Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(tables): infinite scroll with cursor paging and row virtualization; background CSV export and bulk actions past 1,000 rows
aashud253a5c15971
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex a0d3227f33..dce9f6e672 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -3557,3 +3557,12 @@ A ✓ that a script prints after a step that is allowed to fail is not evidence.**Applies to:** `apps/erp/app/routes/api+/v1+/lib/base.server.ts`, `apps/erp/app/routes/api+/mcp+/_index.ts`, every `@mcp`-tagged service taking `db: Kysely<KyselyDatabase>`.+## A constant between `/** @mcp read */` and its function drops the MCP tool++**Context:** Cursor paging (2026-10-13) gave each paged list service an exported `*_DEFAULT_SORTS` constant. The list registry and the loaders read it, so it sits next to the service function.++**Problem:** Twice during that work, the constant went between the doc block and the function. TypeScript attaches a doc comment to the declaration directly under it, so the `@mcp read` tag then belonged to the constant. The generator reads the doc block of exported functions only (`getJsDocs()` in `scripts/lib/service-ast.ts`); it skips a constant that is not a function. The function silently stopped being a tool and left `tool-manifest.digest.json`. Typecheck, tests and the build all passed.++**Rule:** Put a new constant ABOVE the doc block of a service function, never between the block and the function. After you edit a `*.service.ts` file, run `pnpm run generate:mcp`. Then diff the tool names in `tool-manifest.digest.json`. A tool name that disappears is a displaced tag until you prove otherwise.++**Applies to:** `apps/erp/app/modules/*/*.service.ts`, `apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json`.diff --git a/.ai/plans/2026-10-13-infinite-scroll-tables.md b/.ai/plans/2026-10-13-infinite-scroll-tables.mdnew file mode 100644index 0000000000..e2dde3c83e--- /dev/null+++ b/.ai/plans/2026-10-13-infinite-scroll-tables.md@@ -0,0 +1,548 @@+# Infinite scroll for ERP list tables — implementation plan++**Spec / source:** `.ai/specs/2026-10-13-infinite-scroll-tables.md` (read the whole spec, including Autonomous Decisions)+**Research:** `.ai/research/2026-10-13-infinite-scroll-tables.md`+**Branch:** `feat/infinite-scroll` in `/Users/aashu/work/carbon/carbon-feat-infinite-scroll` (work in this checkout; never in `.claude/worktrees`)+**Mode:** autonomous (the user approved the spec and asked for build, test, review and fixes without questions). Record every gap you resolve in the spec's Autonomous Decisions section.++🛑 Never run `git commit`, `git stash`, `git reset` or `git checkout -- <file>`. The user reviews the uncommitted tree. Never rebuild or reset the database.++## Progress++- [x] Task 1: Cursor paging core in `query.ts`+- [x] Task 2: Sort gates+- [x] Task 3: `useInfiniteRows` hook+- [x] Task 4: Desktop Table: virtualization, infinite rows, header count, selection by id+- [x] Task 5: Phone `CompactList`: auto-load and virtualization+- [x] Task 6: Pilot lists: Sales Orders, Parts, Jobs+- [x] Task 7: List registry (server)+- [x] Task 8: "Select all matching" bar and the browser bulk path+- [x] Task 9: CSV export: browser path up to 1,000 rows+- [x] Task 10: Background export job+- [x] Task 11: Background bulk-action job+- [x] Task 12a–12h: Convert the remaining lists, one batch per module+- [x] Task 13: Hand-paged and special lists+- [x] Task 14: Remove the pager code+- [x] Task 15: Docs, rules and lessons+- [x] Task 16: Final verification (browser check blocked: see spec)++## Review fixes++A strict review of the finished tree found 9 blockers. The findings and the fix waves are in `.ai/runs/2026-10-13-infinite-scroll-thermo-review.md`. The spec records each fix as a "Review fix" Autonomous Decision.++- [x] Wave A (table core): `ignoreParams` and `resetKey`, `listError`, the Back store per company, the edits overlay, `useInfiniteScroll`, `useVirtualRows`, `useSelectAllMatching`, `pageUrl`, `idColumn` and `infiniteRows`.+- [x] Wave B (server core and loaders): `loadListPage`, `X_PAGING`, `searchList`, cursor `keys`, offset tokens, no cursor in MCP.+- [x] Wave C (per table and special lists): `mapRows` in place of `onPage`, the planning grids own their rows, the Documents overlay, Sync Activity through `pageUrl`, `SINGLE_LOAD_LIMIT` with `isTruncated`.+- [x] Wave D (jobs and bulk routes): steps of at most 10,000 rows, the Lua lock, per-user export files and their download route, the streamed upload, the 2,000-row limit for Jobs Release and Batches Release, one notification per outcome.+- [ ] Browser check of the Acceptance Criteria after `crbn up` (see the spec, "Verification status").++## Dependencies++- Task 1 → Tasks 3, 6, 7, 12.+- Task 2 is independent.+- Task 3 → Tasks 4, 5.+- Tasks 4, 5 → Task 6.+- Task 6 → Tasks 7, 8, 9, 12.+- Task 7 → Tasks 10, 11.+- Tasks 12a–12h are independent of each other (different modules). Each batch adds its registry entries to its own module file in `apps/erp/app/utils/list-registry/` (Task 7). The files for every batch already exist and `index.server.ts` already merges them, so two batches never edit the same registry file.+- Tasks 12, 13 → Task 14 → Task 15 → Task 16.++## Commands (all confirmed in the repo)++```bash+pnpm --filter erp exec vitest run <path relative to apps/erp> # one test file+pnpm --filter erp test # all ERP unit tests+pnpm exec turbo run typecheck --filter=erp # ERP typecheck (scoped; whole-repo OOMs)+pnpm exec turbo run typecheck --filter=@carbon/jobs # jobs typecheck+pnpm exec biome check --write --no-errors-on-unmatched <paths> # format + lint changed files+pnpm --filter @carbon/checks license-headers # SPDX header on new files+```++The license fixer reads `git ls-files --cached` only (`packages/checks/src/sources/license-files.ts:24`). It does not see a new file until the file is staged. Never stage files for this. Copy the header from an existing AGPL file in the same app (the first 3 lines and one blank line), then confirm it with `inspectLicenseHeader` from `packages/checks/src/license-headers.ts` (result `ok`).++---++## Task 1: Cursor paging core in `query.ts`++**Depends on:** none+**Files:**+- Create: `apps/erp/app/utils/cursor.ts` — encode, decode, keyset filter builder, `toPage`.+- Create: `apps/erp/app/utils/cursor.test.ts`+- Modify: `apps/erp/app/utils/query.ts` — `GenericQueryFilters`, `getGenericQueryFilters`, `setGenericQueryFilters`.+- Modify: `apps/erp/app/utils/pagination.ts` — add `PAGE_SIZE = 100`.+- Copy from (precedent): `packages/ee/src/accounting/core/operations.ts:902-914` (quoted keyset `.or()`), `apps/erp/app/modules/items/items.service.ts:1634-1637` (escaping), `apps/erp/app/utils/query.test.ts` (test setup with the `@carbon/auth` mock and a query stub).++**Steps:**+1. In `pagination.ts`, add `export const PAGE_SIZE = 100;`. Keep the other exports until Task 14.+2. In `cursor.ts`, define:+ ```ts+ export type CursorValue = string | number | boolean | null | string[];+ export type Cursor = { values: CursorValue[]; id: string };+ export function encodeCursor(cursor: Cursor): string; // base64url(JSON)+ export function decodeCursor(token: string | null): Cursor | null; // null on any parse error+ export type KeysetSort = { column: string; ascending: boolean };+ export function buildKeysetFilter(sorts: KeysetSort[], cursor: Cursor, idColumn: string): string;+ export function readSortValue(row: Record<string, unknown>, column: string): CursorValue;+ export function toPage<T extends Record<string, unknown>>(rows: T[], args: { limit: number; sorts: KeysetSort[]; idColumn?: string }): { rows: T[]; nextCursor: string | null };+ ```+3. `buildKeysetFilter` returns the string for `query.or(...)`. Rules:+ - Sorts `s1..sn` plus the tie-breaker `idColumn` ascending. For position k, the branch is `and(s1.eq.v1, …, s(k-1).eq.v(k-1), sk.<op>.vk)`; the last branch compares `idColumn.gt.id`. Join branches with `,`. A branch with one term has no `and(...)`.+ - `<op>` is `gt` for ascending, `lt` for descending.+ - NULL ordering follows Postgres: ascending = NULLS LAST, descending = NULLS FIRST.+ - Ascending, value not null: "after" means `col.gt.v` OR `col.is.null`. Ascending, value null: only rows with `col.is.null` and a later tie-breaker can follow (no `gt` term).+ - Descending, value null: "after" means `col.not.is.null` OR (`col.is.null` and later tie-breaker). Descending, value not null: `col.lt.v`.+ - An equality term for a null value is `col.is.null`.+ - Quote every non-null value: `"` + value with `\` → `\\` and `"` → `\"` + `"`. Booleans and numbers are written as their string form, quoted the same way.+ - An array value becomes a quoted Postgres array literal: `"{\"a\",\"b\"}"` with each element escaped as above.+ - A column `customFields->>abc` is used as written in the filter.+4. `readSortValue(row, column)`: if the column starts with `customFields->>`, read `row.customFields?.[key]` (string or null). Otherwise read `row[column]`. Convert `undefined` to `null`.+5. `toPage`: if `rows.length > limit`, drop the extra row and build `nextCursor` from the last kept row (`values` = each sort column's value, `id` = `String(row[idColumn ?? "id"])`). Otherwise `nextCursor = null`. In development (`process.env.NODE_ENV !== "production"`), throw an `Error` naming the column if a sort column is missing from the row (`!(column in row)` and not a `customFields->>` column).+6. In `query.ts`:+ - `GenericQueryFilters` becomes `{ limit: number; cursor: Cursor | null; sorts?: Sort[]; filters?: Filter[] }`. Remove `offset`.+ - `getGenericQueryFilters(params)` returns `limit: PAGE_SIZE`, `cursor: decodeCursor(params.get("after"))`, and the existing `sorts` / `filters` parsing.+ - `setGenericQueryFilters(query, args, defaultSorts, options?: { idColumn?: string })`:+ 1. Apply filters as today.+ 2. Compute the effective sorts: user sorts when present, else the default sorts. Drop any user sort whose key contains `.` (cross-table sort, Decision 6). Skip default sorts with `foreignTable` for the keyset (they order embedded rows, not the list).+ 3. Apply each `.order(...)` as today. Then add `.order(idColumn, { ascending: true })` unless the last sort is already `idColumn`.+ 4. If `args.cursor` is set, add `query.or(buildKeysetFilter(effectiveSorts, args.cursor, idColumn))`.+ 5. Replace `.range(...)` with `.limit(args.limit + 1)` when `args.limit` is a number.+ - Export a helper `getEffectiveSorts(args, defaultSorts)` that returns the `KeysetSort[]` used in step 2, so loaders can pass the same sorts to `toPage`.+7. Write `cursor.test.ts` with at least these cases: encode/decode round trip; decode of garbage returns `null`; one ascending sort; one descending sort; two sorts; null value ascending and descending; a value with `,`, `(`, `)` and `"`; an array value; a `customFields->>x` sort; `toPage` with `limit + 1` rows and with fewer rows; `toPage` throws for a missing sort column.++**Verify:**+```bash+pnpm --filter erp exec vitest run app/utils/cursor.test.ts+# Expected: all tests pass+pnpm --filter erp exec vitest run app/utils/query.test.ts+# Expected: pass (update the existing tests if they assert offset/range behaviour)+```+Typecheck fails at this point because loaders still read `offset`. That is expected until Task 6 and Task 12.++**Out of scope:** escaping `search` values in services (spec: follow-up).++---++## Task 2: Sort gates++**Depends on:** none+**Files:**+- Modify: `apps/erp/app/components/Table/utils.ts:79-82` — the Sort picker map (`sortKeyToLabel`).+- Modify: `apps/erp/app/components/Table/Table.tsx:1357-1361` — header sort menu gate.+- Modify: `apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx:556,565` — `orderQuantity`, `inventoryQuantity` get `enableSorting: false`.+- Modify: `apps/erp/app/components/Table/utils.test.ts` — add cases.++**Steps:**+1. Write one exported predicate in `utils.ts`: `isServerSortable(column)` returns false when the column has no string `accessorKey`, when the sort key (`meta.sortBy ?? accessorKey`) contains `.`, or when `enableSorting === false`.+2. Use it in `buildColumnMaps` for `sortKeyToLabel` and in the header gate in `Table.tsx`.+3. Add tests: a dotted key and an `enableSorting: false` column are absent from `sortKeyToLabel`.++**Verify:**+```bash+pnpm --filter erp exec vitest run app/components/Table/utils.test.ts+# Expected: pass+```++**Out of scope:** changing views or selects.++---++## Task 3: `useInfiniteRows` hook++**Depends on:** Task 1+**Files:**+- Create: `apps/erp/app/components/Table/useInfiniteRows.ts`+- Create: `apps/erp/app/components/Table/infiniteRowsStore.ts` (module-level back-navigation memory)+- Create: `apps/erp/app/components/Table/infiniteRowsStore.test.ts`+- Copy from (precedent): `apps/erp/app/routes/x+/inventory+/quantities+/$itemId.activity.tsx:230-293` (cursor in refs, one load at a time).++**Steps:**+1. Public type (export it from `components/Table/types.ts`):+ ```ts+ export type InfiniteOptions = {+ dataKey: string; // key of the rows array in the loader data+ nextCursor: string | null; // from the loader+ onPage?: (data: Record<string, unknown>) => void; // per-page extras (Jobs batches)+ };+ ```+2. `useInfiniteRows<T>({ initialRows, infinite, getRowId })` returns `{ rows, hasMore, isLoadingMore, loadError, loadMore, retry, loadAll(limit), totalLoaded, restoredScrollTop, rememberScrollTop }`. The Table calls `rememberScrollTop(scrollTop)` from its scroll listener (spec → Autonomous Decisions).+3. Fetch the next page with `useFetcher()`: `fetcher.load(getPageUrl(useFormAction(), cursor))`. `useFormAction()` is the list route's own URL with the current search (spec → Autonomous Decisions: a drawer's child route and an index route). Track a request id in a ref and accept `fetcher.data` only for the request you started (the router re-loads mounted fetchers on revalidation; ignore those results).+4. One fetch at a time. Stop when `nextCursor` is `null`. On error set `loadError`; `retry()` repeats the last request.+5. Reset rule: when `location.search` changes (ignoring `after`), drop the loaded rows and start from `initialRows`.+6. Revalidation rule (same search, new `initialRows` identity): replace page 1 with `initialRows`. Then re-fetch the other loaded pages in order with fresh cursors, up to 20 pages in total (2,000 rows). Drop rows past 2,000 and take the cursor from row 2,000.+7. Back navigation: `infiniteRowsStore` keeps `{ rows, nextCursor, scrollTop }` per `pathname + search`, max 10 entries, oldest dropped first. Save on unmount and on each page load. On mount, if an entry exists for the same key, start from it and expose `restoredScrollTop` so the Table can scroll the container there after the first render.+8. `loadAll(limit)` loads pages until `nextCursor` is `null` or the loaded row count reaches `limit`. It returns `{ rows, complete }`.+9. Unit-test the store (size cap, key match) and any pure helper you extract (for example the 2,000-row cut).++**Verify:**+```bash+pnpm --filter erp exec vitest run app/components/Table/infiniteRowsStore.test.ts+# Expected: pass+```++**Out of scope:** Table rendering (Task 4).++---++## Task 4: Desktop Table: virtualization, infinite rows, header count, selection by id++**Depends on:** Task 3+**Files:**+- Modify: `apps/erp/app/components/Table/Table.tsx`+- Modify: `apps/erp/app/components/Table/components/Row.tsx`, `components/rowMemo.ts` — accept `rowRef` and `data-index`.+- Modify: `apps/erp/app/components/Table/components/TableHeader.tsx` — remove the condensed Prev/Next (`:402-405`); show the row count.+- Copy from (precedent): `apps/erp/app/components/Grid/Grid.tsx:382-465` (virtualizer, `rangeExtractor`, spacer rows) and `apps/erp/app/components/Grid/components/Row.tsx:23-25,57-58` (`rowRef`, `data-index`).++**Steps:**+1. Add the prop `infinite?: InfiniteOptions` to `TableProps`. When it is set, the table rows come from `useInfiniteRows`; `internalData` syncs from those rows instead of `data`.+2. Default `getRowId` to `(row) => String(row.id)` when rows have an `id` and the caller passed no `getRowId`.+3. Replace `row.index in rowSelection` checks (`Table.tsx:1499-1501`, `:1529-1530`) with `row.getIsSelected()`.+4. Key `expandedRows` by `row.id` instead of `row.index` (`:352-359`, `:1487`, `:1749`).+5. Virtualize the Tbody with `useVirtualizer` on `tableContainerRef`, using one virtual item per data row (its group header row and expanded row render inside the same item, measured with `measureElement`). Keep the Grid pattern: spacer rows above and below, `getItemKey` = `row.id`, `overscan: 10`, a `rangeExtractor` that keeps `selectedCell.row` mounted, and `scrollMargin` = the header height. After a keyboard move in edit mode, call `scrollToIndex(selectedCell.row)`.+6. Prefetch: on the container's `scroll` event (the passive listener at `:1052` exists), call `loadMore()` when `scrollHeight - scrollTop - clientHeight < 600`. Also check once after each page renders (a short list must keep loading until it fills the screen).+7. Below the last row, render one row: a spinner while `isLoadingMore`, or "Couldn't load more rows" with a Retry button when `loadError` is set.+8. Remove the `<Pagination>` render (`:1648`) and the selected-cell reset on page change (`:874-877`, keep the `editMode` reset). Remove `usePagination` from Table.+9. Header count in `TableHeader`: "{count} rows" when `count < 1000`, "about {count} rows" otherwise. Use Lingui `plural` inside a function-declaration hook (see `JobsTable.tsx:157-164` and `.claude/rules/i18n-lingui-system.md` → Plurals).+10. Footer label: when the footer row renders (any column with `meta.renderTotal`), add the text "Total of {n} loaded rows" in the first footer cell that has no total.+11. Restore scroll: if `useInfiniteRows` returns `restoredScrollTop`, set `tableContainerRef.current.scrollTop` after the first render.+12. Tables without `infinite` (the 17 `withPagination={false}` tables and any not yet converted) keep working: they show their `data` rows, virtualized, with no fetching.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp 2>&1 | grep -E "components/Table" | head+# Expected: no errors in components/Table (loader errors from Task 1 are still expected)+```++**Out of scope:** CompactList (Task 5), export (Task 9), select all (Task 8).++**As built:** one virtual item is one `<tbody>` (`measureElement` + `data-index`) that holds the group header row, the data row and the expanded row. So `Row.tsx` and `rowMemo.ts` did not change (spec → Autonomous Decisions).++---++## Task 5: Phone `CompactList`: auto-load and virtualization++**Depends on:** Task 3+**Files:**+- Modify: `apps/erp/app/components/Table/components/Compact/CompactList.tsx`+- Modify: `apps/erp/app/components/Table/Table.tsx` — the phone branch (`:1138-1183`) passes the infinite state instead of `pagination`.+- Copy from (precedent): Task 4 virtualizer code; the scroll element is `<main>` (`apps/erp/app/routes/x+/_layout.tsx:547`), reached with `document.querySelector("main")` as `components/Layout/Mobile/MobileAppBar.tsx:15-17` does.++**Steps:**+1. Remove the `PAGE`, `visible`, `nextLimit`, "Load more" and Previous/Next logic (`:129-165`, `:332-372`).+2. Virtualize the rows with `useVirtualizer({ getScrollElement: () => document.querySelector("main"), scrollMargin: <list top offset>, estimateSize: () => 72, measureElement })`.+3. Prefetch at 600px from the bottom of `<main>` with the same rule as Task 4.+4. Keep the footer text "Showing {n} of {count}" as "{n} of {count} rows" (exact) or "{n} of about {count} rows".+5. Keep selection mode, group headers, totals and expansion as they are.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp 2>&1 | grep -E "Compact" | head+# Expected: no errors in Compact files+```++**Out of scope:** the toolbar sheets.++---++## Task 6: Pilot lists: Sales Orders, Parts, Jobs++**Depends on:** Tasks 1, 4, 5+**Files:**+- Modify: `apps/erp/app/routes/x+/sales+/orders.tsx`, `apps/erp/app/modules/sales/sales.service.ts` (`getSalesOrders`), `apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx`+- Modify: `apps/erp/app/routes/x+/items+/parts.tsx`, `apps/erp/app/modules/items/items.service.ts` (`getParts`), `apps/erp/app/modules/items/ui/Parts/PartsTable.tsx`+- Modify: `apps/erp/app/routes/x+/production+/jobs.tsx`, `apps/erp/app/modules/production/production.service.ts` (`getJobs`), `apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx`++**Steps (the conversion recipe — Task 12 repeats it for every list):**+1. Loader: read `const { limit, cursor, sorts, filters } = getGenericQueryFilters(searchParams)`. Pass `cursor` instead of `offset` to the service.+2. Service: keep its signature (it takes `GenericQueryFilters`). Ask for the count only on the first page: `{ count: args.cursor ? undefined : LIST_COUNT }`.+3. Loader: build the page with `toPage(result.data ?? [], { limit, sorts: getEffectiveSorts({ sorts }, <the service's default sorts>) })`. Export the default sorts from the service as a constant (for example `SALES_ORDERS_DEFAULT_SORTS`) so the loader and service share one value.+4. Loader return: `{ <rowsKey>: page.rows, count: result.count ?? 0, nextCursor: page.nextCursor, ...other keys }`. When `cursor` is set, skip loading the page's reference data that only the first page needs (for example `tags`, `locations`) only if the component tolerates its absence; otherwise keep it.+5. Table component: pass `infinite={{ dataKey: "<rowsKey>", nextCursor }}` to `<Table>`. Read `nextCursor` from `useLoaderData` in the route and pass it down as a prop.+6. Jobs: the loader computes `batchesByJobId` for the page's rows. `JobsTable` keeps a merged map in state and passes `onPage: (d) => merge(d.batchesByJobId)`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp 2>&1 | grep -E "sales\+/orders|items\+/parts|production\+/jobs|SalesOrdersTable|PartsTable|JobsTable|sales.service|items.service|production.service" | head+# Expected: no errors in these files+pnpm --filter erp exec vitest run test/list-select-columns.test.ts+# Expected: pass+```+Then run the app for the pilots (use the project's `run` skill or `pnpm dev`; sign in with the `/auth` skill if needed) and check: scroll Sales Orders to the end, sort by two columns, open an order and press Back, switch to a phone viewport. If the app cannot run, record why in the spec and continue.++**Out of scope:** other lists.++**As built:** the pilots use the Task 7 registry directly. The final recipe for every list is in Task 12.++---++## Task 7: List registry (server)++**Depends on:** Task 6+**Files:**+- Create: `apps/erp/app/utils/list-registry/index.server.ts` — the types, `LIST_REGISTRY` (a merge of the module maps), `getListDefinition`, and `fetchListPage`.+- Create: one file per module, `apps/erp/app/utils/list-registry/{module}.server.ts`. Each exports `{module}Lists: Record<string, ListDefinition>`. The pilots fill `sales.server.ts`, `items.server.ts` and `production.server.ts`. The other module files exist empty, so the Task 12 batches can add entries in parallel without a file conflict.+- Create: `apps/erp/app/utils/list-registry/registry.test.ts` — each list key is used once, and `index.server.ts` merges every module file.+- Modify: the 3 pilot routes — call the shared list query function.++**Steps:**+1. Define:+ ```ts+ export type ListDefinition = {+ key: string; // e.g. "sales-orders"+ permission: Parameters<typeof requirePermissions>[1]; // same object the loader uses, minus bypassRls+ idColumn?: string;+ defaultSorts: { column: string; ascending: boolean }[];+ query: (client: SupabaseClient<Database>, companyId: string, params: URLSearchParams, paging: { limit: number; cursor: Cursor | null }) => PostgrestBuilder; // returns the same query the loader runs+ };+ export const LIST_REGISTRY: Record<string, ListDefinition>;+ export function getListDefinition(key: string): ListDefinition | undefined;+ // Runs `query` for one page and cuts it with `toPage`. Default paging: 100 rows after `?after=`.+ export function fetchListPage<TRow>(definition: ListDefinition<TRow>, client, companyId, params: URLSearchParams, paging?: ListPaging): Promise<{ rows: TRow[]; count: number; nextCursor: string | null; error: unknown }>;+ ```+2. Move each pilot loader's service call (reading `search`, `status`, `customerId`, `supplierId` from `params`) into its `query` function, and make the loader call `fetchListPage(<definition>, …)`. The loader and the jobs then share one query. The loader imports the definition from its module file (for example `salesOrdersList` from `list-registry/sales.server.ts`), so the row type stays exact.+3. Pass `infinite={{ dataKey, nextCursor, listKey: "<key>" }}` from the table (add `listKey?: string` to `InfiniteOptions`). A table without `listKey` gets no background export or background bulk path (it falls back to the 1,000-row browser path with the "filter to under 1,000" message).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp 2>&1 | grep -E "list-registry|sales\+/orders|items\+/parts|production\+/jobs" | head+# Expected: no errors+pnpm --filter erp exec vitest run app/utils/list-registry/registry.test.ts+# Expected: pass+```++**Out of scope:** registering other lists (Task 12 does it per module).++---++## Task 8: "Select all matching" bar and the browser bulk path++**Depends on:** Task 6+**Files:**+- Modify: `apps/erp/app/components/Table/Table.tsx`, `components/TableHeader.tsx`, `components/Compact/CompactList.tsx`++**Steps:**+1. When every loaded row is selected and `hasMore` is true, show a bar above the rows: "{n} selected · Select all {count} matching" (use "about" above 1,000).+2. Click: if `count <= 1000`, call `loadAll(1000)`, then select every loaded row. The existing `renderActions(selectedRows)` runs unchanged.+3. If `count > 1000`: set a table state `selectAllMatching = { listKey, search: location.search, count }` and show "All {count} matching selected". Pass it to `renderActions` as a second argument: `renderActions(selectedRows, { allMatching })`. Tables whose actions support the background path (Task 11) handle it; others show the action disabled with the tooltip "Filter the list to 1,000 rows or fewer".+4. Clear `selectAllMatching` when the search changes or the user clears the selection.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp 2>&1 | grep -E "components/Table" | head+# Expected: no errors+```++**Out of scope:** the server side (Task 11).++---++## Task 9: CSV export: browser path up to 1,000 rows++**Depends on:** Task 6+**Files:**+- Modify: `apps/erp/app/components/Table/components/Download.tsx`, `Table.tsx` (`csvExport` uses the loaded rows), `components/Compact/CompactToolbar.tsx`++**Steps:**+1. `csvExport.data` reads the table's current rows (`internalData`), not the `data` prop (`Table.tsx:1129`, `:1236`).+2. On click: if `count <= 1000` (or the list has no `listKey`), call `loadAll(1000)`, then build the CSV exactly as today (`meta.exportValue`, `idNameMaps`, `selectExportColumns`).+3. If `count > 1000` and the list has a `listKey`, post to the export route (Task 10) with `listKey`, `search`, and the visible columns as `[{ key, label }]` in display order. Show the toast "Your export is being prepared. We'll notify you when it's ready." or the route's "already running" error.+4. A list without `listKey` and more than 1,000 rows exports the first 1,000 rows and shows "Exported the first 1,000 rows."++**Verify:**+```bash+pnpm --filter erp exec vitest run app/components/Table/utils.test.ts+# Expected: pass+```++**Out of scope:** the job (Task 10).++---++## Task 10: Background export job++**Depends on:** Task 7+**Files:**+- Create: `packages/jobs/src/inngest/functions/tasks/table-export.ts`+- Modify: `packages/lib/src/events.ts` (add `"carbon/table-export"` to `Events`), `packages/lib/src/trigger.ts` (`"table-export": "carbon/table-export"`), `packages/jobs/src/inngest/functions/tasks/index.ts`, `packages/jobs/src/inngest/index.ts` (import + `functions` array + export `setTableJobHandlers`)+- Create: `packages/jobs/src/table-jobs/handlers.ts` — `setTableJobHandlers` / `getTableJobHandlers`, same shape as `packages/jobs/src/workflows/actions/dispatcher.ts`.+- Create: `apps/erp/app/routes/api+/table.export.ts` — the route action that starts the job.+- Create: `apps/erp/app/utils/table-jobs.server.ts` — the ERP handlers (page through a list with the registry) and the Redis lock helper.+- Modify: `apps/erp/app/routes/api+/inngest.ts` — wire `setTableJobHandlers` lazily next to `wireWorkflowDispatch` (`:35-48`).+- Modify: `packages/notifications/src/index.ts` (new `NotificationEvent.TableExport`, topic mapping), `packages/jobs/src/inngest/functions/notifications/content.ts` (content case), `packages/jobs/src/inngest/functions/notifications/notify.ts` (default destinations), `apps/erp/app/routes/api+/link.ts` (resolve case), `apps/erp/app/components/Layout/Topbar/Notifications.tsx` (topbar case).+- Copy from (precedent): `packages/jobs/src/inngest/functions/tasks/company-export.ts:363-370` (function header), `packages/jobs/src/inngest/functions/integrations/mount-publish.ts:179-186` (notify), `packages/jobs/src/inngest/functions/integrations/accounting-auth-failure.ts:103-110` (Redis `SET NX`), `apps/erp/app/routes/api+/integrations.journal-backfill.ts:34-75` (route that triggers a job), `packages/files/src/csv/csv.ts:39-77` (`encodeCsv` with `header: false` for later chunks).++**Steps:**+1. Route `api+/table.export.ts` (POST, JSON `{ listKey, search, columns: {key,label}[] }`):+ 1. Look up the list definition. Unknown key → 400.+ 2. `requirePermissions(request, { ...definition.permission, role: "employee" })`.+ 3. Take the lock: `redis.set("table-job:export:" + companyId, userId, "EX", 3600, "NX")`. If the result is not `"OK"` and `redis.get(key)` returns a value → return 409 with "An export is already running for your company". If both return `null` → continue (Redis down, fail-open; Inngest still serializes).+ 4. `trigger("table-export", { companyId, userId, listKey, search, columns, exportId: nanoid() })`. Return `{ success: true }`.+2. Job `table-export.ts`:+ ```ts+ // TODO(scale): this job runs inside the ERP containers (api+/inngest.ts) and shares+ // CPU with web requests. Move table export/bulk jobs to a dedicated worker service+ // before large tenants run many 100k-row exports at the same time.+ export const tableExportFunction = inngest.createFunction(+ { id: "table-export", retries: 1, concurrency: { key: "event.data.companyId", limit: 1 } },+ { event: "carbon/table-export" }, async ({ event, step }) => { … });+ ```+ 1. Check the user still has the list's view permission (use the ERP handler; the precedent for the permission read is `packages/jobs/src/workflows/engine/owner.ts:58-87`).+ 2. Page through the list with the ERP handler `fetchPage(listKey, companyId, search, cursor, limit = 1000)`. Write the header row once (translated labels), then each page with `encodeCsv(rows, { fields, header: false })`. Write the chunks to a temp file (`os.tmpdir()`) so memory stays at one page.+ 3. Stop at 100,000 rows.+ 4. Upload the file to bucket `temp-staging` at `{companyId}/exports/{exportId}.csv` with the service-role client. Prefer a stream upload; if `storage-js` does not accept a Node stream, read the file into a Buffer (the 100,000-row ceiling bounds it) and record that in the spec.+ 5. Notify the user: `trigger("notify", { event: NotificationEvent.TableExport, companyId, documentId: exportId, title, body, recipient: { type: "user", userId } })`. Never set `from` to the requesting user (`notify.ts:326-327` drops it).+ 6. Delete the temp file and the Redis lock in a `finally`.+3. Plain values: `row[key]`; `customFields->>id` reads `row.customFields[id]`; arrays join with `; `; objects become JSON.+4. Notification link: the topbar case and `/api/link` resolve to `path.to.file.preview("temp-staging", "{companyId}/exports/{exportId}.csv")` (`apps/erp/app/utils/path.ts:1175-1176`).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/jobs+# Expected: no errors+pnpm exec turbo run typecheck --filter=erp 2>&1 | grep -E "table\.export|table-jobs|inngest|link\.ts|Notifications" | head+# Expected: no errors+```++**Out of scope:** a separate worker service (the `TODO(scale)` comment covers it).++---++## Task 11: Background bulk-action job++**Depends on:** Tasks 7, 8, 10+**Files:**+- Create: `packages/jobs/src/inngest/functions/tasks/table-bulk-action.ts`, events + trigger entries (`"carbon/table-bulk-action"`), registration as in Task 10.+- Modify: the action routes listed below — move each action's logic into a server function in its module's `{module}.server.ts` (create it if missing), called by the route and by the job handler.+- Modify: `apps/erp/app/utils/table-jobs.server.ts` — `runBulkAction(actionKey, ids, context)` handler.+- New notification event `NotificationEvent.TableBulkAction` (same 6 edits as Task 10).++**Supported actions (spec → Autonomous Decisions):**++| Action key | Route (`apps/erp/app/routes/`) | Server checks to keep or add |+|---|---|---|+| `items.update` | `x+/items+/update.tsx` | `update: "parts"` (or the item type's permission); chunk `.in()` by 100 |+| `jobs.release` | `x+/job+/release.tsx` | already server-side (Draft/Planned, readiness) |+| `jobs.delete` | `x+/job+/update.tsx` | ADD: `delete: "production"`; status in Draft/Planned/Due Today/Overdue; `.eq("companyId")` on the status read; chunk by 100 |+| `purchase-orders.delete` | `x+/purchase-order+/update.tsx` | ADD: `.eq("companyId")`; status Draft/Planned; chunk by 100 |+| `batches.release` / `batches.dissolve` | `x+/production+/batches.release.tsx`, `batches.dissolve.tsx` | release: Planned only (exists); dissolve ADD: Planned/Active only; chunk by 100 |+| `users.deactivate` / `users.invite` / `users.permissions` | `x+/users+/deactivate.tsx`, `resend-invite.tsx`, `bulk-edit-permissions.tsx` | keep existing checks (caller not in list, employee of company) |++**Steps:**+1. Each route accepts either `ids` (today) or `{ allMatching: { listKey, search } }`. With `allMatching`, it takes the Redis lock `table-job:bulk:{companyId}` (same fail-open rule as Task 10), triggers `table-bulk-action`, and returns `{ success: true, background: true }`.+2. The job pages through the list's ids (`fetchPage` with `limit = 1000`), calls `runBulkAction(actionKey, idsChunk, ctx)` per chunk of 100, sums `{ done, skipped, failed }`, and notifies the user with the counts. Add the same `TODO(scale)` comment as Task 10.+3. The browser checks in the table components stay (they filter the selection for the small path). The server checks in the table above are the source of truth.+4. In each supporting table component, `renderActions(selectedRows, { allMatching })` posts `allMatching` instead of ids when it is set, and shows the toast "Running in the background. We'll notify you when it's done."+5. Planning tables and Kanban labels: keep the action disabled when `allMatching` is set (Task 8 tooltip).++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/jobs+pnpm exec turbo run typecheck --filter=erp 2>&1 | grep -E "items\+/update|job\+/(update|release)|purchase-order\+/update|batches\.|users\+/|table-jobs" | head+# Expected: no errors+```++**Out of scope:** planning "Order Parts" / "Create Jobs" / "Apply Suggested Changes" background paths.++---++## Task 12a–12h: Convert the remaining lists, one batch per module++**Depends on:** Tasks 1, 6, 7+**Recipe:** do these steps for every route in the batch. The pilots are the reference: `routes/x+/sales+/orders.tsx`, `list-registry/sales.server.ts`, `getSalesOrders` and `SalesOrdersTable.tsx`.++1. Service: export the default sorts as a constant (`SALES_ORDERS_DEFAULT_SORTS: DefaultSort[]`) and pass it to `setGenericQueryFilters`.+2. Service: ask for the count on the first page only: `{ count: args.cursor ? undefined : LIST_COUNT }`.+3. Registry: add an entry to the batch's module file in `apps/erp/app/utils/list-registry/` (12a `sales.server.ts`, 12b `purchasing.server.ts`, 12c `production.server.ts`, 12d `items.server.ts`, 12e `inventory.server.ts`, 12f `invoicing.server.ts` and `accounting.server.ts`, 12g `quality.server.ts`, 12h `people`, `users`, `resources`, `settings`, `documents` and `workflows.server.ts`). Copy `salesOrdersList`: `key`, `permission` (the loader's object without `bypassRls`), `defaultSorts`, `idColumn` when the source has no `id`, and `query`, which reads the URL params and calls the service with `limit` and `cursor`. End it with `satisfies ListDefinition` and add it to the file's `{module}Lists` map. Never edit `index.server.ts`.+4. Loader: call `requirePermissions(request, { ...xList.permission, bypassRls: true })`, then `fetchListPage(xList, client, companyId, searchParams)`.+5. Loader: return `{ <rowsKey>: page.rows, count: page.count, nextCursor: page.nextCursor, …other keys }`.+6. Loader: if `searchParams.get("after")` is set, skip reference data that only the first page uses (tags, locations). A later page is read for its rows only.+7. Route component: read `nextCursor` from `useLoaderData` and pass it to the table component.+8. Table component: pass `infinite={{ dataKey: "<rowsKey>", nextCursor, listKey: "<key>" }}` to `<Table>`. If the loader computes extras per page, merge them with `onPage` (see `JobsTable.tsx`).++Use the route table in `.ai/research/2026-10-13-infinite-scroll-tables.md` and the per-module lists below. For each list: check that every sortable column of its table is in the select (the `toPage` dev check catches misses). When the source has a default sort on a foreign table, follow the spec's Autonomous Decisions ("single load" lists).++| Batch | Routes |+|---|---|+| 12a Sales | `x+/sales+/` quotes, rfqs, rmas, customers, contracts, rental-agreements, price-list, pricing-rules, customer-portals, customer-statuses, customer-types, no-quote-reasons, return-reasons |+| 12b Purchasing | `x+/purchasing+/` orders (rows key is spelled `purchasOrders` in the code; keep it), planning, quotes, rfqs, supplier-returns, supplier-types, suppliers, leases |+| 12c Production | `x+/production+/` planning, assemblies, batches, demand-forecasts, procedures, scrap-reasons; `x+/job+/` $jobId.events, $jobId.operations, $jobId.quantities, $jobId.steps |+| 12d Items | `x+/items+/` materials, tools, consumables, services, change-notices/_index, change-notice-actions, change-notice-types, dimensions, finishes, forms, grades, groups, substances, types, uom, methods+/materials, methods+/operations |+| 12e Inventory | `x+/inventory+/` quantities, inventory-count, kanbans, picking-lists, receipts, shipments, shipping-methods, stock-movements, stock-transfers, storage-types, storage-units, tracked-entities, warehouse-transfers; `x+/inventory-count+/$id` |+| 12f Invoicing + Accounting | `x+/invoicing+/` sales, purchasing, payments, credit-memos, supplier-credits, charges, reimbursements; `x+/accounting+/` journals, fixed-assets, asset-classes, depreciation-runs, fleet, dimensions, intercompany, payment-terms, projects, lease-runs, revenue-recognition-runs (via `period-runs.server.ts`) |+| 12g Quality | `x+/quality+/` issues, actions, calibrations, documents, gauges, gauge-types, inspection-plans, inspections, issue-types, issue-workflows, required-actions, risks |+| 12h People, Users, Resources, Settings, Documents, Workflows | `x+/people+/` employee, attributes, holidays, shifts, timecard; `x+/users+/` employees, customers, suppliers, employee-types, groups, operators; `x+/resources+/` all 11; `x+/settings+/` api-keys, custom-fields, sequences, serial-numbers, webhooks; `x+/documents+/search`; `x+/workflows+/` _index, runs |++**Verify (per batch):**+```bash+pnpm exec turbo run typecheck --filter=erp 2>&1 | grep -E "<batch route or module path>" | head+# Expected: no errors in the batch's files+pnpm --filter erp exec vitest run app/utils/list-registry/registry.test.ts test/list-select-columns.test.ts+# Expected: pass+```++**Out of scope:** the special lists in Task 13.++---++## Task 13: Hand-paged and special lists++**Depends on:** Tasks 3, 4+**Files:**+- `apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx` (page state + `useFetcher`, `:351-353`, `:640-653`)+- `apps/erp/app/modules/accounting/ui/Reports/AccountLedgerDrawer.tsx` (`?offset=` / `?limit=`, `:73-99`, `:226-230`)+- `x+/settings+/printing.jobs.tsx` (`getPrintJobs`, own `.range`), `x+/settings+/audit-logs.details.tsx` (`getGlobalAuditLog`, RPC `p_offset`)+- `share+/customer.$id.tsx`, `x+/users+/customers.tsx`, `x+/users+/suppliers.tsx`, `x+/resources+/contractors.tsx`, `x+/settings+/custom-fields.tsx`++**Steps:**+1. SyncActivity and AccountLedgerDrawer: switch their sources to cursor paging (`setGenericQueryFilters` + `toPage`, or a hand-written keyset on their own order) and load more on scroll inside their existing scroll element.+2. Printing jobs and audit log: keep their offset sources; feed them through `useInfiniteRows` with an `after` token that holds the next offset (encode `{ values: [], id: String(offset) }`). Record this in the spec.+3. The "single load" lists: load up to 1,000 rows, `nextCursor: null`.+4. `contractors` uses `idColumn: "supplierContactId"`; `custom-fields` uses `idColumn: "table"`.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=erp 2>&1 | grep -E "SyncActivity|AccountLedgerDrawer|printing|audit-logs|customer\.\$id|users\+/|contractors|custom-fields" | head+# Expected: no errors+```++---++## Task 14: Remove the pager code++**Depends on:** Tasks 12, 13+**Steps:**+1. Confirm with grep that nothing imports them, then delete: `components/Table/components/Pagination/` (and its re-exports in `components/Table/components/index.ts`), `getPageSize`, `getPageOffset`, `pageBounds`, `PAGE_SIZES`, `DEFAULT_PAGE_SIZE`, `MAX_PAGE_SIZE` from `utils/pagination.ts`, and `utils/pagination.test.ts` cases for them.+2. Delete `PAGINATION_SHORTCUTS` (`apps/erp/app/shortcuts.ts:61-65`) and its entries in `components/ShortcutHelp.tsx:16`, `:80-89`.+3. Remove `?limit=` / `?offset=` writes left anywhere (`SearchFilter.tsx:30` resets them; change it to reset `after` only if it still matters, else drop it).++**Verify:**+```bash+grep -rn "usePagination\|PAGINATION_SHORTCUTS\|getPageOffset\|pageBounds\|PAGE_SIZES" apps/erp/app | head+# Expected: no output+pnpm exec turbo run typecheck --filter=erp+# Expected: no errors+```++---++## Task 15: Docs, rules and lessons++**Depends on:** Task 14+**Steps:**+1. Update `.claude/rules/table-csv-export.md` for the two export paths.+2. Update `.claude/rules/realtime-system.md` if the list refresh rule changed what it says about list loaders.+3. Add a short section on cursor paging (loader recipe, `toPage`, registry) to `apps/erp/app/components/Table/` docs or the closest AGENTS.md (`packages/react/AGENTS.md` is for the package; use `apps/erp/AGENTS.md` if it exists, else `.claude/rules/conventions-ui.md`).+4. Add a lesson to `.ai/lessons.md` in the `Context → Problem → Rule → Applies to` format for one real pitfall hit during the work.+5. Write all prose in STE-80 (`.claude/rules/writing-ste.md`).++---++## Task 16: Final verification++**Depends on:** all+**Steps:**+1. `pnpm exec turbo run typecheck --filter=erp` and `--filter=@carbon/jobs` — no errors.+2. `pnpm --filter erp test` — all pass.+3. `pnpm exec biome check --write --no-errors-on-unmatched <every changed path>` — clean.+4. `pnpm --filter @carbon/checks license-headers` — new files have SPDX headers.+5. Run the app and walk the spec's Acceptance Criteria that need a browser (pilots, a phone viewport, export of a small list). Record results and anything not verifiable in the spec.+6. Check every Progress box in this file.diff --git a/.ai/specs/2026-07-02-account-ledger-drilldown.md b/.ai/specs/2026-07-02-account-ledger-drilldown.mdindex 3569feecbf..3ea7cf789d 100644--- a/.ai/specs/2026-07-02-account-ledger-drilldown.md+++ b/.ai/specs/2026-07-02-account-ledger-drilldown.md@@ -91,7 +91,7 @@ row type (`AccountLedgerLine` in `types.ts`) — remove both once types regenerathe existing `charts.$accountId` edit route). The three report parents gained `<Outlet />`.- Path helpers: `trialBalanceLedger`, `balanceSheetLedger`, `incomeStatementLedger`,`chartOfAccountsLedger`.-- All four parents export `shouldRevalidate = revalidateIgnoringOffset`+- All four parents export `shouldRevalidate = revalidateOnSearchChange`(`~/utils/revalidate.ts`): opening/closing the drawer and paging skip the expensive balanceRPCs; period/company changes and mutations revalidate normally.diff --git a/.ai/specs/2026-10-13-infinite-scroll-tables.md b/.ai/specs/2026-10-13-infinite-scroll-tables.mdnew file mode 100644index 0000000000..fc16ff6e09--- /dev/null+++ b/.ai/specs/2026-10-13-infinite-scroll-tables.md@@ -0,0 +1,498 @@+# Infinite scroll for ERP list tables++> Status: in-progress+> Author: Aashu+> Date: 2026-10-13+> Research: `.ai/research/2026-10-13-infinite-scroll-tables.md`++## TL;DR++- Every paginated ERP list loads more rows as you scroll, on desktop and on phones. The pager goes away.+- Loaders change from offset paging (`?offset=`) to cursor paging (`?after=`, meaning "the rows after this one").+- The shared `<Table>` virtualizes its rows with `@tanstack/react-virtual`, so thousands of loaded rows still scroll smoothly.+- The next 100 rows start to load when the user is 600px from the bottom, so the user does not see a wait.+- "Select all matching" and CSV export work on every matching row. Up to 1,000 rows they run in the browser; above that, an Inngest job (one per company at a time) does the work.+- Footer totals stay as today (the rows on screen), with a label that says so.+- Filters, sorts, search, saved views, inline editing and the phone list keep working as today.++## Overview diagram++```mermaid+sequenceDiagram+ participant U as User+ participant T as Table (useInfiniteRows)+ participant L as Route loader+ participant DB as PostgREST+ U->>L: open /x/sales/orders?sort=…&filter=…+ L->>DB: first 100 rows + estimated count+ L-->>T: rows, count, nextCursor+ U->>T: scrolls to 600px from the bottom+ T->>L: fetcher.load(same URL + &after=nextCursor)+ L->>DB: keyset query: rows after the cursor, 100 rows+ L-->>T: rows, nextCursor+ T->>T: append rows, virtualizer renders only visible rows+```++## Problem Statement++1. Desktop lists show one page at a time (`PAGE_SIZES = [20, 100, 500, 1000]`). Each Prev/Next click is a GET navigation that re-runs every matched loader.+2. Offset paging gets slower on deep pages. The database reads and discards every row before the offset.+3. Offset paging shifts rows when a record is added or deleted between two requests. The user then sees a row twice or misses one.+4. The phone list has a stopgap "Load more" button (`CompactList.tsx:129-165`). It raises `?limit` up to 1000 and then falls back to Prev/Next.+5. The shared `<Table>` renders every row as a real `<Tr>` (`Table.tsx:1482-1590`). A page of 1000 rows is slow to render.++## Goals++- Infinite scroll on all ~130 paginated list pages that use the shared `<Table>`, on desktop and on phones.+- Infinite scroll on the 2 hand-paged tables: `SyncActivity.tsx` and `AccountLedgerDrawer.tsx`.+- Stable, fast paging at any depth (cursor paging).+- Smooth scrolling with thousands of loaded rows (row virtualization).+- No visible wait at the bottom of the list (prefetch at 600px).++## Non-goals++- MES. It has no paginated tables (`apps/mes/app/routes/x+/jobs.tsx` loads all open jobs).+- The 17 tables with `withPagination={false}` (wizards, grids, reports). They stay as they are.+- Small tables inside detail pages that use the plain `@carbon/react` `Table`.+- Server-side totals for footer rows.+- Sorting by a column of another table (see Decision 6).++## Proposed Solution++### 1. Cursor paging in the loaders++`getGenericQueryFilters` (`apps/erp/app/utils/query.ts:57-93`) reads a new `?after=` param. It stops reading `?offset=`. The param holds an opaque token: base64url JSON of the last row's sort values plus its `id`.++`setGenericQueryFilters` (`query.ts:157-203`) changes in 4 ways:++1. It adds `id` as the last sort key, so the order is always total. A list whose rows have no unique `id` passes its own key column.+2. If a cursor is present, it adds a keyset filter with `.or(…)`. For one sort column `c` (ascending) the filter is `c > v OR (c = v AND id > lastId)`. For more sort columns, the filter expands the same way.+3. It handles NULLs the way Postgres orders them: ascending puts NULLs last, descending puts NULLs first. A NULL cursor value uses `c IS NULL AND id > lastId`.+4. It replaces `.range(offset, …)` with `.limit(limit + 1)`. The extra row tells the loader that more rows exist.++A new helper `toPage(rows, args)` returns `{ rows, nextCursor }`. It drops the extra row and builds `nextCursor` from the last kept row, or returns `null` at the end.++The cursor reads the sort values from the returned row. So every sortable column must be in the list's select. In development, `toPage` throws if a sort column is missing from the row.++Values in the `.or()` string are quoted and escaped. Commas, parentheses and quotes in a value must not break the filter.++Counts: only the first request (no `?after=`) asks for `count: LIST_COUNT`. Later requests ask for no count.++### 2. Loader contract++Each list loader returns its rows, `count` (first page only), and `nextCursor`. The rows keep their current key (for example `salesOrders`). Example for `sales+/orders.tsx`:++```ts+// salesOrdersList (utils/list-registry/sales.server.ts) wraps getSalesOrders.+const page = await fetchListPage(salesOrdersList, client, companyId, searchParams);+return { salesOrders: page.rows, count: page.count, nextCursor: page.nextCursor };+```++The page size is fixed at 100. `?limit=` and `?offset=` are removed. Old bookmarks with `?offset=` or `?limit=` are ignored.++### 3. Shared Table: `useInfiniteRows`++The table component passes a new prop `infinite={{ dataKey: "salesOrders", nextCursor }}` to `<Table>`. A new hook `useInfiniteRows` inside the Table does this:++1. It starts with the loader's rows and `nextCursor`.+2. It calls `fetcher.load(pathname + search + "&after=" + cursor)` when the user is 600px from the bottom. It reads `fetcher.data[dataKey]` and appends the rows.+3. It runs one fetch at a time. It stops when `nextCursor` is `null`.+4. If a fetch fails, the list shows "Couldn't load more rows" with a Retry button.+5. If the reset key changes, it drops the loaded rows and starts again from the loader's first page. The reset key is the URL search without `after` and without the list's `ignoreParams` (Review fix A). So a filter, sort, search or saved view resets the list, and a drawer param does not.++The fetcher re-uses the route's own loader (Decision 3). No new API routes.++### 4. Row virtualization++The Table uses `useVirtualizer` on its existing scroll element `#table-container` (`Table.tsx:1264-1276`). It copies the `Grid.tsx` pattern:++- Spacer `<tr>` rows above and below the visible rows (`Grid.tsx:442-465`).+- `measureElement` for rows of different height (expanded rows, group headers).+- A `rangeExtractor` that keeps the selected cell's row mounted during inline editing (`Grid.tsx:390-403`).+- `overscan: 10`.++The sticky header, pinned columns and edge shadows stay as they are. The prefetch check uses the scroll element: `scrollHeight - scrollTop - clientHeight < 600`.++### 5. Phones++- `CompactList` drops its "Load more" button and its Prev/Next fallback. It uses the same `useInfiniteRows` hook and a virtualizer on the phone list's scroll element.+- The 9 tables with `mobileLayout="table"` behave like desktop.+- The phone keeps one scroll surface, the existing one (`.ai/lessons.md:1326-1336`).++### 6. Header row count++The `<Pagination>` bar, page-size dropdown and Prev/Next buttons go away. The ArrowLeft / ArrowRight pagination shortcuts go away. The table header shows the total:++- An exact number below 1,000 rows: "245 rows".+- "about 2,300 rows" at 1,000 rows or more, because `LIST_COUNT` is an estimate there.++### 7. Selection and "Select all matching"++- The Table sets `getRowId` to the row's `id`. Appending rows then never clears the selection (today it clears when `data.length` changes, `Table.tsx:383-387`).+- The header checkbox selects the loaded rows.+- If more rows exist, a bar shows "100 selected · Select all 2,345 matching". The selection then becomes "all rows that match the current URL filters", not a list of rows.+- Every bulk-action route that receives ids splits them into chunks of 100 for `.in()` (`.ai/lessons.md:2946-2958`).++The bulk action runs in one of 2 ways:++| Matching rows | How the action runs |+|---|---|+| 1,000 or fewer | The browser loads the remaining rows with the cursor loop (at most 10 requests of 100). Then it calls the action with full rows, as today (`renderActions(selectedRows)`). |+| More than 1,000 | The browser posts the action name, its value and the list's URL search to the action route. The route starts an Inngest job. Collect steps read the matching ids, at most 10,000 rows per step, and store each step's ids as one file in `temp-staging`. Apply steps then run the action on one slice of ids each, 100 ids per call. |++Rules for the background bulk action:++1. The job applies the same per-row checks as the browser does today. Example: Jobs Release acts only on Draft and Planned jobs (`JobsTable.tsx:757`). These checks move into the server code of each of the 15 bulk actions.+2. One background job runs per company at a time (Inngest concurrency key `companyId`, limit 1, and a Redis lock). A second request from the same company gets "A bulk action is already running for your company", with the latest time it ends.+3. The job runs with the requesting user's permissions and `companyId`. It never reads another company's rows.+4. When the job ends, the user gets a notification with the counts: done, skipped, failed.+5. Jobs Release and Batches Release run on at most 2,000 matching rows in the background. Each released job runs MRP. Past 2,000 rows the route refuses: "Filter the list to 2,000 rows or fewer" (Review fix D).++### 8. CSV export++Columns stay WYSIWYG: the visible columns in display order (`selectExportColumns`), with the translated headers.++| Matching rows | How the export runs |+|---|---|+| 1,000 or fewer | In the browser, as today. The browser loads the remaining rows with the cursor loop (at most 10 requests of 100). Each cell uses the on-screen format (`meta.exportValue`). |+| More than 1,000 | An Inngest job. The browser sends the list key, the URL search, the visible columns and their translated headers. Each job step reads at most 10,000 rows and writes them as one part file. A last step streams the parts into one CSV file in storage. Then the job sends the user a notification with a download link. |++Rules for the background export:++1. Cells hold the plain database values (for example `2026-10-13`, `1250.5`, the stored status). The on-screen format code runs in the browser, so the job cannot use it. One generic exporter serves every table.+2. The job never holds the whole file in memory. It reads 500 rows per query, and one part (at most 10,000 rows) is in memory at a time. The export stops at 100,000 rows or after the page that passes 200 MB.+3. One export job runs per company at a time (Inngest concurrency key `companyId`, limit 1, and a Redis lock). A second request from the same company gets "An export is already running for your company", with the latest time it ends.+4. The job runs as the requesting user, scoped to their `companyId`.+5. The decision between the 2 ways uses the header count. If the browser loop reaches 1,000 rows and more rows remain, it hands the export to the job.+6. The file belongs to the user who asked for it: `{companyId}/exports/{userId}/{exportId}.csv`. The download route `api+/table.export.$exportId` builds that key from the session and checks the list's permission again (Review fix D).++Accepted risk: background jobs run in the ERP containers (`apps/erp/app/routes/api+/inngest.ts`). Many companies can each run 1 big export at the same time, and those jobs share CPU with web requests. A separate worker container removes that risk; it is out of scope for now. The code puts a `// TODO(scale):` comment on the export and bulk-action Inngest functions that says this.++### 9. Footer totals++The 11 tables with `meta.renderTotal` keep their footer row, and it works as today: it totals the rows on screen, which are now the loaded rows (`aggregateForCol`, `Table.tsx:204-215`). The footer adds a label so the user knows the scope: "Total of 300 loaded rows". There is no "Total all" link.++### 10. Live updates (realtime)++`RouteRealtime` revalidates the loader, which returns only the first page. `useInfiniteRows` then re-fetches the remaining loaded pages in order with fresh cursors, and replaces them. The scroll position stays. Changed rows update in place, new rows appear, and deleted rows leave.++### 11. Back navigation++`useInfiniteRows` keeps the loaded rows, `nextCursor` and the scroll offset in memory, keyed by the company id, `dataKey` and the page URL key (Review fix A). On Back to the same URL, it restores them and scrolls to the same row. A page reload clears the memory. A realtime revalidation on return refreshes the restored rows (section 10).++### 12. The 2 hand-paged tables++- `SyncActivity.tsx` (page state plus `useFetcher`) switches to cursor paging and infinite scroll.+- `AccountLedgerDrawer.tsx` (`?offset=`/`?limit=` URL params) switches to cursor paging and infinite scroll inside the drawer.++### 13. Removal++After every list is converted, delete `usePagination`, `<Pagination>`, `PAGE_SIZES`, `getPageOffset`, `pageBounds` and the pagination shortcuts. Before deleting each one, confirm with a grep that it has no callers.++### Design Decisions++| # | Decision | Choice | Rationale |+|---|----------|--------|-----------|+| 1 | Virtualization library | `@tanstack/react-virtual` 3.13.23 | Already a dependency, used in 7 places, headless, ~5 kB. User decision. |+| 2 | Paging method | Cursor (keyset) paging | Stable under inserts and deletes, fast at any depth. User decision. |+| 3 | How the browser fetches the next page | `useFetcher` on the route's own loader with `?after=` | One place returns each list's rows; no 130 duplicate API routes. User decision. |+| 4 | When to prefetch | 600px from the bottom | The user does not feel a wait. User decision. |+| 5 | Page size | 100 rows, fixed | Matches `DEFAULT_PAGE_SIZE`. Below PostgREST `max_rows = 1000`. |+| 6 | Sort by another table's column (7 tables) | Turn off those sorts | No database change. User decision. |+| 7 | Row count in the header | Exact below 1,000, "about N" above | `LIST_COUNT` is an estimate past 1,000. User decision. |+| 8 | Select all | Gmail-style "Select all N matching" bar, no cap. Exception: Jobs Release and Batches Release act on at most 2,000 rows in the background | User decision. The 2,000 cap: Review fix D, because each released job runs MRP. |+| 9 | Browser or server for "all matching" work | Browser up to 1,000 rows; Inngest job above 1,000 | Small lists stay instant. Journals and ledgers pass 10,000 rows (research file). User decision. |+| 10 | CSV export | All matching rows, visible columns only. Big exports hold plain DB values | The on-screen format code runs only in the browser. User decision. |+| 11 | Footer totals | As today: the rows on screen, with a "loaded rows" label | User decision. |+| 11a | Load on the database and servers | 1 background job per company at a time; accept the risk that many companies run jobs at once | A separate worker container fixes it later; marked with `TODO(scale)`. User decision. |+| 12 | Live updates | Refresh the loaded rows in place | User decision. |+| 13 | Back navigation | Restore rows and scroll position | User decision. |+| 14 | Scope | ~130 paginated lists + 2 hand-paged tables | User decision. Unpaginated tables and MES stay out. |+| 15 | Rollout | Core + 3 pilots (Sales Orders, Parts, Jobs), then module batches | User decision. Same branch. |+| 16 | Tie-breaker column | `id` by default, override per list | Keyset paging needs a total order. |+| 17 | Count on later pages | No count after the first page | Saves one estimate query per scroll. |+| 18 | Size of one job step | At most 10,000 rows (20 pages of 500) | The load balancer cuts a request at 600 s, and one step is one request. Review fix D. |+| 19 | Who can download a big export | Only the user who asked for it, through `api+/table.export.$exportId`, with the list's permission checked again | Review fix D. |++## Data Model Changes++None. No migrations. Decision 6 removes the 7 cross-table sorts instead of changing views.++## API / Service Changes++- `apps/erp/app/utils/query.ts`: `getGenericQueryFilters` reads `?after=`. `setGenericQueryFilters` adds the tie-breaker sort, the keyset filter and `.limit(limit + 1)`. New `toPage` helper. New cursor encode and decode functions.+- `apps/erp/app/utils/pagination.ts`: shrinks to the fixed page size, then goes away (section 13).+- ~130 route loaders under `apps/erp/app/routes/x+/` return `nextCursor` and drop `limit`/`offset`.+- Service functions keep their signature. They receive `cursor` instead of `offset` inside the generic filter args.+- Bulk-action routes for the 15 tables with `withSelectableRows` split id lists into chunks of 100. Each route also accepts "all matching" (the list's URL search) and then starts the background bulk-action job.+- The per-row checks of each bulk action (for example "only Draft and Planned jobs") move from the table component into the route's server code, so the browser path and the job path share them.+- New Inngest functions in `packages/jobs`: a table export job and a table bulk-action job, each with `concurrency: { key: "event.data.companyId", limit: 1 }`. `packages/jobs` cannot import `~/modules`, so the ERP app hands the jobs a dispatcher, like `setWorkflowDispatch` (`apps/erp/app/routes/api+/inngest.ts:34-47`).+- The export job writes the CSV to `temp-staging` at `{companyId}/exports/{userId}/{exportId}.csv` and notifies the user with a link to `api+/table.export.$exportId`.++## Closest Sibling++N/A for a record type. Code precedent:++- `Grid.tsx:384-465`: virtualizer, spacer rows and `rangeExtractor` in a TanStack table.+- `InfiniteScroll.tsx` with `$itemId.activity.tsx:237-321`: keyset cursor paging (`entryNumber`) with a load-more trigger.++## UI Changes++- List page archetype: no change to layout. The pager bar at the bottom goes away.+- Table header: row count ("245 rows" / "about 2,300 rows").+- A loading row at the bottom while the next page loads, and an error row with Retry.+- A selection bar with "Select all N matching".+- CSV export up to 1,000 rows downloads at once. Above 1,000 rows, a toast says "Your export is being prepared. We'll notify you when it's ready."+- A bulk action above 1,000 rows shows a toast "Running in the background. We'll notify you when it's done."+- Footer totals get a "Total of N loaded rows" label.+- Phone list: no "Load more" button; rows load as you scroll.+- All new copy uses Lingui (`t` / `Trans`), with plurals through `plural`.++## Acceptance Criteria++- [ ] On Sales Orders with 2,500 orders, scrolling to 600px from the bottom loads the next 100 rows. No pager shows.+- [ ] Scrolling through 2,500 rows on Sales Orders shows each order exactly once, in sort order, for each sortable column, ascending and descending.+- [ ] A sort on a column with NULL values (for example a blank due date) returns every row exactly once.+- [ ] A sort value (the cursor) with a comma, a parenthesis or a quote does not break the next-page request.+- [ ] Changing a filter, sort, search or saved view resets the list to the first 100 rows of the new result.+- [ ] With 2,000 rows loaded, only the visible rows (plus overscan) exist in the DOM.+- [ ] Inline editing on a table with `withInlineEditing` keeps the selected cell while the user scrolls far away and back.+- [ ] Pinned columns and the sticky header stay in place while rows load and scroll.+- [ ] On a phone (< 48rem), the compact list loads more rows on scroll, with no "Load more" button.+- [ ] The header shows "245 rows" for 245 rows and "about 2,300 rows" for an estimated 2,300.+- [ ] On Jobs with 800 matching jobs, "Select all 800 matching" then Release releases every Draft and Planned job in the browser path.+- [ ] On Jobs with 3,000 matching jobs, "Select all 3,000 matching" then Release starts one background job. It releases only Draft and Planned jobs and notifies the user with the counts.+- [ ] CSV export of 800 matching rows downloads at once, with on-screen formatting and only the visible columns.+- [ ] CSV export of 12,000 matching rows starts a background job. The user gets a notification with a link, and the file has 12,000 data rows with plain database values.+- [ ] A second big export (or bulk action) from the same company while one runs gets the "already running" message. A big export from another company still starts.+- [ ] The background export never reads rows of another company.+- [ ] A footer total on Sales Orders reads "Total of 100 loaded rows" and grows as more rows load.+- [ ] Another user's edit to a loaded row on row 300 shows up without a scroll jump.+- [ ] Open row 400, press Back: rows 1–400 are still loaded and row 400 is in view.+- [ ] `SyncActivity` and `AccountLedgerDrawer` load more rows on scroll.+- [ ] The 7 cross-table sort columns no longer offer a sort.+- [ ] `pnpm exec turbo run typecheck --filter=erp`, Biome and the ERP unit tests pass. Cursor encode/decode and the keyset filter builder have unit tests.++## Verification status++None of the Acceptance Criteria above is browser-verified. This worktree had no running stack (decision "End-to-end check (Task 16)").++Unit tests cover the logic without a browser:++| Area | Tests |+|---|---|+| Cursor encode and decode, `keys`, offset tokens, keyset filter, `toPage` | `apps/erp/app/utils/cursor.test.ts`, `query.test.ts` |+| Registry merge, list select columns | `utils/list-registry/registry.test.ts`, `apps/erp/test/list-select-columns.test.ts` |+| Reset key, store, merge, edits overlay, virtual rows | `components/Table/infiniteRowsStore.test.ts`, `rowEdits.test.ts`, `useVirtualRows.test.ts`, `utils.test.ts` |+| Job ids, row limit, client factory | `apps/erp/app/utils/table-jobs.test.ts` |+| Job steps, lock, CSV, bulk counts | `packages/jobs/src/table-jobs/{run,lock,csv,bulk}.test.ts` |++The type and unit gates run in the final wave of the review fixes; record their result here.++Check in a browser after `crbn up`, in this order:++1. Every Acceptance Criterion above.+2. A drawer opened over a planning grid keeps the loaded rows (`ignoreParams`).+3. A star on a document past row 100 shows at once and stays.+4. A failed later page shows "Couldn't load more rows" with Retry.+5. A background export downloads through `api+/table.export.$exportId`. Another user of the company gets 404 for the same link.+6. "Select all" on more than 2,000 jobs, then Release, shows the 2,000-row refusal.++## Open Questions (resolved)++- [x] Which virtualization library? — **Answer:** TanStack Virtual. It is already installed and used, and it is headless.+- [x] Offset paging or cursor paging? — **Answer:** Cursor paging, because it works well with infinite scroll.+- [x] When to start the next fetch? — **Answer:** At 500–600px from the bottom. The spec uses 600px.+- [x] Reuse the route loader or add API routes? — **Answer:** Reuse the route loader (option A). New API routes would duplicate the loaders.+- [x] What replaces the pager's "1–100 of N"? — **Answer:** A row total in the table header.+- [x] Sorts by another table's column? — **Answer:** Turn off those sorts.+- [x] Row count wording? — **Answer:** Exact below 1,000, "about N" above.+- [x] What does "select all" select? — **Answer:** Every matching row, through a Gmail-style "Select all N matching" bar.+- [x] What does CSV export download? — **Answer:** All matching rows. Columns stay WYSIWYG.+- [x] Load-all cap? — **Answer:** First 5,000 rows in the browser. Then changed: the research suggests journals pass 10,000 rows, so work above 1,000 rows moves to the server.+- [x] Can the server path become an attack surface? — **Answer:** Yes, if requests wait inside the server. Requests above 1,000 rows become Inngest jobs, 1 per company at a time. Many companies at once is an accepted risk until a separate worker container exists.+- [x] What do big exports contain? — **Answer:** Plain database values with the visible columns and translated headers.+- [x] How far does "select all matching" go? — **Answer:** No cap. Above 1,000 rows, the bulk action runs as an Inngest job.+- [x] Live updates while scrolled deep? — **Answer:** Refresh the loaded rows in place.+- [x] Back navigation? — **Answer:** Restore the same rows and scroll position.+- [x] Footer totals? — **Answer:** As today: total of the rows on screen, with a "loaded rows" label. No "Total all".+- [x] Scope? — **Answer:** All paginated lists plus the 2 hand-paged tables.+- [x] Rollout? — **Answer:** Core plus 3 pilots, then the rest in module batches.++## Autonomous Decisions++The user approved the spec, then asked for the whole pipeline (plan, build, test, review, fixes) to run without questions. The code research for the plan found facts the interview did not cover. Each decision below was made without the user. Review the high-stakes ones first.++### High-stakes++- [x] **A second big job from the same company** — **Autonomous:** The route takes a Redis lock (`SET key NX EX`) per company and job type before it starts the Inngest job. If the lock exists, the route answers "already running". If Redis is down (`redis.set` returns `null` and `redis.get` returns `null`), the route starts the job anyway: Inngest's per-company concurrency still runs the jobs one at a time. *(The lock is now a Lua script: Review fix D, "the lock".)* — Codebase rung: Inngest concurrency queues a second run, it never refuses it (`company-export.ts:363-370`); `@carbon/kv` returns `null` on failure (`packages/kv/src/resilient.ts`).+- [x] **Where big CSV files go** — **Autonomous:** The `temp-staging` bucket, under `{companyId}/exports/{jobId}.csv`. The download link is the existing `/file/preview/temp-staging/...` route. The nightly cleanup deletes the file after 7 days. *(Key and link replaced by Review fix D, "per-user export files".)* — Codebase rung: company buckets cap one file at 50 MB (`packages/files/src/storage.ts:36`); `temp-staging` allows 2.5 GB and the preview route already checks the `companyId` prefix (`file+/preview+/$bucket.$.tsx:69-90`).+- [x] **Row ceiling for one background export** — **Autonomous:** 100,000 rows. Above that, the job writes the first 100,000 rows and the notification says the file is cut. — Product judgement: the earlier chat named 100k as the guard; without a ceiling one export can run for a very long time on the shared containers.+- [x] **Which bulk actions get the background path** — **Autonomous:** Only the actions whose request is "ids + one field/value": item bulk update (Parts, Materials, Tools, Consumables, Services), Jobs Release, Jobs Delete, Purchase Order Delete, Batches Release and Dissolve, and user Deactivate / Send Invite / Edit Permissions. The planning tables (Order Parts, Create Jobs, Apply Suggested Changes) and Kanban Print Labels stay browser-only, capped at 1,000 selected rows. — Codebase rung: the planning payloads are built from browser state (drawer edits, time fence, supplier map: `PurchasingPlanningTable.tsx:349-421`); a PDF of thousands of labels is not a bulk action.+- [x] **Server-side checks that were browser-only** — **Autonomous:** Jobs Delete gets a server check for the `delete: production` permission and for the allowed statuses (Draft, Planned, Due Today, Overdue), plus a `companyId` filter on its status read. Purchase Order Delete gets a `companyId` filter and a Draft/Planned status check. — Spec rule 7.1: the job path must apply the same per-row checks; the research found these checks only in the browser (`job+/update.tsx:39-58`, `purchase-order+/update.tsx:26-31`).++### Other decisions++- [x] **Sort gates** — **Autonomous:** Both sort entry points (the header menu, `Table.tsx:1357-1361`, and the toolbar Sort picker, `Table/utils.ts:79-82`) skip any `accessorKey` that contains a `.` and any column with `enableSorting: false`. This turns off the 7 cross-table sorts (Decision 6). Jobs `orderQuantity` and `inventoryQuantity` get `enableSorting: false`: the `jobs` view has no such columns, so their sort fails today.+- [x] **Array sort columns (`tags`, `suppliers`)** — **Autonomous:** The keyset filter encodes an array value as a quoted Postgres array literal. If a unit test or a manual check shows PostgREST rejects it, the executor sets `enableSorting: false` on array columns instead and records it here.+- [x] **Custom field sorts (`customFields->>{id}`)** — **Autonomous:** The cursor reads the value from `row.customFields[id]` and compares it as text.+- [x] **Lists without a unique `id`** — **Autonomous:** `contractors` uses `supplierContactId`, `customFieldTables` uses `table`. The customer portal share page (`share+/customer.$id.tsx`, RPC without a row id) and the customer/supplier account lists (foreign default sort `user(lastName)`, no top-level `id` selected) keep a single load of up to 1,000 rows with no paging. They are small per company.+- [x] **Lists that do not page today** — **Autonomous:** `getCurrencies`, `getJobMaterialsWithQuantityOnHand`, `sync-tieout`, `invoicing+/_index` (a dashboard), `getPrintJobs` and `getGlobalAuditLog` keep their current loading. `getPrintJobs` and `getGlobalAuditLog` use their own offset paging (an RPC with `p_offset`); they get the infinite-scroll UI on top of offset requests, because their sources are outside `setGenericQueryFilters`.+- [x] **Revalidation cost** — **Autonomous:** A loader revalidation with the same URL search replaces the first page and re-fetches the other loaded pages one by one, up to 20 pages (2,000 rows). Rows past 2,000 are dropped and the cursor restarts from row 2,000. — The router re-runs the list loader on every drawer open and close (`defaultShouldRevalidate`), so an unbounded refresh would re-read every loaded row each time.+- [x] **Back-navigation memory** — **Autonomous:** A module-level `Map` (max 10 entries, oldest dropped first) keyed by `pathname + search`. *(Key replaced by Review fix A: company id + `dataKey` + page URL key.)* — The 3 pilot lists unmount when a record opens (`path.to.salesOrderDetails` is outside `sales+/orders`), so component state cannot hold it.+- [x] **Extra per-page data** — **Autonomous:** `infinite` takes an optional `onPage(data)` callback, so a table can merge per-page extras. Jobs uses it for `batchesByJobId`. *(Replaced by Review fix C: `mapRows` puts the extras on each row; `onPage` is gone. The other decisions below that name `onPage` are replaced the same way.)*+- [x] **Search escaping** — **Autonomous:** Out of scope. 49 services put the raw search into `.or()`; that bug exists today and is independent of paging. The acceptance criterion about commas now covers cursor values only. Recorded as a follow-up.+- [x] **Commits** — **Autonomous:** No commits. The user's standing rule forbids commits without permission; the work stays in the working tree for review.+- [x] **A page fetch whose loader throws** — **Autonomous:** The route's error screen shows, as for every fetcher in the app today. *(Replaced by Review fixes A and B: a failed later page returns `listError`, and the list shows "Couldn't load more rows".)* The inline "Couldn't load more rows" row with Retry shows when a request ends without a new rows array. — Codebase rung: React Router sends a fetcher's loader error to the nearest error boundary and drops the fetcher (`setFetcherError`, `react-router/dist/development/chunk-OB3PAWPO.mjs:3141`). A fetcher cannot catch it, and Decision 3 keeps the fetcher.+- [x] **The URL of the next page** — **Autonomous:** `useInfiniteRows` loads the list route's own URL from `useFormAction()`, not `location.pathname`. — Codebase rung: with a drawer open, `location.pathname` is the child route, whose loader has no rows. `useFormAction()` also adds `?index` for an index route (`chunk-OB3PAWPO.mjs:11027`), which `fetcher.load` needs to reach the index loader.+- [x] **Back-navigation restore** — **Autonomous:** The hook restores only on a Back/Forward (`POP`) navigation. Page 1 always comes fresh from the loader. The memory keeps the rows after page 1, their page count, the cursor and the scroll offset. The restored rows can be stale, so the hook fetches them again in the background with the revalidation rule (at most 20 pages). — Product judgement: a sidebar link click should open the list at the top; a record the user just edited must not show its old values after Back.+- [x] **The scroll offset for Back** — **Autonomous:** `useInfiniteRows` returns `rememberScrollTop(scrollTop)`. The Table calls it from its scroll listener. — Plan gap: the hook cannot read the scroll element on unmount, because React detaches the ref before the effect cleanup runs.+- [x] **A cursor that does not fit the sorts** — **Autonomous:** `setGenericQueryFilters` ignores a cursor whose value count differs from the sort count, and the request returns page 1. If every user sort is a cross-table sort (dropped by Decision 6), the default sorts apply. — Product judgement: only a hand-edited URL produces this, and an error screen helps nobody there.+- [x] **One virtual item per row** — **Autonomous:** Each virtual item is one `<tbody>` that holds the group header row, the data row and the expanded row. The virtualizer measures the `<tbody>`. `Row.tsx` and `rowMemo.ts` do not change. — Plan gap: a ref on the data row measures that row only, and a context-menu row gets no ref through `ContextMenuTrigger`. A table can hold many `<tbody>` elements.+- [x] **Row ids** — **Autonomous:** The Table keys rows by `id` only when every row has an `id` and no two rows share it (`hasUniqueRowIds`). Otherwise it keeps index keys, as before. — Product judgement: a list that repeats an id would break React keys and select two rows with one click.+- [x] **A new list query** — **Autonomous:** When the URL search changes (without `after`), the desktop table scrolls to the top and clears an uncontrolled selection. — Codebase rung: before, a new result set cleared the selection through the `data.length` effect and the pager scrolled to the top. With id keys, that effect no longer fires.+- [x] **Header count and footer label** — **Autonomous:** The header shows the row count where the condensed Prev/Next buttons were, only when `withPagination` is on and `count` is above 0. The footer label "Total of N loaded rows" shows only on a table with `infinite`. — Product judgement: a table without `infinite` has all its rows, and a table without a count would read "0 rows".+- [x] **The loading row** — **Autonomous:** While the next page loads, the row under the last row shows a spinner and "Loading more rows". The phone list shows a spinner above its footer text. — Plan step 7 named a spinner only; the text tells a screen reader user what happens.+- [x] **Phone list scroll element** — **Autonomous:** `CompactList` virtualizes against the nearest ancestor that scrolls and has content past its edge. On a page that is `<main>`. — Product judgement: a phone list in a drawer or a modal scrolls inside it. A virtualizer on `<main>` would never render the rows below the first view there.+- [x] **Phone group headers** — **Autonomous:** On phones, a group header is its own virtual item, and the range keeps the header above the first row in view rendered. So the header stays sticky while its rows scroll. — Plan step 5 says "keep group headers as they are". A header inside a per-row wrapper can only stick inside that wrapper.+- [x] **Phone footer text** — **Autonomous:** The phone footer "{n} of {count} rows" shows on every list with `withPagination` or `infinite`, also at the end of the list. An estimated count below the loaded rows shows the loaded number. — Product judgement: at the end of the list the footer is the only total on screen.+- [x] **Registry shape** — **Autonomous:** The registry is a folder, `utils/list-registry/`, with `index.server.ts` (types, `LIST_REGISTRY`, `getListDefinition`, `fetchListPage`) and one file per module. The files for every Task 12 batch exist from the start, and the index merges all of them. A loader imports its definition from the module file to keep the row type. — Parallel batches must not edit the same file. `fetchListPage` keeps each converted loader to one call that the jobs (Tasks 10 and 11) can share.+- [x] **Reference data on later pages** — **Autonomous:** When `?after=` is set, the Parts and Jobs loaders skip `tags` and `locations`. — Plan step 4: the Table reads a fetched page for its rows, `nextCursor` and `onPage` only. No component reads those keys from a fetched page.+- [x] **Jobs tracked entities** — **Autonomous:** `JobsTable` loads the tracked-entity labels of each page from `onPage` and merges them into one map. — Plan gap: the labels came from a browser query over page 1 only, so rows past 100 lost them.+- [x] **Lingui catalogs** — **Autonomous:** Tasks 4–7 add the strings through `Trans`, `Plural` and `t`, and a Vite compile of the 3 changed Table files shows no `@lingui/core` import. The `.po` catalogs are not extracted in these tasks. — `pnpm lingui:extract` rewrites 13 locale files; Task 16 runs it once after all batches, so parallel batches do not conflict on them.+- [x] **Browser check of the pilots (Task 6)** — **Autonomous:** Not run. This worktree has no running dev stack: `https://erp.infinite-scroll.dev/login` returns 502 from the portless proxy, and Docker has no container for this worktree. `crbn up` would create and migrate a new database, which this run must not do. Task 16 repeats the check. — Run rule: never touch the database.+- [x] **Loaders without `bypassRls` (Task 12d)** — **Autonomous:** If a list loader did not pass `bypassRls` before, it still does not. The loader calls `requirePermissions(request, xList.permission)`, and the permission keeps `role: "employee"`. This applies to 13 Items lists (change notices, the material property lists, item groups, units of measure and the 2 method lists). — Product judgement: recipe step 4 assumes every loader bypasses RLS. A switch to the service-role client changes who can read the rows, and paging needs no such change.+- [x] **Material dimensions unit system (Task 12d)** — **Autonomous:** The `material-dimensions` registry query reads `companySettings.useMetric` itself, on every page. — Codebase rung: the loader read it before the list query (`dimensions.tsx`). A background job calls the registry query without the loader, so the query must find the unit system on its own.+- [x] **Rows key `data` (Task 12d)** — **Autonomous:** The units of measure, change notice actions and change notice types loaders returned the raw service result. They now return `{ data, count, nextCursor }`, and the tables use `dataKey: "data"`. — Minimal change: the route components already read `data`.+- [x] **Purchasing Material Planning has no registry entry (Task 12b)** — **Autonomous:** `purchasing+/planning` pages with a cursor (`toPage` in the loader), but it has no `listKey`. Its export and bulk actions keep the 1,000-row browser path. — Codebase rung: the grid RPC needs the location that `resolveLocationId` reads from the user's defaults, and a registry query gets only the URL search. The spec already keeps the planning bulk actions browser-only.+- [x] **Planning rows and actions on later pages (Task 12b)** — **Autonomous:** `PurchasingPlanningTable` merges each later page's `items` and `planningActions` by item id through `onPage`. The supplier defaults, the order drawer and the bulk Order action then see every loaded row. A later page skips the `?item=` drawer-row read. — Plan step 8: the loader reads the actions of its own page only, so rows past 100 had no actions and no planned orders.+- [x] **Supplier contacts on later pages (Task 12b)** — **Autonomous:** The suppliers loader reads the report contacts of every page, and `SuppliersTable` merges them through `onPage`. A background export of more than 1,000 suppliers has no values for the 11 contact and address columns, because they are not columns of the `suppliers` view. — Plan step 8; the background export reads the registry rows only.+- [x] **Loaders without `bypassRls` (Task 12b)** — **Autonomous:** Supplier returns and leases keep the RLS client, by the Task 12d rule. Supplier types keeps `role: "employee"` and no column filters, as its loader had before.+- [x] **Loaders without `bypassRls` (Task 12a)** — **Autonomous:** RMAs, contracts, rental agreements, the price list, pricing rules, customer portals and the 4 reason and type lists keep the RLS client, by the Task 12d rule. The last 7 keep `role: "employee"`.+- [x] **Price list paging (Task 12a)** — **Autonomous:** The `price-list` registry query runs `resolvePriceList` with a customer or customer type in the URL, else `getBaseCatalog`, as the loader did. It reads `quantity` from the URL itself. The rows carry the item id as `itemId`, so the entry sets `idColumn: "itemId"`; the query still breaks ties on `item.id`. A later page skips the scope options. — Codebase rung: the services build each row from one `item` row (`itemId: item.id`).+- [x] **Sorts on computed columns (Task 12a)** — **Autonomous:** The 5 price list columns (Item, Item Group, Base Price, Resolved Price, Source) and the customer portal "Portal Link" column get `enableSorting: false`. — Codebase rung: the `item` table and `externalLink` have no such columns, so their sort fails today; the Jobs columns in "Sort gates" got the same fix.+- [x] **Select all past 1,000 rows without a `listKey` (Task 8)** — **Autonomous:** The bar offers "Select the first 1,000 rows". The browser loads and selects the first 1,000 rows. — Spec 7: browser-only lists cap the selection at 1,000 rows; the export uses the same cap.+- [x] **Rows loaded after "all matching" (Task 8)** — **Autonomous:** The Table selects each row that loads while every matching row is selected. A tick, an untick or "Clear selection" ends the "all matching" state. — Product judgement: an unticked row under "All matching rows selected" contradicts the bar.+- [x] **Select all on phones (Task 8)** — **Autonomous:** Phones get no new select-all control. The bar shows in selection mode when every loaded row is selected. — Standing rule: phone changes adapt the layout and add no features.+- [x] **The `allMatching` tooltip (Task 8)** — **Autonomous:** `useAllMatchingUnsupportedLabel()` (exported from `~/components/Table`) returns "Filter the list to 1,000 rows or fewer". A table whose action has no background path uses it. Until Task 11, Parts and Jobs ignore `allMatching` and act on the loaded rows only. — The plan puts the per-table handling in Task 11.+- [x] **When the export goes to the job (Task 9)** — **Autonomous:** 3 rules, in this order:+ 1. If the list has a `listKey` and the count is above 1,000, the browser posts to the export route at once.+ 2. Else the browser loads up to 1,000 rows. If rows remain and the list has a `listKey`, it posts to the route.+ 3. Else it downloads the first 1,000 rows and shows "Exported the first 1,000 rows."++ A list with every row loaded exports the table's own rows, so inline edits stay in the file. — Spec 8, rule 5: the loop hands the export to the job when rows remain after 1,000.+- [x] **The export request (Task 9)** — **Autonomous:** The browser posts with `fetch`, not a fetcher. The success toast needs `{ success: true }`. On an error the toast shows the route's `error` text, else "The export could not start. Try again." — Codebase rung: a fetcher action revalidates the list loader, which re-fetches every loaded page (`fetch` precedent: `SalesOrderLineForm.tsx:317`).+- [x] **Production lists with no registry entry (Task 12c)** — **Autonomous:** Production Material Planning, Demand Forecasts and the 4 job lists (events, operations, quantities, steps) page with a cursor (`toPage` in the loader), with no `listKey`. Their export and bulk actions keep the 1,000-row browser path. — Codebase rung: a registry query gets only the URL search. The job lists need the `jobId` route param, and the planning lists need the user's default location (same rule as Task 12b).+- [x] **Production planning rows and actions on later pages (Task 12c)** — **Autonomous:** `ProductionPlanningTable` merges each later page's `items` and `planningActions` by item id through `onPage`, and clears them when the page scope changes. A later page skips the `?item=` drawer-row read. — Same rule as Task 12b: the loader reads the actions of its own page only.+- [x] **Production events order (Task 12c)** — **Autonomous:** `getProductionEvents` no longer orders by `startTime` ahead of every sort. `startTime` ascending is now the first default sort, then `createdAt` descending, so a user sort replaces it. — Codebase rung: the cursor must follow every column of the ORDER BY. A fixed first order breaks it.+- [x] **Assembly instructions order (Task 12c)** — **Autonomous:** The default sort is `createdAt` descending, not `updatedAt` descending NULLS LAST. `getAssemblyInstructions` now applies the URL sorts and filters through `setGenericQueryFilters`; before, it ignored them. — Codebase rung: `DefaultSort` has no NULLS option, and a descending cursor puts NULLs first. Instructions never edited would then lead the list.+- [x] **Demand Forecasts count (Task 12c)** — **Autonomous:** The loader returns the RPC's count from the first page, not `data.length`. — Codebase rung: with paging, `data.length` is one page. Production planning already reads the count of the same kind of RPC.+- [x] **Batches sorts on computed columns (Task 12c)** — **Autonomous:** The Jobs and Quantity columns of `BatchesTable` (`memberCount`, `totalQuantity`) get `enableSorting: false`. — The loader computes them per page, so the table has no such column. Same rule as the Jobs `orderQuantity` sort.+- [x] **Loaders without `bypassRls` (Task 12c)** — **Autonomous:** Scrap reasons, procedures, assembly instructions and batches keep the RLS client, by the Task 12d rule. The scrap reasons loader keeps the rows key `data`, by the Task 12d rule.+- [x] **Loaders without `bypassRls` (Task 12g)** — **Autonomous:** All 12 quality lists keep the RLS client and `role: "employee"`, by the Task 12d rule. Gauge types, issue types and required actions keep the rows key `data`. — None of the quality loaders passed `bypassRls` before.+- [x] **Quality reference data on later pages (Task 12g)** — **Autonomous:** On `?after=`, the loaders skip the issue types (issues, actions), the required actions (actions), the gauge types and company settings (gauges, calibrations) and the tags (quality documents). — Plan step 6; the customers loader skips its statuses by the same rule.+- [x] **Inspection plans sort (Task 12g)** — **Autonomous:** `getInspectionDocuments` adds `drawingNumber` to each mapped row, and the plan "Name" column gets `enableSorting: false`. — Codebase rung: the service maps each row, so the cursor found no `drawingNumber` (the default sort). The `inspectionDocuments` view has no `name` column, so that sort fails today.+- [x] **Location-scoped inventory lists (Task 12e)** — **Autonomous:** Quantities, kanbans and stock transfers page with `toPage` in the loader and have no registry entry and no `listKey`. Their export and bulk actions keep the 1,000-row browser path. — Codebase rung: without `?location=`, the loaders read the location from the user's defaults, which a registry query cannot see (the Task 12b planning rule). Quantities pages through its RPC: PostgREST applies the keyset filter, the order and the limit to the rows of `get_inventory_quantities`.+- [x] **Storage units tree (Task 12e)** — **Autonomous:** The storage units list does not page. The loader reads up to 1,000 roots in one load, and `getStorageUnitSubtrees` reads their subtrees 100 root ids per request. — Codebase rung: the Table appends a later page's rows flat, outside their parents, and the tree builds its rows from `data`. The spec's "single load" rule covers lists that cannot page.+- [x] **Realtime by loaded ids (Task 12e)** — **Autonomous:** The receipts, shipments, warehouse transfers and inventory counts tables drop their `useRealtime(table, "id=in.(…)")` call. — Codebase rung: each route's `handle.realtime` already follows every row of that table in the company. The id filter named page 1 only, so it added nothing.+- [x] **Blind count sorts (Task 12e)** — **Autonomous:** While a count is blind, the count lines loader drops a sort on `systemQuantity` or `variance`, as it already drops a filter on them. — Product judgement: the next-page cursor holds the last row's sort values, so it would send the withheld quantity to the browser.+- [x] **Inventory reference data on later pages (Task 12e)** — **Autonomous:** On `?after=`, the loaders skip the option lists (quantities, count lines), the locations (inventory counts), the company settings (tracked entities) and the count summary and movements (count lines). Tracked entities read the shelf-life policies of each page, and `TrackedEntitiesTable` merges them through `onPage`. — Plan steps 6 and 8.+- [x] **Storage rules single load (Task 12e)** — **Autonomous:** `x+/inventory+/storage-rules` passes `cursor: null` in place of `offset: 0`. It still reads up to 1,000 rules in one load. — The batch table does not list it, but it is in the module's folder and failed typecheck on the removed `offset`.+- [x] **Loaders without `bypassRls` (Task 12f)** — **Autonomous:** All 7 invoicing lists and all 11 accounting lists keep the RLS client, by the Task 12d rule. The accounting lists keep `role: "employee"`.+- [x] **Realtime by loaded ids (Task 12f)** — **Autonomous:** The sales invoice and purchase invoice tables drop their `useRealtime(table, "id=in.(…)")` call, as in Task 12e. No id list is built, so the `.in()` bound in `.ai/lessons.md` does not apply. — Codebase rung: `handle.realtime` on `invoicing+/sales` and `invoicing+/purchasing` follows every row of the table (`RouteRealtime` adds a string entry with no filter). A change reloads page 1, and the Table then fetches the loaded pages again.+- [x] **Group-scoped accounting lists (Task 12f)** — **Autonomous:** The `accounting-dimensions` and `intercompany-transactions` registry queries read `company.companyGroupId` for the company, then call the service with the group. — Codebase rung: a registry query gets the company only; `invoicing.service.ts` reads the group with the same `company` select.+- [x] **Period runs (Task 12f)** — **Autonomous:** Revenue recognition runs and lease runs are 2 registry entries on one query factory. `loadPeriodRuns` picks the entry by run type from `periodRunsLists`. `getRevenueRecognitionRuns` and `getDepreciationRuns` add `createdAt` to their selects. — Codebase rung: both default sorts are `createdAt`, so the cursor found no value.+- [x] **Intercompany company sorts (Task 12f)** — **Autonomous:** The Source and Target columns get `enableSorting: false`. — Codebase rung: `sourceCompany` and `targetCompany` are embedded companies, not columns of `intercompanyTransaction`, so their sort fails today.+- [x] **Accounting reference data on later pages (Task 12f)** — **Autonomous:** On `?after=`, fixed assets and fleet skip the asset class reads, and asset classes skips the company settings. Depreciation runs and the period runs keep their one-row "last run" read. — Plan step 6. The last run decides the next period, and it is one row.+- [x] **Invoicing dashboard (Task 12f)** — **Autonomous:** `invoicing+/_index` passes `cursor: null` and keeps the first 6 payments. — Codebase rung: `setGenericQueryFilters` reads `limit + 1` rows for the next-page check.+- [x] **Loaders without `bypassRls` (Task 12h)** — **Autonomous:** Attributes, timecards, employee types, groups, abilities, failure modes, both maintenance lists, training, the 4 settings lists, documents and both workflow lists keep the RLS client, by the Task 12d rule.+- [x] **Groups and partners single load (Task 12h)** — **Autonomous:** `users+/groups` and `resources+/partners` load up to 1,000 rows once, with no registry entry and no next page. — Codebase rung: groups build a tree with `arrayToTree`, and a page cut splits a group from its parent. A partner has one row per ability (primary key `id` + `abilityId`), so `id` cannot break ties.+- [x] **Sales rules and other single loads (Task 12h)** — **Autonomous:** `sales+/sales-rules`, `settings+/serial-numbers.new` and `resources+/assignments.$trainingId` pass `cursor: null` in place of `offset: 0` and keep their single load. Sales rules gets no registry entry: `SalesRulesGroups` is not a `<Table>`, so no `listKey` reads it. Its plan gate does not change. — The same fix as storage rules (Task 12e).+- [x] **Training assignment status (Task 12h)** — **Autonomous:** `getTrainingAssignmentStatus` cuts its in-memory rows at `limit` from row 0. — Codebase rung: the RPC returns every row, `GenericQueryFilters` has no `offset`, and both callers read one list.+- [x] **Recent documents (Task 12h)** — **Autonomous:** The "Recent" view is its own registry entry, `recent-documents`, with the default sorts `lastActivityAt` descending, then `favorite`. A sort the user picks replaces both. The loader picks the entry from `?q=`, and `DocumentsTable` gets the key as a prop. — Codebase rung: `getDocuments` put the `lastActivityAt` order before `setGenericQueryFilters`, so the cursor did not follow it. A registry entry has one fixed `defaultSorts`.+- [x] **Maintenance location (Task 12h)** — **Autonomous:** The 2 maintenance registry queries read `?location=` and fall back to the company's first location, as the loaders did. The loaders set the resolved location on the params they pass to `fetchListPage`. — The Task 12d material dimensions rule: a background job calls the query without the loader.+- [x] **API key hash (Task 12h)** — **Autonomous:** The `api-keys` registry query drops `keyHash` from every row, so an export never holds it. `ApiKeysTable` types its rows without the hash. — The loader dropped it before; the registry query is now the one place that reads the rows.+- [x] **Per-page extras (Task 12h)** — **Autonomous:** `WorkflowsTable` merges the version numbers and last runs of each later page through `onPage`. Workflow runs and documents compute the record names and download tokens per page in the loader, so each row carries its own. On `?after=`, the loaders skip the tags, the option lists, the invites, the MFA users, the document labels and file types, and the webhook config. — Plan steps 6 and 8.+- [x] **Optimistic document rows (Task 12h)** — **Autonomous:** *(Corrected by Review fix C.)* The first version skipped a row past page 1, and no revalidation followed, so a star or a label on such a row never showed. Now `DocumentsTable` lays each star and label change over every loaded row with the edit overlay (`applyRowEdits`). The change stays until its write ends. Then the table revalidates, and a load that starts after the write drops the change. See "Review fix C: Documents keeps the user's changes".+- [x] **Sync Activity pages (Task 13)** — **Autonomous:** The tab loads 100 rows per page, newest first, `id` ascending on ties. The integration loader reads page 1. A new resource route, `api+/integrations.$id.sync-activity`, reads each later page. A revalidation re-reads the loaded rows in one request, up to 2,000 rows. *(Replaced by Review fix C: Sync Activity pages through `pageUrl`, one page per request.)* `getSyncOperations` (`@carbon/ee`) gets an optional `after` keyset and the `id` tie-break, the same keyset as `getSyncOperationsExportPage`. The `syncPage` param is gone. — Codebase rung: the integration loader calls the provider (`listChartOfAccounts`), so a scroll must not re-run it.+- [x] **Account ledger drawer (Task 13)** — **Autonomous:** `getAccountLedger` pages with a cursor through `setGenericQueryFilters` and `ACCOUNT_LEDGER_DEFAULT_SORTS` (posting date, then entry, both descending). Lines of one entry now tie-break on `id` ascending, not descending. The 4 drawer routes read 100 lines per page (before: 50) and skip the summary on `?after=`. The drawer loads more through `useInfiniteRows` when its body scrolls to the end. — Codebase rung: the keyset filter compares the id ascending only.+- [x] **Print jobs and audit log (Task 13)** — **Autonomous:** Both loaders keep their offset sources and read 101 rows. The `after` token is `{ values: [], id: "<next offset>" }`. Neither list has a registry entry, so export and bulk actions keep the 1,000-row browser path. The audit log RPC still counts every page: `@carbon/ee` stays unchanged. — Spec decision "Lists that do not page today".+- [x] **Single-load lists (Task 13)** — **Autonomous:** The customer and supplier account lists and the customer portal share page load up to 1,000 rows and pass no `infinite`. Before, each showed its first 100 rows only. `getExternalSalesOrderLines` passes `idColumn: "salesOrderId"`. — Codebase rung: the RPC returns no `id`, so the default `id` tie-break would fail. A table without `infinite` holds all its rows (decision "Header count and footer label").+- [x] **Contractors and custom fields (Task 13)** — **Autonomous:** Both lists are registered with their `idColumn` and key their rows by it (`getRowId`). `getContractors` now reads the count; before, the list's count was always 0. The custom fields loader now throws its error redirect; before, it built the redirect and dropped it.+- [x] **Job leftovers (Task 13)** — **Autonomous:** `$jobId.materials` passes `cursor`, which `getJobMaterialsWithQuantityOnHand` ignores, so the page still loads every material. `job+/new` passes `cursor: null` and keeps the first 100 assets under construction. — Keep behavior.+- [x] **Which client the table jobs read with (Task 10)** — **Autonomous:** Every table job reads its list as the requesting user (`getUserScopedClient`), also for lists whose loader bypasses RLS. `ListDefinition` gets no RLS flag. — Spec 8.4 says the job runs as the user. A service-role read would rely on each list query to filter by `companyId`, and the queries of the RLS-client lists were not written for that. Risk: a list whose RLS is stricter than its permission exports fewer rows than the screen shows.+- [x] **The job's permission check (Task 10)** — **Autonomous:** The job reads the user's claims as the user (`get_claims`, the `readOwnerPermissions` pattern) and requires the employee role plus the list's permission. The route requires the same through `requirePermissions`. — Codebase rung: `getUserClaims` reads through a cache that can hold a revoked permission for an hour (`owner.ts`).+- [x] **Export page size (Task 10)** — **Autonomous:** The job reads 500 rows per query, not 1,000. — Codebase rung: the list query asks for `limit + 1` rows (`query.ts`), and PostgREST caps a response at `max_rows = 1000` (`config.toml`). A limit of 1,000 gets 1,000 rows back, so `toPage` sees no next page and the export stops at row 1,000. Task 11 must use the same limit.+- [x] **Export upload (Task 10)** — **Autonomous:** The job pages into a temp file, then reads the file into a Buffer and uploads it. *(Replaced by Review fix D: part files and a streamed upload.)* — `storage-js` accepts a Node stream, but no code in this repo uploads a stream, and no running stack was available to prove one against Storage. The 100,000-row ceiling bounds the Buffer.+- [x] **Lock value and release (Task 10)** — **Autonomous:** The lock value is the export id, not the user id. The job deletes the lock only while it still holds that id, in its last step and in `onFailure`. If `trigger` fails, the route deletes the lock. — A lock that expired after one hour and was taken by the next export must not be deleted by the first one.+- [x] **Export notifications (Task 10)** — **Autonomous:** `NotificationEvent.TableExport` (topic General) goes in-app and by email when the file is ready. The text comes from the payload, like `IntegrationSync`, in English, like every notification built in `content.ts`. A refused or failed export goes in-app only, with documentId `failed:{exportId}`, and its row opens the home page. A ready export's row downloads the file with a full page request (`reloadDocument`): the preview route is a resource route. — Product judgement: an email for a failure would carry a download button with no file behind it.+- [x] **Who can open an export file (Task 10)** — **Autonomous:** Any employee of the company who has the link. *(Replaced by Review fix D: the user who asked for it only.)* The preview route checks the employee role and the `{companyId}/` prefix only. The export id is a `nanoid`, so nobody guesses a link. The daily cleanup (cron `0 7 * * *`) deletes the file after 7 days: it is in no `modelUpload` row (`cleanup.ts`, "prune-staged-raw-models").+- [x] **The bulk job reads every id first (Task 11)** — **Autonomous:** The job reads all matching ids (500 per query, at most 100,000, duplicates dropped) before it acts. *(Steps replaced by Review fix D: collect steps of 10,000 rows, ids stored in `temp-staging`.)* Then it runs the action 100 ids at a time. Past 100,000 rows the notification says that only the first 100,000 were processed. — Product judgement: an update moves `updatedAt`, so on a list sorted by `updatedAt` an updated row lands behind the cursor and the job would read it again without end. The 100,000 ceiling is the export's.+- [x] **No retry for the bulk job (Task 11)** — **Autonomous:** `table-bulk-action` has `retries: 0`. A chunk that throws counts as `failed` and the run goes on. — A retry runs every chunk again, and Send Invite would email each user twice.+- [x] **Where the production bulk actions live (Task 11)** — **Autonomous:** `bulkReleaseJobs`, `bulkDeleteJobs`, `bulkReleaseBatches` and `bulkDissolveBatches` are in `modules/production/bulk-actions.server.ts`, not `production.server.ts`. Items and purchasing use their `{module}.server.ts`. — Codebase rung: `job+/release.test.ts` replaces `releaseJobs` in `production.server.ts`, and a module cannot replace its own internal calls. The module already has other `.server.ts` files (`forecast.server.ts`).+- [x] **Rows an action may not act on (Task 11)** — **Autonomous:** On both paths the server skips them and counts them as `skipped`: a job that is not Draft / Planned / Due Today / Overdue (Delete) or Draft / Planned (Release), a purchase order that is not Draft / Planned, a batch that is not Planned (Release) or Planned / Active (Dissolve), and an id of another company. The small path answers success for the rest, as Jobs Release did for a stale selection. Purchase Order Delete also requires `delete: purchasing` on the server, as the table did. Batch Dissolve now skips a Completing or Completed batch; before, the server function refused it and the toast named it as failed. — Spec rule 7.1; codebase rung: `job+/release.tsx` skipped a stale selection silently.+- [x] **Bulk action notification (Task 11)** — **Autonomous:** `NotificationEvent.TableBulkAction` (topic General), in-app only. The title holds the action and the 3 counts ("Release jobs finished: 1,200 done, 3 skipped, 0 failed"); the row opens the home page. — The topbar shows the title only, and a run has no file or record to link to.+- [x] **User bulk actions (Task 11)** — **Autonomous:** For Deactivate, Send Invite and Edit Permissions, "done" means queued: the job queues the existing `user-admin` and `update-permissions` jobs. The job picks the users with `canBulkActOnUser` (`users.models.ts`), the rule the table applies to its selection, and reads them with the service role scoped to the company, as the routes do. With `allMatching`, the modal posts through a fetcher that `EmployeesTable` owns, and the route answers `{ background: true }` instead of a redirect. — Codebase rung: the modals close on submit, and an unmounted fetcher never reports its result. The toast text needs Lingui, so it cannot be a flash message.+- [x] **Planning and Kanban bulk actions (Task 11)** — **Autonomous:** No change. These tables have no `listKey`, and the Table sets `allMatching` only for a list with a `listKey` (`Table.tsx:718`), so their actions never see it. — Minimal change: a disabled state for a value that cannot occur is dead code.+- [x] **Item bulk update writes (Task 11)** — **Autonomous:** `bulkUpdateItems` sets the item posting group with one read, one update and one insert per 100 items. Before, the route made 2 queries per item. Jobs Release schedules each location once per chunk of 100 jobs in the background job. — `AGENTS.md`: never query inside a loop. A per-chunk schedule keeps `runBulkAction` one call per chunk.+- [x] **`MAX_PAGE_SIZE` callers (Task 14)** — **Autonomous:** `users+/groups` and `resources+/partners` pass `limit: 1000`, as `storage-rules` and `sales-rules` do. `utils/pagination.ts` keeps `PAGE_SIZE` only. — Plan step 1 deletes `MAX_PAGE_SIZE`, and these 2 single loads were its last callers.+- [x] **Old `offset` resets (Task 14)** — **Autonomous:** `SearchFilter`, the count lines quick filters and the 3 ledger openers (chart of accounts, trial balance, multi-period statements) no longer delete `offset` or `limit` from the URL. `revalidateIgnoringOffset` drops its `offset` handling and becomes `revalidateOnSearchChange` in its 5 routes (4 reports and the chart of accounts). — Codebase rung: no list or drawer writes `?offset=` now (Task 13 moved the ledger drawer to a cursor), and `?after=` never enters the page URL. The old name described a param that no longer exists.+- [x] **Keyboard shortcuts page (Task 14)** — **Autonomous:** `docs/content/docs/reference/keyboard-shortcuts.mdx` drops the ← / → page keys, and its section is now "From a list page". — `keep-sources-in-sync.md`: a user-facing doc must not describe a removed shortcut.+- [x] **Where the paging guide lives (Task 15)** — **Autonomous:** A new rule, `.claude/rules/table-infinite-scroll.md`, with `paths:` on the Table, `query.ts`, `cursor.ts`, the registry and `routes/x+/**`. The root `AGENTS.md` Task Router links it. — Codebase rung: `apps/erp/AGENTS.md` does not exist (plan step 3), and a rule auto-loads where loaders are written. `packages/query/AGENTS.md` names no pager or offset, so it does not change.+- [x] **MCP and v1 API paging (Task 16)** — **Autonomous:** `GenericQueryFilters` keeps an optional `offset`. `setGenericQueryFilters` uses cursor paging (`limit + 1`) when the args carry a `cursor` key, and exact offset paging (`.range`) otherwise. — The MCP generator publishes `limit` + `offset` for every `GenericQueryFilters` service (`scripts/lib/service-metadata.ts`), and `dispatch-parity.test.ts` failed: without this, MCP and agent callers would get page 1 for every offset. `getAccountLedger` takes an optional `cursor` (typed `Cursor`) and `offset` for the same reason.+- [x] **End-to-end check (Task 16)** — **Autonomous:** Not run. This worktree has no running stack, and `crbn up` would create and migrate a new database (AGENTS.md: wait for the user before rebuilding a database). The only other running stack (`carbon-feat-active-pieces-integration`) has a corrupted database: PostgREST logs `missing chunk number 0 for toast value 99130 in pg_toast_2619`. Run `crbn up` in this worktree, then walk the Acceptance Criteria.+- [x] **Review fix A: drawer params keep the list (B4)** — **Autonomous:** `InfiniteOptions.ignoreParams` names the URL params that do not define the list. `getSearchKey` drops them with `after`, so the reset key, the Back store key and the selection ignore them. `useInfiniteRows` returns `resetKey`, and the Table reads it instead of deriving its own.+- [x] **Review fix A: failed later page (B7, client)** — **Autonomous:** A loader returns `listError` (a string) next to its rows key for a failed `?after=` page (`InfiniteListError`, `components/Table/types.ts`). `readPage` reads it as an error, so the list shows "Couldn't load more rows" with Retry. `readPage` also ends the list when `nextCursor` equals the cursor it requested (R1 client guard).+- [x] **Review fix A: Back store per company (B8, R13)** — **Autonomous:** The store key is company id + `dataKey` + page URL key. The company id comes from the authenticated root route data (`useRouteData`), not `useUser()`, which throws outside `/x`. The first store read or write with another company empties the store. A save keeps at most 19 later pages (20 with page 1), the same cap a revalidation re-reads. The rows on screen are never cut. The restored scroll offset stops at the end of the content.+- [x] **Review fix A: edits overlay (B9)** — **Autonomous:** The Table keeps `edits` (row id → edited values and a tick) in place of the `internalData` copy. A logical clock (`tick()`, `rowEdits.ts`) orders edits and loads. `useInfiniteRows.syncedAt` is the tick when the current rows started to load: a new page 1 when no later page is loaded, else the start of the last refresh. An edit before `syncedAt`, or one the row already holds, is dropped. An append does not move `syncedAt`, so it keeps every edit. A table without `infinite` gets a new `syncedAt` with each new `data`, so it drops edits as the old copy did. The values are keyed by column id, not `Partial<T>`, because a nested editable column uses a `a_b` path.+- [x] **Review fix A: one scroll mechanism (C5, R12, R14)** — **Autonomous:** `useInfiniteScroll` observes a sentinel after the rows with an IntersectionObserver (root = the scroll element, `rootMargin: "0px 0px 600px 0px"`). It loads again after each page while the sentinel stays in range, so a short list fills the view. It also remembers the offset for Back, restores it, and scrolls to the top on a new `resetKey`. `isNearEnd` is gone. The Table, the phone list and the account ledger drawer (root "auto": the nearest scrolling ancestor) use it. A `loadMore` during a refresh waits and runs when the task queue is empty. The phone list finds its scroll element again on each resize of the list.+- [x] **Review fix A: shared virtual rows and select-all (C6, C7, C8)** — **Autonomous:** `useVirtualRows` (virtualizer, kept index, spacer slots) serves the Table, the phone list and the Grid. `useSelectAllMatching` derives "all matching" from the choice, the list key and the selection it was made over: a new selection or a new list ends it, with no effect. `useInfiniteRows` has one ref for the latest render's values, one failed-task state and one `isStale` guard.+- [x] **Review fix A: new API for the other waves** — **Autonomous:** `InfiniteOptions.pageUrl` (default `useFormAction()`) lets an `api+` loader serve the pages. `InfiniteOptions.idColumn` keys and de-duplicates rows with no unique `id`. A parent may call `useInfiniteRows` itself and pass the result as `<Table infiniteRows={…}>`; the Table then runs its own hook with infinite scroll off. `loadAll` returns the `resetKey` at its end: the CSV download and "Select all" compare it with the key at the start and stop when the list changed (R15). `EXACT_COUNT_LIMIT` (1,000) replaces the bare `1000` in the row count copy; the "first 1,000 rows" copy takes the number as a value.+- [x] **Review fix D: the table jobs run in steps (B1)** — **Autonomous:** One step reads at most 20 pages of 500 rows (`TABLE_JOB_ROWS_PER_STEP`, 10,000). The export writes one part file per step and a last `compose` step streams the parts into the file. The bulk job stores the ids of each collect step in one file and then runs one apply step per slice. A step returns counts and the next cursor only, and the function sums them outside the steps. — The load balancer cuts a request at 600 s (`sst.config.ts`), and one step is one request. 20 queries stay well below that on a slow view. This replaces the decisions "The bulk job reads every id first" (one step) and "Export upload" (one Buffer).+- [x] **Review fix D: where the bulk ids live (B1)** — **Autonomous:** In `temp-staging`, at `{companyId}/bulk-actions/{runId}/{n}.json`, not in Redis. The job deletes them at the end; the nightly cleanup is the backstop. If an apply step cannot read its file, it counts the slice as failed and the run goes on. — A Redis key with a TTL can be evicted under memory pressure, and the run would then act on nothing without an error.+- [x] **Review fix D: duplicate ids across steps** — **Autonomous:** A collect step drops duplicate ids within its own pages only. A row can appear in two steps only when its sort value changes during the collection. Every action checks the row's status again, so a repeat is skipped or writes the same value. Send Invite can then email a user twice. — An exact check across steps needs every earlier id in each step.+- [x] **Review fix D: ids per apply step** — **Autonomous:** 1,000 by default, 100 per call. Jobs Release takes 25 per step and Batches Release 10, because each job runs the requirements recalculation and MRP. Batches Dissolve takes 100. The route sends `maxRows` and `idsPerStep` on the event (`BULK_ACTIONS`, `utils/table-jobs.ts`). — Product judgement: no measured MRP time was available; these keep a step far below 600 s for a run of one minute per job.+- [x] **Review fix D: 2,000-row limit for the two releases (B1)** — **Autonomous:** The route reads the list's header count (exact up to 1,000, an estimate above) and refuses past 2,000: "Release jobs runs on at most 2,000 rows. Filter the list to 2,000 rows or fewer." The job also stops at 2,000 rows and says so. In the menu, the disabled item shows "Filter the list to 2,000 rows or fewer" as its second line (`useAllMatchingLimitLabel`), because a disabled item takes no pointer events, so a tooltip cannot show. — The count is an estimate, so both checks are needed.+- [x] **Review fix D: the lock (R9)** — **Autonomous:** Take, release and extend are each one Lua script (`packages/jobs/src/table-jobs/lock.ts`): SET NX EX with the remaining TTL on refusal, compare-and-delete, compare-and-expire. Each step of a running job sets the TTL back to one hour. The 409 says "at the latest in N minutes" from the TTL. When Redis answers nothing, the route still starts the job (fail-open, as before). — A long run must not lose its lock to the next request.+- [x] **Review fix D: a new user token every four minutes (B2)** — **Autonomous:** The job passes a client factory (`refreshingClientFactory`, `utils/table-jobs.ts`) that signs a new token when the last is four minutes old. Jobs Release, Batches Release and Batches Dissolve ask it for the client before each row; the other actions ask once per chunk. The action routes pass the request's client. — A token lives five minutes, and a chunk of releases can run longer.+- [x] **Review fix D: per-user export files (R6)** — **Autonomous:** The file is `{companyId}/exports/{userId}/{exportId}.csv`, and the export id is `{listKey}.{random}`. `api+/table.export.$exportId.ts` builds the key from the session, so a user reaches their own exports only, and it requires the list's permission again. The notification links there. The general preview route still serves `temp-staging` under the company prefix, but no link names an export key any more. That route was outside this fix and is not changed. — The list key in the id lets the route check the permission with no second store; changing it names a file that does not exist. This replaces the decision "Who can open an export file".+- [x] **Review fix D: the export upload streams (R7)** — **Autonomous:** `compose` uploads a `ReadableStream` that downloads one part at a time. storage-js 2.117.2 sends a stream as a chunked body with `duplex: "half"`; a local HTTP server received the exact bytes. Supabase Storage itself was not exercised (no running stack). The export also stops after the page that passes 200 MB (`MAX_EXPORT_BYTES`). — A part holds at most 10,000 rows in memory.+- [x] **Review fix D: one notification per outcome (R10)** — **Autonomous:** `notifyTableJobUser` sends `notify` with an event id per run and outcome (`table-export:{id}:ready`, `:failed`, `:denied`). Inngest drops a second event with the same id for 24 hours, so a retried step does not notify twice.+- [x] **Review fix D: one bulk delete (C10, R8)** — **Autonomous:** `bulkDeleteByStatus` (`utils/bulk-delete.server.ts`) deletes 100 ids per request with the company and the allowed statuses in the DELETE itself and `.select("id")`. Deleted = the rows the database returned; skipped = the rest of the chunk. The purchase order statuses come from the enum filtered by `isPurchaseOrderBulkDeletable`. — One statement per chunk, and a row whose status changed after the selection stays.+- [x] **Review fix D: one answer shape for "every matching row" (C11)** — **Autonomous:** Every bulk route answers `{ success: true, background: true }` or `{ success: false, message }` (`BulkActionStart`) through `startAllMatchingBulkAction`. The three form routes add `data` and `error` (`bulkStartFormResponse`), because about 20 property panels type their fetcher with the items update action and read `error`. The tables use `useBulkFormAction`, `useBulkStartToast` and `bulkSelectionBody` / `appendBulkSelection`. The bulk action metadata (`BULK_ACTIONS`) is in the pure `utils/table-jobs.ts`; what each action does stays in `table-jobs.server.ts`.+- [x] **Review fix D: the handler interface stays as it is (C9)** — **Autonomous:** `canReadList` and `canRunBulkAction` stay two methods. The shared parts moved to `packages/jobs/src/table-jobs/` (`paging.ts`, `lock.ts`, `notify.ts`, `storage.ts`, `export-run.ts`, `bulk-run.ts`). — One `authorize(kind, payload)` method would hide the same two checks behind a union and delete no code.+- [x] **Review fix D: one notification target (C12)** — **Autonomous:** `notificationTarget` (`utils/notification-target.ts`) serves the topbar row and `api+/link.ts`. Three targets changed: Stock Transfer Assignment opens the stock transfer (the topbar opened a sales order of that id); an email link for Integration Sync opens the integration page (it opened the home page); an approval with no document type opens the purchase order in both. The job pages use the `…Details` routes. Jobs Projected Late keeps no topbar row (it had none), but its email link still opens the job.+- [x] **Review fix D: item bulk update reports partial work (R11, C13)** — **Autonomous:** `bulkUpdateItems` moved to `modules/items/bulk-actions.server.ts` (logger `items-bulk-actions`). It first reads the ids under the company, so the `itemCost` insert names only the company's items and an unknown id counts as skipped. If a chunk fails after others committed, the route answers the error with `done` and `failed`, and the toast says "Updated N. Could not update M: …".+- [x] **Review fix D: Edit Permissions re-checks the plan in the job** — **Autonomous:** `canRunBulkAction` also calls `companyHasFeature` for an action with a `feature` (`users.permissions` → `PERMISSIONS`), with the service-role client. The route keeps `requireFeature`.+- [x] **Review fix B: one loader helper (C3, B7)** — **Autonomous:** `loadListPage(request, list, { dataKey, bypassRls?, guard?, params?, firstPage?, onError? })` (`utils/list-registry/load.server.ts`) is the whole loader of a registered list. It runs `requirePermissions` with the list's permission, `guard` on every page, `fetchListPage`, and `firstPage` on page 1 only. A failed later page logs the error (`erp/list-registry`) and returns `listError: "Failed to load more rows"`. A failed page 1 throws the loader's old redirect with its flash (`onError`); without `onError` it shows no rows, as before. Every bare `redirect(...)` in a converted loader is now thrown. A loader that does not fit calls `fetchListPage` and returns `listErrorPage(dataKey)`.+- [x] **Review fix B: one paging constant per list (C4, J4)** — **Autonomous:** `X_PAGING: Paging = { defaultSorts, idColumn? }` replaces the 118 `X_DEFAULT_SORTS` constants. `setGenericQueryFilters(query, args, X_PAGING)`, `toPage(rows, { limit, sorts }, X_PAGING)` and the registry entry read it. The two planning constants keep their names (`PURCHASING_PLANNING_DEFAULT_SORTS`, `PRODUCTION_PLANNING_DEFAULT_SORTS`): wave C owns their routes. The price list's paging names `itemId`, but its item query breaks ties on the item's own `id` (the same value), so the service passes only `PRICE_LIST_PAGING.defaultSorts`.+- [x] **Review fix B: the query context and `searchList` (C2, J2, S2)** — **Autonomous:** `fetchListPage` parses `getGenericQueryFilters` once and calls `query(client, companyId, { params, limit, cursor, sorts, filters, companyGroupId? })`. `searchList({ key, permission, paging, service, params })` builds the common entry: the service gets `{ search, ...params, limit, cursor, sorts, filters }`. A `params` entry names a URL param or reads one (`(params) => …`). 94 of 110 entries use it. The dimension and intercompany lists read the group with `resolveCompanyGroupId`: a loader passes the group from `requirePermissions`; a background job has none, so the list reads it once per page, as before. The group is an optional 6th argument, so `fetchListPage` stays compatible with the jobs.+- [x] **Review fix B: a missing sort column ends the list (R1)** — **Autonomous:** `toPage` no longer throws in development. In every environment, if the last row has no value for a sort column or the id column, it returns `nextCursor: null` and logs a warning (`erp/cursor`). Fixed assets now select `createdAt` and `updatedAt`. `test/list-select-columns.test.ts` also checks that each listed `*_LIST_COLUMNS` holds the sort and id columns of its paging.+- [x] **Review fix B: cursor or offset (R2)** — **Autonomous:** `setGenericQueryFilters` pages by cursor when `args.cursor !== undefined`, not when the key exists.+- [x] **Review fix B: a cursor names its order (R4)** — **Autonomous:** A cursor stores `keys`, each keyset column with its direction (`createdAt:desc`). If the keys differ from the request's order, the query adds a filter that no row matches (`and(id.is.null,id.not.is.null)`). The list then ends instead of restarting at page 1. A cursor without `keys` does not decode.+- [x] **Review fix B: offset tokens (S3)** — **Autonomous:** Printing jobs and the audit log use `encodeOffsetToken` / `decodeOffsetToken`, not a `Cursor` with an offset in `id`. A failed later page of either returns `listError`.+- [x] **Review fix B: no cursor in MCP (R3)** — **Autonomous:** `getAccountLedger` (MCP) pages by `offset` only. The 4 ledger drawers call `getAccountLedgerPage` (`accounting.server.ts`), which reads `getAccountLedgerLines` (no `@mcp` tag) and replaced `getConsolidatedAccountLedger`. `getAssemblyInstructions` (MCP) takes its old flat args with `offset?` again and ends with `query = setGenericQueryFilters(…); return query;`; with only `limit` it reads from offset 0. The list reads `getAssemblyInstructionsPage` (no `@mcp` tag). Typing the MCP args as `GenericQueryFilters & {…}` was rejected: the generator then publishes them nested under `args`, a contract change.+- [x] **Review fix B: sync operations (R17)** — **Autonomous:** `getSyncOperations` counts on the first page only (no `after`, offset 0). It quotes the cursor values with the escape of `cursor.ts`, copied into ee because ee cannot import the app.+- [x] **Review fix C: per-row extras come with each page (C1)** — **Autonomous:** `loadListPage` takes `mapRows(rows, context)`, which runs on every page after a load without an error. Jobs (batches and the tracked entity), Suppliers (report contacts), Tracked Entities (shelf-life policy) and Workflows (published version number, last run) put the value on the row, and their tables read it from the row. `onPage` and every "merge later pages" state are gone; `InfiniteOptions.onPage` is removed. The Jobs tracked-entity lookup moved from the browser to the loader (the loader's client, filtered by `companyId`). — One page carries its own values, so a revalidation re-read of the loaded pages refreshes them too.+- [x] **Review fix C: the planning grids own their rows (C1, B4, B5)** — **Autonomous:** The planning loaders attach each item's actions to its row (`withPlanningActions`, `planning-action-scope.ts`), and to the linked drawer row. The table calls `useInfiniteRows` with `ignoreParams: [PLANNING_DRAWER_PARAM]` and passes it as `infiniteRows`. The drawer rows add the linked row only when it is not loaded, and the actions are read from those rows, so a loaded drawer row is counted once (production and purchasing alike). The constants are now `PURCHASING_PLANNING_PAGING` and `PRODUCTION_PLANNING_PAGING`. A failed later page returns `listErrorPage("items")`; a failed page 1 now throws its redirect (it was a bare `redirect(...)`). This replaces the Review fix B note that the two planning constants keep their names.+- [x] **Review fix C: Documents keeps the user's changes, not the rows (B3)** — **Autonomous:** `DocumentsTable` runs `useInfiniteRows` and lays the user's star and label changes over every loaded row with the Table's edit overlay (`applyRowEdits`, `rowEdits.ts`). A change is pending (never dropped) until its write ends; it then takes a tick and the table revalidates, so a load that starts after the write drops it. The "Starred" view hides a row the overlay unstars. This replaces the decision "Optimistic document rows (Task 12h)". The loader uses `loadListPage` with `mapRows` for the download tokens.+- [x] **Review fix C: Sync Activity pages from its API route (B6)** — **Autonomous:** `SyncActivity` uses `useInfiniteRows` with `pageUrl: path.to.api.integrationSyncActivity(id, status)` and `ignoreParams: ["tab"]`. The API route reads one page (no `?limit=`) and returns `{ operations, nextCursor }` or `listErrorPage`. Each row carries its `reference` (the document number and the Carbon row id, `withSyncOperationReferences`), which replaces the page-level `readableIds` map. A revalidation re-reads at most 20 pages, as every list.+- [x] **Review fix C: single-load lists read exactly 1,000 rows (R5)** — **Autonomous:** `SINGLE_LOAD_LIMIT` (`utils/pagination.ts`) with offset mode, `{ limit, offset: 0 }` → `.range(0, 999)`. A list with search or filters returns `isTruncated` when it gets 1,000 rows, and `<Table isTruncated>` shows "Showing the first 1,000 rows. Search or filter to see the rest." in a row under the rows (desktop) or under the list (phones), where "Loading more rows" shows on an infinite list (`RowLimitNote`): groups, partners, the customer and supplier accounts, the storage unit roots and the customer portal. Sales rules, storage rules, the new serial number form and a training's assignments use offset mode with no note: the first three have no search or filter, and the assignments page searches only the rows it loaded, so the note would be false. `getTrainingAssignmentStatus` (MCP) takes `offset` again.+- [x] **Review fix C: the customer portal's lookups are bounded (R16)** — **Autonomous:** The thumbnails download 8 at a time (`async.map`). `getJobOperationAttachments` sends 100 operation ids per request, 8 requests at a time, and logs a failed request; the page shows without those attachments, as before.+- [x] **Review fix C: the ERP tests import no list registry through a service** — **Autonomous:** `listErrorPage` and `LOAD_MORE_ERROR` moved to `utils/list-registry/list-error.ts`, which imports nothing; `load.server.ts` re-exports them. `accounting.server.ts` imported `load.server.ts`, which loads the registry and every module's service, and through them a Lingui `msg` macro (`@carbon/onboarding`) that vitest does not compile: `lease-run-posting.test.ts` failed to load.+- [x] **Review fix C: five tables keep their indentation** — **Autonomous:** `PricingRulesTable`, `SalesRFQsTable`, `ContractsTable`, `ReturnReasonsTable` and `CustomerTypesTable` read their props in the body (`memo((props) => { const { … } = props;`), so the change is the new prop and the `infinite` block only.++## Risks++- A list without a unique `id` column needs its own tie-breaker. The plan lists every such list before conversion.+- A sortable column that is not in the list's select ends the list after the page: `toPage` logs a warning. The plan checks each list.+- Background jobs share the ERP containers with web requests. Many companies with big jobs at once can slow every user. Accepted for now; a separate worker container fixes it (`TODO(scale)`).+- Each of the 15 bulk actions needs its per-row checks on the server. A check that stays only in the browser lets the job act on rows the user could not act on before.+- Big exports show plain values, so they differ from small exports (for example `1250.5` instead of `$1,250.50`).++## Changelog++- 2026-10-13: First draft, written after the design interview.+- 2026-10-13: Replaced the 5,000-row browser cap with a 1,000-row split: browser below, Inngest job above. Footer totals stay as today.+- 2026-10-13: Spec approved. Added Autonomous Decisions from the plan research.+- 2026-10-13: Review fixes A–D recorded. Corrected the Documents decision, marked the replaced decisions, and updated sections 3, 7, 8, 11 and the Design Decisions for job steps, the 2,000-row release limit and per-user export files. Added "Verification status".diff --git a/.claude/rules/realtime-system.md b/.claude/rules/realtime-system.mdindex 3a3f00574d..8dfd252832 100644--- a/.claude/rules/realtime-system.md+++ b/.claude/rules/realtime-system.md@@ -7,6 +7,7 @@ paths:- "packages/database/src/event-system/functions/log_*.sql"- "apps/*/app/components/RealtimeDataProvider.tsx"- "apps/*/app/stores/**"+ - "apps/erp/app/components/Table/useInfiniteRows.ts"---# Realtime: broadcast topics, route declarations, live lists@@ -106,6 +107,20 @@ the navigation that follows a save restarts that navigation.- A table missing from `attachments.ts`: add `broadcast_table_changes` to itsentry, `pnpm db:migrate`, then `authz migration <name>`.+**Infinite-scroll lists.** A list loader returns page 1 only (100 rows). The+pages after it come from `useInfiniteRows`+(`apps/erp/app/components/Table/useInfiniteRows.ts`). When a revalidation gives+the same list (the same reset key, see `table-infinite-scroll.md`) a new page 1, the hook fetches the loaded pages again, in+order and with fresh cursors. Then it swaps them in at once, so edits, new rows+and deleted rows show in place and the scroll position stays. It keeps at most+20 pages (`MAX_REFRESH_PAGES`, 2,000 rows), and the cursor continues after the+last one. Revalidations that arrive during a refresh wait for one more refresh,+not one each. A `loadMore` during a refresh waits and runs when it ends. So a+list page needs only its table name in `handle.realtime`.+Do not add `useRealtime(table, "id=in.(…)")` with the loaded ids to a list+table. The plain table name already follows every row of the company, and an+id list names page 1 only.+| For | Use ||---|---|| A component that is not a route | the app's `useRealtime(table, filter?)`. An `id=eq.` / `id=in.()` filter narrows it, and so does the same on a `<name>Id` column (`quoteLineId=eq.…`); a filter on any other column wakes on every change to the table |diff --git a/.claude/rules/table-csv-export.md b/.claude/rules/table-csv-export.mdindex f3d60334e0..88baa535ad 100644--- a/.claude/rules/table-csv-export.md+++ b/.claude/rules/table-csv-export.md@@ -3,6 +3,11 @@ description: How the shared ERP data table exports its rows to CSV (the Downloadpaths:- "apps/erp/app/components/Table/**"- "apps/erp/app/modules/**/ui/**"+ - "apps/erp/app/routes/api+/table.export.ts"+ - "apps/erp/app/routes/api+/table.export.$exportId.ts"+ - "apps/erp/app/utils/table-jobs*.ts"+ - "packages/jobs/src/table-jobs/**"+ - "packages/jobs/src/inngest/functions/tasks/table-export.ts"---# Table CSV export (ERP)@@ -45,8 +50,11 @@ once by `buildColumnMaps(columns, translateLabel)` in(`useSavedViews()`) so the export mirrors what the user currently sees.`TableHeader` (`apps/erp/app/components/Table/components/TableHeader.tsx`) always-renders `<Download data columnAccessors exportValues columnOrder columnVisibility />`-and passes `sortKeyToLabel` to `<Sort>`.+renders `<Download data columnAccessors exportValues columnOrder columnVisibility infinite />`+and passes `sortKeyToLabel` to `<Sort>`. `infinite` (`InfiniteExport`) is set+only on a table with the `infinite` prop. It carries the header `count`,+`hasMore`, the list's `listKey` and `loadAll(limit)` from `useInfiniteRows`.+The phone list's ⋯ menu runs the same `useCsvDownload` hook.## meta hooks (`types.ts`)@@ -114,6 +122,99 @@ optional, export/sort-related fields:`Map<id, name>` per store; falls back to the raw value if not found.- Renders nothing (and does nothing on click) when `data` is empty.+## Two export paths: browser and background job++An infinite list holds only the rows loaded so far. `useCsvDownload`+(`Download.tsx`) picks one of 2 paths on each click. `BROWSER_ROW_LIMIT` is+1,000 (`components/Table/infiniteRowsStore.ts`).++| Case (checked in this order) | Path |+|---|---|+| No `infinite`, or `hasMore` is false | The browser exports the table's own `data`. Inline edits stay in the file. |+| `listKey` is set and `count` is above 1,000 | The browser POSTs to the export route at once. |+| Else | `loadAll(1000)` loads pages in the browser. If rows remain and `listKey` is set, the browser POSTs to the export route. If rows remain and no `listKey` is set, it downloads the first 1,000 rows and shows "Exported the first 1,000 rows." |++**Browser path.** Every cell uses the on-screen value (`meta.exportValue`, the+id → name maps). The columns are the visible columns, as described above.++**Background path.** The browser POSTs `{ listKey, search, columns: [{ key,+label }] }` with `fetch`, not a fetcher: a fetcher action would revalidate the+list and re-read every loaded page. The steps:++1. `api+/table.export.ts` finds the list in the registry (`getListDefinition`).+ It runs `requirePermissions` with the list's permission and `role: "employee"`.+2. It makes the export id, `{listKey}.{random}` (`newTableExportId`,+ `utils/table-jobs.ts`).+3. It takes the company's export lock (`takeTableJobLock`,+ `packages/jobs/src/table-jobs/lock.ts`). The value is the export id.+ - If another export holds it, the route answers 409 with+ `tableJobBusyMessage`: "An export is already running for your company.+ Try again when it ends, at the latest in N minutes." N comes from the+ lock's TTL.+ - If Redis does not answer, the route starts the job anyway and logs a+ warning. Inngest's per-company concurrency still runs one export at a time.+4. It triggers `table-export` (`packages/jobs/src/inngest/functions/tasks/table-export.ts`,+ `concurrency: { key: "event.data.companyId", limit: 1 }`, `retries: 1`).+ If `trigger` fails, the route deletes the lock.+5. Step `check-permission`: the job reads the user's claims again+ (`canReadList`, `utils/table-jobs.server.ts`). If the user lost the list's+ permission, it notifies "Your export did not run" in-app and stops.+6. Steps `write-part-0`, `write-part-1`, …: each step extends the lock, then+ reads at most 20 pages of 500 rows (`TABLE_JOB_ROWS_PER_STEP`, 10,000,+ `table-jobs/paging.ts`) as the user (`getUserScopedClient`, `fetchListPage`).+ It writes them as one part file (`writeExportPart`, `table-jobs/export-run.ts`).+ Part 0 starts with the header row. The step returns the counts and the next+ cursor only.+7. The parts stop at the end of the list, at 100,000 rows (`MAX_EXPORT_ROWS`),+ or after the page that passes 200 MB (`MAX_EXPORT_BYTES`, `table-jobs/csv.ts`).+8. Step `compose` uploads one `ReadableStream` that downloads the parts one at+ a time (`composeExport`, `concatParts`). Only one part is in memory. Then+ it deletes the parts.+9. Step `notify` sends `NotificationEvent.TableExport`. The title says "first+ N rows" when the export stopped at a limit.+10. Step `release-lock` deletes the lock.++| File | Key (`table-jobs/storage.ts`, bucket `temp-staging`) |+|---|---|+| The export | `{companyId}/exports/{userId}/{exportId}.csv` (`tableExportStorageKey`) |+| One part | `{companyId}/exports/{userId}/{exportId}.parts/{n}.csv` (`tableExportPartKey`) |++**The lock.** One Redis key per company and job kind, value = the job id,+TTL one hour (`TABLE_JOB_LOCK_TTL_SECONDS`). Take, release and extend are each+one Lua script: `SET NX EX` that returns the TTL on refusal,+compare-and-delete, compare-and-expire. A job deletes or extends only a lock+that still holds its own id. `onFailure` also releases it and deletes the+parts.++**The download.** The notification row links to+`api+/table.export.$exportId.ts` (`path.to.api.tableExport` + `/{exportId}`,+`notificationTarget`). The route reads the list key from the export id and+runs `requirePermissions` with that list's permission again. It builds the+storage key from the session's company and user, so a user only reaches their+own exports. A missing file answers 404 "Exports are kept for 7 days". A failed+or refused export has documentId `failed:{exportId}`, notifies in-app only and+has no link.++**One notification per outcome.** `notifyTableJobUser` (`table-jobs/notify.ts`)+sends `notify` with an Inngest event id: `table-export:{exportId}:ready`,+`:failed` or `:denied`. Inngest drops a second event with the same id for+24 hours, so a retried step does not notify twice.++The background file holds plain database values (`formatExportValue`,+`packages/jobs/src/table-jobs/csv.ts`): `2026-10-13`, `1250.5`, the stored+status. The on-screen formatters run in the browser only. An array cell joins+with `; `, an object cell becomes JSON, and a `customFields->>{id}` column reads+the custom field. The header row holds the translated labels in display order.++The daily cleanup (`prune-staged-raw-models`, `scheduled/cleanup.ts`) deletes+`temp-staging` objects after 7 days (`STAGED_RAW_TTL_DAYS`), so an export link+expires after 7 days. It also removes a part file that a job could not delete.++The job page size is 500, not 1,000 (`TABLE_JOB_PAGE_SIZE`). The list query+asks for `limit + 1` rows, and PostgREST returns at most 1,000 (`max_rows`).+With a limit of 1,000, `toPage` sees no next page and the export stops at+row 1,000.+The stores are live-list hooks (`useLiveList`, `@carbon/query`) consumed as tuples,e.g. `const [items] = useItems();`; each element exposes at least `{ id, name }`.@@ -131,8 +232,17 @@ Just render `<Table>` — the button comes for free. No `enableExport`-style pro- The underscore restriction is enforced in `buildColumnMaps` (`utils.ts`), not in`Download.tsx` — a `_` in any accessorKey crashes the table (it's the first mapbuilt) before export is even possible.-- Export uses `data` currently passed to the table (the current page/result set),- not a full server-side dump.+- A list without a `listKey` (a loader that calls `toPage` itself, with no+ registry entry) never reaches the background path. Its export stops at+ 1,000 rows.+- A column that only the loader adds per page (`loadListPage`'s `mapRows`,+ not a column of the registry query) needs the list's `exportRows`, or it is+ blank in a background export. The job asks for export rows+ (`fetchListPage` with `forExport`), and the ERP handler runs `exportRows`:+ the loader's lookup, then the table's shared export values under the+ column keys. Jobs (Batches, Tracking), Suppliers (contacts, addresses) and+ Workflows (Last Run) have one. Any other `meta.exportValue` is not run:+ the background file holds the raw value.- The `name` substitution is keyed on the literal accessor strings `itemId` /`supplierId` / `employeeId` / `customerId` **and only runs when the column has no`meta.exportValue`**; a column holding one of those ids under a differentdiff --git a/.claude/rules/table-infinite-scroll.md b/.claude/rules/table-infinite-scroll.mdnew file mode 100644index 0000000000..481fcb5fde--- /dev/null+++ b/.claude/rules/table-infinite-scroll.md@@ -0,0 +1,328 @@+---+description: Cursor paging and infinite scroll for ERP list tables — the loader recipe, toPage, fetchListPage, the list registry, sort rules and the 1,000-row thresholds.+paths:+ - "apps/erp/app/components/Table/**"+ - "apps/erp/app/utils/query.ts"+ - "apps/erp/app/utils/cursor.ts"+ - "apps/erp/app/utils/list-registry/**"+ - "apps/erp/app/routes/x+/**"+ - "apps/erp/app/routes/api+/table.*"+ - "apps/erp/app/modules/**/ui/**/*Table.tsx"+---++# Cursor paging and infinite scroll++Every paged ERP list loads 100 rows (`PAGE_SIZE`, `utils/pagination.ts`). It+loads the next 100 when a sentinel after the rows comes within 600px of the+end of the scroll element (`useInfiniteScroll`, an IntersectionObserver with+`PREFETCH_DISTANCE`, `components/Table/infiniteRowsStore.ts`). There is no+pager, no `?offset=` and no `?limit=` in a list URL. Design and decisions:+`.ai/specs/2026-10-13-infinite-scroll-tables.md`.++## How a page loads++1. The route loader returns page 1: `{ <rows>, count, nextCursor }`.+2. `useInfiniteRows` (`components/Table/useInfiniteRows.ts`) calls+ `fetcher.load` on `pageUrl` plus `after=<nextCursor>`. The default+ `pageUrl` is `useFormAction()`, not `location.pathname`, so a drawer route+ does not catch the request.+3. It appends the page's rows, one request at a time, until `nextCursor` is+ null. It drops a row whose id (`idColumn`, default `id`) is already loaded.+4. A new reset key drops the loaded pages, the scroll offset and an+ uncontrolled selection. The reset key is the URL search without `after` and without+ `ignoreParams` (`getSearchKey`, `getResetKey`). So a filter, sort, search or+ saved view resets the list, and a drawer param in `ignoreParams` does not.+5. A revalidation re-reads the loaded pages, up to 20 (see `realtime-system.md`).+ A `loadMore` during that refresh waits and runs after it.+6. Back (`POP`) restores the loaded rows and the scroll offset from memory.+ The memory key is the company id, `dataKey` and the page URL key.++The cursor (`utils/cursor.ts`) is base64url JSON of the last row's sort values,+its id and `keys`, the order it was cut for (`["createdAt:desc"]`).+`setGenericQueryFilters` (`utils/query.ts`) adds a keyset filter with `.or(…)`,+the id tie-break order and `.limit(limit + 1)`. The extra row tells `toPage`+that a next page exists. NULLs sort last ascending and first descending, and+the keyset filter follows that rule. A cursor whose `keys` differ from the+request's order gives an empty page, so the list ends rather than restarting.+A list that pages by offset (printing jobs, the audit log) uses+`encodeOffsetToken` / `decodeOffsetToken`, not a cursor.++## Loader recipe (a registered list)++```ts+// routes/x+/sales+/customers.tsx+export async function loader({ request }: LoaderFunctionArgs) {+ return loadListPage(request, customersList, {+ dataKey: "customers",+ bypassRls: true, // only if the loader passed it before+ firstPage: async ({ client, companyId }) => ({+ tags: (await getTagsList(client, companyId, "customer")).data ?? []+ }),+ onError: { redirectTo: path.to.sales, message: "Failed to fetch customers" }+ });+}+```++`loadListPage` (`utils/list-registry/load.server.ts`) runs `requirePermissions`+with the list's permission, `guard` (every page), `fetchListPage` with the+user's company group, `firstPage` (page 1 only, in parallel) and `mapRows`+(every page, after it). It returns+`{ [dataKey]: rows, count, nextCursor, ...extras }`. `params` replaces the URL+search the query reads. On an error:++- A later page logs it and returns `{ [dataKey]: [], nextCursor: null, listError }`+ (`InfiniteListError`). The Table shows "Couldn't load more rows" with Retry.+- Page 1 throws `redirect(onError.redirectTo)` with an error flash, or shows no+ rows without `onError`.++A loader that does more (an early return, a flash without a redirect) calls+`fetchListPage` itself and returns `listErrorPage(dataKey)` for a failed later page+(`utils/list-registry/list-error.ts`: no imports, so a service module can use it+without loading the registry).++The table passes `infinite` (`InfiniteOptions`, `components/Table/types.ts`)+to `<Table>`:++```tsx+infinite={{ dataKey: "customers", nextCursor, listKey: "customers" }}+```++| Option | Meaning |+|---|---|+| `dataKey` | The key of the rows array in the loader data. |+| `nextCursor` | The loader's cursor. Null when page 1 is the whole list. |+| `listKey` | The registry key. Without it, export and "select all" stop at 1,000 rows. |+| `ignoreParams` | URL params that do not define the list. A change of one keeps the loaded pages. The planning grids pass `[PLANNING_DRAWER_PARAM]`, Sync Activity `["tab"]`. |+| `idColumn` | The unique id column when it is not `id`. It de-duplicates and keys the rows. |+| `pageUrl` | The URL that serves the later pages, when it is an `api+` loader (Sync Activity: `path.to.api.integrationSyncActivity`). Same response shape. |++- Values from another table (a lookup the list's view lacks) go on each row+ in the loader, with `loadListPage`'s `mapRows`, so every page carries its+ own and the table keeps no merge state (Jobs, Suppliers, Workflows).+ - Put the lookup in the list's registry file (`withJobListExtras`) and pass+ it as `mapRows`.+ - If a column exports one of those values, give the registry entry an+ `exportRows`: the same lookup, then `withExportValues` with the table's+ shared export map (`JOB_LIST_EXPORT_VALUES`). The background CSV export+ runs no column code, so without it the column is blank past 1,000 rows.+- 🛑 Pass the loader's `data` array to `<Table infinite>`, or a memoized one.+ `useInfiniteRows` reads a new array as a revalidation and re-reads every+ loaded page. A copy built in the render body (`data.map(…)`) re-reads them+ on every render. `test/infinite-table-data-identity.test.ts` checks this, but+ its regex reads only the `<Table …>` elements with no `>` inside: most+ tables slip past it (open, see the 2026-10-14 review).+- Column widths: only the rows in view are rendered (`useVirtualRows`, 10+ rows of overscan), so table layout alone would narrow and widen a column as+ rows scroll by. `useGrowOnlyColumnWidths` holds each column at its widest so+ far as the header's `min-width` (capped at `30dvw`, a body cell's maximum).+ The widths start over on a new list (`resetKey`), a new column set, or a new+ container width. A column still widens once when a wider cell first shows.+ Never lock widths with `table-layout: fixed`: a width measured at one bad+ moment stays wrong, and late content (names from a store) gets cut off.+- A parent that needs every loaded row (the planning grids, Documents) calls+ `useInfiniteRows` itself and passes the result as `<Table infiniteRows={…}>`.+ The Table then runs its own hook with infinite scroll off. A list that is not+ a `<Table>` (Sync Activity) calls `useInfiniteRows` and `useInfiniteScroll`+ itself.++## The service function++```ts+export const SALES_ORDERS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+ // idColumn: "…" // when `id` is not unique+};++/** @mcp read */+export async function getSalesOrders(client, companyId, args: GenericQueryFilters & { … }) {+ let query = client+ .from("salesOrders")+ .select(SALES_ORDERS_LIST_COLUMNS, { count: args.cursor ? undefined : LIST_COUNT })+ .eq("companyId", companyId);+ // filters, search …+ query = setGenericQueryFilters(query, args, SALES_ORDERS_PAGING);+ return query;+}+```++One `X_PAGING` per list. The service passes it to `setGenericQueryFilters`, a+loader without a registry entry to `toPage(rows, { limit, sorts }, X_PAGING)`,+and the registry entry spreads it.++🛑 Put the `*_PAGING` constant ABOVE the doc block. A constant between+`/** @mcp read */` and its function takes the doc block, and the function stops+being an MCP tool with no error (see `.ai/lessons.md`).++🛑 Never put `cursor` in an `@mcp` function's own args type. Type the args as+`GenericQueryFilters & { … }` (the generator publishes `limit` + `offset`), or+give the loader a function with no `@mcp` tag (`getAccountLedgerLines`).++Rules for the query:++| Rule | Why |+|---|---|+| Ask for the count only when `args.cursor` is null | Later pages need no count. `fetchListPage` returns 0 for them. |+| Every sortable column, the default sorts and the id column are in the select | `toPage` reads the cursor values from the row. A missing one ends the list after the page and logs a warning. |+| Never put an `.order()` before `setGenericQueryFilters` | The cursor follows only the sorts that `setGenericQueryFilters` applies. A fixed first order breaks it. |+| A default sort on a `foreignTable` orders the embedded rows only | `resolveSorts` keeps it out of the keyset. |+| A list with no unique `id` names `idColumn` in its `X_PAGING` | Examples: contractors (`supplierContactId`), custom field tables (`table`), the price list (`itemId`). |+| `args.cursor !== undefined` means cursor paging | Without it, `limit` + `offset` page exactly (MCP, v1 API). |++## Sortable columns++`isServerSortable` (`components/Table/utils.ts`) gates the header sort menu and+the toolbar Sort picker:++- A sort key with a `.` (another table's column) is off. `resolveSorts` also drops it on the server.+- Set `enableSorting: false` on a column the list's view does not have: a+ value the loader computes per page, an embedded record, a joined name.+ Examples: Jobs `orderQuantity`, Batches `memberCount`, the price list columns.++## The list registry++`utils/list-registry/index.server.ts` holds `LIST_REGISTRY`, `getListDefinition`,+`fetchListPage` and `searchList`. Each module keeps its entries in its own file+(`sales.server.ts`, …), merged by the index. Most entries use `searchList`:++```ts+export const salesOrdersList = searchList({+ key: "sales-orders",+ permission: { view: "sales" }, // the loader's check, without bypassRls+ paging: SALES_ORDERS_PAGING,+ service: getSalesOrders, // gets { search, ...params, limit, cursor, sorts, filters }+ params: { status: "status", customerId: "customerId" } // or (params) => …+});+```++A list with another service shape writes its own entry:+`{ key, permission, ...X_PAGING, query }`. `query(client, companyId, context)`+gets `{ params, limit, cursor, sorts, filters, companyGroupId? }`, parsed once+by `fetchListPage`. A group-scoped list reads the group with+`resolveCompanyGroupId(client, companyId, context)`: the loader passes it, a+background job does not.++- The loader and the background jobs (export, bulk action) run the same+ `query`. So the query reads everything from `params` and the company. It+ cannot read route params or the user's default location.+- If the list needs either of those, give it no registry entry. The loader+ calls the service, then `toPage(rows, { limit, sorts }, X_PAGING)`.+ Examples: kanbans, stock transfers, quantities, the job sub-lists, the+ planning lists. Such a list has no `listKey`.+- A background job reads as the requesting user (`getUserScopedClient`) and+ checks the list's permission on the user's claims+ (`utils/table-jobs.server.ts`).++## Single-load lists++A list that cannot page passes `{ limit: SINGLE_LOAD_LIMIT, offset: 0 }`+(`utils/pagination.ts`, 1,000) and no `infinite`. Offset mode reads exactly+`.range(0, 999)`: with `cursor: null` the query asks for 1,001 rows, and+PostgREST's `max_rows` cuts that to 1,000, so a full list looked complete.+Examples: groups (a tree), partners (one row per ability, so `id` is not+unique), the storage unit roots (a tree), storage rules, sales rules, the+customer and supplier account lists, the customer portal share page.++When a list with search or filters gets exactly 1,000 rows, the loader returns+`isTruncated` and the table passes it to `<Table isTruncated>`, which shows+"Showing the first 1,000 rows. Search or filter to see the rest." under the+rows (`RowLimitNote`). A table without `infinite` holds all its rows, so it+shows no "loaded rows" footer label.++## Thresholds++| Value | Where | Meaning |+|---|---|---|+| 100 | `PAGE_SIZE` | Rows per page |+| 600px | `PREFETCH_DISTANCE` | Start the next page this close to the end |+| 20 pages | `MAX_REFRESH_PAGES` | At most 2,000 rows stay loaded after a revalidation, and in the Back memory |+| 1,000 | `BROWSER_ROW_LIMIT` | The browser loads at most this many rows for "select all" and CSV export |+| 1,000 | `EXACT_COUNT_LIMIT` | Below it the header count is exact ("245 rows"); from it "about N rows" (`LIST_COUNT` is an estimate there) |+| 1,000 | `SINGLE_LOAD_LIMIT` | Rows a single-load list reads |+| 500 | `TABLE_JOB_PAGE_SIZE` (`packages/jobs/src/table-jobs/paging.ts`) | Rows per query in a job. `limit + 1` must stay at or below PostgREST `max_rows` (1,000) |+| 10,000 | `TABLE_JOB_ROWS_PER_STEP` | Rows one job step reads (20 pages). One step is one HTTP request, and the load balancer cuts a request at 600 s |+| 100,000 | `MAX_EXPORT_ROWS`, `MAX_BULK_ROWS` | The most rows one background job reads |+| 200 MB | `MAX_EXPORT_BYTES` | The export stops after the page that passes it |+| 2,000 | `ALL_MATCHING_RELEASE_LIMIT` (`utils/table-jobs.ts`) | The most rows Jobs Release and Batches Release act on in the background |++"Select all" (`Table.tsx`, `SelectAllMatchingBar`): when every loaded row is+selected and more rows exist, the bar offers the rest.++| Matching rows | What "select all" does |+|---|---|+| 1,000 or fewer | The browser loads them (`loadAll(1000)`) and selects them. |+| More than 1,000, with `listKey` | The selection becomes "all matching" (`AllMatchingSelection`: list key, URL search, count). A bulk action gets it in `renderActions(rows, { allMatching })`. |+| More than 1,000, no `listKey` | The bar offers "Select the first 1,000 rows". |++`useSelectAllMatching` (`components/Table/components/SelectAllMatching.tsx`)+derives the "all matching" state. A new selection or a new reset key ends it.++CSV export follows the same split: see `table-csv-export.md`.++## The background bulk action++A bulk route that gets `allMatching` in place of ids calls+`startAllMatchingBulkAction` (`utils/table-jobs.server.ts`). It answers+`{ success: true, background: true }` or `{ success: false, message }`+(`BulkActionStart`). The steps:++1. `startTableBulkAction` checks that the action serves the list+ (`BULK_ACTIONS`, `utils/table-jobs.ts`) and the user's permission+ (`canRunBulkAction`, also the plan `feature` of the action).+2. If the action has `maxRows`, it counts the matching rows and refuses past+ the limit (`rowLimitRefusal`). Jobs Release and Batches Release have a+ limit of 2,000. The menu item shows "Filter the list to 2,000 rows or fewer"+ (`useAllMatchingLimitLabel`).+3. It takes the company's bulk lock (`takeTableJobLock("bulk", …)`, the same+ Lua lock as the export). A busy lock answers the remaining time.+4. It triggers `table-bulk-action`+ (`packages/jobs/src/inngest/functions/tasks/table-bulk-action.ts`,+ `retries: 0`, one run per company at a time).+5. Steps `collect-ids-{n}`: each reads at most 10,000 rows and stores their+ ids as one file in `temp-staging`+ (`{companyId}/bulk-actions/{bulkActionId}/{n}.json`, `tableBulkIdsKey`).+ The job also stops at `maxRows`. A run for selected rows (`ids` in the+ event) has one step `store-selected-ids` instead, and reads no list pages.+6. Steps per slice: each reads `idsPerStep` ids (default 1,000; Jobs Release+ 25, Batches Release 10, Batches Dissolve 100) and runs the action 100 ids+ per call (`BULK_CHUNK_SIZE`). Each call gets the `carry` the call before+ it returned and returns the next one. Jobs Release carries the PO each+ supplier went on, so a later slice adds to the PO an earlier slice made+ (`bulkReleaseStartingPurchaseOrders`) instead of refusing the job.+7. Step `notify` sends `NotificationEvent.TableBulkAction` with the counts+ in the title: done, skipped, failed. Its event id+ (`table-bulk-action:{id}:done`) stops a second send on a retry.+8. Steps `remove-ids` and `release-lock` delete the id files and the lock.++A step returns counts, cursors and the small `carry` only. The function adds+them up outside the steps. The browser side uses `appendBulkSelection` / `bulkSelectionBody`+(`utils/bulk-selection.ts`), `useBulkFormAction` and `useBulkStartToast`+(`hooks/useBulkAction.ts`).++**Selected rows that do not fit one request.** Jobs Release and Batches+Release act on every selected row in the request itself only up to the+action's `idsPerStep` (25 jobs, 10 batches; `fitsOneRequest`). A bigger+selection goes to the same background job with its ids+(`startSelectedBulkAction`), because each release runs MRP and the load+balancer cuts a request at 600 s.++## Known limits++- `TODO(scale)` (`packages/jobs/src/inngest/functions/tasks/table-export.ts`):+ the table jobs run in the ERP containers (`api+/inngest.ts`) and share CPU+ with web requests. One job per company runs at a time, but many companies+ can run one each. A separate worker service removes this risk.+- Footer totals (`meta.renderTotal`) add up the loaded rows only. The footer+ says "Total of N loaded rows".+- 49 services put the raw search text into `.or()`. This is independent of+ paging and is not fixed here.++## Tests++`utils/cursor.test.ts` (encode, decode, keys, offset tokens, keyset filter, `toPage`), `utils/query.test.ts`,+`utils/list-registry/registry.test.ts` (every module file is merged),+`components/Table/infiniteRowsStore.test.ts`, `utils/table-jobs.test.ts` and+`packages/jobs/src/table-jobs/*.test.ts`, `apps/erp/test/infinite-table-data-identity.test.ts`+(no render-body copy of `data`), `apps/erp/test/list-export-values.test.ts` (each+`mapRows` list has `exportRows`). `apps/erp/test/list-select-columns.test.ts`+fails when a table's `accessorKey`, or its paging's sort or id column, is+missing from its `*_LIST_COLUMNS`.diff --git a/AGENTS.md b/AGENTS.mdindex cad1f04292..f46d6c1e85 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -94,6 +94,7 @@ IMPORTANT: Before any research or coding, match the task to this table. A single| **UI & Forms** | || Building forms (ValidatedForm + zod) | `.claude/rules/conventions-forms.md` + `packages/form/AGENTS.md` || UI components and conventions | `.claude/rules/conventions-ui.md` + `packages/react/AGENTS.md` |+| List tables: cursor paging, infinite scroll, list registry | `.claude/rules/table-infinite-scroll.md` + `.claude/rules/table-csv-export.md` || i18n / translations (Lingui) | `.claude/rules/i18n-lingui-system.md` + `packages/locale/AGENTS.md` || Flash messages and toasts | `.claude/rules/flash-system.md` || Document templates / customizer | `.claude/rules/document-template-customizer.md` |diff --git a/apps/erp/app/components/Grid/Grid.tsx b/apps/erp/app/components/Grid/Grid.tsxindex ce44d8cb3d..2a8051fbcf 100644--- a/apps/erp/app/components/Grid/Grid.tsx+++ b/apps/erp/app/components/Grid/Grid.tsx@@ -23,15 +23,13 @@ import {getCoreRowModel,useReactTable} from "@tanstack/react-table";-import type { Range } from "@tanstack/react-virtual";-import { defaultRangeExtractor, useVirtualizer } from "@tanstack/react-virtual";-import type { ReactNode } from "react";import { useCallback, useEffect, useRef, useState } from "react";import { LuCirclePlus } from "react-icons/lu";import type {EditableTableCellComponent,Position} from "~/components/Editable";+import { useVirtualRows } from "~/components/Table/useVirtualRows";import { Row } from "./components";import { getAccessorKey, updateNestedProperty } from "./utils";@@ -387,22 +385,9 @@ const Grid = <T extends object>({// The selected row stays rendered when it scrolls out of view: it holds the// keyboard focus and, mid-edit, the open editor. Dropping it would lose both.const selectedRow = selectedCell?.row;- const rangeExtractor = useCallback(- (range: Range) => {- const indexes = defaultRangeExtractor(range);- if (- selectedRow === undefined ||- selectedRow >= range.count ||- indexes.includes(selectedRow)- ) {- return indexes;- }- return [...indexes, selectedRow].sort((a, b) => a - b);- },- [selectedRow]- );+ const keepSelectedRow = useCallback(() => selectedRow, [selectedRow]);- const rowVirtualizer = useVirtualizer({+ const { virtualizer: rowVirtualizer, renderRows } = useVirtualRows({enabled: isVirtual,count: rows.length,getScrollElement: () => tableContainerRef.current,@@ -410,10 +395,10 @@ const Grid = <T extends object>({estimateSize: () => ESTIMATED_ROW_HEIGHT,overscan: OVERSCAN,scrollMargin: HEADER_HEIGHT,- rangeExtractor,+ keepIndex: keepSelectedRow,// The scroller is not measured until after the first render; without this// that render would draw no rows at all.- initialRect: { width: 0, height: maxHeight ?? 0 }+ initialHeight: maxHeight ?? 0});const renderRow = (row: (typeof rows)[number], virtualIndex?: number) => (@@ -441,27 +426,14 @@ const Grid = <T extends object>({// is not rendered, so the scrollbar and every row's position stay true.const renderVirtualRows = () => {const columnCount = table.getVisibleLeafColumns().length;- const spacer = (key: string, height: number) => (- <tr key={key} aria-hidden>- <td colSpan={columnCount} style={{ height, padding: 0 }} />- </tr>+ return renderRows(+ (index) => renderRow(rows[index]!, index),+ (key, height) => (+ <tr key={key} aria-hidden>+ <td colSpan={columnCount} style={{ height, padding: 0 }} />+ </tr>+ ));-- const rendered: ReactNode[] = [];- let offset = 0;- for (const item of rowVirtualizer.getVirtualItems()) {- const row = rows[item.index];- if (!row) continue;- const start = item.start - HEADER_HEIGHT;- if (start > offset) {- rendered.push(spacer(`before-${item.index}`, start - offset));- }- rendered.push(renderRow(row, item.index));- offset = item.end - HEADER_HEIGHT;- }- const totalSize = rowVirtualizer.getTotalSize();- if (totalSize > offset) rendered.push(spacer("after", totalSize - offset));- return rendered;};// In a virtualized grid "New" sits under the scroller, always in view, sodiff --git a/apps/erp/app/components/Layout/Topbar/Notifications.tsx b/apps/erp/app/components/Layout/Topbar/Notifications.tsxindex 69a40d95be..da9fe5ab03 100644--- a/apps/erp/app/components/Layout/Topbar/Notifications.tsx+++ b/apps/erp/app/components/Layout/Topbar/Notifications.tsx@@ -3,12 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source."use client";-import type { ApprovalDocumentType } from "@carbon/ee/approvals";-import {- NotificationEvent,- type RecurringInvoicingDocumentType,- renderInlineLinks-} from "@carbon/notifications";+import { NotificationEvent, renderInlineLinks } from "@carbon/notifications";import { useLoaderQuery } from "@carbon/query";import {Badge,@@ -37,6 +32,7 @@ import {LuCirclePlay,LuClipboardCheck,LuDollarSign,+ LuFileSpreadsheet,LuGitPullRequestArrow,LuGraduationCap,LuHammer,@@ -64,16 +60,13 @@ import { useNotifications, useUser } from "~/hooks";import { useRestoreBrowserNotifications } from "~/hooks/usePushSubscription";import { usePeople } from "~/stores";import type { Notification as NotificationRecord } from "~/types";-import { getRecordPath } from "~/utils/entity";+import {+ type NotificationDocumentType,+ notificationTarget+} from "~/utils/notification-target";import { path } from "~/utils/path";import { EnableBrowserNotifications } from "./EnableBrowserNotifications";-/** The approvable document of an Approval* event, or what a Recurring- * invoicing notification lists. */-type NotificationDocumentType =- | ApprovalDocumentType- | RecurringInvoicingDocumentType;-type OutstandingTraining = {trainingAssignmentId: string;trainingId: string;@@ -158,6 +151,7 @@ function TrainingItem({function Notification({icon,to,+ reloadDocument,description,body,createdAt,@@ -167,6 +161,9 @@ function Notification({}: {icon: React.ReactNode;to: string;+ // A resource route (a file download) needs a full page request, not a+ // client navigation.+ reloadDocument?: boolean;description: string;body?: string;createdAt: string;@@ -243,14 +240,16 @@ function Notification({className="flex items-between justify-between gap-x-4 cursor-pointer"onClick={() => {onClose();- navigate(to);+ if (reloadDocument) window.location.assign(to);+ else navigate(to);}}onKeyDown={(e) => {if (e.target !== e.currentTarget) return;if (e.key !== "Enter" && e.key !== " ") return;e.preventDefault();onClose();- navigate(to);+ if (reloadDocument) window.location.assign(to);+ else navigate(to);}}>{content}@@ -260,6 +259,7 @@ function Notification({className="flex items-between justify-between gap-x-4 "onClick={() => onClose()}to={to}+ reloadDocument={reloadDocument}>{content}</Link>@@ -279,6 +279,52 @@ function Notification({);}+/** The topbar icon of each event. An event without one has no row here+ * (Digest rows are `DigestNotification`). */+const NOTIFICATION_ICONS: Partial<Record<NotificationEvent, React.ReactNode>> =+ {+ [NotificationEvent.ApprovalApproved]: <LuClipboardCheck />,+ [NotificationEvent.ApprovalRejected]: <LuClipboardCheck />,+ [NotificationEvent.ApprovalRequested]: <LuClipboardCheck />,+ [NotificationEvent.ChangeNoticeStarted]: <LuGitPullRequestArrow />,+ [NotificationEvent.ChangeNoticeImplementation]: <LuGitPullRequestArrow />,+ [NotificationEvent.ChangeNoticeDone]: <LuGitPullRequestArrow />,+ [NotificationEvent.DigitalQuoteResponse]: <LuDollarSign />,+ [NotificationEvent.GaugeCalibrationExpired]: <LuCircleGauge />,+ [NotificationEvent.SalesRuleViolation]: <LuShieldAlert />,+ [NotificationEvent.IntegrationSync]: <LuRefreshCw />,+ [NotificationEvent.TableExport]: <LuFileSpreadsheet />,+ [NotificationEvent.TableBulkAction]: <LuListChecks />,+ [NotificationEvent.RecurringInvoicing]: <LuDollarSign />,+ [NotificationEvent.LeaseCriticalDate]: <LuCalendarClock />,+ [NotificationEvent.JobCompleted]: <LuHammer />,+ [NotificationEvent.JobAssignment]: <LuHammer />,+ [NotificationEvent.JobOperationAssignment]: <LuCirclePlay />,+ [NotificationEvent.JobOperationMessage]: <LuMessageSquare />,+ [NotificationEvent.MaintenanceDispatchCreated]: <LuWrench />,+ [NotificationEvent.MaintenanceDispatchAssignment]: <LuWrench />,+ [NotificationEvent.NonConformanceAssignment]: <LuShieldX />,+ [NotificationEvent.ProcedureAssignment]: <LuListChecks />,+ [NotificationEvent.QuoteExpired]: <LuCalendarX />,+ [NotificationEvent.PurchaseInvoiceAssignment]: <LuShoppingCart />,+ [NotificationEvent.PurchasingRfqAssignment]: <LuPackageSearch />,+ [NotificationEvent.PurchaseOrderAssignment]: <LuShoppingCart />,+ [NotificationEvent.QuoteAssignment]: <RiProgress4Line />,+ [NotificationEvent.RiskAssignment]: <LuShieldAlert />,+ [NotificationEvent.SalesRfqReady]: <RiProgress2Line />,+ [NotificationEvent.SalesRfqAssignment]: <RiProgress2Line />,+ [NotificationEvent.SalesOrderAssignment]: <RiProgress8Line />,+ [NotificationEvent.StockTransferAssignment]: <LuListChecks />,+ [NotificationEvent.PickingListAssignment]: <LuListChecks />,+ [NotificationEvent.SuggestionResponse]: <LuLightbulb />,+ [NotificationEvent.SupplierQuoteAssignment]: <LuDollarSign />,+ [NotificationEvent.SupplierQuoteResponse]: <LuMailCheck />,+ [NotificationEvent.TrainingAssignment]: <LuListChecks />,+ [NotificationEvent.TrainingReminder]: <LuListChecks />,+ [NotificationEvent.ResourceTrainingAssignment]: <LuGraduationCap />,+ [NotificationEvent.Workflow]: <LuGitPullRequestArrow />+ };+function GenericNotification({id,event,@@ -295,290 +341,18 @@ function GenericNotification({markMessageAsRead?: () => void;onClose: () => void;}) {- switch (event) {- case NotificationEvent.ApprovalApproved:- case NotificationEvent.ApprovalRejected:- case NotificationEvent.ApprovalRequested:- return (- <Notification- icon={<LuClipboardCheck />}- to={- documentType === "qualityDocument"- ? path.to.qualityDocument(id)- : documentType === "supplier"- ? path.to.supplier(id)- : documentType === "changeOrder"- ? path.to.changeNoticeDetails(id)- : path.to.purchaseOrderDetails(id)- }- {...props}- />- );- case NotificationEvent.ChangeNoticeStarted:- case NotificationEvent.ChangeNoticeImplementation:- case NotificationEvent.ChangeNoticeDone:- return (- <Notification- icon={<LuGitPullRequestArrow />}- to={path.to.changeNoticeDetails(id)}- {...props}- />- );- case NotificationEvent.DigitalQuoteResponse:- return (- <Notification- icon={<LuDollarSign />}- to={path.to.quoteDetails(id)}- {...props}- />- );- case NotificationEvent.GaugeCalibrationExpired:- return (- <Notification- icon={<LuCircleGauge />}- to={path.to.gauge(id)}- {...props}- />- );- case NotificationEvent.SalesRuleViolation: {- // Compound documentId: "<quote|salesOrder|salesInvoice>:<documentId>:<outcome>"- const [docType, docId] = id.split(":");- return (- <Notification- icon={<LuShieldAlert />}- to={- docType === "salesInvoice"- ? path.to.salesInvoiceDetails(docId ?? "")- : docType === "salesOrder"- ? path.to.salesOrderDetails(docId ?? "")- : path.to.quoteDetails(docId ?? "")- }- {...props}- />- );- }- case NotificationEvent.IntegrationSync:- // id is the provider id ("rillet", "xero", ...) — link to that- // integration's settings page, where the Sync Activity tab lives.- return (- <Notification- icon={<LuRefreshCw />}- to={path.to.integration(id)}- {...props}- />- );- case NotificationEvent.RecurringInvoicing:- // The description carries the digest's counts; id is only the first- // invoice, so land on the list it is about: the lease drafts waiting- // for the buyer, else the sales invoices that need review (see- // api+/link).- return (- <Notification- icon={<LuDollarSign />}- to={- documentType === "purchaseInvoice"- ? `${path.to.invoicingPurchasing}?filter=status:eq:Draft`- : `${path.to.invoicingSales}?filter=needsReview:eq:true`- }- {...props}- />- );- case NotificationEvent.LeaseCriticalDate:- return (- <Notification- icon={<LuCalendarClock />}- to={path.to.leaseDetails(id)}- {...props}- />- );- case NotificationEvent.JobCompleted:- case NotificationEvent.JobAssignment:- return (- <Notification- icon={<LuHammer />}- to={path.to.jobDetails(id)}- {...props}- />- );- case NotificationEvent.JobOperationAssignment:- case NotificationEvent.JobOperationMessage:- const [jobId, operationId, makeMethodId, materialId] = id.split(":");- const link = materialId- ? path.to.jobMakeMethod(jobId, makeMethodId)- : path.to.jobMethod(jobId, makeMethodId);-- return (- <Notification- icon={- event === NotificationEvent.JobOperationMessage ? (- <LuMessageSquare />- ) : (- <LuCirclePlay />- )- }- to={`${link}?selectedOperation=${operationId}`}- {...props}- />- );- case NotificationEvent.MaintenanceDispatchCreated:- case NotificationEvent.MaintenanceDispatchAssignment:- return (- <Notification- icon={<LuWrench />}- to={path.to.maintenanceDispatch(id)}- {...props}- />- );- case NotificationEvent.NonConformanceAssignment:- return (- <Notification icon={<LuShieldX />} to={path.to.issue(id)} {...props} />- );- case NotificationEvent.ProcedureAssignment:- return (- <Notification- icon={<LuListChecks />}- to={path.to.procedure(id)}- {...props}- />- );- case NotificationEvent.QuoteExpired:- return (- <Notification- icon={<LuCalendarX />}- to={path.to.quoteDetails(id)}- {...props}- />- );- case NotificationEvent.PurchaseInvoiceAssignment:- return (- <Notification- icon={<LuShoppingCart />}- to={path.to.purchaseInvoiceDetails(id)}- {...props}- />- );- case NotificationEvent.PurchasingRfqAssignment:- return (- <Notification- icon={<LuPackageSearch />}- to={path.to.purchasingRfq(id)}- {...props}- />- );- case NotificationEvent.PurchaseOrderAssignment:- return (- <Notification- icon={<LuShoppingCart />}- to={path.to.purchaseOrderDetails(id)}- {...props}- />- );- case NotificationEvent.QuoteAssignment:- return (- <Notification- icon={<RiProgress4Line />}- to={path.to.quoteDetails(id)}- {...props}- />- );- case NotificationEvent.RiskAssignment:- return (- <Notification- icon={<LuShieldAlert />}- to={path.to.risk(id)}- {...props}- />- );- case NotificationEvent.SalesRfqReady:- case NotificationEvent.SalesRfqAssignment:- return (- <Notification- icon={<RiProgress2Line />}- to={path.to.salesRfq(id)}- {...props}- />- );- case NotificationEvent.SalesOrderAssignment:- return (- <Notification- icon={<RiProgress8Line />}- to={path.to.salesOrderDetails(id)}- {...props}- />- );- case NotificationEvent.StockTransferAssignment:- return (- <Notification- icon={<LuListChecks />}- to={path.to.salesOrderDetails(id)}- {...props}- />- );- case NotificationEvent.PickingListAssignment:- return (- <Notification- icon={<LuListChecks />}- to={path.to.pickingList(id)}- {...props}- />- );- case NotificationEvent.SuggestionResponse:- return (- <Notification- icon={<LuLightbulb />}- to={path.to.suggestion(id)}- {...props}- />- );- case NotificationEvent.SupplierQuoteAssignment:- return (- <Notification- icon={<LuDollarSign />}- to={path.to.supplierQuoteDetails(id)}- {...props}- />- );- case NotificationEvent.SupplierQuoteResponse:- return (- <Notification- icon={<LuMailCheck />}- to={path.to.supplierQuoteDetails(id)}- {...props}- />- );- case NotificationEvent.TrainingAssignment:- case NotificationEvent.TrainingReminder:- return (- <Notification- icon={<LuListChecks />}- to={path.to.completeTrainingAssignment(id)}- {...props}- />- );- case NotificationEvent.ResourceTrainingAssignment:- return (- <Notification- icon={<LuGraduationCap />}- to={path.to.training(id)}- {...props}- />- );- case NotificationEvent.Workflow:- return (- <Notification- icon={<LuGitPullRequestArrow />}- to={getRecordPath(documentType, id) ?? path.to.authenticatedRoot}- {...props}- />- );- case NotificationEvent.Digest:- // Digest rows are rendered by DigestNotification (expandable). This- // branch is unreachable when GenericNotification is used from the- // topbar maps — kept as a defensive fallback.- return null;- default:- return null;- }+ const icon = NOTIFICATION_ICONS[event];+ if (!icon) return null;+ // The same target as the email link (`api+/link.ts`).+ const target = notificationTarget(event, id, documentType);+ return (+ <Notification+ icon={icon}+ to={target?.path ?? path.to.authenticatedRoot}+ reloadDocument={target?.download}+ {...props}+ />+ );}function DigestNotification({diff --git a/apps/erp/app/components/SearchFilter.tsx b/apps/erp/app/components/SearchFilter.tsxindex 9c31e6ef04..a8859c3aa0 100644--- a/apps/erp/app/components/SearchFilter.tsx+++ b/apps/erp/app/components/SearchFilter.tsx@@ -27,7 +27,7 @@ const SearchFilter = ({ param, size, ...props }: SearchFilterProps) => {const written = useRef(urlQuery);const debounceQuery = useDebounce((q: string) => {written.current = q.trim();- setParams({ [param]: q.trim(), offset: null, limit: null });+ setParams({ [param]: q.trim() });}, 500);useEffect(() => {diff --git a/apps/erp/app/components/ShortcutHelp.tsx b/apps/erp/app/components/ShortcutHelp.tsxindex 6cda536e22..1aafe5fa68 100644--- a/apps/erp/app/components/ShortcutHelp.tsx+++ b/apps/erp/app/components/ShortcutHelp.tsx@@ -13,7 +13,6 @@ import {EXPLORER_SHORTCUTS,MODULE_GO_TO,MODULE_GO_TO_PREFIX,- PAGINATION_SHORTCUTS,SHORTCUTS,searchShortcut} from "~/shortcuts";@@ -77,16 +76,6 @@ const ShortcutHelp = () => {description: t`New record`,group: listPages},- {- shortcut: PAGINATION_SHORTCUTS.previous,- description: t`Previous page`,- group: listPages- },- {- shortcut: PAGINATION_SHORTCUTS.next,- description: t`Next page`,- group: listPages- },{shortcut: DETAIL_TAB_SHORTCUTS.details,description: t`Details`,diff --git a/apps/erp/app/components/Table/Table.tsx b/apps/erp/app/components/Table/Table.tsxindex 259bf792de..29db5f7a39 100644--- a/apps/erp/app/components/Table/Table.tsx+++ b/apps/erp/app/components/Table/Table.tsx@@ -3,7 +3,6 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import {- ActionMenu,Button,ContextMenu,ContextMenuContent,@@ -29,7 +28,7 @@ import {VStack} from "@carbon/react";import { clamp } from "@carbon/utils";-import { Trans, useLingui } from "@lingui/react/macro";+import { Plural, Trans, useLingui } from "@lingui/react/macro";import { useNumberFormatter } from "@react-aria/i18n";import type {Column,@@ -46,26 +45,12 @@ import {getCoreRowModel,useReactTable} from "@tanstack/react-table";-import type {- CSSProperties,- MutableRefObject,- ReactElement,- ReactNode-} from "react";-import {- Fragment,- useCallback,- useEffect,- useMemo,- useRef,- useState-} from "react";+import type { CSSProperties, ReactElement, ReactNode } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {LuArrowDown,LuArrowUp,LuArrowUpDown,- LuChevronDown,- LuChevronRight,LuHash,LuSigma,LuTrendingUpDown,@@ -80,20 +65,59 @@ import type {import { useUrlParams } from "~/hooks";import { useSavedViews } from "~/hooks/useSavedViews";import type { fieldMappings } from "~/modules/shared";-import {- IndeterminateCheckbox,- Pagination,- Row,- TableHeader,- usePagination,- useSort-} from "./components";+import { Row, TableHeader, useSort } from "./components";import { CompactList } from "./components/Compact";import { CompactToolbar } from "./components/Compact/CompactToolbar";import type { ColumnFilter } from "./components/Filter/types";import { useFilters } from "./components/Filter/useFilters";-import type { ColumnSizeMap } from "./types";-import { buildColumnMaps, getAccessorKey, updateNestedProperty } from "./utils";+import { InfiniteStatus } from "./components/InfiniteStatus";+import { RowLimitNote } from "./components/RowLimitNote";+import {+ SelectAllMatchingBar,+ useSelectAllMatching+} from "./components/SelectAllMatching";+import {+ getActionColumn,+ getExpandColumn,+ getRowSelectionColumn+} from "./components/SyntheticColumns";+import { TableSkeleton } from "./components/TableSkeleton";+import { readRowId } from "./infiniteRowsStore";+import { applyRowEdits, pruneRowEdits, type RowEdits, tick } from "./rowEdits";+import type {+ BulkActionScope,+ ColumnSizeMap,+ InfiniteOptions,+ InfiniteRows+} from "./types";+import { useGrowOnlyColumnWidths } from "./useGrowOnlyColumnWidths";+import { useInfiniteRows } from "./useInfiniteRows";+import { useInfiniteScroll } from "./useInfiniteScroll";+import { useVirtualRows } from "./useVirtualRows";+import {+ buildColumnMaps,+ getAccessorKey,+ hasUniqueRowIds,+ isServerSortable+} from "./utils";++// A column's held width, as a header `min-width`. A body cell is at most+// `30dvw` wide (`Cell.tsx`), so no column needs more: the cap keeps one odd+// reading from pushing the rest of the table out of view.+const minWidthStyle = (width: number | undefined) =>+ width === undefined ? undefined : `min(${width}px, 30dvw)`;++// Used until a row is measured: a body cell is `h-11` plus the row's border.+const ESTIMATED_ROW_HEIGHT = 45;+// Used until the header is measured: every `Th` is `h-11`.+const ESTIMATED_HEADER_HEIGHT = 44;+// The rows rendered beyond each edge of the view.+const OVERSCAN = 10;+// The view height the server and the first client render assume, before the+// scroll element is measured. Without it those renders would draw no rows.+const INITIAL_VIEW_HEIGHT = 1200;+// The columns the Table adds itself. They never hold the footer label.+const SYNTHETIC_COLUMNS = new Set(["Expand", "Select", "Actions"]);interface TableProps<T extends object> {columns: ColumnDef<T>[];@@ -145,12 +169,23 @@ interface TableProps<T extends object> {withSimpleSorting?: boolean;sort?: ReactNode;getRowId?: (originalRow: T, index: number) => string;+ // Infinite scroll: the loader pages with a cursor (`toPage`), and the table+ // loads the next page from the same loader as the user scrolls.+ infinite?: InfiniteOptions;+ // Controlled infinite scroll: the parent's `useInfiniteRows` result, in+ // place of `infinite` (see `InfiniteOptions`). `data` is its page 1.+ infiniteRows?: InfiniteRows<T>;+ // A single-load list (no `infinite`) whose loader read `SINGLE_LOAD_LIMIT`+ // rows: more may match, so the table says it shows only the first ones.+ isTruncated?: boolean;// Optional per-row class (e.g. to highlight rows that failed validation).getRowClassName?: (originalRow: T) => string | undefined;rowSelection?: RowSelectionState;onRowSelectionChange?: OnChangeFn<RowSelectionState>;onSelectedRowsChange?: (selectedRows: T[]) => void;- renderActions?: (selectedRows: T[]) => ReactNode;+ // `scope.allMatching` is set when the user selected every matching row of a+ // list past 1,000 rows (only `selectedRows` are loaded then).+ renderActions?: (selectedRows: T[], scope?: BulkActionScope) => ReactNode;renderContextMenu?: (row: T) => JSX.Element | null;renderExpandedRow?: (row: T) => ReactNode;// Pin an expanded row's content (`sticky left-0`) to the scroll container's@@ -317,6 +352,9 @@ const Table = <T extends object>({withSimpleSorting = true,sort,getRowId,+ infinite,+ infiniteRows: controlledInfiniteRows,+ isTruncated = false,getRowClassName,rowSelection: controlledRowSelection,onRowSelectionChange,@@ -348,47 +386,78 @@ const Table = <T extends object>({const { currentView, view } = useSavedViews();- /* Expandable Rows */- const [expandedRows, setExpandedRows] = useState<Record<number, boolean>>({});+ /* Expandable Rows (keyed by row id) */+ const [expandedRows, setExpandedRows] = useState<Record<string, boolean>>({});- const toggleRowExpanded = useCallback((rowIndex: number) => {+ const toggleRowExpanded = useCallback((rowId: string) => {setExpandedRows((prev) => ({...prev,- [rowIndex]: !prev[rowIndex]+ [rowId]: !prev[rowId]}));}, []);- /* Data for Optimistic Updates */- const [internalData, setInternalData] = useState<T[]>(data);+ /* Rows: the loader's rows, then the pages loaded on scroll (`infinite`).+ With `infiniteRows` the parent runs the hook, and this one stays off. */+ const ownInfiniteRows = useInfiniteRows<T>({+ initialRows: data,+ infinite: controlledInfiniteRows ? undefined : infinite,+ getRowId: getRowId ? (row) => getRowId(row, -1) : undefined+ });+ const infiniteRows = controlledInfiniteRows ?? ownInfiniteRows;+ const { hasMore, isLoadingMore, loadError, retry, syncedAt } = infiniteRows;+ const sourceRows = infiniteRows.rows;+ const infiniteOptions = infiniteRows.options;+ const isInfinite = !!infiniteOptions;+ const listKey = infiniteOptions?.listKey;++ // Key rows by their id when every row has a unique one, so a selection, an+ // expanded row or an edit stays on its row when pages are appended.+ const idColumn = infiniteOptions?.idColumn ?? "id";+ const rowIdsAreUnique = useMemo(+ () => hasUniqueRowIds(sourceRows, idColumn),+ [sourceRows, idColumn]+ );+ const resolvedGetRowId = useMemo(+ () =>+ getRowId ??+ (rowIdsAreUnique ? (row: T) => readRowId(row, idColumn)! : undefined),+ [getRowId, rowIdsAreUnique, idColumn]+ );+ const rowKey = useCallback(+ (row: T, index: number) =>+ resolvedGetRowId ? resolvedGetRowId(row, index) : String(index),+ [resolvedGetRowId]+ );++ /* Optimistic inline edits by row id, laid over the rows until a load that+ started after the edit, or a row that already holds it. */+ const [edits, setEdits] = useState<RowEdits>({});+ const tableData = useMemo(+ () => applyRowEdits(sourceRows, edits, rowKey, syncedAt),+ [sourceRows, edits, rowKey, syncedAt]+ );useEffect(() => {- setInternalData(data);- }, [data]);-- /* Selectable Rows */- const [internalRowSelection, setInternalRowSelection] =- useState<RowSelectionState>({});- const isSelectionControlled = controlledRowSelection !== undefined;- const rowSelection = isSelectionControlled- ? controlledRowSelection- : internalRowSelection;- const setRowSelection = onRowSelectionChange ?? setInternalRowSelection;+ setEdits((current) => pruneRowEdits(current, sourceRows, rowKey, syncedAt));+ }, [sourceRows, rowKey, syncedAt]);++ /* Selectable Rows, with "Select all matching" */+ const selection = useSelectAllMatching({+ rows: tableData,+ getRowId: rowKey,+ isSelectable: withSelectableRows,+ hasStableRowIds: !!resolvedGetRowId,+ rowSelection: controlledRowSelection,+ onRowSelectionChange,+ infiniteRows,+ count,+ canSelectAll:+ withSelectableRows && typeof renderActions === "function" && isInfinite+ });+ const { rowSelection, allMatching } = selection;// Anchor row (by id) for shift-click range selection.const selectionAnchorRef = useRef<string | null>(null);- /* Clear row selection when data changes. Skip when rows have stable ids- (getRowId) or selection is controlled — the selection survives data- reshapes like tree expansion in those cases. */- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (withSelectableRows && !getRowId && !isSelectionControlled) {- setRowSelection({});- }- }, [data.length, withSelectableRows]);-- /* Pagination */- const pagination = usePagination(count, setRowSelection, data.length);-/* Column Visibility */const [columnVisibility, setColumnVisibility] = useState(currentView?.columnVisibility ?? defaultColumnVisibility ?? {}@@ -399,43 +468,26 @@ const Table = <T extends object>({currentView?.columnOrder ?? defaultColumnOrder ?? []);- const [columnPinning, setColumnPinning] = useState<ColumnPinningState>(() => {- const left: string[] = [];- const right: string[] = [];- if (renderExpandedRow) {- left.push("Expand");- }- if (withSelectableRows) {- left.push("Select");- }- if (renderContextMenu) {- right.push("Actions");- }-- if (currentView?.columnPinning) {- return currentView.columnPinning;- }- if (- defaultColumnPinning &&- "left" in defaultColumnPinning &&- Array.isArray(defaultColumnPinning.left)- ) {- left.push(...defaultColumnPinning.left);- }-- if (- defaultColumnPinning &&- "right" in defaultColumnPinning &&- Array.isArray(defaultColumnPinning.right)- ) {- right.push(...defaultColumnPinning.right);- }-- return {- left,- right- };+ // The synthetic columns first (left) and last (right), then the caller's+ // default pins.+ const getDefaultColumnPinning = (): ColumnPinningState => ({+ left: [+ ...(renderExpandedRow ? ["Expand"] : []),+ ...(withSelectableRows ? ["Select"] : []),+ ...(Array.isArray(defaultColumnPinning?.left)+ ? defaultColumnPinning.left+ : [])+ ],+ right: [+ ...(renderContextMenu ? ["Actions"] : []),+ ...(Array.isArray(defaultColumnPinning?.right)+ ? defaultColumnPinning.right+ : [])+ ]});+ const [columnPinning, setColumnPinning] = useState<ColumnPinningState>(+ () => currentView?.columnPinning ?? getDefaultColumnPinning()+ );// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {@@ -446,40 +498,7 @@ const Table = <T extends object>({} else {setColumnVisibility(defaultColumnVisibility ?? {});setColumnOrder(defaultColumnOrder ?? []);- setColumnPinning(() => {- const left: string[] = [];- const right: string[] = [];- if (renderExpandedRow) {- left.push("Expand");- }- if (withSelectableRows) {- left.push("Select");- }- if (renderContextMenu) {- right.push("Actions");- }-- if (- defaultColumnPinning &&- "left" in defaultColumnPinning &&- Array.isArray(defaultColumnPinning.left)- ) {- left.push(...defaultColumnPinning.left);- }-- if (- defaultColumnPinning &&- "right" in defaultColumnPinning &&- Array.isArray(defaultColumnPinning.right)- ) {- right.push(...defaultColumnPinning.right);- }-- return {- left,- right- };- });+ setColumnPinning(getDefaultColumnPinning());}}, [view]);@@ -541,7 +560,7 @@ const Table = <T extends object>({]);const table = useReactTable({- data: internalData,+ data: tableData,columns: internalColumns,state: {columnVisibility: effectiveColumnVisibility,@@ -552,35 +571,24 @@ const Table = <T extends object>({onColumnVisibilityChange: setColumnVisibility,onColumnOrderChange: setColumnOrder,onColumnPinningChange: setColumnPinning,- onRowSelectionChange: setRowSelection,- getRowId,+ onRowSelectionChange: selection.onRowSelectionChange,+ getRowId: resolvedGetRowId,getCoreRowModel: getCoreRowModel(),meta: {// These are not part of the standard API, but are accessible via table.options.metaeditableComponents,updateData: (rowIndex, updates) => {- setInternalData((previousData) => {- const newData = previousData.map((row, index) => {- if (index === rowIndex) {- return Object.entries(updates).reduce(- (newRow, [columnId, value]) => {- if (columnId.includes("_") && !(columnId in newRow)) {- updateNestedProperty(newRow, columnId, value);- return newRow;- } else {- return {- ...newRow,- [columnId]: value- };- }- },- row- );- }- return row;- });-- return newData;+ const row = tableData[rowIndex];+ if (!row) return;+ const id = rowKey(row, rowIndex);+ setEdits((current) => {+ const previous = current[id];+ const values =+ previous && previous.at >= syncedAt ? previous.values : {};+ return {+ ...current,+ [id]: { values: { ...values, ...updates }, at: tick() }+ };});}}@@ -597,6 +605,25 @@ const Table = <T extends object>({}}, [rowSelection, onSelectedRowsChange]);+ const selectAllBar = (+ <SelectAllMatchingBar+ selectedCount={selectedRows.length}+ count={count}+ {...selection.bar}+ />+ );++ // The actions see the selection's scope; past 1,000 rows `selectedRows`+ // holds only the loaded rows.+ const scopedRenderActions = useMemo(+ () =>+ renderActions+ ? (rows: T[]) =>+ renderActions(rows, { allMatching: allMatching ?? undefined })+ : undefined,+ [renderActions, allMatching]+ );+const [editMode, setEditMode] = useState(forceEditMode);const [isEditing, setIsEditing] = useState(false);const [selectedCell, setSelectedCell] = useState<Position>(null);@@ -874,7 +901,7 @@ const Table = <T extends object>({// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {if (selectedCell) setSelectedCell(null);- }, [editMode, pagination.pageIndex, pagination.pageSize]);+ }, [editMode]);useMount(() => {setColumnOrder(table.getAllLeafColumns().map((column) => column.id));@@ -923,6 +950,60 @@ const Table = <T extends object>({return starts;}, [rows, groupRowsBy]);+ /* Row virtualization: only the rows in view (plus overscan) are in the DOM.+ One virtual item is one data row, with its group header and expanded row+ in the same `<tbody>`, so one measurement covers all three. */+ const isPhoneList = isPhone && mobileLayout === "list";+ const hasRows = rows.length > 0;+ const theadRef = useRef<HTMLTableSectionElement>(null);+ const [headerHeight, setHeaderHeight] = useState(ESTIMATED_HEADER_HEIGHT);+ // biome-ignore lint/correctness/useExhaustiveDependencies: the header mounts with the first row+ useEffect(() => {+ const el = theadRef.current;+ if (!el || typeof ResizeObserver === "undefined") return;+ const update = () => setHeaderHeight(el.offsetHeight);+ update();+ const observer = new ResizeObserver(update);+ observer.observe(el);+ return () => observer.disconnect();+ }, [hasRows, isPhoneList]);++ // The selected row stays rendered when it scrolls out of view: it holds the+ // keyboard focus and, mid-edit, the open editor. Dropping it would lose both.+ const selectedRowIndex = selectedCell?.row;+ const keepSelectedRow = useCallback(+ () => selectedRowIndex,+ [selectedRowIndex]+ );+ const { virtualizer: rowVirtualizer, renderRows: renderVirtualRows } =+ useVirtualRows({+ enabled: !isPhoneList,+ count: rows.length,+ getScrollElement: () => tableContainerRef.current,+ getItemKey: (index) => rows[index]?.id ?? index,+ estimateSize: () => ESTIMATED_ROW_HEIGHT,+ overscan: OVERSCAN,+ scrollMargin: headerHeight,+ // A row scrolled into view lands below the sticky header, not under it.+ scrollPaddingStart: headerHeight,+ keepIndex: keepSelectedRow,+ initialHeight: INITIAL_VIEW_HEIGHT+ });++ // Keyboard moves in edit mode can leave the view: follow the selected row.+ // biome-ignore lint/correctness/useExhaustiveDependencies: follows the selected row only+ useEffect(() => {+ if (!editMode || selectedRowIndex === undefined || isPhoneList) return;+ rowVirtualizer.scrollToIndex(selectedRowIndex, { align: "auto" });+ }, [editMode, selectedRowIndex]);++ /* Infinite scroll (a sentinel after the rows), the scroll offset for Back,+ and the top of a new list. */+ const sentinelRef = useInfiniteScroll(infiniteRows, {+ root: tableContainerRef,+ enabled: !isPhoneList+ });+const tableRef = useRef<HTMLTableElement>(null);// Getter for the nested table wrapper element@@ -932,6 +1013,15 @@ const Table = <T extends object>({);const getHeaderElSelector = (id: string) => `#header-${id}`;+ const columnMinWidths = useGrowOnlyColumnWidths({+ tableRef,+ containerRef: tableContainerRef,+ resetKey: `${visibleColumns.map((c) => c.id).join(",")}|${+ infiniteRows.resetKey+ }|${rows.length > 0}`,+ enabled: !isPhoneList+ });+const pinnedColumnsKey = visibleColumns.reduce<string>((acc, col) => (col.getIsPinned() ? `${acc}:${col.id}` : acc),""@@ -1123,19 +1213,29 @@ const Table = <T extends object>({!params.get("search")?.trim();// Phones export from the toolbar's ⋯ (list and grid alike); desktop keeps- // the toolbar's Download button.+ // the toolbar's Download button. Both export the table's current rows; an+ // infinite list first loads the rest (or hands a big export to a job).const csvExport = withCsvExport? {- data,+ data: tableData,columnAccessors,exportValues,exportOnlyColumns,columnOrder,- columnVisibility+ columnVisibility,+ infinite: isInfinite+ ? {+ count,+ hasMore,+ listKey,+ loadAll: infiniteRows.loadAll,+ resetKey: infiniteRows.resetKey+ }+ : undefined}: undefined;- if (isPhone && mobileLayout === "list") {+ if (isPhoneList) {return (<CompactListtitleBadge={titleBadge}@@ -1148,7 +1248,8 @@ const Table = <T extends object>({withSearch={withSearch}withSort={sort !== null}withPagination={withPagination}- pagination={pagination}+ infinite={isInfinite ? infiniteRows : undefined}+ isTruncated={isTruncated && !isInfinite}withSelectableRows={withSelectableRows}headerActions={headerActions}primaryAction={primaryAction}@@ -1161,7 +1262,9 @@ const Table = <T extends object>({csvExport={csvExport}importCSV={importCSV}renderContextMenu={renderContextMenu}- renderActions={renderActions}+ renderActions={scopedRenderActions}+ selectAllBar={selectAllBar}+ allMatchingCount={allMatching?.count}renderExpandedRow={renderExpandedRow}canExpandRow={canExpandRow}groupStarts={groupStarts}@@ -1191,6 +1294,32 @@ const Table = <T extends object>({? undefined: primaryAction;+ // The rows in view are each in their own `<tbody>`; an empty one stands in+ // for each run of rows that is not rendered.+ const spacerRow = (key: string, height: number) => (+ <tbody key={key} aria-hidden>+ <tr>+ <td colSpan={visibleColumns.length} style={{ height, padding: 0 }} />+ </tr>+ </tbody>+ );++ // Footer totals add up the loaded rows only, so an infinite list says so in+ // the first footer cell that holds nothing else.+ const footerLabelId =+ isInfinite &&+ visibleColumns.some((column) => column.columnDef.meta?.renderTotal)+ ? table+ .getFooterGroups()[0]+ ?.headers.find(+ (footer) =>+ !footer.isPlaceholder &&+ !SYNTHETIC_COLUMNS.has(footer.column.id) &&+ !footer.column.columnDef.meta?.renderTotal &&+ !footer.column.columnDef.footer+ )?.id+ : undefined;+return (<VStackkey={view ?? tableName ?? ""}@@ -1233,16 +1362,18 @@ const Table = <T extends object>({columnVisibility={columnVisibility}columns={table.getAllLeafColumns()}compact={compact}- data={data}+ data={tableData}+ infiniteExport={csvExport?.infinite}editMode={editMode}filters={filters}isEmpty={isTableEmpty}importCSV={importCSV}- pagination={pagination}+ count={count}primaryAction={headerPrimaryAction}headerActions={headerActions}- renderActions={renderActions}+ renderActions={scopedRenderActions}selectedRows={selectedRows}+ selectedCount={allMatching?.count ?? selectedRows.length}setColumnOrder={setColumnOrder}setEditMode={setEditMode}table={tableName}@@ -1260,6 +1391,7 @@ const Table = <T extends object>({sort={sort}/>)}+ {selectAllBar}<divid="table-container"@@ -1277,42 +1409,7 @@ const Table = <T extends object>({<div className="flex max-w-full h-full">{rows.length === 0 ? (isLoading ? (- <div className="flex h-full w-full items-start justify-center">- <TableBase full className="w-full">- <Thead>- <Tr>- {Array.from({ length: 7 }).map((_, colIndex) => (- <Th- key={colIndex}- className={cn(- "h-[44px] w-[200px] bg-card",- colIndex === 0 && "border-r border-border"- )}- >- <div className="h-8" />- </Th>- ))}- </Tr>- </Thead>- <Tbody>- {Array.from({ length: 30 }).map((_, rowIndex) => (- <Tr key={rowIndex}>- {Array.from({ length: 7 }).map((_, colIndex) => (- <Td- key={colIndex}- className={cn(- "h-[44px] w-[200px]",- colIndex === 0 && "border-r border-border"- )}- >- <div className="h-6 w-full bg-gradient-to-r from-foreground/10 to-foreground/10 rounded animate-pulse" />- </Td>- ))}- </Tr>- ))}- </Tbody>- </TableBase>- </div>+ <TableSkeleton />) : emptyState ? (<div className="flex flex-col w-full h-full items-center justify-center gap-4">{emptyState}@@ -1346,7 +1443,7 @@ const Table = <T extends object>({fullclassName="relative border-collapse border-spacing-0">- <Thead className="sticky top-0 z-10">+ <Thead ref={theadRef} className="sticky top-0 z-10">{table.getHeaderGroups().map((headerGroup) => (<Tr key={headerGroup.id} className="h-10">{headerGroup.headers.map((header) => {@@ -1356,9 +1453,7 @@ const Table = <T extends object>({const sortable =withSimpleSorting &&- accessorKey &&- !accessorKey.endsWith(".id") &&- header.column.columnDef.enableSorting !== false;+ isServerSortable(header.column.columnDef);const sortKey =header.column.columnDef.meta?.sortBy ?? accessorKey;const sorted = isSorted(sortKey ?? "");@@ -1368,6 +1463,7 @@ const Table = <T extends object>({key={header.id}colSpan={header.colSpan}id={`header-${header.id}`}+ data-column-id={header.column.id}aria-sort={sorted === 1? "ascending"@@ -1383,7 +1479,10 @@ const Table = <T extends object>({)}style={{...getPinnedStyles(header.column),- width: header.getSize()+ width: header.getSize(),+ minWidth: minWidthStyle(+ columnMinWidths.get(header.column.id)+ )}}>{!header.isPlaceholder &&@@ -1478,116 +1577,141 @@ const Table = <T extends object>({</Tr>))}</Thead>- <Tbody>- {rows.map((row) => {- const rowExpandable =- !!renderExpandedRow &&- (!canExpandRow || canExpandRow(row.original));- const isRowExpanded =- rowExpandable && expandedRows[row.index];- const handleRowClick = rowExpandable- ? () => toggleRowExpanded(row.index)- : undefined;- const rowContent = renderContextMenu ? (- <Menu type="context" key={row.index}>- <ContextMenu>- <ContextMenuTrigger asChild>- <Row- editableComponents={editableComponents}- isEditing={isEditing}- isEditMode={editMode}- isRowSelected={- row.index in rowSelection &&- !!rowSelection[row.index]- }- visibleColumns={visibleColumns}- selectedCell={selectedCell}- row={row}- rowIsSelected={selectedCell?.row === row.index}- getPinnedStyles={getPinnedStyles}- pinnedStyleKey={pinnedStyleKey}- onCellClick={onCellClick}- onCellUpdate={onCellUpdate}- onClick={handleRowClick}- className={cn(- rowExpandable && "cursor-pointer",- getRowClassName?.(row.original)- )}- />- </ContextMenuTrigger>- <ContextMenuContent className="w-128">- {renderContextMenu(row.original)}- </ContextMenuContent>- </ContextMenu>- </Menu>- ) : (- <Row- key={row.id}- editableComponents={editableComponents}- isEditing={isEditing}- isEditMode={editMode}- isRowSelected={- row.index in rowSelection && !!rowSelection[row.index]- }- visibleColumns={visibleColumns}- selectedCell={selectedCell}- row={row}- rowIsSelected={selectedCell?.row === row.index}- getPinnedStyles={getPinnedStyles}- pinnedStyleKey={pinnedStyleKey}- onCellClick={onCellClick}- onCellUpdate={onCellUpdate}- onClick={handleRowClick}- className={cn(- rowExpandable && "cursor-pointer",- getRowClassName?.(row.original)- )}- />- );-- const groupRows = groupStarts.get(row.id);-- return (- <Fragment key={row.id}>- {groupRows && groupRowsBy && (- <Tr>- <Td- colSpan={visibleColumns.length}- className="p-0 bg-muted/40 border-b border-border"- >- <div className="sticky left-0 w-fit">- {groupRowsBy.header(groupRows)}+ {renderVirtualRows((virtualIndex) => {+ const row = rows[virtualIndex]!;+ const rowExpandable =+ !!renderExpandedRow &&+ (!canExpandRow || canExpandRow(row.original));+ const isRowExpanded = rowExpandable && !!expandedRows[row.id];+ const handleRowClick = rowExpandable+ ? () => toggleRowExpanded(row.id)+ : undefined;+ const rowContent = renderContextMenu ? (+ <Menu type="context">+ <ContextMenu>+ <ContextMenuTrigger asChild>+ <Row+ editableComponents={editableComponents}+ isEditing={isEditing}+ isEditMode={editMode}+ isRowSelected={row.getIsSelected()}+ visibleColumns={visibleColumns}+ selectedCell={selectedCell}+ row={row}+ rowIsSelected={selectedCell?.row === row.index}+ getPinnedStyles={getPinnedStyles}+ pinnedStyleKey={pinnedStyleKey}+ onCellClick={onCellClick}+ onCellUpdate={onCellUpdate}+ onClick={handleRowClick}+ className={cn(+ rowExpandable && "cursor-pointer",+ getRowClassName?.(row.original)+ )}+ />+ </ContextMenuTrigger>+ <ContextMenuContent className="w-128">+ {renderContextMenu(row.original)}+ </ContextMenuContent>+ </ContextMenu>+ </Menu>+ ) : (+ <Row+ key={row.id}+ editableComponents={editableComponents}+ isEditing={isEditing}+ isEditMode={editMode}+ isRowSelected={row.getIsSelected()}+ visibleColumns={visibleColumns}+ selectedCell={selectedCell}+ row={row}+ rowIsSelected={selectedCell?.row === row.index}+ getPinnedStyles={getPinnedStyles}+ pinnedStyleKey={pinnedStyleKey}+ onCellClick={onCellClick}+ onCellUpdate={onCellUpdate}+ onClick={handleRowClick}+ className={cn(+ rowExpandable && "cursor-pointer",+ getRowClassName?.(row.original)+ )}+ />+ );++ const groupRows = groupStarts.get(row.id);++ return (+ <Tbody+ key={row.id}+ ref={rowVirtualizer.measureElement}+ data-index={virtualIndex}+ >+ {groupRows && groupRowsBy && (+ <Tr>+ <Td+ colSpan={visibleColumns.length}+ className="p-0 bg-muted/40 border-b border-border"+ >+ <div className="sticky left-0 w-fit">+ {groupRowsBy.header(groupRows)}+ </div>+ </Td>+ </Tr>+ )}+ {rowContent}+ {isRowExpanded && (+ <Tr>+ <Td+ colSpan={visibleColumns.length}+ className="p-0 bg-muted/20 border-b border-border"+ >+ {pinExpandedRows ? (+ <div+ className="sticky left-0"+ style={+ containerWidth > 0+ ? { width: containerWidth }+ : undefined+ }+ >+ {renderExpandedRow(row.original)}</div>- </Td>- </Tr>- )}- {rowContent}- {isRowExpanded && (- <Tr>- <Td- colSpan={visibleColumns.length}- className="p-0 bg-muted/20 border-b border-border"- >- {pinExpandedRows ? (- <div- className="sticky left-0"- style={- containerWidth > 0- ? { width: containerWidth }- : undefined- }- >- {renderExpandedRow(row.original)}- </div>- ) : (- renderExpandedRow(row.original)- )}- </Td>- </Tr>- )}- </Fragment>- );- })}+ ) : (+ renderExpandedRow(row.original)+ )}+ </Td>+ </Tr>+ )}+ </Tbody>+ );+ }, spacerRow)}+ {isTruncated && !isInfinite && (+ <tbody>+ <tr>+ <td colSpan={visibleColumns.length} className="p-0">+ <RowLimitNote className="sticky left-0 w-fit px-4 py-3" />+ </td>+ </tr>+ </tbody>+ )}+ {isInfinite && (+ <tbody+ ref={sentinelRef}+ aria-hidden={!isLoadingMore && !loadError}+ >+ <tr>+ <td colSpan={visibleColumns.length} className="p-0">+ <InfiniteStatus+ isLoading={isLoadingMore}+ loadError={loadError}+ onRetry={retry}+ className="sticky left-0 w-fit px-4 py-3"+ />+ </td>+ </tr>+ </tbody>+ )}+ <Tbody>{table.getFooterGroups().map((footerGroup) => (<Tr key={footerGroup.id} className="h-10">{footerGroup.headers.map((footer) => {@@ -1634,6 +1758,14 @@ const Table = <T extends object>({footer.column.columnDef.footer,footer.getContext())+ ) : footer.id === footerLabelId ? (+ <span className="font-normal text-muted-foreground">+ <Plural+ value={rows.length}+ one="Total of # loaded row"+ other="Total of # loaded rows"+ />+ </span>) : null)}</Th>);@@ -1645,128 +1777,8 @@ const Table = <T extends object>({)}</div></div>- {withPagination && !isTableEmpty && <Pagination {...pagination} />}</VStack>);};-function getRowSelectionColumn<T>(- anchorRef: MutableRefObject<string | null>-): ColumnDef<T>[] {- return [- {- id: "Select",- // width:1 + whitespace-nowrap = shrink-to-fit. A fixed pixel width- // inflates on w-full auto-layout tables because leftover space is- // distributed proportionally to specified column widths.- size: 1,- minSize: 1,- enablePinning: true,- header: ({ table }) => (- <IndeterminateCheckbox- {...{- checked: table.getIsAllRowsSelected(),- indeterminate: table.getIsSomeRowsSelected(),- onChange: (checked: boolean) => {- table.toggleAllRowsSelected(checked);- anchorRef.current = null;- }- }}- />- ),- cell: ({ row, table }) => (- <IndeterminateCheckbox- {...{- checked: row.getIsSelected(),- indeterminate: row.getIsSomeSelected(),- onChange: (checked: boolean, shiftKey: boolean) => {- const rows = table.getRowModel().rows;- const clickedIndex = rows.findIndex((r) => r.id === row.id);- const anchorIndex =- anchorRef.current == null- ? -1- : rows.findIndex((r) => r.id === anchorRef.current);-- if (shiftKey && anchorIndex !== -1 && clickedIndex !== -1) {- const start = Math.min(anchorIndex, clickedIndex);- const end = Math.max(anchorIndex, clickedIndex);- table.setRowSelection((prev) => {- const next = { ...prev };- for (let i = start; i <= end; i++) {- const id = rows[i].id;- if (checked) next[id] = true;- else delete next[id];- }- return next;- });- // Keep the anchor fixed so the range can be re-dragged.- return;- }-- row.toggleSelected(checked);- anchorRef.current = row.id;- }- }}- />- )- }- ];-}--function getActionColumn<T>(- renderContextMenu: (item: T) => JSX.Element | null,- actionsLabel: string-): ColumnDef<T>[] {- return [- {- id: "Actions",- header: () => <span className="sr-only">{actionsLabel}</span>,- cell: (item) => (- <div className="flex justify-end">- <ActionMenu>{renderContextMenu(item.row.original)}</ActionMenu>- </div>- ),- size: 60- }- ];-}--function getExpandColumn<T>(- expandedRows: Record<number, boolean>,- toggleRowExpanded: (rowIndex: number) => void,- labels: { expand: string; expandRow: string; collapseRow: string },- canExpandRow?: (row: T) => boolean-): ColumnDef<T>[] {- return [- {- id: "Expand",- size: 40,- enablePinning: true,- header: () => <span className="sr-only">{labels.expand}</span>,- cell: ({ row }) => {- // No chevron for rows that have nothing to reveal (tree `hasChildren`).- if (canExpandRow && !canExpandRow(row.original)) return null;- const isExpanded = expandedRows[row.index] ?? false;- return (- <button- type="button"- onClick={(e) => {- e.stopPropagation();- toggleRowExpanded(row.index);- }}- className="p-1 hover:bg-muted rounded transition-colors text-muted-foreground hover:text-foreground"- aria-label={isExpanded ? labels.collapseRow : labels.expandRow}- >- {isExpanded ? (- <LuChevronDown className="size-4" />- ) : (- <LuChevronRight className="size-4" />- )}- </button>- );- }- }- ];-}-export default Table;diff --git a/apps/erp/app/components/Table/components/Compact/CompactList.tsx b/apps/erp/app/components/Table/components/Compact/CompactList.tsxindex b89a5b52dc..83956a944a 100644--- a/apps/erp/app/components/Table/components/Compact/CompactList.tsx+++ b/apps/erp/app/components/Table/components/Compact/CompactList.tsx@@ -12,26 +12,55 @@ import {DropdownMenuTrigger,Menu} from "@carbon/react";+import { plural } from "@lingui/core/macro";import { Trans, useLingui } from "@lingui/react/macro";import { useNumberFormatter } from "@react-aria/i18n";-import type { Table } from "@tanstack/react-table";+import type { Row, Table } from "@tanstack/react-table";+import type { Range } from "@tanstack/react-virtual";import type { ReactNode } from "react";-import { Fragment, useEffect, useMemo, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { LuChevronDown } from "react-icons/lu";import { BottomBar } from "~/components/Layout/Mobile/ChromeSlots";import { useSetAppBarOverride } from "~/components/Layout/Mobile/useAppBarOverride";import { useUrlParams } from "~/hooks";import type { fieldMappings } from "~/modules/shared/imports.models";-import { MAX_PAGE_SIZE, PAGE_SIZES } from "~/utils/pagination";+import { EXACT_COUNT_LIMIT } from "../../infiniteRowsStore";+import type { InfiniteRows } from "../../types";+import { findScrollParent, useInfiniteScroll } from "../../useInfiniteScroll";+import { useVirtualRows } from "../../useVirtualRows";import type { DownloadProps } from "../Download";import type { ColumnFilter } from "../Filter/types";-import type { usePagination } from "../Pagination";+import { InfiniteStatus } from "../InfiniteStatus";+import { RowLimitNote } from "../RowLimitNote";import { CompactEmpty, CompactLoading, CompactNoResults } from "./CompactEmpty";import { CompactRow } from "./CompactRow";import { CompactToolbar } from "./CompactToolbar";import { resolveSlots } from "./resolveSlots";-const PAGE = 25;+// Used until a row is measured: a 3-line list row.+const ESTIMATED_ROW_HEIGHT = 72;+// Used until a group header is measured.+const ESTIMATED_GROUP_HEIGHT = 30;+const OVERSCAN = 10;+// The view height the server and the first client render assume, before+// the scroll element is measured. Without it those renders would draw no rows.+const INITIAL_VIEW_HEIGHT = 900;++// A page's phone list scrolls with the app shell's `<main>`; a list in a+// drawer or a modal scrolls with that. It is the nearest ancestor that can+// scroll and has content past its edge; `<main>` when none has yet.+function findListScrollParent(element: HTMLElement): HTMLElement | null {+ return (+ findScrollParent(element, { withOverflow: true }) ??+ document.querySelector<HTMLElement>("main")+ );+}++// One virtual item: a group header (its own item, so it can stay sticky+// while its rows scroll under it) or a row with its expanded content.+type ListEntry<T> =+ | { kind: "group"; key: string; rows: T[] }+ | { kind: "row"; key: string; row: Row<T> };export type CompactListProps<T> = {table: Table<T>;@@ -44,7 +73,10 @@ export type CompactListProps<T> = {withSearch: boolean;withSort: boolean;withPagination: boolean;- pagination: ReturnType<typeof usePagination>;+ /** The infinite-scroll state, when the list loads more rows on scroll. */+ infinite?: InfiniteRows<T>;+ /** A single-load list that read `SINGLE_LOAD_LIMIT` rows (`<Table isTruncated>`). */+ isTruncated?: boolean;withSelectableRows: boolean;headerActions?: ReactNode;primaryAction?: ReactNode;@@ -59,6 +91,10 @@ export type CompactListProps<T> = {importCSV?: { table: keyof typeof fieldMappings; label: string }[];renderContextMenu?: (row: T) => JSX.Element | null;renderActions?: (selectedRows: T[]) => ReactNode;+ /** The "Select all matching" bar, shown above the rows while selecting. */+ selectAllBar?: ReactNode;+ /** Set while every matching row is selected: the list's count. */+ allMatchingCount?: number;renderExpandedRow?: (row: T) => ReactNode;canExpandRow?: (row: T) => boolean;groupStarts: Map<string, T[]>;@@ -86,7 +122,8 @@ export function CompactList<T>({withSearch,withSort,withPagination,- pagination,+ infinite,+ isTruncated = false,withSelectableRows,headerActions,primaryAction,@@ -100,6 +137,8 @@ export function CompactList<T>({importCSV,renderContextMenu,renderActions,+ selectAllBar,+ allMatchingCount,renderExpandedRow,canExpandRow,groupStarts,@@ -109,7 +148,7 @@ export function CompactList<T>({}: CompactListProps<T>) {const { t } = useLingui();const numberFormatter = useNumberFormatter();- const [params, setParams] = useUrlParams();+ const [, setParams] = useUrlParams();const rows = table.getRowModel().rows;// Only the columns desktop shows (a hidden column never fills a slot).@@ -126,49 +165,15 @@ export function CompactList<T>({[table, tableName, title, columnVisibility]);- /* Paging: reveal 25 loaded rows at a time. On the first page, raise `limit`- up to the largest page size; past it (or from a deep link with an- offset), step through pages like desktop. */- const [visible, setVisible] = useState(PAGE);- // biome-ignore lint/correctness/useExhaustiveDependencies: a new result set starts over- useEffect(() => {- setVisible(PAGE);- }, [- params.get("search"),- params.getAll("filter").join(),- params.getAll("sort").join(),- params.get("view"),- params.get("offset")- ]);-- const shown = Math.min(visible, rows.length);- const offset = withPagination ? pagination.offset : 0;- const total = withPagination ? pagination.count : rows.length;- const allShown = shown >= rows.length;- const hasNextPage = withPagination && pagination.canNextPage;- const nextLimit =- hasNextPage && offset === 0 && pagination.pageSize < MAX_PAGE_SIZE- ? PAGE_SIZES.find((size) => size > pagination.pageSize)- : undefined;- const canLoadMore = !allShown || nextLimit !== undefined;- const loadMore = () => {- setVisible((v) => v + PAGE);- if (allShown && nextLimit !== undefined) {- setParams({ limit: String(nextLimit), offset: null });- }- };- const firstShown = offset + 1;- const lastShown = offset + shown;- const showPageNav =- allShown &&- nextLimit === undefined &&- (hasNextPage || (withPagination && pagination.canPreviousPage));-/* Selection mode */const [selecting, setSelecting] = useState(false);const selectedRows = selecting? table.getSelectedRowModel().flatRows.map((row) => row.original): [];+ const selectionLabel =+ allMatchingCount !== undefined+ ? t`All matching rows selected`+ : t`${selectedRows.length} selected`;const exitSelection = () => {table.resetRowSelection();setSelecting(false);@@ -179,7 +184,7 @@ export function CompactList<T>({selecting? {kind: "selection" as const,- title: t`${selectedRows.length} selected`,+ title: selectionLabel,trailing: (<Button variant="ghost" size="lg" onClick={exitSelection}><Trans>Cancel</Trans>@@ -187,13 +192,95 @@ export function CompactList<T>({)}: null,- [selecting, selectedRows.length]+ [selecting, selectionLabel]);useSetAppBarOverride(override);/* Expandable rows */const [expanded, setExpanded] = useState<Record<string, boolean>>({});+ /* Row virtualization on the list's scroll element (`<main>` on a page) */+ const entries = useMemo(() => {+ const list: ListEntry<T>[] = [];+ for (const row of rows) {+ const groupRows = groupHeader ? groupStarts.get(row.id) : undefined;+ if (groupRows) {+ list.push({ kind: "group", key: `group-${row.id}`, rows: groupRows });+ }+ list.push({ kind: "row", key: row.id, row });+ }+ return list;+ }, [rows, groupStarts, groupHeader]);++ const rootRef = useRef<HTMLDivElement>(null);+ const listRef = useRef<HTMLDivElement>(null);+ const [scrollElement, setScrollElement] = useState<HTMLElement | null>(null);+ // The list starts below the toolbar, inside the scrolled content.+ const [listOffset, setListOffset] = useState(0);+ // The scroll element is found again when the layout changes: a list that+ // grows past its drawer's edge starts to scroll with the drawer.+ // biome-ignore lint/correctness/useExhaustiveDependencies: the list mounts with the first row+ useEffect(() => {+ const root = rootRef.current;+ if (!root || typeof ResizeObserver === "undefined") return;+ const update = () => {+ const scroller = findListScrollParent(root);+ setScrollElement(scroller);+ const list = listRef.current;+ if (!scroller || !list) return;+ setListOffset(+ list.getBoundingClientRect().top -+ scroller.getBoundingClientRect().top ++ scroller.scrollTop+ );+ };+ update();+ const observer = new ResizeObserver(update);+ observer.observe(root);+ return () => observer.disconnect();+ }, [rows.length > 0]);++ // The group header above the first row in view stays rendered, so it can+ // stay stuck to the top while its rows scroll.+ const keepGroupHeader = useCallback(+ (range: Range) => {+ if (!groupHeader) return undefined;+ for (let index = range.startIndex; index >= 0; index--) {+ if (entries[index]?.kind === "group") return index;+ }+ return undefined;+ },+ [entries, groupHeader]+ );++ const { virtualizer, renderRows } = useVirtualRows({+ count: entries.length,+ getScrollElement: () => scrollElement,+ getItemKey: (index) => entries[index]?.key ?? index,+ estimateSize: (index) =>+ entries[index]?.kind === "group"+ ? ESTIMATED_GROUP_HEIGHT+ : ESTIMATED_ROW_HEIGHT,+ overscan: OVERSCAN,+ scrollMargin: listOffset,+ keepIndex: keepGroupHeader,+ initialHeight: INITIAL_VIEW_HEIGHT+ });++ /* Infinite scroll: a sentinel after the rows, on the list's scroll+ element; it also remembers the scroll offset for Back. */+ const sentinelRef = useInfiniteScroll(infinite, { root: scrollElement });+ const isLoadingMore = infinite?.isLoadingMore ?? false;++ // "245 of 245 rows" in place of the pager: exact below 1,000, else "about".+ // An estimate can be below the rows already loaded; it never shows less.+ const total = Math.max(count, rows.length);+ const loadedLabel = numberFormatter.format(rows.length);+ const loadedOfTotal =+ total < EXACT_COUNT_LIMIT+ ? t`${loadedLabel} of ${plural(total, { one: "# row", other: "# rows" })}`+ : t`${loadedLabel} of about ${plural(total, { one: "# row", other: "# rows" })}`;+const toolbar = (<CompactToolbartitleBadge={titleBadge}@@ -250,8 +337,86 @@ export function CompactList<T>({);}+ // Each entry's outer element is the one the virtualizer measures.+ const renderEntry = (entry: ListEntry<T>, index: number) => {+ const measured = {+ ref: virtualizer.measureElement,+ "data-index": index+ };+ if (entry.kind === "group") {+ return (+ <div+ key={entry.key}+ {...measured}+ className="sticky top-0 z-20 flex items-center justify-between gap-3 border-b border-border bg-muted/90 px-4 py-1.5 text-xs font-medium uppercase tracking-[0.04em] text-muted-foreground backdrop-blur"+ >+ <div className="min-w-0 truncate normal-case tracking-normal">+ {groupHeader?.(entry.rows)}+ </div>+ <span className="shrink-0 tabular-nums">{entry.rows.length}</span>+ </div>+ );+ }+ const { row } = entry;+ const rowExpandable =+ !!renderExpandedRow && (!canExpandRow || canExpandRow(row.original));+ const isExpanded = rowExpandable && !!expanded[row.id];+ const content = (+ <CompactRow+ row={row}+ slots={slots}+ selection={+ selecting+ ? {+ selected: row.getIsSelected(),+ onToggle: () => row.toggleSelected()+ }+ : undefined+ }+ expansion={+ rowExpandable+ ? {+ expanded: isExpanded,+ onToggle: () =>+ setExpanded((prev) => ({+ ...prev,+ [row.id]: !prev[row.id]+ }))+ }+ : undefined+ }+ />+ );+ return (+ <div key={entry.key} {...measured}>+ {renderContextMenu && !selecting ? (+ <Menu type="context">+ <ContextMenu>+ <ContextMenuTrigger asChild>+ <div>{content}</div>+ </ContextMenuTrigger>+ <ContextMenuContent>+ {renderContextMenu(row.original)}+ </ContextMenuContent>+ </ContextMenu>+ </Menu>+ ) : (+ content+ )}+ {isExpanded && renderExpandedRow ? (+ <div className="overflow-x-auto border-b border-border bg-muted/20">+ {renderExpandedRow(row.original)}+ </div>+ ) : null}+ </div>+ );+ };+return (- <div className="flex min-h-full w-full min-w-0 flex-col bg-card">+ <div+ ref={rootRef}+ className="flex min-h-full w-full min-w-0 flex-col bg-card"+ >{toolbar}{primaryActionRow}{totals.length > 0 ? (@@ -260,113 +425,33 @@ export function CompactList<T>({format={(value) => numberFormatter.format(value)}/>) : null}- <div className="flex flex-col border-t border-border">- {rows.slice(0, shown).map((row) => {- const rowExpandable =- !!renderExpandedRow &&- (!canExpandRow || canExpandRow(row.original));- const isExpanded = rowExpandable && !!expanded[row.id];- const groupRows = groupStarts.get(row.id);- const content = (- <CompactRow- row={row}- slots={slots}- selection={- selecting- ? {- selected: row.getIsSelected(),- onToggle: () => row.toggleSelected()- }- : undefined- }- expansion={- rowExpandable- ? {- expanded: isExpanded,- onToggle: () =>- setExpanded((prev) => ({- ...prev,- [row.id]: !prev[row.id]- }))- }- : undefined- }- />- );- return (- <Fragment key={row.id}>- {groupRows && groupHeader ? (- <div className="sticky top-0 z-20 flex items-center justify-between gap-3 border-b border-border bg-muted/90 px-4 py-1.5 text-xs font-medium uppercase tracking-[0.04em] text-muted-foreground backdrop-blur">- <div className="min-w-0 truncate normal-case tracking-normal">- {groupHeader(groupRows)}- </div>- <span className="shrink-0 tabular-nums">- {groupRows.length}- </span>- </div>- ) : null}- {renderContextMenu && !selecting ? (- <Menu type="context">- <ContextMenu>- <ContextMenuTrigger asChild>- <div>{content}</div>- </ContextMenuTrigger>- <ContextMenuContent>- {renderContextMenu(row.original)}- </ContextMenuContent>- </ContextMenu>- </Menu>- ) : (- content- )}- {isExpanded && renderExpandedRow ? (- <div className="overflow-x-auto border-b border-border bg-muted/20">- {renderExpandedRow(row.original)}- </div>- ) : null}- </Fragment>- );- })}+ {selecting ? selectAllBar : null}+ {/* An empty block stands in for each run of entries not rendered. A+ group header is the measured element itself, so `sticky` works+ against the list, not against a wrapper. */}+ <div ref={listRef} className="flex flex-col border-t border-border">+ {renderRows(+ (index) => renderEntry(entries[index]!, index),+ (key, height) => (+ <div key={key} aria-hidden style={{ height }} />+ )+ )}</div>+ <div ref={sentinelRef} aria-hidden />+ {isTruncated ? (+ <RowLimitNote className="px-4 py-4 text-center text-xs" />+ ) : null}- {offset > 0 || shown < total ? (+ {withPagination || infinite ? (<div className="flex flex-col items-center gap-2 px-4 py-4">- {canLoadMore ? (- <Button- variant="secondary"- size="lg"- className="w-full"- onClick={loadMore}- isLoading={isLoading}- >- <Trans>Load more</Trans>- </Button>- ) : null}- {showPageNav ? (- <div className="flex w-full gap-2">- <Button- variant="secondary"- size="lg"- className="flex-1"- isDisabled={!pagination.canPreviousPage}- onClick={pagination.previousPage}- >- <Trans>Previous page</Trans>- </Button>- <Button- variant="secondary"- size="lg"- className="flex-1"- isDisabled={!hasNextPage}- isLoading={isLoading}- onClick={pagination.nextPage}- >- <Trans>Next page</Trans>- </Button>- </div>- ) : null}+ <InfiniteStatus+ variant="list"+ isLoading={isLoadingMore}+ loadError={infinite?.loadError ?? false}+ onRetry={() => infinite?.retry()}+ /><span className="text-xs text-muted-foreground tabular-nums">- {t`Showing ${firstShown}–${lastShown} of ${total}`}+ {loadedOfTotal}</span></div>) : null}@@ -375,7 +460,7 @@ export function CompactList<T>({<BottomBar><div className="flex items-center gap-3 border-t border-border bg-card px-4 pt-2 pb-safe-4"><span className="min-w-0 flex-1 truncate text-sm text-muted-foreground">- {t`${selectedRows.length} selected`}+ {selectionLabel}</span><DropdownMenu><DropdownMenuTrigger asChild>diff --git a/apps/erp/app/components/Table/components/Compact/CompactToolbar.tsx b/apps/erp/app/components/Table/components/Compact/CompactToolbar.tsxindex 243853a858..5a78d523c9 100644--- a/apps/erp/app/components/Table/components/Compact/CompactToolbar.tsx+++ b/apps/erp/app/components/Table/components/Compact/CompactToolbar.tsx@@ -93,7 +93,7 @@ export function CompactToolbar({const { t } = useLingui();const { urlFiltersParams, hasFilters } = useFilters();const [sheetOpen, setSheetOpen] = useState(false);- const exportCsv = useCsvDownload(csvExport ?? NO_EXPORT);+ const { onClick: exportCsv } = useCsvDownload(csvExport ?? NO_EXPORT);const [importTable, setImportTable] = useState<keyof typeof fieldMappings | null>(null);diff --git a/apps/erp/app/components/Table/components/Download.tsx b/apps/erp/app/components/Table/components/Download.tsxindex 14c7fc0264..dba647c123 100644--- a/apps/erp/app/components/Table/components/Download.tsx+++ b/apps/erp/app/components/Table/components/Download.tsx@@ -7,14 +7,35 @@ import {IconButton,Tooltip,TooltipContent,- TooltipTrigger+ TooltipTrigger,+ toast} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useCallback, useMemo } from "react";+import { useNumberFormatter } from "@react-aria/i18n";+import { useCallback, useMemo, useRef, useState } from "react";import { LuDownload } from "react-icons/lu";+import { useLocation } from "react-router";import { useCustomers, useItems, usePeople, useSuppliers } from "~/stores";+import { path } from "~/utils/path";+import { BROWSER_ROW_LIMIT } from "../infiniteRowsStore";import { selectExportColumns } from "../utils";+/** An infinite list's export: the rows the browser has not loaded yet. */+export type InfiniteExport = {+ /** The list's header count: exact below 1,000, else an estimate. */+ count: number;+ /** True while rows past the loaded ones exist. */+ hasMore: boolean;+ /** The list's registry key. Without it the export stops at 1,000 rows. */+ listKey?: string;+ /** Loads pages until the list ends or `limit` rows are loaded. */+ loadAll: (+ limit: number+ ) => Promise<{ rows: object[]; complete: boolean; resetKey: string }>;+ /** The list's reset key (`InfiniteRows.resetKey`) at render. */+ resetKey: string;+};+export type DownloadProps = {data: object[];columnAccessors: Record<string, string>;@@ -24,11 +45,16 @@ export type DownloadProps = {// Export-only columns (meta.exportOnly): hidden in the grid but always// included in the CSV, regardless of visibility.exportOnlyColumns: string[];+ infinite?: InfiniteExport;};/**- * Builds the CSV of the current page (visible columns, view order) and+ * Builds the CSV of the table's rows (visible columns, view order) and* downloads it. The desktop Download button and the compact ⋯ menu share it.+ *+ * An infinite list first loads the rest of its rows, up to 1,000. Past 1,000,+ * a list with a `listKey` asks the server for a background export instead;+ * a list without one exports the first 1,000 rows.*/export function useCsvDownload({data,@@ -36,12 +62,18 @@ export function useCsvDownload({exportValues,columnOrder,columnVisibility,- exportOnlyColumns+ exportOnlyColumns,+ infinite}: DownloadProps) {+ const { t } = useLingui();+ const numberFormatter = useNumberFormatter();+ const { search } = useLocation();const [items] = useItems();const [suppliers] = useSuppliers();const [people] = usePeople();const [customers] = useCustomers();+ const [isExporting, setIsExporting] = useState(false);+ const isExportingRef = useRef(false);// Maps an id column's accessor key -> a lookup of record id -> name, so the// CSV can show the human-readable name instead of the raw id.@@ -66,38 +98,127 @@ export function useCsvDownload({[columnOrder, columnVisibility, columnAccessors, exportOnlyColumns]);- const onClick = useCallback(() => {- if (!data?.length) {- return;- }- // Build label-keyed rows so the CSV emits the view's header labels, in the- // view's column order, substituting names for id columns.- const rows = data.map((row) => {- const out: Record<string, unknown> = {};- for (const key of exportColumns) {- const exporter = exportValues[key];- let value: unknown;- if (exporter) {- value = exporter(row);+ const downloadRows = useCallback(+ (source: object[]) => {+ // Build label-keyed rows so the CSV emits the view's header labels, in+ // the view's column order, substituting names for id columns.+ const rows = source.map((row) => {+ const out: Record<string, unknown> = {};+ for (const key of exportColumns) {+ const exporter = exportValues[key];+ let value: unknown;+ if (exporter) {+ value = exporter(row);+ } else {+ const raw = (row as Record<string, unknown>)[key];+ const map = idNameMaps[key];+ value = map && raw != null ? (map.get(String(raw)) ?? raw) : raw;+ }+ out[columnAccessors[key]] = value;+ }+ return out;+ });+ downloadCsv(rows, "data.csv");+ },+ [exportColumns, idNameMaps, columnAccessors, exportValues]+ );++ // Starts the background export: the server writes the CSV and notifies the+ // user. The columns go with their translated headers, in display order.+ const startBackgroundExport = useCallback(+ async (listKey: string) => {+ const failed = t`The export could not start. Try again.`;+ try {+ const response = await fetch(path.to.api.tableExport, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ listKey,+ search,+ columns: exportColumns.map((key) => ({+ key,+ label: columnAccessors[key]+ }))+ }),+ credentials: "include"+ });+ const result: unknown = await response.json().catch(() => null);+ if (response.ok && isSuccess(result)) {+ toast.success(+ t`Your export is being prepared. We'll notify you when it's ready.`+ );} else {- const raw = (row as Record<string, unknown>)[key];- const map = idNameMaps[key];- value = map && raw != null ? (map.get(String(raw)) ?? raw) : raw;+ toast.error(errorMessage(result) ?? failed);}- out[columnAccessors[key]] = value;+ } catch {+ toast.error(failed);+ }+ },+ [t, search, exportColumns, columnAccessors]+ );++ const onClick = useCallback(async () => {+ if (!data?.length || isExportingRef.current) {+ return;+ }+ if (!infinite?.hasMore) {+ downloadRows(data);+ return;+ }++ isExportingRef.current = true;+ setIsExporting(true);+ try {+ const { count, listKey, loadAll, resetKey } = infinite;+ if (listKey && count > BROWSER_ROW_LIMIT) {+ await startBackgroundExport(listKey);+ return;+ }+ const { rows, complete, ...loaded } = await loadAll(BROWSER_ROW_LIMIT);+ // A filter, sort or search changed while the rows loaded: they are not+ // the list the user asked to export.+ if (loaded.resetKey !== resetKey) {+ toast.info(t`The list changed while the export loaded. Try again.`);+ return;}- return out;- });- downloadCsv(rows, "data.csv");- }, [data, exportColumns, idNameMaps, columnAccessors, exportValues]);+ // The count was low, but more rows remain past 1,000.+ if (!complete && listKey) {+ await startBackgroundExport(listKey);+ return;+ }+ const exported = complete ? rows : rows.slice(0, BROWSER_ROW_LIMIT);+ downloadRows(exported);+ if (!complete) {+ const exportedCount = numberFormatter.format(exported.length);+ toast.info(t`Exported the first ${exportedCount} rows.`);+ }+ } finally {+ isExportingRef.current = false;+ setIsExporting(false);+ }+ }, [data, infinite, downloadRows, startBackgroundExport, numberFormatter, t]);++ return { onClick, isExporting };+}++function isSuccess(result: unknown): boolean {+ return (+ typeof result === "object" &&+ result !== null &&+ (result as { success?: unknown }).success === true+ );+}- return onClick;+function errorMessage(result: unknown): string | null {+ if (typeof result !== "object" || result === null) return null;+ const { error } = result as { error?: unknown };+ return typeof error === "string" && error.length > 0 ? error : null;}const Download = (props: DownloadProps) => {const { t } = useLingui();const { data } = props;- const onClick = useCsvDownload(props);+ const { onClick, isExporting } = useCsvDownload(props);if (!data?.length) {return null;@@ -112,6 +233,7 @@ const Download = (props: DownloadProps) => {variant={"ghost"}icon={<LuDownload />}className={"!border-dashed border-border"}+ isLoading={isExporting}onClick={onClick}/></TooltipTrigger>diff --git a/apps/erp/app/components/Table/components/InfiniteStatus.tsx b/apps/erp/app/components/Table/components/InfiniteStatus.tsxnew file mode 100644index 0000000000..50bc5a00e0--- /dev/null+++ b/apps/erp/app/components/Table/components/InfiniteStatus.tsx@@ -0,0 +1,70 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { Button, cn, Spinner } from "@carbon/react";+import { Trans } from "@lingui/react/macro";++/**+ * The state of an infinite list below its rows: "Loading more rows" while a+ * page loads, "Couldn't load more rows" with Retry after a failed one.+ * "row" is the desktop line (a table row, a drawer); "list" is the phone list.+ */+export function InfiniteStatus({+ isLoading,+ loadError,+ onRetry,+ variant = "row",+ className+}: {+ isLoading: boolean;+ loadError: boolean;+ onRetry: () => void;+ variant?: "row" | "list";+ className?: string;+}) {+ if (!loadError && !isLoading) return null;++ if (variant === "list") {+ return loadError ? (+ <div className={cn("flex w-full flex-col items-center gap-2", className)}>+ <span className="text-sm text-muted-foreground">+ <Trans>Couldn't load more rows</Trans>+ </span>+ <Button+ variant="secondary"+ size="lg"+ className="w-full"+ onClick={onRetry}+ >+ <Trans>Retry</Trans>+ </Button>+ </div>+ ) : (+ <Spinner className={cn("text-muted-foreground", className)} />+ );+ }++ return (+ <div+ className={cn(+ "flex items-center gap-3 text-sm text-muted-foreground",+ className+ )}+ >+ {loadError ? (+ <>+ <Trans>Couldn't load more rows</Trans>+ <Button variant="secondary" size="sm" onClick={onRetry}>+ <Trans>Retry</Trans>+ </Button>+ </>+ ) : (+ <>+ <Spinner />+ <Trans>Loading more rows</Trans>+ </>+ )}+ </div>+ );+}diff --git a/apps/erp/app/components/Table/components/Pagination/Pagination.tsx b/apps/erp/app/components/Table/components/Pagination/Pagination.tsxdeleted file mode 100644index a81969340f..0000000000--- a/apps/erp/app/components/Table/components/Pagination/Pagination.tsx+++ /dev/null@@ -1,221 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import {- Button,- DropdownMenu,- DropdownMenuContent,- DropdownMenuLabel,- DropdownMenuRadioGroup,- DropdownMenuRadioItem,- DropdownMenuSeparator,- DropdownMenuTrigger,- HStack,- IconButton,- ShortcutKey,- Tooltip,- TooltipContent,- TooltipTrigger,- useShortcutKeyMap-} from "@carbon/react";-import { Trans, useLingui } from "@lingui/react/macro";-import type { ReactElement } from "react";-import { useCallback, useMemo, useRef } from "react";-import { BsChevronLeft, BsChevronRight } from "react-icons/bs";-import { PAGINATION_SHORTCUTS } from "~/shortcuts";-import { PAGE_SIZES } from "~/utils/pagination";--export type PaginationProps = {- compact?: boolean;- count: number;- offset: number;- pageIndex: number;- pageSize: number;- canPreviousPage: boolean;- canNextPage: boolean;- pageCount: number;- gotoPage: (page: number) => void;- nextPage: () => void;- previousPage: () => void;- setPageSize: (size: number) => void;-};--const Pagination = (props: PaginationProps) => {- const { pageSize, setPageSize } = props;-- return (- <>- <hr className="m-0 h-px w-full border-none bg-gradient-to-r from-zinc-200/0 via-zinc-500/30 to-zinc-200/0" />- <HStack- className="text-center bg-card justify-between py-4 w-full z-[1] px-4"- spacing={6}- >- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button variant="secondary">- {pageSize} <Trans>rows</Trans>- </Button>- </DropdownMenuTrigger>- <DropdownMenuContent align="start" className="w-48">- <DropdownMenuLabel>- <Trans>Results per page</Trans>- </DropdownMenuLabel>- <DropdownMenuSeparator />- <DropdownMenuRadioGroup value={`${pageSize}`}>- {PAGE_SIZES.map((size) => (- <DropdownMenuRadioItem- key={`${size}`}- value={`${size}`}- onClick={() => {- setPageSize(size);- }}- >- {size}- </DropdownMenuRadioItem>- ))}- </DropdownMenuRadioGroup>- </DropdownMenuContent>- </DropdownMenu>- <HStack>- <PaginationButtons {...props} />- </HStack>- </HStack>- </>- );-};--export const PaginationButtons = ({- condensed = false,- canNextPage,- canPreviousPage,- count,- nextPage,- offset,- pageSize,- previousPage-}: PaginationProps & { condensed?: boolean }) => {- const { t } = useLingui();- const nextButtonRef = useRef<HTMLButtonElement>(null);- const previousButtonRef = useRef<HTMLButtonElement>(null);-- const scrollToTop = useCallback(() => {- document- .getElementById("table-container")- ?.scrollTo({ top: 0, behavior: "smooth" });- }, []);-- const handlePreviousPage = useCallback(() => {- previousPage();- scrollToTop();- }, [previousPage, scrollToTop]);-- const handleNextPage = useCallback(() => {- nextPage();- scrollToTop();- }, [nextPage, scrollToTop]);-- useShortcutKeyMap(- useMemo(- () => [- {- shortcut: PAGINATION_SHORTCUTS.next,- action: () => nextButtonRef.current?.click()- },- {- shortcut: PAGINATION_SHORTCUTS.previous,- action: () => previousButtonRef.current?.click()- }- ],- []- )- );-- return (- <>- {condensed ? (- <>- <PaginationTooltip direction="previous">- <IconButton- ref={previousButtonRef}- aria-label={t`Previous`}- icon={<BsChevronLeft />}- isDisabled={!canPreviousPage}- onClick={handlePreviousPage}- variant="secondary"- />- </PaginationTooltip>- <PaginationTooltip direction="next">- <IconButton- ref={nextButtonRef}- aria-label={t`Next`}- icon={<BsChevronRight />}- isDisabled={!canNextPage}- onClick={handleNextPage}- variant="secondary"- />- </PaginationTooltip>- </>- ) : (- <>- <div className="text-foreground text-sm font-medium align-center hidden lg:flex">- {count > 0 ? offset + 1 : 0} - {Math.min(offset + pageSize, count)}{" "}- <Trans>of</Trans> {count}- </div>- <PaginationTooltip direction="previous">- <Button- ref={previousButtonRef}- variant="secondary"- isDisabled={!canPreviousPage}- onClick={handlePreviousPage}- leftIcon={<BsChevronLeft />}- >- <Trans>Previous</Trans>- </Button>- </PaginationTooltip>- <PaginationTooltip direction="next">- <Button- ref={nextButtonRef}- variant="secondary"- isDisabled={!canNextPage}- onClick={handleNextPage}- rightIcon={<BsChevronRight />}- >- <Trans>Next</Trans>- </Button>- </PaginationTooltip>- </>- )}- </>- );-};--/** Says what the button does, then its key — a bare arrow keycap reads as "chevron". */-const PaginationTooltip = ({- direction,- children-}: {- direction: keyof typeof PAGINATION_SHORTCUTS;- children: ReactElement;-}) => (- <Tooltip>- <TooltipTrigger asChild>{children}</TooltipTrigger>- <TooltipContent>- <HStack>- <span>- {direction === "previous" ? (- <Trans>Previous page</Trans>- ) : (- <Trans>Next page</Trans>- )}- </span>- <ShortcutKey- shortcut={PAGINATION_SHORTCUTS[direction]}- variant="small"- />- </HStack>- </TooltipContent>- </Tooltip>-);--export default Pagination;diff --git a/apps/erp/app/components/Table/components/Pagination/index.ts b/apps/erp/app/components/Table/components/Pagination/index.tsdeleted file mode 100644index 71163895fe..0000000000--- a/apps/erp/app/components/Table/components/Pagination/index.ts+++ /dev/null@@ -1,10 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import type { PaginationProps } from "./Pagination";-import Pagination, { PaginationButtons } from "./Pagination";-import { usePagination } from "./usePagination";--export { Pagination, PaginationButtons, usePagination };-export type { PaginationProps };diff --git a/apps/erp/app/components/Table/components/Pagination/usePagination.tsx b/apps/erp/app/components/Table/components/Pagination/usePagination.tsxdeleted file mode 100644index 9350606a84..0000000000--- a/apps/erp/app/components/Table/components/Pagination/usePagination.tsx+++ /dev/null@@ -1,71 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import type { RowSelectionState } from "@tanstack/react-table";-import type { Dispatch, SetStateAction } from "react";-import { flushSync } from "react-dom";-import { useUrlParams } from "~/hooks";-import { getPageOffset, getPageSize, pageBounds } from "~/utils/pagination";--export function usePagination(- estimatedCount: number,- setRowSelections: Dispatch<SetStateAction<RowSelectionState>>,- rowsOnPage: number-) {- const [params, setParams] = useUrlParams();- const pageSize = getPageSize(params);- const offset = getPageOffset(params);-- const pageIndex = Math.floor(offset / pageSize) + 1;- const { canNextPage, count } = pageBounds({- count: estimatedCount,- offset,- pageSize,- rowsOnPage- });- const pageCount = Math.ceil(count / pageSize);- const canPreviousPage = pageIndex > 1;-- const gotoPage = (page: number) => {- flushSync(() => {- setRowSelections({});- setParams({- ...Object.fromEntries(params),- offset: (page - 1) * pageSize,- limit: pageSize- });- });-- window?.scrollTo({ top: 0, behavior: "smooth" });- };-- const previousPage = () => {- gotoPage(pageIndex - 1);- };-- const nextPage = () => {- gotoPage(pageIndex + 1);- };-- const setPageSize = (pageSize: number) => {- setParams({- offset: 0,- limit: pageSize- });- };-- return {- count,- offset,- pageIndex,- pageCount,- pageSize,- canPreviousPage,- canNextPage,- gotoPage,- nextPage,- previousPage,- setPageSize- };-}diff --git a/apps/erp/app/components/Table/components/RowLimitNote.tsx b/apps/erp/app/components/Table/components/RowLimitNote.tsxnew file mode 100644index 0000000000..e699719d99--- /dev/null+++ b/apps/erp/app/components/Table/components/RowLimitNote.tsx@@ -0,0 +1,24 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { cn } from "@carbon/react";+import { Trans } from "@lingui/react/macro";+import { useNumberFormatter } from "@react-aria/i18n";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";++/**+ * Below the rows of a single-load list that read `SINGLE_LOAD_LIMIT` rows+ * (`<Table isTruncated>`): more rows may match, and only search or a filter+ * reaches them.+ */+export function RowLimitNote({ className }: { className?: string }) {+ const limit = useNumberFormatter().format(SINGLE_LOAD_LIMIT);+ return (+ <p className={cn("text-sm text-muted-foreground", className)}>+ <Trans>+ Showing the first {limit} rows. Search or filter to see the rest.+ </Trans>+ </p>+ );+}diff --git a/apps/erp/app/components/Table/components/SelectAllMatching.tsx b/apps/erp/app/components/Table/components/SelectAllMatching.tsxnew file mode 100644index 0000000000..2b2a2274f0--- /dev/null+++ b/apps/erp/app/components/Table/components/SelectAllMatching.tsx@@ -0,0 +1,281 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { Button, cn } from "@carbon/react";+import { Plural, Trans, useLingui } from "@lingui/react/macro";+import { useNumberFormatter } from "@react-aria/i18n";+import type { OnChangeFn, RowSelectionState } from "@tanstack/react-table";+import { useEffect, useMemo, useState } from "react";+import { useLocation } from "react-router";+import { BROWSER_ROW_LIMIT, EXACT_COUNT_LIMIT } from "../infiniteRowsStore";+import type { AllMatchingSelection, InfiniteRows } from "../types";++/**+ * What the bar offers when every loaded row is selected and more rows exist:+ * "all" selects every matching row; "first" (a list past 1,000 rows without+ * a background path) selects the first 1,000.+ */+export type SelectAllOffer = "all" | "first";++type SelectAllMatchingBarProps = {+ /** The selected rows the browser holds. */+ selectedCount: number;+ /** The list's header count: exact below 1,000, else an estimate. */+ count: number;+ allMatching: AllMatchingSelection | null;+ offer: SelectAllOffer | null;+ isLoading: boolean;+ onSelectAll: () => void;+ onClear: () => void;+ className?: string;+};++/**+ * The bar above the rows: "100 selected · Select all 245 matching rows", and+ * "All matching rows selected (about 2,300) · Clear selection" after it.+ */+export function SelectAllMatchingBar({+ selectedCount,+ count,+ allMatching,+ offer,+ isLoading,+ onSelectAll,+ onClear,+ className+}: SelectAllMatchingBarProps) {+ const numberFormatter = useNumberFormatter();+ if (!allMatching && !offer) return null;+ const limit = numberFormatter.format(BROWSER_ROW_LIMIT);++ return (+ <div+ className={cn(+ "flex flex-wrap items-center justify-center gap-x-2 gap-y-1 border-b border-border bg-muted/40 px-4 py-1.5 text-sm text-muted-foreground tabular-nums",+ className+ )}+ >+ {allMatching ? (+ <>+ <span>+ <Plural+ value={allMatching.count}+ one="All matching rows selected (about #)"+ other="All matching rows selected (about #)"+ />+ </span>+ <span aria-hidden>·</span>+ <Button variant="link" size="sm" onClick={onClear}>+ <Trans>Clear selection</Trans>+ </Button>+ </>+ ) : (+ <>+ <span>+ <Plural value={selectedCount} one="# selected" other="# selected" />+ </span>+ <span aria-hidden>·</span>+ <Button+ variant="link"+ size="sm"+ isLoading={isLoading}+ onClick={onSelectAll}+ >+ {offer === "first" ? (+ <Trans>Select the first {limit} rows</Trans>+ ) : count < EXACT_COUNT_LIMIT ? (+ <Plural+ value={count}+ one="Select all # matching row"+ other="Select all # matching rows"+ />+ ) : (+ <Plural+ value={count}+ one="Select all matching rows (about #)"+ other="Select all matching rows (about #)"+ />+ )}+ </Button>+ </>+ )}+ </div>+ );+}++/**+ * The tooltip of a bulk action that has no background path, shown disabled+ * while `allMatching` is set.+ */+export function useAllMatchingUnsupportedLabel() {+ const { t } = useLingui();+ const limit = useNumberFormatter().format(BROWSER_ROW_LIMIT);+ return t`Filter the list to ${limit} rows or fewer`;+}++/**+ * The toast a bulk action shows when its route started the background job+ * (`{ background: true }`): the selection is every matching row.+ */+export function useBackgroundBulkActionMessage() {+ const { t } = useLingui();+ return t`Running in the background. We'll notify you when it's done.`;+}++/** What a bulk action posts in place of ids for an "all matching" selection:+ * the list and its URL search (the route reads it with `parseAllMatching`). */+export function allMatchingRequest(allMatching: AllMatchingSelection) {+ return { listKey: allMatching.listKey, search: allMatching.search };+}++// A selection belongs to one list: a new `resetKey` reads as no selection.+type KeyedSelection = { resetKey: string; selection: RowSelectionState };++/**+ * The Table's row selection, with "Select all matching" (see+ * `SelectAllMatchingBar`). While every matching row is selected, the+ * selection is derived: every loaded row, the rows loaded later included.+ * Any other change of the selection ends it.+ *+ * `rowSelection` / `onRowSelectionChange` are the Table's controlled props;+ * without them the hook keeps the selection, per list (`resetKey`).+ */+export function useSelectAllMatching<T>({+ rows,+ getRowId,+ isSelectable,+ hasStableRowIds,+ rowSelection: controlledSelection,+ onRowSelectionChange: onControlledChange,+ infiniteRows,+ count,+ canSelectAll+}: {+ rows: T[];+ getRowId: (row: T, index: number) => string;+ isSelectable: boolean;+ /** False when rows are keyed by index: a change of the row count clears the selection. */+ hasStableRowIds: boolean;+ rowSelection?: RowSelectionState;+ onRowSelectionChange?: OnChangeFn<RowSelectionState>;+ infiniteRows: InfiniteRows<T>;+ /** The list's header count: exact below 1,000, else an estimate. */+ count: number;+ /** The list is infinite and has bulk actions. */+ canSelectAll: boolean;+}) {+ const { search } = useLocation();+ const { resetKey, hasMore, loadAll } = infiniteRows;+ const listKey = infiniteRows.options?.listKey;++ const [internal, setInternal] = useState<KeyedSelection>({+ resetKey,+ selection: {}+ });+ const isControlled = controlledSelection !== undefined;+ const ownSelection = internal.resetKey === resetKey ? internal.selection : {};+ const baseSelection = isControlled ? controlledSelection : ownSelection;+ const setBaseSelection: OnChangeFn<RowSelectionState> =+ onControlledChange ??+ ((updater) =>+ setInternal((previous) => {+ const current =+ previous.resetKey === resetKey ? previous.selection : {};+ return {+ resetKey,+ selection: typeof updater === "function" ? updater(current) : updater+ };+ }));++ // "All matching", with the selection it was chosen over: a new selection+ // or a new list ends it.+ const [chosen, setChosen] = useState<{+ allMatching: AllMatchingSelection;+ resetKey: string;+ over: RowSelectionState;+ } | null>(null);+ const allMatching =+ chosen && chosen.resetKey === resetKey && chosen.over === baseSelection+ ? chosen.allMatching+ : null;++ const everyRowSelection = useMemo(() => {+ if (!allMatching) return null;+ const selection: RowSelectionState = {};+ rows.forEach((row, index) => {+ selection[getRowId(row, index)] = true;+ });+ return selection;+ }, [allMatching, rows, getRowId]);+ const rowSelection = everyRowSelection ?? baseSelection;++ // A change made while every matching row is selected starts from that+ // selection, and becomes the new base selection.+ const onRowSelectionChange: OnChangeFn<RowSelectionState> = (updater) =>+ setBaseSelection(+ everyRowSelection && typeof updater === "function"+ ? updater(everyRowSelection)+ : updater+ );++ /* Rows keyed by index: a new row count leaves the keys on other rows. */+ // biome-ignore lint/correctness/useExhaustiveDependencies: runs when the row count changes+ useEffect(() => {+ if (isSelectable && !hasStableRowIds && !isControlled) {+ setBaseSelection({});+ }+ }, [rows.length, isSelectable]);++ // Every loaded row is selected and more rows exist: offer the rest. A list+ // without a background path offers at most the first 1,000 rows.+ const offer: SelectAllOffer | null =+ canSelectAll &&+ hasMore &&+ !allMatching &&+ rows.length > 0 &&+ rows.every((row, index) => rowSelection[getRowId(row, index)])+ ? count <= BROWSER_ROW_LIMIT || listKey+ ? "all"+ : rows.length < BROWSER_ROW_LIMIT+ ? "first"+ : null+ : null;++ const [isLoading, setIsLoading] = useState(false);+ const onSelectAll = async () => {+ if (count > BROWSER_ROW_LIMIT && listKey) {+ setChosen({+ allMatching: { listKey, search, count },+ resetKey,+ over: baseSelection+ });+ return;+ }+ setIsLoading(true);+ const loaded = await loadAll(BROWSER_ROW_LIMIT);+ setIsLoading(false);+ // The list changed while it loaded: its rows are not the ones offered.+ if (loaded.resetKey !== resetKey) return;+ setBaseSelection((previous) => {+ const next = { ...previous };+ loaded.rows.slice(0, BROWSER_ROW_LIMIT).forEach((row, index) => {+ next[getRowId(row, index)] = true;+ });+ return next;+ });+ };++ return {+ rowSelection,+ onRowSelectionChange,+ allMatching,+ bar: {+ allMatching,+ offer,+ isLoading,+ onSelectAll,+ onClear: () => setBaseSelection({})+ }+ };+}diff --git a/apps/erp/app/components/Table/components/SyntheticColumns.tsx b/apps/erp/app/components/Table/components/SyntheticColumns.tsxnew file mode 100644index 0000000000..03d55f99ff--- /dev/null+++ b/apps/erp/app/components/Table/components/SyntheticColumns.tsx@@ -0,0 +1,130 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { ActionMenu } from "@carbon/react";+import type { ColumnDef } from "@tanstack/react-table";+import type { MutableRefObject } from "react";+import { LuChevronDown, LuChevronRight } from "react-icons/lu";+import IndeterminateCheckbox from "./IndeterminateCheckbox";++// The columns the Table adds itself: expand, select and actions.++export function getRowSelectionColumn<T>(+ anchorRef: MutableRefObject<string | null>+): ColumnDef<T>[] {+ return [+ {+ id: "Select",+ // width:1 + whitespace-nowrap = shrink-to-fit. A fixed pixel width+ // inflates on w-full auto-layout tables because leftover space is+ // distributed proportionally to specified column widths.+ size: 1,+ minSize: 1,+ enablePinning: true,+ header: ({ table }) => (+ <IndeterminateCheckbox+ {...{+ checked: table.getIsAllRowsSelected(),+ indeterminate: table.getIsSomeRowsSelected(),+ onChange: (checked: boolean) => {+ table.toggleAllRowsSelected(checked);+ anchorRef.current = null;+ }+ }}+ />+ ),+ cell: ({ row, table }) => (+ <IndeterminateCheckbox+ {...{+ checked: row.getIsSelected(),+ indeterminate: row.getIsSomeSelected(),+ onChange: (checked: boolean, shiftKey: boolean) => {+ const rows = table.getRowModel().rows;+ const clickedIndex = rows.findIndex((r) => r.id === row.id);+ const anchorIndex =+ anchorRef.current == null+ ? -1+ : rows.findIndex((r) => r.id === anchorRef.current);++ if (shiftKey && anchorIndex !== -1 && clickedIndex !== -1) {+ const start = Math.min(anchorIndex, clickedIndex);+ const end = Math.max(anchorIndex, clickedIndex);+ table.setRowSelection((prev) => {+ const next = { ...prev };+ for (let i = start; i <= end; i++) {+ const id = rows[i].id;+ if (checked) next[id] = true;+ else delete next[id];+ }+ return next;+ });+ // Keep the anchor fixed so the range can be re-dragged.+ return;+ }++ row.toggleSelected(checked);+ anchorRef.current = row.id;+ }+ }}+ />+ )+ }+ ];+}++export function getActionColumn<T>(+ renderContextMenu: (item: T) => JSX.Element | null,+ actionsLabel: string+): ColumnDef<T>[] {+ return [+ {+ id: "Actions",+ header: () => <span className="sr-only">{actionsLabel}</span>,+ cell: (item) => (+ <div className="flex justify-end">+ <ActionMenu>{renderContextMenu(item.row.original)}</ActionMenu>+ </div>+ ),+ size: 60+ }+ ];+}++export function getExpandColumn<T>(+ expandedRows: Record<string, boolean>,+ toggleRowExpanded: (rowId: string) => void,+ labels: { expand: string; expandRow: string; collapseRow: string },+ canExpandRow?: (row: T) => boolean+): ColumnDef<T>[] {+ return [+ {+ id: "Expand",+ size: 40,+ enablePinning: true,+ header: () => <span className="sr-only">{labels.expand}</span>,+ cell: ({ row }) => {+ // No chevron for rows that have nothing to reveal (tree `hasChildren`).+ if (canExpandRow && !canExpandRow(row.original)) return null;+ const isExpanded = expandedRows[row.id] ?? false;+ return (+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ toggleRowExpanded(row.id);+ }}+ className="p-1 hover:bg-muted rounded transition-colors text-muted-foreground hover:text-foreground"+ aria-label={isExpanded ? labels.collapseRow : labels.expandRow}+ >+ {isExpanded ? (+ <LuChevronDown className="size-4" />+ ) : (+ <LuChevronRight className="size-4" />+ )}+ </button>+ );+ }+ }+ ];+}diff --git a/apps/erp/app/components/Table/components/TableHeader.tsx b/apps/erp/app/components/Table/components/TableHeader.tsxindex f28e9e0910..d5e115bc8f 100644--- a/apps/erp/app/components/Table/components/TableHeader.tsx+++ b/apps/erp/app/components/Table/components/TableHeader.tsx@@ -26,7 +26,7 @@ import {toast,useDisclosure} from "@carbon/react";-import { Trans, useLingui } from "@lingui/react/macro";+import { Plural, Trans, useLingui } from "@lingui/react/macro";import type {Column,ColumnOrderState,@@ -53,12 +53,11 @@ import { useSavedViews } from "~/hooks/useSavedViews";import type { fieldMappings } from "~/modules/shared/imports.models";import type { action as savedViewAction } from "~/routes/x+/shared+/views";import { path } from "~/utils/path";+import { EXACT_COUNT_LIMIT } from "../infiniteRowsStore";import Columns from "./Columns";-import Download from "./Download";+import Download, { type InfiniteExport } from "./Download";import { ActiveFilters, Filter } from "./Filter";import type { ColumnFilter } from "./Filter/types";-import type { PaginationProps } from "./Pagination";-import { PaginationButtons } from "./Pagination";import Sort from "./Sort";type HeaderProps<T> = {@@ -72,7 +71,11 @@ type HeaderProps<T> = {columnVisibility: Record<string, boolean>;columns: Column<T, unknown>[];compact?: boolean;+ // The number of matching rows. Exact below 1,000; above, an estimate.+ count: number;data: object[];+ // Infinite lists: the export loads the rest first, or hands it to a job.+ infiniteExport?: InfiniteExport;editMode: boolean;filters: ColumnFilter[];// True when the table has no rows and no active filter/sort/search — hides the@@ -86,8 +89,10 @@ type HeaderProps<T> = {// Extra controls in the toolbar row next to search/filter (e.g. quick// filter toggles that write their own `filter` URL params).headerActions?: ReactNode;- pagination: PaginationProps;selectedRows: T[];+ // The selection's size: the matching count when every matching row is+ // selected, else `selectedRows.length`.+ selectedCount?: number;setColumnOrder: (newOrder: ColumnOrderState) => void;setEditMode: (editMode: boolean) => void;table?: string;@@ -119,15 +124,17 @@ const TableHeader = <T extends object>({columnPinning,columnVisibility,columns,+ count,data,+ infiniteExport,editMode,filters,isEmpty,importCSV,primaryAction,headerActions,- pagination,selectedRows,+ selectedCount,renderActions,setColumnOrder,setEditMode,@@ -335,7 +342,7 @@ const TableHeader = <T extends object>({variant="secondary"><Badge variant="secondary">- <span>{selectedRows.length}</span>+ <span>{selectedCount ?? selectedRows.length}</span></Badge></Button></DropdownMenuTrigger>@@ -391,6 +398,7 @@ const TableHeader = <T extends object>({{withCsvExport && (<Downloaddata={data}+ infinite={infiniteExport}columnAccessors={columnAccessors}exportValues={exportValues}exportOnlyColumns={exportOnlyColumns}@@ -399,10 +407,7 @@ const TableHeader = <T extends object>({/>)}- {withPagination &&- (pagination.canNextPage || pagination.canPreviousPage) && (- <PaginationButtons {...pagination} condensed />- )}+ {withPagination && count > 0 && <RowCount count={count} />}{withInlineEditing &&!forceEditMode &&@@ -452,4 +457,18 @@ const TableHeader = <T extends object>({);};+// The list's total in place of the pager. `LIST_COUNT` is an estimate from+// 1,000 rows up, so the number says "about" there.+function RowCount({ count }: { count: number }) {+ return (+ <span className="whitespace-nowrap px-2 text-sm text-muted-foreground tabular-nums">+ {count < EXACT_COUNT_LIMIT ? (+ <Plural value={count} one="# row" other="# rows" />+ ) : (+ <Plural value={count} one="about # row" other="about # rows" />+ )}+ </span>+ );+}+export default TableHeader;diff --git a/apps/erp/app/components/Table/components/TableSkeleton.tsx b/apps/erp/app/components/Table/components/TableSkeleton.tsxnew file mode 100644index 0000000000..b1dfed114e--- /dev/null+++ b/apps/erp/app/components/Table/components/TableSkeleton.tsx@@ -0,0 +1,55 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ cn,+ Table as TableBase,+ Tbody,+ Td,+ Th,+ Thead,+ Tr+} from "@carbon/react";++/** The Table's placeholder while its first rows load. */+export function TableSkeleton() {+ return (+ <div className="flex h-full w-full items-start justify-center">+ <TableBase full className="w-full">+ <Thead>+ <Tr>+ {Array.from({ length: 7 }).map((_, colIndex) => (+ <Th+ key={colIndex}+ className={cn(+ "h-[44px] w-[200px] bg-card",+ colIndex === 0 && "border-r border-border"+ )}+ >+ <div className="h-8" />+ </Th>+ ))}+ </Tr>+ </Thead>+ <Tbody>+ {Array.from({ length: 30 }).map((_, rowIndex) => (+ <Tr key={rowIndex}>+ {Array.from({ length: 7 }).map((_, colIndex) => (+ <Td+ key={colIndex}+ className={cn(+ "h-[44px] w-[200px]",+ colIndex === 0 && "border-r border-border"+ )}+ >+ <div className="h-6 w-full bg-gradient-to-r from-foreground/10 to-foreground/10 rounded animate-pulse" />+ </Td>+ ))}+ </Tr>+ ))}+ </Tbody>+ </TableBase>+ </div>+ );+}diff --git a/apps/erp/app/components/Table/components/index.ts b/apps/erp/app/components/Table/components/index.tsindex 8dbaf8ef48..2494fd920b 100644--- a/apps/erp/app/components/Table/components/index.ts+++ b/apps/erp/app/components/Table/components/index.ts@@ -4,17 +4,8 @@import Cell from "./Cell";import IndeterminateCheckbox from "./IndeterminateCheckbox";-import { Pagination, usePagination } from "./Pagination";import Row from "./Row";import { useSort } from "./Sort";import TableHeader from "./TableHeader";-export {- Cell,- IndeterminateCheckbox,- Pagination,- Row,- TableHeader,- usePagination,- useSort-};+export { Cell, IndeterminateCheckbox, Row, TableHeader, useSort };diff --git a/apps/erp/app/components/Table/index.ts b/apps/erp/app/components/Table/index.tsindex cfec0c5964..961a287775 100644--- a/apps/erp/app/components/Table/index.ts+++ b/apps/erp/app/components/Table/index.ts@@ -4,6 +4,19 @@import Table from "./Table";+export {+ allMatchingRequest,+ useAllMatchingUnsupportedLabel,+ useBackgroundBulkActionMessage+} from "./components/SelectAllMatching";+export type {+ AllMatchingSelection,+ BulkActionScope,+ InfiniteListError,+ InfiniteOptions,+ InfiniteRows+} from "./types";+export { useInfiniteRows } from "./useInfiniteRows";export { exportOnlyColumn } from "./utils";export default Table;diff --git a/apps/erp/app/components/Table/infiniteRowsStore.test.ts b/apps/erp/app/components/Table/infiniteRowsStore.test.tsnew file mode 100644index 0000000000..778ab62815--- /dev/null+++ b/apps/erp/app/components/Table/infiniteRowsStore.test.ts@@ -0,0 +1,252 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { beforeEach, describe, expect, it } from "vitest";+import {+ clearInfiniteRows,+ getInfiniteRows,+ getPageUrl,+ getRefreshPageCount,+ getResetKey,+ getSearchKey,+ getStoreKey,+ type InfiniteRowsEntry,+ MAX_REFRESH_PAGES,+ mergeRows,+ readPage,+ readRowId,+ saveInfiniteRows+} from "./infiniteRowsStore";++const entry = (scrollTop: number, pageCount = 1): InfiniteRowsEntry => ({+ pages: Array.from({ length: pageCount }, (_, page) => ({+ rows: [{ id: `row-${scrollTop}-${page}` }],+ nextCursor: `c${page}`+ })),+ scrollTop+});++const company = "company-a";++describe("infinite rows memory", () => {+ beforeEach(() => clearInfiniteRows());++ it("returns the entry saved for the same key only", () => {+ saveInfiniteRows(company, "/x/sales/orders?sort=name%3Aasc", entry(300));+ expect(getInfiniteRows(company, "/x/sales/orders?sort=name%3Aasc")).toEqual(+ entry(300)+ );+ expect(getInfiniteRows(company, "/x/sales/orders?")).toBeUndefined();+ expect(+ getInfiniteRows(company, "/x/items/parts?sort=name%3Aasc")+ ).toBeUndefined();+ });++ it("keeps 10 entries and drops the oldest save first", () => {+ for (let i = 0; i < 11; i++) {+ saveInfiniteRows(company, `/list/${i}?`, entry(i));+ }+ expect(getInfiniteRows(company, "/list/0?")).toBeUndefined();+ expect(getInfiniteRows(company, "/list/1?")).toEqual(entry(1));+ expect(getInfiniteRows(company, "/list/10?")).toEqual(entry(10));+ });++ it("treats a new save of a key as the newest", () => {+ for (let i = 0; i < 10; i++) {+ saveInfiniteRows(company, `/list/${i}?`, entry(i));+ }+ saveInfiniteRows(company, "/list/0?", entry(99)); // list 0 is now the newest+ saveInfiniteRows(company, "/list/10?", entry(10)); // drops list 1, not list 0+ expect(getInfiniteRows(company, "/list/0?")).toEqual(entry(99));+ expect(getInfiniteRows(company, "/list/1?")).toBeUndefined();+ });++ it("forgets every entry when the company changes", () => {+ saveInfiniteRows(company, "/list?", entry(1));+ expect(getInfiniteRows("company-b", "/list?")).toBeUndefined();+ // Back in the first company, its rows are gone too.+ expect(getInfiniteRows(company, "/list?")).toBeUndefined();+ });++ it("saves at most the pages a revalidation re-reads", () => {+ saveInfiniteRows(company, "/list?", entry(1, 40));+ const saved = getInfiniteRows(company, "/list?");+ expect(saved?.pages).toHaveLength(MAX_REFRESH_PAGES - 1);+ // The cursor continues after the last page kept.+ expect(saved?.pages.at(-1)?.nextCursor).toBe(`c${MAX_REFRESH_PAGES - 2}`);+ });+});++describe("getStoreKey", () => {+ const key = (companyId: string, dataKey: string, pageUrl: string) =>+ getStoreKey({ companyId, dataKey, pageUrl, ignoreParams: ["item"] });++ it("keys by company, rows key and URL", () => {+ const base = key("a", "jobs", "/x/production/jobs?sort=name%3Aasc");+ expect(key("b", "jobs", "/x/production/jobs?sort=name%3Aasc")).not.toBe(+ base+ );+ expect(key("a", "batches", "/x/production/jobs?sort=name%3Aasc")).not.toBe(+ base+ );+ expect(key("a", "jobs", "/x/production/jobs?sort=name%3Adesc")).not.toBe(+ base+ );+ });++ it("ignores `after`, the ignored params and the param order", () => {+ expect(+ key("a", "jobs", "/x/production/jobs?item=i1&after=c&sort=name%3Aasc")+ ).toBe(key("a", "jobs", "/x/production/jobs?sort=name%3Aasc"));+ });+});++describe("getSearchKey", () => {+ it("ignores `after` and the parameter order", () => {+ expect(getSearchKey("?sort=name:asc&after=abc&filter=status:eq:Open")).toBe(+ getSearchKey("?filter=status:eq:Open&sort=name:asc")+ );+ });++ it("changes with a filter, a sort or a search", () => {+ const base = getSearchKey("?sort=name:asc");+ expect(getSearchKey("?sort=name:desc")).not.toBe(base);+ expect(getSearchKey("?sort=name:asc&search=bolt")).not.toBe(base);+ });+});++describe("getResetKey", () => {+ it("stays the same when only an ignored param changes", () => {+ expect(getResetKey("?sort=name:asc&item=i1", undefined, ["item"])).toBe(+ getResetKey("?sort=name:asc", undefined, ["item"])+ );+ expect(getResetKey("?sort=name:desc", undefined, ["item"])).not.toBe(+ getResetKey("?sort=name:asc", undefined, ["item"])+ );+ });++ it("follows the search of a separate page URL", () => {+ expect(getResetKey("", "/api/sync?status=failed")).not.toBe(+ getResetKey("", "/api/sync?status=ok")+ );+ expect(getResetKey("", "/api/sync?status=ok&after=c")).toBe(+ getResetKey("", "/api/sync?status=ok")+ );+ });+});++describe("getPageUrl", () => {+ it("sets `after` on the list route's URL and keeps its search", () => {+ const url = getPageUrl("/x/sales/orders?sort=name%3Aasc&after=old", "new");+ const parsed = new URL(url, "http://localhost");+ expect(parsed.pathname).toBe("/x/sales/orders");+ expect(parsed.searchParams.get("sort")).toBe("name:asc");+ expect(parsed.searchParams.getAll("after")).toEqual(["new"]);+ });++ it("keeps the naked `index` param of an index route", () => {+ const parsed = new URL(+ getPageUrl("/x/workflows?index&search=a", "c1"),+ "http://localhost"+ );+ expect(parsed.searchParams.getAll("index")).toEqual([""]);+ expect(parsed.searchParams.get("after")).toBe("c1");+ });++ it("works for a URL with no search", () => {+ expect(getPageUrl("/x/items/parts", "c1")).toBe("/x/items/parts?after=c1");+ });+});++describe("getRefreshPageCount", () => {+ it("refreshes every loaded page up to 2,000 rows in total", () => {+ expect(MAX_REFRESH_PAGES).toBe(20);+ expect(getRefreshPageCount(0)).toBe(0);+ expect(getRefreshPageCount(5)).toBe(5);+ expect(getRefreshPageCount(19)).toBe(19); // page 1 + 19 = 20 pages+ expect(getRefreshPageCount(40)).toBe(19); // the rest is dropped+ });+});++describe("mergeRows", () => {+ const id = (row: { id: string }) => row.id;++ it("keeps page 1's copy of a row that moved into a later page", () => {+ const first = [+ { id: "a", v: 2 },+ { id: "b", v: 2 }+ ];+ const later = [+ { id: "b", v: 1 },+ { id: "c", v: 1 }+ ];+ expect(mergeRows(first, later, id)).toEqual([+ { id: "a", v: 2 },+ { id: "b", v: 2 },+ { id: "c", v: 1 }+ ]);+ });++ it("returns page 1 itself when nothing else is loaded", () => {+ const first = [{ id: "a" }];+ expect(mergeRows(first, [], id)).toBe(first);+ });++ it("appends without a check when rows have no id", () => {+ expect(mergeRows([{ id: "a" }], [{ id: "a" }])).toHaveLength(2);+ });++ it("de-duplicates by another id column", () => {+ const byItem = (row: { itemId: string }) => readRowId(row, "itemId");+ expect(+ mergeRows([{ itemId: "a" }], [{ itemId: "a" }, { itemId: "b" }], byItem)+ ).toEqual([{ itemId: "a" }, { itemId: "b" }]);+ });+});++describe("readPage", () => {+ it("reads the rows and the cursor of a new page", () => {+ const data = { salesOrders: [{ id: "a" }], nextCursor: "c2", count: 0 };+ expect(readPage(data, undefined, "salesOrders")).toEqual({+ status: "ok",+ rows: [{ id: "a" }],+ nextCursor: "c2"+ });+ expect(+ readPage({ salesOrders: [], nextCursor: null }, undefined, "salesOrders")+ ).toMatchObject({ status: "ok", nextCursor: null });+ });++ it("is an error when the loader returns `listError`", () => {+ expect(+ readPage(+ { salesOrders: [], nextCursor: null, listError: "failed" },+ undefined,+ "salesOrders"+ )+ ).toEqual({ status: "error" });+ });++ it("ends the list when the next cursor repeats the one requested", () => {+ expect(+ readPage(+ { salesOrders: [], nextCursor: "c1" },+ undefined,+ "salesOrders",+ "c1"+ )+ ).toMatchObject({ status: "ok", nextCursor: null });+ });++ it("is an error when the data did not change, is missing or has no rows", () => {+ const data = { salesOrders: [] };+ expect(readPage(data, data, "salesOrders")).toEqual({ status: "error" });+ expect(readPage(undefined, undefined, "salesOrders")).toEqual({+ status: "error"+ });+ expect(readPage({ parts: [] }, undefined, "salesOrders")).toEqual({+ status: "error"+ });+ });+});diff --git a/apps/erp/app/components/Table/infiniteRowsStore.ts b/apps/erp/app/components/Table/infiniteRowsStore.tsnew file mode 100644index 0000000000..ac75479ae4--- /dev/null+++ b/apps/erp/app/components/Table/infiniteRowsStore.ts@@ -0,0 +1,233 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++/**+ * Memory and pure helpers for `useInfiniteRows`.+ *+ * A list unmounts when the user opens a record (the record page is outside the+ * list route), so the loaded rows cannot live in component state. This module+ * keeps them per company, list and URL for the Back button, in memory only: a+ * page reload clears it, and so does a switch to another company.+ */++/** At most this many pages stay loaded after a revalidation (2,000 rows). */+export const MAX_REFRESH_PAGES = 20;++/**+ * The browser loads at most this many rows for "Select all matching" and the+ * CSV export. Past it, a list with a `listKey` hands the work to a job.+ */+export const BROWSER_ROW_LIMIT = 1000;++/**+ * Below this many rows the list's count is exact. From it up, `LIST_COUNT` is+ * an estimate, and the copy says "about".+ */+export const EXACT_COUNT_LIMIT = 1000;++/** The next page starts to load when the user is this close to the end. */+export const PREFETCH_DISTANCE = 600;++const MAX_ENTRIES = 10;++/** One page loaded after page 1, and the cursor after its last row. */+export type InfinitePage<T = unknown> = {+ rows: T[];+ nextCursor: string | null;+};++export type InfiniteRowsEntry = {+ /** The pages loaded after page 1. The loader always returns page 1. */+ pages: InfinitePage[];+ scrollTop: number;+};++const entries = new Map<string, InfiniteRowsEntry>();+let entriesCompanyId: string | undefined;++// The entries belong to one company. Another company's list must never be+// restored, so a new company empties the memory first.+function claimForCompany(companyId: string | undefined) {+ if (companyId === entriesCompanyId) return;+ entries.clear();+ entriesCompanyId = companyId;+}++/** The memory key of one list query: company, rows key and URL. */+export function getStoreKey({+ companyId,+ dataKey,+ pageUrl,+ ignoreParams+}: {+ companyId: string | undefined;+ dataKey: string;+ pageUrl: string;+ ignoreParams?: readonly string[];+}): string {+ const [pathname, search = ""] = pageUrl.split("?");+ return [+ companyId ?? "",+ dataKey,+ `${pathname}?${getSearchKey(search, ignoreParams)}`+ ].join("\n");+}++/** Saves at most `MAX_REFRESH_PAGES` pages: a revalidation re-reads no more. */+export function saveInfiniteRows(+ companyId: string | undefined,+ key: string,+ entry: InfiniteRowsEntry+) {+ claimForCompany(companyId);+ // Re-inserting moves the key to the end, so the oldest save is dropped first.+ entries.delete(key);+ entries.set(key, {+ ...entry,+ pages: entry.pages.slice(0, getRefreshPageCount(entry.pages.length))+ });+ while (entries.size > MAX_ENTRIES) {+ const oldest = entries.keys().next().value;+ if (oldest === undefined) break;+ entries.delete(oldest);+ }+}++export function getInfiniteRows(+ companyId: string | undefined,+ key: string+): InfiniteRowsEntry | undefined {+ claimForCompany(companyId);+ return entries.get(key);+}++export function clearInfiniteRows() {+ entries.clear();+ entriesCompanyId = undefined;+}++/**+ * The URL search without `after` and `ignoreParams`: the identity of one list+ * query. `ignoreParams` are the params that do not change the list, for+ * example the one that opens a drawer over it.+ */+export function getSearchKey(+ search: string,+ ignoreParams?: readonly string[]+): string {+ const params = new URLSearchParams(search);+ params.delete("after");+ for (const param of ignoreParams ?? []) params.delete(param);+ params.sort();+ return params.toString();+}++/**+ * The list's reset key: the page's URL search, plus the search of `pageUrl`+ * when the pages come from another endpoint. A new key drops the loaded pages.+ */+export function getResetKey(+ search: string,+ pageUrl: string | undefined,+ ignoreParams?: readonly string[]+): string {+ const key = getSearchKey(search, ignoreParams);+ if (!pageUrl) return key;+ const [pathname, pageSearch = ""] = pageUrl.split("?");+ return `${key}\n${pathname}?${getSearchKey(pageSearch, ignoreParams)}`;+}++/**+ * The URL of the next page: the list route's own URL (with `?index` for an+ * index route) with `after` set to the cursor.+ */+export function getPageUrl(routeUrl: string, cursor: string): string {+ const [pathname, search = ""] = routeUrl.split("?");+ const params = new URLSearchParams(search);+ params.delete("after");+ params.set("after", cursor);+ // `index=` still reads as the naked `?index` React Router looks for.+ return `${pathname}?${params.toString()}`;+}++/** How many loaded pages after page 1 a revalidation fetches again. */+export function getRefreshPageCount(loadedPages: number): number {+ return Math.max(0, Math.min(loadedPages, MAX_REFRESH_PAGES - 1));+}++/** The row's id in `idColumn` (default `id`), when it has one. */+export function readRowId(row: unknown, idColumn = "id"): string | undefined {+ if (!row || typeof row !== "object" || !(idColumn in row)) return undefined;+ const id = (row as Record<string, unknown>)[idColumn];+ return id === null || id === undefined ? undefined : String(id);+}++/**+ * Page 1 followed by the later rows, without a row twice. A row moves between+ * pages when other rows are added or deleted; page 1 is the newest copy.+ */+export function mergeRows<T>(+ firstPage: T[],+ laterRows: T[],+ getRowId?: (row: T) => string | undefined+): T[] {+ if (laterRows.length === 0) return firstPage;+ if (!getRowId) return [...firstPage, ...laterRows];++ const seen = new Set<string>();+ for (const row of firstPage) {+ const id = getRowId(row);+ if (id !== undefined) seen.add(id);+ }+ const merged = [...firstPage];+ for (const row of laterRows) {+ const id = getRowId(row);+ if (id !== undefined) {+ if (seen.has(id)) continue;+ seen.add(id);+ }+ merged.push(row);+ }+ return merged;+}++export type PageResult<T> =+ | {+ status: "ok";+ rows: T[];+ nextCursor: string | null;+ }+ | { status: "error" }+ | { status: "aborted" };++/**+ * Reads one fetched page from the fetcher's data. It is an error when:+ * - the data is still the object seen before the request (a loader that+ * threw leaves no new data: the router drops the fetcher),+ * - the loader returned `listError` (`InfiniteListError`),+ * - the data has no rows array.+ *+ * A `nextCursor` equal to the cursor just requested would load the same page+ * again forever, so the list ends there.+ */+export function readPage<T>(+ data: unknown,+ dataAtStart: unknown,+ dataKey: string | undefined,+ requestedCursor?: string+): PageResult<T> {+ if (!dataKey || !data || typeof data !== "object" || data === dataAtStart) {+ return { status: "error" };+ }+ const record = data as Record<string, unknown>;+ if (typeof record.listError === "string") return { status: "error" };+ const rows = record[dataKey];+ if (!Array.isArray(rows)) return { status: "error" };+ const nextCursor =+ typeof record.nextCursor === "string" &&+ record.nextCursor !== requestedCursor+ ? record.nextCursor+ : null;+ return { status: "ok", rows: rows as T[], nextCursor };+}diff --git a/apps/erp/app/components/Table/rowEdits.test.ts b/apps/erp/app/components/Table/rowEdits.test.tsnew file mode 100644index 0000000000..a1898ce4fc--- /dev/null+++ b/apps/erp/app/components/Table/rowEdits.test.ts@@ -0,0 +1,104 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ applyRowEdit,+ applyRowEdits,+ editMatchesRow,+ pruneRowEdits,+ type RowEdits,+ tick+} from "./rowEdits";++type Line = { id: string; quantity: number; item?: { name: string } };++const byId = (row: Line) => row.id;+const rows: Line[] = [+ { id: "a", quantity: 1 },+ { id: "b", quantity: 2 }+];++describe("tick", () => {+ it("only goes up", () => {+ const first = tick();+ expect(tick()).toBeGreaterThan(first);+ });+});++describe("applyRowEdit", () => {+ it("returns a new row and leaves the row as it was", () => {+ const row = { id: "a", quantity: 1, item: { name: "Bolt" } };+ const edited = applyRowEdit(row, { quantity: 5, item_name: "Nut" });+ expect(edited).toEqual({ id: "a", quantity: 5, item: { name: "Nut" } });+ expect(row).toEqual({ id: "a", quantity: 1, item: { name: "Bolt" } });+ });++ it("writes a key with `_` as is when the row has that key", () => {+ expect(applyRowEdit({ unit_price: 1 }, { unit_price: 2 })).toEqual({+ unit_price: 2+ });+ });+});++describe("editMatchesRow", () => {+ it("is true only when the row holds every edited value", () => {+ const row = { id: "a", quantity: 5, item: { name: "Nut" } };+ expect(editMatchesRow(row, { quantity: 5, item_name: "Nut" })).toBe(true);+ expect(editMatchesRow(row, { quantity: 6 })).toBe(false);+ });+});++describe("applyRowEdits", () => {+ it("lays an edit over its row by id, wherever the row is", () => {+ const at = tick();+ const edits: RowEdits = { b: { values: { quantity: 9 }, at } };+ const moved = [rows[1]!, rows[0]!];+ expect(applyRowEdits(moved, edits, byId, at - 1)).toEqual([+ { id: "b", quantity: 9 },+ { id: "a", quantity: 1 }+ ]);+ });++ it("drops an edit once a load that started after it has finished", () => {+ const at = tick();+ const edits: RowEdits = { a: { values: { quantity: 9 }, at } };+ const syncedAt = tick();+ expect(applyRowEdits(rows, edits, byId, syncedAt)).toBe(rows);+ });++ it("keeps an edit over a load that started before it", () => {+ const syncedAt = tick();+ const edits: RowEdits = { a: { values: { quantity: 9 }, at: tick() } };+ expect(applyRowEdits(rows, edits, byId, syncedAt)[0]).toEqual({+ id: "a",+ quantity: 9+ });+ });++ it("returns the rows themselves when no edit applies", () => {+ expect(applyRowEdits(rows, {}, byId, 0)).toBe(rows);+ });+});++describe("pruneRowEdits", () => {+ it("drops an edit the row already holds, and a stale one", () => {+ const syncedAt = tick();+ const at = tick();+ const edits: RowEdits = {+ a: { values: { quantity: 1 }, at }, // the row holds it+ b: { values: { quantity: 7 }, at }, // still live+ c: { values: { quantity: 3 }, at: syncedAt - 1 } // before the load+ };+ expect(pruneRowEdits(edits, rows, byId, syncedAt)).toEqual({+ b: { values: { quantity: 7 }, at }+ });+ });++ it("keeps a live edit of a row that is not loaded", () => {+ const syncedAt = tick();+ const edits: RowEdits = { z: { values: { quantity: 1 }, at: tick() } };+ expect(pruneRowEdits(edits, rows, byId, syncedAt)).toBe(edits);+ });+});diff --git a/apps/erp/app/components/Table/rowEdits.ts b/apps/erp/app/components/Table/rowEdits.tsnew file mode 100644index 0000000000..a78e2dce7e--- /dev/null+++ b/apps/erp/app/components/Table/rowEdits.ts@@ -0,0 +1,126 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++/**+ * Optimistic inline edits, laid over the rows the Table gets.+ *+ * The Table keeps only the user's edits (by row id), never a copy of the rows.+ * An edit shows until the rows catch up with it: a load of the rows that+ * started after the edit, or a row whose value already equals the edit.+ */++let clock = 0;++/** A logical clock. An edit and a load each take a tick, so they can be ordered. */+export function tick(): number {+ clock += 1;+ return clock;+}++/** The values one row was edited to, by column id, and the tick of the edit. */+export type RowEdit = { values: Record<string, unknown>; at: number };++export type RowEdits = Record<string, RowEdit>;++// A column id with `_` that is not a key of the row is a nested path+// (`updateNestedProperty` in `Grid/utils.ts` uses the same rule).+function pathOf(row: object, columnId: string): string[] {+ return columnId.includes("_") && !(columnId in row)+ ? columnId.split("_")+ : [columnId];+}++function readPath(row: object, path: string[]): unknown {+ let value: unknown = row;+ for (const key of path) {+ if (!value || typeof value !== "object") return undefined;+ value = (value as Record<string, unknown>)[key];+ }+ return value;+}++function writePath(row: object, path: string[], value: unknown): object {+ const [key, ...rest] = path;+ const current = row as Record<string, unknown>;+ if (rest.length === 0) return { ...current, [key!]: value };+ const child = current[key!];+ return {+ ...current,+ [key!]: writePath(+ child && typeof child === "object" ? child : {},+ rest,+ value+ )+ };+}++/** The row with the edit's values. The row itself is never changed. */+export function applyRowEdit<T extends object>(+ row: T,+ values: Record<string, unknown>+): T {+ let next: object = row;+ for (const [columnId, value] of Object.entries(values)) {+ const path = pathOf(row, columnId);+ // A nested path skips `undefined`, as `updateNestedProperty` did.+ if (path.length > 1 && value === undefined) continue;+ next = writePath(next, path, value);+ }+ return next as T;+}++/** True when the row already holds every value of the edit. */+export function editMatchesRow(+ row: object,+ values: Record<string, unknown>+): boolean {+ return Object.entries(values).every(([columnId, value]) =>+ Object.is(readPath(row, pathOf(row, columnId)), value)+ );+}++// An edit is live while no load that started after it has finished, and the+// row (when it is loaded) does not already hold it.+function isLive(edit: RowEdit, row: object | undefined, syncedAt: number) {+ if (edit.at < syncedAt) return false;+ return !row || !editMatchesRow(row, edit.values);+}++/** The rows with each live edit laid over its row. Unchanged rows keep their identity. */+export function applyRowEdits<T extends object>(+ rows: T[],+ edits: RowEdits,+ getRowId: (row: T, index: number) => string,+ syncedAt: number+): T[] {+ if (Object.keys(edits).length === 0) return rows;+ let changed = false;+ const next = rows.map((row, index) => {+ const edit = edits[getRowId(row, index)];+ if (!edit || !isLive(edit, row, syncedAt)) return row;+ changed = true;+ return applyRowEdit(row, edit.values);+ });+ return changed ? next : rows;+}++/** The edits without the ones the rows caught up with. The same object when none goes. */+export function pruneRowEdits<T extends object>(+ edits: RowEdits,+ rows: T[],+ getRowId: (row: T, index: number) => string,+ syncedAt: number+): RowEdits {+ const ids = Object.keys(edits);+ if (ids.length === 0) return edits;+ const rowById = new Map<string, T>();+ rows.forEach((row, index) => {+ rowById.set(getRowId(row, index), row);+ });+ const kept: RowEdits = {};+ for (const id of ids) {+ if (isLive(edits[id]!, rowById.get(id), syncedAt)) kept[id] = edits[id]!;+ }+ return Object.keys(kept).length === ids.length ? edits : kept;+}diff --git a/apps/erp/app/components/Table/types.ts b/apps/erp/app/components/Table/types.tsindex 3dc45b3d81..7309b40b35 100644--- a/apps/erp/app/components/Table/types.ts+++ b/apps/erp/app/components/Table/types.ts@@ -58,3 +58,118 @@ declare module "@tanstack/react-table" {}export type ColumnSizeMap = Map<string, { width: number; startX: number }>;++/**+ * Turns on infinite scroll for a list whose loader pages with a cursor+ * (`toPage`). The Table fetches the next page from the same route loader.+ *+ * Two ways to use it:+ * - `<Table infinite={options}>`: the Table runs `useInfiniteRows` itself.+ * - Controlled: the parent calls `useInfiniteRows({ initialRows, infinite })`+ * and passes the result as `<Table data={initialRows} infiniteRows={result}>`.+ * The parent then reads `result.rows` (every loaded row) with no state copy,+ * for example to total or plan over them.+ */+export type InfiniteOptions = {+ /** The key of the rows array in the loader data, for example "salesOrders". */+ dataKey: string;+ /** The loader's `nextCursor`: null when page 1 is the whole list. */+ nextCursor: string | null;+ /**+ * The list's key in the server list registry (`utils/list-registry`). Only+ * a registered list gets the background export and bulk-action paths.+ */+ listKey?: string;+ /**+ * URL search params that do not define the list, for example the param+ * that opens a drawer over it. A change of one keeps the loaded pages, the+ * scroll offset and the selection. `after` is always ignored.+ */+ ignoreParams?: string[];+ /**+ * The rows' unique id column when it is not `id`. It de-duplicates rows+ * that move between pages and keys the rows (selection, edits).+ */+ idColumn?: string;+ /**+ * The URL that serves the later pages, with its own search. Default: the+ * list route's own URL (`useFormAction()`). Set it when the rows come from+ * an `api+` loader instead of the route. Its response has the same shape:+ * `{ [dataKey]: rows, nextCursor }`, and `listError` on a failed page.+ */+ pageUrl?: string;+};++/**+ * What a list loader returns, next to its rows key, for a later page+ * (`?after=`) that failed: `{ [dataKey]: [], nextCursor: null, listError }`.+ * The Table then shows "Couldn't load more rows" with Retry, and keeps the+ * rows it has. Page 1 throws (or redirects) as before.+ */+export type InfiniteListError = {+ /** A short message for the log; the Table does not show it. */+ listError: string;+};++/** The state of an infinite list (`useInfiniteRows`). */+export type InfiniteRows<T> = {+ /** Page 1 from the loader, then every page loaded after it. */+ rows: T[];+ hasMore: boolean;+ isLoadingMore: boolean;+ loadError: boolean;+ /**+ * Loads the next page. Does nothing after an error. During a refresh of+ * the loaded pages it waits and loads when the refresh ends.+ */+ loadMore: () => void;+ /** Repeats the request that failed. */+ retry: () => void;+ /**+ * Loads pages until the list ends or `limit` rows are loaded. `resetKey`+ * is the list's key when it ended: a different key than at the start means+ * the list changed while it loaded.+ */+ loadAll: (+ limit: number+ ) => Promise<{ rows: T[]; complete: boolean; resetKey: string }>;+ totalLoaded: number;+ /** The scroll offset to put back after Back navigation, else null. */+ restoredScrollTop: number | null;+ /** The list reports its scroll offset here, so Back can restore it. */+ rememberScrollTop: (scrollTop: number) => void;+ /**+ * The list's identity: the URL search without `after` and `ignoreParams`+ * (and the `pageUrl` search). A new key drops the loaded pages.+ */+ resetKey: string;+ /**+ * The tick (`rowEdits.ts`) when the load of the current rows started. An+ * inline edit made before it is in the rows already.+ */+ syncedAt: number;+ /** The options in use; undefined when infinite scroll is off. */+ options?: InfiniteOptions;+};++/**+ * "Every row that matches the list's URL search": the selection a list makes+ * past 1,000 rows. The browser does not load those rows; a job reads them.+ */+export type AllMatchingSelection = {+ listKey: string;+ /** The list's URL search (`location.search`) when the user chose it. */+ search: string;+ /** The header count then: an estimate from 1,000 rows up. */+ count: number;+};++/** The second argument of `renderActions`. */+export type BulkActionScope = {+ /**+ * Set when the selection is every matching row, not only the selected rows.+ * An action without a background path shows itself disabled with the+ * tooltip from `useAllMatchingUnsupportedLabel`.+ */+ allMatching?: AllMatchingSelection;+};diff --git a/apps/erp/app/components/Table/useGrowOnlyColumnWidths.test.ts b/apps/erp/app/components/Table/useGrowOnlyColumnWidths.test.tsnew file mode 100644index 0000000000..e35b54fa53--- /dev/null+++ b/apps/erp/app/components/Table/useGrowOnlyColumnWidths.test.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { growWidths } from "./useGrowOnlyColumnWidths";++describe("growWidths", () => {+ it("keeps the widest width each column has had", () => {+ const first = growWidths(new Map(), [+ ["customer", 240],+ ["status", 140]+ ]);+ expect(first).toEqual(+ new Map([+ ["customer", 240],+ ["status", 140]+ ])+ );+ // The wide customer scrolled out: the column keeps 240; status grew.+ expect(+ growWidths(first!, [+ ["customer", 120],+ ["status", 190]+ ])+ ).toEqual(+ new Map([+ ["customer", 240],+ ["status", 190]+ ])+ );+ });++ it("answers null when no column grew, so nothing re-renders", () => {+ const widths = new Map([["customer", 240]]);+ expect(growWidths(widths, [["customer", 200]])).toBeNull();+ expect(growWidths(widths, [["customer", 240]])).toBeNull();+ });+});diff --git a/apps/erp/app/components/Table/useGrowOnlyColumnWidths.ts b/apps/erp/app/components/Table/useGrowOnlyColumnWidths.tsnew file mode 100644index 0000000000..24f276c695--- /dev/null+++ b/apps/erp/app/components/Table/useGrowOnlyColumnWidths.ts@@ -0,0 +1,91 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { RefObject } from "react";+import { useEffect, useState } from "react";++type Widths = { key: string; widths: Map<string, number> };++const NONE = new Map<string, number>();++/** `widths` raised to every larger measured width, or null when none grew. */+export function growWidths(+ widths: ReadonlyMap<string, number>,+ measured: Iterable<readonly [string, number]>+): Map<string, number> | null {+ let next: Map<string, number> | null = null;+ for (const [id, width] of measured) {+ const current = (next ?? widths).get(id);+ if (current === undefined || width > current) {+ next ??= new Map(widths);+ next.set(id, width);+ }+ }+ return next;+}++/**+ * The widest each header cell (`th[data-column-id]`) has been, for its+ * `min-width`. Only the rows in view are rendered, so table layout would+ * narrow a column again each time its widest cell scrolls out. Holding the+ * widest width stops that; a column still widens once when a wider cell first+ * shows. The table keeps its normal layout, so a column always fits its+ * content. The widths start over on a new `resetKey` (the list, the column+ * set) and when the scroll container changes width.+ */+export function useGrowOnlyColumnWidths({+ tableRef,+ containerRef,+ resetKey,+ enabled+}: {+ tableRef: RefObject<HTMLTableElement | null>;+ containerRef: RefObject<HTMLElement | null>;+ resetKey: string;+ enabled: boolean;+}): ReadonlyMap<string, number> {+ const [containerWidth, setContainerWidth] = useState(0);+ useEffect(() => {+ const container = containerRef.current;+ if (!enabled || !container || typeof ResizeObserver === "undefined") {+ return;+ }+ const observer = new ResizeObserver(() =>+ setContainerWidth(container.clientWidth)+ );+ observer.observe(container);+ return () => observer.disconnect();+ }, [enabled, containerRef]);++ const key = `${resetKey}|${containerWidth}`;+ const [state, setState] = useState<Widths>({ key, widths: NONE });++ useEffect(() => {+ const table = tableRef.current;+ if (!enabled || !table || typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver((entries) => {+ const measured = entries.map((entry) => {+ const cell = entry.target as HTMLElement;+ return [+ cell.dataset.columnId!,+ Math.ceil(cell.getBoundingClientRect().width)+ ] as const;+ });+ setState((previous) => {+ const widths = previous.key === key ? previous.widths : NONE;+ const grown = growWidths(widths, measured);+ if (grown) return { key, widths: grown };+ return previous.key === key ? previous : { key, widths };+ });+ });+ for (const cell of table.querySelectorAll<HTMLElement>(+ "thead th[data-column-id]"+ )) {+ observer.observe(cell);+ }+ return () => observer.disconnect();+ }, [enabled, tableRef, key]);++ return enabled && state.key === key ? state.widths : NONE;+}diff --git a/apps/erp/app/components/Table/useInfiniteRows.ts b/apps/erp/app/components/Table/useInfiniteRows.tsnew file mode 100644index 0000000000..db4bbf81d8--- /dev/null+++ b/apps/erp/app/components/Table/useInfiniteRows.ts@@ -0,0 +1,471 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { useRouteData } from "@carbon/react";+import {+ useCallback,+ useEffect,+ useMemo,+ useReducer,+ useRef,+ useState+} from "react";+import {+ useFetcher,+ useFormAction,+ useLocation,+ useNavigationType+} from "react-router";+import { path } from "~/utils/path";+import {+ getInfiniteRows,+ getPageUrl,+ getRefreshPageCount,+ getResetKey,+ getStoreKey,+ type InfinitePage,+ mergeRows,+ type PageResult,+ readPage,+ readRowId,+ saveInfiniteRows+} from "./infiniteRowsStore";+import { tick } from "./rowEdits";+import type { InfiniteOptions, InfiniteRows } from "./types";++export type { InfiniteRows } from "./types";++// The pages loaded after page 1, for one list query.+type Loaded<T> = {+ resetKey: string;+ /** The page 1 these pages were loaded after. Null: fetch them again. */+ baseRows: T[] | null;+ pages: InfinitePage<T>[];+ /** The tick when the load of these pages started (`InfiniteRows.syncedAt`). */+ syncedAt: number;+};++type PendingRequest = {+ id: number;+ cursor: string;+ dataAtStart: unknown;+ loading: boolean;+ settled: boolean;+ resolve: (result: PageResult<unknown>) => void;+};++type FailedTask = "append" | "refresh";++/**+ * Infinite scroll over a loader that pages with a cursor (`toPage`).+ *+ * Page 1 always comes from the loader, so a revalidation or a filter change+ * needs no extra request for it. Later pages come from `useFetcher` on the+ * list route (or `pageUrl`) with `?after=<cursor>`, one request at a time.+ *+ * Without `infinite`, the hook returns `initialRows` and fetches nothing.+ */+export function useInfiniteRows<T>({+ initialRows,+ infinite,+ getRowId+}: {+ initialRows: T[];+ infinite?: InfiniteOptions;+ getRowId?: (row: T) => string;+}): InfiniteRows<T> {+ const enabled = !!infinite;+ const fetcher = useFetcher();+ // The list route's own URL with the current search. Not `location.pathname`:+ // with a drawer open, that is the child route, whose loader has no rows.+ const formAction = useFormAction();+ const location = useLocation();+ const navigationType = useNavigationType();+ const companyId = useRouteData<{ company?: { id?: string } }>(+ path.to.authenticatedRoot+ )?.company?.id;++ const pageUrl = infinite?.pageUrl ?? formAction;+ const resetKey = getResetKey(+ location.search,+ infinite?.pageUrl,+ infinite?.ignoreParams+ );+ const storeKey = getStoreKey({+ companyId,+ dataKey: infinite?.dataKey ?? "",+ pageUrl,+ ignoreParams: infinite?.ignoreParams+ });+ const rowIdOf = getRowId ?? ((row: T) => readRowId(row, infinite?.idColumn));++ // A new page 1 is a load of the rows: edits made before it are in it.+ // biome-ignore lint/correctness/useExhaustiveDependencies: a new page 1 takes a new tick+ const baseTick = useMemo(() => tick(), [initialRows]);++ const [restored] = useState(() =>+ enabled && navigationType === "POP"+ ? getInfiniteRows(companyId, storeKey)+ : undefined+ );+ const [initialLoaded] = useState<Loaded<T>>(() => ({+ resetKey,+ // Rows from memory may be stale: fetch them again (see the revalidation+ // effect below).+ baseRows: restored?.pages.length ? null : initialRows,+ pages: (restored?.pages ?? []) as InfinitePage<T>[],+ syncedAt: baseTick+ }));++ const loadedRef = useRef(initialLoaded);+ const [renderCount, render] = useReducer((count: number) => count + 1, 0);+ const [isLoadingMore, setIsLoadingMore] = useState(false);+ const [failed, setFailedState] = useState<FailedTask | null>(null);+ const failedRef = useRef<FailedTask | null>(null);+ const setFailed = useCallback((task: FailedTask | null) => {+ failedRef.current = task;+ setFailedState(task);+ }, []);++ // The latest render's values, for async work that reads them after an await.+ const values = {+ infinite,+ initialRows,+ rowIdOf,+ resetKey,+ pageUrl,+ storeKey,+ companyId,+ load: fetcher.load,+ fetcherData: fetcher.data as unknown+ };+ const latest = useRef(values);+ latest.current = values;++ const mountedRef = useRef(true);+ const generationRef = useRef(0);+ const requestIdRef = useRef(0);+ const requestRef = useRef<PendingRequest | null>(null);+ const taskRef = useRef<Promise<void>>(Promise.resolve());+ const busyRef = useRef(0);+ const refreshQueuedRef = useRef(false);+ const refreshesRef = useRef(0);+ const loadMoreQueuedRef = useRef(false);+ const loadMoreRef = useRef<() => void>(() => undefined);+ const scrollTopRef = useRef(restored?.scrollTop ?? 0);++ // Work that started before a reset or an unmount must not write.+ const isStale = useCallback(+ (generation: number) =>+ generation !== generationRef.current || !mountedRef.current,+ []+ );++ const currentPages = useCallback((): InfinitePage<T>[] => {+ const loaded = loadedRef.current;+ return loaded.resetKey === latest.current.resetKey ? loaded.pages : [];+ }, []);++ const currentNextCursor = useCallback((): string | null => {+ if (loadedRef.current.resetKey !== latest.current.resetKey) return null;+ const pages = loadedRef.current.pages;+ return pages.length > 0+ ? pages[pages.length - 1]!.nextCursor+ : (latest.current.infinite?.nextCursor ?? null);+ }, []);++ const currentRows = useCallback(+ (): T[] =>+ mergeRows(+ latest.current.initialRows,+ currentPages().flatMap((page) => page.rows),+ latest.current.rowIdOf+ ),+ [currentPages]+ );++ const save = useCallback(() => {+ const { infinite, companyId, storeKey, resetKey } = latest.current;+ if (!infinite || loadedRef.current.resetKey !== resetKey) return;+ saveInfiniteRows(companyId, storeKey, {+ pages: loadedRef.current.pages,+ scrollTop: scrollTopRef.current+ });+ }, []);++ const cancelPending = useCallback(() => {+ const request = requestRef.current;+ requestRef.current = null;+ request?.resolve({ status: "aborted" });+ }, []);++ // One request at a time: a new request ends the previous one as aborted.+ const fetchPage = useCallback(+ (cursor: string) =>+ new Promise<PageResult<T>>((resolve) => {+ cancelPending();+ requestIdRef.current += 1;+ const id = requestIdRef.current;+ requestRef.current = {+ id,+ cursor,+ dataAtStart: latest.current.fetcherData,+ loading: false,+ settled: false,+ resolve: resolve as PendingRequest["resolve"]+ };+ latest.current+ .load(getPageUrl(latest.current.pageUrl, cursor))+ .finally(() => {+ const request = requestRef.current;+ if (request?.id !== id) return;+ request.settled = true;+ render();+ });+ }),+ [cancelPending]+ );++ // Accept the fetcher's data only for the request this hook started. The+ // router also reloads mounted fetchers on revalidation; those results land+ // while no request is pending and are ignored.+ // biome-ignore lint/correctness/useExhaustiveDependencies: renderCount re-runs the check after a request settles+ useEffect(() => {+ const request = requestRef.current;+ if (!request) return;+ if (fetcher.state !== "idle") {+ request.loading = true;+ return;+ }+ if (!request.loading && !request.settled) return;+ requestRef.current = null;+ request.resolve(+ readPage(+ fetcher.data,+ request.dataAtStart,+ latest.current.infinite?.dataKey,+ request.cursor+ )+ );+ }, [fetcher.state, fetcher.data, renderCount]);++ // Work that fetches runs one task at a time, in order. A `loadMore` asked+ // for during a refresh runs when the queue is empty.+ const runTask = useCallback(+ (task: (generation: number) => Promise<unknown>): Promise<void> => {+ busyRef.current += 1;+ const run = taskRef.current+ .then(() => task(generationRef.current))+ .then(() => undefined)+ .catch(() => undefined)+ .finally(() => {+ busyRef.current -= 1;+ if (busyRef.current === 0 && loadMoreQueuedRef.current) {+ loadMoreQueuedRef.current = false;+ loadMoreRef.current();+ }+ });+ taskRef.current = run;+ return run;+ },+ []+ );++ const appendNextPage = useCallback(+ async (generation: number): Promise<boolean> => {+ const cursor = currentNextCursor();+ if (!cursor) return true;++ setIsLoadingMore(true);+ const result = await fetchPage(cursor);+ setIsLoadingMore(false);+ if (isStale(generation)) return false;+ if (result.status !== "ok") {+ if (result.status === "error") setFailed("append");+ return false;+ }++ const loaded = loadedRef.current;+ loadedRef.current = {+ ...loaded,+ pages: [+ ...loaded.pages,+ { rows: result.rows, nextCursor: result.nextCursor }+ ]+ };+ save();+ render();+ return true;+ },+ [currentNextCursor, fetchPage, isStale, save, setFailed]+ );++ // Fetch the loaded pages again after a new page 1, with fresh cursors, and+ // swap them in at once. At most `MAX_REFRESH_PAGES` pages stay loaded; the+ // cursor then continues after the last one.+ const refresh = useCallback(+ async (generation: number) => {+ const startedAt = tick();+ const pagesToLoad = getRefreshPageCount(loadedRef.current.pages.length);+ let cursor = latest.current.infinite?.nextCursor ?? null;+ const pages: InfinitePage<T>[] = [];++ while (cursor && pages.length < pagesToLoad) {+ const result = await fetchPage(cursor);+ if (isStale(generation)) return;+ if (result.status !== "ok") {+ if (result.status === "error") setFailed("refresh");+ return;+ }+ pages.push({ rows: result.rows, nextCursor: result.nextCursor });+ cursor = result.nextCursor;+ }++ loadedRef.current = { ...loadedRef.current, pages, syncedAt: startedAt };+ if (failedRef.current === "refresh") setFailed(null);+ save();+ render();+ },+ [fetchPage, isStale, save, setFailed]+ );++ const scheduleRefresh = useCallback(() => {+ // Coalesce: one refresh waits at most, whatever the number of revalidations.+ if (refreshQueuedRef.current) return;+ refreshQueuedRef.current = true;+ refreshesRef.current += 1;+ void runTask(async (generation) => {+ refreshQueuedRef.current = false;+ try {+ await refresh(generation);+ } finally {+ refreshesRef.current -= 1;+ }+ });+ }, [refresh, runTask]);++ // Reset rule: a new filter, sort, search or view drops the loaded pages.+ useEffect(() => {+ if (loadedRef.current.resetKey === resetKey) return;+ generationRef.current += 1;+ cancelPending();+ loadMoreQueuedRef.current = false;+ loadedRef.current = {+ resetKey,+ baseRows: latest.current.initialRows,+ pages: [],+ syncedAt: tick()+ };+ setFailed(null);+ setIsLoadingMore(false);+ scrollTopRef.current = 0;+ render();+ }, [resetKey, cancelPending, setFailed]);++ // Revalidation rule: the same query with a new page 1 refreshes the later+ // pages too, so edits, new rows and deleted rows show up in place.+ useEffect(() => {+ if (!enabled) return;+ const loaded = loadedRef.current;+ if (loaded.resetKey !== resetKey || loaded.baseRows === initialRows) {+ return;+ }+ const hasPages = loaded.pages.length > 0;+ loadedRef.current = {+ ...loaded,+ baseRows: initialRows,+ syncedAt: hasPages ? loaded.syncedAt : baseTick+ };+ if (hasPages) scheduleRefresh();+ }, [enabled, initialRows, resetKey, baseTick, scheduleRefresh]);++ useEffect(() => {+ mountedRef.current = true;+ return () => {+ mountedRef.current = false;+ cancelPending();+ save();+ };+ }, [cancelPending, save]);++ const loadMore = useCallback(() => {+ if (!latest.current.infinite || failedRef.current) return;+ if (refreshesRef.current > 0) {+ loadMoreQueuedRef.current = true;+ return;+ }+ if (busyRef.current > 0 || !currentNextCursor()) return;+ void runTask(appendNextPage);+ }, [appendNextPage, currentNextCursor, runTask]);+ loadMoreRef.current = loadMore;++ const retry = useCallback(() => {+ const task = failedRef.current;+ if (!task) return;+ setFailed(null);+ if (task === "refresh") scheduleRefresh();+ else void runTask(appendNextPage);+ }, [appendNextPage, runTask, scheduleRefresh, setFailed]);++ const loadAll = useCallback(+ async (limit: number) => {+ if (latest.current.infinite) {+ setFailed(null);+ await runTask(async (generation) => {+ while (currentNextCursor() && currentRows().length < limit) {+ if (!(await appendNextPage(generation))) break;+ }+ });+ }+ return {+ rows: currentRows(),+ complete: currentNextCursor() === null,+ resetKey: latest.current.resetKey+ };+ },+ [appendNextPage, currentNextCursor, currentRows, runTask, setFailed]+ );++ const rememberScrollTop = useCallback((scrollTop: number) => {+ scrollTopRef.current = scrollTop;+ }, []);++ const loaded = loadedRef.current;+ const isCurrent = enabled && loaded.resetKey === resetKey;+ const laterPages = isCurrent ? loaded.pages : null;+ // The row id is read through a ref, so an inline getRowId does not rebuild the rows.+ const rows = useMemo(+ () =>+ laterPages?.length+ ? mergeRows(+ initialRows,+ laterPages.flatMap((page) => page.rows),+ latest.current.rowIdOf+ )+ : initialRows,+ [initialRows, laterPages]+ );+ const nextCursor = !enabled+ ? null+ : laterPages?.length+ ? laterPages[laterPages.length - 1]!.nextCursor+ : (infinite?.nextCursor ?? null);++ return {+ rows,+ hasMore: nextCursor !== null,+ isLoadingMore,+ loadError: failed !== null,+ loadMore,+ retry,+ loadAll,+ totalLoaded: rows.length,+ restoredScrollTop:+ restored && restored.scrollTop > 0 ? restored.scrollTop : null,+ rememberScrollTop,+ resetKey,+ syncedAt: laterPages?.length ? loaded.syncedAt : baseTick,+ options: infinite+ };+}diff --git a/apps/erp/app/components/Table/useInfiniteScroll.ts b/apps/erp/app/components/Table/useInfiniteScroll.tsnew file mode 100644index 0000000000..5a76a5cbab--- /dev/null+++ b/apps/erp/app/components/Table/useInfiniteScroll.ts@@ -0,0 +1,125 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { clamp } from "@carbon/utils";+import type { RefObject } from "react";+import { useEffect, useRef, useState } from "react";+import { PREFETCH_DISTANCE } from "./infiniteRowsStore";+import type { InfiniteRows } from "./types";++/**+ * The nearest ancestor that scrolls vertically. With `withOverflow`, only one+ * whose content already runs past its edge counts.+ */+export function findScrollParent(+ element: Element,+ { withOverflow = false }: { withOverflow?: boolean } = {}+): HTMLElement | null {+ for (let node = element.parentElement; node; node = node.parentElement) {+ const { overflowY } = getComputedStyle(node);+ if (overflowY !== "auto" && overflowY !== "scroll") continue;+ if (!withOverflow || node.scrollHeight > node.clientHeight) return node;+ }+ return null;+}++/** A scroll offset the element can actually reach. */+export function clampScrollTop(+ scrollTop: number,+ element: { scrollHeight: number; clientHeight: number }+): number {+ return clamp(+ scrollTop,+ 0,+ Math.max(0, element.scrollHeight - element.clientHeight)+ );+}++type ScrollRoot = RefObject<HTMLElement | null> | HTMLElement | null | "auto";++function resolveRoot(root: ScrollRoot, sentinel: Element | null) {+ if (root === "auto") return sentinel ? findScrollParent(sentinel) : null;+ if (root && "current" in root) return root.current;+ return root;+}++/**+ * Infinite scroll for one list: an element at the end of the rows (the+ * sentinel) that loads the next page when it comes within 600px of the+ * scroll element's view. The sentinel stays in range while a short list+ * loads, so the list keeps loading until it fills the view.+ *+ * It also remembers the scroll offset for Back, puts it back once the+ * restored rows render, and scrolls to the top when the list's `resetKey`+ * changes (a new filter, sort or search).+ *+ * `root` is the scroll element, a ref to it, or "auto" (the nearest+ * scrolling ancestor of the sentinel). Returns the sentinel's ref.+ */+export function useInfiniteScroll(+ rows: InfiniteRows<unknown> | undefined,+ { root, enabled = true }: { root: ScrollRoot; enabled?: boolean }+) {+ const [sentinel, setSentinel] = useState<Element | null>(null);+ const [inView, setInView] = useState(false);+ const isOn = enabled && !!rows?.options;++ useEffect(() => {+ const element = resolveRoot(root, sentinel);+ if (!isOn || !sentinel || typeof IntersectionObserver === "undefined") {+ setInView(false);+ return;+ }+ const observer = new IntersectionObserver(+ ([entry]) => setInView(!!entry?.isIntersecting),+ { root: element, rootMargin: `0px 0px ${PREFETCH_DISTANCE}px 0px` }+ );+ observer.observe(sentinel);+ return () => observer.disconnect();+ }, [isOn, root, sentinel]);++ const hasMore = rows?.hasMore ?? false;+ const isLoadingMore = rows?.isLoadingMore ?? false;+ const loadError = rows?.loadError ?? false;+ const loadMore = rows?.loadMore;+ // biome-ignore lint/correctness/useExhaustiveDependencies: totalLoaded re-checks after each page renders+ useEffect(() => {+ if (inView && hasMore && !isLoadingMore && !loadError) loadMore?.();+ }, [inView, hasMore, isLoadingMore, loadError, loadMore, rows?.totalLoaded]);++ // The scroll offset, for Back.+ const rememberScrollTop = rows?.rememberScrollTop;+ useEffect(() => {+ const element = resolveRoot(root, sentinel);+ if (!isOn || !element || !rememberScrollTop) return;+ const onScroll = () => rememberScrollTop(element.scrollTop);+ element.addEventListener("scroll", onScroll, { passive: true });+ return () => element.removeEventListener("scroll", onScroll);+ }, [isOn, root, sentinel, rememberScrollTop]);++ // Back: put the offset back once the restored rows render. Fewer rows may+ // come back than were saved, so the offset stops at the end.+ const restoredScrollTop = rows?.restoredScrollTop ?? null;+ const hasRows = (rows?.totalLoaded ?? 0) > 0;+ const restoredRef = useRef(false);+ useEffect(() => {+ const element = resolveRoot(root, sentinel);+ if (restoredRef.current || restoredScrollTop === null || !element) return;+ if (!hasRows) return;+ restoredRef.current = true;+ element.scrollTop = clampScrollTop(restoredScrollTop, element);+ }, [root, sentinel, hasRows, restoredScrollTop]);++ // A new list starts at the top.+ const resetKey = rows?.resetKey;+ const resetKeyRef = useRef(resetKey);+ // biome-ignore lint/correctness/useExhaustiveDependencies: runs when the list changes only+ useEffect(() => {+ if (resetKeyRef.current === resetKey) return;+ resetKeyRef.current = resetKey;+ resolveRoot(root, sentinel)?.scrollTo({ top: 0 });+ }, [resetKey]);++ return setSentinel;+}diff --git a/apps/erp/app/components/Table/useVirtualRows.test.ts b/apps/erp/app/components/Table/useVirtualRows.test.tsnew file mode 100644index 0000000000..9e73645bb9--- /dev/null+++ b/apps/erp/app/components/Table/useVirtualRows.test.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { clampScrollTop } from "./useInfiniteScroll";+import { getVirtualSlots, withKeptIndex } from "./useVirtualRows";++describe("withKeptIndex", () => {+ it("adds the kept index in order when it is out of view", () => {+ expect(withKeptIndex([5, 6, 7], 1, 10)).toEqual([1, 5, 6, 7]);+ expect(withKeptIndex([5, 6, 7], 9, 10)).toEqual([5, 6, 7, 9]);+ });++ it("changes nothing for an index in view, out of range or unset", () => {+ const indexes = [5, 6, 7];+ expect(withKeptIndex(indexes, 6, 10)).toBe(indexes);+ expect(withKeptIndex(indexes, 12, 10)).toBe(indexes);+ expect(withKeptIndex(indexes, undefined, 10)).toBe(indexes);+ });+});++describe("getVirtualSlots", () => {+ it("puts a spacer before, between and after the rendered items", () => {+ // Items of 10px start at the 40px margin (a header).+ const item = (index: number) => ({+ index,+ start: 40 + index * 10,+ end: 50 + index * 10+ });+ expect(getVirtualSlots([item(2), item(3), item(6)], 100, 40)).toEqual([+ { kind: "spacer", key: "before-2", height: 20 },+ { kind: "item", index: 2 },+ { kind: "item", index: 3 },+ { kind: "spacer", key: "before-6", height: 20 },+ { kind: "item", index: 6 },+ { kind: "spacer", key: "after", height: 30 }+ ]);+ });++ it("is one spacer when nothing is rendered", () => {+ expect(getVirtualSlots([], 50, 0)).toEqual([+ { kind: "spacer", key: "after", height: 50 }+ ]);+ });+});++describe("clampScrollTop", () => {+ it("stops a restored offset at the end of the content", () => {+ const element = { scrollHeight: 2000, clientHeight: 500 };+ expect(clampScrollTop(800, element)).toBe(800);+ expect(clampScrollTop(9000, element)).toBe(1500);+ expect(clampScrollTop(-5, element)).toBe(0);+ expect(clampScrollTop(100, { scrollHeight: 300, clientHeight: 500 })).toBe(+ 0+ );+ });+});diff --git a/apps/erp/app/components/Table/useVirtualRows.ts b/apps/erp/app/components/Table/useVirtualRows.tsnew file mode 100644index 0000000000..9338dedcc9--- /dev/null+++ b/apps/erp/app/components/Table/useVirtualRows.ts@@ -0,0 +1,127 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Range, VirtualItem } from "@tanstack/react-virtual";+import { defaultRangeExtractor, useVirtualizer } from "@tanstack/react-virtual";+import type { Key, ReactNode } from "react";+import { useCallback } from "react";++/** The rendered indexes plus `keep` when it is outside them, in order. */+export function withKeptIndex(+ indexes: number[],+ keep: number | undefined,+ count: number+): number[] {+ if (keep === undefined || keep < 0 || keep >= count) return indexes;+ if (indexes.includes(keep)) return indexes;+ return [...indexes, keep].sort((a, b) => a - b);+}++export type VirtualSlot =+ | { kind: "item"; index: number }+ | { kind: "spacer"; key: string; height: number };++/**+ * The items in view, with a spacer standing in for each run of items that is+ * not rendered, so the scroll height and every item's position stay true.+ * `margin` is where the first item starts in the scroll element (the+ * virtualizer's `scrollMargin`).+ */+export function getVirtualSlots(+ items: Pick<VirtualItem, "index" | "start" | "end">[],+ totalSize: number,+ margin: number+): VirtualSlot[] {+ const slots: VirtualSlot[] = [];+ let offset = 0;+ for (const item of items) {+ const start = item.start - margin;+ if (start > offset) {+ slots.push({+ kind: "spacer",+ key: `before-${item.index}`,+ height: start - offset+ });+ }+ slots.push({ kind: "item", index: item.index });+ offset = item.end - margin;+ }+ if (totalSize > offset) {+ slots.push({ kind: "spacer", key: "after", height: totalSize - offset });+ }+ return slots;+}++/**+ * Row virtualization for the Table, the phone list and the Grid: only the+ * rows in view (plus `overscan`) are in the DOM.+ *+ * `keepIndex` names one more index to keep rendered out of view (the row that+ * holds the keyboard focus, or the sticky group header above the view). Pass+ * a memoized function: a new one recomputes the range.+ */+export function useVirtualRows({+ count,+ getScrollElement,+ getItemKey,+ estimateSize,+ overscan,+ scrollMargin = 0,+ scrollPaddingStart,+ keepIndex,+ initialHeight,+ enabled = true+}: {+ count: number;+ getScrollElement: () => HTMLElement | null;+ getItemKey: (index: number) => Key;+ estimateSize: (index: number) => number;+ overscan: number;+ scrollMargin?: number;+ scrollPaddingStart?: number;+ keepIndex?: (range: Range) => number | undefined;+ /** The view height the server and the first render assume, before the+ * scroll element is measured. Without it those renders draw no rows. */+ initialHeight: number;+ enabled?: boolean;+}) {+ const rangeExtractor = useCallback(+ (range: Range) =>+ withKeptIndex(+ defaultRangeExtractor(range),+ keepIndex?.(range),+ range.count+ ),+ [keepIndex]+ );++ const virtualizer = useVirtualizer({+ enabled,+ count,+ getScrollElement,+ getItemKey,+ estimateSize,+ overscan,+ scrollMargin,+ scrollPaddingStart,+ rangeExtractor,+ initialRect: { width: 0, height: initialHeight }+ });++ const renderRows = (+ renderItem: (index: number) => ReactNode,+ renderSpacer: (key: string, height: number) => ReactNode+ ): ReactNode[] =>+ getVirtualSlots(+ virtualizer.getVirtualItems(),+ virtualizer.getTotalSize(),+ scrollMargin+ ).map((slot) =>+ slot.kind === "item"+ ? renderItem(slot.index)+ : renderSpacer(slot.key, slot.height)+ );++ return { virtualizer, renderRows };+}diff --git a/apps/erp/app/components/Table/utils.test.ts b/apps/erp/app/components/Table/utils.test.tsindex 220e1ffdf7..a26110bf1e 100644--- a/apps/erp/app/components/Table/utils.test.ts+++ b/apps/erp/app/components/Table/utils.test.ts@@ -7,6 +7,8 @@ import { describe, expect, it } from "vitest";import {buildColumnMaps,exportOnlyColumn,+ hasUniqueRowIds,+ isServerSortable,selectExportColumns} from "./utils";@@ -104,6 +106,66 @@ describe("buildColumnMaps", () => {expect(exportValues.supplierTypeId).toBe(exportValue);expect(sortKeyToLabel).toEqual({ type: "Type" });});++ it("leaves a sort on another table's column out of the sort picker", () => {+ const { accessors, sortKeyToLabel } = buildColumnMaps(+ cols(+ { accessorKey: "customer.name", header: "Customer" },+ {+ accessorKey: "supplierTypeId",+ header: "Type",+ meta: { sortBy: "supplierType.name" }+ },+ { accessorKey: "type", header: "Kind" }+ )+ );+ // the columns still export+ expect(accessors).toEqual({+ "customer.name": "Customer",+ supplierTypeId: "Type",+ type: "Kind"+ });+ expect(sortKeyToLabel).toEqual({ type: "Kind" });+ });++ it("leaves an enableSorting: false column out of the sort picker", () => {+ const { accessors, sortKeyToLabel } = buildColumnMaps(+ cols({ accessorKey: "type", header: "Type", enableSorting: false })+ );+ expect(accessors).toEqual({ type: "Type" });+ expect(sortKeyToLabel).toEqual({});+ });+});++describe("isServerSortable", () => {+ it("is true for a plain accessor column", () => {+ expect(isServerSortable<Row>({ accessorKey: "type", header: "Type" })).toBe(+ true+ );+ });++ it("is false for a display column, a dotted sort key and enableSorting: false", () => {+ expect(isServerSortable<Row>({ id: "labels", header: "Labels" })).toBe(+ false+ );+ expect(+ isServerSortable<Row>({ accessorKey: "customer.id", header: "Customer" })+ ).toBe(false);+ expect(+ isServerSortable<Row>({+ accessorKey: "supplierTypeId",+ header: "Type",+ meta: { sortBy: "supplierType.name" }+ })+ ).toBe(false);+ expect(+ isServerSortable<Row>({+ accessorKey: "type",+ header: "Type",+ enableSorting: false+ })+ ).toBe(false);+ });});describe("exportOnlyColumn", () => {@@ -174,3 +236,25 @@ describe("selectExportColumns", () => {).toEqual(["type"]);});});++describe("hasUniqueRowIds", () => {+ it("is true when every row has its own id", () => {+ expect(hasUniqueRowIds([{ id: "a" }, { id: "b" }, { id: 3 }])).toBe(true);+ expect(hasUniqueRowIds([])).toBe(true);+ });++ it("is false when an id repeats, is missing or is null", () => {+ expect(hasUniqueRowIds([{ id: "a" }, { id: "a" }])).toBe(false);+ expect(hasUniqueRowIds([{ id: "a" }, { name: "b" }])).toBe(false);+ expect(hasUniqueRowIds([{ id: null }])).toBe(false);+ });++ it("reads another id column", () => {+ expect(hasUniqueRowIds([{ itemId: "a" }, { itemId: "b" }], "itemId")).toBe(+ true+ );+ expect(hasUniqueRowIds([{ itemId: "a" }, { itemId: "a" }], "itemId")).toBe(+ false+ );+ });+});diff --git a/apps/erp/app/components/Table/utils.ts b/apps/erp/app/components/Table/utils.tsindex 47e336fafb..5b8ba87c1c 100644--- a/apps/erp/app/components/Table/utils.ts+++ b/apps/erp/app/components/Table/utils.ts@@ -10,6 +10,18 @@ export function getAccessorKey<T>(columnDef: ColumnDef<T, unknown>) {: undefined;}+// Whether the server can sort the list by this column. Cursor paging compares+// the sort value inside one table, so a sort on another table's column+// (`table.column`) is off, as is a column that opts out with+// `enableSorting: false` (for example a value the list's view does not have).+export function isServerSortable<T>(columnDef: ColumnDef<T, unknown>) {+ const accessorKey = getAccessorKey(columnDef);+ if (!accessorKey) return false;+ if (columnDef.enableSorting === false) return false;+ const sortKey = columnDef.meta?.sortBy ?? accessorKey;+ return !sortKey.includes(".");+}+export interface ColumnMaps<T> {// accessorKey (or column id for display columns) -> header labelaccessors: Record<string, string>;@@ -36,7 +48,7 @@ export function buildColumnMaps<T>(for (const column of columns) {const accessorKey = getAccessorKey(column);- // '_' is the nested-path separator for editable cells (updateNestedProperty).+ // '_' is the nested-path separator for editable cells (`rowEdits.ts`).// Custom-field columns are read-only and keyed by a generated id that may// contain '_', so they are exempt.if (@@ -76,7 +88,7 @@ export function buildColumnMaps<T>(// Sort picker stays keyed on string-header columns only, so JSX-header// columns (e.g. MRP week columns with a filterHeader) never flood it.- if (accessorKey && stringHeader !== undefined) {+ if (accessorKey && stringHeader !== undefined && isServerSortable(column)) {const sortKey = column.meta?.sortBy ?? accessorKey;sortKeyToLabel[sortKey] = stringHeader;}@@ -139,17 +151,23 @@ export function exportOnlyColumn<T>(opts: {};}-export function updateNestedProperty(- obj: object,- path: string | string[],- value: unknown-): unknown {- if (typeof path == "string")- return updateNestedProperty(obj, path.split("_"), value);- else if (path.length == 1 && value !== undefined)- // @ts-expect-error- return (obj[path[0]] = value);- else if (path.length == 0) return obj;- // @ts-expect-error- else return updateNestedProperty(obj[path[0]], path.slice(1), value);+/**+ * True when every row has an id in `idColumn` and no two rows share it. The+ * Table then keys rows by it, so selection and expansion follow the row when+ * pages are appended or rows move. A list that repeats an id keeps index keys.+ */+export function hasUniqueRowIds(+ rows: readonly unknown[],+ idColumn = "id"+): boolean {+ const seen = new Set<string>();+ for (const row of rows) {+ if (!row || typeof row !== "object" || !(idColumn in row)) return false;+ const id = (row as Record<string, unknown>)[idColumn];+ if (id === null || id === undefined) return false;+ const key = String(id);+ if (seen.has(key)) return false;+ seen.add(key);+ }+ return true;}diff --git a/apps/erp/app/hooks/useBulkAction.ts b/apps/erp/app/hooks/useBulkAction.tsnew file mode 100644index 0000000000..756d448941--- /dev/null+++ b/apps/erp/app/hooks/useBulkAction.ts@@ -0,0 +1,119 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { useAction } from "@carbon/query";+import { toast } from "@carbon/react";+import { useLingui } from "@lingui/react/macro";+import { useCallback, useRef } from "react";+import { useBackgroundBulkActionMessage } from "~/components/Table";+import {+ appendBulkSelection,+ type BulkSelection+} from "~/utils/bulk-selection";++/**+ * The client half of the bulk actions' "every matching row" path. Every bulk+ * action route answers such a request with the same shape+ * (`BulkActionStart`, `~/utils/table-jobs`): `{ success: true, background:+ * true }` when the background job started, `{ success: false, message }` when+ * it did not.+ */++/**+ * A function that toasts a route's answer when it is a background start (or+ * a refused one) and says whether it did, so the caller only handles its own+ * results.+ */+export function useBulkStartToast() {+ const backgroundMessage = useBackgroundBulkActionMessage();+ return useCallback(+ (data: unknown): boolean => {+ if (data === null || typeof data !== "object") return false;+ const result = data as {+ success?: unknown;+ background?: unknown;+ message?: unknown;+ };+ if (result.background === true) {+ toast.success(backgroundMessage);+ return true;+ }+ if (result.success === false && typeof result.message === "string") {+ toast.error(result.message);+ return true;+ }+ return false;+ },+ [backgroundMessage]+ );+}++/** What a form-posted bulk action route answers. `done` / `failed` come with+ * an error when some rows were changed before a later chunk failed. */+type BulkFormResult = {+ success?: boolean;+ background?: boolean;+ message?: string;+ error?: { message: string } | null;+ done?: number;+ failed?: number;+};++/**+ * A form-posted bulk action (the item tables' Update, Jobs and Purchase+ * Orders Delete): posts the selection plus the action's own fields and toasts+ * the answer. On success the page revalidates; nothing else is shown.+ * `fetcher` is the same fetcher, for a table's other posts whose error is+ * `{ error: { message } }` too (a row's Duplicate).+ */+export function useBulkFormAction() {+ const { t } = useLingui();+ const showStart = useBulkStartToast();+ const fetcher = useAction<BulkFormResult>({+ onSuccess: (data) => {+ showStart(data);+ },+ onError: (data) => {+ if (showStart(data)) return;+ const message = data.error?.message;+ if (!message) return;+ const { done = 0, failed = 0 } = data;+ toast.error(+ failed > 0+ ? t`Updated ${done}. Could not update ${failed}: ${message}`+ : message+ );+ }+ });++ const submitRef = useRef(fetcher.submit);+ submitRef.current = fetcher.submit;+ const submit = useCallback(+ (+ action: string,+ selection: BulkSelection,+ fields: Record<string, string | null | undefined>+ ) => {+ const formData = appendBulkSelection(new FormData(), selection);+ for (const [name, value] of Object.entries(fields)) {+ if (value !== null && value !== undefined) formData.append(name, value);+ }+ submitRef.current(formData, { method: "post", action });+ },+ []+ );++ return { submit, fetcher };+}++/**+ * The reason a bulk action is disabled for an "every matching row" selection+ * past its row limit (`isOverAllMatchingLimit`). A disabled menu item takes no+ * pointer events, so the item shows it as its second line.+ */+export function useAllMatchingLimitLabel(limit: number) {+ const { t, i18n } = useLingui();+ const rows = i18n.number(limit);+ return t`Filter the list to ${rows} rows or fewer`;+}diff --git a/apps/erp/app/modules/accounting/accounting.journals.test.ts b/apps/erp/app/modules/accounting/accounting.journals.test.tsindex 9f5b3d4044..f050274afd 100644--- a/apps/erp/app/modules/accounting/accounting.journals.test.ts+++ b/apps/erp/app/modules/accounting/accounting.journals.test.ts@@ -40,7 +40,7 @@ function recordingClient() {return { client: { from: () => builder } as any, calls };}-const listArgs = { search: null, status: null, limit: 25, offset: 0 };+const listArgs = { search: null, status: null, limit: 25, cursor: null };describe("getJournalEntries", () => {it("hides Superseded journals when no status is asked for", async () => {diff --git a/apps/erp/app/modules/accounting/accounting.server.ts b/apps/erp/app/modules/accounting/accounting.server.tsindex 859ca8a1b0..3b4f92c697 100644--- a/apps/erp/app/modules/accounting/accounting.server.ts+++ b/apps/erp/app/modules/accounting/accounting.server.ts@@ -28,14 +28,19 @@ import {runTypeOfScheduleRow} from "@carbon/database/run-type";import { getNextSequence } from "@carbon/database/sequence";+import { getLogger } from "@carbon/logger";import type { ReportPeriodBucket } from "@carbon/utils";import { datetime, equals, formatDate, round } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { sql } from "kysely";+import { decodeCursor, toPage } from "~/utils/cursor";+import { listErrorPage } from "~/utils/list-registry/list-error";+import { PAGE_SIZE } from "~/utils/pagination";import {+ ACCOUNT_LEDGER_PAGING,ACCOUNTING_NOT_STARTED,applyCtaToReportPeriodSeries,- getAccountLedger,+ getAccountLedgerLines,getAccountLedgerSummary,getConsolidatedBalances,getConsolidatedPeriodSeries,@@ -52,6 +57,8 @@ import {runPostingTargets} from "./accounting.utils";+const logger = getLogger("erp", "accounting");+/*** The cutover date the enable wizard works against, with the earliest and the* latest date its date picker allows (`activationCutoverDates`), from the@@ -251,47 +258,88 @@ export function getConsolidatedBalancesForReport();}-// Consolidated account drill-down ("All Companies"). Reads via service role so-// the synthetic elimination entities' journal lines (invisible to the user's-// RLS session — no user is a member of them) appear in the ledger and the-// summary ties to the consolidated report. Scoped to the group's own companies-// so a service-role read cannot cross tenants.-export async function getConsolidatedAccountLedger(- companyGroupId: string,+/**+ * One page of an account's ledger lines for the ledger drawers (the chart of+ * accounts and the three statement reports), with the drawer's summary on+ * the first page.+ *+ * "All Companies" (`consolidated`) reads via service role so the synthetic+ * elimination entities' journal lines (invisible to the user's RLS session —+ * no user is a member of them) appear in the ledger and the summary ties to+ * the consolidated report. It is scoped to the group's own companies so a+ * service-role read cannot cross tenants.+ *+ * A failed later page (`after`) returns `listError` for the drawer's list.+ */+export async function getAccountLedgerPage(+ client: SupabaseClient<Database>,args: {accountId: string;+ companyGroupId: string;+ /** One company's lines; null reads every company the client can see. */+ companyId: string | null;+ consolidated?: boolean;startDate: string | null;endDate: string | null;- limit: number;- offset: number;+ /** The `?after=` token; a later page reads its lines only. */+ after: string | null;}) {- const serviceRole = getCarbonServiceRole();- const { data: groupCompanies } = await serviceRole- .from("company")- .select("id")- .eq("companyGroupId", companyGroupId)- .eq("active", true);- const companyIds = (groupCompanies ?? []).map((c) => c.id);+ const cursor = decodeCursor(args.after);+ let readClient = client;+ let companyIds: string[] | undefined;+ if (args.consolidated) {+ readClient = getCarbonServiceRole();+ const { data: groupCompanies } = await readClient+ .from("company")+ .select("id")+ .eq("companyGroupId", args.companyGroupId)+ .eq("active", true);+ companyIds = (groupCompanies ?? []).map((c) => c.id);+ }+ const companyId = args.consolidated ? null : args.companyId;+ const { accountId, startDate, endDate } = args;const [ledger, summary] = await Promise.all([- getAccountLedger(serviceRole, {- accountId: args.accountId,- companyId: null,+ getAccountLedgerLines(readClient, {+ accountId,+ companyId,companyIds,- startDate: args.startDate,- endDate: args.endDate,- limit: args.limit,- offset: args.offset+ startDate,+ endDate,+ limit: PAGE_SIZE,+ cursor}),- getAccountLedgerSummary(serviceRole, companyGroupId, null, {- accountId: args.accountId,- startDate: args.startDate,- endDate: args.endDate- })+ cursor+ ? null+ : getAccountLedgerSummary(readClient, args.companyGroupId, companyId, {+ accountId,+ startDate,+ endDate+ })]);- return { ledger, summary };+ const emptySummary = { opening: 0, netChange: 0, closing: 0 };+ if (ledger.error) {+ logger.error("Failed to load an account ledger page", {+ accountId,+ companyGroupId: args.companyGroupId,+ error: ledger.error+ });+ if (cursor) return listErrorPage("lines");+ }++ const page = toPage(+ ledger.data ?? [],+ { limit: PAGE_SIZE },+ ACCOUNT_LEDGER_PAGING+ );+ return {+ lines: page.rows,+ count: ledger.count ?? 0,+ nextCursor: page.nextCursor,+ summary: summary?.data ?? emptySummary+ };}/**diff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.tsindex c8a43c04a1..4e8ca932c0 100644--- a/apps/erp/app/modules/accounting/accounting.service.ts+++ b/apps/erp/app/modules/accounting/accounting.service.ts@@ -36,7 +36,8 @@ import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";import { sql } from "kysely";import type { z } from "zod";import { getNextSequence } from "~/modules/settings";-import type { GenericQueryFilters } from "~/utils/query";+import type { Cursor } from "~/utils/cursor";+import type { GenericQueryFilters, Paging } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";import type {@@ -198,26 +199,34 @@ export async function getTrialBalance(});}-/** @mcp read */-export async function getAccountLedger(+// Newest first. `setGenericQueryFilters` breaks ties on `id` ascending.+export const ACCOUNT_LEDGER_PAGING: Paging = {+ defaultSorts: [+ { column: "postingDate", ascending: false },+ { column: "journalEntryId", ascending: false }+ ]+};++type AccountLedgerScope = {+ accountId: string;+ companyId: string | null;+ // Consolidated drill-down: restrict to an explicit set of companies (the+ // group's operating companies + elimination entities) so a service-role read+ // doesn't leak across tenants. Ignored when companyId is set.+ companyIds?: string[];+ startDate: string | null;+ endDate: string | null;+};++function accountLedgerQuery(client: SupabaseClient<Database>,- args: {- accountId: string;- companyId: string | null;- // Consolidated drill-down: restrict to an explicit set of companies (the- // group's operating companies + elimination entities) so a service-role read- // doesn't leak across tenants. Ignored when companyId is set.- companyIds?: string[];- startDate: string | null;- endDate: string | null;- limit: number;- offset: number;- }+ args: AccountLedgerScope,+ count: "exact" | undefined) {// TODO: remove the cast once cloud-generated DB types include the view.let query = client.from("journalLines" as any)- .select("*", { count: "exact" })+ .select("*", { count }).eq("accountId", args.accountId).gte("postingDate",@@ -230,18 +239,54 @@ export async function getAccountLedger(} else if (args.companyIds && args.companyIds.length > 0) {query = query.in("companyId", args.companyIds);}+ return query;+}- const result = await query- .order("postingDate", { ascending: false })- .order("journalEntryId", { ascending: false })- .order("id", { ascending: false })- .range(args.offset, args.offset + args.limit - 1);+type AccountLedgerResult = {+ data: AccountLedgerLine[] | null;+ count: number | null;+ error: PostgrestError | null;+};- return result as unknown as {- data: AccountLedgerLine[] | null;- count: number | null;- error: PostgrestError | null;- };+/** @mcp read */+export async function getAccountLedger(+ client: SupabaseClient<Database>,+ args: {+ accountId: string;+ companyId: string | null;+ // Consolidated drill-down: restrict to an explicit set of companies (the+ // group's operating companies + elimination entities) so a service-role read+ // doesn't leak across tenants. Ignored when companyId is set.+ companyIds?: string[];+ startDate: string | null;+ endDate: string | null;+ limit: number;+ offset?: number;+ }+) {+ const result = await setGenericQueryFilters(+ accountLedgerQuery(client, args, "exact"),+ { limit: args.limit, offset: args.offset ?? 0 },+ ACCOUNT_LEDGER_PAGING+ );+ return result as unknown as AccountLedgerResult;+}++/**+ * One cursor page of an account's ledger lines (`limit + 1` rows for+ * `toPage`), for the ledger drawers. Not an MCP tool: MCP and the API page+ * by offset through `getAccountLedger`. Only the first page counts.+ */+export async function getAccountLedgerLines(+ client: SupabaseClient<Database>,+ args: AccountLedgerScope & { limit: number; cursor: Cursor | null }+) {+ const result = await setGenericQueryFilters(+ accountLedgerQuery(client, args, args.cursor ? undefined : "exact"),+ { limit: args.limit, cursor: args.cursor },+ ACCOUNT_LEDGER_PAGING+ );+ return result as unknown as AccountLedgerResult;}/** @mcp read */@@ -4328,6 +4373,10 @@ export async function getPaymentTerm(.single();}+export const PAYMENT_TERMS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getPaymentTerms(client: SupabaseClient<Database>,@@ -4339,7 +4388,7 @@ export async function getPaymentTerms(let query = client.from("paymentTerm").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId).eq("active", true);@@ -4348,9 +4397,7 @@ export async function getPaymentTerms(query = query.ilike("name", `%${args.search}%`);}- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, PAYMENT_TERMS_PAGING);return query;}@@ -4670,6 +4717,10 @@ export async function getProject(.single();}+export const PROJECTS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getProjects(client: SupabaseClient<Database>,@@ -4678,7 +4729,7 @@ export async function getProjects() {let query = client.from("project")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId).eq("active", true);@@ -4688,9 +4739,7 @@ export async function getProjects();}- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, PROJECTS_PAGING);return query;}@@ -4727,6 +4776,10 @@ export async function upsertProject(.single();}+export const DIMENSIONS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getDimensions(client: SupabaseClient<Database>,@@ -4738,7 +4791,7 @@ export async function getDimensions(let query = client.from("dimension").select("*, dimensionValue(id, name)", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyGroupId", companyGroupId).eq("active", true);@@ -4747,9 +4800,7 @@ export async function getDimensions(query = query.ilike("name", `%${args.search}%`);}- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, DIMENSIONS_PAGING);return query;}@@ -5555,6 +5606,10 @@ export async function getConsolidatedBalances(// -- Intercompany --+export const INTERCOMPANY_TRANSACTIONS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getIntercompanyTransactions(client: SupabaseClient<Database>,@@ -5565,7 +5620,7 @@ export async function getIntercompanyTransactions(.from("intercompanyTransaction").select("*, sourceCompany:company!intercompanyTransaction_sourceCompanyId_fkey(name), targetCompany:company!intercompanyTransaction_targetCompanyId_fkey(name)",- { count: LIST_COUNT }+ { count: args.cursor ? undefined : LIST_COUNT }).eq("companyGroupId", companyGroupId);@@ -5573,9 +5628,7 @@ export async function getIntercompanyTransactions(query = query.eq("status", args.status);}- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, INTERCOMPANY_TRANSACTIONS_PAGING);return query;}@@ -5757,6 +5810,15 @@ export async function getExchangeRateHistory(// Manual JEs start as Draft and are posted by flipping status to Posted.// amount > 0 = debit, amount < 0 = credit.+// The enable writes many journals in one transaction, so they share a+// createdAt; the entry number breaks the tie.+export const JOURNAL_ENTRIES_PAGING: Paging = {+ defaultSorts: [+ { column: "createdAt", ascending: false },+ { column: "journalEntryId", ascending: false }+ ]+};+/** @mcp read */export async function getJournalEntries(client: SupabaseClient<Database>,@@ -5765,7 +5827,7 @@ export async function getJournalEntries() {let query = client.from("journalEntries")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {@@ -5792,12 +5854,7 @@ export async function getJournalEntries(query = query.neq("status", "Superseded");}- // The enable writes many journals in one transaction, so they share a- // createdAt; the entry number breaks the tie.- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false },- { column: "journalEntryId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, JOURNAL_ENTRIES_PAGING);return query;}@@ -6728,6 +6785,10 @@ export async function reverseJournalEntry(// -- Asset Classes --+export const FIXED_ASSET_CLASSES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getFixedAssetClasses(client: SupabaseClient<Database>,@@ -6738,7 +6799,7 @@ export async function getFixedAssetClasses(.from("fixedAssetClass").select("id, name, description, depreciationMethod, usefulLifeMonths, residualValuePercent, taxDepreciationMethod, taxUsefulLifeMonths, macrsPropertyClass",- { count: LIST_COUNT }+ { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);@@ -6751,9 +6812,7 @@ export async function getFixedAssetClasses(query = query.ilike("name", `%${args.search}%`);}- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, FIXED_ASSET_CLASSES_PAGING);return query;}@@ -6816,6 +6875,15 @@ export async function deleteFixedAssetClass(// -- Fixed Assets --+// `createdAt` and `updatedAt` are selected for a sort the URL can ask for:+// `toPage` reads every sort column from the row.+const FIXED_ASSETS_LIST_COLUMNS =+ "id,fixedAssetId,fixedAssetClassId,name,serialNumber,status,depreciationMethod,acquisitionCost,accumulatedDepreciation,createdAt,updatedAt,fixedAssetClass:fixedAssetClassId(id, name),location:locationId(id, name)" as const;++export const FIXED_ASSETS_PAGING: Paging = {+ defaultSorts: [{ column: "fixedAssetId", ascending: true }]+};+/** @mcp read */export async function getFixedAssets(client: SupabaseClient<Database>,@@ -6827,10 +6895,9 @@ export async function getFixedAssets() {let query = client.from("fixedAsset")- .select(- "id, fixedAssetId, fixedAssetClassId, name, serialNumber, status, depreciationMethod, acquisitionCost, accumulatedDepreciation, fixedAssetClass:fixedAssetClassId(id, name), location:locationId(id, name)",- { count: LIST_COUNT }- )+ .select(FIXED_ASSETS_LIST_COLUMNS, {+ count: args.cursor ? undefined : LIST_COUNT+ }).eq("companyId", companyId);if (args.search) {@@ -6843,9 +6910,7 @@ export async function getFixedAssets(query = query.eq("status", args.status);}- query = setGenericQueryFilters(query, args, [- { column: "fixedAssetId", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, FIXED_ASSETS_PAGING);return query;}@@ -7390,6 +7455,10 @@ export async function deleteDepreciationRun(// -- Depreciation --+export const DEPRECIATION_RUNS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getDepreciationRuns(client: SupabaseClient<Database>,@@ -7398,8 +7467,8 @@ export async function getDepreciationRuns() {let query = client.from("depreciationRun")- .select("id, depreciationRunId, periodEnd, status, postedAt", {- count: LIST_COUNT+ .select("id, depreciationRunId, periodEnd, status, postedAt, createdAt", {+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -7407,9 +7476,7 @@ export async function getDepreciationRuns(query = query.ilike("depreciationRunId", `%${args.search}%`);}- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, DEPRECIATION_RUNS_PAGING);return query;}@@ -7443,6 +7510,10 @@ export async function getDepreciationRunLines(// -- Revenue Recognition --+export const PERIOD_RUNS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getRevenueRecognitionRuns(client: SupabaseClient<Database>,@@ -7452,9 +7523,10 @@ export async function getRevenueRecognitionRuns() {let query = client.from("revenueRecognitionRun")- .select("id, runId, type, periodEnd, status, postedAt, journalId", {- count: "exact"- })+ .select(+ "id, runId, type, periodEnd, status, postedAt, journalId, createdAt",+ { count: args.cursor ? undefined : "exact" }+ ).eq("companyId", companyId).eq("type", type);@@ -7462,9 +7534,7 @@ export async function getRevenueRecognitionRuns(query = query.ilike("runId", `%${args.search}%`);}- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, PERIOD_RUNS_PAGING);return query;}@@ -8486,6 +8556,10 @@ export async function upsertFixedAssetUsageLog(// -- Fleet --+export const FLEET_ASSETS_PAGING: Paging = {+ defaultSorts: [{ column: "fixedAssetId", ascending: true }]+};+/** @mcp read */export async function getFleetAssets(client: SupabaseClient<Database>,@@ -8497,7 +8571,7 @@ export async function getFleetAssets() {let query = client.from("fleetAssets")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {@@ -8510,9 +8584,7 @@ export async function getFleetAssets(query = query.eq("fleetStatus", args.fleetStatus);}- query = setGenericQueryFilters(query, args, [- { column: "fixedAssetId", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, FLEET_ASSETS_PAGING);return query;}diff --git a/apps/erp/app/modules/accounting/period-runs.server.ts b/apps/erp/app/modules/accounting/period-runs.server.tsindex 475ef52f41..987ee32ce5 100644--- a/apps/erp/app/modules/accounting/period-runs.server.ts+++ b/apps/erp/app/modules/accounting/period-runs.server.ts@@ -19,60 +19,41 @@ import { serverFns } from "@carbon/server-functions";import { datetime, redirect } from "@carbon/utils";import { endOfMonth, parseDate } from "@internationalized/date";import { getDatabaseClient } from "~/services/database.server";+import { periodRunsLists } from "~/utils/list-registry/accounting.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";import { getCompanyTimeZone } from "../shared/timezone.server";import { revenueRecognitionRunValidator } from "./accounting.models";import { futureRunPeriodError } from "./accounting.server";-import { getRevenueRecognitionRuns } from "./accounting.service";import { getNextRevenueRecognitionPeriodEnd } from "./accounting.utils";import { RUN_PAGES } from "./ui/RevenueRecognition/runPages";export async function loadPeriodRuns(request: Request, type: RunType) {- const { client, companyId } = await requirePermissions(request, {- view: "accounting",- role: "employee"+ return loadListPage(request, periodRunsLists[type], {+ dataKey: "data",+ firstPage: async ({ client, companyId }) => {+ const lastRun = await client+ .from("revenueRecognitionRun")+ .select("periodEnd, status")+ .eq("companyId", companyId)+ .eq("type", type)+ .order("periodEnd", { ascending: false })+ .limit(1);++ const lastRunData =+ lastRun.data && lastRun.data.length > 0 ? lastRun.data[0] : null;+ // The proposed period: the month after the last run, or the month just+ // closed in the company's calendar when there is no run yet.+ const nextPeriodEnd = getNextRevenueRecognitionPeriodEnd(+ lastRunData?.periodEnd ?? null,+ datetime.today(await getCompanyTimeZone(client, companyId)).toString()+ );+ return {+ nextPeriodEnd,+ hasDraftBlocking: lastRunData?.status === "Draft"+ };+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [runs, lastRun] = await Promise.all([- getRevenueRecognitionRuns(client, companyId, type, {- search,- limit,- offset,- sorts,- filters- }),- client- .from("revenueRecognitionRun")- .select("periodEnd, status")- .eq("companyId", companyId)- .eq("type", type)- .order("periodEnd", { ascending: false })- .limit(1)- ]);-- const lastRunData =- lastRun.data && lastRun.data.length > 0 ? lastRun.data[0] : null;- // The proposed period: the month after the last run, or the month just- // closed in the company's calendar when there is no run yet.- const nextPeriodEnd = getNextRevenueRecognitionPeriodEnd(- lastRunData?.periodEnd ?? null,- datetime.today(await getCompanyTimeZone(client, companyId)).toString()- );- const hasDraftBlocking = lastRunData?.status === "Draft";-- return {- data: runs.data ?? [],- count: runs.count ?? 0,- nextPeriodEnd,- hasDraftBlocking- };}export async function proposePeriodRun(diff --git a/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTree.tsx b/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTree.tsxindex 97d747a6e0..55bae6a00f 100644--- a/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTree.tsx+++ b/apps/erp/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTree.tsx@@ -117,9 +117,7 @@ const ChartOfAccountsTree = memo(const [params] = useUrlParams();const openLedger = (accountId: string) => {- const nextParams = new URLSearchParams(params);- nextParams.delete("offset");- const qs = nextParams.toString();+ const qs = params.toString();const to = path.to.chartOfAccountsLedger(accountId);navigate(qs ? `${to}?${qs}` : to);};diff --git a/apps/erp/app/modules/accounting/ui/Dimensions/DimensionsTable.tsx b/apps/erp/app/modules/accounting/ui/Dimensions/DimensionsTable.tsxindex 1c05178936..2a93571251 100644--- a/apps/erp/app/modules/accounting/ui/Dimensions/DimensionsTable.tsx+++ b/apps/erp/app/modules/accounting/ui/Dimensions/DimensionsTable.tsx@@ -24,9 +24,12 @@ import type { Dimension } from "../../types";type DimensionsTableProps = {data: Dimension[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const DimensionsTable = memo(({ data, count }: DimensionsTableProps) => {+const DimensionsTable = memo((props: DimensionsTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -131,6 +134,11 @@ const DimensionsTable = memo(({ data, count }: DimensionsTableProps) => {return (<Table<Dimension>+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "accounting-dimensions"+ }}data={data}columns={columns}count={count}diff --git a/apps/erp/app/modules/accounting/ui/FixedAssets/AssetClassesTable.tsx b/apps/erp/app/modules/accounting/ui/FixedAssets/AssetClassesTable.tsxindex 105e647890..ad45f63a41 100644--- a/apps/erp/app/modules/accounting/ui/FixedAssets/AssetClassesTable.tsx+++ b/apps/erp/app/modules/accounting/ui/FixedAssets/AssetClassesTable.tsx@@ -30,6 +30,8 @@ import type { FixedAssetClassListItem } from "../../types";type AssetClassesTableProps = {data: FixedAssetClassListItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;taxDepreciationEnabled: boolean;primaryAction?: ReactNode;};@@ -39,7 +41,8 @@ const AssetClassesTable = memo(data,count,taxDepreciationEnabled,- primaryAction+ primaryAction,+ nextCursor}: AssetClassesTableProps) => {const { t } = useLingui();const navigate = useNavigate();@@ -150,6 +153,11 @@ const AssetClassesTable = memo(return (<><Table<FixedAssetClassListItem>+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "asset-classes"+ }}data={data}columns={columns}count={count}diff --git a/apps/erp/app/modules/accounting/ui/FixedAssets/DepreciationRunTable.tsx b/apps/erp/app/modules/accounting/ui/FixedAssets/DepreciationRunTable.tsxindex 70149f29f7..14aec54d49 100644--- a/apps/erp/app/modules/accounting/ui/FixedAssets/DepreciationRunTable.tsx+++ b/apps/erp/app/modules/accounting/ui/FixedAssets/DepreciationRunTable.tsx@@ -24,11 +24,13 @@ import DepreciationRunStatus from "./DepreciationRunStatus";type DepreciationRunTableProps = {data: DepreciationRunListItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;primaryAction?: ReactNode;};const DepreciationRunTable = memo(- ({ data, count, primaryAction }: DepreciationRunTableProps) => {+ ({ data, count, primaryAction, nextCursor }: DepreciationRunTableProps) => {const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -126,6 +128,11 @@ const DepreciationRunTable = memo(return (<><Table<DepreciationRunListItem>+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "depreciation-runs"+ }}data={data}columns={columns}count={count}diff --git a/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetsTable.tsx b/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetsTable.tsxindex 1e16055cac..c3e038396d 100644--- a/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetsTable.tsx+++ b/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetsTable.tsx@@ -41,12 +41,20 @@ import FixedAssetStatus from "./FixedAssetStatus";type FixedAssetsTableProps = {data: FixedAssetListItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;assetClasses: { id: string; name: string }[];primaryAction?: ReactNode;};const FixedAssetsTable = memo(- ({ data, count, assetClasses, primaryAction }: FixedAssetsTableProps) => {+ ({+ data,+ count,+ assetClasses,+ primaryAction,+ nextCursor+ }: FixedAssetsTableProps) => {const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -218,6 +226,11 @@ const FixedAssetsTable = memo(return (<><Table<FixedAssetListItem>+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "fixed-assets"+ }}data={data}columns={columns}count={count}diff --git a/apps/erp/app/modules/accounting/ui/FixedAssets/FleetAssetsTable.tsx b/apps/erp/app/modules/accounting/ui/FixedAssets/FleetAssetsTable.tsxindex 525cf39573..60dc838a5d 100644--- a/apps/erp/app/modules/accounting/ui/FixedAssets/FleetAssetsTable.tsx+++ b/apps/erp/app/modules/accounting/ui/FixedAssets/FleetAssetsTable.tsx@@ -38,6 +38,8 @@ export type FleetAssetRow = NonNullable<type FleetAssetsTableProps = {data: FleetAssetRow[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;primaryAction?: ReactNode;};@@ -47,7 +49,7 @@ const isOnBooks = (row: FleetAssetRow) =>row.status === "Active" || row.status === "Fully Depreciated";const FleetAssetsTable = memo(- ({ data, count, primaryAction }: FleetAssetsTableProps) => {+ ({ data, count, primaryAction, nextCursor }: FleetAssetsTableProps) => {const { t } = useLingui();const navigate = useNavigate();const fetcher = useFetcher();@@ -229,6 +231,11 @@ const FleetAssetsTable = memo(return (<Table<FleetAssetRow>+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "fleet-assets"+ }}data={data}columns={columns}count={count}diff --git a/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionTable.tsx b/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionTable.tsxindex 7d392dfe7a..66a9da81f4 100644--- a/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionTable.tsx+++ b/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionTable.tsx@@ -36,11 +36,18 @@ type IntercompanyTransaction = {type IntercompanyTransactionTableProps = {data: IntercompanyTransaction[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;primaryAction?: ReactNode;};const IntercompanyTransactionTable = memo(- ({ data, count, primaryAction }: IntercompanyTransactionTableProps) => {+ ({+ data,+ count,+ primaryAction,+ nextCursor+ }: IntercompanyTransactionTableProps) => {const { t } = useLingui();// Currency varies per row, so the formatter is built per cell from the// app locale rather than a single-currency hook instance.@@ -52,6 +59,8 @@ const IntercompanyTransactionTable = memo(accessorKey: "sourceCompany",header: t`Source`,cell: ({ row }) => row.original.sourceCompany?.name ?? "—",+ // An embedded company, not a column of the list: no server sort.+ enableSorting: false,meta: {icon: <LuBuilding2 />}@@ -60,6 +69,7 @@ const IntercompanyTransactionTable = memo(accessorKey: "targetCompany",header: t`Target`,cell: ({ row }) => row.original.targetCompany?.name ?? "—",+ enableSorting: false,meta: {mobile: "P3",icon: <LuBuilding2 />@@ -133,6 +143,11 @@ const IntercompanyTransactionTable = memo(return (<Table<IntercompanyTransaction>+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "intercompany-transactions"+ }}data={data}columns={columns}count={count}diff --git a/apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntriesTable.tsx b/apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntriesTable.tsxindex 014f9773be..36a14bb0b5 100644--- a/apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntriesTable.tsx+++ b/apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntriesTable.tsx@@ -43,6 +43,8 @@ import JournalEntryStatus from "./JournalEntryStatus";type JournalEntriesTableProps = {data: JournalEntryListItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;primaryAction?: ReactNode;};@@ -55,7 +57,7 @@ const defaultColumnVisibility = {};const JournalEntriesTable = memo(- ({ data, count, primaryAction }: JournalEntriesTableProps) => {+ ({ data, count, primaryAction, nextCursor }: JournalEntriesTableProps) => {const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -279,6 +281,11 @@ const JournalEntriesTable = memo(return (<><Table<JournalEntryListItem>+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "journal-entries"+ }}data={data}columns={columns}count={count}diff --git a/apps/erp/app/modules/accounting/ui/PaymentTerms/PaymentTermsTable.tsx b/apps/erp/app/modules/accounting/ui/PaymentTerms/PaymentTermsTable.tsxindex 1791e1c37e..c8d141a6f3 100644--- a/apps/erp/app/modules/accounting/ui/PaymentTerms/PaymentTermsTable.tsx+++ b/apps/erp/app/modules/accounting/ui/PaymentTerms/PaymentTermsTable.tsx@@ -26,9 +26,12 @@ import type { PaymentTerm } from "../../types";type PaymentTermsTableProps = {data: PaymentTerm[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const PaymentTermsTable = memo(({ data, count }: PaymentTermsTableProps) => {+const PaymentTermsTable = memo((props: PaymentTermsTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -129,6 +132,11 @@ const PaymentTermsTable = memo(({ data, count }: PaymentTermsTableProps) => {return (<Table<PaymentTerm>+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "payment-terms"+ }}data={data}columns={columns}count={count}diff --git a/apps/erp/app/modules/accounting/ui/Projects/ProjectsTable.tsx b/apps/erp/app/modules/accounting/ui/Projects/ProjectsTable.tsxindex b8b39596a1..21285051e2 100644--- a/apps/erp/app/modules/accounting/ui/Projects/ProjectsTable.tsx+++ b/apps/erp/app/modules/accounting/ui/Projects/ProjectsTable.tsx@@ -21,9 +21,12 @@ import type { Project } from "../../types";type ProjectsTableProps = {data: Project[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const ProjectsTable = memo(({ data, count }: ProjectsTableProps) => {+const ProjectsTable = memo((props: ProjectsTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -88,6 +91,11 @@ const ProjectsTable = memo(({ data, count }: ProjectsTableProps) => {return (<Table<Project>+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "projects"+ }}data={data}columns={columns}count={count}diff --git a/apps/erp/app/modules/accounting/ui/Reports/AccountLedgerDrawer.tsx b/apps/erp/app/modules/accounting/ui/Reports/AccountLedgerDrawer.tsxindex 222cca0bcf..3db568e632 100644--- a/apps/erp/app/modules/accounting/ui/Reports/AccountLedgerDrawer.tsx+++ b/apps/erp/app/modules/accounting/ui/Reports/AccountLedgerDrawer.tsx@@ -9,7 +9,6 @@ import {DrawerContent,DrawerHeader,DrawerTitle,- IconButton,PrefetchLink,Table,Tbody,@@ -20,8 +19,10 @@ import {} from "@carbon/react";import { toDisplayCredit, toDisplayDebit } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";-import { LuChevronLeft, LuChevronRight } from "react-icons/lu";import { useNavigate } from "react-router";+import { InfiniteStatus } from "~/components/Table/components/InfiniteStatus";+import { useInfiniteRows } from "~/components/Table/useInfiniteRows";+import { useInfiniteScroll } from "~/components/Table/useInfiniteScroll";import { useUrlParams } from "~/hooks";import type {AccountClass,@@ -43,8 +44,8 @@ type AccountLedgerDrawerProps = {summary: AccountLedgerSummary;startDate: string | null;endDate: string | null;- offset: number;- limit: number;+ /** The loader's `nextCursor`: null when the first page is every line. */+ nextCursor: string | null;backTo: string;};@@ -70,18 +71,24 @@ const AccountLedgerDrawer = ({summary,startDate,endDate,- offset,- limit,+ nextCursor,backTo}: AccountLedgerDrawerProps) => {const { t } = useLingui();const navigate = useNavigate();- const [params, setParams] = useUrlParams();+ const [params] = useUrlParams();++ // The first page comes from the loader; later pages load as the drawer+ // body scrolls to its end.+ const ledger = useInfiniteRows<AccountLedgerLine>({+ initialRows: lines,+ infinite: { dataKey: "lines", nextCursor }+ });+ const { rows, hasMore, loadError, retry, totalLoaded } = ledger;+ const endRef = useInfiniteScroll(ledger, { root: "auto" });const onClose = () => {- const backParams = new URLSearchParams(params);- backParams.delete("offset");- const search = backParams.toString();+ const search = new URLSearchParams(params).toString();navigate(search ? `${backTo}?${search}` : backTo);};@@ -95,8 +102,6 @@ const AccountLedgerDrawer = ({: t`All Time`;const accountClass = (account.class ?? "Asset") as AccountClass;- const from = count === 0 ? 0 : offset + 1;- const to = Math.min(offset + limit, count);return (<Drawer@@ -143,7 +148,7 @@ const AccountLedgerDrawer = ({</p></div></div>- {lines.length === 0 ? (+ {rows.length === 0 ? (<div className="flex w-full items-center justify-center py-16 text-sm text-muted-foreground"><Trans>No transactions in this period</Trans></div>@@ -169,7 +174,7 @@ const AccountLedgerDrawer = ({</Tr></Thead><Tbody>- {lines.map((line) => {+ {rows.map((line) => {const debit = toDisplayDebit(line.amount, accountClass);const credit = toDisplayCredit(line.amount, accountClass);return (@@ -210,36 +215,21 @@ const AccountLedgerDrawer = ({</Tbody></Table>)}- {count > limit && (- <div className="flex w-full items-center justify-between border-t border-border px-4 py-2">- <p className="text-xs text-muted-foreground tabular-nums">+ {(hasMore || loadError) && (+ <div+ ref={endRef}+ className="flex w-full items-center justify-between gap-3 border-t border-border px-4 py-3 text-sm text-muted-foreground"+ >+ <InfiniteStatus+ isLoading={hasMore}+ loadError={loadError}+ onRetry={retry}+ />+ <p className="text-xs tabular-nums"><Trans>- {from}–{to} of {count}+ {totalLoaded} of {count}</Trans></p>- <div className="flex items-center gap-1">- <IconButton- aria-label={t`Previous page`}- variant="ghost"- size="sm"- icon={<LuChevronLeft />}- isDisabled={offset === 0}- onClick={() =>- setParams({- offset:- offset - limit > 0 ? String(offset - limit) : undefined- })- }- />- <IconButton- aria-label={t`Next page`}- variant="ghost"- size="sm"- icon={<LuChevronRight />}- isDisabled={offset + limit >= count}- onClick={() => setParams({ offset: String(offset + limit) })}- />- </div></div>)}</DrawerBody>diff --git a/apps/erp/app/modules/accounting/ui/Reports/MultiPeriodStatementTree.tsx b/apps/erp/app/modules/accounting/ui/Reports/MultiPeriodStatementTree.tsxindex e66465d1e1..b5c6c0b407 100644--- a/apps/erp/app/modules/accounting/ui/Reports/MultiPeriodStatementTree.tsx+++ b/apps/erp/app/modules/accounting/ui/Reports/MultiPeriodStatementTree.tsx@@ -139,9 +139,7 @@ const MultiPeriodStatementTree = memo(const openLedger = (accountId: string) => {if (!ledgerPath) return;- const nextParams = new URLSearchParams(params);- nextParams.delete("offset");- const qs = nextParams.toString();+ const qs = params.toString();navigate(qs ? `${ledgerPath(accountId)}?${qs}` : ledgerPath(accountId));};diff --git a/apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTree.tsx b/apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTree.tsxindex 1430b732c8..734fa958f2 100644--- a/apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTree.tsx+++ b/apps/erp/app/modules/accounting/ui/Reports/TrialBalanceTree.tsx@@ -89,9 +89,7 @@ const TrialBalanceTree = memo(const openLedger = (accountId: string) => {if (!ledgerPath) return;- const nextParams = new URLSearchParams(params);- nextParams.delete("offset");- const qs = nextParams.toString();+ const qs = params.toString();navigate(qs ? `${ledgerPath(accountId)}?${qs}` : ledgerPath(accountId));};diff --git a/apps/erp/app/modules/accounting/ui/RevenueRecognition/PeriodRunsPage.tsx b/apps/erp/app/modules/accounting/ui/RevenueRecognition/PeriodRunsPage.tsxindex 3f240351b2..1994ed2da1 100644--- a/apps/erp/app/modules/accounting/ui/RevenueRecognition/PeriodRunsPage.tsx+++ b/apps/erp/app/modules/accounting/ui/RevenueRecognition/PeriodRunsPage.tsx@@ -32,6 +32,8 @@ type PeriodRunsPageProps = {type: RunType;data: RevenueRecognitionRunListItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;nextPeriodEnd: string;hasDraftBlocking: boolean;};@@ -41,6 +43,7 @@ export default function PeriodRunsPage({type,data,count,+ nextCursor,nextPeriodEnd,hasDraftBlocking}: PeriodRunsPageProps) {@@ -66,6 +69,7 @@ export default function PeriodRunsPage({type={type}data={data}count={count}+ nextCursor={nextCursor}primaryAction={permissions.can("create", "accounting") && (<TooltipProvider>diff --git a/apps/erp/app/modules/accounting/ui/RevenueRecognition/RevenueRecognitionRunsTable.tsx b/apps/erp/app/modules/accounting/ui/RevenueRecognition/RevenueRecognitionRunsTable.tsxindex 2f4cabec51..c8999df3d7 100644--- a/apps/erp/app/modules/accounting/ui/RevenueRecognition/RevenueRecognitionRunsTable.tsx+++ b/apps/erp/app/modules/accounting/ui/RevenueRecognition/RevenueRecognitionRunsTable.tsx@@ -27,11 +27,19 @@ type RevenueRecognitionRunsTableProps = {type: RunType;data: RevenueRecognitionRunListItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;primaryAction?: ReactNode;};const RevenueRecognitionRunsTable = memo(- ({ type, data, count, primaryAction }: RevenueRecognitionRunsTableProps) => {+ ({+ type,+ data,+ count,+ primaryAction,+ nextCursor+ }: RevenueRecognitionRunsTableProps) => {const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -121,6 +129,12 @@ const RevenueRecognitionRunsTable = memo(return (<><Table<RevenueRecognitionRunListItem>+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey:+ type === "Lease" ? "lease-runs" : "revenue-recognition-runs"+ }}data={data}columns={columns}count={count}diff --git a/apps/erp/app/modules/documents/documents.service.ts b/apps/erp/app/modules/documents/documents.service.tsindex 04bf92cc30..58752454d8 100644--- a/apps/erp/app/modules/documents/documents.service.ts+++ b/apps/erp/app/modules/documents/documents.service.ts@@ -8,7 +8,7 @@ import { isHeic } from "@carbon/files/media";import { trigger } from "@carbon/jobs";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";-import type { GenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";import { getDocumentType } from "../shared/shared.service";@@ -63,6 +63,19 @@ export async function getDocument(return client.from("documents").select("*").eq("id", documentId).single();}+export const DOCUMENTS_PAGING: Paging = {+ defaultSorts: [{ column: "favorite", ascending: false }]+};++// The "Recent" view: the last activity first. It is a default sort, so the+// cursor follows it and a sort the user picks replaces it.+export const RECENT_DOCUMENTS_PAGING: Paging = {+ defaultSorts: [+ { column: "lastActivityAt", ascending: false },+ ...DOCUMENTS_PAGING.defaultSorts+ ]+};+/** @mcp read */export async function getDocuments(client: SupabaseClient<Database>,@@ -78,7 +91,7 @@ export async function getDocuments(let query = client.from("documents").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId).eq("active", args.active);@@ -93,13 +106,11 @@ export async function getDocuments(query = query.eq("favorite", true);}- if (args.recent) {- query = query.order("lastActivityAt", { ascending: false });- }-- query = setGenericQueryFilters(query, args, [- { column: "favorite", ascending: false }- ]);+ query = setGenericQueryFilters(+ query,+ args,+ args.recent ? RECENT_DOCUMENTS_PAGING : DOCUMENTS_PAGING+ );return query;}diff --git a/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx b/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsxindex 69dadd97e3..c28fa04c5a 100644--- a/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx+++ b/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx@@ -27,7 +27,7 @@ import {import { filterEmpty } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";-import { memo, useCallback, useEffect, useMemo, useState } from "react";+import { memo, useCallback, useMemo, useRef, useState } from "react";import { IoMdAdd } from "react-icons/io";import {LuBookMarked,@@ -48,6 +48,12 @@ import { DateTime, EmployeeAvatar, Hyperlink, Table } from "~/components";import DocumentIcon from "~/components/DocumentIcon";import { Enumerable } from "~/components/Enumerable";import { Confirm, ConfirmDelete } from "~/components/Modals";+import {+ applyRowEdits,+ type RowEdits,+ tick+} from "~/components/Table/rowEdits";+import { useInfiniteRows } from "~/components/Table/useInfiniteRows";import { usePermissions, useUrlParams } from "~/hooks";import { documentTypes } from "~/modules/shared";import { usePeople } from "~/stores";@@ -57,15 +63,27 @@ import type { Document, DocumentLabel } from "../../types";import DocumentCreateForm from "./DocumentCreateForm";import { useDocument } from "./useDocument";+const documentId = (row: Document) => row.id ?? "";+type DocumentsTableProps = {data: Document[];count: number;+ nextCursor: string | null;+ // "documents", or "recent-documents" for the Recent view.+ listKey: string;labels: DocumentLabel[];extensions: (string | null)[];};const DocumentsTable = memo(- ({ data, count, labels, extensions }: DocumentsTableProps) => {+ ({+ data,+ count,+ nextCursor,+ listKey,+ labels,+ extensions+ }: DocumentsTableProps) => {const { t } = useLingui();const { isPhone } = useViewport();const permissions = usePermissions();@@ -73,13 +91,24 @@ const DocumentsTable = memo(const [params] = useUrlParams();const filter = params.get("q");- // put rows in state for use with optimistic ui updates- const [rows, setRows] = useState<Document[]>(data);- // we have to do this useEffect silliness since we're putitng rows- // in state for optimistic ui updates- useEffect(() => {- setRows(data);- }, [data]);+ const infiniteRows = useInfiniteRows<Document>({+ initialRows: data,+ infinite: { dataKey: "documents", nextCursor, listKey }+ });+ // The user's star and label changes by document id, laid over the loaded+ // rows until a load that started after the write (`rowEdits.ts`).+ const [overrides, setOverrides] = useState<RowEdits>({});+ const rows = useMemo(() => {+ const edited = applyRowEdits(+ infiniteRows.rows,+ overrides,+ documentId,+ infiniteRows.syncedAt+ );+ return filter === "starred"+ ? edited.filter((item) => item.favorite === true)+ : edited;+ }, [infiniteRows.rows, infiniteRows.syncedAt, overrides, filter]);const {canUpdate,@@ -113,6 +142,42 @@ const DocumentsTable = memo([labels]);+ // Shows the change at once, writes it, then reloads the rows. The change+ // stays until a load that started after the write. `row` is the row on+ // screen, so an earlier change that is still showing is kept.+ const writesRef = useRef(new Map<string, number>());+ const writeOverride = useCallback(+ async (+ row: Document,+ values: Partial<Pick<Document, "favorite" | "labels">>,+ mutate: () => PromiseLike<unknown> | undefined+ ) => {+ const id = documentId(row);+ const write = (writesRef.current.get(id) ?? 0) + 1;+ writesRef.current.set(id, write);+ setOverrides((prev) => ({+ ...prev,+ [id]: {+ values: { favorite: row.favorite, labels: row.labels, ...values },+ at: Number.POSITIVE_INFINITY+ }+ }));+ try {+ await mutate();+ } finally {+ // Only the last write of a row dates its change.+ if (writesRef.current.get(id) === write) {+ const at = tick();+ setOverrides((prev) =>+ prev[id] ? { ...prev, [id]: { ...prev[id], at } } : prev+ );+ }+ revalidator.revalidate();+ }+ },+ [revalidator]+ );+const onDeleteLabel = useCallback(async (e: React.MouseEvent<HTMLButtonElement, MouseEvent>,@@ -120,61 +185,27 @@ const DocumentsTable = memo(label: string) => {e.stopPropagation();- // optimistically update the UI and then make the mutation- setRows((prev) => {- const index = prev.findIndex((item) => item.id === row.id);- const updated = [...prev];- const labelIndex = updated[index].labels?.findIndex(- (item: string) => item === label- );- if (labelIndex) {- updated[index].labels?.splice(labelIndex, 1);- }- return updated;- });- // mutate the database- await deleteLabel(row, label);+ await writeOverride(+ row,+ { labels: (row.labels ?? []).filter((item) => item !== label) },+ () => deleteLabel(row, label)+ );},- [deleteLabel]+ [deleteLabel, writeOverride]);const onLabel = useCallback(- async (row: Document, labels: string[]) => {- // optimistically update the UI and then make the mutation- setRows((prev) => {- const index = prev.findIndex((item) => item.id === row.id);- const updated = [...prev];- updated[index] = {- ...updated[index],- labels: labels.sort()- };- return updated;- });- // mutate the database- await label(row, labels);- },- [label]+ (row: Document, labels: string[]) =>+ writeOverride(row, { labels: [...labels].sort() }, () =>+ label(row, labels)+ ),+ [label, writeOverride]);- // TODO: rows shouldn't be in state -- we should use optimistic updates like purchase order favoritesconst onFavorite = useCallback(- async (row: Document) => {- // optimistically update the UI and then make the mutation- setRows((prev) => {- const index = prev.findIndex((item) => item.id === row.id);- const updated = [...prev];- updated[index] = {- ...updated[index],- favorite: !updated[index].favorite- };- return filter === "starred"- ? updated.filter((item) => item.favorite === true)- : updated;- });- // mutate the database- await favorite(row);- },- [favorite, filter]+ (row: Document) =>+ writeOverride(row, { favorite: !row.favorite }, () => favorite(row)),+ [favorite, writeOverride]);// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration@@ -280,13 +311,12 @@ const DocumentsTable = memo(newValue])}- onCreateOption={async (newValue) => {- await onLabel(row.original, [+ onCreateOption={(newValue) =>+ onLabel(row.original, [...(row.original.labels ?? []),newValue- ]);- revalidator.revalidate();- }}+ ])+ }/></PopoverContent></Popover>@@ -418,7 +448,6 @@ const DocumentsTable = memo(}}];- // Don't put the revalidator in the deps array}, [ERP_URL,extensions,@@ -508,7 +537,8 @@ const DocumentsTable = memo(<Table<Document>count={count}columns={columns}- data={rows}+ data={data}+ infiniteRows={{ ...infiniteRows, rows }}defaultColumnVisibility={defaultColumnVisibility}primaryAction={permissions.can("create", "documents") &&diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex 56bdf1dc26..0b954f0dae 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -20,7 +20,7 @@ import { nanoid } from "nanoid";import type { z } from "zod";import { getNextSequence } from "~/modules/settings/settings.service";import type { StorageItem } from "~/types";-import type { GenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";import {LIST_COUNT,setGenericQueryFilters,@@ -336,6 +336,10 @@ export async function getBatchProperties(.order("sortOrder");}+export const INVENTORY_ITEMS_PAGING: Paging = {+ defaultSorts: [{ column: "readableIdWithRevision", ascending: true }]+};+/** @mcp read */export async function getInventoryItems(client: SupabaseClient<Database>,@@ -352,7 +356,8 @@ export async function getInventoryItems(company_id: companyId},{- count: LIST_COUNT+ // Later pages (`cursor`) skip the count: the first page already has it.+ count: args.cursor ? undefined : LIST_COUNT});@@ -361,9 +366,7 @@ export async function getInventoryItems("readableIdWithRevision"]);- query = setGenericQueryFilters(query, args, [- { column: "readableIdWithRevision", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, INVENTORY_ITEMS_PAGING);return query;}@@ -532,6 +535,10 @@ export async function createInventoryReconciliationJournal(}}+export const KANBANS_PAGING: Paging = {+ defaultSorts: [{ column: "readableIdWithRevision", ascending: true }]+};+/** @mcp read */export async function getKanbans(client: SupabaseClient<Database>,@@ -544,7 +551,7 @@ export async function getKanbans(let query = client.from("kanbans").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId).eq("locationId", locationId);@@ -555,9 +562,7 @@ export async function getKanbans();}- query = setGenericQueryFilters(query, args, [- { column: "readableIdWithRevision", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, KANBANS_PAGING);return query;}@@ -628,6 +633,10 @@ export async function getStockTransferTracking(.eq("companyId", companyId);}+export const STOCK_TRANSFERS_PAGING: Paging = {+ defaultSorts: [{ column: "stockTransferId", ascending: false }]+};+/** @mcp read */export async function getStockTransfers(client: SupabaseClient<Database>,@@ -640,7 +649,7 @@ export async function getStockTransfers(let query = client.from("stockTransfer").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -652,9 +661,7 @@ export async function getStockTransfers(query = query.eq("locationId", args.locationId);}- query = setGenericQueryFilters(query, args, [- { column: "stockTransferId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, STOCK_TRANSFERS_PAGING);return query;}@@ -695,6 +702,10 @@ export async function getDefaultStorageUnitOrStorageUnitWithHighestQuantity(return storageUnitWithHighestQuantity?.storageUnitId ?? null;}+export const RECEIPTS_PAGING: Paging = {+ defaultSorts: [{ column: "receiptId", ascending: false }]+};+/** @mcp read */export async function getReceipts(client: SupabaseClient<Database>,@@ -706,7 +717,7 @@ export async function getReceipts(let query = client.from("receipt").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId).neq("sourceDocumentId", "");@@ -717,9 +728,7 @@ export async function getReceipts();}- query = setGenericQueryFilters(query, args, [- { column: "receiptId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, RECEIPTS_PAGING);return query;}@@ -1122,6 +1131,10 @@ export async function getEffectiveWorkCenterId(// Roots only (depth = 1). Honors search/filter/pagination so the table can// paginate top-level storage units while children load lazily on demand.+export const STORAGE_UNIT_ROOTS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getStorageUnitRoots(client: SupabaseClient<Database>,@@ -1131,7 +1144,7 @@ export async function getStorageUnitRoots() {let query = client.from("storageUnits_recursive")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId).eq("locationId", locationId).eq("depth", 1);@@ -1140,9 +1153,7 @@ export async function getStorageUnitRoots(query = query.ilike("name", `%${args.search}%`);}- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, STORAGE_UNIT_ROOTS_PAGING);return query;}@@ -1178,15 +1189,29 @@ export async function getStorageUnitSubtrees(if (rootIds.length === 0) {return { data: [] as any[], error: null };}- return client- .from("storageUnits_recursive")- .select("*")- .eq("companyId", companyId)- .eq("locationId", locationId)- .gt("depth", 1)- .lte("depth", maxDepth)- .overlaps("ancestorPath", rootIds)- .order("name");+ // `overlaps` writes each root id into the URL, so the ids go 100 per+ // request. A descendant has one root, so each chunk keeps its own order.+ const chunks: string[][] = [];+ for (let i = 0; i < rootIds.length; i += 100) {+ chunks.push(rootIds.slice(i, i + 100));+ }+ const results = await Promise.all(+ chunks.map((ids) =>+ client+ .from("storageUnits_recursive")+ .select("*")+ .eq("companyId", companyId)+ .eq("locationId", locationId)+ .gt("depth", 1)+ .lte("depth", maxDepth)+ .overlaps("ancestorPath", ids)+ .order("name")+ )+ );+ return {+ data: results.flatMap((result) => result.data ?? []),+ error: results.find((result) => result.error)?.error ?? null+ };}// Set of storageUnit ids that have at least one child in the given location.@@ -1268,6 +1293,13 @@ export async function searchStorageUnitsWithAncestors(};}+export const STOCK_MOVEMENTS_PAGING: Paging = {+ defaultSorts: [+ { column: "createdAt", ascending: false },+ { column: "entryNumber", ascending: false }+ ]+};+/** @mcp read */export async function getStockMovements(client: SupabaseClient<Database>,@@ -1279,7 +1311,7 @@ export async function getStockMovements(let query = client.from("itemLedgers").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -1293,13 +1325,14 @@ export async function getStockMovements();}- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false },- { column: "entryNumber", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, STOCK_MOVEMENTS_PAGING);return query;}+export const SHIPMENTS_PAGING: Paging = {+ defaultSorts: [{ column: "shipmentId", ascending: false }]+};+/** @mcp read */export async function getShipments(client: SupabaseClient<Database>,@@ -1311,7 +1344,7 @@ export async function getShipments(let query = client.from("shipment").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId).neq("sourceDocumentId", "");@@ -1322,9 +1355,7 @@ export async function getShipments();}- query = setGenericQueryFilters(query, args, [- { column: "shipmentId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, SHIPMENTS_PAGING);return query;}@@ -1513,6 +1544,10 @@ export async function getShippingMethod(.single();}+export const SHIPPING_METHODS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getShippingMethods(client: SupabaseClient<Database>,@@ -1524,7 +1559,7 @@ export async function getShippingMethods(let query = client.from("shippingMethod").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId).eq("active", true);@@ -1535,9 +1570,7 @@ export async function getShippingMethods();}- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, SHIPPING_METHODS_PAGING);return query;}@@ -1625,6 +1658,10 @@ export async function mergeTrackedEntities(});}+export const TRACKED_ENTITIES_PAGING: Paging = {+ defaultSorts: [{ column: "sourceDocumentReadableId", ascending: true }]+};+/** @mcp read */export async function getTrackedEntities(client: SupabaseClient<Database>,@@ -1636,7 +1673,7 @@ export async function getTrackedEntities(let query = client.from("trackedEntity").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId).neq("status", "Reserved");@@ -1647,9 +1684,7 @@ export async function getTrackedEntities();}- query = setGenericQueryFilters(query, args, [- { column: "sourceDocumentReadableId", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, TRACKED_ENTITIES_PAGING);return query;}@@ -1786,6 +1821,10 @@ export async function getTrackedEntitiesByOperationId();}+export const WAREHOUSE_TRANSFERS_PAGING: Paging = {+ defaultSorts: [{ column: "transferId", ascending: false }]+};+/** @mcp read */export async function getWarehouseTransfers(client: SupabaseClient<Database>,@@ -1799,7 +1838,7 @@ export async function getWarehouseTransfers(.select("*, fromLocation:location!fromLocationId(name), toLocation:location!toLocationId(name)",{- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -1810,9 +1849,7 @@ export async function getWarehouseTransfers();}- query = setGenericQueryFilters(query, args, [- { column: "transferId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, WAREHOUSE_TRANSFERS_PAGING);return query;}@@ -2045,6 +2082,10 @@ export async function correctStockMovement(// Inventory Count / Cycle Count// ===========================================================================+export const INVENTORY_COUNTS_PAGING: Paging = {+ defaultSorts: [{ column: "inventoryCountId", ascending: false }]+};+/** @mcp read */export async function getInventoryCounts(client: SupabaseClient<Database>,@@ -2053,16 +2094,14 @@ export async function getInventoryCounts() {let query = client.from("inventoryCount")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {query = query.ilike("inventoryCountId", `%${args.search}%`);}- query = setGenericQueryFilters(query, args, [- { column: "inventoryCountId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, INVENTORY_COUNTS_PAGING);return query;}@@ -2080,6 +2119,13 @@ export async function getInventoryCount(.single();}+export const INVENTORY_COUNT_LINES_PAGING: Paging = {+ defaultSorts: [+ { column: "itemReadableIdWithRevision", ascending: true },+ { column: "id", ascending: true }+ ]+};+/** @mcp read */export async function getInventoryCountLines(client: SupabaseClient<Database>,@@ -2092,7 +2138,7 @@ export async function getInventoryCountLines(// apply the same generic column filters the quantities screen does.let query = client.from("inventoryCountLines")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("inventoryCountId", inventoryCountId).eq("companyId", companyId);@@ -2110,10 +2156,7 @@ export async function getInventoryCountLines(// Snapshot lines all share one insert timestamp, so order by the item's part// number for a readable count sheet and fall back to the line id for a stable,// deterministic order.- query = setGenericQueryFilters(query, args, [- { column: "itemReadableIdWithRevision", ascending: true },- { column: "id", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, INVENTORY_COUNT_LINES_PAGING);return query;}@@ -2940,6 +2983,10 @@ export async function deleteStorageTypeWithCascade(return client.from("storageType").delete().eq("id", id);}+export const STORAGE_TYPES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getStorageTypes(client: SupabaseClient<Database>,@@ -2948,16 +2995,14 @@ export async function getStorageTypes() {let query = client.from("storageType")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {query = query.ilike("name", `%${args.search}%`);}- query = setGenericQueryFilters(query, args ?? {}, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args ?? {}, STORAGE_TYPES_PAGING);return query;}@@ -3055,6 +3100,10 @@ export async function getTrackedEntityExpirations(// Picking List CRUD// ----------------------------------------------------------------------------+export const PICKING_LISTS_PAGING: Paging = {+ defaultSorts: [{ column: "pickingListId", ascending: false }]+};+/** @mcp read */export async function getPickingLists(client: SupabaseClient<Database>,@@ -3069,7 +3118,7 @@ export async function getPickingLists(let query = client.from("pickingLists").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -3092,9 +3141,7 @@ export async function getPickingLists(query = query.eq("locationId", args.locationId);}- query = setGenericQueryFilters(query, args, [- { column: "pickingListId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, PICKING_LISTS_PAGING);return query;}diff --git a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsxindex 216272c0be..ff4d709369 100644--- a/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx+++ b/apps/erp/app/modules/inventory/ui/Inventory/InventoryTable.tsx@@ -74,6 +74,8 @@ import type { InventoryItem } from "../../types";type InventoryTableProps = {data: InventoryItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;locationId: string;forms: ListItem[];substances: ListItem[];@@ -86,6 +88,7 @@ const InventoryTable = memo(({data,count,+ nextCursor,locationId,forms,substances,@@ -656,6 +659,8 @@ const InventoryTable = memo(count={count}columns={columns}data={data}+ // Location-scoped: no list registry entry, so no `listKey`.+ infinite={{ dataKey: "inventoryItems", nextCursor }}defaultColumnVisibility={defaultColumnVisibility}defaultColumnPinning={defaultColumnPinning}importCSV={[diff --git a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCount.tsx b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCount.tsxindex 83c6cb43fc..94a662ae97 100644--- a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCount.tsx+++ b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCount.tsx@@ -49,6 +49,8 @@ type InventoryCountDetailsProps = {inventoryCount: InventoryCountType;lines: InventoryCountLine[];count: number;+ // The loader's cursor for the next page of lines (infinite scroll).+ nextCursor: string | null;summary: { uncounted: number; variances: number };// Ledger adjustments this count has posted (empty for a never-posted Draft).movements: StockMovement[];@@ -64,6 +66,7 @@ const InventoryCountDetails = ({inventoryCount,lines,count,+ nextCursor,summary,movements,forms,@@ -198,6 +201,7 @@ const InventoryCountDetails = ({<InventoryCountLineslines={lines}count={count}+ nextCursor={nextCursor}hideSystemQuantity={hideSystemQuantity}isReadOnly={isReadOnly}locationId={inventoryCount.locationId}diff --git a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountLines.tsx b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountLines.tsxindex 0bc2071f38..c9c337914a 100644--- a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountLines.tsx+++ b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountLines.tsx@@ -48,6 +48,8 @@ const VARIANCE_FILTER = "variance:neq:0";type InventoryCountLinesProps = {lines: InventoryCountLine[];count: number;+ // The loader's cursor for the next page of lines (infinite scroll).+ nextCursor: string | null;// Blind counting withholds System Qty + Variance until Posted; the caller// decides when — kept separate from the read-only (Draft) edit gate.hideSystemQuantity: boolean;@@ -70,6 +72,7 @@ type InventoryCountLinesProps = {const InventoryCountLines = ({lines,count,+ nextCursor,hideSystemQuantity,isReadOnly,locationId,@@ -127,10 +130,7 @@ const InventoryCountLines = ({setParams({filter: filterParams.includes(filter)? filterParams.filter((f) => f !== filter)- : filterParams.concat(filter),- // Changing the result set invalidates the current page — reset paging- // the same way SearchFilter does.- offset: null+ : filterParams.concat(filter)});};@@ -680,6 +680,8 @@ const InventoryCountLines = ({mobileLayout="table"columns={columns}data={lines}+ // One count's lines: no list registry entry, so no `listKey`.+ infinite={{ dataKey: "lines", nextCursor }}count={count}defaultColumnVisibility={defaultColumnVisibility}editableComponents={editableComponents}diff --git a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountsTable.tsx b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountsTable.tsxindex ea6fedfea8..5f2301eafc 100644--- a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountsTable.tsx+++ b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountsTable.tsx@@ -25,7 +25,7 @@ import {import { useNavigate } from "react-router";import { DateTime, EmployeeAvatar, Hyperlink, New, Table } from "~/components";import { ConfirmDelete } from "~/components/Modals";-import { usePermissions, useRealtime, useUrlParams } from "~/hooks";+import { usePermissions, useUrlParams } from "~/hooks";import type { InventoryCount } from "~/modules/inventory";import { InventoryCountStatus } from "~/modules/inventory";import { usePeople } from "~/stores";@@ -34,13 +34,15 @@ import { path } from "~/utils/path";type InventoryCountsTableProps = {data: InventoryCount[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;locations: { id: string; name: string }[];};+// The route's `handle.realtime` follows every inventory count of the company,+// so the rows of a later page refresh too.const InventoryCountsTable = memo(- ({ data, count, locations }: InventoryCountsTableProps) => {- useRealtime("inventoryCount", `id=in.(${data.map((d) => d.id).join(",")})`);-+ ({ data, count, nextCursor, locations }: InventoryCountsTableProps) => {const [params] = useUrlParams();const { t } = useLingui();const navigate = useNavigate();@@ -195,6 +197,11 @@ const InventoryCountsTable = memo(<><Table<InventoryCount>data={data}+ infinite={{+ dataKey: "inventoryCounts",+ nextCursor,+ listKey: "inventory-counts"+ }}columns={columns}count={count}defaultColumnPinning={{ left: ["inventoryCountId"] }}diff --git a/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx b/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsxindex 54d4347753..0db5b83afb 100644--- a/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx+++ b/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx@@ -73,6 +73,8 @@ import type { Kanban } from "../../types";type KanbansTableProps = {data: Kanban[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;locationId: string;kanbanOutput: (typeof kanbanOutputTypes)[number];};@@ -86,7 +88,13 @@ const defaultColumnVisibility = {};const KanbansTable = memo(- ({ data, count, locationId, kanbanOutput }: KanbansTableProps) => {+ ({+ data,+ count,+ nextCursor,+ locationId,+ kanbanOutput+ }: KanbansTableProps) => {const [params] = useUrlParams();const { t } = useLingui();@@ -696,6 +704,8 @@ const KanbansTable = memo(count={count}columns={columns}data={data}+ // Location-scoped: no list registry entry, so no `listKey`.+ infinite={{ dataKey: "kanbans", nextCursor }}defaultColumnVisibility={defaultColumnVisibility}primaryAction={<div className="flex items-center gap-2">diff --git a/apps/erp/app/modules/inventory/ui/PickingLists/PickingListsTable.tsx b/apps/erp/app/modules/inventory/ui/PickingLists/PickingListsTable.tsxindex d0c5979ac9..6ebcad6e08 100644--- a/apps/erp/app/modules/inventory/ui/PickingLists/PickingListsTable.tsx+++ b/apps/erp/app/modules/inventory/ui/PickingLists/PickingListsTable.tsx@@ -52,9 +52,12 @@ export type PickingList = {type PickingListsTableProps = {data: PickingList[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const PickingListsTable = memo(({ data, count }: PickingListsTableProps) => {+const PickingListsTable = memo((props: PickingListsTableProps) => {+ const { data, count, nextCursor } = props;const [params] = useUrlParams();const { t } = useLingui();const navigate = useNavigate();@@ -217,6 +220,11 @@ const PickingListsTable = memo(({ data, count }: PickingListsTableProps) => {<><Table<PickingList>data={data}+ infinite={{+ dataKey: "pickingLists",+ nextCursor,+ listKey: "picking-lists"+ }}columns={columns}count={count}defaultColumnPinning={{diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsxindex eecc5a3348..c0e7ac258a 100644--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx@@ -36,7 +36,7 @@ import {import { Enumerable } from "~/components/Enumerable";import { ConfirmDelete } from "~/components/Modals";import { NewAction } from "~/components/New";-import { usePermissions, useRealtime, useUrlParams } from "~/hooks";+import { usePermissions, useUrlParams } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";import type { Receipt } from "~/modules/inventory";import {@@ -75,10 +75,14 @@ function NewReceipt() {type ReceiptsTableProps = {data: Receipt[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const ReceiptsTable = memo(({ data, count }: ReceiptsTableProps) => {- useRealtime("receipt", `id=in.(${data.map((d) => d.id).join(",")})`);+const ReceiptsTable = memo((props: ReceiptsTableProps) => {+ const { data, count, nextCursor } = props;+ // The route's `handle.realtime` follows every receipt of the company, so+ // the rows of a later page refresh too.const [params] = useUrlParams();const { t } = useLingui();@@ -392,6 +396,7 @@ const ReceiptsTable = memo(({ data, count }: ReceiptsTableProps) => {<><Table<(typeof data)[number]>data={data}+ infinite={{ dataKey: "receipts", nextCursor, listKey: "receipts" }}columns={columns}count={count}defaultColumnPinning={{diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsxindex 336565084c..b7adef778d 100644--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx@@ -36,7 +36,7 @@ import {import { Enumerable } from "~/components/Enumerable";import { ConfirmDelete } from "~/components/Modals";import { NewAction } from "~/components/New";-import { usePermissions, useRealtime, useUrlParams } from "~/hooks";+import { usePermissions, useUrlParams } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";import { useCustomers, usePeople } from "~/stores";import { path } from "~/utils/path";@@ -75,10 +75,14 @@ function NewShipment() {type ShipmentsTableProps = {data: Shipment[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const ShipmentsTable = memo(({ data, count }: ShipmentsTableProps) => {- useRealtime("shipment", `id=in.(${data.map((d) => d.id).join(",")})`);+const ShipmentsTable = memo((props: ShipmentsTableProps) => {+ const { data, count, nextCursor } = props;+ // The route's `handle.realtime` follows every shipment of the company, so+ // the rows of a later page refresh too.const [params] = useUrlParams();const { t } = useLingui();@@ -407,6 +411,7 @@ const ShipmentsTable = memo(({ data, count }: ShipmentsTableProps) => {<><Table<(typeof data)[number]>data={data}+ infinite={{ dataKey: "shipments", nextCursor, listKey: "shipments" }}columns={columns}count={count}defaultColumnPinning={{diff --git a/apps/erp/app/modules/inventory/ui/ShippingMethods/ShippingMethodsTable.tsx b/apps/erp/app/modules/inventory/ui/ShippingMethods/ShippingMethodsTable.tsxindex b260374f54..9d0d1475d8 100644--- a/apps/erp/app/modules/inventory/ui/ShippingMethods/ShippingMethodsTable.tsx+++ b/apps/erp/app/modules/inventory/ui/ShippingMethods/ShippingMethodsTable.tsx@@ -26,10 +26,12 @@ import { path } from "~/utils/path";type ShippingMethodsTableProps = {data: ShippingMethod[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const ShippingMethodsTable = memo(- ({ data, count }: ShippingMethodsTableProps) => {+ ({ data, count, nextCursor }: ShippingMethodsTableProps) => {const [params] = useUrlParams();const { t } = useLingui();const navigate = useNavigate();@@ -141,6 +143,11 @@ const ShippingMethodsTable = memo(return (<Table<(typeof data)[number]>data={data}+ infinite={{+ dataKey: "shippingMethods",+ nextCursor,+ listKey: "shipping-methods"+ }}columns={columns}count={count}primaryAction={diff --git a/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx b/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsxindex 70deb5ba99..be972a1b92 100644--- a/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx+++ b/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx@@ -54,10 +54,12 @@ import StockMovementCorrectionModal from "./StockMovementCorrectionModal";type StockMovementsTableProps = {data: StockMovement[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const StockMovementsTable = memo(- ({ data, count }: StockMovementsTableProps) => {+ ({ data, count, nextCursor }: StockMovementsTableProps) => {const { t } = useLingui();const permissions = usePermissions();const [correctionTarget, setCorrectionTarget] =@@ -301,6 +303,11 @@ const StockMovementsTable = memo(<><Table<(typeof data)[number]>data={data}+ infinite={{+ dataKey: "movements",+ nextCursor,+ listKey: "stock-movements"+ }}columns={columns}count={count}defaultColumnPinning={{diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsxindex 92b287980a..426721b56d 100644--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx@@ -41,11 +41,13 @@ import { StockTransferWizard } from "./StockTransferWizard";type StockTransfersTableProps = {data: StockTransfer[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;locationId: string;};const StockTransfersTable = memo(- ({ data, count, locationId }: StockTransfersTableProps) => {+ ({ data, count, nextCursor, locationId }: StockTransfersTableProps) => {const wizardDisclosure = useDisclosure();const [params] = useUrlParams();@@ -276,6 +278,8 @@ const StockTransfersTable = memo(<><Table<(typeof data)[number]>data={data}+ // Location-scoped: no list registry entry, so no `listKey`.+ infinite={{ dataKey: "stockTransfers", nextCursor }}columns={columns}count={count}defaultColumnPinning={{diff --git a/apps/erp/app/modules/inventory/ui/StorageTypes/StorageTypesTable.tsx b/apps/erp/app/modules/inventory/ui/StorageTypes/StorageTypesTable.tsxindex 5b534bab65..72394a6b19 100644--- a/apps/erp/app/modules/inventory/ui/StorageTypes/StorageTypesTable.tsx+++ b/apps/erp/app/modules/inventory/ui/StorageTypes/StorageTypesTable.tsx@@ -25,9 +25,12 @@ type StorageType = {type StorageTypesTableProps = {data: StorageType[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const StorageTypesTable = memo(({ data, count }: StorageTypesTableProps) => {+const StorageTypesTable = memo((props: StorageTypesTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -90,6 +93,11 @@ const StorageTypesTable = memo(({ data, count }: StorageTypesTableProps) => {return (<Table<(typeof rows)[number]>data={data}+ infinite={{+ dataKey: "storageTypes",+ nextCursor,+ listKey: "storage-types"+ }}columns={columns}count={count}importCSV={[diff --git a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitsTable.tsx b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitsTable.tsxindex 7fd6b48a84..31f12c4f6e 100644--- a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitsTable.tsx+++ b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitsTable.tsx@@ -61,6 +61,8 @@ type StorageUnit = {type StorageUnitsTableProps = {data: StorageUnit[];count: number;+ // The roots read SINGLE_LOAD_LIMIT rows: more may match.+ isTruncated?: boolean;locations: { id: string; name: string }[];locationId: string;storageTypes: { id: string; name: string }[];@@ -72,6 +74,7 @@ const StorageUnitsTable = memo(({data,count,+ isTruncated,locations: serverLocations,locationId,storageTypes: serverStorageTypes,@@ -648,6 +651,7 @@ const StorageUnitsTable = memo(<><Table<StorageUnit>count={count}+ isTruncated={isTruncated}columns={columns}data={displayRows}defaultColumnVisibility={defaultColumnVisibility}diff --git a/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsx b/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsxindex df298ed1d0..b34367b091 100644--- a/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsx+++ b/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsx@@ -41,19 +41,26 @@ type ShelfLifePolicy = {calculateFromBom?: boolean | null;};+// A row of the list, with its item's shelf-life policy (from the loader), so+// the Expiry trace popover can show the Policy step.+type TrackedEntityRow = TrackedEntity & {+ shelfLifePolicy: ShelfLifePolicy | null;+};+type TrackedEntitiesTableProps = {- data: TrackedEntity[];+ data: TrackedEntityRow[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;nearExpiryWarningDays: number | null;- shelfLifePolicies?: Record<string, ShelfLifePolicy>;};const TrackedEntitiesTable = memo(({data,count,- nearExpiryWarningDays,- shelfLifePolicies+ nextCursor,+ nearExpiryWarningDays}: TrackedEntitiesTableProps) => {const navigate = useNavigate();const { t } = useLingui();@@ -66,6 +73,15 @@ const TrackedEntitiesTable = memo(// can pre-fill its form. Lives at table level so the row context-menu// action can open it.const [unscrapping, setUnscrapping] = useState<TrackedEntity | null>(null);++ const infinite = useMemo(+ () => ({+ dataKey: "trackedEntities",+ nextCursor,+ listKey: "tracked-entities"+ }),+ [nextCursor]+ );const [editingExpiry, setEditingExpiry] = useState<TrackedEntity | null>(null);@@ -183,8 +199,7 @@ const TrackedEntitiesTable = memo({formatted}</span>);- const itemId = (row.original as { itemId?: string | null }).itemId;- const policy = itemId ? shelfLifePolicies?.[itemId] : undefined;+ const policy = row.original.shelfLifePolicy;return (<ExpiryTracePopoverentity={row.original}@@ -223,14 +238,7 @@ const TrackedEntitiesTable = memo(}}],- [- numberFormatter,- items,- t,- nearExpiryWarningDays,- shelfLifePolicies,- formatDate- ]+ [numberFormatter, items, t, nearExpiryWarningDays, formatDate]);const renderContextMenu = useCallback(@@ -281,6 +289,7 @@ const TrackedEntitiesTable = memo(<><Table<(typeof data)[number]>data={data}+ infinite={infinite}columns={columns}count={count}renderContextMenu={renderContextMenu}diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransfersTable.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransfersTable.tsxindex ff880cf189..65ce956955 100644--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransfersTable.tsx+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransfersTable.tsx@@ -24,7 +24,7 @@ import {import { useNavigate } from "react-router";import { DateTime, EmployeeAvatar, Hyperlink, New, Table } from "~/components";import { ConfirmDelete } from "~/components/Modals";-import { usePermissions, useRealtime, useUrlParams } from "~/hooks";+import { usePermissions, useUrlParams } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";import { usePeople } from "~/stores";import { path } from "~/utils/path";@@ -35,15 +35,14 @@ import WarehouseTransferStatus from "./WarehouseTransferStatus";type WarehouseTransfersTableProps = {data: WarehouseTransfer[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};+// The route's `handle.realtime` follows every warehouse transfer of the+// company, so the rows of a later page refresh too.const WarehouseTransfersTable = memo(- ({ data, count }: WarehouseTransfersTableProps) => {- useRealtime(- "warehouseTransfer",- `id=in.(${data.map((d) => d.id).join(",")})`- );-+ ({ data, count, nextCursor }: WarehouseTransfersTableProps) => {const [params] = useUrlParams();const { t } = useLingui();const navigate = useNavigate();@@ -254,6 +253,11 @@ const WarehouseTransfersTable = memo(<><Table<(typeof data)[number]>data={data}+ infinite={{+ dataKey: "warehouseTransfers",+ nextCursor,+ listKey: "warehouse-transfers"+ }}columns={columns}count={count}defaultColumnPinning={{diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.tsindex 7aa507a375..202e857dcc 100644--- a/apps/erp/app/modules/invoicing/invoicing.service.ts+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts@@ -46,7 +46,7 @@ import {getSupplierShipping,insertSupplierInteraction} from "~/modules/purchasing";-import type { GenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";import { getExchangeRate } from "../accounting/accounting.service";@@ -362,6 +362,10 @@ export async function getPurchaseInvoice(.single();}+export const PURCHASE_INVOICES_PAGING: Paging = {+ defaultSorts: [{ column: "invoiceId", ascending: false }]+};+/** @mcp read */export async function getPurchaseInvoices(client: SupabaseClient<Database>,@@ -373,7 +377,9 @@ export async function getPurchaseInvoices() {let query = client.from("purchaseInvoices")- .select(PURCHASE_INVOICES_LIST_COLUMNS, { count: LIST_COUNT })+ .select(PURCHASE_INVOICES_LIST_COLUMNS, {+ count: args.cursor ? undefined : LIST_COUNT+ }).eq("companyId", companyId);if (args.search) {@@ -384,9 +390,7 @@ export async function getPurchaseInvoices(query = query.eq("supplierId", args.supplierId);}- query = setGenericQueryFilters(query, args, [- { column: "invoiceId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, PURCHASE_INVOICES_PAGING);return query;}@@ -452,6 +456,10 @@ export async function getSalesInvoiceCustomerDetails(.single();}+export const SALES_INVOICES_PAGING: Paging = {+ defaultSorts: [{ column: "invoiceId", ascending: false }]+};+/** @mcp read */export async function getSalesInvoices(client: SupabaseClient<Database>,@@ -463,7 +471,9 @@ export async function getSalesInvoices() {let query = client.from("salesInvoices")- .select(SALES_INVOICES_LIST_COLUMNS, { count: LIST_COUNT })+ .select(SALES_INVOICES_LIST_COLUMNS, {+ count: args.cursor ? undefined : LIST_COUNT+ }).eq("companyId", companyId);if (args.search) {@@ -474,9 +484,7 @@ export async function getSalesInvoices(query = query.eq("customerId", args.customerId);}- query = setGenericQueryFilters(query, args, [- { column: "invoiceId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, SALES_INVOICES_PAGING);return query;}@@ -1359,6 +1367,13 @@ export async function getPayment(return query.single();}+// Newest first by the sequential paymentId (PAY-yyyy-mm-NNNNNN), matching the+// sales/purchase invoice lists (invoiceId desc), so the most recently created+// payment is at the top (paymentDate ties otherwise).+export const PAYMENTS_PAGING: Paging = {+ defaultSorts: [{ column: "paymentId", ascending: false }]+};+/** @mcp read */export async function getPayments(client: SupabaseClient<Database>,@@ -1376,7 +1391,7 @@ export async function getPayments() {let query = client.from("payment")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {@@ -1401,12 +1416,7 @@ export async function getPayments(query = query.or(`customerId.in.(${csv}),supplierId.in.(${csv})`);}- // Default to newest first by the sequential paymentId (PAY-yyyy-mm-NNNNNN),- // matching the sales/purchase invoice lists (invoiceId desc) and guaranteeing- // the most recently created payment is at the top (paymentDate ties otherwise).- query = setGenericQueryFilters(query, args, [- { column: "paymentId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, PAYMENTS_PAGING);return query;}@@ -1424,6 +1434,12 @@ export async function getCharge(.single();}+// Newest first by the sequential chargeId (CHG-yyyy-mm-NNNNNN), mirroring the+// payments' paymentId desc default.+export const CHARGES_PAGING: Paging = {+ defaultSorts: [{ column: "chargeId", ascending: false }]+};+/** @mcp read */export async function getCharges(client: SupabaseClient<Database>,@@ -1436,7 +1452,7 @@ export async function getCharges() {let query = client.from("charge")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {@@ -1451,11 +1467,7 @@ export async function getCharges(query = query.eq("status", args.status);}- // Default to newest first by the sequential chargeId- // (CHG-yyyy-mm-NNNNNN), mirroring getPayments' paymentId desc default.- query = setGenericQueryFilters(query, args, [- { column: "chargeId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, CHARGES_PAGING);return query;}@@ -1475,6 +1487,12 @@ export async function getReimbursement(.single();}+// Newest first by the sequential reimbursementId (REIMB-yyyy-mm-NNNNNN),+// mirroring the charges' chargeId desc default.+export const REIMBURSEMENTS_PAGING: Paging = {+ defaultSorts: [{ column: "reimbursementId", ascending: false }]+};+/** @mcp read */export async function getReimbursements(client: SupabaseClient<Database>,@@ -1487,7 +1505,7 @@ export async function getReimbursements() {let query = client.from("reimbursement")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {@@ -1502,11 +1520,7 @@ export async function getReimbursements(query = query.eq("employeeId", args.employeeId);}- // Newest first by the sequential reimbursementId (REIMB-yyyy-mm-NNNNNN),- // mirroring getCharges' chargeId desc default.- query = setGenericQueryFilters(query, args, [- { column: "reimbursementId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, REIMBURSEMENTS_PAGING);return query;}@@ -3894,6 +3908,13 @@ export async function getMemo(return query.single();}+// Newest first by creation date (not the readable memoId — Credit and Debit+// share the table but use separate CR-/DR- sequences, so a memoId sort+// interleaves them oddly).+export const MEMOS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getMemos(client: SupabaseClient<Database>,@@ -3911,7 +3932,7 @@ export async function getMemos() {let query = client.from("memo")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {@@ -3935,12 +3956,7 @@ export async function getMemos(query = query.or(`customerId.in.(${csv}),supplierId.in.(${csv})`);}- // Newest first by creation date (not the readable memoId — Credit and Debit- // share the table but use separate CR-/DR- sequences, so a memoId sort- // interleaves them oddly).- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, MEMOS_PAGING);return query;}diff --git a/apps/erp/app/modules/invoicing/ui/Charge/ChargesTable.tsx b/apps/erp/app/modules/invoicing/ui/Charge/ChargesTable.tsxindex 36cc70f875..d69898a066 100644--- a/apps/erp/app/modules/invoicing/ui/Charge/ChargesTable.tsx+++ b/apps/erp/app/modules/invoicing/ui/Charge/ChargesTable.tsx@@ -29,9 +29,12 @@ type ChargeRow = Database["public"]["Tables"]["charge"]["Row"];type ChargesTableProps = {data: ChargeRow[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const ChargesTable = memo(({ data, count }: ChargesTableProps) => {+const ChargesTable = memo((props: ChargesTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const { locale } = useLocale();// Each transaction carries its own currencyCode (a company can hold cards in@@ -137,6 +140,11 @@ const ChargesTable = memo(({ data, count }: ChargesTableProps) => {return (<Table<ChargeRow>+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "charges"+ }}count={count}columns={columns}data={data}diff --git a/apps/erp/app/modules/invoicing/ui/Memo/MemosTable.tsx b/apps/erp/app/modules/invoicing/ui/Memo/MemosTable.tsxindex 57a52f364b..d6baa4f853 100644--- a/apps/erp/app/modules/invoicing/ui/Memo/MemosTable.tsx+++ b/apps/erp/app/modules/invoicing/ui/Memo/MemosTable.tsx@@ -59,13 +59,16 @@ type MemoRow = {type MemosTableProps = {data: MemoRow[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;// Which party this list is scoped to. "customer" → Credit Memos (AR),// "supplier" → Supplier Credits (AP). Drives the counterparty column, the// title, and the New-button label/default party.party: "customer" | "supplier";};-const MemosTable = memo(({ data, count, party }: MemosTableProps) => {+const MemosTable = memo((props: MemosTableProps) => {+ const { data, count, party, nextCursor } = props;const { t } = useLingui();const permissions = usePermissions();const navigate = useNavigate();@@ -242,6 +245,11 @@ const MemosTable = memo(({ data, count, party }: MemosTableProps) => {return (<><Table<MemoRow>+ infinite={{+ dataKey: "memos",+ nextCursor,+ listKey: party === "customer" ? "credit-memos" : "supplier-credits"+ }}count={count}columns={columns}data={data}diff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentsTable.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentsTable.tsxindex 71cea5fc15..650980c3d5 100644--- a/apps/erp/app/modules/invoicing/ui/Payment/PaymentsTable.tsx+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentsTable.tsx@@ -44,9 +44,12 @@ type PaymentRow = Database["public"]["Tables"]["payment"]["Row"];type PaymentsTableProps = {data: PaymentRow[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const PaymentsTable = memo(({ data, count }: PaymentsTableProps) => {+const PaymentsTable = memo((props: PaymentsTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const permissions = usePermissions();const navigate = useNavigate();@@ -211,6 +214,11 @@ const PaymentsTable = memo(({ data, count }: PaymentsTableProps) => {return (<><Table<PaymentRow>+ infinite={{+ dataKey: "payments",+ nextCursor,+ listKey: "payments"+ }}count={count}columns={columns}data={data}diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsxindex 8068cd4f61..155898d3d1 100644--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx@@ -36,7 +36,7 @@ import {} from "~/components";import { Enumerable } from "~/components/Enumerable";import { ConfirmDelete } from "~/components/Modals";-import { useCurrencyFormatter, usePermissions, useRealtime } from "~/hooks";+import { useCurrencyFormatter, usePermissions } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";import type { PurchaseInvoiceListItem } from "~/modules/invoicing";import {@@ -49,15 +49,12 @@ import { path } from "~/utils/path";type PurchaseInvoicesTableProps = {data: PurchaseInvoiceListItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const PurchaseInvoicesTable = memo(- ({ data, count }: PurchaseInvoicesTableProps) => {- useRealtime(- "purchaseInvoice",- `id=in.(${data.map((d) => d.id).join(",")})`- );-+ ({ data, count, nextCursor }: PurchaseInvoicesTableProps) => {const { t } = useLingui();const permissions = usePermissions();const navigate = useNavigate();@@ -351,6 +348,11 @@ const PurchaseInvoicesTable = memo(count={count}columns={columns}data={data}+ infinite={{+ dataKey: "purchaseInvoices",+ nextCursor,+ listKey: "purchase-invoices"+ }}defaultColumnPinning={{left: ["invoiceId"]}}diff --git a/apps/erp/app/modules/invoicing/ui/Reimbursement/ReimbursementsTable.tsx b/apps/erp/app/modules/invoicing/ui/Reimbursement/ReimbursementsTable.tsxindex d5ff3eb4de..c659c50710 100644--- a/apps/erp/app/modules/invoicing/ui/Reimbursement/ReimbursementsTable.tsx+++ b/apps/erp/app/modules/invoicing/ui/Reimbursement/ReimbursementsTable.tsx@@ -29,10 +29,12 @@ type ReimbursementRow = Database["public"]["Tables"]["reimbursement"]["Row"];type ReimbursementsTableProps = {data: ReimbursementRow[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const ReimbursementsTable = memo(- ({ data, count }: ReimbursementsTableProps) => {+ ({ data, count, nextCursor }: ReimbursementsTableProps) => {const { t } = useLingui();const { locale } = useLocale();// Each reimbursement carries its own currencyCode, so the amount is@@ -135,6 +137,11 @@ const ReimbursementsTable = memo(return (<Table<ReimbursementRow>+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "reimbursements"+ }}count={count}columns={columns}data={data}diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsxindex 5f8b308eaf..f691850977 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx@@ -39,7 +39,7 @@ import {} from "~/components";import { Enumerable } from "~/components/Enumerable";import { ConfirmDelete } from "~/components/Modals";-import { useCurrencyFormatter, usePermissions, useRealtime } from "~/hooks";+import { useCurrencyFormatter, usePermissions } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";import type { SalesInvoiceListItem } from "~/modules/invoicing";import { salesInvoiceStatusType } from "~/modules/invoicing";@@ -50,10 +50,12 @@ import SalesInvoiceStatus from "./SalesInvoiceStatus";type SalesInvoicesTableProps = {data: SalesInvoiceListItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const SalesInvoicesTable = memo(({ data, count }: SalesInvoicesTableProps) => {- useRealtime("salesInvoice", `id=in.(${data.map((d) => d.id).join(",")})`);+const SalesInvoicesTable = memo((props: SalesInvoicesTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const permissions = usePermissions();@@ -376,6 +378,11 @@ const SalesInvoicesTable = memo(({ data, count }: SalesInvoicesTableProps) => {count={count}columns={columns}data={data}+ infinite={{+ dataKey: "salesInvoices",+ nextCursor,+ listKey: "sales-invoices"+ }}defaultColumnPinning={{left: ["invoiceId"]}}diff --git a/apps/erp/app/modules/items/bulk-actions.server.ts b/apps/erp/app/modules/items/bulk-actions.server.tsnew file mode 100644index 0000000000..164c7ec5bd--- /dev/null+++ b/apps/erp/app/modules/items/bulk-actions.server.ts@@ -0,0 +1,214 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Database } from "@carbon/database";+import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import { getLogger } from "@carbon/logger";+import { chunkArray, datetime } from "@carbon/utils";+import type { SupabaseClient } from "@supabase/supabase-js";+import type { ItemBulkUpdateField } from "./items.models";+import { deriveItemMethodUpdate } from "./items.models";+import {+ cascadeItemTrackingType,+ updateItemMethodAndSourcing+} from "./items.service";+import type { InventoryItemType } from "./types";++/**+ * The bulk Update of the item tables (Parts, Materials, Tools, Consumables,+ * Services). Called by `x+/items+/update.tsx` with the selected items and by+ * the background bulk-action job (`~/utils/table-jobs.server`) with up to 100+ * items at a time.+ */++const logger = getLogger("erp", "items-bulk-actions");++export type BulkUpdateItemsResult = {+ /** Items updated. */+ done: number;+ /** Ids that are not an item of the company. */+ skipped: number;+ /** Items whose chunk failed. */+ failed: number;+ /** The first failure's message, or null. */+ error: string | null;+};++/** An `.in()` filter rides in the request URL, so items go 100 at a time. */+const ITEM_BULK_CHUNK = 100;++/**+ * Sets one field on many items. Writes as `client` (the user), and the+ * cascades through `db`. Each chunk commits on its own: a failed chunk leaves+ * the chunks before it applied, and the result counts both, so the caller can+ * say what was done.+ */+export async function bulkUpdateItems(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ args: {+ itemIds: string[];+ field: ItemBulkUpdateField;+ value: string;+ companyId: string;+ userId: string;+ }+): Promise<BulkUpdateItemsResult> {+ const result: BulkUpdateItemsResult = {+ done: 0,+ skipped: 0,+ failed: 0,+ error: null+ };+ const ids = [...new Set(args.itemIds.filter(Boolean))];+ for (const chunk of chunkArray(ids, ITEM_BULK_CHUNK)) {+ // The writes below trust these ids (the itemCost insert names them), so+ // keep only the company's own items.+ const items = await client+ .from("item")+ .select("id")+ .in("id", chunk)+ .eq("companyId", args.companyId);+ if (items.error) {+ logger.error("Failed to read the items of a bulk update", {+ companyId: args.companyId,+ error: items.error+ });+ result.failed += chunk.length;+ result.error ??= items.error.message;+ continue;+ }+ const itemIds = items.data.map((item) => item.id);+ result.skipped += chunk.length - itemIds.length;+ if (itemIds.length === 0) continue;++ const error = await updateItemsChunk(client, db, { ...args, itemIds });+ if (error) {+ logger.error("Failed to bulk update items", {+ companyId: args.companyId,+ field: args.field,+ error+ });+ result.failed += itemIds.length;+ result.error ??= error;+ } else {+ result.done += itemIds.length;+ }+ }+ return result;+}++/** One chunk of `bulkUpdateItems`. Answers the error message, or null. */+async function updateItemsChunk(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ {+ itemIds,+ field,+ value,+ companyId,+ userId+ }: {+ itemIds: string[];+ field: ItemBulkUpdateField;+ value: string;+ companyId: string;+ userId: string;+ }+): Promise<string | null> {+ const updatedAt = datetime.timestamp();+ switch (field) {+ case "itemTrackingType": {+ const newType = value as InventoryItemType;+ const update = await client+ .from("item")+ .update({ itemTrackingType: newType, updatedBy: userId, updatedAt })+ .in("id", itemIds)+ .eq("companyId", companyId);+ if (update.error) return update.error.message;+ try {+ await cascadeItemTrackingType(db, {+ itemIds,+ companyId,+ newType,+ userId+ });+ } catch (err) {+ logger.error("Failed to cascade item tracking type", {+ companyId,+ error: err+ });+ return "Failed to cascade tracking flags";+ }+ return null;+ }+ case "replenishmentSystem":+ case "defaultMethodType":+ case "sourcingType": {+ // These three fields are interlocked and each mirror down to the item's+ // method materials. updateItemMethodAndSourcing applies the item write+ // and the cascade in one transaction, so they can't be left half-applied.+ const { itemUpdate, cascade } = deriveItemMethodUpdate(field, value);+ try {+ await updateItemMethodAndSourcing(db, {+ itemIds,+ companyId,+ userId,+ itemUpdate,+ cascade+ });+ } catch (err) {+ logger.error("Failed to update item method/sourcing", {+ companyId,+ field,+ error: err+ });+ return "Failed to update item";+ }+ return null;+ }+ case "itemPostingGroupId": {+ // One read for the chunk, then one update of the items that have an+ // itemCost row and one insert for the rest.+ const existing = await client+ .from("itemCost")+ .select("itemId")+ .in("itemId", itemIds)+ .eq("companyId", companyId);+ if (existing.error) return existing.error.message;+ const withCost = new Set(existing.data.map((row) => row.itemId));+ const itemPostingGroupId = value || null;++ if (withCost.size > 0) {+ const update = await client+ .from("itemCost")+ .update({ itemPostingGroupId, updatedBy: userId, updatedAt })+ .in("itemId", [...withCost])+ .eq("companyId", companyId);+ if (update.error) return update.error.message;+ }++ const missing = itemIds.filter((itemId) => !withCost.has(itemId));+ if (missing.length > 0) {+ const insert = await client.from("itemCost").insert(+ missing.map((itemId) => ({+ itemId,+ itemPostingGroupId,+ costingMethod: "Standard" as const,+ standardCost: 0,+ unitCost: 0,+ costIsAdjusted: false,+ companyId,+ createdBy: userId,+ updatedBy: userId,+ createdAt: updatedAt,+ updatedAt+ }))+ );+ if (insert.error) return insert.error.message;+ }+ return null;+ }+ }+}diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.tsindex e8e8180e44..993f9fac1e 100644--- a/apps/erp/app/modules/items/items.models.ts+++ b/apps/erp/app/modules/items/items.models.ts@@ -65,6 +65,23 @@ export const itemReplenishmentSystems = ["Buy and Make"] as const;+/** The fields the item tables' bulk Update sets on many items at once. */+export const itemBulkUpdateFields = [+ "itemPostingGroupId",+ "replenishmentSystem",+ "defaultMethodType",+ "sourcingType",+ "itemTrackingType"+] as const;++export type ItemBulkUpdateField = (typeof itemBulkUpdateFields)[number];++export function isItemBulkUpdateField(+ field: unknown+): field is ItemBulkUpdateField {+ return itemBulkUpdateFields.some((allowed) => allowed === field);+}+// Maps an edit of ONE of the three interlocked item-level fields// (replenishmentSystem, defaultMethodType, sourcingType) to the columns that must// change together on the item, plus the values to mirror down to method materials.diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex a71e89d89d..ba9fc03f24 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -26,7 +26,7 @@ import { datetime, isUniqueViolation, withPathIds } from "@carbon/utils";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";import { createDocumentUploadUrl } from "~/modules/documents/documents.service";-import type { GenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";import {LIST_COUNT,setGenericQueryFilters,@@ -885,6 +885,10 @@ export async function getConsumable(.single();}+export const CONSUMABLES_PAGING: Paging = {+ defaultSorts: [{ column: "readableIdWithRevision", ascending: true }]+};+/** @mcp read */export async function getConsumables(client: SupabaseClient<Database>,@@ -897,7 +901,7 @@ export async function getConsumables(let query = client.from("consumables").select(CONSUMABLES_LIST_COLUMNS, {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -913,9 +917,7 @@ export async function getConsumables(query = query.contains("suppliers", [args.supplierId]);}- query = setGenericQueryFilters(query, args, [- { column: "readableIdWithRevision", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, CONSUMABLES_PAGING);return query;}@@ -1175,6 +1177,10 @@ export async function getItemPostingGroup(return client.from("itemPostingGroup").select("*").eq("id", id).single();}+export const ITEM_POSTING_GROUPS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getItemPostingGroups(client: SupabaseClient<Database>,@@ -1184,7 +1190,7 @@ export async function getItemPostingGroups(let query = client.from("itemPostingGroup").select("*", {- count: LIST_COUNT+ count: args?.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -1193,9 +1199,7 @@ export async function getItemPostingGroups(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, ITEM_POSTING_GROUPS_PAGING);}return query;@@ -1579,6 +1583,10 @@ export async function getMaterial(.single();}+export const MATERIALS_PAGING: Paging = {+ defaultSorts: [{ column: "readableIdWithRevision", ascending: true }]+};+/** @mcp read */export async function getMaterials(client: SupabaseClient<Database>,@@ -1591,7 +1599,7 @@ export async function getMaterials(let query = client.from("materials").select(MATERIALS_LIST_COLUMNS, {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).or(`companyId.eq.${companyId},companyId.is.null`);@@ -1607,9 +1615,7 @@ export async function getMaterials(query = query.contains("suppliers", [args.supplierId]);}- query = setGenericQueryFilters(query, args, [- { column: "readableIdWithRevision", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, MATERIALS_PAGING);return query;}@@ -1644,6 +1650,13 @@ export async function getMaterialDimension(return client.from("materialDimension").select("*").eq("id", id).single();}+export const MATERIAL_DIMENSIONS_PAGING: Paging = {+ defaultSorts: [+ { column: "formName", ascending: true },+ { column: "name", ascending: true }+ ]+};+/** @mcp read */export async function getMaterialDimensions(client: SupabaseClient<Database>,@@ -1653,7 +1666,7 @@ export async function getMaterialDimensions(let query = client.from("materialDimensions").select("*", {- count: LIST_COUNT+ count: args?.cursor ? undefined : LIST_COUNT}).eq("isMetric", args?.isMetric ?? false).or(`companyId.eq.${companyId},companyId.is.null`);@@ -1665,10 +1678,7 @@ export async function getMaterialDimensions(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "formName", ascending: true },- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, MATERIAL_DIMENSIONS_PAGING);}return query;@@ -1697,6 +1707,13 @@ export async function getMaterialFinish(return client.from("materialFinish").select("*").eq("id", id).single();}+export const MATERIAL_FINISHES_PAGING: Paging = {+ defaultSorts: [+ { column: "substanceName", ascending: true },+ { column: "name", ascending: true }+ ]+};+/** @mcp read */export async function getMaterialFinishes(client: SupabaseClient<Database>,@@ -1706,7 +1723,7 @@ export async function getMaterialFinishes(let query = client.from("materialFinishes").select("*", {- count: LIST_COUNT+ count: args?.cursor ? undefined : LIST_COUNT}).or(`companyId.eq.${companyId},companyId.is.null`);@@ -1717,10 +1734,7 @@ export async function getMaterialFinishes(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "substanceName", ascending: true },- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, MATERIAL_FINISHES_PAGING);}return query;@@ -1747,6 +1761,10 @@ export async function getMaterialForm(return client.from("materialForm").select("*").eq("id", id).single();}+export const MATERIAL_FORMS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getMaterialForms(client: SupabaseClient<Database>,@@ -1756,7 +1774,7 @@ export async function getMaterialForms(let query = client.from("materialForm").select("*", {- count: LIST_COUNT+ count: args?.cursor ? undefined : LIST_COUNT}).or(`companyId.eq.${companyId},companyId.is.null`);@@ -1765,9 +1783,7 @@ export async function getMaterialForms(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, MATERIAL_FORMS_PAGING);}return query;@@ -1785,6 +1801,13 @@ export async function getMaterialFormsList(.order("name");}+export const MATERIAL_GRADES_PAGING: Paging = {+ defaultSorts: [+ { column: "substanceName", ascending: true },+ { column: "name", ascending: true }+ ]+};+/** @mcp read */export async function getMaterialGrades(client: SupabaseClient<Database>,@@ -1794,7 +1817,7 @@ export async function getMaterialGrades(let query = client.from("materialGrades").select("*", {- count: LIST_COUNT+ count: args?.cursor ? undefined : LIST_COUNT}).or(`companyId.eq.${companyId},companyId.is.null`);@@ -1805,10 +1828,7 @@ export async function getMaterialGrades(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "substanceName", ascending: true },- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, MATERIAL_GRADES_PAGING);}return query;@@ -1843,6 +1863,10 @@ export async function getMaterialSubstance(return client.from("materialSubstance").select("*").eq("id", id).single();}+export const MATERIAL_SUBSTANCES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getMaterialSubstances(client: SupabaseClient<Database>,@@ -1852,7 +1876,7 @@ export async function getMaterialSubstances(let query = client.from("materialSubstance").select("*", {- count: LIST_COUNT+ count: args?.cursor ? undefined : LIST_COUNT}).or(`companyId.eq.${companyId},companyId.is.null`);@@ -1861,9 +1885,7 @@ export async function getMaterialSubstances(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, MATERIAL_SUBSTANCES_PAGING);}return query;@@ -1893,6 +1915,8 @@ export async function getMethodMaterial(.single();}+export const METHOD_MATERIALS_PAGING: Paging = { defaultSorts: [] };+/** @mcp read */export async function getMethodMaterials(client: SupabaseClient<Database>,@@ -1904,7 +1928,7 @@ export async function getMethodMaterials(.select("*, item(name, readableIdWithRevision), makeMethod!makeMethodId(item(id, type, name, readableIdWithRevision))",{- count: LIST_COUNT+ count: args?.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -1914,7 +1938,7 @@ export async function getMethodMaterials(}if (args) {- query = setGenericQueryFilters(query, args, []);+ query = setGenericQueryFilters(query, args, METHOD_MATERIALS_PAGING);}return query;@@ -1956,6 +1980,10 @@ export async function getMethodMaterialsByMakeMethod(return result;}+export const METHOD_OPERATIONS_PAGING: Paging = {+ defaultSorts: [{ column: "order", ascending: true }]+};+/** @mcp read */export async function getMethodOperations(client: SupabaseClient<Database>,@@ -1967,7 +1995,7 @@ export async function getMethodOperations(.select("*, makeMethod!makeMethodId(item(id, type, name, readableIdWithRevision))",{- count: LIST_COUNT+ count: args?.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -1977,9 +2005,7 @@ export async function getMethodOperations(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "order", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, METHOD_OPERATIONS_PAGING);}return query;@@ -2243,6 +2269,10 @@ export async function getPart(.single();}+export const PARTS_PAGING: Paging = {+ defaultSorts: [{ column: "readableIdWithRevision", ascending: true }]+};+/** @mcp read */export async function getParts(client: SupabaseClient<Database>,@@ -2254,8 +2284,9 @@ export async function getParts() {let query = client.from("parts")+ // Later pages (`cursor`) skip the count: the first page already has it..select(PARTS_LIST_COLUMNS, {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -2271,9 +2302,7 @@ export async function getParts(query = query.contains("suppliers", [args.supplierId]);}- query = setGenericQueryFilters(query, args, [- { column: "readableIdWithRevision", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, PARTS_PAGING);return query;}@@ -2433,6 +2462,10 @@ export async function getPickMethods(.eq("companyId", companyId);}+export const SERVICES_PAGING: Paging = {+ defaultSorts: [{ column: "readableIdWithRevision", ascending: true }]+};+/** @mcp read */export async function getServices(client: SupabaseClient<Database>,@@ -2446,7 +2479,7 @@ export async function getServices(let query = client.from("services").select(SERVICES_LIST_COLUMNS, {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -2465,9 +2498,7 @@ export async function getServices(query = query.contains("suppliers", [args.supplierId]);}- query = setGenericQueryFilters(query, args, [- { column: "readableIdWithRevision", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, SERVICES_PAGING);return query;}@@ -2553,6 +2584,10 @@ export async function getTool(.single();}+export const TOOLS_PAGING: Paging = {+ defaultSorts: [{ column: "readableIdWithRevision", ascending: true }]+};+/** @mcp read */export async function getTools(client: SupabaseClient<Database>,@@ -2565,7 +2600,7 @@ export async function getTools(let query = client.from("tools").select(TOOLS_LIST_COLUMNS, {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -2581,9 +2616,7 @@ export async function getTools(query = query.contains("suppliers", [args.supplierId]);}- query = setGenericQueryFilters(query, args, [- { column: "readableIdWithRevision", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, TOOLS_PAGING);return query;}@@ -2632,6 +2665,10 @@ export async function getUnitOfMeasureUsage(return client.rpc("get_unit_of_measure_usage", { p_id: id });}+export const UNIT_OF_MEASURES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getUnitOfMeasures(client: SupabaseClient<Database>,@@ -2641,7 +2678,7 @@ export async function getUnitOfMeasures(let query = client.from("unitOfMeasure").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -2649,9 +2686,7 @@ export async function getUnitOfMeasures(query = query.or(`name.ilike.%${args.search}%,code.ilike.%${args.search}%`);}- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, UNIT_OF_MEASURES_PAGING);return query;}@@ -6200,6 +6235,8 @@ export async function deleteMaterialType(return client.from("materialType").delete().eq("id", id);}+export const MATERIAL_TYPES_PAGING: Paging = { defaultSorts: [] };+/** @mcp read */export async function getMaterialTypes(client: SupabaseClient<Database>,@@ -6208,7 +6245,7 @@ export async function getMaterialTypes() {let query = client.from("materialTypes")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).or(`companyId.eq.${companyId},companyId.is.null`);if (args?.search) {@@ -6222,7 +6259,7 @@ export async function getMaterialTypes();}- query = setGenericQueryFilters(query, args ?? {});+ query = setGenericQueryFilters(query, args ?? {}, MATERIAL_TYPES_PAGING);return query;}@@ -6870,6 +6907,10 @@ export async function getChangeNotice(.single();}+export const CHANGE_NOTICES_PAGING: Paging = {+ defaultSorts: [{ column: "changeOrderId", ascending: false }]+};+/** @mcp read */export async function getChangeNotices(client: SupabaseClient<Database>,@@ -6878,7 +6919,7 @@ export async function getChangeNotices() {let query = client.from("changeOrders")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -6888,9 +6929,7 @@ export async function getChangeNotices(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "changeOrderId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, CHANGE_NOTICES_PAGING);}return query;@@ -7114,6 +7153,10 @@ export async function updateChangeNoticeStatus(// -----------------------------------------------------------------------------// Change Notice Types (the "Category" lookup — configured like Issue Types)// -----------------------------------------------------------------------------+export const CHANGE_NOTICE_TYPES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getChangeNoticeTypes(client: SupabaseClient<Database>,@@ -7122,7 +7165,7 @@ export async function getChangeNoticeTypes() {let query = client.from("changeOrderType")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -7130,9 +7173,7 @@ export async function getChangeNoticeTypes(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, CHANGE_NOTICE_TYPES_PAGING);}return query;@@ -8467,6 +8508,10 @@ export async function updateChangeNoticeActionOrder(// Change Notice Required Actions (the configurable default-action templates the// config CRUD page manages, and the source new change notices are seeded from).// =============================================================================+export const CHANGE_NOTICE_REQUIRED_ACTIONS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getChangeNoticeRequiredActions(client: SupabaseClient<Database>,@@ -8475,7 +8520,7 @@ export async function getChangeNoticeRequiredActions() {let query = client.from("changeOrderRequiredAction")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -8483,9 +8528,11 @@ export async function getChangeNoticeRequiredActions(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(+ query,+ args,+ CHANGE_NOTICE_REQUIRED_ACTIONS_PAGING+ );}return query;diff --git a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticesTable.tsx b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticesTable.tsxindex 70c7bb5950..0014c10d97 100644--- a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticesTable.tsx+++ b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticesTable.tsx@@ -50,6 +50,7 @@ type ChangeNoticesTableProps = {data: ChangeNoticeListItem[];types: ListItem[];count: number;+ nextCursor: string | null;};// One entry of the changeOrders view's `affectedItems` jsonb rollup — enough to@@ -63,7 +64,7 @@ type AffectedItemSummary = {};const ChangeNoticesTable = memo(- ({ data, types, count }: ChangeNoticesTableProps) => {+ ({ data, types, count, nextCursor }: ChangeNoticesTableProps) => {const navigate = useNavigate();const { t } = useLingui();const permissions = usePermissions();@@ -321,6 +322,11 @@ const ChangeNoticesTable = memo(<><Table<ChangeNoticeListItem>data={data}+ infinite={{+ dataKey: "changeNotices",+ nextCursor,+ listKey: "change-notices"+ }}columns={columns}count={count}primaryAction={diff --git a/apps/erp/app/modules/items/ui/ChangeNoticeActions/ChangeNoticeRequiredActionsTable.tsx b/apps/erp/app/modules/items/ui/ChangeNoticeActions/ChangeNoticeRequiredActionsTable.tsxindex 967914e412..32a6c367b8 100644--- a/apps/erp/app/modules/items/ui/ChangeNoticeActions/ChangeNoticeRequiredActionsTable.tsx+++ b/apps/erp/app/modules/items/ui/ChangeNoticeActions/ChangeNoticeRequiredActionsTable.tsx@@ -22,10 +22,11 @@ import type { ChangeNoticeRequiredAction } from "../../types";type ChangeNoticeRequiredActionsTableProps = {data: ChangeNoticeRequiredAction[];count: number;+ nextCursor: string | null;};const ChangeNoticeRequiredActionsTable = memo(- ({ data, count }: ChangeNoticeRequiredActionsTableProps) => {+ ({ data, count, nextCursor }: ChangeNoticeRequiredActionsTableProps) => {const [params] = useUrlParams();const navigate = useNavigate();const { t } = useLingui();@@ -96,6 +97,11 @@ const ChangeNoticeRequiredActionsTable = memo(return (<Table<ChangeNoticeRequiredAction>data={data}+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "change-notice-actions"+ }}columns={columns}count={count}primaryAction={diff --git a/apps/erp/app/modules/items/ui/ChangeNoticeTypes/ChangeNoticeTypesTable.tsx b/apps/erp/app/modules/items/ui/ChangeNoticeTypes/ChangeNoticeTypesTable.tsxindex f6cd8efa66..1fab40076f 100644--- a/apps/erp/app/modules/items/ui/ChangeNoticeTypes/ChangeNoticeTypesTable.tsx+++ b/apps/erp/app/modules/items/ui/ChangeNoticeTypes/ChangeNoticeTypesTable.tsx@@ -17,10 +17,11 @@ import type { ChangeNoticeType } from "../../types";type ChangeNoticeTypesTableProps = {data: ChangeNoticeType[];count: number;+ nextCursor: string | null;};const ChangeNoticeTypesTable = memo(- ({ data, count }: ChangeNoticeTypesTableProps) => {+ ({ data, count, nextCursor }: ChangeNoticeTypesTableProps) => {const [params] = useUrlParams();const navigate = useNavigate();const { t } = useLingui();@@ -84,6 +85,11 @@ const ChangeNoticeTypesTable = memo(return (<Table<ChangeNoticeType>data={data}+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "change-notice-types"+ }}columns={columns}count={count}primaryAction={diff --git a/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx b/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsxindex e75bf6041f..49d749e257 100644--- a/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx+++ b/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx@@ -2,7 +2,6 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useAction } from "@carbon/query";import {Badge,Button,@@ -21,7 +20,6 @@ import {MENU_ITEM_SHORTCUTS,MenuIcon,MenuItem,- toast,useDisclosure,VStack} from "@carbon/react";@@ -62,10 +60,11 @@ import {import { Enumerable } from "~/components/Enumerable";import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { ConfirmDelete } from "~/components/Modals";+import type { BulkActionScope } from "~/components/Table";import { usePermissions } from "~/hooks";+import { useBulkFormAction } from "~/hooks/useBulkAction";import { useCustomColumns } from "~/hooks/useCustomColumns";import { methodType } from "~/modules/shared";-import type { action } from "~/routes/x+/items+/update";import { usePeople, useSuppliers } from "~/stores";import { path } from "~/utils/path";import { itemTrackingTypes } from "../../items.models";@@ -75,10 +74,11 @@ type ConsumablesTableProps = {data: ConsumableListItem[];tags: { name: string }[];count: number;+ nextCursor: string | null;};const ConsumablesTable = memo(- ({ data, count, tags }: ConsumablesTableProps) => {+ ({ data, count, tags, nextCursor }: ConsumablesTableProps) => {const { t } = useLingui();const translateMethodType = useCallback((v: string) =>@@ -444,14 +444,7 @@ const ConsumablesTable = memo(translateTrackingType]);- const fetcher = useAction<typeof action>({- onError: (data) => {- if (data?.error) {- toast.error(data.error.message);- }- }- });- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration+ const { submit: submitBulk } = useBulkFormAction();const onBulkUpdate = useCallback((selectedRows: typeof data,@@ -460,25 +453,20 @@ const ConsumablesTable = memo(| "defaultMethodType"| "itemTrackingType"| "itemPostingGroupId",- value: string+ value: string,+ scope?: BulkActionScope) => {- const formData = new FormData();- selectedRows.forEach((row) => {- if (row.id) formData.append("items", row.id);- });- formData.append("field", field);- formData.append("value", value);- fetcher.submit(formData, {- method: "post",- action: path.to.bulkUpdateItems- });+ submitBulk(+ path.to.bulkUpdateItems,+ { scope, idsField: "items", ids: selectedRows.map((row) => row.id) },+ { field, value }+ );},-- []+ [submitBulk]);const renderActions = useCallback(- (selectedRows: typeof data) => {+ (selectedRows: typeof data, scope?: BulkActionScope) => {return (<DropdownMenuContent align="end" className="min-w-[200px]"><DropdownMenuLabel>@@ -499,7 +487,8 @@ const ConsumablesTable = memo(onBulkUpdate(selectedRows,"itemPostingGroupId",- group.value+ group.value,+ scope)}>@@ -519,7 +508,12 @@ const ConsumablesTable = memo(<DropdownMenuItemkey={type}onClick={() =>- onBulkUpdate(selectedRows, "defaultMethodType", type)+ onBulkUpdate(+ selectedRows,+ "defaultMethodType",+ type,+ scope+ )}><DropdownMenuIcon icon={<MethodIcon type={type} />} />@@ -539,7 +533,12 @@ const ConsumablesTable = memo(<DropdownMenuItemkey={type}onClick={() =>- onBulkUpdate(selectedRows, "itemTrackingType", type)+ onBulkUpdate(+ selectedRows,+ "itemTrackingType",+ type,+ scope+ )}><DropdownMenuIcon@@ -595,6 +594,11 @@ const ConsumablesTable = memo(count={count}columns={columns}data={data}+ infinite={{+ dataKey: "consumables",+ nextCursor,+ listKey: "consumables"+ }}defaultColumnPinning={{left: ["id"]}}diff --git a/apps/erp/app/modules/items/ui/ItemPostingGroups/ItemPostingGroupsTable.tsx b/apps/erp/app/modules/items/ui/ItemPostingGroups/ItemPostingGroupsTable.tsxindex c46fa3a567..6f49488131 100644--- a/apps/erp/app/modules/items/ui/ItemPostingGroups/ItemPostingGroupsTable.tsx+++ b/apps/erp/app/modules/items/ui/ItemPostingGroups/ItemPostingGroupsTable.tsx@@ -18,9 +18,11 @@ import type { ItemPostingGroup } from "../../types";type ItemGroupsTableProps = {data: ItemPostingGroup[];count: number;+ nextCursor: string | null;};-const ItemGroupsTable = memo(({ data, count }: ItemGroupsTableProps) => {+const ItemGroupsTable = memo((props: ItemGroupsTableProps) => {+ const { data, count, nextCursor } = props;const [params] = useUrlParams();const navigate = useNavigate();const { t } = useLingui();@@ -97,6 +99,11 @@ const ItemGroupsTable = memo(({ data, count }: ItemGroupsTableProps) => {return (<Table<(typeof rows)[number]>data={data}+ infinite={{+ dataKey: "itemPostingGroups",+ nextCursor,+ listKey: "item-posting-groups"+ }}columns={columns}count={count}importCSV={[diff --git a/apps/erp/app/modules/items/ui/MaterialDimensions/MaterialDimensionsTable.tsx b/apps/erp/app/modules/items/ui/MaterialDimensions/MaterialDimensionsTable.tsxindex 1c03629da6..b2682ad2a6 100644--- a/apps/erp/app/modules/items/ui/MaterialDimensions/MaterialDimensionsTable.tsx+++ b/apps/erp/app/modules/items/ui/MaterialDimensions/MaterialDimensionsTable.tsx@@ -31,10 +31,11 @@ import type { MaterialDimension } from "../../types";type MaterialDimensionsTableProps = {data: MaterialDimension[];count: number;+ nextCursor: string | null;};const MaterialDimensionsTable = memo(- ({ data, count }: MaterialDimensionsTableProps) => {+ ({ data, count, nextCursor }: MaterialDimensionsTableProps) => {const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -160,6 +161,11 @@ const MaterialDimensionsTable = memo(return (<Table<(typeof rows)[number]>data={data}+ infinite={{+ dataKey: "materialDimensions",+ nextCursor,+ listKey: "material-dimensions"+ }}columns={columns}count={count}importCSV={[diff --git a/apps/erp/app/modules/items/ui/MaterialFinishes/MaterialFinishesTable.tsx b/apps/erp/app/modules/items/ui/MaterialFinishes/MaterialFinishesTable.tsxindex d6df35df74..a27b63206f 100644--- a/apps/erp/app/modules/items/ui/MaterialFinishes/MaterialFinishesTable.tsx+++ b/apps/erp/app/modules/items/ui/MaterialFinishes/MaterialFinishesTable.tsx@@ -31,10 +31,11 @@ import type { MaterialFinish } from "../../types";type MaterialFinishesTableProps = {data: MaterialFinish[];count: number;+ nextCursor: string | null;};const MaterialFinishesTable = memo(- ({ data, count }: MaterialFinishesTableProps) => {+ ({ data, count, nextCursor }: MaterialFinishesTableProps) => {const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -161,6 +162,11 @@ const MaterialFinishesTable = memo(return (<Table<(typeof rows)[number]>data={data}+ infinite={{+ dataKey: "materialFinishes",+ nextCursor,+ listKey: "material-finishes"+ }}columns={columns}count={count}importCSV={[diff --git a/apps/erp/app/modules/items/ui/MaterialGrades/MaterialGradesTable.tsx b/apps/erp/app/modules/items/ui/MaterialGrades/MaterialGradesTable.tsxindex 99e45d3bb9..ca74452099 100644--- a/apps/erp/app/modules/items/ui/MaterialGrades/MaterialGradesTable.tsx+++ b/apps/erp/app/modules/items/ui/MaterialGrades/MaterialGradesTable.tsx@@ -31,10 +31,11 @@ import type { MaterialGrade } from "../../types";type MaterialGradesTableProps = {data: MaterialGrade[];count: number;+ nextCursor: string | null;};const MaterialGradesTable = memo(- ({ data, count }: MaterialGradesTableProps) => {+ ({ data, count, nextCursor }: MaterialGradesTableProps) => {const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -158,6 +159,11 @@ const MaterialGradesTable = memo(return (<Table<(typeof rows)[number]>data={data}+ infinite={{+ dataKey: "materialGrades",+ nextCursor,+ listKey: "material-grades"+ }}columns={columns}count={count}importCSV={[diff --git a/apps/erp/app/modules/items/ui/MaterialShapes/MaterialShapesTable.tsx b/apps/erp/app/modules/items/ui/MaterialShapes/MaterialShapesTable.tsxindex 0b6be2fb57..af184523a3 100644--- a/apps/erp/app/modules/items/ui/MaterialShapes/MaterialShapesTable.tsx+++ b/apps/erp/app/modules/items/ui/MaterialShapes/MaterialShapesTable.tsx@@ -31,10 +31,11 @@ import type { Form } from "../../types";type MaterialShapesTableProps = {data: Form[];count: number;+ nextCursor: string | null;};const MaterialShapesTable = memo(- ({ data, count }: MaterialShapesTableProps) => {+ ({ data, count, nextCursor }: MaterialShapesTableProps) => {const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -151,6 +152,11 @@ const MaterialShapesTable = memo(return (<Table<(typeof rows)[number]>data={data}+ infinite={{+ dataKey: "materialForms",+ nextCursor,+ listKey: "material-forms"+ }}columns={columns}count={count}importCSV={[diff --git a/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsx b/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsxindex 7f5c1c5029..637601153e 100644--- a/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsx+++ b/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsx@@ -31,10 +31,11 @@ import type { Substance } from "../../types";type MaterialSubstancesTableProps = {data: Substance[];count: number;+ nextCursor: string | null;};const MaterialSubstancesTable = memo(- ({ data, count }: MaterialSubstancesTableProps) => {+ ({ data, count, nextCursor }: MaterialSubstancesTableProps) => {const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -153,6 +154,11 @@ const MaterialSubstancesTable = memo(return (<Table<(typeof rows)[number]>data={data}+ infinite={{+ dataKey: "materialSubstances",+ nextCursor,+ listKey: "material-substances"+ }}columns={columns}count={count}importCSV={[diff --git a/apps/erp/app/modules/items/ui/MaterialTypes/MaterialTypesTable.tsx b/apps/erp/app/modules/items/ui/MaterialTypes/MaterialTypesTable.tsxindex 6e722b212d..a03c1977e2 100644--- a/apps/erp/app/modules/items/ui/MaterialTypes/MaterialTypesTable.tsx+++ b/apps/erp/app/modules/items/ui/MaterialTypes/MaterialTypesTable.tsx@@ -33,9 +33,11 @@ import type { MaterialType } from "../../types";type MaterialTypesTableProps = {data: MaterialType[];count: number;+ nextCursor: string | null;};-const MaterialTypesTable = memo(({ data, count }: MaterialTypesTableProps) => {+const MaterialTypesTable = memo((props: MaterialTypesTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -174,6 +176,11 @@ const MaterialTypesTable = memo(({ data, count }: MaterialTypesTableProps) => {return (<Table<(typeof rows)[number]>data={data}+ infinite={{+ dataKey: "materialTypes",+ nextCursor,+ listKey: "material-types"+ }}columns={columns}count={count}importCSV={[diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsxindex 4592faa942..5984e7e92c 100644--- a/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx+++ b/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx@@ -2,7 +2,6 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useAction } from "@carbon/query";import {Badge,Button,@@ -24,7 +23,6 @@ import {MenuSub,MenuSubContent,MenuSubTrigger,- toast,useDisclosure,VStack} from "@carbon/react";@@ -74,11 +72,12 @@ import { Enumerable } from "~/components/Enumerable";import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";import { ConfirmDelete } from "~/components/Modals";+import type { BulkActionScope } from "~/components/Table";import { useFilters } from "~/components/Table/components/Filter/useFilters";import { usePermissions } from "~/hooks";+import { useBulkFormAction } from "~/hooks/useBulkAction";import { useCustomColumns } from "~/hooks/useCustomColumns";import { methodType } from "~/modules/shared";-import type { action } from "~/routes/x+/items+/update";import { usePeople, useSuppliers } from "~/stores";import { path } from "~/utils/path";import { itemTrackingTypes } from "../../items.models";@@ -88,9 +87,11 @@ type MaterialsTableProps = {data: MaterialListItem[];tags: { name: string }[];count: number;+ nextCursor: string | null;};-const MaterialsTable = memo(({ data, tags, count }: MaterialsTableProps) => {+const MaterialsTable = memo((props: MaterialsTableProps) => {+ const { data, tags, count, nextCursor } = props;const { t } = useLingui();const translateMethodType = useCallback((v: string) =>@@ -569,14 +570,7 @@ const MaterialsTable = memo(({ data, tags, count }: MaterialsTableProps) => {translateTrackingType]);- const fetcher = useAction<typeof action>({- onError: (data) => {- if (data?.error) {- toast.error(data.error.message);- }- }- });- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration+ const { submit: submitBulk } = useBulkFormAction();const onBulkUpdate = useCallback((selectedRows: typeof data,@@ -586,25 +580,20 @@ const MaterialsTable = memo(({ data, tags, count }: MaterialsTableProps) => {| "defaultMethodType"| "itemTrackingType"| "itemPostingGroupId",- value: string+ value: string,+ scope?: BulkActionScope) => {- const formData = new FormData();- selectedRows.forEach((row) => {- if (row.id) formData.append("items", row.id);- });- formData.append("field", field);- formData.append("value", value);- fetcher.submit(formData, {- method: "post",- action: path.to.bulkUpdateItems- });+ submitBulk(+ path.to.bulkUpdateItems,+ { scope, idsField: "items", ids: selectedRows.map((row) => row.id) },+ { field, value }+ );},-- [materialSubstanceId, materialFormId]+ [submitBulk]);const renderActions = useCallback(- (selectedRows: typeof data) => {+ (selectedRows: typeof data, scope?: BulkActionScope) => {return (<DropdownMenuContent align="end" className="min-w-[200px]"><DropdownMenuLabel>@@ -625,7 +614,8 @@ const MaterialsTable = memo(({ data, tags, count }: MaterialsTableProps) => {onBulkUpdate(selectedRows,"itemPostingGroupId",- group.value+ group.value,+ scope)}>@@ -645,7 +635,12 @@ const MaterialsTable = memo(({ data, tags, count }: MaterialsTableProps) => {<DropdownMenuItemkey={type}onClick={() =>- onBulkUpdate(selectedRows, "defaultMethodType", type)+ onBulkUpdate(+ selectedRows,+ "defaultMethodType",+ type,+ scope+ )}><DropdownMenuIcon icon={<MethodIcon type={type} />} />@@ -665,7 +660,12 @@ const MaterialsTable = memo(({ data, tags, count }: MaterialsTableProps) => {<DropdownMenuItemkey={type}onClick={() =>- onBulkUpdate(selectedRows, "itemTrackingType", type)+ onBulkUpdate(+ selectedRows,+ "itemTrackingType",+ type,+ scope+ )}><DropdownMenuIcon@@ -747,6 +747,7 @@ const MaterialsTable = memo(({ data, tags, count }: MaterialsTableProps) => {count={count}columns={columns}data={data}+ infinite={{ dataKey: "materials", nextCursor, listKey: "materials" }}defaultColumnPinning={{left: ["id"]}}diff --git a/apps/erp/app/modules/items/ui/Methods/MethodMaterialsTable.tsx b/apps/erp/app/modules/items/ui/Methods/MethodMaterialsTable.tsxindex 160f1883d1..655f071e53 100644--- a/apps/erp/app/modules/items/ui/Methods/MethodMaterialsTable.tsx+++ b/apps/erp/app/modules/items/ui/Methods/MethodMaterialsTable.tsx@@ -15,10 +15,11 @@ import { getPathToMakeMethod } from "./utils";type MethodMaterialsTableProps = {data: MethodMaterial[];count: number;+ nextCursor: string | null;};const MethodMaterialsTable = memo(- ({ data, count }: MethodMaterialsTableProps) => {+ ({ data, count, nextCursor }: MethodMaterialsTableProps) => {const { t } = useLingui();const parts = useParts();const tools = useTools();@@ -144,6 +145,11 @@ const MethodMaterialsTable = memo(count={count}columns={columns}data={data}+ infinite={{+ dataKey: "materials",+ nextCursor,+ listKey: "method-materials"+ }}title={t`Method Materials`}/>);diff --git a/apps/erp/app/modules/items/ui/Methods/MethodOperationsTable.tsx b/apps/erp/app/modules/items/ui/Methods/MethodOperationsTable.tsxindex b84b07ce68..f3a112c7ab 100644--- a/apps/erp/app/modules/items/ui/Methods/MethodOperationsTable.tsx+++ b/apps/erp/app/modules/items/ui/Methods/MethodOperationsTable.tsx@@ -15,10 +15,11 @@ import { getPathToMakeMethod } from "./utils";type MethodOperationsTableProps = {data: MethodOperation[];count: number;+ nextCursor: string | null;};const MethodOperationsTable = memo(- ({ data, count }: MethodOperationsTableProps) => {+ ({ data, count, nextCursor }: MethodOperationsTableProps) => {const { t } = useLingui();const parts = useParts();const tools = useTools();@@ -109,6 +110,11 @@ const MethodOperationsTable = memo(count={count}columns={columns}data={data}+ infinite={{+ dataKey: "operations",+ nextCursor,+ listKey: "method-operations"+ }}title={t`Method Operations`}/>);diff --git a/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx b/apps/erp/app/modules/items/ui/Parts/PartsTable.tsxindex eb0d0f85fa..83088c1e76 100644--- a/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx+++ b/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx@@ -2,7 +2,6 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useAction } from "@carbon/query";import {Badge,Button,@@ -24,7 +23,6 @@ import {MenuSub,MenuSubContent,MenuSubTrigger,- toast,useDisclosure,VStack} from "@carbon/react";@@ -68,10 +66,11 @@ import { Enumerable } from "~/components/Enumerable";import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { ReplenishmentSystemIcon } from "~/components/Icons";import { ConfirmDelete } from "~/components/Modals";+import type { BulkActionScope } from "~/components/Table";import { usePermissions } from "~/hooks";+import { useBulkFormAction } from "~/hooks/useBulkAction";import { useCustomColumns } from "~/hooks/useCustomColumns";import { methodType } from "~/modules/shared";-import type { action } from "~/routes/x+/items+/update";import { usePeople, useSuppliers } from "~/stores";import { path } from "~/utils/path";import {@@ -84,9 +83,12 @@ type PartsTableProps = {data: PartListItem[];tags: { name: string }[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {+const PartsTable = memo((props: PartsTableProps) => {+ const { data, tags, count, nextCursor } = props;const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -487,14 +489,7 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {translateTrackingType]);- const fetcher = useAction<typeof action>({- onError: (data) => {- if (data?.error) {- toast.error(data.error.message);- }- }- });- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration+ const { submit: submitBulk, fetcher } = useBulkFormAction();const onBulkUpdate = useCallback((selectedRows: typeof data,@@ -503,25 +498,20 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {| "defaultMethodType"| "itemTrackingType"| "itemPostingGroupId",- value: string+ value: string,+ scope?: BulkActionScope) => {- const formData = new FormData();- selectedRows.forEach((row) => {- if (row.id) formData.append("items", row.id);- });- formData.append("field", field);- formData.append("value", value);- fetcher.submit(formData, {- method: "post",- action: path.to.bulkUpdateItems- });+ submitBulk(+ path.to.bulkUpdateItems,+ { scope, idsField: "items", ids: selectedRows.map((row) => row.id) },+ { field, value }+ );},-- []+ [submitBulk]);const renderActions = useCallback(- (selectedRows: typeof data) => {+ (selectedRows: typeof data, scope?: BulkActionScope) => {return (<DropdownMenuContent align="end" className="min-w-[200px]"><DropdownMenuLabel>@@ -542,7 +532,8 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {onBulkUpdate(selectedRows,"itemPostingGroupId",- group.value+ group.value,+ scope)}>@@ -565,7 +556,8 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {onBulkUpdate(selectedRows,"replenishmentSystem",- system+ system,+ scope)}>@@ -588,7 +580,12 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {<DropdownMenuItemkey={type}onClick={() =>- onBulkUpdate(selectedRows, "defaultMethodType", type)+ onBulkUpdate(+ selectedRows,+ "defaultMethodType",+ type,+ scope+ )}><DropdownMenuIcon icon={<MethodIcon type={type} />} />@@ -608,7 +605,12 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {<DropdownMenuItemkey={type}onClick={() =>- onBulkUpdate(selectedRows, "itemTrackingType", type)+ onBulkUpdate(+ selectedRows,+ "itemTrackingType",+ type,+ scope+ )}><DropdownMenuIcon@@ -703,6 +705,7 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {count={count}columns={columns}data={data}+ infinite={{ dataKey: "parts", nextCursor, listKey: "parts" }}defaultColumnPinning={{left: ["id"]}}diff --git a/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx b/apps/erp/app/modules/items/ui/Services/ServicesTable.tsxindex 4d9aa0fc9d..068913f2a7 100644--- a/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx+++ b/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx@@ -2,7 +2,6 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useAction } from "@carbon/query";import {Badge,Button,@@ -24,7 +23,6 @@ import {MenuSub,MenuSubContent,MenuSubTrigger,- toast,useDisclosure,VStack} from "@carbon/react";@@ -64,10 +62,11 @@ import { Enumerable } from "~/components/Enumerable";import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { ReplenishmentSystemIcon } from "~/components/Icons";import { ConfirmDelete } from "~/components/Modals";+import type { BulkActionScope } from "~/components/Table";import { usePermissions } from "~/hooks";+import { useBulkFormAction } from "~/hooks/useBulkAction";import { useCustomColumns } from "~/hooks/useCustomColumns";import { methodType } from "~/modules/shared";-import type { action } from "~/routes/x+/items+/update";import { usePeople, useSuppliers } from "~/stores";import { path } from "~/utils/path";import { serviceReplenishmentSystems } from "../../items.models";@@ -77,6 +76,7 @@ type ServicesTableProps = {data: ServiceListItem[];tags: { name: string }[];count: number;+ nextCursor: string | null;};// Services are Non-Inventory, so "Pull from Inventory" is never valid.@@ -84,7 +84,8 @@ const serviceMethodTypes = methodType.filter((type) => type !== "Pull from Inventory");-const ServicesTable = memo(({ data, tags, count }: ServicesTableProps) => {+const ServicesTable = memo((props: ServicesTableProps) => {+ const { data, tags, count, nextCursor } = props;const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -408,37 +409,25 @@ const ServicesTable = memo(({ data, tags, count }: ServicesTableProps) => {translateReplenishment]);- const fetcher = useAction<typeof action>({- onError: (data) => {- if (data?.error) {- toast.error(data.error.message);- }- }- });- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration+ const { submit: submitBulk } = useBulkFormAction();const onBulkUpdate = useCallback((selectedRows: typeof data,field: "replenishmentSystem" | "defaultMethodType" | "itemPostingGroupId",- value: string+ value: string,+ scope?: BulkActionScope) => {- const formData = new FormData();- selectedRows.forEach((row) => {- if (row.id) formData.append("items", row.id);- });- formData.append("field", field);- formData.append("value", value);- fetcher.submit(formData, {- method: "post",- action: path.to.bulkUpdateItems- });+ submitBulk(+ path.to.bulkUpdateItems,+ { scope, idsField: "items", ids: selectedRows.map((row) => row.id) },+ { field, value }+ );},-- []+ [submitBulk]);const renderActions = useCallback(- (selectedRows: typeof data) => {+ (selectedRows: typeof data, scope?: BulkActionScope) => {return (<DropdownMenuContent align="end" className="min-w-[200px]"><DropdownMenuLabel>@@ -459,7 +448,8 @@ const ServicesTable = memo(({ data, tags, count }: ServicesTableProps) => {onBulkUpdate(selectedRows,"itemPostingGroupId",- group.value+ group.value,+ scope)}>@@ -479,7 +469,12 @@ const ServicesTable = memo(({ data, tags, count }: ServicesTableProps) => {<DropdownMenuItemkey={type}onClick={() =>- onBulkUpdate(selectedRows, "defaultMethodType", type)+ onBulkUpdate(+ selectedRows,+ "defaultMethodType",+ type,+ scope+ )}><DropdownMenuIcon icon={<MethodIcon type={type} />} />@@ -554,6 +549,7 @@ const ServicesTable = memo(({ data, tags, count }: ServicesTableProps) => {count={count}columns={columns}data={data}+ infinite={{ dataKey: "services", nextCursor, listKey: "services" }}defaultColumnPinning={{left: ["id"]}}diff --git a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsxindex cc1c3beaa4..3012a68214 100644--- a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx+++ b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx@@ -2,7 +2,6 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useAction } from "@carbon/query";import {Badge,Button,@@ -24,7 +23,6 @@ import {MenuSub,MenuSubContent,MenuSubTrigger,- toast,useDisclosure,VStack} from "@carbon/react";@@ -68,10 +66,11 @@ import { Enumerable } from "~/components/Enumerable";import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { ReplenishmentSystemIcon } from "~/components/Icons";import { ConfirmDelete } from "~/components/Modals";+import type { BulkActionScope } from "~/components/Table";import { usePermissions } from "~/hooks";+import { useBulkFormAction } from "~/hooks/useBulkAction";import { useCustomColumns } from "~/hooks/useCustomColumns";import { methodType } from "~/modules/shared";-import type { action } from "~/routes/x+/items+/update";import { usePeople, useSuppliers } from "~/stores";import { path } from "~/utils/path";import {@@ -84,9 +83,11 @@ type ToolsTableProps = {data: ToolListItem[];tags: { name: string }[];count: number;+ nextCursor: string | null;};-const ToolsTable = memo(({ data, tags, count }: ToolsTableProps) => {+const ToolsTable = memo((props: ToolsTableProps) => {+ const { data, tags, count, nextCursor } = props;const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -484,14 +485,7 @@ const ToolsTable = memo(({ data, tags, count }: ToolsTableProps) => {translateTrackingType]);- const fetcher = useAction<typeof action>({- onError: (data) => {- if (data?.error) {- toast.error(data.error.message);- }- }- });- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration+ const { submit: submitBulk } = useBulkFormAction();const onBulkUpdate = useCallback((selectedRows: typeof data,@@ -500,25 +494,20 @@ const ToolsTable = memo(({ data, tags, count }: ToolsTableProps) => {| "defaultMethodType"| "itemTrackingType"| "itemPostingGroupId",- value: string+ value: string,+ scope?: BulkActionScope) => {- const formData = new FormData();- selectedRows.forEach((row) => {- if (row.id) formData.append("items", row.id);- });- formData.append("field", field);- formData.append("value", value);- fetcher.submit(formData, {- method: "post",- action: path.to.bulkUpdateItems- });+ submitBulk(+ path.to.bulkUpdateItems,+ { scope, idsField: "items", ids: selectedRows.map((row) => row.id) },+ { field, value }+ );},-- []+ [submitBulk]);const renderActions = useCallback(- (selectedRows: typeof data) => {+ (selectedRows: typeof data, scope?: BulkActionScope) => {return (<DropdownMenuContent align="end" className="min-w-[200px]"><DropdownMenuLabel>@@ -539,7 +528,8 @@ const ToolsTable = memo(({ data, tags, count }: ToolsTableProps) => {onBulkUpdate(selectedRows,"itemPostingGroupId",- group.value+ group.value,+ scope)}>@@ -559,7 +549,12 @@ const ToolsTable = memo(({ data, tags, count }: ToolsTableProps) => {<DropdownMenuItemkey={type}onClick={() =>- onBulkUpdate(selectedRows, "defaultMethodType", type)+ onBulkUpdate(+ selectedRows,+ "defaultMethodType",+ type,+ scope+ )}><DropdownMenuIcon icon={<MethodIcon type={type} />} />@@ -579,7 +574,12 @@ const ToolsTable = memo(({ data, tags, count }: ToolsTableProps) => {<DropdownMenuItemkey={type}onClick={() =>- onBulkUpdate(selectedRows, "itemTrackingType", type)+ onBulkUpdate(+ selectedRows,+ "itemTrackingType",+ type,+ scope+ )}><DropdownMenuIcon@@ -661,6 +661,7 @@ const ToolsTable = memo(({ data, tags, count }: ToolsTableProps) => {count={count}columns={columns}data={data}+ infinite={{ dataKey: "tools", nextCursor, listKey: "tools" }}defaultColumnPinning={{left: ["id"]}}diff --git a/apps/erp/app/modules/items/ui/UnitOfMeasure/UnitOfMeasuresTable.tsx b/apps/erp/app/modules/items/ui/UnitOfMeasure/UnitOfMeasuresTable.tsxindex 736f70ec97..826d3d9792 100644--- a/apps/erp/app/modules/items/ui/UnitOfMeasure/UnitOfMeasuresTable.tsx+++ b/apps/erp/app/modules/items/ui/UnitOfMeasure/UnitOfMeasuresTable.tsx@@ -19,10 +19,11 @@ import type { UnitOfMeasure } from "../../types";type UnitOfMeasuresTableProps = {data: UnitOfMeasure[];count: number;+ nextCursor: string | null;};const UnitOfMeasuresTable = memo(- ({ data, count }: UnitOfMeasuresTableProps) => {+ ({ data, count, nextCursor }: UnitOfMeasuresTableProps) => {const [params] = useUrlParams();const navigate = useNavigate();const { t } = useLingui();@@ -95,6 +96,7 @@ const UnitOfMeasuresTable = memo(return (<Table<(typeof data)[number]>data={data}+ infinite={{ dataKey: "data", nextCursor, listKey: "units-of-measure" }}columns={columns}count={count}importCSV={[diff --git a/apps/erp/app/modules/people/people.service.ts b/apps/erp/app/modules/people/people.service.tsindex a724af369c..6d9b19e76c 100644--- a/apps/erp/app/modules/people/people.service.ts+++ b/apps/erp/app/modules/people/people.service.ts@@ -12,7 +12,7 @@ import type { z } from "zod";import type { DataType } from "~/modules/shared";import type { Employee } from "~/modules/users";import { getEmployees } from "~/modules/users/users.service";-import type { GenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";import type {@@ -104,6 +104,10 @@ async function getAttributes(.order("sortOrder", { foreignTable: "userAttribute", ascending: true });}+export const ATTRIBUTE_CATEGORIES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getAttributeCategories(client: SupabaseClient<Database>,@@ -113,7 +117,7 @@ export async function getAttributeCategories(let query = client.from("userAttributeCategory").select("*, userAttribute(id, name, attributeDataType(id))", {- count: LIST_COUNT+ count: args?.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId).eq("active", true)@@ -124,9 +128,7 @@ export async function getAttributeCategories(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, ATTRIBUTE_CATEGORIES_PAGING);}return query;@@ -254,6 +256,10 @@ export async function getHoliday(return client.from("holiday").select("*").eq("id", holidayId).single();}+export const HOLIDAYS_PAGING: Paging = {+ defaultSorts: [{ column: "date", ascending: true }]+};+/** @mcp read */export async function getHolidays(client: SupabaseClient<Database>,@@ -263,7 +269,7 @@ export async function getHolidays(let query = client.from("holiday").select("*", {- count: LIST_COUNT+ count: args?.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -272,9 +278,7 @@ export async function getHolidays(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "date", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, HOLIDAYS_PAGING);}return query;@@ -428,6 +432,10 @@ export async function getShift(.single();}+export const SHIFTS_PAGING: Paging = {+ defaultSorts: [{ column: "locationId", ascending: true }]+};+/** @mcp read */export async function getShifts(client: SupabaseClient<Database>,@@ -437,7 +445,7 @@ export async function getShifts(let query = client.from("shifts").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId).eq("active", true);@@ -446,9 +454,7 @@ export async function getShifts(query = query.ilike("name", `%${args.search}%`);}- query = setGenericQueryFilters(query, args, [- { column: "locationId", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, SHIFTS_PAGING);return query;}@@ -1020,6 +1026,10 @@ export async function getTimeCardEntries(return query;}+export const TIMECARD_ENTRIES_PAGING: Paging = {+ defaultSorts: [{ column: "clockIn", ascending: false }]+};+/** @mcp read */export async function getTimecardEntries(client: SupabaseClient<Database>,@@ -1028,7 +1038,7 @@ export async function getTimecardEntries() {let query = client.from("timeCardEntries")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {@@ -1037,9 +1047,7 @@ export async function getTimecardEntries();}- query = setGenericQueryFilters(query, args, [- { column: "clockIn", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, TIMECARD_ENTRIES_PAGING);return query;}diff --git a/apps/erp/app/modules/people/ui/Attributes/AttributeCategoriesTable.tsx b/apps/erp/app/modules/people/ui/Attributes/AttributeCategoriesTable.tsxindex bc00e842f7..f88582d5b4 100644--- a/apps/erp/app/modules/people/ui/Attributes/AttributeCategoriesTable.tsx+++ b/apps/erp/app/modules/people/ui/Attributes/AttributeCategoriesTable.tsx@@ -27,10 +27,11 @@ import type { AttributeCategory } from "../../types";type AttributeCategoriesTableProps = {data: AttributeCategory[];count: number;+ nextCursor: string | null;};const AttributeCategoriesTable = memo(- ({ data, count }: AttributeCategoriesTableProps) => {+ ({ data, count, nextCursor }: AttributeCategoriesTableProps) => {const { t } = useLingui();const navigate = useNavigate();const [params] = useUrlParams();@@ -183,6 +184,11 @@ const AttributeCategoriesTable = memo(<><Table<AttributeCategory>data={data}+ infinite={{+ dataKey: "categories",+ nextCursor,+ listKey: "attribute-categories"+ }}columns={columns}count={count ?? 0}primaryAction={diff --git a/apps/erp/app/modules/people/ui/Holidays/HolidaysTable.tsx b/apps/erp/app/modules/people/ui/Holidays/HolidaysTable.tsxindex 1db8a8548a..16754fe1ec 100644--- a/apps/erp/app/modules/people/ui/Holidays/HolidaysTable.tsx+++ b/apps/erp/app/modules/people/ui/Holidays/HolidaysTable.tsx@@ -21,10 +21,12 @@ import type { Holiday } from "../../types";type HolidaysTableProps = {data: Holiday[];count: number;+ nextCursor: string | null;years: number[];};-const HolidaysTable = memo(({ data, count, years }: HolidaysTableProps) => {+const HolidaysTable = memo((props: HolidaysTableProps) => {+ const { data, count, nextCursor, years } = props;const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -113,6 +115,7 @@ const HolidaysTable = memo(({ data, count, years }: HolidaysTableProps) => {return (<Table<(typeof data)[number]>data={data}+ infinite={{ dataKey: "holidays", nextCursor, listKey: "holidays" }}count={count}columns={columns}primaryAction={diff --git a/apps/erp/app/modules/people/ui/People/PeopleTable.tsx b/apps/erp/app/modules/people/ui/People/PeopleTable.tsxindex 3d43076e30..5d6047d6a2 100644--- a/apps/erp/app/modules/people/ui/People/PeopleTable.tsx+++ b/apps/erp/app/modules/people/ui/People/PeopleTable.tsx@@ -45,6 +45,7 @@ type PeopleTableProps = {attributeCategories: AttributeCategory[];data: Person[];count: number;+ nextCursor: string | null;employeeTypes: Partial<EmployeeType>[];shifts: { id: string; name: string }[];};@@ -54,6 +55,7 @@ const PeopleTable = memo(attributeCategories,data,count,+ nextCursor,employeeTypes,shifts}: PeopleTableProps) => {@@ -308,6 +310,7 @@ const PeopleTable = memo(count={count}columns={columns}data={data}+ infinite={{ dataKey: "people", nextCursor, listKey: "people" }}defaultColumnPinning={{left: ["Select", "User"]}}diff --git a/apps/erp/app/modules/people/ui/Shifts/ShiftsTable.tsx b/apps/erp/app/modules/people/ui/Shifts/ShiftsTable.tsxindex 086d688669..0f3be9610f 100644--- a/apps/erp/app/modules/people/ui/Shifts/ShiftsTable.tsx+++ b/apps/erp/app/modules/people/ui/Shifts/ShiftsTable.tsx@@ -34,10 +34,12 @@ import type { Shift } from "../../types";type ShiftsTableProps = {data: Shift[];count: number;+ nextCursor: string | null;locations: Partial<ShiftLocation>[];};-const ShiftsTable = memo(({ data, count, locations }: ShiftsTableProps) => {+const ShiftsTable = memo((props: ShiftsTableProps) => {+ const { data, count, nextCursor, locations } = props;const { t } = useLingui();const { locale } = useLocale();const navigate = useNavigate();@@ -224,6 +226,7 @@ const ShiftsTable = memo(({ data, count, locations }: ShiftsTableProps) => {return (<Table<Shift>data={data}+ infinite={{ dataKey: "shifts", nextCursor, listKey: "shifts" }}count={count}columns={columns}primaryAction={diff --git a/apps/erp/app/modules/people/ui/Timecards/TimecardsTable.tsx b/apps/erp/app/modules/people/ui/Timecards/TimecardsTable.tsxindex 53e3c76bec..b2e84d152c 100644--- a/apps/erp/app/modules/people/ui/Timecards/TimecardsTable.tsx+++ b/apps/erp/app/modules/people/ui/Timecards/TimecardsTable.tsx@@ -48,6 +48,7 @@ type TimeCardEntry = {type TimecardsTableProps = {data: TimeCardEntry[];count: number;+ nextCursor: string | null;};function formatTime(dateStr: string, locale: string) {@@ -65,7 +66,8 @@ function formatDuration(clockInStr: string, clockOutStr: string | null) {return `${hours}h ${minutes}m`;}-const TimecardsTable = memo(({ data, count }: TimecardsTableProps) => {+const TimecardsTable = memo((props: TimecardsTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const { locale } = useLocale();const navigate = useNavigate();@@ -267,6 +269,7 @@ const TimecardsTable = memo(({ data, count }: TimecardsTableProps) => {return (<Table<TimeCardEntry>data={data}+ infinite={{ dataKey: "entries", nextCursor, listKey: "timecards" }}count={count}columns={columns}primaryAction={diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex f8290baf06..6d62b1c3a4 100644--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@ -10,7 +10,7 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced- **Job Material** — BOM line within a make method. Each has a `methodType` (Pull from Inventory, Purchase to Order, Make to Order) that drives procurement.- **Production Event** — time tracking (Labor/Machine/Setup) against an operation.- **Production Quantity** — output recording (Production/Scrap/Rework) against an operation with optional `scrapReason`.-- **Operation Batch** (`jobOperationBatch`) — N job operations sharing one run on a **batchable process** (`process.batchable`: laser table, furnace, plating; `process.batchType` `Sequential`/`Simultaneous` = the s-batch/p-batch physics — serial queue vs parallel load — driving the batch's planned duration `setup(max) + Σ|max(run)` via `@carbon/utils` `batchDuration`). Jobs are never merged and the BOM is never modified; each member stays a first-class `jobOperation`. Time/cost split **proportional to `operationQuantity`**, materialized at completion as per-member `productionEvent` slices, so job costing/GL post per job with no special-casing. Status **`Planned → Active → Completing → Completed`** (no `Cancelled` — dissolve deletes a pre-start batch instead). `Planned` is the pre-floor state: composed in the builder from ANY live job's unstarted ops (the planner RPC no longer requires released jobs), fully editable (add/remove/work-center widened to Planned+Active pre-event), invisible to MES. **`Active` displays as "Released"** (exactly like job `Ready`); the `release` server-function intent (`Planned → Active`, requires ≥1 member — NO work center: the scheduler pre-pass auto-selects earliest-finish among the process's work centers and persists it to batch + members) puts members on the floor, and releasing it RELEASES its Draft/Planned member jobs through the job page's own path — `releaseBatchMemberJobs` → `releaseJobs` (`production.server.ts`: recalc, MRP, status Ready, outside-operation POs via `create` `purchaseOrderFromJob`, releasedDate) after `getJobReleaseReadiness` validates EVERY such job (assemblies without operations, manufacturing blocked, or an outside operation whose supplier can't be resolved — `resolveOperationSupplier`: its own supplier process, else the process's only supplier — refuse the whole batch untouched; there is no per-operation supplier picker on batch release); a supplier's first new PO is reused for the later jobs so a batch lands on one PO per supplier. The `BatchReleaseModal` (drawer, table row action, builder Create & Release) shows the checks and the per-supplier PO choice; bulk `batches/release` passes no choice, so a batch needing a fix or with Draft POs to choose from is skipped and named. Then it notifies the scheduler; `unrelease` (`Active → Planned`) is allowed only before the first production event. **Membership-handoff floor rule**: an op in a batch is floor-visible iff its BATCH is Released (`Active`/`Completing`) — even when its job is Draft/Planned; an op in no batch follows its JOB's release (the pre-batching rule — a released job's un-batched batchable op always remains runnable, never blocked; removing it from a batch is the escape hatch). Enforced in `get_active_job_operations_by_location`, MES `getOpenJobs`, AND server-side in the MES operation loader + start route (list visibility alone was the leak). **Scheduling**: a Released batch is ONE scheduling unit — the batch pre-pass (`packages/planning/src/scheduling/batch-scheduler.ts`, run by `runLocationSchedule` before the per-job passes) writes a single coalesced `capacityReservation` tagged `jobOperationBatchId` (NOT NULL `operationId`/`jobId` anchored on the min member op), members pin to the window in the selector (generalized pinned-OSP path, no per-member reservation), downstream ops chain after the batch end, and the anchor comes from persisted predecessor forecasts (overruns flag a conflict and converge next wave); a batch whose open members all carry zero time standards still surfaces — a flagged 1h placeholder (`workHours` 0, never blocks) with a conflict naming the data gap, instead of silently vanishing from the reservation-driven forecast; Planned batches still schedule per-op. Completion is **two-phase and resumable** — Phase 1 (one txn) slices events + records quantities + flips `Active → Completing`; Phase 2 (idempotent, server-function-owned) issues each member's BOM, flips members `Done`, posts GL, then `Completing → Completed`. A Phase-2 failure leaves the batch `Completing` and re-invoking resumes (no double issue/GL). A retry MUST resubmit the quantities Phase 1 recorded — a changed quantity is rejected, not silently applied. Proportional split logic lives in `@carbon/utils` `batch-time-split`. Distinct from lot/batch tracking (`trackedEntity`/`batchNumber`). Outside Processing operations are never batchable — a batch is one run on one of our work centers, and joining one would stamp its work center onto subcontracted work: `get_batchable_operations` leaves them out of the candidates and `assertEligible` refuses them. Mutations go through the `batch-operations` server function (create/add/remove/update/dissolve/complete); payload record ids are re-read under `companyId` (`assertCompanyRecord` for location/work center) and the batch table's location/process/workCenter FKs are composite `(<col>, "companyId")` (`20260905132037_job-operation-batching.sql` (the consolidated branch migration)), so a cross-tenant id is refused by the fn AND rejected by the schema. Batch COMPOSITION happens ONLY in the batch builder (below) — the operations priority board's select-to-batch flow (checkboxes on cards, `BatchSelectionProvider`, the floating create bar, and the `BatchOpportunity` banner/column hints) was removed 2026-09-01 at Sid's direction, after the dedicated drag-and-drop batching board went the same way 2026-08-21. The board still SHOWS batches: each live batch collapses to one `BatchItemCard` in its work-center column (drag across columns reassigns the batch work center via `priorityBatchingUpdate`; Completing cards are read-only). The one composition surface — a guided **batch builder** — launches from the Batches list (`New Batch`) and an Active batch's drawer (`Add operations` → add-mode): a full-screen three-step drawer wizard (`ui/Batches/BatchBuilder.tsx`) that picks a location + batchable process (deep-linkable via `?location=&process=`; the last scope/view is remembered in localStorage), fetches candidates from `api/production/batchable-operations` (the revived `getBatchableOperations` RPC wrapper, enriched with each op's setup/labor/machine time, due date, and item thumbnail, plus per-work-center queue load and a hidden-ops count), and offers local search, a due-window quick filter (7/14/30d, due-date-sorted), a dynamic local-state "+ Filter" facet picker over the dimensions the candidates' BOMs actually contain (the material ITEM itself plus substance/grade/dimension/form/finish where populated — ANY BOM line matches ALL active facets; active facets render as removable/editable chips), two list views (polished table or group-by-material-signature sections with per-group select-all and setup-saving chips — a line's signature falls back to its BOM item's readable id when no normalized properties exist, so property-less BOMs still group by what they consume; an operation with NO op-linked BOM lines takes the JOB's unassigned (`jobOperationId IS NULL`) lines — BOMs are routinely authored without per-operation assignment, and without the fallback every such op read "No materials", emptied the facet picker, and degraded grouping to the produced item), a prominent scored suggestions banner at the top of the operations list — groups ranked by `rankSuggestions` (blended, normalised score: setup saved + due urgency + capacity fit + dimension specificity; each signature group is first split into due-date clusters no wider than `SUGGESTION_DUE_WINDOW_DAYS` = 7 via `splitByDueWindow`, so a suggestion never spans weeks — same material next month is next month's batch), each row a one-click apply with a reason chip (due now / fills a run); grouping uses `groupingKey` (material signature, falling back to the produced item for material-less assembly ops) while the mixed-materials warning uses the materials-only `materialSignature`, so the fallback never fakes a material clash. The pure logic (signatures, value sets, duration math, scoring) lives in `ui/Batches/batch-builder-logic.ts` — no JSX/lingui, unit-tested by `apps/erp/test/batch-suggestions.test.ts`, and a live preview (count · quantity · estimated run time, setup-saving + due-spread chips, plus a non-blocking "mixing materials" warning — material compatibility guides but never blocks, per the locked spec decision). Create-mode can attach a work center (picker shows each center's queue depth) and optional notes (additive `notes` field on the server function's create payload), and — instead of creating a duplicate — offers a searchable **"Add to batch"** footer popover (`AddToBatchButton`: a `Command` list over the compatible Active same-process batches from `deriveAddTargets`, each row `readableId · N ops`, on-select → the same `add` submit) rather than one button per batch, so it scales to hundreds of open batches. When the chosen work center has a `batchCapacity` set, a fill bar under the picker shows selected qty vs capacity ("fits in one run" / "over capacity — N loads") plus a `minimumBatchQuantity` met/short line — purely ADVISORY, Create never blocks (`resources.workCenter.batchCapacity`/`minimumBatchQuantity`). The scoped process's `batchRules` (`process.batchRules`, threaded through `getBatchableProcesses`) drives compatibility: the candidate signature/facets/mixed-material warning use every non-"ignore" dimension (default substance/grade/dimension, with the material item as a fallback for property-less BOMs), a "guide" mismatch versus the current selection shows a quiet amber tag on the row, and a "must" mismatch renders the row visible-but-LOCKED (grey lock tag, checkbox no-op, excluded from suggestions/select-all — clears when the selection empties). All resolution/enforcement is the shared `@carbon/utils` `batch-compatibility` module (`resolveBatchRules`/`mustViolations`); the client uses names and the server function uses ids through the same value-agnostic fold, so they always agree. The server function's `assertMaterialCompatible` re-checks the WHOLE membership (create: incoming set; add: existing members + incoming) after `assertEligible` and rejects a must-violating batch naming the dimension — the LOCK in the UI is advisory-fast; the server function is the real gate. It submits `create`/`add` to the same `batching.update` action + `batch-operations` server function — no new mutation path. Completion (MES modal → `complete`) can mark a member "not in this run" (`excluded`): it detaches back to the schedule un-run inside the Phase-1 txn instead of flipping Done; excluded members carry no quantities, all-excluded is rejected (dissolve instead), and a resume drops already-applied exclusions but rejects new ones. Batches LIST at `/x/production/batches` (nav: Production → Batches; `getJobOperationBatches` + `getJobOperationBatchMemberStats` + `getJobOperationBatchMembers`); rows are **expandable** (`renderExpandedRow`/`canExpandRow` on the shared `Table`, same mechanism as the ECO change-notices table) to reveal each member operation (job link, item thumbnail + readable id, completed/qty + scrap); clicking a batch opens a FULL-SIZE detail drawer (`ui/Batches/BatchDetailDrawer.tsx`): header meta (status/process/WC/location/created-by/notes), an enriched member table (thumbnails, completed/qty + scrap, status badges), and a Run card — per-type actual-vs-plan progress (per-type plan buckets = max member setup + Σ|max labor/machine by `process.batchType`; the "Planned time" total = shared setup + Σ|max of each member's run `max(labor, machine)`, matching the scheduler's reservation and MES batch mode via `@carbon/utils` `batchPlanBreakdown`) with a pulsing timer-running badge and the batch's production-event history (`getJobOperationBatchWithMembers` + `getJobOperationBatchEvents`; completed batches show the per-member slices, which keep the batch tag). The Batches list also bulk-RELEASES via selectable rows → a "Release N batches" bulk action posting the selected **Planned** ids to the `batches/release` route (one release per id, mirroring the single-batch `batching.update` release branch: `releaseBatchMemberJobs` → `releaseJobOperationBatch` → `notifyScheduleInputsChanged`; per-batch server-function refusals land in the toast summary's `failed` list, the rest still release; a non-Planned id from a stale selection is skipped). Deleting from ERP = the server function's `dissolve`: single via the `batches/delete/:batchId` ConfirmDelete route (destructive "Dissolve Batch" in the table's row context menu + a destructive Dissolve button on the detail drawer, Active only), and bulk via selectable rows → a "Dissolve N batches" bulk action posting the selected Active ids to the `batches/dissolve` route (one server-function dissolve per id; the server's per-batch refusal for started batches lands in the toast summary's `failed` list, the rest still dissolve), and a printable **batch list** serves at `/file/batch/:id.pdf` (`BatchListPDF` in `@carbon/documents`; menu entries on the batch card and MES batch chip). **Materials and output lots (2026-09-16):** the MES batch-mode materials panel shows each item's summed BATCH requirement alongside the member's own (`getBatchMaterialTotals`), and ONE pick covers the whole batch — `issue` case `trackedEntitiesToBatch` splits the picked lot(s) **pro-rata by each member's REMAINING requirement** (`splitPickAcrossMembers` in `@carbon/utils` `batch-pick-split`, largest-remainder so shares sum exactly) and records each member's own consumption against its own WIP entity, so cost and lot genealogy stay per job while the operator acts once; the pick modal's default quantity is the batch remaining, NOT the member's share (defaulting to one member's share splits it again across all of them and satisfies none). Completion finalizes each member's produced lot via the lean `issue` case `jobOperationBatchOutput` (the `Produce` activity + entity flip EXTRACTED from `jobOperationBatchComplete`, WITHOUT that case's `productionQuantity` insert and backflush — Phase 1 and the Phase-2 issue step already did both), under lot numbers PLANNED AT CREATION — the builder's Output section (`ui/Batches/BatchOutputLots.tsx`) either sets each member's lot (written to its WIP `trackedEntity.readableId` by the `batch-operations` create) or, when every member makes the same batch-tracked item, "Combine output into one lot" (`jobOperationBatch.mergeOutput` + `outputLotNumber`, migration `20260918094217_batch-output-lot-at-creation.sql`); the operator never edits lots at completion. A merged batch's member lots are combined right after completion (and the batch drawer's "Merge output lots" covers a Completed batch kept separate) into ONE lot via `issue` `mergeTrackedEntities` — genealogy keeps every source job, so the merged lot is strictly more traceable than a single directly-produced one. Both entry points derive the parent ids SERVER-SIDE from the batch's membership and call the `issue` server function. Eligibility gained a `producedItem` dimension in `BATCH_RULE_DIMENSIONS` (default `ignore`) so a process can require members to make the same item. Serial-tracked members are unchanged — batch mode still disables tracked activity for them. Job surfaces show live-batch membership: a Batches column on the jobs table (loader-side lookup), a badge on the `JobBillOfProcess` operation row (`jobOperationBatch` embed), and a chip on the MES job DAG node.+- **Operation Batch** (`jobOperationBatch`) — N job operations sharing one run on a **batchable process** (`process.batchable`: laser table, furnace, plating; `process.batchType` `Sequential`/`Simultaneous` = the s-batch/p-batch physics — serial queue vs parallel load — driving the batch's planned duration `setup(max) + Σ|max(run)` via `@carbon/utils` `batchDuration`). Jobs are never merged and the BOM is never modified; each member stays a first-class `jobOperation`. Time/cost split **proportional to `operationQuantity`**, materialized at completion as per-member `productionEvent` slices, so job costing/GL post per job with no special-casing. Status **`Planned → Active → Completing → Completed`** (no `Cancelled` — dissolve deletes a pre-start batch instead). `Planned` is the pre-floor state: composed in the builder from ANY live job's unstarted ops (the planner RPC no longer requires released jobs), fully editable (add/remove/work-center widened to Planned+Active pre-event), invisible to MES. **`Active` displays as "Released"** (exactly like job `Ready`); the `release` server-function intent (`Planned → Active`, requires ≥1 member — NO work center: the scheduler pre-pass auto-selects earliest-finish among the process's work centers and persists it to batch + members) puts members on the floor, and releasing it RELEASES its Draft/Planned member jobs through the job page's own path — `releaseBatchMemberJobs` → `releaseJobs` (`production.server.ts`: recalc, MRP, status Ready, outside-operation POs via `create` `purchaseOrderFromJob`, releasedDate) after `getJobReleaseReadiness` validates EVERY such job (assemblies without operations, manufacturing blocked, or an outside operation whose supplier can't be resolved — `resolveOperationSupplier`: its own supplier process, else the process's only supplier — refuse the whole batch untouched; there is no per-operation supplier picker on batch release); a supplier's first new PO is reused for the later jobs so a batch lands on one PO per supplier. The `BatchReleaseModal` (drawer, table row action, builder Create & Release) shows the checks and the per-supplier PO choice; bulk `batches/release` passes no choice, so a batch needing a fix or with Draft POs to choose from is skipped and named. Then it notifies the scheduler; `unrelease` (`Active → Planned`) is allowed only before the first production event. **Membership-handoff floor rule**: an op in a batch is floor-visible iff its BATCH is Released (`Active`/`Completing`) — even when its job is Draft/Planned; an op in no batch follows its JOB's release (the pre-batching rule — a released job's un-batched batchable op always remains runnable, never blocked; removing it from a batch is the escape hatch). Enforced in `get_active_job_operations_by_location`, MES `getOpenJobs`, AND server-side in the MES operation loader + start route (list visibility alone was the leak). **Scheduling**: a Released batch is ONE scheduling unit — the batch pre-pass (`packages/planning/src/scheduling/batch-scheduler.ts`, run by `runLocationSchedule` before the per-job passes) writes a single coalesced `capacityReservation` tagged `jobOperationBatchId` (NOT NULL `operationId`/`jobId` anchored on the min member op), members pin to the window in the selector (generalized pinned-OSP path, no per-member reservation), downstream ops chain after the batch end, and the anchor comes from persisted predecessor forecasts (overruns flag a conflict and converge next wave); a batch whose open members all carry zero time standards still surfaces — a flagged 1h placeholder (`workHours` 0, never blocks) with a conflict naming the data gap, instead of silently vanishing from the reservation-driven forecast; Planned batches still schedule per-op. Completion is **two-phase and resumable** — Phase 1 (one txn) slices events + records quantities + flips `Active → Completing`; Phase 2 (idempotent, server-function-owned) issues each member's BOM, flips members `Done`, posts GL, then `Completing → Completed`. A Phase-2 failure leaves the batch `Completing` and re-invoking resumes (no double issue/GL). A retry MUST resubmit the quantities Phase 1 recorded — a changed quantity is rejected, not silently applied. Proportional split logic lives in `@carbon/utils` `batch-time-split`. Distinct from lot/batch tracking (`trackedEntity`/`batchNumber`). Outside Processing operations are never batchable — a batch is one run on one of our work centers, and joining one would stamp its work center onto subcontracted work: `get_batchable_operations` leaves them out of the candidates and `assertEligible` refuses them. Mutations go through the `batch-operations` server function (create/add/remove/update/dissolve/complete); payload record ids are re-read under `companyId` (`assertCompanyRecord` for location/work center) and the batch table's location/process/workCenter FKs are composite `(<col>, "companyId")` (`20260905132037_job-operation-batching.sql` (the consolidated branch migration)), so a cross-tenant id is refused by the fn AND rejected by the schema. Batch COMPOSITION happens ONLY in the batch builder (below) — the operations priority board's select-to-batch flow (checkboxes on cards, `BatchSelectionProvider`, the floating create bar, and the `BatchOpportunity` banner/column hints) was removed 2026-09-01 at Sid's direction, after the dedicated drag-and-drop batching board went the same way 2026-08-21. The board still SHOWS batches: each live batch collapses to one `BatchItemCard` in its work-center column (drag across columns reassigns the batch work center via `priorityBatchingUpdate`; Completing cards are read-only). The one composition surface — a guided **batch builder** — launches from the Batches list (`New Batch`) and an Active batch's drawer (`Add operations` → add-mode): a full-screen three-step drawer wizard (`ui/Batches/BatchBuilder.tsx`) that picks a location + batchable process (deep-linkable via `?location=&process=`; the last scope/view is remembered in localStorage), fetches candidates from `api/production/batchable-operations` (the revived `getBatchableOperations` RPC wrapper, enriched with each op's setup/labor/machine time, due date, and item thumbnail, plus per-work-center queue load and a hidden-ops count), and offers local search, a due-window quick filter (7/14/30d, due-date-sorted), a dynamic local-state "+ Filter" facet picker over the dimensions the candidates' BOMs actually contain (the material ITEM itself plus substance/grade/dimension/form/finish where populated — ANY BOM line matches ALL active facets; active facets render as removable/editable chips), two list views (polished table or group-by-material-signature sections with per-group select-all and setup-saving chips — a line's signature falls back to its BOM item's readable id when no normalized properties exist, so property-less BOMs still group by what they consume; an operation with NO op-linked BOM lines takes the JOB's unassigned (`jobOperationId IS NULL`) lines — BOMs are routinely authored without per-operation assignment, and without the fallback every such op read "No materials", emptied the facet picker, and degraded grouping to the produced item), a prominent scored suggestions banner at the top of the operations list — groups ranked by `rankSuggestions` (blended, normalised score: setup saved + due urgency + capacity fit + dimension specificity; each signature group is first split into due-date clusters no wider than `SUGGESTION_DUE_WINDOW_DAYS` = 7 via `splitByDueWindow`, so a suggestion never spans weeks — same material next month is next month's batch), each row a one-click apply with a reason chip (due now / fills a run); grouping uses `groupingKey` (material signature, falling back to the produced item for material-less assembly ops) while the mixed-materials warning uses the materials-only `materialSignature`, so the fallback never fakes a material clash. The pure logic (signatures, value sets, duration math, scoring) lives in `ui/Batches/batch-builder-logic.ts` — no JSX/lingui, unit-tested by `apps/erp/test/batch-suggestions.test.ts`, and a live preview (count · quantity · estimated run time, setup-saving + due-spread chips, plus a non-blocking "mixing materials" warning — material compatibility guides but never blocks, per the locked spec decision). Create-mode can attach a work center (picker shows each center's queue depth) and optional notes (additive `notes` field on the server function's create payload), and — instead of creating a duplicate — offers a searchable **"Add to batch"** footer popover (`AddToBatchButton`: a `Command` list over the compatible Active same-process batches from `deriveAddTargets`, each row `readableId · N ops`, on-select → the same `add` submit) rather than one button per batch, so it scales to hundreds of open batches. When the chosen work center has a `batchCapacity` set, a fill bar under the picker shows selected qty vs capacity ("fits in one run" / "over capacity — N loads") plus a `minimumBatchQuantity` met/short line — purely ADVISORY, Create never blocks (`resources.workCenter.batchCapacity`/`minimumBatchQuantity`). The scoped process's `batchRules` (`process.batchRules`, threaded through `getBatchableProcesses`) drives compatibility: the candidate signature/facets/mixed-material warning use every non-"ignore" dimension (default substance/grade/dimension, with the material item as a fallback for property-less BOMs), a "guide" mismatch versus the current selection shows a quiet amber tag on the row, and a "must" mismatch renders the row visible-but-LOCKED (grey lock tag, checkbox no-op, excluded from suggestions/select-all — clears when the selection empties). All resolution/enforcement is the shared `@carbon/utils` `batch-compatibility` module (`resolveBatchRules`/`mustViolations`); the client uses names and the server function uses ids through the same value-agnostic fold, so they always agree. The server function's `assertMaterialCompatible` re-checks the WHOLE membership (create: incoming set; add: existing members + incoming) after `assertEligible` and rejects a must-violating batch naming the dimension — the LOCK in the UI is advisory-fast; the server function is the real gate. It submits `create`/`add` to the same `batching.update` action + `batch-operations` server function — no new mutation path. Completion (MES modal → `complete`) can mark a member "not in this run" (`excluded`): it detaches back to the schedule un-run inside the Phase-1 txn instead of flipping Done; excluded members carry no quantities, all-excluded is rejected (dissolve instead), and a resume drops already-applied exclusions but rejects new ones. Batches LIST at `/x/production/batches` (nav: Production → Batches; `getJobOperationBatches` + `getJobOperationBatchMemberStats` + `getJobOperationBatchMembers`); rows are **expandable** (`renderExpandedRow`/`canExpandRow` on the shared `Table`, same mechanism as the ECO change-notices table) to reveal each member operation (job link, item thumbnail + readable id, completed/qty + scrap); clicking a batch opens a FULL-SIZE detail drawer (`ui/Batches/BatchDetailDrawer.tsx`): header meta (status/process/WC/location/created-by/notes), an enriched member table (thumbnails, completed/qty + scrap, status badges), and a Run card — per-type actual-vs-plan progress (per-type plan buckets = max member setup + Σ|max labor/machine by `process.batchType`; the "Planned time" total = shared setup + Σ|max of each member's run `max(labor, machine)`, matching the scheduler's reservation and MES batch mode via `@carbon/utils` `batchPlanBreakdown`) with a pulsing timer-running badge and the batch's production-event history (`getJobOperationBatchWithMembers` + `getJobOperationBatchEvents`; completed batches show the per-member slices, which keep the batch tag). The Batches list also bulk-RELEASES via selectable rows → a "Release N batches" bulk action posting the selected **Planned** ids to the `batches/release` route (one release per id, mirroring the single-batch `batching.update` release branch: `releaseBatchMemberJobs` → `releaseJobOperationBatch` → `notifyScheduleInputsChanged`; per-batch server-function refusals land in the toast summary's `failed` list, the rest still release; a non-Planned id from a stale selection is skipped; `bulkReleaseBatches` in `bulk-actions.server.ts`. With `{ allMatching }` in place of ids, the route starts the background `table-bulk-action` job instead — at most 2,000 matching batches, `ALL_MATCHING_RELEASE_LIMIT` in `utils/table-jobs.ts`). Deleting from ERP = the server function's `dissolve`: single via the `batches/delete/:batchId` ConfirmDelete route (destructive "Dissolve Batch" in the table's row context menu + a destructive Dissolve button on the detail drawer, Active only), and bulk via selectable rows → a "Dissolve N batches" bulk action posting the selected Planned or Active ids to the `batches/dissolve` route (`bulkDissolveBatches`: one server-function dissolve per id; the server's per-batch refusal for started batches lands in the toast summary's `failed` list, the rest still dissolve; a Completing or Completed batch is skipped; `{ allMatching }` runs it in the background job), and a printable **batch list** serves at `/file/batch/:id.pdf` (`BatchListPDF` in `@carbon/documents`; menu entries on the batch card and MES batch chip). **Materials and output lots (2026-09-16):** the MES batch-mode materials panel shows each item's summed BATCH requirement alongside the member's own (`getBatchMaterialTotals`), and ONE pick covers the whole batch — `issue` case `trackedEntitiesToBatch` splits the picked lot(s) **pro-rata by each member's REMAINING requirement** (`splitPickAcrossMembers` in `@carbon/utils` `batch-pick-split`, largest-remainder so shares sum exactly) and records each member's own consumption against its own WIP entity, so cost and lot genealogy stay per job while the operator acts once; the pick modal's default quantity is the batch remaining, NOT the member's share (defaulting to one member's share splits it again across all of them and satisfies none). Completion finalizes each member's produced lot via the lean `issue` case `jobOperationBatchOutput` (the `Produce` activity + entity flip EXTRACTED from `jobOperationBatchComplete`, WITHOUT that case's `productionQuantity` insert and backflush — Phase 1 and the Phase-2 issue step already did both), under lot numbers PLANNED AT CREATION — the builder's Output section (`ui/Batches/BatchOutputLots.tsx`) either sets each member's lot (written to its WIP `trackedEntity.readableId` by the `batch-operations` create) or, when every member makes the same batch-tracked item, "Combine output into one lot" (`jobOperationBatch.mergeOutput` + `outputLotNumber`, migration `20260918094217_batch-output-lot-at-creation.sql`); the operator never edits lots at completion. A merged batch's member lots are combined right after completion (and the batch drawer's "Merge output lots" covers a Completed batch kept separate) into ONE lot via `issue` `mergeTrackedEntities` — genealogy keeps every source job, so the merged lot is strictly more traceable than a single directly-produced one. Both entry points derive the parent ids SERVER-SIDE from the batch's membership and call the `issue` server function. Eligibility gained a `producedItem` dimension in `BATCH_RULE_DIMENSIONS` (default `ignore`) so a process can require members to make the same item. Serial-tracked members are unchanged — batch mode still disables tracked activity for them. Job surfaces show live-batch membership: a Batches column on the jobs table (loader-side lookup), a badge on the `JobBillOfProcess` operation row (`jobOperationBatch` embed), and a chip on the MES job DAG node.- **Procedure** — versioned work instructions linked to operations via `processId`. Statuses: Draft/Active/Archived.- **Assembly Instructions** — 3D animated work instructions, available to all users. (Previously gated to Carbon-internal emails via `requireAssembliesInternal` / `useFlags().isInternal`; that gate was removed to ship publicly.) **Versioned** (Draft/Published/Archived) as **row-per-version**, not an in-place counter: sibling versions are grouped by a self-referential `assemblyInstruction.rootInstructionId` (NULL = "I am the root"; group root = `rootInstructionId ?? id`, siblings = `id = root OR rootInstructionId = root`). `copyAssemblyInstructionAsVersion` spins a new editable **Draft** as a perfect copy (`version = max+1`, deep-copies steps with `parentStepId` remapped + each step's materials/slides/tools). `activateAssemblyInstructionVersion` makes a version active: publishes it, **archives the prior Published sibling**, and repoints `jobOperation.assemblyInstructionId` from other group versions to it — but only for active operations (status ≠ Done/Canceled) on active jobs (`!isJobLocked`). Only Draft is editable; the header exposes a "Versions" switcher + Make Active / New Version. `updateAssemblyInstructionStatus` no longer bumps `version`. The **list** (`getAssemblyInstructions`) reads the `assemblyInstructions` **view** (not the base table): it collapses each group to its latest version (`WHERE version = MAX(version)` per `rootInstructionId ?? id`) and rolls every sibling into a `versions` jsonb array, mirroring the `procedures` view — the table shows a `Version N` subtitle on the name plus a "Versions" hover card. Migration `20260730153412_assembly-instructions-view.sql`.- **Sub-assemblies** — a header row (`assemblyInstructionStep.isSubAssembly`, no parts of its own) plus the steps whose `parentStepId` is that header, stored directly BEFORE it in `sortOrder` (play order); the header's `usedInStepId` is the later step that fits the finished unit (NULL = it joins the main build at the header). One level only. Every structural write (`makeAssemblySubAssembly`, `insertAssemblyInstructionStep`, `updateAssemblySubAssembly`, `ungroupAssemblySubAssembly`, `deleteAssemblySubAssembly`, `updateAssemblyInstructionStepOrder`) is a Kysely transaction that locks the instruction, applies the change in memory, checks `validateSubAssemblies` and writes the new order — never a partial update. Header rows are never copied into job steps. The step that uses a sub-assembly never re-lists its parts, so BOM materials are seeded once. Viewer side: `packages/viewer/src/subassembly.ts`.@@ -86,7 +86,7 @@ pnpm --filter @carbon/erp test- `convertSalesOrderLinesToJobs` — creates jobs from sales order Make to Order lines; each job takes the order line's `configuration` (else the converted quote line's, via `resolveJobConfiguration` in `~/modules/sales`) and is built with `itemToJob` instead of `quoteLineToJob` when the order line was reconfigured- `getJob` / `getJobs` / `getJobMethodTree` / `getJobMethodTreeArray` — job reads with method hierarchy-- `releaseJobs` (`production.server.ts`) — the one release path (recalc, MRP, status Ready, outside-operation POs, releasedDate); returns the supplier→PO map with the POs it created so a caller releasing job by job keeps one PO per supplier, and `releasedJobIds` — the jobs that ARE Ready when it returns, so a PO failure after the flip is reported as "released, but …" and the job is still scheduled (bulk route `warnings`, job page flash). The flip is guarded: `updateJobStatus(..., { fromStatuses: ["Draft", "Planned"] })` adds `.in("status", …)` to the UPDATE and returns `updated: false` when the row no longer matched (someone cancelled or released it during the recalc/MRP), so the release stops instead of resurrecting the job; pinned by `test/job-status-guard.test.ts`. A failed MRP run is logged and never blocks the release (the 3-hourly MRP cron and Material Planning's Recalculate repair it); a failed `releasedDate` write is reported as "released, but …" because nothing else writes that date and the completion-time KPI reads it. Pinned by `test/release-jobs.test.ts`. Callers: the job Release dialog (`$jobId.status.tsx`), batch release (`releaseBatchMemberJobs`), and the jobs table's bulk **Release Jobs** action (`x+/job+/release.tsx`, `path.to.bulkReleaseJob`). Bulk release has no dialog: each selected Draft/Planned job is checked on its own (`getJobReleaseReadiness` once for the selection — every read goes through `fetchAllByIds`, which sends each id list in groups of 100 (an `in` filter rides in the URL) and pages each group with `fetchAllRecords` (a page of jobs passes PostgREST's 1000-row cap); pinned by `test/job-release-readiness.test.ts` — `jobReleaseProblems` in `ui/Jobs/job-release-logic.ts`, plus zero quantity and — via the per-job `supplierIds` — a supplier with Draft POs to choose from); a job with a problem is skipped and named in the toast's `failed` list, the rest release, then `runLocationSchedule` runs once per location. Pinned by `routes/x+/job+/release.test.ts`+- `releaseJobs` (`production.server.ts`) — the one release path (recalc, MRP, status Ready, outside-operation POs, releasedDate); returns the supplier→PO map with the POs it created so a caller releasing job by job keeps one PO per supplier, and `releasedJobIds` — the jobs that ARE Ready when it returns, so a PO failure after the flip is reported as "released, but …" and the job is still scheduled (bulk route `warnings`, job page flash). The flip is guarded: `updateJobStatus(..., { fromStatuses: ["Draft", "Planned"] })` adds `.in("status", …)` to the UPDATE and returns `updated: false` when the row no longer matched (someone cancelled or released it during the recalc/MRP), so the release stops instead of resurrecting the job; pinned by `test/job-status-guard.test.ts`. A failed MRP run is logged and never blocks the release (the 3-hourly MRP cron and Material Planning's Recalculate repair it); a failed `releasedDate` write is reported as "released, but …" because nothing else writes that date and the completion-time KPI reads it. Pinned by `test/release-jobs.test.ts`. Callers: the job Release dialog (`$jobId.status.tsx`), batch release (`releaseBatchMemberJobs`), and the jobs table's bulk **Release Jobs** action (`x+/job+/release.tsx`, `path.to.bulkReleaseJob`, which calls `bulkReleaseJobs` in `bulk-actions.server.ts`; with `{ allMatching }` in place of ids, or more than 25 selected ids (`fitsOneRequest`), it starts the background `table-bulk-action` job, at most 2,000 jobs; the job carries the supplier→PO map from one slice of 25 to the next, so later jobs go on the PO an earlier slice made). Bulk release has no dialog: each selected Draft/Planned job is checked on its own (`getJobReleaseReadiness` once for the selection — every read goes through `fetchAllByIds`, which sends each id list in groups of 100 (an `in` filter rides in the URL) and pages each group with `fetchAllRecords` (a page of jobs passes PostgREST's 1000-row cap); pinned by `test/job-release-readiness.test.ts` — `jobReleaseProblems` in `ui/Jobs/job-release-logic.ts`, plus zero quantity and — via the per-job `supplierIds` — a supplier with Draft POs to choose from); a job with a problem is skipped and named in the toast's `failed` list, the rest release, then `runLocationSchedule` runs once per location. Pinned by `routes/x+/job+/release.test.ts`- `getJobMaterialsWithQuantityOnHand` — BOM with on-hand for shortfall visibility- `getJobMaterialShortfallByItem` — priority-adjusted shortfall calculation- `getJobOrderStatusMap` — procurement status indicators per materialdiff --git a/apps/erp/app/modules/production/bulk-actions.server.ts b/apps/erp/app/modules/production/bulk-actions.server.tsnew file mode 100644index 0000000000..35763b9cc9--- /dev/null+++ b/apps/erp/app/modules/production/bulk-actions.server.ts@@ -0,0 +1,455 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { getCarbonServiceRole } from "@carbon/auth/client.server";+import type { Database } from "@carbon/database";+import type { Kysely, KyselyDatabase } from "@carbon/database/client";+import { getLogger } from "@carbon/logger";+import { runLocationSchedule } from "@carbon/planning";+import { chunkArray, getErrorMessage } from "@carbon/utils";+import type { SupabaseClient } from "@supabase/supabase-js";+import {+ type BulkDeleteResult,+ bulkDeleteByStatus+} from "~/utils/bulk-delete.server";+import {+ resolveUserClient,+ splitIdsByStatus,+ type UserClientSource+} from "~/utils/table-jobs";+import {+ isBatchDissolvable,+ isBatchReleasable,+ isJobBulkReleasable,+ JOB_BULK_DELETABLE_STATUSES+} from "./production.models";+import { releaseBatchMemberJobs, releaseJobs } from "./production.server";+import {+ getJobReleaseReadiness,+ notifyScheduleInputsChanged,+ releaseJobOperationBatch,+ updateJobOperationBatch+} from "./production.service";+import {+ bulkReleaseStartingPurchaseOrders,+ jobReleaseProblems+} from "./ui/Jobs/job-release-logic";++/**+ * The bulk actions of the jobs and batches tables. Each one is called by its+ * action route with the selected ids, and by the background bulk-action job+ * (`~/utils/table-jobs.server`) with 100 ids at a time. The per-row checks live+ * here, so both paths apply them: a row the action may not act on is skipped.+ *+ * In their own file, not `production.server.ts`: the jobs release route test+ * replaces `releaseJobs` there, and a module cannot replace its own calls.+ */++const logger = getLogger("erp", "production-bulk-actions");++/** An `.in()` filter rides in the request URL, so ids are read 100 at a time. */+const IN_CHUNK = 100;++type Args = {+ /** The user's client. The background job passes a factory that signs a new+ * token before the last expires; it is asked again before each row. */+ client: UserClientSource;+ companyId: string;+ userId: string;+};++type Problem = { readableId: string; message: string };++export type BulkReleaseJobsResult =+ | {+ success: true;+ released: number;+ /** Released, with something left to fix on the job (its POs). */+ warnings: Problem[];+ failed: Problem[];+ /** Selected jobs that are not Draft or Planned (a stale selection). */+ skipped: number;+ scheduled: boolean;+ /** The PO each supplier's outside operations went on. The background+ * release passes it to its next slice of jobs. */+ purchaseOrdersBySupplierId: Record<string, string>;+ }+ | { success: false; message: string };++/**+ * Releases each Draft / Planned job through the job page's release path+ * (`releaseJobs`) on its own: a job that is not ready is reported in `failed`+ * while the rest still release. There is no dialog, so a job with something+ * to fix or a purchase order to choose is skipped and named. A job in any+ * other status is skipped silently. Then each location is scheduled once.+ */+export async function bulkReleaseJobs({+ client,+ db,+ jobIds,+ companyId,+ userId,+ purchaseOrdersBySupplierId+}: Args & {+ db: Kysely<KyselyDatabase>;+ jobIds: string[];+ /** The map an earlier slice of the same bulk release returned. */+ purchaseOrdersBySupplierId?: Record<string, string>;+}): Promise<BulkReleaseJobsResult> {+ const ids = [...new Set(jobIds.filter(Boolean))];+ const readClient = await resolveUserClient(client);+ const jobs = [];+ for (const batch of chunkArray(ids, IN_CHUNK)) {+ const page = await readClient+ .from("job")+ .select("id, jobId, status, quantity, scrapQuantity, locationId")+ .in("id", batch)+ .eq("companyId", companyId);+ if (page.error) {+ logger.error("Failed to load the selected jobs", {+ companyId,+ error: page.error+ });+ return { success: false, message: "Failed to load the selected jobs" };+ }+ jobs.push(...page.data);+ }++ const releasable = jobs+ .filter((job) => isJobBulkReleasable(job.status))+ .sort((a, b) => a.jobId.localeCompare(b.jobId));+ const skipped = ids.length - releasable.length;+ const readiness = await getJobReleaseReadiness(+ readClient,+ releasable.map((job) => job.id),+ companyId+ );+ if (readiness.error || !readiness.data) {+ logger.error("Failed to validate the selected jobs", {+ companyId,+ error: readiness.error+ });+ return { success: false, message: "Failed to validate the selected jobs" };+ }++ const readinessByJobId = new Map(+ readiness.data.jobs.map((job) => [job.id, job] as const)+ );+ // Every supplier starts on a new PO, or on the one an earlier slice of this+ // release created; a PO a job creates is reused by the jobs after it, so the+ // selection lands on one PO per supplier.+ const starting = bulkReleaseStartingPurchaseOrders(+ readiness.data.suppliers,+ purchaseOrdersBySupplierId+ );+ const suppliersWithDraftPurchaseOrders = starting.suppliersToChoose;+ let purchaseOrders = starting.purchaseOrders;++ let released = 0;+ const failed: Problem[] = [];+ const warnings: Problem[] = [];+ const locationIds = new Set<string>();+ for (const job of releasable) {+ const ready = readinessByJobId.get(job.id);+ const problems = ready+ ? [+ // The job page disables Release for the same job.+ ...(job.quantity === 0 && job.scrapQuantity === 0+ ? ["nothing to make"]+ : []),+ ...jobReleaseProblems(ready),+ ...(ready.supplierIds.some((id) =>+ suppliersWithDraftPurchaseOrders.has(id)+ )+ ? ["choose a purchase order for its outside operations on the job"]+ : [])+ ]+ : ["could not be validated"];+ if (problems.length > 0) {+ failed.push({ readableId: job.jobId, message: problems.join("; ") });+ continue;+ }++ const result = await releaseJobs({+ client: await resolveUserClient(client),+ db,+ jobIds: [job.id],+ companyId,+ userId,+ purchaseOrdersBySupplierId: purchaseOrders+ });+ purchaseOrders = result.purchaseOrdersBySupplierId;+ if (result.error) {+ logger.error("Failed to release job", {+ companyId,+ jobId: job.id,+ error: result.error+ });+ }+ // The job is Ready when its id came back released, error or not; a job+ // that is Ready must be scheduled and counted, whatever failed after.+ if (!result.releasedJobIds.includes(job.id)) {+ failed.push({ readableId: job.jobId, message: result.error ?? "" });+ continue;+ }+ if (result.error) {+ warnings.push({ readableId: job.jobId, message: result.error });+ }++ locationIds.add(job.locationId);+ released += 1;+ }++ // After every status flip is persisted — the scheduler only places jobs that+ // are already released. One run per location, as on the job page.+ let scheduled = true;+ for (const locationId of locationIds) {+ try {+ await runLocationSchedule({+ db,+ client: getCarbonServiceRole(),+ locationId,+ companyId,+ userId+ });+ } catch (error) {+ logger.error("Failed to schedule released jobs", {+ companyId,+ locationId,+ error+ });+ scheduled = false;+ }+ }++ return {+ success: true,+ released,+ warnings,+ failed,+ skipped,+ scheduled,+ purchaseOrdersBySupplierId: {+ ...purchaseOrdersBySupplierId,+ ...purchaseOrders+ }+ };+}++export type BulkDeleteJobsResult = BulkDeleteResult;++/**+ * Deletes the jobs the table's bulk Delete may delete: Draft, Planned, Due+ * Today and Overdue. The status filter is part of the DELETE, so a job that+ * moved on since it was selected stays. The caller checks the+ * `delete: production` permission.+ */+export function bulkDeleteJobs({+ client,+ jobIds,+ companyId+}: {+ client: SupabaseClient<Database>;+ jobIds: string[];+ companyId: string;+}): Promise<BulkDeleteJobsResult> {+ return bulkDeleteByStatus({+ ids: jobIds,+ companyId,+ label: "jobs",+ deleteChunk: (ids) =>+ client+ .from("job")+ .delete()+ .in("id", ids)+ .eq("companyId", companyId)+ .in("status", [...JOB_BULK_DELETABLE_STATUSES])+ .select("id")+ });+}++export type BulkBatchResult =+ | {+ success: true;+ /** Batches released or dissolved. */+ done: number;+ failed: Problem[];+ /** Batches whose status the action does not accept, or not found. */+ skipped: number;+ }+ | { success: false; message: string };++async function readBatches(+ client: SupabaseClient<Database>,+ ids: string[],+ companyId: string+) {+ const rows = [];+ for (const chunk of chunkArray(ids, IN_CHUNK)) {+ const page = await client+ .from("jobOperationBatch")+ .select("id, readableId, status, workCenterId")+ .in("id", chunk)+ .eq("companyId", companyId);+ if (page.error) return { data: null, error: page.error };+ rows.push(...page.data);+ }+ return { data: rows, error: null };+}++/**+ * Releases each Planned batch on its own: a batch the server function refuses+ * (no members, production already recorded) is reported in `failed` while the+ * rest still release. Any other status is skipped, so a stale selection can't+ * flip an Active or Completing batch.+ */+export async function bulkReleaseBatches({+ client,+ db,+ batchIds,+ companyId,+ userId+}: Args & {+ db: Kysely<KyselyDatabase>;+ batchIds: string[];+}): Promise<BulkBatchResult> {+ const ids = [...new Set(batchIds.filter(Boolean))];+ const rows = await readBatches(+ await resolveUserClient(client),+ ids,+ companyId+ );+ if (rows.error || !rows.data) {+ logger.error("Failed to load the batches to release", {+ companyId,+ error: rows.error+ });+ return { success: false, message: "Failed to load the selected batches" };+ }+ const batchById = new Map(rows.data.map((row) => [row.id, row] as const));+ const { allowed, skipped } = splitIdsByStatus(+ ids,+ rows.data,+ isBatchReleasable+ );++ let released = 0;+ const failed: Problem[] = [];+ for (const batchId of allowed) {+ const batch = batchById.get(batchId)!;+ const batchClient = await resolveUserClient(client);+ const members = await batchClient+ .from("jobOperation")+ .select("jobId")+ .eq("jobOperationBatchId", batchId)+ .eq("companyId", companyId);+ if (members.error) {+ failed.push({+ readableId: batch.readableId,+ message: "Failed to load the batch members"+ });+ continue;+ }++ // Member jobs release first, through the job page's release path. With no+ // dialog here, a batch with an invalid job or a PO choice to make is+ // skipped and named — the planner releases it from its drawer.+ const releasedJobs = await releaseBatchMemberJobs({+ client: batchClient,+ db,+ jobIds: (members.data ?? []).map((op) => op.jobId),+ companyId,+ userId+ });+ if (releasedJobs.error) {+ failed.push({+ readableId: batch.readableId,+ message: releasedJobs.error+ });+ continue;+ }++ const result = await releaseJobOperationBatch(batchClient, db, {+ batchId,+ companyId,+ userId+ });+ if (result.error) {+ failed.push({+ readableId: batch.readableId,+ message: getErrorMessage(result.error, "Failed to release")+ });+ continue;+ }++ // After the status flip is persisted — the wave must see the new state.+ await notifyScheduleInputsChanged(+ companyId,+ "work-center",+ "batch released",+ batch.workCenterId ?? undefined+ );+ released += 1;+ }++ return { success: true, done: released, failed, skipped };+}++/**+ * Dissolves each Planned or Active batch on its own: a batch that has recorded+ * production is refused by the server function and reported in `failed`. A+ * Completing or Completed batch is skipped.+ */+export async function bulkDissolveBatches({+ client,+ db,+ batchIds,+ companyId,+ userId+}: Args & {+ db: Kysely<KyselyDatabase>;+ batchIds: string[];+}): Promise<BulkBatchResult> {+ const ids = [...new Set(batchIds.filter(Boolean))];+ const rows = await readBatches(+ await resolveUserClient(client),+ ids,+ companyId+ );+ if (rows.error || !rows.data) {+ logger.error("Failed to load the batches to dissolve", {+ companyId,+ error: rows.error+ });+ return { success: false, message: "Failed to load the selected batches" };+ }+ const readableById = new Map(+ rows.data.map((row) => [row.id, row.readableId] as const)+ );+ const { allowed, skipped } = splitIdsByStatus(+ ids,+ rows.data,+ isBatchDissolvable+ );++ let dissolved = 0;+ const failed: Problem[] = [];+ for (const batchId of allowed) {+ const result = await updateJobOperationBatch(+ await resolveUserClient(client),+ db,+ { type: "dissolve", batchId, companyId, userId }+ );+ if (result.error) {+ failed.push({+ readableId: readableById.get(batchId) ?? batchId,+ message: getErrorMessage(result.error, "Failed to dissolve")+ });+ } else {+ dissolved += 1;+ }+ }++ return { success: true, done: dissolved, failed, skipped };+}diff --git a/apps/erp/app/modules/production/production.models.test.ts b/apps/erp/app/modules/production/production.models.test.tsnew file mode 100644index 0000000000..d721d6383e--- /dev/null+++ b/apps/erp/app/modules/production/production.models.test.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it, vi } from "vitest";++// The models' module graph can reach @carbon/content/glossary and Lingui `msg`+// macros at module load, which plain vitest does not transform. The helpers+// under test need neither (same stubs as production.service.test.ts).+vi.mock("@carbon/content/glossary", () => ({+ terms: {},+ getEntry: vi.fn(),+ lookupEntry: vi.fn(),+ hasEntry: vi.fn(),+ termSlug: vi.fn(),+ glossaryEntries: () => []+}));+vi.mock("@lingui/core/macro", () => ({+ msg: (strings: TemplateStringsArray | string, ...values: unknown[]) =>+ Array.isArray(strings)+ ? strings.reduce(+ (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),+ ""+ )+ : String(strings)+}));++const {+ isBatchDissolvable,+ isBatchReleasable,+ isJobBulkDeletable,+ isJobBulkReleasable,+ jobStatus+} = await import("./production.models");++describe("isJobBulkDeletable", () => {+ it("accepts Draft, Planned and the 2 deprecated due statuses only", () => {+ const deletable = jobStatus.filter(isJobBulkDeletable);+ expect(deletable).toEqual(["Draft", "Planned", "Overdue", "Due Today"]);+ expect(isJobBulkDeletable(null)).toBe(false);+ });+});++describe("isJobBulkReleasable", () => {+ it("accepts Draft and Planned only", () => {+ expect(jobStatus.filter(isJobBulkReleasable)).toEqual(["Draft", "Planned"]);+ });+});++describe("batch status gates", () => {+ const statuses = ["Planned", "Active", "Completing", "Completed"];++ it("releases a Planned batch only", () => {+ expect(statuses.filter(isBatchReleasable)).toEqual(["Planned"]);+ });++ it("dissolves a Planned or Active batch only", () => {+ expect(statuses.filter(isBatchDissolvable)).toEqual(["Planned", "Active"]);+ });+});diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.tsindex 5cdbf42564..be388d4ca1 100644--- a/apps/erp/app/modules/production/production.models.ts+++ b/apps/erp/app/modules/production/production.models.ts@@ -90,7 +90,8 @@ export {PLANNING_ACTIONS_COLUMN,PLANNING_ASSIGNEE_COLUMN,PLANNING_DRAWER_PARAM,- resolvePlanningActionScope+ resolvePlanningActionScope,+ withPlanningActions} from "./ui/Planning/planning-action-scope";/**@@ -118,6 +119,37 @@ export function isJobLocked(status: string | null | undefined): boolean {);}+/** The statuses the jobs table's bulk Delete acts on. "Due Today" and+ * "Overdue" are deprecated statuses that old jobs can still hold. */+export const JOB_BULK_DELETABLE_STATUSES = [+ "Draft",+ "Planned",+ "Due Today",+ "Overdue"+] as const;++export function isJobBulkDeletable(status: string | null | undefined): boolean {+ return JOB_BULK_DELETABLE_STATUSES.some((allowed) => allowed === status);+}++/** The statuses the jobs table's bulk Release acts on. */+export function isJobBulkReleasable(+ status: string | null | undefined+): boolean {+ return status === "Draft" || status === "Planned";+}++/** Release is the Planned → Active flip of an operation batch. */+export function isBatchReleasable(status: string | null | undefined): boolean {+ return status === "Planned";+}++/** A started batch must be completed, not dissolved; a completed one is+ * history. */+export function isBatchDissolvable(status: string | null | undefined): boolean {+ return status === "Planned" || status === "Active";+}+export const DATE_COLUMN_SENTINELS = ["unscheduled","next-week",diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 9fd5f328f5..e3e5fa2135 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -52,7 +52,7 @@ import { nanoid } from "nanoid";import type { z } from "zod";import { createDocumentUploadUrl } from "~/modules/documents/documents.service";import type { StorageItem } from "~/types";-import type { GenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";import {getGenericFilter,LIST_COUNT,@@ -1257,6 +1257,10 @@ export async function getProductionEventsByJob(.eq("jobOperation.jobId", jobId);}+export const JOBS_PAGING: Paging = {+ defaultSorts: [{ column: "jobId", ascending: false }]+};+/** @mcp read */export async function getJobs(client: SupabaseClient<Database>,@@ -1265,8 +1269,9 @@ export async function getJobs() {let query = client.from("jobs")+ // Later pages (`cursor`) skip the count: the first page already has it..select("*", {- count: LIST_COUNT+ count: args?.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -1275,9 +1280,7 @@ export async function getJobs(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "jobId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, JOBS_PAGING);}return query;@@ -1962,6 +1965,14 @@ export async function getJobOperation(.single();}+export const JOB_OPERATIONS_PAGING: Paging = {+ defaultSorts: [+ { column: "description", ascending: true },+ { column: "order", ascending: true },+ { column: "createdAt", ascending: false }+ ]+};+/** @mcp read */export async function getJobOperations(client: SupabaseClient<Database>,@@ -1973,7 +1984,8 @@ export async function getJobOperations(.select("*, jobMakeMethod(parentMaterialId, item(readableIdWithRevision))",{- count: LIST_COUNT+ // Later pages (`cursor`) skip the count: the first page already has it.+ count: args?.cursor ? undefined : LIST_COUNT}).eq("jobId", jobId);@@ -1983,11 +1995,7 @@ export async function getJobOperations(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "description", ascending: true },- { column: "order", ascending: true },- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, JOB_OPERATIONS_PAGING);}return query;@@ -2026,12 +2034,24 @@ export async function getJobOperationAttachments(): Promise<Record<string, string[]>> {if (jobOperationIds.length === 0) return {};- const { data: operationAttributes } = await client- .from("jobOperationStep")- .select("*, jobOperationStepRecord(*)")- .in("operationId", jobOperationIds);-- if (!operationAttributes) return {};+ // 100 ids per request (a long `.in()` list overflows the request URL),+ // 8 requests at a time.+ const results = await async.map(+ chunkArray(jobOperationIds, 100),+ async (ids) =>+ await client+ .from("jobOperationStep")+ .select("*, jobOperationStepRecord(*)")+ .in("operationId", ids)+ );+ const failed = results.find((result) => result.error);+ if (failed) {+ // The attachments are extras on the page: it shows without them.+ logger.error("Failed to load job operation attachments", {+ error: failed.error+ });+ }+ const operationAttributes = results.flatMap((result) => result.data ?? []);const attachmentsByOperation: Record<string, string[]> = {};operationAttributes.forEach((attr) => {@@ -2079,6 +2099,10 @@ export async function getJobOperationsByMethodId(.order("order", { ascending: true });}+export const JOB_OPERATION_STEP_RECORDS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getJobOperationStepRecords(client: SupabaseClient<Database>,@@ -2099,9 +2123,11 @@ export async function getJobOperationStepRecords();}- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(+ query,+ args,+ JOB_OPERATION_STEP_RECORDS_PAGING+ );return query;}@@ -2169,6 +2195,10 @@ export async function getProcedureVersions(.order("version", { ascending: false });}+export const PROCEDURES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getProcedures(client: SupabaseClient<Database>,@@ -2178,7 +2208,8 @@ export async function getProcedures(let query = client.from("procedures").select("*", {- count: LIST_COUNT+ // Later pages (`cursor`) skip the count: the first page already has it.+ count: args?.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -2187,9 +2218,7 @@ export async function getProcedures(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, PROCEDURES_PAGING);}return query;@@ -2226,6 +2255,15 @@ export async function getProductionEvent(.single();}+// The start time was a fixed order ahead of every sort. The cursor must follow+// each column the list orders by, so it is the first default sort instead.+export const PRODUCTION_EVENTS_PAGING: Paging = {+ defaultSorts: [+ { column: "startTime", ascending: true },+ { column: "createdAt", ascending: false }+ ]+};+/** @mcp read */export async function getProductionEvents(client: SupabaseClient<Database>,@@ -2237,21 +2275,17 @@ export async function getProductionEvents(.select("*, jobOperation(description, jobMakeMethod(parentMaterialId, item(readableIdWithRevision)))",{- count: LIST_COUNT+ // Later pages (`cursor`) skip the count: the first page already has it.+ count: args?.cursor ? undefined : LIST_COUNT})- .in("jobOperationId", jobOperationIds)- .order("startTime", { ascending: true });+ .in("jobOperationId", jobOperationIds);if (args?.search) {query = query.or(`jobOperation.description.ilike.%${args.search}%`);}- if (args) {- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);- }+ query = setGenericQueryFilters(query, args ?? {}, PRODUCTION_EVENTS_PAGING);return query;}@@ -2304,6 +2338,16 @@ export async function getProductionEventsByOperations(.order("startTime", { ascending: true });}+// What the row's Order / Make button offers (the grid RPC's orderQuantity,+// from MRP's open new-supply actions), then the part number so a page is+// stable when many rows have nothing to order.+export const PRODUCTION_PLANNING_PAGING: Paging = {+ defaultSorts: [+ { column: "orderQuantity", ascending: false },+ { column: "readableIdWithRevision", ascending: true }+ ]+};+/** @mcp read */export async function getProductionPlanning(client: SupabaseClient<Database>,@@ -2339,7 +2383,8 @@ export async function getProductionPlanning(action_assignees: args.actionAssignees},{- count: LIST_COUNT+ // Later pages (`cursor`) skip the count: the first page already has it.+ count: args.cursor ? undefined : LIST_COUNT});@@ -2349,17 +2394,15 @@ export async function getProductionPlanning();}- // What the row's Order / Make button offers (the grid RPC's orderQuantity,- // from MRP's open new-supply actions), then the part number so a page is- // stable when many rows have nothing to order.- query = setGenericQueryFilters(query, args, [- { column: "orderQuantity", ascending: false },- { column: "readableIdWithRevision", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, PRODUCTION_PLANNING_PAGING);return query;}+export const PRODUCTION_PROJECTIONS_PAGING: Paging = {+ defaultSorts: [{ column: "readableIdWithRevision", ascending: true }]+};+/** @mcp read */export async function getProductionProjections(client: SupabaseClient<Database>,@@ -2378,7 +2421,8 @@ export async function getProductionProjections(periods},{- count: LIST_COUNT+ // Later pages (`cursor`) skip the count: the first page already has it.+ count: args.cursor ? undefined : LIST_COUNT});@@ -2388,9 +2432,7 @@ export async function getProductionProjections();}- query = setGenericQueryFilters(query, args, [- { column: "readableIdWithRevision", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, PRODUCTION_PROJECTIONS_PAGING);return query;}@@ -2407,6 +2449,10 @@ export async function getProductionQuantity(.single();}+export const PRODUCTION_QUANTITIES_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getProductionQuantities(client: SupabaseClient<Database>,@@ -2418,7 +2464,8 @@ export async function getProductionQuantities(.select("*, jobOperation(description, jobMakeMethod(parentMaterialId, item(readableIdWithRevision)))",{- count: LIST_COUNT+ // Later pages (`cursor`) skip the count: the first page already has it.+ count: args?.cursor ? undefined : LIST_COUNT}).in("jobOperationId", jobOperationIds);@@ -2428,9 +2475,7 @@ export async function getProductionQuantities(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, PRODUCTION_QUANTITIES_PAGING);}return query;@@ -2491,6 +2536,10 @@ export async function getScrapReason(.single();}+export const SCRAP_REASONS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getScrapReasons(client: SupabaseClient<Database>,@@ -2499,7 +2548,10 @@ export async function getScrapReasons() {let query = client.from("scrapReason")- .select("id, name, customFields", { count: LIST_COUNT })+ // Later pages (`cursor`) skip the count: the first page already has it.+ .select("id, name, customFields", {+ count: args?.cursor ? undefined : LIST_COUNT+ }).eq("companyId", companyId);if (args?.search) {@@ -2507,9 +2559,7 @@ export async function getScrapReasons(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, SCRAP_REASONS_PAGING);}return query;@@ -6636,6 +6686,10 @@ export async function getUnbatchedBatchableOperationCount(.not("job.status", "in", "(Completed,Closed,Cancelled)");}+export const JOB_OPERATION_BATCHES_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getJobOperationBatches(client: SupabaseClient<Database>,@@ -6644,7 +6698,10 @@ export async function getJobOperationBatches() {let query = client.from("jobOperationBatch")- .select("*, process(name), workCenter(name)", { count: LIST_COUNT })+ // Later pages (`cursor`) skip the count: the first page already has it.+ .select("*, process(name), workCenter(name)", {+ count: args?.cursor ? undefined : LIST_COUNT+ }).eq("companyId", companyId);if (args?.search) {@@ -6652,9 +6709,7 @@ export async function getJobOperationBatches(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, JOB_OPERATION_BATCHES_PAGING);}return query;@@ -7022,17 +7077,23 @@ export async function getAssemblyInstruction(.single();}-/** @mcp read */-export async function getAssemblyInstructions(+// Newest first. Not `updatedAt`: it is null until the first edit, and the+// cursor follows Postgres' order, which puts those nulls first.+export const ASSEMBLY_INSTRUCTIONS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};++type AssemblyInstructionsScope = {+ companyId: string;+ search?: string;+ status?: (typeof assemblyInstructionStatuses)[number];+ itemId?: string;+};++function assemblyInstructionsQuery(client: SupabaseClient<Database>,- args: {- companyId: string;- search?: string;- status?: (typeof assemblyInstructionStatuses)[number];- itemId?: string;- limit?: number;- offset?: number;- }+ args: AssemblyInstructionsScope,+ count: typeof LIST_COUNT | undefined) {let query = client// "assemblyInstructions" (plural) is the version-collapsing view: one row@@ -7041,7 +7102,7 @@ export async function getAssemblyInstructions(// 20260730153412_assembly-instructions-view migration..from("assemblyInstructions").select("*, modelUpload(id, name, componentCount, processingStatus)", {- count: "exact"+ count}).eq("companyId", args.companyId);@@ -7054,14 +7115,47 @@ export async function getAssemblyInstructions(if (args.itemId) {query = query.eq("itemId", args.itemId);}- if (args.limit) {- query = query.limit(args.limit);- }- if (args.offset) {- query = query.range(args.offset, args.offset + (args.limit ?? 25) - 1);+ return query;+}++/** @mcp read */+export async function getAssemblyInstructions(+ client: SupabaseClient<Database>,+ args: {+ companyId: string;+ search?: string;+ status?: (typeof assemblyInstructionStatuses)[number];+ itemId?: string;+ limit?: number;+ offset?: number;}+) {+ let query = assemblyInstructionsQuery(client, args, LIST_COUNT);+ // With only `limit`, the read starts at offset 0.+ query = setGenericQueryFilters(+ query,+ { limit: args.limit, offset: args.offset ?? 0 },+ ASSEMBLY_INSTRUCTIONS_PAGING+ );+ return query;+}- return query.order("updatedAt", { ascending: false, nullsFirst: false });+/**+ * One cursor page of the assembly instructions list (`limit + 1` rows for+ * `toPage`). Not an MCP tool: MCP pages by offset through+ * `getAssemblyInstructions`. Only the first page counts.+ */+export async function getAssemblyInstructionsPage(+ client: SupabaseClient<Database>,+ args: AssemblyInstructionsScope & Partial<GenericQueryFilters>+) {+ let query = assemblyInstructionsQuery(+ client,+ args,+ args.cursor ? undefined : LIST_COUNT+ );+ query = setGenericQueryFilters(query, args, ASSEMBLY_INSTRUCTIONS_PAGING);+ return query;}/** @mcp read */diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionsTable.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionsTable.tsxindex 808fc8a1b3..0927c6e98c 100644--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionsTable.tsx+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionsTable.tsx@@ -50,6 +50,8 @@ import AssemblyInstructionStatus from "./AssemblyInstructionStatus";type AssemblyInstructionsTableProps = {data: AssemblyInstructionListItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const itemTypesWithDetails = ["Part", "Material", "Tool", "Consumable"];@@ -71,7 +73,7 @@ function ProcessingStatus({ status }: { status?: string | null }) {}const AssemblyInstructionsTable = memo(- ({ data, count }: AssemblyInstructionsTableProps) => {+ ({ data, count, nextCursor }: AssemblyInstructionsTableProps) => {const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -287,6 +289,11 @@ const AssemblyInstructionsTable = memo(data={data}columns={columns}count={count}+ infinite={{+ dataKey: "instructions",+ nextCursor,+ listKey: "assembly-instructions"+ }}primaryAction={permissions.can("create", "production") && (<Newdiff --git a/apps/erp/app/modules/production/ui/Batches/BatchesTable.tsx b/apps/erp/app/modules/production/ui/Batches/BatchesTable.tsxindex 6c51396a29..2ba46e556e 100644--- a/apps/erp/app/modules/production/ui/Batches/BatchesTable.tsx+++ b/apps/erp/app/modules/production/ui/Batches/BatchesTable.tsx@@ -34,15 +34,28 @@ import {import { Link, useFetcher, useNavigate } from "react-router";import { DateTime, Hyperlink, ItemThumbnail, New, Table } from "~/components";import { Enumerable } from "~/components/Enumerable";+import type { BulkActionScope } from "~/components/Table";import { usePermissions } from "~/hooks";+import {+ useAllMatchingLimitLabel,+ useBulkStartToast+} from "~/hooks/useBulkAction";import { useCustomColumns } from "~/hooks/useCustomColumns";+import {+ bulkSelectionBody,+ isOverAllMatchingLimit+} from "~/utils/bulk-selection";import { path } from "~/utils/path";+import { ALL_MATCHING_RELEASE_LIMIT } from "~/utils/table-jobs";+import { isBatchDissolvable, isBatchReleasable } from "../../production.models";import type { JobOperationBatch } from "../../types";import { BatchReleaseModal } from "./BatchReleaseModal";type BatchesTableProps = {data: JobOperationBatch[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const BATCH_STATUSES = [@@ -94,9 +107,13 @@ function useBatchCountMessages() {);}-const BatchesTable = memo(({ data, count }: BatchesTableProps) => {+const BatchesTable = memo(({ data, count, nextCursor }: BatchesTableProps) => {const { t } = useLingui();const countMessages = useBatchCountMessages();+ const showBulkStart = useBulkStartToast();+ const releaseLimitLabel = useAllMatchingLimitLabel(+ ALL_MATCHING_RELEASE_LIMIT+ );const permissions = usePermissions();const navigate = useNavigate();const canUpdate = permissions.can("update", "production");@@ -207,6 +224,7 @@ const BatchesTable = memo(({ data, count }: BatchesTableProps) => {const dissolveFetcher = useFetcher<{success?: boolean;message?: string;+ background?: boolean;dissolved?: number;failed?: { readableId: string; message: string }[];}>();@@ -219,11 +237,7 @@ const BatchesTable = memo(({ data, count }: BatchesTableProps) => {if (!wasDissolving.current) return;wasDissolving.current = false;const d = dissolveFetcher.data;- if (!d) return;- if (d.success === false && d.message) {- toast.error(d.message);- return;- }+ if (!d || showBulkStart(d)) return;if (d.dissolved) {toast.success(countMessages.dissolved(d.dissolved));}@@ -234,7 +248,13 @@ const BatchesTable = memo(({ data, count }: BatchesTableProps) => {.join(", ")} — production already recorded`);}- }, [dissolveFetcher.state, dissolveFetcher.data, t, countMessages]);+ }, [+ dissolveFetcher.state,+ dissolveFetcher.data,+ t,+ countMessages,+ showBulkStart+ ]);// Bulk release for the selected rows — Planned batches only (release is the// Planned → Active flip; Active/Completing/Completed batches are already on or@@ -243,6 +263,7 @@ const BatchesTable = memo(({ data, count }: BatchesTableProps) => {const releaseBatchesFetcher = useFetcher<{success?: boolean;message?: string;+ background?: boolean;released?: number;failed?: { readableId: string; message: string }[];}>();@@ -255,11 +276,7 @@ const BatchesTable = memo(({ data, count }: BatchesTableProps) => {if (!wasReleasingBatches.current) return;wasReleasingBatches.current = false;const d = releaseBatchesFetcher.data;- if (!d) return;- if (d.success === false && d.message) {- toast.error(d.message);- return;- }+ if (!d || showBulkStart(d)) return;if (d.released) {toast.success(countMessages.released(d.released));}@@ -274,14 +291,24 @@ const BatchesTable = memo(({ data, count }: BatchesTableProps) => {releaseBatchesFetcher.state,releaseBatchesFetcher.data,t,- countMessages+ countMessages,+ showBulkStart]);const renderActions = useCallback(- (selectedRows: JobOperationBatch[]) => {- const releasable = selectedRows.filter((r) => r.status === "Planned");- const dissolvable = selectedRows.filter(- (r) => r.status === "Planned" || r.status === "Active"+ (selectedRows: JobOperationBatch[], scope?: BulkActionScope) => {+ const releasable = selectedRows.filter((r) =>+ isBatchReleasable(r.status)+ );+ const dissolvable = selectedRows.filter((r) =>+ isBatchDissolvable(r.status)+ );+ // Every matching row: the server picks the batches each action may act+ // on and skips the rest. Release runs on at most 2,000 of them.+ const allMatching = scope?.allMatching;+ const overReleaseLimit = isOverAllMatchingLimit(+ scope,+ ALL_MATCHING_RELEASE_LIMIT);return (<DropdownMenuContent align="end" className="min-w-[220px]">@@ -290,10 +317,18 @@ const BatchesTable = memo(({ data, count }: BatchesTableProps) => {</DropdownMenuLabel><DropdownMenuSeparator /><DropdownMenuItem- disabled={releasable.length === 0 || !canUpdate}+ disabled={+ (!allMatching && releasable.length === 0) ||+ overReleaseLimit ||+ !canUpdate+ }onClick={() =>releaseBatchesFetcher.submit(- { batchIds: releasable.map((r) => r.id) },+ bulkSelectionBody({+ scope,+ idsField: "batchIds",+ ids: releasable.map((r) => r.id)+ }),{method: "post",action: path.to.releaseOperationBatches,@@ -303,14 +338,29 @@ const BatchesTable = memo(({ data, count }: BatchesTableProps) => {}><DropdownMenuIcon icon={<LuCirclePlay />} />- {countMessages.release(releasable.length)}+ <div className="flex flex-col">+ {allMatching ? (+ <Trans>Release batches</Trans>+ ) : (+ countMessages.release(releasable.length)+ )}+ {overReleaseLimit && (+ <span className="text-xs text-muted-foreground">+ {releaseLimitLabel}+ </span>+ )}+ </div></DropdownMenuItem><DropdownMenuItemdestructive- disabled={dissolvable.length === 0 || !canUpdate}+ disabled={(!allMatching && dissolvable.length === 0) || !canUpdate}onClick={() =>dissolveFetcher.submit(- { batchIds: dissolvable.map((r) => r.id) },+ bulkSelectionBody({+ scope,+ idsField: "batchIds",+ ids: dissolvable.map((r) => r.id)+ }),{method: "post",action: path.to.dissolveOperationBatches,@@ -320,12 +370,22 @@ const BatchesTable = memo(({ data, count }: BatchesTableProps) => {}><DropdownMenuIcon icon={<LuTrash />} />- {countMessages.dissolve(dissolvable.length)}+ {allMatching ? (+ <Trans>Dissolve batches</Trans>+ ) : (+ countMessages.dissolve(dissolvable.length)+ )}</DropdownMenuItem></DropdownMenuContent>);},- [canUpdate, dissolveFetcher, releaseBatchesFetcher, countMessages]+ [+ canUpdate,+ dissolveFetcher,+ releaseBatchesFetcher,+ countMessages,+ releaseLimitLabel+ ]);const customColumns =@@ -388,6 +448,8 @@ const BatchesTable = memo(({ data, count }: BatchesTableProps) => {{accessorKey: "memberCount",header: t`Jobs`,+ // The loader counts the members per page: no column to sort on.+ enableSorting: false,cell: ({ row }) => (<span className="tabular-nums">{row.original.memberCount ?? 0}</span>),@@ -400,6 +462,8 @@ const BatchesTable = memo(({ data, count }: BatchesTableProps) => {{accessorKey: "totalQuantity",header: t`Quantity`,+ // The loader sums the members per page: no column to sort on.+ enableSorting: false,cell: ({ row }) => (<span className="tabular-nums">{row.original.totalQuantity ?? 0}@@ -502,6 +566,11 @@ const BatchesTable = memo(({ data, count }: BatchesTableProps) => {data={data}columns={columns}count={count}+ infinite={{+ dataKey: "batches",+ nextCursor,+ listKey: "operation-batches"+ }}primaryAction={permissions.can("create", "production") && (<New label={t`Batch`} to={path.to.newOperationBatch} />diff --git a/apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionTable.tsx b/apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionTable.tsxindex 0f633e5ee5..478ef27699 100644--- a/apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionTable.tsx+++ b/apps/erp/app/modules/production/ui/DemandProjection/DemandProjectionTable.tsx@@ -40,6 +40,8 @@ import type { DemandProjection } from "../../types";type DemandProjectionsTableProps = {data: DemandProjection[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;locationId: string;periods: { id: string; startDate: string; endDate: string }[];};@@ -50,7 +52,13 @@ const defaultColumnPinning = {};const DemandProjectionsTable = memo(- ({ data, count, locationId, periods }: DemandProjectionsTableProps) => {+ ({+ data,+ count,+ nextCursor,+ locationId,+ periods+ }: DemandProjectionsTableProps) => {const numberFormatter = useNumberFormatter();const dateFormatter = useDateFormatter({month: "short",@@ -209,6 +217,8 @@ const DemandProjectionsTable = memo(data={data}columns={columns}count={count}+ // Location-scoped: no list registry entry, so no `listKey`.+ infinite={{ dataKey: "projections", nextCursor }}defaultColumnPinning={defaultColumnPinning}title={t`Demand Forecasts`}table="demand-projection"diff --git a/apps/erp/app/modules/production/ui/Jobs/JobOperationStepRecordsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobOperationStepRecordsTable.tsxindex f4c114f7c2..ec9ccadb85 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobOperationStepRecordsTable.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobOperationStepRecordsTable.tsx@@ -53,10 +53,12 @@ type JobOperationStepRecord = {type JobOperationStepRecordsTableProps = {data: JobOperationStepRecord[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const JobOperationStepRecordsTable = memo(- ({ data, count }: JobOperationStepRecordsTableProps) => {+ ({ data, count, nextCursor }: JobOperationStepRecordsTableProps) => {const { jobId } = useParams();const { t } = useLingui();if (!jobId) throw new Error("Job ID is required");@@ -237,6 +239,8 @@ const JobOperationStepRecordsTable = memo(<Table<JobOperationStepRecord>compactcount={count}+ // Scoped to one job: no list registry entry, so no `listKey`.+ infinite={{ dataKey: "stepRecords", nextCursor }}columns={columns}data={data}title={t`Step Records`}diff --git a/apps/erp/app/modules/production/ui/Jobs/JobOperationsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobOperationsTable.tsxindex 6453ab70b0..db90ea8bb9 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobOperationsTable.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobOperationsTable.tsx@@ -43,9 +43,12 @@ import type { Job, JobOperation } from "../../types";type JobOperationsTableProps = {data: JobOperation[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const JobOperationsTable = memo(({ data, count }: JobOperationsTableProps) => {+const JobOperationsTable = memo((props: JobOperationsTableProps) => {+ const { data, count, nextCursor } = props;const { jobId } = useParams();const { t } = useLingui();if (!jobId) throw new Error("Job ID is required");@@ -235,8 +238,14 @@ const JobOperationsTable = memo(({ data, count }: JobOperationsTableProps) => {}, [onCellEdit]);const pendingItems = usePendingItems();+ // The Table reads a new `data` array as a revalidation and re-reads every+ // loaded page, so the overlay keeps `data` itself while nothing is pending+ // and changes only with the pending statuses.+ const pendingKey = pendingItems+ .map((pendingItem) => `${pendingItem.id}:${pendingItem.status}`)+ .join(",");- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration+ // biome-ignore lint/correctness/useExhaustiveDependencies: pendingKey stands in for pendingItemsconst optimisticData = useMemo<typeof data>(() => {if (pendingItems.length === 0) return data;return data.map((item) => {@@ -251,13 +260,15 @@ const JobOperationsTable = memo(({ data, count }: JobOperationsTableProps) => {}return item;});- }, [pendingItems.length]);+ }, [data, pendingKey]);return (<Table<JobOperation>mobileLayout="table"compactcount={count}+ // Scoped to one job: no list registry entry, so no `listKey`.+ infinite={{ dataKey: "operations", nextCursor }}columns={columns}data={optimisticData}primaryAction={diff --git a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsxindex 32736f493a..915d00a7ed 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx@@ -2,7 +2,6 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useCarbon } from "@carbon/auth";import { useAction } from "@carbon/query";import {Badge,@@ -30,7 +29,7 @@ import {import { plural } from "@lingui/core/macro";import { Trans, useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";-import { memo, useCallback, useEffect, useMemo, useState } from "react";+import { memo, useCallback, useMemo, useState } from "react";import { AiOutlinePartition } from "react-icons/ai";import {LuBookMarked,@@ -62,25 +61,49 @@ import {import { Enumerable } from "~/components/Enumerable";import { useLocations } from "~/components/Form/Location";import { ConfirmDelete } from "~/components/Modals";-import { usePermissions, useUrlParams, useUser } from "~/hooks";+import type { BulkActionScope } from "~/components/Table";+import { usePermissions, useUrlParams } from "~/hooks";+import {+ useAllMatchingLimitLabel,+ useBulkFormAction,+ useBulkStartToast+} from "~/hooks/useBulkAction";import { useCustomColumns } from "~/hooks/useCustomColumns";import type { action as releaseAction } from "~/routes/x+/job+/release";-import type { action } from "~/routes/x+/job+/update";import { useCustomers, useParts, usePeople, useTools } from "~/stores";+import {+ bulkSelectionBody,+ isOverAllMatchingLimit+} from "~/utils/bulk-selection";import { path } from "~/utils/path";-import { deadlineTypes, jobStatus } from "../../production.models";+import { ALL_MATCHING_RELEASE_LIMIT } from "~/utils/table-jobs";+import {+ deadlineTypes,+ isJobBulkDeletable,+ isJobBulkReleasable,+ jobStatus+} from "../../production.models";import type { Job } from "../../types";import { getDeadlineIcon } from "./Deadline";import JobStatus from "./JobStatus";+import { JOB_LIST_EXPORT_VALUES } from "./job-list-export";++// A row of the jobs list, with the values the loader adds per page.+type JobRow = Job & {+ // The readableIds of the live (Active/Completing) operation batches the job+ // has an operation in. Batching is per-operation, so this is the only+ // job-level view of it.+ batchReadableIds: string[];+ // The readableId of the tracked entity the job's make method produces.+ trackedEntityReadableId: string | null;+};type JobsTableProps = {- data: Job[];+ data: JobRow[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;tags: { name: string }[];- // jobId -> readableIds of live (Active/Completing) operation batches the- // job has an operation in. Batching is per-operation, so this is the only- // job-level view of it.- batchesByJobId?: Record<string, string[]>;};const defaultColumnVisibility = {@@ -99,61 +122,6 @@ const defaultColumnVisibility = {quantityReceivedToInventory: false};-function useReadableTrackedEntities(data: Job[], companyId: string) {- const [trackedEntities, setTrackedEntities] = useState<- Record<string, string>- >({});- const { carbon } = useCarbon();-- async function getTrackedEntities(- jobMakeMethodIds: string[],- companyId: string- ) {- if (carbon) {- const response = await carbon- ?.from("trackedEntity")- .select("*")- .in("attributes->>Job Make Method", jobMakeMethodIds)- .eq("companyId", companyId);-- if (response.data) {- const result = response.data.reduce<Record<string, string>>(- (acc, curr) => {- if (- curr.attributes !== null &&- typeof curr.attributes === "object" &&- "Job Make Method" in curr.attributes &&- curr.readableId- ) {- acc[curr.attributes["Job Make Method"] as string] =- curr.readableId;- }- return acc;- },- {}- );-- setTrackedEntities(result);- }- }- }-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- getTrackedEntities(- data.reduce<string[]>((acc, curr) => {- if (curr.jobMakeMethodId) {- acc.push(curr.jobMakeMethodId);- }- return acc;- }, []),- companyId- );- }, [data]);-- return trackedEntities;-}-// A function declaration on purpose: `plural()` nested in `t` inside a// `memo(…)` component compiles to the global i18n, which is never activated// (see .claude/rules/i18n-lingui-system.md).@@ -187,17 +155,13 @@ function renderQuantity(job: Job, unit?: string | null) {}const JobsTable = memo((props: JobsTableProps) => {- const { data, count, tags, batchesByJobId = {} } = props;+ const { data, count, nextCursor, tags } = props;const navigate = useNavigate();const { t } = useLingui();const releasedJobsMessage = useReleasedJobsMessage();const [params] = useUrlParams();const parts = useParts();const tools = useTools();- const {- company: { id: companyId }- } = useUser();-const items = useMemo(() => [...parts, ...tools], [parts, tools]);const [people] = usePeople();@@ -221,7 +185,10 @@ const JobsTable = memo((props: JobsTableProps) => {const deleteModal = useDisclosure();const [selectedJob, setSelectedJob] = useState<Job | null>(null);- const trackedEntities = useReadableTrackedEntities(data, companyId);+ const infinite = useMemo(+ () => ({ dataKey: "jobs", nextCursor, listKey: "jobs" }),+ [nextCursor]+ );const onDelete = (data: Job) => {setSelectedJob(data);@@ -235,10 +202,10 @@ const JobsTable = memo((props: JobsTableProps) => {const todaysDate = useMemo(() => today(getLocalTimeZone()), []);- const customColumns = useCustomColumns<Job>("job");+ const customColumns = useCustomColumns<JobRow>("job");// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- const columns = useMemo<ColumnDef<Job>[]>(() => {- const defaultColumns: ColumnDef<Job>[] = [+ const columns = useMemo<ColumnDef<JobRow>[]>(() => {+ const defaultColumns: ColumnDef<JobRow>[] = [{accessorKey: "jobId",header: t`Job ID`,@@ -290,7 +257,7 @@ const JobsTable = memo((props: JobsTableProps) => {icon: <AiOutlinePartition />}},- exportOnlyColumn<Job>({+ exportOnlyColumn<JobRow>({id: "itemName",header: t`Item Name`,value: (row) => row.name ?? null@@ -299,15 +266,15 @@ const JobsTable = memo((props: JobsTableProps) => {id: "trackedEntityId",header: t`Tracking`,cell: ({ row }) =>- row.original.jobMakeMethodId &&- trackedEntities[row.original.jobMakeMethodId] ? (+ row.original.trackedEntityReadableId ? (<Badge variant="secondary" className="items-center gap-1"><LuQrCode />- {trackedEntities[row.original.jobMakeMethodId]}+ {row.original.trackedEntityReadableId}</Badge>) : null,meta: {- icon: <LuQrCode />+ icon: <LuQrCode />,+ exportValue: JOB_LIST_EXPORT_VALUES.trackedEntityId}},{@@ -351,9 +318,7 @@ const JobsTable = memo((props: JobsTableProps) => {id: "batches",header: t`Batches`,cell: ({ row }) => {- const batches = row.original.id- ? (batchesByJobId[row.original.id] ?? [])- : [];+ const batches = row.original.batchReadableIds ?? [];if (batches.length === 0) return null;return (<HStack spacing={1}>@@ -374,8 +339,7 @@ const JobsTable = memo((props: JobsTableProps) => {meta: {icon: <LuLayers />,filterHeader: t`Batches`,- exportValue: (row: Job) =>- row.id ? (batchesByJobId[row.id] ?? []).join(", ") : null+ exportValue: JOB_LIST_EXPORT_VALUES.batches}},{@@ -556,6 +520,8 @@ const JobsTable = memo((props: JobsTableProps) => {accessorKey: "orderQuantity",header: t`Order Qty`,cell: (item) => item.getValue<number>(),+ // Not a column of the `jobs` view, so the server cannot sort by it.+ enableSorting: false,meta: {icon: <LuHash />,renderTotal: true@@ -565,6 +531,8 @@ const JobsTable = memo((props: JobsTableProps) => {accessorKey: "inventoryQuantity",header: t`Inventory Qty`,cell: (item) => item.getValue<number>(),+ // Not a column of the `jobs` view, so the server cannot sort by it.+ enableSorting: false,meta: {icon: <LuHash />,renderTotal: true@@ -693,39 +661,35 @@ const JobsTable = memo((props: JobsTableProps) => {}];return [...defaultColumns, ...customColumns];- }, [params, customColumns, trackedEntities, batchesByJobId]);+ }, [params, customColumns]);- const fetcher = useAction<typeof action>({- onError: (data) => {- if (data?.error) {- toast.error(data.error.message);- }- }- });- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration+ const { submit: submitBulk } = useBulkFormAction();const onBulkUpdate = useCallback(- (selectedRows: typeof data, field: "delete", value?: string) => {- const formData = new FormData();- selectedRows.forEach((row) => {- if (row.id) formData.append("ids", row.id);- });- formData.append("field", field);- if (value) formData.append("value", value);- fetcher.submit(formData, {- method: "post",- action: path.to.bulkUpdateJob- });+ (+ selectedRows: typeof data,+ field: "delete",+ value?: string,+ scope?: BulkActionScope+ ) => {+ submitBulk(+ path.to.bulkUpdateJob,+ { scope, idsField: "ids", ids: selectedRows.map((row) => row.id) },+ { field, value }+ );},-- []+ [submitBulk]);// Bulk release for the selected rows — Draft and Planned jobs only. Posts the// ids to the release action, which holds each job to the job page's release// checks and releases the ones that pass; we toast the summary.+ const showBulkStart = useBulkStartToast();+ const releaseLimitLabel = useAllMatchingLimitLabel(+ ALL_MATCHING_RELEASE_LIMIT+ );const releaseFetcher = useAction<typeof releaseAction>({onSuccess: (result) => {- if (!result.success) return;+ if (showBulkStart(result) || !("released" in result)) return;if (result.released) {toast.success(releasedJobsMessage(result.released));}@@ -748,14 +712,21 @@ const JobsTable = memo((props: JobsTableProps) => {}},onError: (result) => {- if (!result.success) toast.error(result.message);+ showBulkStart(result);}});const renderActions = useCallback(- (selectedRows: typeof data) => {- const releasable = selectedRows.filter(- (row) => row.status === "Draft" || row.status === "Planned"+ (selectedRows: typeof data, scope?: BulkActionScope) => {+ const releasable = selectedRows.filter((row) =>+ isJobBulkReleasable(row.status)+ );+ // Every matching row: the server picks the jobs each action may act on+ // and skips the rest. Release runs on at most 2,000 of them.+ const allMatching = scope?.allMatching;+ const overReleaseLimit = isOverAllMatchingLimit(+ scope,+ ALL_MATCHING_RELEASE_LIMIT);return (<DropdownMenuContent align="end" className="min-w-[200px]">@@ -767,12 +738,17 @@ const JobsTable = memo((props: JobsTableProps) => {<DropdownMenuItemdisabled={!permissions.can("update", "production") ||- releasable.length === 0 ||+ (!allMatching && releasable.length === 0) ||+ overReleaseLimit ||releaseFetcher.isPending}onClick={() =>releaseFetcher.submit(- { jobIds: releasable.flatMap((row) => row.id ?? []) },+ bulkSelectionBody({+ scope,+ idsField: "jobIds",+ ids: releasable.map((row) => row.id)+ }),{method: "post",action: path.to.bulkReleaseJob,@@ -782,24 +758,25 @@ const JobsTable = memo((props: JobsTableProps) => {}><MenuIcon icon={<LuCirclePlay />} />- <Trans>Release Jobs</Trans>+ <div className="flex flex-col">+ <Trans>Release Jobs</Trans>+ {overReleaseLimit && (+ <span className="text-xs text-muted-foreground">+ {releaseLimitLabel}+ </span>+ )}+ </div></DropdownMenuItem><DropdownMenuItemdisabled={!permissions.can("delete", "production") ||- selectedRows.some(- (row) =>- ![- "Draft",- "Planned",- "Due Today",- "Overdue",- "Draft"- ].includes(row.status ?? "")- )+ (!allMatching &&+ selectedRows.some((row) => !isJobBulkDeletable(row.status)))}destructive- onClick={() => onBulkUpdate(selectedRows, "delete")}+ onClick={() =>+ onBulkUpdate(selectedRows, "delete", undefined, scope)+ }><MenuIcon icon={<LuTrash />} />Delete Jobs@@ -808,11 +785,11 @@ const JobsTable = memo((props: JobsTableProps) => {</DropdownMenuContent>);},- [onBulkUpdate, permissions, releaseFetcher]+ [onBulkUpdate, permissions, releaseFetcher, releaseLimitLabel]);// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- const renderContextMenu = useCallback<(row: Job) => JSX.Element>(+ const renderContextMenu = useCallback<(row: JobRow) => JSX.Element>((row) => (<><MenuItem@@ -841,7 +818,7 @@ const JobsTable = memo((props: JobsTableProps) => {return (<>- <Table<Job>+ <Table<JobRow>data={data}defaultColumnVisibility={defaultColumnVisibility}defaultColumnPinning={{@@ -849,6 +826,7 @@ const JobsTable = memo((props: JobsTableProps) => {}}columns={columns}count={count ?? 0}+ infinite={infinite}primaryAction={permissions.can("update", "resources") && (<New label={t`Job`} to={path.to.newJob} />diff --git a/apps/erp/app/modules/production/ui/Jobs/ProductionEventsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/ProductionEventsTable.tsxindex 84cf3e1e5f..c1f017927e 100644--- a/apps/erp/app/modules/production/ui/Jobs/ProductionEventsTable.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/ProductionEventsTable.tsx@@ -34,12 +34,20 @@ import type { ProductionEvent } from "../../types";type ProductionEventsTableProps = {data: ProductionEvent[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;operations: { id: string; description: string | null }[];workCenters: WorkCenter[];};const ProductionEventsTable = memo(- ({ data, count, operations, workCenters }: ProductionEventsTableProps) => {+ ({+ data,+ count,+ nextCursor,+ operations,+ workCenters+ }: ProductionEventsTableProps) => {const { jobId } = useParams();const { t } = useLingui();if (!jobId) throw new Error("Job ID is required");@@ -270,6 +278,8 @@ const ProductionEventsTable = memo(<Table<ProductionEvent>compactcount={count}+ // Scoped to one job: no list registry entry, so no `listKey`.+ infinite={{ dataKey: "events", nextCursor }}columns={columns}data={data}emptyState={emptyState}diff --git a/apps/erp/app/modules/production/ui/Jobs/ProductionQuantitiesTable.tsx b/apps/erp/app/modules/production/ui/Jobs/ProductionQuantitiesTable.tsxindex 0180e1bbf6..675c20e25b 100644--- a/apps/erp/app/modules/production/ui/Jobs/ProductionQuantitiesTable.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/ProductionQuantitiesTable.tsx@@ -25,6 +25,8 @@ import type { ProductionQuantity, ScrapReason } from "../../types";type ProductionQuantitiesTableProps = {data: ProductionQuantity[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;operations: { id: string; description: string | null }[];scrapReasons: ScrapReason[];};@@ -33,6 +35,7 @@ const ProductionQuantitiesTable = memo(({data,count,+ nextCursor,operations,scrapReasons}: ProductionQuantitiesTableProps) => {@@ -223,6 +226,8 @@ const ProductionQuantitiesTable = memo(<Table<ProductionQuantity>compactcount={count}+ // Scoped to one job: no list registry entry, so no `listKey`.+ infinite={{ dataKey: "events", nextCursor }}columns={columns}data={data}primaryAction={diff --git a/apps/erp/app/modules/production/ui/Jobs/job-list-export.ts b/apps/erp/app/modules/production/ui/Jobs/job-list-export.tsnew file mode 100644index 0000000000..69b5bed0c7--- /dev/null+++ b/apps/erp/app/modules/production/ui/Jobs/job-list-export.ts@@ -0,0 +1,18 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++/**+ * The Jobs table columns whose values the loader adds to each page's rows, by+ * column id. The table exports them with these, and the background CSV export+ * writes the same values (`jobsList.exportRows`).+ */+type Row = {+ batchReadableIds?: string[] | null;+ trackedEntityReadableId?: string | null;+};++export const JOB_LIST_EXPORT_VALUES = {+ batches: (row: Row) => (row.batchReadableIds ?? []).join(", "),+ trackedEntityId: (row: Row) => row.trackedEntityReadableId ?? null+} satisfies Record<string, (row: Row) => string | null>;diff --git a/apps/erp/app/modules/production/ui/Jobs/job-release-logic.ts b/apps/erp/app/modules/production/ui/Jobs/job-release-logic.tsindex 7669b6c71d..d25d08fa0a 100644--- a/apps/erp/app/modules/production/ui/Jobs/job-release-logic.ts+++ b/apps/erp/app/modules/production/ui/Jobs/job-release-logic.ts@@ -116,3 +116,38 @@ export function jobReleaseProblems(job: {)];}++/**+ * The purchase order each supplier's outside operations start on in a bulk+ * release, and the suppliers whose jobs must be refused because the user has+ * to choose among their Draft POs.+ *+ * A background release runs in slices of 25 jobs. A slice reads the supplier's+ * Draft POs after an earlier slice has created one. `carried` (the map the+ * previous slice returned) names that PO, so the supplier keeps it instead of+ * asking for a choice. A carried PO that is no longer a Draft of its supplier+ * is ignored.+ */+export function bulkReleaseStartingPurchaseOrders(+ suppliers: {+ supplierId: string;+ draftPurchaseOrders: { id: string }[];+ }[],+ carried: Record<string, string> = {}+): {+ purchaseOrders: Record<string, string>;+ suppliersToChoose: Set<string>;+} {+ const purchaseOrders: Record<string, string> = {};+ const suppliersToChoose = new Set<string>();+ for (const { supplierId, draftPurchaseOrders } of suppliers) {+ const carriedId = carried[supplierId];+ if (carriedId && draftPurchaseOrders.some((po) => po.id === carriedId)) {+ purchaseOrders[supplierId] = carriedId;+ continue;+ }+ purchaseOrders[supplierId] = "new";+ if (draftPurchaseOrders.length > 0) suppliersToChoose.add(supplierId);+ }+ return { purchaseOrders, suppliersToChoose };+}diff --git a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsxindex 784fc320b6..aac08f760b 100644--- a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx+++ b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx@@ -42,6 +42,7 @@ import {import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { useLocations } from "~/components/Form/Location";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";+import { useInfiniteRows } from "~/components/Table/useInfiniteRows";import {useLinkedDrawerItem,useMrpScheduleDescription,@@ -79,17 +80,22 @@ import { path } from "~/utils/path";import type { ProductionPlanningItem } from "../../types";import { ProductionPlanningOrderDrawer } from "./ProductionPlanningOrderDrawer";+/** A grid row with its persisted MRP worklist (spec §P1.7), rendered as the+ * Actions column + the item's expanded row. Every action is here whatever+ * its date; the row's time fence decides what shows. */+type PlanningRow = ProductionPlanningItem & {+ planningActions: PlanningAction[];+};+type ProductionPlanningTableProps = {- data: ProductionPlanningItem[];+ data: PlanningRow[];/** The row a `?item=` link opens the drawer on when it is not in `data`. */- drawerItem: ProductionPlanningItem | null;+ drawerItem: PlanningRow | null;count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;locationId: string;periods: { id: string; startDate: string; endDate: string }[];- /** The persisted MRP worklist for the rows on this page (spec §P1.7),- * rendered as the Actions column + each item's expanded row. Every action- * is here whatever its date; the row's time fence decides what shows. */- planningActions: PlanningAction[];/** The Actions-column filter in effect; null when the grid is not filtered* by action type. */actionTypes: string[] | null;@@ -101,9 +107,9 @@ const ProductionPlanningTable = ({data,drawerItem,count,+ nextCursor,locationId,periods,- planningActions,actionTypes,locationToday}: ProductionPlanningTableProps) => {@@ -124,11 +130,31 @@ const ProductionPlanningTable = ({});const mrpScheduleDescription = useMrpScheduleDescription();- // What the order drawer can open on: the page's rows, plus the row a link- // names when it is not on this page.+ // Every loaded row, each with its own actions. The grid is location-scoped:+ // no list registry entry, so no `listKey`. The open drawer's param does not+ // change the list.+ const infiniteRows = useInfiniteRows({+ initialRows: data,+ infinite: {+ dataKey: "items",+ nextCursor,+ ignoreParams: [PLANNING_DRAWER_PARAM]+ }+ });+ const loadedRows = infiniteRows.rows;++ // What the order drawer can open on: the loaded rows, plus the row a link+ // names when it is not loaded. A loaded row is never counted twice.const drawerRows = useMemo(- () => (drawerItem ? [...data, drawerItem] : data),- [data, drawerItem]+ () =>+ drawerItem && !loadedRows.some((row) => row.id === drawerItem.id)+ ? [...loadedRows, drawerItem]+ : loadedRows,+ [loadedRows, drawerItem]+ );+ const loadedPlanningActions = useMemo(+ () => drawerRows.flatMap((row) => row.planningActions),+ [drawerRows]);// ── Planning actions (the MRP worklist) ──────────────────────────────────@@ -146,7 +172,7 @@ const ProductionPlanningTable = ({submitActions} = usePlanningActions({data: drawerRows,- planningActions,+ planningActions: loadedPlanningActions,actionTypes,locationId,updatePath: path.to.bulkUpdateProductionPlanning,@@ -292,7 +318,7 @@ const ProductionPlanningTable = ({const ordersByItemId = useMemo(() =>new Map(- data.map((row) => [+ loadedRows.map((row) => [row.id,productionOrdersFromActions(openNewSupplyActions(actionsByItemId.get(row.id), "Make"),@@ -300,12 +326,12 @@ const ProductionPlanningTable = ({)])),- [data, actionsByItemId, locationToday]+ [loadedRows, actionsByItemId, locationToday]);// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onBulkUpdate = useCallback(- (selectedRows: typeof data, action: "order") => {+ (selectedRows: ProductionPlanningItem[], action: "order") => {const payload = {locationId,items: selectedRows@@ -390,7 +416,7 @@ const ProductionPlanningTable = ({key: drawerKey,open: openDrawer,close: closeDrawer- } = useLinkedDrawerItem({+ } = useLinkedDrawerItem<ProductionPlanningItem>({param: PLANNING_DRAWER_PARAM,rows: drawerRows});@@ -660,7 +686,7 @@ const ProductionPlanningTable = ({]);const renderActions = useCallback(- (selectedRows: typeof data) => {+ (selectedRows: ProductionPlanningItem[]) => {// inside each row's time fence only — what the row is showingconst applyableIds = selectedRows.flatMap((row) =>(visibleActionsByItemId.get(row.id) ?? [])@@ -748,6 +774,7 @@ const ProductionPlanningTable = ({count={count}columns={columns}data={data}+ infiniteRows={infiniteRows}defaultColumnVisibility={defaultColumnVisibility}defaultColumnPinning={defaultColumnPinning}primaryAction={diff --git a/apps/erp/app/modules/production/ui/Planning/planning-action-scope.ts b/apps/erp/app/modules/production/ui/Planning/planning-action-scope.tsindex 04f453dc88..71f5141d85 100644--- a/apps/erp/app/modules/production/ui/Planning/planning-action-scope.ts+++ b/apps/erp/app/modules/production/ui/Planning/planning-action-scope.ts@@ -75,3 +75,24 @@ export function actionsOfTypes<if (!types || types.length === 0) return [...actions];return actions.filter((action) => types.includes(action.type));}++/**+ * Each row with its own planning actions (by `itemId`). A grid page carries+ * the actions of its rows, so the grid reads every loaded row's actions from+ * the rows themselves, with no merge of later pages.+ */+export function withPlanningActions<+ R extends { id: string },+ A extends { itemId: string }+>(rows: readonly R[], actions: readonly A[]): (R & { planningActions: A[] })[] {+ const byItemId = new Map<string, A[]>();+ for (const action of actions) {+ const list = byItemId.get(action.itemId);+ if (list) list.push(action);+ else byItemId.set(action.itemId, [action]);+ }+ return rows.map((row) => ({+ ...row,+ planningActions: byItemId.get(row.id) ?? []+ }));+}diff --git a/apps/erp/app/modules/production/ui/Planning/useJobPlanningRelease.ts b/apps/erp/app/modules/production/ui/Planning/useJobPlanningRelease.tsindex ed3fbaa09c..4cd8a55572 100644--- a/apps/erp/app/modules/production/ui/Planning/useJobPlanningRelease.ts+++ b/apps/erp/app/modules/production/ui/Planning/useJobPlanningRelease.ts@@ -25,7 +25,8 @@ export function useJobPlanningRelease(): {const { t } = useLingui();const releaseFetcher = useAction<typeof releaseAction>({onSuccess: (result) => {- if (!result.success) return;+ // This hook posts job ids, so the route never answers `background`.+ if (!result.success || "background" in result) return;if (result.released) toast.success(t`Job released`);for (const warning of result.warnings) {toast.error(diff --git a/apps/erp/app/modules/production/ui/Procedures/ProceduresTable.tsx b/apps/erp/app/modules/production/ui/Procedures/ProceduresTable.tsxindex 3a5d8922f2..874a63093e 100644--- a/apps/erp/app/modules/production/ui/Procedures/ProceduresTable.tsx+++ b/apps/erp/app/modules/production/ui/Procedures/ProceduresTable.tsx@@ -42,9 +42,12 @@ type ProceduresTableProps = {data: Procedures[];tags: { name: string }[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const ProceduresTable = memo(({ data, tags, count }: ProceduresTableProps) => {+const ProceduresTable = memo((props: ProceduresTableProps) => {+ const { data, tags, count, nextCursor } = props;const navigate = useNavigate();const { t } = useLingui();const permissions = usePermissions();@@ -231,6 +234,11 @@ const ProceduresTable = memo(({ data, tags, count }: ProceduresTableProps) => {data={data}columns={columns}count={count}+ infinite={{+ dataKey: "procedures",+ nextCursor,+ listKey: "procedures"+ }}primaryAction={permissions.can("create", "production") && (<New label={t`Procedure`} to={path.to.newProcedure} />diff --git a/apps/erp/app/modules/production/ui/ScrapReasons/ScrapReasonsTable.tsx b/apps/erp/app/modules/production/ui/ScrapReasons/ScrapReasonsTable.tsxindex 07cc63297f..dd6a154569 100644--- a/apps/erp/app/modules/production/ui/ScrapReasons/ScrapReasonsTable.tsx+++ b/apps/erp/app/modules/production/ui/ScrapReasons/ScrapReasonsTable.tsx@@ -18,9 +18,12 @@ import type { ScrapReason } from "../../types";type ScrapReasonsTableProps = {data: ScrapReason[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const ScrapReasonsTable = memo(({ data, count }: ScrapReasonsTableProps) => {+const ScrapReasonsTable = memo((props: ScrapReasonsTableProps) => {+ const { data, count, nextCursor } = props;const [params] = useUrlParams();const { t } = useLingui();const navigate = useNavigate();@@ -83,6 +86,11 @@ const ScrapReasonsTable = memo(({ data, count }: ScrapReasonsTableProps) => {data={data}columns={columns}count={count}+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "scrap-reasons"+ }}importCSV={[{table: "scrapReason" as const,diff --git a/apps/erp/app/modules/purchasing/purchasing.models.test.ts b/apps/erp/app/modules/purchasing/purchasing.models.test.tsindex 4d5bf32e42..6c3345a657 100644--- a/apps/erp/app/modules/purchasing/purchasing.models.test.ts+++ b/apps/erp/app/modules/purchasing/purchasing.models.test.ts@@ -22,6 +22,7 @@ vi.mock("@carbon/content/glossary", () => ({import * as purchasingModels from "./purchasing.models";import {canCreatePurchaseOrderRevision,+ isPurchaseOrderBulkDeletable,isPurchaseOrderLocked,leaseClassificationValidator,leaseDetailsValidator,@@ -551,3 +552,15 @@ describe("lease action validators", () => {).toBe(false);});});++describe("isPurchaseOrderBulkDeletable", () => {+ it("accepts Draft and Planned only", () => {+ expect(isPurchaseOrderBulkDeletable("Draft")).toBe(true);+ expect(isPurchaseOrderBulkDeletable("Planned")).toBe(true);+ for (const status of purchaseOrderStatusType) {+ if (status === "Draft" || status === "Planned") continue;+ expect(isPurchaseOrderBulkDeletable(status)).toBe(false);+ }+ expect(isPurchaseOrderBulkDeletable(null)).toBe(false);+ });+});diff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.tsindex a7c1e8b17b..d6cb9e4f38 100644--- a/apps/erp/app/modules/purchasing/purchasing.models.ts+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts@@ -749,6 +749,13 @@ export function isPurchaseOrderLocked();}+/** The statuses the purchase orders table's bulk Delete acts on. */+export function isPurchaseOrderBulkDeletable(+ status: string | null | undefined+): boolean {+ return status === "Draft" || status === "Planned";+}+/*** The PO statuses planning may change: Apply on a planning action, the order* drawer's inline edits, and Cancel's line delete. An allowlist on purpose —diff --git a/apps/erp/app/modules/purchasing/purchasing.server.ts b/apps/erp/app/modules/purchasing/purchasing.server.tsindex 586d87b068..45bdd0b928 100644--- a/apps/erp/app/modules/purchasing/purchasing.server.ts+++ b/apps/erp/app/modules/purchasing/purchasing.server.ts@@ -4,7 +4,12 @@import { hasPermission } from "@carbon/auth";import { getUserClaims } from "@carbon/auth/users.server";-import { type Database, getCompanyTimeZone, type Json } from "@carbon/database";+import {+ Constants,+ type Database,+ getCompanyTimeZone,+ type Json+} from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";import { serverFns } from "@carbon/server-functions";import {@@ -15,8 +20,13 @@ import { datetime, openEndedLeaseHorizon } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { sql, type Transaction } from "kysely";import type { z } from "zod";+import {+ type BulkDeleteResult,+ bulkDeleteByStatus+} from "~/utils/bulk-delete.server";import { path } from "~/utils/path";import {+ isPurchaseOrderBulkDeletable,leaseLineColumns,leaseLinePaymentFields,type leaseLineValidator,@@ -541,3 +551,37 @@ export async function draftLeaseSetupPath(}return path.to.leaseSetup(id, "assets");}++export type BulkDeletePurchaseOrdersResult = BulkDeleteResult;++/** The statuses the bulk Delete deletes, from the table's own rule. */+const BULK_DELETABLE_PURCHASE_ORDER_STATUSES =+ Constants.public.Enums.purchaseOrderStatus.filter(+ isPurchaseOrderBulkDeletable+ );++/**+ * The purchase orders table's bulk Delete: deletes the Draft and Planned+ * orders of the company, 100 ids per request. The status filter is part of+ * the DELETE, so an order that moved on since it was selected stays. Called+ * by `x+/purchase-order+/update.tsx` and by the background bulk-action job.+ * The caller checks the `delete: purchasing` permission.+ */+export function bulkDeletePurchaseOrders(+ client: SupabaseClient<Database>,+ args: { purchaseOrderIds: string[]; companyId: string }+): Promise<BulkDeletePurchaseOrdersResult> {+ return bulkDeleteByStatus({+ ids: args.purchaseOrderIds,+ companyId: args.companyId,+ label: "purchase orders",+ deleteChunk: (ids) =>+ client+ .from("purchaseOrder")+ .delete()+ .in("id", ids)+ .eq("companyId", args.companyId)+ .in("status", BULK_DELETABLE_PURCHASE_ORDER_STATUSES)+ .select("id")+ });+}diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex 0d75a74344..35db151db0 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -36,7 +36,7 @@ import { sql } from "kysely";import type { z } from "zod";import { createDocumentUploadUrl } from "~/modules/documents/documents.service";import { getEmployeeJob } from "~/modules/people";-import type { GenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";import {@@ -487,6 +487,10 @@ export async function finalizePurchasingRfq(.invoke("finalize-purchasing-rfq", input);}+export const PURCHASE_ORDERS_PAGING: Paging = {+ defaultSorts: [{ column: "purchaseOrderId", ascending: false }]+};+/** @mcp read */export async function getPurchaseOrders(client: SupabaseClient<Database>,@@ -499,7 +503,10 @@ export async function getPurchaseOrders() {let query = client.from("purchaseOrders")- .select(PURCHASE_ORDERS_LIST_COLUMNS, { count: LIST_COUNT })+ // Later pages (`cursor`) skip the count: the first page already has it.+ .select(PURCHASE_ORDERS_LIST_COLUMNS, {+ count: args.cursor ? undefined : LIST_COUNT+ }).eq("companyId", companyId);if (args.search) {@@ -512,9 +519,7 @@ export async function getPurchaseOrders(query = query.eq("supplierId", args.supplierId);}- query = setGenericQueryFilters(query, args, [- { column: "purchaseOrderId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, PURCHASE_ORDERS_PAGING);return query;}@@ -634,6 +639,16 @@ export async function getPurchasingDocumentsAssignedToMe(return merged;}+// What the row's Order / Make button offers (the grid RPC's orderQuantity,+// from MRP's open new-supply actions), then the part number so a page is+// stable when many rows have nothing to order.+export const PURCHASING_PLANNING_PAGING: Paging = {+ defaultSorts: [+ { column: "orderQuantity", ascending: false },+ { column: "readableIdWithRevision", ascending: true }+ ]+};+/** @mcp read */export async function getPurchasingPlanning(client: SupabaseClient<Database>,@@ -669,7 +684,8 @@ export async function getPurchasingPlanning(action_assignees: args.actionAssignees},{- count: LIST_COUNT+ // Later pages (`cursor`) skip the count: the first page already has it.+ count: args.cursor ? undefined : LIST_COUNT});@@ -679,13 +695,7 @@ export async function getPurchasingPlanning();}- // What the row's Order / Make button offers (the grid RPC's orderQuantity,- // from MRP's open new-supply actions), then the part number so a page is- // stable when many rows have nothing to order.- query = setGenericQueryFilters(query, args, [- { column: "orderQuantity", ascending: false },- { column: "readableIdWithRevision", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, PURCHASING_PLANNING_PAGING);return query;}@@ -971,6 +981,10 @@ export async function getSupplierQuoteByExternalLinkId(.single();}+export const SUPPLIER_QUOTES_PAGING: Paging = {+ defaultSorts: [{ column: "supplierQuoteId", ascending: false }]+};+/** @mcp read */export async function getSupplierQuotes(client: SupabaseClient<Database>,@@ -981,7 +995,7 @@ export async function getSupplierQuotes() {let query = client.from("supplierQuotes")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {@@ -990,9 +1004,7 @@ export async function getSupplierQuotes();}- query = setGenericQueryFilters(query, args, [- { column: "supplierQuoteId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, SUPPLIER_QUOTES_PAGING);return query;}@@ -1110,6 +1122,10 @@ export async function getSupplierReportContacts(]);}+export const SUPPLIERS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getSuppliers(client: SupabaseClient<Database>,@@ -1123,7 +1139,7 @@ export async function getSuppliers(let query = client.from("suppliers").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -1142,9 +1158,7 @@ export async function getSuppliers();}- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, SUPPLIERS_PAGING);return query;}@@ -1173,6 +1187,10 @@ export async function getSupplierType(.single();}+export const SUPPLIER_TYPES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getSupplierTypes(client: SupabaseClient<Database>,@@ -1181,7 +1199,7 @@ export async function getSupplierTypes() {let query = client.from("supplierType")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -1189,9 +1207,7 @@ export async function getSupplierTypes(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, SUPPLIER_TYPES_PAGING);}return query;@@ -3144,6 +3160,10 @@ export async function getPurchasingRFQ(return client.from("purchasingRfqs").select("*").eq("id", id).single();}+export const PURCHASING_RFQS_PAGING: Paging = {+ defaultSorts: [{ column: "rfqId", ascending: false }]+};+/** @mcp read */export async function getPurchasingRFQs(client: SupabaseClient<Database>,@@ -3154,16 +3174,14 @@ export async function getPurchasingRFQs() {let query = client.from("purchasingRfqs")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {query = query.ilike("rfqId", `%${args.search}%`);}- query = setGenericQueryFilters(query, args, [- { column: "rfqId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, PURCHASING_RFQS_PAGING);return query;}@@ -3847,6 +3865,10 @@ export async function updatePurchaseOrderLineSchedule(// ─── Purchase Return Orders (Supplier Returns) ───+export const PURCHASE_RETURN_ORDERS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getPurchaseReturnOrders(client: SupabaseClient<Database>,@@ -3859,7 +3881,7 @@ export async function getPurchaseReturnOrders() {let query = client.from("purchaseReturnOrders")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {@@ -3879,9 +3901,7 @@ export async function getPurchaseReturnOrders(query = query.eq("supplierId", args.supplierId);}- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, PURCHASE_RETURN_ORDERS_PAGING);return query;}@@ -5280,6 +5300,10 @@ function leaseRefusal(code: string, message: string) {};}+export const LEASES_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getLeases(client: SupabaseClient<Database>,@@ -5288,7 +5312,7 @@ export async function getLeases() {let query = client.from("leases")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {@@ -5297,9 +5321,7 @@ export async function getLeases();}- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, LEASES_PAGING);return query;}diff --git a/apps/erp/app/modules/purchasing/types.ts b/apps/erp/app/modules/purchasing/types.tsindex 961801a18b..1db5a8906d 100644--- a/apps/erp/app/modules/purchasing/types.ts+++ b/apps/erp/app/modules/purchasing/types.ts@@ -96,8 +96,8 @@ export type SupplierContact = NonNullable<>[number];// Element types of each of the 3 parallel queries in getSupplierReportContacts,-// keyed by supplier id / supplierId. Used to type the per-supplier report-contact-// map built in the suppliers.tsx loader and consumed by SuppliersTable's CSV+// keyed by supplier id / supplierId. Used to type the report contacts the+// suppliers.tsx loader adds to each row, read by SuppliersTable's CSV// export-only columns.type SupplierReportContactsResult = Awaited<ReturnType<typeof getSupplierReportContacts>@@ -112,14 +112,11 @@ export type SupplierShippingContact = NonNullable<SupplierReportContactsResult[2]["data"]>[number];-export type SupplierReportContactsBySupplierId = Record<- string,- {- purchasingContact: SupplierPurchasingContact | null;- payment: SupplierPaymentContact | null;- shipping: SupplierShippingContact | null;- }->;+export type SupplierReportContacts = {+ purchasingContact: SupplierPurchasingContact | null;+ payment: SupplierPaymentContact | null;+ shipping: SupplierShippingContact | null;+};export type SupplierInteraction = NonNullable<Awaited<ReturnType<typeof getSupplierInteraction>>["data"]diff --git a/apps/erp/app/modules/purchasing/ui/Leases/LeasesTable.tsx b/apps/erp/app/modules/purchasing/ui/Leases/LeasesTable.tsxindex 35e62609c1..24b25f1809 100644--- a/apps/erp/app/modules/purchasing/ui/Leases/LeasesTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/Leases/LeasesTable.tsx@@ -36,9 +36,11 @@ import type { Lease } from "./types";type LeasesTableProps = {data: Lease[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const LeasesTable = memo(({ data, count }: LeasesTableProps) => {+const LeasesTable = memo(({ data, count, nextCursor }: LeasesTableProps) => {const { t } = useLingui();const permissions = usePermissions();const navigate = useNavigate();@@ -245,6 +247,11 @@ const LeasesTable = memo(({ data, count }: LeasesTableProps) => {count={count}columns={columns}data={data}+ infinite={{+ dataKey: "leases",+ nextCursor,+ listKey: "leases"+ }}defaultColumnPinning={{left: ["leaseId"]}}diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsxindex 9269f1aad9..10cbb12dc6 100644--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx@@ -46,6 +46,7 @@ import {import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";import { useLocations } from "~/components/Form/Location";import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";+import { useInfiniteRows } from "~/components/Table/useInfiniteRows";import {useLinkedDrawerItem,useMrpScheduleDescription,@@ -87,17 +88,22 @@ import type { PurchasingPlanningItem } from "../../types";import { PurchasingPlanningOrderDrawer } from "./PurchasingPlanningOrderDrawer";import { usePurchaseOrderPlanningCommands } from "./usePurchaseOrderPlanningCommands";+/** A grid row with its persisted MRP worklist (spec §P1.7), rendered as the+ * Actions column + the item's expanded row. Every action is here whatever+ * its date; the row's time fence decides what shows. */+type PlanningRow = PurchasingPlanningItem & {+ planningActions: PlanningAction[];+};+type PlanningTableProps = {- data: PurchasingPlanningItem[];+ data: PlanningRow[];/** The row a `?item=` link opens the drawer on when it is not in `data`. */- drawerItem: PurchasingPlanningItem | null;+ drawerItem: PlanningRow | null;count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;locationId: string;periods: { id: string; startDate: string; endDate: string }[];- /** The persisted MRP worklist for the rows on this page (spec §P1.7),- * rendered as the Actions column + each item's expanded row. Every action- * is here whatever its date; the row's time fence decides what shows. */- planningActions: PlanningAction[];/** The Actions-column filter in effect; null when the grid is not filtered* by action type. */actionTypes: string[] | null;@@ -110,9 +116,9 @@ const PlanningTable = memo(data,drawerItem,count,+ nextCursor,locationId,periods,- planningActions,actionTypes,locationToday}: PlanningTableProps) => {@@ -135,11 +141,30 @@ const PlanningTable = memo(const mrpScheduleDescription = useMrpScheduleDescription();const bulkUpdateFetcher = useFetcher<typeof bulkUpdateAction>();- // What the order drawer can open on: the page's rows, plus the row a link- // names when it is not on this page.+ // Every loaded row, each with its own actions. The open drawer's param+ // does not change the list.+ const infiniteRows = useInfiniteRows({+ initialRows: data,+ infinite: {+ dataKey: "items",+ nextCursor,+ ignoreParams: [PLANNING_DRAWER_PARAM]+ }+ });+ const { rows } = infiniteRows;++ // What the order drawer can open on: the loaded rows, plus the row a link+ // names when it is not loaded. A loaded row is never counted twice.const drawerRows = useMemo(- () => (drawerItem ? [...data, drawerItem] : data),- [data, drawerItem]+ () =>+ drawerItem && !rows.some((row) => row.id === drawerItem.id)+ ? [...rows, drawerItem]+ : rows,+ [rows, drawerItem]+ );+ const planningActions = useMemo(+ () => drawerRows.flatMap((row) => row.planningActions),+ [drawerRows]);// ── Planning actions (the MRP worklist) ──────────────────────────────────@@ -315,8 +340,8 @@ const PlanningTable = memo();const ordersByItemId = useMemo(- () => new Map(data.map((row) => [row.id, plannedOrdersFor(row)])),- [data, plannedOrdersFor]+ () => new Map(rows.map((row) => [row.id, plannedOrdersFor(row)])),+ [rows, plannedOrdersFor]);// Store orders in a map keyed by item id - calculate on-demand instead of eagerly@@ -344,7 +369,7 @@ const PlanningTable = memo(// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onBulkUpdate = useCallback(- (selectedRows: typeof data, action: "order") => {+ (selectedRows: PurchasingPlanningItem[], action: "order") => {// Filter out rows without suppliers and track them for error reportingconst rowsWithoutSuppliers = selectedRows.filter((row) => row.id && !suppliersMap[row.id]@@ -463,7 +488,7 @@ const PlanningTable = memo(key: drawerKey,open: openDrawer,close: closeDrawer- } = useLinkedDrawerItem({+ } = useLinkedDrawerItem<PurchasingPlanningItem>({param: PLANNING_DRAWER_PARAM,rows: drawerRows});@@ -768,7 +793,7 @@ const PlanningTable = memo(]);const renderActions = useCallback(- (selectedRows: typeof data) => {+ (selectedRows: PurchasingPlanningItem[]) => {// inside each row's time fence only — what the row is showingconst applyableIds = selectedRows.flatMap((row) =>(visibleActionsByItemId.get(row.id) ?? [])@@ -857,6 +882,7 @@ const PlanningTable = memo(count={count}columns={columns}data={data}+ infiniteRows={infiniteRows}defaultColumnVisibility={defaultColumnVisibility}defaultColumnPinning={defaultColumnPinning}primaryAction={diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsxindex b0b15ff40a..5ee453973a 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx@@ -2,7 +2,6 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useAction } from "@carbon/query";import {BarProgress,Checkbox,@@ -15,7 +14,6 @@ import {MENU_ITEM_SHORTCUTS,MenuIcon,MenuItem,- toast,useDisclosure} from "@carbon/react";import { getLocalTimeZone, today } from "@internationalized/date";@@ -52,11 +50,15 @@ import { Enumerable } from "~/components/Enumerable";import { usePaymentTerm } from "~/components/Form/PaymentTerm";import { useShippingMethod } from "~/components/Form/ShippingMethod";import { ConfirmDelete } from "~/components/Modals";+import type { BulkActionScope } from "~/components/Table";import { useCurrencyFormatter, usePermissions, useRealtime } from "~/hooks";+import { useBulkFormAction } from "~/hooks/useBulkAction";import { useCustomColumns } from "~/hooks/useCustomColumns";import type { PurchaseOrderListItem } from "~/modules/purchasing";-import { purchaseOrderStatusType } from "~/modules/purchasing";-import type { action } from "~/routes/x+/purchase-order+/update";+import {+ isPurchaseOrderBulkDeletable,+ purchaseOrderStatusType+} from "~/modules/purchasing";import { usePeople, useSuppliers } from "~/stores";import { path } from "~/utils/path";import PurchasingStatus from "./PurchasingStatus";@@ -65,10 +67,12 @@ import { usePurchaseOrder } from "./usePurchaseOrder";type PurchaseOrdersTableProps = {data: PurchaseOrderListItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const PurchaseOrdersTable = memo(- ({ data, count }: PurchaseOrdersTableProps) => {+ ({ data, count, nextCursor }: PurchaseOrdersTableProps) => {useRealtime("purchaseOrder");const { t } = useLingui();@@ -408,33 +412,25 @@ const PurchaseOrdersTable = memo(t]);- const fetcher = useAction<typeof action>({- onError: (data) => {- if (data?.error) {- toast.error(data.error.message);- }- }- });- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration+ const { submit: submitBulk, fetcher } = useBulkFormAction();const onBulkUpdate = useCallback(- (selectedRows: typeof data, field: "delete", value?: string) => {- const formData = new FormData();- selectedRows.forEach((row) => {- if (row.id) formData.append("ids", row.id);- });- formData.append("field", field);- if (value) formData.append("value", value);- fetcher.submit(formData, {- method: "post",- action: path.to.bulkUpdatePurchaseOrder- });+ (+ selectedRows: typeof data,+ field: "delete",+ value?: string,+ scope?: BulkActionScope+ ) => {+ submitBulk(+ path.to.bulkUpdatePurchaseOrder,+ { scope, idsField: "ids", ids: selectedRows.map((row) => row.id) },+ { field, value }+ );},-- []+ [submitBulk]);const renderActions = useCallback(- (selectedRows: typeof data) => {+ (selectedRows: typeof data, scope?: BulkActionScope) => {return (<DropdownMenuContent align="end" className="min-w-[200px]"><DropdownMenuLabel>Update</DropdownMenuLabel>@@ -443,12 +439,17 @@ const PurchaseOrdersTable = memo(<DropdownMenuItemdisabled={!permissions.can("delete", "purchasing") ||- selectedRows.some(- (row) => !["Draft", "Planned"].includes(row.status ?? "")- )+ // Every matching row: the server deletes the Draft and+ // Planned orders and skips the rest.+ (!scope?.allMatching &&+ selectedRows.some(+ (row) => !isPurchaseOrderBulkDeletable(row.status)+ ))}destructive- onClick={() => onBulkUpdate(selectedRows, "delete")}+ onClick={() =>+ onBulkUpdate(selectedRows, "delete", undefined, scope)+ }><MenuIcon icon={<LuTrash />} /><Trans>Delete Purchase Orders</Trans>@@ -526,6 +527,11 @@ const PurchaseOrdersTable = memo(count={count}columns={columns}data={data}+ infinite={{+ dataKey: "purchasOrders",+ nextCursor,+ listKey: "purchase-orders"+ }}defaultColumnPinning={{left: ["purchaseOrderId"]}}diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/PurchaseReturnOrdersTable.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/PurchaseReturnOrdersTable.tsxindex be90b145ef..58762f920b 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/PurchaseReturnOrdersTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/PurchaseReturnOrdersTable.tsx@@ -42,10 +42,12 @@ import type { PurchaseReturnOrderListItem } from "./types";type PurchaseReturnOrdersTableProps = {data: PurchaseReturnOrderListItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const PurchaseReturnOrdersTable = memo(- ({ data, count }: PurchaseReturnOrdersTableProps) => {+ ({ data, count, nextCursor }: PurchaseReturnOrdersTableProps) => {const { t } = useLingui();const permissions = usePermissions();const navigate = useNavigate();@@ -232,6 +234,11 @@ const PurchaseReturnOrdersTable = memo(count={count}columns={columns}data={data}+ infinite={{+ dataKey: "purchaseReturnOrders",+ nextCursor,+ listKey: "purchase-return-orders"+ }}defaultColumnPinning={{left: ["purchaseReturnOrderId"]}}diff --git a/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQsTable.tsx b/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQsTable.tsxindex d32bd8aa5f..17cbb47831 100644--- a/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQsTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQsTable.tsx@@ -37,10 +37,12 @@ import { PurchasingRFQStatus } from ".";type PurchasingRFQsTableProps = {data: PurchasingRFQ[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const PurchasingRFQsTable = memo(- ({ data, count }: PurchasingRFQsTableProps) => {+ ({ data, count, nextCursor }: PurchasingRFQsTableProps) => {const { t } = useLingui();const permissions = usePermissions();const navigate = useNavigate();@@ -280,6 +282,11 @@ const PurchasingRFQsTable = memo(count={count}columns={columns}data={data}+ infinite={{+ dataKey: "rfqs",+ nextCursor,+ listKey: "purchasing-rfqs"+ }}defaultColumnPinning={{left: ["rfqId"]}}diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SuppliersTable.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SuppliersTable.tsxindex 5a4cec86c9..0433a61237 100644--- a/apps/erp/app/modules/purchasing/ui/Supplier/SuppliersTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SuppliersTable.tsx@@ -11,7 +11,6 @@ import {MenuItem,useDisclosure} from "@carbon/react";-import { formatAddress } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";import { memo, useMemo, useState } from "react";@@ -46,27 +45,29 @@ import { useSupplierTypes } from "~/components/Form/SupplierType";import { ConfirmDelete } from "~/components/Modals";import { useCompanySettings, usePermissions } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";-import type {- Supplier,- SupplierReportContactsBySupplierId-} from "~/modules/purchasing";+import type { Supplier, SupplierReportContacts } from "~/modules/purchasing";import { supplierStatusType } from "~/modules/purchasing";import { SupplierStatusIndicator } from "~/modules/purchasing/ui/Supplier/SupplierStatusIndicator";import { usePeople } from "~/stores";import { path } from "~/utils/path";+import { SUPPLIER_CONTACT_VALUES } from "./supplier-list-export";++// A row of the suppliers list, with the contacts the loader adds per page.+type SupplierRow = Supplier & { reportContacts: SupplierReportContacts };type SuppliersTableProps = {- data: Supplier[];+ data: SupplierRow[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;tags: { name: string }[];- supplierReportContacts: SupplierReportContactsBySupplierId;};const SuppliersTable = memo(function SuppliersTable({data,count,- tags,- supplierReportContacts+ nextCursor,+ tags}: SuppliersTableProps) {const { t } = useLingui();const navigate = useNavigate();@@ -81,36 +82,14 @@ const SuppliersTable = memo(function SuppliersTable({const showSupplierReadableId =companySettings?.showSupplierReadableId ?? false;- const customColumns = useCustomColumns<Supplier>("supplier");- const columns = useMemo<ColumnDef<Supplier>[]>(() => {- const getPurchasingContact = (row: Supplier) =>- supplierReportContacts[row.id!]?.purchasingContact?.contact ?? null;- const getInvoiceContact = (row: Supplier) =>- supplierReportContacts[row.id!]?.payment?.invoiceContact?.contact ?? null;- const getShippingContact = (row: Supplier) =>- supplierReportContacts[row.id!]?.shipping?.shippingContact?.contact ??- null;- const getInvoiceAddress = (row: Supplier) =>- supplierReportContacts[row.id!]?.payment?.invoiceLocation?.address ??- null;- const getShippingAddress = (row: Supplier) =>- supplierReportContacts[row.id!]?.shipping?.shippingLocation?.address ??- null;- const formatSupplierAddress = (- address: ReturnType<typeof getInvoiceAddress>- ) =>- address- ? formatAddress(- address.addressLine1,- address.addressLine2,- address.city,- address.stateProvince,- address.postalCode,- address.country?.name- )- : null;+ const infinite = useMemo(+ () => ({ dataKey: "suppliers", nextCursor, listKey: "suppliers" }),+ [nextCursor]+ );- const idColumn: ColumnDef<Supplier> = {+ const customColumns = useCustomColumns<SupplierRow>("supplier");+ const columns = useMemo<ColumnDef<SupplierRow>[]>(() => {+ const idColumn: ColumnDef<SupplierRow> = {accessorKey: "readableId",header: t`ID`,cell: ({ row }) => (@@ -122,7 +101,7 @@ const SuppliersTable = memo(function SuppliersTable({icon: <LuHash />}};- const defaultColumns: ColumnDef<Supplier>[] = [+ const defaultColumns: ColumnDef<SupplierRow>[] = [...(showSupplierReadableId ? [idColumn] : []),{accessorKey: "name",@@ -306,119 +285,120 @@ const SuppliersTable = memo(function SuppliersTable({{id: "purchasingContactName",header: t`Purchasing Contact Name`,- cell: ({ row }) => getPurchasingContact(row.original)?.fullName ?? "",+ cell: ({ row }) =>+ SUPPLIER_CONTACT_VALUES.purchasingContactName(row.original) ?? "",meta: {icon: <LuUser />,- exportValue: (row) => getPurchasingContact(row)?.fullName ?? null+ exportValue: SUPPLIER_CONTACT_VALUES.purchasingContactName}},{id: "purchasingContactEmail",header: t`Purchasing Contact Email`,- cell: ({ row }) => getPurchasingContact(row.original)?.email ?? "",+ cell: ({ row }) =>+ SUPPLIER_CONTACT_VALUES.purchasingContactEmail(row.original) ?? "",meta: {icon: <LuMail />,- exportValue: (row) => getPurchasingContact(row)?.email ?? null+ exportValue: SUPPLIER_CONTACT_VALUES.purchasingContactEmail}},{id: "purchasingContactPhone",header: t`Purchasing Contact Phone`,- cell: ({ row }) => getPurchasingContact(row.original)?.workPhone ?? "",+ cell: ({ row }) =>+ SUPPLIER_CONTACT_VALUES.purchasingContactPhone(row.original) ?? "",meta: {icon: <LuPhone />,- exportValue: (row) => getPurchasingContact(row)?.workPhone ?? null+ exportValue: SUPPLIER_CONTACT_VALUES.purchasingContactPhone}},{id: "invoiceAddress",header: t`Invoice Address`,cell: ({ row }) =>- formatSupplierAddress(getInvoiceAddress(row.original)) ?? "",+ SUPPLIER_CONTACT_VALUES.invoiceAddress(row.original) ?? "",meta: {icon: <LuMapPin />,- exportValue: (row) => formatSupplierAddress(getInvoiceAddress(row))+ exportValue: SUPPLIER_CONTACT_VALUES.invoiceAddress}},{id: "invoiceContactName",header: t`Invoice Contact Name`,- cell: ({ row }) => getInvoiceContact(row.original)?.fullName ?? "",+ cell: ({ row }) =>+ SUPPLIER_CONTACT_VALUES.invoiceContactName(row.original) ?? "",meta: {icon: <LuUser />,- exportValue: (row) => getInvoiceContact(row)?.fullName ?? null+ exportValue: SUPPLIER_CONTACT_VALUES.invoiceContactName}},{id: "invoiceContactEmail",header: t`Invoice Contact Email`,- cell: ({ row }) => getInvoiceContact(row.original)?.email ?? "",+ cell: ({ row }) =>+ SUPPLIER_CONTACT_VALUES.invoiceContactEmail(row.original) ?? "",meta: {icon: <LuMail />,- exportValue: (row) => getInvoiceContact(row)?.email ?? null+ exportValue: SUPPLIER_CONTACT_VALUES.invoiceContactEmail}},{id: "invoiceContactPhone",header: t`Invoice Contact Phone`,- cell: ({ row }) => getInvoiceContact(row.original)?.workPhone ?? "",+ cell: ({ row }) =>+ SUPPLIER_CONTACT_VALUES.invoiceContactPhone(row.original) ?? "",meta: {icon: <LuPhone />,- exportValue: (row) => getInvoiceContact(row)?.workPhone ?? null+ exportValue: SUPPLIER_CONTACT_VALUES.invoiceContactPhone}},{id: "shippingAddress",header: t`Shipping Address`,cell: ({ row }) =>- formatSupplierAddress(getShippingAddress(row.original)) ?? "",+ SUPPLIER_CONTACT_VALUES.shippingAddress(row.original) ?? "",meta: {icon: <LuMapPin />,- exportValue: (row) => formatSupplierAddress(getShippingAddress(row))+ exportValue: SUPPLIER_CONTACT_VALUES.shippingAddress}},{id: "shippingContactName",header: t`Shipping Contact Name`,- cell: ({ row }) => getShippingContact(row.original)?.fullName ?? "",+ cell: ({ row }) =>+ SUPPLIER_CONTACT_VALUES.shippingContactName(row.original) ?? "",meta: {icon: <LuUser />,- exportValue: (row) => getShippingContact(row)?.fullName ?? null+ exportValue: SUPPLIER_CONTACT_VALUES.shippingContactName}},{id: "shippingContactEmail",header: t`Shipping Contact Email`,- cell: ({ row }) => getShippingContact(row.original)?.email ?? "",+ cell: ({ row }) =>+ SUPPLIER_CONTACT_VALUES.shippingContactEmail(row.original) ?? "",meta: {icon: <LuMail />,- exportValue: (row) => getShippingContact(row)?.email ?? null+ exportValue: SUPPLIER_CONTACT_VALUES.shippingContactEmail}},{id: "shippingContactPhone",header: t`Shipping Contact Phone`,- cell: ({ row }) => getShippingContact(row.original)?.workPhone ?? "",+ cell: ({ row }) =>+ SUPPLIER_CONTACT_VALUES.shippingContactPhone(row.original) ?? "",meta: {icon: <LuPhone />,- exportValue: (row) => getShippingContact(row)?.workPhone ?? null+ exportValue: SUPPLIER_CONTACT_VALUES.shippingContactPhone}}];return [...defaultColumns, ...customColumns];- }, [- supplierTypes,- people,- tags,- customColumns,- t,- showSupplierReadableId,- supplierReportContacts- ]);+ }, [supplierTypes, people, tags, customColumns, t, showSupplierReadableId]);const renderContextMenu = useMemo(- () => (row: Supplier) => (+ () => (row: SupplierRow) => (<><MenuItemshortcut={MENU_ITEM_SHORTCUTS.edit}@@ -446,10 +426,11 @@ const SuppliersTable = memo(function SuppliersTable({return (<>- <Table<Supplier>+ <Table<SupplierRow>count={count}columns={columns}data={data}+ infinite={infinite}defaultColumnPinning={{left: ["name"]}}diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/supplier-list-export.ts b/apps/erp/app/modules/purchasing/ui/Supplier/supplier-list-export.tsnew file mode 100644index 0000000000..3340162558--- /dev/null+++ b/apps/erp/app/modules/purchasing/ui/Supplier/supplier-list-export.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { formatAddress } from "@carbon/utils";+import type { SupplierReportContacts } from "../../types";++/**+ * The supplier contact and address columns, by column id. The loader adds+ * `reportContacts` to each page's rows; the Suppliers table shows and exports+ * these values, and the background CSV export writes the same ones+ * (`suppliersList.exportRows`).+ */+type Row = { reportContacts?: SupplierReportContacts | null };++const purchasingContact = (row: Row) =>+ row.reportContacts?.purchasingContact?.contact ?? null;+const invoiceContact = (row: Row) =>+ row.reportContacts?.payment?.invoiceContact?.contact ?? null;+const shippingContact = (row: Row) =>+ row.reportContacts?.shipping?.shippingContact?.contact ?? null;++type Address = NonNullable<+ NonNullable<SupplierReportContacts["payment"]>["invoiceLocation"]+>["address"];++const formatSupplierAddress = (address: Address | null | undefined) =>+ address+ ? formatAddress(+ address.addressLine1,+ address.addressLine2,+ address.city,+ address.stateProvince,+ address.postalCode,+ address.country?.name+ )+ : null;++export const SUPPLIER_CONTACT_VALUES = {+ purchasingContactName: (row: Row) => purchasingContact(row)?.fullName ?? null,+ purchasingContactEmail: (row: Row) => purchasingContact(row)?.email ?? null,+ purchasingContactPhone: (row: Row) =>+ purchasingContact(row)?.workPhone ?? null,+ invoiceAddress: (row: Row) =>+ formatSupplierAddress(+ row.reportContacts?.payment?.invoiceLocation?.address+ ),+ invoiceContactName: (row: Row) => invoiceContact(row)?.fullName ?? null,+ invoiceContactEmail: (row: Row) => invoiceContact(row)?.email ?? null,+ invoiceContactPhone: (row: Row) => invoiceContact(row)?.workPhone ?? null,+ shippingAddress: (row: Row) =>+ formatSupplierAddress(+ row.reportContacts?.shipping?.shippingLocation?.address+ ),+ shippingContactName: (row: Row) => shippingContact(row)?.fullName ?? null,+ shippingContactEmail: (row: Row) => shippingContact(row)?.email ?? null,+ shippingContactPhone: (row: Row) => shippingContact(row)?.workPhone ?? null+} satisfies Record<string, (row: Row) => string | null>;diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuotesTable.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuotesTable.tsxindex 004e0f6340..1d4e8e1f7f 100644--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuotesTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuotesTable.tsx@@ -47,10 +47,12 @@ import {type SupplierQuotesTableProps = {data: SupplierQuote[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const SupplierQuotesTable = memo(- ({ data, count }: SupplierQuotesTableProps) => {+ ({ data, count, nextCursor }: SupplierQuotesTableProps) => {const { t } = useLingui();const permissions = usePermissions();const navigate = useNavigate();@@ -272,6 +274,11 @@ const SupplierQuotesTable = memo(count={count}columns={columns}data={data}+ infinite={{+ dataKey: "quotes",+ nextCursor,+ listKey: "supplier-quotes"+ }}defaultColumnPinning={{left: ["supplierQuoteId"]}}diff --git a/apps/erp/app/modules/purchasing/ui/SupplierTypes/SupplierTypesTable.tsx b/apps/erp/app/modules/purchasing/ui/SupplierTypes/SupplierTypesTable.tsxindex 425f7d00bd..47cc988606 100644--- a/apps/erp/app/modules/purchasing/ui/SupplierTypes/SupplierTypesTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/SupplierTypes/SupplierTypesTable.tsx@@ -19,9 +19,12 @@ import { path } from "~/utils/path";type SupplierTypesTableProps = {data: SupplierType[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const SupplierTypesTable = memo(({ data, count }: SupplierTypesTableProps) => {+const SupplierTypesTable = memo((props: SupplierTypesTableProps) => {+ const { data, count, nextCursor } = props;const [params] = useUrlParams();const { t } = useLingui();const navigate = useNavigate();@@ -96,6 +99,11 @@ const SupplierTypesTable = memo(({ data, count }: SupplierTypesTableProps) => {data={data}columns={columns}count={count}+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "supplier-types"+ }}primaryAction={permissions.can("create", "purchasing") && (<Newdiff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.tsindex 3dedf22bf5..00428ea79b 100644--- a/apps/erp/app/modules/quality/quality.service.ts+++ b/apps/erp/app/modules/quality/quality.service.ts@@ -11,7 +11,7 @@ import { datetime } from "@carbon/utils";import { parseDate } from "@internationalized/date";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";-import type { GenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";@@ -277,6 +277,10 @@ export async function getGauge(return client.from("gauges").select("*").eq("id", gaugeId).single();}+export const GAUGES_PAGING: Paging = {+ defaultSorts: [{ column: "gaugeId", ascending: false }]+};+/** @mcp read */export async function getGauges(client: SupabaseClient<Database>,@@ -285,7 +289,7 @@ export async function getGauges() {let query = client.from("gauges")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -295,9 +299,7 @@ export async function getGauges(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "gaugeId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, GAUGES_PAGING);}return query;@@ -330,6 +332,13 @@ export async function getGaugeCalibrationRecord(.single();}+export const GAUGE_CALIBRATION_RECORDS_PAGING: Paging = {+ defaultSorts: [+ { column: "createdAt", ascending: false },+ { column: "dateCalibrated", ascending: false }+ ]+};+/** @mcp read */export async function getGaugeCalibrationRecords(client: SupabaseClient<Database>,@@ -338,7 +347,7 @@ export async function getGaugeCalibrationRecords() {let query = client.from("gaugeCalibrationRecords")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -348,10 +357,11 @@ export async function getGaugeCalibrationRecords(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false },- { column: "dateCalibrated", ascending: false }- ]);+ query = setGenericQueryFilters(+ query,+ args,+ GAUGE_CALIBRATION_RECORDS_PAGING+ );}return query;@@ -389,6 +399,10 @@ export async function getGaugeType(return client.from("gaugeType").select("*").eq("id", gaugeTypeId).single();}+export const GAUGE_TYPES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getGaugeTypes(client: SupabaseClient<Database>,@@ -397,7 +411,7 @@ export async function getGaugeTypes() {let query = client.from("gaugeType")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -405,9 +419,7 @@ export async function getGaugeTypes(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, GAUGE_TYPES_PAGING);}return query;@@ -425,6 +437,10 @@ export async function getIssue(.single();}+export const ISSUES_PAGING: Paging = {+ defaultSorts: [{ column: "nonConformanceId", ascending: false }]+};+/** @mcp read */export async function getIssues(client: SupabaseClient<Database>,@@ -433,7 +449,7 @@ export async function getIssues() {let query = client.from("issues")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -443,9 +459,7 @@ export async function getIssues(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "nonConformanceId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, ISSUES_PAGING);}return query;@@ -1008,6 +1022,10 @@ export async function getIssueTypeByName(return query.limit(1).maybeSingle();}+export const ISSUE_TYPES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getIssueTypes(client: SupabaseClient<Database>,@@ -1016,7 +1034,7 @@ export async function getIssueTypes() {let query = client.from("nonConformanceType")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -1024,14 +1042,16 @@ export async function getIssueTypes(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, ISSUE_TYPES_PAGING);}return query;}+export const ISSUE_WORKFLOWS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getIssueWorkflows(client: SupabaseClient<Database>,@@ -1040,7 +1060,7 @@ export async function getIssueWorkflows() {let query = client.from("nonConformanceWorkflow")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId).eq("active", true);@@ -1049,9 +1069,7 @@ export async function getIssueWorkflows(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, ISSUE_WORKFLOWS_PAGING);}return query;@@ -1082,6 +1100,10 @@ export async function getIssueTypesList(.order("name");}+export const QUALITY_ACTIONS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getQualityActions(client: SupabaseClient<Database>,@@ -1090,7 +1112,7 @@ export async function getQualityActions() {let query = client.from("qualityActions")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -1100,9 +1122,7 @@ export async function getQualityActions(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, QUALITY_ACTIONS_PAGING);}return query;@@ -1146,6 +1166,10 @@ export async function getQualityDocumentVersions(.order("version", { ascending: false });}+export const QUALITY_DOCUMENTS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getQualityDocuments(client: SupabaseClient<Database>,@@ -1155,7 +1179,7 @@ export async function getQualityDocuments(let query = client.from("qualityDocuments").select("*", {- count: LIST_COUNT+ count: args?.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -1164,9 +1188,7 @@ export async function getQualityDocuments(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, QUALITY_DOCUMENTS_PAGING);}return query;@@ -1215,6 +1237,10 @@ export async function getRequiredActionsList(.order("name");}+export const REQUIRED_ACTIONS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getRequiredActions(client: SupabaseClient<Database>,@@ -1223,7 +1249,7 @@ export async function getRequiredActions() {let query = client.from("nonConformanceRequiredAction")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -1231,9 +1257,7 @@ export async function getRequiredActions(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, REQUIRED_ACTIONS_PAGING);}return query;@@ -1259,6 +1283,10 @@ export async function getRisk(return client.from("riskRegister").select("*").eq("id", riskId).single();}+export const RISKS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getRisks(client: SupabaseClient<Database>,@@ -1274,7 +1302,7 @@ export async function getRisks(let query = client.from("riskRegisters").select("*", {- count: LIST_COUNT+ count: args?.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -1297,9 +1325,7 @@ export async function getRisks(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, RISKS_PAGING);}return query;@@ -2398,6 +2424,10 @@ export async function upsertRisk(// Inbound Inspections (lot-based)// -------------------------------------------------------------+export const INSPECTIONS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getInspections(client: SupabaseClient<Database>,@@ -2414,7 +2444,7 @@ export async function getInspections(.from("inspection").select("*, item(readableId, name), supplier(name), inspectionSample(status)",- { count: LIST_COUNT }+ { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);@@ -2435,9 +2465,7 @@ export async function getInspections(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, INSPECTIONS_PAGING);}return query;@@ -2671,6 +2699,10 @@ function mapInspectionDocument(row: Record<string, unknown>) {};}+export const INSPECTION_DOCUMENTS_PAGING: Paging = {+ defaultSorts: [{ column: "drawingNumber", ascending: true }]+};+/** @mcp read */export async function getInspectionDocuments(client: SupabaseClient<Database>,@@ -2679,7 +2711,7 @@ export async function getInspectionDocuments() {let query = client.from("inspectionDocuments")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -2689,17 +2721,17 @@ export async function getInspectionDocuments(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "drawingNumber", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, INSPECTION_DOCUMENTS_PAGING);}const result = await query;return {- data: (result.data ?? []).map((row: Record<string, unknown>) =>- mapInspectionDocument(row)- ),+ // The cursor reads the default sort column from the row.+ data: (result.data ?? []).map((row: Record<string, unknown>) => ({+ ...mapInspectionDocument(row),+ drawingNumber: (row.drawingNumber as string | null) ?? null+ })),count: result.count ?? 0,error: result.error};diff --git a/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx b/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsxindex 3427ceb2bf..591f4ab1a0 100644--- a/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx+++ b/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx@@ -40,10 +40,17 @@ type ActionsTableProps = {issueTypes: ListItem[];requiredActions: ListItem[];count: number;+ nextCursor: string | null;};const ActionsTable = memo(- ({ data, issueTypes, requiredActions, count }: ActionsTableProps) => {+ ({+ data,+ issueTypes,+ requiredActions,+ count,+ nextCursor+ }: ActionsTableProps) => {const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -257,6 +264,11 @@ const ActionsTable = memo(return (<Table<QualityAction>data={data}+ infinite={{+ dataKey: "actions",+ nextCursor,+ listKey: "quality-actions"+ }}columns={columns}count={count}renderContextMenu={renderContextMenu}diff --git a/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable.tsx b/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable.tsxindex f8b6673956..7989cd323b 100644--- a/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable.tsx+++ b/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable.tsx@@ -57,6 +57,7 @@ type GaugeCalibrationRecordsTableProps = {data: GaugeCalibrationRecord[];types: ListItem[];count: number;+ nextCursor: string | null;};const defaultColumnVisibility = {@@ -70,7 +71,7 @@ const defaultColumnVisibility = {};const GaugeCalibrationRecordsTable = memo(- ({ data, types, count }: GaugeCalibrationRecordsTableProps) => {+ ({ data, types, count, nextCursor }: GaugeCalibrationRecordsTableProps) => {const [params] = useUrlParams();const navigate = useNavigate();const { t } = useLingui();@@ -398,6 +399,11 @@ const GaugeCalibrationRecordsTable = memo(<><Table<GaugeCalibrationRecord>data={data}+ infinite={{+ dataKey: "gaugeCalibrationRecords",+ nextCursor,+ listKey: "gauge-calibration-records"+ }}columns={columns}count={count}defaultColumnVisibility={defaultColumnVisibility}diff --git a/apps/erp/app/modules/quality/ui/Documents/QualityDocumentsTable.tsx b/apps/erp/app/modules/quality/ui/Documents/QualityDocumentsTable.tsxindex a8be0c343b..4e78d7bc91 100644--- a/apps/erp/app/modules/quality/ui/Documents/QualityDocumentsTable.tsx+++ b/apps/erp/app/modules/quality/ui/Documents/QualityDocumentsTable.tsx@@ -41,11 +41,12 @@ import QualityDocumentStatus from "./QualityDocumentStatus";type QualityDocumentsTableProps = {data: QualityDocuments[];count: number;+ nextCursor: string | null;tags: Array<{ name: string }>;};const QualityDocumentsTable = memo(- ({ data, count, tags }: QualityDocumentsTableProps) => {+ ({ data, count, tags, nextCursor }: QualityDocumentsTableProps) => {const navigate = useNavigate();const { t } = useLingui();const permissions = usePermissions();@@ -228,6 +229,11 @@ const QualityDocumentsTable = memo(<><Table<QualityDocuments>data={data}+ infinite={{+ dataKey: "qualityDocuments",+ nextCursor,+ listKey: "quality-documents"+ }}columns={columns}count={count}primaryAction={diff --git a/apps/erp/app/modules/quality/ui/Gauge/GaugesTable.tsx b/apps/erp/app/modules/quality/ui/Gauge/GaugesTable.tsxindex 7d9c7f577d..481cdca93b 100644--- a/apps/erp/app/modules/quality/ui/Gauge/GaugesTable.tsx+++ b/apps/erp/app/modules/quality/ui/Gauge/GaugesTable.tsx@@ -59,6 +59,7 @@ type GaugesTableProps = {data: Gauge[];types: ListItem[];count: number;+ nextCursor: string | null;};const defaultColumnVisibility = {@@ -67,7 +68,8 @@ const defaultColumnVisibility = {updatedBy: false};-const GaugesTable = memo(({ data, types, count }: GaugesTableProps) => {+const GaugesTable = memo((props: GaugesTableProps) => {+ const { data, types, count, nextCursor } = props;const [params] = useUrlParams();const navigate = useNavigate();const { t } = useLingui();@@ -396,6 +398,11 @@ const GaugesTable = memo(({ data, types, count }: GaugesTableProps) => {<><Table<Gauge>data={data}+ infinite={{+ dataKey: "gauges",+ nextCursor,+ listKey: "gauges"+ }}columns={columns}count={count}defaultColumnVisibility={defaultColumnVisibility}diff --git a/apps/erp/app/modules/quality/ui/GaugeTypes/GaugeTypesTable.tsx b/apps/erp/app/modules/quality/ui/GaugeTypes/GaugeTypesTable.tsxindex 89f9ac6205..4cefe1b533 100644--- a/apps/erp/app/modules/quality/ui/GaugeTypes/GaugeTypesTable.tsx+++ b/apps/erp/app/modules/quality/ui/GaugeTypes/GaugeTypesTable.tsx@@ -18,9 +18,11 @@ import type { GaugeType } from "../../types";type GaugeTypesTableProps = {data: GaugeType[];count: number;+ nextCursor: string | null;};-const GaugeTypesTable = memo(({ data, count }: GaugeTypesTableProps) => {+const GaugeTypesTable = memo((props: GaugeTypesTableProps) => {+ const { data, count, nextCursor } = props;const [params] = useUrlParams();const navigate = useNavigate();const { t } = useLingui();@@ -82,6 +84,11 @@ const GaugeTypesTable = memo(({ data, count }: GaugeTypesTableProps) => {return (<Table<GaugeType>data={data}+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "gauge-types"+ }}columns={columns}count={count}primaryAction={diff --git a/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentTable.tsx b/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentTable.tsxindex 85e55df26b..b270f01143 100644--- a/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentTable.tsx+++ b/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentTable.tsx@@ -32,6 +32,7 @@ import type { InspectionDocument } from "../../types";type InspectionDocumentTableProps = {data: InspectionDocument[];count: number;+ nextCursor: string | null;};const defaultColumnVisibility = {@@ -41,7 +42,7 @@ const defaultColumnVisibility = {};const InspectionDocumentTable = memo(- ({ data, count }: InspectionDocumentTableProps) => {+ ({ data, count, nextCursor }: InspectionDocumentTableProps) => {const [params] = useUrlParams();const navigate = useNavigate();const { t } = useLingui();@@ -94,6 +95,8 @@ const InspectionDocumentTable = memo(accessorKey: "name",header: t`Name`,cell: ({ row }) => row.original.name,+ // The service computes `name`; the view has no such column to sort.+ enableSorting: false,meta: { mobile: "P3", icon: <LuTarget /> }},{@@ -170,6 +173,11 @@ const InspectionDocumentTable = memo(<><Table<InspectionDocument>data={data}+ infinite={{+ dataKey: "diagrams",+ nextCursor,+ listKey: "inspection-plans"+ }}columns={columns}count={count}defaultColumnVisibility={defaultColumnVisibility}diff --git a/apps/erp/app/modules/quality/ui/Inspections/InspectionsTable.tsx b/apps/erp/app/modules/quality/ui/Inspections/InspectionsTable.tsxindex 67ccbe1bb8..8c24fcb684 100644--- a/apps/erp/app/modules/quality/ui/Inspections/InspectionsTable.tsx+++ b/apps/erp/app/modules/quality/ui/Inspections/InspectionsTable.tsx@@ -35,6 +35,7 @@ import { getInspectionStatusVariant } from "./InspectionStatus";type InspectionsTableProps = {data: Inspection[];count: number;+ nextCursor: string | null;};function computeProgress(row: Inspection): {@@ -49,7 +50,8 @@ function computeProgress(row: Inspection): {return { inspected, total: (row as any).sampleSize ?? 0 };}-const InspectionsTable = memo(({ data, count }: InspectionsTableProps) => {+const InspectionsTable = memo((props: InspectionsTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const [params] = useUrlParams();const [items] = useItems();@@ -202,6 +204,11 @@ const InspectionsTable = memo(({ data, count }: InspectionsTableProps) => {return (<Table<Inspection>data={data}+ infinite={{+ dataKey: "inspections",+ nextCursor,+ listKey: "inspections"+ }}columns={columns}count={count ?? 0}title={t`Inspections`}diff --git a/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsx b/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsxindex 334d680c72..4bf29ca071 100644--- a/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsx@@ -52,9 +52,11 @@ type IssuesTableProps = {data: Issue[];types: ListItem[];count: number;+ nextCursor: string | null;};-const IssuesTable = memo(({ data, types, count }: IssuesTableProps) => {+const IssuesTable = memo((props: IssuesTableProps) => {+ const { data, types, count, nextCursor } = props;const navigate = useNavigate();const { t } = useLingui();const permissions = usePermissions();@@ -358,6 +360,11 @@ const IssuesTable = memo(({ data, types, count }: IssuesTableProps) => {<><Table<Issue>data={data}+ infinite={{+ dataKey: "issues",+ nextCursor,+ listKey: "issues"+ }}columns={columns}count={count}primaryAction={diff --git a/apps/erp/app/modules/quality/ui/IssueTypes/IssueTypesTable.tsx b/apps/erp/app/modules/quality/ui/IssueTypes/IssueTypesTable.tsxindex 008eecc219..d926f62a03 100644--- a/apps/erp/app/modules/quality/ui/IssueTypes/IssueTypesTable.tsx+++ b/apps/erp/app/modules/quality/ui/IssueTypes/IssueTypesTable.tsx@@ -18,9 +18,11 @@ import type { IssueType } from "../../types";type IssueTypesTableProps = {data: IssueType[];count: number;+ nextCursor: string | null;};-const IssueTypesTable = memo(({ data, count }: IssueTypesTableProps) => {+const IssueTypesTable = memo((props: IssueTypesTableProps) => {+ const { data, count, nextCursor } = props;const [params] = useUrlParams();const navigate = useNavigate();const { t } = useLingui();@@ -82,6 +84,11 @@ const IssueTypesTable = memo(({ data, count }: IssueTypesTableProps) => {return (<Table<IssueType>data={data}+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "issue-types"+ }}columns={columns}count={count}primaryAction={diff --git a/apps/erp/app/modules/quality/ui/IssueWorkflows/IssueWorkflowsTable.tsx b/apps/erp/app/modules/quality/ui/IssueWorkflows/IssueWorkflowsTable.tsxindex 111926c9a9..6c4fd26d3a 100644--- a/apps/erp/app/modules/quality/ui/IssueWorkflows/IssueWorkflowsTable.tsx+++ b/apps/erp/app/modules/quality/ui/IssueWorkflows/IssueWorkflowsTable.tsx@@ -30,10 +30,11 @@ import { getPriorityIcon, getSourceIcon } from "../Issue/IssueIcons";type IssueWorkflowsTableProps = {data: IssueWorkflow[];count: number;+ nextCursor: string | null;};const IssueWorkflowsTable = memo(- ({ data, count }: IssueWorkflowsTableProps) => {+ ({ data, count, nextCursor }: IssueWorkflowsTableProps) => {const navigate = useNavigate();const { t } = useLingui();const permissions = usePermissions();@@ -128,6 +129,11 @@ const IssueWorkflowsTable = memo(<><Table<IssueWorkflow>data={data}+ infinite={{+ dataKey: "procedures",+ nextCursor,+ listKey: "issue-workflows"+ }}columns={columns}count={count}primaryAction={diff --git a/apps/erp/app/modules/quality/ui/RequiredActions/RequiredActionsTable.tsx b/apps/erp/app/modules/quality/ui/RequiredActions/RequiredActionsTable.tsxindex 709a0a63a5..522a52630e 100644--- a/apps/erp/app/modules/quality/ui/RequiredActions/RequiredActionsTable.tsx+++ b/apps/erp/app/modules/quality/ui/RequiredActions/RequiredActionsTable.tsx@@ -25,10 +25,11 @@ import type { RequiredAction } from "../../types";type RequiredActionsTableProps = {data: RequiredAction[];count: number;+ nextCursor: string | null;};const RequiredActionsTable = memo(- ({ data, count }: RequiredActionsTableProps) => {+ ({ data, count, nextCursor }: RequiredActionsTableProps) => {const [params] = useUrlParams();const navigate = useNavigate();const { t } = useLingui();@@ -103,6 +104,11 @@ const RequiredActionsTable = memo(<><Table<RequiredAction>data={data}+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "required-actions"+ }}columns={columns}count={count}primaryAction={diff --git a/apps/erp/app/modules/quality/ui/RiskRegister/RiskRegistersTable.tsx b/apps/erp/app/modules/quality/ui/RiskRegister/RiskRegistersTable.tsxindex c1b962d8cc..422013f306 100644--- a/apps/erp/app/modules/quality/ui/RiskRegister/RiskRegistersTable.tsx+++ b/apps/erp/app/modules/quality/ui/RiskRegister/RiskRegistersTable.tsx@@ -51,6 +51,7 @@ import RiskType from "./RiskType";type RiskRegistersTableProps = {data: Risk[];count: number;+ nextCursor: string | null;};const defaultColumnVisibility = {@@ -60,7 +61,8 @@ const defaultColumnVisibility = {updatedAt: false};-const RiskRegistersTable = memo(({ data, count }: RiskRegistersTableProps) => {+const RiskRegistersTable = memo((props: RiskRegistersTableProps) => {+ const { data, count, nextCursor } = props;const navigate = useNavigate();const [params] = useUrlParams();const workCenters = useWorkCenters({});@@ -284,6 +286,11 @@ const RiskRegistersTable = memo(({ data, count }: RiskRegistersTableProps) => {<><Table<Risk>data={data}+ infinite={{+ dataKey: "risks",+ nextCursor,+ listKey: "risks"+ }}defaultColumnVisibility={defaultColumnVisibility}columns={columns}count={count ?? 0}diff --git a/apps/erp/app/modules/resources/resources.service.ts b/apps/erp/app/modules/resources/resources.service.tsindex f8aaa61197..0b289d1f2a 100644--- a/apps/erp/app/modules/resources/resources.service.ts+++ b/apps/erp/app/modules/resources/resources.service.ts@@ -10,7 +10,7 @@ import {} from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";-import type { GenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";import type {@@ -226,6 +226,10 @@ export async function deleteWorkCenter(return client.from("workCenter").update({ active: false }).eq("id", id);}+export const ABILITIES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getAbilities(client: SupabaseClient<Database>,@@ -244,7 +248,7 @@ export async function getAbilities(// rather than embedded, so the read never depends on a view→table embed.let query = client.from("abilities")- .select(`*`, { count: LIST_COUNT })+ .select(`*`, { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId).eq("active", true);@@ -266,9 +270,7 @@ export async function getAbilities(query = query.ilike("name", `%${args.search}%`);}- query = setGenericQueryFilters(query, { ...args, filters }, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, { ...args, filters }, ABILITIES_PAGING);const result = await query;if (result.error || !result.data) return result;@@ -359,6 +361,12 @@ export async function getContractor(.single();}+// The `contractors` view has no `id`; a contractor is one supplier contact.+export const CONTRACTORS_PAGING: Paging = {+ defaultSorts: [{ column: "lastName", ascending: true }],+ idColumn: "supplierContactId"+};+/** @mcp read */export async function getContractors(client: SupabaseClient<Database>,@@ -367,7 +375,7 @@ export async function getContractors() {let query = client.from("contractors")- .select("*")+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId).eq("active", true);@@ -378,9 +386,7 @@ export async function getContractors(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "lastName", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, CONTRACTORS_PAGING);}return query;@@ -423,6 +429,10 @@ export async function getFailureMode(.single();}+export const FAILURE_MODES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getFailureModes(client: SupabaseClient<Database>,@@ -431,7 +441,7 @@ export async function getFailureModes() {let query = client.from("maintenanceFailureMode")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -439,9 +449,7 @@ export async function getFailureModes(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, FAILURE_MODES_PAGING);}return query;@@ -467,6 +475,10 @@ export async function getLocation(return client.from("location").select("*").eq("id", locationId).single();}+export const LOCATIONS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getLocations(client: SupabaseClient<Database>,@@ -475,7 +487,7 @@ export async function getLocations() {let query = client.from("location")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -483,9 +495,7 @@ export async function getLocations(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, LOCATIONS_PAGING);}return query;@@ -607,6 +617,10 @@ export async function getMaintenanceDispatches(return query;}+export const MAINTENANCE_DISPATCHES_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getMaintenanceDispatchesByLocation(client: SupabaseClient<Database>,@@ -620,7 +634,7 @@ export async function getMaintenanceDispatchesByLocation(p_company_id: companyId,p_location_id: locationId},- { count: LIST_COUNT }+ { count: args?.cursor ? undefined : LIST_COUNT });if (args?.search) {@@ -628,9 +642,7 @@ export async function getMaintenanceDispatchesByLocation(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, MAINTENANCE_DISPATCHES_PAGING);}return query;@@ -707,6 +719,10 @@ export async function getMaintenanceSchedules(return query;}+export const MAINTENANCE_SCHEDULES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getMaintenanceSchedulesByLocation(client: SupabaseClient<Database>,@@ -720,7 +736,7 @@ export async function getMaintenanceSchedulesByLocation(p_company_id: companyId,p_location_id: locationId},- { count: LIST_COUNT }+ { count: args?.cursor ? undefined : LIST_COUNT });if (args?.search) {@@ -732,9 +748,7 @@ export async function getMaintenanceSchedulesByLocation(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, MAINTENANCE_SCHEDULES_PAGING);}return query;@@ -860,6 +874,10 @@ export async function getProcess(return client.from("processes").select("*").eq("id", processId).single();}+export const PROCESSES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getProcesses(client: SupabaseClient<Database>,@@ -868,7 +886,7 @@ export async function getProcesses() {let query = client.from("processes")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -876,9 +894,7 @@ export async function getProcesses(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, PROCESSES_PAGING);}return query;@@ -905,6 +921,10 @@ export async function getSuggestion(return client.from("suggestions").select("*").eq("id", suggestionId).single();}+export const SUGGESTIONS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getSuggestions(client: SupabaseClient<Database>,@@ -913,7 +933,7 @@ export async function getSuggestions() {let query = client.from("suggestions")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -921,9 +941,7 @@ export async function getSuggestions(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, SUGGESTIONS_PAGING);}return query;@@ -1041,7 +1059,7 @@ export async function getTrainingAssignmentStatus(return 0;});- // Apply pagination+ // The RPC returns every row, so `limit` + `offset` cut the list in memory.const count = filteredData.length;if (args?.limit) {const offset = args.offset ?? 0;@@ -1073,6 +1091,10 @@ export async function getTrainingQuestions(.order("sortOrder", { ascending: true });}+export const TRAININGS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getTrainings(client: SupabaseClient<Database>,@@ -1082,7 +1104,7 @@ export async function getTrainings(let query = client.from("trainings").select("*", {- count: LIST_COUNT+ count: args?.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -1091,9 +1113,7 @@ export async function getTrainings(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, TRAININGS_PAGING);}return query;@@ -1146,6 +1166,10 @@ export async function getWorkCenter(};}+export const WORK_CENTERS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getWorkCenters(client: SupabaseClient<Database>,@@ -1155,7 +1179,7 @@ export async function getWorkCenters(let query = client.from("workCenters").select("*", {- count: LIST_COUNT+ count: args?.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -1164,9 +1188,7 @@ export async function getWorkCenters(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, WORK_CENTERS_PAGING);}return query;diff --git a/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsx b/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsxindex edfcc06a56..b3aff6c9f4 100644--- a/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsx+++ b/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsx@@ -26,9 +26,11 @@ type Ability = Abilities[number];type AbilitiesTableProps = {data: Abilities;count: number;+ nextCursor: string | null;};-const AbilitiesTable = memo(({ data, count }: AbilitiesTableProps) => {+const AbilitiesTable = memo((props: AbilitiesTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const navigate = useNavigate();const [params] = useUrlParams();@@ -127,6 +129,7 @@ const AbilitiesTable = memo(({ data, count }: AbilitiesTableProps) => {return (<Table<Ability>data={data}+ infinite={{ dataKey: "abilities", nextCursor, listKey: "abilities" }}columns={columns}count={count ?? 0}primaryAction={diff --git a/apps/erp/app/modules/resources/ui/Contractors/ContractorsTable.tsx b/apps/erp/app/modules/resources/ui/Contractors/ContractorsTable.tsxindex e958b532c9..a27fba5605 100644--- a/apps/erp/app/modules/resources/ui/Contractors/ContractorsTable.tsx+++ b/apps/erp/app/modules/resources/ui/Contractors/ContractorsTable.tsx@@ -24,10 +24,12 @@ import { path } from "~/utils/path";type ContractorsTableProps = {data: Contractor[];count: number;+ nextCursor: string | null;// abilities: Partial<Ability>[];};-const ContractorsTable = memo(({ data, count }: ContractorsTableProps) => {+const ContractorsTable = memo((props: ContractorsTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -162,6 +164,12 @@ const ContractorsTable = memo(({ data, count }: ContractorsTableProps) => {data={data}count={count}columns={columns}+ infinite={{+ dataKey: "contractors",+ nextCursor,+ listKey: "contractors"+ }}+ getRowId={(row) => String(row.supplierContactId)}primaryAction={permissions.can("create", "resources") && (<New label={t`Contractor`} to={`new?${params.toString()}`} />diff --git a/apps/erp/app/modules/resources/ui/FailureModes/FailureModesTable.tsx b/apps/erp/app/modules/resources/ui/FailureModes/FailureModesTable.tsxindex ae6dee4830..1164f9146f 100644--- a/apps/erp/app/modules/resources/ui/FailureModes/FailureModesTable.tsx+++ b/apps/erp/app/modules/resources/ui/FailureModes/FailureModesTable.tsx@@ -18,9 +18,11 @@ import type { FailureMode } from "../../types";type FailureModesTableProps = {data: FailureMode[];count: number;+ nextCursor: string | null;};-const FailureModesTable = memo(({ data, count }: FailureModesTableProps) => {+const FailureModesTable = memo((props: FailureModesTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -96,6 +98,7 @@ const FailureModesTable = memo(({ data, count }: FailureModesTableProps) => {return (<Table<FailureMode>data={data}+ infinite={{ dataKey: "data", nextCursor, listKey: "failure-modes" }}columns={columns}count={count}primaryAction={diff --git a/apps/erp/app/modules/resources/ui/Locations/LocationsTable.tsx b/apps/erp/app/modules/resources/ui/Locations/LocationsTable.tsxindex 2754decc79..6154468dd1 100644--- a/apps/erp/app/modules/resources/ui/Locations/LocationsTable.tsx+++ b/apps/erp/app/modules/resources/ui/Locations/LocationsTable.tsx@@ -29,22 +29,20 @@ import { path } from "~/utils/path";type LocationsTableProps = {data: ShiftLocation[];count: number;+ nextCursor: string | null;};-const LocationsTable = memo(({ data, count }: LocationsTableProps) => {+const LocationsTable = memo((props: LocationsTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();const [params] = useUrlParams();const [people] = usePeople();- const rows = data.map((row) => ({- ...row- }));-const customColumns = useCustomColumns<ShiftLocation>("location");- const columns = useMemo<ColumnDef<(typeof rows)[number]>[]>(() => {- const defaultColumns: ColumnDef<(typeof rows)[number]>[] = [+ const columns = useMemo<ColumnDef<(typeof data)[number]>[]>(() => {+ const defaultColumns: ColumnDef<(typeof data)[number]>[] = [{accessorKey: "name",header: t`Location`,@@ -176,8 +174,9 @@ const LocationsTable = memo(({ data, count }: LocationsTableProps) => {);return (- <Table<(typeof rows)[number]>- data={rows}+ <Table<(typeof data)[number]>+ data={data}+ infinite={{ dataKey: "locations", nextCursor, listKey: "locations" }}count={count}columns={columns}primaryAction={diff --git a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchesTable.tsx b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchesTable.tsxindex 3faba5583d..12cef47bc7 100644--- a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchesTable.tsx+++ b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchesTable.tsx@@ -47,6 +47,7 @@ import MaintenanceStatus from "./MaintenanceStatus";type MaintenanceDispatchesTableProps = {data: MaintenanceDispatch[];count: number;+ nextCursor: string | null;failureModes: ListItem[];locations: { id: string; name: string }[];locationId: string | null;@@ -56,6 +57,7 @@ const MaintenanceDispatchesTable = memo(({data,count,+ nextCursor,failureModes,locations,locationId@@ -378,6 +380,11 @@ const MaintenanceDispatchesTable = memo(return (<Table<MaintenanceDispatch>data={data}+ infinite={{+ dataKey: "dispatches",+ nextCursor,+ listKey: "maintenance-dispatches"+ }}columns={columns}defaultColumnPinning={{left: ["maintenanceDispatchId"]diff --git a/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceSchedulesTable.tsx b/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceSchedulesTable.tsxindex 34d2df9ffc..21ce147011 100644--- a/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceSchedulesTable.tsx+++ b/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceSchedulesTable.tsx@@ -42,12 +42,19 @@ import MaintenancePriority from "../Maintenance/MaintenancePriority";type MaintenanceSchedulesTableProps = {data: MaintenanceSchedule[];count: number;+ nextCursor: string | null;locations: { id: string; name: string }[];locationId: string | null;};const MaintenanceSchedulesTable = memo(- ({ data, count, locations, locationId }: MaintenanceSchedulesTableProps) => {+ ({+ data,+ count,+ nextCursor,+ locations,+ locationId+ }: MaintenanceSchedulesTableProps) => {const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -277,6 +284,11 @@ const MaintenanceSchedulesTable = memo(return (<Table<MaintenanceSchedule>data={data}+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "maintenance-schedules"+ }}columns={columns}count={count}primaryAction={diff --git a/apps/erp/app/modules/resources/ui/Partners/PartnersTable.tsx b/apps/erp/app/modules/resources/ui/Partners/PartnersTable.tsxindex 521667bbbd..dcce9c1c89 100644--- a/apps/erp/app/modules/resources/ui/Partners/PartnersTable.tsx+++ b/apps/erp/app/modules/resources/ui/Partners/PartnersTable.tsx@@ -24,10 +24,13 @@ import { path } from "~/utils/path";type PartnersTableProps = {data: Partner[];count: number;+ // The loader read SINGLE_LOAD_LIMIT rows: more may match.+ isTruncated?: boolean;// abilities: Partial<Ability>[];};-const PartnersTable = memo(({ data, count }: PartnersTableProps) => {+const PartnersTable = memo((props: PartnersTableProps) => {+ const { data, count, isTruncated } = props;const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -138,6 +141,7 @@ const PartnersTable = memo(({ data, count }: PartnersTableProps) => {<Table<Partner>data={data}count={count}+ isTruncated={isTruncated}columns={columns}primaryAction={permissions.can("create", "resources") && (diff --git a/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx b/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsxindex 61f4f1ff29..8da96cc290 100644--- a/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx+++ b/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx@@ -58,6 +58,7 @@ import { path } from "~/utils/path";type ProcessesTableProps = {data: Process[];count: number;+ nextCursor: string | null;};const defaultColumnVisibility = {@@ -67,7 +68,8 @@ const defaultColumnVisibility = {updatedBy: false};-const ProcessesTable = memo(({ data, count }: ProcessesTableProps) => {+const ProcessesTable = memo((props: ProcessesTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -391,6 +393,7 @@ const ProcessesTable = memo(({ data, count }: ProcessesTableProps) => {return (<Table<Process>data={data}+ infinite={{ dataKey: "processes", nextCursor, listKey: "processes" }}count={count}columns={columns}defaultColumnVisibility={defaultColumnVisibility}diff --git a/apps/erp/app/modules/resources/ui/Suggestions/SuggestionsTable.tsx b/apps/erp/app/modules/resources/ui/Suggestions/SuggestionsTable.tsxindex 74910867c0..4b311a8906 100644--- a/apps/erp/app/modules/resources/ui/Suggestions/SuggestionsTable.tsx+++ b/apps/erp/app/modules/resources/ui/Suggestions/SuggestionsTable.tsx@@ -33,12 +33,13 @@ type SuggestionsTableProps = {data: SuggestionListItem[];tags: { name: string }[];count: number;+ nextCursor: string | null;};const defaultColumnVisibility = {};const SuggestionsTable = memo(- ({ data, tags, count }: SuggestionsTableProps) => {+ ({ data, tags, count, nextCursor }: SuggestionsTableProps) => {const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -169,6 +170,11 @@ const SuggestionsTable = memo(return (<Table<SuggestionListItem>data={data}+ infinite={{+ dataKey: "suggestions",+ nextCursor,+ listKey: "suggestions"+ }}count={count}columns={columns}defaultColumnVisibility={defaultColumnVisibility}diff --git a/apps/erp/app/modules/resources/ui/Training/TrainingsTable.tsx b/apps/erp/app/modules/resources/ui/Training/TrainingsTable.tsxindex d3c3f43c32..3b05bf1986 100644--- a/apps/erp/app/modules/resources/ui/Training/TrainingsTable.tsx+++ b/apps/erp/app/modules/resources/ui/Training/TrainingsTable.tsx@@ -38,10 +38,12 @@ import TrainingStatus from "./TrainingStatus";type TrainingsTableProps = {data: TrainingListItem[];count: number;+ nextCursor: string | null;tags: Array<{ name: string }>;};-const TrainingsTable = memo(({ data, count, tags }: TrainingsTableProps) => {+const TrainingsTable = memo((props: TrainingsTableProps) => {+ const { data, count, nextCursor, tags } = props;const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -241,6 +243,7 @@ const TrainingsTable = memo(({ data, count, tags }: TrainingsTableProps) => {<><Table<TrainingListItem>data={data}+ infinite={{ dataKey: "trainings", nextCursor, listKey: "trainings" }}columns={columns}count={count}primaryAction={diff --git a/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx b/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsxindex 92ce39c754..d7d0717b1b 100644--- a/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx+++ b/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx@@ -65,6 +65,7 @@ const logger = getLogger("erp", "workcenterstable");type WorkCentersTableProps = {data: WorkCenter[];count: number;+ nextCursor: string | null;departments: ListItem[];locations: ListItem[];};@@ -78,7 +79,13 @@ const defaultColumnVisibility = {};const WorkCentersTable = memo(- ({ data, count, departments, locations }: WorkCentersTableProps) => {+ ({+ data,+ count,+ nextCursor,+ departments,+ locations+ }: WorkCentersTableProps) => {const { t } = useLingui();const navigate = useNavigate();const [params] = useUrlParams();@@ -348,6 +355,11 @@ const WorkCentersTable = memo(<><Table<WorkCenter>data={data}+ infinite={{+ dataKey: "workCenters",+ nextCursor,+ listKey: "work-centers"+ }}defaultColumnVisibility={defaultColumnVisibility}columns={columns}count={count ?? 0}diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex 2db5180156..92aa0ad6e5 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -33,7 +33,7 @@ import type { z } from "zod";import { createDocumentUploadUrl } from "~/modules/documents/documents.service";import { getSupplierPriceBreaksForItems } from "~/modules/items/items.service";import { getEmployeeJob } from "~/modules/people";-import type { GenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import { sanitize } from "~/utils/supabase";import { getCurrencyByCode, getExchangeRate } from "../accounting";@@ -943,6 +943,10 @@ function pickBestBreak(return best;}+export const CUSTOMERS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getCustomers(client: SupabaseClient<Database>,@@ -954,7 +958,7 @@ export async function getCustomers(let query = client.from("customers").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -962,9 +966,7 @@ export async function getCustomers(query = query.ilike("name", `%${args.search}%`);}- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, CUSTOMERS_PAGING);return query;}@@ -993,6 +995,10 @@ export async function getCustomerStatus(.single();}+export const CUSTOMER_STATUSES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getCustomerStatuses(client: SupabaseClient<Database>,@@ -1001,7 +1007,9 @@ export async function getCustomerStatuses() {let query = client.from("customerStatus")- .select("id, name, customFields", { count: LIST_COUNT })+ .select("id, name, customFields", {+ count: args?.cursor ? undefined : LIST_COUNT+ }).eq("companyId", companyId);if (args?.search) {@@ -1009,9 +1017,7 @@ export async function getCustomerStatuses(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, CUSTOMER_STATUSES_PAGING);}return query;@@ -1041,6 +1047,10 @@ export async function getCustomerType(.single();}+export const CUSTOMER_TYPES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getCustomerTypes(client: SupabaseClient<Database>,@@ -1049,7 +1059,7 @@ export async function getCustomerTypes() {let query = client.from("customerType")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -1057,9 +1067,7 @@ export async function getCustomerTypes(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, CUSTOMER_TYPES_PAGING);}return query;@@ -1098,9 +1106,12 @@ export async function getExternalSalesOrderLines(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "orderDate", ascending: true }- ]);+ // The RPC returns no `id`, so `salesOrderId` is the last order term. The+ // share page loads one page only and never follows a cursor.+ query = setGenericQueryFilters(query, args, {+ defaultSorts: [{ column: "orderDate", ascending: true }],+ idColumn: "salesOrderId"+ });}return query;@@ -1146,6 +1157,10 @@ export async function getNoQuoteReason(.single();}+export const NO_QUOTE_REASONS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getNoQuoteReasons(client: SupabaseClient<Database>,@@ -1154,7 +1169,7 @@ export async function getNoQuoteReasons() {let query = client.from("noQuoteReason")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -1162,9 +1177,7 @@ export async function getNoQuoteReasons(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, NO_QUOTE_REASONS_PAGING);}return query;@@ -1281,6 +1294,9 @@ export async function getPricingRule(return client.from("pricingRule").select("*").eq("id", id).single();}+// No default order: without a sort the list follows the id.+export const PRICING_RULES_PAGING: Paging = { defaultSorts: [] };+/** @mcp read */export async function getPricingRules(client: SupabaseClient<Database>,@@ -1289,7 +1305,7 @@ export async function getPricingRules() {let query = client.from("pricingRule")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -1297,7 +1313,7 @@ export async function getPricingRules(}if (args) {- query = setGenericQueryFilters(query, args);+ query = setGenericQueryFilters(query, args, PRICING_RULES_PAGING);}return query;@@ -1319,6 +1335,10 @@ export async function getQuote(return client.from("quotes").select("*").eq("id", quoteId).single();}+export const QUOTES_PAGING: Paging = {+ defaultSorts: [{ column: "quoteId", ascending: false }]+};+/** @mcp read */export async function getQuotes(client: SupabaseClient<Database>,@@ -1329,7 +1349,9 @@ export async function getQuotes() {let query = client.from("quotes")- .select(QUOTES_LIST_COLUMNS, { count: LIST_COUNT })+ .select(QUOTES_LIST_COLUMNS, {+ count: args.cursor ? undefined : LIST_COUNT+ }).eq("companyId", companyId);if (args.search) {@@ -1338,9 +1360,7 @@ export async function getQuotes();}- query = setGenericQueryFilters(query, args, [- { column: "quoteId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, QUOTES_PAGING);return query;}@@ -1839,6 +1859,10 @@ export async function getSalesOrderRelatedItems(};}+export const SALES_ORDERS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getSalesOrders(client: SupabaseClient<Database>,@@ -1851,7 +1875,10 @@ export async function getSalesOrders() {let query = client.from("salesOrders")- .select(SALES_ORDERS_LIST_COLUMNS, { count: LIST_COUNT })+ // Later pages (`cursor`) skip the count: the first page already has it.+ .select(SALES_ORDERS_LIST_COLUMNS, {+ count: args.cursor ? undefined : LIST_COUNT+ }).eq("companyId", companyId);if (args.search) {@@ -1864,9 +1891,7 @@ export async function getSalesOrders(query = query.eq("customerId", args.customerId);}- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, SALES_ORDERS_PAGING);return query;}@@ -2070,6 +2095,10 @@ export async function getSalesRFQ(return client.from("salesRfqs").select("*").eq("id", id).single();}+export const SALES_RFQS_PAGING: Paging = {+ defaultSorts: [{ column: "rfqId", ascending: false }]+};+/** @mcp read */export async function getSalesRFQs(client: SupabaseClient<Database>,@@ -2080,7 +2109,7 @@ export async function getSalesRFQs() {let query = client.from("salesRfqs")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {@@ -2089,9 +2118,7 @@ export async function getSalesRFQs();}- query = setGenericQueryFilters(query, args, [- { column: "rfqId", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, SALES_RFQS_PAGING);return query;}@@ -2530,6 +2557,15 @@ async function resolvePostingGroupFilter(return { itemIds, filters: remaining };}+// The price list (`resolvePriceList`, `getBaseCatalog`) has no default order:+// without a sort it follows the item id. Its rows are computed per item, so+// a row's tie-breaker is `itemId`; the item query itself breaks ties on the+// item's own `id`, the same value.+export const PRICE_LIST_PAGING: Paging = {+ defaultSorts: [],+ idColumn: "itemId"+};+/** @mcp action */export async function resolvePriceList(client: SupabaseClient<Database>,@@ -2570,7 +2606,7 @@ export async function resolvePriceList(.from("item").select("id, readableId, name, thumbnailPath, itemUnitSalePrice(unitSalePrice), itemCost(itemPostingGroupId)",- { count: LIST_COUNT }+ { count: args.cursor ? undefined : LIST_COUNT }).eq("active", true).in("id", overriddenItemIds);@@ -2590,10 +2626,11 @@ export async function resolvePriceList(itemQuery = itemQuery.in("id", postingGroupItemIds);}- itemQuery = setGenericQueryFilters(itemQuery, {- ...args,- filters: filtersWithoutPostingGroup- });+ itemQuery = setGenericQueryFilters(+ itemQuery,+ { ...args, filters: filtersWithoutPostingGroup },+ PRICE_LIST_PAGING.defaultSorts+ );const { data: items, count } = await itemQuery;if (!items || items.length === 0) {@@ -2857,7 +2894,7 @@ export async function getBaseCatalog(.from("item").select("id, readableId, name, thumbnailPath, itemUnitSalePrice(unitSalePrice), itemCost(itemPostingGroupId)",- { count: LIST_COUNT }+ { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId).eq("active", true);@@ -2877,10 +2914,11 @@ export async function getBaseCatalog(query = query.in("id", postingGroupItemIds);}- query = setGenericQueryFilters(query, {- ...args,- filters: filtersWithoutPostingGroup- });+ query = setGenericQueryFilters(+ query,+ { ...args, filters: filtersWithoutPostingGroup },+ PRICE_LIST_PAGING.defaultSorts+ );const { data: items, count } = await query;if (!items || items.length === 0) {@@ -7045,6 +7083,10 @@ export async function updateSalesRFQLineOrder(// ─── Sales Return Orders (RMAs) ───+export const RETURN_REASONS_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getReturnReasons(client: SupabaseClient<Database>,@@ -7053,7 +7095,7 @@ export async function getReturnReasons() {let query = client.from("returnReason")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -7061,9 +7103,7 @@ export async function getReturnReasons(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, RETURN_REASONS_PAGING);}return query;@@ -7135,6 +7175,10 @@ export async function deleteReturnReason(return client.from("returnReason").delete().eq("id", returnReasonId);}+export const SALES_RETURN_ORDERS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getSalesReturnOrders(client: SupabaseClient<Database>,@@ -7147,7 +7191,7 @@ export async function getSalesReturnOrders() {let query = client.from("salesReturnOrders")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {@@ -7167,9 +7211,7 @@ export async function getSalesReturnOrders(query = query.eq("customerId", args.customerId);}- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, SALES_RETURN_ORDERS_PAGING);return query;}@@ -8639,6 +8681,10 @@ export async function createOpportunityLineDocumentUploadUrl(// the Draft-stage writes.// ----------------------------------------------------------------------+export const RENTAL_AGREEMENTS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getRentalAgreements(client: SupabaseClient<Database>,@@ -8649,7 +8695,7 @@ export async function getRentalAgreements() {let query = client.from("rentalAgreements")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {@@ -8658,9 +8704,7 @@ export async function getRentalAgreements();}- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, RENTAL_AGREEMENTS_PAGING);return query;}@@ -9649,6 +9693,10 @@ export async function getRentalAgreementRelatedDocuments(// carry their own guards and build every row from an explicit field picker.// ----------------------------------------------------------------------+export const CONTRACTS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/*** Lists contracts with their customer, value invoiced to date and next invoice date.* @mcp read@@ -9662,7 +9710,7 @@ export async function getContracts() {let query = client.from("customerContracts")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {@@ -9671,9 +9719,7 @@ export async function getContracts();}- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, CONTRACTS_PAGING);return query;}diff --git a/apps/erp/app/modules/sales/ui/Contracts/ContractsTable.tsx b/apps/erp/app/modules/sales/ui/Contracts/ContractsTable.tsxindex 97dad03842..d8f175fb00 100644--- a/apps/erp/app/modules/sales/ui/Contracts/ContractsTable.tsx+++ b/apps/erp/app/modules/sales/ui/Contracts/ContractsTable.tsx@@ -40,9 +40,12 @@ import type { ContractListItem } from "./types";type ContractsTableProps = {data: ContractListItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const ContractsTable = memo(({ data, count }: ContractsTableProps) => {+const ContractsTable = memo((props: ContractsTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const permissions = usePermissions();const navigate = useNavigate();@@ -242,6 +245,11 @@ const ContractsTable = memo(({ data, count }: ContractsTableProps) => {<><Table<ContractListItem>count={count}+ infinite={{+ dataKey: "contracts",+ nextCursor,+ listKey: "contracts"+ }}columns={columns}data={data}defaultColumnPinning={{diff --git a/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsTable.ee.tsx b/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsTable.ee.tsxindex d8e6e61a1f..0dfb580c69 100644--- a/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsTable.ee.tsx+++ b/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsTable.ee.tsx@@ -24,10 +24,12 @@ type CustomerPortalsTableProps = {appUrl: string;data: CustomerPortal[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const CustomerPortalsTable = memo(- ({ appUrl, data, count }: CustomerPortalsTableProps) => {+ ({ appUrl, data, count, nextCursor }: CustomerPortalsTableProps) => {const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -59,6 +61,8 @@ const CustomerPortalsTable = memo({accessorKey: "portalLink",header: t`Portal Link`,+ // The link is built from the id; `externalLink` has no such column to sort by.+ enableSorting: false,cell: ({ row }) => {const portalUrl = `${appUrl}/share/customer/${row.original.id}`;return (@@ -123,6 +127,11 @@ const CustomerPortalsTable = memo(data={data}columns={columns}count={count}+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "customer-portals"+ }}primaryAction={permissions.can("create", "sales") && (<Newdiff --git a/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsUpgradeOverlay.tsx b/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsUpgradeOverlay.tsxindex 985be00e8c..19d590d11f 100644--- a/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsUpgradeOverlay.tsx+++ b/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsUpgradeOverlay.tsx@@ -61,6 +61,7 @@ export default function CustomerPortalsUpgradeOverlay() {appUrl="https://app.carbon.ms"data={mockPortals}count={mockPortals.length}+ nextCursor={null}/></UpgradeOverlayPreview><UpgradeOverlayCard>diff --git a/apps/erp/app/modules/sales/ui/CustomerStatuses/CustomerStatusesTable.tsx b/apps/erp/app/modules/sales/ui/CustomerStatuses/CustomerStatusesTable.tsxindex 7e935406a6..1e4d8f6bd0 100644--- a/apps/erp/app/modules/sales/ui/CustomerStatuses/CustomerStatusesTable.tsx+++ b/apps/erp/app/modules/sales/ui/CustomerStatuses/CustomerStatusesTable.tsx@@ -19,10 +19,12 @@ import type { CustomerStatus } from "../../types";type CustomerStatusesTableProps = {data: CustomerStatus[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const CustomerStatusesTable = memo(- ({ data, count }: CustomerStatusesTableProps) => {+ ({ data, count, nextCursor }: CustomerStatusesTableProps) => {const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -96,6 +98,11 @@ const CustomerStatusesTable = memo(data={data}columns={columns}count={count}+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "customer-statuses"+ }}primaryAction={permissions.can("create", "sales") && (<Newdiff --git a/apps/erp/app/modules/sales/ui/CustomerTypes/CustomerTypesTable.tsx b/apps/erp/app/modules/sales/ui/CustomerTypes/CustomerTypesTable.tsxindex 7a1f9ad53a..4813e7503f 100644--- a/apps/erp/app/modules/sales/ui/CustomerTypes/CustomerTypesTable.tsx+++ b/apps/erp/app/modules/sales/ui/CustomerTypes/CustomerTypesTable.tsx@@ -19,9 +19,12 @@ import type { CustomerType } from "../../types";type CustomerTypesTableProps = {data: CustomerType[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const CustomerTypesTable = memo(({ data, count }: CustomerTypesTableProps) => {+const CustomerTypesTable = memo((props: CustomerTypesTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -96,6 +99,11 @@ const CustomerTypesTable = memo(({ data, count }: CustomerTypesTableProps) => {data={data}columns={columns}count={count}+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "customer-types"+ }}primaryAction={permissions.can("create", "sales") && (<Newdiff --git a/apps/erp/app/modules/sales/ui/Customers/CustomersTable.tsx b/apps/erp/app/modules/sales/ui/Customers/CustomersTable.tsxindex 98dd4ec481..53596b770c 100644--- a/apps/erp/app/modules/sales/ui/Customers/CustomersTable.tsx+++ b/apps/erp/app/modules/sales/ui/Customers/CustomersTable.tsx@@ -50,12 +50,20 @@ import type { Customer, CustomerStatus } from "../../types";type CustomersTableProps = {data: Customer[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;customerStatuses: CustomerStatus[];tags: { name: string }[];};const CustomersTable = memo(- ({ data, count, customerStatuses, tags }: CustomersTableProps) => {+ ({+ data,+ count,+ nextCursor,+ customerStatuses,+ tags+ }: CustomersTableProps) => {const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -311,6 +319,11 @@ const CustomersTable = memo(<><Table<Customer>count={count}+ infinite={{+ dataKey: "customers",+ nextCursor,+ listKey: "customers"+ }}columns={columns}data={data}defaultColumnPinning={{diff --git a/apps/erp/app/modules/sales/ui/NoQuoteReasons/NoQuoteReasonsTable.tsx b/apps/erp/app/modules/sales/ui/NoQuoteReasons/NoQuoteReasonsTable.tsxindex e52638f91e..7ba1ff94e6 100644--- a/apps/erp/app/modules/sales/ui/NoQuoteReasons/NoQuoteReasonsTable.tsx+++ b/apps/erp/app/modules/sales/ui/NoQuoteReasons/NoQuoteReasonsTable.tsx@@ -18,10 +18,12 @@ import type { NoQuoteReason } from "../../types";type NoQuoteReasonsTableProps = {data: NoQuoteReason[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const NoQuoteReasonsTable = memo(- ({ data, count }: NoQuoteReasonsTableProps) => {+ ({ data, count, nextCursor }: NoQuoteReasonsTableProps) => {const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -86,6 +88,11 @@ const NoQuoteReasonsTable = memo(data={data}columns={columns}count={count}+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "no-quote-reasons"+ }}primaryAction={permissions.can("create", "sales") && (<Newdiff --git a/apps/erp/app/modules/sales/ui/Pricing/PriceOverridesTable.tsx b/apps/erp/app/modules/sales/ui/Pricing/PriceOverridesTable.tsxindex 877604bdcd..32d11c4dd8 100644--- a/apps/erp/app/modules/sales/ui/Pricing/PriceOverridesTable.tsx+++ b/apps/erp/app/modules/sales/ui/Pricing/PriceOverridesTable.tsx@@ -58,6 +58,8 @@ import { type ScopeOption, ScopePicker } from "./ScopePicker";type PriceListTableProps = {data: PriceListRow[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;scopeOptions: ScopeOption[];hasScope: boolean;};@@ -74,7 +76,13 @@ const sourceVariant: Record<};const PriceListTable = memo(- ({ data, count, scopeOptions, hasScope }: PriceListTableProps) => {+ ({+ data,+ count,+ nextCursor,+ scopeOptions,+ hasScope+ }: PriceListTableProps) => {const { t } = useLingui();const permissions = usePermissions();const currencyFormatter = useCurrencyFormatter();@@ -137,6 +145,8 @@ const PriceListTable = memo({accessorKey: "partId",header: t`Item`,+ // The price list computes these values per item; the database cannot sort by them.+ enableSorting: false,cell: ({ row }) => (<HStack className="min-w-[240px] items-center" spacing={2}><ItemThumbnail@@ -170,6 +180,7 @@ const PriceListTable = memo({accessorKey: "itemPostingGroupId",header: t`Item Group`,+ enableSorting: false,cell: ({ row }) => {const id = row.original.itemPostingGroupId;if (!id) return null;@@ -191,6 +202,7 @@ const PriceListTable = memo({accessorKey: "basePrice",header: t`Base Price`,+ enableSorting: false,cell: ({ row }) => (<span className="text-muted-foreground">{currencyFormatter.format(row.original.basePrice)}@@ -208,6 +220,7 @@ const PriceListTable = memo({accessorKey: "resolvedPrice",header: t`Resolved Price`,+ enableSorting: false,cell: ({ row }) => (<HStack spacing={2} className="items-center"><span>@@ -232,6 +245,7 @@ const PriceListTable = memo({accessorKey: "source",header: t`Source`,+ enableSorting: false,cell: ({ row }) => (<Badge variant={sourceVariant[row.original.source] ?? "outline"}>{row.original.source}@@ -372,6 +386,11 @@ const PriceListTable = memo(data={data}columns={columns}count={count}+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "price-list"+ }}primaryAction={<div className="flex items-center gap-2"><ScopePickerdiff --git a/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx b/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsxindex 47141a7192..b7b102de66 100644--- a/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx+++ b/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx@@ -50,6 +50,8 @@ import type { PricingRule } from "../../types";type PricingRulesTableProps = {data: PricingRule[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const defaultColumnVisibility = {@@ -59,7 +61,8 @@ const defaultColumnVisibility = {itemPostingGroupId: false};-const PricingRulesTable = memo(({ data, count }: PricingRulesTableProps) => {+const PricingRulesTable = memo((props: PricingRulesTableProps) => {+ const { data, count, nextCursor } = props;const [params] = useUrlParams();const navigate = useNavigate();const { t } = useLingui();@@ -475,6 +478,11 @@ const PricingRulesTable = memo(({ data, count }: PricingRulesTableProps) => {data={data}columns={columns}count={count}+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "pricing-rules"+ }}defaultColumnVisibility={defaultColumnVisibility}primaryAction={canCreate && (diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsxindex 1821ed8e74..7f23acc4df 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx@@ -49,9 +49,11 @@ import QuoteStatus from "./QuoteStatus";type QuotesTableProps = {data: QuotationListItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const QuotesTable = memo(({ data, count }: QuotesTableProps) => {+const QuotesTable = memo(({ data, count, nextCursor }: QuotesTableProps) => {const { t } = useLingui();const permissions = usePermissions();const navigate = useNavigate();@@ -351,6 +353,11 @@ const QuotesTable = memo(({ data, count }: QuotesTableProps) => {<><Table<QuotationListItem>count={count}+ infinite={{+ dataKey: "quotes",+ nextCursor,+ listKey: "quotes"+ }}columns={columns}data={data}defaultColumnPinning={{diff --git a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementsTable.tsx b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementsTable.tsxindex 8d9bd54d91..10f240a107 100644--- a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementsTable.tsx+++ b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementsTable.tsx@@ -32,10 +32,12 @@ import type { RentalAgreementListItem } from "./types";type RentalAgreementsTableProps = {data: RentalAgreementListItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const RentalAgreementsTable = memo(- ({ data, count }: RentalAgreementsTableProps) => {+ ({ data, count, nextCursor }: RentalAgreementsTableProps) => {const { t } = useLingui();const permissions = usePermissions();const navigate = useNavigate();@@ -196,6 +198,11 @@ const RentalAgreementsTable = memo(<><Table<RentalAgreementListItem>count={count}+ infinite={{+ dataKey: "rentalAgreements",+ nextCursor,+ listKey: "rental-agreements"+ }}columns={columns}data={data}defaultColumnPinning={{diff --git a/apps/erp/app/modules/sales/ui/ReturnReasons/ReturnReasonsTable.tsx b/apps/erp/app/modules/sales/ui/ReturnReasons/ReturnReasonsTable.tsxindex a8d814c985..bc22e41b33 100644--- a/apps/erp/app/modules/sales/ui/ReturnReasons/ReturnReasonsTable.tsx+++ b/apps/erp/app/modules/sales/ui/ReturnReasons/ReturnReasonsTable.tsx@@ -25,9 +25,12 @@ type ReturnReason = Database["public"]["Tables"]["returnReason"]["Row"];type ReturnReasonsTableProps = {data: ReturnReason[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const ReturnReasonsTable = memo(({ data, count }: ReturnReasonsTableProps) => {+const ReturnReasonsTable = memo((props: ReturnReasonsTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -111,6 +114,11 @@ const ReturnReasonsTable = memo(({ data, count }: ReturnReasonsTableProps) => {data={data}columns={columns}count={count}+ infinite={{+ dataKey: "data",+ nextCursor,+ listKey: "return-reasons"+ }}primaryAction={permissions.can("create", "sales") && (<Newdiff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsxindex a4ad304e46..ad69827f0a 100644--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx@@ -75,6 +75,8 @@ import { useSalesOrder } from "./useSalesOrder";type SalesOrdersTableProps = {data: SalesOrderListItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const IconWithTooltip = ({@@ -96,7 +98,8 @@ const IconWithTooltip = ({</Tooltip>);-const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {+const SalesOrdersTable = memo((props: SalesOrdersTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const permissions = usePermissions();const currencyFormatter = useCurrencyFormatter();@@ -583,6 +586,11 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {count={count}columns={columns}data={data}+ infinite={{+ dataKey: "salesOrders",+ nextCursor,+ listKey: "sales-orders"+ }}defaultColumnPinning={{left: ["salesOrderId"]}}diff --git a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQsTable.tsx b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQsTable.tsxindex e656225bf4..905aa38da8 100644--- a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQsTable.tsx+++ b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQsTable.tsx@@ -45,9 +45,12 @@ import { SalesRFQStatus } from ".";type SalesRFQsTableProps = {data: SalesRFQ[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};-const SalesRFQsTable = memo(({ data, count }: SalesRFQsTableProps) => {+const SalesRFQsTable = memo((props: SalesRFQsTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const permissions = usePermissions();const navigate = useNavigate();@@ -275,6 +278,11 @@ const SalesRFQsTable = memo(({ data, count }: SalesRFQsTableProps) => {<><Table<SalesRFQ>count={count}+ infinite={{+ dataKey: "rfqs",+ nextCursor,+ listKey: "sales-rfqs"+ }}columns={columns}data={data}defaultColumnPinning={{diff --git a/apps/erp/app/modules/sales/ui/SalesReturnOrders/SalesReturnOrdersTable.tsx b/apps/erp/app/modules/sales/ui/SalesReturnOrders/SalesReturnOrdersTable.tsxindex fefc57b680..c5f253f6e9 100644--- a/apps/erp/app/modules/sales/ui/SalesReturnOrders/SalesReturnOrdersTable.tsx+++ b/apps/erp/app/modules/sales/ui/SalesReturnOrders/SalesReturnOrdersTable.tsx@@ -43,10 +43,12 @@ import type { SalesReturnOrderListItem } from "./types";type SalesReturnOrdersTableProps = {data: SalesReturnOrderListItem[];count: number;+ // The loader's cursor for the next page (infinite scroll).+ nextCursor: string | null;};const SalesReturnOrdersTable = memo(- ({ data, count }: SalesReturnOrdersTableProps) => {+ ({ data, count, nextCursor }: SalesReturnOrdersTableProps) => {const { t } = useLingui();const permissions = usePermissions();const navigate = useNavigate();@@ -228,6 +230,11 @@ const SalesReturnOrdersTable = memo(<><Table<SalesReturnOrderListItem>count={count}+ infinite={{+ dataKey: "salesReturnOrders",+ nextCursor,+ listKey: "sales-return-orders"+ }}columns={columns}data={data}defaultColumnPinning={{diff --git a/apps/erp/app/modules/settings/settings.server.ts b/apps/erp/app/modules/settings/settings.server.tsindex c6e6d8000d..f858d787a3 100644--- a/apps/erp/app/modules/settings/settings.server.ts+++ b/apps/erp/app/modules/settings/settings.server.ts@@ -716,8 +716,7 @@ type SyncOperationReference = {};/**- * The lookup key, built identically here and in `SyncActivity`'s- * `getEntityReference`.+ * The key of an operation in `getSyncOperationReadableIds`' result.*/function syncOperationReadableIdKey(operation: {entityType: string;@@ -859,3 +858,25 @@ export async function getSyncOperationReadableIds(return Object.fromEntries(results.flat());}++/**+ * Each operation with its `reference` (`getSyncOperationReadableIds`), or+ * null when it has none. Every page of the Sync Activity tab carries its own.+ */+export async function withSyncOperationReferences<+ T extends SyncOperationReference+>(+ client: SupabaseClient<Database>,+ companyId: string,+ operations: T[]+): Promise<(T & { reference: { label: string; recordId: string } | null })[]> {+ const readableIds = await getSyncOperationReadableIds(+ client,+ companyId,+ operations+ );+ return operations.map((operation) => ({+ ...operation,+ reference: readableIds[syncOperationReadableIdKey(operation)] ?? null+ }));+}diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex 17bda4fcea..2d004ba732 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -27,7 +27,7 @@ import { datetime } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";import type { plmReleaseControl as plmReleaseControlOptions } from "~/modules/items/items.models";-import type { GenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import { interpolateSequenceDate } from "~/utils/string";import { sanitize } from "~/utils/supabase";@@ -101,6 +101,10 @@ export async function deleteSubsidiary(return client.from("company").delete().eq("id", companyId);}+export const API_KEYS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: true }]+};+/*** @mcp read* @mcp permission users:update@@ -112,7 +116,7 @@ export async function getApiKeys() {let query = client.from("apiKey")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -120,9 +124,7 @@ export async function getApiKeys(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, API_KEYS_PAGING);}return query;@@ -331,6 +333,12 @@ export async function getCustomFields(.single();}+// The `customFieldTables` view has no `id`; one row is one table.+export const CUSTOM_FIELD_TABLES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }],+ idColumn: "table"+};+/** @mcp read */export async function getCustomFieldsTables(client: SupabaseClient<Database>,@@ -342,7 +350,7 @@ export async function getCustomFieldsTables(let query = client.from("customFieldTables").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -350,9 +358,7 @@ export async function getCustomFieldsTables(query = query.ilike("name", `%${args.search}%`);}- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, CUSTOM_FIELD_TABLES_PAGING);return query;}@@ -429,6 +435,10 @@ export async function getSequence(.single();}+export const SEQUENCES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getSequences(client: SupabaseClient<Database>,@@ -440,7 +450,7 @@ export async function getSequences(let query = client.from("sequence").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -448,9 +458,7 @@ export async function getSequences(query = query.ilike("name", `%${args.search}%`);}- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, SEQUENCES_PAGING);return query;}@@ -468,6 +476,10 @@ export async function getSequencesList(.order("table");}+export const ITEM_SERIAL_SEQUENCES_PAGING: Paging = {+ defaultSorts: [{ column: "itemReadableId", ascending: true }]+};+/** @mcp read */export async function getItemSerialSequences(client: SupabaseClient<Database>,@@ -479,7 +491,7 @@ export async function getItemSerialSequences(let query = client.from("itemSerialSequences").select("*", {- count: LIST_COUNT+ count: args.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -492,9 +504,7 @@ export async function getItemSerialSequences();}- query = setGenericQueryFilters(query, args, [- { column: "itemReadableId", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, ITEM_SERIAL_SEQUENCES_PAGING);return query;}@@ -811,6 +821,10 @@ export async function getWebhook(client: SupabaseClient<Database>, id: string) {return client.from("webhook").select("*").eq("id", id).single();}+export const WEBHOOKS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: true }]+};+/** @mcp read */export async function getWebhooks(client: SupabaseClient<Database>,@@ -820,7 +834,7 @@ export async function getWebhooks(let query = client.from("webhook").select("*", {- count: LIST_COUNT+ count: args?.cursor ? undefined : LIST_COUNT}).eq("companyId", companyId);@@ -829,9 +843,7 @@ export async function getWebhooks(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, WEBHOOKS_PAGING);}return query;diff --git a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsxindex ef2ed9f38e..66bdaa9c07 100644--- a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx+++ b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx@@ -31,14 +31,18 @@ import type { ApiKey } from "~/modules/settings";import { usePeople } from "~/stores";import { path } from "~/utils/path";+// The loader never sends the key hash to the browser.+type ApiKeyRow = Omit<ApiKey, "keyHash">;+type ApiKeysTableProps = {- data: ApiKey[];+ data: ApiKeyRow[];count: number;+ nextCursor: string | null;};// `apiKey.scopes` is a `Json` column; narrow it to the scope map shape once so// the cell and the CSV export read it the same way without an `as any` cast.-function getScopes(apiKey: ApiKey): Record<string, string[]> | null {+function getScopes(apiKey: ApiKeyRow): Record<string, string[]> | null {const { scopes } = apiKey;return scopes && typeof scopes === "object" && !Array.isArray(scopes)? (scopes as Record<string, string[]>)@@ -59,14 +63,15 @@ function formatRateLimit(limit: number, window: string): string {return `${limit}${windowLabels[window] ?? "/hr"}`;}-const ApiKeysTable = memo(({ data, count }: ApiKeysTableProps) => {+const ApiKeysTable = memo((props: ApiKeysTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const navigate = useNavigate();const [params] = useUrlParams();const permissions = usePermissions();const [people] = usePeople();- const columns = useMemo<ColumnDef<ApiKey>[]>(() => {+ const columns = useMemo<ColumnDef<ApiKeyRow>[]>(() => {return [{accessorKey: "name",@@ -224,8 +229,9 @@ const ApiKeysTable = memo(({ data, count }: ApiKeysTableProps) => {return (<>- <Table<ApiKey>+ <Table<ApiKeyRow>data={data}+ infinite={{ dataKey: "apiKeys", nextCursor, listKey: "api-keys" }}columns={columns}count={count ?? 0}primaryAction={diff --git a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysUpgradeOverlay.tsx b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysUpgradeOverlay.tsxindex a469cf24b5..710ca6ad39 100644--- a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysUpgradeOverlay.tsx+++ b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysUpgradeOverlay.tsx@@ -98,7 +98,11 @@ export default function ApiKeysUpgradeOverlay() {return (<UpgradeOverlay><UpgradeOverlayPreview>- <ApiKeysTable data={mockApiKeys} count={mockApiKeys.length} />+ <ApiKeysTable+ data={mockApiKeys}+ count={mockApiKeys.length}+ nextCursor={null}+ /></UpgradeOverlayPreview><UpgradeOverlayCard><UpgradeOverlayIcon>diff --git a/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsx b/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsxindex 9cd22d99a8..11414af5c4 100644--- a/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsx+++ b/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsx@@ -23,6 +23,7 @@ import { path } from "~/utils/path";type AuditLogTableProps = {entries: AuditLogEntry[];count: number;+ nextCursor: string | null;};const operationConfig: Record<@@ -121,7 +122,8 @@ const ExpandedRowContent = memo(({ entry }: { entry: AuditLogEntry }) => {});ExpandedRowContent.displayName = "ExpandedRowContent";-const AuditLogTable = memo(({ entries, count }: AuditLogTableProps) => {+const AuditLogTable = memo((props: AuditLogTableProps) => {+ const { entries, count, nextCursor } = props;const { t } = useLingui();const columns = useMemo<ColumnDef<AuditLogEntry>[]>(() => [@@ -255,6 +257,7 @@ const AuditLogTable = memo(({ entries, count }: AuditLogTableProps) => {table="auditLog"withSearchwithPagination+ infinite={{ dataKey: "entries", nextCursor }}renderExpandedRow={renderExpandedRow}/>);diff --git a/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsx b/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsxindex 107caf4ec7..a01566f280 100644--- a/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsx+++ b/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsx@@ -27,9 +27,11 @@ import { path } from "~/utils/path";type CustomFieldsTableProps = {data: CustomFieldsTableType[];count: number;+ nextCursor: string | null;};-const CustomFieldsTable = memo(({ data, count }: CustomFieldsTableProps) => {+const CustomFieldsTable = memo((props: CustomFieldsTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const navigate = useNavigate();const [params] = useUrlParams();@@ -139,6 +141,12 @@ const CustomFieldsTable = memo(({ data, count }: CustomFieldsTableProps) => {data={data}columns={columns}count={count ?? 0}+ infinite={{+ dataKey: "tables",+ nextCursor,+ listKey: "custom-field-tables"+ }}+ getRowId={(row) => String(row.table)}title={t`Custom Fields`}renderContextMenu={renderContextMenu}/>diff --git a/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx b/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsxindex 23a172f643..69e193ad5e 100644--- a/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx+++ b/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx@@ -34,8 +34,6 @@ import { useCallback, useMemo, useState } from "react";import {LuArrowDownLeft,LuArrowUpRight,- LuChevronLeft,- LuChevronRight,LuCircleSlash,LuDownload,LuRefreshCw,@@ -45,7 +43,11 @@ import {LuTriangleAlert} from "react-icons/lu";import { Link, useFetcher } from "react-router";+import { InfiniteStatus } from "~/components/Table/components/InfiniteStatus";+import { useInfiniteRows } from "~/components/Table/useInfiniteRows";+import { useInfiniteScroll } from "~/components/Table/useInfiniteScroll";import { useDateFormatter, usePermissions, useUrlParams } from "~/hooks";+import type { KeysetSort } from "~/utils/cursor";import { path } from "~/utils/path";/**@@ -88,6 +90,13 @@ export type SyncActivityOperation = {createdAt: string;updatedBy: string | null;updatedAt: string | null;+ /**+ * The document number a human reads (`PO000001`) plus the CARBON row id+ * to link to, resolved in the loader. Null on purpose for a pulled record+ * that never landed a Carbon row: it has only the PROVIDER's remote id,+ * and the row falls back to it.+ */+ reference: SyncOperationReference | null;};/**@@ -121,17 +130,10 @@ type SyncActivityProps = {/** The integration whose activity this is — scopes the CSV export. */integrationId: string;operations: SyncActivityOperation[];- /**- * `entityType:entityId` -> the document number a human reads- * (`PO000001`) plus the CARBON row id to link to, resolved in the loader.- * Sparse on purpose: a pulled record that never landed a Carbon row has- * only the PROVIDER's remote id, and those rows fall back to it.- */- readableIds?: Record<string, SyncOperationReference>;count: number;status: SyncOperationStatus | null;- page: number;- pageSize: number;+ /** The loader's cursor after the first page; null when it holds every row. */+ nextCursor: string | null;/*** Latest reconciliation report from the integration's metadata* (settings.postingSync.lastReconciliation). Rendered as a warning@@ -151,6 +153,14 @@ type SyncActivityProps = {} | null;};+/**+ * The order the tab pages in: newest first, `id` ascending on ties. The+ * cursor (`toPage`) follows it; `getSyncOperations` orders the same way.+ */+export const SYNC_ACTIVITY_SORTS: KeysetSort[] = [+ { column: "createdAt", ascending: false }+];+const STATUS_FILTERS: SyncOperationStatus[] = ["Pending","In Flight",@@ -229,18 +239,18 @@ type SyncOperationReference = { label: string; recordId: string };* number and the Carbon row when the loader resolved one, else the raw id* it stored.*/-function getEntityReference(- operation: SyncActivityOperation,- readableIds: Record<string, SyncOperationReference> | undefined-): { label: string; isReadable: boolean; path: string | null } {- const resolved =- readableIds?.[`${operation.entityType}:${operation.entityId}`];+function getEntityReference(operation: SyncActivityOperation): {+ label: string;+ isReadable: boolean;+ path: string | null;+} {+ const resolved = operation.reference;const pathFn = ENTITY_PATHS[operation.entityType];const recordId = resolved?.recordId ?? operation.entityId;return {label: resolved?.label ?? operation.entityId,- isReadable: resolved !== undefined,+ isReadable: resolved !== null,path: pathFn ? pathFn(recordId) : null};}@@ -273,11 +283,9 @@ export function SyncActivity({tabs,integrationId,operations,- readableIds,count,status,- page,- pageSize,+ nextCursor,lastReconciliation,tieOut}: SyncActivityProps) {@@ -312,46 +320,44 @@ export function SyncActivity({const setStatusFilter = useCallback((nextStatus: SyncOperationStatus | null) => {- setParams({- syncStatus: nextStatus ?? undefined,- syncPage: undefined- });+ setParams({ syncStatus: nextStatus ?? undefined });},[setParams]);- const setPage = useCallback(- (nextPage: number) => {- setParams({- syncPage: nextPage > 1 ? String(nextPage) : undefined- });- },- [setParams]- );+ // The first page comes from the loader; later pages load from the API+ // route as the drawer body scrolls to the end of the table.+ const syncRows = useInfiniteRows({+ initialRows: operations,+ infinite: {+ dataKey: "operations",+ nextCursor,+ pageUrl: path.to.api.integrationSyncActivity(integrationId, status),+ ignoreParams: ["tab"]+ }+ });+ const { rows, hasMore, loadError, retry } = syncRows;+ const endRef = useInfiniteScroll(syncRows, { root: "auto" });// Keep the detail drawer in sync with revalidated data: after a// transition the row's status updates (or the row leaves the current// filter, closing the drawer).const selectedOperation = useMemo(- () => operations.find((operation) => operation.id === selectedId) ?? null,- [operations, selectedId]+ () => rows.find((operation) => operation.id === selectedId) ?? null,+ [rows, selectedId]);const retryableIds = useMemo(() =>- operations+ rows.filter((operation) =>operation.status === "Failed" || operation.status === "Warning").map((operation) => operation.id),- [operations]+ [rows]);- const totalPages = Math.max(1, Math.ceil(count / pageSize));- const from = count === 0 ? 0 : (page - 1) * pageSize + 1;- const to = Math.min(count, (page - 1) * pageSize + operations.length);-return (<><DrawerBody className="gap-4">@@ -433,7 +439,7 @@ export function SyncActivity({</div><div className="w-full rounded-lg border border-border">- {operations.length === 0 ? (+ {rows.length === 0 ? (<div className="flex w-full items-center justify-center py-16 text-sm text-muted-foreground">{status ? (<Trans>No {status.toLowerCase()} sync operations</Trans>@@ -470,12 +476,9 @@ export function SyncActivity({</Tr></Thead><Tbody>- {operations.map((operation) => {+ {rows.map((operation) => {const transitions = getAvailableTransitions(operation.status);- const entityReference = getEntityReference(- operation,- readableIds- );+ const entityReference = getEntityReference(operation);return (<Trkey={operation.id}@@ -625,40 +628,31 @@ export function SyncActivity({)}</div>- <div className="flex w-full items-center justify-between">+ <div+ ref={endRef}+ className="flex w-full items-center justify-between gap-3"+ >+ <div>+ <InfiniteStatus+ isLoading={hasMore}+ loadError={loadError}+ onRetry={retry}+ />+ </div><p className="text-xs text-muted-foreground tabular-nums">{count === 0 ? (<Trans>0 operations</Trans>) : (<Trans>- {from}–{to} of {count} operations+ {rows.length} of {count} operations</Trans>)}</p>- <div className="flex items-center gap-1">- <IconButton- aria-label={t`Previous page`}- variant="ghost"- size="sm"- icon={<LuChevronLeft />}- isDisabled={page <= 1}- onClick={() => setPage(page - 1)}- />- <IconButton- aria-label={t`Next page`}- variant="ghost"- size="sm"- icon={<LuChevronRight />}- isDisabled={page >= totalPages}- onClick={() => setPage(page + 1)}- />- </div></div></DrawerBody><SyncOperationDetailDraweroperation={selectedOperation}- readableIds={readableIds}canUpdate={canUpdate}isTransitioning={isTransitioning}onTransition={submitTransition}@@ -865,14 +859,12 @@ function Detail({function SyncOperationDetailDrawer({operation,- readableIds,canUpdate,isTransitioning,onTransition,onClose}: {operation: SyncActivityOperation | null;- readableIds?: Record<string, SyncOperationReference>;canUpdate: boolean;isTransitioning: boolean;onTransition: (ids: string[], to: "Pending" | "Skipped") => void;@@ -884,7 +876,7 @@ function SyncOperationDetailDrawer({if (!operation) return null;const transitions = getAvailableTransitions(operation.status);- const entityReference = getEntityReference(operation, readableIds);+ const entityReference = getEntityReference(operation);const hasMetadata =operation.metadata && Object.keys(operation.metadata).length > 0;diff --git a/apps/erp/app/modules/settings/ui/Printing/PrintJobsTable.tsx b/apps/erp/app/modules/settings/ui/Printing/PrintJobsTable.tsxindex b3d505fca1..cf5e1f4143 100644--- a/apps/erp/app/modules/settings/ui/Printing/PrintJobsTable.tsx+++ b/apps/erp/app/modules/settings/ui/Printing/PrintJobsTable.tsx@@ -38,6 +38,7 @@ import { DateTime, Table } from "~/components";type PrintJobsTableProps = {jobs: PrintJob[];count: number;+ nextCursor: string | null;};type ViewContent = {@@ -235,7 +236,8 @@ function ZplPreview({ zpl }: { zpl: string }) {);}-const PrintJobsTable = memo(({ jobs, count }: PrintJobsTableProps) => {+const PrintJobsTable = memo((props: PrintJobsTableProps) => {+ const { jobs, count, nextCursor } = props;const { t } = useLingui();const fetcher = useFetcher<{success: boolean;@@ -443,6 +445,7 @@ const PrintJobsTable = memo(({ jobs, count }: PrintJobsTableProps) => {table="printJob"withSearchwithPagination+ infinite={{ dataKey: "jobs", nextCursor }}renderExpandedRow={renderExpandedRow}renderContextMenu={renderContextMenu}/>diff --git a/apps/erp/app/modules/settings/ui/Sequences/SequencesTable.tsx b/apps/erp/app/modules/settings/ui/Sequences/SequencesTable.tsxindex 367f4d423d..ed4721545f 100644--- a/apps/erp/app/modules/settings/ui/Sequences/SequencesTable.tsx+++ b/apps/erp/app/modules/settings/ui/Sequences/SequencesTable.tsx@@ -24,9 +24,11 @@ import { path } from "~/utils/path";type SequencesTableProps = {data: Sequence[];count: number;+ nextCursor: string | null;};-const SequencesTable = memo(({ data, count }: SequencesTableProps) => {+const SequencesTable = memo((props: SequencesTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -115,6 +117,7 @@ const SequencesTable = memo(({ data, count }: SequencesTableProps) => {return (<Table<(typeof data)[number]>data={data}+ infinite={{ dataKey: "data", nextCursor, listKey: "sequences" }}columns={columns}count={count}renderContextMenu={renderContextMenu}diff --git a/apps/erp/app/modules/settings/ui/SerialNumbers/ItemSerialSequencesTable.tsx b/apps/erp/app/modules/settings/ui/SerialNumbers/ItemSerialSequencesTable.tsxindex d8fc386af7..7adee42e27 100644--- a/apps/erp/app/modules/settings/ui/SerialNumbers/ItemSerialSequencesTable.tsx+++ b/apps/erp/app/modules/settings/ui/SerialNumbers/ItemSerialSequencesTable.tsx@@ -27,10 +27,11 @@ import { path } from "~/utils/path";type ItemSerialSequencesTableProps = {data: ItemSerialSequence[];count: number;+ nextCursor: string | null;};const ItemSerialSequencesTable = memo(- ({ data, count }: ItemSerialSequencesTableProps) => {+ ({ data, count, nextCursor }: ItemSerialSequencesTableProps) => {const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -149,6 +150,7 @@ const ItemSerialSequencesTable = memo(return (<Table<(typeof data)[number]>data={data}+ infinite={{ dataKey: "data", nextCursor, listKey: "serial-numbers" }}columns={columns}count={count}primaryAction={diff --git a/apps/erp/app/modules/settings/ui/Webhooks/WebhooksTable.tsx b/apps/erp/app/modules/settings/ui/Webhooks/WebhooksTable.tsxindex 762cf4c676..1e2a4aeacf 100644--- a/apps/erp/app/modules/settings/ui/Webhooks/WebhooksTable.tsx+++ b/apps/erp/app/modules/settings/ui/Webhooks/WebhooksTable.tsx@@ -58,9 +58,11 @@ import { useWebhookTables } from "./WebhookForm";type WebhooksTableProps = {data: Webhook[];count: number;+ nextCursor: string | null;};-const WebhooksTable = memo(({ data, count }: WebhooksTableProps) => {+const WebhooksTable = memo((props: WebhooksTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const navigate = useNavigate();const [params] = useUrlParams();@@ -208,6 +210,7 @@ const WebhooksTable = memo(({ data, count }: WebhooksTableProps) => {<><Table<Webhook>data={data}+ infinite={{ dataKey: "webhooks", nextCursor, listKey: "webhooks" }}columns={columns}count={count ?? 0}defaultColumnVisibility={{diff --git a/apps/erp/app/modules/settings/ui/Webhooks/WebhooksUpgradeOverlay.tsx b/apps/erp/app/modules/settings/ui/Webhooks/WebhooksUpgradeOverlay.tsxindex 318913c8a3..7c2208df28 100644--- a/apps/erp/app/modules/settings/ui/Webhooks/WebhooksUpgradeOverlay.tsx+++ b/apps/erp/app/modules/settings/ui/Webhooks/WebhooksUpgradeOverlay.tsx@@ -101,7 +101,11 @@ export default function WebhooksUpgradeOverlay() {return (<UpgradeOverlay><UpgradeOverlayPreview>- <WebhooksTable data={mockWebhooks} count={mockWebhooks.length} />+ <WebhooksTable+ data={mockWebhooks}+ count={mockWebhooks.length}+ nextCursor={null}+ /></UpgradeOverlayPreview><UpgradeOverlayCard><UpgradeOverlayIcon>diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.tsindex 975302d78a..79fd1070e6 100644--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@ -22,7 +22,7 @@ import type {PostgrestSingleResponse,SupabaseClient} from "@supabase/supabase-js";-import type { GenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import type {PriceBreak,@@ -305,6 +305,10 @@ export async function upsertExternalLink(.single();}+export const CUSTOMER_PORTALS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+/** @mcp read */export async function getCustomerPortals(client: SupabaseClient<Database>,@@ -313,7 +317,7 @@ export async function getCustomerPortals() {let query = client.from("externalLink")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId).eq("documentType", "Customer");@@ -322,9 +326,7 @@ export async function getCustomerPortals(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, CUSTOMER_PORTALS_PAGING);}return query;diff --git a/apps/erp/app/modules/users/ui/Customers/CustomerAccountsTable.tsx b/apps/erp/app/modules/users/ui/Customers/CustomerAccountsTable.tsxindex 82bf2926c6..5b56ca99da 100644--- a/apps/erp/app/modules/users/ui/Customers/CustomerAccountsTable.tsx+++ b/apps/erp/app/modules/users/ui/Customers/CustomerAccountsTable.tsx@@ -39,6 +39,8 @@ import { path } from "~/utils/path";type CustomerAccountsTableProps = {data: Customer[];count: number;+ // The loader read SINGLE_LOAD_LIMIT rows: more may match.+ isTruncated?: boolean;customerTypes: ListItem[];unrevokedInviteEmails: string[];};@@ -52,6 +54,7 @@ const CustomerAccountsTable = memo(({data,count,+ isTruncated,customerTypes,unrevokedInviteEmails}: CustomerAccountsTableProps) => {@@ -323,6 +326,7 @@ const CustomerAccountsTable = memo(<><Table<(typeof rows)[number]>count={count}+ isTruncated={isTruncated}columns={columns}data={rows}defaultColumnVisibility={defaultColumnVisibility}diff --git a/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesTable.ee.tsx b/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesTable.ee.tsxindex fceaaa8040..82551eaab3 100644--- a/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesTable.ee.tsx+++ b/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesTable.ee.tsx@@ -18,9 +18,11 @@ import { path } from "~/utils/path";type EmployeeTypesTableProps = {data: EmployeeType[];count: number;+ nextCursor: string | null;};-const EmployeeTypesTable = memo(({ data, count }: EmployeeTypesTableProps) => {+const EmployeeTypesTable = memo((props: EmployeeTypesTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();const [params] = useUrlParams();const navigate = useNavigate();@@ -92,6 +94,7 @@ const EmployeeTypesTable = memo(({ data, count }: EmployeeTypesTableProps) => {return (<Table<(typeof data)[number]>data={data}+ infinite={{ dataKey: "data", nextCursor, listKey: "employee-types" }}columns={columns}count={count}primaryAction={diff --git a/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesUpgradeOverlay.ee.tsx b/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesUpgradeOverlay.ee.tsxindex 6af2d64442..d67bd977b5 100644--- a/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesUpgradeOverlay.ee.tsx+++ b/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesUpgradeOverlay.ee.tsx@@ -49,6 +49,7 @@ export default function EmployeeTypesUpgradeOverlay() {<EmployeeTypesTabledata={mockEmployeeTypes}count={mockEmployeeTypes.length}+ nextCursor={null}/>}title={<Trans>Employee Types</Trans>}diff --git a/apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.ee.tsx b/apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.ee.tsxindex 5c1f7c9af4..6865f92a89 100644--- a/apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.ee.tsx+++ b/apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.ee.tsx@@ -19,6 +19,10 @@ import { Trans, useLingui } from "@lingui/react/macro";import { useEffect, useMemo } from "react";import { Employees, Hidden, Radios, Submit } from "~/components/Form";import PermissionMatrix from "~/components/PermissionMatrix";+import {+ type AllMatchingSelection,+ allMatchingRequest+} from "~/components/Table";import { usePermissions } from "~/hooks";import {fromEmployeeTypePermissions,@@ -26,18 +30,32 @@ import {usePermissionMatrix} from "~/hooks/usePermissionMatrix";import type { CompanyPermission } from "~/modules/users";-import { bulkPermissionsValidator } from "~/modules/users";+import {+ bulkPermissionsAllMatchingValidator,+ bulkPermissionsValidator+} from "~/modules/users";import { path } from "~/utils/path";+import {+ AllMatchingUsersNote,+ type BulkUserActionFetcher+} from "../components/AllMatchingUsers";type BulkEditPermissionsProps = {userIds: string[];isOpen: boolean;+ /** Set when the action applies to every matching user of the list. */+ allMatching?: AllMatchingSelection | null;+ /** Posts the every-matching-user request. The table owns it, so its result+ * toast still shows after this drawer closes. */+ allMatchingFetcher?: BulkUserActionFetcher;onClose: () => void;};const BulkEditPermissions = ({userIds,isOpen,+ allMatching,+ allMatchingFetcher,onClose}: BulkEditPermissionsProps) => {const { t } = useLingui();@@ -95,9 +113,16 @@ const BulkEditPermissions = ({><DrawerContent><ValidatedForm- validator={bulkPermissionsValidator}+ validator={+ allMatching+ ? bulkPermissionsAllMatchingValidator+ : bulkPermissionsValidator+ }method="post"action={path.to.bulkEditPermissions}+ // Every matching user runs in the background: the route answers+ // data, not a redirect, so it posts through a fetcher.+ fetcher={allMatching ? allMatchingFetcher : undefined}onSubmit={onClose}defaultValues={{ userIds }}className="flex flex-col h-full"@@ -127,11 +152,21 @@ const BulkEditPermissions = ({/></div>- <Employees- name="userIds"- selectionsMaxHeight={"calc(100vh - 330px)"}- label={t`Users to Update`}- />+ {allMatching ? (+ <>+ <AllMatchingUsersNote />+ <Hidden+ name="allMatching"+ value={JSON.stringify(allMatchingRequest(allMatching))}+ />+ </>+ ) : (+ <Employees+ name="userIds"+ selectionsMaxHeight={"calc(100vh - 330px)"}+ label={t`Users to Update`}+ />+ )}{hasModules && (<PermissionMatrixdiff --git a/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx b/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsxindex 4515ee4fc0..77a42b33c6 100644--- a/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx+++ b/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx@@ -34,21 +34,25 @@ import {import { useNavigate } from "react-router";import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";import { Enumerable } from "~/components/Enumerable";+import type { AllMatchingSelection, BulkActionScope } from "~/components/Table";import { usePermissions, useUrlParams, useUser } from "~/hooks";import { useSettings } from "~/hooks/useSettings";import type { Employee } from "~/modules/users";import {BulkEditPermissionsForm,+ canBulkActOnUser,DeactivateUsersModal,ResendInviteModal,RevokeInviteModal} from "~/modules/users";import type { ListItem } from "~/types";import { path } from "~/utils/path";+import { useBulkUserActionFetcher } from "../components/AllMatchingUsers";type EmployeesTableProps = {data: Employee[];count: number;+ nextCursor: string | null;employeeTypes: ListItem[];unrevokedInviteEmails: string[];mfaEnrolledUserIds: string[];@@ -63,6 +67,7 @@ const EmployeesTable = memo(({data,count,+ nextCursor,employeeTypes,unrevokedInviteEmails,mfaEnrolledUserIds@@ -96,6 +101,10 @@ const EmployeesTable = memo();const [selectedUserIds, setSelectedUserIds] = useState<string[]>([]);+ // Set when a bulk action applies to every matching user of the list.+ const [bulkAllMatching, setBulkAllMatching] =+ useState<AllMatchingSelection | null>(null);+ const allMatchingFetcher = useBulkUserActionFetcher();const bulkEditDrawer = useDisclosure();const deactivateEmployeeModal = useDisclosure();@@ -277,22 +286,34 @@ const EmployeesTable = memo(}, [params, mfaEnrolledSet, requireMfa]);const renderActions = useCallback(- (selectedRows: typeof data) => {+ (selectedRows: typeof data, scope?: BulkActionScope) => {+ // Every matching user: the background job applies the same rules+ // (`canBulkActOnUser`) to each matching row and skips the rest.+ const allMatching = scope?.allMatching ?? null;+ const rules = {+ actorId: currentUserId,+ unrevokedInviteEmails: unrevokedInviteSet+ };+ const usersFor = (action: "permissions" | "invite" | "deactivate") =>+ selectedRows+ .filter((row) => canBulkActOnUser(action, row, rules))+ .map((row) => row.id!);+ const open = (+ action: "permissions" | "invite" | "deactivate",+ onOpen: () => void+ ) => {+ setBulkAllMatching(allMatching);+ setSelectedUserIds(allMatching ? [] : usersFor(action));+ onOpen();+ };return (<DropdownMenuContent><DropdownMenuItemshortcut={MENU_ITEM_SHORTCUTS.edit}- onClick={() => {- setSelectedUserIds(- selectedRows- .filter((row) => row.active === true)- .map((row) => row.id!)- );- bulkEditDrawer.onOpen();- }}+ onClick={() => open("permissions", bulkEditDrawer.onOpen)}disabled={!permissions.can("update", "users") ||- selectedRows.every((row) => row.active === false)+ (!allMatching && usersFor("permissions").length === 0)}><LuShield className="mr-2 h-4 w-4" />@@ -301,27 +322,10 @@ const EmployeesTable = memo(</span></DropdownMenuItem><DropdownMenuItem- onClick={() => {- setSelectedUserIds(- selectedRows- .filter(- (row) =>- row.active === false &&- !!row.email &&- !unrevokedInviteSet.has(row.email)- )- .map((row) => row.id!)- );- resendInviteModal.onOpen();- }}+ onClick={() => open("invite", resendInviteModal.onOpen)}disabled={!permissions.can("create", "users") ||- !selectedRows.some(- (row) =>- row.active === false &&- !!row.email &&- !unrevokedInviteSet.has(row.email)- )+ (!allMatching && usersFor("invite").length === 0)}><LuMailCheck className="mr-2 h-4 w-4" />@@ -330,21 +334,10 @@ const EmployeesTable = memo(</span></DropdownMenuItem><DropdownMenuItem- onClick={() => {- setSelectedUserIds(- selectedRows- .filter(- (row) => row.active === true && row.id !== currentUserId- )- .map((row) => row.id!)- );- deactivateEmployeeModal.onOpen();- }}+ onClick={() => open("deactivate", deactivateEmployeeModal.onOpen)}disabled={!permissions.can("delete", "users") ||- !selectedRows.some(- (row) => row.active === true && row.id !== currentUserId- )+ (!allMatching && usersFor("deactivate").length === 0)}><LuBan className="mr-2 h-4 w-4" />@@ -472,6 +465,11 @@ const EmployeesTable = memo(count={count}columns={columns}data={data}+ infinite={{+ dataKey: "employees",+ nextCursor,+ listKey: "employee-accounts"+ }}defaultColumnVisibility={defaultColumnVisibility}primaryAction={permissions.can("create", "users") && (@@ -487,21 +485,36 @@ const EmployeesTable = memo(<BulkEditPermissionsFormuserIds={selectedUserIds}isOpen={bulkEditDrawer.isOpen}- onClose={bulkEditDrawer.onClose}+ allMatching={bulkAllMatching}+ allMatchingFetcher={allMatchingFetcher}+ onClose={() => {+ bulkEditDrawer.onClose();+ setBulkAllMatching(null);+ }}/>)}{deactivateEmployeeModal.isOpen && (<DeactivateUsersModaluserIds={selectedUserIds}isOpen={deactivateEmployeeModal.isOpen}- onClose={deactivateEmployeeModal.onClose}+ allMatching={bulkAllMatching}+ allMatchingFetcher={allMatchingFetcher}+ onClose={() => {+ deactivateEmployeeModal.onClose();+ setBulkAllMatching(null);+ }}/>)}{resendInviteModal.isOpen && (<ResendInviteModaluserIds={selectedUserIds}isOpen={resendInviteModal.isOpen}- onClose={resendInviteModal.onClose}+ allMatching={bulkAllMatching}+ allMatchingFetcher={allMatchingFetcher}+ onClose={() => {+ resendInviteModal.onClose();+ setBulkAllMatching(null);+ }}/>)}{revokeInviteModal.isOpen && (diff --git a/apps/erp/app/modules/users/ui/Groups/GroupsTable.tsx b/apps/erp/app/modules/users/ui/Groups/GroupsTable.tsxindex b2056257b3..c25aa2e007 100644--- a/apps/erp/app/modules/users/ui/Groups/GroupsTable.tsx+++ b/apps/erp/app/modules/users/ui/Groups/GroupsTable.tsx@@ -23,9 +23,11 @@ import { path } from "~/utils/path";type GroupsTableProps = {data: Group[];count: number;+ // The loader read SINGLE_LOAD_LIMIT rows: more may match.+ isTruncated?: boolean;};-const GroupsTable = memo(({ data, count }: GroupsTableProps) => {+const GroupsTable = memo(({ data, count, isTruncated }: GroupsTableProps) => {const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();@@ -143,6 +145,7 @@ const GroupsTable = memo(({ data, count }: GroupsTableProps) => {<Table<(typeof rows)[number]>data={rows}count={count}+ isTruncated={isTruncated}columns={columns}primaryAction={permissions.can("create", "users") && (diff --git a/apps/erp/app/modules/users/ui/Suppliers/SupplierAccountsTable/SuppliersAccountsTable.tsx b/apps/erp/app/modules/users/ui/Suppliers/SupplierAccountsTable/SuppliersAccountsTable.tsxindex 294518774d..9ba5b1b1c4 100644--- a/apps/erp/app/modules/users/ui/Suppliers/SupplierAccountsTable/SuppliersAccountsTable.tsx+++ b/apps/erp/app/modules/users/ui/Suppliers/SupplierAccountsTable/SuppliersAccountsTable.tsx@@ -39,6 +39,8 @@ import { path } from "~/utils/path";type SupplierAccountsTableProps = {data: Supplier[];count: number;+ // The loader read SINGLE_LOAD_LIMIT rows: more may match.+ isTruncated?: boolean;supplierTypes: ListItem[];unrevokedInviteEmails: string[];};@@ -52,6 +54,7 @@ const SupplierAccountsTable = memo(({data,count,+ isTruncated,supplierTypes,unrevokedInviteEmails}: SupplierAccountsTableProps) => {@@ -320,6 +323,7 @@ const SupplierAccountsTable = memo(<><Table<(typeof rows)[number]>count={count}+ isTruncated={isTruncated}columns={columns}data={rows}defaultColumnVisibility={defaultColumnVisibility}diff --git a/apps/erp/app/modules/users/ui/components/AllMatchingUsers.tsx b/apps/erp/app/modules/users/ui/components/AllMatchingUsers.tsxnew file mode 100644index 0000000000..9018344f33--- /dev/null+++ b/apps/erp/app/modules/users/ui/components/AllMatchingUsers.tsx@@ -0,0 +1,37 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { useAction } from "@carbon/query";+import { Trans } from "@lingui/react/macro";+import { useBulkStartToast } from "~/hooks/useBulkAction";+import type { BulkActionStart } from "~/utils/table-jobs";++/**+ * The fetcher an Employees bulk action posts "every matching user" through.+ * The route starts the background job and answers `{ background: true }`, or+ * `{ success: false, message }`. The table holds it, not the modal: the modal+ * closes on submit, and an unmounted fetcher never reports its result.+ */+export function useBulkUserActionFetcher() {+ const showBulkStart = useBulkStartToast();+ return useAction<BulkActionStart>({+ onSuccess: showBulkStart,+ onError: showBulkStart+ });+}++export type BulkUserActionFetcher = ReturnType<typeof useBulkUserActionFetcher>;++/** Stands in for the selected users in a bulk action's modal when the action+ * applies to every matching user. */+export function AllMatchingUsersNote() {+ return (+ <p className="text-sm text-muted-foreground">+ <Trans>+ Every user that matches the list's filters. Users this action does not+ apply to are skipped.+ </Trans>+ </p>+ );+}diff --git a/apps/erp/app/modules/users/ui/components/DeactivateUsersModal.tsx b/apps/erp/app/modules/users/ui/components/DeactivateUsersModal.tsxindex bbef44e284..09465bad8f 100644--- a/apps/erp/app/modules/users/ui/components/DeactivateUsersModal.tsx+++ b/apps/erp/app/modules/users/ui/components/DeactivateUsersModal.tsx@@ -15,13 +15,29 @@ import {} from "@carbon/react";import { Trans } from "@lingui/react/macro";import { UserSelect } from "~/components/Selectors";-import { deactivateUsersValidator } from "~/modules/users";+import {+ type AllMatchingSelection,+ allMatchingRequest+} from "~/components/Table";+import {+ deactivateUsersAllMatchingValidator,+ deactivateUsersValidator+} from "~/modules/users";import { path } from "~/utils/path";+import {+ AllMatchingUsersNote,+ type BulkUserActionFetcher+} from "./AllMatchingUsers";type DeactivateUsersModalProps = {userIds: string[];isOpen: boolean;redirectTo?: string;+ /** Set when the action applies to every matching user of the list. */+ allMatching?: AllMatchingSelection | null;+ /** Posts the every-matching-user request. The table owns it, so its result+ * toast still shows after this modal closes. */+ allMatchingFetcher?: BulkUserActionFetcher;onClose: () => void;};@@ -29,9 +45,11 @@ const DeactivateUsersModal = ({userIds,isOpen,redirectTo = path.to.employeeAccounts,+ allMatching,+ allMatchingFetcher,onClose}: DeactivateUsersModalProps) => {- const isSingleUser = userIds.length === 1;+ const isSingleUser = !allMatching && userIds.length === 1;return (<Modal@@ -58,7 +76,11 @@ const DeactivateUsersModal = ({<Trans>Are you sure you want to deactivate these users?</Trans>)}</p>- <UserSelect value={userIds} readOnly isMulti />+ {allMatching ? (+ <AllMatchingUsersNote />+ ) : (+ <UserSelect value={userIds} readOnly isMulti />+ )}</ModalBody><ModalFooter><HStack>@@ -68,10 +90,24 @@ const DeactivateUsersModal = ({<ValidatedFormmethod="post"action={path.to.deactivateUsers}- validator={deactivateUsersValidator}+ validator={+ allMatching+ ? deactivateUsersAllMatchingValidator+ : deactivateUsersValidator+ }+ // Every matching user runs in the background: the route+ // answers data, not a redirect, so it posts through a fetcher.+ fetcher={allMatching ? allMatchingFetcher : undefined}onSubmit={onClose}>- {userIds.map((id, index) => (+ {allMatching && (+ <input+ type="hidden"+ name="allMatching"+ value={JSON.stringify(allMatchingRequest(allMatching))}+ />+ )}+ {(allMatching ? [] : userIds).map((id, index) => (<inputkey={id}type="hidden"diff --git a/apps/erp/app/modules/users/ui/components/ResendInviteModal.tsx b/apps/erp/app/modules/users/ui/components/ResendInviteModal.tsxindex ad0b6e1969..4786312060 100644--- a/apps/erp/app/modules/users/ui/components/ResendInviteModal.tsx+++ b/apps/erp/app/modules/users/ui/components/ResendInviteModal.tsx@@ -16,22 +16,40 @@ import {import { Trans } from "@lingui/react/macro";import { useFetcher } from "react-router";import { UserSelect } from "~/components/Selectors";-import { resendInviteValidator } from "~/modules/users";+import {+ type AllMatchingSelection,+ allMatchingRequest+} from "~/components/Table";+import {+ resendInviteAllMatchingValidator,+ resendInviteValidator+} from "~/modules/users";import { path } from "~/utils/path";+import {+ AllMatchingUsersNote,+ type BulkUserActionFetcher+} from "./AllMatchingUsers";type ResendInviteModalProps = {userIds: string[];isOpen: boolean;+ /** Set when the action applies to every matching user of the list. */+ allMatching?: AllMatchingSelection | null;+ /** Posts the every-matching-user request. The table owns it, so its result+ * toast still shows after this modal closes. */+ allMatchingFetcher?: BulkUserActionFetcher;onClose: () => void;};const ResendInviteModal = ({userIds,isOpen,+ allMatching,+ allMatchingFetcher,onClose}: ResendInviteModalProps) => {const fetcher = useFetcher<{}>();- const isSingleUser = userIds.length === 1;+ const isSingleUser = !allMatching && userIds.length === 1;return (<Modal@@ -63,7 +81,11 @@ const ResendInviteModal = ({</Trans>)}</p>- <UserSelect value={userIds} readOnly isMulti />+ {allMatching ? (+ <AllMatchingUsersNote />+ ) : (+ <UserSelect value={userIds} readOnly isMulti />+ )}</ModalBody><ModalFooter><HStack>@@ -73,11 +95,22 @@ const ResendInviteModal = ({<ValidatedFormmethod="post"action={path.to.resendInvite}- validator={resendInviteValidator}+ validator={+ allMatching+ ? resendInviteAllMatchingValidator+ : resendInviteValidator+ }onSubmit={onClose}- fetcher={fetcher}+ fetcher={allMatching ? allMatchingFetcher : fetcher}>- {userIds.map((id, index) => (+ {allMatching && (+ <input+ type="hidden"+ name="allMatching"+ value={JSON.stringify(allMatchingRequest(allMatching))}+ />+ )}+ {(allMatching ? [] : userIds).map((id, index) => (<inputkey={id}type="hidden"diff --git a/apps/erp/app/modules/users/ui/components/index.ts b/apps/erp/app/modules/users/ui/components/index.tsindex 6c3fad5503..c8e785c389 100644--- a/apps/erp/app/modules/users/ui/components/index.ts+++ b/apps/erp/app/modules/users/ui/components/index.ts@@ -2,8 +2,20 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import {+ AllMatchingUsersNote,+ type BulkUserActionFetcher,+ useBulkUserActionFetcher+} from "./AllMatchingUsers";import DeactivateUsersModal from "./DeactivateUsersModal";import ResendInviteModal from "./ResendInviteModal";import RevokeInviteModal from "./RevokeInviteModal";-export { DeactivateUsersModal, ResendInviteModal, RevokeInviteModal };+export type { BulkUserActionFetcher };+export {+ AllMatchingUsersNote,+ DeactivateUsersModal,+ ResendInviteModal,+ RevokeInviteModal,+ useBulkUserActionFetcher+};diff --git a/apps/erp/app/modules/users/users.models.test.ts b/apps/erp/app/modules/users/users.models.test.tsnew file mode 100644index 0000000000..b05950014b--- /dev/null+++ b/apps/erp/app/modules/users/users.models.test.ts@@ -0,0 +1,53 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { canBulkActOnUser } from "./users.models";++const context = {+ actorId: "me",+ unrevokedInviteEmails: new Set(["[email protected]"])+};++const user = (+ id: string,+ active: boolean | null,+ email: string | null = `${id}@example.com`+) => ({ id, active, email });++describe("canBulkActOnUser", () => {+ it("edits the permissions of active users only", () => {+ expect(canBulkActOnUser("permissions", user("a", true), context)).toBe(+ true+ );+ expect(canBulkActOnUser("permissions", user("b", false), context)).toBe(+ false+ );+ });++ it("deactivates active users other than the actor", () => {+ expect(canBulkActOnUser("deactivate", user("a", true), context)).toBe(true);+ expect(canBulkActOnUser("deactivate", user("me", true), context)).toBe(+ false+ );+ expect(canBulkActOnUser("deactivate", user("b", false), context)).toBe(+ false+ );+ });++ it("invites inactive users with an email and no unrevoked invite", () => {+ expect(canBulkActOnUser("invite", user("a", false), context)).toBe(true);+ expect(canBulkActOnUser("invite", user("a", true), context)).toBe(false);+ expect(canBulkActOnUser("invite", user("a", false, null), context)).toBe(+ false+ );+ expect(+ canBulkActOnUser(+ "invite",+ user("p", false, "[email protected]"),+ context+ )+ ).toBe(false);+ });+});diff --git a/apps/erp/app/modules/users/users.models.ts b/apps/erp/app/modules/users/users.models.tsindex bfa9fa443b..ab0632833e 100644--- a/apps/erp/app/modules/users/users.models.ts+++ b/apps/erp/app/modules/users/users.models.ts@@ -190,3 +190,48 @@ export const userFlagValidator = z.object({});export const userFlagsValidator = z.record(userFlagKeyValidator, z.boolean());++// "Every matching row" in place of the selected users: the list and its URL+// search as JSON (`allMatchingRequest`, `~/components/Table`).+const allMatchingField = z.string().min(1, { message: "Invalid selection" });++export const bulkPermissionsAllMatchingValidator = bulkPermissionsValidator+ .omit({ userIds: true })+ .extend({ allMatching: allMatchingField });++export const deactivateUsersAllMatchingValidator = deactivateUsersValidator+ .omit({ users: true })+ .extend({ allMatching: allMatchingField });++export const resendInviteAllMatchingValidator = z.object({+ allMatching: allMatchingField+});++/** The Employees table's bulk actions on users. */+export type BulkUserAction = "deactivate" | "invite" | "permissions";++/**+ * Whether a bulk action on the Employees table acts on this user: the rule+ * the table applies to its selection, and the background job to every+ * matching row. Edit Permissions takes active users, Deactivate active users+ * other than the actor, and Send Invite inactive users with an email and no+ * unrevoked invite.+ */+export function canBulkActOnUser(+ action: BulkUserAction,+ user: { id: string | null; active: boolean | null; email: string | null },+ context: { actorId: string; unrevokedInviteEmails: ReadonlySet<string> }+): boolean {+ switch (action) {+ case "permissions":+ return user.active === true;+ case "deactivate":+ return user.active === true && user.id !== context.actorId;+ case "invite":+ return (+ user.active === false &&+ !!user.email &&+ !context.unrevokedInviteEmails.has(user.email)+ );+ }+}diff --git a/apps/erp/app/modules/users/users.server.ts b/apps/erp/app/modules/users/users.server.tsindex f595090500..2cb50a7e07 100644--- a/apps/erp/app/modules/users/users.server.ts+++ b/apps/erp/app/modules/users/users.server.ts@@ -28,13 +28,22 @@ import {seedSsoIdentityForUser,uncoveredSsoDomainError} from "@carbon/ee/sso.server";+import { batchTrigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";-import { redirect } from "@carbon/utils";+import { chunkArray, redirect } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { getSupplierContact } from "~/modules/purchasing";import { getCustomerContact } from "~/modules/sales";-import type { EmployeeInsert, InviteInsert, User } from "~/modules/users";-import { getPermissionsByEmployeeType } from "~/modules/users";+import type {+ BulkUserAction,+ EmployeeInsert,+ InviteInsert,+ User+} from "~/modules/users";+import {+ canBulkActOnUser,+ getPermissionsByEmployeeType+} from "~/modules/users";import { getDatabaseClient } from "~/services/database.server";import { path } from "~/utils/path";import { insertEmployeeJob } from "../people/people.service";@@ -1375,3 +1384,144 @@ async function setUserPermissions(return result;}++// --- Bulk actions of the Employees table --------------------------------+// The action routes call the `queue*` functions with the selected users; the+// background bulk-action job (`~/utils/table-jobs.server`) first narrows each+// chunk of matching users with `selectUsersForBulkAction`, then calls them.++/** Queues the `user-admin` deactivate job for each user. */+export async function queueUserDeactivations(args: {+ userIds: string[];+ companyId: string;+ actorId: string;+ ip?: string;+}) {+ await batchTrigger(+ "user-admin",+ args.userIds.map((id) => ({+ payload: {+ id,+ type: "deactivate" as const,+ companyId: args.companyId,+ actorId: args.actorId,+ ip: args.ip+ }+ }))+ );+}++/** Queues the `user-admin` resend-invite job for each user. */+export async function queueInviteResends(args: {+ userIds: string[];+ companyId: string;+ location: string;+ ip: string;+}) {+ await batchTrigger(+ "user-admin",+ args.userIds.map((id) => ({+ payload: {+ id,+ type: "resend" as const,+ companyId: args.companyId,+ location: args.location,+ ip: args.ip+ }+ }))+ );+}++/** Queues the `update-permissions` job for each user. */+export async function queuePermissionUpdates(args: {+ userIds: string[];+ companyId: string;+ actorId: string;+ permissions: Record<+ string,+ { view: boolean; create: boolean; update: boolean; delete: boolean }+ >;+ addOnly: boolean;+ ip?: string;+}) {+ await batchTrigger(+ "update-permissions",+ args.userIds.map((id) => ({+ payload: {+ id,+ permissions: args.permissions,+ addOnly: args.addOnly,+ companyId: args.companyId,+ actorId: args.actorId,+ ip: args.ip+ }+ }))+ );+}++/**+ * The users a bulk action on the Employees table may act on, from the ids+ * the background job read from the list: employees of the company only, by+ * the table's own rule (`canBulkActOnUser`). Reads with the service role, as+ * the action routes and the jobs they queue do, always scoped to the company.+ */+export async function selectUsersForBulkAction(args: {+ action: BulkUserAction;+ userIds: string[];+ companyId: string;+ actorId: string;+}): Promise<{ allowed: string[]; skipped: number }> {+ const serviceRole = getCarbonServiceRole();+ const ids = [...new Set(args.userIds)];+ const rows: {+ id: string | null;+ active: boolean | null;+ email: string | null;+ }[] = [];+ for (const chunk of chunkArray(ids, 100)) {+ const employees = await serviceRole+ .from("employees")+ .select("id, active, email")+ .in("id", chunk)+ .eq("companyId", args.companyId);+ if (employees.error) {+ logger.error("Failed to load the users of a bulk action", {+ companyId: args.companyId,+ error: employees.error+ });+ throw new Error("Failed to load the users of a bulk action");+ }+ rows.push(...employees.data);+ }++ let unrevokedInviteEmails = new Set<string>();+ if (args.action === "invite") {+ const emails = rows.flatMap((row) => (row.email ? [row.email] : []));+ for (const chunk of chunkArray(emails, 100)) {+ const invites = await serviceRole+ .from("invite")+ .select("email")+ .in("email", chunk)+ .eq("companyId", args.companyId)+ .is("acceptedAt", null)+ .is("revokedAt", null);+ if (invites.error) {+ logger.error("Failed to load the invites of a bulk action", {+ companyId: args.companyId,+ error: invites.error+ });+ throw new Error("Failed to load the invites of a bulk action");+ }+ unrevokedInviteEmails = new Set([+ ...unrevokedInviteEmails,+ ...invites.data.map((invite) => invite.email)+ ]);+ }+ }++ const context = { actorId: args.actorId, unrevokedInviteEmails };+ const allowed = rows+ .filter((row) => canBulkActOnUser(args.action, row, context))+ .flatMap((row) => (row.id ? [row.id] : []));+ return { allowed, skipped: ids.length - allowed.length };+}diff --git a/apps/erp/app/modules/users/users.service.ts b/apps/erp/app/modules/users/users.service.tsindex a9fbb8c3a0..4a35d00414 100644--- a/apps/erp/app/modules/users/users.service.ts+++ b/apps/erp/app/modules/users/users.service.ts@@ -7,7 +7,7 @@ import { fetchAllFromTable } from "@carbon/database";import { getLogger } from "@carbon/logger";import { datetime } from "@carbon/utils";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";-import type { GenericQueryFilters } from "~/utils/query";+import type { GenericQueryFilters, Paging } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import type { UserSelectGroupMembers } from "./types";@@ -251,6 +251,10 @@ export async function getUsersWithVerifiedMfa(return client.rpc("users_with_verified_mfa", { company_id: companyId });}+export const EMPLOYEES_PAGING: Paging = {+ defaultSorts: [{ column: "lastName", ascending: true }]+};+/** @mcp read */export async function getEmployees(client: SupabaseClient<Database>,@@ -261,7 +265,7 @@ export async function getEmployees() {let query = client.from("employees")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args.search) {@@ -277,12 +281,14 @@ export async function getEmployees(query = query.in("status", ["Active", "Invited"]);}- query = setGenericQueryFilters(query, args, [- { column: "lastName", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, EMPLOYEES_PAGING);return query;}+export const CONSOLE_OPERATORS_PAGING: Paging = {+ defaultSorts: [{ column: "lastName", ascending: true }]+};+/*** Gets console operators — users with @console.internal emails.* Uses the employees view (which joins user + employee) and filters@@ -302,7 +308,7 @@ export async function getConsoleOperators() {let query = client.from("employees")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId).like("email", "%@console.internal");@@ -310,9 +316,7 @@ export async function getConsoleOperators(query = query.ilike("name", `%${args.search}%`);}- query = setGenericQueryFilters(query, args, [- { column: "lastName", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, CONSOLE_OPERATORS_PAGING);return query;}@@ -328,6 +332,10 @@ export async function getEmployeeType(.single();}+export const EMPLOYEE_TYPES_PAGING: Paging = {+ defaultSorts: [{ column: "name", ascending: true }]+};+/** @mcp read */export async function getEmployeeTypes(client: SupabaseClient<Database>,@@ -336,7 +344,7 @@ export async function getEmployeeTypes() {let query = client.from("employeeType")- .select("*", { count: LIST_COUNT })+ .select("*", { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args?.search) {@@ -344,9 +352,7 @@ export async function getEmployeeTypes(}if (args) {- query = setGenericQueryFilters(query, args, [- { column: "name", ascending: true }- ]);+ query = setGenericQueryFilters(query, args, EMPLOYEE_TYPES_PAGING);}return query;diff --git a/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunsTable.tsx b/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunsTable.tsxindex 01421c4d9a..c325217b70 100644--- a/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunsTable.tsx+++ b/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunsTable.tsx@@ -29,9 +29,11 @@ export type WorkflowRunListItem = WorkflowRun & { recordName?: string };type WorkflowRunsTableProps = {data: WorkflowRunListItem[];count: number;+ nextCursor: string | null;};-const WorkflowRunsTable = memo(({ data, count }: WorkflowRunsTableProps) => {+const WorkflowRunsTable = memo((props: WorkflowRunsTableProps) => {+ const { data, count, nextCursor } = props;const { t } = useLingui();// A fresh closure each render, so the columns memo reads it through a ref rather than// rebuilding every column on every render.@@ -163,6 +165,7 @@ const WorkflowRunsTable = memo(({ data, count }: WorkflowRunsTableProps) => {{hasInFlight && <RunsLiveUpdates />}<Table<WorkflowRunListItem>data={data}+ infinite={{ dataKey: "data", nextCursor, listKey: "workflow-runs" }}columns={columns}count={count}title={t`Runs`}diff --git a/apps/erp/app/modules/workflows/ui/WorkflowsTable.tsx b/apps/erp/app/modules/workflows/ui/WorkflowsTable.tsxindex c66451c15f..70e55ee48e 100644--- a/apps/erp/app/modules/workflows/ui/WorkflowsTable.tsx+++ b/apps/erp/app/modules/workflows/ui/WorkflowsTable.tsx@@ -42,16 +42,22 @@ import type { Workflow, WorkflowLastRun } from "../workflows.service";import { ConfirmUnpublishWorkflow } from "./ConfirmUnpublishWorkflow";import { RunStatus } from "./Runs/RunStatus";import WorkflowForm from "./WorkflowForm";+import { WORKFLOW_LIST_EXPORT_VALUES } from "./workflow-list-export";++// A row of the list, with the values the loader adds per page.+type WorkflowRow = Workflow & {+ publishedVersionNumber: number | null;+ lastRun: WorkflowLastRun | null;+};type WorkflowsTableProps = {- data: Workflow[];+ data: WorkflowRow[];count: number;- versionNumbers: Record<string, number>;- lastRuns: Record<string, WorkflowLastRun>;+ nextCursor: string | null;};const WorkflowsTable = memo(- ({ data, count, versionNumbers, lastRuns }: WorkflowsTableProps) => {+ ({ data, count, nextCursor }: WorkflowsTableProps) => {const navigate = useNavigate();const { t } = useLingui();const permissions = usePermissions();@@ -64,7 +70,12 @@ const WorkflowsTable = memo(null);- const columns = useMemo<ColumnDef<Workflow>[]>(+ const infinite = useMemo(+ () => ({ dataKey: "data", nextCursor, listKey: "workflows" }),+ [nextCursor]+ );++ const columns = useMemo<ColumnDef<WorkflowRow>[]>(() => [{accessorKey: "name",@@ -118,7 +129,7 @@ const WorkflowsTable = memo({ value: "Draft", label: t`Draft` }]},- exportValue: (row: Workflow) =>+ exportValue: (row: WorkflowRow) =>row.publishedVersionId ? "Published" : "Draft"}},@@ -143,10 +154,7 @@ const WorkflowsTable = memo(accessorKey: "publishedVersionId",header: t`Published Version`,cell: ({ row }) => {- const versionId = row.original.publishedVersionId;- const versionNumber = versionId- ? versionNumbers[versionId]- : undefined;+ const versionNumber = row.original.publishedVersionNumber;return versionNumber ? (<Badge variant="outline">v{versionNumber}</Badge>) : (@@ -159,7 +167,7 @@ const WorkflowsTable = memo(id: "lastRun",header: t`Last Run`,cell: ({ row }) => {- const lastRun = lastRuns[row.original.id];+ const lastRun = row.original.lastRun;if (!lastRun?.runId || !lastRun.status) return "—";const ts = lastRun.completedAt ?? lastRun.createdAt;return (@@ -179,7 +187,7 @@ const WorkflowsTable = memo(meta: {icon: <LuHistory />,filterHeader: t`Last Run`,- exportValue: (row: Workflow) => lastRuns[row.id]?.status ?? ""+ exportValue: WORKFLOW_LIST_EXPORT_VALUES.lastRun}},{@@ -192,11 +200,11 @@ const WorkflowsTable = memo(meta: { icon: <LuCalendar /> }}],- [t, versionNumbers, lastRuns, people]+ [t, people]);const renderContextMenu = useCallback(- (row: Workflow) => (+ (row: WorkflowRow) => (<><MenuItemshortcut={MENU_ITEM_SHORTCUTS.open}@@ -254,8 +262,9 @@ const WorkflowsTable = memo(return (<>- <Table<Workflow>+ <Table<WorkflowRow>data={data}+ infinite={infinite}columns={columns}count={count}primaryAction={diff --git a/apps/erp/app/modules/workflows/ui/workflow-list-export.ts b/apps/erp/app/modules/workflows/ui/workflow-list-export.tsnew file mode 100644index 0000000000..157fbbb9d1--- /dev/null+++ b/apps/erp/app/modules/workflows/ui/workflow-list-export.ts@@ -0,0 +1,14 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++/**+ * The Workflows table columns whose values the loader adds to each page's+ * rows, by column id. The table exports them with these, and the background+ * CSV export writes the same values (`workflowsList.exportRows`).+ */+type Row = { lastRun?: { status?: string | null } | null };++export const WORKFLOW_LIST_EXPORT_VALUES = {+ lastRun: (row: Row) => row.lastRun?.status ?? ""+} satisfies Record<string, (row: Row) => string>;diff --git a/apps/erp/app/modules/workflows/workflows.service.ts b/apps/erp/app/modules/workflows/workflows.service.tsindex 6014255e41..2d7cfcbb4b 100644--- a/apps/erp/app/modules/workflows/workflows.service.ts+++ b/apps/erp/app/modules/workflows/workflows.service.ts@@ -7,10 +7,14 @@ import { fkDisplayRegistry } from "@carbon/database/audit.config";import { datetime } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import type { z } from "zod";-import type { Filter, GenericQueryFilters } from "~/utils/query";+import type { Filter, GenericQueryFilters, Paging } from "~/utils/query";import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";import type { workflowValidator } from "./workflows.models";+export const WORKFLOWS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+export async function getWorkflows(client: SupabaseClient<Database>,companyId: string,@@ -20,7 +24,7 @@ export async function getWorkflows(.from("workflow").select("id, name, description, ownerId, publishedVersionId, createdAt, updatedAt",- { count: LIST_COUNT }+ { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);@@ -47,9 +51,11 @@ export async function getWorkflows(}}- query = setGenericQueryFilters(query, { ...args, filters: columnFilters }, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(+ query,+ { ...args, filters: columnFilters },+ WORKFLOWS_PAGING+ );}return query;@@ -287,6 +293,10 @@ export async function deleteWorkflow(.eq("companyId", companyId);}+export const WORKFLOW_RUNS_PAGING: Paging = {+ defaultSorts: [{ column: "createdAt", ascending: false }]+};+export async function getWorkflowRuns(client: SupabaseClient<Database>,companyId: string,@@ -298,14 +308,12 @@ export async function getWorkflowRuns("id, workflowId, workflowVersionId, eventId, sourceEventId, triggerTable, triggerRecordId, ownerId, status, statusReason, isTest, rootRunId, causedByRunId, depth, path, startedAt, completedAt, durationMs, error, createdAt, workflow(name)",// Estimated, not exact: this table grows with event volume, and `exact` is a// COUNT(*) over the company's whole retained history on every page load.- { count: LIST_COUNT }+ { count: args?.cursor ? undefined : LIST_COUNT }).eq("companyId", companyId);if (args) {- query = setGenericQueryFilters(query, args, [- { column: "createdAt", ascending: false }- ]);+ query = setGenericQueryFilters(query, args, WORKFLOW_RUNS_PAGING);}return query;diff --git a/apps/erp/app/routes/api+/inngest.ts b/apps/erp/app/routes/api+/inngest.tsindex 35aa2d832a..af2a77e80e 100644--- a/apps/erp/app/routes/api+/inngest.ts+++ b/apps/erp/app/routes/api+/inngest.ts@@ -3,7 +3,12 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { getCarbonServiceRole } from "@carbon/auth/client.server";-import { functions, inngest, setWorkflowDispatch } from "@carbon/jobs/inngest";+import {+ functions,+ inngest,+ setTableJobHandlers,+ setWorkflowDispatch+} from "@carbon/jobs/inngest";import { getLogger } from "@carbon/logger";import { describeRequest } from "@carbon/logger/middleware.server";import {@@ -12,6 +17,7 @@ import {} from "@carbon/logger/tracing.server";import { serve } from "inngest/remix";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { tableJobHandlers } from "~/utils/table-jobs.server";import { callOperation } from "./v1+/lib/call.server";const logger = getLogger("erp", "inngest");@@ -32,7 +38,8 @@ const functionIds = new Set(}));-// packages/jobs cannot import ~/modules, so the ERP app hands it the dispatcher.+// packages/jobs cannot import ~/modules, so the ERP app hands it the dispatcher+// and the table-job handlers (list registry reads for exports and bulk actions).// Wired on first request rather than at module scope: a top-level side effect is// not removable by the client build, which would drag the server-only jobs graph// into the browser bundle.@@ -44,6 +51,7 @@ function wireWorkflowDispatch() {setWorkflowDispatch((name, context, args) =>callOperation(name, { ...context, authKind: "session", scopes: {} }, args));+ setTableJobHandlers(tableJobHandlers);dispatchWired = true;}diff --git a/apps/erp/app/routes/api+/integrations.$id.sync-activity.ts b/apps/erp/app/routes/api+/integrations.$id.sync-activity.tsnew file mode 100644index 0000000000..09690e5ed5--- /dev/null+++ b/apps/erp/app/routes/api+/integrations.$id.sync-activity.ts@@ -0,0 +1,79 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { requirePermissions } from "@carbon/auth/auth.server";+import { integrations as availableIntegrations } from "@carbon/ee";+import {+ getSyncOperations,+ SyncOperationStatusSchema+} from "@carbon/ee/accounting";+import { getLogger } from "@carbon/logger";+import type { LoaderFunctionArgs } from "react-router";+import { withSyncOperationReferences } from "~/modules/settings/settings.server";+import { SYNC_ACTIVITY_SORTS } from "~/modules/settings/ui/Integrations/SyncActivity";+import { decodeCursor, toPage } from "~/utils/cursor";+import { listErrorPage } from "~/utils/list-registry/list-error";+import { PAGE_SIZE } from "~/utils/pagination";++const logger = getLogger("erp", "integrations-sync-activity");++/**+ * GET — the Sync Activity rows after `?after=` (the previous page's last row),+ * under the tab's status filter (`?status=`). The Sync Activity tab loads+ * them as it scrolls (`useInfiniteRows` with this URL as its `pageUrl`), and+ * re-reads the loaded pages after a revalidation. Gated like the tab itself.+ */+export async function loader({ request, params }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ update: "settings"+ });++ const integration = availableIntegrations.find(+ (candidate) => candidate.id === params.id+ );+ if (!integration) {+ throw new Response("Integration not found", { status: 404 });+ }++ const searchParams = new URL(request.url).searchParams;+ const status = SyncOperationStatusSchema.safeParse(+ searchParams.get("status")+ );+ const cursor = decodeCursor(searchParams.get("after"));+ const createdAt = cursor?.values[0];+ if (!cursor || typeof createdAt !== "string") {+ // A failed page, not a thrown response: the tab shows its own retry+ // row, where a thrown response would replace the page.+ logger.warn("Sync activity page cursor is not valid", { companyId });+ return listErrorPage("operations");+ }++ // One extra row tells whether a next page exists.+ const operations = await getSyncOperations(client, {+ companyId,+ integration: integration.id,+ status: status.success ? status.data : undefined,+ after: { createdAt, id: cursor.id },+ limit: PAGE_SIZE + 1+ });++ if (operations.error) {+ logger.error("Failed to load sync operations", {+ companyId,+ integration: integration.id,+ error: operations.error+ });+ return listErrorPage("operations");+ }++ const page = toPage(operations.data, {+ limit: PAGE_SIZE,+ sorts: SYNC_ACTIVITY_SORTS+ });++ return {+ operations: await withSyncOperationReferences(client, companyId, page.rows),+ nextCursor: page.nextCursor+ };+}diff --git a/apps/erp/app/routes/api+/link.ts b/apps/erp/app/routes/api+/link.tsindex 33f9f4cdce..69cc60965d 100644--- a/apps/erp/app/routes/api+/link.ts+++ b/apps/erp/app/routes/api+/link.ts@@ -5,131 +5,16 @@import { requirePermissions } from "@carbon/auth/auth.server";import { getCompanyId, setCompanyId } from "@carbon/auth/company.server";import { updateCompanySession } from "@carbon/auth/session.server";-import type { Database } from "@carbon/database";-import {- NotificationEvent,- type RecurringInvoicingDocumentType-} from "@carbon/notifications";+import type { NotificationEvent } from "@carbon/notifications";import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { getCompanies } from "~/modules/settings";-import { getRecordPath } from "~/utils/entity";+import {+ type NotificationDocumentType,+ notificationTarget+} from "~/utils/notification-target";import { path } from "~/utils/path";-type ApprovalDocumentType = Database["public"]["Enums"]["approvalDocumentType"];-/** The approvable document of an Approval* event, or what a Recurring- * invoicing notification lists. */-type NotificationDocumentType =- | ApprovalDocumentType- | RecurringInvoicingDocumentType;--function resolve(- event: NotificationEvent,- documentId: string,- documentType?: NotificationDocumentType-): string | null {- switch (event) {- case NotificationEvent.TrainingAssignment:- case NotificationEvent.TrainingReminder: {- // documentId is a trainingAssignment id; the recipient is the trainee,- // so land on the completion page (same target as the topbar row).- return path.to.completeTrainingAssignment(documentId);- }- case NotificationEvent.ResourceTrainingAssignment: {- // documentId is a training id; land on the training viewer (same- // target as the topbar row).- return path.to.training(documentId);- }- case NotificationEvent.JobAssignment:- case NotificationEvent.JobCompleted:- case NotificationEvent.JobsProjectedLate:- return path.to.job(documentId);- case NotificationEvent.JobOperationAssignment:- case NotificationEvent.JobOperationMessage: {- const [jobId, operationId, makeMethodId, materialId] =- documentId.split(":");- if (!jobId || !operationId || !makeMethodId) return null;- const link = materialId- ? path.to.jobMakeMethod(jobId, makeMethodId)- : path.to.jobMethod(jobId, makeMethodId);- return `${link}?selectedOperation=${operationId}`;- }- case NotificationEvent.PurchaseInvoiceAssignment:- return path.to.purchaseInvoice(documentId);- case NotificationEvent.PurchaseOrderAssignment:- return path.to.purchaseOrder(documentId);- case NotificationEvent.QuoteAssignment:- case NotificationEvent.QuoteExpired:- case NotificationEvent.DigitalQuoteResponse:- return path.to.quote(documentId);- case NotificationEvent.SupplierQuoteAssignment:- case NotificationEvent.SupplierQuoteResponse:- return path.to.supplierQuote(documentId);- case NotificationEvent.SalesOrderAssignment:- return path.to.salesOrder(documentId);- case NotificationEvent.PurchasingRfqAssignment:- return path.to.purchasingRfq(documentId);- case NotificationEvent.SalesRfqAssignment:- case NotificationEvent.SalesRfqReady:- return path.to.salesRfq(documentId);- case NotificationEvent.SalesRuleViolation: {- // Compound documentId: "<quote|salesOrder|salesInvoice>:<documentId>:<outcome>"- const [docType, docId] = documentId.split(":");- if (!docId) return null;- return docType === "salesInvoice"- ? path.to.salesInvoice(docId)- : docType === "salesOrder"- ? path.to.salesOrder(docId)- : path.to.quote(docId);- }- case NotificationEvent.MaintenanceDispatchAssignment:- case NotificationEvent.MaintenanceDispatchCreated:- return path.to.maintenanceDispatch(documentId);- case NotificationEvent.GaugeCalibrationExpired:- return path.to.gauge(documentId);- case NotificationEvent.NonConformanceAssignment:- return path.to.issue(documentId);- case NotificationEvent.ChangeNoticeStarted:- case NotificationEvent.ChangeNoticeImplementation:- case NotificationEvent.ChangeNoticeDone:- return path.to.changeNoticeDetails(documentId);- case NotificationEvent.RiskAssignment:- return path.to.risk(documentId);- case NotificationEvent.ProcedureAssignment:- return path.to.procedure(documentId);- case NotificationEvent.StockTransferAssignment:- return path.to.stockTransfer(documentId);- case NotificationEvent.PickingListAssignment:- return path.to.pickingList(documentId);- case NotificationEvent.SuggestionResponse:- return path.to.suggestion(documentId);- case NotificationEvent.RecurringInvoicing:- // documentId is only the digest's first invoice; land on the list it- // is about (same target as the topbar row): the lease drafts waiting- // for the buyer, else the sales invoices that need review.- return documentType === "purchaseInvoice"- ? `${path.to.invoicingPurchasing}?filter=status:eq:Draft`- : `${path.to.invoicingSales}?filter=needsReview:eq:true`;- case NotificationEvent.LeaseCriticalDate:- return path.to.leaseDetails(documentId);- case NotificationEvent.Workflow:- return getRecordPath(documentType, documentId);- case NotificationEvent.ApprovalApproved:- case NotificationEvent.ApprovalRejected:- case NotificationEvent.ApprovalRequested:- if (documentType === "purchaseOrder")- return path.to.purchaseOrder(documentId);- if (documentType === "qualityDocument")- return path.to.qualityDocument(documentId);- if (documentType === "supplier") return path.to.supplier(documentId);- if (documentType === "changeOrder")- return path.to.changeNoticeDetails(documentId);- return null;- default:- return null;- }-}-export async function loader({ request }: LoaderFunctionArgs) {const {client,@@ -156,8 +41,10 @@ export async function loader({ request }: LoaderFunctionArgs) {// Email footer link — no document, but the company-switch below still applies.redirectTo = path.to.accountSettings("notifications");} else if (event && documentId) {- const link = resolve(event, documentId, documentType ?? undefined);- redirectTo = link ?? path.to.authenticatedRoot;+ // The same target as the topbar row (`notificationTarget`).+ redirectTo =+ notificationTarget(event, documentId, documentType)?.path ??+ path.to.authenticatedRoot;} else if (companyId) {redirectTo = path.to.authenticatedRoot;} else {diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex 118720a225..cf3638380d 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -38,7 +38,7 @@{"name":"accounting_getAccountingPeriods","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"bd245bd0358c","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getAccountingSyncTieOut","classification":"READ","paramCount":3,"schema":"4feda8437359","response":"5483e69d7515","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getAccountingSyncTieOutCell","classification":"READ","paramCount":1,"schema":"1a84bfebf9e9","response":"a5febf12f4bd","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getAccountLedger","classification":"READ","paramCount":6,"schema":"8ad7f551d78b","response":"faf531dd8b9a","injectAuth":"companyId","permission":"accounting:view","paginates":true},+ {"name":"accounting_getAccountLedger","classification":"READ","paramCount":6,"schema":"35b79c87221a","response":"faf531dd8b9a","injectAuth":"companyId","permission":"accounting:view","paginates":true},{"name":"accounting_getAccountLedgerSummary","classification":"READ","paramCount":3,"schema":"aad65f7c3f63","response":"0a28a92b28ff","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getAccountPeriodSeries","classification":"READ","paramCount":2,"schema":"d5db2abee293","response":"2c75339d9fde","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getAccounts","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"84821cb96b68","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},@@ -65,7 +65,7 @@{"name":"accounting_getDeferredRevenueWaterfall","classification":"READ","paramCount":1,"schema":"c860433efc00","response":"6ba817c304ae","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getDepreciationRun","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"22ccbb1556ab","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getDepreciationRunLines","classification":"READ","paramCount":1,"schema":"e83946bf5ea7","response":"9c31ce726755","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getDepreciationRuns","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"829d729e81c9","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},+ {"name":"accounting_getDepreciationRuns","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"8896184e60b3","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},{"name":"accounting_getDimension","classification":"READ","paramCount":1,"schema":"96e5d0fb89ae","response":"e869e1d37e76","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getDimensionPivot","classification":"READ","paramCount":6,"schema":"4dc617d84588","response":"c7069f830357","injectAuth":"companyGroupId+companyId","permission":"accounting:view","paginates":false,"defaults":"always"},{"name":"accounting_getDimensionPivotLines","classification":"READ","paramCount":17,"schema":"6f74597ffe85","response":"100f0689af3e","injectAuth":"companyGroupId+companyId","permission":"accounting:view","paginates":false},@@ -83,7 +83,7 @@{"name":"accounting_getFixedAssetClasses","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"03a52bf94953","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},{"name":"accounting_getFixedAssetClassesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"123f9f4a60f8","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getFixedAssetDisposal","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"4b37a6513b87","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getFixedAssets","classification":"READ","paramCount":4,"schema":"98a82364580e","response":"1352052a4d0e","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},+ {"name":"accounting_getFixedAssets","classification":"READ","paramCount":4,"schema":"98a82364580e","response":"883d15b0ec6d","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},{"name":"accounting_getFixedAssetsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0c62226f500a","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getFixedAssetsListForSale","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0c62226f500a","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getFixedAssetTransfers","classification":"READ","paramCount":1,"schema":"91f483e6fee8","response":"e88320352e28","injectAuth":"companyId","permission":"accounting:view","paginates":false},@@ -117,7 +117,7 @@{"name":"accounting_getReportViews","classification":"READ","paramCount":1,"schema":"f60ae5d8a496","response":"7f6aad3009db","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getRevenueRecognitionRun","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"fb8cbba30867","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getRevenueRecognitionRunLines","classification":"READ","paramCount":1,"schema":"8245d2d4cee4","response":"beb79b629050","injectAuth":"companyId","permission":"accounting:view","paginates":false},- {"name":"accounting_getRevenueRecognitionRuns","classification":"READ","paramCount":2,"schema":"cde27bc67b4d","response":"cfdb7948ea0a","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},+ {"name":"accounting_getRevenueRecognitionRuns","classification":"READ","paramCount":2,"schema":"cde27bc67b4d","response":"2c5b3de7d4b3","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},{"name":"accounting_getRevenueSchedules","classification":"READ","paramCount":4,"schema":"a9a93466d158","response":"029139d6955a","injectAuth":"companyId","permission":"accounting:view","paginates":true,"defaults":"always"},{"name":"accounting_getScrapAccountIds","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"681004346c78","injectAuth":"companyId","permission":"accounting:view","paginates":false},{"name":"accounting_getTrialBalance","classification":"READ","paramCount":2,"schema":"3eb7f553b21b","response":"e782cb2b76dc","injectAuth":"companyId","permission":"accounting:view","paginates":false},@@ -259,7 +259,7 @@{"name":"inventory_getStorageUnitsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getStorageUnitsListForLocation","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getStorageUnitsTreeForLocation","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"ecdf2c570468","injectAuth":"companyId","permission":"inventory:view","paginates":false},- {"name":"inventory_getStorageUnitSubtrees","classification":"READ","paramCount":3,"schema":"c5258b49b1b9","response":"10e6a05f40e5","injectAuth":"companyId","permission":"inventory:view","paginates":false},+ {"name":"inventory_getStorageUnitSubtrees","classification":"READ","paramCount":3,"schema":"c5258b49b1b9","response":"2b4ed272b37a","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getStorageUnitTree","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"3bae190e2656","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_getTrackedEntities","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},{"name":"inventory_getTrackedEntitiesByMakeMethodId","classification":"READ","paramCount":1,"schema":"c32158774ba3","response":"c20d7cb06756","injectAuth":"companyId","permission":"inventory:view","paginates":false},@@ -1014,7 +1014,7 @@{"name":"quality_getGaugeTypesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"quality:view","paginates":false},{"name":"quality_getInspection","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId","permission":"quality:view","paginates":false},{"name":"quality_getInspectionDocument","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"a82889f583de","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getInspectionDocuments","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"0daf2106401c","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},+ {"name":"quality_getInspectionDocuments","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"daa253e3c540","injectAuth":"companyId","permission":"quality:view","paginates":true,"defaults":"always"},{"name":"quality_getInspectionDocumentsForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"cfa5f1f7b8aa","injectAuth":"companyId","permission":"quality:view","paginates":false},{"name":"quality_getInspectionFeatures","classification":"READ","paramCount":1,"schema":"c25fe011e891","response":"1e8d8f002f21","injectAuth":"companyId","permission":"quality:view","paginates":false},{"name":"quality_getInspectionGauges","classification":"READ","paramCount":1,"schema":"d88996520fca","response":"d5c3ebb5ddd2","injectAuth":"companyId","permission":"quality:view","paginates":false},diff --git a/apps/erp/app/routes/api+/table.export.$exportId.ts b/apps/erp/app/routes/api+/table.export.$exportId.tsnew file mode 100644index 0000000000..b1408d870f--- /dev/null+++ b/apps/erp/app/routes/api+/table.export.$exportId.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { requirePermissions } from "@carbon/auth/auth.server";+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import {+ fileResponseHeaders,+ isStorageNotFound,+ storageErrorStatus,+ TEMP_STAGING_BUCKET+} from "@carbon/files";+import { CSV_CONTENT_TYPE } from "@carbon/files/csv";+import { tableExportStorageKey } from "@carbon/jobs/inngest";+import { getLogger } from "@carbon/logger";+import type { LoaderFunctionArgs } from "react-router";+import { getListDefinition } from "~/utils/list-registry/index.server";+import { parseTableExportId } from "~/utils/table-jobs";++const logger = getLogger("erp", "table-export-download");++export const config = {+ runtime: "nodejs"+};++/**+ * GET — downloads a background export (`table.export.ts`). The file lives at+ * `{companyId}/exports/{userId}/{exportId}.csv`, and the key is built from the+ * session, so a user only ever reaches their own exports of the active+ * company. The list's permission is checked again: a user who lost access to+ * the list since the export no longer gets its rows.+ */+export async function loader({ request, params }: LoaderFunctionArgs) {+ const exportId = params.exportId ?? "";+ const parsed = parseTableExportId(exportId);+ const definition = parsed ? getListDefinition(parsed.listKey) : undefined;+ if (!parsed || !definition) {+ logger.error("Refused a table export download for an unknown export", {+ exportId+ });+ throw new Response("This export could not be found.", { status: 404 });+ }++ const { companyId, userId } = await requirePermissions(request, {+ ...definition.permission,+ role: "employee"+ });++ const key = tableExportStorageKey(companyId, userId, exportId);+ const file = await getCarbonServiceRole()+ .storage.from(TEMP_STAGING_BUCKET)+ .download(key);+ if (file.error) {+ const notFound = await isStorageNotFound(file.error);+ logger.error("Failed to download a table export", {+ companyId,+ key,+ status: storageErrorStatus(file.error),+ error: file.error+ });+ if (notFound) {+ // The nightly cleanup deletes exports after 7 days.+ throw new Response(+ "This export could not be found. Exports are kept for 7 days.",+ { status: 404 }+ );+ }+ throw new Response(null, { status: 500 });+ }++ const headers = fileResponseHeaders(CSV_CONTENT_TYPE, "private, no-store");+ headers.set(+ "Content-Disposition",+ `attachment; filename="${parsed.listKey}.csv"`+ );+ return new Response(file.data, { status: 200, headers });+}diff --git a/apps/erp/app/routes/api+/table.export.ts b/apps/erp/app/routes/api+/table.export.tsnew file mode 100644index 0000000000..28d3668284--- /dev/null+++ b/apps/erp/app/routes/api+/table.export.ts@@ -0,0 +1,97 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { assertIsPost } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { trigger } from "@carbon/jobs";+import { releaseTableJobLock, takeTableJobLock } from "@carbon/jobs/inngest";+import { getLogger } from "@carbon/logger";+import type { ActionFunctionArgs } from "react-router";+import { data } from "react-router";+import { z } from "zod";+import { getListDefinition } from "~/utils/list-registry/index.server";+import { newTableExportId, tableJobBusyMessage } from "~/utils/table-jobs";++const logger = getLogger("erp", "table-export");++export const config = {+ runtime: "nodejs"+};++const exportRequestValidator = z.object({+ listKey: z.string().min(1),+ search: z.string().max(10_000),+ columns: z+ .array(z.object({ key: z.string().min(1), label: z.string() }))+ .min(1)+ .max(500)+});++/**+ * POST `{ listKey, search, columns: [{ key, label }] }` — starts the background+ * CSV export of a registered list (the Table's Download button, past 1,000+ * rows). Answers `{ success: true }`, or `{ error }` with 400 (bad request,+ * unknown list), 409 (an export of the company is already running; the text+ * says how long its lock can still hold) or 500. The file is served by+ * `api+/table.export.$exportId.ts`, to the requester only.+ */+export async function action({ request }: ActionFunctionArgs) {+ assertIsPost(request);++ const body = exportRequestValidator.safeParse(+ await request.json().catch(() => null)+ );+ if (!body.success) {+ return data({ error: "The export request is not valid" }, { status: 400 });+ }+ const { listKey, search, columns } = body.data;++ const definition = getListDefinition(listKey);+ if (!definition) {+ logger.error("Export requested for an unknown list", { listKey });+ return data({ error: "This list cannot be exported" }, { status: 400 });+ }++ const { companyId, userId } = await requirePermissions(request, {+ ...definition.permission,+ role: "employee"+ });++ const exportId = newTableExportId(listKey);+ const lock = await takeTableJobLock("export", companyId, exportId);+ if (lock.status === "busy") {+ return data(+ { error: tableJobBusyMessage("export", lock.retryAfterSeconds) },+ { status: 409 }+ );+ }+ if (lock.status === "unavailable") {+ // Fail-open: Inngest's per-company concurrency still runs one at a time.+ logger.warn("Starting a table export without the Redis lock", {+ companyId,+ listKey+ });+ }++ try {+ await trigger("table-export", {+ companyId,+ userId,+ exportId,+ listKey,+ search,+ columns+ });+ } catch (error) {+ logger.error("Failed to start a table export", {+ companyId,+ listKey,+ error+ });+ await releaseTableJobLock("export", companyId, exportId);+ return data({ error: "The export could not start" }, { status: 500 });+ }++ return data({ success: true });+}diff --git a/apps/erp/app/routes/share+/customer.$id.tsx b/apps/erp/app/routes/share+/customer.$id.tsxindex 418d5f9451..e6c45733ee 100644--- a/apps/erp/app/routes/share+/customer.$id.tsx+++ b/apps/erp/app/routes/share+/customer.$id.tsx@@ -6,7 +6,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { companyHasFeature } from "@carbon/ee/plan.server";import { getLogger } from "@carbon/logger";import { Avatar } from "@carbon/react";-import { SCALE_FORMAT } from "@carbon/utils";+import { async, SCALE_FORMAT } from "@carbon/utils";import { useLocale, useNumberFormatter } from "@react-aria/i18n";import type { ColumnDef } from "@tanstack/react-table";import { useMemo } from "react";@@ -37,6 +37,7 @@ import {getBase64ImageFromSupabase,getCustomerPortal} from "~/modules/shared/shared.service";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";@@ -50,6 +51,9 @@ const defaultColumnPinning = {const logger = getLogger("erp", "share", "customer-portal");+// The thumbnails the page downloads at once.+const THUMBNAIL_CONCURRENCY = 8;+export async function loader({ params, request }: LoaderFunctionArgs) {const { id } = params;if (!id) {@@ -83,15 +87,15 @@ export async function loader({ params, request }: LoaderFunctionArgs) {const url = new URL(request.url);const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);+ const { sorts, filters } = getGenericQueryFilters(searchParams);const [company, salesOrderLines] = await Promise.all([getCompany(serviceRole, customer.data.companyId),getExternalSalesOrderLines(serviceRole, customer.data.customerId, {search,- limit,- offset,+ // A single-load list: the RPC returns no row id for a cursor to follow.+ limit: SINGLE_LOAD_LIMIT,+ offset: 0,sorts,filters})@@ -117,35 +121,33 @@ export async function loader({ params, request }: LoaderFunctionArgs) {return acc;}, {});- const [thumbnails, jobOperationAttachments] = await Promise.all([- (thumbnailPaths- ? await Promise.all(- Object.entries(thumbnailPaths).map(([id, path]) => {- if (!path) {- return null;- }- return getBase64ImageFromSupabase(serviceRole, path).then(- (data) => ({- id,- data- })- );- })- )- : []- )?.reduce<Record<string, string | null>>((acc, thumbnail) => {+ // Up to 1,000 lines: the thumbnails download a few at a time.+ const [thumbnailList, jobOperationAttachments] = await Promise.all([+ async.map(+ Object.entries(thumbnailPaths ?? {}),+ async ([id, path]) =>+ path+ ? { id, data: await getBase64ImageFromSupabase(serviceRole, path) }+ : null,+ { concurrency: THUMBNAIL_CONCURRENCY }+ ),+ getJobOperationAttachments(serviceRole, jobOperationIds ?? [])+ ]);+ const thumbnails = thumbnailList.reduce<Record<string, string | null>>(+ (acc, thumbnail) => {if (thumbnail) {acc[thumbnail.id] = thumbnail.data;}return acc;- }, {}) ?? {},- getJobOperationAttachments(serviceRole, jobOperationIds ?? [])- ]);+ },+ {}+ );return {customer: customer.data,company: company.data,salesOrderLines: salesOrderLines.data ?? [],+ isTruncated: (salesOrderLines.data?.length ?? 0) >= SINGLE_LOAD_LIMIT,jobOperationAttachments,count: salesOrderLines.count,thumbnails@@ -158,6 +160,7 @@ export default function CustomerPortal() {customer,company,salesOrderLines,+ isTruncated,thumbnails,jobOperationAttachments} = useLoaderData<typeof loader>();@@ -390,6 +393,7 @@ export default function CustomerPortal() {data={salesOrderLines}columns={columns}count={count ?? 0}+ isTruncated={isTruncated}compactdefaultColumnPinning={defaultColumnPinning}sort={<PortalSort columns={sortableColumns} />}diff --git a/apps/erp/app/routes/x+/accounting+/asset-classes.tsx b/apps/erp/app/routes/x+/accounting+/asset-classes.tsxindex bef9f5bfee..6a54a4ede2 100644--- a/apps/erp/app/routes/x+/accounting+/asset-classes.tsx+++ b/apps/erp/app/routes/x+/accounting+/asset-classes.tsx@@ -2,7 +2,6 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { Button, RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import { Trans, useLingui } from "@lingui/react/macro";@@ -11,12 +10,12 @@ import type { LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate } from "react-router";import { NewAction } from "~/components/New";import { usePermissions } from "~/hooks";-import { getFixedAssetClasses } from "~/modules/accounting";import { AssetClassesTable } from "~/modules/accounting/ui/FixedAssets";import { getCompanySettings } from "~/modules/settings";import type { Handle } from "~/utils/handle";+import { assetClassesList } from "~/utils/list-registry/accounting.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Asset Classes`,@@ -24,38 +23,20 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "accounting",- role: "employee"+ return loadListPage(request, assetClassesList, {+ dataKey: "data",+ firstPage: async ({ client, companyId }) => {+ const companySettings = await getCompanySettings(client, companyId);+ return {+ taxDepreciationEnabled:+ (companySettings.data as any)?.assetTaxDepreciationEnabled ?? false+ };+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [classes, companySettings] = await Promise.all([- getFixedAssetClasses(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getCompanySettings(client, companyId)- ]);-- return {- data: classes.data ?? [],- count: classes.count ?? 0,- taxDepreciationEnabled:- (companySettings.data as any)?.assetTaxDepreciationEnabled ?? false- };}export default function AssetClassesRoute() {- const { data, count, taxDepreciationEnabled } =+ const { data, count, nextCursor, taxDepreciationEnabled } =useLoaderData<typeof loader>();const { t } = useLingui();const permissions = usePermissions();@@ -66,6 +47,7 @@ export default function AssetClassesRoute() {<AssetClassesTabledata={data}count={count}+ nextCursor={nextCursor}taxDepreciationEnabled={taxDepreciationEnabled}primaryAction={permissions.can("create", "accounting") && (diff --git a/apps/erp/app/routes/x+/accounting+/charts.ledger.$accountId.tsx b/apps/erp/app/routes/x+/accounting+/charts.ledger.$accountId.tsxindex bab99c57b3..7ef96dcf65 100644--- a/apps/erp/app/routes/x+/accounting+/charts.ledger.$accountId.tsx+++ b/apps/erp/app/routes/x+/accounting+/charts.ledger.$accountId.tsx@@ -9,18 +9,13 @@ import { getLogger } from "@carbon/logger";import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import {- getAccount,- getAccountLedger,- getAccountLedgerSummary-} from "~/modules/accounting";+import { getAccount } from "~/modules/accounting";+import { getAccountLedgerPage } from "~/modules/accounting/accounting.server";import { AccountLedgerDrawer } from "~/modules/accounting/ui/Reports";import { path } from "~/utils/path";const logger = getLogger("erp", "accounting-charts-ledger");-const LEDGER_PAGE_SIZE = 50;-export async function loader({ request, params }: LoaderFunctionArgs) {// bypassRls matches the chart of accounts page, whose balances span every// company in the group regardless of the user's per-company roles@@ -37,7 +32,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const searchParams = new URLSearchParams(url.search);const startDate = searchParams.get("startDate") || null;const endDate = searchParams.get("endDate") || null;- const offset = Math.max(0, Number(searchParams.get("offset")) || 0);// bypassRls makes `client` the service role and the ledger read below is// unscoped by company, so the account must be proven to be this group's@@ -57,35 +51,26 @@ export async function loader({ request, params }: LoaderFunctionArgs) {throw redirect(path.to.chartOfAccounts);}- const [ledger, summary] = await Promise.all([- getAccountLedger(client, {- accountId,- companyId: null,- startDate,- endDate,- limit: LEDGER_PAGE_SIZE,- offset- }),- getAccountLedgerSummary(client, companyGroupId, null, {- accountId,- startDate,- endDate- })- ]);+ // A later page (`?after=`) is read for its lines only.+ const ledger = await getAccountLedgerPage(client, {+ accountId,+ companyGroupId,+ companyId: null,+ startDate,+ endDate,+ after: searchParams.get("after")+ });return {account: account.data,- lines: ledger.data ?? [],- count: ledger.count ?? 0,- summary: summary.data ?? { opening: 0, netChange: 0, closing: 0 },+ ...ledger,startDate,- endDate,- offset+ endDate};}export default function ChartOfAccountsLedgerRoute() {- const { account, lines, count, summary, startDate, endDate, offset } =+ const { account, lines, count, nextCursor, summary, startDate, endDate } =useLoaderData<typeof loader>();return (@@ -96,8 +81,7 @@ export default function ChartOfAccountsLedgerRoute() {summary={summary}startDate={startDate}endDate={endDate}- offset={offset}- limit={LEDGER_PAGE_SIZE}+ nextCursor={nextCursor}backTo={path.to.chartOfAccounts}/>);diff --git a/apps/erp/app/routes/x+/accounting+/charts.tsx b/apps/erp/app/routes/x+/accounting+/charts.tsxindex e36fc6f78a..cbef659b82 100644--- a/apps/erp/app/routes/x+/accounting+/charts.tsx+++ b/apps/erp/app/routes/x+/accounting+/charts.tsx@@ -21,14 +21,14 @@ import ChartOfAccountsTableFilters from "~/modules/accounting/ui/ChartOfAccountsimport { months } from "~/modules/shared";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";-import { revalidateIgnoringOffset } from "~/utils/revalidate";+import { revalidateOnSearchChange } from "~/utils/revalidate";export const handle: Handle = {breadcrumb: msg`Chart of Accounts`,to: path.to.chartOfAccounts};-export const shouldRevalidate = revalidateIgnoringOffset;+export const shouldRevalidate = revalidateOnSearchChange;export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId, companyGroupId } = await requirePermissions(diff --git a/apps/erp/app/routes/x+/accounting+/depreciation-runs.tsx b/apps/erp/app/routes/x+/accounting+/depreciation-runs.tsxindex 90a9828fb0..634a521a9f 100644--- a/apps/erp/app/routes/x+/accounting+/depreciation-runs.tsx+++ b/apps/erp/app/routes/x+/accounting+/depreciation-runs.tsx@@ -2,7 +2,6 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import {Button,DatePicker,@@ -23,12 +22,12 @@ import type { LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate } from "react-router";import { Confirm } from "~/components/Modals";import { usePermissions } from "~/hooks";-import { getDepreciationRuns } from "~/modules/accounting";import { getNextPeriodEnd } from "~/modules/accounting/accounting.utils";import { DepreciationRunTable } from "~/modules/accounting/ui/FixedAssets";import type { Handle } from "~/utils/handle";+import { depreciationRunsList } from "~/utils/list-registry/accounting.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Depreciation`,@@ -36,50 +35,39 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "accounting",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);+ return loadListPage(request, depreciationRunsList, {+ dataKey: "data",+ firstPage: async ({ client, companyId }) => {+ const lastRun = await client+ .from("depreciationRun")+ .select("periodEnd, status")+ .eq("companyId", companyId)+ .order("periodEnd", { ascending: false })+ .limit(1);- const [runs, lastRun] = await Promise.all([- getDepreciationRuns(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- client- .from("depreciationRun")- .select("periodEnd, status")- .eq("companyId", companyId)- .order("periodEnd", { ascending: false })- .limit(1)- ]);+ const lastRunData =+ lastRun.data && lastRun.data.length > 0 ? lastRun.data[0] : null;+ const nextPeriodEnd = getNextPeriodEnd(lastRunData?.periodEnd ?? null);+ const hasDraftBlocking = lastRunData?.status === "Draft";- const lastRunData =- lastRun.data && lastRun.data.length > 0 ? lastRun.data[0] : null;- const nextPeriodEnd = getNextPeriodEnd(lastRunData?.periodEnd ?? null);- const hasDraftBlocking = lastRunData?.status === "Draft";-- return {- data: runs.data ?? [],- count: runs.count ?? 0,- lastPeriodEnd: lastRunData?.periodEnd ?? null,- nextPeriodEnd,- hasDraftBlocking- };+ return {+ lastPeriodEnd: lastRunData?.periodEnd ?? null,+ nextPeriodEnd,+ hasDraftBlocking+ };+ }+ });}export default function DepreciationRunsRoute() {- const { data, count, lastPeriodEnd, nextPeriodEnd, hasDraftBlocking } =- useLoaderData<typeof loader>();+ const {+ data,+ count,+ nextCursor,+ lastPeriodEnd,+ nextPeriodEnd,+ hasDraftBlocking+ } = useLoaderData<typeof loader>();const { t } = useLingui();const permissions = usePermissions();const navigate = useNavigate();@@ -99,6 +87,7 @@ export default function DepreciationRunsRoute() {<DepreciationRunTabledata={data}count={count}+ nextCursor={nextCursor}primaryAction={permissions.can("create", "accounting") && (<TooltipProvider>diff --git a/apps/erp/app/routes/x+/accounting+/dimensions.tsx b/apps/erp/app/routes/x+/accounting+/dimensions.tsxindex 85768e7def..1b2c74b94a 100644--- a/apps/erp/app/routes/x+/accounting+/dimensions.tsx+++ b/apps/erp/app/routes/x+/accounting+/dimensions.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getDimensions } from "~/modules/accounting";import { DimensionsTable } from "~/modules/accounting/ui/Dimensions";import type { Handle } from "~/utils/handle";+import { dimensionsList } from "~/utils/list-registry/accounting.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Dimensions`,@@ -19,32 +18,15 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyGroupId } = await requirePermissions(request, {- view: "accounting",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getDimensions(client, companyGroupId, {- search,- limit,- offset,- sorts,- filters- });+ return loadListPage(request, dimensionsList, { dataKey: "data" });}export default function DimensionsRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <DimensionsTable data={data ?? []} count={count ?? 0} />+ <DimensionsTable data={data} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/accounting+/exchange-rates.tsx b/apps/erp/app/routes/x+/accounting+/exchange-rates.tsxindex 282fee55ff..e716dd049d 100644--- a/apps/erp/app/routes/x+/accounting+/exchange-rates.tsx+++ b/apps/erp/app/routes/x+/accounting+/exchange-rates.tsx@@ -33,14 +33,14 @@ export async function loader({ request }: LoaderFunctionArgs) {const url = new URL(request.url);const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =+ const { limit, cursor, sorts, filters } =getGenericQueryFilters(searchParams);const [currencies, exchangeRates] = await Promise.all([getCurrencies(client, companyGroupId, {search,limit,- offset,+ cursor,sorts,filters}),diff --git a/apps/erp/app/routes/x+/accounting+/fixed-assets.tsx b/apps/erp/app/routes/x+/accounting+/fixed-assets.tsxindex 6e58366374..cf94b8ec74 100644--- a/apps/erp/app/routes/x+/accounting+/fixed-assets.tsx+++ b/apps/erp/app/routes/x+/accounting+/fixed-assets.tsx@@ -2,7 +2,6 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { Button, RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import { Trans, useLingui } from "@lingui/react/macro";@@ -11,11 +10,12 @@ import type { LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate } from "react-router";import { NewAction } from "~/components/New";import { usePermissions } from "~/hooks";-import { getFixedAssetClassesList, getFixedAssets } from "~/modules/accounting";+import { getFixedAssetClassesList } from "~/modules/accounting";import { FixedAssetsTable } from "~/modules/accounting/ui/FixedAssets";import type { Handle } from "~/utils/handle";+import { fixedAssetsList } from "~/utils/list-registry/accounting.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Fixed Assets`,@@ -23,44 +23,18 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "accounting",- role: "employee"+ return loadListPage(request, fixedAssetsList, {+ dataKey: "data",+ firstPage: async ({ client, companyId }) => {+ const assetClasses = await getFixedAssetClassesList(client, companyId);+ return { assetClasses: assetClasses.data ?? [] };+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const status = searchParams.get("status") as- | "Draft"- | "Active"- | "Fully Depreciated"- | "Disposed"- | null;- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [assets, assetClasses] = await Promise.all([- getFixedAssets(client, companyId, {- search,- status,- limit,- offset,- sorts,- filters- }),- getFixedAssetClassesList(client, companyId)- ]);-- return {- data: assets.data ?? [],- count: assets.count ?? 0,- assetClasses: assetClasses.data ?? []- };}export default function FixedAssetsRoute() {- const { data, count, assetClasses } = useLoaderData<typeof loader>();+ const { data, count, nextCursor, assetClasses } =+ useLoaderData<typeof loader>();const { t } = useLingui();const permissions = usePermissions();const navigate = useNavigate();@@ -70,6 +44,7 @@ export default function FixedAssetsRoute() {<FixedAssetsTabledata={data}count={count}+ nextCursor={nextCursor}assetClasses={assetClasses}primaryAction={permissions.can("create", "accounting") && (diff --git a/apps/erp/app/routes/x+/accounting+/fleet.tsx b/apps/erp/app/routes/x+/accounting+/fleet.tsxindex 7b9d512bf2..b9c5d07ac1 100644--- a/apps/erp/app/routes/x+/accounting+/fleet.tsx+++ b/apps/erp/app/routes/x+/accounting+/fleet.tsx@@ -2,7 +2,6 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { Button, RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import { Trans } from "@lingui/react/macro";@@ -10,11 +9,11 @@ import { LuHammer } from "react-icons/lu";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate } from "react-router";import { usePermissions } from "~/hooks";-import { getFleetAssets } from "~/modules/accounting";import { FleetAssetsTable } from "~/modules/accounting/ui/FixedAssets";import type { Handle } from "~/utils/handle";+import { fleetAssetsList } from "~/utils/list-registry/accounting.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Fleet`,@@ -24,54 +23,34 @@ export const handle: Handle = {const RENTAL_FLEET_CLASS_NAME = "Rental Fleet";export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "accounting",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const fleetStatus = searchParams.get("fleetStatus");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);+ return loadListPage(request, fleetAssetsList, {+ dataKey: "data",+ firstPage: async ({ client, companyId }) => {+ // "Build for fleet" opens a new job completing to the Rental Fleet class,+ // else the first in-service class. A CIP class is never a target.+ // `getFixedAssetClassesList` does not select `isConstructionInProgress`,+ // so the filter is applied here (same select as `x+/job+/new.tsx`).+ const assetClasses = await client+ .from("fixedAssetClass")+ .select("id, name")+ .eq("companyId", companyId)+ .eq("isConstructionInProgress", false)+ .order("name");- const [assets, assetClasses] = await Promise.all([- getFleetAssets(client, companyId, {- search,- fleetStatus,- limit,- offset,- sorts,- filters- }),- // "Build for fleet" opens a new job completing to the Rental Fleet class,- // else the first in-service class. A CIP class is never a target.- // `getFixedAssetClassesList` does not select `isConstructionInProgress`,- // so the filter is applied here (same select as `x+/job+/new.tsx`).- client- .from("fixedAssetClass")- .select("id, name")- .eq("companyId", companyId)- .eq("isConstructionInProgress", false)- .order("name")- ]);+ const classes = assetClasses.data ?? [];+ const buildForFleetClassId =+ classes.find((c) => c.name === RENTAL_FLEET_CLASS_NAME)?.id ??+ classes[0]?.id ??+ null;- const classes = assetClasses.data ?? [];- const buildForFleetClassId =- classes.find((c) => c.name === RENTAL_FLEET_CLASS_NAME)?.id ??- classes[0]?.id ??- null;-- return {- data: assets.data ?? [],- count: assets.count ?? 0,- buildForFleetClassId- };+ return { buildForFleetClassId };+ }+ });}export default function FleetRoute() {- const { data, count, buildForFleetClassId } = useLoaderData<typeof loader>();+ const { data, count, nextCursor, buildForFleetClassId } =+ useLoaderData<typeof loader>();const permissions = usePermissions();const navigate = useNavigate();@@ -80,6 +59,7 @@ export default function FleetRoute() {<FleetAssetsTabledata={data}count={count}+ nextCursor={nextCursor}primaryAction={permissions.can("create", "production") && (<Buttondiff --git a/apps/erp/app/routes/x+/accounting+/intercompany.tsx b/apps/erp/app/routes/x+/accounting+/intercompany.tsxindex b0fa009cf2..5b7b319579 100644--- a/apps/erp/app/routes/x+/accounting+/intercompany.tsx+++ b/apps/erp/app/routes/x+/accounting+/intercompany.tsx@@ -2,7 +2,6 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { Button, RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import { useLingui } from "@lingui/react/macro";@@ -10,11 +9,11 @@ import type { LoaderFunctionArgs } from "react-router";import { useFetcher, useLoaderData } from "react-router";import { New } from "~/components";import { usePermissions, useUrlParams } from "~/hooks";-import { getIntercompanyTransactions } from "~/modules/accounting";import { IntercompanyTransactionTable } from "~/modules/accounting/ui/Intercompany";import type { Handle } from "~/utils/handle";+import { intercompanyTransactionsList } from "~/utils/list-registry/accounting.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Intercompany`,@@ -22,38 +21,14 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyGroupId } = await requirePermissions(request, {- view: "accounting",- role: "employee"+ return loadListPage(request, intercompanyTransactionsList, {+ dataKey: "data"});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const status = searchParams.get("status");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const transactions = await getIntercompanyTransactions(- client,- companyGroupId,- {- status,- limit,- offset,- sorts,- filters- }- );-- return {- data: transactions.data,- count: transactions.count- };}export default function IntercompanyRoute() {const { t } = useLingui();- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();const [params] = useUrlParams();const permissions = usePermissions();const matchFetcher = useFetcher();@@ -63,8 +38,9 @@ export default function IntercompanyRoute() {return (<VStack spacing={0} className="h-full"><IntercompanyTransactionTable- data={data ?? []}- count={count ?? 0}+ data={data}+ count={count}+ nextCursor={nextCursor}primaryAction={permissions.can("create", "accounting") && (<div className="flex items-center gap-2">diff --git a/apps/erp/app/routes/x+/accounting+/journals.tsx b/apps/erp/app/routes/x+/accounting+/journals.tsxindex aa047c3d19..ce3cef486c 100644--- a/apps/erp/app/routes/x+/accounting+/journals.tsx+++ b/apps/erp/app/routes/x+/accounting+/journals.tsx@@ -2,7 +2,6 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { Button, RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import { Trans, useLingui } from "@lingui/react/macro";@@ -11,11 +10,11 @@ import type { LoaderFunctionArgs } from "react-router";import { useFetcher, useLoaderData } from "react-router";import { NewAction } from "~/components/New";import { usePermissions } from "~/hooks";-import { getJournalEntries } from "~/modules/accounting";import { JournalEntriesTable } from "~/modules/accounting/ui/JournalEntries";import type { Handle } from "~/utils/handle";+import { journalEntriesList } from "~/utils/list-registry/accounting.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Journal Entries`,@@ -23,31 +22,7 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "accounting",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const status = searchParams.get("status");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const entries = await getJournalEntries(client, companyId, {- search,- status,- limit,- offset,- sorts,- filters- });-- return {- data: entries.data ?? [],- count: entries.count ?? 0- };+ return loadListPage(request, journalEntriesList, { dataKey: "data" });}function NewJournalEntry() {@@ -74,7 +49,7 @@ function NewJournalEntry() {}export default function JournalEntriesRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();const permissions = usePermissions();return (@@ -82,6 +57,7 @@ export default function JournalEntriesRoute() {<JournalEntriesTabledata={data}count={count}+ nextCursor={nextCursor}primaryAction={permissions.can("create", "accounting") && <NewJournalEntry />}diff --git a/apps/erp/app/routes/x+/accounting+/payment-terms.tsx b/apps/erp/app/routes/x+/accounting+/payment-terms.tsxindex 3c10f91259..160979d4c8 100644--- a/apps/erp/app/routes/x+/accounting+/payment-terms.tsx+++ b/apps/erp/app/routes/x+/accounting+/payment-terms.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getPaymentTerms } from "~/modules/accounting";import { PaymentTermsTable } from "~/modules/accounting/ui/PaymentTerms";import type { Handle } from "~/utils/handle";+import { paymentTermsList } from "~/utils/list-registry/accounting.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Payment Terms`,@@ -19,32 +18,15 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "accounting",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getPaymentTerms(client, companyId, {- search,- limit,- offset,- sorts,- filters- });+ return loadListPage(request, paymentTermsList, { dataKey: "data" });}export default function PaymentTermsRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <PaymentTermsTable data={data ?? []} count={count ?? 0} />+ <PaymentTermsTable data={data} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/accounting+/projects.tsx b/apps/erp/app/routes/x+/accounting+/projects.tsxindex a63fd9e95f..58f649b002 100644--- a/apps/erp/app/routes/x+/accounting+/projects.tsx+++ b/apps/erp/app/routes/x+/accounting+/projects.tsx@@ -5,15 +5,19 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";-import { getProjects } from "~/modules/accounting";import { ProjectsTable } from "~/modules/accounting/ui/Projects";import type { Handle } from "~/utils/handle";+import { projectsList } from "~/utils/list-registry/accounting.server";+import { fetchListPage } from "~/utils/list-registry/index.server";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";++const logger = getLogger("erp", "projects");export const handle: Handle = {breadcrumb: msg`Projects`,@@ -21,41 +25,50 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "accounting",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const projects = await getProjects(client, companyId, {- search,- limit,- offset,- sorts,- filters- });+ const { client, companyId } = await requirePermissions(+ request,+ projectsList.permission+ );++ const searchParams = new URL(request.url).searchParams;+ const projects = await fetchListPage(+ projectsList,+ client,+ companyId,+ searchParams+ );if (projects.error) {+ if (searchParams.get("after")) {+ logger.error("Failed to load a later page of projects", {+ companyId,+ error: projects.error+ });+ return listErrorPage("data");+ }return data(- { data: [], count: 0 },+ { data: [], count: 0, nextCursor: null },await flash(request, error(projects.error, "Failed to fetch projects")));}- return { data: projects.data ?? [], count: projects.count ?? 0 };+ return {+ data: projects.rows,+ count: projects.count,+ nextCursor: projects.nextCursor+ };}export default function ProjectsRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ProjectsTable data={data ?? []} count={count ?? 0} />+ <ProjectsTable+ data={data ?? []}+ count={count ?? 0}+ nextCursor={nextCursor ?? null}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/documents+/search.tsx b/apps/erp/app/routes/x+/documents+/search.tsxindex 21c38d2f29..757348a6e4 100644--- a/apps/erp/app/routes/x+/documents+/search.tsx+++ b/apps/erp/app/routes/x+/documents+/search.tsx@@ -2,17 +2,13 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";import { generateDownloadToken } from "@carbon/auth/download-token.server";-import { flash } from "@carbon/auth/session.server";import {RecordOutlet,ResizablePanel,ResizablePanelGroup,VStack} from "@carbon/react";-import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { useResolved } from "~/hooks/useResolved";@@ -20,84 +16,61 @@ import type { Document } from "~/modules/documents";import {DocumentsTable,getDocumentExtensions,- getDocumentLabels,- getDocuments+ getDocumentLabels} from "~/modules/documents";+import {+ documentsList,+ recentDocumentsList+} from "~/utils/list-registry/documents.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId, userId } = await requirePermissions(request, {- view: "documents"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const filter = searchParams.get("q");-- const createdBy = filter === "my" ? userId : undefined;- const favorite = filter === "starred" ? true : undefined;- const recent = filter === "recent" ? true : undefined;- const active = filter === "trash" ? false : true;-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- // Only the file-type filter needs this, so it streams rather than holding- // the page.- const extensions = getDocumentExtensions(client, companyId).then(- (result) => result.data?.map(({ extension }) => extension) ?? []- );+ // The "Recent" view orders by the last activity, so it is its own list.+ const list =+ new URL(request.url).searchParams.get("q") === "recent"+ ? recentDocumentsList+ : documentsList;- const [documents, labels] = await Promise.all([- getDocuments(client, companyId, {- search,- favorite,- recent,- createdBy,- active,- limit,- offset,- sorts,- filters+ return loadListPage(request, list, {+ dataKey: "documents",+ firstPage: async ({ client, companyId, userId }) => ({+ listKey: list.key,+ labels: (await getDocumentLabels(client, userId)).data ?? [],+ // Only the file-type filter needs this, so it streams rather than+ // holding the page.+ extensions: getDocumentExtensions(client, companyId).then(+ (result) => result.data?.map(({ extension }) => extension) ?? []+ )}),- getDocumentLabels(client, userId)- ]);-- if (documents.error) {- redirect(- path.to.authenticatedRoot,- await flash(request, error(documents.error, "Failed to fetch documents"))- );- }-- // Mint a signed download token per file-backed row. Signing is a server-only- // HS256 op over the current result set (the same set the CSV exports).- const documentsWithDownloadTokens: Document[] = await Promise.all(- (documents.data ?? []).map(async (document) => ({- ...document,- downloadToken:- document.id && document.path- ? await generateDownloadToken({- userId,- companyId,- documentId: document.id- })- : undefined- }))- );-- return {- count: documents.count ?? 0,- documents: documentsWithDownloadTokens,- labels: labels.data ?? [],- extensions- };+ // A signed download token per file-backed row. Signing is a server-only+ // HS256 op. Each page mints its own, so every loaded row carries one.+ mapRows: (documents, { companyId, userId }) =>+ Promise.all(+ (documents as Document[]).map(+ async (document): Promise<Document> => ({+ ...document,+ downloadToken:+ document.id && document.path+ ? await generateDownloadToken({+ userId,+ companyId,+ documentId: document.id+ })+ : undefined+ })+ )+ ),+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch documents"+ }+ });}export default function DocumentsAllRoute() {- const { count, documents, labels, ...data } = useLoaderData<typeof loader>();+ const { count, documents, nextCursor, listKey, labels, ...data } =+ useLoaderData<typeof loader>();const extensions = useResolved(data.extensions, []);return (@@ -107,6 +80,8 @@ export default function DocumentsAllRoute() {<DocumentsTabledata={documents}count={count}+ nextCursor={nextCursor}+ listKey={listKey}labels={labels}extensions={extensions}/>diff --git a/apps/erp/app/routes/x+/inventory+/inventory-count.tsx b/apps/erp/app/routes/x+/inventory+/inventory-count.tsxindex e4c047b379..891d90c02f 100644--- a/apps/erp/app/routes/x+/inventory+/inventory-count.tsx+++ b/apps/erp/app/routes/x+/inventory+/inventory-count.tsx@@ -2,19 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getInventoryCounts, InventoryCountsTable } from "~/modules/inventory";+import { InventoryCountsTable } from "~/modules/inventory";import { getLocationsList } from "~/modules/resources";import type { Handle } from "~/utils/handle";+import { inventoryCountsList } from "~/utils/list-registry/inventory.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["inventoryCount"],@@ -23,52 +20,29 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "inventory"+ return loadListPage(request, inventoryCountsList, {+ dataKey: "inventoryCounts",+ firstPage: async ({ client, companyId }) => {+ const locations = await getLocationsList(client, companyId);+ return { locations: locations.data ?? [] };+ },+ onError: {+ redirectTo: path.to.inventory,+ message: "Error loading inventory count"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [inventoryCounts, locations] = await Promise.all([- getInventoryCounts(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getLocationsList(client, companyId)- ]);-- if (inventoryCounts.error) {- throw redirect(- path.to.inventory,- await flash(- request,- error(inventoryCounts.error, "Error loading inventory count")- )- );- }-- return {- inventoryCounts: inventoryCounts.data ?? [],- count: inventoryCounts.count ?? 0,- locations: locations.data ?? []- };}export default function InventoryCountRoute() {- const { inventoryCounts, count, locations } = useLoaderData<typeof loader>();+ const { inventoryCounts, count, nextCursor, locations } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full"><InventoryCountsTabledata={inventoryCounts}- count={count ?? 0}+ count={count}+ nextCursor={nextCursor}locations={locations}/><RecordOutlet />diff --git a/apps/erp/app/routes/x+/inventory+/kanbans.tsx b/apps/erp/app/routes/x+/inventory+/kanbans.tsxindex 4d94a97ae4..be1ef9d669 100644--- a/apps/erp/app/routes/x+/inventory+/kanbans.tsx+++ b/apps/erp/app/routes/x+/inventory+/kanbans.tsx@@ -5,20 +5,25 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";import { RecordOutlet, VStack } from "@carbon/react";import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getKanbans } from "~/modules/inventory";+import { getKanbans, KANBANS_PAGING } from "~/modules/inventory";import KanbansTable from "~/modules/inventory/ui/Kanbans/KanbansTable";import { getLocationsList } from "~/modules/resources";import { getKanbanOutputSetting } from "~/modules/settings";import { getUserDefaults } from "~/modules/users/users.server";+import { toPage } from "~/utils/cursor";import type { Handle } from "~/utils/handle";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";+const logger = getLogger("erp", "kanbans");+export const handle: Handle = {breadcrumb: msg`Kanbans`,to: path.to.kanbans,@@ -35,7 +40,7 @@ export async function loader({ request }: LoaderFunctionArgs) {const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =+ const { limit, cursor, sorts, filters } =getGenericQueryFilters(searchParams);let locationId = searchParams.get("location");@@ -73,7 +78,7 @@ export async function loader({ request }: LoaderFunctionArgs) {getKanbans(client, locationId, companyId, {search,limit,- offset,+ cursor,sorts,filters}),@@ -81,22 +86,32 @@ export async function loader({ request }: LoaderFunctionArgs) {]);if (kanbans.error) {+ if (cursor) {+ logger.error("Failed to load a later page of kanbans", {+ companyId,+ error: kanbans.error+ });+ return listErrorPage("kanbans");+ }throw redirect(path.to.authenticatedRoot,await flash(request, error(kanbans.error, "Failed to fetch kanbans")));}+ const page = toPage(kanbans.data ?? [], { limit, sorts }, KANBANS_PAGING);+return {count: kanbans.count ?? 0,- kanbans: kanbans.data ?? [],+ kanbans: page.rows,+ nextCursor: page.nextCursor,kanbanOutput: kanbanOutput.data?.kanbanOutput ?? "qrcode",locationId};}export default function KanbansRoute() {- const { count, kanbans, locationId, kanbanOutput } =+ const { count, kanbans, nextCursor, locationId, kanbanOutput } =useLoaderData<typeof loader>();return (@@ -104,6 +119,7 @@ export default function KanbansRoute() {<KanbansTabledata={kanbans}count={count}+ nextCursor={nextCursor}locationId={locationId}kanbanOutput={kanbanOutput}/>diff --git a/apps/erp/app/routes/x+/inventory+/picking-lists.tsx b/apps/erp/app/routes/x+/inventory+/picking-lists.tsxindex 70336facfb..64157ed4d9 100644--- a/apps/erp/app/routes/x+/inventory+/picking-lists.tsx+++ b/apps/erp/app/routes/x+/inventory+/picking-lists.tsx@@ -2,20 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getPickingLists } from "~/modules/inventory";import type { PickingList } from "~/modules/inventory/ui/PickingLists";import { PickingListsTable } from "~/modules/inventory/ui/PickingLists";import type { Handle } from "~/utils/handle";+import { pickingListsList } from "~/utils/list-registry/inventory.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["pickingList"],@@ -24,53 +20,24 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "inventory"+ return loadListPage(request, pickingListsList, {+ dataKey: "pickingLists",+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Error loading picking lists"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const status = searchParams.get("status");- const assignee = searchParams.get("assignee");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const pickingLists = await getPickingLists(client, companyId, {- search,- status,- assignee,- locationId: null,- limit,- offset,- sorts,- filters- });-- if (pickingLists.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(- request,- error(pickingLists.error, "Error loading picking lists")- )- );- }-- return {- pickingLists: pickingLists.data ?? [],- pickingListCount: pickingLists.count ?? 0- };}export default function PickingListsRoute() {- const { pickingLists, pickingListCount } = useLoaderData<typeof loader>();+ const { pickingLists, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full"><PickingListsTabledata={pickingLists as PickingList[]}- count={pickingListCount}+ count={count}+ nextCursor={nextCursor}/><RecordOutlet /></VStack>diff --git a/apps/erp/app/routes/x+/inventory+/quantities.tsx b/apps/erp/app/routes/x+/inventory+/quantities.tsxindex 0acb0498f6..d37f4ce3c7 100644--- a/apps/erp/app/routes/x+/inventory+/quantities.tsx+++ b/apps/erp/app/routes/x+/inventory+/quantities.tsx@@ -5,6 +5,7 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";import {RecordOutlet,ResizablePanel,@@ -19,7 +20,8 @@ import {expandStorageUnitIdsWithDescendants,getInventoryItems,getStorageTypesList,- getStorageUnitsList+ getStorageUnitsList,+ INVENTORY_ITEMS_PAGING} from "~/modules/inventory";import InventoryTable from "~/modules/inventory/ui/Inventory/InventoryTable";import {@@ -29,10 +31,14 @@ import {import { getLocationsList } from "~/modules/resources";import { getTagsList } from "~/modules/shared";import { getUserDefaults } from "~/modules/users/users.server";+import { toPage } from "~/utils/cursor";import type { Handle } from "~/utils/handle";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";+const logger = getLogger("erp", "inventory-quantities");+export const handle: Handle = {realtime: ["itemStockQuantities"]};@@ -47,8 +53,10 @@ export async function loader({ request }: LoaderFunctionArgs) {const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =+ const { limit, cursor, sorts, filters } =getGenericQueryFilters(searchParams);+ // A later page (`?after=`) is read for its rows only: skip the option lists.+ const isFirstPage = !cursor;const storageUnitFilter = filters?.find((f) => f.column === "storageUnitIds" && f.value@@ -103,18 +111,25 @@ export async function loader({ request }: LoaderFunctionArgs) {getInventoryItems(client, locationId, companyId, {search,limit,- offset,+ cursor,sorts,filters}),- getMaterialFormsList(client, companyId),- getMaterialSubstancesList(client, companyId),- getTagsList(client, companyId),- getStorageTypesList(client, companyId),- getStorageUnitsList(client, companyId)+ isFirstPage ? getMaterialFormsList(client, companyId) : null,+ isFirstPage ? getMaterialSubstancesList(client, companyId) : null,+ isFirstPage ? getTagsList(client, companyId) : null,+ isFirstPage ? getStorageTypesList(client, companyId) : null,+ isFirstPage ? getStorageUnitsList(client, companyId) : null]);if (inventoryItems.error) {+ if (cursor) {+ logger.error("Failed to load a later page of inventory items", {+ companyId,+ error: inventoryItems.error+ });+ return listErrorPage("inventoryItems");+ }throw redirect(path.to.authenticatedRoot,await flash(@@ -124,17 +139,24 @@ export async function loader({ request }: LoaderFunctionArgs) {);}- const uniqueTags = pluckUnique(tags.data, (t) => t.name);+ const uniqueTags = pluckUnique(tags?.data, (t) => t.name);++ const page = toPage(+ inventoryItems.data ?? [],+ { limit, sorts },+ INVENTORY_ITEMS_PAGING+ );return {count: inventoryItems.count ?? 0,- inventoryItems: (inventoryItems.data ?? []) as InventoryItem[],+ inventoryItems: page.rows as InventoryItem[],+ nextCursor: page.nextCursor,locationId,- forms: forms.data ?? [],- substances: substances.data ?? [],+ forms: forms?.data ?? [],+ substances: substances?.data ?? [],tags: uniqueTags,- storageTypes: storageTypes.data ?? [],- storageUnits: storageUnits.data ?? []+ storageTypes: storageTypes?.data ?? [],+ storageUnits: storageUnits?.data ?? []};}@@ -142,6 +164,7 @@ export default function QuantitiesRoute() {const {count,inventoryItems,+ nextCursor,locationId,forms,substances,@@ -162,6 +185,7 @@ export default function QuantitiesRoute() {<InventoryTabledata={inventoryItems}count={count}+ nextCursor={nextCursor}locationId={locationId}forms={forms}substances={substances}diff --git a/apps/erp/app/routes/x+/inventory+/receipts.tsx b/apps/erp/app/routes/x+/inventory+/receipts.tsxindex 267d63e462..85651fdd1c 100644--- a/apps/erp/app/routes/x+/inventory+/receipts.tsx+++ b/apps/erp/app/routes/x+/inventory+/receipts.tsx@@ -2,18 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getReceipts, ReceiptsTable } from "~/modules/inventory";+import { ReceiptsTable } from "~/modules/inventory";import type { Handle } from "~/utils/handle";+import { receiptsList } from "~/utils/list-registry/inventory.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["receipt"],@@ -22,43 +19,21 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "inventory"+ return loadListPage(request, receiptsList, {+ dataKey: "receipts",+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Error loading receipts"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const receipts = await getReceipts(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (receipts.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(request, error(null, "Error loading receipts"))- );- }-- return {- receipts: receipts.data ?? [],- count: receipts.count ?? 0- };}export default function ReceiptsRoute() {- const { receipts, count } = useLoaderData<typeof loader>();+ const { receipts, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ReceiptsTable data={receipts} count={count ?? 0} />+ <ReceiptsTable data={receipts} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/inventory+/shipments.tsx b/apps/erp/app/routes/x+/inventory+/shipments.tsxindex b4b323e0a1..0f2340c5a6 100644--- a/apps/erp/app/routes/x+/inventory+/shipments.tsx+++ b/apps/erp/app/routes/x+/inventory+/shipments.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getShipments } from "~/modules/inventory";import ShipmentsTable from "~/modules/inventory/ui/Shipments/ShipmentsTable";import type { Handle } from "~/utils/handle";+import { shipmentsList } from "~/utils/list-registry/inventory.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["shipment"],@@ -23,43 +19,21 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "inventory"+ return loadListPage(request, shipmentsList, {+ dataKey: "shipments",+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Error loading shipments"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const shipments = await getShipments(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (shipments.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(request, error(null, "Error loading shipments"))- );- }-- return {- shipments: shipments.data ?? [],- count: shipments.count ?? 0- };}export default function ShipmentsRoute() {- const { shipments, count } = useLoaderData<typeof loader>();+ const { shipments, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ShipmentsTable data={shipments} count={count ?? 0} />+ <ShipmentsTable data={shipments} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/inventory+/shipping-methods.tsx b/apps/erp/app/routes/x+/inventory+/shipping-methods.tsxindex dbf2e2340b..572f37a462 100644--- a/apps/erp/app/routes/x+/inventory+/shipping-methods.tsx+++ b/apps/erp/app/routes/x+/inventory+/shipping-methods.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getAccountsList } from "~/modules/accounting";-import { getShippingMethods, ShippingMethodsTable } from "~/modules/inventory";+import { ShippingMethodsTable } from "~/modules/inventory";import type { Handle } from "~/utils/handle";+import { shippingMethodsList } from "~/utils/list-registry/inventory.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Shipping Methods`,@@ -22,50 +18,25 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId, companyGroupId } = await requirePermissions(- request,- {- view: "inventory",- role: "employee"+ return loadListPage(request, shippingMethodsList, {+ dataKey: "shippingMethods",+ onError: {+ redirectTo: path.to.inventory,+ message: "Error loading shipping methods"}- );-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [shippingMethods] = await Promise.all([- getShippingMethods(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getAccountsList(client, companyGroupId)- ]);-- if (shippingMethods.error) {- throw redirect(- path.to.inventory,- await flash(request, error(null, "Error loading shipping methods"))- );- }-- return {- shippingMethods: shippingMethods.data ?? [],- count: shippingMethods.count ?? 0- };+ });}export default function ShippingMethodsRoute() {- const { shippingMethods, count } = useLoaderData<typeof loader>();+ const { shippingMethods, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ShippingMethodsTable data={shippingMethods ?? []} count={count ?? 0} />+ <ShippingMethodsTable+ data={shippingMethods}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/inventory+/stock-movements.tsx b/apps/erp/app/routes/x+/inventory+/stock-movements.tsxindex a8ab0b140f..4766e784d9 100644--- a/apps/erp/app/routes/x+/inventory+/stock-movements.tsx+++ b/apps/erp/app/routes/x+/inventory+/stock-movements.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getStockMovements } from "~/modules/inventory";import StockMovementsTable from "~/modules/inventory/ui/StockMovements/StockMovementsTable";import type { Handle } from "~/utils/handle";+import { stockMovementsList } from "~/utils/list-registry/inventory.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["itemLedger"],@@ -23,46 +19,25 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "inventory"+ return loadListPage(request, stockMovementsList, {+ dataKey: "movements",+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Error loading stock movements"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const movements = await getStockMovements(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (movements.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(- request,- error(movements.error, "Error loading stock movements")- )- );- }-- return {- movements: movements.data ?? [],- count: movements.count ?? 0- };}export default function StockMovementsRoute() {- const { movements, count } = useLoaderData<typeof loader>();+ const { movements, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <StockMovementsTable data={movements} count={count ?? 0} />+ <StockMovementsTable+ data={movements}+ count={count}+ nextCursor={nextCursor}+ /></VStack>);}diff --git a/apps/erp/app/routes/x+/inventory+/stock-transfers.tsx b/apps/erp/app/routes/x+/inventory+/stock-transfers.tsxindex 7185f2b6f7..dc00f1483d 100644--- a/apps/erp/app/routes/x+/inventory+/stock-transfers.tsx+++ b/apps/erp/app/routes/x+/inventory+/stock-transfers.tsx@@ -11,11 +11,13 @@ import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getStockTransfers } from "~/modules/inventory";+import { getStockTransfers, STOCK_TRANSFERS_PAGING } from "~/modules/inventory";import StockTransfersTable from "~/modules/inventory/ui/StockTransfers/StockTransfersTable";import { getLocationsList } from "~/modules/resources";import { getUserDefaults } from "~/modules/users/users.server";+import { toPage } from "~/utils/cursor";import type { Handle } from "~/utils/handle";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";@@ -35,7 +37,7 @@ export async function loader({ request }: LoaderFunctionArgs) {const url = new URL(request.url);const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =+ const { limit, cursor, sorts, filters } =getGenericQueryFilters(searchParams);let locationId = searchParams.get("location");@@ -73,12 +75,19 @@ export async function loader({ request }: LoaderFunctionArgs) {locationId,search,limit,- offset,+ cursor,sorts,filters});if (stockTransfers.error) {+ if (cursor) {+ logger.error("Failed to load a later page of stock transfers", {+ companyId,+ error: stockTransfers.error+ });+ return listErrorPage("stockTransfers");+ }logger.error(stockTransfers.error);throw redirect(path.to.authenticatedRoot,@@ -86,21 +95,30 @@ export async function loader({ request }: LoaderFunctionArgs) {);}+ const page = toPage(+ stockTransfers.data ?? [],+ { limit, sorts },+ STOCK_TRANSFERS_PAGING+ );+return {- stockTransfers: stockTransfers.data ?? [],+ stockTransfers: page.rows,count: stockTransfers.count ?? 0,+ nextCursor: page.nextCursor,locationId};}export default function StockTransfersRoute() {- const { stockTransfers, count, locationId } = useLoaderData<typeof loader>();+ const { stockTransfers, count, nextCursor, locationId } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full"><StockTransfersTabledata={stockTransfers}- count={count ?? 0}+ count={count}+ nextCursor={nextCursor}locationId={locationId}/><RecordOutlet />diff --git a/apps/erp/app/routes/x+/inventory+/storage-rules.tsx b/apps/erp/app/routes/x+/inventory+/storage-rules.tsxindex 58d0ec21c8..573dfc52c2 100644--- a/apps/erp/app/routes/x+/inventory+/storage-rules.tsx+++ b/apps/erp/app/routes/x+/inventory+/storage-rules.tsx@@ -18,6 +18,7 @@ import {getEnforcementRules} from "~/modules/shared";import type { Handle } from "~/utils/handle";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";export const handle: Handle = {@@ -33,7 +34,7 @@ export async function loader({ request }: LoaderFunctionArgs) {const rules = await getEnforcementRules(client, "storage", companyId, {search: null,- limit: 1000,+ limit: SINGLE_LOAD_LIMIT,offset: 0,sorts: []});diff --git a/apps/erp/app/routes/x+/inventory+/storage-types.tsx b/apps/erp/app/routes/x+/inventory+/storage-types.tsxindex 681a8f2895..ccbfd2d033 100644--- a/apps/erp/app/routes/x+/inventory+/storage-types.tsx+++ b/apps/erp/app/routes/x+/inventory+/storage-types.tsx@@ -2,22 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { getLogger } from "@carbon/logger";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getStorageTypes } from "~/modules/inventory";import StorageTypesTable from "~/modules/inventory/ui/StorageTypes/StorageTypesTable";import type { Handle } from "~/utils/handle";+import { storageTypesList } from "~/utils/list-registry/inventory.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";--const logger = getLogger("erp", "storage-types");export const handle: Handle = {breadcrumb: msg`Storage Types`,@@ -25,45 +18,25 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const storageTypes = await getStorageTypes(client, companyId, {- limit,- offset,- sorts,- search,- filters+ return loadListPage(request, storageTypesList, {+ dataKey: "storageTypes",+ onError: {+ redirectTo: path.to.inventory,+ message: "Error loading storage types"+ }});-- if (storageTypes.error) {- logger.error(storageTypes.error);- throw redirect(- path.to.inventory,- await flash(request, error(null, "Error loading storage types"))- );- }-- return {- storageTypes: storageTypes.data ?? [],- count: storageTypes.count ?? 0- };}export default function StorageTypesRoute() {- const { storageTypes, count } = useLoaderData<typeof loader>();+ const { storageTypes, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <StorageTypesTable data={storageTypes} count={count ?? 0} />+ <StorageTypesTable+ data={storageTypes}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/inventory+/storage-units.tsx b/apps/erp/app/routes/x+/inventory+/storage-units.tsxindex 4ff21d07fe..a059e1f8bd 100644--- a/apps/erp/app/routes/x+/inventory+/storage-units.tsx+++ b/apps/erp/app/routes/x+/inventory+/storage-units.tsx@@ -21,6 +21,7 @@ import StorageUnitsTable from "~/modules/inventory/ui/StorageUnits/StorageUnitsTimport { getLocationsList } from "~/modules/resources";import { getUserDefaults } from "~/modules/users/users.server";import type { Handle } from "~/utils/handle";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";@@ -34,6 +35,10 @@ export const handle: Handle = {// Nodes below this still render with an expand chevron and lazy-load on click.const EAGER_EXPAND_MAX_DEPTH = 5;+// The tree cannot page: the Table would append a later page's rows flat,+// outside their parents. So the roots load at once: the first+// SINGLE_LOAD_LIMIT of them.+export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId, userId } = await requirePermissions(request, {view: "inventory",@@ -44,8 +49,7 @@ export async function loader({ request }: LoaderFunctionArgs) {const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);+ const { sorts, filters } = getGenericQueryFilters(searchParams);let locationId = searchParams.get("location");@@ -93,6 +97,7 @@ export async function loader({ request }: LoaderFunctionArgs) {let rows: any[];let count: number;let initialExpanded: string[] = [];+ let isTruncated = false;if (search) {const searchResult = await searchStorageUnitsWithAncestors(@@ -118,7 +123,7 @@ export async function loader({ request }: LoaderFunctionArgs) {client,companyId,locationId,- { search, limit, offset, sorts, filters }+ { search, limit: SINGLE_LOAD_LIMIT, offset: 0, sorts, filters });if (rootsResult.error) {throw redirect(@@ -131,12 +136,13 @@ export async function loader({ request }: LoaderFunctionArgs) {}const roots = rootsResult.data ?? [];count = rootsResult.count ?? 0;+ isTruncated = roots.length >= SINGLE_LOAD_LIMIT;- // Eagerly load the subtrees of the visible (paginated) roots so the tree- // renders expanded by default instead of lazily loading one level at a- // time. Pagination still applies to roots; each shown root just arrives- // with its descendants. The depth cap bounds how much of a deep tree we- // pull (and pre-expand) up front — anything below it still lazy-loads.+ // Eagerly load the subtrees of the roots so the tree renders expanded by+ // default instead of lazily loading one level at a time. Each root+ // arrives with its descendants. The depth cap bounds how much of a deep+ // tree we pull (and pre-expand) up front — anything below it still+ // lazy-loads.const descendants = await getStorageUnitSubtrees(client,companyId,@@ -174,7 +180,8 @@ export async function loader({ request }: LoaderFunctionArgs) {initialExpanded,locations: locationsList.data,locationId,- storageTypes: storageTypesList.data ?? []+ storageTypes: storageTypesList.data ?? [],+ isTruncated};}@@ -186,7 +193,8 @@ export default function StorageUnitsRoute() {initialExpanded,locations,locationId,- storageTypes+ storageTypes,+ isTruncated} = useLoaderData<typeof loader>();// storageUnits comes from storageUnits_recursive (a view) so every column@@ -208,6 +216,7 @@ export default function StorageUnitsRoute() {<StorageUnitsTabledata={rows}count={count}+ isTruncated={isTruncated}locations={locations}locationId={locationId}storageTypes={storageTypes}diff --git a/apps/erp/app/routes/x+/inventory+/tracked-entities.tsx b/apps/erp/app/routes/x+/inventory+/tracked-entities.tsxindex 0f6e9b1a75..89110655fa 100644--- a/apps/erp/app/routes/x+/inventory+/tracked-entities.tsx+++ b/apps/erp/app/routes/x+/inventory+/tracked-entities.tsx@@ -2,20 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getTrackedEntities } from "~/modules/inventory";import TrackedEntitiesTable from "~/modules/inventory/ui/Traceability/TrackedEntitiesTable";import { getCompanySettings } from "~/modules/settings";import type { Handle } from "~/utils/handle";+import { trackedEntitiesList } from "~/utils/list-registry/inventory.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["trackedEntity"],@@ -24,100 +20,67 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "inventory",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [trackedEntities, companySettings] = await Promise.all([- getTrackedEntities(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getCompanySettings(client, companyId)- ]);-- if (trackedEntities.error) {- throw redirect(- path.to.inventory,- await flash(request, error(null, "Error loading tracked entities"))- );- }-- const inventoryShelfLife = companySettings.data?.inventoryShelfLife as {- nearExpiryWarningDays?: number | null;- } | null;-- // Pull the shelf-life policy for every item that shows up in the table so- // the Expiry trace popover can render the Policy step without an extra- // round-trip per row. Keyed by itemId.- const itemIds = Array.from(- new Set(- (trackedEntities.data ?? [])- .map((te) => te.itemId)- .filter((id): id is string => !!id)- )- );- const shelfLifeRows =- itemIds.length > 0- ? await client- .from("itemShelfLife")- .select("itemId, mode, days, calculateFromBom")- .in("itemId", itemIds)- : {- data: [] as {- itemId: string;- mode: string;- days: number | null;- calculateFromBom: boolean | null;- }[]- };- const shelfLifePolicies: Record<- string,- {- mode: string;- days: number | null;- calculateFromBom: boolean | null;- }- > = {};- for (const row of shelfLifeRows.data ?? []) {- if (row.itemId) {- shelfLifePolicies[row.itemId] = {- mode: row.mode,- days: row.days ?? null,- calculateFromBom: row.calculateFromBom ?? false+ return loadListPage(request, trackedEntitiesList, {+ dataKey: "trackedEntities",+ firstPage: async ({ client, companyId }) => {+ const companySettings = await getCompanySettings(client, companyId);+ const inventoryShelfLife = companySettings.data?.inventoryShelfLife as {+ nearExpiryWarningDays?: number | null;+ } | null;+ return {+ nearExpiryWarningDays: inventoryShelfLife?.nearExpiryWarningDays ?? null};+ },+ // The shelf-life policy of each row's item, so the Expiry trace popover+ // can render the Policy step without an extra round-trip per row.+ mapRows: async (trackedEntities, { client }) => {+ const itemIds = Array.from(+ new Set(+ trackedEntities+ .map((te) => te.itemId)+ .filter((id): id is string => !!id)+ )+ );+ const shelfLifeRows =+ itemIds.length > 0+ ? await client+ .from("itemShelfLife")+ .select("itemId, mode, days, calculateFromBom")+ .in("itemId", itemIds)+ : { data: [] };+ const policyByItemId = new Map(+ (shelfLifeRows.data ?? []).map((row) => [+ row.itemId,+ {+ mode: row.mode,+ days: row.days ?? null,+ calculateFromBom: row.calculateFromBom ?? false+ }+ ])+ );+ return trackedEntities.map((te) => ({+ ...te,+ shelfLifePolicy: (te.itemId && policyByItemId.get(te.itemId)) || null+ }));+ },+ onError: {+ redirectTo: path.to.inventory,+ message: "Error loading tracked entities"}- }-- return {- trackedEntities: trackedEntities.data ?? [],- count: trackedEntities.count ?? 0,- nearExpiryWarningDays: inventoryShelfLife?.nearExpiryWarningDays ?? null,- shelfLifePolicies- };+ });}export default function TraceabilityRoute() {- const { trackedEntities, count, nearExpiryWarningDays, shelfLifePolicies } =+ const { trackedEntities, count, nextCursor, nearExpiryWarningDays } =useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full"><TrackedEntitiesTable- data={trackedEntities ?? []}- count={count ?? 0}+ data={trackedEntities}+ count={count}+ nextCursor={nextCursor}nearExpiryWarningDays={nearExpiryWarningDays ?? null}- shelfLifePolicies={shelfLifePolicies ?? {}}/></VStack>);diff --git a/apps/erp/app/routes/x+/inventory+/warehouse-transfers.tsx b/apps/erp/app/routes/x+/inventory+/warehouse-transfers.tsxindex b8b29cc20e..060ee024bb 100644--- a/apps/erp/app/routes/x+/inventory+/warehouse-transfers.tsx+++ b/apps/erp/app/routes/x+/inventory+/warehouse-transfers.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getWarehouseTransfers } from "~/modules/inventory";import WarehouseTransfersTable from "~/modules/inventory/ui/WarehouseTransfers/WarehouseTransfersTable";import type { Handle } from "~/utils/handle";+import { warehouseTransfersList } from "~/utils/list-registry/inventory.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["warehouseTransfer"],@@ -23,43 +19,26 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "inventory"+ return loadListPage(request, warehouseTransfersList, {+ dataKey: "warehouseTransfers",+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Error loading warehouse transfers"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const warehouseTransfers = await getWarehouseTransfers(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (warehouseTransfers.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(request, error(null, "Error loading warehouse transfers"))- );- }-- return {- warehouseTransfers: warehouseTransfers.data ?? [],- count: warehouseTransfers.count ?? 0- };}export default function WarehouseTransfersRoute() {- const { warehouseTransfers, count } = useLoaderData<typeof loader>();+ const { warehouseTransfers, count, nextCursor } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <WarehouseTransfersTable data={warehouseTransfers} count={count ?? 0} />+ <WarehouseTransfersTable+ data={warehouseTransfers}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/inventory-count+/$id.tsx b/apps/erp/app/routes/x+/inventory-count+/$id.tsxindex 5bf8062616..6dfb6086b3 100644--- a/apps/erp/app/routes/x+/inventory-count+/$id.tsx+++ b/apps/erp/app/routes/x+/inventory-count+/$id.tsx@@ -5,6 +5,7 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";import { RecordOutlet } from "@carbon/react";import { pluckUnique, redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";@@ -17,6 +18,7 @@ import {getInventoryCountMovements,getStorageTypesList,getStorageUnitsListForLocation,+ INVENTORY_COUNT_LINES_PAGING,InventoryCountDetails} from "~/modules/inventory";import {@@ -24,10 +26,14 @@ import {getMaterialSubstancesList} from "~/modules/items";import { getTagsList } from "~/modules/shared";+import { toPage } from "~/utils/cursor";import { detailBreadcrumb, type Handle } from "~/utils/handle";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";+const logger = getLogger("erp", "inventory-count");+export const handle: Handle = {realtime: [{ table: "inventoryCount", column: "id", param: "id" },@@ -62,18 +68,27 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const url = new URL(request.url);const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =+ const { limit, cursor, sorts, filters } =getGenericQueryFilters(searchParams);+ // A later page (`?after=`) is read for its rows only: skip the summary,+ // the movements and the option lists.+ const isFirstPage = !cursor;// True blind counting: the system quantity (and the variance it can be// derived from) must not reach the client until the count is Posted. That// includes filtering on them — a crafted ?filter=systemQuantity:gt:0 would- // reveal which lines have stock — so drop those filters while blind.+ // reveal which lines have stock — so drop those filters while blind. The+ // same goes for sorts: the next-page cursor holds the last row's sort values.const isBlindEntry =inventoryCount.data.isBlind && inventoryCount.data.status !== "Posted";+ const isWithheld = (column: string) =>+ ["systemQuantity", "variance"].includes(column);const allowedFilters = isBlindEntry- ? filters?.filter((f) => !["systemQuantity", "variance"].includes(f.column))+ ? filters?.filter((f) => !isWithheld(f.column)): filters;+ const allowedSorts = isBlindEntry+ ? sorts?.filter((s) => !isWithheld(s.sortBy))+ : sorts;const [lines,@@ -88,30 +103,46 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getInventoryCountLines(client, id, companyId, {search,limit,- offset,- sorts,+ cursor,+ sorts: allowedSorts,filters: allowedFilters}),- getInventoryCountLineSummary(client, id, companyId),+ isFirstPage ? getInventoryCountLineSummary(client, id, companyId) : null,// Adjustments this count has posted (empty for a never-posted Draft).- getInventoryCountMovements(client, companyId, id),+ isFirstPage ? getInventoryCountMovements(client, companyId, id) : null,// Option lists for the count-line column filters (same set the quantities// screen loads).- getMaterialFormsList(client, companyId),- getMaterialSubstancesList(client, companyId),- getTagsList(client, companyId),- getStorageTypesList(client, companyId),- getStorageUnitsListForLocation(- client,- companyId,- inventoryCount.data.locationId- )+ isFirstPage ? getMaterialFormsList(client, companyId) : null,+ isFirstPage ? getMaterialSubstancesList(client, companyId) : null,+ isFirstPage ? getTagsList(client, companyId) : null,+ isFirstPage ? getStorageTypesList(client, companyId) : null,+ isFirstPage+ ? getStorageUnitsListForLocation(+ client,+ companyId,+ inventoryCount.data.locationId+ )+ : null]);+ if (lines.error && cursor) {+ logger.error("Failed to load a later page of inventory count lines", {+ companyId,+ error: lines.error+ });+ return listErrorPage("lines");+ }++ const page = toPage(+ lines.data ?? [],+ { limit, sorts: allowedSorts },+ INVENTORY_COUNT_LINES_PAGING+ );+// Hiding the columns client-side isn't enough — the values would ship in the// loader payload and CSV export. Strip them server-side through Draft AND// Pending; they are revealed only once Posted.- const lineData = (lines.data ?? []).map((line) =>+ const lineData = page.rows.map((line) =>isBlindEntry? // Withhold System Qty (and the variance it can be derived from). Use null,// not 0, so it reads as "not available" (blank / "—" in the UI and CSV)@@ -124,13 +155,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {inventoryCount: inventoryCount.data,lines: lineData,count: lines.count ?? 0,- summary,- movements: movements.data ?? [],- forms: forms.data ?? [],- substances: substances.data ?? [],- tags: pluckUnique(tags.data, (tag) => tag.name),- storageTypes: storageTypes.data ?? [],- storageUnits: storageUnits.data ?? []+ nextCursor: page.nextCursor,+ summary: summary ?? { uncounted: 0, variances: 0 },+ movements: movements?.data ?? [],+ forms: forms?.data ?? [],+ substances: substances?.data ?? [],+ tags: pluckUnique(tags?.data, (tag) => tag.name),+ storageTypes: storageTypes?.data ?? [],+ storageUnits: storageUnits?.data ?? []};}@@ -139,6 +171,7 @@ export default function InventoryCountDetailRoute() {inventoryCount,lines,count,+ nextCursor,summary,movements,forms,@@ -155,6 +188,7 @@ export default function InventoryCountDetailRoute() {inventoryCount={inventoryCount}lines={lines}count={count}+ nextCursor={nextCursor}summary={summary}movements={movements}forms={forms}diff --git a/apps/erp/app/routes/x+/invoicing+/_index.tsx b/apps/erp/app/routes/x+/invoicing+/_index.tsxindex c603f57128..bf7952d22b 100644--- a/apps/erp/app/routes/x+/invoicing+/_index.tsx+++ b/apps/erp/app/routes/x+/invoicing+/_index.tsx@@ -94,7 +94,7 @@ export async function loader({ request }: LoaderFunctionArgs) {customerId: null,supplierId: null,limit: 6,- offset: 0,+ cursor: null,sorts,filters})@@ -108,7 +108,11 @@ export async function loader({ request }: LoaderFunctionArgs) {ap: sumAging((apAging.data ?? []) as AgingRow[]),arTieOut: arTieOut.data ?? null,apTieOut: apTieOut.data ?? null,- recentPayments: (payments.data ?? []) as unknown as RecentPayment[]+ // The query reads one row past `limit` (the next-page check); drop it.+ recentPayments: (payments.data ?? []).slice(+ 0,+ 6+ ) as unknown as RecentPayment[]};}diff --git a/apps/erp/app/routes/x+/invoicing+/charges.tsx b/apps/erp/app/routes/x+/invoicing+/charges.tsxindex a0a7e52c5d..13fbaf8edc 100644--- a/apps/erp/app/routes/x+/invoicing+/charges.tsx+++ b/apps/erp/app/routes/x+/invoicing+/charges.tsx@@ -2,18 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { ChargesTable, getCharges } from "~/modules/invoicing";+import { ChargesTable } from "~/modules/invoicing";import type { Handle } from "~/utils/handle";+import { chargesList } from "~/utils/list-registry/invoicing.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Charges`,@@ -22,57 +19,20 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "invoicing"+ return loadListPage(request, chargesList, {+ dataKey: "data",+ onError: {+ redirectTo: path.to.invoicing,+ message: "Failed to fetch charges"+ }});-- const url = new URL(request.url);- const searchParams = url.searchParams;- const search = searchParams.get("search");- const type = searchParams.get("type") as- | "Charge"- | "Credit"- | "Payment"- | "Cashback"- | "Repayment"- | null;- const status = searchParams.get("status") as- | "Draft"- | "Posted"- | "Voided"- | null;-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const charges = await getCharges(client, companyId, {- search,- type,- status,- limit,- offset,- sorts,- filters- });-- if (charges.error) {- throw redirect(- path.to.invoicing,- await flash(request, error(charges.error, "Failed to fetch charges"))- );- }-- return {- count: charges.count ?? 0,- data: charges.data ?? []- };}export default function ChargesRoute() {- const { count, data } = useLoaderData<typeof loader>();+ const { count, data, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ChargesTable data={data} count={count} />+ <ChargesTable data={data} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/invoicing+/credit-memos.tsx b/apps/erp/app/routes/x+/invoicing+/credit-memos.tsxindex 038562c83a..977ca91400 100644--- a/apps/erp/app/routes/x+/invoicing+/credit-memos.tsx+++ b/apps/erp/app/routes/x+/invoicing+/credit-memos.tsx@@ -2,17 +2,14 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getMemos, MemosTable } from "~/modules/invoicing";+import { MemosTable } from "~/modules/invoicing";import type { Handle } from "~/utils/handle";+import { creditMemosList } from "~/utils/list-registry/invoicing.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";// Accounts Receivable — customer credit/debit memos. The supplier side lives in// supplier-credits.tsx; both read the same `memo` table, scoped by party.@@ -23,61 +20,23 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "invoicing"+ return loadListPage(request, creditMemosList, {+ dataKey: "memos",+ onError: {+ redirectTo: path.to.invoicing,+ message: "Failed to fetch credit memos"+ }});-- const url = new URL(request.url);- const searchParams = url.searchParams;- const search = searchParams.get("search");- const direction = searchParams.get("direction") as "Credit" | "Debit" | null;- const status = searchParams.get("status") as- | "Draft"- | "Posted"- | "Voided"- | null;-- const {- limit,- offset,- sorts,- filters = []- } = getGenericQueryFilters(searchParams);-- // The "Customer" column filter is keyed as "counterparty"; pull it out and- // hand it to getMemos, which applies it to customerId. The rest pass through.- const counterpartyIds = filters- .filter((f) => f.column === "counterparty")- .flatMap((f) => (f.value ?? "").split(","))- .filter(Boolean);- const passThroughFilters = filters.filter((f) => f.column !== "counterparty");-- const memos = await getMemos(client, companyId, {- search,- direction,- status,- party: "customer",- counterpartyIds: counterpartyIds.length > 0 ? counterpartyIds : null,- limit,- offset,- sorts,- filters: passThroughFilters- });-- if (memos.error) {- throw redirect(- path.to.invoicing,- await flash(request, error(memos.error, "Failed to fetch credit memos"))- );- }-- return {- count: memos.count ?? 0,- memos: memos.data ?? []- };}export default function CreditMemosRoute() {- const { count, memos } = useLoaderData<typeof loader>();- return <MemosTable data={memos} count={count} party="customer" />;+ const { count, memos, nextCursor } = useLoaderData<typeof loader>();+ return (+ <MemosTable+ data={memos}+ count={count}+ nextCursor={nextCursor}+ party="customer"+ />+ );}diff --git a/apps/erp/app/routes/x+/invoicing+/payments.tsx b/apps/erp/app/routes/x+/invoicing+/payments.tsxindex e16dedad61..5a658942d8 100644--- a/apps/erp/app/routes/x+/invoicing+/payments.tsx+++ b/apps/erp/app/routes/x+/invoicing+/payments.tsx@@ -2,17 +2,14 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getPayments, PaymentsTable } from "~/modules/invoicing";+import { PaymentsTable } from "~/modules/invoicing";import type { Handle } from "~/utils/handle";+import { paymentsList } from "~/utils/list-registry/invoicing.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["payment"],@@ -22,68 +19,18 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "invoicing"+ return loadListPage(request, paymentsList, {+ dataKey: "payments",+ onError: {+ redirectTo: path.to.invoicing,+ message: "Failed to fetch payments"+ }});-- const url = new URL(request.url);- const searchParams = url.searchParams;- const search = searchParams.get("search");- const paymentType = searchParams.get("paymentType") as- | "Receipt"- | "Disbursement"- | null;- const status = searchParams.get("status") as- | "Draft"- | "Posted"- | "Voided"- | null;- const customerId = searchParams.get("customerId");- const supplierId = searchParams.get("supplierId");-- const {- limit,- offset,- sorts,- filters = []- } = getGenericQueryFilters(searchParams);-- // The "Counterparty" column filter spans two columns (customerId OR- // supplierId), so pull it out of the generic filters and hand it to- // getPayments, which applies it as an OR. The rest pass through normally.- const counterpartyIds = filters- .filter((f) => f.column === "counterparty")- .flatMap((f) => (f.value ?? "").split(","))- .filter(Boolean);- const passThroughFilters = filters.filter((f) => f.column !== "counterparty");-- const payments = await getPayments(client, companyId, {- search,- paymentType,- status,- customerId,- supplierId,- counterpartyIds: counterpartyIds.length > 0 ? counterpartyIds : null,- limit,- offset,- sorts,- filters: passThroughFilters- });-- if (payments.error) {- throw redirect(- path.to.invoicing,- await flash(request, error(payments.error, "Failed to fetch payments"))- );- }-- return {- count: payments.count ?? 0,- payments: payments.data ?? []- };}export default function PaymentsRoute() {- const { count, payments } = useLoaderData<typeof loader>();- return <PaymentsTable data={payments} count={count} />;+ const { count, payments, nextCursor } = useLoaderData<typeof loader>();+ return (+ <PaymentsTable data={payments} count={count} nextCursor={nextCursor} />+ );}diff --git a/apps/erp/app/routes/x+/invoicing+/purchasing.tsx b/apps/erp/app/routes/x+/invoicing+/purchasing.tsxindex 6bef4a1b16..88e560a71e 100644--- a/apps/erp/app/routes/x+/invoicing+/purchasing.tsx+++ b/apps/erp/app/routes/x+/invoicing+/purchasing.tsx@@ -2,21 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import {- getPurchaseInvoices,- PurchaseInvoicesTable-} from "~/modules/invoicing";+import { PurchaseInvoicesTable } from "~/modules/invoicing";import type { Handle } from "~/utils/handle";+import { purchaseInvoicesList } from "~/utils/list-registry/invoicing.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["purchaseInvoice"],@@ -26,49 +20,26 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "invoicing"+ return loadListPage(request, purchaseInvoicesList, {+ dataKey: "purchaseInvoices",+ onError: {+ redirectTo: path.to.invoicing,+ message: "Failed to fetch purchase invoices"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const supplierId = searchParams.get("supplierId");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const purchaseInvoices = await getPurchaseInvoices(client, companyId, {- search,- supplierId,- limit,- offset,- sorts,- filters- });-- if (purchaseInvoices.error) {- redirect(- path.to.invoicing,- await flash(- request,- error(purchaseInvoices.error, "Failed to fetch purchase invoices")- )- );- }-- return {- count: purchaseInvoices.count ?? 0,- purchaseInvoices: purchaseInvoices.data ?? []- };}export default function InvoicingPurchaseInvoicesRoute() {- const { count, purchaseInvoices } = useLoaderData<typeof loader>();+ const { count, purchaseInvoices, nextCursor } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <PurchaseInvoicesTable data={purchaseInvoices} count={count} />+ <PurchaseInvoicesTable+ data={purchaseInvoices}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/invoicing+/reimbursements.tsx b/apps/erp/app/routes/x+/invoicing+/reimbursements.tsxindex 26e72b8eee..ee4118279e 100644--- a/apps/erp/app/routes/x+/invoicing+/reimbursements.tsx+++ b/apps/erp/app/routes/x+/invoicing+/reimbursements.tsx@@ -2,18 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getReimbursements, ReimbursementsTable } from "~/modules/invoicing";+import { ReimbursementsTable } from "~/modules/invoicing";import type { Handle } from "~/utils/handle";+import { reimbursementsList } from "~/utils/list-registry/invoicing.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Reimbursements`,@@ -22,56 +19,22 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "invoicing"+ return loadListPage(request, reimbursementsList, {+ dataKey: "data",+ onError: {+ redirectTo: path.to.invoicing,+ message: "Failed to fetch reimbursements"+ }});-- const url = new URL(request.url);- const searchParams = url.searchParams;- const search = searchParams.get("search");- const status = searchParams.get("status") as- | "Draft"- | "Posted"- | "Voided"- | null;- const employeeId = searchParams.get("employeeId");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const reimbursements = await getReimbursements(client, companyId, {- search,- status,- employeeId,- limit,- offset,- sorts,- filters- });-- if (reimbursements.error) {- throw redirect(- path.to.invoicing,- await flash(- request,- error(reimbursements.error, "Failed to fetch reimbursements")- )- );- }-- return {- count: reimbursements.count ?? 0,- data: reimbursements.data ?? []- };}export default function ReimbursementsRoute() {- const { count, data } = useLoaderData<typeof loader>();+ const { count, data, nextCursor } = useLoaderData<typeof loader>();// No <Outlet /> — unlike charges, the reimbursement detail is a full page of// its own rather than a Drawer child of this list.return (<VStack spacing={0} className="h-full">- <ReimbursementsTable data={data} count={count} />+ <ReimbursementsTable data={data} count={count} nextCursor={nextCursor} /></VStack>);}diff --git a/apps/erp/app/routes/x+/invoicing+/sales.tsx b/apps/erp/app/routes/x+/invoicing+/sales.tsxindex 0672d62467..aaf3a85059 100644--- a/apps/erp/app/routes/x+/invoicing+/sales.tsx+++ b/apps/erp/app/routes/x+/invoicing+/sales.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getSalesInvoices } from "~/modules/invoicing";import SalesInvoicesTable from "~/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable";import type { Handle } from "~/utils/handle";+import { salesInvoicesList } from "~/utils/list-registry/invoicing.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["salesInvoice"],@@ -24,49 +20,25 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "invoicing"+ return loadListPage(request, salesInvoicesList, {+ dataKey: "salesInvoices",+ onError: {+ redirectTo: path.to.invoicing,+ message: "Failed to fetch sales invoices"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const customerId = searchParams.get("customerId");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const salesInvoices = await getSalesInvoices(client, companyId, {- search,- customerId,- limit,- offset,- sorts,- filters- });-- if (salesInvoices.error) {- redirect(- path.to.invoicing,- await flash(- request,- error(salesInvoices.error, "Failed to fetch sales invoices")- )- );- }-- return {- count: salesInvoices.count ?? 0,- salesInvoices: salesInvoices.data ?? []- };}export default function InvoicingSalesInvoicesRoute() {- const { count, salesInvoices } = useLoaderData<typeof loader>();+ const { count, salesInvoices, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <SalesInvoicesTable data={salesInvoices} count={count} />+ <SalesInvoicesTable+ data={salesInvoices}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/invoicing+/supplier-credits.tsx b/apps/erp/app/routes/x+/invoicing+/supplier-credits.tsxindex 285c189dd4..178a422e6b 100644--- a/apps/erp/app/routes/x+/invoicing+/supplier-credits.tsx+++ b/apps/erp/app/routes/x+/invoicing+/supplier-credits.tsx@@ -2,17 +2,14 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getMemos, MemosTable } from "~/modules/invoicing";+import { MemosTable } from "~/modules/invoicing";import type { Handle } from "~/utils/handle";+import { supplierCreditsList } from "~/utils/list-registry/invoicing.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";// Accounts Payable — supplier credit/debit memos. The customer side lives in// credit-memos.tsx; both read the same `memo` table, scoped by party.@@ -23,64 +20,23 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "invoicing"+ return loadListPage(request, supplierCreditsList, {+ dataKey: "memos",+ onError: {+ redirectTo: path.to.invoicing,+ message: "Failed to fetch supplier credits"+ }});-- const url = new URL(request.url);- const searchParams = url.searchParams;- const search = searchParams.get("search");- const direction = searchParams.get("direction") as "Credit" | "Debit" | null;- const status = searchParams.get("status") as- | "Draft"- | "Posted"- | "Voided"- | null;-- const {- limit,- offset,- sorts,- filters = []- } = getGenericQueryFilters(searchParams);-- // The "Supplier" column filter is keyed as "counterparty"; pull it out and- // hand it to getMemos, which applies it to supplierId. The rest pass through.- const counterpartyIds = filters- .filter((f) => f.column === "counterparty")- .flatMap((f) => (f.value ?? "").split(","))- .filter(Boolean);- const passThroughFilters = filters.filter((f) => f.column !== "counterparty");-- const memos = await getMemos(client, companyId, {- search,- direction,- status,- party: "supplier",- counterpartyIds: counterpartyIds.length > 0 ? counterpartyIds : null,- limit,- offset,- sorts,- filters: passThroughFilters- });-- if (memos.error) {- throw redirect(- path.to.invoicing,- await flash(- request,- error(memos.error, "Failed to fetch supplier credits")- )- );- }-- return {- count: memos.count ?? 0,- memos: memos.data ?? []- };}export default function SupplierCreditsRoute() {- const { count, memos } = useLoaderData<typeof loader>();- return <MemosTable data={memos} count={count} party="supplier" />;+ const { count, memos, nextCursor } = useLoaderData<typeof loader>();+ return (+ <MemosTable+ data={memos}+ count={count}+ nextCursor={nextCursor}+ party="supplier"+ />+ );}diff --git a/apps/erp/app/routes/x+/items+/change-notice-actions.tsx b/apps/erp/app/routes/x+/items+/change-notice-actions.tsxindex 394dc4830e..00aa8f89df 100644--- a/apps/erp/app/routes/x+/items+/change-notice-actions.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice-actions.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getChangeNoticeRequiredActions } from "~/modules/items";import { ChangeNoticeRequiredActionsTable } from "~/modules/items/ui/ChangeNoticeActions";import type { Handle } from "~/utils/handle";+import { changeNoticeRequiredActionsList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Change Notice Actions`,@@ -19,32 +18,21 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getChangeNoticeRequiredActions(client, companyId, {- search,- limit,- offset,- sorts,- filters+ return loadListPage(request, changeNoticeRequiredActionsList, {+ dataKey: "data"});}export default function ChangeNoticeActionsRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ChangeNoticeRequiredActionsTable data={data ?? []} count={count ?? 0} />+ <ChangeNoticeRequiredActionsTable+ data={data}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/items+/change-notice-types.tsx b/apps/erp/app/routes/x+/items+/change-notice-types.tsxindex fb0b8324cf..dc2acfa4bc 100644--- a/apps/erp/app/routes/x+/items+/change-notice-types.tsx+++ b/apps/erp/app/routes/x+/items+/change-notice-types.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getChangeNoticeTypes } from "~/modules/items";import { ChangeNoticeTypesTable } from "~/modules/items/ui/ChangeNoticeTypes";import type { Handle } from "~/utils/handle";+import { changeNoticeTypesList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Change Notice Types`,@@ -19,32 +18,19 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getChangeNoticeTypes(client, companyId, {- search,- limit,- offset,- sorts,- filters- });+ return loadListPage(request, changeNoticeTypesList, { dataKey: "data" });}export default function ChangeNoticeTypesRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ChangeNoticeTypesTable data={data ?? []} count={count ?? 0} />+ <ChangeNoticeTypesTable+ data={data}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/items+/change-notices+/_index.tsx b/apps/erp/app/routes/x+/items+/change-notices+/_index.tsxindex 17f3dfa3fb..7d6806fe7b 100644--- a/apps/erp/app/routes/x+/items+/change-notices+/_index.tsx+++ b/apps/erp/app/routes/x+/items+/change-notices+/_index.tsx@@ -2,64 +2,40 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getChangeNotices, getChangeNoticeTypesList } from "~/modules/items";+import { getChangeNoticeTypesList } from "~/modules/items";import { ChangeNoticesTable } from "~/modules/items/ui/ChangeNotice";+import { changeNoticesList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [changeNotices, types] = await Promise.all([- getChangeNotices(client, companyId, {- search,- limit,- offset,- sorts,- filters+ return loadListPage(request, changeNoticesList, {+ dataKey: "changeNotices",+ firstPage: async ({ client, companyId }) => ({+ types: (await getChangeNoticeTypesList(client, companyId)).data ?? []}),- getChangeNoticeTypesList(client, companyId)- ]);-- if (changeNotices.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(- request,- error(changeNotices.error, "Error loading change notices")- )- );- }-- return {- changeNotices: changeNotices.data ?? [],- count: changeNotices.count ?? 0,- types: types.data ?? []- };+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Error loading change notices"+ }+ });}export default function ChangeNoticesIndexRoute() {- const { changeNotices, count, types } = useLoaderData<typeof loader>();+ const { changeNotices, count, nextCursor, types } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ChangeNoticesTable data={changeNotices} count={count} types={types} />+ <ChangeNoticesTable+ data={changeNotices}+ count={count}+ nextCursor={nextCursor}+ types={types}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/items+/consumables.tsx b/apps/erp/app/routes/x+/items+/consumables.tsxindex 84c09fbc25..ea31936940 100644--- a/apps/erp/app/routes/x+/items+/consumables.tsx+++ b/apps/erp/app/routes/x+/items+/consumables.tsx@@ -2,20 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getConsumables } from "~/modules/items";import { ConsumablesTable } from "~/modules/items/ui/Consumables";import { getTagsList } from "~/modules/shared";import type { Handle } from "~/utils/handle";+import { consumablesList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["item"],@@ -24,55 +20,32 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- bypassRls: true- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const supplierId = searchParams.get("supplierId");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [consumables, tags] = await Promise.all([- getConsumables(client, companyId, {- search,- supplierId,- limit,- offset,- sorts,- filters+ return loadListPage(request, consumablesList, {+ dataKey: "consumables",+ bypassRls: true,+ firstPage: async ({ client, companyId }) => ({+ tags: (await getTagsList(client, companyId, "consumable")).data ?? []}),- getTagsList(client, companyId, "consumable")- ]);-- if (consumables.error) {- redirect(- path.to.authenticatedRoot,- await flash(- request,- error(consumables.error, "Failed to fetch consumables")- )- );- }-- return {- count: consumables.count ?? 0,- consumables: consumables.data ?? [],- tags: tags.data ?? []- };+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch consumables"+ }+ });}export default function ConsumablesSearchRoute() {- const { count, consumables, tags } = useLoaderData<typeof loader>();+ const { count, consumables, nextCursor, tags } =+ useLoaderData<typeof loader>();useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ConsumablesTable data={consumables} count={count} tags={tags} />+ <ConsumablesTable+ data={consumables}+ count={count}+ nextCursor={nextCursor}+ tags={tags}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/items+/dimensions.tsx b/apps/erp/app/routes/x+/items+/dimensions.tsxindex 2469279b32..12fc2581db 100644--- a/apps/erp/app/routes/x+/items+/dimensions.tsx+++ b/apps/erp/app/routes/x+/items+/dimensions.tsx@@ -2,23 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { getLogger } from "@carbon/logger";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getMaterialDimensions } from "~/modules/items";import MaterialDimensionsTable from "~/modules/items/ui/MaterialDimensions/MaterialDimensionsTable";-import { getCompanySettings } from "~/modules/settings/settings.service";import type { Handle } from "~/utils/handle";+import { materialDimensionsList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";--const logger = getLogger("erp", "dimensions");export const handle: Handle = {breadcrumb: msg`Dimensions`,@@ -26,48 +18,26 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- role: "employee"+ return loadListPage(request, materialDimensionsList, {+ dataKey: "materialDimensions",+ onError: {+ redirectTo: path.to.items,+ message: "Error loading material dimensions"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const settings = await getCompanySettings(client, companyId);-- const materialDimensions = await getMaterialDimensions(client, companyId, {- limit,- offset,- sorts,- search,- filters,- isMetric: settings?.data?.useMetric ?? false- });-- if (materialDimensions.error) {- logger.error(materialDimensions.error);- throw redirect(- path.to.items,- await flash(request, error(null, "Error loading material dimensions"))- );- }-- return {- materialDimensions: materialDimensions.data ?? [],- count: materialDimensions.count ?? 0- };}export default function MaterialDimensionsRoute() {- const { materialDimensions, count } = useLoaderData<typeof loader>();+ const { materialDimensions, count, nextCursor } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <MaterialDimensionsTable data={materialDimensions} count={count ?? 0} />+ <MaterialDimensionsTable+ data={materialDimensions}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/items+/finishes.tsx b/apps/erp/app/routes/x+/items+/finishes.tsxindex ae137b1f22..28550a189c 100644--- a/apps/erp/app/routes/x+/items+/finishes.tsx+++ b/apps/erp/app/routes/x+/items+/finishes.tsx@@ -2,22 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { getLogger } from "@carbon/logger";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getMaterialFinishes } from "~/modules/items";import MaterialFinishesTable from "~/modules/items/ui/MaterialFinishes/MaterialFinishesTable";import type { Handle } from "~/utils/handle";+import { materialFinishesList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";--const logger = getLogger("erp", "finishes");export const handle: Handle = {breadcrumb: msg`Finishes`,@@ -25,45 +18,26 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const materialFinishes = await getMaterialFinishes(client, companyId, {- limit,- offset,- sorts,- search,- filters+ return loadListPage(request, materialFinishesList, {+ dataKey: "materialFinishes",+ onError: {+ redirectTo: path.to.items,+ message: "Error loading material substances"+ }});-- if (materialFinishes.error) {- logger.error(materialFinishes.error);- throw redirect(- path.to.items,- await flash(request, error(null, "Error loading material substances"))- );- }-- return {- materialFinishes: materialFinishes.data ?? [],- count: materialFinishes.count ?? 0- };}export default function MaterialFinishesRoute() {- const { materialFinishes, count } = useLoaderData<typeof loader>();+ const { materialFinishes, count, nextCursor } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <MaterialFinishesTable data={materialFinishes} count={count ?? 0} />+ <MaterialFinishesTable+ data={materialFinishes}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/items+/forms.tsx b/apps/erp/app/routes/x+/items+/forms.tsxindex d3486c4b34..c497aa1477 100644--- a/apps/erp/app/routes/x+/items+/forms.tsx+++ b/apps/erp/app/routes/x+/items+/forms.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getMaterialForms } from "~/modules/items";import { MaterialFormsTable } from "~/modules/items/ui/MaterialShapes";import type { Handle } from "~/utils/handle";+import { materialFormsList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Shapes`,@@ -22,44 +18,25 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- role: "employee"+ return loadListPage(request, materialFormsList, {+ dataKey: "materialForms",+ onError: {+ redirectTo: path.to.items,+ message: "Error loading material forms"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const materialForms = await getMaterialForms(client, companyId, {- limit,- offset,- sorts,- search,- filters- });-- if (materialForms.error) {- throw redirect(- path.to.items,- await flash(request, error(null, "Error loading material forms"))- );- }-- return {- materialForms: materialForms.data ?? [],- count: materialForms.count ?? 0- };}export default function MaterialFormsRoute() {- const { materialForms, count } = useLoaderData<typeof loader>();+ const { materialForms, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <MaterialFormsTable data={materialForms} count={count ?? 0} />+ <MaterialFormsTable+ data={materialForms}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/items+/grades.tsx b/apps/erp/app/routes/x+/items+/grades.tsxindex 956c1add22..ae90760a5d 100644--- a/apps/erp/app/routes/x+/items+/grades.tsx+++ b/apps/erp/app/routes/x+/items+/grades.tsx@@ -2,22 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { getLogger } from "@carbon/logger";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getMaterialGrades } from "~/modules/items";import MaterialGradesTable from "~/modules/items/ui/MaterialGrades/MaterialGradesTable";import type { Handle } from "~/utils/handle";+import { materialGradesList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";--const logger = getLogger("erp", "grades");export const handle: Handle = {breadcrumb: msg`Grades`,@@ -25,45 +18,25 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const materialGrades = await getMaterialGrades(client, companyId, {- limit,- offset,- sorts,- search,- filters+ return loadListPage(request, materialGradesList, {+ dataKey: "materialGrades",+ onError: {+ redirectTo: path.to.items,+ message: "Error loading material substances"+ }});-- if (materialGrades.error) {- logger.error(materialGrades.error);- throw redirect(- path.to.items,- await flash(request, error(null, "Error loading material substances"))- );- }-- return {- materialGrades: materialGrades.data ?? [],- count: materialGrades.count ?? 0- };}export default function MaterialGradesRoute() {- const { materialGrades, count } = useLoaderData<typeof loader>();+ const { materialGrades, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <MaterialGradesTable data={materialGrades} count={count ?? 0} />+ <MaterialGradesTable+ data={materialGrades}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/items+/groups.tsx b/apps/erp/app/routes/x+/items+/groups.tsxindex 84977a3bc4..255862a4a0 100644--- a/apps/erp/app/routes/x+/items+/groups.tsx+++ b/apps/erp/app/routes/x+/items+/groups.tsx@@ -3,7 +3,6 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";import { redirect } from "@carbon/utils";@@ -11,11 +10,11 @@ import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { getAccountsList } from "~/modules/accounting";-import { getItemPostingGroups } from "~/modules/items";import { ItemPostingGroupsTable } from "~/modules/items/ui/ItemPostingGroups";import type { Handle } from "~/utils/handle";+import { itemPostingGroupsList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Item Groups`,@@ -23,58 +22,36 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId, companyGroupId } = await requirePermissions(- request,- {- view: "parts",- role: "employee"+ return loadListPage(request, itemPostingGroupsList, {+ dataKey: "itemPostingGroups",+ firstPage: async ({ client, companyGroupId }) => {+ const accounts = await getAccountsList(client, companyGroupId);+ if (accounts.error) {+ throw redirect(+ path.to.itemPostingGroups,+ await flash(request, error(accounts.error, "Error loading accounts"))+ );+ }+ return { accounts: accounts.data ?? [] };+ },+ onError: {+ redirectTo: path.to.items,+ message: "Error loading item groups"}- );-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [itemPostingGroups, accounts] = await Promise.all([- getItemPostingGroups(client, companyId, {- limit,- offset,- sorts,- search,- filters- }),- getAccountsList(client, companyGroupId)- ]);-- if (itemPostingGroups.error) {- throw redirect(- path.to.items,- await flash(request, error(null, "Error loading item groups"))- );- }-- if (accounts.error) {- throw redirect(- path.to.itemPostingGroups,- await flash(request, error(accounts.error, "Error loading accounts"))- );- }-- return {- itemPostingGroups: itemPostingGroups.data ?? [],- count: itemPostingGroups.count ?? 0,- accounts: accounts.data ?? []- };+ });}export default function ItemPostingGroupsRoute() {- const { itemPostingGroups, count } = useLoaderData<typeof loader>();+ const { itemPostingGroups, count, nextCursor } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ItemPostingGroupsTable data={itemPostingGroups} count={count ?? 0} />+ <ItemPostingGroupsTable+ data={itemPostingGroups}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/items+/materials.tsx b/apps/erp/app/routes/x+/items+/materials.tsxindex 028d158a46..5ec63666a2 100644--- a/apps/erp/app/routes/x+/items+/materials.tsx+++ b/apps/erp/app/routes/x+/items+/materials.tsx@@ -2,20 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getMaterials } from "~/modules/items";import { MaterialsTable } from "~/modules/items/ui/Materials";import { getTagsList } from "~/modules/shared";import type { Handle } from "~/utils/handle";+import { materialsList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["item"],@@ -24,51 +20,30 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- bypassRls: true- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const supplierId = searchParams.get("supplierId");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [materials, tags] = await Promise.all([- getMaterials(client, companyId, {- search,- supplierId,- limit,- offset,- sorts,- filters+ return loadListPage(request, materialsList, {+ dataKey: "materials",+ bypassRls: true,+ firstPage: async ({ client, companyId }) => ({+ tags: (await getTagsList(client, companyId, "material")).data ?? []}),- getTagsList(client, companyId, "material")- ]);-- if (materials.error) {- redirect(- path.to.authenticatedRoot,- await flash(request, error(materials.error, "Failed to fetch materials"))- );- }-- return {- count: materials.count ?? 0,- materials: materials.data ?? [],- tags: tags.data ?? []- };+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch materials"+ }+ });}export default function MaterialsSearchRoute() {- const { count, materials, tags } = useLoaderData<typeof loader>();+ const { count, materials, nextCursor, tags } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <MaterialsTable data={materials} count={count} tags={tags} />+ <MaterialsTable+ data={materials}+ count={count}+ nextCursor={nextCursor}+ tags={tags}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/items+/methods+/materials.tsx b/apps/erp/app/routes/x+/items+/methods+/materials.tsxindex f1a439a661..d4877a82c4 100644--- a/apps/erp/app/routes/x+/items+/methods+/materials.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/materials.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getMethodMaterials } from "~/modules/items";import { MethodMaterialsTable } from "~/modules/items/ui/Methods";import type { Handle } from "~/utils/handle";+import { methodMaterialsList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Method Materials`,@@ -22,50 +18,28 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "production",- role: "employee"+ return loadListPage(request, methodMaterialsList, {+ dataKey: "materials",+ onError: {+ redirectTo: path.to.production,+ message: "Failed to fetch method materials"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const materials = await getMethodMaterials(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (materials.error) {- redirect(- path.to.production,- await flash(- request,- error(materials.error, "Failed to fetch method materials")- )- );- }-- return {- count: materials.count ?? 0,- materials: materials.data ?? []- };}export default function MethodMaterialsRoute() {- const { count, materials } = useLoaderData<typeof loader>();+ const { count, materials, nextCursor } = useLoaderData<typeof loader>();return (<VStackspacing={0}className="h-[calc(100dvh-var(--topbar-height)-var(--content-inset))]">- <MethodMaterialsTable data={materials} count={count} />+ <MethodMaterialsTable+ data={materials}+ count={count}+ nextCursor={nextCursor}+ /></VStack>);}diff --git a/apps/erp/app/routes/x+/items+/methods+/operations.tsx b/apps/erp/app/routes/x+/items+/methods+/operations.tsxindex 7ee5be6ba1..35b4fe1230 100644--- a/apps/erp/app/routes/x+/items+/methods+/operations.tsx+++ b/apps/erp/app/routes/x+/items+/methods+/operations.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getMethodOperations } from "~/modules/items";import { MethodOperationsTable } from "~/modules/items/ui/Methods";import type { Handle } from "~/utils/handle";+import { methodOperationsList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Method Operations`,@@ -22,50 +18,28 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "production",- role: "employee"+ return loadListPage(request, methodOperationsList, {+ dataKey: "operations",+ onError: {+ redirectTo: path.to.production,+ message: "Failed to fetch method operations"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const operations = await getMethodOperations(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (operations.error) {- redirect(- path.to.production,- await flash(- request,- error(operations.error, "Failed to fetch method operations")- )- );- }-- return {- count: operations.count ?? 0,- operations: operations.data ?? []- };}export default function MethodOperationsRoute() {- const { count, operations } = useLoaderData<typeof loader>();+ const { count, operations, nextCursor } = useLoaderData<typeof loader>();return (<VStackspacing={0}className="h-[calc(100dvh-var(--topbar-height)-var(--content-inset))]">- <MethodOperationsTable data={operations} count={count} />+ <MethodOperationsTable+ data={operations}+ count={count}+ nextCursor={nextCursor}+ /></VStack>);}diff --git a/apps/erp/app/routes/x+/items+/parts.tsx b/apps/erp/app/routes/x+/items+/parts.tsxindex c1d4cd83e5..50adafd4d5 100644--- a/apps/erp/app/routes/x+/items+/parts.tsx+++ b/apps/erp/app/routes/x+/items+/parts.tsx@@ -2,20 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getParts } from "~/modules/items";import { PartsTable } from "~/modules/items/ui/Parts";import { getTagsList } from "~/modules/shared";import type { Handle } from "~/utils/handle";+import { partsList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";import { useRealtime } from "../../../hooks";export const handle: Handle = {@@ -25,53 +21,32 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- bypassRls: true- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const supplierId = searchParams.get("supplierId");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [parts, tags] = await Promise.all([- getParts(client, companyId, {- search,- supplierId,- limit,- offset,- sorts,- filters+ return loadListPage(request, partsList, {+ dataKey: "parts",+ bypassRls: true,+ firstPage: async ({ client, companyId }) => ({+ tags: (await getTagsList(client, companyId, "part")).data ?? []}),- getTagsList(client, companyId, "part")- ]);-- if (parts.error) {- redirect(- path.to.authenticatedRoot,- await flash(request, error(parts.error, "Failed to fetch parts"))- );- }-- return {- count: parts.count ?? 0,- parts: parts.data ?? [],- tags: tags.data ?? []- };+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch parts"+ }+ });}export default function PartsSearchRoute() {- const { count, parts, tags } = useLoaderData<typeof loader>();+ const { count, parts, nextCursor, tags } = useLoaderData<typeof loader>();useRealtime("part");return (<VStack spacing={0} className="h-full">- <PartsTable data={parts} count={count} tags={tags} />+ <PartsTable+ data={parts}+ count={count}+ nextCursor={nextCursor}+ tags={tags}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/items+/services.tsx b/apps/erp/app/routes/x+/items+/services.tsxindex 4dee2cb2bb..edc08885ad 100644--- a/apps/erp/app/routes/x+/items+/services.tsx+++ b/apps/erp/app/routes/x+/items+/services.tsx@@ -2,20 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getServices } from "~/modules/items";import { ServicesTable } from "~/modules/items/ui/Services";import { getTagsList } from "~/modules/shared";import type { Handle } from "~/utils/handle";+import { servicesList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["item"],@@ -24,53 +20,30 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- bypassRls: true- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const supplierId = searchParams.get("supplierId");- const group = searchParams.get("group");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [services, tags] = await Promise.all([- getServices(client, companyId, {- search,- supplierId,- group,- limit,- offset,- sorts,- filters+ return loadListPage(request, servicesList, {+ dataKey: "services",+ bypassRls: true,+ firstPage: async ({ client, companyId }) => ({+ tags: (await getTagsList(client, companyId, "service")).data ?? []}),- getTagsList(client, companyId, "service")- ]);-- if (services.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(request, error(services.error, "Failed to fetch services"))- );- }-- return {- count: services.count ?? 0,- services: services.data ?? [],- tags: tags.data ?? []- };+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch services"+ }+ });}export default function ServicesSearchRoute() {- const { count, services, tags } = useLoaderData<typeof loader>();+ const { count, services, nextCursor, tags } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ServicesTable data={services} count={count} tags={tags} />+ <ServicesTable+ data={services}+ count={count}+ nextCursor={nextCursor}+ tags={tags}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/items+/substances.tsx b/apps/erp/app/routes/x+/items+/substances.tsxindex 535351c218..8607f50593 100644--- a/apps/erp/app/routes/x+/items+/substances.tsx+++ b/apps/erp/app/routes/x+/items+/substances.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getMaterialSubstances } from "~/modules/items";import { MaterialSubstancesTable } from "~/modules/items/ui/MaterialSubstances";import type { Handle } from "~/utils/handle";+import { materialSubstancesList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Substances`,@@ -22,44 +18,26 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- role: "employee"+ return loadListPage(request, materialSubstancesList, {+ dataKey: "materialSubstances",+ onError: {+ redirectTo: path.to.items,+ message: "Error loading material substances"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const materialSubstances = await getMaterialSubstances(client, companyId, {- limit,- offset,- sorts,- search,- filters- });-- if (materialSubstances.error) {- throw redirect(- path.to.items,- await flash(request, error(null, "Error loading material substances"))- );- }-- return {- materialSubstances: materialSubstances.data ?? [],- count: materialSubstances.count ?? 0- };}export default function MaterialSubstancesRoute() {- const { materialSubstances, count } = useLoaderData<typeof loader>();+ const { materialSubstances, count, nextCursor } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <MaterialSubstancesTable data={materialSubstances} count={count ?? 0} />+ <MaterialSubstancesTable+ data={materialSubstances}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/items+/tools.tsx b/apps/erp/app/routes/x+/items+/tools.tsxindex ddb386ba46..88c11e767d 100644--- a/apps/erp/app/routes/x+/items+/tools.tsx+++ b/apps/erp/app/routes/x+/items+/tools.tsx@@ -2,20 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getTools } from "~/modules/items";import { ToolsTable } from "~/modules/items/ui/Tools";import { getTagsList } from "~/modules/shared";import type { Handle } from "~/utils/handle";+import { toolsList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["item"],@@ -24,51 +20,30 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- bypassRls: true- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const supplierId = searchParams.get("supplierId");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [tools, tags] = await Promise.all([- getTools(client, companyId, {- search,- supplierId,- limit,- offset,- sorts,- filters+ return loadListPage(request, toolsList, {+ dataKey: "tools",+ bypassRls: true,+ firstPage: async ({ client, companyId }) => ({+ tags: (await getTagsList(client, companyId, "tool")).data ?? []}),- getTagsList(client, companyId, "tool")- ]);-- if (tools.error) {- redirect(- path.to.authenticatedRoot,- await flash(request, error(tools.error, "Failed to fetch tools"))- );- }-- return {- count: tools.count ?? 0,- tools: tools.data ?? [],- tags: tags.data ?? []- };+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch tools"+ }+ });}export default function ToolsSearchRoute() {- const { count, tools, tags } = useLoaderData<typeof loader>();+ const { count, tools, nextCursor, tags } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ToolsTable data={tools} count={count} tags={tags} />+ <ToolsTable+ data={tools}+ count={count}+ nextCursor={nextCursor}+ tags={tags}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/items+/types.tsx b/apps/erp/app/routes/x+/items+/types.tsxindex d671ec5ced..1b36bf2fb8 100644--- a/apps/erp/app/routes/x+/items+/types.tsx+++ b/apps/erp/app/routes/x+/items+/types.tsx@@ -2,22 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { getLogger } from "@carbon/logger";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getMaterialTypes } from "~/modules/items";import MaterialTypesTable from "~/modules/items/ui/MaterialTypes/MaterialTypesTable";import type { Handle } from "~/utils/handle";+import { materialTypesList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";--const logger = getLogger("erp", "types");export const handle: Handle = {breadcrumb: msg`Types`,@@ -25,45 +18,25 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const materialTypes = await getMaterialTypes(client, companyId, {- limit,- offset,- sorts,- search,- filters+ return loadListPage(request, materialTypesList, {+ dataKey: "materialTypes",+ onError: {+ redirectTo: path.to.items,+ message: "Error loading material types"+ }});-- if (materialTypes.error) {- logger.error(materialTypes.error);- throw redirect(- path.to.items,- await flash(request, error(null, "Error loading material types"))- );- }-- return {- materialTypes: materialTypes.data ?? [],- count: materialTypes.count ?? 0- };}export default function MaterialTypesRoute() {- const { materialTypes, count } = useLoaderData<typeof loader>();+ const { materialTypes, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <MaterialTypesTable data={materialTypes} count={count ?? 0} />+ <MaterialTypesTable+ data={materialTypes}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/items+/uom.tsx b/apps/erp/app/routes/x+/items+/uom.tsxindex 62db07dbaa..a904733b2b 100644--- a/apps/erp/app/routes/x+/items+/uom.tsx+++ b/apps/erp/app/routes/x+/items+/uom.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getUnitOfMeasures } from "~/modules/items";import { UnitOfMeasuresTable } from "~/modules/items/ui/UnitOfMeasure";import type { Handle } from "~/utils/handle";+import { unitOfMeasuresList } from "~/utils/list-registry/items.server";+import { loadListPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Unit of Measures`,@@ -19,32 +18,15 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "parts",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getUnitOfMeasures(client, companyId, {- search,- limit,- offset,- sorts,- filters- });+ return loadListPage(request, unitOfMeasuresList, { dataKey: "data" });}export default function UnitOfMeasuresRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <UnitOfMeasuresTable data={data ?? []} count={count ?? 0} />+ <UnitOfMeasuresTable data={data} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/items+/update.tsx b/apps/erp/app/routes/x+/items+/update.tsxindex 043d8bb351..d8b788a549 100644--- a/apps/erp/app/routes/x+/items+/update.tsx+++ b/apps/erp/app/routes/x+/items+/update.tsx@@ -7,19 +7,19 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { getLogger } from "@carbon/logger";import { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";-import type { InventoryItemType } from "~/modules/items";-import { deriveItemMethodUpdate } from "~/modules/items";+import { isItemBulkUpdateField } from "~/modules/items";+import { bulkUpdateItems } from "~/modules/items/bulk-actions.server";import {getUnreleasedChangeOrderItems,unreleasedChangeOrderItemsMessage} from "~/modules/items/items.server";import {- cascadeItemTrackingType,- updateItemMethodAndSourcing,updateMaterialProperties,updateServiceName} from "~/modules/items/items.service";import { getDatabaseClient } from "~/services/database.server";+import { bulkStartFormResponse } from "~/utils/table-jobs";+import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";const logger = getLogger("erp", "update");@@ -37,43 +37,35 @@ export async function action({ request }: ActionFunctionArgs) {return { error: { message: "Invalid form data" }, data: null };}- switch (field) {- case "itemTrackingType": {- const newType = value as InventoryItemType;-- const result = await client- .from("item")- .update({- itemTrackingType: newType,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .in("id", items as string[])- .eq("companyId", companyId);-- if (result.error) return result;-- try {- await cascadeItemTrackingType(getDatabaseClient(), {- itemIds: items as string[],- companyId,- newType,- userId- });- } catch (err) {- logger.error("Failed to cascade item tracking type", {- field,- itemIds: items,- error: err- });- return {- error: { message: "Failed to cascade tracking flags" },- data: null- };- }+ // The item tables' bulk Update: every matching row runs in the background,+ // a selection runs here. Both go through bulkUpdateItems.+ if (isItemBulkUpdateField(field)) {+ const started = await startAllMatchingBulkAction(+ formData.get("allMatching"),+ { companyId, userId, actionKey: "items.update", params: { field, value } }+ );+ if (started) return bulkStartFormResponse(started);++ // Each chunk of 100 commits on its own, so a failure can follow applied+ // chunks: the counts let the table say what was done.+ const result = await bulkUpdateItems(client, getDatabaseClient(), {+ itemIds: items as string[],+ field,+ value,+ companyId,+ userId+ });+ return result.error+ ? {+ error: { message: result.error },+ data: null,+ done: result.done,+ failed: result.failed+ }+ : { data: null, error: null };+ }- return result;- }+ switch (field) {case "name":case "description":case "mpn":@@ -89,32 +81,6 @@ export async function action({ request }: ActionFunctionArgs) {).in("id", items as string[]).eq("companyId", companyId);- case "replenishmentSystem":- case "defaultMethodType":- case "sourcingType": {- // These three fields are interlocked and each mirror down to the item's- // method materials. updateItemMethodAndSourcing applies the item write- // and the cascade in one transaction, so they can't be left half-applied.- const { itemUpdate, cascade } = deriveItemMethodUpdate(field, value);- try {- await updateItemMethodAndSourcing(getDatabaseClient(), {- itemIds: items as string[],- companyId,- userId,- itemUpdate,- cascade- });- } catch (err) {- logger.error("Failed to update item method/sourcing", {- field,- value,- itemIds: items,- error: err- });- return { error: { message: "Failed to update item" }, data: null };- }- return { data: null, error: null };- }case "gradeId":case "dimensionId":case "finishId":@@ -195,60 +161,6 @@ export async function action({ request }: ActionFunctionArgs) {.eq("companyId", companyId);}- case "itemPostingGroupId":- // Update itemCost table for all selected items- const itemCostUpdates = await Promise.all(- (items as string[]).map(async (itemId) => {- const existingCost = await client- .from("itemCost")- .select("itemId")- .eq("itemId", itemId)- .single();-- if (existingCost.data) {- // Update existing record- return client- .from("itemCost")- .update({- itemPostingGroupId: value || null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })- .eq("itemId", itemId);- } else {- // Create new record- return client.from("itemCost").insert({- itemId,- itemPostingGroupId: value || null,- costingMethod: "Standard",- standardCost: 0,- unitCost: 0,- costIsAdjusted: false,- companyId,- createdBy: userId,- updatedBy: userId,- createdAt: new Date().toISOString(),- updatedAt: new Date().toISOString()- });- }- })- );-- // Check for any errors- const errors = itemCostUpdates.filter((result) => result.error);- if (errors.length > 0) {- return {- error: {- message: errors[0].error?.message || "Failed to update item costs"- },- data: null- };- }-- return {- data: null,- error: null- };case "partId":if (items.length > 1) {return {diff --git a/apps/erp/app/routes/x+/job+/$jobId.events.tsx b/apps/erp/app/routes/x+/job+/$jobId.events.tsxindex c261f1b014..e1888975fd 100644--- a/apps/erp/app/routes/x+/job+/$jobId.events.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.events.tsx@@ -5,6 +5,7 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";import { RecordOutlet, useMount, VStack } from "@carbon/react";import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";@@ -12,13 +13,18 @@ import { useLoaderData } from "react-router";import { usePanels } from "~/components/Layout";import {getJobOperationsList,- getProductionEvents+ getProductionEvents,+ PRODUCTION_EVENTS_PAGING} from "~/modules/production";import { ProductionEventsTable } from "~/modules/production/ui/Jobs";import { getWorkCentersList } from "~/modules/resources";+import { toPage } from "~/utils/cursor";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path, requestReferrer } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";+const logger = getLogger("erp", "job-events");+export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {view: "production"@@ -30,12 +36,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const url = new URL(request.url);const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =+ const { limit, cursor, sorts, filters } =getGenericQueryFilters(searchParams);const operations = await getJobOperationsList(client, jobId);if (operations.error) {- redirect(+ throw redirect(requestReferrer(request) ?? path.to.job(jobId),await flash(request,@@ -48,39 +54,55 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return {count: 0,events: [],+ nextCursor: null,workCenters: [],operations: []};}+ // A later page (`?after=`) is read for its rows only: skip the work centers.const [events, workCenters] = await Promise.all([getProductionEvents(client, operations.data?.map((o) => o.id) ?? [], {search,limit,- offset,+ cursor,sorts,filters}),- getWorkCentersList(client, companyId)+ cursor ? null : getWorkCentersList(client, companyId)]);if (events.error) {- redirect(+ if (cursor) {+ logger.error("Failed to load a later page of production events", {+ companyId,+ error: events.error+ });+ return listErrorPage("events");+ }+ throw redirect(path.to.production,await flash(request, error(events.error, "Failed to fetch job events")));}+ const page = toPage(+ events.data ?? [],+ { limit, sorts },+ PRODUCTION_EVENTS_PAGING+ );+return {count: events.count ?? 0,- events: events.data ?? [],- workCenters: workCenters.data ?? [],+ events: page.rows,+ nextCursor: page.nextCursor,+ workCenters: workCenters?.data ?? [],operations: operations.data ?? []};}export default function ProductionEventsRoute() {- const { count, events, operations, workCenters } =+ const { count, events, nextCursor, operations, workCenters } =useLoaderData<typeof loader>();const { setIsExplorerCollapsed } = usePanels();@@ -98,6 +120,7 @@ export default function ProductionEventsRoute() {<ProductionEventsTabledata={events}count={count}+ nextCursor={nextCursor}operations={operations}workCenters={workCenters}/>diff --git a/apps/erp/app/routes/x+/job+/$jobId.materials.tsx b/apps/erp/app/routes/x+/job+/$jobId.materials.tsxindex 4f9bcfa8f2..796b5cd387 100644--- a/apps/erp/app/routes/x+/job+/$jobId.materials.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.materials.tsx@@ -36,7 +36,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const url = new URL(request.url);const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =+ const { limit, cursor, sorts, filters } =getGenericQueryFilters(searchParams);const job = await getJob(client, jobId);@@ -54,7 +54,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getJobMaterialsWithQuantityOnHand(client, jobId, companyId, locationId, {search,limit,- offset,+ cursor,sorts,// orderStatus is filtered client-side — not a column the RPC can filter on.// readableIdWithRevision was the Item filter's column before it moved todiff --git a/apps/erp/app/routes/x+/job+/$jobId.operations.tsx b/apps/erp/app/routes/x+/job+/$jobId.operations.tsxindex e2ad61bdb0..288dc804ad 100644--- a/apps/erp/app/routes/x+/job+/$jobId.operations.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.operations.tsx@@ -5,18 +5,27 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";import { useMount, VStack } from "@carbon/react";import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { usePanels } from "~/components/Layout";-import { getJob, getJobOperations } from "~/modules/production";+import {+ getJob,+ getJobOperations,+ JOB_OPERATIONS_PAGING+} from "~/modules/production";import { JobOperationsTable } from "~/modules/production/ui/Jobs";+import { toPage } from "~/utils/cursor";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";+const logger = getLogger("erp", "job-operations");+export async function loader({ request, params }: LoaderFunctionArgs) {- const { client } = await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {view: "production",role: "employee"});@@ -27,7 +36,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const url = new URL(request.url);const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =+ const { limit, cursor, sorts, filters } =getGenericQueryFilters(searchParams);const job = await getJob(client, jobId);@@ -41,13 +50,20 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const operations = await getJobOperations(client, jobId, {search,limit,- offset,+ cursor,sorts,filters});if (operations.error) {- redirect(+ if (cursor) {+ logger.error("Failed to load a later page of job operations", {+ companyId,+ error: operations.error+ });+ return listErrorPage("operations");+ }+ throw redirect(path.to.production,await flash(request,@@ -56,14 +72,21 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}+ const page = toPage(+ operations.data ?? [],+ { limit, sorts },+ JOB_OPERATIONS_PAGING+ );+return {count: operations.count ?? 0,- operations: operations.data ?? []+ operations: page.rows,+ nextCursor: page.nextCursor};}export default function JobOperationsRoute() {- const { count, operations } = useLoaderData<typeof loader>();+ const { count, operations, nextCursor } = useLoaderData<typeof loader>();const { setIsExplorerCollapsed } = usePanels();@@ -76,7 +99,11 @@ export default function JobOperationsRoute() {spacing={0}className="h-[calc(100dvh-var(--topbar-height)-var(--header-height)-var(--content-inset))]">- <JobOperationsTable data={operations} count={count} />+ <JobOperationsTable+ data={operations}+ count={count}+ nextCursor={nextCursor}+ /></VStack>);}diff --git a/apps/erp/app/routes/x+/job+/$jobId.quantities.tsx b/apps/erp/app/routes/x+/job+/$jobId.quantities.tsxindex 9cee44eeb7..9882c6c585 100644--- a/apps/erp/app/routes/x+/job+/$jobId.quantities.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.quantities.tsx@@ -5,6 +5,7 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";import { RecordOutlet, useMount, VStack } from "@carbon/react";import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";@@ -13,12 +14,17 @@ import { usePanels } from "~/components/Layout";import {getJobOperationsList,getProductionQuantities,- getScrapReasons+ getScrapReasons,+ PRODUCTION_QUANTITIES_PAGING} from "~/modules/production";import { ProductionQuantitiesTable } from "~/modules/production/ui/Jobs";+import { toPage } from "~/utils/cursor";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path, requestReferrer } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";+const logger = getLogger("erp", "job-quantities");+export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {view: "production"@@ -30,12 +36,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const url = new URL(request.url);const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =+ const { limit, cursor, sorts, filters } =getGenericQueryFilters(searchParams);const operations = await getJobOperationsList(client, jobId);if (operations.error) {- redirect(+ throw redirect(requestReferrer(request) ?? path.to.job(jobId),await flash(request,@@ -48,39 +54,55 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return {count: 0,events: [],+ nextCursor: null,operations: [],scrapReasons: []};}+ // A later page (`?after=`) is read for its rows only: skip the scrap reasons.const [events, scrapReasons] = await Promise.all([getProductionQuantities(client, operations.data?.map((o) => o.id) ?? [], {search,limit,- offset,+ cursor,sorts,filters}),- getScrapReasons(client, companyId)+ cursor ? null : getScrapReasons(client, companyId)]);if (events.error) {- redirect(+ if (cursor) {+ logger.error("Failed to load a later page of production quantities", {+ companyId,+ error: events.error+ });+ return listErrorPage("events");+ }+ throw redirect(path.to.production,await flash(request, error(events.error, "Failed to fetch job events")));}+ const page = toPage(+ events.data ?? [],+ { limit, sorts },+ PRODUCTION_QUANTITIES_PAGING+ );+return {count: events.count ?? 0,- events: events.data ?? [],+ events: page.rows,+ nextCursor: page.nextCursor,operations: operations.data ?? [],- scrapReasons: scrapReasons.data ?? []+ scrapReasons: scrapReasons?.data ?? []};}export default function ProductionQuantitiesRoute() {- const { count, events, operations, scrapReasons } =+ const { count, events, nextCursor, operations, scrapReasons } =useLoaderData<typeof loader>();const { setIsExplorerCollapsed } = usePanels();@@ -98,6 +120,7 @@ export default function ProductionQuantitiesRoute() {<ProductionQuantitiesTabledata={events}count={count}+ nextCursor={nextCursor}operations={operations}scrapReasons={scrapReasons}/>diff --git a/apps/erp/app/routes/x+/job+/$jobId.steps.tsx b/apps/erp/app/routes/x+/job+/$jobId.steps.tsxindex 1c47dca8df..6e5ca0ffb7 100644--- a/apps/erp/app/routes/x+/job+/$jobId.steps.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.steps.tsx@@ -5,16 +5,24 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";import { useMount, VStack } from "@carbon/react";import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { usePanels } from "~/components/Layout";-import { getJobOperationStepRecords } from "~/modules/production";+import {+ getJobOperationStepRecords,+ JOB_OPERATION_STEP_RECORDS_PAGING+} from "~/modules/production";import { JobOperationStepRecordsTable } from "~/modules/production/ui/Jobs";+import { toPage } from "~/utils/cursor";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";+const logger = getLogger("erp", "job-steps");+export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {view: "production",@@ -28,7 +36,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =+ const { limit, cursor, sorts, filters } =getGenericQueryFilters(searchParams);const stepRecords = await getJobOperationStepRecords(@@ -37,7 +45,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {companyId,{limit,- offset,+ cursor,sorts,filters,search@@ -45,7 +53,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);if (stepRecords.error) {- redirect(+ if (cursor) {+ logger.error("Failed to load a later page of job step records", {+ companyId,+ error: stepRecords.error+ });+ return listErrorPage("stepRecords");+ }+ throw redirect(path.to.production,await flash(request,@@ -54,14 +69,21 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}+ const page = toPage(+ stepRecords.data ?? [],+ { limit, sorts },+ JOB_OPERATION_STEP_RECORDS_PAGING+ );+return {count: stepRecords.count ?? 0,- stepRecords: stepRecords.data ?? []+ stepRecords: page.rows,+ nextCursor: page.nextCursor};}export default function JobOperationStepRecordsRoute() {- const { count, stepRecords } = useLoaderData<typeof loader>();+ const { count, stepRecords, nextCursor } = useLoaderData<typeof loader>();const { setIsExplorerCollapsed } = usePanels();@@ -74,8 +96,12 @@ export default function JobOperationStepRecordsRoute() {spacing={0}className="h-[calc(100dvh-var(--topbar-height)-var(--header-height)-var(--content-inset))]">- {/* @ts-expect-error TS2322 */}- <JobOperationStepRecordsTable data={stepRecords} count={count} />+ <JobOperationStepRecordsTable+ // @ts-expect-error TS2322+ data={stepRecords}+ count={count}+ nextCursor={nextCursor}+ /></VStack>);}diff --git a/apps/erp/app/routes/x+/job+/new.tsx b/apps/erp/app/routes/x+/job+/new.tsxindex 180ef647b8..2f97af8377 100644--- a/apps/erp/app/routes/x+/job+/new.tsx+++ b/apps/erp/app/routes/x+/job+/new.tsx@@ -57,7 +57,7 @@ export async function loader({ request }: LoaderFunctionArgs) {search: null,status: "Under Construction",limit: 100,- offset: 0,+ cursor: null,sorts: [],filters: []})@@ -69,13 +69,14 @@ export async function loader({ request }: LoaderFunctionArgs) {id: assetClass.id,name: assetClass.name})),- underConstructionAssets: (underConstructionAssets?.data ?? []).map(- (asset) => ({+ // The query reads one row past `limit` (the next-page probe); keep 100.+ underConstructionAssets: (underConstructionAssets?.data ?? [])+ .slice(0, 100)+ .map((asset) => ({id: asset.id,fixedAssetId: asset.fixedAssetId,name: asset.name- })- )+ }))};}diff --git a/apps/erp/app/routes/x+/job+/release.test.ts b/apps/erp/app/routes/x+/job+/release.test.tsindex 3db6495871..2028901e39 100644--- a/apps/erp/app/routes/x+/job+/release.test.ts+++ b/apps/erp/app/routes/x+/job+/release.test.ts@@ -24,15 +24,46 @@ vi.mock("@carbon/logger", () => ({vi.mock("~/services/database.server", () => ({getDatabaseClient: vi.fn(() => ({}))}));-vi.mock("~/modules/production", () => ({+// The release logic lives in production/bulk-actions.server.ts; these stand in+// for the modules it calls.+vi.mock("~/modules/production/production.service", () => ({getJobReleaseReadiness: vi.fn()}));vi.mock("~/modules/production/production.server", () => ({releaseJobs: vi.fn()}));+// A request with ids never reaches the background path.+vi.mock("~/utils/table-jobs.server", () => ({+ startAllMatchingBulkAction: vi.fn(async () => null),+ startSelectedBulkAction: vi.fn(async () => ({+ success: true,+ background: true+ }))+}));+// production.models reaches @carbon/content/glossary and Lingui `msg` macros+// at module load, which plain vitest does not transform.+vi.mock("@carbon/content/glossary", () => ({+ terms: {},+ getEntry: vi.fn(),+ lookupEntry: vi.fn(),+ hasEntry: vi.fn(),+ termSlug: vi.fn(),+ glossaryEntries: () => []+}));+vi.mock("@lingui/core/macro", () => ({+ msg: (strings: TemplateStringsArray | string, ...values: unknown[]) =>+ Array.isArray(strings)+ ? strings.reduce(+ (acc, s, i) => acc + s + (i < values.length ? String(values[i]) : ""),+ ""+ )+ : String(strings)+}));-import { getJobReleaseReadiness } from "~/modules/production";+import { bulkReleaseJobs } from "~/modules/production/bulk-actions.server";import { releaseJobs } from "~/modules/production/production.server";+import { getJobReleaseReadiness } from "~/modules/production/production.service";+import { startSelectedBulkAction } from "~/utils/table-jobs.server";import { action } from "./release";type JobRow = {@@ -116,6 +147,33 @@ beforeEach(() => {});describe("bulk job release", () => {+ it("sends more than 25 selected jobs to the background job", async () => {+ const ids = Array.from({ length: 26 }, (_, i) => `j${i}`);+ setup(ids.map((id) => job(id)));++ const result = await run(ids);++ expect(result).toEqual({ success: true, background: true });+ expect(vi.mocked(startSelectedBulkAction).mock.calls[0]?.[0]).toMatchObject(+ { actionKey: "jobs.release", listKey: "jobs", ids }+ );+ expect(releaseJobs).not.toHaveBeenCalled();+ });++ it("releases 25 selected jobs in the request itself", async () => {+ const ids = Array.from({ length: 25 }, (_, i) => `j${i}`);+ setup(ids.map((id) => job(id)));+ vi.mocked(getJobReleaseReadiness).mockResolvedValue({+ data: { jobs: ids.map((id) => ready(id)), suppliers: [] },+ error: null+ });++ const result = await run(ids);++ expect(startSelectedBulkAction).not.toHaveBeenCalled();+ expect(result).toMatchObject({ success: true, released: 25 });+ });+it("releases Draft and Planned jobs and skips the rest of the selection", async () => {setup([job("j1", { status: "Draft" }),@@ -141,7 +199,9 @@ describe("bulk job release", () => {released: 2,warnings: [],failed: [],- scheduled: true+ skipped: 1,+ scheduled: true,+ purchaseOrdersBySupplierId: {}});});@@ -314,7 +374,7 @@ describe("bulk job release", () => {it("loads a large selection in groups, and releases it in job order", async () => {const ids = Array.from({ length: 250 }, (_, index) => `j${index}`);- // Stored out of order, so the release order is the route's own doing.+ // Stored out of order, so the release order is the function's own doing.const { inFilterSizes } = setup([...ids].reverse().map((id) => job(id, { jobId: id.padStart(5, "0") })));@@ -322,8 +382,17 @@ describe("bulk job release", () => {data: { jobs: ids.map((id) => ready(id)), suppliers: [] },error: null});-- const result = await run(ids);+ // The route sends a selection this big to the background job, so call+ // the release function itself, as the job does.+ const { client } = await requirePermissions(request(ids), {});++ const result = await bulkReleaseJobs({+ client,+ db: {} as any,+ jobIds: ids,+ companyId: "company-1",+ userId: "user-1"+ });expect(inFilterSizes).toEqual([100, 100, 50]);expect(result).toMatchObject({ released: 250, failed: [] });diff --git a/apps/erp/app/routes/x+/job+/release.tsx b/apps/erp/app/routes/x+/job+/release.tsxindex 4268b601cc..51556b74b7 100644--- a/apps/erp/app/routes/x+/job+/release.tsx+++ b/apps/erp/app/routes/x+/job+/release.tsx@@ -4,27 +4,26 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { getCarbonServiceRole } from "@carbon/auth/client.server";-import { getLogger } from "@carbon/logger";-import { runLocationSchedule } from "@carbon/planning";-import { chunkArray } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { z } from "zod";-import { getJobReleaseReadiness } from "~/modules/production";-import { releaseJobs } from "~/modules/production/production.server";-import { jobReleaseProblems } from "~/modules/production/ui/Jobs/job-release-logic";+import { bulkReleaseJobs } from "~/modules/production/bulk-actions.server";import { getDatabaseClient } from "~/services/database.server";--const logger = getLogger("erp", "job-release");+import { fitsOneRequest } from "~/utils/table-jobs";+import {+ startAllMatchingBulkAction,+ startSelectedBulkAction+} from "~/utils/table-jobs.server";const bodySchema = z.object({ jobIds: z.array(z.string()) });// Bulk release — the jobs table's "Release Jobs" action. Each selected Draft /-// Planned job goes through the job page's release path (releaseJobs) on its-// own: a job that is not ready is reported in `failed` while the rest still-// release. There is no dialog here, so a job with something to fix or a-// purchase order to choose is skipped and named — the planner releases it from-// the job. A job in any other status (a stale selection) is skipped silently.+// Planned job goes through the job page's release path (bulkReleaseJobs) on+// its own: a job that is not ready is reported in `failed` while the rest+// still release. A job in any other status (a stale selection) is skipped.+// `{ allMatching: { listKey, search } }` in place of `jobIds` releases every+// matching job in the background job instead, up to 2,000 jobs. More than 25+// selected jobs also go to the background job: each runs MRP, and one request+// must end before the load balancer's 600 s.// Fetcher-driven; the table toasts the summary and the loader revalidates.export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);@@ -34,7 +33,16 @@ export async function action({ request }: ActionFunctionArgs) {// A body that is not JSON, or not the shape the table sends, is a plain// refusal rather than a 500.- const body = bodySchema.safeParse(await request.json().catch(() => null));+ const json = await request.json().catch(() => null);+ const started = await startAllMatchingBulkAction(json?.allMatching, {+ companyId,+ userId,+ actionKey: "jobs.release",+ params: {}+ });+ if (started) return started;++ const body = bodySchema.safeParse(json);if (!body.success) {return { success: false as const, message: "Invalid request" };}@@ -42,139 +50,22 @@ export async function action({ request }: ActionFunctionArgs) {if (ids.length === 0) {return { success: false as const, message: "No jobs selected" };}-- // An `in` filter rides in the request URL, so a whole page of ids is read in- // groups.- const jobs = [];- for (const batch of chunkArray(ids, 100)) {- const page = await client- .from("job")- .select("id, jobId, status, quantity, scrapQuantity, locationId")- .in("id", batch)- .eq("companyId", companyId);- if (page.error) {- logger.error("Failed to load the selected jobs", {- companyId,- error: page.error- });- return {- success: false as const,- message: "Failed to load the selected jobs"- };- }- jobs.push(...page.data);- }-- const releasable = jobs- .filter((job) => job.status === "Draft" || job.status === "Planned")- .sort((a, b) => a.jobId.localeCompare(b.jobId));- const readiness = await getJobReleaseReadiness(- client,- releasable.map((job) => job.id),- companyId- );- if (readiness.error || !readiness.data) {- logger.error("Failed to validate the selected jobs", {- companyId,- error: readiness.error- });- return {- success: false as const,- message: "Failed to validate the selected jobs"- };- }-- const readinessByJobId = new Map(- readiness.data.jobs.map((job) => [job.id, job] as const)- );- const suppliersWithDraftPurchaseOrders = new Set(- readiness.data.suppliers- .filter((supplier) => supplier.draftPurchaseOrders.length > 0)- .map((supplier) => supplier.supplierId)- );- // Every supplier starts on a new PO; one a job creates is reused by the jobs- // after it, so the selection lands on one PO per supplier.- let purchaseOrders: Record<string, string> = Object.fromEntries(- readiness.data.suppliers.map((supplier) => [supplier.supplierId, "new"])- );-- let released = 0;- const failed: { readableId: string; message: string }[] = [];- // Released, with something left to fix on the job (its purchase orders).- const warnings: { readableId: string; message: string }[] = [];- const locationIds = new Set<string>();- for (const job of releasable) {- const ready = readinessByJobId.get(job.id);- const problems = ready- ? [- // The job page disables Release for the same job.- ...(job.quantity === 0 && job.scrapQuantity === 0- ? ["nothing to make"]- : []),- ...jobReleaseProblems(ready),- ...(ready.supplierIds.some((id) =>- suppliersWithDraftPurchaseOrders.has(id)- )- ? ["choose a purchase order for its outside operations on the job"]- : [])- ]- : ["could not be validated"];- if (problems.length > 0) {- failed.push({ readableId: job.jobId, message: problems.join("; ") });- continue;- }-- const result = await releaseJobs({- client,- db: getDatabaseClient(),- jobIds: [job.id],+ if (!fitsOneRequest("jobs.release", ids.length)) {+ return startSelectedBulkAction({companyId,userId,- purchaseOrdersBySupplierId: purchaseOrders+ actionKey: "jobs.release",+ params: {},+ listKey: "jobs",+ ids});- purchaseOrders = result.purchaseOrdersBySupplierId;- if (result.error) {- logger.error("Failed to release job", {- companyId,- jobId: job.id,- error: result.error- });- }- // The job is Ready when its id came back released, error or not; a job- // that is Ready must be scheduled and counted, whatever failed after.- if (!result.releasedJobIds.includes(job.id)) {- failed.push({ readableId: job.jobId, message: result.error ?? "" });- continue;- }- if (result.error) {- warnings.push({ readableId: job.jobId, message: result.error });- }-- locationIds.add(job.locationId);- released += 1;}- // After every status flip is persisted — the scheduler only places jobs that- // are already released. One run per location, as on the job page.- let scheduled = true;- for (const locationId of locationIds) {- try {- await runLocationSchedule({- db: getDatabaseClient(),- client: getCarbonServiceRole(),- locationId,- companyId,- userId- });- } catch (error) {- logger.error("Failed to schedule released jobs", {- companyId,- locationId,- error- });- scheduled = false;- }- }-- return { success: true as const, released, warnings, failed, scheduled };+ return bulkReleaseJobs({+ client,+ db: getDatabaseClient(),+ jobIds: ids,+ companyId,+ userId+ });}diff --git a/apps/erp/app/routes/x+/job+/update.tsx b/apps/erp/app/routes/x+/job+/update.tsxindex 1df34e67c3..1378a60abb 100644--- a/apps/erp/app/routes/x+/job+/update.tsx+++ b/apps/erp/app/routes/x+/job+/update.tsx@@ -15,9 +15,12 @@ import {recalculateJobRequirements,upsertJobMethod} from "~/modules/production";+import { bulkDeleteJobs } from "~/modules/production/bulk-actions.server";import { isSalesOrderClosed } from "~/modules/sales";import { getDatabaseClient } from "~/services/database.server";import { requireUnlockedBulk } from "~/utils/lockedGuard.server";+import { bulkStartFormResponse } from "~/utils/table-jobs";+import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";const logger = getLogger("erp", "update");@@ -35,11 +38,36 @@ export async function action({ request }: ActionFunctionArgs) {return { error: { message: "Invalid form data" }, data: null };}+ // The jobs table's bulk Delete. It deletes Draft, Planned, Due Today and+ // Overdue jobs only (bulkDeleteJobs skips the rest), and needs the delete+ // permission as well as update.+ if (field === "delete") {+ await requirePermissions(request, {+ update: "production",+ delete: "production"+ });+ const started = await startAllMatchingBulkAction(+ formData.get("allMatching"),+ { companyId, userId, actionKey: "jobs.delete", params: {} }+ );+ if (started) return bulkStartFormResponse(started);++ const result = await bulkDeleteJobs({+ client,+ jobIds: ids as string[],+ companyId+ });+ return result.error+ ? { error: { message: result.error }, data: null }+ : { data: null, error: null };+ }+// Per-ID locked checkconst jobs = await client.from("job").select("id, status, quantity, fixedAssetClassId, fixedAssetId")- .in("id", ids as string[]);+ .in("id", ids as string[])+ .eq("companyId", companyId);const lockedError = requireUnlockedBulk({statuses: (jobs.data ?? []).map((j) => j.status),@@ -50,13 +78,6 @@ export async function action({ request }: ActionFunctionArgs) {const serviceRole = await getCarbonServiceRole();- if (field === "delete") {- return await client- .from("job")- .delete()- .in("id", ids as string[])- .eq("companyId", companyId);- }if (typeof value !== "string" && value !== null) {return { error: { message: "Invalid form data" }, data: null };}diff --git a/apps/erp/app/routes/x+/people+/attributes.tsx b/apps/erp/app/routes/x+/people+/attributes.tsxindex 381e41e005..b0f68126c5 100644--- a/apps/erp/app/routes/x+/people+/attributes.tsx+++ b/apps/erp/app/routes/x+/people+/attributes.tsx@@ -2,22 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import {- getAttributeCategories,- getAttributeDataTypes-} from "~/modules/people";+import { getAttributeDataTypes } from "~/modules/people";import { AttributeCategoriesTable } from "~/modules/people/ui/Attributes";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { attributeCategoriesList } from "~/utils/list-registry/people.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Attributes`,@@ -25,51 +19,28 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "people",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [categories, dataTypes] = await Promise.all([- getAttributeCategories(client, companyId, {- search,- limit,- offset,- sorts,- filters+ return loadListPage(request, attributeCategoriesList, {+ dataKey: "categories",+ firstPage: async ({ client }) => ({+ dataTypes: (await getAttributeDataTypes(client)).data ?? []}),- getAttributeDataTypes(client)- ]);-- if (categories.error) {- redirect(- path.to.authenticatedRoot,- await flash(- request,- error(categories.error, "Failed to fetch attribute categories")- )- );- }-- return {- count: categories.count ?? 0,- categories: categories.data ?? [],- dataTypes: dataTypes.data ?? []- };+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch attribute categories"+ }+ });}export default function UserAttributesRoute() {- const { count, categories } = useLoaderData<typeof loader>();+ const { count, categories, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <AttributeCategoriesTable data={categories} count={count} />+ <AttributeCategoriesTable+ data={categories}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/people+/employee.tsx b/apps/erp/app/routes/x+/people+/employee.tsxindex 9e399a7e28..c4cc71deb4 100644--- a/apps/erp/app/routes/x+/people+/employee.tsx+++ b/apps/erp/app/routes/x+/people+/employee.tsx@@ -3,80 +3,71 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import {- getAttributeCategories,- getPeople,- getShiftsList-} from "~/modules/people";+import { getAttributeCategories, getShiftsList } from "~/modules/people";import { PeopleTable } from "~/modules/people/ui/People";import { getEmployeeTypes } from "~/modules/users";+import { loadListPage } from "~/utils/list-registry/load.server";+import { peopleList } from "~/utils/list-registry/people.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "people",- role: "employee",- bypassRls: true+ return loadListPage(request, peopleList, {+ dataKey: "people",+ bypassRls: true,+ firstPage: async ({ client, companyId, request }) => {+ const [attributeCategories, employeeTypes, shifts] = await Promise.all([+ getAttributeCategories(client, companyId),+ getEmployeeTypes(client, companyId),+ getShiftsList(client, companyId, null)+ ]);+ if (attributeCategories.error) {+ throw redirect(+ path.to.authenticatedRoot,+ await flash(+ request,+ error(+ attributeCategories.error,+ "Error loading attribute categories"+ )+ )+ );+ }+ if (employeeTypes.error) {+ throw redirect(+ path.to.authenticatedRoot,+ await flash(+ request,+ error(employeeTypes.error, "Error loading employee types")+ )+ );+ }+ return {+ attributeCategories: attributeCategories.data ?? [],+ employeeTypes: employeeTypes.data ?? [],+ shifts: shifts.data ?? []+ };+ },+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Error loading people"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("name");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [attributeCategories, employeeTypes, people, shifts] =- await Promise.all([- getAttributeCategories(client, companyId),- getEmployeeTypes(client, companyId),- getPeople(client, companyId, { search, limit, offset, sorts, filters }),- getShiftsList(client, companyId, null)- ]);- if (attributeCategories.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(- request,- error(attributeCategories.error, "Error loading attribute categories")- )- );- }- if (employeeTypes.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(- request,- error(employeeTypes.error, "Error loading employee types")- )- );- }- if (people.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(request, error(people.error, "Error loading people"))- );- }-- return {- attributeCategories: attributeCategories.data,- employeeTypes: employeeTypes.data ?? [],- people: people.data ?? [],- shifts: shifts.data ?? [],- count: people.count ?? 0- };}export default function ResourcesPeopleRoute() {- const { attributeCategories, count, employeeTypes, people, shifts } =- useLoaderData<typeof loader>();+ const {+ attributeCategories,+ count,+ employeeTypes,+ people,+ shifts,+ nextCursor+ } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">@@ -84,6 +75,7 @@ export default function ResourcesPeopleRoute() {attributeCategories={attributeCategories}data={people ?? []}count={count ?? 0}+ nextCursor={nextCursor}employeeTypes={employeeTypes}shifts={shifts}/>diff --git a/apps/erp/app/routes/x+/people+/holidays.tsx b/apps/erp/app/routes/x+/people+/holidays.tsxindex 21e677eb69..8dd266d076 100644--- a/apps/erp/app/routes/x+/people+/holidays.tsx+++ b/apps/erp/app/routes/x+/people+/holidays.tsx@@ -2,19 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getHolidays, getHolidayYears } from "~/modules/people";+import { getHolidayYears } from "~/modules/people";import { HolidaysTable } from "~/modules/people/ui/Holidays";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { holidaysList } from "~/utils/list-registry/people.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Holidays`,@@ -22,50 +19,31 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "people",- role: "employee",- bypassRls: true+ return loadListPage(request, holidaysList, {+ dataKey: "holidays",+ bypassRls: true,+ firstPage: async ({ client, companyId }) => {+ const years = await getHolidayYears(client, companyId);+ return {+ years:+ years.data?.map((d) => d.year as number).sort((a, b) => b - a) ?? []+ };+ },+ onError: { redirectTo: path.to.people, message: "Failed to load holidays" }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [holidays, years] = await Promise.all([- getHolidays(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getHolidayYears(client, companyId)- ]);-- if (holidays.error) {- throw redirect(- path.to.people,- await flash(request, error(holidays.error, "Failed to load holidays"))- );- }-- return {- holidays: holidays.data ?? [],- years:- years?.data?.map((d) => d.year as number).sort((a, b) => b - a) ?? [],- count: holidays.count ?? 0- };}export default function Route() {- const { holidays, years, count } = useLoaderData<typeof loader>();+ const { holidays, years, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <HolidaysTable data={holidays} count={count} years={years} />+ <HolidaysTable+ data={holidays}+ count={count}+ nextCursor={nextCursor}+ years={years}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/people+/shifts.tsx b/apps/erp/app/routes/x+/people+/shifts.tsxindex 6b3be2a0cd..f52973ce4f 100644--- a/apps/erp/app/routes/x+/people+/shifts.tsx+++ b/apps/erp/app/routes/x+/people+/shifts.tsx@@ -2,20 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getShifts } from "~/modules/people";import { ShiftsTable } from "~/modules/people/ui/Shifts";import { getLocations } from "~/modules/resources/resources.service";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { shiftsList } from "~/utils/list-registry/people.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Shifts`,@@ -23,43 +19,28 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "people",- role: "employee",- bypassRls: true+ return loadListPage(request, shiftsList, {+ dataKey: "shifts",+ bypassRls: true,+ firstPage: async ({ client, companyId }) => ({+ locations: (await getLocations(client, companyId)).data ?? []+ }),+ onError: { redirectTo: path.to.people, message: "Failed to load shifts" }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [shifts, locations] = await Promise.all([- getShifts(client, companyId, { search, limit, offset, sorts, filters }),- getLocations(client, companyId)- ]);-- if (shifts.error) {- throw redirect(- path.to.people,- await flash(request, error(shifts.error, "Failed to load shifts"))- );- }-- return {- shifts: shifts.data ?? [],- locations: locations.data ?? [],- count: shifts.count ?? 0- };}export default function ShiftsRoute() {- const { shifts, locations, count } = useLoaderData<typeof loader>();+ const { shifts, locations, count, nextCursor } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ShiftsTable data={shifts} count={count} locations={locations} />+ <ShiftsTable+ data={shifts}+ count={count}+ nextCursor={nextCursor}+ locations={locations}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/people+/timecard.tsx b/apps/erp/app/routes/x+/people+/timecard.tsxindex b23d226d3b..c43a3aa0f6 100644--- a/apps/erp/app/routes/x+/people+/timecard.tsx+++ b/apps/erp/app/routes/x+/people+/timecard.tsx@@ -3,19 +3,18 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getTimecardEntries } from "~/modules/people";import { TimecardsTable } from "~/modules/people/ui/Timecards";import { getCompanySettings } from "~/modules/settings";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { timecardEntriesList } from "~/utils/list-registry/people.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Timecards`,@@ -23,60 +22,36 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "people"+ return loadListPage(request, timecardEntriesList, {+ dataKey: "entries",+ guard: async ({ client, companyId, request }) => {+ const companySettings = await getCompanySettings(client, companyId);+ if (!companySettings.data?.timeCardEnabled) {+ throw redirect(+ path.to.people,+ await flash(+ request,+ error(+ null,+ "Timecards are not enabled. To enable this feature, go to Settings → People to enable Timecards."+ )+ )+ );+ }+ },+ onError: {+ redirectTo: path.to.people,+ message: "Failed to load timecard entries"+ }});-- const companySettings = await getCompanySettings(client, companyId);- if (!companySettings.data?.timeCardEnabled) {- throw redirect(- path.to.people,- await flash(- request,- error(- null,- "Timecards are not enabled. To enable this feature, go to Settings → People to enable Timecards."- )- )- );- }-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const entries = await getTimecardEntries(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (entries.error) {- throw redirect(- path.to.people,- await flash(- request,- error(entries.error, "Failed to load timecard entries")- )- );- }-- return {- entries: entries.data ?? [],- count: entries.count ?? 0- };}export default function Route() {- const { entries, count } = useLoaderData<typeof loader>();+ const { entries, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <TimecardsTable data={entries} count={count} />+ <TimecardsTable data={entries} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/production+/assemblies.tsx b/apps/erp/app/routes/x+/production+/assemblies.tsxindex 0b0d917331..6118fe6524 100644--- a/apps/erp/app/routes/x+/production+/assemblies.tsx+++ b/apps/erp/app/routes/x+/production+/assemblies.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getAssemblyInstructions } from "~/modules/production";import AssemblyInstructionsTable from "~/modules/production/ui/Assemblies/AssemblyInstructionsTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { assemblyInstructionsList } from "~/utils/list-registry/production.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Assemblies`,@@ -19,35 +18,21 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "production",- role: "employee"+ return loadListPage(request, assemblyInstructionsList, {+ dataKey: "instructions"});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset } = getGenericQueryFilters(searchParams);-- const instructions = await getAssemblyInstructions(client, {- companyId,- search: search ?? undefined,- limit,- offset- });-- return {- instructions: instructions.data ?? [],- count: instructions.count ?? 0- };}export default function AssemblyInstructionsRoute() {- const { instructions, count } = useLoaderData<typeof loader>();+ const { instructions, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <AssemblyInstructionsTable data={instructions} count={count} />+ <AssemblyInstructionsTable+ data={instructions}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/production+/batches.dissolve.tsx b/apps/erp/app/routes/x+/production+/batches.dissolve.tsxindex 8bc84dc50c..c9c82c50b2 100644--- a/apps/erp/app/routes/x+/production+/batches.dissolve.tsx+++ b/apps/erp/app/routes/x+/production+/batches.dissolve.tsx@@ -4,55 +4,59 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { getErrorMessage } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";-import { updateJobOperationBatch } from "~/modules/production";+import { bulkDissolveBatches } from "~/modules/production/bulk-actions.server";import { getDatabaseClient } from "~/services/database.server";+import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";-// Bulk dissolve — one server-fn dissolve per selected batch. Each is independent:-// a batch that has recorded production is refused (the server fn's own guard) and-// reported in `failed` while the rest still dissolve. Fetcher-driven; the table-// toasts the summary and the loader revalidates.+// Bulk dissolve — one server-fn dissolve per selected Planned or Active batch.+// Each is independent: a batch that has recorded production is refused (the+// server fn's own guard) and reported in `failed` while the rest still+// dissolve; a Completing or Completed batch is skipped. `{ allMatching }` in+// place of `batchIds` dissolves every matching batch in the background job+// instead. Fetcher-driven; the table toasts the summary and the loader+// revalidates.export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);const { client, companyId, userId } = await requirePermissions(request, {update: "production"});- const { batchIds } = (await request.json()) as { batchIds?: string[] };- const ids = [...new Set((batchIds ?? []).filter(Boolean))];+ const json = (await request.json().catch(() => null)) as {+ batchIds?: string[];+ allMatching?: unknown;+ } | null;+ const started = await startAllMatchingBulkAction(json?.allMatching, {+ companyId,+ userId,+ actionKey: "batches.dissolve",+ params: {}+ });+ if (started) return started;++ const ids = [+ ...new Set(+ (Array.isArray(json?.batchIds) ? json.batchIds : []).filter(+ (id): id is string => typeof id === "string" && id.length > 0+ )+ )+ ];if (ids.length === 0) {return { success: false, message: "No batches selected" };}- // Resolve readable ids up front so failures name the batch, not its nanoid.- const rows = await client- .from("jobOperationBatch")- .select("id, readableId")- .in("id", ids)- .eq("companyId", companyId);- const readableById = new Map(- (rows.data ?? []).map((r) => [r.id, r.readableId] as const)- );-- let dissolved = 0;- const failed: { readableId: string; message: string }[] = [];- for (const batchId of ids) {- const result = await updateJobOperationBatch(client, getDatabaseClient(), {- type: "dissolve",- batchId,- companyId,- userId- });- if (result.error) {- failed.push({- readableId: readableById.get(batchId) ?? batchId,- message: getErrorMessage(result.error, "Failed to dissolve")- });- } else {- dissolved += 1;- }- }-- return { success: true, dissolved, failed };+ const result = await bulkDissolveBatches({+ client,+ db: getDatabaseClient(),+ batchIds: ids,+ companyId,+ userId+ });+ if (!result.success) return result;+ return {+ success: true,+ dissolved: result.done,+ failed: result.failed,+ skipped: result.skipped+ };}diff --git a/apps/erp/app/routes/x+/production+/batches.release.tsx b/apps/erp/app/routes/x+/production+/batches.release.tsxindex 467c09548f..d192bb299a 100644--- a/apps/erp/app/routes/x+/production+/batches.release.tsx+++ b/apps/erp/app/routes/x+/production+/batches.release.tsx@@ -4,22 +4,26 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { getErrorMessage } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { z } from "zod";-import {- notifyScheduleInputsChanged,- releaseJobOperationBatch-} from "~/modules/production";-import { releaseBatchMemberJobs } from "~/modules/production/production.server";+import { bulkReleaseBatches } from "~/modules/production/bulk-actions.server";import { getDatabaseClient } from "~/services/database.server";+import { fitsOneRequest } from "~/utils/table-jobs";+import {+ startAllMatchingBulkAction,+ startSelectedBulkAction+} from "~/utils/table-jobs.server";// Bulk release — one release per selected Planned batch. Each is independent:// a batch the server fn refuses (no members, already recorded production) is// reported in `failed` while the rest still release. Only Planned batches are-// released — the caller filters, and any non-Planned id is refused here too so a-// stale selection can't flip an Active/Completing batch. Fetcher-driven; the-// table toasts the summary and the loader revalidates.+// released — the caller filters, and bulkReleaseBatches skips any other status+// too, so a stale selection can't flip an Active/Completing batch.+// `{ allMatching: { listKey, search } }` in place of `batchIds` releases every+// matching batch in the background job instead, up to 2,000 batches. More+// than 10 selected batches also go to the background job: each releases its+// member jobs with MRP, and one request must end before the 600 s cutoff.+// Fetcher-driven; the table toasts the summary and the loader revalidates.const bodySchema = z.object({ batchIds: z.array(z.string()) });export async function action({ request }: ActionFunctionArgs) {@@ -30,7 +34,16 @@ export async function action({ request }: ActionFunctionArgs) {// A body that is not JSON, or not the shape the table sends, is a plain// refusal rather than a 500.- const body = bodySchema.safeParse(await request.json().catch(() => null));+ const json = await request.json().catch(() => null);+ const started = await startAllMatchingBulkAction(json?.allMatching, {+ companyId,+ userId,+ actionKey: "batches.release",+ params: {}+ });+ if (started) return started;++ const body = bodySchema.safeParse(json);if (!body.success) {return { success: false, message: "Invalid request" };}@@ -38,82 +51,29 @@ export async function action({ request }: ActionFunctionArgs) {if (ids.length === 0) {return { success: false, message: "No batches selected" };}-- // Resolve readable ids + status + work center up front: failures name the- // batch (not its nanoid), we only release Planned batches, and the notify- // needs the work center.- const rows = await client- .from("jobOperationBatch")- .select("id, readableId, status, workCenterId")- .in("id", ids)- .eq("companyId", companyId);- if (rows.error) {- return { success: false, message: "Failed to load the selected batches" };- }- const batchById = new Map((rows.data ?? []).map((r) => [r.id, r] as const));-- let released = 0;- const failed: { readableId: string; message: string }[] = [];- for (const batchId of ids) {- const batch = batchById.get(batchId);- if (!batch || batch.status !== "Planned") {- // Silently skip a stale selection — nothing was released, nothing failed.- continue;- }-- const members = await client- .from("jobOperation")- .select("jobId")- .eq("jobOperationBatchId", batchId)- .eq("companyId", companyId);- if (members.error) {- failed.push({- readableId: batch.readableId,- message: "Failed to load the batch members"- });- continue;- }-- // Member jobs release first, through the job page's release path. With no- // dialog here, a batch with an invalid job or a PO choice to make is- // skipped and named — the planner releases it from its drawer.- const releasedJobs = await releaseBatchMemberJobs({- client,- db: getDatabaseClient(),- jobIds: (members.data ?? []).map((op) => op.jobId),- companyId,- userId- });- if (releasedJobs.error) {- failed.push({- readableId: batch.readableId,- message: releasedJobs.error- });- continue;- }-- const result = await releaseJobOperationBatch(client, getDatabaseClient(), {- batchId,+ if (!fitsOneRequest("batches.release", ids.length)) {+ return startSelectedBulkAction({companyId,- userId+ userId,+ actionKey: "batches.release",+ params: {},+ listKey: "operation-batches",+ ids});- if (result.error) {- failed.push({- readableId: batch.readableId,- message: getErrorMessage(result.error, "Failed to release")- });- continue;- }-- // After the status flip is persisted — the wave must see the new state.- await notifyScheduleInputsChanged(- companyId,- "work-center",- "batch released",- batch.workCenterId ?? undefined- );- released += 1;}- return { success: true, released, failed };+ const result = await bulkReleaseBatches({+ client,+ db: getDatabaseClient(),+ batchIds: ids,+ companyId,+ userId+ });+ if (!result.success) return result;+ return {+ success: true,+ released: result.done,+ failed: result.failed,+ skipped: result.skipped+ };}diff --git a/apps/erp/app/routes/x+/production+/batches.tsx b/apps/erp/app/routes/x+/production+/batches.tsxindex 05dc2c6ada..d9579c2e0c 100644--- a/apps/erp/app/routes/x+/production+/batches.tsx+++ b/apps/erp/app/routes/x+/production+/batches.tsx@@ -3,19 +3,23 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";+import { getLogger } from "@carbon/logger";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import {- getJobOperationBatches,getJobOperationBatchMemberStats,getJobOperationBatchMembers} from "~/modules/production";import BatchesTable from "~/modules/production/ui/Batches/BatchesTable";import type { Handle } from "~/utils/handle";+import { fetchListPage } from "~/utils/list-registry/index.server";+import { listErrorPage } from "~/utils/list-registry/load.server";+import { operationBatchesList } from "~/utils/list-registry/production.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";++const logger = getLogger("erp", "batches");export const handle: Handle = {breadcrumb: msg`Batches`,@@ -23,34 +27,39 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "production",- role: "employee"- });+ const { client, companyId } = await requirePermissions(+ request,+ operationBatchesList.permission+ );- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);+ const searchParams = new URL(request.url).searchParams;+ const batches = await fetchListPage(+ operationBatchesList,+ client,+ companyId,+ searchParams+ );- const batches = await getJobOperationBatches(client, companyId, {- search,- limit,- offset,- sorts,- filters- });+ if (batches.error && searchParams.get("after")) {+ logger.error("Failed to load a later page of batches", {+ companyId,+ error: batches.error+ });+ return listErrorPage("batches");+ }- const batchIds = (batches.data ?? []).map((b) => b.id);+ // The member stats and rows of this page's batches only. A later page+ // (`?after=`) brings its own, in its rows.+ const batchIds = batches.rows.map((b) => b.id);const [stats, members] = await Promise.all([getJobOperationBatchMemberStats(client, companyId, batchIds),getJobOperationBatchMembers(client, companyId, batchIds)]);return {- count: batches.count ?? 0,- batches: (batches.data ?? []).map((b) => ({+ count: batches.count,+ nextCursor: batches.nextCursor,+ batches: batches.rows.map((b) => ({...b,memberCount: stats.data[b.id]?.memberCount ?? 0,totalQuantity: stats.data[b.id]?.totalQuantity ?? 0,@@ -66,11 +75,11 @@ export async function loader({ request }: LoaderFunctionArgs) {}export default function BatchesRoute() {- const { batches, count } = useLoaderData<typeof loader>();+ const { batches, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <BatchesTable data={batches} count={count} />+ <BatchesTable data={batches} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/production+/demand-forecasts.tsx b/apps/erp/app/routes/x+/production+/demand-forecasts.tsxindex 4c63628997..7f263d0b56 100644--- a/apps/erp/app/routes/x+/production+/demand-forecasts.tsx+++ b/apps/erp/app/routes/x+/production+/demand-forecasts.tsx@@ -5,6 +5,7 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";import { RecordOutlet, VStack } from "@carbon/react";import { datetime, redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";@@ -12,16 +13,23 @@ import { Trans } from "@lingui/react/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { usePlanGate } from "~/hooks/usePlanGate";-import { getProductionProjections } from "~/modules/production";+import {+ getProductionProjections,+ PRODUCTION_PROJECTIONS_PAGING+} from "~/modules/production";import DemandProjectionsTable from "~/modules/production/ui/DemandProjection/DemandProjectionTable";import ForecastUpgradeOverlay from "~/modules/production/ui/ForecastUpgradeOverlay";import { resolveLocationId } from "~/modules/shared/location.server";import { getOrCreatePeriods } from "~/modules/shared/shared.server";import { getLocationTimeZone } from "~/modules/shared/timezone.server";+import { toPage } from "~/utils/cursor";import type { Handle } from "~/utils/handle";+import { listErrorPage } from "~/utils/list-registry/load.server";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";+const logger = getLogger("erp", "demand-forecasts");+export const handle: Handle = {breadcrumb: msg`Demand Forecasts`,to: path.to.demandProjections@@ -39,7 +47,7 @@ export async function loader({ request }: LoaderFunctionArgs) {const url = new URL(request.url);const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =+ const { limit, cursor, sorts, filters } =getGenericQueryFilters(searchParams);const locationId = await resolveLocationId(client, request, {@@ -63,13 +71,20 @@ export async function loader({ request }: LoaderFunctionArgs) {{search,limit,- offset,+ cursor,sorts,filters});if (projections.error) {+ if (cursor) {+ logger.error("Failed to load a later page of production projections", {+ companyId,+ error: projections.error+ });+ return listErrorPage("projections");+ }throw redirect(path.to.production,await flash(@@ -79,16 +94,23 @@ export async function loader({ request }: LoaderFunctionArgs) {);}+ const page = toPage(+ projections.data ?? [],+ { limit, sorts },+ PRODUCTION_PROJECTIONS_PAGING+ );+return {- projections: projections.data ?? [],- count: projections.data?.length ?? 0,+ projections: page.rows,+ count: projections.count ?? 0,+ nextCursor: page.nextCursor,locationId,periods};}export default function DemandProjectionsRoute() {- const { projections, count, locationId, periods } =+ const { projections, count, nextCursor, locationId, periods } =useLoaderData<typeof loader>();const { isGated } = usePlanGate({ feature: "FORECAST" });@@ -112,6 +134,7 @@ export default function DemandProjectionsRoute() {<DemandProjectionsTabledata={projections}count={count}+ nextCursor={nextCursor}locationId={locationId}periods={periods}/>diff --git a/apps/erp/app/routes/x+/production+/jobs.tsx b/apps/erp/app/routes/x+/production+/jobs.tsxindex 9e046e2e31..148924ac41 100644--- a/apps/erp/app/routes/x+/production+/jobs.tsx+++ b/apps/erp/app/routes/x+/production+/jobs.tsx@@ -2,21 +2,20 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getJobs } from "~/modules/production";import { JobsTable } from "~/modules/production/ui/Jobs";import { getLocationsList } from "~/modules/resources";import { getTagsList } from "~/modules/shared";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import {+ jobsList,+ withJobListExtras+} from "~/utils/list-registry/production.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["job"],@@ -25,79 +24,31 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "production",- role: "employee",- bypassRls: true+ return loadListPage(request, jobsList, {+ dataKey: "jobs",+ bypassRls: true,+ firstPage: async ({ client, companyId }) => {+ const [locations, tags] = await Promise.all([+ getLocationsList(client, companyId),+ getTagsList(client, companyId, "job")+ ]);+ return { locations: locations.data ?? [], tags: tags.data ?? [] };+ },+ mapRows: withJobListExtras,+ onError: { redirectTo: path.to.production, message: "Failed to fetch jobs" }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [jobs, locations, tags] = await Promise.all([- getJobs(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getLocationsList(client, companyId),- getTagsList(client, companyId, "job")- ]);-- if (jobs.error) {- redirect(- path.to.production,- await flash(request, error(jobs.error, "Failed to fetch jobs"))- );- }-- // Which of this page's jobs have an operation in a live (Active/Completing)- // batch. The jobs view carries no batch column — batching is per-operation —- // so one secondary lookup builds jobId -> batch readableIds for the badge.- const jobIds = (jobs.data ?? []).map((j) => j.id!).filter(Boolean);- const batchedOps =- jobIds.length > 0- ? await client- .from("jobOperation")- .select("jobId, jobOperationBatch(id, readableId, status)")- .in("jobId", jobIds)- .eq("companyId", companyId)- .not("jobOperationBatchId", "is", null)- : { data: [], error: null };- const batchesByJobId: Record<string, string[]> = {};- for (const op of batchedOps.data ?? []) {- const batch = op.jobOperationBatch;- if (!batch || (batch.status !== "Active" && batch.status !== "Completing"))- continue;- if (!op.jobId || !batch.readableId) continue;- const list = (batchesByJobId[op.jobId] ??= []);- if (!list.includes(batch.readableId)) list.push(batch.readableId);- }-- return {- count: jobs.count ?? 0,- jobs: jobs.data ?? [],- batchesByJobId,- locations: locations.data ?? [],- tags: tags.data ?? []- };}export default function JobsRoute() {- const { count, tags, jobs, batchesByJobId } = useLoaderData<typeof loader>();+ const { count, tags, jobs, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full"><JobsTabledata={jobs}count={count}+ nextCursor={nextCursor}tags={tags}- batchesByJobId={batchesByJobId}/><RecordOutlet /></VStack>diff --git a/apps/erp/app/routes/x+/production+/planning.tsx b/apps/erp/app/routes/x+/production+/planning.tsxindex c20576bb65..ca6bc5f1c4 100644--- a/apps/erp/app/routes/x+/production+/planning.tsx+++ b/apps/erp/app/routes/x+/production+/planning.tsx@@ -21,13 +21,17 @@ import {getPlanningActions,getProductionPlanning,PLANNING_DRAWER_PARAM,- resolvePlanningActionScope+ PRODUCTION_PLANNING_PAGING,+ resolvePlanningActionScope,+ withPlanningActions} from "~/modules/production";import ProductionPlanningTable from "~/modules/production/ui/Planning/ProductionPlanningTable";import { resolveLocationId } from "~/modules/shared/location.server";import { getOrCreatePeriods } from "~/modules/shared/shared.server";import { getLocationTimeZone } from "~/modules/shared/timezone.server";+import { toPage } from "~/utils/cursor";import type { Handle } from "~/utils/handle";+import { listErrorPage } from "~/utils/list-registry/list-error";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";@@ -52,7 +56,7 @@ export async function loader({ request }: LoaderFunctionArgs) {const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =+ const { limit, cursor, sorts, filters } =getGenericQueryFilters(searchParams);const locationId = await resolveLocationId(client, request, {@@ -80,13 +84,14 @@ export async function loader({ request }: LoaderFunctionArgs) {// A link to a row's order drawer (`?item=`) opens it even when the row is// not on this page — the plan has changed since the link was made, or it// came from another page. That row is read on its own, alongside the page.- const drawerItemId = searchParams.get(PLANNING_DRAWER_PARAM);+ // A later page (`?after=`) is read for its rows and their actions only.+ const drawerItemId = cursor ? null : searchParams.get(PLANNING_DRAWER_PARAM);const [items, drawerItemRead] = await Promise.all([getProductionPlanning(client, locationId, companyId, periodIds, {search,limit,- offset,+ cursor,sorts,filters: gridFilters,asOf,@@ -97,7 +102,7 @@ export async function loader({ request }: LoaderFunctionArgs) {? getProductionPlanning(client, locationId, companyId, periodIds, {search: null,limit: 1,- offset: 0,+ cursor: null,sorts: [],filters: [{ column: "id", operator: "eq", value: drawerItemId }],asOf@@ -106,7 +111,14 @@ export async function loader({ request }: LoaderFunctionArgs) {]);if (items.error) {- redirect(+ logger.error("Failed to load the planning items", {+ companyId,+ locationId,+ laterPage: Boolean(cursor),+ error: items.error+ });+ if (cursor) return listErrorPage("items");+ throw redirect(path.to.production,await flash(request, error(items.error, "Failed to fetch planning items")));@@ -122,7 +134,12 @@ export async function loader({ request }: LoaderFunctionArgs) {error: drawerItemRead.error});}- const pageItems = (items.data ?? []) as ProductionPlanningItem[];+ const page = toPage(+ (items.data ?? []) as ProductionPlanningItem[],+ { limit, sorts },+ PRODUCTION_PLANNING_PAGING+ );+ const pageItems = page.rows;const linkedItem = (drawerItemRead?.data?.[0] ??null) as ProductionPlanningItem | null;const drawerItem =@@ -151,15 +168,20 @@ export async function loader({ request }: LoaderFunctionArgs) {locationId,error: planningActions.error});+ if (cursor) return listErrorPage("items");throw new Response("Failed to load planning actions", { status: 500 });}+ // Each row carries its own actions, so a later page brings its rows' actions.+ const actions = planningActions.data ?? [];return {- items: pageItems,+ items: withPlanningActions(pageItems, actions),// The row a `?item=` link opens the drawer on, when it is not in `items`.- drawerItem,+ drawerItem: drawerItem+ ? (withPlanningActions([drawerItem], actions)[0] ?? null)+ : null,count: items.count ?? 0,- planningActions: planningActions.data ?? [],+ nextCursor: page.nextCursor,// The Actions-column filter the rows were matched on: each row shows only// its actions of these types.actionTypes: actionTypes ?? null,@@ -176,9 +198,9 @@ export default function ProductionPlanningRoute() {items,drawerItem,count,+ nextCursor,locationId,periods,- planningActions,actionTypes,locationToday} = useLoaderData<typeof loader>();@@ -196,9 +218,9 @@ export default function ProductionPlanningRoute() {data={items}drawerItem={drawerItem}count={count}+ nextCursor={nextCursor}locationId={locationId}periods={periods}- planningActions={planningActions}actionTypes={actionTypes}locationToday={locationToday}/>diff --git a/apps/erp/app/routes/x+/production+/procedures.tsx b/apps/erp/app/routes/x+/production+/procedures.tsxindex cb10e7b021..840a6324d7 100644--- a/apps/erp/app/routes/x+/production+/procedures.tsx+++ b/apps/erp/app/routes/x+/production+/procedures.tsx@@ -2,17 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getProcedures } from "~/modules/production";import ProceduresTable from "~/modules/production/ui/Procedures/ProceduresTable";import { getTagsList } from "~/modules/shared";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { proceduresList } from "~/utils/list-registry/production.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Procedures`,@@ -20,41 +19,26 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "production",- role: "employee"+ return loadListPage(request, proceduresList, {+ dataKey: "procedures",+ firstPage: async ({ client, companyId }) => ({+ tags: (await getTagsList(client, companyId, "procedure")).data ?? []+ })});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [procedures, tags] = await Promise.all([- getProcedures(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getTagsList(client, companyId, "procedure")- ]);-- return {- procedures: procedures.data ?? [],- tags: tags.data ?? [],- count: procedures.count ?? 0- };}export default function ProceduresRoute() {- const { procedures, tags, count } = useLoaderData<typeof loader>();+ const { procedures, tags, count, nextCursor } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ProceduresTable data={procedures} tags={tags} count={count} />+ <ProceduresTable+ data={procedures}+ tags={tags}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/production+/scrap-reasons.tsx b/apps/erp/app/routes/x+/production+/scrap-reasons.tsxindex b47cd9f8c0..8a1b5d00cf 100644--- a/apps/erp/app/routes/x+/production+/scrap-reasons.tsx+++ b/apps/erp/app/routes/x+/production+/scrap-reasons.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getScrapReasons } from "~/modules/production";import ScrapReasonsTable from "~/modules/production/ui/ScrapReasons/ScrapReasonsTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { scrapReasonsList } from "~/utils/list-registry/production.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Scrap Reasons`,@@ -19,32 +18,15 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "production",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getScrapReasons(client, companyId, {- search,- limit,- offset,- sorts,- filters- });+ return loadListPage(request, scrapReasonsList, { dataKey: "data" });}export default function ScrapReasonsRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ScrapReasonsTable data={data ?? []} count={count ?? 0} />+ <ScrapReasonsTable data={data} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/purchase-order+/update.tsx b/apps/erp/app/routes/x+/purchase-order+/update.tsxindex 14f45f1318..1dd34500d7 100644--- a/apps/erp/app/routes/x+/purchase-order+/update.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/update.tsx@@ -7,7 +7,10 @@ import { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { getExchangeRate } from "~/modules/accounting";import { isPurchaseOrderLocked } from "~/modules/purchasing";+import { bulkDeletePurchaseOrders } from "~/modules/purchasing/purchasing.server";import { requireUnlockedBulk } from "~/utils/lockedGuard.server";+import { bulkStartFormResponse } from "~/utils/table-jobs";+import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";export async function action({ request }: ActionFunctionArgs) {const { client, companyId, userId } = await requirePermissions(request, {@@ -23,11 +26,27 @@ export async function action({ request }: ActionFunctionArgs) {return { error: { message: "Invalid form data" }, data: null };}+ // The purchase orders table's bulk Delete. It deletes the company's Draft+ // and Planned orders only (bulkDeletePurchaseOrders skips the rest), and+ // needs the delete permission as well as update, as the table does.if (field === "delete") {- return await client- .from("purchaseOrder")- .delete()- .in("id", ids as string[]);+ await requirePermissions(request, {+ update: "purchasing",+ delete: "purchasing"+ });+ const started = await startAllMatchingBulkAction(+ formData.get("allMatching"),+ { companyId, userId, actionKey: "purchase-orders.delete", params: {} }+ );+ if (started) return bulkStartFormResponse(started);++ const result = await bulkDeletePurchaseOrders(client, {+ purchaseOrderIds: ids as string[],+ companyId+ });+ return result.error+ ? { error: { message: result.error }, data: null }+ : { data: null, error: null };}// Check if any of the POs are locked except for deliveryDatediff --git a/apps/erp/app/routes/x+/purchasing+/leases.tsx b/apps/erp/app/routes/x+/purchasing+/leases.tsxindex eab234a568..d85455d401 100644--- a/apps/erp/app/routes/x+/purchasing+/leases.tsx+++ b/apps/erp/app/routes/x+/purchasing+/leases.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getLeases } from "~/modules/purchasing";import { LeasesTable } from "~/modules/purchasing/ui/Leases";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { leasesList } from "~/utils/list-registry/purchasing.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Leases`,@@ -22,44 +18,21 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "purchasing"+ return loadListPage(request, leasesList, {+ dataKey: "leases",+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch leases"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const leases = await getLeases(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (leases.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(request, error(leases.error, "Failed to fetch leases"))- );- }-- return {- count: leases.count ?? 0,- leases: leases.data ?? []- };}export default function LeasesRoute() {- const { count, leases } = useLoaderData<typeof loader>();+ const { count, leases, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <LeasesTable data={leases} count={count} />+ <LeasesTable data={leases} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/purchasing+/orders.tsx b/apps/erp/app/routes/x+/purchasing+/orders.tsxindex 8ede5e4153..5627e37056 100644--- a/apps/erp/app/routes/x+/purchasing+/orders.tsx+++ b/apps/erp/app/routes/x+/purchasing+/orders.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getPurchaseOrders } from "~/modules/purchasing";import { PurchaseOrdersTable } from "~/modules/purchasing/ui/PurchaseOrder";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { purchaseOrdersList } from "~/utils/list-registry/purchasing.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["purchaseOrder"],@@ -23,52 +19,26 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "purchasing",- bypassRls: true+ return loadListPage(request, purchaseOrdersList, {+ dataKey: "purchasOrders",+ bypassRls: true,+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch purchase orders"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const status = searchParams.get("status");- const supplierId = searchParams.get("supplierId");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const purchasOrders = await getPurchaseOrders(client, companyId, {- search,- status,- supplierId,- limit,- offset,- sorts,- filters- });-- if (purchasOrders.error) {- redirect(- path.to.authenticatedRoot,- await flash(- request,- error(purchasOrders.error, "Failed to fetch purchase orders")- )- );- }-- return {- count: purchasOrders.count ?? 0,- purchasOrders: purchasOrders.data ?? []- };}export default function PurchaseOrdersSearchRoute() {- const { count, purchasOrders } = useLoaderData<typeof loader>();+ const { count, purchasOrders, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <PurchaseOrdersTable data={purchasOrders} count={count} />+ <PurchaseOrdersTable+ data={purchasOrders}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/purchasing+/planning.tsx b/apps/erp/app/routes/x+/purchasing+/planning.tsxindex 77cc6d0ac5..1408900fc3 100644--- a/apps/erp/app/routes/x+/purchasing+/planning.tsx+++ b/apps/erp/app/routes/x+/purchasing+/planning.tsx@@ -19,15 +19,21 @@ import { useLoaderData } from "react-router";import {getPlanningActions,PLANNING_DRAWER_PARAM,- resolvePlanningActionScope+ resolvePlanningActionScope,+ withPlanningActions} from "~/modules/production";import type { PurchasingPlanningItem } from "~/modules/purchasing";-import { getPurchasingPlanning } from "~/modules/purchasing";+import {+ getPurchasingPlanning,+ PURCHASING_PLANNING_PAGING+} from "~/modules/purchasing";import PurchasingPlanningTable from "~/modules/purchasing/ui/Planning/PurchasingPlanningTable";import { resolveLocationId } from "~/modules/shared/location.server";import { getOrCreatePeriods } from "~/modules/shared/shared.server";import { getLocationTimeZone } from "~/modules/shared/timezone.server";+import { toPage } from "~/utils/cursor";import type { Handle } from "~/utils/handle";+import { listErrorPage } from "~/utils/list-registry/list-error";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";@@ -51,7 +57,7 @@ export async function loader({ request }: LoaderFunctionArgs) {const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =+ const { limit, cursor, sorts, filters } =getGenericQueryFilters(searchParams);const locationId = await resolveLocationId(client, request, {@@ -79,13 +85,14 @@ export async function loader({ request }: LoaderFunctionArgs) {// A link to a row's order drawer (`?item=`) opens it even when the row is// not on this page — the plan has changed since the link was made, or it// came from another page. That row is read on its own, alongside the page.- const drawerItemId = searchParams.get(PLANNING_DRAWER_PARAM);+ // A later page (`?after=`) is read for its rows and their actions only.+ const drawerItemId = cursor ? null : searchParams.get(PLANNING_DRAWER_PARAM);const [items, drawerItemRead] = await Promise.all([getPurchasingPlanning(client, locationId, companyId, periodIds, {search,limit,- offset,+ cursor,sorts,filters: gridFilters,asOf,@@ -96,7 +103,7 @@ export async function loader({ request }: LoaderFunctionArgs) {? getPurchasingPlanning(client, locationId, companyId, periodIds, {search: null,limit: 1,- offset: 0,+ cursor: null,sorts: [],filters: [{ column: "id", operator: "eq", value: drawerItemId }],asOf@@ -105,7 +112,14 @@ export async function loader({ request }: LoaderFunctionArgs) {]);if (items.error) {- redirect(+ logger.error("Failed to load the planning items", {+ companyId,+ locationId,+ laterPage: Boolean(cursor),+ error: items.error+ });+ if (cursor) return listErrorPage("items");+ throw redirect(path.to.purchasing,await flash(request, error(items.error, "Failed to fetch planning items")));@@ -121,7 +135,12 @@ export async function loader({ request }: LoaderFunctionArgs) {error: drawerItemRead.error});}- const pageItems = (items.data ?? []) as PurchasingPlanningItem[];+ const page = toPage(+ (items.data ?? []) as PurchasingPlanningItem[],+ { limit, sorts },+ PURCHASING_PLANNING_PAGING+ );+ const pageItems = page.rows;const linkedItem = (drawerItemRead?.data?.[0] ??null) as PurchasingPlanningItem | null;const drawerItem =@@ -150,15 +169,20 @@ export async function loader({ request }: LoaderFunctionArgs) {locationId,error: planningActions.error});+ if (cursor) return listErrorPage("items");throw new Response("Failed to load planning actions", { status: 500 });}+ // Each row carries its own actions, so a later page brings its rows' actions.+ const actions = planningActions.data ?? [];return {- items: pageItems,+ items: withPlanningActions(pageItems, actions),// The row a `?item=` link opens the drawer on, when it is not in `items`.- drawerItem,+ drawerItem: drawerItem+ ? (withPlanningActions([drawerItem], actions)[0] ?? null)+ : null,count: items.count ?? 0,- planningActions: planningActions.data ?? [],+ nextCursor: page.nextCursor,// The Actions-column filter the rows were matched on: each row shows only// its actions of these types.actionTypes: actionTypes ?? null,@@ -175,9 +199,9 @@ export default function PurchasingPlanningRoute() {items,drawerItem,count,+ nextCursor,locationId,periods,- planningActions,actionTypes,locationToday} = useLoaderData<typeof loader>();@@ -195,9 +219,9 @@ export default function PurchasingPlanningRoute() {data={items}drawerItem={drawerItem}count={count}+ nextCursor={nextCursor}locationId={locationId}periods={periods}- planningActions={planningActions}actionTypes={actionTypes}locationToday={locationToday}/>diff --git a/apps/erp/app/routes/x+/purchasing+/quotes.tsx b/apps/erp/app/routes/x+/purchasing+/quotes.tsxindex 5be3b0786c..4e712840da 100644--- a/apps/erp/app/routes/x+/purchasing+/quotes.tsx+++ b/apps/erp/app/routes/x+/purchasing+/quotes.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getSupplierQuotes } from "~/modules/purchasing/purchasing.service";import { SupplierQuotesTable } from "~/modules/purchasing/ui/SupplierQuote";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { supplierQuotesList } from "~/utils/list-registry/purchasing.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["supplierQuote"],@@ -23,45 +19,26 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "purchasing",- bypassRls: true+ return loadListPage(request, supplierQuotesList, {+ dataKey: "quotes",+ bypassRls: true,+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch quotes"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const quotes = await getSupplierQuotes(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (quotes.error) {- redirect(- path.to.authenticatedRoot,- await flash(request, error(quotes.error, "Failed to fetch quotes"))- );- }-- return {- count: quotes.count ?? 0,- quotes: quotes.data ?? []- };}export default function SupplierQuotesRoute() {- const { count, quotes } = useLoaderData<typeof loader>();+ const { count, quotes, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <SupplierQuotesTable data={quotes} count={count} />+ <SupplierQuotesTable+ data={quotes}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/purchasing+/rfqs.tsx b/apps/erp/app/routes/x+/purchasing+/rfqs.tsxindex fb7c32b09f..afccb3a328 100644--- a/apps/erp/app/routes/x+/purchasing+/rfqs.tsx+++ b/apps/erp/app/routes/x+/purchasing+/rfqs.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getPurchasingRFQs } from "~/modules/purchasing";import { PurchasingRFQsTable } from "~/modules/purchasing/ui/PurchasingRfq";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { purchasingRfqsList } from "~/utils/list-registry/purchasing.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["purchasingRfq"],@@ -23,45 +19,22 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "purchasing",- bypassRls: true+ return loadListPage(request, purchasingRfqsList, {+ dataKey: "rfqs",+ bypassRls: true,+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch RFQs"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const rfqs = await getPurchasingRFQs(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (rfqs.error) {- redirect(- path.to.authenticatedRoot,- await flash(request, error(rfqs.error, "Failed to fetch RFQs"))- );- }-- return {- count: rfqs.count ?? 0,- rfqs: rfqs.data ?? []- };}export default function PurchasingRFQsRoute() {- const { count, rfqs } = useLoaderData<typeof loader>();+ const { count, rfqs, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <PurchasingRFQsTable data={rfqs} count={count} />+ <PurchasingRFQsTable data={rfqs} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/purchasing+/supplier-returns.tsx b/apps/erp/app/routes/x+/purchasing+/supplier-returns.tsxindex 8180ed873f..7dd30e1dfd 100644--- a/apps/erp/app/routes/x+/purchasing+/supplier-returns.tsx+++ b/apps/erp/app/routes/x+/purchasing+/supplier-returns.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getPurchaseReturnOrders } from "~/modules/purchasing";import { PurchaseReturnOrdersTable } from "~/modules/purchasing/ui/PurchaseReturnOrders";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { purchaseReturnOrdersList } from "~/utils/list-registry/purchasing.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["purchaseReturnOrder"],@@ -23,58 +19,26 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "purchasing"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const status = searchParams.get("status");- const supplierId = searchParams.get("supplierId");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const purchaseReturnOrders = await getPurchaseReturnOrders(- client,- companyId,- {- search,- status,- supplierId,- limit,- offset,- sorts,- filters+ return loadListPage(request, purchaseReturnOrdersList, {+ dataKey: "purchaseReturnOrders",+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch purchase return orders"}- );-- if (purchaseReturnOrders.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(- request,- error(- purchaseReturnOrders.error,- "Failed to fetch purchase return orders"- )- )- );- }-- return {- count: purchaseReturnOrders.count ?? 0,- purchaseReturnOrders: purchaseReturnOrders.data ?? []- };+ });}export default function PurchaseReturnOrdersSearchRoute() {- const { count, purchaseReturnOrders } = useLoaderData<typeof loader>();+ const { count, purchaseReturnOrders, nextCursor } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <PurchaseReturnOrdersTable data={purchaseReturnOrders} count={count} />+ <PurchaseReturnOrdersTable+ data={purchaseReturnOrders}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/purchasing+/supplier-types.tsx b/apps/erp/app/routes/x+/purchasing+/supplier-types.tsxindex 8401c75fdc..0ffeed31c5 100644--- a/apps/erp/app/routes/x+/purchasing+/supplier-types.tsx+++ b/apps/erp/app/routes/x+/purchasing+/supplier-types.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getSupplierTypes } from "~/modules/purchasing";import { SupplierTypesTable } from "~/modules/purchasing/ui/SupplierTypes";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { supplierTypesList } from "~/utils/list-registry/purchasing.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Supplier Types`,@@ -19,30 +18,15 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "purchasing",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts } = getGenericQueryFilters(searchParams);-- return await getSupplierTypes(client, companyId, {- search,- limit,- offset,- sorts- });+ return loadListPage(request, supplierTypesList, { dataKey: "data" });}export default function SupplierTypesRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <SupplierTypesTable data={data ?? []} count={count ?? 0} />+ <SupplierTypesTable data={data} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/purchasing+/suppliers.tsx b/apps/erp/app/routes/x+/purchasing+/suppliers.tsxindex f317c6b402..4bde12eb0f 100644--- a/apps/erp/app/routes/x+/purchasing+/suppliers.tsx+++ b/apps/erp/app/routes/x+/purchasing+/suppliers.tsx@@ -2,21 +2,19 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { indexBy, indexByMapped, pluckUnique, redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import type { SupplierReportContactsBySupplierId } from "~/modules/purchasing";-import { getSupplierReportContacts, getSuppliers } from "~/modules/purchasing";import { SuppliersTable } from "~/modules/purchasing/ui/Supplier";import { getTagsList } from "~/modules/shared";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import {+ suppliersList,+ withSupplierReportContacts+} from "~/utils/list-registry/purchasing.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["supplier"],@@ -25,84 +23,31 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "purchasing",- bypassRls: true- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const type = searchParams.get("type");- const status = searchParams.get("status");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [suppliers, tags] = await Promise.all([- getSuppliers(client, companyId, {- search,- type,- status,- limit,- offset,- sorts,- filters+ return loadListPage(request, suppliersList, {+ dataKey: "suppliers",+ bypassRls: true,+ firstPage: async ({ client, companyId }) => ({+ tags: (await getTagsList(client, companyId, "supplier")).data ?? []}),- getTagsList(client, companyId, "supplier")- ]);-- if (suppliers.error) {- redirect(- path.to.purchasing,- await flash(request, error(suppliers.error, "Failed to fetch suppliers"))- );- }-- const supplierIds = pluckUnique(suppliers.data, (s) => s.id);-- const [purchasingRes, paymentRes, shippingRes] =- await getSupplierReportContacts(client, companyId, supplierIds);-- const purchasingBySupplierId = indexByMapped(- purchasingRes.data,- (r) => r.id,- (r) => r.purchasingContact- );- const paymentBySupplierId = indexBy(paymentRes.data, (r) => r.supplierId);- const shippingBySupplierId = indexBy(shippingRes.data, (r) => r.supplierId);-- const supplierReportContacts: SupplierReportContactsBySupplierId =- Object.fromEntries(- supplierIds.map((id) => [- id,- {- purchasingContact: purchasingBySupplierId.get(id) ?? null,- payment: paymentBySupplierId.get(id) ?? null,- shipping: shippingBySupplierId.get(id) ?? null- }- ])- );-- return {- count: suppliers.count ?? 0,- suppliers: suppliers.data ?? [],- tags: tags.data ?? [],- supplierReportContacts- };+ // The report contacts of each page's suppliers, for the CSV export.+ mapRows: withSupplierReportContacts,+ onError: {+ redirectTo: path.to.purchasing,+ message: "Failed to fetch suppliers"+ }+ });}export default function PurchasingSuppliersRoute() {- const { count, suppliers, tags, supplierReportContacts } =- useLoaderData<typeof loader>();+ const { count, suppliers, nextCursor, tags } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full"><SuppliersTabledata={suppliers}count={count}+ nextCursor={nextCursor}tags={tags}- supplierReportContacts={supplierReportContacts}/><RecordOutlet /></VStack>diff --git a/apps/erp/app/routes/x+/quality+/actions.tsx b/apps/erp/app/routes/x+/quality+/actions.tsxindex 37a0a5ead6..2cfd77c546 100644--- a/apps/erp/app/routes/x+/quality+/actions.tsx+++ b/apps/erp/app/routes/x+/quality+/actions.tsx@@ -2,23 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";-import { getLogger } from "@carbon/logger";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import {- getIssueTypesList,- getQualityActions,- getRequiredActionsList-} from "~/modules/quality";+import { getIssueTypesList, getRequiredActionsList } from "~/modules/quality";import ActionsTable from "~/modules/quality/ui/Actions/ActionsTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { qualityActionsList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";--const logger = getLogger("erp", "actions");export const handle: Handle = {breadcrumb: msg`Actions`,@@ -26,43 +19,23 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "quality",- role: "employee"+ return loadListPage(request, qualityActionsList, {+ dataKey: "actions",+ firstPage: async ({ client, companyId }) => {+ const [issueTypes, requiredActions] = await Promise.all([+ getIssueTypesList(client, companyId),+ getRequiredActionsList(client, companyId)+ ]);+ return {+ issueTypes: issueTypes.data ?? [],+ requiredActions: requiredActions.data ?? []+ };+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [actions, issueTypes, requiredActions] = await Promise.all([- getQualityActions(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getIssueTypesList(client, companyId),- getRequiredActionsList(client, companyId)- ]);-- if (actions.error) {- logger.error(actions.error);- }-- return {- actions: actions.data ?? [],- count: actions.count ?? 0,- issueTypes: issueTypes.data ?? [],- requiredActions: requiredActions.data ?? []- };}export default function ActionsRoute() {- const { actions, count, issueTypes, requiredActions } =+ const { actions, count, nextCursor, issueTypes, requiredActions } =useLoaderData<typeof loader>();return (@@ -70,6 +43,7 @@ export default function ActionsRoute() {<ActionsTabledata={actions}count={count}+ nextCursor={nextCursor}issueTypes={issueTypes}requiredActions={requiredActions}/>diff --git a/apps/erp/app/routes/x+/quality+/calibrations.tsx b/apps/erp/app/routes/x+/quality+/calibrations.tsxindex 641a48e686..9a917a0550 100644--- a/apps/erp/app/routes/x+/quality+/calibrations.tsx+++ b/apps/erp/app/routes/x+/quality+/calibrations.tsx@@ -2,20 +2,17 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import {- getGaugeCalibrationRecords,- getGaugeTypesList-} from "~/modules/quality";+import { getGaugeTypesList } from "~/modules/quality";import GaugeCalibrationRecordsTable from "~/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable";import { getCompanySettings } from "~/modules/settings";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { gaugeCalibrationRecordsList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Calibrations`,@@ -23,40 +20,23 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "quality",- role: "employee"+ return loadListPage(request, gaugeCalibrationRecordsList, {+ dataKey: "gaugeCalibrationRecords",+ firstPage: async ({ client, companyId }) => {+ const [gaugeTypes, companySettings] = await Promise.all([+ getGaugeTypesList(client, companyId),+ getCompanySettings(client, companyId)+ ]);+ return {+ gaugeTypes: gaugeTypes.data ?? [],+ useMetric: companySettings.data?.useMetric ?? false+ };+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [gaugeCalibrationRecords, gaugeTypes, companySettings] =- await Promise.all([- getGaugeCalibrationRecords(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getGaugeTypesList(client, companyId),- getCompanySettings(client, companyId)- ]);-- return {- gaugeCalibrationRecords: gaugeCalibrationRecords.data ?? [],- count: gaugeCalibrationRecords.count ?? 0,- gaugeTypes: gaugeTypes.data ?? [],- useMetric: companySettings.data?.useMetric ?? false- };}export default function GaugesRoute() {- const { gaugeCalibrationRecords, count, gaugeTypes } =+ const { gaugeCalibrationRecords, count, nextCursor, gaugeTypes } =useLoaderData<typeof loader>();return (@@ -64,6 +44,7 @@ export default function GaugesRoute() {<GaugeCalibrationRecordsTabledata={gaugeCalibrationRecords}count={count}+ nextCursor={nextCursor}types={gaugeTypes}/><RecordOutlet />diff --git a/apps/erp/app/routes/x+/quality+/documents.tsx b/apps/erp/app/routes/x+/quality+/documents.tsxindex 6d17580d7a..ea07a8f432 100644--- a/apps/erp/app/routes/x+/quality+/documents.tsx+++ b/apps/erp/app/routes/x+/quality+/documents.tsx@@ -2,17 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getQualityDocuments } from "~/modules/quality";import QualityDocumentsTable from "~/modules/quality/ui/Documents/QualityDocumentsTable";import { getTagsList } from "~/modules/shared";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { qualityDocumentsList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Quality Documents`,@@ -20,43 +19,24 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "quality",- role: "employee"+ return loadListPage(request, qualityDocumentsList, {+ dataKey: "qualityDocuments",+ firstPage: async ({ client, companyId }) => ({+ tags: (await getTagsList(client, companyId, "qualityDocument")).data ?? []+ })});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [qualityDocuments, tags] = await Promise.all([- getQualityDocuments(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getTagsList(client, companyId, "qualityDocument")- ]);-- return {- qualityDocuments: qualityDocuments.data ?? [],- count: qualityDocuments.count ?? 0,- tags: tags.data ?? []- };}export default function QualityDocumentsRoute() {- const { qualityDocuments, count, tags } = useLoaderData<typeof loader>();+ const { qualityDocuments, count, nextCursor, tags } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full"><QualityDocumentsTabledata={qualityDocuments}count={count}+ nextCursor={nextCursor}tags={tags}/><RecordOutlet />diff --git a/apps/erp/app/routes/x+/quality+/gauge-types.tsx b/apps/erp/app/routes/x+/quality+/gauge-types.tsxindex fd7925a419..110a3012a2 100644--- a/apps/erp/app/routes/x+/quality+/gauge-types.tsx+++ b/apps/erp/app/routes/x+/quality+/gauge-types.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getGaugeTypes } from "~/modules/quality";import GaugeTypesTable from "~/modules/quality/ui/GaugeTypes/GaugeTypesTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { gaugeTypesList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Gauge Types`,@@ -19,32 +18,15 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "quality",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getGaugeTypes(client, companyId, {- search,- limit,- offset,- sorts,- filters- });+ return loadListPage(request, gaugeTypesList, { dataKey: "data" });}export default function NonConformanceTypesRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <GaugeTypesTable data={data ?? []} count={count ?? 0} />+ <GaugeTypesTable data={data} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/quality+/gauges.tsx b/apps/erp/app/routes/x+/quality+/gauges.tsxindex bb6f44f0d3..30ca9ba6e5 100644--- a/apps/erp/app/routes/x+/quality+/gauges.tsx+++ b/apps/erp/app/routes/x+/quality+/gauges.tsx@@ -2,16 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getGauges, getGaugeTypesList } from "~/modules/quality";+import { getGaugeTypesList } from "~/modules/quality";import GaugesTable from "~/modules/quality/ui/Gauge/GaugesTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { gaugesList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Gauges`,@@ -19,41 +19,26 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "quality",- role: "employee"+ return loadListPage(request, gaugesList, {+ dataKey: "gauges",+ firstPage: async ({ client, companyId }) => ({+ gaugeTypes: (await getGaugeTypesList(client, companyId)).data ?? []+ })});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [gauges, gaugeTypes] = await Promise.all([- getGauges(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getGaugeTypesList(client, companyId)- ]);-- return {- gauges: gauges.data ?? [],- count: gauges.count ?? 0,- gaugeTypes: gaugeTypes.data ?? []- };}export default function GaugesRoute() {- const { gauges, count, gaugeTypes } = useLoaderData<typeof loader>();+ const { gauges, count, nextCursor, gaugeTypes } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <GaugesTable data={gauges} count={count} types={gaugeTypes} />+ <GaugesTable+ data={gauges}+ count={count}+ nextCursor={nextCursor}+ types={gaugeTypes}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/quality+/inspection-plans.tsx b/apps/erp/app/routes/x+/quality+/inspection-plans.tsxindex bf862deba0..26e2f3b3e0 100644--- a/apps/erp/app/routes/x+/quality+/inspection-plans.tsx+++ b/apps/erp/app/routes/x+/quality+/inspection-plans.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getInspectionDocuments } from "~/modules/quality";import { InspectionDocumentTable } from "~/modules/quality/ui/InspectionDocument";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { inspectionPlansList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Inspection Plans`,@@ -19,37 +18,19 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "quality",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const diagrams = await getInspectionDocuments(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- return {- diagrams: diagrams.data ?? [],- count: diagrams.count ?? 0- };+ return loadListPage(request, inspectionPlansList, { dataKey: "diagrams" });}export default function InspectionDocumentsRoute() {- const { diagrams, count } = useLoaderData<typeof loader>();+ const { diagrams, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <InspectionDocumentTable data={diagrams} count={count} />+ <InspectionDocumentTable+ data={diagrams}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/quality+/inspections.tsx b/apps/erp/app/routes/x+/quality+/inspections.tsxindex 2bdffbd59d..2e11c99567 100644--- a/apps/erp/app/routes/x+/quality+/inspections.tsx+++ b/apps/erp/app/routes/x+/quality+/inspections.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getInspections } from "~/modules/quality";import InspectionsTable from "~/modules/quality/ui/Inspections/InspectionsTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { inspectionsList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["inspection"],@@ -23,51 +19,25 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "quality",- role: "employee"+ return loadListPage(request, inspectionsList, {+ dataKey: "inspections",+ onError: {+ redirectTo: path.to.quality,+ message: "Failed to load inspections"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const status = searchParams.get("status");- const source = searchParams.get("source");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const inspections = await getInspections(client, companyId, {- search,- status,- source,- limit,- offset,- sorts,- filters- });-- if (inspections.error) {- throw redirect(- path.to.quality,- await flash(- request,- error(inspections.error, "Failed to load inspections")- )- );- }-- return {- inspections: inspections.data ?? [],- count: inspections.count ?? 0- };}export default function InspectionsRoute() {- const { inspections, count } = useLoaderData<typeof loader>();+ const { inspections, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <InspectionsTable data={inspections} count={count} />+ <InspectionsTable+ data={inspections}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/quality+/issue-types.tsx b/apps/erp/app/routes/x+/quality+/issue-types.tsxindex 437c5cadd0..74fd4e3b43 100644--- a/apps/erp/app/routes/x+/quality+/issue-types.tsx+++ b/apps/erp/app/routes/x+/quality+/issue-types.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getIssueTypes } from "~/modules/quality";import IssueTypesTable from "~/modules/quality/ui/IssueTypes/IssueTypesTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { issueTypesList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Issue Types`,@@ -19,32 +18,15 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "quality",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getIssueTypes(client, companyId, {- search,- limit,- offset,- sorts,- filters- });+ return loadListPage(request, issueTypesList, { dataKey: "data" });}export default function IssueTypesRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <IssueTypesTable data={data ?? []} count={count ?? 0} />+ <IssueTypesTable data={data} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/quality+/issue-workflows.tsx b/apps/erp/app/routes/x+/quality+/issue-workflows.tsxindex 61ecbafba5..3f73c474f9 100644--- a/apps/erp/app/routes/x+/quality+/issue-workflows.tsx+++ b/apps/erp/app/routes/x+/quality+/issue-workflows.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getIssueWorkflows } from "~/modules/quality";import IssueWorkflowsTable from "~/modules/quality/ui/IssueWorkflows/IssueWorkflowsTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { issueWorkflowsList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Issue Workflows`,@@ -19,37 +18,19 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "quality",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const procedures = await getIssueWorkflows(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- return {- procedures: procedures.data ?? [],- count: procedures.count ?? 0- };+ return loadListPage(request, issueWorkflowsList, { dataKey: "procedures" });}export default function IssueWorkflowsRoute() {- const { procedures, count } = useLoaderData<typeof loader>();+ const { procedures, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <IssueWorkflowsTable data={procedures} count={count} />+ <IssueWorkflowsTable+ data={procedures}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/quality+/issues.tsx b/apps/erp/app/routes/x+/quality+/issues.tsxindex 87ac72cd2a..43a9688a6b 100644--- a/apps/erp/app/routes/x+/quality+/issues.tsx+++ b/apps/erp/app/routes/x+/quality+/issues.tsx@@ -2,22 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { getLogger } from "@carbon/logger";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getIssues, getIssueTypesList } from "~/modules/quality";+import { getIssueTypesList } from "~/modules/quality";import IssuesTable from "~/modules/quality/ui/Issue/IssuesTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { issuesList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";--const logger = getLogger("erp", "issues");export const handle: Handle = {realtime: ["nonConformance"],@@ -26,49 +20,29 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "quality",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [issues, nonConformanceTypes] = await Promise.all([- getIssues(client, companyId, {- search,- limit,- offset,- sorts,- filters+ return loadListPage(request, issuesList, {+ dataKey: "issues",+ firstPage: async ({ client, companyId }) => ({+ types: (await getIssueTypesList(client, companyId)).data ?? []}),- getIssueTypesList(client, companyId)- ]);-- if (issues.error) {- logger.error(issues.error);- throw redirect(- path.to.authenticatedRoot,- await flash(request, error(issues.error, "Error loading issues"))- );- }-- return {- issues: issues.data ?? [],- count: issues.count ?? 0,- types: nonConformanceTypes.data ?? []- };+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Error loading issues"+ }+ });}export default function IssuesRoute() {- const { issues, count, types } = useLoaderData<typeof loader>();+ const { issues, count, nextCursor, types } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <IssuesTable data={issues} count={count} types={types} />+ <IssuesTable+ data={issues}+ count={count}+ nextCursor={nextCursor}+ types={types}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/quality+/required-actions.tsx b/apps/erp/app/routes/x+/quality+/required-actions.tsxindex b6b5b413ea..b2827013c6 100644--- a/apps/erp/app/routes/x+/quality+/required-actions.tsx+++ b/apps/erp/app/routes/x+/quality+/required-actions.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getRequiredActions } from "~/modules/quality";import RequiredActionsTable from "~/modules/quality/ui/RequiredActions/RequiredActionsTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { requiredActionsList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Required Actions`,@@ -19,32 +18,15 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "quality",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getRequiredActions(client, companyId, {- search,- limit,- offset,- sorts,- filters- });+ return loadListPage(request, requiredActionsList, { dataKey: "data" });}export default function RequiredActionsRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <RequiredActionsTable data={data ?? []} count={count ?? 0} />+ <RequiredActionsTable data={data} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/quality+/risks.tsx b/apps/erp/app/routes/x+/quality+/risks.tsxindex f6b2575fec..6b70722d37 100644--- a/apps/erp/app/routes/x+/quality+/risks.tsx+++ b/apps/erp/app/routes/x+/quality+/risks.tsx@@ -2,20 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";-import { data, useLoaderData } from "react-router";-import { getRisks } from "~/modules/quality/quality.service";-import type { Risk } from "~/modules/quality/types";+import { useLoaderData } from "react-router";import RiskRegistersTable from "~/modules/quality/ui/RiskRegister/RiskRegistersTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { risksList } from "~/utils/list-registry/quality.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Risks`,@@ -23,44 +18,18 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "quality",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const risks = await getRisks(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (risks.error) {- redirect(- path.to.quality,- await flash(request, error(risks.error, "Failed to fetch risks"))- );- }-- return data({- count: risks.count ?? 0,- risks: (risks.data ?? []) as unknown as Risk[]+ return loadListPage(request, risksList, {+ dataKey: "risks",+ onError: { redirectTo: path.to.quality, message: "Failed to fetch risks" }});}export default function RisksRoute() {- const { count, risks } = useLoaderData<typeof loader>();+ const { count, risks, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <RiskRegistersTable data={risks} count={count} />+ <RiskRegistersTable data={risks} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/reports+/balance-sheet.$accountId.tsx b/apps/erp/app/routes/x+/reports+/balance-sheet.$accountId.tsxindex 3ef4191dce..dedd039ab4 100644--- a/apps/erp/app/routes/x+/reports+/balance-sheet.$accountId.tsx+++ b/apps/erp/app/routes/x+/reports+/balance-sheet.$accountId.tsx@@ -8,17 +8,11 @@ import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import {- getAccount,- getAccountLedger,- getAccountLedgerSummary-} from "~/modules/accounting";-import { getConsolidatedAccountLedger } from "~/modules/accounting/accounting.server";+import { getAccount } from "~/modules/accounting";+import { getAccountLedgerPage } from "~/modules/accounting/accounting.server";import { AccountLedgerDrawer } from "~/modules/accounting/ui/Reports";import { path } from "~/utils/path";-const LEDGER_PAGE_SIZE = 50;-export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId, companyGroupId } = await requirePermissions(request,@@ -37,44 +31,24 @@ export async function loader({ request, params }: LoaderFunctionArgs) {// The balance sheet is an as-of statement: the window is inception → endDateconst startDate = null;const endDate = searchParams.get("endDate") || null;- const offset = Math.max(0, Number(searchParams.get("offset")) || 0);-- // "All Companies" drills into the consolidated ledger — including the- // elimination entities, which the user's RLS session can't see. Reading them- // via service role (scoped to this group) makes the elimination journal- // entries appear and the drawer summary tie to the consolidated report.const isConsolidated = companiesParam === "all";const selectedCompanyId = isConsolidated? null: (companiesParam ?? companyId);- const [account, drill] = await Promise.all([+ const [account, ledger] = await Promise.all([getAccount(client, accountId),- isConsolidated- ? getConsolidatedAccountLedger(companyGroupId, {- accountId,- startDate,- endDate,- limit: LEDGER_PAGE_SIZE,- offset- })- : Promise.all([- getAccountLedger(client, {- accountId,- companyId: selectedCompanyId,- startDate,- endDate,- limit: LEDGER_PAGE_SIZE,- offset- }),- getAccountLedgerSummary(client, companyGroupId, selectedCompanyId, {- accountId,- startDate,- endDate- })- ]).then(([ledger, summary]) => ({ ledger, summary }))+ // A later page (`?after=`) is read for its lines only.+ getAccountLedgerPage(client, {+ accountId,+ companyGroupId,+ companyId: selectedCompanyId,+ consolidated: isConsolidated,+ startDate,+ endDate,+ after: searchParams.get("after")+ })]);- const { ledger, summary } = drill;if (account.error || !account.data) {throw redirect(@@ -85,17 +59,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return {account: account.data,- lines: ledger.data ?? [],- count: ledger.count ?? 0,- summary: summary.data ?? { opening: 0, netChange: 0, closing: 0 },+ ...ledger,startDate,- endDate,- offset+ endDate};}export default function BalanceSheetLedgerRoute() {- const { account, lines, count, summary, startDate, endDate, offset } =+ const { account, lines, count, nextCursor, summary, startDate, endDate } =useLoaderData<typeof loader>();return (@@ -106,8 +77,7 @@ export default function BalanceSheetLedgerRoute() {summary={summary}startDate={startDate}endDate={endDate}- offset={offset}- limit={LEDGER_PAGE_SIZE}+ nextCursor={nextCursor}backTo={path.to.balanceSheet}/>);diff --git a/apps/erp/app/routes/x+/reports+/balance-sheet.tsx b/apps/erp/app/routes/x+/reports+/balance-sheet.tsxindex 8a45987a22..7ce4158b5d 100644--- a/apps/erp/app/routes/x+/reports+/balance-sheet.tsx+++ b/apps/erp/app/routes/x+/reports+/balance-sheet.tsx@@ -37,14 +37,14 @@ import { months } from "~/modules/shared";import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";-import { revalidateIgnoringOffset } from "~/utils/revalidate";+import { revalidateOnSearchChange } from "~/utils/revalidate";export const handle: Handle = {breadcrumb: msg`Balance Sheet`,to: path.to.balanceSheet};-export const shouldRevalidate = revalidateIgnoringOffset;+export const shouldRevalidate = revalidateOnSearchChange;export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId, companyGroupId } = await requirePermissions(diff --git a/apps/erp/app/routes/x+/reports+/executive-pnl.tsx b/apps/erp/app/routes/x+/reports+/executive-pnl.tsxindex 7c37161fd3..581b7c7e67 100644--- a/apps/erp/app/routes/x+/reports+/executive-pnl.tsx+++ b/apps/erp/app/routes/x+/reports+/executive-pnl.tsx@@ -35,14 +35,14 @@ import { months } from "~/modules/shared";import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";-import { revalidateIgnoringOffset } from "~/utils/revalidate";+import { revalidateOnSearchChange } from "~/utils/revalidate";export const handle: Handle = {breadcrumb: msg`Executive P&L`,to: path.to.executivePnl};-export const shouldRevalidate = revalidateIgnoringOffset;+export const shouldRevalidate = revalidateOnSearchChange;export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId, companyGroupId } = await requirePermissions(diff --git a/apps/erp/app/routes/x+/reports+/income-statement.$accountId.tsx b/apps/erp/app/routes/x+/reports+/income-statement.$accountId.tsxindex 923f34d152..150a46e894 100644--- a/apps/erp/app/routes/x+/reports+/income-statement.$accountId.tsx+++ b/apps/erp/app/routes/x+/reports+/income-statement.$accountId.tsx@@ -8,17 +8,11 @@ import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import {- getAccount,- getAccountLedger,- getAccountLedgerSummary-} from "~/modules/accounting";-import { getConsolidatedAccountLedger } from "~/modules/accounting/accounting.server";+import { getAccount } from "~/modules/accounting";+import { getAccountLedgerPage } from "~/modules/accounting/accounting.server";import { AccountLedgerDrawer } from "~/modules/accounting/ui/Reports";import { path } from "~/utils/path";-const LEDGER_PAGE_SIZE = 50;-export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId, companyGroupId } = await requirePermissions(request,@@ -36,44 +30,24 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const companiesParam = searchParams.get("companies");const startDate = searchParams.get("startDate") || null;const endDate = searchParams.get("endDate") || null;- const offset = Math.max(0, Number(searchParams.get("offset")) || 0);-- // "All Companies" drills into the consolidated ledger — including the- // elimination entities, which the user's RLS session can't see. Reading them- // via service role (scoped to this group) makes the elimination journal- // entries appear and the drawer summary tie to the consolidated report.const isConsolidated = companiesParam === "all";const selectedCompanyId = isConsolidated? null: (companiesParam ?? companyId);- const [account, drill] = await Promise.all([+ const [account, ledger] = await Promise.all([getAccount(client, accountId),- isConsolidated- ? getConsolidatedAccountLedger(companyGroupId, {- accountId,- startDate,- endDate,- limit: LEDGER_PAGE_SIZE,- offset- })- : Promise.all([- getAccountLedger(client, {- accountId,- companyId: selectedCompanyId,- startDate,- endDate,- limit: LEDGER_PAGE_SIZE,- offset- }),- getAccountLedgerSummary(client, companyGroupId, selectedCompanyId, {- accountId,- startDate,- endDate- })- ]).then(([ledger, summary]) => ({ ledger, summary }))+ // A later page (`?after=`) is read for its lines only.+ getAccountLedgerPage(client, {+ accountId,+ companyGroupId,+ companyId: selectedCompanyId,+ consolidated: isConsolidated,+ startDate,+ endDate,+ after: searchParams.get("after")+ })]);- const { ledger, summary } = drill;if (account.error || !account.data) {throw redirect(@@ -84,17 +58,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return {account: account.data,- lines: ledger.data ?? [],- count: ledger.count ?? 0,- summary: summary.data ?? { opening: 0, netChange: 0, closing: 0 },+ ...ledger,startDate,- endDate,- offset+ endDate};}export default function IncomeStatementLedgerRoute() {- const { account, lines, count, summary, startDate, endDate, offset } =+ const { account, lines, count, nextCursor, summary, startDate, endDate } =useLoaderData<typeof loader>();return (@@ -105,8 +76,7 @@ export default function IncomeStatementLedgerRoute() {summary={summary}startDate={startDate}endDate={endDate}- offset={offset}- limit={LEDGER_PAGE_SIZE}+ nextCursor={nextCursor}backTo={path.to.incomeStatement}/>);diff --git a/apps/erp/app/routes/x+/reports+/income-statement.tsx b/apps/erp/app/routes/x+/reports+/income-statement.tsxindex 48b4a0deca..3ea9bd003e 100644--- a/apps/erp/app/routes/x+/reports+/income-statement.tsx+++ b/apps/erp/app/routes/x+/reports+/income-statement.tsx@@ -34,14 +34,14 @@ import { months } from "~/modules/shared";import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";-import { revalidateIgnoringOffset } from "~/utils/revalidate";+import { revalidateOnSearchChange } from "~/utils/revalidate";export const handle: Handle = {breadcrumb: msg`Income Statement`,to: path.to.incomeStatement};-export const shouldRevalidate = revalidateIgnoringOffset;+export const shouldRevalidate = revalidateOnSearchChange;export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId, companyGroupId } = await requirePermissions(diff --git a/apps/erp/app/routes/x+/reports+/trial-balance.$accountId.tsx b/apps/erp/app/routes/x+/reports+/trial-balance.$accountId.tsxindex 70c08bdafb..7fcf6aeb7b 100644--- a/apps/erp/app/routes/x+/reports+/trial-balance.$accountId.tsx+++ b/apps/erp/app/routes/x+/reports+/trial-balance.$accountId.tsx@@ -8,17 +8,11 @@ import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import {- getAccount,- getAccountLedger,- getAccountLedgerSummary-} from "~/modules/accounting";-import { getConsolidatedAccountLedger } from "~/modules/accounting/accounting.server";+import { getAccount } from "~/modules/accounting";+import { getAccountLedgerPage } from "~/modules/accounting/accounting.server";import { AccountLedgerDrawer } from "~/modules/accounting/ui/Reports";import { path } from "~/utils/path";-const LEDGER_PAGE_SIZE = 50;-export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId, companyGroupId } = await requirePermissions(request,@@ -36,46 +30,24 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const companiesParam = searchParams.get("companies");const startDate = searchParams.get("startDate") || null;const endDate = searchParams.get("endDate") || null;- const offset = Math.max(0, Number(searchParams.get("offset")) || 0);-- // Mirrors the parent page: a single selected company filters lines; "all"- // matches the RPC's null company filter (every company in the group)- // "All Companies" drills into the consolidated ledger — including the- // elimination entities, which the user's RLS session can't see. Reading them- // via service role (scoped to this group) makes the elimination journal- // entries appear and the drawer summary tie to the consolidated report.const isConsolidated = companiesParam === "all";const selectedCompanyId = isConsolidated? null: (companiesParam ?? companyId);- const [account, drill] = await Promise.all([+ const [account, ledger] = await Promise.all([getAccount(client, accountId),- isConsolidated- ? getConsolidatedAccountLedger(companyGroupId, {- accountId,- startDate,- endDate,- limit: LEDGER_PAGE_SIZE,- offset- })- : Promise.all([- getAccountLedger(client, {- accountId,- companyId: selectedCompanyId,- startDate,- endDate,- limit: LEDGER_PAGE_SIZE,- offset- }),- getAccountLedgerSummary(client, companyGroupId, selectedCompanyId, {- accountId,- startDate,- endDate- })- ]).then(([ledger, summary]) => ({ ledger, summary }))+ // A later page (`?after=`) is read for its lines only.+ getAccountLedgerPage(client, {+ accountId,+ companyGroupId,+ companyId: selectedCompanyId,+ consolidated: isConsolidated,+ startDate,+ endDate,+ after: searchParams.get("after")+ })]);- const { ledger, summary } = drill;if (account.error || !account.data) {throw redirect(@@ -86,17 +58,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return {account: account.data,- lines: ledger.data ?? [],- count: ledger.count ?? 0,- summary: summary.data ?? { opening: 0, netChange: 0, closing: 0 },+ ...ledger,startDate,- endDate,- offset+ endDate};}export default function TrialBalanceLedgerRoute() {- const { account, lines, count, summary, startDate, endDate, offset } =+ const { account, lines, count, nextCursor, summary, startDate, endDate } =useLoaderData<typeof loader>();return (@@ -107,8 +76,7 @@ export default function TrialBalanceLedgerRoute() {summary={summary}startDate={startDate}endDate={endDate}- offset={offset}- limit={LEDGER_PAGE_SIZE}+ nextCursor={nextCursor}backTo={path.to.trialBalance}/>);diff --git a/apps/erp/app/routes/x+/reports+/trial-balance.tsx b/apps/erp/app/routes/x+/reports+/trial-balance.tsxindex 3c5280d23b..439d71166c 100644--- a/apps/erp/app/routes/x+/reports+/trial-balance.tsx+++ b/apps/erp/app/routes/x+/reports+/trial-balance.tsx@@ -29,14 +29,14 @@ import { months } from "~/modules/shared";import { getCompanyTimeZone } from "~/modules/shared/timezone.server";import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";-import { revalidateIgnoringOffset } from "~/utils/revalidate";+import { revalidateOnSearchChange } from "~/utils/revalidate";export const handle: Handle = {breadcrumb: msg`Trial Balance`,to: path.to.trialBalance};-export const shouldRevalidate = revalidateIgnoringOffset;+export const shouldRevalidate = revalidateOnSearchChange;export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId, companyGroupId } = await requirePermissions(diff --git a/apps/erp/app/routes/x+/resources+/abilities.tsx b/apps/erp/app/routes/x+/resources+/abilities.tsxindex 985acd3ee4..b39e90d7c9 100644--- a/apps/erp/app/routes/x+/resources+/abilities.tsx+++ b/apps/erp/app/routes/x+/resources+/abilities.tsx@@ -2,18 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { AbilitiesTable, getAbilities } from "~/modules/resources";+import { AbilitiesTable } from "~/modules/resources";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { abilitiesList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Abilities`,@@ -21,44 +18,21 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "resources",- role: "employee"+ return loadListPage(request, abilitiesList, {+ dataKey: "abilities",+ onError: {+ redirectTo: path.to.resources,+ message: "Failed to fetch abilities"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const abilities = await getAbilities(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (abilities.error) {- throw redirect(- path.to.resources,- await flash(request, error(abilities.error, "Failed to fetch abilities"))- );- }-- return {- count: abilities.count ?? 0,- abilities: abilities.data ?? []- };}export default function AbilitiesRoute() {- const { count, abilities } = useLoaderData<typeof loader>();+ const { count, abilities, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <AbilitiesTable data={abilities} count={count} />+ <AbilitiesTable data={abilities} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/resources+/assignments.$trainingId.tsx b/apps/erp/app/routes/x+/resources+/assignments.$trainingId.tsxindex 5f8f1c24a8..7d159f63f9 100644--- a/apps/erp/app/routes/x+/resources+/assignments.$trainingId.tsx+++ b/apps/erp/app/routes/x+/resources+/assignments.$trainingId.tsx@@ -39,6 +39,7 @@ import { usePermissions } from "~/hooks";import { getTraining, getTrainingAssignmentStatus } from "~/modules/resources";import type { TrainingAssignmentStatusItem } from "~/modules/resources/types";import type { Handle } from "~/utils/handle";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";export const handle: Handle = {@@ -66,7 +67,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {trainingId,status: undefined,search: undefined,- limit: 10000,+ limit: SINGLE_LOAD_LIMIT,offset: 0,sorts: [],filters: []diff --git a/apps/erp/app/routes/x+/resources+/contractors.tsx b/apps/erp/app/routes/x+/resources+/contractors.tsxindex 2e61bcf553..dd5cdde63b 100644--- a/apps/erp/app/routes/x+/resources+/contractors.tsx+++ b/apps/erp/app/routes/x+/resources+/contractors.tsx@@ -2,22 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import {- ContractorsTable,- getAbilitiesList,- getContractors-} from "~/modules/resources";+import { ContractorsTable, getAbilitiesList } from "~/modules/resources";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { contractorsList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Contractors`,@@ -25,54 +18,29 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "resources",- role: "employee",- bypassRls: true- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [contractors, abilities] = await Promise.all([- getContractors(client, companyId, {- search,- limit,- offset,- sorts,- filters+ return loadListPage(request, contractorsList, {+ dataKey: "contractors",+ bypassRls: true,+ firstPage: async ({ client, companyId }) => ({+ abilities: (await getAbilitiesList(client, companyId)).data ?? []}),- getAbilitiesList(client, companyId)- ]);-- if (contractors.error) {- throw redirect(- path.to.resources,- await flash(- request,- error(contractors.error, "Failed to load contractors")- )- );- }-- return {- contractors: contractors.data ?? [],- abilities: abilities.data ?? [],- count: contractors.count ?? 0- };+ onError: {+ redirectTo: path.to.resources,+ message: "Failed to load contractors"+ }+ });}export default function Route() {- const { contractors, abilities, count } = useLoaderData<typeof loader>();+ const { contractors, abilities, count, nextCursor } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full"><ContractorsTabledata={contractors}count={count}+ nextCursor={nextCursor}// @ts-expect-error TS2322 - TODO: fix typeabilities={abilities}/>diff --git a/apps/erp/app/routes/x+/resources+/failure-modes.tsx b/apps/erp/app/routes/x+/resources+/failure-modes.tsxindex d50bce14b8..596a4b16a5 100644--- a/apps/erp/app/routes/x+/resources+/failure-modes.tsx+++ b/apps/erp/app/routes/x+/resources+/failure-modes.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getFailureModes } from "~/modules/resources";import FailureModesTable from "~/modules/resources/ui/FailureModes/FailureModesTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { failureModesList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Failure Modes`,@@ -19,32 +18,19 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "resources",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getFailureModes(client, companyId, {- search,- limit,- offset,- sorts,- filters- });+ return loadListPage(request, failureModesList, { dataKey: "data" });}export default function FailureModesRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <FailureModesTable data={data ?? []} count={count ?? 0} />+ <FailureModesTable+ data={data ?? []}+ count={count ?? 0}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/resources+/locations.tsx b/apps/erp/app/routes/x+/resources+/locations.tsxindex 43bbf800cf..e53f5e40b0 100644--- a/apps/erp/app/routes/x+/resources+/locations.tsx+++ b/apps/erp/app/routes/x+/resources+/locations.tsx@@ -2,18 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getLocations, LocationsTable } from "~/modules/resources";+import { LocationsTable } from "~/modules/resources";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { locationsList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Locations`,@@ -21,45 +18,22 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "resources",- role: "employee",- bypassRls: true+ return loadListPage(request, locationsList, {+ dataKey: "locations",+ bypassRls: true,+ onError: {+ redirectTo: path.to.resources,+ message: "Failed to load locations"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const locations = await getLocations(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (locations.error) {- throw redirect(- path.to.resources,- await flash(request, error(locations.error, "Failed to load locations"))- );- }-- return {- locations: locations.data ?? [],- count: locations.count ?? 0- };}export default function LocationsRoute() {- const { locations, count } = useLoaderData<typeof loader>();+ const { locations, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <LocationsTable data={locations} count={count} />+ <LocationsTable data={locations} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/resources+/maintenance.tsx b/apps/erp/app/routes/x+/resources+/maintenance.tsxindex d78c3582a7..81ed117b90 100644--- a/apps/erp/app/routes/x+/resources+/maintenance.tsx+++ b/apps/erp/app/routes/x+/resources+/maintenance.tsx@@ -2,20 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import {- getFailureModesList,- getLocationsList,- getMaintenanceDispatchesByLocation-} from "~/modules/resources";+import { getFailureModesList, getLocationsList } from "~/modules/resources";import MaintenanceDispatchesTable from "~/modules/resources/ui/Maintenance/MaintenanceDispatchesTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { maintenanceDispatchesList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Maintenance`,@@ -23,58 +19,26 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "resources",- role: "employee"+ return loadListPage(request, maintenanceDispatchesList, {+ dataKey: "dispatches",+ firstPage: async ({ client, companyId, params }) => {+ const [locations, failureModes] = await Promise.all([+ getLocationsList(client, companyId),+ getFailureModesList(client, companyId)+ ]);+ const locationsList = locations.data ?? [];+ return {+ failureModes: failureModes.data ?? [],+ locations: locationsList,+ // The registry query defaults to the first location too.+ locationId: params.get("location") ?? locationsList[0]?.id ?? null+ };+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const status = searchParams.get("status") ?? undefined;- const locationId = searchParams.get("location");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const locations = await getLocationsList(client, companyId);- const locationsList = locations.data ?? [];-- // Default to first location if none specified- const selectedLocationId = locationId ?? locationsList[0]?.id;-- if (!selectedLocationId) {- return {- dispatches: [],- count: 0,- failureModes: [],- locations: locationsList,- locationId: null- };- }-- const [dispatches, failureModes] = await Promise.all([- getMaintenanceDispatchesByLocation(client, companyId, selectedLocationId, {- search,- status,- limit,- offset,- sorts,- filters- }),- getFailureModesList(client, companyId)- ]);-- return {- dispatches: dispatches.data ?? [],- count: dispatches.count ?? 0,- failureModes: failureModes.data ?? [],- locations: locationsList,- locationId: selectedLocationId- };}export default function MaintenanceRoute() {- const { dispatches, count, failureModes, locations, locationId } =+ const { dispatches, count, nextCursor, failureModes, locations, locationId } =useLoaderData<typeof loader>();return (@@ -83,6 +47,7 @@ export default function MaintenanceRoute() {// @ts-expect-error TS2322 - TODO: fix typedata={dispatches ?? []}count={count ?? 0}+ nextCursor={nextCursor}failureModes={failureModes ?? []}locations={locations}locationId={locationId}diff --git a/apps/erp/app/routes/x+/resources+/partners.tsx b/apps/erp/app/routes/x+/resources+/partners.tsxindex ec901d5da4..75fd251b79 100644--- a/apps/erp/app/routes/x+/resources+/partners.tsx+++ b/apps/erp/app/routes/x+/resources+/partners.tsx@@ -16,6 +16,7 @@ import {PartnersTable} from "~/modules/resources";import type { Handle } from "~/utils/handle";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";@@ -34,14 +35,15 @@ export async function loader({ request }: LoaderFunctionArgs) {const url = new URL(request.url);const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);+ const { sorts, filters } = getGenericQueryFilters(searchParams);+ // A partner has one row per ability, so `id` is not unique and a cursor+ // cannot page the list. It loads once: the first SINGLE_LOAD_LIMIT rows.const [partners] = await Promise.all([getPartners(client, companyId, {search,- limit,- offset,+ limit: SINGLE_LOAD_LIMIT,+ offset: 0,sorts,filters}),@@ -57,16 +59,17 @@ export async function loader({ request }: LoaderFunctionArgs) {return {partners: partners.data ?? [],- count: partners.count ?? 0+ count: partners.count ?? 0,+ isTruncated: (partners.data?.length ?? 0) >= SINGLE_LOAD_LIMIT};}export default function Route() {- const { partners, count } = useLoaderData<typeof loader>();+ const { partners, count, isTruncated } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <PartnersTable data={partners} count={count} />+ <PartnersTable data={partners} count={count} isTruncated={isTruncated} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/resources+/processes.tsx b/apps/erp/app/routes/x+/resources+/processes.tsxindex f6e930a8ff..a601363b36 100644--- a/apps/erp/app/routes/x+/resources+/processes.tsx+++ b/apps/erp/app/routes/x+/resources+/processes.tsx@@ -2,18 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getProcesses, ProcessesTable } from "~/modules/resources";+import { ProcessesTable } from "~/modules/resources";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { processesList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Processes`,@@ -21,45 +18,22 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "resources",- role: "employee",- bypassRls: true+ return loadListPage(request, processesList, {+ dataKey: "processes",+ bypassRls: true,+ onError: {+ redirectTo: path.to.resources,+ message: "Failed to load processes"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const processes = await getProcesses(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (processes.error) {- throw redirect(- path.to.resources,- await flash(request, error(processes.error, "Failed to load processes"))- );- }-- return {- processes: processes.data ?? [],- count: processes.count ?? 0- };}export default function ProcessesRoute() {- const { processes, count } = useLoaderData<typeof loader>();+ const { processes, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ProcessesTable data={processes} count={count} />+ <ProcessesTable data={processes} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/resources+/scheduled-maintenance.tsx b/apps/erp/app/routes/x+/resources+/scheduled-maintenance.tsxindex 24599da409..096301e05e 100644--- a/apps/erp/app/routes/x+/resources+/scheduled-maintenance.tsx+++ b/apps/erp/app/routes/x+/resources+/scheduled-maintenance.tsx@@ -5,19 +5,21 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";import type { MaintenanceSchedule } from "~/modules/resources";-import {- getLocationsList,- getMaintenanceSchedulesByLocation-} from "~/modules/resources";+import { getLocationsList } from "~/modules/resources";import MaintenanceSchedulesTable from "~/modules/resources/ui/MaintenanceSchedule/MaintenanceSchedulesTable";import type { Handle } from "~/utils/handle";+import { fetchListPage } from "~/utils/list-registry/index.server";+import { listErrorPage } from "~/utils/list-registry/load.server";+import { maintenanceSchedulesList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";++const logger = getLogger("erp", "maintenance-schedules");export const handle: Handle = {breadcrumb: msg`Scheduled Maintenances`,@@ -25,17 +27,13 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "resources",- role: "employee"- });+ const { client, companyId } = await requirePermissions(+ request,+ maintenanceSchedulesList.permission+ );- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");+ const searchParams = new URL(request.url).searchParams;const locationId = searchParams.get("location");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);const locations = await getLocationsList(client, companyId);const locationsList = locations.data ?? [];@@ -47,29 +45,35 @@ export async function loader({ request }: LoaderFunctionArgs) {return {data: [],count: 0,+ nextCursor: null,locations: locationsList,locationId: null};}- const schedules = await getMaintenanceSchedulesByLocation(+ // The registry query reads the location from the URL: pass the default.+ const listParams = new URLSearchParams(searchParams);+ listParams.set("location", selectedLocationId);+ const schedules = await fetchListPage(+ maintenanceSchedulesList,client,companyId,- selectedLocationId,- {- search,- limit,- offset,- sorts,- filters- }+ listParams);- if (!schedules.data) {+ if (schedules.error) {+ if (searchParams.get("after")) {+ logger.error("Failed to load a later page of maintenance schedules", {+ companyId,+ error: schedules.error+ });+ return listErrorPage("data");+ }return data({data: [] as MaintenanceSchedule[],count: 0,+ nextCursor: null,locations: locationsList,locationId: selectedLocationId},@@ -81,21 +85,24 @@ export async function loader({ request }: LoaderFunctionArgs) {}return {- data: (schedules.data ?? []) as MaintenanceSchedule[],- count: schedules.count ?? 0,+ data: schedules.rows as MaintenanceSchedule[],+ count: schedules.count,+ nextCursor: schedules.nextCursor,locations: locationsList,locationId: selectedLocationId};}export default function MaintenanceSchedulesRoute() {- const { data, count, locations, locationId } = useLoaderData<typeof loader>();+ const { data, count, nextCursor, locations, locationId } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full"><MaintenanceSchedulesTabledata={data ?? []}count={count ?? 0}+ nextCursor={nextCursor}locations={locations}locationId={locationId}/>diff --git a/apps/erp/app/routes/x+/resources+/suggestions.tsx b/apps/erp/app/routes/x+/resources+/suggestions.tsxindex 3cb3f3a393..c02a0b7833 100644--- a/apps/erp/app/routes/x+/resources+/suggestions.tsx+++ b/apps/erp/app/routes/x+/resources+/suggestions.tsx@@ -2,19 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getSuggestions, SuggestionsTable } from "~/modules/resources";+import { SuggestionsTable } from "~/modules/resources";import { getTagsList } from "~/modules/shared";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { suggestionsList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Suggestions`,@@ -22,52 +19,31 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "resources",- role: "employee",- bypassRls: true- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [suggestions, tags] = await Promise.all([- getSuggestions(client, companyId, {- search,- limit,- offset,- sorts,- filters+ return loadListPage(request, suggestionsList, {+ dataKey: "suggestions",+ bypassRls: true,+ firstPage: async ({ client, companyId }) => ({+ tags: (await getTagsList(client, companyId, "suggestion")).data ?? []}),- getTagsList(client, companyId, "suggestion")- ]);-- if (suggestions.error) {- throw redirect(- path.to.resources,- await flash(- request,- error(suggestions.error, "Failed to load suggestions")- )- );- }-- return {- suggestions: suggestions.data ?? [],- tags: tags.data ?? [],- count: suggestions.count ?? 0- };+ onError: {+ redirectTo: path.to.resources,+ message: "Failed to load suggestions"+ }+ });}export default function SuggestionsRoute() {- const { suggestions, tags, count } = useLoaderData<typeof loader>();+ const { suggestions, tags, count, nextCursor } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <SuggestionsTable data={suggestions} tags={tags} count={count} />+ <SuggestionsTable+ data={suggestions}+ tags={tags}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/resources+/training.tsx b/apps/erp/app/routes/x+/resources+/training.tsxindex ce0800fa28..af6d8430f1 100644--- a/apps/erp/app/routes/x+/resources+/training.tsx+++ b/apps/erp/app/routes/x+/resources+/training.tsx@@ -3,18 +3,18 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getTrainings, TrainingsTable } from "~/modules/resources";+import { TrainingsTable } from "~/modules/resources";import { getTagsList } from "~/modules/shared";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { trainingsList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Training`,@@ -22,55 +22,36 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "resources",- role: "employee"+ return loadListPage(request, trainingsList, {+ dataKey: "trainings",+ firstPage: async ({ client, companyId, request }) => {+ const tags = await getTagsList(client, companyId, "training");+ if (tags.error) {+ throw redirect(+ path.to.authenticatedRoot,+ await flash(request, error(tags.error, "Error loading tags"))+ );+ }+ return { tags: tags.data ?? [] };+ },+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Error loading trainings"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [trainings, tags] = await Promise.all([- getTrainings(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getTagsList(client, companyId, "training")- ]);-- if (trainings.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(request, error(trainings.error, "Error loading trainings"))- );- }-- if (tags.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(request, error(tags.error, "Error loading tags"))- );- }-- return {- trainings: trainings.data ?? [],- count: trainings.count ?? 0,- tags: tags.data ?? []- };}export default function TrainingsRoute() {- const { trainings, count, tags } = useLoaderData<typeof loader>();+ const { trainings, count, nextCursor, tags } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <TrainingsTable data={trainings} count={count} tags={tags} />+ <TrainingsTable+ data={trainings}+ count={count}+ nextCursor={nextCursor}+ tags={tags}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/resources+/work-centers.tsx b/apps/erp/app/routes/x+/resources+/work-centers.tsxindex 75068dc6fc..78391b2e62 100644--- a/apps/erp/app/routes/x+/resources+/work-centers.tsx+++ b/apps/erp/app/routes/x+/resources+/work-centers.tsx@@ -2,23 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { getDepartmentsList } from "~/modules/people";-import {- getLocationsList,- getWorkCenters,- WorkCentersTable-} from "~/modules/resources";+import { getLocationsList, WorkCentersTable } from "~/modules/resources";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { workCentersList } from "~/utils/list-registry/resources.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Work Centers`,@@ -26,50 +19,28 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "resources",- role: "employee",- bypassRls: true+ return loadListPage(request, workCentersList, {+ dataKey: "workCenters",+ bypassRls: true,+ firstPage: async ({ client, companyId }) => {+ const [departments, locations] = await Promise.all([+ getDepartmentsList(client, companyId),+ getLocationsList(client, companyId)+ ]);+ return {+ departments: departments.data ?? [],+ locations: locations.data ?? []+ };+ },+ onError: {+ redirectTo: path.to.resources,+ message: "Failed to fetch work centers"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [workCenters, departments, locations] = await Promise.all([- getWorkCenters(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getDepartmentsList(client, companyId),- getLocationsList(client, companyId)- ]);-- if (workCenters.error) {- redirect(- path.to.resources,- await flash(- request,- error(workCenters.error, "Failed to fetch work centers")- )- );- }-- return {- count: workCenters.count ?? 0,- departments: departments.data ?? [],- workCenters: workCenters.data ?? [],- locations: locations.data ?? []- };}export default function WorkCentersRoute() {- const { count, departments, locations, workCenters } =+ const { count, departments, locations, workCenters, nextCursor } =useLoaderData<typeof loader>();return (@@ -77,6 +48,7 @@ export default function WorkCentersRoute() {<WorkCentersTabledata={workCenters}count={count}+ nextCursor={nextCursor}departments={departments}locations={locations}/>diff --git a/apps/erp/app/routes/x+/sales+/contracts.tsx b/apps/erp/app/routes/x+/sales+/contracts.tsxindex b2cbd14304..4c542a1582 100644--- a/apps/erp/app/routes/x+/sales+/contracts.tsx+++ b/apps/erp/app/routes/x+/sales+/contracts.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getContracts } from "~/modules/sales";import { ContractsTable } from "~/modules/sales/ui/Contracts";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { contractsList } from "~/utils/list-registry/sales.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Service Contracts`,@@ -22,44 +18,21 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "sales"+ return loadListPage(request, contractsList, {+ dataKey: "contracts",+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch contracts"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const contracts = await getContracts(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (contracts.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(request, error(contracts.error, "Failed to fetch contracts"))- );- }-- return {- count: contracts.count ?? 0,- contracts: contracts.data ?? []- };}export default function ContractsRoute() {- const { count, contracts } = useLoaderData<typeof loader>();+ const { count, contracts, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ContractsTable data={contracts} count={count} />+ <ContractsTable data={contracts} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/sales+/customer-portals.tsx b/apps/erp/app/routes/x+/sales+/customer-portals.tsxindex 95383cc45a..2185a00f8c 100644--- a/apps/erp/app/routes/x+/sales+/customer-portals.tsx+++ b/apps/erp/app/routes/x+/sales+/customer-portals.tsx@@ -3,7 +3,6 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { getAppUrl } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";@@ -13,10 +12,10 @@ import {CustomerPortalsTable,CustomerPortalsUpgradeOverlay} from "~/modules/sales/ui/CustomerPortals";-import { getCustomerPortals } from "~/modules/shared";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { customerPortalsList } from "~/utils/list-registry/sales.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Customer Portals`,@@ -24,31 +23,14 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "sales",- role: "employee"+ return loadListPage(request, customerPortalsList, {+ dataKey: "data",+ firstPage: () => ({ appUrl: getAppUrl() })});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return {- appUrl: getAppUrl(),- ...(await getCustomerPortals(client, companyId, {- search,- limit,- offset,- sorts,- filters- }))- };}export default function CustomerPortalsRoute() {- const { appUrl, data, count } = useLoaderData<typeof loader>();+ const { appUrl, data, count, nextCursor } = useLoaderData<typeof loader>();const { isGated } = usePlanGate({ feature: "CUSTOMER_PORTALS" });if (isGated) {@@ -59,8 +41,9 @@ export default function CustomerPortalsRoute() {<VStack spacing={0} className="h-full"><CustomerPortalsTableappUrl={appUrl}- data={data ?? []}- count={count ?? 0}+ data={data}+ count={count}+ nextCursor={nextCursor}/><RecordOutlet /></VStack>diff --git a/apps/erp/app/routes/x+/sales+/customer-statuses.tsx b/apps/erp/app/routes/x+/sales+/customer-statuses.tsxindex 2d65048557..0163c8618a 100644--- a/apps/erp/app/routes/x+/sales+/customer-statuses.tsx+++ b/apps/erp/app/routes/x+/sales+/customer-statuses.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getCustomerStatuses } from "~/modules/sales";import { CustomerStatusesTable } from "~/modules/sales/ui/CustomerStatuses";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { customerStatusesList } from "~/utils/list-registry/sales.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Customer Statuses`,@@ -19,32 +18,19 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "sales",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getCustomerStatuses(client, companyId, {- search,- limit,- offset,- sorts,- filters- });+ return loadListPage(request, customerStatusesList, { dataKey: "data" });}export default function CustomerStatusesRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <CustomerStatusesTable data={data ?? []} count={count ?? 0} />+ <CustomerStatusesTable+ data={data}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/sales+/customer-types.tsx b/apps/erp/app/routes/x+/sales+/customer-types.tsxindex ba1628b64d..91fd95b908 100644--- a/apps/erp/app/routes/x+/sales+/customer-types.tsx+++ b/apps/erp/app/routes/x+/sales+/customer-types.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getCustomerTypes } from "~/modules/sales";import { CustomerTypesTable } from "~/modules/sales/ui/CustomerTypes";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { customerTypesList } from "~/utils/list-registry/sales.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Customer Types`,@@ -19,32 +18,15 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "sales",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getCustomerTypes(client, companyId, {- search,- limit,- offset,- sorts,- filters- });+ return loadListPage(request, customerTypesList, { dataKey: "data" });}export default function CustomerTypesRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <CustomerTypesTable data={data ?? []} count={count ?? 0} />+ <CustomerTypesTable data={data} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/sales+/customers.tsx b/apps/erp/app/routes/x+/sales+/customers.tsxindex a75271cdb0..29bc09620e 100644--- a/apps/erp/app/routes/x+/sales+/customers.tsx+++ b/apps/erp/app/routes/x+/sales+/customers.tsx@@ -2,20 +2,17 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getCustomerStatuses, getCustomers } from "~/modules/sales";+import { getCustomerStatuses } from "~/modules/sales";import { CustomersTable } from "~/modules/sales/ui/Customers";import { getTagsList } from "~/modules/shared";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { customersList } from "~/utils/list-registry/sales.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["customer"],@@ -24,47 +21,25 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "sales",- bypassRls: true+ return loadListPage(request, customersList, {+ dataKey: "customers",+ bypassRls: true,+ firstPage: async ({ client, companyId }) => {+ const [customerStatuses, tags] = await Promise.all([+ getCustomerStatuses(client, companyId),+ getTagsList(client, companyId, "customer")+ ]);+ return {+ customerStatuses: customerStatuses.data ?? [],+ tags: tags.data ?? []+ };+ },+ onError: { redirectTo: path.to.sales, message: "Failed to fetch customers" }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [customers, customerStatuses, tags] = await Promise.all([- getCustomers(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getCustomerStatuses(client, companyId),- getTagsList(client, companyId, "customer")- ]);-- if (customers.error) {- redirect(- path.to.sales,- await flash(request, error(customers.error, "Failed to fetch customers"))- );- }-- return {- count: customers.count ?? 0,- customers: customers.data ?? [],- customerStatuses: customerStatuses.data ?? [],- tags: tags.data ?? []- };}export default function SalesCustomersRoute() {- const { count, customers, customerStatuses, tags } =+ const { count, customers, nextCursor, customerStatuses, tags } =useLoaderData<typeof loader>();return (@@ -72,6 +47,7 @@ export default function SalesCustomersRoute() {<CustomersTabledata={customers}count={count}+ nextCursor={nextCursor}customerStatuses={customerStatuses}tags={tags}/>diff --git a/apps/erp/app/routes/x+/sales+/no-quote-reasons.tsx b/apps/erp/app/routes/x+/sales+/no-quote-reasons.tsxindex 86ffef6cea..552efbeeb1 100644--- a/apps/erp/app/routes/x+/sales+/no-quote-reasons.tsx+++ b/apps/erp/app/routes/x+/sales+/no-quote-reasons.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getNoQuoteReasons } from "~/modules/sales";import { NoQuoteReasonsTable } from "~/modules/sales/ui/NoQuoteReasons";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { noQuoteReasonsList } from "~/utils/list-registry/sales.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`No Quote Reasons`,@@ -19,32 +18,15 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "sales",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getNoQuoteReasons(client, companyId, {- search,- limit,- offset,- sorts,- filters- });+ return loadListPage(request, noQuoteReasonsList, { dataKey: "data" });}export default function ScrapReasonsRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <NoQuoteReasonsTable data={data ?? []} count={count ?? 0} />+ <NoQuoteReasonsTable data={data} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/sales+/orders.tsx b/apps/erp/app/routes/x+/sales+/orders.tsxindex 3af91c0f3e..1d6686c298 100644--- a/apps/erp/app/routes/x+/sales+/orders.tsx+++ b/apps/erp/app/routes/x+/sales+/orders.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getSalesOrders } from "~/modules/sales";import { SalesOrdersTable } from "~/modules/sales/ui/SalesOrder";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { salesOrdersList } from "~/utils/list-registry/sales.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["salesOrder"],@@ -23,52 +19,26 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "sales",- bypassRls: true+ return loadListPage(request, salesOrdersList, {+ dataKey: "salesOrders",+ bypassRls: true,+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch sales orders"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const status = searchParams.get("status");- const customerId = searchParams.get("customerId");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const salesOrders = await getSalesOrders(client, companyId, {- search,- status,- customerId,- limit,- offset,- sorts,- filters- });-- if (salesOrders.error) {- redirect(- path.to.authenticatedRoot,- await flash(- request,- error(salesOrders.error, "Failed to fetch sales orders")- )- );- }-- return {- count: salesOrders.count ?? 0,- salesOrders: salesOrders.data ?? []- };}export default function SalesOrdersSearchRoute() {- const { count, salesOrders } = useLoaderData<typeof loader>();+ const { count, salesOrders, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <SalesOrdersTable data={salesOrders} count={count} />+ <SalesOrdersTable+ data={salesOrders}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/sales+/price-list.tsx b/apps/erp/app/routes/x+/sales+/price-list.tsxindex e87665081d..85f87953f1 100644--- a/apps/erp/app/routes/x+/sales+/price-list.tsx+++ b/apps/erp/app/routes/x+/sales+/price-list.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getBaseCatalog, resolvePriceList } from "~/modules/sales";import PriceListTable from "~/modules/sales/ui/Pricing/PriceOverridesTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { priceListList } from "~/utils/list-registry/sales.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Price List`,@@ -19,75 +18,37 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "sales",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const customerId = searchParams.get("customerId");- const customerTypeId = searchParams.get("customerTypeId");- const rawQuantity = Number(searchParams.get("quantity") ?? "1");- const quantity =- Number.isFinite(rawQuantity) && rawQuantity >= 0 ? rawQuantity : 1;- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const groupOptionsQuery = client- .from("group")- .select("id, name, isCustomerOrgGroup, isCustomerTypeGroup")- .eq("companyId", companyId)- .or("isCustomerOrgGroup.eq.true,isCustomerTypeGroup.eq.true")- .order("isCustomerTypeGroup", { ascending: false })- .order("name");+ return loadListPage(request, priceListList, {+ dataKey: "data",+ firstPage: async ({ client, companyId, params }) => {+ const hasScope = Boolean(+ params.get("customerId") || params.get("customerTypeId")+ );+ const groupsResult = await client+ .from("group")+ .select("id, name, isCustomerOrgGroup, isCustomerTypeGroup")+ .eq("companyId", companyId)+ .or("isCustomerOrgGroup.eq.true,isCustomerTypeGroup.eq.true")+ .order("isCustomerTypeGroup", { ascending: false })+ .order("name");- const hasScope = Boolean(customerId || customerTypeId);- const listPromise = hasScope- ? resolvePriceList(client, companyId, {- customerId: customerId ?? undefined,- customerTypeId: customerTypeId ?? undefined,- quantity,- search: search ?? undefined,- limit,- offset,- sorts,- filters- })- : getBaseCatalog(client, companyId, {- search: search ?? undefined,- limit,- offset,- sorts,- filters- });+ const scopeOptions = (groupsResult.data ?? [])+ .filter((g) => !g.id.startsWith("11111111-1111"))+ .map((g) => ({+ value: g.id,+ label: g.name,+ helper: (g.isCustomerTypeGroup ? "Type" : "Customer") as+ | "Type"+ | "Customer"+ }));- const [list, groupsResult] = await Promise.all([- listPromise,- groupOptionsQuery- ]);-- const scopeOptions = (groupsResult.data ?? [])- .filter((g) => !g.id.startsWith("11111111-1111"))- .map((g) => ({- value: g.id,- label: g.name,- helper: (g.isCustomerTypeGroup ? "Type" : "Customer") as- | "Type"- | "Customer"- }));-- return {- data: list.data ?? [],- count: list.count ?? 0,- scopeOptions,- hasScope- };+ return { scopeOptions, hasScope };+ }+ });}export default function PriceListRoute() {- const { data, count, scopeOptions, hasScope } =+ const { data, count, nextCursor, scopeOptions, hasScope } =useLoaderData<typeof loader>();return (@@ -95,6 +56,7 @@ export default function PriceListRoute() {<PriceListTabledata={data}count={count}+ nextCursor={nextCursor}scopeOptions={scopeOptions}hasScope={hasScope}/>diff --git a/apps/erp/app/routes/x+/sales+/pricing-rules.tsx b/apps/erp/app/routes/x+/sales+/pricing-rules.tsxindex e5e086cfb0..d99cd56d0d 100644--- a/apps/erp/app/routes/x+/sales+/pricing-rules.tsx+++ b/apps/erp/app/routes/x+/sales+/pricing-rules.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getPricingRules } from "~/modules/sales";import PricingRulesTable from "~/modules/sales/ui/Pricing/PricingRulesTable";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { pricingRulesList } from "~/utils/list-registry/sales.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Pricing Rules`,@@ -19,32 +18,15 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "sales",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getPricingRules(client, companyId, {- search: search ?? undefined,- limit,- offset,- sorts,- filters- });+ return loadListPage(request, pricingRulesList, { dataKey: "data" });}export default function PricingRulesRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <PricingRulesTable data={data ?? []} count={count ?? 0} />+ <PricingRulesTable data={data} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/sales+/quotes.tsx b/apps/erp/app/routes/x+/sales+/quotes.tsxindex 223d12491a..810d866349 100644--- a/apps/erp/app/routes/x+/sales+/quotes.tsx+++ b/apps/erp/app/routes/x+/sales+/quotes.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getQuotes } from "~/modules/sales";import { QuotesTable } from "~/modules/sales/ui/Quotes";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { quotesList } from "~/utils/list-registry/sales.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["quote"],@@ -23,45 +19,22 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "sales",- bypassRls: true+ return loadListPage(request, quotesList, {+ dataKey: "quotes",+ bypassRls: true,+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch quotes"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const quotes = await getQuotes(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (quotes.error) {- redirect(- path.to.authenticatedRoot,- await flash(request, error(quotes.error, "Failed to fetch quotes"))- );- }-- return {- count: quotes.count ?? 0,- quotes: quotes.data ?? []- };}export default function QuotesRoute() {- const { count, quotes } = useLoaderData<typeof loader>();+ const { count, quotes, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <QuotesTable data={quotes} count={count} />+ <QuotesTable data={quotes} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/sales+/rental-agreements.tsx b/apps/erp/app/routes/x+/sales+/rental-agreements.tsxindex 821ddf8ab5..2834b931dc 100644--- a/apps/erp/app/routes/x+/sales+/rental-agreements.tsx+++ b/apps/erp/app/routes/x+/sales+/rental-agreements.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getRentalAgreements } from "~/modules/sales";import { RentalAgreementsTable } from "~/modules/sales/ui/Rentals";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { rentalAgreementsList } from "~/utils/list-registry/sales.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Rental Agreements`,@@ -22,47 +18,26 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "sales"+ return loadListPage(request, rentalAgreementsList, {+ dataKey: "rentalAgreements",+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch rental agreements"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const rentalAgreements = await getRentalAgreements(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (rentalAgreements.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(- request,- error(rentalAgreements.error, "Failed to fetch rental agreements")- )- );- }-- return {- count: rentalAgreements.count ?? 0,- rentalAgreements: rentalAgreements.data ?? []- };}export default function RentalAgreementsRoute() {- const { count, rentalAgreements } = useLoaderData<typeof loader>();+ const { count, rentalAgreements, nextCursor } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <RentalAgreementsTable data={rentalAgreements} count={count} />+ <RentalAgreementsTable+ data={rentalAgreements}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/sales+/return-reasons.tsx b/apps/erp/app/routes/x+/sales+/return-reasons.tsxindex 7d46f0ec3f..fd92d1f04f 100644--- a/apps/erp/app/routes/x+/sales+/return-reasons.tsx+++ b/apps/erp/app/routes/x+/sales+/return-reasons.tsx@@ -2,16 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getReturnReasons } from "~/modules/sales";import { ReturnReasonsTable } from "~/modules/sales/ui/ReturnReasons";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { returnReasonsList } from "~/utils/list-registry/sales.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Return Reasons`,@@ -19,32 +18,15 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "sales",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getReturnReasons(client, companyId, {- search,- limit,- offset,- sorts,- filters- });+ return loadListPage(request, returnReasonsList, { dataKey: "data" });}export default function ReturnReasonsRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ReturnReasonsTable data={data ?? []} count={count ?? 0} />+ <ReturnReasonsTable data={data} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/sales+/rfqs.tsx b/apps/erp/app/routes/x+/sales+/rfqs.tsxindex 161407d186..0187991fb4 100644--- a/apps/erp/app/routes/x+/sales+/rfqs.tsx+++ b/apps/erp/app/routes/x+/sales+/rfqs.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getSalesRFQs } from "~/modules/sales";import { SalesRFQsTable } from "~/modules/sales/ui/SalesRFQ";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { salesRfqsList } from "~/utils/list-registry/sales.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["salesRfq"],@@ -23,45 +19,22 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "sales",- bypassRls: true+ return loadListPage(request, salesRfqsList, {+ dataKey: "rfqs",+ bypassRls: true,+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch RFQs"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const rfqs = await getSalesRFQs(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- if (rfqs.error) {- redirect(- path.to.authenticatedRoot,- await flash(request, error(rfqs.error, "Failed to fetch RFQs"))- );- }-- return {- count: rfqs.count ?? 0,- rfqs: rfqs.data ?? []- };}export default function RFQsRoute() {- const { count, rfqs } = useLoaderData<typeof loader>();+ const { count, rfqs, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <SalesRFQsTable data={rfqs} count={count} />+ <SalesRFQsTable data={rfqs} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/sales+/rmas.tsx b/apps/erp/app/routes/x+/sales+/rmas.tsxindex 236864a80b..d986ac04df 100644--- a/apps/erp/app/routes/x+/sales+/rmas.tsx+++ b/apps/erp/app/routes/x+/sales+/rmas.tsx@@ -2,19 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getSalesReturnOrders } from "~/modules/sales";import { SalesReturnOrdersTable } from "~/modules/sales/ui/SalesReturnOrders";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { salesReturnOrdersList } from "~/utils/list-registry/sales.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {realtime: ["salesReturnOrder"],@@ -23,51 +19,26 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "sales"+ return loadListPage(request, salesReturnOrdersList, {+ dataKey: "salesReturnOrders",+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch sales return orders"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const status = searchParams.get("status");- const customerId = searchParams.get("customerId");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const salesReturnOrders = await getSalesReturnOrders(client, companyId, {- search,- status,- customerId,- limit,- offset,- sorts,- filters- });-- if (salesReturnOrders.error) {- throw redirect(- path.to.authenticatedRoot,- await flash(- request,- error(salesReturnOrders.error, "Failed to fetch sales return orders")- )- );- }-- return {- count: salesReturnOrders.count ?? 0,- salesReturnOrders: salesReturnOrders.data ?? []- };}export default function SalesReturnOrdersSearchRoute() {- const { count, salesReturnOrders } = useLoaderData<typeof loader>();+ const { count, salesReturnOrders, nextCursor } =+ useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <SalesReturnOrdersTable data={salesReturnOrders} count={count} />+ <SalesReturnOrdersTable+ data={salesReturnOrders}+ count={count}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/sales+/sales-rules.tsx b/apps/erp/app/routes/x+/sales+/sales-rules.tsxindex 94d48c4ae6..dbef3599d3 100644--- a/apps/erp/app/routes/x+/sales+/sales-rules.tsx+++ b/apps/erp/app/routes/x+/sales+/sales-rules.tsx@@ -20,6 +20,7 @@ import {getEnforcementRules} from "~/modules/shared";import type { Handle } from "~/utils/handle";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";export const handle: Handle = {@@ -35,7 +36,7 @@ export async function loader({ request }: LoaderFunctionArgs) {const rules = await getEnforcementRules(client, "sales", companyId, {search: null,- limit: 1000,+ limit: SINGLE_LOAD_LIMIT,offset: 0,sorts: []});diff --git a/apps/erp/app/routes/x+/settings+/api-keys.tsx b/apps/erp/app/routes/x+/settings+/api-keys.tsxindex 424663a6b9..8d7a542929 100644--- a/apps/erp/app/routes/x+/settings+/api-keys.tsx+++ b/apps/erp/app/routes/x+/settings+/api-keys.tsx@@ -2,23 +2,16 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { usePlanGate } from "~/hooks/usePlanGate";-import {- ApiKeysTable,- ApiKeysUpgradeOverlay,- getApiKeys-} from "~/modules/settings";+import { ApiKeysTable, ApiKeysUpgradeOverlay } from "~/modules/settings";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { apiKeysList } from "~/utils/list-registry/settings.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`API Keys`,@@ -26,39 +19,19 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- update: "users"+ // The registry query drops each key's hash.+ return loadListPage(request, apiKeysList, {+ dataKey: "apiKeys",+ firstPage: ({ companyId }) => ({ companyId }),+ onError: {+ redirectTo: path.to.settings,+ message: "Failed to load api keys"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const apiKeys = await getApiKeys(client, companyId, {- limit,- offset,- sorts,- search,- filters- });- if (apiKeys.error) {- throw redirect(- path.to.settings,- await flash(request, error(apiKeys.error, "Failed to load api keys"))- );- }-- return {- apiKeys: apiKeys.data?.map(({ keyHash, ...rest }: any) => rest) ?? [],- count: apiKeys.count ?? 0,- companyId- };}export default function ApiKeysRoute() {- const { apiKeys, count } = useLoaderData<typeof loader>();+ const { apiKeys, count, nextCursor } = useLoaderData<typeof loader>();const { isGated } = usePlanGate({ feature: "API_KEYS" });if (isGated) {@@ -66,7 +39,7 @@ export default function ApiKeysRoute() {}return (<>- <ApiKeysTable count={count} data={apiKeys} />+ <ApiKeysTable count={count} data={apiKeys} nextCursor={nextCursor} /><RecordOutlet /></>);diff --git a/apps/erp/app/routes/x+/settings+/audit-logs.details.tsx b/apps/erp/app/routes/x+/settings+/audit-logs.details.tsxindex 16b9c722b6..7a793eea88 100644--- a/apps/erp/app/routes/x+/settings+/audit-logs.details.tsx+++ b/apps/erp/app/routes/x+/settings+/audit-logs.details.tsx@@ -4,6 +4,7 @@import { requirePermissions } from "@carbon/auth/auth.server";import { getGlobalAuditLog } from "@carbon/ee/audit.server";+import { getLogger } from "@carbon/logger";import {Drawer,DrawerBody,@@ -15,9 +16,14 @@ import { Trans } from "@lingui/react/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate } from "react-router";import { AuditLogTable } from "~/modules/settings";+import { decodeOffsetToken, encodeOffsetToken } from "~/utils/cursor";+import { listErrorPage } from "~/utils/list-registry/load.server";+import { PAGE_SIZE } from "~/utils/pagination";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";+const logger = getLogger("erp", "audit-logs");+export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {view: "settings"@@ -26,7 +32,10 @@ export async function loader({ request }: LoaderFunctionArgs) {const url = new URL(request.url);const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, filters } = getGenericQueryFilters(searchParams);+ const { filters } = getGenericQueryFilters(searchParams);+ // The audit log RPC pages by offset, so the `after` token holds the next+ // offset.+ const offset = decodeOffsetToken(searchParams.get("after"));const entityTypeFilter = filters?.find((f) => f.column === "entityType")?.value as string | undefined;@@ -34,8 +43,9 @@ export async function loader({ request }: LoaderFunctionArgs) {const operationFilter = filters?.find((f) => f.column === "operation")?.value as "INSERT" | "UPDATE" | "DELETE" | undefined;- const result = await getGlobalAuditLog(client, companyId, {- limit,+ const query = getGlobalAuditLog(client, companyId, {+ // One extra row tells whether a next page exists.+ limit: PAGE_SIZE + 1,offset,search: search ?? undefined,entityType: entityTypeFilter as NonNullable<@@ -44,15 +54,33 @@ export async function loader({ request }: LoaderFunctionArgs) {actorId: actorIdFilter,operation: operationFilter});+ // The RPC throws on an error. A later page reports it to the list instead+ // of replacing the page.+ const result =+ offset > 0+ ? await query.catch((cause: unknown) => {+ logger.error("Failed to load a page of the audit log", {+ companyId,+ offset,+ error: cause+ });+ return null;+ })+ : await query;+ if (!result) return listErrorPage("entries");return {- entries: result.data,- count: result.count+ entries: result.data.slice(0, PAGE_SIZE),+ count: result.count,+ nextCursor:+ result.data.length > PAGE_SIZE+ ? encodeOffsetToken(offset + PAGE_SIZE)+ : null};}export default function AuditLogDetailsRoute() {- const { entries, count } = useLoaderData<typeof loader>();+ const { entries, count, nextCursor } = useLoaderData<typeof loader>();const navigate = useNavigate();return (<Drawer@@ -70,7 +98,11 @@ export default function AuditLogDetailsRoute() {</DrawerTitle></DrawerHeader><DrawerBody className="p-0 max-md:p-0">- <AuditLogTable entries={entries} count={count} />+ <AuditLogTable+ entries={entries}+ count={count}+ nextCursor={nextCursor}+ /></DrawerBody></DrawerContent></Drawer>diff --git a/apps/erp/app/routes/x+/settings+/custom-fields.tsx b/apps/erp/app/routes/x+/settings+/custom-fields.tsxindex 6fefcefc90..3e3bde8303 100644--- a/apps/erp/app/routes/x+/settings+/custom-fields.tsx+++ b/apps/erp/app/routes/x+/settings+/custom-fields.tsx@@ -2,19 +2,18 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { RecordOutlet, VStack } from "@carbon/react";-import { redirect, unchecked } from "@carbon/utils";+import { unchecked } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { getAttributeDataTypes } from "~/modules/people";-import { CustomFieldsTable, getCustomFieldsTables } from "~/modules/settings";+import { CustomFieldsTable } from "~/modules/settings";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { customFieldTablesList } from "~/utils/list-registry/settings.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Custom Fields`,@@ -22,40 +21,17 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "settings",- role: "employee"+ return loadListPage(request, customFieldTablesList, {+ dataKey: "tables",+ firstPage: async ({ client }) => {+ const dataTypes = await getAttributeDataTypes(client);+ return { dataTypes: dataTypes.data ?? [] };+ },+ onError: {+ redirectTo: path.to.authenticatedRoot,+ message: "Failed to fetch custom fields"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [tables, dataTypes] = await Promise.all([- getCustomFieldsTables(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getAttributeDataTypes(client)- ]);-- if (tables.error) {- redirect(- path.to.authenticatedRoot,- await flash(request, error(tables.error, "Failed to fetch custom fields"))- );- }-- return {- count: tables.count ?? 0,- tables: tables.data ?? [],- dataTypes: dataTypes.data ?? []- };}export async function action({ request }: ActionFunctionArgs) {@@ -98,11 +74,11 @@ function getIdField(table: string) {}export default function CustomFieldsRoute() {- const { count, tables } = useLoaderData<typeof loader>();+ const { count, tables, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <CustomFieldsTable data={tables} count={count} />+ <CustomFieldsTable data={tables} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.$id.tsxindex 6682d5bfba..65120a720f 100644--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx@@ -122,9 +122,9 @@ import {syncEnabledValidator} from "~/modules/settings/settings.models";import {- getSyncOperationReadableIds,invalidateIntegrationHealthCache,- upsertCompanyIntegration+ upsertCompanyIntegration,+ withSyncOperationReferences} from "~/modules/settings/settings.server";import { AccountingSyncControl } from "~/modules/settings/ui/Integrations/AccountingSyncControl";import { AccountMapping } from "~/modules/settings/ui/Integrations/AccountMapping";@@ -132,8 +132,13 @@ import { DimensionMapping } from "~/modules/settings/ui/Integrations/DimensionMaimport type { IntegrationFormTab } from "~/modules/settings/ui/Integrations/IntegrationForm";import { useMountActionStates } from "~/modules/settings/ui/Integrations/MountPublishStatus";import { PostingSyncSettings } from "~/modules/settings/ui/Integrations/PostingSyncSettings";-import type { SyncReconciliationReport } from "~/modules/settings/ui/Integrations/SyncActivity";+import {+ SYNC_ACTIVITY_SORTS,+ type SyncReconciliationReport+} from "~/modules/settings/ui/Integrations/SyncActivity";import { getDatabaseClient } from "~/services/database.server";+import { toPage } from "~/utils/cursor";+import { PAGE_SIZE } from "~/utils/pagination";import { path } from "~/utils/path";const logger = getLogger("erp", "integrations-id");@@ -706,21 +711,22 @@ export async function loader({ request, params }: LoaderFunctionArgs) {providerRole !== undefined && integrationData.data.active;// Sync-operation inbox (RLS SELECT covers employees, so the user-scoped- // client is enough). Params are prefixed (syncStatus/syncPage) to avoid- // clashing with other search params.+ // client is enough). The status param is prefixed (syncStatus) to avoid+ // clashing with other search params. Later pages come from+ // `api+/integrations.$id.sync-activity` as the tab scrolls.let syncActivity: {- operations: SyncOperation[];/**- * `entityType:entityId` -> the document number a human reads- * (`PO000001`) plus the Carbon row id to link to. Sparse: a pulled- * record that never landed a Carbon row is keyed by the provider's- * remote id, and the table falls back to it.+ * Each with its `reference`: the document number a human reads+ * (`PO000001`) plus the Carbon row id to link to. Null for a pulled+ * record that never landed a Carbon row: the table falls back to the+ * provider's remote id.*/- readableIds: Record<string, { label: string; recordId: string }>;+ operations: (SyncOperation & {+ reference: { label: string; recordId: string } | null;+ })[];count: number;status: SyncOperationStatus | null;- page: number;- pageSize: number;+ nextCursor: string | null;lastReconciliation: SyncReconciliationReport | null;/** Failed + Warning operations — the tab-label badge. */failingCount: number;@@ -742,19 +748,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const statusFilter = SyncOperationStatusSchema.safeParse(url.searchParams.get("syncStatus"));- const page = Math.max(- 1,- Number.parseInt(url.searchParams.get("syncPage") ?? "1", 10) || 1- );- const pageSize = 25;const [operations, failingOps, tieOutRows] = await Promise.all([getSyncOperations(client, {companyId,integration: integrationId,status: statusFilter.success ? statusFilter.data : undefined,- limit: pageSize,- offset: (page - 1) * pageSize+ // One extra row tells whether a next page exists.+ limit: PAGE_SIZE + 1}),// Failed + Warning count for the tab badge — only the exact count is// used, so fetch a single row.@@ -824,17 +825,20 @@ export async function loader({ request, params }: LoaderFunctionArgs) {? (storedReconciliation as SyncReconciliationReport): null;+ const firstPage = toPage(operations.data, {+ limit: PAGE_SIZE,+ sorts: SYNC_ACTIVITY_SORTS+ });+syncActivity = {- operations: operations.data,- readableIds: await getSyncOperationReadableIds(+ operations: await withSyncOperationReferences(client,companyId,- operations.data+ firstPage.rows),count: operations.count ?? 0,status: statusFilter.success ? statusFilter.data : null,- page,- pageSize,+ nextCursor: firstPage.nextCursor,lastReconciliation,failingCount: failingOps.error ? 0 : (failingOps.count ?? 0),tieOut@@ -2239,9 +2243,7 @@ export default function IntegrationRoute() {operations={syncActivity.operations}count={syncActivity.count}status={syncActivity.status}- page={syncActivity.page}- pageSize={syncActivity.pageSize}- readableIds={syncActivity.readableIds}+ nextCursor={syncActivity.nextCursor}lastReconciliation={syncActivity.lastReconciliation}tieOut={syncActivity.tieOut}/>diff --git a/apps/erp/app/routes/x+/settings+/printing.jobs.tsx b/apps/erp/app/routes/x+/settings+/printing.jobs.tsxindex 472a4c662e..e8f1ef32d1 100644--- a/apps/erp/app/routes/x+/settings+/printing.jobs.tsx+++ b/apps/erp/app/routes/x+/settings+/printing.jobs.tsx@@ -27,6 +27,9 @@ import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData, useNavigate } from "react-router";import { useRealtime } from "~/hooks";import { PrintJobsTable } from "~/modules/settings";+import { decodeOffsetToken, encodeOffsetToken } from "~/utils/cursor";+import { listErrorPage } from "~/utils/list-registry/load.server";+import { PAGE_SIZE } from "~/utils/pagination";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";@@ -40,7 +43,9 @@ export async function loader({ request }: LoaderFunctionArgs) {const url = new URL(request.url);const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, filters } = getGenericQueryFilters(searchParams);+ const { filters } = getGenericQueryFilters(searchParams);+ // `getPrintJobs` pages by offset, so the `after` token holds the next offset.+ const offset = decodeOffsetToken(searchParams.get("after"));const status = filters?.find((f) => f.column === "status")?.value;const origin = filters?.find((f) => f.column === "origin")?.value;@@ -55,13 +60,26 @@ export async function loader({ request }: LoaderFunctionArgs) {sourceDocument,contentType,search,- limit,+ // One extra row tells whether a next page exists.+ limit: PAGE_SIZE + 1,offset});+ if (result.error) {+ logger.error("Failed to load print jobs", {+ companyId,+ offset,+ error: result.error+ });+ if (offset > 0) return listErrorPage("jobs");+ }++ const jobs = (result.data ?? []) as PrintJob[];return {- jobs: (result.data ?? []) as PrintJob[],- count: result.count ?? 0+ jobs: jobs.slice(0, PAGE_SIZE),+ count: result.count ?? 0,+ nextCursor:+ jobs.length > PAGE_SIZE ? encodeOffsetToken(offset + PAGE_SIZE) : null};}@@ -199,7 +217,7 @@ export async function action({ request }: ActionFunctionArgs) {}export default function PrintJobsRoute() {- const { jobs, count } = useLoaderData<typeof loader>();+ const { jobs, count, nextCursor } = useLoaderData<typeof loader>();const navigate = useNavigate();useRealtime("printJob");@@ -220,7 +238,7 @@ export default function PrintJobsRoute() {</DrawerTitle></DrawerHeader><DrawerBody className="p-0 max-md:p-0">- <PrintJobsTable jobs={jobs} count={count} />+ <PrintJobsTable jobs={jobs} count={count} nextCursor={nextCursor} /></DrawerBody></DrawerContent></Drawer>diff --git a/apps/erp/app/routes/x+/settings+/sequences.tsx b/apps/erp/app/routes/x+/settings+/sequences.tsxindex 4e66408da7..8fa0e49800 100644--- a/apps/erp/app/routes/x+/settings+/sequences.tsx+++ b/apps/erp/app/routes/x+/settings+/sequences.tsx@@ -2,15 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import { getSequences, SequencesTable } from "~/modules/settings";+import { SequencesTable } from "~/modules/settings";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { sequencesList } from "~/utils/list-registry/settings.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Sequences`,@@ -18,32 +18,19 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "settings",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getSequences(client, companyId, {- search,- limit,- offset,- sorts,- filters- });+ return loadListPage(request, sequencesList, { dataKey: "data" });}export default function SequencesRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <SequencesTable data={data ?? []} count={count ?? 0} />+ <SequencesTable+ data={data ?? []}+ count={count ?? 0}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/settings+/serial-numbers.new.tsx b/apps/erp/app/routes/x+/settings+/serial-numbers.new.tsxindex 21142359df..2c225d53fa 100644--- a/apps/erp/app/routes/x+/settings+/serial-numbers.new.tsx+++ b/apps/erp/app/routes/x+/settings+/serial-numbers.new.tsx@@ -15,6 +15,7 @@ import {itemSerialSequenceValidator,upsertItemSerialSequence} from "~/modules/settings";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";export async function loader({ request }: LoaderFunctionArgs) {@@ -26,7 +27,7 @@ export async function loader({ request }: LoaderFunctionArgs) {// Items that already have a sequence can't get a second one.const existing = await getItemSerialSequences(client, companyId, {search: null,- limit: 1000,+ limit: SINGLE_LOAD_LIMIT,offset: 0,sorts: [],filters: []diff --git a/apps/erp/app/routes/x+/settings+/serial-numbers.tsx b/apps/erp/app/routes/x+/settings+/serial-numbers.tsxindex f66a56ef5a..50d1f7360f 100644--- a/apps/erp/app/routes/x+/settings+/serial-numbers.tsx+++ b/apps/erp/app/routes/x+/settings+/serial-numbers.tsx@@ -2,18 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import {- getItemSerialSequences,- ItemSerialSequencesTable-} from "~/modules/settings";+import { ItemSerialSequencesTable } from "~/modules/settings";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { itemSerialSequencesList } from "~/utils/list-registry/settings.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Serial Numbers`,@@ -21,32 +18,19 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "settings",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- return await getItemSerialSequences(client, companyId, {- search,- limit,- offset,- sorts,- filters- });+ return loadListPage(request, itemSerialSequencesList, { dataKey: "data" });}export default function SerialNumbersRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <ItemSerialSequencesTable data={data ?? []} count={count ?? 0} />+ <ItemSerialSequencesTable+ data={data ?? []}+ count={count ?? 0}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/settings+/webhooks.tsx b/apps/erp/app/routes/x+/settings+/webhooks.tsxindex 18fa64f0d2..015885776b 100644--- a/apps/erp/app/routes/x+/settings+/webhooks.tsx+++ b/apps/erp/app/routes/x+/settings+/webhooks.tsx@@ -3,7 +3,6 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { RecordOutlet } from "@carbon/react";import { redirect } from "@carbon/utils";@@ -11,14 +10,15 @@ import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { usePlanGate } from "~/hooks/usePlanGate";-import { getConfig, getWebhooks } from "~/modules/settings";+import { getConfig } from "~/modules/settings";import {WebhooksTable,WebhooksUpgradeOverlay} from "~/modules/settings/ui/Webhooks";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { webhooksList } from "~/utils/list-registry/settings.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Webhooks`,@@ -26,56 +26,33 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "settings"+ return loadListPage(request, webhooksList, {+ dataKey: "webhooks",+ firstPage: async ({ client }) => {+ const config = await getConfig(client);+ if (config.error || !config.data?.apiUrl) {+ throw redirect(+ path.to.settings,+ await flash(+ request,+ error(+ config.error,+ "Failed to load config. Please make sure a valid record exists in your public.config table."+ )+ )+ );+ }+ return { config: config.data ?? null };+ },+ onError: {+ redirectTo: path.to.settings,+ message: "Failed to load webhooks"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [webhooks, config] = await Promise.all([- getWebhooks(client, companyId, {- limit,- offset,- sorts,- search,- filters- }),- getConfig(client)- ]);-- if (webhooks.error) {- throw redirect(- path.to.settings,- await flash(request, error(webhooks.error, "Failed to load webhooks"))- );- }-- if (config.error || !config.data?.apiUrl) {- throw redirect(- path.to.settings,- await flash(- request,- error(- config.error,- "Failed to load config. Please make sure a valid record exists in your public.config table."- )- )- );- }-- return {- webhooks: webhooks.data ?? [],- count: webhooks.count ?? 0,- config: config.data ?? null- };}export default function WebhooksRoute() {- const { webhooks, count } = useLoaderData<typeof loader>();+ const { webhooks, count, nextCursor } = useLoaderData<typeof loader>();const { isGated } = usePlanGate({ feature: "WEBHOOKS" });if (isGated) {@@ -83,7 +60,7 @@ export default function WebhooksRoute() {}return (<>- <WebhooksTable count={count} data={webhooks} />+ <WebhooksTable count={count} data={webhooks} nextCursor={nextCursor} /><RecordOutlet /></>);diff --git a/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx b/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsxindex c9ab3d516a..1c5f60d7e8 100644--- a/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx+++ b/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx@@ -8,18 +8,43 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import { requireFeature } from "@carbon/ee/plan.server";import { validationError, validator } from "@carbon/form";-import { batchTrigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import { getClientIp, redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";+import { data } from "react-router";import {+ bulkPermissionsAllMatchingValidator,bulkPermissionsValidator,userPermissionsValidator} from "~/modules/users";+import { queuePermissionUpdates } from "~/modules/users/users.server";import { getParams, path } from "~/utils/path";+import { parseAllMatching } from "~/utils/table-jobs";+import { startTableBulkAction } from "~/utils/table-jobs.server";const logger = getLogger("erp", "users-bulk-edit-permissions");+type ModulePermissions = Record<+ string,+ { view: boolean; create: boolean; update: boolean; delete: boolean }+>;++/** The form's permissions JSON, or null when it is not valid. */+function parsePermissions(json: string): ModulePermissions | null {+ let permissions: unknown;+ try {+ permissions = JSON.parse(json);+ } catch {+ return null;+ }+ if (permissions === null || typeof permissions !== "object") return null;+ return Object.values(permissions).every(+ (permission) => userPermissionsValidator.safeParse(permission).success+ )+ ? (permissions as ModulePermissions)+ : null;+}+export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);const { client, companyId, userId } = await requirePermissions(request, {@@ -34,34 +59,56 @@ export async function action({ request }: ActionFunctionArgs) {feature: "PERMISSIONS"});+ const formData = await request.formData();++ // Every matching user of the Employees list: the background job picks the+ // active users and queues their permission update.+ const allMatching = parseAllMatching(formData.get("allMatching"));+ if (allMatching) {+ const matching = await validator(+ bulkPermissionsAllMatchingValidator+ ).validate(formData);+ if (matching.error) {+ return validationError(matching.error);+ }+ const permissions = parsePermissions(matching.data.data);+ if (!permissions) {+ return data({ success: false, message: "Failed to parse permissions" });+ }+ const ip = getClientIp(request) ?? undefined;+ const started = await startTableBulkAction({+ companyId,+ userId,+ actionKey: "users.permissions",+ params: {+ permissions,+ addOnly: matching.data.editType === "add",+ ...(ip ? { ip } : {})+ },+ allMatching+ });+ return started;+ }+const validation = await validator(bulkPermissionsValidator).validate(- await request.formData()+ formData);if (validation.error) {return validationError(validation.error);}- const { editType, userIds, data } = validation.data;+ const { editType, userIds } = validation.data;const addOnly = editType === "add";- const permissions: Record<- string,- {- view: boolean;- create: boolean;- update: boolean;- delete: boolean;- }- > = JSON.parse(data);+ const permissions = parsePermissions(validation.data.data);- if (- !Object.values(permissions).every(- (permission) => userPermissionsValidator.safeParse(permission).success- )- ) {+ if (!permissions) {throw redirect(path.to.employeeAccounts,- await flash(request, error(permissions, "Failed to parse permissions"))+ await flash(+ request,+ error(validation.data.data, "Failed to parse permissions")+ ));}@@ -87,18 +134,14 @@ export async function action({ request }: ActionFunctionArgs) {const ip = getClientIp(request) ?? undefined;- const batchPayload = userIds.map((id) => ({- payload: {- id,- permissions,- addOnly,- companyId,- actorId: userId,- ip- }- }));-- await batchTrigger("update-permissions", batchPayload);+ await queuePermissionUpdates({+ userIds,+ companyId,+ actorId: userId,+ permissions,+ addOnly,+ ip+ });throw redirect(`${path.to.employeeAccounts}?${getParams(request)}`,diff --git a/apps/erp/app/routes/x+/users+/customers.tsx b/apps/erp/app/routes/x+/users+/customers.tsxindex d694eb43c9..77748f6ba8 100644--- a/apps/erp/app/routes/x+/users+/customers.tsx+++ b/apps/erp/app/routes/x+/users+/customers.tsx@@ -17,6 +17,7 @@ import {getUnrevokedInviteEmails} from "~/modules/users";import type { Handle } from "~/utils/handle";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";@@ -35,17 +36,24 @@ export async function loader({ request }: LoaderFunctionArgs) {const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);+ const { sorts, filters } = getGenericQueryFilters(searchParams);const [customers, customerTypes, invites] = await Promise.all([- getCustomers(client, companyId, { search, limit, offset, sorts, filters }),+ getCustomers(client, companyId, {+ search,+ // A single-load list: its default sort is on the joined user, which a+ // cursor cannot follow.+ limit: SINGLE_LOAD_LIMIT,+ offset: 0,+ sorts,+ filters+ }),getCustomerTypes(client, companyId),getUnrevokedInviteEmails(client, companyId)]);if (customers.error) {- redirect(+ throw redirect(path.to.users,await flash(request, error(customers.error, "Failed to fetch customers")));@@ -54,20 +62,27 @@ export async function loader({ request }: LoaderFunctionArgs) {return {count: customers.count ?? 0,customers: customers.data ?? [],+ isTruncated: (customers.data?.length ?? 0) >= SINGLE_LOAD_LIMIT,customerTypes: customerTypes.data ?? [],unrevokedInviteEmails: invites.data?.map((i) => i.email) ?? []};}export default function UsersCustomersRoute() {- const { count, customers, customerTypes, unrevokedInviteEmails } =- useLoaderData<typeof loader>();+ const {+ count,+ customers,+ isTruncated,+ customerTypes,+ unrevokedInviteEmails+ } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full"><CustomerAccountsTabledata={customers}count={count}+ isTruncated={isTruncated}customerTypes={customerTypes}unrevokedInviteEmails={unrevokedInviteEmails}/>diff --git a/apps/erp/app/routes/x+/users+/deactivate.tsx b/apps/erp/app/routes/x+/users+/deactivate.tsxindex 34c6f5998e..0bd74bd079 100644--- a/apps/erp/app/routes/x+/users+/deactivate.tsx+++ b/apps/erp/app/routes/x+/users+/deactivate.tsx@@ -7,18 +7,38 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { deactivateUser } from "@carbon/auth/users.server";import { validationError, validator } from "@carbon/form";-import { batchTrigger } from "@carbon/jobs";+import { getLogger } from "@carbon/logger";import { getClientIp, redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { deactivateUsersValidator } from "~/modules/users";+import { queueUserDeactivations } from "~/modules/users/users.server";+import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";++const logger = getLogger("erp", "users-deactivate");export async function action({ request }: ActionFunctionArgs) {const { client, companyId, userId } = await requirePermissions(request, {delete: "users"});+ const formData = await request.formData();+ const ip = getClientIp(request) ?? undefined;++ // Every matching user of the Employees list: the background job picks the+ // active users other than the actor and queues their deactivation.+ const started = await startAllMatchingBulkAction(+ formData.get("allMatching"),+ {+ companyId,+ userId,+ actionKey: "users.deactivate",+ params: ip ? { ip } : {}+ }+ );+ if (started) return started;+const validation = await validator(deactivateUsersValidator).validate(- await request.formData()+ formData);if (validation.error) {@@ -27,8 +47,6 @@ export async function action({ request }: ActionFunctionArgs) {const { users, redirectTo } = validation.data;- const ip = getClientIp(request) ?? undefined;-if (users.includes(userId)) {throw redirect(redirectTo,@@ -48,31 +66,32 @@ export async function action({ request }: ActionFunctionArgs) {);throw redirect(redirectTo, await flash(request, result));- } else {- const batchPayload = users.map((id) => ({- payload: {- id,- type: "deactivate" as const,- companyId,- actorId: userId,- ip- }- }));+ }- try {- await batchTrigger("user-admin", batchPayload);- throw redirect(- redirectTo,- await flash(- request,- success("Success. Please check back in a few moments.")- )- );- } catch (e) {- throw redirect(- redirectTo,- await flash(request, error(e, "Failed to deactivate users"))- );- }+ // The success redirect stays outside the try: a thrown redirect is caught+ // like an error, and every deactivation then reported a failure.+ try {+ await queueUserDeactivations({+ userIds: users,+ companyId,+ actorId: userId,+ ip+ });+ } catch (e) {+ logger.error("Failed to queue user deactivations", {+ companyId,+ error: e+ });+ throw redirect(+ redirectTo,+ await flash(request, error(e, "Failed to deactivate users"))+ );}+ throw redirect(+ redirectTo,+ await flash(+ request,+ success("Success. Please check back in a few moments.")+ )+ );}diff --git a/apps/erp/app/routes/x+/users+/employee-types.tsx b/apps/erp/app/routes/x+/users+/employee-types.tsxindex 5c54e1232e..e7c08b34f0 100644--- a/apps/erp/app/routes/x+/users+/employee-types.tsx+++ b/apps/erp/app/routes/x+/users+/employee-types.tsx@@ -2,7 +2,6 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { RecordOutlet, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import type { LoaderFunctionArgs } from "react-router";@@ -10,12 +9,12 @@ import { useLoaderData } from "react-router";import { usePlanGate } from "~/hooks/usePlanGate";import {EmployeeTypesTable,- EmployeeTypesUpgradeOverlay,- getEmployeeTypes+ EmployeeTypesUpgradeOverlay} from "~/modules/users";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { employeeTypesList } from "~/utils/list-registry/users.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Employee Types`,@@ -23,33 +22,11 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "users",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const employeeTypes = await getEmployeeTypes(client, companyId, {- search,- limit,- offset,- sorts,- filters- });-- return {- data: employeeTypes.data ?? [],- count: employeeTypes.count ?? 0- };+ return loadListPage(request, employeeTypesList, { dataKey: "data" });}export default function EmployeeTypesRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();const { isGated } = usePlanGate({ feature: "PERMISSIONS" });if (isGated) {@@ -58,7 +35,11 @@ export default function EmployeeTypesRoute() {return (<VStack spacing={0} className="h-full">- <EmployeeTypesTable data={data ?? []} count={count ?? 0} />+ <EmployeeTypesTable+ data={data ?? []}+ count={count ?? 0}+ nextCursor={nextCursor}+ /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/users+/employees.tsx b/apps/erp/app/routes/x+/users+/employees.tsxindex 93566afd8a..c54303405b 100644--- a/apps/erp/app/routes/x+/users+/employees.tsx+++ b/apps/erp/app/routes/x+/users+/employees.tsx@@ -3,7 +3,6 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { getLogger } from "@carbon/logger";import { RecordOutlet, VStack } from "@carbon/react";@@ -13,14 +12,14 @@ import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import {EmployeesTable,- getEmployees,getEmployeeTypes,getUnrevokedInviteEmails,getUsersWithVerifiedMfa} from "~/modules/users";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { employeeAccountsList } from "~/utils/list-registry/users.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Employees`,@@ -28,68 +27,56 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "users",- role: "employee",- bypassRls: true- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);+ return loadListPage(request, employeeAccountsList, {+ dataKey: "employees",+ bypassRls: true,+ // The invites and the MFA users cover the whole company, so page 1 has them.+ firstPage: async ({ client, companyId }) => {+ const [employeeTypes, invites, mfaUsers] = await Promise.all([+ getEmployeeTypes(client, companyId),+ getUnrevokedInviteEmails(client, companyId),+ getUsersWithVerifiedMfa(client, companyId)+ ]);- const [employees, employeeTypes, invites, mfaUsers] = await Promise.all([- getEmployees(client, companyId, { search, limit, offset, sorts, filters }),- getEmployeeTypes(client, companyId),- getUnrevokedInviteEmails(client, companyId),- getUsersWithVerifiedMfa(client, companyId)- ]);+ if (mfaUsers.error) {+ getLogger("users").error("Failed to load MFA status for employees", {+ error: mfaUsers.error,+ companyId+ });+ }- if (mfaUsers.error) {- getLogger("users").error("Failed to load MFA status for employees", {- error: mfaUsers.error,- companyId- });- }+ if (employeeTypes.error) {+ throw redirect(+ path.to.users,+ await flash(+ request,+ error(employeeTypes.error, "Error loading employee types")+ )+ );+ }- if (employees.error) {- throw redirect(- path.to.users,- await flash(request, error(employees.error, "Error loading employees"))- );- }- if (employeeTypes.error) {- throw redirect(- path.to.users,- await flash(- request,- error(employeeTypes.error, "Error loading employee types")- )- );- }-- return {- count: employees.count ?? 0,- employees: employees.data ?? [],- employeeTypes: employeeTypes.data,- unrevokedInviteEmails: invites.data?.map((i) => i.email) ?? [],- // Surfaced rather than swallowed: a missing/stale RPC (e.g. PostgREST's- // schema cache not yet reloaded after the migration) otherwise looks- // exactly like "nobody has 2FA", which is a silently wrong answer.- mfaEnrolledUserIds: mfaUsers.error- ? []- : ((mfaUsers.data as { userId: string }[] | null)?.map((r) => r.userId) ??- [])- };+ return {+ employeeTypes: employeeTypes.data ?? [],+ unrevokedInviteEmails: invites.data?.map((i) => i.email) ?? [],+ // Surfaced rather than swallowed: a missing/stale RPC (e.g. PostgREST's+ // schema cache not yet reloaded after the migration) otherwise looks+ // exactly like "nobody has 2FA", which is a silently wrong answer.+ mfaEnrolledUserIds: mfaUsers.error+ ? []+ : ((mfaUsers.data as { userId: string }[] | null)?.map(+ (r) => r.userId+ ) ?? [])+ };+ },+ onError: { redirectTo: path.to.users, message: "Error loading employees" }+ });}export default function UsersEmployeesRoute() {const {count,employees,+ nextCursor,employeeTypes,unrevokedInviteEmails,mfaEnrolledUserIds@@ -100,6 +87,7 @@ export default function UsersEmployeesRoute() {<EmployeesTabledata={employees}count={count}+ nextCursor={nextCursor}employeeTypes={employeeTypes}unrevokedInviteEmails={unrevokedInviteEmails}mfaEnrolledUserIds={mfaEnrolledUserIds}diff --git a/apps/erp/app/routes/x+/users+/groups.tsx b/apps/erp/app/routes/x+/users+/groups.tsxindex 05fb06cb46..7b142d9b3d 100644--- a/apps/erp/app/routes/x+/users+/groups.tsx+++ b/apps/erp/app/routes/x+/users+/groups.tsx@@ -13,6 +13,7 @@ import { data, useLoaderData } from "react-router";import type { Group } from "~/modules/users";import { GroupsTable, getGroups } from "~/modules/users";import type { Handle } from "~/utils/handle";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";@@ -31,21 +32,22 @@ export async function loader({ request }: LoaderFunctionArgs) {const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");const uid = searchParams.get("uid");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);+ const { sorts, filters } = getGenericQueryFilters(searchParams);+ // The list is a tree (`arrayToTree`), and a page cut can split a group from+ // its parent, so it loads once: the first SINGLE_LOAD_LIMIT groups.const groups = await getGroups(client, companyId, {search,uid,- limit,- offset,+ limit: SINGLE_LOAD_LIMIT,+ offset: 0,sorts,filters});if (groups.error) {return data(- { groups: [], count: 0, error: groups.error },+ { groups: [], count: 0, isTruncated: false, error: groups.error },await flash(request, error(groups.error, "Failed to load groups")));}@@ -53,16 +55,17 @@ export async function loader({ request }: LoaderFunctionArgs) {return {groups: (groups.data ? arrayToTree(groups.data) : []) as Group[],error: null,- count: groups.count ?? 0+ count: groups.count ?? 0,+ isTruncated: (groups.data?.length ?? 0) >= SINGLE_LOAD_LIMIT};}export default function GroupsRoute() {- const { groups, count } = useLoaderData<typeof loader>();+ const { groups, count, isTruncated } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <GroupsTable data={groups} count={count} />+ <GroupsTable data={groups} count={count} isTruncated={isTruncated} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/routes/x+/users+/operators.tsx b/apps/erp/app/routes/x+/users+/operators.tsxindex e6cdbf489f..ef21d12281 100644--- a/apps/erp/app/routes/x+/users+/operators.tsx+++ b/apps/erp/app/routes/x+/users+/operators.tsx@@ -2,11 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";import { Checkbox, MenuIcon, MenuItem, RecordOutlet } from "@carbon/react";-import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import { useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";@@ -23,14 +19,13 @@ import { useLoaderData, useNavigate } from "react-router";import { EmployeeAvatar, New, Table } from "~/components";import { Enumerable } from "~/components/Enumerable";import { usePermissions, useUrlParams } from "~/hooks";-import {- getConsoleOperators,- getEmployeeTypes-} from "~/modules/users/users.service";+import type { getConsoleOperators } from "~/modules/users/users.service";+import { getEmployeeTypes } from "~/modules/users/users.service";import type { ListItem } from "~/types";import type { Handle } from "~/utils/handle";+import { loadListPage } from "~/utils/list-registry/load.server";+import { consoleOperatorsList } from "~/utils/list-registry/users.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {breadcrumb: msg`Operators`,@@ -38,45 +33,18 @@ export const handle: Handle = {};export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "users",- role: "employee",- bypassRls: true+ return loadListPage(request, consoleOperatorsList, {+ dataKey: "operators",+ bypassRls: true,+ firstPage: async ({ client, companyId }) => {+ const employeeTypes = await getEmployeeTypes(client, companyId);+ return { employeeTypes: employeeTypes.data ?? [] };+ },+ onError: {+ redirectTo: path.to.users,+ message: "Error loading console operators"+ }});-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");-- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const [operators, employeeTypes] = await Promise.all([- getConsoleOperators(client, companyId, {- search,- limit,- offset,- sorts,- filters- }),- getEmployeeTypes(client, companyId)- ]);-- if (operators.error) {- throw redirect(- path.to.users,- await flash(- request,- error(operators.error, "Error loading console operators")- )- );- }-- return {- count: operators.count ?? 0,- operators: operators.data ?? [],- employeeTypes: employeeTypes.data ?? []- };}type Operator = NonNullable<@@ -87,10 +55,12 @@ const OperatorsTable = memo(({data,count,+ nextCursor,employeeTypes}: {data: Operator[];count: number;+ nextCursor: string | null;employeeTypes: ListItem[];}) => {const { t } = useLingui();@@ -203,6 +173,11 @@ const OperatorsTable = memo(count={count}columns={columns}data={data}+ infinite={{+ dataKey: "operators",+ nextCursor,+ listKey: "console-operators"+ }}primaryAction={permissions.can("create", "users") && (<New label={t`Operator`} to={`new?${params.toString()}`} />@@ -218,13 +193,15 @@ const OperatorsTable = memo(OperatorsTable.displayName = "OperatorsTable";export default function ConsoleOperatorsRoute() {- const { count, operators, employeeTypes } = useLoaderData<typeof loader>();+ const { count, operators, nextCursor, employeeTypes } =+ useLoaderData<typeof loader>();return (<><OperatorsTabledata={operators}count={count}+ nextCursor={nextCursor}employeeTypes={employeeTypes}/><RecordOutlet />diff --git a/apps/erp/app/routes/x+/users+/resend-invite.tsx b/apps/erp/app/routes/x+/users+/resend-invite.tsxindex 2e42510000..f0a239c40b 100644--- a/apps/erp/app/routes/x+/users+/resend-invite.tsx+++ b/apps/erp/app/routes/x+/users+/resend-invite.tsx@@ -9,7 +9,6 @@ import { flash } from "@carbon/auth/session.server";import { InviteEmail } from "@carbon/documents/email";import { getSsoAwareInviteLink } from "@carbon/ee/sso.server";import { validationError, validator } from "@carbon/form";-import { batchTrigger } from "@carbon/jobs";import { sendEmail } from "@carbon/lib/email.server";import { datetime, getClientIp } from "@carbon/utils";import { render } from "@react-email/components";@@ -17,15 +16,33 @@ import { nanoid } from "nanoid";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { resendInviteValidator } from "~/modules/users";+import { queueInviteResends } from "~/modules/users/users.server";+import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";export async function action({ request }: ActionFunctionArgs) {- const { companyId } = await requirePermissions(request, {+ const { companyId, userId: actorId } = await requirePermissions(request, {create: "users"});- const validation = await validator(resendInviteValidator).validate(- await request.formData()+ const formData = await request.formData();++ // Every matching user of the Employees list: the background job picks the+ // inactive users with an email and no unrevoked invite and queues a resend.+ const started = await startAllMatchingBulkAction(+ formData.get("allMatching"),+ {+ companyId,+ userId: actorId,+ actionKey: "users.invite",+ params: {+ location: request.headers.get("x-vercel-ip-city") ?? "Unknown",+ ip: getClientIp(request) ?? "127.0.0.1"+ }+ });+ if (started) return started;++ const validation = await validator(resendInviteValidator).validate(formData);if (validation.error) {return validationError(validation.error);@@ -133,18 +150,7 @@ export async function action({ request }: ActionFunctionArgs) {const location = request.headers.get("x-vercel-ip-city") ?? "Unknown";const ip = getClientIp(request) ?? "127.0.0.1";try {- await batchTrigger(- "user-admin",- users.map((id) => ({- payload: {- id,- type: "resend" as const,- companyId,- location,- ip- }- }))- );+ await queueInviteResends({ userIds: users, companyId, location, ip });return data({},await flash(request, success("Successfully added invites to queue"))diff --git a/apps/erp/app/routes/x+/users+/suppliers.tsx b/apps/erp/app/routes/x+/users+/suppliers.tsxindex cda5e55f05..d8556dbcd5 100644--- a/apps/erp/app/routes/x+/users+/suppliers.tsx+++ b/apps/erp/app/routes/x+/users+/suppliers.tsx@@ -17,6 +17,7 @@ import {SupplierAccountsTable} from "~/modules/users";import type { Handle } from "~/utils/handle";+import { SINGLE_LOAD_LIMIT } from "~/utils/pagination";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";@@ -35,14 +36,15 @@ export async function loader({ request }: LoaderFunctionArgs) {const searchParams = new URLSearchParams(url.search);const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);+ const { sorts, filters } = getGenericQueryFilters(searchParams);const [suppliers, supplierTypes, invites] = await Promise.all([getSuppliers(client, companyId, {search,- limit,- offset,+ // A single-load list: its default sort is on the joined user, which a+ // cursor cannot follow.+ limit: SINGLE_LOAD_LIMIT,+ offset: 0,sorts,filters}),@@ -67,21 +69,28 @@ export async function loader({ request }: LoaderFunctionArgs) {return {count: suppliers.count ?? 0,- suppliers: suppliers.data,+ suppliers: suppliers.data ?? [],+ isTruncated: (suppliers.data?.length ?? 0) >= SINGLE_LOAD_LIMIT,supplierTypes: supplierTypes.data,unrevokedInviteEmails: invites.data?.map((i) => i.email) ?? []};}export default function UsersSuppliersRoute() {- const { count, suppliers, supplierTypes, unrevokedInviteEmails } =- useLoaderData<typeof loader>();+ const {+ count,+ suppliers,+ isTruncated,+ supplierTypes,+ unrevokedInviteEmails+ } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full"><SupplierAccountsTabledata={suppliers}count={count}+ isTruncated={isTruncated}supplierTypes={supplierTypes}unrevokedInviteEmails={unrevokedInviteEmails}/>diff --git a/apps/erp/app/routes/x+/workflows+/_index.tsx b/apps/erp/app/routes/x+/workflows+/_index.tsxindex 049f70333f..d774b8daaf 100644--- a/apps/erp/app/routes/x+/workflows+/_index.tsx+++ b/apps/erp/app/routes/x+/workflows+/_index.tsx@@ -2,78 +2,28 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { requirePermissions } from "@carbon/auth/auth.server";import { VStack } from "@carbon/react";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { usePlanGate } from "~/hooks/usePlanGate";-import type { WorkflowLastRun } from "~/modules/workflows";-import {- getWorkflowLastRuns,- getWorkflows,- getWorkflowVersionNumbers-} from "~/modules/workflows";import WorkflowsTable from "~/modules/workflows/ui/WorkflowsTable";import WorkflowsUpgradeOverlay from "~/modules/workflows/ui/WorkflowsUpgradeOverlay";-import { getGenericQueryFilters } from "~/utils/query";+import { loadListPage } from "~/utils/list-registry/load.server";+import {+ withWorkflowListExtras,+ workflowsList+} from "~/utils/list-registry/workflows.server";export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "workflows",- role: "employee"- });-- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const search = searchParams.get("search");- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);-- const workflows = await getWorkflows(client, companyId, {- search,- limit,- offset,- sorts,- filters+ return loadListPage(request, workflowsList, {+ dataKey: "data",+ // The published version number and the last run of each page's rows.+ mapRows: withWorkflowListExtras});-- const rows = workflows.data ?? [];- const publishedVersionIds = rows- .map((row) => row.publishedVersionId)- .filter((id): id is string => id !== null);-- const versionNumbers: Record<string, number> = {};- if (publishedVersionIds.length) {- const versions = await getWorkflowVersionNumbers(- client,- publishedVersionIds,- companyId- );- for (const version of versions.data ?? []) {- versionNumbers[version.id] = version.versionNumber;- }- }-- const workflowIds = rows.map((row) => row.id);- const lastRuns: Record<string, WorkflowLastRun> = {};- if (workflowIds.length) {- const runs = await getWorkflowLastRuns(client, workflowIds, companyId);- for (const run of runs.data ?? []) {- if (run.workflowId) lastRuns[run.workflowId] = run;- }- }-- return {- data: rows,- count: workflows.count ?? 0,- versionNumbers,- lastRuns- };}export default function WorkflowsIndexRoute() {- const { data, count, versionNumbers, lastRuns } =- useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();const { isGated } = usePlanGate({ feature: "WORKFLOWS" });if (isGated) {@@ -82,12 +32,7 @@ export default function WorkflowsIndexRoute() {return (<VStack spacing={0} className="h-full">- <WorkflowsTable- data={data}- count={count}- versionNumbers={versionNumbers}- lastRuns={lastRuns}- />+ <WorkflowsTable data={data} count={count} nextCursor={nextCursor} /></VStack>);}diff --git a/apps/erp/app/routes/x+/workflows+/runs.tsx b/apps/erp/app/routes/x+/workflows+/runs.tsxindex 4db3b0bc64..75c523303c 100644--- a/apps/erp/app/routes/x+/workflows+/runs.tsx+++ b/apps/erp/app/routes/x+/workflows+/runs.tsx@@ -4,22 +4,24 @@import { requirePermissions } from "@carbon/auth/auth.server";import { requireFeature } from "@carbon/ee/plan.server";+import { getLogger } from "@carbon/logger";import { RecordOutlet, VStack } from "@carbon/react";import type { LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";-import {- getWorkflowRunRecordNames,- getWorkflowRuns-} from "~/modules/workflows";+import { getWorkflowRunRecordNames } from "~/modules/workflows";import WorkflowRunsTable from "~/modules/workflows/ui/Runs/WorkflowRunsTable";+import { fetchListPage } from "~/utils/list-registry/index.server";+import { listErrorPage } from "~/utils/list-registry/load.server";+import { workflowRunsList } from "~/utils/list-registry/workflows.server";import { path } from "~/utils/path";-import { getGenericQueryFilters } from "~/utils/query";++const logger = getLogger("erp", "workflow-runs");export async function loader({ request }: LoaderFunctionArgs) {- const { client, companyId } = await requirePermissions(request, {- view: "workflows",- role: "employee"- });+ const { client, companyId } = await requirePermissions(+ request,+ workflowRunsList.permission+ );await requireFeature({request,client,@@ -28,19 +30,24 @@ export async function loader({ request }: LoaderFunctionArgs) {redirectTo: path.to.workflows});- const url = new URL(request.url);- const searchParams = new URLSearchParams(url.search);- const { limit, offset, sorts, filters } =- getGenericQueryFilters(searchParams);+ const searchParams = new URL(request.url).searchParams;+ const runs = await fetchListPage(+ workflowRunsList,+ client,+ companyId,+ searchParams+ );- const runs = await getWorkflowRuns(client, companyId, {- limit,- offset,- sorts,- filters- });+ if (runs.error && searchParams.get("after")) {+ logger.error("Failed to load a later page of workflow runs", {+ companyId,+ error: runs.error+ });+ return listErrorPage("data");+ }- const data = runs.data ?? [];+ // The record names are read per page, so every loaded row carries its own.+ const data = runs.rows;const recordNames = await getWorkflowRunRecordNames(client,companyId,@@ -56,15 +63,16 @@ export async function loader({ request }: LoaderFunctionArgs) {...run,recordName: recordNames[`${run.triggerTable}:${run.triggerRecordId}`]})),- count: runs.count ?? 0+ count: runs.count,+ nextCursor: runs.nextCursor};}export default function WorkflowRunsRoute() {- const { data, count } = useLoaderData<typeof loader>();+ const { data, count, nextCursor } = useLoaderData<typeof loader>();return (<VStack spacing={0} className="h-full">- <WorkflowRunsTable data={data} count={count} />+ <WorkflowRunsTable data={data} count={count} nextCursor={nextCursor} /><RecordOutlet /></VStack>);diff --git a/apps/erp/app/shortcuts.ts b/apps/erp/app/shortcuts.tsindex b066789096..36ad385a19 100644--- a/apps/erp/app/shortcuts.ts+++ b/apps/erp/app/shortcuts.ts@@ -58,12 +58,6 @@ export const ONBOARDING_SHORTCUTS = {continue: "enter"} as const satisfies Record<string, ShortcutInput>;-/** Table pagination. */-export const PAGINATION_SHORTCUTS = {- previous: "arrowleft",- next: "arrowright"-} as const satisfies Record<string, ShortcutInput>;-/*** g-then-letter module go-to, keyed by the stable module `key` from* useModules() — never by position, since module order and visibility arediff --git a/apps/erp/app/utils/bulk-delete.server.ts b/apps/erp/app/utils/bulk-delete.server.tsnew file mode 100644index 0000000000..49bf73efb3--- /dev/null+++ b/apps/erp/app/utils/bulk-delete.server.ts@@ -0,0 +1,66 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { getLogger } from "@carbon/logger";+import { chunkArray } from "@carbon/utils";++const logger = getLogger("erp", "bulk-delete");++/** An `.in()` filter rides in the request URL, so ids go 100 at a time. */+const IN_CHUNK = 100;++export type BulkDeleteResult = {+ /** Rows the database deleted. */+ deleted: number;+ /** Ids it did not delete: another status, another company, or not found. */+ skipped: number;+ /** Ids whose delete failed (a whole chunk fails together). */+ failed: number;+ /** The first failure's message, or null. */+ error: string | null;+};++type DeleteChunk = (ids: string[]) => PromiseLike<{+ data: { id: string }[] | null;+ error: { message: string } | null;+}>;++/**+ * A table's bulk Delete: deletes the ids 100 at a time and counts the rows+ * that went. `deleteChunk` filters on the company AND the statuses the action+ * accepts in the DELETE itself and returns the deleted ids (`.select("id")`),+ * so a row whose status changed since the user selected it stays, and the+ * counts are the database's, not the request's.+ */+export async function bulkDeleteByStatus(args: {+ ids: string[];+ companyId: string;+ /** What is deleted, for the log ("jobs"). */+ label: string;+ deleteChunk: DeleteChunk;+}): Promise<BulkDeleteResult> {+ const result: BulkDeleteResult = {+ deleted: 0,+ skipped: 0,+ failed: 0,+ error: null+ };+ const ids = [...new Set(args.ids.filter(Boolean))];+ for (const chunk of chunkArray(ids, IN_CHUNK)) {+ const deleted = await args.deleteChunk(chunk);+ if (deleted.error) {+ logger.error(`Failed to delete ${args.label}`, {+ companyId: args.companyId,+ error: deleted.error+ });+ result.failed += chunk.length;+ result.error ??= deleted.error.message;+ continue;+ }+ const count = deleted.data?.length ?? 0;+ result.deleted += count;+ result.skipped += chunk.length - count;+ }+ return result;+}diff --git a/apps/erp/app/utils/bulk-selection.ts b/apps/erp/app/utils/bulk-selection.tsnew file mode 100644index 0000000000..3939b86e94--- /dev/null+++ b/apps/erp/app/utils/bulk-selection.ts@@ -0,0 +1,61 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { allMatchingRequest, type BulkActionScope } from "~/components/Table";+import type { AllMatchingRequest } from "./table-jobs";++/**+ * What a bulk action posts for its selection: every matching row+ * (`allMatching`, the list and its URL search) when the Table's scope says+ * so, else the selected ids under the route's own field name.+ */++export type BulkSelection = {+ scope?: BulkActionScope;+ /** The route's id field: "items", "ids", "jobIds", "batchIds", … */+ idsField: string;+ ids: (string | null | undefined)[];+};++/** Adds the selection to a form body: one `idsField` entry per id, or the+ * `allMatching` JSON the route reads with `parseAllMatching`. */+export function appendBulkSelection(+ formData: FormData,+ { scope, idsField, ids }: BulkSelection+): FormData {+ if (scope?.allMatching) {+ formData.append(+ "allMatching",+ JSON.stringify(allMatchingRequest(scope.allMatching))+ );+ } else {+ for (const id of ids) if (id) formData.append(idsField, id);+ }+ return formData;+}++/** The selection as a JSON body. */+export function bulkSelectionBody({+ scope,+ idsField,+ ids+}: BulkSelection):+ | { allMatching: AllMatchingRequest }+ | Record<string, string[]> {+ return scope?.allMatching+ ? { allMatching: allMatchingRequest(scope.allMatching) }+ : { [idsField]: ids.filter((id): id is string => !!id) };+}++/**+ * Whether an "every matching row" selection is past an action's row limit+ * (Jobs Release and Batches Release run on at most 2,000). The count is the+ * header's: exact up to 1,000, an estimate above, so the route checks again.+ */+export function isOverAllMatchingLimit(+ scope: BulkActionScope | undefined,+ limit: number+): boolean {+ return !!scope?.allMatching && scope.allMatching.count > limit;+}diff --git a/apps/erp/app/utils/cursor.test.ts b/apps/erp/app/utils/cursor.test.tsnew file mode 100644index 0000000000..3c91fec663--- /dev/null+++ b/apps/erp/app/utils/cursor.test.ts@@ -0,0 +1,348 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ buildKeysetFilter,+ cursorMatchesSorts,+ decodeCursor,+ decodeOffsetToken,+ encodeCursor,+ encodeOffsetToken,+ keysetKeys,+ readSortValue,+ toPage+} from "./cursor";++describe("encodeCursor / decodeCursor", () => {+ it("round-trips a cursor, including non-ASCII text and arrays", () => {+ const cursor = {+ values: ['Müller, (GmbH) "quoted"', 12.5, true, null, ["a", "b"]],+ id: "so_123",+ keys: ["name:asc", "total:desc", "paid:asc", "dueDate:asc", "tags:asc"]+ };+ const token = encodeCursor(cursor);+ expect(token).toMatch(/^[A-Za-z0-9_-]+$/);+ expect(decodeCursor(token)).toEqual(cursor);+ });++ it("returns null for a missing token", () => {+ expect(decodeCursor(null)).toBeNull();+ expect(decodeCursor("")).toBeNull();+ });++ it("returns null for garbage", () => {+ expect(decodeCursor("not a cursor!!")).toBeNull();+ expect(decodeCursor("e30")).toBeNull(); // "{}"+ expect(decodeCursor(btoa(JSON.stringify({ values: [{}], id: "x" })))).toBe(+ null+ );+ expect(+ decodeCursor(btoa(JSON.stringify({ values: [], id: 1, keys: [] })))+ ).toBe(null);+ });++ it("returns null for a cursor without the sorts it was cut for", () => {+ expect(decodeCursor(btoa(JSON.stringify({ values: [], id: "x" })))).toBe(+ null+ );+ });+});++describe("cursorMatchesSorts", () => {+ const sorts = [{ column: "createdAt", ascending: false }];+ const cursor = {+ values: ["2026-10-13"],+ id: "so_1",+ keys: keysetKeys(sorts)+ };++ it("accepts a cursor cut for the same order", () => {+ expect(cursorMatchesSorts(cursor, sorts)).toBe(true);+ });++ it("rejects a cursor cut for another column or direction", () => {+ expect(+ cursorMatchesSorts(cursor, [{ column: "dueDate", ascending: false }])+ ).toBe(false);+ expect(+ cursorMatchesSorts(cursor, [{ column: "createdAt", ascending: true }])+ ).toBe(false);+ });++ it("rejects a cursor cut for more or fewer sorts", () => {+ expect(cursorMatchesSorts(cursor, [])).toBe(false);+ expect(+ cursorMatchesSorts(cursor, [+ ...sorts,+ { column: "name", ascending: true }+ ])+ ).toBe(false);+ });+});++describe("encodeOffsetToken / decodeOffsetToken", () => {+ it("round-trips an offset", () => {+ expect(decodeOffsetToken(encodeOffsetToken(300))).toBe(300);+ });++ it("reads a missing, malformed or negative token as 0", () => {+ expect(decodeOffsetToken(null)).toBe(0);+ expect(decodeOffsetToken("garbage!!")).toBe(0);+ expect(decodeOffsetToken(btoa(JSON.stringify({ offset: -5 })))).toBe(0);+ expect(decodeOffsetToken(btoa(JSON.stringify({ offset: "9" })))).toBe(0);+ });+});++describe("buildKeysetFilter", () => {+ it("one ascending sort: larger values, then NULLs, then ties by id", () => {+ expect(+ buildKeysetFilter(+ [{ column: "name", ascending: true }],+ { values: ["Bolt"], id: "it_1" },+ "id"+ )+ ).toBe('name.gt."Bolt",name.is.null,and(name.eq."Bolt",id.gt."it_1")');+ });++ it("one descending sort: smaller values, then ties by id", () => {+ expect(+ buildKeysetFilter(+ [{ column: "createdAt", ascending: false }],+ { values: ["2026-10-13T10:00:00+00:00"], id: "so_9" },+ "id"+ )+ ).toBe(+ 'createdAt.lt."2026-10-13T10:00:00+00:00",and(createdAt.eq."2026-10-13T10:00:00+00:00",id.gt."so_9")'+ );+ });++ it("two sorts: each branch fixes the earlier sorts with equality", () => {+ expect(+ buildKeysetFilter(+ [+ { column: "status", ascending: true },+ { column: "dueDate", ascending: false }+ ],+ { values: ["Open", "2026-11-01"], id: "j_4" },+ "id"+ )+ ).toBe(+ [+ 'status.gt."Open"',+ "status.is.null",+ 'and(status.eq."Open",dueDate.lt."2026-11-01")',+ 'and(status.eq."Open",dueDate.eq."2026-11-01",id.gt."j_4")'+ ].join(",")+ );+ });++ it("a NULL value, ascending: only later NULLs by id can follow", () => {+ expect(+ buildKeysetFilter(+ [{ column: "dueDate", ascending: true }],+ { values: [null], id: "j_4" },+ "id"+ )+ ).toBe('and(dueDate.is.null,id.gt."j_4")');+ });++ it("a NULL value, descending: every non-NULL value follows", () => {+ expect(+ buildKeysetFilter(+ [{ column: "dueDate", ascending: false }],+ { values: [null], id: "j_4" },+ "id"+ )+ ).toBe('dueDate.not.is.null,and(dueDate.is.null,id.gt."j_4")');+ });++ it("quotes and escapes commas, parentheses and quotes", () => {+ const value = 'Washer, Flat (M8) "zinc" \\ end';+ expect(+ buildKeysetFilter(+ [{ column: "name", ascending: false }],+ { values: [value], id: 'a"b' },+ "id"+ )+ ).toBe(+ 'name.lt."Washer, Flat (M8) \\"zinc\\" \\\\ end",and(name.eq."Washer, Flat (M8) \\"zinc\\" \\\\ end",id.gt."a\\"b")'+ );+ });++ it("writes numbers and booleans in quoted string form", () => {+ expect(+ buildKeysetFilter(+ [+ { column: "quantity", ascending: true },+ { column: "active", ascending: false }+ ],+ { values: [12.5, true], id: "x" },+ "id"+ )+ ).toBe(+ [+ 'quantity.gt."12.5"',+ "quantity.is.null",+ 'and(quantity.eq."12.5",active.lt."true")',+ 'and(quantity.eq."12.5",active.eq."true",id.gt."x")'+ ].join(",")+ );+ });++ it("writes an array as a quoted Postgres array literal", () => {+ expect(+ buildKeysetFilter(+ [{ column: "tags", ascending: false }],+ { values: [["a", 'b"c']], id: "x" },+ "id"+ )+ ).toBe(+ 'tags.lt."{\\"a\\",\\"b\\\\\\"c\\"}",and(tags.eq."{\\"a\\",\\"b\\\\\\"c\\"}",id.gt."x")'+ );+ });++ it("uses a custom-field column as written", () => {+ expect(+ buildKeysetFilter(+ [{ column: "customFields->>color", ascending: true }],+ { values: ["Red"], id: "x" },+ "id"+ )+ ).toBe(+ 'customFields->>color.gt."Red",customFields->>color.is.null,and(customFields->>color.eq."Red",id.gt."x")'+ );+ });++ it("uses the list's own id column as the tie-breaker", () => {+ expect(+ buildKeysetFilter(+ [{ column: "name", ascending: false }],+ { values: ["A"], id: "sc_1" },+ "supplierContactId"+ )+ ).toBe('name.lt."A",and(name.eq."A",supplierContactId.gt."sc_1")');+ });++ it("adds no tie-breaker when the last sort is the id itself", () => {+ expect(+ buildKeysetFilter(+ [{ column: "id", ascending: false }],+ { values: ["x"], id: "x" },+ "id"+ )+ ).toBe('id.lt."x"');+ });++ it("with no sorts, pages by id alone", () => {+ expect(buildKeysetFilter([], { values: [], id: "x" }, "id")).toBe(+ 'id.gt."x"'+ );+ });+});++describe("readSortValue", () => {+ it("reads a plain column and turns undefined into null", () => {+ expect(readSortValue({ name: "Bolt" }, "name")).toBe("Bolt");+ expect(readSortValue({}, "name")).toBeNull();+ });++ it("reads a custom field as text", () => {+ const row = { customFields: { color: "Red", size: 4 } };+ expect(readSortValue(row, "customFields->>color")).toBe("Red");+ expect(readSortValue(row, "customFields->>size")).toBe("4");+ expect(readSortValue(row, "customFields->>missing")).toBeNull();+ expect(readSortValue({ customFields: null }, "customFields->>x")).toBe(+ null+ );+ });+});++describe("toPage", () => {+ const sorts = [{ column: "name", ascending: true }];+ const rows = (count: number) =>+ Array.from({ length: count }, (_, i) => ({+ id: `it_${i}`,+ name: `Item ${String(i).padStart(3, "0")}`+ }));++ it("drops the extra row and builds the cursor from the last kept row", () => {+ const page = toPage(rows(4), { limit: 3, sorts });+ expect(page.rows).toHaveLength(3);+ expect(page.nextCursor).not.toBeNull();+ expect(decodeCursor(page.nextCursor)).toEqual({+ values: ["Item 002"],+ id: "it_2",+ keys: ["name:asc"]+ });+ });++ it("returns every row and no cursor on the last page", () => {+ const page = toPage(rows(2), { limit: 3, sorts });+ expect(page.rows).toHaveLength(2);+ expect(page.nextCursor).toBeNull();+ });++ it("reads the tie-breaker from a custom id column", () => {+ const page = toPage(+ [+ { supplierContactId: "a", name: "A" },+ { supplierContactId: "b", name: "B" }+ ],+ { limit: 1, sorts, idColumn: "supplierContactId" }+ );+ expect(decodeCursor(page.nextCursor)).toEqual({+ values: ["A"],+ id: "a",+ keys: ["name:asc"]+ });+ });++ it("ends the list when a sort column is not in the row", () => {+ const page = toPage(rows(4), {+ limit: 3,+ sorts: [{ column: "dueDate", ascending: true }]+ });+ expect(page.rows).toHaveLength(3);+ expect(page.nextCursor).toBeNull();+ });++ it("ends the list when the id column is not in the row", () => {+ const page = toPage(rows(4), { limit: 3, sorts, idColumn: "itemId" });+ expect(page.nextCursor).toBeNull();+ });++ it("resolves the order from the list's paging", () => {+ const paging = {+ defaultSorts: [+ { column: "name", ascending: true },+ { column: "name", ascending: true, foreignTable: "supplier" }+ ]+ };+ const fromDefaults = toPage(rows(4), { limit: 3 }, paging);+ expect(decodeCursor(fromDefaults.nextCursor)?.keys).toEqual(["name:asc"]);++ const fromUser = toPage(+ rows(4),+ { limit: 3, sorts: [{ sortBy: "id", sortAsc: false }] },+ paging+ );+ expect(decodeCursor(fromUser.nextCursor)).toEqual({+ values: ["it_2"],+ id: "it_2",+ keys: ["id:desc"]+ });+ });++ it("does not require a custom-field sort column to be a top-level key", () => {+ const page = toPage(+ [+ { id: "x", customFields: {} },+ { id: "y", customFields: {} }+ ],+ { limit: 1, sorts: [{ column: "customFields->>color", ascending: true }] }+ );+ expect(page.nextCursor).not.toBeNull();+ });+});diff --git a/apps/erp/app/utils/cursor.ts b/apps/erp/app/utils/cursor.tsnew file mode 100644index 0000000000..95948ca0f1--- /dev/null+++ b/apps/erp/app/utils/cursor.ts@@ -0,0 +1,337 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { getLogger } from "@carbon/logger";++/**+ * Cursor (keyset) paging for list loaders.+ *+ * A cursor is the last row of a page: the value of each sort column plus the+ * row's unique id. The next page is "every row that sorts after it", which the+ * database answers from an index at any depth, and which stays stable when+ * rows are added or deleted between two requests.+ *+ * Postgres orders NULLs last when ascending and first when descending (the+ * default, which `.order(column, { ascending })` keeps), so the "after" filter+ * follows the same rule.+ */++export type CursorValue = string | number | boolean | null | string[];++/**+ * The last row of a page. `keys` names the sorts the values were read for+ * (`keysetKeys`), so a cursor cut for another order is never compared with+ * this one.+ */+export type Cursor = { values: CursorValue[]; id: string; keys: string[] };++export type KeysetSort = { column: string; ascending: boolean };++/** A sort the user picked (`?sort=column:asc`). */+export type Sort = {+ sortBy: string;+ sortAsc: boolean;+};++export type DefaultSort = {+ column: string;+ ascending: boolean;+ foreignTable?: string;+};++/**+ * How a list orders its rows when the user picks no sort, and the unique+ * column that breaks ties. One `X_PAGING` constant per list: the service+ * passes it to `setGenericQueryFilters`, the loader to `toPage`, and the+ * registry entry spreads it.+ */+export type Paging = {+ defaultSorts: DefaultSort[];+ /** The unique column that breaks ties. Default: `id`. */+ idColumn?: string;+};++const CUSTOM_FIELD_PREFIX = "customFields->>";++const logger = getLogger("erp", "cursor");++/**+ * The list's order: the user's sorts when present, else the defaults. A sort+ * on another table's column (`table.column`) is dropped: the keyset filter+ * cannot compare it. A default sort on a `foreignTable` orders the embedded+ * rows, not the list, so it is applied but stays out of the keyset.+ */+export function resolveSorts(+ sorts: Sort[] | undefined,+ defaultSorts: DefaultSort[] = []+): { orders: DefaultSort[]; keyset: KeysetSort[] } {+ const userSorts = (sorts ?? [])+ .filter((sort) => !sort.sortBy.includes("."))+ .map((sort) => ({ column: sort.sortBy, ascending: sort.sortAsc }));++ const orders = userSorts.length > 0 ? userSorts : defaultSorts;+ const keyset = orders+ .filter((sort) => !("foreignTable" in sort && sort.foreignTable))+ .map(({ column, ascending }) => ({ column, ascending }));++ return { orders, keyset };+}++/** The signature of an order, stored in the cursor: `["createdAt:desc"]`. */+export function keysetKeys(sorts: KeysetSort[]): string[] {+ return sorts.map(+ (sort) => `${sort.column}:${sort.ascending ? "asc" : "desc"}`+ );+}++/** Whether `cursor` was cut for the order `sorts`. */+export function cursorMatchesSorts(cursor: Cursor, sorts: KeysetSort[]) {+ const keys = keysetKeys(sorts);+ return (+ cursor.values.length === keys.length &&+ cursor.keys.length === keys.length &&+ cursor.keys.every((key, index) => key === keys[index])+ );+}++function toBase64Url(text: string) {+ const bytes = new TextEncoder().encode(text);+ let binary = "";+ for (const byte of bytes) binary += String.fromCharCode(byte);+ return btoa(binary)+ .replace(/\+/g, "-")+ .replace(/\//g, "_")+ .replace(/=+$/, "");+}++function fromBase64Url(token: string): unknown {+ const base64 = token.replace(/-/g, "+").replace(/_/g, "/");+ const binary = atob(base64);+ const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));+ return JSON.parse(new TextDecoder().decode(bytes));+}++export function encodeCursor(cursor: Cursor): string {+ return toBase64Url(JSON.stringify(cursor));+}++/** Returns null for a missing, malformed or tampered token. */+export function decodeCursor(token: string | null): Cursor | null {+ if (!token) return null;+ try {+ const parsed = fromBase64Url(token);+ return isCursor(parsed) ? parsed : null;+ } catch {+ return null;+ }+}++/**+ * The `?after=` token of a list that pages by offset (an RPC with no+ * keyset: printing jobs, the audit log). It is not a `Cursor`.+ */+export function encodeOffsetToken(offset: number): string {+ return toBase64Url(JSON.stringify({ offset }));+}++/** The offset in an offset token; 0 for a missing or malformed token. */+export function decodeOffsetToken(token: string | null): number {+ if (!token) return 0;+ try {+ const parsed = fromBase64Url(token) as { offset?: unknown } | null;+ const offset = parsed?.offset;+ return typeof offset === "number" && Number.isInteger(offset) && offset > 0+ ? offset+ : 0;+ } catch {+ return 0;+ }+}++function isCursorValue(value: unknown): value is CursorValue {+ if (value === null) return true;+ if (Array.isArray(value)) return value.every((v) => typeof v === "string");+ return ["string", "number", "boolean"].includes(typeof value);+}++function isCursor(value: unknown): value is Cursor {+ if (!value || typeof value !== "object") return false;+ const candidate = value as Record<string, unknown>;+ return (+ typeof candidate.id === "string" &&+ Array.isArray(candidate.values) &&+ candidate.values.every(isCursorValue) &&+ Array.isArray(candidate.keys) &&+ candidate.keys.every((key) => typeof key === "string")+ );+}++// A value inside a PostgREST logic tree (`or=(...)`): quoting keeps `,`, `(`,+// `)`, `.` and `:` from changing the filter's shape.+// `packages/ee/src/accounting/core/operations.ts` repeats this escape (ee+// cannot import the app).+function escapeQuoted(value: string) {+ return value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');+}++/** A value quoted for a PostgREST `or=(...)` filter. */+export function quoteFilterValue(value: string) {+ return `"${escapeQuoted(value)}"`;+}++function quote(value: Exclude<CursorValue, null>) {+ if (Array.isArray(value)) {+ const literal = `{${value.map((v) => `"${escapeQuoted(v)}"`).join(",")}}`;+ return `"${escapeQuoted(literal)}"`;+ }+ return `"${escapeQuoted(String(value))}"`;+}++function equalTerm(column: string, value: CursorValue) {+ return value === null ? `${column}.is.null` : `${column}.eq.${quote(value)}`;+}++// The terms that put a row strictly after `value` on one sort column. Each+// term becomes its own branch; an empty list means no row is strictly after.+function afterTerms(sort: KeysetSort, value: CursorValue): string[] {+ const { column, ascending } = sort;+ if (ascending) {+ // NULLS LAST: after a value come the larger values, then the NULLs.+ return value === null+ ? []+ : [`${column}.gt.${quote(value)}`, `${column}.is.null`];+ }+ // NULLS FIRST: after a NULL come all the values; after a value, the smaller ones.+ return value === null+ ? [`${column}.not.is.null`]+ : [`${column}.lt.${quote(value)}`];+}++function branch(terms: string[]) {+ return terms.length === 1 ? terms[0] : `and(${terms.join(",")})`;+}++/**+ * The argument for `query.or(...)` that keeps only the rows after `cursor` in+ * the order `sorts` + `idColumn` ascending.+ */+export function buildKeysetFilter(+ sorts: KeysetSort[],+ cursor: Pick<Cursor, "values" | "id">,+ idColumn: string+): string {+ const branches: string[] = [];+ const prefix: string[] = [];++ sorts.forEach((sort, index) => {+ const value = cursor.values[index] ?? null;+ for (const term of afterTerms(sort, value)) {+ branches.push(branch([...prefix, term]));+ }+ prefix.push(equalTerm(sort.column, value));+ });++ // The id is unique, so it decides between rows that tie on every sort. When+ // the last sort is the id itself, the order is already total.+ if (sorts[sorts.length - 1]?.column !== idColumn) {+ branches.push(branch([...prefix, `${idColumn}.gt.${quote(cursor.id)}`]));+ }++ return branches.join(",");+}++function toCursorValue(value: unknown): CursorValue {+ if (value === undefined || value === null) return null;+ if (Array.isArray(value)) return value.map((v) => String(v));+ if (typeof value === "object") return JSON.stringify(value);+ return value as CursorValue;+}++export function readSortValue(+ row: Record<string, unknown>,+ column: string+): CursorValue {+ if (column.startsWith(CUSTOM_FIELD_PREFIX)) {+ const key = column.slice(CUSTOM_FIELD_PREFIX.length);+ const customFields = row.customFields as+ | Record<string, unknown>+ | null+ | undefined;+ const value = customFields?.[key];+ // `->>` reads JSON as text, so the cursor compares it as text too.+ return value === undefined || value === null ? null : String(value);+ }+ return toCursorValue(row[column]);+}++function missingColumn(row: Record<string, unknown>, columns: string[]) {+ return columns.find(+ (column) => !column.startsWith(CUSTOM_FIELD_PREFIX) && !(column in row)+ );+}++type PageArgs = { limit: number; sorts: KeysetSort[]; idColumn?: string };++/**+ * Turns `limit + 1` fetched rows into one page. The extra row only proves that+ * a next page exists; the cursor comes from the last row the page keeps.+ *+ * Two forms:+ * - `toPage(rows, { limit, sorts, idColumn })` with the sorts the query+ * ordered by (`getEffectiveSorts`).+ * - `toPage(rows, { limit, sorts }, X_PAGING)` with the user's sorts (from+ * `getGenericQueryFilters`) and the list's paging: it resolves the order+ * the same way `setGenericQueryFilters` does.+ *+ * If a sort column or the id column is not in the row (the service's select+ * lacks it), the page ends the list (`nextCursor: null`) and a warning is+ * logged: a cursor without the value would repeat or skip rows.+ */+export function toPage<T extends Record<string, unknown>>(+ rows: T[],+ args: PageArgs+): { rows: T[]; nextCursor: string | null };+export function toPage<T extends Record<string, unknown>>(+ rows: T[],+ args: { limit: number; sorts?: Sort[] },+ paging: Paging+): { rows: T[]; nextCursor: string | null };+export function toPage<T extends Record<string, unknown>>(+ rows: T[],+ args: PageArgs | { limit: number; sorts?: Sort[] },+ paging?: Paging+): { rows: T[]; nextCursor: string | null } {+ const { limit } = args;+ const sorts = paging+ ? resolveSorts(args.sorts as Sort[] | undefined, paging.defaultSorts).keyset+ : (args as PageArgs).sorts;+ const idColumn = (paging ?? (args as PageArgs)).idColumn ?? "id";++ if (rows.length <= limit) {+ return { rows, nextCursor: null };+ }++ const kept = rows.slice(0, limit);+ const last = kept[kept.length - 1];+ const missing = missingColumn(last, [+ ...sorts.map((sort) => sort.column),+ idColumn+ ]);+ if (missing) {+ logger.warning(+ "Cursor paging stopped: the column {column} is not in the list's select",+ { column: missing }+ );+ return { rows: kept, nextCursor: null };+ }++ return {+ rows: kept,+ nextCursor: encodeCursor({+ values: sorts.map((sort) => readSortValue(last, sort.column)),+ id: String(last[idColumn]),+ keys: keysetKeys(sorts)+ })+ };+}diff --git a/apps/erp/app/utils/list-registry/accounting.server.ts b/apps/erp/app/utils/list-registry/accounting.server.tsnew file mode 100644index 0000000000..e0bc70b8ac--- /dev/null+++ b/apps/erp/app/utils/list-registry/accounting.server.ts@@ -0,0 +1,186 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { RunType } from "@carbon/database/run-type";+import {+ DEPRECIATION_RUNS_PAGING,+ DIMENSIONS_PAGING,+ FIXED_ASSET_CLASSES_PAGING,+ FIXED_ASSETS_PAGING,+ FLEET_ASSETS_PAGING,+ getDepreciationRuns,+ getDimensions,+ getFixedAssetClasses,+ getFixedAssets,+ getFleetAssets,+ getIntercompanyTransactions,+ getJournalEntries,+ getPaymentTerms,+ getProjects,+ getRevenueRecognitionRuns,+ INTERCOMPANY_TRANSACTIONS_PAGING,+ JOURNAL_ENTRIES_PAGING,+ PAYMENT_TERMS_PAGING,+ PERIOD_RUNS_PAGING,+ PROJECTS_PAGING+} from "~/modules/accounting";+import type { ListDefinition } from "./index.server";+import { resolveCompanyGroupId, searchList } from "./index.server";++const ACCOUNTING_PERMISSION = {+ view: "accounting",+ role: "employee"+} satisfies ListDefinition["permission"];++// Dimensions and intercompany transactions belong to the company group: the+// loader passes its group, and a background job's query reads it.++export const journalEntriesList = searchList({+ key: "journal-entries",+ permission: ACCOUNTING_PERMISSION,+ paging: JOURNAL_ENTRIES_PAGING,+ service: getJournalEntries,+ params: { status: "status" }+});++export const fixedAssetsList = searchList({+ key: "fixed-assets",+ permission: ACCOUNTING_PERMISSION,+ paging: FIXED_ASSETS_PAGING,+ service: getFixedAssets,+ params: { status: "status" }+});++export const assetClassesList = searchList({+ key: "asset-classes",+ permission: ACCOUNTING_PERMISSION,+ paging: FIXED_ASSET_CLASSES_PAGING,+ service: getFixedAssetClasses+});++export const depreciationRunsList = searchList({+ key: "depreciation-runs",+ permission: ACCOUNTING_PERMISSION,+ paging: DEPRECIATION_RUNS_PAGING,+ service: getDepreciationRuns+});++export const fleetAssetsList = searchList({+ key: "fleet-assets",+ permission: ACCOUNTING_PERMISSION,+ paging: FLEET_ASSETS_PAGING,+ service: getFleetAssets,+ params: { fleetStatus: "fleetStatus" }+});++export const dimensionsList = {+ key: "accounting-dimensions",+ permission: ACCOUNTING_PERMISSION,+ ...DIMENSIONS_PAGING,+ query: async (client, companyId, context) => {+ const { companyGroupId, error } = await resolveCompanyGroupId(+ client,+ companyId,+ context+ );+ if (!companyGroupId) return { data: null, error };+ const { params, limit, cursor, sorts, filters } = context;+ return getDimensions(client, companyGroupId, {+ search: params.get("search"),+ limit,+ cursor,+ sorts,+ filters+ });+ }+} satisfies ListDefinition;++export const intercompanyTransactionsList = {+ key: "intercompany-transactions",+ permission: ACCOUNTING_PERMISSION,+ ...INTERCOMPANY_TRANSACTIONS_PAGING,+ query: async (client, companyId, context) => {+ const { companyGroupId, error } = await resolveCompanyGroupId(+ client,+ companyId,+ context+ );+ if (!companyGroupId) return { data: null, error };+ const { params, limit, cursor, sorts, filters } = context;+ return getIntercompanyTransactions(client, companyGroupId, {+ status: params.get("status"),+ limit,+ cursor,+ sorts,+ filters+ });+ }+} satisfies ListDefinition;++export const paymentTermsList = searchList({+ key: "payment-terms",+ permission: ACCOUNTING_PERMISSION,+ paging: PAYMENT_TERMS_PAGING,+ service: getPaymentTerms+});++export const projectsList = searchList({+ key: "projects",+ permission: ACCOUNTING_PERMISSION,+ paging: PROJECTS_PAGING,+ service: getProjects+});++// Revenue recognition runs and lease runs share one engine and one list query+// (`period-runs.server.ts`); each run type is its own list.+function periodRunsQuery(type: RunType) {+ return (+ ...[+ client,+ companyId,+ { params, limit, cursor, sorts, filters }+ ]: Parameters<ListDefinition["query"]>+ ) =>+ getRevenueRecognitionRuns(client, companyId, type, {+ search: params.get("search"),+ limit,+ cursor,+ sorts,+ filters+ });+}++export const revenueRecognitionRunsList = {+ key: "revenue-recognition-runs",+ permission: ACCOUNTING_PERMISSION,+ ...PERIOD_RUNS_PAGING,+ query: periodRunsQuery("Revenue Recognition")+} satisfies ListDefinition;++export const leaseRunsList = {+ key: "lease-runs",+ permission: ACCOUNTING_PERMISSION,+ ...PERIOD_RUNS_PAGING,+ query: periodRunsQuery("Lease")+} satisfies ListDefinition;++export const periodRunsLists = {+ "Revenue Recognition": revenueRecognitionRunsList,+ Lease: leaseRunsList+} satisfies Record<RunType, ListDefinition>;++// The accounting lists. Each entry follows `sales.server.ts`.+export const accountingLists: Record<string, ListDefinition> = {+ [journalEntriesList.key]: journalEntriesList,+ [fixedAssetsList.key]: fixedAssetsList,+ [assetClassesList.key]: assetClassesList,+ [depreciationRunsList.key]: depreciationRunsList,+ [fleetAssetsList.key]: fleetAssetsList,+ [dimensionsList.key]: dimensionsList,+ [intercompanyTransactionsList.key]: intercompanyTransactionsList,+ [paymentTermsList.key]: paymentTermsList,+ [projectsList.key]: projectsList,+ [revenueRecognitionRunsList.key]: revenueRecognitionRunsList,+ [leaseRunsList.key]: leaseRunsList+};diff --git a/apps/erp/app/utils/list-registry/documents.server.ts b/apps/erp/app/utils/list-registry/documents.server.tsnew file mode 100644index 0000000000..c575757d94--- /dev/null+++ b/apps/erp/app/utils/list-registry/documents.server.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ DOCUMENTS_PAGING,+ getDocuments,+ RECENT_DOCUMENTS_PAGING+} from "~/modules/documents/documents.service";+import type { ListDefinition } from "./index.server";++// `?q=` picks the view: `starred`, `recent`, `trash`, `my` or none (all).+// `getDocuments` does not filter on `createdBy`, so `my` lists every document.+// The `recent` flag comes from the list, not the URL, so the query's order+// always matches the list's paging.+function documentsQuery(recent: boolean) {+ return (+ ...[+ client,+ companyId,+ { params, limit, cursor, sorts, filters }+ ]: Parameters<ListDefinition["query"]>+ ) => {+ const filter = params.get("q");+ return getDocuments(client, companyId, {+ search: params.get("search"),+ favorite: filter === "starred" ? true : undefined,+ recent: recent ? true : undefined,+ active: filter !== "trash",+ limit,+ cursor,+ sorts,+ filters+ });+ };+}++export const documentsList = {+ key: "documents",+ permission: { view: "documents" },+ ...DOCUMENTS_PAGING,+ query: documentsQuery(false)+} satisfies ListDefinition;++// The "Recent" view has its own default order, so it is its own list: the+// cursor must follow the order the query uses.+export const recentDocumentsList = {+ key: "recent-documents",+ permission: { view: "documents" },+ ...RECENT_DOCUMENTS_PAGING,+ query: documentsQuery(true)+} satisfies ListDefinition;++// The documents lists. Each entry follows `sales.server.ts`.+export const documentsLists: Record<string, ListDefinition> = {+ [documentsList.key]: documentsList,+ [recentDocumentsList.key]: recentDocumentsList+};diff --git a/apps/erp/app/utils/list-registry/export-values.ts b/apps/erp/app/utils/list-registry/export-values.tsnew file mode 100644index 0000000000..87ba00b3e3--- /dev/null+++ b/apps/erp/app/utils/list-registry/export-values.ts@@ -0,0 +1,21 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++/** A column's export value, computed from a row (`meta.exportValue`). */+export type ListExportValues<TRow> = Record<string, (row: TRow) => unknown>;++/**+ * Each row with `values` computed onto it, keyed by column: what a list's+ * `exportRows` hands the background export, which reads `row[key]`.+ */+export function withExportValues<TRow extends Record<string, unknown>>(+ rows: TRow[],+ values: ListExportValues<TRow>+): Record<string, unknown>[] {+ const entries = Object.entries(values);+ return rows.map((row) => ({+ ...row,+ ...Object.fromEntries(entries.map(([key, value]) => [key, value(row)]))+ }));+}diff --git a/apps/erp/app/utils/list-registry/index.server.ts b/apps/erp/app/utils/list-registry/index.server.tsnew file mode 100644index 0000000000..4f7cb99e7e--- /dev/null+++ b/apps/erp/app/utils/list-registry/index.server.ts@@ -0,0 +1,249 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { requirePermissions } from "@carbon/auth/auth.server";+import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";+import type { Cursor, Paging } from "../cursor";+import { decodeCursor, toPage } from "../cursor";+import { PAGE_SIZE } from "../pagination";+import type { Filter, Sort } from "../query";+import { getGenericQueryFilters } from "../query";+import { accountingLists } from "./accounting.server";+import { documentsLists } from "./documents.server";+import { inventoryLists } from "./inventory.server";+import { invoicingLists } from "./invoicing.server";+import { itemsLists } from "./items.server";+import { peopleLists } from "./people.server";+import { productionLists } from "./production.server";+import { purchasingLists } from "./purchasing.server";+import { qualityLists } from "./quality.server";+import { resourcesLists } from "./resources.server";+import { salesLists } from "./sales.server";+import { settingsLists } from "./settings.server";+import { usersLists } from "./users.server";+import { workflowsLists } from "./workflows.server";++/**+ * The server's list of paged ERP lists. One entry holds the query a list's+ * loader runs, so the loader and the background jobs (export, bulk action)+ * read the same rows with the same filters, sorts and permission.+ *+ * Each module keeps its entries in its own file (`sales.server.ts`, …), so+ * module batches can add entries without touching the same file.+ */++/** Which page to read: `limit` rows after `cursor` (null: the first page). */+export type ListPaging = { limit: number; cursor: Cursor | null };++export type ListPermission = Omit<+ Parameters<typeof requirePermissions>[1],+ "bypassRls"+>;++export type ListQueryResult<TRow> = {+ data: TRow[] | null;+ error: unknown;+ count?: number | null;+};++/**+ * What a list's `query` gets, parsed once by `fetchListPage`: the URL search,+ * the page, and the user's sorts and filters (`getGenericQueryFilters`).+ */+export type ListQueryContext = ListPaging & {+ /** The URL search: `search` and the list's own params (`status`, …). */+ params: URLSearchParams;+ sorts: Sort[];+ filters: Filter[];+ /**+ * The company's group, when the caller already has it (a loader's+ * `requirePermissions`). A group-scoped list reads it with+ * `resolveCompanyGroupId`, which looks it up only when it is absent.+ */+ companyGroupId?: string;+};++export type ListRowsContext = {+ client: SupabaseClient<Database>;+ companyId: string;+};++export type ListDefinition<+ TRow extends Record<string, unknown> = Record<string, unknown>+> = Paging & {+ /** The list's key, for example "sales-orders". */+ key: string;+ /** The loader's permission check, without `bypassRls`. */+ permission: ListPermission;+ /** The loader's query for one page. */+ query: (+ client: SupabaseClient<Database>,+ companyId: string,+ context: ListQueryContext+ ) => PromiseLike<ListQueryResult<TRow>>;+ /**+ * The rows of one page as the background CSV export writes them, for a list+ * whose loader adds per-row values (`mapRows`) that columns export: the same+ * lookup, then each such column's export value under its column key. The+ * export job reads `row[key]` and runs no column code.+ */+ exportRows?(+ rows: TRow[],+ context: ListRowsContext+ ): Promise<Record<string, unknown>[]>;+};++export type ListPage<TRow> = {+ rows: TRow[];+ /** The number of matching rows. Only the first page counts (0 later). */+ count: number;+ nextCursor: string | null;+ error: unknown;+};++// One file per module. A module batch adds its entries to its own file only.+export const LIST_REGISTRY: Record<string, ListDefinition> = {+ ...accountingLists,+ ...documentsLists,+ ...inventoryLists,+ ...invoicingLists,+ ...itemsLists,+ ...peopleLists,+ ...productionLists,+ ...purchasingLists,+ ...qualityLists,+ ...resourcesLists,+ ...salesLists,+ ...settingsLists,+ ...usersLists,+ ...workflowsLists+};++export function getListDefinition(key: string): ListDefinition | undefined {+ return Object.hasOwn(LIST_REGISTRY, key) ? LIST_REGISTRY[key] : undefined;+}++/**+ * Runs a list's query for one page and cuts it with `toPage`. Without+ * `paging`, the page is the one the URL asks for: 100 rows after `?after=`.+ * `options.companyGroupId` saves a group lookup for group-scoped lists.+ */+export async function fetchListPage<TRow extends Record<string, unknown>>(+ definition: ListDefinition<TRow>,+ client: SupabaseClient<Database>,+ companyId: string,+ params: URLSearchParams,+ paging: ListPaging = {+ limit: PAGE_SIZE,+ cursor: decodeCursor(params.get("after"))+ },+ options: { companyGroupId?: string } = {}+): Promise<ListPage<TRow>> {+ const { sorts = [], filters = [] } = getGenericQueryFilters(params);+ const result = await definition.query(client, companyId, {+ ...paging,+ params,+ sorts,+ filters,+ companyGroupId: options.companyGroupId+ });+ const page = toPage(+ result.data ?? [],+ { limit: paging.limit, sorts },+ definition+ );+ return {+ rows: page.rows,+ count: result.count ?? 0,+ nextCursor: page.nextCursor,+ error: result.error+ };+}++/**+ * The company's group for a group-scoped list (dimensions, intercompany):+ * the caller's when it passed one, else read from the company.+ */+export async function resolveCompanyGroupId(+ client: SupabaseClient<Database>,+ companyId: string,+ context: Pick<ListQueryContext, "companyGroupId">+): Promise<{ companyGroupId: string | null; error: unknown }> {+ if (context.companyGroupId) {+ return { companyGroupId: context.companyGroupId, error: null };+ }+ const company = await client+ .from("company")+ .select("companyGroupId")+ .eq("id", companyId)+ .single();+ return {+ companyGroupId: company.data?.companyGroupId ?? null,+ error: company.error+ };+}++/** A URL param the list passes to its service: its name, or a reader. */+type ParamReader = string | ((params: URLSearchParams) => unknown);++/**+ * A list whose service takes `(client, companyId, args)` and reads the+ * common args: the service gets `{ search, ...params, limit, cursor, sorts,+ * filters }`. `search` is `params.get("search")`; each entry of `params`+ * names a URL param (passed as `string | null`) or reads one itself.+ *+ * ```ts+ * export const salesOrdersList = searchList({+ * key: "sales-orders",+ * permission: { view: "sales" },+ * paging: SALES_ORDERS_PAGING,+ * service: getSalesOrders,+ * params: { status: "status", customerId: "customerId" }+ * });+ * ```+ *+ * A list with another service shape (a group id, a positional arg, two+ * services) writes its own `query`.+ */+export function searchList<TRow extends Record<string, unknown>, TArgs>({+ key,+ permission,+ paging,+ service,+ params: readers = {},+ exportRows+}: {+ key: string;+ permission: ListPermission;+ paging: Paging;+ service: (+ client: SupabaseClient<Database>,+ companyId: string,+ args: TArgs+ ) => PromiseLike<ListQueryResult<TRow>>;+ params?: Record<string, ParamReader>;+ exportRows?: ListDefinition<TRow>["exportRows"];+}): ListDefinition<TRow> {+ return {+ key,+ permission,+ ...paging,+ ...(exportRows ? { exportRows } : {}),+ query: (client, companyId, { params, limit, cursor, sorts, filters }) => {+ const named: Record<string, unknown> = { search: params.get("search") };+ for (const [arg, reader] of Object.entries(readers)) {+ named[arg] =+ typeof reader === "string" ? params.get(reader) : reader(params);+ }+ return service(client, companyId, {+ ...named,+ limit,+ cursor,+ sorts,+ filters+ } as TArgs);+ }+ };+}diff --git a/apps/erp/app/utils/list-registry/inventory.server.ts b/apps/erp/app/utils/list-registry/inventory.server.tsnew file mode 100644index 0000000000..ea83df0255--- /dev/null+++ b/apps/erp/app/utils/list-registry/inventory.server.ts@@ -0,0 +1,107 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ getInventoryCounts,+ getPickingLists,+ getReceipts,+ getShipments,+ getShippingMethods,+ getStockMovements,+ getStorageTypes,+ getTrackedEntities,+ getWarehouseTransfers,+ INVENTORY_COUNTS_PAGING,+ PICKING_LISTS_PAGING,+ RECEIPTS_PAGING,+ SHIPMENTS_PAGING,+ SHIPPING_METHODS_PAGING,+ STOCK_MOVEMENTS_PAGING,+ STORAGE_TYPES_PAGING,+ TRACKED_ENTITIES_PAGING,+ WAREHOUSE_TRANSFERS_PAGING+} from "~/modules/inventory";+import type { ListDefinition } from "./index.server";+import { searchList } from "./index.server";++// The inventory lists. Each entry follows `sales.server.ts`. The quantities,+// kanbans, stock transfers and storage units lists have no entry: their+// loaders read the location from the user's defaults, which a registry query+// cannot see.++export const inventoryCountsList = searchList({+ key: "inventory-counts",+ permission: { view: "inventory" },+ paging: INVENTORY_COUNTS_PAGING,+ service: getInventoryCounts+});++export const pickingListsList = searchList({+ key: "picking-lists",+ permission: { view: "inventory" },+ paging: PICKING_LISTS_PAGING,+ service: getPickingLists,+ params: { status: "status", assignee: "assignee", locationId: () => null }+});++export const receiptsList = searchList({+ key: "receipts",+ permission: { view: "inventory" },+ paging: RECEIPTS_PAGING,+ service: getReceipts+});++export const shipmentsList = searchList({+ key: "shipments",+ permission: { view: "inventory" },+ paging: SHIPMENTS_PAGING,+ service: getShipments+});++export const shippingMethodsList = searchList({+ key: "shipping-methods",+ permission: { view: "inventory", role: "employee" },+ paging: SHIPPING_METHODS_PAGING,+ service: getShippingMethods+});++export const stockMovementsList = searchList({+ key: "stock-movements",+ permission: { view: "inventory" },+ paging: STOCK_MOVEMENTS_PAGING,+ service: getStockMovements+});++export const storageTypesList = searchList({+ key: "storage-types",+ permission: { view: "parts", role: "employee" },+ paging: STORAGE_TYPES_PAGING,+ service: getStorageTypes+});++export const trackedEntitiesList = searchList({+ key: "tracked-entities",+ permission: { view: "inventory", role: "employee" },+ paging: TRACKED_ENTITIES_PAGING,+ service: getTrackedEntities+});++export const warehouseTransfersList = searchList({+ key: "warehouse-transfers",+ permission: { view: "inventory" },+ paging: WAREHOUSE_TRANSFERS_PAGING,+ service: getWarehouseTransfers+});++export const inventoryLists: Record<string, ListDefinition> = {+ [inventoryCountsList.key]: inventoryCountsList,+ [pickingListsList.key]: pickingListsList,+ [receiptsList.key]: receiptsList,+ [shipmentsList.key]: shipmentsList,+ [shippingMethodsList.key]: shippingMethodsList,+ [stockMovementsList.key]: stockMovementsList,+ [storageTypesList.key]: storageTypesList,+ [trackedEntitiesList.key]: trackedEntitiesList,+ [warehouseTransfersList.key]: warehouseTransfersList+};diff --git a/apps/erp/app/utils/list-registry/invoicing.server.ts b/apps/erp/app/utils/list-registry/invoicing.server.tsnew file mode 100644index 0000000000..b2b2350f6a--- /dev/null+++ b/apps/erp/app/utils/list-registry/invoicing.server.ts@@ -0,0 +1,144 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ CHARGES_PAGING,+ getCharges,+ getMemos,+ getPayments,+ getPurchaseInvoices,+ getReimbursements,+ getSalesInvoices,+ MEMOS_PAGING,+ PAYMENTS_PAGING,+ PURCHASE_INVOICES_PAGING,+ REIMBURSEMENTS_PAGING,+ SALES_INVOICES_PAGING+} from "~/modules/invoicing";+import type { Filter } from "../query";+import type { ListDefinition } from "./index.server";+import { searchList } from "./index.server";++// The "Counterparty" column filter spans two columns (customerId OR+// supplierId), so the payments and memos lists take it out of the generic+// filters and hand it to the service, which applies it as an OR.+function splitCounterpartyFilter(filters: Filter[] = []) {+ const counterpartyIds = filters+ .filter((f) => f.column === "counterparty")+ .flatMap((f) => (f.value ?? "").split(","))+ .filter(Boolean);+ return {+ counterpartyIds: counterpartyIds.length > 0 ? counterpartyIds : null,+ filters: filters.filter((f) => f.column !== "counterparty")+ };+}++// The status filter of the payment, memo, charge and reimbursement lists.+type DocumentStatus = "Draft" | "Posted" | "Voided";++export const salesInvoicesList = searchList({+ key: "sales-invoices",+ permission: { view: "invoicing" },+ paging: SALES_INVOICES_PAGING,+ service: getSalesInvoices,+ params: { customerId: "customerId" }+});++export const purchaseInvoicesList = searchList({+ key: "purchase-invoices",+ permission: { view: "invoicing" },+ paging: PURCHASE_INVOICES_PAGING,+ service: getPurchaseInvoices,+ params: { supplierId: "supplierId" }+});++export const paymentsList = {+ key: "payments",+ permission: { view: "invoicing" },+ ...PAYMENTS_PAGING,+ query: (client, companyId, { params, limit, cursor, sorts, filters }) => {+ const split = splitCounterpartyFilter(filters);+ return getPayments(client, companyId, {+ search: params.get("search"),+ paymentType: params.get("paymentType") as+ | "Receipt"+ | "Disbursement"+ | null,+ status: params.get("status") as DocumentStatus | null,+ customerId: params.get("customerId"),+ supplierId: params.get("supplierId"),+ counterpartyIds: split.counterpartyIds,+ limit,+ cursor,+ sorts,+ filters: split.filters+ });+ }+} satisfies ListDefinition;++// Accounts Receivable (customer memos) and Accounts Payable (supplier memos)+// read the same `memo` table, scoped by party.+function memosQuery(party: "customer" | "supplier") {+ return (+ ...[+ client,+ companyId,+ { params, limit, cursor, sorts, filters }+ ]: Parameters<ListDefinition["query"]>+ ) => {+ const split = splitCounterpartyFilter(filters);+ return getMemos(client, companyId, {+ search: params.get("search"),+ direction: params.get("direction") as "Credit" | "Debit" | null,+ status: params.get("status") as DocumentStatus | null,+ party,+ counterpartyIds: split.counterpartyIds,+ limit,+ cursor,+ sorts,+ filters: split.filters+ });+ };+}++export const creditMemosList = {+ key: "credit-memos",+ permission: { view: "invoicing" },+ ...MEMOS_PAGING,+ query: memosQuery("customer")+} satisfies ListDefinition;++export const supplierCreditsList = {+ key: "supplier-credits",+ permission: { view: "invoicing" },+ ...MEMOS_PAGING,+ query: memosQuery("supplier")+} satisfies ListDefinition;++export const chargesList = searchList({+ key: "charges",+ permission: { view: "invoicing" },+ paging: CHARGES_PAGING,+ service: getCharges,+ params: { type: "type", status: "status" }+});++export const reimbursementsList = searchList({+ key: "reimbursements",+ permission: { view: "invoicing" },+ paging: REIMBURSEMENTS_PAGING,+ service: getReimbursements,+ params: { status: "status", employeeId: "employeeId" }+});++// The invoicing lists. Each entry follows `sales.server.ts`.+export const invoicingLists: Record<string, ListDefinition> = {+ [salesInvoicesList.key]: salesInvoicesList,+ [purchaseInvoicesList.key]: purchaseInvoicesList,+ [paymentsList.key]: paymentsList,+ [creditMemosList.key]: creditMemosList,+ [supplierCreditsList.key]: supplierCreditsList,+ [chargesList.key]: chargesList,+ [reimbursementsList.key]: reimbursementsList+};diff --git a/apps/erp/app/utils/list-registry/items.server.ts b/apps/erp/app/utils/list-registry/items.server.tsnew file mode 100644index 0000000000..b8b28759b3--- /dev/null+++ b/apps/erp/app/utils/list-registry/items.server.ts@@ -0,0 +1,212 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ CHANGE_NOTICE_REQUIRED_ACTIONS_PAGING,+ CHANGE_NOTICE_TYPES_PAGING,+ CHANGE_NOTICES_PAGING,+ CONSUMABLES_PAGING,+ getChangeNoticeRequiredActions,+ getChangeNotices,+ getChangeNoticeTypes,+ getConsumables,+ getItemPostingGroups,+ getMaterialDimensions,+ getMaterialFinishes,+ getMaterialForms,+ getMaterialGrades,+ getMaterialSubstances,+ getMaterials,+ getMaterialTypes,+ getMethodMaterials,+ getMethodOperations,+ getParts,+ getServices,+ getTools,+ getUnitOfMeasures,+ ITEM_POSTING_GROUPS_PAGING,+ MATERIAL_DIMENSIONS_PAGING,+ MATERIAL_FINISHES_PAGING,+ MATERIAL_FORMS_PAGING,+ MATERIAL_GRADES_PAGING,+ MATERIAL_SUBSTANCES_PAGING,+ MATERIAL_TYPES_PAGING,+ MATERIALS_PAGING,+ METHOD_MATERIALS_PAGING,+ METHOD_OPERATIONS_PAGING,+ PARTS_PAGING,+ SERVICES_PAGING,+ TOOLS_PAGING,+ UNIT_OF_MEASURES_PAGING+} from "~/modules/items";+import { getCompanySettings } from "~/modules/settings/settings.service";+import type { ListDefinition } from "./index.server";+import { searchList } from "./index.server";++export const partsList = searchList({+ key: "parts",+ permission: { view: "parts" },+ paging: PARTS_PAGING,+ service: getParts,+ params: { supplierId: "supplierId" }+});++export const materialsList = searchList({+ key: "materials",+ permission: { view: "parts" },+ paging: MATERIALS_PAGING,+ service: getMaterials,+ params: { supplierId: "supplierId" }+});++export const toolsList = searchList({+ key: "tools",+ permission: { view: "parts" },+ paging: TOOLS_PAGING,+ service: getTools,+ params: { supplierId: "supplierId" }+});++export const consumablesList = searchList({+ key: "consumables",+ permission: { view: "parts" },+ paging: CONSUMABLES_PAGING,+ service: getConsumables,+ params: { supplierId: "supplierId" }+});++export const servicesList = searchList({+ key: "services",+ permission: { view: "parts" },+ paging: SERVICES_PAGING,+ service: getServices,+ params: { supplierId: "supplierId", group: "group" }+});++export const changeNoticesList = searchList({+ key: "change-notices",+ permission: { view: "parts", role: "employee" },+ paging: CHANGE_NOTICES_PAGING,+ service: getChangeNotices+});++export const changeNoticeRequiredActionsList = searchList({+ key: "change-notice-actions",+ permission: { view: "parts", role: "employee" },+ paging: CHANGE_NOTICE_REQUIRED_ACTIONS_PAGING,+ service: getChangeNoticeRequiredActions+});++export const changeNoticeTypesList = searchList({+ key: "change-notice-types",+ permission: { view: "parts", role: "employee" },+ paging: CHANGE_NOTICE_TYPES_PAGING,+ service: getChangeNoticeTypes+});++export const materialDimensionsList = {+ key: "material-dimensions",+ permission: { view: "parts", role: "employee" },+ ...MATERIAL_DIMENSIONS_PAGING,+ // The list shows the dimensions of the company's unit system only.+ query: async (+ client,+ companyId,+ { params, limit, cursor, sorts, filters }+ ) => {+ const settings = await getCompanySettings(client, companyId);+ return getMaterialDimensions(client, companyId, {+ search: params.get("search"),+ isMetric: settings?.data?.useMetric ?? false,+ limit,+ cursor,+ sorts,+ filters+ });+ }+} satisfies ListDefinition;++export const materialFinishesList = searchList({+ key: "material-finishes",+ permission: { view: "parts", role: "employee" },+ paging: MATERIAL_FINISHES_PAGING,+ service: getMaterialFinishes+});++export const materialFormsList = searchList({+ key: "material-forms",+ permission: { view: "parts", role: "employee" },+ paging: MATERIAL_FORMS_PAGING,+ service: getMaterialForms+});++export const materialGradesList = searchList({+ key: "material-grades",+ permission: { view: "parts", role: "employee" },+ paging: MATERIAL_GRADES_PAGING,+ service: getMaterialGrades+});++export const itemPostingGroupsList = searchList({+ key: "item-posting-groups",+ permission: { view: "parts", role: "employee" },+ paging: ITEM_POSTING_GROUPS_PAGING,+ service: getItemPostingGroups+});++export const materialSubstancesList = searchList({+ key: "material-substances",+ permission: { view: "parts", role: "employee" },+ paging: MATERIAL_SUBSTANCES_PAGING,+ service: getMaterialSubstances+});++export const materialTypesList = searchList({+ key: "material-types",+ permission: { view: "parts", role: "employee" },+ paging: MATERIAL_TYPES_PAGING,+ service: getMaterialTypes+});++export const unitOfMeasuresList = searchList({+ key: "units-of-measure",+ permission: { view: "parts", role: "employee" },+ paging: UNIT_OF_MEASURES_PAGING,+ service: getUnitOfMeasures+});++export const methodMaterialsList = searchList({+ key: "method-materials",+ permission: { view: "production", role: "employee" },+ paging: METHOD_MATERIALS_PAGING,+ service: getMethodMaterials+});++export const methodOperationsList = searchList({+ key: "method-operations",+ permission: { view: "production", role: "employee" },+ paging: METHOD_OPERATIONS_PAGING,+ service: getMethodOperations+});++export const itemsLists: Record<string, ListDefinition> = {+ [partsList.key]: partsList,+ [materialsList.key]: materialsList,+ [toolsList.key]: toolsList,+ [consumablesList.key]: consumablesList,+ [servicesList.key]: servicesList,+ [changeNoticesList.key]: changeNoticesList,+ [changeNoticeRequiredActionsList.key]: changeNoticeRequiredActionsList,+ [changeNoticeTypesList.key]: changeNoticeTypesList,+ [materialDimensionsList.key]: materialDimensionsList,+ [materialFinishesList.key]: materialFinishesList,+ [materialFormsList.key]: materialFormsList,+ [materialGradesList.key]: materialGradesList,+ [itemPostingGroupsList.key]: itemPostingGroupsList,+ [materialSubstancesList.key]: materialSubstancesList,+ [materialTypesList.key]: materialTypesList,+ [unitOfMeasuresList.key]: unitOfMeasuresList,+ [methodMaterialsList.key]: methodMaterialsList,+ [methodOperationsList.key]: methodOperationsList+};diff --git a/apps/erp/app/utils/list-registry/list-error.ts b/apps/erp/app/utils/list-registry/list-error.tsnew file mode 100644index 0000000000..317d01ee59--- /dev/null+++ b/apps/erp/app/utils/list-registry/list-error.ts@@ -0,0 +1,27 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// No imports on purpose: a service module (`accounting.server.ts`) returns a+// failed page without loading the list registry, which reaches every module.++/** The `listError` of a failed later page. The Table does not show it. */+export const LOAD_MORE_ERROR = "Failed to load more rows";++/**+ * The loader data of a later page (`?after=`) that failed, for a list loader+ * that does not use `loadListPage`: `{ [dataKey]: [], count: 0,+ * nextCursor: null, listError }`. Log the real error first, then+ * `return listErrorPage(dataKey)`.+ *+ * Typed `never` so the loader's data type stays the page-1 shape that+ * `useLoaderData` reads: only the Table's fetcher reads a later page.+ */+export function listErrorPage(dataKey: string): never {+ return {+ [dataKey]: [],+ count: 0,+ nextCursor: null,+ listError: LOAD_MORE_ERROR+ } as never;+}diff --git a/apps/erp/app/utils/list-registry/load.server.ts b/apps/erp/app/utils/list-registry/load.server.tsnew file mode 100644index 0000000000..84415fe440--- /dev/null+++ b/apps/erp/app/utils/list-registry/load.server.ts@@ -0,0 +1,174 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { error } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";+import { getLogger } from "@carbon/logger";+import { redirect } from "@carbon/utils";+import type { InfiniteListError } from "~/components/Table/types";+import type { ListDefinition } from "./index.server";+import { fetchListPage } from "./index.server";+import { listErrorPage } from "./list-error";++export { LOAD_MORE_ERROR, listErrorPage } from "./list-error";++const logger = getLogger("erp", "list-registry");++/** What a list loader has when it reads its page and its page-1 extras. */+export type ListLoaderContext = Awaited<+ ReturnType<typeof requirePermissions>+> & {+ request: Request;+ /** The URL search the list reads. */+ params: URLSearchParams;+};++/** The loader data of a list page: the rows under `dataKey`, the count and+ * the cursor, plus `listError` on a failed later page. */+export type ListLoaderData<TKey extends string, TRow> = {+ [K in TKey]: TRow[];+} & {+ count: number;+ nextCursor: string | null;+} & Partial<InfiniteListError>;++export type LoadListPageOptions<+ TKey extends string,+ TExtra,+ TRow = Record<string, unknown>,+ TOut = TRow+> = {+ /** The key of the rows in the loader data (the Table's `infinite.dataKey`). */+ dataKey: TKey;+ /** Pass the loader's own `bypassRls: true`, if it had one. Never add it. */+ bypassRls?: boolean;+ /**+ * A check that runs on every page, after the permission check and before+ * the query: it throws (a redirect) when the list must not load, for+ * example a feature the company has turned off.+ */+ guard?: (context: ListLoaderContext) => Promise<void> | void;+ /**+ * The URL search the list query reads, when it is not the request's: for+ * example a default for a param the URL leaves out. Runs on every page.+ */+ params?: (context: ListLoaderContext) => URLSearchParams;+ /**+ * The page-1 extras (option lists, tags, settings). Runs only without+ * `?after=`, in parallel with the page; its result is merged into the+ * loader data. A later page returns the rows only.+ */+ firstPage?: (context: ListLoaderContext) => Promise<TExtra> | TExtra;+ /**+ * Adds per-row values the list's view does not have (a lookup in another+ * table) to the rows of every page, so each page carries its own and the+ * table needs no merge state. Runs after a page loads without an error.+ */+ mapRows?: (rows: TRow[], context: ListLoaderContext) => Promise<TOut[]>;+ /**+ * A failed first page redirects here with an error flash. Without it, the+ * page shows no rows. A failed later page never redirects: it returns+ * `listError`, and the Table shows "Couldn't load more rows" with Retry.+ */+ onError?: { redirectTo: string; message: string };+};++/**+ * The whole loader of a registered list:+ *+ * 1. `requirePermissions` with the list's permission (and `bypassRls`).+ * 2. `guard`, then `fetchListPage` for the URL's page (or `params`), with+ * the user's company group.+ * 3. `firstPage` extras on page 1 only, in parallel with the page;+ * `mapRows` on every page, after it.+ * 4. On an error: a later page returns `{ [dataKey]: [], nextCursor: null,+ * listError }`; page 1 redirects with `onError`, or shows no rows.+ *+ * A loader that does more (an early return, a flash without a redirect)+ * calls `fetchListPage` itself and returns `listErrorPage(dataKey)` for a+ * failed later page.+ *+ * ```ts+ * export async function loader({ request }: LoaderFunctionArgs) {+ * return loadListPage(request, customersList, {+ * dataKey: "customers",+ * bypassRls: true,+ * firstPage: async ({ client, companyId }) => ({+ * tags: (await getTagsList(client, companyId, "customer")).data ?? []+ * }),+ * onError: { redirectTo: path.to.sales, message: "Failed to fetch customers" }+ * });+ * }+ * ```+ *+ * The return type holds the extras: `useLoaderData` reads page 1, which has+ * them. Only the Table's fetcher reads a later page.+ */+export async function loadListPage<+ TRow extends Record<string, unknown>,+ TKey extends string,+ TExtra extends Record<string, unknown> = Record<never, never>,+ TOut = TRow+>(+ request: Request,+ list: ListDefinition<TRow>,+ options: LoadListPageOptions<TKey, TExtra, TRow, TOut>+): Promise<ListLoaderData<TKey, TOut> & TExtra> {+ const auth = await requirePermissions(+ request,+ options.bypassRls+ ? { ...list.permission, bypassRls: true }+ : list.permission+ );+ const requestParams = new URL(request.url).searchParams;+ const after = requestParams.get("after");+ const context: ListLoaderContext = {+ ...auth,+ request,+ params: requestParams+ };+ await options.guard?.(context);+ if (options.params) context.params = options.params(context);++ const [page, extra] = await Promise.all([+ fetchListPage(+ list,+ auth.client,+ auth.companyId,+ context.params,+ undefined,+ { companyGroupId: auth.companyGroupId }+ ),+ after ? undefined : options.firstPage?.(context)+ ]);++ if (page.error) {+ logger.error("Failed to load a page of the list {listKey}", {+ listKey: list.key,+ companyId: auth.companyId,+ laterPage: Boolean(after),+ error: page.error+ });+ if (after) return listErrorPage(options.dataKey);+ if (options.onError) {+ throw redirect(+ options.onError.redirectTo,+ await flash(request, error(page.error, options.onError.message))+ );+ }+ }++ const rows =+ options.mapRows && !page.error+ ? await options.mapRows(page.rows, context)+ : page.rows;++ return {+ ...extra,+ [options.dataKey]: rows,+ count: page.count,+ nextCursor: page.nextCursor+ } as ListLoaderData<TKey, TOut> & TExtra;+}diff --git a/apps/erp/app/utils/list-registry/people.server.ts b/apps/erp/app/utils/list-registry/people.server.tsnew file mode 100644index 0000000000..02bf74aaed--- /dev/null+++ b/apps/erp/app/utils/list-registry/people.server.ts@@ -0,0 +1,64 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ ATTRIBUTE_CATEGORIES_PAGING,+ getAttributeCategories,+ getHolidays,+ getPeople,+ getShifts,+ getTimecardEntries,+ HOLIDAYS_PAGING,+ SHIFTS_PAGING,+ TIMECARD_ENTRIES_PAGING+} from "~/modules/people";+import { EMPLOYEES_PAGING } from "~/modules/users/users.service";+import type { ListDefinition } from "./index.server";+import { searchList } from "./index.server";++// The people list searches with `?name=`, not `?search=`.+export const peopleList = searchList({+ key: "people",+ permission: { view: "people", role: "employee" },+ paging: EMPLOYEES_PAGING,+ service: getPeople,+ params: { search: "name" }+});++export const attributeCategoriesList = searchList({+ key: "attribute-categories",+ permission: { view: "people", role: "employee" },+ paging: ATTRIBUTE_CATEGORIES_PAGING,+ service: getAttributeCategories+});++export const holidaysList = searchList({+ key: "holidays",+ permission: { view: "people", role: "employee" },+ paging: HOLIDAYS_PAGING,+ service: getHolidays+});++export const shiftsList = searchList({+ key: "shifts",+ permission: { view: "people", role: "employee" },+ paging: SHIFTS_PAGING,+ service: getShifts+});++export const timecardEntriesList = searchList({+ key: "timecards",+ permission: { view: "people" },+ paging: TIMECARD_ENTRIES_PAGING,+ service: getTimecardEntries+});++// The people lists. Each entry follows `sales.server.ts`.+export const peopleLists: Record<string, ListDefinition> = {+ [peopleList.key]: peopleList,+ [attributeCategoriesList.key]: attributeCategoriesList,+ [holidaysList.key]: holidaysList,+ [shiftsList.key]: shiftsList,+ [timecardEntriesList.key]: timecardEntriesList+};diff --git a/apps/erp/app/utils/list-registry/production.server.ts b/apps/erp/app/utils/list-registry/production.server.tsnew file mode 100644index 0000000000..1fead5999b--- /dev/null+++ b/apps/erp/app/utils/list-registry/production.server.ts@@ -0,0 +1,142 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ ASSEMBLY_INSTRUCTIONS_PAGING,+ getAssemblyInstructionsPage,+ getJobOperationBatches,+ getJobs,+ getProcedures,+ getScrapReasons,+ JOB_OPERATION_BATCHES_PAGING,+ JOBS_PAGING,+ PROCEDURES_PAGING,+ SCRAP_REASONS_PAGING+} from "~/modules/production";+import { JOB_LIST_EXPORT_VALUES } from "~/modules/production/ui/Jobs/job-list-export";+import { withExportValues } from "./export-values";+import type { ListDefinition, ListRowsContext } from "./index.server";+import { searchList } from "./index.server";++/**+ * The live batches and the tracked entity of each job: the jobs view has+ * neither. The loader adds them to every page (`mapRows`); the background+ * export adds them through `exportRows`.+ */+export async function withJobListExtras<+ T extends { id: string | null; jobMakeMethodId: string | null }+>(jobs: T[], { client, companyId }: ListRowsContext) {+ const jobIds = jobs.map((job) => job.id!).filter(Boolean);+ const makeMethodIds = jobs+ .map((job) => job.jobMakeMethodId)+ .filter((id): id is string => !!id);+ const [batchedOps, trackedEntities] = await Promise.all([+ // The jobs view carries no batch column (batching is per operation),+ // so one lookup finds the live (Active/Completing) batches of each job.+ jobIds.length > 0+ ? client+ .from("jobOperation")+ .select("jobId, jobOperationBatch(id, readableId, status)")+ .in("jobId", jobIds)+ .eq("companyId", companyId)+ .not("jobOperationBatchId", "is", null)+ : { data: [] },+ makeMethodIds.length > 0+ ? client+ .from("trackedEntity")+ .select("readableId, attributes")+ .in("attributes->>Job Make Method", makeMethodIds)+ .eq("companyId", companyId)+ : { data: [] }+ ]);++ const batchesByJobId: Record<string, string[]> = {};+ for (const op of batchedOps.data ?? []) {+ const batch = op.jobOperationBatch;+ if (!batch || (batch.status !== "Active" && batch.status !== "Completing"))+ continue;+ if (!op.jobId || !batch.readableId) continue;+ const list = (batchesByJobId[op.jobId] ??= []);+ if (!list.includes(batch.readableId)) list.push(batch.readableId);+ }++ const trackedEntityByMakeMethodId: Record<string, string> = {};+ for (const entity of trackedEntities.data ?? []) {+ const makeMethodId = readJobMakeMethodId(entity.attributes);+ if (makeMethodId && entity.readableId) {+ trackedEntityByMakeMethodId[makeMethodId] = entity.readableId;+ }+ }++ return jobs.map((job) => ({+ ...job,+ batchReadableIds: (job.id && batchesByJobId[job.id]) || [],+ trackedEntityReadableId:+ (job.jobMakeMethodId &&+ trackedEntityByMakeMethodId[job.jobMakeMethodId]) ||+ null+ }));+}++function readJobMakeMethodId(attributes: unknown): string | null {+ if (!attributes || typeof attributes !== "object") return null;+ const value = (attributes as Record<string, unknown>)["Job Make Method"];+ return typeof value === "string" ? value : null;+}++export const jobsList = searchList({+ key: "jobs",+ permission: { view: "production", role: "employee" },+ paging: JOBS_PAGING,+ service: getJobs,+ exportRows: async (rows, context) =>+ withExportValues(+ await withJobListExtras(rows, context),+ JOB_LIST_EXPORT_VALUES+ )+});++export const assemblyInstructionsList = {+ key: "assembly-instructions",+ permission: { view: "production", role: "employee" },+ ...ASSEMBLY_INSTRUCTIONS_PAGING,+ query: (client, companyId, { params, limit, cursor, sorts, filters }) =>+ getAssemblyInstructionsPage(client, {+ companyId,+ search: params.get("search") ?? undefined,+ limit,+ cursor,+ sorts,+ filters+ })+} satisfies ListDefinition;++export const operationBatchesList = searchList({+ key: "operation-batches",+ permission: { view: "production", role: "employee" },+ paging: JOB_OPERATION_BATCHES_PAGING,+ service: getJobOperationBatches+});++export const proceduresList = searchList({+ key: "procedures",+ permission: { view: "production", role: "employee" },+ paging: PROCEDURES_PAGING,+ service: getProcedures+});++export const scrapReasonsList = searchList({+ key: "scrap-reasons",+ permission: { view: "production", role: "employee" },+ paging: SCRAP_REASONS_PAGING,+ service: getScrapReasons+});++export const productionLists: Record<string, ListDefinition> = {+ [jobsList.key]: jobsList,+ [assemblyInstructionsList.key]: assemblyInstructionsList,+ [operationBatchesList.key]: operationBatchesList,+ [proceduresList.key]: proceduresList,+ [scrapReasonsList.key]: scrapReasonsList+};diff --git a/apps/erp/app/utils/list-registry/purchasing.server.ts b/apps/erp/app/utils/list-registry/purchasing.server.tsnew file mode 100644index 0000000000..714a88fca5--- /dev/null+++ b/apps/erp/app/utils/list-registry/purchasing.server.ts@@ -0,0 +1,135 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { indexBy, indexByMapped, pluckUnique } from "@carbon/utils";+import type { SupplierReportContacts } from "~/modules/purchasing";+import {+ getLeases,+ getPurchaseOrders,+ getPurchaseReturnOrders,+ getPurchasingRFQs,+ getSupplierQuotes,+ getSupplierReportContacts,+ getSuppliers,+ getSupplierTypes,+ LEASES_PAGING,+ PURCHASE_ORDERS_PAGING,+ PURCHASE_RETURN_ORDERS_PAGING,+ PURCHASING_RFQS_PAGING,+ SUPPLIER_QUOTES_PAGING,+ SUPPLIER_TYPES_PAGING,+ SUPPLIERS_PAGING+} from "~/modules/purchasing";+import { SUPPLIER_CONTACT_VALUES } from "~/modules/purchasing/ui/Supplier/supplier-list-export";+import { withExportValues } from "./export-values";+import type { ListDefinition, ListRowsContext } from "./index.server";+import { searchList } from "./index.server";++// The purchasing lists. Each entry follows `sales.server.ts`.+// Material Planning (`purchasing+/planning`) is not registered: its query+// needs the location the loader resolves from the user's defaults.++export const purchaseOrdersList = searchList({+ key: "purchase-orders",+ permission: { view: "purchasing" },+ paging: PURCHASE_ORDERS_PAGING,+ service: getPurchaseOrders,+ params: { status: "status", supplierId: "supplierId" }+});++export const supplierQuotesList = searchList({+ key: "supplier-quotes",+ permission: { view: "purchasing" },+ paging: SUPPLIER_QUOTES_PAGING,+ service: getSupplierQuotes+});++export const purchasingRfqsList = searchList({+ key: "purchasing-rfqs",+ permission: { view: "purchasing" },+ paging: PURCHASING_RFQS_PAGING,+ service: getPurchasingRFQs+});++export const purchaseReturnOrdersList = searchList({+ key: "purchase-return-orders",+ permission: { view: "purchasing" },+ paging: PURCHASE_RETURN_ORDERS_PAGING,+ service: getPurchaseReturnOrders,+ params: { status: "status", supplierId: "supplierId" }+});++export const supplierTypesList = {+ key: "supplier-types",+ permission: { view: "purchasing", role: "employee" },+ ...SUPPLIER_TYPES_PAGING,+ // The list has no column filters: the loader never passed them.+ query: (client, companyId, { params, limit, cursor, sorts }) =>+ getSupplierTypes(client, companyId, {+ search: params.get("search"),+ limit,+ cursor,+ sorts+ })+} satisfies ListDefinition;++/**+ * The report contacts (purchasing, invoice, shipping) of each supplier: the+ * suppliers view has none. The loader adds them to every page (`mapRows`);+ * the background export adds them through `exportRows`.+ */+export async function withSupplierReportContacts<+ T extends { id: string | null }+>(suppliers: T[], { client, companyId }: ListRowsContext) {+ const supplierIds = pluckUnique(suppliers, (s) => s.id);+ const [purchasingRes, paymentRes, shippingRes] =+ await getSupplierReportContacts(client, companyId, supplierIds);++ const purchasingBySupplierId = indexByMapped(+ purchasingRes.data,+ (r) => r.id,+ (r) => r.purchasingContact+ );+ const paymentBySupplierId = indexBy(paymentRes.data, (r) => r.supplierId);+ const shippingBySupplierId = indexBy(shippingRes.data, (r) => r.supplierId);++ return suppliers.map((supplier) => {+ const reportContacts: SupplierReportContacts = {+ purchasingContact: purchasingBySupplierId.get(supplier.id!) ?? null,+ payment: paymentBySupplierId.get(supplier.id!) ?? null,+ shipping: shippingBySupplierId.get(supplier.id!) ?? null+ };+ return { ...supplier, reportContacts };+ });+}++export const suppliersList = searchList({+ key: "suppliers",+ permission: { view: "purchasing" },+ paging: SUPPLIERS_PAGING,+ service: getSuppliers,+ params: { type: "type", status: "status" },+ exportRows: async (rows, context) =>+ withExportValues(+ await withSupplierReportContacts(rows, context),+ SUPPLIER_CONTACT_VALUES+ )+});++export const leasesList = searchList({+ key: "leases",+ permission: { view: "purchasing" },+ paging: LEASES_PAGING,+ service: getLeases+});++export const purchasingLists: Record<string, ListDefinition> = {+ [purchaseOrdersList.key]: purchaseOrdersList,+ [supplierQuotesList.key]: supplierQuotesList,+ [purchasingRfqsList.key]: purchasingRfqsList,+ [purchaseReturnOrdersList.key]: purchaseReturnOrdersList,+ [supplierTypesList.key]: supplierTypesList,+ [suppliersList.key]: suppliersList,+ [leasesList.key]: leasesList+};diff --git a/apps/erp/app/utils/list-registry/quality.server.ts b/apps/erp/app/utils/list-registry/quality.server.tsnew file mode 100644index 0000000000..3d9404d567--- /dev/null+++ b/apps/erp/app/utils/list-registry/quality.server.ts@@ -0,0 +1,135 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ GAUGE_CALIBRATION_RECORDS_PAGING,+ GAUGE_TYPES_PAGING,+ GAUGES_PAGING,+ getGaugeCalibrationRecords,+ getGauges,+ getGaugeTypes,+ getInspectionDocuments,+ getInspections,+ getIssues,+ getIssueTypes,+ getIssueWorkflows,+ getQualityActions,+ getQualityDocuments,+ getRequiredActions,+ getRisks,+ INSPECTION_DOCUMENTS_PAGING,+ INSPECTIONS_PAGING,+ ISSUE_TYPES_PAGING,+ ISSUE_WORKFLOWS_PAGING,+ ISSUES_PAGING,+ QUALITY_ACTIONS_PAGING,+ QUALITY_DOCUMENTS_PAGING,+ REQUIRED_ACTIONS_PAGING,+ RISKS_PAGING+} from "~/modules/quality";+import type { ListDefinition } from "./index.server";+import { searchList } from "./index.server";++// The quality loaders do not bypass RLS, so their lists keep the RLS client+// and `role: "employee"`.++export const issuesList = searchList({+ key: "issues",+ permission: { view: "quality", role: "employee" },+ paging: ISSUES_PAGING,+ service: getIssues+});++export const qualityActionsList = searchList({+ key: "quality-actions",+ permission: { view: "quality", role: "employee" },+ paging: QUALITY_ACTIONS_PAGING,+ service: getQualityActions+});++export const gaugeCalibrationRecordsList = searchList({+ key: "gauge-calibration-records",+ permission: { view: "quality", role: "employee" },+ paging: GAUGE_CALIBRATION_RECORDS_PAGING,+ service: getGaugeCalibrationRecords+});++export const qualityDocumentsList = searchList({+ key: "quality-documents",+ permission: { view: "quality", role: "employee" },+ paging: QUALITY_DOCUMENTS_PAGING,+ service: getQualityDocuments+});++export const gaugesList = searchList({+ key: "gauges",+ permission: { view: "quality", role: "employee" },+ paging: GAUGES_PAGING,+ service: getGauges+});++export const gaugeTypesList = searchList({+ key: "gauge-types",+ permission: { view: "quality", role: "employee" },+ paging: GAUGE_TYPES_PAGING,+ service: getGaugeTypes+});++export const inspectionPlansList = searchList({+ key: "inspection-plans",+ permission: { view: "quality", role: "employee" },+ paging: INSPECTION_DOCUMENTS_PAGING,+ service: getInspectionDocuments+});++export const inspectionsList = searchList({+ key: "inspections",+ permission: { view: "quality", role: "employee" },+ paging: INSPECTIONS_PAGING,+ service: getInspections,+ params: { status: "status", source: "source" }+});++export const issueTypesList = searchList({+ key: "issue-types",+ permission: { view: "quality", role: "employee" },+ paging: ISSUE_TYPES_PAGING,+ service: getIssueTypes+});++export const issueWorkflowsList = searchList({+ key: "issue-workflows",+ permission: { view: "quality", role: "employee" },+ paging: ISSUE_WORKFLOWS_PAGING,+ service: getIssueWorkflows+});++export const requiredActionsList = searchList({+ key: "required-actions",+ permission: { view: "quality", role: "employee" },+ paging: REQUIRED_ACTIONS_PAGING,+ service: getRequiredActions+});++export const risksList = searchList({+ key: "risks",+ permission: { view: "quality", role: "employee" },+ paging: RISKS_PAGING,+ service: getRisks+});++export const qualityLists: Record<string, ListDefinition> = {+ [issuesList.key]: issuesList,+ [qualityActionsList.key]: qualityActionsList,+ [gaugeCalibrationRecordsList.key]: gaugeCalibrationRecordsList,+ [qualityDocumentsList.key]: qualityDocumentsList,+ [gaugesList.key]: gaugesList,+ [gaugeTypesList.key]: gaugeTypesList,+ [inspectionPlansList.key]: inspectionPlansList,+ [inspectionsList.key]: inspectionsList,+ [issueTypesList.key]: issueTypesList,+ [issueWorkflowsList.key]: issueWorkflowsList,+ [requiredActionsList.key]: requiredActionsList,+ [risksList.key]: risksList+};diff --git a/apps/erp/app/utils/list-registry/registry.test.ts b/apps/erp/app/utils/list-registry/registry.test.tsnew file mode 100644index 0000000000..975eb5f57f--- /dev/null+++ b/apps/erp/app/utils/list-registry/registry.test.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { readdirSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++/**+ * The registry's module files import the module barrels, which cannot load in+ * a unit test, so this test reads the files as text.+ */++const DIR = __dirname;+const moduleFiles = readdirSync(DIR).filter(+ (file) =>+ file.endsWith(".server.ts") &&+ file !== "index.server.ts" &&+ file !== "load.server.ts"+);+const index = readFileSync(join(DIR, "index.server.ts"), "utf8");++describe("list registry files", () => {+ // The module files are merged with spreads, so a key in two files would+ // silently drop one list.+ it("uses each list key once", () => {+ const seen = new Map<string, string>();+ for (const file of moduleFiles) {+ const source = readFileSync(join(DIR, file), "utf8");+ for (const match of source.matchAll(/^\s+key: "([^"]+)",$/gm)) {+ const key = match[1];+ expect(seen.get(key), `"${key}" in ${file}`).toBeUndefined();+ seen.set(key, file);+ }+ }+ expect(seen.has("sales-orders")).toBe(true);+ });++ it("merges every module file into the registry", () => {+ for (const file of moduleFiles) {+ const name = `${file.replace(".server.ts", "")}Lists`;+ expect(index, `${name} from ${file}`).toContain(`...${name}`);+ }+ });+});diff --git a/apps/erp/app/utils/list-registry/resources.server.ts b/apps/erp/app/utils/list-registry/resources.server.tsnew file mode 100644index 0000000000..4bb7d0eaa3--- /dev/null+++ b/apps/erp/app/utils/list-registry/resources.server.ts@@ -0,0 +1,167 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";+import {+ ABILITIES_PAGING,+ CONTRACTORS_PAGING,+ FAILURE_MODES_PAGING,+ getAbilities,+ getContractors,+ getFailureModes,+ getLocations,+ getLocationsList,+ getMaintenanceDispatchesByLocation,+ getMaintenanceSchedulesByLocation,+ getProcesses,+ getSuggestions,+ getTrainings,+ getWorkCenters,+ LOCATIONS_PAGING,+ MAINTENANCE_DISPATCHES_PAGING,+ MAINTENANCE_SCHEDULES_PAGING,+ PROCESSES_PAGING,+ SUGGESTIONS_PAGING,+ TRAININGS_PAGING,+ WORK_CENTERS_PAGING+} from "~/modules/resources/resources.service";+import type { ListDefinition } from "./index.server";+import { searchList } from "./index.server";++/**+ * The maintenance lists show one location: `?location=`, else the company's+ * first location. Null when the company has no location.+ */+export async function resolveMaintenanceLocationId(+ client: SupabaseClient<Database>,+ companyId: string,+ params: URLSearchParams+) {+ const locationId = params.get("location");+ if (locationId) return locationId;+ const locations = await getLocationsList(client, companyId);+ return locations.data?.[0]?.id ?? null;+}++export const abilitiesList = searchList({+ key: "abilities",+ permission: { view: "resources", role: "employee" },+ paging: ABILITIES_PAGING,+ service: getAbilities+});++export const failureModesList = searchList({+ key: "failure-modes",+ permission: { view: "resources", role: "employee" },+ paging: FAILURE_MODES_PAGING,+ service: getFailureModes+});++export const locationsList = searchList({+ key: "locations",+ permission: { view: "resources", role: "employee" },+ paging: LOCATIONS_PAGING,+ service: getLocations+});++export const maintenanceDispatchesList = {+ key: "maintenance-dispatches",+ permission: { view: "resources", role: "employee" },+ ...MAINTENANCE_DISPATCHES_PAGING,+ query: async (+ client,+ companyId,+ { params, limit, cursor, sorts, filters }+ ) => {+ const locationId = await resolveMaintenanceLocationId(+ client,+ companyId,+ params+ );+ if (!locationId) return { data: [], error: null, count: 0 };+ return getMaintenanceDispatchesByLocation(client, companyId, locationId, {+ search: params.get("search"),+ status: params.get("status") ?? undefined,+ limit,+ cursor,+ sorts,+ filters+ });+ }+} satisfies ListDefinition;++export const maintenanceSchedulesList = {+ key: "maintenance-schedules",+ permission: { view: "resources", role: "employee" },+ ...MAINTENANCE_SCHEDULES_PAGING,+ query: async (+ client,+ companyId,+ { params, limit, cursor, sorts, filters }+ ) => {+ const locationId = await resolveMaintenanceLocationId(+ client,+ companyId,+ params+ );+ if (!locationId) return { data: [], error: null, count: 0 };+ return getMaintenanceSchedulesByLocation(client, companyId, locationId, {+ search: params.get("search"),+ limit,+ cursor,+ sorts,+ filters+ });+ }+} satisfies ListDefinition;++export const processesList = searchList({+ key: "processes",+ permission: { view: "resources", role: "employee" },+ paging: PROCESSES_PAGING,+ service: getProcesses+});++export const suggestionsList = searchList({+ key: "suggestions",+ permission: { view: "resources", role: "employee" },+ paging: SUGGESTIONS_PAGING,+ service: getSuggestions+});++export const trainingsList = searchList({+ key: "trainings",+ permission: { view: "resources", role: "employee" },+ paging: TRAININGS_PAGING,+ service: getTrainings+});++export const workCentersList = searchList({+ key: "work-centers",+ permission: { view: "resources", role: "employee" },+ paging: WORK_CENTERS_PAGING,+ service: getWorkCenters+});++export const contractorsList = searchList({+ key: "contractors",+ permission: { view: "resources", role: "employee" },+ paging: CONTRACTORS_PAGING,+ service: getContractors+});++// The resources lists. Each entry follows `sales.server.ts`.+export const resourcesLists: Record<string, ListDefinition> = {+ [abilitiesList.key]: abilitiesList,+ [contractorsList.key]: contractorsList,+ [failureModesList.key]: failureModesList,+ [locationsList.key]: locationsList,+ [maintenanceDispatchesList.key]: maintenanceDispatchesList,+ [maintenanceSchedulesList.key]: maintenanceSchedulesList,+ [processesList.key]: processesList,+ [suggestionsList.key]: suggestionsList,+ [trainingsList.key]: trainingsList,+ [workCentersList.key]: workCentersList+};diff --git a/apps/erp/app/utils/list-registry/sales.server.ts b/apps/erp/app/utils/list-registry/sales.server.tsnew file mode 100644index 0000000000..3537aa851c--- /dev/null+++ b/apps/erp/app/utils/list-registry/sales.server.ts@@ -0,0 +1,189 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ CONTRACTS_PAGING,+ CUSTOMER_STATUSES_PAGING,+ CUSTOMER_TYPES_PAGING,+ CUSTOMERS_PAGING,+ getBaseCatalog,+ getContracts,+ getCustomerStatuses,+ getCustomers,+ getCustomerTypes,+ getNoQuoteReasons,+ getPricingRules,+ getQuotes,+ getRentalAgreements,+ getReturnReasons,+ getSalesOrders,+ getSalesReturnOrders,+ getSalesRFQs,+ NO_QUOTE_REASONS_PAGING,+ PRICE_LIST_PAGING,+ PRICING_RULES_PAGING,+ QUOTES_PAGING,+ RENTAL_AGREEMENTS_PAGING,+ RETURN_REASONS_PAGING,+ resolvePriceList,+ SALES_ORDERS_PAGING,+ SALES_RETURN_ORDERS_PAGING,+ SALES_RFQS_PAGING+} from "~/modules/sales";+import { CUSTOMER_PORTALS_PAGING, getCustomerPortals } from "~/modules/shared";+import type { ListDefinition } from "./index.server";+import { searchList } from "./index.server";++export const salesOrdersList = searchList({+ key: "sales-orders",+ permission: { view: "sales" },+ paging: SALES_ORDERS_PAGING,+ service: getSalesOrders,+ params: { status: "status", customerId: "customerId" }+});++export const quotesList = searchList({+ key: "quotes",+ permission: { view: "sales" },+ paging: QUOTES_PAGING,+ service: getQuotes+});++export const salesRfqsList = searchList({+ key: "sales-rfqs",+ permission: { view: "sales" },+ paging: SALES_RFQS_PAGING,+ service: getSalesRFQs+});++export const salesReturnOrdersList = searchList({+ key: "sales-return-orders",+ permission: { view: "sales" },+ paging: SALES_RETURN_ORDERS_PAGING,+ service: getSalesReturnOrders,+ params: { status: "status", customerId: "customerId" }+});++export const customersList = searchList({+ key: "customers",+ permission: { view: "sales" },+ paging: CUSTOMERS_PAGING,+ service: getCustomers+});++export const contractsList = searchList({+ key: "contracts",+ permission: { view: "sales" },+ paging: CONTRACTS_PAGING,+ service: getContracts+});++export const rentalAgreementsList = searchList({+ key: "rental-agreements",+ permission: { view: "sales" },+ paging: RENTAL_AGREEMENTS_PAGING,+ service: getRentalAgreements+});++// With a customer or a customer type in the URL, the list resolves that+// scope's prices; without one, it shows the base catalog.+export const priceListList = {+ key: "price-list",+ permission: { view: "sales", role: "employee" },+ ...PRICE_LIST_PAGING,+ query: async (+ client,+ companyId,+ { params, limit, cursor, sorts, filters }+ ) => {+ const search = params.get("search") ?? undefined;+ const customerId = params.get("customerId") ?? undefined;+ const customerTypeId = params.get("customerTypeId") ?? undefined;+ const rawQuantity = Number(params.get("quantity") ?? "1");+ const quantity =+ Number.isFinite(rawQuantity) && rawQuantity >= 0 ? rawQuantity : 1;++ const result =+ customerId || customerTypeId+ ? await resolvePriceList(client, companyId, {+ customerId,+ customerTypeId,+ quantity,+ search,+ limit,+ cursor,+ sorts,+ filters+ })+ : await getBaseCatalog(client, companyId, {+ search,+ limit,+ cursor,+ sorts,+ filters+ });++ return { ...result, error: null };+ }+} satisfies ListDefinition;++export const pricingRulesList = searchList({+ key: "pricing-rules",+ permission: { view: "sales", role: "employee" },+ paging: PRICING_RULES_PAGING,+ service: getPricingRules,+ params: { search: (params) => params.get("search") ?? undefined }+});++export const customerPortalsList = searchList({+ key: "customer-portals",+ permission: { view: "sales", role: "employee" },+ paging: CUSTOMER_PORTALS_PAGING,+ service: getCustomerPortals+});++export const customerStatusesList = searchList({+ key: "customer-statuses",+ permission: { view: "sales", role: "employee" },+ paging: CUSTOMER_STATUSES_PAGING,+ service: getCustomerStatuses+});++export const customerTypesList = searchList({+ key: "customer-types",+ permission: { view: "sales", role: "employee" },+ paging: CUSTOMER_TYPES_PAGING,+ service: getCustomerTypes+});++export const noQuoteReasonsList = searchList({+ key: "no-quote-reasons",+ permission: { view: "sales", role: "employee" },+ paging: NO_QUOTE_REASONS_PAGING,+ service: getNoQuoteReasons+});++export const returnReasonsList = searchList({+ key: "return-reasons",+ permission: { view: "sales", role: "employee" },+ paging: RETURN_REASONS_PAGING,+ service: getReturnReasons+});++export const salesLists: Record<string, ListDefinition> = {+ [salesOrdersList.key]: salesOrdersList,+ [quotesList.key]: quotesList,+ [salesRfqsList.key]: salesRfqsList,+ [salesReturnOrdersList.key]: salesReturnOrdersList,+ [customersList.key]: customersList,+ [contractsList.key]: contractsList,+ [rentalAgreementsList.key]: rentalAgreementsList,+ [priceListList.key]: priceListList,+ [pricingRulesList.key]: pricingRulesList,+ [customerPortalsList.key]: customerPortalsList,+ [customerStatusesList.key]: customerStatusesList,+ [customerTypesList.key]: customerTypesList,+ [noQuoteReasonsList.key]: noQuoteReasonsList,+ [returnReasonsList.key]: returnReasonsList+};diff --git a/apps/erp/app/utils/list-registry/settings.server.ts b/apps/erp/app/utils/list-registry/settings.server.tsnew file mode 100644index 0000000000..ee64d5f41b--- /dev/null+++ b/apps/erp/app/utils/list-registry/settings.server.ts@@ -0,0 +1,79 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ API_KEYS_PAGING,+ CUSTOM_FIELD_TABLES_PAGING,+ getApiKeys,+ getCustomFieldsTables,+ getItemSerialSequences,+ getSequences,+ getWebhooks,+ ITEM_SERIAL_SEQUENCES_PAGING,+ SEQUENCES_PAGING,+ WEBHOOKS_PAGING+} from "~/modules/settings/settings.service";+import type { ListDefinition } from "./index.server";+import { searchList } from "./index.server";++export const apiKeysList = {+ key: "api-keys",+ permission: { update: "users" },+ ...API_KEYS_PAGING,+ // The key hash never leaves the server: not to the page, not to an export.+ query: async (+ client,+ companyId,+ { params, limit, cursor, sorts, filters }+ ) => {+ const result = await getApiKeys(client, companyId, {+ search: params.get("search"),+ limit,+ cursor,+ sorts,+ filters+ });+ return {+ ...result,+ data: result.data?.map(({ keyHash: _keyHash, ...rest }) => rest) ?? null+ };+ }+} satisfies ListDefinition;++export const sequencesList = searchList({+ key: "sequences",+ permission: { view: "settings", role: "employee" },+ paging: SEQUENCES_PAGING,+ service: getSequences+});++export const itemSerialSequencesList = searchList({+ key: "serial-numbers",+ permission: { view: "settings", role: "employee" },+ paging: ITEM_SERIAL_SEQUENCES_PAGING,+ service: getItemSerialSequences+});++export const webhooksList = searchList({+ key: "webhooks",+ permission: { view: "settings" },+ paging: WEBHOOKS_PAGING,+ service: getWebhooks+});++// The settings lists. Each entry follows `sales.server.ts`.+export const customFieldTablesList = searchList({+ key: "custom-field-tables",+ permission: { view: "settings", role: "employee" },+ paging: CUSTOM_FIELD_TABLES_PAGING,+ service: getCustomFieldsTables+});++export const settingsLists: Record<string, ListDefinition> = {+ [apiKeysList.key]: apiKeysList,+ [customFieldTablesList.key]: customFieldTablesList,+ [sequencesList.key]: sequencesList,+ [itemSerialSequencesList.key]: itemSerialSequencesList,+ [webhooksList.key]: webhooksList+};diff --git a/apps/erp/app/utils/list-registry/users.server.ts b/apps/erp/app/utils/list-registry/users.server.tsnew file mode 100644index 0000000000..11444df531--- /dev/null+++ b/apps/erp/app/utils/list-registry/users.server.ts@@ -0,0 +1,42 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ CONSOLE_OPERATORS_PAGING,+ EMPLOYEE_TYPES_PAGING,+ EMPLOYEES_PAGING,+ getConsoleOperators,+ getEmployees,+ getEmployeeTypes+} from "~/modules/users/users.service";+import type { ListDefinition } from "./index.server";+import { searchList } from "./index.server";++export const employeeAccountsList = searchList({+ key: "employee-accounts",+ permission: { view: "users", role: "employee" },+ paging: EMPLOYEES_PAGING,+ service: getEmployees+});++export const employeeTypesList = searchList({+ key: "employee-types",+ permission: { view: "users", role: "employee" },+ paging: EMPLOYEE_TYPES_PAGING,+ service: getEmployeeTypes+});++export const consoleOperatorsList = searchList({+ key: "console-operators",+ permission: { view: "users", role: "employee" },+ paging: CONSOLE_OPERATORS_PAGING,+ service: getConsoleOperators+});++// The users lists. Each entry follows `sales.server.ts`.+export const usersLists: Record<string, ListDefinition> = {+ [employeeAccountsList.key]: employeeAccountsList,+ [employeeTypesList.key]: employeeTypesList,+ [consoleOperatorsList.key]: consoleOperatorsList+};diff --git a/apps/erp/app/utils/list-registry/workflows.server.ts b/apps/erp/app/utils/list-registry/workflows.server.tsnew file mode 100644index 0000000000..b0e37b3ce6--- /dev/null+++ b/apps/erp/app/utils/list-registry/workflows.server.ts@@ -0,0 +1,80 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { WorkflowLastRun } from "~/modules/workflows";+import {+ getWorkflowLastRuns,+ getWorkflowRuns,+ getWorkflows,+ getWorkflowVersionNumbers,+ WORKFLOW_RUNS_PAGING,+ WORKFLOWS_PAGING+} from "~/modules/workflows";+import { WORKFLOW_LIST_EXPORT_VALUES } from "~/modules/workflows/ui/workflow-list-export";+import { withExportValues } from "./export-values";+import type { ListDefinition, ListRowsContext } from "./index.server";+import { searchList } from "./index.server";++/**+ * The published version number and the last run of each workflow. The loader+ * adds them to every page (`mapRows`); the background export adds them+ * through `exportRows`.+ */+export async function withWorkflowListExtras<+ T extends { id: string; publishedVersionId: string | null }+>(rows: T[], { client, companyId }: ListRowsContext) {+ const publishedVersionIds = rows+ .map((row) => row.publishedVersionId)+ .filter((id): id is string => id !== null);+ const workflowIds = rows.map((row) => row.id);+ const [versions, runs] = await Promise.all([+ publishedVersionIds.length+ ? getWorkflowVersionNumbers(client, publishedVersionIds, companyId)+ : null,+ workflowIds.length+ ? getWorkflowLastRuns(client, workflowIds, companyId)+ : null+ ]);++ const versionNumbers = new Map(+ (versions?.data ?? []).map((version) => [version.id, version.versionNumber])+ );+ const lastRuns = new Map<string, WorkflowLastRun>();+ for (const run of runs?.data ?? []) {+ if (run.workflowId) lastRuns.set(run.workflowId, run);+ }++ return rows.map((row) => ({+ ...row,+ publishedVersionNumber: row.publishedVersionId+ ? (versionNumbers.get(row.publishedVersionId) ?? null)+ : null,+ lastRun: lastRuns.get(row.id) ?? null+ }));+}++export const workflowsList = searchList({+ key: "workflows",+ permission: { view: "workflows", role: "employee" },+ paging: WORKFLOWS_PAGING,+ service: getWorkflows,+ exportRows: async (rows, context) =>+ withExportValues(+ await withWorkflowListExtras(rows, context),+ WORKFLOW_LIST_EXPORT_VALUES+ )+});++export const workflowRunsList = searchList({+ key: "workflow-runs",+ permission: { view: "workflows", role: "employee" },+ paging: WORKFLOW_RUNS_PAGING,+ service: getWorkflowRuns+});++// The workflows lists. Each entry follows `sales.server.ts`.+export const workflowsLists: Record<string, ListDefinition> = {+ [workflowsList.key]: workflowsList,+ [workflowRunsList.key]: workflowRunsList+};diff --git a/apps/erp/app/utils/notification-target.ts b/apps/erp/app/utils/notification-target.tsnew file mode 100644index 0000000000..60c0c249c9--- /dev/null+++ b/apps/erp/app/utils/notification-target.ts@@ -0,0 +1,165 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Database } from "@carbon/database";+import {+ NotificationEvent,+ type RecurringInvoicingDocumentType+} from "@carbon/notifications";+import { getRecordPath } from "./entity";+import { path } from "./path";++type ApprovalDocumentType = Database["public"]["Enums"]["approvalDocumentType"];++/** The approvable document of an Approval* event, the record type of a+ * Workflow notification, or what a Recurring invoicing notification lists. */+export type NotificationDocumentType =+ | ApprovalDocumentType+ | RecurringInvoicingDocumentType+ | (string & {});++export type NotificationTarget = {+ /** Where the notification leads. */+ path: string;+ /** A file download: a resource route that needs a full page request. */+ download: boolean;+};++const page = (to: string): NotificationTarget => ({+ path: to,+ download: false+});++/**+ * Where a notification leads, for the topbar row and for the email link+ * (`api+/link.ts`), so the two never disagree. Null when the notification+ * names no page (the caller lands on the home page).+ */+export function notificationTarget(+ event: NotificationEvent,+ documentId: string,+ documentType?: NotificationDocumentType | null+): NotificationTarget | null {+ switch (event) {+ case NotificationEvent.ApprovalApproved:+ case NotificationEvent.ApprovalRejected:+ case NotificationEvent.ApprovalRequested:+ // Approvals started with purchase orders, so a notification without a+ // document type is one.+ return page(+ documentType === "qualityDocument"+ ? path.to.qualityDocument(documentId)+ : documentType === "supplier"+ ? path.to.supplier(documentId)+ : documentType === "changeOrder"+ ? path.to.changeNoticeDetails(documentId)+ : path.to.purchaseOrderDetails(documentId)+ );+ case NotificationEvent.ChangeNoticeStarted:+ case NotificationEvent.ChangeNoticeImplementation:+ case NotificationEvent.ChangeNoticeDone:+ return page(path.to.changeNoticeDetails(documentId));+ case NotificationEvent.DigitalQuoteResponse:+ case NotificationEvent.QuoteAssignment:+ case NotificationEvent.QuoteExpired:+ return page(path.to.quoteDetails(documentId));+ case NotificationEvent.GaugeCalibrationExpired:+ return page(path.to.gauge(documentId));+ case NotificationEvent.SalesRuleViolation: {+ // Compound documentId: "<quote|salesOrder|salesInvoice>:<documentId>:<outcome>"+ const [docType, docId] = documentId.split(":");+ if (!docId) return null;+ return page(+ docType === "salesInvoice"+ ? path.to.salesInvoiceDetails(docId)+ : docType === "salesOrder"+ ? path.to.salesOrderDetails(docId)+ : path.to.quoteDetails(docId)+ );+ }+ case NotificationEvent.IntegrationSync:+ // documentId is the provider id ("rillet", "xero", …): its settings+ // page, where the Sync Activity tab lives.+ return page(path.to.integration(documentId));+ case NotificationEvent.TableExport:+ // documentId is the export id; `failed:{exportId}` has no file. The+ // export route serves the file to the user who asked for it only.+ return documentId.startsWith("failed:")+ ? null+ : {+ path: `${path.to.api.tableExport}/${encodeURIComponent(documentId)}`,+ download: true+ };+ case NotificationEvent.TableBulkAction:+ // documentId is the run id, not a record; the title has the counts.+ return null;+ case NotificationEvent.RecurringInvoicing:+ // documentId is only the digest's first invoice: land on the list it is+ // about, the lease drafts waiting for the buyer, else the sales invoices+ // that need review.+ return page(+ documentType === "purchaseInvoice"+ ? `${path.to.invoicingPurchasing}?filter=status:eq:Draft`+ : `${path.to.invoicingSales}?filter=needsReview:eq:true`+ );+ case NotificationEvent.LeaseCriticalDate:+ return page(path.to.leaseDetails(documentId));+ case NotificationEvent.JobAssignment:+ case NotificationEvent.JobCompleted:+ case NotificationEvent.JobsProjectedLate:+ return page(path.to.jobDetails(documentId));+ case NotificationEvent.JobOperationAssignment:+ case NotificationEvent.JobOperationMessage: {+ const [jobId, operationId, makeMethodId, materialId] =+ documentId.split(":");+ if (!jobId || !operationId || !makeMethodId) return null;+ const link = materialId+ ? path.to.jobMakeMethod(jobId, makeMethodId)+ : path.to.jobMethod(jobId, makeMethodId);+ return page(`${link}?selectedOperation=${operationId}`);+ }+ case NotificationEvent.MaintenanceDispatchAssignment:+ case NotificationEvent.MaintenanceDispatchCreated:+ return page(path.to.maintenanceDispatch(documentId));+ case NotificationEvent.NonConformanceAssignment:+ return page(path.to.issue(documentId));+ case NotificationEvent.ProcedureAssignment:+ return page(path.to.procedure(documentId));+ case NotificationEvent.PurchaseInvoiceAssignment:+ return page(path.to.purchaseInvoiceDetails(documentId));+ case NotificationEvent.PurchaseOrderAssignment:+ return page(path.to.purchaseOrderDetails(documentId));+ case NotificationEvent.PurchasingRfqAssignment:+ return page(path.to.purchasingRfq(documentId));+ case NotificationEvent.RiskAssignment:+ return page(path.to.risk(documentId));+ case NotificationEvent.SalesRfqAssignment:+ case NotificationEvent.SalesRfqReady:+ return page(path.to.salesRfq(documentId));+ case NotificationEvent.SalesOrderAssignment:+ return page(path.to.salesOrderDetails(documentId));+ case NotificationEvent.StockTransferAssignment:+ return page(path.to.stockTransfer(documentId));+ case NotificationEvent.PickingListAssignment:+ return page(path.to.pickingList(documentId));+ case NotificationEvent.SuggestionResponse:+ return page(path.to.suggestion(documentId));+ case NotificationEvent.SupplierQuoteAssignment:+ case NotificationEvent.SupplierQuoteResponse:+ return page(path.to.supplierQuoteDetails(documentId));+ case NotificationEvent.TrainingAssignment:+ case NotificationEvent.TrainingReminder:+ // documentId is a trainingAssignment id; the recipient is the trainee.+ return page(path.to.completeTrainingAssignment(documentId));+ case NotificationEvent.ResourceTrainingAssignment:+ // documentId is a training id: the training viewer.+ return page(path.to.training(documentId));+ case NotificationEvent.Workflow: {+ const to = getRecordPath(documentType, documentId);+ return to ? page(to) : null;+ }+ default:+ return null;+ }+}diff --git a/apps/erp/app/utils/pagination.test.ts b/apps/erp/app/utils/pagination.test.tsdeleted file mode 100644index 66527b05b0..0000000000--- a/apps/erp/app/utils/pagination.test.ts+++ /dev/null@@ -1,28 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { describe, expect, it, vi } from "vitest";--// The @carbon/auth barrel does not load under vitest.-vi.mock("@carbon/auth", () => ({ parseNumberFromUrlParam: vi.fn() }));--const { pageBounds } = await import("./pagination");--describe("pageBounds", () => {- const page = (count: number, offset: number, rowsOnPage: number) =>- pageBounds({ count, offset, pageSize: 100, rowsOnPage });-- it("ends on a short page or where an exact count says the list stops", () => {- expect(page(5000, 300, 20).canNextPage).toBe(false);- expect(page(200, 100, 100).canNextPage).toBe(false);- });-- it("does not trust an estimate that equals the rows seen", () => {- expect(page(1500, 1400, 100).canNextPage).toBe(true);- });-- it("keeps going past a low estimate while pages come back full", () => {- expect(page(300, 300, 100)).toEqual({ canNextPage: true, count: 400 });- });-});diff --git a/apps/erp/app/utils/pagination.ts b/apps/erp/app/utils/pagination.tsindex 7ed594034a..509437eef7 100644--- a/apps/erp/app/utils/pagination.ts+++ b/apps/erp/app/utils/pagination.ts@@ -2,39 +2,11 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { parseNumberFromUrlParam } from "@carbon/auth";--export const PAGE_SIZES = [20, 100, 500, 1000];-export const DEFAULT_PAGE_SIZE = 100;-export const MAX_PAGE_SIZE = PAGE_SIZES[PAGE_SIZES.length - 1];--// Snap ?limit= onto the page-size options so a hand-typed value can't dump every row on one page.-export function getPageSize(params: URLSearchParams): number {- const limit = parseNumberFromUrlParam(params, "limit", DEFAULT_PAGE_SIZE);- if (!Number.isFinite(limit) || limit < 1) return DEFAULT_PAGE_SIZE;- return PAGE_SIZES.find((size) => size >= limit) ?? MAX_PAGE_SIZE;-}--export function getPageOffset(params: URLSearchParams): number {- return Math.max(0, parseNumberFromUrlParam(params, "offset", 0));-}--// PostgREST's `estimated` count is exact up to max-rows (config.toml) and a-// planner estimate above it.-const MAX_EXACT_COUNT = 1000;--// An estimate can run low, so past the exact range the rows returned decide-// whether a next page exists.-export function pageBounds(args: {- count: number;- offset: number;- pageSize: number;- rowsOnPage: number;-}) {- const seen = args.offset + args.rowsOnPage;- const atExactEnd = args.count <= MAX_EXACT_COUNT && seen === args.count;- return {- canNextPage: args.rowsOnPage >= args.pageSize && !atExactEnd,- count: Math.max(args.count, seen)- };-}+// Rows per cursor page (infinite scroll). Below PostgREST's max_rows of 1000.+export const PAGE_SIZE = 100;++// Rows a single-load list (one that cannot page: a tree, a list with no unique+// id, a sort on a joined table) reads at once, by offset: `.range(0, 999)`.+// It is PostgREST's max_rows, so a list that gets exactly this many may have+// more, and its table says so (`<Table isTruncated>`).+export const SINGLE_LOAD_LIMIT = 1000;diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 8adb6c3595..60dc2544ac 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -159,6 +159,11 @@ export const path = {),inspectionDocuments: (itemId: string) =>generatePath(`${api}/quality/inspection-documents/${itemId}`),+ // The Sync Activity pages after the first; the tab adds `after`.+ integrationSyncActivity: (id: string, status?: string | null) =>+ `${generatePath(`${api}/integrations/${id}/sync-activity`)}${+ status ? `?${new URLSearchParams({ status })}` : ""+ }`,integrationSyncActivityCsv: (id: string, status?: string | null) =>`${generatePath(`${api}/integrations/${id}/sync-activity.csv`)}${status ? `?${new URLSearchParams({ status })}` : ""@@ -371,6 +376,7 @@ export const path = {supplierProcesses: (id: string) =>generatePath(`${api}/purchasing/supplier-processes/${id}`),supplierTypes: `${api}/purchasing/supplier-types`,+ tableExport: `${api}/table/export`,tags: (table?: string) =>generatePath(`${api}/shared/tags?table=${table}`),timecard: `${api}/people/timecard`,diff --git a/apps/erp/app/utils/query.test.ts b/apps/erp/app/utils/query.test.tsindex 2fce7784a3..fcfc072730 100644--- a/apps/erp/app/utils/query.test.ts+++ b/apps/erp/app/utils/query.test.ts@@ -14,12 +14,15 @@ vi.mock("@carbon/auth", () => ({parseNumberFromUrlParam: vi.fn()}));+const { encodeCursor } = await import("./cursor");const {formatRangeFilter,+ getEffectiveSorts,getGenericFilter,getGenericQueryFilters,getSearchTokens,parseRangeFilter,+ setGenericQueryFilters,setSearchFilter} = await import("./query");@@ -138,6 +141,131 @@ describe("between filter", () => {});});+describe("cursor paging params", () => {+ it("reads the cursor from ?after= and fixes the page size", () => {+ const cursor = { values: ["Bolt"], id: "it_1", keys: ["name:asc"] };+ const params = new URLSearchParams({ after: encodeCursor(cursor) });+ // ?limit= and ?offset= from old bookmarks are ignored.+ params.set("limit", "1000");+ params.set("offset", "500");++ expect(getGenericQueryFilters(params)).toMatchObject({+ limit: 100,+ cursor+ });+ });++ it("starts from the first page without ?after= or with a bad token", () => {+ expect(getGenericQueryFilters(new URLSearchParams()).cursor).toBeNull();+ expect(+ getGenericQueryFilters(new URLSearchParams({ after: "garbage" })).cursor+ ).toBeNull();+ });+});++describe("getEffectiveSorts", () => {+ const defaults = [+ { column: "createdAt", ascending: false },+ { column: "name", ascending: true, foreignTable: "customer" }+ ];++ it("uses the defaults, minus foreign-table sorts, when the user has none", () => {+ expect(getEffectiveSorts({ sorts: [] }, defaults)).toEqual([+ { column: "createdAt", ascending: false }+ ]);+ });++ it("uses the user's sorts and drops a sort on another table's column", () => {+ expect(+ getEffectiveSorts(+ {+ sorts: [+ { sortBy: "customer.name", sortAsc: true },+ { sortBy: "dueDate", sortAsc: true }+ ]+ },+ defaults+ )+ ).toEqual([{ column: "dueDate", ascending: true }]);+ });++ it("falls back to the defaults when every user sort is dropped", () => {+ expect(+ getEffectiveSorts(+ { sorts: [{ sortBy: "customer.name", sortAsc: true }] },+ defaults+ )+ ).toEqual([{ column: "createdAt", ascending: false }]);+ });+});++describe("setGenericQueryFilters paging", () => {+ const sorts = [{ column: "createdAt", ascending: false }];++ it("asks for one extra row in cursor mode (list loaders)", () => {+ const query = createQueryStub();+ setGenericQueryFilters(query as never, { limit: 100, cursor: null }, sorts);+ expect(query.limit).toHaveBeenCalledWith(101);+ expect(query.range).not.toHaveBeenCalled();+ });++ it("keeps exact offset paging when no cursor is given (MCP, v1 API)", () => {+ const query = createQueryStub();+ setGenericQueryFilters(query as never, { limit: 50, offset: 100 }, sorts);+ expect(query.range).toHaveBeenCalledWith(100, 149);+ expect(query.limit).not.toHaveBeenCalled();+ });++ it("pages by offset when the cursor key is present but undefined", () => {+ const query = createQueryStub();+ setGenericQueryFilters(+ query as never,+ { limit: 50, offset: 100, cursor: undefined },+ sorts+ );+ expect(query.range).toHaveBeenCalledWith(100, 149);+ expect(query.limit).not.toHaveBeenCalled();+ });++ it("filters after a cursor cut for the same order", () => {+ const query = createQueryStub();+ setGenericQueryFilters(+ query as never,+ {+ limit: 100,+ cursor: { values: ["2026-10-13"], id: "so_1", keys: ["createdAt:desc"] }+ },+ { defaultSorts: sorts }+ );+ expect(query.or).toHaveBeenCalledWith(+ 'createdAt.lt."2026-10-13",and(createdAt.eq."2026-10-13",id.gt."so_1")'+ );+ });++ it("returns no rows for a cursor cut for another order", () => {+ const query = createQueryStub();+ setGenericQueryFilters(+ query as never,+ {+ limit: 100,+ cursor: { values: ["Bolt"], id: "it_1", keys: ["name:asc"] }+ },+ { defaultSorts: sorts, idColumn: "itemId" }+ );+ expect(query.or).toHaveBeenCalledWith(+ "and(itemId.is.null,itemId.not.is.null)"+ );+ expect(query.limit).toHaveBeenCalledWith(101);+ });++ it("does not page at all without a limit", () => {+ const query = createQueryStub();+ setGenericQueryFilters(query as never, {}, sorts);+ expect(query.range).not.toHaveBeenCalled();+ expect(query.limit).not.toHaveBeenCalled();+ });+});+function createQueryStub() {const self = function (this: unknown) {return this;@@ -145,6 +273,9 @@ function createQueryStub() {return {or: vi.fn(self),gte: vi.fn(self),- lte: vi.fn(self)+ lte: vi.fn(self),+ order: vi.fn(self),+ limit: vi.fn(self),+ range: vi.fn(self)};}diff --git a/apps/erp/app/utils/query.ts b/apps/erp/app/utils/query.tsindex 01edc4224f..284cde9d10 100644--- a/apps/erp/app/utils/query.ts+++ b/apps/erp/app/utils/query.ts@@ -4,7 +4,16 @@import { badRequest } from "@carbon/auth";import type { PostgrestFilterBuilder } from "@supabase/postgrest-js";-import { getPageOffset, getPageSize } from "./pagination";+import type { Cursor, DefaultSort, KeysetSort, Paging, Sort } from "./cursor";+import {+ buildKeysetFilter,+ cursorMatchesSorts,+ decodeCursor,+ resolveSorts+} from "./cursor";+import { PAGE_SIZE } from "./pagination";++export type { DefaultSort, Paging, Sort } from "./cursor";type GenericSchema = {Tables: Record<string, unknown>;@@ -19,7 +28,7 @@ type GenericSchema = {** PostgREST implements `exact` as `COUNT(*) OVER ()`, which makes Postgres* materialize the entire filtered result set purely to produce a total — so- * `.range()` pagination limits what is transferred but not what is computed.+ * `.limit()` paging limits what is transferred but not what is computed.** `estimated` is a hybrid, not a blind guess: PostgREST still returns an exact* count when the planner's estimate is under `max-rows`, and only falls back to@@ -36,11 +45,6 @@ type GenericSchema = {*/export const LIST_COUNT = "estimated" as const;-export type Sort = {- sortBy: string;- sortAsc: boolean;-};-export type Filter = {column: string;operator: string;@@ -49,7 +53,17 @@ export type Filter = {export interface GenericQueryFilters {limit: number;- offset: number;+ /**+ * The last row of the previous page (`?after=`); null on the first page.+ * Set (even to null) by every list loader: it turns on cursor paging.+ */+ cursor?: Cursor | null;+ /**+ * Offset paging for callers outside the list pages: the MCP server and the+ * v1 API publish `limit` + `offset` for every `GenericQueryFilters` service+ * (`scripts/lib/service-metadata.ts`). Used only when `cursor` is absent.+ */+ offset?: number;sorts?: Sort[];filters?: Filter[];}@@ -57,8 +71,8 @@ export interface GenericQueryFilters {export function getGenericQueryFilters(params: URLSearchParams): GenericQueryFilters {- const limit = getPageSize(params);- const offset = getPageOffset(params);+ const limit = PAGE_SIZE;+ const cursor = decodeCursor(params.get("after"));const sortParams = params.getAll("sort");const sorts: Sort[] =@@ -89,7 +103,7 @@ export function getGenericQueryFilters(.filter((filter) => filter !== undefined) as Filter[]): [];- return { limit, offset, sorts, filters };+ return { limit, cursor, sorts, filters };}/**@@ -154,6 +168,33 @@ export function getGenericFilter<}}+function toPaging(paging: Paging | DefaultSort[] | undefined): Paging {+ if (!paging) return { defaultSorts: [] };+ return Array.isArray(paging) ? { defaultSorts: paging } : paging;+}++/**+ * The sorts the cursor follows for these args. Loaders pass the result to+ * `toPage` so the cursor reads the same columns the query orders by.+ */+export function getEffectiveSorts(+ args: Pick<Partial<GenericQueryFilters>, "sorts">,+ paging?: Paging | DefaultSort[]+): KeysetSort[] {+ return resolveSorts(args.sorts, toPaging(paging).defaultSorts).keyset;+}++/**+ * Applies the filters, the order and the page to a list query.+ *+ * - `paging` is the list's `X_PAGING` (a bare `DefaultSort[]` still works for+ * a query that is not a paged list).+ * - With `args.cursor` set (even to null), it pages by cursor: the keyset+ * filter after the cursor, and `limit + 1` rows for `toPage`. A cursor cut+ * for another order (a hand-edited URL, a sort changed mid-request) gives an+ * empty page, so the list ends rather than restarting at page 1.+ * - Without `args.cursor`, it pages by `offset` + `limit` (MCP, v1 API).+ */export function setGenericQueryFilters<T extends GenericSchema,U extends Record<string, unknown>,@@ -162,9 +203,11 @@ export function setGenericQueryFilters<// @ts-expect-error TS2707 - TODO: fix typequery: PostgrestFilterBuilder<T, U, V>,args: Partial<GenericQueryFilters>,- defaultSorts?: { column: string; ascending: boolean; foreignTable?: string }[]+ paging?: Paging | DefaultSort[]// @ts-expect-error TS2707 - TODO: fix type): PostgrestFilterBuilder<T, U, V> {+ const { defaultSorts, idColumn = "id" } = toPaging(paging);+args.filters?.forEach((filter) => {if (!filter.value) return;query = getGenericFilter(@@ -175,27 +218,37 @@ export function setGenericQueryFilters<);});- if (args.sorts && args.sorts.length > 0) {- args.sorts.forEach((sort) => {- if (sort.sortBy.includes(".")) {- const [table, column] = sort.sortBy.split(".");- query = query.order(`${table}(${column})`, {- ascending: sort.sortAsc- });- } else {- query = query.order(sort.sortBy, { ascending: sort.sortAsc });- }- });- } else if (defaultSorts && defaultSorts?.length > 0) {- defaultSorts.forEach((sort) => {- query = query.order(sort.column, {- ascending: sort.ascending,- foreignTable: sort.foreignTable- });+ const { orders, keyset } = resolveSorts(args.sorts, defaultSorts);++ if (args.cursor) {+ query = query.or(+ cursorMatchesSorts(args.cursor, keyset)+ ? buildKeysetFilter(keyset, args.cursor, idColumn)+ : // No row: the id is never both null and not null.+ `and(${idColumn}.is.null,${idColumn}.not.is.null)`+ );+ }++ orders.forEach((sort) => {+ query = query.order(sort.column, {+ ascending: sort.ascending,+ foreignTable: sort.foreignTable});+ });++ // The id breaks ties, so the order is total and every row has one place.+ if (keyset[keyset.length - 1]?.column !== idColumn) {+ query = query.order(idColumn, { ascending: true });}- if (Number.isInteger(args.offset) && Number.isInteger(args.limit)) {+ if (args.cursor !== undefined) {+ // Cursor paging (list loaders). One extra row tells `toPage` that a next+ // page exists.+ if (typeof args.limit === "number") {+ query = query.limit(args.limit + 1);+ }+ } else if (Number.isInteger(args.offset) && Number.isInteger(args.limit)) {+ // Offset paging (MCP, v1 API): the exact page, as before cursor paging.query = query.range(args.offset!, args.offset! + args.limit! - 1);}diff --git a/apps/erp/app/utils/revalidate.ts b/apps/erp/app/utils/revalidate.tsindex 3e5cb2b4ae..3e6fbed7ac 100644--- a/apps/erp/app/utils/revalidate.ts+++ b/apps/erp/app/utils/revalidate.ts@@ -5,12 +5,12 @@import type { ShouldRevalidateFunction } from "react-router";/**- * Skips revalidation for navigations that only open/close a child drawer or- * page through it (`offset` param) — report loaders depend on the remaining- * search params only, and their balance RPCs are expensive. Mutations and any- * other param change revalidate as usual.+ * Skips revalidation for navigations that keep the search params, such as+ * opening or closing a child drawer. Report loaders depend on the search params+ * only, and their balance RPCs are expensive. Mutations and any param change+ * revalidate as usual.*/-export const revalidateIgnoringOffset: ShouldRevalidateFunction = ({+export const revalidateOnSearchChange: ShouldRevalidateFunction = ({currentUrl,nextUrl,formMethod,@@ -20,8 +20,6 @@ export const revalidateIgnoringOffset: ShouldRevalidateFunction = ({const current = new URLSearchParams(currentUrl.search);const next = new URLSearchParams(nextUrl.search);- current.delete("offset");- next.delete("offset");current.sort();next.sort();diff --git a/apps/erp/app/utils/table-jobs.server.ts b/apps/erp/app/utils/table-jobs.server.tsnew file mode 100644index 0000000000..650344e870--- /dev/null+++ b/apps/erp/app/utils/table-jobs.server.ts@@ -0,0 +1,594 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { getClaims, makePermissionsFromClaims } from "@carbon/auth";+import {+ getCarbonServiceRole,+ getUserScopedClient+} from "@carbon/auth/client.server";+import type { Json } from "@carbon/database";+import { companyHasFeature } from "@carbon/ee/plan.server";+import { trigger } from "@carbon/jobs";+import {+ releaseTableJobLock,+ type TableBulkAction,+ type TableBulkActionCarry,+ type TableBulkActionResult,+ type TableJobContext,+ type TableJobHandlers,+ takeTableJobLock+} from "@carbon/jobs/inngest";+import { getLogger } from "@carbon/logger";+import { nanoid } from "nanoid";+import { isItemBulkUpdateField } from "~/modules/items";+import { bulkUpdateItems } from "~/modules/items/bulk-actions.server";+import {+ bulkDeleteJobs,+ bulkDissolveBatches,+ bulkReleaseBatches,+ bulkReleaseJobs+} from "~/modules/production/bulk-actions.server";+import { bulkDeletePurchaseOrders } from "~/modules/purchasing/purchasing.server";+import { userPermissionsValidator } from "~/modules/users";+import {+ queueInviteResends,+ queuePermissionUpdates,+ queueUserDeactivations,+ selectUsersForBulkAction+} from "~/modules/users/users.server";+import { getDatabaseClient } from "~/services/database.server";+import { decodeCursor } from "./cursor";+import { fetchListPage, getListDefinition } from "./list-registry/index.server";+import {+ type AllMatchingRequest,+ type BulkActionStart,+ bulkActionServesList,+ getBulkActionMeta,+ hasListPermission,+ parseAllMatching,+ refreshingClientFactory,+ rowLimitRefusal,+ type TableBulkActionKey,+ type TableJobClaims,+ tableJobBusyMessage+} from "./table-jobs";++const logger = getLogger("erp", "table-jobs");++/**+ * Every table job reads as the requesting user (`getUserScopedClient`), so RLS+ * applies as it does to a loader that keeps the RLS client. A loader that+ * bypasses RLS checks the same permission first (`hasListPermission`), so the+ * user client returns the same rows unless a policy is stricter than the+ * permission. A service-role read would rely on every list query to filter by+ * `companyId` itself, and the queries of the RLS-client lists were never+ * written or reviewed for that.+ */+async function canReadList(+ listKey: string,+ context: TableJobContext+): Promise<boolean> {+ const definition = getListDefinition(listKey);+ if (!definition) return false;++ const claims = await readClaims(context);+ if (!claims) return false;+ return hasListPermission(claims, definition.permission, context.companyId);+}++/** The user's claims for the company, read fresh as the user (not through+ * the permission cache, which can hold a revoked permission for an hour). */+async function readClaims({+ companyId,+ userId+}: TableJobContext): Promise<TableJobClaims | null> {+ const client = await getUserScopedClient(userId);+ const claims = await getClaims(client, userId, companyId);+ if (claims.error || claims.data === null) {+ logger.error("Failed to read the claims of a table job's user", {+ companyId,+ userId,+ error: claims.error+ });+ return null;+ }+ return makePermissionsFromClaims(claims.data as Json[]) ?? null;+}++async function fetchPage(+ listKey: string,+ { companyId, userId }: TableJobContext,+ search: string,+ page: { cursor: string | null; limit: number; forExport?: boolean }+) {+ const definition = getListDefinition(listKey);+ if (!definition) {+ return { rows: [], nextCursor: null, error: `Unknown list "${listKey}"` };+ }+ const params = new URLSearchParams(search);+ // The job pages with its own cursor; a cursor in the saved search is stale.+ params.delete("after");++ // One token per page: it lives five minutes, and a page is one query.+ const client = await getUserScopedClient(userId);+ const result = await fetchListPage(definition, client, companyId, params, {+ limit: page.limit,+ cursor: decodeCursor(page.cursor)+ });+ if (result.error || !page.forExport || !definition.exportRows) {+ return {+ rows: result.rows,+ nextCursor: result.nextCursor,+ error: result.error ?? undefined+ };+ }+ // The values the list's loader adds per page, so the export's columns+ // match the table's. A failed lookup fails the page, not a blank column.+ try {+ return {+ rows: await definition.exportRows(result.rows, { client, companyId }),+ nextCursor: result.nextCursor+ };+ } catch (error) {+ logger.error("Failed to add the export values of a list page", {+ companyId,+ listKey,+ error+ });+ return { rows: [], nextCursor: null, error };+ }+}++type BulkActionRunContext = TableJobContext & {+ /** The user's client, signed again when its token is four minutes old:+ * RLS applies as it does to the action route. */+ getClient: ReturnType<typeof userClientFactory>;+ db: ReturnType<typeof getDatabaseClient>;+};++/** What a bulk action does to one chunk of ids (at most 100); throws only+ * when nothing ran. Its metadata is `BULK_ACTIONS` in `./table-jobs`.+ * `carry` is what the previous chunk of the same run returned. */+type BulkActionRun = (+ ids: string[],+ params: Record<string, unknown>,+ context: BulkActionRunContext,+ carry?: TableBulkActionCarry+) => Promise<TableBulkActionResult>;++/** The supplier → PO map a Jobs Release chunk carries to the next one. */+function carriedPurchaseOrders(+ carry: TableBulkActionCarry | undefined+): Record<string, string> {+ const value = carry?.purchaseOrdersBySupplierId;+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};+ return Object.fromEntries(+ Object.entries(value).filter(+ (entry): entry is [string, string] => typeof entry[1] === "string"+ )+ );+}++function userClientFactory(userId: string) {+ return refreshingClientFactory(() => getUserScopedClient(userId));+}++/**+ * Each bulk action with a background path runs the same server function as+ * its action route, so the per-row checks are the same on both paths.+ */+const BULK_ACTION_RUNS: Record<TableBulkActionKey, BulkActionRun> = {+ "items.update": async (ids, { field, value }, context) => {+ if (!isItemBulkUpdateField(field) || typeof value !== "string") {+ throw new Error("The item update is not valid");+ }+ const result = await bulkUpdateItems(+ await context.getClient(),+ context.db,+ {+ itemIds: ids,+ field,+ value,+ companyId: context.companyId,+ userId: context.userId+ }+ );+ return {+ done: result.done,+ skipped: result.skipped,+ failed: result.failed+ };+ },+ "jobs.release": async (ids, _params, context, carry) => {+ const result = await bulkReleaseJobs({+ client: context.getClient,+ db: context.db,+ jobIds: ids,+ companyId: context.companyId,+ userId: context.userId,+ // A PO an earlier chunk created is this run's own, not a Draft to+ // choose from: the jobs after it go on the same PO.+ purchaseOrdersBySupplierId: carriedPurchaseOrders(carry)+ });+ if (!result.success) throw new Error(result.message);+ return {+ done: result.released,+ skipped: result.skipped,+ failed: result.failed.length,+ carry: { purchaseOrdersBySupplierId: result.purchaseOrdersBySupplierId }+ };+ },+ "jobs.delete": async (ids, _params, context) => {+ const result = await bulkDeleteJobs({+ client: await context.getClient(),+ jobIds: ids,+ companyId: context.companyId+ });+ return {+ done: result.deleted,+ skipped: result.skipped,+ failed: result.failed+ };+ },+ "purchase-orders.delete": async (ids, _params, context) => {+ const result = await bulkDeletePurchaseOrders(await context.getClient(), {+ purchaseOrderIds: ids,+ companyId: context.companyId+ });+ return {+ done: result.deleted,+ skipped: result.skipped,+ failed: result.failed+ };+ },+ "batches.release": async (ids, _params, context) => {+ const result = await bulkReleaseBatches({+ client: context.getClient,+ db: context.db,+ batchIds: ids,+ companyId: context.companyId,+ userId: context.userId+ });+ if (!result.success) throw new Error(result.message);+ return {+ done: result.done,+ skipped: result.skipped,+ failed: result.failed.length+ };+ },+ "batches.dissolve": async (ids, _params, context) => {+ const result = await bulkDissolveBatches({+ client: context.getClient,+ db: context.db,+ batchIds: ids,+ companyId: context.companyId,+ userId: context.userId+ });+ if (!result.success) throw new Error(result.message);+ return {+ done: result.done,+ skipped: result.skipped,+ failed: result.failed.length+ };+ },+ "users.deactivate": async (ids, { ip }, { companyId, userId }) => {+ const { allowed, skipped } = await selectUsersForBulkAction({+ action: "deactivate",+ userIds: ids,+ companyId,+ actorId: userId+ });+ if (allowed.length > 0) {+ await queueUserDeactivations({+ userIds: allowed,+ companyId,+ actorId: userId,+ ip: typeof ip === "string" ? ip : undefined+ });+ }+ // Done = queued: the user-admin job deactivates each user.+ return { done: allowed.length, skipped, failed: 0 };+ },+ "users.invite": async (ids, { location, ip }, { companyId, userId }) => {+ const { allowed, skipped } = await selectUsersForBulkAction({+ action: "invite",+ userIds: ids,+ companyId,+ actorId: userId+ });+ if (allowed.length > 0) {+ await queueInviteResends({+ userIds: allowed,+ companyId,+ location: typeof location === "string" ? location : "Unknown",+ ip: typeof ip === "string" ? ip : "127.0.0.1"+ });+ }+ return { done: allowed.length, skipped, failed: 0 };+ },+ "users.permissions": async (+ ids,+ { permissions, addOnly, ip },+ { companyId, userId }+ ) => {+ if (!isModulePermissions(permissions) || typeof addOnly !== "boolean") {+ throw new Error("The permission update is not valid");+ }+ const { allowed, skipped } = await selectUsersForBulkAction({+ action: "permissions",+ userIds: ids,+ companyId,+ actorId: userId+ });+ if (allowed.length > 0) {+ await queuePermissionUpdates({+ userIds: allowed,+ companyId,+ actorId: userId,+ permissions,+ addOnly,+ ip: typeof ip === "string" ? ip : undefined+ });+ }+ return { done: allowed.length, skipped, failed: 0 };+ }+};++/** The `permissions` param of `users.permissions`, checked again in the job:+ * a module name to its four switches, as the route validated it. */+function isModulePermissions(+ value: unknown+): value is Record<+ string,+ { view: boolean; create: boolean; update: boolean; delete: boolean }+> {+ return (+ value !== null &&+ typeof value === "object" &&+ Object.values(value).every(+ (permission) => userPermissionsValidator.safeParse(permission).success+ )+ );+}++/** Whether the user may still run the action on the list: an employee with+ * the list's view permission and the action's own permission, in a company+ * whose plan has the action's feature. */+async function canRunBulkAction(+ listKey: string,+ action: TableBulkAction,+ context: TableJobContext+): Promise<boolean> {+ const bulkAction = getBulkActionMeta(action.key);+ const list = getListDefinition(listKey);+ if (!bulkAction || !list || !bulkActionServesList(action.key, listKey)) {+ return false;+ }+ const claims = await readClaims(context);+ if (!claims) return false;+ if (+ !hasListPermission(claims, list.permission, context.companyId) ||+ !hasListPermission(claims, bulkAction.permission, context.companyId)+ ) {+ return false;+ }+ return bulkAction.feature+ ? companyHasFeature(getCarbonServiceRole(), context.companyId, {+ feature: bulkAction.feature+ })+ : true;+}++async function runBulkAction(+ action: TableBulkAction,+ ids: string[],+ context: TableJobContext,+ carry?: TableBulkActionCarry+): Promise<TableBulkActionResult> {+ const run = getBulkActionMeta(action.key)+ ? BULK_ACTION_RUNS[action.key as TableBulkActionKey]+ : undefined;+ if (!run) throw new Error(`Unknown bulk action "${action.key}"`);+ return run(+ ids,+ action.params,+ {+ ...context,+ getClient: userClientFactory(context.userId),+ db: getDatabaseClient()+ },+ carry+ );+}++/** The ERP side of the table jobs, handed to packages/jobs by api+/inngest.ts. */+export const tableJobHandlers: TableJobHandlers = {+ canReadList,+ fetchListPage: fetchPage,+ listIdColumn: (listKey) => getListDefinition(listKey)?.idColumn ?? "id",+ canRunBulkAction,+ runBulkAction+};++/** The list's matching rows as its header counts them: exact up to 1,000,+ * the planner's estimate above. Null when the count cannot be read. */+async function countMatchingRows(+ listKey: string,+ { companyId, userId }: TableJobContext,+ search: string+): Promise<number | null> {+ const definition = getListDefinition(listKey);+ if (!definition) return null;+ const params = new URLSearchParams(search);+ params.delete("after");+ const result = await fetchListPage(+ definition,+ await getUserScopedClient(userId),+ companyId,+ params,+ { limit: 1, cursor: null }+ );+ if (result.error) {+ logger.error("Failed to count the rows of a bulk action", {+ companyId,+ listKey,+ error: result.error+ });+ return null;+ }+ return result.count;+}++/**+ * Starts the background bulk action on every row of the list that matches its+ * URL search: the action routes call it when the request holds `allMatching`+ * in place of ids. The route has already checked the action's permission; this+ * checks the list's too, the action's row limit, takes the company's bulk lock+ * and sends the event.+ */+export function startTableBulkAction({+ allMatching,+ ...args+}: BulkRunArgs & {+ allMatching: AllMatchingRequest;+}): Promise<BulkActionStart> {+ return startBulkRun({+ ...args,+ listKey: allMatching.listKey,+ search: allMatching.search+ });+}++/**+ * Starts the background bulk action on rows the user selected, when there are+ * too many for one request (`fitsOneRequest`). The job acts on these ids and+ * reads no list pages; the per-row checks are the same as on the route.+ */+export function startSelectedBulkAction({+ listKey,+ ids,+ ...args+}: BulkRunArgs & { listKey: string; ids: string[] }): Promise<BulkActionStart> {+ return startBulkRun({ ...args, listKey, search: "", ids });+}++type BulkRunArgs = {+ companyId: string;+ userId: string;+ actionKey: TableBulkActionKey;+ params: Record<string, unknown>;+};++async function startBulkRun({+ companyId,+ userId,+ actionKey,+ params,+ listKey,+ search,+ ids+}: BulkRunArgs & {+ listKey: string;+ search: string;+ ids?: string[];+}): Promise<BulkActionStart> {+ const bulkAction = getBulkActionMeta(actionKey);+ if (+ !bulkAction ||+ !bulkActionServesList(actionKey, listKey) ||+ !getListDefinition(listKey)+ ) {+ logger.error("A bulk action was requested for a list it does not serve", {+ companyId,+ actionKey,+ listKey+ });+ return { success: false, message: "This action cannot run on this list" };+ }++ const context = { companyId, userId };+ if (!(await canRunBulkAction(listKey, { key: actionKey, params }, context))) {+ return {+ success: false,+ message: "You do not have permission to do this on every matching row"+ };+ }++ if (bulkAction.maxRows !== undefined) {+ const matching = ids+ ? ids.length+ : await countMatchingRows(listKey, context, search);+ if (matching === null) {+ return { success: false, message: "The bulk action could not start" };+ }+ const refusal = rowLimitRefusal(bulkAction, matching);+ if (refusal) return { success: false, message: refusal };+ }++ const bulkActionId = nanoid();+ const lock = await takeTableJobLock("bulk", companyId, bulkActionId);+ if (lock.status === "busy") {+ return {+ success: false,+ message: tableJobBusyMessage("bulk", lock.retryAfterSeconds)+ };+ }+ if (lock.status === "unavailable") {+ // Fail-open: Inngest's per-company concurrency still runs one at a time.+ logger.warn("Starting a table bulk action without the Redis lock", {+ companyId,+ actionKey+ });+ }++ try {+ await trigger("table-bulk-action", {+ companyId,+ userId,+ bulkActionId,+ actionKey,+ actionLabel: bulkAction.label,+ params,+ listKey,+ search,+ ...(bulkAction.maxRows !== undefined+ ? { maxRows: bulkAction.maxRows }+ : {}),+ ...(bulkAction.idsPerStep !== undefined+ ? { idsPerStep: bulkAction.idsPerStep }+ : {}),+ ...(ids ? { ids } : {})+ });+ } catch (error) {+ logger.error("Failed to start a table bulk action", {+ companyId,+ actionKey,+ error+ });+ await releaseTableJobLock("bulk", companyId, bulkActionId);+ return { success: false, message: "The bulk action could not start" };+ }+ return { success: true, background: true };+}++/**+ * The `allMatching` branch every bulk action route shares: when the request+ * names every matching row (`allMatching` in a form field or a JSON body), it+ * starts the background job and answers what the route returns. Null when the+ * request names ids instead, so the route goes on with its own path.+ */+export async function startAllMatchingBulkAction(+ allMatching: unknown,+ args: {+ companyId: string;+ userId: string;+ actionKey: TableBulkActionKey;+ params: Record<string, unknown>;+ }+): Promise<BulkActionStart | null> {+ const request = parseAllMatching(allMatching);+ return request+ ? startTableBulkAction({ ...args, allMatching: request })+ : null;+}diff --git a/apps/erp/app/utils/table-jobs.test.ts b/apps/erp/app/utils/table-jobs.test.tsnew file mode 100644index 0000000000..a0e8168b4f--- /dev/null+++ b/apps/erp/app/utils/table-jobs.test.ts@@ -0,0 +1,232 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ BULK_ACTIONS,+ bulkActionServesList,+ bulkStartFormResponse,+ fitsOneRequest,+ getBulkActionMeta,+ hasListPermission,+ newTableExportId,+ parseAllMatching,+ parseTableExportId,+ refreshingClientFactory,+ resolveUserClient,+ rowLimitRefusal,+ splitIdsByStatus,+ type TableJobClaims,+ tableJobBusyMessage,+ USER_CLIENT_MAX_AGE_MS+} from "./table-jobs";++describe("tableJobBusyMessage", () => {+ it("says how long the lock can still hold, in whole minutes", () => {+ expect(tableJobBusyMessage("export", 1741)).toBe(+ "An export is already running for your company. Try again when it ends, at the latest in 30 minutes."+ );+ expect(tableJobBusyMessage("bulk", 30)).toBe(+ "A bulk action is already running for your company. Try again when it ends, at the latest in 1 minute."+ );+ });++ it("promises no wait when Redis gave no TTL", () => {+ expect(tableJobBusyMessage("bulk", 0)).toBe(+ "A bulk action is already running for your company."+ );+ });+});++describe("export ids", () => {+ it("carries the list key the download route checks", () => {+ expect(parseTableExportId(newTableExportId("purchase-orders"))).toEqual({+ listKey: "purchase-orders"+ });+ });++ it("refuses an id that is not one", () => {+ expect(parseTableExportId("failed:abc")).toBeNull();+ expect(parseTableExportId("parts")).toBeNull();+ expect(parseTableExportId("parts.short")).toBeNull();+ expect(parseTableExportId("../x.V1StGXR8_Z5jdHi6B-myT")).toBeNull();+ expect(parseTableExportId("parts.V1StGXR8_Z5jdHi6B-myT.csv")).toBeNull();+ });+});++describe("refreshingClientFactory", () => {+ it("keeps one token for four minutes, then signs a new one", async () => {+ let clock = 0;+ let signed = 0;+ const getClient = refreshingClientFactory(+ async () => ++signed,+ USER_CLIENT_MAX_AGE_MS,+ () => clock+ );+ expect(await getClient()).toBe(1);+ clock = USER_CLIENT_MAX_AGE_MS - 1;+ expect(await getClient()).toBe(1);+ clock = USER_CLIENT_MAX_AGE_MS;+ expect(await getClient()).toBe(2);+ clock += 1_000;+ expect(await getClient()).toBe(2);+ });++ it("serves the request's client as it is", async () => {+ const client = { from: () => null } as never;+ expect(await resolveUserClient(client)).toBe(client);+ });+});++function claims(overrides: Partial<TableJobClaims> = {}): TableJobClaims {+ return {+ role: "employee",+ permissions: {+ sales: { view: ["co_1"], create: [], update: ["co_1"], delete: [] },+ parts: { view: ["co_2"], create: [], update: [], delete: [] }+ },+ ...overrides+ };+}++describe("hasListPermission", () => {+ it("accepts an employee with the list's permission in the company", () => {+ expect(hasListPermission(claims(), { view: "sales" }, "co_1")).toBe(true);+ });++ it("refuses a permission granted in another company only", () => {+ expect(hasListPermission(claims(), { view: "parts" }, "co_1")).toBe(false);+ });++ it("refuses a portal account even with the permission", () => {+ expect(+ hasListPermission(claims({ role: "customer" }), { view: "sales" }, "co_1")+ ).toBe(false);+ });++ it("requires every action and every module of the permission", () => {+ expect(+ hasListPermission(claims(), { view: "sales", update: "sales" }, "co_1")+ ).toBe(true);+ expect(+ hasListPermission(claims(), { view: ["sales", "parts"] }, "co_1")+ ).toBe(false);+ expect(+ hasListPermission(claims(), { view: "sales", delete: "sales" }, "co_1")+ ).toBe(false);+ });++ it("accepts a role-only permission for an employee", () => {+ expect(hasListPermission(claims(), { role: "employee" }, "co_1")).toBe(+ true+ );+ });+});++describe("splitIdsByStatus", () => {+ const isDraft = (status: string | null) => status === "Draft";++ it("keeps the ids whose status the action accepts, in request order", () => {+ expect(+ splitIdsByStatus(+ ["b", "a", "c"],+ [+ { id: "a", status: "Draft" },+ { id: "b", status: "Draft" },+ { id: "c", status: "Released" }+ ],+ isDraft+ )+ ).toEqual({ allowed: ["b", "a"], skipped: 1 });+ });++ it("skips an id the database did not return", () => {+ expect(+ splitIdsByStatus(+ ["a", "other-company"],+ [{ id: "a", status: "Draft" }],+ isDraft+ )+ ).toEqual({ allowed: ["a"], skipped: 1 });+ });+});++describe("parseAllMatching", () => {+ it("reads an object", () => {+ expect(parseAllMatching({ listKey: "jobs", search: "?q=x" })).toEqual({+ listKey: "jobs",+ search: "?q=x"+ });+ });++ it("reads the JSON text of a form field", () => {+ expect(+ parseAllMatching(JSON.stringify({ listKey: "parts", search: "" }))+ ).toEqual({ listKey: "parts", search: "" });+ });++ it("refuses a missing or broken value", () => {+ expect(parseAllMatching(null)).toBeNull();+ expect(parseAllMatching("not json")).toBeNull();+ expect(parseAllMatching({ listKey: "", search: "" })).toBeNull();+ expect(parseAllMatching({ listKey: "jobs" })).toBeNull();+ });+});++describe("the bulk actions' background path", () => {+ it("runs an action only on the lists it names", () => {+ expect(bulkActionServesList("jobs.release", "jobs")).toBe(true);+ expect(bulkActionServesList("jobs.release", "parts")).toBe(false);+ expect(bulkActionServesList("items.update", "services")).toBe(true);+ expect(bulkActionServesList("unknown", "jobs")).toBe(false);+ expect(getBulkActionMeta("toString")).toBeUndefined();+ });++ it("refuses Jobs Release and Batches Release past 2,000 rows", () => {+ expect(rowLimitRefusal(BULK_ACTIONS["jobs.release"], 2_000)).toBeNull();+ expect(rowLimitRefusal(BULK_ACTIONS["jobs.release"], 2_001)).toBe(+ "Release jobs runs on at most 2,000 rows. Filter the list to 2,000 rows or fewer."+ );+ expect(rowLimitRefusal(BULK_ACTIONS["batches.release"], 5_000)).toContain(+ "Release batches runs on at most 2,000 rows"+ );+ });++ it("puts no row limit on the other actions", () => {+ expect(rowLimitRefusal(BULK_ACTIONS["items.update"], 90_000)).toBeNull();+ expect(rowLimitRefusal(BULK_ACTIONS["jobs.delete"], 90_000)).toBeNull();+ });++ it("re-checks the plan feature of Edit Permissions in the job", () => {+ expect(getBulkActionMeta("users.permissions")?.feature).toBe("PERMISSIONS");+ });++ it("answers a form route's start with an error field on both outcomes", () => {+ expect(bulkStartFormResponse({ success: true, background: true })).toEqual({+ success: true,+ background: true,+ data: null,+ error: null+ });+ expect(bulkStartFormResponse({ success: false, message: "Busy" })).toEqual({+ success: false,+ message: "Busy",+ data: null,+ error: { message: "Busy" }+ });+ });+});++describe("fitsOneRequest", () => {+ it("keeps a selection inside one background step in the request", () => {+ expect(fitsOneRequest("jobs.release", 25)).toBe(true);+ expect(fitsOneRequest("jobs.release", 26)).toBe(false);+ expect(fitsOneRequest("batches.release", 10)).toBe(true);+ expect(fitsOneRequest("batches.release", 11)).toBe(false);+ });++ it("runs any selection in the request for an action with no step size", () => {+ expect(fitsOneRequest("jobs.delete", 1_000)).toBe(true);+ });+});diff --git a/apps/erp/app/utils/table-jobs.ts b/apps/erp/app/utils/table-jobs.tsnew file mode 100644index 0000000000..a15c213863--- /dev/null+++ b/apps/erp/app/utils/table-jobs.ts@@ -0,0 +1,320 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Database } from "@carbon/database";+import type { Feature } from "@carbon/ee/plan";+import { RoundingMode, round } from "@carbon/utils";+import type { SupabaseClient } from "@supabase/supabase-js";+import { nanoid } from "nanoid";+import type { ListPermission } from "./list-registry/index.server";++/**+ * Pure parts of the table jobs (background export and bulk actions), shared by+ * the server handlers (`table-jobs.server.ts`), the action routes and the+ * export download route. No I/O here.+ */++export type TableJobClaims = {+ role: string | null;+ permissions: Record<+ string,+ { view: string[]; create: string[]; update: string[]; delete: string[] }+ >;+};++const PERMISSION_ACTIONS = ["view", "create", "update", "delete"] as const;++/**+ * The check `requirePermissions` does for a list's permission, on claims read+ * for one company. A table job also requires the employee role: the loaders+ * refuse portal accounts, and the job must never do more than the loader.+ */+export function hasListPermission(+ claims: TableJobClaims,+ permission: ListPermission,+ companyId: string+): boolean {+ if (claims.role !== "employee") return false;+ if (permission.role && claims.role !== permission.role) return false;+ return PERMISSION_ACTIONS.every((action) => {+ const required = permission[action];+ if (required === undefined) return true;+ const modules = Array.isArray(required) ? required : [required];+ return modules.every(+ (module) =>+ claims.permissions[module]?.[action]?.includes(companyId) ?? false+ );+ });+}++/** The answer when another job of the company holds the lock: the job kind+ * and, when Redis knows it, how long until the lock expires at the latest. */+export function tableJobBusyMessage(+ kind: "export" | "bulk",+ retryAfterSeconds: number+): string {+ const running =+ kind === "export"+ ? "An export is already running for your company."+ : "A bulk action is already running for your company.";+ if (retryAfterSeconds <= 0) return running;+ const minutes = round(retryAfterSeconds / 60, 0, RoundingMode.Up);+ return `${running} Try again when it ends, at the latest in ${minutes} ${+ minutes === 1 ? "minute" : "minutes"+ }.`;+}++const LIST_KEY = /^[a-z0-9-]{1,64}$/;+const EXPORT_TOKEN = /^[A-Za-z0-9_-]{10,64}$/;++/**+ * A new export id, `{listKey}.{random}`. The list key rides in the id so the+ * download route can check the list's permission again without a second+ * store; changing it in a link names a file that does not exist.+ */+export function newTableExportId(listKey: string): string {+ return `${listKey}.${nanoid()}`;+}++/** The list key of an export id, or null when the id is not one. */+export function parseTableExportId(+ exportId: string+): { listKey: string } | null {+ const [listKey, token, ...rest] = exportId.split(".");+ if (rest.length > 0 || !listKey || !token) return null;+ if (!LIST_KEY.test(listKey) || !EXPORT_TOKEN.test(token)) return null;+ return { listKey };+}++/**+ * The client a bulk action writes with: the request's client on the action+ * route, or a factory in the background job, which signs a new user token+ * when the last is about to expire (they live five minutes). A long action+ * asks for the client again before each row it acts on.+ */+export type UserClientSource =+ | SupabaseClient<Database>+ | (() => Promise<SupabaseClient<Database>>);++export function resolveUserClient(+ source: UserClientSource+): Promise<SupabaseClient<Database>> {+ return typeof source === "function" ? source() : Promise.resolve(source);+}++/** A user token lives five minutes; sign a new one after four, so a call made+ * just before the switch still has a minute to run. */+export const USER_CLIENT_MAX_AGE_MS = 4 * 60 * 1000;++/**+ * A factory that hands out the same client until it is `maxAgeMs` old, then+ * signs a new one. `now` is the wall clock in milliseconds (an instant, not a+ * date, so `Date.now` is right here).+ */+export function refreshingClientFactory<T>(+ sign: () => Promise<T>,+ maxAgeMs = USER_CLIENT_MAX_AGE_MS,+ now: () => number = Date.now+): () => Promise<T> {+ let current: { client: Promise<T>; signedAt: number } | null = null;+ return () => {+ const at = now();+ if (!current || at - current.signedAt >= maxAgeMs) {+ current = { client: sign(), signedAt: at };+ }+ return current.client;+ };+}++/**+ * Splits the requested ids into the ones the action may act on and the rest.+ * `rows` is what the database returned for the ids (scoped to the company);+ * an id with no row (another company's, or deleted) counts as skipped, like+ * a row whose status the action does not accept.+ */+export function splitIdsByStatus<TStatus>(+ ids: string[],+ rows: { id: string; status: TStatus }[],+ isAllowed: (status: TStatus) => boolean+): { allowed: string[]; skipped: number } {+ const statusById = new Map(rows.map((row) => [row.id, row.status] as const));+ const allowed = ids.filter(+ (id) => statusById.has(id) && isAllowed(statusById.get(id) as TStatus)+ );+ return { allowed, skipped: ids.length - allowed.length };+}++/** A bulk action route's "every matching row" request: the list and its URL+ * search, as the Table's `AllMatchingSelection` holds them. */+export type AllMatchingRequest = { listKey: string; search: string };++/**+ * What a bulk action route answers for an "every matching row" request: the+ * background job started, or why it did not. Every route answers the same+ * shape, so one client helper (`useBulkActionResult`) reads them all.+ */+export type BulkActionStart =+ | { success: true; background: true }+ | { success: false; message: string };++/**+ * A form-posted route's answer for a bulk start: the `BulkActionStart` fields+ * plus the route's usual `{ data, error }`, so code typed by the route's+ * answer reads `error` on every variant.+ */+export function bulkStartFormResponse(start: BulkActionStart) {+ return start.success+ ? { ...start, data: null, error: null }+ : { ...start, data: null, error: { message: start.message } };+}++/**+ * The most rows Jobs Release and Batches Release act on in the background.+ * Each released job runs the requirements recalculation and MRP, so a bigger+ * run would hold the company's queue for hours.+ */+export const ALL_MATCHING_RELEASE_LIMIT = 2_000;++export type BulkActionMeta = {+ /** The action's English name for the notification ("Release jobs"). */+ label: string;+ /** The list keys whose rows the action may act on. */+ lists: readonly string[];+ /** The action route's permission check (the job adds the employee role). */+ permission: ListPermission;+ /** The plan feature the action route requires, checked again by the job. */+ feature?: Feature;+ /** The most matching rows the action runs on (default 100,000). */+ maxRows?: number;+ /** Ids per job step (default 1,000). Lower for an action that does a lot+ * per row, so one step stays well below the load balancer's 600 s. */+ idsPerStep?: number;+};++/**+ * The bulk actions with a background path (spec "Which bulk actions get the+ * background path"): what they may act on and how the job runs them. What+ * each one does is in `table-jobs.server.ts`, under the same key.+ */+export const BULK_ACTIONS = {+ "items.update": {+ label: "Update items",+ lists: ["parts", "materials", "tools", "consumables", "services"],+ permission: { update: "parts" }+ },+ "jobs.release": {+ label: "Release jobs",+ lists: ["jobs"],+ permission: { update: "production" },+ maxRows: ALL_MATCHING_RELEASE_LIMIT,+ // Each job runs the requirements recalculation and MRP.+ idsPerStep: 25+ },+ "jobs.delete": {+ label: "Delete jobs",+ lists: ["jobs"],+ permission: { update: "production", delete: "production" }+ },+ "purchase-orders.delete": {+ label: "Delete purchase orders",+ lists: ["purchase-orders"],+ permission: { update: "purchasing", delete: "purchasing" }+ },+ "batches.release": {+ label: "Release batches",+ lists: ["operation-batches"],+ permission: { update: "production" },+ maxRows: ALL_MATCHING_RELEASE_LIMIT,+ // Each batch releases its member jobs, each with its own MRP run.+ idsPerStep: 10+ },+ "batches.dissolve": {+ label: "Dissolve batches",+ lists: ["operation-batches"],+ permission: { update: "production" },+ idsPerStep: 100+ },+ "users.deactivate": {+ label: "Deactivate users",+ lists: ["employee-accounts"],+ permission: { delete: "users" }+ },+ "users.invite": {+ label: "Send invites",+ lists: ["employee-accounts"],+ permission: { create: "users" }+ },+ "users.permissions": {+ label: "Edit permissions",+ lists: ["employee-accounts"],+ permission: { update: "users" },+ // The route requires it with `requireFeature`; the job checks it again,+ // in case the plan changed while the run waited.+ feature: "PERMISSIONS"+ }+} as const satisfies Record<string, BulkActionMeta>;++export type TableBulkActionKey = keyof typeof BULK_ACTIONS;++/**+ * Whether an action route can act on `count` selected rows in the request+ * itself: no more than one background step takes (`idsPerStep`). A bigger+ * selection goes to the background job, or the load balancer cuts the request+ * at 600 s.+ */+export function fitsOneRequest(+ actionKey: TableBulkActionKey,+ count: number+): boolean {+ const meta: BulkActionMeta = BULK_ACTIONS[actionKey];+ return meta.idsPerStep === undefined || count <= meta.idsPerStep;+}++export function getBulkActionMeta(key: string): BulkActionMeta | undefined {+ const actions: Record<string, BulkActionMeta> = BULK_ACTIONS;+ return Object.hasOwn(actions, key) ? actions[key] : undefined;+}++/** Whether the action runs on the list: a known action, named for it. */+export function bulkActionServesList(actionKey: string, listKey: string) {+ return getBulkActionMeta(actionKey)?.lists.includes(listKey) ?? false;+}++const rowCount = new Intl.NumberFormat("en-US");++/**+ * Why the action may not start on `matchingRows` rows (the list header's+ * count: exact up to 1,000, an estimate above), or null. The job also stops+ * at the limit, so an estimate that was low still runs on the first rows only.+ */+export function rowLimitRefusal(+ action: BulkActionMeta,+ matchingRows: number+): string | null {+ if (action.maxRows === undefined || matchingRows <= action.maxRows) {+ return null;+ }+ const limit = rowCount.format(action.maxRows);+ return `${action.label} runs on at most ${limit} rows. Filter the list to ${limit} rows or fewer.`;+}++/**+ * Reads `allMatching` from a bulk action request: an object (JSON body) or+ * its JSON text (a form field). Answers null when it is missing or not valid.+ */+export function parseAllMatching(value: unknown): AllMatchingRequest | null {+ let parsed = value;+ if (typeof value === "string") {+ try {+ parsed = JSON.parse(value);+ } catch {+ return null;+ }+ }+ if (parsed === null || typeof parsed !== "object") return null;+ const { listKey, search } = parsed as Record<string, unknown>;+ if (typeof listKey !== "string" || listKey.length === 0) return null;+ if (typeof search !== "string" || search.length > 10_000) return null;+ return { listKey, search };+}diff --git a/apps/erp/test/infinite-table-data-identity.test.ts b/apps/erp/test/infinite-table-data-identity.test.tsnew file mode 100644index 0000000000..68ec4a1dc9--- /dev/null+++ b/apps/erp/test/infinite-table-data-identity.test.ts@@ -0,0 +1,82 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { readdirSync, readFileSync, statSync } from "node:fs";+import { join, relative } from "node:path";+import { describe, expect, it } from "vitest";++/**+ * `useInfiniteRows` reads a new `data` array as a revalidation: it re-reads+ * every loaded page (up to 20). So a table with `infinite` must pass the+ * loader's array itself, or a memoized one. A copy built in the render body+ * (`const rows = data.map(…)`) is a new array on every render, and every+ * render then refreshes the whole list.+ */++const APP = join(__dirname, "..", "app");++function tsxFiles(dir: string): string[] {+ return readdirSync(dir).flatMap((name) => {+ const path = join(dir, name);+ if (statSync(path).isDirectory()) return tsxFiles(path);+ return path.endsWith(".tsx") ? [path] : [];+ });+}++/** The identifier passed as `data={…}` on a JSX element that has `infinite=`. */+function infiniteDataNames(source: string): string[] {+ const names: string[] = [];+ for (const match of source.matchAll(/<Table\b[^>]*?>/gs)) {+ const element = match[0];+ if (!/\binfinite=\{/.test(element)) continue;+ const data = /\bdata=\{\s*([A-Za-z_$][\w$]*)\s*\}/.exec(element);+ if (data) names.push(data[1]);+ }+ return names;+}++/** True when `name` is built in the render body by copying an array. */+function isRenderCopy(source: string, name: string): boolean {+ const copy = new RegExp(+ String.raw`const\s+${name}\s*=\s*(?:[\w$.?]+\s*\.\s*(?:map|filter|slice|concat|toSorted)\s*\(|\[\s*\.\.\.)`+ );+ return copy.test(source);+}++describe("infinite tables pass a stable data array", () => {+ const files = tsxFiles(APP).filter((file) =>+ readFileSync(file, "utf8").includes("infinite={")+ );++ it("finds the infinite tables", () => {+ expect(files.length).toBeGreaterThan(50);+ });++ it("never passes an array copied during render", () => {+ const offenders = files.flatMap((file) => {+ const source = readFileSync(file, "utf8");+ return infiniteDataNames(source)+ .filter((name) => isRenderCopy(source, name))+ .map((name) => `${relative(APP, file)}: data={${name}}`);+ });+ expect(offenders).toEqual([]);+ });++ it("detects a copy built with .map", () => {+ const source = `+ const rows = data.map((row) => ({ ...row }));+ return <Table data={rows} infinite={{ dataKey: "x", nextCursor }} />;+ `;+ expect(infiniteDataNames(source)).toEqual(["rows"]);+ expect(isRenderCopy(source, "rows")).toBe(true);+ });++ it("accepts a memoized array", () => {+ const source = `+ const rows = useMemo(() => data.map((row) => ({ ...row })), [data]);+ return <Table data={rows} infinite={{ dataKey: "x", nextCursor }} />;+ `;+ expect(isRenderCopy(source, "rows")).toBe(false);+ });+});diff --git a/apps/erp/test/job-release-logic.test.ts b/apps/erp/test/job-release-logic.test.tsindex ff6767e2fc..7828cb3b2e 100644--- a/apps/erp/test/job-release-logic.test.ts+++ b/apps/erp/test/job-release-logic.test.ts@@ -4,6 +4,7 @@import { describe, expect, it } from "vitest";import {+ bulkReleaseStartingPurchaseOrders,jobReleaseProblems,makeMethodsMissingOperations,outsideOperationsNeedingPurchaseOrders,@@ -136,3 +137,33 @@ describe("jobReleaseProblems", () => {]);});});++describe("bulkReleaseStartingPurchaseOrders", () => {+ it("starts every supplier on a new PO and asks for a choice when Drafts exist", () => {+ const result = bulkReleaseStartingPurchaseOrders([+ { supplierId: "s1", draftPurchaseOrders: [] },+ { supplierId: "s2", draftPurchaseOrders: [{ id: "po-a" }] }+ ]);+ expect(result.purchaseOrders).toEqual({ s1: "new", s2: "new" });+ expect([...result.suppliersToChoose]).toEqual(["s2"]);+ });++ it("keeps the PO an earlier slice created, with no choice to make", () => {+ // Slice 1 created po-1 for s1; slice 2 now reads it as a Draft of s1.+ const result = bulkReleaseStartingPurchaseOrders(+ [{ supplierId: "s1", draftPurchaseOrders: [{ id: "po-1" }] }],+ { s1: "po-1" }+ );+ expect(result.purchaseOrders).toEqual({ s1: "po-1" });+ expect(result.suppliersToChoose.size).toBe(0);+ });++ it("ignores a carried PO that is no longer a Draft of the supplier", () => {+ const result = bulkReleaseStartingPurchaseOrders(+ [{ supplierId: "s1", draftPurchaseOrders: [{ id: "po-other" }] }],+ { s1: "po-1" }+ );+ expect(result.purchaseOrders).toEqual({ s1: "new" });+ expect([...result.suppliersToChoose]).toEqual(["s1"]);+ });+});diff --git a/apps/erp/test/list-export-values.test.ts b/apps/erp/test/list-export-values.test.tsnew file mode 100644index 0000000000..0b482393ca--- /dev/null+++ b/apps/erp/test/list-export-values.test.ts@@ -0,0 +1,116 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import { JOB_LIST_EXPORT_VALUES } from "../app/modules/production/ui/Jobs/job-list-export";+import { SUPPLIER_CONTACT_VALUES } from "../app/modules/purchasing/ui/Supplier/supplier-list-export";+import { WORKFLOW_LIST_EXPORT_VALUES } from "../app/modules/workflows/ui/workflow-list-export";+import { withExportValues } from "../app/utils/list-registry/export-values";++/**+ * A list whose loader adds per-row values (`mapRows`) exports them in the+ * browser through each column's `meta.exportValue`. The background export+ * (over 1,000 rows) runs no column code: it reads `row[key]`. So the list's+ * `exportRows` runs the same lookup and writes the same values under the+ * column keys, from one shared map per table.+ */++const APP = join(__dirname, "..", "app");+const read = (path: string) => readFileSync(join(APP, path), "utf8");++const LISTS = [+ {+ route: "routes/x+/production+/jobs.tsx",+ registry: "utils/list-registry/production.server.ts",+ table: "modules/production/ui/Jobs/JobsTable.tsx",+ values: JOB_LIST_EXPORT_VALUES+ },+ {+ route: "routes/x+/purchasing+/suppliers.tsx",+ registry: "utils/list-registry/purchasing.server.ts",+ table: "modules/purchasing/ui/Supplier/SuppliersTable.tsx",+ values: SUPPLIER_CONTACT_VALUES+ },+ {+ route: "routes/x+/workflows+/_index.tsx",+ registry: "utils/list-registry/workflows.server.ts",+ table: "modules/workflows/ui/WorkflowsTable.tsx",+ values: WORKFLOW_LIST_EXPORT_VALUES+ }+];++describe("withExportValues", () => {+ it("writes each column's value under its key", () => {+ const rows = withExportValues(+ [{ id: "j1", batchReadableIds: ["BAT-1", "BAT-2"] }],+ JOB_LIST_EXPORT_VALUES+ );+ expect(rows).toEqual([+ {+ id: "j1",+ batchReadableIds: ["BAT-1", "BAT-2"],+ batches: "BAT-1, BAT-2",+ trackedEntityId: null+ }+ ]);+ });+});++describe("the shared export values", () => {+ it("reads the job extras the loader adds", () => {+ const row = { batchReadableIds: ["BAT-7"], trackedEntityReadableId: "L-9" };+ expect(JOB_LIST_EXPORT_VALUES.batches(row)).toBe("BAT-7");+ expect(JOB_LIST_EXPORT_VALUES.trackedEntityId(row)).toBe("L-9");+ });++ it("reads the supplier report contacts the loader adds", () => {+ const row = {+ reportContacts: {+ purchasingContact: {+ contact: { fullName: "Ada Park", email: "[email protected]" }+ },+ payment: null,+ shipping: null+ }+ } as unknown as Parameters<+ typeof SUPPLIER_CONTACT_VALUES.purchasingContactName+ >[0];+ expect(SUPPLIER_CONTACT_VALUES.purchasingContactName(row)).toBe("Ada Park");+ expect(SUPPLIER_CONTACT_VALUES.purchasingContactEmail(row)).toBe(+ );+ expect(SUPPLIER_CONTACT_VALUES.invoiceAddress(row)).toBeNull();+ });++ it("reads the workflow last run the loader adds", () => {+ expect(+ WORKFLOW_LIST_EXPORT_VALUES.lastRun({ lastRun: { status: "Succeeded" } })+ ).toBe("Succeeded");+ expect(WORKFLOW_LIST_EXPORT_VALUES.lastRun({ lastRun: null })).toBe("");+ });+});++describe("lists with per-page extras", () => {+ it.each(LISTS)("$route exports its extras in the background", (list) => {+ // The loader and the export run the same lookup from the registry.+ const lookup = /mapRows:\s*(with\w+)/.exec(read(list.route))?.[1];+ expect(lookup).toBeDefined();+ const registry = read(list.registry);+ expect(registry).toContain(`export async function ${lookup}`);+ expect(registry).toMatch(+ new RegExp(String.raw`exportRows:[\s\S]*?${lookup}\(rows, context\)`)+ );+ });++ it.each(LISTS)("$table has a column for every export value", (list) => {+ const table = read(list.table);+ for (const key of Object.keys(list.values)) {+ expect(table, key).toMatch(+ new RegExp(String.raw`(?:id|accessorKey): "${key}"`)+ );+ }+ });+});diff --git a/apps/erp/test/list-select-columns.test.ts b/apps/erp/test/list-select-columns.test.tsindex 43446d81ea..55470ecb36 100644--- a/apps/erp/test/list-select-columns.test.ts+++ b/apps/erp/test/list-select-columns.test.ts@@ -34,66 +34,78 @@ type Target = {constant: string;service: string;table: string;+ /** The list's `X_PAGING` constant in the same service file. */+ paging: string;};const TARGETS: Target[] = [{label: "parts",constant: "PARTS_LIST_COLUMNS",+ paging: "PARTS_PAGING",service: "app/modules/items/items.service.ts",table: "app/modules/items/ui/Parts/PartsTable.tsx"},{label: "materials",constant: "MATERIALS_LIST_COLUMNS",+ paging: "MATERIALS_PAGING",service: "app/modules/items/items.service.ts",table: "app/modules/items/ui/Materials/MaterialsTable.tsx"},{label: "tools",constant: "TOOLS_LIST_COLUMNS",+ paging: "TOOLS_PAGING",service: "app/modules/items/items.service.ts",table: "app/modules/items/ui/Tools/ToolsTable.tsx"},{label: "consumables",constant: "CONSUMABLES_LIST_COLUMNS",+ paging: "CONSUMABLES_PAGING",service: "app/modules/items/items.service.ts",table: "app/modules/items/ui/Consumables/ConsumablesTable.tsx"},{label: "services",constant: "SERVICES_LIST_COLUMNS",+ paging: "SERVICES_PAGING",service: "app/modules/items/items.service.ts",table: "app/modules/items/ui/Services/ServicesTable.tsx"},{label: "purchaseOrders",constant: "PURCHASE_ORDERS_LIST_COLUMNS",+ paging: "PURCHASE_ORDERS_PAGING",service: "app/modules/purchasing/purchasing.service.ts",table: "app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx"},{label: "quotes",constant: "QUOTES_LIST_COLUMNS",+ paging: "QUOTES_PAGING",service: "app/modules/sales/sales.service.ts",table: "app/modules/sales/ui/Quotes/QuotesTable.tsx"},{label: "salesOrders",constant: "SALES_ORDERS_LIST_COLUMNS",+ paging: "SALES_ORDERS_PAGING",service: "app/modules/sales/sales.service.ts",table: "app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx"},{label: "purchaseInvoices",constant: "PURCHASE_INVOICES_LIST_COLUMNS",+ paging: "PURCHASE_INVOICES_PAGING",service: "app/modules/invoicing/invoicing.service.ts",table: "app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx"},{label: "salesInvoices",constant: "SALES_INVOICES_LIST_COLUMNS",+ paging: "SALES_INVOICES_PAGING",service: "app/modules/invoicing/invoicing.service.ts",table: "app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx"}@@ -108,6 +120,35 @@ function selectedColumns(service: string, constant: string): string[] {return match[1].split(",");}+// A list whose explicit select is checked for its sort columns only: its+// table reads embedded records (`location.name`), not flat accessors.+const SORT_ONLY_TARGETS: Target[] = [+ {+ label: "fixedAssets",+ constant: "FIXED_ASSETS_LIST_COLUMNS",+ paging: "FIXED_ASSETS_PAGING",+ service: "app/modules/accounting/accounting.service.ts",+ table: "app/modules/accounting/ui/FixedAssets/FixedAssetsTable.tsx"+ }+];++/** The list-order columns of an `X_PAGING` constant (embedded-table sorts+ * excluded), and its id column. */+function pagingColumns(service: string, paging: string): string[] {+ const src = readFileSync(join(ROOT, service), "utf8");+ const match = src.match(+ new RegExp(`export const ${paging}: Paging = \\{([\\s\\S]*?)\\};`)+ );+ if (!match) throw new Error(`${paging} not found in ${service}`);+ const sorts = [...match[1].matchAll(/\{([^{}]*)\}/g)]+ .map((m) => m[1])+ .filter((sort) => !sort.includes("foreignTable"))+ .map((sort) => sort.match(/column:\s*"([^"]+)"/)?.[1])+ .filter((column): column is string => Boolean(column));+ const idColumn = match[1].match(/idColumn:\s*"([^"]+)"/)?.[1] ?? "id";+ return [...sorts, idColumn];+}+function declaredAccessorKeys(table: string): string[] {const src = readFileSync(join(ROOT, table), "utf8");return [...src.matchAll(/accessorKey:\s*"([^"]+)"/g)]@@ -144,3 +185,30 @@ describe("list endpoints select every column their table exports", () => {}});});++// `toPage` reads each sort column and the id from the last row of a page. A+// column missing from the select ends the list after page 1.+describe("list endpoints select the columns their cursor reads", () => {+ it.each([...TARGETS, ...SORT_ONLY_TARGETS])(+ "$label",+ ({ constant, service, paging }) => {+ const selected = new Set(selectedColumns(service, constant));+ const missing = pagingColumns(service, paging).filter(+ (column) => !selected.has(column)+ );+ expect(+ missing,+ `${constant} is missing the sort or id column(s) of ${paging}`+ ).toEqual([]);+ }+ );++ it("selects createdAt for fixed assets, a sort the URL can ask for", () => {+ expect(+ selectedColumns(+ "app/modules/accounting/accounting.service.ts",+ "FIXED_ASSETS_LIST_COLUMNS"+ )+ ).toContain("createdAt");+ });+});diff --git a/apps/erp/test/planning-action-scope.test.ts b/apps/erp/test/planning-action-scope.test.tsindex eabb85241a..99fed088f3 100644--- a/apps/erp/test/planning-action-scope.test.ts+++ b/apps/erp/test/planning-action-scope.test.ts@@ -7,7 +7,8 @@ import {actionsOfTypes,PLANNING_ACTIONS_COLUMN,PLANNING_ASSIGNEE_COLUMN,- resolvePlanningActionScope+ resolvePlanningActionScope,+ withPlanningActions} from "../app/modules/production/ui/Planning/planning-action-scope";describe("resolvePlanningActionScope", () => {@@ -143,3 +144,24 @@ describe("actionsOfTypes", () => {expect(actionsOfTypes(actions, ["Order"])).toEqual([]);});});++describe("withPlanningActions", () => {+ it("gives each row its own actions, and none to a row without any", () => {+ const actions = [+ { id: "a1", itemId: "item-1" },+ { id: "a2", itemId: "item-2" },+ { id: "a3", itemId: "item-1" },+ { id: "a4", itemId: "item-off-page" }+ ];+ expect(+ withPlanningActions(+ [{ id: "item-1" }, { id: "item-2" }, { id: "item-3" }],+ actions+ )+ ).toEqual([+ { id: "item-1", planningActions: [actions[0], actions[2]] },+ { id: "item-2", planningActions: [actions[1]] },+ { id: "item-3", planningActions: [] }+ ]);+ });+});diff --git a/docs/content/docs/building/architecture.mdx b/docs/content/docs/building/architecture.mdxindex 7fdd00f0e7..2efdfeb8d6 100644--- a/docs/content/docs/building/architecture.mdx+++ b/docs/content/docs/building/architecture.mdx@@ -263,8 +263,9 @@ such as reordering, inline edits, or deletion. Fetcher submissions still triggermenus, and layout primitives built on Radix UI [[19]](#g19) and Tailwind.- `apps/erp/app/components/`: app-level pieces. The big one is`components/Table/Table.tsx`, a generic TanStack Table implementation used by list screens. It handles sorting,- filtering, pagination, saved views, CSV import and export, column visibility, and inline editing. The server- performs pagination from URL search parameters.+ filtering, infinite scroll, saved views, CSV import and export, column visibility, and inline editing. The+ route loader returns the first 100 rows and a cursor. As the user scrolls, the table loads the next 100 rows+ from the same loader with `?after=<cursor>` and renders only the visible rows.**Client state** is limited. Shared reference lists use nanostores [[13]](#g13) and are refreshed by`RealtimeDataProvider`. Ephemeral UI state uses zustand [[29]](#g29). User and permission data comes from route loaders.diff --git a/docs/content/docs/reference/keyboard-shortcuts.mdx b/docs/content/docs/reference/keyboard-shortcuts.mdxindex 8ce93bb8b5..90d253f478 100644--- a/docs/content/docs/reference/keyboard-shortcuts.mdx+++ b/docs/content/docs/reference/keyboard-shortcuts.mdx@@ -23,9 +23,9 @@ Press **G**, then a letter, within about a second and a half. The sidebar showsItems, Invoicing, and Inventory all start with I, so Items is **T** and Invoicing is **V**. A shortcut only works for a module you can see in your sidebar: one you have hidden, or have no permission for, does nothing.-## Move through tables+## From a list page-On any paged table, **←** goes to the previous page and **→** to the next. The Previous and Next buttons show the key when you hover them. **N** opens a new record from a list page, and **⌘K** (Ctrl+K on Windows) opens search from anywhere.+**N** opens a new record from a list page, and **⌘K** (Ctrl+K on Windows) opens search from anywhere.## Act from a menudiff --git a/packages/ee/src/accounting/core/operations.ts b/packages/ee/src/accounting/core/operations.tsindex 194c64ba37..e41bbf7a30 100644--- a/packages/ee/src/accounting/core/operations.ts+++ b/packages/ee/src/accounting/core/operations.ts@@ -789,12 +789,20 @@ export async function transitionOperation(return { data: updated.data as SyncOperation, error: null };}+// A value quoted for a PostgREST `or=(...)` filter: the escape of+// `apps/erp/app/utils/cursor.ts` (`quoteFilterValue`), which ee cannot import.+function quoteFilterValue(value: string) {+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;+}+/*** List sync operations for the activity/error-inbox UI, newest first, with* an optional status filter and offset pagination. `count` is the total for* the current filter. `entityType` narrows to one entity type — the* consolidation and reconciliation crons page journalEntry operations- * without wading through every other entity's history.+ * without wading through every other entity's history. `after` reads the+ * rows after a previous page's last row instead (keyset on createdAt DESC,+ * id), like `getSyncOperationsExportPage`.*/export async function getSyncOperations(client: SupabaseClient<Database>,@@ -805,6 +813,7 @@ export async function getSyncOperations(entityType?: string;limit?: number;offset?: number;+ after?: SyncOperationCursor;}): Promise<{data: SyncOperation[];@@ -815,7 +824,11 @@ export async function getSyncOperations(const offset = args.offset ?? 0;let query = syncOperationTable(client)- .select("*", { count: "exact" })+ // Only the first page counts: a later page (`after`, or an offset) does+ // not need the total again.+ .select("*", {+ count: args.after || offset > 0 ? undefined : "exact"+ }).eq("companyId", args.companyId).eq("integration", args.integration);@@ -829,8 +842,21 @@ export async function getSyncOperations(query = query.eq("entityType", args.entityType);}+ if (args.after) {+ // Quoted: a timestamp carries `.`, `:` and `+`, all reserved in an+ // or-filter. The cursor comes from the URL, so a `"` or `\` in it is+ // escaped too.+ const createdAt = quoteFilterValue(args.after.createdAt);+ const id = quoteFilterValue(args.after.id);+ query = query.or(+ `createdAt.lt.${createdAt},and(createdAt.eq.${createdAt},id.gt.${id})`+ );+ }++ // `id` ascending breaks createdAt ties, so every row has one place.const result = await query.order("createdAt", { ascending: false })+ .order("id", { ascending: true }).range(offset, offset + limit - 1);if (result.error) {diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.mdindex 5e561be7a8..2494971730 100644--- a/packages/jobs/AGENTS.md+++ b/packages/jobs/AGENTS.md@@ -43,7 +43,7 @@ pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id> # MRP +|---------|----------|| `.` | `trigger`, `batchTrigger`, `Events`, Jira/Linear webhook schemas || `./events` | `Events` type |-| `./inngest` | Inngest client plus workflow dispatch/manual-run server seams |+| `./inngest` | Inngest client plus workflow dispatch/manual-run server seams; the table-job seams for the ERP: `setTableJobHandlers`, `takeTableJobLock` / `releaseTableJobLock`, `tableExportStorageKey`, `tempStagingStorage`, `TABLE_JOB_PAGE_SIZE` || `./backups` | Import-light backup catalog, scope, and compatibility helpers |## Durable Entry Points@@ -69,6 +69,8 @@ pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id> # MRP +| `notification-digest` | `carbon/notification-digest.process` (sent by the `notification-digest-sweeper` pg_cron job every 15 min, only when `util.notification_digest_has_work()`) | Roll unread notifications into one digest per user, company and topic || `workflow-run-retention` | `carbon/workflow-run-retention.process` (sent by the `workflow-run-retention-sweeper` pg_cron job at 04:00 UTC, only when `util.workflow_run_retention_has_work()`) | Reap stale runs, compact and drop step detail, purge old run headers || `embedding-queue` | `carbon/embedding-queue.process` (sent by the 10 s `process-embeddings` pg_cron doorbell while visible messages wait) | Drain the pgmq `embedding_jobs` queue and write embeddings |+| `table-export` | `carbon/table-export` (`api+/table.export.ts`) | Background CSV export of a registered ERP list past 1,000 rows. One run per company. Steps of at most 10,000 rows write part files to `temp-staging`; `compose` streams them into `{companyId}/exports/{userId}/{exportId}.csv`. Stops at 100,000 rows or 200 MB. Step bodies in `src/table-jobs/export-run.ts` |+| `table-bulk-action` | `carbon/table-bulk-action` (`startTableBulkAction`, ERP `utils/table-jobs.server.ts`) | A bulk action on every matching row of a registered list, or on selected rows too many for one request (`ids` in the event, `startSelectedBulkAction`). One run per company, `retries: 0`. Collect steps store the ids (10,000 rows per step) in `temp-staging`; a selected-rows run stores its ids in one step instead. Apply steps run the action on one slice each, 100 ids per call, passing each call's `carry` to the next. Step bodies in `src/table-jobs/bulk-run.ts` || `mrp` | `*/15 * * * *` | Scheduled MRP. Each tick plans only the companies that are DUE — every 3 hours (UTC) by default, or once a day at `companySettings.mrpRunTime` on the company's clock (`isMrpDue` / `mrpTick`) — and have planning work (`companiesWithPlanningWork`), both in `scheduled/mrp-companies.ts`; one `step.run` per company |## Safety Notes@@ -78,6 +80,7 @@ pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id> # MRP +- Jobs that post or recalculate (`tasks/post-transaction.ts`, `tasks/recalculate.ts`, the Ramp families, the invoice automation in `src/invoicing/automate-invoice.ts`) call `@carbon/server-functions` directly, in-process — not over HTTP.- `src/inngest/functions/events/sync-tables.ts` is the import-light table→accounting-entity map. `subscriptions-mapping.test.ts` pins it to provider subscriptions/syncers.- `src/inngest/functions/integrations/ramp-sync.ts` owns step ids, ordering, result aggregation, and notification only; changing a family module must preserve that durable public shape.+- `src/table-jobs/` holds what both table jobs share: paging (`paging.ts`), the per-company Redis lock as Lua scripts (`lock.ts`), storage keys (`storage.ts`) and `notifyTableJobUser` with an Inngest event id per outcome (`notify.ts`). `packages/jobs` cannot import `~/modules`, so the ERP fills `TableJobHandlers` with `setTableJobHandlers` in `api+/inngest.ts`. See `.claude/rules/table-csv-export.md` and `.claude/rules/table-infinite-scroll.md`.- `src/workflows/actions/dispatcher.ts` is filled by `apps/erp/app/routes/api+/inngest.ts` with the canonical `callOperation` seam. Missing registration fails cleanly.- `src/workflows/engine/log.ts` redacts secret/token/password/header values before persisting step input.- Bare `tsx` scripts cannot rely on Vite's CJS/ESM interop. Keep runtime imports from packages without `"type":"module"` out of script dependency chains; type-only imports are safe.diff --git a/packages/jobs/src/inngest/functions/notifications/content.ts b/packages/jobs/src/inngest/functions/notifications/content.tsindex 7bef53d5e0..27801633c5 100644--- a/packages/jobs/src/inngest/functions/notifications/content.ts+++ b/packages/jobs/src/inngest/functions/notifications/content.ts@@ -1397,6 +1397,25 @@ async function buildEventContent(};}+ // Payload-carried like IntegrationSync: the table-export job writes the+ // outcome as `title` and the row count as `body`; documentId is the export+ // id, not a record, so there is nothing to look up.+ case NotificationEvent.TableExport: {+ return {+ description: opts?.title ?? "Your export is ready",+ details: opts?.body ? [{ label: "Detail", value: opts.body }] : []+ };+ }++ // Payload-carried like TableExport: the bulk-action job writes the outcome+ // and the counts as `title`; documentId is the run id, not a record.+ case NotificationEvent.TableBulkAction: {+ return {+ description: opts?.title ?? "Your bulk action is done",+ details: opts?.body ? [{ label: "Detail", value: opts.body }] : []+ };+ }+// The recurring-billing job says which date is coming up in `body`// ("notice must be given by Jun 30, 2027"); the lease names the rest.case NotificationEvent.LeaseCriticalDate: {diff --git a/packages/jobs/src/inngest/functions/notifications/notify.ts b/packages/jobs/src/inngest/functions/notifications/notify.tsindex b35881ba3d..b768090d1e 100644--- a/packages/jobs/src/inngest/functions/notifications/notify.ts+++ b/packages/jobs/src/inngest/functions/notifications/notify.ts@@ -233,7 +233,16 @@ const defaultDestinations: Partial<// email per sweep cycle would be noise. Browser push still follows in-app,// so the integration's last editor gets a push every sweep (30 min) until// the failures clear — deliberate: push mirrors the bell exactly.- [NotificationEvent.IntegrationSync]: [NotificationDestination.InApp]+ [NotificationEvent.IntegrationSync]: [NotificationDestination.InApp],+ // One per export the user asked for; the email link downloads the file. The+ // job sends a failure in-app only, since there is no file to link to.+ [NotificationEvent.TableExport]: [+ NotificationDestination.InApp,+ NotificationDestination.Email+ ],+ // In-app only: the counts are the whole message, and there is no file or+ // record for an email to link to.+ [NotificationEvent.TableBulkAction]: [NotificationDestination.InApp]};export const notifyFunction = inngest.createFunction(diff --git a/packages/jobs/src/inngest/functions/tasks/index.ts b/packages/jobs/src/inngest/functions/tasks/index.tsindex 8882b069b7..57c364b1ec 100644--- a/packages/jobs/src/inngest/functions/tasks/index.ts+++ b/packages/jobs/src/inngest/functions/tasks/index.ts@@ -26,5 +26,7 @@ export { postTransactionFunction } from "./post-transaction";export { printJobFunction } from "./print-job";export { printJobDeliverFunction } from "./print-job-deliver";export { recalculateFunction } from "./recalculate";+export { tableBulkActionFunction } from "./table-bulk-action";+export { tableExportFunction } from "./table-export";export { updatePermissionsFunction } from "./update-permissions";export { userAdminFunction } from "./user-admin";diff --git a/packages/jobs/src/inngest/functions/tasks/table-bulk-action.ts b/packages/jobs/src/inngest/functions/tasks/table-bulk-action.tsnew file mode 100644index 0000000000..547c18067a--- /dev/null+++ b/packages/jobs/src/inngest/functions/tasks/table-bulk-action.ts@@ -0,0 +1,250 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { getLogger } from "@carbon/logger";+import { NotificationEvent } from "@carbon/notifications";+import {+ addBulkActionCounts,+ BULK_CHUNK_SIZE,+ bulkActionTitle,+ bulkActionTruncatedBody,+ DEFAULT_BULK_IDS_PER_STEP,+ MAX_BULK_ROWS,+ NO_BULK_COUNTS,+ planIdSlices+} from "../../../table-jobs/bulk";+import {+ applyIdSlice,+ collectIds,+ storeSelectedIds+} from "../../../table-jobs/bulk-run";+import {+ requireTableJobHandlers,+ type TableBulkAction,+ type TableBulkActionCarry,+ type TableJobContext+} from "../../../table-jobs/handlers";+import {+ extendTableJobLock,+ releaseTableJobLock+} from "../../../table-jobs/lock";+import { notifyTableJobUser } from "../../../table-jobs/notify";+import { TABLE_JOB_ROWS_PER_STEP } from "../../../table-jobs/paging";+import {+ tableBulkIdsKey,+ tempStagingStorage+} from "../../../table-jobs/storage";+import { inngest } from "../../client";++const log = getLogger("jobs", "table-bulk-action");++function deps() {+ return {+ handlers: requireTableJobHandlers("Table bulk actions"),+ storage: tempStagingStorage()+ };+}++/** Deletes the id files of a run; the nightly cleanup is the backstop. The+ * files are numbered from 0, one per collect step. */+async function removeIdFiles(args: {+ companyId: string;+ bulkActionId: string;+ files: number;+}) {+ const files = Array.from({ length: args.files }, (_, file) =>+ tableBulkIdsKey(args.companyId, args.bulkActionId, file)+ );+ try {+ await tempStagingStorage().remove(files);+ } catch (error) {+ log.error("Failed to delete the id files of a bulk action", {+ companyId: args.companyId,+ bulkActionId: args.bulkActionId,+ error+ });+ }+}++// TODO(scale): this job runs inside the ERP containers (api+/inngest.ts) and shares+// CPU with web requests. Move table export/bulk jobs to a dedicated worker service+// before large tenants run many 100k-row bulk actions at the same time.+export const tableBulkActionFunction = inngest.createFunction(+ {+ id: "table-bulk-action",+ // No retry: a second attempt of an apply step would run its chunks again,+ // and not every action is safe to repeat (Send Invite emails each user).+ // A failed chunk is counted as failed instead of failing the run.+ retries: 0,+ concurrency: { key: "event.data.companyId", limit: 1 },+ onFailure: async ({ event, error }) => {+ const { companyId, userId, bulkActionId, actionKey, actionLabel } =+ event.data.event.data;+ log.error("Table bulk action failed", {+ companyId,+ actionKey,+ bulkActionId,+ error: error.message+ });+ try {+ await notifyTableJobUser({+ event: NotificationEvent.TableBulkAction,+ companyId,+ userId,+ documentId: `failed:${bulkActionId}`,+ title: `${actionLabel} could not be completed`,+ body: "Some rows may have changed. Check the list, then try again.",+ dedupeId: `table-bulk-action:${bulkActionId}:failed`+ });+ } catch (notifyError) {+ log.error("Failed to send the bulk action failure notification", {+ companyId,+ error: notifyError+ });+ }+ // The run state is gone here: remove every file a run of this size+ // could have written.+ const maxRows = event.data.event.data.maxRows ?? MAX_BULK_ROWS;+ await removeIdFiles({+ companyId,+ bulkActionId,+ files: Math.ceil(maxRows / TABLE_JOB_ROWS_PER_STEP)+ });+ await releaseTableJobLock("bulk", companyId, bulkActionId);+ }+ },+ { event: "carbon/table-bulk-action" },+ async ({ event, step }) => {+ const {+ companyId,+ userId,+ bulkActionId,+ actionKey,+ actionLabel,+ params,+ listKey,+ search,+ ids: selectedIds+ } = event.data;+ const maxRows = event.data.maxRows ?? MAX_BULK_ROWS;+ const idsPerStep = event.data.idsPerStep ?? DEFAULT_BULK_IDS_PER_STEP;+ const context: TableJobContext = { companyId, userId };+ const action: TableBulkAction = { key: actionKey, params };++ // The route checked the permissions; read them again in case they changed+ // while the run waited in the company's queue.+ const allowed = await step.run("check-permission", () =>+ requireTableJobHandlers("Table bulk actions").canRunBulkAction(+ listKey,+ action,+ context+ )+ );++ if (!allowed) {+ await step.run("notify-denied", () =>+ notifyTableJobUser({+ event: NotificationEvent.TableBulkAction,+ companyId,+ userId,+ documentId: `failed:${bulkActionId}`,+ title: `${actionLabel} did not run`,+ body: "You no longer have permission to do this.",+ dedupeId: `table-bulk-action:${bulkActionId}:denied`+ })+ );+ await step.run("release-lock", () =>+ releaseTableJobLock("bulk", companyId, bulkActionId)+ );+ return { ran: false as const };+ }++ // 1. Read every matching id first, 10,000 rows per step, one file per+ // step. A step returns counts only: the ids stay out of the run state.+ // A run for selected rows stores those ids as its one file instead.+ const idsPerFile: number[] = [];+ let truncated = false;+ if (selectedIds) {+ const stored = await step.run("store-selected-ids", async () => {+ await extendTableJobLock("bulk", companyId, bulkActionId);+ return storeSelectedIds(deps(), {+ ids: selectedIds,+ maxRows,+ key: tableBulkIdsKey(companyId, bulkActionId, 0)+ });+ });+ idsPerFile.push(stored.ids);+ truncated = stored.truncated;+ } else {+ let cursor: string | null = null;+ let rows = 0;+ for (let file = 0; ; file++) {+ const key = tableBulkIdsKey(companyId, bulkActionId, file);+ const collected = await step.run(`collect-ids-${file}`, async () => {+ await extendTableJobLock("bulk", companyId, bulkActionId);+ return collectIds(deps(), {+ context,+ listKey,+ search,+ cursor,+ rowsBefore: rows,+ maxRows,+ key+ });+ });+ idsPerFile.push(collected.ids);+ rows += collected.rows;+ truncated = collected.truncated;+ cursor = collected.nextCursor;+ if (!cursor) break;+ }+ }++ // 2. Act on the ids, one step per slice of `idsPerStep`. The counts are+ // summed here, outside the steps, from their stored results.+ let counts = NO_BULK_COUNTS;+ // What one slice hands the next (Jobs Release: the PO each supplier went+ // on). It comes from the stored step results, so a replay rebuilds it.+ let carry: TableBulkActionCarry | undefined;+ for (const slice of planIdSlices(idsPerFile, idsPerStep)) {+ const result = await step.run(+ `apply-${slice.file}-${slice.start}`,+ async () => {+ await extendTableJobLock("bulk", companyId, bulkActionId);+ return applyIdSlice(deps(), {+ context,+ action,+ key: tableBulkIdsKey(companyId, bulkActionId, slice.file),+ start: slice.start,+ end: slice.end,+ chunkSize: Math.min(idsPerStep, BULK_CHUNK_SIZE),+ carry+ });+ }+ );+ counts = addBulkActionCounts(counts, result);+ carry = (result.carry as TableBulkActionCarry | undefined) ?? carry;+ }++ await step.run("notify", () =>+ notifyTableJobUser({+ event: NotificationEvent.TableBulkAction,+ companyId,+ userId,+ documentId: bulkActionId,+ title: bulkActionTitle(actionLabel, counts),+ body: truncated ? bulkActionTruncatedBody(maxRows) : undefined,+ dedupeId: `table-bulk-action:${bulkActionId}:done`+ })+ );++ await step.run("remove-ids", () =>+ removeIdFiles({ companyId, bulkActionId, files: idsPerFile.length })+ );+ await step.run("release-lock", () =>+ releaseTableJobLock("bulk", companyId, bulkActionId)+ );+ return { ran: true as const, ...counts, truncated };+ }+);diff --git a/packages/jobs/src/inngest/functions/tasks/table-export.ts b/packages/jobs/src/inngest/functions/tasks/table-export.tsnew file mode 100644index 0000000000..6e7c3e1937--- /dev/null+++ b/packages/jobs/src/inngest/functions/tasks/table-export.ts@@ -0,0 +1,193 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { getLogger } from "@carbon/logger";+import { NotificationEvent } from "@carbon/notifications";+import { MAX_EXPORT_ROWS } from "../../../table-jobs/csv";+import {+ composeExport,+ type ExportDeps,+ writeExportPart+} from "../../../table-jobs/export-run";+import {+ requireTableJobHandlers,+ type TableJobContext+} from "../../../table-jobs/handlers";+import {+ extendTableJobLock,+ releaseTableJobLock+} from "../../../table-jobs/lock";+import { notifyTableJobUser } from "../../../table-jobs/notify";+import { TABLE_JOB_ROWS_PER_STEP } from "../../../table-jobs/paging";+import {+ type TableJobStorage,+ tableExportPartKey,+ tableExportStorageKey,+ tempStagingStorage+} from "../../../table-jobs/storage";+import { inngest } from "../../client";++const log = getLogger("jobs", "table-export");++const rowCount = new Intl.NumberFormat("en-US");++function deps(): ExportDeps {+ return {+ handlers: requireTableJobHandlers("Table export"),+ storage: tempStagingStorage()+ };+}++/** Deletes the parts of a failed export; the nightly cleanup is the backstop.+ * The parts are numbered from 0, one per step of `TABLE_JOB_ROWS_PER_STEP`. */+async function removeParts(+ storage: TableJobStorage,+ args: { companyId: string; userId: string; exportId: string }+) {+ const keys = Array.from(+ { length: MAX_EXPORT_ROWS / TABLE_JOB_ROWS_PER_STEP },+ (_, part) =>+ tableExportPartKey(args.companyId, args.userId, args.exportId, part)+ );+ try {+ await storage.remove(keys);+ } catch (error) {+ log.error("Failed to delete the parts of a failed export", {+ companyId: args.companyId,+ exportId: args.exportId,+ error+ });+ }+}++// TODO(scale): this job runs inside the ERP containers (api+/inngest.ts) and shares+// CPU with web requests. Move table export/bulk jobs to a dedicated worker service+// before large tenants run many 100k-row exports at the same time.+export const tableExportFunction = inngest.createFunction(+ {+ id: "table-export",+ // Every step is safe to repeat: a part is written again under the same+ // key, and the notification carries an event id Inngest de-duplicates.+ retries: 1,+ concurrency: { key: "event.data.companyId", limit: 1 },+ onFailure: async ({ event, error }) => {+ const { companyId, userId, exportId, listKey } = event.data.event.data;+ log.error("Table export failed", {+ companyId,+ listKey,+ exportId,+ error: error.message+ });+ try {+ await notifyTableJobUser({+ event: NotificationEvent.TableExport,+ companyId,+ userId,+ documentId: `failed:${exportId}`,+ title: "Your export could not be completed",+ body: "Try again. If it fails again, filter the list to fewer rows.",+ inAppOnly: true,+ dedupeId: `table-export:${exportId}:failed`+ });+ } catch (notifyError) {+ log.error("Failed to send the export failure notification", {+ companyId,+ error: notifyError+ });+ }+ await removeParts(tempStagingStorage(), { companyId, userId, exportId });+ await releaseTableJobLock("export", companyId, exportId);+ }+ },+ { event: "carbon/table-export" },+ async ({ event, step }) => {+ const { companyId, userId, exportId, listKey, search, columns } =+ event.data;+ const context: TableJobContext = { companyId, userId };++ // The route checked the permission; read it again in case it changed+ // while the run waited in the company's queue.+ const allowed = await step.run("check-permission", () =>+ requireTableJobHandlers("Table export").canReadList(listKey, context)+ );++ if (!allowed) {+ await step.run("notify-denied", () =>+ notifyTableJobUser({+ event: NotificationEvent.TableExport,+ companyId,+ userId,+ documentId: `failed:${exportId}`,+ title: "Your export did not run",+ body: "You no longer have access to this list.",+ inAppOnly: true,+ dedupeId: `table-export:${exportId}:denied`+ })+ );+ await step.run("release-lock", () =>+ releaseTableJobLock("export", companyId, exportId)+ );+ return { exported: false as const };+ }++ // One step per 10,000 rows: a step is one HTTP request, and the load+ // balancer cuts a request at 600 s.+ const partKeys: string[] = [];+ let cursor: string | null = null;+ let rows = 0;+ let bytes = 0;+ let truncated = false;+ for (let part = 0; ; part++) {+ const key = tableExportPartKey(companyId, userId, exportId, part);+ const result = await step.run(`write-part-${part}`, async () => {+ await extendTableJobLock("export", companyId, exportId);+ return writeExportPart(deps(), {+ context,+ listKey,+ search,+ columns,+ cursor,+ part,+ rowsBefore: rows,+ bytesBefore: bytes,+ key+ });+ });+ partKeys.push(key);+ rows += result.rows;+ bytes += result.bytes;+ truncated = result.truncated;+ cursor = result.nextCursor;+ if (!cursor) break;+ }++ await step.run("compose", () =>+ composeExport(deps(), {+ partKeys,+ key: tableExportStorageKey(companyId, userId, exportId)+ })+ );++ await step.run("notify", () =>+ notifyTableJobUser({+ event: NotificationEvent.TableExport,+ companyId,+ userId,+ documentId: exportId,+ title: truncated+ ? `Your export is ready (first ${rowCount.format(rows)} rows)`+ : "Your export is ready",+ body: truncated+ ? `The list has more than ${rowCount.format(rows)} rows. Filter it to export the rest.`+ : `${rowCount.format(rows)} ${rows === 1 ? "row" : "rows"}`,+ dedupeId: `table-export:${exportId}:ready`+ })+ );++ await step.run("release-lock", () =>+ releaseTableJobLock("export", companyId, exportId)+ );+ return { exported: true as const, rows, truncated };+ }+);diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.tsindex 454362f1c1..a9824807aa 100644--- a/packages/jobs/src/inngest/index.ts+++ b/packages/jobs/src/inngest/index.ts@@ -9,6 +9,27 @@ import { Edition } from "@carbon/utils";// Re-export the inngest client and helpers+export type {+ TableBulkAction,+ TableBulkActionCarry,+ TableBulkActionCounts,+ TableBulkActionResult,+ TableJobContext,+ TableJobHandlers,+ TableJobKind,+ TableJobPage+} from "../table-jobs/handlers.ts";+export { setTableJobHandlers } from "../table-jobs/handlers.ts";+export type { TableJobLock } from "../table-jobs/lock.ts";+export {+ releaseTableJobLock,+ takeTableJobLock+} from "../table-jobs/lock.ts";+export { TABLE_JOB_PAGE_SIZE } from "../table-jobs/paging.ts";+export {+ tableExportStorageKey,+ tempStagingStorage+} from "../table-jobs/storage.ts";// Server-only on purpose: the app bundle imports `@carbon/jobs`, not this subpath.export type {DispatchContext,@@ -103,6 +124,8 @@ import {printJobDeliverFunction,printJobFunction,recalculateFunction,+ tableBulkActionFunction,+ tableExportFunction,updatePermissionsFunction,userAdminFunction} from "./functions/tasks";@@ -157,6 +180,8 @@ export const functions = [printJobFunction,printJobDeliverFunction,changelogDispatchFunction,+ tableExportFunction,+ tableBulkActionFunction,// ScheduledcleanupFunction,dispatchFunction,diff --git a/packages/jobs/src/table-jobs/bulk-run.ts b/packages/jobs/src/table-jobs/bulk-run.tsnew file mode 100644index 0000000000..abe0033ed2--- /dev/null+++ b/packages/jobs/src/table-jobs/bulk-run.ts@@ -0,0 +1,195 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { getLogger } from "@carbon/logger";+import { chunkArray } from "@carbon/utils";+import {+ addBulkActionCounts,+ BULK_CHUNK_SIZE,+ collectRowIds,+ NO_BULK_COUNTS+} from "./bulk";+import type {+ TableBulkAction,+ TableBulkActionCarry,+ TableBulkActionResult,+ TableJobContext,+ TableJobHandlers+} from "./handlers";+import { readListPages } from "./paging";+import type { TableJobStorage } from "./storage";++/**+ * The step bodies of the background bulk action (`table-bulk-action.ts`).+ * Collect steps read the matching ids, up to 10,000 per step, and store each+ * step's ids as one file. Apply steps each read one slice of a file and run+ * the action on it, 100 ids per call. The function only orders the steps, so+ * these run, and are tested, without Inngest.+ */++const log = getLogger("jobs", "table-bulk-action");++export type CollectIdsResult = {+ /** Ids stored in this step's file. */+ ids: number;+ /** Rows this step read (counted against the run's row limit). */+ rows: number;+ nextCursor: string | null;+ truncated: boolean;+};++/**+ * Reads up to 10,000 rows from `cursor` and stores their ids at `key`, in+ * list order, without duplicates within the step. Reading first keeps the run+ * correct when the action changes a sort or filter column: a row the action+ * moved behind the cursor is never read again.+ */+export async function collectIds(+ deps: {+ handlers: Pick<TableJobHandlers, "fetchListPage" | "listIdColumn">;+ storage: Pick<TableJobStorage, "upload">;+ },+ args: {+ context: TableJobContext;+ listKey: string;+ search: string;+ cursor: string | null;+ rowsBefore: number;+ maxRows: number;+ key: string;+ }+): Promise<CollectIdsResult> {+ const idColumn = deps.handlers.listIdColumn(args.listKey);+ const ids = new Set<string>();+ const read = await readListPages({+ handlers: deps.handlers,+ listKey: args.listKey,+ context: args.context,+ search: args.search,+ cursor: args.cursor,+ rowsBefore: args.rowsBefore,+ maxRows: args.maxRows,+ onPage: (rows) => {+ collectRowIds(ids, rows, idColumn);+ }+ });+ await deps.storage.upload(+ args.key,+ JSON.stringify([...ids]),+ "application/json"+ );+ return {+ ids: ids.size,+ rows: read.rows,+ nextCursor: read.nextCursor,+ truncated: read.truncated+ };+}++/**+ * Stores the ids the user selected as the run's only id file, in place of the+ * collect steps: unique, non-empty, and at most `maxRows` of them.+ */+export async function storeSelectedIds(+ deps: { storage: Pick<TableJobStorage, "upload"> },+ args: { ids: string[]; maxRows: number; key: string }+): Promise<{ ids: number; truncated: boolean }> {+ const unique = [...new Set(args.ids.filter(Boolean))];+ const kept = unique.slice(0, args.maxRows);+ await deps.storage.upload(args.key, JSON.stringify(kept), "application/json");+ return { ids: kept.length, truncated: kept.length < unique.length };+}++/** The ids a collect step stored, or null when the file is not a list of+ * strings. */+export function parseIdFile(bytes: Uint8Array): string[] | null {+ try {+ const parsed: unknown = JSON.parse(new TextDecoder().decode(bytes));+ return Array.isArray(parsed) && parsed.every((id) => typeof id === "string")+ ? parsed+ : null;+ } catch {+ return null;+ }+}++/**+ * Runs the action on ids `start` to `end` of the file at `key`, `chunkSize`+ * ids per call (at most 100). A chunk that throws counts as failed and the+ * rest still run; a file that cannot be read counts the whole slice as+ * failed. So the step never throws, and the run goes on to the next slice.+ * `carry` goes from chunk to chunk; the slice returns the last one, for the+ * next slice.+ */+export async function applyIdSlice(+ deps: {+ handlers: Pick<TableJobHandlers, "runBulkAction">;+ storage: Pick<TableJobStorage, "download">;+ },+ args: {+ context: TableJobContext;+ action: TableBulkAction;+ key: string;+ start: number;+ end: number;+ chunkSize: number;+ carry?: TableBulkActionCarry;+ }+): Promise<TableBulkActionResult> {+ const sliceSize = args.end - args.start;+ let ids: string[] | null = null;+ try {+ ids = parseIdFile(await deps.storage.download(args.key));+ if (!ids) {+ log.error("The ids file of a bulk action is not a list of ids", {+ companyId: args.context.companyId,+ key: args.key+ });+ }+ } catch (error) {+ log.error("Failed to read the ids of a bulk action", {+ companyId: args.context.companyId,+ key: args.key,+ error+ });+ }+ if (!ids)+ return withCarry({ done: 0, skipped: 0, failed: sliceSize }, args.carry);++ const size = Math.min(Math.max(1, args.chunkSize), BULK_CHUNK_SIZE);+ let counts = NO_BULK_COUNTS;+ let carry = args.carry;+ for (const chunk of chunkArray(ids.slice(args.start, args.end), size)) {+ try {+ const result = await deps.handlers.runBulkAction(+ args.action,+ chunk,+ args.context,+ carry+ );+ counts = addBulkActionCounts(counts, result);+ carry = result.carry ?? carry;+ } catch (error) {+ // One chunk's failure must not stop the rest: count it and go on.+ log.error("A chunk of the bulk action failed", {+ companyId: args.context.companyId,+ actionKey: args.action.key,+ error+ });+ counts = addBulkActionCounts(counts, {+ done: 0,+ skipped: 0,+ failed: chunk.length+ });+ }+ }+ return withCarry(counts, carry);+}++function withCarry(+ counts: TableBulkActionResult,+ carry: TableBulkActionCarry | undefined+): TableBulkActionResult {+ return carry === undefined ? counts : { ...counts, carry };+}diff --git a/packages/jobs/src/table-jobs/bulk.test.ts b/packages/jobs/src/table-jobs/bulk.test.tsnew file mode 100644index 0000000000..323b8690de--- /dev/null+++ b/packages/jobs/src/table-jobs/bulk.test.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ addBulkActionCounts,+ bulkActionTitle,+ bulkActionTruncatedBody,+ collectRowIds,+ NO_BULK_COUNTS,+ planIdSlices+} from "./bulk";++describe("addBulkActionCounts", () => {+ it("sums each count", () => {+ expect(+ addBulkActionCounts(+ { done: 1, skipped: 2, failed: 3 },+ { done: 10, skipped: 20, failed: 30 }+ )+ ).toEqual({ done: 11, skipped: 22, failed: 33 });+ });++ it("starts from zero", () => {+ expect(+ addBulkActionCounts(NO_BULK_COUNTS, { done: 4, skipped: 0, failed: 1 })+ ).toEqual({ done: 4, skipped: 0, failed: 1 });+ });+});++describe("collectRowIds", () => {+ it("reads the id column and keeps the page order", () => {+ const ids = new Set<string>();+ collectRowIds(ids, [{ itemId: "b" }, { itemId: "a" }], "itemId");+ expect([...ids]).toEqual(["b", "a"]);+ });++ it("drops rows without an id and ids it already holds", () => {+ const ids = new Set<string>(["a"]);+ collectRowIds(+ ids,+ [{ id: "a" }, { id: null }, { id: "" }, {}, { id: 7 }, { id: "c" }],+ "id"+ );+ expect([...ids]).toEqual(["a", "7", "c"]);+ });+});++describe("bulkActionTitle", () => {+ it("names the action and every count", () => {+ expect(+ bulkActionTitle("Release jobs", { done: 1200, skipped: 3, failed: 0 })+ ).toBe("Release jobs finished: 1,200 done, 3 skipped, 0 failed");+ });+});++describe("bulkActionTruncatedBody", () => {+ it("names the action's own row limit", () => {+ expect(bulkActionTruncatedBody(2000)).toContain("first 2,000");+ });+});++describe("planIdSlices", () => {+ it("cuts each file into slices of at most idsPerStep", () => {+ expect(planIdSlices([2500, 10], 1000)).toEqual([+ { file: 0, start: 0, end: 1000 },+ { file: 0, start: 1000, end: 2000 },+ { file: 0, start: 2000, end: 2500 },+ { file: 1, start: 0, end: 10 }+ ]);+ });++ it("skips an empty file", () => {+ expect(planIdSlices([0, 3], 25)).toEqual([{ file: 1, start: 0, end: 3 }]);+ });+});diff --git a/packages/jobs/src/table-jobs/bulk.ts b/packages/jobs/src/table-jobs/bulk.tsnew file mode 100644index 0000000000..3c100428e6--- /dev/null+++ b/packages/jobs/src/table-jobs/bulk.ts@@ -0,0 +1,96 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { TableBulkActionCounts } from "./handlers";++/**+ * Pure parts of the background bulk action: how the job reads ids, sums the+ * counts and words the notification.+ */++/** Ids per `runBulkAction` call: an `.in()` filter rides in the request URL. */+export const BULK_CHUNK_SIZE = 100;++/** The most rows one run acts on, unless the action sets a lower limit+ * (`maxRows` on the event). The run acts on the first rows above it. */+export const MAX_BULK_ROWS = 100_000;++/** Ids one apply step acts on, unless the action sets fewer (`idsPerStep` on+ * the event): an action that does more per row gets smaller steps, so one+ * step stays well below the load balancer's 600 s. */+export const DEFAULT_BULK_IDS_PER_STEP = 1_000;++export const NO_BULK_COUNTS: TableBulkActionCounts = {+ done: 0,+ skipped: 0,+ failed: 0+};++export function addBulkActionCounts(+ a: TableBulkActionCounts,+ b: TableBulkActionCounts+): TableBulkActionCounts {+ return {+ done: a.done + b.done,+ skipped: a.skipped + b.skipped,+ failed: a.failed + b.failed+ };+}++/**+ * Adds the string ids of a page to `ids`, in page order. A row without an id+ * is left out. The Set drops a row that an earlier page already held.+ */+export function collectRowIds(+ ids: Set<string>,+ rows: Record<string, unknown>[],+ idColumn: string+): void {+ for (const row of rows) {+ const id = row[idColumn];+ if (typeof id === "string" && id.length > 0) ids.add(id);+ else if (typeof id === "number") ids.add(String(id));+ }+}++const count = new Intl.NumberFormat("en-US");++/** The notification title: the action, then the counts. The topbar shows+ * the title only, so the counts must be in it. */+export function bulkActionTitle(+ actionLabel: string,+ counts: TableBulkActionCounts+): string {+ return `${actionLabel} finished: ${count.format(counts.done)} done, ${count.format(+ counts.skipped+ )} skipped, ${count.format(counts.failed)} failed`;+}++/** The notification body when the run stopped at its row limit. */+export function bulkActionTruncatedBody(maxRows: number): string {+ return `The list has more than ${count.format(maxRows)} rows. Only the first ${count.format(+ maxRows+ )} were processed. Filter the list to process the rest.`;+}++export type IdSlice = { file: number; start: number; end: number };++/**+ * Splits the collected ids into the slices the apply steps act on: each+ * collect step wrote one file of `idsPerFile[file]` ids, and each slice is at+ * most `idsPerStep` ids of one file. An empty file has no slice.+ */+export function planIdSlices(+ idsPerFile: number[],+ idsPerStep: number+): IdSlice[] {+ const size = Math.max(1, idsPerStep);+ const slices: IdSlice[] = [];+ idsPerFile.forEach((total, file) => {+ for (let start = 0; start < total; start += size) {+ slices.push({ file, start, end: Math.min(start + size, total) });+ }+ });+ return slices;+}diff --git a/packages/jobs/src/table-jobs/csv.test.ts b/packages/jobs/src/table-jobs/csv.test.tsnew file mode 100644index 0000000000..7f220fe3ac--- /dev/null+++ b/packages/jobs/src/table-jobs/csv.test.ts@@ -0,0 +1,81 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ encodeExportHeader,+ encodeExportRows,+ formatExportValue,+ readExportValue+} from "./csv";+import { TABLE_JOB_PAGE_SIZE } from "./paging";++describe("readExportValue", () => {+ it("reads a plain column", () => {+ expect(readExportValue({ status: "Draft" }, "status")).toBe("Draft");+ });++ it("reads a custom field from customFields", () => {+ const row = { customFields: { qzAx: "Blue" } };+ expect(readExportValue(row, "customFields->>qzAx")).toBe("Blue");+ });++ it("reads nothing when the row has no custom fields", () => {+ expect(+ readExportValue({ customFields: null }, "customFields->>qzAx")+ ).toBeUndefined();+ expect(readExportValue({}, "customFields->>qzAx")).toBeUndefined();+ });+});++describe("formatExportValue", () => {+ it("keeps plain values as they are", () => {+ expect(formatExportValue("2026-10-13")).toBe("2026-10-13");+ expect(formatExportValue(1250.5)).toBe(1250.5);+ expect(formatExportValue(false)).toBe(false);+ expect(formatExportValue(null)).toBeNull();+ expect(formatExportValue(undefined)).toBeNull();+ });++ it("joins an array with semicolons", () => {+ expect(formatExportValue(["red", "blue", null, 3])).toBe("red; blue; 3");+ });++ it("writes an object as JSON", () => {+ expect(formatExportValue({ name: "Acme" })).toBe('{"name":"Acme"}');+ expect(formatExportValue([{ id: 1 }])).toBe('{"id":1}');+ });+});++describe("encodeExportHeader / encodeExportRows", () => {+ const columns = [+ { key: "id", label: "Name" },+ { key: "customFields->>c1", label: "Name" },+ { key: "tags", label: "Tags" }+ ];++ it("writes the labels once and the rows without a header", () => {+ const header = encodeExportHeader(columns);+ const rows = encodeExportRows(+ [{ id: "SO-1", customFields: { c1: "x" }, tags: ["a", "b"] }],+ columns+ );+ expect(header).toBe("Name,Name,Tags");+ expect(rows).toBe("SO-1,x,a; b");+ });++ it("strips a formula prefix from a cell", () => {+ expect(+ encodeExportRows([{ id: "=SUM(A1)" }], [{ key: "id", label: "Name" }])+ ).toBe("SUM(A1)");+ });++ it("returns an empty string for an empty page", () => {+ expect(encodeExportRows([], columns)).toBe("");+ });++ it("keeps the page below PostgREST's max_rows", () => {+ expect(TABLE_JOB_PAGE_SIZE + 1).toBeLessThanOrEqual(1000);+ });+});diff --git a/packages/jobs/src/table-jobs/csv.ts b/packages/jobs/src/table-jobs/csv.tsnew file mode 100644index 0000000000..826df35e57--- /dev/null+++ b/packages/jobs/src/table-jobs/csv.ts@@ -0,0 +1,100 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { encodeCsv } from "@carbon/files/csv";++/**+ * Cell values of the background table export. The on-screen formatters run in+ * the browser only, so a big export holds the plain database values: a date+ * stays `2026-10-13`, an amount stays `1250.5`. One exporter serves every list.+ */++export type ExportColumn = { key: string; label: string };++/** The most rows one export writes. The file holds the first rows above it. */+export const MAX_EXPORT_ROWS = 100_000;++/** The most bytes one export writes (about 200 MB). A wide list can pass this+ * before `MAX_EXPORT_ROWS`; the file then stops after the page that crossed it. */+export const MAX_EXPORT_BYTES = 200 * 1024 * 1024;++const CUSTOM_FIELD_PREFIX = "customFields->>";++/** The raw value of a column: `row[key]`, or the custom field's value for a+ * `customFields->>{id}` column (the same key the Table's custom columns use). */+export function readExportValue(+ row: Record<string, unknown>,+ key: string+): unknown {+ if (key.startsWith(CUSTOM_FIELD_PREFIX)) {+ const customFields = row.customFields;+ if (+ customFields === null ||+ typeof customFields !== "object" ||+ Array.isArray(customFields)+ ) {+ return undefined;+ }+ return (customFields as Record<string, unknown>)[+ key.slice(CUSTOM_FIELD_PREFIX.length)+ ];+ }+ return row[key];+}++/** A raw value as one CSV cell: arrays join with "; ", objects become JSON. */+export function formatExportValue(+ value: unknown+): string | number | boolean | null {+ if (value === null || value === undefined) return null;+ if (+ typeof value === "string" ||+ typeof value === "number" ||+ typeof value === "boolean"+ ) {+ return value;+ }+ if (Array.isArray(value)) {+ return value+ .filter((item) => item !== null && item !== undefined)+ .map((item) =>+ typeof item === "object" ? JSON.stringify(item) : String(item)+ )+ .join("; ");+ }+ if (typeof value === "bigint") return value.toString();+ return JSON.stringify(value);+}++/** The header line of the file: the translated labels, in display order,+ * without a line end (each page starts with its own "\r\n"). */+export function encodeExportHeader(columns: ExportColumn[]): string {+ // With no data rows, papaparse still ends the header with "\r\n".+ return encodeCsv([], {+ fields: columns.map((column) => column.label)+ }).replace(/\r?\n$/, "");+}++/**+ * One page of rows as CSV lines, without a header. Cells are keyed by the+ * column key, not the label, so two columns with the same label stay apart.+ * Returns "" for an empty page.+ */+export function encodeExportRows(+ rows: Record<string, unknown>[],+ columns: ExportColumn[]+): string {+ if (rows.length === 0) return "";+ const cells = rows.map((row) => {+ const out: Record<string, unknown> = {};+ for (const column of columns) {+ out[column.key] = formatExportValue(readExportValue(row, column.key));+ }+ return out;+ });+ return encodeCsv(cells, {+ fields: columns.map((column) => column.key),+ header: false+ });+}diff --git a/packages/jobs/src/table-jobs/export-run.ts b/packages/jobs/src/table-jobs/export-run.tsnew file mode 100644index 0000000000..350de9ec04--- /dev/null+++ b/packages/jobs/src/table-jobs/export-run.ts@@ -0,0 +1,140 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { CSV_CONTENT_TYPE } from "@carbon/files/csv";+import { getLogger } from "@carbon/logger";+import {+ type ExportColumn,+ encodeExportHeader,+ encodeExportRows,+ MAX_EXPORT_BYTES,+ MAX_EXPORT_ROWS+} from "./csv";+import type { TableJobContext, TableJobHandlers } from "./handlers";+import { readListPages } from "./paging";+import type { TableJobStorage } from "./storage";++/**+ * The step bodies of the background export (`table-export.ts`). Each part+ * step reads up to 10,000 rows from its cursor and writes them as one part+ * file; the last step joins the parts into the export. The function only+ * orders the steps, so these run, and are tested, without Inngest.+ */++export type ExportDeps = {+ handlers: Pick<TableJobHandlers, "fetchListPage">;+ storage: TableJobStorage;+};++export type ExportPartResult = {+ rows: number;+ bytes: number;+ /** Where the next part starts, or null when this was the last part. */+ nextCursor: string | null;+ /** The export stopped at `MAX_EXPORT_ROWS` or `MAX_EXPORT_BYTES`. */+ truncated: boolean;+};++const log = getLogger("jobs", "table-export");++const encoder = new TextEncoder();++/**+ * Writes one part. Part 0 starts with the header line; every page starts+ * with its own line end, so the parts join without a separator.+ */+export async function writeExportPart(+ deps: ExportDeps,+ args: {+ context: TableJobContext;+ listKey: string;+ search: string;+ columns: ExportColumn[];+ cursor: string | null;+ part: number;+ rowsBefore: number;+ bytesBefore: number;+ key: string;+ }+): Promise<ExportPartResult> {+ const chunks: string[] = [];+ let bytes = 0;+ const add = (chunk: string) => {+ chunks.push(chunk);+ bytes += encoder.encode(chunk).byteLength;+ };+ if (args.part === 0) add(encodeExportHeader(args.columns));++ const read = await readListPages({+ handlers: deps.handlers,+ listKey: args.listKey,+ context: args.context,+ search: args.search,+ cursor: args.cursor,+ rowsBefore: args.rowsBefore,+ maxRows: MAX_EXPORT_ROWS,+ forExport: true,+ onPage: (rows) => {+ const lines = encodeExportRows(rows, args.columns);+ if (lines) add(`\r\n${lines}`);+ return args.bytesBefore + bytes < MAX_EXPORT_BYTES;+ }+ });++ await deps.storage.upload(args.key, chunks.join(""), CSV_CONTENT_TYPE);+ return {+ rows: read.rows,+ bytes,+ nextCursor: read.nextCursor,+ truncated: read.truncated+ };+}++/**+ * A stream of the parts in order, one part in memory at a time: each is+ * downloaded only when the upload asks for more.+ */+export function concatParts(+ storage: Pick<TableJobStorage, "download">,+ keys: string[]+): ReadableStream<Uint8Array> {+ let next = 0;+ return new ReadableStream<Uint8Array>({+ async pull(controller) {+ const key = keys[next++];+ if (key === undefined) {+ controller.close();+ return;+ }+ try {+ controller.enqueue(await storage.download(key));+ } catch (error) {+ controller.error(error);+ }+ }+ });+}++/** Streams the parts into the export file, then deletes the parts. A part+ * that cannot be deleted is logged; the nightly cleanup removes it. */+export async function composeExport(+ deps: Pick<ExportDeps, "storage">,+ args: { partKeys: string[]; key: string }+): Promise<{ partsRemoved: boolean }> {+ await deps.storage.upload(+ args.key,+ concatParts(deps.storage, args.partKeys),+ CSV_CONTENT_TYPE+ );+ try {+ await deps.storage.remove(args.partKeys);+ return { partsRemoved: true };+ } catch (error) {+ log.error("Failed to delete the parts of an export", {+ key: args.key,+ error+ });+ return { partsRemoved: false };+ }+}diff --git a/packages/jobs/src/table-jobs/handlers.ts b/packages/jobs/src/table-jobs/handlers.tsnew file mode 100644index 0000000000..bc2ce15b5a--- /dev/null+++ b/packages/jobs/src/table-jobs/handlers.ts@@ -0,0 +1,132 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { NonRetriableError } from "inngest";++/**+ * The ERP side of the table jobs (background export and background bulk+ * actions). The list queries live in the ERP's list registry+ * (`apps/erp/app/utils/list-registry`), which packages/jobs cannot import, so+ * the ERP app hands them over at boot, like `setWorkflowDispatch`.+ */++export type TableJobContext = {+ companyId: string;+ userId: string;+};++export type TableJobPage = {+ rows: Record<string, unknown>[];+ /** The cursor of the next page, or null on the last page. */+ nextCursor: string | null;+ error?: unknown;+};++export interface TableJobHandlers {+ /**+ * Whether the user can still read the list: an employee of the company with+ * the list's permission. Read fresh, so a permission revoked after the+ * request is honored.+ */+ canReadList(listKey: string, context: TableJobContext): Promise<boolean>;+ /**+ * One page of the list for its URL search, read as the user. `cursor` is+ * the previous page's `nextCursor` (null for the first page). `limit` must+ * stay below PostgREST's `max_rows` (1,000): the query asks for one row+ * more than `limit` to know whether another page exists. `forExport` asks+ * for the rows as the CSV export writes them: with the values the list's+ * loader adds per page (the ERP's `exportRows`).+ */+ fetchListPage(+ listKey: string,+ context: TableJobContext,+ search: string,+ page: { cursor: string | null; limit: number; forExport?: boolean }+ ): Promise<TableJobPage>;+ /** The list's unique id column (`id` unless the list says otherwise). */+ listIdColumn(listKey: string): string;+ /**+ * Whether the user can still run the bulk action on the list: the list's+ * view permission, the action's own permission and any plan feature the+ * action needs, read fresh.+ */+ canRunBulkAction(+ listKey: string,+ action: TableBulkAction,+ context: TableJobContext+ ): Promise<boolean>;+ /**+ * Runs the action on one chunk of ids (at most 100), as the user. The+ * action applies its own per-row checks: a row it may not act on counts as+ * `skipped`, never as an error. `carry` is the value the previous chunk of+ * the same run returned (Jobs Release: the PO each supplier went on).+ */+ runBulkAction(+ action: TableBulkAction,+ ids: string[],+ context: TableJobContext,+ carry?: TableBulkActionCarry+ ): Promise<TableBulkActionResult>;+}++export type TableBulkAction = {+ /** A key of the ERP's bulk actions, for example "jobs.release". */+ key: string;+ /** The action's own values, for example `{ field, value }`. */+ params: Record<string, unknown>;+};++/** What a bulk action did to its rows. The ERP's action routes and the+ * background job count the same way. */+export type TableBulkActionCounts = {+ done: number;+ skipped: number;+ failed: number;+};++/** JSON an action hands from one chunk of a run to the next. It goes through+ * the step results, so it must stay small. */+export type TableBulkActionCarry = Record<string, unknown>;++export type TableBulkActionResult = TableBulkActionCounts & {+ carry?: TableBulkActionCarry;+};++let handlers: TableJobHandlers | undefined;++/** The ERP app supplies this at boot; packages/jobs cannot import ~/ itself. */+export function setTableJobHandlers(next: TableJobHandlers): void {+ handlers = next;+}++export function getTableJobHandlers(): TableJobHandlers | undefined {+ return handlers;+}++/** The handlers, or a non-retriable failure naming the job (`what`). */+export function requireTableJobHandlers(what: string): TableJobHandlers {+ const current = getTableJobHandlers();+ if (!current) {+ // The ERP wires them on the first request to api+/inngest.ts, which is+ // also how this run arrived; reaching here means another host served it.+ throw new NonRetriableError(`${what} is not available in this environment`);+ }+ return current;+}++export type TableJobKind = "export" | "bulk";++/**+ * The per-company Redis lock of a table job. The ERP route takes it+ * (`takeTableJobLock`, value = the job's id) before it sends the event; the+ * job deletes it when it ends. Inngest's concurrency key queues a second run,+ * it never refuses one, so the lock is what answers "already running".+ */+export function tableJobLockKey(kind: TableJobKind, companyId: string): string {+ return `table-job:${kind}:${companyId}`;+}++/** Seconds a lock lives if its job never deletes it (a crashed process). Each+ * step of a running job sets it back to this (`extendTableJobLock`). */+export const TABLE_JOB_LOCK_TTL_SECONDS = 60 * 60;diff --git a/packages/jobs/src/table-jobs/lock.test.ts b/packages/jobs/src/table-jobs/lock.test.tsnew file mode 100644index 0000000000..5f08debbb6--- /dev/null+++ b/packages/jobs/src/table-jobs/lock.test.ts@@ -0,0 +1,39 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it, vi } from "vitest";++// The Redis client itself is the boundary: only the reply is decided here.+vi.mock("@carbon/kv", () => ({ redis: {} }));++import { decideTableJobLock } from "./lock";++describe("decideTableJobLock", () => {+ it("takes the lock when the script set it", () => {+ expect(decideTableJobLock([1, 0])).toEqual({ status: "acquired" });+ });++ it("refuses with the remaining seconds while another job holds it", () => {+ expect(decideTableJobLock([0, 1740])).toEqual({+ status: "busy",+ retryAfterSeconds: 1740+ });+ });++ it("never promises a wait for a key without a real TTL", () => {+ expect(decideTableJobLock([0, -1])).toEqual({+ status: "busy",+ retryAfterSeconds: 0+ });+ expect(decideTableJobLock([0, -2])).toEqual({+ status: "busy",+ retryAfterSeconds: 0+ });+ });++ it("fails open when Redis answers nothing", () => {+ expect(decideTableJobLock(null)).toEqual({ status: "unavailable" });+ expect(decideTableJobLock([])).toEqual({ status: "unavailable" });+ });+});diff --git a/packages/jobs/src/table-jobs/lock.ts b/packages/jobs/src/table-jobs/lock.tsnew file mode 100644index 0000000000..6ec03b776f--- /dev/null+++ b/packages/jobs/src/table-jobs/lock.ts@@ -0,0 +1,120 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { redis } from "@carbon/kv";+import {+ TABLE_JOB_LOCK_TTL_SECONDS,+ type TableJobKind,+ tableJobLockKey+} from "./handlers";++/**+ * The per-company lock of a table job, one key per company and job kind. The+ * value is the job's id, so a job only ever deletes or extends its own lock:+ * a lock that expired and was taken by the next job belongs to that job.+ *+ * Each operation is one Lua script, so the read and the write are atomic.+ * `@carbon/kv` answers `null` for any command while Redis is down, which every+ * caller treats as "no lock": the route starts the job anyway (Inngest's+ * per-company concurrency still runs them one at a time).+ */++/** The part of an ioredis client the lock uses. */+export type LockClient = {+ eval(+ script: string,+ numKeys: number,+ ...args: (string | number)[]+ ): Promise<unknown>;+};++// SET NX EX, and the remaining TTL when another job holds the key.+const TAKE_SCRIPT = `if redis.call("SET", KEYS[1], ARGV[1], "NX", "EX", ARGV[2]) then+ return {1, 0}+end+return {0, redis.call("TTL", KEYS[1])}`;++// Compare-and-delete: only the holder deletes the key.+const RELEASE_SCRIPT = `if redis.call("GET", KEYS[1]) == ARGV[1] then+ return redis.call("DEL", KEYS[1])+end+return 0`;++// Compare-and-expire: only the holder sets the TTL back.+const EXTEND_SCRIPT = `if redis.call("GET", KEYS[1]) == ARGV[1] then+ return redis.call("EXPIRE", KEYS[1], ARGV[2])+end+return 0`;++/**+ * What taking the lock answered.+ *+ * - `acquired`: the lock is ours.+ * - `busy`: another job of the company holds it; it expires in+ * `retryAfterSeconds` at the latest.+ * - `unavailable`: Redis did not answer. The job starts anyway.+ */+export type TableJobLock =+ | { status: "acquired" }+ | { status: "busy"; retryAfterSeconds: number }+ | { status: "unavailable" };++/** Reads the take script's reply: `[1, 0]`, `[0, ttl]`, or null. */+export function decideTableJobLock(reply: unknown): TableJobLock {+ if (!Array.isArray(reply) || reply.length < 2) {+ return { status: "unavailable" };+ }+ const [taken, ttl] = reply as [unknown, unknown];+ if (Number(taken) === 1) return { status: "acquired" };+ const seconds = Number(ttl);+ // TTL is -2 when the key vanished between the two calls and -1 without an+ // expiry; neither should promise a wait that is not real.+ return {+ status: "busy",+ retryAfterSeconds: Number.isFinite(seconds) && seconds > 0 ? seconds : 0+ };+}++export async function takeTableJobLock(+ kind: TableJobKind,+ companyId: string,+ jobId: string,+ client: LockClient = redis+): Promise<TableJobLock> {+ const reply = await client.eval(+ TAKE_SCRIPT,+ 1,+ tableJobLockKey(kind, companyId),+ jobId,+ TABLE_JOB_LOCK_TTL_SECONDS+ );+ return decideTableJobLock(reply);+}++/** Deletes the lock while it still holds `jobId`. */+export async function releaseTableJobLock(+ kind: TableJobKind,+ companyId: string,+ jobId: string,+ client: LockClient = redis+): Promise<void> {+ await client.eval(RELEASE_SCRIPT, 1, tableJobLockKey(kind, companyId), jobId);+}++/** Sets the lock's TTL back to the full hour while it still holds `jobId`:+ * a long run must not lose its lock to the next request. */+export async function extendTableJobLock(+ kind: TableJobKind,+ companyId: string,+ jobId: string,+ client: LockClient = redis+): Promise<void> {+ await client.eval(+ EXTEND_SCRIPT,+ 1,+ tableJobLockKey(kind, companyId),+ jobId,+ TABLE_JOB_LOCK_TTL_SECONDS+ );+}diff --git a/packages/jobs/src/table-jobs/notify.ts b/packages/jobs/src/table-jobs/notify.tsnew file mode 100644index 0000000000..b9ff050fac--- /dev/null+++ b/packages/jobs/src/table-jobs/notify.ts@@ -0,0 +1,43 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { trigger } from "@carbon/lib/trigger";+import {+ NotificationDestination,+ type NotificationEvent+} from "@carbon/notifications";++/**+ * Tells the user who asked for a table job how it went. `dedupeId` is the+ * Inngest event id: a step that sends and then fails before it returns is+ * retried, and the retry sends the same id, which Inngest drops for 24 h.+ */+export async function notifyTableJobUser(args: {+ event: NotificationEvent.TableExport | NotificationEvent.TableBulkAction;+ companyId: string;+ userId: string;+ documentId: string;+ title: string;+ body?: string;+ inAppOnly?: boolean;+ dedupeId: string;+}): Promise<void> {+ // Never `from`: notify drops the sender from the recipients, and the+ // sender here would be the recipient.+ await trigger(+ "notify",+ {+ event: args.event,+ companyId: args.companyId,+ documentId: args.documentId,+ title: args.title,+ ...(args.body ? { body: args.body } : {}),+ recipient: { type: "user", userId: args.userId },+ ...(args.inAppOnly+ ? { destinations: [NotificationDestination.InApp] }+ : {})+ },+ { id: args.dedupeId }+ );+}diff --git a/packages/jobs/src/table-jobs/paging.ts b/packages/jobs/src/table-jobs/paging.tsnew file mode 100644index 0000000000..fbb6209cc5--- /dev/null+++ b/packages/jobs/src/table-jobs/paging.ts@@ -0,0 +1,81 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { TableJobContext, TableJobHandlers } from "./handlers";++/** Rows per page the table jobs read. Below PostgREST's `max_rows` (1,000):+ * the list query asks for one row more than this to know if a page follows. */+export const TABLE_JOB_PAGE_SIZE = 500;++/**+ * Pages one Inngest step reads (10,000 rows). A step is one HTTP request, and+ * the load balancer cuts a request at 600 s; 20 list queries stay well below+ * that even on a slow view. Past this the job goes on in a new step from the+ * cursor the last one returned.+ */+export const TABLE_JOB_PAGES_PER_STEP = 20;++/** Rows one step reads at most. */+export const TABLE_JOB_ROWS_PER_STEP =+ TABLE_JOB_PAGE_SIZE * TABLE_JOB_PAGES_PER_STEP;++export type ListPagesResult = {+ /** Rows this call read. */+ rows: number;+ /** Where the next step starts, or null when there is nothing more to read. */+ nextCursor: string | null;+ /** True when the read stopped at `maxRows` (or `onPage` stopped it) while+ * the list had more rows. */+ truncated: boolean;+};++/**+ * Reads up to `TABLE_JOB_PAGES_PER_STEP` pages of a list from `cursor` and+ * hands each to `onPage`. Stops at the end of the list, at `maxRows` rows in+ * total (`rowsBefore` were read by earlier steps), or when `onPage` answers+ * false. Throws when a page cannot be read.+ */+export async function readListPages(args: {+ handlers: Pick<TableJobHandlers, "fetchListPage">;+ listKey: string;+ context: TableJobContext;+ search: string;+ cursor: string | null;+ rowsBefore: number;+ maxRows: number;+ /** Read the rows as the CSV export writes them (`fetchListPage`). */+ forExport?: boolean;+ onPage: (rows: Record<string, unknown>[]) => boolean | void;+}): Promise<ListPagesResult> {+ let cursor = args.cursor;+ let rows = 0;+ for (let page = 0; page < TABLE_JOB_PAGES_PER_STEP; page++) {+ const remaining = args.maxRows - args.rowsBefore - rows;+ if (remaining <= 0) return { rows, nextCursor: null, truncated: true };++ const result = await args.handlers.fetchListPage(+ args.listKey,+ args.context,+ args.search,+ {+ cursor,+ limit: Math.min(TABLE_JOB_PAGE_SIZE, remaining),+ ...(args.forExport ? { forExport: true } : {})+ }+ );+ if (result.error) {+ throw new Error(`Failed to read the list "${args.listKey}"`, {+ cause: result.error+ });+ }+ rows += result.rows.length;+ const keepGoing = args.onPage(result.rows) !== false;+ cursor = result.nextCursor;+ if (!cursor) return { rows, nextCursor: null, truncated: false };+ if (!keepGoing || args.rowsBefore + rows >= args.maxRows) {+ return { rows, nextCursor: null, truncated: true };+ }+ }+ return { rows, nextCursor: cursor, truncated: false };+}diff --git a/packages/jobs/src/table-jobs/run.test.ts b/packages/jobs/src/table-jobs/run.test.tsnew file mode 100644index 0000000000..eb50e16b09--- /dev/null+++ b/packages/jobs/src/table-jobs/run.test.ts@@ -0,0 +1,452 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { planIdSlices } from "./bulk";+import { applyIdSlice, collectIds, storeSelectedIds } from "./bulk-run";+import { MAX_EXPORT_ROWS } from "./csv";+import { composeExport, writeExportPart } from "./export-run";+import type {+ TableBulkActionCounts,+ TableJobHandlers,+ TableJobPage+} from "./handlers";+import {+ readListPages,+ TABLE_JOB_PAGE_SIZE,+ TABLE_JOB_ROWS_PER_STEP+} from "./paging";+import type { TableJobStorage } from "./storage";++/**+ * The step bodies of the two table jobs, run against a list of plain rows (the+ * ERP's list registry is the boundary) and a storage held in a Map (the+ * bucket is the boundary). Each test checks what a step leaves behind: the+ * file it wrote, the counts it returned, the cursor the next step starts from.+ */++const context = { companyId: "co_1", userId: "user_1" };++/** A list of `total` rows `{ id, name }`, paged by a numeric cursor. */+function listOf(total: number, options: { failAt?: number } = {}) {+ const rows = Array.from({ length: total }, (_, i) => ({+ id: `row_${i}`,+ name: `Row ${i}`+ }));+ const handlers: Pick<TableJobHandlers, "fetchListPage" | "listIdColumn"> = {+ async fetchListPage(_listKey, _context, _search, page) {+ const start = page.cursor === null ? 0 : Number(page.cursor);+ if (options.failAt !== undefined && start >= options.failAt) {+ return { rows: [], nextCursor: null, error: "boom" } as TableJobPage;+ }+ const slice = rows.slice(start, start + page.limit);+ const end = start + slice.length;+ return { rows: slice, nextCursor: end < total ? String(end) : null };+ },+ listIdColumn: () => "id"+ };+ return handlers;+}++function memoryStorage(options: { failDownload?: boolean } = {}) {+ const files = new Map<string, Uint8Array>();+ const storage: TableJobStorage = {+ async upload(key, body) {+ files.set(+ key,+ typeof body === "string"+ ? new TextEncoder().encode(body)+ : new Uint8Array(await new Response(body).arrayBuffer())+ );+ },+ async download(key) {+ const file = files.get(key);+ if (options.failDownload || !file) throw new Error(`No file ${key}`);+ return file;+ },+ async remove(keys) {+ for (const key of keys) files.delete(key);+ }+ };+ const text = (key: string) =>+ new TextDecoder().decode(files.get(key) ?? new Uint8Array());+ return { storage, files, text };+}++describe("readListPages", () => {+ it("stops after one step's pages and hands back the cursor", async () => {+ const pages: number[] = [];+ const result = await readListPages({+ handlers: listOf(TABLE_JOB_ROWS_PER_STEP + 10),+ listKey: "parts",+ context,+ search: "",+ cursor: null,+ rowsBefore: 0,+ maxRows: MAX_EXPORT_ROWS,+ onPage: (rows) => {+ pages.push(rows.length);+ }+ });+ expect(result).toEqual({+ rows: TABLE_JOB_ROWS_PER_STEP,+ nextCursor: String(TABLE_JOB_ROWS_PER_STEP),+ truncated: false+ });+ expect(pages.every((size) => size === TABLE_JOB_PAGE_SIZE)).toBe(true);+ });++ it("stops at the row limit counted across steps", async () => {+ const result = await readListPages({+ handlers: listOf(5_000),+ listKey: "parts",+ context,+ search: "",+ cursor: "1000",+ rowsBefore: 1_000,+ maxRows: 2_000,+ onPage: () => undefined+ });+ expect(result).toEqual({ rows: 1_000, nextCursor: null, truncated: true });+ });++ it("is not truncated when the list ends exactly at the limit", async () => {+ const result = await readListPages({+ handlers: listOf(2_000),+ listKey: "parts",+ context,+ search: "",+ cursor: null,+ rowsBefore: 0,+ maxRows: 2_000,+ onPage: () => undefined+ });+ expect(result).toEqual({ rows: 2_000, nextCursor: null, truncated: false });+ });++ it("throws when a page cannot be read", async () => {+ await expect(+ readListPages({+ handlers: listOf(2_000, { failAt: 500 }),+ listKey: "parts",+ context,+ search: "",+ cursor: null,+ rowsBefore: 0,+ maxRows: 2_000,+ onPage: () => undefined+ })+ ).rejects.toThrow('Failed to read the list "parts"');+ });+});++describe("the export steps", () => {+ const columns = [+ { key: "id", label: "Part" },+ { key: "name", label: "Name" }+ ];++ async function runExport(total: number) {+ const { storage, files, text } = memoryStorage();+ const handlers = listOf(total);+ const partKeys: string[] = [];+ let cursor: string | null = null;+ let rows = 0;+ let bytes = 0;+ for (let part = 0; ; part++) {+ const key = `parts/${part}.csv`;+ const result = await writeExportPart(+ { handlers, storage },+ {+ context,+ listKey: "parts",+ search: "",+ columns,+ cursor,+ part,+ rowsBefore: rows,+ bytesBefore: bytes,+ key+ }+ );+ partKeys.push(key);+ rows += result.rows;+ bytes += result.bytes;+ cursor = result.nextCursor;+ if (!cursor) break;+ }+ await composeExport({ storage }, { partKeys, key: "export.csv" });+ return { files, text, partKeys, rows };+ }++ it("joins the parts into one file with one header and every row", async () => {+ const total = TABLE_JOB_ROWS_PER_STEP * 2 + 3;+ const { text, files, partKeys, rows } = await runExport(total);+ expect(partKeys).toHaveLength(3);+ expect(rows).toBe(total);++ const lines = text("export.csv").split("\r\n");+ expect(lines[0]).toBe("Part,Name");+ expect(lines).toHaveLength(total + 1);+ expect(lines[1]).toBe("row_0,Row 0");+ expect(lines[total]).toBe(`row_${total - 1},Row ${total - 1}`);+ // The parts are deleted once the export is written.+ expect([...files.keys()]).toEqual(["export.csv"]);+ });++ it("writes the header alone for an empty list", async () => {+ const { text } = await runExport(0);+ expect(text("export.csv")).toBe("Part,Name");+ });+});++describe("the bulk action steps", () => {+ async function collectAll(total: number, maxRows: number) {+ const { storage, text } = memoryStorage();+ const handlers = listOf(total);+ const idsPerFile: number[] = [];+ let cursor: string | null = null;+ let rows = 0;+ let truncated = false;+ for (let file = 0; ; file++) {+ const result = await collectIds(+ { handlers, storage },+ {+ context,+ listKey: "jobs",+ search: "",+ cursor,+ rowsBefore: rows,+ maxRows,+ key: `ids/${file}.json`+ }+ );+ idsPerFile.push(result.ids);+ rows += result.rows;+ truncated = result.truncated;+ cursor = result.nextCursor;+ if (!cursor) break;+ }+ return { storage, text, idsPerFile, truncated };+ }++ it("stores each step's ids in its own file, in list order", async () => {+ const { text, idsPerFile, truncated } = await collectAll(+ TABLE_JOB_ROWS_PER_STEP + 5,+ 100_000+ );+ expect(idsPerFile).toEqual([TABLE_JOB_ROWS_PER_STEP, 5]);+ expect(truncated).toBe(false);+ const second = JSON.parse(text("ids/1.json"));+ expect(second[0]).toBe(`row_${TABLE_JOB_ROWS_PER_STEP}`);+ });++ it("stops at the action's row limit and says so", async () => {+ const { idsPerFile, truncated } = await collectAll(5_000, 2_000);+ expect(idsPerFile).toEqual([2_000]);+ expect(truncated).toBe(true);+ });++ it("acts on every collected id exactly once across the slices", async () => {+ const { storage, idsPerFile } = await collectAll(+ TABLE_JOB_ROWS_PER_STEP + 250,+ 100_000+ );+ const seen: string[] = [];+ const handlers: Pick<TableJobHandlers, "runBulkAction"> = {+ async runBulkAction(_action, ids) {+ seen.push(...ids);+ return { done: ids.length, skipped: 0, failed: 0 };+ }+ };+ let total: TableBulkActionCounts = { done: 0, skipped: 0, failed: 0 };+ for (const slice of planIdSlices(idsPerFile, 1_000)) {+ const counts = await applyIdSlice(+ { handlers, storage },+ {+ context,+ action: { key: "jobs.delete", params: {} },+ key: `ids/${slice.file}.json`,+ start: slice.start,+ end: slice.end,+ chunkSize: 100+ }+ );+ total = {+ done: total.done + counts.done,+ skipped: total.skipped + counts.skipped,+ failed: total.failed + counts.failed+ };+ }+ expect(total.done).toBe(TABLE_JOB_ROWS_PER_STEP + 250);+ expect(new Set(seen).size).toBe(seen.length);+ expect(seen).toHaveLength(TABLE_JOB_ROWS_PER_STEP + 250);+ });++ it("hands the carry from chunk to chunk and from slice to slice", async () => {+ const { storage, idsPerFile } = await collectAll(60, 100_000);+ // Each call sees the carry the call before it returned.+ const seenCarries: unknown[] = [];+ const handlers: Pick<TableJobHandlers, "runBulkAction"> = {+ async runBulkAction(_action, ids, _context, carry) {+ seenCarries.push(carry?.calls ?? null);+ const calls = ((carry?.calls as number | undefined) ?? 0) + 1;+ return { done: ids.length, skipped: 0, failed: 0, carry: { calls } };+ }+ };+ let carry: Record<string, unknown> | undefined;+ for (const slice of planIdSlices(idsPerFile, 25)) {+ const result = await applyIdSlice(+ { handlers, storage },+ {+ context,+ action: { key: "jobs.release", params: {} },+ key: `ids/${slice.file}.json`,+ start: slice.start,+ end: slice.end,+ chunkSize: 10,+ carry+ }+ );+ carry = result.carry;+ }+ // 60 ids: slices of 25, 25, 10; chunks of 10 -> 7 calls in a row.+ expect(seenCarries).toEqual([null, 1, 2, 3, 4, 5, 6]);+ expect(carry).toEqual({ calls: 7 });+ });++ it("counts a failed chunk as failed and runs the rest", async () => {+ const { storage, idsPerFile } = await collectAll(250, 100_000);+ let call = 0;+ const handlers: Pick<TableJobHandlers, "runBulkAction"> = {+ async runBulkAction(_action, ids) {+ call += 1;+ if (call === 2) throw new Error("chunk failed");+ return { done: ids.length - 1, skipped: 1, failed: 0 };+ }+ };+ const [slice] = planIdSlices(idsPerFile, 1_000);+ const counts = await applyIdSlice(+ { handlers, storage },+ {+ context,+ action: { key: "jobs.delete", params: {} },+ key: "ids/0.json",+ start: slice!.start,+ end: slice!.end,+ chunkSize: 100+ }+ );+ // Chunks of 100, 100 and 50: the second throws.+ expect(counts).toEqual({ done: 99 + 49, skipped: 2, failed: 100 });+ });++ it("counts the whole slice as failed when its ids cannot be read", async () => {+ const { storage } = memoryStorage({ failDownload: true });+ const counts = await applyIdSlice(+ {+ handlers: {+ runBulkAction: async () => ({ done: 1, skipped: 0, failed: 0 })+ },+ storage+ },+ {+ context,+ action: { key: "jobs.delete", params: {} },+ key: "ids/0.json",+ start: 1_000,+ end: 1_250,+ chunkSize: 100+ }+ );+ expect(counts).toEqual({ done: 0, skipped: 0, failed: 250 });+ });+});++describe("storeSelectedIds", () => {+ it("stores the selected ids once each, and acts on exactly those", async () => {+ const { storage } = memoryStorage();+ const stored = await storeSelectedIds(+ { storage },+ { ids: ["j1", "j2", "", "j1", "j3"], maxRows: 2_000, key: "ids/0.json" }+ );+ expect(stored).toEqual({ ids: 3, truncated: false });++ const seen: string[] = [];+ const counts = await applyIdSlice(+ {+ handlers: {+ async runBulkAction(_action, ids) {+ seen.push(...ids);+ return { done: ids.length, skipped: 0, failed: 0 };+ }+ },+ storage+ },+ {+ context,+ action: { key: "jobs.release", params: {} },+ key: "ids/0.json",+ start: 0,+ end: stored.ids,+ chunkSize: 25+ }+ );+ expect(seen).toEqual(["j1", "j2", "j3"]);+ expect(counts.done).toBe(3);+ });++ it("keeps at most maxRows ids and says so", async () => {+ const { storage } = memoryStorage();+ const stored = await storeSelectedIds(+ { storage },+ { ids: ["a", "b", "c"], maxRows: 2, key: "ids/0.json" }+ );+ expect(stored).toEqual({ ids: 2, truncated: true });+ });+});++describe("which page reads ask for the export's rows", () => {+ it("asks when writing an export part, never when collecting ids", async () => {+ const forExport: Array<boolean | undefined> = [];+ const base = listOf(3);+ const handlers: Pick<TableJobHandlers, "fetchListPage" | "listIdColumn"> = {+ ...base,+ async fetchListPage(listKey, readContext, search, page) {+ forExport.push(page.forExport);+ return base.fetchListPage(listKey, readContext, search, page);+ }+ };+ const { storage } = memoryStorage();++ await writeExportPart(+ { handlers, storage },+ {+ context,+ listKey: "jobs",+ search: "",+ columns: [{ key: "id", label: "Id" }],+ cursor: null,+ part: 0,+ rowsBefore: 0,+ bytesBefore: 0,+ key: "parts/0.csv"+ }+ );+ await collectIds(+ { handlers, storage },+ {+ context,+ listKey: "jobs",+ search: "",+ cursor: null,+ rowsBefore: 0,+ maxRows: 100,+ key: "ids/0.json"+ }+ );++ expect(forExport).toEqual([true, undefined]);+ });+});diff --git a/packages/jobs/src/table-jobs/storage.ts b/packages/jobs/src/table-jobs/storage.tsnew file mode 100644index 0000000000..4e73ee415f--- /dev/null+++ b/packages/jobs/src/table-jobs/storage.ts@@ -0,0 +1,78 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { TEMP_STAGING_BUCKET } from "@carbon/files";++/**+ * Where the table jobs keep their files: the `temp-staging` bucket, under the+ * company's prefix. The nightly cleanup (`prune-staged-raw-models`) deletes an+ * object there after 7 days, so a file a job could not remove still goes.+ */++/** The finished export. Per user: the ERP's export download route+ * (`api+/table.export.$exportId.ts`) serves it to this user only. */+export function tableExportStorageKey(+ companyId: string,+ userId: string,+ exportId: string+): string {+ return `${companyId}/exports/${userId}/${exportId}.csv`;+}++/** One part of an export, written by one step. The last step joins them. */+export function tableExportPartKey(+ companyId: string,+ userId: string,+ exportId: string,+ part: number+): string {+ return `${companyId}/exports/${userId}/${exportId}.parts/${part}.csv`;+}++/** The ids one collect step of a bulk action read, as a JSON array. */+export function tableBulkIdsKey(+ companyId: string,+ bulkActionId: string,+ file: number+): string {+ return `${companyId}/bulk-actions/${bulkActionId}/${file}.json`;+}++/** The storage the table jobs use. Every call throws on failure. */+export interface TableJobStorage {+ upload(+ key: string,+ body: string | ReadableStream<Uint8Array>,+ contentType: string+ ): Promise<void>;+ download(key: string): Promise<Uint8Array>;+ remove(keys: string[]): Promise<void>;+}++/** `temp-staging`, read and written with the service role. */+export function tempStagingStorage(): TableJobStorage {+ const bucket = () => getCarbonServiceRole().storage.from(TEMP_STAGING_BUCKET);+ return {+ async upload(key, body, contentType) {+ // storage-js sends a ReadableStream as the request body with+ // `duplex: "half"`, so a stream is never held in memory whole.+ const result = await bucket().upload(key, body, {+ contentType,+ upsert: true+ });+ if (result.error) throw result.error;+ },+ async download(key) {+ const result = await bucket().download(key);+ if (result.error) throw result.error;+ return new Uint8Array(await result.data.arrayBuffer());+ },+ async remove(keys) {+ if (keys.length === 0) return;+ const result = await bucket().remove(keys);+ if (result.error) throw result.error;+ }+ };+}diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.tsindex ae312617b7..9309399875 100644--- a/packages/lib/src/events.ts+++ b/packages/lib/src/events.ts@@ -660,6 +660,59 @@ export type Events = {};};+ // A table's CSV export past the browser's 1,000-row limit. The ERP route+ // (api+/table.export.ts) takes the per-company lock and sends it; the job+ // pages the list's registry query as the user and notifies them with the file.+ "carbon/table-export": {+ data: {+ companyId: string;+ userId: string;+ // The file's id, `{listKey}.{random}`: the file is+ // `{companyId}/exports/{userId}/{exportId}.csv` in temp-staging, served+ // to this user only by the ERP's export download route.+ exportId: string;+ // A key of the ERP's list registry (`utils/list-registry`).+ listKey: string;+ // The list's URL search (filters, sorts, search), with or without "?".+ search: string;+ // The visible columns in display order, with their translated headers.+ columns: Array<{ key: string; label: string }>;+ };+ };++ // A table's bulk action on every row that matches the list's URL search,+ // past the browser's 1,000-row limit. The ERP action route takes the+ // per-company lock and sends it; the job pages the list's ids as the user+ // (10,000 rows per step, stored in temp-staging), runs the action one slice+ // per step, 100 ids per call, and notifies the user with the counts.+ "carbon/table-bulk-action": {+ data: {+ companyId: string;+ userId: string;+ // The run's id; also the value of the per-company Redis lock.+ bulkActionId: string;+ // A key of the ERP's bulk actions (`utils/table-jobs.server.ts`).+ actionKey: string;+ // The action's English name for the notification ("Release jobs").+ actionLabel: string;+ // The action's own values, for example `{ field, value }`.+ params: Record<string, unknown>;+ // A key of the ERP's list registry (`utils/list-registry`).+ listKey: string;+ // The list's URL search (filters, sorts, search), with or without "?".+ search: string;+ // The most rows the run acts on (default 100,000). Jobs Release and+ // Batches Release stop at 2,000.+ maxRows?: number;+ // Ids per apply step (default 1,000); an action that does more per+ // row sets fewer, so one step stays well below 600 s.+ idsPerStep?: number;+ // The rows the user selected, when there are too many for one request.+ // The run acts on these ids and reads no list pages; `search` is "".+ ids?: string[];+ };+ };+// Onshape released-asset backfill / reconcile"carbon/onshape-backfill": {data: {diff --git a/packages/lib/src/trigger.ts b/packages/lib/src/trigger.tsindex 0cf61b63eb..6724213636 100644--- a/packages/lib/src/trigger.ts+++ b/packages/lib/src/trigger.ts@@ -48,6 +48,8 @@ const taskToEvent = {"sync-external-accounting": "carbon/sync-external-accounting","sync-issue-from-jira": "carbon/jira-sync","sync-issue-from-linear": "carbon/linear-sync",+ "table-bulk-action": "carbon/table-bulk-action",+ "table-export": "carbon/table-export","update-permissions": "carbon/update-permissions","user-admin": "carbon/user-admin","extract-document": "carbon/extract-document",diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 58fc6f83cd..75a777bb5c 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -93,6 +93,10 @@ msgstr "{0, plural, one {# Zeile verweist auf Daten außerhalb dieses Unternehmemsgid "{0, plural, one {# week} other {# weeks}}"msgstr "{0, plural, one {# Woche} other {# Wochen}}"+#. placeholder {0}: allMatching.count+msgid "{0, plural, one {All matching rows selected (about #)} other {All matching rows selected (about #)}}"+msgstr "{0, plural, one {Alle passenden Zeilen ausgewählt (etwa #)} other {Alle passenden Zeilen ausgewählt (etwa #)}}"+#. placeholder {0}: check.countmsgid "{0, plural, one {Complete or cancel the # job that took costs before Carbon recorded them.} other {Complete or cancel the # jobs that took costs before Carbon recorded them.}}"msgstr "{0, plural, one {Schließen Sie den # Fertigungsauftrag ab oder brechen Sie ihn ab, der Kosten verursacht hat, bevor Carbon sie aufzeichnete.} other {Schließen Sie die # Fertigungsaufträge ab oder brechen Sie sie ab, die Kosten verursacht haben, bevor Carbon sie aufzeichnete.}}"@@ -113,6 +117,10 @@ msgstr "{0, plural, one {Der Planer behandelt diese Komponente als einen starrenmsgid "{0, plural, one {This item is on 1 open change notice} other {This item is on # open change notices}}"msgstr "{0, plural, one {Dieser Artikel ist auf 1 offener Änderungsmitteilung} other {Dieser Artikel ist auf # offenen Änderungsmitteilungen}}"+#. placeholder {0}: rows.length+msgid "{0, plural, one {Total of # loaded row} other {Total of # loaded rows}}"+msgstr "{0, plural, one {Insgesamt # geladene Zeile} other {Insgesamt # geladene Zeilen}}"+#. placeholder {0}: rate.customerType.namemsgid "{0} (type)"msgstr "{0} (Typ)"@@ -252,6 +260,10 @@ msgstr "{0} von {1}"msgid "{0} of {1} posting accounts mapped"msgstr "{0} von {1} Buchungskonten zugeordnet"+#. placeholder {0}: rows.length+msgid "{0} of {count} operations"+msgstr "{0} von {count} Arbeitsgängen"+#. placeholder {0}: rows.lengthmsgid "{0} of {maxSlots} provider slots used"msgstr "{0} von {maxSlots} Provider-Slots verwendet"@@ -441,6 +453,12 @@ msgstr "{count, plural, one {# Kurs} other {# Kurse}}"msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"msgstr "{count, plural, one {# weitere nach {fenceLabel}} other {# weitere nach {fenceLabel}}}"+msgid "{count, plural, one {# row} other {# rows}}"+msgstr "{count, plural, one {# Zeile} other {# Zeilen}}"++msgid "{count, plural, one {about # row} other {about # rows}}"+msgstr "{count, plural, one {etwa # Zeile} other {etwa # Zeilen}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {# Los auflösen} other {# Lose auflösen}}"@@ -456,6 +474,12 @@ msgstr "{count, plural, one {# Los freigegeben} other {# Lose freigegeben}}"msgid "{count, plural, one {Released # job} other {Released # jobs}}"msgstr "{count, plural, one {# Fertigungsauftrag freigegeben} other {# Fertigungsaufträge freigegeben}}"+msgid "{count, plural, one {Select all # matching row} other {Select all # matching rows}}"+msgstr "{count, plural, one {Alle # passende Zeile auswählen} other {Alle # passenden Zeilen auswählen}}"++msgid "{count, plural, one {Select all matching rows (about #)} other {Select all matching rows (about #)}}"+msgstr "{count, plural, one {Alle passenden Zeilen auswählen (etwa #)} other {Alle passenden Zeilen auswählen (etwa #)}}"+msgid "{count} of {total} units"msgstr "{count} von {total} Einheiten"@@ -486,12 +510,6 @@ msgstr "{done} von {total} Phasen abgeschlossen"msgid "{excluded, plural, one {# row excluded} other {# rows excluded}}"msgstr "{excluded, plural, one {# Zeile ausgeschlossen} other {# Zeilen ausgeschlossen}}"-msgid "{from}–{to} of {count}"-msgstr "{from}–{to} von {count}"--msgid "{from}–{to} of {count} operations"-msgstr "{from}–{to} von {count} Arbeitsgängen"-msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"msgstr "{hidden, plural, one {Und # weiterer Datensatz.} other {Und # weitere Datensätze.}}"@@ -515,6 +533,12 @@ msgstr "{linesCount, plural, one {# Zeile} other {# Zeilen}}"msgid "{load} in queue"msgstr "{load} in Warteschlange"+msgid "{loadedLabel} of {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} von {total, plural, one {# Zeile} other {# Zeilen}}"++msgid "{loadedLabel} of about {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} von etwa {total, plural, one {# Zeile} other {# Zeilen}}"+msgid "{locationName} (the lease's)"msgstr "{locationName} (des Leasings)"@@ -607,6 +631,9 @@ msgstr "{scopeCount} Berechtigungen"msgid "{sectionLineCount} lines"msgstr "{sectionLineCount} Positionen"+msgid "{selectedCount, plural, one {# selected} other {# selected}}"+msgstr "{selectedCount, plural, one {# ausgewählt} other {# ausgewählt}}"+msgid "{selectedCount} selected"msgstr "{selectedCount} ausgewählt"@@ -622,6 +649,9 @@ msgstr "{total} Phasen bis zur Live-Schaltung"msgid "{totalCount} results"msgstr "{totalCount} Ergebnisse"+msgid "{totalLoaded} of {count}"+msgstr "{totalLoaded} von {count}"+msgid "{totalQuantity, plural, one {# unit} other {# units}}"msgstr "{totalQuantity, plural, one {# Einheit} other {# Einheiten}}"@@ -2316,6 +2346,9 @@ msgstr "Alle Standorte"msgid "all make {0}"msgstr "alle Eigenfertigung {0}"+msgid "All matching rows selected"+msgstr "Alle passenden Zeilen ausgewählt"+msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "Alle Mitglieder der ausgewählten Gruppen und ausgewählten Personen können Anfragen genehmigen"@@ -5959,6 +5992,9 @@ msgstr "Konnte die Onshape Government-Verbindung nicht abschließen"msgid "Couldn't load documents"msgstr "Dokumente konnten nicht geladen werden"+msgid "Couldn't load more rows"+msgstr "Weitere Zeilen konnten nicht geladen werden"+msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "Konnte zugehörige Dokumente nicht laden. Aktualisieren Sie den Bereich, bevor Sie ein neues Dokument erstellen, um Duplikate zu vermeiden."@@ -7766,6 +7802,9 @@ msgstr "Batch auflösen"msgid "Dissolve Batch"msgstr "Batch auflösen"+msgid "Dissolve batches"+msgstr "Lose auflösen"+#. placeholder {0}: batch.readableIdmsgid "Dissolving {0} returns its {memberCount} operations to the schedule un-run and deletes the batch. A batch with recorded production must be completed instead."msgstr "Das Auflösen von {0} gibt seine {memberCount} Arbeitsgänge als nicht ausgeführt zur Planung zurück und löscht das Los. Ein Los mit erfasster Produktion muss stattdessen abgeschlossen werden."@@ -9087,6 +9126,9 @@ msgstr "Jede Zeile wurde erfolgreich importiert."msgid "Every unit has a rate."msgstr "Jede Einheit hat einen Satz."+msgid "Every user that matches the list's filters. Users this action does not apply to are skipped."+msgstr "Jeder Benutzer, der den Filtern der Liste entspricht. Benutzer, auf die diese Aktion nicht zutrifft, werden übersprungen."+msgid "Everyone must set up an authenticator app before opening this company."msgstr "Jeder muss eine Authentifizierungs-App einrichten, bevor er dieses Unternehmen öffnet."@@ -9328,6 +9370,9 @@ msgstr "CSV exportieren"msgid "Export Lines to CSV"msgstr "Zeilen als CSV exportieren"+msgid "Exported the first {exportedCount} rows."+msgstr "Die ersten {exportedCount} Zeilen exportiert."+msgid "Extended Price"msgstr "Erweiterte Preis"@@ -9885,6 +9930,12 @@ msgstr "Filtern und Sortieren"msgid "Filter by…"msgstr "Filtern nach…"+msgid "Filter the list to {limit} rows or fewer"+msgstr "Liste auf {limit} Zeilen oder weniger filtern"++msgid "Filter the list to {rows} rows or fewer"+msgstr "Liste auf {rows} Zeilen oder weniger filtern"+msgid "Filters"msgstr "Filter"@@ -11509,7 +11560,7 @@ msgid "Invoice schedule"msgstr "Rechnungsplan"msgid "Invoice Separately"-msgstr ""+msgstr "Separat in Rechnung stellen"msgid "Invoice settlement"msgstr "Rechnungsabrechnung"@@ -11542,7 +11593,7 @@ msgid "Invoiced Amount:"msgstr "Fakturierter Betrag:"msgid "Invoiced separately"-msgstr ""+msgstr "Separat fakturiert"msgid "Invoiced Statuses"msgstr "Fakturierte Status"@@ -12438,9 +12489,6 @@ msgstr "Live-Neuladen"msgid "Load"msgstr "Auslastung"-msgid "Load more"-msgstr "Mehr laden"-msgid "Load newer"msgstr "Neuere laden"@@ -12465,6 +12513,9 @@ msgstr "Aktuelle Menge wird geladen…"msgid "Loading item details..."msgstr "Artikeldetails werden geladen..."+msgid "Loading more rows"+msgstr "Weitere Zeilen werden geladen"+msgid "Loading returnable lines..."msgstr "Rückgabefähige Zeilen werden geladen..."@@ -17123,7 +17174,7 @@ msgid "Push to accounting"msgstr "Zur Buchhaltung senden"msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."-msgstr ""+msgstr "Diese Gebühr auf eine eigene Rechnung setzen, die vor dem Buchen geprüft wird. Andernfalls wird sie auf der nächsten Rechnung der Vereinbarung abgerechnet."msgid "Putting your data back"msgstr "Ihre Daten werden wiederhergestellt"@@ -17877,6 +17928,9 @@ msgstr "Los freigeben"msgid "Release batch {0}"msgstr "Los {0} freigeben"+msgid "Release batches"+msgstr "Lose freigeben"+msgid "Release change notice"msgstr "Änderungsmitteilung freigeben"@@ -18451,9 +18505,6 @@ msgstr "Ergebnis"msgid "Results"msgstr "Ergebnisse"-msgid "Results per page"-msgstr "Ergebnisse pro Seite"-msgid "Resume"msgstr "Fortsetzen"@@ -18852,9 +18903,6 @@ msgstr "Arbeitsplan"msgid "Routing Number (ABA)"msgstr "Routing-Nummer (ABA)"-msgid "rows"-msgstr "Zeilen"-msgid "Rows left out of this backup"msgstr "Zeilen, die aus dieser Sicherung ausgelassen wurden"@@ -18930,6 +18978,9 @@ msgstr "Diesen Workflow jetzt ausführen?"msgid "Running"msgstr "Wird ausgeführt"+msgid "Running in the background. We'll notify you when it's done."+msgstr "Läuft im Hintergrund. Wir benachrichtigen Sie, sobald es fertig ist."+msgid "Running inventory after each week's supply and demand — the line."msgstr "Bestandsverwaltung nach wöchentlicher Deckung und Bedarf — die Zeile."@@ -19704,6 +19755,9 @@ msgstr "Lieferantentyp auswählen"msgid "Select surfaces"msgstr "Oberflächen auswählen"+msgid "Select the first {limit} rows"+msgstr "Die ersten {limit} Zeilen auswählen"+msgid "Select the groups that should complete this training"msgstr "Wählen Sie die Gruppen aus, die diese Schulung absolvieren sollen"@@ -19967,7 +20021,7 @@ msgid "Set Up Accounting"msgstr "Buchhaltung einrichten"msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."-msgstr ""+msgstr "Richten Sie die Buchhaltung ein, um Berichte, Buchungssätze, Buchungsperioden, Abschreibungsläufe und mehr zu nutzen."msgid "Set up authenticator app"msgstr "Authentifizierungs-App einrichten"@@ -20351,12 +20405,12 @@ msgstr "Zeige {0} von {totalCount} — verfeinern Sie Ihre Suche"msgid "Showing {0} of {totalFiltered} — refine your search"msgstr "Zeige {0} von {totalFiltered} — verfeinern Sie Ihre Suche"-msgid "Showing {firstShown}–{lastShown} of {total}"-msgstr "Zeigt {firstShown}–{lastShown} von {total}"-msgid "Showing in {parentCurrency}"msgstr "Anzeige in {parentCurrency}"+msgid "Showing the first {limit} rows. Search or filter to see the rest."+msgstr "Die ersten {limit} Zeilen werden angezeigt. Suchen Sie oder filtern Sie die Liste, um den Rest zu sehen."+msgid "Showing the first 500 lines"msgstr "Die ersten 500 Zeilen werden angezeigt"@@ -22000,6 +22054,9 @@ msgstr "Der erwartete Prozentsatz der Ausgabe dieses Artikels, der während dermsgid "The expense account this indirect-spend line posts to; required because indirect lines don't have an item ledger entry to derive the account from."msgstr "Das Aufwandskonto, auf das diese indirekte Ausgabenzeile gebucht wird; erforderlich, da indirekte Zeilen keinen Bestandsposten haben, von dem das Konto abgeleitet werden kann."+msgid "The export could not start. Try again."+msgstr "Der Export konnte nicht gestartet werden. Versuchen Sie es erneut."+msgid "The file you uploaded and the mappings you've made will be lost."msgstr "Die hochgeladene Datei und die vorgenommenen Zuordnungen gehen verloren."@@ -22182,6 +22239,9 @@ msgstr "Der Lebenszykluszustand dieses Kunden – Aktiv, Interessent, Inaktiv, umsgid "The lifecycle state of this supplier — Active, Inactive, Pending Approval, etc.; only Active suppliers appear in PO / quote selectors."msgstr "Der Lebenszykluszustand dieses Lieferanten – Aktiv, Inaktiv, Genehmigung Ausstehend, usw.; nur aktive Lieferanten werden in PO / Angebots-Selektoren angezeigt."+msgid "The list changed while the export loaded. Try again."+msgstr "Die Liste hat sich geändert, während der Export geladen wurde. Versuchen Sie es erneut."+msgid "The local timezone this location reports time in; schedules, timecards, and shift hours at this location are interpreted in this zone regardless of the user's browser locale."msgstr "Die Zeitzone dieses Standorts; Terminpläne, Zeiterfassung und Schichtstunden an diesem Standort werden in dieser Zone interpretiert, unabhängig vom Browser-Gebietsschema des Benutzers."@@ -24140,6 +24200,9 @@ msgstr "Bestellmengen aktualisieren"msgid "Updated"msgstr "Aktualisiert"+msgid "Updated {done}. Could not update {failed}: {message}"+msgstr "{done} aktualisiert. {failed} konnten nicht aktualisiert werden: {message}"+msgid "Updated account"msgstr "Konto aktualisiert"@@ -25629,6 +25692,9 @@ msgstr "Ihr DNS-Anbieter kann Ihre Domäne möglicherweise automatisch an den Eimsgid "Your Email"msgstr "Ihre E-Mail"+msgid "Your export is being prepared. We'll notify you when it's ready."+msgstr "Ihr Export wird vorbereitet. Wir benachrichtigen Sie, sobald er bereit ist."+msgid "Your general-ledger accounts and their structure"msgstr "Ihre Hauptbuchkonten und deren Struktur"diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 7d7711d027..2b5efe0e23 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -93,6 +93,10 @@ msgstr "{0, plural, one {# row links to data outside this company, so it can't bmsgid "{0, plural, one {# week} other {# weeks}}"msgstr "{0, plural, one {# week} other {# weeks}}"+#. placeholder {0}: allMatching.count+msgid "{0, plural, one {All matching rows selected (about #)} other {All matching rows selected (about #)}}"+msgstr "{0, plural, one {All matching rows selected (about #)} other {All matching rows selected (about #)}}"+#. placeholder {0}: check.countmsgid "{0, plural, one {Complete or cancel the # job that took costs before Carbon recorded them.} other {Complete or cancel the # jobs that took costs before Carbon recorded them.}}"msgstr "{0, plural, one {Complete or cancel the # job that took costs before Carbon recorded them.} other {Complete or cancel the # jobs that took costs before Carbon recorded them.}}"@@ -113,6 +117,10 @@ msgstr "{0, plural, one {The planner treats this component as one rigid body —msgid "{0, plural, one {This item is on 1 open change notice} other {This item is on # open change notices}}"msgstr "{0, plural, one {This item is on 1 open change notice} other {This item is on # open change notices}}"+#. placeholder {0}: rows.length+msgid "{0, plural, one {Total of # loaded row} other {Total of # loaded rows}}"+msgstr "{0, plural, one {Total of # loaded row} other {Total of # loaded rows}}"+#. placeholder {0}: rate.customerType.namemsgid "{0} (type)"msgstr "{0} (type)"@@ -252,6 +260,10 @@ msgstr "{0} of {1}"msgid "{0} of {1} posting accounts mapped"msgstr "{0} of {1} posting accounts mapped"+#. placeholder {0}: rows.length+msgid "{0} of {count} operations"+msgstr "{0} of {count} operations"+#. placeholder {0}: rows.lengthmsgid "{0} of {maxSlots} provider slots used"msgstr "{0} of {maxSlots} provider slots used"@@ -441,6 +453,12 @@ msgstr "{count, plural, one {# course} other {# courses}}"msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"msgstr "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"+msgid "{count, plural, one {# row} other {# rows}}"+msgstr "{count, plural, one {# row} other {# rows}}"++msgid "{count, plural, one {about # row} other {about # rows}}"+msgstr "{count, plural, one {about # row} other {about # rows}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"@@ -456,6 +474,12 @@ msgstr "{count, plural, one {Released # batch} other {Released # batches}}"msgid "{count, plural, one {Released # job} other {Released # jobs}}"msgstr "{count, plural, one {Released # job} other {Released # jobs}}"+msgid "{count, plural, one {Select all # matching row} other {Select all # matching rows}}"+msgstr "{count, plural, one {Select all # matching row} other {Select all # matching rows}}"++msgid "{count, plural, one {Select all matching rows (about #)} other {Select all matching rows (about #)}}"+msgstr "{count, plural, one {Select all matching rows (about #)} other {Select all matching rows (about #)}}"+msgid "{count} of {total} units"msgstr "{count} of {total} units"@@ -486,12 +510,6 @@ msgstr "{done} of {total} phases complete"msgid "{excluded, plural, one {# row excluded} other {# rows excluded}}"msgstr "{excluded, plural, one {# row excluded} other {# rows excluded}}"-msgid "{from}–{to} of {count}"-msgstr "{from}–{to} of {count}"--msgid "{from}–{to} of {count} operations"-msgstr "{from}–{to} of {count} operations"-msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"msgstr "{hidden, plural, one {And # more record.} other {And # more records.}}"@@ -515,6 +533,12 @@ msgstr "{linesCount, plural, one {# line} other {# lines}}"msgid "{load} in queue"msgstr "{load} in queue"+msgid "{loadedLabel} of {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} of {total, plural, one {# row} other {# rows}}"++msgid "{loadedLabel} of about {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} of about {total, plural, one {# row} other {# rows}}"+msgid "{locationName} (the lease's)"msgstr "{locationName} (the lease's)"@@ -607,6 +631,9 @@ msgstr "{scopeCount} permissions"msgid "{sectionLineCount} lines"msgstr "{sectionLineCount} lines"+msgid "{selectedCount, plural, one {# selected} other {# selected}}"+msgstr "{selectedCount, plural, one {# selected} other {# selected}}"+msgid "{selectedCount} selected"msgstr "{selectedCount} selected"@@ -622,6 +649,9 @@ msgstr "{total} phases to go live"msgid "{totalCount} results"msgstr "{totalCount} results"+msgid "{totalLoaded} of {count}"+msgstr "{totalLoaded} of {count}"+msgid "{totalQuantity, plural, one {# unit} other {# units}}"msgstr "{totalQuantity, plural, one {# unit} other {# units}}"@@ -2316,6 +2346,9 @@ msgstr "All Locations"msgid "all make {0}"msgstr "all make {0}"+msgid "All matching rows selected"+msgstr "All matching rows selected"+msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "All members of selected groups and selected individuals will be able to approve requests"@@ -5959,6 +5992,9 @@ msgstr "Couldn't complete the Onshape Government connection"msgid "Couldn't load documents"msgstr "Couldn't load documents"+msgid "Couldn't load more rows"+msgstr "Couldn't load more rows"+msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."@@ -7766,6 +7802,9 @@ msgstr "Dissolve batch"msgid "Dissolve Batch"msgstr "Dissolve Batch"+msgid "Dissolve batches"+msgstr "Dissolve batches"+#. placeholder {0}: batch.readableIdmsgid "Dissolving {0} returns its {memberCount} operations to the schedule un-run and deletes the batch. A batch with recorded production must be completed instead."msgstr "Dissolving {0} returns its {memberCount} operations to the schedule un-run and deletes the batch. A batch with recorded production must be completed instead."@@ -9087,6 +9126,9 @@ msgstr "Every row was imported successfully."msgid "Every unit has a rate."msgstr "Every unit has a rate."+msgid "Every user that matches the list's filters. Users this action does not apply to are skipped."+msgstr "Every user that matches the list's filters. Users this action does not apply to are skipped."+msgid "Everyone must set up an authenticator app before opening this company."msgstr "Everyone must set up an authenticator app before opening this company."@@ -9328,6 +9370,9 @@ msgstr "Export CSV"msgid "Export Lines to CSV"msgstr "Export Lines to CSV"+msgid "Exported the first {exportedCount} rows."+msgstr "Exported the first {exportedCount} rows."+msgid "Extended Price"msgstr "Extended Price"@@ -9885,6 +9930,12 @@ msgstr "Filter and sort"msgid "Filter by…"msgstr "Filter by…"+msgid "Filter the list to {limit} rows or fewer"+msgstr "Filter the list to {limit} rows or fewer"++msgid "Filter the list to {rows} rows or fewer"+msgstr "Filter the list to {rows} rows or fewer"+msgid "Filters"msgstr "Filters"@@ -12438,9 +12489,6 @@ msgstr "Live reloading"msgid "Load"msgstr "Load"-msgid "Load more"-msgstr "Load more"-msgid "Load newer"msgstr "Load newer"@@ -12465,6 +12513,9 @@ msgstr "Loading current quantity…"msgid "Loading item details..."msgstr "Loading item details..."+msgid "Loading more rows"+msgstr "Loading more rows"+msgid "Loading returnable lines..."msgstr "Loading returnable lines..."@@ -17877,6 +17928,9 @@ msgstr "Release Batch"msgid "Release batch {0}"msgstr "Release batch {0}"+msgid "Release batches"+msgstr "Release batches"+msgid "Release change notice"msgstr "Release change notice"@@ -18451,9 +18505,6 @@ msgstr "Result"msgid "Results"msgstr "Results"-msgid "Results per page"-msgstr "Results per page"-msgid "Resume"msgstr "Resume"@@ -18852,9 +18903,6 @@ msgstr "Routing"msgid "Routing Number (ABA)"msgstr "Routing Number (ABA)"-msgid "rows"-msgstr "rows"-msgid "Rows left out of this backup"msgstr "Rows left out of this backup"@@ -18930,6 +18978,9 @@ msgstr "Run this workflow now?"msgid "Running"msgstr "Running"+msgid "Running in the background. We'll notify you when it's done."+msgstr "Running in the background. We'll notify you when it's done."+msgid "Running inventory after each week's supply and demand — the line."msgstr "Running inventory after each week's supply and demand — the line."@@ -19704,6 +19755,9 @@ msgstr "Select Supplier Type"msgid "Select surfaces"msgstr "Select surfaces"+msgid "Select the first {limit} rows"+msgstr "Select the first {limit} rows"+msgid "Select the groups that should complete this training"msgstr "Select the groups that should complete this training"@@ -20351,12 +20405,12 @@ msgstr "Showing {0} of {totalCount} — refine your search"msgid "Showing {0} of {totalFiltered} — refine your search"msgstr "Showing {0} of {totalFiltered} — refine your search"-msgid "Showing {firstShown}–{lastShown} of {total}"-msgstr "Showing {firstShown}–{lastShown} of {total}"-msgid "Showing in {parentCurrency}"msgstr "Showing in {parentCurrency}"+msgid "Showing the first {limit} rows. Search or filter to see the rest."+msgstr "Showing the first {limit} rows. Search or filter to see the rest."+msgid "Showing the first 500 lines"msgstr "Showing the first 500 lines"@@ -22000,6 +22054,9 @@ msgstr "The expected percentage of this item's output lost during production; plmsgid "The expense account this indirect-spend line posts to; required because indirect lines don't have an item ledger entry to derive the account from."msgstr "The expense account this indirect-spend line posts to; required because indirect lines don't have an item ledger entry to derive the account from."+msgid "The export could not start. Try again."+msgstr "The export could not start. Try again."+msgid "The file you uploaded and the mappings you've made will be lost."msgstr "The file you uploaded and the mappings you've made will be lost."@@ -22182,6 +22239,9 @@ msgstr "The lifecycle state of this customer — Active, Prospect, Inactive, etcmsgid "The lifecycle state of this supplier — Active, Inactive, Pending Approval, etc.; only Active suppliers appear in PO / quote selectors."msgstr "The lifecycle state of this supplier — Active, Inactive, Pending Approval, etc.; only Active suppliers appear in PO / quote selectors."+msgid "The list changed while the export loaded. Try again."+msgstr "The list changed while the export loaded. Try again."+msgid "The local timezone this location reports time in; schedules, timecards, and shift hours at this location are interpreted in this zone regardless of the user's browser locale."msgstr "The local timezone this location reports time in; schedules, timecards, and shift hours at this location are interpreted in this zone regardless of the user's browser locale."@@ -24140,6 +24200,9 @@ msgstr "Update the purchase order quantities"msgid "Updated"msgstr "Updated"+msgid "Updated {done}. Could not update {failed}: {message}"+msgstr "Updated {done}. Could not update {failed}: {message}"+msgid "Updated account"msgstr "Updated account"@@ -25632,6 +25695,9 @@ msgstr "Your DNS provider may auto-append your domain to the record name — ifmsgid "Your Email"msgstr "Your Email"+msgid "Your export is being prepared. We'll notify you when it's ready."+msgstr "Your export is being prepared. We'll notify you when it's ready."+msgid "Your general-ledger accounts and their structure"msgstr "Your general-ledger accounts and their structure"diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex e79629add8..3a32e58c67 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -93,6 +93,10 @@ msgstr "{0, plural, one {# fila vincula a datos fuera de esta empresa, por lo qumsgid "{0, plural, one {# week} other {# weeks}}"msgstr "{0, plural, one {# semana} other {# semanas}}"+#. placeholder {0}: allMatching.count+msgid "{0, plural, one {All matching rows selected (about #)} other {All matching rows selected (about #)}}"+msgstr "{0, plural, one {Todas las filas coincidentes seleccionadas (aprox. #)} other {Todas las filas coincidentes seleccionadas (aprox. #)}}"+#. placeholder {0}: check.countmsgid "{0, plural, one {Complete or cancel the # job that took costs before Carbon recorded them.} other {Complete or cancel the # jobs that took costs before Carbon recorded them.}}"msgstr "{0, plural, one {Completar o cancelar la # Orden de trabajo que tuvo costos antes de que Carbon los registrara.} other {Completar o cancelar las # Órdenes de trabajo que tuvieron costos antes de que Carbon los registrara.}}"@@ -113,6 +117,10 @@ msgstr "{0, plural, one {El planificador trata este componente como un cuerpo rmsgid "{0, plural, one {This item is on 1 open change notice} other {This item is on # open change notices}}"msgstr "{0, plural, one {Este artículo está en 1 aviso de cambio abierto} other {Este artículo está en # avisos de cambio abiertos}}"+#. placeholder {0}: rows.length+msgid "{0, plural, one {Total of # loaded row} other {Total of # loaded rows}}"+msgstr "{0, plural, one {En total, # fila cargada} other {En total, # filas cargadas}}"+#. placeholder {0}: rate.customerType.namemsgid "{0} (type)"msgstr "{0} (tipo)"@@ -252,6 +260,10 @@ msgstr "{0} de {1}"msgid "{0} of {1} posting accounts mapped"msgstr "{0} de {1} cuentas de contabilización asignadas"+#. placeholder {0}: rows.length+msgid "{0} of {count} operations"+msgstr "{0} de {count} operaciones"+#. placeholder {0}: rows.lengthmsgid "{0} of {maxSlots} provider slots used"msgstr "{0} de {maxSlots} espacios de proveedor utilizados"@@ -441,6 +453,12 @@ msgstr "{count, plural, one {# curso} other {# cursos}}"msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"msgstr "{count, plural, one {# más después de {fenceLabel}} other {# más después de {fenceLabel}}}"+msgid "{count, plural, one {# row} other {# rows}}"+msgstr "{count, plural, one {# fila} other {# filas}}"++msgid "{count, plural, one {about # row} other {about # rows}}"+msgstr "{count, plural, one {aprox. # fila} other {aprox. # filas}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {Disolver # lote de producción} other {Disolver # lotes de producción}}"@@ -456,6 +474,12 @@ msgstr "{count, plural, one {Liberado # lote de producción} other {Liberados #msgid "{count, plural, one {Released # job} other {Released # jobs}}"msgstr "{count, plural, one {Liberada # orden de trabajo} other {Liberadas # órdenes de trabajo}}"+msgid "{count, plural, one {Select all # matching row} other {Select all # matching rows}}"+msgstr "{count, plural, one {Seleccionar # fila coincidente} other {Seleccionar todas las # filas coincidentes}}"++msgid "{count, plural, one {Select all matching rows (about #)} other {Select all matching rows (about #)}}"+msgstr "{count, plural, one {Seleccionar todas las filas coincidentes (aprox. #)} other {Seleccionar todas las filas coincidentes (aprox. #)}}"+msgid "{count} of {total} units"msgstr "{count} de {total} unidades"@@ -486,12 +510,6 @@ msgstr "{done} de {total} fases completadas"msgid "{excluded, plural, one {# row excluded} other {# rows excluded}}"msgstr "{excluded, plural, one {# fila excluida} other {# filas excluidas}}"-msgid "{from}–{to} of {count}"-msgstr "{from}–{to} de {count}"--msgid "{from}–{to} of {count} operations"-msgstr "{from}–{to} de {count} operaciones"-msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"msgstr "{hidden, plural, one {Y # registro más.} other {Y # registros más.}}"@@ -515,6 +533,12 @@ msgstr "{linesCount, plural, one {# línea} other {# líneas}}"msgid "{load} in queue"msgstr "{load} en cola"+msgid "{loadedLabel} of {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} de {total, plural, one {# fila} other {# filas}}"++msgid "{loadedLabel} of about {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} de aprox. {total, plural, one {# fila} other {# filas}}"+msgid "{locationName} (the lease's)"msgstr "{locationName} (del arrendamiento)"@@ -607,6 +631,9 @@ msgstr "{scopeCount} permisos"msgid "{sectionLineCount} lines"msgstr "{sectionLineCount} líneas"+msgid "{selectedCount, plural, one {# selected} other {# selected}}"+msgstr "{selectedCount, plural, one {# seleccionado} other {# seleccionados}}"+msgid "{selectedCount} selected"msgstr "{selectedCount} seleccionados"@@ -622,6 +649,9 @@ msgstr "{total} fases para activar"msgid "{totalCount} results"msgstr "{totalCount} resultados"+msgid "{totalLoaded} of {count}"+msgstr "{totalLoaded} de {count}"+msgid "{totalQuantity, plural, one {# unit} other {# units}}"msgstr "{totalQuantity, plural, one {# unidad} other {# unidades}}"@@ -2316,6 +2346,9 @@ msgstr "Todas las Ubicaciones"msgid "all make {0}"msgstr "todos fabricados {0}"+msgid "All matching rows selected"+msgstr "Todas las filas coincidentes seleccionadas"+msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "Todos los miembros de los grupos seleccionados e individuos seleccionados podrán aprobar solicitudes"@@ -5959,6 +5992,9 @@ msgstr "No se pudo completar la conexión con Onshape Government"msgid "Couldn't load documents"msgstr "No se pudieron cargar los documentos"+msgid "Couldn't load more rows"+msgstr "No se pudieron cargar más filas"+msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "No se pudieron cargar los documentos relacionados. Actualice antes de crear uno nuevo para evitar duplicados."@@ -7766,6 +7802,9 @@ msgstr "Disolver lote"msgid "Dissolve Batch"msgstr "Disolver Lote"+msgid "Dissolve batches"+msgstr "Disolver lotes de producción"+#. placeholder {0}: batch.readableIdmsgid "Dissolving {0} returns its {memberCount} operations to the schedule un-run and deletes the batch. A batch with recorded production must be completed instead."msgstr "Disolver {0} devuelve sus {memberCount} operaciones a la programación sin ejecutar y elimina el lote. Un lote con producción registrada debe completarse en su lugar."@@ -9087,6 +9126,9 @@ msgstr "Cada fila se importó correctamente."msgid "Every unit has a rate."msgstr "Cada unidad tiene una tarifa."+msgid "Every user that matches the list's filters. Users this action does not apply to are skipped."+msgstr "Todos los usuarios que coinciden con los filtros de la lista. A los usuarios a los que esta acción no aplica se les marcará como omitidos."+msgid "Everyone must set up an authenticator app before opening this company."msgstr "Todos deben configurar una aplicación autenticadora antes de abrir esta empresa."@@ -9328,6 +9370,9 @@ msgstr "Exportar CSV"msgid "Export Lines to CSV"msgstr "Exportar Líneas a CSV"+msgid "Exported the first {exportedCount} rows."+msgstr "Se exportaron las primeras {exportedCount} filas."+msgid "Extended Price"msgstr "Precio Extendido"@@ -9885,6 +9930,12 @@ msgstr "Filtrar y ordenar"msgid "Filter by…"msgstr "Filtrar por…"+msgid "Filter the list to {limit} rows or fewer"+msgstr "Filtrar la lista a {limit} filas o menos"++msgid "Filter the list to {rows} rows or fewer"+msgstr "Filtrar la lista a {rows} filas o menos"+msgid "Filters"msgstr "Filtros"@@ -11509,7 +11560,7 @@ msgid "Invoice schedule"msgstr "Programa de facturación"msgid "Invoice Separately"-msgstr ""+msgstr "Facturar por separado"msgid "Invoice settlement"msgstr "Liquidación de facturas"@@ -11542,7 +11593,7 @@ msgid "Invoiced Amount:"msgstr "Monto Facturado:"msgid "Invoiced separately"-msgstr ""+msgstr "Facturado por separado"msgid "Invoiced Statuses"msgstr "Estados Facturados"@@ -12438,9 +12489,6 @@ msgstr "Recarga en vivo"msgid "Load"msgstr "Carga"-msgid "Load more"-msgstr "Cargar más"-msgid "Load newer"msgstr "Cargar más recientes"@@ -12465,6 +12513,9 @@ msgstr "Cargando cantidad actual…"msgid "Loading item details..."msgstr "Cargando detalles del artículo..."+msgid "Loading more rows"+msgstr "Cargando más filas"+msgid "Loading returnable lines..."msgstr "Cargando líneas retornables..."@@ -17123,7 +17174,7 @@ msgid "Push to accounting"msgstr "Enviar a contabilidad"msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."-msgstr ""+msgstr "Incluye este cargo en una factura propia, retenida para revisión antes de contabilizarla. Si no, irá en la siguiente factura del acuerdo."msgid "Putting your data back"msgstr "Restaurando tus datos"@@ -17877,6 +17928,9 @@ msgstr "Liberar lote de producción"msgid "Release batch {0}"msgstr "Liberar lote de producción {0}"+msgid "Release batches"+msgstr "Liberar lotes de producción"+msgid "Release change notice"msgstr "Liberar aviso de cambio"@@ -18451,9 +18505,6 @@ msgstr "Resultado"msgid "Results"msgstr "Resultados"-msgid "Results per page"-msgstr "Resultados por página"-msgid "Resume"msgstr "Reanudar"@@ -18852,9 +18903,6 @@ msgstr "Ruta de fabricación"msgid "Routing Number (ABA)"msgstr "Número de ruta (ABA)"-msgid "rows"-msgstr "filas"-msgid "Rows left out of this backup"msgstr "Filas excluidas de esta copia de seguridad"@@ -18930,6 +18978,9 @@ msgstr "¿Ejecutar este flujo de trabajo ahora?"msgid "Running"msgstr "Ejecutando"+msgid "Running in the background. We'll notify you when it's done."+msgstr "Ejecutándose en segundo plano. Te avisaremos cuando termine."+msgid "Running inventory after each week's supply and demand — the line."msgstr "Inventario en ejecución después del suministro y la demanda de cada semana — la línea."@@ -19704,6 +19755,9 @@ msgstr "Seleccionar Tipo de Proveedor"msgid "Select surfaces"msgstr "Seleccionar superficies"+msgid "Select the first {limit} rows"+msgstr "Seleccionar las primeras {limit} filas"+msgid "Select the groups that should complete this training"msgstr "Selecciona los grupos que deben completar esta capacitación"@@ -19967,7 +20021,7 @@ msgid "Set Up Accounting"msgstr "Configurar Contabilidad"msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."-msgstr ""+msgstr "Configura la contabilidad para usar informes, asientos, períodos contables, ejecuciones de depreciación y más."msgid "Set up authenticator app"msgstr "Configurar aplicación autenticadora"@@ -20351,12 +20405,12 @@ msgstr "Mostrando {0} de {totalCount} — refina tu búsqueda"msgid "Showing {0} of {totalFiltered} — refine your search"msgstr "Mostrando {0} de {totalFiltered} — refina tu búsqueda"-msgid "Showing {firstShown}–{lastShown} of {total}"-msgstr "Mostrando {firstShown}–{lastShown} de {total}"-msgid "Showing in {parentCurrency}"msgstr "Mostrando en {parentCurrency}"+msgid "Showing the first {limit} rows. Search or filter to see the rest."+msgstr "Mostrando las primeras {limit} filas. Busca o filtra para ver el resto."+msgid "Showing the first 500 lines"msgstr "Mostrando las primeras 500 líneas"@@ -22000,6 +22054,9 @@ msgstr "El porcentaje esperado de la producción de este artículo perdido duranmsgid "The expense account this indirect-spend line posts to; required because indirect lines don't have an item ledger entry to derive the account from."msgstr "La cuenta de gastos en la que se contabiliza esta línea de gasto indirecto; es obligatoria porque las líneas indirectas no tienen un asiento de mayor de inventario del cual derivar la cuenta."+msgid "The export could not start. Try again."+msgstr "No se pudo iniciar la exportación. Inténtalo de nuevo."+msgid "The file you uploaded and the mappings you've made will be lost."msgstr "Se perderán el archivo que subiste y las asignaciones que hiciste."@@ -22182,6 +22239,9 @@ msgstr "El estado del ciclo de vida de este cliente - Activo, Prospecto, Inactivmsgid "The lifecycle state of this supplier — Active, Inactive, Pending Approval, etc.; only Active suppliers appear in PO / quote selectors."msgstr "El estado del ciclo de vida de este proveedor - Activo, Inactivo, Aprobación Pendiente, etc.; solo los proveedores Activos aparecen en PO / selectores de cotización."+msgid "The list changed while the export loaded. Try again."+msgstr "La lista cambió mientras se cargaba la exportación. Inténtalo de nuevo."+msgid "The local timezone this location reports time in; schedules, timecards, and shift hours at this location are interpreted in this zone regardless of the user's browser locale."msgstr "La zona horaria local en que esta ubicación informa la hora; programas, registro de tiempos, y horas de turno en esta ubicación se interpretan en esta zona independientemente de la configuración regional del navegador del usuario."@@ -24140,6 +24200,9 @@ msgstr "Actualizar las cantidades de la orden de compra"msgid "Updated"msgstr "Actualizado"+msgid "Updated {done}. Could not update {failed}: {message}"+msgstr "Se actualizaron {done}. No se pudieron actualizar {failed}: {message}"+msgid "Updated account"msgstr "Cuenta actualizada"@@ -25629,6 +25692,9 @@ msgstr "Tu proveedor de DNS puede añadir automáticamente tu dominio al nombremsgid "Your Email"msgstr "Tu correo electrónico"+msgid "Your export is being prepared. We'll notify you when it's ready."+msgstr "Tu exportación se está preparando. Te avisaremos cuando esté lista."+msgid "Your general-ledger accounts and their structure"msgstr "Sus cuentas del libro mayor general y su estructura"diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 7fa470d50c..f2c921e200 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -93,6 +93,10 @@ msgstr "{0, plural, one {# ligne se connecte à des données en dehors de cettemsgid "{0, plural, one {# week} other {# weeks}}"msgstr "{0, plural, one {# semaine} other {# semaines}}"+#. placeholder {0}: allMatching.count+msgid "{0, plural, one {All matching rows selected (about #)} other {All matching rows selected (about #)}}"+msgstr "{0, plural, one {Toutes les lignes correspondantes sont sélectionnées (environ #)} other {Toutes les lignes correspondantes sont sélectionnées (environ #)}}"+#. placeholder {0}: check.countmsgid "{0, plural, one {Complete or cancel the # job that took costs before Carbon recorded them.} other {Complete or cancel the # jobs that took costs before Carbon recorded them.}}"msgstr "{0, plural, one {Terminez ou annulez l'ordre de fabrication # qui a engagé des coûts avant que Carbon ne les enregistre.} other {Terminez ou annulez les # ordres de fabrication qui ont engagé des coûts avant que Carbon ne les enregistre.}}"@@ -113,6 +117,10 @@ msgstr "{0, plural, one {Le planificateur traite ce composant comme un corps rigmsgid "{0, plural, one {This item is on 1 open change notice} other {This item is on # open change notices}}"msgstr "{0, plural, one {Cet article est sur 1 avis de modification ouvert} other {Cet article est sur # avis de modification ouverts}}"+#. placeholder {0}: rows.length+msgid "{0, plural, one {Total of # loaded row} other {Total of # loaded rows}}"+msgstr "{0, plural, one {Total de # ligne chargée} other {Total de # lignes chargées}}"+#. placeholder {0}: rate.customerType.namemsgid "{0} (type)"msgstr "{0} (type)"@@ -252,6 +260,10 @@ msgstr "{0} sur {1}"msgid "{0} of {1} posting accounts mapped"msgstr "{0} sur {1} comptes de comptabilisation mappés"+#. placeholder {0}: rows.length+msgid "{0} of {count} operations"+msgstr "{0} sur {count} opérations"+#. placeholder {0}: rows.lengthmsgid "{0} of {maxSlots} provider slots used"msgstr "{0} sur {maxSlots} emplacements de fournisseur utilisés"@@ -441,6 +453,12 @@ msgstr "{count, plural, one {# cours} other {# cours}}"msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"msgstr "{count, plural, one {# plus après {fenceLabel}} other {# plus après {fenceLabel}}}"+msgid "{count, plural, one {# row} other {# rows}}"+msgstr "{count, plural, one {# ligne} other {# lignes}}"++msgid "{count, plural, one {about # row} other {about # rows}}"+msgstr "{count, plural, one {environ # ligne} other {environ # lignes}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {Dissoudre # lot de production} other {Dissoudre # lots de production}}"@@ -456,6 +474,12 @@ msgstr "{count, plural, one {# lot de production lancé} other {# lots de producmsgid "{count, plural, one {Released # job} other {Released # jobs}}"msgstr "{count, plural, one {# ordre de fabrication lancé} other {# ordres de fabrication lancés}}"+msgid "{count, plural, one {Select all # matching row} other {Select all # matching rows}}"+msgstr "{count, plural, one {Tout sélectionner (# ligne correspondante)} other {Tout sélectionner (# lignes correspondantes)}}"++msgid "{count, plural, one {Select all matching rows (about #)} other {Select all matching rows (about #)}}"+msgstr "{count, plural, one {Tout sélectionner (environ # ligne correspondante)} other {Tout sélectionner (environ # lignes correspondantes)}}"+msgid "{count} of {total} units"msgstr "{count} sur {total} unités"@@ -486,12 +510,6 @@ msgstr "{done} sur {total} phases terminées"msgid "{excluded, plural, one {# row excluded} other {# rows excluded}}"msgstr "{excluded, plural, one {# ligne exclue} other {# lignes exclues}}"-msgid "{from}–{to} of {count}"-msgstr "{from}–{to} sur {count}"--msgid "{from}–{to} of {count} operations"-msgstr "{from}–{to} sur {count} opérations"-msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"msgstr "{hidden, plural, one {Et # enregistrement de plus.} other {Et # enregistrements de plus.}}"@@ -515,6 +533,12 @@ msgstr "{linesCount, plural, one {# ligne} other {# lignes}}"msgid "{load} in queue"msgstr "{load} en attente"+msgid "{loadedLabel} of {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} sur {total, plural, one {# ligne} other {# lignes}}"++msgid "{loadedLabel} of about {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} sur environ {total, plural, one {# ligne} other {# lignes}}"+msgid "{locationName} (the lease's)"msgstr "{locationName} (de la location)"@@ -607,6 +631,9 @@ msgstr "{scopeCount} autorisations"msgid "{sectionLineCount} lines"msgstr "{sectionLineCount} lignes"+msgid "{selectedCount, plural, one {# selected} other {# selected}}"+msgstr "{selectedCount, plural, one {# sélectionné} other {# sélectionnés}}"+msgid "{selectedCount} selected"msgstr "{selectedCount} sélectionnés"@@ -622,6 +649,9 @@ msgstr "{total} phases pour être en direct"msgid "{totalCount} results"msgstr "{totalCount} résultats"+msgid "{totalLoaded} of {count}"+msgstr "{totalLoaded} sur {count}"+msgid "{totalQuantity, plural, one {# unit} other {# units}}"msgstr "{totalQuantity, plural, one {# unité} other {# unités}}"@@ -2316,6 +2346,9 @@ msgstr "Tous les Emplacements"msgid "all make {0}"msgstr "Tous font {0}"+msgid "All matching rows selected"+msgstr "Toutes les lignes correspondantes sont sélectionnées"+msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "Tous les membres des groupes sélectionnés et les individus sélectionnés pourront approuver les demandes"@@ -5959,6 +5992,9 @@ msgstr "Impossible de terminer la connexion à Onshape Government"msgid "Couldn't load documents"msgstr "Impossible de charger les documents"+msgid "Couldn't load more rows"+msgstr "Impossible de charger d'autres lignes"+msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "Impossible de charger les documents associés. Actualisez avant de créer un nouveau pour éviter les doublons."@@ -7766,6 +7802,9 @@ msgstr "Dissoudre le lot"msgid "Dissolve Batch"msgstr "Dissoudre le lot"+msgid "Dissolve batches"+msgstr "Dissoudre les lots de production"+#. placeholder {0}: batch.readableIdmsgid "Dissolving {0} returns its {memberCount} operations to the schedule un-run and deletes the batch. A batch with recorded production must be completed instead."msgstr "La dissolution de {0} remet ses {memberCount} opérations à la planification en tant que non-exécutées et supprime le lot. Un lot avec production enregistrée doit être complété à la place."@@ -9087,6 +9126,9 @@ msgstr "Chaque ligne a été importée avec succès."msgid "Every unit has a rate."msgstr "Chaque unité a un taux."+msgid "Every user that matches the list's filters. Users this action does not apply to are skipped."+msgstr "Tous les utilisateurs correspondant aux filtres de la liste. Les utilisateurs auxquels cette action ne s'applique pas sont ignorés."+msgid "Everyone must set up an authenticator app before opening this company."msgstr "Tout le monde doit configurer une application d'authentification avant d'ouvrir cette société."@@ -9328,6 +9370,9 @@ msgstr "Exporter CSV"msgid "Export Lines to CSV"msgstr "Exporter les lignes en CSV"+msgid "Exported the first {exportedCount} rows."+msgstr "Les {exportedCount} premières lignes ont été exportées."+msgid "Extended Price"msgstr "Prix étendu"@@ -9885,6 +9930,12 @@ msgstr "Filtrer et trier"msgid "Filter by…"msgstr "Filtrer par…"+msgid "Filter the list to {limit} rows or fewer"+msgstr "Filtrer la liste à {limit} lignes maximum"++msgid "Filter the list to {rows} rows or fewer"+msgstr "Filtrer la liste à {rows} lignes maximum"+msgid "Filters"msgstr "Filtres"@@ -11509,7 +11560,7 @@ msgid "Invoice schedule"msgstr "Planning de facturation"msgid "Invoice Separately"-msgstr ""+msgstr "Facturer séparément"msgid "Invoice settlement"msgstr "Règlement de facture"@@ -11542,7 +11593,7 @@ msgid "Invoiced Amount:"msgstr "Montant facturé :"msgid "Invoiced separately"-msgstr ""+msgstr "Facturé séparément"msgid "Invoiced Statuses"msgstr "Statuts facturés"@@ -12438,9 +12489,6 @@ msgstr "Rechargement en direct"msgid "Load"msgstr "Charge"-msgid "Load more"-msgstr "Charger plus"-msgid "Load newer"msgstr "Charger les plus récents"@@ -12465,6 +12513,9 @@ msgstr "Chargement de la quantité actuelle…"msgid "Loading item details..."msgstr "Chargement des détails de l'article..."+msgid "Loading more rows"+msgstr "Chargement d'autres lignes en cours"+msgid "Loading returnable lines..."msgstr "Chargement des lignes retournables..."@@ -17123,7 +17174,7 @@ msgid "Push to accounting"msgstr "Envoyer vers la comptabilité"msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."-msgstr ""+msgstr "Placer ce frais sur sa propre facture, en attente de revue avant sa comptabilisation. Sinon, il figure sur la prochaine facture du contrat."msgid "Putting your data back"msgstr "Restauration de vos données"@@ -17877,6 +17928,9 @@ msgstr "Lancer le lot de production"msgid "Release batch {0}"msgstr "Lancer le lot de production {0}"+msgid "Release batches"+msgstr "Lancer les lots de production"+msgid "Release change notice"msgstr "Lancer l'avis de modification"@@ -18451,9 +18505,6 @@ msgstr "Résultat"msgid "Results"msgstr "Résultats"-msgid "Results per page"-msgstr "Résultats par page"-msgid "Resume"msgstr "Reprendre"@@ -18852,9 +18903,6 @@ msgstr "Gamme opératoire"msgid "Routing Number (ABA)"msgstr "Numéro d'acheminement (ABA)"-msgid "rows"-msgstr "lignes"-msgid "Rows left out of this backup"msgstr "Lignes exclues de cette sauvegarde"@@ -18930,6 +18978,9 @@ msgstr "Exécuter ce flux de travail maintenant ?"msgid "Running"msgstr "En cours d'exécution"+msgid "Running in the background. We'll notify you when it's done."+msgstr "En cours d'exécution en arrière-plan. Nous vous préviendrons lorsque ce sera terminé."+msgid "Running inventory after each week's supply and demand — the line."msgstr "Inventaire permanent après chaque semaine d'approvisionnement et de besoins — la ligne."@@ -19704,6 +19755,9 @@ msgstr "Sélectionner le type de fournisseur"msgid "Select surfaces"msgstr "Sélectionner les surfaces"+msgid "Select the first {limit} rows"+msgstr "Sélectionner les {limit} premières lignes"+msgid "Select the groups that should complete this training"msgstr "Sélectionnez les groupes qui doivent suivre cette formation"@@ -19967,7 +20021,7 @@ msgid "Set Up Accounting"msgstr "Configurer la comptabilité"msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."-msgstr ""+msgstr "Configurez la comptabilité pour utiliser les rapports, les écritures, les périodes comptables, les calculs d'amortissement et plus encore."msgid "Set up authenticator app"msgstr "Configurer l'application d'authentification"@@ -20351,12 +20405,12 @@ msgstr "Affichage de {0} sur {totalCount} — affinez votre recherche"msgid "Showing {0} of {totalFiltered} — refine your search"msgstr "Affichage de {0} sur {totalFiltered} — affinez votre recherche"-msgid "Showing {firstShown}–{lastShown} of {total}"-msgstr "Affichage de {firstShown} à {lastShown} sur {total}"-msgid "Showing in {parentCurrency}"msgstr "Affichage en {parentCurrency}"+msgid "Showing the first {limit} rows. Search or filter to see the rest."+msgstr "Affichage des {limit} premières lignes. Rechercher ou filtrer pour voir le reste."+msgid "Showing the first 500 lines"msgstr "Affichage des 500 premières lignes"@@ -22000,6 +22054,9 @@ msgstr "Le pourcentage attendu de la production de cet article perdu lors de lamsgid "The expense account this indirect-spend line posts to; required because indirect lines don't have an item ledger entry to derive the account from."msgstr "Le compte de charge auquel cette ligne de dépenses indirectes se comptabilise; requis parce que les lignes indirectes n'ont pas d'entrée de livre comptable d'article à partir de laquelle dériver le compte."+msgid "The export could not start. Try again."+msgstr "L'exportation n'a pas pu démarrer. Réessayez."+msgid "The file you uploaded and the mappings you've made will be lost."msgstr "Le fichier que vous avez importé et les correspondances que vous avez définies seront perdus."@@ -22182,6 +22239,9 @@ msgstr "L'état du cycle de vie de ce client - Actif, Prospect, Inactif, etc.; smsgid "The lifecycle state of this supplier — Active, Inactive, Pending Approval, etc.; only Active suppliers appear in PO / quote selectors."msgstr "L'état du cycle de vie de ce fournisseur - Actif, Inactif, Approbation en attente, etc.; seuls les fournisseurs Actifs apparaissent dans les sélecteurs PO/devis."+msgid "The list changed while the export loaded. Try again."+msgstr "La liste a changé pendant le chargement de l'exportation. Réessayez."+msgid "The local timezone this location reports time in; schedules, timecards, and shift hours at this location are interpreted in this zone regardless of the user's browser locale."msgstr "Le fuseau horaire local utilisé par ce site; la planification, les feuilles de temps, et les heures d'équipe sont interprétées dans cette zone indépendamment de la locale du navigateur de l'utilisateur."@@ -24140,6 +24200,9 @@ msgstr "Mettre à jour les quantités du bon de commande"msgid "Updated"msgstr "Mis à jour"+msgid "Updated {done}. Could not update {failed}: {message}"+msgstr "{done} mis à jour. Impossible de mettre à jour {failed} : {message}"+msgid "Updated account"msgstr "Compte mis à jour"@@ -25629,6 +25692,9 @@ msgstr "Votre fournisseur DNS peut ajouter automatiquement votre domaine au nommsgid "Your Email"msgstr "Votre e-mail"+msgid "Your export is being prepared. We'll notify you when it's ready."+msgstr "Votre exportation est en cours de préparation. Nous vous préviendrons lorsqu'elle sera prête."+msgid "Your general-ledger accounts and their structure"msgstr "Vos comptes du grand livre et leur structure"diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 020509ea50..a14650f0cc 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -93,6 +93,10 @@ msgstr "{0, plural, one {# पंक्ति इस कंपनी के बmsgid "{0, plural, one {# week} other {# weeks}}"msgstr "{0, plural, one {# सप्ताह} other {# सप्ताह}}"+#. placeholder {0}: allMatching.count+msgid "{0, plural, one {All matching rows selected (about #)} other {All matching rows selected (about #)}}"+msgstr "मिलती हुई सभी पंक्तियाँ चुनी गईं (लगभग #)"+#. placeholder {0}: check.countmsgid "{0, plural, one {Complete or cancel the # job that took costs before Carbon recorded them.} other {Complete or cancel the # jobs that took costs before Carbon recorded them.}}"msgstr "{0, plural, one {# जॉब को पूर्ण करें या रद्द करें जिस पर Carbon के लागत दर्ज करने से पहले लागत लगी थी।} other {# जॉबें को पूर्ण करें या रद्द करें जिन पर Carbon के लागत दर्ज करने से पहले लागत लगी थी।}}"@@ -113,6 +117,10 @@ msgstr "{0, plural, one {योजनाकार इस घटक को एकmsgid "{0, plural, one {This item is on 1 open change notice} other {This item is on # open change notices}}"msgstr "{0, plural, one {यह आइटम 1 खुली परिवर्तन सूचना पर है} other {यह आइटम # खुली परिवर्तन सूचनाओं पर है}}"+#. placeholder {0}: rows.length+msgid "{0, plural, one {Total of # loaded row} other {Total of # loaded rows}}"+msgstr "{0, plural, one {लोड की गई कुल # पंक्ति} other {लोड की गई कुल # पंक्तियाँ}}"+#. placeholder {0}: rate.customerType.namemsgid "{0} (type)"msgstr "{0} (प्रकार)"@@ -252,6 +260,10 @@ msgstr "{0} में से {1}"msgid "{0} of {1} posting accounts mapped"msgstr "{0} में से {1} पोस्टिंग खातों को मैप किया गया"+#. placeholder {0}: rows.length+msgid "{0} of {count} operations"+msgstr "{count} में से {0} ऑपरेशन"+#. placeholder {0}: rows.lengthmsgid "{0} of {maxSlots} provider slots used"msgstr "{0} में से {maxSlots} प्रदाता स्लॉट उपयोग किए गए"@@ -441,6 +453,12 @@ msgstr "{count, plural, one {# कोर्स} other {# कोर्स}}"msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"msgstr "{count, plural, one {# अधिक {fenceLabel} के बाद} other {# अधिक {fenceLabel} के बाद}}"+msgid "{count, plural, one {# row} other {# rows}}"+msgstr "{count, plural, one {# पंक्ति} other {# पंक्तियाँ}}"++msgid "{count, plural, one {about # row} other {about # rows}}"+msgstr "{count, plural, one {लगभग # पंक्ति} other {लगभग # पंक्तियाँ}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {# बैच विघटित करें} other {# बैच विघटित करें}}"@@ -456,6 +474,12 @@ msgstr "{count, plural, one {# बैच जारी} other {# बैच जाmsgid "{count, plural, one {Released # job} other {Released # jobs}}"msgstr "{count, plural, one {# जॉब जारी} other {# जॉब जारी}}"+msgid "{count, plural, one {Select all # matching row} other {Select all # matching rows}}"+msgstr "{count, plural, one {मिलती हुई # पंक्ति चुनें} other {मिलती हुई सभी # पंक्तियाँ चुनें}}"++msgid "{count, plural, one {Select all matching rows (about #)} other {Select all matching rows (about #)}}"+msgstr "मिलती हुई सभी पंक्तियाँ चुनें (लगभग #)"+msgid "{count} of {total} units"msgstr "{count} का {total} इकाइयों में से"@@ -486,12 +510,6 @@ msgstr "{done} में से {total} चरण पूर्ण"msgid "{excluded, plural, one {# row excluded} other {# rows excluded}}"msgstr "{excluded, plural, one {# पंक्ति बाहर रखी गई} other {# पंक्तियाँ बाहर रखी गईं}}"-msgid "{from}–{to} of {count}"-msgstr "{from}–{to} में से {count}"--msgid "{from}–{to} of {count} operations"-msgstr "{count} ऑपरेशन में से {from}–{to}"-msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"msgstr "{hidden, plural, one {और # अधिक रिकॉर्ड।} other {और # अधिक रिकॉर्ड।}}"@@ -515,6 +533,12 @@ msgstr "{linesCount, plural, one {# लाइन} other {# लाइनें}}"msgid "{load} in queue"msgstr "{load} कतार में"+msgid "{loadedLabel} of {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} में से {total, plural, one {# पंक्ति} other {# पंक्तियाँ}}"++msgid "{loadedLabel} of about {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} में से लगभग {total, plural, one {# पंक्ति} other {# पंक्तियाँ}}"+msgid "{locationName} (the lease's)"msgstr "{locationName} (पट्टे का)"@@ -607,6 +631,9 @@ msgstr "{scopeCount} अनुमतियाँ"msgid "{sectionLineCount} lines"msgstr "{sectionLineCount} पंक्तियाँ"+msgid "{selectedCount, plural, one {# selected} other {# selected}}"+msgstr "{selectedCount, plural, one {# चुना गया} other {# चुने गए}}"+msgid "{selectedCount} selected"msgstr "{selectedCount} चयनित"@@ -622,6 +649,9 @@ msgstr "{total} चरण लाइव होने के लिए"msgid "{totalCount} results"msgstr "{totalCount} परिणाम"+msgid "{totalLoaded} of {count}"+msgstr "{totalLoaded} में से {count}"+msgid "{totalQuantity, plural, one {# unit} other {# units}}"msgstr "{totalQuantity, plural, one {# इकाई} other {# इकाइयाँ}}"@@ -2316,6 +2346,9 @@ msgstr "सभी स्थान"msgid "all make {0}"msgstr "सभी निर्माण {0}"+msgid "All matching rows selected"+msgstr "मिलती हुई सभी पंक्तियाँ चुनी गईं"+msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "चयनित समूहों के सभी सदस्य और चयनित व्यक्ति अनुरोधों को अनुमोदित करने में सक्षम होंगे"@@ -5959,6 +5992,9 @@ msgstr "Onshape Government कनेक्शन को पूर्ण नहmsgid "Couldn't load documents"msgstr "दस्तावेज़ लोड नहीं हो सके"+msgid "Couldn't load more rows"+msgstr "और पंक्तियाँ लोड नहीं हो सकीं"+msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "संबंधित दस्तावेज़ लोड नहीं किए जा सके। डुप्लिकेट से बचने के लिए एक नया बनाने से पहले रीफ़्रेश करें।"@@ -7766,6 +7802,9 @@ msgstr "बैच को भंग करें"msgid "Dissolve Batch"msgstr "बैच भंग करना"+msgid "Dissolve batches"+msgstr "बैच भंग करें"+#. placeholder {0}: batch.readableIdmsgid "Dissolving {0} returns its {memberCount} operations to the schedule un-run and deletes the batch. A batch with recorded production must be completed instead."msgstr "भंग करने से {0} अपने {memberCount} ऑपरेशन को शेड्यूल को अचलित लौटाता है और बैच को हटा देता है। उत्पादन रिकॉर्ड के साथ एक बैच को पूर्ण किया जाना चाहिए।"@@ -9087,6 +9126,9 @@ msgstr "हर पंक्ति सफलतापूर्वक आयातmsgid "Every unit has a rate."msgstr "प्रत्येक इकाई की एक दर है।"+msgid "Every user that matches the list's filters. Users this action does not apply to are skipped."+msgstr "सूची के फ़िल्टर से मेल खाने वाला हर उपयोगकर्ता। जिन उपयोगकर्ताओं पर यह कार्रवाई लागू नहीं होती, उन्हें छोड़ दिया जाएगा।"+msgid "Everyone must set up an authenticator app before opening this company."msgstr "इस कंपनी को खोलने से पहले सभी को प्रमाणकर्ता ऐप सेट अप करना होगा।"@@ -9328,6 +9370,9 @@ msgstr "CSV निर्यात करें"msgid "Export Lines to CSV"msgstr "CSV में लाइनें निर्यात करें"+msgid "Exported the first {exportedCount} rows."+msgstr "पहली {exportedCount} पंक्तियाँ निर्यात की गईं।"+msgid "Extended Price"msgstr "विस्तारित मूल्य"@@ -9885,6 +9930,12 @@ msgstr "फ़िल्टर और क्रमबद्ध करें"msgid "Filter by…"msgstr "द्वारा फ़िल्टर करें…"+msgid "Filter the list to {limit} rows or fewer"+msgstr "सूची को {limit} या उससे कम पंक्तियों तक फ़िल्टर करें"++msgid "Filter the list to {rows} rows or fewer"+msgstr "सूची को {rows} या उससे कम पंक्तियों तक फ़िल्टर करें"+msgid "Filters"msgstr "फ़िल्टर"@@ -11509,7 +11560,7 @@ msgid "Invoice schedule"msgstr "चालान शेड्यूल"msgid "Invoice Separately"-msgstr ""+msgstr "अलग से चालान करें"msgid "Invoice settlement"msgstr "चालान निपटान"@@ -11542,7 +11593,7 @@ msgid "Invoiced Amount:"msgstr "चालान की गई राशि:"msgid "Invoiced separately"-msgstr ""+msgstr "अलग से चालान किया गया"msgid "Invoiced Statuses"msgstr "चालान की गई स्थितियां"@@ -12438,9 +12489,6 @@ msgstr "लाइव रीलोडिंग"msgid "Load"msgstr "भार"-msgid "Load more"-msgstr "और अधिक लोड करें"-msgid "Load newer"msgstr "नया लोड करें"@@ -12465,6 +12513,9 @@ msgstr "वर्तमान मात्रा लोड हो रही हmsgid "Loading item details..."msgstr "आइटम विवरण लोड हो रहे हैं..."+msgid "Loading more rows"+msgstr "और पंक्तियाँ लोड हो रही हैं"+msgid "Loading returnable lines..."msgstr "रिटर्न योग्य लाइनें लोड हो रही हैं..."@@ -17123,7 +17174,7 @@ msgid "Push to accounting"msgstr "लेखांकन को धकेलें"msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."-msgstr ""+msgstr "इस शुल्क को अलग चालान में रखें, जिसे पोस्ट होने से पहले समीक्षा के लिए रोका जाएगा। अन्यथा यह अनुबंध के अगले चालान में जाएगा।"msgid "Putting your data back"msgstr "आपका डेटा वापस डाल रहे हैं"@@ -17877,6 +17928,9 @@ msgstr "बैच जारी करें"msgid "Release batch {0}"msgstr "बैच {0} जारी करें"+msgid "Release batches"+msgstr "बैच जारी करें"+msgid "Release change notice"msgstr "परिवर्तन सूचना जारी करें"@@ -18451,9 +18505,6 @@ msgstr "परिणाम"msgid "Results"msgstr "परिणाम"-msgid "Results per page"-msgstr "प्रति पृष्ठ परिणाम"-msgid "Resume"msgstr "पुनः शुरू करें"@@ -18852,9 +18903,6 @@ msgstr "रूटिंग"msgid "Routing Number (ABA)"msgstr "रूटिंग संख्या (ABA)"-msgid "rows"-msgstr "पंक्तियाँ"-msgid "Rows left out of this backup"msgstr "इस बैकअप से छोड़ी गई पंक्तियां"@@ -18930,6 +18978,9 @@ msgstr "अभी यह वर्कफ़्लो चलाएं?"msgid "Running"msgstr "चल रहा है"+msgid "Running in the background. We'll notify you when it's done."+msgstr "पृष्ठभूमि में चल रहा है। पूरा होने पर हम आपको सूचित करेंगे।"+msgid "Running inventory after each week's supply and demand — the line."msgstr "प्रत्येक सप्ताह की आपूर्ति और मांग के बाद चलाई जाने वाली इन्वेंटरी — पंक्ति।"@@ -19704,6 +19755,9 @@ msgstr "आपूर्तिकर्ता प्रकार चुनें"msgid "Select surfaces"msgstr "सतहें चुनें"+msgid "Select the first {limit} rows"+msgstr "पहली {limit} पंक्तियाँ चुनें"+msgid "Select the groups that should complete this training"msgstr "उन समूहों का चयन करें जिन्हें इस प्रशिक्षण को पूरा करना चाहिए"@@ -19967,7 +20021,7 @@ msgid "Set Up Accounting"msgstr "लेखांकन स्थापित करें"msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."-msgstr ""+msgstr "रिपोर्ट, जर्नल प्रविष्टियाँ, लेखा अवधि, मूल्यह्रास रन और अन्य सुविधाओं का उपयोग करने के लिए लेखांकन सेट अप करें।"msgid "Set up authenticator app"msgstr "प्रमाणकर्ता ऐप सेटअप करें"@@ -20351,12 +20405,12 @@ msgstr "{0} of {totalCount} दिखा रहे हैं — अपनीmsgid "Showing {0} of {totalFiltered} — refine your search"msgstr "{0} of {totalFiltered} दिखा रहे हैं — अपनी खोज को परिष्कृत करें"-msgid "Showing {firstShown}–{lastShown} of {total}"-msgstr "{firstShown}–{lastShown} को {total} में से दिखा रहे हैं"-msgid "Showing in {parentCurrency}"msgstr "में दिखाई दे रहा है {parentCurrency}"+msgid "Showing the first {limit} rows. Search or filter to see the rest."+msgstr "पहली {limit} पंक्तियाँ दिखाई जा रही हैं। बाकी देखने के लिए खोजें या फ़िल्टर करें।"+msgid "Showing the first 500 lines"msgstr "पहली 500 लाइनें दिखा रहे हैं"@@ -22000,6 +22054,9 @@ msgstr "इस आइटम के आउटपुट का अपेक्षmsgid "The expense account this indirect-spend line posts to; required because indirect lines don't have an item ledger entry to derive the account from."msgstr "व्यय खाता जिस पर यह अप्रत्यक्ष-खर्च लाइन पोस्ट करता है; आवश्यक है क्योंकि अप्रत्यक्ष लाइनों के पास खाता प्राप्त करने के लिए कोई वस्तु बही प्रविष्टि नहीं है।"+msgid "The export could not start. Try again."+msgstr "निर्यात शुरू नहीं हो सका। फिर से कोशिश करें।"+msgid "The file you uploaded and the mappings you've made will be lost."msgstr "आपके द्वारा अपलोड की गई फ़ाइल और की गई मैपिंग खो जाएँगी।"@@ -22182,6 +22239,9 @@ msgstr "इस ग्राहक की जीवन चक्र स्थिmsgid "The lifecycle state of this supplier — Active, Inactive, Pending Approval, etc.; only Active suppliers appear in PO / quote selectors."msgstr "इस आपूर्तिकर्ता की जीवन चक्र स्थिति — सक्रिय, निष्क्रिय, अनुमोदन लंबित, आदि; केवल सक्रिय आपूर्तिकर्ता PO/कोटेशन चयनकर्ता में दिखाई देते हैं।"+msgid "The list changed while the export loaded. Try again."+msgstr "निर्यात लोड होने के दौरान सूची बदल गई। फिर से कोशिश करें।"+msgid "The local timezone this location reports time in; schedules, timecards, and shift hours at this location are interpreted in this zone regardless of the user's browser locale."msgstr "स्थानीय समय क्षेत्र जिसमें यह स्थान समय रिपोर्ट करता है; इस स्थान पर शेड्यूल, टाइमकार्ड और शिफ्ट घंटों की व्याख्या इस क्षेत्र में की जाती है, भले ही उपयोगकर्ता के ब्राउज़र लोकेल की परवाह किए बिना।"@@ -24140,6 +24200,9 @@ msgstr "क्रय आदेश मात्रा अपडेट करेmsgid "Updated"msgstr "अपडेट किया गया"+msgid "Updated {done}. Could not update {failed}: {message}"+msgstr "{done} अपडेट किए गए। {failed} अपडेट नहीं हो सके: {message}"+msgid "Updated account"msgstr "खाता अपडेट किया गया"@@ -25632,6 +25695,9 @@ msgstr "आपका DNS प्रदाता रिकॉर्ड नामmsgid "Your Email"msgstr "आपका ईमेल"+msgid "Your export is being prepared. We'll notify you when it's ready."+msgstr "आपका निर्यात तैयार किया जा रहा है। तैयार होने पर हम आपको सूचित करेंगे।"+msgid "Your general-ledger accounts and their structure"msgstr "आपके सामान्य-खाता खातों और उनकी संरचना"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 874ac4635f..1d08df46ff 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -93,6 +93,10 @@ msgstr "{0, plural, one {# riga si collega ai dati al di fuori di questa Aziendamsgid "{0, plural, one {# week} other {# weeks}}"msgstr "{0, plural, one {# settimana} other {# settimane}}"+#. placeholder {0}: allMatching.count+msgid "{0, plural, one {All matching rows selected (about #)} other {All matching rows selected (about #)}}"+msgstr "{0, plural, one {Tutte le righe corrispondenti selezionate (circa #)} other {Tutte le righe corrispondenti selezionate (circa #)}}"+#. placeholder {0}: check.countmsgid "{0, plural, one {Complete or cancel the # job that took costs before Carbon recorded them.} other {Complete or cancel the # jobs that took costs before Carbon recorded them.}}"msgstr "{0, plural, one {Completa o annulla l'# ordine di produzione che ha sostenuto costi prima che Carbon li registrasse.} other {Completa o annulla gli # ordini di produzione che hanno sostenuto costi prima che Carbon li registrasse.}}"@@ -113,6 +117,10 @@ msgstr "{0, plural, one {Il pianificatore tratta questo componente come un corpomsgid "{0, plural, one {This item is on 1 open change notice} other {This item is on # open change notices}}"msgstr "{0, plural, one {Questo articolo è in 1 avviso di modifica aperto} other {Questo articolo è in # avvisi di modifica aperti}}"+#. placeholder {0}: rows.length+msgid "{0, plural, one {Total of # loaded row} other {Total of # loaded rows}}"+msgstr "{0, plural, one {Totale di # riga caricata} other {Totale di # righe caricate}}"+#. placeholder {0}: rate.customerType.namemsgid "{0} (type)"msgstr "{0} (tipo)"@@ -252,6 +260,10 @@ msgstr "{0} di {1}"msgid "{0} of {1} posting accounts mapped"msgstr "{0} di {1} conti di registrazione mappati"+#. placeholder {0}: rows.length+msgid "{0} of {count} operations"+msgstr "{0} di {count} operazioni"+#. placeholder {0}: rows.lengthmsgid "{0} of {maxSlots} provider slots used"msgstr "{0} di {maxSlots} slot provider utilizzati"@@ -441,6 +453,12 @@ msgstr "{count, plural, one {# corso} other {# corsi}}"msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"msgstr "{count, plural, one {# altri dopo {fenceLabel}} other {# altri dopo {fenceLabel}}}"+msgid "{count, plural, one {# row} other {# rows}}"+msgstr "{count, plural, one {# riga} other {# righe}}"++msgid "{count, plural, one {about # row} other {about # rows}}"+msgstr "{count, plural, one {circa # riga} other {circa # righe}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {Sciogli # lotto di produzione} other {Sciogli # lotti di produzione}}"@@ -456,6 +474,12 @@ msgstr "{count, plural, one {Liberato # lotto di produzione} other {Liberati # lmsgid "{count, plural, one {Released # job} other {Released # jobs}}"msgstr "{count, plural, one {Rilasciato # ordine di produzione} other {Rilasciati # ordini di produzione}}"+msgid "{count, plural, one {Select all # matching row} other {Select all # matching rows}}"+msgstr "{count, plural, one {Seleziona # riga corrispondente} other {Seleziona tutte le # righe corrispondenti}}"++msgid "{count, plural, one {Select all matching rows (about #)} other {Select all matching rows (about #)}}"+msgstr "{count, plural, one {Seleziona tutte le righe corrispondenti (circa #)} other {Seleziona tutte le righe corrispondenti (circa #)}}"+msgid "{count} of {total} units"msgstr "{count} di {total} unità"@@ -486,12 +510,6 @@ msgstr "{done} di {total} fasi completate"msgid "{excluded, plural, one {# row excluded} other {# rows excluded}}"msgstr "{excluded, plural, one {# riga esclusa} other {# righe escluse}}"-msgid "{from}–{to} of {count}"-msgstr "{from}–{to} di {count}"--msgid "{from}–{to} of {count} operations"-msgstr "{from}–{to} di {count} operazioni"-msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"msgstr "{hidden, plural, one {E # altro record.} other {E # altri record.}}"@@ -515,6 +533,12 @@ msgstr "{linesCount, plural, one {# riga} other {# righe}}"msgid "{load} in queue"msgstr "{load} in coda"+msgid "{loadedLabel} of {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} di {total, plural, one {# riga} other {# righe}}"++msgid "{loadedLabel} of about {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} di circa {total, plural, one {# riga} other {# righe}}"+msgid "{locationName} (the lease's)"msgstr "{locationName} (del leasing)"@@ -607,6 +631,9 @@ msgstr "{scopeCount} autorizzazioni"msgid "{sectionLineCount} lines"msgstr "{sectionLineCount} righe"+msgid "{selectedCount, plural, one {# selected} other {# selected}}"+msgstr "{selectedCount, plural, one {# selezionato} other {# selezionati}}"+msgid "{selectedCount} selected"msgstr "{selectedCount} selezionati"@@ -622,6 +649,9 @@ msgstr "{total} fasi per andare live"msgid "{totalCount} results"msgstr "{totalCount} risultati"+msgid "{totalLoaded} of {count}"+msgstr "{totalLoaded} di {count}"+msgid "{totalQuantity, plural, one {# unit} other {# units}}"msgstr "{totalQuantity, plural, one {# unità} other {# unità}}"@@ -2316,6 +2346,9 @@ msgstr "Tutte le Ubicazioni"msgid "all make {0}"msgstr "Produzione di {0}"+msgid "All matching rows selected"+msgstr "Tutte le righe corrispondenti selezionate"+msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "Tutti i membri dei gruppi selezionati e gli individui selezionati potranno approvare le richieste"@@ -5959,6 +5992,9 @@ msgstr "Impossibile completare la connessione Onshape Government"msgid "Couldn't load documents"msgstr "Impossibile caricare i documenti"+msgid "Couldn't load more rows"+msgstr "Impossibile caricare altre righe"+msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "Impossibile caricare i documenti correlati. Aggiorna prima di crearne uno nuovo per evitare duplicati."@@ -7766,6 +7802,9 @@ msgstr "Elimina batch"msgid "Dissolve Batch"msgstr "Sciogliere Lotto"+msgid "Dissolve batches"+msgstr "Scioglie lotti di produzione"+#. placeholder {0}: batch.readableIdmsgid "Dissolving {0} returns its {memberCount} operations to the schedule un-run and deletes the batch. A batch with recorded production must be completed instead."msgstr "Lo scioglimento di {0} restituisce le sue {memberCount} operazioni al programma in sospeso ed elimina il lotto. Un lotto con produzione registrata deve essere completato."@@ -9087,6 +9126,9 @@ msgstr "Ogni riga è stata importata correttamente."msgid "Every unit has a rate."msgstr "Ogni unità ha un tasso."+msgid "Every user that matches the list's filters. Users this action does not apply to are skipped."+msgstr "Ogni utente che corrisponde ai filtri dell'elenco. Gli utenti a cui questa azione non si applica vengono saltati."+msgid "Everyone must set up an authenticator app before opening this company."msgstr "Tutti devono configurare un'app autenticatore prima di aprire questa azienda."@@ -9328,6 +9370,9 @@ msgstr "Esporta CSV"msgid "Export Lines to CSV"msgstr "Esporta Righe in CSV"+msgid "Exported the first {exportedCount} rows."+msgstr "Esportate le prime {exportedCount} righe."+msgid "Extended Price"msgstr "Prezzo Esteso"@@ -9885,6 +9930,12 @@ msgstr "Filtra e ordina"msgid "Filter by…"msgstr "Filtra per…"+msgid "Filter the list to {limit} rows or fewer"+msgstr "Filtra l'elenco a {limit} righe o meno"++msgid "Filter the list to {rows} rows or fewer"+msgstr "Filtra l'elenco a {rows} righe o meno"+msgid "Filters"msgstr "Filtri"@@ -11509,7 +11560,7 @@ msgid "Invoice schedule"msgstr "Programma di fatturazione"msgid "Invoice Separately"-msgstr ""+msgstr "Fattura separatamente"msgid "Invoice settlement"msgstr "Regolamento della fattura"@@ -11542,7 +11593,7 @@ msgid "Invoiced Amount:"msgstr "Importo Fatturato:"msgid "Invoiced separately"-msgstr ""+msgstr "Fatturato separatamente"msgid "Invoiced Statuses"msgstr "Stati Fatturati"@@ -12438,9 +12489,6 @@ msgstr "Ricaricamento in tempo reale"msgid "Load"msgstr "Carico"-msgid "Load more"-msgstr "Carica altri"-msgid "Load newer"msgstr "Carica più recenti"@@ -12465,6 +12513,9 @@ msgstr "Caricamento della quantità attuale…"msgid "Loading item details..."msgstr "Caricamento dettagli articolo..."+msgid "Loading more rows"+msgstr "Caricamento di altre righe in corso"+msgid "Loading returnable lines..."msgstr "Caricamento linee restituibili in corso..."@@ -17123,7 +17174,7 @@ msgid "Push to accounting"msgstr "Invia alla contabilità"msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."-msgstr ""+msgstr "Metti questo addebito in una fattura separata, da verificare prima di essere registrato. Altrimenti finisce nella prossima fattura del contratto."msgid "Putting your data back"msgstr "Ripristino dei dati"@@ -17877,6 +17928,9 @@ msgstr "Rilascia lotto"msgid "Release batch {0}"msgstr "Rilascia lotto di produzione {0}"+msgid "Release batches"+msgstr "Rilascia lotti di produzione"+msgid "Release change notice"msgstr "Rilascia avviso di modifica"@@ -18451,9 +18505,6 @@ msgstr "Risultato"msgid "Results"msgstr "Risultati"-msgid "Results per page"-msgstr "Risultati per pagina"-msgid "Resume"msgstr "Riprendi"@@ -18852,9 +18903,6 @@ msgstr "Ciclo di lavorazione"msgid "Routing Number (ABA)"msgstr "Numero di instradamento (ABA)"-msgid "rows"-msgstr "righe"-msgid "Rows left out of this backup"msgstr "Righe escluse da questo backup"@@ -18930,6 +18978,9 @@ msgstr "Eseguire questo workflow ora?"msgid "Running"msgstr "In esecuzione"+msgid "Running in the background. We'll notify you when it's done."+msgstr "In esecuzione in background. Ti avviseremo quando sarà completata."+msgid "Running inventory after each week's supply and demand — the line."msgstr "Giacenza corrente dopo la copertura e il fabbisogno di ogni settimana — la riga."@@ -19704,6 +19755,9 @@ msgstr "Seleziona Tipo Fornitore"msgid "Select surfaces"msgstr "Seleziona superfici"+msgid "Select the first {limit} rows"+msgstr "Seleziona le prime {limit} righe"+msgid "Select the groups that should complete this training"msgstr "Seleziona i gruppi che dovrebbero completare questa formazione"@@ -19967,7 +20021,7 @@ msgid "Set Up Accounting"msgstr "Configura la contabilità"msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."-msgstr ""+msgstr "Configura la contabilità per usare report, scritture in prima nota, periodi contabili, elaborazioni di ammortamento e altro."msgid "Set up authenticator app"msgstr "Configura app autenticatore"@@ -20351,12 +20405,12 @@ msgstr "Mostrando {0} di {totalCount} — raffina la tua ricerca"msgid "Showing {0} of {totalFiltered} — refine your search"msgstr "Visualizzazione {0} di {totalFiltered} — perfeziona la ricerca"-msgid "Showing {firstShown}–{lastShown} of {total}"-msgstr "Mostra {firstShown}–{lastShown} di {total}"-msgid "Showing in {parentCurrency}"msgstr "Visualizzazione in {parentCurrency}"+msgid "Showing the first {limit} rows. Search or filter to see the rest."+msgstr "Vengono mostrate le prime {limit} righe. Cerca o filtra per vedere le altre."+msgid "Showing the first 500 lines"msgstr "Visualizzazione delle prime 500 righe"@@ -22000,6 +22054,9 @@ msgstr "La percentuale prevista di produzione di questo articolo persa durante lmsgid "The expense account this indirect-spend line posts to; required because indirect lines don't have an item ledger entry to derive the account from."msgstr "Il conto spese a cui questa riga di spesa indiretta viene contabilizzata; obbligatorio perché le righe indirette non hanno una voce di inventario da cui derivare il conto."+msgid "The export could not start. Try again."+msgstr "Impossibile avviare l'esportazione. Riprova."+msgid "The file you uploaded and the mappings you've made will be lost."msgstr "Il file caricato e le mappature effettuate andranno persi."@@ -22182,6 +22239,9 @@ msgstr "Lo stato del ciclo di vita di questo cliente - Attivo, Prospect, Inattivmsgid "The lifecycle state of this supplier — Active, Inactive, Pending Approval, etc.; only Active suppliers appear in PO / quote selectors."msgstr "Lo stato del ciclo di vita di questo fornitore — Attivo, Inattivo, In attesa di approvazione, ecc.; solo i fornitori attivi compaiono nei selettori di ordine di acquisto / offerta."+msgid "The list changed while the export loaded. Try again."+msgstr "L'elenco è cambiato durante il caricamento dell'esportazione. Riprova."+msgid "The local timezone this location reports time in; schedules, timecards, and shift hours at this location are interpreted in this zone regardless of the user's browser locale."msgstr "Il fuso orario locale in cui questa ubicazione riporta l'ora; i programmi, la rilevazione tempi e gli orari di turno in questa ubicazione vengono interpretati in questo fuso orario indipendentemente dalla locale del browser dell'utente."@@ -24140,6 +24200,9 @@ msgstr "Aggiorna le quantità dell'ordine di acquisto"msgid "Updated"msgstr "Aggiornato"+msgid "Updated {done}. Could not update {failed}: {message}"+msgstr "Aggiornati {done}. Impossibile aggiornare {failed}: {message}"+msgid "Updated account"msgstr "Account aggiornato"@@ -25629,6 +25692,9 @@ msgstr "Il tuo provider DNS potrebbe aggiungere automaticamente il tuo dominio amsgid "Your Email"msgstr "La tua email"+msgid "Your export is being prepared. We'll notify you when it's ready."+msgstr "La tua esportazione è in preparazione. Ti avviseremo quando sarà pronta."+msgid "Your general-ledger accounts and their structure"msgstr "I tuoi conti di contabilità generale e la loro struttura"diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 624d40d953..d6d3c9ec99 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -93,6 +93,10 @@ msgstr "{0, plural, one {# 行はこの会社の外部のデータにリンクmsgid "{0, plural, one {# week} other {# weeks}}"msgstr "{0, plural, other {#週}}"+#. placeholder {0}: allMatching.count+msgid "{0, plural, one {All matching rows selected (about #)} other {All matching rows selected (about #)}}"+msgstr "{0, plural, one {一致する行を約#件選択しました} other {一致する行を約#件選択しました}}"+#. placeholder {0}: check.countmsgid "{0, plural, one {Complete or cancel the # job that took costs before Carbon recorded them.} other {Complete or cancel the # jobs that took costs before Carbon recorded them.}}"msgstr "{0, plural, one {Carbon が原価を記録する前に原価が発生した # 製造指図を完了またはキャンセルしてください。} other {Carbon が原価を記録する前に原価が発生した # 製造指図を完了またはキャンセルしてください。}}"@@ -113,6 +117,10 @@ msgstr "{0, plural, one {プランナーはこのコンポーネントを1つのmsgid "{0, plural, one {This item is on 1 open change notice} other {This item is on # open change notices}}"msgstr "{0, plural, one {このアイテムは1つの未完了の変更通知に含まれています} other {このアイテムは#つの未完了の変更通知に含まれています}}"+#. placeholder {0}: rows.length+msgid "{0, plural, one {Total of # loaded row} other {Total of # loaded rows}}"+msgstr "{0, plural, one {読み込み済みの行 合計#件} other {読み込み済みの行 合計#件}}"+#. placeholder {0}: rate.customerType.namemsgid "{0} (type)"msgstr "{0}(タイプ)"@@ -252,6 +260,10 @@ msgstr "{0}/{1}"msgid "{0} of {1} posting accounts mapped"msgstr "{0} 件/{1} 件の転記勘定がマップされました"+#. placeholder {0}: rows.length+msgid "{0} of {count} operations"+msgstr "{0} / {count} 工程"+#. placeholder {0}: rows.lengthmsgid "{0} of {maxSlots} provider slots used"msgstr "{0}個の{maxSlots}プロバイダースロットが使用されています"@@ -441,6 +453,12 @@ msgstr "{count, plural, one {# コース} other {# コース}}"msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"msgstr "{count, plural, other {{fenceLabel}以降の追加 # 件}}"+msgid "{count, plural, one {# row} other {# rows}}"+msgstr "{count, plural, one {# 行} other {# 行}}"++msgid "{count, plural, one {about # row} other {about # rows}}"+msgstr "{count, plural, one {約# 行} other {約# 行}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {# バッチを解散} other {# バッチを解散}}"@@ -456,6 +474,12 @@ msgstr "{count, plural, one {# バッチがリリース済} other {# バッチmsgid "{count, plural, one {Released # job} other {Released # jobs}}"msgstr "{count, plural, one {# 製造指図がリリース済} other {# 製造指図がリリース済}}"+msgid "{count, plural, one {Select all # matching row} other {Select all # matching rows}}"+msgstr "{count, plural, one {一致する# 行をすべて選択} other {一致する# 行をすべて選択}}"++msgid "{count, plural, one {Select all matching rows (about #)} other {Select all matching rows (about #)}}"+msgstr "{count, plural, one {一致する行をすべて選択(約#件)} other {一致する行をすべて選択(約#件)}}"+msgid "{count} of {total} units"msgstr "{count} / {total} 個"@@ -486,12 +510,6 @@ msgstr "{done} / {total} フェーズ完了"msgid "{excluded, plural, one {# row excluded} other {# rows excluded}}"msgstr "{excluded, plural, one {# 行除外} other {# 行除外}}"-msgid "{from}–{to} of {count}"-msgstr "{from}–{to} / {count}"--msgid "{from}–{to} of {count} operations"-msgstr "{from}–{to} / {count} 件の工程"-msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"msgstr "{hidden, plural, one {他に # 件のレコード} other {他に # 件のレコード}}"@@ -515,6 +533,12 @@ msgstr "{linesCount, plural, one {# 行} other {# 行}}"msgid "{load} in queue"msgstr "キューに{load}件"+msgid "{loadedLabel} of {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} / {total, plural, one {# 行} other {# 行}}"++msgid "{loadedLabel} of about {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} / 約 {total, plural, one {# 行} other {# 行}}"+msgid "{locationName} (the lease's)"msgstr "{locationName}(リースの拠点)"@@ -607,6 +631,9 @@ msgstr "{scopeCount} 個の権限"msgid "{sectionLineCount} lines"msgstr "{sectionLineCount} 明細"+msgid "{selectedCount, plural, one {# selected} other {# selected}}"+msgstr "{selectedCount, plural, one {# 件選択中} other {# 件選択中}}"+msgid "{selectedCount} selected"msgstr "{selectedCount} 件が選択されています"@@ -622,6 +649,9 @@ msgstr "{total}個のフェーズをライブにする"msgid "{totalCount} results"msgstr "{totalCount} 件の検索結果"+msgid "{totalLoaded} of {count}"+msgstr "{totalLoaded} / {count}"+msgid "{totalQuantity, plural, one {# unit} other {# units}}"msgstr "{totalQuantity, plural, one {# 個} other {# 個}}"@@ -2316,6 +2346,9 @@ msgstr "すべての場所"msgid "all make {0}"msgstr "すべて内製 {0}"+msgid "All matching rows selected"+msgstr "一致するすべての行を選択しました"+msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "選択されたグループのすべてのメンバーと選択された個人が承認リクエストを承認できます"@@ -5959,6 +5992,9 @@ msgstr "Onshape Government接続を完了できませんでした"msgid "Couldn't load documents"msgstr "ドキュメントを読み込めませんでした"+msgid "Couldn't load more rows"+msgstr "これ以上の行を読み込めませんでした"+msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "関連ドキュメントを読み込めませんでした。新しいものを作成する前に更新して、重複を回避してください。"@@ -7766,6 +7802,9 @@ msgstr "バッチを解除"msgid "Dissolve Batch"msgstr "バッチを解散"+msgid "Dissolve batches"+msgstr "バッチを解消"+#. placeholder {0}: batch.readableIdmsgid "Dissolving {0} returns its {memberCount} operations to the schedule un-run and deletes the batch. A batch with recorded production must be completed instead."msgstr "{0}を解除するとその{memberCount}個の工程がスケジュールに未実行で戻され、バッチが削除されます。記録された生産があるバッチは代わりに完了させる必要があります。"@@ -9087,6 +9126,9 @@ msgstr "すべての行が正常にインポートされました。"msgid "Every unit has a rate."msgstr "すべての個にレートが設定されています。"+msgid "Every user that matches the list's filters. Users this action does not apply to are skipped."+msgstr "一覧の絞り込み条件に一致するすべてのユーザーが対象です。このアクションの対象外のユーザーはスキップされます。"+msgid "Everyone must set up an authenticator app before opening this company."msgstr "この会社を開く前に、誰もが認証器アプリをセットアップする必要があります。"@@ -9328,6 +9370,9 @@ msgstr "CSVをエクスポート"msgid "Export Lines to CSV"msgstr "CSVにラインをエクスポート"+msgid "Exported the first {exportedCount} rows."+msgstr "先頭の{exportedCount}行をエクスポートしました。"+msgid "Extended Price"msgstr "拡張価格"@@ -9885,6 +9930,12 @@ msgstr "絞り込みと並び替え"msgid "Filter by…"msgstr "絞り込み…"+msgid "Filter the list to {limit} rows or fewer"+msgstr "一覧を{limit}行以下に絞り込んでください"++msgid "Filter the list to {rows} rows or fewer"+msgstr "一覧を{rows}行以下に絞り込んでください"+msgid "Filters"msgstr "絞り込み"@@ -11509,7 +11560,7 @@ msgid "Invoice schedule"msgstr "請求スケジュール"msgid "Invoice Separately"-msgstr ""+msgstr "個別に請求書を発行"msgid "Invoice settlement"msgstr "請求書決済"@@ -11542,7 +11593,7 @@ msgid "Invoiced Amount:"msgstr "請求済み金額:"msgid "Invoiced separately"-msgstr ""+msgstr "個別に請求済"msgid "Invoiced Statuses"msgstr "請求済みステータス"@@ -12438,9 +12489,6 @@ msgstr "ライブリロード中"msgid "Load"msgstr "負荷"-msgid "Load more"-msgstr "もっと読み込む"-msgid "Load newer"msgstr "新しいものを読み込む"@@ -12465,6 +12513,9 @@ msgstr "現在の数量を読み込み中…"msgid "Loading item details..."msgstr "アイテムの詳細を読み込み中..."+msgid "Loading more rows"+msgstr "さらに行を読み込み中"+msgid "Loading returnable lines..."msgstr "返品対象行を読み込み中..."@@ -17123,7 +17174,7 @@ msgid "Push to accounting"msgstr "会計にプッシュ"msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."-msgstr ""+msgstr "この料金は単独の請求書に計上され、転記される前にレビューのため保留されます。それ以外の場合は、契約の次回の請求書に含まれます。"msgid "Putting your data back"msgstr "データを復元中"@@ -17877,6 +17928,9 @@ msgstr "バッチをリリース"msgid "Release batch {0}"msgstr "バッチ {0} をリリース"+msgid "Release batches"+msgstr "バッチをリリース"+msgid "Release change notice"msgstr "変更通知をリリース"@@ -18451,9 +18505,6 @@ msgstr "結果"msgid "Results"msgstr "結果"-msgid "Results per page"-msgstr "ページあたりの結果数"-msgid "Resume"msgstr "再開"@@ -18852,9 +18903,6 @@ msgstr "工順"msgid "Routing Number (ABA)"msgstr "ルーティング番号(ABA)"-msgid "rows"-msgstr "行"-msgid "Rows left out of this backup"msgstr "このバックアップから除外された行"@@ -18930,6 +18978,9 @@ msgstr "このワークフローを今すぐ実行しますか?"msgid "Running"msgstr "実行中"+msgid "Running in the background. We'll notify you when it's done."+msgstr "バックグラウンドで実行中です。完了したら通知します。"+msgid "Running inventory after each week's supply and demand — the line."msgstr "毎週の供給と所要量の後に在庫管理を実行 — 明細"@@ -19704,6 +19755,9 @@ msgstr "仕入先タイプを選択"msgid "Select surfaces"msgstr "サーフェスを選択"+msgid "Select the first {limit} rows"+msgstr "先頭の{limit}行を選択"+msgid "Select the groups that should complete this training"msgstr "この教育訓練を完了すべきグループを選択してください"@@ -19967,7 +20021,7 @@ msgid "Set Up Accounting"msgstr "会計を設定"msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."-msgstr ""+msgstr "会計を設定すると、レポート、仕訳、会計期間、減価償却の実行などが利用できます。"msgid "Set up authenticator app"msgstr "認証アプリをセットアップ"@@ -20351,12 +20405,12 @@ msgstr "{0} / {totalCount} を表示中 — 検索を絞り込みます"msgid "Showing {0} of {totalFiltered} — refine your search"msgstr "{totalFiltered}中{0}を表示中 — 検索を絞り込む"-msgid "Showing {firstShown}–{lastShown} of {total}"-msgstr "{firstShown}–{lastShown}件(全{total}件中)を表示中"-msgid "Showing in {parentCurrency}"msgstr "{parentCurrency}で表示"+msgid "Showing the first {limit} rows. Search or filter to see the rest."+msgstr "先頭の{limit}行を表示しています。残りを表示するには検索または絞り込みを行ってください。"+msgid "Showing the first 500 lines"msgstr "最初の 500 行を表示中"@@ -22000,6 +22054,9 @@ msgstr "生産中にこの品目の出力の失われると予想される割合msgid "The expense account this indirect-spend line posts to; required because indirect lines don't have an item ledger entry to derive the account from."msgstr "この間接支出明細が転記される費用勘定。間接明細には品目台帳エントリがないため、勘定を導出できないため必須です。"+msgid "The export could not start. Try again."+msgstr "エクスポートを開始できませんでした。もう一度お試しください。"+msgid "The file you uploaded and the mappings you've made will be lost."msgstr "アップロードしたファイルと設定したマッピングは失われます。"@@ -22182,6 +22239,9 @@ msgstr "このお客様のライフサイクル状態—有効、見込客、無msgid "The lifecycle state of this supplier — Active, Inactive, Pending Approval, etc.; only Active suppliers appear in PO / quote selectors."msgstr "この仕入先のライフサイクル状態 — 有効、無効、承認待機中など;有効な仕入先のみが発注書/見積セレクターに表示されます。"+msgid "The list changed while the export loaded. Try again."+msgstr "エクスポートの読み込み中に一覧が変更されました。もう一度お試しください。"+msgid "The local timezone this location reports time in; schedules, timecards, and shift hours at this location are interpreted in this zone regardless of the user's browser locale."msgstr "この場所が時刻を報告する現地タイムゾーン。この場所でのスケジュール、タイムカード、シフト時間は、ユーザーのブラウザロケールに関係なく、このゾーンで解釈されます。"@@ -24140,6 +24200,9 @@ msgstr "発注書の数量を更新"msgid "Updated"msgstr "更新済み"+msgid "Updated {done}. Could not update {failed}: {message}"+msgstr "{done}件を更新しました。{failed}件は更新できませんでした: {message}"+msgid "Updated account"msgstr "アカウントを更新しました"@@ -25629,6 +25692,9 @@ msgstr "DNS プロバイダーはレコード名にドメインを自動的にmsgid "Your Email"msgstr "あなたのメールアドレス"+msgid "Your export is being prepared. We'll notify you when it's ready."+msgstr "エクスポートを準備しています。準備ができたら通知します。"+msgid "Your general-ledger accounts and their structure"msgstr "あなたの総勘定元帳アカウントとその構造"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 3c66848ee2..cb69c97976 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -93,6 +93,10 @@ msgstr "{0, plural, one {# 행은 이 회사 외부의 데이터에 연결되어msgid "{0, plural, one {# week} other {# weeks}}"msgstr "{0, plural, other {#주}}"+#. placeholder {0}: allMatching.count+msgid "{0, plural, one {All matching rows selected (about #)} other {All matching rows selected (about #)}}"+msgstr "{0, plural, one {일치하는 모든 행이 선택됨(약 #)} other {일치하는 모든 행이 선택됨(약 #)}}"+#. placeholder {0}: check.countmsgid "{0, plural, one {Complete or cancel the # job that took costs before Carbon recorded them.} other {Complete or cancel the # jobs that took costs before Carbon recorded them.}}"msgstr "{0, plural, one {Carbon이 원가를 기록하기 전에 원가가 발생한 # 작업 지시를 완료 처리하거나 취소하세요.} other {Carbon이 원가를 기록하기 전에 원가가 발생한 # 작업 지시를 완료 처리하거나 취소하세요.}}"@@ -113,6 +117,10 @@ msgstr "{0, plural, one {플래너는 이 부품을 하나의 강체로 취급msgid "{0, plural, one {This item is on 1 open change notice} other {This item is on # open change notices}}"msgstr "{0, plural, one {이 품목은 1개의 미결 변경 통지에 포함되어 있습니다} other {이 품목은 # 개의 미결 변경 통지에 포함되어 있습니다}}"+#. placeholder {0}: rows.length+msgid "{0, plural, one {Total of # loaded row} other {Total of # loaded rows}}"+msgstr "{0, plural, one {불러온 행 전체 #행} other {불러온 행 전체 #행}}"+#. placeholder {0}: rate.customerType.namemsgid "{0} (type)"msgstr "{0} (유형)"@@ -252,6 +260,10 @@ msgstr "{0}/{1}"msgid "{0} of {1} posting accounts mapped"msgstr "{0}개의 {1}개 전기 계정 매핑됨"+#. placeholder {0}: rows.length+msgid "{0} of {count} operations"+msgstr "{0} / {count} 공정"+#. placeholder {0}: rows.lengthmsgid "{0} of {maxSlots} provider slots used"msgstr "{0}개 중 {maxSlots}개 제공자 슬롯 사용됨"@@ -441,6 +453,12 @@ msgstr "교육과정 {count}개"msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"msgstr "{count, plural, other {{fenceLabel} 이후 # 개}}"+msgid "{count, plural, one {# row} other {# rows}}"+msgstr "{count, plural, one {#행} other {#행}}"++msgid "{count, plural, one {about # row} other {about # rows}}"+msgstr "{count, plural, one {약 #행} other {약 #행}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {배치 # 해제} other {배치 # 해제}}"@@ -456,6 +474,12 @@ msgstr "{count, plural, one {배치 # 릴리스됨} other {배치 # 릴리스됨msgid "{count, plural, one {Released # job} other {Released # jobs}}"msgstr "{count, plural, one {작업 지시 # 릴리스됨} other {작업 지시 # 릴리스됨}}"+msgid "{count, plural, one {Select all # matching row} other {Select all # matching rows}}"+msgstr "{count, plural, one {일치하는 #행 모두 선택} other {일치하는 #행 모두 선택}}"++msgid "{count, plural, one {Select all matching rows (about #)} other {Select all matching rows (about #)}}"+msgstr "{count, plural, one {일치하는 모든 행 선택(약 #)} other {일치하는 모든 행 선택(약 #)}}"+msgid "{count} of {total} units"msgstr "{count}/{total} 개"@@ -486,12 +510,6 @@ msgstr "{done}개 중 {total}개 단계 완료"msgid "{excluded, plural, one {# row excluded} other {# rows excluded}}"msgstr "{excluded, plural, one {# 행 제외됨} other {# 행 제외됨}}"-msgid "{from}–{to} of {count}"-msgstr "{count}개 중 {from}–{to}"--msgid "{from}–{to} of {count} operations"-msgstr "{from}–{to}/{count} 공정"-msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"msgstr "{hidden, plural, one {그리고 # 개 이상의 기록.} other {그리고 # 개 이상의 기록.}}"@@ -515,6 +533,12 @@ msgstr "{linesCount, plural, one {# 줄} other {# 줄}}"msgid "{load} in queue"msgstr "큐에 {load}개 대기 중"+msgid "{loadedLabel} of {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel}, 전체 {total, plural, one {#행} other {#행}}"++msgid "{loadedLabel} of about {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel}, 전체 약 {total, plural, one {#행} other {#행}}"+msgid "{locationName} (the lease's)"msgstr "{locationName} (리스의 사업장)"@@ -607,6 +631,9 @@ msgstr "권한 {scopeCount}개"msgid "{sectionLineCount} lines"msgstr "{sectionLineCount} 라인"+msgid "{selectedCount, plural, one {# selected} other {# selected}}"+msgstr "{selectedCount, plural, one {#개 선택됨} other {#개 선택됨}}"+msgid "{selectedCount} selected"msgstr "{selectedCount}개 선택됨"@@ -622,6 +649,9 @@ msgstr "도입까지 {total}단계"msgid "{totalCount} results"msgstr "{totalCount}개 결과"+msgid "{totalLoaded} of {count}"+msgstr "{totalLoaded} / {count}"+msgid "{totalQuantity, plural, one {# unit} other {# units}}"msgstr "{totalQuantity, plural, one {# 단위} other {# 단위}}"@@ -2316,6 +2346,9 @@ msgstr "모든 위치"msgid "all make {0}"msgstr "모두 사내 생산 {0}"+msgid "All matching rows selected"+msgstr "일치하는 모든 행이 선택됨"+msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "선택한 그룹의 모든 구성원과 선택한 개인이 요청을 승인할 수 있습니다"@@ -5959,6 +5992,9 @@ msgstr "Onshape Government 연동을 완료 처리할 수 없습니다."msgid "Couldn't load documents"msgstr "문서를 불러올 수 없습니다"+msgid "Couldn't load more rows"+msgstr "행을 더 불러오지 못했습니다"+msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "관련 문서를 로드할 수 없습니다. 새 문서를 생성하기 전에 새로고침하여 복제를 피하십시오."@@ -7766,6 +7802,9 @@ msgstr "배치 해제"msgid "Dissolve Batch"msgstr "배치 해체"+msgid "Dissolve batches"+msgstr "배치 해제"+#. placeholder {0}: batch.readableIdmsgid "Dissolving {0} returns its {memberCount} operations to the schedule un-run and deletes the batch. A batch with recorded production must be completed instead."msgstr "배치 {0}를 해제하면 {memberCount}개의 공정을 미실행 상태로 일정에 반환하고 배치를 삭제합니다. 기록된 생산이 있는 배치는 대신 완료되어야 합니다."@@ -9087,6 +9126,9 @@ msgstr "모든 행이 성공적으로 가져와졌습니다."msgid "Every unit has a rate."msgstr "모든 단위에 요율이 있습니다."+msgid "Every user that matches the list's filters. Users this action does not apply to are skipped."+msgstr "목록 필터와 일치하는 모든 사용자입니다. 이 작업이 적용되지 않는 사용자는 건너뜁니다."+msgid "Everyone must set up an authenticator app before opening this company."msgstr "이 회사를 열기 전에 모든 사람이 인증기 앱을 설정해야 합니다."@@ -9328,6 +9370,9 @@ msgstr "CSV 내보내기"msgid "Export Lines to CSV"msgstr "라인을 CSV로 내보내기"+msgid "Exported the first {exportedCount} rows."+msgstr "처음 {exportedCount}행을 내보냈습니다."+msgid "Extended Price"msgstr "확장 가격"@@ -9885,6 +9930,12 @@ msgstr "필터 및 정렬"msgid "Filter by…"msgstr "필터링…"+msgid "Filter the list to {limit} rows or fewer"+msgstr "필터로 목록을 {limit}행 이하로 좁히세요"++msgid "Filter the list to {rows} rows or fewer"+msgstr "필터로 목록을 {rows}행 이하로 좁히세요"+msgid "Filters"msgstr "필터"@@ -11509,7 +11560,7 @@ msgid "Invoice schedule"msgstr "송장 일정"msgid "Invoice Separately"-msgstr ""+msgstr "별도 송장 발행"msgid "Invoice settlement"msgstr "송장 결제"@@ -11542,7 +11593,7 @@ msgid "Invoiced Amount:"msgstr "송장 발행 금액:"msgid "Invoiced separately"-msgstr ""+msgstr "별도 송장 발행됨"msgid "Invoiced Statuses"msgstr "송장 발행됨 상태"@@ -12438,9 +12489,6 @@ msgstr "실시간 새로고침"msgid "Load"msgstr "부하"-msgid "Load more"-msgstr "더 보기"-msgid "Load newer"msgstr "최신 항목 불러오기"@@ -12465,6 +12513,9 @@ msgstr "현재 수량 로드 중…"msgid "Loading item details..."msgstr "품목 세부정보를 불러오는 중..."+msgid "Loading more rows"+msgstr "행을 더 불러오는 중"+msgid "Loading returnable lines..."msgstr "반품 가능한 라인 로드 중..."@@ -17123,7 +17174,7 @@ msgid "Push to accounting"msgstr "회계로 푸시"msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."-msgstr ""+msgstr "이 청구를 별도 송장으로 발행하며, 전기되기 전에 검토를 위해 보류합니다. 그렇지 않으면 계약의 다음 송장에 포함됩니다."msgid "Putting your data back"msgstr "데이터 복원 중"@@ -17877,6 +17928,9 @@ msgstr "배치 릴리스"msgid "Release batch {0}"msgstr "배치 {0} 릴리스"+msgid "Release batches"+msgstr "배치 릴리스"+msgid "Release change notice"msgstr "변경 통지 릴리스"@@ -18451,9 +18505,6 @@ msgstr "결과"msgid "Results"msgstr "결과"-msgid "Results per page"-msgstr "페이지당 결과 수"-msgid "Resume"msgstr "재개"@@ -18852,9 +18903,6 @@ msgstr "라우팅"msgid "Routing Number (ABA)"msgstr "라우팅 번호(ABA)"-msgid "rows"-msgstr "행"-msgid "Rows left out of this backup"msgstr "이 백업에서 제외된 행"@@ -18930,6 +18978,9 @@ msgstr "이 워크플로우를 지금 실행하시겠습니까?"msgid "Running"msgstr "실행 중"+msgid "Running in the background. We'll notify you when it's done."+msgstr "백그라운드에서 실행 중입니다. 완료되면 알려 드리겠습니다."+msgid "Running inventory after each week's supply and demand — the line."msgstr "매주 공급 및 소요량 이후의 누계 재고 — 라인."@@ -19704,6 +19755,9 @@ msgstr "공급업체 유형 선택"msgid "Select surfaces"msgstr "표면 선택"+msgid "Select the first {limit} rows"+msgstr "처음 {limit}행 선택"+msgid "Select the groups that should complete this training"msgstr "이 교육을 완료해야 하는 그룹을 선택하세요"@@ -19967,7 +20021,7 @@ msgid "Set Up Accounting"msgstr "회계 설정"msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."-msgstr ""+msgstr "회계를 설정하면 보고서, 전표, 회계 기간, 감가상각 실행 등을 사용할 수 있습니다."msgid "Set up authenticator app"msgstr "인증자 앱 설정"@@ -20351,12 +20405,12 @@ msgstr "{0}개/총 {totalCount}개 표시 — 검색 범위 좁혀보기"msgid "Showing {0} of {totalFiltered} — refine your search"msgstr "{0}개 표시 (총 {totalFiltered}개) — 검색을 세밀하게 조정하세요"-msgid "Showing {firstShown}–{lastShown} of {total}"-msgstr "{firstShown}–{lastShown} / {total}"-msgid "Showing in {parentCurrency}"msgstr "{parentCurrency}로 표시"+msgid "Showing the first {limit} rows. Search or filter to see the rest."+msgstr "처음 {limit}행을 표시하고 있습니다. 나머지를 보려면 검색하거나 필터를 적용하세요."+msgid "Showing the first 500 lines"msgstr "처음 500줄을 표시하고 있습니다"@@ -22000,6 +22054,9 @@ msgstr "생산 중 이 품목의 출력량 손실의 예상 비율로, 계획에msgid "The expense account this indirect-spend line posts to; required because indirect lines don't have an item ledger entry to derive the account from."msgstr "이 간접비 지출 라인이 계상되는 비용 계정입니다. 간접비 라인은 계정을 도출할 품목 원장 항목이 없으므로 필수입니다."+msgid "The export could not start. Try again."+msgstr "내보내기를 시작하지 못했습니다. 다시 시도하세요."+msgid "The file you uploaded and the mappings you've made will be lost."msgstr "업로드한 파일과 설정한 매핑이 손실됩니다."@@ -22182,6 +22239,9 @@ msgstr "이 고객의 생애주기 상태입니다 — 활성, 잠재고객, 비msgid "The lifecycle state of this supplier — Active, Inactive, Pending Approval, etc.; only Active suppliers appear in PO / quote selectors."msgstr "이 공급업체의 생명주기 상태(활성, 비활성, 승인 대기 중 등)이며, 활성 공급업체만 발주서/견적서 선택기에 표시됩니다."+msgid "The list changed while the export loaded. Try again."+msgstr "내보내기를 준비하는 동안 목록이 변경되었습니다. 다시 시도하세요."+msgid "The local timezone this location reports time in; schedules, timecards, and shift hours at this location are interpreted in this zone regardless of the user's browser locale."msgstr "이 사업장이 시간을 보고하는 로컬 시간대로, 사용자의 브라우저 로케일에 관계없이 이 사업장의 일정, 타임카드 및 교대조 시간이 이 시간대로 해석됩니다."@@ -24140,6 +24200,9 @@ msgstr "발주서 수량 업데이트"msgid "Updated"msgstr "업데이트됨"+msgid "Updated {done}. Could not update {failed}: {message}"+msgstr "{done}건 변경됨. {failed}건은 변경하지 못했습니다: {message}"+msgid "Updated account"msgstr "계정이 업데이트됨"@@ -25629,6 +25692,9 @@ msgstr "DNS 공급자가 레코드 이름에 도메인을 자동으로 추가할msgid "Your Email"msgstr "이메일"+msgid "Your export is being prepared. We'll notify you when it's ready."+msgstr "내보내기를 준비하고 있습니다. 준비가 끝나면 알려 드리겠습니다."+msgid "Your general-ledger accounts and their structure"msgstr "총계정원장 계정과 그 구조"diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 5245d79b90..ec85f8043a 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -93,6 +93,10 @@ msgstr "{0, plural, one {# wiersz łączy się z danymi spoza tej firmy, dlategomsgid "{0, plural, one {# week} other {# weeks}}"msgstr "{0, plural, one {# tydzień} few {# tygodnie} many {# tygodni} other {# tygodnia}}"+#. placeholder {0}: allMatching.count+msgid "{0, plural, one {All matching rows selected (about #)} other {All matching rows selected (about #)}}"+msgstr "{0, plural, one {Zaznaczono wszystkie pasujące wiersze (około #)} other {Zaznaczono wszystkie pasujące wiersze (około #)}}"+#. placeholder {0}: check.countmsgid "{0, plural, one {Complete or cancel the # job that took costs before Carbon recorded them.} other {Complete or cancel the # jobs that took costs before Carbon recorded them.}}"msgstr "{0, plural, one {Ukończ lub anuluj # zlecenie produkcyjne, które poniosło koszty przed ich zarejestrowaniem przez Carbon.} other {Ukończ lub anuluj # zleceń produkcyjnych, które poniosły koszty przed ich zarejestrowaniem przez Carbon.}}"@@ -113,6 +117,10 @@ msgstr "{0, plural, one {Planista traktuje ten składnik jako jedno sztywne ciamsgid "{0, plural, one {This item is on 1 open change notice} other {This item is on # open change notices}}"msgstr "{0, plural, one {Ten artykuł jest na 1 otwartym zawiadomieniu o zmianie} other {Ten artykuł jest na # otwartych zawiadomieniach o zmianie}}"+#. placeholder {0}: rows.length+msgid "{0, plural, one {Total of # loaded row} other {Total of # loaded rows}}"+msgstr "{0, plural, one {Razem # załadowany wiersz} few {Razem # załadowane wiersze} many {Razem # załadowanych wierszy} other {Razem # załadowanych wierszy}}"+#. placeholder {0}: rate.customerType.namemsgid "{0} (type)"msgstr "{0} (typ)"@@ -252,6 +260,10 @@ msgstr "{0} z {1}"msgid "{0} of {1} posting accounts mapped"msgstr "{0} z {1} kont księgowych zmapowanych"+#. placeholder {0}: rows.length+msgid "{0} of {count} operations"+msgstr "{0} z {count} operacji"+#. placeholder {0}: rows.lengthmsgid "{0} of {maxSlots} provider slots used"msgstr "{0} z {maxSlots} slotów dostawcy jest w użyciu"@@ -441,6 +453,12 @@ msgstr "{count, plural, one {# kurs} other {# kursy}}"msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"msgstr "{count, plural, one {# więcej po {fenceLabel}} few {# więcej po {fenceLabel}} many {# więcej po {fenceLabel}} other {# więcej po {fenceLabel}}}"+msgid "{count, plural, one {# row} other {# rows}}"+msgstr "{count, plural, one {# wiersz} few {# wiersze} many {# wierszy} other {# wierszy}}"++msgid "{count, plural, one {about # row} other {about # rows}}"+msgstr "{count, plural, one {około # wiersz} few {około # wiersze} many {około # wierszy} other {około # wierszy}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {Rozpuść # partię produkcyjną} few {Rozpuść # partie produkcyjne} many {Rozpuść # partii produkcyjnych} other {Rozpuść # partii produkcyjnych}}"@@ -456,6 +474,12 @@ msgstr "{count, plural, one {Zwolniono # partię produkcyjną} few {Zwolniono #msgid "{count, plural, one {Released # job} other {Released # jobs}}"msgstr "{count, plural, one {Zwolniono # zlecenie produkcyjne} few {Zwolniono # zlecenia produkcyjne} many {Zwolniono # zleceń produkcyjnych} other {Zwolniono # zleceń produkcyjnych}}"+msgid "{count, plural, one {Select all # matching row} other {Select all # matching rows}}"+msgstr "{count, plural, one {Zaznacz wszystkie pasujące wiersze (#)} few {Zaznacz wszystkie pasujące wiersze (#)} many {Zaznacz wszystkie pasujące wiersze (#)} other {Zaznacz wszystkie pasujące wiersze (#)}}"++msgid "{count, plural, one {Select all matching rows (about #)} other {Select all matching rows (about #)}}"+msgstr "{count, plural, one {Zaznacz wszystkie pasujące wiersze (około #)} few {Zaznacz wszystkie pasujące wiersze (około #)} many {Zaznacz wszystkie pasujące wiersze (około #)} other {Zaznacz wszystkie pasujące wiersze (około #)}}"+msgid "{count} of {total} units"msgstr "{count} z {total} sztuk"@@ -486,12 +510,6 @@ msgstr "{done} z {total} faz ukończonych"msgid "{excluded, plural, one {# row excluded} other {# rows excluded}}"msgstr "{excluded, plural, one {# wiersz wyłączony} other {# wierszy wyłączonych}}"-msgid "{from}–{to} of {count}"-msgstr "{from}–{to} z {count}"--msgid "{from}–{to} of {count} operations"-msgstr "{from}–{to} z {count} operacji"-msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"msgstr "{hidden, plural, one {I jeszcze # rekord.} other {I jeszcze # rekordy.}}"@@ -515,6 +533,12 @@ msgstr "{linesCount, plural, one {# linia} other {# linii}}"msgid "{load} in queue"msgstr "{load} w kolejce"+msgid "{loadedLabel} of {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} z {total, plural, one {# wiersza} few {# wierszy} many {# wierszy} other {# wierszy}}"++msgid "{loadedLabel} of about {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} z około {total, plural, one {# wiersza} few {# wierszy} many {# wierszy} other {# wierszy}}"+msgid "{locationName} (the lease's)"msgstr "{locationName} (z leasingu)"@@ -607,6 +631,9 @@ msgstr "{scopeCount} uprawnień"msgid "{sectionLineCount} lines"msgstr "{sectionLineCount} pozycji"+msgid "{selectedCount, plural, one {# selected} other {# selected}}"+msgstr "{selectedCount, plural, one {# zaznaczony} few {# zaznaczone} many {# zaznaczonych} other {# zaznaczonych}}"+msgid "{selectedCount} selected"msgstr "{selectedCount} zaznaczonych"@@ -622,6 +649,9 @@ msgstr "{total} faz do uruchomienia"msgid "{totalCount} results"msgstr "{totalCount} wyników"+msgid "{totalLoaded} of {count}"+msgstr "{totalLoaded} z {count}"+msgid "{totalQuantity, plural, one {# unit} other {# units}}"msgstr "{totalQuantity, plural, one {# jednostka} other {# jednostek}}"@@ -2316,6 +2346,9 @@ msgstr "Wszystkie lokalizacje"msgid "all make {0}"msgstr "całość produkcji {0}"+msgid "All matching rows selected"+msgstr "Zaznaczono wszystkie pasujące wiersze"+msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "Wszyscy członkowie wybranych grup i wybrane osoby będą mogły zatwierdzać żądania"@@ -5959,6 +5992,9 @@ msgstr "Nie udało się zakończyć połączenia Onshape Government"msgid "Couldn't load documents"msgstr "Nie udało się załadować dokumentów"+msgid "Couldn't load more rows"+msgstr "Nie udało się wczytać kolejnych wierszy"+msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "Nie można załadować powiązanych dokumentów. Odśwież przed utworzeniem nowego, aby uniknąć duplikatów."@@ -7766,6 +7802,9 @@ msgstr "Rozwiązać partię"msgid "Dissolve Batch"msgstr "Rozpuść partię"+msgid "Dissolve batches"+msgstr "Rozłóż partie produkcyjne"+#. placeholder {0}: batch.readableIdmsgid "Dissolving {0} returns its {memberCount} operations to the schedule un-run and deletes the batch. A batch with recorded production must be completed instead."msgstr "Rozpuszczenie {0} zwraca jego {memberCount} operacji do harmonogramu nie wykonanych i usuwa partię. Partię z zarejestrowaną produkcją należy zamiast tego ukończyć."@@ -9087,6 +9126,9 @@ msgstr "Każdy wiersz został pomyślnie zaimportowany."msgid "Every unit has a rate."msgstr "Każda sztuka ma stawkę."+msgid "Every user that matches the list's filters. Users this action does not apply to are skipped."+msgstr "Każdy użytkownik pasujący do filtrów listy. Użytkownicy, których ta akcja nie dotyczy, zostaną pominięci."+msgid "Everyone must set up an authenticator app before opening this company."msgstr "Każdy musi skonfigurować aplikację uwierzytelniającą przed otwarciem tej firmy."@@ -9328,6 +9370,9 @@ msgstr "Eksportuj CSV"msgid "Export Lines to CSV"msgstr "Eksportuj linie do CSV"+msgid "Exported the first {exportedCount} rows."+msgstr "Wyeksportowano pierwsze {exportedCount} wierszy."+msgid "Extended Price"msgstr "Cena rozszerzona"@@ -9885,6 +9930,12 @@ msgstr "Filtruj i sortuj"msgid "Filter by…"msgstr "Filtruj wg…"+msgid "Filter the list to {limit} rows or fewer"+msgstr "Filtruj listę, aby zawierała maksymalnie {limit} wierszy"++msgid "Filter the list to {rows} rows or fewer"+msgstr "Filtruj listę, aby zawierała maksymalnie {rows} wierszy"+msgid "Filters"msgstr "Filtry"@@ -11509,7 +11560,7 @@ msgid "Invoice schedule"msgstr "Harmonogram fakturowania"msgid "Invoice Separately"-msgstr ""+msgstr "Wystaw osobną fakturę"msgid "Invoice settlement"msgstr "Rozliczenie faktury"@@ -11542,7 +11593,7 @@ msgid "Invoiced Amount:"msgstr "Kwota zafakturowana:"msgid "Invoiced separately"-msgstr ""+msgstr "Zafakturowano osobno"msgid "Invoiced Statuses"msgstr "Statusy Zafakturowane"@@ -12438,9 +12489,6 @@ msgstr "Odświeżanie na żywo"msgid "Load"msgstr "Obciążenie"-msgid "Load more"-msgstr "Załaduj więcej"-msgid "Load newer"msgstr "Załaduj nowsze"@@ -12465,6 +12513,9 @@ msgstr "Ładowanie bieżącej ilości…"msgid "Loading item details..."msgstr "Ładowanie szczegółów przedmiotu..."+msgid "Loading more rows"+msgstr "Wczytywanie kolejnych wierszy"+msgid "Loading returnable lines..."msgstr "Ładowanie linii podlegających zwrotowi..."@@ -17123,7 +17174,7 @@ msgid "Push to accounting"msgstr "Wyślij do systemu księgowego"msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."-msgstr ""+msgstr "Umieść tę opłatę na osobnej fakturze, wstrzymanej do przeglądu przed zaksięgowaniem. W przeciwnym razie trafi na następną fakturę umowy."msgid "Putting your data back"msgstr "Przywracanie twoich danych"@@ -17877,6 +17928,9 @@ msgstr "Zwolnij partię produkcyjną"msgid "Release batch {0}"msgstr "Zwolnij partię produkcyjną {0}"+msgid "Release batches"+msgstr "Zwolnij partie produkcyjne"+msgid "Release change notice"msgstr "Zwolnij zawiadomienie o zmianie"@@ -18451,9 +18505,6 @@ msgstr "Wynik"msgid "Results"msgstr "Wyniki"-msgid "Results per page"-msgstr "Wyniki na stronę"-msgid "Resume"msgstr "Wznów"@@ -18852,9 +18903,6 @@ msgstr "Marszruta"msgid "Routing Number (ABA)"msgstr "Numer routingu (ABA)"-msgid "rows"-msgstr "wiersze"-msgid "Rows left out of this backup"msgstr "Wiersze pominięte w tej kopii zapasowej"@@ -18930,6 +18978,9 @@ msgstr "Uruchomić ten przepływ pracy teraz?"msgid "Running"msgstr "Uruchomione"+msgid "Running in the background. We'll notify you when it's done."+msgstr "Działa w tle. Powiadomimy Cię, gdy się zakończy."+msgid "Running inventory after each week's supply and demand — the line."msgstr "Stan zapasów po każdym tygodniu pokrycia i zapotrzebowania — linia."@@ -19704,6 +19755,9 @@ msgstr "Wybierz typ dostawcy"msgid "Select surfaces"msgstr "Wybierz powierzchnie"+msgid "Select the first {limit} rows"+msgstr "Zaznacz pierwsze {limit} wierszy"+msgid "Select the groups that should complete this training"msgstr "Wybierz grupy, które powinny ukończyć to szkolenie"@@ -19967,7 +20021,7 @@ msgid "Set Up Accounting"msgstr "Skonfiguruj Księgowość"msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."-msgstr ""+msgstr "Skonfiguruj księgowość, aby korzystać z raportów, dowodów księgowych, okresów księgowych, uruchomień amortyzacji i innych funkcji."msgid "Set up authenticator app"msgstr "Skonfiguruj aplikację authenticator"@@ -20351,12 +20405,12 @@ msgstr "Wyświetlanie {0} z {totalCount} — uściśl wyszukiwanie"msgid "Showing {0} of {totalFiltered} — refine your search"msgstr "Pokazuję {0} z {totalFiltered} — sprecyzuj wyszukiwanie"-msgid "Showing {firstShown}–{lastShown} of {total}"-msgstr "Wyświetlanie {firstShown}–{lastShown} z {total}"-msgid "Showing in {parentCurrency}"msgstr "Wyświetlanie w {parentCurrency}"+msgid "Showing the first {limit} rows. Search or filter to see the rest."+msgstr "Pokazano pierwsze {limit} wierszy. Szukaj lub filtruj, aby zobaczyć resztę."+msgid "Showing the first 500 lines"msgstr "Pokazywanie pierwszych 500 linii"@@ -22000,6 +22054,9 @@ msgstr "Oczekiwany procent wyniku tego artykułu utraconego podczas produkcji; pmsgid "The expense account this indirect-spend line posts to; required because indirect lines don't have an item ledger entry to derive the account from."msgstr "Konto wydatków, na które ta linia wydatków pośrednich jest księgowana; wymagane, ponieważ linie pośrednie nie mają wpisu do księgi inwentarzowej, z którego można pochodzić konto."+msgid "The export could not start. Try again."+msgstr "Nie udało się rozpocząć eksportu. Spróbuj ponownie."+msgid "The file you uploaded and the mappings you've made will be lost."msgstr "Przesłany plik i utworzone mapowania zostaną utracone."@@ -22182,6 +22239,9 @@ msgstr "Stan cyklu życia tego klienta - Aktywny, Prospect, Nieaktywny, itp.; tymsgid "The lifecycle state of this supplier — Active, Inactive, Pending Approval, etc.; only Active suppliers appear in PO / quote selectors."msgstr "Stan cyklu życia tego dostawcy - Aktywny, Nieaktywny, Oczekujące Zatwierdzenie, itp.; tylko Aktywni dostawcy pojawiają się w selektorach PO/oferty."+msgid "The list changed while the export loaded. Try again."+msgstr "Lista zmieniła się podczas wczytywania eksportu. Spróbuj ponownie."+msgid "The local timezone this location reports time in; schedules, timecards, and shift hours at this location are interpreted in this zone regardless of the user's browser locale."msgstr "Lokalna strefa czasowa, w której ta lokalizacja zgłasza czas; harmonogramy, karty pracy i godziny zmian w tej lokalizacji są interpretowane w tej strefie niezależnie od locale przeglądarki użytkownika."@@ -24140,6 +24200,9 @@ msgstr "Zaktualizuj ilości zamówienia zakupu"msgid "Updated"msgstr "Zaktualizowano"+msgid "Updated {done}. Could not update {failed}: {message}"+msgstr "Zaktualizowano {done}. Nie udało się zaktualizować {failed}: {message}"+msgid "Updated account"msgstr "Zaktualizowano konto"@@ -25629,6 +25692,9 @@ msgstr "Twój dostawca DNS może automatycznie dołączyć Twoją domenę do nazmsgid "Your Email"msgstr "Twój e-mail"+msgid "Your export is being prepared. We'll notify you when it's ready."+msgstr "Eksport jest przygotowywany. Powiadomimy Cię, gdy będzie gotowy."+msgid "Your general-ledger accounts and their structure"msgstr "Twoje konta księgi głównej i ich struktura"diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex b4c35b733a..8bea94d27c 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -93,6 +93,10 @@ msgstr "{0, plural, one {# linha vincula dados fora desta empresa, portanto nãomsgid "{0, plural, one {# week} other {# weeks}}"msgstr "{0, plural, one {# semana} other {# semanas}}"+#. placeholder {0}: allMatching.count+msgid "{0, plural, one {All matching rows selected (about #)} other {All matching rows selected (about #)}}"+msgstr "{0, plural, one {Todas as linhas correspondentes selecionadas (cerca de #)} other {Todas as linhas correspondentes selecionadas (cerca de #)}}"+#. placeholder {0}: check.countmsgid "{0, plural, one {Complete or cancel the # job that took costs before Carbon recorded them.} other {Complete or cancel the # jobs that took costs before Carbon recorded them.}}"msgstr "{0, plural, one {Concluir ou cancelar a # ordem de produção que teve custos antes de o Carbon registrá-los.} other {Concluir ou cancelar as # ordens de produção que tiveram custos antes de o Carbon registrá-los.}}"@@ -113,6 +117,10 @@ msgstr "{0, plural, one {O planejador trata este componente como um corpo rígidmsgid "{0, plural, one {This item is on 1 open change notice} other {This item is on # open change notices}}"msgstr "{0, plural, one {Este item está em 1 aviso de alteração aberto} other {Este item está em # avisos de alteração abertos}}"+#. placeholder {0}: rows.length+msgid "{0, plural, one {Total of # loaded row} other {Total of # loaded rows}}"+msgstr "{0, plural, one {Total de # linha carregada} other {Total de # linhas carregadas}}"+#. placeholder {0}: rate.customerType.namemsgid "{0} (type)"msgstr "{0} (tipo)"@@ -252,6 +260,10 @@ msgstr "{0} de {1}"msgid "{0} of {1} posting accounts mapped"msgstr "{0} de {1} contas de contabilização mapeadas"+#. placeholder {0}: rows.length+msgid "{0} of {count} operations"+msgstr "{0} de {count} operações"+#. placeholder {0}: rows.lengthmsgid "{0} of {maxSlots} provider slots used"msgstr "{0} de {maxSlots} slots de provedor utilizados"@@ -441,6 +453,12 @@ msgstr "{count, plural, one {# curso} other {# cursos}}"msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"msgstr "{count, plural, one {# mais após {fenceLabel}} other {# mais após {fenceLabel}}}"+msgid "{count, plural, one {# row} other {# rows}}"+msgstr "{count, plural, one {# linha} other {# linhas}}"++msgid "{count, plural, one {about # row} other {about # rows}}"+msgstr "{count, plural, one {cerca de # linha} other {cerca de # linhas}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {Dissolver # lote de produção} other {Dissolver # lotes de produção}}"@@ -456,6 +474,12 @@ msgstr "{count, plural, one {# lote de produção liberado} other {# lotes de prmsgid "{count, plural, one {Released # job} other {Released # jobs}}"msgstr "{count, plural, one {# ordem de produção liberada} other {# ordens de produção liberadas}}"+msgid "{count, plural, one {Select all # matching row} other {Select all # matching rows}}"+msgstr "{count, plural, one {Selecionar a # linha correspondente} other {Selecionar todas as # linhas correspondentes}}"++msgid "{count, plural, one {Select all matching rows (about #)} other {Select all matching rows (about #)}}"+msgstr "{count, plural, one {Selecionar todas as linhas correspondentes (cerca de #)} other {Selecionar todas as linhas correspondentes (cerca de #)}}"+msgid "{count} of {total} units"msgstr "{count} de {total} unidades"@@ -486,12 +510,6 @@ msgstr "{done} de {total} fases concluídas"msgid "{excluded, plural, one {# row excluded} other {# rows excluded}}"msgstr "{excluded, plural, one {# linha excluída} other {# linhas excluídas}}"-msgid "{from}–{to} of {count}"-msgstr "{from}–{to} de {count}"--msgid "{from}–{to} of {count} operations"-msgstr "{from}–{to} de {count} operações"-msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"msgstr "{hidden, plural, one {E # mais registro.} other {E # mais registros.}}"@@ -515,6 +533,12 @@ msgstr "{linesCount, plural, one {# linha} other {# linhas}}"msgid "{load} in queue"msgstr "{load} na fila"+msgid "{loadedLabel} of {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} de {total, plural, one {# linha} other {# linhas}}"++msgid "{loadedLabel} of about {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} de cerca de {total, plural, one {# linha} other {# linhas}}"+msgid "{locationName} (the lease's)"msgstr "{locationName} (do arrendamento)"@@ -607,6 +631,9 @@ msgstr "{scopeCount} permissões"msgid "{sectionLineCount} lines"msgstr "{sectionLineCount} linhas"+msgid "{selectedCount, plural, one {# selected} other {# selected}}"+msgstr "{selectedCount, plural, one {# selecionado} other {# selecionados}}"+msgid "{selectedCount} selected"msgstr "{selectedCount} selecionados"@@ -622,6 +649,9 @@ msgstr "{total} fases para entrar em produção"msgid "{totalCount} results"msgstr "{totalCount} resultados"+msgid "{totalLoaded} of {count}"+msgstr "{totalLoaded} de {count}"+msgid "{totalQuantity, plural, one {# unit} other {# units}}"msgstr "{totalQuantity, plural, one {# unidade} other {# unidades}}"@@ -2316,6 +2346,9 @@ msgstr "Todos os Locais"msgid "all make {0}"msgstr "toda Fabricação {0}"+msgid "All matching rows selected"+msgstr "Todas as linhas correspondentes selecionadas"+msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "Todos os membros dos grupos selecionados e indivíduos selecionados poderão aprovar solicitações"@@ -5959,6 +5992,9 @@ msgstr "Não foi possível concluir a conexão com Onshape Government"msgid "Couldn't load documents"msgstr "Não foi possível carregar documentos"+msgid "Couldn't load more rows"+msgstr "Não foi possível carregar mais linhas"+msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "Não foi possível carregar os documentos relacionados. Atualize antes de criar um novo para evitar duplicatas."@@ -7766,6 +7802,9 @@ msgstr "Dissolver lote"msgid "Dissolve Batch"msgstr "Dissolver Lote"+msgid "Dissolve batches"+msgstr "Desfazer lotes de produção"+#. placeholder {0}: batch.readableIdmsgid "Dissolving {0} returns its {memberCount} operations to the schedule un-run and deletes the batch. A batch with recorded production must be completed instead."msgstr "A dissolução de {0} retorna suas {memberCount} operações para o cronograma não executado e exclui o lote. Um lote com produção registrada deve ser concluído."@@ -9087,6 +9126,9 @@ msgstr "Cada linha foi importada com sucesso."msgid "Every unit has a rate."msgstr "Cada unidade tem uma taxa."+msgid "Every user that matches the list's filters. Users this action does not apply to are skipped."+msgstr "Todo usuário que corresponde aos filtros da lista. Os usuários aos quais esta ação não se aplica serão ignorados."+msgid "Everyone must set up an authenticator app before opening this company."msgstr "Todos devem configurar um aplicativo autenticador antes de abrir esta empresa."@@ -9328,6 +9370,9 @@ msgstr "Exportar CSV"msgid "Export Lines to CSV"msgstr "Exportar Linhas para CSV"+msgid "Exported the first {exportedCount} rows."+msgstr "Exportadas as primeiras {exportedCount} linhas."+msgid "Extended Price"msgstr "Preço Estendido"@@ -9885,6 +9930,12 @@ msgstr "Filtrar e classificar"msgid "Filter by…"msgstr "Filtrar por…"+msgid "Filter the list to {limit} rows or fewer"+msgstr "Filtre a lista para {limit} linhas ou menos"++msgid "Filter the list to {rows} rows or fewer"+msgstr "Filtre a lista para {rows} linhas ou menos"+msgid "Filters"msgstr "Filtros"@@ -11509,7 +11560,7 @@ msgid "Invoice schedule"msgstr "Cronograma de faturamento"msgid "Invoice Separately"-msgstr ""+msgstr "Faturar Separadamente"msgid "Invoice settlement"msgstr "Liquidação de fatura"@@ -11542,7 +11593,7 @@ msgid "Invoiced Amount:"msgstr "Valor Faturado:"msgid "Invoiced separately"-msgstr ""+msgstr "Faturado separadamente"msgid "Invoiced Statuses"msgstr "Status Faturados"@@ -12438,9 +12489,6 @@ msgstr "Recarregamento ao vivo"msgid "Load"msgstr "Carga"-msgid "Load more"-msgstr "Carregar mais"-msgid "Load newer"msgstr "Carregar mais recentes"@@ -12465,6 +12513,9 @@ msgstr "Carregando quantidade atual…"msgid "Loading item details..."msgstr "Carregando detalhes do item..."+msgid "Loading more rows"+msgstr "Carregando mais linhas"+msgid "Loading returnable lines..."msgstr "Carregando linhas devolvíveis..."@@ -17123,7 +17174,7 @@ msgid "Push to accounting"msgstr "Enviar para contabilidade"msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."-msgstr ""+msgstr "Lança esta cobrança em uma fatura própria, retida para revisão antes de ser contabilizada. Caso contrário, ela vai para a próxima fatura do contrato."msgid "Putting your data back"msgstr "Colocando seus dados de volta"@@ -17877,6 +17928,9 @@ msgstr "Liberar lote de produção"msgid "Release batch {0}"msgstr "Liberar lote de produção {0}"+msgid "Release batches"+msgstr "Liberar lotes de produção"+msgid "Release change notice"msgstr "Liberar aviso de alteração"@@ -18451,9 +18505,6 @@ msgstr "Resultado"msgid "Results"msgstr "Resultados"-msgid "Results per page"-msgstr "Resultados por página"-msgid "Resume"msgstr "Retomar"@@ -18852,9 +18903,6 @@ msgstr "Roteiro de produção"msgid "Routing Number (ABA)"msgstr "Número de roteamento (ABA)"-msgid "rows"-msgstr "linhas"-msgid "Rows left out of this backup"msgstr "Linhas deixadas de fora deste backup"@@ -18930,6 +18978,9 @@ msgstr "Executar este fluxo de trabalho agora?"msgid "Running"msgstr "Em execução"+msgid "Running in the background. We'll notify you when it's done."+msgstr "Em execução em segundo plano. Avisaremos quando for concluído."+msgid "Running inventory after each week's supply and demand — the line."msgstr "Inventário em execução após o suprimento e demanda de cada semana — a linha."@@ -19704,6 +19755,9 @@ msgstr "Selecionar Tipo de Fornecedor"msgid "Select surfaces"msgstr "Selecionar superfícies"+msgid "Select the first {limit} rows"+msgstr "Selecione as primeiras {limit} linhas"+msgid "Select the groups that should complete this training"msgstr "Selecione os grupos que devem concluir este treinamento"@@ -19967,7 +20021,7 @@ msgid "Set Up Accounting"msgstr "Configurar contabilidade"msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."-msgstr ""+msgstr "Configure a contabilidade para usar relatórios, lançamentos de diário, períodos contábeis, execuções de depreciação e muito mais."msgid "Set up authenticator app"msgstr "Configurar aplicativo autenticador"@@ -20351,12 +20405,12 @@ msgstr "Mostrando {0} de {totalCount} — refine sua pesquisa"msgid "Showing {0} of {totalFiltered} — refine your search"msgstr "Mostrando {0} de {totalFiltered} — refine sua pesquisa"-msgid "Showing {firstShown}–{lastShown} of {total}"-msgstr "Mostrando {firstShown}–{lastShown} de {total}"-msgid "Showing in {parentCurrency}"msgstr "Exibindo em {parentCurrency}"+msgid "Showing the first {limit} rows. Search or filter to see the rest."+msgstr "Mostrando as primeiras {limit} linhas. Pesquise ou filtre para ver as demais."+msgid "Showing the first 500 lines"msgstr "Mostrando as primeiras 500 linhas"@@ -22000,6 +22054,9 @@ msgstr "O percentual esperado de saída deste item perdida durante a produção;msgid "The expense account this indirect-spend line posts to; required because indirect lines don't have an item ledger entry to derive the account from."msgstr "A conta de despesas em que essa linha de despesa indireta é lançada; obrigatória porque as linhas indiretas não têm um lançamento do livro de inventário do qual derivar a conta."+msgid "The export could not start. Try again."+msgstr "Não foi possível iniciar a exportação. Tente novamente."+msgid "The file you uploaded and the mappings you've made will be lost."msgstr "O arquivo enviado e os mapeamentos feitos serão perdidos."@@ -22182,6 +22239,9 @@ msgstr "O estado do ciclo de vida deste cliente - Ativo, Perspectiva, Inativo, emsgid "The lifecycle state of this supplier — Active, Inactive, Pending Approval, etc.; only Active suppliers appear in PO / quote selectors."msgstr "O estado do ciclo de vida deste fornecedor - Ativo, Inativo, Aprovação Pendente, etc.; apenas fornecedores Ativos aparecem nos seletores PO/cotação."+msgid "The list changed while the export loaded. Try again."+msgstr "A lista foi alterada enquanto a exportação carregava. Tente novamente."+msgid "The local timezone this location reports time in; schedules, timecards, and shift hours at this location are interpreted in this zone regardless of the user's browser locale."msgstr "O fuso horário local em que este local reporta a hora; as programações, apontamentos e horas de turno neste local são interpretados nesta zona independentemente da localidade do navegador do usuário."@@ -24140,6 +24200,9 @@ msgstr "Atualizar as quantidades do pedido de compra"msgid "Updated"msgstr "Atualizado"+msgid "Updated {done}. Could not update {failed}: {message}"+msgstr "Atualizados {done}. Não foi possível atualizar {failed}: {message}"+msgid "Updated account"msgstr "Conta atualizada"@@ -25629,6 +25692,9 @@ msgstr "Seu provedor de DNS pode anexar automaticamente seu domínio ao nome domsgid "Your Email"msgstr "Seu Email"+msgid "Your export is being prepared. We'll notify you when it's ready."+msgstr "Sua exportação está sendo preparada. Avisaremos quando estiver pronta."+msgid "Your general-ledger accounts and their structure"msgstr "Suas contas do razão geral e sua estrutura"diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex cf15f225ce..2e30f68ec1 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -93,6 +93,10 @@ msgstr "{0, plural, one {# строка связана с данными внеmsgid "{0, plural, one {# week} other {# weeks}}"msgstr "{0, plural, one {# неделя} few {# недели} many {# недель} other {# недели}}"+#. placeholder {0}: allMatching.count+msgid "{0, plural, one {All matching rows selected (about #)} other {All matching rows selected (about #)}}"+msgstr "{0, plural, one {Выбраны все подходящие строки (примерно #)} other {Выбраны все подходящие строки (примерно #)}}"+#. placeholder {0}: check.countmsgid "{0, plural, one {Complete or cancel the # job that took costs before Carbon recorded them.} other {Complete or cancel the # jobs that took costs before Carbon recorded them.}}"msgstr "{0, plural, one {Завершить или отменить # производственный заказ, по которому были затраты до того, как Carbon начал их записывать.} other {Завершить или отменить # производственные заказы, по которым были затраты до того, как Carbon начал их записывать.}}"@@ -113,6 +117,10 @@ msgstr "{0, plural, one {Планировщик рассматривает этmsgid "{0, plural, one {This item is on 1 open change notice} other {This item is on # open change notices}}"msgstr "{0, plural, one {Эта номенклатура находится в 1 открытом извещении об изменении} other {Эта номенклатура находится в # открытых извещениях об изменении}}"+#. placeholder {0}: rows.length+msgid "{0, plural, one {Total of # loaded row} other {Total of # loaded rows}}"+msgstr "{0, plural, one {Всего загружена # строка} few {Всего загружено # строки} many {Всего загружено # строк} other {Всего загружено # строки}}"+#. placeholder {0}: rate.customerType.namemsgid "{0} (type)"msgstr "{0} (тип)"@@ -252,6 +260,10 @@ msgstr "{0} из {1}"msgid "{0} of {1} posting accounts mapped"msgstr "{0} из {1} счетов проведения отображено"+#. placeholder {0}: rows.length+msgid "{0} of {count} operations"+msgstr "Операции: {0} из {count}"+#. placeholder {0}: rows.lengthmsgid "{0} of {maxSlots} provider slots used"msgstr "{0} из {maxSlots} слотов провайдера используется"@@ -441,6 +453,12 @@ msgstr "{count, plural, one {# курс} other {# курсов}}"msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"msgstr "{count, plural, one {# еще после {fenceLabel}} few {# еще после {fenceLabel}} many {# еще после {fenceLabel}} other {# еще после {fenceLabel}}}"+msgid "{count, plural, one {# row} other {# rows}}"+msgstr "{count, plural, one {# строка} few {# строки} many {# строк} other {# строки}}"++msgid "{count, plural, one {about # row} other {about # rows}}"+msgstr "{count, plural, one {около # строки} few {около # строк} many {около # строк} other {около # строк}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {Расформировать # серию} few {Расформировать # серии} many {Расформировать # серий} other {Расформировать # серий}}"@@ -456,6 +474,12 @@ msgstr "{count, plural, one {Запущена # серия} few {Запущенmsgid "{count, plural, one {Released # job} other {Released # jobs}}"msgstr "{count, plural, one {Запущен # производственный заказ} few {Запущено # производственных заказа} many {Запущено # производственных заказов} other {Запущено # производственных заказов}}"+msgid "{count, plural, one {Select all # matching row} other {Select all # matching rows}}"+msgstr "{count, plural, one {Выбрать все # подходящую строку} few {Выбрать все # подходящие строки} many {Выбрать все # подходящих строк} other {Выбрать все # подходящие строки}}"++msgid "{count, plural, one {Select all matching rows (about #)} other {Select all matching rows (about #)}}"+msgstr "{count, plural, one {Выбрать все подходящие строки (примерно #)} other {Выбрать все подходящие строки (примерно #)}}"+msgid "{count} of {total} units"msgstr "{count} из {total} единиц"@@ -486,12 +510,6 @@ msgstr "{done} из {total} этапов завершено"msgid "{excluded, plural, one {# row excluded} other {# rows excluded}}"msgstr "{excluded, plural, one {# строка исключена} other {# строк исключено}}"-msgid "{from}–{to} of {count}"-msgstr "{from}–{to} из {count}"--msgid "{from}–{to} of {count} operations"-msgstr "{from}–{to} из {count} операций"-msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"msgstr "{hidden, plural, one {Еще # запись.} other {Еще # записей.}}"@@ -515,6 +533,12 @@ msgstr "{linesCount, plural, one {# строка} other {# строк}}"msgid "{load} in queue"msgstr "{load} в очереди"+msgid "{loadedLabel} of {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} из {total, plural, one {# строки} few {# строк} many {# строк} other {# строк}}"++msgid "{loadedLabel} of about {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} из примерно {total, plural, one {# строки} few {# строк} many {# строк} other {# строк}}"+msgid "{locationName} (the lease's)"msgstr "{locationName} (площадка аренды)"@@ -607,6 +631,9 @@ msgstr "{scopeCount} прав доступа"msgid "{sectionLineCount} lines"msgstr "{sectionLineCount} строк"+msgid "{selectedCount, plural, one {# selected} other {# selected}}"+msgstr "{selectedCount, plural, one {Выбрано: #} other {Выбрано: #}}"+msgid "{selectedCount} selected"msgstr "{selectedCount} выбрано"@@ -622,6 +649,9 @@ msgstr "{total} этапов до запуска"msgid "{totalCount} results"msgstr "{totalCount} результатов"+msgid "{totalLoaded} of {count}"+msgstr "{totalLoaded} из {count}"+msgid "{totalQuantity, plural, one {# unit} other {# units}}"msgstr "{totalQuantity, plural, one {# единица} other {# единиц}}"@@ -2316,6 +2346,9 @@ msgstr "Все местоположения"msgid "all make {0}"msgstr "все производят {0}"+msgid "All matching rows selected"+msgstr "Выбраны все подходящие строки"+msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "Все члены выбранных групп и выбранные лица смогут утвердить запросы"@@ -5959,6 +5992,9 @@ msgstr "Не удалось завершить подключение Onshape Gomsgid "Couldn't load documents"msgstr "Не удалось загрузить документы"+msgid "Couldn't load more rows"+msgstr "Не удалось загрузить больше строк"+msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "Не удалось загрузить связанные документы. Обновите страницу перед созданием нового, чтобы избежать дублирования."@@ -7766,6 +7802,9 @@ msgstr "Разбить партию"msgid "Dissolve Batch"msgstr "Распустить партию"+msgid "Dissolve batches"+msgstr "Расформировать серии"+#. placeholder {0}: batch.readableIdmsgid "Dissolving {0} returns its {memberCount} operations to the schedule un-run and deletes the batch. A batch with recorded production must be completed instead."msgstr "Распускание {0} возвращает его {memberCount} операций в расписание невыполненными и удаляет партию. Партию с записанным производством необходимо вместо этого завершить."@@ -9087,6 +9126,9 @@ msgstr "Каждая строка была успешно импортироваmsgid "Every unit has a rate."msgstr "Каждая единица имеет ставку."+msgid "Every user that matches the list's filters. Users this action does not apply to are skipped."+msgstr "Каждый пользователь, подходящий под фильтры списка. Пользователи, к которым это действие не применяется, пропускаются."+msgid "Everyone must set up an authenticator app before opening this company."msgstr "Все должны установить приложение-аутентификатор перед открытием этой организации."@@ -9328,6 +9370,9 @@ msgstr "Экспортировать CSV"msgid "Export Lines to CSV"msgstr "Экспортировать строки в CSV"+msgid "Exported the first {exportedCount} rows."+msgstr "Экспортированы первые {exportedCount} строк."+msgid "Extended Price"msgstr "Расширенная цена"@@ -9885,6 +9930,12 @@ msgstr "Фильтр и сортировка"msgid "Filter by…"msgstr "Фильтровать по…"+msgid "Filter the list to {limit} rows or fewer"+msgstr "Отфильтруйте список до {limit} строк или меньше"++msgid "Filter the list to {rows} rows or fewer"+msgstr "Отфильтруйте список до {rows} строк или меньше"+msgid "Filters"msgstr "Фильтры"@@ -11509,7 +11560,7 @@ msgid "Invoice schedule"msgstr "График выставления счетов"msgid "Invoice Separately"-msgstr ""+msgstr "Выставить счет-фактуру отдельно"msgid "Invoice settlement"msgstr "Расчет по счету-фактуре"@@ -11542,7 +11593,7 @@ msgid "Invoiced Amount:"msgstr "Выставленная сумма счета-фактуры:"msgid "Invoiced separately"-msgstr ""+msgstr "Выставлен счет отдельно"msgid "Invoiced Statuses"msgstr "Статусы выставленного счета"@@ -12438,9 +12489,6 @@ msgstr "Живая перезагрузка"msgid "Load"msgstr "Нагрузка"-msgid "Load more"-msgstr "Загрузить ещё"-msgid "Load newer"msgstr "Загрузить новые"@@ -12465,6 +12513,9 @@ msgstr "Загрузка текущего количества…"msgid "Loading item details..."msgstr "Загрузка деталей товара..."+msgid "Loading more rows"+msgstr "Загружаем больше строк"+msgid "Loading returnable lines..."msgstr "Загрузка возвратных строк..."@@ -17123,7 +17174,7 @@ msgid "Push to accounting"msgstr "Отправить в бухгалтерию"msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."-msgstr ""+msgstr "Выставить это начисление отдельной счет-фактурой. Она будет ждать проверки до проведения. Иначе начисление попадет в следующий счет по договору."msgid "Putting your data back"msgstr "Восстановление ваших данных"@@ -17877,6 +17928,9 @@ msgstr "Запустить серию в работу"msgid "Release batch {0}"msgstr "Запустить в работу серию {0}"+msgid "Release batches"+msgstr "Запустить серии в работу"+msgid "Release change notice"msgstr "Запустить в работу извещение об изменении"@@ -18451,9 +18505,6 @@ msgstr "Результат"msgid "Results"msgstr "Результаты"-msgid "Results per page"-msgstr "Результатов на странице"-msgid "Resume"msgstr "Возобновить"@@ -18852,9 +18903,6 @@ msgstr "Маршрут операций"msgid "Routing Number (ABA)"msgstr "Маршрутный номер (ABA)"-msgid "rows"-msgstr "строк"-msgid "Rows left out of this backup"msgstr "Строки, не включенные в эту резервную копию"@@ -18930,6 +18978,9 @@ msgstr "Запустить этот рабочий процесс сейчас?"msgid "Running"msgstr "Выполняется"+msgid "Running in the background. We'll notify you when it's done."+msgstr "Выполняется в фоновом режиме. Мы уведомим вас, когда процесс завершится."+msgid "Running inventory after each week's supply and demand — the line."msgstr "Текущие запасы после еженедельного обеспечения и потребности — строка."@@ -19704,6 +19755,9 @@ msgstr "Выберите тип поставщика"msgid "Select surfaces"msgstr "Выберите поверхности"+msgid "Select the first {limit} rows"+msgstr "Выбрать первые {limit} строк"+msgid "Select the groups that should complete this training"msgstr "Выберите группы, которые должны пройти это обучение"@@ -19967,7 +20021,7 @@ msgid "Set Up Accounting"msgstr "Установка бухгалтерии"msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."-msgstr ""+msgstr "Настройте бухгалтерию, чтобы пользоваться отчетами, журнальными операциями, учетными периодами, запусками амортизации и другим."msgid "Set up authenticator app"msgstr "Установить приложение аутентификации"@@ -20351,12 +20405,12 @@ msgstr "Показано {0} из {totalCount} — уточните поиск"msgid "Showing {0} of {totalFiltered} — refine your search"msgstr "Показано {0} из {totalFiltered} — уточните поиск"-msgid "Showing {firstShown}–{lastShown} of {total}"-msgstr "Показаны {firstShown}–{lastShown} из {total}"-msgid "Showing in {parentCurrency}"msgstr "Отображение в {parentCurrency}"+msgid "Showing the first {limit} rows. Search or filter to see the rest."+msgstr "Показаны первые {limit} строк. Используйте поиск или фильтр, чтобы увидеть остальные."+msgid "Showing the first 500 lines"msgstr "Показано первые 500 строк"@@ -22000,6 +22054,9 @@ msgstr "Ожидаемый процент выпуска этой номенклmsgid "The expense account this indirect-spend line posts to; required because indirect lines don't have an item ledger entry to derive the account from."msgstr "Счет расходов, на который относится эта строка косвенных расходов; требуется, так как косвенные строки не имеют записи в книге товаров, из которой можно вывести счет."+msgid "The export could not start. Try again."+msgstr "Не удалось начать экспорт. Попробуйте еще раз."+msgid "The file you uploaded and the mappings you've made will be lost."msgstr "Загруженный файл и созданные сопоставления будут потеряны."@@ -22182,6 +22239,9 @@ msgstr "Состояние жизненного цикла этого покупmsgid "The lifecycle state of this supplier — Active, Inactive, Pending Approval, etc.; only Active suppliers appear in PO / quote selectors."msgstr "Состояние жизненного цикла этого поставщика — Активный, Неактивный, В ожидании утверждения и т. д.; только активные поставщики появляются в селекторах заказов поставщикам и коммерческих предложений."+msgid "The list changed while the export loaded. Try again."+msgstr "Список изменился во время подготовки экспорта. Попробуйте еще раз."+msgid "The local timezone this location reports time in; schedules, timecards, and shift hours at this location are interpreted in this zone regardless of the user's browser locale."msgstr "Местный часовой пояс, в котором это местоположение сообщает время; расписания, табели учета рабочего времени и часы смены в этом месте интерпретируются в этом часовом поясе независимо от локали браузера пользователя."@@ -24140,6 +24200,9 @@ msgstr "Обновить количества Заказа поставщику"msgid "Updated"msgstr "Обновлено"+msgid "Updated {done}. Could not update {failed}: {message}"+msgstr "Обновлено: {done}. Не удалось обновить {failed}: {message}"+msgid "Updated account"msgstr "Счет обновлен"@@ -25629,6 +25692,9 @@ msgstr "Ваш поставщик DNS может автоматически доmsgid "Your Email"msgstr "Ваша электронная почта"+msgid "Your export is being prepared. We'll notify you when it's ready."+msgstr "Экспорт готовится. Мы уведомим вас, когда файл будет готов."+msgid "Your general-ledger accounts and their structure"msgstr "Ваши счета главной книги и их структура"diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex b048b9a924..fee3fc4331 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -93,6 +93,10 @@ msgstr "{0, plural, one {# satır bu şirketin dışındaki verilere bağlantımsgid "{0, plural, one {# week} other {# weeks}}"msgstr "{0, plural, one {# hafta} other {# hafta}}"+#. placeholder {0}: allMatching.count+msgid "{0, plural, one {All matching rows selected (about #)} other {All matching rows selected (about #)}}"+msgstr "Eşleşen satırların tümü seçildi (yaklaşık #)"+#. placeholder {0}: check.countmsgid "{0, plural, one {Complete or cancel the # job that took costs before Carbon recorded them.} other {Complete or cancel the # jobs that took costs before Carbon recorded them.}}"msgstr "{0, plural, one {Carbon maliyetleri kaydetmeden önce maliyet oluşan # iş emrini tamamla veya iptal et.} other {Carbon maliyetleri kaydetmeden önce maliyet oluşan # iş emirlerini tamamla veya iptal et.}}"@@ -113,6 +117,10 @@ msgstr "{0, plural, one {Planlama motoru bu bileşeni tek bir rijit gövde olaramsgid "{0, plural, one {This item is on 1 open change notice} other {This item is on # open change notices}}"msgstr "{0, plural, one {Bu ürün 1 açık değişiklik bildirisinde yer alıyor} other {Bu ürün # açık değişiklik bildirisinde yer alıyor}}"+#. placeholder {0}: rows.length+msgid "{0, plural, one {Total of # loaded row} other {Total of # loaded rows}}"+msgstr "Yüklenen toplam # satır"+#. placeholder {0}: rate.customerType.namemsgid "{0} (type)"msgstr "{0} (tür)"@@ -252,6 +260,10 @@ msgstr "{0} / {1}"msgid "{0} of {1} posting accounts mapped"msgstr "{0}/{1} muhasebeleştirme hesabı eşleştirildi"+#. placeholder {0}: rows.length+msgid "{0} of {count} operations"+msgstr "{count} operasyonlardan {0}"+#. placeholder {0}: rows.lengthmsgid "{0} of {maxSlots} provider slots used"msgstr "{0}/{maxSlots} sağlayıcı yuvası kullanıldı"@@ -441,6 +453,12 @@ msgstr "{count, plural, one {# kurs} other {# kurs}}"msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"msgstr "{count, plural, one {# daha {fenceLabel} sonra} other {# daha {fenceLabel} sonra}}"+msgid "{count, plural, one {# row} other {# rows}}"+msgstr "{count, plural, one {# satır} other {# satır}}"++msgid "{count, plural, one {about # row} other {about # rows}}"+msgstr "{count, plural, one {yaklaşık # satır} other {yaklaşık # satır}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {# partiyi çöz} other {# partileri çöz}}"@@ -456,6 +474,12 @@ msgstr "{count, plural, one {# parti serbest bırakıldı} other {# partiler sermsgid "{count, plural, one {Released # job} other {Released # jobs}}"msgstr "{count, plural, one {# iş emri serbest bırakıldı} other {# iş emirleri serbest bırakıldı}}"+msgid "{count, plural, one {Select all # matching row} other {Select all # matching rows}}"+msgstr "Eşleşen # satırın tümünü seç"++msgid "{count, plural, one {Select all matching rows (about #)} other {Select all matching rows (about #)}}"+msgstr "Eşleşen satırların tümünü seç (yaklaşık #)"+msgid "{count} of {total} units"msgstr "{count}/{total} adet"@@ -486,12 +510,6 @@ msgstr "{done} / {total} aşama tamamlandı"msgid "{excluded, plural, one {# row excluded} other {# rows excluded}}"msgstr "{excluded, plural, one {# satır hariç tutuldu} other {# satır hariç tutuldu}}"-msgid "{from}–{to} of {count}"-msgstr "{from}–{to} / {count}"--msgid "{from}–{to} of {count} operations"-msgstr "{from}–{to} /{count} operasyon"-msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"msgstr "{hidden, plural, one {Ve # daha fazla kayıt.} other {Ve # daha fazla kayıt.}}"@@ -515,6 +533,12 @@ msgstr "{linesCount, plural, one {# satır} other {# satırlar}}"msgid "{load} in queue"msgstr "{load} kuyruğunda"+msgid "{loadedLabel} of {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} / {total, plural, one {# satır} other {# satır}}"++msgid "{loadedLabel} of about {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} / yaklaşık {total, plural, one {# satır} other {# satır}}"+msgid "{locationName} (the lease's)"msgstr "{locationName} (kiralamanın)"@@ -607,6 +631,9 @@ msgstr "{scopeCount} izinleri"msgid "{sectionLineCount} lines"msgstr "{sectionLineCount} satır"+msgid "{selectedCount, plural, one {# selected} other {# selected}}"+msgstr "{selectedCount, plural, one {# seçili} other {# seçili}}"+msgid "{selectedCount} selected"msgstr "{selectedCount} seçildi"@@ -622,6 +649,9 @@ msgstr "{total} aşama canlı yayına alınacak"msgid "{totalCount} results"msgstr "{totalCount} sonuç"+msgid "{totalLoaded} of {count}"+msgstr "{totalLoaded} / {count}"+msgid "{totalQuantity, plural, one {# unit} other {# units}}"msgstr "{totalQuantity, plural, one {# birim} other {# birimler}}"@@ -2316,6 +2346,9 @@ msgstr "Tüm Konumlar"msgid "all make {0}"msgstr "tümü {0} üretim"+msgid "All matching rows selected"+msgstr "Eşleşen tüm satırlar seçildi"+msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "Seçilen gruplardaki ve bireylerdeki tüm üyeler talepleri onaylayabilecektir"@@ -5959,6 +5992,9 @@ msgstr "Onshape Government bağlantısı tamamlanamadı"msgid "Couldn't load documents"msgstr "Belgeler yüklenemedi"+msgid "Couldn't load more rows"+msgstr "Daha fazla satır yüklenemedi"+msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "İlgili belgeler yüklenemedi. Yinelemelerden kaçınmak için yeni bir tane oluşturmadan önce yenileyin."@@ -7766,6 +7802,9 @@ msgstr "Toplu İşi Kaldır"msgid "Dissolve Batch"msgstr "Toplu İşi Çöz"+msgid "Dissolve batches"+msgstr "Partileri dağıt"+#. placeholder {0}: batch.readableIdmsgid "Dissolving {0} returns its {memberCount} operations to the schedule un-run and deletes the batch. A batch with recorded production must be completed instead."msgstr "{0} çözüldüğünde, {memberCount} operasyonu zamanlamaya yürütülmemiş olarak geri verir ve toplu işi siler. Kaydedilmiş üretimi olan bir toplu iş yerine tamamlanmalıdır."@@ -9087,6 +9126,9 @@ msgstr "Her satır başarıyla içe aktarıldı."msgid "Every unit has a rate."msgstr "Her adetin bir oranı vardır."+msgid "Every user that matches the list's filters. Users this action does not apply to are skipped."+msgstr "Listenin filtrelerine uyan her kullanıcı. Bu işlemin uygulanmadığı kullanıcılar atlanır."+msgid "Everyone must set up an authenticator app before opening this company."msgstr "Herkes bu şirketi açmadan önce bir kimlik doğrulaması uygulaması kurması gerekir."@@ -9328,6 +9370,9 @@ msgstr "CSV'yi dışa aktar"msgid "Export Lines to CSV"msgstr "Satırları CSV'ye Dışa Aktar"+msgid "Exported the first {exportedCount} rows."+msgstr "İlk {exportedCount} satır dışa aktarıldı."+msgid "Extended Price"msgstr "Genelletilmiş Fiyat"@@ -9885,6 +9930,12 @@ msgstr "Filtrele ve sırala"msgid "Filter by…"msgstr "Filtrele…"+msgid "Filter the list to {limit} rows or fewer"+msgstr "Listeyi en fazla {limit} satır olacak şekilde filtrele"++msgid "Filter the list to {rows} rows or fewer"+msgstr "Listeyi en fazla {rows} satır olacak şekilde filtrele"+msgid "Filters"msgstr "Filtreler"@@ -11509,7 +11560,7 @@ msgid "Invoice schedule"msgstr "Fatura çizelgesi"msgid "Invoice Separately"-msgstr ""+msgstr "Ayrı Faturala"msgid "Invoice settlement"msgstr "Fatura Ödeme"@@ -11542,7 +11593,7 @@ msgid "Invoiced Amount:"msgstr "Faturalandı Tutarı:"msgid "Invoiced separately"-msgstr ""+msgstr "Ayrı faturalandı"msgid "Invoiced Statuses"msgstr "Faturalandı Durumları"@@ -12438,9 +12489,6 @@ msgstr "Canlı yeniden yükleniyor"msgid "Load"msgstr "Yük"-msgid "Load more"-msgstr "Daha fazla yükle"-msgid "Load newer"msgstr "Daha yenisini yükle"@@ -12465,6 +12513,9 @@ msgstr "Geçerli miktar yükleniyor…"msgid "Loading item details..."msgstr "Ürün detayları yükleniyor..."+msgid "Loading more rows"+msgstr "Daha fazla satır yükleniyor"+msgid "Loading returnable lines..."msgstr "İadesine uygun satırlar yükleniyor..."@@ -17123,7 +17174,7 @@ msgid "Push to accounting"msgstr "Muhasebede gönder"msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."-msgstr ""+msgstr "Bu ücreti kendi faturasına ayırın; muhasebeleştirilmeden önce incelemeye alınır. Aksi halde sözleşmenin bir sonraki faturasına eklenir."msgid "Putting your data back"msgstr "Verileriniz geri konuluyor"@@ -17877,6 +17928,9 @@ msgstr "Partiyi Serbest Bırak"msgid "Release batch {0}"msgstr "Parti {0} serbest bırak"+msgid "Release batches"+msgstr "Partileri serbest bırak"+msgid "Release change notice"msgstr "Değişiklik bildirimi serbest bırak"@@ -18451,9 +18505,6 @@ msgstr "Sonuç"msgid "Results"msgstr "Sonuçlar"-msgid "Results per page"-msgstr "Sayfa başına sonuçlar"-msgid "Resume"msgstr "Devam et"@@ -18852,9 +18903,6 @@ msgstr "Operasyon rotası"msgid "Routing Number (ABA)"msgstr "Yönlendirme numarası (ABA)"-msgid "rows"-msgstr "satırlar"-msgid "Rows left out of this backup"msgstr "Bu yedeklemeden hariç tutulan satırlar"@@ -18930,6 +18978,9 @@ msgstr "Bu iş akışı şimdi çalıştırılsın mı?"msgid "Running"msgstr "Çalışıyor"+msgid "Running in the background. We'll notify you when it's done."+msgstr "Arka planda çalışıyor. Bittiğinde size haber vereceğiz."+msgid "Running inventory after each week's supply and demand — the line."msgstr "Her haftalık arz ve talep sonrası çalışan envanter — satır."@@ -19704,6 +19755,9 @@ msgstr "Tedarikçi Türü Seçin"msgid "Select surfaces"msgstr "Yüzeyleri seç"+msgid "Select the first {limit} rows"+msgstr "İlk {limit} satırı seç"+msgid "Select the groups that should complete this training"msgstr "Bu eğitimi tamamlaması gereken grupları seçin"@@ -19967,7 +20021,7 @@ msgid "Set Up Accounting"msgstr "Muhasebeyi Ayarlayın"msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."-msgstr ""+msgstr "Raporları, muhasebe fişlerini, muhasebe dönemlerini, amortisman çalıştırmalarını ve daha fazlasını kullanmak için muhasebeyi kurun."msgid "Set up authenticator app"msgstr "Doğrulayıcı uygulamayı ayarla"@@ -20351,12 +20405,12 @@ msgstr "{0} / {totalCount} gösteriliyor — aramanızı daraltın"msgid "Showing {0} of {totalFiltered} — refine your search"msgstr "{0} / {totalFiltered} gösteriliyor — aramanızı daraltın"-msgid "Showing {firstShown}–{lastShown} of {total}"-msgstr "{firstShown}–{lastShown} / {total} gösteriliyor"-msgid "Showing in {parentCurrency}"msgstr "{parentCurrency} cinsinden gösteriliyor"+msgid "Showing the first {limit} rows. Search or filter to see the rest."+msgstr "İlk {limit} satır gösteriliyor. Kalanları görmek için ara veya filtrele."+msgid "Showing the first 500 lines"msgstr "İlk 500 satır gösteriliyor"@@ -22000,6 +22054,9 @@ msgstr "Bu stok kartının üretim sırasında kaybettiği beklenen yüzde; planmsgid "The expense account this indirect-spend line posts to; required because indirect lines don't have an item ledger entry to derive the account from."msgstr "Bu dolaylı harcama satırının nakledildiği gider hesabı; dolaylı satırlar hesabı türetmek için bir envanter defter girişine sahip olmadığından gereklidir."+msgid "The export could not start. Try again."+msgstr "Dışa aktarma başlatılamadı. Tekrar deneyin."+msgid "The file you uploaded and the mappings you've made will be lost."msgstr "Yüklediğiniz dosya ve yaptığınız eşleştirmeler kaybolacak."@@ -22182,6 +22239,9 @@ msgstr "Bu Müşterinin yaşam döngüsü durumu — Aktif, Potansiyel müşterimsgid "The lifecycle state of this supplier — Active, Inactive, Pending Approval, etc.; only Active suppliers appear in PO / quote selectors."msgstr "Bu Tedarikçinin yaşam döngüsü durumu — Aktif, Pasif, Onay Beklemede vb.; sadece Aktif Tedarikçiler Satın alma siparişi / Teklif seçicilerinde görünür."+msgid "The list changed while the export loaded. Try again."+msgstr "Dışa aktarma yüklenirken liste değişti. Tekrar deneyin."+msgid "The local timezone this location reports time in; schedules, timecards, and shift hours at this location are interpreted in this zone regardless of the user's browser locale."msgstr "Bu Lokasyonda raporlanan yerel saat dilimi; bu Lokasyondaki Çizelgeler, Puantajlar ve Vardiya saatleri kullanıcının tarayıcı yerinden bağımsız olarak bu dilimde yorumlanır."@@ -24140,6 +24200,9 @@ msgstr "Satın alma siparişi miktarlarını güncelle"msgid "Updated"msgstr "Güncellendi"+msgid "Updated {done}. Could not update {failed}: {message}"+msgstr "{done} güncellendi. {failed} güncellenemedi: {message}"+msgid "Updated account"msgstr "Hesap güncellendi"@@ -25629,6 +25692,9 @@ msgstr "DNS sağlayıcınız kaydın adına etki alanınızı otomatik olarak ekmsgid "Your Email"msgstr "E-posta Adresiniz"+msgid "Your export is being prepared. We'll notify you when it's ready."+msgstr "Dışa aktarımınız hazırlanıyor. Hazır olduğunda size haber vereceğiz."+msgid "Your general-ledger accounts and their structure"msgstr "Genel muhasebe hesaplarınız ve bunların yapısı"diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex eeff6a1765..389e5dbea5 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -93,6 +93,10 @@ msgstr "{0, plural, one {# 行链接到该公司外的数据,无法备份。msgid "{0, plural, one {# week} other {# weeks}}"msgstr "{0, plural, other {#周}}"+#. placeholder {0}: allMatching.count+msgid "{0, plural, one {All matching rows selected (about #)} other {All matching rows selected (about #)}}"+msgstr "{0, plural, one {已选择全部匹配行(约 #)} other {已选择全部匹配行(约 #)}}"+#. placeholder {0}: check.countmsgid "{0, plural, one {Complete or cancel the # job that took costs before Carbon recorded them.} other {Complete or cancel the # jobs that took costs before Carbon recorded them.}}"msgstr "{0, plural, one {完成或取消在 Carbon 记录成本之前已产生成本的 # 个工单。} other {完成或取消在 Carbon 记录成本之前已产生成本的 # 个工单。}}"@@ -113,6 +117,10 @@ msgstr "{0, plural, one {计划员将此组件视为一个刚体 — 说明中msgid "{0, plural, one {This item is on 1 open change notice} other {This item is on # open change notices}}"msgstr "{0, plural, one {此物料有1个未结的变更通知} other {此物料有#个未结的变更通知}}"+#. placeholder {0}: rows.length+msgid "{0, plural, one {Total of # loaded row} other {Total of # loaded rows}}"+msgstr "{0, plural, one {共 # 行已加载} other {共 # 行已加载}}"+#. placeholder {0}: rate.customerType.namemsgid "{0} (type)"msgstr "{0}(类型)"@@ -252,6 +260,10 @@ msgstr "{0}/{1}"msgid "{0} of {1} posting accounts mapped"msgstr "{0} / {1} 个过账科目已映射"+#. placeholder {0}: rows.length+msgid "{0} of {count} operations"+msgstr "{0} / 共 {count} 道工序"+#. placeholder {0}: rows.lengthmsgid "{0} of {maxSlots} provider slots used"msgstr "{0} / {maxSlots} 个提供商插槽已使用"@@ -441,6 +453,12 @@ msgstr "{count, plural, one {# 门课程} other {# 门课程}}"msgid "{count, plural, one {# More After {fenceLabel}} other {# More After {fenceLabel}}}"msgstr "{count, plural, other {{fenceLabel}之后还有 # 个}}"+msgid "{count, plural, one {# row} other {# rows}}"+msgstr "{count, plural, one {# 行} other {# 行}}"++msgid "{count, plural, one {about # row} other {about # rows}}"+msgstr "{count, plural, one {约 # 行} other {约 # 行}}"+msgid "{count, plural, one {Dissolve # batch} other {Dissolve # batches}}"msgstr "{count, plural, one {关闭 # 生产批次} other {关闭 # 生产批次}}"@@ -456,6 +474,12 @@ msgstr "{count, plural, one {已发布 # 生产批次} other {已发布 # 生产msgid "{count, plural, one {Released # job} other {Released # jobs}}"msgstr "{count, plural, one {已下达 # 工单} other {已下达 # 工单}}"+msgid "{count, plural, one {Select all # matching row} other {Select all # matching rows}}"+msgstr "{count, plural, one {选择全部 # 行匹配项} other {选择全部 # 行匹配项}}"++msgid "{count, plural, one {Select all matching rows (about #)} other {Select all matching rows (about #)}}"+msgstr "{count, plural, one {选择全部匹配行(约 #)} other {选择全部匹配行(约 #)}}"+msgid "{count} of {total} units"msgstr "{count} / {total} 件"@@ -486,12 +510,6 @@ msgstr "{done}个/{total}个阶段已完成"msgid "{excluded, plural, one {# row excluded} other {# rows excluded}}"msgstr "{excluded, plural, one {# 行已排除} other {# 行已排除}}"-msgid "{from}–{to} of {count}"-msgstr "{from}–{to} 共 {count}"--msgid "{from}–{to} of {count} operations"-msgstr "第{from}–{to}个工序(共{count}个)"-msgid "{hidden, plural, one {And # more record.} other {And # more records.}}"msgstr "{hidden, plural, one {还有 # 条记录。} other {还有 # 条记录。}}"@@ -515,6 +533,12 @@ msgstr "{linesCount, plural, one {# 行} other {# 行}}"msgid "{load} in queue"msgstr "{load} 在队列中"+msgid "{loadedLabel} of {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} / {total, plural, one {# 行} other {# 行}}"++msgid "{loadedLabel} of about {total, plural, one {# row} other {# rows}}"+msgstr "{loadedLabel} / 约 {total, plural, one {# 行} other {# 行}}"+msgid "{locationName} (the lease's)"msgstr "{locationName}(该租赁的地点)"@@ -607,6 +631,9 @@ msgstr "{scopeCount} 个权限"msgid "{sectionLineCount} lines"msgstr "{sectionLineCount} 行"+msgid "{selectedCount, plural, one {# selected} other {# selected}}"+msgstr "{selectedCount, plural, one {已选择 #} other {已选择 #}}"+msgid "{selectedCount} selected"msgstr "{selectedCount} 已选择"@@ -622,6 +649,9 @@ msgstr "{total}个阶段即可正式运行"msgid "{totalCount} results"msgstr "{totalCount} 个结果"+msgid "{totalLoaded} of {count}"+msgstr "{totalLoaded} / {count}"+msgid "{totalQuantity, plural, one {# unit} other {# units}}"msgstr "{totalQuantity, plural, one {# 件} other {# 件}}"@@ -2316,6 +2346,9 @@ msgstr "所有位置"msgid "all make {0}"msgstr "全部自制 {0}"+msgid "All matching rows selected"+msgstr "已选择全部匹配行"+msgid "All members of selected groups and selected individuals will be able to approve requests"msgstr "所选组的所有成员和所选个人都将能够审批请求"@@ -5959,6 +5992,9 @@ msgstr "无法完成 Onshape Government 连接"msgid "Couldn't load documents"msgstr "无法加载文档"+msgid "Couldn't load more rows"+msgstr "无法加载更多行"+msgid "Couldn't load related documents. Refresh before creating a new one to avoid duplicates."msgstr "无法加载相关文档。创建新文档前请刷新以避免重复。"@@ -7766,6 +7802,9 @@ msgstr "解散批次"msgid "Dissolve Batch"msgstr "解散批次"+msgid "Dissolve batches"+msgstr "解散生产批次"+#. placeholder {0}: batch.readableIdmsgid "Dissolving {0} returns its {memberCount} operations to the schedule un-run and deletes the batch. A batch with recorded production must be completed instead."msgstr "解散{0}会将其{memberCount}个操作返回到未运行的计划中,并删除该批次。包含已记录生产的批次必须改为完成。"@@ -9087,6 +9126,9 @@ msgstr "每一行都已成功导入。"msgid "Every unit has a rate."msgstr "每件都有费率。"+msgid "Every user that matches the list's filters. Users this action does not apply to are skipped."+msgstr "符合列表筛选条件的每个用户。本操作不适用的用户将被跳过。"+msgid "Everyone must set up an authenticator app before opening this company."msgstr "每个人在打开此公司之前都必须设置身份验证器应用程序。"@@ -9328,6 +9370,9 @@ msgstr "导出 CSV"msgid "Export Lines to CSV"msgstr "导出行到 CSV"+msgid "Exported the first {exportedCount} rows."+msgstr "已导出前 {exportedCount} 行。"+msgid "Extended Price"msgstr "扩展价格"@@ -9885,6 +9930,12 @@ msgstr "筛选和排序"msgid "Filter by…"msgstr "按…筛选"+msgid "Filter the list to {limit} rows or fewer"+msgstr "将列表筛选为不超过 {limit} 行"++msgid "Filter the list to {rows} rows or fewer"+msgstr "将列表筛选为不超过 {rows} 行"+msgid "Filters"msgstr "筛选"@@ -11509,7 +11560,7 @@ msgid "Invoice schedule"msgstr "发票日程表"msgid "Invoice Separately"-msgstr ""+msgstr "单独开票"msgid "Invoice settlement"msgstr "发票结算"@@ -11542,7 +11593,7 @@ msgid "Invoiced Amount:"msgstr "已开票金额:"msgid "Invoiced separately"-msgstr ""+msgstr "已单独开票"msgid "Invoiced Statuses"msgstr "已开票状态"@@ -12438,9 +12489,6 @@ msgstr "实时重新加载"msgid "Load"msgstr "负荷"-msgid "Load more"-msgstr "加载更多"-msgid "Load newer"msgstr "加载更新"@@ -12465,6 +12513,9 @@ msgstr "正在加载当前数量…"msgid "Loading item details..."msgstr "正在加载项目详情..."+msgid "Loading more rows"+msgstr "正在加载更多行"+msgid "Loading returnable lines..."msgstr "正在加载可退货行..."@@ -17123,7 +17174,7 @@ msgid "Push to accounting"msgstr "推送到会计系统"msgid "Put this charge on its own invoice, held for review before it is posted. Otherwise it goes on the agreement's next invoice."-msgstr ""+msgstr "将此费用单独开具发票,过账前需先评审。否则,该费用将计入协议的下一张发票。"msgid "Putting your data back"msgstr "正在恢复您的数据"@@ -17877,6 +17928,9 @@ msgstr "下达生产批次"msgid "Release batch {0}"msgstr "下达生产批次{0}"+msgid "Release batches"+msgstr "下达生产批次"+msgid "Release change notice"msgstr "下达变更通知"@@ -18451,9 +18505,6 @@ msgstr "结果"msgid "Results"msgstr "结果"-msgid "Results per page"-msgstr "每页结果数"-msgid "Resume"msgstr "恢复"@@ -18852,9 +18903,6 @@ msgstr "工艺路线"msgid "Routing Number (ABA)"msgstr "ABA路由号码"-msgid "rows"-msgstr "行"-msgid "Rows left out of this backup"msgstr "此备份中遗漏的行"@@ -18930,6 +18978,9 @@ msgstr "立即运行此工作流?"msgid "Running"msgstr "运行中"+msgid "Running in the background. We'll notify you when it's done."+msgstr "正在后台运行。完成后我们将通知您。"+msgid "Running inventory after each week's supply and demand — the line."msgstr "每周供应和需求后运行库存管理——这一行"@@ -19704,6 +19755,9 @@ msgstr "选择供应商类型"msgid "Select surfaces"msgstr "选择表面"+msgid "Select the first {limit} rows"+msgstr "选择前 {limit} 行"+msgid "Select the groups that should complete this training"msgstr "选择应该完成此培训的组"@@ -19967,7 +20021,7 @@ msgid "Set Up Accounting"msgstr "设置会计"msgid "Set up accounting to use reports, journal entries, accounting periods, depreciation runs and more."-msgstr ""+msgstr "设置会计后,即可使用报表、凭证、会计期间、折旧运行等功能。"msgid "Set up authenticator app"msgstr "设置身份验证器应用"@@ -20351,12 +20405,12 @@ msgstr "显示 {0} 个,共 {totalCount} 个 — 优化搜索"msgid "Showing {0} of {totalFiltered} — refine your search"msgstr "显示 {0} / {totalFiltered} — 优化您的搜索"-msgid "Showing {firstShown}–{lastShown} of {total}"-msgstr "显示 {firstShown}–{lastShown}(共 {total} 条)"-msgid "Showing in {parentCurrency}"msgstr "显示货币:{parentCurrency}"+msgid "Showing the first {limit} rows. Search or filter to see the rest."+msgstr "仅显示前 {limit} 行。请搜索或筛选以查看其余行。"+msgid "Showing the first 500 lines"msgstr "显示前500行"@@ -22000,6 +22054,9 @@ msgstr "此物料产出在生产期间预期丢失的百分比;计划将需求msgid "The expense account this indirect-spend line posts to; required because indirect lines don't have an item ledger entry to derive the account from."msgstr "此间接支出行过账至的费用科目;因为间接行没有物料分类账条目来推导科目,所以这是必需的。"+msgid "The export could not start. Try again."+msgstr "无法开始导出。请重试。"+msgid "The file you uploaded and the mappings you've made will be lost."msgstr "您上传的文件和已完成的映射将会丢失。"@@ -22182,6 +22239,9 @@ msgstr "此客户的生命周期状态——启用、潜在客户、已停用等msgid "The lifecycle state of this supplier — Active, Inactive, Pending Approval, etc.; only Active suppliers appear in PO / quote selectors."msgstr "此供应商的生命周期状态 — 启用、已停用、待批准等;仅启用的供应商出现在采购订单/报价单选择器中。"+msgid "The list changed while the export loaded. Try again."+msgstr "导出加载期间列表已发生变化。请重试。"+msgid "The local timezone this location reports time in; schedules, timecards, and shift hours at this location are interpreted in this zone regardless of the user's browser locale."msgstr "此地点报告时间所在的本地时区;此地点的排程、工时记录和班次小时数在此时区中解释,无论用户的浏览器区域设置如何。"@@ -24140,6 +24200,9 @@ msgstr "更新采购订单数量"msgid "Updated"msgstr "已更新"+msgid "Updated {done}. Could not update {failed}: {message}"+msgstr "已更新 {done}。无法更新 {failed}:{message}"+msgid "Updated account"msgstr "已更新账户"@@ -25632,6 +25695,9 @@ msgstr "您的 DNS 提供商可能会自动将您的域追加到记录名称中msgid "Your Email"msgstr "你的电子邮件"+msgid "Your export is being prepared. We'll notify you when it's ready."+msgstr "正在准备您的导出文件。准备就绪后我们将通知您。"+msgid "Your general-ledger accounts and their structure"msgstr "您的总账账户及其结构"diff --git a/packages/notifications/src/index.ts b/packages/notifications/src/index.tsindex e8363f5247..3210251351 100644--- a/packages/notifications/src/index.ts+++ b/packages/notifications/src/index.ts@@ -57,6 +57,16 @@ export enum NotificationEvent {SalesRuleViolation = "sales-rule-violation",StockTransferAssignment = "stock-transfer-assignment",SuggestionResponse = "suggestion-response",+ // A background table export finished, failed, or was refused. Payload-carried+ // like IntegrationSync: the text arrives as `title` / `body`. documentId is the+ // export id (the file is `{companyId}/exports/{userId}/{exportId}.csv` in+ // temp-staging, served to that user only by the ERP's export route), or+ // `failed:{exportId}` when there is no file.+ TableExport = "table-export",+ // A background bulk action finished, failed, or was refused. Payload-carried+ // like TableExport: the outcome and the counts arrive as `title` / `body`.+ // documentId is the run id, or `failed:{runId}`; neither is a record.+ TableBulkAction = "table-bulk-action",// Weekly digest reminder for outstanding trainings (documentIds-shaped).TrainingReminder = "training-reminder",SupplierQuoteAssignment = "supplier-quote-assignment",@@ -230,6 +240,8 @@ export function getNotificationTopic(// exhaustive Record<NotificationTopic, string>.case NotificationEvent.Workflow:case NotificationEvent.IntegrationSync:+ case NotificationEvent.TableExport:+ case NotificationEvent.TableBulkAction:return NotificationTopic.General;default:return NotificationTopic.General;@@ -316,6 +328,10 @@ export function getNotificationEmailHeading(event: NotificationEvent): string {return "Workflow";case NotificationEvent.IntegrationSync:return "Accounting sync needs attention";+ case NotificationEvent.TableExport:+ return "Your export";+ case NotificationEvent.TableBulkAction:+ return "Your bulk action";case NotificationEvent.RecurringInvoicing:return "Recurring invoicing summary";case NotificationEvent.LeaseCriticalDate:@@ -358,6 +374,10 @@ export function getNotificationEmailCtaLabel(event: NotificationEvent): string {return "View details";case NotificationEvent.IntegrationSync:return "View sync activity";+ case NotificationEvent.TableExport:+ return "Download export";+ case NotificationEvent.TableBulkAction:+ return "View details";case NotificationEvent.RecurringInvoicing:return "Review invoices";case NotificationEvent.LeaseCriticalDate: