Skip to content

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.

Merge remote-tracking branch 'origin/main' into feat/infinite-scroll

aashu66808407c846
diff --cc .claude/rules/database-patterns.md
index 6a4194dae4,76ec631f6c..e1a7bd9c1a
--- a/.claude/rules/database-patterns.md
+++ b/.claude/rules/database-patterns.md
@@@ -108,8 -108,8 +108,8 @@@ Conventions (see also `conventions-serv
- Always scope list queries by `companyId` (`.eq("companyId", companyId)`) — defense in depth even though RLS also enforces it.
- List endpoints take `GenericQueryFilters` and run through `setGenericQueryFilters(query, args, [...])` (`~/utils/query`) for search/sort/pagination.
-- Count/select for list endpoints: prefer `{ count: LIST_COUNT }` (`LIST_COUNT = "estimated"`, `~/utils/query`) over `count: "exact"`. `exact` is `COUNT(*) OVER ()`, which materializes the whole filtered set just to produce a total the UI shows approximately anyway — on 500k `trackedEntity` rows that is 652 ms vs 1.5 ms. `estimated` is a hybrid: PostgREST still returns an exact count below its threshold, so small tenants see no change. Currently used by the ten view-backed endpoints plus `getJobs` and `getTrackedEntities`.
-- The ten endpoints backed by the big multi-join **views** (`parts`, `materials`, `tools`, `consumables`, `services`, `purchaseOrders`, `quotes`, `salesOrders`, `purchaseInvoices`, `salesInvoices`) additionally select an explicit `*_LIST_COLUMNS` constant instead of `select("*")`, so Postgres can prune the views' unreferenced computed columns. Adding a column to one of those tables means adding it to the constant — the `list-select-covers-columns` check (`@carbon/checks`) fails if an `accessorKey` is missing (a new constant needs a `LIST_TABLES` entry there), because the CSV export reads accessors untyped. The rationale lives once on `LIST_COUNT` in `apps/erp/app/utils/query.ts`, not at each constant.
+- Count/select for list endpoints: prefer `{ count: LIST_COUNT }` (`LIST_COUNT = "estimated"`, `~/utils/query`) over `count: "exact"` (a paged list counts with `listCount(args)`, which asks for `exact` only in the Table's separate count request; see `table-infinite-scroll.md`). `exact` is `COUNT(*) OVER ()`, which materializes the whole filtered set just to produce a total the UI shows approximately anyway — on 500k `trackedEntity` rows that is 652 ms vs 1.5 ms. `estimated` is a hybrid: PostgREST still returns an exact count below its threshold, so small tenants see no change. Currently used by the ten view-backed endpoints plus `getJobs` and `getTrackedEntities`.
- - The ten endpoints backed by the big multi-join **views** (`parts`, `materials`, `tools`, `consumables`, `services`, `purchaseOrders`, `quotes`, `salesOrders`, `purchaseInvoices`, `salesInvoices`) additionally select an explicit `*_LIST_COLUMNS` constant instead of `select("*")`, so Postgres can prune the views' unreferenced computed columns. Adding a column to one of those tables means adding it to the constant — `apps/erp/test/list-select-columns.test.ts` fails if an `accessorKey` is missing, because the CSV export reads accessors untyped. The rationale lives once on `LIST_COUNT` in `apps/erp/app/utils/query.ts`, not at each constant.
++- The ten endpoints backed by the big multi-join **views** (`parts`, `materials`, `tools`, `consumables`, `services`, `purchaseOrders`, `quotes`, `salesOrders`, `purchaseInvoices`, `salesInvoices`) additionally select an explicit `*_LIST_COLUMNS` constant instead of `select("*")`, so Postgres can prune the views' unreferenced computed columns. Adding a column to one of those tables means adding it to the constant — the `list-select-covers-columns` check (`@carbon/checks`) fails if an `accessorKey` is missing (a new constant needs a `LIST_TABLES` entry there), because the CSV export reads accessors untyped. The same check fails a constant that drops a sort or id column of its `X_PAGING`, which the cursor reads from each page's last row. The rationale lives once on `LIST_COUNT` in `apps/erp/app/utils/query.ts`, not at each constant.
- Use `sanitize(...)` (re-exported from `@carbon/utils`) to strip empty values before insert/update.
- Upserts are done either with a manual `id ? update : insert` branch or supabase's native `.upsert(...)`; both are in use.
- `fetchAllFromTable(client, table, columns, qb)` (from `@carbon/database`) pages through large result sets:
diff --cc .claude/rules/table-infinite-scroll.md
index 444c31fb09,0000000000..e5928b109f
mode 100644,000000..100644
--- a/.claude/rules/table-infinite-scroll.md
+++ b/.claude/rules/table-infinite-scroll.md
@@@ -1,362 -1,0 +1,356 @@@
+---
+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.
+
+## The row count
+
+The header shows the number of matching rows ("2,345 rows"), exact at any size.
+
+1. Page 1 asks for `LIST_COUNT` (`estimated`). PostgREST counts exactly below
+ 1,000 rows. From 1,000 rows up it gives the planner's estimate, because an
+ exact count (`COUNT(*) OVER ()`) reads every matching row.
+2. From 1,000 up, `useExactCount` (`components/Table/useExactCount.ts`) loads
+ the list route with `count=exact` in place of `after` (`getCountUrl`),
+ after page 1 shows and again after each revalidation. The rows never wait
+ for the count.
+3. `getGenericQueryFilters` reads `count=exact` as `exactCount: true` (and no
+ cursor). `listCount(args)` then asks for `exact`, and
+ `setGenericQueryFilters` reads one row (`.limit(1)`).
+4. `loadListPage` answers that request with the count only: no `firstPage`,
+ no `mapRows`, `{ [dataKey]: [], count, exactCount: true }`. A loader that
+ calls `fetchListPage` itself returns `exactCount: page.exactCount`.
+5. Until the answer comes, the copy says "about" (header, phone footer,
+ select-all bar). A failed request keeps the estimate.
+
+Only a list with `listKey` asks, and only an answer with `exactCount: true`
+counts. A loader that builds its own args from `getGenericQueryFilters`
+(`{ limit, cursor, sorts, filters }`) drops `exactCount`, so its count stays
+the estimate rather than showing an estimate as exact.
+
+## 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.
+ A later page that throws (not a `Response`) is caught and answered the same
+ way: a fetcher whose loader throws replaces the list with the route's error
+ screen.
+- 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: it
- parses every `.tsx` with the TypeScript compiler and fails on an infinite
- `<Table>` whose `data` is a `.map`/`.filter`/`.slice`/`.concat`/`.toSorted`
- call or a `[...x]` spread, inline or in a variable.
++ on every render. Nothing checks this automatically.
+- 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: listCount(args) })
+ .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 |
+|---|---|
+| Count with `listCount(args)` | `LIST_COUNT` on page 1, no count on a later page (`fetchListPage` returns 0), `exact` for the count request (see "The row count"). |
+| 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 page-1 count is exact ("245 rows"). From it, `LIST_COUNT` is an estimate: "about N rows" until `useExactCount` gets the exact count |
+| 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. With all
+ `MAX_RUNNING_TABLE_JOBS` (4) slots across companies taken it refuses
+ (`refusal: { code: "full" }`, see `table-csv-export.md`).
+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, and at most
+ `MAX_RUNNING_TABLE_JOBS` (4) across all companies; a request past that is
+ refused with a toast, not queued. While Redis is down the lock fails open
+ and neither limit holds there (Inngest still runs one per company). A
+ separate worker service removes this limit.
+- 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`.
++`packages/jobs/src/table-jobs/*.test.ts`. The `list-select-covers-columns`
++check (`@carbon/checks`) fails when a table's `accessorKey`, or its paging's
++sort or id column, is missing from its `*_LIST_COLUMNS`.
diff --cc apps/erp/app/components/Table/components/Compact/CompactToolbar.tsx
index 5a78d523c9,b6a6bdc75e..1b97ae8904
--- a/apps/erp/app/components/Table/components/Compact/CompactToolbar.tsx
+++ b/apps/erp/app/components/Table/components/Compact/CompactToolbar.tsx
@@@ -221,3 -208,20 +208,20 @@@ export function CompactToolbar(
</>
);
}
+
+ /**
+ * Export CSV, mounted only when there is something to export. Its hook reads
+ * the signed-in company's items, suppliers, people and customers to name the
+ * ids in the file, and a signed-out page — a customer portal — has no company
+ * to read: called unconditionally, it threw "useUser must be used within an
+ * authenticated route" and the page answered 500.
+ */
+ function ExportCsvItem({ csvExport }: { csvExport: DownloadProps }) {
- const exportCsv = useCsvDownload(csvExport);
++ const { onClick: exportCsv } = useCsvDownload(csvExport);
+ return (
+ <DropdownMenuItem onClick={exportCsv}>
+ <DropdownMenuIcon icon={<LuDownload />} />
+ <Trans>Export CSV</Trans>
+ </DropdownMenuItem>
+ );
+ }
diff --cc apps/erp/app/modules/accounting/accounting.service.ts
index 5585b651da,7529d4b023..dfa25f993f
--- a/apps/erp/app/modules/accounting/accounting.service.ts
+++ b/apps/erp/app/modules/accounting/accounting.service.ts
@@@ -220,12 -220,12 +220,17 @@@ import
} from "~/modules/invoicing/invoicing.service";
import { getOnRentLineForAsset } from "~/modules/sales/sales.service";
import { getNextSequence } from "~/modules/settings/settings.service";
-import type { GenericQueryFilters } from "~/utils/query";
+import type { Cursor } from "~/utils/cursor";
+import { decodeCursor, toPage } from "~/utils/cursor";
+import { listErrorPage } from "~/utils/list-registry/list-error";
+import { PAGE_SIZE } from "~/utils/pagination";
+import type { GenericQueryFilters, Paging } from "~/utils/query";
- import { LIST_COUNT, listCount, setGenericQueryFilters } from "~/utils/query";
+ import {
+ LIST_COUNT,
++ listCount,
+ setGenericQueryFilters,
+ setSearchFilter
+ } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import {
allocateJournalLineIds,
@@@ -460,55 -456,90 +470,119 @@@ function accountLedgerQuery
} 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;
- };
+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;
}
+ // The general ledger report reads the lines of Posted and Reversed journals
+ // only — the lines the trial balance sums. The `journalLines` view filters the
+ // same statuses; the report states them so it holds if the view changes.
+ const GENERAL_LEDGER_LINE_COLUMNS =
+ "id, journalId, journalEntryId, postingDate, status, sourceType, journalDescription, description, amount, accountId, documentType, account(number, name, class)";
+
+ type GeneralLedgerArgs = Pick<GenericQueryFilters, "sorts" | "filters"> & {
+ search: string | null;
+ startDate: string;
+ endDate: string;
+ };
+
++export const GENERAL_LEDGER_PAGING: Paging = {
++ defaultSorts: [
++ { column: "postingDate", ascending: true },
++ { column: "journalEntryId", ascending: true }
++ ]
++};
++
+ function generalLedgerLinesQuery(
+ client: SupabaseClient<Database>,
+ companyId: string,
- args: GeneralLedgerArgs,
- withCount: boolean
++ args: GeneralLedgerArgs &
++ Partial<Pick<GenericQueryFilters, "limit" | "cursor">>,
++ count: ReturnType<typeof listCount>
+ ) {
+ let query = client
+ .from("journalLines")
- .select(
- GENERAL_LEDGER_LINE_COLUMNS,
- withCount ? { count: LIST_COUNT } : undefined
- )
++ .select(GENERAL_LEDGER_LINE_COLUMNS, count ? { count } : undefined)
+ .eq("companyId", companyId)
+ .in("status", [...GL_JOURNAL_STATUSES])
+ .gte("postingDate", args.startDate)
+ .lte("postingDate", args.endDate);
+
+ query = setSearchFilter(query, args.search, [
+ "journalEntryId",
+ "description",
+ "journalDescription"
+ ]);
+
- query = setGenericQueryFilters(
- query,
- { sorts: args.sorts, filters: args.filters },
- [
- { column: "postingDate", ascending: true },
- { column: "journalEntryId", ascending: true }
- ]
- );
-
- // A unique tie-break keeps pages (and the CSV's batches) stable
- return query.order("id", { ascending: true });
++ // The id breaks ties, so pages (and the CSV's batches) are stable
++ return setGenericQueryFilters(query, args, GENERAL_LEDGER_PAGING);
+ }
+
++/** One cursor page of the report (`limit + 1` rows for `toPage`). */
+ export async function getGeneralLedgerLines(
+ client: SupabaseClient<Database>,
+ companyId: string,
- args: GeneralLedgerArgs & Pick<GenericQueryFilters, "limit" | "offset">
++ args: GeneralLedgerArgs & Pick<GenericQueryFilters, "limit" | "cursor">
+ ) {
- return generalLedgerLinesQuery(client, companyId, args, true).range(
- args.offset,
- args.offset + args.limit - 1
- );
++ return generalLedgerLinesQuery(client, companyId, args, listCount(args));
+ }
+
+ /** Every line of the report, past PostgREST's row cap — for the CSV export. */
+ export async function getAllGeneralLedgerLines(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args: GeneralLedgerArgs
+ ) {
+ return fetchAll<GeneralLedgerLine>(() =>
- generalLedgerLinesQuery(client, companyId, args, false)
++ generalLedgerLinesQuery(client, companyId, args, undefined)
+ );
+ }
+
export async function getAccountLedgerSummary(
client: SupabaseClient<Database>,
companyGroupId: string,
diff --cc apps/erp/app/modules/accounting/ui/Reports/GeneralLedgerTable.tsx
index 0000000000,77c3cfc926..33138e312d
mode 000000,100644..100644
--- a/apps/erp/app/modules/accounting/ui/Reports/GeneralLedgerTable.tsx
+++ b/apps/erp/app/modules/accounting/ui/Reports/GeneralLedgerTable.tsx
@@@ -1,0 -1,208 +1,217 @@@
+ // 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 { HStack } from "@carbon/react";
+ import { toDisplayCredit, toDisplayDebit } from "@carbon/utils";
+ import { useLingui } from "@lingui/react/macro";
+ import type { ColumnDef } from "@tanstack/react-table";
+ import { memo, useMemo } from "react";
+ import {
+ LuBookmark,
+ LuCalendar,
+ LuCircleDollarSign,
+ LuFileText,
+ LuLandmark,
+ LuTag
+ } from "react-icons/lu";
+ import { DateTime, Hyperlink, Table } from "~/components";
+ import { Enumerable } from "~/components/Enumerable";
+ import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";
+ import { path } from "~/utils/path";
+ import {
+ journalEntrySourceTypes,
+ journalLineDocumentType
+ } from "../../accounting.models";
+ import type { AccountClass, GeneralLedgerLine } from "../../types";
+ import JournalEntryStatus from "../JournalEntries/JournalEntryStatus";
+
+ type GeneralLedgerTableProps = {
+ data: GeneralLedgerLine[];
+ count: number;
++ // The loader's cursor for the next page (infinite scroll).
++ nextCursor: string | null;
+ accounts: { id: string; number: string | null; name: string | null }[];
+ currencyCode: string;
+ };
+
+ const defaultColumnVisibility = {
+ documentType: false
+ };
+
+ function accountLabel(line: GeneralLedgerLine) {
+ return [line.account?.number, line.account?.name].filter(Boolean).join(" ");
+ }
+
+ // `amount` is signed by the account's natural balance, so debit and credit
+ // depend on the account's class
+ function debitOf(line: GeneralLedgerLine) {
+ return toDisplayDebit(
+ line.amount ?? 0,
+ (line.account?.class ?? "Asset") as AccountClass
+ );
+ }
+
+ function creditOf(line: GeneralLedgerLine) {
+ return toDisplayCredit(
+ line.amount ?? 0,
+ (line.account?.class ?? "Asset") as AccountClass
+ );
+ }
+
+ const GeneralLedgerTable = memo(
- ({ data, count, accounts, currencyCode }: GeneralLedgerTableProps) => {
++ ({
++ data,
++ count,
++ nextCursor,
++ accounts,
++ currencyCode
++ }: GeneralLedgerTableProps) => {
+ const { t } = useLingui();
+ const currencyFormatter = useCurrencyFormatter({ currency: currencyCode });
+
+ const columns = useMemo<ColumnDef<GeneralLedgerLine>[]>(
+ () => [
+ {
+ accessorKey: "postingDate",
+ header: t`Date`,
+ cell: ({ row }) => (
+ <DateTime value={row.original.postingDate} variant="date" />
+ ),
+ meta: {
+ mobile: "P2",
+ icon: <LuCalendar />
+ }
+ },
+ {
+ accessorKey: "journalEntryId",
+ header: t`Journal Entry`,
+ cell: ({ row }) => (
+ <HStack spacing={2}>
+ <Hyperlink
+ to={path.to.journalEntryDetails(row.original.journalId!)}
+ >
+ {row.original.journalEntryId}
+ </Hyperlink>
+ {row.original.status !== "Posted" && row.original.status && (
+ <JournalEntryStatus status={row.original.status} />
+ )}
+ </HStack>
+ ),
+ meta: {
+ mobile: "P1",
+ icon: <LuBookmark />
+ }
+ },
+ {
+ accessorKey: "accountId",
+ header: t`Account`,
+ cell: ({ row }) => accountLabel(row.original) || "—",
+ meta: {
+ mobile: "P3",
+ icon: <LuLandmark />,
+ sortBy: "account.number",
+ exportValue: accountLabel,
+ filter: {
+ type: "static",
+ isArray: true,
+ options: accounts.map((account) => ({
+ label: [account.number, account.name].filter(Boolean).join(" "),
+ value: account.id
+ }))
+ }
+ }
+ },
+ {
+ accessorKey: "description",
+ header: t`Description`,
+ cell: ({ row }) => (
+ <span className="line-clamp-1 max-w-[320px]">
+ {row.original.description ??
+ row.original.journalDescription ??
+ "—"}
+ </span>
+ ),
+ meta: {
+ icon: <LuFileText />,
+ exportValue: (row) =>
+ row.description ?? row.journalDescription ?? null
+ }
+ },
+ {
+ accessorKey: "sourceType",
+ header: t`Source`,
+ cell: ({ row }) => <Enumerable value={row.original.sourceType} />,
+ meta: {
+ icon: <LuTag />,
+ filter: {
+ type: "static",
+ isArray: true,
+ options: journalEntrySourceTypes.map((v) => ({
+ label: <Enumerable value={v} />,
+ value: v
+ }))
+ }
+ }
+ },
+ {
+ accessorKey: "documentType",
+ header: t`Document Type`,
+ cell: ({ row }) => <Enumerable value={row.original.documentType} />,
+ meta: {
+ icon: <LuTag />,
+ filter: {
+ type: "static",
+ isArray: true,
+ options: journalLineDocumentType.map((v) => ({
+ label: <Enumerable value={v} />,
+ value: v
+ }))
+ }
+ }
+ },
+ {
+ id: "debit",
+ header: t`Debit`,
+ cell: ({ row }) => {
+ const debit = debitOf(row.original);
+ return debit !== 0 ? currencyFormatter.format(debit) : "";
+ },
+ meta: {
+ icon: <LuCircleDollarSign />,
+ exportValue: debitOf
+ }
+ },
+ {
+ id: "credit",
+ header: t`Credit`,
+ cell: ({ row }) => {
+ const credit = creditOf(row.original);
+ return credit !== 0 ? currencyFormatter.format(credit) : "";
+ },
+ meta: {
+ icon: <LuCircleDollarSign />,
+ exportValue: creditOf
+ }
+ }
+ ],
+ [accounts, currencyFormatter, t]
+ );
+
+ return (
+ <Table<GeneralLedgerLine>
+ data={data}
+ columns={columns}
+ count={count}
++ infinite={{ dataKey: "lines", nextCursor }}
+ defaultColumnVisibility={defaultColumnVisibility}
+ title={t`General Ledger`}
+ // The page's Download exports every line of the period, not one page
+ withCsvExport={false}
+ />
+ );
+ }
+ );
+
+ GeneralLedgerTable.displayName = "GeneralLedgerTable";
+ export default GeneralLedgerTable;
diff --cc apps/erp/app/modules/invoicing/invoicing.service.ts
index e2614147f1,00eba63995..bbbe877d4b
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@@ -210,9 -210,8 +210,8 @@@ import
syncDraftRecognitionRuns
} from "~/modules/shared/shared.service";
import { getUser } from "~/modules/users/users.service";
-import type { GenericQueryFilters } from "~/utils/query";
-import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";
+import type { GenericQueryFilters, Paging } from "~/utils/query";
+import { listCount, setGenericQueryFilters } from "~/utils/query";
- import { stripSpecialCharacters } from "~/utils/string";
import { sanitize } from "~/utils/supabase";
import { getExchangeRate } from "../accounting/accounting.service";
import { getEmployeeJob } from "../people/people.service";
diff --cc apps/erp/app/modules/production/production.models.test.ts
index d721d6383e,cc27064c4b..8689b53a25
--- a/apps/erp/app/modules/production/production.models.test.ts
+++ b/apps/erp/app/modules/production/production.models.test.ts
@@@ -2,59 -2,53 +2,86 @@@
// 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 {
+ import { describe, expect, it } from "vitest";
-import { assemblyInstructionStepValidator } from "./production.models";
++import {
++ assemblyInstructionStepValidator,
+ isBatchDissolvable,
+ isBatchReleasable,
+ isJobBulkDeletable,
+ isJobBulkReleasable,
+ jobStatus
- } = await import("./production.models");
++} from "./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"]);
+ });
+});
+
+ // An assembly instruction List step needs at least one option, like the bill of
+ // process steps (shared.models.test.ts). Blank rows are dropped first, so the
+ // empty row "Add option" leaves behind never blocks a save and is never stored.
+ describe("assemblyInstructionStepValidator list options", () => {
+ const listStep = (listValues?: string[]) => ({
+ assemblyInstructionId: "ai1",
+ title: "Pick a finish",
+ type: "List" as const,
+ listValues
+ });
+
+ const listValuesError = (listValues?: string[]) => {
+ const result = assemblyInstructionStepValidator.safeParse(
+ listStep(listValues)
+ );
+ if (result.success) return undefined;
+ return result.error.issues.find(
+ (issue) => issue.path.join(".") === "listValues"
+ )?.message;
+ };
+
+ it("requires at least one option", () => {
+ expect(listValuesError(undefined)).toBe("List options are required");
+ expect(listValuesError([])).toBe("List options are required");
+ });
+
+ it("treats a list of blank rows as no options", () => {
+ expect(listValuesError(["", " "])).toBe("List options are required");
+ });
+
+ it("drops a trailing empty row instead of refusing the save", () => {
+ const result = assemblyInstructionStepValidator.safeParse(
+ listStep(["Matte", "Gloss", ""])
+ );
+ expect(result.success).toBe(true);
+ expect(result.data?.listValues).toEqual(["Matte", "Gloss"]);
+ });
+
+ it("does not require options on other step types", () => {
+ expect(
+ assemblyInstructionStepValidator.safeParse({
+ ...listStep(),
+ type: "Task"
+ }).success
+ ).toBe(true);
+ });
+ });
diff --cc apps/erp/app/modules/production/production.service.ts
index 4051e49fde,68cf542183..fb08937e23
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@@ -2102,10 -2083,20 +2110,24 @@@ export async function getJobOperationsB
.order("order", { ascending: true });
}
+export const JOB_OPERATION_STEP_RECORDS_PAGING: Paging = {
+ defaultSorts: [{ column: "createdAt", ascending: false }]
+};
+
+ /** `getJobOperationsByMethodId` for several make methods of one company. */
+ export async function getJobOperationsByMethodIds(
+ client: SupabaseClient<Database>,
+ jobMakeMethodIds: string[],
+ companyId: string
+ ) {
+ return client
+ .from("jobOperation")
+ .select(JOB_OPERATION_DETAIL_COLUMNS)
+ .in("jobMakeMethodId", jobMakeMethodIds)
+ .eq("companyId", companyId)
+ .order("order", { ascending: true });
+ }
+
export async function getJobOperationStepRecords(
client: SupabaseClient<Database>,
jobId: string,
diff --cc apps/erp/app/modules/purchasing/purchasing.models.test.ts
index 64a0c667f3,8ab3083d14..9c4407a2aa
--- a/apps/erp/app/modules/purchasing/purchasing.models.test.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.test.ts
@@@ -2,29 -2,11 +2,12 @@@
// 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";
-
- // @carbon/content/glossary's terms.ts evaluates Lingui `msg` macros at module load,
- // which vitest doesn't transform. Nothing under test touches the glossary
- // (it's pulled in via the ../shared barrel), so stub the whole package.
- vi.mock("@carbon/content/glossary", () => ({
- getDefinitionText: () => "",
- getEntry: () => undefined,
- getTermText: () => "",
- glossaryEntries: () => [],
- hasEntry: () => false,
- listEntries: () => [],
- lookupEntry: () => undefined,
- termSlug: (t: string) => t,
- terms: {}
- }));
-
- import * as purchasingModels from "./purchasing.models";
+ import { describe, expect, it } from "vitest";
+
import {
canCreatePurchaseOrderRevision,
+ isPurchaseOrderBulkDeletable,
isPurchaseOrderLocked,
- leaseClassificationValidator,
leaseDetailsValidator,
leaseDurationOf,
leaseEndDate,
diff --cc apps/erp/app/modules/purchasing/purchasing.service.ts
index b9f6278506,5acaff3989..5959e5f9ab
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@@ -118,14 -120,9 +121,13 @@@ import
getCompanySettings
} from "~/modules/settings/settings.service";
import { getUser } from "~/modules/users/users.service";
+import {
+ type BulkDeleteResult,
+ bulkDeleteByStatus
+} from "~/utils/bulk-delete.server";
import { path } from "~/utils/path";
-import type { GenericQueryFilters } from "~/utils/query";
-import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";
+import type { GenericQueryFilters, Paging } from "~/utils/query";
+import { listCount, setGenericQueryFilters } from "~/utils/query";
- import { stripSpecialCharacters } from "~/utils/string";
import { sanitize } from "~/utils/supabase";
import {
getCurrencyByCode,
diff --cc apps/erp/app/modules/sales/sales.service.ts
index ff6b9f7bca,dc284439cb..19ab7429de
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@@ -149,9 -153,8 +153,8 @@@ import
} from "~/modules/shared/shared.service";
import { getUser } from "~/modules/users/users.service";
import { path } from "~/utils/path";
-import type { GenericQueryFilters } from "~/utils/query";
-import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";
+import type { GenericQueryFilters, Paging } from "~/utils/query";
+import { LIST_COUNT, listCount, setGenericQueryFilters } from "~/utils/query";
- import { stripSpecialCharacters } from "~/utils/string";
import { sanitize } from "~/utils/supabase";
import {
getCurrencyByCode,
diff --cc apps/erp/app/modules/users/users.service.ts
index 9f99844866,5c17f7bf53..04c059c462
--- a/apps/erp/app/modules/users/users.service.ts
+++ b/apps/erp/app/modules/users/users.service.ts
@@@ -41,12 -41,18 +42,18 @@@ import { batchTrigger } from "@carbon/j
import { redis } from "@carbon/kv";
import { sendEmail } from "@carbon/lib/email.server";
import { getLogger } from "@carbon/logger";
- import type { NotificationPreferenceChannel } from "@carbon/notifications";
- import { chunkArray, datetime, getClientIp } from "@carbon/utils";
+ import {
+ isNotificationTopic,
+ type NotificationPreferenceChannel,
+ type NotificationTopic,
+ notificationPreferenceCompanyId
+ } from "@carbon/notifications";
+ import { updateSubscriptionQuantityForCompany } from "@carbon/stripe/stripe.server";
-import { datetime, Edition, getClientIp } from "@carbon/utils";
++import { chunkArray, datetime, Edition, getClientIp } from "@carbon/utils";
import { now, parseAbsolute } from "@internationalized/date";
- import { render } from "@react-email/components";
import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
+ import { render } from "react-email";
import type { z } from "zod";
import { getAttribute } from "~/modules/people/people.service";
import { getSupplierContact } from "~/modules/purchasing/purchasing.service";
diff --cc apps/erp/app/routes/share+/customer.$id.tsx
index 30276c651c,1768be4a0a..566891b10d
--- a/apps/erp/app/routes/share+/customer.$id.tsx
+++ b/apps/erp/app/routes/share+/customer.$id.tsx
@@@ -393,8 -390,10 +393,11 @@@ export default function CustomerPortal(
data={salesOrderLines}
columns={columns}
count={count ?? 0}
+ isTruncated={isTruncated}
compact
+ // Signed out: the export names ids from the signed-in company's
+ // lists, and there is no company here to read them from.
+ withCsvExport={false}
defaultColumnPinning={defaultColumnPinning}
sort={<PortalSort columns={sortableColumns} />}
/>
diff --cc apps/erp/app/routes/x+/reports+/general-ledger.server.ts
index 0000000000,d772dfb8e2..bcc0090524
mode 000000,100644..100644
--- a/apps/erp/app/routes/x+/reports+/general-ledger.server.ts
+++ b/apps/erp/app/routes/x+/reports+/general-ledger.server.ts
@@@ -1,0 -1,106 +1,106 @@@
+ // 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 general ledger page and its CSV download read the same lines, so they
+ // share the request's parsing: the company, the period and the table's search,
+ // filters and sorts.
+
+ 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 { datetime, defaultReportRange, redirect } from "@carbon/utils";
+ import { financialReportParamsValidator } from "~/modules/accounting/accounting.models";
+ import {
+ getCompaniesInGroup,
+ getFiscalYearSettings
+ } from "~/modules/accounting/accounting.service";
+ import { months } from "~/modules/shared/shared.models";
+ import { getCompanyTimeZone } from "~/modules/shared/shared.service";
+ import { path } from "~/utils/path";
+ import { getGenericQueryFilters } from "~/utils/query";
+
+ const logger = getLogger("erp", "reports-general-ledger");
+
+ export async function resolveGeneralLedgerRequest(request: Request) {
+ const { client, companyId, companyGroupId } = await requirePermissions(
+ request,
+ {
+ view: "accounting",
+ role: "employee"
+ }
+ );
+
+ const url = new URL(request.url);
+ const searchParams = url.searchParams;
+ // Invalid params fall back to defaults — a bad bookmark must not 500
+ const parsed = financialReportParamsValidator.safeParse(
+ Object.fromEntries(searchParams.entries())
+ );
+ const companiesParam = parsed.success
+ ? (parsed.data.companies ?? null)
+ : null;
+ const startDateParam = parsed.success
+ ? (parsed.data.startDate ?? null)
+ : null;
+ const endDateParam = parsed.success ? (parsed.data.endDate ?? null) : null;
+
+ const [companies, fiscalYearSettings] = await Promise.all([
+ getCompaniesInGroup(client, companyGroupId),
+ getFiscalYearSettings(client, companyId)
+ ]);
+ if (companies.error) {
+ throw redirect(
+ path.to.reports,
+ await flash(
+ request,
+ error(companies.error, "Failed to load report companies")
+ )
+ );
+ }
+ const companiesList = companies.data ?? [];
+
+ // One company at a time: each company's lines are in its own base currency,
+ // so a list across companies would add unlike amounts.
+ const selectedCompanyId =
+ companiesParam && companiesParam !== "all" ? companiesParam : companyId;
+ const selectedCompany = companiesList.find(
+ (company) => company.id === selectedCompanyId
+ );
+ if (!selectedCompany) {
+ logger.error("General ledger company is not in the caller's group", {
+ companyGroupId,
+ selectedCompanyId
+ });
+ throw new Response("The company could not be found.", { status: 404 });
+ }
+
+ // The same default window as the trial balance, so a drill from one to the
+ // other reads the same lines
+ const range = defaultReportRange(
+ endDateParam ??
+ datetime.today(await getCompanyTimeZone(client, companyId)).toString()
+ );
+
- const { limit, offset, sorts, filters } =
++ const { limit, cursor, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ return {
+ client,
+ companies: companiesList,
+ selectedCompany,
+ fiscalStartMonth:
+ months.indexOf(fiscalYearSettings.data?.startMonth ?? "January") + 1,
+ companyGroupId,
+ query: {
+ search: searchParams.get("search"),
+ startDate: startDateParam ?? range.startDate,
+ endDate: endDateParam ?? range.endDate,
+ sorts,
+ filters
+ },
+ limit,
- offset
++ cursor
+ };
+ }
diff --cc apps/erp/app/routes/x+/reports+/general-ledger.tsx
index 0000000000,39898de68e..d158ea9ea8
mode 000000,100644..100644
--- a/apps/erp/app/routes/x+/reports+/general-ledger.tsx
+++ b/apps/erp/app/routes/x+/reports+/general-ledger.tsx
@@@ -1,0 -1,109 +1,131 @@@
+ // 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 { flash } from "@carbon/auth/session.server";
++import { getLogger } from "@carbon/logger";
+ import { VStack } from "@carbon/react";
+ import { redirect } from "@carbon/utils";
+ import { msg } from "@lingui/core/macro";
+ import type { LoaderFunctionArgs } from "react-router";
+ import { useLoaderData, useLocation } from "react-router";
+ import {
++ GENERAL_LEDGER_PAGING,
+ getAccountsList,
+ getGeneralLedgerLines
+ } from "~/modules/accounting/accounting.service";
+ import {
+ GeneralLedgerTable,
+ ReportFilters
+ } from "~/modules/accounting/ui/Reports";
++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 { resolveGeneralLedgerRequest } from "./general-ledger.server";
+
++const logger = getLogger("erp", "reports-general-ledger");
++
+ export const handle: Handle = {
+ breadcrumb: msg`General Ledger`,
+ to: path.to.generalLedger
+ };
+
+ export async function loader({ request }: LoaderFunctionArgs) {
+ const {
+ client,
+ companies,
+ selectedCompany,
+ fiscalStartMonth,
+ companyGroupId,
+ query,
+ limit,
- offset
++ cursor
+ } = await resolveGeneralLedgerRequest(request);
+
+ const [lines, accounts] = await Promise.all([
+ getGeneralLedgerLines(client, selectedCompany.id, {
+ ...query,
+ limit,
- offset
++ cursor
+ }),
+ getAccountsList(client, companyGroupId, { isGroup: false })
+ ]);
+
++ if (lines.error && cursor) {
++ logger.error("Failed to load a later page of the general ledger", {
++ companyId: selectedCompany.id,
++ error: lines.error
++ });
++ return listErrorPage("lines");
++ }
++
+ if (lines.error) {
+ throw redirect(
+ path.to.reports,
+ await flash(request, error(lines.error, "Failed to load general ledger"))
+ );
+ }
+
++ const page = toPage(
++ lines.data ?? [],
++ { limit, sorts: query.sorts },
++ GENERAL_LEDGER_PAGING
++ );
++
+ return {
- lines: lines.data ?? [],
++ lines: page.rows,
+ count: lines.count ?? 0,
++ nextCursor: page.nextCursor,
+ accounts: accounts.data ?? [],
+ companies,
+ selectedCompanyId: selectedCompany.id,
+ currencyCode: selectedCompany.baseCurrencyCode,
+ fiscalStartMonth
+ };
+ }
+
+ export default function GeneralLedgerRoute() {
+ const {
+ lines,
+ count,
++ nextCursor,
+ accounts,
+ companies,
+ selectedCompanyId,
+ currencyCode,
+ fiscalStartMonth
+ } = useLoaderData<typeof loader>();
+ const { search } = useLocation();
+
+ const onDownload = () => {
+ const params = new URLSearchParams(search);
- params.delete("limit");
- params.delete("offset");
++ params.delete("after");
+ const query = params.toString();
+ window.location.assign(
+ query ? `${path.to.generalLedgerCsv}?${query}` : path.to.generalLedgerCsv
+ );
+ };
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <ReportFilters
+ companies={companies}
+ selectedCompanyIds={[selectedCompanyId]}
+ isMultiCompany={false}
+ allowAllCompanies={false}
+ fiscalStartMonth={fiscalStartMonth}
+ showSearch={false}
+ onDownload={onDownload}
+ />
+ <GeneralLedgerTable
+ data={lines}
+ count={count}
++ nextCursor={nextCursor}
+ accounts={accounts}
+ currencyCode={currencyCode}
+ />
+ </VStack>
+ );
+ }
diff --cc apps/erp/app/utils/query.test.ts
index b3529768bb,73045e931e..29c0633b0c
--- a/apps/erp/app/utils/query.test.ts
+++ b/apps/erp/app/utils/query.test.ts
@@@ -3,30 -3,14 +3,19 @@@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { describe, expect, it, vi } from "vitest";
-
- // @carbon/auth's barrel export pulls in @carbon/content/glossary, whose Lingui `msg`
- // macro isn't transformed under plain vitest (no lingui plugin configured for
- // apps/erp tests). Mock it the same way traceability.search.test.ts does -
- // getSearchTokens/setSearchFilter don't call badRequest or
- // parseNumberFromUrlParam, so the mock only needs to satisfy the import.
- vi.mock("@carbon/auth", () => ({
- badRequest: vi.fn(),
- parseNumberFromUrlParam: vi.fn()
- }));
-
- const { encodeCursor } = await import("./cursor");
- const {
++import { encodeCursor } from "./cursor";
+ import {
formatRangeFilter,
+ getEffectiveSorts,
getGenericFilter,
getGenericQueryFilters,
getSearchTokens,
+ LIST_COUNT,
+ listCount,
parseRangeFilter,
+ setGenericQueryFilters,
setSearchFilter
- } = await import("./query");
+ } from "./query";
describe("getSearchTokens", () => {
it("splits a multi-word search into tokens", () => {
diff --cc apps/erp/test/planning-action-scope.test.ts
index 99fed088f3,f0ca20bef4..2415e33110
--- a/apps/erp/test/planning-action-scope.test.ts
+++ b/apps/erp/test/planning-action-scope.test.ts
@@@ -7,17 -7,15 +7,16 @@@ import
actionsOfTypes,
PLANNING_ACTIONS_COLUMN,
PLANNING_ASSIGNEE_COLUMN,
- resolvePlanningActionScope
+ resolvePlanningActionScope,
+ withPlanningActions
} from "../app/modules/production/ui/Planning/planning-action-scope";
+ const partFilter = { column: "type", operator: "eq", value: "Part" };
+
describe("resolvePlanningActionScope", () => {
- it("passes the grid's own filters through untouched and restricts nothing", () => {
- const filters = [{ column: "type", operator: "eq", value: "Part" }];
- expect(
- resolvePlanningActionScope({ filters })
- ).toEqual({
- gridFilters: filters,
+ it("passes the grid's own filters through and restricts nothing", () => {
+ expect(resolvePlanningActionScope({ filters: [partFilter] })).toEqual({
+ gridFilters: [partFilter],
actionTypes: undefined,
actionAssignees: undefined
});
@@@ -121,47 -72,18 +73,39 @@@ describe("actionsOfTypes", () =>
{ id: "d", type: "Cancel" }
] as const;
- it("shows every action when the grid is not filtered by type", () => {
- expect(actionsOfTypes(actions, undefined)).toEqual([...actions]);
- expect(actionsOfTypes(actions, null)).toEqual([...actions]);
- expect(actionsOfTypes(actions, [])).toEqual([...actions]);
- });
-
- it("keeps only the filtered type, in the original order", () => {
- expect(actionsOfTypes(actions, ["Expedite"]).map((a) => a.id)).toEqual([
- "a",
- "c"
- ]);
- });
-
- it("keeps any of several filtered types", () => {
- expect(
- actionsOfTypes(actions, ["Cancel", "Defer"]).map((a) => a.id)
- ).toEqual(["b", "d"]);
- });
+ it.each([undefined, null, []])(
+ "shows every action when the type filter is %j",
+ (types) => {
+ expect(actionsOfTypes(actions, types)).toEqual([...actions]);
+ }
+ );
- it("returns nothing when the row has no action of the filtered type", () => {
- expect(actionsOfTypes(actions, ["Order"])).toEqual([]);
+ it.each([
+ [["Expedite"], ["a", "c"]],
+ [["Cancel", "Defer"], ["b", "d"]],
+ [["Order"], []]
+ ])("keeps only actions of %j, in the original order", (types, ids) => {
+ expect(actionsOfTypes(actions, types).map((a) => a.id)).toEqual(ids);
});
});
+
+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 --cc packages/checks/src/conformance/list-select-covers-columns.test.ts
index 0000000000,c10e792dd5..63c75e5a49
mode 000000,100644..100644
--- a/packages/checks/src/conformance/list-select-covers-columns.test.ts
+++ b/packages/checks/src/conformance/list-select-covers-columns.test.ts
@@@ -1,0 -1,82 +1,153 @@@
+ // 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 {
+ findUnselectedListColumns,
+ LIST_TABLES
+ } from "./list-select-covers-columns";
+
+ const PARTS_TABLE = LIST_TABLES.PARTS_LIST_COLUMNS as string;
+
-const service = (constants: Record<string, string>) => ({
++const ID_PAGING = `{ defaultSorts: [{ column: "id", ascending: true }] }`;
++
++// Each constant with an `X_PAGING` beside it; `paging` overrides its body.
++const service = (
++ constants: Record<string, string>,
++ paging: Record<string, string> = {}
++) => ({
+ file: "apps/erp/app/modules/items/items.service.ts",
+ contents: Object.entries(constants)
- .map(([name, list]) => `const ${name} =\n "${list}" as const;`)
++ .map(([name, list]) => {
++ const pagingName = name.replace(/_LIST_COLUMNS$/, "_PAGING");
++ const body = paging[pagingName] ?? ID_PAGING;
++ return `const ${name} =\n "${list}" as const;\nexport const ${pagingName}: Paging = ${body};`;
++ })
+ .join("\n")
+ });
+
+ const table = (body: string) => ({ file: PARTS_TABLE, contents: body });
+
+ // Every other mapped constant, defined and with an empty table, so a case
+ // only reports what it is about.
+ const others = () => {
+ const rest = Object.entries(LIST_TABLES).filter(
+ ([name]) => name !== "PARTS_LIST_COLUMNS"
+ );
+ return {
+ services: [service(Object.fromEntries(rest.map(([name]) => [name, "id"])))],
+ tables: rest.map(([, file]) => ({ file, contents: "" }))
+ };
+ };
+
+ const snippets = (partsList: string | null, partsTable: string) => {
+ const { services, tables } = others();
+ const constants: Record<string, string> =
+ partsList === null ? {} : { PARTS_LIST_COLUMNS: partsList };
+ return findUnselectedListColumns(
+ [...services, service(constants)],
+ [...tables, table(partsTable)]
+ ).map((v) => v.snippet);
+ };
+
+ describe("findUnselectedListColumns", () => {
+ it("accepts a table whose accessorKeys are all selected", () => {
+ expect(
+ snippets(
+ "id,name,customFields",
+ `accessorKey: "id", accessorKey: "name", accessorKey: "customFields->>abc", useCustomColumns`
+ )
+ ).toEqual([]);
+ });
+
+ it("flags an accessorKey the select dropped", () => {
+ expect(snippets("id", `accessorKey: "id", accessorKey: "mpn"`)).toEqual([
+ "PARTS_LIST_COLUMNS lacks mpn"
+ ]);
+ });
+
+ it("flags custom columns rendered without selecting customFields", () => {
+ expect(snippets("id", `accessorKey: "id", useCustomColumns`)).toEqual([
+ "PARTS_LIST_COLUMNS lacks customFields"
+ ]);
+ });
+
+ it("flags a new list constant with no table mapped", () => {
+ const { services, tables } = others();
+ expect(
+ findUnselectedListColumns(
+ [
+ ...services,
+ service({ PARTS_LIST_COLUMNS: "id", KITS_LIST_COLUMNS: "id" })
+ ],
+ [...tables, table("")]
+ ).map((v) => v.snippet)
+ ).toEqual(["KITS_LIST_COLUMNS"]);
+ });
+
+ it("flags a mapped constant that no service defines any more", () => {
+ expect(snippets(null, "")).toEqual(["PARTS_LIST_COLUMNS"]);
+ });
++
++ it("flags a sort or id column of X_PAGING the select dropped", () => {
++ const { services, tables } = others();
++ expect(
++ findUnselectedListColumns(
++ [
++ ...services,
++ service(
++ { PARTS_LIST_COLUMNS: "id,name" },
++ {
++ PARTS_PAGING: `{
++ defaultSorts: [
++ { column: "createdAt", ascending: false },
++ { column: "name", foreignTable: "supplier", ascending: true }
++ ],
++ idColumn: "readableIdWithRevision"
++ }`
++ }
++ )
++ ],
++ [...tables, table("")]
++ ).map((v) => v.snippet)
++ ).toEqual([
++ "PARTS_LIST_COLUMNS lacks cursor column createdAt",
++ "PARTS_LIST_COLUMNS lacks cursor column readableIdWithRevision"
++ ]);
++ });
++
++ it("flags a list constant with no X_PAGING beside it", () => {
++ const { services, tables } = others();
++ expect(
++ findUnselectedListColumns(
++ [
++ ...services,
++ {
++ file: "apps/erp/app/modules/items/items.service.ts",
++ contents: `const PARTS_LIST_COLUMNS = "id" as const;`
++ }
++ ],
++ [...tables, table("")]
++ ).map((v) => v.snippet)
++ ).toEqual(["PARTS_LIST_COLUMNS has no PARTS_PAGING"]);
++ });
++
++ it("checks a sort-only list for its cursor columns but not its table", () => {
++ const { services, tables } = others();
++ expect(
++ findUnselectedListColumns(
++ [
++ ...services,
++ service(
++ { PARTS_LIST_COLUMNS: "id", FIXED_ASSETS_LIST_COLUMNS: "id" },
++ {
++ FIXED_ASSETS_PAGING: `{ defaultSorts: [{ column: "fixedAssetId", ascending: true }] }`
++ }
++ )
++ ],
++ [...tables, table("")]
++ ).map((v) => v.snippet)
++ ).toEqual(["FIXED_ASSETS_LIST_COLUMNS lacks cursor column fixedAssetId"]);
++ });
+ });
diff --cc packages/checks/src/conformance/list-select-covers-columns.ts
index 0000000000,ac265b6453..911c15aee9
mode 000000,100644..100644
--- a/packages/checks/src/conformance/list-select-covers-columns.ts
+++ b/packages/checks/src/conformance/list-select-covers-columns.ts
@@@ -1,0 -1,106 +1,152 @@@
+ // 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 { SourceFile, Violation } from "../check";
+
+ export const LIST_SELECT_COVERS_COLUMNS = "list-select-covers-columns";
+
+ const UI = "apps/erp/app/modules";
+
+ /**
+ * The view-backed list endpoints select an explicit column list (so Postgres
+ * prunes the views' unused computed columns), and each list table exports the
+ * columns it declares. The narrowed select narrows the row type, but the CSV
+ * export (`Table/components/Download.tsx`) reads `row[accessorKey]` untyped:
+ * an accessorKey the select dropped exports blank, and nothing else fails.
+ *
+ * Each `*_LIST_COLUMNS` constant names the table that renders its rows.
+ * Not covered: `meta.exportValue` / `exportOnlyColumn` read arbitrary fields.
++ *
++ * Every constant must also select the columns its cursor reads: `toPage`
++ * reads each sort column of the list's `X_PAGING` and its id from the last
++ * row of a page, so a column missing from the select ends the list after
++ * page 1.
+ */
+ export const LIST_TABLES: Record<string, string> = {
+ PARTS_LIST_COLUMNS: `${UI}/items/ui/Parts/PartsTable.tsx`,
+ MATERIALS_LIST_COLUMNS: `${UI}/items/ui/Materials/MaterialsTable.tsx`,
+ TOOLS_LIST_COLUMNS: `${UI}/items/ui/Tools/ToolsTable.tsx`,
+ CONSUMABLES_LIST_COLUMNS: `${UI}/items/ui/Consumables/ConsumablesTable.tsx`,
+ SERVICES_LIST_COLUMNS: `${UI}/items/ui/Services/ServicesTable.tsx`,
+ PURCHASE_ORDERS_LIST_COLUMNS: `${UI}/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx`,
+ QUOTES_LIST_COLUMNS: `${UI}/sales/ui/Quotes/QuotesTable.tsx`,
+ SALES_ORDERS_LIST_COLUMNS: `${UI}/sales/ui/SalesOrder/SalesOrdersTable.tsx`,
+ PURCHASE_INVOICES_LIST_COLUMNS: `${UI}/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx`,
+ SALES_INVOICES_LIST_COLUMNS: `${UI}/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx`
+ };
+
++// Lists checked for their cursor columns only: their tables read embedded
++// records (`location.name`), not flat accessors.
++export const SORT_ONLY_LISTS = new Set(["FIXED_ASSETS_LIST_COLUMNS"]);
++
+ const LIST_CONSTANT = /const ([A-Z_]+_LIST_COLUMNS) =\s*"([^"]*)"/g;
+
++/** The list-order columns of an `X_PAGING` constant (embedded-table sorts
++ * excluded) and its id column, or null when the service has no such constant. */
++function pagingColumns(contents: string, paging: string): string[] | null {
++ const match = contents.match(
++ new RegExp(`export const ${paging}: Paging = \\{([\\s\\S]*?)\\};`)
++ );
++ if (!match) return null;
++ const body = match[1] ?? "";
++ const sorts = [...body.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 = body.match(/idColumn:\s*"([^"]+)"/)?.[1] ?? "id";
++ return [...sorts, idColumn];
++}
++
+ const lineAt = (contents: string, index = 0) =>
+ contents.slice(0, index).split("\n").length;
+
+ /** Every list table's accessorKeys against the columns its endpoint selects. */
+ export function findUnselectedListColumns(
+ services: SourceFile[],
+ tables: SourceFile[]
+ ): Violation[] {
+ const out: Violation[] = [];
+ const tableByFile = new Map(tables.map((t) => [t.file, t]));
+ const found = new Set<string>();
+
+ for (const service of services) {
+ for (const match of service.contents.matchAll(LIST_CONSTANT)) {
+ const [, constant = "", list = ""] = match;
+ found.add(constant);
++ const selected = new Set(list.split(","));
++ const paging = `${constant.replace(/_LIST_COLUMNS$/, "")}_PAGING`;
++ const cursorColumns = pagingColumns(service.contents, paging);
++ if (!cursorColumns) {
++ out.push({
++ file: service.file,
++ line: lineAt(service.contents, match.index),
++ snippet: `${constant} has no ${paging}`,
++ message: `${paging} not found beside ${constant}, so its cursor columns cannot be checked`
++ });
++ }
++ for (const column of cursorColumns ?? []) {
++ if (selected.has(column)) continue;
++ out.push({
++ file: service.file,
++ line: lineAt(service.contents, match.index),
++ snippet: `${constant} lacks cursor column ${column}`,
++ message: `${paging} sorts or pages on "${column}" but ${constant} does not select it, so the list ends after page 1`
++ });
++ }
++ if (SORT_ONLY_LISTS.has(constant)) continue;
+ const tablePath = LIST_TABLES[constant];
+ const table = tablePath ? tableByFile.get(tablePath) : undefined;
+ if (!table) {
+ out.push({
+ file: service.file,
+ line: lineAt(service.contents, match.index),
+ snippet: constant,
+ message: tablePath
+ ? `${tablePath} not found; update LIST_TABLES in list-select-covers-columns.ts`
+ : `Add ${constant} and the table that renders it to LIST_TABLES in list-select-covers-columns.ts`
+ });
+ continue;
+ }
- const selected = new Set(list.split(","));
+ for (const key of table.contents.matchAll(/accessorKey:\s*"([^"]+)"/g)) {
+ const column = key[1] ?? "";
+ // Custom-field columns are keyed `customFields->>{id}`; the
+ // `customFields` column itself is what has to be selected.
+ if (column.startsWith("customFields->>") || selected.has(column))
+ continue;
+ out.push({
+ file: table.file,
+ line: lineAt(table.contents, key.index),
+ snippet: `${constant} lacks ${column}`,
+ message: `accessorKey "${column}" is not in ${constant}, so it exports blank in the CSV download`
+ });
+ }
+ if (
+ table.contents.includes("useCustomColumns") &&
+ !selected.has("customFields")
+ ) {
+ out.push({
+ file: table.file,
+ line: lineAt(
+ table.contents,
+ table.contents.indexOf("useCustomColumns")
+ ),
+ snippet: `${constant} lacks customFields`,
+ message: `The table renders custom columns but ${constant} does not select customFields`
+ });
+ }
+ }
+ }
+
+ for (const constant of Object.keys(LIST_TABLES)) {
+ if (found.has(constant)) continue;
+ out.push({
+ file: "packages/checks/src/conformance/list-select-covers-columns.ts",
+ line: 0,
+ snippet: constant,
+ message: `${constant} is not defined in any module service; update LIST_TABLES`
+ });
+ }
+ return out;
+ }