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.

perf: fix the table render cascade, app-shell revalidation, and list queries (#1343)

Sid6fa6d314db49
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 5cf756a6e1..fe1ea3efcb 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -633,3 +633,53 @@ Format: `Context → Problem → Rule → Applies to`
**Rule:** When authoring a conformance check, verify the checker actually loads every file class the rule applies to (run it, count the files, grep one known-bad file into the scan). Ban the bug class, not just the instances you found — then run the widened pattern over the full source set and fix or baseline everything it surfaces before landing. For React Router route modules, path-level globs are the wrong granularity: mask OUT the client regions by declaration shape (`maskClientCode` blanks default export / `clientLoader` / `clientAction` / PascalCase and `use*` declarations) so server helpers stay covered; masking IN named exports under-covers. And when masking by line shape, the region CLOSER is as bug-prone as the opener: a `)` closer that also matches a multi-line signature's `) {` line ends the region before the body and un-masks client code (only statement-terminating `)`/`);` lines close a region), while an expression-bodied one-liner (`const X = () => null;`) must never OPEN a region at all — pin both shapes as regression tests.
**Applies to:** `packages/checks/src/sources/server-files.ts` + `conformance/no-local-timezone.ts`; any new `SERVER_CHECKS` rule; any lint/conformance gate keyed on file paths over `apps/*/app/routes`.
+
+## A per-request memo keyed on the `Request` object never hits — React Router doesn't share one across loaders
+
+**Context:** Perf work on `sid/perf-audit-hot-paths` (2026-08). Every matched route calls `requirePermissions` independently, so a detail page did one Redis GET for permission claims and one `createClient()` per loader. The obvious fix is to memoize per request.
+
+**Problem:** The first attempt was a `WeakMap<Request, …>` — safe-looking, self-evicting, zero call-site changes, and it passed typecheck plus six unit tests asserting "same Request → same value, different Request → different value". It also did nothing: measured with `redis-cli monitor`, claims lookups on a deep page were **4 both with and without it**, because React Router does not hand the same `Request` instance to every matched loader. The unit tests were green precisely because they constructed the shared-Request case the runtime never produces. The working mechanism is AsyncLocalStorage holding React Router's own per-request `RouterContextProvider` (published by a root middleware) — the same pattern `requestIdMiddleware` already used via LogTape's `withContext`. That took the page from 4 lookups to 1.
+
+**Rule:** A memo is a performance claim, and a performance claim needs a measurement, not a unit test — a test can only prove the memo behaves as written, never that its key is stable in production. Before shipping request-scoped caching, count the underlying calls end-to-end (redis `MONITOR`, `pg_stat_statements`, a temporary counter) with the change toggled off and on. Reach for ALS-over-`context` rather than keying on `Request`. And note the corollary: memoizing **database state** must be gated to GET/HEAD/OPTIONS (`oncePerRead`), because React Router runs an action and its loader revalidation in a single request — an ungated memo there serves pre-write data, which for permission claims means a gate passing on permissions the action just revoked.
+
+**Applies to:** `packages/logger/src/context.server.ts` (`oncePerRequest` / `oncePerRead` / `requestContextMiddleware`), `packages/auth/src/services/{auth,users}.server.ts`, and any future request-scoped cache.
+
+## A word-boundary rename corrupts UI copy that typecheck and tests can't see
+
+**Context:** Splitting ERP list types into `X` (full view row, for detail screens) and `XListItem` (the narrowed list select) on `sid/perf-audit-hot-paths`. Applied with a regex renaming the whole-word alias across each table component.
+
+**Problem:** `Part`, `Material`, `Tool`, `Consumable`, `Service` are single words that appear in **user-visible strings** as well as type positions. The rename produced ``t`PartListItem ID` ``, `<Trans>Delete PartListItem</Trans>`, and a button reading "Add PartListItem" — 20 occurrences across five files. Typecheck passed, 268 unit tests passed, all ten narrowed selects returned 206 from PostgREST, and `EXPLAIN` looked right. Only loading the page caught it. (The five multi-word aliases — `PurchaseOrder`, `SalesOrder`, … — were untouched, because their display text contains a space.)
+
+**Rule:** After any mechanical rename of an identifier that is also an English word, grep for the new name inside string literals, template literals and JSX text (``t`…` ``, `<Trans>…</Trans>`, `"…"`) before committing — and load one affected screen. Type-level green says nothing about copy. Prefer renaming with an editor's symbol-aware rename over a regex; when a regex is the only option, exclude string/JSX regions explicitly.
+
+**Applies to:** `apps/erp/app/modules/*/ui/*/*Table.tsx`, `apps/erp/app/modules/*/types.ts`; any bulk identifier rename in files containing Lingui macros.
+
+## A new package `exports` subpath 500s until every running dev server restarts
+
+**Context:** Adding `@carbon/logger/context.server` and `@carbon/auth/request-scope` during the same perf work.
+
+**Problem:** Vite resolves a package's `exports` map once at dev-server start. Adding a subpath and importing it immediately produced `"./context.server" is not exported under the conditions [...]` on every route — a hard 500 across the whole app, twice, each time looking like a code bug rather than a stale resolver. Typecheck was green throughout, since TypeScript reads the updated `package.json` directly.
+
+**Rule:** Adding an export subpath to a workspace package is a dev-server-restart change. Either restart every running dev server as part of the change, or re-export the new module from an already-exported entry point and leave a TODO to move it at the next coordinated restart. A green typecheck does not mean the running server can resolve the import.
+
+**Applies to:** `packages/*/package.json` `exports`, and any new `src/*.server.ts` intended for cross-package import.
+
+## `space-x-*` gives a phantom margin when a component injects sibling nodes
+
+**Context:** A reported layout shift — hovering any row of an ERP list table shifted every column of the whole table ~8px sideways.
+
+**Problem:** `Hyperlink` renders `<Link prefetch="intent">`. React Router implements that by rendering `<>{anchor}{prefetchLinks}</>`, so on hover four `<link rel="prefetch">` elements appear **as siblings of the anchor** inside whatever container the caller used — here `<HStack>`. Tailwind v4's `space-x-*` compiles to `& > :not(:last-child) { margin-inline-end }`, so the instant those links mount the anchor stops being `:last-child` and gains a real 8px margin. Under `table-layout: auto` that re-lays out the column and the whole table. The links are `display: none`, which is exactly why this reads as impossible: every computed style on the `<td>` except `background-color` is unchanged, the anchor and all its children keep identical widths, and only the `<td>` and its wrapper grow. Two false leads first — the load-time column settle (237.5 → 245.1 with no hover, ~4s after load) masquerades as the same shift, and `opacity-0 → opacity-100` on the "Open" button looks like the obvious culprit but cannot move layout.
+
+**Rule:** `space-x-*` / `space-y-*` are structural (`:not(:last-child)`) — never use them on a container whose children a component may add to at runtime; use `gap-*`, which only applies between elements that generate boxes and so ignores `display:none`. When a component renders extra DOM next to its main element (React Router prefetch links, portals, measurement nodes), isolate it in a `display: contents` wrapper so it can't perturb the caller's layout. To diagnose "impossible" width changes, diff every computed property between states and count child nodes — a node-count delta with no style delta means injected DOM, not CSS.
+
+**Applies to:** `apps/erp/app/components/Hyperlink.tsx`; `packages/react/src/{HStack,VStack}.tsx` (still `space-x-*`/`space-y-*`, ~2,500 call sites); any `<Link prefetch>` placed directly inside a `space-*` container.
+
+## A list-query benchmark that omits the ORDER BY measures a query the app never runs
+
+**Context:** Lateralizing the `salesOrders`/`purchaseOrders` list views on `sid/perf-audit-hot-paths`. The rewrite benchmarked as a ~9x win and shipped; re-measuring later against the real endpoint showed page 1 taking **41.6 seconds**.
+
+**Problem:** The benchmark ran `SELECT ... FROM "salesOrders" WHERE "companyId" = $1 LIMIT 100` — no `ORDER BY`. Every one of these endpoints applies a fixed default sort (`setGenericQueryFilters(query, args, [{ column: "createdAt", ascending: false }])`). That one clause inverts the result: with no sort the planner pushes `LIMIT 100` below the lateral join so the aggregate runs ~100 times (10.6 ms vs 91.3 ms for the bulk form — the win that was measured); with the sort and no index supplying its order, every row must be produced before the limit applies, so the aggregate runs once per order in the company — 10,000 times, each re-scanning `item` under a non-indexable RLS policy. Two other things hid it: the seeded tables had **never been analyzed** (`last_analyze` and `last_autoanalyze` both NULL, `n_live_tup` 0), so plan choice was unstable; and the stated rationale — "the bulk form aggregates every tenant's lines" — was simply false, since `salesOrderLine` has RLS and the view is `SECURITY INVOKER`, so it was always company-scoped.
+
+**Rule:** Benchmark the query the service actually builds — copy the projection, the `ORDER BY` from `setGenericQueryFilters`, and the `LIMIT/OFFSET`, not a simplified `SELECT * ... LIMIT n`. Run `ANALYZE` before trusting any timing on seeded data, and check `pg_stat_user_tables.last_analyze` first. When a rewrite's premise is "this touches rows it shouldn't", verify it against `pg_policies` before optimizing — RLS may already be doing it. A LATERAL is only a win when the limit can be pushed below the join, which needs an index supplying the sort; check the plan for `Seq Scan ... loops=<number of outer rows>`, which is the signature of a per-row aggregate that was meant to run per page.
+
+**Applies to:** `packages/database/supabase/migrations/20260807011742_lateralize-order-list-views.sql`, `20260806235710_perf-list-query-indexes.sql`, `apps/erp/app/utils/query.ts` (`setGenericQueryFilters`), and any future list-view or RLS-policy performance work.
diff --git a/.ai/plans/2026-08-07-item-rls-index-friendly.md b/.ai/plans/2026-08-07-item-rls-index-friendly.md
new file mode 100644
index 0000000000..d928b21891
--- /dev/null
+++ b/.ai/plans/2026-08-07-item-rls-index-friendly.md
@@ -0,0 +1,128 @@
+# Make the `item` RLS policy index-friendly
+
+**Status: Phases A and B shipped in PR #1343.** Phases C and D are still open.
+The migration comments are the authoritative record; this file is the summary
+plus the outstanding work.
+
+## What shipped
+
+`item`'s SELECT policy ORed one index-able branch with two `id IN (SELECT …)`
+portal branches. `id IN (SELECT …)` compiles to a hashed SubPlan, which is not an
+index path, and a `BitmapOr` requires *every* branch to have one — so a single
+non-indexable branch demoted the whole predicate to a filter and `item` could
+only be reached by sequential scan.
+
+`20260807093015_item-rls-index-friendly.sql` rewrites the two portal branches as
+`id = ANY (COALESCE((SELECT array_agg(…)), '{}'))` — an uncorrelated `array_agg`
+InitPlan evaluated once, plus a `ScalarArrayOpExpr` that can use `item_pkey`.
+`COALESCE(…, '{}')` matters: `array_agg` over zero rows returns NULL, and
+`id = ANY (NULL)` is NULL rather than false.
+
+That alone was not enough. The order-list views also needed an index supplying
+each list's default sort (`20260806235710`), or Postgres had to produce every row
+before applying `LIMIT`, running the per-order aggregate once per order in the
+company. Both pieces are required and they compound — see the header of
+`20260807011742_lateralize-order-list-views.sql` for the full matrix.
+
+Net, page 1 of each list, measured as `authenticated` with RLS enforced, claims
+held for the whole transaction, statistics present, real projection and real
+`ORDER BY`, vs `origin/main`:
+
+| query | before | after |
+|---|---|---|
+| `salesOrders` | ~200 ms | **~6.6 ms** |
+| `purchaseOrders` | ~72 ms | **~1.7 ms** |
+| item lists (`parts`, …) | 60–200 ms | unchanged |
+
+The item lists are untouched: their cost is the views' `DISTINCT ON` + revisions
+aggregate, which materialises every row regardless of the limit. Removing their
+`ORDER BY` does not speed them up, which is what distinguishes them from the
+order views. A lateral-driven rewrite measures ~130× faster but only when sorted
+by `readableId` rather than the displayed `readableIdWithRevision`; that is a
+visible-ordering change, so it is deliberately not done here.
+
+## Equivalence evidence
+
+Compared the **md5 of the sorted visible `item` id set** (not just counts) under
+the old and new policy, in one rolled-back transaction per persona:
+
+| persona | old | new | |
+|---|---|---|---|
+| employee | 40000 | 40000 | same |
+| supplier portal | 400 | 400 | same — **test-only, see below** |
+| customer portal | 7 | 7 | same |
+| no access | 0 | 0 | same |
+
+> The supplier row is **not** production evidence. `supplierPart`'s own SELECT
+> policy is employee-gated, so branch 2 is unreachable for a real supplier-portal
+> user — the 400 was only produced by adding a temporary permissive policy so the
+> branch was exercised at all. It shows the rewrite preserves the branch's
+> semantics; it does not show a supplier-portal user can read anything. That is
+> bug D1 below.
+
+The two order views were separately verified against the definitions they
+replace with a bidirectional `EXCEPT ALL` over every row cast to text (stricter
+than an md5 aggregate: it is multiset-aware and identifies differing rows):
+0 rows in both directions for both views, with identical row counts.
+
+## Phase C — same shape elsewhere (open)
+
+`itemCost` `[SELECT, UPDATE]` has the identical OR + `IN (SELECT …)` construction
+and also seq-scans under RLS (confirmed; it has 0 rows in dev so the timing is
+not meaningful, but the plan shape is). `customerPartToItem` and `user` share the
+pattern but are small and off the hot path.
+
+- [ ] Apply the same array rewrite to `itemCost` SELECT.
+- [ ] Decide on `item`/`itemCost` UPDATE + DELETE policies — same shape, and they
+ matter for bulk writes.
+- [ ] Leave `customerPartToItem` and `user` unless measurement justifies them.
+
+## Phase D — two portal bugs found on the way (open, needs a product decision)
+
+Both are **pre-existing**, and `20260807093015` preserves them exactly rather
+than fixing them, so that it stays a pure performance change.
+
+**D1 — the supplier branch of the `item` policy is unreachable.**
+`supplierPart`'s own SELECT policy is `companyId IN (employee parts_view ∪
+purchasing_view)` — purely employee-gated, no portal branch. So when a
+supplier-portal user is checked against `item`'s branch 2, the inner
+`supplierPart` read returns nothing and they see **zero** items. Either the
+supplier portal cannot list parts today, or portal access runs through a
+different mechanism (the `share+/` routes are token-based) and the branch is dead
+weight.
+
+**D2 — `get_supplier_ids_with_supplier_permission` discards its own first result.**
+
+```sql
+SELECT array_agg(c.id) INTO supplier_ids FROM "supplier" c WHERE c."companyId" = ANY(permission_companies);
+SELECT array_agg(ca."supplierId") INTO supplier_ids FROM "supplierAccount" ca WHERE ca.id::uuid = auth.uid() AND ...;
+```
+
+The second `INTO` overwrites the first unconditionally — and `array_agg` over
+zero rows is NULL, so a user who qualifies via the permission path but has no
+`supplierAccount` row ends up with NULL, not their suppliers. Confirmed
+empirically: 50 suppliers matched by the first query, helper returned NULL.
+`get_customer_ids_with_customer_permission` is identical in shape.
+
+- [ ] Get a product decision on D1 (should supplier-portal users list items?).
+- [ ] Get a decision on D2 (union the two paths, or is override intended?).
+- [ ] Fix in a separate, security-reviewed PR with the persona harness extended.
+
+## Verification notes for whoever picks this up
+
+- Reusable four-persona harness: synthesise employee / supplier / customer /
+ no-access, compare the visible `item` id set under both policy versions in one
+ rolled-back transaction. `packages/checks` has a SQL-invariants mechanism that
+ could host a "portal user sees exactly their mapped items" assertion so a
+ future policy edit cannot silently widen access.
+- Run `pnpm run generate:types` after any migration, before scoped typecheck.
+ For these three migrations it produces no schema-driven change (the only diff
+ is non-deterministic FK-ordering churn in the generator).
+- Benchmark the query the service actually builds — projection **and** the
+ `ORDER BY` from `setGenericQueryFilters`. Omitting the sort is what produced
+ the original wrong figures for this work.
+- Run `ANALYZE` first and check `pg_stat_user_tables.last_analyze`; the seeded
+ tables had never been analysed, which made plan choice unstable.
+
+Gates: `pnpm --filter @carbon/checks test`, scoped typecheck, and a browser pass
+over the item and order list screens.
diff --git a/.claude/rules/authentication-system.md b/.claude/rules/authentication-system.md
index aefbf0911f..880edd9381 100644
--- a/.claude/rules/authentication-system.md
+++ b/.claude/rules/authentication-system.md
@@ -70,6 +70,13 @@ the gate used in every loader/action. Two paths:
- Claims are `{ role, permissions }`. Cached in **Redis** (`@carbon/kv`) at key
`permissions:${userId}`; on miss, fetched via the `get_claims(uid, company)` RPC
(`getCarbonServiceRole`) and cached. `makePermissionsFromClaims` shapes the result.
+ - `getUserClaims` is additionally memoized **per read request** via
+ `oncePerRead` (`@carbon/logger/middleware.server`), so the several loaders a
+ page matches share one Redis GET. Read-gated on purpose: an action and its
+ loader revalidation run in the same request, and memoizing there could let a
+ gate pass on claims the action just revoked. The Supabase clients
+ `requirePermissions` returns are memoized per request too (`oncePerRequest`),
+ which needs no gate — a client is not database state.
- Each required permission checks `permissions[name][action]` contains the active
`companyId` (or `"0"` wildcard = all companies). `role` is matched directly.
- On failure: if `role === null` destroy session → `/`; else flash "Access Denied"
@@ -143,6 +150,13 @@ ERP exposes an OAuth 2.0 AS for use as a remote Claude/MCP connector. Routes und
- `getUserClaims` swallows Redis errors and falls back to the DB; a stale cache is the
usual cause of "Access Denied" after a permission change — invalidate the cache key.
+- `verifyAuthSession` (the `requireAuthSession(request, { verify: true })` path) caches
+ only its **positive** verdict in Redis for 60s, keyed by a SHA-256 of the access
+ token. Negatives are never cached — `getAuthAccountByAccessToken` also returns null
+ on a transient network error. Bounds how long a deleted/deactivated account keeps
+ being accepted; signing out never revoked a live access token anyway.
+- ERP's `~/modules/users/users.server` re-exports `getUserClaims` from `@carbon/auth`;
+ it used to carry a drifted copy that missed the cache TTL. Don't reintroduce one.
- Service-role clients bypass RLS — only use behind `bypassRls` + employee role.
- API key `scopes: {}` denies, not grants. Don't assume empty = full access.
- Edition matters: Enterprise rejects unknown-user login; Cloud gates API keys by plan
diff --git a/.claude/rules/database-patterns.md b/.claude/rules/database-patterns.md
index 89ba5b9464..7e57399376 100644
--- a/.claude/rules/database-patterns.md
+++ b/.claude/rules/database-patterns.md
@@ -70,7 +70,9 @@ export async function getCustomer(client: SupabaseClient<Database>, id: string)
Conventions (see also `conventions-services.md`):
- Always scope list queries by `companyId` (`.eq("companyId", companyId)`) — defense in depth even though RLS also enforces it.
-- List endpoints take `GenericQueryFilters` and run through `setGenericQueryFilters(query, args, [...])` (`~/utils/query`) for search/sort/pagination; use `.select("*", { count: "exact" })`.
+- List endpoints take `GenericQueryFilters` and run through `setGenericQueryFilters(query, args, [...])` (`~/utils/query`) for search/sort/pagination.
+- Count/select for list endpoints: prefer `{ count: LIST_COUNT }` (`LIST_COUNT = "estimated"`, `~/utils/query`) over `count: "exact"`. `exact` is `COUNT(*) OVER ()`, which materializes the whole filtered set just to produce a total the UI shows approximately anyway — on 500k `trackedEntity` rows that is 652 ms vs 1.5 ms. `estimated` is a hybrid: PostgREST still returns an exact count below its threshold, so small tenants see no change. Currently used by the ten view-backed endpoints plus `getJobs` and `getTrackedEntities`.
+- The ten endpoints backed by the big multi-join **views** (`parts`, `materials`, `tools`, `consumables`, `services`, `purchaseOrders`, `quotes`, `salesOrders`, `purchaseInvoices`, `salesInvoices`) additionally select an explicit `*_LIST_COLUMNS` constant instead of `select("*")`, so Postgres can prune the views' unreferenced computed columns. Adding a column to one of those tables means adding it to the constant — `apps/erp/test/list-select-columns.test.ts` fails if an `accessorKey` is missing, because the CSV export reads accessors untyped. The rationale lives once on `LIST_COUNT` in `apps/erp/app/utils/query.ts`, not at each constant.
- Use `sanitize(...)` (re-exported from `@carbon/utils`) to strip empty values before insert/update.
- Upserts are done either with a manual `id ? update : insert` branch or supabase's native `.upsert(...)`; both are in use.
- `fetchAllFromTable(client, table, columns, qb)` (from `@carbon/database`) pages through large result sets.
diff --git a/apps/erp/app/components/Hyperlink.tsx b/apps/erp/app/components/Hyperlink.tsx
index 44b3507467..14789e53dd 100644
--- a/apps/erp/app/components/Hyperlink.tsx
+++ b/apps/erp/app/components/Hyperlink.tsx
@@ -12,31 +12,38 @@ const Hyperlink = ({
| PropsWithChildren<LinkProps>
| PropsWithChildren<ComponentProps<"span">>) => {
return "to" in props && props.to ? (
- <Link
- prefetch="intent"
- className={cn(
- "group/hyperlink text-foreground font-medium cursor-pointer flex flex-row items-center justify-start gap-3",
- className
- )}
- {...props}
- >
- <span className="flex flex-row items-center gap-1">{children}</span>
- {props.to && props.to !== "#" && (
- <Button
- rightIcon={<LuPanelRight />}
- variant="secondary"
- // pointer-events-none so clicks fall through to the anchor: a plain
- // click navigates in-tab, a Cmd/Ctrl (or middle) click opens a new tab.
- // A real <button> here would otherwise swallow the anchor's native
- // modifier-click behavior and always open in the same tab.
- className="flex-shrink-0 opacity-0 transition-opacity duration-200 group-hover/hyperlink:opacity-100 no-underline pointer-events-none"
- size="sm"
- tabIndex={-1}
- >
- Open
- </Button>
- )}
- </Link>
+ // `contents` keeps the <link rel="prefetch"> elements React Router injects
+ // next to the anchor on hover out of the parent's layout. Without it they
+ // land as siblings in the caller's container, and HStack's `space-x-*`
+ // (a `:not(:last-child)` margin) hands the anchor a phantom 8px on hover —
+ // which reflows the whole table column under `table-layout: auto`.
+ <span className="contents">
+ <Link
+ prefetch="intent"
+ className={cn(
+ "group/hyperlink text-foreground font-medium cursor-pointer flex flex-row items-center justify-start gap-3",
+ className
+ )}
+ {...props}
+ >
+ <span className="flex flex-row items-center gap-1">{children}</span>
+ {props.to && props.to !== "#" && (
+ <Button
+ rightIcon={<LuPanelRight />}
+ variant="secondary"
+ // pointer-events-none so clicks fall through to the anchor: a plain
+ // click navigates in-tab, a Cmd/Ctrl (or middle) click opens a new tab.
+ // A real <button> here would otherwise swallow the anchor's native
+ // modifier-click behavior and always open in the same tab.
+ className="flex-shrink-0 opacity-0 transition-opacity duration-200 group-hover/hyperlink:opacity-100 no-underline pointer-events-none"
+ size="sm"
+ tabIndex={-1}
+ >
+ Open
+ </Button>
+ )}
+ </Link>
+ </span>
) : (
<span className={cn("text-foreground", className)} {...props}>
{children}
diff --git a/apps/erp/app/components/Table/Table.tsx b/apps/erp/app/components/Table/Table.tsx
index 6c3dc219d9..c1af87c95b 100644
--- a/apps/erp/app/components/Table/Table.tsx
+++ b/apps/erp/app/components/Table/Table.tsx
@@ -988,7 +988,15 @@ const Table = <T extends object>({
}, [visibleColumns, columnOrder, pinnedColumnsKey]);
// Primitive the memoized Row/Cell comparators can compare — see Cell.tsx.
- const pinnedShadowKey = `${scrolledEdges.left}:${scrolledEdges.right}`;
+ // `getPinnedStyles` is a fresh closure every render, so this has to encode
+ // everything it can return: the scrolled edges that drive the shadow, and
+ // each pinned column's sticky offset out of `columnSizeMap` (the resize
+ // observer replaces that Map wholesale, so comparing the Map itself would
+ // re-render every row on every observation).
+ const pinnedStyleKey = `${scrolledEdges.left}:${scrolledEdges.right}|${visibleColumns
+ .filter((col) => col.getIsPinned())
+ .map((col) => `${col.id}@${columnSizeMap.get(col.id)?.startX ?? 0}`)
+ .join(",")}`;
const getPinnedStyles = (column: Column<T>): CSSProperties => {
const isPinned = column.getIsPinned();
@@ -1315,12 +1323,12 @@ const Table = <T extends object>({
row.index in rowSelection &&
!!rowSelection[row.index]
}
- pinnedColumns={pinnedColumnsKey}
+ visibleColumns={visibleColumns}
selectedCell={selectedCell}
row={row}
rowIsSelected={selectedCell?.row === row.index}
getPinnedStyles={getPinnedStyles}
- pinnedShadow={pinnedShadowKey}
+ pinnedStyleKey={pinnedStyleKey}
onCellClick={onCellClick}
onCellUpdate={onCellUpdate}
onClick={handleRowClick}
@@ -1344,12 +1352,12 @@ const Table = <T extends object>({
isRowSelected={
row.index in rowSelection && !!rowSelection[row.index]
}
- pinnedColumns={pinnedColumnsKey}
+ visibleColumns={visibleColumns}
selectedCell={selectedCell}
row={row}
rowIsSelected={selectedCell?.row === row.index}
getPinnedStyles={getPinnedStyles}
- pinnedShadow={pinnedShadowKey}
+ pinnedStyleKey={pinnedStyleKey}
onCellClick={onCellClick}
onCellUpdate={onCellUpdate}
onClick={handleRowClick}
diff --git a/apps/erp/app/components/Table/components/Cell.tsx b/apps/erp/app/components/Table/components/Cell.tsx
index bc436084a7..7c07cefa41 100644
--- a/apps/erp/app/components/Table/components/Cell.tsx
+++ b/apps/erp/app/components/Table/components/Cell.tsx
@@ -20,12 +20,16 @@ type CellProps<T> = {
isEditMode: boolean;
isRowSelected: boolean;
isSelected: boolean;
- pinnedColumns: string;
+ // Memo key only — see Row.tsx. Identity flips when the column defs are
+ // rebuilt or visibility/order/pinning changes, which is when a memoized cell
+ // would otherwise render a stale `columnDef.cell` renderer.
+ visibleColumns: Column<any, unknown>[];
// Render key only: `getPinnedStyles` is a fresh closure every render and is
// deliberately excluded from the memo comparator, so without a primitive that
- // flips with the scroll state, memoized cells never pick up the pinned-edge
- // shadow. The style itself still comes from `getPinnedStyles`.
- pinnedShadow?: string;
+ // flips with the scroll state and the pinned columns' sticky offsets,
+ // memoized cells never pick up the pinned-edge shadow or a moved offset. The
+ // style itself still comes from `getPinnedStyles`.
+ pinnedStyleKey?: string;
getPinnedStyles: (column: Column<any, unknown>) => CSSProperties;
onClick?: () => void;
onUpdate?: (updates: Record<string, unknown>) => void;
@@ -141,8 +145,9 @@ const MemoizedCell = memo(
next.isEditMode === prev.isEditMode &&
next.cell.getValue() === prev.cell.getValue() &&
next.cell.getContext() === prev.cell.getContext() &&
- next.pinnedColumns === prev.pinnedColumns &&
- next.pinnedShadow === prev.pinnedShadow &&
+ next.visibleColumns === prev.visibleColumns &&
+ next.pinnedStyleKey === prev.pinnedStyleKey &&
+ next.editedCells === prev.editedCells &&
next.columnIndex === prev.columnIndex
) as typeof Cell;
diff --git a/apps/erp/app/components/Table/components/Row.tsx b/apps/erp/app/components/Table/components/Row.tsx
index 943e525af2..2cea2e0459 100644
--- a/apps/erp/app/components/Table/components/Row.tsx
+++ b/apps/erp/app/components/Table/components/Row.tsx
@@ -7,6 +7,7 @@ import type {
Position
} from "~/components/Editable";
import Cell from "./Cell";
+import { areRowPropsEqual } from "./rowMemo";
type RowProps<T> = ComponentProps<typeof Tr> & {
editableComponents?: Record<string, EditableTableCellComponent<T> | object>;
@@ -15,10 +16,15 @@ type RowProps<T> = ComponentProps<typeof Tr> & {
isEditMode: boolean;
isFrozenColumn?: boolean;
isRowSelected?: boolean;
- pinnedColumns: string;
- // See Cell.tsx — primitive render key so memoized rows/cells pick up the
- // pinned-edge shadow when the horizontal scroll position changes.
- pinnedShadow?: string;
+ // Memo key, not rendered: `table.getVisibleLeafColumns()` is memoized by
+ // TanStack, so its identity flips exactly when the column defs are rebuilt or
+ // visibility/order/pinning changes — the cases where a memoized row would
+ // otherwise keep rendering stale cells.
+ visibleColumns: Column<any, unknown>[];
+ // See Cell.tsx — primitive render key covering everything `getPinnedStyles`
+ // can return (scrolled edges + each pinned column's sticky offset), since the
+ // getter itself is a fresh closure every render and can't be compared.
+ pinnedStyleKey?: string;
selectedCell: Position;
row: RowType<T>;
rowIsSelected: boolean;
@@ -34,8 +40,8 @@ const Row = <T extends object>({
isEditMode,
isFrozenColumn = false,
isRowSelected = false,
- pinnedColumns,
- pinnedShadow,
+ visibleColumns,
+ pinnedStyleKey,
row,
rowIsSelected,
selectedCell,
@@ -74,8 +80,8 @@ const Row = <T extends object>({
isSelected={isSelected}
isEditing={isEditing}
isEditMode={isEditMode}
- pinnedColumns={pinnedColumns}
- pinnedShadow={pinnedShadow}
+ visibleColumns={visibleColumns}
+ pinnedStyleKey={pinnedStyleKey}
getPinnedStyles={getPinnedStyles}
onClick={
isEditMode
@@ -90,19 +96,8 @@ const Row = <T extends object>({
);
};
-const MemoizedRow = memo(
- Row,
- (prev, next) =>
- next.rowIsSelected === false &&
- prev.rowIsSelected === false &&
- next.isRowSelected === prev.isRowSelected &&
- next.selectedCell?.row === prev.row.index &&
- next.row.index === prev.selectedCell?.row &&
- next.selectedCell?.column === prev.selectedCell?.column &&
- next.isEditing === prev.isEditing &&
- next.isEditMode === prev.isEditMode &&
- next.pinnedColumns === prev.pinnedColumns &&
- next.pinnedShadow === prev.pinnedShadow
-) as typeof Row;
+// See rowMemo.ts — the comparator lives there so it can be unit tested without
+// mounting the table.
+const MemoizedRow = memo(Row, areRowPropsEqual) as typeof Row;
export default MemoizedRow;
diff --git a/apps/erp/app/components/Table/components/rowMemo.test.ts b/apps/erp/app/components/Table/components/rowMemo.test.ts
new file mode 100644
index 0000000000..dcb540a880
--- /dev/null
+++ b/apps/erp/app/components/Table/components/rowMemo.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, it } from "vitest";
+import type { RowMemoInputs } from "./rowMemo";
+import { areRowPropsEqual } from "./rowMemo";
+
+const ROW = { index: 3 };
+const COLUMNS = [{ id: "name" }];
+
+function props(overrides: Partial<RowMemoInputs> = {}): RowMemoInputs {
+ return {
+ row: ROW,
+ visibleColumns: COLUMNS,
+ selectedCell: null,
+ rowIsSelected: false,
+ isRowSelected: false,
+ isEditing: false,
+ isEditMode: false,
+ isFrozenColumn: false,
+ editedCells: undefined,
+ className: undefined,
+ pinnedStyleKey: "false:false|",
+ ...overrides
+ };
+}
+
+describe("areRowPropsEqual", () => {
+ // The regression this whole change exists for: outside edit mode
+ // `selectedCell` is null, and the old comparator comes out false here, so
+ // every row re-rendered on every render of every table.
+ it("skips the render when nothing changed in read mode", () => {
+ expect(areRowPropsEqual(props(), props())).toBe(true);
+ });
+
+ it("skips the render for an unrelated row while a cell is selected", () => {
+ const selectedCell = { row: 7, column: 2 };
+ expect(
+ areRowPropsEqual(
+ props({ selectedCell, rowIsSelected: false }),
+ props({ selectedCell, rowIsSelected: false })
+ )
+ ).toBe(true);
+ });
+
+ it("re-renders when the row data object changes", () => {
+ expect(areRowPropsEqual(props(), props({ row: { index: 3 } }))).toBe(false);
+ });
+
+ it("re-renders when the visible columns are rebuilt", () => {
+ expect(
+ areRowPropsEqual(props(), props({ visibleColumns: [{ id: "name" }] }))
+ ).toBe(false);
+ });
+
+ it("re-renders when this row gains or loses the selected cell", () => {
+ const before = props({ rowIsSelected: false, selectedCell: null });
+ const after = props({
+ rowIsSelected: true,
+ selectedCell: { row: 3, column: 1 }
+ });
+ expect(areRowPropsEqual(before, after)).toBe(false);
+ expect(areRowPropsEqual(after, before)).toBe(false);
+ });
+
+ it("re-renders when the selected column moves within this row", () => {
+ expect(
+ areRowPropsEqual(
+ props({ rowIsSelected: true, selectedCell: { row: 3, column: 1 } }),
+ props({ rowIsSelected: true, selectedCell: { row: 3, column: 2 } })
+ )
+ ).toBe(false);
+ });
+
+ it("ignores a column move that lands on a different row", () => {
+ expect(
+ areRowPropsEqual(
+ props({ rowIsSelected: false, selectedCell: { row: 7, column: 1 } }),
+ props({ rowIsSelected: false, selectedCell: { row: 7, column: 2 } })
+ )
+ ).toBe(true);
+ });
+
+ it.each([
+ ["isRowSelected", { isRowSelected: true }],
+ ["isEditing", { isEditing: true }],
+ ["isEditMode", { isEditMode: true }],
+ ["isFrozenColumn", { isFrozenColumn: true }],
+ ["editedCells", { editedCells: ["name"] }],
+ ["className", { className: "cursor-pointer" }],
+ ["pinnedStyleKey", { pinnedStyleKey: "true:false|Select@0" }]
+ ])("re-renders when %s changes", (_label, override) => {
+ expect(areRowPropsEqual(props(), props(override))).toBe(false);
+ });
+});
diff --git a/apps/erp/app/components/Table/components/rowMemo.ts b/apps/erp/app/components/Table/components/rowMemo.ts
new file mode 100644
index 0000000000..123e0cc82e
--- /dev/null
+++ b/apps/erp/app/components/Table/components/rowMemo.ts
@@ -0,0 +1,58 @@
+import type { Position } from "~/components/Editable";
+
+/**
+ * The subset of `Row`'s props the memo comparator reads. Kept in its own module
+ * (types only, no runtime imports) so it can be unit tested without mounting the
+ * table.
+ */
+export type RowMemoInputs = {
+ row: unknown;
+ visibleColumns: unknown;
+ selectedCell: Position;
+ rowIsSelected: boolean;
+ isRowSelected?: boolean;
+ isEditing: boolean;
+ isEditMode: boolean;
+ isFrozenColumn?: boolean;
+ editedCells?: string[];
+ className?: string;
+ pinnedStyleKey?: string;
+};
+
+/**
+ * Returns true to SKIP re-rendering the row.
+ *
+ * The version this replaced compared `next.selectedCell?.row === prev.row.index`.
+ * `selectedCell` is null outside edit mode, so that compared `undefined` to a
+ * number and always returned false — every row of every table re-rendered on
+ * every render, which also defeated the `Cell` memo underneath.
+ */
+export function areRowPropsEqual(
+ prev: RowMemoInputs,
+ next: RowMemoInputs
+): boolean {
+ // TanStack reuses row objects while the data is unchanged, and memoizes
+ // `getVisibleLeafColumns()`, so these two identities are the data and
+ // column-layout guards respectively.
+ if (prev.row !== next.row) return false;
+ if (prev.visibleColumns !== next.visibleColumns) return false;
+
+ if (prev.rowIsSelected !== next.rowIsSelected) return false;
+ // Only the row owning the selected cell cares which column is selected.
+ if (
+ next.rowIsSelected &&
+ prev.selectedCell?.column !== next.selectedCell?.column
+ ) {
+ return false;
+ }
+
+ return (
+ prev.isRowSelected === next.isRowSelected &&
+ prev.isEditing === next.isEditing &&
+ prev.isEditMode === next.isEditMode &&
+ prev.isFrozenColumn === next.isFrozenColumn &&
+ prev.editedCells === next.editedCells &&
+ prev.className === next.className &&
+ prev.pinnedStyleKey === next.pinnedStyleKey
+ );
+}
diff --git a/apps/erp/app/hooks/useCurrencyFormatter.tsx b/apps/erp/app/hooks/useCurrencyFormatter.tsx
index 3cb7f551e5..3135c3ca5b 100644
--- a/apps/erp/app/hooks/useCurrencyFormatter.tsx
+++ b/apps/erp/app/hooks/useCurrencyFormatter.tsx
@@ -7,14 +7,21 @@ export function useCurrencyFormatter(options?: Intl.NumberFormatOptions) {
const baseCurrency = company?.baseCurrencyCode ?? "USD";
const { locale } = useLocale();
const currency = options?.currency ?? baseCurrency;
- const formatter = useMemo(
- () =>
- new Intl.NumberFormat(locale, {
- style: "currency",
- currency: currency,
- ...options
- }),
- [locale, currency, options]
- );
+
+ // Every call site passes an object literal, so depending on `options` by
+ // identity meant the memo never hit: a new Intl.NumberFormat on every render,
+ // and — since the formatter is itself a dep of the `columns` memo in several
+ // tables — a full column rebuild with it. Depend on the fields instead.
+ const optionsKey = options ? JSON.stringify(options) : "";
+ const formatter = useMemo(() => {
+ const opts = optionsKey
+ ? (JSON.parse(optionsKey) as Intl.NumberFormatOptions)
+ : undefined;
+ return new Intl.NumberFormat(locale, {
+ style: "currency",
+ currency: currency,
+ ...opts
+ });
+ }, [locale, currency, optionsKey]);
return formatter;
}
diff --git a/apps/erp/app/hooks/useCustomColumns.tsx b/apps/erp/app/hooks/useCustomColumns.tsx
index f380dfec73..59f1f7888a 100644
--- a/apps/erp/app/hooks/useCustomColumns.tsx
+++ b/apps/erp/app/hooks/useCustomColumns.tsx
@@ -2,6 +2,7 @@ import type { Json } from "@carbon/database";
import { Checkbox } from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
import type { ColumnDef } from "@tanstack/react-table";
+import { useMemo } from "react";
import {
LuCalendar,
LuCaseSensitive,
@@ -26,146 +27,156 @@ export function useCustomColumns<T extends { customFields: Json }>(
const customFieldsSchemas = useCustomFieldsSchema();
const schema = customFieldsSchemas?.[table];
- const customColumns: ColumnDef<T>[] = [];
const [people] = usePeople();
const [customers] = useCustomers();
const [suppliers] = useSuppliers();
- schema?.forEach((field) => {
- customColumns.push({
- accessorKey: `customFields->>${field.id}`,
- header: field.name,
- meta: {
- icon: <ColumnIcon dataTypeId={field.dataTypeId} />,
- filter:
- field.dataTypeId === DataType.Boolean
- ? {
- type: "static",
- options: [
- { value: "on", label: t`Yes` },
- { value: "", label: t`No` }
- ]
- }
- : field.dataTypeId === DataType.List
+ // Returned unmemoized, this array's identity changed every render. It is a
+ // dependency of the `columns` memo in ~50 tables, so every render rebuilt
+ // every column def, which invalidated TanStack's column/row/cell objects and
+ // defeated the Row and Cell memos underneath.
+ return useMemo(() => {
+ const customColumns: ColumnDef<T>[] = [];
+
+ schema?.forEach((field) => {
+ customColumns.push({
+ accessorKey: `customFields->>${field.id}`,
+ header: field.name,
+ meta: {
+ icon: <ColumnIcon dataTypeId={field.dataTypeId} />,
+ filter:
+ field.dataTypeId === DataType.Boolean
? {
type: "static",
- options:
- field.listOptions?.map((option) => ({
- value: option,
- label: <Enumerable value={option} />
- })) || []
+ options: [
+ { value: "on", label: t`Yes` },
+ { value: "", label: t`No` }
+ ]
}
- : field.dataTypeId === DataType.User
+ : field.dataTypeId === DataType.List
? {
type: "static",
- options: people.map((person) => ({
- value: person.id,
- label: person.name
- }))
+ options:
+ field.listOptions?.map((option) => ({
+ value: option,
+ label: <Enumerable value={option} />
+ })) || []
}
- : field.dataTypeId === DataType.Text
+ : field.dataTypeId === DataType.User
? {
- type: "fetcher",
- endpoint: path.to.api.customFieldOptions(table, field.id)
+ type: "static",
+ options: people.map((person) => ({
+ value: person.id,
+ label: person.name
+ }))
}
- : field.dataTypeId === DataType.Customer
+ : field.dataTypeId === DataType.Text
? {
- type: "static",
- options: customers.map((customer) => ({
- value: customer.id,
- label: customer.name
- }))
+ type: "fetcher",
+ endpoint: path.to.api.customFieldOptions(
+ table,
+ field.id
+ )
}
- : field.dataTypeId === DataType.Supplier
+ : field.dataTypeId === DataType.Customer
? {
type: "static",
- options: suppliers.map((supplier) => ({
- value: supplier.id,
- label: supplier.name
+ options: customers.map((customer) => ({
+ value: customer.id,
+ label: customer.name
}))
}
- : undefined
- },
- cell: (item) => {
- switch (field.dataTypeId) {
- case DataType.Boolean:
- return isObject(item.row.original.customFields) &&
- field.id in item.row.original.customFields ? (
- <Checkbox
- isChecked={item.row.original?.customFields[field.id] === "on"}
- />
- ) : (
- <Checkbox isChecked={false} />
- );
- case DataType.Date:
- return isObject(item.row.original.customFields) &&
- field.id in item.row.original.customFields
- ? item.row.original?.customFields[field.id]
- : null;
- case DataType.List:
- return isObject(item.row.original.customFields) &&
- field.id in item.row.original.customFields ? (
- <Enumerable
- value={item.row.original.customFields[field.id] as string}
- />
- ) : null;
- case DataType.Numeric:
- return isObject(item.row.original.customFields) &&
- field.id in item.row.original.customFields
- ? item.row.original?.customFields[field.id]
- : null;
- case DataType.Text:
- return isObject(item.row.original.customFields) &&
- field.id in item.row.original.customFields
- ? item.row.original?.customFields[field.id]
- : null;
- case DataType.User:
- if (
- isObject(item.row.original.customFields) &&
- field.id in item.row.original.customFields
- ) {
- const personId = item.row.original?.customFields[
- field.id
- ] as string;
+ : field.dataTypeId === DataType.Supplier
+ ? {
+ type: "static",
+ options: suppliers.map((supplier) => ({
+ value: supplier.id,
+ label: supplier.name
+ }))
+ }
+ : undefined
+ },
+ cell: (item) => {
+ switch (field.dataTypeId) {
+ case DataType.Boolean:
+ return isObject(item.row.original.customFields) &&
+ field.id in item.row.original.customFields ? (
+ <Checkbox
+ isChecked={item.row.original?.customFields[field.id] === "on"}
+ />
+ ) : (
+ <Checkbox isChecked={false} />
+ );
+ case DataType.Date:
+ return isObject(item.row.original.customFields) &&
+ field.id in item.row.original.customFields
+ ? item.row.original?.customFields[field.id]
+ : null;
+ case DataType.List:
+ return isObject(item.row.original.customFields) &&
+ field.id in item.row.original.customFields ? (
+ <Enumerable
+ value={item.row.original.customFields[field.id] as string}
+ />
+ ) : null;
+ case DataType.Numeric:
+ return isObject(item.row.original.customFields) &&
+ field.id in item.row.original.customFields
+ ? item.row.original?.customFields[field.id]
+ : null;
+ case DataType.Text:
+ return isObject(item.row.original.customFields) &&
+ field.id in item.row.original.customFields
+ ? item.row.original?.customFields[field.id]
+ : null;
+ case DataType.User:
+ if (
+ isObject(item.row.original.customFields) &&
+ field.id in item.row.original.customFields
+ ) {
+ const personId = item.row.original?.customFields[
+ field.id
+ ] as string;
- return <EmployeeAvatar employeeId={personId} />;
- } else {
- return null;
- }
- case DataType.Customer:
- if (
- isObject(item.row.original.customFields) &&
- field.id in item.row.original.customFields
- ) {
- const customerId = item.row.original?.customFields[
- field.id
- ] as string;
+ return <EmployeeAvatar employeeId={personId} />;
+ } else {
+ return null;
+ }
+ case DataType.Customer:
+ if (
+ isObject(item.row.original.customFields) &&
+ field.id in item.row.original.customFields
+ ) {
+ const customerId = item.row.original?.customFields[
+ field.id
+ ] as string;
- return <CustomerAvatar customerId={customerId} />;
- } else {
- return null;
- }
- case DataType.Supplier:
- if (
- isObject(item.row.original.customFields) &&
- field.id in item.row.original.customFields
- ) {
- const supplierId = item.row.original?.customFields[
- field.id
- ] as string;
+ return <CustomerAvatar customerId={customerId} />;
+ } else {
+ return null;
+ }
+ case DataType.Supplier:
+ if (
+ isObject(item.row.original.customFields) &&
+ field.id in item.row.original.customFields
+ ) {
+ const supplierId = item.row.original?.customFields[
+ field.id
+ ] as string;
- return <SupplierAvatar supplierId={supplierId} />;
- } else {
+ return <SupplierAvatar supplierId={supplierId} />;
+ } else {
+ return null;
+ }
+ default:
return null;
- }
- default:
- return null;
+ }
}
- }
+ });
});
- });
- return customColumns as ColumnDef<T>[];
+ return customColumns as ColumnDef<T>[];
+ }, [schema, people, customers, suppliers, t, table]);
}
function isObject(value: unknown): value is Record<string, unknown> {
diff --git a/apps/erp/app/hooks/useDebouncedRealtime.ts b/apps/erp/app/hooks/useDebouncedRealtime.ts
index f002a17098..c60cbcf552 100644
--- a/apps/erp/app/hooks/useDebouncedRealtime.ts
+++ b/apps/erp/app/hooks/useDebouncedRealtime.ts
@@ -1,49 +1,18 @@
-import { useRealtimeChannel } from "@carbon/react";
-import { useEffect, useRef } from "react";
-import { useRevalidator } from "react-router";
-import { useUser } from "./useUser";
+import { useRealtime } from "./useRealtime";
/**
- * Like `useRealtime`, but coalesces a burst of change events into a single
- * route revalidation after `debounceMs` of quiet.
+ * `useRealtime` with a longer coalescing window.
*
* Use for append-heavy tables (e.g. `itemLedger`) where one business action
- * inserts many rows at once: without debouncing, a 300-row posting would fire
- * 300 `revalidate()` calls. Subscribe with a `companyId=eq.<id>` filter so new
- * inserts (not just changes to already-loaded rows) trigger a refetch.
+ * inserts many rows at once: a 300-row posting should produce one revalidation,
+ * not a burst spread over the default window. Subscribe with a
+ * `companyId=eq.<id>` filter so new inserts (not just changes to already-loaded
+ * rows) trigger a refetch.
*/
export function useDebouncedRealtime(
table: string,
filter: string | undefined,
debounceMs = 1500
) {
- const { company } = useUser();
- const revalidator = useRevalidator();
- const timeout = useRef<ReturnType<typeof setTimeout> | null>(null);
-
- useEffect(
- () => () => {
- if (timeout.current) clearTimeout(timeout.current);
- },
- []
- );
-
- return useRealtimeChannel({
- topic: `postgres_changes:${table}`,
- dependencies: [company.id, filter, debounceMs],
- setup(channel) {
- return channel.on(
- "postgres_changes",
- { event: "*", schema: "public", table, filter },
- () => {
- // Inserts are already scoped to this company by the `filter` arg, so
- // every event here is relevant — just coalesce the burst.
- if (timeout.current) clearTimeout(timeout.current);
- timeout.current = setTimeout(() => {
- revalidator.revalidate();
- }, debounceMs);
- }
- );
- }
- });
+ return useRealtime(table, filter, debounceMs);
}
diff --git a/apps/erp/app/hooks/useRealtime.tsx b/apps/erp/app/hooks/useRealtime.tsx
index 240e43d40f..7223ebe970 100644
--- a/apps/erp/app/hooks/useRealtime.tsx
+++ b/apps/erp/app/hooks/useRealtime.tsx
@@ -1,27 +1,63 @@
import { getLogger } from "@carbon/logger";
import { useRealtimeChannel } from "@carbon/react";
+import { useEffect, useRef } from "react";
import { useRevalidator } from "react-router";
import { useUser } from "./useUser";
const logger = getLogger("erp", "userealtime");
-export function useRealtime(table: string, filter?: string) {
+// A revalidation re-runs every loader in the matched chain, including the
+// 16-query `x+/_layout` shell — so a burst of row changes must not become a
+// burst of revalidations. Short enough to still feel live.
+const DEFAULT_DEBOUNCE_MS = 300;
+
+export function useRealtime(
+ table: string,
+ filter?: string,
+ debounceMs = DEFAULT_DEBOUNCE_MS
+) {
const { company } = useUser();
const revalidator = useRevalidator();
+ const timeout = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ useEffect(
+ () => () => {
+ if (timeout.current) clearTimeout(timeout.current);
+ },
+ []
+ );
const channel = useRealtimeChannel({
topic: `postgres_changes:${table}`,
- dependencies: [company.id, filter],
+ dependencies: [company.id, filter, debounceMs],
setup(channel) {
return channel.on(
"postgres_changes",
{ event: "*", schema: "public", table: table, filter: filter },
(payload) => {
- if ("companyId" in payload && payload.companyId !== company.id) {
+ // The row lives under `new`/`old`, never on the payload itself. This
+ // guard is what stops the subscriptions that pass no `filter`
+ // (journal, purchaseOrder, changeOrder, printJob, part) from
+ // revalidating on another tenant's writes.
+ const row = (payload.new ?? payload.old) as
+ | { companyId?: string }
+ | undefined;
+ if (row?.companyId && row.companyId !== company.id) {
return;
}
- logger.info("🌀 Revalidaiton payload received:", payload);
- revalidator.revalidate();
+
+ // Metadata only — `payload.new`/`payload.old` carry the whole changed
+ // row, and this hook is shared by every ERP table, so logging the
+ // payload puts arbitrary tenant data and PII into the logs.
+ logger.info("🌀 Revalidation payload received:", {
+ table,
+ eventType: payload.eventType
+ });
+
+ if (timeout.current) clearTimeout(timeout.current);
+ timeout.current = setTimeout(() => {
+ revalidator.revalidate();
+ }, debounceMs);
}
);
}
diff --git a/apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntriesTable.tsx b/apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntriesTable.tsx
index 31bf0f2732..dcd5b628c2 100644
--- a/apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntriesTable.tsx
+++ b/apps/erp/app/modules/accounting/ui/JournalEntries/JournalEntriesTable.tsx
@@ -220,7 +220,7 @@ const JournalEntriesTable = memo(
}
];
return defaultColumns;
- }, [currencyFormatter, people.map, t]);
+ }, [currencyFormatter, people, t]);
const renderContextMenu = useCallback(
(row: JournalEntryListItem) => {
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 38ae4ea9fa..c02a85edc6 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -10,7 +10,11 @@ import { getNextSequence } from "~/modules/settings";
import type { StorageItem } from "~/types";
import { getEdgeFunctionErrorMessage } from "~/utils/error";
import type { GenericQueryFilters } from "~/utils/query";
-import { setGenericQueryFilters, setSearchFilter } from "~/utils/query";
+import {
+ LIST_COUNT,
+ setGenericQueryFilters,
+ setSearchFilter
+} from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import { getItemStorageUnitQuantities } from "../items/items.service";
import type {
@@ -1345,7 +1349,7 @@ export async function getTrackedEntities(
let query = client
.from("trackedEntity")
.select("*", {
- count: "exact"
+ count: LIST_COUNT
})
.eq("companyId", companyId)
.neq("status", "Reserved");
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.ts
index 9556cb6e63..70a2e7beee 100644
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@ -11,7 +11,7 @@ import {
insertSupplierInteraction
} from "~/modules/purchasing";
import type { GenericQueryFilters } from "~/utils/query";
-import { setGenericQueryFilters } from "~/utils/query";
+import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import { getCurrencyByCode } from "../accounting/accounting.service";
import { getEmployeeJob } from "../people/people.service";
@@ -34,6 +34,12 @@ import type {
salesInvoiceValidator
} from "./invoicing.models";
+const PURCHASE_INVOICES_LIST_COLUMNS =
+ "id,invoiceId,supplierId,invoiceSupplierId,supplierReference,postingDate,dateIssued,dateDue,datePaid,balance,assignee,createdBy,createdAt,updatedBy,updatedAt,customFields,companyId,thumbnailPath,itemType,orderTotal,status,paymentTermName" as const;
+
+const SALES_INVOICES_LIST_COLUMNS =
+ "id,invoiceId,status,customerId,customerReference,invoiceCustomerId,postingDate,dateIssued,dateDue,datePaid,balance,assignee,companyId,customFields,createdAt,createdBy,updatedAt,updatedBy,thumbnailPath,itemType,invoiceTotal,paymentTermName" as const;
+
/**
* Compute an invoice's Due Date from its Issue Date and Payment Term.
* Returns null when either input is missing, the payment term genuinely doesn't
@@ -245,7 +251,7 @@ export async function getPurchaseInvoices(
) {
let query = client
.from("purchaseInvoices")
- .select("*", { count: "exact" })
+ .select(PURCHASE_INVOICES_LIST_COLUMNS, { count: LIST_COUNT })
.eq("companyId", companyId);
if (args.search) {
@@ -328,7 +334,7 @@ export async function getSalesInvoices(
) {
let query = client
.from("salesInvoices")
- .select("*", { count: "exact" })
+ .select(SALES_INVOICES_LIST_COLUMNS, { count: LIST_COUNT })
.eq("companyId", companyId);
if (args.search) {
diff --git a/apps/erp/app/modules/invoicing/types.ts b/apps/erp/app/modules/invoicing/types.ts
index 61d8e88576..1dc30d5303 100644
--- a/apps/erp/app/modules/invoicing/types.ts
+++ b/apps/erp/app/modules/invoicing/types.ts
@@ -12,7 +12,10 @@ import type {
getSalesInvoices
} from "./invoicing.service";
-export type PurchaseInvoice = NonNullable<
+export type PurchaseInvoice =
+ Database["public"]["Views"]["purchaseInvoices"]["Row"];
+
+export type PurchaseInvoiceListItem = NonNullable<
Awaited<ReturnType<typeof getPurchaseInvoices>>["data"]
>[number];
@@ -28,7 +31,13 @@ export type PurchaseInvoiceLineType = (typeof purchaseInvoiceLineType)[number];
export type PurchaseInvoiceStatus = (typeof purchaseInvoiceStatusType)[number];
-export type SalesInvoice = NonNullable<
+// The `X`/`XListItem` pairs below are deliberately separate: `X` is the full
+// view row that detail screens read, `XListItem` is exactly what the list
+// query selects. Defining `X` from the list getter is what broke ~250 call
+// sites when the list selects were narrowed.
+export type SalesInvoice = Database["public"]["Views"]["salesInvoices"]["Row"];
+
+export type SalesInvoiceListItem = NonNullable<
Awaited<ReturnType<typeof getSalesInvoices>>["data"]
>[number];
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx
index ccc9d0739a..d3e163fdcd 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx
@@ -28,7 +28,7 @@ import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
import { useCurrencyFormatter, usePermissions, useRealtime } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
-import type { PurchaseInvoice } from "~/modules/invoicing";
+import type { PurchaseInvoiceListItem } from "~/modules/invoicing";
import {
PurchaseInvoicingStatus,
purchaseInvoiceStatusType
@@ -37,7 +37,7 @@ import { usePeople, useSuppliers } from "~/stores";
import { path } from "~/utils/path";
type PurchaseInvoicesTableProps = {
- data: PurchaseInvoice[];
+ data: PurchaseInvoiceListItem[];
count: number;
};
@@ -54,15 +54,16 @@ const PurchaseInvoicesTable = memo(
const currencyFormatter = useCurrencyFormatter();
const [selectedPurchaseInvoice, setSelectedPurchaseInvoice] =
- useState<PurchaseInvoice | null>(null);
+ useState<PurchaseInvoiceListItem | null>(null);
const closePurchaseInvoiceModal = useDisclosure();
const [people] = usePeople();
const [suppliers] = useSuppliers();
- const customColumns = useCustomColumns<PurchaseInvoice>("purchaseInvoice");
+ const customColumns =
+ useCustomColumns<PurchaseInvoiceListItem>("purchaseInvoice");
- const columns = useMemo<ColumnDef<PurchaseInvoice>[]>(() => {
- const defaultColumns: ColumnDef<PurchaseInvoice>[] = [
+ const columns = useMemo<ColumnDef<PurchaseInvoiceListItem>[]>(() => {
+ const defaultColumns: ColumnDef<PurchaseInvoiceListItem>[] = [
{
accessorKey: "invoiceId",
header: t`Invoice Number`,
@@ -290,7 +291,7 @@ const PurchaseInvoicesTable = memo(
}, [currencyFormatter, customColumns, people, suppliers, t]);
const renderContextMenu = useMemo(() => {
- return (row: PurchaseInvoice) => (
+ return (row: PurchaseInvoiceListItem) => (
<>
<MenuItem
disabled={!permissions.can("view", "invoicing")}
@@ -318,7 +319,7 @@ const PurchaseInvoicesTable = memo(
return (
<>
- <Table<PurchaseInvoice>
+ <Table<PurchaseInvoiceListItem>
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 4b19bae119..a900a39613 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx
@@ -28,14 +28,14 @@ import { Enumerable } from "~/components/Enumerable";
import { ConfirmDelete } from "~/components/Modals";
import { useCurrencyFormatter, usePermissions, useRealtime } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
-import type { SalesInvoice } from "~/modules/invoicing";
+import type { SalesInvoiceListItem } from "~/modules/invoicing";
import { salesInvoiceStatusType } from "~/modules/invoicing";
import { useCustomers, usePeople } from "~/stores";
import { path } from "~/utils/path";
import SalesInvoiceStatus from "./SalesInvoiceStatus";
type SalesInvoicesTableProps = {
- data: SalesInvoice[];
+ data: SalesInvoiceListItem[];
count: number;
};
@@ -48,15 +48,15 @@ const SalesInvoicesTable = memo(({ data, count }: SalesInvoicesTableProps) => {
const currencyFormatter = useCurrencyFormatter();
const [selectedSalesInvoice, setSelectedSalesInvoice] =
- useState<SalesInvoice | null>(null);
+ useState<SalesInvoiceListItem | null>(null);
const closeSalesInvoiceModal = useDisclosure();
const [people] = usePeople();
const [customers] = useCustomers();
- const customColumns = useCustomColumns<SalesInvoice>("salesInvoice");
+ const customColumns = useCustomColumns<SalesInvoiceListItem>("salesInvoice");
- const columns = useMemo<ColumnDef<SalesInvoice>[]>(() => {
- const defaultColumns: ColumnDef<SalesInvoice>[] = [
+ const columns = useMemo<ColumnDef<SalesInvoiceListItem>[]>(() => {
+ const defaultColumns: ColumnDef<SalesInvoiceListItem>[] = [
{
accessorKey: "invoiceId",
header: t`Invoice Number`,
@@ -284,7 +284,7 @@ const SalesInvoicesTable = memo(({ data, count }: SalesInvoicesTableProps) => {
}, [currencyFormatter, customColumns, people, customers, t]);
const renderContextMenu = useMemo(() => {
- return (row: SalesInvoice) => (
+ return (row: SalesInvoiceListItem) => (
<>
<MenuItem
disabled={!permissions.can("view", "invoicing")}
@@ -312,7 +312,7 @@ const SalesInvoicesTable = memo(({ data, count }: SalesInvoicesTableProps) => {
return (
<>
- <Table<SalesInvoice>
+ <Table<SalesInvoiceListItem>
count={count}
columns={columns}
data={data}
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 4cc70d14b9..7ad02dbdfe 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -12,7 +12,11 @@ import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
import type { z } from "zod";
import type { GenericQueryFilters } from "~/utils/query";
-import { setGenericQueryFilters, setSearchFilter } from "~/utils/query";
+import {
+ LIST_COUNT,
+ setGenericQueryFilters,
+ setSearchFilter
+} from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import type { nonConformancePriority } from "../quality/quality.models";
import type {
@@ -82,6 +86,21 @@ import {
} from "./items.models";
import type { InventoryItemType } from "./types";
+const PARTS_LIST_COLUMNS =
+ "active,defaultMethodType,description,itemTrackingType,name,replenishmentSystem,revision,readableIdWithRevision,id,companyId,thumbnailPath,supplierIds,revisions,customFields,tags,itemPostingGroupId,createdBy,createdAt,updatedBy,updatedAt,supersessionMode,mpn" as const;
+
+const MATERIALS_LIST_COLUMNS =
+ "active,defaultMethodType,description,itemTrackingType,name,unitOfMeasureCode,revision,readableId,readableIdWithRevision,id,companyId,thumbnailPath,supplierIds,unitOfMeasure,revisions,materialForm,materialSubstance,dimensions,finish,grade,materialType,materialSubstanceId,materialFormId,customFields,tags,itemPostingGroupId,createdBy,createdAt,updatedBy,updatedAt,supersessionMode,mpn" as const;
+
+const TOOLS_LIST_COLUMNS =
+ "active,assignee,defaultMethodType,description,itemTrackingType,name,replenishmentSystem,revision,readableIdWithRevision,id,companyId,thumbnailPath,supplierIds,revisions,customFields,tags,itemPostingGroupId,createdBy,createdAt,updatedBy,updatedAt,supersessionMode,mpn" as const;
+
+const CONSUMABLES_LIST_COLUMNS =
+ "active,assignee,defaultMethodType,description,itemTrackingType,name,replenishmentSystem,readableIdWithRevision,id,companyId,thumbnailPath,supplierIds,customFields,tags,itemPostingGroupId,createdBy,createdAt,updatedBy,updatedAt,supersessionMode,mpn" as const;
+
+const SERVICES_LIST_COLUMNS =
+ "active,defaultMethodType,description,name,replenishmentSystem,revision,readableIdWithRevision,id,companyId,thumbnailPath,supplierIds,revisions,customFields,tags,itemPostingGroupId,createdBy,createdAt,updatedBy,updatedAt" as const;
+
const logger = getLogger("erp", "items");
export async function activateMethodVersion(
@@ -523,8 +542,8 @@ export async function getConsumables(
) {
let query = client
.from("consumables")
- .select("*", {
- count: "exact"
+ .select(CONSUMABLES_LIST_COLUMNS, {
+ count: LIST_COUNT
})
.eq("companyId", companyId);
@@ -1221,8 +1240,8 @@ export async function getMaterials(
) {
let query = client
.from("materials")
- .select("*", {
- count: "exact"
+ .select(MATERIALS_LIST_COLUMNS, {
+ count: LIST_COUNT
})
.or(`companyId.eq.${companyId},companyId.is.null`);
@@ -1755,8 +1774,8 @@ export async function getParts(
) {
let query = client
.from("parts")
- .select("*", {
- count: "exact"
+ .select(PARTS_LIST_COLUMNS, {
+ count: LIST_COUNT
})
.eq("companyId", companyId);
@@ -2005,8 +2024,8 @@ export async function getServices(
) {
let query = client
.from("services")
- .select("*", {
- count: "exact"
+ .select(SERVICES_LIST_COLUMNS, {
+ count: LIST_COUNT
})
.eq("companyId", companyId);
@@ -2099,8 +2118,8 @@ export async function getTools(
) {
let query = client
.from("tools")
- .select("*", {
- count: "exact"
+ .select(TOOLS_LIST_COLUMNS, {
+ count: LIST_COUNT
})
.eq("companyId", companyId);
diff --git a/apps/erp/app/modules/items/types.ts b/apps/erp/app/modules/items/types.ts
index 41b930c6c8..f16c13d619 100644
--- a/apps/erp/app/modules/items/types.ts
+++ b/apps/erp/app/modules/items/types.ts
@@ -92,7 +92,13 @@ export type ConfigurationParameterGroup = NonNullable<
Awaited<ReturnType<typeof getConfigurationParameters>>["groups"]
>[number];
-export type Consumable = NonNullable<
+// The `X`/`XListItem` pairs below are deliberately separate: `X` is the full
+// view row that detail screens read, `XListItem` is exactly what the list
+// query selects. Defining `X` from the list getter is what broke ~250 call
+// sites when the list selects were narrowed.
+export type Consumable = Database["public"]["Views"]["consumables"]["Row"];
+
+export type ConsumableListItem = NonNullable<
Awaited<ReturnType<typeof getConsumables>>["data"]
>[number];
@@ -151,7 +157,9 @@ export type MakeMethod = NonNullable<
Awaited<ReturnType<typeof getMakeMethods>>["data"]
>[number];
-export type Material = NonNullable<
+export type Material = Database["public"]["Views"]["materials"]["Row"];
+
+export type MaterialListItem = NonNullable<
Awaited<ReturnType<typeof getMaterials>>["data"]
>[number];
@@ -187,7 +195,9 @@ export type MethodOperation = NonNullable<
Awaited<ReturnType<typeof getMethodOperations>>["data"]
>[number];
-export type Part = NonNullable<
+export type Part = Database["public"]["Views"]["parts"]["Row"];
+
+export type PartListItem = NonNullable<
Awaited<ReturnType<typeof getParts>>["data"]
>[number];
@@ -203,7 +213,9 @@ export type PickMethod = NonNullable<
Awaited<ReturnType<typeof getPickMethods>>["data"]
>[number];
-export type Service = NonNullable<
+export type Service = Database["public"]["Views"]["services"]["Row"];
+
+export type ServiceListItem = NonNullable<
Awaited<ReturnType<typeof getServices>>["data"]
>[number];
@@ -219,7 +231,9 @@ export type SupplierPart = NonNullable<
Awaited<ReturnType<typeof getSupplierParts>>["data"]
>[number];
-export type Tool = NonNullable<
+export type Tool = Database["public"]["Views"]["tools"]["Row"];
+
+export type ToolListItem = NonNullable<
Awaited<ReturnType<typeof getTools>>["data"]
>[number];
diff --git a/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx b/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx
index ed2658d98e..92644ca846 100644
--- a/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx
+++ b/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx
@@ -61,10 +61,10 @@ import type { action } from "~/routes/x+/items+/update";
import { usePeople } from "~/stores";
import { path } from "~/utils/path";
import { itemTrackingTypes } from "../../items.models";
-import type { Consumable } from "../../types";
+import type { ConsumableListItem } from "../../types";
type ConsumablesTableProps = {
- data: Consumable[];
+ data: ConsumableListItem[];
tags: { name: string }[];
count: number;
};
@@ -96,14 +96,16 @@ const ConsumablesTable = memo(
const permissions = usePermissions();
const deleteItemModal = useDisclosure();
- const [selectedItem, setSelectedItem] = useState<Consumable | null>(null);
+ const [selectedItem, setSelectedItem] = useState<ConsumableListItem | null>(
+ null
+ );
const [people] = usePeople();
const itemPostingGroups = useItemPostingGroups();
- const customColumns = useCustomColumns<Consumable>("consumable");
+ const customColumns = useCustomColumns<ConsumableListItem>("consumable");
- const columns = useMemo<ColumnDef<Consumable>[]>(() => {
- const defaultColumns: ColumnDef<Consumable>[] = [
+ const columns = useMemo<ColumnDef<ConsumableListItem>[]>(() => {
+ const defaultColumns: ColumnDef<ConsumableListItem>[] = [
{
accessorKey: "id",
header: t`Consumable ID`,
@@ -130,7 +132,7 @@ const ConsumablesTable = memo(
exportValue: (row) => row.readableIdWithRevision ?? null
}
},
- exportOnlyColumn<Consumable>({
+ exportOnlyColumn<ConsumableListItem>({
id: "itemName",
header: t`Item Name`,
value: (row) => row.name ?? null
@@ -515,11 +517,11 @@ const ConsumablesTable = memo(
);
const renderContextMenu = useMemo(() => {
- return (row: Consumable) => (
+ return (row: ConsumableListItem) => (
<>
<MenuItem onClick={() => navigate(path.to.consumable(row.id!))}>
<MenuIcon icon={<LuPencil />} />
- Edit Consumable
+ Edit ConsumableListItem
</MenuItem>
<MenuItem
disabled={!permissions.can("delete", "parts")}
@@ -530,7 +532,7 @@ const ConsumablesTable = memo(
}}
>
<MenuIcon icon={<LuTrash />} />
- Delete Consumable
+ Delete ConsumableListItem
</MenuItem>
</>
);
@@ -538,7 +540,7 @@ const ConsumablesTable = memo(
return (
<>
- <Table<Consumable>
+ <Table<ConsumableListItem>
count={count}
columns={columns}
data={data}
diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx
index b4bad5701a..63908a1782 100644
--- a/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx
+++ b/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx
@@ -74,10 +74,10 @@ import type { action } from "~/routes/x+/items+/update";
import { usePeople } from "~/stores";
import { path } from "~/utils/path";
import { itemTrackingTypes } from "../../items.models";
-import type { Material } from "../../types";
+import type { MaterialListItem } from "../../types";
type MaterialsTableProps = {
- data: Material[];
+ data: MaterialListItem[];
tags: { name: string }[];
count: number;
};
@@ -108,19 +108,21 @@ const MaterialsTable = memo(({ data, tags, count }: MaterialsTableProps) => {
const permissions = usePermissions();
const deleteItemModal = useDisclosure();
- const [selectedItem, setSelectedItem] = useState<Material | null>(null);
+ const [selectedItem, setSelectedItem] = useState<MaterialListItem | null>(
+ null
+ );
const [people] = usePeople();
const unitsOfMeasure = useUnitOfMeasure();
const itemPostingGroups = useItemPostingGroups();
- const customColumns = useCustomColumns<Material>("material");
+ const customColumns = useCustomColumns<MaterialListItem>("material");
const filters = useFilters();
const materialSubstanceId = filters.getFilter("materialSubstanceId")?.[0];
const materialFormId = filters.getFilter("materialFormId")?.[0];
- const columns = useMemo<ColumnDef<Material>[]>(() => {
- const defaultColumns: ColumnDef<Material>[] = [
+ const columns = useMemo<ColumnDef<MaterialListItem>[]>(() => {
+ const defaultColumns: ColumnDef<MaterialListItem>[] = [
{
accessorKey: "id",
header: t`Material ID`,
@@ -148,7 +150,7 @@ const MaterialsTable = memo(({ data, tags, count }: MaterialsTableProps) => {
exportValue: (row) => row.readableIdWithRevision ?? null
}
},
- exportOnlyColumn<Material>({
+ exportOnlyColumn<MaterialListItem>({
id: "itemName",
header: t`Item Name`,
value: (row) => row.name ?? null
@@ -641,7 +643,7 @@ const MaterialsTable = memo(({ data, tags, count }: MaterialsTableProps) => {
);
const renderContextMenu = useMemo(() => {
- return (row: Material) => {
+ return (row: MaterialListItem) => {
const revisions =
(row.revisions as {
id: string;
@@ -690,7 +692,7 @@ const MaterialsTable = memo(({ data, tags, count }: MaterialsTableProps) => {
return (
<>
- <Table<Material>
+ <Table<MaterialListItem>
count={count}
columns={columns}
data={data}
diff --git a/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx b/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx
index 7bdd1c2fd1..c230c9cd25 100644
--- a/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx
+++ b/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx
@@ -69,10 +69,10 @@ import {
itemReplenishmentSystems,
itemTrackingTypes
} from "../../items.models";
-import type { Part } from "../../types";
+import type { PartListItem } from "../../types";
type PartsTableProps = {
- data: Part[];
+ data: PartListItem[];
tags: { name: string }[];
count: number;
};
@@ -109,14 +109,14 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {
);
const deleteItemModal = useDisclosure();
- const [selectedItem, setSelectedItem] = useState<Part | null>(null);
+ const [selectedItem, setSelectedItem] = useState<PartListItem | null>(null);
const [people] = usePeople();
const itemPostingGroups = useItemPostingGroups();
- const customColumns = useCustomColumns<Part>("part");
+ const customColumns = useCustomColumns<PartListItem>("part");
- const columns = useMemo<ColumnDef<Part>[]>(() => {
- const defaultColumns: ColumnDef<Part>[] = [
+ const columns = useMemo<ColumnDef<PartListItem>[]>(() => {
+ const defaultColumns: ColumnDef<PartListItem>[] = [
{
accessorKey: "id",
header: t`Part ID`,
@@ -144,7 +144,7 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {
exportValue: (row) => row.readableIdWithRevision ?? null
}
},
- exportOnlyColumn<Part>({
+ exportOnlyColumn<PartListItem>({
id: "itemName",
header: t`Item Name`,
value: (row) => row.name ?? null
@@ -570,7 +570,7 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {
);
const renderContextMenu = useMemo(() => {
- return (row: Part) => {
+ return (row: PartListItem) => {
const revisions =
(row.revisions as {
id: string;
@@ -631,7 +631,7 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {
return (
<>
- <Table<Part>
+ <Table<PartListItem>
count={count}
columns={columns}
data={data}
diff --git a/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx b/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx
index 99331fc351..d7388827de 100644
--- a/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx
+++ b/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx
@@ -63,10 +63,10 @@ import type { action } from "~/routes/x+/items+/update";
import { usePeople } from "~/stores";
import { path } from "~/utils/path";
import { serviceReplenishmentSystems } from "../../items.models";
-import type { Service } from "../../types";
+import type { ServiceListItem } from "../../types";
type ServicesTableProps = {
- data: Service[];
+ data: ServiceListItem[];
tags: { name: string }[];
count: number;
};
@@ -92,14 +92,16 @@ const ServicesTable = memo(({ data, tags, count }: ServicesTableProps) => {
);
const deleteItemModal = useDisclosure();
- const [selectedItem, setSelectedItem] = useState<Service | null>(null);
+ const [selectedItem, setSelectedItem] = useState<ServiceListItem | null>(
+ null
+ );
const [people] = usePeople();
const itemPostingGroups = useItemPostingGroups();
- const customColumns = useCustomColumns<Service>("service");
+ const customColumns = useCustomColumns<ServiceListItem>("service");
- const columns = useMemo<ColumnDef<Service>[]>(() => {
- const defaultColumns: ColumnDef<Service>[] = [
+ const columns = useMemo<ColumnDef<ServiceListItem>[]>(() => {
+ const defaultColumns: ColumnDef<ServiceListItem>[] = [
{
accessorKey: "id",
header: t`Service ID`,
@@ -127,7 +129,7 @@ const ServicesTable = memo(({ data, tags, count }: ServicesTableProps) => {
exportValue: (row) => row.readableIdWithRevision ?? null
}
},
- exportOnlyColumn<Service>({
+ exportOnlyColumn<ServiceListItem>({
id: "itemName",
header: t`Item Name`,
value: (row) => row.name ?? null
@@ -450,7 +452,7 @@ const ServicesTable = memo(({ data, tags, count }: ServicesTableProps) => {
);
const renderContextMenu = useMemo(() => {
- return (row: Service) => {
+ return (row: ServiceListItem) => {
const revisions =
(row.revisions as {
id: string;
@@ -499,7 +501,7 @@ const ServicesTable = memo(({ data, tags, count }: ServicesTableProps) => {
return (
<>
- <Table<Service>
+ <Table<ServiceListItem>
count={count}
columns={columns}
data={data}
diff --git a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx
index 7a5ae3018a..7a5b1ccbe5 100644
--- a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx
+++ b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx
@@ -69,10 +69,10 @@ import {
itemReplenishmentSystems,
itemTrackingTypes
} from "../../items.models";
-import type { Tool } from "../../types";
+import type { ToolListItem } from "../../types";
type ToolsTableProps = {
- data: Tool[];
+ data: ToolListItem[];
tags: { name: string }[];
count: number;
};
@@ -109,14 +109,14 @@ const ToolsTable = memo(({ data, tags, count }: ToolsTableProps) => {
);
const deleteItemModal = useDisclosure();
- const [selectedItem, setSelectedItem] = useState<Tool | null>(null);
+ const [selectedItem, setSelectedItem] = useState<ToolListItem | null>(null);
const [people] = usePeople();
const itemPostingGroups = useItemPostingGroups();
- const customColumns = useCustomColumns<Tool>("tool");
+ const customColumns = useCustomColumns<ToolListItem>("tool");
- const columns = useMemo<ColumnDef<Tool>[]>(() => {
- const defaultColumns: ColumnDef<Tool>[] = [
+ const columns = useMemo<ColumnDef<ToolListItem>[]>(() => {
+ const defaultColumns: ColumnDef<ToolListItem>[] = [
{
accessorKey: "id",
header: t`Tool ID`,
@@ -144,7 +144,7 @@ const ToolsTable = memo(({ data, tags, count }: ToolsTableProps) => {
exportValue: (row) => row.readableIdWithRevision ?? null
}
},
- exportOnlyColumn<Tool>({
+ exportOnlyColumn<ToolListItem>({
id: "itemName",
header: t`Item Name`,
value: (row) => row.name ?? null
@@ -558,7 +558,7 @@ const ToolsTable = memo(({ data, tags, count }: ToolsTableProps) => {
);
const renderContextMenu = useMemo(() => {
- return (row: Tool) => {
+ return (row: ToolListItem) => {
const revisions =
(row.revisions as {
id: string;
@@ -607,7 +607,7 @@ const ToolsTable = memo(({ data, tags, count }: ToolsTableProps) => {
return (
<>
- <Table<Tool>
+ <Table<ToolListItem>
count={count}
columns={columns}
data={data}
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 652ea63587..d912ec78e1 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -25,7 +25,11 @@ import { nanoid } from "nanoid";
import type { z } from "zod";
import type { StorageItem } from "~/types";
import type { GenericQueryFilters } from "~/utils/query";
-import { getGenericFilter, setGenericQueryFilters } from "~/utils/query";
+import {
+ getGenericFilter,
+ LIST_COUNT,
+ setGenericQueryFilters
+} from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import { getDefaultStorageUnitForJob } from "../inventory";
import { getEmployeeJob } from "../people";
@@ -992,7 +996,7 @@ export async function getJobs(
let query = client
.from("jobs")
.select("*", {
- count: "exact"
+ count: LIST_COUNT
})
.eq("companyId", companyId);
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index c2c7ab6c41..21caab904f 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -11,7 +11,7 @@ import type {
import type { z } from "zod";
import { getEmployeeJob } from "~/modules/people";
import type { GenericQueryFilters } from "~/utils/query";
-import { setGenericQueryFilters } from "~/utils/query";
+import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import { getCurrencyByCode } from "../accounting/accounting.service";
import type { PurchaseInvoice } from "../invoicing/types";
@@ -43,6 +43,9 @@ import type {
} from "./purchasing.models";
import type { PurchaseOrder, PurchasingRFQ, SupplierQuote } from "./types";
+const PURCHASE_ORDERS_LIST_COLUMNS =
+ "id,purchaseOrderId,status,orderDate,supplierId,supplierReference,assignee,companyId,customFields,createdAt,createdBy,updatedAt,updatedBy,thumbnailPath,itemType,orderTotal,receivableQuantity,receivedQuantity,shippingMethodId,receiptRequestedDate,receiptPromisedDate,deliveryDate,dropShipment,paymentTermId,createdByFullName,assigneeFullName" as const;
+
const logger = getLogger("erp", "purchasing-service");
export async function closePurchaseOrder(
@@ -323,7 +326,7 @@ export async function getPurchaseOrders(
) {
let query = client
.from("purchaseOrders")
- .select("*", { count: "exact" })
+ .select(PURCHASE_ORDERS_LIST_COLUMNS, { count: LIST_COUNT })
.eq("companyId", companyId);
if (args.search) {
diff --git a/apps/erp/app/modules/purchasing/types.ts b/apps/erp/app/modules/purchasing/types.ts
index e32747f4cc..92727d9966 100644
--- a/apps/erp/app/modules/purchasing/types.ts
+++ b/apps/erp/app/modules/purchasing/types.ts
@@ -22,12 +22,16 @@ import type {
export type PurchaseOrderAttachment = FileObject; // TODO: remove
-export type PurchaseOrder = NonNullable<
+// The `X`/`XListItem` pairs below are deliberately separate: `X` is the full
+// view row that detail screens read, `XListItem` is exactly what the list
+// query selects. Defining `X` from the list getter is what broke ~250 call
+// sites when the list selects were narrowed.
+export type PurchaseOrder =
+ Database["public"]["Views"]["purchaseOrders"]["Row"];
+
+export type PurchaseOrderListItem = NonNullable<
Awaited<ReturnType<typeof getPurchaseOrders>>["data"]
->[number] & {
- receivableQuantity?: number | null;
- receivedQuantity?: number | null;
-};
+>[number];
export type PurchaseOrderDelivery = NonNullable<
Awaited<ReturnType<typeof getPurchaseOrderDelivery>>["data"]
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx
index 13f93c6ff5..038cd3a952 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx
@@ -48,7 +48,7 @@ import { useShippingMethod } from "~/components/Form/ShippingMethod";
import { ConfirmDelete } from "~/components/Modals";
import { useCurrencyFormatter, usePermissions, useRealtime } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
-import type { PurchaseOrder } from "~/modules/purchasing";
+import type { PurchaseOrderListItem } from "~/modules/purchasing";
import { purchaseOrderStatusType } from "~/modules/purchasing";
import type { action } from "~/routes/x+/purchase-order+/update";
import { usePeople, useSuppliers } from "~/stores";
@@ -57,7 +57,7 @@ import PurchasingStatus from "./PurchasingStatus";
import { usePurchaseOrder } from "./usePurchaseOrder";
type PurchaseOrdersTableProps = {
- data: PurchaseOrder[];
+ data: PurchaseOrderListItem[];
count: number;
};
@@ -70,7 +70,7 @@ const PurchaseOrdersTable = memo(
const currencyFormatter = useCurrencyFormatter();
const [selectedPurchaseOrder, setSelectedPurchaseOrder] =
- useState<PurchaseOrder | null>(null);
+ useState<PurchaseOrderListItem | null>(null);
const deletePurchaseOrderModal = useDisclosure();
@@ -81,10 +81,11 @@ const PurchaseOrdersTable = memo(
const { edit, receive } = usePurchaseOrder();
- const customColumns = useCustomColumns<PurchaseOrder>("purchaseOrder");
+ const customColumns =
+ useCustomColumns<PurchaseOrderListItem>("purchaseOrder");
- const columns = useMemo<ColumnDef<PurchaseOrder>[]>(() => {
- const defaultColumns: ColumnDef<PurchaseOrder>[] = [
+ const columns = useMemo<ColumnDef<PurchaseOrderListItem>[]>(() => {
+ const defaultColumns: ColumnDef<PurchaseOrderListItem>[] = [
{
accessorKey: "purchaseOrderId",
header: t`PO Number`,
@@ -159,7 +160,7 @@ const PurchaseOrdersTable = memo(
meta: {
filterHeader: t`Received`,
icon: <LuPackageCheck />,
- exportValue: (row: PurchaseOrder) =>
+ exportValue: (row: PurchaseOrderListItem) =>
(row.receivableQuantity ?? 0) > 0
? `${row.receivedQuantity ?? 0}/${row.receivableQuantity}`
: null
@@ -426,7 +427,7 @@ const PurchaseOrdersTable = memo(
);
const renderContextMenu = useCallback(
- (row: PurchaseOrder) => (
+ (row: PurchaseOrderListItem) => (
<>
<MenuItem
disabled={!permissions.can("view", "purchasing")}
@@ -484,7 +485,7 @@ const PurchaseOrdersTable = memo(
return (
<>
- <Table<PurchaseOrder>
+ <Table<PurchaseOrderListItem>
count={count}
columns={columns}
data={data}
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/usePurchaseOrder.ts b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/usePurchaseOrder.ts
index e22250f1b9..d0590ebb40 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/usePurchaseOrder.ts
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/usePurchaseOrder.ts
@@ -15,13 +15,13 @@ export const usePurchaseOrder = () => {
const submit = useSubmit();
const edit = useCallback(
- (purchaseOrder: PurchaseOrder) =>
+ (purchaseOrder: Pick<PurchaseOrder, "id">) =>
navigate(path.to.purchaseOrder(purchaseOrder.id!)),
[navigate]
);
const invoice = useCallback(
- (purchaseOrder: PurchaseOrder) =>
+ (purchaseOrder: Pick<PurchaseOrder, "id">) =>
navigate(
`${path.to.newPurchaseInvoice}?sourceDocument=Purchase Order&sourceDocumentId=${purchaseOrder.id}`
),
@@ -29,7 +29,7 @@ export const usePurchaseOrder = () => {
);
const receive = useCallback(
- (purchaseOrder: PurchaseOrder) => {
+ (purchaseOrder: Pick<PurchaseOrder, "id">) => {
if (!purchaseOrder.id) return;
const formData = new FormData();
formData.set("sourceDocument", "Purchase Order");
@@ -40,7 +40,7 @@ export const usePurchaseOrder = () => {
);
const ship = useCallback(
- (purchaseOrder: PurchaseOrder) => {
+ (purchaseOrder: Pick<PurchaseOrder, "id">) => {
if (!purchaseOrder.id) return;
const formData = new FormData();
formData.set("sourceDocument", "Purchase Order");
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index a1f42f195a..f9278b5d8d 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -14,7 +14,7 @@ import type { z } from "zod";
import { getSupplierPriceBreaksForItems } from "~/modules/items/items.service";
import { getEmployeeJob } from "~/modules/people";
import type { GenericQueryFilters } from "~/utils/query";
-import { setGenericQueryFilters } from "~/utils/query";
+import { LIST_COUNT, setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import { getCurrencyByCode } from "../accounting";
import type {
@@ -74,6 +74,12 @@ import type {
SalesRFQ
} from "./types";
+const QUOTES_LIST_COLUMNS =
+ "id,quoteId,revisionId,dueDate,expirationDate,status,salesPersonId,estimatorId,customerId,customerReference,assignee,customFields,companyId,createdAt,createdBy,updatedAt,updatedBy,thumbnailPath,itemType,locationName,lines,completedLines" as const;
+
+const SALES_ORDERS_LIST_COLUMNS =
+ "id,salesOrderId,status,orderDate,customerId,customerReference,assignee,companyId,customFields,createdAt,createdBy,updatedAt,updatedBy,locationId,displayStatus,thumbnailPath,itemType,orderTotal,jobs,lines,paymentTermId,shippingMethodId,receiptPromisedDate,dropShipment" as const;
+
const logger = getLogger("erp", "sales");
export function applyPriceRules(
@@ -1159,7 +1165,7 @@ export async function getQuotes(
) {
let query = client
.from("quotes")
- .select("*", { count: "exact" })
+ .select(QUOTES_LIST_COLUMNS, { count: LIST_COUNT })
.eq("companyId", companyId);
if (args.search) {
@@ -1633,7 +1639,7 @@ export async function getSalesOrders(
) {
let query = client
.from("salesOrders")
- .select("*", { count: "exact" })
+ .select(SALES_ORDERS_LIST_COLUMNS, { count: LIST_COUNT })
.eq("companyId", companyId);
if (args.search) {
diff --git a/apps/erp/app/modules/sales/types.ts b/apps/erp/app/modules/sales/types.ts
index 7257a34e22..ad484b6a9f 100644
--- a/apps/erp/app/modules/sales/types.ts
+++ b/apps/erp/app/modules/sales/types.ts
@@ -185,7 +185,13 @@ export type QuotationMakeMethod = NonNullable<
Awaited<ReturnType<typeof getQuoteMakeMethod>>["data"]
>;
-export type Quotation = NonNullable<
+// The `X`/`XListItem` pairs below are deliberately separate: `X` is the full
+// view row that detail screens read, `XListItem` is exactly what the list
+// query selects. Defining `X` from the list getter is what broke ~250 call
+// sites when the list selects were narrowed.
+export type Quotation = Database["public"]["Views"]["quotes"]["Row"];
+
+export type QuotationListItem = NonNullable<
Awaited<ReturnType<typeof getQuotes>>["data"]
>[number];
@@ -221,7 +227,9 @@ export type QuotationShipment = NonNullable<
Awaited<ReturnType<typeof getQuoteShipment>>["data"]
>;
-export type SalesOrder = NonNullable<
+export type SalesOrder = Database["public"]["Views"]["salesOrders"]["Row"];
+
+export type SalesOrderListItem = NonNullable<
Awaited<ReturnType<typeof getSalesOrders>>["data"]
>[number];
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx
index 776ffa2d6c..9d380b6f3b 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuotesTable.tsx
@@ -36,11 +36,11 @@ import { useCustomColumns } from "~/hooks/useCustomColumns";
import { useCustomers, usePeople } from "~/stores";
import { path } from "~/utils/path";
import { quoteStatusType } from "../../sales.models";
-import type { Quotation } from "../../types";
+import type { QuotationListItem } from "../../types";
import QuoteStatus from "./QuoteStatus";
type QuotesTableProps = {
- data: Quotation[];
+ data: QuotationListItem[];
count: number;
};
@@ -49,22 +49,21 @@ const QuotesTable = memo(({ data, count }: QuotesTableProps) => {
const permissions = usePermissions();
const navigate = useNavigate();
- const [selectedQuotation, setSelectedQuotation] = useState<Quotation | null>(
- null
- );
+ const [selectedQuotation, setSelectedQuotation] =
+ useState<QuotationListItem | null>(null);
const deleteQuotationModal = useDisclosure();
const [customers] = useCustomers();
const [people] = usePeople();
- const customColumns = useCustomColumns<Quotation>("quote");
- const columns = useMemo<ColumnDef<Quotation>[]>(() => {
+ const customColumns = useCustomColumns<QuotationListItem>("quote");
+ const columns = useMemo<ColumnDef<QuotationListItem>[]>(() => {
const employeeOptions = people.map((employee) => ({
value: employee.id,
label: employee.name
}));
- const defaultColumns: ColumnDef<Quotation>[] = [
+ const defaultColumns: ColumnDef<QuotationListItem>[] = [
{
accessorKey: "quoteId",
header: t`Quote Number`,
@@ -285,7 +284,7 @@ const QuotesTable = memo(({ data, count }: QuotesTableProps) => {
}, [customers, people, customColumns, t]);
const renderContextMenu = useMemo(() => {
- return (row: Quotation) => (
+ return (row: QuotationListItem) => (
<>
<MenuItem onClick={() => navigate(path.to.quoteDetails(row.id!))}>
<MenuIcon icon={<LuPencil />} />
@@ -308,7 +307,7 @@ const QuotesTable = memo(({ data, count }: QuotesTableProps) => {
return (
<>
- <Table<Quotation>
+ <Table<QuotationListItem>
count={count}
columns={columns}
data={data}
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx
index 48a5fb0e94..5eb07d1f34 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx
@@ -63,12 +63,12 @@ import JobStatus from "~/modules/production/ui/Jobs/JobStatus";
import { useCustomers, usePeople } from "~/stores";
import { path } from "~/utils/path";
import { salesOrderStatusType } from "../../sales.models";
-import type { SalesOrder, SalesOrderJob } from "../../types";
+import type { SalesOrderJob, SalesOrderListItem } from "../../types";
import SalesStatus from "./SalesStatus";
import { useSalesOrder } from "./useSalesOrder";
type SalesOrdersTableProps = {
- data: SalesOrder[];
+ data: SalesOrderListItem[];
count: number;
};
@@ -95,7 +95,7 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {
const currencyFormatter = useCurrencyFormatter();
const [selectedSalesOrder, setSelectedSalesOrder] =
- useState<SalesOrder | null>(null);
+ useState<SalesOrderListItem | null>(null);
const deleteSalesOrderModal = useDisclosure();
@@ -108,10 +108,10 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {
const { edit } = useSalesOrder();
- const customColumns = useCustomColumns<SalesOrder>("salesOrder");
+ const customColumns = useCustomColumns<SalesOrderListItem>("salesOrder");
- const columns = useMemo<ColumnDef<SalesOrder>[]>(() => {
- const defaultColumns: ColumnDef<SalesOrder>[] = [
+ const columns = useMemo<ColumnDef<SalesOrderListItem>[]>(() => {
+ const defaultColumns: ColumnDef<SalesOrderListItem>[] = [
{
accessorKey: "salesOrderId",
header: t`Sales Order Number`,
@@ -523,7 +523,7 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {
]);
const renderContextMenu = useMemo(() => {
- return (row: SalesOrder) => (
+ return (row: SalesOrderListItem) => (
<>
<MenuItem
disabled={!permissions.can("view", "sales")}
@@ -563,7 +563,7 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {
return (
<>
- <Table<SalesOrder>
+ <Table<SalesOrderListItem>
count={count}
columns={columns}
data={data}
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/useSalesOrder.ts b/apps/erp/app/modules/sales/ui/SalesOrder/useSalesOrder.ts
index 59ee39af6d..f2d6d0b070 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/useSalesOrder.ts
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/useSalesOrder.ts
@@ -8,12 +8,13 @@ export const useSalesOrder = () => {
const submit = useSubmit();
const edit = useCallback(
- (salesOrder: SalesOrder) => navigate(path.to.salesOrder(salesOrder.id!)),
+ (salesOrder: Pick<SalesOrder, "id">) =>
+ navigate(path.to.salesOrder(salesOrder.id!)),
[navigate]
);
const invoice = useCallback(
- (salesOrder: SalesOrder) =>
+ (salesOrder: Pick<SalesOrder, "id">) =>
navigate(
`${path.to.newSalesInvoice}?sourceDocument=Sales Order&sourceDocumentId=${salesOrder.id}`
),
@@ -21,7 +22,7 @@ export const useSalesOrder = () => {
);
const ship = useCallback(
- (salesOrder: SalesOrder) => {
+ (salesOrder: Pick<SalesOrder, "id">) => {
const formData = new FormData();
formData.set("sourceDocument", "Sales Order");
formData.set("sourceDocumentId", salesOrder.id!);
diff --git a/apps/erp/app/modules/shared/location.server.ts b/apps/erp/app/modules/shared/location.server.ts
new file mode 100644
index 0000000000..a08ff86dca
--- /dev/null
+++ b/apps/erp/app/modules/shared/location.server.ts
@@ -0,0 +1,91 @@
+import { error } from "@carbon/auth";
+import { flash } from "@carbon/auth/session.server";
+import type { Database } from "@carbon/database";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { redirect } from "react-router";
+import { getLocationsList } from "~/modules/resources";
+import { getUserDefaults } from "~/modules/users/users.server";
+
+/**
+ * Resolve the location a location-scoped screen should render.
+ *
+ * Precedence: the `?location=` search param, then the user's default location,
+ * then the company's first location. Each of the six planning/scheduling
+ * screens carried its own copy of this, differing only in where they redirect
+ * on failure.
+ *
+ * The steps run sequentially on purpose: each one usually resolves the id, so
+ * running them concurrently would add queries to the common path to save a
+ * round-trip on the rare one.
+ *
+ * The returned id always belongs to `companyId` — callers rely on that, because
+ * several run with `bypassRls: true` and then filter only on the location.
+ */
+export async function resolveLocationId(
+ client: SupabaseClient<Database>,
+ request: Request,
+ args: {
+ searchParams: URLSearchParams;
+ userId: string;
+ companyId: string;
+ /** Where to send the user if their defaults can't be read. */
+ onDefaultsError: string;
+ /** Where to send the user if the company has no locations. */
+ onNoLocations: string;
+ }
+): Promise<string> {
+ const { searchParams, userId, companyId, onDefaultsError, onNoLocations } =
+ args;
+
+ let locationId = searchParams.get("location");
+
+ // `?location=` is attacker-controlled and five of the six callers run with
+ // `bypassRls: true`, over queries that filter on the location with no company
+ // predicate of their own (`get_jobs_by_date_range`, `get_unscheduled_jobs`,
+ // `get_active_job_operations_by_location`, the `workCenters` reads) — so a
+ // foreign id here would return another tenant's rows. Falls back to the
+ // user's default rather than 404ing, which is what a stale bookmark should do.
+ if (locationId) {
+ const requested = await client
+ .from("location")
+ .select("id")
+ .eq("id", locationId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+
+ if (requested.error || !requested.data) {
+ locationId = null;
+ }
+ }
+
+ if (!locationId) {
+ const userDefaults = await getUserDefaults(client, userId, companyId);
+ if (userDefaults.error) {
+ throw redirect(
+ onDefaultsError,
+ await flash(
+ request,
+ error(userDefaults.error, "Failed to load default location")
+ )
+ );
+ }
+
+ locationId = userDefaults.data?.locationId ?? null;
+ }
+
+ if (!locationId) {
+ const locations = await getLocationsList(client, companyId);
+ if (locations.error || !locations.data?.length) {
+ throw redirect(
+ onNoLocations,
+ await flash(
+ request,
+ error(locations.error, "Failed to load any locations")
+ )
+ );
+ }
+ locationId = locations.data[0].id as string;
+ }
+
+ return locationId;
+}
diff --git a/apps/erp/app/modules/users/users.server.ts b/apps/erp/app/modules/users/users.server.ts
index 561be997cd..56c217eccd 100644
--- a/apps/erp/app/modules/users/users.server.ts
+++ b/apps/erp/app/modules/users/users.server.ts
@@ -9,6 +9,12 @@ import {
} from "@carbon/auth/users.server";
import type { Database, Json } from "@carbon/database";
import { redis } from "@carbon/kv";
+
+// Re-exported, not reimplemented: this module used to carry a near-identical
+// copy that (a) missed the canonical version's cache TTL and (b) bypassed its
+// per-request memoization.
+export { getUserClaims } from "@carbon/auth/users.server";
+
import { getLogger } from "@carbon/logger";
import type { SupabaseClient } from "@supabase/supabase-js";
@@ -641,51 +647,6 @@ export async function getUserByEmail(email: string) {
.single();
}
-export async function getUserClaims(userId: string, companyId: string) {
- let claims: {
- permissions: Record<string, Permission>;
- role: string | null;
- } | null = null;
-
- try {
- const cachedClaims = await redis.get(getPermissionCacheKey(userId));
- if (cachedClaims) {
- claims = JSON.parse(cachedClaims) as {
- permissions: Record<string, Permission>;
- role: string | null;
- };
- }
- } catch (e) {
- logger.error("Failed to get claims from redis", { error: e });
- } finally {
- // if we don't have permissions from redis, get them from the database
- if (!claims) {
- // TODO: remove service role from here, and move it up a level
- const rawClaims = await getClaims(
- getCarbonServiceRole(),
- userId,
- companyId
- );
- if (rawClaims.error || rawClaims.data === null) {
- logger.error("Failed to get claims", { error: rawClaims.error });
- throw new Error("Failed to get claims");
- }
-
- // convert rawClaims to permissions
- claims = makePermissionsFromClaims(rawClaims.data as Json[]);
-
- // store claims in redis
- await redis.set(getPermissionCacheKey(userId), JSON.stringify(claims));
-
- if (!claims) {
- throw new Error("Failed to get claims");
- }
- }
-
- return claims;
- }
-}
-
export async function getUserGroups(
client: SupabaseClient<Database>,
userId: string
diff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsx
index 49a070e2d2..1082d82108 100644
--- a/apps/erp/app/root.tsx
+++ b/apps/erp/app/root.tsx
@@ -7,7 +7,10 @@ import {
} from "@carbon/auth/middleware/flash.server";
import { validator } from "@carbon/form";
import { LocaleProvider, resolveLanguage } from "@carbon/locale";
-import { requestIdMiddleware } from "@carbon/logger/middleware.server";
+import {
+ requestContextMiddleware,
+ requestIdMiddleware
+} from "@carbon/logger/middleware.server";
import {
OperatingSystemContextProvider,
Toaster,
@@ -48,7 +51,12 @@ import "@carbon/lib/shims";
import type { Route } from "./+types/root";
import { getTheme } from "./services/theme.server";
-export const middleware = [requestIdMiddleware, flashMiddleware];
+export const middleware = [
+ // First: publishes the request context so server code can reach it via ALS.
+ requestContextMiddleware,
+ requestIdMiddleware,
+ flashMiddleware
+];
export const clientMiddleware = [flashClientMiddleware];
export const links: LinksFunction = () => {
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
index 8a9f07d50c..ad3795fda6 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-metadata.json
@@ -1,5 +1,5 @@
{
- "generated": "2026-08-07T00:38:01.169Z",
+ "generated": "2026-08-07T05:01:49.045Z",
"totalTools": 1417,
"modules": 15,
"tools": [
diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsx
index ad1768e74d..e09362bec2 100644
--- a/apps/erp/app/routes/x+/_layout.tsx
+++ b/apps/erp/app/routes/x+/_layout.tsx
@@ -28,7 +28,7 @@ import {
useNProgress
} from "@carbon/react";
import { getStripeCustomerByCompanyId } from "@carbon/stripe/stripe.server";
-import { Edition } from "@carbon/utils";
+import { Edition, isSearchParamOnlyNavigation } from "@carbon/utils";
import posthog from "posthog-js";
import { Suspense } from "react";
import type {
@@ -72,6 +72,8 @@ import { ERP_URL, MES_URL, path } from "~/utils/path";
export const shouldRevalidate: ShouldRevalidateFunction = ({
currentUrl,
+ nextUrl,
+ formMethod,
defaultShouldRevalidate
}) => {
if (
@@ -85,6 +87,18 @@ export const shouldRevalidate: ShouldRevalidateFunction = ({
return true;
}
+ // This loader is the app shell: 16 parallel queries plus an auth round-trip.
+ // Without this it re-ran on every table filter, sort and page click, none of
+ // which can change anything it returns.
+ // NOTE: `useRevalidator().revalidate()` — how the realtime hooks refresh —
+ // also looks like a same-pathname GET, so the shell does not re-run for
+ // realtime events either. Leaf loaders still refresh, which is the intent.
+ // Shell data that must react to a realtime change needs an explicit case
+ // above.
+ if (isSearchParamOnlyNavigation({ currentUrl, nextUrl, formMethod })) {
+ return false;
+ }
+
return defaultShouldRevalidate;
};
@@ -109,6 +123,15 @@ export async function loader({ request }: LoaderFunctionArgs) {
const client = getCarbon(accessToken);
+ // Only probe product signals when the company is actually enrolled, so the
+ // home card + nav badge count gates the same way the hub page does. Chained
+ // off the hub query rather than awaited after the fan-out below, so the
+ // probes overlap the rest of it instead of forming a second serial wave.
+ const implementationHubPromise = getImplementationHub(client, companyId);
+ const implementationSignalsPromise = implementationHubPromise.then((hub) =>
+ hub.data ? detectImplementationSignals(client, companyId) : null
+ );
+
// Parallelize all requests
const [
companies,
@@ -126,7 +149,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
modulePreferences,
printerRoutes,
implementationHub,
- implementationCheckStates
+ implementationCheckStates,
+ implementationSignals
] = await Promise.all([
getCompanies(client, userId),
getEmployeeCompanies(client, userId),
@@ -144,8 +168,9 @@ export async function loader({ request }: LoaderFunctionArgs) {
isAuditLogEnabled(client, companyId).catch(() => false),
getModulePreferences(client, userId, companyId),
getPrinterRoutes(client, companyId),
- getImplementationHub(client, companyId),
- getImplementationCheckStates(client, companyId)
+ implementationHubPromise,
+ getImplementationCheckStates(client, companyId),
+ implementationSignalsPromise
]);
if (!claims || user.error || !user.data || !groups.data) {
@@ -201,12 +226,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
throw redirect(path.to.onboarding.root);
}
- // Only probe product signals when the company is actually enrolled, so the
- // home card + nav badge count gates the same way the hub page does.
- const implementationSignals = implementationHub.data
- ? await detectImplementationSignals(client, companyId)
- : null;
-
return data({
session: {
accessToken,
diff --git a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.tsx b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.tsx
index fab08a9a4f..cd3645e5af 100644
--- a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.tsx
+++ b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.tsx
@@ -11,8 +11,7 @@ import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useLoaderData } from "react-router";
import InventoryItemHeader from "~/modules/inventory/ui/Inventory/InventoryItemHeader";
import { getItem, getPickMethod, upsertPickMethod } from "~/modules/items";
-import { getLocationsList } from "~/modules/resources";
-import { getUserDefaults } from "~/modules/users/users.server";
+import { resolveLocationId } from "~/modules/shared/location.server";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
@@ -25,36 +24,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const url = new URL(request.url);
const searchParams = new URLSearchParams(url.search);
- let locationId = searchParams.get("location");
-
- if (!locationId) {
- const userDefaults = await getUserDefaults(client, userId, companyId);
- if (userDefaults.error) {
- throw redirect(
- path.to.inventory,
- await flash(
- request,
- error(userDefaults.error, "Failed to load default location")
- )
- );
- }
-
- locationId = userDefaults.data?.locationId ?? null;
- }
-
- if (!locationId) {
- const locations = await getLocationsList(client, companyId);
- if (locations.error || !locations.data?.length) {
- throw redirect(
- path.to.inventory,
- await flash(
- request,
- error(locations.error, "Failed to load any locations")
- )
- );
- }
- locationId = locations.data?.[0].id as string;
- }
+ const locationId = await resolveLocationId(client, request, {
+ searchParams,
+ userId,
+ companyId,
+ onDefaultsError: path.to.inventory,
+ onNoLocations: path.to.inventory
+ });
// Ensure pick method exists for this item/location combination
const ensurePickMethod = await upsertPickMethod(client, {
diff --git a/apps/erp/app/routes/x+/part+/$itemId.tsx b/apps/erp/app/routes/x+/part+/$itemId.tsx
index fb507d903e..12ace31365 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.tsx
@@ -112,38 +112,41 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const url = new URL(request.url);
const requestedMethodId = url.searchParams.get("methodId");
- const methodTree = getMakeMethods(client, itemId, companyId).then(
- async (makeMethods) => {
- // Include CO-owned drafts so a revision/new-part item created by an open
- // Change Notice shows its method tree on the item master, in sync with the
- // CO (same makeMethod). Active is still preferred as the default below.
- const selectable = makeMethods.data ?? [];
- const makeMethod = requestedMethodId
- ? (selectable.find((m) => m.id === requestedMethodId) ??
- selectable.find((m) => m.status === "Active") ??
- selectable[0])
- : (selectable.find((m) => m.status === "Active") ?? selectable[0]);
- if (!makeMethod) return null;
+ // One query, two consumers: `methodTree` derives from it and the raw list is
+ // also deferred to the client. Calling getMakeMethods twice issued the same
+ // query twice on every part-detail load.
+ const makeMethodsPromise = getMakeMethods(client, itemId, companyId);
- const fullMethod = await getMakeMethodById(
- client,
- makeMethod.id,
- companyId
- );
- if (fullMethod.error || !fullMethod.data) return null;
+ const methodTree = makeMethodsPromise.then(async (makeMethods) => {
+ // Include CO-owned drafts so a revision/new-part item created by an open
+ // Change Notice shows its method tree on the item master, in sync with the
+ // CO (same makeMethod). Active is still preferred as the default below.
+ const selectable = makeMethods.data ?? [];
+ const makeMethod = requestedMethodId
+ ? (selectable.find((m) => m.id === requestedMethodId) ??
+ selectable.find((m) => m.status === "Active") ??
+ selectable[0])
+ : (selectable.find((m) => m.status === "Active") ?? selectable[0]);
+ if (!makeMethod) return null;
- const tree = await getMethodTree(client, fullMethod.data.id);
- if (tree.error) return null;
+ const fullMethod = await getMakeMethodById(
+ client,
+ makeMethod.id,
+ companyId
+ );
+ if (fullMethod.error || !fullMethod.data) return null;
- const methods =
- tree.data.length > 0 ? flattenTree<Method>(tree.data[0]) : [];
+ const tree = await getMethodTree(client, fullMethod.data.id);
+ if (tree.error) return null;
- return {
- makeMethod: fullMethod.data,
- methods
- };
- }
- );
+ const methods =
+ tree.data.length > 0 ? flattenTree<Method>(tree.data[0]) : [];
+
+ return {
+ makeMethod: fullMethod.data,
+ methods
+ };
+ });
return {
partSummary: partSummary.data,
@@ -152,7 +155,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
files: getItemFiles(client, itemId, companyId),
supplierParts: supplierParts.data ?? [],
pickMethods: pickMethods.data ?? [],
- makeMethods: getMakeMethods(client, itemId, companyId),
+ makeMethods: makeMethodsPromise,
tags: tags.data ?? [],
usedIn: getPartUsedIn(client, itemId, companyId),
methodTree,
diff --git a/apps/erp/app/routes/x+/production+/planning.tsx b/apps/erp/app/routes/x+/production+/planning.tsx
index 82ec98831c..7c334c237c 100644
--- a/apps/erp/app/routes/x+/production+/planning.tsx
+++ b/apps/erp/app/routes/x+/production+/planning.tsx
@@ -9,10 +9,9 @@ import { Outlet, redirect, useLoaderData } from "react-router";
import type { ProductionPlanningItem } from "~/modules/production";
import { getProductionPlanning } from "~/modules/production";
import ProductionPlanningTable from "~/modules/production/ui/Planning/ProductionPlanningTable";
-import { getLocationsList } from "~/modules/resources";
+import { resolveLocationId } from "~/modules/shared/location.server";
import { getOrCreatePeriods } from "~/modules/shared/shared.server";
import { getLocationTimeZone } from "~/modules/shared/timezone.server";
-import { getUserDefaults } from "~/modules/users/users.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";
@@ -37,36 +36,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
const { limit, offset, sorts, filters } =
getGenericQueryFilters(searchParams);
- let locationId = searchParams.get("location");
-
- if (!locationId) {
- const userDefaults = await getUserDefaults(client, userId, companyId);
- if (userDefaults.error) {
- throw redirect(
- path.to.production,
- await flash(
- request,
- error(userDefaults.error, "Failed to load default location")
- )
- );
- }
-
- locationId = userDefaults.data?.locationId ?? null;
- }
-
- if (!locationId) {
- const locations = await getLocationsList(client, companyId);
- if (locations.error || !locations.data?.length) {
- throw redirect(
- path.to.inventory,
- await flash(
- request,
- error(locations.error, "Failed to load any locations")
- )
- );
- }
- locationId = locations.data?.[0].id as string;
- }
+ const locationId = await resolveLocationId(client, request, {
+ searchParams,
+ userId,
+ companyId,
+ onDefaultsError: path.to.production,
+ onNoLocations: path.to.inventory
+ });
const locationToday = datetime.today(
await getLocationTimeZone(client, locationId, companyId)
diff --git a/apps/erp/app/routes/x+/production+/projections.tsx b/apps/erp/app/routes/x+/production+/projections.tsx
index 4df9855f7a..189cf65701 100644
--- a/apps/erp/app/routes/x+/production+/projections.tsx
+++ b/apps/erp/app/routes/x+/production+/projections.tsx
@@ -8,10 +8,9 @@ import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useLoaderData } from "react-router";
import { getProductionProjections } from "~/modules/production";
import DemandProjectionsTable from "~/modules/production/ui/Projection/DemandProjectionTable";
-import { getLocationsList } from "~/modules/resources";
+import { resolveLocationId } from "~/modules/shared/location.server";
import { getOrCreatePeriods } from "~/modules/shared/shared.server";
import { getLocationTimeZone } from "~/modules/shared/timezone.server";
-import { getUserDefaults } from "~/modules/users/users.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";
@@ -36,36 +35,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
const { limit, offset, sorts, filters } =
getGenericQueryFilters(searchParams);
- let locationId = searchParams.get("location");
-
- if (!locationId) {
- const userDefaults = await getUserDefaults(client, userId, companyId);
- if (userDefaults.error) {
- throw redirect(
- path.to.production,
- await flash(
- request,
- error(userDefaults.error, "Failed to load default location")
- )
- );
- }
-
- locationId = userDefaults.data?.locationId ?? null;
- }
-
- if (!locationId) {
- const locations = await getLocationsList(client, companyId);
- if (locations.error || !locations.data?.length) {
- throw redirect(
- path.to.inventory,
- await flash(
- request,
- error(locations.error, "Failed to load any locations")
- )
- );
- }
- locationId = locations.data?.[0].id as string;
- }
+ const locationId = await resolveLocationId(client, request, {
+ searchParams,
+ userId,
+ companyId,
+ onDefaultsError: path.to.production,
+ onNoLocations: path.to.inventory
+ });
const periods = await getOrCreatePeriods(
datetime.today(await getLocationTimeZone(client, locationId, companyId)),
diff --git a/apps/erp/app/routes/x+/purchasing+/planning.tsx b/apps/erp/app/routes/x+/purchasing+/planning.tsx
index 7b6261c76a..a484488002 100644
--- a/apps/erp/app/routes/x+/purchasing+/planning.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/planning.tsx
@@ -9,10 +9,9 @@ import { Outlet, redirect, useLoaderData } from "react-router";
import type { PurchasingPlanningItem } from "~/modules/purchasing";
import { getPurchasingPlanning } from "~/modules/purchasing";
import PurchasingPlanningTable from "~/modules/purchasing/ui/Planning/PurchasingPlanningTable";
-import { getLocationsList } from "~/modules/resources";
+import { resolveLocationId } from "~/modules/shared/location.server";
import { getOrCreatePeriods } from "~/modules/shared/shared.server";
import { getLocationTimeZone } from "~/modules/shared/timezone.server";
-import { getUserDefaults } from "~/modules/users/users.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";
@@ -37,36 +36,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
const { limit, offset, sorts, filters } =
getGenericQueryFilters(searchParams);
- let locationId = searchParams.get("location");
-
- if (!locationId) {
- const userDefaults = await getUserDefaults(client, userId, companyId);
- if (userDefaults.error) {
- throw redirect(
- path.to.inventory,
- await flash(
- request,
- error(userDefaults.error, "Failed to load default location")
- )
- );
- }
-
- locationId = userDefaults.data?.locationId ?? null;
- }
-
- if (!locationId) {
- const locations = await getLocationsList(client, companyId);
- if (locations.error || !locations.data?.length) {
- throw redirect(
- path.to.purchasing,
- await flash(
- request,
- error(locations.error, "Failed to load any locations")
- )
- );
- }
- locationId = locations.data?.[0].id as string;
- }
+ const locationId = await resolveLocationId(client, request, {
+ searchParams,
+ userId,
+ companyId,
+ onDefaultsError: path.to.inventory,
+ onNoLocations: path.to.purchasing
+ });
const locationToday = datetime.today(
await getLocationTimeZone(client, locationId, companyId)
diff --git a/apps/erp/app/routes/x+/schedule+/dates.tsx b/apps/erp/app/routes/x+/schedule+/dates.tsx
index b9373fadf6..4025faa269 100644
--- a/apps/erp/app/routes/x+/schedule+/dates.tsx
+++ b/apps/erp/app/routes/x+/schedule+/dates.tsx
@@ -53,10 +53,9 @@ import type { Column, JobItem } from "~/modules/production/ui/Schedule";
import type { DisplaySettings } from "~/modules/production/ui/Schedule/Kanban";
import { DateKanban } from "~/modules/production/ui/Schedule/Kanban/DateKanban";
import { ScheduleNavigation } from "~/modules/production/ui/Schedule/Kanban/ScheuleNavigation";
-import { getLocationsList } from "~/modules/resources";
import { getTagsList } from "~/modules/shared";
+import { resolveLocationId } from "~/modules/shared/location.server";
import { getLocationTimeZone } from "~/modules/shared/timezone.server";
-import { getUserDefaults } from "~/modules/users/users.server";
import { usePeople } from "~/stores";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -113,36 +112,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
}
- let locationId = searchParams.get("location");
-
- if (!locationId) {
- const userDefaults = await getUserDefaults(client, userId, companyId);
- if (userDefaults.error) {
- throw redirect(
- path.to.production,
- await flash(
- request,
- error(userDefaults.error, "Failed to load default location")
- )
- );
- }
-
- locationId = userDefaults.data?.locationId ?? null;
- }
-
- if (!locationId) {
- const locations = await getLocationsList(client, companyId);
- if (locations.error || !locations.data?.length) {
- throw redirect(
- path.to.production,
- await flash(
- request,
- error(locations.error, "Failed to load any locations")
- )
- );
- }
- locationId = locations.data?.[0].id as string;
- }
+ const locationId = await resolveLocationId(client, request, {
+ searchParams,
+ userId,
+ companyId,
+ onDefaultsError: path.to.production,
+ onNoLocations: path.to.production
+ });
// The board's "today" and its week/month windows belong to the plant being
// scheduled, not the server — resolved after locationId settles.
diff --git a/apps/erp/app/routes/x+/schedule+/operations.tsx b/apps/erp/app/routes/x+/schedule+/operations.tsx
index 236ac4d7cc..ca05b44f27 100644
--- a/apps/erp/app/routes/x+/schedule+/operations.tsx
+++ b/apps/erp/app/routes/x+/schedule+/operations.tsx
@@ -1,6 +1,5 @@
-import { error, useCarbon } from "@carbon/auth";
+import { useCarbon } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
import {
Button,
ClientOnly,
@@ -39,7 +38,7 @@ import {
LuTriangleAlert
} from "react-icons/lu";
import type { LoaderFunctionArgs } from "react-router";
-import { Link, redirect, useLoaderData } from "react-router";
+import { Link, useLoaderData } from "react-router";
import { SearchFilter } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
@@ -57,12 +56,11 @@ import type {
import { Kanban } from "~/modules/production/ui/Schedule/Kanban";
import { ScheduleNavigation } from "~/modules/production/ui/Schedule/Kanban/ScheuleNavigation";
import {
- getLocationsList,
getProcessesList,
getWorkCentersByLocation
} from "~/modules/resources";
import { getTagsList } from "~/modules/shared";
-import { getUserDefaults } from "~/modules/users/users.server";
+import { resolveLocationId } from "~/modules/shared/location.server";
import { usePeople } from "~/stores";
import { makeDurations } from "~/utils/duration";
import type { Handle } from "~/utils/handle";
@@ -128,36 +126,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
}
}
- let locationId = searchParams.get("location");
-
- if (!locationId) {
- const userDefaults = await getUserDefaults(client, userId, companyId);
- if (userDefaults.error) {
- throw redirect(
- path.to.inventory,
- await flash(
- request,
- error(userDefaults.error, "Failed to load default location")
- )
- );
- }
-
- locationId = userDefaults.data?.locationId ?? null;
- }
-
- if (!locationId) {
- const locations = await getLocationsList(client, companyId);
- if (locations.error || !locations.data?.length) {
- throw redirect(
- path.to.inventory,
- await flash(
- request,
- error(locations.error, "Failed to load any locations")
- )
- );
- }
- locationId = locations.data?.[0].id as string;
- }
+ const locationId = await resolveLocationId(client, request, {
+ searchParams,
+ userId,
+ companyId,
+ onDefaultsError: path.to.inventory,
+ onNoLocations: path.to.inventory
+ });
const [workCenters, processes, operations, tags] = await Promise.all([
getWorkCentersByLocation(client, locationId),
diff --git a/apps/erp/app/utils/query.ts b/apps/erp/app/utils/query.ts
index 1490722185..e51530e87b 100644
--- a/apps/erp/app/utils/query.ts
+++ b/apps/erp/app/utils/query.ts
@@ -3,6 +3,28 @@ import type { PostgrestFilterBuilder } from "@supabase/postgrest-js";
import type { GenericSchema } from "@supabase/supabase-js/dist/module/lib/types";
import { getPageOffset, getPageSize } from "./pagination";
+/**
+ * Count mode for the paged list endpoints backed by the big multi-join views
+ * (`parts`, `materials`, `salesOrders`, `purchaseOrders`, the invoice views…).
+ *
+ * PostgREST implements `exact` as `COUNT(*) OVER ()`, which makes Postgres
+ * materialize the entire filtered result set purely to produce a total — so
+ * `.range()` pagination limits what is transferred but not what is computed.
+ *
+ * `estimated` is a hybrid, not a blind guess: PostgREST still returns an exact
+ * count when the planner's estimate is under `max-rows`, and only falls back to
+ * the estimate for result sets far larger than any page a user is reading. The
+ * totals stay accurate at the sizes where being off by a few would be visible.
+ *
+ * These endpoints also pair it with an explicit `*_LIST_COLUMNS` constant rather
+ * than `select("*")`, for the same reason: naming the columns lets Postgres
+ * prune the views' unreferenced computed columns instead of materializing them
+ * per row. Adding a column to one of those tables means adding it to the
+ * constant — `apps/erp/test/list-select-columns.test.ts` fails if an
+ * `accessorKey` is missing, because the CSV export reads accessors untyped.
+ */
+export const LIST_COUNT = "estimated" as const;
+
export type Sort = {
sortBy: string;
sortAsc: boolean;
diff --git a/apps/erp/test/list-select-columns.test.ts b/apps/erp/test/list-select-columns.test.ts
new file mode 100644
index 0000000000..7bfd3e33ed
--- /dev/null
+++ b/apps/erp/test/list-select-columns.test.ts
@@ -0,0 +1,142 @@
+import { readFileSync } from "node:fs";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+/**
+ * The view-backed list endpoints select an explicit column list rather than
+ * `*`, so Postgres can prune the views' unreferenced computed columns.
+ *
+ * TypeScript catches most under-selection, because the narrowed select narrows
+ * the row type. It does NOT catch the CSV export path: `Table/components/
+ * Download.tsx` reads `row[key]` for each column's `accessorKey`, untyped. A
+ * column dropped from the select but still declared as an `accessorKey` would
+ * export as blank with nothing failing.
+ *
+ * This test closes that gap: every accessorKey a list table declares must be a
+ * column its endpoint actually selects.
+ *
+ * Known limitation: it does NOT cover `meta.exportValue` / `exportOnlyColumn`
+ * functions, which read arbitrary row fields rather than a declared accessor
+ * (e.g. PartsTable's `itemName` reads `row.name`). Those are correct today
+ * because the column lists were derived by scanning whole table files, but a
+ * future exportValue reading a dropped column would slip past this. Verify a
+ * CSV export by hand when adding one.
+ */
+
+const ROOT = join(__dirname, "..");
+
+type Target = {
+ label: string;
+ constant: string;
+ service: string;
+ table: string;
+};
+
+const TARGETS: Target[] = [
+ {
+ label: "parts",
+ constant: "PARTS_LIST_COLUMNS",
+ service: "app/modules/items/items.service.ts",
+ table: "app/modules/items/ui/Parts/PartsTable.tsx"
+ },
+ {
+ label: "materials",
+ constant: "MATERIALS_LIST_COLUMNS",
+ service: "app/modules/items/items.service.ts",
+ table: "app/modules/items/ui/Materials/MaterialsTable.tsx"
+ },
+ {
+ label: "tools",
+ constant: "TOOLS_LIST_COLUMNS",
+ service: "app/modules/items/items.service.ts",
+ table: "app/modules/items/ui/Tools/ToolsTable.tsx"
+ },
+ {
+ label: "consumables",
+ constant: "CONSUMABLES_LIST_COLUMNS",
+ service: "app/modules/items/items.service.ts",
+ table: "app/modules/items/ui/Consumables/ConsumablesTable.tsx"
+ },
+ {
+ label: "services",
+ constant: "SERVICES_LIST_COLUMNS",
+ service: "app/modules/items/items.service.ts",
+ table: "app/modules/items/ui/Services/ServicesTable.tsx"
+ },
+ {
+ label: "purchaseOrders",
+ constant: "PURCHASE_ORDERS_LIST_COLUMNS",
+ service: "app/modules/purchasing/purchasing.service.ts",
+ table: "app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx"
+ },
+ {
+ label: "quotes",
+ constant: "QUOTES_LIST_COLUMNS",
+ service: "app/modules/sales/sales.service.ts",
+ table: "app/modules/sales/ui/Quotes/QuotesTable.tsx"
+ },
+ {
+ label: "salesOrders",
+ constant: "SALES_ORDERS_LIST_COLUMNS",
+ service: "app/modules/sales/sales.service.ts",
+ table: "app/modules/sales/ui/SalesOrder/SalesOrdersTable.tsx"
+ },
+ {
+ label: "purchaseInvoices",
+ constant: "PURCHASE_INVOICES_LIST_COLUMNS",
+ service: "app/modules/invoicing/invoicing.service.ts",
+ table: "app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicesTable.tsx"
+ },
+ {
+ label: "salesInvoices",
+ constant: "SALES_INVOICES_LIST_COLUMNS",
+ service: "app/modules/invoicing/invoicing.service.ts",
+ table: "app/modules/invoicing/ui/SalesInvoice/SalesInvoicesTable.tsx"
+ }
+];
+
+function selectedColumns(service: string, constant: string): string[] {
+ const src = readFileSync(join(ROOT, service), "utf8");
+ const match = src.match(
+ new RegExp(`const ${constant} =\\s*\\n?\\s*"([^"]+)" as const;`)
+ );
+ if (!match) throw new Error(`${constant} not found in ${service}`);
+ return match[1].split(",");
+}
+
+function declaredAccessorKeys(table: string): string[] {
+ const src = readFileSync(join(ROOT, table), "utf8");
+ return [...src.matchAll(/accessorKey:\s*"([^"]+)"/g)]
+ .map((m) => m[1])
+ // custom-field columns are keyed `customFields->>{id}` at runtime; the
+ // `customFields` column itself is what has to be selected.
+ .filter((key) => !key.startsWith("customFields->>"));
+}
+
+describe("list endpoints select every column their table exports", () => {
+ it.each(TARGETS)(
+ "$label",
+ ({ constant, service, table }) => {
+ const selected = new Set(selectedColumns(service, constant));
+ const missing = declaredAccessorKeys(table).filter(
+ (key) => !selected.has(key)
+ );
+ expect(
+ missing,
+ `${constant} is missing accessorKey(s) used by ${table}. These render ` +
+ `blank in the CSV export, which nothing else catches.`
+ ).toEqual([]);
+ }
+ );
+
+ it("selects customFields wherever the table renders custom columns", () => {
+ for (const { label, constant, service, table } of TARGETS) {
+ const src = readFileSync(join(ROOT, table), "utf8");
+ if (!src.includes("useCustomColumns")) continue;
+ expect(
+ selectedColumns(service, constant),
+ `${label} renders custom columns but ${constant} omits customFields`
+ ).toContain("customFields");
+ }
+ });
+});
diff --git a/apps/erp/test/resolve-location-id.test.ts b/apps/erp/test/resolve-location-id.test.ts
new file mode 100644
index 0000000000..f9b81304b2
--- /dev/null
+++ b/apps/erp/test/resolve-location-id.test.ts
@@ -0,0 +1,156 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { resolveLocationId } from "~/modules/shared/location.server";
+
+/**
+ * `resolveLocationId` returns the location id that five `bypassRls: true`
+ * screens then filter on with no company predicate of their own
+ * (`get_jobs_by_date_range`, `get_unscheduled_jobs`,
+ * `get_active_job_operations_by_location`, the `workCenters` reads). So the
+ * multi-tenant boundary for those screens is this function: an id it returns
+ * MUST belong to the caller's company.
+ */
+
+const COMPANY = "company_a";
+const OWN_LOCATION = "loc_owned_by_a";
+const FOREIGN_LOCATION = "loc_owned_by_b";
+const DEFAULT_LOCATION = "loc_default_of_a";
+
+/**
+ * Minimal stand-in for the bits of the supabase client this function touches:
+ * `.from("location").select().eq().eq().maybeSingle()` for the scoping probe,
+ * and `.from("userDefaults")…` / `.from("location")…` for the fallbacks.
+ * `location` rows are keyed by (id, companyId), mirroring the composite PK.
+ */
+function makeClient(locations: { id: string; companyId: string }[]) {
+ const calls: string[] = [];
+
+ const client = {
+ calls,
+ from(table: string) {
+ calls.push(table);
+ const filters: Record<string, unknown> = {};
+ const builder: Record<string, unknown> = {
+ select: () => builder,
+ eq: (col: string, val: unknown) => {
+ filters[col] = val;
+ return builder;
+ },
+ order: () => builder,
+ maybeSingle: async () => {
+ const match = locations.find(
+ (l) => l.id === filters.id && l.companyId === filters.companyId
+ );
+ return { data: match ? { id: match.id } : null, error: null };
+ },
+ single: async () => ({
+ data: { locationId: DEFAULT_LOCATION },
+ error: null
+ }),
+ then: undefined
+ };
+ return builder;
+ }
+ };
+
+ return client as unknown as Parameters<typeof resolveLocationId>[0] & {
+ calls: string[];
+ };
+}
+
+function args(searchParams: string) {
+ return {
+ searchParams: new URLSearchParams(searchParams),
+ userId: "user_1",
+ companyId: COMPANY,
+ onDefaultsError: "/x/production",
+ onNoLocations: "/x/production"
+ };
+}
+
+// `~/modules/resources` is a barrel that reaches UI components and so pulls in
+// `@carbon/glossary`, whose `msg` macro is untransformed under vitest (no
+// lingui plugin here). Stub it so this test exercises the server helper only.
+vi.mock("@carbon/glossary", () => ({
+ getDefinitionText: () => "",
+ getEntry: () => undefined,
+ getTermText: () => "",
+ glossaryEntries: [],
+ hasEntry: () => false,
+ listEntries: () => [],
+ lookupEntry: () => undefined,
+ termSlug: () => "",
+ terms: {}
+}));
+
+// The defaults path goes through `getUserDefaults`, which reads a different
+// table via a different shape; stub it so these cases exercise only the
+// scoping decision.
+vi.mock("~/modules/users/users.server", () => ({
+ getUserDefaults: async () => ({
+ data: { locationId: DEFAULT_LOCATION },
+ error: null
+ })
+}));
+
+vi.mock("~/modules/resources", () => ({
+ getLocationsList: async () => ({
+ data: [{ id: DEFAULT_LOCATION }],
+ error: null
+ })
+}));
+
+describe("resolveLocationId company scoping", () => {
+ const request = new Request("https://erp.test/x/schedule/dates");
+
+ it("returns a ?location= that belongs to the caller's company", async () => {
+ const client = makeClient([{ id: OWN_LOCATION, companyId: COMPANY }]);
+
+ const result = await resolveLocationId(
+ client,
+ request,
+ args(`location=${OWN_LOCATION}`)
+ );
+
+ expect(result).toBe(OWN_LOCATION);
+ });
+
+ it("never returns a ?location= belonging to another company", async () => {
+ const client = makeClient([
+ { id: OWN_LOCATION, companyId: COMPANY },
+ { id: FOREIGN_LOCATION, companyId: "company_b" }
+ ]);
+
+ const result = await resolveLocationId(
+ client,
+ request,
+ args(`location=${FOREIGN_LOCATION}`)
+ );
+
+ expect(result).not.toBe(FOREIGN_LOCATION);
+ expect(result).toBe(DEFAULT_LOCATION);
+ });
+
+ it("falls back for a ?location= that does not exist at all", async () => {
+ const client = makeClient([{ id: OWN_LOCATION, companyId: COMPANY }]);
+
+ const result = await resolveLocationId(
+ client,
+ request,
+ args("location=loc_does_not_exist")
+ );
+
+ expect(result).toBe(DEFAULT_LOCATION);
+ });
+
+ it("skips the scoping probe when no ?location= is supplied", async () => {
+ const client = makeClient([{ id: OWN_LOCATION, companyId: COMPANY }]);
+
+ const result = await resolveLocationId(client, request, args(""));
+
+ expect(result).toBe(DEFAULT_LOCATION);
+ // The probe is the only reason this function reads `location` directly;
+ // the absent-param path must not pay for it.
+ expect(client.calls).not.toContain("location");
+ });
+});
diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsx
index 546ec0e681..4746c03349 100644
--- a/apps/mes/app/root.tsx
+++ b/apps/mes/app/root.tsx
@@ -7,7 +7,10 @@ import {
} from "@carbon/auth/middleware/flash.server";
import { validator } from "@carbon/form";
import { LocaleProvider, resolveLanguage } from "@carbon/locale";
-import { requestIdMiddleware } from "@carbon/logger/middleware.server";
+import {
+ requestContextMiddleware,
+ requestIdMiddleware
+} from "@carbon/logger/middleware.server";
import {
OperatingSystemContextProvider,
Toaster,
@@ -46,7 +49,12 @@ import "@carbon/lib/shims";
import type { Route } from "./+types/root";
import { getTheme } from "./services/theme.server";
-export const middleware = [requestIdMiddleware, flashMiddleware];
+export const middleware = [
+ // First: publishes the request context so server code can reach it via ALS.
+ requestContextMiddleware,
+ requestIdMiddleware,
+ flashMiddleware
+];
export const clientMiddleware = [flashClientMiddleware];
export const links: Route.LinksFunction = () => [
diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsx
index c6b19d8bdb..a96cbc64c4 100644
--- a/apps/mes/app/routes/x+/_layout.tsx
+++ b/apps/mes/app/routes/x+/_layout.tsx
@@ -23,7 +23,7 @@ import {
useNProgress
} from "@carbon/react";
import { getStripeCustomerByCompanyId } from "@carbon/stripe/stripe.server";
-import { Edition } from "@carbon/utils";
+import { Edition, isSearchParamOnlyNavigation } from "@carbon/utils";
import posthog from "posthog-js";
import { Suspense } from "react";
import type {
@@ -57,6 +57,8 @@ import { ERP_URL, MES_URL, path } from "~/utils/path";
export const shouldRevalidate: ShouldRevalidateFunction = ({
currentUrl,
+ nextUrl,
+ formMethod,
defaultShouldRevalidate
}) => {
if (
@@ -66,6 +68,18 @@ export const shouldRevalidate: ShouldRevalidateFunction = ({
return true;
}
+ // This loader is the app shell: 9 queries plus an auth round-trip. Without
+ // this it re-ran on every filter, sort and page click, none of which can
+ // change anything it returns.
+ // NOTE: `useRevalidator().revalidate()` — how the realtime hooks refresh —
+ // also looks like a same-pathname GET, so the shell does not re-run for
+ // realtime events either. Leaf loaders still refresh, which is the intent.
+ // Shell data that must react to a realtime change needs an explicit case
+ // above.
+ if (isSearchParamOnlyNavigation({ currentUrl, nextUrl, formMethod })) {
+ return false;
+ }
+
return defaultShouldRevalidate;
};
diff --git a/packages/auth/src/services/auth.server.ts b/packages/auth/src/services/auth.server.ts
index ed056ba395..d9f843efdd 100644
--- a/packages/auth/src/services/auth.server.ts
+++ b/packages/auth/src/services/auth.server.ts
@@ -1,5 +1,8 @@
import type { Database } from "@carbon/database";
import { checkApiKeyRateLimit } from "@carbon/database/ratelimit";
+import { redis } from "@carbon/kv";
+import { getLogger } from "@carbon/logger";
+import { oncePerRequest } from "@carbon/logger/middleware.server";
import { Edition, Plan } from "@carbon/utils";
import type {
AuthSession as SupabaseAuthSession,
@@ -28,6 +31,16 @@ import {
import { getCompaniesForUser } from "./users";
import { getUserClaims } from "./users.server";
+const log = getLogger("auth");
+
+// Each matched loader used to build its own Supabase client for identical
+// credentials; `createClient` is not free and they are interchangeable.
+const carbonForRequest = (accessToken: string) =>
+ oncePerRequest(`carbon:${accessToken}`, () => getCarbon(accessToken));
+
+const serviceRoleForRequest = () =>
+ oncePerRequest("carbon:service-role", () => getCarbonServiceRole());
+
export async function createEmailAuthAccount(
email: string,
password: string,
@@ -312,8 +325,8 @@ export async function requirePermissions(
return {
client:
requiredPermissions.bypassRls && myClaims.role === "employee"
- ? getCarbonServiceRole()
- : getCarbon(accessToken),
+ ? serviceRoleForRequest()
+ : carbonForRequest(accessToken),
companyId,
companyGroupId,
email,
@@ -370,8 +383,8 @@ export async function requirePermissions(
return {
client:
!!requiredPermissions.bypassRls && myClaims.role === "employee"
- ? getCarbonServiceRole()
- : getCarbon(accessToken),
+ ? serviceRoleForRequest()
+ : carbonForRequest(accessToken),
companyId,
companyGroupId,
email,
@@ -484,12 +497,46 @@ export async function refreshAccessToken(
return makeAuthSession(data.session, companyId!, companyGroupId!);
}
+// `requireAuthSession(request, { verify: true })` costs a full GoTrue round-trip
+// on the critical path of every authenticated request, and the ERP/MES shells
+// re-run it on every navigation. 60s takes it off the hot path while bounding
+// how long a revoked account keeps being accepted. (Signing out doesn't revoke
+// an access token either way — a JWT stays valid until it expires — so the
+// window that actually matters here is admin deletion/deactivation.)
+const AUTH_VERIFY_CACHE_TTL_SECONDS = 60;
+
+function getAuthVerifyCacheKey(accessToken: string) {
+ return `auth:verify:${createHash("sha256")
+ .update(accessToken)
+ .digest("hex")}`;
+}
+
export async function verifyAuthSession(authSession: AuthSession) {
+ const cacheKey = getAuthVerifyCacheKey(authSession.accessToken);
+
+ try {
+ if (await redis.get(cacheKey)) return true;
+ } catch (e) {
+ log.error("Failed to read cached auth verification", { error: e });
+ }
+
const authAccount = await getAuthAccountByAccessToken(
authSession.accessToken
);
+ const isValid = Boolean(authAccount);
+
+ // Only positive verdicts are cached. `getAuthAccountByAccessToken` also
+ // returns null on a transient network error, so caching a failure would turn
+ // one blip into a minute of forced logouts.
+ if (isValid) {
+ try {
+ await redis.set(cacheKey, "1", "EX", AUTH_VERIFY_CACHE_TTL_SECONDS);
+ } catch (e) {
+ log.error("Failed to cache auth verification", { error: e });
+ }
+ }
- return Boolean(authAccount);
+ return isValid;
}
export async function signInWithPasskey(
diff --git a/packages/auth/src/services/users.server.ts b/packages/auth/src/services/users.server.ts
index 938d798ef6..3b0320eb21 100644
--- a/packages/auth/src/services/users.server.ts
+++ b/packages/auth/src/services/users.server.ts
@@ -1,6 +1,7 @@
import type { Database, Json } from "@carbon/database";
import { redis } from "@carbon/kv";
import { getLogger } from "@carbon/logger";
+import { oncePerRead } from "@carbon/logger/middleware.server";
import type { SupabaseClient } from "@supabase/supabase-js";
import { getCarbonServiceRole } from "../lib/supabase/client.server";
import type { Permission, Result } from "../types";
@@ -26,7 +27,23 @@ export async function getUserByEmail(email: string) {
.single();
}
-export async function getUserClaims(userId: string, companyId: string) {
+/**
+ * Claims for a user in a company, resolved once per read request.
+ *
+ * Every matched loader that calls `requirePermissions` — plus the app-shell
+ * loaders that call this directly — otherwise repeated the same Redis GET.
+ *
+ * Read-gated deliberately: React Router runs an action and its loader
+ * revalidation in one request, so memoizing here on a mutating request could
+ * let a permission gate pass on claims the action had just revoked.
+ */
+export function getUserClaims(userId: string, companyId: string) {
+ return oncePerRead(`claims:${userId}:${companyId}`, () =>
+ loadUserClaims(userId, companyId)
+ );
+}
+
+async function loadUserClaims(userId: string, companyId: string) {
let claims: {
permissions: Record<string, Permission>;
role: string | null;
diff --git a/packages/database/supabase/migrations/20260806235710_perf-list-query-indexes.sql b/packages/database/supabase/migrations/20260806235710_perf-list-query-indexes.sql
new file mode 100644
index 0000000000..88a5997cc6
--- /dev/null
+++ b/packages/database/supabase/migrations/20260806235710_perf-list-query-indexes.sql
@@ -0,0 +1,122 @@
+-- Performance: index the RLS/join predicates the list screens actually filter
+-- on, drop duplicate indexes, and let the planner hoist the RLS helpers.
+--
+-- Every statement is idempotent (IF NOT EXISTS / IF EXISTS), and every index
+-- added here was verified absent — and every index dropped verified duplicated —
+-- against a live database rather than inferred from the migration history.
+--
+-- NOTE: plain CREATE INDEX takes a SHARE lock, blocking writes to the table
+-- while the index builds. That matches every other index migration in this repo
+-- and is fine for a maintenance window; for a zero-downtime production apply,
+-- split these into CREATE INDEX CONCURRENTLY statements run outside a
+-- transaction.
+
+-- 1. companyId indexes -------------------------------------------------------
+-- Each of these tables has a `companyId` column and a composite PK leading on
+-- `id`, so nothing indexes `companyId` on its own. The standard RLS predicate is
+-- `"companyId" = ANY((SELECT get_companies_with_employee_permission(...)))`,
+-- which means every policy check on these tables falls back to a scan.
+--
+-- Deliberately excluded: `supplierPart` already has one (named
+-- `buyMethod_companyId_idx` — the table was renamed, the index was not).
+
+CREATE INDEX IF NOT EXISTS "itemCost_companyId_idx" ON "itemCost" ("companyId");
+CREATE INDEX IF NOT EXISTS "itemPlanning_companyId_idx" ON "itemPlanning" ("companyId");
+CREATE INDEX IF NOT EXISTS "jobMakeMethod_companyId_idx" ON "jobMakeMethod" ("companyId");
+CREATE INDEX IF NOT EXISTS "jobMaterial_companyId_idx" ON "jobMaterial" ("companyId");
+CREATE INDEX IF NOT EXISTS "jobOperation_companyId_idx" ON "jobOperation" ("companyId");
+CREATE INDEX IF NOT EXISTS "jobOperationDependency_companyId_idx" ON "jobOperationDependency" ("companyId");
+CREATE INDEX IF NOT EXISTS "methodMaterial_companyId_idx" ON "methodMaterial" ("companyId");
+CREATE INDEX IF NOT EXISTS "methodOperation_companyId_idx" ON "methodOperation" ("companyId");
+CREATE INDEX IF NOT EXISTS "purchaseInvoiceLine_companyId_idx" ON "purchaseInvoiceLine" ("companyId");
+CREATE INDEX IF NOT EXISTS "quoteLine_companyId_idx" ON "quoteLine" ("companyId");
+CREATE INDEX IF NOT EXISTS "quoteMakeMethod_companyId_idx" ON "quoteMakeMethod" ("companyId");
+CREATE INDEX IF NOT EXISTS "quoteMaterial_companyId_idx" ON "quoteMaterial" ("companyId");
+CREATE INDEX IF NOT EXISTS "quoteOperation_companyId_idx" ON "quoteOperation" ("companyId");
+CREATE INDEX IF NOT EXISTS "receiptLine_companyId_idx" ON "receiptLine" ("companyId");
+CREATE INDEX IF NOT EXISTS "salesOrderLine_companyId_idx" ON "salesOrderLine" ("companyId");
+CREATE INDEX IF NOT EXISTS "shipmentLine_companyId_idx" ON "shipmentLine" ("companyId");
+
+-- 2. itemId join keys --------------------------------------------------------
+-- The `salesOrders` and `quotes` list views join their line tables to `item`;
+-- neither line table indexes `itemId`.
+
+CREATE INDEX IF NOT EXISTS "salesOrderLine_itemId_idx" ON "salesOrderLine" ("itemId");
+CREATE INDEX IF NOT EXISTS "quoteLine_itemId_idx" ON "quoteLine" ("itemId");
+
+-- 3. MES active-operations filter -------------------------------------------
+-- `apps/mes/app/services/operations.service.ts` filters job by exactly
+-- (companyId, status, locationId). Today that can use `idx_job_companyId` or
+-- `idx_job_status_location`, but not one index covering all three.
+
+CREATE INDEX IF NOT EXISTS "job_companyId_status_locationId_idx" ON "job" ("companyId", "status", "locationId");
+
+-- 4. Duplicate indexes -------------------------------------------------------
+-- Byte-identical index definitions created twice under different naming
+-- conventions. They cost write amplification and buy no reads. Keeping the
+-- `"<table>_<column>_idx"` form in each pair.
+
+DROP INDEX IF EXISTS "idx_job_sales_order_line_id";
+DROP INDEX IF EXISTS "idx_jobMakeMethod_jobId";
+DROP INDEX IF EXISTS "idx_jobMakeMethod_parentMaterialId";
+DROP INDEX IF EXISTS "idx_jobOperation_jobMakeMethodId";
+DROP INDEX IF EXISTS "idx_quoteMakeMethod_parentMaterialId";
+DROP INDEX IF EXISTS "idx_quoteMakeMethod_quoteId";
+DROP INDEX IF EXISTS "idx_quoteMakeMethod_quoteLineId";
+DROP INDEX IF EXISTS "idx_quoteOperation_quoteMakeMethodId";
+
+-- 5. RLS helper volatility ---------------------------------------------------
+-- All of these are declared `LANGUAGE plpgsql SECURITY DEFINER` with no
+-- volatility marker, so Postgres assumes VOLATILE and re-evaluates them per row
+-- — even where the argument is constant for the whole query. None of them write,
+-- so STABLE is the correct marker and lets the planner hoist the uncorrelated
+-- calls into an InitPlan evaluated once.
+--
+-- ALTER FUNCTION rather than CREATE OR REPLACE: the bodies are unchanged, so
+-- there is nothing here to drift from the definitions in earlier migrations.
+--
+-- The deprecated per-company permission helper is deliberately NOT altered
+-- here: the `no-legacy-rls` conformance check matches its bare name anywhere in
+-- a migration, so naming it — even only to set its volatility — trips the gate.
+-- It should get the same treatment as part of migrating the 32 tables still on
+-- that helper over to the uncorrelated pattern, which retires it outright.
+
+ALTER FUNCTION public.get_claims(text, text) STABLE;
+ALTER FUNCTION public.get_companies_with_employee_permission(text) STABLE;
+ALTER FUNCTION public.get_companies_with_employee_role() STABLE;
+ALTER FUNCTION public.get_company_id_from_foreign_key(text, text) STABLE;
+ALTER FUNCTION public.get_permission_companies(text) STABLE;
+ALTER FUNCTION public.has_any_company_permission(text) STABLE;
+ALTER FUNCTION public.has_role(text, text) STABLE;
+
+-- Sort-supporting indexes for the two order lists.
+--
+-- These are what let the LATERAL rewrite in 20260807011742 work at all. Each
+-- list has a fixed default sort, and without an index that already supplies it
+-- Postgres must sort every order the caller can see before applying LIMIT 100 --
+-- which means the lateral aggregate runs once per order in the company rather
+-- than once per row on the page. With the index the sort is index-ordered, the
+-- limit is pushed below the join, and the aggregate runs ~100 times.
+--
+-- salesOrders page 1: 223 ms -> 2.8 ms. purchaseOrders page 1: 61 ms -> 4.5 ms.
+--
+-- Column order matters: companyId first (the equality predicate), then the sort
+-- key in the direction the list actually uses.
+CREATE INDEX IF NOT EXISTS "salesOrder_companyId_createdAt_idx"
+ ON "salesOrder" ("companyId", "createdAt" DESC);
+
+CREATE INDEX IF NOT EXISTS "purchaseOrder_companyId_purchaseOrderId_idx"
+ ON "purchaseOrder" ("companyId", "purchaseOrderId" DESC);
+
+-- Same treatment for the jobs list: `job` has separate "companyId" and "jobId"
+-- indexes but no composite, so the list's default sort could not be served from
+-- an index within the company. Measured on 100k jobs, page 1 with the real
+-- ORDER BY "jobId" DESC: 432 ms -> 281 ms once the count is estimated rather
+-- than exact.
+--
+-- This does NOT make the jobs list O(page) the way it did for the order lists:
+-- the `jobs` view builds a `job_model` CTE that scans every job, so the plan
+-- still materializes all rows before the limit. Getting past that needs the
+-- view restructured, which is deliberately not in this PR.
+CREATE INDEX IF NOT EXISTS "job_companyId_jobId_idx"
+ ON "job" ("companyId", "jobId" DESC);
diff --git a/packages/database/supabase/migrations/20260807011742_lateralize-order-list-views.sql b/packages/database/supabase/migrations/20260807011742_lateralize-order-list-views.sql
new file mode 100644
index 0000000000..52410c88b0
--- /dev/null
+++ b/packages/database/supabase/migrations/20260807011742_lateralize-order-list-views.sql
@@ -0,0 +1,224 @@
+-- Make the order list views parameterizable with LATERAL.
+--
+-- Both views rolled their line aggregates up through
+-- LEFT JOIN (SELECT ... GROUP BY "<order>Id") x ON x."<order>Id" = o.id
+-- A subquery RTE with GROUP BY cannot be parameterized -- only LATERAL can --
+-- so the aggregate was computed for every order the caller can see, then hash
+-- joined down to the 100 rows the page asked for. Rewritten as
+-- LEFT JOIN LATERAL ... ON true, correlated on the order id, the aggregate is
+-- evaluated per qualifying order instead.
+--
+-- This is only correct as a performance change in combination with TWO other
+-- pieces in this PR. Alone it is catastrophic, and the intermediate states are
+-- worth recording so nobody lands a partial version:
+--
+-- LATERAL alone 41,648 ms
+-- LATERAL + sort index only 401 ms
+-- LATERAL + index-friendly item RLS only 215 ms
+-- LATERAL + both (shipped) 2.8 ms
+-- the bulk form this replaces 223 ms
+--
+-- 1. `item`'s SELECT policy must be index-able (20260807093015). The lateral
+-- body reads `item` for `thumbnailPath`/`itemType`; while that policy was
+-- an un-indexable OR, every invocation seq-scanned all of `item`.
+-- 2. An index must supply the list's default sort order (20260806235710:
+-- salesOrder(companyId, createdAt DESC), purchaseOrder(companyId,
+-- purchaseOrderId DESC)). Without one, Postgres must sort every row before
+-- applying LIMIT, so the lateral runs once per order in the company
+-- instead of once per row on the page. This is the trap the original
+-- benchmark for this migration fell into: measured without an ORDER BY,
+-- the limit is pushed below the join and the lateral looks like a 9x win
+-- (10.6 ms vs 91.3 ms) -- but the endpoints always sort, and with the sort
+-- and no index it is a 200x loss.
+--
+-- All timings: as `authenticated` with RLS enforced, claims held for the whole
+-- transaction, statistics present (ANALYZE run -- the seeded tables had never
+-- been analyzed, which on its own made plan choice unstable), production
+-- projection and real ORDER BY, 10k orders / 40k lines / 40k items.
+--
+-- Semantics preserved: an aggregate with no GROUP BY over an empty set returns
+-- a single all-NULL row, exactly what the LEFT JOIN miss produced before.
+-- Verified output-identical against the definitions these replace, two ways:
+-- a bidirectional EXCEPT ALL over every row cast to text (multiset-aware, and
+-- it names the differing rows rather than just flagging a mismatch) returned 0
+-- rows in both directions for both views with identical row counts; and md5
+-- over every column of all 10,000 rows matched:
+-- salesOrders 10000|ff11e3974f94976976d81b396966f8e2
+-- purchaseOrders 10000|a649b4cd7477e1a9d8c6e5629f910bc0
+--
+-- jobs/lines get an explicit ORDER BY inside array_agg. Element order was
+-- previously unspecified (it only looked stable because the plan was), so
+-- pinning it both makes this migration byte-identical in output and stops the
+-- UI ordering from depending on the query plan.
+
+CREATE OR REPLACE VIEW "salesOrders" WITH (security_invoker = true) AS
+ SELECT s.id,
+ s."salesOrderId",
+ s."revisionId",
+ s.status,
+ s."orderDate",
+ s."currencyCode",
+ s."customerId",
+ s."customerLocationId",
+ s."customerContactId",
+ s."customerReference",
+ s.assignee,
+ s."companyId",
+ s."closedAt",
+ s."closedBy",
+ s."customFields",
+ s."createdAt",
+ s."createdBy",
+ s."updatedAt",
+ s."updatedBy",
+ s."locationId",
+ s."exchangeRate",
+ s."exchangeRateUpdatedAt",
+ s."externalNotes",
+ s."internalNotes",
+ s."salesPersonId",
+ s."sentCompleteDate",
+ s."opportunityId",
+ s."completedDate",
+ s."customerEngineeringContactId",
+ CASE
+ WHEN (s.status <> ALL (ARRAY['Closed'::"salesOrderStatus", 'Cancelled'::"salesOrderStatus"])) AND (EXISTS ( SELECT 1
+ FROM "salesOrderLine" sol
+ WHERE sol."salesOrderId" = s.id AND sol."methodType" = 'Make to Order'::"methodType" AND COALESCE(( SELECT sum(j."quantityComplete") AS sum
+ FROM job j
+ WHERE j."salesOrderLineId" = sol.id AND j."salesOrderId" = sol."salesOrderId"), 0::numeric) < sol."saleQuantity")) THEN 'In Progress'::"salesOrderStatus"
+ ELSE s.status
+ END AS "displayStatus",
+ sl."thumbnailPath",
+ sl."itemType",
+ sl."orderTotal" + COALESCE(ss."shippingCost", 0::numeric) AS "orderTotal",
+ sl.jobs,
+ sl.lines,
+ st.name AS "shippingTermName",
+ sp."paymentTermId",
+ ss."shippingMethodId",
+ ss."receiptRequestedDate",
+ ss."receiptPromisedDate",
+ ss."dropShipment",
+ ss."shippingCost",
+ ss.incoterm,
+ ss."incotermLocation",
+ ( SELECT COALESCE(jsonb_object_agg(eim.integration,
+ CASE
+ WHEN eim.metadata IS NOT NULL THEN eim.metadata
+ ELSE to_jsonb(eim."externalId")
+ END) FILTER (WHERE eim."externalId" IS NOT NULL OR eim.metadata IS NOT NULL), '{}'::jsonb) AS "coalesce"
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'salesOrder'::text AND eim."entityId" = s.id) AS "externalId"
+ FROM "salesOrder" s
+ LEFT JOIN LATERAL ( SELECT
+ min(
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ sum(DISTINCT (1::numeric + COALESCE(sol."taxPercent", 0::numeric)) * (COALESCE(sol."saleQuantity", 0::numeric) * COALESCE(sol."unitPrice", 0::numeric) + COALESCE(sol."shippingCost", 0::numeric) + COALESCE(sol."addOnCost", 0::numeric)) + COALESCE(sol."nonTaxableAddOnCost", 0::numeric)) AS "orderTotal",
+ min(i.type) AS "itemType",
+ array_agg(
+ CASE
+ WHEN j.id IS NOT NULL THEN json_build_object('id', j.id, 'jobId', j."jobId", 'status', j.status, 'dueDate', j."dueDate", 'productionQuantity', j."productionQuantity", 'quantityComplete', j."quantityComplete", 'quantityShipped', j."quantityShipped", 'quantity', j.quantity, 'scrapQuantity', j."scrapQuantity", 'salesOrderLineId', sol.id, 'assignee', j.assignee)
+ ELSE NULL::json
+ END ORDER BY sol.id, j.id) FILTER (WHERE j.id IS NOT NULL) AS jobs,
+ array_agg(json_build_object('id', sol.id, 'methodType', sol."methodType", 'saleQuantity', sol."saleQuantity") ORDER BY sol.id) AS lines
+ FROM "salesOrderLine" sol
+ LEFT JOIN item i ON i.id = sol."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN job j ON j."salesOrderId" = sol."salesOrderId" AND j."salesOrderLineId" = sol.id
+ WHERE sol."salesOrderId" = s.id) sl ON true
+ LEFT JOIN "salesOrderShipment" ss ON ss.id = s.id
+ LEFT JOIN "shippingTerm" st ON st.id = ss."shippingTermId"
+ LEFT JOIN "salesOrderPayment" sp ON sp.id = s.id;
+
+CREATE OR REPLACE VIEW "purchaseOrders" WITH (security_invoker = true) AS
+ SELECT p.id,
+ p."purchaseOrderId",
+ p."revisionId",
+ p.status,
+ p."orderDate",
+ p."supplierId",
+ p."supplierLocationId",
+ p."supplierContactId",
+ p."supplierReference",
+ p.assignee,
+ p."companyId",
+ p."closedAt",
+ p."closedBy",
+ p."customFields",
+ p."createdAt",
+ p."createdBy",
+ p."updatedAt",
+ p."updatedBy",
+ p."currencyCode",
+ p."exchangeRate",
+ p."exchangeRateUpdatedAt",
+ p.tags,
+ p."internalNotes",
+ p."externalNotes",
+ p."supplierInteractionId",
+ p."purchaseOrderType",
+ p."jobId",
+ p."jobReadableId",
+ pl."thumbnailPath",
+ pl."itemType",
+ pl."orderTotal" + pd."supplierShippingCost" /
+ CASE
+ WHEN p."exchangeRate" = 0::numeric THEN 1::numeric
+ ELSE p."exchangeRate"
+ END AS "orderTotal",
+ COALESCE(pl."receivableQuantity", 0::numeric) AS "receivableQuantity",
+ COALESCE(pl."receivedQuantity", 0::numeric) AS "receivedQuantity",
+ pd."shippingMethodId",
+ pd."shippingTermId",
+ pd."receiptRequestedDate",
+ pd."receiptPromisedDate",
+ pd."deliveryDate",
+ pd."dropShipment",
+ pp."paymentTermId",
+ pd."locationId",
+ pd."supplierShippingCost",
+ pd.incoterm,
+ pd."incotermLocation",
+ u."fullName" AS "createdByFullName",
+ u.email AS "createdByEmail",
+ u.phone AS "createdByPhone",
+ ua."fullName" AS "assigneeFullName",
+ ua.email AS "assigneeEmail",
+ ua.phone AS "assigneePhone",
+ uam."fullName" AS "accountManagerFullName",
+ uam.email AS "accountManagerEmail",
+ uam.phone AS "accountManagerPhone"
+ FROM "purchaseOrder" p
+ LEFT JOIN LATERAL ( SELECT
+ min(
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ sum(COALESCE(pol."purchaseQuantity", 0::numeric) * COALESCE(pol."unitPrice", 0::numeric) + COALESCE(pol."shippingCost", 0::numeric) + COALESCE(pol."taxAmount", 0::numeric)) AS "orderTotal",
+ sum(
+ CASE
+ WHEN pol."purchaseOrderLineType" <> ALL (ARRAY['Comment'::"purchaseOrderLineType", 'G/L Account'::"purchaseOrderLineType"]) THEN COALESCE(pol."purchaseQuantity", 0::numeric)
+ ELSE 0::numeric
+ END) AS "receivableQuantity",
+ sum(
+ CASE
+ WHEN pol."purchaseOrderLineType" <> ALL (ARRAY['Comment'::"purchaseOrderLineType", 'G/L Account'::"purchaseOrderLineType"]) THEN COALESCE(pol."quantityReceived", 0::numeric)
+ ELSE 0::numeric
+ END) AS "receivedQuantity",
+ min(i.type) AS "itemType"
+ FROM "purchaseOrderLine" pol
+ LEFT JOIN item i ON i.id = pol."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ WHERE pol."purchaseOrderId" = p.id) pl ON true
+ LEFT JOIN "purchaseOrderDelivery" pd ON pd.id = p.id
+ LEFT JOIN "shippingTerm" st ON st.id = pd."shippingTermId"
+ LEFT JOIN "purchaseOrderPayment" pp ON pp.id = p.id
+ LEFT JOIN "user" u ON u.id = p."createdBy"
+ LEFT JOIN "user" ua ON ua.id = p.assignee
+ LEFT JOIN supplier s ON s.id = p."supplierId"
+ LEFT JOIN "user" uam ON uam.id = s."accountManagerId";
diff --git a/packages/database/supabase/migrations/20260807093015_item-rls-index-friendly.sql b/packages/database/supabase/migrations/20260807093015_item-rls-index-friendly.sql
new file mode 100644
index 0000000000..57fef2b20b
--- /dev/null
+++ b/packages/database/supabase/migrations/20260807093015_item-rls-index-friendly.sql
@@ -0,0 +1,66 @@
+-- Make `item`'s SELECT policy index-friendly.
+--
+-- The policy is an OR of three branches. The first is already index-able
+-- (`"companyId" = ANY (array)`), but the two portal branches were written as
+-- `id IN (SELECT ...)`, which Postgres compiles to a hashed SubPlan. A SubPlan
+-- is not an index path, and a BitmapOr requires EVERY branch to have one, so a
+-- single non-indexable branch demotes the whole predicate to a filter and the
+-- planner can only reach `item` by sequential scan.
+--
+-- That is survivable when `item` is scanned once. It is not survivable when
+-- `item` is reached once per outer row: the salesOrders list view produced
+-- Seq Scan on item (rows=40000, loops=10000)
+-- — 400M row visits, 43s for one page of 100 orders.
+--
+-- Rewritten so all three branches are index-able. An uncorrelated `array_agg`
+-- is evaluated once as an InitPlan, and `id = ANY (array)` is a
+-- ScalarArrayOpExpr, which CAN use item_pkey. The plan flips from
+-- Seq Scan on item (rows=40000, loops=10000) 43,454 ms
+-- to
+-- Index Scan using item_pkey (rows=1, loops=40000) 219 ms
+--
+-- COALESCE(..., '{}') matters: array_agg over zero rows returns NULL, and
+-- `id = ANY (NULL)` is NULL rather than false. Both NULL and false mean "not
+-- visible" inside a USING clause, but the COALESCE keeps the intent explicit.
+--
+-- Semantics are UNCHANGED, including two pre-existing quirks this deliberately
+-- preserves rather than fixes (they belong in their own security-reviewed
+-- change): `supplierPart`'s own SELECT policy is employee-gated, so branch 2 is
+-- unreachable for a real portal user; and both `get_*_ids_with_*_permission`
+-- helpers overwrite their first `SELECT ... INTO` with a second, so the
+-- permission path is discarded. This migration calls the same helpers and so
+-- inherits the same behaviour exactly.
+--
+-- Equivalence verified against four synthesised personas in one rolled-back
+-- transaction, comparing the md5 of the sorted visible id set (not just the
+-- count), with both portal branches made reachable by a temporary permissive
+-- policy so the branches were actually exercised:
+--
+-- persona old policy new policy
+-- employee 40000 8ff8d9fbadfe 40000 8ff8d9fbadfe same
+-- supplier 400 ddd8d332865b 400 ddd8d332865b same
+-- customer 7 3b0780d09b4e 7 3b0780d09b4e same
+-- no access 0 d41d8cd98f00 0 d41d8cd98f00 same
+
+DROP POLICY "SELECT" ON "public"."item";
+
+CREATE POLICY "SELECT" ON "public"."item"
+FOR SELECT USING (
+ "companyId" = ANY ((SELECT get_companies_with_employee_role())::text[])
+ OR id = ANY (COALESCE((
+ SELECT array_agg(sp."itemId")
+ FROM "supplierPart" sp
+ WHERE sp."supplierId" = ANY (
+ (SELECT get_supplier_ids_with_supplier_permission('parts_view'))::text[]
+ )
+ AND sp."itemId" IS NOT NULL
+ ), '{}'::text[]))
+ OR id = ANY (COALESCE((
+ SELECT array_agg(cpi."itemId")
+ FROM "customerPartToItem" cpi
+ WHERE cpi."customerId" = ANY (
+ (SELECT get_customer_ids_with_customer_permission('parts_view'))::text[]
+ )
+ AND cpi."itemId" IS NOT NULL
+ ), '{}'::text[]))
+);
diff --git a/packages/logger/AGENTS.md b/packages/logger/AGENTS.md
index de19500250..7f2489cd2d 100644
--- a/packages/logger/AGENTS.md
+++ b/packages/logger/AGENTS.md
@@ -21,9 +21,16 @@ categories, env-driven levels, and cloud-agnostic request-id correlation.
overrides the default (dev `debug`, server prod `info`, browser prod
`warning`).
- Request id is automatic inside loaders/actions/services: `requestIdMiddleware`
- (registered first in each app's `root.tsx`) puts `{ requestId }` into implicit
- context, so every server log during a request carries it. Read it explicitly
- with `getRequestId(context)` from `@carbon/logger/middleware.server`.
+ puts `{ requestId }` into implicit context, so every server log during a
+ request carries it. Read it with `getRequestId(context)` from
+ `@carbon/logger/middleware.server`, or `getRequestId()` with no argument from
+ a plain service function (resolved via `requestContextMiddleware`'s scope).
+- Request-scoped memoization: `oncePerRequest(key, fn)` computes once per HTTP
+ request; `oncePerRead(key, fn)` does the same but ONLY on GET/HEAD/OPTIONS.
+ Use `oncePerRead` for anything derived from database state — React Router runs
+ an action and its loader revalidation in one request, so a plain memo there
+ would serve pre-write data. `oncePerRequest` is for values that are not
+ database state (e.g. a Supabase client).
- Request-body logging is **debug-only** and guarded: `requestIdMiddleware`
captures the body onto the access-log record's `body` prop **only** when
`LOG_LEVEL=debug` (skipped entirely at the prod `info` default — no clone, no
@@ -69,15 +76,16 @@ pnpm --filter @carbon/logger test
| `.` | `getLogger`, `LOG_LEVELS`, `parseLogLevel`, `CarbonLogLevel`, `Logger` type — isomorphic, safe everywhere |
| `./config.server` | `ensureLoggingConfigured()` (ANSI dev / JSONL+redacted prod, ALS) |
| `./config.client` | `ensureLoggingConfigured()` (plain console sink, no ALS) |
-| `./middleware.server` | `requestIdMiddleware`, `requestIdContext`, `getRequestId`, `REQUEST_ID_HEADER` |
+| `./middleware.server` | `requestIdMiddleware`, `requestIdContext`, `getRequestId`, `REQUEST_ID_HEADER`, plus the request-context API re-exported from `context.server`: `requestContextMiddleware`, `getRouterContext`, `getRequestContext`, `oncePerRequest`, `oncePerRead` |
| `./inngest` | `createInngestLogger()` — adapter passed to `new Inngest({ logger })` |
## Wiring (per app)
- `entry.server.tsx`: `import { ensureLoggingConfigured } from "@carbon/logger/config.server"; ensureLoggingConfigured();` at top.
- `entry.client.tsx`: same from `@carbon/logger/config.client`.
-- `root.tsx`: `export const middleware = [requestIdMiddleware, flashMiddleware]`
- (request id FIRST so downstream runs inside its context scope).
+- `root.tsx`: `export const middleware = [requestContextMiddleware, requestIdMiddleware, flashMiddleware]`
+ (request context FIRST so every downstream middleware and handler runs inside
+ the AsyncLocalStorage scope, then request id so downstream logs carry it).
## Cross-References
diff --git a/packages/logger/src/context.server.test.ts b/packages/logger/src/context.server.test.ts
new file mode 100644
index 0000000000..161780bf64
--- /dev/null
+++ b/packages/logger/src/context.server.test.ts
@@ -0,0 +1,191 @@
+import { createContext, RouterContextProvider } from "react-router";
+import { describe, expect, it } from "vitest";
+import {
+ getRequestContext,
+ getRouterContext,
+ oncePerRead,
+ oncePerRequest,
+ requestMemoSize,
+ runInRequestContext
+} from "./context.server";
+
+const provider = () => new RouterContextProvider();
+
+describe("request context", () => {
+ it("exposes the router context inside a scope and nothing outside", () => {
+ const p = provider();
+ expect(getRouterContext()).toBeUndefined();
+ runInRequestContext(p, () => {
+ expect(getRouterContext()).toBe(p);
+ });
+ expect(getRouterContext()).toBeUndefined();
+ });
+
+ it("reads a createContext value set by middleware, without threading it", () => {
+ const idContext = createContext<string | null>(null);
+ const p = provider();
+ p.set(idContext, "req_123");
+
+ // A "service function" deep in the call tree, taking no context argument.
+ const service = () => getRequestContext(idContext);
+
+ expect(runInRequestContext(p, service)).toBe("req_123");
+ expect(service()).toBeUndefined(); // outside a request
+ });
+});
+
+describe("oncePerRequest", () => {
+ it("computes once per key within a request", () => {
+ let calls = 0;
+ const compute = () => ({ id: ++calls });
+
+ const [a, b, c] = runInRequestContext(provider(), () => [
+ oncePerRequest("claims:u1:c1", compute),
+ oncePerRequest("claims:u1:c1", compute),
+ oncePerRequest("claims:u1:c1", compute)
+ ]);
+
+ expect(calls).toBe(1);
+ expect(b).toBe(a);
+ expect(c).toBe(a);
+ });
+
+ // The safety property: separate requests never observe each other's values.
+ it("never shares a value between requests, even for the same key", () => {
+ const a = runInRequestContext(provider(), () =>
+ oncePerRequest("claims:u1:c1", () => "TENANT_A")
+ );
+ const b = runInRequestContext(provider(), () =>
+ oncePerRequest("claims:u1:c1", () => "TENANT_B")
+ );
+ expect(a).toBe("TENANT_A");
+ expect(b).toBe("TENANT_B");
+ });
+
+ // ALS is the point: loaders are independent async branches of one request.
+ it("propagates across awaits and concurrent branches", async () => {
+ let calls = 0;
+ const lookup = () =>
+ new Promise<string>((resolve) => {
+ calls++;
+ setTimeout(() => resolve("claims"), 5);
+ });
+
+ const results = await runInRequestContext(provider(), async () => {
+ await new Promise((r) => setTimeout(r, 1));
+ return Promise.all([
+ oncePerRequest("claims", lookup),
+ oncePerRequest("claims", lookup),
+ (async () => {
+ await new Promise((r) => setTimeout(r, 2));
+ return oncePerRequest("claims", lookup);
+ })()
+ ]);
+ });
+
+ expect(calls).toBe(1);
+ expect(results).toEqual(["claims", "claims", "claims"]);
+ });
+
+ it("keeps concurrent requests isolated", async () => {
+ const run = (tenant: string, delay: number) =>
+ runInRequestContext(provider(), async () => {
+ await new Promise((r) => setTimeout(r, delay));
+ return oncePerRequest("claims", () => tenant);
+ });
+
+ expect(await Promise.all([run("A", 3), run("B", 1), run("C", 2)])).toEqual([
+ "A",
+ "B",
+ "C"
+ ]);
+ });
+
+ it("keys distinct values separately", () => {
+ const size = runInRequestContext(provider(), () => {
+ oncePerRequest("claims:u1:c1", () => 1);
+ oncePerRequest("claims:u1:c2", () => 2);
+ oncePerRequest("carbon:tokenA", () => 3);
+ expect(oncePerRequest("claims:u1:c2", () => 99)).toBe(2);
+ return requestMemoSize();
+ });
+ expect(size).toBe(3);
+ });
+
+ it("memoizes a falsy value rather than recomputing", () => {
+ let calls = 0;
+ runInRequestContext(provider(), () => {
+ oncePerRequest("k", () => {
+ calls++;
+ return null;
+ });
+ oncePerRequest("k", () => {
+ calls++;
+ return null;
+ });
+ });
+ expect(calls).toBe(1);
+ });
+
+ // Inngest jobs, edge functions and tests run with no middleware around them.
+ it("falls back to computing every time outside a request", () => {
+ let calls = 0;
+ const compute = () => ++calls;
+ expect(oncePerRequest("k", compute)).toBe(1);
+ expect(oncePerRequest("k", compute)).toBe(2);
+ expect(requestMemoSize()).toBe(0);
+ });
+});
+
+describe("oncePerRead", () => {
+ it("memoizes on a read-only request", () => {
+ let calls = 0;
+ const compute = () => ++calls;
+ runInRequestContext(provider(), () => {
+ oncePerRead("claims:u1:c1", compute);
+ oncePerRead("claims:u1:c1", compute);
+ });
+ expect(calls).toBe(1);
+ });
+
+ // Why this helper exists. React Router runs an action and the loader
+ // revalidation that follows it in ONE request. Memoizing database state there
+ // would hand the revalidating loaders pre-write data — for permission claims
+ // that means a gate passing on permissions the action just revoked.
+ it("does NOT memoize on a mutating request", () => {
+ let claims = "can:delete";
+ const seen: string[] = [];
+ runInRequestContext(
+ provider(),
+ () => {
+ seen.push(oncePerRead("claims:u1:c1", () => claims)); // action reads
+ claims = "revoked"; // action writes + invalidates the redis key
+ seen.push(oncePerRead("claims:u1:c1", () => claims)); // loaders revalidate
+ },
+ { isRead: false }
+ );
+ expect(seen).toEqual(["can:delete", "revoked"]);
+ });
+
+ it("is a pass-through outside any request scope", () => {
+ let calls = 0;
+ const compute = () => ++calls;
+ expect(oncePerRead("k", compute)).toBe(1);
+ expect(oncePerRead("k", compute)).toBe(2);
+ });
+
+ // The client memo is intentionally NOT read-gated: a Supabase client is
+ // interchangeable regardless of what the request does.
+ it("oncePerRequest still memoizes on a mutating request", () => {
+ let calls = 0;
+ runInRequestContext(
+ provider(),
+ () => {
+ oncePerRequest("carbon:token", () => ++calls);
+ oncePerRequest("carbon:token", () => ++calls);
+ },
+ { isRead: false }
+ );
+ expect(calls).toBe(1);
+ });
+});
diff --git a/packages/logger/src/context.server.ts b/packages/logger/src/context.server.ts
new file mode 100644
index 0000000000..044e0256e9
--- /dev/null
+++ b/packages/logger/src/context.server.ts
@@ -0,0 +1,133 @@
+import { AsyncLocalStorage } from "node:async_hooks";
+import {
+ createContext,
+ type MiddlewareFunction,
+ type RouterContext,
+ type RouterContextProvider
+} from "react-router";
+
+/**
+ * Makes React Router's per-request `context` readable from anywhere on the
+ * server, without threading it through every function signature.
+ *
+ * React Router already gives each request a `RouterContextProvider` and hands it
+ * to middleware, loaders and actions. What it does not give you is a way to read
+ * it from a plain service function — so anything that wants request-scoped state
+ * (`requirePermissions`, a logger, a DB client) has to take `context` as an
+ * argument, which for an existing codebase means touching every call site.
+ *
+ * Storing the provider itself in an AsyncLocalStorage closes that gap: ALS
+ * propagates through the async call tree, so every loader running inside
+ * `next()` — and everything they call — can reach the same provider. The values
+ * still live in React Router's own typed `createContext` slots; ALS only
+ * provides the access path.
+ *
+ * Safety: the provider is per-request and ALS gives each concurrent request its
+ * own store, so one request can never observe another's values. Outside a
+ * request (Inngest jobs, edge functions, tests) `getRouterContext()` is
+ * undefined and callers fall back to computing directly.
+ *
+ * A WeakMap keyed on the `Request` does NOT work as a substitute: React Router
+ * does not hand the same Request instance to every matched loader, so such a
+ * memo never hits (measured — no change in per-request claim lookups).
+ */
+// Middleware hands `context` as Readonly<…>; its get/set methods stay callable.
+type RequestContext = Readonly<RouterContextProvider>;
+
+const storage = new AsyncLocalStorage<RequestContext>();
+
+/**
+ * Publishes the request's context provider to `getRouterContext()`.
+ *
+ * Register FIRST in an app's root `middleware` array, so every downstream
+ * middleware and handler runs inside the scope.
+ */
+export const requestContextMiddleware: MiddlewareFunction<Response> = (
+ { context, request },
+ next
+) => {
+ context.set(isReadRequestContext, READ_METHODS.has(request.method));
+ return storage.run(context, () => next());
+};
+
+const READ_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
+
+/** Whether this request only reads — see `oncePerRead`. */
+const isReadRequestContext = createContext<boolean>(false);
+
+/** The current request's context provider, or undefined outside a request. */
+export function getRouterContext(): RequestContext | undefined {
+ return storage.getStore();
+}
+
+/**
+ * Read a `createContext` value for the current request from anywhere.
+ * Returns `undefined` outside a request scope.
+ */
+export function getRequestContext<T>(context: RouterContext<T>): T | undefined {
+ return storage.getStore()?.get(context);
+}
+
+/** Backing store for `oncePerRequest`, kept in the router context itself. */
+const memoContext = createContext<Map<string, unknown> | null>(null);
+
+/**
+ * Compute a value at most once per request.
+ *
+ * Every matched route resolves the same request-scoped values independently — a
+ * detail page's five loaders each looked up the same permission claims and built
+ * their own Supabase client. Keyed memoization collapses that to one.
+ *
+ * Promises are cached as promises (not awaited results) so concurrent loaders
+ * share a single in-flight lookup rather than racing to populate the entry.
+ *
+ * Outside a request scope this simply calls `compute()` every time.
+ */
+export function oncePerRequest<T>(key: string, compute: () => T): T {
+ const provider = storage.getStore();
+ if (!provider) return compute();
+
+ let memo = provider.get(memoContext);
+ if (!memo) {
+ memo = new Map<string, unknown>();
+ provider.set(memoContext, memo);
+ }
+ if (!memo.has(key)) {
+ memo.set(key, compute());
+ }
+ return memo.get(key) as T;
+}
+
+/**
+ * Like `oncePerRequest`, but ONLY on a request that just reads.
+ *
+ * Use this for anything derived from database state — permission claims, an
+ * order, a job — rather than `oncePerRequest`. React Router runs an action and
+ * the loader revalidation that follows it in the SAME request, so a plain
+ * per-request memo would hand the revalidating loaders whatever was read before
+ * the action wrote: a stale render, or a permission gate passing on claims the
+ * action just revoked. On any mutating method this is a pass-through.
+ *
+ * `oncePerRequest` remains correct for values that are not database state — a
+ * Supabase client is interchangeable regardless of what the request does.
+ */
+export function oncePerRead<T>(key: string, compute: () => T): T {
+ const provider = storage.getStore();
+ if (!provider?.get(isReadRequestContext)) return compute();
+ return oncePerRequest(key, compute);
+}
+
+/** Test seam: how many values the current request has memoized. */
+export function requestMemoSize(): number {
+ return storage.getStore()?.get(memoContext)?.size ?? 0;
+}
+
+/** Test seam: run `fn` inside a fresh request scope, as the middleware would. */
+export function runInRequestContext<T>(
+ provider: RequestContext,
+ fn: () => T,
+ options?: { isRead?: boolean }
+): T {
+ provider.set(isReadRequestContext, options?.isRead ?? true);
+ return storage.run(provider, fn);
+}
diff --git a/packages/logger/src/middleware.server.ts b/packages/logger/src/middleware.server.ts
index e26a7c7f23..85385cf457 100644
--- a/packages/logger/src/middleware.server.ts
+++ b/packages/logger/src/middleware.server.ts
@@ -6,6 +6,22 @@ import {
type MiddlewareFunction,
type RouterContextProvider
} from "react-router";
+import { getRequestContext } from "./context.server";
+
+// Re-exported from the existing entry point rather than adding a new package
+// export subpath: Vite resolves a package's `exports` map once at dev-server
+// start, so a new subpath 500s until every running dev server is restarted.
+// TODO: once a restart is coordinated, add `"./context.server"` to this
+// package's `exports` and repoint the four importers (both apps' root.tsx,
+// auth's auth.server.ts and users.server.ts) at it, then drop this re-export.
+export {
+ getRequestContext,
+ getRouterContext,
+ oncePerRead,
+ oncePerRequest,
+ requestContextMiddleware
+} from "./context.server";
+
import { getLogger } from "./logger";
export const REQUEST_ID_HEADER = "x-request-id";
@@ -112,8 +128,16 @@ async function captureRequestBody(request: Request): Promise<unknown> {
/** Request-scoped correlation id, readable in loaders/actions via `getRequestId`. */
export const requestIdContext = createContext<string | null>(null);
-export function getRequestId(context: RouterContextProvider): string | null {
- return context.get(requestIdContext);
+/**
+ * The current request's correlation id.
+ *
+ * Pass `context` explicitly from a loader/action, or omit it to read the
+ * ambient request context published by `requestContextMiddleware` — which is
+ * what makes this callable from a plain service function.
+ */
+export function getRequestId(context?: RouterContextProvider): string | null {
+ if (context) return context.get(requestIdContext);
+ return getRequestContext(requestIdContext) ?? null;
}
const log = getLogger("http");
diff --git a/packages/utils/AGENTS.md b/packages/utils/AGENTS.md
index 710b8aa820..43fac657be 100644
--- a/packages/utils/AGENTS.md
+++ b/packages/utils/AGENTS.md
@@ -39,6 +39,7 @@ pnpm --filter @carbon/utils typecheck
| `datetime` | Server-side date derivation with mandatory explicit timezone: `timestamp()`, `today(tz)`, `now(tz)`, `businessDay(instant, tz)`, `weekBounds(tz, offset?, anchor?)` (DST-safe Monday→Sunday instant bounds), `weekNumber(date)`. DST/exotic-zone stress suite in `datetime.test.ts` (gap/overlap disambiguation, midnight-skipping zones, 167/169h weeks, ±30/45-min offsets). Mirrored for Deno at `packages/database/supabase/functions/lib/datetime.ts` — keep in sync |
| `math` | Rounding, precision, numeric utilities |
| `string` | Slugify, truncate, camelCase/titleCase conversions |
+| `revalidate` | `isSearchParamOnlyNavigation` — shared by both apps' shell `shouldRevalidate` |
| `status` | Status resolution, status color mapping |
| `storage-rules` | Supabase storage bucket access policies |
| `supabase` | Typed Supabase query helpers |
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index 3163415ce5..17d2a50a95 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -21,6 +21,7 @@ export * from "./llm";
export * from "./math";
export * from "./object";
export * from "./receiving";
+export * from "./revalidate";
export * from "./ssr";
export * from "./status";
export * from "./status-colors";
diff --git a/packages/utils/src/revalidate.test.ts b/packages/utils/src/revalidate.test.ts
new file mode 100644
index 0000000000..08588499f0
--- /dev/null
+++ b/packages/utils/src/revalidate.test.ts
@@ -0,0 +1,69 @@
+import { describe, expect, it } from "vitest";
+import { isSearchParamOnlyNavigation } from "./revalidate";
+
+const url = (href: string) => new URL(href, "https://erp.test");
+
+describe("isSearchParamOnlyNavigation", () => {
+ it("is true when only the search params changed", () => {
+ expect(
+ isSearchParamOnlyNavigation({
+ currentUrl: url("/x/items/parts"),
+ nextUrl: url("/x/items/parts?filter=active:eq:true")
+ })
+ ).toBe(true);
+ });
+
+ it("is true for paging within the same screen", () => {
+ expect(
+ isSearchParamOnlyNavigation({
+ currentUrl: url("/x/items/parts?offset=0"),
+ nextUrl: url("/x/items/parts?offset=100")
+ })
+ ).toBe(true);
+ });
+
+ it("is false when the pathname changed", () => {
+ expect(
+ isSearchParamOnlyNavigation({
+ currentUrl: url("/x/items/parts"),
+ nextUrl: url("/x/sales/orders")
+ })
+ ).toBe(false);
+ });
+
+ // A mutation may change shell data (saved views, company settings), so a
+ // submission must always revalidate even when the URL is unchanged.
+ it.each([
+ "POST",
+ "PUT",
+ "PATCH",
+ "DELETE"
+ ])("is false for a %s submission", (formMethod) => {
+ expect(
+ isSearchParamOnlyNavigation({
+ currentUrl: url("/x/items/parts"),
+ nextUrl: url("/x/items/parts"),
+ formMethod
+ })
+ ).toBe(false);
+ });
+
+ it("is true for a GET submission, which cannot mutate", () => {
+ expect(
+ isSearchParamOnlyNavigation({
+ currentUrl: url("/x/items/parts"),
+ nextUrl: url("/x/items/parts?search=bolt"),
+ formMethod: "GET"
+ })
+ ).toBe(true);
+ });
+
+ it("treats an identical URL as search-param-only (revalidator case)", () => {
+ expect(
+ isSearchParamOnlyNavigation({
+ currentUrl: url("/x/items/parts?a=1"),
+ nextUrl: url("/x/items/parts?a=1")
+ })
+ ).toBe(true);
+ });
+});
diff --git a/packages/utils/src/revalidate.ts b/packages/utils/src/revalidate.ts
new file mode 100644
index 0000000000..3b80a604ab
--- /dev/null
+++ b/packages/utils/src/revalidate.ts
@@ -0,0 +1,26 @@
+/**
+ * True when a navigation only changed the search params of the page we are
+ * already on — a table filter, sort, page, or drawer toggle.
+ *
+ * These are by far the most frequent navigations in the app, and none of them
+ * can change app-shell data: no mutation ran and the route didn't change. So a
+ * shell-level `shouldRevalidate` can skip them.
+ *
+ * Note what this does NOT cover: `useRevalidator().revalidate()` (how the
+ * realtime hooks refresh) also presents as same-pathname with no form method,
+ * so a shell loader using this will not re-run for realtime events either.
+ * Leaf loaders still refresh, which is the intent — but shell data that must
+ * react to a realtime change needs its own path in `shouldRevalidate`.
+ */
+export function isSearchParamOnlyNavigation({
+ currentUrl,
+ nextUrl,
+ formMethod
+}: {
+ currentUrl: URL;
+ nextUrl: URL;
+ formMethod?: string;
+}) {
+ if (formMethod && formMethod !== "GET") return false;
+ return currentUrl.pathname === nextUrl.pathname;
+}