Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
Client query cache, realtime over broadcast, and faster detail pages (#1843)
Sid79af16d7f195
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 59a0367e24..16f55f176b 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -2923,3 +2923,68 @@ tag until proven otherwise.**Rule:** When a transform plugin misbehaves only on route modules, look at the id's query. Verify a build-plugin change with a real `react-router build` of ERP, not with vitest.**Applies to:** `packages/dev/vite.js` (`linguiWithoutIdQuery`), `apps/*/vite.config.ts`.+++## A realtime subscription to a table that is not published fails silently++**Context:** The ERP job page did not show an operation completed in the MES until a reload. It subscribed with `postgres_changes` to `jobOperationStep` and `jobOperationStepRecord`, which were never in the `supabase_realtime` publication, and it had no subscription to `jobOperation` or `job` at all.++**Problem:** Realtime accepts a `postgres_changes` subscription for any table name. For an unpublished table it joins, delivers nothing and reports nothing. The code looked wired and typecheck, lint and tests were all green.++**Rule:** Realtime goes through broadcast topics (`@carbon/query`). Declare a route's tables in `handle.realtime`; the table type is derived from `event-system/attachments.ts`, so a table with no broadcast handler does not compile, and `no-postgres-changes` fails the old API. Verify a "live" page by changing the row while the page is open, not by reading the subscription code.++**Applies to:** `apps/*/app/routes/**` `handle.realtime`, `useRealtime`, `useChangedRows`, `.claude/rules/realtime-system.md`.+++## `getCompanyId()` read an httpOnly cookie in the browser and always returned null++**Context:** The client cache scoped its keys with `getCompanyId()`, which parsed `document.cookie` for `companyId`.++**Problem:** That cookie is httpOnly, so JavaScript never sees it. Every key was scoped to the string `"null"`, and an invalidation that matched on the real company id matched nothing. It went unnoticed because a company switch reloads the page and empties the in-memory cache.++**Rule:** Never read a session cookie from `document.cookie`. A value the browser needs comes from loader data: the shell layout calls `setClientCompanyId(company.id)` during render (`@carbon/query/cache`).++**Applies to:** `packages/query/src/cache.ts`, both `apps/*/app/routes/x+/_layout.tsx`, any new client-side tenant scoping.+++## A `.client.ts` module is empty on the server, even for a value a route only calls at load++**Context:** The invalidation middleware factory lived in `invalidate.client.ts`, next to `flash.client.ts`. `root.tsx` calls `createInvalidationMiddleware(...)` while the module is evaluated.++**Problem:** React Router replaces a `.client` module's exports with `undefined` on the server. `flash.client.ts` survives because `root.tsx` only REFERENCES its export; a factory is CALLED, so SSR died with "is not a function". Typecheck, lint and unit tests passed.++**Rule:** A module whose export is called at module load of a route must not be named `.client` or `.server`. After adding anything to `root.tsx` or a shell layout, load the page from a running dev server before calling it done.++**Applies to:** `apps/*/app/root.tsx`, `packages/query/src/invalidation.ts`, any shared module imported by a route.+++## Two hooks that open the same Realtime topic close each other's channel++**Context:** The shell, the live lists and individual components each called `carbon.channel(topic)` for `company:<id>:<table>`.++**Problem:** `RealtimeClient.channel()` returns the EXISTING channel when the topic is already open. Two hooks then hold one channel object, and the first to unmount calls `removeChannel` and silences the other. A customers page that declared `customer` while the customer list also followed it would have lost one of them at random.++**Rule:** One owner per topic. Listeners register in the registry in `packages/query/src/useRealtime.tsx` (`useTopic`, `useTableChanges`) and `RouteRealtime` owns the channels. Do not call `carbon.channel` or `useRealtimeChannel` for a broadcast topic directly.++**Applies to:** `packages/query/src/useRealtime.tsx`, any new realtime listener.+++## Chained Supabase writes in a route action are not a transaction++**Context:** RFQ finalize and supplier quote finalize each wrote a quote, its lines, a share link and a price list as separate `client.from(...)` calls in a loop, logging and skipping any that failed.++**Problem:** Every statement was its own PostgREST request (about 34 ms each), and a failure partway left quotes without lines or half a price list while the action still reported success. The checks that made the write safe (every line priced, the RFQ still Draft) lived in the route, so the API tool for the same operation skipped them.++**Rule:** A write that spans tables is a server function (`packages/server-functions`) with one Kysely transaction. Its preconditions are checked inside it, on a locked read of the document (`forUpdate()`), so a double submit and every other caller get the same answer. The route keeps only what is about the request: the form, the flash, the email.++**Applies to:** any route action with more than one write; `finalize-purchasing-rfq`, `finalize-supplier-quote`.++## A stored copy of server data belongs to a user, not a browser++**Context:** The live lists (items, customers, suppliers, people) were kept in IndexedDB under `<list>:<companyId>` and patched from a change log.++**Problem:** The rows a user holds are their RLS view. The next person to sign in on that browser hydrated the previous user's rows, and patching only the changed ids never removed them. The in-memory query cache had the same hole inside one tab.++**Rule:** Key anything stored on the device by user as well as company, and empty the in-memory cache when the user changes (`setClientCompanyId(companyId, userId)`). A cache that is only ever patched needs a path that replaces it.++**Applies to:** `packages/query/src/useLiveList.tsx`, `packages/query/src/cache.ts`, any new client-side persistence.diff --git a/.ai/plans/2026-10-04-client-query-cache-and-realtime-broadcast.md b/.ai/plans/2026-10-04-client-query-cache-and-realtime-broadcast.mdnew file mode 100644index 0000000000..b8ea245aa3--- /dev/null+++ b/.ai/plans/2026-10-04-client-query-cache-and-realtime-broadcast.md@@ -0,0 +1,704 @@+# Client query cache and realtime broadcast — implementation plan++**Spec:** .ai/specs/2026-10-04-client-query-cache-and-realtime-broadcast.md+**Research:** .ai/research/2026-10-01-client-cache-on-react-router.md+**Branch:** claude/tanstack-query-caching-realtime-54567c++## Progress+- [x] Task 1: Install dependencies and prove broadcast on the local stack+- [x] Task 2: Add the realtime table lists+- [x] Task 3: Add the three broadcast functions and the `realtime.messages` policies (authz manifest)+- [x] Task 4: Write the attach migration+- [x] Task 5: Apply the migrations and regenerate types+- [x] Task 6: Add the database tests+- [x] Task 6b: Move event triggers and interceptor bodies out of migrations (user, 2026-10-05)+- [x] Task 7: Add the `realtime-table-has-trigger` check+- [x] Task 8: Add the private option to `useRealtimeChannel`+- [x] Task 9: Add `cachedClientLoader` and the company id value+- [x] Task 10: Add the invalidation middleware to both roots+- [x] Task 11: Convert the 27 cached `clientLoader` exports+- [x] Task 12: Delete the invalidation-only `clientAction` exports+- [x] Task 13: Add `useRealtime` and `useRouteRealtime` to `@carbon/react`+- [x] Task 14: Move the ERP lists to `useLiveList`+- [x] Task 15: Move the MES lists and remove nanostores+- [x] Task 16: Move notifications and the implementation hub+- [x] Task 17: Declare `handle.realtime` on the routes and convert the subscribers+- [x] Task 18: Add `useLoaderQuery` and migrate the `.load()` call sites (13 event-driven sites stay on `useFetcher`: Linear and Jira issue search, the Onshape sync steps, the Stripe customer lookup, the 2 report drill-downs, the MES issue-material modal)+- [x] Task 19: Add `useAction` and migrate the submit call sites (98 single-condition effects; the 133 effects with several branches are a follow-up PR, user decision 2026-10-05)+- [x] Task 20: Update the rules, the lessons and the `AGENTS.md` files+- [x] Task 21: Run the full verification and the browser tests++## Dependencies++- Task 1 gates everything. If it fails, stop.+- Tasks 2 → 3 → 4 → 5 → 6 run in order (database).+- Task 7 needs Task 2.+- Tasks 8, 9 are independent of the database tasks.+- Task 10 needs Task 9. Tasks 11 and 12 need Task 10.+- Task 13 needs Tasks 5, 8 and 10. Tasks 14, 15, 16 and 17 need Task 13.+- Task 18 needs Task 11. Task 19 is independent of Task 18.+- Tasks 11, 12, 18 and 19 are codemod sweeps. Run each sweep one module folder at a time.++Rules for every task:++- Run each typecheck alone: `pnpm exec turbo run typecheck --filter=<pkg> --concurrency=1`.+- Start each new source file with its SPDX header: `pnpm --filter @carbon/checks license-headers`.+- Never run `pnpm db:migrate`. The user runs it.+- Never push. Commit only through `/check-and-commit`.++---++## Task 1: Install dependencies and prove broadcast on the local stack++**Depends on:** none+**Files:**+- Create: `<scratchpad>/broadcast-spike.sql`, `<scratchpad>/broadcast-spike.mjs` (not committed)++**Steps:**+1. Ask the user to approve `pnpm install` in this worktree. Run it with no `--filter`.+2. Ask the user to start the stack with `crbn up`, if it is not running.+3. In `psql`, run `SELECT to_regprocedure('realtime.send(jsonb,text,text,boolean)');`.+4. If step 3 returns NULL, STOP and report. Do not improvise.+5. Write the spike script. It signs in as the `DEV_BYPASS_EMAIL` user with supabase-js.+6. The script joins `company:<companyId>:spike` with `{ config: { private: true } }`.+7. Before the policy exists, confirm that the join returns `CHANNEL_ERROR`.+8. In a `psql` transaction, create the company policy from the spec. Do not commit it.+9. Run `SELECT realtime.send('{"op":"INSERT"}'::jsonb, 'INSERT', 'company:<companyId>:spike', true);`.+10. Confirm that the script prints the message.+11. Roll the transaction back.++**Verify:**+```bash+node <scratchpad>/broadcast-spike.mjs+# Expected: "CHANNEL_ERROR" without the policy; "received INSERT" with it+```++**Out of scope:** any change to a tracked file. If Realtime v2.89.0 does not deliver the message, STOP and report.++---++## Task 2: Add the realtime table lists++**Depends on:** Task 1+**Files:**+- Create: `packages/database/src/realtime-tables.ts`+- Create: `packages/database/src/realtime-tables.test.ts`+- Modify: `packages/database/package.json` — add the export `./realtime-tables`+- Copy from (precedent): `packages/database/src/supersession-pick.ts` (a client-safe module with its own export)++**Steps:**+1. Export `REALTIME_TABLES` as a `const` array of table names, typed `keyof Database["public"]["Tables"]`.+2. Put these 66 names in it: `assemblyPlanJob`, `changeOrder`, `customField`, `customer`, `documentExtraction`, `documentTemplate`, `employee`, `implementationCheckState`, `implementationFieldValue`, `implementationHub`, `implementationRow`, `inspection`, `inventoryCount`, `item`, `itemLedger`, `itemStockQuantities`, `itemSupersession`, `job`, `jobMakeMethod`, `jobMaterial`, `jobOperation`, `jobOperationNote`, `jobOperationStep`, `jobOperationStepRecord`, `journal`, `maintenanceDispatch`, `material`, `materialForm`, `materialSubstance`, `modelUpload`, `nonConformance`, `nonConformanceActionTask`, `part`, `pickingList`, `pickingListLine`, `printJob`, `productionEvent`, `productionQuantity`, `purchaseInvoice`, `purchaseInvoiceLine`, `purchaseOrder`, `purchaseOrderLine`, `purchaseReturnOrder`, `purchasingRfq`, `quote`, `quoteLine`, `quoteMaterial`, `quoteOperation`, `receipt`, `receiptLine`, `salesInvoice`, `salesInvoiceLine`, `salesOrder`, `salesOrderLine`, `salesReturnOrder`, `salesRfq`, `salesRfqLine`, `shipment`, `shipmentLine`, `stockTransfer`, `supplier`, `supplierQuote`, `trackedEntity`, `warehouseTransfer`, `workflowRun`, `workflowStepRun`.+3. Export `REALTIME_REFERENCE_TABLES` with these 20 names: `ability`, `customerContact`, `customerLocation`, `customerType`, `itemPostingGroup`, `location`, `materialType`, `nonConformanceType`, `paymentTerm`, `procedure`, `process`, `qualityDocument`, `shippingMethod`, `storageUnit`, `supplierContact`, `supplierLocation`, `supplierProcess`, `supplierType`, `unitOfMeasure`, `workCenter`.+4. Export `REALTIME_USER_TABLES = ["notification"] as const`.+5. Export the type `RealtimeTable` as the union of the first list.+6. In the test, assert that the three lists share no name and hold no duplicate.+7. For each name, run `SELECT relkind FROM pg_class WHERE oid = '"<name>"'::regclass;`. If one is not `r`, STOP and report.++**Verify:**+```bash+pnpm --filter @carbon/database exec vitest run src/realtime-tables.test.ts+# Expected: 1 file passed+```++**Out of scope:** a table for a settings or admin page. Task 17 may add a name here only when a route in the spec's folder list needs it.++---++## Task 3: Add the three broadcast functions and the `realtime.messages` policies++**Depends on:** Task 2+**Files:**+- Create: `packages/database/src/event-system/functions/broadcast_table_changes.sql`+- Create: `packages/database/src/event-system/functions/broadcast_user_changes.sql`+- Create: `packages/database/src/event-system/functions/broadcast_reference_changes.sql`+- Modify: `packages/database/src/event-dispatch.test.ts` — check the ignored-column list in the 3 new files+- Modify: `packages/database/src/authz/rules.ts`, `sync.ts`, `migration.ts`, `manifest.ts` — the manifest owns `"realtime.messages"`+- Modify: `packages/checks/src/conformance/no-authz-ddl-in-migrations.ts` — flag a policy on the `realtime` schema+- Copy from (precedent): `packages/database/src/event-system/functions/dispatch_event_batch.sql`++**Steps:**+1. Read `.claude/rules/authz-manifest.md` → "Event-system functions" before you write a file.+2. Write `broadcast_table_changes.sql` with the function body from the spec's Data Model section.+3. Write `broadcast_user_changes.sql`. Use the same body. Group by `c->>'userId'`. Send to `'user:' || user_id || ':' || TG_TABLE_NAME`.+4. Write `broadcast_reference_changes.sql`. Use the same body. Send `{ table, op }` to `'company:' || company_id || ':reference'`.+5. In each file, declare `ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];` on one line.+6. In `event-dispatch.test.ts`, run the existing constant check for each of the 4 files in a loop.+7. Add `locate(key)` and `external()` to `rules.ts`. A key with a dot names `<schema>.<table>`.+8. Add the `"realtime.messages"` entry with the 2 policies to `manifest.ts`.+9. Make `sync.ts` and `migration.ts` read the schema from the key. Keep the `public` output byte for byte.+10. Run `pnpm --filter @carbon/database authz migration realtime-broadcast`.+11. If the timestamp is older than the newest migration on `main`, rename the file to a later timestamp.+12. Do not edit the content of the generated migration.+13. When the local stack runs, run `pnpm --filter @carbon/database authz sync` and the `sync.test.ts` file.++**Verify:**+```bash+pnpm --filter @carbon/database exec vitest run src/event-dispatch.test.ts src/authz+# Expected: all files passed; the generated migration lists the 3 function names+```++**Out of scope:** `dispatch_event_batch.sql` and `attach_statement_handler.sql`. If `authz sync` refuses a file, STOP and report.++---++## Task 4: Write the attach migration++**Depends on:** Task 3+**Files:**+- Create: `packages/database/supabase/migrations/<timestamp>_realtime-broadcast-attach.sql` through `pnpm db:migrate:new realtime-broadcast-attach`+- Copy from (precedent): `packages/database/supabase/migrations/20260812002454_item-stock-quantities-incremental.sql` (the `attach_statement_handler` call)++**Steps:**+1. Run `pnpm db:migrate:new realtime-broadcast-attach`.+2. Confirm that its timestamp is later than the generated migration of Task 3.+3. Write no policy in this file. The generated migration of Task 3 ships the 2 policies.+4. Add one `SELECT attach_statement_handler('<table>', ARRAY['broadcast_table_changes']);` line for each name in `REALTIME_TABLES`, except `itemLedger`.+5. For `itemLedger`, pass `ARRAY['apply_item_stock_quantities', 'broadcast_table_changes']`.+6. Add one line with `ARRAY['broadcast_reference_changes']` for each name in `REALTIME_REFERENCE_TABLES`.+7. Add the line for `notification` with `ARRAY['broadcast_user_changes']`.+8. Query `pg_publication_tables` for `supabase_realtime`. Add one guarded `ALTER PUBLICATION supabase_realtime DROP TABLE` for each row.+9. Wrap each drop in a `DO` block that checks `pg_publication_tables` first, so the migration is idempotent.+10. Add `CREATE OR REPLACE FUNCTION public.list_checksums(p_company_id TEXT)` from the spec, with the fifth row `mesItems`.+11. The `mesItems` row hashes `id, readableIdWithRevision, name, type, replenishmentSystem, itemTrackingType, active, thumbnailPath` and the model's `thumbnailPath`.+12. Add `REVOKE ALL ON FUNCTION public.list_checksums(TEXT) FROM PUBLIC, anon;` and `GRANT EXECUTE ... TO authenticated;`.+13. Run `pnpm --filter @carbon/checks clobbers`.++**Verify:**+```bash+grep -c "attach_statement_handler(" packages/database/supabase/migrations/*_realtime-broadcast-attach.sql+# Expected: 87 (66 + 20 + 1)+pnpm --filter @carbon/checks exec vitest run src/conformance/no-authz-ddl-in-migrations.test.ts+# Expected: passed+```++**Out of scope:** any `CREATE POLICY`. The check rejects a policy on `public` or `realtime` in a hand-written migration.++---++## Task 6b: Move event triggers and interceptor bodies out of migrations++**Depends on:** Task 5+**Files:**+- Create: `packages/database/src/event-system/attachments.ts` — the triggers of 141 tables+- Create: `packages/database/src/event-system/attachments-sync.ts`, `attachments-sync.test.ts`+- Create: `packages/database/src/event-system/handlers/*.sql` — 64 functions, read from the database with `pg_get_functiondef`+- Create: `packages/database/src/event-system/functions/set_event_triggers.sql`+- Create: `packages/database/supabase/migrations/20261004193811_drop-stale-interceptor-overload.sql`+- Create: `packages/database/supabase/migrations/20261004194527_event-attachments.sql` (generated)+- Modify: `packages/database/src/authz/sync.ts`, `migration.ts`, `cli.ts`, `helpers.ts`+- Modify: `packages/database/src/realtime-tables.ts` — the 3 lists derive from `attachments.ts`+- Modify: `packages/database/supabase/migrations/20261004192633_realtime-broadcast-attach.sql` — no attach call stays+- Modify: `packages/checks/src/conformance/no-authz-ddl-in-migrations.ts` — reject attach calls++**Steps:**+1. Read the live triggers of each table from the local database. Write them to `attachments.ts`.+2. Read each attached function with `pg_get_functiondef`. Write each one to `handlers/<name>.sql`.+3. Make `authz sync` compare the live triggers with `attachments.ts`.+4. Make `authz migration` write one `SELECT set_event_triggers(...)` for each changed table.+5. Run `pnpm --filter @carbon/database authz migration event-attachments`.+6. Ask the user to run `pnpm db:migrate`.++**Verify:**+```bash+SUPABASE_DB_URL=<local url> pnpm --filter @carbon/database exec vitest run src/authz src/event-system+# Expected: all passed; `authz check` reports 0 helpers, 0 tables, 0 event triggers+```++**Out of scope:** a change to what a trigger does. The takeover ships the triggers and the bodies as the database has them.++---++## Task 5: Apply the migrations and regenerate types++**Depends on:** Task 4+**Files:**+- Modify: `packages/database/src/types.ts` (generated) — gains `list_checksums`++**Steps:**+1. Ask the user to run `pnpm db:migrate`. Wait for the user.+2. Run `pnpm run generate:types`.+3. Run `EXPLAIN ANALYZE INSERT` on `jobOperation` in a rolled-back transaction. Record the trigger time in `.ai/runs/2026-10-04-realtime-broadcast.md`.+4. Run `EXPLAIN ANALYZE SELECT * FROM list_checksums('<companyId>')`. Record the time in the same file.++**Verify:**+```bash+psql "$SUPABASE_DB_URL" -c "SELECT count(*) FROM pg_publication_tables WHERE pubname = 'supabase_realtime';"+# Expected: 0+pnpm exec turbo run typecheck --filter=@carbon/database --concurrency=1+# Expected: 0 errors+```++**Out of scope:** hand edits to `types.ts`.++---++## Task 6: Add the database tests++**Depends on:** Task 5+**Files:**+- Create: `packages/database/supabase/tests/realtime-broadcast.test.sql`+- Copy from (precedent): `packages/database/supabase/tests/rpc-privileges.test.sql`++**Steps:**+1. Copy the fixture block: 2 companies, 2 users, all inside one rolled-back transaction.+2. Assert: an `INSERT` into `item` for company A adds 1 row to `realtime.messages` with topic `company:<A>:item`.+3. Assert: an `UPDATE` that changes only `updatedAt` adds 0 rows.+4. Assert: an `UPDATE` of 150 rows adds 1 row with `ids` null.+5. Assert: an `INSERT` into `notification` adds 1 row with topic `user:<userId>:notification`.+6. Assert: an `INSERT` into `customerType` adds 1 row with topic `company:<A>:reference`.+7. Assert: as user A, a `SELECT` on `realtime.messages` with `realtime.topic` set to `company:<B>:item` returns 0 rows.+8. Assert: as user B, the topic `user:<A>:notification` returns 0 rows.+9. Assert: `list_checksums` as user A for company B returns hashes of empty lists.+10. Assert: `list_checksums` changes after a customer rename and after an item delete.++**Verify:**+```bash+pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/realtime-broadcast.test.sql+# Expected: exit 0, ends with ROLLBACK+```++**Out of scope:** committed fixture rows.++---++## Task 7: Add the `realtime-table-has-trigger` check++**Depends on:** Task 2+**Files:**+- Create: `packages/checks/src/conformance/realtime-table-has-trigger.ts`+- Create: `packages/checks/src/conformance/realtime-table-has-trigger.test.ts`+- Modify: `packages/checks/src/index.ts`, `packages/checks/src/run.ts` — register the check+- Copy from (precedent): `packages/checks/src/conformance/index-redirect-before-loaders.ts`++**Steps:**+1. Scan each file under `apps/{erp,mes}/app` for `realtime: [` in a `handle` export and for `useRealtime("…")`.+2. Report a violation for each table name that `REALTIME_TABLES` lacks.+3. Report a violation for each `"postgres_changes"` string literal in `apps/` or `packages/react/src`.+4. In the test, cover 3 cases: a listed table passes, an unlisted table fails, a `postgres_changes` literal fails.++**Verify:**+```bash+pnpm --filter @carbon/checks exec vitest run src/conformance/realtime-table-has-trigger.test.ts+# Expected: 3 tests passed+```++**Out of scope:** a baseline entry. The check must end with zero findings after Task 17.++---++## Task 8: Add the private option to `useRealtimeChannel`++**Depends on:** Task 1+**Files:**+- Modify: `packages/react/src/hooks/useRealtimeChannel.ts` — new `private?: boolean` option and an `onSubscribed?: (isReconnect: boolean) => void` option++**Steps:**+1. Pass `{ config: { private: true } }` to `carbon.channel(topic, …)` when `private` is true.+2. Call `onSubscribed(true)` on each `SUBSCRIBED` status after the first one. Call `onSubscribed(false)` on the first.+3. Add `private` to the effect dependencies.++**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/react --concurrency=1+# Expected: 0 errors+```++**Out of scope:** the retry schedule and the toast behavior.++---++## Task 9: Add `cachedClientLoader` and the company id value++**Depends on:** Task 1+**Files:**+- Modify: `apps/erp/app/utils/react-query.ts` — add `LOADER`, `LOADER_GC_TIME`, `loaderQueryKey`, `cachedClientLoader`, `setCompanyId`+- Modify: `apps/erp/app/utils/react-query.test.ts` — new cases+- Modify: `apps/erp/app/routes/x+/_layout.tsx` — call `setCompanyId(company.id)` before the first child renders++**Steps:**+1. Add `export const LOADER = "loader";` and `const LOADER_GC_TIME = 1000 * 60 * 30;`.+2. Replace the cookie read in `getCompanyId` with a module variable that `setCompanyId` writes.+3. Add `loaderQueryKey(url: string)`. It returns `[LOADER, companyId, pathname, search]`.+4. Add `cachedClientLoader` with the body from the spec.+5. Test: 2 concurrent calls for one URL call `serverLoader` 1 time.+6. Test: a call after `invalidateQueries({ queryKey: [LOADER] })` calls `serverLoader` again.+7. Test: with no company id, the function calls `serverLoader` and writes no cache entry.+8. Test: the returned function has `hydrate === true`.++**Verify:**+```bash+pnpm --filter erp exec vitest run app/utils/react-query.test.ts+# Expected: all tests passed+```++**Out of scope:** the existing key factories. Task 12 deletes the unused ones.++---++## Task 10: Add the invalidation middleware to both roots++**Depends on:** Task 9+**Files:**+- Create: `packages/auth/src/middleware/invalidate.client.ts`+- Create: `packages/auth/src/middleware/invalidate.client.test.ts`+- Modify: `apps/erp/app/root.tsx` — add the middleware to `clientMiddleware`+- Modify: `apps/mes/app/root.tsx` — store the client on `window.clientCache`; add the middleware+- Modify: `apps/mes/app/types/global.d.ts` (create it if absent) — declare `window.clientCache`+- Copy from (precedent): `packages/auth/src/middleware/flash.client.ts`++**Steps:**+1. Export `createInvalidationMiddleware({ getCache, skipPaths })`.+2. After `await next()`, return if `request.method` is `GET`.+3. Return if `skipPaths` holds the request pathname.+4. Call `getCache()?.invalidateQueries({ queryKey: ["loader"] })`.+5. In each root, pass `skipPaths: [path.to.refreshSession]`.+6. In the MES root, copy the ERP `useState` initializer that reuses `window.clientCache`.+7. Test 3 cases: a `GET` invalidates nothing, a `POST` invalidates, a `POST` to `/refresh-session` invalidates nothing.++**Verify:**+```bash+pnpm --filter @carbon/auth exec vitest run src/middleware/invalidate.client.test.ts+# Expected: 3 tests passed+```++**Out of scope:** `flashClientMiddleware`. `@carbon/auth` gets no dependency on `@tanstack/react-query`; type the cache as `{ invalidateQueries(filter: { queryKey: unknown[] }): unknown }`.++---++## Task 11: Convert the 27 cached `clientLoader` exports++**Depends on:** Task 10+**Files:**+- Modify: each file that `grep -rlE "export (async function|const) clientLoader" apps/erp/app/routes/api+` prints (27 files)++**Steps:**+1. In each file, replace the `clientLoader` function and its `.hydrate` line with `export const clientLoader = cachedClientLoader<typeof loader>();`.+2. If the old code passed a `staleTime` other than `RefreshRate.Low`, pass the same `staleTime`.+3. Remove the imports that the file no longer uses.+4. `inventory.storage-units.ts` and `inventory.storage-units-with-quantities.ts` shared one key. Confirm that their URL keys now differ.++**Verify:**+```bash+grep -rLE "cachedClientLoader<typeof loader>" $(grep -rlE "clientLoader" apps/erp/app/routes/api+) | wc -l+# Expected: 0+pnpm exec turbo run typecheck --filter=erp --concurrency=1+# Expected: 0 errors+```++**Out of scope:** the server `loader` of each file.++---++## Task 12: Delete the invalidation-only `clientAction` exports++**Depends on:** Task 10+**Files:**+- Modify: each file that `grep -rlE "export (async function|const) clientAction" apps/erp/app/routes` prints (78 files)+- Modify: `apps/erp/app/utils/react-query.ts` — delete each export with zero importers+- Modify: `apps/erp/app/components/Form/Item.tsx`, `Form/Account.tsx`, `Form/EmailRecipients.tsx`, `components/Selectors/UserSelect/useUserSelect.ts` — move `cachedApiQuery` callers to `loaderQueryKey(url)`++**Steps:**+1. Read each `clientAction`. If it only invalidates or nulls a key and calls `serverAction()`, delete the export.+2. If it does other work, keep that work and delete the cache lines.+3. Change `cachedApiQuery(query, url)` to take only `url`. Key it with `loaderQueryKey(url)`.+4. Delete `invalidateUserSelectQueries` and `invalidateInspectionDocuments`, and their callers.+5. For each export left in `react-query.ts`, run `grep -rn "<name>" apps/erp/app`. Delete the export if only its definition matches.+6. Keep `ITEM_QUANTITIES_QUERY_KEY` and `itemQuantitiesQuery`.++**Verify:**+```bash+grep -rn "setQueryData\|getQueryData" apps/erp/app/routes | wc -l+# Expected: 0+pnpm exec turbo run typecheck --filter=erp --concurrency=1+# Expected: 0 errors+```++**Out of scope:** the server `action` of each file.++---++## Task 13: Add `useRealtime` and `useRouteRealtime` to `@carbon/react`++**Depends on:** Tasks 5, 8, 10+**Files:**+- Create: `packages/react/src/hooks/useRealtime.ts` — exports `useRealtime`, `useDebouncedRealtime`, `useRealtimeRevalidator`, `useRouteRealtime`, `matchesIdFilter`+- Create: `packages/react/src/hooks/useRealtime.test.ts`+- Modify: `packages/react/src/hooks/index.ts` — export them+- Modify: `apps/erp/app/hooks/useRealtime.tsx`, `apps/erp/app/hooks/useDebouncedRealtime.ts`, `apps/mes/app/hooks/useRealtime.tsx` — re-export from `@carbon/react`+- Modify: `apps/erp/app/routes/x+/_layout.tsx`, `apps/mes/app/routes/x+/_layout.tsx` — call `useRouteRealtime(company.id)`+- Copy from (precedent): `apps/mes/app/hooks/useRealtime.tsx` (`useRealtimeRevalidator`)++**Steps:**+1. Move `useRealtimeRevalidator` from the MES file. It skips the revalidation while a fetcher is submitting.+2. Change it to run the skipped revalidation when the fetcher returns to `idle`.+3. Write `matchesIdFilter(filter, ids)`. It parses `id=eq.<id>` and `id=in.(<ids>)`.+4. If the filter names another column, `matchesIdFilter` returns true.+5. If `ids` is null, `matchesIdFilter` returns true.+6. Write `useRealtime(table: RealtimeTable, filter?, debounceMs = 300)`. It takes `companyId` from a `RealtimeContext` that the shell provides.+7. `useRealtime` subscribes to `company:<companyId>:<table>` with `private: true` and event `"*"` on `"broadcast"`.+8. On a matching message, it restarts the debounce timer. When the timer ends, it invalidates `["loader"]` and revalidates.+9. Write `useRouteRealtime(companyId)`. It reads `handle.realtime` from `useMatches()` and subscribes for each unique table.+10. `useRouteRealtime` also subscribes to `company:<companyId>:reference`. On a message it invalidates `["loader"]` only.+11. On `onSubscribed(true)`, both hooks invalidate and revalidate one time.+12. Test `matchesIdFilter` with 5 cases: `id=eq`, `id=in`, a parent column, null ids, no filter.++**Verify:**+```bash+pnpm --filter @carbon/react exec vitest run src/hooks/useRealtime.test.ts+# Expected: 5 tests passed+pnpm exec turbo run typecheck --filter=@carbon/react --concurrency=1+# Expected: 0 errors+```++**Out of scope:** callers of `useRealtime`. Task 17 converts them. `@carbon/react` reads the cache from `window.clientCache`; it gets no new dependency in this task.++---++## Task 14: Move the ERP lists to `useLiveList`++**Depends on:** Task 13+**Files:**+- Create: `packages/react/src/hooks/useLiveList.ts`, `packages/react/src/hooks/useLiveList.test.ts`+- Modify: `packages/react/package.json` — add `@tanstack/react-query` at the version the apps use (`5.97.0`)+- Modify: `apps/erp/app/stores/items.ts`, `customers.ts`, `suppliers.ts`, `people.ts` — hooks read the query cache+- Modify: `apps/erp/app/components/RealtimeDataProvider.tsx` — 4 `useLiveList` calls and the `itemStockQuantities` listener+- Copy from (precedent): `apps/erp/app/components/RealtimeDataProvider.tsx` (the column lists and the IndexedDB keys)++**Steps:**+1. Add the dependency with a bare `pnpm install`. Check `git diff --stat pnpm-lock.yaml` for unrelated changes.+2. Write `defineLiveList({ name, table, view?, columns, sort, enrich? })`. It returns the definition and the key `["live", companyId, name]`.+3. Write the pure function `applyBroadcast(rows, { op, ids }, fetched, sort)`. Test it with 4 cases: insert, update, delete, duplicate insert.+4. Write `useLiveList(definition, companyId)`. It does the cold-load steps 1 to 6 of the spec.+5. It subscribes to the definition's topic. On a message it does the broadcast steps 1 to 5 of the spec.+6. It calls `list_checksums` one time for all lists that mount in the same tick.+7. Store each list in IndexedDB as `{ rows, checksum }` under `<name>:<companyId>`.+8. If a stored value is a bare array (the old format), treat the checksum as absent.+9. The items definition sets `enrich` to merge `itemSupersession` rows. It also listens to the `itemSupersession` topic and resyncs.+10. The people definition reads the `employees` view and listens to the `employee` topic. A message always resyncs.+11. In each store file, export the hook as `() => [rows, setRows]`. `setRows` calls `setQueryData` on the list key.+12. Change `useParts`, `useTools`, `useServices`, `useMaterials` to `useQuery` with a `select` filter.+13. Keep `upsertIntoListStore` and `latestRevisionByReadableId`.+14. In the provider, on an `itemStockQuantities` message, invalidate the queries whose key starts with `ITEM_QUANTITIES_QUERY_KEY`.++**Verify:**+```bash+pnpm --filter @carbon/react exec vitest run src/hooks/useLiveList.test.ts+# Expected: 4 tests passed+pnpm exec turbo run typecheck --filter=erp --concurrency=1+# Expected: 0 errors, with no change to a file that calls useItems, useCustomers, useSuppliers or usePeople+```++**Out of scope:** the about 200 consumer files. If a consumer fails the typecheck, fix the hook's return type, not the consumer.++---++## Task 15: Move the MES lists and remove nanostores++**Depends on:** Task 14+**Files:**+- Modify: `apps/mes/app/stores/items.ts`, `apps/mes/app/stores/people.ts`, `apps/mes/app/components/RealtimeDataProvider.tsx`+- Delete: `packages/react/src/hooks/useNanoStore.ts`+- Modify: `packages/react/src/hooks/index.ts`, `apps/erp/app/hooks/index.ts`, `apps/mes/app/hooks/index.ts` — remove `useNanoStore`+- Modify: `apps/erp/package.json`, `apps/mes/package.json`, `packages/react/package.json`, `pnpm-workspace.yaml` — remove `nanostores` and `@nanostores/react`++**Steps:**+1. Define the MES item list with name `mesItems` and the MES column list.+2. Define the MES people list with the same definition as the ERP.+3. Replace the MES provider body with 2 `useLiveList` calls.+4. Delete `useNanoStore` and its exports.+5. Remove the 2 packages from each `package.json` and from the catalog. Run a bare `pnpm install`.++**Verify:**+```bash+grep -rl "nanostores" apps packages --include="*.ts" --include="*.tsx" --include="package.json" | grep -v node_modules | wc -l+# Expected: 0+pnpm exec turbo run typecheck --filter=mes --concurrency=1+# Expected: 0 errors+```++**Out of scope:** `localforage`. The topbar search keeps its own keys.++---++## Task 16: Move notifications and the implementation hub++**Depends on:** Task 13+**Files:**+- Modify: `apps/erp/app/hooks/useNotifications.tsx`+- Modify: `apps/erp/app/hooks/useImplementationRealtime.tsx`++**Steps:**+1. In `useNotifications`, subscribe to `user:<userId>:notification` with `private: true`.+2. On `INSERT` or `UPDATE`, read the rows with `.in("id", ids).eq("companyId", companyId)`. Use the select string of the initial load.+3. Apply the existing `digestedInto` rules to each row.+4. On `DELETE`, remove the rows whose `_id` is in `ids`.+5. If `ids` is null, run the initial load again.+6. In `useImplementationRealtime`, replace the 4 `postgres_changes` listeners with 4 `useRealtime` calls.++**Verify:**+```bash+grep -rn "postgres_changes" apps/erp/app/hooks/useNotifications.tsx apps/erp/app/hooks/useImplementationRealtime.tsx | wc -l+# Expected: 0+pnpm exec turbo run typecheck --filter=erp --concurrency=1+# Expected: 0 errors+```++**Out of scope:** `markMessageAsRead` and the digest loader.++---++## Task 17: Declare `handle.realtime` on the routes and convert the subscribers++**Depends on:** Task 13+**Files:**+- Modify: each route layout or page under the folders in the spec's "Operational routes" list+- Modify: each route under `apps/mes/app/routes/x+` that has a `loader` and a default export+- Modify: the 41 files that `grep -rlE "useRealtime\(|useDebouncedRealtime\(|useRealtimeChannel\(" apps` prints+- Modify: `apps/erp/app/types/` — add `realtime?: RealtimeTable[]` to the `Handle` type++**Steps:**+1. For each route, list the tables that its `loader` reads. Follow each service function to its `.from("…")` call.+2. If the loader reads a view, list the base tables that the page must follow.+3. Add `realtime: [...]` to the route's `handle`. Merge it with an existing `breadcrumb` or `module` key.+4. If a table is not in `REALTIME_TABLES`, add it there and add its `attach_statement_handler` line to a new migration `realtime-broadcast-attach-2`.+5. Set the ERP job layout `x+/job+/$jobId.tsx` to `["job", "jobOperation", "jobMaterial", "jobMakeMethod", "jobOperationStep", "jobOperationStepRecord", "productionEvent", "pickingListLine", "modelUpload"]`.+6. For each of the 41 subscriber files: if the file is a route, delete its `useRealtime` call and use `handle.realtime`.+7. If the file is a component that only revalidates, keep `useRealtime(table, filter)`.+8. If the file reads `payload.new` or `payload.old`, read the rows by `ids` through `carbon.from(table).select().in("id", ids)`.+9. `JobBillOfProcess.tsx` has 3 channels. Convert the `productionEvent` and `jobOperationNote` channels by step 8. Delete the `bop-steps` channel.+10. Delete each `companyId` guard on a payload row. The topic carries the company.+11. Run the check of Task 7. Fix each finding.++**Verify:**+```bash+grep -rn "postgres_changes" apps packages --include="*.ts" --include="*.tsx" | grep -v node_modules | grep -v "realtime-table-has-trigger" | wc -l+# Expected: 0+pnpm --filter @carbon/checks exec vitest run+# Expected: all passed, 0 findings for realtime-table-has-trigger+pnpm exec turbo run typecheck --filter=erp --concurrency=1+pnpm exec turbo run typecheck --filter=mes --concurrency=1+# Expected: 0 errors each+```++**Out of scope:** routes under settings, users, account, accounting, people, resources, documents, templates and workflows that have no subscription today. If step 4 adds more than 15 tables, STOP and report the list.++---++## Task 18: Add `useLoaderQuery` and migrate the `.load()` call sites++**Depends on:** Task 11+**Files:**+- Create: `packages/react/src/hooks/useLoaderQuery.ts`+- Modify: each file that `grep -rlE "\.load\(" apps/erp/app apps/mes/app` prints (137 call sites)++**Steps:**+1. Write `useLoaderQuery<L>(url: string | null, options?)`. It calls `useQuery` with the key `["loader", companyId, pathname, search]`.+2. The `queryFn` fetches `<url>` with `.data` handling equal to `fetcher.load`: use `fetch(url)` and `res.json()` for `api+` routes.+3. If `url` is null, set `enabled: false`.+4. Migrate one module first: `apps/erp/app/components/Form/` (the pickers). Run the browser check of Task 21 step 2 on it.+5. Then migrate each remaining call site where the URL is under `path.to.api`.+6. Replace `fetcher.data` with `data`, and `fetcher.state === "loading"` with `isPending`.+7. Leave a call site on `useFetcher` if its URL is a page route. Add no comment.++**Verify:**+```bash+grep -rnE "\.load\(path\.to\.api" apps/erp/app apps/mes/app | wc -l+# Expected: 0+pnpm exec turbo run typecheck --filter=erp --concurrency=1+# Expected: 0 errors+```++**Out of scope:** suspense variants and `refetchInterval`. If an `api+` route returns a turbo-stream body that `res.json()` cannot read, STOP and report.++---++## Task 19: Add `useAction` and migrate the submit call sites++**Depends on:** Task 13+**Files:**+- Create: `packages/react/src/hooks/useAction.ts`, `packages/react/src/hooks/useAction.test.tsx`+- Modify: each file that `grep -rlE "fetcher\w*\.submit\(" apps/erp/app apps/mes/app` prints++**Steps:**+1. Write `useAction<A>({ onSuccess?, onError?, key? })`. It wraps `useFetcher<A>({ key })`.+2. Return `{ submit, Form, data, isPending, pending }`. `pending` is `fetcher.formData`.+3. Call `onSuccess(data)` one time when the state returns to `idle` with data whose `success` is not false.+4. Call `onError(data)` one time when the data has `success === false` or an `error` key.+5. Hold the callbacks in refs, so a new closure on each render fires nothing.+6. Test 3 cases with `createRoutesStub`: success, error, and a second submit that fires `onSuccess` again.+7. Migrate `apps/erp/app/modules/sales` first. Run its playbooks under `.ai/playbooks/` before you continue.+8. Then migrate each file where an effect reads `fetcher.data` or `fetcher.state` to close, toast or navigate.+9. Delete the effect. Move its body into `onSuccess` or `onError`.+10. Leave a call site on `useFetcher` if no effect reads its result.++**Verify:**+```bash+pnpm --filter @carbon/react exec vitest run src/hooks/useAction.test.tsx+# Expected: 3 tests passed+pnpm --filter @carbon/checks exec vitest run src/conformance/no-unguarded-submit.test.ts+# Expected: passed+pnpm exec turbo run typecheck --filter=erp --concurrency=1+pnpm exec turbo run typecheck --filter=mes --concurrency=1+# Expected: 0 errors each+```++**Out of scope:** `ValidatedForm` and `packages/form`. Optimistic cache writes. The MES "Complete Batch" fetcher owner (`.ai/lessons.md` line 1994) keeps its place in `JobOperation`.++---++## Task 20: Update the rules, the lessons and the `AGENTS.md` files++**Depends on:** Tasks 12, 15, 17, 19+**Files:**+- Modify: `.claude/rules/clientAction-patterns.md` — rewrite for `cachedClientLoader` and the middleware+- Modify: `.claude/rules/coding-conventions.md` — the State section+- Create: `.claude/rules/realtime-system.md` — topics, the 3 functions, `handle.realtime`, `useLiveList`, the check+- Modify: `.claude/rules/event-system.md`, `.claude/rules/authz-manifest.md` — the 3 new managed functions (37 → 40)+- Modify: `.ai/lessons.md` — 2 lessons+- Modify: `packages/react/AGENTS.md`, `packages/database/AGENTS.md`, `AGENTS.md` (Task Router row for realtime)+- Modify: the spec — status `implemented`, changelog entry++**Steps:**+1. Write the lesson "a subscription to an unpublished table fails silently" in the `Context → Problem → Rule → Applies to` format.+2. Write the lesson "`getCompanyId()` read an httpOnly cookie and always returned null".+3. In each rule, describe committed code only.+4. Do the STE-80 review pass on the spec after the edit.++**Verify:**+```bash+grep -rn "window.clientCache?.setQueryData\|nanostores\|postgres_changes" .claude/rules | wc -l+# Expected: 0+```++**Out of scope:** product docs under `docs/`. The change adds no user-facing feature that needs a page.++---++## Task 21: Run the full verification and the browser tests++**Depends on:** all tasks+**Files:**+- Create: `.ai/playbooks/realtime-broadcast.md` (through `/test`)+- Modify: `.ai/runs/2026-10-04-realtime-broadcast.md` — results++**Steps:**+1. Run `pnpm run lint`, `pnpm run test`, and the 5 scoped typechecks of the spec, one at a time.+2. Run `/auth`, then `/test` with these 8 checks:+3. Complete an operation in the MES. The ERP job page shows it as complete within 3 seconds, with no reload.+4. Add a customer type in tab A. The picker in tab B shows it within 3 seconds.+5. Reload with no data change. The network log shows 1 `list_checksums` call and 0 calls to `item`, `supplier`, `customer`, `employees`, `itemSupersession`.+6. Rename a customer in tab A, close tab B first, then open tab B. The log shows a `customer` fetch only.+7. Send a notification to the user. The bell shows it within 3 seconds.+8. Switch company. No item, customer or cached list of the first company shows.+9. Run the MES "Complete Batch" flow. The redirect to the operations page happens.+10. Open the ERP job page, the sales order page and the MES operations page. The console shows 0 realtime errors.+11. Run `/self-review`.++**Verify:**+```bash+pnpm run lint && pnpm run test+# Expected: exit 0+```++**Out of scope:** a push or a pull request. Ask the user before each one.diff --git a/.ai/research/2026-10-01-client-cache-on-react-router.md b/.ai/research/2026-10-01-client-cache-on-react-router.mdnew file mode 100644index 0000000000..ce2099ce7d--- /dev/null+++ b/.ai/research/2026-10-01-client-cache-on-react-router.md@@ -0,0 +1,78 @@+# Client cache on React Router — internals and libraries++Date: 2026-10-01. Question: can a TanStack Query–backed cache be tied tightly to React+Router so routes never manage query keys, and is there a library to build on?++Carbon today: `react-router` 7.18.0, React 18.3.1, `@tanstack/react-query` 5.97.0.++## React Router internals (read from the installed 7.18.0 source and bundled docs)++| Fact | Where | Consequence |+|---|---|---|+| Every loader read is `fetch("<path>.data?_routes=…")` through the global `fetch` | `fetchAndDecodeViaTurboStream` | The URL fully identifies the data; a URL is a usable cache key |+| A route with a `clientLoader` leaves the combined request; its `serverLoader()` sends its own `.data?_routes=<routeId>` | `singleFetchLoaderNavigationStrategy` | Caching through `clientLoader` costs one request per cached route on a miss, each authenticating separately on the server |+| `fetcher.load` is one request for one route | `singleFetchLoaderFetcherStrategy` | Selector reads are already per-route; nothing is lost by caching them through `clientLoader` |+| `dataStrategy` is data-mode only. In framework mode it is hard-wired inside `createHydratedRouter`; `HydratedRouter` takes only `getContext`, `onError`, `instrumentations` | `dom-export.mjs`, `docs/how-to/data-strategy.md` | The seam React Router itself calls "the foundation to build … caching layers" is closed to us without forking `HydratedRouter` on `UNSAFE_createRouter` + `UNSAFE_getTurboStreamSingleFetchDataStrategy` |+| Instrumentations are read-only by design | `docs/how-to/instrumentation.md` | They can observe navigations, loaders and actions (invalidation triggers, metrics); they cannot serve cached data |+| `defaultShouldRevalidate` is stable since 7.15 on `<Link>`, `<Form>`, `useSubmit`, `fetcher.submit`, `setSearchParams` | changelog, `.d.mts` | A single submit or link can skip revalidation without route code — e.g. inline cell edits |+| The official client-cache example is URL-keyed: `generateKey(request)` in `clientLoader`, delete in `clientAction` | `docs/how-to/client-data.md` | Keying by URL is the documented pattern, not a hack |+| Route `headers` apply to `.data` responses | `singleFetchLoaders` → `getDocumentHeaders` | A route can state cache policy in a header |+| `pattern` in loader args is the matched leaf pattern | `.d.mts` | Good for tracing, not a per-route identity |+| The router is reachable at `window.__reactRouterDataRouter` | `dom-export.mjs` | `revalidate()`, `subscribe()`, `state.revalidation` are available outside React |++### Version risk++React Router 8.0.0 shipped 2026-06-17: React 19.2.7+, Node 22.22+, Vite 7+, ESM-only, all+`v8_*` flags default. The changelog lists no change to the `.data` wire format or+`clientLoader`. 8.4.0 reworked the internal data-router contexts. Carbon is on the last 7.x+and React 18, so anything built on `UNSAFE_*` exports or the wire format has to survive+that upgrade.++## Libraries++| Library | Version, last publish | What it is | Fit |+|---|---|---|---|+| `remix-client-cache` | 3.0.0, 2025-04-27, peer `react-router ^7` | `clientLoader` cache. Default key is `pathname + search + hash`. Stale-while-revalidate by default: returns cached data plus a deferred promise and hot-swaps. Pluggable storage adapters | Closest to "no keys, tied to React Router". But no staleness or TTL, no in-flight dedupe, no awareness of actions; invalidation is manual by key; components must use its own hook. Unpublished for ~18 months. Useful as a ~200-line reference, not as a dependency |+| `@tanstack/query-core` | 5.104.0, 2026-09-26 | The headless engine Carbon already uses | Keep as the engine. Persistence (`query-persist-client-core`) and cross-tab sync (`query-broadcast-client-experimental`) exist as add-ons |+| `@tanstack/db` + `@tanstack/query-db-collection` | 0.11.0 / 1.3.1, 2026-09-30 | Collections, live queries, optimistic writes. Sync modes: eager, on-demand ("the component's query becomes the API call"), progressive | One key per collection instead of per query. Active but pre-1.0 |+| `@supabase-labs/tanstack-db` | 0.1.0, 2026-09-25 | Supabase's TanStack DB collection: PostgREST reads from the browser, Realtime sync, optimistic writes, RLS applies | A direct replacement for `RealtimeDataProvider`. Alpha: no SSR, Realtime usage "still being stabilized", offset paging can skip rows, 1,000-row cap on some reads |+| `@supabase-cache-helpers/postgrest-react-query` | 1.13.9, 2026-03-12 | Derives keys from the PostgREST query; updates cached queries after mutations | Only for browser-side supabase-js reads and its own mutation hooks |+| oRPC / tRPC TanStack utilities | — | Keys derived from the procedure path; `queryOptions()` usable in loaders | Needs an RPC layer over the services. A large change |+| `@epic-web/cachified` | 5.6.3, 2026-07-02 | Server-side TTL and stale-while-revalidate over any store, including Redis | Would replace hand-written Redis get/set such as the plan and changelog caches |+| `@remix-pwa/sw` | 3.0.10, 2025-03-08, peers on Remix v2 | Service-worker caching of loader requests | Not usable on React Router 7 |+| `@lukemorales/query-key-factory` | 1.3.4, 2024-02-25 | Key registry helper | Stale, and it is the thing we want to stop maintaining |++No maintained library does wire-level caching of `.data` requests for React Router 7.++## What this changes++1. **Reference lists (`api+` loaders):** a URL-keyed `clientLoader` factory on query-core is+ the documented React Router pattern plus the two things `remix-client-cache` lacks,+ staleness and dedupe. About 40 lines of our own; no dependency. Selector reads are+ already one request per route, so the per-route request cost does not apply.+2. **Realtime lists (items, customers, suppliers, people):** `@supabase-labs/tanstack-db` is+ the first library that does what `RealtimeDataProvider` hand-rolls. It is two weeks old+ and alpha, so it is a spike candidate, not an adoption.+3. **Page data:** caching it through `clientLoader` splits one request into many, and the+ proper seam (`dataStrategy`) is closed in framework mode. Leave page data uncached.+4. **New lever:** `defaultShouldRevalidate={false}` at the call site for mutations that+ cannot change anything else on screen.++## Open++- The July client-cache spec (`.ai/specs/2026-07-23-client-query-cache.md`) is not on this+ branch. It rejected a URL-keyed middleware; its reasons need checking against item 1.+- Whether a factory-returned `clientLoader` with `.hydrate = true` is picked up correctly.+- Supabase Realtime cost and RLS behaviour for the alpha collection under multi-tenant load.++## Sources++- React Router changelog — https://reactrouter.com/changelog+- React Router docs bundled in the package (`node_modules/react-router/docs`): `how-to/client-data.md`, `how-to/data-strategy.md`, `how-to/instrumentation.md`+- Call-site revalidation opt-out — https://github.com/remix-run/react-router/pull/14542+- React Router + TanStack Query discussion — https://github.com/remix-run/react-router/discussions/12944+- remix-client-cache — https://github.com/forge-42/remix-client-cache/blob/main/README.md+- TanStack DB — https://tanstack.com/db/latest/docs/overview , https://tanstack.com/blog/tanstack-db-0.5-query-driven-sync+- Supabase TanStack DB collection — https://github.com/supabase/tanstack-db+- oRPC TanStack Query integration — https://orpc.dev/docs/integrations/tanstack-query+- npm registry (`pnpm view`) for versions and publish dates, 2026-10-01diff --git a/.ai/research/2026-10-01-route-loader-audit.md b/.ai/research/2026-10-01-route-loader-audit.mdindex c779e2accf..ef0ade17c2 100644--- a/.ai/research/2026-10-01-route-loader-audit.md+++ b/.ai/research/2026-10-01-route-loader-audit.md@@ -290,7 +290,7 @@ uses it too. It cannot wrap `getCompanySettings` as written, because that lives| `x+/priority+/people.tsx` | Reads a cookie for its default scope; its only child is an action route, so there is no child navigation to save. || `share+/customer.$id.tsx` | Public portal layout; its loader is the access and plan gate, so it stays evaluated on every navigation. || `api+` / webhook routes in the "layout" count | Resource routes, not navigations — false positives of the file-name heuristic. |-| N+1 inside `getPartUsedIn` | Still ~15 queries per item; it now streams and no longer repeats per tab click, but batching it across items is its own change. |+| N+1 inside `getPartUsedIn` | Fixed 2026-10-05: one `get_item_used_in` RPC per item. Was ~15 queries per item; it now streams and no longer repeats per tab click, but batching it across items is its own change. |## Suggested order (as written before the fixes)diff --git a/.ai/runs/2026-10-04-realtime-broadcast.md b/.ai/runs/2026-10-04-realtime-broadcast.mdnew file mode 100644index 0000000000..36c88d8901--- /dev/null+++ b/.ai/runs/2026-10-04-realtime-broadcast.md@@ -0,0 +1,85 @@+# Realtime broadcast — run log++**Plan:** .ai/plans/2026-10-04-client-query-cache-and-realtime-broadcast.md+**Stack:** local, Realtime v2.89.0, satellite demo dataset (37 items, 119 job operations)++## 2026-10-05 — spike and database tasks++| Check | Result |+|-------|--------|+| The 2 migrations apply on a new database | Pass. `crbn up` applied all 1,099 migrations. |+| `authz sync` after the migrations | Pass. A second `authz check` reports 0 helpers and 0 tables to change. |+| `realtime.messages` policies | Pass. `company topic` and `user topic`, both `SELECT` for `authenticated`. |+| Triggers | Pass. 261 broadcast triggers: 87 tables, 3 operations each. |+| `supabase_realtime` publication | Pass. It holds 0 tables. |+| `realtime-broadcast.test.sql` | Pass. |+| A client joins its own company topic on a private channel | Pass. Status `SUBSCRIBED`. |+| A client joins the topic of another company | Pass. Realtime answers `Unauthorized`. |+| A client joins the notification topic of another user | Pass. Realtime answers `Unauthorized`. |+| A client receives the message for an `UPDATE` of `customer` | Pass on the second run. See the note below. |++## Measurements++| Statement | Broadcast trigger time | Whole statement |+|-----------|------------------------|-----------------|+| `UPDATE` of 1 `jobOperation` row | 1.3 ms | 3.5 ms |+| `UPDATE` of 37 `item` rows | 1.1 ms | 13.3 ms |+| `list_checksums` for the demo company | not applicable | 4.8 ms |++The demo company is small. These numbers do not show the cost on a large company.++## Note: the first message after the first private join++Realtime creates its replication slot for `realtime.messages` when the first+private channel joins. In the first spike run, the client did not receive a+message that Postgres sent 6 seconds after that first join. In the second run,+the slot existed and the client received the message. The catch-up on+`onSubscribed` does not cover this case, because the join itself succeeds.+The cause is not confirmed. Test it again in Task 21.++## 2026-10-05 — change log replaces the checksum++| Check | Result |+|-------|--------|+| `realtime-broadcast.test.sql` with the change-log assertions | Pass. |+| `authz check` after the sync | Pass. 0 helpers, 0 tables, 0 event triggers. |+| Reload with no change | Pass. 1 `table_changes_since` request, 0 table requests. |+| Rename 1 customer while the tab is closed, then open the app | Pass. 1 `table_changes_since` request and 1 `customer` request with `id=in.(<that id>)`. |+| Rename 1 customer while the tab is open | Pass. The cached list shows the new name within 3 seconds. |++Not measured: the cost of the log insert on a write, and the reader on a large company.++## 2026-10-05 — final verification++Automated gates:++| Gate | Result |+|------|--------|+| `pnpm run lint` | Pass. 35 tasks. |+| `pnpm run test` with the local database | Pass. 33 tasks. |+| Typecheck: `erp`, `mes`, `@carbon/query`, `@carbon/react`, `@carbon/auth`, `@carbon/database`, `@carbon/checks`, `@carbon/jobs`, `@carbon/viewer` | Pass. Each one ran alone. |+| `realtime-broadcast.test.sql` | Pass. |+| `authz check` | Pass. 0 helpers, 0 tables, 0 event triggers. |++Browser checks on the local stack (ERP and MES dev servers, satellite demo company):++| Check | Result |+|-------|--------|+| An operator finishes an operation in the MES. The ERP job page in a second tab shows status `Done` with no reload. | Pass. The ERP tab revalidated 1 time. The MES redirected to the operations list. |+| A change to a job operation shows on the ERP bill of process within 3 seconds. | Pass. |+| The ERP sales orders list and the MES operations page revalidate 1 time for 1 change. | Pass. |+| Reload with no change: 1 `table_changes_since` request, 0 table requests. | Pass. |+| Rename 1 customer while the tab is closed: 1 read of that row only. | Pass. |+| A new notification shows in the bell with no reload. | Pass. The count went to 1 and the inbox showed the row. |+| Another writer adds a customer type while a form is open. The picker list updates. | Pass. 4 rows became 5 with 1 refetch. |+| Save a storage unit. The cached storage-unit list refetches with the new name. | Pass. The route has no `clientAction`. |+| A setting saved through `useAction` shows its toast 1 time. | Pass. |+| The 5 module dashboards load their KPI queries. | Pass. |++Not checked:++- Company switch. The local stack has 1 company.+- The MES "Complete Batch" flow. The demo data has no active batch.+- Two signed-in users at the same time. The second writer was a SQL statement.+- `/self-review` has not run on the branch.+- The first message after the first private join on a new Realtime server. It failed 1 time and was not reproduced.diff --git a/.ai/specs/2026-10-04-client-query-cache-and-realtime-broadcast.html b/.ai/specs/2026-10-04-client-query-cache-and-realtime-broadcast.htmlnew file mode 100644index 0000000000..807e025366--- /dev/null+++ b/.ai/specs/2026-10-04-client-query-cache-and-realtime-broadcast.html@@ -0,0 +1,317 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta name="viewport" content="width=device-width, initial-scale=1" />+<meta name="explain-source" content=".ai/specs/2026-10-04-client-query-cache-and-realtime-broadcast.md" />+<meta name="explain-source-hash" content="4d8339e93dbb001ace309331fc30e994c0f99591" />+<title>Client cache and realtime</title>+<style>+ :root {+ --bg: #fbfbf9; --panel: #ffffff; --ink: #262323; --faint: #6b6764;+ --hairline: #e3e2de; --accent: #1e84b0; --accent-soft: #dff5ff;+ --warn: #a3520f; --warn-soft: #fff1e0; --ok: #2c7a14; --ok-soft: #e4f8da;+ --code-bg: #efefeb;+ }+ @media (prefers-color-scheme: dark) {+ :root {+ --bg: #141416; --panel: #1c1c1f; --ink: #ececea; --faint: #a3a19c;+ --hairline: #2e2e33; --accent: #5cc2ee; --accent-soft: #10303f;+ --warn: #f0a35e; --warn-soft: #3a2614; --ok: #8fd672; --ok-soft: #1b3112;+ --code-bg: #26262a;+ }+ }+ * { box-sizing: border-box; }+ body { margin: 0; background: var(--bg); color: var(--ink);+ font: 16px/1.65 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; }+ main { max-width: 880px; margin: 0 auto; padding: 48px 16px 96px; }+ h1 { font-size: 30px; line-height: 1.2; margin: 8px 0 12px; }+ h2 { font-size: 20px; margin: 56px 0 12px; padding-top: 24px; border-top: 1px solid var(--hairline); }+ h3 { font-size: 16px; margin: 24px 0 8px; }+ p, li { max-width: 72ch; }+ a { color: var(--accent); }+ code { font: 13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;+ background: var(--code-bg); border-radius: 4px; padding: 1px 5px; }+ .kicker { color: var(--faint); font-size: 13px; letter-spacing: .06em; text-transform: uppercase; }+ .tldr { font-size: 18px; border-left: 3px solid var(--accent); padding: 4px 0 4px 16px; margin: 0; }+ .callout { border-radius: 10px; padding: 12px 16px; margin: 16px 0; border: 1px solid var(--hairline); }+ .callout.example { background: var(--accent-soft); }+ .callout.warn { background: var(--warn-soft); }+ .callout .label { display: block; font-size: 11px; font-weight: 700; letter-spacing: .08em;+ text-transform: uppercase; color: var(--faint); margin-bottom: 4px; }+ ol.steps { padding-left: 0; list-style: none; counter-reset: s; }+ ol.steps li { counter-increment: s; position: relative; padding: 8px 0 8px 44px; }+ ol.steps li::before { content: counter(s); position: absolute; left: 0; top: 8px; width: 28px; height: 28px;+ border-radius: 50%; background: var(--accent-soft); color: var(--accent);+ font-weight: 700; font-size: 14px; display: grid; place-items: center; }+ figure { margin: 20px 0; background: var(--panel); border: 1px solid var(--hairline);+ border-radius: 12px; padding: 16px; overflow-x: auto; }+ figcaption { color: var(--faint); font-size: 14px; margin-top: 8px; }+ /* SVG diagram primitives — use these classes, never inline colors */+ svg.diagram { display: block; width: 100%; height: auto; min-width: 560px; }+ svg .box { fill: var(--panel); stroke: var(--hairline); stroke-width: 1.5; }+ svg .box.hot { stroke: var(--accent); stroke-width: 2.5; fill: var(--accent-soft); }+ svg .box.new { stroke: var(--ok); stroke-width: 2; fill: var(--ok-soft); }+ svg .box.risk { stroke: var(--warn); stroke-width: 2; fill: var(--warn-soft); }+ svg .lane { fill: none; stroke: var(--hairline); stroke-dasharray: 4 4; }+ svg .edge { fill: none; stroke: var(--faint); stroke-width: 1.5; }+ svg .edge.hot { stroke: var(--accent); stroke-width: 2.5; }+ svg text { fill: var(--ink); font: 14px ui-sans-serif, system-ui, sans-serif; }+ svg text.small { fill: var(--faint); font-size: 12px; }+ svg text.mono { font-family: ui-monospace, Menlo, monospace; font-size: 13px; }+ svg marker path { fill: var(--faint); }+ svg marker.hot path { fill: var(--accent); }+ /* Tabs (before / after) */+ .tabs { border: 1px solid var(--hairline); border-radius: 12px; background: var(--panel); margin: 16px 0; }+ .tabs [role=tablist] { display: flex; gap: 4px; padding: 8px; border-bottom: 1px solid var(--hairline); }+ .tabs button { font: inherit; font-size: 14px; border: 0; background: none; color: var(--faint);+ padding: 6px 12px; border-radius: 8px; cursor: pointer; }+ .tabs button[aria-selected=true] { background: var(--accent-soft); color: var(--accent); font-weight: 600; }+ .tabs [role=tabpanel] { padding: 12px 16px; }+ .tabs [role=tabpanel][hidden] { display: none; }+ /* Decisions */+ details { border: 1px solid var(--hairline); border-radius: 10px; background: var(--panel); margin: 8px 0; }+ details > summary { cursor: pointer; padding: 10px 14px; list-style: none; }+ details > summary::-webkit-details-marker { display: none; }+ details > summary::before { content: "▸"; color: var(--faint); margin-right: 8px; display: inline-block; transition: transform .15s; }+ details[open] > summary::before { transform: rotate(90deg); }+ details > div { padding: 0 14px 12px 34px; }+ .choice { font-weight: 600; }+ .rejected { color: var(--faint); }+ .tag { display: inline-block; font-size: 11px; font-weight: 700; letter-spacing: .06em; text-transform: uppercase;+ border-radius: 999px; padding: 1px 8px; margin-left: 6px; vertical-align: 2px; }+ .tag.human { background: var(--ok-soft); color: var(--ok); }+ .tag.assumed { background: var(--warn-soft); color: var(--warn); }+ table { border-collapse: collapse; width: 100%; margin: 12px 0; font-size: 14px; }+ th, td { text-align: left; border-bottom: 1px solid var(--hairline); padding: 8px 10px; vertical-align: top; }+ th { color: var(--faint); font-weight: 600; }+ .table-wrap { overflow-x: auto; }+ ul.checks { list-style: none; padding-left: 0; }+ ul.checks li { padding: 6px 0 6px 28px; position: relative; }+ ul.checks li::before { content: "☐"; position: absolute; left: 0; color: var(--accent); }+ dl.terms dt { font-weight: 600; margin-top: 12px; }+ dl.terms dd { margin: 2px 0 0 0; color: var(--faint); max-width: 72ch; }+ footer { margin-top: 64px; color: var(--faint); font-size: 13px; border-top: 1px solid var(--hairline); padding-top: 16px; }+</style>+</head>+<body>+<main>++ <header>+ <p class="kicker">Spec · in-progress · 2026-10-04 · <code>.ai/specs/2026-10-04-client-query-cache-and-realtime-broadcast.md</code></p>+ <h1>Client query cache and realtime broadcast</h1>+ <p class="tldr">Cached lists never go stale, pages miss changes, and each cold load fetches five whole tables. The ERP and the MES get one client cache and one realtime system that Postgres drives by broadcast. Operational pages update live in both apps, and a cold load with no change fetches no table.</p>+ </header>++ <section>+ <h2>The picture</h2>+ <figure>+ <svg class="diagram" viewBox="0 0 800 470" role="img" aria-label="Five rows show each old mechanism on the left and the mechanism that replaces it on the right.">+ <defs>+ <marker id="arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" /></marker>+ </defs>+ <text x="40" y="53">Reference lists</text><rect class="box risk" x="240" y="20" width="160" height="56" rx="8" /><text x="320" y="45" text-anchor="middle">27 clientLoaders</text><text class="small" x="320" y="64" text-anchor="middle">hand-written</text><path class="edge" d="M400,48 L438,48" marker-end="url(#arrow)" /><rect class="box new" x="440" y="20" width="160" height="56" rx="8" /><text x="520" y="53" text-anchor="middle">cachedClientLoader</text>+<text x="40" y="143">Reference lists</text><rect class="box risk" x="240" y="110" width="160" height="56" rx="8" /><text x="320" y="135" text-anchor="middle">78 clientActions</text><text class="small" x="320" y="154" text-anchor="middle">invalidations</text><path class="edge" d="M400,138 L438,138" marker-end="url(#arrow)" /><rect class="box new" x="440" y="110" width="160" height="56" rx="8" /><text x="520" y="135" text-anchor="middle">Root middleware</text><text class="small" x="520" y="154" text-anchor="middle">invalidation</text>+<text x="40" y="233">Page updates</text><rect class="box risk" x="240" y="200" width="160" height="56" rx="8" /><text x="320" y="225" text-anchor="middle">postgres_changes</text><text class="small" x="320" y="244" text-anchor="middle">per page</text><path class="edge" d="M400,228 L438,228" marker-end="url(#arrow)" /><rect class="box new" x="440" y="200" width="160" height="56" rx="8" /><text x="520" y="225" text-anchor="middle">Broadcast trigger</text><text class="small" x="520" y="244" text-anchor="middle">per table</text><path class="edge" d="M600,228 L638,228" marker-end="url(#arrow)" /><rect class="box new" x="640" y="200" width="160" height="56" rx="8" /><text x="720" y="225" text-anchor="middle">handle.realtime</text><text class="small" x="720" y="244" text-anchor="middle">on the route</text>+<text x="40" y="323">Realtime lists</text><rect class="box risk" x="240" y="290" width="160" height="56" rx="8" /><text x="320" y="315" text-anchor="middle">nanostores</text><text class="small" x="320" y="334" text-anchor="middle">5 table fetches</text><path class="edge" d="M400,318 L438,318" marker-end="url(#arrow)" /><rect class="box hot" x="440" y="290" width="160" height="56" rx="8" /><text x="520" y="315" text-anchor="middle">useLiveList</text><text class="small" x="520" y="334" text-anchor="middle">in query cache</text><path class="edge" d="M600,318 L638,318" marker-end="url(#arrow)" /><rect class="box new" x="640" y="290" width="160" height="56" rx="8" /><text x="720" y="315" text-anchor="middle">Checksum</text><text class="small" x="720" y="334" text-anchor="middle">skips the fetch</text>+<text x="40" y="413">Component hooks</text><rect class="box risk" x="240" y="380" width="160" height="56" rx="8" /><text x="320" y="405" text-anchor="middle">useFetcher</text><text class="small" x="320" y="424" text-anchor="middle">with effects</text><path class="edge" d="M400,408 L438,408" marker-end="url(#arrow)" /><rect class="box new" x="440" y="380" width="160" height="56" rx="8" /><text x="520" y="405" text-anchor="middle">useLoaderQuery</text><text class="small" x="520" y="424" text-anchor="middle">and useAction</text>++ </svg>+ <figcaption>Read each row left to right. The orange box is the old mechanism. The green boxes are new, and the blue box is changed.</figcaption>+ </figure>+ </section>++ <section>+ <h2>The problem</h2>+ <p>The 27 cached <code>api+</code> routes read with <code>getQueryData</code>, which ignores <code>staleTime</code> and <code>invalidateQueries</code>. So a cached list never goes stale. 78 route files each export a <code>clientAction</code> that names the keys to invalidate.</p>+ <p>A page can miss the changes of a table it shows. <code>RealtimeDataProvider</code> reads five whole tables from the browser on each cold load, about 950 ms each.</p>+ <p><code>postgres_changes</code> does one permission check for each subscriber for each change, on one thread for all tenants.</p>+ <div class="callout example">+ <span class="label">Example</span>+ <p>Jane Doe completes an operation for job J-001 in the MES. The ERP job page has no subscription on <code>jobOperation</code> or <code>job</code>. So the planner sees the old status until a reload.</p>+ </div>+ </section>++ <section>+ <h2>How it works</h2>+ <h3>Part 1 — Query cache</h3>+ <ol class="steps">+ <li>A cached <code>api+</code> route exports <code>cachedClientLoader<typeof loader>()</code>.</li>+ <li>The loader reads with <code>fetchQuery</code>, so <code>staleTime</code> and in-flight dedupe apply.</li>+ <li>One root middleware runs after each request.</li>+ <li>If the method is <code>GET</code> or the path is <code>/refresh-session</code>, the middleware does nothing.</li>+ <li>Otherwise the middleware marks every <code>LOADER</code> entry stale.</li>+ </ol>+ <h3>Part 2 — Realtime by broadcast</h3>+ <ol class="steps">+ <li>A statement trigger calls <code>broadcast_table_changes</code>.</li>+ <li>The function sends <code>{ table, op, ids }</code> to the private topic <code>company:<companyId>:<table></code>.</li>+ <li>A policy on <code>realtime.messages</code> lets only an employee of that company join the topic.</li>+ <li>A route declares its tables in <code>handle.realtime</code>.</li>+ <li><code>useRouteRealtime()</code> in the shell subscribes to one channel for each declared table.</li>+ <li>On a message, the hook starts a 300 ms debounce timer.</li>+ <li>If a fetcher is submitting when the timer ends, the hook waits for it.</li>+ <li>The hook marks the <code>LOADER</code> entries stale. Then it revalidates the page.</li>+ </ol>+ <details>+ <summary>Reference lists and notifications</summary>+ <div>+ <p>The tables behind the cached reference lists use <code>broadcast_reference_changes</code>. It sends <code>{ table, op }</code> to one shared topic, <code>company:<companyId>:reference</code>. The shell marks the <code>LOADER</code> entries stale on each message.</p>+ <p><code>useNotifications</code> subscribes to <code>user:<userId>:notification</code>. On an <code>INSERT</code> or <code>UPDATE</code>, the hook reads the rows with those ids through PostgREST. On a <code>DELETE</code>, the hook removes the rows with those ids.</p>+ <p><code>useRealtime(table, filter?)</code> stays for a component that is not a route. If the filter names <code>id</code>, the hook compares the message ids with the filter ids. If the filter names another column, the hook wakes on any change to the table.</p>+ </div>+ </details>+ <h3>Part 3 — Live lists, cold load</h3>+ <ol class="steps">+ <li><code>useLiveList</code> reads the list and its checksum from IndexedDB.</li>+ <li>The hook puts the list in the query cache.</li>+ <li>The hook calls the <code>list_checksums</code> function.</li>+ <li>If the checksum matches, the app fetches nothing.</li>+ <li>If the checksum differs, the hook fetches the list in full.</li>+ <li>The hook writes the list and the new checksum to IndexedDB.</li>+ </ol>+ <details>+ <summary>What a broadcast message does to a list</summary>+ <div>+ <p>If <code>ids</code> is null, the hook runs the checksum steps again. If <code>op</code> is <code>DELETE</code>, the hook removes those rows from the cache. Otherwise the hook reads those rows through PostgREST, merges them, sorts, and writes the list to IndexedDB. A reconnect runs the checksum steps again.</p>+ </div>+ </details>+ <h3>Part 4 — Component hooks</h3>+ <ol class="steps">+ <li><code>useLoaderQuery(url)</code> reads an <code>api+</code> URL through <code>useQuery</code>, on the same key as the loader.</li>+ <li><code>useAction({ onSuccess, onError })</code> wraps <code>useFetcher</code>. It returns <code>submit</code>, <code>isPending</code>, <code>data</code> and <code>pending</code>.</li>+ </ol>+ </section>++ <section>+ <h2>Before and after</h2>+ <div class="tabs" data-tabs>+ <div role="tablist">+ <button role="tab" aria-selected="true">Before</button>+ <button role="tab" aria-selected="false">After</button>+ </div>+ <div role="tabpanel">+ <ol>+ <li>Reference lists: a cached route keeps its first result for the whole session.</li>+ <li>Mutations: each of 78 routes names the keys to invalidate. A route that forgets one leaves a stale dropdown.</li>+ <li>Page updates: the ERP job page does not show an operation that the MES completed, until a reload.</li>+ <li>Realtime lists: each cold load reads <code>item</code>, <code>supplier</code>, <code>customer</code>, <code>employees</code> and <code>itemSupersession</code> in full.</li>+ <li>Components: 137 call sites load with a fetcher in a mount effect. 435 submit call sites use <code>useFetcher</code>.</li>+ </ol>+ </div>+ <div role="tabpanel" hidden>+ <ol>+ <li>Reference lists: an entry goes stale after <code>staleTime</code>, after a mutation, and after a change by another user.</li>+ <li>Mutations: one root middleware marks every loader entry stale. No route names a key.</li>+ <li>Page updates: the ERP job page shows the completed operation within 3 seconds, with no reload.</li>+ <li>Realtime lists: a cold load with a matching checksum sends 1 <code>list_checksums</code> request and reads no table.</li>+ <li>Components: five pickers on one page share one request. <code>useAction</code> gives the pending state with no effect.</li>+ </ol>+ </div>+ </div>+ </section>++ <section>+ <h2>Decisions</h2>+ <details><summary>How does the cache name an entry? <span class="choice">By URL: <code>[LOADER, companyId, pathname, search]</code>.</span></summary><div><p>Why: React Router's own client-cache guide keys by URL. A route author writes no key.</p></div></details>+<details><summary>What goes stale after a mutation? <span class="choice">Every <code>LOADER</code> entry.</span></summary><div><p>Why: It costs one extra fetch when a list is next used. It removes 78 hand-written invalidations and the key registry.</p></div></details>+<details><summary>Does the cache hold page data? <span class="choice">No.</span></summary><div><p>Why: A route with a <code>clientLoader</code> leaves the combined <code>.data</code> request. <code>dataStrategy</code> is closed in framework mode.</p></div></details>+<details><summary>Which realtime transport? <span class="choice">Broadcast from the database.</span></summary><div><p>Why: Realtime checks permission one time at join. <code>postgres_changes</code> checks each change for each subscriber on one thread.</p></div></details>+<details><summary>What does a message hold? <span class="choice"><code>{ table, op, ids }</code>, with ids null above 100 rows.</span></summary><div><p>Why: The client reads rows through PostgREST, so table RLS still decides what a user sees.</p></div></details>+<details><summary>How fine is a topic? <span class="choice">One topic for each company for each table.</span><span class="tag human">human</span></summary><div><p>Why: A caller with a parent-column filter wakes on any change to the table. The debounce bounds the cost.</p></div></details>+<details><summary>Which tables get a trigger? <span class="choice">Only tables that a route or a live list declares.</span><span class="tag human">human</span></summary><div><p>Why: A table that no page watches gets no write overhead and stores no messages.</p></div></details>+<details><summary>Which pages update live? <span class="choice">Operational pages in the ERP, all of the MES, and the cached reference lists.</span><span class="tag human">human</span></summary><div><p>Why: Settings and admin pages change rarely. They reload on navigation as today.</p></div></details>+<details><summary>How do reference lists hear a change? <span class="choice">One shared topic, <code>company:<companyId>:reference</code>.</span></summary><div><p>Why: One channel for each client covers every reference table. A topic for each table would hold about 30 channels open.</p></div></details>+<details><summary>Where does a trigger attach to a table? <span class="choice">In <code>event-system/attachments.ts</code>, applied by <code>set_event_triggers</code>.</span><span class="tag human">human</span></summary><div><p>Why: Each attach call replaces the whole list of a table. One typed manifest removes the clobber risk. No migration attaches a trigger.</p></div></details>+<details><summary>Where do the interceptor bodies live? <span class="choice">In managed files under <code>event-system/handlers/</code>.</span><span class="tag human">human</span></summary><div><p>Why: The 63 interceptors and <code>apply_item_stock_quantities</code> leave the migrations. <code>authz sync</code> and <code>authz migration</code> own them.</p></div></details>+<details><summary>How does a missed declaration show? <span class="choice">The new <code>realtime-table-has-trigger</code> check fails the build.</span></summary><div><p>Why: <code>postgres_changes</code> fails silently for an unpublished table.</p></div></details>+<details><summary>When do tables leave the publication? <span class="choice">In this PR.</span><span class="tag human">human</span></summary><div><p>Why: A tab on the old build goes quiet until a reload. It shows no error.</p></div></details>+<details><summary>What stays on <code>postgres_changes</code>? <span class="choice">Nothing.</span><span class="tag human">human</span></summary><div><p>Why: The publication ends empty. No second realtime system stays in the code.</p></div></details>+<details><summary>How do notifications travel? <span class="choice">A private topic for each user: <code>user:<userId>:notification</code>.</span><span class="tag human">human</span></summary><div><p>Why: A company topic would wake every employee for each notification of each other employee.</p></div></details>+<details><summary>How does a cold load avoid the table fetches? <span class="choice">A change log names the rows that changed.</span><span class="tag human">human</span></summary><div><p>Why: The client reads only the rows that changed since its stored copy. A checksum refetches a whole list when one row changes.</p></div></details>+<details><summary>Who may the checksum function read for? <span class="choice"><code>SECURITY INVOKER</code>: the calling user.</span></summary><div><p>Why: The hash must cover the rows that this user can read. The same RLS applies to the list fetch.</p></div></details>+<details><summary>Where do the lists live? <span class="choice">The query cache, key <code>["live", companyId, <list>]</code>.</span></summary><div><p>Why: One store holds the server data. nanostores has no other user after this change.</p></div></details>+<details><summary>How far does <code>useAction</code> go? <span class="choice">Pending state and callbacks only.</span><span class="tag human">human</span></summary><div><p>Why: Mutations stay plain router actions. Optimistic cache writes are out of scope.</p></div></details>+<details><summary>Where does the shared code live? <span class="choice"><code>@carbon/react</code>.</span></summary><div><p>Why: Both apps need the hooks. The <code>no-duplicated-app-file</code> check forbids a copy in each app.</p></div></details>+<details><summary>What breaks for existing users? <span class="choice">One thing: the publication drop.</span></summary><div><p>Why: The API, the MCP tools and the webhooks do not change.</p></div></details>++ </section>++ <section>+ <h2>Data model</h2>+ <p>The change adds no table and no column. It adds four functions, two policies on <code>realtime.messages</code>, and one statement trigger set for each watched table.</p>+ <figure>+ <svg class="diagram" viewBox="0 0 800 190" role="img" aria-label="Three broadcast functions send to three kinds of topic, and two policies guard who may join.">+ <rect class="box new" x="40" y="20" width="220" height="150" rx="8" />+ <text class="mono" x="56" y="46">functions</text>+ <text class="small mono" x="56" y="72">broadcast_table_changes</text>+ <text class="small mono" x="56" y="94">broadcast_reference_changes</text>+ <text class="small mono" x="56" y="116">broadcast_user_changes</text>+ <text class="small mono" x="56" y="138">list_checksums</text>+ <path class="edge" d="M260,95 L298,95" marker-end="url(#arrow2)" />+ <defs><marker id="arrow2" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" /></marker></defs>+ <rect class="box new" x="300" y="20" width="220" height="150" rx="8" />+ <text class="mono" x="316" y="46">topics</text>+ <text class="small mono" x="316" y="72">company:<id>:<table></text>+ <text class="small mono" x="316" y="94">company:<id>:reference</text>+ <text class="small mono" x="316" y="116">user:<id>:notification</text>+ <path class="edge" d="M560,95 L522,95" marker-end="url(#arrow2)" />+ <rect class="box new" x="560" y="20" width="220" height="150" rx="8" />+ <text class="mono" x="576" y="46">realtime.messages</text>+ <text class="small" x="576" y="72">policy: employee of company</text>+ <text class="small" x="576" y="94">policy: the user's own id</text>+ </svg>+ <figcaption>The functions send to the topics. The two policies decide who may join a topic.</figcaption>+ </figure>+ <ul>+ <li><code>itemSupersession</code> and <code>itemStockQuantities</code> have no <code>id</code> column. Their messages carry <code>ids: null</code>.</li>+ <li><code>implementationHub</code> has no <code>companyId</code> column. The function reads the company from <code>id</code> for this table.</li>+ <li><code>itemLedger</code> keeps its existing handler, <code>apply_item_stock_quantities</code>, beside the new one.</li>+ <li>The 3 broadcast functions are managed files. They ship through <code>authz migration</code>.</li>+ <li>The authz manifest owns the 2 policies on <code>realtime.messages</code>, under the key <code>"realtime.messages"</code>.</li>+ <li>The migration drops each moved table from the <code>supabase_realtime</code> publication.</li>+ </ul>+ </section>++ <section>+ <h2>Done when</h2>+ <ul class="checks">+ <li>An operator completes an operation in the MES. The ERP job page shows it as complete within 3 seconds, with no reload.</li><li>A user adds a customer type. The picker on another open form shows it after the save, with no reload.</li><li>A second user in the same company adds a customer type. The first user's picker shows it within 3 seconds.</li><li>A cold load with a matching checksum sends 1 <code>list_checksums</code> request and 0 requests to the five list tables.</li><li>A cold load after another user renames a customer refetches <code>customer</code> only.</li><li>A user deletes an item while a second user's tab is closed. The second user's list lacks that item after the next load.</li><li>A notification for user A shows in user A's bell within 3 seconds. User B cannot join <code>user:<A>:notification</code>.</li><li>The <code>supabase_realtime</code> publication holds 0 tables.</li><li>A user in company A cannot join <code>company:<B>:item</code>. The subscribe call returns an error.</li><li>A user switches company. No list and no cached loader entry from the first company appears.</li><li>An update that changes only <code>updatedAt</code> on <code>item</code> sends no message.</li><li>A bulk update of 10,000 <code>item</code> rows sends 1 message for each company, with <code>ids</code> null.</li><li>A realtime message during a fetcher submit does not cancel that fetcher's redirect (MES "Complete Batch").</li><li>No file under <code>apps</code> or <code>packages</code> imports nanostores.</li><li>No file under <code>apps</code> or <code>packages</code> contains <code>postgres_changes</code>.</li><li>No route exports a <code>clientAction</code> that only invalidates.</li><li>The <code>realtime-table-has-trigger</code> check fails when a route declares a table that <code>REALTIME_TABLES</code> lacks.</li><li><code>event-dispatch.test.ts</code> fails when the ignored-column list in <code>broadcast_table_changes.sql</code> differs from <code>auditConfig.skipFields</code>.</li><li>The local stack and the self-hosted compose stack (Realtime v2.89.0) both deliver a broadcast on a private channel.</li><li>The typechecks for <code>erp</code>, <code>mes</code>, <code>@carbon/react</code>, <code>@carbon/database</code> and <code>@carbon/checks</code> pass, one at a time.</li><li><code>pnpm run lint</code> and <code>pnpm run test</code> pass.</li>+ </ul>+ </section>++ <section>+ <h2>Terms</h2>+ <dl class="terms">+ <dt>Reference list</dt><dd>A list that a cached <code>api+</code> loader returns, for example customer types.</dd>+ <dt>Realtime list</dt><dd>One of four lists that the app keeps current: items, customers, suppliers, people.</dd>+ <dt><code>LOADER</code> entry</dt><dd>A query cache entry with the key <code>[LOADER, companyId, pathname, search]</code>.</dd>+ <dt>Topic</dt><dd>The name of a private channel that a client joins to get broadcast messages.</dd>+ <dt>Publication</dt><dd><code>supabase_realtime</code>, the list of tables that <code>postgres_changes</code> can deliver.</dd>+ <dt>Checksum</dt><dd>A hash of the ids and list columns of one list, for the rows this user can read.</dd>+ <dt>Cold load</dt><dd>The first load of the app in a tab.</dd>+ <dt><code>handle.realtime</code></dt><dd>The list of tables that a route shows, declared on the route.</dd>+ </dl>+ </section>++ <footer>+ Generated by <code>/explain</code> from <code>.ai/specs/2026-10-04-client-query-cache-and-realtime-broadcast.md</code>.+ If this page and the source disagree, the source is correct.+ </footer>++</main>+<script>+ // Tabs: no dependencies. Works for every [data-tabs] block on the page.+ document.querySelectorAll("[data-tabs]").forEach(function (root) {+ var tabs = root.querySelectorAll("[role=tab]");+ var panels = root.querySelectorAll("[role=tabpanel]");+ tabs.forEach(function (tab, i) {+ tab.addEventListener("click", function () {+ tabs.forEach(function (t, j) { t.setAttribute("aria-selected", String(i === j)); });+ panels.forEach(function (p, j) { p.hidden = i !== j; });+ });+ });+ });+</script>+</body>+</html>diff --git a/.ai/specs/2026-10-04-client-query-cache-and-realtime-broadcast.md b/.ai/specs/2026-10-04-client-query-cache-and-realtime-broadcast.mdnew file mode 100644index 0000000000..4d8339e93d--- /dev/null+++ b/.ai/specs/2026-10-04-client-query-cache-and-realtime-broadcast.md@@ -0,0 +1,462 @@+# Client query cache and realtime broadcast++> Status: in-progress+> Author: Sidwebworks+> Date: 2026-10-04++## TLDR++The ERP and the MES get one client cache and one realtime system. A+`cachedClientLoader()` factory caches the `api+` reference lists by URL, and one+root middleware marks them stale after every mutation. Postgres sends a small+broadcast message for each changed table, and a route declares the tables it+shows, so operational pages update live in both apps. The four realtime lists+(items, customers, suppliers, people) move into the query cache. A change log+tells the client which rows changed since its stored copy. `useLoaderQuery` and `useAction` replace+hand-written fetcher effects. nanostores leaves the repo.++Research: `.ai/research/2026-10-01-client-cache-on-react-router.md`.++## Overview diagram++```mermaid+flowchart LR+ subgraph Cache["Reference lists"]+ A1["27 hand-written clientLoaders"] --> A2["cachedClientLoader"]:::new+ A3["78 clientAction invalidations"] --> A4["Root invalidation middleware"]:::new+ end+ subgraph Live["Page updates"]+ B1["postgres_changes per page"] --> B2["Broadcast trigger per table"]:::new+ B2 --> B3["handle.realtime on the route"]:::new+ end+ subgraph Lists["Realtime lists"]+ C1["nanostores and 5 table fetches"] --> C2["useLiveList in query cache"]:::hot+ C2 --> C3["Checksum skips the fetch"]:::new+ end+ subgraph Hooks["Component reads and writes"]+ D1["useFetcher with effects"] --> D2["useLoaderQuery and useAction"]:::new+ end+ classDef hot stroke-width:3px+ classDef new stroke-dasharray:4 3+```++## Problem Statement++The client has four defects today.++| # | Defect | Evidence |+|---|--------|----------|+| 1 | A cached route never goes stale. | The 27 cached `api+` routes read with `getQueryData` and write with `setQueryData`. Both ignore `staleTime` and `invalidateQueries`. |+| 2 | Each mutation route must name the keys it invalidates. | 78 route files export a `clientAction` for this. A route that forgets one leaves a stale dropdown. |+| 3 | A page that shows a table can miss its changes. | The ERP job page has no subscription on `jobOperation` or `job`. An operation completed in the MES does not show until a reload. The page also subscribes to `jobOperationStep` and `jobOperationStepRecord`, and the publication contains neither, so both subscriptions deliver nothing. |+| 4 | The realtime lists cost five whole-table fetches on each cold load. | `RealtimeDataProvider.tsx:88` reads `item`, `supplier`, `customer`, `employees` and `itemSupersession` from the browser, about 950 ms each (measured 2026-09-18). |++Two more defects come from the realtime provider itself.++- The provider writes the item column list three times. The insert handler maps+ `description`, which the fetch never selects. No handler updates the+ supersession fields.+- `postgres_changes` does one permission check for each subscriber for each+ change, on one thread for all tenants. One company's bulk write can delay the+ updates of every other company.++## Proposed Solution++The change has four parts. Each part stands on its own code, and the parts share+the query cache.++### Part 1 — Query cache for `api+` reference lists++1. Add `cachedClientLoader<typeof loader>(options?)` to+ `apps/erp/app/utils/react-query.ts`.+2. Key each entry as `[LOADER, companyId, pathname, search]`. `LOADER` is the+ string `"loader"`.+3. Read with `fetchQuery`, so `staleTime` and in-flight dedupe apply.+4. Set `clientLoader.hydrate = true` on the returned function.+5. Replace the body of each of the 27 cached `clientLoader` exports with one call.+6. Add the invalidation middleware to `clientMiddleware` in the ERP `root.tsx`.+7. Delete the 78 `clientAction` exports that only invalidate a key.+8. Delete the key factories in `react-query.ts` that no caller uses after step 7.++```ts+export function cachedClientLoader<L>(options?: { staleTime?: number }) {+ const clientLoader = ({ request, serverLoader }: ClientLoaderFunctionArgs) => {+ const cache = getClientCache();+ const companyId = getCompanyId();+ if (!cache || !companyId) return serverLoader<L>();+ const url = new URL(request.url);+ return cache.fetchQuery({+ queryKey: [LOADER, companyId, url.pathname, url.search],+ queryFn: () => serverLoader<L>(),+ staleTime: options?.staleTime ?? RefreshRate.Low,+ gcTime: LOADER_GC_TIME+ });+ };+ clientLoader.hydrate = true as const;+ return clientLoader;+}+```++The middleware runs after each request. If the method is `GET`, it does+nothing. If the path is `/refresh-session`, it does nothing. Otherwise it calls+`invalidateQueries({ queryKey: [LOADER] })`.++`getCompanyId()` reads `document.cookie`, and the `companyId` cookie is+httpOnly, so the function returns `null` today. Part 1 replaces it with a value+that the shell layout sets from `useUser().company.id` on mount. The live-list+keys in Part 3 use the same value.++### Part 2 — Realtime by broadcast++**Database.** One function, `broadcast_table_changes`, sends one message for each+company for each statement. The message holds the table name, the operation and+the changed ids. It holds no row data.++**Topic.** `company:<companyId>:<table>`. The channel is private.++**Authorization.** One policy on `realtime.messages` lets a user join a topic+only if the user is an employee of the company in the topic.++**Client.** A route declares the tables it shows:++```ts+export const handle = { realtime: ["job", "jobOperation"] };+```++One hook in each shell layout, `useRouteRealtime()`, does these steps:++1. Read `useMatches()` and collect the unique table names from `handle.realtime`.+2. Subscribe to one private channel for each table.+3. On a message, start a 300 ms debounce timer. A new message restarts the timer.+4. When the timer ends, check the fetchers. If a fetcher is submitting, wait for it to finish.+5. Call `invalidateQueries({ queryKey: [LOADER] })`.+6. Call `revalidator.revalidate()`.+7. On a reconnect, do steps 5 and 6 one time.++`useRealtime(table, filter?)` keeps its signature for components that are not a+route. If the filter is `id=eq.<id>` or `id=in.(<ids>)`, the hook compares the+message ids with the filter ids. If the filter names another column, the hook+ignores the filter and wakes on any change to the table.++**Reference lists.** A cached `api+` loader is not a matched route, so+`useMatches()` does not see it. The tables behind the cached reference lists get+a second function, `broadcast_reference_changes`. It sends+`{ table, op }` to one shared topic, `company:<companyId>:reference`. Each shell+layout subscribes to that one topic. On a message, the shell calls+`invalidateQueries({ queryKey: [LOADER] })` after the same 300 ms debounce. Each+active `useLoaderQuery` then refetches.++**Notifications.** `useNotifications` subscribes to+`user:<userId>:notification`. On an `INSERT` or `UPDATE` message, the hook reads+the rows with those ids and the current `companyId` through PostgREST. Then it+applies the same rules as today for `digestedInto`. On a `DELETE` message, the+hook removes the rows with those ids.++### Part 3 — Live lists++`useItems()`, `useCustomers()`, `useSuppliers()` and `usePeople()` keep their+names and their `[value, setValue]` return shape. About 200 files call them.++Each list becomes a `useLiveList` definition. The definition holds the table,+the column list, the sort function and the query key+`["live", companyId, <list>]`. The column list has one copy. A definition can+name related tables, for example `itemSupersession` for the item list.++Cold load does these steps:++1. Read each list and its cursor from IndexedDB (`<list>:<companyId>`).+2. Put each list in the query cache.+3. Call `table_changes_since` one time, with the oldest cursor.+4. If the answer is `reset`, fetch each list in full.+5. Otherwise, for each list, read only the rows that the answer names.+6. Remove a named row that the read does not return.+7. Write each list and the new cursor to IndexedDB.++The reader answers `reset` in 3 cases:++- The client sent no cursor.+- The server restarted after it issued the cursor.+- The cursor is older than 6 days.++The client also fetches a list in full when the answer names more than 500 changed rows for it.++A broadcast message does these steps:++1. If `ids` is null, do the cold-load steps 3 to 7 for that list.+2. If `op` is `DELETE`, remove the rows with those ids from the cache.+3. Otherwise, read the rows with those ids through PostgREST with the list's column list.+4. Merge the rows into the cache and sort.+5. Write the list to IndexedDB. The cursor does not change.++A reconnect does the cold-load steps 3 to 7.++### Part 4 — Component hooks++| Hook | Replaces | Behavior |+|------|----------|----------|+| `useLoaderQuery<typeof loader>(url, options?)` | `useFetcher` + `fetcher.load(url)` in a mount effect (137 call sites) | `useQuery` over the same `[LOADER, companyId, pathname, search]` key. Five pickers on one page share one request. |+| `useAction<typeof action>({ onSuccess, onError })` | `useFetcher` + an effect that watches `fetcher.data` (435 submit call sites) | Wraps `useFetcher`. Returns `submit`, `isPending`, `data` and `pending` (the form values in flight). It writes nothing to the cache. |++Part 4 migrates each call site where a fetcher loads an `api+` URL or submits+to a route action. A `fetcher.load` of a page route stays on `useFetcher`.++### Design Decisions++| Decision | Choice | Rationale |+|----------|--------|-----------|+| Cache engine | Keep `@tanstack/react-query` on the existing `window.clientCache` client | The app already ships it. A second client would split invalidation. |+| Cache key | URL: `[LOADER, companyId, pathname, search]` | React Router's own client-cache guide keys by URL. A route author writes no key. |+| Invalidation after a mutation | Mark every `LOADER` entry stale | It costs one extra fetch when a list is next used. It removes 78 hand-written invalidations and the key registry. |+| `LOADER` prefix | Required | A bare `invalidateQueries()` also refetches each active `useQuery`, for example the 3D model loader, on each save. |+| Page data | Not cached | A route with a `clientLoader` leaves the combined `.data` request. `dataStrategy` is closed in framework mode. |+| `gcTime` for loader entries | 30 minutes | The client default is `Infinity`. URL keys create one entry for each distinct search string. |+| Realtime transport | Broadcast from the database | Realtime checks permission one time at join. `postgres_changes` checks each change for each subscriber on one thread. |+| Trigger attachment (user, 2026-10-05) | Declared in `event-system/attachments.ts`, applied by `set_event_triggers` | Each attach call replaces the whole list of a table. One typed manifest removes the clobber risk. No migration attaches a trigger. |+| Interceptor bodies (user, 2026-10-05) | Managed files in `event-system/handlers/` | The 63 interceptors and `apply_item_stock_quantities` leave the migrations. `authz sync` and `authz migration` own them. |+| Message payload | `{ table, op, ids }`, ids null above 100 rows | The client reads rows through PostgREST, so table RLS still decides what a user sees. |+| Topic grain (user, 2026-10-04) | One topic for each company for each table | A caller with a parent-column filter wakes on any change to the table. The debounce bounds the cost. |+| Tables with a trigger (user, 2026-10-04) | Only tables that a route or a live list declares | A table that no page watches gets no write overhead and stores no messages. |+| Page coverage (user, 2026-10-04) | Operational pages in the ERP, all of the MES, and the cached reference lists | Settings and admin pages change rarely. They reload on navigation as today. |+| Reference lists | One shared topic, `company:<companyId>:reference` | One channel for each client covers every reference table. A topic for each table would hold about 30 channels open for the whole session. |+| Policies on `realtime.messages` (user, 2026-10-04) | The authz manifest, entry `"realtime.messages"` | One system owns every policy. A hand-written migration would bypass `authz sync` and the migration check. |+| Source of truth for the table list | `REALTIME_TABLES`, derived from `attachments.ts` | A table is realtime when its entry attaches `broadcast_table_changes`. No second list exists. |+| Missed-declaration guard | New `realtime-table-has-trigger` check in `@carbon/checks` | `postgres_changes` fails silently for an unpublished table. The check makes that a build failure. |+| Publication (user, 2026-10-04) | Drop the moved tables from `supabase_realtime` in this PR | A tab on the old build goes quiet until a reload. It shows no error. |+| Tables that stay on `postgres_changes` (user, 2026-10-04) | None | The publication ends empty. No second realtime system stays in the code. |+| Notifications (user, 2026-10-04) | Private topic `user:<userId>:notification`, sent by `broadcast_user_changes` | A company topic would wake every employee for each notification of each other employee. |+| `implementationHub` | `broadcast_table_changes` reads the company from `id` for this table | The table has no `companyId` column. Its `id` is the company id. |+| Ignored updates | Skip an update that changes only `updatedAt`, `updatedBy` or `embedding` | `dispatch_event_batch` has the same rule. `event-dispatch.test.ts` checks that the two lists match. |+| List storage | Query cache, key `["live", companyId, <list>]` | One store for server data. nanostores has no other user after this change. |+| Cold-load sync (user, 2026-10-05) | A change log: the `tableChange` table and `table_changes_since(cursor)` | The client reads only the rows that changed since its stored copy. A checksum refetches a whole list when one row changes, and it scans every row on each load. |+| Change log storage (user, 2026-10-05) | `UNLOGGED` table | The log insert on each write skips WAL. A crash empties the table. The reader detects a server restart by its epoch and answers `reset`. |+| Change log cursor | The transaction id `pg_snapshot_xmin(pg_current_snapshot())` | A sequence value is taken before commit. A reader that keeps "the highest id" skips a row whose transaction commits late. |+| Change log retention | 7 days, purged hourly by `pg_cron` | A cursor older than 6 days gets `reset`. The 1-day margin covers a purge that runs between the check and the read. |+| Reader security | `SECURITY DEFINER` with a company check | The table has no API access. The reader reveals row ids only, as a broadcast does. The client re-reads the rows under table RLS. |+| A renamed user | `log_user_changes` logs it as an `employee` change for each company of that user | The `user` row has no `companyId`. Each company shows the name in its people list. |+| IndexedDB | Keep localforage, keys `<list>:<companyId>` | `.ai/lessons.md` line 254: a cache without `companyId` in its key leaks across tenants. |+| `useAction` scope (user, 2026-10-04) | Pending state and callbacks only | Mutations stay plain router actions. Optimistic cache writes are out of scope. |+| Shared code | `useRouteRealtime`, `useLiveList`, `useRealtime` live in `@carbon/react` | Both apps need them. The `no-duplicated-app-file` check forbids a copy in each app. `@carbon/react` already depends on `react-router`. |+| MES cache | The MES root adopts `window.clientCache` and the same middleware | `useLiveList` and the invalidation need one client that code outside React can reach. |+| Heuristics 1, 3, 6 (new tables, RLS on new tables, module layout) | N/A | The change adds no table and no module. |+| Heuristic 2 (service shape) | N/A | The change adds no service function. The browser calls `list_checksums` through `carbon.rpc`. |+| Heuristic 4 (permission scoping) | No change | No route changes its `requirePermissions` call. |+| Heuristic 5 (form pattern) | No change | `ValidatedForm` and its props stay as they are. `useAction` wraps `useFetcher` only. |+| Heuristic 7 (backward compatibility) | One break: the publication drop | The API, the MCP tools and the webhooks do not change. |++## Data Model Changes++One migration. It adds no table and no column.++```sql+-- 1. Broadcast function (managed file:+-- packages/database/src/event-system/functions/broadcast_table_changes.sql)+CREATE OR REPLACE FUNCTION public.broadcast_table_changes()+RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path = '' AS $$+DECLARE+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];+ rec RECORD;+ source_sql TEXT;+BEGIN+ IF TG_OP = 'UPDATE' THEN+ source_sql := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n+ EXCEPT SELECT to_jsonb(o) - $1 FROM batched_old o';+ ELSIF TG_OP = 'DELETE' THEN+ source_sql := 'SELECT to_jsonb(o) AS c FROM batched_old o';+ ELSE+ source_sql := 'SELECT to_jsonb(n) AS c FROM batched_new n';+ END IF;++ FOR rec IN EXECUTE format(+ -- implementationHub has no companyId: its id is the company id+ 'SELECT coalesce(c->>''companyId'',+ CASE WHEN $2 = ''implementationHub'' THEN c->>''id'' END) AS company_id,+ count(*) AS n,+ jsonb_agg(c->''id'') FILTER (WHERE c ? ''id'') AS ids+ FROM (%s) changed GROUP BY 1',+ source_sql+ ) USING ignored_columns, TG_TABLE_NAME LOOP+ CONTINUE WHEN rec.company_id IS NULL;+ PERFORM realtime.send(+ jsonb_build_object(+ 'table', TG_TABLE_NAME,+ 'op', TG_OP,+ 'ids', CASE WHEN rec.n <= 100 THEN rec.ids END+ ),+ TG_OP,+ 'company:' || rec.company_id || ':' || TG_TABLE_NAME,+ true+ );+ END LOOP;+ RETURN NULL;+END $$;++-- 2. Who can join a company topic (authored in authz/manifest.ts, not in a migration)+CREATE POLICY "company topic"+ON realtime.messages FOR SELECT TO authenticated+USING (+ split_part(realtime.topic(), ':', 1) = 'company'+ AND split_part(realtime.topic(), ':', 2) = ANY (+ (SELECT get_companies_with_employee_role())::text[]+ )+);++CREATE POLICY "user topic"+ON realtime.messages FOR SELECT TO authenticated+USING (+ split_part(realtime.topic(), ':', 1) = 'user'+ AND split_part(realtime.topic(), ':', 2) = (SELECT auth.uid())::text+);++-- broadcast_user_changes: the same body as broadcast_table_changes, but it+-- groups by c->>'userId' and sends to 'user:' || user_id || ':' || TG_TABLE_NAME+SELECT attach_statement_handler('notification', ARRAY['broadcast_user_changes']);++-- 3. Attach, one line for each table in REALTIME_TABLES+SELECT attach_statement_handler('item', ARRAY['broadcast_table_changes']);+-- itemLedger keeps its existing handler: attach_statement_handler replaces the list+SELECT attach_statement_handler('itemLedger',+ ARRAY['apply_item_stock_quantities', 'broadcast_table_changes']);++-- 4. Leave postgres_changes, one line for each moved table+ALTER PUBLICATION supabase_realtime DROP TABLE public.item;++-- 5. The change log (20261004200418_table-change-log.sql)+CREATE UNLOGGED TABLE "tableChange" (+ "id" BIGINT GENERATED ALWAYS AS IDENTITY,+ "companyId" TEXT NOT NULL,+ "table" TEXT NOT NULL,+ "rowId" TEXT, -- NULL: more than 100 rows changed in one statement+ "xid" XID8 NOT NULL DEFAULT pg_current_xact_id(),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ CONSTRAINT "tableChange_pkey" PRIMARY KEY ("id", "companyId"),+ CONSTRAINT "tableChange_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE+);++-- table_changes_since(p_company_id, p_xid, p_epoch, p_at) returns+-- { reset, changes: { "<table>": ["<rowId>", ...] | null }, xid, epoch, at }+```++Rules for the migration:++- The statement handlers `log_table_changes` and `log_user_changes` write the log. `attachments.ts` attaches them to `item`, `itemSupersession`, `customer`, `supplier`, `employee`, `modelUpload` and `user`.+- The table has no audit columns and no `id('prefix')` default. It is a log that only triggers write.+- The backup engine skips the table. Its transaction ids mean nothing in another database.+- `itemSupersession` has no `id` column. Its message and its log row carry the `itemId`.+- `itemStockQuantities` has no `id` column. Its message carries `ids: null`, so the client invalidates.+- The people list reads the `employees` view. A change to `user.name` sends no+ message, as today. The change log records it, so the next load or reconnect reads that person again.+- The 3 broadcast functions are managed files under `packages/database/src/event-system/functions/`. They ship through `authz migration`, not a hand-written migration.+- The authz manifest owns the 2 policies on `realtime.messages`. The manifest key is `"realtime.messages"`, built with `external()`.+- `authz sync`, `authz migration` and the `no-authz-ddl-in-migrations` check read the schema from the key. A key with no dot is a `public` table.+- Supabase owns the RLS switch of `realtime.messages`. The sync fails if the switch is off. The sync never changes it.+- Run `pnpm run generate:types` after the migration, before the typecheck.++## API / Service Changes++| File | Change |+|------|--------|+| `apps/erp/app/utils/react-query.ts` | Add `LOADER`, `cachedClientLoader`, `loaderQueryKey(url)`, `setCompanyId`. Delete the unused key factories and `invalidate*` helpers. |+| `packages/auth/src/middleware/` | Add `createInvalidationMiddleware(getCache, refreshSessionPath)`. Both app roots add it to `clientMiddleware`. |+| `apps/erp/app/routes/api+/*` (27 files) | `export const clientLoader = cachedClientLoader<typeof loader>()`. |+| `apps/erp/app/routes/x+/**` (78 files) | Delete the `clientAction` export. |+| `packages/database/src/realtime-tables.ts` | New `REALTIME_TABLES` and `REALTIME_REFERENCE_TABLES` constants. The second list holds the tables behind the cached `api+` loaders. |+| `packages/react/src/hooks/useRealtimeChannel.ts` | New `private?: boolean` option, passed to `carbon.channel(topic, { config: { private } })`. |+| `packages/react/package.json` | Add `@tanstack/react-query`, at the version the apps use. |+| `packages/react/src/hooks/` | New `useRouteRealtime`, `useRealtime`, `useLiveList`, `useLoaderQuery`, `useAction`. The `useRealtime` and `useDebouncedRealtime` files in each app become re-exports. |+| `packages/checks/src/conformance/` | New `realtime-table-has-trigger` check with its test. |+| `apps/mes/app/root.tsx` | Set `window.clientCache`, as the ERP root does. |+| `.claude/rules/clientAction-patterns.md`, `coding-conventions.md` | Rewrite the cache and state sections. Add a `realtime-system.md` rule. |+| `.ai/lessons.md` | Add the job-page lesson: a subscription to an unpublished table fails silently. |++`fetchQuery` waits for the refetch when an entry is stale. A component that+needs the old value at once reads through `useLoaderQuery`.++## UI Changes++No new page and no new component. These behaviors change:++| Where | Change |+|-------|--------|+| ERP operational routes and all MES routes | Add `handle.realtime` with the tables that the loader reads. |+| ERP job page (`x+/job+/$jobId.tsx`) | Declares `job`, `jobOperation`, `jobMaterial`, `jobOperationStep`, `jobOperationStepRecord`, `productionEvent`, `pickingListLine`. |+| 41 files that subscribe today | A route moves to `handle.realtime`. A component keeps `useRealtime`. A component that reads the row payload reads the row by id. |+| `RealtimeDataProvider` (ERP and MES) | Becomes four `useLiveList` calls (ERP) and two (MES). The reducers go. |+| `apps/erp/app/stores/{items,customers,suppliers,people}.ts` and the MES pair | Hooks read the query cache. `useParts`, `useTools`, `useServices`, `useMaterials` become `select` filters. |+| `useNanoStore` in `@carbon/react` | Deleted, with the `nanostores` and `@nanostores/react` dependencies. |+| `Form/Item.tsx` on-hand badge | A `itemStockQuantities` message invalidates the `itemQuantities` query, as today. |++"Operational routes" means the route folders for: job, production, scheduling,+priority, quote, sales-order, sales-rfq, sales-invoice, sales-return-order,+purchase-order, purchasing-rfq, supplier-quote, purchase-invoice,+purchase-return-order, shipment, receipt, inventory, inventory-count,+picking-list, stock-transfer, warehouse-transfer, issue, inspection,+change-order, change-notice, maintenance, and the list pages under items,+sales, purchasing, invoicing and quality. The folders settings, users, account,+accounting, people, resources, documents, templates and workflows keep their+existing subscriptions only.++## Acceptance Criteria++- [ ] An operator completes an operation in the MES. The ERP job page for that job shows the operation as complete within 3 seconds, with no reload.+- [ ] A user adds a customer type. The customer type picker on another open form shows the new type after the save, with no reload.+- [ ] A second user in the same company adds a customer type. The first user's picker shows it within 3 seconds.+- [ ] A cold load with no change sends 1 `table_changes_since` request and 0 requests to `item`, `supplier`, `customer`, `employees` or `itemSupersession`.+- [ ] A cold load after another user renames 1 customer sends 1 request to `customer`, with `id=in.(<that id>)`.+- [ ] A cold load after a database restart fetches each list in full.+- [ ] A user deletes an item while a second user's tab is closed. The second user's item list lacks that item after the next load.+- [ ] A notification for user A shows in user A's bell within 3 seconds. User B in the same company cannot join `user:<A>:notification`.+- [ ] `SELECT count(*) FROM pg_publication_tables WHERE pubname = 'supabase_realtime'` returns 0.+- [ ] A user in company A cannot join `company:<B>:item`. The subscribe call returns an error.+- [ ] A user switches company. No list and no cached loader entry from the first company appears.+- [ ] An update that changes only `updatedAt` on `item` sends no message.+- [ ] A bulk update of 10,000 `item` rows sends 1 message for each company, with `ids` null.+- [ ] A realtime message that arrives while a fetcher is submitting does not cancel that fetcher's redirect (MES "Complete Batch").+- [ ] `grep -r nanostores apps packages --include=*.ts --include=*.tsx` returns no file.+- [ ] `grep -r "postgres_changes" apps packages` returns no file.+- [ ] No file under `apps/erp/app/routes` exports a `clientAction`, or each one that stays does more than invalidate.+- [ ] The `realtime-table-has-trigger` check fails when a route declares a table that `REALTIME_TABLES` lacks.+- [ ] `event-dispatch.test.ts` fails when the ignored-column list in `broadcast_table_changes.sql` differs from `auditConfig.skipFields`.+- [ ] The local stack and the self-hosted compose stack (Realtime v2.89.0) both deliver a broadcast on a private channel.+- [ ] `pnpm exec turbo run typecheck --filter=erp`, `--filter=mes`, `--filter=@carbon/react`, `--filter=@carbon/database` and `--filter=@carbon/checks` pass, one at a time.+- [ ] `pnpm run lint` and `pnpm run test` pass.++## Risks++| Risk | Severity | Mitigation |+|------|----------|------------|+| A mistake in the `realtime.messages` policy leaks change signals across companies. | High | The policy uses the same helper as the table policies. A database test joins a foreign company topic and expects a refusal. |+| A dropped broadcast leaves a list or a page stale. | Med | A reconnect and a tab focus both run the catch-up steps. The checksum runs on each load. |+| The PR is large: about 27 + 78 + 41 + 137 + 435 call sites and one migration. | High | The plan orders the work in phases that each pass the typecheck. Mechanical edits use a codemod. Each phase has a browser check. |+| Tabs on the old build go quiet after the publication drop. | Med | The user accepted this. The lists and pages recover on reload. |+| The broadcast trigger slows writes on `itemLedger`, `jobOperation` and `productionEvent`. | Med | The trigger is statement-level and sends ids only. Measure with `EXPLAIN ANALYZE` on one insert before and after. |+| `realtime.messages` grows on busy tables. | Low | Realtime keeps messages for about three days. The payload is ids only, capped at 100. |+| A crash empties the `UNLOGGED` change log. | Med | The reader compares the server start time with the cursor's epoch and answers `reset`. Each client then fetches its lists one time. |+| A bug in the change log leaves a list stale with no error. | High | `realtime-broadcast.test.sql` covers the writer and the reader. `liveList.test.ts` covers the plan. A browser check covers a change made while the tab is closed. |+| Realtime v2.89.0 lacks `realtime.send` or private channels. | Med | Verify on the local stack as the first task of the plan. If it fails, raise the image version in both compose files. |+| Blunt invalidation refetches every active `useLoaderQuery` after each save. | Low | Each refetch is one small `api+` request. `staleTime` does not stop it, by design. |+| A realtime revalidation re-runs every loader of the page. | Med | The debounce collapses bursts. Shell loaders already skip through `shouldRevalidate`. |+| A `handle.realtime` list on a route goes out of date when its loader reads a new table. | Med | The check covers a missing trigger only. The new rule file tells the author to update the list with the loader. |+| `useAction` changes the timing of `onSuccess` against a redirect. | Med | Migrate one module first and run its browser playbook before the codemod. |++## Open Questions++- [x] May the PR add a policy on `realtime.messages` and triggers on core tables? — **Answer:** Yes, both. The user runs `db:migrate`.+- [x] How do the lists avoid the whole-table fetches on cold load? — **Answer:** A change log on an `UNLOGGED` table. The user replaced the checksum on 2026-10-05: a checksum refetches a whole list for one changed row.+- [x] How much goes in the first PR? — **Answer:** Everything: the cache, the component hooks and all realtime callers.+- [x] How does a caller with a parent-column filter work on broadcast? — **Answer:** One topic for each table. The caller wakes on any change to the table.+- [x] Does the ERP job-page bug get its own fix? — **Answer:** No. It ships in this rewrite. The goal is live pages in the ERP and the MES.+- [x] Which pages update live? — **Answer:** Operational pages, all of the MES, and the cached reference lists.+- [x] Which tables get the trigger? — **Answer:** Only the tables that a route or a live list declares.+- [x] When do the tables leave the publication? — **Answer:** In this PR.+- [x] How far does `useAction` go? — **Answer:** Pending state and callbacks only. No optimistic cache writes.+- [x] Do `notification` and `implementationHub` move to broadcast? — **Answer:** Yes. Notifications use a private topic for each user. Nothing stays on `postgres_changes`.++## Changelog++- 2026-10-04: Created. All nine questions were answered by the user before writing.+- 2026-10-04: Notifications and the implementation hub move to broadcast. The publication ends empty.+- 2026-10-04: Planning found that the broadcast functions are managed event-system files. `@carbon/react` gains `@tanstack/react-query`.+- 2026-10-04: The authz manifest owns the `realtime.messages` policies (user decision). The authz system now handles one table outside `public`.+- 2026-10-05: The user moved all event triggers and interceptor bodies out of migrations. `attachments.ts` declares the triggers of 141 tables. `event-system/handlers/` holds 64 functions. The takeover migration is `20261004194527_event-attachments.sql`.+- 2026-10-05: The user replaced the checksum with a change log (`tableChange`, `UNLOGGED`, `table_changes_since`). The shared code moved to the new `@carbon/query` package, and `~/utils/react-query` is gone. All listeners of a topic share one channel.+- 2026-10-05: `useAction` moves 98 single-condition effects. The 133 mutation effects with several branches stay for a follow-up PR (user decision). 13 event-driven load sites stay on `useFetcher`.diff --git a/.claude/rules/authz-manifest.md b/.claude/rules/authz-manifest.mdindex 3f1538e59f..c333825075 100644--- a/.claude/rules/authz-manifest.md+++ b/.claude/rules/authz-manifest.md@@ -16,7 +16,16 @@ Every RLS policy on a `public` table, and the 16 RLS/auth helper functions, are(`no-authz-ddl-in-migrations` in `@carbon/checks` fails them, from `20260927000000` on).`storage.objects` (bucket) policies are not in the manifest and stay in migrations.-The same machinery owns the event system's 37 functions — see+One table outside `public` is in the manifest: **`realtime.messages`**, the policies that+decide who may join a private Realtime broadcast topic (`company:<companyId>:<table>`,+`user:<userId>:<table>`). Its key is `"realtime.messages"` and its rule is built with+`external()`. A key with a dot is `<schema>.<table>` (`locate()` in `rules.ts`); sync, the+migration generator and `no-authz-ddl-in-migrations` all read the schema from it. Supabase+owns that table and its RLS switch, so sync and the generated migration never run+`ENABLE ROW LEVEL SECURITY` on it — sync fails instead if the switch is off. To add another+external table, extend `ExternalTable` in `rules.ts` and `MANIFEST_SCHEMAS` in the check.++The same machinery owns the event system's 41 functions, its 64 table handlers and the event triggers — see[Event-system functions](#event-system-functions) below.| File | What it is |@@ -76,8 +85,8 @@ or `baseline.json` by hand.## Event-system functions`packages/database/src/event-system/functions/` holds one file per function for dispatch,-subscriptions, the queue wake-up, the audit log, the search index and embeddings (37:-31 in `public`, 6 in `util`). They are loaded, synced, shipped and guarded exactly like the+subscriptions, the queue wake-up, the audit log, the search index, embeddings and the+realtime broadcast triggers (41: 35 in `public`, 6 in `util`). They are loaded, synced, shipped and guarded exactly like theRLS helpers — `loadHelpers()` reads both directories, and a `Helper` carries its `schema`.- **File name is the function**: `dispatch_event_batch.sql` defines@@ -97,13 +106,62 @@ RLS helpers — `loadHelpers()` reads both directories, and a `Helper` carries i- **Signature changes and new functions** still need a hand-written migration for the`DROP FUNCTION` (sync refuses a file that would create an overload); the new definitiongoes in the file.-- **Not managed**: the per-table interceptors (`sync_*`) stay in their table's migration,- as do `util.send_inngest_event` and `public.set_inngest_event_url`+- **Table handlers are managed too**: `../event-system/handlers/<name>.sql` holds every+ function a table attaches — the 63 interceptors (`sync_*`, `prevent_*`, `set_shelf_life_*`,+ `storage_unit_*`) and the statement handler `apply_item_stock_quantities`. Same format,+ same sync, same shipping; checked from `20261004194527` (`ATTACHMENTS_SINCE`). A new+ interceptor is a new file there, never a function in a migration.+- **Not managed**: `util.send_inngest_event` and `public.set_inngest_event_url`(`20261002170250`).- **Retired**: `util.anon_key`, `util.invoke_edge_function` and `util.process_embeddings`(`RETIRED_HELPERS`, dropped by `20261002170619`) — Postgres no longer calls an edgefunction; `util.sweep_embedding_queue` replaced the last.+## Event triggers (attachments)++Which functions run on which table is declared in ONE place,+`packages/database/src/event-system/attachments.ts`, typed by table name:++```ts+customer: {+ before: ["sync_update_customer_type_group"],+ after: ["sync_create_customer_entries", "sync_create_customer_org_group"],+ events: true,+ statement: ["broadcast_table_changes"]+},+```++- `before` / `after` — interceptors, in order, run per row inside the writing transaction.+- `events` — changes are queued for the event system (`dispatch_event_batch`).+- `statement` — handlers run once per statement (`attach_statement_handler`).++A migration never calls `attach_event_trigger`, `attach_statement_handler` or+`set_event_triggers` (`no-authz-ddl-in-migrations` rejects it from `20261004194527`). Each of+those replaces a table's WHOLE list, so a call that left a function out silently detached+it. The `clobbers` check used to watch for that; it now covers views and+functions only.++- **Sync**: `authz sync` compares each table's live triggers with its entry and calls+ `set_event_triggers(table, before, after, events, statement)` where they differ. A table+ with event triggers and no entry is detached. `set_event_triggers` itself returns+ without touching a table whose triggers are already as declared: creating a trigger+ locks the table against writes, and a migration restates every table.+- **Shipping**: `authz migration <name>` writes one `SELECT set_event_triggers(...)` per+ changed table, after the functions and policies, between `SET lock_timeout = '5s'`+ and `RESET lock_timeout`: behind a long transaction the migration fails and is run+ again, instead of queueing every writer of that table behind it. `unshipped()` compares each table's last+ shipped statement with what the manifest renders, and reports a table that was shipped+ and later removed (it is shipped again, detached). There is no baseline: the takeover+ migration `20261004194527_event-attachments.sql` ships all 141 tables.+- **Adding a table's triggers**: add its entry, `pnpm db:migrate` (syncs locally), then+ `authz migration <name>`.+- **Realtime lists are derived**: `REALTIME_TABLES`, `REALTIME_REFERENCE_TABLES` and+ `REALTIME_USER_TABLES` (`packages/database/src/realtime-tables.ts`) are the tables whose+ entry attaches `broadcast_table_changes`, `broadcast_reference_changes` or+ `broadcast_user_changes`. Making a table realtime is adding that handler to its entry.+- Pinned by `event-system/attachments-sync.test.ts`: against a database, the live triggers+ equal the manifest, and re-applying every entry recreates each trigger byte for byte.+## Commands```bashdiff --git a/.claude/rules/clientAction-patterns.md b/.claude/rules/clientAction-patterns.mdindex 3debb949df..4aaeaade87 100644--- a/.claude/rules/clientAction-patterns.md+++ b/.claude/rules/clientAction-patterns.md@@ -1,133 +1,99 @@---paths:+ - "packages/query/**"- "apps/erp/app/routes/api+/**"- - "apps/erp/app/routes/x+/**"- - "apps/erp/app/utils/react-query.ts"- - "apps/erp/app/root.tsx"----# clientLoader / clientAction Patterns+# Client cache: `cachedClientLoader` and the invalidation middleware-React Router v7 (`react-router`, **not** Remix) client data functions. They run an-in-memory SPA cache in front of the route's own server `loader` / `action`. This is an-**ERP-only** convention — `apps/mes/app` uses neither. As of grounding: ~25 ERP files use-`clientLoader`, ~63 use `clientAction`.+How the ERP and the MES cache route data in the browser. All of it lives in+`@carbon/query` (`packages/query`); there is no app-level cache file+(`~/utils/react-query` is gone) and no route exports a `clientAction`.-Types are imported from `"react-router"`:+## The cache-```ts-import type {- ClientLoaderFunctionArgs,- ClientActionFunctionArgs,-} from "react-router";-```+One TanStack `QueryClient` per page. Each app's `root.tsx` creates it and stores+it on `window.clientCache`, so code outside React (a `clientLoader`, the+middleware, the realtime hooks) reaches the same client as `useQuery` does.+`getClientCache()` from `@carbon/query/cache` returns it (undefined on the server).-## The cache: a `window.clientCache` QueryClient--The cache is a TanStack `QueryClient` attached to `window.clientCache` — **not** a-module-level Map or localStorage. It is created once on mount in-`apps/erp/app/root.tsx` with everything set to never expire, so it behaves as a-session-lived in-memory cache:+## Caching a loader: one line, no key```ts-window.clientCache = new QueryClient({- defaultOptions: {- queries: { gcTime: Infinity, refetchOnWindowFocus: false, staleTime: Infinity },- },-});-```+// apps/erp/app/routes/api+/sales.customer-types.ts+import { cachedClientLoader } from "@carbon/query/cache";-Query keys come from factory functions in `apps/erp/app/utils/react-query.ts`-(e.g. `customerTypesQuery(companyId)`, `itemPostingGroupsQuery(companyId)`), each-returning `{ queryKey, staleTime }`. Keys are namespaced by company for multi-tenancy.-Helpers in that file: `getCompanyId()` reads the `companyId` cookie client-side (returns-`null` on the server); `getClientCache()` returns `window.clientCache` or `undefined`.+export async function loader({ request }: LoaderFunctionArgs) { /* unchanged */ }-## clientLoader — read-through cache (read routes, `api+/`)--Canonical shape (`apps/erp/app/routes/api+/sales.customer-types.ts`): company-scoped-read-through cache. No company → defer to server. Cache miss → `serverLoader()` then-populate. Cache hit → skip the network.--```ts-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();- if (!companyId) return await serverLoader<typeof loader>();-- const queryKey = customerTypesQuery(companyId).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(queryKey);-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();+// or cachedClientLoader<typeof loader>({ staleTime: RefreshRate.Never })```-- `serverLoader<typeof loader>()` is the typed call back to the route's own server `loader`.-- `clientLoader.hydrate = true` makes the client loader run on **initial hydration**, not- just subsequent client navigations — so the cache warms on first load. Present on all- `api+` clientLoader files; no `HydrateFallback` is exported anywhere.-- Variants fold route/search params into the key- (`apps/erp/app/routes/api+/items.types.$substanceId.$formId.ts` →- `materialTypesQuery(substanceId, formId, companyId)`).-- For component-driven (non-navigation) fetches, `clientLoader` never runs — raw- `fetch` bypasses it. Those use `cachedApiQuery(queryDef, url)`- (`apps/erp/app/utils/react-query.ts`), an imperative- `clientCache.fetchQuery` read-through with the same key factories, so- `clientAction` invalidation still applies (see the user-select endpoints,- invalidated by `invalidateUserSelectQueries`).--## clientAction — cache invalidation (mutation routes, `x+/`)+- The key is the URL: `[LOADER, companyId, pathname, search]`. Nobody writes a+ query key or a key factory. A route param or a search param is part of the key+ because it is part of the URL.+- It reads with `fetchQuery`, so `staleTime` is honored and concurrent loads of+ one URL share a request. (The old `getQueryData`/`setQueryData` pair ignored+ both: an entry lived for the whole session.)+- `clientLoader.hydrate` is set, so the cache warms on first load.+- With no company yet, or no cache, it calls `serverLoader()` uncached.+- Loader entries are garbage-collected after 30 minutes unused.+- Import from `@carbon/query/cache` in a route module, not `@carbon/query`: the+ subpath has no React or UI import, and a route module also runs on the server.-Mutation routes (`*.new`, `*.$id`, `*.delete.*`) invalidate the matching cached query,-then delegate to the server `action`. **No optimistic updates** — invalidation only; the-next `clientLoader` run sees a miss and re-fetches.+**Scope: `api+` reference lists only.** Page data is not cached this way. A+route with a `clientLoader` leaves the combined single-fetch request and sends+its own, so caching page loaders turns one request into many.-Invalidate-by-predicate (`apps/erp/app/routes/x+/items+/groups.$groupId.tsx`):+## Invalidation: once, in `root.tsx````ts-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- const companyId = getCompanyId();- window.clientCache?.invalidateQueries({- predicate: (query) => {- const queryKey = query.queryKey as string[];- return (- queryKey[0] === itemPostingGroupsQuery(companyId).queryKey[0] &&- queryKey[1] === companyId- );- },- });- return await serverAction();-}+export const clientMiddleware = [+ flashClientMiddleware,+ createInvalidationMiddleware({+ getCache: () => window.clientCache,+ skipPaths: [path.to.refreshSession]+ })+];```-Alternative for a single known key — set it to `null` instead of a predicate:--```ts-window?.clientCache?.setQueryData(uomsQuery(getCompanyId()).queryKey, null);-return await serverAction();-```--If you need form data inside the clientAction (e.g. to pick which key to invalidate),-clone the request first — `request.clone().formData()` — so the server `action` can still-read the body.--## Rules--1. **Always end by calling `serverAction()` / `serverLoader()`** — the client function- wraps the real server function, it does not replace it.-2. **Optional-chain the cache**: `window?.clientCache?.` — it may not exist yet.-3. **Scope by company**: build keys with `getCompanyId()`; bail to the server when it's- `null`.-4. `invalidateQueries({ predicate })` for bulk/prefix invalidation;- `setQueryData(key, null)` for one specific key.-5. Set `clientLoader.hydrate = true` so the cache warms on first load.--<!-- UNVERIFIED: claim that clientAction "can handle validation errors before hitting the-server" — the old supplier-processes example wasn't re-confirmed at grounding; treat-validation-in-clientAction as a rare special case, not the standard pattern. -->+After any non-GET request finishes, every `LOADER` entry is marked stale. The+action and the revalidation that follows it are separate passes through the+middleware, so the entries are already stale when the loaders re-run. Client+middleware wraps fetcher submissions too, so a modal's save is covered.++- A route does not name what its action changes. Do not add a `clientAction`+ to invalidate.+- `skipPaths` is for POSTs that change no data. `/refresh-session` fires on+ every tab focus and would otherwise refetch every list.+- It is deliberately blunt: saving a part also marks customer types stale,+ which costs one extra fetch the next time that list is used.+- Realtime invalidates the same entries when another user changes a reference+ table (see `realtime-system.md`).++## Reading in a component++| Hook | Use |+|---|---|+| `useLoaderQuery<T>(url \| null)` | Render with an `api+` URL's data. One request per URL however many components read it; refetches when invalidated. `T` is the data, or `typeof loader`. `null` waits |+| `cachedApiQuery<T>(url)` | The same read from an event handler or an effect |+| `useAction<T>({ onSuccess, onError, onSettled })` | A mutation fetcher whose result goes to a callback instead of an effect watching `fetcher.data`. Submit with `.submit()` or `<action.Form>` as with `useFetcher`. `onSettled` runs whenever a submission finishes; `onSuccess` / `onError` only when the action returned data (an action that redirects returns none) |++Do not write `useFetcher()` + `fetcher.load(url)` in a mount effect for an+`api+` list: it is one request per component, shows no cached value, and never+refetches after a save. Keep `useFetcher` for a load that happens on an event+(a search box, a drill-down click) or that calls a third party.++## The company in the key++The `companyId` cookie is httpOnly, so the browser cannot read it. Each shell+layout calls `setClientCompanyId(company.id)` during render, and `getCompanyId()`+returns that. Before this, `getCompanyId()` parsed `document.cookie` and always+returned `null`, so every key was scoped to the string `"null"`.++## Naming trap++Never name a module `*.client.ts` if a route calls something from it while the+module is evaluated. React Router empties `.client` modules on the server:+`createInvalidationMiddleware(...)` in `root.tsx` became "is not a function"+during SSR. Typecheck and unit tests pass with that bug in place.diff --git a/.claude/rules/coding-conventions.md b/.claude/rules/coding-conventions.mdindex bc386c9287..1604114a2f 100644--- a/.claude/rules/coding-conventions.md+++ b/.claude/rules/coding-conventions.md@@ -127,7 +127,8 @@ MES is lighter: services live under `apps/mes/app/services/`, components underparent loader runs for a request that is about to be redirected. Enforced by the`index-redirect-before-loaders` check (`@carbon/checks`).- On success an action throws a redirect (`throw redirect(...)`), not `return`.- Cached entities add a `clientAction`/`clientLoader` for cache control.+ A cached `api+` loader exports `clientLoader = cachedClientLoader<typeof loader>()`;+ no route exports a `clientAction`.## Errors: always log before you throw@@ -167,13 +168,17 @@ MES is lighter: services live under `apps/mes/app/services/`, components under## State- **Server state / route data**: React Router loaders.-- **Client read-through cache**: TanStack React Query (`window.clientCache`);- query keys are company-scoped, e.g. `["things", companyId]`- (`apps/erp/app/utils/react-query.ts`).+- **Client cache of server data**: TanStack Query through `@carbon/query`. A+ cached `api+` loader is `cachedClientLoader<typeof loader>()`, keyed by its+ URL; components read with `useLoaderQuery(url)`; the root middleware+ invalidates after every mutation. No hand-written query keys+ (see `clientAction-patterns.md`).+- **Realtime**: private broadcast topics through `@carbon/query`. A route+ declares its tables in `handle.realtime`; the live lists (`useItems`,+ `useCustomers`, `useSuppliers`, `usePeople`) are queries kept current by+ `LiveLists` (see `realtime-system.md`).- **Global UI state**: zustand (`apps/erp/app/stores/ui.ts`). nanostores is- legacy: it now only holds the realtime lists (`stores/items.ts`, `customers.ts`,- `suppliers.ts`, `people.ts`) and goes when that provider is rebuilt — do not add- new atoms.+ gone from the repo.## Path Helpersdiff --git a/.claude/rules/conventions-forms.md b/.claude/rules/conventions-forms.mdindex b8d20f5b3f..0ddb2237c3 100644--- a/.claude/rules/conventions-forms.md+++ b/.claude/rules/conventions-forms.md@@ -203,10 +203,7 @@ import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { data, redirect } from "react-router";import { thingValidator, upsertThing } from "~/modules/things";import { setCustomFields } from "~/utils/form";@@ -361,29 +358,24 @@ const typeOptions = thingTypes.map((t) => ({ label: t, value: t }));<Select name="type" label="Type" options={typeOptions} />```-### Client action (cache invalidation)+### Cache invalidation-Cached entities add a `clientAction` that clears/invalidates the company-scoped-query, then delegates. Two shapes are both in use:+Nothing to write. The root client middleware (`createInvalidationMiddleware`,+`@carbon/query`) marks every cached loader entry stale after any action, so a+form's route does not export a `clientAction` and does not name the lists it+changes. See `clientAction-patterns.md`.-```typescript-// Clear a specific cached query (most common for these list queries)-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(thingsQuery(getCompanyId()).queryKey, null);- return await serverAction();-}+### Reacting to the result-// Or invalidate by predicate on a company-scoped key-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- const companyId = getCompanyId();- window.clientCache?.invalidateQueries({- predicate: (query) => {- const queryKey = query.queryKey as string[];- return queryKey[0] === "things" && queryKey[1] === companyId;- }- });- return await serverAction();-}+Use `useAction` from `@carbon/query` instead of `useFetcher` plus an effect that+watches `fetcher.data`:++```typescript+const fetcher = useAction<typeof action>({+ onSuccess: () => onClose(),+ onError: (data) => toast.error(data.message)+});+// <ValidatedForm fetcher={fetcher} …> or fetcher.submit(…), as before```## Checklist@@ -396,6 +388,5 @@ export async function clientAction({ serverAction }: ClientActionFunctionArgs) {`validator(schema).validate(formData)` → service → flash/redirect- [ ] `setCustomFields(formData)` + `<CustomFormFields table="..." />` if thetable has custom fields-- [ ] `clientAction` if the entity is cached client-side- [ ] Path helpers in `~/utils/path` (use `path.to.*`, never hardcoded URLs)- [ ] Container matches neighboring routes (ModalDrawer, Card, inline, etc.)diff --git a/.claude/rules/database-patterns.md b/.claude/rules/database-patterns.mdindex 1acd60bc7d..9a8047148f 100644--- a/.claude/rules/database-patterns.md+++ b/.claude/rules/database-patterns.md@@ -309,4 +309,4 @@ export async function action({ request, params }: ActionFunctionArgs) {- New migration: `npm run db:migrate <name>` (avoid `000000` HHMMSS to prevent cross-branch collisions).- Follow `workflow-database-migration.md` and `conventions-database.md` when adding tables.-<!-- UNVERIFIED: realtime postgres_changes subscriptions exist in app code (e.g. apps/erp/app/hooks/useRealtime.tsx, RealtimeDataProvider.tsx) but are a UI concern, not a service-layer pattern, so omitted from this rule. -->+Realtime is not a service-layer pattern and is not covered here: see `realtime-system.md` (broadcast topics, `handle.realtime`, live lists).diff --git a/.claude/rules/event-system.md b/.claude/rules/event-system.mdindex 26c08f48c3..2b24cb9277 100644--- a/.claude/rules/event-system.md+++ b/.claude/rules/event-system.md@@ -57,6 +57,7 @@ behaviour arrived, not where to read the current definition. Details:- `dispatch_event_interceptors()` — BEFORE ROW. Runs named sync interceptor functions inline (data-integrity, not async).- `dispatch_event_after_interceptors()` — AFTER ROW. Same but post-commit-of-row, safe for FK refs (added `20260410030406`).- Both dispatchers are SECURITY DEFINER (`20260925121735`), so interceptors run as the owner on every write. Write a new interceptor as **SECURITY INVOKER**: it still runs as the owner from the dispatcher, but a direct `/rpc/<interceptor>` call with a forged payload runs under the caller's RLS. A SECURITY DEFINER interceptor is callable by anyone with the anon key as the owner — `public-definer-function-authorizes-caller` fails on it.+- **Which functions run on which table is declared in `packages/database/src/event-system/attachments.ts`**, and the interceptor bodies in `event-system/handlers/<name>.sql`. Neither is written in a migration; `authz sync` applies them through `set_event_triggers` and `authz migration` ships them (see `authz-manifest.md` → Event triggers). The two helpers below are what `set_event_triggers` calls.- `attach_event_trigger(table, sync_functions[], after_sync_functions[])` — helper that wires the BEFORE SYNC / AFTER SYNC / ASYNC STATEMENT triggers on a table (3rd arg added `20260410030406`). One signature is live, `(TEXT, TEXT[] DEFAULT, TEXT[] DEFAULT)`. `CREATE OR REPLACE` with an added parameter creates a sibling rather than replacing, and a 2-arg call then matches more than one candidate (`function attach_event_trigger(unknown, text[]) is not unique`, breaking every call site) — so adding an argument means a migration that drops the old signature first; `authz sync` refuses a file that would create an overload.- `attach_statement_handler(table, handler_functions[])` (`20260812002453`) — the STATEMENT-level counterpart to the row-level interceptors. Attaches each function as `trg_event_statement_<fn>_{ins,upd,del}` with transition tables `batched_new` / `batched_old`; an empty array detaches. Does **not** register the table for PGMQ dispatch. Used by `itemLedger` to maintain the `itemStockQuantities` aggregate.- Handlers are attached for all three operations, so each **must branch on `TG_OP`**: only `batched_new` exists on INSERT, only `batched_old` on DELETE. PL/pgSQL plans lazily, so a branch that doesn't run never resolves its missing transition table.diff --git a/.claude/rules/mes-job-operation-ui.md b/.claude/rules/mes-job-operation-ui.mdindex e07fe048fb..5e5548269b 100644--- a/.claude/rules/mes-job-operation-ui.md+++ b/.claude/rules/mes-job-operation-ui.md@@ -222,7 +222,7 @@ In batch mode `JobOperation` derives `isBatched = !!batch`,`ReworkModal`, `SerialSelectorModal`, `QualityIssueModal`, `MaintenanceDispatch`,`ScrapReason`, `Chat.tsx` (`OperationChat`), `TableSkeleton`.- **Hooks:** `hooks/useOperation.tsx` (modal disclosures, live progress via- `useInterval` + `useRealtimeChannel`, active-event detection, serial selection),+ `useInterval` + realtime (`@carbon/query`, see `realtime-system.md`), active-event detection, serial selection),`hooks/useFiles.tsx` (`downloadFile`/`downloadModel` via `path.to.file.previewFile`).## Tabsdiff --git a/.claude/rules/realtime-system.md b/.claude/rules/realtime-system.mdnew file mode 100644index 0000000000..b2102606f7--- /dev/null+++ b/.claude/rules/realtime-system.md@@ -0,0 +1,183 @@+---+paths:+ - "packages/query/**"+ - "packages/database/src/realtime-tables.ts"+ - "packages/database/src/event-system/attachments.ts"+ - "packages/database/src/event-system/functions/broadcast_*.sql"+ - "packages/database/src/event-system/functions/log_*.sql"+ - "apps/*/app/components/RealtimeDataProvider.tsx"+ - "apps/*/app/stores/**"+---++# Realtime: broadcast topics, route declarations, live lists++How a change in the database reaches an open page, and how the app catches up on+what it missed. Client code is in `@carbon/query` (`packages/query`). Nothing+uses `postgres_changes`: the `supabase_realtime` publication is empty, and the+`no-postgres-changes` check (`@carbon/checks`) fails a new subscription to it.++## The message++A statement-level trigger sends ONE message per company per statement:+`{ table, op, ids, parents }`, with `ids` and `parents` null past 100 rows.+`parents` holds each FOREIGN KEY `<name>Id` column of the changed rows and its+values (`{ jobId: ["job_…"] }`), plus the columns its ancestors add, so a page+that shows one record can ignore changes to another's rows; a column with more+than 20 values is left out. A column that only ends in `Id` (`readableId`, an+order's own number, `taxId`) is the row's data and is never sent — any employee+of the company may join any table's topic, so a filter on such a column cannot+work and matches every change. Only ids+leave the database — the client re-reads what it needs through PostgREST, so+table RLS still decides what each user sees.++A route scopes a table to its own record with+`{ table: "jobOperation", column: "jobId", param: "jobId" }` in+`handle.realtime` (`RouteRealtimeTable`; the column is checked against the+table's row type). `{ table, filter: ({ params, data }) => string | undefined }`+builds the filter from the route's loader data, for a record the URL does not+name (the MES operation page follows its job, or everything when it runs in a+batch); it returns `false` to follow nothing (a job with no model). A plain table name follows every change in the company: right for a+list page, wasteful on a detail page. A missing answer always means "it may+concern me": the filter can cause an extra reload, never a missed one. An+UPDATE names the values a row had as well as the ones it has, so a row moved+to another parent reaches both pages.++A table that reaches its record through another table gets that record's id+added: a production event carries `jobId`, read from its operation. The hops+are the `ancestors` constant in `broadcast_table_changes.sql`;+`REALTIME_ANCESTOR_COLUMNS` (`realtime-tables.ts`) types the same columns and+a test keeps the two equal. Add a hop there when a detail page must follow a+grandchild table. A hop with a fourth element looks the other way: a payment+has no invoice column, so its message names the invoices its+`invoiceSettlement` rows apply it to (`targetSalesInvoiceId`,+`targetPurchaseInvoiceId`; an empty list when it is applied to none). An+invoice page follows `invoiceSettlement` and `payment` on that column: voiding+a payment changes the payment row only.++The broadcast functions return at once when `realtime.send` does not exist, so+a database without Supabase Realtime still accepts writes.++| Function (`event-system/functions/`) | Topic | For |+|---|---|---|+| `broadcast_table_changes` | `company:<companyId>:<table>` | pages and live lists |+| `broadcast_reference_changes` | `company:<companyId>:reference` (one shared topic) | cached `api+` reference lists |+| `broadcast_user_changes` | `user:<userId>:<table>` | notifications |++- An UPDATE that changes only `updatedAt` / `updatedBy` / `embedding` sends+ nothing (the same list `dispatch_event_batch` ignores; `event-dispatch.test.ts`+ keeps the copies equal).+- `itemSupersession` has no `id`: its message carries the `itemId`.+ `implementationHub` has no `companyId`: its `id` is the company.+- Which tables broadcast is declared in `event-system/attachments.ts`, never in+ a migration (see `authz-manifest.md` → Event triggers). `REALTIME_TABLES` and+ the `RealtimeTable` type are DERIVED from it (`realtime-tables.ts`), so a table+ name with no handler does not compile.++## Who may listen++Topics are private. Two policies on `realtime.messages`, owned by the authz+manifest (`"realtime.messages"`): an employee of the company may join a+`company:` topic, and a user may join a `user:` topic that carries their own id.+Realtime checks the policy once, at join — not per change per subscriber, which+is what made `postgres_changes` a single-threaded bottleneck across tenants.+Pinned by `supabase/tests/realtime-broadcast.test.sql`.++## Making a page live++A route names the tables it shows:++```ts+export const handle: Handle = {+ realtime: ["job", "jobOperation", "jobMaterial"]+};+```++`RouteRealtime`, rendered once in each app shell, subscribes to the tables of+the matched routes and, 300 ms after the last message, invalidates the cached+loader entries and revalidates the page. A burst is one reload; a route and a+component following the same table reload once; a reload waits while a fetcher+is submitting (React Router drops a fetcher's redirect when a revalidation+starts during its action) and runs when it finishes.++- Update the list when the loader starts reading a new table. Nothing checks+ that a list is COMPLETE, only that each name can broadcast.+- A table missing from `attachments.ts`: add `broadcast_table_changes` to its+ entry, `pnpm db:migrate`, then `authz migration <name>`.++| For | Use |+|---|---|+| A component that is not a route | the app's `useRealtime(table, filter?)`. An `id=eq.` / `id=in.()` filter narrows it, and so does the same on a `<name>Id` column (`quoteLineId=eq.…`); a filter on any other column wakes on every change to the table |+| A component that keeps rows in its own state (a chat, running events) | `useChangedRows({ table, columns, onChange, onResync })` — it re-reads the changed rows and hands them over |+| Raw access to a topic | `useTableChanges` / `useTopic` |++**One channel per topic.** The Realtime client returns the SAME channel object+for a topic it already has, so two hooks that each opened one would tear each+other down. Every listener registers in a module-level registry and+`RouteRealtime` owns one channel per topic. Never call `carbon.channel(...)` or+`useRealtimeChannel` for a broadcast topic yourself; nothing is delivered unless+`RouteRealtime` is mounted.++## Live lists++`useItems`, `useCustomers`, `useSuppliers`, `usePeople` (and the MES pair) are+`LiveList` definitions in `apps/*/app/stores/`: the table, the ONE column list,+`fetchAll`, `fetchByIds`, `related` tables and the sort. The rows live in the+query cache under `["live", companyId, <name>]`; the hooks keep their+`[rows, setRows]` shape. `LiveLists` (in `RealtimeDataProvider`) loads them:++1. IndexedDB first (`<name>:<companyId>`), so pickers have options at once.+2. One `table_changes_since(cursor)` call.+3. Only the rows it names are re-read; a named row that does not come back is+ removed. The whole list is fetched once per device, and again only when the+ log answers `reset` or names more than 500 rows. Ids are re-read 100 per+ request: `.in()` goes in the URL, and a few hundred ids exceed the gateway's+ limit.+4. While the tab is open, broadcasts patch the list row by row. After a+ reconnect, step 2 runs again.++### The change log++`tableChange` (`20261004200418_table-change-log.sql`) is an UNLOGGED table: one+row per changed row of a list table, written by the `log_table_changes` /+`log_user_changes` statement handlers, purged after 7 days by `pg_cron`. It has+no API access; `table_changes_since` (SECURITY DEFINER, checks the caller's+company) is the only reader, and the backup engine skips the table.++- **The cursor is a transaction id** — `pg_snapshot_xmin(pg_current_snapshot())`+ — not the table's id or a timestamp. A sequence value is taken before commit,+ so "the highest id I saw" skips a row whose transaction commits late. With+ xmin a few rows are named twice; re-reading them is harmless.+- **`reset`** when there is no cursor, the log was emptied since it was issued,+ or the cursor is older than the retention less a day. The epoch is a token in+ `util."tableChangeEpoch"`, an UNLOGGED table the same crash recovery empties+ (the postmaster start time does not change when a backend crashes). With no+ token every call resets, until the hourly `util.purge_table_changes()` writes+ a new one. A writer that runs with triggers off (company restore) inserts a+ null-`rowId` row per `CHANGE_LOGGED_TABLES` entry itself.+- **`table_changes_since` must stay `STABLE`**: the read of the log and+ `pg_current_snapshot()` then share one snapshot. As `VOLATILE`, a change+ committed between the two is skipped for good.+- **No foreign key to `company`.** Deleting a company cascades to its items,+ whose log trigger inserts a row for a company already gone in that+ transaction; a key would abort the delete. The purge removes those rows.+- **One update of a list at a time** (`inTurn` in `useLiveList.tsx`): a full+ fetch and a broadcast's re-read would otherwise overlap, and the older read+ could land last.+- **A cursor belongs to one company.** `LiveLists` stays mounted across a+ company switch, so it keys cursors by company as well as list.+- **A patch is a function of the current rows** (`commit` in `useLiveList.tsx`),+ never a value computed before an awaited read: two broadcasts inside one+ round-trip would otherwise overwrite each other.+- A renamed `user` has no company; `log_user_changes` records it as an+ `employee` change for each company the user belongs to.+- To give another list a delta: add `log_table_changes` to its tables' entries+ in `attachments.ts`.++## Gotchas++- `payload.new` / `payload.old` do not exist. Re-read by id.+- Do not key a client cache without the company (`.ai/lessons.md`: an unkeyed+ IndexedDB copy once hydrated one company's pickers with another's rows).+- The first message after the first-ever private join on a fresh Realtime+ server was not delivered in one test (the replication slot is created at that+ join). Not reproduced since; the reconnect catch-up does not cover it.diff --git a/.claude/rules/table-csv-export.md b/.claude/rules/table-csv-export.mdindex 45e2cf74c8..5529affcf6 100644--- a/.claude/rules/table-csv-export.md+++ b/.claude/rules/table-csv-export.md@@ -114,7 +114,7 @@ optional, export/sort-related fields:`Map<id, name>` per store; falls back to the raw value if not found.- Renders nothing (and does nothing on click) when `data` is empty.-The stores are nanostore-backed hooks consumed as tuples,+The stores are live-list hooks (`useLiveList`, `@carbon/query`) consumed as tuples,e.g. `const [items] = useItems();`; each element exposes at least `{ id, name }`.## Opting in (example)diff --git a/.claude/rules/workflow-event-system.md b/.claude/rules/workflow-event-system.mdindex 8cb895f878..cb8d4a7f80 100644--- a/.claude/rules/workflow-event-system.md+++ b/.claude/rules/workflow-event-system.md@@ -26,7 +26,9 @@ the procedure, not a re-description — it does not repeat that detail.| Event-name type registry (`Events`) | `packages/lib/src/events.ts` (re-exported, NOT defined, by `packages/jobs/src/events.ts`) || Zod schemas + subscription helpers | `packages/database/src/event.ts` || `attach_event_trigger`, `dispatch_event_batch` and the other event-system functions | `packages/database/src/event-system/functions/<name>.sql` (edit the file, then `authz migration`; see `authz-manifest.md`) |-| Handler-type CHECK, per-table `attach_event_trigger(...)` calls | `packages/database/supabase/migrations/` |+| Handler-type CHECK | `packages/database/supabase/migrations/` |+| Which functions run on which table (event triggers) | `packages/database/src/event-system/attachments.ts` |+| Interceptor and statement-handler bodies | `packages/database/src/event-system/handlers/<name>.sql` |## Use cases → handler type@@ -45,7 +47,18 @@ the procedure, not a re-description — it does not repeat that detail.### 1. Create a migration-Triggers are wired by the SQL helper `attach_event_trigger`. Its current signature+Triggers are declared in `packages/database/src/event-system/attachments.ts`, never in a+migration (see `authz-manifest.md` → Event triggers). Add the table's entry there:++```ts+yourNewTable: { events: true }, // async only+yourNewTable: { before: ["validate_before_insert"], events: true }, // BEFORE ROW interceptors+yourNewTable: { after: ["sync_create_entries"], events: true }, // AFTER ROW interceptors+```++Then `pnpm db:migrate` and `pnpm --filter @carbon/database authz migration <name>`. The+SQL below is what that renders through `set_event_triggers`; it is shown for the meaning+of each list, not to be written by hand. `attach_event_trigger`'s signaturetakes **three** args (the 3rd added in `20260410030406_event-system-after-interceptors.sql`):```sql@@ -283,7 +296,7 @@ that path; it does not exist.## Checklist-- [ ] Trigger attached via `attach_event_trigger(table, sync[], after_sync[])` (3-arg)+- [ ] Trigger declared in `event-system/attachments.ts` and shipped with `authz migration`- [ ] Subscription(s) created with correct `companyId` and uppercase `operations`- [ ] (new type) `HandlerTypeSchema` widened in `packages/database/src/event.ts`- [ ] (new type) `handlerType` CHECK widened in a new migrationdiff --git a/.claude/rules/workflow-run-history.md b/.claude/rules/workflow-run-history.mdindex 7477623e7f..c6f6ec755b 100644--- a/.claude/rules/workflow-run-history.md+++ b/.claude/rules/workflow-run-history.md@@ -142,5 +142,6 @@ information the tool exists to show.`RunLiveUpdates` / `RunsLiveUpdates` in `ui/Runs/RunLiveUpdates.tsx` use `useDebouncedRealtime`to revalidate the loader after 1.5 s of quiet. They mount only while at least one row is-non-terminal — an unfiltered subscription on `workflowStepRun` would fire on every company's-every step. Caller supplies the filter; the hook does not add `companyId` itself.+non-terminal. The broadcast topic is per company, so the runs list follows `workflowRun`+with no filter; the run drawer filters `workflowStepRun` on `runId` and `workflowRun` on+`id` (see `realtime-system.md`).diff --git a/AGENTS.md b/AGENTS.mdindex 1cba51f89b..2f4d9aa4f0 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -132,6 +132,9 @@ IMPORTANT: Before any research or coding, match the task to this table. A single| Linear integration | `.claude/rules/linear-integration.md` || Xero API / webhooks | `.claude/rules/xero-api-contact-structure.md` + `.claude/rules/xero-webhooks.md` || Redis (shared dev) | `.claude/rules/dev-shared-redis.md` |+| Client cache (`cachedClientLoader`, `useLoaderQuery`, `useAction`) | `.claude/rules/clientAction-patterns.md` + `packages/query/AGENTS.md` |+| Realtime (broadcast, `handle.realtime`, live lists, change log) | `.claude/rules/realtime-system.md` + `packages/query/AGENTS.md` |+| Event triggers and interceptors (attachments manifest) | `.claude/rules/authz-manifest.md` || **Architecture** | || General coding conventions | `.claude/rules/coding-conventions.md` || Date & time handling (no JS `Date`) | `.claude/rules/date-handling.md` |@@ -206,7 +209,7 @@ IMPORTANT: Before any research or coding, match the task to this table. A single- **Database**: Supabase (Postgres) with RLS, typed via `@carbon/database` + Kysely- **Background jobs**: Inngest (NOT Trigger.dev), via `@carbon/jobs`- **Apps**: `erp` (main), `mes` (shop floor), `academy` (training), `starter` (example)-- **Packages**: 28 under `packages/` — auth, database, lib, react, form, documents, jobs, notifications, config, env, checks, harness, dev, stripe, ee, tiptap, locale, utils, files, kv, printing, onboarding, logger, server-functions, planning, api, viewer, workflows-core — plus `@carbon/content` at `docs/content` (docs MDX + glossary)+- **Packages**: 29 under `packages/` — auth, database, lib, react, query, form, documents, jobs, notifications, config, env, checks, harness, dev, stripe, ee, tiptap, locale, utils, files, kv, printing, onboarding, logger, server-functions, planning, api, viewer, workflows-core — plus `@carbon/content` at `docs/content` (docs MDX + glossary)- **Multi-tenancy**: every table has `companyId` + composite PK `("id", "companyId")`- **IDs**: `id('prefix')` default in SQL- **Imports**: `~/*` → app code; `@carbon/*` → workspace packagesdiff --git a/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx b/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsxindex e4da53d624..44fc591ddb 100644--- a/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx+++ b/apps/erp/app/components/Configurator/ConfiguratorForm/ConfiguratorForm.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useLoaderQuery } from "@carbon/query";import {Alert,AlertTitle,@@ -27,13 +28,11 @@ import {SelectTrigger,SelectValue,Switch,- toast,- useMount+ toast} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import { createContext, useContext, useEffect, useMemo, useState } from "react";import { LuChevronDown, LuChevronUp, LuTriangleAlert } from "react-icons/lu";-import { useFetcher } from "react-router";import { z } from "zod";import { zfd } from "zod-form-data";import type {@@ -102,13 +101,9 @@ type MaterialOption = {function useMaterialsWithFilter(materialFormFilterId?: string | null) {const allMaterials = useMaterials();- const materialsFetcher = useFetcher<{ data: MaterialOption[] }>();-- useMount(() => {- if (materialFormFilterId) {- materialsFetcher.load(path.to.api.materials(materialFormFilterId));- }- });+ const materialsFetcher = useLoaderQuery<{ data: MaterialOption[] }>(+ materialFormFilterId ? path.to.api.materials(materialFormFilterId) : null+ );const materials = useMemo(() => {if (materialFormFilterId && materialsFetcher.data?.data) {diff --git a/apps/erp/app/components/DocumentTemplateEditor/context.tsx b/apps/erp/app/components/DocumentTemplateEditor/context.tsxindex 7233d36b16..4241fe3e8a 100644--- a/apps/erp/app/components/DocumentTemplateEditor/context.tsx+++ b/apps/erp/app/components/DocumentTemplateEditor/context.tsx@@ -12,6 +12,7 @@ import {type DocumentTheme,type HeaderOptions} from "@carbon/documents/template";+import { useAction } from "@carbon/query";import type { JSONContent } from "@carbon/react";import { arrayMove } from "@dnd-kit/sortable";import { nanoid } from "nanoid";@@ -24,7 +25,6 @@ import {useMemo,useRef} from "react";-import { useFetcher } from "react-router";import type { StoreApi } from "zustand";import { createStore, useStore } from "zustand";import { useShallow } from "zustand/react/shallow";@@ -329,7 +329,14 @@ export function DocumentTemplateProvider({store.setState({ sections: props.sections });}, [store, props.sections]);- const fetcher = useFetcher<{ success?: boolean }>();+ const fetcher = useAction<{ success?: boolean }>({+ onSuccess: (data) => {+ if (savedRef.current && data?.success) {+ savedRef.current = false;+ store.getState().rebaseline();+ }+ }+ });const isSaving = fetcher.state !== "idle";const savedRef = useRef(false);@@ -347,14 +354,6 @@ export function DocumentTemplateProvider({fetcher.submit(formData, { method: "post", action: props.actionPath });}, [store, fetcher, props.actionPath]);- // Once our save resolves, clear the dirty baseline to the just-saved state.- useEffect(() => {- if (savedRef.current && fetcher.state === "idle" && fetcher.data?.success) {- savedRef.current = false;- store.getState().rebaseline();- }- }, [fetcher.data, fetcher.state, store]);-const value = useMemo(() => ({ store, save, isSaving }),[store, save, isSaving]diff --git a/apps/erp/app/components/DocumentTemplateEditor/useTemplateConflict.tsx b/apps/erp/app/components/DocumentTemplateEditor/useTemplateConflict.tsxindex 2df3f7c27b..3ab0ab785c 100644--- a/apps/erp/app/components/DocumentTemplateEditor/useTemplateConflict.tsx+++ b/apps/erp/app/components/DocumentTemplateEditor/useTemplateConflict.tsx@@ -2,7 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useRealtimeChannel } from "@carbon/react";+import { useChangedRows } from "@carbon/query";import { useState } from "react";import { useUser } from "~/hooks";@@ -20,28 +20,19 @@ export function useTemplateConflict(documentType: string) {const { id: userId, company } = useUser();const [conflict, setConflict] = useState(false);- useRealtimeChannel({- topic: `document-template-conflict:${documentType}`,- dependencies: [company.id, documentType, userId],- setup(channel) {- return channel.on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "documentTemplate",- filter: `companyId=eq.${company.id}`- },- (payload) => {- const row = payload.new as- | { documentType?: string; updatedBy?: string }- | undefined;- // Only this template, and only someone else's write.- if (!row || row.documentType !== documentType) return;- if (!row.updatedBy || row.updatedBy === userId) return;- setConflict(true);- }+ useChangedRows<{ id: string; documentType?: string; updatedBy?: string }>({+ companyId: company.id,+ table: "documentTemplate",+ columns: "id, documentType, updatedBy",+ onChange: ({ rows }) => {+ // Only this template, and only someone else's write.+ const theirs = rows.some(+ (row) =>+ row.documentType === documentType &&+ row.updatedBy &&+ row.updatedBy !== userId);+ if (theirs) setConflict(true);}});diff --git a/apps/erp/app/components/Form/Ability.tsx b/apps/erp/app/components/Form/Ability.tsxindex ceb04d7361..fdbe804e0f 100644--- a/apps/erp/app/components/Form/Ability.tsx+++ b/apps/erp/app/components/Form/Ability.tsx@@ -4,9 +4,8 @@import type { ComboboxProps } from "@carbon/form";import { Combobox } from "@carbon/form";-import { useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";import { useMemo } from "react";-import { useFetcher } from "react-router";import type { getAbilitiesList } from "~/modules/resources";import { path } from "~/utils/path";import { useEmptyState } from "./emptyStates";@@ -33,12 +32,9 @@ Ability.displayName = "Ability";export default Ability;export const useAbilities = () => {- const abilityFetcher =- useFetcher<Awaited<ReturnType<typeof getAbilitiesList>>>();-- useMount(() => {- abilityFetcher.load(path.to.api.abilities);- });+ const abilityFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getAbilitiesList>>+ >(path.to.api.abilities);const options = useMemo(() =>diff --git a/apps/erp/app/components/Form/Account.tsx b/apps/erp/app/components/Form/Account.tsxindex afa9bdcd44..2999b3c4c3 100644--- a/apps/erp/app/components/Form/Account.tsx+++ b/apps/erp/app/components/Form/Account.tsx@@ -4,16 +4,11 @@import type { ComboboxProps } from "@carbon/form";import { Combobox } from "@carbon/form";-import { Badge, Combobox as ComboboxBase, useMount } from "@carbon/react";-import { useEffect, useMemo, useState } from "react";-import { useFetcher } from "react-router";+import { useLoaderQuery } from "@carbon/query";+import { Badge, Combobox as ComboboxBase } from "@carbon/react";+import { useMemo } from "react";import type { AccountClass, getAccountsList } from "~/modules/accounting";import { path } from "~/utils/path";-import {- accountsQuery,- getClientCache,- getCompanyId-} from "~/utils/react-query";type AccountData = {id: string;@@ -23,27 +18,13 @@ type AccountData = {incomeBalance: string | null;};+const NO_ACCOUNTS: AccountData[] = [];+export function useAccounts(classes?: AccountClass[]): AccountData[] {- const fetcher = useFetcher<Awaited<ReturnType<typeof getAccountsList>>>();- const companyId = getCompanyId();- const { queryKey } = accountsQuery(companyId);-- const [accounts, setAccounts] = useState<AccountData[]>(() => {- return getClientCache()?.getQueryData<AccountData[]>(queryKey) ?? [];- });-- useMount(() => {- if (accounts.length === 0) {- fetcher.load(`${path.to.api.accounts}?isGroup=false`);- }- });-- useEffect(() => {- if (fetcher.data?.data) {- getClientCache()?.setQueryData(queryKey, fetcher.data.data);- setAccounts(fetcher.data.data as AccountData[]);- }- }, [fetcher.data, queryKey]);+ const { data } = useLoaderQuery<Awaited<ReturnType<typeof getAccountsList>>>(+ `${path.to.api.accounts}?isGroup=false`+ );+ const accounts = (data?.data ?? NO_ACCOUNTS) as AccountData[];return useMemo(() => {if (!classes || classes.length === 0) return accounts;diff --git a/apps/erp/app/components/Form/AssemblyInstruction.tsx b/apps/erp/app/components/Form/AssemblyInstruction.tsxindex 0897b7450f..69fa796c4d 100644--- a/apps/erp/app/components/Form/AssemblyInstruction.tsx+++ b/apps/erp/app/components/Form/AssemblyInstruction.tsx@@ -4,9 +4,9 @@import type { ComboboxProps } from "@carbon/form";import { Combobox } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import { HStack } from "@carbon/react";-import { useEffect, useMemo } from "react";-import { useFetcher } from "react-router";+import { useMemo } from "react";import type { getAssemblyInstructionsForItem } from "~/modules/production/production.service";import AssemblyInstructionStatus from "~/modules/production/ui/Assemblies/AssemblyInstructionStatus";import { path } from "~/utils/path";@@ -38,17 +38,11 @@ export default AssemblyInstruction;export const useAssemblyInstructions = (args: { itemId?: string }) => {const { itemId } = args;- const assemblyInstructionFetcher =- useFetcher<Awaited<ReturnType<typeof getAssemblyInstructionsForItem>>>();+ const assemblyInstructionFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getAssemblyInstructionsForItem>>+ >(itemId ? path.to.api.assemblyInstructions(itemId) : null);- // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher.load is not referentially stable; reload only when itemId changes- useEffect(() => {- if (itemId) {- assemblyInstructionFetcher.load(path.to.api.assemblyInstructions(itemId));- }- }, [itemId]);-- const loading = assemblyInstructionFetcher.state !== "idle";+ const loading = assemblyInstructionFetcher.isFetching;const options = useMemo(() =>diff --git a/apps/erp/app/components/Form/AssetClass.tsx b/apps/erp/app/components/Form/AssetClass.tsxindex 93d094bde1..0fc995056d 100644--- a/apps/erp/app/components/Form/AssetClass.tsx+++ b/apps/erp/app/components/Form/AssetClass.tsx@@ -4,7 +4,8 @@import type { CreatableComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useMemo, useRef, useState } from "react";import { useFetcher } from "react-router";import type { getFixedAssetClassesList } from "~/modules/accounting";@@ -103,12 +104,9 @@ AssetClass.displayName = "AssetClass";export default AssetClass;export const useAssetClasses = () => {- const assetClassFetcher =- useFetcher<Awaited<ReturnType<typeof getFixedAssetClassesList>>>();-- useMount(() => {- assetClassFetcher.load(path.to.api.assetClasses);- });+ const assetClassFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getFixedAssetClassesList>>+ >(path.to.api.assetClasses);const assetClasses = useMemo(() => assetClassFetcher.data?.data ?? [],diff --git a/apps/erp/app/components/Form/CostCenter.tsx b/apps/erp/app/components/Form/CostCenter.tsxindex d732e73d44..4c0b4a035d 100644--- a/apps/erp/app/components/Form/CostCenter.tsx+++ b/apps/erp/app/components/Form/CostCenter.tsx@@ -4,9 +4,9 @@import type { ComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import { useUser } from "~/hooks/useUser";import type { getCostCentersList } from "~/modules/accounting";import CostCenterForm from "~/modules/accounting/ui/CostCenters/CostCenterForm";@@ -64,12 +64,9 @@ CostCenter.displayName = "CostCenter";export default CostCenter;export const useCostCenters = () => {- const costCenterFetcher =- useFetcher<Awaited<ReturnType<typeof getCostCentersList>>>();-- useMount(() => {- costCenterFetcher.load(path.to.api.costCenters);- });+ const costCenterFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getCostCentersList>>+ >(path.to.api.costCenters);const options = useMemo(() =>diff --git a/apps/erp/app/components/Form/Country.tsx b/apps/erp/app/components/Form/Country.tsxindex 1bb23273cf..8c4722d883 100644--- a/apps/erp/app/components/Form/Country.tsx+++ b/apps/erp/app/components/Form/Country.tsx@@ -3,10 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import type { ComboboxProps } from "@carbon/form";-import { useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";import { useLingui } from "@lingui/react/macro";import { useMemo } from "react";-import { useFetcher } from "react-router";import { Combobox } from "~/components/Form";import type { getCountries } from "~/modules/shared";import { path } from "~/utils/path";@@ -25,11 +24,9 @@ Country.displayName = "Country";export default Country;export const useCountries = (enabled = true) => {- const countryFetcher = useFetcher<Awaited<ReturnType<typeof getCountries>>>();-- useMount(() => {- if (enabled) countryFetcher.load(path.to.api.countries);- });+ const countryFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getCountries>>+ >(enabled ? path.to.api.countries : null);const options = useMemo(() => {return (countryFetcher.data?.data ?? []).map((c) => ({diff --git a/apps/erp/app/components/Form/CustomerContact.tsx b/apps/erp/app/components/Form/CustomerContact.tsxindex cefceb024f..b054390fa7 100644--- a/apps/erp/app/components/Form/CustomerContact.tsx+++ b/apps/erp/app/components/Form/CustomerContact.tsx@@ -4,10 +4,10 @@import type { ComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import { Avatar, HStack, useDisclosure } from "@carbon/react";import { useLingui } from "@lingui/react/macro";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";+import { useMemo, useRef, useState } from "react";import type {CustomerContact as CustomerContactType,getCustomerContacts@@ -114,20 +114,10 @@ const CustomerContact = ({export default CustomerContact;function useCustomerContacts(customerId?: string) {- const customerContactsFetcher =- useFetcher<Awaited<ReturnType<typeof getCustomerContacts>>>();-- const reload = useCallback(() => {- if (customerId) {- customerContactsFetcher.load(path.to.api.customerContacts(customerId));- }- // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher identity is stable- }, [customerId]);-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- reload();- }, [customerId]);+ const customerContactsFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getCustomerContacts>>+ >(customerId ? path.to.api.customerContacts(customerId) : null);+ const reload = customerContactsFetcher.refetch;const options = useMemo(() =>diff --git a/apps/erp/app/components/Form/CustomerLocation.tsx b/apps/erp/app/components/Form/CustomerLocation.tsxindex 49a9875342..265def4f2b 100644--- a/apps/erp/app/components/Form/CustomerLocation.tsx+++ b/apps/erp/app/components/Form/CustomerLocation.tsx@@ -4,11 +4,11 @@import type { ComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import { useDisclosure } from "@carbon/react";import { formatAddress } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import { useEffect, useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";+import { useMemo, useRef, useState } from "react";import type {CustomerLocation as CustomerLocationType,getCustomerLocations@@ -40,20 +40,14 @@ const CustomerLocation = ({...props}: CustomerLocationSelectProps) => {const { t } = useLingui();- const customerLocationsFetcher =- useFetcher<Awaited<ReturnType<typeof getCustomerLocations>>>();+ const customerLocationsFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getCustomerLocations>>+ >(customer ? path.to.api.customerLocations(customer) : null);const newLocationModal = useDisclosure();const [created, setCreated] = useState<string>("");const triggerRef = useRef<HTMLButtonElement>(null);- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (customer) {- customerLocationsFetcher.load(path.to.api.customerLocations(customer));- }- }, [customer]);-const options = useMemo(() =>customerLocationsFetcher.data?.data?.map((c) => ({@@ -108,12 +102,6 @@ const CustomerLocation = ({onClose={() => {setCreated("");newLocationModal.onClose();- // Reload the per-customer fetcher so a just-created location appears.- if (customer) {- customerLocationsFetcher.load(- path.to.api.customerLocations(customer)- );- }triggerRef.current?.click();}}initialValues={{diff --git a/apps/erp/app/components/Form/CustomerStatus.tsx b/apps/erp/app/components/Form/CustomerStatus.tsxindex 1c13c7ac40..a2e5c96380 100644--- a/apps/erp/app/components/Form/CustomerStatus.tsx+++ b/apps/erp/app/components/Form/CustomerStatus.tsx@@ -4,10 +4,10 @@import type { ComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useLingui } from "@lingui/react/macro";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import { Enumerable } from "~/components/Enumerable";import { useRouteData } from "~/hooks";import type {@@ -72,19 +72,15 @@ CustomerStatus.displayName = "CustomerStatus";export default CustomerStatus;export const useCustomerStatuses = (enabled = true) => {- const customerStatusFetcher =- useFetcher<Awaited<ReturnType<typeof getCustomerStatusesList>>>();-const sharedCustomerData = useRouteData<{customerStatuses: CustomerStatusStatus[];}>(path.to.customerRoot);const hasCustomerData = sharedCustomerData?.customerStatuses;- useMount(() => {- if (enabled && !hasCustomerData)- customerStatusFetcher.load(path.to.api.customerStatuses);- });+ const customerStatusFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getCustomerStatusesList>>+ >(enabled && !hasCustomerData ? path.to.api.customerStatuses : null);const options = useMemo(() => {const dataSource =diff --git a/apps/erp/app/components/Form/CustomerType.tsx b/apps/erp/app/components/Form/CustomerType.tsxindex c881fb3687..381dbaf56b 100644--- a/apps/erp/app/components/Form/CustomerType.tsx+++ b/apps/erp/app/components/Form/CustomerType.tsx@@ -4,9 +4,9 @@import type { ComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import { Enumerable } from "~/components/Enumerable";import type { getCustomerTypesList } from "~/modules/sales";import { CustomerTypeForm } from "~/modules/sales/ui/CustomerTypes";@@ -69,12 +69,9 @@ CustomerType.displayName = "CustomerType";export default CustomerType;export const useCustomerTypes = (enabled = true) => {- const customerTypeFetcher =- useFetcher<Awaited<ReturnType<typeof getCustomerTypesList>>>();-- useMount(() => {- if (enabled) customerTypeFetcher.load(path.to.api.customerTypes);- });+ const customerTypeFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getCustomerTypesList>>+ >(enabled ? path.to.api.customerTypes : null);const options = useMemo(() => {const dataSource = customerTypeFetcher.data?.data ?? [];diff --git a/apps/erp/app/components/Form/Department.tsx b/apps/erp/app/components/Form/Department.tsxindex f88b818df9..4277831299 100644--- a/apps/erp/app/components/Form/Department.tsx+++ b/apps/erp/app/components/Form/Department.tsx@@ -4,9 +4,9 @@import type { ComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import { Enumerable } from "~/components/Enumerable";import type { getDepartmentsList } from "~/modules/people";import DepartmentForm from "~/modules/people/ui/Departments/DepartmentForm";@@ -64,12 +64,9 @@ Department.displayName = "Department";export default Department;export const useDepartments = () => {- const departmentFetcher =- useFetcher<Awaited<ReturnType<typeof getDepartmentsList>>>();-- useMount(() => {- departmentFetcher.load(path.to.api.departments);- });+ const departmentFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getDepartmentsList>>+ >(path.to.api.departments);const options = useMemo(() =>diff --git a/apps/erp/app/components/Form/EmailRecipients.tsx b/apps/erp/app/components/Form/EmailRecipients.tsxindex fdf55a9360..0dad2d0f5a 100644--- a/apps/erp/app/components/Form/EmailRecipients.tsx+++ b/apps/erp/app/components/Form/EmailRecipients.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { useField } from "@carbon/form";+import { cachedApiQuery, RefreshRate } from "@carbon/query";import {Badge,BadgeCloseButton,@@ -33,13 +34,6 @@ import { LuUsers } from "react-icons/lu";import type { User, UserSelectGroup } from "~/modules/users";import { isValidEmail } from "~/utils/form";import { path } from "~/utils/path";-import {- cachedApiQuery,- getCompanyId,- groupEmailsQuery,- userSelectGroupsQuery,- userSelectSearchQuery-} from "~/utils/react-query";type EmailRecipientsProps = {name: string;@@ -82,9 +76,7 @@ const useEmailOptions = (} | null>(null);useMount(() => {- const companyId = getCompanyId();cachedApiQuery<{ groups: UserSelectGroup[]; hasMore: boolean }>(- userSelectGroupsQuery(companyId, type, 0),path.to.api.userSelectGroups(type, 0)).then((data) => setTopGroups(data.groups))@@ -98,11 +90,10 @@ const useEmailOptions = (setSearchResults(null);return;}- const companyId = getCompanyId();const timeout = setTimeout(() => {cachedApiQuery<{ groups: UserSelectGroup[]; users: User[] }>(- userSelectSearchQuery(companyId, type, q, ""),- path.to.api.userSelectSearch(q, type)+ path.to.api.userSelectSearch(q, type),+ { staleTime: RefreshRate.High }).then(setSearchResults).catch(() => setSearchResults(null));@@ -229,13 +220,9 @@ export default function EmailRecipients({addEmail(option.email);} else {try {- const companyId = getCompanyId();const { emails: groupEmails } = await cachedApiQuery<{emails: string[];- }>(- groupEmailsQuery(companyId, option.id),- path.to.api.userSelectGroupEmails(option.id)- );+ }>(path.to.api.userSelectGroupEmails(option.id));addEmails(groupEmails);} catch {// leave the input as-is — selecting again retriesdiff --git a/apps/erp/app/components/Form/Gauge.tsx b/apps/erp/app/components/Form/Gauge.tsxindex 3ba905cc28..5439a1b2e8 100644--- a/apps/erp/app/components/Form/Gauge.tsx+++ b/apps/erp/app/components/Form/Gauge.tsx@@ -4,10 +4,10 @@import type { ComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { getLocalTimeZone, today } from "@internationalized/date";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import { useUser } from "~/hooks";import type { getGaugesList, getGaugeTypesList } from "~/modules/quality";import GaugeForm from "~/modules/quality/ui/Gauge/GaugeForm";@@ -79,14 +79,10 @@ Gauge.displayName = "Gauge";export default Gauge;export const useGauges = () => {- const gaugeFetcher = useFetcher<{+ const gaugeFetcher = useLoaderQuery<{gauges: Awaited<ReturnType<typeof getGaugesList>>["data"];gaugeTypes: Awaited<ReturnType<typeof getGaugeTypesList>>["data"];- }>();-- useMount(() => {- gaugeFetcher.load(path.to.api.gauges);- });+ }>(path.to.api.gauges);const options = useMemo(() =>diff --git a/apps/erp/app/components/Form/InspectionDocument.tsx b/apps/erp/app/components/Form/InspectionDocument.tsxindex d61bcdb06a..564a579188 100644--- a/apps/erp/app/components/Form/InspectionDocument.tsx+++ b/apps/erp/app/components/Form/InspectionDocument.tsx@@ -4,9 +4,9 @@import type { ComboboxProps } from "@carbon/form";import { Combobox } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import { HStack } from "@carbon/react";-import { useEffect, useMemo } from "react";-import { useFetcher } from "react-router";+import { useMemo } from "react";import type { getInspectionDocumentsForItem } from "~/modules/quality/quality.service";import { path } from "~/utils/path";@@ -37,17 +37,11 @@ export default InspectionDocument;export const useInspectionDocuments = (args: { itemId?: string }) => {const { itemId } = args;- const inspectionDocumentFetcher =- useFetcher<Awaited<ReturnType<typeof getInspectionDocumentsForItem>>>();+ const inspectionDocumentFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getInspectionDocumentsForItem>>+ >(itemId ? path.to.api.inspectionDocuments(itemId) : null);- // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher.load is not referentially stable; reload only when itemId changes- useEffect(() => {- if (itemId) {- inspectionDocumentFetcher.load(path.to.api.inspectionDocuments(itemId));- }- }, [itemId]);-- const loading = inspectionDocumentFetcher.state !== "idle";+ const loading = inspectionDocumentFetcher.isFetching;const options = useMemo(() =>diff --git a/apps/erp/app/components/Form/IssueType.tsx b/apps/erp/app/components/Form/IssueType.tsxindex 1ce34d61a2..09988578d9 100644--- a/apps/erp/app/components/Form/IssueType.tsx+++ b/apps/erp/app/components/Form/IssueType.tsx@@ -2,21 +2,17 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";import { useMemo } from "react";-import { useFetcher } from "react-router";import type { getIssueTypesList } from "~/modules/quality";import { path } from "~/utils/path";/** The company's issue types, read through the shared client cache. The quality screens* still hand-roll their own issue-type dropdown; a selector built on this belongs here. */export const useIssueTypes = () => {- const issueTypeFetcher =- useFetcher<Awaited<ReturnType<typeof getIssueTypesList>>>();-- useMount(() => {- issueTypeFetcher.load(path.to.api.issueTypes);- });+ const issueTypeFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getIssueTypesList>>+ >(path.to.api.issueTypes);return useMemo(() =>diff --git a/apps/erp/app/components/Form/Item.tsx b/apps/erp/app/components/Form/Item.tsxindex 3f9439a9b2..d468ac00e6 100644--- a/apps/erp/app/components/Form/Item.tsx+++ b/apps/erp/app/components/Form/Item.tsx@@ -4,6 +4,7 @@import type { ComboboxProps } from "@carbon/form";import { useControlField, useField } from "@carbon/form";+import { RefreshRate, useLoaderQuery } from "@carbon/query";import {Button,CreatableCombobox,@@ -27,14 +28,11 @@ import {Tooltip,TooltipContent,TooltipTrigger,- useDisclosure,- useMount+ useDisclosure} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useQuery } from "@tanstack/react-query";import { useEffect, useMemo, useRef, useState } from "react";import { LuFilter, LuTriangleAlert } from "react-icons/lu";-import { useFetcher } from "react-router";import ConsumableForm from "~/modules/items/ui/Consumables/ConsumableForm";import MaterialForm from "~/modules/items/ui/Materials/MaterialForm";import PartForm from "~/modules/items/ui/Parts/PartForm";@@ -45,7 +43,6 @@ import { itemType, methodItemType } from "~/modules/shared";import { useItems } from "~/stores";import { latestRevisionByReadableId } from "~/stores/items";import { path } from "~/utils/path";-import { getCompanyId, itemQuantitiesQuery } from "~/utils/react-query";import { MethodItemTypeIcon } from "../Icons";import { ItemLifecycleBadge } from "../ItemLifecycleBadge";import type { EntityKey } from "./emptyStates";@@ -120,27 +117,15 @@ const NO_QUANTITIES: Record<string, number> = {};* picker on the page.** An OBSERVED query, not the imperative `cachedApiQuery` read-through: a stock- * movement invalidates this key (`RealtimeDataProvider`), and only an observer+ * movement invalidates this entry (`RealtimeDataProvider`), and only an observer* re-fetches and re-renders. Copying one result into state left an open picker* showing yesterday's numbers until it remounted.*/function useItemQuantities(locationId?: string) {- const scope = locationId ?? "all";- const { queryKey, staleTime } = itemQuantitiesQuery(scope, getCompanyId());-- const { data } = useQuery({- queryKey,- staleTime,- queryFn: async () => {- const response = await fetch(path.to.api.itemQuantities(scope));- if (!response.ok) {- throw new Error(`Request failed with status ${response.status}`);- }- return (await response.json()) as {- data: Record<string, number> | null;- };- }- });+ const { data } = useLoaderQuery<{ data: Record<string, number> | null }>(+ path.to.api.itemQuantities(locationId ?? "all"),+ { staleTime: RefreshRate.High }+ );// A badge is decoration — a failed read leaves it off rather than breaking// the picker.@@ -685,13 +670,9 @@ Item.displayName = "Item";export default Item;export const useConfigurableItems = () => {- const configurableItemsLoader = useFetcher<{+ const configurableItemsLoader = useLoaderQuery<{data: { itemId: string }[] | null;- }>();-- useMount(() => {- configurableItemsLoader.load(path.to.api.itemConfigurable);- });+ }>(path.to.api.itemConfigurable);const configurableItemIds = useMemo(() => {return (configurableItemsLoader.data?.data ?? []).map((c) => c.itemId);diff --git a/apps/erp/app/components/Form/ItemPostingGroup.tsx b/apps/erp/app/components/Form/ItemPostingGroup.tsxindex 5795ff99ae..a3f0a01828 100644--- a/apps/erp/app/components/Form/ItemPostingGroup.tsx+++ b/apps/erp/app/components/Form/ItemPostingGroup.tsx@@ -4,9 +4,9 @@import type { CreatableComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import type { getItemPostingGroupsList } from "~/modules/items";import ItemPostingGroupForm from "~/modules/items/ui/ItemPostingGroups/ItemPostingGroupForm";import { path } from "~/utils/path";@@ -80,12 +80,9 @@ ItemPostingGroup.displayName = "ItemPostingGroup";export default ItemPostingGroup;export const useItemPostingGroups = () => {- const itemGroupFetcher =- useFetcher<Awaited<ReturnType<typeof getItemPostingGroupsList>>>();-- useMount(() => {- itemGroupFetcher.load(path.to.api.itemPostingGroups);- });+ const itemGroupFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getItemPostingGroupsList>>+ >(path.to.api.itemPostingGroups);const options = useMemo(() =>diff --git a/apps/erp/app/components/Form/JobSalesOrderLine.tsx b/apps/erp/app/components/Form/JobSalesOrderLine.tsxindex f960d1572f..f22e45461a 100644--- a/apps/erp/app/components/Form/JobSalesOrderLine.tsx+++ b/apps/erp/app/components/Form/JobSalesOrderLine.tsx@@ -14,10 +14,10 @@import type { ComboboxProps } from "@carbon/form";import { Combobox, FieldEmptyState } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import { useLingui } from "@lingui/react/macro";import type { ReactNode } from "react";-import { useEffect, useMemo } from "react";-import { useFetcher } from "react-router";+import { useMemo } from "react";import type { getOpenSalesOrderLinesForItem } from "~/modules/sales";import { useCustomers } from "~/stores";import { path } from "~/utils/path";@@ -53,13 +53,9 @@ const JobSalesOrderLine = ({const { t } = useLingui();const [customers] = useCustomers();- const fetcher =- useFetcher<Awaited<ReturnType<typeof getOpenSalesOrderLinesForItem>>>();-- // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher identity is stable- useEffect(() => {- if (jobId) fetcher.load(path.to.api.jobSalesOrderLines(jobId));- }, [jobId]);+ const fetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getOpenSalesOrderLinesForItem>>+ >(jobId ? path.to.api.jobSalesOrderLines(jobId) : null);const lines = fetcher.data?.data ?? [];diff --git a/apps/erp/app/components/Form/Location.tsx b/apps/erp/app/components/Form/Location.tsxindex a691bc0ba5..d2044cfe31 100644--- a/apps/erp/app/components/Form/Location.tsx+++ b/apps/erp/app/components/Form/Location.tsx@@ -4,10 +4,10 @@import type { CreatableComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { getLocalTimeZone } from "@internationalized/date";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import { useUser } from "~/hooks";import type { getLocationsList } from "~/modules/resources";import LocationForm from "~/modules/resources/ui/Locations/LocationForm";@@ -90,12 +90,9 @@ Location.displayName = "Location";export default Location;export const useLocations = () => {- const locationFetcher =- useFetcher<Awaited<ReturnType<typeof getLocationsList>>>();-- useMount(() => {- locationFetcher.load(path.to.api.locations);- });+ const locationFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getLocationsList>>+ >(path.to.api.locations);const options = useMemo(() =>diff --git a/apps/erp/app/components/Form/LocationEmployee.tsx b/apps/erp/app/components/Form/LocationEmployee.tsxindex 1ff9392c2e..7eb79c3a73 100644--- a/apps/erp/app/components/Form/LocationEmployee.tsx+++ b/apps/erp/app/components/Form/LocationEmployee.tsx@@ -4,9 +4,9 @@import type { ComboboxProps } from "@carbon/form";import { Combobox } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import { useLingui } from "@lingui/react/macro";-import { useEffect, useMemo } from "react";-import { useFetcher } from "react-router";+import { useMemo } from "react";import type { getLocationEmployees } from "~/modules/production";import { path } from "~/utils/path";import Avatar from "../Avatar";@@ -29,7 +29,7 @@ const LocationEmployee = ({<Comboboxoptions={options}emptyMessage={emptyMessage}- isLoading={locationEmployeeFetcher.state === "loading"}+ isLoading={locationEmployeeFetcher.isFetching}{...props}label={props?.label ?? t`Employee`}placeholder={props?.placeholder ?? t`Select Employee`}@@ -42,15 +42,9 @@ LocationEmployee.displayName = "LocationEmployee";export default LocationEmployee;export const useLocationEmployees = (locationId?: string) => {- const locationEmployeeFetcher =- useFetcher<Awaited<ReturnType<typeof getLocationEmployees>>>();-- useEffect(() => {- if (locationId) {- locationEmployeeFetcher.load(path.to.api.locationEmployees(locationId));- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [locationId]);+ const locationEmployeeFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getLocationEmployees>>+ >(locationId ? path.to.api.locationEmployees(locationId) : null);const options = useMemo(() =>diff --git a/apps/erp/app/components/Form/MaterialDimension.tsx b/apps/erp/app/components/Form/MaterialDimension.tsxindex f3f65760d8..a5771c4b7a 100644--- a/apps/erp/app/components/Form/MaterialDimension.tsx+++ b/apps/erp/app/components/Form/MaterialDimension.tsx@@ -4,10 +4,10 @@import type { ComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useLingui } from "@lingui/react/macro";-import { useEffect, useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";+import { useMemo, useRef, useState } from "react";import type {getMaterialDimensionList,MaterialDimension as MaterialDimensionType@@ -36,30 +36,14 @@ const MaterialDimensionPreview = (const MaterialDimension = (props: MaterialDimensionSelectProps) => {const { t } = useLingui();- const materialDimensionsLoader =- useFetcher<Awaited<ReturnType<typeof getMaterialDimensionList>>>();+ const materialDimensionsLoader = useLoaderQuery<+ Awaited<ReturnType<typeof getMaterialDimensionList>>+ >(props.formId ? path.to.api.materialDimensions(props.formId) : null);const newDimensionModal = useDisclosure();const [created, setCreated] = useState<string>("");const triggerRef = useRef<HTMLButtonElement>(null);- useMount(() => {- if (props.formId) {- materialDimensionsLoader.load(- path.to.api.materialDimensions(props.formId)- );- }- });-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (props.formId) {- materialDimensionsLoader.load(- path.to.api.materialDimensions(props.formId)- );- }- }, [props.formId]);-const options = useMemo(() => {return (materialDimensionsLoader.data?.data ?? []).map((c) => ({value: c.id,diff --git a/apps/erp/app/components/Form/MaterialFinish.tsx b/apps/erp/app/components/Form/MaterialFinish.tsxindex 3f24aef544..b3c91c3424 100644--- a/apps/erp/app/components/Form/MaterialFinish.tsx+++ b/apps/erp/app/components/Form/MaterialFinish.tsx@@ -4,10 +4,10 @@import type { ComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useLingui } from "@lingui/react/macro";-import { useEffect, useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";+import { useMemo, useRef, useState } from "react";import type {getMaterialFinishList,MaterialFinish as MaterialFinishType@@ -36,30 +36,14 @@ const MaterialFinishPreview = (const MaterialFinish = (props: MaterialFinishSelectProps) => {const { t } = useLingui();- const materialFinishesLoader =- useFetcher<Awaited<ReturnType<typeof getMaterialFinishList>>>();+ const materialFinishesLoader = useLoaderQuery<+ Awaited<ReturnType<typeof getMaterialFinishList>>+ >(props.substanceId ? path.to.api.materialFinishes(props.substanceId) : null);const newFinishModal = useDisclosure();const [created, setCreated] = useState<string>("");const triggerRef = useRef<HTMLButtonElement>(null);- useMount(() => {- if (props.substanceId) {- materialFinishesLoader.load(- path.to.api.materialFinishes(props.substanceId)- );- }- });-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (props.substanceId) {- materialFinishesLoader.load(- path.to.api.materialFinishes(props.substanceId)- );- }- }, [props.substanceId]);-const options = useMemo(() => {return (materialFinishesLoader.data?.data ?? []).map((c) => ({value: c.id,diff --git a/apps/erp/app/components/Form/MaterialGrade.tsx b/apps/erp/app/components/Form/MaterialGrade.tsxindex a1bbba9913..96d800105e 100644--- a/apps/erp/app/components/Form/MaterialGrade.tsx+++ b/apps/erp/app/components/Form/MaterialGrade.tsx@@ -4,10 +4,10 @@import type { ComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useLingui } from "@lingui/react/macro";-import { useEffect, useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";+import { useMemo, useRef, useState } from "react";import type {getMaterialGradeList,MaterialGrade as MaterialGradeType@@ -36,26 +36,14 @@ const MaterialGradePreview = (const MaterialGrade = (props: MaterialGradeSelectProps) => {const { t } = useLingui();- const materialGradesLoader =- useFetcher<Awaited<ReturnType<typeof getMaterialGradeList>>>();+ const materialGradesLoader = useLoaderQuery<+ Awaited<ReturnType<typeof getMaterialGradeList>>+ >(props.substanceId ? path.to.api.materialGrades(props.substanceId) : null);const newGradeModal = useDisclosure();const [created, setCreated] = useState<string>("");const triggerRef = useRef<HTMLButtonElement>(null);- useMount(() => {- if (props.substanceId) {- materialGradesLoader.load(path.to.api.materialGrades(props.substanceId));- }- });-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (props.substanceId) {- materialGradesLoader.load(path.to.api.materialGrades(props.substanceId));- }- }, [props.substanceId]);-const options = useMemo(() => {return (materialGradesLoader.data?.data ?? []).map((c) => ({value: c.id,diff --git a/apps/erp/app/components/Form/MaterialType.tsx b/apps/erp/app/components/Form/MaterialType.tsxindex 62b639b517..c5b4a768db 100644--- a/apps/erp/app/components/Form/MaterialType.tsx+++ b/apps/erp/app/components/Form/MaterialType.tsx@@ -4,10 +4,10 @@import type { ComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useLingui } from "@lingui/react/macro";-import { useEffect, useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";+import { useMemo, useRef, useState } from "react";import type { getMaterialTypeList } from "~/modules/items";import MaterialTypeForm from "~/modules/items/ui/MaterialTypes/MaterialTypeForm";import { path } from "~/utils/path";@@ -104,21 +104,13 @@ const MaterialType = (props: MaterialTypeSelectProps) => {};export const useMaterialTypes = (substanceId?: string, formId?: string) => {- const materialTypes =- useFetcher<Awaited<ReturnType<typeof getMaterialTypeList>>>();-- useMount(() => {- if (substanceId && formId) {- materialTypes.load(path.to.api.materialTypes(substanceId, formId));- }- });-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (substanceId && formId) {- materialTypes.load(path.to.api.materialTypes(substanceId, formId));- }- }, [substanceId, formId]);+ const materialTypes = useLoaderQuery<+ Awaited<ReturnType<typeof getMaterialTypeList>>+ >(+ substanceId && formId+ ? path.to.api.materialTypes(substanceId, formId)+ : null+ );const options = useMemo(() => {return (materialTypes.data?.data ?? []).map((c) => ({diff --git a/apps/erp/app/components/Form/PaymentTerm.tsx b/apps/erp/app/components/Form/PaymentTerm.tsxindex 13d0428e16..7d18a0561a 100644--- a/apps/erp/app/components/Form/PaymentTerm.tsx+++ b/apps/erp/app/components/Form/PaymentTerm.tsx@@ -4,9 +4,9 @@import type { ComboboxProps } from "@carbon/form";import { Combobox, CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import { usePermissions } from "~/hooks";import type { getPaymentTermsList } from "~/modules/accounting";import PaymentTermForm from "~/modules/accounting/ui/PaymentTerms/PaymentTermForm";@@ -86,12 +86,9 @@ PaymentTerm.displayName = "PaymentTerm";export default PaymentTerm;export const usePaymentTerm = () => {- const paymentTermFetcher =- useFetcher<Awaited<ReturnType<typeof getPaymentTermsList>>>();-- useMount(() => {- paymentTermFetcher.load(path.to.api.paymentTerms);- });+ const paymentTermFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getPaymentTermsList>>+ >(path.to.api.paymentTerms);const options = useMemo(() => {return (paymentTermFetcher.data?.data ?? []).map((c) => ({diff --git a/apps/erp/app/components/Form/Procedure.tsx b/apps/erp/app/components/Form/Procedure.tsxindex 755ecdf7db..727f240c10 100644--- a/apps/erp/app/components/Form/Procedure.tsx+++ b/apps/erp/app/components/Form/Procedure.tsx@@ -4,9 +4,9 @@import type { ComboboxProps } from "@carbon/form";import { Combobox } from "@carbon/form";-import { HStack, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { HStack } from "@carbon/react";import { useMemo } from "react";-import { useFetcher } from "react-router";import type { getProceduresList } from "~/modules/production/production.service";import ProcedureStatus from "~/modules/production/ui/Procedures/ProcedureStatus";import { path } from "~/utils/path";@@ -45,14 +45,11 @@ export default Procedure;export const useProcedures = (args: { processId?: string }) => {const { processId } = args;- const procedureFetcher =- useFetcher<Awaited<ReturnType<typeof getProceduresList>>>();+ const procedureFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getProceduresList>>+ >(path.to.api.procedures);- useMount(() => {- procedureFetcher.load(path.to.api.procedures);- });-- const loading = procedureFetcher.state !== "idle";+ const loading = procedureFetcher.isFetching;const options = useMemo(() =>diff --git a/apps/erp/app/components/Form/Process.tsx b/apps/erp/app/components/Form/Process.tsxindex 8edd1ab914..dedfcb6b18 100644--- a/apps/erp/app/components/Form/Process.tsx+++ b/apps/erp/app/components/Form/Process.tsx@@ -4,9 +4,9 @@import type { ComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import {batchRuleInitialValues,type getProcessesList@@ -99,11 +99,9 @@ Process.displayName = "Process";export default Process;export const useProcesses = () => {- const fetcher = useFetcher<Awaited<ReturnType<typeof getProcessesList>>>();-- useMount(() => {- fetcher.load(path.to.api.processes);- });+ const fetcher = useLoaderQuery<Awaited<ReturnType<typeof getProcessesList>>>(+ path.to.api.processes+ );const options = useMemo(() =>diff --git a/apps/erp/app/components/Form/Processes.tsx b/apps/erp/app/components/Form/Processes.tsxindex 025ad2773e..da3b8bad4e 100644--- a/apps/erp/app/components/Form/Processes.tsx+++ b/apps/erp/app/components/Form/Processes.tsx@@ -4,9 +4,9 @@import type { CreatableMultiSelectProps } from "@carbon/form";import { CreatableMultiSelect } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import {batchRuleInitialValues,type getProcessesList@@ -71,11 +71,9 @@ Processes.displayName = "Process";export default Processes;export const useProcesses = () => {- const fetcher = useFetcher<Awaited<ReturnType<typeof getProcessesList>>>();-- useMount(() => {- fetcher.load(path.to.api.processes);- });+ const fetcher = useLoaderQuery<Awaited<ReturnType<typeof getProcessesList>>>(+ path.to.api.processes+ );const options = useMemo(() =>diff --git a/apps/erp/app/components/Form/ScrapReason.tsx b/apps/erp/app/components/Form/ScrapReason.tsxindex afba265b41..bc5a47b81c 100644--- a/apps/erp/app/components/Form/ScrapReason.tsx+++ b/apps/erp/app/components/Form/ScrapReason.tsx@@ -4,9 +4,8 @@import type { ComboboxProps } from "@carbon/form";import { Combobox } from "@carbon/form";-import { useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";import { useMemo } from "react";-import { useFetcher } from "react-router";import { useRouteData } from "~/hooks";import type {getScrapReasonsList,@@ -33,18 +32,15 @@ ScrapReason.displayName = "ScrapReason";export default ScrapReason;export const useScrapReasons = () => {- const scrapReasonFetcher =- useFetcher<Awaited<ReturnType<typeof getScrapReasonsList>>>();-const sharedProductionData = useRouteData<{scrapReasons: ScrapReasonType[];}>(path.to.production);const hasScrapReasonData = sharedProductionData?.scrapReasons;- useMount(() => {- if (!hasScrapReasonData) scrapReasonFetcher.load(path.to.api.scrapReasons);- });+ const scrapReasonFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getScrapReasonsList>>+ >(!hasScrapReasonData ? path.to.api.scrapReasons : null);const options = useMemo(() => {const dataSource =diff --git a/apps/erp/app/components/Form/Sequence.tsx b/apps/erp/app/components/Form/Sequence.tsxindex b5f60cb9a7..f61b85c68f 100644--- a/apps/erp/app/components/Form/Sequence.tsx+++ b/apps/erp/app/components/Form/Sequence.tsx@@ -4,9 +4,8 @@import type { SelectProps } from "@carbon/form";import { Select } from "@carbon/form";-import { useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";import { useMemo } from "react";-import { useFetcher } from "react-router";import type { getSequencesList } from "~/modules/settings";import { path } from "~/utils/path";@@ -15,12 +14,9 @@ type SequenceSelectProps = Omit<SelectProps, "options"> & {};const Sequence = (props: SequenceSelectProps) => {- const sequenceFetcher =- useFetcher<Awaited<ReturnType<typeof getSequencesList>>>();-- useMount(() => {- sequenceFetcher.load(path.to.api.sequences(props.table));- });+ const sequenceFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getSequencesList>>+ >(path.to.api.sequences(props.table));const options = useMemo(() =>diff --git a/apps/erp/app/components/Form/Shape.tsx b/apps/erp/app/components/Form/Shape.tsxindex ec38e952a5..53379fcabe 100644--- a/apps/erp/app/components/Form/Shape.tsx+++ b/apps/erp/app/components/Form/Shape.tsx@@ -4,9 +4,9 @@import type { ComboboxProps } from "@carbon/form";import { Combobox, CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import { usePermissions } from "~/hooks";import type { getMaterialFormsList } from "~/modules/items";import { MaterialShapeForm } from "~/modules/items/ui/MaterialShapes";@@ -83,12 +83,9 @@ Shape.displayName = "Shape";export default Shape;export const useShape = () => {- const materialFormsLoader =- useFetcher<Awaited<ReturnType<typeof getMaterialFormsList>>>();-- useMount(() => {- materialFormsLoader.load(path.to.api.materialForms);- });+ const materialFormsLoader = useLoaderQuery<+ Awaited<ReturnType<typeof getMaterialFormsList>>+ >(path.to.api.materialForms);const options = useMemo(() => {return (materialFormsLoader.data?.data ?? []).map((c) => ({diff --git a/apps/erp/app/components/Form/ShelfLifeStartEvent.tsx b/apps/erp/app/components/Form/ShelfLifeStartEvent.tsxindex 399a13ec58..37381ea18c 100644--- a/apps/erp/app/components/Form/ShelfLifeStartEvent.tsx+++ b/apps/erp/app/components/Form/ShelfLifeStartEvent.tsx@@ -4,18 +4,17 @@import type { TermId } from "@carbon/content/glossary";import { useControlField } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import {ChoiceCardGroup,FormControl,FormHelperText,FormLabel,- LabelWithHelp,- useMount+ LabelWithHelp} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import { useMemo } from "react";import { LuCalendarArrowDown, LuCalendarArrowUp } from "react-icons/lu";-import { useFetcher } from "react-router";import { path } from "~/utils/path";import Process, { useProcesses } from "./Process";@@ -130,15 +129,11 @@ export const ShelfLifeStartTiming = ({// Returns the processIds referenced by the item's active recipe, or// `undefined` while loading. Empty array = item has no recipe operations.function useItemRecipeProcessIds(itemId: string | undefined) {- const fetcher = useFetcher<{ data: string[]; error: unknown }>();-- useMount(() => {- if (itemId) {- fetcher.load(path.to.api.itemRecipeProcesses(itemId));- }- });+ const fetcher = useLoaderQuery<{ data: string[]; error: unknown }>(+ itemId ? path.to.api.itemRecipeProcesses(itemId) : null+ );if (!itemId) return [] as string[];- if (fetcher.state !== "idle" || !fetcher.data) return undefined;+ if (fetcher.isFetching || !fetcher.data) return undefined;return fetcher.data.data ?? [];}diff --git a/apps/erp/app/components/Form/Shift.tsx b/apps/erp/app/components/Form/Shift.tsxindex 7e8d44f658..3b615947d4 100644--- a/apps/erp/app/components/Form/Shift.tsx+++ b/apps/erp/app/components/Form/Shift.tsx@@ -4,8 +4,8 @@import type { SelectProps } from "@carbon/form";import { Select } from "@carbon/form";-import { useEffect, useMemo } from "react";-import { useFetcher } from "react-router";+import { useLoaderQuery } from "@carbon/query";+import { useMemo } from "react";import type { getShiftsList } from "~/modules/people";import { path } from "~/utils/path";import { useEmptyState } from "./emptyStates";@@ -34,14 +34,9 @@ const Shift = (props: ShiftSelectProps) => {export default Shift;export const useShifts = (props?: { location?: string }) => {- const shiftFetcher = useFetcher<Awaited<ReturnType<typeof getShiftsList>>>();-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (props?.location) {- shiftFetcher.load(path.to.api.shifts(props.location));- }- }, [props?.location]);+ const shiftFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getShiftsList>>+ >(props?.location ? path.to.api.shifts(props.location) : null);const options = useMemo(() =>diff --git a/apps/erp/app/components/Form/ShippingMethod.tsx b/apps/erp/app/components/Form/ShippingMethod.tsxindex be5e4d3783..411ff0edbc 100644--- a/apps/erp/app/components/Form/ShippingMethod.tsx+++ b/apps/erp/app/components/Form/ShippingMethod.tsx@@ -4,9 +4,9 @@import type { ComboboxProps } from "@carbon/form";import { Combobox, CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import { usePermissions } from "~/hooks";import type { getShippingMethodsList } from "~/modules/inventory";import { ShippingMethodForm } from "~/modules/inventory";@@ -70,12 +70,9 @@ ShippingMethod.displayName = "ShippingMethod";export default ShippingMethod;export const useShippingMethod = () => {- const shippingMethodFetcher =- useFetcher<Awaited<ReturnType<typeof getShippingMethodsList>>>();-- useMount(() => {- shippingMethodFetcher.load(path.to.api.shippingMethods);- });+ const shippingMethodFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getShippingMethodsList>>+ >(path.to.api.shippingMethods);const options = useMemo(() => {return (shippingMethodFetcher.data?.data ?? []).map((c) => ({diff --git a/apps/erp/app/components/Form/StorageTypes.tsx b/apps/erp/app/components/Form/StorageTypes.tsxindex ddbabfdedf..9dcc1f63ae 100644--- a/apps/erp/app/components/Form/StorageTypes.tsx+++ b/apps/erp/app/components/Form/StorageTypes.tsx@@ -4,9 +4,9 @@import type { CreatableMultiSelectProps } from "@carbon/form";import { CreatableMultiSelect } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";-import { useEffect, useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";+import { useMemo, useRef, useState } from "react";import type { getStorageTypesList } from "~/modules/inventory";import StorageTypeForm from "~/modules/inventory/ui/StorageTypes/StorageTypeForm";import { path } from "~/utils/path";@@ -54,17 +54,9 @@ const StorageTypes = (props: StorageTypesSelectProps) => {};export const useStorageTypes = () => {- const storageTypes =- useFetcher<Awaited<ReturnType<typeof getStorageTypesList>>>();-- useMount(() => {- storageTypes.load(path.to.api.storageTypes);- });-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- storageTypes.load(path.to.api.storageTypes);- }, []);+ const storageTypes = useLoaderQuery<+ Awaited<ReturnType<typeof getStorageTypesList>>+ >(path.to.api.storageTypes);const options = useMemo(() => {return (storageTypes.data?.data ?? []).map((c) => ({diff --git a/apps/erp/app/components/Form/StorageUnit.tsx b/apps/erp/app/components/Form/StorageUnit.tsxindex efd9d16519..afdef5b9ef 100644--- a/apps/erp/app/components/Form/StorageUnit.tsx+++ b/apps/erp/app/components/Form/StorageUnit.tsx@@ -16,13 +16,13 @@import type { TermId } from "@carbon/content/glossary";import { CreatableCombobox } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import {CreatableCombobox as CreatableComboboxBase,useDisclosure} from "@carbon/react";import type { MouseEventHandler } from "react";-import { useEffect, useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";+import { useMemo, useRef, useState } from "react";import type { getStorageUnitsList } from "~/modules/inventory";import StorageUnitForm from "~/modules/inventory/ui/StorageUnits/StorageUnitForm";import type { ListItem } from "~/types";@@ -47,15 +47,10 @@ export type StorageUnitTreeRow = {* parent picker and storage-rule value inputs.*/export function useStorageUnitsTree(locationId?: string | null) {- const fetcher = useFetcher<{+ const fetcher = useLoaderQuery<{data: StorageUnitTreeRow[] | null;error: unknown;- }>();-- // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher identity changes every render- useEffect(() => {- if (locationId) fetcher.load(path.to.api.storageUnitsTree(locationId));- }, [locationId]);+ }>(locationId ? path.to.api.storageUnitsTree(locationId) : null);return fetcher.data?.data ?? [];}@@ -65,22 +60,17 @@ export function useStorageUnitsTree(locationId?: string | null) {* helpers. Kept for non-leaf-aware callsites that pull their own options.*/export function useStorageUnits(locationId?: string, itemId?: string) {- const storageUnitsFetcher =- useFetcher<Awaited<ReturnType<typeof getStorageUnitsList>>>();- const storageUnitsWithQuantitiesFetcher =- useFetcher<Awaited<ReturnType<typeof getStorageUnitsList>>>();-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (locationId) {- if (itemId) {- storageUnitsWithQuantitiesFetcher.load(- path.to.api.storageUnitsWithQuantities(locationId, itemId)- );- }- storageUnitsFetcher.load(path.to.api.storageUnits(locationId));- }- }, [locationId, itemId]);+ const storageUnitsFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getStorageUnitsList>>+ >(locationId ? path.to.api.storageUnits(locationId) : null);+ const storageUnitsWithQuantitiesFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getStorageUnitsList>>+ >(+ locationId && itemId+ ? path.to.api.storageUnitsWithQuantities(locationId, itemId)+ : null,+ { staleTime: 0 }+ );const options = useMemo(() => {if (itemId && storageUnitsWithQuantitiesFetcher.data?.data) {@@ -134,14 +124,12 @@ type StorageUnitOption = { value: string; label: string; helper?: string };* fetches when both ids are present, so item-less pickers don't pay for it.*/function useStorageUnitQuantities(locationId?: string | null, itemId?: string) {- const fetcher = useFetcher<{ data: { id: string; quantity: number }[] }>();-- // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher identity changes every render- useEffect(() => {- if (locationId && itemId) {- fetcher.load(path.to.api.storageUnitsWithQuantities(locationId, itemId));- }- }, [locationId, itemId]);+ const fetcher = useLoaderQuery<{ data: { id: string; quantity: number }[] }>(+ locationId && itemId+ ? path.to.api.storageUnitsWithQuantities(locationId, itemId)+ : null,+ { staleTime: 0 }+ );return useMemo(() => {const m = new Map<string, number>();diff --git a/apps/erp/app/components/Form/Substance.tsx b/apps/erp/app/components/Form/Substance.tsxindex a5e6af0d68..fd3849401f 100644--- a/apps/erp/app/components/Form/Substance.tsx+++ b/apps/erp/app/components/Form/Substance.tsx@@ -4,9 +4,9 @@import type { ComboboxProps } from "@carbon/form";import { Combobox, CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import { usePermissions } from "~/hooks";import type { getMaterialSubstancesList } from "~/modules/items";import { MaterialSubstanceForm } from "~/modules/items/ui/MaterialSubstances";@@ -83,12 +83,9 @@ Substance.displayName = "Substance";export default Substance;export const useSubstance = () => {- const materialSubstances =- useFetcher<Awaited<ReturnType<typeof getMaterialSubstancesList>>>();-- useMount(() => {- materialSubstances.load(path.to.api.materialSubstances);- });+ const materialSubstances = useLoaderQuery<+ Awaited<ReturnType<typeof getMaterialSubstancesList>>+ >(path.to.api.materialSubstances);const options = useMemo(() => {return (materialSubstances.data?.data ?? []).map((c) => ({diff --git a/apps/erp/app/components/Form/SupplierContact.tsx b/apps/erp/app/components/Form/SupplierContact.tsxindex a901fdbe18..d9cd5941e9 100644--- a/apps/erp/app/components/Form/SupplierContact.tsx+++ b/apps/erp/app/components/Form/SupplierContact.tsx@@ -4,10 +4,10 @@import type { CreatableComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import { Avatar, HStack, useDisclosure } from "@carbon/react";import { useLingui } from "@lingui/react/macro";-import { useEffect, useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";+import { useMemo, useRef, useState } from "react";import type {getSupplierContacts,SupplierContact as SupplierContactType@@ -51,8 +51,9 @@ const SupplierContact = ({...props}: SupplierContactSelectProps) => {const { t } = useLingui();- const supplierContactsFetcher =- useFetcher<Awaited<ReturnType<typeof getSupplierContacts>>>();+ const supplierContactsFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getSupplierContacts>>+ >(supplier ? path.to.api.supplierContacts(supplier) : null);const newContactModal = useDisclosure();const [created, setCreated] = useState<string>("");@@ -64,13 +65,6 @@ const SupplierContact = ({const initialFirstName = nameTokens[0] || "";const initialLastName = nameTokens.slice(1).join(" ");- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (supplier) {- supplierContactsFetcher.load(path.to.api.supplierContacts(supplier));- }- }, [supplier]);-const options = useMemo(() =>supplierContactsFetcher.data?.data?.map((c) => ({@@ -120,12 +114,6 @@ const SupplierContact = ({onClose={() => {setCreated("");newContactModal.onClose();- // Reload the per-supplier fetcher so a just-created contact appears.- if (supplier) {- supplierContactsFetcher.load(- path.to.api.supplierContacts(supplier)- );- }triggerRef.current?.click();}}initialValues={{diff --git a/apps/erp/app/components/Form/SupplierLocation.tsx b/apps/erp/app/components/Form/SupplierLocation.tsxindex a9577c67f7..280fa5d1ca 100644--- a/apps/erp/app/components/Form/SupplierLocation.tsx+++ b/apps/erp/app/components/Form/SupplierLocation.tsx@@ -4,10 +4,10 @@import type { CreatableComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import { useDisclosure } from "@carbon/react";import { formatAddress } from "@carbon/utils";-import { useEffect, useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";+import { useMemo, useRef, useState } from "react";import type {getSupplierLocations,SupplierLocation as SupplierLocationType@@ -44,19 +44,13 @@ const SupplierLocation = ({const newLocationModal = useDisclosure();const [created, setCreated] = useState<string>("");const triggerRef = useRef<HTMLButtonElement>(null);- const supplierLocationsFetcher =- useFetcher<Awaited<ReturnType<typeof getSupplierLocations>>>();+ const supplierLocationsFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getSupplierLocations>>+ >(supplier ? path.to.api.supplierLocations(supplier) : null);const [suppliers] = useSuppliers();const supplierName =suppliers.find((s) => s.id === supplier)?.name ?? "Main Location";- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (supplier) {- supplierLocationsFetcher.load(path.to.api.supplierLocations(supplier));- }- }, [supplier]);-const options = useMemo(() =>supplierLocationsFetcher.data?.data?.map((c) => ({@@ -110,12 +104,6 @@ const SupplierLocation = ({onClose={() => {setCreated("");newLocationModal.onClose();- // Reload the per-supplier fetcher so a just-created location appears.- if (supplier) {- supplierLocationsFetcher.load(- path.to.api.supplierLocations(supplier)- );- }triggerRef.current?.click();}}initialValues={{diff --git a/apps/erp/app/components/Form/SupplierProcess.tsx b/apps/erp/app/components/Form/SupplierProcess.tsxindex a6f511caa8..27019eaaea 100644--- a/apps/erp/app/components/Form/SupplierProcess.tsx+++ b/apps/erp/app/components/Form/SupplierProcess.tsx@@ -4,10 +4,10 @@import type { ComboboxProps } from "@carbon/form";import { CreatableCombobox, FieldEmptyState } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import { useDisclosure } from "@carbon/react";import { useLingui } from "@lingui/react/macro";-import { useEffect, useMemo, useRef } from "react";-import { useFetcher } from "react-router";+import { useMemo, useRef } from "react";import type { getSupplierProcessesByProcess } from "~/modules/purchasing";import { SupplierProcessForm } from "~/modules/purchasing/ui/Supplier";import { useSuppliers } from "~/stores";@@ -88,17 +88,12 @@ export default SupplierProcess;export const useSupplierProcesses = (args: { processId?: string }) => {const { processId } = args;- const fetcher =- useFetcher<Awaited<ReturnType<typeof getSupplierProcessesByProcess>>>();+ const fetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getSupplierProcessesByProcess>>+ >(processId ? path.to.api.supplierProcesses(processId) : null);// An empty processId would build a URL with an empty segment that matches no// route — the resulting 404 bubbles to the root error boundary.- useEffect(() => {- if (processId) {- fetcher.load(path.to.api.supplierProcesses(processId));- }- }, [processId]);-const supplierProcesses = useMemo(() => (fetcher.data?.data ? fetcher.data?.data : []),[fetcher.data]diff --git a/apps/erp/app/components/Form/SupplierType.tsx b/apps/erp/app/components/Form/SupplierType.tsxindex 50c1d75705..2eae8dc405 100644--- a/apps/erp/app/components/Form/SupplierType.tsx+++ b/apps/erp/app/components/Form/SupplierType.tsx@@ -4,9 +4,9 @@import type { ComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import { Enumerable } from "~/components/Enumerable";import type { getSupplierTypesList } from "~/modules/purchasing";import SupplierTypeForm from "~/modules/purchasing/ui/SupplierTypes/SupplierTypeForm";@@ -67,12 +67,9 @@ SupplierType.displayName = "SupplierType";export default SupplierType;export const useSupplierTypes = () => {- const supplierTypeFetcher =- useFetcher<Awaited<ReturnType<typeof getSupplierTypesList>>>();-- useMount(() => {- supplierTypeFetcher.load(path.to.api.supplierTypes);- });+ const supplierTypeFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getSupplierTypesList>>+ >(path.to.api.supplierTypes);const options = useMemo(() => {const dataSource = supplierTypeFetcher.data?.data ?? [];diff --git a/apps/erp/app/components/Form/Timezone.tsx b/apps/erp/app/components/Form/Timezone.tsxindex 87947fa1e6..741d7150cf 100644--- a/apps/erp/app/components/Form/Timezone.tsx+++ b/apps/erp/app/components/Form/Timezone.tsx@@ -3,11 +3,10 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { Timezone as TimezoneBase } from "@carbon/form";-import { useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";import type { TimezoneGroup } from "@carbon/utils";import type { ComponentProps } from "react";import { useMemo } from "react";-import { useFetcher } from "react-router";import type { getTimezoneNames } from "~/modules/shared/shared.service";import { path } from "~/utils/path";@@ -18,11 +17,9 @@ import { path } from "~/utils/path";* runtime's Intl list.*/const Timezone = (props: ComponentProps<typeof TimezoneBase>) => {- const fetcher = useFetcher<Awaited<ReturnType<typeof getTimezoneNames>>>();-- useMount(() => {- fetcher.load(path.to.api.timezones);- });+ const fetcher = useLoaderQuery<Awaited<ReturnType<typeof getTimezoneNames>>>(+ path.to.api.timezones+ );const options = useMemo<TimezoneGroup[] | undefined>(() => {const zones = fetcher.data?.data;diff --git a/apps/erp/app/components/Form/UnitOfMeasure.tsx b/apps/erp/app/components/Form/UnitOfMeasure.tsxindex c1cd8fb4c7..c6febc9c0c 100644--- a/apps/erp/app/components/Form/UnitOfMeasure.tsx+++ b/apps/erp/app/components/Form/UnitOfMeasure.tsx@@ -4,9 +4,9 @@import type { ComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import { useRouteData } from "~/hooks";import type {getUnitOfMeasuresList,@@ -80,18 +80,15 @@ UnitOfMeasure.displayName = "UnitOfMeasure";export default UnitOfMeasure;export const useUnitOfMeasure = () => {- const uomFetcher =- useFetcher<Awaited<ReturnType<typeof getUnitOfMeasuresList>>>();-const sharedPartData = useRouteData<{unitOfMeasures: UnitOfMeasureListItem[];}>(path.to.partRoot);const hasSharedPartData = sharedPartData?.unitOfMeasures?.length;- useMount(() => {- if (!hasSharedPartData) uomFetcher.load(path.to.api.unitOfMeasures);- });+ const uomFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getUnitOfMeasuresList>>+ >(!hasSharedPartData ? path.to.api.unitOfMeasures : null);const options = useMemo(() => {const dataSource =diff --git a/apps/erp/app/components/Form/WorkCenter.tsx b/apps/erp/app/components/Form/WorkCenter.tsxindex ee3b9ec531..301fd711ca 100644--- a/apps/erp/app/components/Form/WorkCenter.tsx+++ b/apps/erp/app/components/Form/WorkCenter.tsx@@ -4,9 +4,9 @@import type { ComboboxProps } from "@carbon/form";import { CreatableCombobox } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import { Enumerable } from "~/components/Enumerable";import { useUser } from "~/hooks";import type { getWorkCentersList } from "~/modules/resources";@@ -53,7 +53,7 @@ const WorkCenter = (props: WorkCenterSelectProps) => {props?.autoSelectSingleOption &&Boolean(props?.processId) &&options.length === 1 &&- workCenterFetcher.state === "idle"+ !workCenterFetcher.isFetching}ref={triggerRef}options={options.map((o) => ({@@ -106,12 +106,9 @@ export const useWorkCenters = (args: {locationId?: string;}) => {const { processId, locationId } = args;- const workCenterFetcher =- useFetcher<Awaited<ReturnType<typeof getWorkCentersList>>>();-- useMount(() => {- workCenterFetcher.load(path.to.api.workCenters);- });+ const workCenterFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getWorkCentersList>>+ >(path.to.api.workCenters);const options = useMemo(() =>diff --git a/apps/erp/app/components/Form/WorkCenters.tsx b/apps/erp/app/components/Form/WorkCenters.tsxindex 902086d1db..4e2074800b 100644--- a/apps/erp/app/components/Form/WorkCenters.tsx+++ b/apps/erp/app/components/Form/WorkCenters.tsx@@ -4,9 +4,9 @@import type { CreatableMultiSelectProps } from "@carbon/form";import { CreatableMultiSelect } from "@carbon/form";-import { useDisclosure, useMount } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { useDisclosure } from "@carbon/react";import { useMemo, useRef, useState } from "react";-import { useFetcher } from "react-router";import { useUser } from "~/hooks";import type { getWorkCentersList } from "~/modules/resources";import WorkCenterForm from "~/modules/resources/ui/WorkCenters/WorkCenterForm";@@ -76,12 +76,9 @@ WorkCenters.displayName = "WorkCenter";export default WorkCenters;export const useWorkCenters = () => {- const workCenterFetcher =- useFetcher<Awaited<ReturnType<typeof getWorkCentersList>>>();-- useMount(() => {- workCenterFetcher.load(path.to.api.workCenters);- });+ const workCenterFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getWorkCentersList>>+ >(path.to.api.workCenters);const options = useMemo(() =>diff --git a/apps/erp/app/components/ImportCSVModal/FieldMappings.tsx b/apps/erp/app/components/ImportCSVModal/FieldMappings.tsxindex 2066752ae4..d4991c87ed 100644--- a/apps/erp/app/components/ImportCSVModal/FieldMappings.tsx+++ b/apps/erp/app/components/ImportCSVModal/FieldMappings.tsx@@ -7,6 +7,7 @@import { useCarbon } from "@carbon/auth";import type { Database } from "@carbon/database";import { Combobox, CreatableCombobox, useFormContext } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,ModalBody,@@ -31,7 +32,6 @@ import {useState} from "react";import { LuInfo, LuListPlus, LuMoveRight, LuPlus } from "react-icons/lu";-import { useFetcher } from "react-router";import { Submit } from "~/components/Form";import {useCompanySettings,@@ -93,7 +93,26 @@ export function FieldMapping({const initialized = useRef(false);const { validate } = useFormContext(formId);const { fileColumns, filePath, firstRows } = useCsvContext();- const fetcher = useFetcher<typeof action>();+ const fetcher = useAction<typeof action>({+ onSettled: (data) => {+ if (data && Object.keys(data).length > 0 && !initialized.current) {+ initialized.current = true;+ setColumnMappings((prevMappings) => {+ if (!data || !fileColumns) return prevMappings;++ return Object.entries(data).reduce(+ (acc, [key, value]) => {+ if (fileColumns.includes(value)) {+ acc[key] = value;+ }+ return acc;+ },+ {} as Record<string, string>+ );+ });+ }+ }+ });const mappableFields = fieldMappings[table];const [currentStep, setCurrentStep] = useState(0);const [columnMappings, setColumnMappings] = useState<Record<string, string>>(@@ -155,30 +174,6 @@ export function FieldMapping({);}, [fileColumns, firstRows]);- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (- fetcher.data &&- Object.keys(fetcher.data).length > 0 &&- !initialized.current- ) {- initialized.current = true;- setColumnMappings((prevMappings) => {- if (!fetcher.data || !fileColumns) return prevMappings;-- return Object.entries(fetcher.data).reduce(- (acc, [key, value]) => {- if (fileColumns.includes(value)) {- acc[key] = value;- }- return acc;- },- {} as Record<string, string>- );- });- }- }, [fetcher.data]);-const enumFields: [string,{diff --git a/apps/erp/app/components/Layout/Topbar/Notifications.tsx b/apps/erp/app/components/Layout/Topbar/Notifications.tsxindex 0eedb37f11..4ef2c05ab2 100644--- a/apps/erp/app/components/Layout/Topbar/Notifications.tsx+++ b/apps/erp/app/components/Layout/Topbar/Notifications.tsx@@ -5,6 +5,7 @@"use client";import type { ApprovalDocumentType } from "@carbon/ee/approvals";import { NotificationEvent, renderInlineLinks } from "@carbon/notifications";+import { useLoaderQuery } from "@carbon/query";import {Badge,Button,@@ -51,7 +52,7 @@ import {RiProgress4Line,RiProgress8Line} from "react-icons/ri";-import { Link, useFetcher, useNavigate } from "react-router";+import { Link, useNavigate } from "react-router";import { DateTime } from "~/components";import { useNotifications, useUser } from "~/hooks";import { usePeople } from "~/stores";@@ -649,8 +650,13 @@ const Notifications = () => {} = useUser();const [isOpen, setOpen] = useState(false);const [activeTab, setActiveTab] = useState("inbox");- const [trainingsLoaded, setTrainingsLoaded] = useState(false);- const trainingsFetcher = useFetcher<{ data: OutstandingTraining[] }>();+ // Loaded when the tab is opened, and again each time the popover reopens.+ const trainingsFetcher = useLoaderQuery<{ data: OutstandingTraining[] }>(+ isOpen && activeTab === "trainings"+ ? path.to.api.outstandingTrainings+ : null,+ { staleTime: 0 }+ );const {fetchDigestChildren,@@ -672,21 +678,6 @@ const Notifications = () => {(notification) => notification.read);- // Lazy load trainings when the tab is selected- useEffect(() => {- if (activeTab === "trainings" && !trainingsLoaded && isOpen) {- trainingsFetcher.load(path.to.api.outstandingTrainings);- setTrainingsLoaded(true);- }- }, [activeTab, trainingsLoaded, isOpen, trainingsFetcher]);-- // Reset trainings loaded state when popover closes- useEffect(() => {- if (!isOpen) {- setTrainingsLoaded(false);- }- }, [isOpen]);-// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {if (isOpen && hasUnseenNotifications) {@@ -695,7 +686,7 @@ const Notifications = () => {}, [hasUnseenNotifications, isOpen]);const outstandingTrainings = trainingsFetcher.data?.data ?? [];- const isLoadingTrainings = trainingsFetcher.state === "loading";+ const isLoadingTrainings = trainingsFetcher.isFetching;return (<Popover onOpenChange={setOpen} open={isOpen}>diff --git a/apps/erp/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx b/apps/erp/app/components/Modals/ConfirmDelete/ConfirmDelete.tsxindex ba08c6d9bf..8f4d1ea326 100644--- a/apps/erp/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx+++ b/apps/erp/app/components/Modals/ConfirmDelete/ConfirmDelete.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {Button,Modal,@@ -14,8 +15,7 @@ import {SHORTCUTS} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useEffect, useRef } from "react";-import { useFetcher } from "react-router";+import { useRef } from "react";type ConfirmDeleteProps = {action?: string;@@ -50,14 +50,15 @@ const ConfirmDelete = ({onSubmit}: ConfirmDeleteProps) => {const { t } = useLingui();- const fetcher = useFetcher<{}>();- const submitted = useRef(false);- useEffect(() => {- if (fetcher.state === "idle" && submitted.current) {- onSubmit?.();- submitted.current = false;+ const fetcher = useAction<{}>({+ onSettled: () => {+ if (submitted.current) {+ onSubmit?.();+ submitted.current = false;+ }}- }, [fetcher.state, onSubmit]);+ });+ const submitted = useRef(false);return (<Modalopen={isOpen}diff --git a/apps/erp/app/components/RealtimeDataProvider.tsx b/apps/erp/app/components/RealtimeDataProvider.tsxindex 50da81fd66..350c719d78 100644--- a/apps/erp/app/components/RealtimeDataProvider.tsx+++ b/apps/erp/app/components/RealtimeDataProvider.tsx@@ -4,466 +4,58 @@"use client";-import { useCarbon } from "@carbon/auth";-import { type Database, fetchAllFromTable } from "@carbon/database";-import { getLogger } from "@carbon/logger";-import { useRealtimeChannel } from "@carbon/react";-import { useEffect } from "react";-import { useUser } from "~/hooks";import {- upsertIntoListStore,- useCustomers,- useItems,- usePeople,- useSuppliers-} from "~/stores";-import type { Item } from "~/stores/items";-import type { ListItem } from "~/types";-import { ITEM_QUANTITIES_QUERY_KEY } from "~/utils/react-query";--const logger = getLogger("erp", "realtime-data-provider");--// IndexedDB entries are keyed per company (`customers:<companyId>`) — a global-// key let one company's cached list hydrate the pickers after switching to-// another company, which produced cross-tenant refs (e.g. a salesOrder pointing-// at another company's customer). `activeCompanyId` also guards the async idb /-// fetch callbacks racing a mid-flight company switch.-let activeCompanyId: string | null = null;-let hydratedFromServer = false;--const LEGACY_IDB_KEYS = ["customers", "items", "suppliers", "people"];+ getClientCache,+ LiveLists,+ LOADER,+ useTableChanges+} from "@carbon/query";+import { useUser } from "~/hooks";+import { customersList } from "~/stores/customers";+import { itemsList } from "~/stores/items";+import { peopleList } from "~/stores/people";+import { suppliersList } from "~/stores/suppliers";+import { path } from "~/utils/path";++// Module-level so their identity is stable across renders.+const LISTS = [itemsList, suppliersList, customersList, peopleList];+// Every location's on-hand entry shares this URL prefix.+const ITEM_QUANTITIES_PATH = path.to.api.itemQuantities("");+const storage = async () => (await import("localforage")).default;const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {- const { carbon, accessToken } = useCarbon();const {+ id: userId,company: { id: companyId }} = useUser();- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- hydratedFromServer = false;- }, [companyId]);-- // Reset on logout so the next login triggers a fresh server hydrate.- useEffect(() => {- if (!accessToken) hydratedFromServer = false;- }, [accessToken]);-- const [, setItems] = useItems();- const [, setSuppliers] = useSuppliers();- const [, setCustomers] = useCustomers();- const [, setPeople] = usePeople();-- const hydrate = async () => {- const idb = (await import("localforage")).default;- const requestedCompanyId = companyId;- if (activeCompanyId !== requestedCompanyId) {- activeCompanyId = requestedCompanyId;-- // pre-keying entries were global; purge so they can never hydrate again- for (const key of LEGACY_IDB_KEYS) {- void idb.removeItem(key);- }-- const fresh = () =>- !hydratedFromServer && activeCompanyId === requestedCompanyId;-- idb.getItem(`customers:${requestedCompanyId}`).then((data) => {- if (data && fresh()) setCustomers(data as ListItem[], true);- });- idb.getItem(`items:${requestedCompanyId}`).then((data) => {- if (data && fresh()) setItems(data as Item[], true);+ // Quantities are maintained incrementally by triggers on itemLedger, so this+ // fires on the posting itself. Invalidate rather than refetch: the on-hand map+ // is read by the item picker (`useItemQuantities` in `~/components/Form/Item`)+ // and only when one is mounted.+ useTableChanges({+ companyId,+ table: "itemStockQuantities",+ onChange: () => {+ getClientCache()?.invalidateQueries({+ predicate: ({ queryKey }) =>+ queryKey[0] === LOADER &&+ String(queryKey[2]).startsWith(ITEM_QUANTITIES_PATH)});- idb.getItem(`suppliers:${requestedCompanyId}`).then((data) => {- if (data && fresh()) setSuppliers(data as ListItem[], true);- });- idb.getItem(`people:${requestedCompanyId}`).then((data) => {- // @ts-expect-error- if (data && fresh()) setPeople(data, true);- });- }-- if (!carbon || !accessToken || hydratedFromServer) return;-- const [items, suppliers, customers, people, supersessions] =- await Promise.all([- fetchAllFromTable<{- id: string;- readableId: string;- revision: string;- readableIdWithRevision: string;- unitOfMeasureCode: string;- name: string;- type: Database["public"]["Enums"]["itemType"];- replenishmentSystem: Database["public"]["Enums"]["itemReplenishmentSystem"];- active: boolean;- itemTrackingType: Database["public"]["Enums"]["itemTrackingType"];- }>(- carbon,- "item",- "id, readableId, revision, readableIdWithRevision, unitOfMeasureCode, name, type, replenishmentSystem, active, itemTrackingType",- (query) =>- query- .eq("companyId", companyId)- .order("readableId", { ascending: true })- .order("revision", { ascending: false })- ),- fetchAllFromTable<{- id: string;- name: string;- website: string;- supplierStatus: string;- readableId: string | null;- }>(- carbon,- "supplier",- "id, name, website, supplierStatus, readableId",- (query) => query.eq("companyId", companyId).order("name")- ),- fetchAllFromTable<{- id: string;- name: string;- website: string;- readableId: string | null;- }>(carbon, "customer", "id, name, website, readableId", (query) =>- query.eq("companyId", companyId).order("name")- ),- fetchAllFromTable<{- id: string;- name: string;- email: string;- avatarUrl: string;- active: boolean;- }>(carbon, "employees", "id, name, email, avatarUrl, active", (query) =>- query.eq("companyId", companyId).order("name")- ),- fetchAllFromTable<{- itemId: string;- supersessionMode: Database["public"]["Enums"]["supersessionMode"];- successorItemId: string | null;- }>(- carbon,- "itemSupersession",- "itemId, supersessionMode, successorItemId",- (query) => query.eq("companyId", companyId)- )- ]);-- if (items.error) {- throw new Error("Failed to fetch items");- }- if (suppliers.error) {- throw new Error("Failed to fetch suppliers");- }- if (customers.error) {- throw new Error("Failed to fetch customers");- }- if (people.error) {- throw new Error("Failed to fetch people");- }-- // company switched while fetching — these results belong to the old company- if (activeCompanyId !== requestedCompanyId) return;-- hydratedFromServer = true;-- const supersessionByItem = new Map(- (supersessions.data ?? []).map((s) => [s.itemId, s])- );- const itemsWithLifecycle = (items.data ?? []).map((i) => ({- ...i,- supersessionMode: supersessionByItem.get(i.id)?.supersessionMode ?? null,- successorItemId: supersessionByItem.get(i.id)?.successorItemId ?? null- }));- setItems(itemsWithLifecycle);- setSuppliers(suppliers.data ?? []);- setCustomers(customers.data ?? []);- setPeople(people.data ?? []);-- await Promise.all([- idb.setItem(`items:${requestedCompanyId}`, itemsWithLifecycle),- idb.setItem(`suppliers:${requestedCompanyId}`, suppliers.data),- idb.setItem(`customers:${requestedCompanyId}`, customers.data),- idb.setItem(`people:${requestedCompanyId}`, people.data)- ]);- };-- // Re-run when auth becomes ready: `hydrate()` bails if `carbon` / `accessToken` are missing,- // and with only `[companyId]` that first run could be the only attempt — leaving `items` empty- // (e.g. New Job item combobox shows no options).- // biome-ignore lint/correctness/useExhaustiveDependencies: hydrate closes over setters + idb- useEffect(() => {- if (!companyId) return;- hydrate().catch((err) => logger.error("hydrate failed", { error: err }));- }, [companyId, carbon, accessToken]);-- // Every subscription below is filtered by `companyId` server-side. Without it- // each tenant's row changes are fanned out to every connected client and then- // discarded in JS — the client-side guards stay as defence in depth. The filter- // holds on DELETE too: `companyId` is part of each table's composite PK, so it- // is present in a payload that otherwise carries only key columns.- useRealtimeChannel({- topic: `realtime:core`,- dependencies: [companyId],- setup(channel, carbon) {- return channel- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "item",- filter: `companyId=eq.${companyId}`- },- (payload) => {- switch (payload.eventType) {- case "INSERT":- if (- "companyId" in payload.new &&- payload.new.companyId !== companyId- )- return;- const { new: inserted } = payload;-- setItems((items) =>- [- ...items,- {- id: inserted.id,- name: inserted.name,- readableId: inserted.readableId,- revision: inserted.revision,- readableIdWithRevision: inserted.readableIdWithRevision,- description: inserted.description,- replenishmentSystem: inserted.replenishmentSystem,- itemTrackingType: inserted.itemTrackingType,- unitOfMeasureCode: inserted.unitOfMeasureCode,- type: inserted.type,- active: inserted.active- }- ].sort((a, b) =>- a.readableIdWithRevision.localeCompare(- b.readableIdWithRevision- )- )- );- break;- case "UPDATE":- const { new: updated } = payload;-- setItems((items) =>- items- .map((i) => {- if (i.id === updated.id) {- return {- ...i,- readableId: updated.readableId,- revision: updated.revision,- readableIdWithRevision:- updated.readableIdWithRevision,- name: updated.name,- replenishmentSystem: updated.replenishmentSystem,- itemTrackingType: updated.itemTrackingType,- unitOfMeasureCode: updated.unitOfMeasureCode,- type: updated.type,- active: updated.active- };- }- return i;- })- .sort((a, b) =>- a.readableIdWithRevision.localeCompare(- b.readableIdWithRevision- )- )- );- break;- case "DELETE":- const { old: deleted } = payload;- setItems((items) => items.filter((p) => p.id !== deleted.id));- break;- default:- break;- }- }- )- .on(- "postgres_changes",- {- event: "*",- schema: "public",- // Quantities are maintained incrementally by triggers on itemLedger,- // so this fires on the posting itself rather than up to 30 min later- // (the matview refresh this replaced).- table: "itemStockQuantities",- filter: `companyId=eq.${companyId}`- },- (payload) => {- // companyId is part of the primary key, so it is present even on a- // DELETE payload (which otherwise carries only key columns).- const row =- payload.eventType === "DELETE" ? payload.old : payload.new;- if (row && "companyId" in row && row.companyId !== companyId)- return;- // Invalidate rather than refetch: the on-hand map is fetched by the- // item picker (`useItemQuantities` in `~/components/Form/Item`) and- // only when one is mounted. Re-reading the whole table here cost a- // full download per burst of stock movements for a dropdown badge- // that may not be on screen at all.- // Every key under this prefix, not just this company's: the- // companyId term of the key comes from `getCompanyId()`, which- // reads `document.cookie` — and every cookie here is httpOnly, so- // it is always "null". Matching on it invalidated nothing. Keys for- // another company would only exist after a company switch, which- // reloads the page and empties this in-memory cache anyway.- window.clientCache?.invalidateQueries({- predicate: (query) =>- (query.queryKey as unknown[])[0] === ITEM_QUANTITIES_QUERY_KEY- });- }- )- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "customer",- filter: `companyId=eq.${companyId}`- },- (payload) => {- switch (payload.eventType) {- case "INSERT":- if (- "companyId" in payload.new &&- payload.new.companyId !== companyId- )- return;- const { new: inserted } = payload;- // upsert (not append): the create-on-the-fly flow may have- // already added this customer synchronously.- setCustomers((customers) =>- upsertIntoListStore(customers, {- id: inserted.id,- name: inserted.name,- website: inserted.website,- readableId: inserted.readableId ?? undefined- })- );- break;- case "UPDATE":- const { new: updated } = payload;- setCustomers((customers) =>- customers- .map((p) => {- if (p.id === updated.id) {- return {- ...p,- name: updated.name,- website: updated.website,- readableId: updated.readableId ?? undefined- };- }- return p;- })- .sort((a, b) => a.name.localeCompare(b.name))- );- break;- case "DELETE":- const { old: deleted } = payload;- setCustomers((customers) =>- customers.filter((p) => p.id !== deleted.id)- );- break;- default:- break;- }- }- )- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "supplier",- filter: `companyId=eq.${companyId}`- },- (payload) => {- switch (payload.eventType) {- case "INSERT":- if (- "companyId" in payload.new &&- payload.new.companyId !== companyId- )- return;- const { new: inserted } = payload;- // upsert (not append): the create-on-the-fly flow may have- // already added this supplier synchronously.- setSuppliers((suppliers) =>- upsertIntoListStore(suppliers, {- id: inserted.id,- name: inserted.name,- website: inserted.website,- supplierStatus: inserted.supplierStatus,- readableId: inserted.readableId ?? undefined- })- );- break;- case "UPDATE":- const { new: updated } = payload;- setSuppliers((suppliers) =>- suppliers- .map((p) => {- if (p.id === updated.id) {- return {- ...p,- name: updated.name,- website: updated.website,- supplierStatus: updated.supplierStatus,- readableId: updated.readableId ?? undefined- };- }- return p;- })- .sort((a, b) => a.name.localeCompare(b.name))- );- break;- case "DELETE":- const { old: deleted } = payload;- setSuppliers((suppliers) =>- suppliers.filter((p) => p.id !== deleted.id)- );- break;- default:- break;- }- }- )- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "employee",- filter: `companyId=eq.${companyId}`- },- async (payload) => {- // TODO: there's a cleaner way of doing this, but since customers and suppliers- // are also in the users table, we can't automatically add/update/delete them- // from our list of employees. So for now we just refetch.- const { data } = await carbon- .from("employees")- .select("id, name, avatarUrl")- .eq("companyId", companyId)- .order("name");- if (data) {- setPeople(data);- }- }- );}});- return <>{children}</>;+ return (+ <>+ <LiveLists+ companyId={companyId}+ userId={userId}+ lists={LISTS}+ storage={storage}+ />+ {children}+ </>+ );};export default RealtimeDataProvider;diff --git a/apps/erp/app/components/Selectors/UserSelect/useUserSelect.ts b/apps/erp/app/components/Selectors/UserSelect/useUserSelect.tsindex 4a93ec63b6..d327cd1962 100644--- a/apps/erp/app/components/Selectors/UserSelect/useUserSelect.ts+++ b/apps/erp/app/components/Selectors/UserSelect/useUserSelect.ts@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { getLogger } from "@carbon/logger";+import { cachedApiQuery, RefreshRate } from "@carbon/query";import { useDisclosure, useOutsideClick } from "@carbon/react";import debounce from "lodash/debounce";import words from "lodash/words";@@ -21,14 +22,6 @@ import type {UserSelectGroupMembers} from "~/modules/users";import { path } from "~/utils/path";-import {- cachedApiQuery,- getCompanyId,- userSelectGroupsQuery,- userSelectMembersQuery,- userSelectResolveQuery,- userSelectSearchQuery-} from "~/utils/react-query";import type {GroupNode,@@ -130,8 +123,6 @@ export default function useUserSelect(props: UserSelectProps) {const loadPage = useCallback(async (offset: number, append: boolean) => {- const companyId = getCompanyId();- const type = innerProps.type ?? null;if (append) {setLoadingMore(true);} else {@@ -141,10 +132,7 @@ export default function useUserSelect(props: UserSelectProps) {const data = await cachedApiQuery<{groups: UserSelectGroup[];hasMore: boolean;- }>(- userSelectGroupsQuery(companyId, type, offset),- path.to.api.userSelectGroups(innerProps.type, offset, PAGE_SIZE)- );+ }>(path.to.api.userSelectGroups(innerProps.type, offset, PAGE_SIZE));setTopLevelGroups((prev) => {const base = append ? prev : [];const seen = new Set(base.map((g) => g.id));@@ -183,13 +171,11 @@ export default function useUserSelect(props: UserSelectProps) {const fetchMembers = useCallback(async (groupId: string): Promise<UserSelectGroupMembers | null> => {- const companyId = getCompanyId();setLoadingGroups((prev) =>prev[groupId] ? prev : { ...prev, [groupId]: true });try {const data = await cachedApiQuery<UserSelectGroupMembers>(- userSelectMembersQuery(companyId, groupId),path.to.api.userSelectGroupMembers(groupId));setMembersById((prev) => ({ ...prev, [groupId]: data }));@@ -315,15 +301,10 @@ export default function useUserSelect(props: UserSelectProps) {missing.forEach((val) => {resolveRequested.current.add(val);});-- const companyId = getCompanyId();cachedApiQuery<{users: User[];groups: { id: string; name: string }[];- }>(- userSelectResolveQuery(companyId, missing),- path.to.api.userSelectResolve(missing)- )+ }>(path.to.api.userSelectResolve(missing)).then((data) => {setSelectionItemsById((prev) => {let changed = false;@@ -585,9 +566,6 @@ export default function useUserSelect(props: UserSelectProps) {resetFocus();return;}-- const companyId = getCompanyId();- const filtersKey = `${queryFilters?.excludeSelf ?? ""}|${queryFilters?.allowedIds?.join(",") ?? ""}`;let searchUrl = path.to.api.userSelectSearch(q, type);if (queryFilters?.excludeSelf) {searchUrl += "&excludeSelf=true";@@ -601,10 +579,7 @@ export default function useUserSelect(props: UserSelectProps) {const data = await cachedApiQuery<{groups: UserSelectGroup[];users: User[];- }>(- userSelectSearchQuery(companyId, type ?? null, q, filtersKey),- searchUrl- );+ }>(searchUrl, { staleTime: RefreshRate.High });setSearchResults(data);} catch (e) {logger.error("Failed to search users", { error: e });diff --git a/apps/erp/app/components/SessionLockOverlay.tsx b/apps/erp/app/components/SessionLockOverlay.tsxindex d0260e54b3..cfc0ea1307 100644--- a/apps/erp/app/components/SessionLockOverlay.tsx+++ b/apps/erp/app/components/SessionLockOverlay.tsx@@ -9,6 +9,7 @@ import {useControlField,ValidatedForm} from "@carbon/form";+import { useAction } from "@carbon/query";import {Alert,AlertDescription,@@ -27,7 +28,7 @@ import {} from "@simplewebauthn/browser";import { useEffect, useRef, useState } from "react";import { LuFingerprint, LuLock } from "react-icons/lu";-import { Form, useFetcher, useLocation } from "react-router";+import { Form, useLocation } from "react-router";import { z } from "zod";import type { Result } from "~/types";@@ -80,7 +81,13 @@ export default function SessionLockOverlay({const location = useLocation();const redirectTo = `${location.pathname}${location.search}`;- const fetcher = useFetcher<Result>();+ const fetcher = useAction<Result>({+ onSuccess: (data) => {+ if (data?.success === true) {+ onUnlocked?.();+ }+ }+ });const [passkeySupported, setPasskeySupported] = useState(false);const [passkeyLoading, setPasskeyLoading] = useState(false);@@ -89,13 +96,6 @@ export default function SessionLockOverlay({if (hasPasskeyAuth && browserSupportsWebAuthn()) setPasskeySupported(true);}, [hasPasskeyAuth]);- // A successful in-place unlock (TOTP or passkey) rotated the cookie already;- // clear the client lock so the overlay unmounts and the app (revalidated with- // the fresh session) shows through.- useEffect(() => {- if (fetcher.data?.success === true) onUnlocked?.();- }, [fetcher.data, onUnlocked]);-const onUnlockWithPasskey = async () => {setPasskeyLoading(true);try {diff --git a/apps/erp/app/components/TimeCardWarning.tsx b/apps/erp/app/components/TimeCardWarning.tsxindex a004238726..d1c27c2710 100644--- a/apps/erp/app/components/TimeCardWarning.tsx+++ b/apps/erp/app/components/TimeCardWarning.tsx@@ -5,6 +5,7 @@"use client";import { ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Modal,@@ -32,7 +33,6 @@ import {import { Trans, useLingui } from "@lingui/react/macro";import { useLocale } from "@react-aria/i18n";import { useEffect, useState } from "react";-import { useFetcher } from "react-router";import { setClockOutValidator } from "~/modules/people";import { path } from "~/utils/path";import { DateTimePicker, Hidden, Submit } from "./Form";@@ -52,7 +52,16 @@ export function TimeCardWarning({ openClockEntry }: TimeCardWarningProps) {const { t } = useLingui();const { locale } = useLocale();const [showClockWarning, setShowClockWarning] = useState(false);- const fetcher = useFetcher();+ const fetcher = useAction({+ onSettled: (data) => {+ if (data) {+ if ((data as { success?: boolean }).success) {+ toast.success(t`Updated successfully`);+ setShowClockWarning(false);+ }+ }+ }+ });useEffect(() => {if (!openClockEntry) {@@ -81,15 +90,6 @@ export function TimeCardWarning({ openClockEntry }: TimeCardWarningProps) {return () => clearInterval(interval);}, [openClockEntry]);- useEffect(() => {- if (fetcher.data && fetcher.state === "idle") {- if ((fetcher.data as { success?: boolean }).success) {- toast.success(t`Updated successfully`);- setShowClockWarning(false);- }- }- }, [fetcher.data, fetcher.state, t]);-const handleClockAcknowledge = () => {if (openClockEntry) {sessionStorage.setItem(CLOCK_STORAGE_KEY, openClockEntry.id);diff --git a/apps/erp/app/hooks/index.ts b/apps/erp/app/hooks/index.tsindex 1e0421a07f..5cb3b27ad1 100644--- a/apps/erp/app/hooks/index.ts+++ b/apps/erp/app/hooks/index.ts@@ -5,7 +5,6 @@import { usePrinting } from "@carbon/printing/ui";import {useIdle,- useNanoStore,useOptimisticLocation,useRouteData,useUrlParams@@ -68,7 +67,6 @@ export {useSettingsModule,useModelUpload,useMovingCellRef,- useNanoStore,useNextItemId,useNotifications,useOnboarding,diff --git a/apps/erp/app/hooks/useCurrencies.ts b/apps/erp/app/hooks/useCurrencies.tsindex 6c2a596ca8..1b5945004a 100644--- a/apps/erp/app/hooks/useCurrencies.ts+++ b/apps/erp/app/hooks/useCurrencies.ts@@ -2,10 +2,9 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useMount } from "@carbon/react";+import { RefreshRate, useLoaderQuery } from "@carbon/query";import { cldrCurrencyDecimals, DEFAULT_CURRENCY_DECIMALS } from "@carbon/utils";import { createContext, useContext, useMemo } from "react";-import { useFetcher } from "react-router";import type { getCurrenciesList } from "~/modules/accounting";import { path } from "~/utils/path";import { useCompanySettings } from "./useCompanySettings";@@ -15,7 +14,7 @@ type CurrencyList = NonNullable<>;/** Set by a route that loaded the list itself. The currencies API is- * `requirePermissions`-gated, so the fetcher below returns nothing on a public+ * `requirePermissions`-gated, so the query below returns nothing on a public* page and every amount silently falls back to CLDR — which is the one thing* the standard says is NOT authoritative. */const CurrenciesContext = createContext<CurrencyList | undefined>(undefined);@@ -30,13 +29,12 @@ export const CurrenciesProvider = CurrenciesContext.Provider;*/export function useCurrencies(): CurrencyList {const provided = useContext(CurrenciesContext);- const currencyFetcher =- useFetcher<Awaited<ReturnType<typeof getCurrenciesList>>>();-- useMount(() => {- // A provided list means the route already has it and the endpoint is not- // reachable anyway — asking would be a guaranteed 401 on every public view.- if (!provided) currencyFetcher.load(path.to.api.currencies);+ // A provided list means the route already has it and the endpoint is not+ // reachable anyway — asking would be a guaranteed 401 on every public view.+ const currencyFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getCurrenciesList>>+ >(provided ? null : path.to.api.currencies, {+ staleTime: RefreshRate.Never});return provided ?? currencyFetcher.data?.data ?? [];diff --git a/apps/erp/app/hooks/useDebouncedRealtime.ts b/apps/erp/app/hooks/useDebouncedRealtime.tsindex 61185a15d6..cf2a9cbe64 100644--- a/apps/erp/app/hooks/useDebouncedRealtime.ts+++ b/apps/erp/app/hooks/useDebouncedRealtime.ts@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import type { RealtimeTable } from "@carbon/database/realtime-tables";import { useRealtime } from "./useRealtime";/**@@ -9,13 +10,12 @@ import { useRealtime } from "./useRealtime";** Use for append-heavy tables (e.g. `itemLedger`) where one business action* 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.+ * not a burst spread over the default window. The topic is already the+ * company's, so no filter is needed to follow every change to the table.*/export function useDebouncedRealtime(- table: string,- filter: string | undefined,+ table: RealtimeTable,+ filter?: string,debounceMs = 1500) {return useRealtime(table, filter, debounceMs);diff --git a/apps/erp/app/hooks/useDocumentExtraction.tsx b/apps/erp/app/hooks/useDocumentExtraction.tsxindex 7f4a800613..07f8050d6f 100644--- a/apps/erp/app/hooks/useDocumentExtraction.tsx+++ b/apps/erp/app/hooks/useDocumentExtraction.tsx@@ -2,7 +2,8 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useCarbon, useRealtimeChannel } from "@carbon/react";+import { useChangedRows } from "@carbon/query";+import { useCarbon } from "@carbon/react";import { useCallback, useEffect, useRef, useState } from "react";import type {DocumentExtractionType,@@ -30,7 +31,7 @@ const POLL_INTERVAL_MS = 3_000;* (confidence-gated) data once completed.** Uses two complementary strategies:- * 1. Supabase Realtime postgres_changes — instant push when available.+ * 1. A realtime broadcast — instant push when available.* 2. Polling fallback every 3 s while extraction is in-progress — ensures* the UI never stalls if the realtime event is missed or the channel* takes time to subscribe.@@ -107,36 +108,35 @@ export function useDocumentExtraction(}, [clearPoll]);// Subscribe to realtime changes- useRealtimeChannel({- topic: `extraction:${extractionId ?? "none"}`,- dependencies: [extractionId, company.id],- setup(channel) {- // Fetch initial data on subscribe (also starts polling if in-progress)- fetchInitial();-- return channel.on(- "postgres_changes",- {- event: "UPDATE",- schema: "public",- table: "documentExtraction",- filter: extractionId ? `id=eq.${extractionId}` : undefined- },- (payload) => {- const row = payload.new as Record<string, unknown>;- if (row.companyId !== company.id) return;+ // biome-ignore lint/correctness/useExhaustiveDependencies: load once per extraction (also starts polling if in-progress)+ useEffect(() => {+ fetchInitial();+ }, [extractionId, company.id]);- handleRealtimeUpdate({- id: row.id as string,- status: row.status as ExtractionStatus,- filteredData: row.filteredData- ? parseExtractedData(documentType, row.filteredData)- : null,- error: row.error as string | null,- storagePath: row.storagePath as string | null- });- }- );+ useChangedRows<{+ id: string;+ status: ExtractionStatus;+ filteredData: unknown;+ error: string | null;+ storagePath: string | null;+ }>({+ companyId: company.id,+ table: "documentExtraction",+ columns: "id, status, filteredData, error, storagePath",+ enabled: !!extractionId,+ onResync: fetchInitial,+ onChange: ({ rows }) => {+ const row = rows.find((r) => r.id === extractionId);+ if (!row) return;+ handleRealtimeUpdate({+ id: row.id,+ status: row.status,+ filteredData: row.filteredData+ ? parseExtractedData(documentType, row.filteredData)+ : null,+ error: row.error,+ storagePath: row.storagePath+ });}});diff --git a/apps/erp/app/hooks/useImplementationRealtime.tsx b/apps/erp/app/hooks/useImplementationRealtime.tsxindex 9c033baa36..0cedd5faab 100644--- a/apps/erp/app/hooks/useImplementationRealtime.tsx+++ b/apps/erp/app/hooks/useImplementationRealtime.tsx@@ -2,61 +2,13 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useRealtimeChannel } from "@carbon/react";-import { useRevalidator } from "react-router";+import { useRealtimeTable } from "@carbon/query";// Live-sync the Implementation Hub both directions: any change by Carbon staff or-// the customer's own users re-runs the hub loaders for every open client. Reuses-// the shared realtime channel infra (auth + reconnect handled there).+// the customer's own users re-runs the hub loaders for every open client.export function useImplementationRealtime(companyId: string) {- const revalidator = useRevalidator();-- useRealtimeChannel({- topic: `implementation:${companyId}`,- dependencies: [companyId],- setup(channel) {- const onChange = () => revalidator.revalidate();- return channel- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "implementationHub",- filter: `id=eq.${companyId}`- },- onChange- )- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "implementationCheckState",- filter: `companyId=eq.${companyId}`- },- onChange- )- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "implementationFieldValue",- filter: `companyId=eq.${companyId}`- },- onChange- )- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "implementationRow",- filter: `companyId=eq.${companyId}`- },- onChange- );- }- });+ useRealtimeTable({ companyId, table: "implementationHub" });+ useRealtimeTable({ companyId, table: "implementationCheckState" });+ useRealtimeTable({ companyId, table: "implementationFieldValue" });+ useRealtimeTable({ companyId, table: "implementationRow" });}diff --git a/apps/erp/app/hooks/useNotifications.tsx b/apps/erp/app/hooks/useNotifications.tsxindex 73aba18a7d..f1d1f7e883 100644--- a/apps/erp/app/hooks/useNotifications.tsx+++ b/apps/erp/app/hooks/useNotifications.tsx@@ -3,7 +3,8 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { getLogger } from "@carbon/logger";-import { useCarbon, useRealtimeChannel } from "@carbon/react";+import { useTopic } from "@carbon/query";+import { useCarbon } from "@carbon/react";import { useCallback, useEffect, useMemo, useState } from "react";import type { Notification } from "~/types";@@ -39,8 +40,12 @@ export function useNotifications({const { carbon } = useCarbon();const [isLoading, setLoading] = useState(true);const [notifications, setNotifications] = useState<Notification[]>([]);+ // Bumped to run the initial load again (a reconnect, a bulk change).+ const [reloads, setReloads] = useState(0);- // Initial fetch — runs once per (carbon/user/company) tuple.+ // Initial fetch — runs once per (carbon/user/company) tuple, and again when+ // `reloads` is bumped.+ // biome-ignore lint/correctness/useExhaustiveDependencies: `reloads` is a trigger, not an inputuseEffect(() => {if (!carbon) return;let cancelled = false;@@ -70,64 +75,47 @@ export function useNotifications({return () => {cancelled = true;};- }, [carbon, userId, companyId]);-- // Realtime stream — useRealtimeChannel waits for isRealtimeAuthSet so RLS- // policies on `notification` resolve via the user's JWT.- useRealtimeChannel({- dependencies: [userId, companyId],- setup(channel) {- return channel.on(- "postgres_changes" as any,- {- event: "*",- filter: `userId=eq.${userId}`,- schema: "public",- table: "notification"- },- (payload: {- eventType: string;- new: NotificationRow;- old: NotificationRow;- }) => {- if (payload.new && payload.new.companyId !== companyId) return;- if (payload.eventType === "INSERT") {- // Rows born inside a digest (digestedInto set on insert) are- // represented by their parent — never shown individually.- const insertedRow = payload.new as NotificationRow & {- digestedInto?: string | null;- };- if (insertedRow.digestedInto) return;- setNotifications((prev) => [- rowToNotification(payload.new),- ...prev- ]);- } else if (payload.eventType === "UPDATE") {- // A row that just got attached to a digest disappears from the- // topbar — it's now represented by its digest parent.- const newRow = payload.new as NotificationRow & {- digestedInto?: string | null;- };- if (newRow.digestedInto) {- setNotifications((prev) =>- prev.filter((n) => n._id !== newRow.id)- );- } else {- setNotifications((prev) =>- prev.map((n) =>- n._id === newRow.id ? rowToNotification(newRow) : n- )- );- }- } else if (payload.eventType === "DELETE") {- setNotifications((prev) =>- prev.filter((n) => n._id !== (payload.old as NotificationRow).id)- );- }- }+ }, [carbon, userId, companyId, reloads]);++ // Realtime stream. A broadcast names the rows that changed and nothing else,+ // so they are re-read here: table RLS limits that read to this user's rows.+ useTopic(`user:${userId}:notification`, async (change) => {+ // A reconnect or a bulk change: load the list again.+ if (!change?.ids || !carbon) {+ setReloads((n) => n + 1);+ return;+ }+ const { op, ids } = change;+ if (op === "DELETE") {+ setNotifications((prev) => prev.filter((n) => !ids.includes(n._id)));+ return;+ }+ const { data, error } = await carbon+ .from("notification")+ .select(+ "id, userId, companyId, readAt, seenAt, createdAt, payload, digestedInto"+ )+ .in("id", ids)+ .eq("companyId", companyId);+ if (error) {+ logger.error("Failed to load changed notifications", error);+ return;+ }+ const rows = (data ?? []) as (NotificationRow & {+ digestedInto?: string | null;+ })[];+ setNotifications((prev) => {+ // A row attached to a digest — on insert or later — is represented+ // by its digest parent, never shown on its own.+ const changed = new Set(ids);+ const kept = prev.filter((n) => !changed.has(n._id));+ const shown = rows+ .filter((row) => !row.digestedInto)+ .map(rowToNotification);+ return [...shown, ...kept].sort((a, b) =>+ b.createdAt.localeCompare(a.createdAt));- },- topic: `notification:${companyId}:${userId}`+ });});const markMessageAsRead = useCallback(diff --git a/apps/erp/app/hooks/useRealtime.tsx b/apps/erp/app/hooks/useRealtime.tsxindex 4c1d8a7ab7..dfb33b0a5a 100644--- a/apps/erp/app/hooks/useRealtime.tsx+++ b/apps/erp/app/hooks/useRealtime.tsx@@ -2,77 +2,25 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { getLogger } from "@carbon/logger";-import { useRealtimeChannel } from "@carbon/react";-import { useEffect, useRef } from "react";-import { useRevalidator } from "react-router";+import type { RealtimeTable } from "@carbon/database/realtime-tables";+import { useRealtimeTable } from "@carbon/query";import { useUser } from "./useUser";-const logger = getLogger("erp", "userealtime");--// 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;-+/**+ * Reloads the page's data when `table` changes in the user's company. A route+ * declares its tables in `handle.realtime` instead; this is for a component+ * that is not a route. Only an `id=eq.` / `id=in.()` filter narrows it.+ */export function useRealtime(- table: string,+ table: RealtimeTable,filter?: string,- debounceMs = DEFAULT_DEBOUNCE_MS+ debounceMs?: number) {const { company } = useUser();- const revalidator = useRevalidator();- const timeout = useRef<ReturnType<typeof setTimeout> | null>(null);-- // Default to the caller's company rather than subscribing to every tenant's- // writes and discarding them below — with ~1600 tenants an unfiltered- // subscription fans every company's changes out to every client. A caller- // that passes its own narrower filter (`runId=eq.…`) keeps it. This assumes- // the table has a `companyId` column; every table reached without a filter- // does. Pass an explicit filter for one that does not — a filter on a column- // that doesn't exist delivers nothing at all, silently.- const scopedFilter = filter ?? `companyId=eq.${company.id}`;-- useEffect(- () => () => {- if (timeout.current) clearTimeout(timeout.current);- },- []- );-- const channel = useRealtimeChannel({- topic: `postgres_changes:${table}`,- dependencies: [company.id, scopedFilter, debounceMs],- setup(channel) {- return channel.on(- "postgres_changes",- { event: "*", schema: "public", table: table, filter: scopedFilter },- (payload) => {- // The row lives under `new`/`old`, never on the payload itself.- // Defence in depth behind the server-side filter above.- const row = (payload.new ?? payload.old) as- | { companyId?: string }- | undefined;- if (row?.companyId && row.companyId !== company.id) {- return;- }-- // 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);- }- );- }+ return useRealtimeTable({+ companyId: company.id,+ table,+ filter,+ debounceMs});-- return channel;}diff --git a/apps/erp/app/hooks/useSwaggerDocs.tsx b/apps/erp/app/hooks/useSwaggerDocs.tsxindex 63c74d1236..8e1c2e6dc0 100644--- a/apps/erp/app/hooks/useSwaggerDocs.tsx+++ b/apps/erp/app/hooks/useSwaggerDocs.tsx@@ -2,8 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useMount } from "@carbon/react";-import { useFetcher } from "react-router";+import { useLoaderQuery } from "@carbon/query";import { path } from "~/utils/path";type SwaggerDocsSchema = {@@ -12,11 +11,7 @@ type SwaggerDocsSchema = {};export const useSwaggerDocs = () => {- const docsFetcher = useFetcher<SwaggerDocsSchema>();-- useMount(() => {- docsFetcher.load(path.to.api.docs);- });+ const docsFetcher = useLoaderQuery<SwaggerDocsSchema>(path.to.api.docs);return docsFetcher.data;};diff --git a/apps/erp/app/modules/agent/ui/AgentThreadList.tsx b/apps/erp/app/modules/agent/ui/AgentThreadList.tsxindex 5bae2a9acc..a19cddff37 100644--- a/apps/erp/app/modules/agent/ui/AgentThreadList.tsx+++ b/apps/erp/app/modules/agent/ui/AgentThreadList.tsx@@ -2,7 +2,8 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useEffect, useState } from "react";+import { useLoaderQuery } from "@carbon/query";+import { useState } from "react";import { LuTrash2 } from "react-icons/lu";import { useFetcher } from "react-router";import { DateTime } from "~/components";@@ -21,17 +22,13 @@ export function AgentThreadList({onSelect: (id: string) => void;onDelete?: (id: string) => void;}) {- const fetcher = useFetcher<{ threads: Thread[] }>();+ const fetcher = useLoaderQuery<{ threads: Thread[] }>(+ path.to.api.agentThreads+ );const deleteFetcher = useFetcher();const [query, setQuery] = useState("");const [deletedIds, setDeletedIds] = useState<Set<string>>(new Set());- useEffect(() => {- if (fetcher.state === "idle" && !fetcher.data) {- fetcher.load(path.to.api.agentThreads);- }- }, [fetcher]);-const threads = (fetcher.data?.threads ?? []).filter((t) => !deletedIds.has(t.id));diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex cf776634ea..e69090e74c 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -13,7 +13,7 @@ import { consumableInWholeAssemblies } from "@carbon/database/supersession-pick"import { storage } from "@carbon/files";import { type ServerFnInput, serverFns } from "@carbon/server-functions";import type { TrackedEntityAttributes } from "@carbon/utils";-import { datetime, getErrorMessage } from "@carbon/utils";+import { async, datetime, getErrorMessage } from "@carbon/utils";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";import { nanoid } from "nanoid";import type { z } from "zod";@@ -3519,13 +3519,17 @@ async function getWarehouseOnHand(}total = Math.max(0, total);- for (const [storageUnitId, qty] of perUnit) {- if (qty <= 0) continue;- const effectiveWc = await client.rpc("get_effective_work_center_id", {- p_storage_unit_id: storageUnitId- });- if (!effectiveWc.data) total += qty;- }+ const stocked = Array.from(perUnit).filter(([, qty]) => qty > 0);+ const workCenters = await async.map(+ stocked,+ async ([storageUnitId]) =>+ await client.rpc("get_effective_work_center_id", {+ p_storage_unit_id: storageUnitId+ })+ );+ stocked.forEach(([, qty], index) => {+ if (!workCenters[index]?.data) total += qty;+ });return total;}diff --git a/apps/erp/app/modules/inventory/ui/Batches/BatchPropertiesConfig.tsx b/apps/erp/app/modules/inventory/ui/Batches/BatchPropertiesConfig.tsxindex 7a1e9e80b6..afe12a71f5 100644--- a/apps/erp/app/modules/inventory/ui/Batches/BatchPropertiesConfig.tsx+++ b/apps/erp/app/modules/inventory/ui/Batches/BatchPropertiesConfig.tsx@@ -10,6 +10,7 @@ import {Submit,ValidatedForm} from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,ClientOnly,@@ -44,14 +45,14 @@ import {import { SortableContext, useSortable } from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";import { Trans, useLingui } from "@lingui/react/macro";-import { useEffect, useRef, useState } from "react";+import { useRef, useState } from "react";import { createPortal } from "react-dom";import {LuCirclePlus,LuEllipsisVertical,LuGripVertical} from "react-icons/lu";-import { useFetcher, useFetchers, useSubmit } from "react-router";+import { useFetchers, useSubmit } from "react-router";import { DateTime, EmployeeAvatar } from "~/components";import { ConfiguratorDataTypeIcon } from "~/components/Configurator/Icons";import { ConfirmDelete } from "~/components/Modals";@@ -79,13 +80,13 @@ export default function BatchPropertiesConfig({const { t } = useLingui();const submit = useSubmit();- const fetcher = useFetcher<typeof batchPropertyAction>();-- useEffect(() => {- if (fetcher.data?.success === false) {- toast.error(t`Failed to update batch property`);+ const fetcher = useAction<typeof batchPropertyAction>({+ onError: (data) => {+ if (data?.success === false) {+ toast.error(t`Failed to update batch property`);+ }}- }, [fetcher.data, t]);+ });const propertiesById = new Map<string, BatchProperty>(initialProperties.map((property) => [property.id, property])@@ -309,7 +310,14 @@ function BatchPropertyComponent({const disclosure = useDisclosure();const deletePropertyDisclosure = useDisclosure();const submitted = useRef(false);- const fetcher = useFetcher<typeof batchPropertyAction>();+ const fetcher = useAction<typeof batchPropertyAction>({+ onSettled: () => {+ if (submitted.current) {+ disclosure.onClose();+ submitted.current = false;+ }+ }+ });const {attributes,@@ -327,13 +335,6 @@ function BatchPropertyComponent({transition};- useEffect(() => {- if (submitted.current && fetcher.state === "idle") {- disclosure.onClose();- submitted.current = false;- }- }, [disclosure, fetcher.state]);-const isUpdated = property.updatedBy !== null;const person = isUpdated ? property.updatedBy : property.createdBy;const date = property.updatedAt ?? property.createdAt;diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsxindex 13dbbf988b..71dee6e110 100644--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx@@ -5,6 +5,7 @@import { useCarbon } from "@carbon/auth";import { isPreviewableDocumentType, storage } from "@carbon/files";import { Number, Submit, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Card,@@ -1232,13 +1233,13 @@ function SplitReceiptLineModal({onClose: () => void;}) {const { t } = useLingui();- const fetcher = useFetcher<{ success: boolean }>();- useEffect(() => {- if (fetcher.data?.success) {- onClose();+ const fetcher = useAction<{ success: boolean }>({+ onSuccess: (data) => {+ if (data?.success) {+ onClose();+ }}- }, [fetcher.data?.success, onClose]);-+ });return (<Modal open onOpenChange={onClose}><ModalContent>diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptVoidModal.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptVoidModal.tsxindex da66834043..192f278c19 100644--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptVoidModal.tsx+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptVoidModal.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {Alert,AlertDescription,@@ -17,9 +18,9 @@ import {ModalTitle} from "@carbon/react";import { Trans } from "@lingui/react/macro";-import { useEffect, useRef } from "react";+import { useRef } from "react";import { LuTriangleAlert } from "react-icons/lu";-import { useFetcher, useNavigation, useParams } from "react-router";+import { useNavigation, useParams } from "react-router";import { path } from "~/utils/path";const ReceiptVoidModal = ({ onClose }: { onClose: () => void }) => {@@ -27,15 +28,14 @@ const ReceiptVoidModal = ({ onClose }: { onClose: () => void }) => {if (!receiptId) throw new Error("receiptId not found");const navigation = useNavigation();- const fetcher = useFetcher<{}>();- const submitted = useRef(false);-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (fetcher.state === "idle" && submitted.current) {- onClose();+ const fetcher = useAction<{}>({+ onSettled: () => {+ if (submitted.current) {+ onClose();+ }}- }, [fetcher.state]);+ });+ const submitted = useRef(false);return (<Modaldiff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReturnEntityForm.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReturnEntityForm.tsxindex 9644c90630..c1e0650893 100644--- a/apps/erp/app/modules/inventory/ui/Receipts/ReturnEntityForm.tsx+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReturnEntityForm.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import { Combobox, HStack, VStack } from "@carbon/react";import { round } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";@@ -52,7 +53,13 @@ export function ReturnEntityForm({candidates: CandidateEntity[];assigned: AssignedRow[];}>();- const assignFetcher = useFetcher<{ error?: string }>();+ const assignFetcher = useAction<{ error?: string }>({+ onSettled: (data) => {+ if (data) {+ reload();+ }+ }+ });const reload = () => {if (line.lineId) {@@ -67,14 +74,6 @@ export function ReturnEntityForm({reload();}, [line.lineId]);- // Refresh assignment state after each assign/remove settles- // biome-ignore lint/correctness/useExhaustiveDependencies: refetch on settle- useEffect(() => {- if (assignFetcher.state === "idle" && assignFetcher.data) {- reload();- }- }, [assignFetcher.state]);-const candidates = candidatesFetcher.data?.candidates;const assignedByEntityId = useMemo(() => {diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsxindex 8d70abc444..b9bb091dc4 100644--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentLines.tsx@@ -4,6 +4,7 @@import { useCarbon } from "@carbon/auth";import { Number, Submit, ValidatedForm } from "@carbon/form";+import { useAction, useLoaderQuery } from "@carbon/query";import {Button,Card,@@ -1360,13 +1361,13 @@ function SplitShipmentLineModal({onClose: () => void;}) {const { t } = useLingui();- const fetcher = useFetcher<{ success: boolean }>();- useEffect(() => {- if (fetcher.data?.success) {- onClose();+ const fetcher = useAction<{ success: boolean }>({+ onSuccess: (data) => {+ if (data?.success) {+ onClose();+ }}- }, [fetcher.data?.success, onClose]);-+ });return (<Modal open onOpenChange={onClose}><ModalContent>@@ -1487,29 +1488,17 @@ function resolveTrackedEntity(export default ShipmentLines;export function useSerialNumbers(itemId?: string, isReadOnly = false) {- const serialNumbersFetcher =- useFetcher<Awaited<ReturnType<typeof getSerialNumbersForItem>>>();-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (itemId) {- serialNumbersFetcher.load(path.to.api.serialNumbers(itemId, isReadOnly));- }- }, [itemId]);+ const serialNumbersFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getSerialNumbersForItem>>+ >(itemId ? path.to.api.serialNumbers(itemId, isReadOnly) : null);return { data: serialNumbersFetcher.data };}export function useBatchNumbers(itemId?: string) {- const batchNumbersFetcher =- useFetcher<Awaited<ReturnType<typeof getBatchNumbersForItem>>>();-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (itemId) {- batchNumbersFetcher.load(path.to.api.batchNumbers(itemId));- }- }, [itemId]);+ const batchNumbersFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getBatchNumbersForItem>>+ >(itemId ? path.to.api.batchNumbers(itemId) : null);return { data: batchNumbersFetcher.data };}diff --git a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentVoidModal.tsx b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentVoidModal.tsxindex 24eb85872b..97a6928d5f 100644--- a/apps/erp/app/modules/inventory/ui/Shipments/ShipmentVoidModal.tsx+++ b/apps/erp/app/modules/inventory/ui/Shipments/ShipmentVoidModal.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {Alert,AlertDescription,@@ -17,9 +18,9 @@ import {ModalTitle} from "@carbon/react";import { Trans } from "@lingui/react/macro";-import { useEffect, useRef } from "react";+import { useRef } from "react";import { LuTriangleAlert } from "react-icons/lu";-import { useFetcher, useNavigation, useParams } from "react-router";+import { useNavigation, useParams } from "react-router";import { path } from "~/utils/path";const ShipmentVoidModal = ({ onClose }: { onClose: () => void }) => {@@ -27,15 +28,14 @@ const ShipmentVoidModal = ({ onClose }: { onClose: () => void }) => {if (!shipmentId) throw new Error("shipmentId not found");const navigation = useNavigation();- const fetcher = useFetcher<{}>();- const submitted = useRef(false);-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (fetcher.state === "idle" && submitted.current) {- onClose();+ const fetcher = useAction<{}>({+ onSettled: () => {+ if (submitted.current) {+ onClose();+ }}- }, [fetcher.state]);+ });+ const submitted = useRef(false);return (<Modaldiff --git a/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx b/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsxindex ee2306efbc..d63bd64ff6 100644--- a/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx+++ b/apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx@@ -38,7 +38,7 @@ import {} from "~/components";import { Enumerable } from "~/components/Enumerable";import { useLocations } from "~/components/Form/Location";-import { usePermissions, useUser } from "~/hooks";+import { usePermissions } from "~/hooks";import { useDebouncedRealtime } from "~/hooks/useDebouncedRealtime";import type { MethodItemType } from "~/modules/shared";import { usePeople } from "~/stores";@@ -58,7 +58,6 @@ type StockMovementsTableProps = {const StockMovementsTable = memo(({ data, count }: StockMovementsTableProps) => {const { t } = useLingui();- const { company } = useUser();const permissions = usePermissions();const [correctionTarget, setCorrectionTarget] =useState<StockMovement | null>(null);@@ -72,7 +71,7 @@ const StockMovementsTable = memo(// Company-wide realtime: a single posting can insert many itemLedger rows// at once, so coalesce the burst into one route revalidation (1.5s debounce// inside useDebouncedRealtime) rather than revalidating per event.- useDebouncedRealtime("itemLedger", `companyId=eq.${company.id}`);+ useDebouncedRealtime("itemLedger");const columns = useMemo<ColumnDef<StockMovement>[]>(() => {return [diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferCompleteModal.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferCompleteModal.tsxindex 6d9766590a..5c066229d4 100644--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferCompleteModal.tsx+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferCompleteModal.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { useCarbon } from "@carbon/auth";+import { useAction } from "@carbon/query";import {Alert,AlertDescription,@@ -23,9 +24,9 @@ import {} from "@carbon/react";import { getItemReadableId } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";-import { useEffect, useRef, useState } from "react";+import { useRef, useState } from "react";import { LuTriangleAlert } from "react-icons/lu";-import { useFetcher, useNavigation, useParams } from "react-router";+import { useNavigation, useParams } from "react-router";import { useUser } from "~/hooks";import { useItems } from "~/stores";import { path } from "~/utils/path";@@ -110,15 +111,14 @@ const StockTransferPostModal = ({ onClose }: { onClose: () => void }) => {validateStockTransferTracking();});- const fetcher = useFetcher<{}>();- const submitted = useRef(false);- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (fetcher.state === "idle" && submitted.current) {- onClose();+ const fetcher = useAction<{}>({+ onSettled: () => {+ if (submitted.current) {+ onClose();+ }}- }, [fetcher.state]);-+ });+ const submitted = useRef(false);return (<Modalopen={true}diff --git a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitParentSelect.tsx b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitParentSelect.tsxindex 41c793779b..4a109f8a9f 100644--- a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitParentSelect.tsx+++ b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitParentSelect.tsx@@ -11,6 +11,7 @@import type { TermId } from "@carbon/content/glossary";import { useControlField, useField } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import {cn,FormControl,@@ -25,7 +26,6 @@ import {} from "@carbon/react";import { useCallback, useEffect, useMemo, useState } from "react";import { LuChevronDown, LuChevronRight, LuMapPin, LuX } from "react-icons/lu";-import { useFetcher } from "react-router";import { useLocations } from "~/components/Form/Location";import {type StorageUnitTreeRow,@@ -40,14 +40,9 @@ import { path } from "~/utils/path";// ---------------------------------------------------------------------------function useExcludedDescendantIds(rootId?: string): Set<string> {- const descendantsFetcher = useFetcher<{ data: { id: string }[] }>();-- // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher identity changes every render- useEffect(() => {- if (rootId) {- descendantsFetcher.load(path.to.api.storageUnitDescendants(rootId));- }- }, [rootId]);+ const descendantsFetcher = useLoaderQuery<{ data: { id: string }[] }>(+ rootId ? path.to.api.storageUnitDescendants(rootId) : null+ );return useMemo(() => {if (!rootId) return new Set<string>();diff --git a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsxindex 8eb49aab2e..636435d817 100644--- a/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx+++ b/apps/erp/app/modules/inventory/ui/WarehouseTransfers/WarehouseTransferLines.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {Badge,Button,@@ -31,9 +32,9 @@ import {} from "@carbon/react";import { getItemById, getItemReadableId } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";-import { useEffect, useRef } from "react";+import { useRef } from "react";import { LuArrowRight, LuCirclePlus, LuEllipsisVertical } from "react-icons/lu";-import { Link, Outlet, useFetcher, useNavigate } from "react-router";+import { Link, Outlet, useNavigate } from "react-router";import { DateTime, EmployeeAvatar, Empty, ItemThumbnail } from "~/components";import { useItems } from "~/stores";import { path } from "~/utils/path";@@ -252,15 +253,15 @@ function DeleteWarehouseTransferLine({onCancel: () => void;onSubmit: () => void;}) {- const fetcher = useFetcher<{ success: boolean }>();- const submitted = useRef(false);-- useEffect(() => {- if (submitted.current && fetcher.state === "idle") {- onSubmit();- submitted.current = false;+ const fetcher = useAction<{ success: boolean }>({+ onSettled: () => {+ if (submitted.current) {+ onSubmit();+ submitted.current = false;+ }}- }, [fetcher.state, onSubmit]);+ });+ const submitted = useRef(false);return (<Modaldiff --git a/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.test.tsx b/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.test.tsxindex 9c108efbf4..ecf2aba83e 100644--- a/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.test.tsx+++ b/apps/erp/app/modules/invoicing/ui/Payment/PaymentForm.test.tsx@@ -142,9 +142,17 @@ vi.mock("@lingui/react/macro", () => ({)})}));+// The currency list is read through the query cache (`useCurrencies`).+vi.mock("@carbon/query", () => ({+ RefreshRate: { Never: Number.POSITIVE_INFINITY },+ useLoaderQuery: () => ({+ data: { data: harness.currencies },+ isFetching: false+ })+}));vi.mock("react-router", () => ({generatePath: (path: string) => path,- useFetcher: () => ({ state: "idle", data: { data: harness.currencies } })+ useFetcher: () => ({ state: "idle" })}));vi.mock("~/components", () => ({ DocumentHeader: () => null }));vi.mock("~/components/Enumerable", () => ({ Enumerable: () => null }));diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties.tsxindex 45ca5ef51e..f5a583926a 100644--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties.tsx+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceProperties.tsx@@ -4,6 +4,7 @@import type { Json } from "@carbon/database";import { DatePicker, InputControlled, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Copy,@@ -17,7 +18,7 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useCallback, useEffect } from "react";+import { useCallback } from "react";import {LuCopy,LuInfo,@@ -60,13 +61,13 @@ const PurchaseInvoiceProperties = () => {purchaseInvoice: PurchaseInvoice;}>(path.to.purchaseInvoice(invoiceId));- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });const { company } = useUser();const exchangeRateFetcher = useFetcher<typeof exchangeRateAction>();diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceVoidModal.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceVoidModal.tsxindex 9be26b6cac..d6501ddb82 100644--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceVoidModal.tsx+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceVoidModal.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {Alert,AlertDescription,@@ -18,9 +19,9 @@ import {ModalTitle} from "@carbon/react";import { Trans } from "@lingui/react/macro";-import { useEffect, useRef } from "react";+import { useRef } from "react";import { LuTriangleAlert } from "react-icons/lu";-import { useFetcher, useNavigation, useParams } from "react-router";+import { useNavigation, useParams } from "react-router";import { path } from "~/utils/path";const PurchaseInvoiceVoidModal = ({ onClose }: { onClose: () => void }) => {@@ -28,15 +29,14 @@ const PurchaseInvoiceVoidModal = ({ onClose }: { onClose: () => void }) => {if (!invoiceId) throw new Error("invoiceId not found");const navigation = useNavigation();- const fetcher = useFetcher<{}>();- const submitted = useRef(false);-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (fetcher.state === "idle" && submitted.current) {- onClose();+ const fetcher = useAction<{}>({+ onSettled: () => {+ if (submitted.current) {+ onClose();+ }}- }, [fetcher.state]);+ });+ const submitted = useRef(false);return (<Modaldiff --git a/apps/erp/app/modules/invoicing/ui/Reimbursement/ReimbursementEditForm.test.tsx b/apps/erp/app/modules/invoicing/ui/Reimbursement/ReimbursementEditForm.test.tsxindex 79dfc0a7c8..ffb70a0efa 100644--- a/apps/erp/app/modules/invoicing/ui/Reimbursement/ReimbursementEditForm.test.tsx+++ b/apps/erp/app/modules/invoicing/ui/Reimbursement/ReimbursementEditForm.test.tsx@@ -102,14 +102,22 @@ vi.mock("@lingui/react/macro", () => ({)})}));+// The currency list is read through the query cache (`useCurrencies`).+vi.mock("@carbon/query", () => ({+ RefreshRate: { Never: Number.POSITIVE_INFINITY },+ useLoaderQuery: () => ({+ data: { data: harness.currencies },+ isFetching: false+ })+}));vi.mock("react-router", () => ({Link: ({ children }: { children?: ReactNode }) =>- createElement("a", null, children),- useFetcher: () => ({ state: "idle", data: { data: harness.currencies } })+ createElement("a", null, children)}));vi.mock("~/utils/path", () => ({path: {to: {+ api: { currencies: "/api/accounting/currencies" },authenticatedRoot: "/x",reimbursement: (id: string) => `/x/reimbursements/${id}`}diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties.tsxindex a080be5ee7..52940ecdca 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceProperties.tsx@@ -4,6 +4,7 @@import type { Json } from "@carbon/database";import { DatePicker, InputControlled, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Copy,@@ -17,7 +18,7 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useCallback, useEffect } from "react";+import { useCallback } from "react";import {LuCopy,LuInfo,@@ -55,13 +56,13 @@ const SalesInvoiceProperties = () => {salesInvoice: SalesInvoice;}>(path.to.salesInvoice(invoiceId));- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });const { company } = useUser();const exchangeRateFetcher = useFetcher<typeof exchangeRateAction>();diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceVoidModal.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceVoidModal.tsxindex dff88269a1..986b4a6997 100644--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceVoidModal.tsx+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceVoidModal.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {Alert,AlertDescription,@@ -19,9 +20,9 @@ import {} from "@carbon/react";import { Trans } from "@lingui/react/macro";-import { useEffect, useRef } from "react";+import { useRef } from "react";import { LuTriangleAlert } from "react-icons/lu";-import { useFetcher, useNavigation, useParams } from "react-router";+import { useNavigation, useParams } from "react-router";import { path } from "~/utils/path";const SalesInvoiceVoidModal = ({ onClose }: { onClose: () => void }) => {@@ -29,15 +30,14 @@ const SalesInvoiceVoidModal = ({ onClose }: { onClose: () => void }) => {if (!invoiceId) throw new Error("invoiceId not found");const navigation = useNavigation();- const fetcher = useFetcher<{}>();- const submitted = useRef(false);-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (fetcher.state === "idle" && submitted.current) {- onClose();+ const fetcher = useAction<{}>({+ onSettled: () => {+ if (submitted.current) {+ onClose();+ }}- }, [fetcher.state]);+ });+ const submitted = useRef(false);return (<Modaldiff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex 2bfb0a98a1..a56c549ffa 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -1231,130 +1231,29 @@ export async function getJobMaterialUsageForItem(return { byMaterialId, byJobId };}-/** @mcp read */+/**+ * Where a material or consumable is used.+ * @mcp read+ */export async function getMaterialUsedIn(client: SupabaseClient<Database>,itemId: string,companyId: string) {- const [- issues,- jobMaterials,- maintenanceDispatchItems,- methodMaterials,- purchaseOrderLines,- receiptLines,- quoteMaterials,- salesOrderLines,- shipmentLines,- supplierQuotes,- inspections,- jobMaterialUsage- ] = await Promise.all([- client- .from("nonConformanceItem")- .select(- "id, ...nonConformance(documentReadableId:nonConformanceId, documentId:id)"- )- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("jobMaterial")- .select("id, methodType, ...job(documentReadableId:jobId, documentId:id)")- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("maintenanceDispatchItem")- .select(- "id, ...maintenanceDispatch!maintenanceDispatchId(documentReadableId:maintenanceDispatchId, documentId:id)"- )- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("methodMaterial")- .select(- "id, methodType, ...makeMethod!makeMethodId(documentId:id, version, ...item(documentReadableId:readableIdWithRevision, documentParentId:id, itemType:type))"- )- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("purchaseOrderLine")- .select(- "id, ...purchaseOrder(documentReadableId:purchaseOrderId, documentId:id)"- )- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("receiptLine")- .select("id, ...receipt(documentReadableId:receiptId, documentId:id)")- .eq("itemId", itemId)- .eq("companyId", companyId),- client- .from("quoteMaterial")- .select(- "id, methodType, documentParentId:quoteId, documentId:quoteLineId, ...quoteLine(...item(documentReadableId:readableIdWithRevision))"- )- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("salesOrderLine")- .select(- "id, methodType, ...salesOrder(documentReadableId:salesOrderId, documentId:id)"- )- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("shipmentLine")- .select("id, ...shipment(documentReadableId:shipmentId, documentId:id)")- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("supplierQuoteLine")- .select(- "id, ...supplierQuote(documentReadableId:supplierQuoteId, documentId:id)"- )- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100),- client- .from("inspection")- .select("id, documentReadableId:inspectionId")- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- getJobMaterialUsageForItem(client, { itemId, companyId })- ]);-+ const usedIn = await readUsedIn(client, itemId, companyId);return {- issues: issues.data ?? [],- jobMaterials: jobMaterials.data ?? [],- maintenanceDispatchItems: maintenanceDispatchItems.data ?? [],- methodMaterials: methodMaterials.data ?? [],- purchaseOrderLines: purchaseOrderLines.data ?? [],- receiptLines: receiptLines.data ?? [],- quoteMaterials: quoteMaterials.data ?? [],- salesOrderLines: salesOrderLines.data ?? [],- shipmentLines: shipmentLines.data ?? [],- supplierQuotes: supplierQuotes.data ?? [],- inspections: inspections.data ?? [],- jobMaterialUsage+ issues: usedIn.issues,+ jobMaterials: usedIn.jobMaterials,+ maintenanceDispatchItems: usedIn.maintenanceDispatchItems,+ methodMaterials: usedIn.methodMaterials,+ purchaseOrderLines: usedIn.purchaseOrderLines,+ receiptLines: usedIn.receiptLines,+ quoteMaterials: usedIn.quoteMaterials,+ salesOrderLines: usedIn.salesOrderLines,+ shipmentLines: usedIn.shipmentLines,+ supplierQuotes: usedIn.supplierQuotes,+ inspections: usedIn.inspections,+ jobMaterialUsage: usedIn.jobMaterialUsage};}@@ -2113,162 +2012,97 @@ export async function getPartsList();}-/** @mcp read */-export async function getPartUsedIn(+// Every line's document exists: the foreign keys are NOT NULL.+type UsedInDocument = {+ id: string;+ documentReadableId: string;+ documentId: string;+};+type UsedInMethod = UsedInDocument & { methodType: string };++export type ItemUsedIn = {+ issues: UsedInDocument[];+ jobMaterials: UsedInMethod[];+ jobs: { id: string; documentReadableId: string }[];+ maintenanceDispatchItems: UsedInDocument[];+ methodMaterials: (UsedInMethod & {+ version: number;+ documentParentId: string;+ itemType: Database["public"]["Enums"]["itemType"];+ })[];+ purchaseOrderLines: UsedInDocument[];+ receiptLines: UsedInDocument[];+ quoteLines: UsedInMethod[];+ quoteMaterials: (UsedInMethod & { documentParentId: string })[];+ salesOrderLines: UsedInMethod[];+ shipmentLines: UsedInDocument[];+ supplierQuotes: UsedInDocument[];+ assemblyInstructions: {+ id: string;+ documentReadableId: string;+ version: number;+ }[];+ inspections: { id: string; documentReadableId: string }[];+ jobMaterialUsage: {+ byMaterialId: Record<string, number>;+ byJobId: Record<string, number>;+ };+};++const NOT_USED: ItemUsedIn = {+ issues: [],+ jobMaterials: [],+ jobs: [],+ maintenanceDispatchItems: [],+ methodMaterials: [],+ purchaseOrderLines: [],+ receiptLines: [],+ quoteLines: [],+ quoteMaterials: [],+ salesOrderLines: [],+ shipmentLines: [],+ supplierQuotes: [],+ assemblyInstructions: [],+ inspections: [],+ jobMaterialUsage: { byMaterialId: {}, byJobId: {} }+};++/**+ * Every place an item is referenced, in one request (`get_item_used_in`). It+ * was fifteen PostgREST requests fired at once: on a page load they took most+ * of the request's eight call slots from the queries the page was waiting on.+ * A failure is logged and reads as "not used", as each of the fifteen did.+ */+async function readUsedIn(client: SupabaseClient<Database>,itemId: string,companyId: string-) {- const [- issues,- jobMaterials,- jobs,- maintenanceDispatchItems,- methodMaterials,- purchaseOrderLines,- receiptLines,- quoteLines,- quoteMaterials,- salesOrderLines,- shipmentLines,- supplierQuotes,- assemblyInstructions,- inspections,- jobMaterialUsage- ] = await Promise.all([- client- .from("nonConformanceItem")- .select(- "id, ...nonConformance(documentReadableId:nonConformanceId, documentId:id)"- )- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("jobMaterial")- .select("id, methodType, ...job(documentReadableId:jobId, documentId:id)")- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("job")- .select("id, documentReadableId:jobId")- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("maintenanceDispatchItem")- .select(- "id, ...maintenanceDispatch!maintenanceDispatchId(documentReadableId:maintenanceDispatchId, documentId:id)"- )- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("methodMaterial")- .select(- "id, methodType, ...makeMethod!makeMethodId(documentId:id, version, ...item(documentReadableId:readableIdWithRevision, documentParentId:id, itemType:type))"- )- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("purchaseOrderLine")- .select(- "id, ...purchaseOrder(documentReadableId:purchaseOrderId, documentId:id)"- )- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("receiptLine")- .select("id, ...receipt(documentReadableId:receiptId, documentId:id)")- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("quoteLine")- .select(- "id, methodType, ...quote(documentReadableId:quoteId, documentId:id)"- )- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100),-- client- .from("quoteMaterial")- .select(- "id, methodType, documentParentId:quoteId, documentId:quoteLineId, ...quoteLine(...item(documentReadableId:readableIdWithRevision))"- )- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("salesOrderLine")- .select(- "id, methodType, ...salesOrder(documentReadableId:salesOrderId, documentId:id)"- )- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("shipmentLine")- .select("id, ...shipment(documentReadableId:shipmentId, documentId:id)")- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("supplierQuoteLine")- .select(- "id, ...supplierQuote(documentReadableId:supplierQuoteId, documentId:id)"- )- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100),- client- .from("assemblyInstruction")- .select("id, documentReadableId:name, version")- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- client- .from("inspection")- .select("id, documentReadableId:inspectionId")- .eq("itemId", itemId)- .eq("companyId", companyId)- .limit(100)- .order("createdAt", { ascending: false }),- getJobMaterialUsageForItem(client, { itemId, companyId })- ]);+): Promise<ItemUsedIn> {+ const { data, error } = await client.rpc("get_item_used_in", {+ item_id: itemId,+ company_id: companyId+ });+ if (error || !data) {+ logger.error("Failed to read where an item is used", {+ companyId,+ itemId,+ error+ });+ return structuredClone(NOT_USED);+ }+ return data as unknown as ItemUsedIn;+}- return {- issues: issues.data ?? [],- jobMaterials: jobMaterials.data ?? [],- jobs: jobs.data ?? [],- maintenanceDispatchItems: maintenanceDispatchItems.data ?? [],- methodMaterials: methodMaterials.data ?? [],- purchaseOrderLines: purchaseOrderLines.data ?? [],- receiptLines: receiptLines.data ?? [],- quoteLines: quoteLines.data ?? [],- quoteMaterials: quoteMaterials.data ?? [],- salesOrderLines: salesOrderLines.data ?? [],- shipmentLines: shipmentLines.data ?? [],- supplierQuotes: supplierQuotes.data ?? [],- assemblyInstructions: assemblyInstructions.data ?? [],- inspections: inspections.data ?? [],- jobMaterialUsage- };+/**+ * Where a part, tool or service is used.+ * @mcp read+ */+export async function getPartUsedIn(+ client: SupabaseClient<Database>,+ itemId: string,+ companyId: string+): Promise<ItemUsedIn> {+ return readUsedIn(client, itemId, companyId);}/** @mcp read */@@ -7880,7 +7714,14 @@ export type ChangeNoticeForItem = {createdAt: string;};-/** @mcp read */+/**+ * Every change notice that touches an item or any other revision of it: as an+ * affected item, as a component on a notice's draft method, as either side of+ * a supersession, or as the revision a notice created. One request+ * (`get_item_change_notices`); it was eight in five steps, awaited by every+ * item page.+ * @mcp read+ */export async function findChangeNoticesForItem(client: SupabaseClient<Database>,args: {@@ -7889,100 +7730,13 @@ export async function findChangeNoticesForItem(statuses?: Database["public"]["Enums"]["changeOrderStatus"][];}): Promise<{ data: ChangeNoticeForItem[]; error: { message: string } | null }> {- const { itemId, companyId, statuses } = args;-- // Resolve every revision (item row) sharing this part's readableId.- const item = await client- .from("item")- .select("readableId")- .eq("id", itemId)- .eq("companyId", companyId)- .maybeSingle();- if (item.error) return { data: [], error: item.error };- if (!item.data?.readableId) return { data: [], error: null };-- const siblings = await client- .from("item")- .select("id, changeOrderId")- .eq("readableId", item.data.readableId)- .eq("companyId", companyId);- if (siblings.error) return { data: [], error: siblings.error };- const itemIds = (siblings.data ?? []).map((s) => s.id);- if (itemIds.length === 0) return { data: [], error: null };-- // Collect referencing changeOrderIds from every relation. v2: instead of a- // staged-material mirror, "this item is a component in a CO's edited BOM" is- // found via methodMaterial rows on CO-owned draft methods (makeMethod with a- // non-null changeOrderId).- const [affected, componentMaterials, predecessors, successors] =- await Promise.all([- client- .from("changeOrderAffectedItem")- .select("changeOrderId")- .in("itemId", itemIds)- .eq("companyId", companyId),- client- .from("methodMaterial")- .select("makeMethodId")- .in("itemId", itemIds)- .eq("companyId", companyId),- client- .from("changeOrderSupersession")- .select("changeOrderId")- .in("predecessorItemId", itemIds)- .eq("companyId", companyId),- client- .from("changeOrderSupersession")- .select("changeOrderId")- .in("successorItemId", itemIds)- .eq("companyId", companyId)- ]);- if (affected.error) return { data: [], error: affected.error };- if (componentMaterials.error)- return { data: [], error: componentMaterials.error };- if (predecessors.error) return { data: [], error: predecessors.error };- if (successors.error) return { data: [], error: successors.error };-- // Resolve which of those make methods are CO-owned drafts.- const makeMethodIds = [- ...new Set(- (componentMaterials.data ?? []).map((m) => m.makeMethodId).filter(Boolean)- )- ] as string[];- const coOwnedMethods = makeMethodIds.length- ? await client- .from("makeMethod")- .select("changeOrderId")- .in("id", makeMethodIds)- .not("changeOrderId", "is", null)- .eq("companyId", companyId)- : { data: [], error: null };- if (coOwnedMethods.error) return { data: [], error: coOwnedMethods.error };-- const coIds = new Set<string>();- for (const a of affected.data ?? []) coIds.add(a.changeOrderId);- for (const m of coOwnedMethods.data ?? []) {- if (m.changeOrderId) coIds.add(m.changeOrderId);- }- for (const p of predecessors.data ?? []) coIds.add(p.changeOrderId);- for (const s of successors.data ?? []) coIds.add(s.changeOrderId);-- // Reverse link: a released revision points at the CO that created it.- for (const s of siblings.data ?? []) {- if (s.changeOrderId) coIds.add(s.changeOrderId);- }-- if (coIds.size === 0) return { data: [], error: null };-- let query = client- .from("changeOrder")- .select("id, changeOrderId, name, status, changeOrderTypeId, createdAt")- .in("id", [...coIds])- .eq("companyId", companyId);- if (statuses && statuses.length > 0) query = query.in("status", statuses);- query = query.order("createdAt", { ascending: false });-- const result = await query;+ const result = await client.rpc("get_item_change_notices", {+ item_id: args.itemId,+ company_id: args.companyId,+ ...(args.statuses && args.statuses.length > 0+ ? { statuses: args.statuses }+ : {})+ });if (result.error) return { data: [], error: result.error };return { data: result.data ?? [], error: null };}diff --git a/apps/erp/app/modules/items/ui/ChangeNotice/AffectedItemForm.tsx b/apps/erp/app/modules/items/ui/ChangeNotice/AffectedItemForm.tsxindex 55cff2598a..78d6aea227 100644--- a/apps/erp/app/modules/items/ui/ChangeNotice/AffectedItemForm.tsx+++ b/apps/erp/app/modules/items/ui/ChangeNotice/AffectedItemForm.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { ValidatedForm } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import {Alert,AlertDescription,@@ -84,19 +85,15 @@ export default function AffectedItemForm({// current (draft) make method to Active. Fetch the item's method status on// selection; the warning shows only when it has a method but none is Active.const [selectedItemId, setSelectedItemId] = useState<string>("");- const methodStatusFetcher = useFetcher<{+ const methodStatusFetcher = useLoaderQuery<{hasActiveMethod: boolean;hasAnyMethod: boolean;- }>();+ }>(+ changeType === "Version" && selectedItemId+ ? path.to.api.itemMakeMethodStatus(selectedItemId)+ : null+ );// Only re-fetch when the item/type changes; the fetcher identity is stable.- // biome-ignore lint/correctness/useExhaustiveDependencies: fetcher is stable- useEffect(() => {- if (changeType === "Version" && selectedItemId) {- methodStatusFetcher.load(- path.to.api.itemMakeMethodStatus(selectedItemId)- );- }- }, [changeType, selectedItemId]);const willActivateDraft =changeType === "Version" &&!!selectedItemId &&diff --git a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeProperties.tsx b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeProperties.tsxindex 2f9020332e..03f1a6cc44 100644--- a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeProperties.tsx+++ b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeProperties.tsx@@ -8,6 +8,7 @@ import {Select,ValidatedForm} from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Copy,@@ -22,9 +23,9 @@ import {} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import type { ReactNode } from "react";-import { useCallback, useEffect } from "react";+import { useCallback } from "react";import { LuKeySquare, LuLink } from "react-icons/lu";-import { Link, useFetcher, useNavigate, useParams } from "react-router";+import { Link, useNavigate, useParams } from "react-router";import { z } from "zod";import { Assignee, EmployeeAvatar } from "~/components";import { Enumerable } from "~/components/Enumerable";@@ -110,13 +111,13 @@ const ChangeNoticeProperties = () => {const isImplementation = changeNotice?.status === "Implementation";const canUpdate = permissions.can("update", "parts");- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });// biome-ignore lint/correctness/useExhaustiveDependencies: id is stableconst onUpdate = useCallback((field: string, value: string | null) => {diff --git a/apps/erp/app/modules/items/ui/Consumables/ConsumableProperties.tsx b/apps/erp/app/modules/items/ui/Consumables/ConsumableProperties.tsxindex 8d6a6c9639..b61d7dbdcf 100644--- a/apps/erp/app/modules/items/ui/Consumables/ConsumableProperties.tsx+++ b/apps/erp/app/modules/items/ui/Consumables/ConsumableProperties.tsx@@ -4,6 +4,7 @@import type { Json } from "@carbon/database";import { InputControlled, Select, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Badge,Button,@@ -17,9 +18,9 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { Suspense, useCallback, useEffect } from "react";+import { Suspense, useCallback } from "react";import { LuCopy, LuKeySquare, LuLink } from "react-icons/lu";-import { Await, Link, useFetcher, useParams } from "react-router";+import { Await, Link, useParams } from "react-router";import { z } from "zod";import { zfd } from "zod-form-data";import { MethodBadge, MethodIcon, TrackingTypeIcon } from "~/components";@@ -137,12 +138,13 @@ const ConsumableProperties = ({ data }: ConsumablePropertiesProps) => {// ? optimisticAssignment// : routeData?.consumableSummary?.assignee;- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);+ });// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onUpdate = useCallback((diff --git a/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx b/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsxindex 626427df53..3d4875b6c2 100644--- a/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx+++ b/apps/erp/app/modules/items/ui/Consumables/ConsumablesTable.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {Badge,Button,@@ -27,7 +28,7 @@ import {import { Trans, useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";-import { memo, useCallback, useEffect, useMemo, useState } from "react";+import { memo, useCallback, useMemo, useState } from "react";import {LuAlignJustify,LuBookMarked,@@ -43,7 +44,7 @@ import {} from "react-icons/lu";import { RxCodesandboxLogo } from "react-icons/rx";import { TbTargetArrow } from "react-icons/tb";-import { Link, useFetcher, useNavigate } from "react-router";+import { Link, useNavigate } from "react-router";import {DateTime,EmployeeAvatar,@@ -434,12 +435,13 @@ const ConsumablesTable = memo(translateTrackingType]);- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);+ });// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onBulkUpdate = useCallback((diff --git a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsxindex df9ea73f26..8888c90177 100644--- a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx+++ b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx@@ -7,6 +7,7 @@ import { useCarbon } from "@carbon/auth";import { getCompanyPrivateBucket, storage } from "@carbon/files";import { convertHeicToJpeg, isHeic } from "@carbon/files/media";import { Array as ArrayInput, Input, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import type { JSONContent } from "@carbon/react";import {Alert,@@ -19,6 +20,7 @@ import {CardContent,CardHeader,CardTitle,+ ClientOnly,Count,cn,DropdownMenu,@@ -2527,16 +2529,15 @@ function AttributesListItem({const disclosure = useDisclosure();const deleteModalDisclosure = useDisclosure();const submitted = useRef(false);- const fetcher = useFetcher<typeof editMethodOperationStepAction>();- const duplicateFetcher = useFetcher();-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (submitted.current && fetcher.state === "idle") {- disclosure.onClose();- submitted.current = false;+ const fetcher = useAction<typeof editMethodOperationStepAction>({+ onSettled: () => {+ if (submitted.current) {+ disclosure.onClose();+ submitted.current = false;+ }}- }, [fetcher.state]);+ });+ const duplicateFetcher = useFetcher();const [type, setType] = useState<OperationStep["type"]>(attribute.type);const [numericControls, setNumericControls] = useState<string[]>(() => {@@ -3331,15 +3332,14 @@ function ParametersListItem({const disclosure = useDisclosure();const deleteModalDisclosure = useDisclosure();const submitted = useRef(false);- const fetcher = useFetcher<typeof editMethodOperationParameterAction>();-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (submitted.current && fetcher.state === "idle") {- disclosure.onClose();- submitted.current = false;+ const fetcher = useAction<typeof editMethodOperationParameterAction>({+ onSettled: () => {+ if (submitted.current) {+ disclosure.onClose();+ submitted.current = false;+ }}- }, [fetcher.state]);+ });const isUpdated = updatedBy !== null;const person = isUpdated ? updatedBy : createdBy;@@ -3770,12 +3770,18 @@ function OperationPreview({{step.type ? <Badge variant="secondary">{step.type}</Badge> : null}</div><p className="text-sm font-medium">{step.name ?? t`Step`}</p>- {descriptionHtml ? (- <div- className="prose prose-sm max-w-none text-sm dark:prose-invert"- dangerouslySetInnerHTML={{ __html: descriptionHtml }}- />- ) : null}+ {/* generateHTML returns nothing on the server, so the server never+ renders this block: rendering it during hydration would not match. */}+ <ClientOnly>+ {() =>+ descriptionHtml ? (+ <div+ className="prose prose-sm max-w-none text-sm dark:prose-invert"+ dangerouslySetInnerHTML={{ __html: descriptionHtml }}+ />+ ) : null+ }+ </ClientOnly><div className="flex flex-col gap-1 border-t pt-3"><Subheading variant="heavy">@@ -3931,15 +3937,14 @@ function ToolsListItem({const disclosure = useDisclosure();const deleteModalDisclosure = useDisclosure();const submitted = useRef(false);- const fetcher = useFetcher<typeof editMethodOperationToolAction>();-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (submitted.current && fetcher.state === "idle") {- disclosure.onClose();- submitted.current = false;+ const fetcher = useAction<typeof editMethodOperationToolAction>({+ onSettled: () => {+ if (submitted.current) {+ disclosure.onClose();+ submitted.current = false;+ }}- }, [fetcher.state]);+ });const tools = useTools();const tool = tools.find((t) => t.id === toolId);diff --git a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsxindex 4ecc8d24b3..eba99dc66b 100644--- a/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx+++ b/apps/erp/app/modules/items/ui/Item/ItemPlanningChart.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useLoaderQuery } from "@carbon/query";import {Card,CardAction,@@ -20,7 +21,6 @@ import {Tooltip,TooltipContent,TooltipTrigger,- useMount,VStack} from "@carbon/react";import type { ChartConfig } from "@carbon/react/Chart";@@ -43,7 +43,6 @@ import {LuShoppingCart,LuTriangleAlert} from "react-icons/lu";-import { useFetcher } from "react-router";import {Area,Bar,@@ -165,8 +164,10 @@ export const ItemPlanningChart = ({conversionFactor?: number;}) => {const { t } = useLingui();- const forecastFetcher = useFetcher<typeof forecastLoader>();- const isFetching = forecastFetcher.state !== "idle" || !forecastFetcher.data;+ const forecastFetcher = useLoaderQuery<typeof forecastLoader>(+ path.to.api.itemForecast(itemId, locationId)+ );+ const isFetching = forecastFetcher.isFetching || !forecastFetcher.data;const [searchTerm, setSearchTerm] = useState("");const [hiddenSeries, setHiddenSeries] = useState<Set<SeriesKey>>(() => new Set()@@ -187,10 +188,6 @@ export const ItemPlanningChart = ({const numberFormatter = useNumberFormatter();- useMount(() => {- forecastFetcher.load(path.to.api.itemForecast(itemId, locationId));- });-const hasSafetyStock = typeof safetyStock === "number" && safetyStock > 0;const safetyStockValue = hasSafetyStock ? safetyStock : 0;diff --git a/apps/erp/app/modules/items/ui/Item/MakeMethodTools.tsx b/apps/erp/app/modules/items/ui/Item/MakeMethodTools.tsxindex 70b6cdc78b..92d4b3f4d1 100644--- a/apps/erp/app/modules/items/ui/Item/MakeMethodTools.tsx+++ b/apps/erp/app/modules/items/ui/Item/MakeMethodTools.tsx@@ -4,6 +4,7 @@import { useCarbon } from "@carbon/auth";import { Number, SelectControlled, Submit, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Alert,AlertTitle,@@ -56,7 +57,7 @@ import {LuStar,LuTriangleAlert} from "react-icons/lu";-import { Link, useFetcher, useParams } from "react-router";+import { Link, useParams } from "react-router";import { Hidden, Item, useConfigurableItems } from "~/components/Form";import { Confirm } from "~/components/Modals";import { usePermissions, useUser } from "~/hooks";@@ -91,7 +92,13 @@ const MakeMethodTools = ({}: MakeMethodToolsProps) => {const permissions = usePermissions();const { t } = useLingui();- const fetcher = useFetcher<{ error: string | null }>();+ const fetcher = useAction<{ error: string | null }>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error);+ }+ }+ });const params = useParams();const { methodId, makeMethodId } = params;const activeMethodId = currentMethodId ?? makeMethodId ?? methodId;@@ -101,12 +108,6 @@ const MakeMethodTools = ({const isSaveMethodLoading =fetcher.state !== "idle" && fetcher.formAction === path.to.makeMethodSave;- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error);- }- }, [fetcher.data?.error]);-const [includeInactive, setIncludeInactive] = useState<boolean>(true);const configurableItemIds = useConfigurableItems();diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialProperties.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialProperties.tsxindex acda9d4a02..80ba9259c6 100644--- a/apps/erp/app/modules/items/ui/Materials/MaterialProperties.tsx+++ b/apps/erp/app/modules/items/ui/Materials/MaterialProperties.tsx@@ -4,6 +4,7 @@import type { Json } from "@carbon/database";import { InputControlled, Select, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Alert,AlertTitle,@@ -28,7 +29,7 @@ import {import { Trans, useLingui } from "@lingui/react/macro";import { Suspense, useCallback, useEffect, useState } from "react";import { LuCopy, LuKeySquare, LuLink, LuTriangleAlert } from "react-icons/lu";-import { Await, Link, useFetcher, useParams } from "react-router";+import { Await, Link, useParams } from "react-router";import { z } from "zod";import { zfd } from "zod-form-data";import {@@ -159,13 +160,13 @@ const MaterialProperties = ({ data }: MaterialPropertiesProps) => {// ? optimisticAssignment// : routeData?.materialSummary?.assignee;- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });const confirmDisclosure = useDisclosure();const [materialPropertyUpdate, setMaterialPropertyUpdate] = useState<{field:diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsxindex 18aa3993a7..9fd8c8e3c1 100644--- a/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx+++ b/apps/erp/app/modules/items/ui/Materials/MaterialsTable.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {Badge,Button,@@ -30,7 +31,7 @@ import {import { Trans, useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";-import { memo, useCallback, useEffect, useMemo, useState } from "react";+import { memo, useCallback, useMemo, useState } from "react";import {LuAlignJustify,LuBookMarked,@@ -54,7 +55,7 @@ import {} from "react-icons/lu";import { RxCodesandboxLogo } from "react-icons/rx";import { TbTargetArrow } from "react-icons/tb";-import { Link, useFetcher, useNavigate } from "react-router";+import { Link, useNavigate } from "react-router";import {DateTime,EmployeeAvatar,@@ -558,13 +559,13 @@ const MaterialsTable = memo(({ data, tags, count }: MaterialsTableProps) => {translateTrackingType]);- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onBulkUpdate = useCallback((diff --git a/apps/erp/app/modules/items/ui/Parts/ConfigurationParameters.tsx b/apps/erp/app/modules/items/ui/Parts/ConfigurationParameters.tsxindex d1d4624e29..495783bf5b 100644--- a/apps/erp/app/modules/items/ui/Parts/ConfigurationParameters.tsx+++ b/apps/erp/app/modules/items/ui/Parts/ConfigurationParameters.tsx@@ -11,6 +11,7 @@ import {Submit,ValidatedForm} from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Card,@@ -62,7 +63,7 @@ import { SortableContext, useSortable } from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";import { Trans, useLingui } from "@lingui/react/macro";import { cva } from "class-variance-authority";-import { useEffect, useRef, useState } from "react";+import { useRef, useState } from "react";import { createPortal, flushSync } from "react-dom";import {LuCirclePlus,@@ -71,7 +72,7 @@ import {LuGripVertical,LuKeySquare} from "react-icons/lu";-import { useFetcher, useFetchers, useParams, useSubmit } from "react-router";+import { useFetchers, useParams, useSubmit } from "react-router";import { DateTime, EmployeeAvatar } from "~/components";import { ConfiguratorDataTypeIcon } from "~/components/Configurator/Icons";import { Enumerable } from "~/components/Enumerable";@@ -116,13 +117,13 @@ export default function ConfigurationParametersForm({const materialShapeOptions = useShape();const submit = useSubmit();- const fetcher = useFetcher<typeof configurationParameterAction>();-- useEffect(() => {- if (fetcher.data?.success === false) {- toast.error(t`Failed to update configuration parameter`);+ const fetcher = useAction<typeof configurationParameterAction>({+ onError: (data) => {+ if (data?.success === false) {+ toast.error(t`Failed to update configuration parameter`);+ }}- }, [fetcher.data, t]);+ });const groupDisclosure = useDisclosure();const deleteGroupDisclosure = useDisclosure();@@ -829,7 +830,14 @@ function ConfigurableParameter({const disclosure = useDisclosure();const deleteParameterDisclosure = useDisclosure();const submitted = useRef(false);- const fetcher = useFetcher<typeof configurationParameterAction>();+ const fetcher = useAction<typeof configurationParameterAction>({+ onSettled: () => {+ if (submitted.current) {+ disclosure.onClose();+ submitted.current = false;+ }+ }+ });const {attributes,@@ -854,13 +862,6 @@ function ConfigurableParameter({transition};- useEffect(() => {- if (submitted.current && fetcher.state === "idle") {- disclosure.onClose();- submitted.current = false;- }- }, [disclosure, fetcher.state]);-const isUpdated = parameter.updatedBy !== null;const person = isUpdated ? parameter.updatedBy : parameter.createdBy;const date = parameter.updatedAt ?? parameter.createdAt;diff --git a/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx b/apps/erp/app/modules/items/ui/Parts/PartProperties.tsxindex b51092d2c9..c179fb4e64 100644--- a/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx+++ b/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx@@ -4,6 +4,7 @@import type { Json } from "@carbon/database";import { InputControlled, Select, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Badge,Button,@@ -19,7 +20,7 @@ import {} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import type { PostgrestResponse } from "@supabase/supabase-js";-import { Suspense, useCallback, useEffect } from "react";+import { Suspense, useCallback } from "react";import {LuCopy,LuExternalLink,@@ -27,7 +28,7 @@ import {LuLink,LuMove3D} from "react-icons/lu";-import { Await, Link, useFetcher, useParams } from "react-router";+import { Await, Link, useParams } from "react-router";import { z } from "zod";import { zfd } from "zod-form-data";import { MethodBadge, MethodIcon, TrackingTypeIcon } from "~/components";@@ -180,13 +181,13 @@ const PartProperties = ({// ? optimisticAssignment// : routeData?.partSummary?.assignee;- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onUpdate = useCallback((diff --git a/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx b/apps/erp/app/modules/items/ui/Parts/PartsTable.tsxindex 87afa36a1e..e01433ead5 100644--- a/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx+++ b/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {Badge,Button,@@ -30,7 +31,7 @@ import {import { Trans, useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";-import { memo, useCallback, useEffect, useMemo, useState } from "react";+import { memo, useCallback, useMemo, useState } from "react";import {LuAlignJustify,LuBookMarked,@@ -48,7 +49,7 @@ import {} from "react-icons/lu";import { RxCodesandboxLogo } from "react-icons/rx";import { TbTargetArrow } from "react-icons/tb";-import { Link, useFetcher, useNavigate } from "react-router";+import { Link, useNavigate } from "react-router";import {DateTime,EmployeeAvatar,@@ -477,13 +478,13 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {translateTrackingType]);- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onBulkUpdate = useCallback((diff --git a/apps/erp/app/modules/items/ui/Services/ServiceProperties.tsx b/apps/erp/app/modules/items/ui/Services/ServiceProperties.tsxindex 936f7e8443..8ddac116af 100644--- a/apps/erp/app/modules/items/ui/Services/ServiceProperties.tsx+++ b/apps/erp/app/modules/items/ui/Services/ServiceProperties.tsx@@ -4,6 +4,7 @@import type { Json } from "@carbon/database";import { InputControlled, Select, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Badge,Button,@@ -18,9 +19,9 @@ import {} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import type { PostgrestResponse } from "@supabase/supabase-js";-import { Suspense, useCallback, useEffect } from "react";+import { Suspense, useCallback } from "react";import { LuCopy, LuKeySquare, LuLink } from "react-icons/lu";-import { Await, Link, useFetcher, useParams } from "react-router";+import { Await, Link, useParams } from "react-router";import { z } from "zod";import { zfd } from "zod-form-data";import { MethodBadge, MethodIcon } from "~/components";@@ -97,13 +98,13 @@ const ServiceProperties = ({ data }: ServicePropertiesProps) => {const supplierParts = routeData?.supplierParts ?? [];- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onUpdate = useCallback((diff --git a/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx b/apps/erp/app/modules/items/ui/Services/ServicesTable.tsxindex 1f2dab2595..bd86db2762 100644--- a/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx+++ b/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {Badge,Button,@@ -30,7 +31,7 @@ import {import { Trans, useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";-import { memo, useCallback, useEffect, useMemo, useState } from "react";+import { memo, useCallback, useMemo, useState } from "react";import {LuAlignJustify,LuBookMarked,@@ -46,7 +47,7 @@ import {LuUser} from "react-icons/lu";import { RxCodesandboxLogo } from "react-icons/rx";-import { Link, useFetcher, useNavigate } from "react-router";+import { Link, useNavigate } from "react-router";import {DateTime,EmployeeAvatar,@@ -399,13 +400,13 @@ const ServicesTable = memo(({ data, tags, count }: ServicesTableProps) => {translateReplenishment]);- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onBulkUpdate = useCallback((diff --git a/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx b/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsxindex 54505b8bde..5d1620d811 100644--- a/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx+++ b/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx@@ -4,6 +4,7 @@import type { Json } from "@carbon/database";import { InputControlled, Select, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Badge,Button,@@ -18,9 +19,9 @@ import {} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import type { PostgrestResponse } from "@supabase/supabase-js";-import { Suspense, useCallback, useEffect } from "react";+import { Suspense, useCallback } from "react";import { LuCopy, LuKeySquare, LuLink } from "react-icons/lu";-import { Await, Link, useFetcher, useParams } from "react-router";+import { Await, Link, useParams } from "react-router";import { z } from "zod";import { zfd } from "zod-form-data";import {@@ -142,13 +143,13 @@ const ToolProperties = ({ data }: ToolPropertiesProps) => {// ? optimisticAssignment// : routeData?.toolSummary?.assignee;- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onUpdate = useCallback((diff --git a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsxindex 4638bf3f6a..5fab082a2c 100644--- a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx+++ b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {Badge,Button,@@ -30,7 +31,7 @@ import {import { Trans, useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";-import { memo, useCallback, useEffect, useMemo, useState } from "react";+import { memo, useCallback, useMemo, useState } from "react";import {LuAlignJustify,LuBookMarked,@@ -48,7 +49,7 @@ import {} from "react-icons/lu";import { RxCodesandboxLogo } from "react-icons/rx";import { TbTargetArrow } from "react-icons/tb";-import { Link, useFetcher, useNavigate } from "react-router";+import { Link, useNavigate } from "react-router";import {DateTime,EmployeeAvatar,@@ -474,13 +475,13 @@ const ToolsTable = memo(({ data, tags, count }: ToolsTableProps) => {translateTrackingType]);- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onBulkUpdate = useCallback((diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 689067b087..5b715078b4 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -1459,20 +1459,24 @@ export async function getJobMaterialShortfallByItem(.filter((id) => !onHandByItem.has(id))));- for (const successorId of successorIds) {- const quantities = await client.rpc("get_inventory_quantities", {- location_id: locationId,- company_id: companyId,- item_id: successorId- });- const row = quantities.data?.[0];+ const successorQuantities = await async.map(+ successorIds,+ async (successorId) =>+ await client.rpc("get_inventory_quantities", {+ location_id: locationId,+ company_id: companyId,+ item_id: successorId+ })+ );+ successorIds.forEach((successorId, index) => {+ const row = successorQuantities[index]?.data?.[0];onHandByItem.set(successorId, Number(row?.quantityOnHand ?? 0));incomingByItem.set(successorId,Number(row?.quantityOnPurchaseOrder ?? 0) +Number(row?.quantityOnProductionOrder ?? 0));- }+ });// Remaining demand for those items across every active job at this location.const { data } = await clientdiff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsxindex 2eee962275..b36042847f 100644--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyBomTree.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {Badge,Button,@@ -1280,14 +1281,14 @@ function CreateUnitModal({onCreated: () => void;}) {const { t } = useLingui();- const fetcher = useFetcher<{ success: boolean }>();- const [name, setName] = useState("");-- useEffect(() => {- if (fetcher.state === "idle" && fetcher.data?.success) {- onCreated();+ const fetcher = useAction<{ success: boolean }>({+ onSuccess: (data) => {+ if (data?.success) {+ onCreated();+ }}- }, [fetcher.state, fetcher.data, onCreated]);+ });+ const [name, setName] = useState("");const onSubmit = () => {if (!name.trim()) return;@@ -1372,18 +1373,18 @@ function EditUnitModal({onUpdated: () => void;}) {const { t } = useLingui();- const fetcher = useFetcher<{ success: boolean }>();+ const fetcher = useAction<{ success: boolean }>({+ onSuccess: (data) => {+ if (data?.success) {+ onUpdated();+ }+ }+ });const [name, setName] = useState(unit.name);const [memberIds, setMemberIds] = useState<string[]>(unit.componentNodeIds ?? []);- useEffect(() => {- if (fetcher.state === "idle" && fetcher.data?.success) {- onUpdated();- }- }, [fetcher.state, fetcher.data, onUpdated]);-const memberSet = useMemo(() => new Set(memberIds), [memberIds]);// Distinct components in the unit, so removal is per component type ("drop this cap"),// not per individual instance.diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepMaterials.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepMaterials.tsxindex e1f011b335..d8ad2737f2 100644--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepMaterials.tsx+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepMaterials.tsx@@ -3,8 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { Combobox, Hidden, Number, Submit, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import { Badge, HStack, IconButton, Subheading, VStack } from "@carbon/react";-import { useEffect, useMemo, useState } from "react";+import { useMemo, useState } from "react";import { LuCirclePlus, LuTrash } from "react-icons/lu";import { useFetcher } from "react-router";import { Empty } from "~/components";@@ -35,18 +36,18 @@ export default function AssemblyStepMaterials({isDisabled}: AssemblyStepMaterialsProps) {const permissions = usePermissions();- const fetcher = useFetcher<{ success: boolean }>();+ const fetcher = useAction<{ success: boolean }>({+ onSuccess: (data) => {+ if (data?.success) {+ setFormKey((key) => key + 1);+ setSelectedItemId(null);+ }+ }+ });// Remount the form after a successful add so the fields clearconst [formKey, setFormKey] = useState(0);const [selectedItemId, setSelectedItemId] = useState<string | null>(null);- useEffect(() => {- if (fetcher.state === "idle" && fetcher.data?.success) {- setFormKey((key) => key + 1);- setSelectedItemId(null);- }- }, [fetcher.state, fetcher.data]);-// One option per distinct BOM item, excluding items already on the stepconst options = useMemo(() => {const usedItemIds = new Set(materials.map((material) => material.itemId));diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepTools.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepTools.tsxindex 4d5d6fe33f..d306607a89 100644--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepTools.tsx+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepTools.tsx@@ -3,8 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { Hidden, Number, Submit, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import { Badge, HStack, IconButton, Subheading, VStack } from "@carbon/react";-import { useEffect, useState } from "react";+import { useState } from "react";import { LuCirclePlus, LuTrash } from "react-icons/lu";import { useFetcher } from "react-router";import { Tool } from "~/components/Form";@@ -31,16 +32,16 @@ export default function AssemblyStepTools({isDisabled}: AssemblyStepToolsProps) {const permissions = usePermissions();- const fetcher = useFetcher<{ success: boolean }>();+ const fetcher = useAction<{ success: boolean }>({+ onSuccess: (data) => {+ if (data?.success) {+ setFormKey((key) => key + 1);+ }+ }+ });// Remount the form after a successful add so the fields clearconst [formKey, setFormKey] = useState(0);- useEffect(() => {- if (fetcher.state === "idle" && fetcher.data?.success) {- setFormKey((key) => key + 1);- }- }, [fetcher.state, fetcher.data]);-return (<VStack spacing={2} className="w-full"><Subheading as="h4" variant="light">diff --git a/apps/erp/app/modules/production/ui/Batches/BatchBuilder.tsx b/apps/erp/app/modules/production/ui/Batches/BatchBuilder.tsxindex 1d3eac6748..dd4852fc6e 100644--- a/apps/erp/app/modules/production/ui/Batches/BatchBuilder.tsx+++ b/apps/erp/app/modules/production/ui/Batches/BatchBuilder.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useLoaderQuery } from "@carbon/query";import {Badge,Button,@@ -411,22 +412,20 @@ export function BatchBuilder({processes]);- const candidatesFetcher = useFetcher<CandidatesResponse>();const submitFetcher = useFetcher<{success?: boolean;message?: string;batchId?: string | null;}>();- // Load candidates whenever the scope is complete. Only the scope drives the- // fetch — the fetcher's `.load` identity is unstable and must not be a dep.- // biome-ignore lint/correctness/useExhaustiveDependencies: intentional — scope-only trigger- useEffect(() => {- if (!locationId || !processId) return;- candidatesFetcher.load(- path.to.api.batchableOperations(locationId, processId)- );- }, [locationId, processId]);+ // Candidates for the scope, once it is complete. `staleTime: 0`: operations+ // move on the shop floor, so each scope change asks again.+ const candidatesFetcher = useLoaderQuery<CandidatesResponse>(+ locationId && processId+ ? path.to.api.batchableOperations(locationId, processId)+ : null,+ { staleTime: 0 }+ );// A scope change invalidates the current selection and filters.const resetComposition = useCallback(() => {@@ -827,7 +826,7 @@ export function BatchBuilder({const isSubmitting = submitFetcher.state !== "idle";// Output lots are planned here; a batch never reaches the floor without them.const lotPlanIncomplete = outputLotsProblem(selected, outputLots) !== null;- const isLoading = candidatesFetcher.state !== "idle";+ const isLoading = candidatesFetcher.isFetching;const locationOptions = useMemo(() =>diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsxindex 08db44bf93..e07c4e0d21 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx@@ -9,6 +9,7 @@ import { getCompanyPrivateBucket, storage } from "@carbon/files";import { convertHeicToJpeg, isHeic } from "@carbon/files/media";import { Array as ArrayInput, Input, ValidatedForm } from "@carbon/form";import { getLogger } from "@carbon/logger";+import { useAction, useChangedRows } from "@carbon/query";import type { JSONContent } from "@carbon/react";import {Alert,@@ -52,7 +53,6 @@ import {useDebounce,useDisclosure,useMount,- useRealtimeChannel,VStack} from "@carbon/react";import { Editor } from "@carbon/react/Editor";@@ -741,76 +741,27 @@ const JobBillOfProcess = ({const [hasMore, setHasMore] = useState(true);const addOperationButtonRef = useRef<HTMLButtonElement>(null);- useRealtimeChannel({- topic: `production-events:${selectedItemId}`,+ useChangedRows<Database["public"]["Tables"]["productionEvent"]["Row"]>({+ companyId,+ table: "productionEvent",enabled: !!selectedItemId && !temporaryItems[selectedItemId],- setup(channel) {- return channel.on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "productionEvent",- filter: `jobOperationId=eq.${selectedItemId}`- },- (payload) => {- switch (payload.eventType) {- case "INSERT":- const { new: inserted } = payload;- setProductionEvents((prevEvents) => [- ...prevEvents,- inserted as Database["public"]["Tables"]["productionEvent"]["Row"]- ]);- break;- case "UPDATE":- const { new: updated } = payload;- setProductionEvents((prevEvents) =>- prevEvents.map((event) =>- event.id === updated.id- ? (updated as Database["public"]["Tables"]["productionEvent"]["Row"])- : event- )- );- break;- case "DELETE":- const { old: deleted } = payload;- setProductionEvents((prevEvents) =>- prevEvents.filter((event) => event.id !== deleted.id)- );- break;- default:- break;- }- }- );- }- });-- // Phase 3: keep the live job's BOP steps fresh without closing the panel. When steps are- // added/edited/reordered for the open operation, or an operator records a step on the shop- // floor (jobOperationStepRecord), revalidate so the loader re-serves the latest steps.- const revalidator = useRevalidator();- useRealtimeChannel({- topic: `bop-steps:${selectedItemId}`,- enabled: !!selectedItemId && !temporaryItems[selectedItemId],- setup(channel) {- const refresh = () => revalidator.revalidate();- return channel- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "jobOperationStep",- filter: `operationId=eq.${selectedItemId}`- },- refresh- )- .on(- "postgres_changes",- { event: "*", schema: "public", table: "jobOperationStepRecord" },- refresh+ onChange: ({ op, ids, rows }) => {+ if (op === "DELETE") {+ setProductionEvents((prevEvents) =>+ prevEvents.filter((event) => !ids.includes(event.id)));+ return;+ }+ const mine = rows.filter((row) => row.jobOperationId === selectedItemId);+ setProductionEvents((prevEvents) => {+ let next = prevEvents;+ for (const row of mine) {+ next = next.some((event) => event.id === row.id)+ ? next.map((event) => (event.id === row.id ? row : event))+ : [...next, row];+ }+ return next;+ });}});@@ -2120,7 +2071,14 @@ function StepsListItem({const disclosure = useDisclosure();const deleteModalDisclosure = useDisclosure();const submitted = useRef(false);- const fetcher = useFetcher<typeof editJobOperationStepAction>();+ const fetcher = useAction<typeof editJobOperationStepAction>({+ onSettled: () => {+ if (submitted.current) {+ disclosure.onClose();+ submitted.current = false;+ }+ }+ });const duplicateStepFetcher = useFetcher();const { t } = useLingui();const [description, setDescription] = useState<JSONContent>(() => {@@ -2137,14 +2095,6 @@ function StepsListItem({}});- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (submitted.current && fetcher.state === "idle") {- disclosure.onClose();- submitted.current = false;- }- }, [fetcher.state]);-const [type, setType] = useState<OperationStep["type"]>(attribute.type);const [numericControls, setNumericControls] = useState<string[]>(() => {const controls = [];@@ -2666,16 +2616,15 @@ function ParametersListItem({const disclosure = useDisclosure();const deleteModalDisclosure = useDisclosure();const submitted = useRef(false);- const fetcher = useFetcher<typeof editJobOperationParameterAction>();- const { t } = useLingui();-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (submitted.current && fetcher.state === "idle") {- disclosure.onClose();- submitted.current = false;+ const fetcher = useAction<typeof editJobOperationParameterAction>({+ onSettled: () => {+ if (submitted.current) {+ disclosure.onClose();+ submitted.current = false;+ }}- }, [fetcher.state]);+ });+ const { t } = useLingui();const isUpdated = updatedBy !== null;const person = isUpdated ? updatedBy : createdBy;@@ -3758,13 +3707,13 @@ function ProcedureSyncModal({procedureId: string;onClose: () => void;}) {- const fetcher = useFetcher<{ success: boolean }>();- useEffect(() => {- if (fetcher.data?.success) {- onClose();+ const fetcher = useAction<{ success: boolean }>({+ onSuccess: (data) => {+ if (data?.success) {+ onClose();+ }}- }, [fetcher.data?.success, onClose]);-+ });return (<Modalopen@@ -3831,13 +3780,13 @@ function AssemblyStepsSyncModal({assemblyInstructionId: string;onClose: () => void;}) {- const fetcher = useFetcher<{ success: boolean }>();- useEffect(() => {- if (fetcher.data?.success) {- onClose();+ const fetcher = useAction<{ success: boolean }>({+ onSuccess: (data) => {+ if (data?.success) {+ onClose();+ }}- }, [fetcher.data?.success, onClose]);-+ });return (<Modalopen@@ -3954,16 +3903,15 @@ function ToolsListItem({const disclosure = useDisclosure();const deleteModalDisclosure = useDisclosure();const submitted = useRef(false);- const fetcher = useFetcher<typeof editJobOperationToolAction>();- const { t } = useLingui();-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (submitted.current && fetcher.state === "idle") {- disclosure.onClose();- submitted.current = false;+ const fetcher = useAction<typeof editJobOperationToolAction>({+ onSettled: () => {+ if (submitted.current) {+ disclosure.onClose();+ submitted.current = false;+ }}- }, [fetcher.state]);+ });+ const { t } = useLingui();const tools = useTools();const tool = tools.find((t) => t.id === toolId);@@ -4217,26 +4165,17 @@ function OperationChat({ jobOperationId }: { jobOperationId: string }) {fetchChat();});- useRealtimeChannel({- topic: `job-operation-notes-${jobOperationId}`,- setup(channel) {- return channel.on(- "postgres_changes",- {- event: "INSERT",- schema: "public",- table: "jobOperationNote",- filter: `jobOperationId=eq.${jobOperationId}`- },- (payload) => {- setMessages((prev) => {- if (prev.some((m) => m.id === payload.new.id)) {- return prev;- }- return [...prev, payload.new as Message];- });- }- );+ useChangedRows<Message & { jobOperationId: string }>({+ companyId: user.company.id,+ table: "jobOperationNote",+ onResync: fetchChat,+ onChange: ({ op, rows }) => {+ if (op !== "INSERT") return;+ const notes = rows.filter((row) => row.jobOperationId === jobOperationId);+ setMessages((prev) => [+ ...prev,+ ...notes.filter((note) => !prev.some((m) => m.id === note.id))+ ]);}});diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsxindex 1617dcd52c..00181af12d 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx@@ -4,6 +4,7 @@import { useCarbon } from "@carbon/auth";import { ValidatedForm } from "@carbon/form";+import { useAction, useLoaderQuery } from "@carbon/query";import {Alert,AlertTitle,@@ -47,7 +48,7 @@ import {LuTriangleAlert} from "react-icons/lu";import { RiProgress4Line } from "react-icons/ri";-import { useFetcher, useLocation, useParams } from "react-router";+import { useLocation, useParams } from "react-router";import { PrintButton } from "~/components";import { ConfiguratorModal } from "~/components/Configurator/ConfiguratorForm";import {@@ -79,7 +80,13 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {const { jobId, methodId } = useParams();if (!jobId) throw new Error("jobId not found");- const fetcher = useFetcher<{ error: string | null }>();+ const fetcher = useAction<{ error: string | null }>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error);+ }+ }+ });const routeData = useRouteData<{job: Job;method: Tree<JobMethod>;@@ -119,12 +126,6 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {const isSaveMethodLoading =fetcher.state !== "idle" && fetcher.formAction === path.to.jobMethodSave;- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error);- }- }, [fetcher.data?.error]);-const [includeInactive, setIncludeInactive] = useState<boolean | "indeterminate">(true);@@ -730,13 +731,9 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {function CompletedJobMethodForm({ currentJobId }: { currentJobId: string }) {const { t } = useLingui();- const jobsFetcher = useFetcher<{+ const jobsFetcher = useLoaderQuery<{data: { id: string; jobId: string }[] | null;- }>();-- useMount(() => {- jobsFetcher.load(`${path.to.api.jobs}?status=Completed&status=Closed`);- });+ }>(`${path.to.api.jobs}?status=Completed&status=Closed`);const jobOptions = useMemo(() =>diff --git a/apps/erp/app/modules/production/ui/Jobs/JobProperties.tsx b/apps/erp/app/modules/production/ui/Jobs/JobProperties.tsxindex e8379aa78f..5a5fda4333 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobProperties.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobProperties.tsx@@ -10,6 +10,7 @@ import {Select,ValidatedForm} from "@carbon/form";+import { useAction } from "@carbon/query";import {Badge,Button,@@ -32,10 +33,10 @@ import {} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import type { PostgrestResponse } from "@supabase/supabase-js";-import { Suspense, useCallback, useEffect, useState } from "react";+import { Suspense, useCallback, useState } from "react";import { LuCopy, LuKeySquare, LuLink, LuUnlink2 } from "react-icons/lu";import { RiProgress8Line } from "react-icons/ri";-import { Await, useFetcher, useParams } from "react-router";+import { Await, useParams } from "react-router";import { z } from "zod";import { zfd } from "zod-form-data";import {@@ -81,13 +82,13 @@ const JobProperties = () => {const unlinkDisclosure = useDisclosure();- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });const [type, setType] = useState<MethodItemType>((routeData?.job?.itemType ?? "Part") as MethodItemType);diff --git a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsxindex 39d23dbc7c..2a61e51579 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { useCarbon } from "@carbon/auth";+import { useAction } from "@carbon/query";import {Badge,BarProgress,@@ -44,7 +45,7 @@ import {LuUser,LuUsers} from "react-icons/lu";-import { useFetcher, useNavigate } from "react-router";+import { useNavigate } from "react-router";import {CustomerAvatar,DateTime,@@ -656,13 +657,13 @@ const JobsTable = memo((props: JobsTableProps) => {return [...defaultColumns, ...customColumns];}, [params, customColumns, trackedEntities, batchesByJobId]);- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onBulkUpdate = useCallback((selectedRows: typeof data, field: "delete", value?: string) => {diff --git a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsxindex 728cac4f59..8c34b780f1 100644--- a/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx+++ b/apps/erp/app/modules/production/ui/Planning/ProductionPlanningTable.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {Button,Combobox,@@ -89,16 +90,15 @@ const ProductionPlanningTable = ({const locations = useLocations();const unitOfMeasures = useUnitOfMeasure();- const mrpFetcher = useFetcher<typeof mrpAction>();- const bulkUpdateFetcher = useFetcher<typeof bulkUpdateAction>();-- // Clear cache when MRP completes- useEffect(() => {- if (mrpFetcher.state === "idle" && mrpFetcher.data) {- clearOrdersCache();- setOrdersMap({}); // Reset local state to force recalculation+ const mrpFetcher = useAction<typeof mrpAction>({+ onSettled: (data) => {+ if (data) {+ clearOrdersCache();+ setOrdersMap({}); // Reset local state to force recalculation+ }}- }, [mrpFetcher.state, mrpFetcher.data]);+ });+ const bulkUpdateFetcher = useFetcher<typeof bulkUpdateAction>();// Clear local state when data changes (e.g., filters, search)// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationdiff --git a/apps/erp/app/modules/production/ui/Procedures/ProcedureProperties.tsx b/apps/erp/app/modules/production/ui/Procedures/ProcedureProperties.tsxindex 2d09da932b..c3ed08a2ea 100644--- a/apps/erp/app/modules/production/ui/Procedures/ProcedureProperties.tsx+++ b/apps/erp/app/modules/production/ui/Procedures/ProcedureProperties.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { Select, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Copy,@@ -15,9 +16,9 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useCallback, useEffect } from "react";+import { useCallback } from "react";import { LuCopy, LuKeySquare, LuLink } from "react-icons/lu";-import { useFetcher, useParams } from "react-router";+import { useParams } from "react-router";import { z } from "zod";import Assignee, { useOptimisticAssignment } from "~/components/Assignee";import { Process, Tags } from "~/components/Form";@@ -40,13 +41,13 @@ const ProcedureProperties = () => {tags: { name: string }[];}>(path.to.procedure(id));- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onUpdate = useCallback((field: "name" | "processId" | "status", value: string | null) => {diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex 7c372ab12a..cd0af41075 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -9,6 +9,7 @@ import { storage } from "@carbon/files";import { getLogger } from "@carbon/logger";import { serverFns } from "@carbon/server-functions";import {+ async,datetime,EPSILON,getPurchaseOrderStatus,@@ -393,23 +394,25 @@ export async function getPurchaseOrder(/** @mcp update */export async function finalizeSupplierQuote(client: SupabaseClient<Database>,- supplierQuoteId: string,- userId: string+ db: Kysely<KyselyDatabase>,+ payload: { supplierQuoteId: string; companyId: string; userId: string }) {- const quoteUpdate = await client- .from("supplierQuote")- .update({- status: "Active",- updatedAt: datetime.timestamp(),- updatedBy: userId- })- .eq("id", supplierQuoteId);-- if (quoteUpdate.error) {- return quoteUpdate;- }+ const { companyId, userId, ...input } = payload;+ return serverFns+ .as({ client, db, companyId, userId })+ .invoke("finalize-supplier-quote", input);+}- return { data: null, error: null };+/** @mcp update */+export async function finalizePurchasingRfq(+ client: SupabaseClient<Database>,+ db: Kysely<KyselyDatabase>,+ payload: { rfqId: string; companyId: string; userId: string }+) {+ const { companyId, userId, ...input } = payload;+ return serverFns+ .as({ client, db, companyId, userId })+ .invoke("finalize-purchasing-rfq", input);}/** @mcp read */@@ -731,6 +734,41 @@ export async function getSupplierInteractionLineDocuments(}));}+/**+ * Signed links to every document attached to the given lines, for an email's+ * attachments. Lines are listed and signed together, in the lines' order.+ */+export async function getSupplierInteractionLineAttachments(+ client: SupabaseClient<Database>,+ companyId: string,+ lineIds: string[]+): Promise<{ filename: string; path: string }[]> {+ const perLine = await async.map(lineIds, async (lineId) => {+ const docs = await getSupplierInteractionLineDocuments(+ client,+ companyId,+ lineId+ );+ return async.map(docs, async (doc) => {+ const storagePath = `${companyId}/supplier-interaction-line/${lineId}/${doc.name}`;+ const { data, error } = await storage(client)+ .company(companyId)+ .createSignedUrl(storagePath, 3600);+ if (!data) {+ logger.error("Failed to create signed URL for attachment", {+ storagePath,+ error+ });+ return null;+ }+ return { filename: doc.name, path: data.signedUrl };+ });+ });+ return perLine+ .flat()+ .flatMap((attachment) => (attachment ? [attachment] : []));+}+/** @mcp read */export async function getSupplierLocations(client: SupabaseClient<Database>,diff --git a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsxindex d767a91431..febee22b0a 100644--- a/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/Planning/PurchasingPlanningTable.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {Button,Combobox,@@ -94,7 +95,14 @@ const PlanningTable = memo(const unitOfMeasures = useUnitOfMeasure();const [suppliers] = useSuppliers();- const mrpFetcher = useFetcher<typeof mrpAction>();+ const mrpFetcher = useAction<typeof mrpAction>({+ onSettled: (data) => {+ if (data) {+ clearOrdersCache();+ setOrdersMap({}); // Reset local state to force recalculation+ }+ }+ });const bulkUpdateFetcher = useFetcher<typeof bulkUpdateAction>();// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration@@ -207,14 +215,6 @@ const PlanningTable = memo(Map<string, PlannedOrder[]>>(new Map());- // Clear cache when MRP completes- useEffect(() => {- if (mrpFetcher.state === "idle" && mrpFetcher.data) {- clearOrdersCache();- setOrdersMap({}); // Reset local state to force recalculation- }- }, [mrpFetcher.state, mrpFetcher.data]);-// Clear local state when data changes (e.g., filters, search)// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsxindex cee5575520..ce2814247f 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderLineForm.tsx@@ -9,6 +9,7 @@ import {InputControlled,ValidatedForm} from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import {Badge,Button,@@ -39,7 +40,7 @@ import { getItemReadableId, INPUT_FORMAT } from "@carbon/utils";import { getLocalTimeZone, today } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";import type { PostgrestResponse } from "@supabase/supabase-js";-import { useEffect, useMemo, useState } from "react";+import { useMemo, useState } from "react";import { LuBox, LuChevronRight, LuLandmark, LuReceipt } from "react-icons/lu";import { useFetcher, useParams } from "react-router";import type { z } from "zod";@@ -1097,12 +1098,9 @@ function JobOperationSelect(initialValues: { jobId?: string }) {initialValues.jobId ?? null);- const jobsFetcher =- useFetcher<PostgrestResponse<{ id: string; jobId: string }>>();- useMount(() => {- jobsFetcher.load(path.to.api.jobs);- });-+ const jobsFetcher = useLoaderQuery<+ PostgrestResponse<{ id: string; jobId: string }>+ >(path.to.api.jobs);const jobOptions = useMemo(() =>jobsFetcher.data?.data@@ -1114,15 +1112,9 @@ function JobOperationSelect(initialValues: { jobId?: string }) {[jobsFetcher.data]);- const jobOperationFetcher =- useFetcher<PostgrestResponse<{ id: string; description: string }>>();- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (jobId) {- jobOperationFetcher.load(path.to.api.outsideOperations(jobId));- }- }, [jobId]);-+ const jobOperationFetcher = useLoaderQuery<+ PostgrestResponse<{ id: string; description: string }>+ >(jobId ? path.to.api.outsideOperations(jobId) : null);const jobOperationOptions = useMemo(() => {return (jobOperationFetcher.data?.data?.map((c) => ({diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderProperties.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderProperties.tsxindex ce05e8e519..9d13da452f 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderProperties.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderProperties.tsx@@ -5,6 +5,7 @@import type { Json } from "@carbon/database";import { getPurchaseOrderDisplayId } from "@carbon/documents/utils";import { DatePicker, InputControlled, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Badge,Button,@@ -19,7 +20,7 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useCallback, useEffect } from "react";+import { useCallback } from "react";import {LuCirclePlay,LuCopy,@@ -69,13 +70,13 @@ const PurchaseOrderProperties = () => {supplierQuote: SupplierQuote;}>(path.to.purchaseOrder(orderId));- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });const { company } = useUser();const exchangeRateFetcher = useFetcher<typeof exchangeRateAction>();const { t } = useLingui();diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsxindex 87670f0ac0..2a0e165197 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrdersTable.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {BarProgress,Checkbox,@@ -20,7 +21,7 @@ import {import { getLocalTimeZone, today } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";-import { memo, useCallback, useEffect, useMemo, useState } from "react";+import { memo, useCallback, useMemo, useState } from "react";import {LuBookMarked,LuCalendar,@@ -37,7 +38,6 @@ import {LuTruck,LuUser} from "react-icons/lu";-import { useFetcher } from "react-router";import {DateTime,EmployeeAvatar,@@ -395,13 +395,13 @@ const PurchaseOrdersTable = memo(t]);- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onBulkUpdate = useCallback((selectedRows: typeof data, field: "delete", value?: string) => {diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/PurchaseReturnOrderProperties.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/PurchaseReturnOrderProperties.tsxindex 1c577c06bc..6418624614 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/PurchaseReturnOrderProperties.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/PurchaseReturnOrderProperties.tsx@@ -10,6 +10,7 @@ import {InputControlled,ValidatedForm} from "@carbon/form";+import { useAction } from "@carbon/query";import {Badge,Button,@@ -33,7 +34,7 @@ import { Trans, useLingui } from "@lingui/react/macro";import { useCallback, useEffect, useMemo, useState } from "react";import { LuCopy, LuKeySquare, LuLink, LuUnlink2 } from "react-icons/lu";import { RiProgress8Line } from "react-icons/ri";-import { useFetcher, useParams } from "react-router";+import { useParams } from "react-router";import { z } from "zod";import { zfd } from "zod-form-data";import {@@ -89,13 +90,13 @@ const PurchaseReturnOrderProperties = () => {const unlinkDisclosure = useDisclosure();- const fetcher = useFetcher<{ error: { message: string } | null }>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<{ error: { message: string } | null }>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });const { carbon } = useCarbon();const [purchaseOrderOptions, setPurchaseOrderOptions] = useState<{ value: string; label: string }[]diff --git a/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQProperties.tsx b/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQProperties.tsxindex ab33728658..1d488cabdc 100644--- a/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQProperties.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchasingRfq/PurchasingRFQProperties.tsx@@ -4,6 +4,7 @@import type { Json } from "@carbon/database";import { CreatableMultiSelect, DatePicker, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Avatar,AvatarGroup,@@ -21,9 +22,9 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useCallback, useEffect, useMemo, useState } from "react";+import { useCallback, useMemo, useState } from "react";import { LuCopy, LuKeySquare, LuLink } from "react-icons/lu";-import { useFetcher, useParams } from "react-router";+import { useParams } from "react-router";import { z } from "zod";import { zfd } from "zod-form-data";import { Assignee, useOptimisticAssignment } from "~/components";@@ -89,13 +90,13 @@ const PurchasingRFQProperties = () => {);}, [routeData?.suppliers]);- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onUpdate = useCallback((field: keyof PurchasingRFQ, value: string | null) => {diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteProperties.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteProperties.tsxindex 5fe962519a..ac7f4b66d1 100644--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteProperties.tsx+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteProperties.tsx@@ -4,6 +4,7 @@import type { Json } from "@carbon/database";import { DatePicker, InputControlled, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Copy,@@ -17,7 +18,7 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useCallback, useEffect } from "react";+import { useCallback } from "react";import {LuCopy,LuInfo,@@ -52,13 +53,13 @@ const SupplierQuoteProperties = () => {quote: SupplierQuote;}>(path.to.supplierQuote(id));- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });const { company } = useUser();const exchangeRateFetcher = useFetcher<typeof exchangeRateAction>();const { t } = useLingui();diff --git a/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx b/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsxindex e9f5fe6958..ad5449f4fd 100644--- a/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx+++ b/apps/erp/app/modules/quality/ui/Inspections/InspectionView.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useLoaderQuery } from "@carbon/query";import {Alert,AlertDescription,@@ -791,7 +792,7 @@ function DocumentSwitchModal({}) {const { t } = useLingui();const fetcher = useFetcher<{}>();- const optionsFetcher = useFetcher<{+ const optionsFetcher = useLoaderQuery<{data:| {id: string;@@ -800,16 +801,9 @@ function DocumentSwitchModal({version: number;}[]| null;- }>();+ }>(path.to.api.inspectionDocuments(itemId));const [documentId, setDocumentId] = useState(currentDocumentId ?? "none");- useEffect(() => {- if (optionsFetcher.state === "idle" && optionsFetcher.data == null) {- optionsFetcher.load(path.to.api.inspectionDocuments(itemId));- }- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-const options = optionsFetcher.data?.data ?? [];return (diff --git a/apps/erp/app/modules/quality/ui/Inspections/RejectLotModal.tsx b/apps/erp/app/modules/quality/ui/Inspections/RejectLotModal.tsxindex 6afbcd1fb6..25297d2f97 100644--- a/apps/erp/app/modules/quality/ui/Inspections/RejectLotModal.tsx+++ b/apps/erp/app/modules/quality/ui/Inspections/RejectLotModal.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {Alert,AlertDescription,@@ -24,9 +25,8 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useEffect, useRef, useState } from "react";+import { useRef, useState } from "react";import { LuTriangleAlert } from "react-icons/lu";-import { useFetcher } from "react-router";import type { IssueTypeListItem } from "~/modules/quality/types";export type FailedFeatureSummary = {@@ -55,20 +55,20 @@ const RejectLotModal = ({onSubmit}: RejectLotModalProps) => {const { t } = useLingui();- const fetcher = useFetcher<{}>();+ const fetcher = useAction<{}>({+ onSettled: () => {+ if (submitted.current) {+ onSubmit();+ submitted.current = false;+ }+ }+ });const submitted = useRef(false);const [createNcr, setCreateNcr] = useState(true);const [issueTypeId, setIssueTypeId] = useState<string>(issueTypes[0]?.id ?? "");- useEffect(() => {- if (fetcher.state === "idle" && submitted.current) {- onSubmit();- submitted.current = false;- }- }, [fetcher.state, onSubmit]);-const hasIssueTypes = issueTypes.length > 0;return (diff --git a/apps/erp/app/modules/quality/ui/Issue/ActionTasksList.tsx b/apps/erp/app/modules/quality/ui/Issue/ActionTasksList.tsxindex ba6031b100..4763707577 100644--- a/apps/erp/app/modules/quality/ui/Issue/ActionTasksList.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/ActionTasksList.tsx@@ -2,10 +2,11 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import { toast } from "@carbon/react";import { useLingui } from "@lingui/react/macro";-import { useCallback, useEffect } from "react";-import { useFetcher, useParams } from "react-router";+import { useCallback } from "react";+import { useParams } from "react-router";import { ActionTaskList } from "~/components/ActionTasks/ActionTaskList";import { useRouteData } from "~/hooks";import type { IssueActionTask } from "~/modules/quality";@@ -33,11 +34,13 @@ export function ActionTasksList({requiredActions: ListItem[];nonConformance: { requiredActionIds: string[] | null };}>(path.to.issue(id));- const addFetcher = useFetcher<{ error: { message: string } | null }>();-- useEffect(() => {- if (addFetcher.data?.error) toast.error(addFetcher.data.error.message);- }, [addFetcher.data]);+ const addFetcher = useAction<{ error: { message: string } | null }>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }+ }+ });const existingIds = routeData?.nonConformance?.requiredActionIds ?? [];diff --git a/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx b/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsxindex 2be82800f4..27b3623a4e 100644--- a/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx@@ -10,6 +10,7 @@ import {Submit,ValidatedForm} from "@carbon/form";+import { useAction } from "@carbon/query";import {Alert,AlertDescription,@@ -79,13 +80,13 @@ function DispositionQuantityInput({quantity: number;}) {const { t } = useLingui();- const fetcher = useFetcher<typeof action>();-- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);+ });// Show the submitted value while the save is in flight; once the fetcher is// idle this falls back to the loader's quantity, which also resets the field@@ -177,19 +178,19 @@ export function AssociatedItemsList({const [items] = useItems();const { t } = useLingui();const permissions = usePermissions();- const fetcher = useFetcher<typeof action>();+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }+ }+ });const splitFetcher = useFetcher<typeof splitAction>();const assignFetcher = useFetcher<typeof assignAction>();const [splitTarget, setSplitTarget] = useState<SplitTarget | null>(null);const [moveTarget, setMoveTarget] = useState<MoveTarget | null>(null);const [dragOverRowId, setDragOverRowId] = useState<string | null>(null);- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);- }- }, [fetcher.data]);-useEffect(() => {if (splitFetcher.data &&diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsxindex 13a164e3fc..113b9edd67 100644--- a/apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/IssueProperties.tsx@@ -10,6 +10,7 @@ import {Select,ValidatedForm} from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Copy,@@ -22,9 +23,9 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useCallback, useEffect } from "react";+import { useCallback } from "react";import { LuCopy, LuKeySquare, LuLink } from "react-icons/lu";-import { useFetcher, useParams } from "react-router";+import { useParams } from "react-router";import { z } from "zod";import {Assignee,@@ -76,13 +77,13 @@ const IssueProperties = () => {const isStarted = routeData?.nonConformance?.status !== "Registered";const isLocked = isIssueLocked(routeData?.nonConformance?.status);- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onUpdate = useCallback((diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsxindex 140f5959cf..b4d612574a 100644--- a/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx@@ -296,11 +296,7 @@ export function TaskItem({showDragHandle={showDragHandle}dragControls={dragControls}statusBadge={- <IssueTaskStatus- task={task}- type="investigation"- isDisabled={isDisabled}- />+ <IssueTaskStatus task={task} type={type} isDisabled={isDisabled} />}headerExtras={<>diff --git a/apps/erp/app/modules/quality/ui/Issue/ReviewersList.tsx b/apps/erp/app/modules/quality/ui/Issue/ReviewersList.tsxindex 5b7543bfed..ee5056ce36 100644--- a/apps/erp/app/modules/quality/ui/Issue/ReviewersList.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/ReviewersList.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { Input, Submit, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Card,@@ -22,9 +23,9 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useCallback, useEffect, useRef, useState } from "react";+import { useCallback, useRef, useState } from "react";import { LuCirclePlus } from "react-icons/lu";-import { useFetcher, useParams } from "react-router";+import { useParams } from "react-router";import { useRouteData } from "~/hooks";import type { IssueReviewer } from "~/modules/quality";import { nonConformanceReviewerValidator } from "~/modules/quality";@@ -43,16 +44,15 @@ export function ReviewersList({const disclosure = useDisclosure();const { t } = useLingui();- const fetcher = useFetcher<typeof reviewAction>();- const submitted = useRef(false);- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (fetcher.data?.success && submitted.current) {- disclosure.onClose();- submitted.current = false;+ const fetcher = useAction<typeof reviewAction>({+ onSuccess: (data) => {+ if (data?.success && submitted.current) {+ disclosure.onClose();+ submitted.current = false;+ }}- }, [fetcher.data?.success]);-+ });+ const submitted = useRef(false);if (reviewers.length === 0) {return <NewApprovalRequirement isDisabled={isDisabled} />;}@@ -150,14 +150,14 @@ function NewApprovalRequirement({ isDisabled }: { isDisabled: boolean }) {nonConformance: Issue;}>(path.to.issue(id));- const fetcher = useFetcher();-- useEffect(() => {- if (fetcher.state === "idle" && fetcher.data) {- setIsOpen(false);- setIsMRBChecked(false);+ const fetcher = useAction({+ onSettled: (data) => {+ if (data) {+ setIsOpen(false);+ setIsMRBChecked(false);+ }}- }, [fetcher.state, fetcher.data]);+ });const handleSubmit = useCallback(() => {const formData = new FormData();diff --git a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchExplorer.tsx b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchExplorer.tsxindex 2ebc6965cd..67ddac9a0a 100644--- a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchExplorer.tsx+++ b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchExplorer.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { DateTimePicker, Hidden, Submit, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Count,@@ -32,7 +33,7 @@ import {import { formatDate } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { useLocale } from "@react-aria/i18n";-import { useEffect, useState } from "react";+import { useState } from "react";import { flushSync } from "react-dom";import {LuBox,@@ -45,7 +46,7 @@ import {LuSearch,LuTrash} from "react-icons/lu";-import { Link, useFetcher, useParams } from "react-router";+import { Link, useParams } from "react-router";import { Employee, TextArea, WorkCenter } from "~/components/Form";import { ConfirmDelete } from "~/components/Modals";import { LevelLine } from "~/components/TreeView";@@ -425,13 +426,13 @@ function NewTimecardModal({dispatchId: string;}) {const { t } = useLingui();- const fetcher = useFetcher();-- useEffect(() => {- if (fetcher.state === "idle" && fetcher.data?.success === true) {- onClose();+ const fetcher = useAction({+ onSuccess: (data) => {+ if (data?.success === true) {+ onClose();+ }}- }, [fetcher.state, fetcher.data, onClose]);+ });return (<Modal@@ -492,13 +493,13 @@ function EditTimecardModal({event: MaintenanceDispatchEvent & { type: "event" };}) {const { t } = useLingui();- const fetcher = useFetcher();-- useEffect(() => {- if (fetcher.state === "idle" && fetcher.data?.success === true) {- onClose();+ const fetcher = useAction({+ onSuccess: (data) => {+ if (data?.success === true) {+ onClose();+ }}- }, [fetcher.state, fetcher.data, onClose]);+ });return (<Modaldiff --git a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchProperties.tsx b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchProperties.tsxindex 2b618a503c..ab63065fee 100644--- a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchProperties.tsx+++ b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchProperties.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { DateTimePicker, Hidden, Select, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Copy,@@ -78,14 +79,14 @@ const MaintenanceDispatchProperties = () => {? optimisticAssignment: (routeData?.dispatch?.assignee?.id ?? null);- const fetcher = useFetcher<{ error?: { message: string } }>();- const eventFetcher = useFetcher<{ error?: { message: string } }>();-- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<{ error?: { message: string } }>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);+ });+ const eventFetcher = useFetcher<{ error?: { message: string } }>();useEffect(() => {if (diff --git a/apps/erp/app/modules/resources/ui/Training/TrainingProperties.tsx b/apps/erp/app/modules/resources/ui/Training/TrainingProperties.tsxindex 4560a32515..e936eff8ff 100644--- a/apps/erp/app/modules/resources/ui/Training/TrainingProperties.tsx+++ b/apps/erp/app/modules/resources/ui/Training/TrainingProperties.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { Select, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Badge,Button,@@ -16,9 +17,9 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useCallback, useEffect } from "react";+import { useCallback } from "react";import { LuCopy, LuKeySquare, LuLink } from "react-icons/lu";-import { useFetcher, useParams } from "react-router";+import { useParams } from "react-router";import { z } from "zod";import Assignee, { useOptimisticAssignment } from "~/components/Assignee";import { Enumerable } from "~/components/Enumerable";@@ -46,13 +47,13 @@ const TrainingProperties = () => {tags: Array<{ name: string }>;}>(path.to.training(id));- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onUpdate = useCallback((diff --git a/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx b/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsxindex 7be22ab63a..2172753b33 100644--- a/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx+++ b/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx@@ -5,6 +5,7 @@import { useCarbon } from "@carbon/auth";import { activeJobStatuses } from "@carbon/database";import { getLogger } from "@carbon/logger";+import { useAction } from "@carbon/query";import {Alert,AlertDescription,@@ -28,7 +29,7 @@ import {} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";-import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";+import { memo, useCallback, useMemo, useRef, useState } from "react";import {LuAlignLeft,LuBuilding2,@@ -41,7 +42,7 @@ import {LuTriangleAlert,LuUser} from "react-icons/lu";-import { useFetcher, useNavigate } from "react-router";+import { useNavigate } from "react-router";import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";import { Enumerable } from "~/components/Enumerable";import { EnumerableGroup } from "~/components/EnumerableGroup";@@ -445,15 +446,15 @@ function DeleteWorkCenterModal({}};- const fetcher = useFetcher<{}>();- const submitted = useRef(false);- useEffect(() => {- if (fetcher.state === "idle" && submitted.current) {- onSubmit?.();- submitted.current = false;+ const fetcher = useAction<{}>({+ onSettled: () => {+ if (submitted.current) {+ onSubmit?.();+ submitted.current = false;+ }}- }, [fetcher.state, onSubmit]);-+ });+ const submitted = useRef(false);useMount(() => {getActiveOperations();});diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsxindex c7739a4237..7c51f597f6 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx@@ -5,6 +5,7 @@"use client";import { useCarbon } from "@carbon/auth";import { Array as ArrayInput, Input, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import type { JSONContent } from "@carbon/react";import {Alert,@@ -1146,15 +1147,14 @@ function AttributesListItem({const disclosure = useDisclosure();const deleteModalDisclosure = useDisclosure();const submitted = useRef(false);- const fetcher = useFetcher<typeof editQuoteOperationStepAction>();-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (submitted.current && fetcher.state === "idle") {- disclosure.onClose();- submitted.current = false;+ const fetcher = useAction<typeof editQuoteOperationStepAction>({+ onSettled: () => {+ if (submitted.current) {+ disclosure.onClose();+ submitted.current = false;+ }}- }, [fetcher.state]);+ });const [type, setType] = useState<OperationStep["type"]>(attribute.type);@@ -1535,15 +1535,14 @@ function ParametersListItem({const disclosure = useDisclosure();const deleteModalDisclosure = useDisclosure();const submitted = useRef(false);- const fetcher = useFetcher<typeof editQuoteOperationParameterAction>();-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (submitted.current && fetcher.state === "idle") {- disclosure.onClose();- submitted.current = false;+ const fetcher = useAction<typeof editQuoteOperationParameterAction>({+ onSettled: () => {+ if (submitted.current) {+ disclosure.onClose();+ submitted.current = false;+ }}- }, [fetcher.state]);+ });const isUpdated = updatedBy !== null;const person = isUpdated ? updatedBy : createdBy;@@ -2555,15 +2554,14 @@ function ToolsListItem({const disclosure = useDisclosure();const deleteModalDisclosure = useDisclosure();const submitted = useRef(false);- const fetcher = useFetcher<typeof editQuoteOperationToolAction>();-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (submitted.current && fetcher.state === "idle") {- disclosure.onClose();- submitted.current = false;+ const fetcher = useAction<typeof editQuoteOperationToolAction>({+ onSettled: () => {+ if (submitted.current) {+ disclosure.onClose();+ submitted.current = false;+ }}- }, [fetcher.state]);+ });const tools = useTools();const tool = tools.find((t) => t.id === toolId);diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteLineMethodForm.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteLineMethodForm.tsxindex 5e96b93627..6e367b13cb 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteLineMethodForm.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteLineMethodForm.tsx@@ -3,39 +3,29 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { Combobox, Hidden, SelectControlled } from "@carbon/form";-import { useMount, VStack } from "@carbon/react";+import { useLoaderQuery } from "@carbon/query";+import { VStack } from "@carbon/react";import { useLingui } from "@lingui/react/macro";import type { PostgrestResponse } from "@supabase/supabase-js";-import { useEffect, useMemo, useState } from "react";-import { useFetcher } from "react-router";+import { useMemo, useState } from "react";import { RevisionSuffix } from "~/components";import { path } from "~/utils/path";import type { getQuoteLinesList } from "../../sales.service";export function QuoteLineMethodForm() {const { t } = useLingui();- const quoteFetcher =- useFetcher<- PostgrestResponse<{ id: string; quoteId: string; revisionId: number }>- >();- const quoteLineFetcher =- useFetcher<Awaited<ReturnType<typeof getQuoteLinesList>>>();+ const quoteFetcher = useLoaderQuery<+ PostgrestResponse<{ id: string; quoteId: string; revisionId: number }>+ >(path.to.api.quotes);- // const quotesLoading = quoteFetcher.state === "loading";- // const quoteLinesLoading = quoteLineFetcher.state === "loading";+ // const quotesLoading = quoteFetcher.isFetching;+ // const quoteLinesLoading = quoteLineFetcher.isFetching;const [quote, setQuote] = useState<string | null>(null);- const [quoteLine, setQuoteLine] = useState<string | null>(null);-- useMount(() => {- quoteFetcher.load(path.to.api.quotes);- });- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (quote) {- quoteLineFetcher.load(path.to.api.quoteLines(quote));- }- }, [quote]);+ const quoteLineFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getQuoteLinesList>>+ >(quote ? path.to.api.quoteLines(quote) : null);+ const [quoteLine, setQuoteLine] = useState<string | null>(null);const quoteOptions = useMemo(() =>diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsxindex 6fa003820f..c0d32f03ba 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx@@ -4,6 +4,7 @@import { useCarbon } from "@carbon/auth";import { SelectControlled, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Alert,AlertTitle,@@ -46,7 +47,7 @@ import {LuTriangleAlert} from "react-icons/lu";import { RiProgress4Line } from "react-icons/ri";-import { useFetcher, useLocation, useParams } from "react-router";+import { useLocation, useParams } from "react-router";import { ConfiguratorModal } from "~/components/Configurator/ConfiguratorForm";import { Hidden, Item, Submit, useConfigurableItems } from "~/components/Form";import type { Tree } from "~/components/TreeView";@@ -70,7 +71,13 @@ const QuoteMakeMethodTools = () => {const { quoteId, lineId, methodId } = useParams();if (!quoteId) throw new Error("quoteId not found");- const fetcher = useFetcher<{ error: string | null }>();+ const fetcher = useAction<{ error: string | null }>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error);+ }+ }+ });const routeData = useRouteData<{quote: Quotation;lines: QuotationLine[];@@ -112,12 +119,6 @@ const QuoteMakeMethodTools = () => {const isSaveMethodLoading =fetcher.state !== "idle" && fetcher.formAction === path.to.quoteMethodSave;- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error);- }- }, [fetcher.data?.error]);-const [includeInactive, setIncludeInactive] = useState<boolean | "indeterminate">(true);diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteProperties.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteProperties.tsxindex 2803ced990..f47563abf7 100644--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteProperties.tsx+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteProperties.tsx@@ -5,6 +5,7 @@import type { Json } from "@carbon/database";import { getQuoteDisplayId } from "@carbon/documents/utils";import { DatePicker, InputControlled, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Copy,@@ -18,7 +19,7 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useCallback, useEffect } from "react";+import { useCallback } from "react";import {LuCopy,LuInfo,@@ -61,13 +62,13 @@ const QuoteProperties = () => {quote: Quotation;}>(path.to.quote(quoteId));- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });const { company } = useUser();const exchangeRateFetcher = useFetcher<typeof exchangeRateAction>();diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderProperties.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderProperties.tsxindex 344a4ea8f9..0d99d6c8f7 100644--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderProperties.tsx+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderProperties.tsx@@ -4,6 +4,7 @@import type { Json } from "@carbon/database";import { DatePicker, InputControlled, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Copy,@@ -17,7 +18,7 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useCallback, useEffect } from "react";+import { useCallback } from "react";import {LuCopy,LuInfo,@@ -60,13 +61,13 @@ const SalesOrderProperties = () => {salesOrder: SalesOrder;}>(path.to.salesOrder(orderId));- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });const { company } = useUser();const exchangeRateFetcher = useFetcher<typeof exchangeRateAction>();diff --git a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQProperties.tsx b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQProperties.tsxindex 3bb5215923..43c685b437 100644--- a/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQProperties.tsx+++ b/apps/erp/app/modules/sales/ui/SalesRFQ/SalesRFQProperties.tsx@@ -4,6 +4,7 @@import type { Json } from "@carbon/database";import { DatePicker, InputControlled, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Copy,@@ -16,9 +17,9 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useCallback, useEffect } from "react";+import { useCallback } from "react";import { LuCopy, LuKeySquare, LuLink } from "react-icons/lu";-import { useFetcher, useParams } from "react-router";+import { useParams } from "react-router";import { z } from "zod";import { zfd } from "zod-form-data";import { Assignee, useOptimisticAssignment } from "~/components";@@ -46,13 +47,13 @@ const SalesRFQProperties = () => {rfqSummary: SalesRFQ;}>(path.to.salesRfq(rfqId));- const fetcher = useFetcher<typeof action>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<typeof action>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationconst onUpdate = useCallback((field: keyof SalesRFQ, value: string | null) => {diff --git a/apps/erp/app/modules/sales/ui/SalesReturnOrders/SalesReturnOrderLineForm.tsx b/apps/erp/app/modules/sales/ui/SalesReturnOrders/SalesReturnOrderLineForm.tsxindex a4bc5a5452..4be9d368c4 100644--- a/apps/erp/app/modules/sales/ui/SalesReturnOrders/SalesReturnOrderLineForm.tsx+++ b/apps/erp/app/modules/sales/ui/SalesReturnOrders/SalesReturnOrderLineForm.tsx@@ -4,6 +4,7 @@import { useCarbon } from "@carbon/auth";import { Combobox, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Select as CarbonSelect,@@ -27,7 +28,7 @@ import {} from "@carbon/react";import { INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";-import { Fragment, useEffect, useState } from "react";+import { Fragment, useState } from "react";import { LuCircleStop, LuLoaderCircle } from "react-icons/lu";import { useFetcher, useParams } from "react-router";import type { z } from "zod";@@ -238,18 +239,16 @@ const SalesReturnOrderLineForm = ({// Disposition submits through its own fetcher, not the line form. Scrap and// Rework escalate to an Issue instead of writing the disposition directly.- const dispositionFetcher = useFetcher<{ success: boolean }>();+ const dispositionFetcher = useAction<{ success: boolean }>({+ onSettled: () => {+ if (line?.disposition) {+ setDisposition(line.disposition as string);+ }+ }+ });const [disposition, setDisposition] = useState((line?.disposition as string | undefined) ?? "Pending");- // The disposition routes always redirect (success or flashed error), so the- // loader's revalidated value is the persisted truth — sync the select to it.- // A failed submit reverts; a successful one confirms the same value.- useEffect(() => {- if (dispositionFetcher.state === "idle" && line?.disposition) {- setDisposition(line.disposition as string);- }- }, [dispositionFetcher.state, line?.disposition]);const quantityReceived = line?.quantityReceived ?? 0;const onDispositionChange = (value: string) => {diff --git a/apps/erp/app/modules/sales/ui/SalesReturnOrders/SalesReturnOrderProperties.tsx b/apps/erp/app/modules/sales/ui/SalesReturnOrders/SalesReturnOrderProperties.tsxindex 7cd94f567a..2514f95de0 100644--- a/apps/erp/app/modules/sales/ui/SalesReturnOrders/SalesReturnOrderProperties.tsx+++ b/apps/erp/app/modules/sales/ui/SalesReturnOrders/SalesReturnOrderProperties.tsx@@ -10,6 +10,7 @@ import {InputControlled,ValidatedForm} from "@carbon/form";+import { useAction } from "@carbon/query";import {Badge,Button,@@ -33,7 +34,7 @@ import { Trans, useLingui } from "@lingui/react/macro";import { useCallback, useEffect, useMemo, useState } from "react";import { LuCopy, LuKeySquare, LuLink, LuUnlink2 } from "react-icons/lu";import { RiProgress8Line } from "react-icons/ri";-import { useFetcher, useParams } from "react-router";+import { useParams } from "react-router";import { z } from "zod";import { zfd } from "zod-form-data";import {@@ -90,13 +91,13 @@ const SalesReturnOrderProperties = () => {const unlinkDisclosure = useDisclosure();- const fetcher = useFetcher<{ error: { message: string } | null }>();- useEffect(() => {- if (fetcher.data?.error) {- toast.error(fetcher.data.error.message);+ const fetcher = useAction<{ error: { message: string } | null }>({+ onError: (data) => {+ if (data?.error) {+ toast.error(data.error.message);+ }}- }, [fetcher.data]);-+ });const { carbon } = useCarbon();const [salesOrderOptions, setSalesOrderOptions] = useState<{ value: string; label: string }[]diff --git a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysForm.tsx b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysForm.tsxindex 8139081225..185dc260d0 100644--- a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysForm.tsx+++ b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysForm.tsx@@ -4,6 +4,7 @@import { getBrowserEnv } from "@carbon/auth";import { DateTimePicker, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Alert,AlertTitle,@@ -30,7 +31,6 @@ import {import { Trans, useLingui } from "@lingui/react/macro";import { useEffect, useMemo, useState } from "react";import { LuCheck, LuClipboard, LuLock } from "react-icons/lu";-import { useFetcher } from "react-router";import type { z } from "zod";import { Hidden, Input, Submit } from "~/components/Form";import PermissionMatrix from "~/components/PermissionMatrix";@@ -63,7 +63,13 @@ const ApiKeyForm = ({}: ApiKeyFormProps) => {const { t } = useLingui();const permissions = usePermissions();- const fetcher = useFetcher<{ key: string }>();+ const fetcher = useAction<{ key: string }>({+ onSettled: (data) => {+ if (data?.key) {+ setKey(data.key);+ }+ }+ });const isEditing = initialValues.id !== undefined;const isDisabled = !permissions.can("update", "users");@@ -85,12 +91,6 @@ const ApiKeyForm = ({bulkExcludedKeys: apiKeyOptInPermissionKeys});- useEffect(() => {- if (fetcher.data?.key) {- setKey(fetcher.data.key);- }- }, [fetcher.data]);-// Serialize scopes to JSONB format for form submissionconst scopesJsonb = companyId? JSON.stringify(toApiKeyScopes(matrix.permissions, companyId))diff --git a/apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsx b/apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsxindex 20d04855b6..ca71148882 100644--- a/apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsx+++ b/apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { Combobox, Submit, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Drawer,@@ -567,18 +568,16 @@ function MatchByCodeDrawer({canUpdate: boolean;onClose: () => void;}) {- const fetcher = useFetcher();+ const fetcher = useAction({+ onSettled: () => {+ if (submittedRef.current) {+ onClose();+ }+ }+ });const isSubmitting = fetcher.state !== "idle";const submittedRef = useRef(false);- // Close once the confirm-all POST settles; revalidation has already- // refreshed the sections behind the drawer.- useEffect(() => {- if (submittedRef.current && fetcher.state === "idle") {- onClose();- }- }, [fetcher.state, onClose]);-const confirmAll = () => {if (proposals.length === 0) return;const formData = new FormData();@@ -711,7 +710,13 @@ function AiSuggestModal({const suggestFetcher = useFetcher<{proposals?: AccountMatchProposalRow[];}>();- const applyFetcher = useFetcher();+ const applyFetcher = useAction({+ onSettled: () => {+ if (appliedRef.current) {+ onClose();+ }+ }+ });const appliedRef = useRef(false);const isSuggesting = suggestFetcher.state !== "idle";@@ -719,14 +724,6 @@ function AiSuggestModal({const proposals = suggestFetcher.data?.proposals;const hasSuggested = proposals !== undefined;- // Close once the apply POST settles; revalidation has already refreshed- // the sections behind the modal.- useEffect(() => {- if (appliedRef.current && applyFetcher.state === "idle") {- onClose();- }- }, [applyFetcher.state, onClose]);-const suggest = () => {const formData = new FormData();formData.append("intent", "ai-suggest-account-mappings");diff --git a/apps/erp/app/modules/settings/ui/Integrations/DimensionMapping.tsx b/apps/erp/app/modules/settings/ui/Integrations/DimensionMapping.tsxindex e9a4789f9f..badd0268cf 100644--- a/apps/erp/app/modules/settings/ui/Integrations/DimensionMapping.tsx+++ b/apps/erp/app/modules/settings/ui/Integrations/DimensionMapping.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { Combobox, Radios, Submit, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Badge,Button,@@ -27,9 +28,8 @@ import {} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import type { ReactNode } from "react";-import { useEffect, useMemo, useRef, useState } from "react";+import { useMemo, useRef, useState } from "react";import { LuArrowRight, LuLink, LuPlus, LuTrash2 } from "react-icons/lu";-import { useFetcher } from "react-router";import { usePermissions } from "~/hooks";import {dimensionSlotsUpdateValidator,@@ -714,18 +714,16 @@ function MatchByNameDrawer({canUpdate: boolean;onClose: () => void;}) {- const fetcher = useFetcher();+ const fetcher = useAction({+ onSettled: () => {+ if (submittedRef.current) {+ onClose();+ }+ }+ });const isSubmitting = fetcher.state !== "idle";const submittedRef = useRef(false);- // Close once the confirm-all POST settles; revalidation has already- // refreshed the sections behind the drawer.- useEffect(() => {- if (submittedRef.current && fetcher.state === "idle") {- onClose();- }- }, [fetcher.state, onClose]);-const confirmAll = () => {if (proposals.length === 0) return;const formData = new FormData();diff --git a/apps/erp/app/modules/settings/ui/Webhooks/WebhookForm.tsx b/apps/erp/app/modules/settings/ui/Webhooks/WebhookForm.tsxindex 554b9a0d60..03de59e581 100644--- a/apps/erp/app/modules/settings/ui/Webhooks/WebhookForm.tsx+++ b/apps/erp/app/modules/settings/ui/Webhooks/WebhookForm.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { Boolean, Input, Select, ValidatedForm } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import {Badge,Button,@@ -17,7 +18,6 @@ import {HStack,Separator,toast,- useMount,VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";@@ -153,12 +153,9 @@ const WebhookForm = ({export default WebhookForm;export const useWebhookTables = () => {- const tablesFetcher =- useFetcher<Awaited<ReturnType<typeof getWebhookTables>>>();-- useMount(() => {- tablesFetcher.load(path.to.api.webhookTables);- });+ const tablesFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getWebhookTables>>+ >(path.to.api.webhookTables);const tables = tablesFetcher.data?.data ?? [];diff --git a/apps/erp/app/modules/users/ui/Customers/CreateCustomerModal.tsx b/apps/erp/app/modules/users/ui/Customers/CreateCustomerModal.tsxindex 733d8ecc84..94014c9305 100644--- a/apps/erp/app/modules/users/ui/Customers/CreateCustomerModal.tsx+++ b/apps/erp/app/modules/users/ui/Customers/CreateCustomerModal.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { useControlField, useField, ValidatedForm } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import {Combobox,FormControl,@@ -150,15 +151,12 @@ const CustomerContact = ({} = useField(name);const [value, setValue] = useControlField<string | null>(name);- const customerContactFetcher =- useFetcher<Awaited<ReturnType<typeof getCustomerContacts>>>();+ const customerContactFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getCustomerContacts>>+ >(customer ? path.to.api.customerContacts(customer) : null);// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {- if (customer) {- customerContactFetcher.load(path.to.api.customerContacts(customer));- }-if (initialLoad.current) {initialLoad.current = false;} else {diff --git a/apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.ee.tsx b/apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.ee.tsxindex d9672cb4ee..5c1f7c9af4 100644--- a/apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.ee.tsx+++ b/apps/erp/app/modules/users/ui/Employees/BulkEditPermissionsForm.ee.tsx@@ -3,6 +3,7 @@// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.import { ValidatedForm } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import {Button,Drawer,@@ -12,12 +13,10 @@ import {DrawerHeader,DrawerTitle,HStack,- useMount,VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import { useEffect, useMemo } from "react";-import { useFetcher } from "react-router";import { Employees, Hidden, Radios, Submit } from "~/components/Form";import PermissionMatrix from "~/components/PermissionMatrix";import { usePermissions } from "~/hooks";@@ -43,7 +42,7 @@ const BulkEditPermissions = ({}: BulkEditPermissionsProps) => {const { t } = useLingui();const permissions = usePermissions();- const emptyPermissionsFetcher = useFetcher<{+ const emptyPermissionsFetcher = useLoaderQuery<{permissions: Record<string,{@@ -51,14 +50,10 @@ const BulkEditPermissions = ({permission: CompanyPermission;}>;- }>();+ }>(path.to.api.emptyPermissions);const canEditPermissions = permissions.can("update", "users");- useMount(() => {- emptyPermissionsFetcher.load(path.to.api.emptyPermissions);- });-const { state: initialState, modules } = useMemo(() => {if (emptyPermissionsFetcher.data) {return fromEmployeeTypePermissions(diff --git a/apps/erp/app/modules/users/ui/Employees/CreateEmployeeModal.tsx b/apps/erp/app/modules/users/ui/Employees/CreateEmployeeModal.tsxindex 47db77cf26..ac994250bd 100644--- a/apps/erp/app/modules/users/ui/Employees/CreateEmployeeModal.tsx+++ b/apps/erp/app/modules/users/ui/Employees/CreateEmployeeModal.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { ValidatedForm } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import {HStack,Modal,@@ -13,7 +14,6 @@ import {ModalOverlay,ModalTitle,useCloseRoute,- useMount,VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";@@ -47,12 +47,9 @@ const CreateEmployeeModal = ({ invitable }: CreateEmployeeModalProps) => {const { isGated: permissionsGated } = usePlanGate({ feature: "PERMISSIONS" });const closeRoute = useCloseRoute();const formFetcher = useFetcher<Result>();- const employeeTypeFetcher =- useFetcher<Awaited<ReturnType<typeof getEmployeeTypes>>>();-- useMount(() => {- employeeTypeFetcher.load(path.to.api.employeeTypes);- });+ const employeeTypeFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getEmployeeTypes>>+ >(path.to.api.employeeTypes);const employeeTypes = employeeTypeFetcher.data?.data ?? [];const employeeTypeOptions = employeeTypes.map((et) => ({diff --git a/apps/erp/app/modules/users/ui/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx b/apps/erp/app/modules/users/ui/Suppliers/CreateSupplierModal/CreateSupplierModal.tsxindex c1a44b9376..e91b3e65c0 100644--- a/apps/erp/app/modules/users/ui/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx+++ b/apps/erp/app/modules/users/ui/Suppliers/CreateSupplierModal/CreateSupplierModal.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { useControlField, useField, ValidatedForm } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import {Combobox,FormControl,@@ -150,15 +151,12 @@ const SupplierContact = ({} = useField(name);const [value, setValue] = useControlField<string | null>(name);- const supplierContactFetcher =- useFetcher<Awaited<ReturnType<typeof getSupplierContacts>>>();+ const supplierContactFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getSupplierContacts>>+ >(supplier ? path.to.api.supplierContacts(supplier) : null);// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {- if (supplier) {- supplierContactFetcher.load(path.to.api.supplierContacts(supplier));- }-if (initialLoad.current) {initialLoad.current = false;} else {diff --git a/apps/erp/app/modules/workflows/ui/Runs/RunLiveUpdates.tsx b/apps/erp/app/modules/workflows/ui/Runs/RunLiveUpdates.tsxindex 8619f448de..0b48554957 100644--- a/apps/erp/app/modules/workflows/ui/Runs/RunLiveUpdates.tsx+++ b/apps/erp/app/modules/workflows/ui/Runs/RunLiveUpdates.tsx@@ -4,8 +4,8 @@import { useDebouncedRealtime } from "~/hooks/useDebouncedRealtime";-export function RunsLiveUpdates({ companyId }: { companyId: string }) {- useDebouncedRealtime("workflowRun", `companyId=eq.${companyId}`);+export function RunsLiveUpdates() {+ useDebouncedRealtime("workflowRun");return null;}diff --git a/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunsTable.tsx b/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunsTable.tsxindex c015d8db2f..d686f34ef2 100644--- a/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunsTable.tsx+++ b/apps/erp/app/modules/workflows/ui/Runs/WorkflowRunsTable.tsx@@ -17,7 +17,6 @@ import {LuZap} from "react-icons/lu";import { EmployeeAvatar, Hyperlink, Table } from "~/components";-import { useUser } from "~/hooks";import { path } from "~/utils/path";import type { WorkflowRun } from "../../workflows.service";import { useWorkflowEventLabel } from "../Builder/catalog";@@ -34,7 +33,6 @@ type WorkflowRunsTableProps = {const WorkflowRunsTable = memo(({ data, count }: WorkflowRunsTableProps) => {const { t } = useLingui();- const { company } = useUser();// A fresh closure each render, so the columns memo reads it through a ref rather than// rebuilding every column on every render.const eventLabel = useWorkflowEventLabel();@@ -161,7 +159,7 @@ const WorkflowRunsTable = memo(({ data, count }: WorkflowRunsTableProps) => {return (<>- {hasInFlight && <RunsLiveUpdates companyId={company.id} />}+ {hasInFlight && <RunsLiveUpdates />}<Table<WorkflowRunListItem>data={data}columns={columns}diff --git a/apps/erp/app/modules/workflows/ui/WorkflowForm.tsx b/apps/erp/app/modules/workflows/ui/WorkflowForm.tsxindex b6bf8bd215..4fe7949922 100644--- a/apps/erp/app/modules/workflows/ui/WorkflowForm.tsx+++ b/apps/erp/app/modules/workflows/ui/WorkflowForm.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,HStack,@@ -16,8 +17,7 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useEffect } from "react";-import { useFetcher, useNavigate } from "react-router";+import { useNavigate } from "react-router";import type { z } from "zod";import { Hidden, Input, Submit } from "~/components/Form";import { usePermissions } from "~/hooks";@@ -39,19 +39,19 @@ const WorkflowForm = ({const { t } = useLingui();const navigate = useNavigate();const permissions = usePermissions();- const fetcher = useFetcher<{ id: string } | { success: false }>();+ const fetcher = useAction<{ id: string } | { success: false }>({+ onSettled: (data) => {+ if (data && "id" in data) {+ navigate(path.to.workflow(data.id));+ }+ }+ });const isEditing = initialValues.id !== undefined;const isDisabled = isEditing? !permissions.can("update", "workflows"): !permissions.can("create", "workflows");- useEffect(() => {- if (fetcher.data && "id" in fetcher.data) {- navigate(path.to.workflow(fetcher.data.id));- }- }, [fetcher.data, navigate]);-return (<ModalDrawerProvider type="modal"><ModalDrawerdiff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsxindex 46578b18de..ed3e28ac20 100644--- a/apps/erp/app/root.tsx+++ b/apps/erp/app/root.tsx@@ -16,6 +16,7 @@ import { validator } from "@carbon/form";import { LocaleProvider, resolveLanguage } from "@carbon/locale";import { requestMiddleware } from "@carbon/logger/middleware.server";import { timedMiddleware } from "@carbon/logger/tracing.server";+import { createInvalidationMiddleware } from "@carbon/query/cache";import {OperatingSystemContextProvider,Toaster,@@ -34,6 +35,7 @@ import {import { faviconLinks } from "@carbon/utils/favicon";import { I18nProvider } from "@react-aria/i18n";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { ReactQueryDevtools } from "@tanstack/react-query-devtools";import { Analytics } from "@vercel/analytics/react";import type React from "react";import { useContext, useState } from "react";@@ -60,6 +62,7 @@ import { getMode, setMode } from "~/services/mode.server";import Background from "~/styles/background.css?url";import NProgress from "~/styles/nprogress.css?url";import Tailwind from "~/styles/tailwind.css?url";+import { path } from "~/utils/path";import "@carbon/lib/shims";import { MotionConfig } from "motion/react";import type { Route } from "./+types/root";@@ -72,7 +75,13 @@ export const middleware = timedMiddleware({formBody: formBodyMiddleware,flash: flashMiddleware});-export const clientMiddleware = [flashClientMiddleware];+export const clientMiddleware = [+ flashClientMiddleware,+ createInvalidationMiddleware({+ getCache: () => window.clientCache,+ skipPaths: [path.to.refreshSession]+ })+];export const links: LinksFunction = () => {return [@@ -327,6 +336,8 @@ export default function App() {env={env}><Outlet />+ {/* Renders nothing outside development; the package strips itself. */}+ <ReactQueryDevtools buttonPosition="bottom-right" /></Document></MotionConfig></TooltipProvider>diff --git a/apps/erp/app/routes/api+/accounting.currencies.ts b/apps/erp/app/routes/api+/accounting.currencies.tsindex e2f3111ac5..ec944c8174 100644--- a/apps/erp/app/routes/api+/accounting.currencies.ts+++ b/apps/erp/app/routes/api+/accounting.currencies.ts@@ -3,12 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader, RefreshRate } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getCurrenciesList } from "~/modules/accounting";-import { currenciesQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyGroupId } = await requirePermissions(request, {});@@ -16,16 +13,6 @@ export async function loader({ request }: LoaderFunctionArgs) {return await getCurrenciesList(client, companyGroupId);}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const query = currenciesQuery();- const data = window?.clientCache?.getQueryData<typeof loader>(query.queryKey);-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(query.queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>({+ staleTime: RefreshRate.Never+});diff --git a/apps/erp/app/routes/api+/accounting.payment-terms.ts b/apps/erp/app/routes/api+/accounting.payment-terms.tsindex 16e6bb0964..621a52002f 100644--- a/apps/erp/app/routes/api+/accounting.payment-terms.ts+++ b/apps/erp/app/routes/api+/accounting.payment-terms.ts@@ -3,12 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getPaymentTermsList } from "~/modules/accounting";-import { getCompanyId, paymentTermsQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {});@@ -16,25 +13,4 @@ export async function loader({ request }: LoaderFunctionArgs) {return await getPaymentTermsList(client, companyId);}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId) {- return await serverLoader<typeof loader>();- }-- const queryKey = paymentTermsQuery(companyId).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/countries.ts b/apps/erp/app/routes/api+/countries.tsindex 78180640e4..f2cb6a33f4 100644--- a/apps/erp/app/routes/api+/countries.ts+++ b/apps/erp/app/routes/api+/countries.ts@@ -3,30 +3,15 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader, RefreshRate } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getCountries } from "~/modules/shared";-import { countriesQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {});return await getCountries(client);}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const query = countriesQuery();- const data = window?.clientCache?.getQueryData<- Awaited<ReturnType<typeof loader>>- >(query.queryKey);-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(query.queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>({+ staleTime: RefreshRate.Never+});diff --git a/apps/erp/app/routes/api+/docs.ts b/apps/erp/app/routes/api+/docs.tsindex 1c38f994db..71244ac7d1 100644--- a/apps/erp/app/routes/api+/docs.ts+++ b/apps/erp/app/routes/api+/docs.ts@@ -4,13 +4,9 @@import swaggerDocsSchema from "@carbon/database/swagger-docs-schema";import { Ratelimit, redis } from "@carbon/kv";+import { cachedClientLoader, RefreshRate } from "@carbon/query/cache";import { getClientIp } from "@carbon/utils";-import {- type ClientLoaderFunctionArgs,- data,- type LoaderFunctionArgs-} from "react-router";-import { docsQuery } from "~/utils/react-query";+import { data, type LoaderFunctionArgs } from "react-router";export async function loader({ request }: LoaderFunctionArgs) {const ip = getClientIp(request) ?? "127.0.0.1";@@ -28,19 +24,6 @@ export async function loader({ request }: LoaderFunctionArgs) {return swaggerDocsSchema;}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const queryKey = docsQuery().queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>({+ staleTime: RefreshRate.Never+});diff --git a/apps/erp/app/routes/api+/inventory.shipping-methods.ts b/apps/erp/app/routes/api+/inventory.shipping-methods.tsindex a28f6c420f..a541fc87d1 100644--- a/apps/erp/app/routes/api+/inventory.shipping-methods.ts+++ b/apps/erp/app/routes/api+/inventory.shipping-methods.ts@@ -3,12 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getShippingMethodsList } from "~/modules/inventory";-import { getCompanyId, shippingMethodsQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {});@@ -16,25 +13,4 @@ export async function loader({ request }: LoaderFunctionArgs) {return await getShippingMethodsList(client, companyId);}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId) {- return await serverLoader<typeof loader>();- }-- const queryKey = shippingMethodsQuery(companyId).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/inventory.storage-units-with-quantities.ts b/apps/erp/app/routes/api+/inventory.storage-units-with-quantities.tsindex 5a038ae414..5b6cdb377f 100644--- a/apps/erp/app/routes/api+/inventory.storage-units-with-quantities.ts+++ b/apps/erp/app/routes/api+/inventory.storage-units-with-quantities.ts@@ -3,13 +3,10 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getStorageUnitsListForLocation } from "~/modules/inventory";import { getItemStorageUnitQuantities } from "~/modules/items/items.service";-import { getCompanyId, storageUnitsQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -69,35 +66,6 @@ export async function loader({ request }: LoaderFunctionArgs) {return await getStorageUnitsListForLocation(client, companyId, locationId);}-export async function clientLoader({- request,- serverLoader-}: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId) {- return await serverLoader<typeof loader>();- }-- const url = new URL(request.url);- const locationId = url.searchParams.get("locationId");- const itemId = url.searchParams.get("itemId");-- const queryKey = storageUnitsQuery(- companyId,- locationId ?? null,- itemId ?? null- ).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}+// On-hand moves with every receipt, pick and shipment, by anyone: the cached+// value is shown at once and always read again.+export const clientLoader = cachedClientLoader<typeof loader>({ staleTime: 0 });diff --git a/apps/erp/app/routes/api+/inventory.storage-units.ts b/apps/erp/app/routes/api+/inventory.storage-units.tsindex 4bd6d417c0..483b23b59e 100644--- a/apps/erp/app/routes/api+/inventory.storage-units.ts+++ b/apps/erp/app/routes/api+/inventory.storage-units.ts@@ -3,12 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getStorageUnitsListForLocation } from "~/modules/inventory";-import { getCompanyId, storageUnitsQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -27,30 +24,4 @@ export async function loader({ request }: LoaderFunctionArgs) {return await getStorageUnitsListForLocation(client, companyId, locationId);}-export async function clientLoader({- request,- serverLoader-}: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId) {- return await serverLoader<typeof loader>();- }-- const url = new URL(request.url);- const locationId = url.searchParams.get("locationId");-- const queryKey = storageUnitsQuery(companyId, locationId ?? null).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/items.groups.ts b/apps/erp/app/routes/api+/items.groups.tsindex 2b0da61952..9994ac0050 100644--- a/apps/erp/app/routes/api+/items.groups.ts+++ b/apps/erp/app/routes/api+/items.groups.ts@@ -3,13 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";-+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getItemPostingGroupsList } from "~/modules/items";-import { getCompanyId, itemPostingGroupsQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {});@@ -17,22 +13,4 @@ export async function loader({ request }: LoaderFunctionArgs) {return await getItemPostingGroupsList(client, companyId);}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId) {- return await serverLoader<typeof loader>();- }-- const queryKey = itemPostingGroupsQuery(companyId).queryKey;- const data = window?.clientCache?.getQueryData<typeof loader>(queryKey);-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/items.types.$substanceId.$formId.ts b/apps/erp/app/routes/api+/items.types.$substanceId.$formId.tsindex 42da04fe66..c9a16383d9 100644--- a/apps/erp/app/routes/api+/items.types.$substanceId.$formId.ts+++ b/apps/erp/app/routes/api+/items.types.$substanceId.$formId.ts@@ -3,13 +3,10 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { data } from "react-router";import { getMaterialTypeList } from "~/modules/items";-import { getCompanyId, materialTypesQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -32,32 +29,4 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}-export async function clientLoader({- params,- serverLoader-}: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId || !params.substanceId || !params.formId) {- return await serverLoader<typeof loader>();- }-- const query = materialTypesQuery(- params.substanceId,- params.formId,- companyId- );- const data = window?.clientCache?.getQueryData<- Awaited<ReturnType<typeof loader>>- >(query.queryKey);-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(query.queryKey, serverData);- return serverData;- }-- return data;-}--clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/items.uoms.ts b/apps/erp/app/routes/api+/items.uoms.tsindex cadb7c235a..e8ca918e98 100644--- a/apps/erp/app/routes/api+/items.uoms.ts+++ b/apps/erp/app/routes/api+/items.uoms.ts@@ -3,12 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader, RefreshRate } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getUnitOfMeasuresList } from "~/modules/items";-import { getCompanyId, uomsQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {});@@ -16,25 +13,6 @@ export async function loader({ request }: LoaderFunctionArgs) {return await getUnitOfMeasuresList(client, companyId);}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId) {- return await serverLoader<typeof loader>();- }-- const queryKey = uomsQuery(companyId).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>({+ staleTime: RefreshRate.Medium+});diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex 0aab95a693..70178007a9 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -1,5 +1,5 @@{- "totalTools": 1483,+ "totalTools": 1484,"modules": 15,"tools": [{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},@@ -450,7 +450,7 @@{"name":"items_getMaterialType","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"0cc848ca86e3","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getMaterialTypeList","classification":"READ","paramCount":2,"schema":"babec8528804","response":"c3dfbc0fdf89","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getMaterialTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"cbbbd5d9c38d","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},- {"name":"items_getMaterialUsedIn","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"6c20410ebbf7","injectAuth":"companyId","permission":"parts:view","paginates":false},+ {"name":"items_getMaterialUsedIn","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"5bc3cafcb138","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getMethodMaterial","classification":"READ","paramCount":1,"schema":"5aa329400da2","response":"4f986471aaee","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getMethodMaterials","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"16cb0357007c","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},{"name":"items_getMethodMaterialsByMakeMethod","classification":"READ","paramCount":1,"schema":"2796fbbcab70","response":"ed99eb62f33c","injectAuth":"companyId","permission":"parts:view","paginates":false},@@ -466,7 +466,7 @@{"name":"items_getPart","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"85d85a501c26","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getParts","classification":"READ","paramCount":4,"schema":"5571215d4362","response":"b134f22017b9","injectAuth":"companyId","permission":"parts:view","paginates":true,"defaults":"always"},{"name":"items_getPartsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f674f76b8278","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getPartUsedIn","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"bc331becb999","injectAuth":"companyId","permission":"parts:view","paginates":false},+ {"name":"items_getPartUsedIn","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"e205f0dd9382","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getPickMethod","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"781e7f3fc24f","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getPickMethods","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"f1260811ebd4","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getRecipeProcessIdsForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"681004346c78","injectAuth":"companyId","permission":"parts:view","paginates":false},@@ -849,7 +849,8 @@{"name":"purchasing_deleteSupplierType","classification":"DESTRUCTIVE","paramCount":1,"schema":"900045091850","response":"bcde375ebd4c","injectAuth":"companyId","permission":"purchasing:delete","paginates":false},{"name":"purchasing_duplicatePurchaseOrder","classification":"WRITE","paramCount":1,"schema":"b6bf3abf506d","response":"f5212679d580","injectAuth":"companyGroupId+companyId+createdBy+updatedBy+userId","permission":"purchasing:create","paginates":false},{"name":"purchasing_finalizePurchaseOrder","classification":"WRITE","paramCount":1,"schema":"28cffcd9d6e8","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},- {"name":"purchasing_finalizeSupplierQuote","classification":"WRITE","paramCount":1,"schema":"5db39f9abf41","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_finalizePurchasingRfq","classification":"WRITE","paramCount":1,"schema":"9531e4360acd","response":"e2e56b5a6c0a","injectAuth":"companyId+updatedBy+userId","permission":"purchasing:update","paginates":false},+ {"name":"purchasing_finalizeSupplierQuote","classification":"WRITE","paramCount":1,"schema":"5db39f9abf41","response":"9e056a59d695","injectAuth":"companyId+updatedBy+userId","permission":"purchasing:update","paginates":false},{"name":"purchasing_getCreditableQuantitiesForPurchaseReturn","classification":"READ","paramCount":1,"schema":"11b028f16d94","response":"1e97e6c72b1d","injectAuth":"companyId","permission":"purchasing:view","paginates":false},{"name":"purchasing_getDefaultAttachmentsForPO","classification":"READ","paramCount":2,"schema":"17cccb0ea3ef","response":"4a42c6b9da80","injectAuth":"companyId","permission":"purchasing:view","paginates":false},{"name":"purchasing_getLinkedPurchasingRfqs","classification":"READ","paramCount":1,"schema":"5db39f9abf41","response":"9c82bc9ce35e","injectAuth":"companyId","permission":"purchasing:view","paginates":false},diff --git a/apps/erp/app/routes/api+/production.assembly-instructions.$itemId.ts b/apps/erp/app/routes/api+/production.assembly-instructions.$itemId.tsindex 6d197cb36b..088722d683 100644--- a/apps/erp/app/routes/api+/production.assembly-instructions.$itemId.ts+++ b/apps/erp/app/routes/api+/production.assembly-instructions.$itemId.ts@@ -3,13 +3,10 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { data } from "react-router";import { getAssemblyInstructionsForItem } from "~/modules/production";-import { assemblyInstructionsQuery, getCompanyId } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -24,28 +21,4 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return await getAssemblyInstructionsForItem(client, itemId, companyId);}-export async function clientLoader({- params,- serverLoader-}: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId || !params.itemId) {- return await serverLoader<typeof loader>();- }-- const query = assemblyInstructionsQuery(params.itemId, companyId);- const data = window?.clientCache?.getQueryData<- Awaited<ReturnType<typeof loader>>- >(query.queryKey);-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(query.queryKey, serverData);- return serverData;- }-- return data;-}--clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/production.procedures.ts b/apps/erp/app/routes/api+/production.procedures.tsindex bd9715e4fb..7a3cd39f1c 100644--- a/apps/erp/app/routes/api+/production.procedures.ts+++ b/apps/erp/app/routes/api+/production.procedures.ts@@ -3,12 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getProceduresList } from "~/modules/production";-import { getCompanyId, proceduresQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -18,25 +15,4 @@ export async function loader({ request }: LoaderFunctionArgs) {return await getProceduresList(client, companyId);}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId) {- return await serverLoader<typeof loader>();- }-- const queryKey = proceduresQuery(companyId).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/purchasing.supplier-contacts.$supplierId.ts b/apps/erp/app/routes/api+/purchasing.supplier-contacts.$supplierId.tsindex 1cde634dff..1a591d4da1 100644--- a/apps/erp/app/routes/api+/purchasing.supplier-contacts.$supplierId.ts+++ b/apps/erp/app/routes/api+/purchasing.supplier-contacts.$supplierId.ts@@ -5,13 +5,10 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { data } from "react-router";import { getSupplierContacts } from "~/modules/purchasing";-import { supplierContactsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const authorized = await requirePermissions(request, {@@ -39,28 +36,4 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return contacts;}-export async function clientLoader({- serverLoader,- params-}: ClientLoaderFunctionArgs) {- const { supplierId } = params;-- if (!supplierId) {- return await serverLoader<typeof loader>();- }-- const queryKey = supplierContactsQuery(supplierId).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/purchasing.supplier-locations.$supplierId.ts b/apps/erp/app/routes/api+/purchasing.supplier-locations.$supplierId.tsindex 1d49649a53..faa4e732cc 100644--- a/apps/erp/app/routes/api+/purchasing.supplier-locations.$supplierId.ts+++ b/apps/erp/app/routes/api+/purchasing.supplier-locations.$supplierId.ts@@ -5,13 +5,10 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { data } from "react-router";import { getSupplierLocations } from "~/modules/purchasing";-import { supplierLocationsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const authorized = await requirePermissions(request, {@@ -39,28 +36,4 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return locations;}-export async function clientLoader({- serverLoader,- params-}: ClientLoaderFunctionArgs) {- const { supplierId } = params;-- if (!supplierId) {- return await serverLoader<typeof loader>();- }-- const queryKey = supplierLocationsQuery(supplierId).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/purchasing.supplier-processes.$processId.ts b/apps/erp/app/routes/api+/purchasing.supplier-processes.$processId.tsindex 0dfed56210..8291247bfa 100644--- a/apps/erp/app/routes/api+/purchasing.supplier-processes.$processId.ts+++ b/apps/erp/app/routes/api+/purchasing.supplier-processes.$processId.ts@@ -5,13 +5,10 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { data } from "react-router";import { getSupplierProcessesByProcess } from "~/modules/purchasing";-import { supplierProcessesQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const authorized = await requirePermissions(request, {});@@ -40,28 +37,4 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return processes;}-export async function clientLoader({- serverLoader,- params-}: ClientLoaderFunctionArgs) {- const { processId } = params;-- if (!processId) {- return await serverLoader<typeof loader>();- }-- const queryKey = supplierProcessesQuery(processId).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/purchasing.supplier-types.ts b/apps/erp/app/routes/api+/purchasing.supplier-types.tsindex 2272b4841c..3c3da43056 100644--- a/apps/erp/app/routes/api+/purchasing.supplier-types.ts+++ b/apps/erp/app/routes/api+/purchasing.supplier-types.ts@@ -3,12 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getSupplierTypesList } from "~/modules/purchasing";-import { getCompanyId, supplierTypesQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -18,25 +15,4 @@ export async function loader({ request }: LoaderFunctionArgs) {return await getSupplierTypesList(client, companyId);}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId) {- return await serverLoader<typeof loader>();- }-- const queryKey = supplierTypesQuery(companyId).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/quality.inspection-documents.$itemId.ts b/apps/erp/app/routes/api+/quality.inspection-documents.$itemId.tsindex d81d439fa8..8e657bbecf 100644--- a/apps/erp/app/routes/api+/quality.inspection-documents.$itemId.ts+++ b/apps/erp/app/routes/api+/quality.inspection-documents.$itemId.ts@@ -3,13 +3,10 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { data } from "react-router";import { getInspectionDocumentsForItem } from "~/modules/quality";-import { getCompanyId, inspectionDocumentsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -24,28 +21,4 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return await getInspectionDocumentsForItem(client, itemId, companyId);}-export async function clientLoader({- params,- serverLoader-}: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId || !params.itemId) {- return await serverLoader<typeof loader>();- }-- const query = inspectionDocumentsQuery(params.itemId, companyId);- const data = window?.clientCache?.getQueryData<- Awaited<ReturnType<typeof loader>>- >(query.queryKey);-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(query.queryKey, serverData);- return serverData;- }-- return data;-}--clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/quality.issue-types.ts b/apps/erp/app/routes/api+/quality.issue-types.tsindex 319c34b0a7..d74d0eca68 100644--- a/apps/erp/app/routes/api+/quality.issue-types.ts+++ b/apps/erp/app/routes/api+/quality.issue-types.ts@@ -3,12 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getIssueTypesList } from "~/modules/quality";-import { getCompanyId, issueTypesQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -18,25 +15,4 @@ export async function loader({ request }: LoaderFunctionArgs) {return await getIssueTypesList(client, companyId);}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId) {- return await serverLoader<typeof loader>();- }-- const queryKey = issueTypesQuery(companyId).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/resources.abilities.ts b/apps/erp/app/routes/api+/resources.abilities.tsindex b785b3d41c..221f9438c6 100644--- a/apps/erp/app/routes/api+/resources.abilities.ts+++ b/apps/erp/app/routes/api+/resources.abilities.ts@@ -3,12 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getAbilitiesList } from "~/modules/resources";-import { abilitiesQuery, getCompanyId } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -18,25 +15,4 @@ export async function loader({ request }: LoaderFunctionArgs) {return await getAbilitiesList(client, companyId);}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId) {- return await serverLoader<typeof loader>();- }-- const queryKey = abilitiesQuery(companyId).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/resources.locations.ts b/apps/erp/app/routes/api+/resources.locations.tsindex 69bf8d8e49..880525cce2 100644--- a/apps/erp/app/routes/api+/resources.locations.ts+++ b/apps/erp/app/routes/api+/resources.locations.ts@@ -3,12 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getLocationsList } from "~/modules/resources";-import { getCompanyId, locationsQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {});@@ -16,25 +13,4 @@ export async function loader({ request }: LoaderFunctionArgs) {return await getLocationsList(client, companyId);}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId) {- return await serverLoader<typeof loader>();- }-- const queryKey = locationsQuery(companyId).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/resources.processes.tsx b/apps/erp/app/routes/api+/resources.processes.tsxindex 21051b35c7..75d512c2a3 100644--- a/apps/erp/app/routes/api+/resources.processes.tsx+++ b/apps/erp/app/routes/api+/resources.processes.tsx@@ -3,12 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getProcessesList } from "~/modules/resources";-import { getCompanyId, processesQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {});@@ -16,25 +13,4 @@ export async function loader({ request }: LoaderFunctionArgs) {return await getProcessesList(client, companyId);}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId) {- return await serverLoader<typeof loader>();- }-- const queryKey = processesQuery(companyId).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/resources.work-centers.tsx b/apps/erp/app/routes/api+/resources.work-centers.tsxindex 70c4e8e184..ebc21b7072 100644--- a/apps/erp/app/routes/api+/resources.work-centers.tsx+++ b/apps/erp/app/routes/api+/resources.work-centers.tsx@@ -3,12 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getWorkCentersList } from "~/modules/resources";-import { getCompanyId, workCentersQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {});@@ -16,22 +13,4 @@ export async function loader({ request }: LoaderFunctionArgs) {return await getWorkCentersList(client, companyId);}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId) {- return await serverLoader<typeof loader>();- }-- const queryKey = workCentersQuery(companyId).queryKey;- const data = window?.clientCache?.getQueryData<typeof loader>(queryKey);-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/sales.customer-contacts.$customerId.ts b/apps/erp/app/routes/api+/sales.customer-contacts.$customerId.tsindex 6f61b9fda3..1e572a5e4f 100644--- a/apps/erp/app/routes/api+/sales.customer-contacts.$customerId.ts+++ b/apps/erp/app/routes/api+/sales.customer-contacts.$customerId.ts@@ -5,14 +5,10 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";-+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { data } from "react-router";import { getCustomerContacts } from "~/modules/sales";-import { customerContactsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const authorized = await requirePermissions(request, {@@ -40,25 +36,4 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return contacts;}-export async function clientLoader({- serverLoader,- params-}: ClientLoaderFunctionArgs) {- const { customerId } = params;-- if (!customerId) {- return await serverLoader<typeof loader>();- }-- const queryKey = customerContactsQuery(customerId).queryKey;- const data = window?.clientCache?.getQueryData<typeof loader>(queryKey);-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/sales.customer-locations.$customerId.ts b/apps/erp/app/routes/api+/sales.customer-locations.$customerId.tsindex 35c364538d..ac9855d9ca 100644--- a/apps/erp/app/routes/api+/sales.customer-locations.$customerId.ts+++ b/apps/erp/app/routes/api+/sales.customer-locations.$customerId.ts@@ -5,13 +5,10 @@import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { data } from "react-router";import { getCustomerLocations } from "~/modules/sales";-import { customerLocationsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const authorized = await requirePermissions(request, {@@ -39,28 +36,4 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return locations;}-export async function clientLoader({- serverLoader,- params-}: ClientLoaderFunctionArgs) {- const { customerId } = params;-- if (!customerId) {- return await serverLoader<typeof loader>();- }-- const queryKey = customerLocationsQuery(customerId).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/sales.customer-types.ts b/apps/erp/app/routes/api+/sales.customer-types.tsindex 15c4e3e5a7..d9a25b069d 100644--- a/apps/erp/app/routes/api+/sales.customer-types.ts+++ b/apps/erp/app/routes/api+/sales.customer-types.ts@@ -3,12 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getCustomerTypesList } from "~/modules/sales";-import { customerTypesQuery, getCompanyId } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -18,25 +15,4 @@ export async function loader({ request }: LoaderFunctionArgs) {return await getCustomerTypesList(client, companyId);}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId) {- return await serverLoader<typeof loader>();- }-- const queryKey = customerTypesQuery(companyId).queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>();diff --git a/apps/erp/app/routes/api+/timezones.ts b/apps/erp/app/routes/api+/timezones.tsindex ce76721129..de32a2d948 100644--- a/apps/erp/app/routes/api+/timezones.ts+++ b/apps/erp/app/routes/api+/timezones.ts@@ -3,30 +3,15 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader, RefreshRate } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getCachedTimezoneNames } from "~/modules/shared/shared.server";-import { timezonesQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {});return await getCachedTimezoneNames(client);}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const query = timezonesQuery();- const data = window?.clientCache?.getQueryData<- Awaited<ReturnType<typeof loader>>- >(query.queryKey);-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(query.queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>({+ staleTime: RefreshRate.Never+});diff --git a/apps/erp/app/routes/api+/webhook.tables.ts b/apps/erp/app/routes/api+/webhook.tables.tsindex 34641c8192..792b23f5bb 100644--- a/apps/erp/app/routes/api+/webhook.tables.ts+++ b/apps/erp/app/routes/api+/webhook.tables.ts@@ -3,12 +3,9 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ClientLoaderFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import { cachedClientLoader, RefreshRate } from "@carbon/query/cache";+import type { LoaderFunctionArgs } from "react-router";import { getWebhookTables } from "~/modules/settings/settings.service";-import { getCompanyId, webhookTablesQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {});@@ -16,25 +13,6 @@ export async function loader({ request }: LoaderFunctionArgs) {return await getWebhookTables(client);}-export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {- const companyId = getCompanyId();-- if (!companyId) {- return await serverLoader<typeof loader>();- }-- const queryKey = webhookTablesQuery().queryKey;- const data =- window?.clientCache?.getQueryData<Awaited<ReturnType<typeof loader>>>(- queryKey- );-- if (!data) {- const serverData = await serverLoader<typeof loader>();- window?.clientCache?.setQueryData(queryKey, serverData);- return serverData;- }-- return data;-}-clientLoader.hydrate = true;+export const clientLoader = cachedClientLoader<typeof loader>({+ staleTime: RefreshRate.Never+});diff --git a/apps/erp/app/routes/share+/quote.$id.tsx b/apps/erp/app/routes/share+/quote.$id.tsxindex b6833b3ab8..efe6348926 100644--- a/apps/erp/app/routes/share+/quote.$id.tsx+++ b/apps/erp/app/routes/share+/quote.$id.tsx@@ -13,6 +13,7 @@ import {CardContent,CardHeader,CardTitle,+ ClientOnly,cn,DisabledReason,generateHTML,@@ -1403,14 +1404,20 @@ const Quote = ({ data }: { data: QuoteData }) => {</div></CardContent></Card>- {termsHTML && (- <div- className="prose dark:prose-invert text-muted-foreground max-w-5xl mx-auto"- dangerouslySetInnerHTML={{- __html: termsHTML- }}- />- )}+ {/* generateHTML returns nothing on the server, so the server never+ renders this block: rendering it during hydration would not match. */}+ <ClientOnly>+ {() =>+ termsHTML ? (+ <div+ className="prose dark:prose-invert text-muted-foreground max-w-5xl mx-auto"+ dangerouslySetInnerHTML={{+ __html: termsHTML+ }}+ />+ ) : null+ }+ </ClientOnly>{confirmQuoteModal.isOpen && (<Modalopendiff --git a/apps/erp/app/routes/share+/supplier-quote.$id.tsx b/apps/erp/app/routes/share+/supplier-quote.$id.tsxindex 0c91c1f593..417be8343b 100644--- a/apps/erp/app/routes/share+/supplier-quote.$id.tsx+++ b/apps/erp/app/routes/share+/supplier-quote.$id.tsx@@ -4,6 +4,7 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";import { Input, TextArea, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import type { JSONContent } from "@carbon/react";import {Badge,@@ -44,7 +45,7 @@ import { useLingui } from "@lingui/react/macro";import { useLocale } from "@react-aria/i18n";import { motion } from "motion/react";import type { Dispatch, SetStateAction } from "react";-import { useEffect, useRef, useState } from "react";+import { useRef, useState } from "react";import {LuChevronRight,LuCirclePlus,@@ -52,7 +53,7 @@ import {LuPencil} from "react-icons/lu";import type { LoaderFunctionArgs } from "react-router";-import { useFetcher, useLoaderData, useParams } from "react-router";+import { useLoaderData, useParams } from "react-router";import { DateTime } from "~/components";import { externalSupplierQuoteValidator } from "~/modules/purchasing/purchasing.models";import {@@ -834,19 +835,19 @@ const Quote = ({const submitModal = useDisclosure();const declineModal = useDisclosure();- const fetcher = useFetcher<typeof action>();+ const fetcher = useAction<typeof action>({+ onSettled: () => {+ if (submitted.current) {+ submitModal.onClose();+ declineModal.onClose();+ submitted.current = false;+ }+ }+ });const submitted = useRef<boolean>(false);const mode = useMode();const logo = mode === "dark" ? company?.logoDark : company?.logoLight;- useEffect(() => {- if (fetcher.state === "idle" && submitted.current) {- submitModal.onClose();- declineModal.onClose();- submitted.current = false;- }- }, [fetcher.state, submitModal, declineModal]);-// Initialize selected lines from existing pricing dataconst [selectedLines, setSelectedLines] = useState<Record<string, Record<number, SelectedLine>>diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsxindex 67e8c19602..80b2e0eea1 100644--- a/apps/erp/app/routes/x+/_layout.tsx+++ b/apps/erp/app/routes/x+/_layout.tsx@@ -27,6 +27,8 @@ import { getLogger } from "@carbon/logger";import { getImplementationCheckStates } from "@carbon/onboarding/server";import type { PrintingSettings } from "@carbon/printing";import { PrintingProvider } from "@carbon/printing/ui";+import { RouteRealtime } from "@carbon/query";+import { setClientCompanyId } from "@carbon/query/cache";import {ItarEntityCertification,ItarEntityPendingBlock,@@ -373,6 +375,8 @@ export default function AuthenticatedRoute() {mfaEnrollment,sessionTimeout} = loaderData;+ // During render, not in an effect: clientLoaders and the first child read it.+ setClientCompanyId(company?.id ?? null, user?.id ?? null);// biome-ignore lint/correctness/useExhaustiveDependencies: runs each time the loader doesuseEffect(() => {shellLoadedAt = Date.now();@@ -513,6 +517,7 @@ export default function AuthenticatedRoute() {}}><RealtimeDataProvider>+ {company?.id && <RouteRealtime companyId={company.id} />}<TooltipProvider><SidebarProviderdefaultOpen={false}diff --git a/apps/erp/app/routes/x+/accounting+/charts.$accountId.tsx b/apps/erp/app/routes/x+/accounting+/charts.$accountId.tsxindex 5b028e9669..daab179fc2 100644--- a/apps/erp/app/routes/x+/accounting+/charts.$accountId.tsx+++ b/apps/erp/app/routes/x+/accounting+/charts.$accountId.tsx@@ -7,11 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData, useNavigate } from "react-router";import {accountValidator,@@ -26,7 +22,6 @@ import {} from "~/modules/accounting/ui/ChartOfAccounts";import { getCustomFields, setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { accountsQuery, getCompanyId } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyGroupId } = await requirePermissions(request, {@@ -140,14 +135,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- accountsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function EditChartOfAccountsRoute() {const { account, groupAccounts } = useLoaderData<typeof loader>();const navigate = useNavigate();diff --git a/apps/erp/app/routes/x+/accounting+/charts.delete.$accountId.tsx b/apps/erp/app/routes/x+/accounting+/charts.delete.$accountId.tsxindex c85d24e2fc..1dc4ea05ee 100644--- a/apps/erp/app/routes/x+/accounting+/charts.delete.$accountId.tsx+++ b/apps/erp/app/routes/x+/accounting+/charts.delete.$accountId.tsx@@ -7,16 +7,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";import { deleteAccount, getAccount } from "~/modules/accounting";import { path } from "~/utils/path";-import { accountsQuery, getCompanyId } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -72,14 +67,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- accountsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function DeleteAccountRoute() {const { accountId } = useParams();const { account } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/accounting+/charts.move.$accountId.tsx b/apps/erp/app/routes/x+/accounting+/charts.move.$accountId.tsxindex 779229e0b3..d16ff4124b 100644--- a/apps/erp/app/routes/x+/accounting+/charts.move.$accountId.tsx+++ b/apps/erp/app/routes/x+/accounting+/charts.move.$accountId.tsx@@ -7,11 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect, unchecked } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData, useNavigate } from "react-router";import {getAccount,@@ -20,7 +16,6 @@ import {} from "~/modules/accounting";import { MoveAccountForm } from "~/modules/accounting/ui/ChartOfAccounts";import { path } from "~/utils/path";-import { accountsQuery, getCompanyId } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyGroupId } = await requirePermissions(request, {@@ -152,14 +147,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- accountsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function MoveAccountRoute() {const { account, groupAccounts } = useLoaderData<typeof loader>();const navigate = useNavigate();diff --git a/apps/erp/app/routes/x+/accounting+/charts.new-group.tsx b/apps/erp/app/routes/x+/accounting+/charts.new-group.tsxindex 4f0d3ae12f..e48e480a25 100644--- a/apps/erp/app/routes/x+/accounting+/charts.new-group.tsx+++ b/apps/erp/app/routes/x+/accounting+/charts.new-group.tsx@@ -7,11 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import {data,useLoaderData,@@ -26,7 +22,6 @@ import {} from "~/modules/accounting";import { GroupAccountForm } from "~/modules/accounting/ui/ChartOfAccounts";import { path } from "~/utils/path";-import { accountsQuery, getCompanyId } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyGroupId } = await requirePermissions(request, {@@ -78,14 +73,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- accountsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function NewGroupAccountRoute() {const { groupAccounts } = useLoaderData<typeof loader>();const navigate = useNavigate();diff --git a/apps/erp/app/routes/x+/accounting+/charts.new.tsx b/apps/erp/app/routes/x+/accounting+/charts.new.tsxindex 73a1f96ab4..81bd3c132b 100644--- a/apps/erp/app/routes/x+/accounting+/charts.new.tsx+++ b/apps/erp/app/routes/x+/accounting+/charts.new.tsx@@ -7,11 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import {data,useLoaderData,@@ -27,7 +23,6 @@ import {import { ChartOfAccountForm } from "~/modules/accounting/ui/ChartOfAccounts";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { accountsQuery, getCompanyId } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyGroupId } = await requirePermissions(request, {@@ -88,14 +83,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- accountsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function NewAccountRoute() {const { groupAccounts } = useLoaderData<typeof loader>();const navigate = useNavigate();diff --git a/apps/erp/app/routes/x+/accounting+/exchange-rates.$currencyId.tsx b/apps/erp/app/routes/x+/accounting+/exchange-rates.$currencyId.tsxindex 9f9dd40ca0..758f608194 100644--- a/apps/erp/app/routes/x+/accounting+/exchange-rates.$currencyId.tsx+++ b/apps/erp/app/routes/x+/accounting+/exchange-rates.$currencyId.tsx@@ -7,11 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";import {currencyValidator,@@ -26,7 +22,6 @@ import {import { ExchangeRateForm } from "~/modules/accounting/ui/ExchangeRates";import { getCustomFields, setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";-import { currenciesQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -184,11 +179,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(currenciesQuery().queryKey, null);- return await serverAction();-}-export default function EditExchangeRateRoute() {const { currency, rate, rateSource, exchangeRateHistory } =useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/accounting+/payment-terms.$paymentTermId.tsx b/apps/erp/app/routes/x+/accounting+/payment-terms.$paymentTermId.tsxindex 183467539e..91cb59a92f 100644--- a/apps/erp/app/routes/x+/accounting+/payment-terms.$paymentTermId.tsx+++ b/apps/erp/app/routes/x+/accounting+/payment-terms.$paymentTermId.tsx@@ -8,11 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";import type { PaymentTermCalculationMethod } from "~/modules/accounting";import {@@ -23,7 +19,6 @@ import {import { PaymentTermForm } from "~/modules/accounting/ui/PaymentTerms";import { getCustomFields, setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";-import { getCompanyId, paymentTermsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -80,14 +75,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- paymentTermsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function EditPaymentTermsRoute() {const { paymentTerm } = useLoaderData<typeof loader>();const closeRoute = useCloseRoute();diff --git a/apps/erp/app/routes/x+/accounting+/payment-terms.delete.$paymentTermId.tsx b/apps/erp/app/routes/x+/accounting+/payment-terms.delete.$paymentTermId.tsxindex d27cd4fbdb..fe6ad9f48a 100644--- a/apps/erp/app/routes/x+/accounting+/payment-terms.delete.$paymentTermId.tsx+++ b/apps/erp/app/routes/x+/accounting+/payment-terms.delete.$paymentTermId.tsx@@ -7,16 +7,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";import { deletePaymentTerm, getPaymentTerm } from "~/modules/accounting";import { getParams, path } from "~/utils/path";-import { getCompanyId, paymentTermsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -72,14 +67,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- paymentTermsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function DeletePaymentTermRoute() {const { paymentTermId } = useParams();const { paymentTerm } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/accounting+/payment-terms.new.tsx b/apps/erp/app/routes/x+/accounting+/payment-terms.new.tsxindex ef3098b976..bf87520d69 100644--- a/apps/erp/app/routes/x+/accounting+/payment-terms.new.tsx+++ b/apps/erp/app/routes/x+/accounting+/payment-terms.new.tsx@@ -8,18 +8,13 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data } from "react-router";import type { PaymentTermCalculationMethod } from "~/modules/accounting";import { paymentTermValidator, upsertPaymentTerm } from "~/modules/accounting";import { PaymentTermForm } from "~/modules/accounting/ui/PaymentTerms";import { setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";-import { getCompanyId, paymentTermsQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {await requirePermissions(request, {@@ -71,14 +66,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- paymentTermsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function NewPaymentTermsRoute() {const closeRoute = useCloseRoute();const initialValues = {diff --git a/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsxindex 20fbc21a37..16fff0d311 100644--- a/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/consumable+/$itemId.inventory.tsx@@ -51,8 +51,21 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const searchParams = new URLSearchParams(url.search);let locationId = searchParams.get("location");- if (!locationId) {- const userDefaults = await getUserDefaults(client, userId, companyId);+ // Three waits at most: what needs no location is read while the+ // default location is, and everything that needs it is read together.+ const [userDefaults, shelfLife, bomHasShelfLifeManagedInput, rulesData] =+ await Promise.all([+ locationId ? null : getUserDefaults(client, userId, companyId),+ getItemShelfLife(client, itemId),+ getBomHasShelfLifeManagedInput(client, itemId, companyId),+ getStorageRulesDataForTarget(client, {+ targetType: "item",+ targetId: itemId,+ companyId+ })+ ]);++ if (userDefaults) {if (userDefaults.error) {throw redirect(path.to.consumable(itemId),@@ -80,9 +93,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {locationId = locations.data?.[0].id as string;}- let [consumableInventory] = await Promise.all([- getPickMethod(client, itemId, companyId, locationId)- ]);+ let [consumableInventory, quantities, itemStorageUnitQuantities] =+ await Promise.all([+ getPickMethod(client, itemId, companyId, locationId),+ getItemQuantities(client, itemId, companyId, locationId),+ getItemStorageUnitQuantities(client, itemId, companyId, locationId)+ ]);if (consumableInventory.error || !consumableInventory.data) {const insertPickMethod = await upsertPickMethod(client, {@@ -123,12 +139,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}}- const quantities = await getItemQuantities(- client,- itemId,- companyId,- locationId- );if (quantities.error) {throw redirect(path.to.items,@@ -139,12 +149,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- const itemStorageUnitQuantities = await getItemStorageUnitQuantities(- client,- itemId,- companyId,- locationId- );if (itemStorageUnitQuantities.error || !itemStorageUnitQuantities.data) {throw redirect(path.to.items,@@ -160,21 +164,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {(row) => row.trackedEntityId);- const [- shelfLife,- bomHasShelfLifeManagedInput,- trackedEntityExpirations,- rulesData- ] = await Promise.all([- getItemShelfLife(client, itemId),- getBomHasShelfLifeManagedInput(client, itemId, companyId),- getTrackedEntityExpirations(client, trackedEntityIds),- getStorageRulesDataForTarget(client, {- targetType: "item",- targetId: itemId,- companyId- })- ]);+ const trackedEntityExpirations = await getTrackedEntityExpirations(+ client,+ trackedEntityIds+ );return {consumableInventory: consumableInventory.data,diff --git a/apps/erp/app/routes/x+/customer+/$customerId.contacts.$customerContactId.tsx b/apps/erp/app/routes/x+/customer+/$customerId.contacts.$customerContactId.tsxindex 2764eb9814..16707b25e1 100644--- a/apps/erp/app/routes/x+/customer+/$customerId.contacts.$customerContactId.tsx+++ b/apps/erp/app/routes/x+/customer+/$customerId.contacts.$customerContactId.tsx@@ -13,11 +13,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import {customerContactValidator,@@ -27,7 +23,6 @@ import {import { CustomerContactForm } from "~/modules/sales/ui/Customer";import { getCustomFields, setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { customerContactsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -104,20 +99,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({- serverAction,- params-}: ClientActionFunctionArgs) {- const { customerId } = params;- if (customerId) {- window.clientCache?.setQueryData(- customerContactsQuery(customerId).queryKey,- null- );- }- return await serverAction();-}-export default function EditCustomerContactRoute() {const { contact } = useLoaderData<typeof loader>();const navigate = useNavigate();diff --git a/apps/erp/app/routes/x+/customer+/$customerId.contacts.delete.$customerContactId.tsx b/apps/erp/app/routes/x+/customer+/$customerId.contacts.delete.$customerContactId.tsxindex b7d82e3ba7..6d5c71d21e 100644--- a/apps/erp/app/routes/x+/customer+/$customerId.contacts.delete.$customerContactId.tsx+++ b/apps/erp/app/routes/x+/customer+/$customerId.contacts.delete.$customerContactId.tsx@@ -6,13 +6,9 @@ import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { deleteCustomerContact } from "~/modules/sales";import { path } from "~/utils/path";-import { customerContactsQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {const { client } = await requirePermissions(request, {@@ -49,17 +45,3 @@ export async function action({ request, params }: ActionFunctionArgs) {await flash(request, success("Successfully deleted customer contact")));}--export async function clientAction({- serverAction,- params-}: ClientActionFunctionArgs) {- const { customerId } = params;- if (customerId) {- window.clientCache?.setQueryData(- customerContactsQuery(customerId).queryKey,- null- );- }- return await serverAction();-}diff --git a/apps/erp/app/routes/x+/customer+/$customerId.contacts.new.tsx b/apps/erp/app/routes/x+/customer+/$customerId.contacts.new.tsxindex 2ada274128..55a18cfd6f 100644--- a/apps/erp/app/routes/x+/customer+/$customerId.contacts.new.tsx+++ b/apps/erp/app/routes/x+/customer+/$customerId.contacts.new.tsx@@ -8,10 +8,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { data, useNavigate, useParams } from "react-router";import {customerContactValidator,@@ -21,7 +18,6 @@ import { CustomerContactForm } from "~/modules/sales/ui/Customer";import { requireCompanyRecord } from "~/modules/shared/shared.server";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { customerContactsQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -126,21 +122,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({- serverAction,- params-}: ClientActionFunctionArgs) {- const { customerId } = params;-- if (customerId) {- window.clientCache?.setQueryData(- customerContactsQuery(customerId).queryKey,- null- );- }- return await serverAction();-}-export default function CustomerContactsNewRoute() {const navigate = useNavigate();const { customerId } = useParams();diff --git a/apps/erp/app/routes/x+/customer+/$customerId.locations.$customerLocationId.tsx b/apps/erp/app/routes/x+/customer+/$customerId.locations.$customerLocationId.tsxindex 43d0df2408..729dc9e035 100644--- a/apps/erp/app/routes/x+/customer+/$customerId.locations.$customerLocationId.tsx+++ b/apps/erp/app/routes/x+/customer+/$customerId.locations.$customerLocationId.tsx@@ -13,11 +13,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import {customerLocationValidator,@@ -27,7 +23,6 @@ import {import { CustomerLocationForm } from "~/modules/sales/ui/Customer";import { getCustomFields, setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { customerLocationsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -101,20 +96,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({- serverAction,- params-}: ClientActionFunctionArgs) {- const { customerId } = params;- if (customerId) {- window.clientCache?.setQueryData(- customerLocationsQuery(customerId).queryKey,- null- );- }- return await serverAction();-}-export default function EditCustomerLocationRoute() {const { location } = useLoaderData<typeof loader>();const navigate = useNavigate();diff --git a/apps/erp/app/routes/x+/customer+/$customerId.locations.delete.$customerLocationId.tsx b/apps/erp/app/routes/x+/customer+/$customerId.locations.delete.$customerLocationId.tsxindex ab0a7503bf..d5970c317b 100644--- a/apps/erp/app/routes/x+/customer+/$customerId.locations.delete.$customerLocationId.tsx+++ b/apps/erp/app/routes/x+/customer+/$customerId.locations.delete.$customerLocationId.tsx@@ -6,13 +6,9 @@ import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { deleteCustomerLocation } from "~/modules/sales";import { path } from "~/utils/path";-import { customerLocationsQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {const { client } = await requirePermissions(request, {@@ -52,17 +48,3 @@ export async function action({ request, params }: ActionFunctionArgs) {await flash(request, success("Successfully deleted customer location")));}--export async function clientAction({- serverAction,- params-}: ClientActionFunctionArgs) {- const { customerId } = params;- if (customerId) {- window.clientCache?.setQueryData(- customerLocationsQuery(customerId).queryKey,- null- );- }- return await serverAction();-}diff --git a/apps/erp/app/routes/x+/customer+/$customerId.locations.new.tsx b/apps/erp/app/routes/x+/customer+/$customerId.locations.new.tsxindex 3767473313..4c3cc492bd 100644--- a/apps/erp/app/routes/x+/customer+/$customerId.locations.new.tsx+++ b/apps/erp/app/routes/x+/customer+/$customerId.locations.new.tsx@@ -7,10 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { data, useNavigate, useParams } from "react-router";import { useUser } from "~/hooks";import {@@ -20,7 +17,6 @@ import {import { CustomerLocationForm } from "~/modules/sales/ui/Customer";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { customerLocationsQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -75,20 +71,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({- serverAction,- params-}: ClientActionFunctionArgs) {- const { customerId } = params;- if (customerId) {- window.clientCache?.setQueryData(- customerLocationsQuery(customerId).queryKey,- null- );- }- return await serverAction();-}-export default function CustomerLocationsNewRoute() {const navigate = useNavigate();const { company } = useUser();diff --git a/apps/erp/app/routes/x+/inspection+/$id.tsx b/apps/erp/app/routes/x+/inspection+/$id.tsxindex 9a2b8c7830..5fd16ff662 100644--- a/apps/erp/app/routes/x+/inspection+/$id.tsx+++ b/apps/erp/app/routes/x+/inspection+/$id.tsx@@ -43,6 +43,10 @@ import { detailBreadcrumb, type Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {+ realtime: [+ { table: "inspection", column: "id", param: "id" },+ { table: "inspectionSample", column: "inspectionId", param: "id" }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`Inspections`, to: path.to.inspections },(data) => data?.inspection?.inspectionIddiff --git a/apps/erp/app/routes/x+/inspection-document+/$id.delete.tsx b/apps/erp/app/routes/x+/inspection-document+/$id.delete.tsxindex 7b7cec4a33..910eca5824 100644--- a/apps/erp/app/routes/x+/inspection-document+/$id.delete.tsx+++ b/apps/erp/app/routes/x+/inspection-document+/$id.delete.tsx@@ -8,13 +8,9 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import { storage } from "@carbon/files";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { deleteInspectionDocument } from "~/modules/quality";import { path } from "~/utils/path";-import { invalidateInspectionDocuments } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -48,8 +44,3 @@ export async function action({ request, params }: ActionFunctionArgs) {await flash(request, success("Inspection plan deleted")));}--export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- invalidateInspectionDocuments();- return await serverAction();-}diff --git a/apps/erp/app/routes/x+/inspection-document+/$id.save.tsx b/apps/erp/app/routes/x+/inspection-document+/$id.save.tsxindex 79d62199ef..73445b9d16 100644--- a/apps/erp/app/routes/x+/inspection-document+/$id.save.tsx+++ b/apps/erp/app/routes/x+/inspection-document+/$id.save.tsx@@ -4,10 +4,7 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import {saveInspectionDocumentAtomic,@@ -28,7 +25,6 @@ import {resolveInspectionFeaturePayloadIds,translateLegacyInspectionSavePayload} from "~/modules/quality/quality.server";-import { invalidateInspectionDocuments } from "~/utils/react-query";function getErrorMessage(error: unknown, fallback: string) {if (error instanceof Error) return error.message;@@ -254,8 +250,3 @@ export async function action({ request, params }: ActionFunctionArgs) {balloons: unknown[];};}--export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- invalidateInspectionDocuments();- return await serverAction();-}diff --git a/apps/erp/app/routes/x+/inspection-document+/$id.update-name.tsx b/apps/erp/app/routes/x+/inspection-document+/$id.update-name.tsxindex 529df46a34..8ac51b6158 100644--- a/apps/erp/app/routes/x+/inspection-document+/$id.update-name.tsx+++ b/apps/erp/app/routes/x+/inspection-document+/$id.update-name.tsx@@ -4,11 +4,7 @@import { assertIsPost } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";-import { invalidateInspectionDocuments } from "~/utils/react-query";+import type { ActionFunctionArgs } from "react-router";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -37,8 +33,3 @@ export async function action({ request, params }: ActionFunctionArgs) {return { success: true };}--export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- invalidateInspectionDocuments();- return await serverAction();-}diff --git a/apps/erp/app/routes/x+/inventory+/inventory-count.tsx b/apps/erp/app/routes/x+/inventory+/inventory-count.tsxindex 226ae01cbd..8d4d170aa0 100644--- a/apps/erp/app/routes/x+/inventory+/inventory-count.tsx+++ b/apps/erp/app/routes/x+/inventory+/inventory-count.tsx@@ -20,6 +20,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["inventoryCount"],breadcrumb: msg`Inventory Count`,to: path.to.inventoryCounts};diff --git a/apps/erp/app/routes/x+/inventory+/picking-lists.tsx b/apps/erp/app/routes/x+/inventory+/picking-lists.tsxindex 1aef47a1ef..bdedb0c684 100644--- a/apps/erp/app/routes/x+/inventory+/picking-lists.tsx+++ b/apps/erp/app/routes/x+/inventory+/picking-lists.tsx@@ -18,6 +18,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["pickingList"],breadcrumb: msg`Picking Lists`,to: path.to.pickingLists};diff --git a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.details.tsx b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.details.tsxindex e1421ec2b9..6c2dedde5b 100644--- a/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.details.tsx+++ b/apps/erp/app/routes/x+/inventory+/quantities+/$itemId.details.tsx@@ -46,8 +46,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const searchParams = new URLSearchParams(url.search);let locationId = searchParams.get("location");- if (!locationId) {- const userDefaults = await getUserDefaults(client, userId, companyId);+ // Three waits at most: what needs no location is read while the default+ // location is, and everything else is read together.+ const [userDefaults, item, itemShelfLife, makeMethods] = await Promise.all([+ locationId ? null : getUserDefaults(client, userId, companyId),+ getItem(client, itemId),+ getItemShelfLife(client, itemId),+ getMakeMethods(client, itemId, companyId)+ ]);++ if (userDefaults) {if (userDefaults.error) {throw redirect(path.to.inventory,@@ -75,8 +83,31 @@ export async function loader({ request, params }: LoaderFunctionArgs) {locationId = locations.data?.[0].id as string;}- let [pickMethod] = await Promise.all([- getPickMethod(client, itemId, companyId, locationId)+ // Manufacturing data, for manufactured parts only+ const makeMethod =+ item.data && item.data.replenishmentSystem !== "Buy"+ ? (makeMethods.data?.find((m) => m.status === "Active") ??+ makeMethods.data?.[0])+ : undefined;++ let [+ pickMethod,+ quantities,+ itemStorageUnitQuantities,+ fullMethod,+ methodMaterials,+ methodOperations,+ operationTags+ ] = await Promise.all([+ getPickMethod(client, itemId, companyId, locationId),+ getItemQuantities(client, itemId, companyId, locationId),+ getItemStorageUnitQuantities(client, itemId, companyId, locationId),+ makeMethod ? getMakeMethodById(client, makeMethod.id, companyId) : null,+ makeMethod ? getMethodMaterialsByMakeMethod(client, makeMethod.id) : null,+ makeMethod+ ? getMethodOperationsByMakeMethodId(client, makeMethod.id)+ : null,+ makeMethod ? getTagsList(client, companyId, "operation") : null]);if (pickMethod.error || !pickMethod.data) {@@ -113,10 +144,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}}- const [quantities, item] = await Promise.all([- getItemQuantities(client, itemId, companyId, locationId),- getItem(client, itemId)- ]);if (quantities.error) {throw redirect(path.to.inventory,@@ -131,12 +158,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- const itemStorageUnitQuantities = await getItemStorageUnitQuantities(- client,- itemId,- companyId,- locationId- );if (itemStorageUnitQuantities.error || !itemStorageUnitQuantities.data) {throw redirect(path.to.inventory,@@ -156,56 +177,34 @@ export async function loader({ request, params }: LoaderFunctionArgs) {itemStorageUnitQuantities.data,(row) => row.trackedEntityId);- const [itemShelfLife, trackedEntityExpirations] = await Promise.all([- getItemShelfLife(client, itemId),- getTrackedEntityExpirations(client, trackedEntityIds)- ]);+ const trackedEntityExpirations = await getTrackedEntityExpirations(+ client,+ trackedEntityIds+ );- // Load manufacturing data for manufactured partslet methodData = null;let tags: { name: string }[] = [];- if (item.data.replenishmentSystem !== "Buy") {- const makeMethods = await getMakeMethods(client, itemId, companyId);- const makeMethod =- makeMethods.data?.find((m) => m.status === "Active") ??- makeMethods.data?.[0];-- if (makeMethod) {- const fullMethod = await getMakeMethodById(- client,- makeMethod.id,- companyId- );- if (!fullMethod.error && fullMethod.data) {- const [methodMaterials, methodOperations, operationTags] =- await Promise.all([- getMethodMaterialsByMakeMethod(client, fullMethod.data.id),- getMethodOperationsByMakeMethodId(client, fullMethod.data.id),- getTagsList(client, companyId, "operation")- ]);-- methodData = {- makeMethod: fullMethod.data,- methodMaterials:- methodMaterials.data?.map((m) => ({- ...m,- description: m.item?.name ?? "",- methodType: m.methodType as MethodType,- itemType: m.itemType as MethodItemType- })) ?? [],- methodOperations:- methodOperations.data?.map((operation) => ({- ...operation,- workCenterId: operation.workCenterId ?? undefined,- operationSupplierProcessId:- operation.operationSupplierProcessId ?? undefined,- workInstruction: operation.workInstruction as JSONContent | null- })) ?? []- };- tags = operationTags.data ?? [];- }- }+ if (fullMethod && !fullMethod.error && fullMethod.data) {+ methodData = {+ makeMethod: fullMethod.data,+ methodMaterials:+ methodMaterials?.data?.map((m) => ({+ ...m,+ description: m.item?.name ?? "",+ methodType: m.methodType as MethodType,+ itemType: m.itemType as MethodItemType+ })) ?? [],+ methodOperations:+ methodOperations?.data?.map((operation) => ({+ ...operation,+ workCenterId: operation.workCenterId ?? undefined,+ operationSupplierProcessId:+ operation.operationSupplierProcessId ?? undefined,+ workInstruction: operation.workInstruction as JSONContent | null+ })) ?? []+ };+ tags = operationTags?.data ?? [];}return {diff --git a/apps/erp/app/routes/x+/inventory+/quantities.tsx b/apps/erp/app/routes/x+/inventory+/quantities.tsxindex be4dd3c29c..2cb50d35e3 100644--- a/apps/erp/app/routes/x+/inventory+/quantities.tsx+++ b/apps/erp/app/routes/x+/inventory+/quantities.tsx@@ -27,9 +27,14 @@ import {import { getLocationsList } from "~/modules/resources";import { getTagsList } from "~/modules/shared";import { getUserDefaults } from "~/modules/users/users.server";+import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";+export const handle: Handle = {+ realtime: ["itemStockQuantities"]+};+export const shouldRevalidate: ShouldRevalidateFunction = (args) =>isUnaffectedByNavigation(args, { search: "all" })? falsediff --git a/apps/erp/app/routes/x+/inventory+/receipts.tsx b/apps/erp/app/routes/x+/inventory+/receipts.tsxindex 0aaf7a00f6..a90698643c 100644--- a/apps/erp/app/routes/x+/inventory+/receipts.tsx+++ b/apps/erp/app/routes/x+/inventory+/receipts.tsx@@ -16,6 +16,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["receipt"],breadcrumb: msg`Receipts`,to: path.to.receipts};diff --git a/apps/erp/app/routes/x+/inventory+/shipments.tsx b/apps/erp/app/routes/x+/inventory+/shipments.tsxindex dcd9859875..9331fae029 100644--- a/apps/erp/app/routes/x+/inventory+/shipments.tsx+++ b/apps/erp/app/routes/x+/inventory+/shipments.tsx@@ -17,6 +17,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["shipment"],breadcrumb: msg`Shipments`,to: path.to.shipments};diff --git a/apps/erp/app/routes/x+/inventory+/shipping-methods.$shippingMethodId.tsx b/apps/erp/app/routes/x+/inventory+/shipping-methods.$shippingMethodId.tsxindex 5a376f6bdb..bce009c17d 100644--- a/apps/erp/app/routes/x+/inventory+/shipping-methods.$shippingMethodId.tsx+++ b/apps/erp/app/routes/x+/inventory+/shipping-methods.$shippingMethodId.tsx@@ -8,11 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";import type { ShippingCarrier } from "~/modules/inventory";import {@@ -23,7 +19,6 @@ import {} from "~/modules/inventory";import { getCustomFields, setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";-import { getCompanyId, shippingMethodsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -82,14 +77,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- shippingMethodsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function EditShippingMethodsRoute() {const { shippingMethod } = useLoaderData<typeof loader>();const closeRoute = useCloseRoute();diff --git a/apps/erp/app/routes/x+/inventory+/shipping-methods.delete.$shippingMethodId.tsx b/apps/erp/app/routes/x+/inventory+/shipping-methods.delete.$shippingMethodId.tsxindex f61d240526..dd5dc3c83b 100644--- a/apps/erp/app/routes/x+/inventory+/shipping-methods.delete.$shippingMethodId.tsx+++ b/apps/erp/app/routes/x+/inventory+/shipping-methods.delete.$shippingMethodId.tsx@@ -7,16 +7,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";import { deleteShippingMethod, getShippingMethod } from "~/modules/inventory";import { getParams, path } from "~/utils/path";-import { getCompanyId, shippingMethodsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -72,14 +67,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- shippingMethodsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function DeleteShippingMethodRoute() {const { shippingMethodId } = useParams();if (!shippingMethodId) throw notFound("shippingMethodId not found");diff --git a/apps/erp/app/routes/x+/inventory+/shipping-methods.new.tsx b/apps/erp/app/routes/x+/inventory+/shipping-methods.new.tsxindex 9677ef906d..92a6873fad 100644--- a/apps/erp/app/routes/x+/inventory+/shipping-methods.new.tsx+++ b/apps/erp/app/routes/x+/inventory+/shipping-methods.new.tsx@@ -8,11 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data } from "react-router";import type { ShippingCarrier } from "~/modules/inventory";import {@@ -22,7 +18,6 @@ import {} from "~/modules/inventory";import { setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";-import { getCompanyId, shippingMethodsQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {await requirePermissions(request, {@@ -76,14 +71,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- shippingMethodsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function NewShippingMethodsRoute() {const closeRoute = useCloseRoute();diff --git a/apps/erp/app/routes/x+/inventory+/stock-movements.tsx b/apps/erp/app/routes/x+/inventory+/stock-movements.tsxindex 94d5b8ca3b..043e6cffdf 100644--- a/apps/erp/app/routes/x+/inventory+/stock-movements.tsx+++ b/apps/erp/app/routes/x+/inventory+/stock-movements.tsx@@ -20,6 +20,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["itemLedger"],breadcrumb: msg`Movements`,to: path.to.stockMovements};diff --git a/apps/erp/app/routes/x+/inventory+/stock-transfers.tsx b/apps/erp/app/routes/x+/inventory+/stock-transfers.tsxindex d0b9a541f5..c28cbfdab1 100644--- a/apps/erp/app/routes/x+/inventory+/stock-transfers.tsx+++ b/apps/erp/app/routes/x+/inventory+/stock-transfers.tsx@@ -22,6 +22,7 @@ import { getGenericQueryFilters } from "~/utils/query";const logger = getLogger("erp", "stock-transfers");export const handle: Handle = {+ realtime: ["stockTransfer"],breadcrumb: msg`Stock Transfers`,to: path.to.stockTransfers};diff --git a/apps/erp/app/routes/x+/inventory+/storage-units.$storageUnitId.tsx b/apps/erp/app/routes/x+/inventory+/storage-units.$storageUnitId.tsxindex 0d509b1f15..ac12353e86 100644--- a/apps/erp/app/routes/x+/inventory+/storage-units.$storageUnitId.tsx+++ b/apps/erp/app/routes/x+/inventory+/storage-units.$storageUnitId.tsx@@ -8,11 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, Outlet, useLoaderData } from "react-router";import {getEffectiveWorkCenterId,@@ -24,7 +20,6 @@ import {import { getWorkCentersList } from "~/modules/resources";import { getCustomFields, setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";-import { getCompanyId, storageUnitsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -102,28 +97,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({- request,- serverAction-}: ClientActionFunctionArgs) {- const companyId = getCompanyId();-- const formData = await request.clone().formData();- const validation = await validator(storageUnitValidator).validate(formData);-- if (validation.error) {- return validationError(validation.error);- }-- if (companyId && validation.data.locationId) {- window.clientCache?.setQueryData(- storageUnitsQuery(companyId, validation.data.locationId).queryKey,- null- );- }- return await serverAction();-}-export default function EditStorageUnitRoute() {const { storageUnit, inheritedWorkCenter } = useLoaderData<typeof loader>();const closeRoute = useCloseRoute();diff --git a/apps/erp/app/routes/x+/inventory+/storage-units.delete.$storageUnitId.tsx b/apps/erp/app/routes/x+/inventory+/storage-units.delete.$storageUnitId.tsxindex 9776adb928..9ccc771f4c 100644--- a/apps/erp/app/routes/x+/inventory+/storage-units.delete.$storageUnitId.tsx+++ b/apps/erp/app/routes/x+/inventory+/storage-units.delete.$storageUnitId.tsx@@ -5,6 +5,7 @@import { error, notFound, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";+import { useAction } from "@carbon/query";import {Button,Checkbox,@@ -18,18 +19,9 @@ import {} from "@carbon/react";import { redirect } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";-import { useEffect, useRef, useState } from "react";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";-import {- useFetcher,- useLoaderData,- useNavigate,- useParams-} from "react-router";+import { useRef, useState } from "react";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { useLoaderData, useNavigate, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";import {deleteStorageUnit,@@ -37,7 +29,6 @@ import {getStorageUnit} from "~/modules/inventory";import { getParams, path } from "~/utils/path";-import { getCompanyId } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -114,19 +105,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- // Nothing to validate — ConfirmDelete-style forms only carry the cascade- // flag. Invalidate the cached list so the table refreshes after.- const companyId = getCompanyId();- window.clientCache?.invalidateQueries({- predicate: (query) => {- const queryKey = query.queryKey as string[];- return queryKey[0] === "storageUnits" && queryKey[1] === companyId;- }- });- return await serverAction();-}-export default function DeleteStorageUnitRoute() {const { storageUnitId } = useParams();if (!storageUnitId) throw notFound("storageUnitId not found");@@ -174,16 +152,16 @@ function DeleteWithCascadeModal({onCancel: () => void;}) {const { t } = useLingui();- const fetcher = useFetcher<{}>();+ const fetcher = useAction<{}>({+ onSettled: () => {+ if (submitted.current) {+ submitted.current = false;+ }+ }+ });const [cascade, setCascade] = useState(false);const submitted = useRef(false);- useEffect(() => {- if (fetcher.state === "idle" && submitted.current) {- submitted.current = false;- }- }, [fetcher.state]);-const disabled = !cascade;return (diff --git a/apps/erp/app/routes/x+/inventory+/storage-units.new.tsx b/apps/erp/app/routes/x+/inventory+/storage-units.new.tsxindex cd6fa71fef..6fd80ba309 100644--- a/apps/erp/app/routes/x+/inventory+/storage-units.new.tsx+++ b/apps/erp/app/routes/x+/inventory+/storage-units.new.tsx@@ -8,11 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useSearchParams } from "react-router";import { useUser } from "~/hooks";import {@@ -22,7 +18,6 @@ import {} from "~/modules/inventory";import { setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";-import { getCompanyId, storageUnitsQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {await requirePermissions(request, {@@ -74,28 +69,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({- request,- serverAction-}: ClientActionFunctionArgs) {- const companyId = getCompanyId();-- const formData = await request.clone().formData();- const validation = await validator(storageUnitValidator).validate(formData);-- if (validation.error) {- return validationError(validation.error);- }-- if (companyId && validation.data.locationId) {- window.clientCache?.setQueryData(- storageUnitsQuery(companyId, validation.data.locationId).queryKey,- null- );- }- return await serverAction();-}-export default function NewStorageUnitRoute() {const closeRoute = useCloseRoute();const [searchParams] = useSearchParams();diff --git a/apps/erp/app/routes/x+/inventory+/tracked-entities.tsx b/apps/erp/app/routes/x+/inventory+/tracked-entities.tsxindex d77bd87d32..0f6e9b1a75 100644--- a/apps/erp/app/routes/x+/inventory+/tracked-entities.tsx+++ b/apps/erp/app/routes/x+/inventory+/tracked-entities.tsx@@ -18,6 +18,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["trackedEntity"],breadcrumb: msg`Tracked Entities`,to: path.to.trackedEntities};diff --git a/apps/erp/app/routes/x+/inventory+/warehouse-transfers.tsx b/apps/erp/app/routes/x+/inventory+/warehouse-transfers.tsxindex 9f380995fb..6a6a3d78de 100644--- a/apps/erp/app/routes/x+/inventory+/warehouse-transfers.tsx+++ b/apps/erp/app/routes/x+/inventory+/warehouse-transfers.tsx@@ -17,6 +17,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["warehouseTransfer"],breadcrumb: msg`Warehouse Transfers`,to: path.to.warehouseTransfers};diff --git a/apps/erp/app/routes/x+/inventory-count+/$id.tsx b/apps/erp/app/routes/x+/inventory-count+/$id.tsxindex a231d6fcce..a6e434ce69 100644--- a/apps/erp/app/routes/x+/inventory-count+/$id.tsx+++ b/apps/erp/app/routes/x+/inventory-count+/$id.tsx@@ -31,6 +31,10 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: [+ { table: "inventoryCount", column: "id", param: "id" },+ { table: "inventoryCountLine", column: "inventoryCountId", param: "id" }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`Inventory Count`, to: path.to.inventoryCounts },(data) => data?.inventoryCount?.inventoryCountIddiff --git a/apps/erp/app/routes/x+/invoicing+/payables.tsx b/apps/erp/app/routes/x+/invoicing+/payables.tsxindex 4a28b0cd99..a432ef3c4b 100644--- a/apps/erp/app/routes/x+/invoicing+/payables.tsx+++ b/apps/erp/app/routes/x+/invoicing+/payables.tsx@@ -22,6 +22,7 @@ import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {+ realtime: ["purchaseInvoice", "payment"],breadcrumb: msg`Payables`,to: path.to.payables,module: "invoicing"diff --git a/apps/erp/app/routes/x+/invoicing+/payments.tsx b/apps/erp/app/routes/x+/invoicing+/payments.tsxindex 1c059782c2..e16dedad61 100644--- a/apps/erp/app/routes/x+/invoicing+/payments.tsx+++ b/apps/erp/app/routes/x+/invoicing+/payments.tsx@@ -15,6 +15,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["payment"],breadcrumb: msg`Payments`,to: path.to.payments,module: "invoicing"diff --git a/apps/erp/app/routes/x+/invoicing+/purchasing.tsx b/apps/erp/app/routes/x+/invoicing+/purchasing.tsxindex 66745fb2fa..fcff17a47a 100644--- a/apps/erp/app/routes/x+/invoicing+/purchasing.tsx+++ b/apps/erp/app/routes/x+/invoicing+/purchasing.tsx@@ -19,6 +19,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["purchaseInvoice"],breadcrumb: msg`Purchasing Invoices`,to: path.to.invoicingPurchasing,module: "invoicing"diff --git a/apps/erp/app/routes/x+/invoicing+/receivables.tsx b/apps/erp/app/routes/x+/invoicing+/receivables.tsxindex c8365bae7e..ac596802f9 100644--- a/apps/erp/app/routes/x+/invoicing+/receivables.tsx+++ b/apps/erp/app/routes/x+/invoicing+/receivables.tsx@@ -22,6 +22,7 @@ import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {+ realtime: ["salesInvoice", "payment"],breadcrumb: msg`Receivables`,to: path.to.receivables,module: "invoicing"diff --git a/apps/erp/app/routes/x+/invoicing+/sales.tsx b/apps/erp/app/routes/x+/invoicing+/sales.tsxindex a8b6648774..a968a8a52d 100644--- a/apps/erp/app/routes/x+/invoicing+/sales.tsx+++ b/apps/erp/app/routes/x+/invoicing+/sales.tsx@@ -17,6 +17,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["salesInvoice"],breadcrumb: msg`Sales Invoices`,to: path.to.invoicingSales,module: "invoicing"diff --git a/apps/erp/app/routes/x+/issue+/$id.tsx b/apps/erp/app/routes/x+/issue+/$id.tsxindex 3e14d8e300..6250d89b83 100644--- a/apps/erp/app/routes/x+/issue+/$id.tsx+++ b/apps/erp/app/routes/x+/issue+/$id.tsx@@ -42,6 +42,15 @@ import { path } from "~/utils/path";const logger = getLogger("erp", "issue-detail");export const handle: Handle = {+ realtime: [+ { table: "nonConformance", column: "id", param: "id" },+ {+ table: "nonConformanceActionTask",+ column: "nonConformanceId",+ param: "id"+ },+ { table: "nonConformanceItem", column: "nonConformanceId", param: "id" }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`Issues`, to: path.to.issues },(data) => data?.nonConformance?.nonConformanceIddiff --git a/apps/erp/app/routes/x+/items+/consumables.tsx b/apps/erp/app/routes/x+/items+/consumables.tsxindex 197859ce1d..14d06911b7 100644--- a/apps/erp/app/routes/x+/items+/consumables.tsx+++ b/apps/erp/app/routes/x+/items+/consumables.tsx@@ -18,6 +18,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["item"],breadcrumb: msg`Consumables`,to: path.to.consumables};diff --git a/apps/erp/app/routes/x+/items+/groups.$groupId.tsx b/apps/erp/app/routes/x+/items+/groups.$groupId.tsxindex a88258a51a..c84cebafb0 100644--- a/apps/erp/app/routes/x+/items+/groups.$groupId.tsx+++ b/apps/erp/app/routes/x+/items+/groups.$groupId.tsx@@ -8,11 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";import {getItemPostingGroup,@@ -22,7 +18,6 @@ import {import { ItemPostingGroupForm } from "~/modules/items/ui/ItemPostingGroups";import { getCustomFields, setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";-import { getCompanyId, itemPostingGroupsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -81,22 +76,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- const companyId = getCompanyId();-- window.clientCache?.invalidateQueries({- predicate: (query) => {- const queryKey = query.queryKey as string[];- return (- queryKey[0] === itemPostingGroupsQuery(companyId).queryKey[0] &&- queryKey[1] === companyId- );- }- });-- return await serverAction();-}-export default function EditItemPostingGroupsRoute() {const { itemPostingGroup } = useLoaderData<typeof loader>();const closeRoute = useCloseRoute();diff --git a/apps/erp/app/routes/x+/items+/groups.delete.$groupId.tsx b/apps/erp/app/routes/x+/items+/groups.delete.$groupId.tsxindex 6d9ca45815..5eafd5a812 100644--- a/apps/erp/app/routes/x+/items+/groups.delete.$groupId.tsx+++ b/apps/erp/app/routes/x+/items+/groups.delete.$groupId.tsx@@ -8,16 +8,11 @@ import { flash } from "@carbon/auth/session.server";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";import { deleteItemPostingGroup, getItemPostingGroup } from "~/modules/items";import { getParams, path } from "~/utils/path";-import { getCompanyId, itemPostingGroupsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -73,14 +68,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- itemPostingGroupsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function DeleteItemPostingGroupRoute() {const { groupId } = useParams();if (!groupId) throw new Error("groupId not found");diff --git a/apps/erp/app/routes/x+/items+/groups.new.tsx b/apps/erp/app/routes/x+/items+/groups.new.tsxindex 98addcd10d..fa92da9bfa 100644--- a/apps/erp/app/routes/x+/items+/groups.new.tsx+++ b/apps/erp/app/routes/x+/items+/groups.new.tsx@@ -8,11 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data } from "react-router";import {itemPostingGroupValidator,@@ -21,7 +17,6 @@ import {import { ItemPostingGroupForm } from "~/modules/items/ui/ItemPostingGroups";import { setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";-import { getCompanyId, itemPostingGroupsQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {await requirePermissions(request, {@@ -86,14 +81,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- itemPostingGroupsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function NewItemPostingGroupsRoute() {const closeRoute = useCloseRoute();const initialValues = {diff --git a/apps/erp/app/routes/x+/items+/materials.tsx b/apps/erp/app/routes/x+/items+/materials.tsxindex 2fc6e1f059..56a5bda4f5 100644--- a/apps/erp/app/routes/x+/items+/materials.tsx+++ b/apps/erp/app/routes/x+/items+/materials.tsx@@ -18,6 +18,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["item"],breadcrumb: msg`Materials`,to: path.to.materials};diff --git a/apps/erp/app/routes/x+/items+/parts.tsx b/apps/erp/app/routes/x+/items+/parts.tsxindex d53419e12f..5c7355ef9a 100644--- a/apps/erp/app/routes/x+/items+/parts.tsx+++ b/apps/erp/app/routes/x+/items+/parts.tsx@@ -19,6 +19,7 @@ import { getGenericQueryFilters } from "~/utils/query";import { useRealtime } from "../../../hooks";export const handle: Handle = {+ realtime: ["item"],breadcrumb: msg`Parts`,to: path.to.parts};diff --git a/apps/erp/app/routes/x+/items+/services.tsx b/apps/erp/app/routes/x+/items+/services.tsxindex 3ca17fc165..76688823de 100644--- a/apps/erp/app/routes/x+/items+/services.tsx+++ b/apps/erp/app/routes/x+/items+/services.tsx@@ -18,6 +18,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["item"],breadcrumb: msg`Services`,to: path.to.services};diff --git a/apps/erp/app/routes/x+/items+/tools.tsx b/apps/erp/app/routes/x+/items+/tools.tsxindex f60e60bc44..3ebb672154 100644--- a/apps/erp/app/routes/x+/items+/tools.tsx+++ b/apps/erp/app/routes/x+/items+/tools.tsx@@ -18,6 +18,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["item"],breadcrumb: msg`Tools`,to: path.to.tools};diff --git a/apps/erp/app/routes/x+/items+/types.$id.tsx b/apps/erp/app/routes/x+/items+/types.$id.tsxindex a60574b169..98387f1017 100644--- a/apps/erp/app/routes/x+/items+/types.$id.tsx+++ b/apps/erp/app/routes/x+/items+/types.$id.tsx@@ -8,11 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";import {getMaterialType,@@ -21,7 +17,6 @@ import {} from "~/modules/items";import MaterialTypeForm from "~/modules/items/ui/MaterialTypes/MaterialTypeForm";import { getParams, path } from "~/utils/path";-import { getCompanyId, materialTypesQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -87,30 +82,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({- request,- serverAction-}: ClientActionFunctionArgs) {- const formData = await request.clone().formData();- const validation = await validator(materialTypeValidator).validate(formData);-- if (!validation.error) {- const companyId = getCompanyId();- const { materialSubstanceId, materialFormId } = validation.data;-- if (companyId && materialSubstanceId && materialFormId) {- // Invalidate the cache for this specific combination- window.clientCache?.setQueryData(- materialTypesQuery(materialSubstanceId, materialFormId, companyId)- .queryKey,- null- );- }- }-- return await serverAction();-}-export default function EditMaterialTypesRoute() {const { materialType } = useLoaderData<typeof loader>();const closeRoute = useCloseRoute();diff --git a/apps/erp/app/routes/x+/items+/types.new.tsx b/apps/erp/app/routes/x+/items+/types.new.tsxindex a4bf714cd7..eae7754f97 100644--- a/apps/erp/app/routes/x+/items+/types.new.tsx+++ b/apps/erp/app/routes/x+/items+/types.new.tsx@@ -8,16 +8,11 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data } from "react-router";import { materialTypeValidator, upsertMaterialType } from "~/modules/items";import MaterialTypeForm from "~/modules/items/ui/MaterialTypes/MaterialTypeForm";import { getParams, path } from "~/utils/path";-import { getCompanyId, materialTypesQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {await requirePermissions(request, {@@ -78,30 +73,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({- request,- serverAction-}: ClientActionFunctionArgs) {- const formData = await request.clone().formData();- const validation = await validator(materialTypeValidator).validate(formData);-- if (!validation.error) {- const companyId = getCompanyId();- const { materialSubstanceId, materialFormId } = validation.data;-- if (companyId && materialSubstanceId && materialFormId) {- // Invalidate the cache for this specific combination- window.clientCache?.setQueryData(- materialTypesQuery(materialSubstanceId, materialFormId, companyId)- .queryKey,- null- );- }- }-- return await serverAction();-}-export default function NewMaterialTypesRoute() {const closeRoute = useCloseRoute();const initialValues = {diff --git a/apps/erp/app/routes/x+/items+/uom.$uomId.tsx b/apps/erp/app/routes/x+/items+/uom.$uomId.tsxindex 37a107f75b..46d32d2dc6 100644--- a/apps/erp/app/routes/x+/items+/uom.$uomId.tsx+++ b/apps/erp/app/routes/x+/items+/uom.$uomId.tsx@@ -8,11 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";import {getUnitOfMeasure,@@ -22,7 +18,6 @@ import {import { UnitOfMeasureForm } from "~/modules/items/ui/UnitOfMeasure";import { getCustomFields, setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";-import { getCompanyId, uomsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -79,11 +74,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(uomsQuery(getCompanyId()).queryKey, null);- return await serverAction();-}-export default function EditUnitOfMeasuresRoute() {const { unitOfMeasure } = useLoaderData<typeof loader>();const closeRoute = useCloseRoute();diff --git a/apps/erp/app/routes/x+/items+/uom.delete.$uomId.tsx b/apps/erp/app/routes/x+/items+/uom.delete.$uomId.tsxindex 2736b8ea4b..04c7aa0f4c 100644--- a/apps/erp/app/routes/x+/items+/uom.delete.$uomId.tsx+++ b/apps/erp/app/routes/x+/items+/uom.delete.$uomId.tsx@@ -7,11 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";import {@@ -20,7 +16,6 @@ import {getUnitOfMeasureUsage} from "~/modules/items";import { getParams, path } from "~/utils/path";-import { getCompanyId, uomsQuery } from "~/utils/react-query";import { camelCaseToWords } from "~/utils/string";// "purchase order line (12), item (4)" — humanized table names, no lookup to maintain.@@ -130,11 +125,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(uomsQuery(getCompanyId()).queryKey, null);- return await serverAction();-}-export default function DeleteUnitOfMeasureRoute() {const { uomId } = useParams();const { unitOfMeasure, usage } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/items+/uom.new.tsx b/apps/erp/app/routes/x+/items+/uom.new.tsxindex 89d21ff878..b611ad2e8d 100644--- a/apps/erp/app/routes/x+/items+/uom.new.tsx+++ b/apps/erp/app/routes/x+/items+/uom.new.tsx@@ -8,17 +8,12 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data } from "react-router";import { unitOfMeasureValidator, upsertUnitOfMeasure } from "~/modules/items";import { UnitOfMeasureForm } from "~/modules/items/ui/UnitOfMeasure";import { setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";-import { getCompanyId, uomsQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {await requirePermissions(request, {@@ -70,12 +65,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window?.clientCache?.setQueryData(uomsQuery(getCompanyId()).queryKey, null);-- return await serverAction();-}-export default function NewUnitOfMeasuresRoute() {const closeRoute = useCloseRoute();const initialValues = {diff --git a/apps/erp/app/routes/x+/job+/$jobId.details.tsx b/apps/erp/app/routes/x+/job+/$jobId.details.tsxindex f34809e34c..122870234a 100644--- a/apps/erp/app/routes/x+/job+/$jobId.details.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.details.tsx@@ -32,7 +32,7 @@ import {SupplierAvatar} from "~/components";import { usePanels } from "~/components/Layout";-import { usePermissions, useRealtime, useRouteData } from "~/hooks";+import { usePermissions, useRouteData } from "~/hooks";import type { Job, JobPurchaseOrderLine } from "~/modules/production";import {getJob,@@ -76,12 +76,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { jobId } = params;if (!jobId) throw new Error("Could not find jobId");- // `client` is the service role (bypassRls) and every read keys on the URL id.- await requireCompanyRecord(client, "job", companyId, { id: jobId });-- // After the guard, these three need only the job id: read together, not one- // after another.- const [job, rootMethod, tags] = await Promise.all([+ // `client` is the service role (bypassRls) and every read keys on the URL id,+ // so the job must be this company's. The check runs beside the reads it+ // guards, not before them: it rejects the whole batch, and nothing read here+ // is returned unless it passes.+ const [, job, rootMethod, tags] = await Promise.all([+ requireCompanyRecord(client, "job", companyId, { id: jobId }),getJob(client, jobId),getRootMakeMethod(client, jobId, companyId),getTagsList(client, companyId, "operation")@@ -248,15 +248,10 @@ export default function JobDetailsRoute() {}});- const jobData = useRouteData<{- job: Job;- files: Promise<StorageItem[]> | StorageItem[];- }>(path.to.job(jobId));+ const jobData = useRouteData<{ job: Job }>(path.to.job(jobId));if (!jobData) throw new Error("Could not find job data");- useRealtime("modelUpload", `modelPath=eq.(${jobData?.job.modelPath})`);-const methodId = makeMethod?.id;return (diff --git a/apps/erp/app/routes/x+/job+/$jobId.materials.tsx b/apps/erp/app/routes/x+/job+/$jobId.materials.tsxindex c1d613287d..4f9bcfa8f2 100644--- a/apps/erp/app/routes/x+/job+/$jobId.materials.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.materials.tsx@@ -8,9 +8,8 @@ import { flash } from "@carbon/auth/session.server";import { useMount, VStack } from "@carbon/react";import { datetime, redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";-import { useLoaderData, useParams } from "react-router";+import { useLoaderData } from "react-router";import { usePanels } from "~/components/Layout";-import { useRealtime } from "~/hooks";import { getPicksByJobMaterial } from "~/modules/inventory";import { getItemSupersessionsForItems } from "~/modules/items";import {@@ -227,11 +226,8 @@ export default function JobMaterialsRoute() {picksByMaterialId,consumeFirstByItemId} = useLoaderData<typeof loader>();- const { jobId } = useParams();const { setIsExplorerCollapsed } = usePanels();- useRealtime("pickingListLine", `jobId=eq.${jobId}`);-useMount(() => {setIsExplorerCollapsed(true);});diff --git a/apps/erp/app/routes/x+/job+/$jobId.tsx b/apps/erp/app/routes/x+/job+/$jobId.tsxindex ff6c490741..453758608a 100644--- a/apps/erp/app/routes/x+/job+/$jobId.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.tsx@@ -22,7 +22,6 @@ import { getConfigurationParameters } from "~/modules/items";import type { JobMethodTreeItem } from "~/modules/production";import {getJob,- getJobDocuments,getJobMaterialsWithQuantityOnHand,getJobMethodTree,getJobOrderStatusMap,@@ -76,7 +75,26 @@ export const handle: Handle = {{ breadcrumb: msg`Jobs`, to: path.to.jobs },(data) => data?.job?.jobId),- module: "production"+ module: "production",+ // Everything the job's pages show: an operation finished on the shop floor,+ // a pick, a step record — all reach this page without a reload.+ realtime: [+ { table: "job", column: "id", param: "jobId" },+ { table: "jobOperation", column: "jobId", param: "jobId" },+ { table: "jobMaterial", column: "jobId", param: "jobId" },+ { table: "jobMakeMethod", column: "jobId", param: "jobId" },+ { table: "jobOperationStep", column: "jobId", param: "jobId" },+ { table: "jobOperationStepRecord", column: "jobId", param: "jobId" },+ { table: "productionEvent", column: "jobId", param: "jobId" },+ { table: "pickingListLine", column: "jobId", param: "jobId" },+ {+ // The job's own model. A job without one follows none: attaching a model+ // changes the job row, which is followed above.+ table: "modelUpload",+ filter: ({ data }) =>+ data?.job?.modelUploadId ? `id=eq.${data.job.modelUploadId}` : false+ }+ ]};export const shouldRevalidate: ShouldRevalidateFunction = (args) =>@@ -133,7 +151,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {job: job.data,unbatchedBatchableOperations,tags: tags.data ?? [],- files: getJobDocuments(client, companyId, job.data),trackedEntities: getTrackedEntitiesByJobId(client, jobId),method: getJobMethodTree(client, jobId), // returns a promiseorderStatus: getJobOrderStatus(diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsxindex 20fd6f7681..fb99760fe1 100644--- a/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx@@ -35,6 +35,9 @@ import { detailBreadcrumb, type Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {+ realtime: [+ { table: "maintenanceDispatch", column: "id", param: "dispatchId" }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`Maintenance`, to: path.to.maintenanceDispatches },(data) => data?.dispatch?.maintenanceDispatchIddiff --git a/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/material+/$itemId.inventory.tsxindex 537bf418f1..4418b3b6ff 100644--- a/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/material+/$itemId.inventory.tsx@@ -51,8 +51,21 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const searchParams = new URLSearchParams(url.search);let locationId = searchParams.get("location");- if (!locationId) {- const userDefaults = await getUserDefaults(client, userId, companyId);+ // Three waits at most: what needs no location is read while the+ // default location is, and everything that needs it is read together.+ const [userDefaults, shelfLife, bomHasShelfLifeManagedInput, rulesData] =+ await Promise.all([+ locationId ? null : getUserDefaults(client, userId, companyId),+ getItemShelfLife(client, itemId),+ getBomHasShelfLifeManagedInput(client, itemId, companyId),+ getStorageRulesDataForTarget(client, {+ targetType: "item",+ targetId: itemId,+ companyId+ })+ ]);++ if (userDefaults) {if (userDefaults.error) {throw redirect(path.to.material(itemId),@@ -80,9 +93,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {locationId = locations.data?.[0].id as string;}- let [materialInventory] = await Promise.all([- getPickMethod(client, itemId, companyId, locationId)- ]);+ let [materialInventory, quantities, itemStorageUnitQuantities] =+ await Promise.all([+ getPickMethod(client, itemId, companyId, locationId),+ getItemQuantities(client, itemId, companyId, locationId),+ getItemStorageUnitQuantities(client, itemId, companyId, locationId)+ ]);if (materialInventory.error || !materialInventory.data) {const insertPickMethod = await upsertPickMethod(client, {@@ -120,12 +136,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}}- const quantities = await getItemQuantities(- client,- itemId,- companyId,- locationId- );if (quantities.error) {throw redirect(path.to.items,@@ -136,12 +146,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- const itemStorageUnitQuantities = await getItemStorageUnitQuantities(- client,- itemId,- companyId,- locationId- );if (itemStorageUnitQuantities.error || !itemStorageUnitQuantities.data) {throw redirect(path.to.items,@@ -157,21 +161,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {(row) => row.trackedEntityId);- const [- shelfLife,- bomHasShelfLifeManagedInput,- trackedEntityExpirations,- rulesData- ] = await Promise.all([- getItemShelfLife(client, itemId),- getBomHasShelfLifeManagedInput(client, itemId, companyId),- getTrackedEntityExpirations(client, trackedEntityIds),- getStorageRulesDataForTarget(client, {- targetType: "item",- targetId: itemId,- companyId- })- ]);+ const trackedEntityExpirations = await getTrackedEntityExpirations(+ client,+ trackedEntityIds+ );return {materialInventory: materialInventory.data,diff --git a/apps/erp/app/routes/x+/part+/$itemId.details.tsx b/apps/erp/app/routes/x+/part+/$itemId.details.tsxindex ba3b1a52c6..ec848f2d4e 100644--- a/apps/erp/app/routes/x+/part+/$itemId.details.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.details.tsx@@ -13,11 +13,7 @@ import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import type { PostgrestResponse } from "@supabase/supabase-js";import { Suspense } from "react";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { Await, useLoaderData, useParams } from "react-router";import { CadModel, DeferredFiles } from "~/components";import { usePermissions, useRouteData } from "~/hooks";@@ -60,7 +56,6 @@ import type { MethodItemType, MethodType } from "~/modules/shared";import { getTagsList } from "~/modules/shared";import { getCustomFields, setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { configurableItemsQuery, getCompanyId } from "~/utils/react-query";const logger = getLogger("erp", "itemid-details");@@ -243,14 +238,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- configurableItemsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function PartDetailsRoute() {const { t } = useLingui();const { itemId } = useParams();diff --git a/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/part+/$itemId.inventory.tsxindex f353838ff6..90823294b7 100644--- a/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.inventory.tsx@@ -51,8 +51,21 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const searchParams = new URLSearchParams(url.search);let locationId = searchParams.get("location");- if (!locationId) {- const userDefaults = await getUserDefaults(client, userId, companyId);+ // Three waits at most: what needs no location is read while the+ // default location is, and everything that needs it is read together.+ const [userDefaults, shelfLife, bomHasShelfLifeManagedInput, rulesData] =+ await Promise.all([+ locationId ? null : getUserDefaults(client, userId, companyId),+ getItemShelfLife(client, itemId),+ getBomHasShelfLifeManagedInput(client, itemId, companyId),+ getStorageRulesDataForTarget(client, {+ targetType: "item",+ targetId: itemId,+ companyId+ })+ ]);++ if (userDefaults) {if (userDefaults.error) {throw redirect(path.to.part(itemId),@@ -80,9 +93,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {locationId = locations.data?.[0].id as string;}- let [partInventory] = await Promise.all([- getPickMethod(client, itemId, companyId, locationId)- ]);+ let [partInventory, quantities, itemStorageUnitQuantities] =+ await Promise.all([+ getPickMethod(client, itemId, companyId, locationId),+ getItemQuantities(client, itemId, companyId, locationId),+ getItemStorageUnitQuantities(client, itemId, companyId, locationId)+ ]);if (partInventory.error || !partInventory.data) {const insertPickMethod = await upsertPickMethod(client, {@@ -115,23 +131,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}}- const [- quantities,- itemStorageUnitQuantities,- shelfLife,- bomHasShelfLifeManagedInput,- rulesData- ] = await Promise.all([- getItemQuantities(client, itemId, companyId, locationId),- getItemStorageUnitQuantities(client, itemId, companyId, locationId),- getItemShelfLife(client, itemId),- getBomHasShelfLifeManagedInput(client, itemId, companyId),- getStorageRulesDataForTarget(client, {- targetType: "item",- targetId: itemId,- companyId- })- ]);if (quantities.error) {throw redirect(path.to.items,diff --git a/apps/erp/app/routes/x+/person+/$personId.timecard.tsx b/apps/erp/app/routes/x+/person+/$personId.timecard.tsxindex 4ac4475939..599b1cb744 100644--- a/apps/erp/app/routes/x+/person+/$personId.timecard.tsx+++ b/apps/erp/app/routes/x+/person+/$personId.timecard.tsx@@ -6,6 +6,7 @@ import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validator } from "@carbon/form";+import { useAction } from "@carbon/query";import {Badge,Button,@@ -49,7 +50,7 @@ import {LuTrash} from "react-icons/lu";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";-import { data, Link, useFetcher, useLoaderData, useParams } from "react-router";+import { data, Link, useLoaderData, useParams } from "react-router";import { DateTime } from "~/components";import { ConfirmDelete } from "~/components/Modals";import { useDateFormatter } from "~/hooks";@@ -347,7 +348,14 @@ export default function PersonTimecardRoute() {const { entries, openEntry, weekOffset, weekStart, weekEnd, shift } =useLoaderData<typeof loader>();const { personId } = useParams();- const fetcher = useFetcher<typeof action>();+ const fetcher = useAction<typeof action>({+ onSettled: (data) => {+ if (data) {+ setEditingId(null);+ setShowAddForm(false);+ }+ }+ });const [editingId, setEditingId] = useState<string | null>(null);const [editClockIn, setEditClockIn] = useState("");const [editClockOut, setEditClockOut] = useState("");@@ -370,13 +378,6 @@ export default function PersonTimecardRoute() {const isCurrentWeek = weekOffset === 0;- useEffect(() => {- if (fetcher.data && fetcher.state === "idle") {- setEditingId(null);- setShowAddForm(false);- }- }, [fetcher.data, fetcher.state]);-// Auto-populate shift times when date is selected for new entryuseEffect(() => {if (!addDate) return;diff --git a/apps/erp/app/routes/x+/picking-list+/$pickingListId.tsx b/apps/erp/app/routes/x+/picking-list+/$pickingListId.tsxindex 7049ac6180..f9368664a5 100644--- a/apps/erp/app/routes/x+/picking-list+/$pickingListId.tsx+++ b/apps/erp/app/routes/x+/picking-list+/$pickingListId.tsx@@ -23,6 +23,14 @@ import { detailBreadcrumb, type Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {+ realtime: [+ { table: "pickingList", column: "id", param: "pickingListId" },+ {+ table: "pickingListLine",+ column: "pickingListId",+ param: "pickingListId"+ }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`Picking List`, to: path.to.pickingLists },(data) => data?.pickingList?.pickingListIddiff --git a/apps/erp/app/routes/x+/priority+/_layout.tsx b/apps/erp/app/routes/x+/priority+/_layout.tsxindex 99e4762e55..0bd79fa1d4 100644--- a/apps/erp/app/routes/x+/priority+/_layout.tsx+++ b/apps/erp/app/routes/x+/priority+/_layout.tsx@@ -15,6 +15,7 @@ export const meta: MetaFunction = () => {};export const handle: Handle = {+ realtime: ["job", "jobOperation"],breadcrumb: msg`Production`,to: path.to.production,module: "production"diff --git a/apps/erp/app/routes/x+/priority+/operations.tsx b/apps/erp/app/routes/x+/priority+/operations.tsxindex 3560b1e0f2..b92dde5f13 100644--- a/apps/erp/app/routes/x+/priority+/operations.tsx+++ b/apps/erp/app/routes/x+/priority+/operations.tsx@@ -4,6 +4,7 @@import { useCarbon } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { useChangedRows } from "@carbon/query";import {Button,ClientOnly,@@ -23,7 +24,6 @@ import {useInterval,useLocalStorage,useMount,- useRealtimeChannel,VStack} from "@carbon/react";import { isUnaffectedByNavigation } from "@carbon/utils";@@ -1050,96 +1050,58 @@ function useProgressByOperation(}}, [productionEventsByOperation]);- useRealtimeChannel({- topic: `kanban-schedule:${companyId}`,- setup(channel) {- return channel- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "jobOperation",- filter: `id=in.(${items- .filter((item) => !isBatchItem(item))- .map((item) => item.id)- .join(",")})`- },- (payload) => {- switch (payload.eventType) {- case "UPDATE": {- const { new: updated } = payload;- setItems((prevItems: Item[]) =>- sortItems(- prevItems.map((item: Item) => {- if (item.id === updated.id) {- return {- ...item,- columnId: updated.workCenterId,- priority: updated.priority- };- }- return item;- })- )- );- break;- }- case "DELETE": {- const { old: deleted } = payload;- setItems((prevItems: Item[]) =>- sortItems(- prevItems.filter((item: Item) => item.id !== deleted.id)- )- );- break;- }- }- }- )- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "productionEvent",- filter: `companyId=eq.${companyId}`- },- (payload) => {- if (payload.eventType === "INSERT") {- const { new: inserted } = payload;- if (inserted.jobOperationId) {- setProductionEventsByOperation((prevState) => ({- ...prevState,- [inserted.jobOperationId]: [- ...(prevState[inserted.jobOperationId] ?? []),- inserted- ]- }));- }- } else if (payload.eventType === "UPDATE") {- const { new: updated } = payload;- if (updated.jobOperationId) {- setProductionEventsByOperation((prevState) => ({- ...prevState,- [updated.jobOperationId]: (- prevState[updated.jobOperationId] ?? []- ).map((event) => (event.id === updated.id ? updated : event))- }));- }- } else if (payload.eventType === "DELETE") {- const { old: deleted } = payload;- if (deleted.jobOperationId) {- setProductionEventsByOperation((prevState) => ({- ...prevState,- [deleted.jobOperationId]: (- prevState[deleted.jobOperationId] ?? []- ).filter((event) => event.id !== deleted.id)- }));- }- }- }+ useChangedRows<{ id: string; workCenterId: string; priority: number }>({+ companyId,+ table: "jobOperation",+ columns: "id, workCenterId, priority",+ onChange: ({ op, ids, rows }) => {+ if (op === "DELETE") {+ setItems((prevItems: Item[]) =>+ sortItems(prevItems.filter((item: Item) => !ids.includes(item.id))));+ return;+ }+ const changed = new Map(rows.map((row) => [row.id, row]));+ setItems((prevItems: Item[]) =>+ sortItems(+ prevItems.map((item: Item) => {+ const updated = changed.get(item.id);+ return updated+ ? {+ ...item,+ columnId: updated.workCenterId,+ priority: updated.priority+ }+ : item;+ })+ )+ );+ }+ });++ useChangedRows<Event>({+ companyId,+ table: "productionEvent",+ onChange: ({ op, ids, rows }) => {+ setProductionEventsByOperation((prev) => {+ if (op === "DELETE") {+ return Object.fromEntries(+ Object.entries(prev).map(([operationId, events]) => [+ operationId,+ events.filter((event) => !ids.includes(event.id))+ ])+ );+ }+ const next = { ...prev };+ for (const row of rows) {+ if (!row.jobOperationId) continue;+ const events = next[row.jobOperationId] ?? [];+ next[row.jobOperationId] = events.some((event) => event.id === row.id)+ ? events.map((event) => (event.id === row.id ? row : event))+ : [...events, row];+ }+ return next;+ });}});diff --git a/apps/erp/app/routes/x+/procedure+/delete.$id.tsx b/apps/erp/app/routes/x+/procedure+/delete.$id.tsxindex ba66ba331a..c3e998b8a6 100644--- a/apps/erp/app/routes/x+/procedure+/delete.$id.tsx+++ b/apps/erp/app/routes/x+/procedure+/delete.$id.tsx@@ -6,14 +6,10 @@ import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { deleteProcedure } from "~/modules/production/production.service";import { path } from "~/utils/path";-import { getCompanyId, proceduresQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {const { client } = await requirePermissions(request, {@@ -39,11 +35,3 @@ export async function action({ request, params }: ActionFunctionArgs) {await flash(request, success("Successfully deleted procedure")));}--export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- proceduresQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}diff --git a/apps/erp/app/routes/x+/procedure+/update.tsx b/apps/erp/app/routes/x+/procedure+/update.tsxindex 6bf305a0ef..4d97b4d078 100644--- a/apps/erp/app/routes/x+/procedure+/update.tsx+++ b/apps/erp/app/routes/x+/procedure+/update.tsx@@ -4,11 +4,7 @@import { requirePermissions } from "@carbon/auth/auth.server";import { unchecked } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";-import { getCompanyId, proceduresQuery } from "~/utils/react-query";+import type { ActionFunctionArgs } from "react-router";export async function action({ request }: ActionFunctionArgs) {const { client, userId } = await requirePermissions(request, {@@ -53,11 +49,3 @@ export async function action({ request }: ActionFunctionArgs) {return { error: { message: "Invalid field" }, data: null };}}--export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- proceduresQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}diff --git a/apps/erp/app/routes/x+/production+/_index.tsx b/apps/erp/app/routes/x+/production+/_index.tsxindex f267ab5337..e19b90059e 100644--- a/apps/erp/app/routes/x+/production+/_index.tsx+++ b/apps/erp/app/routes/x+/production+/_index.tsx@@ -5,6 +5,7 @@import { useCarbon } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { activeJobStatuses } from "@carbon/database";+import { useChangedRows, useLoaderQuery } from "@carbon/query";import {Badge,Button,@@ -30,7 +31,6 @@ import {Tooltip,TooltipContent,TooltipTrigger,- useRealtimeChannel,VStack} from "@carbon/react";import type { ChartConfig } from "@carbon/react/Chart";@@ -63,7 +63,7 @@ import {} from "react-icons/lu";import { RiProgress8Line } from "react-icons/ri";import type { LoaderFunctionArgs } from "react-router";-import { Await, Link, useFetcher, useLoaderData } from "react-router";+import { Await, Link, useLoaderData } from "react-router";import { Bar, BarChart, LabelList, XAxis, YAxis } from "recharts";import {CustomerAvatar,@@ -87,9 +87,14 @@ import type { WorkCenter } from "~/modules/resources";import { getWorkCentersListWithBlockingStatus } from "~/modules/resources";import type { loader as kpiLoader } from "~/routes/api+/production.kpi.$key";+import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";import { capitalize } from "~/utils/string";+export const handle: Handle = {+ realtime: ["job", "jobOperation"]+};+const chartConfig = {value: {color: "hsl(var(--primary))"@@ -140,8 +145,6 @@ export default function ProductionDashboard() {useLoaderData<typeof loader>();const user = useUser();- const kpiFetcher = useFetcher<typeof kpiLoader>();- const isFetching = kpiFetcher.state !== "idle" || !kpiFetcher.data;const [interval, setInterval] = useState("month");const [selectedKpi, setSelectedKpi] = useState<@@ -155,6 +158,13 @@ export default function ProductionDashboard() {const selectedKpiData = KPIs.find((k) => k.key === selectedKpi) || KPIs[0];+ const kpiFetcher = useLoaderQuery<typeof kpiLoader>(+ `${path.to.api.productionKpi(+ selectedKpiData.key+ )}?start=${dateRange?.start.toString()}&end=${dateRange?.end.toString()}&interval=${interval}`+ );+ const isFetching = kpiFetcher.isFetching || !kpiFetcher.data;+const kpiLabels: Record<string, string> = useMemo(() => ({utilization: t`Work Center Utilization`,@@ -178,15 +188,6 @@ export default function ProductionDashboard() {return dateRange.end.compare(dateRange.start) * 24 * 60 * 60 * 1000;}, [dateRange]);- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- kpiFetcher.load(- `${path.to.api.productionKpi(- selectedKpiData.key- )}?start=${dateRange?.start.toString()}&end=${dateRange?.end.toString()}&interval=${interval}`- );- }, [selectedKpi, dateRange, interval, selectedKpiData.key]);-const onIntervalChange = (value: string) => {const end = toCalendarDateTime(now("UTC"));if (value === "week") {@@ -430,8 +431,7 @@ export default function ProductionDashboard() {</>)}</VStack>- {kpiFetcher.state === "idle" &&- kpiFetcher.data?.data?.length === 0 ? (+ {!kpiFetcher.isFetching && kpiFetcher.data?.data?.length === 0 ? (<div className="flex flex-col items-center justify-center h-full"><Empty className="py-8"><p className="text-sm text-muted-foreground">@@ -749,44 +749,34 @@ function WorkCenterCards({setEvents(initialEvents);}, [initialEvents]);- useRealtimeChannel({- topic: `production-dashboard-work-centers:${companyId}`,- setup(channel) {- return channel.on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "productionEvent",- filter: `companyId=eq.${companyId}`- },- (payload) => {- if (payload.eventType === "INSERT") {- const { new: inserted } = payload;- setEvents((prev) => [...prev, inserted as ActiveProductionEvent]);- ensureMetaData({ jobOperationId: inserted.jobOperationId });- } else if (payload.eventType === "UPDATE") {- const { new: updated } = payload;- setEvents((prev) => {- if (updated.endTime) {- return prev.filter((event) => event.id !== updated.id);- }- const exists = prev.some((event) => event.id === updated.id);- if (exists) {- return prev.map((event) =>- event.id === updated.id ? { ...event, ...updated } : event- );- }- return [...prev, updated as ActiveProductionEvent];- });- } else if (payload.eventType === "DELETE") {- const { old: deleted } = payload;- setEvents((prev) =>- prev.filter((event) => event.id !== deleted.id)+ useChangedRows<ActiveProductionEvent & { endTime?: string | null }>({+ companyId,+ table: "productionEvent",+ onChange: ({ op, ids, rows }) => {+ if (op === "DELETE") {+ setEvents((prev) => prev.filter((event) => !ids.includes(event.id)));+ return;+ }+ setEvents((prev) => {+ let next = prev;+ for (const row of rows) {+ // A finished event leaves the board; a running one joins or updates.+ if (row.endTime) {+ next = next.filter((event) => event.id !== row.id);+ } else if (next.some((event) => event.id === row.id)) {+ next = next.map((event) =>+ event.id === row.id ? { ...event, ...row } : event);+ } else {+ next = [...next, row];}}- );+ return next;+ });+ for (const row of rows) {+ if (!row.endTime)+ ensureMetaData({ jobOperationId: row.jobOperationId });+ }}});diff --git a/apps/erp/app/routes/x+/production+/jobs.tsx b/apps/erp/app/routes/x+/production+/jobs.tsxindex 1dd04d032a..c9262f76c6 100644--- a/apps/erp/app/routes/x+/production+/jobs.tsx+++ b/apps/erp/app/routes/x+/production+/jobs.tsx@@ -19,6 +19,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["job"],breadcrumb: msg`Jobs`,to: path.to.jobs};diff --git a/apps/erp/app/routes/x+/production+/planning.tsx b/apps/erp/app/routes/x+/production+/planning.tsxindex 03699a238f..6302e56013 100644--- a/apps/erp/app/routes/x+/production+/planning.tsx+++ b/apps/erp/app/routes/x+/production+/planning.tsx@@ -26,6 +26,7 @@ import { getGenericQueryFilters } from "~/utils/query";const WEEKS_TO_PLAN = 12 * 4;export const handle: Handle = {+ realtime: ["job"],breadcrumb: msg`Material Planning`,to: path.to.productionPlanning};diff --git a/apps/erp/app/routes/x+/production+/planning.update.tsx b/apps/erp/app/routes/x+/production+/planning.update.tsxindex 05013e1c7a..d239fba9f4 100644--- a/apps/erp/app/routes/x+/production+/planning.update.tsx+++ b/apps/erp/app/routes/x+/production+/planning.update.tsx@@ -176,6 +176,23 @@ export async function action({ request }: ActionFunctionArgs) {let processedItems = 0;let errors: string[] = [];+ // Manufacturing data for every item being ordered, in one read+ const manufacturingRows = await client+ .from("itemReplenishment")+ .select(+ "itemId, manufacturingBlocked, scrapPercentage, requiresConfiguration"+ )+ .in(+ "itemId",+ itemsToOrder.flatMap((item) =>+ item.orders.length > 0 ? [item.id] : []+ )+ )+ .eq("companyId", companyId);+ const manufacturingByItem = new Map(+ (manufacturingRows.data ?? []).map((row) => [row.itemId, row])+ );+for (const item of itemsToOrder) {const orders = item.orders;@@ -188,15 +205,14 @@ export async function action({ request }: ActionFunctionArgs) {const jobIds: string[] = [];const supplyForecastByPeriod: Record<string, number> = {};- // Get manufacturing data for this item- const manufacturing = await client- .from("itemReplenishment")- .select(- "manufacturingBlocked, scrapPercentage, requiresConfiguration"- )- .eq("itemId", item.id)- .eq("companyId", companyId)- .single();+ const manufacturing = {+ data: manufacturingByItem.get(item.id),+ error:+ manufacturingRows.error ??+ (manufacturingByItem.has(item.id)+ ? null+ : { message: "No replenishment record" })+ };if (manufacturing.error) {const errorMsg = `Failed to retrieve manufacturing data for item ${item.id}: ${manufacturing.error.message}`;diff --git a/apps/erp/app/routes/x+/production+/procedures.new.tsx b/apps/erp/app/routes/x+/production+/procedures.new.tsxindex 77e688c7b7..d6368ff8ef 100644--- a/apps/erp/app/routes/x+/production+/procedures.new.tsx+++ b/apps/erp/app/routes/x+/production+/procedures.new.tsx@@ -7,17 +7,12 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useNavigate } from "react-router";import { procedureValidator } from "~/modules/production/production.models";import { upsertProcedure } from "~/modules/production/production.service";import ProcedureForm from "~/modules/production/ui/Procedures/ProcedureForm";import { path } from "~/utils/path";-import { getCompanyId, proceduresQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {await requirePermissions(request, {@@ -82,14 +77,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- proceduresQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function NewProcedureRoute() {const navigate = useNavigate();const initialValues = {diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsxindex a744617921..c6a2c6ddd5 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx@@ -34,6 +34,18 @@ import { detailBreadcrumb, type Handle } from "~/utils/handle";import { path, requestReferrer } from "~/utils/path";export const handle: Handle = {+ realtime: [+ { table: "purchaseInvoice", column: "id", param: "invoiceId" },+ { table: "purchaseInvoiceLine", column: "invoiceId", param: "invoiceId" },+ // What is applied to this invoice, and the payments behind it: voiding a+ // payment changes the payment row only.+ {+ table: "invoiceSettlement",+ column: "targetPurchaseInvoiceId",+ param: "invoiceId"+ },+ { table: "payment", column: "targetPurchaseInvoiceId", param: "invoiceId" }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`Purchasing Invoices`, to: path.to.invoicingPurchasing },(data) => data?.purchaseInvoice?.invoiceIddiff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsxindex 44d8df23c9..e303ebc011 100644--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx@@ -65,6 +65,26 @@ import { stripSpecialCharacters } from "~/utils/string";const logger = getLogger("erp", "purchase-order");export const handle: Handle = {+ realtime: [+ { table: "purchaseOrder", column: "id", param: "orderId" },+ { table: "purchaseOrderLine", column: "purchaseOrderId", param: "orderId" },+ {+ // Receipts and invoices of this order share its supplier interaction+ // (`usePurchaseOrder`, `getSupplierInteraction`).+ table: "receipt",+ filter: ({ data }) =>+ data?.purchaseOrder?.supplierInteractionId+ ? `supplierInteractionId=eq.${data.purchaseOrder.supplierInteractionId}`+ : undefined+ },+ {+ table: "purchaseInvoice",+ filter: ({ data }) =>+ data?.purchaseOrder?.supplierInteractionId+ ? `supplierInteractionId=eq.${data.purchaseOrder.supplierInteractionId}`+ : undefined+ }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`Orders`, to: path.to.purchaseOrders },(data) => data?.purchaseOrder?.purchaseOrderIddiff --git a/apps/erp/app/routes/x+/purchase-return-order+/$id.tsx b/apps/erp/app/routes/x+/purchase-return-order+/$id.tsxindex cdec535d3a..36545ed7d4 100644--- a/apps/erp/app/routes/x+/purchase-return-order+/$id.tsx+++ b/apps/erp/app/routes/x+/purchase-return-order+/$id.tsx@@ -28,6 +28,14 @@ import { detailBreadcrumb, type Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {+ realtime: [+ { table: "purchaseReturnOrder", column: "id", param: "id" },+ {+ table: "purchaseReturnOrderLine",+ column: "purchaseReturnOrderId",+ param: "id"+ }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`Supplier Returns`, to: path.to.purchaseReturnOrders },(data) => data?.purchaseReturnOrder?.purchaseReturnOrderIddiff --git a/apps/erp/app/routes/x+/purchasing+/_index.tsx b/apps/erp/app/routes/x+/purchasing+/_index.tsxindex 286372e0d7..c333cffbde 100644--- a/apps/erp/app/routes/x+/purchasing+/_index.tsx+++ b/apps/erp/app/routes/x+/purchasing+/_index.tsx@@ -6,6 +6,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { ApprovalRequest } from "@carbon/ee/approvals";import { getPendingApprovalsForApprover } from "@carbon/ee/approvals.server";+import { useLoaderQuery } from "@carbon/query";import {Badge,Button,@@ -49,7 +50,7 @@ import {import { Trans, useLingui } from "@lingui/react/macro";import { useDateFormatter, useNumberFormatter } from "@react-aria/i18n";import type { DateRange } from "@react-types/datepicker";-import { Suspense, useEffect, useMemo, useState } from "react";+import { Suspense, useMemo, useState } from "react";import {LuChevronDown,LuClock,@@ -61,7 +62,7 @@ import {LuPackageSearch} from "react-icons/lu";import type { LoaderFunctionArgs } from "react-router";-import { Await, useFetcher, useLoaderData } from "react-router";+import { Await, useLoaderData } from "react-router";import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";import {DateSelect,@@ -255,8 +256,6 @@ export default function PurchaseDashboard() {]);const { t } = useLingui();- const kpiFetcher = useFetcher<typeof kpiLoader>();- const isFetching = kpiFetcher.state !== "idle" || !kpiFetcher.data;const dateFormatter = useDateFormatter({month: "short",@@ -299,6 +298,15 @@ export default function PurchaseDashboard() {const selectedKpiData = KPIs.find((k) => k.key === selectedKpi) || KPIs[0];+ const kpiFetcher = useLoaderQuery<typeof kpiLoader>(+ `${path.to.api.purchasingKpi(+ selectedKpiData.key+ )}?start=${dateRange?.start.toString()}&end=${dateRange?.end.toString()}&interval=${interval}${+ supplierId === "all" ? "" : `&supplierId=${supplierId}`+ }`+ );+ const isFetching = kpiFetcher.isFetching || !kpiFetcher.data;+const kpiLabels: Record<string, string> = useMemo(() => ({supplierQuoteCount: t`Supplier Quotes`,@@ -310,17 +318,6 @@ export default function PurchaseDashboard() {[t]);- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- kpiFetcher.load(- `${path.to.api.purchasingKpi(- selectedKpiData.key- )}?start=${dateRange?.start.toString()}&end=${dateRange?.end.toString()}&interval=${interval}${- supplierId === "all" ? "" : `&supplierId=${supplierId}`- }`- );- }, [selectedKpi, dateRange, interval, selectedKpiData.key, supplierId]);-const onIntervalChange = (value: string) => {const end = toCalendarDateTime(now("UTC"));if (value === "week") {diff --git a/apps/erp/app/routes/x+/purchasing+/invoices.tsx b/apps/erp/app/routes/x+/purchasing+/invoices.tsxindex da1385a321..c6ba517bc3 100644--- a/apps/erp/app/routes/x+/purchasing+/invoices.tsx+++ b/apps/erp/app/routes/x+/purchasing+/invoices.tsx@@ -4,8 +4,13 @@import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";+import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";+export const handle: Handle = {+ realtime: ["purchaseInvoice"]+};+// Purchase invoices now live solely in the invoicing module. This legacy// Purchasing-module URL redirects there, preserving any filter query string// (e.g. ?filter=supplierId:eq:...).diff --git a/apps/erp/app/routes/x+/purchasing+/orders.tsx b/apps/erp/app/routes/x+/purchasing+/orders.tsxindex 818aec3b85..7d7d660aeb 100644--- a/apps/erp/app/routes/x+/purchasing+/orders.tsx+++ b/apps/erp/app/routes/x+/purchasing+/orders.tsx@@ -20,6 +20,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["purchaseOrder"],breadcrumb: msg`Orders`,to: path.to.purchaseOrders};diff --git a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx b/apps/erp/app/routes/x+/purchasing+/planning.update.tsxindex 1a96f7146c..6482b3b000 100644--- a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx+++ b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx@@ -348,6 +348,16 @@ export async function action({ request }: ActionFunctionArgs) {// Track readable id too so the client can present a clickable toast.const poCache = new Map<string, { id: string; readableId: string }>();+ // Whether purchasing is blocked, for every item ordered, in one read+ const purchasingRows = await client+ .from("itemReplenishment")+ .select("itemId, purchasingBlocked")+ .in("itemId", Array.from(itemIds))+ .eq("companyId", companyId);+ const purchasingByItem = new Map(+ (purchasingRows.data ?? []).map((row) => [row.itemId, row])+ );+for (const [supplierId, ordersInGroup] of ordersBySupplier) {const supplier = suppliersById.get(supplierId);if (!supplier) {@@ -459,12 +469,14 @@ export async function action({ request }: ActionFunctionArgs) {(sp) => sp.itemId === itemId && sp.supplierId === supplierId);- const purchasing = await client- .from("itemReplenishment")- .select("purchasingBlocked")- .eq("itemId", itemId)- .eq("companyId", companyId)- .single();+ const purchasing = {+ data: purchasingByItem.get(itemId),+ error:+ purchasingRows.error ??+ (purchasingByItem.has(itemId)+ ? null+ : { message: "No replenishment record" })+ };if (purchasing.error) {logger.error("Failed to retrieve item replenishment", {diff --git a/apps/erp/app/routes/x+/purchasing+/quotes.tsx b/apps/erp/app/routes/x+/purchasing+/quotes.tsxindex 6b4eed0c89..ba363d64aa 100644--- a/apps/erp/app/routes/x+/purchasing+/quotes.tsx+++ b/apps/erp/app/routes/x+/purchasing+/quotes.tsx@@ -20,6 +20,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["supplierQuote"],breadcrumb: msg`Supplier Quotes`,to: path.to.supplierQuotes};diff --git a/apps/erp/app/routes/x+/purchasing+/rfqs.tsx b/apps/erp/app/routes/x+/purchasing+/rfqs.tsxindex c6808b8cec..48586fb573 100644--- a/apps/erp/app/routes/x+/purchasing+/rfqs.tsx+++ b/apps/erp/app/routes/x+/purchasing+/rfqs.tsx@@ -17,6 +17,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["purchasingRfq"],breadcrumb: msg`RFQs`,to: path.to.purchasingRfqs};diff --git a/apps/erp/app/routes/x+/purchasing+/supplier-returns.tsx b/apps/erp/app/routes/x+/purchasing+/supplier-returns.tsxindex 092152eaa5..a5f7a8e6c0 100644--- a/apps/erp/app/routes/x+/purchasing+/supplier-returns.tsx+++ b/apps/erp/app/routes/x+/purchasing+/supplier-returns.tsx@@ -17,6 +17,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["purchaseReturnOrder"],breadcrumb: msg`Supplier Returns`,to: path.to.purchaseReturnOrders};diff --git a/apps/erp/app/routes/x+/purchasing+/supplier-types.$supplierTypeId.tsx b/apps/erp/app/routes/x+/purchasing+/supplier-types.$supplierTypeId.tsxindex 86752012f1..3215a9e33e 100644--- a/apps/erp/app/routes/x+/purchasing+/supplier-types.$supplierTypeId.tsx+++ b/apps/erp/app/routes/x+/purchasing+/supplier-types.$supplierTypeId.tsx@@ -8,11 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";import {getSupplierType,@@ -22,7 +18,6 @@ import {import { SupplierTypeForm } from "~/modules/purchasing/ui/SupplierTypes";import { getCustomFields, setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";-import { getCompanyId, supplierTypesQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -56,14 +51,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {};}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- supplierTypesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);const { client, userId } = await requirePermissions(request, {diff --git a/apps/erp/app/routes/x+/purchasing+/supplier-types.delete.$supplierTypeId.tsx b/apps/erp/app/routes/x+/purchasing+/supplier-types.delete.$supplierTypeId.tsxindex 2f4a4556da..9ad6ad1334 100644--- a/apps/erp/app/routes/x+/purchasing+/supplier-types.delete.$supplierTypeId.tsx+++ b/apps/erp/app/routes/x+/purchasing+/supplier-types.delete.$supplierTypeId.tsx@@ -7,16 +7,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";import { deleteSupplierType, getSupplierType } from "~/modules/purchasing";import { getParams, path } from "~/utils/path";-import { getCompanyId, supplierTypesQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -73,14 +68,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- supplierTypesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function DeleteSupplierTypeRoute() {const { supplierTypeId } = useParams();const { supplierType } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/purchasing+/supplier-types.new.tsx b/apps/erp/app/routes/x+/purchasing+/supplier-types.new.tsxindex 8835ac90cc..95df20ae4c 100644--- a/apps/erp/app/routes/x+/purchasing+/supplier-types.new.tsx+++ b/apps/erp/app/routes/x+/purchasing+/supplier-types.new.tsx@@ -8,11 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data } from "react-router";import {supplierTypeValidator,@@ -21,7 +17,6 @@ import {import { SupplierTypeForm } from "~/modules/purchasing/ui/SupplierTypes";import { setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";-import { getCompanyId, supplierTypesQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {await requirePermissions(request, {@@ -75,14 +70,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- supplierTypesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function NewSupplierTypesRoute() {const closeRoute = useCloseRoute();const initialValues = {diff --git a/apps/erp/app/routes/x+/purchasing+/suppliers.tsx b/apps/erp/app/routes/x+/purchasing+/suppliers.tsxindex 4cc7fb09e2..7c8b404c33 100644--- a/apps/erp/app/routes/x+/purchasing+/suppliers.tsx+++ b/apps/erp/app/routes/x+/purchasing+/suppliers.tsx@@ -19,6 +19,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["supplier"],breadcrumb: msg`Suppliers`,to: path.to.suppliers};diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.convert.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.convert.tsxdeleted file mode 100644index e4b96c96a7..0000000000--- a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.convert.tsx+++ /dev/null@@ -1,156 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { assertIsPost, error, success } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { getLogger } from "@carbon/logger";-import { redirect } from "@carbon/utils";-import type { ActionFunctionArgs } from "react-router";-import {- getPurchasingRFQ,- getPurchasingRFQLines,- getPurchasingRFQSuppliers,- insertSupplierQuote,- updatePurchasingRFQStatus,- upsertSupplierQuoteLine-} from "~/modules/purchasing";-import type { ItemType } from "~/modules/shared";-import { itemType } from "~/modules/shared";-import { path } from "~/utils/path";--const logger = getLogger("erp", "rfqid-convert");--export async function action({ request, params }: ActionFunctionArgs) {- assertIsPost(request);- const { client, companyId, companyGroupId, userId } =- await requirePermissions(request, {- create: "purchasing"- });-- const { rfqId } = params;- if (!rfqId) throw new Error("Could not find rfqId");-- // Get RFQ, lines, and suppliers- const [rfqResult, linesResult, suppliersResult] = await Promise.all([- getPurchasingRFQ(client, rfqId),- getPurchasingRFQLines(client, rfqId),- getPurchasingRFQSuppliers(client, rfqId)- ]);-- if (rfqResult.error) {- throw redirect(- path.to.purchasingRfqDetails(rfqId),- await flash(request, error(rfqResult.error, "Failed to load RFQ"))- );- }-- if (linesResult.error) {- throw redirect(- path.to.purchasingRfqDetails(rfqId),- await flash(request, error(linesResult.error, "Failed to load RFQ lines"))- );- }-- if (suppliersResult.error) {- throw redirect(- path.to.purchasingRfqDetails(rfqId),- await flash(- request,- error(suppliersResult.error, "Failed to load RFQ suppliers")- )- );- }-- // const rfq = rfqResult.data;- const lines = linesResult.data ?? [];- const suppliers = suppliersResult.data ?? [];-- if (suppliers.length === 0) {- throw redirect(- path.to.purchasingRfqDetails(rfqId),- await flash(request, error(null, "No suppliers found for this RFQ"))- );- }-- if (lines.length === 0) {- throw redirect(- path.to.purchasingRfqDetails(rfqId),- await flash(request, error(null, "No line items found for this RFQ"))- );- }-- // Create a supplier quote for each supplier- const createdQuotes: string[] = [];-- for (const rfqSupplier of suppliers) {- const supplierId = rfqSupplier.supplierId;-- // Create the supplier quote- const quoteResult = await insertSupplierQuote(client, {- supplierId,- companyId,- companyGroupId,- createdBy: userId- });-- if (quoteResult.error || !quoteResult.data) {- logger.error("Failed to create supplier quote", {- error: quoteResult.error- });- continue;- }-- const supplierQuoteId = quoteResult.data.id;- createdQuotes.push(supplierQuoteId);-- // Create quote lines for each RFQ line that has an itemId- for (const line of lines) {- // Skip lines without an itemId since supplierQuoteLine.itemId is NOT NULL- if (!line.itemId) {- logger.warning("Skipping line without itemId", { error: line.id });- continue;- }-- // @ts-expect-error TS2339 - TODO: fix type- const uom = line.unitOfMeasureCode ?? "EA";-- await upsertSupplierQuoteLine(client, {- supplierQuoteId,- supplierQuoteLineType: itemType.includes(line.itemType as ItemType)- ? (line.itemType as ItemType)- : "Part",- itemId: line.itemId,- description: line.description ?? "",- quantity: line.quantity ?? [1],- inventoryUnitOfMeasureCode: uom,- purchaseUnitOfMeasureCode: uom,- companyId,- createdBy: userId- });- }-- // Link RFQ to supplier quote- await client.from("purchasingRfqToSupplierQuote").insert({- purchasingRfqId: rfqId,- supplierQuoteId,- companyId- });- }-- // Update RFQ status to Received- await updatePurchasingRFQStatus(client, {- id: rfqId,- status: "Requested",- updatedBy: userId- });-- throw redirect(- path.to.purchasingRfqDetails(rfqId),- await flash(- request,- success(`Created ${createdQuotes.length} supplier quote(s)`)- )- );-}diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsxindex 9935d63da5..72350eabe0 100644--- a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx+++ b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.finalize.tsx@@ -13,34 +13,28 @@ import { redirect, tiptapToHTML } from "@carbon/utils";import type { JSONContent } from "@tiptap/react";import type { ActionFunctionArgs } from "react-router";import {+ finalizePurchasingRfq,getPurchasingRFQ,getPurchasingRFQLines,- getPurchasingRFQSuppliers,- getSupplierContact,getSupplierInteractionDocuments,- getSupplierInteractionLineDocuments,- insertSupplierQuote,- purchasingRfqFinalizeValidator,- updatePurchasingRFQStatus,- upsertSupplierQuoteLine+ getSupplierInteractionLineAttachments,+ purchasingRfqFinalizeValidator} from "~/modules/purchasing";import { getCompany } from "~/modules/settings";-import type { ItemType } from "~/modules/shared";-import { itemType, upsertExternalLink } from "~/modules/shared";import { requireCompanyRecord } from "~/modules/shared/shared.server";import { getUser } from "~/modules/users/users.server";+import { getDatabaseClient } from "~/services/database.server";import { path } from "~/utils/path";const logger = getLogger("erp", "purchasing-rfq", "finalize");export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, companyId, companyGroupId, userId } =- await requirePermissions(request, {- create: "purchasing",- role: "employee",- bypassRls: true- });+ const { client, companyId, userId } = await requirePermissions(request, {+ create: "purchasing",+ role: "employee",+ bypassRls: true+ });const { rfqId } = params;if (!rfqId) throw new Error("Could not find rfqId");@@ -63,10 +57,9 @@ export async function action({ request, params }: ActionFunctionArgs) {const { suppliers: supplierContacts } = validation.data;// Get RFQ, lines, and suppliers- const [rfqResult, linesResult, suppliersResult] = await Promise.all([+ const [rfqResult, linesResult] = await Promise.all([getPurchasingRFQ(client, rfqId),- getPurchasingRFQLines(client, rfqId),- getPurchasingRFQSuppliers(client, rfqId)+ getPurchasingRFQLines(client, rfqId)]);if (rfqResult.error) {@@ -83,26 +76,7 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- if (suppliersResult.error) {- throw redirect(- path.to.purchasingRfqDetails(rfqId),- await flash(- request,- error(suppliersResult.error, "Failed to load RFQ suppliers")- )- );- }-const lines = linesResult.data ?? [];- const suppliers = suppliersResult.data ?? [];-- if (suppliers.length === 0) {- throw redirect(- path.to.purchasingRfqDetails(rfqId),- await flash(request, error(null, "No suppliers found for this RFQ"))- );- }-if (lines.length === 0) {throw redirect(path.to.purchasingRfqDetails(rfqId),@@ -119,123 +93,56 @@ export async function action({ request, params }: ActionFunctionArgs) {const requestUrl = new URL(request.url);const baseUrl = `${requestUrl.protocol}//${requestUrl.host}`;- // Create a supplier quote for each supplier- const createdQuotes: string[] = [];- const emailsToSend: Array<{- contactEmail: string;- contactFirstName: string;- supplierQuoteId: string;- supplierQuoteReadableId: string;- externalLinkId: string;- }> = [];-- for (const rfqSupplier of suppliers) {- const supplierId = rfqSupplier.supplierId;- const supplierContactData = supplierContacts.find(- (sc) => sc.supplierId === supplierId+ // The quotes, their lines and share links, and the RFQ's status are written+ // in one transaction.+ const finalize = await finalizePurchasingRfq(client, getDatabaseClient(), {+ rfqId,+ companyId,+ userId+ });+ if (finalize.error) {+ throw redirect(+ path.to.purchasingRfqDetails(rfqId),+ await flash(+ request,+ error(+ finalize.error,+ finalize.error.message || "Failed to create supplier quotes"+ )+ ));-- // Create the supplier quote- const quoteResult = await insertSupplierQuote(client, {- supplierId,- companyId,- companyGroupId,- createdBy: userId- });-- if (quoteResult.error || !quoteResult.data) {- logger.error("Failed to create supplier quote", {- error: quoteResult.error- });- continue;- }-- const supplierQuoteId = quoteResult.data.id;- const supplierQuoteReadableId = quoteResult.data.supplierQuoteId;- createdQuotes.push(supplierQuoteId);-- // Create quote lines for each RFQ line that has an itemId- for (const line of lines) {- // Skip lines without an itemId since supplierQuoteLine.itemId is NOT NULL- if (!line.itemId) {- logger.warning("Skipping line without itemId", { lineId: line.id });- continue;- }-- await upsertSupplierQuoteLine(client, {- supplierQuoteId,- supplierQuoteLineType: itemType.includes(line.itemType as ItemType)- ? (line.itemType as ItemType)- : "Part",- itemId: line.itemId,- description: line.description ?? "",- quantity: line.quantity ?? [1],- inventoryUnitOfMeasureCode: line.inventoryUnitOfMeasureCode ?? "EA",- purchaseUnitOfMeasureCode: line.purchaseUnitOfMeasureCode ?? "EA",- conversionFactor: line.conversionFactor ?? 1,- companyId,- createdBy: userId- });- }-- // Link RFQ to supplier quote- await client.from("purchasingRfqToSupplierQuote").insert({- purchasingRfqId: rfqId,- supplierQuoteId,- companyId- });-- // Create or get external link for the supplier quote (required for sharing/email)- // First check if one already exists (in case quote was created before)- const existingLink = await client- .from("externalLink")- .select("id")- .eq("documentId", supplierQuoteId)- .eq("documentType", "SupplierQuote")- .eq("companyId", companyId)- .maybeSingle();-- const externalLinkResult = await upsertExternalLink(client, {- id: existingLink.data?.id,- documentType: "SupplierQuote",- documentId: supplierQuoteId,- supplierId,- companyId- });-- // Update quote with external link ID- if (externalLinkResult.data) {- await client- .from("supplierQuote")- .update({ externalLinkId: externalLinkResult.data.id })- .eq("id", supplierQuoteId);- }-- // If contact was provided, queue up email- if (supplierContactData?.contactId && externalLinkResult.data) {- const supplierContact = await getSupplierContact(- client,- supplierContactData.contactId,- companyId- );-- if (supplierContact?.data?.contact?.email) {- emailsToSend.push({- contactEmail: supplierContact.data.contact.email,- contactFirstName: supplierContact.data.contact.firstName ?? "there",- supplierQuoteId,- supplierQuoteReadableId,- externalLinkId: externalLinkResult.data.id- });- }- }}+ const createdQuotes = finalize.data.quotes;- // Update RFQ status to Requested- await updatePurchasingRFQStatus(client, {- id: rfqId,- status: "Requested",- updatedBy: userId+ const contactIdBySupplier = new Map(+ supplierContacts.flatMap((sc) =>+ sc.contactId ? [[sc.supplierId, sc.contactId] as const] : []+ )+ );+ const contacts = contactIdBySupplier.size+ ? await client+ .from("supplierContact")+ .select("id, contact(email, firstName)")+ .in("id", [...contactIdBySupplier.values()])+ .eq("companyId", companyId)+ : null;+ const contactById = new Map(+ (contacts?.data ?? []).map((row) => [row.id, row.contact])+ );++ const emailsToSend = createdQuotes.flatMap((quote) => {+ const contactId = contactIdBySupplier.get(quote.supplierId);+ const contact = contactId ? contactById.get(contactId) : undefined;+ return contact?.email+ ? [+ {+ contactEmail: contact.email,+ contactFirstName: contact.firstName ?? "there",+ supplierQuoteReadableId: quote.supplierQuoteId,+ externalLinkId: quote.externalLinkId+ }+ ]+ : [];});// Send emails if we have any contacts (using same format as supplier quote send)@@ -266,35 +173,13 @@ export async function action({ request, params }: ActionFunctionArgs) {}}- // Fetch line-level supplier interaction documents- for (const line of lines) {- if (!line.id) continue;-- const lineDocs = await getSupplierInteractionLineDocuments(+ attachments.push(+ ...(await getSupplierInteractionLineAttachments(client,companyId,- line.id- );-- for (const doc of lineDocs) {- const storagePath = `${companyId}/supplier-interaction-line/${line.id}/${doc.name}`;- const { data, error } = await storage(client)- .company(companyId)- .createSignedUrl(storagePath, 3600);-- if (data) {- attachments.push({- filename: doc.name,- path: data.signedUrl- });- } else {- logger.error("Failed to create signed URL for attachment", {- storagePath,- error- });- }- }- }+ lines.flatMap((line) => (line.id ? [line.id] : []))+ ))+ );// Convert internal notes to HTMLconst internalNotes = (rfqResult.data?.internalNotes ?? {}) as JSONContent;diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.tsxindex 64dbf5d1d0..64179648a3 100644--- a/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.tsx+++ b/apps/erp/app/routes/x+/purchasing-rfq+/$rfqId.tsx@@ -35,6 +35,10 @@ import { path } from "~/utils/path";const logger = getLogger("erp", "purchasing-rfq");export const handle: Handle = {+ realtime: [+ { table: "purchasingRfq", column: "id", param: "rfqId" },+ { table: "purchasingRfqLine", column: "purchasingRfqId", param: "rfqId" }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`RFQs`, to: path.to.purchasingRfqs },(data) => data?.rfqSummary?.rfqIddiff --git a/apps/erp/app/routes/x+/quality+/_index.tsx b/apps/erp/app/routes/x+/quality+/_index.tsxindex 51256ff7f4..5066114426 100644--- a/apps/erp/app/routes/x+/quality+/_index.tsx+++ b/apps/erp/app/routes/x+/quality+/_index.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";+import { useLoaderQuery } from "@carbon/query";import {Badge,Button,@@ -42,7 +43,7 @@ import { msg } from "@lingui/core/macro";import { Trans, useLingui } from "@lingui/react/macro";import { useLocale } from "@react-aria/i18n";import type { DateRange } from "@react-types/datepicker";-import { Suspense, useEffect, useMemo, useState } from "react";+import { Suspense, useMemo, useState } from "react";import {LuCalendarClock,LuChevronDown,@@ -56,7 +57,7 @@ import {LuShieldX} from "react-icons/lu";import type { LoaderFunctionArgs } from "react-router";-import { Await, useFetcher, useLoaderData } from "react-router";+import { Await, useLoaderData } from "react-router";import {Bar,BarChart,@@ -307,9 +308,6 @@ export default function QualityDashboard() {return { start, end };});- const kpiFetcher = useFetcher<typeof kpiLoader>();- const avgFetcher = useFetcher<typeof kpiLoader>();-const selectedChartData =QualityKPIs.find((c) => c.key === selectedChart) || QualityKPIs[0];@@ -347,16 +345,19 @@ export default function QualityDashboard() {setInterval(value);};- // Fetch chart data when filters change- // biome-ignore lint/correctness/useExhaustiveDependencies: don't include the load functions- useEffect(() => {- if (!dateRange?.start || !dateRange?.end) return;- const params = `?start=${dateRange.start.toString()}&end=${dateRange.end.toString()}&interval=${interval}${- issueTypeId === "all" ? "" : `&issueTypeId=${issueTypeId}`- }`;- kpiFetcher.load(path.to.api.qualityKpi(selectedChart) + params);- avgFetcher.load(path.to.api.qualityKpi("avgDaysToClose") + params);- }, [selectedChart, dateRange, interval, issueTypeId]);+ // The chart data follows the filters.+ const kpiParams =+ dateRange?.start && dateRange?.end+ ? `?start=${dateRange.start.toString()}&end=${dateRange.end.toString()}&interval=${interval}${+ issueTypeId === "all" ? "" : `&issueTypeId=${issueTypeId}`+ }`+ : null;+ const kpiFetcher = useLoaderQuery<typeof kpiLoader>(+ kpiParams ? path.to.api.qualityKpi(selectedChart) + kpiParams : null+ );+ const avgFetcher = useLoaderQuery<typeof kpiLoader>(+ kpiParams ? path.to.api.qualityKpi("avgDaysToClose") + kpiParams : null+ );const avgDaysToClose = (avgFetcher.data?.data as any)?.[0]?.value ?? null;diff --git a/apps/erp/app/routes/x+/quality+/inbound-inspections.tsx b/apps/erp/app/routes/x+/quality+/inbound-inspections.tsxindex f6d184db8e..238f519891 100644--- a/apps/erp/app/routes/x+/quality+/inbound-inspections.tsx+++ b/apps/erp/app/routes/x+/quality+/inbound-inspections.tsx@@ -4,8 +4,13 @@import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";+import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";+export const handle: Handle = {+ realtime: ["inspection"]+};+// The Inbound Inspections submodule was renamed to Inspections.export async function loader({ request }: LoaderFunctionArgs) {const search = new URL(request.url).search;diff --git a/apps/erp/app/routes/x+/quality+/inspection-plans.new.tsx b/apps/erp/app/routes/x+/quality+/inspection-plans.new.tsxindex 9119126101..6ccf8c1eac 100644--- a/apps/erp/app/routes/x+/quality+/inspection-plans.new.tsx+++ b/apps/erp/app/routes/x+/quality+/inspection-plans.new.tsx@@ -8,16 +8,11 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { upsertInspectionDocument } from "~/modules/quality";import { inspectionDocumentValidator } from "~/modules/quality/quality.models";import { InspectionDocumentForm } from "~/modules/quality/ui/InspectionDocument";import { path } from "~/utils/path";-import { invalidateInspectionDocuments } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {await requirePermissions(request, { create: "quality" });@@ -61,11 +56,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- invalidateInspectionDocuments();- return await serverAction();-}-export default function BalloonNewRoute() {const closeRoute = useCloseRoute();diff --git a/apps/erp/app/routes/x+/quality+/inspections.tsx b/apps/erp/app/routes/x+/quality+/inspections.tsxindex 990aabaf0d..88cbc7581c 100644--- a/apps/erp/app/routes/x+/quality+/inspections.tsx+++ b/apps/erp/app/routes/x+/quality+/inspections.tsx@@ -17,6 +17,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["inspection"],breadcrumb: msg`Inspections`,to: path.to.inspections};diff --git a/apps/erp/app/routes/x+/quality+/issue-types.$id.tsx b/apps/erp/app/routes/x+/quality+/issue-types.$id.tsxindex d3fc105e38..3c210fd924 100644--- a/apps/erp/app/routes/x+/quality+/issue-types.$id.tsx+++ b/apps/erp/app/routes/x+/quality+/issue-types.$id.tsx@@ -8,11 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";import {getIssueType,@@ -23,7 +19,6 @@ import {import IssueTypeForm from "~/modules/quality/ui/IssueTypes/IssueTypeForm";import { getCustomFields, setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { getCompanyId, issueTypesQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -107,14 +102,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- issueTypesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function EditIssueTypeRoute() {const { nonConformanceType } = useLoaderData<typeof loader>();const closeRoute = useCloseRoute();diff --git a/apps/erp/app/routes/x+/quality+/issue-types.delete.$id.tsx b/apps/erp/app/routes/x+/quality+/issue-types.delete.$id.tsxindex 300fcd338c..a94373085b 100644--- a/apps/erp/app/routes/x+/quality+/issue-types.delete.$id.tsx+++ b/apps/erp/app/routes/x+/quality+/issue-types.delete.$id.tsx@@ -7,16 +7,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";import { deleteIssueType, getIssueType } from "~/modules/quality";import { getParams, path } from "~/utils/path";-import { getCompanyId, issueTypesQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -72,14 +67,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- issueTypesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function DeleteIssueTypesRoute() {const { id } = useParams();const { nonConformanceType } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/quality+/issue-types.new.tsx b/apps/erp/app/routes/x+/quality+/issue-types.new.tsxindex 35209baed4..617eea22d1 100644--- a/apps/erp/app/routes/x+/quality+/issue-types.new.tsx+++ b/apps/erp/app/routes/x+/quality+/issue-types.new.tsx@@ -8,11 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import {getIssueTypeByName,issueTypeValidator,@@ -21,7 +17,6 @@ import {import IssueTypeForm from "~/modules/quality/ui/IssueTypes/IssueTypeForm";import { setCustomFields } from "~/utils/form";import { getParams, path, requestReferrer } from "~/utils/path";-import { getCompanyId, issueTypesQuery } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {await requirePermissions(request, {@@ -92,14 +87,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- issueTypesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function NewCustomerStatusesRoute() {const closeRoute = useCloseRoute();const initialValues = {diff --git a/apps/erp/app/routes/x+/quality+/issues.tsx b/apps/erp/app/routes/x+/quality+/issues.tsxindex 1d744ec23c..314ffa6124 100644--- a/apps/erp/app/routes/x+/quality+/issues.tsx+++ b/apps/erp/app/routes/x+/quality+/issues.tsx@@ -20,6 +20,7 @@ import { getGenericQueryFilters } from "~/utils/query";const logger = getLogger("erp", "issues");export const handle: Handle = {+ realtime: ["nonConformance"],breadcrumb: msg`Issues`,to: path.to.issues};diff --git a/apps/erp/app/routes/x+/quality-document+/update.tsx b/apps/erp/app/routes/x+/quality-document+/update.tsxindex fdd20ef2fc..99e44ee01c 100644--- a/apps/erp/app/routes/x+/quality-document+/update.tsx+++ b/apps/erp/app/routes/x+/quality-document+/update.tsx@@ -45,15 +45,31 @@ async function processToActive(const archivedIdsToMoveToDraft: string[] = [];const canTransitionToActive = (s: string | null) =>s === "Draft" || s === "Archived";- for (const doc of docList) {- if (!canTransitionToActive(doc.status)) continue;- const approvalRequired = await isApprovalRequired(+ // The same answer for every document: read once, and only when one needs it.+ const transitioning = docList.filter((doc) =>+ canTransitionToActive(doc.status)+ );+ const approvalRequired =+ transitioning.length > 0 &&+ (await isApprovalRequired(+ serviceRole,+ "qualityDocument",+ companyId,+ undefined+ ));+ let approvers: Promise<string[]> | undefined;+ const getApprovers = () => {+ approvers ??= getApprovalRuleByAmount(serviceRole,"qualityDocument",companyId,undefined+ ).then((rule) =>+ rule.data ? getApproverUserIdsForRule(serviceRole, rule.data) : []);- if (!approvalRequired) continue;+ return approvers;+ };+ for (const doc of approvalRequired ? transitioning : []) {const hasPending = await hasPendingApproval(serviceRole,"qualityDocument",@@ -72,15 +88,7 @@ async function processToActive(amount: undefined});- const rule = await getApprovalRuleByAmount(- serviceRole,- "qualityDocument",- companyId,- undefined- );- const approverIds = rule.data- ? await getApproverUserIdsForRule(serviceRole, rule.data)- : [];+ const approverIds = await getApprovers();if (approverIds.length > 0) {try {diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.tsxindex 65999e85b8..67b3abd964 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.tsx@@ -44,6 +44,13 @@ import { detailBreadcrumb, type Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {+ realtime: [+ { table: "quote", column: "id", param: "quoteId" },+ { table: "quoteLine", column: "quoteId", param: "quoteId" },+ { table: "quoteMaterial", column: "quoteId", param: "quoteId" },+ { table: "quoteOperation", column: "quoteId", param: "quoteId" },+ { table: "quoteMakeMethod", column: "quoteId", param: "quoteId" }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`Quotes`, to: path.to.quotes },(data) => data?.quote?.quoteId@@ -65,7 +72,21 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { quoteId } = params;if (!quoteId) throw new Error("Could not find quoteId");- const quote = await getQuote(client, quoteId);+ // Three steps at most, not five. Everything that needs only the quote id is+ // read with the quote; what needs the quote's or those reads' values follows+ // together; sales order lines wait for the opportunity. `client` is the+ // service role, so nothing read here is returned unless the quote turns out+ // to be this company's.+ const [quote, shipment, payment, lines, prices, methods, companySettings] =+ await Promise.all([+ getQuote(client, quoteId),+ getQuoteShipment(client, quoteId),+ getQuotePayment(client, quoteId),+ getQuoteLines(client, quoteId),+ getQuoteLinePricesByQuoteId(client, quoteId),+ getQuoteMethodTrees(client, quoteId),+ getCompanySettings(client, companyId)+ ]);if (quote.error) {throw redirect(@@ -78,25 +99,32 @@ export async function loader({ request, params }: LoaderFunctionArgs) {throw redirect(path.to.quotes);}- const [- customer,- shipment,- payment,- lines,- prices,- opportunity,- methods,- companySettings- ] = await Promise.all([- getCustomer(client, quote.data?.customerId ?? ""),- getQuoteShipment(client, quoteId),- getQuotePayment(client, quoteId),- getQuoteLines(client, quoteId),- getQuoteLinePricesByQuoteId(client, quoteId),- getOpportunity(client, quote.data?.opportunityId),- getQuoteMethodTrees(client, quoteId),- getCompanySettings(client, companyId)- ]);+ // Collect all Buy item IDs from method trees + top-level Buy lines+ const methodTrees = methods.data ?? [];+ const buyItemIds = new Set<string>();+ function collectBuyItems(tree: (typeof methodTrees)[number]) {+ if (tree.data.methodType === "Purchase to Order" && tree.data.itemId) {+ buyItemIds.add(tree.data.itemId);+ }+ tree.children?.forEach(collectBuyItems);+ }+ methodTrees.forEach(collectBuyItems);+ // Also include top-level Buy lines (non-Make lines)+ for (const line of lines.data ?? []) {+ if (line.methodType === "Purchase to Order" && line.itemId) {+ buyItemIds.add(line.itemId);+ }+ }++ const [customer, opportunity, presentationExchangeRate, supplierPriceMap] =+ await Promise.all([+ getCustomer(client, quote.data?.customerId ?? ""),+ getOpportunity(client, quote.data?.opportunityId),+ quote.data?.currencyCode+ ? getExchangeRate(client, companyId, quote.data.currencyCode)+ : null,+ getSupplierPriceBreaksForItems(client, Array.from(buyItemIds))+ ]);if (opportunity.error) {throw new Error(@@ -118,10 +146,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- if (companyId !== quote.data?.companyId) {- throw redirect(path.to.quotes);- }-if (shipment.error) {throw redirect(path.to.quotes,@@ -139,21 +163,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- let exchangeRate = 1;- if (quote.data?.currencyCode) {- const presentationExchangeRate = await getExchangeRate(- client,- companyId,- quote.data.currencyCode- );- // A missing LIVE rate must not make the quote unopenable — this page hosts- // the refresh button that fixes it. Fall back to the document's own stamped- // snapshot (the PDF routes' policy); writes still refuse.- exchangeRate =- presentationExchangeRate.error || presentationExchangeRate.data === null- ? (quote.data.exchangeRate ?? 1)- : presentationExchangeRate.data;- }+ // A missing LIVE rate must not make the quote unopenable — this page hosts+ // the refresh button that fixes it. Fall back to the document's own stamped+ // snapshot (the PDF routes' policy); writes still refuse.+ const exchangeRate = !presentationExchangeRate+ ? 1+ : presentationExchangeRate.error || presentationExchangeRate.data === null+ ? (quote.data.exchangeRate ?? 1)+ : presentationExchangeRate.data;let salesOrderLines: PostgrestResponse<SalesOrderLine> | null = null;if (@@ -173,28 +190,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {customer.data.defaultCc: (companySettings.data?.defaultCustomerCc ?? []);- // Collect all Buy item IDs from method trees + top-level Buy lines- const methodTrees = methods.data ?? [];- const buyItemIds = new Set<string>();- function collectBuyItems(tree: (typeof methodTrees)[number]) {- if (tree.data.methodType === "Purchase to Order" && tree.data.itemId) {- buyItemIds.add(tree.data.itemId);- }- tree.children?.forEach(collectBuyItems);- }- methodTrees.forEach(collectBuyItems);- // Also include top-level Buy lines (non-Make lines)- for (const line of lines.data ?? []) {- if (line.methodType === "Purchase to Order" && line.itemId) {- buyItemIds.add(line.itemId);- }- }-- const supplierPriceMap = await getSupplierPriceBreaksForItems(- client,- Array.from(buyItemIds)- );-return {quote: quote.data,customer: customer.data,diff --git a/apps/erp/app/routes/x+/receipt+/$receiptId.tsx b/apps/erp/app/routes/x+/receipt+/$receiptId.tsxindex a2d56e297b..c9419f3bad 100644--- a/apps/erp/app/routes/x+/receipt+/$receiptId.tsx+++ b/apps/erp/app/routes/x+/receipt+/$receiptId.tsx@@ -27,6 +27,10 @@ import { detailBreadcrumb, type Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {+ realtime: [+ { table: "receipt", column: "id", param: "receiptId" },+ { table: "receiptLine", column: "receiptId", param: "receiptId" }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`Receipts`, to: path.to.receipts },(data) => data?.receipt?.receiptIddiff --git a/apps/erp/app/routes/x+/resources+/_index.tsx b/apps/erp/app/routes/x+/resources+/_index.tsxindex 116dd082ff..01fd217c35 100644--- a/apps/erp/app/routes/x+/resources+/_index.tsx+++ b/apps/erp/app/routes/x+/resources+/_index.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";+import { useLoaderQuery } from "@carbon/query";import {Badge,Button,@@ -42,7 +43,7 @@ import { getLocalTimeZone, parseDate, today } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";import { useDateFormatter, useNumberFormatter } from "@react-aria/i18n";import type { DateRange } from "@react-types/datepicker";-import { Suspense, useEffect, useMemo, useState } from "react";+import { Suspense, useMemo, useState } from "react";import {LuCalendarClock,LuChevronDown,@@ -54,7 +55,7 @@ import {LuWrench} from "react-icons/lu";import type { LoaderFunctionArgs } from "react-router";-import { Await, useFetcher, useLoaderData } from "react-router";+import { Await, useLoaderData } from "react-router";import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";import { DateSelect, Empty, Hyperlink, MetricCard } from "~/components";import { CSVLink } from "~/components/CSVLink";@@ -143,9 +144,6 @@ export default function MaintenanceDashboard() {assignedToMe} = useLoaderData<typeof loader>();- const kpiFetcher = useFetcher<typeof kpiLoader>();- const isFetching = kpiFetcher.state !== "idle" || !kpiFetcher.data;-const dateFormatter = useDateFormatter({month: "short",day: "numeric"@@ -181,6 +179,15 @@ export default function MaintenanceDashboard() {const selectedKpiData =MaintenanceKPIs.find((k) => k.key === selectedKpi) || MaintenanceKPIs[0];+ const kpiFetcher = useLoaderQuery<typeof kpiLoader>(+ `${path.to.api.resourcesKpi(+ selectedKpiData.key+ )}?start=${dateRange?.start.toString()}&end=${dateRange?.end.toString()}&interval=${interval}${+ workCenterId === "all" ? "" : `&workCenterId=${workCenterId}`+ }`+ );+ const isFetching = kpiFetcher.isFetching || !kpiFetcher.data;+const kpiLabels: Record<string, string> = useMemo(() => ({mttr: t`Mean Time To Repair`,@@ -192,17 +199,6 @@ export default function MaintenanceDashboard() {[t]);- // biome-ignore lint/correctness/useExhaustiveDependencies: deps are intentionally limited- useEffect(() => {- kpiFetcher.load(- `${path.to.api.resourcesKpi(- selectedKpiData.key- )}?start=${dateRange?.start.toString()}&end=${dateRange?.end.toString()}&interval=${interval}${- workCenterId === "all" ? "" : `&workCenterId=${workCenterId}`- }`- );- }, [selectedKpi, dateRange, interval, selectedKpiData.key, workCenterId]);-const onIntervalChange = (value: string) => {const end = today("UTC");if (value === "week") {diff --git a/apps/erp/app/routes/x+/resources+/locations.$locationId.tsx b/apps/erp/app/routes/x+/resources+/locations.$locationId.tsxindex ddbf33cc49..5548ab6db5 100644--- a/apps/erp/app/routes/x+/resources+/locations.$locationId.tsx+++ b/apps/erp/app/routes/x+/resources+/locations.$locationId.tsx@@ -9,11 +9,7 @@ import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";import { getLocalTimeZone } from "@internationalized/date";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import {getLocation,@@ -24,7 +20,6 @@ import {import { invalidateLocationTimeZone } from "~/modules/shared/timezone.server";import { getCustomFields, setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { getCompanyId, locationsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -90,14 +85,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- locationsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function LocationRoute() {const { location } = useLoaderData<typeof loader>();const closeRoute = useCloseRoute();diff --git a/apps/erp/app/routes/x+/resources+/locations.delete.$locationId.tsx b/apps/erp/app/routes/x+/resources+/locations.delete.$locationId.tsxindex 236c4674f2..a957aea8d3 100644--- a/apps/erp/app/routes/x+/resources+/locations.delete.$locationId.tsx+++ b/apps/erp/app/routes/x+/resources+/locations.delete.$locationId.tsx@@ -7,16 +7,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";import { deleteLocation, getLocation } from "~/modules/resources";import { path } from "~/utils/path";-import { getCompanyId, locationsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -73,14 +68,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- locationsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function DeleteLocationRoute() {const { locationId } = useParams();const { location } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/resources+/locations.new.tsx b/apps/erp/app/routes/x+/resources+/locations.new.tsxindex 982783cddc..fbf88029b1 100644--- a/apps/erp/app/routes/x+/resources+/locations.new.tsx+++ b/apps/erp/app/routes/x+/resources+/locations.new.tsx@@ -8,10 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";import { getLocalTimeZone } from "@internationalized/date";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { useNavigate } from "react-router";import { useUser } from "~/hooks";import {@@ -21,7 +18,6 @@ import {} from "~/modules/resources";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { getCompanyId, locationsQuery } from "~/utils/react-query";export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);@@ -68,14 +64,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- locationsQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function NewLocationRoute() {const navigate = useNavigate();const { company } = useUser();diff --git a/apps/erp/app/routes/x+/resources+/processes.$processId.tsx b/apps/erp/app/routes/x+/resources+/processes.$processId.tsxindex 5ef8404275..0b411ac87b 100644--- a/apps/erp/app/routes/x+/resources+/processes.$processId.tsx+++ b/apps/erp/app/routes/x+/resources+/processes.$processId.tsx@@ -9,11 +9,7 @@ import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import type { BatchRules } from "@carbon/utils";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { notifyScheduleInputsChanged } from "~/modules/production";import {@@ -26,7 +22,6 @@ import {} from "~/modules/resources";import { getCustomFields, setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { getCompanyId, processesQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -151,14 +146,6 @@ export async function action({ request }: ActionFunctionArgs) {return modal ? createProcess : redirect(path.to.processes);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- processesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function ProcessRoute() {const { process } = useLoaderData<typeof loader>();const closeRoute = useCloseRoute();diff --git a/apps/erp/app/routes/x+/resources+/processes.activate.$processId.tsx b/apps/erp/app/routes/x+/resources+/processes.activate.$processId.tsxindex ba591e3e25..42a8f0cf41 100644--- a/apps/erp/app/routes/x+/resources+/processes.activate.$processId.tsx+++ b/apps/erp/app/routes/x+/resources+/processes.activate.$processId.tsx@@ -7,16 +7,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import { Confirm } from "~/components/Modals";import { activateProcess, getProcess } from "~/modules/resources";import { path } from "~/utils/path";-import { getCompanyId, processesQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -73,14 +68,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- processesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function ActivateProcessRoute() {const { processId } = useParams();const { process } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/resources+/processes.deactivate.$processId.tsx b/apps/erp/app/routes/x+/resources+/processes.deactivate.$processId.tsxindex 6e6d06db55..b3a4cd8420 100644--- a/apps/erp/app/routes/x+/resources+/processes.deactivate.$processId.tsx+++ b/apps/erp/app/routes/x+/resources+/processes.deactivate.$processId.tsx@@ -7,16 +7,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import { Confirm } from "~/components/Modals";import { getProcess, processDeactivate } from "~/modules/resources";import { path } from "~/utils/path";-import { getCompanyId, processesQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -73,14 +68,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- processesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function DeactivateProcessRoute() {const { processId } = useParams();const { process } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/resources+/processes.delete.$processId.tsx b/apps/erp/app/routes/x+/resources+/processes.delete.$processId.tsxindex 209c664215..8c9cdf538f 100644--- a/apps/erp/app/routes/x+/resources+/processes.delete.$processId.tsx+++ b/apps/erp/app/routes/x+/resources+/processes.delete.$processId.tsx@@ -7,16 +7,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import { Confirm } from "~/components/Modals";import { deleteProcess, getProcess } from "~/modules/resources";import { path } from "~/utils/path";-import { getCompanyId, processesQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -70,14 +65,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- processesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function DeleteProcessRoute() {const { processId } = useParams();const { process } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/resources+/processes.new.tsx b/apps/erp/app/routes/x+/resources+/processes.new.tsxindex 1f81b5fef0..2240a14c87 100644--- a/apps/erp/app/routes/x+/resources+/processes.new.tsx+++ b/apps/erp/app/routes/x+/resources+/processes.new.tsx@@ -7,10 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { useNavigate } from "react-router";import {batchRuleInitialValues,@@ -21,7 +18,6 @@ import {} from "~/modules/resources";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { getCompanyId, processesQuery } from "~/utils/react-query";export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);@@ -95,14 +91,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- processesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function NewProcessRoute() {const navigate = useNavigate();const onClose = () => navigate(path.to.processes);diff --git a/apps/erp/app/routes/x+/resources+/work-centers.$id.tsx b/apps/erp/app/routes/x+/resources+/work-centers.$id.tsxindex e69bcd9a3e..a7e4e3e273 100644--- a/apps/erp/app/routes/x+/resources+/work-centers.$id.tsx+++ b/apps/erp/app/routes/x+/resources+/work-centers.$id.tsx@@ -7,11 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate } from "react-router";import { notifyScheduleInputsChanged } from "~/modules/production";import {@@ -22,7 +18,6 @@ import {} from "~/modules/resources";import { getCustomFields, setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { getCompanyId, workCentersQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -93,14 +88,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- workCentersQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function WorkCenterRoute() {const { workCenter } = useLoaderData<typeof loader>();const navigate = useNavigate();diff --git a/apps/erp/app/routes/x+/resources+/work-centers.activate.$id.tsx b/apps/erp/app/routes/x+/resources+/work-centers.activate.$id.tsxindex 17ab3da405..dd5e0c2ac4 100644--- a/apps/erp/app/routes/x+/resources+/work-centers.activate.$id.tsx+++ b/apps/erp/app/routes/x+/resources+/work-centers.activate.$id.tsx@@ -6,14 +6,10 @@ import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";-import type {- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { LoaderFunctionArgs } from "react-router";import { notifyScheduleInputsChanged } from "~/modules/production";import { activateWorkCenter } from "~/modules/resources";import { path } from "~/utils/path";-import { getCompanyId, workCentersQuery } from "~/utils/react-query";export async function action({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -51,11 +47,3 @@ export async function action({ request, params }: LoaderFunctionArgs) {await flash(request, success("Successfully activate work center")));}--export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- workCentersQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}diff --git a/apps/erp/app/routes/x+/resources+/work-centers.delete.$id.tsx b/apps/erp/app/routes/x+/resources+/work-centers.delete.$id.tsxindex 1aa6f882d7..4fa5830928 100644--- a/apps/erp/app/routes/x+/resources+/work-centers.delete.$id.tsx+++ b/apps/erp/app/routes/x+/resources+/work-centers.delete.$id.tsx@@ -6,14 +6,10 @@ import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";-import type {- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { LoaderFunctionArgs } from "react-router";import { notifyScheduleInputsChanged } from "~/modules/production";import { deleteWorkCenter } from "~/modules/resources";import { path } from "~/utils/path";-import { getCompanyId, workCentersQuery } from "~/utils/react-query";export async function action({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -51,11 +47,3 @@ export async function action({ request, params }: LoaderFunctionArgs) {await flash(request, success("Successfully deactivated work center")));}--export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- workCentersQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}diff --git a/apps/erp/app/routes/x+/resources+/work-centers.new.tsx b/apps/erp/app/routes/x+/resources+/work-centers.new.tsxindex 939084cc67..542028175e 100644--- a/apps/erp/app/routes/x+/resources+/work-centers.new.tsx+++ b/apps/erp/app/routes/x+/resources+/work-centers.new.tsx@@ -7,10 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { useNavigate } from "react-router";import { useUser } from "~/hooks";import { notifyScheduleInputsChanged } from "~/modules/production";@@ -21,7 +18,6 @@ import {} from "~/modules/resources";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { getCompanyId, workCentersQuery } from "~/utils/react-query";export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);@@ -69,14 +65,6 @@ export async function action({ request }: ActionFunctionArgs) {return modal ? createWorkCenter : redirect(path.to.workCenters);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- workCentersQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function NewWorkCenterRoute() {const navigate = useNavigate();const onClose = () => navigate(path.to.workCenters);diff --git a/apps/erp/app/routes/x+/sales+/_index.tsx b/apps/erp/app/routes/x+/sales+/_index.tsxindex 7ca628c62a..0caf523108 100644--- a/apps/erp/app/routes/x+/sales+/_index.tsx+++ b/apps/erp/app/routes/x+/sales+/_index.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";+import { useLoaderQuery } from "@carbon/query";import {Badge,Button,@@ -42,7 +43,7 @@ import { getLocalTimeZone, parseDate, today } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";import { useDateFormatter, useNumberFormatter } from "@react-aria/i18n";import type { DateRange } from "@react-types/datepicker";-import { Suspense, useEffect, useMemo, useState } from "react";+import { Suspense, useMemo, useState } from "react";import {LuChevronDown,LuClock,@@ -56,7 +57,7 @@ import {RiProgress8Line} from "react-icons/ri";import type { LoaderFunctionArgs } from "react-router";-import { Await, useFetcher, useLoaderData } from "react-router";+import { Await, useLoaderData } from "react-router";import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";import {CustomerAvatar,@@ -153,8 +154,52 @@ export default function SalesDashboard() {return merged;}, [openSalesOrders, openQuotes, openRFQs]);- const kpiFetcher = useFetcher<typeof kpiLoader>();- const isFetching = kpiFetcher.state !== "idle" || !kpiFetcher.data;+ const dateFormatter = useDateFormatter({+ month: "short",+ day: "numeric"+ });++ const currencyCompactFormatter = useCurrencyFormatter({ compact: true });+ const currencyFormatter = useCurrencyFormatter();+ const numberFormatter = useNumberFormatter({+ maximumFractionDigits: 0,+ notation: "compact",+ compactDisplay: "short"+ });++ const [customerId, setCustomerId] = useState<string>("all");+ const [customers] = useCustomers();+ const customerOptions = useMemo(() => {+ return [+ {+ label: t`All Customers`,+ value: "all"+ },+ ...customers.map((customer) => ({+ label: customer.name,+ value: customer.id+ }))+ ];+ }, [customers, t]);++ const [interval, setInterval] = useState("month");+ const [selectedKpi, setSelectedKpi] = useState("salesOrderRevenue");+ const [dateRange, setDateRange] = useState<DateRange | null>(() => {+ const end = today("UTC");+ const start = end.add({ months: -1 });+ return { start, end };+ });++ const selectedKpiData = KPIs.find((k) => k.key === selectedKpi) || KPIs[0];++ const kpiFetcher = useLoaderQuery<typeof kpiLoader>(+ `${path.to.api.salesKpi(+ selectedKpiData.key+ )}?start=${dateRange?.start.toString()}&end=${dateRange?.end.toString()}&interval=${interval}${+ customerId === "all" ? "" : `&customerId=${customerId}`+ }`+ );+ const isFetching = kpiFetcher.isFetching || !kpiFetcher.data;const steps = useMemo(() => {const defaultSteps = [@@ -205,44 +250,6 @@ export default function SalesDashboard() {];}, [kpiFetcher.data?.data, t]);- const dateFormatter = useDateFormatter({- month: "short",- day: "numeric"- });-- const currencyCompactFormatter = useCurrencyFormatter({ compact: true });- const currencyFormatter = useCurrencyFormatter();- const numberFormatter = useNumberFormatter({- maximumFractionDigits: 0,- notation: "compact",- compactDisplay: "short"- });-- const [customerId, setCustomerId] = useState<string>("all");- const [customers] = useCustomers();- const customerOptions = useMemo(() => {- return [- {- label: t`All Customers`,- value: "all"- },- ...customers.map((customer) => ({- label: customer.name,- value: customer.id- }))- ];- }, [customers, t]);-- const [interval, setInterval] = useState("month");- const [selectedKpi, setSelectedKpi] = useState("salesOrderRevenue");- const [dateRange, setDateRange] = useState<DateRange | null>(() => {- const end = today("UTC");- const start = end.add({ months: -1 });- return { start, end };- });-- const selectedKpiData = KPIs.find((k) => k.key === selectedKpi) || KPIs[0];-const kpiLabels: Record<string, string> = useMemo(() => ({quoteCount: t`Quotes`,@@ -254,17 +261,6 @@ export default function SalesDashboard() {[t]);- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- kpiFetcher.load(- `${path.to.api.salesKpi(- selectedKpiData.key- )}?start=${dateRange?.start.toString()}&end=${dateRange?.end.toString()}&interval=${interval}${- customerId === "all" ? "" : `&customerId=${customerId}`- }`- );- }, [selectedKpi, dateRange, interval, selectedKpiData.key, customerId]);-const onIntervalChange = (value: string) => {const end = today("UTC");if (value === "week") {diff --git a/apps/erp/app/routes/x+/sales+/customer-types.$customerTypeId.tsx b/apps/erp/app/routes/x+/sales+/customer-types.$customerTypeId.tsxindex dfc4b2b0cd..9ccda00a5d 100644--- a/apps/erp/app/routes/x+/sales+/customer-types.$customerTypeId.tsx+++ b/apps/erp/app/routes/x+/sales+/customer-types.$customerTypeId.tsx@@ -8,11 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";import {customerTypeValidator,@@ -22,7 +18,6 @@ import {import { CustomerTypeForm } from "~/modules/sales/ui/CustomerTypes";import { getCustomFields, setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";-import { customerTypesQuery, getCompanyId } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -86,14 +81,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- customerTypesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function EditCustomerTypesRoute() {const { customerType } = useLoaderData<typeof loader>();const closeRoute = useCloseRoute();diff --git a/apps/erp/app/routes/x+/sales+/customer-types.delete.$customerTypeId.tsx b/apps/erp/app/routes/x+/sales+/customer-types.delete.$customerTypeId.tsxindex 62a26fac0d..e14b052d72 100644--- a/apps/erp/app/routes/x+/sales+/customer-types.delete.$customerTypeId.tsx+++ b/apps/erp/app/routes/x+/sales+/customer-types.delete.$customerTypeId.tsx@@ -7,16 +7,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";import { deleteCustomerType, getCustomerType } from "~/modules/sales";import { getParams, path } from "~/utils/path";-import { customerTypesQuery, getCompanyId } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -72,14 +67,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- customerTypesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function DeleteCustomerTypeRoute() {const { t } = useLingui();const { customerTypeId } = useParams();diff --git a/apps/erp/app/routes/x+/sales+/customer-types.new.tsx b/apps/erp/app/routes/x+/sales+/customer-types.new.tsxindex 45fc3d398b..babb5db050 100644--- a/apps/erp/app/routes/x+/sales+/customer-types.new.tsx+++ b/apps/erp/app/routes/x+/sales+/customer-types.new.tsx@@ -8,16 +8,11 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { customerTypeValidator, upsertCustomerType } from "~/modules/sales";import { CustomerTypeForm } from "~/modules/sales/ui/CustomerTypes";import { setCustomFields } from "~/utils/form";import { getParams, path } from "~/utils/path";-import { customerTypesQuery, getCompanyId } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {await requirePermissions(request, {@@ -71,14 +66,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- window.clientCache?.setQueryData(- customerTypesQuery(getCompanyId()).queryKey,- null- );- return await serverAction();-}-export default function NewCustomerTypesRoute() {const closeRoute = useCloseRoute();const initialValues = {diff --git a/apps/erp/app/routes/x+/sales+/customers.tsx b/apps/erp/app/routes/x+/sales+/customers.tsxindex 5d312175fc..b3b153cdbe 100644--- a/apps/erp/app/routes/x+/sales+/customers.tsx+++ b/apps/erp/app/routes/x+/sales+/customers.tsx@@ -18,6 +18,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["customer"],breadcrumb: msg`Customers`,to: path.to.customers};diff --git a/apps/erp/app/routes/x+/sales+/invoices.tsx b/apps/erp/app/routes/x+/sales+/invoices.tsxindex 78bef47ded..117d1b4d39 100644--- a/apps/erp/app/routes/x+/sales+/invoices.tsx+++ b/apps/erp/app/routes/x+/sales+/invoices.tsx@@ -4,8 +4,13 @@import { redirect } from "@carbon/utils";import type { LoaderFunctionArgs } from "react-router";+import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";+export const handle: Handle = {+ realtime: ["salesInvoice"]+};+// Sales invoices now live solely in the invoicing module. This legacy Sales-module// URL redirects there, preserving any filter query string (e.g. ?filter=customerId:eq:...).export async function loader({ request }: LoaderFunctionArgs) {diff --git a/apps/erp/app/routes/x+/sales+/orders.tsx b/apps/erp/app/routes/x+/sales+/orders.tsxindex fe795d972f..4c781d3c1b 100644--- a/apps/erp/app/routes/x+/sales+/orders.tsx+++ b/apps/erp/app/routes/x+/sales+/orders.tsx@@ -17,6 +17,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["salesOrder"],breadcrumb: msg`Orders`,to: path.to.salesOrders};diff --git a/apps/erp/app/routes/x+/sales+/quotes.tsx b/apps/erp/app/routes/x+/sales+/quotes.tsxindex 0cf02e261e..59ef366937 100644--- a/apps/erp/app/routes/x+/sales+/quotes.tsx+++ b/apps/erp/app/routes/x+/sales+/quotes.tsx@@ -20,6 +20,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["quote"],breadcrumb: msg`Quotes`,to: path.to.quotes};diff --git a/apps/erp/app/routes/x+/sales+/rfqs.tsx b/apps/erp/app/routes/x+/sales+/rfqs.tsxindex bf67ec5240..d25869521b 100644--- a/apps/erp/app/routes/x+/sales+/rfqs.tsx+++ b/apps/erp/app/routes/x+/sales+/rfqs.tsx@@ -20,6 +20,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["salesRfq"],breadcrumb: msg`RFQs`,to: path.to.salesRfqs};diff --git a/apps/erp/app/routes/x+/sales+/rmas.tsx b/apps/erp/app/routes/x+/sales+/rmas.tsxindex b1c02d8871..180207182f 100644--- a/apps/erp/app/routes/x+/sales+/rmas.tsx+++ b/apps/erp/app/routes/x+/sales+/rmas.tsx@@ -17,6 +17,7 @@ import { path } from "~/utils/path";import { getGenericQueryFilters } from "~/utils/query";export const handle: Handle = {+ realtime: ["salesReturnOrder"],breadcrumb: msg`RMAs`,to: path.to.salesReturnOrders};diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsxindex cc9b1d9c86..2ed22f270b 100644--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.tsx@@ -39,6 +39,18 @@ import { detailBreadcrumb, type Handle } from "~/utils/handle";import { path, requestReferrer } from "~/utils/path";export const handle: Handle = {+ realtime: [+ { table: "salesInvoice", column: "id", param: "invoiceId" },+ { table: "salesInvoiceLine", column: "invoiceId", param: "invoiceId" },+ // What is applied to this invoice, and the payments behind it: voiding a+ // payment changes the payment row only.+ {+ table: "invoiceSettlement",+ column: "targetSalesInvoiceId",+ param: "invoiceId"+ },+ { table: "payment", column: "targetSalesInvoiceId", param: "invoiceId" }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`Sales Invoices`, to: path.to.invoicingSales },(data) => data?.salesInvoice?.invoiceIddiff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.tsxindex 48d796471f..400d54c315 100644--- a/apps/erp/app/routes/x+/sales-order+/$orderId.tsx+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.tsx@@ -37,6 +37,28 @@ import { detailBreadcrumb, type Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {+ realtime: [+ { table: "salesOrder", column: "id", param: "orderId" },+ { table: "salesOrderLine", column: "salesOrderId", param: "orderId" },+ {+ // Shipments and invoices made from this order carry its opportunity+ // (`getSalesOrderRelatedItems`, the convert function).+ table: "shipment",+ filter: ({ data }) =>+ data?.opportunity?.id+ ? `opportunityId=eq.${data.opportunity.id}`+ : undefined+ },+ {+ // Shipments and invoices made from this order carry its opportunity+ // (`getSalesOrderRelatedItems`, the convert function).+ table: "salesInvoice",+ filter: ({ data }) =>+ data?.opportunity?.id+ ? `opportunityId=eq.${data.opportunity.id}`+ : undefined+ }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`Orders`, to: path.to.salesOrders },(data) => data?.salesOrder?.salesOrderId@@ -58,9 +80,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { orderId } = params;if (!orderId) throw new Error("Could not find orderId");- const [salesOrder, lines] = await Promise.all([+ // Three steps at most: what needs only the order id is read with the order,+ // what needs the order's or the invoice lines' values follows together, and+ // the originating quote waits for the opportunity.+ const serviceRole = getCarbonServiceRole();+ const [salesOrder, lines, companySettings, invoiceLines] = await Promise.all([getSalesOrder(client, orderId),- getSalesOrderLines(client, orderId)+ getSalesOrderLines(client, orderId),+ getCompanySettings(serviceRole, companyId),+ getSalesOrderInvoiceLines(client, orderId)]);if (salesOrder.error) {@@ -70,15 +98,29 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- const opportunity = await getOpportunity(- client,- salesOrder.data?.opportunityId ?? null- );-if (companyId !== salesOrder.data?.companyId) {throw redirect(path.to.salesOrders);}+ const invoiceIds = Array.from(+ new Set(+ (invoiceLines.data ?? []).map((line) => line.invoiceId).filter(Boolean)+ )+ ) as string[];++ const [opportunity, customer, invoices, payments] = await Promise.all([+ getOpportunity(client, salesOrder.data?.opportunityId ?? null),+ salesOrder.data?.customerId+ ? getCustomer(client, salesOrder.data.customerId)+ : null,+ invoiceIds.length > 0+ ? getSalesOrderInvoicesByIds(client, invoiceIds)+ : null,+ invoiceIds.length > 0+ ? getSalesOrderInvoicePaymentsByIds(client, companyId, invoiceIds)+ : null+ ]);+if (opportunity.error) {throw new Error(`Failed to get opportunity record for sales order ${orderId} (opportunityId: ${@@ -99,18 +141,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- const serviceRole = getCarbonServiceRole();- const [quote, customer, companySettings, invoiceLines] = await Promise.all([- opportunity.data.quotes[0]?.id- ? getQuote(client, opportunity.data.quotes[0].id)- : Promise.resolve(null),- salesOrder.data?.customerId- ? getCustomer(client, salesOrder.data.customerId)- : Promise.resolve(null),- getCompanySettings(serviceRole, companyId),- getSalesOrderInvoiceLines(client, orderId)- ]);-if (invoiceLines.error) {throw redirect(path.to.salesOrder(orderId),@@ -121,22 +151,15 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- const invoiceIds = Array.from(- new Set(- (invoiceLines.data ?? []).map((line) => line.invoiceId).filter(Boolean)- )- ) as string[];+ const quote = opportunity.data.quotes[0]?.id+ ? await getQuote(client, opportunity.data.quotes[0].id)+ : null;let invoicedAmount = 0;let paidAmount = 0;let currencyMismatchCount = 0;- if (invoiceIds.length > 0) {- const [invoices, payments] = await Promise.all([- getSalesOrderInvoicesByIds(client, invoiceIds),- getSalesOrderInvoicePaymentsByIds(client, companyId, invoiceIds)- ]);-+ if (invoices && payments) {if (invoices.error) {throw redirect(path.to.salesOrder(orderId),diff --git a/apps/erp/app/routes/x+/sales-return-order+/$id.tsx b/apps/erp/app/routes/x+/sales-return-order+/$id.tsxindex 34f6529cae..2f9da72495 100644--- a/apps/erp/app/routes/x+/sales-return-order+/$id.tsx+++ b/apps/erp/app/routes/x+/sales-return-order+/$id.tsx@@ -24,6 +24,10 @@ import { detailBreadcrumb, type Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {+ realtime: [+ { table: "salesReturnOrder", column: "id", param: "id" },+ { table: "salesReturnOrderLine", column: "salesReturnOrderId", param: "id" }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`RMAs`, to: path.to.salesReturnOrders },(data) => data?.salesReturnOrder?.salesReturnOrderIddiff --git a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.tsx b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.tsxindex 9468961bc7..0a2cf3d9a8 100644--- a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.tsx+++ b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.tsx@@ -40,6 +40,10 @@ import { path } from "~/utils/path";const logger = getLogger("erp", "sales-rfq");export const handle: Handle = {+ realtime: [+ { table: "salesRfq", column: "id", param: "rfqId" },+ { table: "salesRfqLine", column: "salesRfqId", param: "rfqId" }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`RFQs`, to: path.to.salesRfqs },(data) => data?.rfqSummary?.rfqIddiff --git a/apps/erp/app/routes/x+/scheduling+/_layout.tsx b/apps/erp/app/routes/x+/scheduling+/_layout.tsxindex fa0d734431..78389765c7 100644--- a/apps/erp/app/routes/x+/scheduling+/_layout.tsx+++ b/apps/erp/app/routes/x+/scheduling+/_layout.tsx@@ -15,6 +15,7 @@ export const meta: MetaFunction = () => {};export const handle: Handle = {+ realtime: ["job", "jobOperation"],breadcrumb: msg`Production`,to: path.to.production,module: "production"diff --git a/apps/erp/app/routes/x+/settings+/accounting.tsx b/apps/erp/app/routes/x+/settings+/accounting.tsxindex f2a42b3832..2f9c9a1853 100644--- a/apps/erp/app/routes/x+/settings+/accounting.tsx+++ b/apps/erp/app/routes/x+/settings+/accounting.tsx@@ -6,6 +6,7 @@ import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { ValidatedForm, validationError, validator } from "@carbon/form";+import { useAction } from "@carbon/query";import {Badge,Card,@@ -24,9 +25,9 @@ import {import { redirect } from "@carbon/utils";import { msg } from "@lingui/core/macro";import { Trans } from "@lingui/react/macro";-import { useCallback, useEffect } from "react";+import { useCallback } from "react";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";-import { useFetcher, useLoaderData } from "react-router";+import { useLoaderData } from "react-router";import { z } from "zod";import { zfd } from "zod-form-data";import {@@ -171,33 +172,33 @@ export async function action({ request }: ActionFunctionArgs) {export default function AccountingSettingsRoute() {const { companySettings, accountDefaults } = useLoaderData<typeof loader>();- const fetcher = useFetcher<typeof action>();- const taxFetcher = useFetcher<typeof action>();- const { isInternal } = useFlags();-- const taxEnabled = companySettings.assetTaxDepreciationEnabled ?? false;-- useEffect(() => {- if (fetcher.data && "success" in fetcher.data) {- if (fetcher.data.success === true && fetcher.data.message) {- toast.success(fetcher.data.message);- }- if (fetcher.data.success === false && fetcher.data.message) {- toast.error(fetcher.data.message);+ const fetcher = useAction<typeof action>({+ onSettled: (data) => {+ if (data && "success" in data) {+ if (data.success === true && data.message) {+ toast.success(data.message);+ }+ if (data.success === false && data.message) {+ toast.error(data.message);+ }}}- }, [fetcher.data]);-- useEffect(() => {- if (taxFetcher.data && "success" in taxFetcher.data) {- if (taxFetcher.data.success === true && taxFetcher.data.message) {- toast.success(taxFetcher.data.message);- }- if (taxFetcher.data.success === false && taxFetcher.data.message) {- toast.error(taxFetcher.data.message);+ });+ const taxFetcher = useAction<typeof action>({+ onSettled: (data) => {+ if (data && "success" in data) {+ if (data.success === true && data.message) {+ toast.success(data.message);+ }+ if (data.success === false && data.message) {+ toast.error(data.message);+ }}}- }, [taxFetcher.data]);+ });+ const { isInternal } = useFlags();++ const taxEnabled = companySettings.assetTaxDepreciationEnabled ?? false;const handleAccountingToggle = useCallback((checked: boolean) => {diff --git a/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx b/apps/erp/app/routes/x+/shipment+/$shipmentId.tsxindex d2aa81832e..69e025771c 100644--- a/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx+++ b/apps/erp/app/routes/x+/shipment+/$shipmentId.tsx@@ -23,6 +23,10 @@ import { detailBreadcrumb, type Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {+ realtime: [+ { table: "shipment", column: "id", param: "shipmentId" },+ { table: "shipmentLine", column: "shipmentId", param: "shipmentId" }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`Shipments`, to: path.to.shipments },(data) => data?.shipment?.shipmentIddiff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsxindex a6c25585f1..3cacb0e195 100644--- a/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx@@ -8,6 +8,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";+import { useAction } from "@carbon/query";import {TrackedEntityPicker,type TrackedEntitySelection,@@ -16,15 +17,9 @@ import {import { serverFns } from "@carbon/server-functions";import { getErrorMessage, redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import { useEffect, useMemo } from "react";+import { useMemo } from "react";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";-import {- data,- useFetcher,- useLoaderData,- useNavigate,- useParams-} from "react-router";+import { data, useLoaderData, useNavigate, useParams } from "react-router";import { useRouteData } from "~/hooks";import type { StockTransfer, StockTransferLine } from "~/modules/inventory";import {@@ -284,13 +279,13 @@ export default function StockTransferScan() {const onClose = () =>navigate(path.to.stockTransfer(stockTransferLine.stockTransferId!));- const fetcher = useFetcher<Result>();-- useEffect(() => {- if (fetcher.data?.success === false) {- toast.error(fetcher.data.message);+ const fetcher = useAction<Result>({+ onError: (data) => {+ if (data?.success === false) {+ toast.error(data.message);+ }}- }, [fetcher.data?.message, fetcher.data?.success]);+ });const locationId = routeData?.stockTransfer.locationId ?? "";diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.tsxindex 93a1c7f69c..6b2fcc16f2 100644--- a/apps/erp/app/routes/x+/stock-transfer+/$id.tsx+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.tsx@@ -23,6 +23,10 @@ import { detailBreadcrumb, type Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {+ realtime: [+ { table: "stockTransfer", column: "id", param: "id" },+ { table: "stockTransferLine", column: "stockTransferId", param: "id" }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`Stock Transfers`, to: path.to.stockTransfers },(data) => data?.stockTransfer?.stockTransferIddiff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.$supplierContactId.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.$supplierContactId.tsxindex 3d129559d8..dfd8ec7ea7 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.$supplierContactId.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.$supplierContactId.tsx@@ -13,11 +13,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import {getSupplierContact,@@ -27,7 +23,6 @@ import {import SupplierContactForm from "~/modules/purchasing/ui/Supplier/SupplierContactForm";import { getCustomFields, setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { supplierContactsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -104,20 +99,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({- serverAction,- params-}: ClientActionFunctionArgs) {- const { supplierId } = params;- if (supplierId) {- window.clientCache?.setQueryData(- supplierContactsQuery(supplierId).queryKey,- null- );- }- return await serverAction();-}-export default function EditSupplierContactRoute() {const { contact } = useLoaderData<typeof loader>();const navigate = useNavigate();diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.delete.$supplierContactId.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.delete.$supplierContactId.tsxindex 812a267670..e246cbd671 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.delete.$supplierContactId.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.delete.$supplierContactId.tsx@@ -6,13 +6,9 @@ import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { deleteSupplierContact } from "~/modules/purchasing";import { path } from "~/utils/path";-import { supplierContactsQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {const { client } = await requirePermissions(request, {@@ -49,17 +45,3 @@ export async function action({ request, params }: ActionFunctionArgs) {await flash(request, success("Successfully deleted supplier contact")));}--export async function clientAction({- serverAction,- params-}: ClientActionFunctionArgs) {- const { supplierId } = params;- if (supplierId) {- window.clientCache?.setQueryData(- supplierContactsQuery(supplierId).queryKey,- null- );- }- return await serverAction();-}diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.new.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.new.tsxindex e0b98c3044..c2ec023ed2 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.new.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.contacts.new.tsx@@ -8,10 +8,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { data, useNavigate, useParams } from "react-router";import {insertSupplierContact,@@ -21,7 +18,6 @@ import SupplierContactForm from "~/modules/purchasing/ui/Supplier/SupplierContacimport { requireCompanyRecord } from "~/modules/shared/shared.server";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { supplierContactsQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -125,20 +121,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({- serverAction,- params-}: ClientActionFunctionArgs) {- const { supplierId } = params;- if (supplierId) {- window.clientCache?.setQueryData(- supplierContactsQuery(supplierId).queryKey,- null- );- }- return await serverAction();-}-export default function SupplierContactsNewRoute() {const navigate = useNavigate();const { supplierId } = useParams();diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.locations.$supplierLocationId.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.locations.$supplierLocationId.tsxindex 03764b438e..42425bed88 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.locations.$supplierLocationId.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.locations.$supplierLocationId.tsx@@ -13,11 +13,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import {getSupplierLocation,@@ -27,7 +23,6 @@ import {import SupplierLocationForm from "~/modules/purchasing/ui/Supplier/SupplierLocationForm";import { getCustomFields, setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { supplierLocationsQuery } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -101,20 +96,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({- serverAction,- params-}: ClientActionFunctionArgs) {- const { supplierId } = params;- if (supplierId) {- window.clientCache?.setQueryData(- supplierLocationsQuery(supplierId).queryKey,- null- );- }- return await serverAction();-}-export default function EditSupplierLocationRoute() {const { location } = useLoaderData<typeof loader>();const navigate = useNavigate();diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.locations.delete.$supplierLocationId.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.locations.delete.$supplierLocationId.tsxindex ea1d0b1131..8dc5a77ac7 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.locations.delete.$supplierLocationId.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.locations.delete.$supplierLocationId.tsx@@ -6,13 +6,9 @@ import { error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { deleteSupplierLocation } from "~/modules/purchasing";import { path } from "~/utils/path";-import { supplierLocationsQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {const { client } = await requirePermissions(request, {@@ -51,17 +47,3 @@ export async function action({ request, params }: ActionFunctionArgs) {await flash(request, success("Successfully deleted supplier location")));}--export async function clientAction({- serverAction,- params-}: ClientActionFunctionArgs) {- const { supplierId } = params;- if (supplierId) {- window.clientCache?.setQueryData(- supplierLocationsQuery(supplierId).queryKey,- null- );- }- return await serverAction();-}diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.locations.new.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.locations.new.tsxindex 2806cf6a38..d533bd8c5a 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.locations.new.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.locations.new.tsx@@ -7,10 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { data, useNavigate, useParams } from "react-router";import { useUser } from "~/hooks";import {@@ -20,7 +17,6 @@ import {import SupplierLocationForm from "~/modules/purchasing/ui/Supplier/SupplierLocationForm";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { supplierLocationsQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -94,17 +90,3 @@ export default function SupplierLocationsNewRoute() {/>);}--export async function clientAction({- serverAction,- params-}: ClientActionFunctionArgs) {- const { supplierId } = params;- if (supplierId) {- window.clientCache?.setQueryData(- supplierLocationsQuery(supplierId).queryKey,- null- );- }- return await serverAction();-}diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.processes.$id.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.processes.$id.tsxindex 2e29e8e5dd..95466b38ee 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.processes.$id.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.processes.$id.tsx@@ -8,10 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { useParams } from "react-router";import { useRouteData } from "~/hooks";import type { SupplierProcess } from "~/modules/purchasing";@@ -22,7 +19,6 @@ import {import SupplierProcessForm from "~/modules/purchasing/ui/Supplier/SupplierProcessForm";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { supplierProcessesQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -66,29 +62,6 @@ export async function action({ request, params }: ActionFunctionArgs) {return redirect(path.to.supplierProcesses(supplierId));}-export async function clientAction({- request,- serverAction,- params-}: ClientActionFunctionArgs) {- const formData = await request.clone().formData(); // if we. don't clone it we can't access it in the action- const validation = await validator(supplierProcessValidator).validate(- formData- );-- if (validation.error) {- return validationError(validation.error);- }-- if (validation.data.processId) {- window.clientCache?.setQueryData(- supplierProcessesQuery(validation.data.processId).queryKey,- null- );- }- return await serverAction();-}-export default function SupplierProcessRoute() {const { supplierId, id } = useParams();if (!supplierId) throw new Error("Could not find supplier id");diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.processes.delete.$id.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.processes.delete.$id.tsxindex ff0327eea8..1f7cff4c95 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.processes.delete.$id.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.processes.delete.$id.tsx@@ -8,17 +8,13 @@ import { flash } from "@carbon/auth/session.server";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";import { useRouteData } from "~/hooks";import type { SupplierProcess } from "~/modules/purchasing";import { deleteSupplierProcess } from "~/modules/purchasing";import { path } from "~/utils/path";-import { supplierProcessesQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -45,20 +41,6 @@ export async function action({ request, params }: ActionFunctionArgs) {return redirect(path.to.supplierProcesses(supplierId));}-export async function clientAction({- request,- serverAction-}: ClientActionFunctionArgs) {- const processId = new URL(request.url).searchParams.get("processId");- if (processId) {- window.clientCache?.setQueryData(- supplierProcessesQuery(processId).queryKey,- null- );- }- return await serverAction();-}-export default function DeleteSupplierProcessRoute() {const closeRoute = useCloseRoute();const { supplierId, id } = useParams();diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.processes.new.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.processes.new.tsxindex 02db957baf..5e1658e4bb 100644--- a/apps/erp/app/routes/x+/supplier+/$supplierId.processes.new.tsx+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.processes.new.tsx@@ -8,10 +8,7 @@ import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { useCloseRoute } from "@carbon/react";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { useParams } from "react-router";import {supplierProcessValidator,@@ -20,7 +17,6 @@ import {import SupplierProcessForm from "~/modules/purchasing/ui/Supplier/SupplierProcessForm";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-import { supplierProcessesQuery } from "~/utils/react-query";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);@@ -67,29 +63,6 @@ export async function action({ request, params }: ActionFunctionArgs) {: redirect(path.to.supplierProcesses(supplierId));}-export async function clientAction({- request,- serverAction,- params-}: ClientActionFunctionArgs) {- const formData = await request.clone().formData(); // if we. don't clone it we can't access it in the action- const validation = await validator(supplierProcessValidator).validate(- formData- );-- if (validation.error) {- return validationError(validation.error);- }-- if (validation.data.processId) {- window.clientCache?.setQueryData(- supplierProcessesQuery(validation.data.processId).queryKey,- null- );- }- return await serverAction();-}-export default function NewSupplierProcessRoute() {const { supplierId } = useParams();const closeRoute = useCloseRoute();diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsxindex 78d11a0f4a..e4e5e3e8c1 100644--- a/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx@@ -5,22 +5,15 @@import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { getLogger } from "@carbon/logger";import { redirect } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";-import {- finalizeSupplierQuote,- getSupplierQuote,- getSupplierQuoteLinePricesByQuoteId,- getSupplierQuoteLines-} from "~/modules/purchasing";+import { finalizeSupplierQuote, getSupplierQuote } from "~/modules/purchasing";import { checkPartyContactRequirement } from "~/modules/settings/party-contact.server";import { upsertExternalLink } from "~/modules/shared";import { requireCompanyRecord } from "~/modules/shared/shared.server";+import { getDatabaseClient } from "~/services/database.server";import { path } from "~/utils/path";-const logger = getLogger("erp", "id-finalize");-export async function action(args: ActionFunctionArgs) {const { request, params } = args;assertIsPost(request);@@ -75,188 +68,27 @@ export async function action(args: ActionFunctionArgs) {if (externalLink.data && quote.data.externalLinkId !== externalLink.data.id) {await client.from("supplierQuote")- .update({- externalLinkId: externalLink.data.id,- status: "Active"- })+ .update({ externalLinkId: externalLink.data.id }).eq("id", id);}- // Validate that all quantities have price and lead time- const [quoteLines, quoteLinePrices] = await Promise.all([- getSupplierQuoteLines(client, id),- getSupplierQuoteLinePricesByQuoteId(client, id)- ]);-- if (quoteLines.error) {- throw redirect(- path.to.supplierQuote(id),- await flash(- request,- error(quoteLines.error, "Failed to get supplier quote lines")- )- );- }-- if (quoteLinePrices.error) {+ // The function checks that every line is priced, marks the quote Active and+ // writes the supplier's price list, in one transaction.+ const finalize = await finalizeSupplierQuote(client, getDatabaseClient(), {+ supplierQuoteId: id,+ companyId,+ userId+ });+ if (finalize.error) {throw redirect(path.to.supplierQuote(id),await flash(request,- error(quoteLinePrices.error, "Failed to get supplier quote line prices")- )- );- }-- // Check that each line has at least one quantity with price and lead time- // (not all quantities need them, just at least one per line)- const lines = quoteLines.data ?? [];- const prices = quoteLinePrices.data ?? [];-- for (const line of lines) {- if (!line.id) continue;- const linePrices = prices.filter((p) => p.supplierQuoteLineId === line.id);-- // Check if at least one quantity has both valid price and lead time- const hasValidPriceAndLeadTime = linePrices.some(- (price) =>- price.supplierUnitPrice !== null &&- price.supplierUnitPrice !== 0 &&- price.leadTime !== null &&- price.leadTime !== 0- );-- if (!hasValidPriceAndLeadTime) {- throw redirect(- path.to.supplierQuote(id),- await flash(- request,- error(- null,- `Line ${line.itemReadableId} must have at least one quantity with price and lead time`- )- )- );- }- }-- // TODO: Add PDF generation for supplier quotes when available- // TODO: Add document creation for supplier quotes when PDF is available-- try {- const finalize = await finalizeSupplierQuote(client, id, userId);- if (finalize.error) {- throw redirect(- path.to.supplierQuote(id),- await flash(- request,- error(finalize.error, "Failed to finalize supplier quote")+ error(+ finalize.error,+ finalize.error.message || "Failed to finalize supplier quote")- );- }-- const supplierId = quote.data.supplierId;- if (!supplierId) throw new Error("Supplier quote has no supplier");-- for (const line of lines) {- if (!line.id || !line.itemId) continue;-- const linePrices = prices.filter(- (p) => p.supplierQuoteLineId === line.id- );- if (linePrices.length === 0) continue;-- const existingPart = await client- .from("supplierPart")- .select("id")- .eq("itemId", line.itemId)- .eq("supplierId", supplierId)- .eq("companyId", companyId)- .single();-- let supplierPartId: string | undefined;-- if (existingPart.data?.id) {- supplierPartId = existingPart.data.id;- } else {- const newPart = await client- .from("supplierPart")- .insert({- itemId: line.itemId,- supplierId,- supplierPartId: line.supplierPartId ?? undefined,- supplierUnitOfMeasureCode:- line.purchaseUnitOfMeasureCode ?? undefined,- conversionFactor: line.conversionFactor ?? 1,- companyId,- createdBy: userId- })- .select("id")- .single();-- if (newPart.error || !newPart.data?.id) {- logger.error("Error creating supplier part", {- error: newPart.error- });- continue;- }- supplierPartId = newPart.data.id;- }-- if (!supplierPartId) continue;-- const conversionFactor = line.conversionFactor ?? 1;-- for (const price of linePrices) {- if (!price.supplierUnitPrice || price.supplierUnitPrice === 0) continue;-- const unitPriceInInventoryUnit =- (price.unitPrice ?? 0) / conversionFactor;-- const upsertResult = await client.from("supplierPartPrice").upsert(- {- supplierPartId,- quantity: price.quantity ?? 1,- unitPrice: unitPriceInInventoryUnit,- leadTime: price.leadTime ?? 0,- sourceType: "Quote",- sourceDocumentId: id,- companyId,- createdBy: userId,- updatedBy: userId,- updatedAt: new Date().toISOString()- },- { onConflict: "supplierPartId,quantity" }- );-- if (upsertResult.error) {- logger.error(- "Error upserting supplier part price:",- upsertResult.error- );- }- }-- const bestPrice = linePrices- .filter((p) => p.unitPrice != null && p.unitPrice !== 0)- .sort(- (a, b) => (a.unitPrice ?? Infinity) - (b.unitPrice ?? Infinity)- )[0];-- if (bestPrice) {- await client- .from("supplierPart")- .update({- unitPrice: (bestPrice.unitPrice ?? 0) / conversionFactor,- minimumOrderQuantity: bestPrice.quantity ?? 1- })- .eq("id", supplierPartId);- }- }- } catch (err) {- throw redirect(- path.to.supplierQuote(id),- await flash(request, error(err, "Failed to finalize supplier quote"))+ ));}diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsxindex fa38079ef9..a85a33fb04 100644--- a/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx@@ -14,7 +14,7 @@ import type { ActionFunctionArgs } from "react-router";import {getSupplierContact,getSupplierInteractionDocuments,- getSupplierInteractionLineDocuments,+ getSupplierInteractionLineAttachments,getSupplierQuote,getSupplierQuoteLines,sendSupplierQuote,@@ -157,32 +157,13 @@ export async function action(args: ActionFunctionArgs) {const lines = await getSupplierQuoteLines(client, id);if (lines.data) {- for (const line of lines.data) {- const docs = await getSupplierInteractionLineDocuments(+ attachments.push(+ ...(await getSupplierInteractionLineAttachments(client,companyId,- line.id ?? ""- );-- for (const doc of docs) {- const storagePath = `${companyId}/supplier-interaction-line/${line.id}/${doc.name}`;- const { data, error } = await storage(client)- .company(companyId)- .createSignedUrl(storagePath, 3600);-- if (data) {- attachments.push({- filename: doc.name,- path: data.signedUrl- });- } else {- logger.error("Failed to create signed URL for attachment", {- storagePath,- error- });- }- }- }+ lines.data.flatMap((line) => (line.id ? [line.id] : []))+ ))+ );}const requestUrl = new URL(request.url);diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.tsxindex 180ca59622..22d11c0aca 100644--- a/apps/erp/app/routes/x+/supplier-quote+/$id.tsx+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.tsx@@ -35,6 +35,10 @@ import { detailBreadcrumb, type Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {+ realtime: [+ { table: "supplierQuote", column: "id", param: "id" },+ { table: "supplierQuoteLine", column: "supplierQuoteId", param: "id" }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`Supplier Quotes`, to: path.to.supplierQuotes },(data) => data?.quote?.supplierQuoteId@@ -76,20 +80,32 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- const [lines, prices, siblingQuotes] = await Promise.all([+ const [+ lines,+ prices,+ siblingQuotes,+ supplierInteraction,+ presentationCurrency,+ supplier,+ companySettings,+ rate+ ] = await Promise.all([getSupplierQuoteLines(serviceRole, id),getSupplierQuoteLinePricesByQuoteId(serviceRole, id),- getSiblingQuotesForQuote(serviceRole, id)+ getSiblingQuotesForQuote(serviceRole, id),+ getSupplierInteraction(serviceRole, quote.data.supplierInteractionId!),+ getCurrencyByCode(serviceRole, companyGroupId, quote.data.currencyCode!),+ getSupplier(serviceRole, quote.data.supplierId!),+ getCompanySettings(serviceRole, companyId),+ quote.data.currencyCode+ ? getExchangeRate(+ serviceRole,+ quote.data.companyId,+ quote.data.currencyCode+ )+ : null]);- const [supplierInteraction, presentationCurrency, supplier, companySettings] =- await Promise.all([- getSupplierInteraction(serviceRole, quote.data.supplierInteractionId!),- getCurrencyByCode(serviceRole, companyGroupId, quote.data.currencyCode!),- getSupplier(serviceRole, quote.data.supplierId!),- getCompanySettings(serviceRole, companyId)- ]);-if (supplierInteraction.error) {throw redirect(path.to.supplierQuotes,@@ -103,21 +119,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- let exchangeRate = 1;- if (quote.data?.currencyCode) {- const rate = await getExchangeRate(- serviceRole,- quote.data.companyId,- quote.data.currencyCode- );- // A missing LIVE rate must not make the quote unopenable — this page hosts- // the refresh button that fixes it. Fall back to the document's own stamped- // snapshot (the PDF routes' policy); writes still refuse.- exchangeRate =- rate.error || rate.data === null- ? (quote.data.exchangeRate ?? 1)- : rate.data;- }+ // A missing LIVE rate must not make the quote unopenable — this page hosts+ // the refresh button that fixes it. Fall back to the document's own stamped+ // snapshot (the PDF routes' policy); writes still refuse.+ const exchangeRate = !rate+ ? 1+ : rate.error || rate.data === null+ ? (quote.data.exchangeRate ?? 1)+ : rate.data;// Extract sibling quotes from the linked dataconst siblingQuotesData =diff --git a/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx b/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsxindex 72b17af119..f1ac41c131 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.inventory.tsx@@ -51,8 +51,21 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const searchParams = new URLSearchParams(url.search);let locationId = searchParams.get("location");- if (!locationId) {- const userDefaults = await getUserDefaults(client, userId, companyId);+ // Three waits at most: what needs no location is read while the+ // default location is, and everything that needs it is read together.+ const [userDefaults, shelfLife, bomHasShelfLifeManagedInput, rulesData] =+ await Promise.all([+ locationId ? null : getUserDefaults(client, userId, companyId),+ getItemShelfLife(client, itemId),+ getBomHasShelfLifeManagedInput(client, itemId, companyId),+ getStorageRulesDataForTarget(client, {+ targetType: "item",+ targetId: itemId,+ companyId+ })+ ]);++ if (userDefaults) {if (userDefaults.error) {throw redirect(path.to.tool(itemId),@@ -80,9 +93,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {locationId = locations.data?.[0].id as string;}- let [toolInventory] = await Promise.all([- getPickMethod(client, itemId, companyId, locationId)- ]);+ let [toolInventory, quantities, itemStorageUnitQuantities] =+ await Promise.all([+ getPickMethod(client, itemId, companyId, locationId),+ getItemQuantities(client, itemId, companyId, locationId),+ getItemStorageUnitQuantities(client, itemId, companyId, locationId)+ ]);if (toolInventory.error || !toolInventory.data) {const insertPickMethod = await upsertPickMethod(client, {@@ -115,12 +131,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}}- const quantities = await getItemQuantities(- client,- itemId,- companyId,- locationId- );if (quantities.error) {throw redirect(path.to.items,@@ -128,12 +138,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- const itemStorageUnitQuantities = await getItemStorageUnitQuantities(- client,- itemId,- companyId,- locationId- );if (itemStorageUnitQuantities.error || !itemStorageUnitQuantities.data) {throw redirect(path.to.items,@@ -149,21 +153,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {(row) => row.trackedEntityId);- const [- shelfLife,- bomHasShelfLifeManagedInput,- trackedEntityExpirations,- rulesData- ] = await Promise.all([- getItemShelfLife(client, itemId),- getBomHasShelfLifeManagedInput(client, itemId, companyId),- getTrackedEntityExpirations(client, trackedEntityIds),- getStorageRulesDataForTarget(client, {- targetType: "item",- targetId: itemId,- companyId- })- ]);+ const trackedEntityExpirations = await getTrackedEntityExpirations(+ client,+ trackedEntityIds+ );return {toolInventory: toolInventory.data,diff --git a/apps/erp/app/routes/x+/users+/customers.new.tsx b/apps/erp/app/routes/x+/users+/customers.new.tsxindex 67f57b2933..f5b1779e15 100644--- a/apps/erp/app/routes/x+/users+/customers.new.tsx+++ b/apps/erp/app/routes/x+/users+/customers.new.tsx@@ -19,17 +19,13 @@ import { getLogger } from "@carbon/logger";import { getClientIp, redirect } from "@carbon/utils";import { render } from "@react-email/components";import { nanoid } from "nanoid";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import {CreateCustomerModal,createCustomerAccountValidator} from "~/modules/users";import { createCustomerAccount } from "~/modules/users/users.server";import { path } from "~/utils/path";-import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";const logger = getLogger("erp", "customers-new");@@ -123,11 +119,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- invalidateUserSelectQueries(getCompanyId());- return await serverAction();-}-export default function () {return <CreateCustomerModal />;}diff --git a/apps/erp/app/routes/x+/users+/deactivate.tsx b/apps/erp/app/routes/x+/users+/deactivate.tsxindex ea091fc9e2..34c6f5998e 100644--- a/apps/erp/app/routes/x+/users+/deactivate.tsx+++ b/apps/erp/app/routes/x+/users+/deactivate.tsx@@ -9,12 +9,8 @@ import { deactivateUser } from "@carbon/auth/users.server";import { validationError, validator } from "@carbon/form";import { batchTrigger } from "@carbon/jobs";import { getClientIp, redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { deactivateUsersValidator } from "~/modules/users";-import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";export async function action({ request }: ActionFunctionArgs) {const { client, companyId, userId } = await requirePermissions(request, {@@ -80,8 +76,3 @@ export async function action({ request }: ActionFunctionArgs) {}}}--export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- invalidateUserSelectQueries(getCompanyId());- return await serverAction();-}diff --git a/apps/erp/app/routes/x+/users+/employee-types.$employeeTypeId.tsx b/apps/erp/app/routes/x+/users+/employee-types.$employeeTypeId.tsxindex 24c564b40b..893ca2b3b9 100644--- a/apps/erp/app/routes/x+/users+/employee-types.$employeeTypeId.tsx+++ b/apps/erp/app/routes/x+/users+/employee-types.$employeeTypeId.tsx@@ -13,11 +13,7 @@ import {import { requireFeature } from "@carbon/ee/plan.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";import {EmployeeTypeForm,@@ -27,7 +23,6 @@ import {getPermissionsByEmployeeType} from "~/modules/users";import { path } from "~/utils/path";-import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -139,11 +134,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- invalidateUserSelectQueries(getCompanyId());- return await serverAction();-}-export default function EditEmployeeTypesRoute() {const { employeeType, employeeTypePermissions } =useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/users+/employee-types.delete.$employeeTypeId.tsx b/apps/erp/app/routes/x+/users+/employee-types.delete.$employeeTypeId.tsxindex 10375d767c..16be31ff02 100644--- a/apps/erp/app/routes/x+/users+/employee-types.delete.$employeeTypeId.tsx+++ b/apps/erp/app/routes/x+/users+/employee-types.delete.$employeeTypeId.tsx@@ -9,16 +9,11 @@ import { deleteEmployeeType } from "@carbon/ee/permissions.server";import { requireFeature } from "@carbon/ee/plan.server";import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";import { getEmployeeType } from "~/modules/users";import { path } from "~/utils/path";-import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -97,11 +92,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- invalidateUserSelectQueries(getCompanyId());- return await serverAction();-}-export default function DeleteEmployeeTypeRoute() {const { employeeTypeId } = useParams();const { employeeType } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/users+/employee-types.new.tsx b/apps/erp/app/routes/x+/users+/employee-types.new.tsxindex 5b823bd73c..ed62351366 100644--- a/apps/erp/app/routes/x+/users+/employee-types.new.tsx+++ b/apps/erp/app/routes/x+/users+/employee-types.new.tsx@@ -13,11 +13,7 @@ import {import { requireFeature } from "@carbon/ee/plan.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";import type { CompanyPermission } from "~/modules/users";import {@@ -27,7 +23,6 @@ import {getModules} from "~/modules/users";import { path } from "~/utils/path";-import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId } = await requirePermissions(request, {@@ -145,11 +140,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- invalidateUserSelectQueries(getCompanyId());- return await serverAction();-}-export default function NewEmployeeTypesRoute() {const { permissions } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/users+/employees.$employeeId.tsx b/apps/erp/app/routes/x+/users+/employees.$employeeId.tsxindex 6a77e017d1..c0ca4a87a0 100644--- a/apps/erp/app/routes/x+/users+/employees.$employeeId.tsx+++ b/apps/erp/app/routes/x+/users+/employees.$employeeId.tsx@@ -27,11 +27,7 @@ import {import { getClientIp, redirect } from "@carbon/utils";import { Trans } from "@lingui/react/macro";import { LuShield } from "react-icons/lu";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { data, useLoaderData } from "react-router";import { UpgradeOverlayUpgradeButton } from "~/components/UpgradeOverlay";import { usePlanGate } from "~/hooks/usePlanGate";@@ -46,7 +42,6 @@ import {} from "~/modules/users";import { getClaims } from "~/modules/users/users.server";import { path } from "~/utils/path";-import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";// The per-user permissions editor is a modal over the accounts list; when the// company isn't entitled we show the upgrade prompt IN that modal (not a@@ -210,11 +205,6 @@ export async function action({ request }: ActionFunctionArgs) {throw redirect(path.to.employeeAccounts, await flash(request, result));}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- invalidateUserSelectQueries(getCompanyId());- return await serverAction();-}-export default function UsersEmployeeRoute() {const { permissions, employee, employeeTypes, employeeTypePermissions } =useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/users+/employees.new.tsx b/apps/erp/app/routes/x+/users+/employees.new.tsxindex e5c28d9ed3..e0e5efc488 100644--- a/apps/erp/app/routes/x+/users+/employees.new.tsx+++ b/apps/erp/app/routes/x+/users+/employees.new.tsx@@ -20,11 +20,7 @@ import { getLogger } from "@carbon/logger";import { datetime, getClientIp, redirect } from "@carbon/utils";import { render } from "@react-email/components";import { nanoid } from "nanoid";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import {CreateEmployeeModal,@@ -36,7 +32,6 @@ import {getSsoInviteDomainError} from "~/modules/users/users.server";import { path } from "~/utils/path";-import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";const logger = getLogger("erp", "employees-new");@@ -196,11 +191,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- invalidateUserSelectQueries(getCompanyId());- return await serverAction();-}-export default function () {const { invitable } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/users+/groups.$groupId.tsx b/apps/erp/app/routes/x+/users+/groups.$groupId.tsxindex 1cd45986cd..14a45a06e2 100644--- a/apps/erp/app/routes/x+/users+/groups.$groupId.tsx+++ b/apps/erp/app/routes/x+/users+/groups.$groupId.tsx@@ -7,11 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import {GroupForm,@@ -21,7 +17,6 @@ import {upsertGroupMembers} from "~/modules/users";import { path } from "~/utils/path";-import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -107,11 +102,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- invalidateUserSelectQueries(getCompanyId());- return await serverAction();-}-export default function UsersGroupRoute() {const { group } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/users+/groups.delete.$groupId.tsx b/apps/erp/app/routes/x+/users+/groups.delete.$groupId.tsxindex 90c2a382af..92b573e79d 100644--- a/apps/erp/app/routes/x+/users+/groups.delete.$groupId.tsx+++ b/apps/erp/app/routes/x+/users+/groups.delete.$groupId.tsx@@ -7,16 +7,11 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs,- LoaderFunctionArgs-} from "react-router";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";import { deleteGroup, getGroup } from "~/modules/users";import { path } from "~/utils/path";-import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";export async function loader({ request, params }: LoaderFunctionArgs) {const { client } = await requirePermissions(request, {@@ -65,11 +60,6 @@ export async function action({ request, params }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- invalidateUserSelectQueries(getCompanyId());- return await serverAction();-}-export default function DeleteEmployeeTypeRoute() {const { groupId } = useParams();const { group } = useLoaderData<typeof loader>();diff --git a/apps/erp/app/routes/x+/users+/groups.new.tsx b/apps/erp/app/routes/x+/users+/groups.new.tsxindex 26435f4014..0a92275b49 100644--- a/apps/erp/app/routes/x+/users+/groups.new.tsx+++ b/apps/erp/app/routes/x+/users+/groups.new.tsx@@ -7,10 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { validationError, validator } from "@carbon/form";import { redirect } from "@carbon/utils";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import {deleteGroup,@@ -20,7 +17,6 @@ import {upsertGroupMembers} from "~/modules/users";import { path } from "~/utils/path";-import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";export async function action({ request }: ActionFunctionArgs) {assertIsPost(request);@@ -77,11 +73,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- invalidateUserSelectQueries(getCompanyId());- return await serverAction();-}-export default function NewGroupRoute() {const initialValues = {id: "",diff --git a/apps/erp/app/routes/x+/users+/operators.$operatorId.tsx b/apps/erp/app/routes/x+/users+/operators.$operatorId.tsxindex 1391c20462..43515de3c9 100644--- a/apps/erp/app/routes/x+/users+/operators.$operatorId.tsx+++ b/apps/erp/app/routes/x+/users+/operators.$operatorId.tsx@@ -6,6 +6,7 @@ import { assertIsPost, error, success } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { ValidatedForm, validationError, validator } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import {HStack,Modal,@@ -16,7 +17,6 @@ import {ModalOverlay,ModalTitle,useCloseRoute,- useMount,VStack} from "@carbon/react";import { redirect } from "@carbon/utils";@@ -100,12 +100,9 @@ export default function ConvertOperatorRoute() {const { operator } = useLoaderData<typeof loader>();const closeRoute = useCloseRoute();const formFetcher = useFetcher<Result>();- const employeeTypeFetcher =- useFetcher<Awaited<ReturnType<typeof getEmployeeTypes>>>();-- useMount(() => {- employeeTypeFetcher.load(path.to.api.employeeTypes);- });+ const employeeTypeFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getEmployeeTypes>>+ >(path.to.api.employeeTypes);const employeeTypeOptions =employeeTypeFetcher.data?.datadiff --git a/apps/erp/app/routes/x+/users+/suppliers.new.tsx b/apps/erp/app/routes/x+/users+/suppliers.new.tsxindex dba90c2e9f..7377ef110b 100644--- a/apps/erp/app/routes/x+/users+/suppliers.new.tsx+++ b/apps/erp/app/routes/x+/users+/suppliers.new.tsx@@ -19,17 +19,13 @@ import { getLogger } from "@carbon/logger";import { getClientIp, redirect } from "@carbon/utils";import { render } from "@react-email/components";import { nanoid } from "nanoid";-import type {- ActionFunctionArgs,- ClientActionFunctionArgs-} from "react-router";+import type { ActionFunctionArgs } from "react-router";import {CreateSupplierModal,createSupplierAccountValidator} from "~/modules/users";import { createSupplierAccount } from "~/modules/users/users.server";import { path } from "~/utils/path";-import { getCompanyId, invalidateUserSelectQueries } from "~/utils/react-query";const logger = getLogger("erp", "suppliers-new");@@ -123,11 +119,6 @@ export async function action({ request }: ActionFunctionArgs) {);}-export async function clientAction({ serverAction }: ClientActionFunctionArgs) {- invalidateUserSelectQueries(getCompanyId());- return await serverAction();-}-export default function () {return <CreateSupplierModal />;}diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.tsxindex 32c4a2dd28..9c2953a230 100644--- a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.tsx+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.tsx@@ -20,6 +20,14 @@ import { detailBreadcrumb, type Handle } from "~/utils/handle";import { path } from "~/utils/path";export const handle: Handle = {+ realtime: [+ { table: "warehouseTransfer", column: "id", param: "transferId" },+ {+ table: "warehouseTransferLine",+ column: "transferId",+ param: "transferId"+ }+ ],breadcrumb: detailBreadcrumb({ breadcrumb: msg`Warehouse Transfer`, to: path.to.warehouseTransfers },(data) => data?.warehouseTransfer?.transferIddiff --git a/apps/erp/app/stores/customers.ts b/apps/erp/app/stores/customers.tsindex 5bdeb88b5a..ede8ecd0f6 100644--- a/apps/erp/app/stores/customers.ts+++ b/apps/erp/app/stores/customers.ts@@ -2,14 +2,42 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { atom } from "nanostores";-import { useNanoStore } from "~/hooks";+import { fetchAllFromTable } from "@carbon/database";+import { type LiveList, useLiveList } from "@carbon/query";+import { useUser } from "~/hooks";import type { ListItem } from "~/types";-const $customersStore = atom<- (Omit<ListItem, "readableId"> & {- website?: string | null;- readableId?: string | null;- })[]->([]);-export const useCustomers = () => useNanoStore($customersStore, "customers");+export type Customer = Omit<ListItem, "readableId"> & {+ website?: string | null;+ readableId?: string | null;+};++const COLUMNS = "id, name, website, readableId";++export const customersList: LiveList<Customer> = {+ name: "customers",+ table: "customer",+ async fetchAll(carbon, companyId) {+ const rows = await fetchAllFromTable<Customer>(+ carbon,+ "customer",+ COLUMNS,+ (query) => query.eq("companyId", companyId).order("name")+ );+ if (rows.error) throw new Error("Failed to fetch customers");+ return rows.data ?? [];+ },+ async fetchByIds(carbon, companyId, ids) {+ const rows = await carbon+ .from("customer")+ .select(COLUMNS)+ .eq("companyId", companyId)+ .in("id", ids);+ if (rows.error) throw new Error("Failed to fetch customers");+ return (rows.data ?? []) as Customer[];+ },+ sort: (a, b) => a.name.localeCompare(b.name)+};++export const useCustomers = () =>+ useLiveList(customersList, useUser().company.id);diff --git a/apps/erp/app/stores/items.ts b/apps/erp/app/stores/items.tsindex 111f39fd93..9b984ebd00 100644--- a/apps/erp/app/stores/items.ts+++ b/apps/erp/app/stores/items.ts@@ -3,9 +3,11 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import type { Database } from "@carbon/database";-import { useStore as useValue } from "@nanostores/react";-import { atom, computed } from "nanostores";-import { useNanoStore } from "~/hooks";+import { fetchAllFromTable } from "@carbon/database";+import { type LiveList, useLiveList } from "@carbon/query";+import type { SupabaseClient } from "@supabase/supabase-js";+import { useMemo } from "react";+import { useUser } from "~/hooks";import type { ListItem } from "~/types";export type Item = ListItem & {@@ -48,26 +50,92 @@ export function latestRevisionByReadableId<return Array.from(byKey.values());}-const $itemsStore = atom<Item[]>([]);+// The one place the item list's columns are written: the full fetch and the+// re-read of changed rows both select exactly this.+const ITEM_COLUMNS =+ "id, readableId, revision, readableIdWithRevision, unitOfMeasureCode, name, type, replenishmentSystem, active, itemTrackingType";-const $partsStore = computed($itemsStore, (item) =>- item.filter((i) => i.type === "Part")-);+type ItemRow = Omit<Item, "supersessionMode" | "successorItemId">;-const $toolsStore = computed($itemsStore, (item) =>- item.filter((i) => i.type === "Tool")-);+// A phase-out rule lives on its own table; the pickers read it off the item.+async function withSupersession(+ carbon: SupabaseClient<Database>,+ companyId: string,+ items: ItemRow[],+ ids?: string[]+): Promise<Item[]> {+ const supersessions = await fetchAllFromTable<{+ itemId: string;+ supersessionMode: Database["public"]["Enums"]["supersessionMode"];+ successorItemId: string | null;+ }>(+ carbon,+ "itemSupersession",+ "itemId, supersessionMode, successorItemId",+ (query) => {+ const scoped = query.eq("companyId", companyId);+ return ids ? scoped.in("itemId", ids) : scoped;+ }+ );+ const byItem = new Map((supersessions.data ?? []).map((s) => [s.itemId, s]));+ return items.map((item) => ({+ ...item,+ supersessionMode: byItem.get(item.id)?.supersessionMode ?? null,+ successorItemId: byItem.get(item.id)?.successorItemId ?? null+ }));+}++export const itemsList: LiveList<Item> = {+ name: "items",+ table: "item",+ async fetchAll(carbon, companyId) {+ const items = await fetchAllFromTable<ItemRow>(+ carbon,+ "item",+ ITEM_COLUMNS,+ (query) =>+ query+ .eq("companyId", companyId)+ .order("readableId", { ascending: true })+ .order("revision", { ascending: false })+ );+ if (items.error) throw new Error("Failed to fetch items");+ return withSupersession(carbon, companyId, items.data ?? []);+ },+ async fetchByIds(carbon, companyId, ids) {+ const items = await carbon+ .from("item")+ .select(ITEM_COLUMNS)+ .eq("companyId", companyId)+ .in("id", ids);+ if (items.error) throw new Error("Failed to fetch items");+ return withSupersession(+ carbon,+ companyId,+ (items.data ?? []) as ItemRow[],+ ids+ );+ },+ // A supersession rule is logged under its item's id.+ related: [+ {+ table: "itemSupersession",+ fetch: (carbon, companyId, ids) =>+ itemsList.fetchByIds(carbon, companyId, ids)+ }+ ],+ sort: (a, b) =>+ a.readableIdWithRevision.localeCompare(b.readableIdWithRevision)+};-const $serivceStore = computed($itemsStore, (item) =>- item.filter((i) => i.type === "Service")-);+export const useItems = () => useLiveList(itemsList, useUser().company.id);-const $materialsStore = computed($itemsStore, (item) =>- item.filter((i) => i.type === "Material")-);+const useItemsOfType = (type: Item["type"]) => {+ const [items] = useItems();+ return useMemo(() => items.filter((i) => i.type === type), [items, type]);+};-export const useItems = () => useNanoStore<Item[]>($itemsStore, "items");-export const useParts = () => useValue($partsStore);-export const useTools = () => useValue($toolsStore);-export const useServices = () => useValue($serivceStore);-export const useMaterials = () => useValue($materialsStore);+export const useParts = () => useItemsOfType("Part");+export const useTools = () => useItemsOfType("Tool");+export const useServices = () => useItemsOfType("Service");+export const useMaterials = () => useItemsOfType("Material");diff --git a/apps/erp/app/stores/people.ts b/apps/erp/app/stores/people.tsindex 06fcc669b5..12caeac310 100644--- a/apps/erp/app/stores/people.ts+++ b/apps/erp/app/stores/people.ts@@ -2,11 +2,41 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { atom } from "nanostores";-import { useNanoStore } from "~/hooks";+import { fetchAllFromTable } from "@carbon/database";+import { type LiveList, useLiveList } from "@carbon/query";+import { useUser } from "~/hooks";import type { ListItem } from "~/types";-const $peopleStore = atom<- (ListItem & { avatarUrl: string | null; active?: boolean })[]->([]);-export const usePeople = () => useNanoStore($peopleStore, "people");+export type Person = ListItem & { avatarUrl: string | null; active?: boolean };++// Read from the `employees` view (user + employee + job). An employee's id is+// their user id, so a changed `employee` row — or a renamed `user`, which the+// change log records under `employee` — is re-read from the view by that id.+const COLUMNS = "id, name, email, avatarUrl, active";++export const peopleList: LiveList<Person> = {+ name: "people",+ table: "employee",+ async fetchAll(carbon, companyId) {+ const rows = await fetchAllFromTable<Person>(+ carbon,+ "employees",+ COLUMNS,+ (query) => query.eq("companyId", companyId).order("name")+ );+ if (rows.error) throw new Error("Failed to fetch people");+ return rows.data ?? [];+ },+ async fetchByIds(carbon, companyId, ids) {+ const rows = await carbon+ .from("employees")+ .select(COLUMNS)+ .eq("companyId", companyId)+ .in("id", ids);+ if (rows.error) throw new Error("Failed to fetch people");+ return (rows.data ?? []) as Person[];+ },+ sort: (a, b) => a.name.localeCompare(b.name)+};++export const usePeople = () => useLiveList(peopleList, useUser().company.id);diff --git a/apps/erp/app/stores/suppliers.ts b/apps/erp/app/stores/suppliers.tsindex 6cd05de43f..881974ae46 100644--- a/apps/erp/app/stores/suppliers.ts+++ b/apps/erp/app/stores/suppliers.ts@@ -2,15 +2,43 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { atom } from "nanostores";-import { useNanoStore } from "~/hooks";+import { fetchAllFromTable } from "@carbon/database";+import { type LiveList, useLiveList } from "@carbon/query";+import { useUser } from "~/hooks";import type { ListItem } from "~/types";-const $suppliersStore = atom<- (Omit<ListItem, "readableId"> & {- website?: string | null;- supplierStatus?: string | null;- readableId?: string | null;- })[]->([]);-export const useSuppliers = () => useNanoStore($suppliersStore, "suppliers");+export type Supplier = Omit<ListItem, "readableId"> & {+ website?: string | null;+ supplierStatus?: string | null;+ readableId?: string | null;+};++const COLUMNS = "id, name, website, supplierStatus, readableId";++export const suppliersList: LiveList<Supplier> = {+ name: "suppliers",+ table: "supplier",+ async fetchAll(carbon, companyId) {+ const rows = await fetchAllFromTable<Supplier>(+ carbon,+ "supplier",+ COLUMNS,+ (query) => query.eq("companyId", companyId).order("name")+ );+ if (rows.error) throw new Error("Failed to fetch suppliers");+ return rows.data ?? [];+ },+ async fetchByIds(carbon, companyId, ids) {+ const rows = await carbon+ .from("supplier")+ .select(COLUMNS)+ .eq("companyId", companyId)+ .in("id", ids);+ if (rows.error) throw new Error("Failed to fetch suppliers");+ return (rows.data ?? []) as Supplier[];+ },+ sort: (a, b) => a.name.localeCompare(b.name)+};++export const useSuppliers = () =>+ useLiveList(suppliersList, useUser().company.id);diff --git a/apps/erp/app/utils/handle.ts b/apps/erp/app/utils/handle.tsindex e13f44e88e..37a9d7c00d 100644--- a/apps/erp/app/utils/handle.ts+++ b/apps/erp/app/utils/handle.ts@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import type { RouteRealtimeTable } from "@carbon/database/realtime-tables";import type { MessageDescriptor } from "@lingui/core";import type { ComponentType, ReactNode } from "react";@@ -9,6 +10,9 @@ export type Handle = {breadcrumb?: any;to?: string;module?: string;+ // The tables this route shows. The shell (`RouteRealtime`) reloads the page+ // when one of them changes; each must be in REALTIME_TABLES.+ realtime?: RouteRealtimeTable[];// A module layout's sub-navigation. The shell renders it in the one module// sidebar (`ModuleSidebarLayout`), so it stays in place across modules.sidebar?: ComponentType;diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.tsindex 93bdda4192..1fc5ba464b 100644--- a/apps/erp/app/utils/path.ts+++ b/apps/erp/app/utils/path.ts@@ -1944,8 +1944,6 @@ export const path = {purchasingRfq: (id: string) => generatePath(`${x}/purchasing-rfq/${id}`),purchasingRfqCompare: (id: string) =>generatePath(`${x}/purchasing-rfq/${id}/compare`),- purchasingRfqConvert: (id: string) =>- generatePath(`${x}/purchasing-rfq/${id}/convert`),purchasingRfqDetails: (id: string) =>generatePath(`${x}/purchasing-rfq/${id}/details`),purchasingRfqFavorite: `${x}/purchasing/rfqs/favorite`,diff --git a/apps/erp/app/utils/react-query.test.ts b/apps/erp/app/utils/react-query.test.tsdeleted file mode 100644index 80718a4416..0000000000--- a/apps/erp/app/utils/react-query.test.ts+++ /dev/null@@ -1,18 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { describe, expect, it } from "vitest";-import { getClientCache, getCompanyId } from "./react-query";--describe("getCompanyId", () => {- it("returns null when called during server rendering", () => {- expect(() => getCompanyId()).not.toThrow();- expect(getCompanyId()).toBeNull();- });-- it("does not read the client cache during server rendering", () => {- expect(() => getClientCache()).not.toThrow();- expect(getClientCache()).toBeUndefined();- });-});diff --git a/apps/erp/app/utils/react-query.ts b/apps/erp/app/utils/react-query.tsdeleted file mode 100644index 9d000017db..0000000000--- a/apps/erp/app/utils/react-query.ts+++ /dev/null@@ -1,325 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import type { QueryClient } from "@tanstack/react-query";-import * as cookie from "cookie";--enum RefreshRate {- Never = Infinity,- High = 1000 * 60 * 2,- Medium = 1000 * 60 * 10,- Low = 1000 * 60 * 30-}--export const getCompanyId = () => {- if (typeof document === "undefined") {- return null;- }-- const cookieHeader = document.cookie;- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration- const parsed = cookieHeader ? cookie.parse(cookieHeader)["companyId"] : null;- return parsed ?? null;-};--export const getClientCache = (): QueryClient | undefined => {- if (typeof window === "undefined") {- return undefined;- }-- return window.clientCache;-};--export const abilitiesQuery = (companyId: string | null) => ({- queryKey: ["abilities", companyId ?? "null"],- staleTime: RefreshRate.Low-});--export const accountsQuery = (companyId: string | null) => ({- queryKey: ["accounts", companyId ?? "null"],- staleTime: RefreshRate.Low-});--export const assemblyInstructionsQuery = (- itemId: string,- companyId: string | null-) => ({- queryKey: ["assemblyInstructions", itemId, companyId ?? "null"],- staleTime: RefreshRate.Low-});--export const countriesQuery = () => ({- queryKey: ["countries"],- staleTime: RefreshRate.Never-});--export const currenciesQuery = () => ({- queryKey: ["currencies"],- staleTime: RefreshRate.Never-});--export const timezonesQuery = () => ({- queryKey: ["timezones"],- staleTime: RefreshRate.Never-});--export const customerContactsQuery = (customerId: string) => ({- queryKey: ["customerContacts", customerId],- staleTime: RefreshRate.Low-});--export const customerLocationsQuery = (customerId: string) => ({- queryKey: ["customerLocations", customerId],- staleTime: RefreshRate.Low-});--export const customerTypesQuery = (companyId: string | null) => ({- queryKey: ["customerTypes", companyId ?? "null"],- staleTime: RefreshRate.Low-});--export const issueTypesQuery = (companyId: string | null) => ({- queryKey: ["issueTypes", companyId ?? "null"],- staleTime: RefreshRate.Low-});--export const configurableItemsQuery = (companyId: string | null) => ({- queryKey: ["configurableItems", companyId ?? "null"],- staleTime: RefreshRate.Low-});--export const docsQuery = () => ({- queryKey: ["docs"],- staleTime: RefreshRate.Never-});--export const inspectionDocumentsQuery = (- itemId: string,- companyId: string | null-) => ({- queryKey: ["inspectionDocuments", itemId, companyId ?? "null"],- staleTime: RefreshRate.Low-});--// Clears every cached inspection-document list for the current company. Mutation-// routes are keyed by document `id`, not `itemId`, so they can't rebuild the-// exact per-item key — a predicate on the key prefix covers all item entries.-// `removeQueries` (not `invalidateQueries`) is required: the read route's-// clientLoader gates on `if (!data)`, and the combobox reads via an imperative-// `useFetcher().load()` with no active observer, so a merely stale-marked entry-// would keep returning the cached array and never refetch.-export const invalidateInspectionDocuments = () => {- const companyId = getCompanyId();- getClientCache()?.removeQueries({- predicate: (query) => {- const queryKey = query.queryKey as string[];- return (- queryKey[0] === "inspectionDocuments" &&- (!companyId || queryKey[2] === companyId)- );- }- });-};--export const itemPostingGroupsQuery = (companyId: string | null) => ({- queryKey: ["itemPostingGroups", companyId ?? "null"],- staleTime: RefreshRate.Low-});--export const ITEM_QUANTITIES_QUERY_KEY = "itemQuantities";--export const itemQuantitiesQuery = (- locationId: string,- companyId: string | null-) => ({- queryKey: [ITEM_QUANTITIES_QUERY_KEY, companyId ?? "null", locationId],- staleTime: RefreshRate.High-});--export const locationsQuery = (companyId: string | null) => ({- queryKey: ["locations", companyId ?? "null"],- staleTime: RefreshRate.Low-});--export const paymentTermsQuery = (companyId: string | null) => ({- queryKey: ["paymentTerms", companyId ?? "null"],- staleTime: RefreshRate.Low-});--export const processesQuery = (companyId: string | null) => ({- queryKey: ["processes", companyId ?? "null"],- staleTime: RefreshRate.Low-});--export const proceduresQuery = (companyId: string | null) => ({- queryKey: ["procedures", companyId ?? "null"],- staleTime: RefreshRate.Low-});--export const storageUnitsQuery = (- companyId: string | null,- locationId: string | null,- itemId?: string | null-) => ({- queryKey: [- "storageUnits",- companyId ?? "null",- locationId ?? "null",- itemId ?? "null"- ],- staleTime: RefreshRate.Low-});--export const serialNumbersQuery = (- companyId: string | null,- itemId: string | null-) => ({- queryKey: ["serialNumbers", companyId ?? "null", itemId ?? "null"],- staleTime: RefreshRate.Low-});--export const shippingMethodsQuery = (companyId: string | null) => ({- queryKey: ["shippingMethods", companyId ?? "null"],- staleTime: RefreshRate.Low-});--export const supplierContactsQuery = (supplierId: string) => ({- queryKey: ["supplierContacts", supplierId],- staleTime: RefreshRate.Low-});--export const supplierLocationsQuery = (supplierId: string) => ({- queryKey: ["supplierLocations", supplierId],- staleTime: RefreshRate.Low-});--export const supplierProcessesQuery = (processId: string) => ({- queryKey: ["supplierProcesses", processId],- staleTime: RefreshRate.Low-});--export const supplierTypesQuery = (companyId: string | null) => ({- queryKey: ["supplierTypes", companyId ?? "null"],- staleTime: RefreshRate.Low-});--export const uomsQuery = (companyId: string | null) => ({- queryKey: ["uoms", companyId ?? "null"],- staleTime: RefreshRate.Medium-});--export const webhookTablesQuery = () => ({- queryKey: ["webhookTables"],- staleTime: RefreshRate.Never-});--export const workCentersQuery = (companyId: string | null) => ({- queryKey: ["workCenters", companyId ?? "null"],- staleTime: RefreshRate.Low-});--export const materialTypesQuery = (- substanceId: string,- formId: string,- companyId: string | null-) => ({- queryKey: ["materialTypes", substanceId, formId, companyId ?? "null"],- staleTime: RefreshRate.Low-});--export const userSelectGroupsQuery = (- companyId: string | null,- type: string | null,- offset: number-) => ({- queryKey: ["userSelectGroups", companyId ?? "null", type ?? "all", offset],- staleTime: RefreshRate.Low-});--export const userSelectMembersQuery = (- companyId: string | null,- groupId: string-) => ({- queryKey: ["userSelectMembers", companyId ?? "null", groupId],- staleTime: RefreshRate.Low-});--export const userSelectSearchQuery = (- companyId: string | null,- type: string | null,- q: string,- filters: string-) => ({- queryKey: [- "userSelectSearch",- companyId ?? "null",- type ?? "all",- q,- filters- ],- staleTime: RefreshRate.High-});--export const userSelectResolveQuery = (- companyId: string | null,- ids: string[]-) => ({- queryKey: [- "userSelectResolve",- companyId ?? "null",- [...ids].sort().join(",")- ],- staleTime: RefreshRate.Low-});--export const groupEmailsQuery = (- companyId: string | null,- groupId: string-) => ({- queryKey: ["groupEmails", companyId ?? "null", groupId],- staleTime: RefreshRate.Low-});--const USER_SELECT_QUERY_PREFIXES = [- "userSelectGroups",- "userSelectMembers",- "userSelectSearch",- "userSelectResolve",- "groupEmails"-];--/**- * Read-through fetch against an API route, cached in window.clientCache.- * fetchQuery dedupes concurrent identical calls and honors staleTime.- * Falls back to a plain fetch when the cache isn't mounted yet.- */-export async function cachedApiQuery<T>(- query: { queryKey: unknown[]; staleTime: number },- url: string-): Promise<T> {- const queryFn = async (): Promise<T> => {- const res = await fetch(url);- if (!res.ok) throw new Error(`Request failed with status ${res.status}`);- return res.json();- };- const cache = getClientCache();- if (!cache) return queryFn();- return cache.fetchQuery({- queryKey: query.queryKey,- queryFn,- staleTime: query.staleTime- });-}--export function invalidateUserSelectQueries(companyId: string | null) {- window.clientCache?.invalidateQueries({- predicate: (query) => {- const queryKey = query.queryKey as unknown[];- return (- USER_SELECT_QUERY_PREFIXES.includes(queryKey[0] as string) &&- queryKey[1] === (companyId ?? "null")- );- }- });-}diff --git a/apps/erp/package.json b/apps/erp/package.jsonindex 70a5940d84..d68bbaa909 100644--- a/apps/erp/package.json+++ b/apps/erp/package.json@@ -25,6 +25,7 @@"@carbon/server-functions": "workspace:*","@carbon/planning": "workspace:*","@carbon/printing": "workspace:*",+ "@carbon/query": "workspace:*","@carbon/react": "workspace:*","@carbon/stripe": "workspace:*","@carbon/utils": "workspace:*",@@ -41,7 +42,6 @@"@lingui/react": "catalog:","@modelcontextprotocol/sdk": "1.29.0","@monaco-editor/react": "4.7.0",- "@nanostores/react": "catalog:","@orpc/openapi": "catalog:","@orpc/server": "catalog:","@paper-design/shaders-react": "^0.0.57",@@ -57,7 +57,7 @@"@supabase/postgrest-js": "catalog:","@supabase/storage-js": "catalog:","@supabase/supabase-js": "catalog:",- "@tanstack/react-query": "5.97.0",+ "@tanstack/react-query": "catalog:","@tanstack/react-table": "8.21.3","@tanstack/react-virtual": "3.13.23","@tiptap/react": "catalog:",@@ -92,7 +92,6 @@"motion": "catalog:","motion-number": "0.1.7","nanoid": "catalog:",- "nanostores": "catalog:","non.geist": "catalog:","papaparse": "5.3.2","pdf-lib": "^1.17.1",@@ -139,6 +138,7 @@"zustand": "catalog:"},"devDependencies": {+ "@tanstack/react-query-devtools": "catalog:","@carbon/config": "workspace:*","@carbon/dev": "workspace:*","@lingui/conf": "catalog:",diff --git a/apps/mes/app/components/AssemblyView.tsx b/apps/mes/app/components/AssemblyView.tsxindex b53c245dcb..3bbd08f42b 100644--- a/apps/mes/app/components/AssemblyView.tsx+++ b/apps/mes/app/components/AssemblyView.tsx@@ -44,7 +44,6 @@ import {useDisclosure,useKeyboardWedge,useMode,- useRealtimeChannel,useRouteData,useShortcutKeys} from "@carbon/react";@@ -100,7 +99,7 @@ import { QuantityModal } from "~/components/JobOperation/components/QuantityModaimport { ReworkModal } from "~/components/JobOperation/components/ReworkModal";import { SerialSelectorModal } from "~/components/JobOperation/components/SerialSelectorModal";import { RecordModal } from "~/components/JobOperation/components/Step";-import { useRealtimeRevalidator, useUser } from "~/hooks";+import { useRealtime, useUser } from "~/hooks";import { isSerialEntityIncompleteForOperation } from "~/services/operations.service";import type {JobMaterial,@@ -539,7 +538,6 @@ export function AssemblyView({const { carbon } = useCarbon();const mode = useMode();const navigate = useNavigate();- const revalidate = useRealtimeRevalidator();const [searchParams, setSearchParams] = useSearchParams();const { t } = useLingui();// Which main panel is shown: the assembly details, the 3D model, or chat.@@ -581,44 +579,10 @@ export function AssemblyView({// Live sync — refresh loader data when this operation's events, step records,// job, or tracked entities change (incl. edits from the operation view).- useRealtimeChannel({- topic: `assembly:${operationId}`,- dependencies: [operationId],- setup(channel) {- const refresh = () => revalidate();- return channel- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "productionEvent",- filter: `jobOperationId=eq.${operationId}`- },- refresh- )- .on(- "postgres_changes",- { event: "*", schema: "public", table: "jobOperationStepRecord" },- refresh- )- .on(- "postgres_changes",- { event: "*", schema: "public", table: "trackedActivity" },- refresh- )- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "jobOperation",- filter: `id=eq.${operationId}`- },- refresh- );- }- });+ useRealtime("productionEvent", `jobOperationId=eq.${operationId}`);+ useRealtime("jobOperationStepRecord", `operationId=eq.${operationId}`);+ useRealtime("trackedActivity", `jobOperationId=eq.${operationId}`);+ useRealtime("jobOperation", `id=eq.${operationId}`);// Kanban barcode scan → complete the operation (matches the operation view).// The returned buffer is non-empty while a scan burst is in flight — the@@ -2353,14 +2317,21 @@ export function AssemblyView({<p className="text-lg font-medium leading-relaxed">{step.name ?? `Step ${currentStep + 1}`}</p>- {stepDescriptionHtml ? (- <div- className="prose prose-sm max-w-none text-sm text-foreground dark:prose-invert"- dangerouslySetInnerHTML={{- __html: stepDescriptionHtml- }}- />- ) : null}+ {/* generateHTML returns nothing on the server, so the+ server never renders this block: rendering it during+ hydration would not match. */}+ <ClientOnly>+ {() =>+ stepDescriptionHtml ? (+ <div+ className="prose prose-sm max-w-none text-sm text-foreground dark:prose-invert"+ dangerouslySetInnerHTML={{+ __html: stepDescriptionHtml+ }}+ />+ ) : null+ }+ </ClientOnly></>) : (<p className="text-sm text-muted-foreground">@@ -2965,7 +2936,11 @@ function TimerControl({><span className="hidden flex-col items-end leading-none sm:flex"><span className="text-sm font-medium tabular-nums">- {formatElapsed(elapsed)}+ {/* The clock moves between the server render and hydration, so the+ elapsed time is only rendered in the browser. */}+ <ClientOnly fallback={formatElapsed(0)}>+ {() => formatElapsed(elapsed)}+ </ClientOnly></span><span className="text-[9px] uppercase tracking-wider text-muted-foreground">{workType}diff --git a/apps/mes/app/components/Inspection/DispositionModal.tsx b/apps/mes/app/components/Inspection/DispositionModal.tsxindex a1e7050e36..5e5d97275d 100644--- a/apps/mes/app/components/Inspection/DispositionModal.tsx+++ b/apps/mes/app/components/Inspection/DispositionModal.tsx@@ -9,6 +9,7 @@ import {TextArea,ValidatedForm} from "@carbon/form";+import { useAction } from "@carbon/query";import {Alert,AlertDescription,@@ -112,7 +113,14 @@ const DispositionModal = ({onSubmit}: DispositionModalProps) => {const { t } = useLingui();- const fetcher = useFetcher<{}>();+ const fetcher = useAction<{}>({+ onSettled: () => {+ if (submitted.current) {+ onSubmit();+ submitted.current = false;+ }+ }+ });const targetsFetcher = useFetcher<{ operations: UpstreamOperation[] }>();const submitted = useRef(false);const loadedTargetsRef = useRef(false);@@ -143,13 +151,6 @@ const DispositionModal = ({targetsFetcher.load(path.to.reworkTargets(operationId));}, [operationId, targetsFetcher.load]);- useEffect(() => {- if (fetcher.state === "idle" && submitted.current) {- onSubmit();- submitted.current = false;- }- }, [fetcher.state, onSubmit]);-const targets = targetsFetcher.data?.operations ?? [];const hasIssueTypes = issueTypes.length > 0;diff --git a/apps/mes/app/components/Inspection/InspectionView.tsx b/apps/mes/app/components/Inspection/InspectionView.tsxindex 0238658d5e..bc8e2e7b85 100644--- a/apps/mes/app/components/Inspection/InspectionView.tsx+++ b/apps/mes/app/components/Inspection/InspectionView.tsx@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { useAction } from "@carbon/query";import {Badge,BottomSheet,@@ -1157,15 +1158,15 @@ function AcceptLotModal({eventIds: ProductionEventIdFields;onClose: () => void;}) {- const fetcher = useFetcher<{}>();- const submitted = useRef(false);-- useEffect(() => {- if (fetcher.state === "idle" && submitted.current) {- onClose();- submitted.current = false;+ const fetcher = useAction<{}>({+ onSettled: () => {+ if (submitted.current) {+ onClose();+ submitted.current = false;+ }}- }, [fetcher.state, onClose]);+ });+ const submitted = useRef(false);return (<Modal@@ -1360,7 +1361,11 @@ function TimerControl({><span className="hidden flex-col items-end leading-none sm:flex"><span className="text-sm font-medium tabular-nums">- {formatElapsed(elapsed)}+ {/* The clock moves between the server render and hydration, so the+ elapsed time is only rendered in the browser. */}+ <ClientOnly fallback={formatElapsed(0)}>+ {() => formatElapsed(elapsed)}+ </ClientOnly></span><span className="text-[9px] uppercase tracking-wider text-muted-foreground">{workType}diff --git a/apps/mes/app/components/JobOperation/components/BatchRecordModal.tsx b/apps/mes/app/components/JobOperation/components/BatchRecordModal.tsxindex f876940634..cbaa8e3e73 100644--- a/apps/mes/app/components/JobOperation/components/BatchRecordModal.tsx+++ b/apps/mes/app/components/JobOperation/components/BatchRecordModal.tsx@@ -4,6 +4,7 @@import { useCarbon } from "@carbon/auth";import { storage } from "@carbon/files";+import { useAction } from "@carbon/query";import {Button,Checkbox,@@ -21,9 +22,8 @@ import {import { datetime, stripSpecialCharacters } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { nanoid } from "nanoid";-import { useEffect, useState } from "react";+import { useState } from "react";import { LuCircleCheck, LuFile } from "react-icons/lu";-import { useFetcher } from "react-router";import { useUser } from "~/hooks";import type { BatchStep } from "~/services/operations.service";import { usePeople } from "~/stores";@@ -83,7 +83,13 @@ export function BatchRecordModal({const { carbon } = useCarbon();const { company } = useUser();const [people] = usePeople();- const fetcher = useFetcher<{ success?: boolean }>();+ const fetcher = useAction<{ success?: boolean }>({+ onSuccess: (data) => {+ if (data?.success) {+ onClose();+ }+ }+ });const kind = kindOf(step.type);const ticked = kind === "tick" || kind === "file";@@ -99,10 +105,6 @@ export function BatchRecordModal({const [passed, setPassed] = useState(true);const [uploading, setUploading] = useState(false);- useEffect(() => {- if (fetcher.data?.success) onClose();- }, [fetcher.data?.success, onClose]);-const changed = members.filter((m) =>ticked? selected.has(m.stepId)diff --git a/apps/mes/app/components/JobOperation/components/Chat.tsx b/apps/mes/app/components/JobOperation/components/Chat.tsxindex 0eaf14e77a..d7dd25be5a 100644--- a/apps/mes/app/components/JobOperation/components/Chat.tsx+++ b/apps/mes/app/components/JobOperation/components/Chat.tsx@@ -4,6 +4,7 @@import { useCarbon } from "@carbon/auth";import { getLogger } from "@carbon/logger";+import { useChangedRows } from "@carbon/query";import {Avatar,Button,@@ -12,8 +13,7 @@ import {Loading,ScrollArea,useDebounce,- useMount,- useRealtimeChannel+ useMount} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import { nanoid } from "nanoid";@@ -74,26 +74,17 @@ export function OperationChat({fetchChats();});- useRealtimeChannel({- topic: `job-operation-notes-${operation.id}`,- setup(channel) {- return channel.on(- "postgres_changes",- {- event: "INSERT",- schema: "public",- table: "jobOperationNote",- filter: `jobOperationId=eq.${operation.id}`- },- (payload) => {- setMessages((prev) => {- if (prev.some((note) => note.id === payload.new.id)) {- return prev;- }- return [...prev, payload.new as Message];- });- }- );+ useChangedRows<Message & { jobOperationId: string }>({+ companyId: user.company.id,+ table: "jobOperationNote",+ onResync: fetchChats,+ onChange: ({ op, rows }) => {+ if (op !== "INSERT") return;+ const notes = rows.filter((row) => row.jobOperationId === operation.id);+ setMessages((prev) => [+ ...prev,+ ...notes.filter((note) => !prev.some((p) => p.id === note.id))+ ]);}});diff --git a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsxindex 28bfdb796f..e9d33c5d1f 100644--- a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx+++ b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx@@ -4,6 +4,7 @@import { useCarbon } from "@carbon/auth";import { Number as FormNumberInput, Hidden, ValidatedForm } from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import {Alert,AlertDescription,@@ -2101,29 +2102,18 @@ export function IssueMaterialModal({}function useSerialNumbers(itemId?: string) {- const serialNumbersFetcher =- useFetcher<Awaited<ReturnType<typeof getSerialNumbersForItem>>>();-- // biome-ignore lint/correctness/useExhaustiveDependencies: ignore- useEffect(() => {- if (itemId) {- serialNumbersFetcher.load(path.to.api.serialNumbers(itemId));- }- }, [itemId]);+ const serialNumbersFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getSerialNumbersForItem>>+ >(itemId ? path.to.api.serialNumbers(itemId) : null);return { data: serialNumbersFetcher.data };}// Hook for fetching batch numbersfunction useBatchNumbers(itemId?: string) {- const batchNumbersFetcher =- useFetcher<Awaited<ReturnType<typeof getBatchNumbersForItem>>>();-- useEffect(() => {- if (itemId) {- batchNumbersFetcher.load(path.to.api.batchNumbers(itemId));- }- }, [itemId, batchNumbersFetcher.load]);+ const batchNumbersFetcher = useLoaderQuery<+ Awaited<ReturnType<typeof getBatchNumbersForItem>>+ >(itemId ? path.to.api.batchNumbers(itemId) : null);return { data: batchNumbersFetcher.data };}diff --git a/apps/mes/app/components/JobOperation/components/MaintenanceDispatch.tsx b/apps/mes/app/components/JobOperation/components/MaintenanceDispatch.tsxindex b8c29c541b..6d1aeb2dfa 100644--- a/apps/mes/app/components/JobOperation/components/MaintenanceDispatch.tsx+++ b/apps/mes/app/components/JobOperation/components/MaintenanceDispatch.tsx@@ -9,6 +9,7 @@ import {Submit,ValidatedForm} from "@carbon/form";+import { useLoaderQuery } from "@carbon/query";import type { JSONContent } from "@carbon/react";import {Button,@@ -83,13 +84,12 @@ export function MaintenanceDispatch({onClose: () => void;}) {const fetcher = useFetcher<{ id?: string }>();- const failureModeFetcher =- useFetcher<- PostgrestResponse<{- id: string;- name: string;- }>- >();+ const failureModeFetcher = useLoaderQuery<+ PostgrestResponse<{+ id: string;+ name: string;+ }>+ >(isOpen ? path.to.api.failureModes : null);const [content, setContent] = useState<JSONContent>({});const [severity, setSeverity] =@@ -99,12 +99,6 @@ export function MaintenanceDispatch({const failureModes = failureModeFetcher.data?.data ?? [];- useEffect(() => {- if (isOpen) {- failureModeFetcher.load(path.to.api.failureModes);- }- }, [isOpen, failureModeFetcher.load]);-const handleClose = () => {setContent({});setSeverity("Operator Performed");diff --git a/apps/mes/app/components/JobOperation/components/QualityIssueModal.tsx b/apps/mes/app/components/JobOperation/components/QualityIssueModal.tsxindex 2371435bf7..96c0d49ed7 100644--- a/apps/mes/app/components/JobOperation/components/QualityIssueModal.tsx+++ b/apps/mes/app/components/JobOperation/components/QualityIssueModal.tsx@@ -4,6 +4,7 @@import type { Result } from "@carbon/auth";import { Hidden, Select, Submit, TextArea, ValidatedForm } from "@carbon/form";+import { useAction, useLoaderQuery } from "@carbon/query";import {Button,HStack,@@ -18,8 +19,6 @@ import {} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import type { PostgrestResponse } from "@supabase/supabase-js";-import { useEffect } from "react";-import { useFetcher } from "react-router";import { qualityIssuePriority, qualityIssueValidator } from "~/services/models";import { path } from "~/utils/path";@@ -35,24 +34,19 @@ export function QualityIssueModal({onClose: () => void;}) {const { t } = useLingui();- const fetcher = useFetcher<Result>();- const issueTypeFetcher =- useFetcher<PostgrestResponse<{ id: string; name: string }>>();-- const issueTypes = issueTypeFetcher.data?.data ?? [];-- useEffect(() => {- if (isOpen) {- issueTypeFetcher.load(path.to.api.qualityIssueTypes);+ const fetcher = useAction<Result>({+ onSuccess: (data) => {+ if (data?.success) {+ toast.success(t`Quality issue created`);+ onClose();+ }}- }, [isOpen, issueTypeFetcher.load]);+ });+ const issueTypeFetcher = useLoaderQuery<+ PostgrestResponse<{ id: string; name: string }>+ >(isOpen ? path.to.api.qualityIssueTypes : null);- useEffect(() => {- if (fetcher.state === "idle" && fetcher.data?.success) {- toast.success(t`Quality issue created`);- onClose();- }- }, [fetcher.state, fetcher.data, onClose, t]);+ const issueTypes = issueTypeFetcher.data?.data ?? [];if (!isOpen) return null;diff --git a/apps/mes/app/components/JobOperation/components/QuantityModal.tsx b/apps/mes/app/components/JobOperation/components/QuantityModal.tsxindex c1f9df39a0..b9cbe87894 100644--- a/apps/mes/app/components/JobOperation/components/QuantityModal.tsx+++ b/apps/mes/app/components/JobOperation/components/QuantityModal.tsx@@ -8,6 +8,7 @@ import {TextArea,ValidatedForm} from "@carbon/form";+import { useAction } from "@carbon/query";import {Alert,AlertDescription,@@ -24,9 +25,8 @@ import {VStack} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";-import { useEffect, useRef, useState } from "react";+import { useRef, useState } from "react";import { LuTriangleAlert } from "react-icons/lu";-import { useFetcher } from "react-router";import {finishValidator,nonScrapQuantityValidator,@@ -78,7 +78,13 @@ export function QuantityModal({onClose: () => void;}) {const { t } = useLingui();- const fetcher = useFetcher<ProductionQuantity>();+ const fetcher = useAction<ProductionQuantity>({+ onSettled: () => {+ if (submitted.current) {+ onClose();+ }+ }+ });const [quantity, setQuantity] = useState(parentIsSerial ? 1 : 0);const [confirmedUnissued, setConfirmedUnissued] = useState(false);const submitted = useRef(false);@@ -95,12 +101,6 @@ export function QuantityModal({reworked: operation.quantityReworked ?? 0};- useEffect(() => {- if (submitted.current && fetcher.state === "idle") {- onClose();- }- }, [fetcher.state, onClose]);-const titleMap = {scrap: t`Log scrap for ${operation.itemReadableId}`,rework: t`Log rework for ${operation.itemReadableId}`,diff --git a/apps/mes/app/components/JobOperation/components/ReworkModal.tsx b/apps/mes/app/components/JobOperation/components/ReworkModal.tsxindex 442a383625..7d0a772abc 100644--- a/apps/mes/app/components/JobOperation/components/ReworkModal.tsx+++ b/apps/mes/app/components/JobOperation/components/ReworkModal.tsx@@ -11,6 +11,7 @@ import {TextArea,ValidatedForm} from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Checkbox,@@ -64,7 +65,14 @@ export function ReworkModal({parentIsBatch?: boolean;}) {const { t } = useLingui();- const fetcher = useFetcher<Result>();+ const fetcher = useAction<Result>({+ onSuccess: (data) => {+ if (data?.success) {+ toast.success(t`Rework created successfully`);+ onClose();+ }+ }+ });const targetsFetcher = useFetcher<{operations: UpstreamOperation[];}>();@@ -109,13 +117,6 @@ export function ReworkModal({targetsFetcher.load]);- useEffect(() => {- if (fetcher.state === "idle" && fetcher.data?.success) {- toast.success(t`Rework created successfully`);- onClose();- }- }, [fetcher.state, fetcher.data, onClose, t]);-const filteredEntities = useMemo(() => {if (!scanInput) return trackedEntities;const search = scanInput.toLowerCase();diff --git a/apps/mes/app/components/JobOperation/components/Step.tsx b/apps/mes/app/components/JobOperation/components/Step.tsxindex 86b6254a19..a823e0695f 100644--- a/apps/mes/app/components/JobOperation/components/Step.tsx+++ b/apps/mes/app/components/JobOperation/components/Step.tsx@@ -14,6 +14,7 @@ import {Submit,ValidatedForm} from "@carbon/form";+import { useAction } from "@carbon/query";import type { JSONContent } from "@carbon/react";import {Button,@@ -47,7 +48,7 @@ import {import { Trans, useLingui } from "@lingui/react/macro";import { useNumberFormatter } from "@react-aria/i18n";import { nanoid } from "nanoid";-import { useEffect, useMemo, useRef, useState } from "react";+import { useMemo, useRef, useState } from "react";import {LuChevronDown,LuChevronRight,@@ -495,7 +496,13 @@ export function RecordModal({const [filePath, setFilePath] = useState<string | null>(null);// Bumped on every drop/remove so a stale in-flight upload can't set stateconst uploadIdRef = useRef(0);- const fetcher = useFetcher<{ success: boolean }>();+ const fetcher = useAction<{ success: boolean }>({+ onSuccess: (data) => {+ if (data?.success) {+ onClose();+ }+ }+ });const removeFile = () => {uploadIdRef.current += 1;@@ -532,12 +539,6 @@ export function RecordModal({}};- useEffect(() => {- if (fetcher.data?.success) {- onClose();- }- }, [fetcher.data?.success, onClose]);-const record = attribute?.jobOperationStepRecord.find((r) => r.index === activeStep);@@ -726,13 +727,13 @@ export function DeleteStepRecordModal({title: string;description: string;}) {- const fetcher = useFetcher<{ success: boolean }>();-- useEffect(() => {- if (fetcher.data?.success) {- onClose();+ const fetcher = useAction<{ success: boolean }>({+ onSuccess: (data) => {+ if (data?.success) {+ onClose();+ }}- }, [fetcher.data?.success, onClose]);+ });return (<Modal open={true} onOpenChange={onClose}>diff --git a/apps/mes/app/components/JobOperation/hooks/useOperation.tsx b/apps/mes/app/components/JobOperation/hooks/useOperation.tsxindex e0bc6931f2..02ac154234 100644--- a/apps/mes/app/components/JobOperation/hooks/useOperation.tsx+++ b/apps/mes/app/components/JobOperation/hooks/useOperation.tsx@@ -3,22 +3,17 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { useCarbon } from "@carbon/auth";-import {- toast,- useDisclosure,- useInterval,- useRealtimeChannel-} from "@carbon/react";+import { useChangedRows } from "@carbon/query";+import { toast, useDisclosure, useInterval } from "@carbon/react";import {getLocalTimeZone,now,parseAbsolute,toZoned} from "@internationalized/date";-import type { RealtimeChannel } from "@supabase/supabase-js";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useParams } from "react-router";-import { useRealtimeRevalidator, useUrlParams, useUser } from "~/hooks";+import { useRealtime, useUrlParams, useUser } from "~/hooks";import { isSerialEntityIncompleteForOperation } from "~/services/operations.service";import { shouldAdvanceToNextSerialUnit } from "~/services/serial-advancement";import type {@@ -71,10 +66,6 @@ export function useOperation({const { carbon, accessToken } = useCarbon();const user = useUser();- const revalidate = useRealtimeRevalidator();- // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration- const channelRef = useRef<RealtimeChannel | null>(null);-const actionsSheet = useDisclosure();const scrapModal = useDisclosure();const reworkModal = useDisclosure();@@ -121,91 +112,62 @@ export function useOperation({setOperationState(operation);}, [operation]);- useRealtimeChannel({- topic: `job-operations:${operation.id}`,- dependencies: [operation.jobId, batchId],- setup(channel) {- return channel- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "job",- filter: `id=eq.${operation.jobId}`- },- (payload) => {- if (payload.eventType === "UPDATE") {- revalidate();- }- }- )- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "productionEvent",- filter: batchId- ? `jobOperationBatchId=eq.${batchId}`- : `jobOperationId=eq.${operation.id}`- },- (payload) => {- switch (payload.eventType) {- case "INSERT":- const { new: inserted } = payload;- setEventState((prevEvents) => [- ...prevEvents,- inserted as ProductionEvent- ]);- break;- case "UPDATE":- const { new: updated } = payload;+ useRealtime("job", `id=eq.${operation.jobId}`);- setEventState((prevEvents) =>- prevEvents.map((event) =>- event.id === updated.id- ? ({- ...event,- ...updated- } as ProductionEvent)- : event- )- );- break;- case "DELETE":- const { old: deleted } = payload;- setEventState((prevEvents) =>- prevEvents.filter((event) => event.id !== deleted.id)- );- break;- default:- break;- }- }- )- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "jobOperation",- filter: `id=eq.${operation.id}`- },- (payload) => {- if (payload.eventType === "UPDATE") {- const updated = payload.new;- setOperationState((prev) => ({- ...prev,- ...updated,- operationStatus: updated.status ?? prev.operationStatus- }));- } else if (payload.eventType === "DELETE") {- toast.error("This operation has been deleted");- window.location.href = path.to.operations;- }- }+ useChangedRows<ProductionEvent>({+ companyId: user.company.id,+ table: "productionEvent",+ filter: batchId+ ? `jobOperationBatchId=eq.${batchId}`+ : `jobOperationId=eq.${operation.id}`,+ onChange: ({ op, ids, rows }) => {+ if (op === "DELETE") {+ setEventState((prevEvents) =>+ prevEvents.filter((event) => !ids.includes(event.id)));+ return;+ }+ const mine = rows.filter((row) =>+ batchId+ ? row.jobOperationBatchId === batchId+ : row.jobOperationId === operation.id+ );+ setEventState((prevEvents) => {+ let next = prevEvents;+ for (const row of mine) {+ next = next.some((event) => event.id === row.id)+ ? next.map((event) =>+ event.id === row.id ? { ...event, ...row } : event+ )+ : [...next, row];+ }+ return next;+ });+ }+ });++ useChangedRows<{+ id: string;+ status?: OperationWithDetails["operationStatus"];+ }>({+ companyId: user.company.id,+ table: "jobOperation",+ filter: `id=eq.${operation.id}`,+ onChange: ({ op, ids, rows }) => {+ if (op === "DELETE") {+ if (ids.includes(operation.id)) {+ toast.error("This operation has been deleted");+ window.location.href = path.to.operations;+ }+ return;+ }+ const updated = rows.find((row) => row.id === operation.id);+ if (!updated) return;+ setOperationState((prev) => ({+ ...prev,+ ...updated,+ operationStatus: updated.status ?? prev.operationStatus+ }));}});diff --git a/apps/mes/app/components/RealtimeDataProvider.tsx b/apps/mes/app/components/RealtimeDataProvider.tsxindex 432e0c8da2..e5242c642e 100644--- a/apps/mes/app/components/RealtimeDataProvider.tsx+++ b/apps/mes/app/components/RealtimeDataProvider.tsx@@ -4,206 +4,32 @@"use client";-import { useCarbon } from "@carbon/auth";-import { fetchAllFromTable } from "@carbon/database";-import { useRealtimeChannel } from "@carbon/react";-import type { RealtimeChannel } from "@supabase/supabase-js";-import idb from "localforage";-import { useEffect, useRef } from "react";+import { LiveLists } from "@carbon/query";import { useUser } from "~/hooks";-import { useItems, usePeople } from "~/stores";-import type { Item } from "~/stores/items";+import { itemsList } from "~/stores/items";+import { peopleList } from "~/stores/people";-// IndexedDB entries are keyed per company (`items:<companyId>`) — a global key-// let one company's cached list hydrate the pickers after switching to another-// company. `activeCompanyId` also guards async callbacks racing a mid-flight-// company switch.-let activeCompanyId: string | null = null;-let hydratedFromServer = false;--const LEGACY_IDB_KEYS = ["items", "people"];+// Module-level so their identity is stable across renders.+const LISTS = [itemsList, peopleList];+const storage = async () => (await import("localforage")).default;const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {- // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration- const { carbon, accessToken, isRealtimeAuthSet } = useCarbon();const {+ id: userId,company: { id: companyId }} = useUser();- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- hydratedFromServer = false;- }, [companyId]);-- const [, setItems] = useItems();- const [, setPeople] = usePeople();-- // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration- const channelRef = useRef<RealtimeChannel | null>(null);-- const hydrate = async () => {- const requestedCompanyId = companyId;- if (activeCompanyId !== requestedCompanyId) {- activeCompanyId = requestedCompanyId;-- // pre-keying entries were global; purge so they can never hydrate again- for (const key of LEGACY_IDB_KEYS) {- void idb.removeItem(key);- }-- const fresh = () =>- !hydratedFromServer && activeCompanyId === requestedCompanyId;-- idb.getItem(`items:${requestedCompanyId}`).then((data) => {- if (data && fresh()) setItems(data as Item[], true);- });- idb.getItem(`people:${requestedCompanyId}`).then((data) => {- // @ts-expect-error- if (data && fresh()) setPeople(data, true);- });- }-- if (!carbon || !accessToken || hydratedFromServer) return;-- const [items, people] = await Promise.all([- fetchAllFromTable(- carbon,- "item",- "id, readableIdWithRevision, name, type, replenishmentSystem, itemTrackingType, active, thumbnailPath, modelUpload:modelUploadId(thumbnailPath)",- (query) =>- query- .eq("companyId", companyId)- .order("readableId", { ascending: true })- .order("revision", { ascending: false })- ),- fetchAllFromTable(- carbon,- "employees",- "id, name, email, avatarUrl",- (query) => query.eq("companyId", companyId).order("name")- )- ]);-- if (items.error) {- throw new Error("Failed to fetch items");- }- if (people.error) {- throw new Error("Failed to fetch people");- }-- // company switched while fetching — these results belong to the old company- if (activeCompanyId !== requestedCompanyId) return;-- hydratedFromServer = true;-- type ItemWithModelUpload = Item & {- modelUpload?: { thumbnailPath: string | null } | null;- };- const itemData = (items.data ?? []) as unknown as ItemWithModelUpload[];- setItems(- itemData.map((item) => ({- id: item.id,- name: item.name,- readableIdWithRevision: item.readableIdWithRevision,- type: item.type,- replenishmentSystem: item.replenishmentSystem,- itemTrackingType: item.itemTrackingType,- active: item.active,- thumbnailPath:- item.thumbnailPath ?? item.modelUpload?.thumbnailPath ?? null- }))- );- setPeople(- // @ts-expect-error- people.data ?? []- );- };-- // biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration- useEffect(() => {- if (!companyId) return;- hydrate();- }, [companyId, accessToken]);-- useRealtimeChannel({- topic: "realtime:core",- dependencies: [companyId],- setup(channel) {- return channel.on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "item",- filter: `companyId=eq.${companyId}`- },- (payload) => {- if ("companyId" in payload.new && payload.new.companyId !== companyId)- return;- switch (payload.eventType) {- case "INSERT":- const { new: inserted } = payload;-- setItems((items) =>- [- ...items,- {- id: inserted.id,- name: inserted.name,- readableIdWithRevision: inserted.readableIdWithRevision,- replenishmentSystem: inserted.replenishmentSystem,- itemTrackingType: inserted.itemTrackingType,- type: inserted.type,- active: inserted.active,- thumbnailPath: inserted.thumbnailPath- }- ].sort((a, b) =>- a.readableIdWithRevision.localeCompare(- b.readableIdWithRevision- )- )- );-- break;- case "UPDATE":- const { new: updated } = payload;-- setItems((items) =>- items- .map((i) => {- if (i.id === updated.id) {- return {- ...i,- readableIdWithRevision: updated.readableIdWithRevision,- name: updated.name,- replenishmentSystem: updated.replenishmentSystem,- type: updated.type,- active: updated.active,- thumbnailPath: updated.thumbnailPath- };- }- return i;- })- .sort((a, b) =>- a.readableIdWithRevision.localeCompare(- b.readableIdWithRevision- )- )- );- break;- case "DELETE":- const { old: deleted } = payload;- setItems((items) => items.filter((p) => p.id !== deleted.id));- break;- default:- break;- }- }- );- }- });-- return <>{children}</>;+ return (+ <>+ <LiveLists+ companyId={companyId}+ userId={userId}+ lists={LISTS}+ storage={storage}+ />+ {children}+ </>+ );};export default RealtimeDataProvider;diff --git a/apps/mes/app/components/SessionLockOverlay.tsx b/apps/mes/app/components/SessionLockOverlay.tsxindex 080a64099c..3abb7b3c11 100644--- a/apps/mes/app/components/SessionLockOverlay.tsx+++ b/apps/mes/app/components/SessionLockOverlay.tsx@@ -9,6 +9,7 @@ import {useControlField,ValidatedForm} from "@carbon/form";+import { useAction } from "@carbon/query";import {Alert,AlertDescription,@@ -27,7 +28,7 @@ import {} from "@simplewebauthn/browser";import { useEffect, useRef, useState } from "react";import { LuFingerprint, LuLock } from "react-icons/lu";-import { Form, useFetcher, useLocation } from "react-router";+import { Form, useLocation } from "react-router";import { z } from "zod";import { path } from "~/utils/path";@@ -81,7 +82,13 @@ export default function SessionLockOverlay({const location = useLocation();const redirectTo = `${location.pathname}${location.search}`;- const fetcher = useFetcher<UnlockResult>();+ const fetcher = useAction<UnlockResult>({+ onSuccess: (data) => {+ if (data?.success === true) {+ onUnlocked?.();+ }+ }+ });const [passkeySupported, setPasskeySupported] = useState(false);const [passkeyLoading, setPasskeyLoading] = useState(false);@@ -90,13 +97,6 @@ export default function SessionLockOverlay({if (hasPasskeyAuth && browserSupportsWebAuthn()) setPasskeySupported(true);}, [hasPasskeyAuth]);- // A successful in-place unlock (TOTP or passkey) rotated the cookie already;- // clear the client lock so the overlay unmounts and the app (revalidated with- // the fresh session) shows through.- useEffect(() => {- if (fetcher.data?.success === true) onUnlocked?.();- }, [fetcher.data, onUnlocked]);-const onUnlockWithPasskey = async () => {setPasskeyLoading(true);try {diff --git a/apps/mes/app/components/TimeCardWarning.tsx b/apps/mes/app/components/TimeCardWarning.tsxindex b928fc2b9e..3a4a0bf8c0 100644--- a/apps/mes/app/components/TimeCardWarning.tsx+++ b/apps/mes/app/components/TimeCardWarning.tsx@@ -5,6 +5,7 @@"use client";import { DateTimePicker, Hidden, Submit, ValidatedForm } from "@carbon/form";+import { useAction } from "@carbon/query";import {Button,Modal,@@ -32,7 +33,6 @@ import {import { Trans, useLingui } from "@lingui/react/macro";import { useLocale } from "@react-aria/i18n";import { useEffect, useState } from "react";-import { useFetcher } from "react-router";import { setClockOutValidator } from "~/services/models";import { path } from "~/utils/path";@@ -51,7 +51,16 @@ export function TimeCardWarning({ openClockEntry }: TimeCardWarningProps) {const { t } = useLingui();const { locale } = useLocale();const [showClockWarning, setShowClockWarning] = useState(false);- const fetcher = useFetcher();+ const fetcher = useAction({+ onSettled: (data) => {+ if (data) {+ if ((data as { success?: boolean }).success) {+ toast.success(t`Updated successfully`);+ setShowClockWarning(false);+ }+ }+ }+ });useEffect(() => {if (!openClockEntry) {@@ -80,15 +89,6 @@ export function TimeCardWarning({ openClockEntry }: TimeCardWarningProps) {return () => clearInterval(interval);}, [openClockEntry]);- useEffect(() => {- if (fetcher.data && fetcher.state === "idle") {- if ((fetcher.data as { success?: boolean }).success) {- toast.success(t`Updated successfully`);- setShowClockWarning(false);- }- }- }, [fetcher.data, fetcher.state, t]);-const handleClockAcknowledge = () => {if (openClockEntry) {sessionStorage.setItem(CLOCK_STORAGE_KEY, openClockEntry.id);diff --git a/apps/mes/app/hooks/index.ts b/apps/mes/app/hooks/index.tsindex 2c32e2dc67..57ced180ed 100644--- a/apps/mes/app/hooks/index.ts+++ b/apps/mes/app/hooks/index.ts@@ -5,7 +5,6 @@import { usePrinting } from "@carbon/printing/ui";import {useIdle,- useNanoStore,useOptimisticLocation,useRouteData,useUrlParams@@ -22,7 +21,6 @@ export {useIdle,useImageUpload,useLocationTimeZone,- useNanoStore,useOptimisticLocation,usePrinting,useRealtime,diff --git a/apps/mes/app/hooks/useRealtime.tsx b/apps/mes/app/hooks/useRealtime.tsxindex 8611c32f24..1f00a29fc5 100644--- a/apps/mes/app/hooks/useRealtime.tsx+++ b/apps/mes/app/hooks/useRealtime.tsx@@ -2,51 +2,18 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useRealtimeChannel } from "@carbon/react";-import { useCallback, useRef } from "react";-import { useFetchers, useRevalidator } from "react-router";+import type { RealtimeTable } from "@carbon/database/realtime-tables";+import { useRealtimeRevalidator, useRealtimeTable } from "@carbon/query";import { useUser } from "./useUser";-// Revalidate for a realtime change — except while a fetcher on this page is-// submitting. A submission's own writes echo back over realtime mid-action,-// and React Router drops a fetcher's redirect when a newer navigation started-// after the submit (the page then sits on stale data, or a loader gate-// flashes an error for work that just succeeded). Nothing is lost by skipping:-// the router revalidates after every action, the same reason `revalidate()`-// already no-ops during a navigation submission.-export function useRealtimeRevalidator() {- const revalidator = useRevalidator();- const fetchers = useFetchers();- const submitting = useRef(false);- submitting.current = fetchers.some((f) => f.state === "submitting");+export { useRealtimeRevalidator };- return useCallback(() => {- if (!submitting.current) revalidator.revalidate();- }, [revalidator]);-}--export function useRealtime(table: string, filter?: string) {+/**+ * Reloads the page's data when `table` changes in the user's company. A route+ * declares its tables in `handle.realtime` instead; this is for a component+ * that is not a route. Only an `id=eq.` / `id=in.()` filter narrows it.+ */+export function useRealtime(table: RealtimeTable, filter?: string) {const { company } = useUser();- const revalidate = useRealtimeRevalidator();-- const channel = useRealtimeChannel({- topic: `postgres_changes:${table}`,- dependencies: [company.id, filter],- setup(channel) {- return channel.on(- "postgres_changes",- {- event: "*",- schema: "public",- table: table,- filter: filter ?? `companyId=eq.${company.id}`- },- () => {- revalidate();- }- );- }- });-- return channel;+ return useRealtimeTable({ companyId: company.id, table, filter });}diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsxindex 144e108bbd..214a3accb2 100644--- a/apps/mes/app/root.tsx+++ b/apps/mes/app/root.tsx@@ -16,6 +16,7 @@ import { validator } from "@carbon/form";import { LocaleProvider, resolveLanguage } from "@carbon/locale";import { requestMiddleware } from "@carbon/logger/middleware.server";import { timedMiddleware } from "@carbon/logger/tracing.server";+import { createInvalidationMiddleware } from "@carbon/query/cache";import {OperatingSystemContextProvider,Toaster,@@ -34,6 +35,7 @@ import {import { faviconLinks } from "@carbon/utils/favicon";import { I18nProvider } from "@react-aria/i18n";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { ReactQueryDevtools } from "@tanstack/react-query-devtools";import { Analytics } from "@vercel/analytics/react";import type React from "react";import { useContext, useState } from "react";@@ -59,6 +61,7 @@ import { getMode, setMode } from "~/services/mode.server";import Background from "~/styles/background.css?url";import NProgress from "~/styles/nprogress.css?url";import Tailwind from "~/styles/tailwind.css?url";+import { path } from "~/utils/path";import "@carbon/lib/shims";import { MotionConfig } from "motion/react";import type { Route } from "./+types/root";@@ -71,7 +74,13 @@ export const middleware = timedMiddleware({formBody: formBodyMiddleware,flash: flashMiddleware});-export const clientMiddleware = [flashClientMiddleware];+export const clientMiddleware = [+ flashClientMiddleware,+ createInvalidationMiddleware({+ getCache: () => window.clientCache,+ skipPaths: [path.to.refreshSession]+ })+];export const links: Route.LinksFunction = () => [{ rel: "stylesheet", href: Tailwind },@@ -275,16 +284,22 @@ export default function App() {/* Dark/Light Mode */const mode = useMode();- // Backs hook-based useQuery (the viewer's useOptimizedModel); MES has no- // clientLoader cache convention, so this client exists only for hooks.- const [queryClient] = useState(- () =>- new QueryClient({- defaultOptions: {- queries: { refetchOnWindowFocus: false }- }- })- );+ // One client for hook-based useQuery and for code outside React (the live+ // lists, the invalidation middleware), which reaches it as window.clientCache.+ const [queryClient] = useState(() => {+ if (typeof window !== "undefined" && window.clientCache) {+ return window.clientCache;+ }+ const client = new QueryClient({+ defaultOptions: {+ queries: { refetchOnWindowFocus: false }+ }+ });+ if (typeof window !== "undefined") {+ window.clientCache = client;+ }+ return client;+ });return (<QueryClientProvider client={queryClient}>@@ -300,6 +315,8 @@ export default function App() {env={env}><Outlet />+ {/* Renders nothing outside development; the package strips itself. */}+ <ReactQueryDevtools buttonPosition="bottom-right" /></Document></MotionConfig></TooltipProvider>diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsxindex 4fbcec91d7..6df7486cbd 100644--- a/apps/mes/app/routes/x+/_layout.tsx+++ b/apps/mes/app/routes/x+/_layout.tsx@@ -28,6 +28,8 @@ import { isConsoleModeEnabledForCompany } from "@carbon/ee/console.server";import type { PrintingSettings } from "@carbon/printing";import { getPrinterRoutes } from "@carbon/printing";import { PrintingProvider } from "@carbon/printing/ui";+import { RouteRealtime } from "@carbon/query";+import { setClientCompanyId } from "@carbon/query/cache";import {Button,Heading,@@ -344,6 +346,8 @@ export default function AuthenticatedRoute() {mfaEnrollmentRequired,sessionTimeout} = loaderData;+ // During render, not in an effect: the first child reads it.+ setClientCompanyId(company?.id ?? null, user?.id ?? null);// biome-ignore lint/correctness/useExhaustiveDependencies: runs each time the loader doesuseEffect(() => {shellLoadedAt = Date.now();@@ -505,6 +509,7 @@ export default function AuthenticatedRoute() {}}><RealtimeDataProvider>+ {company?.id && <RouteRealtime companyId={company.id} />}<SidebarProvider defaultOpen={false}><TooltipProvider delayDuration={0}><AppSidebardiff --git a/apps/mes/app/routes/x+/active.tsx b/apps/mes/app/routes/x+/active.tsxindex 791cec0ac3..7ad0549007 100644--- a/apps/mes/app/routes/x+/active.tsx+++ b/apps/mes/app/routes/x+/active.tsx@@ -19,6 +19,11 @@ import { useLoaderData, useParams } from "react-router";import { OperationsList } from "~/components";import { getActiveJobOperationsByEmployee } from "~/services/operations.service";import { makeDurations } from "~/utils/durations";+import type { Handle } from "~/utils/handle";++export const handle: Handle = {+ realtime: ["jobOperation", "productionEvent"]+};export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId, userId } = await requirePermissions(request, {});diff --git a/apps/mes/app/routes/x+/assigned.tsx b/apps/mes/app/routes/x+/assigned.tsxindex d847808ef5..1988b23373 100644--- a/apps/mes/app/routes/x+/assigned.tsx+++ b/apps/mes/app/routes/x+/assigned.tsx@@ -42,6 +42,11 @@ import {getWorkCentersByCompany} from "~/services/operations.service";import { makeDurations } from "~/utils/durations";+import type { Handle } from "~/utils/handle";++export const handle: Handle = {+ realtime: ["jobOperation", "productionEvent"]+};const log = getLogger("mes");diff --git a/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx b/apps/mes/app/routes/x+/dispatch.$dispatchId.tsxindex bc171974c7..e1f34667e1 100644--- a/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx+++ b/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx@@ -21,7 +21,7 @@ import {useDisclosure,VStack} from "@carbon/react";-import { isUnaffectedByNavigation } from "@carbon/utils";+import { groupBy, isUnaffectedByNavigation } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import { useMemo } from "react";import { BsExclamationSquareFill } from "react-icons/bs";@@ -54,8 +54,15 @@ import type {maintenanceSeverity} from "~/services/models";import { useItems } from "~/stores";+import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";+export const handle: Handle = {+ realtime: [+ { table: "maintenanceDispatch", column: "id", param: "dispatchId" }+ ]+};+export const shouldRevalidate: ShouldRevalidateFunction = (args) =>isUnaffectedByNavigation(args, { params: ["dispatchId"] })? false@@ -92,22 +99,23 @@ export async function loader({ request, params }: LoaderFunctionArgs) {replacementParts = parts.data ?? [];}- // Fetch tracked entities for each item- const itemTrackedEntities: Record<- string,- Awaited<- ReturnType<typeof getMaintenanceDispatchItemTrackedEntities>- >["data"]- > = {};- if (items.data) {- for (const item of items.data) {- const trackedEntities = await getMaintenanceDispatchItemTrackedEntities(+ // Tracked entities for every item, in one read+ const trackedEntities = items.data?.length+ ? await getMaintenanceDispatchItemTrackedEntities(client,- item.id- );- itemTrackedEntities[item.id] = trackedEntities.data ?? [];- }- }+ items.data.map((item) => item.id)+ )+ : null;+ const trackedEntitiesByItem = groupBy(+ trackedEntities?.data ?? [],+ (row) => row.maintenanceDispatchItemId+ );+ const itemTrackedEntities = Object.fromEntries(+ (items.data ?? []).map((item) => [+ item.id,+ trackedEntitiesByItem[item.id] ?? []+ ])+ );return {dispatch: dispatch.data,diff --git a/apps/mes/app/routes/x+/inspection.$operationId.tsx b/apps/mes/app/routes/x+/inspection.$operationId.tsxindex cb788fac03..43050efb4b 100644--- a/apps/mes/app/routes/x+/inspection.$operationId.tsx+++ b/apps/mes/app/routes/x+/inspection.$operationId.tsx@@ -35,9 +35,28 @@ import {} from "~/services/quality.service";import type { InspectionSample, OperationWithDetails } from "~/services/types";import { makeDurations } from "~/utils/durations";+import type { Handle } from "~/utils/handle";import { resolveOperationView } from "~/utils/operationView";import { path } from "~/utils/path";+export const handle: Handle = {+ realtime: [+ {+ table: "inspection",+ filter: ({ data }) =>+ data?.inspection?.id ? `id=eq.${data.inspection.id}` : undefined+ },+ {+ table: "inspectionSample",+ filter: ({ data }) =>+ data?.inspection?.id+ ? `inspectionId=eq.${data.inspection.id}`+ : undefined+ },+ { table: "jobOperation", column: "id", param: "operationId" }+ ]+};+const logger = getLogger("mes", "inspection");export async function loader({ request, params }: LoaderFunctionArgs) {diff --git a/apps/mes/app/routes/x+/job.$jobId.tsx b/apps/mes/app/routes/x+/job.$jobId.tsxindex 7f55b6b866..439c085462 100644--- a/apps/mes/app/routes/x+/job.$jobId.tsx+++ b/apps/mes/app/routes/x+/job.$jobId.tsx@@ -15,8 +15,16 @@ import {getJobOperationDependencies,getJobOperations} from "~/services/operations.service";+import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";+export const handle: Handle = {+ realtime: [+ { table: "job", column: "id", param: "jobId" },+ { table: "jobOperation", column: "jobId", param: "jobId" }+ ]+};+const logger = getLogger("mes", "job-dag");export async function loader({ request, params }: LoaderFunctionArgs) {diff --git a/apps/mes/app/routes/x+/jobs.tsx b/apps/mes/app/routes/x+/jobs.tsxindex 12716d78b9..a87b5dc426 100644--- a/apps/mes/app/routes/x+/jobs.tsx+++ b/apps/mes/app/routes/x+/jobs.tsx@@ -31,8 +31,13 @@ import {getOpenJobs,getTrackedEntitiesByJobMakeMethodIds} from "~/services/operations.service";+import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";+export const handle: Handle = {+ realtime: ["job", "jobOperation"]+};+const log = getLogger("mes");export async function loader({ context, request }: LoaderFunctionArgs) {diff --git a/apps/mes/app/routes/x+/maintenance.tsx b/apps/mes/app/routes/x+/maintenance.tsxindex 80f5ae1551..02fc7f69b3 100644--- a/apps/mes/app/routes/x+/maintenance.tsx+++ b/apps/mes/app/routes/x+/maintenance.tsx@@ -41,8 +41,13 @@ import {} from "~/services/maintenance.service";import { maintenanceDispatchPriority } from "~/services/models";import { getWorkCentersByLocation } from "~/services/operations.service";+import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";+export const handle: Handle = {+ realtime: ["maintenanceDispatch"]+};+export async function loader({ context, request }: LoaderFunctionArgs) {const { client, userId } = await requirePermissions(request, {});const locationId = context.get(userContext)?.locationId;diff --git a/apps/mes/app/routes/x+/operation.$operationId.tsx b/apps/mes/app/routes/x+/operation.$operationId.tsxindex 09cae0cacf..21f50aff29 100644--- a/apps/mes/app/routes/x+/operation.$operationId.tsx+++ b/apps/mes/app/routes/x+/operation.$operationId.tsx@@ -41,9 +41,52 @@ type ExpiredEntityPolicy = "Warn" | "Block" | "BlockWithOverride";import { redirect } from "@carbon/utils";import { makeDurations } from "~/utils/durations";+import type { Handle } from "~/utils/handle";import { resolveOperationView } from "~/utils/operationView";import { path } from "~/utils/path";+export const handle: Handle = {+ realtime: [+ // One operation of one job, unless it runs in a batch: a batch shows its+ // members' steps, materials and timers, which belong to other jobs.+ {+ table: "job",+ filter: ({ data }) =>+ data?.batch || !data?.job?.id ? undefined : `id=eq.${data?.job?.id}`+ },+ {+ // Every operation of the job: the one before this one gates it.+ table: "jobOperation",+ filter: ({ data }) =>+ data?.batch || !data?.job?.id ? undefined : `jobId=eq.${data?.job?.id}`+ },+ {+ table: "jobMaterial",+ filter: ({ data }) =>+ data?.batch || !data?.job?.id ? undefined : `jobId=eq.${data?.job?.id}`+ },+ {+ table: "jobOperationStep",+ filter: ({ data, params }) =>+ data?.batch || !data?.job?.id+ ? undefined+ : `operationId=eq.${params.operationId}`+ },+ {+ table: "jobOperationStepRecord",+ filter: ({ data, params }) =>+ data?.batch || !data?.job?.id+ ? undefined+ : `operationId=eq.${params.operationId}`+ },+ {+ table: "pickingListLine",+ filter: ({ data }) =>+ data?.batch || !data?.job?.id ? undefined : `jobId=eq.${data?.job?.id}`+ }+ ]+};+const logger = getLogger("mes", "operation");export async function loader({ request, params }: LoaderFunctionArgs) {diff --git a/apps/mes/app/routes/x+/operations.tsx b/apps/mes/app/routes/x+/operations.tsxindex 629de74c4c..0086af7701 100644--- a/apps/mes/app/routes/x+/operations.tsx+++ b/apps/mes/app/routes/x+/operations.tsx@@ -7,6 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { getLocationTimeZone } from "@carbon/database";import { getLogger } from "@carbon/logger";+import { useChangedRows } from "@carbon/query";import {Button,CarbonPulse,@@ -24,7 +25,6 @@ import {useInterval,useLocalStorage,useMount,- useRealtimeChannel,VStack} from "@carbon/react";import { datetime, redirect } from "@carbon/utils";@@ -59,8 +59,13 @@ import {import { getPeopleOverride } from "~/services/people.server";import { usePeople } from "~/stores";import { makeDurations } from "~/utils/durations";+import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";+export const handle: Handle = {+ realtime: ["job", "jobOperation"]+};+const log = getLogger("mes");type BatchTotals = {@@ -850,84 +855,59 @@ function useProgressByOperation(}}, [productionEventsByOperation]);- useRealtimeChannel({- topic: `kanban-schedule:${companyId}`,- dependencies: [items.length],- setup(channel) {- return channel- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "jobOperation",- filter: `id=in.(${items.map((item) => item.id).join(",")})`- },- (payload) => {- switch (payload.eventType) {- case "UPDATE": {- const { new: updated } = payload;- setItems((prevItems: Item[]) =>- sortItems(- prevItems.map((item: Item) => {- if (item.id === updated.id) {- return {- ...item,- columnId: updated.workCenterId,- priority: updated.priority- };- }- return item;- })- )- );- break;- }- case "DELETE": {- const { old: deleted } = payload;- setItems((prevItems: Item[]) =>- sortItems(- prevItems.filter((item: Item) => item.id !== deleted.id)- )- );- break;- }- }- }- )- .on(- "postgres_changes",- {- event: "*",- schema: "public",- table: "productionEvent",- filter: `companyId=eq.${companyId}`- },- (payload) => {- if (payload.new) {- const event = payload.new as Event;- if (items.some((item) => item.id === event.jobOperationId)) {- setProductionEventsByOperation((prev) => ({- ...prev,- [event.jobOperationId]: [- ...(prev[event.jobOperationId] ?? []),- event- ]- }));- }- } else if (payload.old) {- const event = payload.old as Event;- if (items.some((item) => item.id === event.jobOperationId)) {- setProductionEventsByOperation((prev) => ({- ...prev,- [event.jobOperationId]: (- prev[event.jobOperationId] ?? []- ).filter((e) => e.id !== event.id)- }));- }- }- }+ useChangedRows<{ id: string; workCenterId: string; priority: number }>({+ companyId,+ table: "jobOperation",+ columns: "id, workCenterId, priority",+ onChange: ({ op, ids, rows }) => {+ if (op === "DELETE") {+ setItems((prevItems: Item[]) =>+ sortItems(prevItems.filter((item: Item) => !ids.includes(item.id))));+ return;+ }+ const changed = new Map(rows.map((row) => [row.id, row]));+ setItems((prevItems: Item[]) =>+ sortItems(+ prevItems.map((item: Item) => {+ const updated = changed.get(item.id);+ return updated+ ? {+ ...item,+ columnId: updated.workCenterId,+ priority: updated.priority+ }+ : item;+ })+ )+ );+ }+ });++ useChangedRows<Event>({+ companyId,+ table: "productionEvent",+ onChange: ({ op, ids, rows }) => {+ setProductionEventsByOperation((prev) => {+ if (op === "DELETE") {+ return Object.fromEntries(+ Object.entries(prev).map(([operationId, events]) => [+ operationId,+ events.filter((event) => !ids.includes(event.id))+ ])+ );+ }+ const next = { ...prev };+ for (const row of rows) {+ if (!row.jobOperationId) continue;+ if (!items.some((item) => item.id === row.jobOperationId)) continue;+ const events = next[row.jobOperationId] ?? [];+ next[row.jobOperationId] = events.some((event) => event.id === row.id)+ ? events.map((event) => (event.id === row.id ? row : event))+ : [...events, row];+ }+ return next;+ });}});diff --git a/apps/mes/app/routes/x+/picking.$pickingListId.tsx b/apps/mes/app/routes/x+/picking.$pickingListId.tsxindex 8855a8c5a4..89ca43de69 100644--- a/apps/mes/app/routes/x+/picking.$pickingListId.tsx+++ b/apps/mes/app/routes/x+/picking.$pickingListId.tsx@@ -68,8 +68,20 @@ import { isPickingListLocked } from "~/services/models";import type { UnresolvedPickingListLine } from "~/services/picking.service";import { getPickingListForExecution } from "~/services/picking.service";import { useItems } from "~/stores";+import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";+export const handle: Handle = {+ realtime: [+ { table: "pickingList", column: "id", param: "pickingListId" },+ {+ table: "pickingListLine",+ column: "pickingListId",+ param: "pickingListId"+ }+ ]+};+export const shouldRevalidate: ShouldRevalidateFunction = (args) =>isUnaffectedByNavigation(args, { params: ["pickingListId"] })? falsediff --git a/apps/mes/app/routes/x+/picking._index.tsx b/apps/mes/app/routes/x+/picking._index.tsxindex 46b8cf804a..6d1ed711bb 100644--- a/apps/mes/app/routes/x+/picking._index.tsx+++ b/apps/mes/app/routes/x+/picking._index.tsx@@ -21,8 +21,13 @@ import { DateTime } from "~/components";import { PickingListStatus } from "~/components/PickingListStatus";import { userContext } from "~/context";import { getAssignedPickingLists } from "~/services/picking.service";+import type { Handle } from "~/utils/handle";import { path } from "~/utils/path";+export const handle: Handle = {+ realtime: ["pickingList"]+};+export async function loader({ context, request }: LoaderFunctionArgs) {const { client, userId } = await requirePermissions(request, {});const effectiveUserId = context.get(userContext)?.effectiveUserId ?? userId;diff --git a/apps/mes/app/routes/x+/recent.tsx b/apps/mes/app/routes/x+/recent.tsxindex ebe2987cbd..c2ce12f61b 100644--- a/apps/mes/app/routes/x+/recent.tsx+++ b/apps/mes/app/routes/x+/recent.tsx@@ -19,6 +19,11 @@ import { useLoaderData, useParams } from "react-router";import { OperationsList } from "~/components";import { getRecentJobOperationsByEmployee } from "~/services/operations.service";import { makeDurations } from "~/utils/durations";+import type { Handle } from "~/utils/handle";++export const handle: Handle = {+ realtime: ["jobOperation", "productionEvent"]+};export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId, userId } = await requirePermissions(request, {});diff --git a/apps/mes/app/routes/x+/timecard.tsx b/apps/mes/app/routes/x+/timecard.tsxindex 90bc55ab02..a8628220f4 100644--- a/apps/mes/app/routes/x+/timecard.tsx+++ b/apps/mes/app/routes/x+/timecard.tsx@@ -4,6 +4,7 @@import { requirePermissions } from "@carbon/auth/auth.server";import { getCompanyTimeZone } from "@carbon/database";+import { useAction } from "@carbon/query";import {Badge,Button,@@ -47,7 +48,7 @@ import {LuTrash} from "react-icons/lu";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";-import { Link, useFetcher, useLoaderData } from "react-router";+import { Link, useLoaderData } from "react-router";import { DateTime } from "~/components";import {clockIn,@@ -185,7 +186,13 @@ export async function action({ request }: ActionFunctionArgs) {export default function MESTimecardPage() {const { entries, openEntry, weekOffset, weekStart, weekEnd } =useLoaderData<typeof loader>();- const fetcher = useFetcher<typeof action>();+ const fetcher = useAction<typeof action>({+ onSettled: (data) => {+ if (data) {+ setEditingId(null);+ }+ }+ });const [editingId, setEditingId] = useState<string | null>(null);const [editClockIn, setEditClockIn] = useState("");const [editClockOut, setEditClockOut] = useState("");@@ -204,12 +211,6 @@ export default function MESTimecardPage() {return () => clearInterval(interval);}, []);- useEffect(() => {- if (fetcher.data && fetcher.state === "idle") {- setEditingId(null);- }- }, [fetcher.data, fetcher.state]);-function startEdit(entry: {id: string;clockIn: string;diff --git a/apps/mes/app/services/location.server.ts b/apps/mes/app/services/location.server.tsindex f3e9c5cd81..7a32c90954 100644--- a/apps/mes/app/services/location.server.ts+++ b/apps/mes/app/services/location.server.ts@@ -51,7 +51,9 @@ export async function getLocation(.eq("id", location).eq("companyId", companyId).maybeSingle();- if (owned.error) {+ // A request the browser gave up on (it navigated, or a newer reload+ // replaced this one) aborts its reads: that is not a failure to report.+ if (owned.error && !request.signal.aborted) {logger.error("Failed to verify the location cookie", {companyId,locationId: location,diff --git a/apps/mes/app/services/maintenance.service.ts b/apps/mes/app/services/maintenance.service.tsindex 35eb11ff4f..5f4733c173 100644--- a/apps/mes/app/services/maintenance.service.ts+++ b/apps/mes/app/services/maintenance.service.ts@@ -316,7 +316,7 @@ export async function deleteMaintenanceDispatchItem(export async function getMaintenanceDispatchItemTrackedEntities(client: SupabaseClient<Database>,- maintenanceDispatchItemId: string+ maintenanceDispatchItemIds: string[]) {return client.from("maintenanceDispatchItemTrackedEntity")@@ -326,5 +326,5 @@ export async function getMaintenanceDispatchItemTrackedEntities(trackedEntity:trackedEntityId (id, quantity, status, readableId:sourceDocumentReadableId)`)- .eq("maintenanceDispatchItemId", maintenanceDispatchItemId);+ .in("maintenanceDispatchItemId", maintenanceDispatchItemIds);}diff --git a/apps/mes/app/stores/items.ts b/apps/mes/app/stores/items.tsindex c6585ebe69..cdda4ad66a 100644--- a/apps/mes/app/stores/items.ts+++ b/apps/mes/app/stores/items.ts@@ -3,9 +3,10 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import type { Database } from "@carbon/database";-import { useStore as useValue } from "@nanostores/react";-import { atom, computed } from "nanostores";-import { useNanoStore } from "~/hooks";+import { fetchAllFromTable } from "@carbon/database";+import { type LiveList, useLiveList } from "@carbon/query";+import { useMemo } from "react";+import { useUser } from "~/hooks";import type { ListItem } from "~/types";export type Item = ListItem & {@@ -17,26 +18,72 @@ export type Item = ListItem & {thumbnailPath: string | null;};-const $itemsStore = atom<Item[]>([]);+// The one place the item list's columns are written. The thumbnail falls back+// to the model's when the item has none of its own.+const ITEM_COLUMNS =+ "id, readableIdWithRevision, name, type, replenishmentSystem, itemTrackingType, active, thumbnailPath, modelUpload:modelUploadId(thumbnailPath)";-const $partsStore = computed($itemsStore, (item) =>- item.filter((i) => i.type === "Part")-);+type ItemRow = Item & { modelUpload?: { thumbnailPath: string | null } | null };-const $toolsStore = computed($itemsStore, (item) =>- item.filter((i) => i.type === "Tool")-);+const toItem = ({ modelUpload, ...item }: ItemRow): Item => ({+ ...item,+ thumbnailPath: item.thumbnailPath ?? modelUpload?.thumbnailPath ?? null+});-const $serivceStore = computed($itemsStore, (item) =>- item.filter((i) => i.type === "Service")-);+export const itemsList: LiveList<Item> = {+ name: "mesItems",+ table: "item",+ async fetchAll(carbon, companyId) {+ const items = await fetchAllFromTable<ItemRow>(+ carbon,+ "item",+ ITEM_COLUMNS,+ (query) =>+ query+ .eq("companyId", companyId)+ .order("readableId", { ascending: true })+ .order("revision", { ascending: false })+ );+ if (items.error) throw new Error("Failed to fetch items");+ return (items.data ?? []).map(toItem);+ },+ async fetchByIds(carbon, companyId, ids) {+ const items = await carbon+ .from("item")+ .select(ITEM_COLUMNS)+ .eq("companyId", companyId)+ .in("id", ids);+ if (items.error) throw new Error("Failed to fetch items");+ return ((items.data ?? []) as unknown as ItemRow[]).map(toItem);+ },+ // A model's thumbnail is rendered after upload, on its own row: re-read the+ // items that show it.+ related: [+ {+ table: "modelUpload",+ async fetch(carbon, companyId, ids) {+ const items = await carbon+ .from("item")+ .select(ITEM_COLUMNS)+ .eq("companyId", companyId)+ .in("modelUploadId", ids);+ if (items.error) throw new Error("Failed to fetch items");+ return ((items.data ?? []) as unknown as ItemRow[]).map(toItem);+ }+ }+ ],+ sort: (a, b) =>+ a.readableIdWithRevision.localeCompare(b.readableIdWithRevision)+};++export const useItems = () => useLiveList(itemsList, useUser().company.id);-const $materialsStore = computed($itemsStore, (item) =>- item.filter((i) => i.type === "Material")-);+const useItemsOfType = (type: Item["type"]) => {+ const [items] = useItems();+ return useMemo(() => items.filter((i) => i.type === type), [items, type]);+};-export const useItems = () => useNanoStore<Item[]>($itemsStore, "items");-export const useParts = () => useValue($partsStore);-export const useTools = () => useValue($toolsStore);-export const useServices = () => useValue($serivceStore);-export const useMaterials = () => useValue($materialsStore);+export const useParts = () => useItemsOfType("Part");+export const useTools = () => useItemsOfType("Tool");+export const useServices = () => useItemsOfType("Service");+export const useMaterials = () => useItemsOfType("Material");diff --git a/apps/mes/app/stores/people.ts b/apps/mes/app/stores/people.tsindex 6c03308da7..c68bc7d497 100644--- a/apps/mes/app/stores/people.ts+++ b/apps/mes/app/stores/people.ts@@ -2,9 +2,41 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { atom } from "nanostores";-import { useNanoStore } from "~/hooks";+import { fetchAllFromTable } from "@carbon/database";+import { type LiveList, useLiveList } from "@carbon/query";+import { useUser } from "~/hooks";import type { ListItem } from "~/types";-const $peopleStore = atom<(ListItem & { avatarUrl: string | null })[]>([]);-export const usePeople = () => useNanoStore($peopleStore, "people");+export type Person = ListItem & { avatarUrl: string | null };++// Read from the `employees` view (user + employee + job). An employee's id is+// their user id, so a changed `employee` row — or a renamed `user`, which the+// change log records under `employee` — is re-read from the view by that id.+const COLUMNS = "id, name, email, avatarUrl, active";++export const peopleList: LiveList<Person> = {+ name: "people",+ table: "employee",+ async fetchAll(carbon, companyId) {+ const rows = await fetchAllFromTable<Person>(+ carbon,+ "employees",+ COLUMNS,+ (query) => query.eq("companyId", companyId).order("name")+ );+ if (rows.error) throw new Error("Failed to fetch people");+ return rows.data ?? [];+ },+ async fetchByIds(carbon, companyId, ids) {+ const rows = await carbon+ .from("employees")+ .select(COLUMNS)+ .eq("companyId", companyId)+ .in("id", ids);+ if (rows.error) throw new Error("Failed to fetch people");+ return (rows.data ?? []) as Person[];+ },+ sort: (a, b) => a.name.localeCompare(b.name)+};++export const usePeople = () => useLiveList(peopleList, useUser().company.id);diff --git a/apps/mes/app/types/global.d.ts b/apps/mes/app/types/global.d.tsnew file mode 100644index 0000000000..47ac1b944e--- /dev/null+++ b/apps/mes/app/types/global.d.ts@@ -0,0 +1,13 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { QueryClient } from "@tanstack/react-query";++declare global {+ interface Window {+ clientCache: QueryClient;+ }+}++export {};diff --git a/apps/mes/app/utils/handle.ts b/apps/mes/app/utils/handle.tsindex 9b37ba25dd..e87fd5dd63 100644--- a/apps/mes/app/utils/handle.ts+++ b/apps/mes/app/utils/handle.ts@@ -2,8 +2,12 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import type { RouteRealtimeTable } from "@carbon/database/realtime-tables";export type Handle = {breadcrumb?: any;to?: string;module?: string;+ // The tables this route shows. The shell (`RouteRealtime`) reloads the page+ // when one of them changes; each must be in REALTIME_TABLES.+ realtime?: RouteRealtimeTable[];};diff --git a/apps/mes/package.json b/apps/mes/package.jsonindex c7c293be2c..25ea0e3e66 100644--- a/apps/mes/package.json+++ b/apps/mes/package.json@@ -16,6 +16,7 @@"@carbon/server-functions": "workspace:*","@carbon/notifications": "workspace:*","@carbon/printing": "workspace:*",+ "@carbon/query": "workspace:*","@carbon/react": "workspace:*","@carbon/stripe": "workspace:*","@carbon/utils": "workspace:*",@@ -30,7 +31,6 @@"@lingui/core": "catalog:","@lingui/react": "catalog:","@lingui/vite-plugin": "catalog:",- "@nanostores/react": "catalog:","@react-aria/i18n": "catalog:","@react-pdf/renderer": "catalog:","@react-router/dev": "catalog:",@@ -42,7 +42,7 @@"@supabase/supabase-js": "catalog:","@tailwindcss/typography": "catalog:","@tailwindcss/vite": "catalog:",- "@tanstack/react-query": "5.97.0",+ "@tanstack/react-query": "catalog:","@tiptap/core": "catalog:","@tiptap/extension-color": "catalog:","@tiptap/extension-list-item": "catalog:",@@ -68,7 +68,6 @@"kysely": "catalog:","localforage": "1.10.0","nanoid": "catalog:",- "nanostores": "catalog:","non.geist": "catalog:","pdfjs-dist": "5.4.296","posthog-js": "catalog:",@@ -92,6 +91,7 @@"zod-form-data": "catalog:"},"devDependencies": {+ "@tanstack/react-query-devtools": "catalog:","@lingui/conf": "catalog:","@react-aria/optimize-locales-plugin": "catalog:","@carbon/config": "workspace:*",diff --git a/packages/checks/AGENTS.md b/packages/checks/AGENTS.mdindex 8e03bdf7cc..8b75b743ff 100644--- a/packages/checks/AGENTS.md+++ b/packages/checks/AGENTS.md@@ -17,7 +17,7 @@ Conformance checking, clobber detection, invariant queries, and module structure## Never-- Ignore clobber warnings — they indicate a view/function/trigger is redefined on both your branch and main since the merge-base; rebase first+- Ignore clobber warnings — they indicate a view or function is redefined on both your branch and main since the merge-base; rebase first- Suppress violations by removing checks — add to the baseline if grandfathering is appropriate## Validation Commands@@ -36,6 +36,7 @@ pnpm --filter @carbon/checks baseline # regenerate baseline (careful!)- **Forwarded headers** (own source, `REQUEST_HANDLING_ROOTS`: every app + auth, server-functions, ee, jobs, lib, utils, edge functions): `noRawForwardedHeaders` fails a raw read of `X-Forwarded-For/-Host/-Proto` or `X-Real-IP` outside `packages/utils/src/headers.ts` — use `getClientIp` / `getRequestProtocol` / `getRequestHost` / `getRequestOrigin`. Hand-rolled reads keyed login rate limits and ITAR audit records on the forgeable first `X-Forwarded-For` entry. No baseline entries- **Error log messages** (same source as forwarded headers, `REQUEST_HANDLING_ROOTS`): `noInterpolatedErrorLog` fails `logger.error(`…${value}`)` / `.fatal` — the message is exported as a span attribute and is what errors group by, so values are named (`"Failed to upload {fileName}", { fileName }`). One baseline entry: the `packages/auth/src/utils/result.ts` pass-through, whose message is its caller's- **Numeric-precision checks** (in `TS_CHECKS`, over `sources/typescript.ts`): `noRawRounding` flags `Math.round/ceil/floor` and `.toFixed` on value-bearing numbers (use `round`/`scrapAllowance`/`applyRate`/`deriveRate` from `@carbon/utils`); `noInlineFractionDigits` flags `minimum`/`maximumFractionDigits` at a call site (pick a named kind from `@carbon/utils` `format.ts`, and `INPUT_FORMAT.*` for anything editable); `noUnroundedTrackedQuantity` flags inline unrounded arithmetic inside a `.updateTable("trackedEntity")` statement's `quantity:` set, and a raw `===`/`!==`/`<` compare against a `*[Ee]ntity*.quantity` read (use `round`/`settleQuantity` at the write, `isFullDraw` at a split gate — see `.claude/rules/traceability-model.md`). It is scoped to what one file can prove: a `quantity:` set from an already-rounded variable is unflaggable either way, and a compare of two locals is presumed rounded where they were defined. It has **no baseline entries** — the whole tree was fixed in the pass that added it, so any finding is new. `sources/typescript.ts` walks `apps/erp/app/{components,hooks,modules,routes}`, `apps/mes/app`, `packages/database/supabase/functions`, `packages/database/src`, `packages/{server-functions,ee,jobs}/src`, `packages/documents/src/{pdf,utils}` and the shared packages `packages/{utils,files,form,react,printing}/src` — tests (`*.test.ts(x)`, `*.spec.ts(x)`) and `*-test-fixture.ts` live-database fixtures excluded; a fixture is test support code, so it is held to the tests' rules, not shipped code's. The shared packages matter: `@carbon/utils` is where the standard's own helpers live, and `form`/`react` own the number inputs whose `formatOptions` are part of the storage round-trip. See `.claude/rules/numeric-precision.md`+- **Realtime** (in `TS_CHECKS`): `noPostgresChanges` fails a `postgres_changes` subscription — the `supabase_realtime` publication is empty, so it would never fire. Use a broadcast topic through `@carbon/query` (`.claude/rules/realtime-system.md`).- **Missing audit columns** (built in `collectFindings`, not `TS_CHECKS`): `noMissingAuditColumn(columns)` fails a write that names `createdBy`/`updatedBy` on a relation that has no such column — PostgREST rejects the whole statement (`PGRST204 Could not find the 'createdBy' column of '<table>'`) and TypeScript does not flag it, because supabase-js widens the insert/upsert argument enough for the excess property to survive. That is how the `customerPartToItem` upsert in `sales-rfq.$rfqId.map-lines.ts` shipped with an unchecked result, so every RFQ-line → customer-part mapping silently failed. Roughly a third of Carbon's tables have no audit columns (favourites, link tables, the lean material lookups, `companySettings`) while golden rule 3 says to include them, so it is an easy assumption to carry into the wrong table. It takes the column map as an ARGUMENT — `loadDbTableColumns(root)` (`sources/db-columns.ts`) reads the generated `packages/database/src/types.ts` `Row:` blocks, so the I/O stays in `sources/` and `scan` stays pure, the same shape as `noAuthzDdlInMigrations(loadManagedFunctions(root))`. Scope is the LITERAL argument of the write (`.from`/`insertInto`/`updateTable` + `.insert`/`.upsert`/`.update`/`.values`/`.set`); a payload object spread into the row is invisible here, and for the MCP/API layer that same generated schema drives `withoutAbsentAuditColumns` in `scripts/lib/service-metadata.ts`. No baseline entries — the one hit was fixed when it was added- **Tenant-scoped Kysely writes** (in `TS_CHECKS`): `noUnscopedKyselyWrite` fails any `.updateTable(`/`.deleteFrom(` under `apps/erp/app/{modules,routes}`, `apps/mes/app`, `packages/jobs/src` or `packages/server-functions/src` whose statement (up to `.execute…(`/`.compile(`/`;`/`,` at depth 0, comments blanked) has no `.where("companyId", …)` / `.where("alias.companyId", …)`. Kysely is the superuser connection, and the public API hands a service's `db` param that same client, so the statement's own predicate is the only tenant boundary — ten drag-sort services (`updateQuoteLineOrder` and friends) were a reported cross-tenant write because they keyed on `id` alone. `company` is exempt (its `id` is the tenant); a `companyId` in `.set()` does not count; a link table with no `companyId` column passes by scoping through its parent in a subquery. `packages/ee` is out of scope (see the file header), and so are writes made through the `@carbon/database/rows` helpers (`updateRows` / `deleteRows`): the check only reads Kysely's own builders. One baseline entry: the `companyGroup` delete in `packages/jobs/.../scheduled/purge-company.ts` (a group has no `companyId` column; its `id` is the tenant-group key). Every other hit was fixed when it was added- **Unguarded submit buttons** (in `TS_CHECKS`, `.tsx` only): `noUnguardedSubmit` fails a `<Button>`/`<button>`/`<IconButton>` carrying `type="submit"` whose own opening tag names no in-flight signal (`isLoading`, `isSubmitting`, `isPending`, `isSaving`, `useIsSubmitting`, or a `*fetcher|navigation|transition*.state` read). A live submit button posts again on every click and each POST runs to completion server-side — `fetcher.submit` aborts the previous BROWSER request, but no route action reads `request.signal` — which is how one quote finalize emailed the customer the same PDF three times. It parses the real opening tag (brace- and quote-aware), so a guard written after `type="submit"` still counts and a `>` inside `{a > b}` does not end the tag early. **The presence of `isDisabled` is deliberately not enough**: the incident's button was `isDisabled={loading}` where `loading` was the modal's data-fetch flag, so a check that accepted any `isDisabled` would have passed the exact line it exists to catch; word boundaries matter too (`loading` must not satisfy `isLoading`). Buttons inside a `<ValidatedForm>` are skipped — `ValidatedForm.handleSubmit` drops a re-entrant submit, so a second click cannot produce a second POST however the button is written. `packages/form/src/components/Submit.tsx` is excluded; it IS the guard. The check cannot do dataflow, so a guard held in a differently-named local (`disabled={busy}`) is baselined rather than rewritten. 32 baseline entries, all reviewed: logout/company-switch/theme/console-toggle (idempotent), delete and rule-unassign (a second delete is a no-op), the two chat composers (guarded by a `flushSync` clear plus an empty-message return), and `ConfiguratorForm` (its submit is an `onSubmit` callback — the in-flight state lives at the caller)diff --git a/packages/checks/README.md b/packages/checks/README.mdindex 9373f02a98..b1e3158f04 100644--- a/packages/checks/README.md+++ b/packages/checks/README.md@@ -21,12 +21,13 @@ append-only — new migration files, and new check types in old files, are alway## Clobber check-Detects when the same DB object (view, function, or event-trigger) is redefined+Detects when the same DB object (view or function) is redefinedon **both** the current branch and `main` since their merge-base — a "concurrentredefinition" that will silently overwrite whichever side merges last.-- **What counts as a clobber:** `CREATE OR REPLACE VIEW`, `CREATE OR REPLACE FUNCTION`,- or `attach_event_trigger(...)` targeting the same object name on both sides.+- **What counts as a clobber:** `CREATE OR REPLACE VIEW` or `CREATE OR REPLACE FUNCTION`+ targeting the same object name on both sides. Event triggers are not included:+ they live in the attachments manifest, not in migrations.- **Run at PR time:** `pnpm --filter @carbon/checks clobbers`(needs `origin/main` fetched — run `git fetch origin main` first if needed).- **Grow coverage:** add a `{ kind, re }` row to `OBJECT_PATTERNS` indiff --git a/packages/checks/src/clobber.test.ts b/packages/checks/src/clobber.test.tsindex 4debe26557..c05000f10c 100644--- a/packages/checks/src/clobber.test.ts+++ b/packages/checks/src/clobber.test.ts@@ -6,14 +6,13 @@ import { describe, expect, it } from "vitest";import { findClobbers, objectRefs } from "./clobber";describe("objectRefs", () => {- it("extracts views, functions, and event-trigger redefinitions", () => {+ it("extracts view and function redefinitions", () => {const sql = `CREATE OR REPLACE VIEW "salesOrders" AS SELECT * FROM x;CREATE OR REPLACE FUNCTION get_total() RETURNS int AS $$ $$;- SELECT attach_event_trigger('job', ARRAY[]::text[]);`;expect(objectRefs(sql)).toEqual(- new Set(["view:salesOrders", "function:get_total", "event-trigger:job"])+ new Set(["view:salesOrders", "function:get_total"]));});diff --git a/packages/checks/src/clobber.ts b/packages/checks/src/clobber.tsindex ecd57b0371..5f3771b6c1 100644--- a/packages/checks/src/clobber.ts+++ b/packages/checks/src/clobber.ts@@ -29,11 +29,10 @@ const OBJECT_PATTERNS: { kind: string; re: RegExp }[] = [String.raw`create\s+or\s+replace\s+function\s+${QUALIFIER}"?([a-zA-Z0-9_]+)"?`,"gi")- },- {- kind: "event-trigger",- re: /attach_event_trigger\(\s*'([a-zA-Z0-9_]+)'/gi}+ // Event triggers are not listed: a migration may no longer attach one+ // (`no-authz-ddl-in-migrations`). They are declared in the attachments+ // manifest, where two branches changing one table is an ordinary merge.];/** The set of `kind:name` objects redefined by a SQL string. */diff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.jsonindex e2338fe335..94a6150e2d 100644--- a/packages/checks/src/conformance/baseline.json+++ b/packages/checks/src/conformance/baseline.json@@ -314,6 +314,7 @@"no-numeric-precision::20260604120000_invoice-totals-computed-in-views.sql::NUMERIC(10,2)","no-numeric-precision::20260604120000_invoice-totals-computed-in-views.sql::numeric(10,2)","no-numeric-precision::20260618171234_material-supersession.sql::NUMERIC(10,2)",+ "no-numeric-precision::20261004194527_event-attachments.sql::NUMERIC(10, 2)","no-raw-rounding::apps/erp/app/components/CadModel.tsx::Math.round(artifacts.optimizedSize / 1024)","no-raw-rounding::apps/erp/app/components/CadModel.tsx::{convertKbToString(Math.ceil(file.size / 1024))}","no-raw-rounding::apps/erp/app/components/CadModel.tsx::{convertKbToString(Math.round(artifacts.size / 1024))}",@@ -608,7 +609,6 @@"no-unguarded-submit::apps/mes/app/components/JobOperation/components/Chat.tsx::<Button className=\"h-10\" aria-label=\"Send\" type=\"submit\" leftIcon={<LuArrowUp />} >","no-unguarded-submit::apps/mes/app/components/SessionLockOverlay.tsx::<Button type=\"submit\" variant=\"link\" size=\"sm\" className=\"text-muted-foreground\" >","no-unguarded-submit::apps/mes/app/components/UserNav.tsx::<button ref={consoleSubmitRef} className=\"sr-only\" type=\"submit\" />",- "no-unguarded-submit::apps/mes/app/components/UserNav.tsx::<button ref={modeSubmitRef} className=\"sr-only\" type=\"submit\" />","no-unguarded-submit::apps/mes/app/components/UserNav.tsx::<button type=\"submit\" className=\"w-full flex items-center\">","no-unguarded-submit::apps/mes/app/routes/_public+/mfa.tsx::<Button type=\"submit\" variant=\"link\" size=\"sm\">","no-unguarded-submit::apps/mes/app/routes/_public+/unlock.tsx::<Button type=\"submit\" variant=\"link\" size=\"sm\">",diff --git a/packages/checks/src/conformance/no-authz-ddl-in-migrations.test.ts b/packages/checks/src/conformance/no-authz-ddl-in-migrations.test.tsindex 321a724200..f733bdd22d 100644--- a/packages/checks/src/conformance/no-authz-ddl-in-migrations.test.ts+++ b/packages/checks/src/conformance/no-authz-ddl-in-migrations.test.ts@@ -52,6 +52,19 @@ CREATE POLICY "x" ON "storage"."objects" FOR INSERT WITH CHECK (true);`;expect(check.scan(NEW, sql)).toEqual([]);});+ it("flags a policy on realtime.messages (broadcast authorization is in the manifest)", () => {+ const sql = `CREATE POLICY "company topic" ON realtime.messages FOR SELECT USING (true);`;+ expect(check.scan(NEW, sql)).toHaveLength(1);+ });++ it("flags a call that attaches event triggers (they are declared in attachments.ts)", () => {+ const sql = `SELECT attach_event_trigger('widget', ARRAY['sync_widget']::TEXT[]);+SELECT attach_statement_handler('widget', ARRAY['broadcast_table_changes']);+SELECT set_event_triggers('widget');`;+ expect(check.scan("20261101120000_widget.sql", sql)).toHaveLength(3);+ expect(check.scan("20261004194526_before.sql", sql)).toEqual([]);+ });+it("allows DROP POLICY (needed before dropping a column a policy uses)", () => {expect(check.scan(NEW, `DROP POLICY "SELECT" ON "public"."widget";`)diff --git a/packages/checks/src/conformance/no-authz-ddl-in-migrations.ts b/packages/checks/src/conformance/no-authz-ddl-in-migrations.tsindex e1d76c0795..ec86716ffe 100644--- a/packages/checks/src/conformance/no-authz-ddl-in-migrations.ts+++ b/packages/checks/src/conformance/no-authz-ddl-in-migrations.ts@@ -23,15 +23,31 @@ const SINCE = "20260927000000";/** The migration that took over the event-system functions. */const EVENT_SYSTEM_SINCE = "20261002114954";+/**+ * The migration that took over the table handlers (interceptors and statement+ * handlers) and the event triggers that attach them.+ */+const ATTACHMENTS_SINCE = "20261004194527";+/** The directories of managed function files, and the migration each set is checked from. */export const MANAGED_FUNCTION_SETS = [{ dir: "packages/database/src/authz/helpers", since: SINCE },{dir: "packages/database/src/event-system/functions",since: EVENT_SYSTEM_SINCE+ },+ {+ dir: "packages/database/src/event-system/handlers",+ since: ATTACHMENTS_SINCE}];+// Each of these replaces a table's whole list of handlers, so a call that+// leaves one out detaches it. The lists live in one place instead:+// packages/database/src/event-system/attachments.ts.+const ATTACH_CALL =+ /\b(attach_event_trigger|attach_statement_handler|set_event_triggers)\s*\(/gi;+/** `file` is `<name>.sql` for public, `<schema>.<name>.sql` otherwise. */export type ManagedFunction = {schema: string;@@ -54,7 +70,9 @@ export const GENERATED_AUTHZ_MIGRATION =// Group 2 is the schema when the statement names one, group 3 the function.const NAME = String.raw`(?:"?(\w+)"?\s*\.\s*)?"?(\w+)"?`;// The target may be on a later line; group 2 is its schema, when it names one. The manifest-// owns public tables only, so storage.objects (bucket) policies stay in migrations.+// owns public tables and realtime.messages (broadcast authorization); storage.objects+// (bucket) policies stay in migrations.+const MANIFEST_SCHEMAS = new Set(["public", "realtime"]);const POLICY_DDL =/\b(?:CREATE|ALTER)\s+POLICY\s+(?:"[^"]*"|\S+)\s+ON\s+(?:"?(\w+)"?\s*\.\s*)?"?\w+"?/gi;const FUNCTION_DDL = new RegExp(@@ -73,7 +91,7 @@ export const noAuthzDdlInMigrations = (): ConformanceCheck => ({id: "no-authz-ddl-in-migrations",description:- "Policies, RLS helpers and event-system functions are authored as files, not migrations.",+ "Policies, RLS helpers, event-system functions and event triggers are authored as files, not migrations.",provenance: {deprecates: "CREATE/ALTER POLICY and managed function DDL in migrations",replacedBy:@@ -96,7 +114,7 @@ export const noAuthzDdlInMigrations = (const line = (index: number) => sql.slice(0, index).split("\n").length;const violations: Violation[] = [];for (const m of sql.matchAll(POLICY_DDL)) {- if ((m[1] ?? "public").toLowerCase() !== "public") continue;+ if (!MANIFEST_SCHEMAS.has((m[1] ?? "public").toLowerCase())) continue;violations.push({file,line: line(m.index),@@ -105,6 +123,17 @@ export const noAuthzDdlInMigrations = ("Author policies in packages/database/src/authz/manifest.ts, then run `pnpm --filter @carbon/database authz migration <name>`."});}+ if (timestamp >= ATTACHMENTS_SINCE) {+ for (const m of sql.matchAll(ATTACH_CALL)) {+ violations.push({+ file,+ line: line(m.index),+ snippet: m[0],+ message:+ "Declare event triggers in packages/database/src/event-system/attachments.ts, then run `pnpm --filter @carbon/database authz migration <name>`."+ });+ }+ }for (const m of sql.matchAll(FUNCTION_DDL)) {const fn = managed.get(`${m[2] ?? "public"}.${m[3]}`.toLowerCase());if (!fn || timestamp < fn.since) continue;diff --git a/packages/checks/src/conformance/no-postgres-changes.test.ts b/packages/checks/src/conformance/no-postgres-changes.test.tsnew file mode 100644index 0000000000..2748135063--- /dev/null+++ b/packages/checks/src/conformance/no-postgres-changes.test.ts@@ -0,0 +1,31 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { noPostgresChanges } from "./no-postgres-changes";++const scan = (contents: string) =>+ noPostgresChanges.scan("apps/erp/app/hooks/useThing.tsx", contents);++describe("noPostgresChanges", () => {+ it("flags a postgres_changes subscription, at its line", () => {+ const violations = scan(+ `channel.on(\n "postgres_changes",\n { event: "*", schema: "public", table: "job" },\n refresh\n);`+ );+ expect(violations).toHaveLength(1);+ expect(violations[0]!.line).toBe(2);+ });++ it("accepts a broadcast subscription", () => {+ expect(+ scan(`channel.on("broadcast", { event: "*" }, ({ payload }) => {});`)+ ).toEqual([]);+ });++ it("ignores the words in a comment or prose", () => {+ expect(scan(`// this used to be a postgres_changes subscription`)).toEqual(+ []+ );+ });+});diff --git a/packages/checks/src/conformance/no-postgres-changes.ts b/packages/checks/src/conformance/no-postgres-changes.tsnew file mode 100644index 0000000000..6db440f3c4--- /dev/null+++ b/packages/checks/src/conformance/no-postgres-changes.ts@@ -0,0 +1,41 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { ConformanceCheck, Violation } from "../check";++// Realtime runs on private broadcast topics (@carbon/query). The+// `supabase_realtime` publication is empty, so a `postgres_changes`+// subscription is accepted, delivers nothing, and reports no error — the ERP+// job page sat on two such subscriptions and never showed an operation+// finished on the shop floor. A table name that has no broadcast handler does+// not compile (`RealtimeTable` is derived from the attachments manifest), so+// this string is the only way left to write a subscription that stays silent.+const POSTGRES_CHANGES = /["'`]postgres_changes["'`]/g;++export const noPostgresChanges: ConformanceCheck = {+ id: "no-postgres-changes",+ description:+ "Realtime subscriptions use broadcast topics, never postgres_changes",+ provenance: {+ deprecates:+ 'channel.on("postgres_changes", …) — nothing is published for it to deliver',+ replacedBy:+ "handle.realtime on the route, or useRealtime / useChangedRows / useTableChanges (@carbon/query)",+ since: "2026-10-05"+ },+ scan(file: string, contents: string): Violation[] {+ const violations: Violation[] = [];+ for (const match of contents.matchAll(POSTGRES_CHANGES)) {+ const line = contents.slice(0, match.index).split("\n").length;+ violations.push({+ file,+ line,+ snippet: contents.split("\n")[line - 1]?.trim() ?? "",+ message:+ "Declare the table in the route's `handle.realtime`, or use `useRealtime` / `useChangedRows` from @carbon/query. A table needs a broadcast handler in packages/database/src/event-system/attachments.ts."+ });+ }+ return violations;+ }+};diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.tsindex 51751d15b0..0c476c676d 100644--- a/packages/checks/src/run.ts+++ b/packages/checks/src/run.ts@@ -36,6 +36,7 @@ import { noLocalTimezone } from "./conformance/no-local-timezone";import { noMissingAuditColumn } from "./conformance/no-missing-audit-column";import { noNoopOpenChange } from "./conformance/no-noop-open-change";import { noNumericPrecision } from "./conformance/no-numeric-precision";+import { noPostgresChanges } from "./conformance/no-postgres-changes";import { noRawForwardedHeaders } from "./conformance/no-raw-forwarded-headers";import { noRawRedirect } from "./conformance/no-raw-redirect";import { noRawRounding } from "./conformance/no-raw-rounding";@@ -86,7 +87,8 @@ export const TS_CHECKS: ConformanceCheck[] = [noIntegrationIdBranching,noUnscopedKyselyWrite,noUnguardedSubmit,- noNoopOpenChange+ noNoopOpenChange,+ noPostgresChanges];/** Checks that run once per edge function, over all of its .ts files. */diff --git a/packages/checks/src/sources/typescript.ts b/packages/checks/src/sources/typescript.tsindex c141aa5083..e748b5ba48 100644--- a/packages/checks/src/sources/typescript.ts+++ b/packages/checks/src/sources/typescript.ts@@ -28,6 +28,7 @@ const TYPESCRIPT_ROOTS = ["packages/files/src","packages/form/src","packages/react/src",+ "packages/query/src","packages/printing/src"// (workflows source now lives under packages/ee/src, already scanned above)];diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.mdindex fbc2923386..6a5dee6544 100644--- a/packages/database/AGENTS.md+++ b/packages/database/AGENTS.md@@ -28,6 +28,8 @@ DB types, Supabase/Kysely clients, audit config, event system types, rate limiti- Changing `audit.config.ts` entity definitions (affects which tables get audited and how diffs are computed).- Modifying `src/client.ts` (the Node-only Kysely/node-postgres client shared by the apps, jobs and server functions, including its NUMERIC/DATE type parsers).+- **Declare event triggers in `src/event-system/attachments.ts`**, and write interceptor / statement-handler bodies as files in `src/event-system/handlers/`. `authz sync` applies both; `authz migration <name>` ships them. Never call `attach_event_trigger`, `attach_statement_handler` or `set_event_triggers` in a migration.+- **A table is realtime when its attachments entry lists `broadcast_table_changes`.** `REALTIME_TABLES` (`src/realtime-tables.ts`) is derived from the manifest. See `.claude/rules/realtime-system.md`.## Never- Specify decimal places in `NUMERIC` columns (use bare `NUMERIC`).diff --git a/packages/database/package.json b/packages/database/package.jsonindex 8c1a257262..eb136447f2 100644--- a/packages/database/package.json+++ b/packages/database/package.json@@ -30,6 +30,7 @@"./mrp-engine": "./src/mrp-engine.ts","./supersession-pick": "./src/supersession-pick.ts","./picked-consumption": "./src/picked-consumption.ts",+ "./realtime-tables": "./src/realtime-tables.ts","./posting": "./src/posting.ts","./datasets": "./src/datasets/index.ts","./event": "./src/event.ts",diff --git a/packages/database/src/authz/cli.ts b/packages/database/src/authz/cli.tsindex e99f2a7f9c..2aa4a2e4bf 100644--- a/packages/database/src/authz/cli.ts+++ b/packages/database/src/authz/cli.ts@@ -29,7 +29,8 @@ async function main() {}const { manifest } = await import("./manifest");const helpers = await loadHelpers();- const todo = await unshipped(manifest, helpers);+ const { attachments } = await import("../event-system/attachments");+ const todo = await unshipped(manifest, helpers, undefined, attachments);if (todo.problems.length)throw new Error(`authz migration: fix these first:\n${todo.problems.join("\n")}`@@ -46,14 +47,19 @@ async function main() {for (const table of again ?? []) {if (!todo.tables.includes(table)) todo.tables.push(table);}- if (!todo.tables.length && !todo.helpers.length) {+ if (+ !todo.tables.length &&+ !todo.helpers.length &&+ !todo.attachments.length+ ) {console.log("authz: production already has every rule and helper");return;}const sql = await renderMigration(manifest,helpers.filter((h) => todo.helpers.includes(helperKey(h))),- todo.tables+ todo.tables,+ { attachments, tables: todo.attachments });const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)),@@ -72,7 +78,11 @@ async function main() {);writeFileSync(path.join(root, file), sql);console.log(- `authz: wrote ${file} (${[...todo.helpers, ...todo.tables].join(", ")})`+ `authz: wrote ${file} (${[...todo.helpers, ...todo.tables].join(", ")}${+ todo.attachments.length+ ? `, event triggers of ${todo.attachments.length} table(s)`+ : ""+ })`);return;}@@ -93,14 +103,20 @@ async function main() {await db.connect();try {const { manifest } = await import("./manifest");+ const { attachments } = await import("../event-system/attachments");const result = await syncAuthz(db, manifest, {- dryRun: command === "check"+ dryRun: command === "check",+ attachments});const verb = command === "check" ? "would change" : "changed";console.log(`authz: ${verb} ${result.helpers.length} helper(s)`);for (const name of result.helpers) console.log(` ${name}`);console.log(`authz: ${verb} ${result.changed.length} table(s)`);for (const table of result.changed) console.log(` ${table}`);+ console.log(+ `authz: ${verb} the event triggers of ${result.attachments.length} table(s)`+ );+ for (const table of result.attachments) console.log(` ${table}`);if (result.unmanaged.length) {console.error(`authz: tables with no rule in manifest.ts (left as they are):\n${result.unmanaged@@ -112,7 +128,9 @@ async function main() {// 3, not 1: CI tells "the database differs from the manifest" apart from a failure.if (command === "check" &&- (result.changed.length || result.helpers.length)+ (result.changed.length ||+ result.helpers.length ||+ result.attachments.length)) {process.exit(3);}diff --git a/packages/database/src/authz/helpers.ts b/packages/database/src/authz/helpers.tsindex 9e83fe7842..7f275e9fc0 100644--- a/packages/database/src/authz/helpers.ts+++ b/packages/database/src/authz/helpers.ts@@ -21,7 +21,9 @@ import type { Client } from "pg";const HERE = path.dirname(fileURLToPath(import.meta.url));export const HELPERS_DIR = path.join(HERE, "helpers");export const EVENT_SYSTEM_DIR = path.join(HERE, "../event-system/functions");-export const HELPER_DIRS = [HELPERS_DIR, EVENT_SYSTEM_DIR];+/** The functions attachments.ts attaches to tables: interceptors and statement handlers. */+export const EVENT_HANDLERS_DIR = path.join(HERE, "../event-system/handlers");+export const HELPER_DIRS = [HELPERS_DIR, EVENT_SYSTEM_DIR, EVENT_HANDLERS_DIR];/** `schema` defaults to `public`. */export type Helper = { name: string; sql: string; schema?: string };diff --git a/packages/database/src/authz/manifest.ts b/packages/database/src/authz/manifest.tsindex dc20fb5557..e911bcbcf6 100644--- a/packages/database/src/authz/manifest.ts+++ b/packages/database/src/authz/manifest.ts@@ -12,6 +12,7 @@ import {company,custom,exists,+ external,group,inCompany,inGroup,@@ -1440,6 +1441,9 @@ export const manifest = {supplyForecast: company("inventory", {read: "inventory_view"}),+ // Written by the log_*_changes triggers and read through table_changes_since,+ // which checks the caller's company itself. No API access.+ tableChange: serviceOnly(),tableView: policies({select: or(owner("createdBy"),@@ -1616,5 +1620,13 @@ export const manifest = {update: false,delete: "workflows_update"}),- workflowVersion: company("workflows", { read: "workflows_view" })+ workflowVersion: company("workflows", { read: "workflows_view" }),+ // Who may join a private Realtime broadcast topic. The policy is checked once,+ // when the client joins; the topic itself names the company or the user.+ "realtime.messages": external(+ "the row has no company or user column: the topic (company:<id>:<table>, user:<id>:<table>) carries the scope",+ (t) => `+ CREATE POLICY "company topic" ON ${t} FOR SELECT TO authenticated USING ((split_part(realtime.topic(), ':', 1) = 'company') AND (split_part(realtime.topic(), ':', 2) = ANY ((SELECT get_companies_with_employee_role())::text[])));+ CREATE POLICY "user topic" ON ${t} FOR SELECT TO authenticated USING ((split_part(realtime.topic(), ':', 1) = 'user') AND (split_part(realtime.topic(), ':', 2) = ((SELECT auth.uid()))::text));`+ )} satisfies Manifest;diff --git a/packages/database/src/authz/migration.test.ts b/packages/database/src/authz/migration.test.tsindex fd0d33ad1b..88ebc6aa44 100644--- a/packages/database/src/authz/migration.test.ts+++ b/packages/database/src/authz/migration.test.ts@@ -6,6 +6,7 @@ import { mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import path from "node:path";import { describe, expect, test } from "vitest";+import { attachments } from "../event-system/attachments";import { loadHelpers } from "./helpers";import { manifest } from "./manifest";import {@@ -27,11 +28,12 @@ const migrations = (files: Record<string, string>) => {describe("unshipped: production gets every rule and helper through a migration", () => {test("the repository ships everything the manifest and helpers say", async () => {expect(- await unshipped(manifest, await loadHelpers()),+ await unshipped(manifest, await loadHelpers(), undefined, attachments),"Production would not get these. Run: pnpm --filter @carbon/database authz migration <name>").toEqual({tables: [],helpers: [],+ attachments: [],problems: []});});@@ -97,8 +99,13 @@ describe("unshipped: production gets every rule and helper through a migration",.filter(([, sql]) => sql.startsWith(GENERATED_HEADER)));const dir = migrations({ ...generated, "20270101000001_ship.sql": sql });- const result = await unshipped(edited, helpers, dir);- expect(result).toEqual({ tables: [], helpers: [], problems: [] });+ const result = await unshipped(edited, helpers, dir, attachments);+ expect(result).toEqual({+ tables: [],+ helpers: [],+ attachments: [],+ problems: []+ });});test("the header cannot carry anything `authz migration` does not write", async () => {@@ -116,6 +123,37 @@ describe("unshipped: production gets every rule and helper through a migration",expect(result.tables).toContain("note");});+ test("a table outside public ships its policies without touching its RLS switch", async () => {+ const only = {+ "realtime.messages": manifest["realtime.messages"]+ } as Manifest;+ const sql = await renderMigration(only, [], ["realtime.messages"]);+ expect(sql).toContain(`ON "realtime"."messages"`);+ expect(sql).toContain("schemaname = 'realtime' AND tablename = 'messages'");+ expect(sql).not.toContain("ENABLE ROW LEVEL SECURITY");++ const shipped = migrations({ "20270101000001_realtime.sql": sql });+ expect(await unshipped(only, [], shipped)).toEqual({+ tables: [],+ helpers: [],+ attachments: [],+ problems: []+ });+ expect((await unshipped(only, [], migrations({}))).tables).toEqual([+ "realtime.messages"+ ]);+ });++ test("an edited, a new and a removed attachment are unshipped", async () => {+ const { customer: _, ...rest } = attachments;+ const result = await unshipped(manifest, await loadHelpers(), undefined, {+ ...rest,+ item: { events: true },+ note: { events: true }+ });+ expect(result.attachments).toEqual(["customer", "item", "note"]);+ });+test("a retired helper is accepted only in the migration that last shipped it", async () => {const securityFixes = "20260927172338_authz-security-fixes.sql";const dir = migrations({diff --git a/packages/database/src/authz/migration.ts b/packages/database/src/authz/migration.tsindex 465f01b726..bf2609119d 100644--- a/packages/database/src/authz/migration.ts+++ b/packages/database/src/authz/migration.ts@@ -7,8 +7,10 @@ import { readdirSync, readFileSync } from "node:fs";import path from "node:path";import { fileURLToPath } from "node:url";import { parse } from "libpg-query";+import type { Attachments } from "../event-system/attachments";+import { renderFor } from "../event-system/attachments-sync";import { type Helper, helperKey, RETIRED_HELPERS } from "./helpers";-import { type AnyRule, type Manifest, render } from "./rules";+import { type AnyRule, locate, type Manifest, render } from "./rules";import { assertOnlyPolicies } from "./sync";/**@@ -38,18 +40,24 @@ const BASELINE = path.join(HERE, "baseline.json");export const GENERATED_HEADER ="-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.";+const LOCK_TIMEOUT = "SET lock_timeout = '5s';";+const literal = (s: string) => `'${s.replaceAll("'", "''")}'`;const ident = (s: string) => `"${s.replaceAll('"', '""')}"`;export const hash = (sql: string) =>createHash("sha256").update(sql).digest("hex").slice(0, 16);-const dropAllPolicies = (table: string) =>+// The public form is kept byte for byte: `readShipped` compares it with the text+// of every generated migration already in the repository.+const dropAllPolicies = (table: string, schema = "public") =>["DO $authz$","DECLARE p record;","BEGIN",- ` FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = ${literal(table)} LOOP`,- ` EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, ${literal(table)});`,+ ` FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = ${literal(schema)} AND tablename = ${literal(table)} LOOP`,+ schema === "public"+ ? ` EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, ${literal(table)});`+ : ` EXECUTE format('DROP POLICY %I ON %I.%I', p.policyname, ${literal(schema)}, ${literal(table)});`," END LOOP;","END","$authz$;"@@ -64,7 +72,11 @@ const dropAllPolicies = (table: string) =>export async function renderMigration(manifest: Manifest,helpers: Helper[],- tables: string[]+ tables: string[],+ attached: { attachments: Attachments; tables: string[] } = {+ attachments: {},+ tables: []+ }): Promise<string> {const parts = [GENERATED_HEADER,@@ -73,17 +85,20 @@ export async function renderMigration(for (const helper of helpers) parts.push(helper.sql.trim());- for (const table of tables) {- const rule = (manifest as Record<string, AnyRule>)[table];+ for (const key of tables) {+ const rule = (manifest as Record<string, AnyRule>)[key];if (!rule)- throw new Error(`authz migration: no rule for "${table}" in manifest.ts`);- const sql = render(rule, table);- if (sql) await assertOnlyPolicies(sql, "public", table);+ throw new Error(`authz migration: no rule for "${key}" in manifest.ts`);+ const { schema, table } = locate(key);+ const sql = render(rule, table, schema);+ if (sql) await assertOnlyPolicies(sql, schema, table);parts.push([- `-- ${table}`,- dropAllPolicies(table),- `ALTER TABLE public.${ident(table)} ENABLE ROW LEVEL SECURITY;`,+ `-- ${key}`,+ dropAllPolicies(table, schema),+ // An external table's RLS switch belongs to its owner.+ schema === "public" &&+ `ALTER TABLE public.${ident(table)} ENABLE ROW LEVEL SECURITY;`,sql].filter(Boolean)@@ -91,6 +106,23 @@ export async function renderMigration();}+ // After the functions and policies: the triggers call the functions above.+ if (attached.tables.length) {+ parts.push(+ [+ "-- event triggers (packages/database/src/event-system/attachments.ts)",+ // Creating a trigger locks its table against writes. Behind a long+ // transaction it would wait, and every writer would queue behind it:+ // fail instead, and let the migration be run again.+ LOCK_TIMEOUT,+ ...attached.tables.map((table) =>+ renderFor(attached.attachments, table)+ ),+ "RESET lock_timeout;"+ ].join("\n")+ );+ }+return `${parts.join("\n\n")}\n`;}@@ -116,9 +148,13 @@ async function statements(sql: string): Promise<{ node: Ast; text: string }[]> {type Shipped = {tables: Map<string, { file: string; policies: string[] }>;helpers: Map<string, { file: string; text: string }>;+ /** Each table's last shipped `set_event_triggers` statement. */+ attachments: Map<string, string>;problems: string[];};+const SET_EVENT_TRIGGERS = /^SELECT set_event_triggers\('((?:[^']|'')+)'[,)]/;+/*** What the generated migrations ship, latest file winning. A generated file may contain* only managed helpers and, per table, the drop-all block, ENABLE ROW LEVEL SECURITY and@@ -128,6 +164,7 @@ async function readShipped(dir: string, managed: Set<string>) {const shipped: Shipped = {tables: new Map(),helpers: new Map(),+ attachments: new Map(),problems: []};const files = readdirSync(dir)@@ -136,8 +173,19 @@ async function readShipped(dir: string, managed: Set<string>) {for (const file of files) {const sql = readFileSync(path.join(dir, file), "utf8");if (!sql.startsWith(GENERATED_HEADER)) continue;+ // The manifest key of the block being read, and where that table lives.let table: string | undefined;+ let at = { schema: "public", table: "" };for (const { node, text } of await statements(sql)) {+ const attached = node.SelectStmt && SET_EVENT_TRIGGERS.exec(text);+ if (attached) {+ shipped.attachments.set(+ (attached[1] as string).replaceAll("''", "'"),+ `${text};`+ );+ continue;+ }+ if (node.VariableSetStmt?.name === "lock_timeout") continue;const fn = node.CreateFunctionStmt;const alter = node.AlterTableStmt;const policy = node.CreatePolicyStmt?.table;@@ -150,18 +198,35 @@ async function readShipped(dir: string, managed: Set<string>) {}if (RETIRED_HELPERS[key] === file) continue;} else if (node.DoStmt) {- table = /tablename = '((?:[^']|'')+)'/- .exec(text)?.[1]- ?.replaceAll("''", "'");+ const named =+ /schemaname = '((?:[^']|'')+)' AND tablename = '((?:[^']|'')+)'/.exec(+ text+ );+ table = undefined;+ if (named) {+ at = {+ schema: (named[1] as string).replaceAll("''", "'"),+ table: (named[2] as string).replaceAll("''", "'")+ };+ table =+ at.schema === "public" ? at.table : `${at.schema}.${at.table}`;+ }if (table &&- text === (await statements(dropAllPolicies(table)))[0]?.text- )+ text ===+ (await statements(dropAllPolicies(at.table, at.schema)))[0]?.text+ ) {+ // No ENABLE ROW LEVEL SECURITY follows for an external table, so+ // its block opens here.+ if (at.schema !== "public")+ shipped.tables.set(table, { file, policies: [] });continue;+ }} else if (alter) {const cmds = alter.cmds ?? [];if (table &&+ at.schema === "public" &&alter.relation?.schemaname === "public" &&alter.relation?.relname === table &&cmds.length === 1 &&@@ -172,8 +237,8 @@ async function readShipped(dir: string, managed: Set<string>) {}} else if (table &&- policy?.schemaname === "public" &&- policy?.relname === table &&+ policy?.schemaname === at.schema &&+ policy?.relname === at.table &&shipped.tables.get(table)?.file === file) {shipped.tables.get(table)?.policies.push(text);@@ -190,6 +255,8 @@ async function readShipped(dir: string, managed: Set<string>) {export type Unshipped = {tables: string[];helpers: string[];+ /** Tables whose event triggers production does not have as attachments.ts declares them. */+ attachments: string[];problems: string[];};@@ -197,7 +264,8 @@ export type Unshipped = {export async function unshipped(manifest: Manifest,helpers: Helper[],- dir = MIGRATIONS_DIR+ dir = MIGRATIONS_DIR,+ attachments: Attachments = {}): Promise<Unshipped> {const baseline: {tables: Record<string, string>;@@ -207,11 +275,27 @@ export async function unshipped(const result: Unshipped = {tables: [],helpers: [],+ attachments: [],problems: shipped.problems};+ // A declared table must be shipped as declared; a table shipped once and no+ // longer declared must be shipped again, detached.+ const attachedTables = new Set([+ ...Object.keys(attachments),+ ...shipped.attachments.keys()+ ]);+ for (const table of [...attachedTables].sort()) {+ if (shipped.attachments.get(table) !== renderFor(attachments, table)) {+ // Never declared and never shipped attached: nothing to detach.+ if (!(table in attachments) && !shipped.attachments.has(table)) continue;+ result.attachments.push(table);+ }+ }+for (const [table, rule] of Object.entries(manifest) as [string, AnyRule][]) {- const sql = render(rule, table);+ const at = locate(table);+ const sql = render(rule, at.table, at.schema);const got = shipped.tables.get(table);const same = got? JSON.stringify(got.policies) ===diff --git a/packages/database/src/authz/rules.ts b/packages/database/src/authz/rules.tsindex 2acd71eb48..a7236691ae 100644--- a/packages/database/src/authz/rules.ts+++ b/packages/database/src/authz/rules.ts@@ -224,8 +224,30 @@ export type Rule<T extends Table = Table> =// biome-ignore lint/suspicious/noExplicitAny: a rule for some table, read genericallyexport type AnyRule = Rule<any>;-/** Every public table's rule. Each entry's type is bound to its own table. */-export type Manifest = { [T in Table]?: Rule<T> };+type CustomRule = Extract<AnyRule, { kind: "custom" }>;++/**+ * Tables outside `public` whose policies the manifest also owns, keyed+ * `<schema>.<table>`. Supabase owns the table itself (and its RLS switch); only+ * the policies are ours.+ */+export type ExternalTable = "realtime.messages";++/**+ * Every public table's rule, each entry's type bound to its own table, plus the+ * external tables' policies.+ */+export type Manifest = { [T in Table]?: Rule<T> } & {+ [T in ExternalTable]?: CustomRule;+};++/** The schema and table a manifest key names: `note` is public, `realtime.messages` is not. */+export const locate = (key: string) => {+ const dot = key.indexOf(".");+ return dot === -1+ ? { schema: "public", table: key }+ : { schema: key.slice(0, dot), table: key.slice(dot + 1) };+};/** Any shape: one predicate per command, or `all` for every command at once. */export const policies = <T extends Table>({@@ -344,6 +366,12 @@ export const custom = <T extends Table>(sql: (target: string) => string): Rule<T> => ({ kind: "custom", reason, sql });+/** Policies on a table outside `public` (see `ExternalTable`). */+export const external = (+ reason: string,+ sql: (target: string) => string+): CustomRule => ({ kind: "custom", reason, sql });+// ─── Rendering ───────────────────────────────────────────────────────────────/** Policies cannot take bind parameters, so every value is written inline as a literal. */diff --git a/packages/database/src/authz/sync.ts b/packages/database/src/authz/sync.tsindex 7afc62d762..d9632fd14c 100644--- a/packages/database/src/authz/sync.ts+++ b/packages/database/src/authz/sync.ts@@ -4,8 +4,10 @@import { parse } from "libpg-query";import type { Client } from "pg";+import type { Attachments } from "../event-system/attachments";+import { syncAttachments } from "../event-system/attachments-sync";import { type Helper, loadHelpers, syncHelpers } from "./helpers";-import { type AnyRule, type Manifest, render } from "./rules";+import { type AnyRule, locate, type Manifest, render } from "./rules";export type Policy = {policyname: string;@@ -42,12 +44,12 @@ export const readPolicies = async (db: Client, schema: string, table: string) =>)).rows;-const rlsEnabled = async (db: Client, table: string) =>+const rlsEnabled = async (db: Client, schema: string, table: string) =>(await db.query<{ enabled: boolean }>(`SELECT relrowsecurity AS enabled FROM pg_class- WHERE oid = to_regclass(format('public.%I', $1::text))`,- [table]+ WHERE oid = to_regclass(format('%I.%I', $1::text, $2::text))`,+ [schema, table])).rows[0]?.enabled ?? false;@@ -85,23 +87,26 @@ export async function desiredPolicies(db: Client, manifest: Manifest) {await db.query("SAVEPOINT authz_scratch");try {await db.query(`CREATE SCHEMA ${ident(SCRATCH)}`);- for (const [table, rule] of rulesOf(manifest)) {+ for (const [key, rule] of rulesOf(manifest)) {+ const { schema, table } = locate(key);await db.query("SAVEPOINT authz_rule");try {await db.query(- `CREATE TABLE ${ident(SCRATCH)}.${ident(table)} (LIKE public.${ident(table)})`+ `CREATE TABLE ${ident(SCRATCH)}.${ident(table)} (LIKE ${ident(schema)}.${ident(table)})`);const sql = render(rule, table, SCRATCH);if (sql) {await assertOnlyPolicies(sql, SCRATCH, table);await db.query(sql);}- desired.set(table, await readPolicies(db, SCRATCH, table));+ desired.set(key, await readPolicies(db, SCRATCH, table));+ // Dropped so an external table may share its name with a public one.+ await db.query(`DROP TABLE ${ident(SCRATCH)}.${ident(table)}`);await db.query("RELEASE SAVEPOINT authz_rule");} catch (error) {await db.query("ROLLBACK TO SAVEPOINT authz_rule");desired.set(- table,+ key,error instanceof Error ? error : new Error(String(error)));}@@ -143,6 +148,8 @@ export type SyncResult = {changed: string[];/** Public tables the manifest does not cover. */unmanaged: string[];+ /** Tables whose event triggers differed from attachments.ts. */+ attachments: string[];};/**@@ -153,7 +160,11 @@ export type SyncResult = {export async function syncAuthz(db: Client,manifest: Manifest,- { dryRun = false, helpers }: { dryRun?: boolean; helpers?: Helper[] } = {}+ {+ dryRun = false,+ helpers,+ attachments+ }: { dryRun?: boolean; helpers?: Helper[]; attachments?: Attachments } = {}): Promise<SyncResult> {const managedHelpers = helpers ?? (await loadHelpers());return inAuthzTransaction(@@ -172,27 +183,37 @@ export async function syncAuthz(}const changed: string[] = [];- for (const [table, rule] of rulesOf(manifest)) {- const live = await readPolicies(db, "public", table);+ for (const [key, rule] of rulesOf(manifest)) {+ const { schema, table } = locate(key);+ const live = await readPolicies(db, schema, table);+ const enabled = await rlsEnabled(db, schema, table);+ // An external table's RLS switch belongs to its owner. Policies on a+ // table without it would authorize nothing, so that is a failure.+ if (schema !== "public" && !enabled) {+ throw new Error(+ `authz: ${key} does not have row level security enabled`+ );+ }const same =- JSON.stringify(live) === JSON.stringify(desired.get(table)) &&- (await rlsEnabled(db, table));+ JSON.stringify(live) === JSON.stringify(desired.get(key)) && enabled;if (same) continue;- changed.push(table);+ changed.push(key);if (dryRun) continue;for (const policy of live) {await db.query(- `DROP POLICY ${ident(policy.policyname)} ON public.${ident(table)}`+ `DROP POLICY ${ident(policy.policyname)} ON ${ident(schema)}.${ident(table)}`);}- await db.query(- `ALTER TABLE public.${ident(table)} ENABLE ROW LEVEL SECURITY`- );- const sql = render(rule, table);+ if (schema === "public") {+ await db.query(+ `ALTER TABLE public.${ident(table)} ENABLE ROW LEVEL SECURITY`+ );+ }+ const sql = render(rule, table, schema);if (sql) {- await assertOnlyPolicies(sql, "public", table);+ await assertOnlyPolicies(sql, schema, table);await db.query(sql);}}@@ -211,7 +232,17 @@ export async function syncAuthz()).rows.map((r) => r.table);- return { helpers: changedHelpers, changed, unmanaged };+ // Last: the triggers call the functions synced above.+ const changedAttachments = attachments+ ? await syncAttachments(db, attachments, { dryRun })+ : [];++ return {+ helpers: changedHelpers,+ changed,+ unmanaged,+ attachments: changedAttachments+ };},{ commit: !dryRun });diff --git a/packages/database/src/datasets/wipe.ts b/packages/database/src/datasets/wipe.tsindex 80646eb3dc..e17a3f3eff 100644--- a/packages/database/src/datasets/wipe.ts+++ b/packages/database/src/datasets/wipe.ts@@ -62,6 +62,10 @@ const PRESERVED_TABLES = new Set(["oauthCode","oauthToken","searchIndexRegistry",+ // The change log open clients read to learn what the wipe just deleted: every+ // delete below writes to it, so it can never be empty afterwards. It prunes+ // itself by age, and backups already leave it alone (STRUCTURAL_TABLES).+ "tableChange","tableView","userAttributeCategory","userModulePreference",diff --git a/packages/database/src/event-dispatch.test.ts b/packages/database/src/event-dispatch.test.tsindex 3b21c2a440..54022eb411 100644--- a/packages/database/src/event-dispatch.test.ts+++ b/packages/database/src/event-dispatch.test.ts@@ -7,13 +7,25 @@ import { fileURLToPath } from "node:url";import { describe, expect, it } from "vitest";import { auditConfig } from "./audit.config";-const file = "event-system/functions/dispatch_event_batch.sql";-const sql = readFileSync(fileURLToPath(new URL(file, import.meta.url)), "utf8");+// Every trigger function that drops an UPDATE touching only bookkeeping columns.+const files = [+ "dispatch_event_batch",+ "broadcast_table_changes",+ "broadcast_user_changes",+ "broadcast_reference_changes",+ "log_table_changes",+ "log_user_changes"+].map((name) => `event-system/functions/${name}.sql`);++describe.each(files)("%s", (file) => {+ const sql = readFileSync(+ fileURLToPath(new URL(file, import.meta.url)),+ "utf8"+ );-describe("dispatch_event_batch", () => {// The trigger drops an UPDATE that changes only these columns before it is- // queued, because the audit diff would discard it. A skip field added on one- // side only makes the trigger and the handler disagree.+ // queued or broadcast, because the audit diff would discard it. A skip field+ // added on one side only makes the triggers and the handler disagree.it("ignores exactly the columns the audit diff skips", () => {const declared = sql.match(/ignored_columns CONSTANT TEXT\[\] := ARRAY\[([^\]]*)\]/diff --git a/packages/database/src/event-system/attachments-sync.test.ts b/packages/database/src/event-system/attachments-sync.test.tsnew file mode 100644index 0000000000..69b2ec894c--- /dev/null+++ b/packages/database/src/event-system/attachments-sync.test.ts@@ -0,0 +1,108 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { Client } from "pg";+import { afterAll, beforeAll, describe, expect, test } from "vitest";+import { attachments } from "./attachments";+import {+ liveAttachments,+ renderAttachment,+ renderDetachment,+ renderFor,+ syncAttachments+} from "./attachments-sync";++describe("rendering an attachment", () => {+ test("is one set_event_triggers call with every list spelled out", () => {+ expect(+ renderAttachment("customer", {+ before: ["a"],+ after: ["b", "c"],+ events: true,+ statement: ["z", "y"]+ })+ ).toBe(+ "SELECT set_event_triggers('customer', ARRAY['a']::text[], ARRAY['b', 'c']::text[], true, ARRAY['y', 'z']::text[]);"+ );+ });++ test("a table without an entry is detached", () => {+ expect(renderFor({}, "customer")).toBe(renderDetachment("customer"));+ expect(renderDetachment("customer")).toBe(+ "SELECT set_event_triggers('customer');"+ );+ });+});++// Runs against the local database: SUPABASE_DB_URL=… pnpm vitest run src/event-system+const url = process.env.SUPABASE_DB_URL;++describe.skipIf(!url)("attachments against a migrated database", () => {+ const db = new Client({ connectionString: url });++ // Each event trigger with its oid: a trigger that was dropped and created+ // again has the same definition and a new oid.+ const triggers = async () =>+ (+ await db.query<{ oid: number; definition: string }>(+ `SELECT t.oid::int AS oid, pg_get_triggerdef(t.oid) AS definition+ FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid+ WHERE NOT t.tgisinternal AND t.tgname LIKE 'trg\\_event\\_%'+ ORDER BY c.relname, t.tgname`+ )+ ).rows;++ beforeAll(async () => {+ await db.connect();+ await db.query("BEGIN");+ });++ afterAll(async () => {+ await db.query("ROLLBACK");+ await db.end();+ });++ test("the database already has exactly what attachments.ts declares", async () => {+ expect(await syncAttachments(db, attachments, { dryRun: true })).toEqual(+ []+ );+ });++ test("re-applying every entry touches no trigger", async () => {+ // Creating a trigger locks its table, so a migration that restates every+ // table must leave the ones that have not changed alone.+ const before = await triggers();+ for (const table of Object.keys(attachments)) {+ await db.query(renderFor(attachments, table));+ }+ expect(await triggers()).toEqual(before);+ });++ test("sync detaches a table that has no entry, and heals a missing trigger", async () => {+ const { customer: _, ...rest } = attachments;+ expect(await syncAttachments(db, rest, { dryRun: false })).toEqual([+ "customer"+ ]);+ expect((await liveAttachments(db)).has("customer")).toBe(false);++ expect(await syncAttachments(db, attachments, { dryRun: false })).toEqual([+ "customer"+ ]);+ await db.query(+ `DROP TRIGGER "trg_event_statement_broadcast_table_changes_upd" ON "customer"`+ );+ const broken = await triggers();+ await db.query(renderFor(attachments, "customer"));+ const healed = (await triggers()).map((trigger) => trigger.definition);+ expect(healed).toHaveLength(broken.length + 1);+ expect(+ healed.some(+ (definition) =>+ definition.includes(+ "trg_event_statement_broadcast_table_changes_upd"+ ) && definition.includes("ON public.customer")+ )+ ).toBe(true);+ });+});diff --git a/packages/database/src/event-system/attachments-sync.ts b/packages/database/src/event-system/attachments-sync.tsnew file mode 100644index 0000000000..768b0093af--- /dev/null+++ b/packages/database/src/event-system/attachments-sync.ts@@ -0,0 +1,99 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Client } from "pg";+import type { Attachment, Attachments } from "./attachments";++/**+ * Makes a database's event triggers match attachments.ts, through+ * `set_event_triggers` — the same call a generated migration ships. Runs inside+ * the authz transaction, after the functions it attaches have been synced.+ */++type Resolved = {+ before: string[];+ after: string[];+ events: boolean;+ statement: string[];+};++const literal = (s: string) => `'${s.replaceAll("'", "''")}'`;+const array = (names: readonly string[]) =>+ `ARRAY[${names.map(literal).join(", ")}]::text[]`;++// Statement handlers have no order of their own (Postgres fires same-kind+// triggers by name), so they are compared and written sorted.+const resolve = (attachment: Attachment): Resolved => ({+ before: [...(attachment.before ?? [])],+ after: [...(attachment.after ?? [])],+ events: attachment.events ?? false,+ statement: [...(attachment.statement ?? [])].sort()+});++/** The one statement that gives `table` exactly this attachment. */+export const renderAttachment = (table: string, attachment: Attachment) => {+ const { before, after, events, statement } = resolve(attachment);+ return `SELECT set_event_triggers(${literal(table)}, ${array(before)}, ${array(after)}, ${events}, ${array(statement)});`;+};++/** The statement for a table that is no longer in the manifest. */+export const renderDetachment = (table: string) =>+ `SELECT set_event_triggers(${literal(table)});`;++/** The statement for `table`: its attachment, or a detachment if it has none. */+export const renderFor = (attachments: Attachments, table: string) => {+ const attachment = (attachments as Record<string, Attachment>)[table];+ return attachment+ ? renderAttachment(table, attachment)+ : renderDetachment(table);+};++/** Every public table's event triggers, as the database has them now. */+export async function liveAttachments(db: Client) {+ const { rows } = await db.query<{ table: string } & Resolved>(+ `SELECT c.relname AS "table",+ coalesce((SELECT array_remove(string_to_array(encode(t.tgargs, 'escape'), E'\\\\000'), '')+ FROM pg_trigger t+ WHERE t.tgrelid = c.oid AND t.tgname = 'trg_event_sync_' || c.relname), '{}') AS before,+ coalesce((SELECT array_remove(string_to_array(encode(t.tgargs, 'escape'), E'\\\\000'), '')+ FROM pg_trigger t+ WHERE t.tgrelid = c.oid AND t.tgname = 'trg_event_after_sync_' || c.relname), '{}') AS after,+ (SELECT count(*) = 3 FROM pg_trigger t+ WHERE t.tgrelid = c.oid AND t.tgname LIKE 'trg\\_event\\_async\\_%') AS events,+ coalesce((SELECT array_agg(p.proname::text ORDER BY p.proname)+ FROM pg_trigger t JOIN pg_proc p ON p.oid = t.tgfoid+ WHERE t.tgrelid = c.oid AND t.tgname LIKE 'trg\\_event\\_statement\\_%\\_ins'), '{}') AS statement+ FROM pg_class c+ WHERE c.relnamespace = 'public'::regnamespace+ AND EXISTS (SELECT 1 FROM pg_trigger t+ WHERE t.tgrelid = c.oid AND NOT t.tgisinternal+ AND t.tgname LIKE 'trg\\_event\\_%')`+ );+ return new Map(rows.map(({ table, ...live }) => [table, live]));+}++/**+ * Give every table the triggers its entry declares, and remove the event+ * triggers of a table that has no entry. Returns the tables that differed.+ */+export async function syncAttachments(+ db: Client,+ attachments: Attachments,+ { dryRun }: { dryRun: boolean }+): Promise<string[]> {+ const live = await liveAttachments(db);+ const declared = attachments as Record<string, Attachment>;+ const tables = [+ ...new Set([...Object.keys(declared), ...live.keys()])+ ].sort();+ const changed: string[] = [];+ for (const table of tables) {+ const want = resolve(declared[table] ?? {});+ const have = live.get(table) ?? resolve({});+ if (JSON.stringify(want) === JSON.stringify(have)) continue;+ changed.push(table);+ if (!dryRun) await db.query(renderFor(attachments, table));+ }+ return changed;+}diff --git a/packages/database/src/event-system/attachments.ts b/packages/database/src/event-system/attachments.tsnew file mode 100644index 0000000000..5b793c2311--- /dev/null+++ b/packages/database/src/event-system/attachments.ts@@ -0,0 +1,359 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Database } from "../types";++type Table = keyof Database["public"]["Tables"];++/**+ * What runs when a table's rows change.+ *+ * - `before` / `after`: interceptors, run for each row inside the writing+ * transaction, in this order (`handlers/<name>.sql`).+ * - `events`: every change is queued for the event system (audit log, search+ * index, webhooks, workflows, embeddings).+ * - `statement`: handlers run once per statement, e.g. the realtime broadcasts+ * (`functions/broadcast_*.sql`) and the change log (`functions/log_*.sql`).+ */+export type Attachment = {+ readonly before?: readonly string[];+ readonly after?: readonly string[];+ readonly events?: boolean;+ readonly statement?: readonly string[];+};++export type Attachments = { readonly [T in Table]?: Attachment };++/**+ * The event triggers of every table, and the only place they are declared.+ * `authz sync` makes a database match it; `authz migration` ships a change to+ * production. A migration never calls `attach_event_trigger`,+ * `attach_statement_handler` or `set_event_triggers`: each of those replaces a+ * table's whole list, so a call that forgot one function silently detached it.+ */+export const attachments = {+ ability: { statement: ["broadcast_reference_changes"] },+ address: { before: ["sync_address_to_parent"], events: true },+ assemblyPlanJob: { statement: ["broadcast_table_changes"] },+ changeOrder: { statement: ["broadcast_table_changes"] },+ charge: { events: true },+ company: { after: ["sync_insert_company_related_records"] },+ companyIntegration: { before: ["sync_verify_integration"], events: true },+ contact: { before: ["sync_contact_to_parent"], events: true },+ customField: { statement: ["broadcast_table_changes"] },+ customer: {+ before: ["sync_update_customer_type_group"],+ after: ["sync_create_customer_entries", "sync_create_customer_org_group"],+ events: true,+ statement: ["broadcast_table_changes", "log_table_changes"]+ },+ customerAccount: {+ after: ["sync_add_customer_account_to_group"],+ events: true+ },+ customerContact: { statement: ["broadcast_reference_changes"] },+ customerItemPriceOverride: { events: true },+ customerItemPriceOverrideBreak: { events: true },+ customerLocation: { statement: ["broadcast_reference_changes"] },+ customerPartToItem: { events: true },+ customerPayment: { events: true },+ customerShipping: { events: true },+ customerTax: { events: true },+ customerType: {+ before: ["sync_update_customer_type_group_name"],+ after: ["sync_create_customer_type_group"],+ events: true,+ statement: ["broadcast_reference_changes"]+ },+ document: {+ before: ["sync_edit_document_transaction"],+ after: ["sync_upload_document_transaction"],+ events: true+ },+ documentExtraction: { statement: ["broadcast_table_changes"] },+ documentTemplate: { statement: ["broadcast_table_changes"] },+ employee: {+ before: ["sync_update_employee_type_membership"],+ after: ["sync_add_employee_to_type_group"],+ events: true,+ statement: ["broadcast_table_changes", "log_table_changes"]+ },+ employeeJob: { events: true },+ employeeType: {+ before: ["sync_update_employee_type_group"],+ after: ["sync_create_employee_type_group"],+ events: true+ },+ fixedAsset: { events: true },+ gauge: { events: true },+ gaugeCalibrationRecord: { events: true },+ implementationCheckState: { statement: ["broadcast_table_changes"] },+ implementationFieldValue: { statement: ["broadcast_table_changes"] },+ implementationHub: { statement: ["broadcast_table_changes"] },+ implementationRow: { statement: ["broadcast_table_changes"] },+ inspection: { statement: ["broadcast_table_changes"] },+ inspectionSample: { statement: ["broadcast_table_changes"] },+ inventoryCount: { events: true, statement: ["broadcast_table_changes"] },+ inventoryCountLine: { events: true, statement: ["broadcast_table_changes"] },+ invite: { events: true },+ invoiceSettlement: { statement: ["broadcast_table_changes"] },+ itarCertification: { events: true },+ item: {+ after: [+ "sync_create_item_related_records",+ "sync_create_make_method_related_records",+ "sync_propagate_item_readable_id_to_tracked_entity"+ ],+ events: true,+ statement: ["broadcast_table_changes", "log_table_changes"]+ },+ itemCost: { events: true },+ itemLedger: {+ statement: ["apply_item_stock_quantities", "broadcast_table_changes"]+ },+ itemPlanning: { events: true },+ itemPostingGroup: {+ events: true,+ statement: ["broadcast_reference_changes"]+ },+ itemReplenishment: { events: true },+ itemShelfLife: { events: true },+ itemStockQuantities: { statement: ["broadcast_table_changes"] },+ itemSupersession: {+ statement: ["broadcast_table_changes", "log_table_changes"]+ },+ itemUnitSalePrice: { events: true },+ job: {+ before: ["sync_job_complete_or_canceled"],+ after: ["sync_insert_job_make_method", "sync_job_recompute_service_line"],+ events: true,+ statement: ["broadcast_table_changes"]+ },+ jobMakeMethod: {+ before: [+ "sync_update_tracked_entity_on_job_make_method",+ "sync_delete_tracked_entity_on_job_make_method"+ ],+ events: true,+ statement: ["broadcast_table_changes"]+ },+ jobMaterial: {+ before: [+ "sync_check_job_material_self_reference",+ "sync_update_job_material_make_method_item_id"+ ],+ after: ["sync_insert_job_material_make_method"],+ events: true,+ statement: ["broadcast_table_changes"]+ },+ jobOperation: {+ before: ["sync_finish_job_operation"],+ after: [+ "set_shelf_life_on_operation_done",+ "set_shelf_life_on_operation_started"+ ],+ events: true,+ statement: ["broadcast_table_changes"]+ },+ jobOperationDependency: {+ after: ["sync_set_initial_dependency_status"],+ events: true+ },+ jobOperationNote: { statement: ["broadcast_table_changes"] },+ jobOperationStep: { statement: ["broadcast_table_changes"] },+ jobOperationStepRecord: { statement: ["broadcast_table_changes"] },+ journal: { events: true, statement: ["broadcast_table_changes"] },+ location: {+ after: ["sync_create_location_related_records"],+ events: true,+ statement: ["broadcast_reference_changes"]+ },+ maintenanceDispatch: {+ after: ["sync_on_maintenance_dispatch_complete"],+ events: true,+ statement: ["broadcast_table_changes"]+ },+ maintenanceDispatchComment: { events: true },+ maintenanceDispatchEvent: { events: true },+ maintenanceSchedule: { events: true },+ maintenanceScheduleItem: { events: true },+ material: { statement: ["broadcast_table_changes"] },+ materialForm: { statement: ["broadcast_table_changes"] },+ materialSubstance: { statement: ["broadcast_table_changes"] },+ materialType: { statement: ["broadcast_reference_changes"] },+ methodMaterial: {+ before: ["sync_check_method_material_self_reference"],+ events: true+ },+ modelUpload: { statement: ["broadcast_table_changes", "log_table_changes"] },+ nonConformance: { events: true, statement: ["broadcast_table_changes"] },+ nonConformanceActionTask: {+ events: true,+ statement: ["broadcast_table_changes"]+ },+ nonConformanceApprovalTask: { events: true },+ nonConformanceItem: { events: true, statement: ["broadcast_table_changes"] },+ nonConformanceRequiredAction: {+ before: ["sync_protect_system_required_actions"],+ events: true+ },+ nonConformanceSupplier: {+ after: ["sync_create_nc_external_link"],+ events: true+ },+ nonConformanceType: { statement: ["broadcast_reference_changes"] },+ notification: { statement: ["broadcast_user_changes"] },+ part: { statement: ["broadcast_table_changes"] },+ payment: { events: true, statement: ["broadcast_table_changes"] },+ paymentTerm: { statement: ["broadcast_reference_changes"] },+ pickingList: { statement: ["broadcast_table_changes"] },+ pickingListLine: { statement: ["broadcast_table_changes"] },+ printJob: { statement: ["broadcast_table_changes"] },+ procedure: {+ before: ["sync_archive_other_procedures"],+ events: true,+ statement: ["broadcast_reference_changes"]+ },+ process: { statement: ["broadcast_reference_changes"] },+ productionEvent: {+ before: ["sync_set_job_operation_in_progress"],+ events: true,+ statement: ["broadcast_table_changes"]+ },+ productionQuantity: {+ before: ["sync_update_job_operation_quantities"],+ events: true,+ statement: ["broadcast_table_changes"]+ },+ purchaseInvoice: {+ before: ["prevent_posted_purchase_invoice_deletion"],+ events: true,+ statement: ["broadcast_table_changes"]+ },+ purchaseInvoiceLine: {+ after: ["sync_purchase_invoice_line_price_change"],+ events: true,+ statement: ["broadcast_table_changes"]+ },+ purchaseOrder: { events: true, statement: ["broadcast_table_changes"] },+ purchaseOrderDelivery: { events: true },+ purchaseOrderLine: { events: true, statement: ["broadcast_table_changes"] },+ purchaseOrderPayment: { events: true },+ purchaseReturnOrder: { statement: ["broadcast_table_changes"] },+ purchaseReturnOrderLine: { statement: ["broadcast_table_changes"] },+ purchasingRfq: { statement: ["broadcast_table_changes"] },+ purchasingRfqLine: { statement: ["broadcast_table_changes"] },+ qualityDocument: {+ before: ["sync_archive_other_quality_documents"],+ events: true,+ statement: ["broadcast_reference_changes"]+ },+ quote: {+ before: ["sync_update_quote_exchange_rate"],+ events: true,+ statement: ["broadcast_table_changes"]+ },+ quoteLine: {+ before: ["sync_update_quote_line_make_method_item_id"],+ after: ["sync_insert_quote_line_make_method"],+ events: true,+ statement: ["broadcast_table_changes"]+ },+ quoteMakeMethod: { statement: ["broadcast_table_changes"] },+ quoteMaterial: {+ before: ["sync_update_quote_material_make_method_item_id"],+ after: ["sync_insert_quote_material_make_method"],+ events: true,+ statement: ["broadcast_table_changes"]+ },+ quoteOperation: { statement: ["broadcast_table_changes"] },+ receipt: { events: true, statement: ["broadcast_table_changes"] },+ receiptLine: { events: true, statement: ["broadcast_table_changes"] },+ reimbursement: { events: true },+ salesInvoice: {+ before: ["prevent_posted_sales_invoice_deletion"],+ events: true,+ statement: ["broadcast_table_changes"]+ },+ salesInvoiceLine: { events: true, statement: ["broadcast_table_changes"] },+ salesInvoiceShipment: { events: true },+ salesOrder: {+ before: ["sync_update_sales_order_exchange_rate"],+ events: true,+ statement: ["broadcast_table_changes"]+ },+ salesOrderLine: { events: true, statement: ["broadcast_table_changes"] },+ salesOrderPayment: { events: true },+ salesOrderShipment: { events: true },+ salesReturnOrder: { statement: ["broadcast_table_changes"] },+ salesReturnOrderLine: { statement: ["broadcast_table_changes"] },+ salesRfq: { events: true, statement: ["broadcast_table_changes"] },+ salesRfqLine: { statement: ["broadcast_table_changes"] },+ shipment: { events: true, statement: ["broadcast_table_changes"] },+ shipmentLine: { events: true, statement: ["broadcast_table_changes"] },+ shippingMethod: { statement: ["broadcast_reference_changes"] },+ stockTransfer: { events: true, statement: ["broadcast_table_changes"] },+ stockTransferLine: {+ after: ["sync_update_stock_transfer_status"],+ events: true,+ statement: ["broadcast_table_changes"]+ },+ storageUnit: {+ before: [+ "storage_unit_enforce_same_location",+ "storage_unit_block_location_change_with_children",+ "storage_unit_enforce_no_cycle"+ ],+ events: true,+ statement: ["broadcast_reference_changes"]+ },+ supplier: {+ before: ["sync_update_supplier_type_group"],+ after: ["sync_create_supplier_entries", "sync_create_supplier_org_group"],+ events: true,+ statement: ["broadcast_table_changes", "log_table_changes"]+ },+ supplierAccount: {+ after: ["sync_add_supplier_account_to_group"],+ events: true+ },+ supplierContact: { statement: ["broadcast_reference_changes"] },+ supplierLocation: { statement: ["broadcast_reference_changes"] },+ supplierPart: { events: true },+ supplierPayment: { events: true },+ supplierProcess: { statement: ["broadcast_reference_changes"] },+ supplierQuote: { events: true, statement: ["broadcast_table_changes"] },+ supplierQuoteLine: { events: true, statement: ["broadcast_table_changes"] },+ supplierShipping: { events: true },+ supplierTax: { events: true },+ supplierType: {+ before: ["sync_update_supplier_type_group_name"],+ after: ["sync_create_supplier_type_group"],+ events: true,+ statement: ["broadcast_reference_changes"]+ },+ trackedActivity: { statement: ["broadcast_table_changes"] },+ trackedEntity: { statement: ["broadcast_table_changes"] },+ unitOfMeasure: { statement: ["broadcast_reference_changes"] },+ user: {+ after: [+ "sync_create_user_identity_group",+ "sync_update_user_identity_group",+ "sync_delete_user_identity_group"+ ],+ statement: ["log_user_changes"]+ },+ warehouseTransfer: { events: true, statement: ["broadcast_table_changes"] },+ warehouseTransferLine: {+ events: true,+ statement: ["broadcast_table_changes"]+ },+ webhook: { after: ["sync_webhook_subscription"], events: true },+ workCenter: { events: true, statement: ["broadcast_reference_changes"] },+ workCenterProcess: { events: true },+ workflowRun: { statement: ["broadcast_table_changes"] },+ workflowStepRun: { statement: ["broadcast_table_changes"] }+} as const satisfies Attachments;++export type AttachedTable = keyof typeof attachments;diff --git a/packages/database/src/event-system/functions/broadcast_reference_changes.sql b/packages/database/src/event-system/functions/broadcast_reference_changes.sqlnew file mode 100644index 0000000000..1de47dafce--- /dev/null+++ b/packages/database/src/event-system/functions/broadcast_reference_changes.sql@@ -0,0 +1,49 @@+CREATE OR REPLACE FUNCTION public.broadcast_reference_changes()+ RETURNS trigger+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO ''+AS $function$+DECLARE+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];+ changed_rows TEXT;+ rec RECORD;+BEGIN+ -- A database without Supabase Realtime (a self-hosted install that does not+ -- run it) has nothing to send to: the write must still succeed.+ IF to_regprocedure('realtime.send(jsonb,text,text,boolean)') IS NULL THEN+ RETURN NULL;+ END IF;++ -- Tells the company's clients that a reference list changed (one shared topic, company:<companyId>:reference).+ -- Statement-level (attach_statement_handler): one message per company per+ -- statement, whatever the row count. No row data leaves the database: a client+ -- re-reads what it needs through PostgREST, so table RLS still decides what it sees.+ IF TG_OP = 'UPDATE' THEN+ -- A row whose only changes are in ignored_columns drops out (the rule+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n+ EXCEPT+ SELECT to_jsonb(o) - $1 FROM batched_old o';+ ELSIF TG_OP = 'DELETE' THEN+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';+ ELSE+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';+ END IF;++ FOR rec IN EXECUTE format(+ 'SELECT DISTINCT c->>''companyId'' AS company_id FROM (%s) changed',+ changed_rows+ ) USING ignored_columns+ LOOP+ CONTINUE WHEN rec.company_id IS NULL;+ PERFORM realtime.send(+ jsonb_build_object('table', TG_TABLE_NAME, 'op', TG_OP),+ TG_OP,+ 'company:' || rec.company_id || ':reference',+ true+ );+ END LOOP;+ RETURN NULL;+END;+$function$;diff --git a/packages/database/src/event-system/functions/broadcast_table_changes.sql b/packages/database/src/event-system/functions/broadcast_table_changes.sqlnew file mode 100644index 0000000000..345ee5cc3f--- /dev/null+++ b/packages/database/src/event-system/functions/broadcast_table_changes.sql@@ -0,0 +1,168 @@+CREATE OR REPLACE FUNCTION public.broadcast_table_changes()+ RETURNS trigger+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO ''+AS $function$+DECLARE+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];+ -- Tables whose rows hang off a record through another table. Each hop is+ -- [column of the row, table it points at, column to read there]: its value is+ -- added to the message under that column's name, so a job page can follow+ -- "jobId" on a table that only knows its operation.+ -- A hop with a fourth element looks the other way: the rows of that table+ -- whose fourth column holds this row's value ("id" is the row's own id). A+ -- payment has no invoice column; its settlements name the invoices it pays.+ -- packages/database/src/realtime-tables.ts lists the same columns+ -- (REALTIME_ANCESTOR_COLUMNS; realtime-tables.test.ts keeps them equal).+ ancestors CONSTANT JSONB := '{+ "productionEvent": [["jobOperationId", "jobOperation", "jobId"]],+ "jobOperationStep": [["operationId", "jobOperation", "jobId"]],+ "jobOperationStepRecord": [["jobOperationStepId", "jobOperationStep", "operationId"], ["operationId", "jobOperation", "jobId"]],+ "trackedActivity": [["sourceDocumentId", "productionEvent", "jobOperationId"]],+ "payment": [["id", "invoiceSettlement", "targetSalesInvoiceId", "paymentId"], ["id", "invoiceSettlement", "targetPurchaseInvoiceId", "paymentId"]]+ }';+ changed_rows TEXT;+ parent_rows TEXT;+ parents JSONB;+ sent_columns TEXT[];+ found JSONB;+ hop JSONB;+ rec RECORD;+BEGIN+ -- A database without Supabase Realtime (a self-hosted install that does not+ -- run it) has nothing to send to: the write must still succeed.+ IF to_regprocedure('realtime.send(jsonb,text,text,boolean)') IS NULL THEN+ RETURN NULL;+ END IF;++ -- Tells the company's clients which rows of this table changed (topic company:<companyId>:<table>).+ -- Statement-level (attach_statement_handler): one message per company per+ -- statement, whatever the row count. No row data leaves the database: a client+ -- re-reads what it needs through PostgREST, so table RLS still decides what it sees.+ -- The columns a message may name: the table's foreign keys, and the columns+ -- its ancestors add. A column that merely ends in "Id" is the row's own data+ -- (a part number in "readableId", an order number, a tax id) and stays here.+ SELECT coalesce(array_agg(DISTINCT a.attname::text), ARRAY[]::text[])+ INTO sent_columns+ FROM pg_catalog.pg_constraint k+ JOIN pg_catalog.pg_attribute a+ ON a.attrelid = k.conrelid AND a.attnum = ANY (k.conkey)+ WHERE k.conrelid = TG_RELID AND k.contype = 'f';+ IF ancestors ? TG_TABLE_NAME THEN+ sent_columns := sent_columns || ARRAY(+ SELECT value->>2 FROM jsonb_array_elements(ancestors->TG_TABLE_NAME)+ );+ END IF;++ IF TG_OP = 'UPDATE' THEN+ -- A row whose only changes are in ignored_columns drops out (the rule+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n+ EXCEPT+ SELECT to_jsonb(o) - $1 FROM batched_old o';+ -- The rows as they were, too: a row moved to another parent concerns the+ -- parent it left as much as the one it joined.+ parent_rows := '(' || changed_rows || ')+ UNION ALL+ (SELECT to_jsonb(o) - $1 FROM batched_old o+ EXCEPT+ SELECT to_jsonb(n) - $1 FROM batched_new n)';+ ELSIF TG_OP = 'DELETE' THEN+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';+ parent_rows := changed_rows;+ ELSE+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';+ parent_rows := changed_rows;+ END IF;++ FOR rec IN EXECUTE format(+ -- implementationHub has no companyId: its id is the company id.+ 'WITH keyed AS (+ SELECT coalesce(c->>''companyId'',+ CASE WHEN $2::text = ''implementationHub'' THEN c->>''id'' END) AS company_id,+ c+ FROM (%1$s) changed+ ),+ related AS (+ SELECT coalesce(c->>''companyId'',+ CASE WHEN $2::text = ''implementationHub'' THEN c->>''id'' END) AS company_id,+ c+ FROM (%2$s) changed+ )+ SELECT k.company_id,+ count(*) AS n,+ -- itemSupersession has no id: its row belongs to the item it describes.+ jsonb_agg(coalesce(k.c->''id'', k.c->''itemId''))+ FILTER (WHERE k.c ? ''id'' OR k.c ? ''itemId'') AS ids,+ -- The records these rows belong to: each "<name>Id" column and its+ -- values (narrowed to the foreign keys before sending), so a page showing one job (or quote, or order) can ignore+ -- changes to another''s rows. A column with more than 20 values is+ -- left out, and a client treats a missing column as "may concern me".+ -- Only computed for a statement small enough to list its ids.+ CASE WHEN count(*) <= 100 THEN (+ SELECT jsonb_object_agg(p.key, p.vals)+ FROM (+ SELECT e.key, jsonb_agg(DISTINCT e.value) AS vals+ FROM related k2, jsonb_each(k2.c) e+ WHERE k2.company_id = k.company_id+ AND e.key LIKE ''%%Id'' AND e.key <> ''companyId''+ AND jsonb_typeof(e.value) = ''string''+ GROUP BY e.key+ HAVING count(DISTINCT e.value) <= 20+ ) p+ ) END AS parents+ FROM keyed k+ GROUP BY k.company_id',+ changed_rows, parent_rows+ ) USING ignored_columns, TG_TABLE_NAME+ LOOP+ CONTINUE WHEN rec.company_id IS NULL;++ parents := rec.parents;+ IF parents IS NOT NULL AND ancestors ? TG_TABLE_NAME THEN+ FOR hop IN SELECT value FROM jsonb_array_elements(ancestors->TG_TABLE_NAME) LOOP+ found := CASE WHEN hop->>0 = 'id' THEN rec.ids ELSE parents->(hop->>0) END;+ -- A column that was left out (no value, or too many) leaves its+ -- ancestor out as well: the client then takes the change as its own.+ CONTINUE WHEN found IS NULL;+ EXECUTE format(+ 'SELECT jsonb_agg(DISTINCT %1$I) FROM public.%2$I+ WHERE "companyId" = $1 AND %1$I IS NOT NULL+ AND %3$I IN (SELECT jsonb_array_elements_text($2))',+ hop->>2, hop->>1, coalesce(hop->>3, 'id')+ ) INTO found USING rec.company_id, found;+ IF found IS NOT NULL THEN+ parents := parents || jsonb_build_object(hop->>2, found);+ ELSIF jsonb_array_length(hop) = 4 THEN+ -- Looked for and not there: no such record has this row.+ parents := parents || jsonb_build_object(hop->>2, '[]'::jsonb);+ END IF;+ END LOOP;+ END IF;+ -- An ancestor hop may read a column that is not sent (a polymorphic+ -- "sourceDocumentId"), so the narrowing comes last.+ IF parents IS NOT NULL THEN+ parents := coalesce(+ (SELECT jsonb_object_agg(e.key, e.value)+ FROM jsonb_each(parents) e+ WHERE e.key = ANY (sent_columns)),+ '{}'::jsonb+ );+ END IF;+ PERFORM realtime.send(+ jsonb_build_object(+ 'table', TG_TABLE_NAME,+ 'op', TG_OP,+ -- null = "many rows changed, or the table has no id: resync"+ 'ids', CASE WHEN rec.n <= 100 THEN rec.ids END,+ 'parents', parents+ ),+ TG_OP,+ 'company:' || rec.company_id || ':' || TG_TABLE_NAME,+ true+ );+ END LOOP;+ RETURN NULL;+END;+$function$;diff --git a/packages/database/src/event-system/functions/broadcast_user_changes.sql b/packages/database/src/event-system/functions/broadcast_user_changes.sqlnew file mode 100644index 0000000000..b0c9e3b145--- /dev/null+++ b/packages/database/src/event-system/functions/broadcast_user_changes.sql@@ -0,0 +1,57 @@+CREATE OR REPLACE FUNCTION public.broadcast_user_changes()+ RETURNS trigger+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO ''+AS $function$+DECLARE+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];+ changed_rows TEXT;+ rec RECORD;+BEGIN+ -- A database without Supabase Realtime (a self-hosted install that does not+ -- run it) has nothing to send to: the write must still succeed.+ IF to_regprocedure('realtime.send(jsonb,text,text,boolean)') IS NULL THEN+ RETURN NULL;+ END IF;++ -- Tells one user which of their rows changed (topic user:<userId>:<table>).+ -- Statement-level (attach_statement_handler): one message per user per+ -- statement, whatever the row count. No row data leaves the database: a client+ -- re-reads what it needs through PostgREST, so table RLS still decides what it sees.+ IF TG_OP = 'UPDATE' THEN+ -- A row whose only changes are in ignored_columns drops out (the rule+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n+ EXCEPT+ SELECT to_jsonb(o) - $1 FROM batched_old o';+ ELSIF TG_OP = 'DELETE' THEN+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';+ ELSE+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';+ END IF;++ FOR rec IN EXECUTE format(+ 'SELECT c->>''userId'' AS user_id,+ count(*) AS n,+ jsonb_agg(c->''id'') FILTER (WHERE c ? ''id'') AS ids+ FROM (%s) changed+ GROUP BY 1',+ changed_rows+ ) USING ignored_columns+ LOOP+ CONTINUE WHEN rec.user_id IS NULL;+ PERFORM realtime.send(+ jsonb_build_object(+ 'table', TG_TABLE_NAME,+ 'op', TG_OP,+ 'ids', CASE WHEN rec.n <= 100 THEN rec.ids END+ ),+ TG_OP,+ 'user:' || rec.user_id || ':' || TG_TABLE_NAME,+ true+ );+ END LOOP;+ RETURN NULL;+END;+$function$;diff --git a/packages/database/src/event-system/functions/log_table_changes.sql b/packages/database/src/event-system/functions/log_table_changes.sqlnew file mode 100644index 0000000000..f833d9d91f--- /dev/null+++ b/packages/database/src/event-system/functions/log_table_changes.sql@@ -0,0 +1,45 @@+CREATE OR REPLACE FUNCTION public.log_table_changes()+ RETURNS trigger+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO ''+AS $function$+DECLARE+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];+ changed_rows TEXT;+BEGIN+ -- Records which rows of this table changed, in public."tableChange", so a+ -- client that kept a copy of a list can ask "what changed since I last+ -- looked?" (table_changes_since) and re-read only those rows instead of the+ -- whole table. A broadcast tells an open tab the same thing; this is for the+ -- tab that was closed, or disconnected, when it happened.+ IF TG_OP = 'UPDATE' THEN+ -- A row whose only changes are in ignored_columns drops out (the rule+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n+ EXCEPT+ SELECT to_jsonb(o) - $1 FROM batched_old o';+ ELSIF TG_OP = 'DELETE' THEN+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';+ ELSE+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';+ END IF;++ EXECUTE format(+ -- One log row per changed row. Past 100 rows in one statement, a single row+ -- with a null "rowId" says "this table changed a lot: read it again".+ -- itemSupersession has no id: its row belongs to the item it describes.+ 'INSERT INTO public."tableChange" ("companyId", "table", "rowId")+ SELECT DISTINCT company_id, $2::text, CASE WHEN n <= 100 THEN row_id END+ FROM (+ SELECT c->>''companyId'' AS company_id,+ coalesce(c->>''id'', c->>''itemId'') AS row_id,+ count(*) OVER (PARTITION BY c->>''companyId'') AS n+ FROM (%s) changed+ ) rows+ WHERE company_id IS NOT NULL',+ changed_rows+ ) USING ignored_columns, TG_TABLE_NAME;+ RETURN NULL;+END;+$function$;diff --git a/packages/database/src/event-system/functions/log_user_changes.sql b/packages/database/src/event-system/functions/log_user_changes.sqlnew file mode 100644index 0000000000..e756e62b64--- /dev/null+++ b/packages/database/src/event-system/functions/log_user_changes.sql@@ -0,0 +1,34 @@+CREATE OR REPLACE FUNCTION public.log_user_changes()+ RETURNS trigger+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO ''+AS $function$+DECLARE+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];+ changed_rows TEXT;+BEGIN+ -- A person's name and avatar live on the global "user" row, which has no+ -- company. Each company that person belongs to shows them in its people list+ -- (the employees view), so a change is logged once per company, as a change+ -- to that company's "employee" row.+ IF TG_OP = 'UPDATE' THEN+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n+ EXCEPT+ SELECT to_jsonb(o) - $1 FROM batched_old o';+ ELSIF TG_OP = 'DELETE' THEN+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';+ ELSE+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';+ END IF;++ EXECUTE format(+ 'INSERT INTO public."tableChange" ("companyId", "table", "rowId")+ SELECT DISTINCT m."companyId", ''employee'', changed.c->>''id''+ FROM (%s) changed+ JOIN public."userToCompany" m ON m."userId" = changed.c->>''id''',+ changed_rows+ ) USING ignored_columns;+ RETURN NULL;+END;+$function$;diff --git a/packages/database/src/event-system/functions/set_event_triggers.sql b/packages/database/src/event-system/functions/set_event_triggers.sqlnew file mode 100644index 0000000000..440e36c527--- /dev/null+++ b/packages/database/src/event-system/functions/set_event_triggers.sql@@ -0,0 +1,96 @@+CREATE OR REPLACE FUNCTION public.set_event_triggers(table_name_text text, before_functions text[] DEFAULT ARRAY[]::text[], after_functions text[] DEFAULT ARRAY[]::text[], queue_events boolean DEFAULT false, statement_functions text[] DEFAULT ARRAY[]::text[])+ RETURNS void+ LANGUAGE plpgsql+AS $function$+DECLARE+ existing TEXT;+ fn_args TEXT;+ live TEXT[];+ wanted TEXT[];+BEGIN+ -- Makes a table's event triggers exactly what one entry of+ -- packages/database/src/event-system/attachments.ts says: the interceptors+ -- that run before and after each row, whether changes are queued as events,+ -- and the statement handlers. Called with only the table name, it detaches+ -- everything.++ -- A table dropped since its entry was shipped has nothing to attach to.+ IF to_regclass(format('public.%I', table_name_text)) IS NULL THEN+ RETURN;+ END IF;++ -- Already as declared: touch nothing. Creating a trigger locks the table+ -- against writes until the transaction ends, so a migration that restates+ -- every table's entry must not re-create the ones that have not changed.+ SELECT coalesce(array_agg(t.tgname || ':' || encode(t.tgargs, 'escape') ORDER BY t.tgname), '{}')+ INTO live+ FROM pg_trigger t+ WHERE t.tgrelid = format('public.%I', table_name_text)::regclass+ AND NOT t.tgisinternal+ AND t.tgname LIKE 'trg\_event\_%';++ SELECT coalesce(array_agg(w.name ORDER BY w.name), '{}')+ INTO wanted+ FROM (+ -- A trigger's arguments are stored NUL-terminated; a name is cut at 63 bytes.+ SELECT left('trg_event_sync_' || table_name_text, 63) || ':'+ || array_to_string(before_functions, '\000') || '\000'+ WHERE cardinality(before_functions) > 0+ UNION ALL+ SELECT left('trg_event_after_sync_' || table_name_text, 63) || ':'+ || array_to_string(after_functions, '\000') || '\000'+ WHERE cardinality(after_functions) > 0+ UNION ALL+ SELECT left('trg_event_async_' || op || '_' || table_name_text, 63) || ':'+ FROM unnest(ARRAY['ins', 'del', 'upd']) op+ WHERE queue_events+ UNION ALL+ SELECT left('trg_event_statement_' || fn || '_' || op, 63) || ':'+ FROM unnest(statement_functions) fn, unnest(ARRAY['ins', 'upd', 'del']) op+ ) w(name);++ IF live = wanted THEN+ RETURN;+ END IF;++ IF queue_events THEN+ PERFORM public.attach_event_trigger(table_name_text, before_functions, after_functions);+ ELSE+ -- attach_event_trigger always queues, so here the row-level triggers are+ -- created alone, with the same definitions it uses.+ FOR existing IN+ SELECT t.tgname+ FROM pg_trigger t+ WHERE t.tgrelid = format('public.%I', table_name_text)::regclass+ AND NOT t.tgisinternal+ AND (t.tgname LIKE 'trg\_event\_sync\_%'+ OR t.tgname LIKE 'trg\_event\_after\_sync\_%'+ OR t.tgname LIKE 'trg\_event\_async\_%')+ LOOP+ EXECUTE format('DROP TRIGGER IF EXISTS %2$I ON public.%1$I;', table_name_text, existing);+ END LOOP;++ IF array_length(before_functions, 1) > 0 THEN+ SELECT string_agg(quote_literal(x), ', ') INTO fn_args FROM unnest(before_functions) x;+ EXECUTE format('+ CREATE TRIGGER "trg_event_sync_%1$s"+ BEFORE INSERT OR UPDATE OR DELETE ON public.%1$I+ FOR EACH ROW+ EXECUTE FUNCTION public.dispatch_event_interceptors(%2$s);+ ', table_name_text, fn_args);+ END IF;++ IF array_length(after_functions, 1) > 0 THEN+ SELECT string_agg(quote_literal(x), ', ') INTO fn_args FROM unnest(after_functions) x;+ EXECUTE format('+ CREATE TRIGGER "trg_event_after_sync_%1$s"+ AFTER INSERT OR UPDATE OR DELETE ON public.%1$I+ FOR EACH ROW+ EXECUTE FUNCTION public.dispatch_event_after_interceptors(%2$s);+ ', table_name_text, fn_args);+ END IF;+ END IF;++ PERFORM public.attach_statement_handler(table_name_text, statement_functions);+END;+$function$;diff --git a/packages/database/src/event-system/handlers/apply_item_stock_quantities.sql b/packages/database/src/event-system/handlers/apply_item_stock_quantities.sqlnew file mode 100644index 0000000000..dafa0e4ac1--- /dev/null+++ b/packages/database/src/event-system/handlers/apply_item_stock_quantities.sql@@ -0,0 +1,73 @@+CREATE OR REPLACE FUNCTION public.apply_item_stock_quantities()+ RETURNS trigger+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public', 'pg_temp'+AS $function$+BEGIN+ IF TG_OP = 'INSERT' THEN+ INSERT INTO "itemStockQuantities" AS isq+ ("itemId", "companyId", "locationId", "quantityOnHand")+ SELECT+ "itemId",+ "companyId",+ COALESCE("locationId", ''),+ SUM(item_ledger_on_hand_contribution("quantity", "trackedEntityStatus"))+ FROM batched_new+ GROUP BY "itemId", "companyId", COALESCE("locationId", '')+ ORDER BY 1, 2, 3+ ON CONFLICT ("itemId", "companyId", "locationId")+ DO UPDATE SET "quantityOnHand" = isq."quantityOnHand" + EXCLUDED."quantityOnHand";++ ELSIF TG_OP = 'UPDATE' THEN+ -- Generic old-vs-new: subtract every old row's contribution at its old key+ -- and add every new row's at its new key. Covers the real case (a+ -- trackedEntityStatus flip) and any future quantity/location/item edit+ -- without special-casing.+ INSERT INTO "itemStockQuantities" AS isq+ ("itemId", "companyId", "locationId", "quantityOnHand")+ SELECT "itemId", "companyId", "locationId", SUM(delta)+ FROM (+ SELECT+ "itemId",+ "companyId",+ COALESCE("locationId", '') AS "locationId",+ -item_ledger_on_hand_contribution("quantity", "trackedEntityStatus") AS delta+ FROM batched_old+ UNION ALL+ SELECT+ "itemId",+ "companyId",+ COALESCE("locationId", ''),+ item_ledger_on_hand_contribution("quantity", "trackedEntityStatus")+ FROM batched_new+ ) d+ GROUP BY "itemId", "companyId", "locationId"+ -- A key whose net delta is zero already holds the right number; skipping it+ -- avoids taking a lock on every row a wide UPDATE happened to touch.+ HAVING SUM(delta) <> 0+ ORDER BY 1, 2, 3+ ON CONFLICT ("itemId", "companyId", "locationId")+ DO UPDATE SET "quantityOnHand" = isq."quantityOnHand" + EXCLUDED."quantityOnHand";++ ELSIF TG_OP = 'DELETE' THEN+ -- Defensive: no application path deletes itemLedger rows today. A key left+ -- at zero with no backing ledger rows is removed by the nightly+ -- reconciliation.+ INSERT INTO "itemStockQuantities" AS isq+ ("itemId", "companyId", "locationId", "quantityOnHand")+ SELECT+ "itemId",+ "companyId",+ COALESCE("locationId", ''),+ -SUM(item_ledger_on_hand_contribution("quantity", "trackedEntityStatus"))+ FROM batched_old+ GROUP BY "itemId", "companyId", COALESCE("locationId", '')+ ORDER BY 1, 2, 3+ ON CONFLICT ("itemId", "companyId", "locationId")+ DO UPDATE SET "quantityOnHand" = isq."quantityOnHand" + EXCLUDED."quantityOnHand";+ END IF;++ RETURN NULL;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/prevent_posted_purchase_invoice_deletion.sql b/packages/database/src/event-system/handlers/prevent_posted_purchase_invoice_deletion.sqlnew file mode 100644index 0000000000..61b2ad755f--- /dev/null+++ b/packages/database/src/event-system/handlers/prevent_posted_purchase_invoice_deletion.sql@@ -0,0 +1,16 @@+CREATE OR REPLACE FUNCTION public.prevent_posted_purchase_invoice_deletion(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation = 'DELETE' THEN+ IF NOT EXISTS (SELECT 1 FROM "company" WHERE id = (p_old->>'companyId')) THEN+ RETURN;+ END IF;+ IF p_old->>'status' IS DISTINCT FROM 'Draft' THEN+ RAISE EXCEPTION 'Cannot delete purchase invoice with status "%". Only Draft invoices can be deleted.', p_old->>'status';+ END IF;+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/prevent_posted_sales_invoice_deletion.sql b/packages/database/src/event-system/handlers/prevent_posted_sales_invoice_deletion.sqlnew file mode 100644index 0000000000..7afae2f17a--- /dev/null+++ b/packages/database/src/event-system/handlers/prevent_posted_sales_invoice_deletion.sql@@ -0,0 +1,16 @@+CREATE OR REPLACE FUNCTION public.prevent_posted_sales_invoice_deletion(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation = 'DELETE' THEN+ IF NOT EXISTS (SELECT 1 FROM "company" WHERE id = (p_old->>'companyId')) THEN+ RETURN;+ END IF;+ IF p_old->>'status' IS DISTINCT FROM 'Draft' THEN+ RAISE EXCEPTION 'Cannot delete sales invoice with status "%". Only Draft invoices can be deleted.', p_old->>'status';+ END IF;+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/set_shelf_life_on_operation_done.sql b/packages/database/src/event-system/handlers/set_shelf_life_on_operation_done.sqlnew file mode 100644index 0000000000..e34aab407f--- /dev/null+++ b/packages/database/src/event-system/handlers/set_shelf_life_on_operation_done.sql@@ -0,0 +1,26 @@+CREATE OR REPLACE FUNCTION public.set_shelf_life_on_operation_done(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_old_status TEXT;+ v_new_status TEXT;+BEGIN+ IF p_operation <> 'UPDATE' THEN+ RETURN;+ END IF;++ v_new_status := p_new->>'status';+ IF v_new_status <> 'Done' THEN+ RETURN;+ END IF;++ v_old_status := p_old->>'status';+ IF v_old_status = 'Done' THEN+ RETURN;+ END IF;++ PERFORM set_shelf_life_for_operation(p_new->>'id', 'After');+END;+$function$;diff --git a/packages/database/src/event-system/handlers/set_shelf_life_on_operation_started.sql b/packages/database/src/event-system/handlers/set_shelf_life_on_operation_started.sqlnew file mode 100644index 0000000000..7d2df251a4--- /dev/null+++ b/packages/database/src/event-system/handlers/set_shelf_life_on_operation_started.sql@@ -0,0 +1,26 @@+CREATE OR REPLACE FUNCTION public.set_shelf_life_on_operation_started(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_old_status TEXT;+ v_new_status TEXT;+BEGIN+ IF p_operation <> 'UPDATE' THEN+ RETURN;+ END IF;++ v_new_status := p_new->>'status';+ IF v_new_status <> 'In Progress' THEN+ RETURN;+ END IF;++ v_old_status := p_old->>'status';+ IF v_old_status = 'In Progress' THEN+ RETURN;+ END IF;++ PERFORM set_shelf_life_for_operation(p_new->>'id', 'Before');+END;+$function$;diff --git a/packages/database/src/event-system/handlers/storage_unit_block_location_change_with_children.sql b/packages/database/src/event-system/handlers/storage_unit_block_location_change_with_children.sqlnew file mode 100644index 0000000000..b56e97e322--- /dev/null+++ b/packages/database/src/event-system/handlers/storage_unit_block_location_change_with_children.sql@@ -0,0 +1,30 @@+CREATE OR REPLACE FUNCTION public.storage_unit_block_location_change_with_children(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_id TEXT;+ v_new_location TEXT;+ v_old_location TEXT;+BEGIN+ IF p_operation <> 'UPDATE' THEN+ RETURN;+ END IF;++ v_new_location := p_new->>'locationId';+ v_old_location := p_old->>'locationId';++ IF v_new_location IS NOT DISTINCT FROM v_old_location THEN+ RETURN;+ END IF;++ v_id := p_old->>'id';++ IF EXISTS (SELECT 1 FROM "storageUnit" WHERE "parentId" = v_id) THEN+ RAISE EXCEPTION+ 'Cannot change locationId of storage unit % because it has child units',+ v_id;+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/storage_unit_enforce_no_cycle.sql b/packages/database/src/event-system/handlers/storage_unit_enforce_no_cycle.sqlnew file mode 100644index 0000000000..890c1a7568--- /dev/null+++ b/packages/database/src/event-system/handlers/storage_unit_enforce_no_cycle.sql@@ -0,0 +1,37 @@+CREATE OR REPLACE FUNCTION public.storage_unit_enforce_no_cycle(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_self_id TEXT;+ v_cursor_id TEXT;+ v_depth INTEGER := 0;+BEGIN+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN+ RETURN;+ END IF;++ v_cursor_id := p_new->>'parentId';+ IF v_cursor_id IS NULL THEN+ RETURN;+ END IF;++ v_self_id := p_new->>'id';++ WHILE v_cursor_id IS NOT NULL LOOP+ IF v_cursor_id = v_self_id THEN+ RAISE EXCEPTION 'Cycle detected in storage unit hierarchy at %', v_self_id;+ END IF;++ v_depth := v_depth + 1;+ IF v_depth > 1000 THEN+ RAISE EXCEPTION 'Storage unit hierarchy exceeds max depth (possible cycle)';+ END IF;++ SELECT "parentId" INTO v_cursor_id+ FROM "storageUnit"+ WHERE "id" = v_cursor_id;+ END LOOP;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/storage_unit_enforce_same_location.sql b/packages/database/src/event-system/handlers/storage_unit_enforce_same_location.sqlnew file mode 100644index 0000000000..1144d953c3--- /dev/null+++ b/packages/database/src/event-system/handlers/storage_unit_enforce_same_location.sql@@ -0,0 +1,37 @@+CREATE OR REPLACE FUNCTION public.storage_unit_enforce_same_location(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_parent_id TEXT;+ v_parent_location TEXT;+ v_new_location TEXT;+BEGIN+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN+ RETURN;+ END IF;++ v_parent_id := p_new->>'parentId';+ IF v_parent_id IS NULL THEN+ RETURN;+ END IF;++ v_new_location := p_new->>'locationId';++ SELECT "locationId"+ INTO v_parent_location+ FROM "storageUnit"+ WHERE "id" = v_parent_id;++ IF v_parent_location IS NULL THEN+ RAISE EXCEPTION 'Parent storage unit % does not exist', v_parent_id;+ END IF;++ IF v_parent_location <> v_new_location THEN+ RAISE EXCEPTION+ 'Parent storage unit % is in location %, but this unit is in location %; they must match',+ v_parent_id, v_parent_location, v_new_location;+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_add_customer_account_to_group.sql b/packages/database/src/event-system/handlers/sync_add_customer_account_to_group.sqlnew file mode 100644index 0000000000..30636eef93--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_add_customer_account_to_group.sql@@ -0,0 +1,15 @@+CREATE OR REPLACE FUNCTION public.sync_add_customer_account_to_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "membership" ("groupId", "memberUserId")+ VALUES (+ p_new->>'customerId',+ p_new->>'id'+ );+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_add_employee_to_type_group.sql b/packages/database/src/event-system/handlers/sync_add_employee_to_type_group.sqlnew file mode 100644index 0000000000..43bfc0aed8--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_add_employee_to_type_group.sql@@ -0,0 +1,15 @@+CREATE OR REPLACE FUNCTION public.sync_add_employee_to_type_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "membership" ("groupId", "memberUserId")+ VALUES (+ p_new->>'employeeTypeId',+ p_new->>'id'+ );+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_add_supplier_account_to_group.sql b/packages/database/src/event-system/handlers/sync_add_supplier_account_to_group.sqlnew file mode 100644index 0000000000..eb63500c14--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_add_supplier_account_to_group.sql@@ -0,0 +1,15 @@+CREATE OR REPLACE FUNCTION public.sync_add_supplier_account_to_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "membership" ("groupId", "memberUserId")+ VALUES (+ p_new->>'supplierId',+ p_new->>'id'+ );+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_address_to_parent.sql b/packages/database/src/event-system/handlers/sync_address_to_parent.sqlnew file mode 100644index 0000000000..ad8b43adba--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_address_to_parent.sql@@ -0,0 +1,31 @@+CREATE OR REPLACE FUNCTION public.sync_address_to_parent(table_name text, operation text, new_data jsonb, old_data jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ address_id TEXT;+BEGIN+ IF operation = 'DELETE' THEN+ RETURN;+ END IF;++ IF current_setting('app.sync_in_progress', true) = 'true' THEN+ RETURN;+ END IF;++ address_id := COALESCE(new_data->>'id', old_data->>'id');++ UPDATE "customer" c+ SET "updatedAt" = NOW()+ FROM "customerLocation" cl+ WHERE cl."addressId" = address_id+ AND cl."customerId" = c.id;++ UPDATE "supplier" s+ SET "updatedAt" = NOW()+ FROM "supplierLocation" sl+ WHERE sl."addressId" = address_id+ AND sl."supplierId" = s.id;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_archive_other_procedures.sql b/packages/database/src/event-system/handlers/sync_archive_other_procedures.sqlnew file mode 100644index 0000000000..7d89889172--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_archive_other_procedures.sql@@ -0,0 +1,19 @@+CREATE OR REPLACE FUNCTION public.sync_archive_other_procedures(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF NOT ((p_new->>'status') = 'Active' AND ((p_old->>'status') IS NULL OR (p_old->>'status') != 'Active')) THEN+ RETURN;+ END IF;++ UPDATE procedure+ SET status = 'Archived'+ WHERE name = p_new->>'name'+ AND "companyId" = p_new->>'companyId'+ AND id != p_new->>'id'+ AND status = 'Active';+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_archive_other_quality_documents.sql b/packages/database/src/event-system/handlers/sync_archive_other_quality_documents.sqlnew file mode 100644index 0000000000..f7c5b020d9--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_archive_other_quality_documents.sql@@ -0,0 +1,19 @@+CREATE OR REPLACE FUNCTION public.sync_archive_other_quality_documents(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF NOT ((p_new->>'status') = 'Active' AND ((p_old->>'status') IS NULL OR (p_old->>'status') != 'Active')) THEN+ RETURN;+ END IF;++ UPDATE "qualityDocument"+ SET status = 'Archived'+ WHERE name = p_new->>'name'+ AND "companyId" = p_new->>'companyId'+ AND id != p_new->>'id'+ AND status = 'Active';+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_check_job_material_self_reference.sql b/packages/database/src/event-system/handlers/sync_check_job_material_self_reference.sqlnew file mode 100644index 0000000000..05198a6d5a--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_check_job_material_self_reference.sql@@ -0,0 +1,21 @@+CREATE OR REPLACE FUNCTION public.sync_check_job_material_self_reference(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'pg_temp'+AS $function$+DECLARE+ job_item_id TEXT;+BEGIN+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN RETURN; END IF;++ SELECT "itemId" INTO job_item_id+ FROM job+ WHERE "id" = p_new->>'jobId'+ AND "companyId" = p_new->>'companyId';++ IF job_item_id = p_new->>'itemId' THEN+ RAISE EXCEPTION 'A job cannot consume the item it produces as a material'+ USING ERRCODE = 'check_violation';+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_check_method_material_self_reference.sql b/packages/database/src/event-system/handlers/sync_check_method_material_self_reference.sqlnew file mode 100644index 0000000000..7f79410bd2--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_check_method_material_self_reference.sql@@ -0,0 +1,55 @@+CREATE OR REPLACE FUNCTION public.sync_check_method_material_self_reference(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'pg_temp'+AS $function$+DECLARE+ parent_item_id TEXT;+ cycle_found BOOLEAN;+BEGIN+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN RETURN; END IF;++ -- A make method belongs to exactly one item, so a materialMakeMethodId equal+ -- to the row's own makeMethodId is always a self-loop regardless of itemId.+ IF p_new->>'materialMakeMethodId' = p_new->>'makeMethodId' THEN+ RAISE EXCEPTION 'An item cannot use its own make method as a material sub-method'+ USING ERRCODE = 'check_violation';+ END IF;++ SELECT "itemId" INTO parent_item_id+ FROM "makeMethod"+ WHERE "id" = p_new->>'makeMethodId'+ AND "companyId" = p_new->>'companyId';++ IF parent_item_id = p_new->>'itemId' THEN+ RAISE EXCEPTION 'An item cannot be a material on its own bill of materials'+ USING ERRCODE = 'check_violation';+ END IF;++ -- Multi-node cycles (A needs B, B needs A): would the new material's own+ -- active-method BOM graph reach back to this method's item? Bounded walk+ -- over active methods only — the graph MRP plans against. UNION (not UNION+ -- ALL) dedupes, so the walk terminates even over pre-existing cycles; the+ -- depth cap is a backstop. BOM edits are UI-volume, so the walk is cheap.+ WITH RECURSIVE reachable AS (+ SELECT p_new->>'itemId' AS item_id, 0 AS depth+ UNION+ SELECT mm."itemId", r.depth + 1+ FROM reachable r+ JOIN "activeMakeMethods" amm+ ON amm."itemId" = r.item_id+ AND amm."companyId" = p_new->>'companyId'+ JOIN "methodMaterial" mm+ ON mm."makeMethodId" = amm."id"+ AND mm."companyId" = amm."companyId"+ WHERE r.depth < 100+ )+ SELECT EXISTS (SELECT 1 FROM reachable WHERE item_id = parent_item_id)+ INTO cycle_found;++ IF cycle_found THEN+ RAISE EXCEPTION 'Adding this material would create a loop in the bill of materials: its own BOM already contains this item'+ USING ERRCODE = 'check_violation';+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_contact_to_parent.sql b/packages/database/src/event-system/handlers/sync_contact_to_parent.sqlnew file mode 100644index 0000000000..91dab50da0--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_contact_to_parent.sql@@ -0,0 +1,31 @@+CREATE OR REPLACE FUNCTION public.sync_contact_to_parent(table_name text, operation text, new_data jsonb, old_data jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ contact_id TEXT;+BEGIN+ IF operation = 'DELETE' THEN+ RETURN;+ END IF;++ IF current_setting('app.sync_in_progress', true) = 'true' THEN+ RETURN;+ END IF;++ contact_id := COALESCE(new_data->>'id', old_data->>'id');++ UPDATE "customer" c+ SET "updatedAt" = NOW()+ FROM "customerContact" cc+ WHERE cc."contactId" = contact_id+ AND cc."customerId" = c.id;++ UPDATE "supplier" s+ SET "updatedAt" = NOW()+ FROM "supplierContact" sc+ WHERE sc."contactId" = contact_id+ AND sc."supplierId" = s.id;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_create_customer_entries.sql b/packages/database/src/event-system/handlers/sync_create_customer_entries.sqlnew file mode 100644index 0000000000..804e344aff--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_create_customer_entries.sql@@ -0,0 +1,18 @@+CREATE OR REPLACE FUNCTION public.sync_create_customer_entries(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "customerPayment"("customerId", "invoiceCustomerId", "companyId")+ VALUES (p_new->>'id', p_new->>'id', p_new->>'companyId');++ INSERT INTO "customerShipping"("customerId", "shippingCustomerId", "companyId")+ VALUES (p_new->>'id', p_new->>'id', p_new->>'companyId');++ INSERT INTO "customerTax"("customerId", "companyId")+ VALUES (p_new->>'id', p_new->>'companyId');+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_create_customer_org_group.sql b/packages/database/src/event-system/handlers/sync_create_customer_org_group.sqlnew file mode 100644index 0000000000..4af31ed5b9--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_create_customer_org_group.sql@@ -0,0 +1,17 @@+CREATE OR REPLACE FUNCTION public.sync_create_customer_org_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "group" ("id", "name", "isCustomerOrgGroup", "companyId")+ VALUES (p_new->>'id', p_new->>'name', TRUE, p_new->>'companyId');++ IF p_new->>'customerTypeId' IS NOT NULL THEN+ INSERT INTO "membership"("groupId", "memberGroupId")+ VALUES (p_new->>'customerTypeId', p_new->>'id');+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_create_customer_type_group.sql b/packages/database/src/event-system/handlers/sync_create_customer_type_group.sqlnew file mode 100644index 0000000000..8e7926c8ee--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_create_customer_type_group.sql@@ -0,0 +1,26 @@+CREATE OR REPLACE FUNCTION public.sync_create_customer_type_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "group" ("id", "name", "isCustomerTypeGroup", "companyId")+ VALUES (+ p_new->>'id',+ p_new->>'name',+ TRUE,+ p_new->>'companyId'+ );++ INSERT INTO "membership" ("groupId", "memberGroupId")+ VALUES (+ '11111111-1111-'+ || substring((p_new->>'companyId')::text, 1, 4) || '-'+ || substring((p_new->>'companyId')::text, 5, 4) || '-'+ || substring((p_new->>'companyId')::text, 9, 12),+ p_new->>'id'+ );+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_create_employee_type_group.sql b/packages/database/src/event-system/handlers/sync_create_employee_type_group.sqlnew file mode 100644index 0000000000..029ddb0a85--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_create_employee_type_group.sql@@ -0,0 +1,26 @@+CREATE OR REPLACE FUNCTION public.sync_create_employee_type_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "group" ("id", "name", "isEmployeeTypeGroup", "companyId")+ VALUES (+ p_new->>'id',+ p_new->>'name',+ TRUE,+ p_new->>'companyId'+ );++ INSERT INTO "membership" ("groupId", "memberGroupId")+ VALUES (+ '00000000-0000-'+ || substring((p_new->>'companyId')::text, 1, 4) || '-'+ || substring((p_new->>'companyId')::text, 5, 4) || '-'+ || substring((p_new->>'companyId')::text, 9, 12),+ p_new->>'id'+ );+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_create_item_related_records.sql b/packages/database/src/event-system/handlers/sync_create_item_related_records.sqlnew file mode 100644index 0000000000..0ba4eb4c88--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_create_item_related_records.sql@@ -0,0 +1,34 @@+CREATE OR REPLACE FUNCTION public.sync_create_item_related_records(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ base_currency TEXT;+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ SELECT "baseCurrencyCode"+ INTO base_currency+ FROM "company"+ WHERE "id" = p_new->>'companyId';++ INSERT INTO "itemCost"("itemId", "costingMethod", "createdBy", "companyId")+ VALUES (p_new->>'id', 'FIFO', p_new->>'createdBy', p_new->>'companyId');++ INSERT INTO "itemReplenishment"("itemId", "createdBy", "companyId")+ VALUES (p_new->>'id', p_new->>'createdBy', p_new->>'companyId');++ INSERT INTO "itemUnitSalePrice"("itemId", "currencyCode", "createdBy", "companyId")+ VALUES (p_new->>'id', COALESCE(base_currency, 'USD'), p_new->>'createdBy', p_new->>'companyId');++ INSERT INTO "itemPlanning"("itemId", "locationId", "createdBy", "companyId")+ SELECT+ p_new->>'id',+ l.id,+ p_new->>'createdBy',+ p_new->>'companyId'+ FROM "location" l+ WHERE l."companyId" = p_new->>'companyId';+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_create_location_related_records.sql b/packages/database/src/event-system/handlers/sync_create_location_related_records.sqlnew file mode 100644index 0000000000..e428116982--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_create_location_related_records.sql@@ -0,0 +1,22 @@+CREATE OR REPLACE FUNCTION public.sync_create_location_related_records(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ -- Only create itemPlanning records for the new location+ -- Skip the postingGroupInventory inserts since that table no longer exists+ INSERT INTO "itemPlanning" ("itemId", "locationId", "createdBy", "companyId", "createdAt", "updatedAt")+ SELECT+ i.id AS "itemId",+ p_new->>'id' AS "locationId",+ i."createdBy",+ i."companyId",+ NOW(),+ NOW()+ FROM "item" i+ WHERE i."companyId" = p_new->>'companyId';+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_create_make_method_related_records.sql b/packages/database/src/event-system/handlers/sync_create_make_method_related_records.sqlnew file mode 100644index 0000000000..9807494f54--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_create_make_method_related_records.sql@@ -0,0 +1,14 @@+CREATE OR REPLACE FUNCTION public.sync_create_make_method_related_records(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ IF (p_new->>'type') IN ('Part', 'Tool', 'Service') THEN+ INSERT INTO "makeMethod"("itemId", "createdBy", "companyId")+ VALUES (p_new->>'id', p_new->>'createdBy', p_new->>'companyId');+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_create_nc_external_link.sql b/packages/database/src/event-system/handlers/sync_create_nc_external_link.sqlnew file mode 100644index 0000000000..e4ece50daf--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_create_nc_external_link.sql@@ -0,0 +1,21 @@+CREATE OR REPLACE FUNCTION public.sync_create_nc_external_link(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_external_link_id UUID;+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "externalLink" ("documentType", "documentId", "companyId")+ VALUES ('Non-Conformance Supplier', p_new->>'id', p_new->>'companyId')+ ON CONFLICT ("documentId", "documentType", "companyId") DO UPDATE SET+ "documentType" = EXCLUDED."documentType"+ RETURNING "id" INTO v_external_link_id;++ UPDATE "nonConformanceSupplier"+ SET "externalLinkId" = v_external_link_id+ WHERE "id" = p_new->>'id';+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_create_supplier_entries.sql b/packages/database/src/event-system/handlers/sync_create_supplier_entries.sqlnew file mode 100644index 0000000000..ee417b631f--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_create_supplier_entries.sql@@ -0,0 +1,18 @@+CREATE OR REPLACE FUNCTION public.sync_create_supplier_entries(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "supplierPayment"("supplierId", "invoiceSupplierId", "companyId")+ VALUES (p_new->>'id', p_new->>'id', p_new->>'companyId');++ INSERT INTO "supplierShipping"("supplierId", "shippingSupplierId", "companyId")+ VALUES (p_new->>'id', p_new->>'id', p_new->>'companyId');++ INSERT INTO "supplierTax"("supplierId", "companyId")+ VALUES (p_new->>'id', p_new->>'companyId');+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_create_supplier_org_group.sql b/packages/database/src/event-system/handlers/sync_create_supplier_org_group.sqlnew file mode 100644index 0000000000..1944a1d734--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_create_supplier_org_group.sql@@ -0,0 +1,17 @@+CREATE OR REPLACE FUNCTION public.sync_create_supplier_org_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "group" ("id", "name", "isSupplierOrgGroup", "companyId")+ VALUES (p_new->>'id', p_new->>'name', TRUE, p_new->>'companyId');++ IF p_new->>'supplierTypeId' IS NOT NULL THEN+ INSERT INTO "membership"("groupId", "memberGroupId")+ VALUES (p_new->>'supplierTypeId', p_new->>'id');+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_create_supplier_type_group.sql b/packages/database/src/event-system/handlers/sync_create_supplier_type_group.sqlnew file mode 100644index 0000000000..902726923e--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_create_supplier_type_group.sql@@ -0,0 +1,26 @@+CREATE OR REPLACE FUNCTION public.sync_create_supplier_type_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "group" ("id", "name", "isSupplierTypeGroup", "companyId")+ VALUES (+ p_new->>'id',+ p_new->>'name',+ TRUE,+ p_new->>'companyId'+ );++ INSERT INTO "membership" ("groupId", "memberGroupId")+ VALUES (+ '22222222-2222-'+ || substring((p_new->>'companyId')::text, 1, 4) || '-'+ || substring((p_new->>'companyId')::text, 5, 4) || '-'+ || substring((p_new->>'companyId')::text, 9, 12),+ p_new->>'id'+ );+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_create_user_identity_group.sql b/packages/database/src/event-system/handlers/sync_create_user_identity_group.sqlnew file mode 100644index 0000000000..1318c971ad--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_create_user_identity_group.sql@@ -0,0 +1,22 @@+CREATE OR REPLACE FUNCTION public.sync_create_user_identity_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "group" ("id", "name", "isIdentityGroup")+ VALUES (+ p_new->>'id',+ p_new->>'fullName',+ TRUE+ );++ INSERT INTO "membership" ("groupId", "memberUserId")+ VALUES (+ p_new->>'id',+ p_new->>'id'+ );+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_delete_tracked_entity_on_job_make_method.sql b/packages/database/src/event-system/handlers/sync_delete_tracked_entity_on_job_make_method.sqlnew file mode 100644index 0000000000..2d87609c15--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_delete_tracked_entity_on_job_make_method.sql@@ -0,0 +1,12 @@+CREATE OR REPLACE FUNCTION public.sync_delete_tracked_entity_on_job_make_method(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'DELETE' THEN RETURN; END IF;++ DELETE FROM "trackedEntity"+ WHERE "attributes"->>'Job Make Method' = p_old->>'id';+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_delete_user_identity_group.sql b/packages/database/src/event-system/handlers/sync_delete_user_identity_group.sqlnew file mode 100644index 0000000000..46b9129990--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_delete_user_identity_group.sql@@ -0,0 +1,13 @@+CREATE OR REPLACE FUNCTION public.sync_delete_user_identity_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'DELETE' THEN RETURN; END IF;++ DELETE FROM "group"+ WHERE "id" = p_old->>'id'+ AND "isIdentityGroup" = TRUE;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_edit_document_transaction.sql b/packages/database/src/event-system/handlers/sync_edit_document_transaction.sqlnew file mode 100644index 0000000000..6017b61cc4--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_edit_document_transaction.sql@@ -0,0 +1,12 @@+CREATE OR REPLACE FUNCTION public.sync_edit_document_transaction(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ INSERT INTO "documentTransaction" ("documentId", "type", "userId")+ VALUES (p_new->>'id', 'Edit', p_new->>'createdBy');+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_finish_job_operation.sql b/packages/database/src/event-system/handlers/sync_finish_job_operation.sqlnew file mode 100644index 0000000000..3ed5344dac--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_finish_job_operation.sql@@ -0,0 +1,121 @@+CREATE OR REPLACE FUNCTION public.sync_finish_job_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+DECLARE+ v_job_location_id TEXT;+ v_job_storage_unit_id TEXT;+ v_job_quantity NUMERIC;+ v_sales_order_id TEXT;+ v_quantity_complete NUMERIC;+ v_quantity_lost NUMERIC;+ v_quantity_received NUMERIC;+ v_job_status TEXT;+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF (p_new->>'status') != 'Done' OR (p_old->>'status') = 'Done' THEN RETURN; END IF;++ UPDATE "productionEvent"+ SET "endTime" = NOW()+ WHERE "jobOperationId" = p_new->>'id'+ AND "endTime" IS NULL;++ UPDATE "jobOperation" op+ SET status = 'Ready'+ WHERE EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ WHERE dep."operationId" = op.id+ AND dep."dependsOnId" = p_new->>'id'+ AND op.status = 'Waiting'+ )+ AND NOT EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep2+ JOIN "jobOperation" jo2 ON jo2.id = dep2."dependsOnId"+ WHERE dep2."operationId" = op.id+ AND jo2.status != 'Done'+ AND jo2.id != p_new->>'id'+ );++ SELECT status INTO v_job_status FROM "job" WHERE id = p_new->>'jobId';+ -- A Draft/Planned job's operation can only reach Done through a released+ -- BATCH (batch release outranks job release for floor visibility), so the+ -- run genuinely happened. Completing the batch must complete those jobs+ -- too: otherwise their output lots exist while their receipts never post,+ -- and a merged output lot carries only the received fraction of its+ -- quantity.+ IF v_job_status NOT IN ('Ready', 'In Progress', 'Paused')+ AND NOT (+ (p_new->>'jobOperationBatchId') IS NOT NULL+ AND v_job_status IN ('Draft', 'Planned')+ ) THEN+ RETURN;+ END IF;++ IF is_last_job_operation(p_new->>'id') THEN+ SELECT "locationId", "storageUnitId", quantity, "salesOrderId", "quantityReceivedToInventory"+ INTO v_job_location_id, v_job_storage_unit_id, v_job_quantity, v_sales_order_id, v_quantity_received+ FROM "job"+ WHERE id = p_new->>'jobId';++ v_quantity_complete := (+ SELECT COALESCE(SUM(terminal_jo."quantityComplete"), 0)+ FROM "jobOperation" terminal_jo+ INNER JOIN "jobMakeMethod" terminal_jmm ON terminal_jmm.id = terminal_jo."jobMakeMethodId"+ WHERE terminal_jo."jobId" = p_new->>'jobId'+ AND terminal_jmm."parentMaterialId" IS NULL+ AND NOT EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ INNER JOIN "jobOperation" child_jo ON child_jo.id = dep."operationId"+ INNER JOIN "jobMakeMethod" child_jmm ON child_jmm.id = child_jo."jobMakeMethodId"+ WHERE dep."dependsOnId" = terminal_jo.id+ AND child_jmm."parentMaterialId" IS NULL+ )+ );++ IF COALESCE(v_quantity_complete, 0) = 0 THEN+ -- The zero fallback exists for the quantity-less Finish flow (no+ -- productionQuantity ever recorded). When the job DID record scrap or+ -- rework, zero completions is a real outcome (e.g. a fully-scrapped+ -- lot) — falling back would receive scrapped units into stock.+ SELECT COALESCE(SUM(COALESCE("quantityScrapped", 0) + COALESCE("quantityReworked", 0)), 0)+ INTO v_quantity_lost+ FROM "jobOperation"+ WHERE "jobId" = p_new->>'jobId';++ IF v_quantity_lost = 0 THEN+ v_quantity_complete := v_job_quantity;+ ELSE+ -- Nothing to receive: close the job without posting Assembly Output.+ -- Materials were already consumed by the scrap/complete flows; WIP+ -- cost disposition for fully-scrapped jobs is a costing follow-up.+ UPDATE "job"+ SET status = 'Completed',+ "completedDate" = NOW(),+ "quantityComplete" = 0,+ "updatedBy" = COALESCE(p_new->>'updatedBy', p_new->>'createdBy'),+ "updatedAt" = NOW()+ WHERE id = p_new->>'jobId';+ RETURN;+ END IF;+ END IF;++ -- A reopened job may already have received more than its operations now+ -- report. complete_job_to_inventory refuses a quantity below what was+ -- received, and refusing here would block the Done update itself.+ v_quantity_complete := GREATEST(v_quantity_complete, COALESCE(v_quantity_received, 0));++ PERFORM complete_job_to_inventory(+ p_job_id := p_new->>'jobId',+ p_quantity_complete := v_quantity_complete,+ p_storage_unit_id := v_job_storage_unit_id,+ p_location_id := v_job_location_id,+ p_company_id := p_new->>'companyId',+ p_user_id := COALESCE(p_new->>'updatedBy', p_new->>'createdBy')+ );+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_insert_company_related_records.sql b/packages/database/src/event-system/handlers/sync_insert_company_related_records.sqlnew file mode 100644index 0000000000..0b7d1eb00c--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_insert_company_related_records.sql@@ -0,0 +1,15 @@+CREATE OR REPLACE FUNCTION public.sync_insert_company_related_records(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "terms" ("id")+ VALUES (p_new->>'id');++ INSERT INTO "companySettings" ("id")+ VALUES (p_new->>'id');+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_insert_job_make_method.sql b/packages/database/src/event-system/handlers/sync_insert_job_make_method.sqlnew file mode 100644index 0000000000..d44a6ec1f0--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_insert_job_make_method.sql@@ -0,0 +1,38 @@+CREATE OR REPLACE FUNCTION public.sync_insert_job_make_method(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_item_readable_id TEXT;+ v_item_tracking_type TEXT;+ v_job_make_method_id TEXT;+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ SELECT "readableIdWithRevision", "itemTrackingType"+ INTO v_item_readable_id, v_item_tracking_type+ FROM "item"+ WHERE "id" = p_new->>'itemId';++ INSERT INTO "jobMakeMethod" (+ "jobId", "itemId", "companyId", "createdBy",+ "requiresSerialTracking", "requiresBatchTracking"+ ) VALUES (+ p_new->>'id', p_new->>'itemId', p_new->>'companyId', p_new->>'createdBy',+ v_item_tracking_type = 'Serial', v_item_tracking_type = 'Batch'+ )+ RETURNING "id" INTO v_job_make_method_id;++ INSERT INTO "trackedEntity" (+ "sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",+ "quantity", "status", "companyId", "createdBy", "attributes", "itemId"+ ) VALUES (+ 'Item', p_new->>'itemId', v_item_readable_id,+ COALESCE((p_new->>'quantity')::numeric, 1), 'Reserved',+ p_new->>'companyId', p_new->>'createdBy',+ jsonb_build_object('Job', p_new->>'id', 'Job Make Method', v_job_make_method_id),+ p_new->>'itemId'+ );+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_insert_job_material_make_method.sql b/packages/database/src/event-system/handlers/sync_insert_job_material_make_method.sqlnew file mode 100644index 0000000000..1597b1f002--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_insert_job_material_make_method.sql@@ -0,0 +1,43 @@+CREATE OR REPLACE FUNCTION public.sync_insert_job_material_make_method(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_item_readable_id TEXT;+ v_item_tracking_type TEXT;+ v_job_make_method_id TEXT;+ v_version NUMERIC(10, 2);+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;+ IF (p_new->>'methodType') != 'Make to Order' THEN RETURN; END IF;+ IF (p_new->>'itemId') IS NULL THEN RETURN; END IF;++ SELECT "readableIdWithRevision", "itemTrackingType"+ INTO v_item_readable_id, v_item_tracking_type+ FROM "item"+ WHERE "id" = p_new->>'itemId';++ SELECT "version" INTO v_version FROM "activeMakeMethods" WHERE "itemId" = p_new->>'itemId';++ INSERT INTO "jobMakeMethod" (+ "jobId", "parentMaterialId", "itemId", "companyId", "createdBy",+ "requiresSerialTracking", "requiresBatchTracking", "version"+ ) VALUES (+ p_new->>'jobId', p_new->>'id', p_new->>'itemId', p_new->>'companyId', p_new->>'createdBy',+ v_item_tracking_type = 'Serial', v_item_tracking_type = 'Batch', v_version+ )+ RETURNING "id" INTO v_job_make_method_id;++ INSERT INTO "trackedEntity" (+ "sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",+ "quantity", "status", "companyId", "createdBy", "attributes", "itemId"+ ) VALUES (+ 'Item', p_new->>'itemId', v_item_readable_id,+ (p_new->>'quantity')::numeric, 'Reserved',+ p_new->>'companyId', p_new->>'createdBy',+ jsonb_build_object('Job', p_new->>'jobId', 'Job Make Method', v_job_make_method_id, 'Job Material', p_new->>'id'),+ p_new->>'itemId'+ );+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_insert_quote_line_make_method.sql b/packages/database/src/event-system/handlers/sync_insert_quote_line_make_method.sqlnew file mode 100644index 0000000000..5e2b7dfe63--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_insert_quote_line_make_method.sql@@ -0,0 +1,22 @@+CREATE OR REPLACE FUNCTION public.sync_insert_quote_line_make_method(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_version NUMERIC(10, 2);+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;+ IF (p_new->>'methodType') != 'Make to Order' THEN RETURN; END IF;+ IF (p_new->>'itemId') IS NULL THEN RETURN; END IF;++ SELECT "version" INTO v_version FROM "activeMakeMethods" WHERE "itemId" = p_new->>'itemId';++ INSERT INTO "quoteMakeMethod" (+ "quoteId", "quoteLineId", "itemId", "companyId", "createdAt", "createdBy", "version"+ ) VALUES (+ p_new->>'quoteId', p_new->>'id', p_new->>'itemId',+ p_new->>'companyId', NOW(), p_new->>'createdBy', v_version+ );+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_insert_quote_material_make_method.sql b/packages/database/src/event-system/handlers/sync_insert_quote_material_make_method.sqlnew file mode 100644index 0000000000..f27f93e113--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_insert_quote_material_make_method.sql@@ -0,0 +1,22 @@+CREATE OR REPLACE FUNCTION public.sync_insert_quote_material_make_method(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_version NUMERIC(10, 2);+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;+ IF (p_new->>'methodType') != 'Make to Order' THEN RETURN; END IF;+ IF (p_new->>'itemId') IS NULL THEN RETURN; END IF;++ SELECT "version" INTO v_version FROM "activeMakeMethods" WHERE "itemId" = p_new->>'itemId';++ INSERT INTO "quoteMakeMethod" (+ "quoteId", "quoteLineId", "parentMaterialId", "itemId", "companyId", "createdAt", "createdBy", "version"+ ) VALUES (+ p_new->>'quoteId', p_new->>'quoteLineId', p_new->>'id', p_new->>'itemId',+ p_new->>'companyId', NOW(), p_new->>'createdBy', v_version+ );+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_job_complete_or_canceled.sql b/packages/database/src/event-system/handlers/sync_job_complete_or_canceled.sqlnew file mode 100644index 0000000000..04d7731263--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_job_complete_or_canceled.sql@@ -0,0 +1,49 @@+CREATE OR REPLACE FUNCTION public.sync_job_complete_or_canceled(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ group_ids TEXT[];+BEGIN+ IF p_operation = 'UPDATE'+ AND (p_old->>'status') != (p_new->>'status')+ AND ((p_new->>'status') = 'Completed' OR (p_new->>'status') = 'Cancelled')+ THEN+ UPDATE "kanban"+ SET "jobId" = NULL+ WHERE "jobId" = p_new->>'id';++ -- Send notification on job completion+ IF (p_new->>'status') = 'Completed' THEN+ IF (p_new->>'salesOrderId') IS NULL THEN+ SELECT "inventoryJobCompletedNotificationGroup" INTO group_ids+ FROM "companySettings" WHERE "id" = p_new->>'companyId';+ ELSE+ SELECT "salesJobCompletedNotificationGroup" INTO group_ids+ FROM "companySettings" WHERE "id" = p_new->>'companyId';+ END IF;++ IF (p_new->>'assignee') IS NOT NULL THEN+ group_ids := array_append(COALESCE(group_ids, '{}'), p_new->>'assignee');+ END IF;++ IF array_length(group_ids, 1) > 0 THEN+ PERFORM util.send_inngest_event(+ 'carbon/notify',+ jsonb_build_object(+ 'companyId', p_new->>'companyId',+ 'documentId', p_new->>'id',+ 'event', 'job-completed',+ 'recipient', jsonb_build_object(+ 'type', 'group',+ 'groupIds', group_ids+ ),+ 'from', 'system'+ )+ );+ END IF;+ END IF;+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_job_recompute_service_line.sql b/packages/database/src/event-system/handlers/sync_job_recompute_service_line.sqlnew file mode 100644index 0000000000..8b016d5435--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_job_recompute_service_line.sql@@ -0,0 +1,25 @@+CREATE OR REPLACE FUNCTION public.sync_job_recompute_service_line(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF (p_new->>'salesOrderLineId') IS NULL THEN RETURN; END IF;++ -- Only when the completion state actually changed.+ IF (p_old->>'status') IS NOT DISTINCT FROM (p_new->>'status') THEN RETURN; END IF;+ IF NOT (+ (p_old->>'status') IN ('Completed', 'Closed')+ OR (p_new->>'status') IN ('Completed', 'Closed')+ ) THEN+ RETURN;+ END IF;++ PERFORM recompute_service_line_fulfillment(+ p_new->>'salesOrderLineId',+ p_new->>'companyId',+ p_new->>'updatedBy'+ );+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_on_maintenance_dispatch_complete.sql b/packages/database/src/event-system/handlers/sync_on_maintenance_dispatch_complete.sqlnew file mode 100644index 0000000000..41edda07cd--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_on_maintenance_dispatch_complete.sql@@ -0,0 +1,32 @@+CREATE OR REPLACE FUNCTION public.sync_on_maintenance_dispatch_complete(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF NOT ((p_new->>'status') = 'Completed' AND ((p_old->>'status') IS NULL OR (p_old->>'status') != 'Completed')) THEN+ RETURN;+ END IF;++ -- End all active events for this dispatch+ UPDATE "maintenanceDispatchEvent"+ SET+ "endTime" = COALESCE((p_new->>'completedAt')::timestamptz, NOW()),+ "updatedBy" = p_new->>'updatedBy',+ "updatedAt" = NOW()+ WHERE+ "maintenanceDispatchId" = p_new->>'id'+ AND "endTime" IS NULL;++ -- Set actualEndTime if not already set+ IF (p_new->>'actualEndTime') IS NULL THEN+ UPDATE "maintenanceDispatch"+ SET+ "actualEndTime" = NOW(),+ "updatedBy" = p_new->>'updatedBy',+ "updatedAt" = NOW()+ WHERE id = p_new->>'id';+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_propagate_item_readable_id_to_tracked_entity.sql b/packages/database/src/event-system/handlers/sync_propagate_item_readable_id_to_tracked_entity.sqlnew file mode 100644index 0000000000..9f3b7de402--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_propagate_item_readable_id_to_tracked_entity.sql@@ -0,0 +1,17 @@+CREATE OR REPLACE FUNCTION public.sync_propagate_item_readable_id_to_tracked_entity(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF (p_new->>'readableIdWithRevision') IS NOT DISTINCT FROM (p_old->>'readableIdWithRevision') THEN+ RETURN;+ END IF;++ UPDATE "trackedEntity"+ SET "sourceDocumentReadableId" = p_new->>'readableIdWithRevision'+ WHERE "sourceDocument" = 'Item'+ AND "sourceDocumentId" = p_new->>'id';+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_protect_system_required_actions.sql b/packages/database/src/event-system/handlers/sync_protect_system_required_actions.sqlnew file mode 100644index 0000000000..29c93e709e--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_protect_system_required_actions.sql@@ -0,0 +1,26 @@+CREATE OR REPLACE FUNCTION public.sync_protect_system_required_actions(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation = 'DELETE' THEN+ IF (p_old->>'systemType') IS NOT NULL THEN+ -- Allow cascading deletes when the parent company is being deleted+ IF NOT EXISTS (SELECT 1 FROM "company" WHERE id = p_old->>'companyId') THEN+ RETURN;+ END IF;+ RAISE EXCEPTION 'Cannot delete a system-defined required action. You may deactivate it instead.';+ END IF;+ END IF;++ IF p_operation = 'UPDATE' THEN+ IF (p_old->>'systemType') IS NOT NULL AND (p_new->>'systemType') IS DISTINCT FROM (p_old->>'systemType') THEN+ RAISE EXCEPTION 'Cannot change the systemType of a system-defined required action.';+ END IF;+ IF (p_old->>'systemType') IS NULL AND (p_new->>'systemType') IS NOT NULL THEN+ RAISE EXCEPTION 'Cannot assign a systemType to a custom required action.';+ END IF;+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_purchase_invoice_line_price_change.sql b/packages/database/src/event-system/handlers/sync_purchase_invoice_line_price_change.sqlnew file mode 100644index 0000000000..8c13da6727--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_purchase_invoice_line_price_change.sql@@ -0,0 +1,22 @@+CREATE OR REPLACE FUNCTION public.sync_purchase_invoice_line_price_change(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation = 'UPDATE'+ AND ((p_new->>'unitPrice') IS DISTINCT FROM (p_old->>'unitPrice')+ OR (p_new->>'quantity') IS DISTINCT FROM (p_old->>'quantity'))+ THEN+ INSERT INTO "purchaseInvoicePriceChange" (+ "invoiceId", "invoiceLineId", "previousPrice", "newPrice",+ "previousQuantity", "newQuantity", "updatedBy"+ ) VALUES (+ p_new->>'invoiceId', p_new->>'id',+ (p_old->>'unitPrice')::numeric, (p_new->>'unitPrice')::numeric,+ (p_old->>'quantity')::numeric, (p_new->>'quantity')::numeric,+ COALESCE(p_new->>'updatedBy', p_new->>'createdBy')+ );+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_set_initial_dependency_status.sql b/packages/database/src/event-system/handlers/sync_set_initial_dependency_status.sqlnew file mode 100644index 0000000000..f1c36af1cd--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_set_initial_dependency_status.sql@@ -0,0 +1,36 @@+CREATE OR REPLACE FUNCTION public.sync_set_initial_dependency_status(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ -- Don't update if operation is already Done, In Progress, or Canceled+ IF EXISTS (+ SELECT 1+ FROM "jobOperation"+ WHERE id = p_new->>'operationId'+ AND status IN ('Done', 'In Progress', 'Canceled')+ ) THEN+ RETURN;+ END IF;++ -- Check if there are any incomplete dependencies+ IF EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ JOIN "jobOperation" jo ON jo.id = dep."dependsOnId"+ WHERE dep."operationId" = p_new->>'operationId'+ AND jo.status != 'Done'+ ) THEN+ UPDATE "jobOperation"+ SET status = 'Waiting'+ WHERE id = p_new->>'operationId';+ ELSE+ UPDATE "jobOperation"+ SET status = 'Ready'+ WHERE id = p_new->>'operationId';+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_set_job_operation_in_progress.sql b/packages/database/src/event-system/handlers/sync_set_job_operation_in_progress.sqlnew file mode 100644index 0000000000..1126b00028--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_set_job_operation_in_progress.sql@@ -0,0 +1,24 @@+CREATE OR REPLACE FUNCTION public.sync_set_job_operation_in_progress(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ -- Only set to In Progress if endTime is NULL (event is starting, not already ended)+ IF (p_new->>'endTime') IS NULL THEN+ UPDATE "jobOperation"+ SET "status" = 'In Progress'+ WHERE id = p_new->>'jobOperationId';+ END IF;++ -- Set parent job to In Progress if it is still Ready+ UPDATE "job"+ SET "status" = 'In Progress'+ WHERE id = (+ SELECT "jobId" FROM "jobOperation" WHERE id = p_new->>'jobOperationId'+ )+ AND "status" = 'Ready';+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_update_customer_type_group.sql b/packages/database/src/event-system/handlers/sync_update_customer_type_group.sqlnew file mode 100644index 0000000000..c000334e0c--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_update_customer_type_group.sql@@ -0,0 +1,27 @@+CREATE OR REPLACE FUNCTION public.sync_update_customer_type_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ IF p_old->>'customerTypeId' IS NOT NULL THEN+ IF p_new->>'customerTypeId' IS NOT NULL THEN+ UPDATE "membership" SET "groupId" = p_new->>'customerTypeId'+ WHERE "groupId" = p_old->>'customerTypeId' AND "memberGroupId" = p_new->>'id';+ ELSE+ DELETE FROM "membership"+ WHERE "groupId" = p_old->>'customerTypeId' AND "memberGroupId" = p_new->>'id';+ END IF;+ ELSE+ IF p_new->>'customerTypeId' IS NOT NULL THEN+ INSERT INTO "membership" ("groupId", "memberGroupId")+ VALUES (p_new->>'customerTypeId', p_new->>'id');+ END IF;+ END IF;++ UPDATE "group" SET "name" = p_new->>'name'+ WHERE "id" = p_new->>'id' AND "isCustomerOrgGroup" = TRUE;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_update_customer_type_group_name.sql b/packages/database/src/event-system/handlers/sync_update_customer_type_group_name.sqlnew file mode 100644index 0000000000..ab0b75fef9--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_update_customer_type_group_name.sql@@ -0,0 +1,14 @@+CREATE OR REPLACE FUNCTION public.sync_update_customer_type_group_name(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ UPDATE "group"+ SET "name" = p_new->>'name'+ WHERE "id" = p_new->>'id'+ AND "isCustomerTypeGroup" = TRUE;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_update_employee_type_group.sql b/packages/database/src/event-system/handlers/sync_update_employee_type_group.sqlnew file mode 100644index 0000000000..3b7470c257--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_update_employee_type_group.sql@@ -0,0 +1,14 @@+CREATE OR REPLACE FUNCTION public.sync_update_employee_type_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ UPDATE "group"+ SET "name" = p_new->>'name'+ WHERE "id" = p_new->>'id'+ AND "isEmployeeTypeGroup" = TRUE;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_update_employee_type_membership.sql b/packages/database/src/event-system/handlers/sync_update_employee_type_membership.sqlnew file mode 100644index 0000000000..6b49c54e67--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_update_employee_type_membership.sql@@ -0,0 +1,14 @@+CREATE OR REPLACE FUNCTION public.sync_update_employee_type_membership(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ UPDATE "membership"+ SET "groupId" = p_new->>'employeeTypeId'+ WHERE "groupId" = p_old->>'employeeTypeId'+ AND "memberUserId" = p_new->>'id';+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_update_job_material_make_method_item_id.sql b/packages/database/src/event-system/handlers/sync_update_job_material_make_method_item_id.sqlnew file mode 100644index 0000000000..ad19dc64f3--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_update_job_material_make_method_item_id.sql@@ -0,0 +1,109 @@+CREATE OR REPLACE FUNCTION public.sync_update_job_material_make_method_item_id(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_item_readable_id TEXT;+ v_item_tracking_type TEXT;+ v_job_make_method_id TEXT;+ -- Bare NUMERIC: the repo bans a precision spec on NUMERIC, and the+ -- conformance gate scans migration TEXT — so carrying the original+ -- declaration's precision forward registered as a new violation (as does+ -- quoting it in a comment). Behaviour is identical: makeMethod.version is+ -- itself a constrained numeric, so the value round-trips through this local+ -- unchanged and lands back in the same column.+ v_version NUMERIC;+ v_attributes JSONB;+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ IF NOT (+ ((p_old->>'methodType') = 'Make to Order' AND (p_old->>'itemId') IS DISTINCT FROM (p_new->>'itemId'))+ OR ((p_new->>'methodType') = 'Make to Order' AND (p_old->>'methodType') != 'Make to Order')+ ) THEN+ RETURN;+ END IF;++ -- Both lookups are company-scoped: "item" is keyed ("id", "companyId") and+ -- "activeMakeMethods" is per company, so matching on the item id alone could+ -- read another tenant's row. Pre-existing in the definition this replaces.+ SELECT "readableIdWithRevision", "itemTrackingType"+ INTO v_item_readable_id, v_item_tracking_type+ FROM "item"+ WHERE "id" = p_new->>'itemId'+ AND "companyId" = p_new->>'companyId';++ SELECT "version" INTO v_version FROM "activeMakeMethods"+ WHERE "itemId" = p_new->>'itemId'+ AND "companyId" = p_new->>'companyId';++ IF NOT EXISTS (+ SELECT 1 FROM "jobMakeMethod"+ WHERE "jobId" = p_new->>'jobId' AND "parentMaterialId" = p_new->>'id'+ ) THEN+ INSERT INTO "jobMakeMethod" (+ "jobId", "parentMaterialId", "itemId", "companyId", "createdBy",+ "requiresSerialTracking", "requiresBatchTracking", "version"+ ) VALUES (+ p_new->>'jobId', p_new->>'id', p_new->>'itemId', p_new->>'companyId', p_new->>'createdBy',+ v_item_tracking_type = 'Serial', v_item_tracking_type = 'Batch', v_version+ )+ RETURNING "id" INTO v_job_make_method_id;++ INSERT INTO "trackedEntity" (+ "sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",+ "quantity", "status", "companyId", "createdBy", "attributes", "itemId"+ ) VALUES (+ 'Item', p_new->>'itemId', v_item_readable_id,+ (p_new->>'quantity')::numeric, 'Reserved',+ p_new->>'companyId', p_new->>'createdBy',+ jsonb_build_object('Job', p_new->>'jobId', 'Job Make Method', v_job_make_method_id, 'Job Material', p_new->>'id'),+ p_new->>'itemId'+ );+ ELSE+ UPDATE "jobMakeMethod"+ SET "itemId" = p_new->>'itemId',+ "requiresSerialTracking" = (v_item_tracking_type = 'Serial'),+ "requiresBatchTracking" = (v_item_tracking_type = 'Batch'),+ "version" = v_version+ WHERE "jobId" = p_new->>'jobId' AND "parentMaterialId" = p_new->>'id'+ RETURNING "id" INTO v_job_make_method_id;++ v_attributes := jsonb_build_object(+ 'Job', p_new->>'jobId',+ 'Job Make Method', v_job_make_method_id,+ 'Job Material', p_new->>'id'+ );++ -- Repoint what is already there. Restricted to 'Reserved': an entity that+ -- has been consumed or received is history, and rewriting its item would+ -- falsify what was actually built.+ UPDATE "trackedEntity"+ SET "sourceDocumentId" = p_new->>'itemId',+ "sourceDocumentReadableId" = v_item_readable_id,+ "itemId" = p_new->>'itemId',+ "quantity" = (p_new->>'quantity')::numeric,+ -- Merge, don't replace: the shelf-life stamp writes expirationDate into+ -- this same attributes object, and an assignment would silently drop it.+ "attributes" = "attributes" || v_attributes+ WHERE "companyId" = p_new->>'companyId'+ AND "status" = 'Reserved'+ AND "attributes"->>'Job Material' = p_new->>'id';++ -- Only when there was nothing to repoint.+ IF NOT FOUND THEN+ INSERT INTO "trackedEntity" (+ "sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",+ "quantity", "status", "companyId", "createdBy", "attributes", "itemId"+ ) VALUES (+ 'Item', p_new->>'itemId', v_item_readable_id,+ (p_new->>'quantity')::numeric, 'Reserved',+ p_new->>'companyId', p_new->>'createdBy',+ v_attributes,+ p_new->>'itemId'+ );+ END IF;+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_update_job_operation_quantities.sql b/packages/database/src/event-system/handlers/sync_update_job_operation_quantities.sqlnew file mode 100644index 0000000000..e198a490ff--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_update_job_operation_quantities.sql@@ -0,0 +1,110 @@+CREATE OR REPLACE FUNCTION public.sync_update_job_operation_quantities(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+DECLARE+ v_job_operation_id TEXT;+ v_job_id TEXT;+ v_user_id TEXT;+ v_is_last_top_level_operation BOOLEAN := FALSE;+BEGIN+ v_user_id := COALESCE(+ p_new->>'updatedBy', p_new->>'createdBy',+ p_old->>'updatedBy', p_old->>'createdBy'+ );++ IF p_operation = 'INSERT' THEN+ v_job_operation_id := p_new->>'jobOperationId';++ UPDATE "jobOperation"+ SET+ "quantityComplete" = "quantityComplete" ++ CASE WHEN (p_new->>'type') = 'Production' THEN (p_new->>'quantity')::numeric ELSE 0 END,+ "quantityReworked" = "quantityReworked" ++ CASE WHEN (p_new->>'type') = 'Rework' THEN (p_new->>'quantity')::numeric ELSE 0 END,+ "quantityScrapped" = "quantityScrapped" ++ CASE WHEN (p_new->>'type') = 'Scrap' THEN (p_new->>'quantity')::numeric ELSE 0 END+ WHERE id = v_job_operation_id;++ ELSIF p_operation = 'UPDATE' THEN+ v_job_operation_id := p_new->>'jobOperationId';++ UPDATE "jobOperation"+ SET+ "quantityComplete" = "quantityComplete"+ - CASE WHEN (p_old->>'type') = 'Production' THEN (p_old->>'quantity')::numeric ELSE 0 END+ + CASE WHEN (p_new->>'type') = 'Production' THEN (p_new->>'quantity')::numeric ELSE 0 END,+ "quantityReworked" = "quantityReworked"+ - CASE WHEN (p_old->>'type') = 'Rework' THEN (p_old->>'quantity')::numeric ELSE 0 END+ + CASE WHEN (p_new->>'type') = 'Rework' THEN (p_new->>'quantity')::numeric ELSE 0 END,+ "quantityScrapped" = "quantityScrapped"+ - CASE WHEN (p_old->>'type') = 'Scrap' THEN (p_old->>'quantity')::numeric ELSE 0 END+ + CASE WHEN (p_new->>'type') = 'Scrap' THEN (p_new->>'quantity')::numeric ELSE 0 END+ WHERE id = v_job_operation_id;++ ELSIF p_operation = 'DELETE' THEN+ v_job_operation_id := p_old->>'jobOperationId';++ UPDATE "jobOperation"+ SET+ "quantityComplete" = "quantityComplete" -+ CASE WHEN (p_old->>'type') = 'Production' THEN (p_old->>'quantity')::numeric ELSE 0 END,+ "quantityReworked" = "quantityReworked" -+ CASE WHEN (p_old->>'type') = 'Rework' THEN (p_old->>'quantity')::numeric ELSE 0 END,+ "quantityScrapped" = "quantityScrapped" -+ CASE WHEN (p_old->>'type') = 'Scrap' THEN (p_old->>'quantity')::numeric ELSE 0 END+ WHERE id = v_job_operation_id;+ END IF;++ UPDATE "jobOperation"+ SET "status" = 'Done',+ "updatedBy" = COALESCE(v_user_id, "updatedBy", "createdBy"),+ "updatedAt" = NOW()+ WHERE id = v_job_operation_id+ AND "status" NOT IN ('Done', 'Canceled')+ AND "targetQuantity" > 0+ AND ("quantityComplete" + "quantityReworked") >= "targetQuantity";++ SELECT jo."jobId" INTO v_job_id+ FROM "jobOperation" jo+ WHERE jo.id = v_job_operation_id;++ SELECT EXISTS (+ SELECT 1+ FROM "jobOperation" jo+ INNER JOIN "jobMakeMethod" jmm ON jmm.id = jo."jobMakeMethodId"+ WHERE jo.id = v_job_operation_id+ AND jmm."parentMaterialId" IS NULL+ AND NOT EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ INNER JOIN "jobOperation" child_jo ON child_jo.id = dep."operationId"+ INNER JOIN "jobMakeMethod" child_jmm ON child_jmm.id = child_jo."jobMakeMethodId"+ WHERE dep."dependsOnId" = jo.id+ AND child_jmm."parentMaterialId" IS NULL+ )+ ) INTO v_is_last_top_level_operation;++ IF v_job_id IS NOT NULL AND v_is_last_top_level_operation THEN+ UPDATE "job"+ SET "quantityComplete" = (+ SELECT COALESCE(SUM(terminal_jo."quantityComplete"), 0)+ FROM "jobOperation" terminal_jo+ INNER JOIN "jobMakeMethod" terminal_jmm ON terminal_jmm.id = terminal_jo."jobMakeMethodId"+ WHERE terminal_jo."jobId" = v_job_id+ AND terminal_jmm."parentMaterialId" IS NULL+ AND NOT EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ INNER JOIN "jobOperation" child_jo ON child_jo.id = dep."operationId"+ INNER JOIN "jobMakeMethod" child_jmm ON child_jmm.id = child_jo."jobMakeMethodId"+ WHERE dep."dependsOnId" = terminal_jo.id+ AND child_jmm."parentMaterialId" IS NULL+ )+ )+ WHERE id = v_job_id+ AND status NOT IN ('Completed', 'Cancelled');+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_update_quote_exchange_rate.sql b/packages/database/src/event-system/handlers/sync_update_quote_exchange_rate.sqlnew file mode 100644index 0000000000..e3aee5ac22--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_update_quote_exchange_rate.sql@@ -0,0 +1,15 @@+CREATE OR REPLACE FUNCTION public.sync_update_quote_exchange_rate(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation = 'UPDATE'+ AND (p_old->>'exchangeRate') IS DISTINCT FROM (p_new->>'exchangeRate')+ THEN+ UPDATE "quoteLinePrice"+ SET "exchangeRate" = (p_new->>'exchangeRate')::numeric+ WHERE "quoteId" = p_new->>'id';+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_update_quote_line_make_method_item_id.sql b/packages/database/src/event-system/handlers/sync_update_quote_line_make_method_item_id.sqlnew file mode 100644index 0000000000..af7089de13--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_update_quote_line_make_method_item_id.sql@@ -0,0 +1,38 @@+CREATE OR REPLACE FUNCTION public.sync_update_quote_line_make_method_item_id(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_version NUMERIC(10, 2);+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ -- Only fire when methodType/itemId change is relevant to Make to Order+ IF NOT (+ ((p_old->>'methodType') = 'Make to Order' AND (p_old->>'itemId') IS DISTINCT FROM (p_new->>'itemId'))+ OR ((p_new->>'methodType') = 'Make to Order' AND (p_old->>'methodType') != 'Make to Order')+ ) THEN+ RETURN;+ END IF;++ SELECT "version" INTO v_version FROM "activeMakeMethods" WHERE "itemId" = p_new->>'itemId';++ IF NOT EXISTS (+ SELECT 1 FROM "quoteMakeMethod"+ WHERE "quoteLineId" = p_new->>'id' AND "parentMaterialId" IS NULL+ ) THEN+ INSERT INTO "quoteMakeMethod" (+ "quoteId", "quoteLineId", "itemId", "companyId", "createdAt", "createdBy", "version"+ ) VALUES (+ p_new->>'quoteId', p_new->>'id', p_new->>'itemId',+ p_new->>'companyId', NOW(), p_new->>'createdBy', v_version+ );+ ELSE+ UPDATE "quoteMakeMethod"+ SET "itemId" = p_new->>'itemId',+ "version" = v_version+ WHERE "quoteLineId" = p_new->>'id' AND "parentMaterialId" IS NULL;+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_update_quote_material_make_method_item_id.sql b/packages/database/src/event-system/handlers/sync_update_quote_material_make_method_item_id.sqlnew file mode 100644index 0000000000..8095a0ee5f--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_update_quote_material_make_method_item_id.sql@@ -0,0 +1,37 @@+CREATE OR REPLACE FUNCTION public.sync_update_quote_material_make_method_item_id(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_version NUMERIC(10, 2);+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ IF NOT (+ ((p_old->>'methodType') = 'Make to Order' AND (p_old->>'itemId') IS DISTINCT FROM (p_new->>'itemId'))+ OR ((p_new->>'methodType') = 'Make to Order' AND (p_old->>'methodType') != 'Make to Order')+ ) THEN+ RETURN;+ END IF;++ SELECT "version" INTO v_version FROM "activeMakeMethods" WHERE "itemId" = p_new->>'itemId';++ IF NOT EXISTS (+ SELECT 1 FROM "quoteMakeMethod"+ WHERE "quoteLineId" = p_new->>'quoteLineId' AND "parentMaterialId" = p_new->>'id'+ ) THEN+ INSERT INTO "quoteMakeMethod" (+ "quoteId", "quoteLineId", "parentMaterialId", "itemId", "companyId", "createdAt", "createdBy", "version"+ ) VALUES (+ p_new->>'quoteId', p_new->>'quoteLineId', p_new->>'id', p_new->>'itemId',+ p_new->>'companyId', NOW(), p_new->>'createdBy', v_version+ );+ ELSE+ UPDATE "quoteMakeMethod"+ SET "itemId" = p_new->>'itemId',+ "version" = v_version+ WHERE "quoteLineId" = p_new->>'quoteLineId' AND "parentMaterialId" = p_new->>'id';+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_update_sales_order_exchange_rate.sql b/packages/database/src/event-system/handlers/sync_update_sales_order_exchange_rate.sqlnew file mode 100644index 0000000000..d41ca80b98--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_update_sales_order_exchange_rate.sql@@ -0,0 +1,15 @@+CREATE OR REPLACE FUNCTION public.sync_update_sales_order_exchange_rate(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation = 'UPDATE'+ AND (p_old->>'exchangeRate') IS DISTINCT FROM (p_new->>'exchangeRate')+ THEN+ UPDATE "salesOrderLine"+ SET "exchangeRate" = (p_new->>'exchangeRate')::numeric+ WHERE "salesOrderId" = p_new->>'id';+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_update_stock_transfer_status.sql b/packages/database/src/event-system/handlers/sync_update_stock_transfer_status.sqlnew file mode 100644index 0000000000..35e89673bb--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_update_stock_transfer_status.sql@@ -0,0 +1,28 @@+CREATE OR REPLACE FUNCTION public.sync_update_stock_transfer_status(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF NOT ((p_old->>'pickedQuantity') IS DISTINCT FROM (p_new->>'pickedQuantity')+ AND (p_new->>'pickedQuantity')::numeric != 0) THEN+ RETURN;+ END IF;++ IF EXISTS (+ SELECT 1+ FROM "stockTransferLine"+ WHERE "stockTransferId" = p_new->>'stockTransferId'+ AND ("pickedQuantity" IS NULL OR "pickedQuantity" != "quantity")+ ) THEN+ UPDATE "stockTransfer"+ SET "status" = 'In Progress'+ WHERE "id" = p_new->>'stockTransferId';+ ELSE+ UPDATE "stockTransfer"+ SET "status" = 'Completed', "completedAt" = NOW()+ WHERE "id" = p_new->>'stockTransferId';+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_update_supplier_type_group.sql b/packages/database/src/event-system/handlers/sync_update_supplier_type_group.sqlnew file mode 100644index 0000000000..2b09d00ed3--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_update_supplier_type_group.sql@@ -0,0 +1,27 @@+CREATE OR REPLACE FUNCTION public.sync_update_supplier_type_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ IF p_old->>'supplierTypeId' IS NOT NULL THEN+ IF p_new->>'supplierTypeId' IS NOT NULL THEN+ UPDATE "membership" SET "groupId" = p_new->>'supplierTypeId'+ WHERE "groupId" = p_old->>'supplierTypeId' AND "memberGroupId" = p_new->>'id';+ ELSE+ DELETE FROM "membership"+ WHERE "groupId" = p_old->>'supplierTypeId' AND "memberGroupId" = p_new->>'id';+ END IF;+ ELSE+ IF p_new->>'supplierTypeId' IS NOT NULL THEN+ INSERT INTO "membership" ("groupId", "memberGroupId")+ VALUES (p_new->>'supplierTypeId', p_new->>'id');+ END IF;+ END IF;++ UPDATE "group" SET "name" = p_new->>'name'+ WHERE "id" = p_new->>'id' AND "isSupplierOrgGroup" = TRUE;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_update_supplier_type_group_name.sql b/packages/database/src/event-system/handlers/sync_update_supplier_type_group_name.sqlnew file mode 100644index 0000000000..9a182ff4e2--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_update_supplier_type_group_name.sql@@ -0,0 +1,14 @@+CREATE OR REPLACE FUNCTION public.sync_update_supplier_type_group_name(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ UPDATE "group"+ SET "name" = p_new->>'name'+ WHERE "id" = p_new->>'id'+ AND "isSupplierTypeGroup" = TRUE;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_update_tracked_entity_on_job_make_method.sql b/packages/database/src/event-system/handlers/sync_update_tracked_entity_on_job_make_method.sqlnew file mode 100644index 0000000000..c1ccf34f55--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_update_tracked_entity_on_job_make_method.sql@@ -0,0 +1,18 @@+CREATE OR REPLACE FUNCTION public.sync_update_tracked_entity_on_job_make_method(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF (p_old->>'id') IS NOT DISTINCT FROM (p_new->>'id') THEN RETURN; END IF;++ UPDATE "trackedEntity"+ SET "attributes" = jsonb_set(+ "attributes",+ '{Job Make Method}',+ to_jsonb(p_new->>'id')+ )+ WHERE "attributes"->>'Job Make Method' = p_old->>'id';+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_update_user_identity_group.sql b/packages/database/src/event-system/handlers/sync_update_user_identity_group.sqlnew file mode 100644index 0000000000..8bb5a1717b--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_update_user_identity_group.sql@@ -0,0 +1,14 @@+CREATE OR REPLACE FUNCTION public.sync_update_user_identity_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ UPDATE "group"+ SET "name" = p_new->>'fullName'+ WHERE "id" = p_new->>'id'+ AND "isIdentityGroup" = TRUE;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_upload_document_transaction.sql b/packages/database/src/event-system/handlers/sync_upload_document_transaction.sqlnew file mode 100644index 0000000000..4a79a48108--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_upload_document_transaction.sql@@ -0,0 +1,12 @@+CREATE OR REPLACE FUNCTION public.sync_upload_document_transaction(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "documentTransaction" ("documentId", "type", "userId")+ VALUES (p_new->>'id', 'Upload', p_new->>'createdBy');+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_verify_integration.sql b/packages/database/src/event-system/handlers/sync_verify_integration.sqlnew file mode 100644index 0000000000..ff50b021f2--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_verify_integration.sql@@ -0,0 +1,20 @@+CREATE OR REPLACE FUNCTION public.sync_verify_integration(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ integration_schema JSON;+BEGIN+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN RETURN; END IF;++ SELECT jsonschema INTO integration_schema+ FROM public.integration+ WHERE id = p_new->>'id';++ IF (p_new->>'active')::boolean = TRUE+ AND NOT extensions.json_matches_schema(integration_schema, (p_new->'metadata')::json) THEN+ RAISE EXCEPTION 'metadata does not match jsonschema';+ END IF;+END;+$function$;diff --git a/packages/database/src/event-system/handlers/sync_webhook_subscription.sql b/packages/database/src/event-system/handlers/sync_webhook_subscription.sqlnew file mode 100644index 0000000000..56ab99f6d8--- /dev/null+++ b/packages/database/src/event-system/handlers/sync_webhook_subscription.sql@@ -0,0 +1,43 @@+CREATE OR REPLACE FUNCTION public.sync_webhook_subscription(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+DECLARE+ v_ops TEXT[];+ v_name TEXT;+BEGIN+ IF p_operation = 'DELETE' THEN+ PERFORM delete_event_system_subscriptions_by_name(+ p_old->>'companyId', 'webhook-' || (p_old->>'id')+ );+ RETURN;+ END IF;++ v_name := 'webhook-' || (p_new->>'id');++ -- Clear first: `table` is editable and uniqueness is (companyId, name, table),+ -- so an upsert would strand the old row and fire the webhook twice.+ PERFORM delete_event_system_subscriptions_by_name(p_new->>'companyId', v_name);++ v_ops := ARRAY[]::TEXT[];+ IF (p_new->>'onInsert')::BOOLEAN THEN v_ops := array_append(v_ops, 'INSERT'); END IF;+ IF (p_new->>'onUpdate')::BOOLEAN THEN v_ops := array_append(v_ops, 'UPDATE'); END IF;+ IF (p_new->>'onDelete')::BOOLEAN THEN v_ops := array_append(v_ops, 'DELETE'); END IF;++ IF array_length(v_ops, 1) IS NULL THEN+ RETURN;+ END IF;++ PERFORM create_event_system_subscription(+ v_name,+ p_new->>'table',+ p_new->>'companyId',+ v_ops,+ 'WEBHOOK',+ jsonb_build_object('url', p_new->>'url', 'webhookId', p_new->>'id'),+ '{}'::jsonb,+ COALESCE((p_new->>'active')::BOOLEAN, false)+ );+END;+$function$;diff --git a/packages/database/src/realtime-tables.test.ts b/packages/database/src/realtime-tables.test.tsnew file mode 100644index 0000000000..ed7b0e3eb4--- /dev/null+++ b/packages/database/src/realtime-tables.test.ts@@ -0,0 +1,49 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { readFileSync } from "node:fs";+import { expect, it } from "vitest";+import {+ REALTIME_ANCESTOR_COLUMNS,+ REALTIME_REFERENCE_TABLES,+ REALTIME_TABLES,+ REALTIME_USER_TABLES+} from "./realtime-tables";++it("names each table once, in one list", () => {+ const all = [+ ...REALTIME_TABLES,+ ...REALTIME_REFERENCE_TABLES,+ ...REALTIME_USER_TABLES+ ];+ expect(new Set(all).size).toBe(all.length);+});++it("derives each list from the attached broadcast handler", () => {+ expect(REALTIME_TABLES).toContain("jobOperation");+ expect(REALTIME_REFERENCE_TABLES).toContain("customerType");+ expect(REALTIME_USER_TABLES).toEqual(["notification"]);+});++it("lists the ancestor columns broadcast_table_changes adds", () => {+ const sql = readFileSync(+ new URL(+ "./event-system/functions/broadcast_table_changes.sql",+ import.meta.url+ ),+ "utf8"+ );+ const declared = /ancestors CONSTANT JSONB := '([^']+)'/.exec(sql)?.[1];+ const hops: Record<string, [string, string, string][]> = JSON.parse(+ declared ?? "{}"+ );+ expect(+ Object.fromEntries(+ Object.entries(hops).map(([table, path]) => [+ table,+ path.map(([, , column]) => column)+ ])+ )+ ).toEqual(REALTIME_ANCESTOR_COLUMNS);+});diff --git a/packages/database/src/realtime-tables.ts b/packages/database/src/realtime-tables.tsnew file mode 100644index 0000000000..710c76ad99--- /dev/null+++ b/packages/database/src/realtime-tables.ts@@ -0,0 +1,110 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Attachment } from "./event-system/attachments";+import { attachments } from "./event-system/attachments";+import type { Database } from "./types";++// The tables that broadcast their changes over Realtime. Derived from the+// attachments manifest, so a table is realtime exactly when a broadcast handler+// is attached to it — there is no second list to keep in step.++type Attachments = typeof attachments;++type TablesWith<Handler extends string> = {+ [T in keyof Attachments]: Attachments[T] extends {+ statement: readonly (infer Attached)[];+ }+ ? Handler extends Attached+ ? T+ : never+ : never;+}[keyof Attachments];++const tablesWith = <Handler extends string>(handler: Handler) =>+ (Object.keys(attachments) as (keyof Attachments)[]).filter((table) =>+ (attachments[table] as Attachment).statement?.includes(handler)+ ) as TablesWith<Handler>[];++/**+ * Tables on their own topic, `company:<companyId>:<table>`. A route may only+ * name one of these in `handle.realtime` (the `realtime-table-has-trigger`+ * check): a table without the trigger sends nothing, and nothing errors.+ */+export const REALTIME_TABLES = tablesWith("broadcast_table_changes");++/**+ * Tables behind the cached `api+` reference lists. They share one topic,+ * `company:<companyId>:reference`.+ */+export const REALTIME_REFERENCE_TABLES = tablesWith(+ "broadcast_reference_changes"+);++/** Tables on a per-user topic, `user:<userId>:<table>`. */+export const REALTIME_USER_TABLES = tablesWith("broadcast_user_changes");++/**+ * The names the change log (`tableChange`) records changes under: the tables+ * with `log_table_changes`, and "employee" for `log_user_changes`. A writer+ * that runs with triggers off (a restore) logs a reset for each itself.+ */+export const CHANGE_LOGGED_TABLES: string[] = [+ ...new Set<string>([...tablesWith("log_table_changes"), "employee"])+];++export type RealtimeTable = TablesWith<"broadcast_table_changes">;++type Tables = Database["public"]["Tables"];++/**+ * Columns a broadcast adds for a table whose rows reach a record through+ * another table (a production event knows its operation, not its job). The+ * `ancestors` constant in `broadcast_table_changes.sql` is the source;+ * `realtime-tables.test.ts` keeps this equal to it.+ */+export const REALTIME_ANCESTOR_COLUMNS = {+ productionEvent: ["jobId"],+ jobOperationStep: ["jobId"],+ jobOperationStepRecord: ["operationId", "jobId"],+ trackedActivity: ["jobOperationId"],+ payment: ["targetSalesInvoiceId", "targetPurchaseInvoiceId"]+} as const satisfies Partial<Record<RealtimeTable, readonly string[]>>;++type AncestorColumn<T> = T extends keyof typeof REALTIME_ANCESTOR_COLUMNS+ ? (typeof REALTIME_ANCESTOR_COLUMNS)[T][number]+ : never;++type ScopedTo<T extends RealtimeTable> = T extends keyof Tables+ ? {+ table: T;+ /** `id`, a `<name>Id` column, or an ancestor column: all a broadcast names. */+ column:+ | Extract<keyof Tables[T]["Row"], "id" | `${string}Id`>+ | AncestorColumn<T>;+ /** The route param that holds the value. */+ param: string;+ }+ : never;++/**+ * A `handle.realtime` entry:+ * - a table name: every change to it in the company (a list page);+ * - `{ table, column, param }`: only the rows of the record the route shows+ * (`{ table: "jobOperation", column: "jobId", param: "jobId" }`);+ * - `{ table, filter }`: the filter is built from the route's params and loader+ * data, for a record the URL does not name. Return `undefined` to follow+ * every change, `false` to follow none (the record has no such row yet).+ */+export type RouteRealtimeTable =+ | RealtimeTable+ | { [T in RealtimeTable]: ScopedTo<T> }[RealtimeTable]+ | {+ table: RealtimeTable;+ filter: (route: {+ params: Record<string, string | undefined>;+ // biome-ignore lint/suspicious/noExplicitAny: each route knows its own loader data+ data: any;+ }) => string | undefined | false;+ };diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 3ded3f9c51..ebed379bc4 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -75213,6 +75213,150 @@ export default {tags: ["paymentTerm"]}},+ "/tableChange": {+ get: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.tableChange.id"+ },+ {+ $ref: "#/parameters/rowFilter.tableChange.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.tableChange.table"+ },+ {+ $ref: "#/parameters/rowFilter.tableChange.rowId"+ },+ {+ $ref: "#/parameters/rowFilter.tableChange.xid"+ },+ {+ $ref: "#/parameters/rowFilter.tableChange.createdAt"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/order"+ },+ {+ $ref: "#/parameters/range"+ },+ {+ $ref: "#/parameters/rangeUnit"+ },+ {+ $ref: "#/parameters/offset"+ },+ {+ $ref: "#/parameters/limit"+ },+ {+ $ref: "#/parameters/preferCount"+ }+ ],+ responses: {+ "200": {+ description: "OK",+ schema: {+ items: {+ $ref: "#/definitions/tableChange"+ },+ type: "array"+ }+ },+ "206": {+ description: "Partial Content"+ }+ },+ tags: ["tableChange"]+ },+ post: {+ parameters: [+ {+ $ref: "#/parameters/body.tableChange"+ },+ {+ $ref: "#/parameters/select"+ },+ {+ $ref: "#/parameters/preferPost"+ }+ ],+ responses: {+ "201": {+ description: "Created"+ }+ },+ tags: ["tableChange"]+ },+ delete: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.tableChange.id"+ },+ {+ $ref: "#/parameters/rowFilter.tableChange.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.tableChange.table"+ },+ {+ $ref: "#/parameters/rowFilter.tableChange.rowId"+ },+ {+ $ref: "#/parameters/rowFilter.tableChange.xid"+ },+ {+ $ref: "#/parameters/rowFilter.tableChange.createdAt"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["tableChange"]+ },+ patch: {+ parameters: [+ {+ $ref: "#/parameters/rowFilter.tableChange.id"+ },+ {+ $ref: "#/parameters/rowFilter.tableChange.companyId"+ },+ {+ $ref: "#/parameters/rowFilter.tableChange.table"+ },+ {+ $ref: "#/parameters/rowFilter.tableChange.rowId"+ },+ {+ $ref: "#/parameters/rowFilter.tableChange.xid"+ },+ {+ $ref: "#/parameters/rowFilter.tableChange.createdAt"+ },+ {+ $ref: "#/parameters/body.tableChange"+ },+ {+ $ref: "#/parameters/preferReturn"+ }+ ],+ responses: {+ "204": {+ description: "No Content"+ }+ },+ tags: ["tableChange"]+ }+ },"/rework": {get: {parameters: [@@ -97038,6 +97182,88 @@ export default {tags: ["(rpc) is_claims_admin"]}},+ "/rpc/get_item_change_notices": {+ get: {+ parameters: [+ {+ format: "text",+ in: "query",+ name: "item_id",+ required: true,+ type: "string"+ },+ {+ format: "text",+ in: "query",+ name: "company_id",+ required: true,+ type: "string"+ },+ {+ format: '"changeOrderStatus"[]',+ in: "query",+ name: "statuses",+ required: false,+ type: "string"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_item_change_notices"]+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ company_id: {+ format: "text",+ type: "string"+ },+ item_id: {+ format: "text",+ type: "string"+ },+ statuses: {+ format: '"changeOrderStatus"[]',+ items: {+ type: "string"+ },+ type: "array"+ }+ },+ required: ["item_id", "company_id"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_item_change_notices"]+ }+ },"/rpc/xid": {post: {parameters: [@@ -103339,6 +103565,74 @@ export default {tags: ["(rpc) delete_old_audit_logs"]}},+ "/rpc/get_item_used_in": {+ get: {+ parameters: [+ {+ format: "text",+ in: "query",+ name: "item_id",+ required: true,+ type: "string"+ },+ {+ format: "text",+ in: "query",+ name: "company_id",+ required: true,+ type: "string"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_item_used_in"]+ },+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ company_id: {+ format: "text",+ type: "string"+ },+ item_id: {+ format: "text",+ type: "string"+ }+ },+ required: ["item_id", "company_id"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) get_item_used_in"]+ }+ },"/rpc/get_job_quantity_on_hand": {post: {parameters: [@@ -106301,6 +106595,66 @@ export default {tags: ["(rpc) get_purchasing_planning"]}},+ "/rpc/set_event_triggers": {+ post: {+ parameters: [+ {+ in: "body",+ name: "args",+ required: true,+ schema: {+ properties: {+ after_functions: {+ format: "text[]",+ items: {+ type: "string"+ },+ type: "array"+ },+ before_functions: {+ format: "text[]",+ items: {+ type: "string"+ },+ type: "array"+ },+ queue_events: {+ format: "boolean",+ type: "boolean"+ },+ statement_functions: {+ format: "text[]",+ items: {+ type: "string"+ },+ type: "array"+ },+ table_name_text: {+ format: "text",+ type: "string"+ }+ },+ required: ["table_name_text"],+ type: "object"+ }+ },+ {+ $ref: "#/parameters/preferParams"+ }+ ],+ produces: [+ "application/json",+ "application/vnd.pgrst.object+json;nulls=stripped",+ "application/vnd.pgrst.object+json"+ ],+ responses: {+ "200": {+ description: "OK"+ }+ },+ tags: ["(rpc) set_event_triggers"]+ }+ },"/rpc/create_event_system_subscription": {post: {parameters: [@@ -142686,6 +143040,40 @@ export default {},type: "object"},+ tableChange: {+ required: ["id", "companyId", "table", "xid", "createdAt"],+ properties: {+ id: {+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "bigint",+ type: "integer"+ },+ companyId: {+ description: "Note:\nThis is a Primary Key.<pk/>",+ format: "text",+ type: "string"+ },+ table: {+ format: "text",+ type: "string"+ },+ rowId: {+ format: "text",+ type: "string"+ },+ xid: {+ default: "pg_current_xact_id()",+ format: "xid8",+ type: "string"+ },+ createdAt: {+ default: "now()",+ format: "timestamp with time zone",+ type: "string"+ }+ },+ type: "object"+ },rework: {required: ["id",@@ -191666,6 +192054,51 @@ export default {in: "query",type: "string"},+ "body.tableChange": {+ name: "tableChange",+ description: "tableChange",+ required: false,+ in: "body",+ schema: {+ $ref: "#/definitions/tableChange"+ }+ },+ "rowFilter.tableChange.id": {+ name: "id",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.tableChange.companyId": {+ name: "companyId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.tableChange.table": {+ name: "table",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.tableChange.rowId": {+ name: "rowId",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.tableChange.xid": {+ name: "xid",+ required: false,+ in: "query",+ type: "string"+ },+ "rowFilter.tableChange.createdAt": {+ name: "createdAt",+ required: false,+ in: "query",+ type: "string"+ },"body.rework": {name: "rework",description: "rework",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex f70f24aa8a..ebce0272f1 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -60800,6 +60800,33 @@ export type Database = {}]}+ tableChange: {+ Row: {+ companyId: string+ createdAt: string+ id: number+ rowId: string | null+ table: string+ xid: unknown+ }+ Insert: {+ companyId: string+ createdAt?: string+ id?: never+ rowId?: string | null+ table: string+ xid?: unknown+ }+ Update: {+ companyId?: string+ createdAt?: string+ id?: never+ rowId?: string | null+ table?: string+ xid?: unknown+ }+ Relationships: []+ }tableView: {Row: {columnOrder: string[] | null@@ -83608,6 +83635,21 @@ export type Database = {unitOfMeasureCode: string}[]}+ get_item_change_notices: {+ Args: {+ company_id: string+ item_id: string+ statuses?: Database["public"]["Enums"]["changeOrderStatus"][]+ }+ Returns: {+ changeOrderId: string+ changeOrderTypeId: string+ createdAt: string+ id: string+ name: string+ status: Database["public"]["Enums"]["changeOrderStatus"]+ }[]+ }get_item_ledger_balance: {Args: {company_id: string@@ -83666,6 +83708,10 @@ export type Database = {unitOfMeasureCode: string}[]}+ get_item_used_in: {+ Args: { company_id: string; item_id: string }+ Returns: Json+ }get_job_method: {Args: { jid: string }Returns: {@@ -85182,6 +85228,16 @@ export type Database = {}Returns: undefined}+ set_event_triggers: {+ Args: {+ after_functions?: string[]+ before_functions?: string[]+ queue_events?: boolean+ statement_functions?: string[]+ table_name_text: string+ }+ Returns: undefined+ }set_inngest_event_config: {Args: { p_base_url: string; p_key: string }Returns: undefined@@ -85339,20 +85395,10 @@ export type Database = {Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }Returns: undefined}- sync_finish_job_operation:- | {- Args: { p_new: Json; p_old: Json; p_operation: string }- Returns: undefined- }- | {- Args: {- p_new: Json- p_old: Json- p_operation: string- p_table: string- }- Returns: undefined- }+ sync_finish_job_operation: {+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }+ Returns: undefined+ }sync_insert_company_related_records: {Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }Returns: undefined@@ -85477,6 +85523,15 @@ export type Database = {Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }Returns: undefined}+ table_changes_since: {+ Args: {+ p_at?: string+ p_company_id: string+ p_epoch?: string+ p_xid?: string+ }+ Returns: Json+ }terminal_job_operations: {Args: { p_job_id: string }Returns: {diff --git a/packages/database/supabase/migrations/20261004191247_realtime-broadcast.sql b/packages/database/supabase/migrations/20261004191247_realtime-broadcast.sqlnew file mode 100644index 0000000000..bf55372515--- /dev/null+++ b/packages/database/supabase/migrations/20261004191247_realtime-broadcast.sql@@ -0,0 +1,179 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++CREATE OR REPLACE FUNCTION public.broadcast_reference_changes()+ RETURNS trigger+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO ''+AS $function$+DECLARE+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];+ changed_rows TEXT;+ rec RECORD;+BEGIN+ -- A database without Supabase Realtime (a self-hosted install that does not+ -- run it) has nothing to send to: the write must still succeed.+ IF to_regprocedure('realtime.send(jsonb,text,text,boolean)') IS NULL THEN+ RETURN NULL;+ END IF;++ -- Tells the company's clients that a reference list changed (one shared topic, company:<companyId>:reference).+ -- Statement-level (attach_statement_handler): one message per company per+ -- statement, whatever the row count. No row data leaves the database: a client+ -- re-reads what it needs through PostgREST, so table RLS still decides what it sees.+ IF TG_OP = 'UPDATE' THEN+ -- A row whose only changes are in ignored_columns drops out (the rule+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n+ EXCEPT+ SELECT to_jsonb(o) - $1 FROM batched_old o';+ ELSIF TG_OP = 'DELETE' THEN+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';+ ELSE+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';+ END IF;++ FOR rec IN EXECUTE format(+ 'SELECT DISTINCT c->>''companyId'' AS company_id FROM (%s) changed',+ changed_rows+ ) USING ignored_columns+ LOOP+ CONTINUE WHEN rec.company_id IS NULL;+ PERFORM realtime.send(+ jsonb_build_object('table', TG_TABLE_NAME, 'op', TG_OP),+ TG_OP,+ 'company:' || rec.company_id || ':reference',+ true+ );+ END LOOP;+ RETURN NULL;+END;+$function$;++CREATE OR REPLACE FUNCTION public.broadcast_table_changes()+ RETURNS trigger+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO ''+AS $function$+DECLARE+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];+ changed_rows TEXT;+ rec RECORD;+BEGIN+ -- Tells the company's clients which rows of this table changed (topic company:<companyId>:<table>).+ -- Statement-level (attach_statement_handler): one message per company per+ -- statement, whatever the row count. No row data leaves the database: a client+ -- re-reads what it needs through PostgREST, so table RLS still decides what it sees.+ IF TG_OP = 'UPDATE' THEN+ -- A row whose only changes are in ignored_columns drops out (the rule+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n+ EXCEPT+ SELECT to_jsonb(o) - $1 FROM batched_old o';+ ELSIF TG_OP = 'DELETE' THEN+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';+ ELSE+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';+ END IF;++ FOR rec IN EXECUTE format(+ -- implementationHub has no companyId: its id is the company id.+ 'SELECT coalesce(c->>''companyId'',+ CASE WHEN $2::text = ''implementationHub'' THEN c->>''id'' END) AS company_id,+ count(*) AS n,+ jsonb_agg(c->''id'') FILTER (WHERE c ? ''id'') AS ids+ FROM (%s) changed+ GROUP BY 1',+ changed_rows+ ) USING ignored_columns, TG_TABLE_NAME+ LOOP+ CONTINUE WHEN rec.company_id IS NULL;+ PERFORM realtime.send(+ jsonb_build_object(+ 'table', TG_TABLE_NAME,+ 'op', TG_OP,+ -- null = "many rows changed, or the table has no id: resync"+ 'ids', CASE WHEN rec.n <= 100 THEN rec.ids END+ ),+ TG_OP,+ 'company:' || rec.company_id || ':' || TG_TABLE_NAME,+ true+ );+ END LOOP;+ RETURN NULL;+END;+$function$;++CREATE OR REPLACE FUNCTION public.broadcast_user_changes()+ RETURNS trigger+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO ''+AS $function$+DECLARE+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];+ changed_rows TEXT;+ rec RECORD;+BEGIN+ -- A database without Supabase Realtime (a self-hosted install that does not+ -- run it) has nothing to send to: the write must still succeed.+ IF to_regprocedure('realtime.send(jsonb,text,text,boolean)') IS NULL THEN+ RETURN NULL;+ END IF;++ -- Tells one user which of their rows changed (topic user:<userId>:<table>).+ -- Statement-level (attach_statement_handler): one message per user per+ -- statement, whatever the row count. No row data leaves the database: a client+ -- re-reads what it needs through PostgREST, so table RLS still decides what it sees.+ IF TG_OP = 'UPDATE' THEN+ -- A row whose only changes are in ignored_columns drops out (the rule+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n+ EXCEPT+ SELECT to_jsonb(o) - $1 FROM batched_old o';+ ELSIF TG_OP = 'DELETE' THEN+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';+ ELSE+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';+ END IF;++ FOR rec IN EXECUTE format(+ 'SELECT c->>''userId'' AS user_id,+ count(*) AS n,+ jsonb_agg(c->''id'') FILTER (WHERE c ? ''id'') AS ids+ FROM (%s) changed+ GROUP BY 1',+ changed_rows+ ) USING ignored_columns+ LOOP+ CONTINUE WHEN rec.user_id IS NULL;+ PERFORM realtime.send(+ jsonb_build_object(+ 'table', TG_TABLE_NAME,+ 'op', TG_OP,+ 'ids', CASE WHEN rec.n <= 100 THEN rec.ids END+ ),+ TG_OP,+ 'user:' || rec.user_id || ':' || TG_TABLE_NAME,+ true+ );+ END LOOP;+ RETURN NULL;+END;+$function$;++-- realtime.messages+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'realtime' AND tablename = 'messages' LOOP+ EXECUTE format('DROP POLICY %I ON %I.%I', p.policyname, 'realtime', 'messages');+ END LOOP;+END+$authz$;++ CREATE POLICY "company topic" ON "realtime"."messages" FOR SELECT TO authenticated USING ((split_part(realtime.topic(), ':', 1) = 'company') AND (split_part(realtime.topic(), ':', 2) = ANY ((SELECT get_companies_with_employee_role())::text[])));+ CREATE POLICY "user topic" ON "realtime"."messages" FOR SELECT TO authenticated USING ((split_part(realtime.topic(), ':', 1) = 'user') AND (split_part(realtime.topic(), ':', 2) = ((SELECT auth.uid()))::text));diff --git a/packages/database/supabase/migrations/20261004192633_realtime-publication.sql b/packages/database/supabase/migrations/20261004192633_realtime-publication.sqlnew file mode 100644index 0000000000..c011c45de2--- /dev/null+++ b/packages/database/supabase/migrations/20261004192633_realtime-publication.sql@@ -0,0 +1,22 @@+-- Realtime moves from postgres_changes to broadcast.+--+-- The broadcast functions, the realtime.messages policies and the triggers that+-- attach them are declared in packages/database/src (authz manifest,+-- event-system/functions, event-system/attachments.ts) and shipped by generated+-- migrations. This file removes the old path.++-- 1. Nothing subscribes to postgres_changes any more: empty the publication.+DO $$+DECLARE+ published RECORD;+BEGIN+ FOR published IN+ SELECT schemaname, tablename FROM pg_publication_tables+ WHERE pubname = 'supabase_realtime'+ LOOP+ EXECUTE format(+ 'ALTER PUBLICATION supabase_realtime DROP TABLE %I.%I',+ published.schemaname, published.tablename+ );+ END LOOP;+END $$;diff --git a/packages/database/supabase/migrations/20261004193811_drop-stale-interceptor-overload.sql b/packages/database/supabase/migrations/20261004193811_drop-stale-interceptor-overload.sqlnew file mode 100644index 0000000000..57ffd10235--- /dev/null+++ b/packages/database/supabase/migrations/20261004193811_drop-stale-interceptor-overload.sql@@ -0,0 +1,6 @@+-- sync_finish_job_operation has two overloads. The interceptor dispatcher calls+-- (table, operation, new, old); the older (new, old, operation) form is left+-- over from before that contract and nothing calls it. A managed function file+-- (event-system/handlers/sync_finish_job_operation.sql) defines exactly one+-- function, and `authz sync` refuses a second overload.+DROP FUNCTION IF EXISTS public.sync_finish_job_operation(jsonb, jsonb, text);diff --git a/packages/database/supabase/migrations/20261004194527_event-attachments.sql b/packages/database/supabase/migrations/20261004194527_event-attachments.sqlnew file mode 100644index 0000000000..3fa09c5a85--- /dev/null+++ b/packages/database/supabase/migrations/20261004194527_event-attachments.sql@@ -0,0 +1,2150 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++CREATE OR REPLACE FUNCTION public.set_event_triggers(table_name_text text, before_functions text[] DEFAULT ARRAY[]::text[], after_functions text[] DEFAULT ARRAY[]::text[], queue_events boolean DEFAULT false, statement_functions text[] DEFAULT ARRAY[]::text[])+ RETURNS void+ LANGUAGE plpgsql+AS $function$+DECLARE+ existing TEXT;+ fn_args TEXT;+ live TEXT[];+ wanted TEXT[];+BEGIN+ -- Makes a table's event triggers exactly what one entry of+ -- packages/database/src/event-system/attachments.ts says: the interceptors+ -- that run before and after each row, whether changes are queued as events,+ -- and the statement handlers. Called with only the table name, it detaches+ -- everything.++ -- A table dropped since its entry was shipped has nothing to attach to.+ IF to_regclass(format('public.%I', table_name_text)) IS NULL THEN+ RETURN;+ END IF;++ -- Already as declared: touch nothing. Creating a trigger locks the table+ -- against writes until the transaction ends, so a migration that restates+ -- every table's entry must not re-create the ones that have not changed.+ SELECT coalesce(array_agg(t.tgname || ':' || encode(t.tgargs, 'escape') ORDER BY t.tgname), '{}')+ INTO live+ FROM pg_trigger t+ WHERE t.tgrelid = format('public.%I', table_name_text)::regclass+ AND NOT t.tgisinternal+ AND t.tgname LIKE 'trg\_event\_%';++ SELECT coalesce(array_agg(w.name ORDER BY w.name), '{}')+ INTO wanted+ FROM (+ -- A trigger's arguments are stored NUL-terminated; a name is cut at 63 bytes.+ SELECT left('trg_event_sync_' || table_name_text, 63) || ':'+ || array_to_string(before_functions, '\000') || '\000'+ WHERE cardinality(before_functions) > 0+ UNION ALL+ SELECT left('trg_event_after_sync_' || table_name_text, 63) || ':'+ || array_to_string(after_functions, '\000') || '\000'+ WHERE cardinality(after_functions) > 0+ UNION ALL+ SELECT left('trg_event_async_' || op || '_' || table_name_text, 63) || ':'+ FROM unnest(ARRAY['ins', 'del', 'upd']) op+ WHERE queue_events+ UNION ALL+ SELECT left('trg_event_statement_' || fn || '_' || op, 63) || ':'+ FROM unnest(statement_functions) fn, unnest(ARRAY['ins', 'upd', 'del']) op+ ) w(name);++ IF live = wanted THEN+ RETURN;+ END IF;++ IF queue_events THEN+ PERFORM public.attach_event_trigger(table_name_text, before_functions, after_functions);+ ELSE+ -- attach_event_trigger always queues, so here the row-level triggers are+ -- created alone, with the same definitions it uses.+ FOR existing IN+ SELECT t.tgname+ FROM pg_trigger t+ WHERE t.tgrelid = format('public.%I', table_name_text)::regclass+ AND NOT t.tgisinternal+ AND (t.tgname LIKE 'trg\_event\_sync\_%'+ OR t.tgname LIKE 'trg\_event\_after\_sync\_%'+ OR t.tgname LIKE 'trg\_event\_async\_%')+ LOOP+ EXECUTE format('DROP TRIGGER IF EXISTS %2$I ON public.%1$I;', table_name_text, existing);+ END LOOP;++ IF array_length(before_functions, 1) > 0 THEN+ SELECT string_agg(quote_literal(x), ', ') INTO fn_args FROM unnest(before_functions) x;+ EXECUTE format('+ CREATE TRIGGER "trg_event_sync_%1$s"+ BEFORE INSERT OR UPDATE OR DELETE ON public.%1$I+ FOR EACH ROW+ EXECUTE FUNCTION public.dispatch_event_interceptors(%2$s);+ ', table_name_text, fn_args);+ END IF;++ IF array_length(after_functions, 1) > 0 THEN+ SELECT string_agg(quote_literal(x), ', ') INTO fn_args FROM unnest(after_functions) x;+ EXECUTE format('+ CREATE TRIGGER "trg_event_after_sync_%1$s"+ AFTER INSERT OR UPDATE OR DELETE ON public.%1$I+ FOR EACH ROW+ EXECUTE FUNCTION public.dispatch_event_after_interceptors(%2$s);+ ', table_name_text, fn_args);+ END IF;+ END IF;++ PERFORM public.attach_statement_handler(table_name_text, statement_functions);+END;+$function$;++CREATE OR REPLACE FUNCTION public.apply_item_stock_quantities()+ RETURNS trigger+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO 'public', 'pg_temp'+AS $function$+BEGIN+ IF TG_OP = 'INSERT' THEN+ INSERT INTO "itemStockQuantities" AS isq+ ("itemId", "companyId", "locationId", "quantityOnHand")+ SELECT+ "itemId",+ "companyId",+ COALESCE("locationId", ''),+ SUM(item_ledger_on_hand_contribution("quantity", "trackedEntityStatus"))+ FROM batched_new+ GROUP BY "itemId", "companyId", COALESCE("locationId", '')+ ORDER BY 1, 2, 3+ ON CONFLICT ("itemId", "companyId", "locationId")+ DO UPDATE SET "quantityOnHand" = isq."quantityOnHand" + EXCLUDED."quantityOnHand";++ ELSIF TG_OP = 'UPDATE' THEN+ -- Generic old-vs-new: subtract every old row's contribution at its old key+ -- and add every new row's at its new key. Covers the real case (a+ -- trackedEntityStatus flip) and any future quantity/location/item edit+ -- without special-casing.+ INSERT INTO "itemStockQuantities" AS isq+ ("itemId", "companyId", "locationId", "quantityOnHand")+ SELECT "itemId", "companyId", "locationId", SUM(delta)+ FROM (+ SELECT+ "itemId",+ "companyId",+ COALESCE("locationId", '') AS "locationId",+ -item_ledger_on_hand_contribution("quantity", "trackedEntityStatus") AS delta+ FROM batched_old+ UNION ALL+ SELECT+ "itemId",+ "companyId",+ COALESCE("locationId", ''),+ item_ledger_on_hand_contribution("quantity", "trackedEntityStatus")+ FROM batched_new+ ) d+ GROUP BY "itemId", "companyId", "locationId"+ -- A key whose net delta is zero already holds the right number; skipping it+ -- avoids taking a lock on every row a wide UPDATE happened to touch.+ HAVING SUM(delta) <> 0+ ORDER BY 1, 2, 3+ ON CONFLICT ("itemId", "companyId", "locationId")+ DO UPDATE SET "quantityOnHand" = isq."quantityOnHand" + EXCLUDED."quantityOnHand";++ ELSIF TG_OP = 'DELETE' THEN+ -- Defensive: no application path deletes itemLedger rows today. A key left+ -- at zero with no backing ledger rows is removed by the nightly+ -- reconciliation.+ INSERT INTO "itemStockQuantities" AS isq+ ("itemId", "companyId", "locationId", "quantityOnHand")+ SELECT+ "itemId",+ "companyId",+ COALESCE("locationId", ''),+ -SUM(item_ledger_on_hand_contribution("quantity", "trackedEntityStatus"))+ FROM batched_old+ GROUP BY "itemId", "companyId", COALESCE("locationId", '')+ ORDER BY 1, 2, 3+ ON CONFLICT ("itemId", "companyId", "locationId")+ DO UPDATE SET "quantityOnHand" = isq."quantityOnHand" + EXCLUDED."quantityOnHand";+ END IF;++ RETURN NULL;+END;+$function$;++CREATE OR REPLACE FUNCTION public.prevent_posted_purchase_invoice_deletion(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation = 'DELETE' THEN+ IF NOT EXISTS (SELECT 1 FROM "company" WHERE id = (p_old->>'companyId')) THEN+ RETURN;+ END IF;+ IF p_old->>'status' IS DISTINCT FROM 'Draft' THEN+ RAISE EXCEPTION 'Cannot delete purchase invoice with status "%". Only Draft invoices can be deleted.', p_old->>'status';+ END IF;+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.prevent_posted_sales_invoice_deletion(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation = 'DELETE' THEN+ IF NOT EXISTS (SELECT 1 FROM "company" WHERE id = (p_old->>'companyId')) THEN+ RETURN;+ END IF;+ IF p_old->>'status' IS DISTINCT FROM 'Draft' THEN+ RAISE EXCEPTION 'Cannot delete sales invoice with status "%". Only Draft invoices can be deleted.', p_old->>'status';+ END IF;+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.set_shelf_life_on_operation_done(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_old_status TEXT;+ v_new_status TEXT;+BEGIN+ IF p_operation <> 'UPDATE' THEN+ RETURN;+ END IF;++ v_new_status := p_new->>'status';+ IF v_new_status <> 'Done' THEN+ RETURN;+ END IF;++ v_old_status := p_old->>'status';+ IF v_old_status = 'Done' THEN+ RETURN;+ END IF;++ PERFORM set_shelf_life_for_operation(p_new->>'id', 'After');+END;+$function$;++CREATE OR REPLACE FUNCTION public.set_shelf_life_on_operation_started(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_old_status TEXT;+ v_new_status TEXT;+BEGIN+ IF p_operation <> 'UPDATE' THEN+ RETURN;+ END IF;++ v_new_status := p_new->>'status';+ IF v_new_status <> 'In Progress' THEN+ RETURN;+ END IF;++ v_old_status := p_old->>'status';+ IF v_old_status = 'In Progress' THEN+ RETURN;+ END IF;++ PERFORM set_shelf_life_for_operation(p_new->>'id', 'Before');+END;+$function$;++CREATE OR REPLACE FUNCTION public.storage_unit_block_location_change_with_children(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_id TEXT;+ v_new_location TEXT;+ v_old_location TEXT;+BEGIN+ IF p_operation <> 'UPDATE' THEN+ RETURN;+ END IF;++ v_new_location := p_new->>'locationId';+ v_old_location := p_old->>'locationId';++ IF v_new_location IS NOT DISTINCT FROM v_old_location THEN+ RETURN;+ END IF;++ v_id := p_old->>'id';++ IF EXISTS (SELECT 1 FROM "storageUnit" WHERE "parentId" = v_id) THEN+ RAISE EXCEPTION+ 'Cannot change locationId of storage unit % because it has child units',+ v_id;+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.storage_unit_enforce_no_cycle(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_self_id TEXT;+ v_cursor_id TEXT;+ v_depth INTEGER := 0;+BEGIN+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN+ RETURN;+ END IF;++ v_cursor_id := p_new->>'parentId';+ IF v_cursor_id IS NULL THEN+ RETURN;+ END IF;++ v_self_id := p_new->>'id';++ WHILE v_cursor_id IS NOT NULL LOOP+ IF v_cursor_id = v_self_id THEN+ RAISE EXCEPTION 'Cycle detected in storage unit hierarchy at %', v_self_id;+ END IF;++ v_depth := v_depth + 1;+ IF v_depth > 1000 THEN+ RAISE EXCEPTION 'Storage unit hierarchy exceeds max depth (possible cycle)';+ END IF;++ SELECT "parentId" INTO v_cursor_id+ FROM "storageUnit"+ WHERE "id" = v_cursor_id;+ END LOOP;+END;+$function$;++CREATE OR REPLACE FUNCTION public.storage_unit_enforce_same_location(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_parent_id TEXT;+ v_parent_location TEXT;+ v_new_location TEXT;+BEGIN+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN+ RETURN;+ END IF;++ v_parent_id := p_new->>'parentId';+ IF v_parent_id IS NULL THEN+ RETURN;+ END IF;++ v_new_location := p_new->>'locationId';++ SELECT "locationId"+ INTO v_parent_location+ FROM "storageUnit"+ WHERE "id" = v_parent_id;++ IF v_parent_location IS NULL THEN+ RAISE EXCEPTION 'Parent storage unit % does not exist', v_parent_id;+ END IF;++ IF v_parent_location <> v_new_location THEN+ RAISE EXCEPTION+ 'Parent storage unit % is in location %, but this unit is in location %; they must match',+ v_parent_id, v_parent_location, v_new_location;+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_add_customer_account_to_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "membership" ("groupId", "memberUserId")+ VALUES (+ p_new->>'customerId',+ p_new->>'id'+ );+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_add_employee_to_type_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "membership" ("groupId", "memberUserId")+ VALUES (+ p_new->>'employeeTypeId',+ p_new->>'id'+ );+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_add_supplier_account_to_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "membership" ("groupId", "memberUserId")+ VALUES (+ p_new->>'supplierId',+ p_new->>'id'+ );+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_address_to_parent(table_name text, operation text, new_data jsonb, old_data jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ address_id TEXT;+BEGIN+ IF operation = 'DELETE' THEN+ RETURN;+ END IF;++ IF current_setting('app.sync_in_progress', true) = 'true' THEN+ RETURN;+ END IF;++ address_id := COALESCE(new_data->>'id', old_data->>'id');++ UPDATE "customer" c+ SET "updatedAt" = NOW()+ FROM "customerLocation" cl+ WHERE cl."addressId" = address_id+ AND cl."customerId" = c.id;++ UPDATE "supplier" s+ SET "updatedAt" = NOW()+ FROM "supplierLocation" sl+ WHERE sl."addressId" = address_id+ AND sl."supplierId" = s.id;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_archive_other_procedures(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF NOT ((p_new->>'status') = 'Active' AND ((p_old->>'status') IS NULL OR (p_old->>'status') != 'Active')) THEN+ RETURN;+ END IF;++ UPDATE procedure+ SET status = 'Archived'+ WHERE name = p_new->>'name'+ AND "companyId" = p_new->>'companyId'+ AND id != p_new->>'id'+ AND status = 'Active';+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_archive_other_quality_documents(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF NOT ((p_new->>'status') = 'Active' AND ((p_old->>'status') IS NULL OR (p_old->>'status') != 'Active')) THEN+ RETURN;+ END IF;++ UPDATE "qualityDocument"+ SET status = 'Archived'+ WHERE name = p_new->>'name'+ AND "companyId" = p_new->>'companyId'+ AND id != p_new->>'id'+ AND status = 'Active';+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_check_job_material_self_reference(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'pg_temp'+AS $function$+DECLARE+ job_item_id TEXT;+BEGIN+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN RETURN; END IF;++ SELECT "itemId" INTO job_item_id+ FROM job+ WHERE "id" = p_new->>'jobId'+ AND "companyId" = p_new->>'companyId';++ IF job_item_id = p_new->>'itemId' THEN+ RAISE EXCEPTION 'A job cannot consume the item it produces as a material'+ USING ERRCODE = 'check_violation';+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_check_method_material_self_reference(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'pg_temp'+AS $function$+DECLARE+ parent_item_id TEXT;+ cycle_found BOOLEAN;+BEGIN+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN RETURN; END IF;++ -- A make method belongs to exactly one item, so a materialMakeMethodId equal+ -- to the row's own makeMethodId is always a self-loop regardless of itemId.+ IF p_new->>'materialMakeMethodId' = p_new->>'makeMethodId' THEN+ RAISE EXCEPTION 'An item cannot use its own make method as a material sub-method'+ USING ERRCODE = 'check_violation';+ END IF;++ SELECT "itemId" INTO parent_item_id+ FROM "makeMethod"+ WHERE "id" = p_new->>'makeMethodId'+ AND "companyId" = p_new->>'companyId';++ IF parent_item_id = p_new->>'itemId' THEN+ RAISE EXCEPTION 'An item cannot be a material on its own bill of materials'+ USING ERRCODE = 'check_violation';+ END IF;++ -- Multi-node cycles (A needs B, B needs A): would the new material's own+ -- active-method BOM graph reach back to this method's item? Bounded walk+ -- over active methods only — the graph MRP plans against. UNION (not UNION+ -- ALL) dedupes, so the walk terminates even over pre-existing cycles; the+ -- depth cap is a backstop. BOM edits are UI-volume, so the walk is cheap.+ WITH RECURSIVE reachable AS (+ SELECT p_new->>'itemId' AS item_id, 0 AS depth+ UNION+ SELECT mm."itemId", r.depth + 1+ FROM reachable r+ JOIN "activeMakeMethods" amm+ ON amm."itemId" = r.item_id+ AND amm."companyId" = p_new->>'companyId'+ JOIN "methodMaterial" mm+ ON mm."makeMethodId" = amm."id"+ AND mm."companyId" = amm."companyId"+ WHERE r.depth < 100+ )+ SELECT EXISTS (SELECT 1 FROM reachable WHERE item_id = parent_item_id)+ INTO cycle_found;++ IF cycle_found THEN+ RAISE EXCEPTION 'Adding this material would create a loop in the bill of materials: its own BOM already contains this item'+ USING ERRCODE = 'check_violation';+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_contact_to_parent(table_name text, operation text, new_data jsonb, old_data jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ contact_id TEXT;+BEGIN+ IF operation = 'DELETE' THEN+ RETURN;+ END IF;++ IF current_setting('app.sync_in_progress', true) = 'true' THEN+ RETURN;+ END IF;++ contact_id := COALESCE(new_data->>'id', old_data->>'id');++ UPDATE "customer" c+ SET "updatedAt" = NOW()+ FROM "customerContact" cc+ WHERE cc."contactId" = contact_id+ AND cc."customerId" = c.id;++ UPDATE "supplier" s+ SET "updatedAt" = NOW()+ FROM "supplierContact" sc+ WHERE sc."contactId" = contact_id+ AND sc."supplierId" = s.id;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_create_customer_entries(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "customerPayment"("customerId", "invoiceCustomerId", "companyId")+ VALUES (p_new->>'id', p_new->>'id', p_new->>'companyId');++ INSERT INTO "customerShipping"("customerId", "shippingCustomerId", "companyId")+ VALUES (p_new->>'id', p_new->>'id', p_new->>'companyId');++ INSERT INTO "customerTax"("customerId", "companyId")+ VALUES (p_new->>'id', p_new->>'companyId');+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_create_customer_org_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "group" ("id", "name", "isCustomerOrgGroup", "companyId")+ VALUES (p_new->>'id', p_new->>'name', TRUE, p_new->>'companyId');++ IF p_new->>'customerTypeId' IS NOT NULL THEN+ INSERT INTO "membership"("groupId", "memberGroupId")+ VALUES (p_new->>'customerTypeId', p_new->>'id');+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_create_customer_type_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "group" ("id", "name", "isCustomerTypeGroup", "companyId")+ VALUES (+ p_new->>'id',+ p_new->>'name',+ TRUE,+ p_new->>'companyId'+ );++ INSERT INTO "membership" ("groupId", "memberGroupId")+ VALUES (+ '11111111-1111-'+ || substring((p_new->>'companyId')::text, 1, 4) || '-'+ || substring((p_new->>'companyId')::text, 5, 4) || '-'+ || substring((p_new->>'companyId')::text, 9, 12),+ p_new->>'id'+ );+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_create_employee_type_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "group" ("id", "name", "isEmployeeTypeGroup", "companyId")+ VALUES (+ p_new->>'id',+ p_new->>'name',+ TRUE,+ p_new->>'companyId'+ );++ INSERT INTO "membership" ("groupId", "memberGroupId")+ VALUES (+ '00000000-0000-'+ || substring((p_new->>'companyId')::text, 1, 4) || '-'+ || substring((p_new->>'companyId')::text, 5, 4) || '-'+ || substring((p_new->>'companyId')::text, 9, 12),+ p_new->>'id'+ );+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_create_item_related_records(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ base_currency TEXT;+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ SELECT "baseCurrencyCode"+ INTO base_currency+ FROM "company"+ WHERE "id" = p_new->>'companyId';++ INSERT INTO "itemCost"("itemId", "costingMethod", "createdBy", "companyId")+ VALUES (p_new->>'id', 'FIFO', p_new->>'createdBy', p_new->>'companyId');++ INSERT INTO "itemReplenishment"("itemId", "createdBy", "companyId")+ VALUES (p_new->>'id', p_new->>'createdBy', p_new->>'companyId');++ INSERT INTO "itemUnitSalePrice"("itemId", "currencyCode", "createdBy", "companyId")+ VALUES (p_new->>'id', COALESCE(base_currency, 'USD'), p_new->>'createdBy', p_new->>'companyId');++ INSERT INTO "itemPlanning"("itemId", "locationId", "createdBy", "companyId")+ SELECT+ p_new->>'id',+ l.id,+ p_new->>'createdBy',+ p_new->>'companyId'+ FROM "location" l+ WHERE l."companyId" = p_new->>'companyId';+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_create_location_related_records(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ -- Only create itemPlanning records for the new location+ -- Skip the postingGroupInventory inserts since that table no longer exists+ INSERT INTO "itemPlanning" ("itemId", "locationId", "createdBy", "companyId", "createdAt", "updatedAt")+ SELECT+ i.id AS "itemId",+ p_new->>'id' AS "locationId",+ i."createdBy",+ i."companyId",+ NOW(),+ NOW()+ FROM "item" i+ WHERE i."companyId" = p_new->>'companyId';+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_create_make_method_related_records(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ IF (p_new->>'type') IN ('Part', 'Tool', 'Service') THEN+ INSERT INTO "makeMethod"("itemId", "createdBy", "companyId")+ VALUES (p_new->>'id', p_new->>'createdBy', p_new->>'companyId');+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_create_nc_external_link(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_external_link_id UUID;+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "externalLink" ("documentType", "documentId", "companyId")+ VALUES ('Non-Conformance Supplier', p_new->>'id', p_new->>'companyId')+ ON CONFLICT ("documentId", "documentType", "companyId") DO UPDATE SET+ "documentType" = EXCLUDED."documentType"+ RETURNING "id" INTO v_external_link_id;++ UPDATE "nonConformanceSupplier"+ SET "externalLinkId" = v_external_link_id+ WHERE "id" = p_new->>'id';+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_create_supplier_entries(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "supplierPayment"("supplierId", "invoiceSupplierId", "companyId")+ VALUES (p_new->>'id', p_new->>'id', p_new->>'companyId');++ INSERT INTO "supplierShipping"("supplierId", "shippingSupplierId", "companyId")+ VALUES (p_new->>'id', p_new->>'id', p_new->>'companyId');++ INSERT INTO "supplierTax"("supplierId", "companyId")+ VALUES (p_new->>'id', p_new->>'companyId');+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_create_supplier_org_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "group" ("id", "name", "isSupplierOrgGroup", "companyId")+ VALUES (p_new->>'id', p_new->>'name', TRUE, p_new->>'companyId');++ IF p_new->>'supplierTypeId' IS NOT NULL THEN+ INSERT INTO "membership"("groupId", "memberGroupId")+ VALUES (p_new->>'supplierTypeId', p_new->>'id');+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_create_supplier_type_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "group" ("id", "name", "isSupplierTypeGroup", "companyId")+ VALUES (+ p_new->>'id',+ p_new->>'name',+ TRUE,+ p_new->>'companyId'+ );++ INSERT INTO "membership" ("groupId", "memberGroupId")+ VALUES (+ '22222222-2222-'+ || substring((p_new->>'companyId')::text, 1, 4) || '-'+ || substring((p_new->>'companyId')::text, 5, 4) || '-'+ || substring((p_new->>'companyId')::text, 9, 12),+ p_new->>'id'+ );+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_create_user_identity_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "group" ("id", "name", "isIdentityGroup")+ VALUES (+ p_new->>'id',+ p_new->>'fullName',+ TRUE+ );++ INSERT INTO "membership" ("groupId", "memberUserId")+ VALUES (+ p_new->>'id',+ p_new->>'id'+ );+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_delete_tracked_entity_on_job_make_method(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'DELETE' THEN RETURN; END IF;++ DELETE FROM "trackedEntity"+ WHERE "attributes"->>'Job Make Method' = p_old->>'id';+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_delete_user_identity_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'DELETE' THEN RETURN; END IF;++ DELETE FROM "group"+ WHERE "id" = p_old->>'id'+ AND "isIdentityGroup" = TRUE;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_edit_document_transaction(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ INSERT INTO "documentTransaction" ("documentId", "type", "userId")+ VALUES (p_new->>'id', 'Edit', p_new->>'createdBy');+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_finish_job_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+DECLARE+ v_job_location_id TEXT;+ v_job_storage_unit_id TEXT;+ v_job_quantity NUMERIC;+ v_sales_order_id TEXT;+ v_quantity_complete NUMERIC;+ v_quantity_lost NUMERIC;+ v_quantity_received NUMERIC;+ v_job_status TEXT;+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF (p_new->>'status') != 'Done' OR (p_old->>'status') = 'Done' THEN RETURN; END IF;++ UPDATE "productionEvent"+ SET "endTime" = NOW()+ WHERE "jobOperationId" = p_new->>'id'+ AND "endTime" IS NULL;++ UPDATE "jobOperation" op+ SET status = 'Ready'+ WHERE EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ WHERE dep."operationId" = op.id+ AND dep."dependsOnId" = p_new->>'id'+ AND op.status = 'Waiting'+ )+ AND NOT EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep2+ JOIN "jobOperation" jo2 ON jo2.id = dep2."dependsOnId"+ WHERE dep2."operationId" = op.id+ AND jo2.status != 'Done'+ AND jo2.id != p_new->>'id'+ );++ SELECT status INTO v_job_status FROM "job" WHERE id = p_new->>'jobId';+ -- A Draft/Planned job's operation can only reach Done through a released+ -- BATCH (batch release outranks job release for floor visibility), so the+ -- run genuinely happened. Completing the batch must complete those jobs+ -- too: otherwise their output lots exist while their receipts never post,+ -- and a merged output lot carries only the received fraction of its+ -- quantity.+ IF v_job_status NOT IN ('Ready', 'In Progress', 'Paused')+ AND NOT (+ (p_new->>'jobOperationBatchId') IS NOT NULL+ AND v_job_status IN ('Draft', 'Planned')+ ) THEN+ RETURN;+ END IF;++ IF is_last_job_operation(p_new->>'id') THEN+ SELECT "locationId", "storageUnitId", quantity, "salesOrderId", "quantityReceivedToInventory"+ INTO v_job_location_id, v_job_storage_unit_id, v_job_quantity, v_sales_order_id, v_quantity_received+ FROM "job"+ WHERE id = p_new->>'jobId';++ v_quantity_complete := (+ SELECT COALESCE(SUM(terminal_jo."quantityComplete"), 0)+ FROM "jobOperation" terminal_jo+ INNER JOIN "jobMakeMethod" terminal_jmm ON terminal_jmm.id = terminal_jo."jobMakeMethodId"+ WHERE terminal_jo."jobId" = p_new->>'jobId'+ AND terminal_jmm."parentMaterialId" IS NULL+ AND NOT EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ INNER JOIN "jobOperation" child_jo ON child_jo.id = dep."operationId"+ INNER JOIN "jobMakeMethod" child_jmm ON child_jmm.id = child_jo."jobMakeMethodId"+ WHERE dep."dependsOnId" = terminal_jo.id+ AND child_jmm."parentMaterialId" IS NULL+ )+ );++ IF COALESCE(v_quantity_complete, 0) = 0 THEN+ -- The zero fallback exists for the quantity-less Finish flow (no+ -- productionQuantity ever recorded). When the job DID record scrap or+ -- rework, zero completions is a real outcome (e.g. a fully-scrapped+ -- lot) — falling back would receive scrapped units into stock.+ SELECT COALESCE(SUM(COALESCE("quantityScrapped", 0) + COALESCE("quantityReworked", 0)), 0)+ INTO v_quantity_lost+ FROM "jobOperation"+ WHERE "jobId" = p_new->>'jobId';++ IF v_quantity_lost = 0 THEN+ v_quantity_complete := v_job_quantity;+ ELSE+ -- Nothing to receive: close the job without posting Assembly Output.+ -- Materials were already consumed by the scrap/complete flows; WIP+ -- cost disposition for fully-scrapped jobs is a costing follow-up.+ UPDATE "job"+ SET status = 'Completed',+ "completedDate" = NOW(),+ "quantityComplete" = 0,+ "updatedBy" = COALESCE(p_new->>'updatedBy', p_new->>'createdBy'),+ "updatedAt" = NOW()+ WHERE id = p_new->>'jobId';+ RETURN;+ END IF;+ END IF;++ -- A reopened job may already have received more than its operations now+ -- report. complete_job_to_inventory refuses a quantity below what was+ -- received, and refusing here would block the Done update itself.+ v_quantity_complete := GREATEST(v_quantity_complete, COALESCE(v_quantity_received, 0));++ PERFORM complete_job_to_inventory(+ p_job_id := p_new->>'jobId',+ p_quantity_complete := v_quantity_complete,+ p_storage_unit_id := v_job_storage_unit_id,+ p_location_id := v_job_location_id,+ p_company_id := p_new->>'companyId',+ p_user_id := COALESCE(p_new->>'updatedBy', p_new->>'createdBy')+ );+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_insert_company_related_records(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "terms" ("id")+ VALUES (p_new->>'id');++ INSERT INTO "companySettings" ("id")+ VALUES (p_new->>'id');+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_insert_job_make_method(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_item_readable_id TEXT;+ v_item_tracking_type TEXT;+ v_job_make_method_id TEXT;+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ SELECT "readableIdWithRevision", "itemTrackingType"+ INTO v_item_readable_id, v_item_tracking_type+ FROM "item"+ WHERE "id" = p_new->>'itemId';++ INSERT INTO "jobMakeMethod" (+ "jobId", "itemId", "companyId", "createdBy",+ "requiresSerialTracking", "requiresBatchTracking"+ ) VALUES (+ p_new->>'id', p_new->>'itemId', p_new->>'companyId', p_new->>'createdBy',+ v_item_tracking_type = 'Serial', v_item_tracking_type = 'Batch'+ )+ RETURNING "id" INTO v_job_make_method_id;++ INSERT INTO "trackedEntity" (+ "sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",+ "quantity", "status", "companyId", "createdBy", "attributes", "itemId"+ ) VALUES (+ 'Item', p_new->>'itemId', v_item_readable_id,+ COALESCE((p_new->>'quantity')::numeric, 1), 'Reserved',+ p_new->>'companyId', p_new->>'createdBy',+ jsonb_build_object('Job', p_new->>'id', 'Job Make Method', v_job_make_method_id),+ p_new->>'itemId'+ );+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_insert_job_material_make_method(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_item_readable_id TEXT;+ v_item_tracking_type TEXT;+ v_job_make_method_id TEXT;+ v_version NUMERIC(10, 2);+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;+ IF (p_new->>'methodType') != 'Make to Order' THEN RETURN; END IF;+ IF (p_new->>'itemId') IS NULL THEN RETURN; END IF;++ SELECT "readableIdWithRevision", "itemTrackingType"+ INTO v_item_readable_id, v_item_tracking_type+ FROM "item"+ WHERE "id" = p_new->>'itemId';++ SELECT "version" INTO v_version FROM "activeMakeMethods" WHERE "itemId" = p_new->>'itemId';++ INSERT INTO "jobMakeMethod" (+ "jobId", "parentMaterialId", "itemId", "companyId", "createdBy",+ "requiresSerialTracking", "requiresBatchTracking", "version"+ ) VALUES (+ p_new->>'jobId', p_new->>'id', p_new->>'itemId', p_new->>'companyId', p_new->>'createdBy',+ v_item_tracking_type = 'Serial', v_item_tracking_type = 'Batch', v_version+ )+ RETURNING "id" INTO v_job_make_method_id;++ INSERT INTO "trackedEntity" (+ "sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",+ "quantity", "status", "companyId", "createdBy", "attributes", "itemId"+ ) VALUES (+ 'Item', p_new->>'itemId', v_item_readable_id,+ (p_new->>'quantity')::numeric, 'Reserved',+ p_new->>'companyId', p_new->>'createdBy',+ jsonb_build_object('Job', p_new->>'jobId', 'Job Make Method', v_job_make_method_id, 'Job Material', p_new->>'id'),+ p_new->>'itemId'+ );+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_insert_quote_line_make_method(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_version NUMERIC(10, 2);+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;+ IF (p_new->>'methodType') != 'Make to Order' THEN RETURN; END IF;+ IF (p_new->>'itemId') IS NULL THEN RETURN; END IF;++ SELECT "version" INTO v_version FROM "activeMakeMethods" WHERE "itemId" = p_new->>'itemId';++ INSERT INTO "quoteMakeMethod" (+ "quoteId", "quoteLineId", "itemId", "companyId", "createdAt", "createdBy", "version"+ ) VALUES (+ p_new->>'quoteId', p_new->>'id', p_new->>'itemId',+ p_new->>'companyId', NOW(), p_new->>'createdBy', v_version+ );+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_insert_quote_material_make_method(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_version NUMERIC(10, 2);+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;+ IF (p_new->>'methodType') != 'Make to Order' THEN RETURN; END IF;+ IF (p_new->>'itemId') IS NULL THEN RETURN; END IF;++ SELECT "version" INTO v_version FROM "activeMakeMethods" WHERE "itemId" = p_new->>'itemId';++ INSERT INTO "quoteMakeMethod" (+ "quoteId", "quoteLineId", "parentMaterialId", "itemId", "companyId", "createdAt", "createdBy", "version"+ ) VALUES (+ p_new->>'quoteId', p_new->>'quoteLineId', p_new->>'id', p_new->>'itemId',+ p_new->>'companyId', NOW(), p_new->>'createdBy', v_version+ );+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_job_complete_or_canceled(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ group_ids TEXT[];+BEGIN+ IF p_operation = 'UPDATE'+ AND (p_old->>'status') != (p_new->>'status')+ AND ((p_new->>'status') = 'Completed' OR (p_new->>'status') = 'Cancelled')+ THEN+ UPDATE "kanban"+ SET "jobId" = NULL+ WHERE "jobId" = p_new->>'id';++ -- Send notification on job completion+ IF (p_new->>'status') = 'Completed' THEN+ IF (p_new->>'salesOrderId') IS NULL THEN+ SELECT "inventoryJobCompletedNotificationGroup" INTO group_ids+ FROM "companySettings" WHERE "id" = p_new->>'companyId';+ ELSE+ SELECT "salesJobCompletedNotificationGroup" INTO group_ids+ FROM "companySettings" WHERE "id" = p_new->>'companyId';+ END IF;++ IF (p_new->>'assignee') IS NOT NULL THEN+ group_ids := array_append(COALESCE(group_ids, '{}'), p_new->>'assignee');+ END IF;++ IF array_length(group_ids, 1) > 0 THEN+ PERFORM util.send_inngest_event(+ 'carbon/notify',+ jsonb_build_object(+ 'companyId', p_new->>'companyId',+ 'documentId', p_new->>'id',+ 'event', 'job-completed',+ 'recipient', jsonb_build_object(+ 'type', 'group',+ 'groupIds', group_ids+ ),+ 'from', 'system'+ )+ );+ END IF;+ END IF;+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_job_recompute_service_line(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF (p_new->>'salesOrderLineId') IS NULL THEN RETURN; END IF;++ -- Only when the completion state actually changed.+ IF (p_old->>'status') IS NOT DISTINCT FROM (p_new->>'status') THEN RETURN; END IF;+ IF NOT (+ (p_old->>'status') IN ('Completed', 'Closed')+ OR (p_new->>'status') IN ('Completed', 'Closed')+ ) THEN+ RETURN;+ END IF;++ PERFORM recompute_service_line_fulfillment(+ p_new->>'salesOrderLineId',+ p_new->>'companyId',+ p_new->>'updatedBy'+ );+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_on_maintenance_dispatch_complete(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF NOT ((p_new->>'status') = 'Completed' AND ((p_old->>'status') IS NULL OR (p_old->>'status') != 'Completed')) THEN+ RETURN;+ END IF;++ -- End all active events for this dispatch+ UPDATE "maintenanceDispatchEvent"+ SET+ "endTime" = COALESCE((p_new->>'completedAt')::timestamptz, NOW()),+ "updatedBy" = p_new->>'updatedBy',+ "updatedAt" = NOW()+ WHERE+ "maintenanceDispatchId" = p_new->>'id'+ AND "endTime" IS NULL;++ -- Set actualEndTime if not already set+ IF (p_new->>'actualEndTime') IS NULL THEN+ UPDATE "maintenanceDispatch"+ SET+ "actualEndTime" = NOW(),+ "updatedBy" = p_new->>'updatedBy',+ "updatedAt" = NOW()+ WHERE id = p_new->>'id';+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_propagate_item_readable_id_to_tracked_entity(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF (p_new->>'readableIdWithRevision') IS NOT DISTINCT FROM (p_old->>'readableIdWithRevision') THEN+ RETURN;+ END IF;++ UPDATE "trackedEntity"+ SET "sourceDocumentReadableId" = p_new->>'readableIdWithRevision'+ WHERE "sourceDocument" = 'Item'+ AND "sourceDocumentId" = p_new->>'id';+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_protect_system_required_actions(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation = 'DELETE' THEN+ IF (p_old->>'systemType') IS NOT NULL THEN+ -- Allow cascading deletes when the parent company is being deleted+ IF NOT EXISTS (SELECT 1 FROM "company" WHERE id = p_old->>'companyId') THEN+ RETURN;+ END IF;+ RAISE EXCEPTION 'Cannot delete a system-defined required action. You may deactivate it instead.';+ END IF;+ END IF;++ IF p_operation = 'UPDATE' THEN+ IF (p_old->>'systemType') IS NOT NULL AND (p_new->>'systemType') IS DISTINCT FROM (p_old->>'systemType') THEN+ RAISE EXCEPTION 'Cannot change the systemType of a system-defined required action.';+ END IF;+ IF (p_old->>'systemType') IS NULL AND (p_new->>'systemType') IS NOT NULL THEN+ RAISE EXCEPTION 'Cannot assign a systemType to a custom required action.';+ END IF;+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_purchase_invoice_line_price_change(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation = 'UPDATE'+ AND ((p_new->>'unitPrice') IS DISTINCT FROM (p_old->>'unitPrice')+ OR (p_new->>'quantity') IS DISTINCT FROM (p_old->>'quantity'))+ THEN+ INSERT INTO "purchaseInvoicePriceChange" (+ "invoiceId", "invoiceLineId", "previousPrice", "newPrice",+ "previousQuantity", "newQuantity", "updatedBy"+ ) VALUES (+ p_new->>'invoiceId', p_new->>'id',+ (p_old->>'unitPrice')::numeric, (p_new->>'unitPrice')::numeric,+ (p_old->>'quantity')::numeric, (p_new->>'quantity')::numeric,+ COALESCE(p_new->>'updatedBy', p_new->>'createdBy')+ );+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_set_initial_dependency_status(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ -- Don't update if operation is already Done, In Progress, or Canceled+ IF EXISTS (+ SELECT 1+ FROM "jobOperation"+ WHERE id = p_new->>'operationId'+ AND status IN ('Done', 'In Progress', 'Canceled')+ ) THEN+ RETURN;+ END IF;++ -- Check if there are any incomplete dependencies+ IF EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ JOIN "jobOperation" jo ON jo.id = dep."dependsOnId"+ WHERE dep."operationId" = p_new->>'operationId'+ AND jo.status != 'Done'+ ) THEN+ UPDATE "jobOperation"+ SET status = 'Waiting'+ WHERE id = p_new->>'operationId';+ ELSE+ UPDATE "jobOperation"+ SET status = 'Ready'+ WHERE id = p_new->>'operationId';+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_set_job_operation_in_progress(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ -- Only set to In Progress if endTime is NULL (event is starting, not already ended)+ IF (p_new->>'endTime') IS NULL THEN+ UPDATE "jobOperation"+ SET "status" = 'In Progress'+ WHERE id = p_new->>'jobOperationId';+ END IF;++ -- Set parent job to In Progress if it is still Ready+ UPDATE "job"+ SET "status" = 'In Progress'+ WHERE id = (+ SELECT "jobId" FROM "jobOperation" WHERE id = p_new->>'jobOperationId'+ )+ AND "status" = 'Ready';+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_update_customer_type_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ IF p_old->>'customerTypeId' IS NOT NULL THEN+ IF p_new->>'customerTypeId' IS NOT NULL THEN+ UPDATE "membership" SET "groupId" = p_new->>'customerTypeId'+ WHERE "groupId" = p_old->>'customerTypeId' AND "memberGroupId" = p_new->>'id';+ ELSE+ DELETE FROM "membership"+ WHERE "groupId" = p_old->>'customerTypeId' AND "memberGroupId" = p_new->>'id';+ END IF;+ ELSE+ IF p_new->>'customerTypeId' IS NOT NULL THEN+ INSERT INTO "membership" ("groupId", "memberGroupId")+ VALUES (p_new->>'customerTypeId', p_new->>'id');+ END IF;+ END IF;++ UPDATE "group" SET "name" = p_new->>'name'+ WHERE "id" = p_new->>'id' AND "isCustomerOrgGroup" = TRUE;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_update_customer_type_group_name(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ UPDATE "group"+ SET "name" = p_new->>'name'+ WHERE "id" = p_new->>'id'+ AND "isCustomerTypeGroup" = TRUE;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_update_employee_type_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ UPDATE "group"+ SET "name" = p_new->>'name'+ WHERE "id" = p_new->>'id'+ AND "isEmployeeTypeGroup" = TRUE;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_update_employee_type_membership(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ UPDATE "membership"+ SET "groupId" = p_new->>'employeeTypeId'+ WHERE "groupId" = p_old->>'employeeTypeId'+ AND "memberUserId" = p_new->>'id';+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_update_job_material_make_method_item_id(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_item_readable_id TEXT;+ v_item_tracking_type TEXT;+ v_job_make_method_id TEXT;+ -- Bare NUMERIC: the repo bans a precision spec on NUMERIC, and the+ -- conformance gate scans migration TEXT — so carrying the original+ -- declaration's precision forward registered as a new violation (as does+ -- quoting it in a comment). Behaviour is identical: makeMethod.version is+ -- itself a constrained numeric, so the value round-trips through this local+ -- unchanged and lands back in the same column.+ v_version NUMERIC;+ v_attributes JSONB;+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ IF NOT (+ ((p_old->>'methodType') = 'Make to Order' AND (p_old->>'itemId') IS DISTINCT FROM (p_new->>'itemId'))+ OR ((p_new->>'methodType') = 'Make to Order' AND (p_old->>'methodType') != 'Make to Order')+ ) THEN+ RETURN;+ END IF;++ -- Both lookups are company-scoped: "item" is keyed ("id", "companyId") and+ -- "activeMakeMethods" is per company, so matching on the item id alone could+ -- read another tenant's row. Pre-existing in the definition this replaces.+ SELECT "readableIdWithRevision", "itemTrackingType"+ INTO v_item_readable_id, v_item_tracking_type+ FROM "item"+ WHERE "id" = p_new->>'itemId'+ AND "companyId" = p_new->>'companyId';++ SELECT "version" INTO v_version FROM "activeMakeMethods"+ WHERE "itemId" = p_new->>'itemId'+ AND "companyId" = p_new->>'companyId';++ IF NOT EXISTS (+ SELECT 1 FROM "jobMakeMethod"+ WHERE "jobId" = p_new->>'jobId' AND "parentMaterialId" = p_new->>'id'+ ) THEN+ INSERT INTO "jobMakeMethod" (+ "jobId", "parentMaterialId", "itemId", "companyId", "createdBy",+ "requiresSerialTracking", "requiresBatchTracking", "version"+ ) VALUES (+ p_new->>'jobId', p_new->>'id', p_new->>'itemId', p_new->>'companyId', p_new->>'createdBy',+ v_item_tracking_type = 'Serial', v_item_tracking_type = 'Batch', v_version+ )+ RETURNING "id" INTO v_job_make_method_id;++ INSERT INTO "trackedEntity" (+ "sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",+ "quantity", "status", "companyId", "createdBy", "attributes", "itemId"+ ) VALUES (+ 'Item', p_new->>'itemId', v_item_readable_id,+ (p_new->>'quantity')::numeric, 'Reserved',+ p_new->>'companyId', p_new->>'createdBy',+ jsonb_build_object('Job', p_new->>'jobId', 'Job Make Method', v_job_make_method_id, 'Job Material', p_new->>'id'),+ p_new->>'itemId'+ );+ ELSE+ UPDATE "jobMakeMethod"+ SET "itemId" = p_new->>'itemId',+ "requiresSerialTracking" = (v_item_tracking_type = 'Serial'),+ "requiresBatchTracking" = (v_item_tracking_type = 'Batch'),+ "version" = v_version+ WHERE "jobId" = p_new->>'jobId' AND "parentMaterialId" = p_new->>'id'+ RETURNING "id" INTO v_job_make_method_id;++ v_attributes := jsonb_build_object(+ 'Job', p_new->>'jobId',+ 'Job Make Method', v_job_make_method_id,+ 'Job Material', p_new->>'id'+ );++ -- Repoint what is already there. Restricted to 'Reserved': an entity that+ -- has been consumed or received is history, and rewriting its item would+ -- falsify what was actually built.+ UPDATE "trackedEntity"+ SET "sourceDocumentId" = p_new->>'itemId',+ "sourceDocumentReadableId" = v_item_readable_id,+ "itemId" = p_new->>'itemId',+ "quantity" = (p_new->>'quantity')::numeric,+ -- Merge, don't replace: the shelf-life stamp writes expirationDate into+ -- this same attributes object, and an assignment would silently drop it.+ "attributes" = "attributes" || v_attributes+ WHERE "companyId" = p_new->>'companyId'+ AND "status" = 'Reserved'+ AND "attributes"->>'Job Material' = p_new->>'id';++ -- Only when there was nothing to repoint.+ IF NOT FOUND THEN+ INSERT INTO "trackedEntity" (+ "sourceDocument", "sourceDocumentId", "sourceDocumentReadableId",+ "quantity", "status", "companyId", "createdBy", "attributes", "itemId"+ ) VALUES (+ 'Item', p_new->>'itemId', v_item_readable_id,+ (p_new->>'quantity')::numeric, 'Reserved',+ p_new->>'companyId', p_new->>'createdBy',+ v_attributes,+ p_new->>'itemId'+ );+ END IF;+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_update_job_operation_quantities(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+DECLARE+ v_job_operation_id TEXT;+ v_job_id TEXT;+ v_user_id TEXT;+ v_is_last_top_level_operation BOOLEAN := FALSE;+BEGIN+ v_user_id := COALESCE(+ p_new->>'updatedBy', p_new->>'createdBy',+ p_old->>'updatedBy', p_old->>'createdBy'+ );++ IF p_operation = 'INSERT' THEN+ v_job_operation_id := p_new->>'jobOperationId';++ UPDATE "jobOperation"+ SET+ "quantityComplete" = "quantityComplete" ++ CASE WHEN (p_new->>'type') = 'Production' THEN (p_new->>'quantity')::numeric ELSE 0 END,+ "quantityReworked" = "quantityReworked" ++ CASE WHEN (p_new->>'type') = 'Rework' THEN (p_new->>'quantity')::numeric ELSE 0 END,+ "quantityScrapped" = "quantityScrapped" ++ CASE WHEN (p_new->>'type') = 'Scrap' THEN (p_new->>'quantity')::numeric ELSE 0 END+ WHERE id = v_job_operation_id;++ ELSIF p_operation = 'UPDATE' THEN+ v_job_operation_id := p_new->>'jobOperationId';++ UPDATE "jobOperation"+ SET+ "quantityComplete" = "quantityComplete"+ - CASE WHEN (p_old->>'type') = 'Production' THEN (p_old->>'quantity')::numeric ELSE 0 END+ + CASE WHEN (p_new->>'type') = 'Production' THEN (p_new->>'quantity')::numeric ELSE 0 END,+ "quantityReworked" = "quantityReworked"+ - CASE WHEN (p_old->>'type') = 'Rework' THEN (p_old->>'quantity')::numeric ELSE 0 END+ + CASE WHEN (p_new->>'type') = 'Rework' THEN (p_new->>'quantity')::numeric ELSE 0 END,+ "quantityScrapped" = "quantityScrapped"+ - CASE WHEN (p_old->>'type') = 'Scrap' THEN (p_old->>'quantity')::numeric ELSE 0 END+ + CASE WHEN (p_new->>'type') = 'Scrap' THEN (p_new->>'quantity')::numeric ELSE 0 END+ WHERE id = v_job_operation_id;++ ELSIF p_operation = 'DELETE' THEN+ v_job_operation_id := p_old->>'jobOperationId';++ UPDATE "jobOperation"+ SET+ "quantityComplete" = "quantityComplete" -+ CASE WHEN (p_old->>'type') = 'Production' THEN (p_old->>'quantity')::numeric ELSE 0 END,+ "quantityReworked" = "quantityReworked" -+ CASE WHEN (p_old->>'type') = 'Rework' THEN (p_old->>'quantity')::numeric ELSE 0 END,+ "quantityScrapped" = "quantityScrapped" -+ CASE WHEN (p_old->>'type') = 'Scrap' THEN (p_old->>'quantity')::numeric ELSE 0 END+ WHERE id = v_job_operation_id;+ END IF;++ UPDATE "jobOperation"+ SET "status" = 'Done',+ "updatedBy" = COALESCE(v_user_id, "updatedBy", "createdBy"),+ "updatedAt" = NOW()+ WHERE id = v_job_operation_id+ AND "status" NOT IN ('Done', 'Canceled')+ AND "targetQuantity" > 0+ AND ("quantityComplete" + "quantityReworked") >= "targetQuantity";++ SELECT jo."jobId" INTO v_job_id+ FROM "jobOperation" jo+ WHERE jo.id = v_job_operation_id;++ SELECT EXISTS (+ SELECT 1+ FROM "jobOperation" jo+ INNER JOIN "jobMakeMethod" jmm ON jmm.id = jo."jobMakeMethodId"+ WHERE jo.id = v_job_operation_id+ AND jmm."parentMaterialId" IS NULL+ AND NOT EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ INNER JOIN "jobOperation" child_jo ON child_jo.id = dep."operationId"+ INNER JOIN "jobMakeMethod" child_jmm ON child_jmm.id = child_jo."jobMakeMethodId"+ WHERE dep."dependsOnId" = jo.id+ AND child_jmm."parentMaterialId" IS NULL+ )+ ) INTO v_is_last_top_level_operation;++ IF v_job_id IS NOT NULL AND v_is_last_top_level_operation THEN+ UPDATE "job"+ SET "quantityComplete" = (+ SELECT COALESCE(SUM(terminal_jo."quantityComplete"), 0)+ FROM "jobOperation" terminal_jo+ INNER JOIN "jobMakeMethod" terminal_jmm ON terminal_jmm.id = terminal_jo."jobMakeMethodId"+ WHERE terminal_jo."jobId" = v_job_id+ AND terminal_jmm."parentMaterialId" IS NULL+ AND NOT EXISTS (+ SELECT 1+ FROM "jobOperationDependency" dep+ INNER JOIN "jobOperation" child_jo ON child_jo.id = dep."operationId"+ INNER JOIN "jobMakeMethod" child_jmm ON child_jmm.id = child_jo."jobMakeMethodId"+ WHERE dep."dependsOnId" = terminal_jo.id+ AND child_jmm."parentMaterialId" IS NULL+ )+ )+ WHERE id = v_job_id+ AND status NOT IN ('Completed', 'Cancelled');+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_update_quote_exchange_rate(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation = 'UPDATE'+ AND (p_old->>'exchangeRate') IS DISTINCT FROM (p_new->>'exchangeRate')+ THEN+ UPDATE "quoteLinePrice"+ SET "exchangeRate" = (p_new->>'exchangeRate')::numeric+ WHERE "quoteId" = p_new->>'id';+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_update_quote_line_make_method_item_id(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_version NUMERIC(10, 2);+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ -- Only fire when methodType/itemId change is relevant to Make to Order+ IF NOT (+ ((p_old->>'methodType') = 'Make to Order' AND (p_old->>'itemId') IS DISTINCT FROM (p_new->>'itemId'))+ OR ((p_new->>'methodType') = 'Make to Order' AND (p_old->>'methodType') != 'Make to Order')+ ) THEN+ RETURN;+ END IF;++ SELECT "version" INTO v_version FROM "activeMakeMethods" WHERE "itemId" = p_new->>'itemId';++ IF NOT EXISTS (+ SELECT 1 FROM "quoteMakeMethod"+ WHERE "quoteLineId" = p_new->>'id' AND "parentMaterialId" IS NULL+ ) THEN+ INSERT INTO "quoteMakeMethod" (+ "quoteId", "quoteLineId", "itemId", "companyId", "createdAt", "createdBy", "version"+ ) VALUES (+ p_new->>'quoteId', p_new->>'id', p_new->>'itemId',+ p_new->>'companyId', NOW(), p_new->>'createdBy', v_version+ );+ ELSE+ UPDATE "quoteMakeMethod"+ SET "itemId" = p_new->>'itemId',+ "version" = v_version+ WHERE "quoteLineId" = p_new->>'id' AND "parentMaterialId" IS NULL;+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_update_quote_material_make_method_item_id(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ v_version NUMERIC(10, 2);+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ IF NOT (+ ((p_old->>'methodType') = 'Make to Order' AND (p_old->>'itemId') IS DISTINCT FROM (p_new->>'itemId'))+ OR ((p_new->>'methodType') = 'Make to Order' AND (p_old->>'methodType') != 'Make to Order')+ ) THEN+ RETURN;+ END IF;++ SELECT "version" INTO v_version FROM "activeMakeMethods" WHERE "itemId" = p_new->>'itemId';++ IF NOT EXISTS (+ SELECT 1 FROM "quoteMakeMethod"+ WHERE "quoteLineId" = p_new->>'quoteLineId' AND "parentMaterialId" = p_new->>'id'+ ) THEN+ INSERT INTO "quoteMakeMethod" (+ "quoteId", "quoteLineId", "parentMaterialId", "itemId", "companyId", "createdAt", "createdBy", "version"+ ) VALUES (+ p_new->>'quoteId', p_new->>'quoteLineId', p_new->>'id', p_new->>'itemId',+ p_new->>'companyId', NOW(), p_new->>'createdBy', v_version+ );+ ELSE+ UPDATE "quoteMakeMethod"+ SET "itemId" = p_new->>'itemId',+ "version" = v_version+ WHERE "quoteLineId" = p_new->>'quoteLineId' AND "parentMaterialId" = p_new->>'id';+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_update_sales_order_exchange_rate(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation = 'UPDATE'+ AND (p_old->>'exchangeRate') IS DISTINCT FROM (p_new->>'exchangeRate')+ THEN+ UPDATE "salesOrderLine"+ SET "exchangeRate" = (p_new->>'exchangeRate')::numeric+ WHERE "salesOrderId" = p_new->>'id';+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_update_stock_transfer_status(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF NOT ((p_old->>'pickedQuantity') IS DISTINCT FROM (p_new->>'pickedQuantity')+ AND (p_new->>'pickedQuantity')::numeric != 0) THEN+ RETURN;+ END IF;++ IF EXISTS (+ SELECT 1+ FROM "stockTransferLine"+ WHERE "stockTransferId" = p_new->>'stockTransferId'+ AND ("pickedQuantity" IS NULL OR "pickedQuantity" != "quantity")+ ) THEN+ UPDATE "stockTransfer"+ SET "status" = 'In Progress'+ WHERE "id" = p_new->>'stockTransferId';+ ELSE+ UPDATE "stockTransfer"+ SET "status" = 'Completed', "completedAt" = NOW()+ WHERE "id" = p_new->>'stockTransferId';+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_update_supplier_type_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ IF p_old->>'supplierTypeId' IS NOT NULL THEN+ IF p_new->>'supplierTypeId' IS NOT NULL THEN+ UPDATE "membership" SET "groupId" = p_new->>'supplierTypeId'+ WHERE "groupId" = p_old->>'supplierTypeId' AND "memberGroupId" = p_new->>'id';+ ELSE+ DELETE FROM "membership"+ WHERE "groupId" = p_old->>'supplierTypeId' AND "memberGroupId" = p_new->>'id';+ END IF;+ ELSE+ IF p_new->>'supplierTypeId' IS NOT NULL THEN+ INSERT INTO "membership" ("groupId", "memberGroupId")+ VALUES (p_new->>'supplierTypeId', p_new->>'id');+ END IF;+ END IF;++ UPDATE "group" SET "name" = p_new->>'name'+ WHERE "id" = p_new->>'id' AND "isSupplierOrgGroup" = TRUE;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_update_supplier_type_group_name(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ UPDATE "group"+ SET "name" = p_new->>'name'+ WHERE "id" = p_new->>'id'+ AND "isSupplierTypeGroup" = TRUE;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_update_tracked_entity_on_job_make_method(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;+ IF (p_old->>'id') IS NOT DISTINCT FROM (p_new->>'id') THEN RETURN; END IF;++ UPDATE "trackedEntity"+ SET "attributes" = jsonb_set(+ "attributes",+ '{Job Make Method}',+ to_jsonb(p_new->>'id')+ )+ WHERE "attributes"->>'Job Make Method' = p_old->>'id';+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_update_user_identity_group(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+BEGIN+ IF p_operation != 'UPDATE' THEN RETURN; END IF;++ UPDATE "group"+ SET "name" = p_new->>'fullName'+ WHERE "id" = p_new->>'id'+ AND "isIdentityGroup" = TRUE;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_upload_document_transaction(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+BEGIN+ IF p_operation != 'INSERT' THEN RETURN; END IF;++ INSERT INTO "documentTransaction" ("documentId", "type", "userId")+ VALUES (p_new->>'id', 'Upload', p_new->>'createdBy');+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_verify_integration(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public', 'extensions'+AS $function$+DECLARE+ integration_schema JSON;+BEGIN+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN RETURN; END IF;++ SELECT jsonschema INTO integration_schema+ FROM public.integration+ WHERE id = p_new->>'id';++ IF (p_new->>'active')::boolean = TRUE+ AND NOT extensions.json_matches_schema(integration_schema, (p_new->'metadata')::json) THEN+ RAISE EXCEPTION 'metadata does not match jsonschema';+ END IF;+END;+$function$;++CREATE OR REPLACE FUNCTION public.sync_webhook_subscription(p_table text, p_operation text, p_new jsonb, p_old jsonb)+ RETURNS void+ LANGUAGE plpgsql+ SET search_path TO 'public'+AS $function$+DECLARE+ v_ops TEXT[];+ v_name TEXT;+BEGIN+ IF p_operation = 'DELETE' THEN+ PERFORM delete_event_system_subscriptions_by_name(+ p_old->>'companyId', 'webhook-' || (p_old->>'id')+ );+ RETURN;+ END IF;++ v_name := 'webhook-' || (p_new->>'id');++ -- Clear first: `table` is editable and uniqueness is (companyId, name, table),+ -- so an upsert would strand the old row and fire the webhook twice.+ PERFORM delete_event_system_subscriptions_by_name(p_new->>'companyId', v_name);++ v_ops := ARRAY[]::TEXT[];+ IF (p_new->>'onInsert')::BOOLEAN THEN v_ops := array_append(v_ops, 'INSERT'); END IF;+ IF (p_new->>'onUpdate')::BOOLEAN THEN v_ops := array_append(v_ops, 'UPDATE'); END IF;+ IF (p_new->>'onDelete')::BOOLEAN THEN v_ops := array_append(v_ops, 'DELETE'); END IF;++ IF array_length(v_ops, 1) IS NULL THEN+ RETURN;+ END IF;++ PERFORM create_event_system_subscription(+ v_name,+ p_new->>'table',+ p_new->>'companyId',+ v_ops,+ 'WEBHOOK',+ jsonb_build_object('url', p_new->>'url', 'webhookId', p_new->>'id'),+ '{}'::jsonb,+ COALESCE((p_new->>'active')::BOOLEAN, false)+ );+END;+$function$;++-- event triggers (packages/database/src/event-system/attachments.ts)+SET lock_timeout = '5s';+SELECT set_event_triggers('ability', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('address', ARRAY['sync_address_to_parent']::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('assemblyPlanJob', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('changeOrder', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('charge', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('company', ARRAY[]::text[], ARRAY['sync_insert_company_related_records']::text[], false, ARRAY[]::text[]);+SELECT set_event_triggers('companyIntegration', ARRAY['sync_verify_integration']::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('contact', ARRAY['sync_contact_to_parent']::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('customField', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('customer', ARRAY['sync_update_customer_type_group']::text[], ARRAY['sync_create_customer_entries', 'sync_create_customer_org_group']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('customerAccount', ARRAY[]::text[], ARRAY['sync_add_customer_account_to_group']::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('customerContact', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('customerItemPriceOverride', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('customerItemPriceOverrideBreak', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('customerLocation', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('customerPartToItem', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('customerPayment', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('customerShipping', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('customerTax', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('customerType', ARRAY['sync_update_customer_type_group_name']::text[], ARRAY['sync_create_customer_type_group']::text[], true, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('document', ARRAY['sync_edit_document_transaction']::text[], ARRAY['sync_upload_document_transaction']::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('documentExtraction', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('documentTemplate', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('employee', ARRAY['sync_update_employee_type_membership']::text[], ARRAY['sync_add_employee_to_type_group']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('employeeJob', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('employeeType', ARRAY['sync_update_employee_type_group']::text[], ARRAY['sync_create_employee_type_group']::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('fixedAsset', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('gauge', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('gaugeCalibrationRecord', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('implementationCheckState', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('implementationFieldValue', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('implementationHub', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('implementationRow', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('inspection', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('inventoryCount', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('inventoryCountLine', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('invite', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('itarCertification', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('item', ARRAY[]::text[], ARRAY['sync_create_item_related_records', 'sync_create_make_method_related_records', 'sync_propagate_item_readable_id_to_tracked_entity']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('itemCost', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('itemLedger', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['apply_item_stock_quantities', 'broadcast_table_changes']::text[]);+SELECT set_event_triggers('itemPlanning', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('itemPostingGroup', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('itemReplenishment', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('itemShelfLife', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('itemStockQuantities', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('itemSupersession', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('itemUnitSalePrice', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('job', ARRAY['sync_job_complete_or_canceled']::text[], ARRAY['sync_insert_job_make_method', 'sync_job_recompute_service_line']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('jobMakeMethod', ARRAY['sync_update_tracked_entity_on_job_make_method', 'sync_delete_tracked_entity_on_job_make_method']::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('jobMaterial', ARRAY['sync_check_job_material_self_reference', 'sync_update_job_material_make_method_item_id']::text[], ARRAY['sync_insert_job_material_make_method']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('jobOperation', ARRAY['sync_finish_job_operation']::text[], ARRAY['set_shelf_life_on_operation_done', 'set_shelf_life_on_operation_started']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('jobOperationDependency', ARRAY[]::text[], ARRAY['sync_set_initial_dependency_status']::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('jobOperationNote', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('jobOperationStep', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('jobOperationStepRecord', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('journal', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('location', ARRAY[]::text[], ARRAY['sync_create_location_related_records']::text[], true, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('maintenanceDispatch', ARRAY[]::text[], ARRAY['sync_on_maintenance_dispatch_complete']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('maintenanceDispatchComment', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('maintenanceDispatchEvent', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('maintenanceSchedule', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('maintenanceScheduleItem', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('material', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('materialForm', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('materialSubstance', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('materialType', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('methodMaterial', ARRAY['sync_check_method_material_self_reference']::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('modelUpload', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('nonConformance', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('nonConformanceActionTask', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('nonConformanceApprovalTask', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('nonConformanceItem', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('nonConformanceRequiredAction', ARRAY['sync_protect_system_required_actions']::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('nonConformanceSupplier', ARRAY[]::text[], ARRAY['sync_create_nc_external_link']::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('nonConformanceType', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('notification', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_user_changes']::text[]);+SELECT set_event_triggers('part', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('payment', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('paymentTerm', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('pickingList', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('pickingListLine', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('printJob', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('procedure', ARRAY['sync_archive_other_procedures']::text[], ARRAY[]::text[], true, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('process', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('productionEvent', ARRAY['sync_set_job_operation_in_progress']::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('productionQuantity', ARRAY['sync_update_job_operation_quantities']::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('purchaseInvoice', ARRAY['prevent_posted_purchase_invoice_deletion']::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('purchaseInvoiceLine', ARRAY[]::text[], ARRAY['sync_purchase_invoice_line_price_change']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('purchaseOrder', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('purchaseOrderDelivery', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('purchaseOrderLine', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('purchaseOrderPayment', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('purchaseReturnOrder', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('purchasingRfq', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('qualityDocument', ARRAY['sync_archive_other_quality_documents']::text[], ARRAY[]::text[], true, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('quote', ARRAY['sync_update_quote_exchange_rate']::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('quoteLine', ARRAY['sync_update_quote_line_make_method_item_id']::text[], ARRAY['sync_insert_quote_line_make_method']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('quoteMaterial', ARRAY['sync_update_quote_material_make_method_item_id']::text[], ARRAY['sync_insert_quote_material_make_method']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('quoteOperation', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('receipt', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('receiptLine', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('reimbursement', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('salesInvoice', ARRAY['prevent_posted_sales_invoice_deletion']::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('salesInvoiceLine', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('salesInvoiceShipment', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('salesOrder', ARRAY['sync_update_sales_order_exchange_rate']::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('salesOrderLine', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('salesOrderPayment', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('salesOrderShipment', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('salesReturnOrder', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('salesRfq', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('salesRfqLine', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('shipment', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('shipmentLine', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('shippingMethod', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('stockTransfer', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('stockTransferLine', ARRAY[]::text[], ARRAY['sync_update_stock_transfer_status']::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('storageUnit', ARRAY['storage_unit_enforce_same_location', 'storage_unit_block_location_change_with_children', 'storage_unit_enforce_no_cycle']::text[], ARRAY[]::text[], true, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('supplier', ARRAY['sync_update_supplier_type_group']::text[], ARRAY['sync_create_supplier_entries', 'sync_create_supplier_org_group']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('supplierAccount', ARRAY[]::text[], ARRAY['sync_add_supplier_account_to_group']::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('supplierContact', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('supplierLocation', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('supplierPart', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('supplierPayment', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('supplierProcess', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('supplierQuote', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('supplierQuoteLine', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('supplierShipping', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('supplierTax', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('supplierType', ARRAY['sync_update_supplier_type_group_name']::text[], ARRAY['sync_create_supplier_type_group']::text[], true, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('trackedEntity', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('unitOfMeasure', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('user', ARRAY[]::text[], ARRAY['sync_create_user_identity_group', 'sync_update_user_identity_group', 'sync_delete_user_identity_group']::text[], false, ARRAY[]::text[]);+SELECT set_event_triggers('warehouseTransfer', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('warehouseTransferLine', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('webhook', ARRAY[]::text[], ARRAY['sync_webhook_subscription']::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('workCenter', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_reference_changes']::text[]);+SELECT set_event_triggers('workCenterProcess', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY[]::text[]);+SELECT set_event_triggers('workflowRun', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('workflowStepRun', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+RESET lock_timeout;diff --git a/packages/database/supabase/migrations/20261004200418_table-change-log.sql b/packages/database/supabase/migrations/20261004200418_table-change-log.sqlnew file mode 100644index 0000000000..c1b36a4592--- /dev/null+++ b/packages/database/supabase/migrations/20261004200418_table-change-log.sql@@ -0,0 +1,135 @@+-- A log of which rows changed, so a client that kept a copy of a list (items,+-- customers, suppliers, people) can ask for the changes since it last looked and+-- re-read only those rows — not the whole table on every page load.+--+-- Written by the log_table_changes / log_user_changes statement handlers+-- (packages/database/src/event-system/functions, attached in attachments.ts);+-- read through table_changes_since below. Its RLS rule (no API access) is in+-- the authz manifest.++-- UNLOGGED: it skips WAL, so the extra insert on each write to a list table is+-- cheap. The price is that a crash empties it. A reader detects that by the+-- "epoch" below and falls back to a full fetch+-- (20261005053648_table-change-epoch.sql replaced the server's start time,+-- which a backend crash does not change, with a token the same crash empties).+CREATE UNLOGGED TABLE IF NOT EXISTS "tableChange" (+ "id" BIGINT GENERATED ALWAYS AS IDENTITY,+ "companyId" TEXT NOT NULL,+ "table" TEXT NOT NULL,+ -- NULL: more than 100 rows of the table changed in one statement.+ "rowId" TEXT,+ -- The writing transaction. The cursor a reader keeps is a transaction id, not+ -- this table's "id": ids are handed out before commit, so a reader that+ -- remembered "the highest id I saw" would skip a row whose transaction+ -- committed late. A snapshot's xmin has no such gap.+ "xid" XID8 NOT NULL DEFAULT pg_current_xact_id(),+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),+ -- No foreign key to "company": see 20261004213812_table-change-drop-company-fk.sql.+ CONSTRAINT "tableChange_pkey" PRIMARY KEY ("id", "companyId")+);++CREATE INDEX IF NOT EXISTS "tableChange_companyId_xid_idx" ON "tableChange" ("companyId", "xid");+CREATE INDEX IF NOT EXISTS "tableChange_createdAt_idx" ON "tableChange" ("createdAt");++-- How long a change stays in the log. A reader whose last look is older than+-- this (less a day of margin) is told to fetch everything again.+CREATE OR REPLACE FUNCTION util.table_change_retention()+RETURNS interval+LANGUAGE sql+IMMUTABLE+AS $$ SELECT interval '7 days' $$;++-- The changes to a company's tables since a cursor.+--+-- Call it with no cursor the first time: it answers "reset" (fetch everything)+-- and hands back a cursor. Pass that cursor (xid, epoch, at) on the next call.+--+-- reset true when the log cannot answer for that cursor: there is none, the+-- server restarted since it was issued (a crash empties the log), or+-- it is older than the retention.+-- changes { "<table>": ["<rowId>", ...] | null } — null means "that table+-- changed too much to list: read it again". A row may be listed+-- again on a later call; re-reading it is harmless.+-- xid, epoch, at the cursor for the next call.+--+-- STABLE is load-bearing: the read of the log and pg_current_snapshot() then+-- share the calling statement's snapshot. As VOLATILE each would take its own,+-- and a change committed between the two would be skipped for good.+--+-- SECURITY DEFINER because the table has no API access; it checks the caller's+-- company itself. What it reveals is row ids, the same as a realtime broadcast.+CREATE OR REPLACE FUNCTION public.table_changes_since(+ p_company_id TEXT,+ p_xid TEXT DEFAULT NULL,+ p_epoch TEXT DEFAULT NULL,+ p_at TIMESTAMP WITH TIME ZONE DEFAULT NULL+)+RETURNS JSONB+LANGUAGE plpgsql+STABLE+SECURITY DEFINER+SET search_path = public+AS $$+DECLARE+ v_epoch TEXT := extract(epoch FROM pg_postmaster_start_time())::TEXT;+ v_reset BOOLEAN;+ v_changes JSONB := '{}'::JSONB;+BEGIN+ IF NOT (p_company_id = ANY (COALESCE(get_companies_with_employee_role(), ARRAY[]::TEXT[]))) THEN+ RAISE EXCEPTION 'Not a member of this company' USING ERRCODE = '42501';+ END IF;++ v_reset := p_xid IS NULL+ OR p_epoch IS DISTINCT FROM v_epoch+ OR p_at IS NULL+ OR p_at < NOW() - (util.table_change_retention() - interval '1 day');++ IF NOT v_reset THEN+ SELECT COALESCE(jsonb_object_agg(c."table", c.ids), '{}'::JSONB)+ INTO v_changes+ FROM (+ SELECT "table",+ CASE WHEN bool_or("rowId" IS NULL) THEN NULL+ ELSE to_jsonb(array_agg(DISTINCT "rowId")) END AS ids+ FROM "tableChange"+ WHERE "companyId" = p_company_id AND "xid" >= p_xid::XID8+ GROUP BY "table"+ ) c;+ END IF;++ RETURN jsonb_build_object(+ 'reset', v_reset,+ 'changes', v_changes,+ -- Every transaction older than the snapshot's xmin has finished, so every+ -- change it logged is visible above. Anything at or after it is asked for+ -- again next time.+ 'xid', pg_snapshot_xmin(pg_current_snapshot())::TEXT,+ 'epoch', v_epoch,+ 'at', NOW()+ );+END;+$$;++REVOKE ALL ON FUNCTION public.table_changes_since(TEXT, TEXT, TEXT, TIMESTAMP WITH TIME ZONE) FROM PUBLIC, anon;+GRANT EXECUTE ON FUNCTION public.table_changes_since(TEXT, TEXT, TEXT, TIMESTAMP WITH TIME ZONE) TO authenticated;++-- Retention, hourly.+CREATE OR REPLACE FUNCTION util.purge_table_changes()+RETURNS void+LANGUAGE sql+SECURITY DEFINER+SET search_path = public+AS $$+ DELETE FROM "tableChange" WHERE "createdAt" < NOW() - util.table_change_retention();+$$;++REVOKE ALL ON FUNCTION util.purge_table_changes() FROM PUBLIC;++DO $$+BEGIN+ IF EXISTS (SELECT 1 FROM cron.job WHERE jobname = 'table-change-retention') THEN+ PERFORM cron.unschedule('table-change-retention');+ END IF;+ PERFORM cron.schedule('table-change-retention', '17 * * * *', 'SELECT util.purge_table_changes();');+END;+$$;diff --git a/packages/database/supabase/migrations/20261004201533_table-change-handlers.sql b/packages/database/supabase/migrations/20261004201533_table-change-handlers.sqlnew file mode 100644index 0000000000..fd063917c7--- /dev/null+++ b/packages/database/supabase/migrations/20261004201533_table-change-handlers.sql@@ -0,0 +1,250 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++CREATE OR REPLACE FUNCTION public.broadcast_table_changes()+ RETURNS trigger+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO ''+AS $function$+DECLARE+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];+ -- Tables whose rows hang off a record through another table. Each hop is+ -- [column of the row, table it points at, column to read there]: its value is+ -- added to the message under that column's name, so a job page can follow+ -- "jobId" on a table that only knows its operation.+ -- A hop with a fourth element looks the other way: the rows of that table+ -- whose fourth column holds this row's value ("id" is the row's own id). A+ -- payment has no invoice column; its settlements name the invoices it pays.+ -- packages/database/src/realtime-tables.ts lists the same columns+ -- (REALTIME_ANCESTOR_COLUMNS; realtime-tables.test.ts keeps them equal).+ ancestors CONSTANT JSONB := '{+ "productionEvent": [["jobOperationId", "jobOperation", "jobId"]],+ "jobOperationStep": [["operationId", "jobOperation", "jobId"]],+ "jobOperationStepRecord": [["jobOperationStepId", "jobOperationStep", "operationId"], ["operationId", "jobOperation", "jobId"]],+ "trackedActivity": [["sourceDocumentId", "productionEvent", "jobOperationId"]],+ "payment": [["id", "invoiceSettlement", "targetSalesInvoiceId", "paymentId"], ["id", "invoiceSettlement", "targetPurchaseInvoiceId", "paymentId"]]+ }';+ changed_rows TEXT;+ parent_rows TEXT;+ parents JSONB;+ found JSONB;+ hop JSONB;+ rec RECORD;+BEGIN+ -- A database without Supabase Realtime (a self-hosted install that does not+ -- run it) has nothing to send to: the write must still succeed.+ IF to_regprocedure('realtime.send(jsonb,text,text,boolean)') IS NULL THEN+ RETURN NULL;+ END IF;++ -- Tells the company's clients which rows of this table changed (topic company:<companyId>:<table>).+ -- Statement-level (attach_statement_handler): one message per company per+ -- statement, whatever the row count. No row data leaves the database: a client+ -- re-reads what it needs through PostgREST, so table RLS still decides what it sees.+ IF TG_OP = 'UPDATE' THEN+ -- A row whose only changes are in ignored_columns drops out (the rule+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n+ EXCEPT+ SELECT to_jsonb(o) - $1 FROM batched_old o';+ -- The rows as they were, too: a row moved to another parent concerns the+ -- parent it left as much as the one it joined.+ parent_rows := '(' || changed_rows || ')+ UNION ALL+ (SELECT to_jsonb(o) - $1 FROM batched_old o+ EXCEPT+ SELECT to_jsonb(n) - $1 FROM batched_new n)';+ ELSIF TG_OP = 'DELETE' THEN+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';+ parent_rows := changed_rows;+ ELSE+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';+ parent_rows := changed_rows;+ END IF;++ FOR rec IN EXECUTE format(+ -- implementationHub has no companyId: its id is the company id.+ 'WITH keyed AS (+ SELECT coalesce(c->>''companyId'',+ CASE WHEN $2::text = ''implementationHub'' THEN c->>''id'' END) AS company_id,+ c+ FROM (%1$s) changed+ ),+ related AS (+ SELECT coalesce(c->>''companyId'',+ CASE WHEN $2::text = ''implementationHub'' THEN c->>''id'' END) AS company_id,+ c+ FROM (%2$s) changed+ )+ SELECT k.company_id,+ count(*) AS n,+ -- itemSupersession has no id: its row belongs to the item it describes.+ jsonb_agg(coalesce(k.c->''id'', k.c->''itemId''))+ FILTER (WHERE k.c ? ''id'' OR k.c ? ''itemId'') AS ids,+ -- The records these rows belong to: every "<name>Id" column and its+ -- values, so a page showing one job (or quote, or order) can ignore+ -- changes to another''s rows. A column with more than 20 values is+ -- left out, and a client treats a missing column as "may concern me".+ -- Only computed for a statement small enough to list its ids.+ CASE WHEN count(*) <= 100 THEN (+ SELECT jsonb_object_agg(p.key, p.vals)+ FROM (+ SELECT e.key, jsonb_agg(DISTINCT e.value) AS vals+ FROM related k2, jsonb_each(k2.c) e+ WHERE k2.company_id = k.company_id+ AND e.key LIKE ''%%Id'' AND e.key <> ''companyId''+ AND jsonb_typeof(e.value) = ''string''+ GROUP BY e.key+ HAVING count(DISTINCT e.value) <= 20+ ) p+ ) END AS parents+ FROM keyed k+ GROUP BY k.company_id',+ changed_rows, parent_rows+ ) USING ignored_columns, TG_TABLE_NAME+ LOOP+ CONTINUE WHEN rec.company_id IS NULL;++ parents := rec.parents;+ IF parents IS NOT NULL AND ancestors ? TG_TABLE_NAME THEN+ FOR hop IN SELECT value FROM jsonb_array_elements(ancestors->TG_TABLE_NAME) LOOP+ found := CASE WHEN hop->>0 = 'id' THEN rec.ids ELSE parents->(hop->>0) END;+ -- A column that was left out (no value, or too many) leaves its+ -- ancestor out as well: the client then takes the change as its own.+ CONTINUE WHEN found IS NULL;+ EXECUTE format(+ 'SELECT jsonb_agg(DISTINCT %1$I) FROM public.%2$I+ WHERE "companyId" = $1 AND %1$I IS NOT NULL+ AND %3$I IN (SELECT jsonb_array_elements_text($2))',+ hop->>2, hop->>1, coalesce(hop->>3, 'id')+ ) INTO found USING rec.company_id, found;+ IF found IS NOT NULL THEN+ parents := parents || jsonb_build_object(hop->>2, found);+ ELSIF jsonb_array_length(hop) = 4 THEN+ -- Looked for and not there: no such record has this row.+ parents := parents || jsonb_build_object(hop->>2, '[]'::jsonb);+ END IF;+ END LOOP;+ END IF;+ PERFORM realtime.send(+ jsonb_build_object(+ 'table', TG_TABLE_NAME,+ 'op', TG_OP,+ -- null = "many rows changed, or the table has no id: resync"+ 'ids', CASE WHEN rec.n <= 100 THEN rec.ids END,+ 'parents', parents+ ),+ TG_OP,+ 'company:' || rec.company_id || ':' || TG_TABLE_NAME,+ true+ );+ END LOOP;+ RETURN NULL;+END;+$function$;++CREATE OR REPLACE FUNCTION public.log_table_changes()+ RETURNS trigger+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO ''+AS $function$+DECLARE+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];+ changed_rows TEXT;+BEGIN+ -- Records which rows of this table changed, in public."tableChange", so a+ -- client that kept a copy of a list can ask "what changed since I last+ -- looked?" (table_changes_since) and re-read only those rows instead of the+ -- whole table. A broadcast tells an open tab the same thing; this is for the+ -- tab that was closed, or disconnected, when it happened.+ IF TG_OP = 'UPDATE' THEN+ -- A row whose only changes are in ignored_columns drops out (the rule+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n+ EXCEPT+ SELECT to_jsonb(o) - $1 FROM batched_old o';+ ELSIF TG_OP = 'DELETE' THEN+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';+ ELSE+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';+ END IF;++ EXECUTE format(+ -- One log row per changed row. Past 100 rows in one statement, a single row+ -- with a null "rowId" says "this table changed a lot: read it again".+ -- itemSupersession has no id: its row belongs to the item it describes.+ 'INSERT INTO public."tableChange" ("companyId", "table", "rowId")+ SELECT DISTINCT company_id, $2::text, CASE WHEN n <= 100 THEN row_id END+ FROM (+ SELECT c->>''companyId'' AS company_id,+ coalesce(c->>''id'', c->>''itemId'') AS row_id,+ count(*) OVER (PARTITION BY c->>''companyId'') AS n+ FROM (%s) changed+ ) rows+ WHERE company_id IS NOT NULL',+ changed_rows+ ) USING ignored_columns, TG_TABLE_NAME;+ RETURN NULL;+END;+$function$;++CREATE OR REPLACE FUNCTION public.log_user_changes()+ RETURNS trigger+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO ''+AS $function$+DECLARE+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];+ changed_rows TEXT;+BEGIN+ -- A person's name and avatar live on the global "user" row, which has no+ -- company. Each company that person belongs to shows them in its people list+ -- (the employees view), so a change is logged once per company, as a change+ -- to that company's "employee" row.+ IF TG_OP = 'UPDATE' THEN+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n+ EXCEPT+ SELECT to_jsonb(o) - $1 FROM batched_old o';+ ELSIF TG_OP = 'DELETE' THEN+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';+ ELSE+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';+ END IF;++ EXECUTE format(+ 'INSERT INTO public."tableChange" ("companyId", "table", "rowId")+ SELECT DISTINCT m."companyId", ''employee'', changed.c->>''id''+ FROM (%s) changed+ JOIN public."userToCompany" m ON m."userId" = changed.c->>''id''',+ changed_rows+ ) USING ignored_columns;+ RETURN NULL;+END;+$function$;++-- tableChange+DO $authz$+DECLARE p record;+BEGIN+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'tableChange' LOOP+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'tableChange');+ END LOOP;+END+$authz$;+ALTER TABLE public."tableChange" ENABLE ROW LEVEL SECURITY;++-- event triggers (packages/database/src/event-system/attachments.ts)+SET lock_timeout = '5s';+SELECT set_event_triggers('customer', ARRAY['sync_update_customer_type_group']::text[], ARRAY['sync_create_customer_entries', 'sync_create_customer_org_group']::text[], true, ARRAY['broadcast_table_changes', 'log_table_changes']::text[]);+SELECT set_event_triggers('employee', ARRAY['sync_update_employee_type_membership']::text[], ARRAY['sync_add_employee_to_type_group']::text[], true, ARRAY['broadcast_table_changes', 'log_table_changes']::text[]);+SELECT set_event_triggers('item', ARRAY[]::text[], ARRAY['sync_create_item_related_records', 'sync_create_make_method_related_records', 'sync_propagate_item_readable_id_to_tracked_entity']::text[], true, ARRAY['broadcast_table_changes', 'log_table_changes']::text[]);+SELECT set_event_triggers('itemSupersession', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes', 'log_table_changes']::text[]);+SELECT set_event_triggers('modelUpload', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes', 'log_table_changes']::text[]);+SELECT set_event_triggers('supplier', ARRAY['sync_update_supplier_type_group']::text[], ARRAY['sync_create_supplier_entries', 'sync_create_supplier_org_group']::text[], true, ARRAY['broadcast_table_changes', 'log_table_changes']::text[]);+SELECT set_event_triggers('trackedActivity', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('user', ARRAY[]::text[], ARRAY['sync_create_user_identity_group', 'sync_update_user_identity_group', 'sync_delete_user_identity_group']::text[], false, ARRAY['log_user_changes']::text[]);+RESET lock_timeout;diff --git a/packages/database/supabase/migrations/20261004202758_realtime-route-tables.sql b/packages/database/supabase/migrations/20261004202758_realtime-route-tables.sqlnew file mode 100644index 0000000000..a1196b91cc--- /dev/null+++ b/packages/database/supabase/migrations/20261004202758_realtime-route-tables.sql@@ -0,0 +1,18 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++-- event triggers (packages/database/src/event-system/attachments.ts)+SET lock_timeout = '5s';+SELECT set_event_triggers('inspectionSample', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('inventoryCountLine', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('nonConformanceItem', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('payment', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('purchaseReturnOrderLine', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('purchasingRfqLine', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('quoteMakeMethod', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('salesReturnOrderLine', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('stockTransferLine', ARRAY[]::text[], ARRAY['sync_update_stock_transfer_status']::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('supplierQuoteLine', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+SELECT set_event_triggers('warehouseTransferLine', ARRAY[]::text[], ARRAY[]::text[], true, ARRAY['broadcast_table_changes']::text[]);+RESET lock_timeout;diff --git a/packages/database/supabase/migrations/20261004213812_table-change-drop-company-fk.sql b/packages/database/supabase/migrations/20261004213812_table-change-drop-company-fk.sqlnew file mode 100644index 0000000000..bbb2f2118a--- /dev/null+++ b/packages/database/supabase/migrations/20261004213812_table-change-drop-company-fk.sql@@ -0,0 +1,6 @@+-- The change log must not hold a foreign key to "company". Deleting a company+-- cascades to its items and customers, whose log_table_changes trigger then+-- inserts a "tableChange" row for a company that is already gone in that+-- transaction: the insert fails the key and aborts the delete.+-- Rows of a deleted company are removed by the hourly retention purge.+ALTER TABLE "tableChange" DROP CONSTRAINT IF EXISTS "tableChange_companyId_fkey";diff --git a/packages/database/supabase/migrations/20261004232608_realtime-invoice-settlement.sql b/packages/database/supabase/migrations/20261004232608_realtime-invoice-settlement.sqlnew file mode 100644index 0000000000..e78284500b--- /dev/null+++ b/packages/database/supabase/migrations/20261004232608_realtime-invoice-settlement.sql@@ -0,0 +1,8 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++-- event triggers (packages/database/src/event-system/attachments.ts)+SET lock_timeout = '5s';+SELECT set_event_triggers('invoiceSettlement', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);+RESET lock_timeout;diff --git a/packages/database/supabase/migrations/20261005041631_item-usage-and-change-notice-lookups.sql b/packages/database/supabase/migrations/20261005041631_item-usage-and-change-notice-lookups.sqlnew file mode 100644index 0000000000..0b0e6afafe--- /dev/null+++ b/packages/database/supabase/migrations/20261005041631_item-usage-and-change-notice-lookups.sql@@ -0,0 +1,279 @@+-- Two lookups every item page makes, each as one statement.+--+-- Both were assembled in TypeScript from many PostgREST requests: where an item+-- is used was fifteen requests fired at once, and an item's change notices were+-- eight requests in five sequential steps. SECURITY INVOKER: row-level security+-- decides what the caller sees, exactly as it did for the separate requests.++-- Everywhere an item is referenced. Each list is the newest hundred lines, with+-- the document the line belongs to; lines created together are ordered by id,+-- so the same call always answers the same way. quoteLine and supplierQuoteLine+-- have no "createdAt", so theirs are a hundred in no particular order, as before.+CREATE OR REPLACE FUNCTION get_item_used_in(item_id TEXT, company_id TEXT)+RETURNS JSONB+LANGUAGE sql+STABLE+SECURITY INVOKER+SET search_path = public+AS $$+ SELECT jsonb_build_object(+ 'issues', (+ SELECT coalesce(+ jsonb_agg(to_jsonb(r) - 'createdAt' ORDER BY r."createdAt" DESC, r."id"), '[]'::jsonb+ )+ FROM (+ SELECT l."id", l."createdAt", d."nonConformanceId" AS "documentReadableId", d."id" AS "documentId"+ FROM "nonConformanceItem" l+ LEFT JOIN "nonConformance" d ON d."id" = l."nonConformanceId" AND d."companyId" = l."companyId"+ WHERE l."itemId" = item_id AND l."companyId" = company_id+ ORDER BY l."createdAt" DESC, l."id"+ LIMIT 100+ ) r+ ),+ 'jobMaterials', (+ SELECT coalesce(+ jsonb_agg(to_jsonb(r) - 'createdAt' ORDER BY r."createdAt" DESC, r."id"), '[]'::jsonb+ )+ FROM (+ SELECT l."id", l."createdAt", l."methodType", d."jobId" AS "documentReadableId", d."id" AS "documentId"+ FROM "jobMaterial" l+ LEFT JOIN "job" d ON d."id" = l."jobId" AND d."companyId" = l."companyId"+ WHERE l."itemId" = item_id AND l."companyId" = company_id+ ORDER BY l."createdAt" DESC, l."id"+ LIMIT 100+ ) r+ ),+ 'jobs', (+ SELECT coalesce(+ jsonb_agg(to_jsonb(r) - 'createdAt' ORDER BY r."createdAt" DESC, r."id"), '[]'::jsonb+ )+ FROM (+ SELECT l."id", l."createdAt", l."jobId" AS "documentReadableId"+ FROM "job" l+ WHERE l."itemId" = item_id AND l."companyId" = company_id+ ORDER BY l."createdAt" DESC, l."id"+ LIMIT 100+ ) r+ ),+ 'maintenanceDispatchItems', (+ SELECT coalesce(+ jsonb_agg(to_jsonb(r) - 'createdAt' ORDER BY r."createdAt" DESC, r."id"), '[]'::jsonb+ )+ FROM (+ SELECT l."id", l."createdAt", d."maintenanceDispatchId" AS "documentReadableId", d."id" AS "documentId"+ FROM "maintenanceDispatchItem" l+ LEFT JOIN "maintenanceDispatch" d ON d."id" = l."maintenanceDispatchId" AND d."companyId" = l."companyId"+ WHERE l."itemId" = item_id AND l."companyId" = company_id+ ORDER BY l."createdAt" DESC, l."id"+ LIMIT 100+ ) r+ ),+ 'methodMaterials', (+ SELECT coalesce(+ jsonb_agg(to_jsonb(r) - 'createdAt' ORDER BY r."createdAt" DESC, r."id"), '[]'::jsonb+ )+ FROM (+ SELECT l."id", l."createdAt", l."methodType", d."id" AS "documentId", d."version", i."readableIdWithRevision" AS "documentReadableId", i."id" AS "documentParentId", i."type" AS "itemType"+ FROM "methodMaterial" l+ LEFT JOIN "makeMethod" d ON d."id" = l."makeMethodId" AND d."companyId" = l."companyId"+ LEFT JOIN "item" i ON i."id" = d."itemId" AND i."companyId" = d."companyId"+ WHERE l."itemId" = item_id AND l."companyId" = company_id+ ORDER BY l."createdAt" DESC, l."id"+ LIMIT 100+ ) r+ ),+ 'purchaseOrderLines', (+ SELECT coalesce(+ jsonb_agg(to_jsonb(r) - 'createdAt' ORDER BY r."createdAt" DESC, r."id"), '[]'::jsonb+ )+ FROM (+ SELECT l."id", l."createdAt", d."purchaseOrderId" AS "documentReadableId", d."id" AS "documentId"+ FROM "purchaseOrderLine" l+ LEFT JOIN "purchaseOrder" d ON d."id" = l."purchaseOrderId" AND d."companyId" = l."companyId"+ WHERE l."itemId" = item_id AND l."companyId" = company_id+ ORDER BY l."createdAt" DESC, l."id"+ LIMIT 100+ ) r+ ),+ 'receiptLines', (+ SELECT coalesce(+ jsonb_agg(to_jsonb(r) - 'createdAt' ORDER BY r."createdAt" DESC, r."id"), '[]'::jsonb+ )+ FROM (+ SELECT l."id", l."createdAt", d."receiptId" AS "documentReadableId", d."id" AS "documentId"+ FROM "receiptLine" l+ LEFT JOIN "receipt" d ON d."id" = l."receiptId" AND d."companyId" = l."companyId"+ WHERE l."itemId" = item_id AND l."companyId" = company_id+ ORDER BY l."createdAt" DESC, l."id"+ LIMIT 100+ ) r+ ),+ 'quoteLines', (+ SELECT coalesce(jsonb_agg(to_jsonb(r)), '[]'::jsonb)+ FROM (+ SELECT l."id", l."methodType", d."quoteId" AS "documentReadableId", d."id" AS "documentId"+ FROM "quoteLine" l+ LEFT JOIN "quote" d ON d."id" = l."quoteId" AND d."companyId" = l."companyId"+ WHERE l."itemId" = item_id AND l."companyId" = company_id+ LIMIT 100+ ) r+ ),+ 'quoteMaterials', (+ SELECT coalesce(+ jsonb_agg(to_jsonb(r) - 'createdAt' ORDER BY r."createdAt" DESC, r."id"), '[]'::jsonb+ )+ FROM (+ SELECT l."id", l."createdAt", l."methodType", l."quoteId" AS "documentParentId", l."quoteLineId" AS "documentId", i."readableIdWithRevision" AS "documentReadableId"+ FROM "quoteMaterial" l+ LEFT JOIN "quoteLine" d ON d."id" = l."quoteLineId" AND d."companyId" = l."companyId"+ LEFT JOIN "item" i ON i."id" = d."itemId" AND i."companyId" = d."companyId"+ WHERE l."itemId" = item_id AND l."companyId" = company_id+ ORDER BY l."createdAt" DESC, l."id"+ LIMIT 100+ ) r+ ),+ 'salesOrderLines', (+ SELECT coalesce(+ jsonb_agg(to_jsonb(r) - 'createdAt' ORDER BY r."createdAt" DESC, r."id"), '[]'::jsonb+ )+ FROM (+ SELECT l."id", l."createdAt", l."methodType", d."salesOrderId" AS "documentReadableId", d."id" AS "documentId"+ FROM "salesOrderLine" l+ LEFT JOIN "salesOrder" d ON d."id" = l."salesOrderId" AND d."companyId" = l."companyId"+ WHERE l."itemId" = item_id AND l."companyId" = company_id+ ORDER BY l."createdAt" DESC, l."id"+ LIMIT 100+ ) r+ ),+ 'shipmentLines', (+ SELECT coalesce(+ jsonb_agg(to_jsonb(r) - 'createdAt' ORDER BY r."createdAt" DESC, r."id"), '[]'::jsonb+ )+ FROM (+ SELECT l."id", l."createdAt", d."shipmentId" AS "documentReadableId", d."id" AS "documentId"+ FROM "shipmentLine" l+ LEFT JOIN "shipment" d ON d."id" = l."shipmentId" AND d."companyId" = l."companyId"+ WHERE l."itemId" = item_id AND l."companyId" = company_id+ ORDER BY l."createdAt" DESC, l."id"+ LIMIT 100+ ) r+ ),+ 'supplierQuotes', (+ SELECT coalesce(jsonb_agg(to_jsonb(r)), '[]'::jsonb)+ FROM (+ SELECT l."id", d."supplierQuoteId" AS "documentReadableId", d."id" AS "documentId"+ FROM "supplierQuoteLine" l+ LEFT JOIN "supplierQuote" d ON d."id" = l."supplierQuoteId" AND d."companyId" = l."companyId"+ WHERE l."itemId" = item_id AND l."companyId" = company_id+ LIMIT 100+ ) r+ ),+ 'assemblyInstructions', (+ SELECT coalesce(+ jsonb_agg(to_jsonb(r) - 'createdAt' ORDER BY r."createdAt" DESC, r."id"), '[]'::jsonb+ )+ FROM (+ SELECT l."id", l."createdAt", l."name" AS "documentReadableId", l."version"+ FROM "assemblyInstruction" l+ WHERE l."itemId" = item_id AND l."companyId" = company_id+ ORDER BY l."createdAt" DESC, l."id"+ LIMIT 100+ ) r+ ),+ 'inspections', (+ SELECT coalesce(+ jsonb_agg(to_jsonb(r) - 'createdAt' ORDER BY r."createdAt" DESC, r."id"), '[]'::jsonb+ )+ FROM (+ SELECT l."id", l."createdAt", l."inspectionId" AS "documentReadableId"+ FROM "inspection" l+ WHERE l."itemId" = item_id AND l."companyId" = company_id+ ORDER BY l."createdAt" DESC, l."id"+ LIMIT 100+ ) r+ ),+ 'jobMaterialUsage', jsonb_build_object(+ 'byMaterialId', (+ SELECT coalesce(jsonb_object_agg(m."id", coalesce(m."estimatedQuantity", 0)), '{}'::jsonb)+ FROM "jobMaterial" m+ WHERE m."itemId" = item_id AND m."companyId" = company_id+ ),+ 'byJobId', (+ SELECT coalesce(jsonb_object_agg(j."id", coalesce(j."quantity", 0)), '{}'::jsonb)+ FROM "job" j+ WHERE j."itemId" = item_id AND j."companyId" = company_id+ )+ )+ );+$$;++-- Every change notice that touches an item or any other revision of it (an+-- item row sharing its "readableId"): as an affected item, as a component on a+-- notice's draft method, as either side of a supersession, or as the revision+-- a notice created. Newest first. NULL or empty statuses means any status.+CREATE OR REPLACE FUNCTION get_item_change_notices(+ item_id TEXT,+ company_id TEXT,+ statuses "changeOrderStatus"[] DEFAULT NULL+)+RETURNS TABLE (+ "id" TEXT,+ "changeOrderId" TEXT,+ "name" TEXT,+ "status" "changeOrderStatus",+ "changeOrderTypeId" TEXT,+ "createdAt" TIMESTAMP WITH TIME ZONE+)+LANGUAGE sql+STABLE+SECURITY INVOKER+SET search_path = public+AS $$+ WITH revisions AS (+ SELECT r."id", r."changeOrderId"+ FROM "item" i+ JOIN "item" r+ ON r."readableId" = i."readableId" AND r."companyId" = i."companyId"+ WHERE i."id" = item_id AND i."companyId" = company_id+ ),+ notices AS (+ SELECT a."changeOrderId"+ FROM "changeOrderAffectedItem" a+ WHERE a."companyId" = company_id+ AND a."itemId" IN (SELECT r."id" FROM revisions r)+ UNION+ SELECT m."changeOrderId"+ FROM "methodMaterial" c+ JOIN "makeMethod" m+ ON m."id" = c."makeMethodId" AND m."companyId" = c."companyId"+ WHERE c."companyId" = company_id+ AND c."itemId" IN (SELECT r."id" FROM revisions r)+ AND m."changeOrderId" IS NOT NULL+ UNION+ SELECT s."changeOrderId"+ FROM "changeOrderSupersession" s+ WHERE s."companyId" = company_id+ AND (+ s."predecessorItemId" IN (SELECT r."id" FROM revisions r)+ OR s."successorItemId" IN (SELECT r."id" FROM revisions r)+ )+ UNION+ SELECT r."changeOrderId" FROM revisions r WHERE r."changeOrderId" IS NOT NULL+ )+ SELECT+ co."id",+ co."changeOrderId",+ co."name",+ co."status",+ co."changeOrderTypeId",+ co."createdAt"+ FROM "changeOrder" co+ WHERE co."companyId" = company_id+ AND co."id" IN (SELECT n."changeOrderId" FROM notices n)+ AND (+ statuses IS NULL+ OR cardinality(statuses) = 0+ OR co."status" = ANY (statuses)+ )+ ORDER BY co."createdAt" DESC, co."id";+$$;diff --git a/packages/database/supabase/migrations/20261005053648_table-change-epoch.sql b/packages/database/supabase/migrations/20261005053648_table-change-epoch.sqlnew file mode 100644index 0000000000..bd8e865c5b--- /dev/null+++ b/packages/database/supabase/migrations/20261005053648_table-change-epoch.sql@@ -0,0 +1,84 @@+-- The change log ("tableChange") is UNLOGGED, so crash recovery empties it. A+-- reader must then be told to fetch everything again. It was told by the+-- postmaster's start time, which does not change when a backend crashes and the+-- postmaster recovers in place: the log came back empty under the same epoch,+-- and a client that had been away was answered "no changes".+--+-- The epoch is now a token kept in a second UNLOGGED table, emptied by the same+-- recovery that empties the log. No token means "reset" until the hourly purge+-- writes a new one. A clean restart keeps both, so it resets nobody.++CREATE UNLOGGED TABLE IF NOT EXISTS util."tableChangeEpoch" (+ "id" BOOLEAN PRIMARY KEY DEFAULT TRUE CHECK ("id"),+ "token" TEXT NOT NULL DEFAULT gen_random_uuid()::TEXT+);++INSERT INTO util."tableChangeEpoch" DEFAULT VALUES ON CONFLICT DO NOTHING;++CREATE OR REPLACE FUNCTION public.table_changes_since(+ p_company_id TEXT,+ p_xid TEXT DEFAULT NULL,+ p_epoch TEXT DEFAULT NULL,+ p_at TIMESTAMP WITH TIME ZONE DEFAULT NULL+)+RETURNS JSONB+LANGUAGE plpgsql+STABLE+SECURITY DEFINER+SET search_path = ''+AS $$+DECLARE+ -- NULL after a crash, until util.purge_table_changes() writes a new token.+ v_epoch TEXT := (SELECT "token" FROM util."tableChangeEpoch");+ v_reset BOOLEAN;+ v_changes JSONB := '{}'::JSONB;+BEGIN+ IF NOT (p_company_id = ANY (COALESCE(public.get_companies_with_employee_role(), ARRAY[]::TEXT[]))) THEN+ RAISE EXCEPTION 'Not a member of this company' USING ERRCODE = '42501';+ END IF;++ v_reset := p_xid IS NULL+ OR v_epoch IS NULL+ OR p_epoch IS DISTINCT FROM v_epoch+ OR p_at IS NULL+ OR p_at < pg_catalog.now() - (util.table_change_retention() - interval '1 day');++ IF NOT v_reset THEN+ SELECT COALESCE(pg_catalog.jsonb_object_agg(c."table", c.ids), '{}'::JSONB)+ INTO v_changes+ FROM (+ SELECT "table",+ CASE WHEN pg_catalog.bool_or("rowId" IS NULL) THEN NULL+ ELSE pg_catalog.to_jsonb(pg_catalog.array_agg(DISTINCT "rowId")) END AS ids+ FROM public."tableChange"+ WHERE "companyId" = p_company_id AND "xid" >= p_xid::XID8+ GROUP BY "table"+ ) c;+ END IF;++ RETURN pg_catalog.jsonb_build_object(+ 'reset', v_reset,+ 'changes', v_changes,+ -- Every transaction older than the snapshot's xmin has finished, so every+ -- change it logged is visible above. Anything at or after it is asked for+ -- again next time.+ 'xid', pg_catalog.pg_snapshot_xmin(pg_catalog.pg_current_snapshot())::TEXT,+ 'epoch', v_epoch,+ 'at', pg_catalog.now()+ );+END;+$$;++-- Retention, hourly; and a new epoch after a crash took the last one.+CREATE OR REPLACE FUNCTION util.purge_table_changes()+RETURNS void+LANGUAGE sql+SECURITY DEFINER+SET search_path = ''+AS $$+ DELETE FROM public."tableChange"+ WHERE "createdAt" < pg_catalog.now() - util.table_change_retention();+ INSERT INTO util."tableChangeEpoch" DEFAULT VALUES ON CONFLICT DO NOTHING;+$$;++REVOKE ALL ON FUNCTION util.purge_table_changes() FROM PUBLIC;diff --git a/packages/database/supabase/migrations/20261005053945_broadcast-foreign-keys-only.sql b/packages/database/supabase/migrations/20261005053945_broadcast-foreign-keys-only.sqlnew file mode 100644index 0000000000..181197f43d--- /dev/null+++ b/packages/database/supabase/migrations/20261005053945_broadcast-foreign-keys-only.sql@@ -0,0 +1,172 @@+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.++-- Ships these rules to databases where `authz sync` does not run after migrations yet.++CREATE OR REPLACE FUNCTION public.broadcast_table_changes()+ RETURNS trigger+ LANGUAGE plpgsql+ SECURITY DEFINER+ SET search_path TO ''+AS $function$+DECLARE+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];+ -- Tables whose rows hang off a record through another table. Each hop is+ -- [column of the row, table it points at, column to read there]: its value is+ -- added to the message under that column's name, so a job page can follow+ -- "jobId" on a table that only knows its operation.+ -- A hop with a fourth element looks the other way: the rows of that table+ -- whose fourth column holds this row's value ("id" is the row's own id). A+ -- payment has no invoice column; its settlements name the invoices it pays.+ -- packages/database/src/realtime-tables.ts lists the same columns+ -- (REALTIME_ANCESTOR_COLUMNS; realtime-tables.test.ts keeps them equal).+ ancestors CONSTANT JSONB := '{+ "productionEvent": [["jobOperationId", "jobOperation", "jobId"]],+ "jobOperationStep": [["operationId", "jobOperation", "jobId"]],+ "jobOperationStepRecord": [["jobOperationStepId", "jobOperationStep", "operationId"], ["operationId", "jobOperation", "jobId"]],+ "trackedActivity": [["sourceDocumentId", "productionEvent", "jobOperationId"]],+ "payment": [["id", "invoiceSettlement", "targetSalesInvoiceId", "paymentId"], ["id", "invoiceSettlement", "targetPurchaseInvoiceId", "paymentId"]]+ }';+ changed_rows TEXT;+ parent_rows TEXT;+ parents JSONB;+ sent_columns TEXT[];+ found JSONB;+ hop JSONB;+ rec RECORD;+BEGIN+ -- A database without Supabase Realtime (a self-hosted install that does not+ -- run it) has nothing to send to: the write must still succeed.+ IF to_regprocedure('realtime.send(jsonb,text,text,boolean)') IS NULL THEN+ RETURN NULL;+ END IF;++ -- Tells the company's clients which rows of this table changed (topic company:<companyId>:<table>).+ -- Statement-level (attach_statement_handler): one message per company per+ -- statement, whatever the row count. No row data leaves the database: a client+ -- re-reads what it needs through PostgREST, so table RLS still decides what it sees.+ -- The columns a message may name: the table's foreign keys, and the columns+ -- its ancestors add. A column that merely ends in "Id" is the row's own data+ -- (a part number in "readableId", an order number, a tax id) and stays here.+ SELECT coalesce(array_agg(DISTINCT a.attname::text), ARRAY[]::text[])+ INTO sent_columns+ FROM pg_catalog.pg_constraint k+ JOIN pg_catalog.pg_attribute a+ ON a.attrelid = k.conrelid AND a.attnum = ANY (k.conkey)+ WHERE k.conrelid = TG_RELID AND k.contype = 'f';+ IF ancestors ? TG_TABLE_NAME THEN+ sent_columns := sent_columns || ARRAY(+ SELECT value->>2 FROM jsonb_array_elements(ancestors->TG_TABLE_NAME)+ );+ END IF;++ IF TG_OP = 'UPDATE' THEN+ -- A row whose only changes are in ignored_columns drops out (the rule+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n+ EXCEPT+ SELECT to_jsonb(o) - $1 FROM batched_old o';+ -- The rows as they were, too: a row moved to another parent concerns the+ -- parent it left as much as the one it joined.+ parent_rows := '(' || changed_rows || ')+ UNION ALL+ (SELECT to_jsonb(o) - $1 FROM batched_old o+ EXCEPT+ SELECT to_jsonb(n) - $1 FROM batched_new n)';+ ELSIF TG_OP = 'DELETE' THEN+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';+ parent_rows := changed_rows;+ ELSE+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';+ parent_rows := changed_rows;+ END IF;++ FOR rec IN EXECUTE format(+ -- implementationHub has no companyId: its id is the company id.+ 'WITH keyed AS (+ SELECT coalesce(c->>''companyId'',+ CASE WHEN $2::text = ''implementationHub'' THEN c->>''id'' END) AS company_id,+ c+ FROM (%1$s) changed+ ),+ related AS (+ SELECT coalesce(c->>''companyId'',+ CASE WHEN $2::text = ''implementationHub'' THEN c->>''id'' END) AS company_id,+ c+ FROM (%2$s) changed+ )+ SELECT k.company_id,+ count(*) AS n,+ -- itemSupersession has no id: its row belongs to the item it describes.+ jsonb_agg(coalesce(k.c->''id'', k.c->''itemId''))+ FILTER (WHERE k.c ? ''id'' OR k.c ? ''itemId'') AS ids,+ -- The records these rows belong to: each "<name>Id" column and its+ -- values (narrowed to the foreign keys before sending), so a page showing one job (or quote, or order) can ignore+ -- changes to another''s rows. A column with more than 20 values is+ -- left out, and a client treats a missing column as "may concern me".+ -- Only computed for a statement small enough to list its ids.+ CASE WHEN count(*) <= 100 THEN (+ SELECT jsonb_object_agg(p.key, p.vals)+ FROM (+ SELECT e.key, jsonb_agg(DISTINCT e.value) AS vals+ FROM related k2, jsonb_each(k2.c) e+ WHERE k2.company_id = k.company_id+ AND e.key LIKE ''%%Id'' AND e.key <> ''companyId''+ AND jsonb_typeof(e.value) = ''string''+ GROUP BY e.key+ HAVING count(DISTINCT e.value) <= 20+ ) p+ ) END AS parents+ FROM keyed k+ GROUP BY k.company_id',+ changed_rows, parent_rows+ ) USING ignored_columns, TG_TABLE_NAME+ LOOP+ CONTINUE WHEN rec.company_id IS NULL;++ parents := rec.parents;+ IF parents IS NOT NULL AND ancestors ? TG_TABLE_NAME THEN+ FOR hop IN SELECT value FROM jsonb_array_elements(ancestors->TG_TABLE_NAME) LOOP+ found := CASE WHEN hop->>0 = 'id' THEN rec.ids ELSE parents->(hop->>0) END;+ -- A column that was left out (no value, or too many) leaves its+ -- ancestor out as well: the client then takes the change as its own.+ CONTINUE WHEN found IS NULL;+ EXECUTE format(+ 'SELECT jsonb_agg(DISTINCT %1$I) FROM public.%2$I+ WHERE "companyId" = $1 AND %1$I IS NOT NULL+ AND %3$I IN (SELECT jsonb_array_elements_text($2))',+ hop->>2, hop->>1, coalesce(hop->>3, 'id')+ ) INTO found USING rec.company_id, found;+ IF found IS NOT NULL THEN+ parents := parents || jsonb_build_object(hop->>2, found);+ ELSIF jsonb_array_length(hop) = 4 THEN+ -- Looked for and not there: no such record has this row.+ parents := parents || jsonb_build_object(hop->>2, '[]'::jsonb);+ END IF;+ END LOOP;+ END IF;+ -- An ancestor hop may read a column that is not sent (a polymorphic+ -- "sourceDocumentId"), so the narrowing comes last.+ IF parents IS NOT NULL THEN+ parents := coalesce(+ (SELECT jsonb_object_agg(e.key, e.value)+ FROM jsonb_each(parents) e+ WHERE e.key = ANY (sent_columns)),+ '{}'::jsonb+ );+ END IF;+ PERFORM realtime.send(+ jsonb_build_object(+ 'table', TG_TABLE_NAME,+ 'op', TG_OP,+ -- null = "many rows changed, or the table has no id: resync"+ 'ids', CASE WHEN rec.n <= 100 THEN rec.ids END,+ 'parents', parents+ ),+ TG_OP,+ 'company:' || rec.company_id || ':' || TG_TABLE_NAME,+ true+ );+ END LOOP;+ RETURN NULL;+END;+$function$;diff --git a/packages/database/supabase/tests/realtime-broadcast.test.sql b/packages/database/supabase/tests/realtime-broadcast.test.sqlnew file mode 100644index 0000000000..9e6ee05fed--- /dev/null+++ b/packages/database/supabase/tests/realtime-broadcast.test.sql@@ -0,0 +1,325 @@+-- Realtime broadcast and the change log: what the triggers send and record, who+-- may join a topic, and what table_changes_since answers+-- (20261004191247_realtime-broadcast, 20261004200418_table-change-log).+-- Run from the repository root against an existing local database:+-- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/realtime-broadcast.test.sql+-- All fixtures and role changes are confined to the rolled-back transaction.+\set ON_ERROR_STOP on+BEGIN;+SET LOCAL statement_timeout = '30s';+SET LOCAL "app.sync_in_progress" = 'true';++DO $fixtures$+DECLARE+ group_id text;+ company_a text;+ company_b text;+ user_a text := gen_random_uuid()::text;+ user_b text := gen_random_uuid()::text;+BEGIN+ INSERT INTO "companyGroup" (name, "createdBy") VALUES ('Realtime ' || id(), 'system') RETURNING id INTO group_id;+ INSERT INTO "company" (name, "companyGroupId", "baseCurrencyCode") VALUES ('Realtime A ' || id(), group_id, 'USD') RETURNING id INTO company_a;+ INSERT INTO "company" (name, "companyGroupId", "baseCurrencyCode") VALUES ('Realtime B ' || id(), group_id, 'USD') RETURNING id INTO company_b;+ INSERT INTO "user" (id, email) VALUES+ (user_a, user_a || '@realtime.invalid'),+ (user_b, user_b || '@realtime.invalid');+ INSERT INTO "userToCompany" ("userId", "companyId", role) VALUES+ (user_a, company_a, 'employee'), (user_b, company_b, 'employee');+ INSERT INTO "userPermission" (id, permissions) VALUES+ (user_a, jsonb_build_object('sales_view', jsonb_build_array(company_a))),+ (user_b, jsonb_build_object('sales_view', jsonb_build_array(company_b)));++ PERFORM set_config('test.company_a', company_a, true);+ PERFORM set_config('test.company_b', company_b, true);+ PERFORM set_config('test.user_a', user_a, true);+ PERFORM set_config('test.user_b', user_b, true);+END;+$fixtures$;++-- What a statement sends.+DO $$+DECLARE+ company_a text := current_setting('test.company_a');+ company_b text := current_setting('test.company_b');+ user_a text := current_setting('test.user_a');+ user_b text := current_setting('test.user_b');+ item_topic text := 'company:' || company_a || ':item';+ base int;+ sent int;+ message jsonb;+ customer_id text;+BEGIN+ -- Creating the second company of a group already wrote intercompany partners+ -- into this one, so every count below is relative to this point.+ SELECT count(*) INTO base FROM realtime.messages WHERE topic = 'company:' || company_a || ':customer';++ -- INSERT: one message, the new id, on the company's topic for the table.+ INSERT INTO "customer" (name, "companyId", "readableId", "accountManagerId") VALUES ('Realtime customer', company_a, 'RT-0', user_a) RETURNING id INTO customer_id;+ SELECT count(*) - base INTO sent FROM realtime.messages WHERE topic = 'company:' || company_a || ':customer';+ SELECT payload INTO message FROM realtime.messages+ WHERE topic = 'company:' || company_a || ':customer' AND payload->'ids' = jsonb_build_array(customer_id);+ IF sent <> 1 OR message->>'op' <> 'INSERT' OR message->'ids' <> jsonb_build_array(customer_id)+ OR message->>'table' <> 'customer' OR message ? 'name' THEN+ RAISE EXCEPTION 'FAIL: customer INSERT sent % message(s): %', sent, message;+ END IF;+ IF EXISTS (SELECT 1 FROM realtime.messages WHERE topic = 'company:' || company_b || ':customer' AND payload->'ids' ? customer_id) THEN+ RAISE EXCEPTION 'FAIL: a write in company A reached company B''s topic';+ END IF;+ -- The message names the records the row belongs to: each foreign key+ -- "<name>Id" column that holds a value, so a client can filter on one+ -- (`quoteLineId=eq.…`).+ IF message->'parents'->'accountManagerId' <> jsonb_build_array(user_a) OR message->'parents' ? 'companyId' THEN+ RAISE EXCEPTION 'FAIL: customer INSERT did not name its foreign keys: %', message;+ END IF;+ -- A column that only ends in "Id" is the row's own data and is not sent.+ IF message->'parents' ? 'readableId' OR message::text LIKE '%RT-0%' THEN+ RAISE EXCEPTION 'FAIL: customer INSERT sent the customer number: %', message;+ END IF;+ IF EXISTS (SELECT 1 FROM realtime.messages WHERE topic LIKE 'company:' || company_a || ':%' AND NOT private) THEN+ RAISE EXCEPTION 'FAIL: a broadcast was sent on a public topic';+ END IF;++ -- UPDATE that changes only bookkeeping columns: nothing.+ UPDATE "customer" SET "updatedAt" = now(), "updatedBy" = user_a WHERE id = customer_id;+ SELECT count(*) - base INTO sent FROM realtime.messages WHERE topic = 'company:' || company_a || ':customer';+ IF sent <> 1 THEN+ RAISE EXCEPTION 'FAIL: an updatedAt-only UPDATE sent a message';+ END IF;++ -- A real UPDATE, then a DELETE: one message each.+ UPDATE "customer" SET name = 'Realtime customer 2', "accountManagerId" = user_b WHERE id = customer_id;+ -- A row moved to another parent names the one it left as well as the one it joined.+ SELECT payload INTO message FROM realtime.messages+ WHERE topic = 'company:' || company_a || ':customer' AND payload->>'op' = 'UPDATE'+ AND payload->'ids' = jsonb_build_array(customer_id)+ ORDER BY inserted_at DESC LIMIT 1;+ IF NOT (message->'parents'->'accountManagerId' @> jsonb_build_array(user_a, user_b)) THEN+ RAISE EXCEPTION 'FAIL: an UPDATE did not name the old and the new parent: %', message;+ END IF;++ DELETE FROM "customer" WHERE id = customer_id;+ SELECT count(*) - base INTO sent FROM realtime.messages WHERE topic = 'company:' || company_a || ':customer';+ IF sent <> 3 THEN+ RAISE EXCEPTION 'FAIL: INSERT + UPDATE + DELETE sent % messages, expected 3', sent;+ END IF;+ IF NOT EXISTS (+ SELECT 1 FROM realtime.messages+ WHERE topic = 'company:' || company_a || ':customer'+ AND payload->>'op' = 'DELETE' AND payload->'ids' = jsonb_build_array(customer_id)+ ) THEN+ RAISE EXCEPTION 'FAIL: DELETE did not carry the deleted id';+ END IF;++ -- One statement, many rows, two companies: one message per company, and no ids past 100.+ INSERT INTO "customer" (name, "companyId", "readableId")+ SELECT 'Bulk ' || n, CASE WHEN n <= 150 THEN company_a ELSE company_b END, 'RT-' || n+ FROM generate_series(1, 152) n;+ SELECT count(*) INTO sent FROM realtime.messages+ WHERE topic = 'company:' || company_a || ':customer' AND payload->>'op' = 'INSERT' AND payload->'ids' = 'null'::jsonb+ AND payload->'parents' = 'null'::jsonb;+ IF sent <> 1 THEN+ RAISE EXCEPTION 'FAIL: a 150-row INSERT did not send exactly one "resync" message without ids or parents';+ END IF;+ SELECT count(*) INTO sent FROM realtime.messages+ WHERE topic = 'company:' || company_b || ':customer' AND jsonb_array_length(payload->'ids') = 2;+ IF sent <> 1 THEN+ RAISE EXCEPTION 'FAIL: company B''s 2 rows of the same statement did not arrive as one message with 2 ids';+ END IF;++ -- A reference table goes to the shared topic, without ids.+ INSERT INTO "unitOfMeasure" (code, name, "companyId", "createdBy") VALUES ('RT', 'Realtime unit', company_a, user_a);+ SELECT count(*), max(payload::text)::jsonb INTO sent, message+ FROM realtime.messages WHERE topic = 'company:' || company_a || ':reference';+ IF sent <> 1 OR message->>'table' <> 'unitOfMeasure' OR message ? 'ids' THEN+ RAISE EXCEPTION 'FAIL: unitOfMeasure INSERT sent % reference message(s): %', sent, message;+ END IF;++ -- A notification goes to its user, not to the company.+ INSERT INTO "notification" ("userId", "companyId", topic, event, title)+ VALUES (user_a, company_a, 'test', 'test', 'Realtime notification');+ SELECT count(*) INTO sent FROM realtime.messages WHERE topic = 'user:' || user_a || ':notification';+ IF sent <> 1 THEN+ RAISE EXCEPTION 'FAIL: notification INSERT sent % user message(s)', sent;+ END IF;+ IF EXISTS (SELECT 1 FROM realtime.messages WHERE topic = 'company:' || company_a || ':notification') THEN+ RAISE EXCEPTION 'FAIL: a notification was broadcast to the whole company';+ END IF;+END;+$$;++-- Who may join a topic. Realtime sets realtime.topic and reads realtime.messages+-- as the joining user; a visible row means the join is allowed.+SELECT set_config('request.jwt.claims', jsonb_build_object('sub', current_setting('test.user_a'), 'role', 'authenticated')::text, true);+SET LOCAL ROLE authenticated;+DO $$+DECLARE+ visible int;+BEGIN+ PERFORM set_config('realtime.topic', 'company:' || current_setting('test.company_a') || ':customer', true);+ SELECT count(*) INTO visible FROM realtime.messages;+ IF visible = 0 THEN+ RAISE EXCEPTION 'FAIL: an employee cannot join their own company''s topic';+ END IF;++ PERFORM set_config('realtime.topic', 'company:' || current_setting('test.company_b') || ':customer', true);+ SELECT count(*) INTO visible FROM realtime.messages;+ IF visible <> 0 THEN+ RAISE EXCEPTION 'FAIL: an employee of company A can join company B''s topic';+ END IF;++ PERFORM set_config('realtime.topic', 'user:' || current_setting('test.user_a') || ':notification', true);+ SELECT count(*) INTO visible FROM realtime.messages;+ IF visible = 0 THEN+ RAISE EXCEPTION 'FAIL: a user cannot join their own notification topic';+ END IF;++ PERFORM set_config('realtime.topic', 'user:' || current_setting('test.user_b') || ':notification', true);+ SELECT count(*) INTO visible FROM realtime.messages;+ IF visible <> 0 THEN+ RAISE EXCEPTION 'FAIL: a user can join another user''s notification topic';+ END IF;++ PERFORM set_config('realtime.topic', 'something-else', true);+ SELECT count(*) INTO visible FROM realtime.messages;+ IF visible <> 0 THEN+ RAISE EXCEPTION 'FAIL: a topic outside company:/user: is readable';+ END IF;+END;+$$;++-- The change log: what the list handlers record, and what a reader gets back.+RESET ROLE;+DO $$+DECLARE+ company_a text := current_setting('test.company_a');+ company_b text := current_setting('test.company_b');+ user_a text := current_setting('test.user_a');+ logged int;+BEGIN+ -- The writes above: the single customer (INSERT, a real UPDATE, DELETE — the+ -- updatedAt-only UPDATE logs nothing) and the 150-row statement, which is one+ -- "read it again" row.+ SELECT count(*) INTO logged FROM "tableChange"+ WHERE "companyId" = company_a AND "table" = 'customer' AND "rowId" LIKE 'cust_%'+ AND "rowId" NOT IN (SELECT id FROM customer);+ IF logged <> 3 THEN+ RAISE EXCEPTION 'FAIL: the deleted customer has % log rows, expected 3 (insert, update, delete)', logged;+ END IF;+ SELECT count(*) INTO logged FROM "tableChange"+ WHERE "companyId" = company_a AND "table" = 'customer' AND "rowId" IS NULL;+ IF logged <> 1 THEN+ RAISE EXCEPTION 'FAIL: a 150-row INSERT logged % "read it again" rows, expected 1', logged;+ END IF;+ SELECT count(*) INTO logged FROM "tableChange" c+ WHERE c."companyId" = company_b AND c."table" = 'customer'+ AND c."rowId" IN (SELECT id FROM customer WHERE name LIKE 'Bulk %');+ IF logged <> 2 THEN+ RAISE EXCEPTION 'FAIL: company B''s 2 rows of the bulk statement logged % rows', logged;+ END IF;+ -- A table with no log handler records nothing.+ IF EXISTS (SELECT 1 FROM "tableChange" WHERE "table" = 'unitOfMeasure') THEN+ RAISE EXCEPTION 'FAIL: a table without the log handler was logged';+ END IF;++ -- A person's name lives on "user": the change is logged for their company's people list.+ UPDATE "user" SET "firstName" = 'Renamed' WHERE id = user_a;+ IF NOT EXISTS (+ SELECT 1 FROM "tableChange"+ WHERE "companyId" = company_a AND "table" = 'employee' AND "rowId" = user_a+ ) THEN+ RAISE EXCEPTION 'FAIL: renaming a user did not log a change to their company''s people';+ END IF;+ IF EXISTS (SELECT 1 FROM "tableChange" WHERE "companyId" = company_b AND "rowId" = user_a) THEN+ RAISE EXCEPTION 'FAIL: a user''s rename was logged for a company they are not in';+ END IF;+END;+$$;++SELECT set_config('request.jwt.claims', jsonb_build_object('sub', current_setting('test.user_a'), 'role', 'authenticated')::text, true);+SET LOCAL ROLE authenticated;+DO $$+DECLARE+ company_a text := current_setting('test.company_a');+ company_b text := current_setting('test.company_b');+ first jsonb;+ next jsonb;+BEGIN+ -- The table itself is not readable through the API.+ IF EXISTS (SELECT 1 FROM "tableChange") THEN+ RAISE EXCEPTION 'FAIL: tableChange is readable as an authenticated user';+ END IF;++ -- No cursor: fetch everything, and here is a cursor.+ first := table_changes_since(company_a);+ IF NOT (first->>'reset')::boolean OR first->'changes' <> '{}'::jsonb+ OR first->>'xid' IS NULL OR first->>'epoch' IS NULL OR first->>'at' IS NULL THEN+ RAISE EXCEPTION 'FAIL: a first call did not answer reset with a cursor: %', first;+ END IF;++ -- With the cursor: the changes of this company only. The customer table is+ -- "read it again" (the bulk statement); people lists the renamed user.+ next := table_changes_since(company_a, first->>'xid', first->>'epoch', (first->>'at')::timestamptz);+ IF (next->>'reset')::boolean THEN+ RAISE EXCEPTION 'FAIL: a fresh cursor was answered with reset';+ END IF;+ IF next->'changes'->'customer' <> 'null'::jsonb THEN+ RAISE EXCEPTION 'FAIL: customer should be "read it again" after a 150-row statement: %', next->'changes'->'customer';+ END IF;+ IF NOT (next->'changes'->'employee' ? current_setting('test.user_a')) THEN+ RAISE EXCEPTION 'FAIL: the renamed user is missing from the changes: %', next->'changes';+ END IF;++ -- A cursor from before a restart, and one older than the retention, both reset.+ IF NOT (table_changes_since(company_a, first->>'xid', 'another-epoch', (first->>'at')::timestamptz)->>'reset')::boolean THEN+ RAISE EXCEPTION 'FAIL: a cursor from another server epoch was not reset';+ END IF;+ IF NOT (table_changes_since(company_a, first->>'xid', first->>'epoch', now() - interval '6 days 1 hour')->>'reset')::boolean THEN+ RAISE EXCEPTION 'FAIL: a cursor older than the retention margin was not reset';+ END IF;++ -- Another company's log is refused outright.+ BEGIN+ PERFORM table_changes_since(company_b);+ RAISE EXCEPTION 'FAIL: read another company''s change log';+ EXCEPTION WHEN insufficient_privilege THEN NULL;+ END;+END;+$$;+RESET ROLE;++-- A crash empties the log and its epoch together (both are UNLOGGED). Until+-- the purge writes a new epoch every cursor is answered with reset, and a+-- cursor issued under the old epoch is reset afterwards as well.+DO $$+DECLARE+ company_a text := current_setting('test.company_a');+ before jsonb;+ during jsonb;+ after jsonb;+BEGIN+ PERFORM set_config('request.jwt.claims', jsonb_build_object('sub', current_setting('test.user_a'), 'role', 'authenticated')::text, true);+ before := table_changes_since(company_a);+ IF (table_changes_since(company_a, before->>'xid', before->>'epoch', (before->>'at')::timestamptz)->>'reset')::boolean THEN+ RAISE EXCEPTION 'FAIL: a fresh cursor was answered with reset';+ END IF;++ DELETE FROM util."tableChangeEpoch";+ DELETE FROM "tableChange";+ during := table_changes_since(company_a, before->>'xid', before->>'epoch', (before->>'at')::timestamptz);+ IF NOT (during->>'reset')::boolean OR during->>'epoch' IS NOT NULL THEN+ RAISE EXCEPTION 'FAIL: an emptied log was not answered with reset: %', during;+ END IF;+ IF NOT (table_changes_since(company_a, during->>'xid', during->>'epoch', (during->>'at')::timestamptz)->>'reset')::boolean THEN+ RAISE EXCEPTION 'FAIL: a cursor issued without an epoch was trusted';+ END IF;++ PERFORM util.purge_table_changes();+ after := table_changes_since(company_a, before->>'xid', before->>'epoch', (before->>'at')::timestamptz);+ IF NOT (after->>'reset')::boolean OR after->>'epoch' IS NULL OR after->>'epoch' = before->>'epoch' THEN+ RAISE EXCEPTION 'FAIL: the purge did not start a new epoch: %', after;+ END IF;+END;+$$;++\echo realtime-broadcast: all checks passed+ROLLBACK;diff --git a/packages/ee/src/ramp/config.test.ts b/packages/ee/src/ramp/config.test.tsindex d7a69276d5..e2a2658d27 100644--- a/packages/ee/src/ramp/config.test.ts+++ b/packages/ee/src/ramp/config.test.ts@@ -9,9 +9,9 @@ import { describe, expect, it, vi } from "vitest";// a unit test has no business booting. Everything below runs real — the actual// descriptor, the actual mode profiles, the actual zod schema.vi.mock("@carbon/auth", () => ({ RAMP_CLIENT_ID: "test-client-id" }));-// Same reason, one layer out: `@carbon/react`'s barrel reaches-// `useRealtimeChannel`, which reads env at load. The descriptor only imports it-// for the setup-instructions JSX, which nothing here renders.+// `@carbon/react`'s barrel reaches components that use Lingui macros, which+// cannot run uncompiled. The descriptor only imports it for the+// setup-instructions JSX, which nothing here renders.vi.mock("@carbon/react", () => ({Copy: () => null,Input: () => null,diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.jsonindex 96b06001dd..d5dddf2016 100644--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@ -1,11 +1,11 @@{"kind": "carbon-company-backup","version": 1,- "schemaVersion": "20261004183512",+ "schemaVersion": "20261005041631","sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-10-04T13:57:31.482Z",+ "exportedAt": "2026-10-05T04:22:58.312Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",@@ -6887,6 +6887,7 @@"oauthToken","ssoConnection","ssoDomain",+ "tableChange","webhook"]}diff --git a/packages/jobs/src/backups/schema.ts b/packages/jobs/src/backups/schema.tsindex 48d66ee04a..d18dde4f57 100644--- a/packages/jobs/src/backups/schema.ts+++ b/packages/jobs/src/backups/schema.ts@@ -25,7 +25,9 @@ export const BACKUP_VERSION = 1;* Tables whose contents must never travel in a backup — credentials,* integration tokens and webhook targets stay with the source company.* (`apiKeyRateLimit` dangles without its stripped `apiKey` and is an UNLOGGED- * operational counter, never user data. `employeePin` holds console PIN+ * operational counter, never user data. `tableChange` is the same kind of+ * table: an UNLOGGED log of which rows changed, whose transaction ids mean+ * nothing in another database. `employeePin` holds console PIN* hashes — a 4-digit PIN's bcrypt hash is brute-forced offline in minutes, so* it is a credential; being secret also keeps an in-place restore from wiping* every operator's PIN. `ssoConnection` / `ssoDomain` are the company's login@@ -36,6 +38,7 @@ export const BACKUP_VERSION = 1;export const SECRET_TABLES = ["apiKey","apiKeyRateLimit",+ "tableChange","companyIntegration","employeePin","webhook",diff --git a/packages/jobs/src/inngest/functions/tasks/company-restore.ts b/packages/jobs/src/inngest/functions/tasks/company-restore.tsindex 09d0a290cb..9c9b893ddf 100644--- a/packages/jobs/src/inngest/functions/tasks/company-restore.ts+++ b/packages/jobs/src/inngest/functions/tasks/company-restore.ts@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { CHANGE_LOGGED_TABLES } from "@carbon/database/realtime-tables";import { requireBackupsEntitlement } from "@carbon/ee/backups.server";import { getLogger } from "@carbon/logger";import { chunkArray } from "@carbon/utils";@@ -232,6 +233,16 @@ export async function wipeAndLoad(});}}++ // Every list an open client keeps a copy of has just been replaced. With+ // triggers off nothing logged that, so say it here: a null row id tells+ // the client to read the whole table again.+ await trx+ .insertInto("tableChange")+ .values(+ CHANGE_LOGGED_TABLES.map((table) => ({ companyId, table, rowId: null }))+ )+ .execute();});return { rows: inserted, idRewrite };diff --git a/packages/query/AGENTS.md b/packages/query/AGENTS.mdnew file mode 100644index 0000000000..3ec68f2947--- /dev/null+++ b/packages/query/AGENTS.md@@ -0,0 +1,52 @@+# @carbon/query++The client data layer shared by the ERP and the MES: the TanStack Query cache in front of route loaders, and the realtime system that keeps it and the pages current.++## Always++- **There is no app-level cache file.** Import from `@carbon/query` (components) or `@carbon/query/cache` (route modules); `~/utils/react-query` is gone.+- **Cache a loader by URL, never by a hand-written key.** `export const clientLoader = cachedClientLoader<typeof loader>()`. The key is `[LOADER, companyId, pathname, search]`.+- **Let the root middleware invalidate.** `createInvalidationMiddleware` marks every `LOADER` entry stale after any non-GET request. A route does not name the lists its action changes, and exports no `clientAction` for that.+- **Declare a route's tables in `handle.realtime`.** `RouteRealtime` (rendered once in each app shell) subscribes to them and reloads the page when one changes. A component that is not a route uses the app's `useRealtime(table, filter?)`.+- **A realtime table must have a broadcast handler** in `packages/database/src/event-system/attachments.ts`. `RealtimeTable` is derived from it, so an unknown table does not compile.+- **Import `@carbon/query/cache` from a route module.** It has no React or UI import. The package root (`@carbon/query`) pulls in `@carbon/react`.++## Ask First++- Changing the cache key shape, or what the middleware invalidates+- Adding a topic shape other than `company:<companyId>:<table>`, `company:<companyId>:reference` and `user:<userId>:<table>` (each needs a `realtime.messages` policy in the authz manifest)++## Never++- Name a module here `*.client.ts` or `*.server.ts` if a route calls it at module load: React Router empties `.client` modules on the server, and `root.tsx` calls `createInvalidationMiddleware(...)` while it is evaluated there.+- Subscribe with `postgres_changes`. The `supabase_realtime` publication is empty; a subscription to it delivers nothing and reports no error.+- Read `payload.new` / `payload.old`. A broadcast carries `{ table, op, ids }` and no row data; re-read the rows by id through PostgREST, so table RLS still decides what the user sees.+- Use a row count, a sequence value or a timestamp as a live list's cursor. The cursor is the transaction id `table_changes_since` hands back (a snapshot's xmin): a sequence value is taken before commit, so "the highest I saw" skips a row whose transaction commits late.++## Validation Commands++```bash+pnpm exec turbo run typecheck --filter=@carbon/query+pnpm --filter @carbon/query test+```++## Key Patterns++| Export | Use |+|---|---|+| `cachedClientLoader`, `loaderQueryKey`, `LOADER`, `RefreshRate` | Cache an `api+` loader; build the same key for a component read |+| `useLoaderQuery(url)` | Read an `api+` URL in a component: one shared request per URL, refetched when invalidated. Replaces `useFetcher` + `fetcher.load` in a mount effect |+| `cachedApiQuery(url)` | The same read from an event handler or an effect |+| `useAction({ onSuccess, onError, onSettled })` | A mutation fetcher with callbacks. `onSettled` runs whenever a submission finishes, also when the action redirects and returns no data; `onSuccess` / `onError` need data |+| `setClientCompanyId(companyId, userId)` / `getCompanyId` | The shell layout sets both during render; the `companyId` cookie is httpOnly and unreadable in the browser. A different user empties the cache; leaving a company drops its loader entries |+| `createInvalidationMiddleware({ getCache, skipPaths })` | Root `clientMiddleware`; skip POSTs that change no data (`/refresh-session`) |+| `RouteRealtime`, `useRealtimeTable`, `useTableChanges`, `useRealtimeRevalidator` | Realtime over private broadcast topics. Revalidation waits for a submitting fetcher. A route entry `{ table, column, param }` and a `<name>Id=eq.` filter follow one record's rows only (`matchesFilter`) |+| `useRealtimeChannel` | One channel with retry, `private` and `onSubscribed(isReconnect)`. It reconnects when the tab returns after 10 s hidden or with a channel that is not joined — every reconnect reloads the page's data, so a glance at another tab does not |+| `LiveLists`, `useLiveList`, `LiveList` | Whole lists kept in the cache (items, customers, suppliers, people). IndexedDB first (the stored copy is keyed by company AND user: it is that user's RLS view); then `table_changes_since(cursor)` names the rows that changed since the stored copy and only those are re-read. The full list is fetched once per device, and again only when the log cannot answer (no cursor, a server restart, a cursor older than 7 days, more than 500 changed rows). Broadcasts patch it while the tab is open |++## Cross-References++- `.claude/rules/authz-manifest.md` — the `realtime.messages` policies and the event-trigger attachments+- `packages/database/src/event-system/functions/broadcast_*.sql` — what a message contains+- `packages/database/src/event-system/functions/log_*.sql` and `20261004200418_table-change-log.sql` — the change log (`tableChange`, UNLOGGED) and its reader+- `.ai/specs/2026-10-04-client-query-cache-and-realtime-broadcast.md` — the design and its decisionsdiff --git a/packages/query/CLAUDE.md b/packages/query/CLAUDE.mdnew file mode 100644index 0000000000..43c994c2d3--- /dev/null+++ b/packages/query/CLAUDE.md@@ -0,0 +1 @@diff --git a/packages/query/package.json b/packages/query/package.jsonnew file mode 100644index 0000000000..dbead0c1a6--- /dev/null+++ b/packages/query/package.json@@ -0,0 +1,38 @@+{+ "name": "@carbon/query",+ "private": true,+ "version": "0.0.0",+ "type": "module",+ "sideEffects": false,+ "exports": {+ ".": "./src/index.ts",+ "./cache": "./src/cache.ts"+ },+ "scripts": {+ "clean": "rimraf .turbo node_modules",+ "lint": "biome lint --write ",+ "test": "vitest run",+ "typecheck": "tsgo --noEmit"+ },+ "dependencies": {+ "@carbon/database": "workspace:*",+ "@carbon/env": "workspace:*",+ "@carbon/logger": "workspace:*",+ "@carbon/react": "workspace:*",+ "@carbon/utils": "workspace:*",+ "@supabase/supabase-js": "catalog:",+ "@tanstack/react-query": "catalog:"+ },+ "devDependencies": {+ "@carbon/config": "workspace:*",+ "@types/react": "catalog:",+ "react": "catalog:",+ "react-router": "catalog:",+ "typescript": "catalog:",+ "vitest": "catalog:"+ },+ "peerDependencies": {+ "react": "catalog:",+ "react-router": "catalog:"+ }+}diff --git a/packages/query/src/cache.test.ts b/packages/query/src/cache.test.tsnew file mode 100644index 0000000000..4d1d3978fc--- /dev/null+++ b/packages/query/src/cache.test.ts@@ -0,0 +1,173 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { QueryClient } from "@tanstack/react-query";+import type { ClientLoaderFunctionArgs } from "react-router";+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ cachedApiQuery,+ cachedClientLoader,+ getClientCache,+ getCompanyId,+ LOADER,+ loaderQueryKey,+ setClientCompanyId+} from "./cache";+import { invalidateLoaderEntries } from "./invalidation";++describe("during server rendering", () => {+ it("has no company and no client cache", () => {+ setClientCompanyId("company-a");+ expect(getCompanyId()).toBeNull();+ expect(getClientCache()).toBeUndefined();+ });+});++describe("cachedClientLoader", () => {+ const args = (url: string, serverLoader: () => Promise<unknown>) =>+ ({+ request: new Request(url),+ serverLoader+ }) as unknown as ClientLoaderFunctionArgs;++ const inBrowser = (companyId: string | null) => {+ const cache = new QueryClient();+ vi.stubGlobal("window", { clientCache: cache });+ setClientCompanyId(companyId);+ return cache;+ };++ afterEach(() => {+ setClientCompanyId(null);+ vi.unstubAllGlobals();+ });++ it("hydrates, so the cache warms on first load", () => {+ expect(cachedClientLoader().hydrate).toBe(true);+ });++ it("loads one URL once for concurrent and repeated reads", async () => {+ inBrowser("company-a");+ const serverLoader = vi.fn(async () => ({ data: [1] }));+ const load = cachedClientLoader();+ const url = "http://localhost/api/sales/customer-types";++ const [first, second] = await Promise.all([+ load(args(url, serverLoader)),+ load(args(url, serverLoader))+ ]);+ await load(args(url, serverLoader));++ expect(first).toEqual({ data: [1] });+ expect(second).toBe(first);+ expect(serverLoader).toHaveBeenCalledTimes(1);+ });++ it("keys by search string and by company", async () => {+ const cache = inBrowser("company-a");+ const serverLoader = vi.fn(async () => ({}));+ const load = cachedClientLoader();++ await load(args("http://localhost/api/x?locationId=1", serverLoader));+ await load(args("http://localhost/api/x?locationId=2", serverLoader));+ setClientCompanyId("company-b");+ await load(args("http://localhost/api/x?locationId=1", serverLoader));++ expect(serverLoader).toHaveBeenCalledTimes(3);+ expect(+ cache.getQueryData(loaderQueryKey("/api/x?locationId=1", "company-b"))+ ).toEqual({});+ });++ it("loads again after the loader entries are invalidated", async () => {+ const cache = inBrowser("company-a");+ const serverLoader = vi.fn(async () => ({}));+ const load = cachedClientLoader();+ const url = "http://localhost/api/x";++ await load(args(url, serverLoader));+ await cache.invalidateQueries({ queryKey: [LOADER] });+ await load(args(url, serverLoader));++ expect(serverLoader).toHaveBeenCalledTimes(2);+ });++ it("goes straight to the server, uncached, with no company", async () => {+ const cache = inBrowser(null);+ const serverLoader = vi.fn(async () => ({}));++ await cachedClientLoader()(args("http://localhost/api/x", serverLoader));+ await cachedClientLoader()(args("http://localhost/api/x", serverLoader));++ expect(serverLoader).toHaveBeenCalledTimes(2);+ expect(cache.getQueryCache().getAll()).toHaveLength(0);+ });+});++describe("who the cache belongs to", () => {+ const install = () => {+ const cache = new QueryClient();+ vi.stubGlobal("window", { clientCache: cache });+ return cache;+ };+ afterEach(() => {+ setClientCompanyId(null, null);+ vi.unstubAllGlobals();+ });++ it("is emptied when another user takes over the tab", () => {+ const cache = install();+ setClientCompanyId("company-a", "user-a");+ cache.setQueryData(["live", "company-a", "customers"], [{ id: "1" }]);+ cache.setQueryData(loaderQueryKey("/api/x"), []);++ setClientCompanyId("company-a", "user-b");++ expect(cache.getQueryCache().getAll()).toHaveLength(0);+ });++ it("drops a company's loader entries on leaving it, and nothing else", () => {+ const cache = install();+ setClientCompanyId("company-a", "user-a");+ cache.setQueryData(loaderQueryKey("/api/x"), []);+ cache.setQueryData(["live", "company-a", "customers"], [{ id: "1" }]);++ setClientCompanyId("company-b", "user-a");++ expect(+ cache.getQueryData(loaderQueryKey("/api/x", "company-a"))+ ).toBeUndefined();+ expect(cache.getQueryData(["live", "company-a", "customers"])).toEqual([+ { id: "1" }+ ]);+ });++ it("keeps a load that finished after an invalidation stale", async () => {+ const cache = install();+ setClientCompanyId("company-a", "user-a");+ let finish = (_rows: string[]): void => undefined;+ vi.stubGlobal(+ "fetch",+ () =>+ new Promise((resolve) => {+ finish = (rows) =>+ resolve(+ new Response(JSON.stringify(rows), {+ headers: { "content-type": "application/json" }+ })+ );+ })+ );++ const load = cachedApiQuery<string[]>("/api/x");+ await Promise.resolve();+ invalidateLoaderEntries(cache);+ finish(["before the mutation"]);++ expect(await load).toEqual(["before the mutation"]);+ expect(cache.getQueryState(loaderQueryKey("/api/x"))?.isInvalidated).toBe(+ true+ );+ });+});diff --git a/packages/query/src/cache.ts b/packages/query/src/cache.tsnew file mode 100644index 0000000000..7769365474--- /dev/null+++ b/packages/query/src/cache.ts@@ -0,0 +1,171 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { QueryClient } from "@tanstack/react-query";+import type { ClientLoaderFunctionArgs } from "react-router";+import { LOADER_QUERY_KEY, loaderInvalidations } from "./invalidation";++// The cache half of @carbon/query, with no React or UI import: a route module+// (which also runs on the server) can import it without pulling in the app's+// component library.++export { createInvalidationMiddleware } from "./invalidation";++/** How long a cached entry is served before it is refetched, in ms. */+export const RefreshRate = {+ Never: Number.POSITIVE_INFINITY,+ High: 1000 * 60 * 2,+ Medium: 1000 * 60 * 10,+ Low: 1000 * 60 * 30+} as const;++// The `companyId` cookie is httpOnly, so the browser cannot read it: the shell+// layout hands the company over instead, before anything below it renders.+let clientCompanyId: string | null = null;+let clientUserId: string | null = null;++/**+ * Who the page is working as. The cache is one user's view of one company:+ * - another user in this tab (sign out, sign in) starts from an empty cache;+ * - leaving a company drops its loader entries, because a load that was in+ * flight while another tab switched the company cookie answered for the new+ * company and was stored under the old one.+ */+export const setClientCompanyId = (+ companyId: string | null,+ userId: string | null = clientUserId+) => {+ if (typeof window === "undefined") return;+ const cache = getClientCache();+ if (clientUserId && userId !== clientUserId) {+ cache?.clear();+ } else if (clientCompanyId && companyId !== clientCompanyId) {+ cache?.removeQueries({ queryKey: [LOADER_QUERY_KEY, clientCompanyId] });+ }+ clientCompanyId = companyId;+ clientUserId = userId;+};++export const getCompanyId = () => clientCompanyId;++/** The one QueryClient of the page, reachable outside React. The app root creates it. */+export const getClientCache = (): QueryClient | undefined => {+ if (typeof window === "undefined") {+ return undefined;+ }++ return (window as { clientCache?: QueryClient }).clientCache;+};++/** First segment of every cached loader entry; the root middleware invalidates by it. */+export const LOADER = LOADER_QUERY_KEY;++// URL keys make one entry per distinct search string, so they cannot live forever.+const LOADER_GC_TIME = 1000 * 60 * 30;++/** The cache key of a loader URL — the same for a `clientLoader` and a component read. */+export const loaderQueryKey = (url: string, companyId = getCompanyId()) => {+ const { pathname, search } = new URL(url, "http://localhost");+ return [LOADER, companyId ?? "null", pathname, search];+};++/**+ * A `clientLoader` that caches its route's server loader by URL. Unlike a+ * `getQueryData`/`setQueryData` pair it honors `staleTime`, dedupes concurrent+ * loads, and refetches once the root middleware has invalidated the entry.+ */+export function cachedClientLoader<L>(options?: { staleTime?: number }) {+ const clientLoader = ({+ request,+ serverLoader+ }: ClientLoaderFunctionArgs) => {+ const cache = getClientCache();+ const companyId = getCompanyId();+ if (!cache || !companyId) return serverLoader<L>();+ return fetchLoader(cache, {+ queryKey: loaderQueryKey(request.url, companyId),+ queryFn: () => serverLoader<L>(),+ staleTime: options?.staleTime ?? RefreshRate.Low,+ gcTime: LOADER_GC_TIME+ });+ };+ clientLoader.hydrate = true as const;+ return clientLoader;+}++/**+ * `fetchQuery`, for a load with no observer. Nothing cancels such a load when+ * the entries are invalidated, so one that started before a mutation and+ * finished after it would be stored as fresh: it is marked stale again here.+ */+async function fetchLoader<T>(+ cache: QueryClient,+ query: {+ queryKey: unknown[];+ queryFn: () => Promise<T>;+ staleTime: number;+ gcTime: number;+ }+): Promise<T> {+ const before = loaderInvalidations();+ const data = await cache.fetchQuery(query);+ if (loaderInvalidations() !== before) {+ await cache.invalidateQueries({+ queryKey: query.queryKey,+ exact: true,+ refetchType: "none"+ });+ }+ return data;+}++/** A read the server answered and refused: asking again changes nothing. */+export class LoaderRequestError extends Error {}++const fetchJson = async <T>(url: string): Promise<T> => {+ const res = await fetch(url);+ if (!res.ok) {+ const message = `Request failed with status ${res.status}`;+ throw res.status < 500+ ? new LoaderRequestError(message)+ : new Error(message);+ }+ // An expired session redirects to the login page, which is HTML.+ if (!res.headers.get("content-type")?.includes("json")) {+ throw new LoaderRequestError(+ `Expected JSON from ${url} (is the session still valid?)`+ );+ }+ return res.json();+};++/**+ * What a cached read of `url` is: the key, the fetch and the lifetimes. Shared+ * by the imperative read below and by `useLoaderQuery`, so both land on the+ * entry a `cachedClientLoader` for the same URL uses.+ */+export const loaderQuery = <T>(+ url: string,+ options?: { staleTime?: number }+) => ({+ queryKey: loaderQueryKey(url),+ queryFn: () => fetchJson<T>(url),+ staleTime: options?.staleTime ?? RefreshRate.Low,+ gcTime: LOADER_GC_TIME+});++/**+ * Read-through fetch against an API route, cached by its URL in the page's+ * QueryClient. fetchQuery dedupes concurrent identical calls and honors+ * staleTime. Falls back to a plain fetch when the cache isn't mounted yet.+ * For an event handler or an effect; a component renders with `useLoaderQuery`.+ */+export async function cachedApiQuery<T>(+ url: string,+ options?: { staleTime?: number }+): Promise<T> {+ const cache = getClientCache();+ if (!cache) return fetchJson<T>(url);+ return fetchLoader(cache, loaderQuery<T>(url, options));+}diff --git a/packages/query/src/index.ts b/packages/query/src/index.tsnew file mode 100644index 0000000000..536c0f9f24--- /dev/null+++ b/packages/query/src/index.ts@@ -0,0 +1,23 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++export * from "./cache";+export type { Cursor } from "./liveList";+export { matchesFilter } from "./realtimeFilter";+export { actionOutcome, useAction } from "./useAction";+export type { ChangedRows } from "./useChangedRows";+export { useChangedRows } from "./useChangedRows";+export type { LiveList, LiveListStorage } from "./useLiveList";+export { LiveLists, liveListKey, useLiveList } from "./useLiveList";+export { useLoaderQuery } from "./useLoaderQuery";+export type { BroadcastChange } from "./useRealtime";+export {+ companyTopic,+ RouteRealtime,+ useRealtimeRevalidator,+ useRealtimeTable,+ useTableChanges,+ useTopic+} from "./useRealtime";+export { useRealtimeChannel } from "./useRealtimeChannel";diff --git a/packages/query/src/invalidation.test.ts b/packages/query/src/invalidation.test.tsnew file mode 100644index 0000000000..b28fe095a6--- /dev/null+++ b/packages/query/src/invalidation.test.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { QueryClient } from "@tanstack/react-query";+import { describe, expect, it } from "vitest";+import { createInvalidationMiddleware, LOADER_QUERY_KEY } from "./invalidation";++const loaderKey = [LOADER_QUERY_KEY, "company-a", "/api/x", ""];+const liveKey = ["live", "company-a", "items"];++// A real cache holding one loader entry and one entry of another kind, run+// through the middleware as React Router would for one request.+const run = async (method: string, url: string) => {+ const cache = new QueryClient();+ cache.setQueryData(loaderKey, []);+ cache.setQueryData(liveKey, []);+ const stale = (key: unknown[]) =>+ cache.getQueryState(key)?.isInvalidated ?? false;++ const middleware = createInvalidationMiddleware({+ getCache: () => cache,+ skipPaths: ["/refresh-session"]+ });+ const result = await middleware(+ { request: new Request(url, { method }) } as never,+ (async () => {+ // Nothing is stale until the mutation itself has finished.+ expect(stale(loaderKey)).toBe(false);+ return "result";+ }) as never+ );++ expect(result).toBe("result");+ return { loader: stale(loaderKey), live: stale(liveKey) };+};++describe("createInvalidationMiddleware", () => {+ it("leaves the cache alone on a GET", async () => {+ expect(await run("GET", "http://localhost/x/sales")).toEqual({+ loader: false,+ live: false+ });+ });++ it("marks the loader entries stale after a mutation, and only those", async () => {+ expect(+ await run("POST", "http://localhost/x/sales/customer-types/new")+ ).toEqual({ loader: true, live: false });+ });++ it("leaves the cache alone for a skipped path", async () => {+ expect(await run("POST", "http://localhost/refresh-session")).toEqual({+ loader: false,+ live: false+ });+ });+});diff --git a/packages/query/src/invalidation.ts b/packages/query/src/invalidation.tsnew file mode 100644index 0000000000..5a9f49a6e1--- /dev/null+++ b/packages/query/src/invalidation.ts@@ -0,0 +1,57 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { MiddlewareFunction } from "react-router";++/** The part of a TanStack `QueryClient` this needs; `@carbon/auth` does not depend on it. */+type LoaderCache = {+ invalidateQueries(filters: { queryKey: unknown[] }): unknown;+};++// How many times the loader entries have been marked stale. A load that was in+// flight across one finishes with data from before it: TanStack marks a+// finished fetch fresh, so the loader reads this to mark it stale again.+let invalidations = 0;+export const loaderInvalidations = () => invalidations;++/** Marks every cached loader entry stale (`cachedClientLoader`, `useLoaderQuery`). */+export const invalidateLoaderEntries = (cache: LoaderCache | undefined) => {+ invalidations += 1;+ cache?.invalidateQueries({ queryKey: [LOADER_QUERY_KEY] });+};++/** First segment of every cached loader entry (`cachedClientLoader`, `useLoaderQuery`). */+export const LOADER_QUERY_KEY = "loader";++/**+ * Marks every cached loader entry stale once a mutation has finished, so no+ * route has to name the lists its action changes. The action and the+ * revalidation that follows it are separate passes through the middleware, so+ * the entries are already stale when the loaders re-run.+ *+ * `skipPaths` is for POSTs that change no data (the session refresh that fires+ * on every tab focus would otherwise refetch every list).+ */+export const createInvalidationMiddleware =+ ({+ getCache,+ skipPaths = []+ }: {+ getCache: () => LoaderCache | undefined;+ skipPaths?: string[];+ }): MiddlewareFunction<unknown> =>+ async ({ request }, next) => {+ if (+ request.method === "GET" ||+ skipPaths.includes(new URL(request.url).pathname)+ ) {+ return next();+ }+ try {+ return await next();+ } finally {+ // An action that throws may still have written.+ invalidateLoaderEntries(getCache());+ }+ };diff --git a/packages/query/src/liveList.test.ts b/packages/query/src/liveList.test.tsnew file mode 100644index 0000000000..5f1c66c3d5--- /dev/null+++ b/packages/query/src/liveList.test.ts@@ -0,0 +1,85 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ type LoggedChanges,+ oldestCursor,+ planSync,+ removeRows,+ upsertRows+} from "./liveList";++const byName = (a: { name: string }, b: { name: string }) =>+ a.name.localeCompare(b.name);+const rows = [+ { id: "1", name: "Acme" },+ { id: "2", name: "Zenith" }+];+const cursor = { xid: "100", epoch: "e1", at: "2026-10-05T00:00:00Z" };+const log = (+ changes: LoggedChanges["changes"],+ reset = false+): LoggedChanges => ({ ...cursor, reset, changes });++describe("upsertRows / removeRows", () => {+ it("adds a new row in sort order", () => {+ expect(upsertRows(rows, [{ id: "3", name: "Mid" }], byName)).toEqual([+ rows[0],+ { id: "3", name: "Mid" },+ rows[1]+ ]);+ });++ it("replaces a row it already has, without a duplicate", () => {+ expect(upsertRows(rows, [{ id: "1", name: "Zulu" }], byName)).toEqual([+ rows[1],+ { id: "1", name: "Zulu" }+ ]);+ });++ it("removes rows by id", () => {+ expect(removeRows(rows, ["2", "9"])).toEqual([rows[0]]);+ });+});++describe("oldestCursor", () => {+ it("is null when no list has a cursor", () => {+ expect(oldestCursor([null, null])).toBeNull();+ });++ it("picks the lowest transaction id, compared as a number", () => {+ const older = { ...cursor, xid: "99" };+ expect(oldestCursor([cursor, null, older])).toBe(older);+ });+});++describe("planSync", () => {+ it("re-reads only the changed rows of the list's tables", () => {+ expect(+ planSync(log({ customer: ["1"], supplier: ["7"] }), ["customer"], true)+ ).toEqual([["customer", ["1"]]]);+ });++ it("does nothing when none of the list's tables changed", () => {+ expect(planSync(log({ supplier: ["7"] }), ["customer"], true)).toEqual([]);+ });++ it("fetches everything when the log was reset", () => {+ expect(planSync(log({}, true), ["customer"], true)).toBe("all");+ });++ it("fetches everything when the answer does not cover this list", () => {+ expect(planSync(log({}), ["customer"], false)).toBe("all");+ });++ it("fetches everything when a table changed too much to list", () => {+ expect(planSync(log({ customer: null }), ["customer"], true)).toBe("all");+ });++ it("fetches everything past 500 changed rows", () => {+ const ids = Array.from({ length: 501 }, (_, i) => String(i));+ expect(planSync(log({ customer: ids }), ["customer"], true)).toBe("all");+ });+});diff --git a/packages/query/src/liveList.ts b/packages/query/src/liveList.tsnew file mode 100644index 0000000000..5e37a86c4b--- /dev/null+++ b/packages/query/src/liveList.ts@@ -0,0 +1,85 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// The pure half of the live lists: how a list is brought up to date from the+// change log (`table_changes_since`) or a broadcast. No React, no network.++/** Where to start reading the change log next time. Opaque to the client. */+export type Cursor = { xid: string; epoch: string; at: string };++/** What `table_changes_since` answers. */+export type LoggedChanges = Cursor & {+ /** The log cannot answer for the cursor it was given: fetch everything. */+ reset: boolean;+ /** Changed row ids per table. `null`: too many to list, read the table again. */+ changes: Record<string, string[] | null>;+};++// Past this many changed rows, one full fetch is cheaper than the re-reads.+const MAX_ROWS_TO_REREAD = 500;++/**+ * The cursor to send for several lists: the oldest, so its answer covers them+ * all (a list with a newer cursor is told about a few rows it already has).+ * `null` when no list has one.+ */+export function oldestCursor(cursors: (Cursor | null)[]): Cursor | null {+ let oldest: Cursor | null = null;+ for (const cursor of cursors) {+ if (!cursor) continue;+ if (!oldest || BigInt(cursor.xid) < BigInt(oldest.xid)) oldest = cursor;+ }+ return oldest;+}++/**+ * How to bring one list up to date: `"all"` (fetch it in full) or the changed+ * ids to re-read, per table.+ *+ * `covered` says the answer was computed from a cursor this list can trust:+ * it has rows, and its own cursor is from the same server epoch as the one+ * that was sent. Without that the log's answer says nothing about this list.+ */+export function planSync(+ log: LoggedChanges,+ tables: string[],+ covered: boolean+): "all" | [table: string, ids: string[]][] {+ if (log.reset || !covered) return "all";+ const plan: [string, string[]][] = [];+ let total = 0;+ for (const table of tables) {+ if (!(table in log.changes)) continue;+ const ids = log.changes[table];+ if (!ids) return "all";+ total += ids.length;+ plan.push([table, ids]);+ }+ return total > MAX_ROWS_TO_REREAD ? "all" : plan;+}++/** The list without these rows. */+export function removeRows<Row extends { id: string }>(+ rows: Row[],+ ids: string[]+): Row[] {+ const gone = new Set(ids);+ return rows.filter((row) => !gone.has(row.id));+}++/** The list with these rows added, or replaced where it already has them. */+export function upsertRows<Row extends { id: string }>(+ rows: Row[],+ fetched: Row[],+ sort: (a: Row, b: Row) => number+): Row[] {+ if (fetched.length === 0) return rows;+ return [+ ...removeRows(+ rows,+ fetched.map((row) => row.id)+ ),+ ...fetched+ ].sort(sort);+}diff --git a/packages/query/src/realtimeFilter.test.ts b/packages/query/src/realtimeFilter.test.tsnew file mode 100644index 0000000000..32f61eac0b--- /dev/null+++ b/packages/query/src/realtimeFilter.test.ts@@ -0,0 +1,44 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { matchesFilter } from "./realtimeFilter";++describe("matchesFilter", () => {+ it("matches every change without a filter", () => {+ expect(matchesFilter(undefined, { ids: ["a"] })).toBe(true);+ });++ it("matches an id=eq filter only for that id", () => {+ expect(matchesFilter("id=eq.a", { ids: ["a", "b"] })).toBe(true);+ expect(matchesFilter("id=eq.c", { ids: ["a", "b"] })).toBe(false);+ });++ it("matches an id=in filter when any id is in it", () => {+ expect(matchesFilter("id=in.(a,b)", { ids: ["b"] })).toBe(true);+ expect(matchesFilter("id=in.(a,b)", { ids: ["c"] })).toBe(false);+ });++ it("matches a filter on a parent column by the parents the change names", () => {+ const change = { ids: ["a"], parents: { jobId: ["j1"] } };+ expect(matchesFilter("jobId=eq.j1", change)).toBe(true);+ expect(matchesFilter("jobId=eq.j2", change)).toBe(false);+ expect(matchesFilter("jobId=in.(j2,j1)", change)).toBe(true);+ });++ it("matches every change when the change does not name that column", () => {+ expect(matchesFilter("jobId=eq.j1", { ids: ["a"] })).toBe(true);+ expect(matchesFilter("jobId=eq.j1", { ids: ["a"], parents: {} })).toBe(+ true+ );+ expect(matchesFilter("status=eq.Done", { ids: ["a"] })).toBe(true);+ });++ it("matches a bulk change, which carries neither ids nor parents", () => {+ expect(matchesFilter("id=eq.a", { ids: null, parents: null })).toBe(true);+ expect(matchesFilter("jobId=eq.j1", { ids: null, parents: null })).toBe(+ true+ );+ });+});diff --git a/packages/query/src/realtimeFilter.ts b/packages/query/src/realtimeFilter.tsnew file mode 100644index 0000000000..985d3ef89a--- /dev/null+++ b/packages/query/src/realtimeFilter.ts@@ -0,0 +1,42 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++/** What a broadcast says about the rows that changed. */+type Changed = {+ ids?: string[] | null;+ /** The values of each `<name>Id` column of the changed rows. */+ parents?: Record<string, string[]> | null;+};++/**+ * Whether a change concerns the rows a PostgREST-style filter names:+ * `id=eq.<id>`, `id=in.(<ids>)`, or the same on a `<name>Id` column+ * (`jobId=eq.<id>`). A broadcast carries ids and nothing else, so a filter on+ * any other column matches every change. So does a change that does not say:+ * a bulk change carries neither ids nor parents, and a column with many values+ * is left out. The answer errs towards "it may concern me".+ */+export function matchesFilter(+ filter: string | undefined,+ change: Changed+): boolean {+ const parsed = filter && /^(\w+)=(eq|in)\.(.*)$/.exec(filter);+ if (!parsed) return true;+ const [, column, operator, value] = parsed as unknown as [+ string,+ string,+ string,+ string+ ];+ const changed = column === "id" ? change.ids : change.parents?.[column];+ if (!changed) return true;+ const wanted =+ operator === "eq"+ ? [value]+ : value+ .replace(/^\(|\)$/g, "")+ .split(",")+ .map((id) => id.trim());+ return wanted.some((id) => changed.includes(id));+}diff --git a/packages/query/src/useAction.test.ts b/packages/query/src/useAction.test.tsnew file mode 100644index 0000000000..ae8e522532--- /dev/null+++ b/packages/query/src/useAction.test.ts@@ -0,0 +1,32 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { actionOutcome } from "./useAction";++describe("actionOutcome", () => {+ it("is nothing while there is no data", () => {+ expect(actionOutcome(undefined)).toBeNull();+ expect(actionOutcome(null)).toBeNull();+ });++ it("is nothing for a 422 with field errors", () => {+ expect(+ actionOutcome({ fieldErrors: { name: "Required" }, formId: "form" })+ ).toBeNull();+ });++ it("is an error for success: false or an error", () => {+ expect(actionOutcome({ success: false, message: "No" })).toBe("error");+ expect(actionOutcome({ error: { message: "No" } })).toBe("error");+ expect(actionOutcome({ data: null, error: "No" })).toBe("error");+ });++ it("is a success otherwise", () => {+ expect(actionOutcome({ success: true })).toBe("success");+ expect(actionOutcome({ data: { id: "1" }, error: null })).toBe("success");+ expect(actionOutcome({ id: "1" })).toBe("success");+ expect(actionOutcome({})).toBe("success");+ });+});diff --git a/packages/query/src/useAction.ts b/packages/query/src/useAction.tsnew file mode 100644index 0000000000..202fa48197--- /dev/null+++ b/packages/query/src/useAction.ts@@ -0,0 +1,79 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { useEffect, useRef } from "react";+import { useFetcher } from "react-router";++/** How a finished action turned out, from the shape route actions return. */+export function actionOutcome(data: unknown): "success" | "error" | null {+ if (data == null) return null;+ if (typeof data === "object") {+ const result = data as {+ success?: unknown;+ error?: unknown;+ fieldErrors?: unknown;+ };+ // `validationError`: the form shows the field errors itself.+ if (result.fieldErrors) return null;+ if (result.success === false || result.error) return "error";+ }+ return "success";+}++type ActionData<T> = NonNullable<ReturnType<typeof useFetcher<T>>["data"]>;++/**+ * A fetcher for a mutation, with the result delivered to a callback instead of+ * an effect that watches `fetcher.data`. The mutation is still a router action:+ * submit it with `.submit(...)` or `<action.Form>`, exactly as with `useFetcher`.+ *+ * `onSettled` runs once each time a submission finishes, with or without data:+ * an action that redirects (most deletes) returns none. `onSuccess` /+ * `onError` run only when there is data. `onError` is for a result with+ * `success: false` or an `error`; everything else is a success. A 422 with+ * field errors (`validationError`) is neither: the form shows them itself.+ *+ * The cache needs nothing from the caller: the root middleware marks every+ * loader entry stale after the action.+ */+// biome-ignore lint/suspicious/noExplicitAny: an untyped fetcher's data is `any`, as with useFetcher+export function useAction<T = any>(+ options: {+ key?: string;+ onSuccess?: (data: ActionData<T>) => void;+ onError?: (data: ActionData<T>) => void;+ /** Runs whenever a submission finishes, before `onSuccess` / `onError`. */+ onSettled?: (data: ActionData<T> | undefined) => void;+ } = {}+) {+ const fetcher = useFetcher<T>(options.key ? { key: options.key } : undefined);+ // The latest callbacks, so a new closure each render re-runs nothing.+ const callbacks = useRef(options);+ callbacks.current = options;+ const submitted = useRef(false);++ const { state, data } = fetcher;+ useEffect(() => {+ if (state !== "idle") {+ submitted.current = true;+ return;+ }+ if (!submitted.current) return;+ submitted.current = false;+ const outcome = actionOutcome(data);+ callbacks.current.onSettled?.((data ?? undefined) as ActionData<T>);+ if (outcome === "success") {+ callbacks.current.onSuccess?.(data as ActionData<T>);+ } else if (outcome === "error") {+ callbacks.current.onError?.(data as ActionData<T>);+ }+ }, [state, data]);++ return Object.assign(fetcher, {+ /** A submission is in flight (submitting, or reloading after it). */+ isPending: state !== "idle",+ /** The values being submitted, for showing them before the server answers. */+ pending: fetcher.formData+ });+}diff --git a/packages/query/src/useChangedRows.ts b/packages/query/src/useChangedRows.tsnew file mode 100644index 0000000000..c888ede63e--- /dev/null+++ b/packages/query/src/useChangedRows.ts@@ -0,0 +1,100 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { RealtimeTable } from "@carbon/database/realtime-tables";+import { getLogger } from "@carbon/logger";+import { useCarbon } from "@carbon/react";+import { useRef } from "react";+import { matchesFilter } from "./realtimeFilter";+import type { BroadcastChange } from "./useRealtime";+import { useTableChanges } from "./useRealtime";++const logger = getLogger("query", "changed-rows");++export type ChangedRows<Row> = {+ op: BroadcastChange["op"];+ /** Every id the change named. */+ ids: string[];+ /**+ * Those rows as they are now. Empty for a DELETE. A named row that is missing+ * here is gone, or is not visible to this user.+ */+ rows: Row[];+};++/**+ * Follows a table's rows for a component that keeps them in its own state (a+ * chat, a list of running events). A broadcast names the rows that changed and+ * carries no data, so this re-reads them through PostgREST — table RLS decides+ * what comes back — and hands them to `onChange`.+ *+ * `onResync` runs when the change cannot be applied row by row: after a+ * reconnect, or when more than 100 rows changed at once. Load the state again.+ */+export function useChangedRows<Row extends { id: string }>({+ companyId,+ table,+ columns = "*",+ filter,+ enabled = true,+ onChange,+ onResync+}: {+ companyId: string;+ table: RealtimeTable;+ columns?: string;+ /**+ * Only changes to rows of one record, as `useRealtimeTable` takes it+ * (`jobOperationId=eq.<id>`): other rows are not re-read at all.+ */+ filter?: string;+ enabled?: boolean;+ onChange: (change: ChangedRows<Row>) => void;+ onResync?: () => void;+}) {+ const { carbon } = useCarbon();+ const handlers = useRef({ onChange, onResync });+ handlers.current = { onChange, onResync };+ // Changes are applied in the order they arrived: a delete that lands while+ // an earlier update is still being re-read must not be undone by it.+ const queue = useRef<Promise<void>>(Promise.resolve());++ return useTableChanges({+ companyId,+ table,+ enabled,+ onChange: (change) => {+ if (change && !matchesFilter(filter, change)) return;+ queue.current = queue.current.then(() => apply(change));+ }+ });++ async function apply(change: BroadcastChange | null) {+ if (!change?.ids) {+ handlers.current.onResync?.();+ return;+ }+ const { op, ids } = change;+ if (op === "DELETE") {+ handlers.current.onChange({ op, ids, rows: [] });+ return;+ }+ const { data, error } = await carbon+ // The table is one of ~70 and the columns are the caller's: the typed+ // builder cannot express that, and the caller types the rows.+ .from(table as "item")+ .select(columns)+ .eq("companyId", companyId)+ .in("id", ids);+ if (error) {+ logger.error("Failed to read changed rows", { table, error });+ return;+ }+ handlers.current.onChange({+ op,+ ids,+ rows: (data ?? []) as unknown as Row[]+ });+ }+}diff --git a/packages/query/src/useLiveList.tsx b/packages/query/src/useLiveList.tsxnew file mode 100644index 0000000000..4d0096307c--- /dev/null+++ b/packages/query/src/useLiveList.tsx@@ -0,0 +1,412 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type { Database } from "@carbon/database";+import type { RealtimeTable } from "@carbon/database/realtime-tables";+import { getLogger } from "@carbon/logger";+import { useCarbon } from "@carbon/react";+import { chunkArray } from "@carbon/utils";+import type { SupabaseClient } from "@supabase/supabase-js";+import { useQuery, useQueryClient } from "@tanstack/react-query";+import { useCallback, useEffect, useRef } from "react";+import {+ type Cursor,+ type LoggedChanges,+ oldestCursor,+ planSync,+ removeRows,+ upsertRows+} from "./liveList";+import type { BroadcastChange } from "./useRealtime";+import { useTableChanges } from "./useRealtime";++const logger = getLogger("query", "live-list");++const IDS_PER_REQUEST = 100;++type Carbon = SupabaseClient<Database>;++/**+ * A whole list the app keeps in memory and current: picker options, and labels+ * looked up by id.+ *+ * It is read from IndexedDB at once. The server is then asked which rows+ * changed since the stored copy was taken (`table_changes_since`), and only+ * those rows are read — the full list is fetched once per device, and again+ * only when the change log cannot answer (see `planSync`). While the tab is+ * open, broadcasts patch it row by row.+ */+export type LiveList<Row extends { id: string }> = {+ /** The list's name in the query key and IndexedDB. */+ name: string;+ /** The table whose row ids are this list's row ids. */+ table: RealtimeTable;+ fetchAll: (carbon: Carbon, companyId: string) => Promise<Row[]>;+ /** The rows with these ids, as they are now. A missing one leaves the list. */+ fetchByIds: (+ carbon: Carbon,+ companyId: string,+ ids: string[]+ ) => Promise<Row[]>;+ /**+ * Other tables that feed a list row (an item's supersession, its model's+ * thumbnail). `fetch` returns the list rows that those changed rows touch.+ */+ related?: {+ table: RealtimeTable;+ fetch: (carbon: Carbon, companyId: string, ids: string[]) => Promise<Row[]>;+ }[];+ sort: (a: Row, b: Row) => number;+};++// A list of some row type, handled generically.+type AnyLiveList = LiveList<any>;+type AnyRow = { id: string };++/** Where the lists are kept between sessions (localforage in both apps). */+export type LiveListStorage = {+ getItem: (key: string) => Promise<unknown>;+ setItem: (key: string, value: unknown) => Promise<unknown>;+};++type Stored = { rows: AnyRow[]; cursor: Cursor | null };++export const liveListKey = (companyId: string, name: string) => [+ "live",+ companyId,+ name+];++// Every key carries the company: an unkeyed copy once hydrated one company's+// pickers with another's rows after a company switch.+const storageKey = (companyId: string, name: string) => `${name}:${companyId}`;+// The stored copy also carries the user: it is that user's view of the list+// (table RLS chose the rows), and the next person at this browser starts from+// the server rather than from someone else's rows.+const storedKey = (companyId: string, userId: string, name: string) =>+ `${storageKey(companyId, name)}:${userId}`;++// A copy written before lists had a cursor is a bare array (or carries a+// checksum instead): its rows are still good to show, with no cursor.+const readStored = (value: unknown): Stored | null => {+ if (Array.isArray(value)) return { rows: value, cursor: null };+ const stored = value as Partial<Stored> | null;+ return stored?.rows+ ? { rows: stored.rows, cursor: stored.cursor ?? null }+ : null;+};++/** A list's rows and a setter, in the `[value, setValue]` shape its consumers use. */+export function useLiveList<Row extends { id: string }>(+ list: LiveList<Row>,+ companyId: string+) {+ const queryClient = useQueryClient();+ const queryKey = liveListKey(companyId, list.name);+ // Never fetches: `LiveLists` owns the data and writes it into the cache.+ const { data } = useQuery<Row[]>({+ queryKey,+ queryFn: () => [],+ enabled: false,+ staleTime: Number.POSITIVE_INFINITY,+ gcTime: Number.POSITIVE_INFINITY+ });++ const set = useCallback(+ (value: Row[] | ((current: Row[]) => Row[])) => {+ queryClient.setQueryData<Row[]>(+ liveListKey(companyId, list.name),+ (current) =>+ typeof value === "function" ? value(current ?? []) : value+ );+ },+ [queryClient, companyId, list.name]+ );++ return [data ?? EMPTY, set] as const;+}++const EMPTY: never[] = [];++function Subscription({+ companyId,+ table,+ onChange+}: {+ companyId: string;+ table: RealtimeTable;+ onChange: (change: BroadcastChange | null) => void;+}) {+ useTableChanges({ companyId, table, onChange });+ return null;+}++/** Loads the lists and keeps them current. Render it once, in the shell. */+export function LiveLists({+ companyId,+ userId,+ lists,+ storage+}: {+ companyId: string;+ userId: string;+ lists: AnyLiveList[];+ storage: () => Promise<LiveListStorage>;+}) {+ const { carbon, accessToken } = useCarbon();+ const queryClient = useQueryClient();+ // The company the callbacks below are working for. A read that finishes+ // after a company switch belongs to the old company and is dropped.+ const active = useRef(companyId);+ active.current = companyId;+ // Each list's cursor, per company (a company switch keeps this mounted):+ // where the change log is asked to start next time.+ const cursors = useRef(new Map<string, Cursor | null>());+ const ready = Boolean(carbon && accessToken);+ // One update of a list at a time. A full fetch and a broadcast's re-read+ // overlap otherwise, and the fetch (the older read) lands last and undoes it.+ const queues = useRef(new Map<string, Promise<unknown>>());+ const inTurn = useCallback(+ <T,>(list: AnyLiveList, update: () => Promise<T>): Promise<T> => {+ const key = storageKey(companyId, list.name);+ const turn = (queues.current.get(key) ?? Promise.resolve()).then(+ update,+ update+ );+ queues.current.set(key, turn);+ return turn;+ },+ [companyId]+ );++ const rowsOf = useCallback(+ (list: AnyLiveList) =>+ queryClient.getQueryData<AnyRow[]>(liveListKey(companyId, list.name)),+ [queryClient, companyId]+ );++ /**+ * Change a list's rows in the cache, then store them with the list's cursor.+ * The change is a function of the rows as they are NOW: two re-reads that+ * finish in either order both land, where a value computed before the read+ * would overwrite the other's rows.+ */+ const commit = useCallback(+ async (+ list: AnyLiveList,+ change: (rows: AnyRow[]) => AnyRow[],+ // The cursor these rows are current as of. It moves only with the rows:+ // a change dropped here must be asked for again.+ cursor?: Cursor+ ) => {+ if (active.current !== companyId) return;+ const rows = queryClient.setQueryData<AnyRow[]>(+ liveListKey(companyId, list.name),+ (current) => change(current ?? [])+ );+ if (cursor) cursors.current.set(storageKey(companyId, list.name), cursor);+ const stored: Stored = {+ rows: rows ?? [],+ cursor: cursors.current.get(storageKey(companyId, list.name)) ?? null+ };+ // The stored copy only speeds up the next load.+ try {+ await (await storage()).setItem(+ storedKey(companyId, userId, list.name),+ stored+ );+ } catch (error) {+ logger.warn("live list not stored", { list: list.name, error });+ }+ },+ [queryClient, storage, companyId, userId]+ );++ /** The rows of `table` with these ids changed: how the list changes. */+ const readIds = useCallback(+ async (+ list: AnyLiveList,+ table: string,+ ids: string[]+ ): Promise<(rows: AnyRow[]) => AnyRow[]> => {+ const read =+ table === list.table+ ? list.fetchByIds+ : list.related?.find((r) => r.table === table)?.fetch;+ if (!carbon || !read || ids.length === 0) return (rows) => rows;+ // `.in()` goes in the URL: a few hundred ids exceed the gateway's limit.+ const fetched = (+ await Promise.all(+ chunkArray(ids, IDS_PER_REQUEST).map((chunk) =>+ read(carbon, companyId, chunk)+ )+ )+ ).flat();+ return (rows) =>+ upsertRows(+ // A row of the list's own table that did not come back is gone+ // (deleted, or no longer visible to this user).+ table === list.table ? removeRows(rows, ids) : rows,+ fetched,+ list.sort+ );+ },+ [carbon, companyId]+ );++ /** Ask the change log what changed since the lists' cursors, and apply it. */+ const sync = useCallback(+ async (targets: AnyLiveList[]) => {+ if (!carbon) return;+ // A list's cursor only counts if the list still has its rows.+ const cursorOf = (list: AnyLiveList) =>+ rowsOf(list)+ ? (cursors.current.get(storageKey(companyId, list.name)) ?? null)+ : null;+ const since = oldestCursor(targets.map(cursorOf));+ const { data, error } = await carbon.rpc("table_changes_since", {+ p_company_id: companyId,+ p_xid: since?.xid,+ p_epoch: since?.epoch,+ p_at: since?.at+ });+ if (error) throw error;+ if (active.current !== companyId) return;+ const log = data as unknown as LoggedChanges;+ const next: Cursor = { xid: log.xid, epoch: log.epoch, at: log.at };++ await Promise.all(+ targets.map((list) =>+ inTurn(list, async () => {+ const tables = [+ list.table,+ ...(list.related ?? []).map((r) => r.table)+ ];+ const plan = planSync(+ log,+ tables,+ cursorOf(list)?.epoch === since?.epoch && since !== null+ );+ let changes: ((rows: AnyRow[]) => AnyRow[])[];+ if (plan === "all") {+ const all = await list.fetchAll(carbon, companyId);+ changes = [() => all];+ } else {+ changes = await Promise.all(+ plan.map(([table, ids]) => readIds(list, table, ids))+ );+ }+ await commit(+ list,+ (rows) =>+ changes.reduce((current, change) => change(current), rows),+ next+ );+ })+ )+ );+ },+ [carbon, companyId, rowsOf, readIds, commit, inTurn]+ );++ // Cold load: IndexedDB first so pickers have options at once, then the log.+ useEffect(() => {+ let cancelled = false;+ (async () => {+ // Without storage (blocked, or no driver) the lists come from the server.+ try {+ const idb = await storage();+ await Promise.all(+ lists.map(async (list) => {+ const stored = readStored(+ await idb.getItem(storedKey(companyId, userId, list.name))+ );+ if (!stored || cancelled || rowsOf(list)) return;+ cursors.current.set(+ storageKey(companyId, list.name),+ stored.cursor+ );+ queryClient.setQueryData(+ liveListKey(companyId, list.name),+ stored.rows+ );+ })+ );+ } catch (error) {+ logger.warn("stored live lists not read", { error });+ }+ if (cancelled || !ready) return;+ await sync(lists);+ })().catch((error) => logger.error("live list load failed", { error }));+ return () => {+ cancelled = true;+ };+ }, [companyId, userId, ready, lists, storage, queryClient, rowsOf, sync]);++ const resync = useRef<{+ lists: Set<AnyLiveList>;+ pending: Promise<void> | null;+ }>({ lists: new Set(), pending: null });++ const onChange = useCallback(+ async (+ list: AnyLiveList,+ table: RealtimeTable,+ change: BroadcastChange | null+ ) => {+ // A reconnect or a bulk change: the log knows exactly what was missed.+ // Every channel reconnects together, so the lists ask the log once.+ if (!change?.ids) {+ resync.current.lists.add(list);+ resync.current.pending ??= new Promise<void>((resolve) =>+ setTimeout(resolve, 50)+ ).then(() => {+ const targets = [...resync.current.lists];+ resync.current = { lists: new Set(), pending: null };+ return sync(targets);+ });+ await resync.current.pending;+ return;+ }+ const { ids } = change;+ // The cursor stays where it was: the log will name these rows again on+ // the next load, and re-reading them is harmless.+ await inTurn(list, async () =>+ commit(+ list,+ change.op === "DELETE" && table === list.table+ ? (rows) => removeRows(rows, ids)+ : await readIds(list, table, ids)+ )+ );+ },+ [sync, readIds, commit, inTurn]+ );++ if (!ready) return null;++ return (+ <>+ {lists.flatMap((list) =>+ [list.table, ...(list.related ?? []).map((r) => r.table)].map(+ (table) => (+ <Subscription+ key={`${list.name}:${table}`}+ companyId={companyId}+ table={table}+ onChange={(change) => {+ onChange(list, table, change).catch((error) =>+ logger.error("live list update failed", {+ list: list.name,+ error+ })+ );+ }}+ />+ )+ )+ )}+ </>+ );+}diff --git a/packages/query/src/useLoaderQuery.ts b/packages/query/src/useLoaderQuery.tsnew file mode 100644index 0000000000..e0d30a3c39--- /dev/null+++ b/packages/query/src/useLoaderQuery.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { useQuery } from "@tanstack/react-query";+import { LoaderRequestError, loaderQuery } from "./cache";++/**+ * What a read returns. `T` is the data itself, or the route's `typeof loader`+ * (as `useFetcher<typeof loader>` takes): then it is what that loader returns,+ * without the `data()` wrapper.+ */+// biome-ignore lint/suspicious/noExplicitAny: any loader signature+export type LoaderData<T> = T extends (...args: any[]) => infer R+ ? Unwrapped<Awaited<R>>+ : T;++// Distributes over a loader that returns `data(...)` on one path and a plain+// object on another. The shape is React Router's `DataWithResponseInit`.+type Unwrapped<R> = R extends {+ type: string;+ data: infer D;+ init: ResponseInit | null;+}+ ? D+ : R;++/**+ * Reads an `api+` URL through the cache, as an observed query: every component+ * reading the same URL shares one request, renders the cached value at once,+ * and refetches when a mutation or a realtime change invalidates the entry.+ * Pass `null` to wait (a picker that is still closed, an id not chosen yet).+ */+export function useLoaderQuery<T>(+ url: string | null,+ options?: { staleTime?: number }+) {+ return useQuery<LoaderData<T>>({+ ...loaderQuery<LoaderData<T>>(url ?? "", options),+ enabled: url !== null,+ // A 403 or an expired session fails the same way every time.+ retry: (failures, error) =>+ !(error instanceof LoaderRequestError) && failures < 3+ });+}diff --git a/packages/query/src/useRealtime.tsx b/packages/query/src/useRealtime.tsxnew file mode 100644index 0000000000..6e6860e50d--- /dev/null+++ b/packages/query/src/useRealtime.tsx@@ -0,0 +1,334 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import type {+ RealtimeTable,+ RouteRealtimeTable+} from "@carbon/database/realtime-tables";+import {+ useCallback,+ useEffect,+ useMemo,+ useRef,+ useSyncExternalStore+} from "react";+import { useFetchers, useMatches, useRevalidator } from "react-router";+import { getClientCache } from "./cache";+import { invalidateLoaderEntries } from "./invalidation";+import { matchesFilter } from "./realtimeFilter";+import { useRealtimeChannel } from "./useRealtimeChannel";++/** What `broadcast_table_changes` sends: no row data, only which rows changed. */+export type BroadcastChange = {+ table: string;+ op: "INSERT" | "UPDATE" | "DELETE";+ /** Null when more than 100 rows changed, or the table has no `id`: resync. */+ ids: string[] | null;+ /**+ * The records the rows belong to: each `<name>Id` column and its values.+ * Null with `ids`; a column with more than 20 values is left out.+ */+ parents?: Record<string, string[]> | null;+};++const DEFAULT_DEBOUNCE_MS = 300;+// A table that changes more often than its debounce would never reload.+const MAX_WAIT_MS = 5000;++/** The topic `broadcast_table_changes` sends a company's changes to a table on. */+export const companyTopic = (companyId: string, table: string) =>+ `company:${companyId}:${table}`;++/** Marks every cached loader entry stale (`cachedClientLoader`, `useLoaderQuery`). */+const invalidateLoaders = () => invalidateLoaderEntries(getClientCache());++// ─── One channel per topic ───────────────────────────────────────────────────+//+// The Realtime client hands back the SAME channel for a topic it already has, so+// two hooks that each opened `company:<id>:customer` would share one channel and+// the first to unmount would close it for the other. Instead every interested+// component registers a listener here, and `RouteRealtime` (rendered once, in+// the shell) owns exactly one channel per topic that has listeners.++/** `null` after a reconnect: nothing is replayed, so the listener catches up. */+type Listener = (change: BroadcastChange | null) => void;++const listeners = new Map<string, Set<Listener>>();+const watchers = new Set<() => void>();+const NO_TOPICS: string[] = [];+let topics: string[] = NO_TOPICS;++const publishTopics = () => {+ topics = [...listeners.keys()].sort();+ for (const notify of watchers) notify();+};++const dispatch = (topic: string, change: BroadcastChange | null) => {+ for (const listener of listeners.get(topic) ?? []) listener(change);+};++function listen(topic: string, listener: Listener) {+ const existing = listeners.get(topic);+ if (existing) {+ existing.add(listener);+ } else {+ listeners.set(topic, new Set([listener]));+ publishTopics();+ }+ return () => {+ const set = listeners.get(topic);+ set?.delete(listener);+ if (set?.size === 0) {+ listeners.delete(topic);+ publishTopics();+ }+ };+}++/**+ * Listen to a private broadcast topic. Any number of components may listen to+ * one topic; they share its channel. `onMessage(null)` means "reconnected".+ */+export function useTopic(topic: string, onMessage: Listener, enabled = true) {+ const onMessageRef = useRef(onMessage);+ onMessageRef.current = onMessage;++ useEffect(() => {+ if (!enabled) return;+ return listen(topic, (change) => onMessageRef.current(change));+ }, [topic, enabled]);+}++function TopicChannel({ topic }: { topic: string }) {+ useRealtimeChannel({+ topic,+ private: true,+ dependencies: [topic],+ onSubscribed: (isReconnect) => {+ if (isReconnect) dispatch(topic, null);+ },+ setup(channel) {+ return channel.on("broadcast", { event: "*" }, ({ payload }) => {+ dispatch(topic, payload as BroadcastChange);+ });+ }+ });+ return null;+}++function TopicChannels() {+ const active = useSyncExternalStore(+ (notify) => {+ watchers.add(notify);+ return () => watchers.delete(notify);+ },+ () => topics,+ () => NO_TOPICS+ );+ return (+ <>+ {active.map((topic) => (+ <TopicChannel key={topic} topic={topic} />+ ))}+ </>+ );+}++// A route and a component on it may both follow one table, and one write often+// touches several tables a page follows. Their timers fire together; the page+// is reloaded once.+let revalidation: ReturnType<typeof setTimeout> | null = null;+const requestRevalidation = (revalidate: () => void) => {+ if (revalidation) clearTimeout(revalidation);+ revalidation = setTimeout(() => {+ revalidation = null;+ revalidate();+ }, 50);+};++/**+ * `revalidate()` that waits for submitting fetchers. React Router drops a+ * fetcher's redirect when a revalidation starts during its action, so a change+ * that arrives mid-submit is held and applied once the fetcher is done.+ */+export function useRealtimeRevalidator() {+ const revalidator = useRevalidator();+ const submitting = useFetchers().some((f) => f.state === "submitting");+ const submittingRef = useRef(submitting);+ submittingRef.current = submitting;+ const held = useRef(false);++ useEffect(() => {+ if (!submitting && held.current) {+ held.current = false;+ requestRevalidation(revalidator.revalidate);+ }+ }, [submitting, revalidator]);++ return useCallback(() => {+ if (submittingRef.current) {+ held.current = true;+ return;+ }+ requestRevalidation(revalidator.revalidate);+ }, [revalidator]);+}++/**+ * Calls `onChange` for each change to `table` in the company, and with `null`+ * after a reconnect (nothing is replayed, so the caller catches up).+ */+export function useTableChanges({+ companyId,+ table,+ enabled = true,+ onChange+}: {+ companyId: string;+ table: RealtimeTable;+ enabled?: boolean;+ onChange: (change: BroadcastChange | null) => void;+}) {+ useTopic(companyTopic(companyId, table), onChange, enabled);+}++/**+ * Reloads the page's data when `table` changes in the company. A burst of+ * changes inside `debounceMs` is one reload.+ */+export function useRealtimeTable({+ companyId,+ table,+ filter,+ debounceMs = DEFAULT_DEBOUNCE_MS,+ enabled = true+}: {+ companyId: string;+ table: RealtimeTable;+ /**+ * `id=eq.<id>`, `id=in.(<ids>)`, or the same on a `<name>Id` column+ * (`jobId=eq.<id>`). A filter on any other column is ignored.+ */+ filter?: string;+ debounceMs?: number;+ enabled?: boolean;+}) {+ const revalidate = useRealtimeRevalidator();+ const timeout = useRef<ReturnType<typeof setTimeout> | null>(null);+ const waitingSince = useRef<number | null>(null);++ useEffect(+ () => () => {+ if (timeout.current) clearTimeout(timeout.current);+ },+ []+ );++ useTableChanges({+ companyId,+ table,+ enabled,+ onChange: (change) => {+ if (change && !matchesFilter(filter, change)) return;+ if (timeout.current) clearTimeout(timeout.current);+ waitingSince.current ??= performance.now();+ const waited = performance.now() - waitingSince.current;+ timeout.current = setTimeout(+ () => {+ waitingSince.current = null;+ invalidateLoaders();+ revalidate();+ },+ Math.max(0, Math.min(debounceMs, MAX_WAIT_MS - waited))+ );+ }+ });+}++function TableSubscription(props: {+ companyId: string;+ table: RealtimeTable;+ filter?: string;+}) {+ useRealtimeTable(props);+ return null;+}++/**+ * Keeps the matched routes live: each route names the tables it shows in+ * `handle.realtime`, and this subscribes to them for as long as it is matched.+ * An entry `{ table, column, param }` follows only the rows whose `column` is+ * the route's `param` (a job page: its own operations, not every job's), and+ * `{ table, filter }` builds the filter from the route's loader data.+ * It also owns every realtime channel of the page (see "One channel per topic"):+ * nothing is delivered to any listener unless this is mounted.+ * It also follows the company's reference lists, which are read through cached+ * `api+` loaders rather than a matched route. Render it once, in the shell.+ */+export function RouteRealtime({ companyId }: { companyId: string }) {+ const matches = useMatches();+ const tables = useMemo(() => {+ const followed = new Map<+ string,+ { table: RealtimeTable; filter?: string }+ >();+ for (const match of matches) {+ const entries =+ (match.handle as { realtime?: RouteRealtimeTable[] } | undefined)+ ?.realtime ?? [];+ for (const entry of entries) {+ if (typeof entry === "string") {+ followed.set(entry, { table: entry });+ continue;+ }+ let filter: string | undefined | false;+ if ("filter" in entry) {+ filter = entry.filter({+ params: match.params,+ data: match.loaderData ?? match.data+ });+ } else {+ const value = match.params[entry.param];+ filter = value ? `${entry.column}=eq.${value}` : undefined;+ }+ if (filter === false) continue;+ followed.set(`${entry.table}:${filter ?? ""}`, {+ table: entry.table,+ filter+ });+ }+ }+ return [...followed.entries()].sort(([a], [b]) => a.localeCompare(b));+ }, [matches]);++ const timeout = useRef<ReturnType<typeof setTimeout> | null>(null);+ useEffect(+ () => () => {+ if (timeout.current) clearTimeout(timeout.current);+ },+ []+ );+ useTopic(`company:${companyId}:reference`, (change) => {+ if (!change) {+ invalidateLoaders();+ return;+ }+ if (timeout.current) clearTimeout(timeout.current);+ timeout.current = setTimeout(invalidateLoaders, DEFAULT_DEBOUNCE_MS);+ });++ return (+ <>+ {tables.map(([key, { table, filter }]) => (+ <TableSubscription+ key={key}+ companyId={companyId}+ table={table}+ filter={filter}+ />+ ))}+ <TopicChannels />+ </>+ );+}diff --git a/packages/react/src/hooks/useRealtimeChannel.ts b/packages/query/src/useRealtimeChannel.tssimilarity index 83%rename from packages/react/src/hooks/useRealtimeChannel.tsrename to packages/query/src/useRealtimeChannel.tsindex 43265bba15..588561186c 100644--- a/packages/react/src/hooks/useRealtimeChannel.ts+++ b/packages/query/src/useRealtimeChannel.ts@@ -4,14 +4,15 @@import { NODE_ENV } from "@carbon/env";import { getLogger } from "@carbon/logger";+import { toast, useCarbon } from "@carbon/react";import type { RealtimeChannel, SupabaseClient } from "@supabase/supabase-js";import { REALTIME_SUBSCRIBE_STATES } from "@supabase/supabase-js";import { useCallback, useEffect, useRef } from "react";-import { useCarbon } from "../CarbonContext";-import { toast } from "../Toast";const log = getLogger("react", "realtime-channel");+const RECONNECT_AFTER_HIDDEN_MS = 10_000;+function formatSubscribeErr(err: unknown): string {if (err == null) return "No error details";if (typeof err === "string") return err.trim() || "No error details";@@ -36,6 +37,16 @@ interface UseRealtimeChannelOptions<TDeps extends any[]> {) => RealtimeChannel;enabled?: boolean;dependencies?: TDeps;+ /**+ * Join a private channel: Realtime checks the `realtime.messages` policies+ * for this topic once, at join. Every broadcast topic is private.+ */+ private?: boolean;+ /**+ * Called on each successful join. `isReconnect` is true after the first: no+ * message is replayed, so the caller catches up on what it missed.+ */+ onSubscribed?: (isReconnect: boolean) => void;/** When true, CHANNEL_ERROR / TIMED_OUT open a toast. Defaults to true in dev, false in prod. */notifyOnSubscribeError?: boolean;}@@ -48,6 +59,8 @@ export const useRealtimeChannel = <TDeps extends any[]>(setup,enabled = true,dependencies = [],+ private: isPrivate = false,+ onSubscribed,notifyOnSubscribeError = NODE_ENV === "development"} = options;const channelRef = useRef<RealtimeChannel | null>(null);@@ -59,6 +72,9 @@ export const useRealtimeChannel = <TDeps extends any[]>(const isSilentReconnectRef = useRef(false);// Updated each effect run so the retry timer always calls the latest subscribe closure.const doSubscribeRef = useRef<() => Promise<void>>(() => Promise.resolve());+ const hasSubscribedRef = useRef(false);+ const onSubscribedRef = useRef(onSubscribed);+ onSubscribedRef.current = onSubscribed;const { carbon, isRealtimeAuthSet } = useCarbon();// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration@@ -109,7 +125,9 @@ export const useRealtimeChannel = <TDeps extends any[]>(}try {- const channel = carbon.channel(topic);+ const channel = isPrivate+ ? carbon.channel(topic, { config: { private: true } })+ : carbon.channel(topic);const configuredChannel = memoSetup(channel,carbon,@@ -120,6 +138,8 @@ export const useRealtimeChannel = <TDeps extends any[]>(configuredChannel.subscribe(async (status, err) => {if (status === REALTIME_SUBSCRIBE_STATES.SUBSCRIBED) {retryCountRef.current = 0;+ onSubscribedRef.current?.(hasSubscribedRef.current);+ hasSubscribedRef.current = true;// Dismiss any lingering disconnect toast — reconnect succeeded.if (lastErrorToastIdRef.current != null) {toast.dismiss(lastErrorToastIdRef.current);@@ -193,6 +213,7 @@ export const useRealtimeChannel = <TDeps extends any[]>(// Keep ref up-to-date so retry timers always call the latest closure.doSubscribeRef.current = doSubscribe;+ hasSubscribedRef.current = false;void doSubscribe();const forceReconnect = (silent: boolean) => {@@ -207,8 +228,23 @@ export const useRealtimeChannel = <TDeps extends any[]>(});};+ // A tab that was hidden for long may hold a dead socket, so it reconnects.+ // A glance at another tab does not: every reconnect reloads the page's+ // data, since nothing is replayed.+ let hiddenAt: number | null = null;const handleVisibilityChange = () => {- if (document.visibilityState === "visible") forceReconnect(true);+ if (document.visibilityState !== "visible") {+ hiddenAt = performance.now();+ return;+ }+ const hiddenFor = hiddenAt === null ? 0 : performance.now() - hiddenAt;+ hiddenAt = null;+ if (+ hiddenFor >= RECONNECT_AFTER_HIDDEN_MS ||+ channelRef.current?.state !== "joined"+ ) {+ forceReconnect(true);+ }};const handleOnline = () => forceReconnect(true);@@ -235,6 +271,7 @@ export const useRealtimeChannel = <TDeps extends any[]>(isRealtimeAuthSet,enabled,topic,+ isPrivate,memoSetup,notifyOnSubscribeError// teardown/doSubscribe are NOT in dependencies - defined inlinediff --git a/packages/query/tsconfig.json b/packages/query/tsconfig.jsonnew file mode 100644index 0000000000..0da6e2cbd0--- /dev/null+++ b/packages/query/tsconfig.json@@ -0,0 +1,5 @@+{+ "include": ["src"],+ "exclude": ["node_modules"],+ "extends": "@carbon/config/tsconfig/react-library.json"+}diff --git a/packages/query/vitest.config.ts b/packages/query/vitest.config.tsnew file mode 100644index 0000000000..c95802b144--- /dev/null+++ b/packages/query/vitest.config.ts@@ -0,0 +1,5 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++export { default } from "@carbon/config/vitest";diff --git a/packages/react/package.json b/packages/react/package.jsonindex 4955dbf647..381cab6f05 100644--- a/packages/react/package.json+++ b/packages/react/package.json@@ -6,7 +6,6 @@"@carbon/content": "workspace:*","@carbon/logger": "workspace:*","@carbon/tiptap": "workspace:*",- "@nanostores/react": "catalog:","@carbon/utils": "workspace:*","@base-ui/react": "1.6.0","@radix-ui/react-accordion": "1.2.12",@@ -75,7 +74,6 @@"intl-parse-accept-language": "catalog:","is-hotkey": "0.2.0","nanoid": "catalog:",- "nanostores": "catalog:","nprogress": "0.2.0","react-aria-components": "1.0.1","react-colorful": "5.6.1",diff --git a/packages/react/src/hooks/index.ts b/packages/react/src/hooks/index.tsindex 3541b4d715..a0ffffb8ff 100644--- a/packages/react/src/hooks/index.ts+++ b/packages/react/src/hooks/index.ts@@ -22,12 +22,10 @@ import {useOptimisticMode} from "./useMode";import useMount from "./useMount";-import { useNanoStore } from "./useNanoStore";import { useNProgress } from "./useNProgress";import { useOptimisticLocation } from "./useOptimisticLocation";import useOutsideClick from "./useOutsideClick";import { usePlan } from "./usePlan";-import { useRealtimeChannel } from "./useRealtimeChannel";import { useRouteData } from "./useRouteData";import type { Shortcut, ShortcutDefinition } from "./useShortcutKeys";import { useShortcutKeyMap, useShortcutKeys } from "./useShortcutKeys";@@ -53,13 +51,11 @@ export {useIdle,useModePreference,useMount,- useNanoStore,useNProgress,useOptimisticLocation,useOptimisticMode,useOutsideClick,usePlan,- useRealtimeChannel,useRouteData,useShortcutKeyMap,useShortcutKeys,diff --git a/packages/react/src/hooks/useHydrated.ts b/packages/react/src/hooks/useHydrated.tsindex 784d35aafc..ce65acd1de 100644--- a/packages/react/src/hooks/useHydrated.ts+++ b/packages/react/src/hooks/useHydrated.ts@@ -2,17 +2,15 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { useState } from "react";-import useMount from "./useMount";+import { useSyncExternalStore } from "react";-let hydrating = true;+const subscribe = () => () => {};/*** Return a boolean indicating if the JS has been hydrated already.* When doing Server-Side Rendering, the result will always be false.- * When doing Client-Side Rendering, the result will always be false on the- * first render and true from then on. Even if a new component renders it will- * always start with true.+ * While a component hydrates, the result is false; it is true from then on.+ * A component that mounts after hydration starts with true.** Example: Disable a button that needs JS to work.* ```tsx@@ -25,12 +23,14 @@ let hydrating = true;* ```*/export default function useHydrated() {- let [hydrated, setHydrated] = useState(() => !hydrating);-- useMount(() => {- hydrating = false;- setHydrated(true);- });-- return hydrated;+ // The server snapshot is what React reads while it hydrates THIS component,+ // whenever that happens. A page hydrates in pieces (each Suspense boundary on+ // its own), so a flag flipped by the first mount is already true when a later+ // piece hydrates: it then renders its client-only content against the+ // server's fallback, and React discards the server-rendered page.+ return useSyncExternalStore(+ subscribe,+ () => true,+ () => false+ );}diff --git a/packages/react/src/hooks/useNanoStore.ts b/packages/react/src/hooks/useNanoStore.tsdeleted file mode 100644index b824ee4bbe..0000000000--- a/packages/react/src/hooks/useNanoStore.ts+++ /dev/null@@ -1,24 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-only-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,-// including ports, remain AGPLv3; serving them over a network requires releasing their source.--import { useStore } from "@nanostores/react";-import type { WritableAtom } from "nanostores";-import { useCallback } from "react";--export function useNanoStore<T>(atom: WritableAtom<T>, idbKey?: string) {- const value = useStore(atom);-- const set = useCallback(- (value: T | ((current: T) => T), initial = false) => {- if (typeof value === "function") {- atom.set((value as (current: T) => T)(atom.get()));- } else {- atom.set(value);- }- },- [atom]- );-- return [value, set] as const;-}diff --git a/packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap b/packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snapindex 28904d094f..ac93e2730e 100644--- a/packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap+++ b/packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap@@ -105,6 +105,12 @@ exports[`server function permissions > match the reviewed manifest 1`] = `},},},+ "finalize-purchasing-rfq": {+ "create": "purchasing",+ },+ "finalize-supplier-quote": {+ "create": "purchasing",+ },"get-method": {"update": "production",},diff --git a/packages/server-functions/src/finalize-purchasing-rfq/index.ts b/packages/server-functions/src/finalize-purchasing-rfq/index.tsnew file mode 100644index 0000000000..7e5826ec17--- /dev/null+++ b/packages/server-functions/src/finalize-purchasing-rfq/index.ts@@ -0,0 +1,194 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { selectRows } from "@carbon/database/rows";+import { getNextSequence } from "@carbon/database/sequence";+import { datetime } from "@carbon/utils";+import { z } from "zod";+import { defineServerFn } from "../define-server-fn";+import { InvalidInputError, NotFoundError } from "../errors";++export const finalizePurchasingRfqInput = z.object({+ rfqId: z.string()+});++const ITEM_TYPES = [+ "Part",+ "Material",+ "Tool",+ "Consumable",+ "Service"+] as const;++export type FinalizedSupplierQuote = {+ id: string;+ supplierQuoteId: string;+ supplierId: string;+ externalLinkId: string;+};++/**+ * Sends a purchasing RFQ out: one Draft supplier quote per RFQ supplier, each+ * with its share link and a line per RFQ line that names an item, then the RFQ+ * is marked Requested. One transaction — a failure leaves no quotes behind,+ * and only a Draft RFQ is finalized, so a repeated request creates nothing.+ */+const finalizePurchasingRfq = defineServerFn({+ name: "finalize-purchasing-rfq",+ input: finalizePurchasingRfqInput,+ permissions: { create: "purchasing" },+ async run({ db, companyId, userId }, { rfqId }) {+ const quotes = await db.transaction().execute(async (trx) => {+ // Locked: a second submit waits here, then finds the RFQ Requested.+ const rfq = await trx+ .selectFrom("purchasingRfq")+ .select(["id", "status"])+ .where("id", "=", rfqId)+ .where("companyId", "=", companyId)+ .forUpdate()+ .executeTakeFirst();+ if (!rfq) throw new NotFoundError("RFQ not found");+ if (rfq.status !== "Draft") {+ throw new InvalidInputError(+ `Only a draft RFQ can be finalized; this one is ${rfq.status}`+ );+ }++ const suppliers = await trx+ .selectFrom("purchasingRfqSupplier")+ .select("supplierId")+ .where("purchasingRfqId", "=", rfqId)+ .where("companyId", "=", companyId)+ .orderBy("createdAt")+ .orderBy("id")+ .execute();+ if (suppliers.length === 0) {+ throw new InvalidInputError("No suppliers found for this RFQ");+ }++ const lines = await selectRows(+ trx,+ "purchasingRfqLines",+ { purchasingRfqId: rfqId, companyId },+ { orderBy: ["order"] }+ );+ if (lines.length === 0) {+ throw new InvalidInputError("No line items found for this RFQ");+ }+ // supplierQuoteLine.itemId is NOT NULL+ const quotableLines = lines.flatMap((line) =>+ line.itemId ? [{ ...line, itemId: line.itemId }] : []+ );++ const created: FinalizedSupplierQuote[] = [];+ for (const { supplierId } of suppliers) {+ const supplierQuoteId = await getNextSequence(+ trx,+ "supplierQuote",+ companyId+ );+ const interaction = await trx+ .insertInto("supplierInteraction")+ .values({ companyId, supplierId })+ .returning("id")+ .executeTakeFirstOrThrow();+ const now = datetime.timestamp();+ const quote = await trx+ .insertInto("supplierQuote")+ .values({+ supplierQuoteId,+ supplierId,+ supplierInteractionId: interaction.id,+ status: "Draft",+ exchangeRate: 1,+ exchangeRateUpdatedAt: now,+ quotedDate: now,+ supplierQuoteType: "Purchase",+ companyId,+ createdBy: userId,+ updatedBy: userId+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ const externalLink = await trx+ .insertInto("externalLink")+ .values({+ documentType: "SupplierQuote",+ documentId: quote.id,+ supplierId,+ companyId+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ await trx+ .updateTable("supplierQuote")+ .set({ externalLinkId: externalLink.id })+ .where("id", "=", quote.id)+ .where("companyId", "=", companyId)+ .execute();++ if (quotableLines.length > 0) {+ await trx+ .insertInto("supplierQuoteLine")+ .values(+ quotableLines.map((line, index) => ({+ supplierQuoteId: quote.id,+ supplierQuoteLineType: ITEM_TYPES.some(+ (type) => type === line.itemType+ )+ ? (line.itemType as string)+ : "Part",+ itemId: line.itemId,+ description: line.description ?? "",+ quantity: line.quantity ?? [1],+ inventoryUnitOfMeasureCode:+ line.inventoryUnitOfMeasureCode ?? "EA",+ purchaseUnitOfMeasureCode:+ line.purchaseUnitOfMeasureCode ?? "EA",+ conversionFactor: line.conversionFactor ?? 1,+ sortOrder: index + 1,+ companyId,+ createdBy: userId+ }))+ )+ .execute();+ }++ await trx+ .insertInto("purchasingRfqToSupplierQuote")+ .values({+ purchasingRfqId: rfqId,+ supplierQuoteId: quote.id,+ companyId+ })+ .execute();++ created.push({+ id: quote.id,+ supplierQuoteId,+ supplierId,+ externalLinkId: externalLink.id+ });+ }++ await trx+ .updateTable("purchasingRfq")+ .set({+ status: "Requested",+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ .where("id", "=", rfqId)+ .where("companyId", "=", companyId)+ .execute();++ return created;+ });++ return { quotes };+ }+});++export default finalizePurchasingRfq;diff --git a/packages/server-functions/src/finalize-purchasing-rfq/purchasing-finalize.test.ts b/packages/server-functions/src/finalize-purchasing-rfq/purchasing-finalize.test.tsnew file mode 100644index 0000000000..e9b521ab04--- /dev/null+++ b/packages/server-functions/src/finalize-purchasing-rfq/purchasing-finalize.test.ts@@ -0,0 +1,244 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { sql } from "kysely";+import { expect } from "vitest";+import finalizeSupplierQuote from "../finalize-supplier-quote";+import {+ connectLocalTestDatabase,+ databaseTest+} from "../local-database-test-fixture";+import { ServerFnContext } from "../server-fn-context";+import finalizePurchasingRfq from ".";++// One company with two suppliers, one bought part, a Draft RFQ for it and a+// supplier quote with two price breaks (purchase unit = 2 inventory units).+async function fixture() {+ const db = await connectLocalTestDatabase();+ const p = `pftest-${crypto.randomUUID().replaceAll("-", "").slice(0, 12)}`;+ const companyId = `${p}-company`;+ const ids = {+ rfq: `${p}-rfq`,+ quote: `${p}-quote`,+ quoteLine: `${p}-quote-line`,+ item: `${p}-item`,+ supplier: `${p}-s1`+ };++ await db.transaction().execute(async (trx) => {+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(trx);+ await sql`+ INSERT INTO "companyGroup" (id, name, "createdBy") VALUES (${`${p}-group`}, ${p}, 'system');+ `.execute(trx);+ await sql`+ INSERT INTO "company" (id, name, "companyGroupId", "baseCurrencyCode")+ VALUES (${companyId}, ${p}, ${`${p}-group`}, 'USD')+ `.execute(trx);+ await sql`+ INSERT INTO "sequence" ("table", name, prefix, "companyId")+ VALUES ('supplierQuote', 'Supplier quote', 'PFT-', ${companyId})+ `.execute(trx);+ await sql`+ INSERT INTO "supplier" (id, name, "readableId", "companyId", "createdBy") VALUES+ (${ids.supplier}, 'One', 'S1', ${companyId}, 'system'),+ (${`${p}-s2`}, 'Two', 'S2', ${companyId}, 'system')+ `.execute(trx);+ await sql`+ INSERT INTO "unitOfMeasure" (code, name, "companyId", "createdBy")+ VALUES ('EA', 'Each', ${companyId}, 'system')+ `.execute(trx);+ await sql`+ INSERT INTO "item" (id, "readableId", name, type, "replenishmentSystem", "defaultMethodType",+ "itemTrackingType", "unitOfMeasureCode", "companyId", "createdBy")+ VALUES (${ids.item}, 'P-1', 'Part', 'Part', 'Buy', 'Pull from Inventory', 'Inventory', 'EA',+ ${companyId}, 'system')+ `.execute(trx);+ await sql`+ INSERT INTO "purchasingRfq" (id, "rfqId", "rfqDate", "companyId", "createdBy")+ VALUES (${ids.rfq}, 'RFQ-T', '2026-10-01', ${companyId}, 'system')+ `.execute(trx);+ await sql`+ INSERT INTO "purchasingRfqSupplier" ("purchasingRfqId", "supplierId", "companyId", "createdBy") VALUES+ (${ids.rfq}, ${ids.supplier}, ${companyId}, 'system'),+ (${ids.rfq}, ${`${p}-s2`}, ${companyId}, 'system')+ `.execute(trx);+ await sql`+ INSERT INTO "purchasingRfqLine" (id, "purchasingRfqId", "itemId", description, quantity,+ "purchaseUnitOfMeasureCode", "inventoryUnitOfMeasureCode", "companyId", "createdBy")+ VALUES (${`${p}-rfq-line`}, ${ids.rfq}, ${ids.item}, 'Part', '{1,10}', 'EA', 'EA', ${companyId}, 'system')+ `.execute(trx);+ await sql`+ INSERT INTO "supplierInteraction" (id, "companyId", "supplierId")+ VALUES (${`${p}-interaction`}, ${companyId}, ${ids.supplier})+ `.execute(trx);+ await sql`+ INSERT INTO "supplierQuote" (id, "supplierQuoteId", "supplierId", "supplierInteractionId", status, "companyId", "createdBy")+ VALUES (${ids.quote}, 'PFT-X', ${ids.supplier}, ${`${p}-interaction`}, 'Draft', ${companyId}, 'system')+ `.execute(trx);+ await sql`+ INSERT INTO "supplierQuoteLine" (id, "supplierQuoteId", "itemId", description, quantity,+ "conversionFactor", "companyId", "createdBy")+ VALUES (${ids.quoteLine}, ${ids.quote}, ${ids.item}, 'Part', '{1,10}', 2, ${companyId}, 'system')+ `.execute(trx);+ await sql`+ INSERT INTO "supplierQuoteLinePrice" ("supplierQuoteId", "supplierQuoteLineId", quantity,+ "supplierUnitPrice", "leadTime", "companyId", "createdBy") VALUES+ (${ids.quote}, ${ids.quoteLine}, 1, 10, 5, ${companyId}, 'system'),+ (${ids.quote}, ${ids.quoteLine}, 10, 8, 5, ${companyId}, 'system')+ `.execute(trx);+ });++ return {+ db,+ companyId,+ ids,+ ctx: ServerFnContext.system({ db, companyId, userId: "system" }),+ async cleanup() {+ await db.transaction().execute(async (trx) => {+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(trx);+ await trx.deleteFrom("company").where("id", "=", companyId).execute();+ await trx+ .deleteFrom("companyGroup")+ .where("id", "=", `${p}-group`)+ .execute();+ await sql`DROP TABLE IF EXISTS ${sql.id(`searchIndex_${companyId}`)}`.execute(+ trx+ );+ });+ await db.destroy();+ }+ };+}++const count = async (+ f: Awaited<ReturnType<typeof fixture>>,+ table: "supplierQuote" | "supplierQuoteLine" | "supplierPartPrice"+) =>+ Number(+ (+ await f.db+ .selectFrom(table)+ .select((eb) => eb.fn.countAll().as("n"))+ .where("companyId", "=", f.companyId)+ .executeTakeFirstOrThrow()+ ).n+ );++databaseTest("an RFQ is finalized once", async () => {+ const f = await fixture();+ try {+ const quotesBefore = await count(f, "supplierQuote");+ const first = await finalizePurchasingRfq(f.ctx, { rfqId: f.ids.rfq });+ expect(first.error).toBeNull();+ expect(first.data?.quotes).toHaveLength(2);+ expect(await count(f, "supplierQuote")).toBe(quotesBefore + 2);+ // One line per quote for the RFQ's one line, plus the fixture quote's own.+ expect(await count(f, "supplierQuoteLine")).toBe(3);++ const rfq = await f.db+ .selectFrom("purchasingRfq")+ .select("status")+ .where("id", "=", f.ids.rfq)+ .executeTakeFirstOrThrow();+ expect(rfq.status).toBe("Requested");++ // A repeated request finds it Requested and creates nothing.+ const second = await finalizePurchasingRfq(f.ctx, { rfqId: f.ids.rfq });+ expect(second.error?.status).toBe(400);+ expect(await count(f, "supplierQuote")).toBe(quotesBefore + 2);+ } finally {+ await f.cleanup();+ }+});++databaseTest("another company's RFQ is not found", async () => {+ const f = await fixture();+ try {+ const other = ServerFnContext.system({+ db: f.db,+ companyId: "another-company",+ userId: "system"+ });+ const result = await finalizePurchasingRfq(other, { rfqId: f.ids.rfq });+ expect(result.error?.status).toBe(404);+ expect(await count(f, "supplierQuote")).toBe(1);+ } finally {+ await f.cleanup();+ }+});++databaseTest(+ "a supplier quote's prices become the supplier's price list",+ async () => {+ const f = await fixture();+ try {+ const result = await finalizeSupplierQuote(f.ctx, {+ supplierQuoteId: f.ids.quote+ });+ expect(result.error).toBeNull();++ const part = await f.db+ .selectFrom("supplierPart")+ .select(["id", "unitPrice", "minimumOrderQuantity"])+ .where("itemId", "=", f.ids.item)+ .where("supplierId", "=", f.ids.supplier)+ .executeTakeFirstOrThrow();+ // The lowest quoted price, per inventory unit (2 to a purchase unit).+ expect(Number(part.unitPrice)).toBe(4);+ expect(Number(part.minimumOrderQuantity)).toBe(10);++ const breaks = await f.db+ .selectFrom("supplierPartPrice")+ .select(["quantity", "unitPrice", "leadTime", "sourceDocumentId"])+ .where("supplierPartId", "=", part.id)+ .orderBy("quantity")+ .execute();+ expect(+ breaks.map((b) => [Number(b.quantity), Number(b.unitPrice)])+ ).toEqual([+ [1, 5],+ [10, 4]+ ]);+ expect(breaks.every((b) => b.sourceDocumentId === f.ids.quote)).toBe(+ true+ );++ // Finalizing again rewrites the same breaks rather than adding more.+ await finalizeSupplierQuote(f.ctx, { supplierQuoteId: f.ids.quote });+ expect(await count(f, "supplierPartPrice")).toBe(2);+ } finally {+ await f.cleanup();+ }+ }+);++databaseTest(+ "a line without a price and lead time finalizes nothing",+ async () => {+ const f = await fixture();+ try {+ await f.db+ .updateTable("supplierQuoteLinePrice")+ .set({ leadTime: 0 })+ .where("supplierQuoteId", "=", f.ids.quote)+ .execute();++ const result = await finalizeSupplierQuote(f.ctx, {+ supplierQuoteId: f.ids.quote+ });+ expect(result.error?.status).toBe(400);+ expect(result.error?.message).toContain("P-1");++ const quote = await f.db+ .selectFrom("supplierQuote")+ .select("status")+ .where("id", "=", f.ids.quote)+ .executeTakeFirstOrThrow();+ expect(quote.status).toBe("Draft");+ expect(await count(f, "supplierPartPrice")).toBe(0);+ } finally {+ await f.cleanup();+ }+ }+);diff --git a/packages/server-functions/src/finalize-supplier-quote/index.ts b/packages/server-functions/src/finalize-supplier-quote/index.tsnew file mode 100644index 0000000000..c779bd66a7--- /dev/null+++ b/packages/server-functions/src/finalize-supplier-quote/index.ts@@ -0,0 +1,220 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { many, selectRows } from "@carbon/database/rows";+import { datetime, groupBy } from "@carbon/utils";+import { z } from "zod";+import { defineServerFn } from "../define-server-fn";+import { InvalidInputError, NotFoundError, ServerFnError } from "../errors";++export const finalizeSupplierQuoteInput = z.object({+ supplierQuoteId: z.string()+});++/**+ * Marks a supplier quote Active and copies its prices into the supplier's+ * price list, in one transaction: a supplier part per quoted item (created+ * when the supplier has none), one price break per quoted quantity, and the+ * lowest quoted price as the part's own.+ */+const finalizeSupplierQuote = defineServerFn({+ name: "finalize-supplier-quote",+ input: finalizeSupplierQuoteInput,+ permissions: { create: "purchasing" },+ async run({ db, companyId, userId }, { supplierQuoteId }) {+ await db.transaction().execute(async (trx) => {+ const quote = await trx+ .selectFrom("supplierQuote")+ .select(["id", "supplierId"])+ .where("id", "=", supplierQuoteId)+ .where("companyId", "=", companyId)+ .executeTakeFirst();+ if (!quote) throw new NotFoundError("Supplier quote not found");+ if (!quote.supplierId) {+ throw new ServerFnError("Supplier quote has no supplier", 400);+ }+ const supplierId = quote.supplierId;++ const lines = await selectRows(+ trx,+ "supplierQuoteLine",+ { supplierQuoteId, companyId },+ {+ columns: [+ "id",+ "itemId",+ "supplierPartId",+ "purchaseUnitOfMeasureCode",+ "conversionFactor"+ ],+ orderBy: ["sortOrder", "id"]+ }+ );+ const prices = await many(trx, "supplierQuoteLinePrice", {+ supplierQuoteId,+ companyId+ });+ const pricesByLine = groupBy(+ prices.data,+ (price) => price.supplierQuoteLineId+ );++ // Every line needs one quantity with a price and a lead time: a price+ // list entry without either is worse than none.+ const unpriced = lines.find(+ (line) =>+ !(pricesByLine[line.id] ?? []).some(+ (price) => price.supplierUnitPrice && price.leadTime+ )+ );+ if (unpriced) {+ const item = unpriced.itemId+ ? await trx+ .selectFrom("item")+ .select("readableIdWithRevision")+ .where("id", "=", unpriced.itemId)+ .where("companyId", "=", companyId)+ .executeTakeFirst()+ : undefined;+ throw new InvalidInputError(+ `Line ${item?.readableIdWithRevision ?? unpriced.id} must have at least one quantity with price and lead time`+ );+ }++ await trx+ .updateTable("supplierQuote")+ .set({+ status: "Active",+ updatedAt: datetime.timestamp(),+ updatedBy: userId+ })+ .where("id", "=", supplierQuoteId)+ .where("companyId", "=", companyId)+ .execute();++ const pricedLines = lines.flatMap((line) => {+ const linePrices = pricesByLine[line.id] ?? [];+ return line.itemId && linePrices.length > 0+ ? [{ ...line, itemId: line.itemId, prices: linePrices }]+ : [];+ });+ if (pricedLines.length === 0) return;++ // An item the supplier already has a part for keeps that part as it is.+ await trx+ .insertInto("supplierPart")+ .values(+ pricedLines.map((line) => ({+ itemId: line.itemId,+ supplierId,+ supplierPartId: line.supplierPartId ?? undefined,+ supplierUnitOfMeasureCode:+ line.purchaseUnitOfMeasureCode ?? undefined,+ conversionFactor: line.conversionFactor ?? 1,+ companyId,+ createdBy: userId+ }))+ )+ .onConflict((oc) =>+ oc.columns(["itemId", "supplierId", "companyId"]).doNothing()+ )+ .execute();++ const supplierParts = await trx+ .selectFrom("supplierPart")+ .select(["id", "itemId"])+ .where("supplierId", "=", supplierId)+ .where("companyId", "=", companyId)+ .where("itemId", "in", [+ ...new Set(pricedLines.map((line) => line.itemId))+ ])+ .execute();+ const supplierPartIdByItem = new Map(+ supplierParts.map((part) => [part.itemId, part.id])+ );++ // Keyed by (part, quantity): when two lines quote one item at one+ // quantity the later line wins, as it did when these were written in turn.+ const priceBreaks = new Map<+ string,+ {+ supplierPartId: string;+ quantity: number;+ unitPrice: number;+ leadTime: number;+ }+ >();+ const updatedAt = datetime.timestamp();++ for (const line of pricedLines) {+ const supplierPartId = supplierPartIdByItem.get(line.itemId);+ if (!supplierPartId) {+ throw new ServerFnError("Failed to create supplier part", 500);+ }+ const conversionFactor = line.conversionFactor ?? 1;++ for (const price of line.prices) {+ if (!price.supplierUnitPrice) continue;+ const quantity = price.quantity ?? 1;+ priceBreaks.set(`${supplierPartId}:${quantity}`, {+ supplierPartId,+ quantity,+ unitPrice: (price.unitPrice ?? 0) / conversionFactor,+ leadTime: price.leadTime ?? 0+ });+ }++ const bestPrice = line.prices+ .filter((price) => price.unitPrice != null && price.unitPrice !== 0)+ .sort(+ (a, b) => (a.unitPrice ?? Infinity) - (b.unitPrice ?? Infinity)+ )[0];+ if (bestPrice) {+ await trx+ .updateTable("supplierPart")+ .set({+ unitPrice: (bestPrice.unitPrice ?? 0) / conversionFactor,+ minimumOrderQuantity: bestPrice.quantity ?? 1+ })+ .where("id", "=", supplierPartId)+ .where("companyId", "=", companyId)+ .execute();+ }+ }++ if (priceBreaks.size > 0) {+ await trx+ .insertInto("supplierPartPrice")+ .values(+ [...priceBreaks.values()].map((priceBreak) => ({+ ...priceBreak,+ sourceType: "Quote" as const,+ sourceDocumentId: supplierQuoteId,+ companyId,+ createdBy: userId,+ updatedBy: userId,+ updatedAt+ }))+ )+ .onConflict((oc) =>+ oc.columns(["supplierPartId", "quantity"]).doUpdateSet((eb) => ({+ unitPrice: eb.ref("excluded.unitPrice"),+ leadTime: eb.ref("excluded.leadTime"),+ sourceType: eb.ref("excluded.sourceType"),+ sourceDocumentId: eb.ref("excluded.sourceDocumentId"),+ companyId: eb.ref("excluded.companyId"),+ createdBy: eb.ref("excluded.createdBy"),+ updatedBy: eb.ref("excluded.updatedBy"),+ updatedAt: eb.ref("excluded.updatedAt")+ }))+ )+ .execute();+ }+ });++ return { success: true };+ }+});++export default finalizeSupplierQuote;diff --git a/packages/server-functions/src/invoke.ts b/packages/server-functions/src/invoke.tsindex 5b185fca38..3d7d6dbca4 100644--- a/packages/server-functions/src/invoke.ts+++ b/packages/server-functions/src/invoke.ts@@ -19,6 +19,8 @@ const registry = {convert: () => import("./convert"),"correct-stock-movement": () => import("./correct-stock-movement"),create: () => import("./create"),+ "finalize-purchasing-rfq": () => import("./finalize-purchasing-rfq"),+ "finalize-supplier-quote": () => import("./finalize-supplier-quote"),"get-method": () => import("./get-method"),"import-csv": () => import("./import-csv"),issue: () => import("./issue"),diff --git a/packages/viewer/package.json b/packages/viewer/package.jsonindex ca44e2f818..d052504675 100644--- a/packages/viewer/package.json+++ b/packages/viewer/package.json@@ -6,7 +6,7 @@"@carbon/utils": "workspace:*","@react-three/drei": "9.122.0","@react-three/fiber": "8.18.0",- "@tanstack/react-query": "5.97.0",+ "@tanstack/react-query": "catalog:","occt-import-js": "0.0.23","react-icons": "catalog:","rhino3dm": "8.17.0",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b0df70d795..ee83219f4d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -60,9 +60,6 @@ catalogs:'@marsidev/react-turnstile':specifier: 1.5.0version: 1.5.0- '@nanostores/react':- specifier: 0.7.3- version: 0.7.3'@opentelemetry/api':specifier: 1.9.0version: 1.9.0@@ -153,6 +150,12 @@ catalogs:'@tailwindcss/vite':specifier: 4.3.0version: 4.3.0+ '@tanstack/react-query':+ specifier: 5.104.0+ version: 5.104.0+ '@tanstack/react-query-devtools':+ specifier: 5.104.0+ version: 5.104.0'@tiptap/core':specifier: 2.27.2version: 2.27.2@@ -252,9 +255,6 @@ catalogs:nanoid:specifier: 5.1.16version: 5.1.16- nanostores:- specifier: 0.9.5- version: 0.9.5nodemon:specifier: 3.1.14version: 3.1.14@@ -723,6 +723,9 @@ importers:'@carbon/printing':specifier: workspace:*version: link:../../packages/printing+ '@carbon/query':+ specifier: workspace:*+ version: link:../../packages/query'@carbon/react':specifier: workspace:*version: link:../../packages/react@@ -774,9 +777,6 @@ importers:'@monaco-editor/react':specifier: 4.7.0- '@nanostores/react':- specifier: 'catalog:'- version: 0.7.3([email protected])([email protected])'@orpc/openapi':specifier: 'catalog:'version: 1.15.0(@opentelemetry/[email protected])([email protected]([email protected]))([email protected])@@ -823,8 +823,8 @@ importers:specifier: 'catalog:'version: 2.117.2(@opentelemetry/[email protected])'@tanstack/react-query':- specifier: 5.97.0- version: 5.97.0([email protected])+ specifier: 'catalog:'+ version: 5.104.0([email protected])'@tanstack/react-table':specifier: 8.21.3@@ -927,9 +927,6 @@ importers:nanoid:specifier: 'catalog:'version: 5.1.16- nanostores:- specifier: 'catalog:'- version: 0.9.5non.geist:specifier: 'catalog:'version: 1.0.4@@ -1087,6 +1084,9 @@ importers:'@tailwindcss/vite':specifier: 'catalog:'version: 4.3.0([email protected])+ '@tanstack/react-query-devtools':+ specifier: 'catalog:'+ version: 5.104.0(@tanstack/[email protected]([email protected]))(@types/[email protected])([email protected])([email protected])'@types/d3':specifier: 7.4.3version: 7.4.3@@ -1198,6 +1198,9 @@ importers:'@carbon/printing':specifier: workspace:*version: link:../../packages/printing+ '@carbon/query':+ specifier: workspace:*+ version: link:../../packages/query'@carbon/react':specifier: workspace:*version: link:../../packages/react@@ -1243,9 +1246,6 @@ importers:'@lingui/vite-plugin':specifier: 'catalog:'version: 6.9.0(@babel/[email protected])(@lingui/[email protected](@babel/[email protected]))([email protected])([email protected])([email protected])([email protected])- '@nanostores/react':- specifier: 'catalog:'- version: 0.7.3([email protected])([email protected])'@react-aria/i18n':specifier: 'catalog:'@@ -1280,8 +1280,8 @@ importers:specifier: 'catalog:'version: 4.3.0([email protected])'@tanstack/react-query':- specifier: 5.97.0- version: 5.97.0([email protected])+ specifier: 'catalog:'+ version: 5.104.0([email protected])'@tiptap/core':specifier: 'catalog:'version: 2.27.2(@tiptap/[email protected])@@ -1357,9 +1357,6 @@ importers:nanoid:specifier: 'catalog:'version: 5.1.16- nanostores:- specifier: 'catalog:'- version: 0.9.5non.geist:specifier: 'catalog:'version: 1.0.4@@ -1436,6 +1433,9 @@ importers:'@react-aria/optimize-locales-plugin':specifier: 'catalog:'version: 2.0.2+ '@tanstack/react-query-devtools':+ specifier: 'catalog:'+ version: 5.104.0(@tanstack/[email protected]([email protected]))(@types/[email protected])([email protected])([email protected])'@types/react':specifier: 18.3.28version: 18.3.28@@ -3243,6 +3243,49 @@ importers:specifier: 'catalog:'version: 5.8.3+ packages/query:+ dependencies:+ '@carbon/database':+ specifier: workspace:*+ version: link:../database+ '@carbon/env':+ specifier: workspace:*+ version: link:../env+ '@carbon/logger':+ specifier: workspace:*+ version: link:../logger+ '@carbon/react':+ specifier: workspace:*+ version: link:../react+ '@carbon/utils':+ specifier: workspace:*+ version: link:../utils+ '@supabase/supabase-js':+ specifier: 'catalog:'+ version: 2.117.2(@opentelemetry/[email protected])+ '@tanstack/react-query':+ specifier: 'catalog:'+ version: 5.104.0([email protected])+ devDependencies:+ '@carbon/config':+ specifier: workspace:*+ version: link:../config+ '@types/react':+ specifier: 18.3.28+ version: 18.3.28+ react:+ specifier: 18.3.1+ version: 18.3.1+ react-router:+ specifier: 'catalog:'+ typescript:+ specifier: 'catalog:'+ version: 5.8.3+ vitest:+ specifier: 'catalog:'+ version: 4.1.6(@opentelemetry/[email protected])(@types/[email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+packages/react:dependencies:'@base-ui/react':@@ -3275,9 +3318,6 @@ importers:'@marsidev/react-turnstile':specifier: 'catalog:'- '@nanostores/react':- specifier: 'catalog:'- version: 0.7.3([email protected])([email protected])'@radix-ui/react-accordion':specifier: 1.2.12version: 1.2.12(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])@@ -3482,9 +3522,6 @@ importers:nanoid:specifier: 'catalog:'version: 5.1.16- nanostores:- specifier: 'catalog:'- version: 0.9.5nprogress:specifier: 0.2.0version: 0.2.0@@ -3911,8 +3948,8 @@ importers:specifier: 8.18.0version: 8.18.0(@types/[email protected])([email protected]([email protected]))([email protected])([email protected])'@tanstack/react-query':- specifier: 5.97.0- version: 5.97.0([email protected])+ specifier: 'catalog:'+ version: 5.104.0([email protected])occt-import-js:specifier: 0.0.23version: 0.0.23@@ -4485,6 +4522,11 @@ packages:resolution: {integrity: sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==}engines: {node: '>=0.1.90'}+ '@corvu/[email protected]':+ resolution: {integrity: sha512-Ox2kYyxy7NoXdKWdHeDEjZxClwzO4SKM8plAaVwmAJPxHMqA0rLOoAsa+hBDwRLpctf+ZRnAd/ykguuJidnaTA==}+ peerDependencies:+ solid-js: ^1.8+'@dagrejs/[email protected]':resolution: {integrity: sha512-5SEDlndt4W/LaVzPYJW+bSmSEZc9EzTf8rJ20WCKvjS5EAZAN0b+x0Yww7VMT4R3Wootkg+X9bUfUxazYw6Blw==}@@ -5641,6 +5683,16 @@ packages:'@juggle/[email protected]':resolution: {integrity: sha512-dfLbk+PwWvFzSxwk3n5ySL0hfBog779o8h68wK/7/APo/7cgyWp5jcXockbxdk5kFRkbeXWm4Fbi9FrdN381sA==}+ '@kobalte/[email protected]':+ resolution: {integrity: sha512-SBVB1lnvYbYt2x3t7fG0lo5fGLEbHQ6PII3NDPva8vD5e2v53On84ZVQiuIk0XI/55R4GQhden7Yem+R/XR8uQ==}+ peerDependencies:+ solid-js: ^1.9.8++ '@kobalte/[email protected]':+ resolution: {integrity: sha512-jRVXr+zsVHxzDXRoh+CDeXzvCsFJ6uiHhqqNQ26Cw9ZsZ3D6nqPUBt1gGVtj2ZPmRL3a9Uk1v8D1aJ8/I12Dow==}+ peerDependencies:+ solid-js: ^1.8.8+'@levischuck/[email protected]':resolution: {integrity: sha512-llBRm4dT4Z89aRsm6u2oEZ8tfwL/2l6BwpZ7JcyieouniDECM5AqNgr/y08zalEIvW3RSK4upYyybDcmjXqAow==}@@ -5885,13 +5937,6 @@ packages:peerDependencies:three: '>= 0.159.0'- '@nanostores/[email protected]':- resolution: {integrity: sha512-/XuLAMENRu/Q71biW4AZ4qmU070vkZgiQ28gaTSNRPm2SZF5zGAR81zPE1MaMB4SeOp6ZTst92NBaG75XSspNg==}- engines: {node: ^18.0.0 || >=20.0.0}- peerDependencies:- nanostores: ^0.9.0 || ^0.10.0 || ^0.11.0- react: 18.3.1-'@napi-rs/[email protected]':resolution: {integrity: sha512-V1c/WVw+NzH8vk7ZK/O8/nyBSCQimU8sfMsB/9qeSvdkGKNU7+mxy/bIF0gTgeBFmHpj30S4E9WHMSrxXGQuVQ==}engines: {node: '>= 10'}@@ -9719,6 +9764,71 @@ packages:'@socket.io/[email protected]':resolution: {integrity: sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==}+ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-5I0YJcTVYIWoMmgBSROBZGcz+ymhew/pGTg2dHW74BUjFKsV8Li4bOZYl0YAGP4mHw5o4UBd9/BEesqBci3wxw==}+ peerDependencies:+ solid-js: ^1.6.12++ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-zNadtyYBhJSOjXtogkGHmRxjGdz9KHc8sGGVAGlUABkE8BED2tbIZoxkwSqzOwde8OcUEH0bb5DLZUWIMvyBSA==}+ peerDependencies:+ solid-js: ^1.6.12++ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-B1zyFbsiTQvqPr+cuPCXO72sRuczG9Swncqk5P74NCGw1VE8qa/Ry9GlfI1e/VdeQYHjan+XkbE3rO2GW/qKew==}+ peerDependencies:+ solid-js: ^1.6.12++ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-pk49gPOq/UMRUJ+pTSrOfBiR8xJjRYHXIf1iR/jSnyQ/KroU+ZXhkZzavC7hvfp2vJeOTW5k2/HN0r3Q1VJ7Pw==}+ peerDependencies:+ solid-js: ^1.6.12++ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-MXXdvi2TSB6d+0N6ueA/HP1j/Kh9SEc4WdF1ZDMLwPagxW6pIHHSS9xbRO0RjqSVpNP4j0nxCWT1hx3CkJNhNA==}+ peerDependencies:+ solid-js: ^1.6.12++ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-bLjwIs6ZPu8NQnuw04sU3Zc8qKSpbc0umUU/O4SHf6oWOdO4+dHY8vb1T7C4b/Tg103+9WGr6sEE0+NFlbaB/A==}+ peerDependencies:+ solid-js: ^1.6.12++ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-9Fuu/EWBeGj+atGHRJp70HKhdfalmpjwxY8a32NZixdLNmfCJ45AfhLQNr6uOzETbbiMx4iCKlTrJ8KZCHC2Ww==}+ peerDependencies:+ solid-js: ^1.6.12++ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-TOIZa1VUfVJ+9nkCcRajw3U4t9vBOP1HxX1WHNTbXq32mXwlqTvUnC4CRIilohcryBkT9u2ZkhUDSHRTaGp55g==}+ peerDependencies:+ solid-js: ^1.6.12++ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-LgtVaVBtB7EbmS4+M0b8xY5Iq6pUWXBsIC4VgtrFKDGDdyCaDt88sHk0fUlx1Enxm/XZnZyLXJABRoa39RjJqA==}+ peerDependencies:+ solid-js: ^1.6.12++ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-PpQWR3TaTxHIJFbI9ZssYTM4Aa67g1vJIgps4TPhcXzHqqomrPAIveFC2FG7SDQoi9YQia8FVBjigELziJpfIg==}+ peerDependencies:+ solid-js: ^1.6.12++ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-gnHS0OmcdjeoHN9n7Khu8KNrOlRc8a2weETDt2YT6o1zeW/XtUC6Db3Q9pkMU/9cCKdEmN4b0a/41MKAHRhzWA==}+ peerDependencies:+ solid-js: ^1.6.12++ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-Ju0e+ZOD7hpOp7nptJimvDSZHWFvIvF9iBWMvuwt30smX7c5wmB8Kmc0AdDuv0wOTi06PQ1J5IrP1WJbH2yUBQ==}+ peerDependencies:+ solid-js: ^1.6.12++ '@solid-primitives/[email protected]':+ resolution: {integrity: sha512-ISSB5QX1qP2ynrheIpYwc4oKR5Ny4siNuUyf1qZniy+Il+p/PtDB0QK1Dnle8noiHpwRD3gpPdubOC3qI/Zamg==}+ peerDependencies:+ solid-js: ^1.6.12+'@standard-schema/[email protected]':resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}@@ -9960,11 +10070,25 @@ packages:peerDependencies:vite: 7.3.5- '@tanstack/[email protected]':- resolution: {integrity: sha512-QdpLP5VzVMgo4VtaPppRA2W04UFjIqX+bxke/ZJhE5cfd5UPkRzqIAJQt9uXkQJjqE8LBOMbKv7f8HCsZltXlg==}+ '@tanstack/[email protected]':+ resolution: {integrity: sha512-aPkUQctDzpXLSWhlx7jUDi3mInsI18xcnrK1hvIyIa88ab1ax88cACr7xU+BKMCGB4NZYNwh4SoNSEbv3RY2NA==}+ engines: {node: '>=20'}++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-JrC2r/JQlXt7khBSdUpsgxNvybzOg+aITa+ARRMlP2AFo93Y8vIqz077rp+e61mJetSZ0T6AJbwW1JHer1vrPQ==}- '@tanstack/[email protected]':- resolution: {integrity: sha512-y4So4eGcQoK2WVMAcDNZE9ofB/p5v1OlKvtc1F3uqHwrtifobT7q+ZnXk2mRkc8E84HKYSlAE9z6HXl2V0+ySQ==}+ '@tanstack/[email protected]':+ resolution: {integrity: sha512-snKyFLVFC5LuNoyUTpyqCD2Z8cRlCWrAeO3xub0nGi81IMz8YAUWq2Z+XdpGSGT7bCxqVdOHUjyiA3CtDuBjfQ==}++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-E3AfuGqrdyaamuRV3u8RFWQlkZxk7OQa9MJ3XLF9SEHFRHyTUnlHcAQ0hEpDYxNsNFKYrheiRpDKlYaG4vkt7g==}+ peerDependencies:+ '@tanstack/react-query': ^5.104.0+ '@types/react': 18.3.28+ react: 18.3.1++ '@tanstack/[email protected]':+ resolution: {integrity: sha512-e1TZmDCQnWIfiDVryIHeA6Idj+Lfx1hORLOhXS/l5wcgvtVD4yYqbTDl378sGQKIi2cSgb0TEMC9cKK8GGoJEw==}peerDependencies:react: 18.3.1@@ -11757,6 +11881,10 @@ packages:resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}engines: {node: '>=18'}+ resolution: {integrity: sha512-vePst2VLTSqPglW7Q98VwFpGiGpOHTyXIo81MO5VyLecA5zMbZw/P/V1vmwD1jksa2iJpn/YkDrJ3XhTfzUyhQ==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-es1U2+YTtzpwkxVLwAFdSpaIMyQaq0PBgm3YD1W3Qpsn1NAmO3KSgZfu+oGSWVu6NvLHoHCV/aYcsE5wiB7ALg==}@@ -12901,6 +13029,11 @@ packages:resolution: {integrity: sha512-b/ZCF6amfAUb7dJM/MxRs7AetQEahYzJ8PtgfrmEdtw6uyGOr+ZSGtgjFm6mfsBkxJ4d2W7kg+Nlqzqvn3Bc0w==}+ resolution: {integrity: sha512-U7veizMqxyKlM58+Z5j2ngJBH/r9siDmxpvNxSw0PylF6WQvrASJEZrxh1hidRBJc2jqoBVSyOban5u8m+6Rxg==}+ peerDependencies:+ csstype: ^3.0.10+resolution: {integrity: sha512-eAmLkjDjAFCVXg7A1unxHsLf961m6y17QFqXqAXGj/gVkKFrEICfStRfwUlGNfeCEjNRa32JEWOUTlYXPyyKvA==}engines: {node: '>=14'}@@ -14428,10 +14561,6 @@ packages:engines: {node: ^18 || >=20}hasBin: true- resolution: {integrity: sha512-Z+p+g8E7yzaWwOe5gEUB2Ox0rCEeXWYIZWmYvw/ajNYX8DlXdMvMDj8DWfM/subqPAcsf8l8Td4iAwO1DeIIRQ==}- engines: {node: ^16.0.0 || ^18.0.0 || >=20.0.0}-resolution: {integrity: sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==}engines: {node: '>= 0.6'}@@ -15857,6 +15986,16 @@ packages:resolution: {integrity: sha512-6a6dNqipzbCPlTFgztfNP2oG+IGcflMe/01zSzGrQcxGMKbIjOemBBD85pH92klWaJavAUWxAh9Z0aU28zxW6A==}deprecated: Rolling release, please update to 0.2.0+ resolution: {integrity: sha512-HXuLAX2pu/UByPpaeo/TaMfvMIi+1QqIoPJYCcAtU8QkVNwgR6MPlGuCQTErV1JwraaMbYaWVIBX7mppzGLATQ==}+ engines: {node: '>=10'}+ peerDependencies:+ seroval: ^1.0++ resolution: {integrity: sha512-rVQVWjjSvlINzaQPZH5JFqsqEsIWdTxY3iJZCnTL/5gQbXIRooVZKI60tVCkOVfzcRPejboxO2t0P89dg5mQaA==}+ engines: {node: '>=10'}+resolution: {integrity: sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==}engines: {node: '>= 0.8.0'}@@ -15986,6 +16125,25 @@ packages:resolution: {integrity: sha512-2Dd78bqzzjE6KPkD5fHZmDAKRNe3J15q+YHDrIsy9WEkqttc7GY+kT9OBLSMaPbQaEd0x1BjcmtMtXkfpc+T5A==}engines: {node: '>=10.2.0'}+ resolution: {integrity: sha512-EeiY2xfpZJqPLjXspVEKjAII4yv8NyG//NxZ3IpOFHdUNnnTyL0uJOeS9LWGvA7cFCz5y94cjFwYlmw5Luncsg==}++ resolution: {integrity: sha512-YM92o+jvpzX3XGaD4rLYmq/Kc2ZVh47GSCLEufHBFQQIurvZTs8SoGJxO8BJGNDxBKdcS8F3dYhW1SDXp4BNjA==}+ peerDependencies:+ solid-js: ^1.8++ resolution: {integrity: sha512-2PComVCDHaQN/5t7ogEqUYeHasritZKXZ8Sb/VLkl0Web8o9YhEwOo8LSujJEahvMlYCNyKt0zRJeHldOAeWZg==}+ peerDependencies:+ solid-js: ^1.8++ resolution: {integrity: sha512-iB72c9N5Kz9ykRqIXl0lQohOau4t0dhel9kjwFvx81UZJbVwaChMuBuyhiZmK24b8aKEK0w3uFM96ZxzcyZGdg==}+ engines: {node: '>=18.0.0', pnpm: '>=8.6.0'}+ peerDependencies:+ solid-js: ^1.6.12+resolution: {integrity: sha512-njQ4Hht92m0sMqqHVDL32V2Oun9W1+PHO9NDv9FHfJjT3JT22IG4Jpo3FPQy+mouRKCXFWO+r67v6MrHX2zeIA==}peerDependencies:@@ -16267,6 +16425,10 @@ packages:engines: {npm: '>=8'}hasBin: true+ resolution: {integrity: sha512-H+ue8Zo4vJmV2nRjpx86P35lzwDT3nItnIsocgumgr0hHMQ+ZGq5vrERg9kJBo5AWGmxZDhzDo+WVIJqkB0cGA==}+ engines: {node: '>=16'}+resolution: {integrity: sha512-KKNVtd6pCYgPIKU4cp2733HWYCpplQhddZLBUryaAHou723x+FRzQ5Df824Fj+IyyuiQTRoub4SnIFfIcrp70g==}engines: {node: '>=0.8.0'}@@ -18042,6 +18204,11 @@ snapshots:'@colors/[email protected]':optional: true+ '@corvu/[email protected]([email protected])':+ dependencies:+ '@floating-ui/dom': 1.7.6+ solid-js: 1.9.15+'@dagrejs/[email protected]':dependencies:'@dagrejs/graphlib': 2.2.4@@ -18835,6 +19002,28 @@ snapshots:'@juggle/[email protected]': {}+ '@kobalte/[email protected]([email protected])':+ dependencies:+ '@floating-ui/dom': 1.7.6+ '@internationalized/number': 3.6.5+ '@kobalte/utils': 0.9.2([email protected])+ '@solid-primitives/props': 3.2.4([email protected])+ '@solid-primitives/resize-observer': 2.2.0([email protected])+ solid-js: 1.9.15+ solid-presence: 0.2.0([email protected])+ solid-prevent-scroll: 0.1.11([email protected])++ '@kobalte/[email protected]([email protected])':+ dependencies:+ '@solid-primitives/event-listener': 2.4.6([email protected])+ '@solid-primitives/keyed': 1.5.3([email protected])+ '@solid-primitives/map': 0.4.13([email protected])+ '@solid-primitives/media': 2.3.6([email protected])+ '@solid-primitives/props': 3.2.4([email protected])+ '@solid-primitives/refs': 1.1.4([email protected])+ '@solid-primitives/utils': 6.4.1([email protected])+ solid-js: 1.9.15+'@levischuck/[email protected]': {}'@lingui/[email protected]':@@ -19165,11 +19354,6 @@ snapshots:promise-worker-transferable: 1.0.4three: 0.163.0- dependencies:- nanostores: 0.9.5- react: 18.3.1-'@napi-rs/[email protected]':optional: true@@ -24090,6 +24274,74 @@ snapshots:'@socket.io/[email protected]': {}+ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ '@solid-primitives/utils': 6.4.1([email protected])+ solid-js: 1.9.15++ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ solid-js: 1.9.15++ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ '@solid-primitives/trigger': 1.2.4([email protected])+ solid-js: 1.9.15++ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ '@solid-primitives/event-listener': 2.4.6([email protected])+ '@solid-primitives/rootless': 1.5.4([email protected])+ '@solid-primitives/static-store': 0.1.4([email protected])+ '@solid-primitives/utils': 6.4.1([email protected])+ solid-js: 1.9.15++ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ '@solid-primitives/utils': 6.4.1([email protected])+ solid-js: 1.9.15++ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ '@solid-primitives/utils': 6.4.1([email protected])+ solid-js: 1.9.15++ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ '@solid-primitives/event-listener': 2.4.6([email protected])+ '@solid-primitives/rootless': 1.5.4([email protected])+ '@solid-primitives/static-store': 0.1.4([email protected])+ '@solid-primitives/utils': 6.4.1([email protected])+ solid-js: 1.9.15++ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ '@solid-primitives/utils': 6.4.1([email protected])+ solid-js: 1.9.15++ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ '@solid-primitives/utils': 6.4.1([email protected])+ solid-js: 1.9.15++ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ '@solid-primitives/utils': 6.4.1([email protected])+ solid-js: 1.9.15++ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ solid-js: 1.9.15++ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ '@solid-primitives/utils': 6.4.1([email protected])+ solid-js: 1.9.15++ '@solid-primitives/[email protected]([email protected])':+ dependencies:+ solid-js: 1.9.15+'@standard-schema/[email protected]': {}'@supabase/[email protected]':@@ -24286,11 +24538,40 @@ snapshots:tailwindcss: 4.3.0vite: 8.3.1(@types/[email protected])(@vitejs/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])- '@tanstack/[email protected]': {}+ '@tanstack/[email protected]':+ dependencies:+ remove-accents: 0.5.0++ '@tanstack/[email protected]': {}- '@tanstack/[email protected]([email protected])':+ '@tanstack/[email protected]([email protected])':dependencies:- '@tanstack/query-core': 5.97.0+ '@kobalte/core': 0.13.14([email protected])+ '@solid-primitives/keyed': 1.5.3([email protected])+ '@solid-primitives/resize-observer': 2.2.0([email protected])+ '@solid-primitives/storage': 1.3.11([email protected])+ '@tanstack/match-sorter-utils': 9.1.2+ '@tanstack/query-core': 5.104.0+ clsx: 2.1.1+ goober: 2.1.19([email protected])+ solid-js: 1.9.15+ solid-transition-group: 0.2.3([email protected])+ superjson: 2.2.6+ transitivePeerDependencies:+ - csstype++ '@tanstack/[email protected](@tanstack/[email protected]([email protected]))(@types/[email protected])([email protected])([email protected])':+ dependencies:+ '@tanstack/query-devtools': 5.104.0([email protected])+ '@tanstack/react-query': 5.104.0([email protected])+ '@types/react': 18.3.28+ react: 18.3.1+ transitivePeerDependencies:+ - csstype++ '@tanstack/[email protected]([email protected])':+ dependencies:+ '@tanstack/query-core': 5.104.0react: 18.3.1@@ -26217,6 +26498,8 @@ snapshots:+ [email protected]: {}+@@ -27649,6 +27932,10 @@ snapshots:+ dependencies:+ csstype: 3.2.3+@@ -29432,8 +29719,6 @@ snapshots:- [email protected]: {}-@@ -31146,6 +31431,12 @@ snapshots:+ dependencies:+ seroval: 1.5.6++ [email protected]: {}+dependencies:encodeurl: 2.0.0@@ -31362,6 +31653,28 @@ snapshots:- supports-color- utf-8-validate+ dependencies:+ csstype: 3.2.3+ seroval: 1.5.6+ seroval-plugins: 1.5.6([email protected])++ dependencies:+ '@corvu/utils': 0.4.2([email protected])+ solid-js: 1.9.15++ dependencies:+ '@corvu/utils': 0.4.2([email protected])+ solid-js: 1.9.15++ dependencies:+ '@solid-primitives/refs': 1.1.4([email protected])+ '@solid-primitives/transition-group': 1.1.2([email protected])+ solid-js: 1.9.15+dependencies:react: 18.3.1@@ -31644,6 +31957,10 @@ snapshots:transitivePeerDependencies:- supports-color+ dependencies:+ copy-anything: 4.1.5+diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 96e5e3ddf2..17bdc11241 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -72,7 +72,6 @@ catalog:'@logtape/logtape': 2.2.3'@logtape/redaction': 2.2.3'@logtape/testing': 2.2.3- '@nanostores/react': 0.7.3'@orpc/client': 1.15.0'@orpc/contract': 1.15.0'@orpc/openapi': 1.15.0@@ -104,6 +103,8 @@ catalog:'@tailwindcss/container-queries': 0.2.2'@tailwindcss/typography': 0.5.19'@tailwindcss/vite': 4.3.0+ '@tanstack/react-query': 5.104.0+ '@tanstack/react-query-devtools': 5.104.0'@tiptap/core': 2.27.2'@tiptap/extension-color': 2.27.2'@tiptap/extension-list-item': 2.27.2@@ -141,7 +142,6 @@ catalog:match-sorter: 8.1.0motion: 12.38.0nanoid: 5.1.16- nanostores: 0.9.5nodemon: 3.1.14non.geist: 1.0.4npm-run-all: 4.1.5