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.

fix(tables): background release, delete, dissolve, item update and export run the same code as the screen, so the two paths cannot disagree

aashub7d0365b85ef
diff --git a/.claude/rules/table-csv-export.md b/.claude/rules/table-csv-export.md
index fb8ee1bffd..ac4bd12d74 100644
--- a/.claude/rules/table-csv-export.md
+++ b/.claude/rules/table-csv-export.md
@@ -145,8 +145,10 @@ list and re-read every loaded page. The steps:
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.
+3. `startTableJob("export", …)` (`utils/table-jobs.server.ts`, the bulk
+ actions' start path too) 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
@@ -244,14 +246,14 @@ Just render `<Table>` — the button comes for free. No `enableExport`-style pro
- 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.
+- A column whose value comes from a lookup the list's view lacks is the
+ registry entry's `rows`, which the loader and the export both run
+ (`exportListRows`, `utils/list-registry/index.server.ts`). A column whose
+ `meta.exportValue` computes from the row needs the same function in the
+ entry's `exportValues`. Jobs (Batches, Tracking), Batches (Jobs, Quantity,
+ Process, Work Center), Suppliers (contacts, addresses), Workflows (Last
+ Run) and Workflow Runs (Workflow, Record) have them. 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 different
diff --git a/.claude/rules/table-infinite-scroll.md b/.claude/rules/table-infinite-scroll.md
index 3fe7be5a33..6d01f98f3a 100644
--- a/.claude/rules/table-infinite-scroll.md
+++ b/.claude/rules/table-infinite-scroll.md
@@ -63,7 +63,7 @@ The header shows the number of matching rows ("2,345 rows"), exact at any size.
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
+ no `rows` lookup, `{ [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.
@@ -91,10 +91,10 @@ export async function loader({ request }: LoaderFunctionArgs) {
`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:
+user's company group, `firstPage` (page 1 only, in parallel), then the
+list's own `rows` lookup and `mapRows` (every page, after it). It returns
+`{ [dataKey]: rows, count, nextCursor, infinite, ...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.
@@ -105,17 +105,27 @@ search the query reads. On an error:
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).
+`fetchListPage` itself, returns `infinite: listInfinite(list, dataKey,
+nextCursor)` with page 1, 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>`:
+The table takes `infinite` (`InfiniteOptions`, `components/Table/types.ts`)
+as a prop from the loader data and passes it to `<Table>` as is. A table
+never types its list's `dataKey`, `listKey` or `idColumn`: `listInfinite`
+builds them from the registry entry, so they cannot drift from the server.
```tsx
-infinite={{ dataKey: "customers", nextCursor, listKey: "customers" }}
+// route
+const { customers, count, infinite } = useLoaderData<typeof loader>();
+<CustomersTable data={customers} count={count} infinite={infinite} />
+// table
+<Table data={data} count={count} infinite={infinite} columns={columns} />
```
+A table whose rows do not come from a registered list (an `api+` loader, a
+job page's tab) builds the object itself, without `listKey`.
+
| Option | Meaning |
|---|---|
| `dataKey` | The key of the rows array in the loader data. |
@@ -125,15 +135,17 @@ infinite={{ dataKey: "customers", nextCursor, listKey: "customers" }}
| `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.
+- Values from another table (a lookup the list's view lacks) are the
+ registry entry's `rows` (`withJobListExtras`, `withBatchListExtras`,
+ `withSupplierReportContacts`, `withWorkflowListExtras`,
+ `withWorkflowRunRecordNames`). `loadListPage` runs it on every page and the
+ background export on every part, so each page carries its own values, the
+ table keeps no merge state, and the export never has a blank column.
+ - A column whose `meta.exportValue` computes from the row gets the same
+ function in the entry's `exportValues` (`JOB_LIST_EXPORT_VALUES`, shared
+ with the column). The background export runs no column code.
+ - `mapRows` is for what only the screen needs (a download token per row,
+ Documents).
- 🛑 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
@@ -287,22 +299,28 @@ 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).
+Each bulk action is one entry of `BULK_ACTIONS` (`defineBulkAction`,
+`utils/table-jobs.server.ts`): its label, lists, permission, plan `feature`,
+`maxRows`, `idsPerStep`, the zod schema of the params its route sends, and
+`run`, which calls the route's own service function. Every bulk route calls
+`startBackgroundBulkAction(request, actionKey, { allMatching, ids }, params)`
+first: null means the route acts on the selection itself; otherwise it
+answers `bulkStartFormResponse(BulkActionStart)`. The steps:
+
+1. It checks the action's own permission (`requirePermissions` with the
+ entry's `permission`), that the action serves the list, the params
+ (the entry's schema; the job parses them again before `run`), and the
+ user's permission on the list (`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`).
+3. `startTableJob("bulk", …)` takes the company's bulk lock (the export's
+ start path too, with kind `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`). A
+ failed send gives the lock back.
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).
@@ -316,13 +334,19 @@ A bulk route that gets `allMatching` in place of ids calls
per call (`BULK_CHUNK_SIZE`). Each call gets the `carry` the call before
it returned and returns the next one. Jobs Release and Batches Release
carry the PO each supplier went on, so a later slice adds to the PO an
- earlier slice made (`bulkReleaseStartingPurchaseOrders`) instead of
- refusing the job or batch. Inside one call, `releaseBatches` passes the
- same map from batch to batch (`carriedPurchaseOrders`).
+ earlier slice made (`carriedPurchaseOrders` on `releaseJobs` and
+ `releaseBatches`, read by `startingPurchaseOrders`) instead of refusing
+ the job or batch. Inside one call, `releaseBatches` passes the same map
+ from batch to batch. Every slice calls the action route's own service
+ function (`releaseJobs`, `deleteJobs`, `deletePurchaseOrders`,
+ `releaseBatches`, `dissolveBatches`), so both paths apply one rule.
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.
+8. Steps `remove-ids` and `release-lock` delete the id folder
+ (`removeTableJobFolder`) and the lock. A failed run does the same in
+ `onFailure` (`failTableJob`, `table-jobs/failure.ts`, shared with the
+ export).
A step returns counts, cursors and the small `carry` only. The function adds
them up outside the steps. The browser side uses `appendBulkSelection` / `bulkSelectionBody`
@@ -331,10 +355,9 @@ them up outside the steps. The browser side uses `appendBulkSelection` / `bulkSe
**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.
+action's `idsPerStep` (25 jobs, 10 batches). A bigger selection goes to the
+same background job with its ids (`startBackgroundBulkAction` with `ids`),
+because each release runs MRP and the load balancer cuts a request at 600 s.
## Known limits
diff --git a/apps/erp/app/modules/accounting/ui/Dimensions/DimensionsTable.tsx b/apps/erp/app/modules/accounting/ui/Dimensions/DimensionsTable.tsx
index 2a93571251..758830e0c3 100644
--- a/apps/erp/app/modules/accounting/ui/Dimensions/DimensionsTable.tsx
+++ b/apps/erp/app/modules/accounting/ui/Dimensions/DimensionsTable.tsx
@@ -16,6 +16,7 @@ import {
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
import { dimensionEntityTypes } from "../../accounting.models";
@@ -24,12 +25,11 @@ import type { Dimension } from "../../types";
type DimensionsTableProps = {
data: Dimension[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const DimensionsTable = memo((props: DimensionsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -134,11 +134,7 @@ const DimensionsTable = memo((props: DimensionsTableProps) => {
return (
<Table<Dimension>
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "accounting-dimensions"
- }}
+ infinite={infinite}
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.tsx
index ad45f63a41..a402c203ff 100644
--- a/apps/erp/app/modules/accounting/ui/FixedAssets/AssetClassesTable.tsx
+++ b/apps/erp/app/modules/accounting/ui/FixedAssets/AssetClassesTable.tsx
@@ -23,6 +23,7 @@ import { useNavigate } from "react-router";
import { Hyperlink, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { path } from "~/utils/path";
import type { FixedAssetClassListItem } from "../../types";
@@ -30,8 +31,7 @@ import type { FixedAssetClassListItem } from "../../types";
type AssetClassesTableProps = {
data: FixedAssetClassListItem[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
taxDepreciationEnabled: boolean;
primaryAction?: ReactNode;
};
@@ -42,7 +42,7 @@ const AssetClassesTable = memo(
count,
taxDepreciationEnabled,
primaryAction,
- nextCursor
+ infinite
}: AssetClassesTableProps) => {
const { t } = useLingui();
const navigate = useNavigate();
@@ -153,11 +153,7 @@ const AssetClassesTable = memo(
return (
<>
<Table<FixedAssetClassListItem>
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "asset-classes"
- }}
+ infinite={infinite}
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.tsx
index 14aec54d49..44ae6fd50f 100644
--- a/apps/erp/app/modules/accounting/ui/FixedAssets/DepreciationRunTable.tsx
+++ b/apps/erp/app/modules/accounting/ui/FixedAssets/DepreciationRunTable.tsx
@@ -16,6 +16,7 @@ import { LuCalendar, LuEye, LuHash, LuStar, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { DateTime, Hyperlink, Table } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { path } from "~/utils/path";
import type { DepreciationRunListItem } from "../../types";
@@ -24,13 +25,12 @@ import DepreciationRunStatus from "./DepreciationRunStatus";
type DepreciationRunTableProps = {
data: DepreciationRunListItem[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
primaryAction?: ReactNode;
};
const DepreciationRunTable = memo(
- ({ data, count, primaryAction, nextCursor }: DepreciationRunTableProps) => {
+ ({ data, count, primaryAction, infinite }: DepreciationRunTableProps) => {
const { t } = useLingui();
const navigate = useNavigate();
const permissions = usePermissions();
@@ -128,11 +128,7 @@ const DepreciationRunTable = memo(
return (
<>
<Table<DepreciationRunListItem>
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "depreciation-runs"
- }}
+ infinite={infinite}
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.tsx
index c3e038396d..e8d22d2820 100644
--- a/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetsTable.tsx
+++ b/apps/erp/app/modules/accounting/ui/FixedAssets/FixedAssetsTable.tsx
@@ -28,6 +28,7 @@ import { Hyperlink, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUser } from "~/hooks";
import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";
import { path } from "~/utils/path";
@@ -41,8 +42,7 @@ import FixedAssetStatus from "./FixedAssetStatus";
type FixedAssetsTableProps = {
data: FixedAssetListItem[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
assetClasses: { id: string; name: string }[];
primaryAction?: ReactNode;
};
@@ -53,7 +53,7 @@ const FixedAssetsTable = memo(
count,
assetClasses,
primaryAction,
- nextCursor
+ infinite
}: FixedAssetsTableProps) => {
const { t } = useLingui();
const navigate = useNavigate();
@@ -226,11 +226,7 @@ const FixedAssetsTable = memo(
return (
<>
<Table<FixedAssetListItem>
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "fixed-assets"
- }}
+ infinite={infinite}
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.tsx
index 60dc838a5d..a576eb7223 100644
--- a/apps/erp/app/modules/accounting/ui/FixedAssets/FleetAssetsTable.tsx
+++ b/apps/erp/app/modules/accounting/ui/FixedAssets/FleetAssetsTable.tsx
@@ -24,6 +24,7 @@ import {
import { useFetcher, useNavigate } from "react-router";
import { Hyperlink, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUser } from "~/hooks";
import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";
import { path } from "~/utils/path";
@@ -38,8 +39,7 @@ export type FleetAssetRow = NonNullable<
type FleetAssetsTableProps = {
data: FleetAssetRow[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
primaryAction?: ReactNode;
};
@@ -49,7 +49,7 @@ const isOnBooks = (row: FleetAssetRow) =>
row.status === "Active" || row.status === "Fully Depreciated";
const FleetAssetsTable = memo(
- ({ data, count, primaryAction, nextCursor }: FleetAssetsTableProps) => {
+ ({ data, count, primaryAction, infinite }: FleetAssetsTableProps) => {
const { t } = useLingui();
const navigate = useNavigate();
const fetcher = useFetcher();
@@ -231,11 +231,7 @@ const FleetAssetsTable = memo(
return (
<Table<FleetAssetRow>
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "fleet-assets"
- }}
+ infinite={infinite}
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.tsx
index 66a9da81f4..ef4e39bbcf 100644
--- a/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionTable.tsx
+++ b/apps/erp/app/modules/accounting/ui/Intercompany/IntercompanyTransactionTable.tsx
@@ -15,6 +15,7 @@ import {
LuStar
} from "react-icons/lu";
import { DateTime, Table } from "~/components";
+import type { InfiniteOptions } from "~/components/Table";
import { useCurrencyDecimalsLookup } from "~/hooks";
import { intercompanyTransactionStatuses } from "../../accounting.models";
import IntercompanyTransactionStatus from "./IntercompanyTransactionStatus";
@@ -36,8 +37,7 @@ type IntercompanyTransaction = {
type IntercompanyTransactionTableProps = {
data: IntercompanyTransaction[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
primaryAction?: ReactNode;
};
@@ -46,7 +46,7 @@ const IntercompanyTransactionTable = memo(
data,
count,
primaryAction,
- nextCursor
+ infinite
}: IntercompanyTransactionTableProps) => {
const { t } = useLingui();
// Currency varies per row, so the formatter is built per cell from the
@@ -143,11 +143,7 @@ const IntercompanyTransactionTable = memo(
return (
<Table<IntercompanyTransaction>
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "intercompany-transactions"
- }}
+ infinite={infinite}
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.tsx
index 36a14bb0b5..1db642f12f 100644
--- a/apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntriesTable.tsx
+++ b/apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntriesTable.tsx
@@ -29,6 +29,7 @@ import { DateTime, EmployeeAvatar, Hyperlink, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { JournalEntrySourceTypeIcon } from "~/components/Icons";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUser } from "~/hooks";
import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";
import { usePeople } from "~/stores/people";
@@ -43,8 +44,7 @@ import JournalEntryStatus from "./JournalEntryStatus";
type JournalEntriesTableProps = {
data: JournalEntryListItem[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
primaryAction?: ReactNode;
};
@@ -57,7 +57,7 @@ const defaultColumnVisibility = {
};
const JournalEntriesTable = memo(
- ({ data, count, primaryAction, nextCursor }: JournalEntriesTableProps) => {
+ ({ data, count, primaryAction, infinite }: JournalEntriesTableProps) => {
const { t } = useLingui();
const navigate = useNavigate();
const permissions = usePermissions();
@@ -281,11 +281,7 @@ const JournalEntriesTable = memo(
return (
<>
<Table<JournalEntryListItem>
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "journal-entries"
- }}
+ infinite={infinite}
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.tsx
index c8d141a6f3..46d279a136 100644
--- a/apps/erp/app/modules/accounting/ui/PaymentTerms/PaymentTermsTable.tsx
+++ b/apps/erp/app/modules/accounting/ui/PaymentTerms/PaymentTermsTable.tsx
@@ -17,6 +17,7 @@ import {
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
@@ -26,12 +27,11 @@ import type { PaymentTerm } from "../../types";
type PaymentTermsTableProps = {
data: PaymentTerm[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const PaymentTermsTable = memo((props: PaymentTermsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -132,11 +132,7 @@ const PaymentTermsTable = memo((props: PaymentTermsTableProps) => {
return (
<Table<PaymentTerm>
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "payment-terms"
- }}
+ infinite={infinite}
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.tsx
index 21285051e2..6f93ff8677 100644
--- a/apps/erp/app/modules/accounting/ui/Projects/ProjectsTable.tsx
+++ b/apps/erp/app/modules/accounting/ui/Projects/ProjectsTable.tsx
@@ -14,6 +14,7 @@ import {
} from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
import type { Project } from "../../types";
@@ -21,12 +22,11 @@ import type { Project } from "../../types";
type ProjectsTableProps = {
data: Project[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const ProjectsTable = memo((props: ProjectsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -91,11 +91,7 @@ const ProjectsTable = memo((props: ProjectsTableProps) => {
return (
<Table<Project>
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "projects"
- }}
+ infinite={infinite}
data={data}
columns={columns}
count={count}
diff --git a/apps/erp/app/modules/accounting/ui/RevenueRecognition/PeriodRunsPage.tsx b/apps/erp/app/modules/accounting/ui/RevenueRecognition/PeriodRunsPage.tsx
index 1994ed2da1..f94e890ce2 100644
--- a/apps/erp/app/modules/accounting/ui/RevenueRecognition/PeriodRunsPage.tsx
+++ b/apps/erp/app/modules/accounting/ui/RevenueRecognition/PeriodRunsPage.tsx
@@ -21,6 +21,7 @@ import { useState } from "react";
import { LuCirclePlus } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Confirm } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import RevenueRecognitionRunsTable, {
type RevenueRecognitionRunListItem
@@ -32,8 +33,7 @@ type PeriodRunsPageProps = {
type: RunType;
data: RevenueRecognitionRunListItem[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
nextPeriodEnd: string;
hasDraftBlocking: boolean;
};
@@ -43,7 +43,7 @@ export default function PeriodRunsPage({
type,
data,
count,
- nextCursor,
+ infinite,
nextPeriodEnd,
hasDraftBlocking
}: PeriodRunsPageProps) {
@@ -69,7 +69,7 @@ export default function PeriodRunsPage({
type={type}
data={data}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
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.tsx
index 15f5085b6a..2769e5ae41 100644
--- a/apps/erp/app/modules/accounting/ui/RevenueRecognition/RevenueRecognitionRunsTable.tsx
+++ b/apps/erp/app/modules/accounting/ui/RevenueRecognition/RevenueRecognitionRunsTable.tsx
@@ -12,6 +12,7 @@ import { LuCalendar, LuEye, LuHash, LuStar, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { DateTime, Hyperlink, Table } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import type { getRevenueRecognitionRuns } from "~/modules/accounting/accounting.service";
import { path } from "~/utils/path";
@@ -27,8 +28,7 @@ type RevenueRecognitionRunsTableProps = {
type: RunType;
data: RevenueRecognitionRunListItem[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
primaryAction?: ReactNode;
};
@@ -38,7 +38,7 @@ const RevenueRecognitionRunsTable = memo(
data,
count,
primaryAction,
- nextCursor
+ infinite
}: RevenueRecognitionRunsTableProps) => {
const { t } = useLingui();
const navigate = useNavigate();
@@ -129,12 +129,7 @@ const RevenueRecognitionRunsTable = memo(
return (
<>
<Table<RevenueRecognitionRunListItem>
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey:
- type === "Lease" ? "lease-runs" : "revenue-recognition-runs"
- }}
+ infinite={infinite}
data={data}
columns={columns}
count={count}
diff --git a/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx b/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx
index ab333a0fe1..8c3fcdfedb 100644
--- a/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx
+++ b/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx
@@ -48,6 +48,7 @@ import { DateTime, EmployeeAvatar, Hyperlink, Table } from "~/components";
import DocumentIcon from "~/components/DocumentIcon";
import { Enumerable } from "~/components/Enumerable";
import { Confirm, ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import {
applyRowEdits,
type RowEdits,
@@ -68,22 +69,14 @@ 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;
+ // Its list is "documents", or "recent-documents" for the Recent view.
+ infinite: InfiniteOptions;
labels: DocumentLabel[];
extensions: (string | null)[];
};
const DocumentsTable = memo(
- ({
- data,
- count,
- nextCursor,
- listKey,
- labels,
- extensions
- }: DocumentsTableProps) => {
+ ({ data, count, infinite, labels, extensions }: DocumentsTableProps) => {
const { t } = useLingui();
const { isPhone } = useViewport();
const permissions = usePermissions();
@@ -93,7 +86,7 @@ const DocumentsTable = memo(
const infiniteRows = useInfiniteRows<Document>({
initialRows: data,
- infinite: { dataKey: "documents", nextCursor, listKey }
+ infinite
});
// 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`).
diff --git a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountsTable.tsx b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountsTable.tsx
index ee85170757..2f7757e42b 100644
--- a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCountsTable.tsx
@@ -25,6 +25,7 @@ import {
import { useNavigate } from "react-router";
import { DateTime, EmployeeAvatar, Hyperlink, New, Table } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import type { InventoryCount } from "~/modules/inventory/types";
import { InventoryCountStatus } from "~/modules/inventory/ui";
@@ -34,15 +35,14 @@ import { path } from "~/utils/path";
type InventoryCountsTableProps = {
data: InventoryCount[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
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, nextCursor, locations }: InventoryCountsTableProps) => {
+ ({ data, count, infinite, locations }: InventoryCountsTableProps) => {
const [params] = useUrlParams();
const { t } = useLingui();
const navigate = useNavigate();
@@ -197,11 +197,7 @@ const InventoryCountsTable = memo(
<>
<Table<InventoryCount>
data={data}
- infinite={{
- dataKey: "inventoryCounts",
- nextCursor,
- listKey: "inventory-counts"
- }}
+ infinite={infinite}
columns={columns}
count={count}
defaultColumnPinning={{ left: ["inventoryCountId"] }}
diff --git a/apps/erp/app/modules/inventory/ui/PickingLists/PickingListsTable.tsx b/apps/erp/app/modules/inventory/ui/PickingLists/PickingListsTable.tsx
index 6ebcad6e08..2a7a191065 100644
--- a/apps/erp/app/modules/inventory/ui/PickingLists/PickingListsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/PickingLists/PickingListsTable.tsx
@@ -26,6 +26,7 @@ import { Link, useNavigate } from "react-router";
import { DateTime, EmployeeAvatar, Hyperlink, Table } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
import { NewAction } from "~/components/New";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
import { pickingListStatusType } from "../../inventory.models";
@@ -52,12 +53,11 @@ export type PickingList = {
type PickingListsTableProps = {
data: PickingList[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const PickingListsTable = memo((props: PickingListsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const [params] = useUrlParams();
const { t } = useLingui();
const navigate = useNavigate();
@@ -220,11 +220,7 @@ const PickingListsTable = memo((props: PickingListsTableProps) => {
<>
<Table<PickingList>
data={data}
- infinite={{
- dataKey: "pickingLists",
- nextCursor,
- listKey: "picking-lists"
- }}
+ infinite={infinite}
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.tsx
index afe5e68f72..11312a513a 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptsTable.tsx
@@ -36,6 +36,7 @@ import {
import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
import { NewAction } from "~/components/New";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import {
@@ -75,12 +76,11 @@ function NewReceipt() {
type ReceiptsTableProps = {
data: Receipt[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const ReceiptsTable = memo((props: ReceiptsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
// The route's `handle.realtime` follows every receipt of the company, so
// the rows of a later page refresh too.
@@ -396,7 +396,7 @@ const ReceiptsTable = memo((props: ReceiptsTableProps) => {
<>
<Table<(typeof data)[number]>
data={data}
- infinite={{ dataKey: "receipts", nextCursor, listKey: "receipts" }}
+ infinite={infinite}
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.tsx
index b7adef778d..eb38848def 100644
--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentsTable.tsx
@@ -36,6 +36,7 @@ import {
import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
import { NewAction } from "~/components/New";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { useCustomers, usePeople } from "~/stores";
@@ -75,12 +76,11 @@ function NewShipment() {
type ShipmentsTableProps = {
data: Shipment[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const ShipmentsTable = memo((props: ShipmentsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
// The route's `handle.realtime` follows every shipment of the company, so
// the rows of a later page refresh too.
@@ -411,7 +411,7 @@ const ShipmentsTable = memo((props: ShipmentsTableProps) => {
<>
<Table<(typeof data)[number]>
data={data}
- infinite={{ dataKey: "shipments", nextCursor, listKey: "shipments" }}
+ infinite={infinite}
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.tsx
index 0b7fc53e45..a422462ceb 100644
--- a/apps/erp/app/modules/inventory/ui/ShippingMethods/ShippingMethodsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/ShippingMethods/ShippingMethodsTable.tsx
@@ -17,6 +17,7 @@ import {
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { shippingCarrierType } from "~/modules/inventory/inventory.models";
@@ -26,12 +27,11 @@ import { path } from "~/utils/path";
type ShippingMethodsTableProps = {
data: ShippingMethod[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const ShippingMethodsTable = memo(
- ({ data, count, nextCursor }: ShippingMethodsTableProps) => {
+ ({ data, count, infinite }: ShippingMethodsTableProps) => {
const [params] = useUrlParams();
const { t } = useLingui();
const navigate = useNavigate();
@@ -143,11 +143,7 @@ const ShippingMethodsTable = memo(
return (
<Table<(typeof data)[number]>
data={data}
- infinite={{
- dataKey: "shippingMethods",
- nextCursor,
- listKey: "shipping-methods"
- }}
+ infinite={infinite}
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.tsx
index 8454a62cec..4981f75ec0 100644
--- a/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx
@@ -39,6 +39,7 @@ import {
} from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { useDebouncedRealtime } from "~/hooks/useDebouncedRealtime";
import type { MethodItemType } from "~/modules/shared/types";
@@ -54,12 +55,11 @@ import StockMovementCorrectionModal from "./StockMovementCorrectionModal";
type StockMovementsTableProps = {
data: StockMovement[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const StockMovementsTable = memo(
- ({ data, count, nextCursor }: StockMovementsTableProps) => {
+ ({ data, count, infinite }: StockMovementsTableProps) => {
const { t } = useLingui();
const permissions = usePermissions();
const [correctionTarget, setCorrectionTarget] =
@@ -303,11 +303,7 @@ const StockMovementsTable = memo(
<>
<Table<(typeof data)[number]>
data={data}
- infinite={{
- dataKey: "movements",
- nextCursor,
- listKey: "stock-movements"
- }}
+ infinite={infinite}
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.tsx
index 72394a6b19..332caea73d 100644
--- a/apps/erp/app/modules/inventory/ui/StorageTypes/StorageTypesTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/StorageTypes/StorageTypesTable.tsx
@@ -11,6 +11,7 @@ import { LuPencil, LuTag, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
@@ -25,12 +26,11 @@ type StorageType = {
type StorageTypesTableProps = {
data: StorageType[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const StorageTypesTable = memo((props: StorageTypesTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -93,11 +93,7 @@ const StorageTypesTable = memo((props: StorageTypesTableProps) => {
return (
<Table<(typeof rows)[number]>
data={data}
- infinite={{
- dataKey: "storageTypes",
- nextCursor,
- listKey: "storage-types"
- }}
+ infinite={infinite}
columns={columns}
count={count}
importCSV={[
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsx b/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsx
index ad0cf4d596..efb323222d 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsx
@@ -23,6 +23,7 @@ import {
import { useNavigate } from "react-router";
import { Hyperlink, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { useDateFormatter, usePermissions } from "~/hooks";
import { trackedEntityStatus } from "~/modules/inventory/inventory.models";
import type { TrackedEntity } from "~/modules/inventory/types";
@@ -50,8 +51,7 @@ type TrackedEntityRow = TrackedEntity & {
type TrackedEntitiesTableProps = {
data: TrackedEntityRow[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
nearExpiryWarningDays: number | null;
};
@@ -59,7 +59,7 @@ const TrackedEntitiesTable = memo(
({
data,
count,
- nextCursor,
+ infinite,
nearExpiryWarningDays
}: TrackedEntitiesTableProps) => {
const navigate = useNavigate();
@@ -74,14 +74,6 @@ const TrackedEntitiesTable = memo(
// 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
);
diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransfersTable.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransfersTable.tsx
index 65ce956955..33ad858eec 100644
--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransfersTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransfersTable.tsx
@@ -24,6 +24,7 @@ import {
import { useNavigate } from "react-router";
import { DateTime, EmployeeAvatar, Hyperlink, New, Table } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { usePeople } from "~/stores";
@@ -35,14 +36,13 @@ import WarehouseTransferStatus from "./WarehouseTransferStatus";
type WarehouseTransfersTableProps = {
data: WarehouseTransfer[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
// 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, nextCursor }: WarehouseTransfersTableProps) => {
+ ({ data, count, infinite }: WarehouseTransfersTableProps) => {
const [params] = useUrlParams();
const { t } = useLingui();
const navigate = useNavigate();
@@ -253,11 +253,7 @@ const WarehouseTransfersTable = memo(
<>
<Table<(typeof data)[number]>
data={data}
- infinite={{
- dataKey: "warehouseTransfers",
- nextCursor,
- listKey: "warehouse-transfers"
- }}
+ infinite={infinite}
columns={columns}
count={count}
defaultColumnPinning={{
diff --git a/apps/erp/app/modules/invoicing/ui/Charge/ChargesTable.tsx b/apps/erp/app/modules/invoicing/ui/Charge/ChargesTable.tsx
index d69898a066..85d1c32a70 100644
--- a/apps/erp/app/modules/invoicing/ui/Charge/ChargesTable.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Charge/ChargesTable.tsx
@@ -19,6 +19,7 @@ import {
} from "react-icons/lu";
import { Hyperlink, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { useCurrencyDecimalsLookup } from "~/hooks";
import { path } from "~/utils/path";
import { chargeStatus, chargeType } from "../../invoicing.models";
@@ -29,12 +30,11 @@ 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;
+ infinite: InfiniteOptions;
};
const ChargesTable = memo((props: ChargesTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const { locale } = useLocale();
// Each transaction carries its own currencyCode (a company can hold cards in
@@ -140,11 +140,7 @@ const ChargesTable = memo((props: ChargesTableProps) => {
return (
<Table<ChargeRow>
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "charges"
- }}
+ infinite={infinite}
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.tsx
index d6baa4f853..d95ce25787 100644
--- a/apps/erp/app/modules/invoicing/ui/Memo/MemosTable.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Memo/MemosTable.tsx
@@ -34,6 +34,7 @@ import {
import { Enumerable } from "~/components/Enumerable";
import { useAccounts } from "~/components/Form/Account";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { useCurrencyFormatter, usePermissions } from "~/hooks";
import { useCustomers, useSuppliers } from "~/stores";
import { path } from "~/utils/path";
@@ -59,8 +60,7 @@ type MemoRow = {
type MemosTableProps = {
data: MemoRow[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
// 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.
@@ -68,7 +68,7 @@ type MemosTableProps = {
};
const MemosTable = memo((props: MemosTableProps) => {
- const { data, count, party, nextCursor } = props;
+ const { data, count, party, infinite } = props;
const { t } = useLingui();
const permissions = usePermissions();
const navigate = useNavigate();
@@ -245,11 +245,7 @@ const MemosTable = memo((props: MemosTableProps) => {
return (
<>
<Table<MemoRow>
- infinite={{
- dataKey: "memos",
- nextCursor,
- listKey: party === "customer" ? "credit-memos" : "supplier-credits"
- }}
+ infinite={infinite}
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.tsx
index 650980c3d5..c8b6b2442f 100644
--- a/apps/erp/app/modules/invoicing/ui/Payment/PaymentsTable.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentsTable.tsx
@@ -33,6 +33,7 @@ import {
} from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { useCurrencyFormatter, usePermissions } from "~/hooks";
import { useCustomers, useSuppliers } from "~/stores";
import { path } from "~/utils/path";
@@ -44,12 +45,11 @@ 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;
+ infinite: InfiniteOptions;
};
const PaymentsTable = memo((props: PaymentsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const permissions = usePermissions();
const navigate = useNavigate();
@@ -214,11 +214,7 @@ const PaymentsTable = memo((props: PaymentsTableProps) => {
return (
<>
<Table<PaymentRow>
- infinite={{
- dataKey: "payments",
- nextCursor,
- listKey: "payments"
- }}
+ infinite={infinite}
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.tsx
index 4d266be24d..9a531a0fb9 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx
@@ -36,6 +36,7 @@ import {
} from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { useCurrencyFormatter, usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { purchaseInvoiceStatusType } from "~/modules/invoicing/invoicing.models";
@@ -47,12 +48,11 @@ import { path } from "~/utils/path";
type PurchaseInvoicesTableProps = {
data: PurchaseInvoiceListItem[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const PurchaseInvoicesTable = memo(
- ({ data, count, nextCursor }: PurchaseInvoicesTableProps) => {
+ ({ data, count, infinite }: PurchaseInvoicesTableProps) => {
const { t } = useLingui();
const permissions = usePermissions();
const navigate = useNavigate();
@@ -346,11 +346,7 @@ const PurchaseInvoicesTable = memo(
count={count}
columns={columns}
data={data}
- infinite={{
- dataKey: "purchaseInvoices",
- nextCursor,
- listKey: "purchase-invoices"
- }}
+ infinite={infinite}
defaultColumnPinning={{
left: ["invoiceId"]
}}
diff --git a/apps/erp/app/modules/invoicing/ui/Reimbursement/ReimbursementsTable.tsx b/apps/erp/app/modules/invoicing/ui/Reimbursement/ReimbursementsTable.tsx
index c659c50710..aa1092a36e 100644
--- a/apps/erp/app/modules/invoicing/ui/Reimbursement/ReimbursementsTable.tsx
+++ b/apps/erp/app/modules/invoicing/ui/Reimbursement/ReimbursementsTable.tsx
@@ -18,6 +18,7 @@ import {
LuUser
} from "react-icons/lu";
import { EmployeeAvatar, Hyperlink, Table } from "~/components";
+import type { InfiniteOptions } from "~/components/Table";
import { useCurrencyDecimalsLookup } from "~/hooks";
import { usePeople } from "~/stores";
import { path } from "~/utils/path";
@@ -29,12 +30,11 @@ 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;
+ infinite: InfiniteOptions;
};
const ReimbursementsTable = memo(
- ({ data, count, nextCursor }: ReimbursementsTableProps) => {
+ ({ data, count, infinite }: ReimbursementsTableProps) => {
const { t } = useLingui();
const { locale } = useLocale();
// Each reimbursement carries its own currencyCode, so the amount is
@@ -137,11 +137,7 @@ const ReimbursementsTable = memo(
return (
<Table<ReimbursementRow>
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "reimbursements"
- }}
+ infinite={infinite}
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.tsx
index 61292df720..b69e34a03d 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx
@@ -39,6 +39,7 @@ import {
} from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { useCurrencyFormatter, usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { salesInvoiceStatusType } from "~/modules/invoicing/invoicing.models";
@@ -50,12 +51,11 @@ import SalesInvoiceStatus from "./SalesInvoiceStatus";
type SalesInvoicesTableProps = {
data: SalesInvoiceListItem[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const SalesInvoicesTable = memo((props: SalesInvoicesTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const permissions = usePermissions();
@@ -378,11 +378,7 @@ const SalesInvoicesTable = memo((props: SalesInvoicesTableProps) => {
count={count}
columns={columns}
data={data}
- infinite={{
- dataKey: "salesInvoices",
- nextCursor,
- listKey: "sales-invoices"
- }}
+ infinite={infinite}
defaultColumnPinning={{
left: ["invoiceId"]
}}
diff --git a/apps/erp/app/modules/items/items.models.ts b/apps/erp/app/modules/items/items.models.ts
index 1229aad18a..e8506cd1d8 100644
--- a/apps/erp/app/modules/items/items.models.ts
+++ b/apps/erp/app/modules/items/items.models.ts
@@ -82,6 +82,27 @@ export function isItemBulkUpdateField(
return itemBulkUpdateFields.some((allowed) => allowed === field);
}
+/** One field set on many items (the items tables' Update): the field and a
+ * value it takes. Any item group id, or none, is a value. */
+export const itemBulkUpdateValidator = z.discriminatedUnion("field", [
+ z.object({
+ field: z.literal("itemTrackingType"),
+ value: z.enum(itemTrackingTypes)
+ }),
+ z.object({
+ field: z.literal("replenishmentSystem"),
+ value: z.enum(itemReplenishmentSystems)
+ }),
+ z.object({
+ field: z.literal("defaultMethodType"),
+ value: z.enum(methodType)
+ }),
+ z.object({ field: z.literal("sourcingType"), value: z.enum(sourcingType) }),
+ z.object({ field: z.literal("itemPostingGroupId"), value: z.string() })
+]);
+
+export type ItemBulkUpdate = z.infer<typeof itemBulkUpdateValidator>;
+
// 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.server.ts b/apps/erp/app/modules/items/items.server.ts
index 8c322af40c..1b9b113e60 100644
--- a/apps/erp/app/modules/items/items.server.ts
+++ b/apps/erp/app/modules/items/items.server.ts
@@ -20,7 +20,12 @@ import { onShapeDataValidator } from "@carbon/ee/onshape";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
import { NotificationEvent } from "@carbon/notifications";
-import { datetime, isUniqueViolation, pluckUnique } from "@carbon/utils";
+import {
+ chunkArray,
+ datetime,
+ isUniqueViolation,
+ pluckUnique
+} from "@carbon/utils";
import { z } from "zod";
import { flattenTree } from "~/components/TreeView";
import { replanAfterItemChange } from "~/modules/production/production.server";
@@ -49,6 +54,7 @@ import {
changeNoticeValidator,
deriveItemMethodUpdate,
getMethodValidator,
+ itemBulkUpdateValidator,
itemManufacturingValidator,
itemPlanningValidator,
itemReplenishmentSystems,
@@ -335,6 +341,69 @@ export const setItemPostingGroup = defineServiceFn({
}
});
+/**
+ * Set one field on many items.
+ *
+ * @remarks
+ * The items tables' Update and its background job. 100 items at a time, each
+ * through the field's own operation (`setItemTrackingType`, `setItemSourcing`,
+ * `setItemPostingGroup`), so the value is checked and the cascades run as for
+ * one item. Ids that are not the company's items are skipped. A chunk commits
+ * on its own: when one fails, the chunks before it stay applied.
+ *
+ * @returns `done` (items updated) and `skipped` (ids that are not the company's items).
+ */
+export const updateItems = defineServiceFn({
+ input: z.object({ ids: itemIdsInput, change: itemBulkUpdateValidator }),
+ permission: { update: "parts" },
+
+ async run(ctx, { ids, change }) {
+ const unique = [...new Set(ids)];
+ let done = 0;
+ for (const chunk of chunkArray(unique, 100)) {
+ // The item group write inserts a cost row for each id, so keep only the
+ // company's own items.
+ const items = await ctx.asCaller.supabase
+ .from("item")
+ .select("id")
+ .in("id", chunk)
+ .eq("companyId", ctx.company.id);
+ if (items.error) {
+ return ctx.error("internal", "Failed to read the items", items.error);
+ }
+ const owned = items.data.map((item) => item.id);
+ if (owned.length === 0) continue;
+
+ const update =
+ change.field === "itemTrackingType"
+ ? await setItemTrackingType(ctx, {
+ ids: owned,
+ itemTrackingType: change.value
+ })
+ : change.field === "itemPostingGroupId"
+ ? await setItemPostingGroup(ctx, {
+ ids: owned,
+ itemPostingGroupId: change.value || null
+ })
+ : await setItemSourcing(ctx, {
+ ids: owned,
+ [change.field]: change.value
+ });
+ if (update.error) {
+ return done > 0
+ ? ctx.error(
+ "internal",
+ `Updated ${done} items, then the update failed: ${update.error.message}`,
+ update.error
+ )
+ : update.error;
+ }
+ done += owned.length;
+ }
+ return { done, skipped: unique.length - done };
+ }
+});
+
const renumberedTable = {
Part: "part",
Consumable: "consumable",
diff --git a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticesTable.tsx b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticesTable.tsx
index 0014c10d97..af58bf9265 100644
--- a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticesTable.tsx
+++ b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticesTable.tsx
@@ -29,6 +29,7 @@ import { useNavigate } from "react-router";
import { DateTime, EmployeeAvatar, Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { useRealtime } from "~/hooks/useRealtime";
@@ -50,7 +51,7 @@ type ChangeNoticesTableProps = {
data: ChangeNoticeListItem[];
types: ListItem[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
// One entry of the changeOrders view's `affectedItems` jsonb rollup — enough to
@@ -64,7 +65,7 @@ type AffectedItemSummary = {
};
const ChangeNoticesTable = memo(
- ({ data, types, count, nextCursor }: ChangeNoticesTableProps) => {
+ ({ data, types, count, infinite }: ChangeNoticesTableProps) => {
const navigate = useNavigate();
const { t } = useLingui();
const permissions = usePermissions();
@@ -322,11 +323,7 @@ const ChangeNoticesTable = memo(
<>
<Table<ChangeNoticeListItem>
data={data}
- infinite={{
- dataKey: "changeNotices",
- nextCursor,
- listKey: "change-notices"
- }}
+ infinite={infinite}
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.tsx
index 32a6c367b8..02641fb0f3 100644
--- a/apps/erp/app/modules/items/ui/ChangeNoticeActions/ChangeNoticeRequiredActionsTable.tsx
+++ b/apps/erp/app/modules/items/ui/ChangeNoticeActions/ChangeNoticeRequiredActionsTable.tsx
@@ -15,6 +15,7 @@ import { LuListChecks, LuPencil, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
import type { ChangeNoticeRequiredAction } from "../../types";
@@ -22,11 +23,11 @@ import type { ChangeNoticeRequiredAction } from "../../types";
type ChangeNoticeRequiredActionsTableProps = {
data: ChangeNoticeRequiredAction[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const ChangeNoticeRequiredActionsTable = memo(
- ({ data, count, nextCursor }: ChangeNoticeRequiredActionsTableProps) => {
+ ({ data, count, infinite }: ChangeNoticeRequiredActionsTableProps) => {
const [params] = useUrlParams();
const navigate = useNavigate();
const { t } = useLingui();
@@ -97,11 +98,7 @@ const ChangeNoticeRequiredActionsTable = memo(
return (
<Table<ChangeNoticeRequiredAction>
data={data}
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "change-notice-actions"
- }}
+ infinite={infinite}
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.tsx
index 1fab40076f..710a961a1c 100644
--- a/apps/erp/app/modules/items/ui/ChangeNoticeTypes/ChangeNoticeTypesTable.tsx
+++ b/apps/erp/app/modules/items/ui/ChangeNoticeTypes/ChangeNoticeTypesTable.tsx
@@ -10,6 +10,7 @@ import { LuGitPullRequestArrow, LuPencil, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
import type { ChangeNoticeType } from "../../types";
@@ -17,11 +18,11 @@ import type { ChangeNoticeType } from "../../types";
type ChangeNoticeTypesTableProps = {
data: ChangeNoticeType[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const ChangeNoticeTypesTable = memo(
- ({ data, count, nextCursor }: ChangeNoticeTypesTableProps) => {
+ ({ data, count, infinite }: ChangeNoticeTypesTableProps) => {
const [params] = useUrlParams();
const navigate = useNavigate();
const { t } = useLingui();
@@ -85,11 +86,7 @@ const ChangeNoticeTypesTable = memo(
return (
<Table<ChangeNoticeType>
data={data}
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "change-notice-types"
- }}
+ infinite={infinite}
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.tsx
index 1bc23a1204..6380156be1 100644
--- a/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx
+++ b/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx
@@ -60,7 +60,7 @@ import {
import { Enumerable } from "~/components/Enumerable";
import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";
import { ConfirmDelete } from "~/components/Modals";
-import type { BulkActionScope } from "~/components/Table";
+import type { BulkActionScope, InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { useBulkFormAction } from "~/hooks/useBulkAction";
import { useCustomColumns } from "~/hooks/useCustomColumns";
@@ -74,11 +74,11 @@ type ConsumablesTableProps = {
data: ConsumableListItem[];
tags: { name: string }[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const ConsumablesTable = memo(
- ({ data, count, tags, nextCursor }: ConsumablesTableProps) => {
+ ({ data, count, tags, infinite }: ConsumablesTableProps) => {
const { t } = useLingui();
const translateMethodType = useCallback(
(v: string) =>
@@ -594,11 +594,7 @@ const ConsumablesTable = memo(
count={count}
columns={columns}
data={data}
- infinite={{
- dataKey: "consumables",
- nextCursor,
- listKey: "consumables"
- }}
+ infinite={infinite}
defaultColumnPinning={{
left: ["id"]
}}
diff --git a/apps/erp/app/modules/items/ui/ItemPostingGroups/ItemPostingGroupsTable.tsx b/apps/erp/app/modules/items/ui/ItemPostingGroups/ItemPostingGroupsTable.tsx
index 6f49488131..d5eca7f179 100644
--- a/apps/erp/app/modules/items/ui/ItemPostingGroups/ItemPostingGroupsTable.tsx
+++ b/apps/erp/app/modules/items/ui/ItemPostingGroups/ItemPostingGroupsTable.tsx
@@ -10,6 +10,7 @@ import { LuPencil, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
@@ -18,11 +19,11 @@ import type { ItemPostingGroup } from "../../types";
type ItemGroupsTableProps = {
data: ItemPostingGroup[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const ItemGroupsTable = memo((props: ItemGroupsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const [params] = useUrlParams();
const navigate = useNavigate();
const { t } = useLingui();
@@ -99,11 +100,7 @@ const ItemGroupsTable = memo((props: ItemGroupsTableProps) => {
return (
<Table<(typeof rows)[number]>
data={data}
- infinite={{
- dataKey: "itemPostingGroups",
- nextCursor,
- listKey: "item-posting-groups"
- }}
+ infinite={infinite}
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.tsx
index b2682ad2a6..c3a4e1c5e9 100644
--- a/apps/erp/app/modules/items/ui/MaterialDimensions/MaterialDimensionsTable.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialDimensions/MaterialDimensionsTable.tsx
@@ -24,6 +24,7 @@ import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useShape } from "~/components/Form/Shape";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
import type { MaterialDimension } from "../../types";
@@ -31,11 +32,11 @@ import type { MaterialDimension } from "../../types";
type MaterialDimensionsTableProps = {
data: MaterialDimension[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const MaterialDimensionsTable = memo(
- ({ data, count, nextCursor }: MaterialDimensionsTableProps) => {
+ ({ data, count, infinite }: MaterialDimensionsTableProps) => {
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -161,11 +162,7 @@ const MaterialDimensionsTable = memo(
return (
<Table<(typeof rows)[number]>
data={data}
- infinite={{
- dataKey: "materialDimensions",
- nextCursor,
- listKey: "material-dimensions"
- }}
+ infinite={infinite}
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.tsx
index a27b63206f..0c1212f4f3 100644
--- a/apps/erp/app/modules/items/ui/MaterialFinishes/MaterialFinishesTable.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialFinishes/MaterialFinishesTable.tsx
@@ -24,6 +24,7 @@ import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useSubstance } from "~/components/Form/Substance";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
import type { MaterialFinish } from "../../types";
@@ -31,11 +32,11 @@ import type { MaterialFinish } from "../../types";
type MaterialFinishesTableProps = {
data: MaterialFinish[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const MaterialFinishesTable = memo(
- ({ data, count, nextCursor }: MaterialFinishesTableProps) => {
+ ({ data, count, infinite }: MaterialFinishesTableProps) => {
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -162,11 +163,7 @@ const MaterialFinishesTable = memo(
return (
<Table<(typeof rows)[number]>
data={data}
- infinite={{
- dataKey: "materialFinishes",
- nextCursor,
- listKey: "material-finishes"
- }}
+ infinite={infinite}
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.tsx
index ca74452099..e91b2ba5c2 100644
--- a/apps/erp/app/modules/items/ui/MaterialGrades/MaterialGradesTable.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialGrades/MaterialGradesTable.tsx
@@ -24,6 +24,7 @@ import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useSubstance } from "~/components/Form/Substance";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
import type { MaterialGrade } from "../../types";
@@ -31,11 +32,11 @@ import type { MaterialGrade } from "../../types";
type MaterialGradesTableProps = {
data: MaterialGrade[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const MaterialGradesTable = memo(
- ({ data, count, nextCursor }: MaterialGradesTableProps) => {
+ ({ data, count, infinite }: MaterialGradesTableProps) => {
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -159,11 +160,7 @@ const MaterialGradesTable = memo(
return (
<Table<(typeof rows)[number]>
data={data}
- infinite={{
- dataKey: "materialGrades",
- nextCursor,
- listKey: "material-grades"
- }}
+ infinite={infinite}
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.tsx
index af184523a3..3370797254 100644
--- a/apps/erp/app/modules/items/ui/MaterialShapes/MaterialShapesTable.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialShapes/MaterialShapesTable.tsx
@@ -23,6 +23,7 @@ import {
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
@@ -31,11 +32,11 @@ import type { Form } from "../../types";
type MaterialShapesTableProps = {
data: Form[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const MaterialShapesTable = memo(
- ({ data, count, nextCursor }: MaterialShapesTableProps) => {
+ ({ data, count, infinite }: MaterialShapesTableProps) => {
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -152,11 +153,7 @@ const MaterialShapesTable = memo(
return (
<Table<(typeof rows)[number]>
data={data}
- infinite={{
- dataKey: "materialForms",
- nextCursor,
- listKey: "material-forms"
- }}
+ infinite={infinite}
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.tsx
index 637601153e..32c73b64a8 100644
--- a/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsx
@@ -23,6 +23,7 @@ import {
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
@@ -31,11 +32,11 @@ import type { Substance } from "../../types";
type MaterialSubstancesTableProps = {
data: Substance[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const MaterialSubstancesTable = memo(
- ({ data, count, nextCursor }: MaterialSubstancesTableProps) => {
+ ({ data, count, infinite }: MaterialSubstancesTableProps) => {
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -154,11 +155,7 @@ const MaterialSubstancesTable = memo(
return (
<Table<(typeof rows)[number]>
data={data}
- infinite={{
- dataKey: "materialSubstances",
- nextCursor,
- listKey: "material-substances"
- }}
+ infinite={infinite}
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.tsx
index a03c1977e2..456369a2db 100644
--- a/apps/erp/app/modules/items/ui/MaterialTypes/MaterialTypesTable.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialTypes/MaterialTypesTable.tsx
@@ -26,6 +26,7 @@ import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useShape } from "~/components/Form/Shape";
import { useSubstance } from "~/components/Form/Substance";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
import type { MaterialType } from "../../types";
@@ -33,11 +34,11 @@ import type { MaterialType } from "../../types";
type MaterialTypesTableProps = {
data: MaterialType[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const MaterialTypesTable = memo((props: MaterialTypesTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -176,11 +177,7 @@ const MaterialTypesTable = memo((props: MaterialTypesTableProps) => {
return (
<Table<(typeof rows)[number]>
data={data}
- infinite={{
- dataKey: "materialTypes",
- nextCursor,
- listKey: "material-types"
- }}
+ infinite={infinite}
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.tsx
index 4ef7f1f211..a41d416d48 100644
--- a/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx
+++ b/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx
@@ -72,7 +72,7 @@ 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 type { BulkActionScope, InfiniteOptions } from "~/components/Table";
import { useFilters } from "~/components/Table/components/Filter/useFilters";
import { usePermissions } from "~/hooks";
import { useBulkFormAction } from "~/hooks/useBulkAction";
@@ -87,11 +87,11 @@ type MaterialsTableProps = {
data: MaterialListItem[];
tags: { name: string }[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const MaterialsTable = memo((props: MaterialsTableProps) => {
- const { data, tags, count, nextCursor } = props;
+ const { data, tags, count, infinite } = props;
const { t } = useLingui();
const translateMethodType = useCallback(
(v: string) =>
@@ -747,7 +747,7 @@ const MaterialsTable = memo((props: MaterialsTableProps) => {
count={count}
columns={columns}
data={data}
- infinite={{ dataKey: "materials", nextCursor, listKey: "materials" }}
+ infinite={infinite}
defaultColumnPinning={{
left: ["id"]
}}
diff --git a/apps/erp/app/modules/items/ui/Methods/MethodMaterialsTable.tsx b/apps/erp/app/modules/items/ui/Methods/MethodMaterialsTable.tsx
index 8c721a1ba7..233eadc2bb 100644
--- a/apps/erp/app/modules/items/ui/Methods/MethodMaterialsTable.tsx
+++ b/apps/erp/app/modules/items/ui/Methods/MethodMaterialsTable.tsx
@@ -7,6 +7,7 @@ import { useLingui } from "@lingui/react/macro";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
import { Hyperlink, MethodIcon, MethodItemTypeIcon, Table } from "~/components";
+import type { InfiniteOptions } from "~/components/Table";
import { methodItemType, methodType } from "~/modules/shared/shared.models";
import { useParts, useTools } from "~/stores";
import type { MethodMaterial } from "../../types";
@@ -15,11 +16,11 @@ import { getPathToMakeMethod } from "./utils";
type MethodMaterialsTableProps = {
data: MethodMaterial[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const MethodMaterialsTable = memo(
- ({ data, count, nextCursor }: MethodMaterialsTableProps) => {
+ ({ data, count, infinite }: MethodMaterialsTableProps) => {
const { t } = useLingui();
const parts = useParts();
const tools = useTools();
@@ -145,11 +146,7 @@ const MethodMaterialsTable = memo(
count={count}
columns={columns}
data={data}
- infinite={{
- dataKey: "materials",
- nextCursor,
- listKey: "method-materials"
- }}
+ infinite={infinite}
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.tsx
index 40274a15eb..9358ae8c57 100644
--- a/apps/erp/app/modules/items/ui/Methods/MethodOperationsTable.tsx
+++ b/apps/erp/app/modules/items/ui/Methods/MethodOperationsTable.tsx
@@ -7,6 +7,7 @@ import type { ColumnDef } from "@tanstack/react-table";
import { memo, useMemo } from "react";
import { Hyperlink, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { operationTypes } from "~/modules/shared/shared.models";
import { useParts, useTools } from "~/stores";
import type { MethodOperation } from "../../types";
@@ -15,11 +16,11 @@ import { getPathToMakeMethod } from "./utils";
type MethodOperationsTableProps = {
data: MethodOperation[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const MethodOperationsTable = memo(
- ({ data, count, nextCursor }: MethodOperationsTableProps) => {
+ ({ data, count, infinite }: MethodOperationsTableProps) => {
const { t } = useLingui();
const parts = useParts();
const tools = useTools();
@@ -110,11 +111,7 @@ const MethodOperationsTable = memo(
count={count}
columns={columns}
data={data}
- infinite={{
- dataKey: "operations",
- nextCursor,
- listKey: "method-operations"
- }}
+ infinite={infinite}
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.tsx
index 200ed5754e..7dd5c622d9 100644
--- a/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx
+++ b/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx
@@ -66,7 +66,7 @@ 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 type { BulkActionScope, InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { useBulkFormAction } from "~/hooks/useBulkAction";
import { useCustomColumns } from "~/hooks/useCustomColumns";
@@ -83,12 +83,11 @@ type PartsTableProps = {
data: PartListItem[];
tags: { name: string }[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const PartsTable = memo((props: PartsTableProps) => {
- const { data, tags, count, nextCursor } = props;
+ const { data, tags, count, infinite } = props;
const { t } = useLingui();
const navigate = useNavigate();
const permissions = usePermissions();
@@ -705,7 +704,7 @@ const PartsTable = memo((props: PartsTableProps) => {
count={count}
columns={columns}
data={data}
- infinite={{ dataKey: "parts", nextCursor, listKey: "parts" }}
+ infinite={infinite}
defaultColumnPinning={{
left: ["id"]
}}
diff --git a/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx b/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx
index bbd8f39ad8..cf353c8f6e 100644
--- a/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx
+++ b/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx
@@ -62,7 +62,7 @@ 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 type { BulkActionScope, InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { useBulkFormAction } from "~/hooks/useBulkAction";
import { useCustomColumns } from "~/hooks/useCustomColumns";
@@ -76,7 +76,7 @@ type ServicesTableProps = {
data: ServiceListItem[];
tags: { name: string }[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
// Services are Non-Inventory, so "Pull from Inventory" is never valid.
@@ -85,7 +85,7 @@ const serviceMethodTypes = methodType.filter(
);
const ServicesTable = memo((props: ServicesTableProps) => {
- const { data, tags, count, nextCursor } = props;
+ const { data, tags, count, infinite } = props;
const { t } = useLingui();
const navigate = useNavigate();
const permissions = usePermissions();
@@ -549,7 +549,7 @@ const ServicesTable = memo((props: ServicesTableProps) => {
count={count}
columns={columns}
data={data}
- infinite={{ dataKey: "services", nextCursor, listKey: "services" }}
+ infinite={infinite}
defaultColumnPinning={{
left: ["id"]
}}
diff --git a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx
index 54322cdcaa..df7e87428e 100644
--- a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx
+++ b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx
@@ -66,7 +66,7 @@ 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 type { BulkActionScope, InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { useBulkFormAction } from "~/hooks/useBulkAction";
import { useCustomColumns } from "~/hooks/useCustomColumns";
@@ -83,11 +83,11 @@ type ToolsTableProps = {
data: ToolListItem[];
tags: { name: string }[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const ToolsTable = memo((props: ToolsTableProps) => {
- const { data, tags, count, nextCursor } = props;
+ const { data, tags, count, infinite } = props;
const { t } = useLingui();
const navigate = useNavigate();
const permissions = usePermissions();
@@ -661,7 +661,7 @@ const ToolsTable = memo((props: ToolsTableProps) => {
count={count}
columns={columns}
data={data}
- infinite={{ dataKey: "tools", nextCursor, listKey: "tools" }}
+ infinite={infinite}
defaultColumnPinning={{
left: ["id"]
}}
diff --git a/apps/erp/app/modules/items/ui/UnitOfMeasure/UnitOfMeasuresTable.tsx b/apps/erp/app/modules/items/ui/UnitOfMeasure/UnitOfMeasuresTable.tsx
index 826d3d9792..2a7beb9857 100644
--- a/apps/erp/app/modules/items/ui/UnitOfMeasure/UnitOfMeasuresTable.tsx
+++ b/apps/erp/app/modules/items/ui/UnitOfMeasure/UnitOfMeasuresTable.tsx
@@ -10,6 +10,7 @@ import { LuBookMarked, LuCode, LuPencil, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
@@ -19,11 +20,11 @@ import type { UnitOfMeasure } from "../../types";
type UnitOfMeasuresTableProps = {
data: UnitOfMeasure[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const UnitOfMeasuresTable = memo(
- ({ data, count, nextCursor }: UnitOfMeasuresTableProps) => {
+ ({ data, count, infinite }: UnitOfMeasuresTableProps) => {
const [params] = useUrlParams();
const navigate = useNavigate();
const { t } = useLingui();
@@ -96,7 +97,7 @@ const UnitOfMeasuresTable = memo(
return (
<Table<(typeof data)[number]>
data={data}
- infinite={{ dataKey: "data", nextCursor, listKey: "units-of-measure" }}
+ infinite={infinite}
columns={columns}
count={count}
importCSV={[
diff --git a/apps/erp/app/modules/people/ui/Attributes/AttributeCategoriesTable.tsx b/apps/erp/app/modules/people/ui/Attributes/AttributeCategoriesTable.tsx
index f88582d5b4..e324a1f4ba 100644
--- a/apps/erp/app/modules/people/ui/Attributes/AttributeCategoriesTable.tsx
+++ b/apps/erp/app/modules/people/ui/Attributes/AttributeCategoriesTable.tsx
@@ -20,6 +20,7 @@ import { LuListChecks, LuPencil, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
import type { AttributeCategory } from "../../types";
@@ -27,11 +28,11 @@ import type { AttributeCategory } from "../../types";
type AttributeCategoriesTableProps = {
data: AttributeCategory[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const AttributeCategoriesTable = memo(
- ({ data, count, nextCursor }: AttributeCategoriesTableProps) => {
+ ({ data, count, infinite }: AttributeCategoriesTableProps) => {
const { t } = useLingui();
const navigate = useNavigate();
const [params] = useUrlParams();
@@ -184,11 +185,7 @@ const AttributeCategoriesTable = memo(
<>
<Table<AttributeCategory>
data={data}
- infinite={{
- dataKey: "categories",
- nextCursor,
- listKey: "attribute-categories"
- }}
+ infinite={infinite}
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.tsx
index 16754fe1ec..46da21179f 100644
--- a/apps/erp/app/modules/people/ui/Holidays/HolidaysTable.tsx
+++ b/apps/erp/app/modules/people/ui/Holidays/HolidaysTable.tsx
@@ -13,6 +13,7 @@ import { LuCalendar, LuCalendarDays, LuCalendarRange } from "react-icons/lu";
import { useNavigate } from "react-router";
import { DateTime, Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
@@ -21,12 +22,12 @@ import type { Holiday } from "../../types";
type HolidaysTableProps = {
data: Holiday[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
years: number[];
};
const HolidaysTable = memo((props: HolidaysTableProps) => {
- const { data, count, nextCursor, years } = props;
+ const { data, count, infinite, years } = props;
const { t } = useLingui();
const navigate = useNavigate();
const permissions = usePermissions();
@@ -115,7 +116,7 @@ const HolidaysTable = memo((props: HolidaysTableProps) => {
return (
<Table<(typeof data)[number]>
data={data}
- infinite={{ dataKey: "holidays", nextCursor, listKey: "holidays" }}
+ infinite={infinite}
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.tsx
index 97aabac38f..9b0788cbd6 100644
--- a/apps/erp/app/modules/people/ui/People/PeopleTable.tsx
+++ b/apps/erp/app/modules/people/ui/People/PeopleTable.tsx
@@ -35,6 +35,7 @@ import {
} from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { DataType } from "~/modules/shared/types";
import type { EmployeeType } from "~/modules/users/types";
@@ -45,7 +46,7 @@ type PeopleTableProps = {
attributeCategories: AttributeCategory[];
data: Person[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
employeeTypes: Partial<EmployeeType>[];
shifts: { id: string; name: string }[];
};
@@ -55,7 +56,7 @@ const PeopleTable = memo(
attributeCategories,
data,
count,
- nextCursor,
+ infinite,
employeeTypes,
shifts
}: PeopleTableProps) => {
@@ -310,7 +311,7 @@ const PeopleTable = memo(
count={count}
columns={columns}
data={data}
- infinite={{ dataKey: "people", nextCursor, listKey: "people" }}
+ infinite={infinite}
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.tsx
index 0f3be9610f..32eb747df1 100644
--- a/apps/erp/app/modules/people/ui/Shifts/ShiftsTable.tsx
+++ b/apps/erp/app/modules/people/ui/Shifts/ShiftsTable.tsx
@@ -25,6 +25,7 @@ import {
import { useNavigate } from "react-router";
import { DateTime, Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import type { ShiftLocation } from "~/modules/resources/types";
@@ -34,12 +35,12 @@ import type { Shift } from "../../types";
type ShiftsTableProps = {
data: Shift[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
locations: Partial<ShiftLocation>[];
};
const ShiftsTable = memo((props: ShiftsTableProps) => {
- const { data, count, nextCursor, locations } = props;
+ const { data, count, infinite, locations } = props;
const { t } = useLingui();
const { locale } = useLocale();
const navigate = useNavigate();
@@ -226,7 +227,7 @@ const ShiftsTable = memo((props: ShiftsTableProps) => {
return (
<Table<Shift>
data={data}
- infinite={{ dataKey: "shifts", nextCursor, listKey: "shifts" }}
+ infinite={infinite}
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.tsx
index b2e84d152c..68ec576a8c 100644
--- a/apps/erp/app/modules/people/ui/Timecards/TimecardsTable.tsx
+++ b/apps/erp/app/modules/people/ui/Timecards/TimecardsTable.tsx
@@ -28,6 +28,7 @@ import { useNavigate } from "react-router";
import { DateTime, Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
@@ -48,7 +49,7 @@ type TimeCardEntry = {
type TimecardsTableProps = {
data: TimeCardEntry[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
function formatTime(dateStr: string, locale: string) {
@@ -67,7 +68,7 @@ function formatDuration(clockInStr: string, clockOutStr: string | null) {
}
const TimecardsTable = memo((props: TimecardsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const { locale } = useLocale();
const navigate = useNavigate();
@@ -269,7 +270,7 @@ const TimecardsTable = memo((props: TimecardsTableProps) => {
return (
<Table<TimeCardEntry>
data={data}
- infinite={{ dataKey: "entries", nextCursor, listKey: "timecards" }}
+ infinite={infinite}
count={count}
columns={columns}
primaryAction={
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index 79f2447946..fad2c1684a 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -108,7 +108,7 @@ pnpm --filter 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/sales.utils`) 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`, published as `production_releaseJobs`) — the one release operation: the job page's Release dialog (`x+/job+/$jobId.release.tsx`, through `useJobRelease`), the jobs table's bulk **Release Jobs** (`x+/job+/release.tsx`, `path.to.bulkReleaseJob`), the planning page's Release (`useJobPlanningRelease`) and the API/MCP all run it. Per selected job: a job that is not Draft/Planned is listed in `skipped`; the dialog's supplier picks (`supplierProcessByOperationId`) are saved on the operations first (`stampSupplierChoices`, validated: the operation belongs to the jobs, the supplier process to its process); then `getJobReleaseReadiness` once for the selection (every read through `fetchAllByIds`, pinned by `test/job-release-readiness.test.ts`) and `jobReleaseProblems` per job — nothing to make, manufacturing blocked, an assembly with no operations, an outside operation without a supplier, a Make to Asset job that cannot complete to its asset (`makeToAssetReleaseError`), and, when no `purchaseOrdersBySupplierId` was sent, a supplier with Draft POs to choose from. A job with a problem is named in `failed`; the rest go through `releaseCheckedJobs` one by one on a shared supplier→PO map (a supplier's first new PO is reused), then `runLocationSchedule` runs once per location AFTER every status flip. Returns `{ released, warnings, failed, skipped, scheduled }`; a job released whose POs failed is in `released` and `warnings`. Pinned by `test/release-jobs.test.ts`. More than 25 selected jobs, or "every matching job" (up to 2,000), go to the background `table-bulk-action` job instead (`x+/job+/release.tsx`): it releases slices of 25 through `releaseCheckedJobs` (`utils/production-bulk-actions.server.ts`, a system context on behalf of the user) and carries the supplier→PO map from one slice to the next, so later jobs go on the PO an earlier slice made.
+- `releaseJobs` (`production.server.ts`, published as `production_releaseJobs`) — the one release operation: the job page's Release dialog (`x+/job+/$jobId.release.tsx`, through `useJobRelease`), the jobs table's bulk **Release Jobs** (`x+/job+/release.tsx`, `path.to.bulkReleaseJob`), the planning page's Release (`useJobPlanningRelease`) and the API/MCP all run it. Per selected job: a job that is not Draft/Planned is listed in `skipped`; the dialog's supplier picks (`supplierProcessByOperationId`) are saved on the operations first (`stampSupplierChoices`, validated: the operation belongs to the jobs, the supplier process to its process); then `getJobReleaseReadiness` once for the selection (every read through `fetchAllByIds`, pinned by `test/job-release-readiness.test.ts`) and `jobReleaseProblems` per job — nothing to make, manufacturing blocked, an assembly with no operations, an outside operation without a supplier, a Make to Asset job that cannot complete to its asset (`makeToAssetReleaseError`), and, when no `purchaseOrdersBySupplierId` was sent, a supplier with Draft POs to choose from. A job with a problem is named in `failed`; the rest go through `releaseCheckedJobs` one by one on a shared supplier→PO map (a supplier's first new PO is reused), then `runLocationSchedule` runs once per location AFTER every status flip. Returns `{ released, warnings, failed, skipped, scheduled, purchaseOrdersBySupplierId }`; a job released whose POs failed is in `released` and `warnings`. Pinned by `test/release-jobs.test.ts`. More than 25 selected jobs, or "every matching job" (up to 2,000), go to the background `table-bulk-action` job instead (`x+/job+/release.tsx`): it calls `releaseJobs` per slice of 25 (a system context on behalf of the user, `utils/table-jobs.server.ts`) and passes the returned supplier→PO map to the next slice as `carriedPurchaseOrders`, so later jobs go on the PO an earlier slice made (`startingPurchaseOrders`, `ui/Jobs/job-release-logic.ts`).
- `releaseCheckedJobs` (`production.server.ts`, unpublished) — the step every release shares, for jobs already checked: recalc, MRP (a failure is logged and never blocks), the guarded Ready flip (`updateJobStatus(..., { fromStatuses: ["Draft", "Planned"] })` returns `updated: false` when someone cancelled or released the job during the recalc/MRP, so the release stops; pinned by `test/job-status-guard.test.ts`), outside-operation POs, `releasedDate` (a failed write is reported, since nothing else writes it). Returns `releasedJobIds`, the PO map and a `failure`.
- `releaseBatches` (`production.server.ts`, published as `production_releaseBatches`) — releases Planned batches: member jobs through `releaseBatchMemberJobs` (all-or-nothing on `jobReleaseProblems`), then `releaseJobOperationBatch`, then `notifyScheduleInputsChanged`. One supplier→PO map runs through the batches of a call, so a supplier's outside operations from every batch go on the PO the first batch created; with no PO choice, a supplier with a Draft PO that is not this release's own refuses the batch. `carriedPurchaseOrders` passes the map in from an earlier call and the result returns it: the background Batches Release carries it from slice to slice, as Jobs Release does. Used by the batch drawer (`batching.update` release intent) and the batches table's bulk Release (`production+/batches.release.tsx`). `updateJobStatus` and `releaseJobOperationBatch` are NOT published: each alone skips what release does.
- **Every path to Ready.** Each refuses a job that fails `jobReleaseProblems`, which includes strict backflush lines with no storage unit (`materialsWithoutStorageUnit` from `getJobReleaseReadiness`):
diff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.ts
index d739e9bd77..acf8ff5d0c 100644
--- a/apps/erp/app/modules/production/production.server.ts
+++ b/apps/erp/app/modules/production/production.server.ts
@@ -4,7 +4,7 @@
import { CarbonError, defineServiceFn } from "@carbon/api/service-fn.server";
import { paged, payload, run, unwrap } from "@carbon/api/service-tools.server";
-import type { Json } from "@carbon/database";
+import { fetchAllByIds, type Json } from "@carbon/database";
import { ASSEMBLER_SERVICE_API_KEY, ASSEMBLER_SERVICE_URL } from "@carbon/env";
import { batchTrigger, trigger } from "@carbon/jobs";
import { trackWorkEvent } from "@carbon/lib/telemetry";
@@ -69,8 +69,11 @@ import {
getAssemblyModelState,
getDueDateForColumn,
isAssemblyPlanRunning,
+ isBatchDissolvable,
+ isJobBulkReleasable,
isJobEditableFromPlanning,
isJobLocked,
+ JOB_BULK_DELETABLE_STATUSES,
JOB_LOCKED_MESSAGE,
JOB_LOCKED_STATUSES,
jobOperationStatus,
@@ -101,8 +104,8 @@ import type { JobStatus } from "./production.service";
import * as service from "./production.service";
import * as utils from "./production.utils";
import {
- bulkReleaseStartingPurchaseOrders,
- jobReleaseProblems
+ jobReleaseProblems,
+ startingPurchaseOrders
} from "./ui/Jobs/job-release-logic";
const logger = getLogger("erp", "production");
@@ -395,9 +398,14 @@ type JobRef = { jobId: string; readableId: string };
*
* @param jobIds - The jobs to release.
* @param supplierProcessByOperationId - The supplier process to use for each outside operation, by operation id.
+ * A release of many jobs can run as several calls: `carriedPurchaseOrders`
+ * passes in the PO each supplier went on in an earlier call, so the jobs of a
+ * later call go on it instead of asking for a choice.
+ *
* @param purchaseOrdersBySupplierId - For each supplier, `new` or the id of one of its Draft purchase orders to add to.
+ * @param carriedPurchaseOrders - The PO each supplier went on in an earlier call of the same release, as that call returned it
*
- * @returns `released`, `failed` (each with its reason), `skipped` (not Draft or Planned), `warnings` (released, but a purchase order failed) and the `scheduled` locations.
+ * @returns `released`, `failed` (each with its reason), `skipped` (not Draft or Planned), `warnings` (released, but a purchase order failed), whether the locations were `scheduled`, and `purchaseOrdersBySupplierId` for the next call.
*
* @mcp
*/
@@ -405,13 +413,19 @@ export const releaseJobs = defineServiceFn({
input: z.object({
jobIds: z.array(z.string()).min(1),
purchaseOrdersBySupplierId: z.record(z.string(), z.string()).optional(),
+ carriedPurchaseOrders: z.record(z.string(), z.string()).optional(),
supplierProcessByOperationId: z.record(z.string(), z.string()).default({})
}),
permission: { update: "production" },
async run(
ctx,
- { jobIds, purchaseOrdersBySupplierId, supplierProcessByOperationId }
+ {
+ jobIds,
+ purchaseOrdersBySupplierId,
+ carriedPurchaseOrders,
+ supplierProcessByOperationId
+ }
) {
const client = ctx.asCaller.supabase;
const companyId = ctx.company.id;
@@ -442,7 +456,7 @@ export const releaseJobs = defineServiceFn({
const skipped: (JobRef & { status: string | null })[] = [];
const releasable = jobs
.filter((job) => {
- if (job.status === "Draft" || job.status === "Planned") return true;
+ if (isJobBulkReleasable(job.status)) return true;
skipped.push({
jobId: job.id,
readableId: job.jobId,
@@ -473,29 +487,12 @@ export const releaseJobs = defineServiceFn({
const readinessByJobId = new Map(
readiness.data.jobs.map((job) => [job.id, job] as const)
);
- const draftPurchaseOrdersBySupplier = new Map(
- readiness.data.suppliers.map(
- (supplier) =>
- [
- supplier.supplierId,
- new Set(supplier.draftPurchaseOrders.map((po) => po.id))
- ] as const
- )
- );
- // Only a Draft PO of that supplier is a valid target; anything else is
- // "new". A supplier's first new PO is reused by the jobs after it.
- let purchaseOrders: Record<string, string> = Object.fromEntries(
- readiness.data.suppliers.map((supplier) => {
- const picked = purchaseOrdersBySupplierId?.[supplier.supplierId];
- return [
- supplier.supplierId,
- picked &&
- draftPurchaseOrdersBySupplier.get(supplier.supplierId)?.has(picked)
- ? picked
- : "new"
- ];
- })
- );
+ // A supplier's first new PO is reused by the jobs after it.
+ const starting = startingPurchaseOrders(readiness.data.suppliers, {
+ chosen: purchaseOrdersBySupplierId,
+ carried: carriedPurchaseOrders
+ });
+ let purchaseOrders = starting.purchaseOrders;
const released: JobRef[] = [];
const warnings: (JobRef & { message: string })[] = [];
@@ -507,9 +504,8 @@ export const releaseJobs = defineServiceFn({
? [
...jobReleaseProblems(ready),
// With no choice sent there is no dialog to make one in.
- ...(!purchaseOrdersBySupplierId &&
- ready.supplierIds.some(
- (id) => (draftPurchaseOrdersBySupplier.get(id)?.size ?? 0) > 0
+ ...(ready.supplierIds.some((id) =>
+ starting.suppliersToChoose.has(id)
)
? [
"choose a purchase order for its outside operations on the job"
@@ -561,7 +557,17 @@ export const releaseJobs = defineServiceFn({
}
}
- return { released, warnings, failed, skipped, scheduled };
+ return {
+ released,
+ warnings,
+ failed,
+ skipped,
+ scheduled,
+ purchaseOrdersBySupplierId: {
+ ...carriedPurchaseOrders,
+ ...purchaseOrders
+ }
+ };
}
});
/**
@@ -948,7 +954,7 @@ export const completeJob = defineServiceFn({
* planner can release it from its dialog. An unattended release of several
* batches passes `carriedPurchaseOrders`, the PO each supplier went on in an
* earlier batch of the same release: that supplier stays on it instead of
- * being refused (`bulkReleaseStartingPurchaseOrders`). The PO map is
+ * being refused (`startingPurchaseOrders`). The PO map is
* returned for the next batch, also beside `failure` when a job failed after
* the checks (the jobs before it are released).
*/
@@ -981,7 +987,7 @@ export const releaseBatchMemberJobs = defineServiceFn({
}
const toRelease = (jobs.data ?? [])
- .filter((job) => job.status === "Draft" || job.status === "Planned")
+ .filter((job) => isJobBulkReleasable(job.status))
.map((job) => job.id);
if (toRelease.length === 0) {
return {
@@ -1014,38 +1020,20 @@ export const releaseBatchMemberJobs = defineServiceFn({
);
}
- let purchaseOrders: Record<string, string>;
- if (purchaseOrdersBySupplierId) {
- // Only a Draft PO of that supplier is a valid target; anything else is "new".
- purchaseOrders = Object.fromEntries(
- readiness.data.suppliers.map((supplier) => {
- const picked = purchaseOrdersBySupplierId[supplier.supplierId];
- return [
- supplier.supplierId,
- picked &&
- supplier.draftPurchaseOrders.some((po) => po.id === picked)
- ? picked
- : "new"
- ];
- })
- );
- } else {
- const starting = bulkReleaseStartingPurchaseOrders(
- readiness.data.suppliers,
- carriedPurchaseOrders
+ const starting = startingPurchaseOrders(readiness.data.suppliers, {
+ chosen: purchaseOrdersBySupplierId,
+ carried: carriedPurchaseOrders
+ });
+ if (starting.suppliersToChoose.size > 0) {
+ return ctx.error(
+ "rule",
+ "Outside operations need a purchase order choice — open the batch to release it"
);
- if (starting.suppliersToChoose.size > 0) {
- return ctx.error(
- "rule",
- "Outside operations need a purchase order choice — open the batch to release it"
- );
- }
- purchaseOrders = starting.purchaseOrders;
}
const released = await releaseCheckedJobs(ctx, {
jobIds: toRelease,
- purchaseOrdersBySupplierId: purchaseOrders
+ purchaseOrdersBySupplierId: starting.purchaseOrders
});
if (released.error) return released.error;
// A failure is returned with the PO map: the jobs released before it
@@ -1494,9 +1482,12 @@ const jobIdsInput = z.array(z.string()).min(1);
* Delete jobs.
*
* @remarks
- * Refused, with nothing deleted, when any of the jobs is locked (Completed,
- * Closed or Cancelled). The jobs' methods, materials and operations go with
- * them.
+ * Deletes the Draft and Planned jobs (and old Due Today and Overdue ones) and
+ * skips the rest. The status is part of the DELETE, so a job released since
+ * it was selected stays. Refused when none of the jobs could be deleted. The
+ * jobs' methods, materials and operations go with them.
+ *
+ * @returns `ids`, the jobs deleted, and `skipped`, how many were not.
*
* @mcp destructive
*/
@@ -1505,17 +1496,26 @@ export const deleteJobs = defineServiceFn({
permission: { delete: "production" },
async run(ctx, { ids }) {
- const jobs = await service.readUnlockedJobs(ctx, ids);
- if (jobs instanceof CarbonError) return jobs;
- const deleted = await ctx.asCaller.supabase
- .from("job")
- .delete()
- .in("id", ids)
- .eq("companyId", ctx.company.id);
- if (deleted.error) {
- return ctx.error("internal", deleted.error.message, deleted.error);
+ const unique = [...new Set(ids)];
+ const deleted: string[] = [];
+ // An `in` filter rides in the request URL, so ids go in groups.
+ for (const chunk of chunkArray(unique, 100)) {
+ const result = await ctx.asCaller.supabase
+ .from("job")
+ .delete()
+ .in("id", chunk)
+ .eq("companyId", ctx.company.id)
+ .in("status", [...JOB_BULK_DELETABLE_STATUSES])
+ .select("id");
+ if (result.error) {
+ return ctx.error("internal", "Failed to delete the jobs", result.error);
+ }
+ deleted.push(...result.data.map((job) => job.id));
}
- return { ids };
+ if (deleted.length === 0) {
+ return ctx.error("rule", "Only Draft and Planned jobs can be deleted");
+ }
+ return { ids: deleted, skipped: unique.length - deleted.length };
}
});
@@ -3486,6 +3486,55 @@ export const updateBatch = defineServiceFn({
}
});
+/**
+ * Dissolve operation batches.
+ *
+ * @remarks
+ * Dissolves each Planned or Active batch on its own (`updateBatch`): a batch
+ * that has recorded production is refused and listed in `failed` while the
+ * rest still dissolve. A batch in any other status is skipped.
+ */
+export const dissolveBatches = defineServiceFn({
+ input: z.object({ batchIds: z.array(z.string()).min(1) }),
+ permission: { update: "production" },
+
+ async run(ctx, { batchIds }) {
+ const ids = [...new Set(batchIds)];
+ const batches = await fetchAllByIds(ids, (batch) =>
+ ctx.asCaller.supabase
+ .from("jobOperationBatch")
+ .select("id, readableId, status")
+ .in("id", batch)
+ .eq("companyId", ctx.company.id)
+ .order("id")
+ );
+ if (batches.error) {
+ return ctx.error("internal", "Failed to load the batches", batches.error);
+ }
+
+ const dissolvable = batches.data.filter((batch) =>
+ isBatchDissolvable(batch.status)
+ );
+ let dissolved = 0;
+ const failed: { readableId: string; message: string }[] = [];
+ for (const batch of dissolvable) {
+ const result = await updateBatch(ctx, {
+ batchId: batch.id,
+ type: "dissolve"
+ });
+ if (result.error) {
+ failed.push({
+ readableId: batch.readableId,
+ message: result.error.message || "Failed to dissolve"
+ });
+ } else {
+ dissolved += 1;
+ }
+ }
+ return { dissolved, failed, skipped: ids.length - dissolvable.length };
+ }
+});
+
// --- People board ---------------------------------------------------------
/**
* Put a person at a work center for a date.
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index fb08937e23..25b7ce08c6 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -171,10 +171,6 @@ import {
TIME_ENTRY_BEFORE_CUTOVER_ERROR
} from "~/modules/shared/shared.service";
import type { StorageItem } from "~/types";
-import {
- type BulkDeleteResult,
- bulkDeleteByStatus
-} from "~/utils/bulk-delete.server";
import type { Cursor } from "~/utils/cursor";
import { makeDurations } from "~/utils/duration";
import type { GenericQueryFilters, Paging } from "~/utils/query";
@@ -233,7 +229,6 @@ import {
getAssemblyModelState,
isJobLocked,
isJobOrderStatusHidden,
- JOB_BULK_DELETABLE_STATUSES,
JOB_LOCKED_MESSAGE,
JOB_LOCKED_STATUSES,
JOB_SUPPLY_STATUS_PRIORITY,
@@ -25198,35 +25193,3 @@ export async function batchOperation(
return { success: true, ...result };
}
-
-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")
- });
-}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionsTable.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionsTable.tsx
index b5a0901e77..69921b7323 100644
--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionsTable.tsx
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionsTable.tsx
@@ -39,6 +39,7 @@ import {
Table
} from "~/components";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { MethodItemType } from "~/modules/shared/types";
@@ -50,8 +51,7 @@ import AssemblyInstructionStatus from "./AssemblyInstructionStatus";
type AssemblyInstructionsTableProps = {
data: AssemblyInstructionListItem[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const itemTypesWithDetails = ["Part", "Material", "Tool", "Consumable"];
@@ -73,7 +73,7 @@ function ProcessingStatus({ status }: { status?: string | null }) {
}
const AssemblyInstructionsTable = memo(
- ({ data, count, nextCursor }: AssemblyInstructionsTableProps) => {
+ ({ data, count, infinite }: AssemblyInstructionsTableProps) => {
const { t } = useLingui();
const navigate = useNavigate();
const permissions = usePermissions();
@@ -289,11 +289,7 @@ const AssemblyInstructionsTable = memo(
data={data}
columns={columns}
count={count}
- infinite={{
- dataKey: "instructions",
- nextCursor,
- listKey: "assembly-instructions"
- }}
+ infinite={infinite}
primaryAction={
permissions.can("create", "production") && (
<New
diff --git a/apps/erp/app/modules/production/ui/Batches/BatchesTable.tsx b/apps/erp/app/modules/production/ui/Batches/BatchesTable.tsx
index 62e8e8fb8e..719efc2a73 100644
--- a/apps/erp/app/modules/production/ui/Batches/BatchesTable.tsx
+++ b/apps/erp/app/modules/production/ui/Batches/BatchesTable.tsx
@@ -35,7 +35,7 @@ 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 type { BulkActionScope, InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import {
useAllMatchingLimitLabel,
@@ -52,13 +52,13 @@ import { ALL_MATCHING_RELEASE_LIMIT } from "~/utils/table-jobs";
import { isBatchDissolvable, isBatchReleasable } from "../../production.models";
import type { JobOperationBatch } from "../../types";
import { BatchReleaseModal } from "./BatchReleaseModal";
+import { BATCH_LIST_EXPORT_VALUES } from "./batch-list-export";
import { useBatchRelease } from "./useBatchRelease";
type BatchesTableProps = {
data: JobOperationBatch[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const BATCH_STATUSES = [
@@ -110,7 +110,7 @@ function useBatchCountMessages() {
);
}
-const BatchesTable = memo(({ data, count, nextCursor }: BatchesTableProps) => {
+const BatchesTable = memo(({ data, count, infinite }: BatchesTableProps) => {
const { t } = useLingui();
const countMessages = useBatchCountMessages();
const showBulkStart = useBulkStartToast();
@@ -241,7 +241,8 @@ const BatchesTable = memo(({ data, count, nextCursor }: BatchesTableProps) => {
}
},
onError: (result) => {
- showBulkStart(result);
+ if (showBulkStart(result)) return;
+ if (result.error?.message) toast.error(result.error.message);
}
});
@@ -379,7 +380,7 @@ const BatchesTable = memo(({ data, count, nextCursor }: BatchesTableProps) => {
meta: {
icon: <LuLayers />,
filterHeader: t`Process`,
- exportValue: (row: JobOperationBatch) => row.process?.name ?? null
+ exportValue: BATCH_LIST_EXPORT_VALUES.process
}
},
{
@@ -392,7 +393,7 @@ const BatchesTable = memo(({ data, count, nextCursor }: BatchesTableProps) => {
mobile: "P3",
icon: <LuFactory />,
filterHeader: t`Work Center`,
- exportValue: (row: JobOperationBatch) => row.workCenterName ?? null
+ exportValue: BATCH_LIST_EXPORT_VALUES.workCenter
}
},
{
@@ -516,11 +517,7 @@ const BatchesTable = memo(({ data, count, nextCursor }: BatchesTableProps) => {
data={data}
columns={columns}
count={count}
- infinite={{
- dataKey: "batches",
- nextCursor,
- listKey: "operation-batches"
- }}
+ infinite={infinite}
primaryAction={
permissions.can("create", "production") && (
<New label={t`Batch`} to={path.to.newOperationBatch} />
diff --git a/apps/erp/app/modules/production/ui/Batches/batch-list-export.ts b/apps/erp/app/modules/production/ui/Batches/batch-list-export.ts
new file mode 100644
index 0000000000..8cac989cc1
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/Batches/batch-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 Batches table columns that show a value computed from the row, by
+ * column id. The table exports them with these, and the background CSV
+ * export writes the same values (`operationBatchesList.exportValues`).
+ */
+type Row = {
+ process?: { name: string | null } | null;
+ workCenterName?: string | null;
+};
+
+export const BATCH_LIST_EXPORT_VALUES = {
+ process: (row: Row) => row.process?.name ?? null,
+ workCenter: (row: Row) => row.workCenterName ?? null
+} satisfies Record<string, (row: Row) => string | null>;
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx
index d867bbb045..59dc407f7e 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx
@@ -61,7 +61,7 @@ import {
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
import { ConfirmDelete } from "~/components/Modals";
-import type { BulkActionScope } from "~/components/Table";
+import type { BulkActionScope, InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import {
useAllMatchingLimitLabel,
@@ -101,8 +101,7 @@ type JobRow = Job & {
type JobsTableProps = {
data: JobRow[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
tags: { name: string }[];
};
@@ -155,7 +154,7 @@ function renderQuantity(job: Job, unit?: string | null) {
}
const JobsTable = memo((props: JobsTableProps) => {
- const { data, count, nextCursor, tags } = props;
+ const { data, count, infinite, tags } = props;
const navigate = useNavigate();
const { t } = useLingui();
const releasedJobsMessage = useReleasedJobsMessage();
@@ -185,11 +184,6 @@ const JobsTable = memo((props: JobsTableProps) => {
const deleteModal = useDisclosure();
const [selectedJob, setSelectedJob] = useState<Job | null>(null);
- const infinite = useMemo(
- () => ({ dataKey: "jobs", nextCursor, listKey: "jobs" }),
- [nextCursor]
- );
-
const onDelete = (data: Job) => {
setSelectedJob(data);
deleteModal.onOpen();
@@ -714,7 +708,8 @@ const JobsTable = memo((props: JobsTableProps) => {
}
},
onError: (result) => {
- showBulkStart(result);
+ if (showBulkStart(result)) return;
+ if (result.error?.message) toast.error(result.error.message);
}
});
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.ts
index 3ee63a909a..d4908e1a00 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
@@ -136,22 +136,26 @@ export function jobReleaseProblems(job: {
}
/**
- * The purchase order each supplier's outside operations start on in a bulk
+ * The purchase order each supplier's outside operations start on in a
* 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.
+ * `chosen` is the Release dialog's choice: a supplier keeps its pick when it
+ * is one of its Drafts, else starts a new PO, and nobody is asked again.
+ * Without a choice, a supplier with Drafts must choose, unless `carried`
+ * names one of them: a background release runs in slices of 25 jobs, and
+ * `carried` (the map the previous slice returned) is the PO an earlier slice
+ * created, which the supplier keeps.
*/
-export function bulkReleaseStartingPurchaseOrders(
+export function startingPurchaseOrders(
suppliers: {
supplierId: string;
draftPurchaseOrders: { id: string }[];
}[],
- carried: Record<string, string> = {}
+ {
+ chosen,
+ carried = {}
+ }: { chosen?: Record<string, string>; carried?: Record<string, string> } = {}
): {
purchaseOrders: Record<string, string>;
suppliersToChoose: Set<string>;
@@ -159,13 +163,15 @@ export function bulkReleaseStartingPurchaseOrders(
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;
+ const kept = (chosen ?? carried)[supplierId];
+ if (kept && draftPurchaseOrders.some((po) => po.id === kept)) {
+ purchaseOrders[supplierId] = kept;
continue;
}
purchaseOrders[supplierId] = "new";
- if (draftPurchaseOrders.length > 0) suppliersToChoose.add(supplierId);
+ if (!chosen && draftPurchaseOrders.length > 0) {
+ suppliersToChoose.add(supplierId);
+ }
}
return { purchaseOrders, suppliersToChoose };
}
diff --git a/apps/erp/app/modules/production/ui/Procedures/ProceduresTable.tsx b/apps/erp/app/modules/production/ui/Procedures/ProceduresTable.tsx
index 874a63093e..25922316c8 100644
--- a/apps/erp/app/modules/production/ui/Procedures/ProceduresTable.tsx
+++ b/apps/erp/app/modules/production/ui/Procedures/ProceduresTable.tsx
@@ -33,6 +33,7 @@ import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useProcesses } from "~/components/Form/Process";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { path } from "~/utils/path";
import type { Procedures } from "../../types";
@@ -42,12 +43,11 @@ type ProceduresTableProps = {
data: Procedures[];
tags: { name: string }[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const ProceduresTable = memo((props: ProceduresTableProps) => {
- const { data, tags, count, nextCursor } = props;
+ const { data, tags, count, infinite } = props;
const navigate = useNavigate();
const { t } = useLingui();
const permissions = usePermissions();
@@ -234,11 +234,7 @@ const ProceduresTable = memo((props: ProceduresTableProps) => {
data={data}
columns={columns}
count={count}
- infinite={{
- dataKey: "procedures",
- nextCursor,
- listKey: "procedures"
- }}
+ infinite={infinite}
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.tsx
index dd6a154569..14dbd71820 100644
--- a/apps/erp/app/modules/production/ui/ScrapReasons/ScrapReasonsTable.tsx
+++ b/apps/erp/app/modules/production/ui/ScrapReasons/ScrapReasonsTable.tsx
@@ -10,6 +10,7 @@ import { LuPencil, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
@@ -18,12 +19,11 @@ import type { ScrapReason } from "../../types";
type ScrapReasonsTableProps = {
data: ScrapReason[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const ScrapReasonsTable = memo((props: ScrapReasonsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const [params] = useUrlParams();
const { t } = useLingui();
const navigate = useNavigate();
@@ -86,11 +86,7 @@ const ScrapReasonsTable = memo((props: ScrapReasonsTableProps) => {
data={data}
columns={columns}
count={count}
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "scrap-reasons"
- }}
+ infinite={infinite}
importCSV={[
{
table: "scrapReason" as const,
diff --git a/apps/erp/app/modules/purchasing/purchasing.server.ts b/apps/erp/app/modules/purchasing/purchasing.server.ts
index ac9ea077eb..89563df341 100644
--- a/apps/erp/app/modules/purchasing/purchasing.server.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.server.ts
@@ -4,7 +4,12 @@
import { CarbonError, defineServiceFn } from "@carbon/api/service-fn.server";
import { paged, payload, unwrap } from "@carbon/api/service-tools.server";
-import { type Database, getCompanyTimeZone, type Json } from "@carbon/database";
+import {
+ type Database,
+ fetchAllByIds,
+ getCompanyTimeZone,
+ type Json
+} from "@carbon/database";
import {
convertUnitPrice,
supplierPartCurrency
@@ -1933,10 +1938,12 @@ export const updatePurchaseOrders = defineServiceFn({
* Delete purchase orders.
*
* @remarks
- * Only Draft, Planned or Needs Approval orders. An order that needs approval
- * can be deleted only by the person who requested it (an approver rejects
- * instead), and its pending approval requests are cancelled first. Every
- * order is checked before anything is deleted.
+ * Deletes the Draft and Planned orders, and the Needs Approval orders the
+ * caller requested (their pending approval requests are cancelled first),
+ * and skips the rest: an approver rejects an order instead of deleting it.
+ * Refused, with the first order's reason, when none could be deleted.
+ *
+ * @returns `purchaseOrderIds`, the orders deleted, and `skipped`, how many were not.
*
* @mcp destructive
*/
@@ -1950,31 +1957,38 @@ export const deletePurchaseOrders = defineServiceFn({
const userId = ctx.auditUserId;
const ids = [...new Set(purchaseOrderIds)];
- const orders = await system
- .from("purchaseOrder")
- .select("id, status")
- .in("id", ids)
- .eq("companyId", companyId);
+ const orders = await fetchAllByIds(ids, (batch) =>
+ system
+ .from("purchaseOrder")
+ .select("id, status")
+ .in("id", batch)
+ .eq("companyId", companyId)
+ .order("id")
+ );
if (orders.error) {
- return ctx.error("internal", "Purchase order not found", orders.error);
- }
- if (orders.data.length !== ids.length) {
- return ctx.error("notFound", "Purchase order not found");
+ return ctx.error(
+ "internal",
+ "Failed to read the purchase orders",
+ orders.error
+ );
}
- const needsApproval = orders.data
+ const inApproval = orders.data
.filter((order) => order.status === "Needs Approval")
.map((order) => order.id);
const pending =
- needsApproval.length > 0
- ? await system
- .from("approvalRequest")
- .select("documentId, requestedBy, amount, requestedAt")
- .eq("documentType", "purchaseOrder")
- .in("documentId", needsApproval)
- .eq("companyId", companyId)
- .eq("status", "Pending")
- .order("requestedAt", { ascending: false })
+ inApproval.length > 0
+ ? await fetchAllByIds(inApproval, (batch) =>
+ system
+ .from("approvalRequest")
+ .select("id, documentId, requestedBy, amount, requestedAt")
+ .eq("documentType", "purchaseOrder")
+ .in("documentId", batch)
+ .eq("companyId", companyId)
+ .eq("status", "Pending")
+ .order("requestedAt", { ascending: false })
+ .order("id")
+ )
: null;
if (pending?.error) {
return ctx.error(
@@ -1984,6 +1998,12 @@ export const deletePurchaseOrders = defineServiceFn({
);
}
+ const deletable: string[] = [];
+ let refused: {
+ status: string | null;
+ refusal: "status" | "notRequester";
+ amount: number | null;
+ } | null = null;
for (const order of orders.data) {
const latest = pending?.data.find((r) => r.documentId === order.id);
const refusal = purchaseOrderDeleteRefusal({
@@ -1991,51 +2011,66 @@ export const deletePurchaseOrders = defineServiceFn({
requestedBy: latest?.requestedBy,
userId
});
- if (refusal === "status") {
- return ctx.error(
- "rule",
- `Cannot delete purchase order with status "${order.status ?? "unknown"}". Only Draft, Planned, or Needs Approval (if you're the requester) purchase orders can be deleted.`
- );
+ if (refusal) {
+ refused ??= {
+ status: order.status,
+ refusal,
+ amount: latest?.amount ?? null
+ };
+ } else {
+ deletable.push(order.id);
}
- if (refusal === "notRequester") {
- const isApprover = await canApproveRequest(
- system,
- {
- amount: latest?.amount ?? null,
- documentType: "purchaseOrder",
- companyId
- },
- userId
- );
+ }
+
+ if (deletable.length === 0) {
+ if (!refused) return ctx.error("notFound", "Purchase order not found");
+ if (refused.refusal === "status") {
return ctx.error(
- "forbidden",
- isApprover
- ? "Please reject the approval request instead of deleting"
- : "You do not have permission to delete this purchase order"
+ "rule",
+ `Cannot delete purchase order with status "${refused.status ?? "unknown"}". Only Draft, Planned, or Needs Approval (if you're the requester) purchase orders can be deleted.`
);
}
+ const isApprover = await canApproveRequest(
+ system,
+ {
+ amount: refused.amount,
+ documentType: "purchaseOrder",
+ companyId
+ },
+ userId
+ );
+ return ctx.error(
+ "forbidden",
+ isApprover
+ ? "Please reject the approval request instead of deleting"
+ : "You do not have permission to delete this purchase order"
+ );
}
// One transaction: a delete that fails (an invoice line still names the
- // order) must leave its approval requests pending.
+ // order) must leave its approval requests pending. The status is part of
+ // the DELETE, so an order sent since it was read stays.
const removed = await ctx
.transaction(async (tx) => {
await service.cancelPendingApprovals(tx.asSystem.pg, {
companyId,
userId,
- purchaseOrderIds: needsApproval
+ purchaseOrderIds: inApproval.filter((id) => deletable.includes(id))
});
- await tx.asSystem.pg
+ return tx.asSystem.pg
.deleteFrom("purchaseOrder")
- .where("id", "in", ids)
+ .where("id", "in", deletable)
.where("companyId", "=", companyId)
+ .where("status", "in", ["Draft", "Planned", "Needs Approval"])
+ .returning("id")
.execute();
})
.catch((err) =>
ctx.error("internal", "Failed to delete purchase orders", err)
);
if (removed instanceof CarbonError) return removed;
- return { purchaseOrderIds: ids };
+ const deleted = (removed.data ?? []).map((order) => order.id);
+ return { purchaseOrderIds: deleted, skipped: ids.length - deleted.length };
}
});
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 5959e5f9ab..5beb34a754 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -17,7 +17,6 @@ import { hasPermission } from "@carbon/auth";
import { getUserClaims } from "@carbon/auth/users.server";
import type { Database, Json } from "@carbon/database";
import {
- Constants,
fetchAllByIds,
fetchAllFromTable,
fetchAllRecords,
@@ -121,10 +120,6 @@ 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, Paging } from "~/utils/query";
import { listCount, setGenericQueryFilters } from "~/utils/query";
@@ -177,7 +172,6 @@ import type {
supplierValidator
} from "./purchasing.models";
import {
- isPurchaseOrderBulkDeletable,
leaseDetailFields,
leaseLineColumns,
leaseLinePaymentFields,
@@ -10731,37 +10725,3 @@ export async function createLeaseInvoices(
leaseId
});
}
-
-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/ui/Leases/LeasesTable.tsx b/apps/erp/app/modules/purchasing/ui/Leases/LeasesTable.tsx
index 24b25f1809..c82f34b69e 100644
--- a/apps/erp/app/modules/purchasing/ui/Leases/LeasesTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Leases/LeasesTable.tsx
@@ -24,6 +24,7 @@ import { useNavigate } from "react-router";
import { Hyperlink, New, SupplierAvatar, Table } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
import Money from "~/components/Money";
+import type { InfiniteOptions } from "~/components/Table";
import { useDateFormatter, usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { useSuppliers } from "~/stores";
@@ -36,11 +37,10 @@ import type { Lease } from "./types";
type LeasesTableProps = {
data: Lease[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
-const LeasesTable = memo(({ data, count, nextCursor }: LeasesTableProps) => {
+const LeasesTable = memo(({ data, count, infinite }: LeasesTableProps) => {
const { t } = useLingui();
const permissions = usePermissions();
const navigate = useNavigate();
@@ -247,11 +247,7 @@ const LeasesTable = memo(({ data, count, nextCursor }: LeasesTableProps) => {
count={count}
columns={columns}
data={data}
- infinite={{
- dataKey: "leases",
- nextCursor,
- listKey: "leases"
- }}
+ infinite={infinite}
defaultColumnPinning={{
left: ["leaseId"]
}}
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx
index 9a8ca2cba8..f71878935d 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx
@@ -50,7 +50,7 @@ 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 type { BulkActionScope, InfiniteOptions } from "~/components/Table";
import { useCurrencyFormatter, usePermissions, useRealtime } from "~/hooks";
import { useBulkFormAction } from "~/hooks/useBulkAction";
import { useCustomColumns } from "~/hooks/useCustomColumns";
@@ -67,12 +67,11 @@ import { usePurchaseOrder } from "./usePurchaseOrder";
type PurchaseOrdersTableProps = {
data: PurchaseOrderListItem[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const PurchaseOrdersTable = memo(
- ({ data, count, nextCursor }: PurchaseOrdersTableProps) => {
+ ({ data, count, infinite }: PurchaseOrdersTableProps) => {
useRealtime("purchaseOrder");
const { t } = useLingui();
@@ -527,11 +526,7 @@ const PurchaseOrdersTable = memo(
count={count}
columns={columns}
data={data}
- infinite={{
- dataKey: "purchasOrders",
- nextCursor,
- listKey: "purchase-orders"
- }}
+ infinite={infinite}
defaultColumnPinning={{
left: ["purchaseOrderId"]
}}
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/PurchaseReturnOrdersTable.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/PurchaseReturnOrdersTable.tsx
index 58762f920b..f15bc6e9e8 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/PurchaseReturnOrdersTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/PurchaseReturnOrdersTable.tsx
@@ -31,6 +31,7 @@ import {
Table
} from "~/components";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { useDateFormatter, usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { usePeople, useSuppliers } from "~/stores";
@@ -42,12 +43,11 @@ import type { PurchaseReturnOrderListItem } from "./types";
type PurchaseReturnOrdersTableProps = {
data: PurchaseReturnOrderListItem[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const PurchaseReturnOrdersTable = memo(
- ({ data, count, nextCursor }: PurchaseReturnOrdersTableProps) => {
+ ({ data, count, infinite }: PurchaseReturnOrdersTableProps) => {
const { t } = useLingui();
const permissions = usePermissions();
const navigate = useNavigate();
@@ -234,11 +234,7 @@ const PurchaseReturnOrdersTable = memo(
count={count}
columns={columns}
data={data}
- infinite={{
- dataKey: "purchaseReturnOrders",
- nextCursor,
- listKey: "purchase-return-orders"
- }}
+ infinite={infinite}
defaultColumnPinning={{
left: ["purchaseReturnOrderId"]
}}
diff --git a/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQsTable.tsx b/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQsTable.tsx
index 17cbb47831..433bc4d452 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQsTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQsTable.tsx
@@ -26,6 +26,7 @@ import { useNavigate } from "react-router";
import { DateTime, EmployeeAvatar, Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { usePeople, useSuppliers } from "~/stores";
@@ -37,12 +38,11 @@ import { PurchasingRFQStatus } from ".";
type PurchasingRFQsTableProps = {
data: PurchasingRFQ[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const PurchasingRFQsTable = memo(
- ({ data, count, nextCursor }: PurchasingRFQsTableProps) => {
+ ({ data, count, infinite }: PurchasingRFQsTableProps) => {
const { t } = useLingui();
const permissions = usePermissions();
const navigate = useNavigate();
@@ -282,11 +282,7 @@ const PurchasingRFQsTable = memo(
count={count}
columns={columns}
data={data}
- infinite={{
- dataKey: "rfqs",
- nextCursor,
- listKey: "purchasing-rfqs"
- }}
+ infinite={infinite}
defaultColumnPinning={{
left: ["rfqId"]
}}
diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SuppliersTable.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SuppliersTable.tsx
index 3f31991c54..2a6b2d5112 100644
--- a/apps/erp/app/modules/purchasing/ui/Supplier/SuppliersTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SuppliersTable.tsx
@@ -43,6 +43,7 @@ import {
import { Enumerable } from "~/components/Enumerable";
import { useSupplierTypes } from "~/components/Form/SupplierType";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { useCompanySettings, usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { supplierStatusType } from "~/modules/purchasing/purchasing.models";
@@ -61,15 +62,14 @@ type SupplierRow = Supplier & { reportContacts: SupplierReportContacts };
type SuppliersTableProps = {
data: SupplierRow[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
tags: { name: string }[];
};
const SuppliersTable = memo(function SuppliersTable({
data,
count,
- nextCursor,
+ infinite,
tags
}: SuppliersTableProps) {
const { t } = useLingui();
@@ -85,11 +85,6 @@ const SuppliersTable = memo(function SuppliersTable({
const showSupplierReadableId =
companySettings?.showSupplierReadableId ?? false;
- const infinite = useMemo(
- () => ({ dataKey: "suppliers", nextCursor, listKey: "suppliers" }),
- [nextCursor]
- );
-
const customColumns = useCustomColumns<SupplierRow>("supplier");
const columns = useMemo<ColumnDef<SupplierRow>[]>(() => {
const idColumn: ColumnDef<SupplierRow> = {
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuotesTable.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuotesTable.tsx
index 1d4e8e1f7f..d3990863f7 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuotesTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuotesTable.tsx
@@ -33,6 +33,7 @@ import {
Table
} from "~/components";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { usePeople, useSuppliers } from "~/stores";
@@ -47,12 +48,11 @@ import {
type SupplierQuotesTableProps = {
data: SupplierQuote[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const SupplierQuotesTable = memo(
- ({ data, count, nextCursor }: SupplierQuotesTableProps) => {
+ ({ data, count, infinite }: SupplierQuotesTableProps) => {
const { t } = useLingui();
const permissions = usePermissions();
const navigate = useNavigate();
@@ -274,11 +274,7 @@ const SupplierQuotesTable = memo(
count={count}
columns={columns}
data={data}
- infinite={{
- dataKey: "quotes",
- nextCursor,
- listKey: "supplier-quotes"
- }}
+ infinite={infinite}
defaultColumnPinning={{
left: ["supplierQuoteId"]
}}
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierTypes/SupplierTypesTable.tsx b/apps/erp/app/modules/purchasing/ui/SupplierTypes/SupplierTypesTable.tsx
index fa658cc3b8..7dab7ac179 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierTypes/SupplierTypesTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierTypes/SupplierTypesTable.tsx
@@ -11,6 +11,7 @@ import { LuPencil, LuShapes, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import type { SupplierType } from "~/modules/purchasing/types";
@@ -19,12 +20,11 @@ import { path } from "~/utils/path";
type SupplierTypesTableProps = {
data: SupplierType[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const SupplierTypesTable = memo((props: SupplierTypesTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const [params] = useUrlParams();
const { t } = useLingui();
const navigate = useNavigate();
@@ -99,11 +99,7 @@ const SupplierTypesTable = memo((props: SupplierTypesTableProps) => {
data={data}
columns={columns}
count={count}
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "supplier-types"
- }}
+ infinite={infinite}
primaryAction={
permissions.can("create", "purchasing") && (
<New
diff --git a/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx b/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx
index 591f4ab1a0..0228567db1 100644
--- a/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx
+++ b/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx
@@ -26,6 +26,7 @@ import { useNavigate } from "react-router";
import { DateTime, EmployeeAvatar, Hyperlink, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { EnumerableGroup } from "~/components/EnumerableGroup";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { useItems } from "~/stores";
import { usePeople } from "~/stores/people";
@@ -40,7 +41,7 @@ type ActionsTableProps = {
issueTypes: ListItem[];
requiredActions: ListItem[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const ActionsTable = memo(
@@ -49,7 +50,7 @@ const ActionsTable = memo(
issueTypes,
requiredActions,
count,
- nextCursor
+ infinite
}: ActionsTableProps) => {
const { t } = useLingui();
const navigate = useNavigate();
@@ -264,11 +265,7 @@ const ActionsTable = memo(
return (
<Table<QualityAction>
data={data}
- infinite={{
- dataKey: "actions",
- nextCursor,
- listKey: "quality-actions"
- }}
+ infinite={infinite}
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.tsx
index 7989cd323b..783c5d1b5f 100644
--- a/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable.tsx
+++ b/apps/erp/app/modules/quality/ui/Calibrations/GaugeCalibrationRecordsTable.tsx
@@ -40,6 +40,7 @@ import {
} from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import {
usePercentFormatter,
usePermissions,
@@ -57,7 +58,7 @@ type GaugeCalibrationRecordsTableProps = {
data: GaugeCalibrationRecord[];
types: ListItem[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const defaultColumnVisibility = {
@@ -71,7 +72,7 @@ const defaultColumnVisibility = {
};
const GaugeCalibrationRecordsTable = memo(
- ({ data, types, count, nextCursor }: GaugeCalibrationRecordsTableProps) => {
+ ({ data, types, count, infinite }: GaugeCalibrationRecordsTableProps) => {
const [params] = useUrlParams();
const navigate = useNavigate();
const { t } = useLingui();
@@ -399,11 +400,7 @@ const GaugeCalibrationRecordsTable = memo(
<>
<Table<GaugeCalibrationRecord>
data={data}
- infinite={{
- dataKey: "gaugeCalibrationRecords",
- nextCursor,
- listKey: "gauge-calibration-records"
- }}
+ infinite={infinite}
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.tsx
index 7da2fbace8..b5fe46ead3 100644
--- a/apps/erp/app/modules/quality/ui/Documents/QualityDocumentsTable.tsx
+++ b/apps/erp/app/modules/quality/ui/Documents/QualityDocumentsTable.tsx
@@ -34,6 +34,7 @@ import {
import { useNavigate } from "react-router";
import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import type { action as seedAction } from "~/routes/api+/quality.documents.seed";
import { path } from "~/utils/path";
@@ -43,12 +44,12 @@ import QualityDocumentStatus from "./QualityDocumentStatus";
type QualityDocumentsTableProps = {
data: QualityDocuments[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
tags: Array<{ name: string }>;
};
const QualityDocumentsTable = memo(
- ({ data, count, tags, nextCursor }: QualityDocumentsTableProps) => {
+ ({ data, count, tags, infinite }: QualityDocumentsTableProps) => {
const navigate = useNavigate();
const { t } = useLingui();
const permissions = usePermissions();
@@ -224,11 +225,7 @@ const QualityDocumentsTable = memo(
<>
<Table<QualityDocuments>
data={data}
- infinite={{
- dataKey: "qualityDocuments",
- nextCursor,
- listKey: "quality-documents"
- }}
+ infinite={infinite}
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.tsx
index 481cdca93b..c71e1adfaf 100644
--- a/apps/erp/app/modules/quality/ui/Gauge/GaugesTable.tsx
+++ b/apps/erp/app/modules/quality/ui/Gauge/GaugesTable.tsx
@@ -41,6 +41,7 @@ import {
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
import { Confirm, ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { usePeople } from "~/stores/people";
@@ -59,7 +60,7 @@ type GaugesTableProps = {
data: Gauge[];
types: ListItem[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const defaultColumnVisibility = {
@@ -69,7 +70,7 @@ const defaultColumnVisibility = {
};
const GaugesTable = memo((props: GaugesTableProps) => {
- const { data, types, count, nextCursor } = props;
+ const { data, types, count, infinite } = props;
const [params] = useUrlParams();
const navigate = useNavigate();
const { t } = useLingui();
@@ -398,11 +399,7 @@ const GaugesTable = memo((props: GaugesTableProps) => {
<>
<Table<Gauge>
data={data}
- infinite={{
- dataKey: "gauges",
- nextCursor,
- listKey: "gauges"
- }}
+ infinite={infinite}
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.tsx
index 4cefe1b533..64549f6fc1 100644
--- a/apps/erp/app/modules/quality/ui/GaugeTypes/GaugeTypesTable.tsx
+++ b/apps/erp/app/modules/quality/ui/GaugeTypes/GaugeTypesTable.tsx
@@ -10,6 +10,7 @@ import { LuCircleGauge, LuPencil, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
@@ -18,11 +19,11 @@ import type { GaugeType } from "../../types";
type GaugeTypesTableProps = {
data: GaugeType[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const GaugeTypesTable = memo((props: GaugeTypesTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const [params] = useUrlParams();
const navigate = useNavigate();
const { t } = useLingui();
@@ -84,11 +85,7 @@ const GaugeTypesTable = memo((props: GaugeTypesTableProps) => {
return (
<Table<GaugeType>
data={data}
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "gauge-types"
- }}
+ infinite={infinite}
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.tsx
index b270f01143..cbcdd09e5c 100644
--- a/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentTable.tsx
+++ b/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentTable.tsx
@@ -24,6 +24,7 @@ import {
import { useNavigate } from "react-router";
import { DateTime, EmployeeAvatar, Hyperlink, New, Table } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useItems } from "~/stores/items";
import { path } from "~/utils/path";
@@ -32,7 +33,7 @@ import type { InspectionDocument } from "../../types";
type InspectionDocumentTableProps = {
data: InspectionDocument[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const defaultColumnVisibility = {
@@ -42,7 +43,7 @@ const defaultColumnVisibility = {
};
const InspectionDocumentTable = memo(
- ({ data, count, nextCursor }: InspectionDocumentTableProps) => {
+ ({ data, count, infinite }: InspectionDocumentTableProps) => {
const [params] = useUrlParams();
const navigate = useNavigate();
const { t } = useLingui();
@@ -173,11 +174,7 @@ const InspectionDocumentTable = memo(
<>
<Table<InspectionDocument>
data={data}
- infinite={{
- dataKey: "diagrams",
- nextCursor,
- listKey: "inspection-plans"
- }}
+ infinite={infinite}
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.tsx
index 8c24fcb684..fdc4aba25c 100644
--- a/apps/erp/app/modules/quality/ui/Inspections/InspectionsTable.tsx
+++ b/apps/erp/app/modules/quality/ui/Inspections/InspectionsTable.tsx
@@ -22,6 +22,7 @@ import {
Hyperlink,
Table
} from "~/components";
+import type { InfiniteOptions } from "~/components/Table";
import { useUrlParams } from "~/hooks";
import {
inspectionSourceDocuments,
@@ -35,7 +36,7 @@ import { getInspectionStatusVariant } from "./InspectionStatus";
type InspectionsTableProps = {
data: Inspection[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
function computeProgress(row: Inspection): {
@@ -51,7 +52,7 @@ function computeProgress(row: Inspection): {
}
const InspectionsTable = memo((props: InspectionsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const [params] = useUrlParams();
const [items] = useItems();
@@ -204,11 +205,7 @@ const InspectionsTable = memo((props: InspectionsTableProps) => {
return (
<Table<Inspection>
data={data}
- infinite={{
- dataKey: "inspections",
- nextCursor,
- listKey: "inspections"
- }}
+ infinite={infinite}
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.tsx
index 4bf29ca071..455e8d6ef4 100644
--- a/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsx
@@ -33,6 +33,7 @@ import { Enumerable } from "~/components/Enumerable";
import { EnumerableGroup } from "~/components/EnumerableGroup";
import { useLocations } from "~/components/Form/Location";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { useItems } from "~/stores/items";
@@ -52,11 +53,11 @@ type IssuesTableProps = {
data: Issue[];
types: ListItem[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const IssuesTable = memo((props: IssuesTableProps) => {
- const { data, types, count, nextCursor } = props;
+ const { data, types, count, infinite } = props;
const navigate = useNavigate();
const { t } = useLingui();
const permissions = usePermissions();
@@ -360,11 +361,7 @@ const IssuesTable = memo((props: IssuesTableProps) => {
<>
<Table<Issue>
data={data}
- infinite={{
- dataKey: "issues",
- nextCursor,
- listKey: "issues"
- }}
+ infinite={infinite}
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.tsx
index d926f62a03..0d5372d4d3 100644
--- a/apps/erp/app/modules/quality/ui/IssueTypes/IssueTypesTable.tsx
+++ b/apps/erp/app/modules/quality/ui/IssueTypes/IssueTypesTable.tsx
@@ -10,6 +10,7 @@ import { LuOctagonX, LuPencil, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
@@ -18,11 +19,11 @@ import type { IssueType } from "../../types";
type IssueTypesTableProps = {
data: IssueType[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const IssueTypesTable = memo((props: IssueTypesTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const [params] = useUrlParams();
const navigate = useNavigate();
const { t } = useLingui();
@@ -84,11 +85,7 @@ const IssueTypesTable = memo((props: IssueTypesTableProps) => {
return (
<Table<IssueType>
data={data}
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "issue-types"
- }}
+ infinite={infinite}
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.tsx
index 6c4fd26d3a..04b9dabbd9 100644
--- a/apps/erp/app/modules/quality/ui/IssueWorkflows/IssueWorkflowsTable.tsx
+++ b/apps/erp/app/modules/quality/ui/IssueWorkflows/IssueWorkflowsTable.tsx
@@ -22,6 +22,7 @@ import {
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { path } from "~/utils/path";
import type { IssueWorkflow } from "../../types";
@@ -30,11 +31,11 @@ import { getPriorityIcon, getSourceIcon } from "../Issue/IssueIcons";
type IssueWorkflowsTableProps = {
data: IssueWorkflow[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const IssueWorkflowsTable = memo(
- ({ data, count, nextCursor }: IssueWorkflowsTableProps) => {
+ ({ data, count, infinite }: IssueWorkflowsTableProps) => {
const navigate = useNavigate();
const { t } = useLingui();
const permissions = usePermissions();
@@ -129,11 +130,7 @@ const IssueWorkflowsTable = memo(
<>
<Table<IssueWorkflow>
data={data}
- infinite={{
- dataKey: "procedures",
- nextCursor,
- listKey: "issue-workflows"
- }}
+ infinite={infinite}
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.tsx
index 522a52630e..db0fbee9e7 100644
--- a/apps/erp/app/modules/quality/ui/RequiredActions/RequiredActionsTable.tsx
+++ b/apps/erp/app/modules/quality/ui/RequiredActions/RequiredActionsTable.tsx
@@ -18,6 +18,7 @@ import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
import type { RequiredAction } from "../../types";
@@ -25,11 +26,11 @@ import type { RequiredAction } from "../../types";
type RequiredActionsTableProps = {
data: RequiredAction[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const RequiredActionsTable = memo(
- ({ data, count, nextCursor }: RequiredActionsTableProps) => {
+ ({ data, count, infinite }: RequiredActionsTableProps) => {
const [params] = useUrlParams();
const navigate = useNavigate();
const { t } = useLingui();
@@ -104,11 +105,7 @@ const RequiredActionsTable = memo(
<>
<Table<RequiredAction>
data={data}
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "required-actions"
- }}
+ infinite={infinite}
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.tsx
index 422013f306..e34ffb8c4b 100644
--- a/apps/erp/app/modules/quality/ui/RiskRegister/RiskRegistersTable.tsx
+++ b/apps/erp/app/modules/quality/ui/RiskRegister/RiskRegistersTable.tsx
@@ -35,6 +35,7 @@ import {
import { Enumerable } from "~/components/Enumerable";
import { useWorkCenters } from "~/components/Form/WorkCenter";
import { Confirm } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import {
riskRegisterType,
@@ -51,7 +52,7 @@ import RiskType from "./RiskType";
type RiskRegistersTableProps = {
data: Risk[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const defaultColumnVisibility = {
@@ -62,7 +63,7 @@ const defaultColumnVisibility = {
};
const RiskRegistersTable = memo((props: RiskRegistersTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const navigate = useNavigate();
const [params] = useUrlParams();
const workCenters = useWorkCenters({});
@@ -286,11 +287,7 @@ const RiskRegistersTable = memo((props: RiskRegistersTableProps) => {
<>
<Table<Risk>
data={data}
- infinite={{
- dataKey: "risks",
- nextCursor,
- listKey: "risks"
- }}
+ infinite={infinite}
defaultColumnVisibility={defaultColumnVisibility}
columns={columns}
count={count ?? 0}
diff --git a/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsx b/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsx
index 9ea631a3c4..175bc699a9 100644
--- a/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsx
+++ b/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsx
@@ -16,6 +16,7 @@ import {
import { useNavigate } from "react-router";
import { EmployeeAvatarGroup, Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import type { Abilities } from "~/modules/resources/types";
import { usePeople } from "~/stores";
@@ -26,11 +27,11 @@ type Ability = Abilities[number];
type AbilitiesTableProps = {
data: Abilities;
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const AbilitiesTable = memo((props: AbilitiesTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const navigate = useNavigate();
const [params] = useUrlParams();
@@ -129,7 +130,7 @@ const AbilitiesTable = memo((props: AbilitiesTableProps) => {
return (
<Table<Ability>
data={data}
- infinite={{ dataKey: "abilities", nextCursor, listKey: "abilities" }}
+ infinite={infinite}
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.tsx
index 65b3b28c39..bfc79e1a16 100644
--- a/apps/erp/app/modules/resources/ui/Contractors/ContractorsTable.tsx
+++ b/apps/erp/app/modules/resources/ui/Contractors/ContractorsTable.tsx
@@ -15,6 +15,7 @@ import { memo, useCallback, useMemo } from "react";
import { LuPencil, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, SupplierAvatar, Table } from "~/components";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import type { Contractor } from "~/modules/resources/types";
@@ -24,12 +25,12 @@ import { path } from "~/utils/path";
type ContractorsTableProps = {
data: Contractor[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
// abilities: Partial<Ability>[];
};
const ContractorsTable = memo((props: ContractorsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const navigate = useNavigate();
const permissions = usePermissions();
@@ -164,11 +165,7 @@ const ContractorsTable = memo((props: ContractorsTableProps) => {
data={data}
count={count}
columns={columns}
- infinite={{
- dataKey: "contractors",
- nextCursor,
- listKey: "contractors"
- }}
+ infinite={infinite}
getRowId={(row) => String(row.supplierContactId)}
primaryAction={
permissions.can("create", "resources") && (
diff --git a/apps/erp/app/modules/resources/ui/FailureModes/FailureModesTable.tsx b/apps/erp/app/modules/resources/ui/FailureModes/FailureModesTable.tsx
index 1164f9146f..7bbec7bb25 100644
--- a/apps/erp/app/modules/resources/ui/FailureModes/FailureModesTable.tsx
+++ b/apps/erp/app/modules/resources/ui/FailureModes/FailureModesTable.tsx
@@ -10,6 +10,7 @@ import { LuCircleAlert, LuPencil, LuShapes, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
import { maintenanceFailureModeType } from "../../resources.models";
@@ -18,11 +19,11 @@ import type { FailureMode } from "../../types";
type FailureModesTableProps = {
data: FailureMode[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const FailureModesTable = memo((props: FailureModesTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -98,7 +99,7 @@ const FailureModesTable = memo((props: FailureModesTableProps) => {
return (
<Table<FailureMode>
data={data}
- infinite={{ dataKey: "data", nextCursor, listKey: "failure-modes" }}
+ infinite={infinite}
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.tsx
index 489967bf11..3f576fd2ed 100644
--- a/apps/erp/app/modules/resources/ui/Locations/LocationsTable.tsx
+++ b/apps/erp/app/modules/resources/ui/Locations/LocationsTable.tsx
@@ -20,6 +20,7 @@ import {
import { useNavigate } from "react-router";
import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import type { ShiftLocation } from "~/modules/resources/types";
@@ -29,11 +30,11 @@ import { path } from "~/utils/path";
type LocationsTableProps = {
data: ShiftLocation[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const LocationsTable = memo((props: LocationsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const navigate = useNavigate();
const permissions = usePermissions();
@@ -176,7 +177,7 @@ const LocationsTable = memo((props: LocationsTableProps) => {
return (
<Table<(typeof data)[number]>
data={data}
- infinite={{ dataKey: "locations", nextCursor, listKey: "locations" }}
+ infinite={infinite}
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.tsx
index 12cef47bc7..180645a343 100644
--- a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchesTable.tsx
+++ b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchesTable.tsx
@@ -28,6 +28,7 @@ import { useNavigate } from "react-router";
import { DateTime, EmployeeAvatar, Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useWorkCenters } from "~/components/Form/WorkCenters";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { usePeople } from "~/stores";
import type { ListItem } from "~/types";
@@ -47,7 +48,7 @@ import MaintenanceStatus from "./MaintenanceStatus";
type MaintenanceDispatchesTableProps = {
data: MaintenanceDispatch[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
failureModes: ListItem[];
locations: { id: string; name: string }[];
locationId: string | null;
@@ -57,7 +58,7 @@ const MaintenanceDispatchesTable = memo(
({
data,
count,
- nextCursor,
+ infinite,
failureModes,
locations,
locationId
@@ -380,11 +381,7 @@ const MaintenanceDispatchesTable = memo(
return (
<Table<MaintenanceDispatch>
data={data}
- infinite={{
- dataKey: "dispatches",
- nextCursor,
- listKey: "maintenance-dispatches"
- }}
+ infinite={infinite}
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.tsx
index 21ce147011..981e422795 100644
--- a/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceSchedulesTable.tsx
+++ b/apps/erp/app/modules/resources/ui/MaintenanceSchedule/MaintenanceSchedulesTable.tsx
@@ -30,6 +30,7 @@ import { useNavigate } from "react-router";
import { DateTime, Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
import {
@@ -42,7 +43,7 @@ import MaintenancePriority from "../Maintenance/MaintenancePriority";
type MaintenanceSchedulesTableProps = {
data: MaintenanceSchedule[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
locations: { id: string; name: string }[];
locationId: string | null;
};
@@ -51,7 +52,7 @@ const MaintenanceSchedulesTable = memo(
({
data,
count,
- nextCursor,
+ infinite,
locations,
locationId
}: MaintenanceSchedulesTableProps) => {
@@ -284,11 +285,7 @@ const MaintenanceSchedulesTable = memo(
return (
<Table<MaintenanceSchedule>
data={data}
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "maintenance-schedules"
- }}
+ infinite={infinite}
columns={columns}
count={count}
primaryAction={
diff --git a/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx b/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx
index 52852fe92f..15e565fb5e 100644
--- a/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx
+++ b/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx
@@ -44,6 +44,7 @@ import {
import { Enumerable } from "~/components/Enumerable";
import { EnumerableGroup } from "~/components/EnumerableGroup";
import { useWorkCenters } from "~/components/Form/WorkCenter";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import type { Process } from "~/modules/resources/types";
@@ -58,7 +59,7 @@ import { path } from "~/utils/path";
type ProcessesTableProps = {
data: Process[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const defaultColumnVisibility = {
@@ -69,7 +70,7 @@ const defaultColumnVisibility = {
};
const ProcessesTable = memo((props: ProcessesTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const navigate = useNavigate();
const permissions = usePermissions();
@@ -393,7 +394,7 @@ const ProcessesTable = memo((props: ProcessesTableProps) => {
return (
<Table<Process>
data={data}
- infinite={{ dataKey: "processes", nextCursor, listKey: "processes" }}
+ infinite={infinite}
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.tsx
index 223e2959c8..8abfb6e822 100644
--- a/apps/erp/app/modules/resources/ui/Suggestions/SuggestionsTable.tsx
+++ b/apps/erp/app/modules/resources/ui/Suggestions/SuggestionsTable.tsx
@@ -24,6 +24,7 @@ import {
} from "react-icons/lu";
import { useNavigate } from "react-router";
import { DateTime, Hyperlink, Table } from "~/components";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import type { SuggestionListItem } from "~/modules/resources/types";
import { usePeople } from "~/stores";
@@ -33,13 +34,13 @@ type SuggestionsTableProps = {
data: SuggestionListItem[];
tags: { name: string }[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const defaultColumnVisibility = {};
const SuggestionsTable = memo(
- ({ data, tags, count, nextCursor }: SuggestionsTableProps) => {
+ ({ data, tags, count, infinite }: SuggestionsTableProps) => {
const { t } = useLingui();
const navigate = useNavigate();
const permissions = usePermissions();
@@ -170,11 +171,7 @@ const SuggestionsTable = memo(
return (
<Table<SuggestionListItem>
data={data}
- infinite={{
- dataKey: "suggestions",
- nextCursor,
- listKey: "suggestions"
- }}
+ infinite={infinite}
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.tsx
index e7fe034c2e..a259b36297 100644
--- a/apps/erp/app/modules/resources/ui/Training/TrainingsTable.tsx
+++ b/apps/erp/app/modules/resources/ui/Training/TrainingsTable.tsx
@@ -30,6 +30,7 @@ import { useNavigate } from "react-router";
import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import type { TrainingListItem } from "~/modules/resources/types";
import { path } from "~/utils/path";
@@ -38,12 +39,12 @@ import TrainingStatus from "./TrainingStatus";
type TrainingsTableProps = {
data: TrainingListItem[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
tags: Array<{ name: string }>;
};
const TrainingsTable = memo((props: TrainingsTableProps) => {
- const { data, count, nextCursor, tags } = props;
+ const { data, count, infinite, tags } = props;
const { t } = useLingui();
const navigate = useNavigate();
const permissions = usePermissions();
@@ -243,7 +244,7 @@ const TrainingsTable = memo((props: TrainingsTableProps) => {
<>
<Table<TrainingListItem>
data={data}
- infinite={{ dataKey: "trainings", nextCursor, listKey: "trainings" }}
+ infinite={infinite}
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.tsx
index c729bf38ff..5072717a95 100644
--- a/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx
+++ b/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx
@@ -48,6 +48,7 @@ import { Enumerable } from "~/components/Enumerable";
import { EnumerableGroup } from "~/components/EnumerableGroup";
import { useProcesses } from "~/components/Form/Process";
import { Confirm } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import {
useCurrencyFormatter,
usePermissions,
@@ -65,7 +66,7 @@ const logger = getLogger("erp", "workcenterstable");
type WorkCentersTableProps = {
data: WorkCenter[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
departments: ListItem[];
locations: ListItem[];
};
@@ -82,7 +83,7 @@ const WorkCentersTable = memo(
({
data,
count,
- nextCursor,
+ infinite,
departments,
locations
}: WorkCentersTableProps) => {
@@ -355,11 +356,7 @@ const WorkCentersTable = memo(
<>
<Table<WorkCenter>
data={data}
- infinite={{
- dataKey: "workCenters",
- nextCursor,
- listKey: "work-centers"
- }}
+ infinite={infinite}
defaultColumnVisibility={defaultColumnVisibility}
columns={columns}
count={count ?? 0}
diff --git a/apps/erp/app/modules/sales/ui/Contracts/ContractsTable.tsx b/apps/erp/app/modules/sales/ui/Contracts/ContractsTable.tsx
index d8f175fb00..ea3608eb33 100644
--- a/apps/erp/app/modules/sales/ui/Contracts/ContractsTable.tsx
+++ b/apps/erp/app/modules/sales/ui/Contracts/ContractsTable.tsx
@@ -21,6 +21,7 @@ import {
import { useNavigate } from "react-router";
import { CustomerAvatar, Hyperlink, New, Table } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import {
useCurrencyFormatter,
useDateFormatter,
@@ -40,12 +41,11 @@ import type { ContractListItem } from "./types";
type ContractsTableProps = {
data: ContractListItem[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const ContractsTable = memo((props: ContractsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const permissions = usePermissions();
const navigate = useNavigate();
@@ -245,11 +245,7 @@ const ContractsTable = memo((props: ContractsTableProps) => {
<>
<Table<ContractListItem>
count={count}
- infinite={{
- dataKey: "contracts",
- nextCursor,
- listKey: "contracts"
- }}
+ infinite={infinite}
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.tsx
index 0dfb580c69..f95c931d63 100644
--- a/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsTable.ee.tsx
+++ b/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsTable.ee.tsx
@@ -15,6 +15,7 @@ import {
} from "react-icons/lu";
import { useNavigate } from "react-router";
import { CustomerAvatar, Hyperlink, New, Table } from "~/components";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
@@ -24,12 +25,11 @@ type CustomerPortalsTableProps = {
appUrl: string;
data: CustomerPortal[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const CustomerPortalsTable = memo(
- ({ appUrl, data, count, nextCursor }: CustomerPortalsTableProps) => {
+ ({ appUrl, data, count, infinite }: CustomerPortalsTableProps) => {
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -127,11 +127,7 @@ const CustomerPortalsTable = memo(
data={data}
columns={columns}
count={count}
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "customer-portals"
- }}
+ infinite={infinite}
primaryAction={
permissions.can("create", "sales") && (
<New
diff --git a/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsUpgradeOverlay.tsx b/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsUpgradeOverlay.tsx
index 19d590d11f..98fff65f31 100644
--- a/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsUpgradeOverlay.tsx
+++ b/apps/erp/app/modules/sales/ui/CustomerPortals/CustomerPortalsUpgradeOverlay.tsx
@@ -61,7 +61,7 @@ export default function CustomerPortalsUpgradeOverlay() {
appUrl="https://app.carbon.ms"
data={mockPortals}
count={mockPortals.length}
- nextCursor={null}
+ infinite={{ dataKey: "data", 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.tsx
index 1e4d8f6bd0..f0b3c637dc 100644
--- a/apps/erp/app/modules/sales/ui/CustomerStatuses/CustomerStatusesTable.tsx
+++ b/apps/erp/app/modules/sales/ui/CustomerStatuses/CustomerStatusesTable.tsx
@@ -11,6 +11,7 @@ import { LuPencil, LuStar, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
@@ -19,12 +20,11 @@ import type { CustomerStatus } from "../../types";
type CustomerStatusesTableProps = {
data: CustomerStatus[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const CustomerStatusesTable = memo(
- ({ data, count, nextCursor }: CustomerStatusesTableProps) => {
+ ({ data, count, infinite }: CustomerStatusesTableProps) => {
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -98,11 +98,7 @@ const CustomerStatusesTable = memo(
data={data}
columns={columns}
count={count}
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "customer-statuses"
- }}
+ infinite={infinite}
primaryAction={
permissions.can("create", "sales") && (
<New
diff --git a/apps/erp/app/modules/sales/ui/CustomerTypes/CustomerTypesTable.tsx b/apps/erp/app/modules/sales/ui/CustomerTypes/CustomerTypesTable.tsx
index 4813e7503f..c307c1451a 100644
--- a/apps/erp/app/modules/sales/ui/CustomerTypes/CustomerTypesTable.tsx
+++ b/apps/erp/app/modules/sales/ui/CustomerTypes/CustomerTypesTable.tsx
@@ -11,6 +11,7 @@ import { LuPencil, LuShapes, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
@@ -19,12 +20,11 @@ import type { CustomerType } from "../../types";
type CustomerTypesTableProps = {
data: CustomerType[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const CustomerTypesTable = memo((props: CustomerTypesTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -99,11 +99,7 @@ const CustomerTypesTable = memo((props: CustomerTypesTableProps) => {
data={data}
columns={columns}
count={count}
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "customer-types"
- }}
+ infinite={infinite}
primaryAction={
permissions.can("create", "sales") && (
<New
diff --git a/apps/erp/app/modules/sales/ui/Customers/CustomersTable.tsx b/apps/erp/app/modules/sales/ui/Customers/CustomersTable.tsx
index 53596b770c..aaffb88a02 100644
--- a/apps/erp/app/modules/sales/ui/Customers/CustomersTable.tsx
+++ b/apps/erp/app/modules/sales/ui/Customers/CustomersTable.tsx
@@ -41,6 +41,7 @@ import {
import { Enumerable } from "~/components/Enumerable";
import { useCustomerTypes } from "~/components/Form/CustomerType";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { useCompanySettings, usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { usePeople } from "~/stores";
@@ -50,20 +51,13 @@ 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;
+ infinite: InfiniteOptions;
customerStatuses: CustomerStatus[];
tags: { name: string }[];
};
const CustomersTable = memo(
- ({
- data,
- count,
- nextCursor,
- customerStatuses,
- tags
- }: CustomersTableProps) => {
+ ({ data, count, infinite, customerStatuses, tags }: CustomersTableProps) => {
const { t } = useLingui();
const navigate = useNavigate();
const permissions = usePermissions();
@@ -319,11 +313,7 @@ const CustomersTable = memo(
<>
<Table<Customer>
count={count}
- infinite={{
- dataKey: "customers",
- nextCursor,
- listKey: "customers"
- }}
+ infinite={infinite}
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.tsx
index 7ba1ff94e6..895553f365 100644
--- a/apps/erp/app/modules/sales/ui/NoQuoteReasons/NoQuoteReasonsTable.tsx
+++ b/apps/erp/app/modules/sales/ui/NoQuoteReasons/NoQuoteReasonsTable.tsx
@@ -10,6 +10,7 @@ import { LuBookMarked, LuPencil, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
@@ -18,12 +19,11 @@ import type { NoQuoteReason } from "../../types";
type NoQuoteReasonsTableProps = {
data: NoQuoteReason[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const NoQuoteReasonsTable = memo(
- ({ data, count, nextCursor }: NoQuoteReasonsTableProps) => {
+ ({ data, count, infinite }: NoQuoteReasonsTableProps) => {
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -88,11 +88,7 @@ const NoQuoteReasonsTable = memo(
data={data}
columns={columns}
count={count}
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "no-quote-reasons"
- }}
+ infinite={infinite}
primaryAction={
permissions.can("create", "sales") && (
<New
diff --git a/apps/erp/app/modules/sales/ui/Pricing/PriceOverridesTable.tsx b/apps/erp/app/modules/sales/ui/Pricing/PriceOverridesTable.tsx
index c5d908312c..004f4af252 100644
--- a/apps/erp/app/modules/sales/ui/Pricing/PriceOverridesTable.tsx
+++ b/apps/erp/app/modules/sales/ui/Pricing/PriceOverridesTable.tsx
@@ -47,6 +47,7 @@ import { useNavigate, useSearchParams } from "react-router";
import { DateTime, Hyperlink, ItemThumbnail, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";
+import type { InfiniteOptions } from "~/components/Table";
import { useCurrencyFormatter, usePermissions, useUser } from "~/hooks";
import type { PriceListRow } from "~/modules/sales/types";
import { path } from "~/utils/path";
@@ -58,8 +59,7 @@ 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;
+ infinite: InfiniteOptions;
scopeOptions: ScopeOption[];
hasScope: boolean;
};
@@ -76,13 +76,7 @@ const sourceVariant: Record<
};
const PriceListTable = memo(
- ({
- data,
- count,
- nextCursor,
- scopeOptions,
- hasScope
- }: PriceListTableProps) => {
+ ({ data, count, infinite, scopeOptions, hasScope }: PriceListTableProps) => {
const { t } = useLingui();
const permissions = usePermissions();
const currencyFormatter = useCurrencyFormatter();
@@ -386,11 +380,7 @@ const PriceListTable = memo(
data={data}
columns={columns}
count={count}
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "price-list"
- }}
+ infinite={infinite}
primaryAction={
<div className="flex items-center gap-2">
<ScopePicker
diff --git a/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx b/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx
index b7b102de66..ba62f9edbe 100644
--- a/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx
+++ b/apps/erp/app/modules/sales/ui/Pricing/PricingRulesTable.tsx
@@ -34,6 +34,7 @@ import { CustomerAvatar, Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useCustomerTypes } from "~/components/Form/CustomerType";
import { useItemPostingGroups } from "~/components/Form/ItemPostingGroup";
+import type { InfiniteOptions } from "~/components/Table";
import {
useCurrencyFormatter,
useDateFormatter,
@@ -50,8 +51,7 @@ import type { PricingRule } from "../../types";
type PricingRulesTableProps = {
data: PricingRule[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const defaultColumnVisibility = {
@@ -62,7 +62,7 @@ const defaultColumnVisibility = {
};
const PricingRulesTable = memo((props: PricingRulesTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const [params] = useUrlParams();
const navigate = useNavigate();
const { t } = useLingui();
@@ -478,11 +478,7 @@ const PricingRulesTable = memo((props: PricingRulesTableProps) => {
data={data}
columns={columns}
count={count}
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "pricing-rules"
- }}
+ infinite={infinite}
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.tsx
index 7f23acc4df..ecaa630fca 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx
@@ -38,6 +38,7 @@ import {
} from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { useCustomers, usePeople } from "~/stores";
@@ -49,11 +50,10 @@ import QuoteStatus from "./QuoteStatus";
type QuotesTableProps = {
data: QuotationListItem[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
-const QuotesTable = memo(({ data, count, nextCursor }: QuotesTableProps) => {
+const QuotesTable = memo(({ data, count, infinite }: QuotesTableProps) => {
const { t } = useLingui();
const permissions = usePermissions();
const navigate = useNavigate();
@@ -353,11 +353,7 @@ const QuotesTable = memo(({ data, count, nextCursor }: QuotesTableProps) => {
<>
<Table<QuotationListItem>
count={count}
- infinite={{
- dataKey: "quotes",
- nextCursor,
- listKey: "quotes"
- }}
+ infinite={infinite}
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.tsx
index 10f240a107..e142d3297f 100644
--- a/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementsTable.tsx
+++ b/apps/erp/app/modules/sales/ui/Rentals/RentalAgreementsTable.tsx
@@ -20,6 +20,7 @@ import {
import { useNavigate } from "react-router";
import { CustomerAvatar, Hyperlink, New, Table } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { useDateFormatter, usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { useCustomers } from "~/stores";
@@ -32,12 +33,11 @@ import type { RentalAgreementListItem } from "./types";
type RentalAgreementsTableProps = {
data: RentalAgreementListItem[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const RentalAgreementsTable = memo(
- ({ data, count, nextCursor }: RentalAgreementsTableProps) => {
+ ({ data, count, infinite }: RentalAgreementsTableProps) => {
const { t } = useLingui();
const permissions = usePermissions();
const navigate = useNavigate();
@@ -198,11 +198,7 @@ const RentalAgreementsTable = memo(
<>
<Table<RentalAgreementListItem>
count={count}
- infinite={{
- dataKey: "rentalAgreements",
- nextCursor,
- listKey: "rental-agreements"
- }}
+ infinite={infinite}
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.tsx
index bc22e41b33..3f73b007fe 100644
--- a/apps/erp/app/modules/sales/ui/ReturnReasons/ReturnReasonsTable.tsx
+++ b/apps/erp/app/modules/sales/ui/ReturnReasons/ReturnReasonsTable.tsx
@@ -16,6 +16,7 @@ import { LuBookMarked, LuCircleSlash, LuPencil, LuTrash } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { path } from "~/utils/path";
@@ -25,12 +26,11 @@ 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;
+ infinite: InfiniteOptions;
};
const ReturnReasonsTable = memo((props: ReturnReasonsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -114,11 +114,7 @@ const ReturnReasonsTable = memo((props: ReturnReasonsTableProps) => {
data={data}
columns={columns}
count={count}
- infinite={{
- dataKey: "data",
- nextCursor,
- listKey: "return-reasons"
- }}
+ infinite={infinite}
primaryAction={
permissions.can("create", "sales") && (
<New
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx
index ad69827f0a..a3ef519d1d 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx
@@ -61,6 +61,7 @@ import { useLocations } from "~/components/Form/Location";
import { usePaymentTerm } from "~/components/Form/PaymentTerm";
import { useShippingMethod } from "~/components/Form/ShippingMethod";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { useCurrencyFormatter, usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import type { jobStatus } from "~/modules/production/production.models";
@@ -75,8 +76,7 @@ import { useSalesOrder } from "./useSalesOrder";
type SalesOrdersTableProps = {
data: SalesOrderListItem[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const IconWithTooltip = ({
@@ -99,7 +99,7 @@ const IconWithTooltip = ({
);
const SalesOrdersTable = memo((props: SalesOrdersTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const permissions = usePermissions();
const currencyFormatter = useCurrencyFormatter();
@@ -586,11 +586,7 @@ const SalesOrdersTable = memo((props: SalesOrdersTableProps) => {
count={count}
columns={columns}
data={data}
- infinite={{
- dataKey: "salesOrders",
- nextCursor,
- listKey: "sales-orders"
- }}
+ infinite={infinite}
defaultColumnPinning={{
left: ["salesOrderId"]
}}
diff --git a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQsTable.tsx b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQsTable.tsx
index 905aa38da8..468e9b6462 100644
--- a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQsTable.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQsTable.tsx
@@ -34,6 +34,7 @@ import {
} from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { useCustomers, usePeople } from "~/stores";
@@ -45,12 +46,11 @@ import { SalesRFQStatus } from ".";
type SalesRFQsTableProps = {
data: SalesRFQ[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const SalesRFQsTable = memo((props: SalesRFQsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const permissions = usePermissions();
const navigate = useNavigate();
@@ -278,11 +278,7 @@ const SalesRFQsTable = memo((props: SalesRFQsTableProps) => {
<>
<Table<SalesRFQ>
count={count}
- infinite={{
- dataKey: "rfqs",
- nextCursor,
- listKey: "sales-rfqs"
- }}
+ infinite={infinite}
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.tsx
index c5f253f6e9..74da15af17 100644
--- a/apps/erp/app/modules/sales/ui/SalesReturnOrders/SalesReturnOrdersTable.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesReturnOrders/SalesReturnOrdersTable.tsx
@@ -32,6 +32,7 @@ import {
Table
} from "~/components";
import { ConfirmDelete } from "~/components/Modals";
+import type { InfiniteOptions } from "~/components/Table";
import { useDateFormatter, usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
import { useCustomers, usePeople } from "~/stores";
@@ -43,12 +44,11 @@ import type { SalesReturnOrderListItem } from "./types";
type SalesReturnOrdersTableProps = {
data: SalesReturnOrderListItem[];
count: number;
- // The loader's cursor for the next page (infinite scroll).
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const SalesReturnOrdersTable = memo(
- ({ data, count, nextCursor }: SalesReturnOrdersTableProps) => {
+ ({ data, count, infinite }: SalesReturnOrdersTableProps) => {
const { t } = useLingui();
const permissions = usePermissions();
const navigate = useNavigate();
@@ -230,11 +230,7 @@ const SalesReturnOrdersTable = memo(
<>
<Table<SalesReturnOrderListItem>
count={count}
- infinite={{
- dataKey: "salesReturnOrders",
- nextCursor,
- listKey: "sales-return-orders"
- }}
+ infinite={infinite}
columns={columns}
data={data}
defaultColumnPinning={{
diff --git a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx
index 4307c6a21c..5000674673 100644
--- a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx
+++ b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx
@@ -26,6 +26,7 @@ import {
} from "react-icons/lu";
import { Outlet, useNavigate } from "react-router";
import { DateTime, EmployeeAvatar, Hyperlink, New, Table } from "~/components";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import type { ApiKey } from "~/modules/settings/types";
import { usePeople } from "~/stores";
@@ -37,7 +38,7 @@ type ApiKeyRow = Omit<ApiKey, "keyHash">;
type ApiKeysTableProps = {
data: ApiKeyRow[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
// `apiKey.scopes` is a `Json` column; narrow it to the scope map shape once so
@@ -64,7 +65,7 @@ function formatRateLimit(limit: number, window: string): string {
}
const ApiKeysTable = memo((props: ApiKeysTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const navigate = useNavigate();
const [params] = useUrlParams();
@@ -231,7 +232,7 @@ const ApiKeysTable = memo((props: ApiKeysTableProps) => {
<>
<Table<ApiKeyRow>
data={data}
- infinite={{ dataKey: "apiKeys", nextCursor, listKey: "api-keys" }}
+ infinite={infinite}
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.tsx
index 5f7bf4c037..53502a24d7 100644
--- a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysUpgradeOverlay.tsx
+++ b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysUpgradeOverlay.tsx
@@ -101,7 +101,7 @@ export default function ApiKeysUpgradeOverlay() {
<ApiKeysTable
data={mockApiKeys}
count={mockApiKeys.length}
- nextCursor={null}
+ infinite={{ dataKey: "data", nextCursor: null }}
/>
</UpgradeOverlayPreview>
<UpgradeOverlayCard>
diff --git a/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsx b/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsx
index 0a4cc94bad..1554f9151a 100644
--- a/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsx
+++ b/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsx
@@ -18,6 +18,7 @@ import { LuDatabase, LuLayoutGrid, LuList, LuTags } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import { modulesType } from "~/modules/settings/settings.models";
import type { CustomFieldsTableType } from "~/modules/settings/types";
@@ -27,11 +28,11 @@ import { path } from "~/utils/path";
type CustomFieldsTableProps = {
data: CustomFieldsTableType[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const CustomFieldsTable = memo((props: CustomFieldsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const navigate = useNavigate();
const [params] = useUrlParams();
@@ -141,11 +142,7 @@ const CustomFieldsTable = memo((props: CustomFieldsTableProps) => {
data={data}
columns={columns}
count={count ?? 0}
- infinite={{
- dataKey: "tables",
- nextCursor,
- listKey: "custom-field-tables"
- }}
+ infinite={infinite}
getRowId={(row) => String(row.table)}
title={t`Custom Fields`}
renderContextMenu={renderContextMenu}
diff --git a/apps/erp/app/modules/settings/ui/Sequences/SequencesTable.tsx b/apps/erp/app/modules/settings/ui/Sequences/SequencesTable.tsx
index a50d365661..6c4f40fe0a 100644
--- a/apps/erp/app/modules/settings/ui/Sequences/SequencesTable.tsx
+++ b/apps/erp/app/modules/settings/ui/Sequences/SequencesTable.tsx
@@ -17,6 +17,7 @@ import {
} from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, Table } from "~/components";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import type { Sequence } from "~/modules/settings/types";
import { path } from "~/utils/path";
@@ -24,11 +25,11 @@ import { path } from "~/utils/path";
type SequencesTableProps = {
data: Sequence[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const SequencesTable = memo((props: SequencesTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -117,7 +118,7 @@ const SequencesTable = memo((props: SequencesTableProps) => {
return (
<Table<(typeof data)[number]>
data={data}
- infinite={{ dataKey: "data", nextCursor, listKey: "sequences" }}
+ infinite={infinite}
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.tsx
index 0ec3ec1bbd..e7e3bc62a7 100644
--- a/apps/erp/app/modules/settings/ui/SerialNumbers/ItemSerialSequencesTable.tsx
+++ b/apps/erp/app/modules/settings/ui/SerialNumbers/ItemSerialSequencesTable.tsx
@@ -19,6 +19,7 @@ import {
} from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import type { ItemSerialSequence } from "~/modules/settings/types";
import { useItems } from "~/stores/items";
@@ -27,11 +28,11 @@ import { path } from "~/utils/path";
type ItemSerialSequencesTableProps = {
data: ItemSerialSequence[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const ItemSerialSequencesTable = memo(
- ({ data, count, nextCursor }: ItemSerialSequencesTableProps) => {
+ ({ data, count, infinite }: ItemSerialSequencesTableProps) => {
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -150,7 +151,7 @@ const ItemSerialSequencesTable = memo(
return (
<Table<(typeof data)[number]>
data={data}
- infinite={{ dataKey: "data", nextCursor, listKey: "serial-numbers" }}
+ infinite={infinite}
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.tsx
index 2f5a7514d6..59b82a82df 100644
--- a/apps/erp/app/modules/settings/ui/Webhooks/WebhooksTable.tsx
+++ b/apps/erp/app/modules/settings/ui/Webhooks/WebhooksTable.tsx
@@ -49,6 +49,7 @@ import {
} from "react-icons/lu";
import { Outlet, useNavigate } from "react-router";
import { DateTime, EmployeeAvatar, Hyperlink, New, Table } from "~/components";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams, useUser } from "~/hooks";
import type { Webhook } from "~/modules/settings/types";
import { usePeople } from "~/stores";
@@ -58,11 +59,11 @@ import { useWebhookTables } from "./WebhookForm";
type WebhooksTableProps = {
data: Webhook[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const WebhooksTable = memo((props: WebhooksTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const navigate = useNavigate();
const [params] = useUrlParams();
@@ -210,7 +211,7 @@ const WebhooksTable = memo((props: WebhooksTableProps) => {
<>
<Table<Webhook>
data={data}
- infinite={{ dataKey: "webhooks", nextCursor, listKey: "webhooks" }}
+ infinite={infinite}
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.tsx
index 2bb3c7ca0b..a9ac099890 100644
--- a/apps/erp/app/modules/settings/ui/Webhooks/WebhooksUpgradeOverlay.tsx
+++ b/apps/erp/app/modules/settings/ui/Webhooks/WebhooksUpgradeOverlay.tsx
@@ -104,7 +104,7 @@ export default function WebhooksUpgradeOverlay() {
<WebhooksTable
data={mockWebhooks}
count={mockWebhooks.length}
- nextCursor={null}
+ infinite={{ dataKey: "data", nextCursor: null }}
/>
</UpgradeOverlayPreview>
<UpgradeOverlayCard>
diff --git a/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesTable.ee.tsx b/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesTable.ee.tsx
index 6a01f26e7a..2d2fe6f95b 100644
--- a/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesTable.ee.tsx
+++ b/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesTable.ee.tsx
@@ -11,6 +11,7 @@ import { LuPencil, LuTrash, LuUsers } from "react-icons/lu";
import { useNavigate } from "react-router";
import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import type { EmployeeType } from "~/modules/users/types";
import { path } from "~/utils/path";
@@ -18,11 +19,11 @@ import { path } from "~/utils/path";
type EmployeeTypesTableProps = {
data: EmployeeType[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const EmployeeTypesTable = memo((props: EmployeeTypesTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = props;
const { t } = useLingui();
const [params] = useUrlParams();
const navigate = useNavigate();
@@ -94,7 +95,7 @@ const EmployeeTypesTable = memo((props: EmployeeTypesTableProps) => {
return (
<Table<(typeof data)[number]>
data={data}
- infinite={{ dataKey: "data", nextCursor, listKey: "employee-types" }}
+ infinite={infinite}
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.tsx
index cdfb4135de..419950d12c 100644
--- a/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesUpgradeOverlay.ee.tsx
+++ b/apps/erp/app/modules/users/ui/EmployeeTypes/EmployeeTypesUpgradeOverlay.ee.tsx
@@ -49,7 +49,7 @@ export default function EmployeeTypesUpgradeOverlay() {
<EmployeeTypesTable
data={mockEmployeeTypes}
count={mockEmployeeTypes.length}
- nextCursor={null}
+ infinite={{ dataKey: "data", nextCursor: null }}
/>
}
title={<Trans>Employee Types</Trans>}
diff --git a/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx b/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx
index 390f3a1c14..d9f03bc678 100644
--- a/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx
+++ b/apps/erp/app/modules/users/ui/Employees/EmployeesTable.tsx
@@ -34,7 +34,11 @@ 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 type {
+ AllMatchingSelection,
+ BulkActionScope,
+ InfiniteOptions
+} from "~/components/Table";
import { usePermissions, useUrlParams, useUser } from "~/hooks";
import { useSettings } from "~/hooks/useSettings";
import type { Employee } from "~/modules/users/types";
@@ -52,7 +56,7 @@ import { useBulkUserActionFetcher } from "../components/AllMatchingUsers";
type EmployeesTableProps = {
data: Employee[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
employeeTypes: ListItem[];
unrevokedInviteEmails: string[];
mfaEnrolledUserIds: string[];
@@ -67,7 +71,7 @@ const EmployeesTable = memo(
({
data,
count,
- nextCursor,
+ infinite,
employeeTypes,
unrevokedInviteEmails,
mfaEnrolledUserIds
@@ -465,11 +469,7 @@ const EmployeesTable = memo(
count={count}
columns={columns}
data={data}
- infinite={{
- dataKey: "employees",
- nextCursor,
- listKey: "employee-accounts"
- }}
+ infinite={infinite}
defaultColumnVisibility={defaultColumnVisibility}
primaryAction={
permissions.can("create", "users") && (
diff --git a/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunsTable.tsx b/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunsTable.tsx
index c325217b70..27c15f31ff 100644
--- a/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunsTable.tsx
+++ b/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunsTable.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 { getTableLabel } from "@carbon/database/audit.config";
import { HStack } from "@carbon/react";
import { formatDateTime, formatDurationMilliseconds } from "@carbon/utils";
import { useLingui } from "@lingui/react/macro";
@@ -17,23 +16,25 @@ import {
LuZap
} from "react-icons/lu";
import { EmployeeAvatar, Hyperlink, Table } from "~/components";
+import type { InfiniteOptions } from "~/components/Table";
import { path } from "~/utils/path";
import type { WorkflowRun } from "../../workflows.service";
import { useWorkflowEventLabel } from "../Builder/catalog";
import { EntityRecordLink } from "./EntityRecordLink";
import { RunsLiveUpdates } from "./RunLiveUpdates";
import { RunStatus, TestRunBadge } from "./RunStatus";
+import { WORKFLOW_RUN_LIST_EXPORT_VALUES } from "./workflow-run-list-export";
export type WorkflowRunListItem = WorkflowRun & { recordName?: string };
type WorkflowRunsTableProps = {
data: WorkflowRunListItem[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const WorkflowRunsTable = memo((props: WorkflowRunsTableProps) => {
- const { data, count, nextCursor } = props;
+ const { data, count, infinite } = 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.
@@ -73,8 +74,7 @@ const WorkflowRunsTable = memo((props: WorkflowRunsTableProps) => {
mobile: "P3",
icon: <LuLink />,
filterHeader: t`Workflow`,
- exportValue: (row: WorkflowRunListItem) =>
- (row.workflow as { name?: string } | null)?.name ?? row.workflowId
+ exportValue: WORKFLOW_RUN_LIST_EXPORT_VALUES.workflowId
}
},
{
@@ -104,10 +104,7 @@ const WorkflowRunsTable = memo((props: WorkflowRunsTableProps) => {
meta: {
icon: <LuLink />,
filterHeader: t`Record`,
- exportValue: (row: WorkflowRunListItem) =>
- row.triggerTable && row.triggerRecordId
- ? `${getTableLabel(row.triggerTable)} ${row.recordName ?? row.triggerRecordId}`
- : ""
+ exportValue: WORKFLOW_RUN_LIST_EXPORT_VALUES.triggerRecordId
}
},
{
@@ -165,7 +162,7 @@ const WorkflowRunsTable = memo((props: WorkflowRunsTableProps) => {
{hasInFlight && <RunsLiveUpdates />}
<Table<WorkflowRunListItem>
data={data}
- infinite={{ dataKey: "data", nextCursor, listKey: "workflow-runs" }}
+ infinite={infinite}
columns={columns}
count={count}
title={t`Runs`}
diff --git a/apps/erp/app/modules/workflows/ui/Runs/workflow-run-list-export.ts b/apps/erp/app/modules/workflows/ui/Runs/workflow-run-list-export.ts
new file mode 100644
index 0000000000..a4d07e8f5a
--- /dev/null
+++ b/apps/erp/app/modules/workflows/ui/Runs/workflow-run-list-export.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.
+
+import { getTableLabel } from "@carbon/database/audit.config";
+
+/**
+ * The Workflow Runs table columns that show a value computed from the row,
+ * by column id. The table exports them with these, and the background CSV
+ * export writes the same values (`workflowRunsList.exportValues`).
+ */
+type Row = {
+ workflowId: string;
+ workflow?: unknown;
+ triggerTable: string | null;
+ triggerRecordId: string | null;
+ recordName?: string;
+};
+
+export const WORKFLOW_RUN_LIST_EXPORT_VALUES = {
+ workflowId: (row: Row) =>
+ (row.workflow as { name?: string } | null)?.name ?? row.workflowId,
+ triggerRecordId: (row: Row) =>
+ row.triggerTable && row.triggerRecordId
+ ? `${getTableLabel(row.triggerTable)} ${row.recordName ?? row.triggerRecordId}`
+ : ""
+} satisfies Record<string, (row: Row) => string>;
diff --git a/apps/erp/app/modules/workflows/ui/WorkflowsTable.tsx b/apps/erp/app/modules/workflows/ui/WorkflowsTable.tsx
index 70e55ee48e..42acf2f36b 100644
--- a/apps/erp/app/modules/workflows/ui/WorkflowsTable.tsx
+++ b/apps/erp/app/modules/workflows/ui/WorkflowsTable.tsx
@@ -35,6 +35,7 @@ import { useNavigate } from "react-router";
import { EmployeeAvatar, Hyperlink, Table } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
import { NewAction } from "~/components/New";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions } from "~/hooks";
import { usePeople } from "~/stores";
import { path } from "~/utils/path";
@@ -53,11 +54,11 @@ type WorkflowRow = Workflow & {
type WorkflowsTableProps = {
data: WorkflowRow[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
};
const WorkflowsTable = memo(
- ({ data, count, nextCursor }: WorkflowsTableProps) => {
+ ({ data, count, infinite }: WorkflowsTableProps) => {
const navigate = useNavigate();
const { t } = useLingui();
const permissions = usePermissions();
@@ -70,11 +71,6 @@ const WorkflowsTable = memo(
null
);
- const infinite = useMemo(
- () => ({ dataKey: "data", nextCursor, listKey: "workflows" }),
- [nextCursor]
- );
-
const columns = useMemo<ColumnDef<WorkflowRow>[]>(
() => [
{
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.json
index 0a5b57730a..81f28f6220 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
@@ -697,7 +697,7 @@
{"name":"production_deleteJobOperationStep","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},
{"name":"production_deleteJobOperationStepSlide","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},
{"name":"production_deleteJobOperationTool","classification":"DESTRUCTIVE","schema":"7f8214d1083f","response":"bcde375ebd4c","permission":"production:delete","paginates":false},
- {"name":"production_deleteJobs","classification":"DESTRUCTIVE","schema":"0eb0c2be01ed","response":"0eb0c2be01ed","permission":"production:delete","paginates":false},
+ {"name":"production_deleteJobs","classification":"DESTRUCTIVE","schema":"0eb0c2be01ed","response":"7d63a61ad961","permission":"production:delete","paginates":false},
{"name":"production_deleteMaintenanceDispatch","classification":"DESTRUCTIVE","schema":"74a8a528c9d8","response":"bcde375ebd4c","permission":"production:delete","paginates":false},
{"name":"production_deleteMaintenanceDispatchEvent","classification":"DESTRUCTIVE","schema":"8dc062233861","response":"bcde375ebd4c","permission":"production:delete","paginates":false},
{"name":"production_deleteMaintenanceSchedule","classification":"DESTRUCTIVE","schema":"093d449cdac0","response":"bcde375ebd4c","permission":"production:delete","paginates":false},
@@ -819,7 +819,7 @@
{"name":"production_recalculateJobRequirements","classification":"WRITE","schema":"7f8214d1083f","response":"9e056a59d695","permission":"production:update","paginates":false},
{"name":"production_reconvertAssemblyModel","classification":"DESTRUCTIVE","schema":"3797626bd17e","response":"277f7d872d8c","permission":"production:update","paginates":false},
{"name":"production_releaseBatches","classification":"WRITE","schema":"b6b41ae3a2b7","response":"340a1cb28ff4","permission":"production:update","paginates":false},
- {"name":"production_releaseJobs","classification":"WRITE","schema":"9d50f93189c8","response":"9655f6ea4d0d","permission":"production:update","paginates":false},
+ {"name":"production_releaseJobs","classification":"WRITE","schema":"3baa0df18bff","response":"aee54edd8cae","permission":"production:update","paginates":false},
{"name":"production_reopenJob","classification":"WRITE","schema":"4999bd4be598","response":"64aaffa78287","permission":"production:update","paginates":false},
{"name":"production_reopenProductionPlanningActions","classification":"WRITE","schema":"8c0c1ffe0fab","response":"2a69a1e7d58b","permission":"production:update","paginates":false},
{"name":"production_reorderJobOperations","classification":"WRITE","schema":"c25fc63725f5","response":"4999bd4be598","permission":"production:update","paginates":false},
@@ -919,7 +919,7 @@
{"name":"purchasing_deleteLeaseLine","classification":"DESTRUCTIVE","schema":"2cf0099ceecf","response":"8394fbabd845","permission":"purchasing:delete","paginates":false},
{"name":"purchasing_deleteLeasePayment","classification":"DESTRUCTIVE","schema":"08b90ec76499","response":"8394fbabd845","permission":"purchasing:delete","paginates":false},
{"name":"purchasing_deletePurchaseOrderLine","classification":"DESTRUCTIVE","schema":"555dd21fcbd0","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},
- {"name":"purchasing_deletePurchaseOrders","classification":"DESTRUCTIVE","schema":"56451bca9438","response":"56451bca9438","permission":"purchasing:delete","paginates":false},
+ {"name":"purchasing_deletePurchaseOrders","classification":"DESTRUCTIVE","schema":"56451bca9438","response":"1d2358e4f280","permission":"purchasing:delete","paginates":false},
{"name":"purchasing_deletePurchaseReturnOrder","classification":"DESTRUCTIVE","schema":"ceebeb4f9cac","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},
{"name":"purchasing_deletePurchaseReturnOrderLine","classification":"DESTRUCTIVE","schema":"e2b1df794940","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},
{"name":"purchasing_deletePurchasingRFQ","classification":"DESTRUCTIVE","schema":"a03ea9b74e8a","response":"bcde375ebd4c","permission":"purchasing:delete","paginates":false},
diff --git a/apps/erp/app/routes/api+/table.export.ts b/apps/erp/app/routes/api+/table.export.ts
index add5b79067..7b2bd81a8d 100644
--- a/apps/erp/app/routes/api+/table.export.ts
+++ b/apps/erp/app/routes/api+/table.export.ts
@@ -5,19 +5,13 @@
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,
- TABLE_JOBS_FULL_MESSAGE,
- type TableJobRefusal,
- tableJobBusyMessage,
- tableJobBusyRefusal
-} from "~/utils/table-jobs";
+import { newTableExportId, type TableJobRefusal } from "~/utils/table-jobs";
+import { startTableJob } from "~/utils/table-jobs.server";
const logger = getLogger("erp", "table-export");
@@ -77,59 +71,23 @@ export async function action({ request }: ActionFunctionArgs) {
});
const exportId = newTableExportId(listKey);
- const lock = await takeTableJobLock("export", companyId, exportId);
- if (lock.status === "busy") {
- return data(
- {
- error: tableJobBusyMessage("export", lock.retryAfterSeconds),
- refusal: tableJobBusyRefusal("export", lock.retryAfterSeconds)
- },
- { status: 409 }
- );
- }
- if (lock.status === "full") {
- logger.warn("Refused a table export: every table-job slot is taken", {
- companyId,
- listKey
- });
- return data(
- {
- error: TABLE_JOBS_FULL_MESSAGE,
- refusal: { code: "full" } satisfies TableJobRefusal
- },
- { status: 503 }
- );
- }
- 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);
+ const refused = await startTableJob(
+ "export",
+ { companyId, jobId: exportId, log: { listKey } },
+ () =>
+ trigger("table-export", {
+ companyId,
+ userId,
+ exportId,
+ listKey,
+ search,
+ columns
+ })
+ );
+ if (refused) {
return data(
- {
- error: "The export could not start",
- refusal: { code: "not-started" } satisfies TableJobRefusal
- },
- { status: 500 }
+ { error: refused.message, refusal: refused.refusal },
+ { status: refused.status }
);
}
diff --git a/apps/erp/app/routes/x+/accounting+/asset-classes.tsx b/apps/erp/app/routes/x+/accounting+/asset-classes.tsx
index 3a9dd10a09..f0293174d3 100644
--- a/apps/erp/app/routes/x+/accounting+/asset-classes.tsx
+++ b/apps/erp/app/routes/x+/accounting+/asset-classes.tsx
@@ -36,7 +36,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function AssetClassesRoute() {
- const { data, count, nextCursor, taxDepreciationEnabled } =
+ const { data, count, infinite, taxDepreciationEnabled } =
useLoaderData<typeof loader>();
const { t } = useLingui();
const permissions = usePermissions();
@@ -47,7 +47,7 @@ export default function AssetClassesRoute() {
<AssetClassesTable
data={data}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
taxDepreciationEnabled={taxDepreciationEnabled}
primaryAction={
permissions.can("create", "accounting") && (
diff --git a/apps/erp/app/routes/x+/accounting+/depreciation-runs.tsx b/apps/erp/app/routes/x+/accounting+/depreciation-runs.tsx
index 634a521a9f..cb870c08d6 100644
--- a/apps/erp/app/routes/x+/accounting+/depreciation-runs.tsx
+++ b/apps/erp/app/routes/x+/accounting+/depreciation-runs.tsx
@@ -63,7 +63,7 @@ export default function DepreciationRunsRoute() {
const {
data,
count,
- nextCursor,
+ infinite,
lastPeriodEnd,
nextPeriodEnd,
hasDraftBlocking
@@ -87,7 +87,7 @@ export default function DepreciationRunsRoute() {
<DepreciationRunTable
data={data}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
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.tsx
index 1b2c74b94a..97dac5c609 100644
--- a/apps/erp/app/routes/x+/accounting+/dimensions.tsx
+++ b/apps/erp/app/routes/x+/accounting+/dimensions.tsx
@@ -22,11 +22,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function DimensionsRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <DimensionsTable data={data} count={count} nextCursor={nextCursor} />
+ <DimensionsTable data={data} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/accounting+/fixed-assets.tsx b/apps/erp/app/routes/x+/accounting+/fixed-assets.tsx
index 9931f6de08..e027bdbb19 100644
--- a/apps/erp/app/routes/x+/accounting+/fixed-assets.tsx
+++ b/apps/erp/app/routes/x+/accounting+/fixed-assets.tsx
@@ -33,7 +33,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function FixedAssetsRoute() {
- const { data, count, nextCursor, assetClasses } =
+ const { data, count, infinite, assetClasses } =
useLoaderData<typeof loader>();
const { t } = useLingui();
const permissions = usePermissions();
@@ -44,7 +44,7 @@ export default function FixedAssetsRoute() {
<FixedAssetsTable
data={data}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
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.tsx
index b9c5d07ac1..f31f393c24 100644
--- a/apps/erp/app/routes/x+/accounting+/fleet.tsx
+++ b/apps/erp/app/routes/x+/accounting+/fleet.tsx
@@ -49,7 +49,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function FleetRoute() {
- const { data, count, nextCursor, buildForFleetClassId } =
+ const { data, count, infinite, buildForFleetClassId } =
useLoaderData<typeof loader>();
const permissions = usePermissions();
const navigate = useNavigate();
@@ -59,7 +59,7 @@ export default function FleetRoute() {
<FleetAssetsTable
data={data}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
primaryAction={
permissions.can("create", "production") && (
<Button
diff --git a/apps/erp/app/routes/x+/accounting+/intercompany.tsx b/apps/erp/app/routes/x+/accounting+/intercompany.tsx
index 5b7b319579..fbf9a8b468 100644
--- a/apps/erp/app/routes/x+/accounting+/intercompany.tsx
+++ b/apps/erp/app/routes/x+/accounting+/intercompany.tsx
@@ -28,7 +28,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
export default function IntercompanyRoute() {
const { t } = useLingui();
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
const [params] = useUrlParams();
const permissions = usePermissions();
const matchFetcher = useFetcher();
@@ -40,7 +40,7 @@ export default function IntercompanyRoute() {
<IntercompanyTransactionTable
data={data}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
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.tsx
index ce3cef486c..d27738833d 100644
--- a/apps/erp/app/routes/x+/accounting+/journals.tsx
+++ b/apps/erp/app/routes/x+/accounting+/journals.tsx
@@ -49,7 +49,7 @@ function NewJournalEntry() {
}
export default function JournalEntriesRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
const permissions = usePermissions();
return (
@@ -57,7 +57,7 @@ export default function JournalEntriesRoute() {
<JournalEntriesTable
data={data}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
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.tsx
index 160979d4c8..b70af31139 100644
--- a/apps/erp/app/routes/x+/accounting+/payment-terms.tsx
+++ b/apps/erp/app/routes/x+/accounting+/payment-terms.tsx
@@ -22,11 +22,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function PaymentTermsRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <PaymentTermsTable data={data} count={count} nextCursor={nextCursor} />
+ <PaymentTermsTable data={data} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/accounting+/projects.tsx b/apps/erp/app/routes/x+/accounting+/projects.tsx
index 709bb6077d..913466d866 100644
--- a/apps/erp/app/routes/x+/accounting+/projects.tsx
+++ b/apps/erp/app/routes/x+/accounting+/projects.tsx
@@ -14,7 +14,7 @@ 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 { listErrorPage, listInfinite } from "~/utils/list-registry/load.server";
import { path } from "~/utils/path";
const logger = getLogger("erp", "projects");
@@ -47,7 +47,12 @@ export async function loader({ request }: LoaderFunctionArgs) {
return listErrorPage("data");
}
return data(
- { data: [], count: 0, nextCursor: null },
+ {
+ data: [],
+ count: 0,
+ nextCursor: null,
+ infinite: listInfinite(projectsList, "data", null)
+ },
await flash(request, error(projects.error, "Failed to fetch projects"))
);
}
@@ -56,20 +61,17 @@ export async function loader({ request }: LoaderFunctionArgs) {
data: projects.rows,
count: projects.count,
exactCount: projects.exactCount,
- nextCursor: projects.nextCursor
+ nextCursor: projects.nextCursor,
+ infinite: listInfinite(projectsList, "data", projects.nextCursor)
};
}
export default function ProjectsRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <ProjectsTable
- data={data ?? []}
- count={count ?? 0}
- nextCursor={nextCursor ?? null}
- />
+ <ProjectsTable data={data ?? []} count={count ?? 0} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/documents+/search.tsx b/apps/erp/app/routes/x+/documents+/search.tsx
index d7a2c1ed66..b9c3887abf 100644
--- a/apps/erp/app/routes/x+/documents+/search.tsx
+++ b/apps/erp/app/routes/x+/documents+/search.tsx
@@ -35,7 +35,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
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.
@@ -69,7 +68,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function DocumentsAllRoute() {
- const { count, documents, nextCursor, listKey, labels, ...data } =
+ const { count, documents, infinite, labels, ...data } =
useLoaderData<typeof loader>();
const extensions = useResolved(data.extensions, []);
@@ -80,8 +79,7 @@ export default function DocumentsAllRoute() {
<DocumentsTable
data={documents}
count={count}
- nextCursor={nextCursor}
- listKey={listKey}
+ infinite={infinite}
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.tsx
index 404fca96b4..cb76b4db19 100644
--- a/apps/erp/app/routes/x+/inventory+/inventory-count.tsx
+++ b/apps/erp/app/routes/x+/inventory+/inventory-count.tsx
@@ -34,7 +34,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function InventoryCountRoute() {
- const { inventoryCounts, count, nextCursor, locations } =
+ const { inventoryCounts, count, infinite, locations } =
useLoaderData<typeof loader>();
return (
@@ -42,7 +42,7 @@ export default function InventoryCountRoute() {
<InventoryCountsTable
data={inventoryCounts}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
locations={locations}
/>
<RecordOutlet />
diff --git a/apps/erp/app/routes/x+/inventory+/picking-lists.tsx b/apps/erp/app/routes/x+/inventory+/picking-lists.tsx
index 64157ed4d9..2651c0f90a 100644
--- a/apps/erp/app/routes/x+/inventory+/picking-lists.tsx
+++ b/apps/erp/app/routes/x+/inventory+/picking-lists.tsx
@@ -30,14 +30,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function PickingListsRoute() {
- const { pickingLists, count, nextCursor } = useLoaderData<typeof loader>();
+ const { pickingLists, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<PickingListsTable
data={pickingLists as PickingList[]}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/inventory+/receipts.tsx b/apps/erp/app/routes/x+/inventory+/receipts.tsx
index b4970179a9..7d5293d678 100644
--- a/apps/erp/app/routes/x+/inventory+/receipts.tsx
+++ b/apps/erp/app/routes/x+/inventory+/receipts.tsx
@@ -29,11 +29,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ReceiptsRoute() {
- const { receipts, count, nextCursor } = useLoaderData<typeof loader>();
+ const { receipts, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <ReceiptsTable data={receipts} count={count} nextCursor={nextCursor} />
+ <ReceiptsTable data={receipts} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/inventory+/shipments.tsx b/apps/erp/app/routes/x+/inventory+/shipments.tsx
index 0f2340c5a6..994f631c9d 100644
--- a/apps/erp/app/routes/x+/inventory+/shipments.tsx
+++ b/apps/erp/app/routes/x+/inventory+/shipments.tsx
@@ -29,11 +29,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ShipmentsRoute() {
- const { shipments, count, nextCursor } = useLoaderData<typeof loader>();
+ const { shipments, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <ShipmentsTable data={shipments} count={count} nextCursor={nextCursor} />
+ <ShipmentsTable data={shipments} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/inventory+/shipping-methods.tsx b/apps/erp/app/routes/x+/inventory+/shipping-methods.tsx
index 8fe9b5f9e9..ec1d8db579 100644
--- a/apps/erp/app/routes/x+/inventory+/shipping-methods.tsx
+++ b/apps/erp/app/routes/x+/inventory+/shipping-methods.tsx
@@ -28,14 +28,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ShippingMethodsRoute() {
- const { shippingMethods, count, nextCursor } = useLoaderData<typeof loader>();
+ const { shippingMethods, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<ShippingMethodsTable
data={shippingMethods}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/inventory+/stock-movements.tsx b/apps/erp/app/routes/x+/inventory+/stock-movements.tsx
index 4766e784d9..9c466a7176 100644
--- a/apps/erp/app/routes/x+/inventory+/stock-movements.tsx
+++ b/apps/erp/app/routes/x+/inventory+/stock-movements.tsx
@@ -29,15 +29,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function StockMovementsRoute() {
- const { movements, count, nextCursor } = useLoaderData<typeof loader>();
+ const { movements, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <StockMovementsTable
- data={movements}
- count={count}
- nextCursor={nextCursor}
- />
+ <StockMovementsTable data={movements} count={count} infinite={infinite} />
</VStack>
);
}
diff --git a/apps/erp/app/routes/x+/inventory+/storage-types.tsx b/apps/erp/app/routes/x+/inventory+/storage-types.tsx
index ccbfd2d033..1eb23eeaf6 100644
--- a/apps/erp/app/routes/x+/inventory+/storage-types.tsx
+++ b/apps/erp/app/routes/x+/inventory+/storage-types.tsx
@@ -28,14 +28,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function StorageTypesRoute() {
- const { storageTypes, count, nextCursor } = useLoaderData<typeof loader>();
+ const { storageTypes, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<StorageTypesTable
data={storageTypes}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/inventory+/tracked-entities.tsx b/apps/erp/app/routes/x+/inventory+/tracked-entities.tsx
index ae93980603..581d7c902a 100644
--- a/apps/erp/app/routes/x+/inventory+/tracked-entities.tsx
+++ b/apps/erp/app/routes/x+/inventory+/tracked-entities.tsx
@@ -71,7 +71,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function TraceabilityRoute() {
- const { trackedEntities, count, nextCursor, nearExpiryWarningDays } =
+ const { trackedEntities, count, infinite, nearExpiryWarningDays } =
useLoaderData<typeof loader>();
return (
@@ -79,7 +79,7 @@ export default function TraceabilityRoute() {
<TrackedEntitiesTable
data={trackedEntities}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
nearExpiryWarningDays={nearExpiryWarningDays ?? null}
/>
</VStack>
diff --git a/apps/erp/app/routes/x+/inventory+/warehouse-transfers.tsx b/apps/erp/app/routes/x+/inventory+/warehouse-transfers.tsx
index 060ee024bb..a50b417ee0 100644
--- a/apps/erp/app/routes/x+/inventory+/warehouse-transfers.tsx
+++ b/apps/erp/app/routes/x+/inventory+/warehouse-transfers.tsx
@@ -29,7 +29,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function WarehouseTransfersRoute() {
- const { warehouseTransfers, count, nextCursor } =
+ const { warehouseTransfers, count, infinite } =
useLoaderData<typeof loader>();
return (
@@ -37,7 +37,7 @@ export default function WarehouseTransfersRoute() {
<WarehouseTransfersTable
data={warehouseTransfers}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/invoicing+/charges.tsx b/apps/erp/app/routes/x+/invoicing+/charges.tsx
index b8748dcb99..b1c6cfe6bc 100644
--- a/apps/erp/app/routes/x+/invoicing+/charges.tsx
+++ b/apps/erp/app/routes/x+/invoicing+/charges.tsx
@@ -29,10 +29,10 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ChargesRoute() {
- const { count, data, nextCursor } = useLoaderData<typeof loader>();
+ const { count, data, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <ChargesTable data={data} count={count} nextCursor={nextCursor} />
+ <ChargesTable data={data} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/invoicing+/credit-memos.tsx b/apps/erp/app/routes/x+/invoicing+/credit-memos.tsx
index 611a1e18fd..93665c9a11 100644
--- a/apps/erp/app/routes/x+/invoicing+/credit-memos.tsx
+++ b/apps/erp/app/routes/x+/invoicing+/credit-memos.tsx
@@ -30,12 +30,12 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function CreditMemosRoute() {
- const { count, memos, nextCursor } = useLoaderData<typeof loader>();
+ const { count, memos, infinite } = useLoaderData<typeof loader>();
return (
<MemosTable
data={memos}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
party="customer"
/>
);
diff --git a/apps/erp/app/routes/x+/invoicing+/payments.tsx b/apps/erp/app/routes/x+/invoicing+/payments.tsx
index f37ea48970..2f4d5c807a 100644
--- a/apps/erp/app/routes/x+/invoicing+/payments.tsx
+++ b/apps/erp/app/routes/x+/invoicing+/payments.tsx
@@ -29,8 +29,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function PaymentsRoute() {
- const { count, payments, nextCursor } = useLoaderData<typeof loader>();
- return (
- <PaymentsTable data={payments} count={count} nextCursor={nextCursor} />
- );
+ const { count, payments, infinite } = useLoaderData<typeof loader>();
+ return <PaymentsTable data={payments} count={count} infinite={infinite} />;
}
diff --git a/apps/erp/app/routes/x+/invoicing+/purchasing.tsx b/apps/erp/app/routes/x+/invoicing+/purchasing.tsx
index c897eeb00b..8f2b38e47f 100644
--- a/apps/erp/app/routes/x+/invoicing+/purchasing.tsx
+++ b/apps/erp/app/routes/x+/invoicing+/purchasing.tsx
@@ -30,15 +30,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function InvoicingPurchaseInvoicesRoute() {
- const { count, purchaseInvoices, nextCursor } =
- useLoaderData<typeof loader>();
+ const { count, purchaseInvoices, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<PurchaseInvoicesTable
data={purchaseInvoices}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/invoicing+/reimbursements.tsx b/apps/erp/app/routes/x+/invoicing+/reimbursements.tsx
index c3e6a02714..61106443fe 100644
--- a/apps/erp/app/routes/x+/invoicing+/reimbursements.tsx
+++ b/apps/erp/app/routes/x+/invoicing+/reimbursements.tsx
@@ -29,12 +29,12 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ReimbursementsRoute() {
- const { count, data, nextCursor } = useLoaderData<typeof loader>();
+ const { count, data, infinite } = 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} nextCursor={nextCursor} />
+ <ReimbursementsTable data={data} count={count} infinite={infinite} />
</VStack>
);
}
diff --git a/apps/erp/app/routes/x+/invoicing+/sales.tsx b/apps/erp/app/routes/x+/invoicing+/sales.tsx
index aaf3a85059..4df6ebfea6 100644
--- a/apps/erp/app/routes/x+/invoicing+/sales.tsx
+++ b/apps/erp/app/routes/x+/invoicing+/sales.tsx
@@ -30,14 +30,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function InvoicingSalesInvoicesRoute() {
- const { count, salesInvoices, nextCursor } = useLoaderData<typeof loader>();
+ const { count, salesInvoices, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<SalesInvoicesTable
data={salesInvoices}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/invoicing+/supplier-credits.tsx b/apps/erp/app/routes/x+/invoicing+/supplier-credits.tsx
index 2bd0fe2424..78226b8995 100644
--- a/apps/erp/app/routes/x+/invoicing+/supplier-credits.tsx
+++ b/apps/erp/app/routes/x+/invoicing+/supplier-credits.tsx
@@ -30,12 +30,12 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function SupplierCreditsRoute() {
- const { count, memos, nextCursor } = useLoaderData<typeof loader>();
+ const { count, memos, infinite } = useLoaderData<typeof loader>();
return (
<MemosTable
data={memos}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
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.tsx
index 00aa8f89df..a2adadcf25 100644
--- a/apps/erp/app/routes/x+/items+/change-notice-actions.tsx
+++ b/apps/erp/app/routes/x+/items+/change-notice-actions.tsx
@@ -24,14 +24,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ChangeNoticeActionsRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<ChangeNoticeRequiredActionsTable
data={data}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<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.tsx
index dc2acfa4bc..9d2e7f301e 100644
--- a/apps/erp/app/routes/x+/items+/change-notice-types.tsx
+++ b/apps/erp/app/routes/x+/items+/change-notice-types.tsx
@@ -22,15 +22,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ChangeNoticeTypesRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <ChangeNoticeTypesTable
- data={data}
- count={count}
- nextCursor={nextCursor}
- />
+ <ChangeNoticeTypesTable data={data} count={count} infinite={infinite} />
<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.tsx
index 0bfb85a62e..2f4d7de51b 100644
--- a/apps/erp/app/routes/x+/items+/change-notices+/_index.tsx
+++ b/apps/erp/app/routes/x+/items+/change-notices+/_index.tsx
@@ -25,7 +25,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ChangeNoticesIndexRoute() {
- const { changeNotices, count, nextCursor, types } =
+ const { changeNotices, count, infinite, types } =
useLoaderData<typeof loader>();
return (
@@ -33,7 +33,7 @@ export default function ChangeNoticesIndexRoute() {
<ChangeNoticesTable
data={changeNotices}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
types={types}
/>
<RecordOutlet />
diff --git a/apps/erp/app/routes/x+/items+/consumables.tsx b/apps/erp/app/routes/x+/items+/consumables.tsx
index e98e06a3b4..7b8a4ffc8f 100644
--- a/apps/erp/app/routes/x+/items+/consumables.tsx
+++ b/apps/erp/app/routes/x+/items+/consumables.tsx
@@ -34,8 +34,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ConsumablesSearchRoute() {
- const { count, consumables, nextCursor, tags } =
- useLoaderData<typeof loader>();
+ const { count, consumables, infinite, tags } = useLoaderData<typeof loader>();
useLoaderData<typeof loader>();
return (
@@ -43,7 +42,7 @@ export default function ConsumablesSearchRoute() {
<ConsumablesTable
data={consumables}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
tags={tags}
/>
<RecordOutlet />
diff --git a/apps/erp/app/routes/x+/items+/dimensions.tsx b/apps/erp/app/routes/x+/items+/dimensions.tsx
index 12fc2581db..f5d72ee824 100644
--- a/apps/erp/app/routes/x+/items+/dimensions.tsx
+++ b/apps/erp/app/routes/x+/items+/dimensions.tsx
@@ -28,7 +28,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function MaterialDimensionsRoute() {
- const { materialDimensions, count, nextCursor } =
+ const { materialDimensions, count, infinite } =
useLoaderData<typeof loader>();
return (
@@ -36,7 +36,7 @@ export default function MaterialDimensionsRoute() {
<MaterialDimensionsTable
data={materialDimensions}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/items+/finishes.tsx b/apps/erp/app/routes/x+/items+/finishes.tsx
index 28550a189c..6e86a20889 100644
--- a/apps/erp/app/routes/x+/items+/finishes.tsx
+++ b/apps/erp/app/routes/x+/items+/finishes.tsx
@@ -28,15 +28,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function MaterialFinishesRoute() {
- const { materialFinishes, count, nextCursor } =
- useLoaderData<typeof loader>();
+ const { materialFinishes, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<MaterialFinishesTable
data={materialFinishes}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/items+/forms.tsx b/apps/erp/app/routes/x+/items+/forms.tsx
index c497aa1477..08fbd983ac 100644
--- a/apps/erp/app/routes/x+/items+/forms.tsx
+++ b/apps/erp/app/routes/x+/items+/forms.tsx
@@ -28,14 +28,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function MaterialFormsRoute() {
- const { materialForms, count, nextCursor } = useLoaderData<typeof loader>();
+ const { materialForms, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<MaterialFormsTable
data={materialForms}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/items+/grades.tsx b/apps/erp/app/routes/x+/items+/grades.tsx
index ae90760a5d..5f94ba9c23 100644
--- a/apps/erp/app/routes/x+/items+/grades.tsx
+++ b/apps/erp/app/routes/x+/items+/grades.tsx
@@ -28,14 +28,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function MaterialGradesRoute() {
- const { materialGrades, count, nextCursor } = useLoaderData<typeof loader>();
+ const { materialGrades, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<MaterialGradesTable
data={materialGrades}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/items+/groups.tsx b/apps/erp/app/routes/x+/items+/groups.tsx
index 504774d15c..e007f61761 100644
--- a/apps/erp/app/routes/x+/items+/groups.tsx
+++ b/apps/erp/app/routes/x+/items+/groups.tsx
@@ -42,15 +42,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ItemPostingGroupsRoute() {
- const { itemPostingGroups, count, nextCursor } =
- useLoaderData<typeof loader>();
+ const { itemPostingGroups, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<ItemPostingGroupsTable
data={itemPostingGroups}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/items+/materials.tsx b/apps/erp/app/routes/x+/items+/materials.tsx
index 2e135bab88..1c6bd5f84b 100644
--- a/apps/erp/app/routes/x+/items+/materials.tsx
+++ b/apps/erp/app/routes/x+/items+/materials.tsx
@@ -34,14 +34,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function MaterialsSearchRoute() {
- const { count, materials, nextCursor, tags } = useLoaderData<typeof loader>();
+ const { count, materials, infinite, tags } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<MaterialsTable
data={materials}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
tags={tags}
/>
<RecordOutlet />
diff --git a/apps/erp/app/routes/x+/items+/methods+/materials.tsx b/apps/erp/app/routes/x+/items+/methods+/materials.tsx
index d4877a82c4..e849847f99 100644
--- a/apps/erp/app/routes/x+/items+/methods+/materials.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/materials.tsx
@@ -28,7 +28,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function MethodMaterialsRoute() {
- const { count, materials, nextCursor } = useLoaderData<typeof loader>();
+ const { count, materials, infinite } = useLoaderData<typeof loader>();
return (
<VStack
@@ -38,7 +38,7 @@ export default function MethodMaterialsRoute() {
<MethodMaterialsTable
data={materials}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
</VStack>
);
diff --git a/apps/erp/app/routes/x+/items+/methods+/operations.tsx b/apps/erp/app/routes/x+/items+/methods+/operations.tsx
index 35b4fe1230..ff1834aaa8 100644
--- a/apps/erp/app/routes/x+/items+/methods+/operations.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/operations.tsx
@@ -28,7 +28,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function MethodOperationsRoute() {
- const { count, operations, nextCursor } = useLoaderData<typeof loader>();
+ const { count, operations, infinite } = useLoaderData<typeof loader>();
return (
<VStack
@@ -38,7 +38,7 @@ export default function MethodOperationsRoute() {
<MethodOperationsTable
data={operations}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
</VStack>
);
diff --git a/apps/erp/app/routes/x+/items+/parts.tsx b/apps/erp/app/routes/x+/items+/parts.tsx
index 2cf5b0eb69..5aeab7fcee 100644
--- a/apps/erp/app/routes/x+/items+/parts.tsx
+++ b/apps/erp/app/routes/x+/items+/parts.tsx
@@ -35,18 +35,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function PartsSearchRoute() {
- const { count, parts, nextCursor, tags } = useLoaderData<typeof loader>();
+ const { count, parts, infinite, tags } = useLoaderData<typeof loader>();
useRealtime("part");
return (
<VStack spacing={0} className="h-full">
- <PartsTable
- data={parts}
- count={count}
- nextCursor={nextCursor}
- tags={tags}
- />
+ <PartsTable data={parts} count={count} infinite={infinite} tags={tags} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/items+/services.tsx b/apps/erp/app/routes/x+/items+/services.tsx
index 02130d7e57..adc01deef0 100644
--- a/apps/erp/app/routes/x+/items+/services.tsx
+++ b/apps/erp/app/routes/x+/items+/services.tsx
@@ -34,14 +34,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ServicesSearchRoute() {
- const { count, services, nextCursor, tags } = useLoaderData<typeof loader>();
+ const { count, services, infinite, tags } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<ServicesTable
data={services}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
tags={tags}
/>
<RecordOutlet />
diff --git a/apps/erp/app/routes/x+/items+/substances.tsx b/apps/erp/app/routes/x+/items+/substances.tsx
index 8607f50593..edcc71bca1 100644
--- a/apps/erp/app/routes/x+/items+/substances.tsx
+++ b/apps/erp/app/routes/x+/items+/substances.tsx
@@ -28,7 +28,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function MaterialSubstancesRoute() {
- const { materialSubstances, count, nextCursor } =
+ const { materialSubstances, count, infinite } =
useLoaderData<typeof loader>();
return (
@@ -36,7 +36,7 @@ export default function MaterialSubstancesRoute() {
<MaterialSubstancesTable
data={materialSubstances}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/items+/tools.tsx b/apps/erp/app/routes/x+/items+/tools.tsx
index ab3879482b..e3bfac1c4f 100644
--- a/apps/erp/app/routes/x+/items+/tools.tsx
+++ b/apps/erp/app/routes/x+/items+/tools.tsx
@@ -34,16 +34,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ToolsSearchRoute() {
- const { count, tools, nextCursor, tags } = useLoaderData<typeof loader>();
+ const { count, tools, infinite, tags } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <ToolsTable
- data={tools}
- count={count}
- nextCursor={nextCursor}
- tags={tags}
- />
+ <ToolsTable data={tools} count={count} infinite={infinite} tags={tags} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/items+/types.tsx b/apps/erp/app/routes/x+/items+/types.tsx
index 1b36bf2fb8..e2bf656b3f 100644
--- a/apps/erp/app/routes/x+/items+/types.tsx
+++ b/apps/erp/app/routes/x+/items+/types.tsx
@@ -28,14 +28,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function MaterialTypesRoute() {
- const { materialTypes, count, nextCursor } = useLoaderData<typeof loader>();
+ const { materialTypes, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<MaterialTypesTable
data={materialTypes}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/items+/uom.tsx b/apps/erp/app/routes/x+/items+/uom.tsx
index a904733b2b..0a6a915f33 100644
--- a/apps/erp/app/routes/x+/items+/uom.tsx
+++ b/apps/erp/app/routes/x+/items+/uom.tsx
@@ -22,11 +22,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function UnitOfMeasuresRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <UnitOfMeasuresTable data={data} count={count} nextCursor={nextCursor} />
+ <UnitOfMeasuresTable data={data} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/items+/update.tsx b/apps/erp/app/routes/x+/items+/update.tsx
index a0354bd82f..d31e338347 100644
--- a/apps/erp/app/routes/x+/items+/update.tsx
+++ b/apps/erp/app/routes/x+/items+/update.tsx
@@ -3,19 +3,15 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { carbon } from "@carbon/api/carbon.server";
-import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import { z } from "zod";
import { zfd } from "zod-form-data";
import {
isItemBulkUpdateField,
- type itemTrackingTypes
+ itemBulkUpdateValidator
} from "~/modules/items/items.models";
-import type { methodType, sourcingType } from "~/modules/shared/shared.models";
-import { isItemBulkUpdateValue } from "~/utils/item-bulk-actions.server";
-import { bulkStartFormResponse } from "~/utils/table-jobs";
-import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";
+import { startBackgroundBulkAction } from "~/utils/table-jobs.server";
// The items tables' bulk actions and the item properties panels: one field of
// one or more items per post. The tables' Update posts `allMatching` in
@@ -63,52 +59,31 @@ export async function action(args: ActionFunctionArgs) {
if ("invalid" in input) return input.invalid;
const { items: ids, field, value, allMatching } = input.data;
- // Every matching row: the background job updates them 100 at a time
- // (bulkUpdateItems).
- if (allMatching && isItemBulkUpdateField(field)) {
- if (!isItemBulkUpdateValue(field, value)) {
- return invalid(`${value} is not a valid ${field}`);
- }
- const { companyId, userId } = await requirePermissions(args.request, {
- update: "parts"
- });
- const started = await startAllMatchingBulkAction(allMatching, {
- companyId,
- userId,
- actionKey: "items.update",
- params: { field, value }
- });
- if (started) return bulkStartFormResponse(started);
+ // The fields the tables' Update sets on many items: one operation for
+ // both paths (`updateItems`). Every matching row goes to the background
+ // job, which runs the same operation 100 items at a time.
+ if (isItemBulkUpdateField(field)) {
+ const change = itemBulkUpdateValidator.safeParse({ field, value });
+ if (!change.success) return invalid(`${value} is not a valid ${field}`);
+ const started = await startBackgroundBulkAction(
+ args.request,
+ "items.update",
+ { allMatching },
+ change.data
+ );
+ if (started) return started;
+ const api = await carbon(args.request);
+ return api.items.updateItems({ ids, change: change.data });
}
const api = (await carbon(args.request)).items;
switch (field) {
- case "itemTrackingType":
- return api.setItemTrackingType({
- ids,
- itemTrackingType: value as (typeof itemTrackingTypes)[number]
- });
case "name":
case "description":
case "mpn":
case "unitOfMeasureCode":
return api.setItemFields({ ids, [field]: value });
- case "replenishmentSystem":
- return api.setItemSourcing({
- ids,
- replenishmentSystem: value as "Buy" | "Make" | "Buy and Make"
- });
- case "defaultMethodType":
- return api.setItemSourcing({
- ids,
- defaultMethodType: value as (typeof methodType)[number]
- });
- case "sourcingType":
- return api.setItemSourcing({
- ids,
- sourcingType: value as (typeof sourcingType)[number]
- });
case "gradeId":
case "dimensionId":
case "finishId":
@@ -118,11 +93,6 @@ export async function action(args: ActionFunctionArgs) {
return api.setMaterialProperties({ ids, [field]: value || null });
case "active":
return api.setItemActive({ ids, active: value === "on" });
- case "itemPostingGroupId":
- return api.setItemPostingGroup({
- ids,
- itemPostingGroupId: value || null
- });
case "partId":
case "consumableId":
case "materialId":
diff --git a/apps/erp/app/routes/x+/job+/release.tsx b/apps/erp/app/routes/x+/job+/release.tsx
index 843cf1eecd..412c65ded6 100644
--- a/apps/erp/app/routes/x+/job+/release.tsx
+++ b/apps/erp/app/routes/x+/job+/release.tsx
@@ -3,15 +3,10 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { carbon } from "@carbon/api/carbon.server";
-import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import { releaseJobs } from "~/modules/production/production.server";
-import { bulkStartFormResponse, fitsOneRequest } from "~/utils/table-jobs";
-import {
- startAllMatchingBulkAction,
- startSelectedBulkAction
-} from "~/utils/table-jobs.server";
+import { startBackgroundBulkAction } from "~/utils/table-jobs.server";
// The jobs table's Release Jobs: no dialog, so a job with a choice to make is
// refused and named rather than released with a guess.
@@ -27,35 +22,24 @@ export async function action(args: ActionFunctionArgs) {
.json()
.catch(() => null);
if (json?.allMatching) {
- const { companyId, userId } = await requirePermissions(args.request, {
- update: "production"
- });
- const started = await startAllMatchingBulkAction(json.allMatching, {
- companyId,
- userId,
- actionKey: "jobs.release",
- params: {}
- });
- if (started) return bulkStartFormResponse(started);
+ const started = await startBackgroundBulkAction(
+ args.request,
+ "jobs.release",
+ { allMatching: json.allMatching },
+ {}
+ );
+ if (started) return started;
}
const input = await validator(selection).request(args);
if ("invalid" in input) return input.invalid;
- if (!fitsOneRequest("jobs.release", input.data.jobIds.length)) {
- const { companyId, userId } = await requirePermissions(args.request, {
- update: "production"
- });
- return bulkStartFormResponse(
- await startSelectedBulkAction({
- companyId,
- userId,
- actionKey: "jobs.release",
- params: {},
- listKey: "jobs",
- ids: input.data.jobIds
- })
- );
- }
+ const started = await startBackgroundBulkAction(
+ args.request,
+ "jobs.release",
+ { ids: input.data.jobIds },
+ {}
+ );
+ if (started) return started;
const api = await carbon(args.request);
return api.production.releaseJobs(input.data);
}
diff --git a/apps/erp/app/routes/x+/job+/update.tsx b/apps/erp/app/routes/x+/job+/update.tsx
index 7313eb2b74..3b6efebde9 100644
--- a/apps/erp/app/routes/x+/job+/update.tsx
+++ b/apps/erp/app/routes/x+/job+/update.tsx
@@ -4,14 +4,12 @@
import { carbon } from "@carbon/api/carbon.server";
import { CarbonError, toResult } from "@carbon/api/service-fn.server";
-import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import { z } from "zod";
import { zfd } from "zod-form-data";
import type { deadlineTypes } from "~/modules/production/production.models";
-import { bulkStartFormResponse } from "~/utils/table-jobs";
-import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";
+import { startBackgroundBulkAction } from "~/utils/table-jobs.server";
// The jobs table's bulk actions and the job properties panel: one field of
// one or more jobs per post. The table's Delete posts `allMatching` in place
@@ -47,19 +45,15 @@ export async function action(args: ActionFunctionArgs) {
const { ids, field, value, allMatching } = input.data;
// Every matching row: the background job deletes the Draft, Planned, Due
- // Today and Overdue jobs (bulkDeleteJobs) and skips the rest.
- if (field === "delete" && allMatching) {
- const { companyId, userId } = await requirePermissions(args.request, {
- update: "production",
- delete: "production"
- });
- const started = await startAllMatchingBulkAction(allMatching, {
- companyId,
- userId,
- actionKey: "jobs.delete",
- params: {}
- });
- if (started) return bulkStartFormResponse(started);
+ // Today and Overdue jobs (deleteJobs, as for a selection) and skips the rest.
+ if (field === "delete") {
+ const started = await startBackgroundBulkAction(
+ args.request,
+ "jobs.delete",
+ { allMatching },
+ {}
+ );
+ if (started) return started;
}
const job = (await carbon(args.request)).production;
diff --git a/apps/erp/app/routes/x+/people+/attributes.tsx b/apps/erp/app/routes/x+/people+/attributes.tsx
index 929cb67501..53d9cb61b2 100644
--- a/apps/erp/app/routes/x+/people+/attributes.tsx
+++ b/apps/erp/app/routes/x+/people+/attributes.tsx
@@ -32,14 +32,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function UserAttributesRoute() {
- const { count, categories, nextCursor } = useLoaderData<typeof loader>();
+ const { count, categories, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<AttributeCategoriesTable
data={categories}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/people+/employee.tsx b/apps/erp/app/routes/x+/people+/employee.tsx
index b94f94df34..cd0a6197ab 100644
--- a/apps/erp/app/routes/x+/people+/employee.tsx
+++ b/apps/erp/app/routes/x+/people+/employee.tsx
@@ -69,7 +69,7 @@ export default function ResourcesPeopleRoute() {
employeeTypes,
people,
shifts,
- nextCursor
+ infinite
} = useLoaderData<typeof loader>();
return (
@@ -78,7 +78,7 @@ export default function ResourcesPeopleRoute() {
attributeCategories={attributeCategories}
data={people ?? []}
count={count ?? 0}
- nextCursor={nextCursor}
+ infinite={infinite}
employeeTypes={employeeTypes}
shifts={shifts}
/>
diff --git a/apps/erp/app/routes/x+/people+/holidays.tsx b/apps/erp/app/routes/x+/people+/holidays.tsx
index 7ef15f3ac3..b3ff9b4615 100644
--- a/apps/erp/app/routes/x+/people+/holidays.tsx
+++ b/apps/erp/app/routes/x+/people+/holidays.tsx
@@ -34,14 +34,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function Route() {
- const { holidays, years, count, nextCursor } = useLoaderData<typeof loader>();
+ const { holidays, years, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<HolidaysTable
data={holidays}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
years={years}
/>
<RecordOutlet />
diff --git a/apps/erp/app/routes/x+/people+/shifts.tsx b/apps/erp/app/routes/x+/people+/shifts.tsx
index f52973ce4f..8efcd9c81e 100644
--- a/apps/erp/app/routes/x+/people+/shifts.tsx
+++ b/apps/erp/app/routes/x+/people+/shifts.tsx
@@ -30,15 +30,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ShiftsRoute() {
- const { shifts, locations, count, nextCursor } =
- useLoaderData<typeof loader>();
+ const { shifts, locations, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<ShiftsTable
data={shifts}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
locations={locations}
/>
<RecordOutlet />
diff --git a/apps/erp/app/routes/x+/people+/timecard.tsx b/apps/erp/app/routes/x+/people+/timecard.tsx
index 60dd1a63c5..1b87ae0518 100644
--- a/apps/erp/app/routes/x+/people+/timecard.tsx
+++ b/apps/erp/app/routes/x+/people+/timecard.tsx
@@ -47,11 +47,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function Route() {
- const { entries, count, nextCursor } = useLoaderData<typeof loader>();
+ const { entries, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <TimecardsTable data={entries} count={count} nextCursor={nextCursor} />
+ <TimecardsTable data={entries} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/production+/assemblies.tsx b/apps/erp/app/routes/x+/production+/assemblies.tsx
index 6118fe6524..62be048b8d 100644
--- a/apps/erp/app/routes/x+/production+/assemblies.tsx
+++ b/apps/erp/app/routes/x+/production+/assemblies.tsx
@@ -24,14 +24,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function AssemblyInstructionsRoute() {
- const { instructions, count, nextCursor } = useLoaderData<typeof loader>();
+ const { instructions, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<AssemblyInstructionsTable
data={instructions}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/production+/batches.dissolve.tsx b/apps/erp/app/routes/x+/production+/batches.dissolve.tsx
index e40ba07fdf..28f81da4b1 100644
--- a/apps/erp/app/routes/x+/production+/batches.dissolve.tsx
+++ b/apps/erp/app/routes/x+/production+/batches.dissolve.tsx
@@ -5,32 +5,31 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import type { ActionFunctionArgs } from "react-router";
+import { dissolveBatches } from "~/modules/production/production.server";
import { serviceContext } from "~/modules/service-context.server";
-import { bulkDissolveBatches } from "~/utils/production-bulk-actions.server";
-import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";
+import { startBackgroundBulkAction } from "~/utils/table-jobs.server";
-// 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
+// Bulk dissolve (`dissolveBatches`): one dissolve per selected Planned or
+// Active batch. Each is independent: a batch that has recorded production is
+// refused 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 auth = await requirePermissions(request, { update: "production" });
- const { companyId, userId } = auth;
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: {}
- });
+ const started = await startBackgroundBulkAction(
+ request,
+ "batches.dissolve",
+ { allMatching: json?.allMatching },
+ {}
+ );
if (started) return started;
const ids = [
@@ -44,14 +43,9 @@ export async function action({ request }: ActionFunctionArgs) {
return { success: false, message: "No batches selected" };
}
- const result = await bulkDissolveBatches(serviceContext(auth), {
+ const result = await dissolveBatches(serviceContext(auth), {
batchIds: ids
});
- if (!result.success) return result;
- return {
- success: true,
- dissolved: result.done,
- failed: result.failed,
- skipped: result.skipped
- };
+ if (result.error) return { success: false, message: result.error.message };
+ return { success: true, ...result.data };
}
diff --git a/apps/erp/app/routes/x+/production+/batches.release.tsx b/apps/erp/app/routes/x+/production+/batches.release.tsx
index 656db9db7f..87e12ba829 100644
--- a/apps/erp/app/routes/x+/production+/batches.release.tsx
+++ b/apps/erp/app/routes/x+/production+/batches.release.tsx
@@ -3,15 +3,10 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { carbon } from "@carbon/api/carbon.server";
-import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import { releaseBatches } from "~/modules/production/production.server";
-import { bulkStartFormResponse, fitsOneRequest } from "~/utils/table-jobs";
-import {
- startAllMatchingBulkAction,
- startSelectedBulkAction
-} from "~/utils/table-jobs.server";
+import { startBackgroundBulkAction } from "~/utils/table-jobs.server";
// The batches table's bulk Release: no dialog, so a batch with a purchase
// order choice to make is refused and named.
@@ -27,35 +22,24 @@ export async function action(args: ActionFunctionArgs) {
.json()
.catch(() => null);
if (json?.allMatching) {
- const { companyId, userId } = await requirePermissions(args.request, {
- update: "production"
- });
- const started = await startAllMatchingBulkAction(json.allMatching, {
- companyId,
- userId,
- actionKey: "batches.release",
- params: {}
- });
- if (started) return bulkStartFormResponse(started);
+ const started = await startBackgroundBulkAction(
+ args.request,
+ "batches.release",
+ { allMatching: json.allMatching },
+ {}
+ );
+ if (started) return started;
}
const input = await validator(selection).request(args);
if ("invalid" in input) return input.invalid;
- if (!fitsOneRequest("batches.release", input.data.batchIds.length)) {
- const { companyId, userId } = await requirePermissions(args.request, {
- update: "production"
- });
- return bulkStartFormResponse(
- await startSelectedBulkAction({
- companyId,
- userId,
- actionKey: "batches.release",
- params: {},
- listKey: "operation-batches",
- ids: input.data.batchIds
- })
- );
- }
+ const started = await startBackgroundBulkAction(
+ args.request,
+ "batches.release",
+ { ids: input.data.batchIds },
+ {}
+ );
+ if (started) return started;
const api = await carbon(args.request);
return api.production.releaseBatches(input.data);
}
diff --git a/apps/erp/app/routes/x+/production+/batches.tsx b/apps/erp/app/routes/x+/production+/batches.tsx
index 8dcc9c9c81..cf7b9e5cbc 100644
--- a/apps/erp/app/routes/x+/production+/batches.tsx
+++ b/apps/erp/app/routes/x+/production+/batches.tsx
@@ -2,85 +2,31 @@
// 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 {
- getJobOperationBatchMemberStats,
- getJobOperationBatchMembers
-} from "~/modules/production/production.service";
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 { loadListPage } from "~/utils/list-registry/load.server";
import { operationBatchesList } from "~/utils/list-registry/production.server";
import { path } from "~/utils/path";
-const logger = getLogger("erp", "batches");
-
export const handle: Handle = {
breadcrumb: msg`Batches`,
to: path.to.operationBatches
};
export async function loader({ request }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(
- request,
- operationBatchesList.permission
- );
-
- const searchParams = new URL(request.url).searchParams;
- const batches = await fetchListPage(
- operationBatchesList,
- client,
- companyId,
- searchParams
- );
-
- if (batches.error && searchParams.get("after")) {
- logger.error("Failed to load a later page of batches", {
- companyId,
- error: batches.error
- });
- return listErrorPage("batches");
- }
-
- // 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,
- exactCount: batches.exactCount,
- nextCursor: batches.nextCursor,
- batches: batches.rows.map((b) => ({
- ...b,
- memberCount: stats.data[b.id]?.memberCount ?? 0,
- totalQuantity: stats.data[b.id]?.totalQuantity ?? 0,
- // Header work center when assigned; else the members' shared one (the
- // board's own fallback) — a board-created batch has no header WC until
- // its card is dragged.
- workCenterName:
- b.workCenter?.name ?? stats.data[b.id]?.workCenterName ?? null,
- // Member rows for the expandable sub-list.
- members: members.data[b.id] ?? []
- }))
- };
+ return loadListPage(request, operationBatchesList, { dataKey: "batches" });
}
export default function BatchesRoute() {
- const { batches, count, nextCursor } = useLoaderData<typeof loader>();
+ const { batches, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <BatchesTable data={batches} count={count} nextCursor={nextCursor} />
+ <BatchesTable data={batches} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/production+/jobs.tsx b/apps/erp/app/routes/x+/production+/jobs.tsx
index 4454c290b2..54c4c4b57a 100644
--- a/apps/erp/app/routes/x+/production+/jobs.tsx
+++ b/apps/erp/app/routes/x+/production+/jobs.tsx
@@ -11,10 +11,7 @@ import { getLocationsList } from "~/modules/resources/resources.service";
import { getTagsList } from "~/modules/shared/shared.service";
import type { Handle } from "~/utils/handle";
import { loadListPage } from "~/utils/list-registry/load.server";
-import {
- jobsList,
- withJobListExtras
-} from "~/utils/list-registry/production.server";
+import { jobsList } from "~/utils/list-registry/production.server";
import { path } from "~/utils/path";
export const handle: Handle = {
@@ -34,22 +31,16 @@ export async function loader({ request }: LoaderFunctionArgs) {
]);
return { locations: locations.data ?? [], tags: tags.data ?? [] };
},
- mapRows: withJobListExtras,
onError: { redirectTo: path.to.production, message: "Failed to fetch jobs" }
});
}
export default function JobsRoute() {
- const { count, tags, jobs, nextCursor } = useLoaderData<typeof loader>();
+ const { count, tags, jobs, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <JobsTable
- data={jobs}
- count={count}
- nextCursor={nextCursor}
- tags={tags}
- />
+ <JobsTable data={jobs} count={count} infinite={infinite} tags={tags} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/production+/procedures.tsx b/apps/erp/app/routes/x+/production+/procedures.tsx
index 221dda5809..3e1a060ece 100644
--- a/apps/erp/app/routes/x+/production+/procedures.tsx
+++ b/apps/erp/app/routes/x+/production+/procedures.tsx
@@ -28,8 +28,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ProceduresRoute() {
- const { procedures, tags, count, nextCursor } =
- useLoaderData<typeof loader>();
+ const { procedures, tags, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
@@ -37,7 +36,7 @@ export default function ProceduresRoute() {
data={procedures}
tags={tags}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/production+/scrap-reasons.tsx b/apps/erp/app/routes/x+/production+/scrap-reasons.tsx
index 8a1b5d00cf..df73337cfe 100644
--- a/apps/erp/app/routes/x+/production+/scrap-reasons.tsx
+++ b/apps/erp/app/routes/x+/production+/scrap-reasons.tsx
@@ -22,11 +22,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ScrapReasonsRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <ScrapReasonsTable data={data} count={count} nextCursor={nextCursor} />
+ <ScrapReasonsTable data={data} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/purchase-order+/update.tsx b/apps/erp/app/routes/x+/purchase-order+/update.tsx
index fdbd8dbe78..d7a3615822 100644
--- a/apps/erp/app/routes/x+/purchase-order+/update.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/update.tsx
@@ -3,14 +3,12 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { carbon } from "@carbon/api/carbon.server";
-import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import { z } from "zod";
import { zfd } from "zod-form-data";
import { updatePurchaseOrders } from "~/modules/purchasing/purchasing.server";
-import { bulkStartFormResponse } from "~/utils/table-jobs";
-import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";
+import { startBackgroundBulkAction } from "~/utils/table-jobs.server";
// The properties panel posts one field (`ids`, `field`, `value`); the orders
// table posts `field=delete` for the selected rows, or `allMatching` in place
@@ -28,19 +26,15 @@ export async function action(args: ActionFunctionArgs) {
const { ids, field, value, allMatching } = input.data;
// Every matching row: the background job deletes the Draft and Planned
- // orders (bulkDeletePurchaseOrders) and skips the rest.
- if (field === "delete" && allMatching) {
- const { companyId, userId } = await requirePermissions(args.request, {
- update: "purchasing",
- delete: "purchasing"
- });
- const started = await startAllMatchingBulkAction(allMatching, {
- companyId,
- userId,
- actionKey: "purchase-orders.delete",
- params: {}
- });
- if (started) return bulkStartFormResponse(started);
+ // orders it may (deletePurchaseOrders, as for a selection) and skips the rest.
+ if (field === "delete") {
+ const started = await startBackgroundBulkAction(
+ args.request,
+ "purchase-orders.delete",
+ { allMatching },
+ {}
+ );
+ if (started) return started;
}
const api = await carbon(args.request);
diff --git a/apps/erp/app/routes/x+/purchasing+/leases.tsx b/apps/erp/app/routes/x+/purchasing+/leases.tsx
index d85455d401..cc1fed1455 100644
--- a/apps/erp/app/routes/x+/purchasing+/leases.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/leases.tsx
@@ -28,11 +28,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function LeasesRoute() {
- const { count, leases, nextCursor } = useLoaderData<typeof loader>();
+ const { count, leases, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <LeasesTable data={leases} count={count} nextCursor={nextCursor} />
+ <LeasesTable data={leases} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/purchasing+/orders.tsx b/apps/erp/app/routes/x+/purchasing+/orders.tsx
index 5627e37056..e97f8688d2 100644
--- a/apps/erp/app/routes/x+/purchasing+/orders.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/orders.tsx
@@ -30,14 +30,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function PurchaseOrdersSearchRoute() {
- const { count, purchasOrders, nextCursor } = useLoaderData<typeof loader>();
+ const { count, purchasOrders, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<PurchaseOrdersTable
data={purchasOrders}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/purchasing+/quotes.tsx b/apps/erp/app/routes/x+/purchasing+/quotes.tsx
index 4e712840da..cb86d9872f 100644
--- a/apps/erp/app/routes/x+/purchasing+/quotes.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/quotes.tsx
@@ -30,15 +30,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function SupplierQuotesRoute() {
- const { count, quotes, nextCursor } = useLoaderData<typeof loader>();
+ const { count, quotes, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <SupplierQuotesTable
- data={quotes}
- count={count}
- nextCursor={nextCursor}
- />
+ <SupplierQuotesTable data={quotes} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/purchasing+/rfqs.tsx b/apps/erp/app/routes/x+/purchasing+/rfqs.tsx
index afccb3a328..e74d286e95 100644
--- a/apps/erp/app/routes/x+/purchasing+/rfqs.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/rfqs.tsx
@@ -30,11 +30,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function PurchasingRFQsRoute() {
- const { count, rfqs, nextCursor } = useLoaderData<typeof loader>();
+ const { count, rfqs, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <PurchasingRFQsTable data={rfqs} count={count} nextCursor={nextCursor} />
+ <PurchasingRFQsTable data={rfqs} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/purchasing+/supplier-returns.tsx b/apps/erp/app/routes/x+/purchasing+/supplier-returns.tsx
index 7dd30e1dfd..87de112168 100644
--- a/apps/erp/app/routes/x+/purchasing+/supplier-returns.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/supplier-returns.tsx
@@ -29,7 +29,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function PurchaseReturnOrdersSearchRoute() {
- const { count, purchaseReturnOrders, nextCursor } =
+ const { count, purchaseReturnOrders, infinite } =
useLoaderData<typeof loader>();
return (
@@ -37,7 +37,7 @@ export default function PurchaseReturnOrdersSearchRoute() {
<PurchaseReturnOrdersTable
data={purchaseReturnOrders}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/purchasing+/supplier-types.tsx b/apps/erp/app/routes/x+/purchasing+/supplier-types.tsx
index 0ffeed31c5..830246fef4 100644
--- a/apps/erp/app/routes/x+/purchasing+/supplier-types.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/supplier-types.tsx
@@ -22,11 +22,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function SupplierTypesRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <SupplierTypesTable data={data} count={count} nextCursor={nextCursor} />
+ <SupplierTypesTable data={data} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/purchasing+/suppliers.tsx b/apps/erp/app/routes/x+/purchasing+/suppliers.tsx
index 95c911fa37..899560bddb 100644
--- a/apps/erp/app/routes/x+/purchasing+/suppliers.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/suppliers.tsx
@@ -10,10 +10,7 @@ import { SuppliersTable } from "~/modules/purchasing/ui/Supplier";
import { getTagsList } from "~/modules/shared/shared.service";
import type { Handle } from "~/utils/handle";
import { loadListPage } from "~/utils/list-registry/load.server";
-import {
- suppliersList,
- withSupplierReportContacts
-} from "~/utils/list-registry/purchasing.server";
+import { suppliersList } from "~/utils/list-registry/purchasing.server";
import { path } from "~/utils/path";
export const handle: Handle = {
@@ -29,8 +26,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
firstPage: async ({ client, companyId }) => ({
tags: (await getTagsList(client, companyId, "supplier")).data ?? []
}),
- // The report contacts of each page's suppliers, for the CSV export.
- mapRows: withSupplierReportContacts,
onError: {
redirectTo: path.to.purchasing,
message: "Failed to fetch suppliers"
@@ -39,14 +34,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function PurchasingSuppliersRoute() {
- const { count, suppliers, nextCursor, tags } = useLoaderData<typeof loader>();
+ const { count, suppliers, infinite, tags } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<SuppliersTable
data={suppliers}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
tags={tags}
/>
<RecordOutlet />
diff --git a/apps/erp/app/routes/x+/quality+/actions.tsx b/apps/erp/app/routes/x+/quality+/actions.tsx
index 1a7e5ca0cf..a0906354a8 100644
--- a/apps/erp/app/routes/x+/quality+/actions.tsx
+++ b/apps/erp/app/routes/x+/quality+/actions.tsx
@@ -38,7 +38,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ActionsRoute() {
- const { actions, count, nextCursor, issueTypes, requiredActions } =
+ const { actions, count, infinite, issueTypes, requiredActions } =
useLoaderData<typeof loader>();
return (
@@ -46,7 +46,7 @@ export default function ActionsRoute() {
<ActionsTable
data={actions}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
issueTypes={issueTypes}
requiredActions={requiredActions}
/>
diff --git a/apps/erp/app/routes/x+/quality+/calibrations.tsx b/apps/erp/app/routes/x+/quality+/calibrations.tsx
index 47a1888e96..fb07b44a6b 100644
--- a/apps/erp/app/routes/x+/quality+/calibrations.tsx
+++ b/apps/erp/app/routes/x+/quality+/calibrations.tsx
@@ -36,7 +36,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function GaugesRoute() {
- const { gaugeCalibrationRecords, count, nextCursor, gaugeTypes } =
+ const { gaugeCalibrationRecords, count, infinite, gaugeTypes } =
useLoaderData<typeof loader>();
return (
@@ -44,7 +44,7 @@ export default function GaugesRoute() {
<GaugeCalibrationRecordsTable
data={gaugeCalibrationRecords}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
types={gaugeTypes}
/>
<RecordOutlet />
diff --git a/apps/erp/app/routes/x+/quality+/documents.tsx b/apps/erp/app/routes/x+/quality+/documents.tsx
index 56db00900b..741e60b54b 100644
--- a/apps/erp/app/routes/x+/quality+/documents.tsx
+++ b/apps/erp/app/routes/x+/quality+/documents.tsx
@@ -28,7 +28,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function QualityDocumentsRoute() {
- const { qualityDocuments, count, nextCursor, tags } =
+ const { qualityDocuments, count, infinite, tags } =
useLoaderData<typeof loader>();
return (
@@ -36,7 +36,7 @@ export default function QualityDocumentsRoute() {
<QualityDocumentsTable
data={qualityDocuments}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
tags={tags}
/>
<RecordOutlet />
diff --git a/apps/erp/app/routes/x+/quality+/gauge-types.tsx b/apps/erp/app/routes/x+/quality+/gauge-types.tsx
index 110a3012a2..a820767c3e 100644
--- a/apps/erp/app/routes/x+/quality+/gauge-types.tsx
+++ b/apps/erp/app/routes/x+/quality+/gauge-types.tsx
@@ -22,11 +22,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function NonConformanceTypesRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <GaugeTypesTable data={data} count={count} nextCursor={nextCursor} />
+ <GaugeTypesTable data={data} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/quality+/gauges.tsx b/apps/erp/app/routes/x+/quality+/gauges.tsx
index f29080f839..ed3f1439c2 100644
--- a/apps/erp/app/routes/x+/quality+/gauges.tsx
+++ b/apps/erp/app/routes/x+/quality+/gauges.tsx
@@ -28,7 +28,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function GaugesRoute() {
- const { gauges, count, nextCursor, gaugeTypes } =
+ const { gauges, count, infinite, gaugeTypes } =
useLoaderData<typeof loader>();
return (
@@ -36,7 +36,7 @@ export default function GaugesRoute() {
<GaugesTable
data={gauges}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
types={gaugeTypes}
/>
<RecordOutlet />
diff --git a/apps/erp/app/routes/x+/quality+/inspection-plans.tsx b/apps/erp/app/routes/x+/quality+/inspection-plans.tsx
index 26e2f3b3e0..fe9b083f7c 100644
--- a/apps/erp/app/routes/x+/quality+/inspection-plans.tsx
+++ b/apps/erp/app/routes/x+/quality+/inspection-plans.tsx
@@ -22,14 +22,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function InspectionDocumentsRoute() {
- const { diagrams, count, nextCursor } = useLoaderData<typeof loader>();
+ const { diagrams, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<InspectionDocumentTable
data={diagrams}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/quality+/inspections.tsx b/apps/erp/app/routes/x+/quality+/inspections.tsx
index 2e11c99567..af70a3a005 100644
--- a/apps/erp/app/routes/x+/quality+/inspections.tsx
+++ b/apps/erp/app/routes/x+/quality+/inspections.tsx
@@ -29,15 +29,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function InspectionsRoute() {
- const { inspections, count, nextCursor } = useLoaderData<typeof loader>();
+ const { inspections, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <InspectionsTable
- data={inspections}
- count={count}
- nextCursor={nextCursor}
- />
+ <InspectionsTable data={inspections} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/quality+/issue-types.tsx b/apps/erp/app/routes/x+/quality+/issue-types.tsx
index 74fd4e3b43..27f55253f7 100644
--- a/apps/erp/app/routes/x+/quality+/issue-types.tsx
+++ b/apps/erp/app/routes/x+/quality+/issue-types.tsx
@@ -22,11 +22,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function IssueTypesRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <IssueTypesTable data={data} count={count} nextCursor={nextCursor} />
+ <IssueTypesTable data={data} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/quality+/issue-workflows.tsx b/apps/erp/app/routes/x+/quality+/issue-workflows.tsx
index 3f73c474f9..78c50b2c6e 100644
--- a/apps/erp/app/routes/x+/quality+/issue-workflows.tsx
+++ b/apps/erp/app/routes/x+/quality+/issue-workflows.tsx
@@ -22,14 +22,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function IssueWorkflowsRoute() {
- const { procedures, count, nextCursor } = useLoaderData<typeof loader>();
+ const { procedures, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<IssueWorkflowsTable
data={procedures}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/quality+/issues.tsx b/apps/erp/app/routes/x+/quality+/issues.tsx
index 091a1e26d3..067d9fa2c4 100644
--- a/apps/erp/app/routes/x+/quality+/issues.tsx
+++ b/apps/erp/app/routes/x+/quality+/issues.tsx
@@ -33,14 +33,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function IssuesRoute() {
- const { issues, count, nextCursor, types } = useLoaderData<typeof loader>();
+ const { issues, count, infinite, types } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<IssuesTable
data={issues}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
types={types}
/>
<RecordOutlet />
diff --git a/apps/erp/app/routes/x+/quality+/required-actions.tsx b/apps/erp/app/routes/x+/quality+/required-actions.tsx
index b2827013c6..f285219a2f 100644
--- a/apps/erp/app/routes/x+/quality+/required-actions.tsx
+++ b/apps/erp/app/routes/x+/quality+/required-actions.tsx
@@ -22,11 +22,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function RequiredActionsRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <RequiredActionsTable data={data} count={count} nextCursor={nextCursor} />
+ <RequiredActionsTable data={data} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/quality+/risks.tsx b/apps/erp/app/routes/x+/quality+/risks.tsx
index 6b70722d37..76f3e1aba9 100644
--- a/apps/erp/app/routes/x+/quality+/risks.tsx
+++ b/apps/erp/app/routes/x+/quality+/risks.tsx
@@ -25,11 +25,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function RisksRoute() {
- const { count, risks, nextCursor } = useLoaderData<typeof loader>();
+ const { count, risks, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <RiskRegistersTable data={risks} count={count} nextCursor={nextCursor} />
+ <RiskRegistersTable data={risks} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/resources+/abilities.tsx b/apps/erp/app/routes/x+/resources+/abilities.tsx
index cd0d2c26b1..ada710ad1b 100644
--- a/apps/erp/app/routes/x+/resources+/abilities.tsx
+++ b/apps/erp/app/routes/x+/resources+/abilities.tsx
@@ -28,11 +28,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function AbilitiesRoute() {
- const { count, abilities, nextCursor } = useLoaderData<typeof loader>();
+ const { count, abilities, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <AbilitiesTable data={abilities} count={count} nextCursor={nextCursor} />
+ <AbilitiesTable data={abilities} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/resources+/contractors.tsx b/apps/erp/app/routes/x+/resources+/contractors.tsx
index f80e17dfb9..3a941f1216 100644
--- a/apps/erp/app/routes/x+/resources+/contractors.tsx
+++ b/apps/erp/app/routes/x+/resources+/contractors.tsx
@@ -33,7 +33,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function Route() {
- const { contractors, abilities, count, nextCursor } =
+ const { contractors, abilities, count, infinite } =
useLoaderData<typeof loader>();
return (
@@ -41,7 +41,7 @@ export default function Route() {
<ContractorsTable
data={contractors}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
// @ts-expect-error TS2322 - TODO: fix type
abilities={abilities}
/>
diff --git a/apps/erp/app/routes/x+/resources+/failure-modes.tsx b/apps/erp/app/routes/x+/resources+/failure-modes.tsx
index 596a4b16a5..d3d7ac2bf7 100644
--- a/apps/erp/app/routes/x+/resources+/failure-modes.tsx
+++ b/apps/erp/app/routes/x+/resources+/failure-modes.tsx
@@ -22,14 +22,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function FailureModesRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<FailureModesTable
data={data ?? []}
count={count ?? 0}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/resources+/locations.tsx b/apps/erp/app/routes/x+/resources+/locations.tsx
index 29ea3d4960..f7b179d37b 100644
--- a/apps/erp/app/routes/x+/resources+/locations.tsx
+++ b/apps/erp/app/routes/x+/resources+/locations.tsx
@@ -29,11 +29,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function LocationsRoute() {
- const { locations, count, nextCursor } = useLoaderData<typeof loader>();
+ const { locations, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <LocationsTable data={locations} count={count} nextCursor={nextCursor} />
+ <LocationsTable data={locations} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/resources+/maintenance.tsx b/apps/erp/app/routes/x+/resources+/maintenance.tsx
index c1f40cbffc..a841fa7d65 100644
--- a/apps/erp/app/routes/x+/resources+/maintenance.tsx
+++ b/apps/erp/app/routes/x+/resources+/maintenance.tsx
@@ -41,7 +41,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function MaintenanceRoute() {
- const { dispatches, count, nextCursor, failureModes, locations, locationId } =
+ const { dispatches, count, infinite, failureModes, locations, locationId } =
useLoaderData<typeof loader>();
return (
@@ -50,7 +50,7 @@ export default function MaintenanceRoute() {
// @ts-expect-error TS2322 - TODO: fix type
data={dispatches ?? []}
count={count ?? 0}
- nextCursor={nextCursor}
+ infinite={infinite}
failureModes={failureModes ?? []}
locations={locations}
locationId={locationId}
diff --git a/apps/erp/app/routes/x+/resources+/processes.tsx b/apps/erp/app/routes/x+/resources+/processes.tsx
index 6107ce5bde..954f9e0af1 100644
--- a/apps/erp/app/routes/x+/resources+/processes.tsx
+++ b/apps/erp/app/routes/x+/resources+/processes.tsx
@@ -29,11 +29,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ProcessesRoute() {
- const { processes, count, nextCursor } = useLoaderData<typeof loader>();
+ const { processes, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <ProcessesTable data={processes} count={count} nextCursor={nextCursor} />
+ <ProcessesTable data={processes} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/resources+/scheduled-maintenance.tsx b/apps/erp/app/routes/x+/resources+/scheduled-maintenance.tsx
index 21695fd1ea..0ff7f129c7 100644
--- a/apps/erp/app/routes/x+/resources+/scheduled-maintenance.tsx
+++ b/apps/erp/app/routes/x+/resources+/scheduled-maintenance.tsx
@@ -15,7 +15,7 @@ import type { MaintenanceSchedule } from "~/modules/resources/types";
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 { listErrorPage, listInfinite } from "~/utils/list-registry/load.server";
import { maintenanceSchedulesList } from "~/utils/list-registry/resources.server";
import { path } from "~/utils/path";
@@ -46,6 +46,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
data: [],
count: 0,
nextCursor: null,
+ infinite: listInfinite(maintenanceSchedulesList, "data", null),
locations: locationsList,
locationId: null
};
@@ -74,6 +75,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
data: [] as MaintenanceSchedule[],
count: 0,
nextCursor: null,
+ infinite: listInfinite(maintenanceSchedulesList, "data", null),
locations: locationsList,
locationId: selectedLocationId
},
@@ -89,13 +91,18 @@ export async function loader({ request }: LoaderFunctionArgs) {
count: schedules.count,
exactCount: schedules.exactCount,
nextCursor: schedules.nextCursor,
+ infinite: listInfinite(
+ maintenanceSchedulesList,
+ "data",
+ schedules.nextCursor
+ ),
locations: locationsList,
locationId: selectedLocationId
};
}
export default function MaintenanceSchedulesRoute() {
- const { data, count, nextCursor, locations, locationId } =
+ const { data, count, infinite, locations, locationId } =
useLoaderData<typeof loader>();
return (
@@ -103,7 +110,7 @@ export default function MaintenanceSchedulesRoute() {
<MaintenanceSchedulesTable
data={data ?? []}
count={count ?? 0}
- nextCursor={nextCursor}
+ infinite={infinite}
locations={locations}
locationId={locationId}
/>
diff --git a/apps/erp/app/routes/x+/resources+/suggestions.tsx b/apps/erp/app/routes/x+/resources+/suggestions.tsx
index c3cbce0923..c587b56f42 100644
--- a/apps/erp/app/routes/x+/resources+/suggestions.tsx
+++ b/apps/erp/app/routes/x+/resources+/suggestions.tsx
@@ -33,8 +33,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function SuggestionsRoute() {
- const { suggestions, tags, count, nextCursor } =
- useLoaderData<typeof loader>();
+ const { suggestions, tags, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
@@ -42,7 +41,7 @@ export default function SuggestionsRoute() {
data={suggestions}
tags={tags}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/resources+/training.tsx b/apps/erp/app/routes/x+/resources+/training.tsx
index 56bf92c388..c7ee662470 100644
--- a/apps/erp/app/routes/x+/resources+/training.tsx
+++ b/apps/erp/app/routes/x+/resources+/training.tsx
@@ -42,14 +42,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function TrainingsRoute() {
- const { trainings, count, nextCursor, tags } = useLoaderData<typeof loader>();
+ const { trainings, count, infinite, tags } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<TrainingsTable
data={trainings}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
tags={tags}
/>
<RecordOutlet />
diff --git a/apps/erp/app/routes/x+/resources+/work-centers.tsx b/apps/erp/app/routes/x+/resources+/work-centers.tsx
index dace10de97..3f708fae56 100644
--- a/apps/erp/app/routes/x+/resources+/work-centers.tsx
+++ b/apps/erp/app/routes/x+/resources+/work-centers.tsx
@@ -41,7 +41,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function WorkCentersRoute() {
- const { count, departments, locations, workCenters, nextCursor } =
+ const { count, departments, locations, workCenters, infinite } =
useLoaderData<typeof loader>();
return (
@@ -49,7 +49,7 @@ export default function WorkCentersRoute() {
<WorkCentersTable
data={workCenters}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
departments={departments}
locations={locations}
/>
diff --git a/apps/erp/app/routes/x+/sales+/contracts.tsx b/apps/erp/app/routes/x+/sales+/contracts.tsx
index 4c542a1582..686752e742 100644
--- a/apps/erp/app/routes/x+/sales+/contracts.tsx
+++ b/apps/erp/app/routes/x+/sales+/contracts.tsx
@@ -28,11 +28,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ContractsRoute() {
- const { count, contracts, nextCursor } = useLoaderData<typeof loader>();
+ const { count, contracts, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <ContractsTable data={contracts} count={count} nextCursor={nextCursor} />
+ <ContractsTable data={contracts} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/sales+/customer-portals.tsx b/apps/erp/app/routes/x+/sales+/customer-portals.tsx
index 2185a00f8c..f6ae1052ca 100644
--- a/apps/erp/app/routes/x+/sales+/customer-portals.tsx
+++ b/apps/erp/app/routes/x+/sales+/customer-portals.tsx
@@ -30,7 +30,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function CustomerPortalsRoute() {
- const { appUrl, data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { appUrl, data, count, infinite } = useLoaderData<typeof loader>();
const { isGated } = usePlanGate({ feature: "CUSTOMER_PORTALS" });
if (isGated) {
@@ -43,7 +43,7 @@ export default function CustomerPortalsRoute() {
appUrl={appUrl}
data={data}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/sales+/customer-statuses.tsx b/apps/erp/app/routes/x+/sales+/customer-statuses.tsx
index 0163c8618a..bc141557cc 100644
--- a/apps/erp/app/routes/x+/sales+/customer-statuses.tsx
+++ b/apps/erp/app/routes/x+/sales+/customer-statuses.tsx
@@ -22,15 +22,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function CustomerStatusesRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <CustomerStatusesTable
- data={data}
- count={count}
- nextCursor={nextCursor}
- />
+ <CustomerStatusesTable data={data} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/sales+/customer-types.tsx b/apps/erp/app/routes/x+/sales+/customer-types.tsx
index 91fd95b908..5346f653ba 100644
--- a/apps/erp/app/routes/x+/sales+/customer-types.tsx
+++ b/apps/erp/app/routes/x+/sales+/customer-types.tsx
@@ -22,11 +22,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function CustomerTypesRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <CustomerTypesTable data={data} count={count} nextCursor={nextCursor} />
+ <CustomerTypesTable data={data} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/sales+/customers.tsx b/apps/erp/app/routes/x+/sales+/customers.tsx
index 7c7c8e1013..795d63ebab 100644
--- a/apps/erp/app/routes/x+/sales+/customers.tsx
+++ b/apps/erp/app/routes/x+/sales+/customers.tsx
@@ -39,7 +39,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function SalesCustomersRoute() {
- const { count, customers, nextCursor, customerStatuses, tags } =
+ const { count, customers, infinite, customerStatuses, tags } =
useLoaderData<typeof loader>();
return (
@@ -47,7 +47,7 @@ export default function SalesCustomersRoute() {
<CustomersTable
data={customers}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
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.tsx
index 552efbeeb1..345b91d33f 100644
--- a/apps/erp/app/routes/x+/sales+/no-quote-reasons.tsx
+++ b/apps/erp/app/routes/x+/sales+/no-quote-reasons.tsx
@@ -22,11 +22,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ScrapReasonsRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <NoQuoteReasonsTable data={data} count={count} nextCursor={nextCursor} />
+ <NoQuoteReasonsTable data={data} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/sales+/orders.tsx b/apps/erp/app/routes/x+/sales+/orders.tsx
index 1d6686c298..41c3b02ee7 100644
--- a/apps/erp/app/routes/x+/sales+/orders.tsx
+++ b/apps/erp/app/routes/x+/sales+/orders.tsx
@@ -30,15 +30,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function SalesOrdersSearchRoute() {
- const { count, salesOrders, nextCursor } = useLoaderData<typeof loader>();
+ const { count, salesOrders, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <SalesOrdersTable
- data={salesOrders}
- count={count}
- nextCursor={nextCursor}
- />
+ <SalesOrdersTable data={salesOrders} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/sales+/price-list.tsx b/apps/erp/app/routes/x+/sales+/price-list.tsx
index 85f87953f1..a9ccedb05f 100644
--- a/apps/erp/app/routes/x+/sales+/price-list.tsx
+++ b/apps/erp/app/routes/x+/sales+/price-list.tsx
@@ -48,7 +48,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function PriceListRoute() {
- const { data, count, nextCursor, scopeOptions, hasScope } =
+ const { data, count, infinite, scopeOptions, hasScope } =
useLoaderData<typeof loader>();
return (
@@ -56,7 +56,7 @@ export default function PriceListRoute() {
<PriceListTable
data={data}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
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.tsx
index d99cd56d0d..67a179e7cf 100644
--- a/apps/erp/app/routes/x+/sales+/pricing-rules.tsx
+++ b/apps/erp/app/routes/x+/sales+/pricing-rules.tsx
@@ -22,11 +22,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function PricingRulesRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <PricingRulesTable data={data} count={count} nextCursor={nextCursor} />
+ <PricingRulesTable data={data} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/sales+/quotes.tsx b/apps/erp/app/routes/x+/sales+/quotes.tsx
index 810d866349..97c01c44f2 100644
--- a/apps/erp/app/routes/x+/sales+/quotes.tsx
+++ b/apps/erp/app/routes/x+/sales+/quotes.tsx
@@ -30,11 +30,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function QuotesRoute() {
- const { count, quotes, nextCursor } = useLoaderData<typeof loader>();
+ const { count, quotes, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <QuotesTable data={quotes} count={count} nextCursor={nextCursor} />
+ <QuotesTable data={quotes} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/sales+/rental-agreements.tsx b/apps/erp/app/routes/x+/sales+/rental-agreements.tsx
index 2834b931dc..14f25856b2 100644
--- a/apps/erp/app/routes/x+/sales+/rental-agreements.tsx
+++ b/apps/erp/app/routes/x+/sales+/rental-agreements.tsx
@@ -28,15 +28,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function RentalAgreementsRoute() {
- const { count, rentalAgreements, nextCursor } =
- useLoaderData<typeof loader>();
+ const { count, rentalAgreements, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<RentalAgreementsTable
data={rentalAgreements}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/sales+/return-reasons.tsx b/apps/erp/app/routes/x+/sales+/return-reasons.tsx
index fd92d1f04f..83df0fe462 100644
--- a/apps/erp/app/routes/x+/sales+/return-reasons.tsx
+++ b/apps/erp/app/routes/x+/sales+/return-reasons.tsx
@@ -22,11 +22,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ReturnReasonsRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <ReturnReasonsTable data={data} count={count} nextCursor={nextCursor} />
+ <ReturnReasonsTable data={data} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/sales+/rfqs.tsx b/apps/erp/app/routes/x+/sales+/rfqs.tsx
index 0187991fb4..7bacd9fafe 100644
--- a/apps/erp/app/routes/x+/sales+/rfqs.tsx
+++ b/apps/erp/app/routes/x+/sales+/rfqs.tsx
@@ -30,11 +30,11 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function RFQsRoute() {
- const { count, rfqs, nextCursor } = useLoaderData<typeof loader>();
+ const { count, rfqs, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <SalesRFQsTable data={rfqs} count={count} nextCursor={nextCursor} />
+ <SalesRFQsTable data={rfqs} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/sales+/rmas.tsx b/apps/erp/app/routes/x+/sales+/rmas.tsx
index d986ac04df..6506bb2c0f 100644
--- a/apps/erp/app/routes/x+/sales+/rmas.tsx
+++ b/apps/erp/app/routes/x+/sales+/rmas.tsx
@@ -29,15 +29,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function SalesReturnOrdersSearchRoute() {
- const { count, salesReturnOrders, nextCursor } =
- useLoaderData<typeof loader>();
+ const { count, salesReturnOrders, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<SalesReturnOrdersTable
data={salesReturnOrders}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/settings+/api-keys.tsx b/apps/erp/app/routes/x+/settings+/api-keys.tsx
index b97a834cf1..e8582e8121 100644
--- a/apps/erp/app/routes/x+/settings+/api-keys.tsx
+++ b/apps/erp/app/routes/x+/settings+/api-keys.tsx
@@ -31,7 +31,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function ApiKeysRoute() {
- const { apiKeys, count, nextCursor } = useLoaderData<typeof loader>();
+ const { apiKeys, count, infinite } = useLoaderData<typeof loader>();
const { isGated } = usePlanGate({ feature: "API_KEYS" });
if (isGated) {
@@ -39,7 +39,7 @@ export default function ApiKeysRoute() {
}
return (
<>
- <ApiKeysTable count={count} data={apiKeys} nextCursor={nextCursor} />
+ <ApiKeysTable count={count} data={apiKeys} infinite={infinite} />
<RecordOutlet />
</>
);
diff --git a/apps/erp/app/routes/x+/settings+/custom-fields.tsx b/apps/erp/app/routes/x+/settings+/custom-fields.tsx
index b3feb0195d..4bcfd57bf6 100644
--- a/apps/erp/app/routes/x+/settings+/custom-fields.tsx
+++ b/apps/erp/app/routes/x+/settings+/custom-fields.tsx
@@ -57,11 +57,11 @@ export async function action(args: ActionFunctionArgs) {
}
export default function CustomFieldsRoute() {
- const { count, tables, nextCursor } = useLoaderData<typeof loader>();
+ const { count, tables, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <CustomFieldsTable data={tables} count={count} nextCursor={nextCursor} />
+ <CustomFieldsTable data={tables} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/settings+/sequences.tsx b/apps/erp/app/routes/x+/settings+/sequences.tsx
index f726ee645f..c872debd3e 100644
--- a/apps/erp/app/routes/x+/settings+/sequences.tsx
+++ b/apps/erp/app/routes/x+/settings+/sequences.tsx
@@ -22,14 +22,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function SequencesRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<SequencesTable
data={data ?? []}
count={count ?? 0}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/settings+/serial-numbers.tsx b/apps/erp/app/routes/x+/settings+/serial-numbers.tsx
index f093919679..e8195fef8e 100644
--- a/apps/erp/app/routes/x+/settings+/serial-numbers.tsx
+++ b/apps/erp/app/routes/x+/settings+/serial-numbers.tsx
@@ -22,14 +22,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function SerialNumbersRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
<ItemSerialSequencesTable
data={data ?? []}
count={count ?? 0}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/settings+/webhooks.tsx b/apps/erp/app/routes/x+/settings+/webhooks.tsx
index 69d2cc2237..22dd0d32ea 100644
--- a/apps/erp/app/routes/x+/settings+/webhooks.tsx
+++ b/apps/erp/app/routes/x+/settings+/webhooks.tsx
@@ -52,7 +52,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function WebhooksRoute() {
- const { webhooks, count, nextCursor } = useLoaderData<typeof loader>();
+ const { webhooks, count, infinite } = useLoaderData<typeof loader>();
const { isGated } = usePlanGate({ feature: "WEBHOOKS" });
if (isGated) {
@@ -60,7 +60,7 @@ export default function WebhooksRoute() {
}
return (
<>
- <WebhooksTable count={count} data={webhooks} nextCursor={nextCursor} />
+ <WebhooksTable count={count} data={webhooks} infinite={infinite} />
<RecordOutlet />
</>
);
diff --git a/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx b/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx
index 4565c4f551..e49c49fbb7 100644
--- a/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx
+++ b/apps/erp/app/routes/x+/users+/bulk-edit-permissions.tsx
@@ -3,7 +3,6 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { carbon, respond } from "@carbon/api/carbon.server";
-import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import { z } from "zod";
@@ -14,8 +13,7 @@ import {
} from "~/modules/users/users.models";
import { originOf } from "~/modules/users/users.service";
import { getParams, path } from "~/utils/path";
-import { parseAllMatching } from "~/utils/table-jobs";
-import { startTableBulkAction } from "~/utils/table-jobs.server";
+import { startBackgroundBulkAction } from "~/utils/table-jobs.server";
const modulePermissions = z.record(z.string(), userPermissionsValidator);
@@ -23,13 +21,10 @@ export async function action(args: ActionFunctionArgs) {
// Every matching user of the Employees list: the background job picks the
// active users and queues their permission update. The job checks the
// PERMISSIONS feature (`canRunBulkAction`).
- const allMatching = parseAllMatching(
- (await args.request.clone().formData()).get("allMatching")
+ const allMatching = (await args.request.clone().formData()).get(
+ "allMatching"
);
if (allMatching) {
- const { companyId, userId } = await requirePermissions(args.request, {
- update: "users"
- });
const input = await validator(bulkPermissionsAllMatchingValidator).request(
args
);
@@ -45,17 +40,17 @@ export async function action(args: ActionFunctionArgs) {
return { success: false, message: "Failed to parse permissions" };
}
const { ip } = originOf(args.request);
- return startTableBulkAction({
- companyId,
- userId,
- actionKey: "users.permissions",
- params: {
+ const started = await startBackgroundBulkAction(
+ args.request,
+ "users.permissions",
+ { allMatching },
+ {
permissions: permissions.data,
addOnly: input.data.editType === "add",
...(ip ? { ip } : {})
- },
- allMatching
- });
+ }
+ );
+ if (started) return started;
}
const input = await validator(bulkPermissionsValidator).request(args);
diff --git a/apps/erp/app/routes/x+/users+/deactivate.tsx b/apps/erp/app/routes/x+/users+/deactivate.tsx
index 3c30461e9f..3204de652b 100644
--- a/apps/erp/app/routes/x+/users+/deactivate.tsx
+++ b/apps/erp/app/routes/x+/users+/deactivate.tsx
@@ -3,12 +3,11 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { carbon, respond } from "@carbon/api/carbon.server";
-import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import { deactivateUsersValidator } from "~/modules/users/users.models";
import { originOf } from "~/modules/users/users.service";
-import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";
+import { startBackgroundBulkAction } from "~/utils/table-jobs.server";
export async function action(args: ActionFunctionArgs) {
// Every matching user of the Employees list: the background job picks the
@@ -16,19 +15,14 @@ export async function action(args: ActionFunctionArgs) {
const allMatching = (await args.request.clone().formData()).get(
"allMatching"
);
- if (allMatching) {
- const { companyId, userId } = await requirePermissions(args.request, {
- delete: "users"
- });
- const { ip } = originOf(args.request);
- const started = await startAllMatchingBulkAction(allMatching, {
- companyId,
- userId,
- actionKey: "users.deactivate",
- params: ip ? { ip } : {}
- });
- if (started) return started;
- }
+ const { ip } = originOf(args.request);
+ const started = await startBackgroundBulkAction(
+ args.request,
+ "users.deactivate",
+ { allMatching },
+ ip ? { ip } : {}
+ );
+ if (started) return started;
const input = await validator(deactivateUsersValidator).request(args);
if ("invalid" in input) return input.invalid;
diff --git a/apps/erp/app/routes/x+/users+/employee-types.tsx b/apps/erp/app/routes/x+/users+/employee-types.tsx
index 79ecf0b32f..76d0931e7b 100644
--- a/apps/erp/app/routes/x+/users+/employee-types.tsx
+++ b/apps/erp/app/routes/x+/users+/employee-types.tsx
@@ -26,7 +26,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
export default function EmployeeTypesRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
const { isGated } = usePlanGate({ feature: "PERMISSIONS" });
if (isGated) {
@@ -38,7 +38,7 @@ export default function EmployeeTypesRoute() {
<EmployeeTypesTable
data={data ?? []}
count={count ?? 0}
- nextCursor={nextCursor}
+ infinite={infinite}
/>
<RecordOutlet />
</VStack>
diff --git a/apps/erp/app/routes/x+/users+/employees.tsx b/apps/erp/app/routes/x+/users+/employees.tsx
index 018fdba3a6..3caee502c3 100644
--- a/apps/erp/app/routes/x+/users+/employees.tsx
+++ b/apps/erp/app/routes/x+/users+/employees.tsx
@@ -76,7 +76,7 @@ export default function UsersEmployeesRoute() {
const {
count,
employees,
- nextCursor,
+ infinite,
employeeTypes,
unrevokedInviteEmails,
mfaEnrolledUserIds
@@ -87,7 +87,7 @@ export default function UsersEmployeesRoute() {
<EmployeesTable
data={employees}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
employeeTypes={employeeTypes}
unrevokedInviteEmails={unrevokedInviteEmails}
mfaEnrolledUserIds={mfaEnrolledUserIds}
diff --git a/apps/erp/app/routes/x+/users+/operators.tsx b/apps/erp/app/routes/x+/users+/operators.tsx
index ef21d12281..447ac72c90 100644
--- a/apps/erp/app/routes/x+/users+/operators.tsx
+++ b/apps/erp/app/routes/x+/users+/operators.tsx
@@ -18,6 +18,7 @@ import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData, useNavigate } from "react-router";
import { EmployeeAvatar, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
+import type { InfiniteOptions } from "~/components/Table";
import { usePermissions, useUrlParams } from "~/hooks";
import type { getConsoleOperators } from "~/modules/users/users.service";
import { getEmployeeTypes } from "~/modules/users/users.service";
@@ -55,12 +56,12 @@ const OperatorsTable = memo(
({
data,
count,
- nextCursor,
+ infinite,
employeeTypes
}: {
data: Operator[];
count: number;
- nextCursor: string | null;
+ infinite: InfiniteOptions;
employeeTypes: ListItem[];
}) => {
const { t } = useLingui();
@@ -173,11 +174,7 @@ const OperatorsTable = memo(
count={count}
columns={columns}
data={data}
- infinite={{
- dataKey: "operators",
- nextCursor,
- listKey: "console-operators"
- }}
+ infinite={infinite}
primaryAction={
permissions.can("create", "users") && (
<New label={t`Operator`} to={`new?${params.toString()}`} />
@@ -193,7 +190,7 @@ const OperatorsTable = memo(
OperatorsTable.displayName = "OperatorsTable";
export default function ConsoleOperatorsRoute() {
- const { count, operators, nextCursor, employeeTypes } =
+ const { count, operators, infinite, employeeTypes } =
useLoaderData<typeof loader>();
return (
@@ -201,7 +198,7 @@ export default function ConsoleOperatorsRoute() {
<OperatorsTable
data={operators}
count={count}
- nextCursor={nextCursor}
+ infinite={infinite}
employeeTypes={employeeTypes}
/>
<RecordOutlet />
diff --git a/apps/erp/app/routes/x+/users+/resend-invite.tsx b/apps/erp/app/routes/x+/users+/resend-invite.tsx
index b8ba454347..2a309510ee 100644
--- a/apps/erp/app/routes/x+/users+/resend-invite.tsx
+++ b/apps/erp/app/routes/x+/users+/resend-invite.tsx
@@ -3,12 +3,11 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { carbon } from "@carbon/api/carbon.server";
-import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import { resendInviteValidator } from "~/modules/users/users.models";
import { originOf } from "~/modules/users/users.service";
-import { startAllMatchingBulkAction } from "~/utils/table-jobs.server";
+import { startBackgroundBulkAction } from "~/utils/table-jobs.server";
export async function action(args: ActionFunctionArgs) {
const { ip, city } = originOf(args.request);
@@ -18,18 +17,13 @@ export async function action(args: ActionFunctionArgs) {
const allMatching = (await args.request.clone().formData()).get(
"allMatching"
);
- if (allMatching) {
- const { companyId, userId } = await requirePermissions(args.request, {
- create: "users"
- });
- const started = await startAllMatchingBulkAction(allMatching, {
- companyId,
- userId,
- actionKey: "users.invite",
- params: { location: city ?? "Unknown", ip: ip ?? "127.0.0.1" }
- });
- if (started) return started;
- }
+ const started = await startBackgroundBulkAction(
+ args.request,
+ "users.invite",
+ { allMatching },
+ { location: city ?? "Unknown", ip: ip ?? "127.0.0.1" }
+ );
+ if (started) return started;
const input = await validator(resendInviteValidator).request(args);
if ("invalid" in input) return input.invalid;
diff --git a/apps/erp/app/routes/x+/workflows+/_index.tsx b/apps/erp/app/routes/x+/workflows+/_index.tsx
index d774b8daaf..947c31e04b 100644
--- a/apps/erp/app/routes/x+/workflows+/_index.tsx
+++ b/apps/erp/app/routes/x+/workflows+/_index.tsx
@@ -9,21 +9,14 @@ import { usePlanGate } from "~/hooks/usePlanGate";
import WorkflowsTable from "~/modules/workflows/ui/WorkflowsTable";
import WorkflowsUpgradeOverlay from "~/modules/workflows/ui/WorkflowsUpgradeOverlay";
import { loadListPage } from "~/utils/list-registry/load.server";
-import {
- withWorkflowListExtras,
- workflowsList
-} from "~/utils/list-registry/workflows.server";
+import { workflowsList } from "~/utils/list-registry/workflows.server";
export async function loader({ request }: LoaderFunctionArgs) {
- return loadListPage(request, workflowsList, {
- dataKey: "data",
- // The published version number and the last run of each page's rows.
- mapRows: withWorkflowListExtras
- });
+ return loadListPage(request, workflowsList, { dataKey: "data" });
}
export default function WorkflowsIndexRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
const { isGated } = usePlanGate({ feature: "WORKFLOWS" });
if (isGated) {
@@ -32,7 +25,7 @@ export default function WorkflowsIndexRoute() {
return (
<VStack spacing={0} className="h-full">
- <WorkflowsTable data={data} count={count} nextCursor={nextCursor} />
+ <WorkflowsTable data={data} count={count} infinite={infinite} />
</VStack>
);
}
diff --git a/apps/erp/app/routes/x+/workflows+/runs.tsx b/apps/erp/app/routes/x+/workflows+/runs.tsx
index eaeb1e5ce4..779fe19d94 100644
--- a/apps/erp/app/routes/x+/workflows+/runs.tsx
+++ b/apps/erp/app/routes/x+/workflows+/runs.tsx
@@ -2,78 +2,34 @@
// 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 { 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 WorkflowRunsTable from "~/modules/workflows/ui/Runs/WorkflowRunsTable";
-import { getWorkflowRunRecordNames } from "~/modules/workflows/workflows.service";
-import { fetchListPage } from "~/utils/list-registry/index.server";
-import { listErrorPage } from "~/utils/list-registry/load.server";
+import { loadListPage } from "~/utils/list-registry/load.server";
import { workflowRunsList } from "~/utils/list-registry/workflows.server";
import { path } from "~/utils/path";
-const logger = getLogger("erp", "workflow-runs");
-
export async function loader({ request }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(
- request,
- workflowRunsList.permission
- );
- await requireFeature({
- request,
- client,
- companyId,
- feature: "WORKFLOWS",
- redirectTo: path.to.workflows
+ return loadListPage(request, workflowRunsList, {
+ dataKey: "data",
+ guard: ({ client, companyId }) =>
+ requireFeature({
+ request,
+ client,
+ companyId,
+ feature: "WORKFLOWS",
+ redirectTo: path.to.workflows
+ })
});
-
- const searchParams = new URL(request.url).searchParams;
- const runs = await fetchListPage(
- workflowRunsList,
- client,
- companyId,
- searchParams
- );
-
- if (runs.error && searchParams.get("after")) {
- logger.error("Failed to load a later page of workflow runs", {
- companyId,
- error: runs.error
- });
- return listErrorPage("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,
- data.flatMap((run) =>
- run.triggerTable && run.triggerRecordId
- ? [{ table: run.triggerTable, id: run.triggerRecordId }]
- : []
- )
- );
-
- return {
- data: data.map((run) => ({
- ...run,
- recordName: recordNames[`${run.triggerTable}:${run.triggerRecordId}`]
- })),
- count: runs.count,
- exactCount: runs.exactCount,
- nextCursor: runs.nextCursor
- };
}
export default function WorkflowRunsRoute() {
- const { data, count, nextCursor } = useLoaderData<typeof loader>();
+ const { data, count, infinite } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <WorkflowRunsTable data={data} count={count} nextCursor={nextCursor} />
+ <WorkflowRunsTable data={data} count={count} infinite={infinite} />
<RecordOutlet />
</VStack>
);
diff --git a/apps/erp/app/utils/bulk-delete.server.ts b/apps/erp/app/utils/bulk-delete.server.ts
deleted file mode 100644
index 52db44b2b3..0000000000
--- a/apps/erp/app/utils/bulk-delete.server.ts
+++ /dev/null
@@ -1,67 +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 { 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 {label}", {
- label: 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/item-bulk-actions.server.ts b/apps/erp/app/utils/item-bulk-actions.server.ts
deleted file mode 100644
index 91d0d55d76..0000000000
--- a/apps/erp/app/utils/item-bulk-actions.server.ts
+++ /dev/null
@@ -1,132 +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 { ServiceContext } from "@carbon/api/service-fn.server";
-import { getLogger } from "@carbon/logger";
-import { chunkArray } from "@carbon/utils";
-import {
- type ItemBulkUpdateField,
- itemReplenishmentSystems,
- itemTrackingTypes
-} from "~/modules/items/items.models";
-import {
- setItemPostingGroup,
- setItemSourcing,
- setItemTrackingType
-} from "~/modules/items/items.server";
-import { methodType, sourcingType } from "~/modules/shared/shared.models";
-
-/**
- * The background bulk-action job's slices of the items tables' Update
- * (`~/utils/table-jobs.server`). Each chunk runs the items service function
- * the in-request action runs, so the value is checked and the cascades run
- * the same way on both paths.
- */
-
-const logger = getLogger("erp", "item-bulk-actions");
-
-/** An `.in()` filter rides in the request URL, so items go 100 at a time. */
-const ITEM_BULK_CHUNK = 100;
-
-const allowedValues: Partial<Record<ItemBulkUpdateField, readonly string[]>> = {
- itemTrackingType: itemTrackingTypes,
- replenishmentSystem: itemReplenishmentSystems,
- defaultMethodType: methodType,
- sourcingType: sourcingType
-};
-
-/** Whether `value` is one the field takes. Any item group id (or none) is. */
-export function isItemBulkUpdateValue(
- field: ItemBulkUpdateField,
- value: string
-) {
- const allowed = allowedValues[field];
- return allowed === undefined || allowed.includes(value);
-}
-
-function updateItems(
- ctx: ServiceContext,
- ids: string[],
- field: ItemBulkUpdateField,
- value: string
-) {
- switch (field) {
- case "itemTrackingType":
- return setItemTrackingType(ctx, {
- ids,
- itemTrackingType: value as (typeof itemTrackingTypes)[number]
- });
- case "replenishmentSystem":
- case "defaultMethodType":
- case "sourcingType":
- return setItemSourcing(ctx, { ids, [field]: value });
- case "itemPostingGroupId":
- return setItemPostingGroup(ctx, {
- ids,
- itemPostingGroupId: value || null
- });
- }
-}
-
-export type BulkUpdateItemsResult = {
- done: number;
- /** Ids that are not the company's items. */
- skipped: number;
- /** Items whose chunk failed. */
- failed: number;
- error: string | null;
-};
-
-/**
- * Sets one field on many items, 100 at a time. 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(
- ctx: ServiceContext,
- {
- itemIds,
- field,
- value
- }: { itemIds: string[]; field: ItemBulkUpdateField; value: string }
-): Promise<BulkUpdateItemsResult> {
- const companyId = ctx.company.id;
- const result: BulkUpdateItemsResult = {
- done: 0,
- skipped: 0,
- failed: 0,
- error: null
- };
- const ids = [...new Set(itemIds.filter(Boolean))];
- for (const chunk of chunkArray(ids, ITEM_BULK_CHUNK)) {
- // The item group write inserts a cost row for each id, so keep only the
- // company's own items.
- const items = await ctx.asCaller.supabase
- .from("item")
- .select("id")
- .in("id", chunk)
- .eq("companyId", companyId);
- if (items.error) {
- logger.error("Failed to read the items of a bulk update", {
- companyId,
- error: items.error
- });
- result.failed += chunk.length;
- result.error ??= items.error.message;
- continue;
- }
- const owned = items.data.map((item) => item.id);
- result.skipped += chunk.length - owned.length;
- if (owned.length === 0) continue;
-
- const update = await updateItems(ctx, owned, field, value);
- if (update.error) {
- result.failed += owned.length;
- result.error ??= update.error.message;
- } else {
- result.done += owned.length;
- }
- }
- return result;
-}
diff --git a/apps/erp/app/utils/list-registry/export-values.ts b/apps/erp/app/utils/list-registry/export-values.ts
index 87ba00b3e3..f36e364847 100644
--- a/apps/erp/app/utils/list-registry/export-values.ts
+++ b/apps/erp/app/utils/list-registry/export-values.ts
@@ -2,12 +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.
-/** A column's export value, computed from a row (`meta.exportValue`). */
-export type ListExportValues<TRow> = Record<string, (row: TRow) => unknown>;
+/** A column's export value, computed from a row (`meta.exportValue`). A
+ * method type, so a list typed to its own rows still fits the registry's
+ * `ListDefinition`. */
+type ExportValue<TRow> = { value(row: TRow): unknown }["value"];
+
+export type ListExportValues<TRow> = Record<string, ExportValue<TRow>>;
/**
- * Each row with `values` computed onto it, keyed by column: what a list's
- * `exportRows` hands the background export, which reads `row[key]`.
+ * Each row with `values` computed onto it, keyed by column: what the
+ * background export writes (`exportListRows`), reading `row[key]`.
*/
export function withExportValues<TRow extends Record<string, unknown>>(
rows: TRow[],
diff --git a/apps/erp/app/utils/list-registry/index.server.ts b/apps/erp/app/utils/list-registry/index.server.ts
index d9983c90f4..7dcb3e5ecf 100644
--- a/apps/erp/app/utils/list-registry/index.server.ts
+++ b/apps/erp/app/utils/list-registry/index.server.ts
@@ -11,6 +11,7 @@ import type { Filter, Sort } from "../query";
import { getGenericQueryFilters } from "../query";
import { accountingLists } from "./accounting.server";
import { documentsLists } from "./documents.server";
+import { type ListExportValues, withExportValues } from "./export-values";
import { inventoryLists } from "./inventory.server";
import { invoicingLists } from "./invoicing.server";
import { itemsLists } from "./items.server";
@@ -78,7 +79,8 @@ export type ListRowsContext = {
};
export type ListDefinition<
- TRow extends Record<string, unknown> = Record<string, unknown>
+ TRow extends Record<string, unknown> = Record<string, unknown>,
+ TOut extends Record<string, unknown> = TRow
> = Paging & {
/** The list's key, for example "sales-orders". */
key: string;
@@ -91,15 +93,19 @@ export type ListDefinition<
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.
+ * Adds the per-row values the list's view does not have (a lookup in
+ * another table) to the rows of one page. `loadListPage` runs it on every
+ * page and the background CSV export on every part, so the table and the
+ * file show the same values. A failed lookup throws: a blank column would
+ * read as "none".
*/
- exportRows?(
- rows: TRow[],
- context: ListRowsContext
- ): Promise<Record<string, unknown>[]>;
+ rows?(rows: TRow[], context: ListRowsContext): Promise<TOut[]>;
+ /**
+ * The export values (`meta.exportValue`) of the columns that show a value
+ * computed from the row, by column key. The background export runs no
+ * column code, so it writes these under their keys.
+ */
+ exportValues?: ListExportValues<TOut>;
};
export type ListPage<TRow> = {
@@ -140,8 +146,11 @@ export function getListDefinition(key: string): ListDefinition | undefined {
* or the exact count for `?count=exact`.
* `options.companyGroupId` saves a group lookup for group-scoped lists.
*/
-export async function fetchListPage<TRow extends Record<string, unknown>>(
- definition: ListDefinition<TRow>,
+export async function fetchListPage<
+ TRow extends Record<string, unknown>,
+ TOut extends Record<string, unknown> = TRow
+>(
+ definition: ListDefinition<TRow, TOut>,
client: SupabaseClient<Database>,
companyId: string,
params: URLSearchParams,
@@ -176,6 +185,26 @@ export async function fetchListPage<TRow extends Record<string, unknown>>(
};
}
+/**
+ * One page's rows as the background CSV export writes them: the list's own
+ * `rows` lookup, then its columns' `exportValues` under their keys.
+ */
+export async function exportListRows<
+ TRow extends Record<string, unknown>,
+ TOut extends Record<string, unknown>
+>(
+ definition: ListDefinition<TRow, TOut>,
+ rows: TRow[],
+ context: ListRowsContext
+): Promise<Record<string, unknown>[]> {
+ const withRows = definition.rows
+ ? await definition.rows(rows, context)
+ : (rows as unknown as TOut[]);
+ return definition.exportValues
+ ? withExportValues(withRows, definition.exportValues)
+ : withRows;
+}
+
/**
* The company's group for a group-scoped list (dimensions, intercompany):
* the caller's when it passed one, else read from the company.
@@ -221,13 +250,18 @@ type ParamReader = string | ((params: URLSearchParams) => unknown);
* 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>({
+export function searchList<
+ TRow extends Record<string, unknown>,
+ TArgs,
+ TOut extends Record<string, unknown> = TRow
+>({
key,
permission,
paging,
service,
params: readers = {},
- exportRows
+ rows,
+ exportValues
}: {
key: string;
permission: ListPermission;
@@ -238,13 +272,15 @@ export function searchList<TRow extends Record<string, unknown>, TArgs>({
args: TArgs
) => PromiseLike<ListQueryResult<TRow>>;
params?: Record<string, ParamReader>;
- exportRows?: ListDefinition<TRow>["exportRows"];
-}): ListDefinition<TRow> {
+ rows?: (rows: TRow[], context: ListRowsContext) => Promise<TOut[]>;
+ exportValues?: Record<string, (row: TOut) => unknown>;
+}): ListDefinition<TRow, TOut> {
return {
key,
permission,
...paging,
- ...(exportRows ? { exportRows } : {}),
+ ...(rows ? { rows } : {}),
+ ...(exportValues ? { exportValues } : {}),
query: (
client,
companyId,
diff --git a/apps/erp/app/utils/list-registry/load.server.ts b/apps/erp/app/utils/list-registry/load.server.ts
index c94d377af5..a1271dca50 100644
--- a/apps/erp/app/utils/list-registry/load.server.ts
+++ b/apps/erp/app/utils/list-registry/load.server.ts
@@ -7,7 +7,10 @@ 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 {
+ InfiniteListError,
+ InfiniteOptions
+} from "~/components/Table/types";
import type { ListDefinition } from "./index.server";
import { fetchListPage } from "./index.server";
import { listErrorPage } from "./list-error";
@@ -26,14 +29,30 @@ export type ListLoaderContext = Awaited<
};
/** The loader data of a list page: the rows under `dataKey`, the count and
- * the cursor, plus `listError` on a failed later page. */
+ * the cursor, plus `listError` on a failed later page. Page 1 also carries
+ * the Table's `infinite` prop, so a table never restates the list's keys. */
export type ListLoaderData<TKey extends string, TRow> = {
[K in TKey]: TRow[];
} & {
count: number;
nextCursor: string | null;
+ infinite: InfiniteOptions;
} & Partial<InfiniteListError>;
+/** The Table's `infinite` prop for a page of a registered list. */
+export function listInfinite(
+ list: Pick<ListDefinition, "key" | "idColumn">,
+ dataKey: string,
+ nextCursor: string | null
+): InfiniteOptions {
+ return {
+ dataKey,
+ nextCursor,
+ listKey: list.key,
+ ...(list.idColumn ? { idColumn: list.idColumn } : {})
+ };
+}
+
export type LoadListPageOptions<
TKey extends string,
TExtra,
@@ -62,9 +81,10 @@ export type LoadListPageOptions<
*/
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.
+ * Adds per-row values only the screen needs (a download token) to the rows
+ * of every page, after the list's own `rows` lookup. A value a column
+ * exports belongs in the list's `rows`, which the background export runs
+ * too. Runs after a page loads without an error.
*/
mapRows?: (rows: TRow[], context: ListLoaderContext) => Promise<TOut[]>;
/**
@@ -81,8 +101,8 @@ export type LoadListPageOptions<
* 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.
+ * 3. `firstPage` extras on page 1 only, in parallel with the page; the
+ * list's `rows` lookup, then `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.
*
@@ -110,11 +130,12 @@ export async function loadListPage<
TRow extends Record<string, unknown>,
TKey extends string,
TExtra extends Record<string, unknown> = Record<never, never>,
- TOut = TRow
+ TListRow extends Record<string, unknown> = TRow,
+ TOut = TListRow
>(
request: Request,
- list: ListDefinition<TRow>,
- options: LoadListPageOptions<TKey, TExtra, TRow, TOut>
+ list: ListDefinition<TRow, TListRow>,
+ options: LoadListPageOptions<TKey, TExtra, TListRow, TOut>
): Promise<ListLoaderData<TKey, TOut> & TExtra> {
const auth = await requirePermissions(
request,
@@ -176,16 +197,24 @@ export async function loadListPage<
} as unknown as ListLoaderData<TKey, TOut> & TExtra;
}
+ const listRows =
+ list.rows && !page.error
+ ? await list.rows(page.rows, {
+ client: auth.client,
+ companyId: auth.companyId
+ })
+ : (page.rows as unknown as TListRow[]);
const rows =
options.mapRows && !page.error
- ? await options.mapRows(page.rows, context)
- : page.rows;
+ ? await options.mapRows(listRows, context)
+ : listRows;
return {
...extra,
[options.dataKey]: rows,
count: page.count,
- nextCursor: page.nextCursor
+ nextCursor: page.nextCursor,
+ infinite: listInfinite(list, options.dataKey, page.nextCursor)
} as ListLoaderData<TKey, TOut> & TExtra;
};
diff --git a/apps/erp/app/utils/list-registry/production.server.ts b/apps/erp/app/utils/list-registry/production.server.ts
index 7f3da9c710..628b611445 100644
--- a/apps/erp/app/utils/list-registry/production.server.ts
+++ b/apps/erp/app/utils/list-registry/production.server.ts
@@ -7,6 +7,8 @@ import {
ASSEMBLY_INSTRUCTIONS_PAGING,
getAssemblyInstructionsPage,
getJobOperationBatches,
+ getJobOperationBatchMemberStats,
+ getJobOperationBatchMembers,
getJobs,
getProcedures,
getScrapReasons,
@@ -15,16 +17,13 @@ import {
PROCEDURES_PAGING,
SCRAP_REASONS_PAGING
} from "~/modules/production/production.service";
+import { BATCH_LIST_EXPORT_VALUES } from "~/modules/production/ui/Batches/batch-list-export";
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`.
- */
+/** The live batches and the tracked entity of each job: the jobs view has
+ * neither. */
export async function withJobListExtras<
T extends { id: string | null; jobMakeMethodId: string | null }
>(jobs: T[], { client, companyId }: ListRowsContext) {
@@ -97,11 +96,8 @@ export const jobsList = searchList({
permission: { view: "production", role: "employee" },
paging: JOBS_PAGING,
service: getJobs,
- exportRows: async (rows, context) =>
- withExportValues(
- await withJobListExtras(rows, context),
- JOB_LIST_EXPORT_VALUES
- )
+ rows: withJobListExtras,
+ exportValues: JOB_LIST_EXPORT_VALUES
});
export const assemblyInstructionsList = {
@@ -124,11 +120,40 @@ export const assemblyInstructionsList = {
})
} satisfies ListDefinition;
+/**
+ * Each batch's member count, summed quantity, work center and member rows
+ * (for the expandable sub-list): the batches view has none of them.
+ */
+async function withBatchListExtras<
+ T extends { id: string; workCenter: { name: string | null } | null }
+>(batches: T[], { client, companyId }: ListRowsContext) {
+ const batchIds = batches.map((batch) => batch.id);
+ const [stats, members] = await Promise.all([
+ getJobOperationBatchMemberStats(client, companyId, batchIds),
+ getJobOperationBatchMembers(client, companyId, batchIds)
+ ]);
+ if (stats.error) throw stats.error;
+ if (members.error) throw members.error;
+ return batches.map((batch) => ({
+ ...batch,
+ memberCount: stats.data[batch.id]?.memberCount ?? 0,
+ totalQuantity: stats.data[batch.id]?.totalQuantity ?? 0,
+ // The header work center when assigned, else the members' shared one
+ // (the board's own fallback): a board-created batch has no header work
+ // center until its card is dragged.
+ workCenterName:
+ batch.workCenter?.name ?? stats.data[batch.id]?.workCenterName ?? null,
+ members: members.data[batch.id] ?? []
+ }));
+}
+
export const operationBatchesList = searchList({
key: "operation-batches",
permission: { view: "production", role: "employee" },
paging: JOB_OPERATION_BATCHES_PAGING,
- service: getJobOperationBatches
+ service: getJobOperationBatches,
+ rows: withBatchListExtras,
+ exportValues: BATCH_LIST_EXPORT_VALUES
});
export const proceduresList = searchList({
diff --git a/apps/erp/app/utils/list-registry/purchasing.server.ts b/apps/erp/app/utils/list-registry/purchasing.server.ts
index c0f99b919e..f0007b52cf 100644
--- a/apps/erp/app/utils/list-registry/purchasing.server.ts
+++ b/apps/erp/app/utils/list-registry/purchasing.server.ts
@@ -22,7 +22,6 @@ import {
} from "~/modules/purchasing/purchasing.service";
import type { SupplierReportContacts } from "~/modules/purchasing/types";
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";
@@ -75,11 +74,8 @@ export const supplierTypesList = {
})
} 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`.
- */
+/** The report contacts (purchasing, invoice, shipping) of each supplier: the
+ * suppliers view has none. */
export async function withSupplierReportContacts<
T extends { id: string | null }
>(suppliers: T[], { client, companyId }: ListRowsContext) {
@@ -116,11 +112,8 @@ export const suppliersList = searchList({
paging: SUPPLIERS_PAGING,
service: getSuppliers,
params: { type: "type", status: "status" },
- exportRows: async (rows, context) =>
- withExportValues(
- await withSupplierReportContacts(rows, context),
- SUPPLIER_CONTACT_VALUES
- )
+ rows: withSupplierReportContacts,
+ exportValues: SUPPLIER_CONTACT_VALUES
});
export const leasesList = searchList({
diff --git a/apps/erp/app/utils/list-registry/workflows.server.ts b/apps/erp/app/utils/list-registry/workflows.server.ts
index 405eaf92c0..dc204b0786 100644
--- a/apps/erp/app/utils/list-registry/workflows.server.ts
+++ b/apps/erp/app/utils/list-registry/workflows.server.ts
@@ -2,25 +2,22 @@
// 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 { WORKFLOW_RUN_LIST_EXPORT_VALUES } from "~/modules/workflows/ui/Runs/workflow-run-list-export";
import { WORKFLOW_LIST_EXPORT_VALUES } from "~/modules/workflows/ui/workflow-list-export";
import type { WorkflowLastRun } from "~/modules/workflows/workflows.service";
import {
getWorkflowLastRuns,
+ getWorkflowRunRecordNames,
getWorkflowRuns,
getWorkflows,
getWorkflowVersionNumbers,
WORKFLOW_RUNS_PAGING,
WORKFLOWS_PAGING
} from "~/modules/workflows/workflows.service";
-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`.
- */
+/** The published version number and the last run of each workflow. */
export async function withWorkflowListExtras<
T extends { id: string; publishedVersionId: string | null }
>(rows: T[], { client, companyId }: ListRowsContext) {
@@ -63,18 +60,36 @@ export const workflowsList = searchList({
permission: { view: "workflows", role: "employee" },
paging: WORKFLOWS_PAGING,
service: getWorkflows,
- exportRows: async (rows, context) =>
- withExportValues(
- await withWorkflowListExtras(rows, context),
- WORKFLOW_LIST_EXPORT_VALUES
- )
+ rows: withWorkflowListExtras,
+ exportValues: WORKFLOW_LIST_EXPORT_VALUES
});
+/** The name of the record each run was triggered by. */
+async function withWorkflowRunRecordNames<
+ T extends { triggerTable: string | null; triggerRecordId: string | null }
+>(runs: T[], { client, companyId }: ListRowsContext) {
+ const names = await getWorkflowRunRecordNames(
+ client,
+ companyId,
+ runs.flatMap((run) =>
+ run.triggerTable && run.triggerRecordId
+ ? [{ table: run.triggerTable, id: run.triggerRecordId }]
+ : []
+ )
+ );
+ return runs.map((run) => ({
+ ...run,
+ recordName: names[`${run.triggerTable}:${run.triggerRecordId}`]
+ }));
+}
+
export const workflowRunsList = searchList({
key: "workflow-runs",
permission: { view: "workflows", role: "employee" },
paging: WORKFLOW_RUNS_PAGING,
- service: getWorkflowRuns
+ service: getWorkflowRuns,
+ rows: withWorkflowRunRecordNames,
+ exportValues: WORKFLOW_RUN_LIST_EXPORT_VALUES
});
// The workflows lists. Each entry follows `sales.server.ts`.
diff --git a/apps/erp/app/utils/production-bulk-actions.server.ts b/apps/erp/app/utils/production-bulk-actions.server.ts
deleted file mode 100644
index 0878b490df..0000000000
--- a/apps/erp/app/utils/production-bulk-actions.server.ts
+++ /dev/null
@@ -1,324 +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 { ServiceContext } from "@carbon/api/service-fn.server";
-import { getLogger } from "@carbon/logger";
-import { runLocationSchedule } from "@carbon/planning";
-import { chunkArray } from "@carbon/utils";
-import {
- isBatchDissolvable,
- isJobBulkReleasable
-} from "~/modules/production/production.models";
-import {
- releaseBatches,
- releaseCheckedJobs,
- updateBatch
-} from "~/modules/production/production.server";
-import { getJobReleaseReadiness } from "~/modules/production/production.service";
-import {
- bulkReleaseStartingPurchaseOrders,
- jobReleaseProblems
-} from "~/modules/production/ui/Jobs/job-release-logic";
-import { splitIdsByStatus } from "./table-jobs";
-
-/**
- * The background bulk-action job's slices of the jobs and batches tables'
- * Release and Dissolve (`~/utils/table-jobs.server`). Each runs the
- * production service functions the in-request actions run, in the context
- * the job builds; a row the action may not act on is skipped.
- */
-
-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 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[];
- /** Jobs that are not Draft or Planned (a stale selection). */
- skipped: number;
- scheduled: boolean;
- /** The PO each supplier's outside operations went on. The next slice
- * of the same release takes it. */
- purchaseOrdersBySupplierId: Record<string, string>;
- }
- | { success: false; message: string };
-
-/**
- * Releases each Draft / Planned job on its own (`releaseCheckedJobs`): 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. Then each location is scheduled once.
- *
- * A background release runs in slices of 25 jobs. `purchaseOrdersBySupplierId`
- * is the map the previous slice returned: a supplier keeps the PO an earlier
- * slice created instead of being asked to choose (`bulkReleaseStartingPurchaseOrders`).
- */
-export async function bulkReleaseJobs(
- ctx: ServiceContext,
- {
- jobIds,
- purchaseOrdersBySupplierId
- }: {
- jobIds: string[];
- purchaseOrdersBySupplierId?: Record<string, string>;
- }
-): Promise<BulkReleaseJobsResult> {
- const companyId = ctx.company.id;
- const client = ctx.asCaller.supabase;
- const ids = [...new Set(jobIds.filter(Boolean))];
- const jobs = [];
- for (const batch of chunkArray(ids, IN_CHUNK)) {
- const page = await client
- .from("job")
- .select("id, jobId, status, 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(
- 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, 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
- );
- 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
- ? [
- ...jobReleaseProblems(ready),
- ...(ready.supplierIds.some((id) => starting.suppliersToChoose.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 releaseCheckedJobs(ctx, {
- jobIds: [job.id],
- purchaseOrdersBySupplierId: purchaseOrders
- });
- const failure = result.error ?? result.data.failure;
- if (result.data) purchaseOrders = result.data.purchaseOrdersBySupplierId;
- if (failure) {
- logger.error("Failed to release job", {
- companyId,
- jobId: job.id,
- error: failure
- });
- }
- // 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.data?.releasedJobIds.includes(job.id)) {
- failed.push({ readableId: job.jobId, message: failure?.message ?? "" });
- continue;
- }
- if (failure) {
- warnings.push({ readableId: job.jobId, message: failure.message });
- }
-
- if (job.locationId) 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: ctx.asSystem.pg,
- client: ctx.asSystem.supabase,
- locationId,
- companyId,
- userId: ctx.auditUserId
- });
- } 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 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 };
-
-export type BulkReleaseBatchesResult =
- | (Extract<BulkBatchResult, { success: true }> & {
- /** The PO each supplier's outside operations went on. The next slice
- * of the same release takes it. */
- purchaseOrdersBySupplierId: Record<string, string>;
- })
- | { success: false; message: string };
-
-/**
- * Releases the Planned batches (`releaseBatches`): a batch whose member jobs
- * fail their checks, or that has a PO to choose, is reported in `failed`
- * while the rest still release. Any other status is skipped.
- *
- * `purchaseOrdersBySupplierId` is the map the previous slice returned: a
- * supplier keeps the PO an earlier batch of this release created instead of
- * being asked to choose.
- */
-export async function bulkReleaseBatches(
- ctx: ServiceContext,
- {
- batchIds,
- purchaseOrdersBySupplierId = {}
- }: {
- batchIds: string[];
- purchaseOrdersBySupplierId?: Record<string, string>;
- }
-): Promise<BulkReleaseBatchesResult> {
- const ids = [...new Set(batchIds.filter(Boolean))];
- if (ids.length === 0) {
- return {
- success: true,
- done: 0,
- failed: [],
- skipped: 0,
- purchaseOrdersBySupplierId
- };
- }
- const result = await releaseBatches(ctx, {
- batchIds: ids,
- carriedPurchaseOrders: purchaseOrdersBySupplierId
- });
- if (result.error) {
- logger.error("Failed to release batches", {
- companyId: ctx.company.id,
- error: result.error
- });
- return { success: false, message: result.error.message };
- }
- return {
- success: true,
- done: result.data.released.length,
- failed: result.data.failed.map(({ readableId, message }) => ({
- readableId,
- message
- })),
- skipped: result.data.skipped.length,
- purchaseOrdersBySupplierId: result.data.purchaseOrdersBySupplierId
- };
-}
-
-/**
- * Dissolves each Planned or Active batch on its own (`updateBatch`): a batch
- * that has recorded production is refused and reported in `failed`. A
- * Completing or Completed batch is skipped.
- */
-export async function bulkDissolveBatches(
- ctx: ServiceContext,
- { batchIds }: { batchIds: string[] }
-): Promise<BulkBatchResult> {
- const companyId = ctx.company.id;
- const ids = [...new Set(batchIds.filter(Boolean))];
- const rows: { id: string; readableId: string; status: string }[] = [];
- for (const chunk of chunkArray(ids, IN_CHUNK)) {
- const page = await ctx.asCaller.supabase
- .from("jobOperationBatch")
- .select("id, readableId, status")
- .in("id", chunk)
- .eq("companyId", companyId);
- if (page.error) {
- logger.error("Failed to load the batches to dissolve", {
- companyId,
- error: page.error
- });
- return { success: false, message: "Failed to load the selected batches" };
- }
- rows.push(...page.data);
- }
- const readableById = new Map(
- rows.map((row) => [row.id, row.readableId] as const)
- );
- const { allowed, skipped } = splitIdsByStatus(ids, rows, isBatchDissolvable);
-
- let dissolved = 0;
- const failed: Problem[] = [];
- for (const batchId of allowed) {
- const result = await updateBatch(ctx, { batchId, type: "dissolve" });
- if (result.error) {
- failed.push({
- readableId: readableById.get(batchId) ?? batchId,
- message: result.error.message || "Failed to dissolve"
- });
- } else {
- dissolved += 1;
- }
- }
-
- return { success: true, done: dissolved, failed, skipped };
-}
diff --git a/apps/erp/app/utils/table-jobs.server.ts b/apps/erp/app/utils/table-jobs.server.ts
index e59a53af4c..4ba48e9cdc 100644
--- a/apps/erp/app/utils/table-jobs.server.ts
+++ b/apps/erp/app/utils/table-jobs.server.ts
@@ -2,7 +2,9 @@
// 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 { CarbonError } from "@carbon/api/service-fn.server";
import { getClaims, makePermissionsFromClaims } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
import {
getCarbonServiceRole,
getUserScopedClient
@@ -22,9 +24,16 @@ import {
} from "@carbon/jobs/inngest";
import { getLogger } from "@carbon/logger";
import { nanoid } from "nanoid";
-import { isItemBulkUpdateField } from "~/modules/items/items.models";
-import { bulkDeleteJobs } from "~/modules/production/production.service";
-import { bulkDeletePurchaseOrders } from "~/modules/purchasing/purchasing.service";
+import { z } from "zod";
+import { itemBulkUpdateValidator } from "~/modules/items/items.models";
+import { updateItems } from "~/modules/items/items.server";
+import {
+ deleteJobs,
+ dissolveBatches,
+ releaseBatches,
+ releaseJobs
+} from "~/modules/production/production.server";
+import { deletePurchaseOrders } from "~/modules/purchasing/purchasing.server";
import { systemContext } from "~/modules/service-context.server";
import { userPermissionsValidator } from "~/modules/users/users.models";
import {
@@ -35,27 +44,22 @@ import {
} from "~/modules/users/users.service";
import { decodeCursor } from "./cursor";
import {
- bulkUpdateItems,
- isItemBulkUpdateValue
-} from "./item-bulk-actions.server";
-import { fetchListPage, getListDefinition } from "./list-registry/index.server";
-import {
- bulkDissolveBatches,
- bulkReleaseBatches,
- bulkReleaseJobs
-} from "./production-bulk-actions.server";
+ exportListRows,
+ fetchListPage,
+ getListDefinition
+} from "./list-registry/index.server";
import {
- type AllMatchingRequest,
+ ALL_MATCHING_RELEASE_LIMIT,
+ type BulkActionMeta,
type BulkActionStart,
- bulkActionServesList,
- getBulkActionMeta,
+ bulkStartFormResponse,
hasListPermission,
parseAllMatching,
refreshingClientFactory,
rowLimitRefusal,
TABLE_JOBS_FULL_MESSAGE,
- type TableBulkActionKey,
type TableJobClaims,
+ type TableJobRefusal,
tableJobBusyMessage,
tableJobBusyRefusal
} from "./table-jobs";
@@ -125,7 +129,7 @@ async function fetchPage(
limit: page.limit,
cursor: decodeCursor(page.cursor)
});
- if (result.error || !page.forExport || !definition.exportRows) {
+ if (result.error || !page.forExport) {
return {
rows: result.rows,
nextCursor: result.nextCursor,
@@ -136,7 +140,10 @@ async function fetchPage(
// match the table's. A failed lookup fails the page, not a blank column.
try {
return {
- rows: await definition.exportRows(result.rows, { client, companyId }),
+ rows: await exportListRows(definition, result.rows, {
+ client,
+ companyId
+ }),
nextCursor: result.nextCursor
};
} catch (error) {
@@ -155,15 +162,28 @@ type BulkActionRunContext = TableJobContext & {
getClient: ReturnType<typeof userClientFactory>;
};
-/** 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>;
+/**
+ * A bulk action with a background path (spec "Which bulk actions get the
+ * background path"): who may run it on which lists, the params its route
+ * sends (checked when the job starts and again when it runs), and what it
+ * does to one chunk of ids (at most 100). `run` throws only when nothing ran;
+ * `carry` is what the previous chunk of the same run returned.
+ */
+type BulkActionDefinition<TParams> = BulkActionMeta & {
+ params: z.ZodType<TParams>;
+ run(
+ ids: string[],
+ params: TParams,
+ context: BulkActionRunContext,
+ carry?: TableBulkActionCarry
+ ): Promise<TableBulkActionResult>;
+};
+
+function defineBulkAction<TParams>(definition: BulkActionDefinition<TParams>) {
+ return definition;
+}
+
+const noParams = z.object({});
/** The supplier → PO map a Jobs or Batches Release chunk carries to the
* next one. */
@@ -197,164 +217,247 @@ function problemLines(
};
}
+/** A Delete chunk's counts. The delete is refused only when it could delete
+ * none of the ids (another status, another company), so a refusal other
+ * than a failure skips the chunk. */
+function deleteCounts<T>(
+ ids: string[],
+ result: { data: T | null; error: CarbonError | null },
+ deleted: (data: T) => number
+): TableBulkActionResult {
+ if (result.error || !result.data) {
+ return result.error?.category === "internal"
+ ? {
+ done: 0,
+ skipped: 0,
+ failed: ids.length,
+ problems: [result.error.message],
+ problemCount: 1
+ }
+ : { done: 0, skipped: ids.length, failed: 0 };
+ }
+ const done = deleted(result.data);
+ return { done, skipped: ids.length - done, failed: 0 };
+}
+
function userClientFactory(userId: string) {
return refreshingClientFactory(() => getUserScopedClient(userId));
}
/**
- * Each bulk action with a background path runs the same service functions as
- * its action route, so the per-row checks are the same on both paths.
+ * Each bulk action runs the same service functions 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" ||
- !isItemBulkUpdateValue(field, value)
- ) {
- throw new Error("The item update is not valid");
+const BULK_ACTIONS = {
+ "items.update": defineBulkAction({
+ label: "Update items",
+ lists: ["parts", "materials", "tools", "consumables", "services"],
+ permission: { update: "parts" },
+ params: itemBulkUpdateValidator,
+ run: async (ids, change, context) => {
+ const result = await updateItems(await jobServiceContext(context), {
+ ids,
+ change
+ });
+ if (result.error) throw new Error(result.error.message);
+ return { ...result.data, failed: 0 };
}
- const result = await bulkUpdateItems(await jobServiceContext(context), {
- itemIds: ids,
- field,
- value
- });
- return {
- done: result.done,
- skipped: result.skipped,
- failed: result.failed
- };
- },
- "jobs.release": async (ids, _params, context, carry) => {
- const result = await bulkReleaseJobs(await jobServiceContext(context), {
- jobIds: ids,
- // 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,
- // Released jobs with something left to fix (a PO that failed) are named
- // too: the in-request release shows them, and so must the notification.
- ...problemLines(result.failed, result.warnings),
- 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, carry) => {
- const result = await bulkReleaseBatches(await jobServiceContext(context), {
- batchIds: ids,
- purchaseOrdersBySupplierId: carriedPurchaseOrders(carry)
- });
- if (!result.success) throw new Error(result.message);
- return {
- done: result.done,
- skipped: result.skipped,
- failed: result.failed.length,
- ...problemLines(result.failed),
- carry: { purchaseOrdersBySupplierId: result.purchaseOrdersBySupplierId }
- };
- },
- "batches.dissolve": async (ids, _params, context) => {
- const result = await bulkDissolveBatches(await jobServiceContext(context), {
- batchIds: ids
- });
- if (!result.success) throw new Error(result.message);
- return {
- done: result.done,
- skipped: result.skipped,
- failed: result.failed.length,
- ...problemLines(result.failed)
- };
- },
- "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
+ }),
+ "jobs.release": defineBulkAction({
+ label: "Release jobs",
+ lists: ["jobs"],
+ permission: { update: "production" },
+ maxRows: ALL_MATCHING_RELEASE_LIMIT,
+ // Each job runs the requirements recalculation and MRP.
+ idsPerStep: 25,
+ params: noParams,
+ run: async (ids, _params, context, carry) => {
+ const result = await releaseJobs(await jobServiceContext(context), {
+ jobIds: ids,
+ // 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.
+ carriedPurchaseOrders: carriedPurchaseOrders(carry)
});
+ if (result.error) throw new Error(result.error.message);
+ const { released, warnings, failed, skipped } = result.data;
+ return {
+ done: released.length,
+ skipped: skipped.length,
+ failed: failed.length,
+ // Released jobs with something left to fix (a PO that failed) are
+ // named too: the in-request release shows them, and so must the
+ // notification.
+ ...problemLines(failed, warnings),
+ carry: {
+ purchaseOrdersBySupplierId: result.data.purchaseOrdersBySupplierId
+ }
+ };
}
- // 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,
+ }),
+ "jobs.delete": defineBulkAction({
+ label: "Delete jobs",
+ lists: ["jobs"],
+ permission: { update: "production", delete: "production" },
+ params: noParams,
+ run: async (ids, _params, context) =>
+ deleteCounts(
+ ids,
+ await deleteJobs(await jobServiceContext(context), { ids }),
+ (data) => data.ids.length
+ )
+ }),
+ "purchase-orders.delete": defineBulkAction({
+ label: "Delete purchase orders",
+ lists: ["purchase-orders"],
+ permission: { update: "purchasing", delete: "purchasing" },
+ params: noParams,
+ run: async (ids, _params, context) =>
+ deleteCounts(
+ ids,
+ await deletePurchaseOrders(await jobServiceContext(context), {
+ purchaseOrderIds: ids
+ }),
+ (data) => data.purchaseOrderIds.length
+ )
+ }),
+ "batches.release": defineBulkAction({
+ 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,
+ params: noParams,
+ run: async (ids, _params, context, carry) => {
+ const result = await releaseBatches(await jobServiceContext(context), {
+ batchIds: ids,
+ carriedPurchaseOrders: carriedPurchaseOrders(carry)
+ });
+ if (result.error) throw new Error(result.error.message);
+ const { released, failed, skipped } = result.data;
+ return {
+ done: released.length,
+ skipped: skipped.length,
+ failed: failed.length,
+ ...problemLines(failed),
+ carry: {
+ purchaseOrdersBySupplierId: result.data.purchaseOrdersBySupplierId
+ }
+ };
+ }
+ }),
+ "batches.dissolve": defineBulkAction({
+ label: "Dissolve batches",
+ lists: ["operation-batches"],
+ permission: { update: "production" },
+ idsPerStep: 100,
+ params: noParams,
+ run: async (ids, _params, context) => {
+ const result = await dissolveBatches(await jobServiceContext(context), {
+ batchIds: ids
+ });
+ if (result.error) throw new Error(result.error.message);
+ const { dissolved, failed, skipped } = result.data;
+ return {
+ done: dissolved,
+ skipped,
+ failed: failed.length,
+ ...problemLines(failed)
+ };
+ }
+ }),
+ "users.deactivate": defineBulkAction({
+ label: "Deactivate users",
+ lists: ["employee-accounts"],
+ permission: { delete: "users" },
+ params: z.object({ ip: z.string().optional() }),
+ run: async (ids, { ip }, { companyId, userId }) => {
+ const { allowed, skipped } = await selectUsersForBulkAction({
+ action: "deactivate",
+ userIds: ids,
companyId,
- location: typeof location === "string" ? location : "Unknown",
- ip: typeof ip === "string" ? ip : "127.0.0.1"
+ actorId: userId
});
+ if (allowed.length > 0) {
+ await queueUserDeactivations({
+ userIds: allowed,
+ companyId,
+ actorId: userId,
+ ip
+ });
+ }
+ // Done = queued: the user-admin job deactivates each user.
+ return { done: allowed.length, skipped, failed: 0 };
}
- 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");
+ }),
+ "users.invite": defineBulkAction({
+ label: "Send invites",
+ lists: ["employee-accounts"],
+ permission: { create: "users" },
+ params: z.object({ location: z.string(), ip: z.string() }),
+ run: 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,
+ ip
+ });
+ }
+ return { done: allowed.length, skipped, failed: 0 };
}
- const { allowed, skipped } = await selectUsersForBulkAction({
- action: "permissions",
- userIds: ids,
- companyId,
- actorId: userId
- });
- if (allowed.length > 0) {
- await queuePermissionUpdates({
- userIds: allowed,
+ }),
+ "users.permissions": defineBulkAction({
+ 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",
+ params: z.object({
+ permissions: z.record(z.string(), userPermissionsValidator),
+ addOnly: z.boolean(),
+ ip: z.string().optional()
+ }),
+ run: async (ids, { permissions, addOnly, ip }, { companyId, userId }) => {
+ const { allowed, skipped } = await selectUsersForBulkAction({
+ action: "permissions",
+ userIds: ids,
companyId,
- actorId: userId,
- permissions,
- addOnly,
- ip: typeof ip === "string" ? ip : undefined
+ actorId: userId
});
+ if (allowed.length > 0) {
+ await queuePermissionUpdates({
+ userIds: allowed,
+ companyId,
+ actorId: userId,
+ permissions,
+ addOnly,
+ ip
+ });
+ }
+ return { done: allowed.length, skipped, failed: 0 };
}
- return { done: allowed.length, skipped, failed: 0 };
- }
+ })
};
+export type TableBulkActionKey = keyof typeof BULK_ACTIONS;
+
+type BulkActionParams<K extends TableBulkActionKey> = z.input<
+ (typeof BULK_ACTIONS)[K]["params"]
+>;
+
+function getBulkAction(key: string): BulkActionDefinition<unknown> | undefined {
+ const actions: Record<string, BulkActionDefinition<unknown>> = BULK_ACTIONS;
+ return Object.hasOwn(actions, key) ? actions[key] : undefined;
+}
+
/**
* The context the production service functions run in for a bulk-action job:
* the system, on behalf of the requesting user. The job checked the user's
@@ -381,23 +484,6 @@ async function jobServiceContext({ companyId, userId }: TableJobContext) {
});
}
-/** 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. */
@@ -406,9 +492,9 @@ async function canRunBulkAction(
action: TableBulkAction,
context: TableJobContext
): Promise<boolean> {
- const bulkAction = getBulkActionMeta(action.key);
+ const bulkAction = getBulkAction(action.key);
const list = getListDefinition(listKey);
- if (!bulkAction || !list || !bulkActionServesList(action.key, listKey)) {
+ if (!bulkAction || !list || !bulkAction.lists.includes(listKey)) {
return false;
}
const claims = await readClaims(context);
@@ -432,13 +518,17 @@ async function runBulkAction(
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(
+ const bulkAction = getBulkAction(action.key);
+ if (!bulkAction) throw new Error(`Unknown bulk action "${action.key}"`);
+ const params = bulkAction.params.safeParse(action.params);
+ if (!params.success) {
+ throw new Error(
+ `The params of the bulk action "${action.key}" are not valid`
+ );
+ }
+ return bulkAction.run(
ids,
- action.params,
+ params.data,
{
...context,
getClient: userClientFactory(context.userId)
@@ -472,7 +562,9 @@ async function countMatchingRows(
await getUserScopedClient(userId),
companyId,
params,
- { limit: 1, cursor: null }
+ // Above 1,000 rows a list reads the planner's estimate; the row limit
+ // needs the real count.
+ { limit: 1, cursor: null, exactCount: true }
);
if (result.error) {
logger.error("Failed to count the rows of a bulk action", {
@@ -485,45 +577,117 @@ async function countMatchingRows(
return result.count;
}
+/** Why a table job did not start, with the HTTP status the export route
+ * answers it with. */
+export type TableJobStartRefusal = {
+ status: 409 | 500 | 503;
+ message: string;
+ refusal: TableJobRefusal;
+};
+
/**
- * 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.
+ * The one start path of the table jobs (an export, a bulk action): takes the
+ * company's lock for the job's kind, then sends its event. Another job of the
+ * kind holding the lock refuses (409), so do all slots taken (503): a queue
+ * many companies fill would make every user wait. With Redis down the job
+ * starts anyway: Inngest's per-company concurrency still runs one at a time.
+ * A failed send gives the lock back (500). Null when the job started.
*/
-export function startTableBulkAction({
- allMatching,
- ...args
-}: BulkRunArgs & {
- allMatching: AllMatchingRequest;
-}): Promise<BulkActionStart> {
- return startBulkRun({
- ...args,
- listKey: allMatching.listKey,
- search: allMatching.search
- });
+export async function startTableJob(
+ kind: "export" | "bulk",
+ {
+ companyId,
+ jobId,
+ log
+ }: { companyId: string; jobId: string; log: Record<string, unknown> },
+ send: () => Promise<unknown>
+): Promise<TableJobStartRefusal | null> {
+ const lock = await takeTableJobLock(kind, companyId, jobId);
+ if (lock.status === "busy") {
+ return {
+ status: 409,
+ message: tableJobBusyMessage(kind, lock.retryAfterSeconds),
+ refusal: tableJobBusyRefusal(kind, lock.retryAfterSeconds)
+ };
+ }
+ if (lock.status === "full") {
+ logger.warn("Refused a table job: every table-job slot is taken", {
+ kind,
+ companyId,
+ ...log
+ });
+ return {
+ status: 503,
+ message: TABLE_JOBS_FULL_MESSAGE,
+ refusal: { code: "full" }
+ };
+ }
+ if (lock.status === "unavailable") {
+ logger.warn("Starting a table job without the Redis lock", {
+ kind,
+ companyId,
+ ...log
+ });
+ }
+ try {
+ await send();
+ } catch (error) {
+ logger.error("Failed to start a table job", {
+ kind,
+ companyId,
+ ...log,
+ error
+ });
+ await releaseTableJobLock(kind, companyId, jobId);
+ return {
+ status: 500,
+ message:
+ kind === "export"
+ ? "The export could not start"
+ : "The bulk action could not start",
+ refusal: { code: "not-started" }
+ };
+ }
+ return null;
}
/**
- * 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.
+ * The background path of a bulk action route. When the request names every
+ * matching row (`allMatching`, a form field or a JSON body value), or more
+ * selected `ids` than one request may act on (the action's `idsPerStep`, so a
+ * request ends before the load balancer's 600 s), it checks the action's own
+ * permission, starts the job and answers what the route returns. Null when
+ * the route acts on the selection itself.
*/
-export function startSelectedBulkAction({
- listKey,
- ids,
- ...args
-}: BulkRunArgs & { listKey: string; ids: string[] }): Promise<BulkActionStart> {
- return startBulkRun({ ...args, listKey, search: "", ids });
-}
+export async function startBackgroundBulkAction<K extends TableBulkActionKey>(
+ request: Request,
+ actionKey: K,
+ selection: { allMatching?: unknown; ids?: string[] },
+ params: BulkActionParams<K>
+) {
+ const action: BulkActionDefinition<unknown> = BULK_ACTIONS[actionKey];
+ const allMatching = parseAllMatching(selection.allMatching);
+ const ids = selection.ids ?? [];
+ const tooManyIds =
+ action.idsPerStep !== undefined && ids.length > action.idsPerStep;
+ if (!allMatching && !tooManyIds) return null;
-type BulkRunArgs = {
- companyId: string;
- userId: string;
- actionKey: TableBulkActionKey;
- params: Record<string, unknown>;
-};
+ const { companyId, userId } = await requirePermissions(
+ request,
+ action.permission
+ );
+ return bulkStartFormResponse(
+ await startBulkRun({
+ companyId,
+ userId,
+ actionKey,
+ params,
+ // Selected rows come from the action's one list; the job reads no
+ // list pages for them.
+ ...(allMatching ?? { listKey: action.lists[0]!, search: "", ids })
+ })
+ );
+}
async function startBulkRun({
companyId,
@@ -533,17 +697,17 @@ async function startBulkRun({
listKey,
search,
ids
-}: BulkRunArgs & {
+}: {
+ companyId: string;
+ userId: string;
+ actionKey: TableBulkActionKey;
+ params: unknown;
listKey: string;
search: string;
ids?: string[];
}): Promise<BulkActionStart> {
- const bulkAction = getBulkActionMeta(actionKey);
- if (
- !bulkAction ||
- !bulkActionServesList(actionKey, listKey) ||
- !getListDefinition(listKey)
- ) {
+ const bulkAction: BulkActionDefinition<unknown> = BULK_ACTIONS[actionKey];
+ if (!bulkAction.lists.includes(listKey) || !getListDefinition(listKey)) {
logger.error("A bulk action was requested for a list it does not serve", {
companyId,
actionKey,
@@ -556,12 +720,28 @@ async function startBulkRun({
};
}
+ const parsedParams = bulkAction.params.safeParse(params);
+ if (!parsedParams.success) {
+ logger.error("A bulk action was requested with invalid params", {
+ companyId,
+ actionKey
+ });
+ return {
+ success: false,
+ message: "The bulk action is not valid",
+ refusal: { code: "not-started" }
+ };
+ }
+
const context = { companyId, userId };
let allowed: boolean;
try {
allowed = await canRunBulkAction(
listKey,
- { key: actionKey, params },
+ {
+ key: actionKey,
+ params: parsedParams.data as TableBulkAction["params"]
+ },
context
);
} catch {
@@ -602,84 +782,34 @@ async function startBulkRun({
}
const bulkActionId = nanoid();
- const lock = await takeTableJobLock("bulk", companyId, bulkActionId);
- if (lock.status === "busy") {
- return {
- success: false,
- message: tableJobBusyMessage("bulk", lock.retryAfterSeconds),
- refusal: tableJobBusyRefusal("bulk", lock.retryAfterSeconds)
- };
- }
- if (lock.status === "full") {
- logger.warn("Refused a table bulk action: every table-job slot is taken", {
- companyId,
- actionKey
- });
- return {
- success: false,
- message: TABLE_JOBS_FULL_MESSAGE,
- refusal: { code: "full" }
- };
- }
- 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);
+ const refused = await startTableJob(
+ "bulk",
+ { companyId, jobId: bulkActionId, log: { actionKey } },
+ () =>
+ trigger("table-bulk-action", {
+ companyId,
+ userId,
+ bulkActionId,
+ actionKey,
+ actionLabel: bulkAction.label,
+ params: parsedParams.data as TableBulkAction["params"],
+ listKey,
+ search,
+ ...(bulkAction.maxRows !== undefined
+ ? { maxRows: bulkAction.maxRows }
+ : {}),
+ ...(bulkAction.idsPerStep !== undefined
+ ? { idsPerStep: bulkAction.idsPerStep }
+ : {}),
+ ...(ids ? { ids } : {})
+ })
+ );
+ if (refused) {
return {
success: false,
- message: "The bulk action could not start",
- refusal: { code: "not-started" }
+ message: refused.message,
+ refusal: refused.refusal
};
}
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.ts
index 640987a13e..04f7e2fb12 100644
--- a/apps/erp/app/utils/table-jobs.test.ts
+++ b/apps/erp/app/utils/table-jobs.test.ts
@@ -4,11 +4,7 @@
import { describe, expect, it } from "vitest";
import {
- BULK_ACTIONS,
- bulkActionServesList,
bulkStartFormResponse,
- fitsOneRequest,
- getBulkActionMeta,
hasListPermission,
newTableExportId,
parseAllMatching,
@@ -176,31 +172,16 @@ describe("parseAllMatching", () => {
});
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(
+ it("refuses an action with a row limit past it", () => {
+ const release = { label: "Release jobs", maxRows: 2_000 };
+ expect(rowLimitRefusal(release, 2_000)).toBeNull();
+ expect(rowLimitRefusal(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("puts no row limit on an action without one", () => {
+ expect(rowLimitRefusal({ label: "Delete jobs" }, 90_000)).toBeNull();
});
it("answers a form route's start with an error field on both outcomes", () => {
@@ -237,16 +218,3 @@ describe("tableJobBusyRefusal", () => {
});
});
});
-
-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.ts
index 3fd62435a6..d30393e4b4 100644
--- a/apps/erp/app/utils/table-jobs.ts
+++ b/apps/erp/app/utils/table-jobs.ts
@@ -154,11 +154,6 @@ export function splitIdsByStatus<TStatus>(
* 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.
- */
/**
* Why a table job (an export or a bulk action) did not start. The browser
* words it in the user's language (`useTableJobRefusalMessage`); `message`
@@ -188,6 +183,11 @@ export function tableJobBusyRefusal(
};
}
+/**
+ * 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 (`useBulkStartToast`) reads them all.
+ */
export type BulkActionStart =
| { success: true; background: true }
| { success: false; message: string; refusal: TableJobRefusal };
@@ -226,95 +226,6 @@ export type BulkActionMeta = {
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");
/**
@@ -323,7 +234,7 @@ const rowCount = new Intl.NumberFormat("en-US");
* at the limit, so an estimate that was low still runs on the first rows only.
*/
export function rowLimitRefusal(
- action: BulkActionMeta,
+ action: Pick<BulkActionMeta, "label" | "maxRows">,
matchingRows: number
): string | null {
if (action.maxRows === undefined || matchingRows <= action.maxRows) {
diff --git a/apps/erp/test/job-release-logic.test.ts b/apps/erp/test/job-release-logic.test.ts
index bc86d1b560..a398b66382 100644
--- a/apps/erp/test/job-release-logic.test.ts
+++ b/apps/erp/test/job-release-logic.test.ts
@@ -9,7 +9,7 @@ vi.mock("@lingui/core/macro", () => ({
msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })
}));
import {
- bulkReleaseStartingPurchaseOrders,
+ startingPurchaseOrders,
jobReleaseProblems,
materialsWithoutStorageUnit,
makeMethodsMissingOperations,
@@ -151,9 +151,9 @@ describe("jobReleaseProblems", () => {
});
});
-describe("bulkReleaseStartingPurchaseOrders", () => {
+describe("startingPurchaseOrders", () => {
it("starts every supplier on a new PO and asks for a choice when Drafts exist", () => {
- const result = bulkReleaseStartingPurchaseOrders([
+ const result = startingPurchaseOrders([
{ supplierId: "s1", draftPurchaseOrders: [] },
{ supplierId: "s2", draftPurchaseOrders: [{ id: "po-a" }] }
]);
@@ -163,22 +163,34 @@ describe("bulkReleaseStartingPurchaseOrders", () => {
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(
+ const result = startingPurchaseOrders(
[{ supplierId: "s1", draftPurchaseOrders: [{ id: "po-1" }] }],
- { s1: "po-1" }
+ { carried: { 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(
+ const result = startingPurchaseOrders(
[{ supplierId: "s1", draftPurchaseOrders: [{ id: "po-other" }] }],
- { s1: "po-1" }
+ { carried: { s1: "po-1" } }
);
expect(result.purchaseOrders).toEqual({ s1: "new" });
expect([...result.suppliersToChoose]).toEqual(["s1"]);
});
+
+ it("takes a chosen Draft, and asks nobody once a choice is sent", () => {
+ const result = startingPurchaseOrders(
+ [
+ { supplierId: "s1", draftPurchaseOrders: [{ id: "po-a" }] },
+ { supplierId: "s2", draftPurchaseOrders: [{ id: "po-b" }] }
+ ],
+ { chosen: { s1: "po-a", s2: "po-not-a-draft" } }
+ );
+ expect(result.purchaseOrders).toEqual({ s1: "po-a", s2: "new" });
+ expect(result.suppliersToChoose.size).toBe(0);
+ });
});
describe("jobReleaseProblems with a long BoM", () => {
diff --git a/apps/erp/test/release-jobs.test.ts b/apps/erp/test/release-jobs.test.ts
index c3d5aa6138..bc148b39fa 100644
--- a/apps/erp/test/release-jobs.test.ts
+++ b/apps/erp/test/release-jobs.test.ts
@@ -305,6 +305,7 @@ describe("releaseJobs", () => {
input: {
jobIds: string[];
purchaseOrdersBySupplierId?: Record<string, string>;
+ carriedPurchaseOrders?: Record<string, string>;
supplierProcessByOperationId?: Record<string, string>;
}
) => releaseJobs(contextFor(database({ job: jobs }).client), input);
@@ -323,7 +324,8 @@ describe("releaseJobs", () => {
warnings: [],
failed: [],
skipped: [{ jobId: "j3", readableId: "J3", status: "In Progress" }],
- scheduled: true
+ scheduled: true,
+ purchaseOrdersBySupplierId: {}
});
});
@@ -393,6 +395,32 @@ describe("releaseJobs", () => {
expect(sent).toEqual([{ "supplier-a": "new" }, { "supplier-a": "po-new" }]);
});
+ it("keeps a supplier on the PO an earlier call created, and returns it for the next call", async () => {
+ // A background release runs in slices: slice 1 made po-1, which slice 2
+ // reads as a Draft of the supplier and must not ask to choose among.
+ readiness(
+ [ready("j1", { supplierIds: ["supplier-a"] })],
+ [
+ {
+ supplierId: "supplier-a",
+ draftPurchaseOrders: [{ id: "po-1", purchaseOrderId: "PO000001" }]
+ }
+ ]
+ );
+ const { data } = await run([job("j1")], {
+ jobIds: ["j1"],
+ carriedPurchaseOrders: { "supplier-a": "po-1", "supplier-b": "po-2" }
+ });
+ expect(data?.released).toHaveLength(1);
+ expect(invoke.mock.calls.find(([name]) => name === "create")?.[1]).toMatchObject({
+ purchaseOrdersBySupplierId: { "supplier-a": "po-1" }
+ });
+ expect(data?.purchaseOrdersBySupplierId).toEqual({
+ "supplier-a": "po-1",
+ "supplier-b": "po-2"
+ });
+ });
+
it("reports a job that left Draft or Planned during the release, and schedules each location once", async () => {
readiness([ready("j1"), ready("j2"), ready("j3")]);
const jobs = [job("j1"), job("j2"), job("j3", { locationId: "location-2" })];
diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.md
index eef8b57f35..08460d3964 100644
--- a/packages/jobs/AGENTS.md
+++ b/packages/jobs/AGENTS.md
@@ -77,7 +77,7 @@ pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id> # MRP +
| `model-optimize` | `carbon/model-optimize` `{ modelUploadId, companyId }` (sent by the database: the `queue_model_pipeline` statement handler on `modelUpload` for every new row, except under `app.sync_in_progress` and for bundled `_templates/` paths; also by the viewer's Retry) | One assembler job per new model (`runAssemblerJob`, `tasks/assembler-client.ts`): the optimised preview GLB, the raw's compact form while the raw is in `temp-staging`, and the thumbnail. Then it moves the raw out of staging (`settleCompactedRaw`, else `relocateRaw`, `tasks/model-compact.ts`). The model's file is read only from its own company (`resolveModelSourceBucket`). pg_cron `model-pipeline-reaper` (`util.reap_model_pipeline()`, at :13 and :43) marks an optimise, conversion or plan job Queued or Processing for 8 hours as Failed, and resends this event for a model still Idle 30 to 60 minutes after it was created |
| `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` |
+| `table-bulk-action` | `carbon/table-bulk-action` (`startBackgroundBulkAction`, 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). 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