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
perf: cut event-queue load, page storage lists, upgrade supabase-js, name trace spans (#1809)
Sid823e73659006
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex e50ec78e21..e93b072089 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -2025,7 +2025,7 @@ full-screen ERP route.**Rule:** A retry wrapper must never blindly retry a write with real side effects and no idempotency key. `fetchWithRetry` already carved out `isStorageUpload` for this exact reason ("re-sending a multi-GB PUT ... is wasteful"); the same reasoning applies even harder to Edge Function invocations, which routinely do multi-table, multi-transaction writes (`get-method`, `convert`, every `post-*` function). Added `isEdgeFunctionInvoke` (matches `/functions/v1/`) alongside it — one attempt only, honoring the caller's own signal, no retry on status or network error. When debugging "op failed but extra copies appeared," check for exactly this shape (one incoming request, several committed results) before assuming a client-side double-submit or a browser retry.-**Applies to:** `packages/auth/src/lib/supabase/client.ts` (`fetchWithRetry`, `isEdgeFunctionInvoke`); any future retry/timeout wrapper placed in front of `client.functions.invoke`. Also: `$quoteId.duplicate.tsx` and similar routes that discard the real error into a generic message — add `logger.error` there so a recurrence is diagnosable from Vercel logs alone, without needing Supabase edge-function log access.+**Applies to:** `packages/auth/src/lib/supabase/client.ts` (`fetchWithRetry` and `isEdgeFunctionInvoke` were removed with the supabase-js 2.117 upgrade; `storageReadFetch` retries storage reads only and never touches `/functions/v1/`); any future retry/timeout wrapper placed in front of `client.functions.invoke`. Also: `$quoteId.duplicate.tsx` and similar routes that discard the real error into a generic message — add `logger.error` there so a recurrence is diagnosable from Vercel logs alone, without needing Supabase edge-function log access.## pdfjs rejects Node Buffer by constructor check**Context:** `@carbon/files/pdf` and the shared image pipeline feed bytes from `fs.readFile` / `storage.download().arrayBuffer()` into pdfjs (via unpdf) and jSquash codecs.@@ -2124,7 +2124,7 @@ full-screen ERP route.**Rule:** A retry wrapper must never blindly retry a write with real side effects and no idempotency key. `fetchWithRetry` already carved out `isStorageUpload` for this exact reason ("re-sending a multi-GB PUT ... is wasteful"); the same reasoning applies even harder to Edge Function invocations, which routinely do multi-table, multi-transaction writes (`get-method`, `convert`, every `post-*` function). Added `isEdgeFunctionInvoke` (matches `/functions/v1/`) alongside it — one attempt only, honoring the caller's own signal, no retry on status or network error. When debugging "op failed but extra copies appeared," check for exactly this shape (one incoming request, several committed results) before assuming a client-side double-submit or a browser retry.-**Applies to:** `packages/auth/src/lib/supabase/client.ts` (`fetchWithRetry`, `isEdgeFunctionInvoke`); any future retry/timeout wrapper placed in front of `client.functions.invoke`. Also: `$quoteId.duplicate.tsx` and similar routes that discard the real error into a generic message — add `logger.error` there so a recurrence is diagnosable from Vercel logs alone, without needing Supabase edge-function log access.+**Applies to:** `packages/auth/src/lib/supabase/client.ts` (`fetchWithRetry` and `isEdgeFunctionInvoke` were removed with the supabase-js 2.117 upgrade; `storageReadFetch` retries storage reads only and never touches `/functions/v1/`); any future retry/timeout wrapper placed in front of `client.functions.invoke`. Also: `$quoteId.duplicate.tsx` and similar routes that discard the real error into a generic message — add `logger.error` there so a recurrence is diagnosable from Vercel logs alone, without needing Supabase edge-function log access.## A fetcher's redirect is dropped when anything revalidates during the action@@ -2628,7 +2628,9 @@ failed but extra copies appeared", check all four before assuming a browser doub`isDisabled` bound to any-old-boolean is not a guard: name the submit state.**Applies to:** `packages/react/src/Button.tsx`, `packages/form/src/ValidatedForm.tsx`,-`packages/auth/src/lib/supabase/client.ts` (`fetchWithRetry`, `isReplayable`),+`packages/auth/src/lib/supabase/client.ts` (`fetchWithRetry`, `isReplayable` — both+since removed: database reads now use supabase-js's own retry, which never replays a+write, and only storage reads go through `storageReadFetch`),`packages/jobs/src/inngest/functions/notifications/send-{email,slack}.ts`, and any`<Button type="submit">` — enforced by `no-unguarded-submit` (`@carbon/checks`).@@ -2738,6 +2740,30 @@ drawer (`foo.tsx` + `foo.new.tsx`). A list loader reads the whole query string,`search: "all"`. A loader that reads the pathname, a cookie or a header must not use thehelper.+## A write that changes nothing still costs a queue message, an Inngest event and a function run++**Context:** `/api/inngest` was the largest consumer on the ERP deployment (2026-10-01+traces). The audit handler's log was mostly "Skipping: no meaningful diff for UPDATE on+jobOperation".++**Problem:** The scheduler's `persistChanges` issued one `UPDATE jobOperation` per operation on+every regen, always setting `updatedAt`, and re-stamped `status = 'Ready'` on operations that+were already Ready. `dispatch_event_batch()` queued every one of those updates, the drainer+sent them to Inngest ten at a time, and the audit, search and embedding handlers then threw+them away. Nothing was wrong in any single place; the waste was the sum.++**Rule:** A bulk writer guards its UPDATE on the values it writes (`isDistinctFromAny` in+`scheduling-engine.ts` compares in Postgres, so DATE and timestamptz are matched in their own+type) rather than writing every row and bumping `updatedAt`. The trigger is the backstop: an+UPDATE that changes only `updatedAt` / `updatedBy` / `embedding` is not queued for AUDIT,+SEARCH or EMBEDDING (`20261001195204`). When forking `dispatch_event_batch()` into a new+migration, fork the NEWEST definition; `packages/database/src/event-dispatch.test.ts` fails+if the filter is lost.++**Applies to:** `packages/planning/src/scheduling/`, any job or route that rewrites many rows+of a table with event subscriptions, and every migration that redefines+`dispatch_event_batch()`.+## A cached generator's inputs are everything it executes, not everything it parses**Context:** The MCP manifest generator was made a cached Turborepo task with `inputs`@@ -2787,3 +2813,13 @@ tag until proven otherwise.**Applies to:** `apps/erp/app/modules/*/*.service.ts`, `pnpm run generate:mcp`.++## A cast that silences excess-property errors hides failed writes++**Context:** supabase-js 2.117 types reject keys a table does not have (`RejectExcessProperties`). The upgrade wrapped ~75 failing write payloads in `unchecked()` (a cast to `never`) to get typecheck green.++**Problem:** About 30 of those were typed payloads (a zod validator spread into an insert/update) carrying fields the table lacks: `item.shelfLifeCalculateFromBom`, `ability.name`, `quote.notes`, `salesOrder.promisedDate`, `batchProperty.batchPropertyGroupId`, and more. PostgREST rejects any unknown column with PGRST204, so every such write failed whenever the field was present, and `itemValidator`'s always-present checkbox made the BoM explorer's item edit (`api+/item.$type.ts` → `updateItem`) fail on every save. The cast had removed the only warning. The 2.80 types never rejected excess keys, so these were latent all along.++**Rule:** Never cast a typed payload past the table's type. When the compiler names an extra key, destructure it out at the write, where every caller is covered, and say where the value actually lives. `unchecked()` is only for a column or table chosen at runtime (`{ [field]: value }`, `.from(table)`). To list every extra key at once rather than one per error, probe with `Exclude<keyof Payload, keyof Database["public"]["Tables"][T]["Update"]>`.++**Applies to:** every `{module}.service.ts` write, MES `services/*.service.ts`, `packages/utils/src/object.ts` (`unchecked`).diff --git a/.claude/rules/authentication-system.md b/.claude/rules/authentication-system.mdindex 5eea9b1df7..df3cc1227d 100644--- a/.claude/rules/authentication-system.md+++ b/.claude/rules/authentication-system.md@@ -29,7 +29,7 @@ Export subpaths (`package.json`): `.` (`index.ts`), `./auth.server`, `./session.RLS resolves the company via the key.- `getUserScopedClient(userId)` — mints a short-lived (5m) HS256 JWT with`SUPABASE_JWT_SECRET` and returns a user-scoped client (RLS enforced).-- All clients use `fetchWithRetry` (timeout + retry on 5xx/408/524).+- All clients set `db: { timeout: 25_000 }` and rely on supabase-js's built-in read retries, plus `storageReadFetch` for storage reads (see `database-patterns.md`).## Login (`apps/erp/app/routes/_public+/login.tsx`)diff --git a/.claude/rules/coding-conventions.md b/.claude/rules/coding-conventions.mdindex 6b55e774da..1b05286516 100644--- a/.claude/rules/coding-conventions.md+++ b/.claude/rules/coding-conventions.md@@ -108,7 +108,10 @@ MES is lighter: services live under `apps/mes/app/services/`, components underRender it through `Await` when it is visible on first paint, so it streams in theserver HTML (`ImplementationData` in `~/hooks/useImplementationNavItem` is thepattern); read it with `useResolved` (`~/hooks/useResolved`) when a late value is- harmless.+ harmless. `useResolved` keeps the last value while a revalidation is pending, so a+ component that stays mounted across records passes the record id as its third+ argument (`useResolved(promise, null, itemId)`), or it shows the previous record's+ value until the new one arrives.- On success an action throws a redirect (`throw redirect(...)`), not `return`.Cached entities add a `clientAction`/`clientLoader` for cache control.diff --git a/.claude/rules/database-patterns.md b/.claude/rules/database-patterns.mdindex 8926c87544..c554282f27 100644--- a/.claude/rules/database-patterns.md+++ b/.claude/rules/database-patterns.md@@ -26,8 +26,14 @@ All client factories live in `packages/auth/src/lib/supabase/`.| `getCarbonServiceRole()` | `client.server.ts` (service role key) | No (bypasses RLS) | Server-only privileged ops, jobs, edge functions || `getCarbonAPIKeyClient(apiKey)` | `client.ts` (`carbon-key` header) | Yes | Public API key auth |-`createClient` is configured with `autoRefreshToken: false`, `persistSession: false`, and a-`fetchWithRetry` wrapper (retries 5xx/408/timeouts with backoff). Do not re-create this config ad hoc.+`createClient` is configured with `autoRefreshToken: false`, `persistSession: false` and+`db: { timeout: 25_000 }`. Database retries are supabase-js's own (a read is retried up to three+times on a rejected fetch, 503 or 520; a write is never replayed; a timed-out call is not retried).+Storage reads get the same through `global.fetch: storageReadFetch` (`client.ts`): a GET, HEAD or+listing waits at most 25 s for headers (the body is not timed) and is retried twice on a 5xx or a+dropped connection; uploads, deletes, auth and function calls pass straight through. Do not+re-create this config ad hoc, and do not widen that wrapper to database calls: it would multiply+the SDK's retries.### Getting a client in a routediff --git a/.claude/rules/event-system.md b/.claude/rules/event-system.mdindex 2f62d5586d..ee6fc2c953 100644--- a/.claude/rules/event-system.md+++ b/.claude/rules/event-system.md@@ -42,7 +42,7 @@ The wake path (`20260721184852_event-queue-wake.sql`) — both helpers live in t`handlerType` CHECK now allows all six: `WEBHOOK, WORKFLOW, SYNC, SEARCH, AUDIT, EMBEDDING` (widened across `20260204080000` → `20260212152709` → `20260326120000`).### PL/pgSQL functions (in `_event_system_impl` + later)-- `dispatch_event_batch()` — AFTER STATEMENT. Reads transition tables (`batched_new`/`batched_old`), filters by active subscriptions, builds payload, `pgmq.send_batch('event_system', ...)`. Captures `actorId := auth.uid()::TEXT` (added `20260212153753`; NULL for service-role) and `workflowRunId` from the `workflow_run_id` JWT claim (`20260810100000`). UPDATE pairs transition rows on the table's **full** primary key via `get_primary_key_columns()` (`20260717143448`, restored in `20260810100000` after `20260721184852` copied the older single-column pairing forward). Uses `clock_timestamp()` per event so batched events get unique microsecond timestamps (`20260427120000`).+- `dispatch_event_batch()` — AFTER STATEMENT. Reads transition tables (`batched_new`/`batched_old`), filters by active subscriptions, builds payload, `pgmq.send_batch('event_system', ...)`. Captures `actorId := auth.uid()::TEXT` (added `20260212153753`; NULL for service-role) and `workflowRunId` from the `workflow_run_id` JWT claim (`20260810100000`). UPDATE pairs transition rows on the table's **full** primary key via `get_primary_key_columns()` (`20260717143448`, restored in `20260810100000` after `20260721184852` copied the older single-column pairing forward). Uses `clock_timestamp()` per event so batched events get unique microsecond timestamps (`20260427120000`). An UPDATE that changes nothing but `updatedAt` / `updatedBy` / `embedding` is not queued for `AUDIT`, `SEARCH` or `EMBEDDING` subscriptions (`20261001195204`) — those handlers discard such an event anyway; `WEBHOOK`, `WORKFLOW` and `SYNC` still receive every UPDATE because their payload is a contract. The column list is `ignored_columns` in the function and must equal `auditConfig.skipFields`; `packages/database/src/event-dispatch.test.ts` reads the NEWEST definition and fails when a fork drops the filter or the two lists diverge.- `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.@@ -68,14 +68,14 @@ Zod schemas + helpers. `QueueMessage` = `{ subscriptionId, triggerType: ROW|STAT## Handlers — `packages/jobs/src/inngest/functions/events/`-`queue.ts` is the drainer (id `event-queue`), triggered by `carbon/event-queue.process` with `concurrency: 1`; it loops read → dispatch → delete until the queue is empty (max 10 passes of 100, then re-wakes itself). Burst coalescing is handled upstream — the trigger wakes at most once per transaction — not by `debounce` (the local Inngest dev server, v1.19.4, fails to unmarshal debounce items). Each handler is an Inngest function listening on `carbon/event-<name>`:+`queue.ts` is the drainer (id `event-queue`), triggered by `carbon/event-queue.process` with `concurrency: 1`; it loops read → dispatch → delete until the queue is empty (max 10 passes of 100, then re-wakes itself). Each `step.sendEvent` is a request to the app, so events are packed by SIZE, not a fixed count: `packBySize` (`events/pack.ts`) fills each event up to `MAX_EVENT_BYTES` (200 KB, under Inngest's 256 KB cap) and at most `MAX_RECORDS` (50) records — 10 for `SYNC` and `EMBEDDING`, which call an external service per record. A record larger than the budget travels alone. Burst coalescing is handled upstream — the trigger wakes at most once per transaction — not by `debounce` (the local Inngest dev server, v1.19.4, fails to unmarshal debounce items). Each handler is an Inngest function listening on `carbon/event-<name>`:| handlerType | event name | file | purpose ||---|---|---|---|| `WEBHOOK` | `carbon/event-webhook` | `webhook.ts` | `axios.post(config.url, toWebhookBody(...), { headers })` — customer-facing webhooks; see below || `WORKFLOW` | `carbon/event-workflow` | `workflow.ts` | customer-workflow matcher — announcement → catalog event ids → subscribed workflows → one `workflowRun` each (see `workflow-matcher.md`) || `SYNC` | `carbon/event-sync` | `sync.ts` | accounting sync (Xero); maps table→entity, calls `@carbon/ee/accounting` |-| `SEARCH` | `carbon/event-search` | `search.ts` | upsert/delete `search_index` via RPC per entity config |+| `SEARCH` | `carbon/event-search` | `search.ts` | upsert/delete `search_index` per entity config (`search-config.ts`): last event per record wins, one read per related table for the whole batch, then one delete and one upsert statement over Kysely. A failed read or write throws so the step retries || `AUDIT` | `carbon/event-audit` | `audit.ts` | writes per-company audit log (uses `actorId`, `audit.config`) || `EMBEDDING` | `carbon/event-embedding` | `embedding.ts` | invokes `embed` edge fn for `item/customer/supplier` name/description changes |diff --git a/.claude/rules/mrp-system.md b/.claude/rules/mrp-system.mdindex 6a42411888..9641f605f8 100644--- a/.claude/rules/mrp-system.md+++ b/.claude/rules/mrp-system.md@@ -24,9 +24,14 @@ Phase-7 write) and throws on failure.1. **Scheduled job** — `packages/jobs/src/inngest/functions/scheduled/mrp.ts`.`inngest.createFunction({ id: "mrp", retries: 2 }, { cron: "0 */3 * * *" }, …)`— every 3 hours. A `find-companies` step selects all rows from `company`,- then **one `step.run` per company** (`mrp-<companyId>`) calls- `runMrp(serviceRole, getJobDatabaseClient(), { type: "company", id,- companyId, userId: "system" })` **in-process** (`runMrp` throws on failure;+ narrowed by `companiesWithPlanningWork` (`scheduled/mrp-companies.ts`): one+ UNION over the open demand/supply views, `demandProjection`, and the rows an+ earlier run wrote (`demandForecast` with `forecastMethod = 'mrp'`,+ `demandForecastSource`, `supplyForecast`, non-zero actuals). A company in+ none of them would read nothing and write nothing, so it is skipped; a+ failed lookup plans for every company. Then **one `step.run` per company**+ (`mrp-<companyId>`) calls `runMrp(serviceRole, getJobDatabaseClient(),+ { type: "company", id, companyId, userId: "system" })` **in-process** (`runMrp` throws on failure;the loop try/catches per step and returns `{ companies, failed }`). EveryInngest step is one HTTP request to `/api/inngest`, so a step's ceiling isthat Vercel function's max duration — set project-wide in the Verceldiff --git a/.claude/rules/scheduling-data-structures.md b/.claude/rules/scheduling-data-structures.mdindex 2825dec7b2..e39259cc30 100644--- a/.claude/rules/scheduling-data-structures.md+++ b/.claude/rules/scheduling-data-structures.md@@ -369,7 +369,9 @@ only; its output is read by nothing in the placement path (specdispatch-sequencing policy** — the old per-work-center policy table, its rule enum,and the FIFO/EDD/SPT/… comparators were all removed; placement order is the onlysequence.-- **`persistChanges` (one transaction, only when `persist`)** writes, for every op, the+- **`persistChanges` (one transaction, only when `persist`)** writes, for every op whose+ values changed (`isDistinctFromAny` guards the UPDATE in SQL, so a quiet regen writes no+ `jobOperation` or `job` row and queues no audit/search event), theforward placement's results — `startDate` (projected start, business day) +`jobOperation.projectedCompletionAt` (exact placed-end instant, timestamptz) +`priority` + `workCenterId` + conflict flags. `dueDate` is the backward need-by anddiff --git a/.claude/rules/workflow-event-system.md b/.claude/rules/workflow-event-system.mdindex 5eac733842..8512a967d1 100644--- a/.claude/rules/workflow-event-system.md+++ b/.claude/rules/workflow-event-system.md@@ -200,7 +200,8 @@ In `packages/jobs/src/inngest/functions/events/queue.ts`:```2. Add a dispatch block **inside the drain loop** (the body runs once per `pass`;step ids must include the pass suffix or replays break). Use- `chunk(..., CHUNK_SIZE)` to stay under Inngest's 256KB event limit.+ `packBySize(..., MAX_EVENT_BYTES, MAX_RECORDS)` to stay under Inngest's 256KB+ event limit (`MAX_SLOW_RECORDS` if the handler calls an external service per record).**Batched** (like SEARCH — one event per chunk, `data.records` is an array):```typescriptif (grouped.YOUR_NEW_TYPE.length > 0) {@@ -208,9 +209,9 @@ In `packages/jobs/src/inngest/functions/events/queue.ts`:event: job.message.event,companyId: job.message.companyId,}));- const chunks = chunk(records, CHUNK_SIZE);+ const chunks = packBySize(records, MAX_EVENT_BYTES, MAX_RECORDS);for (let i = 0; i < chunks.length; i++) {- await step.sendEvent(`dispatch-your-new-type-${pass}-${i}`, {+ await step.sendEvent(`send-your-new-type-${pass}-${i}`, {name: "carbon/event-your-new-type" as const,data: { records: chunks[i] },});@@ -231,7 +232,7 @@ Two edits:1. Export it from the barrel `packages/jobs/src/inngest/functions/events/index.ts`.2. Add it to the `functions` array in **`packages/jobs/src/inngest/index.ts`** (under- the "Event handlers" group). That array is what `serve()` / `connect()` serves.+ the "Event handlers" group). That array is what `serve()` serves.There is **no** `packages/jobs/src/inngest/functions/index.ts` — older docs referencedthat path; it does not exist.@@ -274,7 +275,7 @@ that path; it does not exist.3. **Operation casing** — `["INSERT"]`, not `["insert"]`.4. **Forgot to register** — a new handler must be in BOTH the `events/index.ts` barrel ANDthe `functions` array in `packages/jobs/src/inngest/index.ts`, or it is never served.-5. **Event size** — always `chunk(..., CHUNK_SIZE)`; Inngest caps events at 256KB.+5. **Event size** — always `packBySize(..., MAX_EVENT_BYTES, …)`; Inngest caps events at 256KB.6. **Wrong dispatch shape** — match the queue branch to the handler: per-row (`msgId` +flattened config) vs batched (`{ records: [...] }`). Mixing them breaks Zod parsing.diff --git a/apps/erp/app/entry.server.tsx b/apps/erp/app/entry.server.tsxindex 0ac8430b3a..506b39f7f4 100644--- a/apps/erp/app/entry.server.tsx+++ b/apps/erp/app/entry.server.tsx@@ -7,12 +7,14 @@ import {getNonce,setStrictContentSecurityPolicy} from "@carbon/auth/middleware/security.server";+import { inngest } from "@carbon/lib/inngest";import { getLogger } from "@carbon/logger";import { ensureLoggingConfigured } from "@carbon/logger/config.server";import { getRequestId } from "@carbon/logger/middleware.server";import { createTracing } from "@carbon/logger/tracing.server";import { waitUntil } from "@vercel/functions";import { handleRequest as vercelHandleRequest } from "@vercel/react-router/entry.server";+import { InngestSpanProcessor } from "inngest/experimental";import type { EntryContext, RouterContextProvider } from "react-router";import { isRouteErrorResponse } from "react-router";import { scheduleInngestSelfSync } from "./utils/inngest-self-sync.server";@@ -22,7 +24,12 @@ ensureLoggingConfigured();export const instrumentations = createTracing({serviceName: "carbon-erp",// Vercel can suspend the instance once the response is sent.- afterRequest: process.env.VERCEL ? (flush) => waitUntil(flush()) : undefined+ afterRequest: process.env.VERCEL ? (flush) => waitUntil(flush()) : undefined,+ // Sends the spans of a function run to Inngest, so its run timeline shows+ // the queries and HTTP calls each step made. Registered here, not through+ // Inngest's middleware on the client: that module is reachable from browser+ // code (`trigger`) and must not pull in the tracing SDK.+ spanProcessors: [new InngestSpanProcessor(inngest)]});scheduleInngestSelfSync();diff --git a/apps/erp/app/hooks/useResolved.ts b/apps/erp/app/hooks/useResolved.tsindex 932848f525..db4f42ee93 100644--- a/apps/erp/app/hooks/useResolved.ts+++ b/apps/erp/app/hooks/useResolved.ts@@ -7,14 +7,17 @@ import { useEffect, useState } from "react";const settled = new WeakMap<Promise<unknown>, unknown>();// Unwraps a promise a loader streamed instead of awaiting, keeping the last-// value while a revalidation's replacement is pending.+// value while a revalidation's replacement is pending. Pass the record id as+// `scope` when the component stays mounted across records: a new scope drops+// the last value, so one record never shows another's.export function useResolved<T>(promise: Promise<T> | null | undefined,- fallback: T+ fallback: T,+ scope?: string): T {- const [value, setValue] = useState<T>(() =>- promise && settled.has(promise) ? (settled.get(promise) as T) : fallback- );+ const initial = () =>+ promise && settled.has(promise) ? (settled.get(promise) as T) : fallback;+ const [state, setState] = useState(() => ({ scope, value: initial() }));useEffect(() => {if (!promise) return;@@ -22,14 +25,14 @@ export function useResolved<T>(promise.then((resolved) => {settled.set(promise, resolved);- if (active) setValue(resolved);+ if (active) setState({ scope, value: resolved });},() => undefined);return () => {active = false;};- }, [promise]);+ }, [promise, scope]);- return value;+ return state.scope === scope ? state.value : initial();}diff --git a/apps/erp/app/modules/accounting/accounting.service.ts b/apps/erp/app/modules/accounting/accounting.service.tsindex 2643393176..eb5b386423 100644--- a/apps/erp/app/modules/accounting/accounting.service.ts+++ b/apps/erp/app/modules/accounting/accounting.service.ts@@ -16,7 +16,8 @@ import {round,toDisplayCredit,toDisplayDebit,- toStoredAmount+ toStoredAmount,+ unchecked} from "@carbon/utils";import { endOfMonth, parseDate, startOfMonth } from "@internationalized/date";import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";@@ -6076,7 +6077,7 @@ export async function upsertFixedAssetClass(const { id, ...rest } = data;return client.from("fixedAssetClass")- .update(sanitize(rest))+ .update(unchecked(sanitize(rest))).eq("id", id).select("id").single();@@ -6308,7 +6309,7 @@ export async function upsertFixedAsset(const { id, ...rest } = data;return client.from("fixedAsset")- .update(sanitize(rest))+ .update(unchecked(sanitize(rest))).eq("id", id).select("id").single();diff --git a/apps/erp/app/modules/documents/documents.service.ts b/apps/erp/app/modules/documents/documents.service.tsindex 14035b6006..bd5fa0ae03 100644--- a/apps/erp/app/modules/documents/documents.service.ts+++ b/apps/erp/app/modules/documents/documents.service.ts@@ -201,8 +201,8 @@ export async function upsertDocument();}- // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration- const { extension, ...data } = document;+ // Labels live in documentLabel, not on the document row.+ const { extension: _extension, labels: _labels, ...data } = document;return client.from("document").update(diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex 1aad8ee762..b8415269af 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -2190,7 +2190,9 @@ export async function updateBatchPropertyOrder(updatedBy: string;}) {- return client.from("batchProperty").update(sanitize(data)).eq("id", data.id);+ // batchProperty has no group column; the group is not stored.+ const { batchPropertyGroupId: _group, ...order } = data;+ return client.from("batchProperty").update(sanitize(order)).eq("id", data.id);}/** @mcp update */@@ -2224,7 +2226,11 @@ export async function upsertBatchProperty(userId: string;}) {- const { userId, ...data } = batchProperty;+ const {+ userId,+ configurationParameterGroupId: _group,+ ...data+ } = batchProperty;if (batchProperty.id) {return client.from("batchProperty")@@ -2259,22 +2265,18 @@ export async function upsertKanban(customFields?: Json;})) {- if ("createdBy" in kanban) {- return client- .from("kanban")- .insert({- ...kanban- })- .select("id")- .single();+ // kanban has no customFields column.+ const { customFields: _customFields, ...row } = kanban;+ if ("createdBy" in row) {+ return client.from("kanban").insert(row).select("id").single();}return client.from("kanban").update({- ...sanitize(kanban),+ ...sanitize(row),updatedAt: datetime.timestamp()})- .eq("id", kanban.id)+ .eq("id", row.id).select("id").single();}diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.tsindex 480cb62ca9..3ad61fb133 100644--- a/apps/erp/app/modules/invoicing/invoicing.service.ts+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts@@ -849,11 +849,14 @@ export async function upsertPurchaseInvoice(customFields?: Json;})) {+ // Shipping cost belongs to purchaseInvoiceDelivery, not the invoice row.if ("id" in purchaseInvoice) {+ const { supplierShippingCost: _shipping, ...invoiceUpdate } =+ purchaseInvoice;return client.from("purchaseInvoice").update({- ...sanitize(purchaseInvoice),+ ...sanitize(invoiceUpdate),updatedAt: datetime.timestamp()}).eq("id", purchaseInvoice.id)@@ -902,8 +905,11 @@ export async function upsertPurchaseInvoice(const locationId =purchaseInvoice.locationId ?? purchaser?.data?.locationId ?? null;- const { companyGroupId: _companyGroupId, ...purchaseInvoiceData } =- purchaseInvoice;+ const {+ companyGroupId: _companyGroupId,+ supplierShippingCost: _shipping,+ ...purchaseInvoiceData+ } = purchaseInvoice;const invoice = await client.from("purchaseInvoice")@@ -1233,10 +1239,11 @@ export async function upsertSalesInvoice(})) {if ("id" in salesInvoice) {+ const { supplierShippingCost: _shipping, ...invoiceUpdate } = salesInvoice;return client.from("salesInvoice").update({- ...sanitize(salesInvoice),+ ...sanitize(invoiceUpdate),updatedAt: datetime.timestamp()}).eq("id", salesInvoice.id)@@ -1285,7 +1292,11 @@ export async function upsertSalesInvoice(const locationId =salesInvoice.locationId ?? salesPerson?.data?.locationId ?? null;- const { companyGroupId: _companyGroupId, ...salesInvoiceData } = salesInvoice;+ const {+ companyGroupId: _companyGroupId,+ supplierShippingCost: _shipping,+ ...salesInvoiceData+ } = salesInvoice;const invoice = await client.from("salesInvoice")@@ -1370,11 +1381,17 @@ export async function upsertSalesInvoiceLine(customFields?: Json;})) {- if ("id" in salesInvoiceLine) {+ // salesInvoiceLine has no purchase order columns.+ const {+ purchaseOrderId: _purchaseOrderId,+ purchaseOrderLineId: _purchaseOrderLineId,+ ...line+ } = salesInvoiceLine;+ if ("id" in line) {return client.from("salesInvoiceLine")- .update(sanitize(salesInvoiceLine))- .eq("id", salesInvoiceLine.id)+ .update(sanitize(line))+ .eq("id", line.id).select("id").single();}@@ -1382,7 +1399,7 @@ export async function upsertSalesInvoiceLine(const existing = await client.from("salesInvoiceLine").select("sortOrder")- .eq("invoiceId", salesInvoiceLine.invoiceId);+ .eq("invoiceId", line.invoiceId);const maxSortOrder = (existing.data ?? []).reduce((max, row) => Math.max(max, row.sortOrder ?? 0),@@ -1391,7 +1408,7 @@ export async function upsertSalesInvoiceLine(return client.from("salesInvoiceLine")- .insert([{ ...salesInvoiceLine, sortOrder: maxSortOrder + 1 }])+ .insert([{ ...line, sortOrder: maxSortOrder + 1 }]).select("id").single();}diff --git a/apps/erp/app/modules/items/items.server.ts b/apps/erp/app/modules/items/items.server.tsindex 4cd9b1d999..1ed0475e9f 100644--- a/apps/erp/app/modules/items/items.server.ts+++ b/apps/erp/app/modules/items/items.server.ts@@ -8,6 +8,7 @@ import type { Database } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";+import { oncePerRead } from "@carbon/logger/middleware.server";import { NotificationEvent } from "@carbon/notifications";import { chunkArray } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";@@ -15,8 +16,11 @@ import { data } from "react-router";import {activateMethodVersion,findChangeNoticesForItem,+ getChangeNoticeTypesList,getItemSupersededBy,getItemSupersession,+ getMakeMethodById,+ getMakeMethods,upsertItemSupersession} from "~/modules/items";import { getCompanySettings } from "~/modules/settings";@@ -32,6 +36,51 @@ import {const logger = getLogger("erp", "change-orders");+// An item page's layout and its tab loaders run in ONE request and each read the+// item's methods and change notices. These share that read across the loaders;+// on a mutation they are plain calls, so a revalidation never sees stale rows.++export const getMakeMethodsOnce = (+ client: SupabaseClient<Database>,+ itemId: string,+ companyId: string+) =>+ oncePerRead(`makeMethods:${companyId}:${itemId}`, () =>+ getMakeMethods(client, itemId, companyId)+ );++export const getMakeMethodByIdOnce = (+ client: SupabaseClient<Database>,+ makeMethodId: string,+ companyId: string+) =>+ oncePerRead(`makeMethod:${companyId}:${makeMethodId}`, () =>+ getMakeMethodById(client, makeMethodId, companyId)+ );++export const findChangeNoticesForItemOnce = (+ client: SupabaseClient<Database>,+ args: { itemId: string; companyId: string }+) =>+ oncePerRead(`changeNotices:${args.companyId}:${args.itemId}`, () =>+ findChangeNoticesForItem(client, args)+ );++export async function getItemChangeNoticeDataOnce(+ client: SupabaseClient<Database>,+ itemId: string,+ companyId: string+) {+ const [changeNotices, changeNoticeTypes] = await Promise.all([+ findChangeNoticesForItemOnce(client, { itemId, companyId }),+ getChangeNoticeTypesList(client, companyId)+ ]);+ return {+ changeNotices: changeNotices.data,+ changeNoticeTypes: changeNoticeTypes.data ?? []+ };+}+// Release-lock helpers — gate BOM/BOP mutations on a released (Production)// revision. A Production revision is the controlled, released make method;// changes must flow through a change notice. The pending revision an ECO createsdiff --git a/apps/erp/app/modules/items/items.service.test.ts b/apps/erp/app/modules/items/items.service.test.tsindex faf7385aff..17bfb069e9 100644--- a/apps/erp/app/modules/items/items.service.test.ts+++ b/apps/erp/app/modules/items/items.service.test.ts@@ -518,7 +518,10 @@ describe("diffMethod — attributes", () => {});describe("getItemDemand", () => {- function mockClient(rowsByTable: Record<string, unknown[]>) {+ function mockClient(+ rowsByTable: Record<string, unknown[]>,+ errorsByTable: Record<string, unknown> = {}+ ) {const reads: Array<{table: string;filters: Array<[string, string, unknown]>;@@ -539,7 +542,11 @@ describe("getItemDemand", () => {},order: () => builder,then: (resolve: (v: unknown) => void) =>- resolve({ data: rowsByTable[table] ?? [], error: null })+ resolve(+ errorsByTable[table]+ ? { data: null, error: errorsByTable[table] }+ : { data: rowsByTable[table] ?? [], error: null }+ )};return builder;}@@ -598,7 +605,22 @@ describe("getItemDemand", () => {expect(demand).toEqual({actuals: [],forecasts: [],- projections: [projectionRow]+ projections: [projectionRow],+ error: null});});++ it("tells an item with no demand apart from a failed read", async () => {+ const { getItemDemand } = await import("./items.service");++ const empty = await getItemDemand(mockClient({}).client, args);+ expect(empty.error).toBeNull();++ const failure = { message: "permission denied for table demandForecast" };+ const failed = await getItemDemand(+ mockClient({}, { demandForecast: failure }).client,+ args+ );+ expect(failed.error).toBe(failure);+ });});diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.tsindex 333501e2ee..01186fc435 100644--- a/apps/erp/app/modules/items/items.service.ts+++ b/apps/erp/app/modules/items/items.service.ts@@ -738,10 +738,13 @@ export async function getItemDemand(.in("periodId", periods)]);+ // A failed read is reported, not folded into an empty series: an item with+ // no demand yet has empty series too, and the two must not look alike.return {actuals: actuals.data ?? [],forecasts: forecasts.data ?? [],- projections: projections.data ?? []+ projections: projections.data ?? [],+ error: actuals.error ?? forecasts.error ?? projections.error ?? null};}@@ -4024,9 +4027,22 @@ export async function updateItem(type: Database["public"]["Enums"]["itemType"];}) {+ // These are stored elsewhere (pickMethod, itemCost, itemShelfLife), not on+ // the item row.+ const {+ defaultStorageUnitId: _defaultStorageUnitId,+ postingGroupId: _postingGroupId,+ unitCost: _unitCost,+ shelfLifeMode: _shelfLifeMode,+ shelfLifeDays: _shelfLifeDays,+ shelfLifeTriggerProcessId: _shelfLifeTriggerProcessId,+ shelfLifeTriggerTiming: _shelfLifeTriggerTiming,+ shelfLifeCalculateFromBom: _shelfLifeCalculateFromBom,+ ...row+ } = item;return client.from("item")- .update(sanitize(item))+ .update(sanitize(row)).eq("id", item.id).eq("companyId", item.companyId);}@@ -6815,15 +6831,17 @@ export async function upsertChangeNoticeType(customFields?: Json;}) {+ // changeOrderType has no customFields column.if ("createdBy" in changeNoticeType) {- return client- .from("changeOrderType")- .insert([changeNoticeType])- .select("id")- .single();+ const { customFields: _customFields, ...type } = changeNoticeType;+ return client.from("changeOrderType").insert([type]).select("id").single();}// companyId scopes the row, it is not part of the payload (it's in the PK).- const { companyId, ...update } = changeNoticeType;+ const {+ companyId,+ customFields: _customFields,+ ...update+ } = changeNoticeType;return client.from("changeOrderType").update(sanitize(update))diff --git a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeProperties.tsx b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeProperties.tsxindex d922c53063..cc5b6d9475 100644--- a/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeProperties.tsx+++ b/apps/erp/app/modules/items/ui/ChangeNotice/ChangeNoticeProperties.tsx@@ -103,7 +103,7 @@ const ChangeNoticeProperties = () => {const changeNotice = routeData?.changeNotice;const types = routeData?.types ?? [];const affectedItems = routeData?.affectedItems ?? [];- const impactUsedIn = useResolved(routeData?.impactUsedIn, NO_IMPACT);+ const impactUsedIn = useResolved(routeData?.impactUsedIn, NO_IMPACT, id);const nonConformanceOptions = routeData?.nonConformanceOptions ?? [];const linkedNonConformance = routeData?.linkedNonConformance ?? null;const isLocked = isChangeNoticeLocked(changeNotice?.status);diff --git a/apps/erp/app/modules/items/ui/Consumables/ConsumableHeader.tsx b/apps/erp/app/modules/items/ui/Consumables/ConsumableHeader.tsxindex a45869ce4f..e84024a96d 100644--- a/apps/erp/app/modules/items/ui/Consumables/ConsumableHeader.tsx+++ b/apps/erp/app/modules/items/ui/Consumables/ConsumableHeader.tsx@@ -58,7 +58,7 @@ const ConsumableHeader = () => {} | null>;}>(path.to.consumable(itemId));- const supersession = useResolved(routeData?.supersession, null);+ const supersession = useResolved(routeData?.supersession, null, itemId);const lifecycleStatus = getItemLifecycleStatus(supersession?.supersessionMode);diff --git a/apps/erp/app/modules/items/ui/Consumables/ConsumableProperties.tsx b/apps/erp/app/modules/items/ui/Consumables/ConsumableProperties.tsxindex eb984a79e4..8d6a6c9639 100644--- a/apps/erp/app/modules/items/ui/Consumables/ConsumableProperties.tsx+++ b/apps/erp/app/modules/items/ui/Consumables/ConsumableProperties.tsx@@ -112,8 +112,16 @@ const ConsumableProperties = ({ data }: ConsumablePropertiesProps) => {}>>;}>(path.to.consumable(itemId));- const supersession = useResolved(routeDataFromRoute?.supersession, null);- const supersededBy = useResolved(routeDataFromRoute?.supersededBy, null);+ const supersession = useResolved(+ routeDataFromRoute?.supersession,+ null,+ itemId+ );+ const supersededBy = useResolved(+ routeDataFromRoute?.supersededBy,+ null,+ itemId+ );const routeData = data ?? routeDataFromRoute;const locations = data?.locations ?? sharedConsumablesData?.locations ?? [];diff --git a/apps/erp/app/modules/items/ui/Item/CustomerParts/useCustomerParts.tsx b/apps/erp/app/modules/items/ui/Item/CustomerParts/useCustomerParts.tsxindex 014a6cbdea..4be983798e 100644--- a/apps/erp/app/modules/items/ui/Item/CustomerParts/useCustomerParts.tsx+++ b/apps/erp/app/modules/items/ui/Item/CustomerParts/useCustomerParts.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { useCarbon } from "@carbon/auth";+import { unchecked } from "@carbon/utils";import { useCallback } from "react";import { usePermissions } from "~/hooks";import type { CustomerPart } from "../../../types";@@ -19,9 +20,11 @@ export default function useCustomerParts() {if (!carbon) throw new Error("Carbon client not found");return await carbon.from("customerPartToItem")- .update({- [id]: value- })+ .update(+ unchecked({+ [id]: value+ })+ ).eq("id", row.id);},[carbon]diff --git a/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx b/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsxindex 8a8a797740..4e40e188bb 100644--- a/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx+++ b/apps/erp/app/modules/items/ui/Item/SupplierPartForm.tsx@@ -385,7 +385,8 @@ function PriceBreaks({error: null,count: null,status: 200,- statusText: "OK"+ statusText: "OK",+ success: true}) as const,[]);diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialHeader.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialHeader.tsxindex 1785ad149f..fb27f1d049 100644--- a/apps/erp/app/modules/items/ui/Materials/MaterialHeader.tsx+++ b/apps/erp/app/modules/items/ui/Materials/MaterialHeader.tsx@@ -58,7 +58,7 @@ const MaterialHeader = () => {} | null>;}>(path.to.material(itemId));- const supersession = useResolved(routeData?.supersession, null);+ const supersession = useResolved(routeData?.supersession, null, itemId);const lifecycleStatus = getItemLifecycleStatus(supersession?.supersessionMode);diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialProperties.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialProperties.tsxindex 65edc2491b..a063dbb909 100644--- a/apps/erp/app/modules/items/ui/Materials/MaterialProperties.tsx+++ b/apps/erp/app/modules/items/ui/Materials/MaterialProperties.tsx@@ -134,8 +134,16 @@ const MaterialProperties = ({ data }: MaterialPropertiesProps) => {}>>;}>(path.to.material(itemId));- const supersession = useResolved(routeDataFromRoute?.supersession, null);- const supersededBy = useResolved(routeDataFromRoute?.supersededBy, null);+ const supersession = useResolved(+ routeDataFromRoute?.supersession,+ null,+ itemId+ );+ const supersededBy = useResolved(+ routeDataFromRoute?.supersededBy,+ null,+ itemId+ );const routeData = data ?? routeDataFromRoute;const locations = data?.locations ?? sharedMaterialsData?.locations ?? [];diff --git a/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx b/apps/erp/app/modules/items/ui/Parts/PartHeader.tsxindex a089144012..a77558da66 100644--- a/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx+++ b/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx@@ -64,7 +64,7 @@ const PartHeader = () => {} | null>;}>(path.to.part(itemId));- const supersession = useResolved(routeData?.supersession, null);+ const supersession = useResolved(routeData?.supersession, null, itemId);const lifecycleStatus = getItemLifecycleStatus(supersession?.supersessionMode);diff --git a/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx b/apps/erp/app/modules/items/ui/Parts/PartProperties.tsxindex 852bcc0ec6..b51092d2c9 100644--- a/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx+++ b/apps/erp/app/modules/items/ui/Parts/PartProperties.tsx@@ -155,8 +155,16 @@ const PartProperties = ({// Set while the change notice that minted this item is still open.unreleasedChangeOrder?: UnreleasedChangeOrderItem | null;}>(path.to.part(itemId));- const supersession = useResolved(routeDataFromRoute?.supersession, null);- const supersededBy = useResolved(routeDataFromRoute?.supersededBy, null);+ const supersession = useResolved(+ routeDataFromRoute?.supersession,+ null,+ itemId+ );+ const supersededBy = useResolved(+ routeDataFromRoute?.supersededBy,+ null,+ itemId+ );const routeData = data ?? routeDataFromRoute;const locations = data?.locations ?? sharedPartsData?.locations ?? [];diff --git a/apps/erp/app/modules/items/ui/Services/ServiceHeader.tsx b/apps/erp/app/modules/items/ui/Services/ServiceHeader.tsxindex 891c8e0356..58240fd466 100644--- a/apps/erp/app/modules/items/ui/Services/ServiceHeader.tsx+++ b/apps/erp/app/modules/items/ui/Services/ServiceHeader.tsx@@ -58,7 +58,7 @@ const ServiceHeader = () => {} | null>;}>(path.to.service(itemId));- const supersession = useResolved(routeData?.supersession, null);+ const supersession = useResolved(routeData?.supersession, null, itemId);const lifecycleStatus = getItemLifecycleStatus(supersession?.supersessionMode);diff --git a/apps/erp/app/modules/items/ui/Services/ServiceProperties.tsx b/apps/erp/app/modules/items/ui/Services/ServiceProperties.tsxindex 62d8298647..936f7e8443 100644--- a/apps/erp/app/modules/items/ui/Services/ServiceProperties.tsx+++ b/apps/erp/app/modules/items/ui/Services/ServiceProperties.tsx@@ -83,8 +83,16 @@ const ServiceProperties = ({ data }: ServicePropertiesProps) => {}>>;}>(path.to.service(itemId));- const supersession = useResolved(routeDataFromRoute?.supersession, null);- const supersededBy = useResolved(routeDataFromRoute?.supersededBy, null);+ const supersession = useResolved(+ routeDataFromRoute?.supersession,+ null,+ itemId+ );+ const supersededBy = useResolved(+ routeDataFromRoute?.supersededBy,+ null,+ itemId+ );const routeData = data ?? routeDataFromRoute;const supplierParts = routeData?.supplierParts ?? [];diff --git a/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx b/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsxindex 8b710dc9db..f12e550893 100644--- a/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx+++ b/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx@@ -64,7 +64,7 @@ const ToolHeader = () => {} | null>;}>(path.to.tool(itemId));- const supersession = useResolved(routeData?.supersession, null);+ const supersession = useResolved(routeData?.supersession, null, itemId);const lifecycleStatus = getItemLifecycleStatus(supersession?.supersessionMode);diff --git a/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx b/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsxindex a1fb8aad87..54505b8bde 100644--- a/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx+++ b/apps/erp/app/modules/items/ui/Tools/ToolProperties.tsx@@ -117,8 +117,16 @@ const ToolProperties = ({ data }: ToolPropertiesProps) => {// Set while the change notice that minted this item is still open.unreleasedChangeOrder?: UnreleasedChangeOrderItem | null;}>(path.to.tool(itemId));- const supersession = useResolved(routeDataFromRoute?.supersession, null);- const supersededBy = useResolved(routeDataFromRoute?.supersededBy, null);+ const supersession = useResolved(+ routeDataFromRoute?.supersession,+ null,+ itemId+ );+ const supersededBy = useResolved(+ routeDataFromRoute?.supersededBy,+ null,+ itemId+ );const routeData = data ?? routeDataFromRoute;const locations = data?.locations ?? sharedToolsData?.locations ?? [];diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 3ed394d0bd..6c7b9f0af4 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -18,7 +18,8 @@ import {groupBy,nameSimilarity,scrapAllowance,- tiptapToText+ tiptapToText,+ unchecked} from "@carbon/utils";import type {AssemblyGraph,@@ -3534,7 +3535,6 @@ export async function insertJob(salesOrderLineId?: string;quoteId?: string;quoteLineId?: string;- parentJobId?: string;modelUploadId?: string;notes?: string;customFields?: Json;@@ -3656,7 +3656,6 @@ export async function insertJob(salesOrderLineId: input.salesOrderLineId,quoteId: input.quoteId,quoteLineId: input.quoteLineId,- parentJobId: input.parentJobId,modelUploadId: input.modelUploadId,notes: input.notes,customFields: input.customFields,@@ -3805,7 +3804,6 @@ export async function updateJob(salesOrderLineId?: string | null;quoteId?: string | null;quoteLineId?: string | null;- parentJobId?: string | null;modelUploadId?: string | null;notes?: string | null;customFields?: Json;@@ -3839,12 +3837,14 @@ export async function updateJob(return client.from("job")- .update({- ...sanitize(updates),- ...(priority !== undefined && { priority }),- updatedBy,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ ...sanitize(updates),+ ...(priority !== undefined && { priority }),+ updatedBy,+ updatedAt: new Date().toISOString()+ })+ ).eq("id", id).select("id").single();@@ -4940,17 +4940,15 @@ export async function upsertFailureMode(customFields?: Json;})) {- if ("createdBy" in failureMode) {- return client- .from("maintenanceFailureMode")- .insert([failureMode])- .select("id");- } else {- return client- .from("maintenanceFailureMode")- .update(sanitize(failureMode))- .eq("id", failureMode.id);+ // maintenanceFailureMode has no customFields column.+ const { customFields: _customFields, ...mode } = failureMode;+ if ("createdBy" in mode) {+ return client.from("maintenanceFailureMode").insert([mode]).select("id");}+ return client+ .from("maintenanceFailureMode")+ .update(sanitize(mode))+ .eq("id", mode.id);}export async function upsertMaintenanceDispatch(@@ -10376,7 +10374,7 @@ export async function completeOperation(sanitize({jobOperationId: args.operationId,quantity: args.quantity,- type: "Production",+ type: "Production" as const,companyId,createdBy: userId})diff --git a/apps/erp/app/modules/production/ui/Jobs/JobOperationsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobOperationsTable.tsxindex 9c94ca2f47..5a4e330ed8 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobOperationsTable.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobOperationsTable.tsx@@ -14,6 +14,7 @@ import {HStack,IconButton} from "@carbon/react";+import { unchecked } from "@carbon/utils";import { useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";import { memo, useCallback, useMemo } from "react";@@ -212,10 +213,12 @@ const JobOperationsTable = memo(({ data, count }: JobOperationsTableProps) => {if (!carbon) throw new Error("Carbon client not found");return await carbon.from("jobOperation")- .update({- [id]: value,- updatedBy: userId- })+ .update(+ unchecked({+ [id]: value,+ updatedBy: userId+ })+ ).eq("id", row.id!);},[carbon, userId]diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.tsindex 34a657036b..45f879e717 100644--- a/apps/erp/app/modules/purchasing/purchasing.service.ts+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts@@ -1393,9 +1393,16 @@ export async function updateSupplierContact(return customFieldUpdate;}}+ // The contact id is the row key and the location is set on supplierContact+ // above; neither is a contact column.+ const {+ contactId: _contactId,+ supplierLocationId: _supplierLocationId,+ ...contact+ } = supplierContact.contact;return client.from("contact")- .update(sanitize(supplierContact.contact))+ .update(sanitize(contact)).eq("id", supplierContact.contactId).select("id").single();@@ -1787,9 +1794,16 @@ export async function upsertPurchaseOrder(receiptRequestedDate?: string) {if ("id" in purchaseOrder) {+ // locationId belongs on the delivery record, as in the insert below, and+ // notes are stored as internalNotes/externalNotes.+ const {+ locationId: _locationId,+ notes: _notes,+ ...orderUpdate+ } = purchaseOrder;return client.from("purchaseOrder")- .update(sanitize(purchaseOrder))+ .update(sanitize(orderUpdate)).eq("id", purchaseOrder.id).select("id, purchaseOrderId");}@@ -2432,8 +2446,12 @@ export async function upsertSupplierQuote(if (supplierInteraction.error) return supplierInteraction;- const { companyGroupId: _companyGroupId, ...supplierQuoteData } =- supplierQuote;+ // supplierQuote stores notes as internalNotes/externalNotes, not `notes`.+ const {+ companyGroupId: _companyGroupId,+ notes: _notes,+ ...supplierQuoteData+ } = supplierQuote;const insert = await client.from("supplierQuote").insert([@@ -2505,8 +2523,11 @@ export async function upsertSupplierQuote(supplierQuote.exchangeRate = rate.data;supplierQuote.exchangeRateUpdatedAt = new Date().toISOString();}- const { companyGroupId: _companyGroupId2, ...supplierQuoteUpdateData } =- supplierQuote;+ const {+ companyGroupId: _companyGroupId2,+ notes: _notes,+ ...supplierQuoteUpdateData+ } = supplierQuote;const companyTz = await getCompanyTimeZone(client, companyId);return client.from("supplierQuote")@@ -3195,7 +3216,24 @@ export async function getDefaultAttachmentsForPO(path: `${companyId}/default-attachments/supplier/${supplierId}`});}+ // One listing of the item folder says which items have default attachments+ // at all, so only those are listed. A listing per PO line item, almost+ // always empty, was most of the storage calls a PO page made. A failed+ // listing falls back to checking every item.+ const bucket = storage(client).company(companyId);+ const itemFolders =+ itemIds.length === 0+ ? null+ : await bucket.list(`${companyId}/default-attachments/item`);+ const withAttachments = itemFolders?.error+ ? null+ : new Set(+ (itemFolders?.data ?? [])+ .filter((entry) => entry.id === null)+ .map((entry) => entry.name)+ );for (const id of itemIds ?? []) {+ if (withAttachments && !withAttachments.has(id)) continue;prefixes.push({source: "item",path: `${companyId}/default-attachments/item/${id}`@@ -3203,7 +3241,7 @@ export async function getDefaultAttachmentsForPO(}const results = await Promise.all(- prefixes.map(({ path }) => storage(client).company(companyId).list(path))+ prefixes.map(({ path }) => bucket.list(path)));return results.flatMap((result, idx) => {diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsxindex fc1c57633c..6062ce7f80 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx@@ -61,6 +61,7 @@ import {useSupplierApprovalRequired,useUser} from "~/hooks";+import { useResolved } from "~/hooks/useResolved";import { ReceiptStatus } from "~/modules/inventory/ui/Receipts";import { ShipmentStatus } from "~/modules/inventory/ui/Shipments";import PurchaseInvoicingStatus from "~/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicingStatus";@@ -118,8 +119,13 @@ const PurchaseOrderHeader = () => {canDelete: boolean;defaultCc: string[];supplier: { status: string | null } | null;- resolvedAttachments: ResolvedAttachmentItem[];+ resolvedAttachments: Promise<ResolvedAttachmentItem[]>;}>(path.to.purchaseOrder(orderId));+ const resolvedAttachments = useResolved(+ routeData?.resolvedAttachments,+ [],+ orderId+ );const [suppliers] = useSuppliers();const isSupplierApproved = useMemo(@@ -693,7 +699,7 @@ const PurchaseOrderHeader = () => {purchaseOrder={routeData?.purchaseOrder}onClose={finalizeDisclosure.onClose}defaultCc={routeData?.defaultCc ?? []}- resolvedAttachments={routeData?.resolvedAttachments ?? []}+ resolvedAttachments={resolvedAttachments}/>)}{deleteModal.isOpen && (diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierProcesses.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierProcesses.tsxindex ba85c8458a..7fa9eec49d 100644--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierProcesses.tsx+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierProcesses.tsx@@ -18,7 +18,7 @@ import {IconButton,MENU_ITEM_SHORTCUTS} from "@carbon/react";-import { INPUT_FORMAT } from "@carbon/utils";+import { INPUT_FORMAT, unchecked } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";import { useCallback, useMemo } from "react";@@ -62,10 +62,12 @@ const SupplierProccesses = ({ processes }: SupplierProccessesProps) => {if (!carbon) throw new Error("Carbon client not found");return await carbon.from("supplierProcess")- .update({- [id]: value,- updatedBy: userId- })+ .update(+ unchecked({+ [id]: value,+ updatedBy: userId+ })+ ).eq("id", row.id!);},[carbon, userId]diff --git a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsx b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsxindex e7d83fb78e..e5ac758387 100644--- a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsx+++ b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsx@@ -360,8 +360,13 @@ export default SupplierInteractionDocuments;type OptimisticFileObject = Omit<FileObject,- "owner" | "updated_at" | "created_at" | "last_accessed_at" | "buckets"->;+ | "owner"+ | "updated_at"+ | "created_at"+ | "last_accessed_at"+ | "buckets"+ | "metadata"+> & { metadata: { size: number; mimetype: string } };export const usePendingItems = () => {type PendingItem = ReturnType<typeof useFetchers>[number] & {formData: FormData;diff --git a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineNotes.tsx b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineNotes.tsxindex 6715cdb683..cdbacdd138 100644--- a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineNotes.tsx+++ b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineNotes.tsx@@ -63,7 +63,7 @@ const SupplierInteractionLineNotes = ({const onUpdateExternalNotes = useDebounce(async (content: JSONContent) => {await carbon- ?.from(table)+ ?.from(table as "purchaseOrderLine").update({externalNotes: content,updatedAt: today(getLocalTimeZone()).toString(),@@ -78,7 +78,7 @@ const SupplierInteractionLineNotes = ({const onUpdateInternalNotes = useDebounce(async (content: JSONContent) => {await carbon- ?.from(table)+ ?.from(table as "purchaseOrderLine").update({internalNotes: content,updatedAt: today(getLocalTimeZone()).toString(),diff --git a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionNotes.tsx b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionNotes.tsxindex 27b33b25b8..c3a6cf2bd0 100644--- a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionNotes.tsx+++ b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionNotes.tsx@@ -61,7 +61,7 @@ const SupplierInteractionNotes = ({const onUpdateExternalNotes = useDebounce(async (content: JSONContent) => {await carbon- ?.from(table)+ ?.from(table as "purchaseOrder").update({externalNotes: content,updatedAt: today(getLocalTimeZone()).toString(),@@ -76,7 +76,7 @@ const SupplierInteractionNotes = ({const onUpdateInternalNotes = useDebounce(async (content: JSONContent) => {await carbon- ?.from(table)+ ?.from(table as "purchaseOrder").update({internalNotes: content,updatedAt: today(getLocalTimeZone()).toString(),diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.tsindex 33d9ef19b8..1b9f171133 100644--- a/apps/erp/app/modules/quality/quality.service.ts+++ b/apps/erp/app/modules/quality/quality.service.ts@@ -2142,8 +2142,15 @@ export async function upsertIssue(return result;} else {- // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration- const { items, ...data } = nonConformance;+ // The link fields live on their own tables, as in the insert above.+ const {+ items: _items,+ jobOperationId: _jobOperationId,+ customerId: _customerId,+ salesOrderLineId: _salesOrderLineId,+ operationSupplierProcessId: _operationSupplierProcessId,+ ...data+ } = nonConformance;return client.from("nonConformance").update(sanitize(data))diff --git a/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx b/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsxindex 4cdc1e927f..336c61e3f2 100644--- a/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx+++ b/apps/erp/app/modules/quality/ui/InspectionDocument/InspectionDocumentEditor.tsx@@ -369,6 +369,7 @@ type FeatureMutationFn = (count: null;status: number;statusText: string;+ success: true;}>;const ConditionalMeasurementText =@@ -2551,7 +2552,8 @@ export default function InspectionDocumentEditor({error: null,count: null,status: 200,- statusText: "OK"+ statusText: "OK",+ success: true} as const;},[updateFeatureField]diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsxindex 6e5dc1015f..e3f4166443 100644--- a/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx+++ b/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx@@ -376,8 +376,7 @@ function useTaskNotes({async (content: JSONContent) => {// Update notes in Carbon databaseawait carbon- // @ts-expect-error -- ?.from(table)+ ?.from(table as "nonConformanceActionTask").update({notes: content,updatedBy: userIddiff --git a/apps/erp/app/modules/resources/resources.service.ts b/apps/erp/app/modules/resources/resources.service.tsindex 87765b8e36..f8aaa61197 100644--- a/apps/erp/app/modules/resources/resources.service.ts+++ b/apps/erp/app/modules/resources/resources.service.ts@@ -1339,7 +1339,10 @@ export async function updateAbility(recertifyEveryDays?: number | null;}) {- return client.from("ability").update(ability).eq("id", id);+ return client+ .from("ability")+ .update({ recertifyEveryDays: ability.recertifyEveryDays })+ .eq("id", id);}/**@@ -1546,17 +1549,15 @@ export async function upsertFailureMode(customFields?: Json;})) {- if ("createdBy" in failureMode) {- return client- .from("maintenanceFailureMode")- .insert([failureMode])- .select("id");- } else {- return client- .from("maintenanceFailureMode")- .update(sanitize(failureMode))- .eq("id", failureMode.id);+ // maintenanceFailureMode has no customFields column.+ const { customFields: _customFields, ...mode } = failureMode;+ if ("createdBy" in mode) {+ return client.from("maintenanceFailureMode").insert([mode]).select("id");}+ return client+ .from("maintenanceFailureMode")+ .update(sanitize(mode))+ .eq("id", mode.id);}/** @mcp upsert */diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.tsindex ca07920ab3..f860bafcc1 100644--- a/apps/erp/app/modules/sales/sales.service.ts+++ b/apps/erp/app/modules/sales/sales.service.ts@@ -2185,15 +2185,18 @@ export async function insertSalesOrderLines(customFields?: Json;})[]) {- const linesWithDefaults = salesOrderLines.map((line) => ({- ...line,- setupPrice: line.setupPrice ?? 0,- unitPrice: line.unitPrice ?? 0,- shippingCost: line.shippingCost ?? 0,- addOnCost: line.addOnCost ?? 0,- nonTaxableAddOnCost: line.nonTaxableAddOnCost ?? 0,- taxPercent: line.taxPercent ?? 0- }));+ // salesOrderLine has no serviceId column.+ const linesWithDefaults = salesOrderLines.map(+ ({ serviceId: _serviceId, ...line }) => ({+ ...line,+ setupPrice: line.setupPrice ?? 0,+ unitPrice: line.unitPrice ?? 0,+ shippingCost: line.shippingCost ?? 0,+ addOnCost: line.addOnCost ?? 0,+ nonTaxableAddOnCost: line.nonTaxableAddOnCost ?? 0,+ taxPercent: line.taxPercent ?? 0+ })+ );return client.from("salesOrderLine").insert(linesWithDefaults).select("id");}@@ -3260,9 +3263,16 @@ export async function updateCustomerContact(return customFieldUpdate;}}+ // The contact id is the row key and the location is set on customerContact+ // above; neither is a contact column.+ const {+ contactId: _contactId,+ customerLocationId: _customerLocationId,+ ...contact+ } = customerContact.contact;return client.from("contact")- .update(sanitize(customerContact.contact))+ .update(sanitize(contact)).eq("id", customerContact.contactId).select("id").single();@@ -4114,7 +4124,13 @@ export async function upsertQuote(.eq("id", opportunityId);}- const { companyGroupId: _cgId, ...quoteUpdateData } = quote;+ // quote has no name column, and stores notes as internalNotes/externalNotes.+ const {+ companyGroupId: _cgId,+ name: _name,+ notes: _notes,+ ...quoteUpdateData+ } = quote;return client.from("quote").update({@@ -6315,7 +6331,16 @@ export async function upsertSalesOrder(.eq("id", opportunityId);}- const { companyGroupId: _cgId, ...salesOrderUpdateData } = salesOrder;+ // Dates live on salesOrderShipment, the quote link on the opportunity, and+ // notes as internalNotes/externalNotes; none is a salesOrder column.+ const {+ companyGroupId: _cgId,+ notes: _notes,+ requestedDate: _requestedDate,+ promisedDate: _promisedDate,+ quoteId: _quoteId,+ ...salesOrderUpdateData+ } = salesOrder;return client.from("salesOrder").update(sanitize(salesOrderUpdateData))@@ -6490,9 +6515,11 @@ export async function upsertSalesOrderLine(})) {if ("id" in salesOrderLine) {+ // salesOrderLine has no serviceId column.+ const { serviceId: _serviceId, ...lineUpdate } = salesOrderLine;return client.from("salesOrderLine")- .update(sanitize(salesOrderLine))+ .update(sanitize(lineUpdate)).eq("id", salesOrderLine.id).select("id").single();@@ -6578,10 +6605,12 @@ export async function upsertSalesOrderPayment(customFields?: Json;})) {+ // The currency is the order's; salesOrderPayment has no currencyCode column.if ("id" in salesOrderPayment) {+ const { currencyCode: _currencyCode, ...paymentUpdate } = salesOrderPayment;return client.from("salesOrderPayment")- .update(sanitize(salesOrderPayment))+ .update(sanitize(paymentUpdate)).eq("id", salesOrderPayment.id).select("id").single();diff --git a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsxindex 22be495eca..fd56821d6b 100644--- a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx+++ b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx@@ -222,7 +222,7 @@ const DraggableCell = ({}) => {const context = useDndContext();const { attributes, listeners, setNodeRef, transform } = useDraggable({- id: attachment.id,+ id: attachment.id ?? attachment.name,data: {id: attachment.id,name: attachment.name,@@ -449,8 +449,13 @@ export default OpportunityDocuments;type OptimisticFileObject = Omit<FileObject,- "owner" | "updated_at" | "created_at" | "last_accessed_at" | "buckets"->;+ | "owner"+ | "updated_at"+ | "created_at"+ | "last_accessed_at"+ | "buckets"+ | "metadata"+> & { metadata: { size: number; mimetype: string } };export const usePendingItems = () => {type PendingItem = ReturnType<typeof useFetchers>[number] & {formData: FormData;diff --git a/apps/erp/app/modules/sales/ui/Pricing/PriceOverrideForm.tsx b/apps/erp/app/modules/sales/ui/Pricing/PriceOverrideForm.tsxindex 02924aa5ca..bc6a45c19b 100644--- a/apps/erp/app/modules/sales/ui/Pricing/PriceOverrideForm.tsx+++ b/apps/erp/app/modules/sales/ui/Pricing/PriceOverrideForm.tsx@@ -355,7 +355,8 @@ function PriceBreaks({error: null,count: null,status: 200,- statusText: "OK"+ statusText: "OK",+ success: true}) as const,[]);diff --git a/apps/erp/app/modules/settings/party-contact.server.ts b/apps/erp/app/modules/settings/party-contact.server.tsindex bb9125f78a..b2c96e7401 100644--- a/apps/erp/app/modules/settings/party-contact.server.ts+++ b/apps/erp/app/modules/settings/party-contact.server.ts@@ -4,6 +4,7 @@import type { Database } from "@carbon/database";import { getLogger } from "@carbon/logger";+import { unchecked } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import {missingPartyFacts,@@ -68,12 +69,12 @@ export async function checkPartyContactRequirement(client.from(contactTable).select("contact(email)")- .eq(partyColumn, party.id)+ .eq(unchecked(partyColumn), party.id).eq("companyId", companyId),client.from(locationTable).select("address(countryCode, stateProvince)")- .eq(partyColumn, party.id)+ .eq(unchecked(partyColumn), party.id).eq("companyId", companyId)]);diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.tsindex b0825958b3..ebe0cb6897 100644--- a/apps/erp/app/modules/settings/settings.service.ts+++ b/apps/erp/app/modules/settings/settings.service.ts@@ -852,7 +852,8 @@ export async function insertSubsidiary(isEliminationEntity?: boolean;}) {- const { id: _, ...data } = subsidiary;+ // company has no createdBy column.+ const { id: _, createdBy: _createdBy, ...data } = subsidiary;return client.from("company").insert(data).select("id").single();}diff --git a/apps/erp/app/modules/shared/shared.server.ts b/apps/erp/app/modules/shared/shared.server.tsindex e6745f6d83..444f319bc8 100644--- a/apps/erp/app/modules/shared/shared.server.ts+++ b/apps/erp/app/modules/shared/shared.server.ts@@ -8,6 +8,7 @@ import { storage } from "@carbon/files";import { trigger } from "@carbon/jobs";import { redis } from "@carbon/kv";import { getLogger } from "@carbon/logger";+import { unchecked } from "@carbon/utils";import type { CalendarDate } from "@internationalized/date";import { startOfWeek } from "@internationalized/date";import { renderAsync } from "@react-email/components";@@ -48,8 +49,8 @@ export async function assign(client// @ts-ignore.from(table)- .update({ assignee: assignee ? assignee : null })- .eq("id", id)+ .update(unchecked({ assignee: assignee ? assignee : null }))+ .eq(unchecked("id"), id));}diff --git a/apps/erp/app/modules/shared/types.ts b/apps/erp/app/modules/shared/types.tsindex 4a44e891d7..2dc85a7beb 100644--- a/apps/erp/app/modules/shared/types.ts+++ b/apps/erp/app/modules/shared/types.ts@@ -103,8 +103,13 @@ export type OperationParameter = z.infer<typeof operationParameterValidator> & {};export type OptimisticFileObject = Omit<StorageItem,- "owner" | "updated_at" | "created_at" | "last_accessed_at" | "buckets"->;+ | "owner"+ | "updated_at"+ | "created_at"+ | "last_accessed_at"+ | "buckets"+ | "metadata"+> & { metadata: { size: number; mimetype: string } };export type QuantityEffect = (quantity: number) => number;diff --git a/apps/erp/app/modules/users/users.server.ts b/apps/erp/app/modules/users/users.server.tsindex beeea86129..dd72ee389d 100644--- a/apps/erp/app/modules/users/users.server.ts+++ b/apps/erp/app/modules/users/users.server.ts@@ -1332,12 +1332,12 @@ async function rollbackInvite(serviceRole.from("customerAccount").delete()- .eq("userId", userId)+ .eq("id", userId).eq("companyId", companyId),serviceRole.from("supplierAccount").delete()- .eq("userId", userId)+ .eq("id", userId).eq("companyId", companyId)]);}diff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsxindex d236824433..be794aaa09 100644--- a/apps/erp/app/root.tsx+++ b/apps/erp/app/root.tsx@@ -17,6 +17,7 @@ import {requestContextMiddleware,requestIdMiddleware} from "@carbon/logger/middleware.server";+import { namedMiddleware } from "@carbon/logger/tracing.server";import {OperatingSystemContextProvider,Toaster,@@ -64,13 +65,13 @@ import "@carbon/lib/shims";import type { Route } from "./+types/root";import { getTheme } from "./services/theme.server";-export const middleware = [+export const middleware = namedMiddleware([// First: publishes the request context so server code can reach it via ALS.requestContextMiddleware,requestIdMiddleware,securityMiddleware,flashMiddleware-];+]);export const clientMiddleware = [flashClientMiddleware];export const links: LinksFunction = () => {diff --git a/apps/erp/app/routes/api+/inngest.ts b/apps/erp/app/routes/api+/inngest.tsindex 81d216aeb6..e09e1c43a5 100644--- a/apps/erp/app/routes/api+/inngest.ts+++ b/apps/erp/app/routes/api+/inngest.ts@@ -3,23 +3,15 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { functions, inngest, setWorkflowDispatch } from "@carbon/jobs/inngest";+import { describeRequest } from "@carbon/logger/middleware.server";+import {+ annotateRequestSpan,+ nameRequestSpan+} from "@carbon/logger/tracing.server";import { serve } from "inngest/remix";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { callOperation } from "./v1+/lib/call.server";-/**- * Inngest API endpoint.- *- * Supports two modes via INNGEST_MODE env var:- * - "serve" (default): Handle function execution via HTTP- * - "connect": Return info message, execution handled by worker- *- * In "connect" mode, this endpoint still serves function discovery- * but actual execution happens via the WebSocket worker.- */--// const mode = process.env.INNGEST_MODE?.toLowerCase() || "serve";-const handler = serve({client: inngest,functions,@@ -28,6 +20,14 @@ const handler = serve({serveHost: process.env.INNGEST_SERVE_HOST || process.env.ERP_URL});+// As Inngest addresses them: `<app>-<function>`, plus the failure handler's.+const functionIds = new Set(+ functions.flatMap((fn) => {+ const id = fn.id(inngest.id);+ return [id, `${id}-failure`];+ })+);+// packages/jobs cannot import ~/modules, so the ERP app hands it the dispatcher.// Wired on first request rather than at module scope: a top-level side effect is// not removable by the client build, which would drag the server-only jobs graph@@ -43,7 +43,6 @@ function wireWorkflowDispatch() {dispatchWired = true;}-// In connect mode, we still serve for discovery but can log/track differentlyexport function loader(args: LoaderFunctionArgs) {wireWorkflowDispatch();return handler(args);@@ -51,5 +50,19 @@ export function loader(args: LoaderFunctionArgs) {export function action(args: ActionFunctionArgs) {wireWorkflowDispatch();+ // Every function and step arrives on this one route, so without these the+ // trace cannot say which function the time went to.+ const { searchParams } = new URL(args.request.url);+ const functionId = searchParams.get("fnId");+ annotateRequestSpan({+ "inngest.function.id": functionId ?? undefined,+ "inngest.step.id": searchParams.get("stepId") ?? undefined+ });+ // Inngest only calls functions it registered, but the query string is the+ // caller's: an id that is not ours stays out of the span name.+ if (functionId && functionIds.has(functionId)) {+ nameRequestSpan(`${args.request.method} /api/inngest ${functionId}`);+ describeRequest(functionId);+ }return handler(args);}diff --git a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.tsindex 83d21c9c9f..1a068f6515 100644--- a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts+++ b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts@@ -214,10 +214,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {periods.map((p) => p.id ?? ""));- if (demand.actuals.length === 0 && demandForecast.length === 0) {+ // An item with no demand yet is not a failure: it still has stock and+ // supply to chart.+ if (demand.error) {return data(defaultResponse,- await flash(request, error(null, "Failed to load demand"))+ await flash(request, error(demand.error, "Failed to load demand")));}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 e2aa5cb296..92c4a83094 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@@ -162,7 +162,7 @@{"name":"inventory_deleteShippingMethod","classification":"DESTRUCTIVE","paramCount":1,"schema":"493e990b5f3d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},{"name":"inventory_deleteStockTransfer","classification":"DESTRUCTIVE","paramCount":1,"schema":"38111ae0fa2a","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},{"name":"inventory_deleteStockTransferLine","classification":"DESTRUCTIVE","paramCount":1,"schema":"0bbd6a946791","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},- {"name":"inventory_deleteStorageTypeWithCascade","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"567547d42955","injectAuth":"companyId","permission":"inventory:delete","paginates":false},+ {"name":"inventory_deleteStorageTypeWithCascade","classification":"DESTRUCTIVE","paramCount":1,"schema":"3797626bd17e","response":"210a2a62676d","injectAuth":"companyId","permission":"inventory:delete","paginates":false},{"name":"inventory_deleteStorageUnit","classification":"DESTRUCTIVE","paramCount":1,"schema":"c728bf7e5b37","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},{"name":"inventory_deleteStorageUnitCascade","classification":"DESTRUCTIVE","paramCount":1,"schema":"c728bf7e5b37","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},{"name":"inventory_deleteWarehouseTransfer","classification":"DESTRUCTIVE","paramCount":1,"schema":"d51f098ead24","response":"bcde375ebd4c","injectAuth":"companyId","permission":"inventory:delete","paginates":false},@@ -258,7 +258,7 @@{"name":"inventory_mergeTrackedEntities","classification":"WRITE","paramCount":2,"schema":"b12fee74a91e","response":"eeecb06dc790","injectAuth":"companyId+userId","permission":"inventory:update","paginates":false},{"name":"inventory_pickPickingListLine","classification":"WRITE","paramCount":3,"schema":"0371c6fecc9c","response":"3797626bd17e","injectAuth":"companyId+userId","permission":"inventory:update","paginates":false},{"name":"inventory_reconcileReceiptSerialEntities","classification":"DESTRUCTIVE","paramCount":2,"schema":"317d393d5b4a","response":"none","injectAuth":"companyId","permission":"inventory:update","paginates":false},- {"name":"inventory_searchStorageUnitsWithAncestors","classification":"READ","paramCount":2,"schema":"bf8906da76a5","response":"04385ce721d8","injectAuth":"companyId","permission":"inventory:view","paginates":false},+ {"name":"inventory_searchStorageUnitsWithAncestors","classification":"READ","paramCount":2,"schema":"bf8906da76a5","response":"1ef4111538b5","injectAuth":"companyId","permission":"inventory:view","paginates":false},{"name":"inventory_setPickingListLineTrackedEntity","classification":"WRITE","paramCount":5,"schema":"a628dabab831","response":"3797626bd17e","injectAuth":"companyId+updatedBy+userId","permission":"inventory:update","paginates":false},{"name":"inventory_updateBatchPropertyOrder","classification":"WRITE","paramCount":3,"schema":"ed0f513719d1","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false},{"name":"inventory_updateInventoryCountLine","classification":"WRITE","paramCount":3,"schema":"d0dcc5796dc7","response":"ae8f99e1d130","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false},@@ -407,8 +407,8 @@{"name":"items_getItemCostHistory","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"37830a1bad13","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemCustomerPart","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"4c6e08919580","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemCustomerParts","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"458a8cdb47f2","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemDemand","classification":"READ","paramCount":3,"schema":"ba3de97105ef","response":"a45dda8bd7a2","injectAuth":"companyId","permission":"parts:view","paginates":false},- {"name":"items_getItemFiles","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"c8f657a900dd","injectAuth":"companyId","permission":"parts:view","paginates":false},+ {"name":"items_getItemDemand","classification":"READ","paramCount":3,"schema":"ba3de97105ef","response":"fe98aa635e85","injectAuth":"companyId","permission":"parts:view","paginates":false},+ {"name":"items_getItemFiles","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"ffefd03548aa","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemManufacturing","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"f399bb7eda67","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemMpnsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3ff28fd20707","injectAuth":"companyId","permission":"parts:view","paginates":false},{"name":"items_getItemPlanning","classification":"READ","paramCount":2,"schema":"ade4704d7338","response":"dd5cfe4cf204","injectAuth":"companyId","permission":"parts:view","paginates":false},@@ -504,9 +504,9 @@{"name":"items_updateItem","classification":"WRITE","paramCount":18,"schema":"f24ba73701ab","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},{"name":"items_updateItemCost","classification":"WRITE","paramCount":2,"schema":"c55de757a7e4","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},{"name":"items_updateItemMethodAndSourcing","classification":"WRITE","paramCount":3,"schema":"1165eb54378a","response":"none","injectAuth":"companyId+updatedBy+userId","permission":"parts:update","paginates":false},- {"name":"items_updateMaterialOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},+ {"name":"items_updateMaterialOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},{"name":"items_updateMaterialProperties","classification":"WRITE","paramCount":7,"schema":"ba2c8db7ad05","response":"82322ed42796","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},- {"name":"items_updateOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},+ {"name":"items_updateOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},{"name":"items_updateRevision","classification":"WRITE","paramCount":2,"schema":"25c295d358ea","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"parts:update","paginates":false},{"name":"items_upsertChangeNoticeRequiredAction","classification":"WRITE","paramCount":3,"schema":"e790518da1ff","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"parts:create+update","paginates":false},{"name":"items_upsertChangeNoticeType","classification":"WRITE","paramCount":1,"schema":"a91f73f30ea3","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"parts:create+update","paginates":false,"upsert":"id"},@@ -568,11 +568,11 @@{"name":"people_getEmployeeSummary","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"afd28b3efe9e","injectAuth":"companyId","permission":"people:view","paginates":false},{"name":"people_getHoliday","classification":"READ","paramCount":1,"schema":"9189cc10f756","response":"8d2b62b6a13b","injectAuth":"companyId","permission":"people:view","paginates":false},{"name":"people_getHolidays","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"1fedcd5adb59","injectAuth":"companyId","permission":"people:view","paginates":true},- {"name":"people_getHolidayYears","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"88a9d1fc3d35","injectAuth":"companyId","permission":"people:view","paginates":false},+ {"name":"people_getHolidayYears","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f3764070545e","injectAuth":"companyId","permission":"people:view","paginates":false},{"name":"people_getOpenClockEntry","classification":"READ","paramCount":1,"schema":"3d90cb5d0437","response":"48d1ac3381b4","injectAuth":"companyId","permission":"people:view","paginates":false},{"name":"people_getPeople","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"5483e69d7515","injectAuth":"companyId","permission":"people:view","paginates":false},{"name":"people_getRecentTimecards","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"579660621675","injectAuth":"companyId","permission":"people:view","paginates":false},- {"name":"people_getScheduledEmployeesToday","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"c93c10ff0dbe","injectAuth":"companyId","permission":"people:view","paginates":false},+ {"name":"people_getScheduledEmployeesToday","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"c429622c953e","injectAuth":"companyId","permission":"people:view","paginates":false},{"name":"people_getShift","classification":"READ","paramCount":1,"schema":"fbdb1fa56a88","response":"86e4039d95bd","injectAuth":"companyId","permission":"people:view","paginates":false},{"name":"people_getShifts","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"92fec9db1b7e","injectAuth":"companyId","permission":"people:view","paginates":true},{"name":"people_getShiftsList","classification":"READ","paramCount":1,"schema":"b76e1039273f","response":"ce08332e0ce6","injectAuth":"companyId","permission":"people:view","paginates":false},@@ -586,7 +586,7 @@{"name":"people_insertEmployeeJob","classification":"WRITE","paramCount":2,"schema":"8518dfd7feec","response":"4a3b9b98079b","injectAuth":"companyId+updatedBy","permission":"people:create","paginates":false},{"name":"people_updateAttribute","classification":"WRITE","paramCount":4,"schema":"f66dbb270538","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false},{"name":"people_updateAttributeCategory","classification":"WRITE","paramCount":4,"schema":"7bf8c03306de","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false},- {"name":"people_updateAttributeSortOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false},+ {"name":"people_updateAttributeSortOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false},{"name":"people_updateEmployeeJob","classification":"DESTRUCTIVE","paramCount":2,"schema":"fd3a2eef5bc2","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false},{"name":"people_updateTimeCardEntry","classification":"WRITE","paramCount":4,"schema":"486c249ce3fa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"people:update","paginates":false},{"name":"people_upsertDepartment","classification":"WRITE","paramCount":4,"schema":"0008ef42654d","response":"10600fcaa49e","injectAuth":"companyId+createdBy+updatedBy","permission":"people:create+update","paginates":false},@@ -698,7 +698,7 @@{"name":"production_getJobsByDateRange","classification":"READ","paramCount":3,"schema":"00794c516592","response":"737259a0d747","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getJobsBySalesOrderLine","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"630059095fdc","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getJobsList","classification":"READ","paramCount":1,"schema":"6168fc8fbdbe","response":"232ee7305e73","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getLatestAssemblyPlan","classification":"READ","paramCount":1,"schema":"277f7d872d8c","response":"c15540ea30a1","injectAuth":"companyId","permission":"production:view","paginates":false},+ {"name":"production_getLatestAssemblyPlan","classification":"READ","paramCount":1,"schema":"277f7d872d8c","response":"6b38ef1e4ead","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getLatestAssemblyPlanJob","classification":"READ","paramCount":1,"schema":"277f7d872d8c","response":"d45b1cde8dd5","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getLocationEmployees","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"72ccccdcfc21","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getMaintenanceDispatch","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"f0addd41ad4e","injectAuth":"companyId","permission":"production:view","paginates":false},@@ -707,7 +707,7 @@{"name":"production_getMaintenanceDispatchEvents","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"fc0af15629d8","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getMaintenanceDispatchItems","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"7d22c1b8235d","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getMaintenanceDispatchWorkCenters","classification":"READ","paramCount":1,"schema":"34cb412f1fae","response":"245d61ef36d3","injectAuth":"companyId","permission":"production:view","paginates":false},- {"name":"production_getMaintenanceDowntimeForResources","classification":"READ","paramCount":1,"schema":"935cc20961b6","response":"1bd2fbd329dd","injectAuth":"companyId","permission":"production:view","paginates":false},+ {"name":"production_getMaintenanceDowntimeForResources","classification":"READ","paramCount":1,"schema":"935cc20961b6","response":"c9ce440846e1","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getMaintenanceSchedule","classification":"READ","paramCount":1,"schema":"c61245800a33","response":"d794f5e4efb7","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getMaintenanceScheduleItems","classification":"READ","paramCount":1,"schema":"c61245800a33","response":"6e7c564b202a","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getMaintenanceSchedules","classification":"READ","paramCount":4,"schema":"b48b875ac337","response":"80c9953d43e5","injectAuth":"companyId","permission":"production:view","paginates":true},@@ -746,7 +746,7 @@{"name":"production_getWorkCenterReservationsRange","classification":"READ","paramCount":2,"schema":"99ea73b8e7a1","response":"a7e9bc09d2ab","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_getWorkCenterShifts","classification":"READ","paramCount":1,"schema":"e94892850934","response":"2b4835f80e6c","injectAuth":"companyId","permission":"production:view","paginates":false},{"name":"production_insertAssemblyInstructionStep","classification":"WRITE","paramCount":1,"schema":"432e9ed9373b","response":"00404e686415","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"production:create","paginates":false},- {"name":"production_insertJob","classification":"WRITE","paramCount":2,"schema":"fea224e085b1","response":"ad63dfd9d877","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},+ {"name":"production_insertJob","classification":"WRITE","paramCount":2,"schema":"6a0dadd45560","response":"ad63dfd9d877","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create","paginates":false},{"name":"production_invalidateAssemblyModelCache","classification":"DESTRUCTIVE","paramCount":1,"schema":"277f7d872d8c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"production:update","paginates":false},{"name":"production_makeAssemblySubAssembly","classification":"WRITE","paramCount":2,"schema":"e39572ccf46c","response":"00404e686415","injectAuth":"companyId+userId","permission":"production:update","paginates":false},{"name":"production_maxToolQuantityByItem","classification":"READ","paramCount":1,"schema":"8b9e90037b9a","response":"none","injectAuth":"companyId","permission":"production:view","paginates":false},@@ -782,19 +782,19 @@{"name":"production_updateAssemblyStepHiddenComponents","classification":"WRITE","paramCount":3,"schema":"3ac4e88c4df0","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateAssemblyStepMotion","classification":"WRITE","paramCount":3,"schema":"6665a9b53a17","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateAssemblySubAssembly","classification":"WRITE","paramCount":4,"schema":"0f0cbf9e32e1","response":"none","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_updateJob","classification":"WRITE","paramCount":21,"schema":"e224c0a5aa29","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},+ {"name":"production_updateJob","classification":"WRITE","paramCount":20,"schema":"769ff9d7f4ac","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateJobBatchNumber","classification":"WRITE","paramCount":2,"schema":"a4c2a31bb8a6","response":"f7a40899c090","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateJobMaterialOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},+ {"name":"production_updateJobMaterialOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateJobOperationBatch","classification":"WRITE","paramCount":4,"schema":"6aa26c8c9567","response":"none","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},{"name":"production_updateJobOperationDueDate","classification":"WRITE","paramCount":2,"schema":"e04478fc58f7","response":"ac4a3201b981","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateJobOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},+ {"name":"production_updateJobOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateJobOperationStatus","classification":"WRITE","paramCount":2,"schema":"b22654081076","response":"ac4a3201b981","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateJobOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},+ {"name":"production_updateJobOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateJobStatus","classification":"WRITE","paramCount":3,"schema":"bb0874693c4d","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateKanbanJob","classification":"WRITE","paramCount":2,"schema":"2c22838be2d2","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},- {"name":"production_updateMethodOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateProcedureStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},- {"name":"production_updateQuoteOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},+ {"name":"production_updateMethodOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},+ {"name":"production_updateProcedureStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},+ {"name":"production_updateQuoteOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_upsertAssemblyComponentMapping","classification":"WRITE","paramCount":4,"schema":"9ed1f38ce764","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},{"name":"production_upsertAssemblyInstruction","classification":"WRITE","paramCount":4,"schema":"a1796f1bd347","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},{"name":"production_upsertAssemblyInstructionStep","classification":"WRITE","paramCount":1,"schema":"224cc2443995","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"production:create+update","paginates":false},@@ -889,8 +889,8 @@{"name":"purchasing_getSupplierContact","classification":"READ","paramCount":1,"schema":"bc2c630a873e","response":"6d2aa722b1ce","injectAuth":"companyId","permission":"purchasing:view","paginates":false},{"name":"purchasing_getSupplierContacts","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"e28ccbd2c417","injectAuth":"companyId","permission":"purchasing:view","paginates":false},{"name":"purchasing_getSupplierInteraction","classification":"READ","paramCount":1,"schema":"5e54451f6705","response":"e933ede17ac0","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierInteractionDocuments","classification":"READ","paramCount":1,"schema":"2df4b3d111cd","response":"18998cbb23b4","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierInteractionLineDocuments","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"18998cbb23b4","injectAuth":"companyId","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierInteractionDocuments","classification":"READ","paramCount":1,"schema":"2df4b3d111cd","response":"95c1c04c0566","injectAuth":"companyId","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierInteractionLineDocuments","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"95c1c04c0566","injectAuth":"companyId","permission":"purchasing:view","paginates":false},{"name":"purchasing_getSupplierLocation","classification":"READ","paramCount":1,"schema":"bc2c630a873e","response":"4603d06d1055","injectAuth":"companyId","permission":"purchasing:view","paginates":false},{"name":"purchasing_getSupplierLocations","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"6dad1063175d","injectAuth":"companyId","permission":"purchasing:view","paginates":false},{"name":"purchasing_getSupplierPayment","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"24b286adf1ff","injectAuth":"companyId","permission":"purchasing:view","paginates":false},@@ -907,7 +907,7 @@{"name":"purchasing_getSupplierQuotes","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"9e311e59b82e","injectAuth":"companyId","permission":"purchasing:view","paginates":true},{"name":"purchasing_getSupplierQuotesForComparison","classification":"READ","paramCount":1,"schema":"4e16cef99961","response":"540207b2c74e","injectAuth":"companyId","permission":"purchasing:view","paginates":false},{"name":"purchasing_getSupplierQuotesList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"967dcad15168","injectAuth":"companyId","permission":"purchasing:view","paginates":false},- {"name":"purchasing_getSupplierReportContacts","classification":"READ","paramCount":1,"schema":"f6d6276b4996","response":"3a10d699a924","injectAuth":"companyId","permission":"purchasing:view","paginates":false},+ {"name":"purchasing_getSupplierReportContacts","classification":"READ","paramCount":1,"schema":"f6d6276b4996","response":"40779b8d3971","injectAuth":"companyId","permission":"purchasing:view","paginates":false},{"name":"purchasing_getSuppliers","classification":"READ","paramCount":5,"schema":"3fbb04d0ef7e","response":"947b627d845e","injectAuth":"companyId","permission":"purchasing:view","paginates":true},{"name":"purchasing_getSupplierShipping","classification":"READ","paramCount":1,"schema":"67043a31b1b5","response":"17117a952d24","injectAuth":"companyId","permission":"purchasing:view","paginates":false},{"name":"purchasing_getSuppliersList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"purchasing:view","paginates":false},@@ -1000,7 +1000,7 @@{"name":"quality_getIssueReviewers","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"fa7631f38515","injectAuth":"companyId","permission":"quality:view","paginates":false},{"name":"quality_getIssues","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"e08ce0758580","injectAuth":"companyId","permission":"quality:view","paginates":true},{"name":"quality_getIssueSuppliers","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"2a7e42e2f8c2","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getIssueTasks","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"4a4afab580ba","injectAuth":"companyId","permission":"quality:view","paginates":false},+ {"name":"quality_getIssueTasks","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"1071578b0d70","injectAuth":"companyId","permission":"quality:view","paginates":false},{"name":"quality_getIssueType","classification":"READ","paramCount":1,"schema":"bb6b04f68710","response":"63b5b3f8f143","injectAuth":"companyId","permission":"quality:view","paginates":false},{"name":"quality_getIssueTypeByName","classification":"READ","paramCount":2,"schema":"858a6cb73bbb","response":"3797626bd17e","injectAuth":"companyId","permission":"quality:view","paginates":false},{"name":"quality_getIssueTypes","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"95195653f3fc","injectAuth":"companyId","permission":"quality:view","paginates":true},@@ -1015,7 +1015,7 @@{"name":"quality_getQualityDocumentsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"f0df86b695e6","injectAuth":"companyId","permission":"quality:view","paginates":false},{"name":"quality_getQualityDocumentSteps","classification":"READ","paramCount":1,"schema":"6d79e6870690","response":"55202747c3b2","injectAuth":"companyId","permission":"quality:view","paginates":false},{"name":"quality_getQualityDocumentVersions","classification":"READ","paramCount":2,"schema":"89111eab017d","response":"63e52c70cbef","injectAuth":"companyId","permission":"quality:view","paginates":false},- {"name":"quality_getQualityFiles","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"c8f657a900dd","injectAuth":"companyId","permission":"quality:view","paginates":false},+ {"name":"quality_getQualityFiles","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"ffefd03548aa","injectAuth":"companyId","permission":"quality:view","paginates":false},{"name":"quality_getReceiptInspections","classification":"READ","paramCount":1,"schema":"e00a9764517d","response":"e30d015c0242","injectAuth":"companyId","permission":"quality:view","paginates":false},{"name":"quality_getRequiredAction","classification":"READ","paramCount":1,"schema":"cca3bf9f3ebb","response":"00f7e228e469","injectAuth":"companyId","permission":"quality:view","paginates":false},{"name":"quality_getRequiredActions","classification":"READ","paramCount":3,"schema":"04eded31eebb","response":"477e4aa9ac3b","injectAuth":"companyId","permission":"quality:view","paginates":true},@@ -1119,7 +1119,7 @@{"name":"resources_updateAbility","classification":"WRITE","paramCount":2,"schema":"331c98a989f9","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"resources:update","paginates":false},{"name":"resources_updateMaintenanceDispatch","classification":"WRITE","paramCount":18,"schema":"02877e9f1f8d","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"resources:update","paginates":false},{"name":"resources_updateSuggestionEmoji","classification":"WRITE","paramCount":2,"schema":"dc61bce0f764","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:update","paginates":false},- {"name":"resources_updateTrainingQuestionOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"resources:update","paginates":false},+ {"name":"resources_updateTrainingQuestionOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"resources:update","paginates":false},{"name":"resources_upsertContractor","classification":"DESTRUCTIVE","paramCount":1,"schema":"6630f8761e37","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"contractor(id)"},{"name":"resources_upsertEmployeeAbilityCell","classification":"WRITE","paramCount":4,"schema":"800b78f5bbae","response":"3797626bd17e","injectAuth":"companyId","permission":"resources:create+update","paginates":false},{"name":"resources_upsertFailureMode","classification":"WRITE","paramCount":4,"schema":"e4d170d8f468","response":"8394fbabd845","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create+update","paginates":false,"upsert":"id"},@@ -1206,8 +1206,8 @@{"name":"sales_getNoQuoteReasonsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"sales:view","paginates":false},{"name":"sales_getOpenSalesOrderLinesForItem","classification":"READ","paramCount":1,"schema":"623ca47a6c74","response":"334d8429d21a","injectAuth":"companyId","permission":"sales:view","paginates":false},{"name":"sales_getOpportunity","classification":"READ","paramCount":1,"schema":"5e54451f6705","response":"cdaf9ce57087","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getOpportunityDocuments","classification":"READ","paramCount":1,"schema":"a4fcfa20a027","response":"18998cbb23b4","injectAuth":"companyId","permission":"sales:view","paginates":false},- {"name":"sales_getOpportunityLineDocuments","classification":"READ","paramCount":2,"schema":"067400ea63f8","response":"18998cbb23b4","injectAuth":"companyId","permission":"sales:view","paginates":false},+ {"name":"sales_getOpportunityDocuments","classification":"READ","paramCount":1,"schema":"a4fcfa20a027","response":"95c1c04c0566","injectAuth":"companyId","permission":"sales:view","paginates":false},+ {"name":"sales_getOpportunityLineDocuments","classification":"READ","paramCount":2,"schema":"067400ea63f8","response":"95c1c04c0566","injectAuth":"companyId","permission":"sales:view","paginates":false},{"name":"sales_getPricingRule","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"2a1e20313f8b","injectAuth":"companyId","permission":"sales:view","paginates":false},{"name":"sales_getPricingRules","classification":"READ","paramCount":3,"schema":"cae7e7e05408","response":"f3613d31804a","injectAuth":"companyId","permission":"sales:view","paginates":true},{"name":"sales_getQuote","classification":"READ","paramCount":1,"schema":"c726ae407913","response":"ee5f623bf074","injectAuth":"companyId","permission":"sales:view","paginates":false},@@ -1283,7 +1283,7 @@{"name":"sales_insertSalesOrder","classification":"WRITE","paramCount":17,"schema":"b76b79d52d88","response":"dbfc22813350","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},{"name":"sales_insertSalesReturnOrder","classification":"WRITE","paramCount":12,"schema":"307356313ba5","response":"c32485518acd","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},{"name":"sales_insertSalesRFQ","classification":"WRITE","paramCount":13,"schema":"5a54a12e500f","response":"0c1a1b93cca3","injectAuth":"companyId+createdBy+updatedBy","permission":"sales:create","paginates":false},- {"name":"sales_recalculateQuoteLinePrices","classification":"WRITE","paramCount":2,"schema":"55ee981d3d94","response":"6db20595d1b7","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},+ {"name":"sales_recalculateQuoteLinePrices","classification":"WRITE","paramCount":2,"schema":"55ee981d3d94","response":"bef3efeea4ce","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},{"name":"sales_releaseSalesOrder","classification":"WRITE","paramCount":1,"schema":"d160a49d6787","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},{"name":"sales_reopenSalesReturnOrder","classification":"WRITE","paramCount":1,"schema":"3797626bd17e","response":"none","injectAuth":"companyId+userId","permission":"sales:update","paginates":false},{"name":"sales_repriceQuoteLineFromRules","classification":"WRITE","paramCount":2,"schema":"55ee981d3d94","response":"bcde375ebd4c","injectAuth":"companyId","permission":"sales:update","paginates":false},@@ -1303,8 +1303,8 @@{"name":"sales_updateQuoteExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},{"name":"sales_updateQuoteLineOrder","classification":"WRITE","paramCount":2,"schema":"fce9a5d72ad3","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},{"name":"sales_updateQuoteLinePrecision","classification":"WRITE","paramCount":3,"schema":"90f52ec96806","response":"none","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateQuoteMaterialOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},- {"name":"sales_updateQuoteOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteMaterialOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},+ {"name":"sales_updateQuoteOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},{"name":"sales_updateQuoteStatus","classification":"WRITE","paramCount":3,"schema":"35467c4f9528","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},{"name":"sales_updateSalesOrder","classification":"WRITE","paramCount":9,"schema":"d9b815fe7f4c","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},{"name":"sales_updateSalesOrderExchangeRate","classification":"WRITE","paramCount":2,"schema":"bca4d06461aa","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"sales:update","paginates":false},@@ -1451,7 +1451,7 @@{"name":"shared_lookupPriceFromBreaks","classification":"READ","paramCount":3,"schema":"14f107043636","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_resolveBuyUnitCost","classification":"WRITE","paramCount":3,"schema":"4c58915f44dd","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_resolveSupplierPrice","classification":"READ","paramCount":4,"schema":"c92834c91ef5","response":"cddf8275afa1","injectAuth":"companyId","permission":"none","paginates":false},- {"name":"shared_updateSavedViewOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"ce209a810cd2","injectAuth":"companyId+updatedBy","permission":"none","paginates":false},+ {"name":"shared_updateSavedViewOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"none","paginates":false},{"name":"shared_upsertExternalLink","classification":"WRITE","paramCount":1,"schema":"33e54e07795a","response":"3797626bd17e","injectAuth":"companyId","permission":"none","paginates":false},{"name":"shared_upsertSavedView","classification":"WRITE","paramCount":10,"schema":"88a0b7dfec62","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"none","paginates":false},{"name":"users_deleteGroup","classification":"DESTRUCTIVE","paramCount":1,"schema":"c4dcdfdf8647","response":"bcde375ebd4c","injectAuth":"companyId","permission":"users:delete","paginates":false},@@ -1480,8 +1480,8 @@{"name":"users_getUserSelectGroups","classification":"READ","paramCount":4,"schema":"b459d00208b5","response":"51b54791b40a","injectAuth":"companyId","permission":"users:view","paginates":false},{"name":"users_getUsersWithVerifiedMfa","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"4c1fdc714231","injectAuth":"companyId","permission":"users:view","paginates":false},{"name":"users_insertGroup","classification":"WRITE","paramCount":1,"schema":"098974972159","response":"06c8b45796ca","injectAuth":"companyId","permission":"users:create","paginates":false},- {"name":"users_resolveUserSelectIds","classification":"WRITE","paramCount":1,"schema":"0eb0c2be01ed","response":"62ac845cad71","injectAuth":"companyId","permission":"users:update","paginates":false},- {"name":"users_searchUsersForSelect","classification":"READ","paramCount":4,"schema":"230b4891a4e5","response":"80d2a04ba04a","injectAuth":"companyId+userId","permission":"users:view","paginates":false},+ {"name":"users_resolveUserSelectIds","classification":"WRITE","paramCount":1,"schema":"0eb0c2be01ed","response":"7fdfa4c9e77e","injectAuth":"companyId","permission":"users:update","paginates":false},+ {"name":"users_searchUsersForSelect","classification":"READ","paramCount":4,"schema":"230b4891a4e5","response":"c9c1df9c3e28","injectAuth":"companyId+userId","permission":"users:view","paginates":false},{"name":"users_upsertGroup","classification":"WRITE","paramCount":2,"schema":"f06d2d858884","response":"bcde375ebd4c","injectAuth":"companyId","permission":"users:create+update","paginates":false},{"name":"users_upsertGroupMembers","classification":"DESTRUCTIVE","paramCount":2,"schema":"b32a69080685","response":"bcde375ebd4c","injectAuth":"companyId","permission":"users:create+update","paginates":false}]diff --git a/apps/erp/app/routes/api+/v1+/$.ts b/apps/erp/app/routes/api+/v1+/$.tsindex 58c82358cf..0a58379b09 100644--- a/apps/erp/app/routes/api+/v1+/$.ts+++ b/apps/erp/app/routes/api+/v1+/$.ts@@ -9,6 +9,7 @@// Every operation is a POST. The splat forwards the request to the oRPC OpenAPIHandler// after resolving the API key into context. No CORS: keys must not live in browsers.+import { nameRequestSpan } from "@carbon/logger/tracing.server";import type { ActionFunctionArgs } from "react-router";import { resolveApiKeyContext } from "./lib/authenticate.server";import { openApiHandler } from "./lib/handler.server";@@ -28,7 +29,11 @@ export async function action({ request }: ActionFunctionArgs) {context});- if (matched && response) return response;+ if (matched && response) {+ // The route pattern is `/api/v1/*`; a matched path names a real operation.+ nameRequestSpan(`POST ${new URL(request.url).pathname}`);+ return response;+ }return Response.json({ error: "Operation not found" }, { status: 404 });}diff --git a/apps/erp/app/routes/api+/v1+/lib/router.server.ts b/apps/erp/app/routes/api+/v1+/lib/router.server.tsindex 7d56423149..654451566f 100644--- a/apps/erp/app/routes/api+/v1+/lib/router.server.ts+++ b/apps/erp/app/routes/api+/v1+/lib/router.server.ts@@ -8,6 +8,7 @@import type { ManifestEntry } from "@carbon/api";import { jsonSchema, jsonSchemaInput } from "@carbon/api/schema";+import { annotateRequestSpan, withSpan } from "@carbon/logger/tracing.server";import { base, gate, mapThrownErrors } from "./base.server";import { dispatchOperation } from "./dispatch.server";import {@@ -28,6 +29,18 @@ const RESERVED_KEYS = new Set(["toJSON"]);+// Every caller (HTTP, MCP call_tool, the agent, workflows) runs an operation+// through its procedure, so this is the one place a trace learns its name.+const traced = (meta: ManifestEntry) =>+ base.middleware(({ next }) => {+ const attributes = {+ "carbon.operation": meta.name,+ "carbon.operation.module": meta.module+ };+ annotateRequestSpan(attributes);+ return withSpan(`operation ${meta.name}`, attributes, async () => next());+ });+// `module`/`id` name the route; `meta` is the operation it runs. They differ only// for a deprecated alias, which keeps its old path but runs (and is gated as) its// replacement.@@ -39,6 +52,7 @@ function buildProcedure() {return (base+ .use(traced(meta))// Outside the gate so it also covers anything the gate itself throws// through — it re-raises ORPCErrors untouched, so 403s/404s are unaffected..use(mapThrownErrors)diff --git a/apps/erp/app/routes/file+/model+/public.$.tsx b/apps/erp/app/routes/file+/model+/public.$.tsxindex 8eb8664265..9adc927be1 100644--- a/apps/erp/app/routes/file+/model+/public.$.tsx+++ b/apps/erp/app/routes/file+/model+/public.$.tsx@@ -44,8 +44,6 @@ export async function loader({ params }: LoaderFunctionArgs) {// the companyId, which selects the per-company bucket (with legacy fallback).const companyId = path.split("/")[0];- // No retry here: the client's fetchWithRetry already retries 5xx and- // network failures.const { data: fileData, error } = await storage(client).company(companyId).download(path);diff --git a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx b/apps/erp/app/routes/file+/preview+/$bucket.$.tsxindex 2fb9fe55c5..2b6866a812 100644--- a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx+++ b/apps/erp/app/routes/file+/preview+/$bucket.$.tsx@@ -115,8 +115,6 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {return source.download(path);}- // No retry here: the client's fetchWithRetry already retries 5xx and- // network failures.const result = await downloadFile();if (result.error) {logger.error("Failed to download file", {diff --git a/apps/erp/app/routes/share+/customer.$id.$.tsx b/apps/erp/app/routes/share+/customer.$id.$.tsxindex 1078425cc1..0214870078 100644--- a/apps/erp/app/routes/share+/customer.$id.$.tsx+++ b/apps/erp/app/routes/share+/customer.$id.$.tsx@@ -119,8 +119,6 @@ export let loader = async ({ params, request }: LoaderFunctionArgs) => {throw new Error(`File type ${fileType} not supported`);const contentType = getContentType(fileType);- // No retry here: the client's fetchWithRetry already retries 5xx and- // network failures.const { data: fileData, error } = await storage(serviceRole).company(shareCompanyId).download(path);diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsxindex 43d0559102..589f97a63b 100644--- a/apps/erp/app/routes/x+/_layout.tsx+++ b/apps/erp/app/routes/x+/_layout.tsx@@ -104,8 +104,12 @@ let shellLoadedAt = Date.now();export const shouldRevalidate: ShouldRevalidateFunction = ({currentUrl,formMethod,+ formAction,defaultShouldRevalidate}) => {+ // The refreshed session reaches the client through this loader.+ if (formAction === path.to.refreshSession) return true;+if (currentUrl.pathname.startsWith("/x/settings") ||currentUrl.pathname.startsWith("/x/users") ||diff --git a/apps/erp/app/routes/x+/accounting+/charts.move.$accountId.tsx b/apps/erp/app/routes/x+/accounting+/charts.move.$accountId.tsxindex 9d21bcf6dc..becc25cc63 100644--- a/apps/erp/app/routes/x+/accounting+/charts.move.$accountId.tsx+++ b/apps/erp/app/routes/x+/accounting+/charts.move.$accountId.tsx@@ -6,6 +6,7 @@ import { assertIsPost, error, notFound, 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 { unchecked } from "@carbon/utils";import type {ActionFunctionArgs,ClientActionFunctionArgs,@@ -133,7 +134,7 @@ export async function action({ request, params }: ActionFunctionArgs) {const result = await client.from("account")- .update(updateData)+ .update(unchecked(updateData)).eq("id", accountId).select("id").single();diff --git a/apps/erp/app/routes/x+/issue+/update.tsx b/apps/erp/app/routes/x+/issue+/update.tsxindex bf86654eee..0a86a97027 100644--- a/apps/erp/app/routes/x+/issue+/update.tsx+++ b/apps/erp/app/routes/x+/issue+/update.tsx@@ -5,6 +5,7 @@import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { getLogger } from "@carbon/logger";+import { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { isIssueLocked } from "~/modules/quality";import { requireUnlockedBulk } from "~/utils/lockedGuard.server";@@ -48,11 +49,13 @@ export async function action({ request }: ActionFunctionArgs) {const arrayValue = value ? value.split(",") : [];const update = await client.from("nonConformance")- .update({- [field]: arrayValue,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: arrayValue,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]).eq("companyId", companyId);@@ -104,11 +107,13 @@ export async function action({ request }: ActionFunctionArgs) {case "supplierId":return await client.from("nonConformance")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]).eq("companyId", companyId);default:diff --git a/apps/erp/app/routes/x+/items+/update.tsx b/apps/erp/app/routes/x+/items+/update.tsxindex 9dbdfa2a03..35ba5dc8ef 100644--- a/apps/erp/app/routes/x+/items+/update.tsx+++ b/apps/erp/app/routes/x+/items+/update.tsx@@ -5,6 +5,7 @@import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { getLogger } from "@carbon/logger";+import { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import type { InventoryItemType } from "~/modules/items";import { deriveItemMethodUpdate } from "~/modules/items";@@ -78,11 +79,13 @@ export async function action({ request }: ActionFunctionArgs) {case "unitOfMeasureCode":return await client.from("item")- .update({- [field]: value,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", items as string[]).eq("companyId", companyId);case "replenishmentSystem":diff --git a/apps/erp/app/routes/x+/job+/update.tsx b/apps/erp/app/routes/x+/job+/update.tsxindex d93eb15c01..07d7a27d8d 100644--- a/apps/erp/app/routes/x+/job+/update.tsx+++ b/apps/erp/app/routes/x+/job+/update.tsx@@ -6,7 +6,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";-import { scrapAllowance } from "@carbon/utils";+import { scrapAllowance, unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import {calculateJobPriority,@@ -188,12 +188,14 @@ export async function action({ request }: ActionFunctionArgs) {// Update the job with new field value and priorityconst updateResult = await client.from("job")- .update({- [field]: value ? value : null,- priority,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ priority,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).eq("id", id as string).eq("companyId", companyId);@@ -211,22 +213,26 @@ export async function action({ request }: ActionFunctionArgs) {case "unitOfMeasureCode":return await client.from("job")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]).eq("companyId", companyId);case "quantity":case "scrapQuantity":const quantityUpdate = await client.from("job")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]).eq("companyId", companyId);diff --git a/apps/erp/app/routes/x+/part+/$itemId.details.tsx b/apps/erp/app/routes/x+/part+/$itemId.details.tsxindex a441be65a8..4e3a0243e4 100644--- a/apps/erp/app/routes/x+/part+/$itemId.details.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.details.tsx@@ -24,10 +24,7 @@ import type { ItemFile, MakeMethod, PartSummary } from "~/modules/items";import {getConfigurationParameters,getConfigurationRules,- getItemChangeNoticeData,getItemManufacturing,- getMakeMethodById,- getMakeMethods,getMethodMaterialsByMakeMethod,getMethodOperationsByMakeMethodId,itemManufacturingValidator,@@ -35,7 +32,12 @@ import {upsertItemManufacturing,upsertPart} from "~/modules/items";-import { getRevisionLock } from "~/modules/items/items.server";+import {+ getItemChangeNoticeDataOnce,+ getMakeMethodByIdOnce,+ getMakeMethodsOnce,+ getRevisionLock+} from "~/modules/items/items.server";import {ChangeNoticeDraftLockReason,getChangeNoticeDraftLock,@@ -74,10 +76,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const requestedMethodId = url.searchParams.get("methodId");const [makeMethods, revisionLock, changeNoticeData] = await Promise.all([- getMakeMethods(client, itemId, companyId),+ getMakeMethodsOnce(client, itemId, companyId),getRevisionLock(client, { itemId, companyId }),// Part → CO traceability (4b): CO history for this part + type labels.- getItemChangeNoticeData(client, itemId, companyId)+ getItemChangeNoticeDataOnce(client, itemId, companyId)]);const revisionStatus = revisionLock.revisionStatus;const releaseControl = revisionLock.releaseControl;@@ -103,7 +105,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {};}- const fullMethod = await getMakeMethodById(client, makeMethod.id, companyId);+ const fullMethod = await getMakeMethodByIdOnce(+ client,+ makeMethod.id,+ companyId+ );if (fullMethod.error || !fullMethod.data) {return {methodData: null,diff --git a/apps/erp/app/routes/x+/part+/$itemId.tsx b/apps/erp/app/routes/x+/part+/$itemId.tsxindex d1c3e6523d..b93de7ea29 100644--- a/apps/erp/app/routes/x+/part+/$itemId.tsx+++ b/apps/erp/app/routes/x+/part+/$itemId.tsx@@ -37,10 +37,7 @@ import { ResizablePanels } from "~/components/Layout";import { flattenTree } from "~/components/TreeView";import type { ItemFile, PartSummary } from "~/modules/items";import {- findChangeNoticesForItem,getItemFiles,- getMakeMethodById,- getMakeMethods,getMethodTree,getPart,getPartUsedIn,@@ -49,6 +46,9 @@ import {isChangeNoticeOpen} from "~/modules/items";import {+ findChangeNoticesForItemOnce,+ getMakeMethodByIdOnce,+ getMakeMethodsOnce,getUnreleasedChangeOrderForItem,streamItemSupersession} from "~/modules/items/items.server";@@ -111,7 +111,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getTagsList(client, companyId, "part"),// Every CO, any status; the open subset (which locks manual version/revision// creation) is derived below.- findChangeNoticesForItem(client, { itemId, companyId }),+ findChangeNoticesForItemOnce(client, { itemId, companyId }),// Locks the Active toggle while the change notice that minted this item is// still open — release is what activates it.getUnreleasedChangeOrderForItem(client, { itemId, companyId })@@ -142,7 +142,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {// One query, two consumers: `methodTree` derives from it and the raw list is// also deferred to the client. Calling getMakeMethods twice issued the same// query twice on every part-detail load.- const makeMethodsPromise = getMakeMethods(client, itemId, companyId);+ const makeMethodsPromise = getMakeMethodsOnce(client, itemId, companyId);const methodTree = makeMethodsPromise.then(async (makeMethods) => {// Include CO-owned drafts so a revision/new-part item created by an open@@ -156,7 +156,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {: (selectable.find((m) => m.status === "Active") ?? selectable[0]);if (!makeMethod) return null;- const fullMethod = await getMakeMethodById(+ const fullMethod = await getMakeMethodByIdOnce(client,makeMethod.id,companyIddiff --git a/apps/erp/app/routes/x+/procedure+/update.tsx b/apps/erp/app/routes/x+/procedure+/update.tsxindex c97da96fec..6bf305a0ef 100644--- a/apps/erp/app/routes/x+/procedure+/update.tsx+++ b/apps/erp/app/routes/x+/procedure+/update.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 { unchecked } from "@carbon/utils";import type {ActionFunctionArgs,ClientActionFunctionArgs@@ -30,11 +31,13 @@ export async function action({ request }: ActionFunctionArgs) {case "processId":return await client.from("procedure")- .update({- [field]: value,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]);case "tags":return await clientdiff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.$lineId.details.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.$lineId.details.tsxindex 8566e632dc..b4e16d5cc4 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.$lineId.details.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.$lineId.details.tsx@@ -40,14 +40,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const { lineId } = params;if (!lineId) throw notFound("lineId not found");- const [purchaseInvoiceLine, files] = await Promise.all([- getPurchaseInvoiceLine(client, lineId),- getSupplierInteractionLineDocuments(client, companyId, lineId)- ]);+ const purchaseInvoiceLine = await getPurchaseInvoiceLine(client, lineId);return {purchaseInvoiceLine: purchaseInvoiceLine?.data ?? null,- files+ files: getSupplierInteractionLineDocuments(client, companyId, lineId)};}diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsxindex 2c0ed83188..bed0cb27b1 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.tsx@@ -74,7 +74,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {);}- const [supplier, interaction, files, orgHasCredits, currency, rampMapping] =+ const [supplier, interaction, orgHasCredits, currency, rampMapping] =await Promise.all([purchaseInvoice.data?.supplierId? getSupplier(client, purchaseInvoice.data.supplierId)@@ -83,11 +83,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {client,purchaseInvoice.data.supplierInteractionId!),- getSupplierInteractionDocuments(- client,- companyId,- purchaseInvoice.data.supplierInteractionId!- ),getCompanyHasOpenCredits(client, companyId, "purchase"),purchaseInvoice.data?.currencyCode? getCurrencyByCode(@@ -113,7 +108,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {currency: currency?.data ?? null,purchaseInvoiceLines: purchaseInvoiceLines.data ?? [],purchaseInvoiceDelivery: purchaseInvoiceDelivery.data,- files,+ files: getSupplierInteractionDocuments(+ client,+ companyId,+ purchaseInvoice.data.supplierInteractionId!+ ),interaction: interaction.data,supplier: supplier?.data ?? null,orgHasCredits,diff --git a/apps/erp/app/routes/x+/purchase-invoice+/update.tsx b/apps/erp/app/routes/x+/purchase-invoice+/update.tsxindex a3b563ec3a..b1c8eb8801 100644--- a/apps/erp/app/routes/x+/purchase-invoice+/update.tsx+++ b/apps/erp/app/routes/x+/purchase-invoice+/update.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 { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { getExchangeRate } from "~/modules/accounting";import {@@ -157,11 +158,13 @@ export async function action({ request }: ActionFunctionArgs) {case "datePaid":return await client.from("purchaseInvoice")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]);default:diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsxindex 463a666d02..956c6e3e9e 100644--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx@@ -25,6 +25,7 @@ import { VStack } from "@carbon/react";import { isUnaffectedByNavigation } from "@carbon/utils";import { msg } from "@lingui/core/macro";import { renderAsync } from "@react-email/components";+import type { FileObject } from "@supabase/storage-js";import { parseAcceptLanguage } from "intl-parse-accept-language";import type {ActionFunctionArgs,@@ -410,6 +411,17 @@ export const shouldRevalidate: ShouldRevalidateFunction = (args) =>? false: args.defaultShouldRevalidate;+const toAttachments = (docs: FileObject[], folder: string) =>+ docs.map((d) => ({+ source: "po" as const,+ name: d.name,+ size:+ (d.metadata as { size?: number } | null | undefined)?.size != null+ ? Math.round(((d.metadata as { size?: number }).size as number) / 1024)+ : null,+ path: `${folder}/${d.name}`+ }));+export async function loader({ request, params }: LoaderFunctionArgs) {const { client, companyId, companyGroupId, userId } =await requirePermissions(request, {@@ -518,48 +530,52 @@ export async function loader({ request, params }: LoaderFunctionArgs) {));const supplierInteractionId = purchaseOrder.data?.supplierInteractionId;- const [defaultAttachments, adHocDocs, currency] = await Promise.all([+ // One listing feeds both the documents panel and the attachment list, and+ // neither holds up the page.+ const files = supplierInteractionId+ ? getSupplierInteractionDocuments(+ serviceRole,+ companyId,+ supplierInteractionId+ )+ : Promise.resolve([]);+ const resolvedAttachments = Promise.all([getDefaultAttachmentsForPO(serviceRole, {companyId,supplierId: purchaseOrder.data?.supplierId ?? null,itemIds}),- supplierInteractionId- ? getSupplierInteractionDocuments(- serviceRole,- companyId,- supplierInteractionId- )- : Promise.resolve([]),- purchaseOrder.data?.currencyCode- ? getCurrencyByCode(- serviceRole,- companyGroupId,- purchaseOrder.data.currencyCode- )- : null- ]);- const adHocAttachments = adHocDocs.map((d) => ({- source: "po" as const,- name: d.name,- size:- (d.metadata as { size?: number } | null | undefined)?.size != null- ? Math.round(((d.metadata as { size?: number }).size as number) / 1024)- : null,- path: `${companyId}/supplier-interaction/${supplierInteractionId}/${d.name}`- }));- const resolvedAttachments = [...defaultAttachments, ...adHocAttachments];+ files+ ])+ .then(([defaults, adHocDocs]) => [+ ...defaults,+ ...toAttachments(+ adHocDocs,+ `${companyId}/supplier-interaction/${supplierInteractionId}`+ )+ ])+ .catch((error) => {+ logger.error("Failed to resolve purchase order attachments", {+ companyId,+ orderId,+ error+ });+ return [];+ });+ const currency = purchaseOrder.data?.currencyCode+ ? await getCurrencyByCode(+ serviceRole,+ companyGroupId,+ purchaseOrder.data.currencyCode+ )+ : null;return {purchaseOrder: purchaseOrder.data,purchaseOrderDelivery: purchaseOrderDelivery.data,currency: currency?.data ?? null,lines: lines.data ?? [],- files: getSupplierInteractionDocuments(- client,- companyId,- purchaseOrder.data.supplierInteractionId!- ),+ files,interaction: interaction?.data,supplier: supplier?.data ?? null,approvalRequest: approvalRequest.data,diff --git a/apps/erp/app/routes/x+/purchase-order+/update.tsx b/apps/erp/app/routes/x+/purchase-order+/update.tsxindex 1a8cf59a35..14f45f1318 100644--- a/apps/erp/app/routes/x+/purchase-order+/update.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/update.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 { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { getExchangeRate } from "~/modules/accounting";import { isPurchaseOrderLocked } from "~/modules/purchasing";@@ -91,11 +92,13 @@ export async function action({ request }: ActionFunctionArgs) {case "deliveryDate":return await client.from("purchaseOrderDelivery")- .update({- [field]: value ?? undefined,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ?? undefined,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]);case "receiptPromisedDate":const lineUpdates = await client@@ -144,11 +147,13 @@ export async function action({ request }: ActionFunctionArgs) {case "orderDate":return await client.from("purchaseOrder")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]);default:return { error: { message: "Invalid field" }, data: null };diff --git a/apps/erp/app/routes/x+/purchase-return-order+/update.tsx b/apps/erp/app/routes/x+/purchase-return-order+/update.tsxindex 952362ffd1..0b5f278ec6 100644--- a/apps/erp/app/routes/x+/purchase-return-order+/update.tsx+++ b/apps/erp/app/routes/x+/purchase-return-order+/update.tsx@@ -3,7 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import { datetime } from "@carbon/utils";+import { datetime, unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { getExchangeRate } from "~/modules/accounting";import { isPurchaseReturnOrderLocked } from "~/modules/purchasing";@@ -112,11 +112,13 @@ export async function action({ request }: ActionFunctionArgs) {case "orderDate":return await client.from("purchaseReturnOrder")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: datetime.timestamp()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ ).in("id", ids as string[]);default:return { error: { message: "Invalid field" }, data: null };diff --git a/apps/erp/app/routes/x+/purchasing-rfq+/update.tsx b/apps/erp/app/routes/x+/purchasing-rfq+/update.tsxindex 97b60034d9..dbc8806b0e 100644--- a/apps/erp/app/routes/x+/purchasing-rfq+/update.tsx+++ b/apps/erp/app/routes/x+/purchasing-rfq+/update.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 { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import {isRfqLocked,@@ -46,11 +47,13 @@ export async function action({ request }: ActionFunctionArgs) {}return await client.from("purchasingRfq")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]);}case "supplierIds": {diff --git a/apps/erp/app/routes/x+/quality-document+/update.tsx b/apps/erp/app/routes/x+/quality-document+/update.tsxindex d9b0aa2915..fdd20ef2fc 100644--- a/apps/erp/app/routes/x+/quality-document+/update.tsx+++ b/apps/erp/app/routes/x+/quality-document+/update.tsx@@ -17,6 +17,7 @@ import {import { trigger } from "@carbon/jobs";import { getLogger } from "@carbon/logger";import { NotificationEvent } from "@carbon/notifications";+import { unchecked } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import type { ActionFunctionArgs } from "react-router";import { qualityDocumentStatus } from "~/modules/quality/quality.models";@@ -200,11 +201,13 @@ export async function action({ request }: ActionFunctionArgs) {case "name":return await client.from("qualityDocument")- .update({- [field]: value,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]).eq("companyId", companyId);case "status": {diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.tsxindex 65a4588ff0..286f93b0ee 100644--- a/apps/erp/app/routes/x+/quote+/$quoteId.tsx+++ b/apps/erp/app/routes/x+/quote+/$quoteId.tsx@@ -92,7 +92,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {prices,opportunity,methods,- opportunityDocuments,companySettings] = await Promise.all([getCustomer(client, quote.data?.customerId ?? ""),@@ -102,7 +101,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getQuoteLinePricesByQuoteId(client, quoteId),getOpportunity(client, quote.data?.opportunityId),getQuoteMethodTrees(client, quoteId),- getOpportunityDocuments(client, companyId, quote.data?.opportunityId ?? ""),getCompanySettings(client, companyId)]);@@ -208,7 +206,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {customer: customer.data,lines: lines.data ?? [],methods: methodTrees,- files: opportunityDocuments,+ files: getOpportunityDocuments(client, companyId, quote.data.opportunityId),prices: prices.data ?? [],shipment: shipment.data,payment: payment.data,diff --git a/apps/erp/app/routes/x+/quote+/update.tsx b/apps/erp/app/routes/x+/quote+/update.tsxindex b715a49d65..2d06ccb219 100644--- a/apps/erp/app/routes/x+/quote+/update.tsx+++ b/apps/erp/app/routes/x+/quote+/update.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 { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { getExchangeRate } from "~/modules/accounting";import { isQuoteLocked } from "~/modules/sales";@@ -99,11 +100,13 @@ export async function action({ request }: ActionFunctionArgs) {case "salesPersonId":return await client.from("quote")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]);default:return { error: { message: "Invalid field" }, data: null };diff --git a/apps/erp/app/routes/x+/receipt+/fixed-asset-lines.update.tsx b/apps/erp/app/routes/x+/receipt+/fixed-asset-lines.update.tsxindex 933fe86bb0..af3ba91147 100644--- a/apps/erp/app/routes/x+/receipt+/fixed-asset-lines.update.tsx+++ b/apps/erp/app/routes/x+/receipt+/fixed-asset-lines.update.tsx@@ -4,6 +4,7 @@import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";export async function action({ request }: ActionFunctionArgs) {@@ -35,7 +36,7 @@ export async function action({ request }: ActionFunctionArgs) {const update = await serviceRole.from("receiptFixedAssetLine")- .update(updateData)+ .update(unchecked(updateData)).eq("id", id).eq("companyId", companyId);diff --git a/apps/erp/app/routes/x+/receipt+/lines.update.tsx b/apps/erp/app/routes/x+/receipt+/lines.update.tsxindex 7df7e2444c..338ca8291e 100644--- a/apps/erp/app/routes/x+/receipt+/lines.update.tsx+++ b/apps/erp/app/routes/x+/receipt+/lines.update.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 { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";export async function action({ request }: ActionFunctionArgs) {@@ -30,11 +31,13 @@ export async function action({ request }: ActionFunctionArgs) {// Per-line saves go straight through.const update = await client.from("receiptLine")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids).eq("companyId", companyId);diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsxindex 08f2a7b3e6..52d00aa2d7 100644--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.$lineId.details.tsx@@ -54,7 +54,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return {salesInvoiceLine: salesInvoiceLine?.data ?? null,- files: await getOpportunityLineDocuments(client, companyId, lineId, itemId)+ files: getOpportunityLineDocuments(client, companyId, lineId, itemId)};}diff --git a/apps/erp/app/routes/x+/sales-invoice+/update.tsx b/apps/erp/app/routes/x+/sales-invoice+/update.tsxindex a8c744665a..c9c875ae3c 100644--- a/apps/erp/app/routes/x+/sales-invoice+/update.tsx+++ b/apps/erp/app/routes/x+/sales-invoice+/update.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 { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { getExchangeRate } from "~/modules/accounting";import {@@ -156,11 +157,13 @@ export async function action({ request }: ActionFunctionArgs) {case "datePaid":return await client.from("salesInvoice")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]);default:diff --git a/apps/erp/app/routes/x+/sales-order+/update.tsx b/apps/erp/app/routes/x+/sales-order+/update.tsxindex 7485c1001f..dced48d364 100644--- a/apps/erp/app/routes/x+/sales-order+/update.tsx+++ b/apps/erp/app/routes/x+/sales-order+/update.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 { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { getExchangeRate } from "~/modules/accounting";import { isSalesOrderLocked } from "~/modules/sales";@@ -108,21 +109,25 @@ export async function action({ request }: ActionFunctionArgs) {case "salesPersonId":return await client.from("salesOrder")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]);case "receiptPromisedDate":case "receiptRequestedDate":return await client.from("salesOrderShipment")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]);default:return { error: { message: "Invalid field" }, data: null };diff --git a/apps/erp/app/routes/x+/sales-return-order+/update.tsx b/apps/erp/app/routes/x+/sales-return-order+/update.tsxindex b9e6cdc43b..661dca0317 100644--- a/apps/erp/app/routes/x+/sales-return-order+/update.tsx+++ b/apps/erp/app/routes/x+/sales-return-order+/update.tsx@@ -3,7 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import { datetime } from "@carbon/utils";+import { datetime, unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { getExchangeRate } from "~/modules/accounting";import { isSalesReturnOrderLocked } from "~/modules/sales";@@ -112,11 +112,13 @@ export async function action({ request }: ActionFunctionArgs) {case "orderDate":return await client.from("salesReturnOrder")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: datetime.timestamp()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: datetime.timestamp()+ })+ ).in("id", ids as string[]);default:return { error: { message: "Invalid field" }, data: null };diff --git a/apps/erp/app/routes/x+/sales-rfq+/update.tsx b/apps/erp/app/routes/x+/sales-rfq+/update.tsxindex 485951c34f..a14c95e191 100644--- a/apps/erp/app/routes/x+/sales-rfq+/update.tsx+++ b/apps/erp/app/routes/x+/sales-rfq+/update.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 { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { isSalesRfqLocked } from "~/modules/sales";import { requireUnlockedBulk } from "~/utils/lockedGuard.server";@@ -48,11 +49,13 @@ export async function action({ request }: ActionFunctionArgs) {case "salesPersonId":return await client.from("salesRfq")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]);default:return { error: { message: "Invalid field" }, data: null };diff --git a/apps/erp/app/routes/x+/service+/$itemId.details.tsx b/apps/erp/app/routes/x+/service+/$itemId.details.tsxindex f547f71dd6..de2363d6f8 100644--- a/apps/erp/app/routes/x+/service+/$itemId.details.tsx+++ b/apps/erp/app/routes/x+/service+/$itemId.details.tsx@@ -16,13 +16,15 @@ import { DeferredFiles } from "~/components";import { usePermissions, useRouteData } from "~/hooks";import type { ItemFile, MakeMethod, ServiceSummary } from "~/modules/items";import {- getMakeMethodById,- getMakeMethods,getMethodMaterialsByMakeMethod,getMethodOperationsByMakeMethodId,serviceValidator,upsertService} from "~/modules/items";+import {+ getMakeMethodByIdOnce,+ getMakeMethodsOnce+} from "~/modules/items/items.server";import {BillOfMaterial,BillOfProcess,@@ -48,7 +50,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const url = new URL(request.url);const requestedMethodId = url.searchParams.get("methodId");- const makeMethods = await getMakeMethods(client, itemId, companyId);+ const makeMethods = await getMakeMethodsOnce(client, itemId, companyId);const makeMethod = requestedMethodId? (makeMethods.data?.find((m) => m.id === requestedMethodId) ??makeMethods.data?.find((m) => m.status === "Active") ??@@ -60,7 +62,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {return { methodData: null, tags: [] };}- const fullMethod = await getMakeMethodById(client, makeMethod.id, companyId);+ const fullMethod = await getMakeMethodByIdOnce(+ client,+ makeMethod.id,+ companyId+ );if (fullMethod.error || !fullMethod.data) {return { methodData: null, tags: [] };}diff --git a/apps/erp/app/routes/x+/service+/$itemId.tsx b/apps/erp/app/routes/x+/service+/$itemId.tsxindex 5e5534b1b2..d09e33bfb7 100644--- a/apps/erp/app/routes/x+/service+/$itemId.tsx+++ b/apps/erp/app/routes/x+/service+/$itemId.tsx@@ -38,14 +38,16 @@ import { flattenTree } from "~/components/TreeView";import type { ItemFile, ServiceSummary } from "~/modules/items";import {getItemFiles,- getMakeMethodById,- getMakeMethods,getMethodTree,getPartUsedIn,getService,getSupplierParts} from "~/modules/items";-import { streamItemSupersession } from "~/modules/items/items.server";+import {+ getMakeMethodByIdOnce,+ getMakeMethodsOnce,+ streamItemSupersession+} from "~/modules/items/items.server";import { BoMActions, BoMExplorer } from "~/modules/items/ui/Item";import type { UsedInNode } from "~/modules/items/ui/Item/UsedIn";import { UsedInSkeleton, UsedInTree } from "~/modules/items/ui/Item/UsedIn";@@ -99,7 +101,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const url = new URL(request.url);const requestedMethodId = url.searchParams.get("methodId");- const methodTree = getMakeMethods(client, itemId, companyId).then(+ const methodTree = getMakeMethodsOnce(client, itemId, companyId).then(async (makeMethods) => {const makeMethod = requestedMethodId? (makeMethods.data?.find((m) => m.id === requestedMethodId) ??@@ -109,7 +111,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {makeMethods.data?.[0]);if (!makeMethod) return null;- const fullMethod = await getMakeMethodById(+ const fullMethod = await getMakeMethodByIdOnce(client,makeMethod.id,companyId@@ -134,7 +136,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {supersededBy,files: getItemFiles(client, itemId, companyId),supplierParts: supplierParts.data ?? [],- makeMethods: getMakeMethods(client, itemId, companyId),+ makeMethods: getMakeMethodsOnce(client, itemId, companyId),tags: tags.data ?? [],usedIn: getPartUsedIn(client, itemId, companyId),methodTreediff --git a/apps/erp/app/routes/x+/settings+/custom-fields.tsx b/apps/erp/app/routes/x+/settings+/custom-fields.tsxindex 8b77993090..5c272f8d2f 100644--- a/apps/erp/app/routes/x+/settings+/custom-fields.tsx+++ b/apps/erp/app/routes/x+/settings+/custom-fields.tsx@@ -6,7 +6,7 @@ import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { VStack } from "@carbon/react";-import { isUnaffectedByNavigation } from "@carbon/utils";+import { isUnaffectedByNavigation, unchecked } from "@carbon/utils";import { msg } from "@lingui/core/macro";import type {ActionFunctionArgs,@@ -82,11 +82,13 @@ export async function action({ request }: ActionFunctionArgs) {const result = await client// @ts-ignore.from(table)- .update({- customFields: JSON.parse(value),- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ customFields: JSON.parse(value),+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in(getIdField(table), ids as string[]);return result;diff --git a/apps/erp/app/routes/x+/settings+/tags.tsx b/apps/erp/app/routes/x+/settings+/tags.tsxindex 630d01933e..09b05b0c65 100644--- a/apps/erp/app/routes/x+/settings+/tags.tsx+++ b/apps/erp/app/routes/x+/settings+/tags.tsx@@ -4,6 +4,7 @@import { requirePermissions } from "@carbon/auth/auth.server";import { getLogger } from "@carbon/logger";+import { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";const logger = getLogger("erp", "tags");@@ -19,11 +20,13 @@ export async function action({ request }: ActionFunctionArgs) {const result = await client// @ts-expect-error.from(table as string)- .update({- tags: value,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ tags: value,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in(getIdField(table as string), ids as string[]);if (result.error) {diff --git a/apps/erp/app/routes/x+/shipment+/fixed-asset-lines.update.tsx b/apps/erp/app/routes/x+/shipment+/fixed-asset-lines.update.tsxindex ccd8fe77eb..397fcf78de 100644--- a/apps/erp/app/routes/x+/shipment+/fixed-asset-lines.update.tsx+++ b/apps/erp/app/routes/x+/shipment+/fixed-asset-lines.update.tsx@@ -4,6 +4,7 @@import { requirePermissions } from "@carbon/auth/auth.server";import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";export async function action({ request }: ActionFunctionArgs) {@@ -35,7 +36,7 @@ export async function action({ request }: ActionFunctionArgs) {const update = await serviceRole.from("shipmentFixedAssetLine")- .update(updateData)+ .update(unchecked(updateData)).eq("id", id).eq("companyId", companyId);diff --git a/apps/erp/app/routes/x+/shipment+/lines.update.tsx b/apps/erp/app/routes/x+/shipment+/lines.update.tsxindex 1ad478b6fe..9d986d649d 100644--- a/apps/erp/app/routes/x+/shipment+/lines.update.tsx+++ b/apps/erp/app/routes/x+/shipment+/lines.update.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 { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";export async function action({ request }: ActionFunctionArgs) {@@ -30,11 +31,13 @@ export async function action({ request }: ActionFunctionArgs) {// Per-line saves go straight through.const update = await client.from("shipmentLine")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids).eq("companyId", companyId);diff --git a/apps/erp/app/routes/x+/stock-transfer+/lines.update.tsx b/apps/erp/app/routes/x+/stock-transfer+/lines.update.tsxindex c9c6e933b9..61600abe3b 100644--- a/apps/erp/app/routes/x+/stock-transfer+/lines.update.tsx+++ b/apps/erp/app/routes/x+/stock-transfer+/lines.update.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 { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";import { getStockTransfer, isStockTransferLocked } from "~/modules/inventory";import { requireUnlocked } from "~/utils/lockedGuard.server";@@ -58,11 +59,13 @@ export async function action({ request }: ActionFunctionArgs) {// not on per-line edits. Saves go straight through.const update = await client.from("stockTransferLine")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids).eq("companyId", companyId);diff --git a/apps/erp/app/routes/x+/supplier-quote+/update.tsx b/apps/erp/app/routes/x+/supplier-quote+/update.tsxindex d678a2928e..ee3006b2d8 100644--- a/apps/erp/app/routes/x+/supplier-quote+/update.tsx+++ b/apps/erp/app/routes/x+/supplier-quote+/update.tsx@@ -3,7 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { requirePermissions } from "@carbon/auth/auth.server";-import { datetime } from "@carbon/utils";+import { datetime, unchecked } from "@carbon/utils";import type { CalendarDate } from "@internationalized/date";import { parseDate } from "@internationalized/date";import type { ActionFunctionArgs } from "react-router";@@ -98,11 +98,13 @@ export async function action({ request }: ActionFunctionArgs) {case "quotedDate":return await client.from("supplierQuote")- .update({- [field]: value ? value : null,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value ? value : null,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]);case "expirationDate": {diff --git a/apps/erp/app/routes/x+/tool+/$itemId.details.tsx b/apps/erp/app/routes/x+/tool+/$itemId.details.tsxindex 9e2117deb5..f36dd313af 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.details.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.details.tsx@@ -18,10 +18,7 @@ import { CadModel, DeferredFiles } from "~/components";import { usePermissions, useRouteData } from "~/hooks";import type { ItemFile, MakeMethod, ToolSummary } from "~/modules/items";import {- getItemChangeNoticeData,getItemManufacturing,- getMakeMethodById,- getMakeMethods,getMethodMaterialsByMakeMethod,getMethodOperationsByMakeMethodId,itemManufacturingValidator,@@ -29,7 +26,12 @@ import {upsertItemManufacturing,upsertTool} from "~/modules/items";-import { getRevisionLock } from "~/modules/items/items.server";+import {+ getItemChangeNoticeDataOnce,+ getMakeMethodByIdOnce,+ getMakeMethodsOnce,+ getRevisionLock+} from "~/modules/items/items.server";import {ChangeNoticeDraftLockReason,getChangeNoticeDraftLock,@@ -66,10 +68,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const requestedMethodId = url.searchParams.get("methodId");const [makeMethods, revisionLock, changeNoticeData] = await Promise.all([- getMakeMethods(client, itemId, companyId),+ getMakeMethodsOnce(client, itemId, companyId),getRevisionLock(client, { itemId, companyId }),// Tool → CO traceability (4b): CO history for this tool + type labels.- getItemChangeNoticeData(client, itemId, companyId)+ getItemChangeNoticeDataOnce(client, itemId, companyId)]);const revisionStatus = revisionLock.revisionStatus;const releaseControl = revisionLock.releaseControl;@@ -94,7 +96,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {};}- const fullMethod = await getMakeMethodById(client, makeMethod.id, companyId);+ const fullMethod = await getMakeMethodByIdOnce(+ client,+ makeMethod.id,+ companyId+ );if (fullMethod.error || !fullMethod.data) {return {methodData: null,diff --git a/apps/erp/app/routes/x+/tool+/$itemId.tsx b/apps/erp/app/routes/x+/tool+/$itemId.tsxindex 58f26f742e..9c5058f71b 100644--- a/apps/erp/app/routes/x+/tool+/$itemId.tsx+++ b/apps/erp/app/routes/x+/tool+/$itemId.tsx@@ -37,10 +37,7 @@ import { ResizablePanels } from "~/components/Layout";import { flattenTree } from "~/components/TreeView";import type { ItemFile, ToolSummary } from "~/modules/items";import {- findChangeNoticesForItem,getItemFiles,- getMakeMethodById,- getMakeMethods,getMethodTree,getPartUsedIn,getPickMethods,@@ -49,6 +46,9 @@ import {isChangeNoticeOpen} from "~/modules/items";import {+ findChangeNoticesForItemOnce,+ getMakeMethodByIdOnce,+ getMakeMethodsOnce,getUnreleasedChangeOrderForItem,streamItemSupersession} from "~/modules/items/items.server";@@ -106,7 +106,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {getTagsList(client, companyId, "tool"),// Every CO, any status; the open subset (which locks manual version/revision// creation) is derived below.- findChangeNoticesForItem(client, { itemId, companyId }),+ findChangeNoticesForItemOnce(client, { itemId, companyId }),// Locks the Active toggle while the change notice that minted this item is// still open — release is what activates it.getUnreleasedChangeOrderForItem(client, { itemId, companyId })@@ -130,7 +130,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const url = new URL(request.url);const requestedMethodId = url.searchParams.get("methodId");- const methodTree = getMakeMethods(client, itemId, companyId).then(+ const methodTree = getMakeMethodsOnce(client, itemId, companyId).then(async (makeMethods) => {const makeMethod = requestedMethodId? (makeMethods.data?.find((m) => m.id === requestedMethodId) ??@@ -140,7 +140,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {makeMethods.data?.[0]);if (!makeMethod) return null;- const fullMethod = await getMakeMethodById(+ const fullMethod = await getMakeMethodByIdOnce(client,makeMethod.id,companyId@@ -166,7 +166,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {files: getItemFiles(client, itemId, companyId),supplierParts: supplierParts.data ?? [],pickMethods: pickMethods.data ?? [],- makeMethods: getMakeMethods(client, itemId, companyId),+ makeMethods: getMakeMethodsOnce(client, itemId, companyId),tags: tags.data ?? [],usedIn: getPartUsedIn(client, itemId, companyId),methodTree,diff --git a/apps/erp/app/routes/x+/training+/update.tsx b/apps/erp/app/routes/x+/training+/update.tsxindex 86ec06ea1d..3e90cd7e34 100644--- a/apps/erp/app/routes/x+/training+/update.tsx+++ b/apps/erp/app/routes/x+/training+/update.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 { unchecked } from "@carbon/utils";import type { ActionFunctionArgs } from "react-router";export async function action({ request }: ActionFunctionArgs) {@@ -29,11 +30,13 @@ export async function action({ request }: ActionFunctionArgs) {case "description":return await client.from("training")- .update({- [field]: value,- updatedBy: userId,- updatedAt: new Date().toISOString()- })+ .update(+ unchecked({+ [field]: value,+ updatedBy: userId,+ updatedAt: new Date().toISOString()+ })+ ).in("id", ids as string[]);case "grantsAbilityId":return await clientdiff --git a/apps/erp/app/utils/query.ts b/apps/erp/app/utils/query.tsindex 2fa5700dfb..907ef5ad8d 100644--- a/apps/erp/app/utils/query.ts+++ b/apps/erp/app/utils/query.ts@@ -4,9 +4,14 @@import { badRequest } from "@carbon/auth";import type { PostgrestFilterBuilder } from "@supabase/postgrest-js";-import type { GenericSchema } from "@supabase/supabase-js/dist/module/lib/types";import { getPageOffset, getPageSize } from "./pagination";+type GenericSchema = {+ Tables: Record<string, unknown>;+ Views: Record<string, unknown>;+ Functions: Record<string, unknown>;+};+/*** Count mode for every paged list endpoint — any query that goes through* `setGenericQueryFilters`. Counts that drive logic rather than a pagerdiff --git a/apps/erp/test/po-default-attachments.test.ts b/apps/erp/test/po-default-attachments.test.tsnew file mode 100644index 0000000000..c3dcf555b6--- /dev/null+++ b/apps/erp/test/po-default-attachments.test.ts@@ -0,0 +1,107 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it, vi } from "vitest";+import { getDefaultAttachmentsForPO } from "~/modules/purchasing/purchasing.service";++// The service module's message descriptors are compiled by the Lingui Vite+// plugin, which this test environment does not run.+vi.mock("@lingui/core/macro", () => ({+ msg: (strings: TemplateStringsArray) => strings.join("")+}));++const prefix = "co1/default-attachments";++// A storage client whose company bucket holds `folders` (prefix → sub-folder+// names) and `files` (prefix → file names); the legacy bucket is empty.+function fakeClient(+ folders: Record<string, string[]>,+ files: Record<string, string[]>,+ failing: string[] = []+) {+ const listed: string[] = [];+ const listV2 = (bucket: string) =>+ vi.fn(async ({ prefix: path }: { prefix: string }) => {+ if (bucket === "co1") listed.push(path);+ if (failing.includes(path)) {+ return { data: null, error: { message: "storage down" } };+ }+ if (bucket !== "co1") {+ return { data: { hasNext: false, folders: [], objects: [] }, error: null };+ }+ const key = path.replace(/\/$/, "");+ return {+ data: {+ hasNext: false,+ folders: (folders[key] ?? []).map((name) => ({+ key: `${key}/${name}`,+ name: `${key}/${name}/`+ })),+ objects: (files[key] ?? []).map((name) => ({+ key: `${key}/${name}`,+ name: `${key}/${name}`,+ id: `${key}/${name}`,+ metadata: { size: 2048 }+ }))+ },+ error: null+ };+ });+ const buckets = new Map<string, ReturnType<typeof listV2>>();+ const client = {+ storage: {+ from: (bucket: string) => {+ if (!buckets.has(bucket)) buckets.set(bucket, listV2(bucket));+ return { listV2: buckets.get(bucket) };+ }+ }+ };+ return { client: client as never, listed };+}++describe("getDefaultAttachmentsForPO", () => {+ it("lists only the items that have default attachments", async () => {+ const { client, listed } = fakeClient(+ { [`${prefix}/item`]: ["i2"] },+ { [`${prefix}/item/i2`]: ["spec.pdf"] }+ );++ const attachments = await getDefaultAttachmentsForPO(client, {+ companyId: "co1",+ supplierId: "s1",+ itemIds: ["i1", "i2", "i3"]+ });++ expect(listed.sort()).toEqual(+ [+ `${prefix}/company/`,+ `${prefix}/item/`,+ `${prefix}/item/i2/`,+ `${prefix}/supplier/s1/`+ ].sort()+ );+ expect(attachments).toEqual([+ {+ source: "item",+ name: "spec.pdf",+ size: 2,+ path: `${prefix}/item/i2/spec.pdf`+ }+ ]);+ });++ it("checks every item when the item folder cannot be listed", async () => {+ const { client, listed } = fakeClient({}, {}, [`${prefix}/item/`]);++ await getDefaultAttachmentsForPO(client, {+ companyId: "co1",+ supplierId: null,+ itemIds: ["i1", "i2"]+ });++ expect(listed).toEqual(+ expect.arrayContaining([`${prefix}/item/i1/`, `${prefix}/item/i2/`])+ );+ });+});diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsxindex 3d99abede9..2b0be4bbd1 100644--- a/apps/mes/app/root.tsx+++ b/apps/mes/app/root.tsx@@ -17,6 +17,7 @@ import {requestContextMiddleware,requestIdMiddleware} from "@carbon/logger/middleware.server";+import { namedMiddleware } from "@carbon/logger/tracing.server";import {OperatingSystemContextProvider,Toaster,@@ -63,13 +64,13 @@ import "@carbon/lib/shims";import type { Route } from "./+types/root";import { getTheme } from "./services/theme.server";-export const middleware = [+export const middleware = namedMiddleware([// First: publishes the request context so server code can reach it via ALS.requestContextMiddleware,requestIdMiddleware,securityMiddleware,flashMiddleware-];+]);export const clientMiddleware = [flashClientMiddleware];export const links: Route.LinksFunction = () => [diff --git a/apps/mes/app/routes/display+/_layout.tsx b/apps/mes/app/routes/display+/_layout.tsxindex 8584340226..d330848bf1 100644--- a/apps/mes/app/routes/display+/_layout.tsx+++ b/apps/mes/app/routes/display+/_layout.tsx@@ -4,9 +4,14 @@import { CarbonProvider } from "@carbon/auth";import { requireAuthSession } from "@carbon/auth/session.server";-import type { LoaderFunctionArgs, MiddlewareFunction } from "react-router";+import type {+ LoaderFunctionArgs,+ MiddlewareFunction,+ ShouldRevalidateFunction+} from "react-router";import { Outlet, useLoaderData } from "react-router";import { userMiddleware } from "~/middleware/user";+import { path } from "~/utils/path";/*** Layout for the wall-mounted work center displays.@@ -25,6 +30,13 @@ import { userMiddleware } from "~/middleware/user";*/export const middleware: MiddlewareFunction[] = [userMiddleware];+// The refreshed session reaches the client through this loader, and the+// refresh asks for no other loader to re-run.+export const shouldRevalidate: ShouldRevalidateFunction = ({+ formAction,+ defaultShouldRevalidate+}) => formAction === path.to.refreshSession || defaultShouldRevalidate;+export async function loader({ request }: LoaderFunctionArgs) {// `verify: false` skips the `auth.getUser` round-trip on every load. The// display boards revalidate their own data every 30s, which re-runs thisdiff --git a/apps/mes/app/routes/file+/preview+/$bucket.$.tsx b/apps/mes/app/routes/file+/preview+/$bucket.$.tsxindex c2dabc32e1..bc32cba79b 100644--- a/apps/mes/app/routes/file+/preview+/$bucket.$.tsx+++ b/apps/mes/app/routes/file+/preview+/$bucket.$.tsx@@ -123,8 +123,6 @@ export let loader = async ({ request, params }: LoaderFunctionArgs) => {return source.download(path);}- // No retry here: the client's fetchWithRetry already retries 5xx and- // network failures.const result = await downloadFile();if (result.error) {log.error("Failed to download file", {diff --git a/apps/mes/app/routes/x+/_layout.tsx b/apps/mes/app/routes/x+/_layout.tsxindex 3930f64927..f7cfa0e6ea 100644--- a/apps/mes/app/routes/x+/_layout.tsx+++ b/apps/mes/app/routes/x+/_layout.tsx@@ -92,6 +92,9 @@ export const shouldRevalidate: ShouldRevalidateFunction = ({formAction,defaultShouldRevalidate}) => {+ // The refreshed session reaches the client through this loader.+ if (formAction === path.to.refreshSession) return true;+if (currentUrl.pathname.startsWith("/refresh-session") ||currentUrl.pathname.startsWith("/switch-company") ||diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.tsindex 7b957513d8..29daf43f3a 100644--- a/apps/mes/app/services/operations.service.ts+++ b/apps/mes/app/services/operations.service.ts@@ -2407,12 +2407,20 @@ export async function insertReworkQuantity(.insert(sanitize({...insert,- type: "Rework"+ type: "Rework" as const})).select("*");}+// The tracked entity is recorded by the issue path, not on productionQuantity.+function withoutTracking<+ T extends { trackedEntityId?: unknown; trackingType?: unknown }+>(data: T): Omit<T, "trackedEntityId" | "trackingType"> {+ const { trackedEntityId: _entity, trackingType: _tracking, ...rest } = data;+ return rest;+}+export async function insertProductionQuantity(client: SupabaseClient<Database>,data: z.infer<typeof nonScrapQuantityValidator> & {@@ -2430,8 +2438,8 @@ export async function insertProductionQuantity(.from("productionQuantity").insert(sanitize({- ...data,- type: "Production"+ ...withoutTracking(data),+ type: "Production" as const})).select("*");@@ -2464,8 +2472,8 @@ export async function insertScrapQuantity(.from("productionQuantity").insert(sanitize({- ...data,- type: "Scrap"+ ...withoutTracking(data),+ type: "Scrap" as const})).select("*");@@ -2650,7 +2658,7 @@ export async function startProductionEvent(client: SupabaseClient<Database>,data: Omit<z.infer<typeof productionEventValidator>,- "id" | "action" | "hasActiveEvents" | "unitIndex"+ "id" | "action" | "hasActiveEvents" | "unitIndex" | "exclusive"> & {startTime: string;employeeId: string;@@ -2673,11 +2681,14 @@ export async function startProductionEvent(});if (!refs.ok) return notFoundResponse(refs.message);+ // The tracked entity is the separate argument; productionEvent has no column for it.+ const { trackedEntityId: _trackedEntityId, ...event } = data;+if (trackedEntityId) {const activityId = nanoid();const [eventInsert, operation] = await Promise.all([- client.from("productionEvent").insert(data).select("id").single(),+ client.from("productionEvent").insert(event).select("id").single(),client.from("jobOperation").select("*")@@ -2756,7 +2767,7 @@ export async function startProductionEvent(const eventInsert = await client.from("productionEvent")- .insert(data)+ .insert(event).select("*");if (!eventInsert.error) {diff --git a/apps/starter/app/routes/x+/_layout.tsx b/apps/starter/app/routes/x+/_layout.tsxindex 5f118167a1..26cea11163 100644--- a/apps/starter/app/routes/x+/_layout.tsx+++ b/apps/starter/app/routes/x+/_layout.tsx@@ -14,8 +14,19 @@ import {requireAuthSession} from "@carbon/auth/session.server";import { Toaster, useNProgress } from "@carbon/react";-import type { LoaderFunctionArgs } from "react-router";+import type {+ LoaderFunctionArgs,+ ShouldRevalidateFunction+} from "react-router";import { Outlet, redirect, useLoaderData } from "react-router";+import { path } from "~/utils/path";++// The refreshed session reaches the client through this loader, and the+// refresh asks for no other loader to re-run.+export const shouldRevalidate: ShouldRevalidateFunction = ({+ formAction,+ defaultShouldRevalidate+}) => formAction === path.to.refreshSession || defaultShouldRevalidate;export async function loader({ request }: LoaderFunctionArgs) {const { accessToken, companyId, expiresAt, expiresIn, userId } =diff --git a/packages/auth/src/lib/supabase/client.test.ts b/packages/auth/src/lib/supabase/client.test.tsindex 5fe359ff24..117f927d84 100644--- a/packages/auth/src/lib/supabase/client.test.ts+++ b/packages/auth/src/lib/supabase/client.test.ts@@ -2,140 +2,133 @@// Carbon (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 { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";// Env is validated at import time (getEnv throws on missing required vars), so we// stub the config module rather than requiring a full environment in the test run.vi.mock("../../config/env", () => ({- SUPABASE_ANON_KEY: "test-anon-key",+ SUPABASE_ANON_KEY: "sb_publishable_anon",SUPABASE_INTERNAL_URL: "http://supabase.internal.test",SUPABASE_URL: "http://supabase.test"}));-const { fetchWithRetry } = await import("./client");--const jsonResponse = (status: number) =>- new Response(JSON.stringify({}), { status });+const { getCarbonAPIKeyClient, getCarbonClient, storageReadFetch } =+ await import("./client");++// Edge functions recognise a service-role caller by the Authorization bearer.+// supabase-js stops sending a new-format key as that bearer on function calls,+// so the client must set it itself for either key format.+describe("Edge Function calls carry the Authorization bearer", () => {+ const sent = () => {+ const [input, init] = vi.mocked(fetch).mock.calls[0]!;+ const headers = new Headers(+ input instanceof Request ? input.headers : init?.headers+ );+ return headers.get("Authorization");+ };-describe("fetchWithRetry", () => {- let fetchSpy: ReturnType<typeof vi.spyOn>;+ const stubFetch = () =>+ vi.stubGlobal(+ "fetch",+ vi.fn(async () => new Response("{}", { status: 200 }))+ );- beforeEach(() => {- fetchSpy = vi.spyOn(globalThis, "fetch");- });+ afterEach(() => vi.unstubAllGlobals());- afterEach(() => {- fetchSpy.mockRestore();+ it.each([+ ["a legacy JWT key", "eyJhbGciOiJIUzI1NiJ9.e30.signature"],+ ["a new-format secret key", "sb_secret_abc123"]+ ])("service-role client with %s", async (_, key) => {+ stubFetch();+ await getCarbonClient(key).functions.invoke("create", { body: {} });+ expect(sent()).toBe(`Bearer ${key}`);});- // Regression test for the quoteToQuote duplicate-quote incident: retrying a- // 5xx from a non-idempotent Edge Function re-runs its side effects. See- // .ai/lessons.md for the incident this pins.- it("does not retry an Edge Function invocation on a 5xx — one attempt only", async () => {- fetchSpy.mockResolvedValue(jsonResponse(500));-- const response = await fetchWithRetry(- "http://supabase.internal.test/functions/v1/get-method",- { method: "POST", body: "{}" }+ it("a user's token wins over the key", async () => {+ stubFetch();+ await getCarbonClient("sb_secret_abc123", "user-jwt").functions.invoke(+ "create",+ { body: {} });-- expect(fetchSpy).toHaveBeenCalledTimes(1);- expect(response.status).toBe(500);+ expect(sent()).toBe("Bearer user-jwt");});- it("does not retry an Edge Function invocation on a network error — the error propagates", async () => {- fetchSpy.mockRejectedValue(new Error("network down"));-- await expect(- fetchWithRetry("http://supabase.internal.test/functions/v1/get-method", {- method: "POST",- body: "{}"- })- ).rejects.toThrow("network down");-- expect(fetchSpy).toHaveBeenCalledTimes(1);+ it("API-key client", async () => {+ stubFetch();+ await getCarbonAPIKeyClient("crbn_key").functions.invoke("create", {+ body: {}+ });+ expect(sent()).toBe("Bearer sb_publishable_anon");});+});- it("still bypasses retry for a storage upload on a 5xx (existing behavior, unchanged)", async () => {- fetchSpy.mockResolvedValue(jsonResponse(503));+describe("storage reads are retried, everything else passes through", () => {+ const storage = "http://supabase.internal.test/storage/v1";- const response = await fetchWithRetry(- "http://supabase.internal.test/storage/v1/object/bucket/file.png",- { method: "PUT", body: "binary" }- );+ const respond = (...statuses: number[]) => {+ const fetchMock = vi.fn();+ for (const status of statuses) {+ fetchMock.mockResolvedValueOnce(new Response("{}", { status }));+ }+ vi.stubGlobal("fetch", fetchMock);+ return fetchMock;+ };- expect(fetchSpy).toHaveBeenCalledTimes(1);- expect(response.status).toBe(503);- });+ const settle = async <T>(promise: Promise<T>) => {+ await vi.runAllTimersAsync();+ return promise;+ };- it("still retries a normal (non-Edge-Function, non-storage) request on a 5xx", async () => {- fetchSpy- .mockResolvedValueOnce(jsonResponse(500))- .mockResolvedValueOnce(jsonResponse(200));+ afterEach(() => {+ vi.unstubAllGlobals();+ vi.useRealTimers();+ });- const response = await fetchWithRetry(- "http://supabase.internal.test/rest/v1/quote?id=eq.1",- { method: "GET" }+ it("retries a download after a 5xx", async () => {+ vi.useFakeTimers();+ const fetchMock = respond(503, 200);+ const response = await settle(+ storageReadFetch(`${storage}/object/co_1/a.pdf`, { method: "GET" }));-- expect(fetchSpy).toHaveBeenCalledTimes(2);expect(response.status).toBe(200);+ expect(fetchMock).toHaveBeenCalledTimes(2);});- // PostgREST commits before it answers, so a 5xx or a dropped response says- // nothing about whether the write landed. Retrying is how one insert becomes- // several rows. Same rule as the Edge Function carve-out above.- it.each([- ["POST (insert / upsert / rpc)", "POST"],- ["PATCH (update)", "PATCH"],- ["DELETE (delete)", "DELETE"]- ])("does not retry a PostgREST write on a 5xx — %s", async (_label, method) => {- fetchSpy.mockResolvedValue(jsonResponse(503));-- const response = await fetchWithRetry(- "http://supabase.internal.test/rest/v1/quote",- { method, body: "{}" }+ it("retries a listing, which is a POST", async () => {+ vi.useFakeTimers();+ const fetchMock = respond(502, 502, 200);+ const response = await settle(+ storageReadFetch(`${storage}/object/list-v2/co_1`, { method: "POST" }));-- expect(fetchSpy).toHaveBeenCalledTimes(1);- expect(response.status).toBe(503);- });-- it("does not retry a PostgREST write on a network error — the error propagates", async () => {- fetchSpy.mockRejectedValue(new Error("connection reset"));-- await expect(- fetchWithRetry("http://supabase.internal.test/rest/v1/quote", {- method: "POST",- body: "{}"- })- ).rejects.toThrow("connection reset");-- expect(fetchSpy).toHaveBeenCalledTimes(1);+ expect(response.status).toBe(200);+ expect(fetchMock).toHaveBeenCalledTimes(3);});- it("treats a request with no explicit method as a replayable GET", async () => {- fetchSpy- .mockResolvedValueOnce(jsonResponse(500))- .mockResolvedValueOnce(jsonResponse(200));-- const response = await fetchWithRetry(- "http://supabase.internal.test/rest/v1/quote?id=eq.1"+ it("gives up after two retries and returns the last answer", async () => {+ vi.useFakeTimers();+ const fetchMock = respond(500, 500, 500);+ const response = await settle(+ storageReadFetch(`${storage}/object/co_1/a.pdf`));-- expect(fetchSpy).toHaveBeenCalledTimes(2);- expect(response.status).toBe(200);+ expect(response.status).toBe(500);+ expect(fetchMock).toHaveBeenCalledTimes(3);});- it("returns a non-retryable status from a normal request on the first attempt", async () => {- fetchSpy.mockResolvedValue(jsonResponse(404));-- const response = await fetchWithRetry(- "http://supabase.internal.test/rest/v1/quote?id=eq.1",- { method: "GET" }- );+ it("never replays an upload", async () => {+ const fetchMock = respond(500);+ const response = await storageReadFetch(`${storage}/object/co_1/a.pdf`, {+ method: "POST",+ body: "bytes"+ });+ expect(response.status).toBe(500);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });- expect(fetchSpy).toHaveBeenCalledTimes(1);- expect(response.status).toBe(404);+ it("leaves database reads to supabase-js", async () => {+ const fetchMock = respond(503);+ await storageReadFetch("http://supabase.internal.test/rest/v1/item", {+ method: "GET"+ });+ expect(fetchMock).toHaveBeenCalledTimes(1);});});diff --git a/packages/auth/src/lib/supabase/client.ts b/packages/auth/src/lib/supabase/client.tsindex 0bd5e33bb6..d8aa5c3b4c 100644--- a/packages/auth/src/lib/supabase/client.ts+++ b/packages/auth/src/lib/supabase/client.ts@@ -13,101 +13,73 @@ import {SUPABASE_URL} from "../../config/env";-const PER_ATTEMPT_TIMEOUT_MS = 25_000;-const MAX_RETRIES = 2;-const BACKOFF_MS = [500, 1000];-const RETRYABLE_STATUS = new Set([500, 502, 503, 504, 512, 408, 524]);--const sleep = (ms: number) =>- new Promise<void>((resolve) => setTimeout(resolve, ms));--const methodOf = (input: RequestInfo | URL, init?: RequestInit) =>- (+// Retries are supabase-js's own: a read (GET/HEAD) is retried up to three+// times on a rejected fetch, a 503 or a 520, and a write is never replayed.+// The timeout bounds a database call that hangs; an aborted call is not retried.+const db = { timeout: 25_000 } as const;++const STORAGE_WAIT_MS = 25_000;+const STORAGE_BACKOFF_MS = [500, 1000];++// supabase-js retries database reads only. A storage read (a download, an+// info or exists check, a listing) gets the same here: a bounded wait for the+// response headers and two retries on a 5xx or a dropped connection. The body+// itself is not timed, so a large download is never cut off. Uploads, deletes+// and everything outside storage pass straight through.+const isStorageRead = (url: string, method: string) =>+ url.includes("/storage/v1/") &&+ (method === "GET" ||+ method === "HEAD" ||+ (method === "POST" && url.includes("/storage/v1/object/list")));++export const storageReadFetch: typeof fetch = async (input, init) => {+ const url = input instanceof Request ? input.url : String(input);+ const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase();+ if (!isStorageRead(url, method)) return fetch(input, init);-// Storage object writes (uploads) must NOT go through the retry/timeout wrapper:-// re-sending a multi-GB PUT on a 5xx is wasteful, and the 25s per-attempt timeout-// would abort any legitimately long upload. Fail fast — pass straight through and-// honor only the caller's own signal.-const isStorageUpload = (input: RequestInfo | URL, init?: RequestInit) => {- const method = methodOf(input, init);- if (method !== "POST" && method !== "PUT") return false;- const url = input instanceof Request ? input.url : String(input);- return url.includes("/storage/v1/object/");-};--const isEdgeFunctionInvoke = (input: RequestInfo | URL) => {- const url = input instanceof Request ? input.url : String(input);- return url.includes("/functions/v1/");-};--// Only a READ may be replayed. A 5xx or a lost response does not mean the write-// did not land — PostgREST commits before it answers, so a retried insert is a-// duplicate row and a retried RPC re-runs a transaction. None of PostgREST's-// write verbs carry an idempotency key: insert/upsert/rpc are POST, update is-// PATCH, delete is DELETE. This is the same rule the Edge Function carve-out-// above encodes (.ai/lessons.md — the quoteToQuote duplicate-quote incidents,-// "a retry wrapper must never blindly retry a write with real side effects and-// no idempotency key"); that fix covered `/functions/v1/` and left every-// PostgREST write still replaying. The per-attempt timeout still applies to-// writes — it bounds latency without duplicating anything.-const isReplayable = (input: RequestInfo | URL, init?: RequestInit) => {- const method = methodOf(input, init);- return method === "GET" || method === "HEAD";-};--export const fetchWithRetry: typeof fetch = async (input, init) => {- if (isStorageUpload(input, init) || isEdgeFunctionInvoke(input)) {- return fetch(input, init);- }-- const maxRetries = isReplayable(input, init) ? MAX_RETRIES : 0;-- let lastError: unknown;- for (let attempt = 0; attempt <= maxRetries; attempt++) {- const timeoutSignal = AbortSignal.timeout(PER_ATTEMPT_TIMEOUT_MS);+ for (let attempt = 0; ; attempt++) {+ const retry = attempt < STORAGE_BACKOFF_MS.length;+ const waited = new AbortController();+ const timer = setTimeout(() => waited.abort(), STORAGE_WAIT_MS);const signal = init?.signal- ? AbortSignal.any([init.signal, timeoutSignal])- : timeoutSignal;-+ ? AbortSignal.any([init.signal, waited.signal])+ : waited.signal;try {const response = await fetch(input, { ...init, signal });- if (RETRYABLE_STATUS.has(response.status) && attempt < maxRetries) {- await sleep(BACKOFF_MS[attempt] ?? 1000);- continue;- }- return response;+ clearTimeout(timer);+ if (!retry || response.status < 500) return response;+ await response.body?.cancel();} catch (error) {- lastError = error;- if (init?.signal?.aborted) throw error;- if (attempt >= maxRetries) throw error;- await sleep(BACKOFF_MS[attempt] ?? 1000);+ clearTimeout(timer);+ if (!retry || init?.signal?.aborted) throw error;}+ await new Promise((resolve) =>+ setTimeout(resolve, STORAGE_BACKOFF_MS[attempt])+ );}- throw lastError;};export const getCarbonClient = (supabaseKey: string,accessToken?: string): SupabaseClient<Database, "public"> => {- const headers = accessToken- ? { Authorization: `Bearer ${accessToken}` }- : undefined;+ // Always explicit. Left to supabase-js, a new-format key (`sb_secret_…`) is+ // not sent as the bearer on Edge Function calls, and those functions tell a+ // service-role caller from anyone else by this header.+ const headers = { Authorization: `Bearer ${accessToken ?? supabaseKey}` };const client = createClient<Database, "public">(SUPABASE_INTERNAL_URL!,supabaseKey,{+ db,auth: {autoRefreshToken: false,persistSession: false},- global: {- fetch: fetchWithRetry,- ...(headers ? { headers } : {})- }+ global: { headers, fetch: storageReadFetch }});@@ -118,9 +90,11 @@ export const getCarbonAPIKeyClient = (apiKey: string): SupabaseClient<Database, "public"> => {const client = createClient(SUPABASE_INTERNAL_URL!, SUPABASE_ANON_KEY!, {+ db,global: {- fetch: fetchWithRetry,+ fetch: storageReadFetch,headers: {+ Authorization: `Bearer ${SUPABASE_ANON_KEY}`,"carbon-key": apiKey}}@@ -133,13 +107,12 @@ export const createCarbonWithAuthGetter = (store: MutableRefObject<StoreApi<{ accessToken: string }>>): SupabaseClient<Database, "public"> => {return createClient<Database, "public">(SUPABASE_URL!, SUPABASE_ANON_KEY!, {+ db,+ global: { fetch: storageReadFetch },auth: {autoRefreshToken: false,persistSession: false},- global: {- fetch: fetchWithRetry- },async accessToken() {if (!store.current) return null;const state = store.current.getState();diff --git a/packages/auth/src/lib/supabase/provider.tsx b/packages/auth/src/lib/supabase/provider.tsxindex 9846f3fd56..86c66f843a 100644--- a/packages/auth/src/lib/supabase/provider.tsx+++ b/packages/auth/src/lib/supabase/provider.tsx@@ -64,14 +64,34 @@ export const CarbonProvider = ({}}, [carbon, setAuthToken, session.accessToken]);+ // The access token the client holds comes from the shell loader, so only the+ // shell is told to re-run after a refresh. Without that, every loader on the+ // page re-ran each time the tab regained focus.+ const refreshIfDue = (canRefresh: boolean) => {+ const expiresAt = session.expiresAt ?? 0;+ const now = Date.now() / 1000;++ if (expiresAt < now) {+ window.location.reload();+ return;+ }++ // refresh ten minutes before expiry+ if (canRefresh && expiresAt - 60 * 10 < now) {+ refresh.submit(null, {+ method: "post",+ action: path.to.refreshSession,+ defaultShouldRevalidate: false+ });+ }+ };++ // Timers are throttled in a background tab, so a tab that comes back may be+ // past the point where the interval below would have refreshed it.+ // biome-ignore lint/correctness/useExhaustiveDependencies: refreshIfDue reads the latest sessionuseEffect(() => {const handleVisibilityChange = () => {- if (document.visibilityState === "visible") {- refresh.submit(null, {- method: "post",- action: path.to.refreshSession- });- }+ if (document.visibilityState === "visible") refreshIfDue(true);};if (isBrowser) {@@ -86,25 +106,10 @@ export const CarbonProvider = ({);}};- }, [refresh]);+ }, [refresh, session.expiresAt]);useInterval(() => {- // refresh ten minutes before expiry- const expiresAt = session.expiresAt ?? 0;- const shouldRefresh = expiresAt - 60 * 10 < Date.now() / 1000;- const shouldReload = expiresAt < Date.now() / 1000;-- if (shouldReload) {- window.location.reload();- }-- if (!initialLoad.current && shouldRefresh && carbon) {- refresh.submit(null, {- method: "post",- action: path.to.refreshSession- });- }-+ refreshIfDue(!initialLoad.current && !!carbon);initialLoad.current = false;}, 60000); // Check every minutediff --git a/packages/auth/src/services/users.ts b/packages/auth/src/services/users.tsindex 65c97c2919..a4de48f65a 100644--- a/packages/auth/src/services/users.ts+++ b/packages/auth/src/services/users.ts@@ -43,7 +43,7 @@ export async function getCompanies() {const companies = await client.from("companies")- .select("*, companyGroup(name)")+ .select("*").eq("userId", userId).order("name");@@ -52,9 +52,8 @@ export async function getCompanies(}return {- data: companies.data.map(({ companyGroup, ...company }) => ({+ data: companies.data.map((company) => ({...company,- companyGroupName: (companyGroup as { name: string } | null)?.name ?? null,logoLightIcon: company.logoLightIcon? `${SUPABASE_URL}/storage/v1/object/public/public/${company.logoLightIcon}`: null,diff --git a/packages/database/src/event-dispatch.test.ts b/packages/database/src/event-dispatch.test.tsnew file mode 100644index 0000000000..b026054574--- /dev/null+++ b/packages/database/src/event-dispatch.test.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 { readdirSync, readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";+import { auditConfig } from "./audit.config";++const migrations = fileURLToPath(+ new URL("../supabase/migrations/", import.meta.url)+);++function newestDefinition(signature: string) {+ for (const file of readdirSync(migrations).sort().reverse()) {+ const sql = readFileSync(`${migrations}${file}`, "utf8");+ if (sql.includes(signature)) return { file, sql };+ }+ throw new Error(`No migration defines ${signature}`);+}++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 new definition forked+ // from an older one silently loses the filter, and a skip field added on one+ // side only makes the trigger and the handler disagree.+ it("ignores exactly the columns the audit diff skips", () => {+ const { file, sql } = newestDefinition(+ "CREATE OR REPLACE FUNCTION public.dispatch_event_batch()"+ );+ const declared = sql.match(+ /ignored_columns CONSTANT TEXT\[\] := ARRAY\[([^\]]*)\]/+ );++ expect(declared, `${file} has no ignored_columns`).not.toBeNull();+ const columns = declared![1]!+ .split(",")+ .map((column) => column.trim().replace(/'/g, ""));+ expect(columns.sort()).toEqual([...auditConfig.skipFields].sort());+ });+});diff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.tsindex 844fd12a62..eb82380fd7 100644--- a/packages/database/supabase/functions/seed-company/index.ts+++ b/packages/database/supabase/functions/seed-company/index.ts@@ -77,9 +77,8 @@ serve(async (req: Request) => {if (!company.data) throw new Error("Company not found");// Idempotency guard. The whole seed runs in a single transaction, so a- // committed run has inserted `userToCompany(userId, companyId)`. The- // service-role client retries on timeout / transient 5xx (fetchWithRetry),- // so a seed that committed but whose HTTP response was lost gets re-invoked+ // committed run has inserted `userToCompany(userId, companyId)`. A seed+ // that committed but whose HTTP response was lost can be invoked again// with the same payload — re-running would throw 23505 on the identity// inserts. If the link already exists, the prior run finished: no-op.const existingLink = await clientdiff --git a/packages/database/supabase/migrations/20261001195204_event-dispatch-skip-unchanged-updates.sql b/packages/database/supabase/migrations/20261001195204_event-dispatch-skip-unchanged-updates.sqlnew file mode 100644index 0000000000..823bd6af6c--- /dev/null+++ b/packages/database/supabase/migrations/20261001195204_event-dispatch-skip-unchanged-updates.sql@@ -0,0 +1,198 @@+-- An UPDATE that changes nothing but "updatedAt", "updatedBy" or "embedding"+-- is no longer queued for the AUDIT, SEARCH and EMBEDDING handlers.+--+-- Every one of those handlers already discards such an event after it has been+-- queued, sent to Inngest and run: the audit diff skips those three columns+-- (auditConfig.skipFields, packages/database/src/audit.config.ts — keep the two+-- lists in step), the search index is built from none of them, and the+-- embedding handler only acts on a name/description change. A writer that+-- touches rows without changing them (the scheduler regen did, for every open+-- job operation) therefore produced a queue message, an Inngest event and a+-- function run per batch, all to be dropped.+--+-- WEBHOOK, WORKFLOW and SYNC subscriptions are untouched: their payload is a+-- customer-facing contract and they still receive every UPDATE.+--+-- Forked verbatim from 20260811224732_scoped-sync-trigger-suppression.sql with+-- that one change: the UPDATE branch gains the changed-row predicate ($11/$12).++CREATE OR REPLACE FUNCTION public.dispatch_event_batch()+RETURNS TRIGGER+LANGUAGE plpgsql+SECURITY DEFINER+SET search_path = public, pgmq, extensions+AS $$+DECLARE+ sub RECORD;+ msg_batch JSONB[];+ rec_company_id TEXT;+ has_subs BOOLEAN;+ current_actor_id TEXT;+ current_workflow_run_id TEXT;+ pk_column TEXT;+ pk_join TEXT;+ query_text TEXT;+ did_enqueue BOOLEAN := FALSE;+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];+BEGIN+ current_actor_id := auth.uid()::TEXT;+ current_workflow_run_id :=+ (nullif(current_setting('request.jwt.claims', true), '')::jsonb)->>'workflow_run_id';+ pk_column := public.get_primary_key_column(TG_TABLE_NAME);++ -- Pair UPDATE rows on the full key: single-column pairing cross-joins rows+ -- on tables with composite identity.+ SELECT string_agg(format('n.%I = o.%I', col, col), ' AND ')+ INTO pk_join+ FROM unnest(public.get_primary_key_columns(TG_TABLE_NAME)) AS col;++ IF TG_OP = 'DELETE' THEN+ SELECT t."companyId" INTO rec_company_id FROM batched_old t LIMIT 1;+ ELSIF TG_OP = 'INSERT' THEN+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;+ ELSE+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;+ END IF;++ IF rec_company_id IS NULL THEN RETURN NULL; END IF;++ SELECT EXISTS (+ SELECT 1 FROM "eventSystemSubscription"+ WHERE "table" = TG_TABLE_NAME+ AND "companyId" = rec_company_id+ AND "active" = TRUE+ AND TG_OP = ANY("operations")+ AND ("handlerType" NOT IN ('SYNC','WEBHOOK','WORKFLOW')+ OR current_setting('app.sync_in_progress', true) IS DISTINCT FROM 'true')+ ) INTO has_subs;++ IF NOT has_subs THEN RETURN NULL; END IF;++ FOR sub IN+ SELECT * FROM "eventSystemSubscription"+ WHERE "table" = TG_TABLE_NAME+ AND "companyId" = rec_company_id+ AND "active" = TRUE+ AND TG_OP = ANY("operations")+ AND ("handlerType" NOT IN ('SYNC','WEBHOOK','WORKFLOW')+ OR current_setting('app.sync_in_progress', true) IS DISTINCT FROM 'true')+ LOOP++ IF TG_OP = 'INSERT' THEN+ query_text := format('+ SELECT array_agg(+ jsonb_build_object(+ ''subscriptionId'', $1,+ ''triggerType'', $2,+ ''handlerType'', $3,+ ''handlerConfig'', $4,+ ''companyId'', $5,+ ''actorId'', $6,+ ''workflowRunId'', $10,+ ''event'', jsonb_build_object(+ ''table'', $7,+ ''operation'', $8,+ ''recordId'', t.%I::TEXT,+ ''new'', row_to_json(t)::jsonb,+ ''old'', null,+ ''timestamp'', clock_timestamp()+ )+ )+ )+ FROM batched_new t+ WHERE t."companyId" = $5+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)+ ', pk_column);++ EXECUTE query_text INTO msg_batch+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,+ current_workflow_run_id;++ ELSIF TG_OP = 'DELETE' THEN+ query_text := format('+ SELECT array_agg(+ jsonb_build_object(+ ''subscriptionId'', $1,+ ''triggerType'', $2,+ ''handlerType'', $3,+ ''handlerConfig'', $4,+ ''companyId'', $5,+ ''actorId'', $6,+ ''workflowRunId'', $10,+ ''event'', jsonb_build_object(+ ''table'', $7,+ ''operation'', $8,+ ''recordId'', t.%I::TEXT,+ ''new'', null,+ ''old'', row_to_json(t)::jsonb,+ ''timestamp'', clock_timestamp()+ )+ )+ )+ FROM batched_old t+ WHERE t."companyId" = $5+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)+ ', pk_column);++ EXECUTE query_text INTO msg_batch+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,+ current_workflow_run_id;++ ELSIF TG_OP = 'UPDATE' THEN+ query_text := format('+ SELECT array_agg(+ jsonb_build_object(+ ''subscriptionId'', $1,+ ''triggerType'', $2,+ ''handlerType'', $3,+ ''handlerConfig'', $4,+ ''companyId'', $5,+ ''actorId'', $6,+ ''workflowRunId'', $10,+ ''event'', jsonb_build_object(+ ''table'', $7,+ ''operation'', $8,+ ''recordId'', n.%I::TEXT,+ ''new'', row_to_json(n)::jsonb,+ ''old'', row_to_json(o)::jsonb,+ ''timestamp'', clock_timestamp()+ )+ )+ )+ FROM batched_new n+ JOIN batched_old o ON %s+ WHERE n."companyId" = $5+ AND ($9 = ''{}''::jsonb OR row_to_json(n)::jsonb @> $9)+ AND (NOT $11 OR (to_jsonb(n) - $12) IS DISTINCT FROM (to_jsonb(o) - $12))+ ', pk_column, pk_join);++ EXECUTE query_text INTO msg_batch+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,+ current_workflow_run_id,+ sub."handlerType" IN ('AUDIT', 'SEARCH', 'EMBEDDING'),+ ignored_columns;+ END IF;++ IF msg_batch IS NOT NULL AND array_length(msg_batch, 1) > 0 THEN+ PERFORM pgmq.send_batch('event_system', msg_batch);+ did_enqueue := TRUE;+ END IF;++ END LOOP;++ -- Wake the Inngest drainer once per transaction: the GUC is txn-local, so a+ -- bulk import posts a single doorbell instead of one per statement.+ IF did_enqueue+ AND current_setting('carbon.event_wake_sent', true) IS DISTINCT FROM 'true' THEN+ PERFORM util.wake_event_queue();+ PERFORM set_config('carbon.event_wake_sent', 'true', true);+ END IF;++ RETURN NULL;+END;+$$;++COMMENT ON FUNCTION public.dispatch_event_batch() IS 'Dispatches database events to PGMQ and wakes the Inngest drainer via wake_event_queue() (once per transaction). Uses clock_timestamp() so each event has a unique microsecond timestamp even when batched. Stamps workflowRunId from the workflow_run_id JWT claim so workflow-made writes are distinguishable. During sync writes (app.sync_in_progress = true) only SYNC/WEBHOOK/WORKFLOW subscriptions are suppressed (loop/echo break); SEARCH/AUDIT/EMBEDDING observers still see sync-written rows, except an UPDATE that changes only updatedAt/updatedBy/embedding, which those three never act on.';diff --git a/packages/ee/src/jira/lib/service.ts b/packages/ee/src/jira/lib/service.tsindex 7ff4c4faa2..0111da6bf7 100644--- a/packages/ee/src/jira/lib/service.ts+++ b/packages/ee/src/jira/lib/service.ts@@ -5,6 +5,7 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { Database } from "@carbon/database";import { getLogger } from "@carbon/logger";+import { unchecked } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { persistIntegrationSecrets } from "../../integrations/secrets";import type { ActionTaskEntityType } from "../../lib/actionTaskEntity";@@ -128,7 +129,7 @@ export async function linkActionToJiraIssue(// Update the task fieldsconst result = await client.from(entity.table)- .update(updateData)+ .update(unchecked(updateData)).eq("companyId", companyId).eq("id", input.actionId).select(entity.parentColumn);diff --git a/packages/ee/src/linear/lib/service.ts b/packages/ee/src/linear/lib/service.tsindex 2f19b90fe2..397b403d55 100644--- a/packages/ee/src/linear/lib/service.ts+++ b/packages/ee/src/linear/lib/service.ts@@ -5,6 +5,7 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { Database } from "@carbon/database";import { getLogger } from "@carbon/logger";+import { unchecked } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import type z from "zod";import type { ActionTaskEntityType } from "../../lib/actionTaskEntity";@@ -69,7 +70,7 @@ export async function linkActionToLinearIssue(// Update the task fieldsconst result = await client.from(entity.table)- .update(updateData)+ .update(unchecked(updateData)).eq("companyId", companyId).eq("id", input.actionId).select(entity.parentColumn);diff --git a/packages/ee/src/mcp/server.test.ts b/packages/ee/src/mcp/server.test.tsnew file mode 100644index 0000000000..1475c5cecf--- /dev/null+++ b/packages/ee/src/mcp/server.test.ts@@ -0,0 +1,121 @@+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial+// Carbon Enterprise file, licensed only under the Carbon Commercial License+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.++import { describeRequest } from "@carbon/logger/middleware.server";+import {+ annotateRequestSpan,+ nameRequestSpan,+ withSpan+} from "@carbon/logger/tracing.server";+import { Client } from "@modelcontextprotocol/sdk/client/index.js";+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { createMcpServer } from "./server";++vi.mock("@carbon/logger/tracing.server", () => ({+ annotateRequestSpan: vi.fn(),+ nameRequestSpan: vi.fn(),+ withSpan: vi.fn((_name: string, _attributes: unknown, run: () => unknown) =>+ run()+ )+}));+vi.mock("@carbon/logger/middleware.server", () => ({+ describeRequest: vi.fn()+}));+vi.mock("../entitlements.server", () => ({+ requireEntitlement: vi.fn(async () => undefined)+}));++const callOperation = vi.fn(async () => ({+ success: true as const,+ data: [{ id: "cust_1" }]+}));++async function connect() {+ const server = await createMcpServer(+ {+ client: {},+ companyId: "co1",+ companyGroupId: "g1",+ userId: "u1"+ } as never,+ "2026-10-01",+ {+ callOperation,+ operationsByName: new Map([+ ["sales_getCustomer", { name: "sales_getCustomer", module: "sales" }]+ ]),+ isListOperation: () => false,+ isMcpBlockedTool: () => false,+ catalogSearch: { search: async () => ({ matches: [], total: 0 }) },+ toolMetadata: { tools: [{ module: "sales" }], totalTools: 1, modules: 1 }+ } as never+ );+ const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();+ await server.connect(serverSide);+ const client = new Client({ name: "test", version: "0.0.0" });+ await client.connect(clientSide);+ return client;+}++describe("MCP tool calls are traced", () => {+ beforeEach(() => vi.clearAllMocks());++ it("names a call_tool span after the operation and still runs it", async () => {+ const client = await connect();++ const result = await client.callTool({+ name: "call_tool",+ arguments: { name: "sales_getCustomer", arguments: { customerId: "c" } }+ });++ expect(JSON.stringify(result.content)).toContain("cust_1");+ expect(callOperation).toHaveBeenCalledWith(+ "sales_getCustomer",+ expect.objectContaining({ companyId: "co1" }),+ expect.objectContaining({ customerId: "c" })+ );+ const attributes = {+ "carbon.mcp.tool": "call_tool",+ "carbon.operation": "sales_getCustomer"+ };+ expect(withSpan).toHaveBeenCalledWith(+ "mcp call_tool sales_getCustomer",+ attributes,+ expect.any(Function)+ );+ expect(annotateRequestSpan).toHaveBeenCalledWith(attributes);+ expect(nameRequestSpan).toHaveBeenCalledWith(+ "POST /api/mcp call_tool sales_getCustomer"+ );+ expect(describeRequest).toHaveBeenCalledWith("call_tool sales_getCustomer");+ });++ it("keeps a name the client made up out of the span name", async () => {+ const client = await connect();++ await client.callTool({+ name: "call_tool",+ arguments: { name: "not_a_real_operation", arguments: {} }+ });++ expect(withSpan).toHaveBeenCalledWith(+ "mcp call_tool",+ { "carbon.mcp.tool": "call_tool" },+ expect.any(Function)+ );+ });++ it("traces the other tools by their own name", async () => {+ const client = await connect();++ await client.callTool({ name: "search_tools", arguments: { query: "x" } });++ expect(withSpan).toHaveBeenCalledWith(+ "mcp search_tools",+ { "carbon.mcp.tool": "search_tools" },+ expect.any(Function)+ );+ });+});diff --git a/packages/ee/src/mcp/server.ts b/packages/ee/src/mcp/server.tsindex 3a4ccf351f..5b65c3a462 100644--- a/packages/ee/src/mcp/server.ts+++ b/packages/ee/src/mcp/server.ts@@ -4,6 +4,12 @@// @ts-nocheckimport { getLogger } from "@carbon/logger";+import { describeRequest } from "@carbon/logger/middleware.server";+import {+ annotateRequestSpan,+ nameRequestSpan,+ withSpan+} from "@carbon/logger/tracing.server";import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";import { z } from "zod";import { requireEntitlement } from "../entitlements.server";@@ -61,6 +67,25 @@ export async function createMcpServer<Ctx extends McpContext>(});+ // One span per tool call. An operation name comes from the client, so it is+ // put in the span name only when it is a real operation.+ const registerTool = server.registerTool.bind(server);+ server.registerTool = (tool, config, handler) =>+ registerTool(tool, config, (params, extra) => {+ const operation = operationsByName.has(params?.name)+ ? params.name+ : undefined;+ const attributes = {+ "carbon.mcp.tool": tool,+ ...(operation ? { "carbon.operation": operation } : {})+ };+ const call = operation ? `${tool} ${operation}` : tool;+ annotateRequestSpan(attributes);+ nameRequestSpan(`POST /api/mcp ${call}`);+ describeRequest(call);+ return withSpan(`mcp ${call}`, attributes, () => handler(params, extra));+ });+// Register describe_tool to get schema information for any toolserver.registerTool("describe_tool",diff --git a/packages/ee/src/rules/service.server.ts b/packages/ee/src/rules/service.server.tsindex d51a6b2c45..4a29b36ffc 100644--- a/packages/ee/src/rules/service.server.ts+++ b/packages/ee/src/rules/service.server.ts@@ -16,7 +16,7 @@import type { Database, Json } from "@carbon/database";import type { ConditionAst, Severity, TargetType } from "@carbon/utils";-import { datetime, sanitize } from "@carbon/utils";+import { datetime, sanitize, unchecked } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";import { requireEntitlement } from "../entitlements.server";import type { Feature } from "../plan";@@ -283,6 +283,6 @@ export async function unassignStorageRule(return (client as SupabaseClient<Database>).from(table).delete()- .eq(idCol, args.targetId)+ .eq(unchecked(idCol), args.targetId).eq("ruleId", args.ruleId);}diff --git a/packages/files/AGENTS.md b/packages/files/AGENTS.mdindex a6e2e43cfb..587a5a1c65 100644--- a/packages/files/AGENTS.md+++ b/packages/files/AGENTS.md@@ -6,7 +6,7 @@ in the codebase, shared by the browser, Node, and the Supabase edge runtime.| Subpath | Provides ||---------|----------|-| `.` (root) | Cross-type helpers: `MEDIA_CONTENT_TYPES` + `getContentType` (the one extension→MIME map every file-serving route uses), `getFileExtension` / `effectiveExtension` (`.zst` unwrap), `getDocumentType` / `documentTypes` / `isPreviewableDocumentType` (file classification for the Documents UI), `convertKbToString`, and `downloadBlob` / `downloadText` — THE browser "save this as a file" sequence (object URL → anchor click → revoke); never hand-roll it. **`storage(client)`** — the Carbon storage client, supabase-shaped: `.from(bucket)` is plain supabase for `public` / `temp-staging`; `.company(companyId)` is that company's private bucket (bucket id = companyId, THROWS on an empty id) with the legacy shared `private` bucket folded in — reads (`download` / `info` / `createSignedUrl`) fall back to it, `list` unions both, `remove` deletes from both, writes (`upload` / `move` / `copy` / `createSignedUploadUrl`) go to the company bucket only. Every key must sit under `${companyId}/` (under a service-role client that prefix is the ONLY tenant boundary on the shared legacy bucket) and pass `isUnsafeStoragePath`; anything else gets `{ data: null, error }` without touching storage. **`isUnsafeStoragePath(path)`** is THE storage-key traversal guard (dot segments, `\`, `?`, `#`, control characters, checked as given and after every decode so `%2e%2e` / `%252e%252e` are caught; malformed escapes refused) — every route that takes a key from a URL or form calls it rather than a local copy; **`safeStorageFileName(name)`** turns a caller-supplied file name into a safe last key segment (basename, no `%`) or null. This is the contract for document keys (`${companyId}/parts/…`, `/job/…`, `/tmp/…`, everything `getPrivateUrl` serves); the backup and audit-archive layouts (`exports/…`, `audit/…`) share the bucket under their own keys and keep using plain `client.storage.from(companyId)`. All legacy-bucket fallback lives in `storage.ts` so removing it later is a one-file change; `getCompanyPrivateBucket` / `LEGACY_PRIVATE_BUCKET` / `hasCompanyPrivateObjectPathPrefix` are exported for the few places that need the bucket *name* (MediaUploader staging, route authorization, the assembler's bucket resolver) |+| `.` (root) | Cross-type helpers: `MEDIA_CONTENT_TYPES` + `getContentType` (the one extension→MIME map every file-serving route uses), `getFileExtension` / `effectiveExtension` (`.zst` unwrap), `getDocumentType` / `documentTypes` / `isPreviewableDocumentType` (file classification for the Documents UI), `convertKbToString`, and `downloadBlob` / `downloadText` — THE browser "save this as a file" sequence (object URL → anchor click → revoke); never hand-roll it. **`storage(client)`** — the Carbon storage client, supabase-shaped: `.from(bucket)` is plain supabase for `public` / `temp-staging`; `.company(companyId)` is that company's private bucket (bucket id = companyId, THROWS on an empty id). Writes go to the company bucket only; reads (`download`, `info`, `exists`, `createSignedUrl`) fall back to the legacy shared `private` bucket, `move` retries as a move OUT of it, `list` unions both and `remove` deletes from both. The fallback stays until nothing writes to `private` any more: the one-off copy (`scripts/one-off/migrate-private-buckets.ts`) ran, but files have landed there since. `list(folder)` takes no options: it reads the cursor-paged `listV2` endpoint to the end in both buckets and returns every entry directly inside the folder, sorted by name, in the old `list` shape (`name` is the entry's own name; a sub-folder has a null `id`), the company copy winning a tie. Every key must sit under `${companyId}/` and pass `isUnsafeStoragePath`; anything else gets `{ data: null, error }` without touching storage. **`isUnsafeStoragePath(path)`** is THE storage-key traversal guard (dot segments, `\`, `?`, `#`, control characters, checked as given and after every decode so `%2e%2e` / `%252e%252e` are caught; malformed escapes refused) — every route that takes a key from a URL or form calls it rather than a local copy; **`safeStorageFileName(name)`** turns a caller-supplied file name into a safe last key segment (basename, no `%`) or null. This is the contract for document keys (`${companyId}/parts/…`, `/job/…`, `/tmp/…`, everything `getPrivateUrl` serves); the backup and audit-archive layouts (`exports/…`, `audit/…`) share the bucket under their own keys and keep using plain `client.storage.from(companyId)`. `getCompanyPrivateBucket` / `LEGACY_PRIVATE_BUCKET` / `hasCompanyPrivateObjectPathPrefix` are exported for the few places that need the bucket *name* (MediaUploader staging, route authorization, the assembler's bucket resolver) || `./csv` | `encodeCsv` (object rows) / `encodeCsvTable` (header + cells) — the ONE CSV encoder, injection-safe by construction (`stripCsvFormulaPrefix` on every string cell); `parseCsv` (text) / `parseCsvFile` (browser File, streamed); `downloadCsv`; `CSV_CONTENT_TYPE`. papaparse underneath, in every runtime. The Table export button, report exports, import templates, import-error re-exports and the sales CSV import all go through here — before this there were two libraries (`json-2-csv` + papaparse) and two hand-rolled encoders, and only ONE of the five export sites protected against formula injection || `./media` | Images. **`MediaUploader`** — the configured client (constructor takes the storage client + HEIC staging location once, files-sdk style): `prepareForUpload(files)` (HEIC → JPEG sequentially + duplicate-name refusal, throws `DuplicateFileNameError`), `convertHeic(file)`, `prepareImage(file, shape)`. Underneath: `processImage` (the pipeline), `prepareImageUpload` (pipeline → native-decode fallback → imgproxy fallback), `convertHeicToJpeg` / `convertHeicFiles` / `findDuplicateFileName`, `transformImageViaStorage` (imgproxy round-trip), `isHeic`, `IMAGE_UPLOAD_MIME_TYPES`, plus the storage-path helpers `getPrivateUrl` / `getRawModelUrl` / `parseJobFilePath` || `./media/node` | `initNodeImageCodecs()` — Node-only wasm pre-instantiation; call once before the pipeline in Node (jobs, paperless, vitest). The wasm comes from the BUNDLER (`?inline` data URIs), never off disk — so this module is consumable only from a Vite pipeline, and that pipeline needs `assetsInclude: ["**/*.wasm"]` (already set in `apps/erp/vite.config.ts` and `@carbon/config/vitest`). Never import from client code |diff --git a/packages/files/src/storage.test.ts b/packages/files/src/storage.test.tsindex 39ef234b76..fa44017fd3 100644--- a/packages/files/src/storage.test.ts+++ b/packages/files/src/storage.test.ts@@ -38,7 +38,7 @@ const makeClient = (buckets: Record<string, Record<string, unknown>>) => ({info: vi.fn(() => fail("not found")),download: vi.fn(() => fail("not found")),createSignedUrl: vi.fn(() => fail("not found")),- list: vi.fn(() => ok([])),+ listV2: vi.fn(() => ok({ hasNext: false, folders: [], objects: [] })),remove: vi.fn(() => ok([])),...buckets[bucket]}) as unknown as Bucket@@ -360,51 +360,193 @@ describe("storage(client).company", () => {});describe("list", () => {- it("unions both buckets with the company bucket winning ties", async () => {+ const file = (key: string, id: string) => ({+ key,+ name: `co1/docs/${key}`,+ id,+ metadata: { size: 1 }+ });+ // The paged endpoint's folder shape: no id, no metadata.+ const folder = (key: string) => ({ key, name: `co1/docs/${key}/` });++ it("returns the folder's entries by their own names, sorted", async () => {+ const listV2 = vi.fn(() =>+ ok({+ hasNext: false,+ folders: [folder("zeta"), folder("alpha")],+ objects: [file("b.pdf", "2"), file("a.pdf", "1")]+ })+ );+ const legacy = vi.fn(() =>+ ok({ hasNext: false, folders: [], objects: [] })+ );const client = makeClient({- co1: { list: vi.fn(() => ok([{ name: "a.pdf", id: "new" }])) },- [LEGACY_PRIVATE_BUCKET]: {- list: vi.fn(() =>- ok([- { name: "a.pdf", id: "old" },- { name: "b.pdf", id: "legacy-only" }- ])- )- }+ co1: { listV2 },+ [LEGACY_PRIVATE_BUCKET]: { listV2: legacy }});+const { data, error } = await storage(client).company("co1")- .list("co1/docs", { limit: 10 });+ .list("co1/docs");+expect(error).toBeNull();- expect(data?.map((f) => [f.name, f.id]).sort()).toEqual([- ["a.pdf", "new"],- ["b.pdf", "legacy-only"]+ expect(data?.map((f) => [f.name, f.id])).toEqual([+ ["a.pdf", "1"],+ ["alpha", null],+ ["b.pdf", "2"],+ ["zeta", null]]);- expect(client.storage.from("co1").list).toHaveBeenCalledWith("co1/docs", {- limit: 10+ expect(data?.[0]?.metadata).toEqual({ size: 1 });+ expect(data?.[1]).toEqual({+ key: "alpha",+ name: "alpha",+ id: null,+ updated_at: null,+ created_at: null,+ last_accessed_at: null,+ metadata: null+ });+ });++ it("unions both buckets with the company bucket winning ties", async () => {+ const own = vi.fn(() =>+ ok({ hasNext: false, folders: [], objects: [file("b.pdf", "own")] })+ );+ const legacy = vi.fn(() =>+ ok({+ hasNext: false,+ folders: [],+ objects: [file("b.pdf", "legacy"), file("a.pdf", "legacy")]+ })+ );+ const client = makeClient({+ co1: { listV2: own },+ [LEGACY_PRIVATE_BUCKET]: { listV2: legacy }});++ const { data } = await storage(client).company("co1").list("co1/docs");++ expect(data?.map((f) => [f.name, f.id])).toEqual([+ ["a.pdf", "legacy"],+ ["b.pdf", "own"]+ ]);});it("still returns the healthy bucket's rows when the other errors", async () => {const client = makeClient({- co1: { list: vi.fn(() => fail("bucket missing")) },- [LEGACY_PRIVATE_BUCKET]: { list: vi.fn(() => ok([{ name: "b.pdf" }])) }+ co1: { listV2: vi.fn(() => fail("bucket not found")) },+ [LEGACY_PRIVATE_BUCKET]: {+ listV2: vi.fn(() =>+ ok({ hasNext: false, folders: [], objects: [file("a.pdf", "1")] })+ )+ }});+const { data, error } = await storage(client).company("co1").list("co1/docs");+expect(error).toBeNull();- expect(data?.map((f) => f.name)).toEqual(["b.pdf"]);+ expect(data?.map((f) => f.name)).toEqual(["a.pdf"]);+ });++ it("lists what is inside the folder, with or without a trailing slash", async () => {+ for (const path of ["co1/docs", "co1/docs/"]) {+ const listV2 = vi.fn(() =>+ ok({ hasNext: false, folders: [], objects: [] })+ );+ await storage(makeClient({ co1: { listV2 } }))+ .company("co1")+ .list(path);+ expect(listV2).toHaveBeenCalledWith({+ prefix: "co1/docs/",+ with_delimiter: true,+ cursor: undefined+ });+ }+ });++ it("reads every page", async () => {+ const pages = [+ {+ hasNext: true,+ nextCursor: "c1",+ folders: [],+ objects: [file("a.pdf", "1")]+ },+ {+ hasNext: true,+ nextCursor: "c2",+ folders: [],+ objects: [file("b.pdf", "2")]+ },+ { hasNext: false, folders: [], objects: [file("c.pdf", "3")] }+ ];+ const listV2 = vi.fn((options: { cursor?: string }) =>+ ok(pages[["c1", "c2"].indexOf(options.cursor ?? "") + 1])+ );++ const { data } = await storage(makeClient({ co1: { listV2 } }))+ .company("co1")+ .list("co1/docs");++ expect(data?.map((f) => f.name)).toEqual(["a.pdf", "b.pdf", "c.pdf"]);+ });++ it.each([+ ["repeats the cursor", "c1"],+ ["gives no cursor", undefined]+ ])("fails when a page promises more and %s", async (_, nextCursor) => {+ const listV2 = vi.fn(() =>+ ok({+ hasNext: true,+ nextCursor,+ folders: [],+ objects: [file("a.pdf", "1")]+ })+ );++ const { data, error } = await storage(+ makeClient({ co1: { listV2 }, private: { listV2 } })+ )+ .company("co1")+ .list("co1/docs");++ expect(data).toBeNull();+ expect(error?.message).toContain("did not advance");+ expect(listV2.mock.calls.length).toBeLessThanOrEqual(4);+ });++ it("drops a bucket whose later page fails instead of keeping part of it", async () => {+ const listV2 = vi.fn((options: { cursor?: string }) =>+ options.cursor+ ? fail("storage down")+ : ok({+ hasNext: true,+ nextCursor: "c1",+ folders: [],+ objects: [file("a.pdf", "1")]+ })+ );++ const { data, error } = await storage(makeClient({ co1: { listV2 } }))+ .company("co1")+ .list("co1/docs");++ expect(error).toBeNull();+ expect(data).toEqual([]);});it("reports the company error when both buckets fail", async () => {const client = makeClient({- co1: { list: vi.fn(() => fail("company down")) },- [LEGACY_PRIVATE_BUCKET]: { list: vi.fn(() => fail("legacy down")) }+ co1: { listV2: vi.fn(() => fail("company down")) },+ [LEGACY_PRIVATE_BUCKET]: { listV2: vi.fn(() => fail("legacy down")) }});+const { data, error } = await storage(client).company("co1").list("co1/docs");+expect(data).toBeNull();expect(error?.message).toBe("company down");});diff --git a/packages/files/src/storage.ts b/packages/files/src/storage.tsindex 26f7d947d0..5376f094a7 100644--- a/packages/files/src/storage.ts+++ b/packages/files/src/storage.ts@@ -9,9 +9,10 @@* Object keys keep the legacy `${companyId}/...` first segment so paths* stored in the database stay valid and the legacy→company copy is same-key.*- * The legacy shared `private` bucket is a read-only fallback until the copy- * script has run everywhere; every fallback lives in this file so removing- * it later is a one-file change.+ * The legacy shared `private` bucket is a read-only fallback: the one-off copy+ * (`scripts/one-off/migrate-private-buckets.ts`) moved what existed when it+ * ran, but files have landed there since. Every fallback lives in this file so+ * removing it later is a one-file change.** const { data, error } = await storage(client).company(companyId).download(path);* await storage(client).company(companyId).upload(path, file, { upsert: true });@@ -20,7 +21,8 @@import {type DownloadResult,- type SearchOptions,+ type FileObject,+ type SearchV2Result,type StorageClient,StorageError,type TransformOptions@@ -131,9 +133,13 @@ type Bucket = ReturnType<StorageClient["from"]>;* tenant boundary on the shared legacy bucket, and a company bucket must never* hold a key that `getPrivateUrl` would resolve to another company's bucket.*- * Deliberately absent: `getPublicUrl` (private bucket), `createSignedUrls`- * and `listV2` (batch shapes with no single fallback answer). Use `.from()`- * if one is ever needed.+ * `list(folder)` returns EVERY entry directly inside the folder, sorted by+ * name, in the shape the old list endpoint used (a sub-folder is an entry with+ * a null `id`). It takes no options — it reads the cursor-paged list endpoint+ * to the end, so there is no limit or offset to pass.+ *+ * Deliberately absent: `getPublicUrl` (private bucket) and `createSignedUrls`.+ * Use `.from()` if one is ever needed.*/export type CompanyBucket = {upload: Bucket["upload"];@@ -149,8 +155,8 @@ export type CompanyBucket = {options?: { transform?: TransformOptions }): Promise<DownloadResult<Blob>>;createSignedUrl: Bucket["createSignedUrl"];- list(prefix: string, options?: SearchOptions): ReturnType<Bucket["list"]>;- remove: Bucket["remove"];+ list(folder: string): ReturnType<Bucket["list"]>;+ remove(paths: string[]): ReturnType<Bucket["remove"]>;};export type CarbonStorage = {@@ -200,6 +206,63 @@ export async function isStorageNotFound(error: unknown): Promise<boolean> {return body?.statusCode === "404";}+const lastSegment = (path: string) =>+ path.replace(/\/+$/, "").split("/").pop() ?? "";++// What the old endpoint returned for a folder, and every caller checks:+// the paged endpoint gives a folder only its name and key.+const FOLDER_FIELDS = {+ id: null,+ updated_at: null,+ created_at: null,+ last_accessed_at: null,+ metadata: null+};++type ListedEntry =+ | (SearchV2Result["folders"][number] & typeof FOLDER_FIELDS)+ | SearchV2Result["objects"][number];++/**+ * The cursor-paged endpoint names an entry by its full key; callers expect the+ * old endpoint's shape, where `name` is the entry's own name inside the folder.+ */+function toFileObjects(entries: ListedEntry[]): FileObject[] {+ return entries.map((entry) => ({+ ...entry,+ name: lastSegment(entry.key ?? entry.name)+ })) as unknown as FileObject[];+}++/** Everything directly inside `prefix`, read to the last page. */+async function listFolder(bucket: Bucket, prefix: string) {+ const entries: ListedEntry[] = [];+ let cursor: string | undefined;+ do {+ const { data, error } = await bucket.listV2({+ prefix,+ with_delimiter: true,+ cursor+ });+ if (error) return { data: null, error };+ entries.push(+ ...data.folders.map((folder) => ({ ...FOLDER_FIELDS, ...folder })),+ ...data.objects+ );+ if (!data.hasNext) break;+ // More pages promised with no way to reach them: a repeated cursor would+ // loop forever, a missing one would pass a partial list off as complete.+ if (!data.nextCursor || data.nextCursor === cursor) {+ return {+ data: null,+ error: new StorageError(`Listing "${prefix}" did not advance`)+ };+ }+ cursor = data.nextCursor;+ } while (cursor);+ return { data: toFileObjects(entries), error: null };+}+export function storage(client: { storage: StorageClient }): CarbonStorage {return {from: (bucket) => client.storage.from(bucket),@@ -254,11 +317,10 @@ function companyBucket(owns(path) ? own.update(path, ...rest) : refuse(path),uploadToSignedUrl: (path, ...rest) =>owns(path) ? own.uploadToSignedUrl(path, ...rest) : refuse(path),- // A file uploaded before the per-company copy ran still lives only in the- // legacy bucket, so a move within the company bucket finds nothing. Retry- // it as a cross-bucket move OUT of legacy: `/object/move` takes a- // `destinationBucket`, so this stays one server-side operation rather than- // a download/upload/remove dance. Honours an explicit destinationBucket.+ // A file that exists only in the legacy bucket is not found by a move+ // within the company bucket. Retry it as a cross-bucket move OUT of+ // legacy: `/object/move` takes a `destinationBucket`, so this stays one+ // server-side operation. Honours an explicit destinationBucket.move: async (from, to, options) => {if (!owns(from, to)) return refuse(from, to);const primary = await own.move(from, to, options);@@ -289,18 +351,24 @@ function companyBucket(? withFallback((b) => b.createSignedUrl(path, expiresIn, options)): refuse(path),- list: async (prefix, options) => {- if (!owns(prefix)) return refuse(prefix);+ list: async (folder) => {+ if (!owns(folder)) return refuse(folder);+ // The endpoint matches a plain key prefix, so without the trailing slash+ // it would answer with the folder itself rather than what is inside it.+ const prefix = `${folder.replace(/\/+$/, "")}/`;const [primary, fallback] = await Promise.all([- own.list(prefix, options),- legacy.list(prefix, options)+ listFolder(own, prefix),+ listFolder(legacy, prefix)]);if (primary.error && fallback.error) return primary;- // Union by name with the company copy winning: during the fallback- // window a file sits in either bucket, after the copy script in both.+ // Union by name with the company copy winning: a file sits in either+ // bucket, and after the copy script in both.const byName = new Map((fallback.data ?? []).map((f) => [f.name, f]));for (const f of primary.data ?? []) byName.set(f.name, f);- return { data: [...byName.values()], error: null };+ const files = [...byName.values()].sort((a, b) =>+ a.name < b.name ? -1 : a.name > b.name ? 1 : 0+ );+ return { data: files, error: null };},remove: async (paths) => {diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.mdindex 04775a34e8..b42943645a 100644--- a/packages/jobs/AGENTS.md+++ b/packages/jobs/AGENTS.md@@ -21,7 +21,7 @@ Server-only Inngest jobs for event draining, integrations, notifications, workfl## Never-- Never import `@carbon/jobs/inngest` or worker modules into browser bundles. App code normally imports only `@carbon/jobs`.+- Never import `@carbon/jobs/inngest` into browser bundles. App code normally imports only `@carbon/jobs`.- Never use the async event system for data-integrity or real-time guarantees; use database constraints/interceptors.- Never write handler tables directly; database triggers route changes through `dispatch_event_batch()` and PGMQ.- Never give workflow actions a service-role/untagged business client; it bypasses the owner's permissions and workflow loop guards.@@ -45,7 +45,6 @@ pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id> # MRP +| `./events` | `Events` type || `./inngest` | Inngest client plus workflow dispatch/manual-run server seams || `./backups` | Import-light backup catalog, scope, and compatibility helpers |-| `./worker` | Inngest worker entry point |## Durable Entry Pointsdiff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.jsonindex a8cce18ad3..a07da4736b 100644--- a/packages/jobs/manifests/schema.json+++ b/packages/jobs/manifests/schema.json@@ -1,11 +1,11 @@{"kind": "carbon-company-backup","version": 1,- "schemaVersion": "20260930133226",+ "schemaVersion": "20261001195204","sourceCompanyId": "schema-baseline","sourceCompanyGroupId": null,"sourceCompanyName": null,- "exportedAt": "2026-09-30T18:00:33.029Z",+ "exportedAt": "2026-10-01T23:59:25.768Z","exportedBy": "schema-baseline","label": "schema baseline","includeStorage": "none",@@ -2939,6 +2939,7 @@"type","samplingSeverity","samplingSampleSize",+ "gaugeTypeId","label","createdAt","samplingInspectionLevel",@@ -4600,6 +4601,7 @@"rows": 0,"columns": ["discountPercent",+ "priceTrace","unitPrice","quoteLineId","quantity",@@ -4806,6 +4808,7 @@"columns": ["createdAt","companyId",+ "gaugeId","inspectionId","rejectionNumber","updatedBy",@@ -4814,6 +4817,7 @@"codeLetter","sampleSize","inspectionFeatureId",+ "gaugeRecordedAt","acceptanceNumber","updatedAt"]diff --git a/packages/jobs/package.json b/packages/jobs/package.jsonindex 8dba33fdc3..3c7a8cbe8e 100644--- a/packages/jobs/package.json+++ b/packages/jobs/package.json@@ -49,8 +49,7 @@".": "./src/index.ts","./backups": "./src/backups/schema.ts","./events": "./src/events.ts",- "./inngest": "./src/inngest/index.ts",- "./worker": "./src/inngest/worker.ts"+ "./inngest": "./src/inngest/index.ts"},"main": "./src/index.ts","name": "@carbon/jobs",diff --git a/packages/jobs/src/inngest/functions/events/pack.test.ts b/packages/jobs/src/inngest/functions/events/pack.test.tsnew file mode 100644index 0000000000..d357a01cec--- /dev/null+++ b/packages/jobs/src/inngest/functions/events/pack.test.ts@@ -0,0 +1,35 @@+// 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 { packBySize } from "./pack";++const row = (id: number, bytes: number) => ({ id, pad: "x".repeat(bytes) });++describe("packBySize", () => {+ it("keeps order and fills each pack up to the byte budget", () => {+ const items = [row(1, 400), row(2, 400), row(3, 400), row(4, 400)];+ const packs = packBySize(items, 1000);+ expect(packs.map((p) => p.map((i) => i.id))).toEqual([+ [1, 2],+ [3, 4]+ ]);+ });++ it("sends an item larger than the budget on its own", () => {+ const packs = packBySize([row(1, 50), row(2, 5000), row(3, 50)], 1000);+ expect(packs.map((p) => p.map((i) => i.id))).toEqual([[1], [2], [3]]);+ });++ it("caps the item count per pack", () => {+ const items = [1, 2, 3, 4, 5].map((id) => row(id, 1));+ expect(packBySize(items, 1_000_000, 2).map((p) => p.length)).toEqual([+ 2, 2, 1+ ]);+ });++ it("returns no packs for no items", () => {+ expect(packBySize([], 1000)).toEqual([]);+ });+});diff --git a/packages/jobs/src/inngest/functions/events/pack.ts b/packages/jobs/src/inngest/functions/events/pack.tsnew file mode 100644index 0000000000..f6ae055cd1--- /dev/null+++ b/packages/jobs/src/inngest/functions/events/pack.ts@@ -0,0 +1,35 @@+// 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.++/**+ * Splits `items` into order-preserving packs that each serialize to at most+ * `maxBytes` and hold at most `maxItems`. An item larger than the budget+ * travels alone rather than being dropped.+ */+export function packBySize<T>(+ items: T[],+ maxBytes: number,+ maxItems = Number.POSITIVE_INFINITY+): T[][] {+ const packs: T[][] = [];+ let current: T[] = [];+ let bytes = 0;++ for (const item of items) {+ const size = Buffer.byteLength(JSON.stringify(item));+ if (+ current.length > 0 &&+ (bytes + size > maxBytes || current.length >= maxItems)+ ) {+ packs.push(current);+ current = [];+ bytes = 0;+ }+ current.push(item);+ bytes += size;+ }++ if (current.length > 0) packs.push(current);+ return packs;+}diff --git a/packages/jobs/src/inngest/functions/events/queue.ts b/packages/jobs/src/inngest/functions/events/queue.tsindex 784c100a7f..b42a29519f 100644--- a/packages/jobs/src/inngest/functions/events/queue.ts+++ b/packages/jobs/src/inngest/functions/events/queue.ts@@ -6,21 +6,16 @@ import type { HandlerType, QueueMessage } from "@carbon/database/event";import { sql } from "kysely";import { getJobDatabaseClient } from "../../../db";import { inngest } from "../../client";+import { packBySize } from "./pack";const QUEUE_NAME = "event_system"; // Name of the PGMQ queueconst BATCH_SIZE = 100; // Number of messages to process per passconst VISIBILITY_TIMEOUT = 30; // Seconds a message is hidden after being read-const CHUNK_SIZE = 10; // Max events per sendEvent call (keeps under 256KB limit)+const MAX_EVENT_BYTES = 200_000; // Inngest caps an event at 256KB+const MAX_RECORDS = 50; // Records per batched handler event+const MAX_SLOW_RECORDS = 10; // ...for handlers that call an external service per recordconst MAX_PASSES = 10; // Max read/dispatch/delete passes per run (~1000 msgs)-function chunk<T>(arr: T[], size: number): T[][] {- const chunks: T[][] = [];- for (let i = 0; i < arr.length; i += size) {- chunks.push(arr.slice(i, i + size));- }- return chunks;-}-type QueueJob = {msg_id: number;message: QueueMessage;@@ -138,7 +133,7 @@ export const eventQueueFunction = inngest.createFunction(}}));- const chunks = chunk(events, CHUNK_SIZE);+ const chunks = packBySize(events, MAX_EVENT_BYTES);for (let i = 0; i < chunks.length; i++) {await step.sendEvent(`dispatch-webhooks-${pass}-${i}`, chunks[i]!);}@@ -157,7 +152,7 @@ export const eventQueueFunction = inngest.createFunction(}}));- const chunks = chunk(events, CHUNK_SIZE);+ const chunks = packBySize(events, MAX_EVENT_BYTES);for (let i = 0; i < chunks.length; i++) {await step.sendEvent(`dispatch-workflows-${pass}-${i}`, chunks[i]!);}@@ -171,7 +166,7 @@ export const eventQueueFunction = inngest.createFunction(handlerConfig: job.message.handlerConfig}));- const chunks = chunk(records, CHUNK_SIZE);+ const chunks = packBySize(records, MAX_EVENT_BYTES, MAX_SLOW_RECORDS);for (let i = 0; i < chunks.length; i++) {await step.sendEvent(`dispatch-syncs-${pass}-${i}`, {name: "carbon/event-sync" as const,@@ -187,7 +182,7 @@ export const eventQueueFunction = inngest.createFunction(companyId: job.message.companyId}));- const chunks = chunk(records, CHUNK_SIZE);+ const chunks = packBySize(records, MAX_EVENT_BYTES, MAX_RECORDS);for (let i = 0; i < chunks.length; i++) {await step.sendEvent(`dispatch-searches-${pass}-${i}`, {name: "carbon/event-search" as const,@@ -205,7 +200,7 @@ export const eventQueueFunction = inngest.createFunction(handlerConfig: job.message.handlerConfig}));- const chunks = chunk(records, CHUNK_SIZE);+ const chunks = packBySize(records, MAX_EVENT_BYTES, MAX_RECORDS);for (let i = 0; i < chunks.length; i++) {await step.sendEvent(`dispatch-audits-${pass}-${i}`, {name: "carbon/event-audit" as const,@@ -221,7 +216,7 @@ export const eventQueueFunction = inngest.createFunction(companyId: job.message.companyId}));- const chunks = chunk(records, CHUNK_SIZE);+ const chunks = packBySize(records, MAX_EVENT_BYTES, MAX_SLOW_RECORDS);for (let i = 0; i < chunks.length; i++) {await step.sendEvent(`dispatch-embeddings-${pass}-${i}`, {name: "carbon/event-embedding" as const,diff --git a/packages/jobs/src/inngest/functions/events/search-config.test.ts b/packages/jobs/src/inngest/functions/events/search-config.test.tsnew file mode 100644index 0000000000..2ca29cd308--- /dev/null+++ b/packages/jobs/src/inngest/functions/events/search-config.test.ts@@ -0,0 +1,126 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ planIndexWrites,+ planLookups,+ type SearchEvent,+ toIndexRow+} from "./search-config";++const event = (+ table: string,+ operation: SearchEvent["operation"],+ recordId: string,+ record: Record<string, any> | null = { id: recordId }+): SearchEvent => ({ table, operation, recordId, new: record });++describe("planIndexWrites", () => {+ it("keeps only the last event per record", () => {+ const plan = planIndexWrites([+ event("job", "INSERT", "job_1"),+ event("job", "UPDATE", "job_1", { id: "job_1", jobId: "J-2" }),+ event("job", "INSERT", "job_2"),+ event("job", "DELETE", "job_2", null)+ ]);++ expect(plan.upserts.map((u) => u.record)).toEqual([+ { id: "job_1", jobId: "J-2" }+ ]);+ expect(plan.deletes).toEqual([{ entity_type: "job", entity_id: "job_2" }]);+ expect(plan.skipped).toBe(2);+ });++ it("removes a deactivated employee and skips tables it does not index", () => {+ const plan = planIndexWrites([+ event("employee", "UPDATE", "u_1", { id: "u_1", active: false }),+ event("jobOperation", "UPDATE", "op_1")+ ]);++ expect(plan.deletes).toEqual([+ { entity_type: "employee", entity_id: "u_1" }+ ]);+ expect(plan.upserts).toEqual([]);+ expect(plan.skipped).toBe(1);+ });+});++describe("lookups", () => {+ const { upserts } = planIndexWrites([+ event("job", "INSERT", "job_1", {+ id: "job_1",+ jobId: "J-1",+ itemId: "item_1",+ customerId: "cust_1",+ status: "Ready"+ }),+ event("job", "INSERT", "job_2", {+ id: "job_2",+ jobId: "J-2",+ itemId: "item_1",+ customerId: null+ }),+ event("customer", "INSERT", "cust_1", { id: "cust_1", name: "Acme" })+ ]);++ it("reads each related table once for the whole batch", () => {+ expect(planLookups(upserts)).toEqual([+ {+ key: "item.id.name",+ table: "item",+ column: "name",+ matchOn: "id",+ companyScoped: true,+ ids: ["item_1"]+ },+ {+ key: "customer.id.name",+ table: "customer",+ column: "name",+ matchOn: "id",+ companyScoped: true,+ ids: ["cust_1"]+ },+ {+ key: "customerTax.customerId.taxId",+ table: "customerTax",+ column: "taxId",+ matchOn: "customerId",+ companyScoped: true,+ ids: ["cust_1"]+ }+ ]);+ });++ it("limits every lookup to the company except the global user table", () => {+ const employee = planIndexWrites([+ event("employee", "INSERT", "u_1", { id: "u_1", employeeTypeId: "et_1" })+ ]).upserts;+ expect(+ planLookups(employee).map((plan) => [plan.table, plan.companyScoped])+ ).toEqual([+ ["user", false],+ ["employeeType", true]+ ]);+ });++ it("builds the index row from the record and its looked-up names", () => {+ const resolved = new Map([+ ["item.id.name", new Map<string, unknown>([["item_1", "Bracket"]])],+ ["customer.id.name", new Map<string, unknown>([["cust_1", "Acme"]])]+ ]);++ expect(toIndexRow(upserts[0]!, resolved)).toEqual({+ entity_type: "job",+ entity_id: "job_1",+ title: "J-1",+ description: "Bracket Acme",+ link: "/x/job/job_1",+ tags: ["Ready"],+ metadata: { quantity: undefined, dueDate: undefined }+ });+ expect(toIndexRow(upserts[1]!, resolved).description).toBe("Bracket ");+ });+});diff --git a/packages/jobs/src/inngest/functions/events/search-config.ts b/packages/jobs/src/inngest/functions/events/search-config.tsnew file mode 100644index 0000000000..a7f94a0698--- /dev/null+++ b/packages/jobs/src/inngest/functions/events/search-config.ts@@ -0,0 +1,439 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++/**+ * A related name copied onto the index row: `field` is set to `table.column`+ * of the row whose `matchOn` (default `id`) equals `record[from]`. The read is+ * limited to the record's company unless the table is `global` (has no+ * companyId).+ */+export type SearchLookup = {+ field: string;+ table: string;+ column: string;+ from: string;+ matchOn?: string;+ global?: true;+};++// Configuration for each entity type's search indexing+export type SearchEntityConfig = {+ entityType: string;+ getTitle: (record: Record<string, any>) => string;+ getDescription?: (record: Record<string, any>) => string;+ getLink: (record: Record<string, any>) => string;+ getTags: (record: Record<string, any>) => string[];+ getMetadata: (record: Record<string, any>) => Record<string, any>;+ lookups?: SearchLookup[];+};++// Entity configurations matching the existing sync functions+export const SEARCH_ENTITY_CONFIGS: Record<string, SearchEntityConfig> = {+ employee: {+ entityType: "employee",+ getTitle: (r) => r.fullName || "",+ getLink: (r) => `/x/person/${r.id}`,+ getTags: (r) => [r.employeeTypeName].filter(Boolean),+ getMetadata: (r) => ({ active: r.active }),+ lookups: [+ {+ field: "fullName",+ table: "user",+ column: "fullName",+ from: "id",+ global: true+ },+ {+ field: "employeeTypeName",+ table: "employeeType",+ column: "name",+ from: "employeeTypeId"+ }+ ]+ },+ customer: {+ entityType: "customer",+ getTitle: (r) => r.name,+ getLink: (r) => `/x/customer/${r.id}`,+ getTags: (r) => [r.customerTypeName, r.customerStatusName].filter(Boolean),+ getMetadata: (r) => ({ taxId: r.taxId }),+ lookups: [+ {+ field: "customerTypeName",+ table: "customerType",+ column: "name",+ from: "customerTypeId"+ },+ {+ field: "customerStatusName",+ table: "customerStatus",+ column: "name",+ from: "customerStatusId"+ },+ {+ field: "taxId",+ table: "customerTax",+ column: "taxId",+ from: "id",+ matchOn: "customerId"+ }+ ]+ },+ supplier: {+ entityType: "supplier",+ getTitle: (r) => r.name,+ getLink: (r) => `/x/supplier/${r.id}`,+ getTags: (r) => [r.supplierTypeName, r.supplierStatus].filter(Boolean),+ getMetadata: (r) => ({ taxId: r.taxId }),+ lookups: [+ {+ field: "supplierTypeName",+ table: "supplierType",+ column: "name",+ from: "supplierTypeId"+ },+ {+ field: "taxId",+ table: "supplierTax",+ column: "taxId",+ from: "id",+ matchOn: "supplierId"+ }+ ]+ },+ item: {+ entityType: "item",+ getTitle: (r) => r.readableId,+ getDescription: (r) => `${r.name} ${r.description || ""}`,+ getLink: (r) => {+ const typeLinks: Record<string, string> = {+ Part: "/x/part/",+ Service: "/x/service/",+ Tool: "/x/tool/",+ Consumable: "/x/consumable/",+ Material: "/x/material/",+ Fixture: "/x/fixture/"+ };+ return (typeLinks[r.type] || "/x/part/") + r.id;+ },+ getTags: (r) => [r.type, r.replenishmentSystem].filter(Boolean),+ getMetadata: (r) => ({ active: r.active })+ },+ job: {+ entityType: "job",+ getTitle: (r) => r.jobId,+ getDescription: (r) => `${r.itemName || ""} ${r.customerName || ""}`,+ getLink: (r) => `/x/job/${r.id}`,+ getTags: (r) => [r.status, r.deadlineType].filter(Boolean),+ getMetadata: (r) => ({ quantity: r.quantity, dueDate: r.dueDate }),+ lookups: [+ { field: "itemName", table: "item", column: "name", from: "itemId" },+ {+ field: "customerName",+ table: "customer",+ column: "name",+ from: "customerId"+ }+ ]+ },+ purchaseOrder: {+ entityType: "purchaseOrder",+ getTitle: (r) => r.purchaseOrderId,+ getDescription: (r) => r.supplierName || "",+ getLink: (r) => `/x/purchase-order/${r.id}`,+ getTags: (r) => [r.status].filter(Boolean),+ getMetadata: (r) => ({+ orderDate: r.orderDate,+ supplierReference: r.supplierReference+ }),+ lookups: [+ {+ field: "supplierName",+ table: "supplier",+ column: "name",+ from: "supplierId"+ }+ ]+ },+ salesInvoice: {+ entityType: "salesInvoice",+ getTitle: (r) => r.invoiceId,+ getDescription: (r) => r.customerName || "",+ getLink: (r) => `/x/sales-invoice/${r.id}`,+ getTags: (r) => [r.status].filter(Boolean),+ getMetadata: (r) => ({ totalAmount: r.totalAmount, dateDue: r.dateDue }),+ lookups: [+ {+ field: "customerName",+ table: "customer",+ column: "name",+ from: "customerId"+ }+ ]+ },+ purchaseInvoice: {+ entityType: "purchaseInvoice",+ getTitle: (r) => r.invoiceId,+ getDescription: (r) => r.supplierName || "",+ getLink: (r) => `/x/purchase-invoice/${r.id}`,+ getTags: (r) => [r.status].filter(Boolean),+ getMetadata: (r) => ({ totalAmount: r.totalAmount, dateDue: r.dateDue }),+ lookups: [+ {+ field: "supplierName",+ table: "supplier",+ column: "name",+ from: "supplierId"+ }+ ]+ },+ nonConformance: {+ entityType: "issue",+ getTitle: (r) => r.nonConformanceId,+ getDescription: (r) => `${r.name} ${r.description || ""}`,+ getLink: (r) => `/x/issue/${r.id}`,+ getTags: (r) => [r.status, r.priority, r.ncTypeName].filter(Boolean),+ getMetadata: (r) => ({ source: r.source, dueDate: r.dueDate }),+ lookups: [+ {+ field: "ncTypeName",+ table: "nonConformanceType",+ column: "name",+ from: "nonConformanceTypeId"+ }+ ]+ },+ gauge: {+ entityType: "gauge",+ getTitle: (r) => r.gaugeId,+ getDescription: (r) => `${r.description || ""} ${r.serialNumber || ""}`,+ getLink: (r) => `/x/quality/gauges/${r.id}`,+ getTags: (r) =>+ [r.gaugeStatus, r.gaugeCalibrationStatus, r.gaugeTypeName].filter(+ Boolean+ ),+ getMetadata: (r) => ({+ nextCalibrationDate: r.nextCalibrationDate,+ serialNumber: r.serialNumber+ }),+ lookups: [+ {+ field: "gaugeTypeName",+ table: "gaugeType",+ column: "name",+ from: "gaugeTypeId"+ }+ ]+ },+ quote: {+ entityType: "quote",+ getTitle: (r) => r.quoteId,+ getDescription: (r) =>+ `${r.customerName || ""} ${r.customerReference || ""}`,+ getLink: (r) => `/x/quote/${r.id}`,+ getTags: (r) => [r.status].filter(Boolean),+ getMetadata: (r) => ({+ customerId: r.customerId,+ expirationDate: r.expirationDate,+ customerReference: r.customerReference+ }),+ lookups: [+ {+ field: "customerName",+ table: "customer",+ column: "name",+ from: "customerId"+ }+ ]+ },+ salesRfq: {+ entityType: "salesRfq",+ getTitle: (r) => r.rfqId,+ getDescription: (r) => r.customerName || "",+ getLink: (r) => `/x/rfq/${r.id}`,+ getTags: (r) => [r.status].filter(Boolean),+ getMetadata: (r) => ({+ customerId: r.customerId,+ expirationDate: r.expirationDate+ }),+ lookups: [+ {+ field: "customerName",+ table: "customer",+ column: "name",+ from: "customerId"+ }+ ]+ },+ salesOrder: {+ entityType: "salesOrder",+ getTitle: (r) => r.salesOrderId,+ getDescription: (r) =>+ `${r.customerName || ""} ${r.customerReference || ""}`,+ getLink: (r) => `/x/sales-order/${r.id}`,+ getTags: (r) => [r.status].filter(Boolean),+ getMetadata: (r) => ({+ customerId: r.customerId,+ orderDate: r.orderDate,+ customerReference: r.customerReference+ }),+ lookups: [+ {+ field: "customerName",+ table: "customer",+ column: "name",+ from: "customerId"+ }+ ]+ },+ supplierQuote: {+ entityType: "supplierQuote",+ getTitle: (r) => r.supplierQuoteId,+ getDescription: (r) => r.supplierName || "",+ getLink: (r) => `/x/supplier-quote/${r.id}`,+ getTags: (r) => [r.status].filter(Boolean),+ getMetadata: (r) => ({+ supplierId: r.supplierId,+ expirationDate: r.expirationDate+ }),+ lookups: [+ {+ field: "supplierName",+ table: "supplier",+ column: "name",+ from: "supplierId"+ }+ ]+ }+};++export type SearchEvent = {+ table: string;+ operation: "INSERT" | "UPDATE" | "DELETE" | "TRUNCATE";+ recordId: string;+ new: Record<string, any> | null;+};++type IndexKey = { entity_type: string; entity_id: string };++export type IndexRow = IndexKey & {+ title: string;+ description: string;+ link: string;+ tags: string[];+ metadata: Record<string, any>;+};++type PendingUpsert = {+ config: SearchEntityConfig;+ recordId: string;+ record: Record<string, any>;+};++/**+ * Splits one company's events into index writes. Only the last event per+ * record counts: a row inserted and deleted in the same batch must end up+ * absent, whichever order the handler would have applied them in.+ */+export function planIndexWrites(events: SearchEvent[]) {+ const latest = new Map<string, SearchEvent>();+ for (const event of events) {+ latest.set(`${event.table}:${event.recordId}`, event);+ }++ const deletes: IndexKey[] = [];+ const upserts: PendingUpsert[] = [];+ let skipped = events.length - latest.size;++ for (const event of latest.values()) {+ const config = SEARCH_ENTITY_CONFIGS[event.table];+ if (!config) {+ skipped++;+ continue;+ }++ const removed =+ event.operation === "DELETE" ||+ event.operation === "TRUNCATE" ||+ (event.table === "employee" && event.new?.active === false);++ if (removed) {+ deletes.push({+ entity_type: config.entityType,+ entity_id: event.recordId+ });+ } else if (event.new) {+ upserts.push({ config, recordId: event.recordId, record: event.new });+ } else {+ skipped++;+ }+ }++ return { deletes, upserts, skipped };+}++const lookupKey = (lookup: SearchLookup) =>+ `${lookup.table}.${lookup.matchOn ?? "id"}.${lookup.column}`;++/** One read per distinct lookup, covering every record that needs it. */+export function planLookups(upserts: PendingUpsert[]) {+ const plans = new Map<+ string,+ {+ key: string;+ table: string;+ column: string;+ matchOn: string;+ companyScoped: boolean;+ ids: Set<string>;+ }+ >();++ for (const { config, record } of upserts) {+ for (const lookup of config.lookups ?? []) {+ const id = record[lookup.from];+ if (id === null || id === undefined || id === "") continue;++ const key = lookupKey(lookup);+ let plan = plans.get(key);+ if (!plan) {+ plan = {+ key,+ table: lookup.table,+ column: lookup.column,+ matchOn: lookup.matchOn ?? "id",+ companyScoped: !lookup.global,+ ids: new Set()+ };+ plans.set(key, plan);+ }+ plan.ids.add(String(id));+ }+ }++ return [...plans.values()].map((plan) => ({ ...plan, ids: [...plan.ids] }));+}++/** `resolved` maps a lookup key to the looked-up value per matched id. */+export function toIndexRow(+ { config, recordId, record }: PendingUpsert,+ resolved: Map<string, Map<string, unknown>>+): IndexRow {+ const enriched = { ...record };+ for (const lookup of config.lookups ?? []) {+ enriched[lookup.field] = resolved+ .get(lookupKey(lookup))+ ?.get(String(record[lookup.from]));+ }++ return {+ entity_type: config.entityType,+ entity_id: recordId,+ title: config.getTitle(enriched) ?? "",+ description: config.getDescription?.(enriched) || "",+ link: config.getLink(enriched),+ tags: config.getTags(enriched),+ metadata: config.getMetadata(enriched)+ };+}diff --git a/packages/jobs/src/inngest/functions/events/search.ts b/packages/jobs/src/inngest/functions/events/search.tsindex 16172bbf0e..59d002de01 100644--- a/packages/jobs/src/inngest/functions/events/search.ts+++ b/packages/jobs/src/inngest/functions/events/search.ts@@ -4,337 +4,11 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";import { groupBy } from "@carbon/utils";+import { sql } from "kysely";import { z } from "zod";+import { getJobDatabaseClient } from "../../../db";import { inngest } from "../../client";--// Type for the Supabase client with our custom RPC functions-type SearchRpcClient = ReturnType<typeof getCarbonServiceRole> & {- rpc(- fn: "delete_from_search_index",- params: { p_company_id: string; p_entity_type: string; p_entity_id: string }- ): Promise<any>;- rpc(- fn: "upsert_to_search_index",- params: {- p_company_id: string;- p_entity_type: string;- p_entity_id: string;- p_title: string;- p_description: string;- p_link: string;- p_tags: string[];- p_metadata: Record<string, any>;- }- ): Promise<any>;-};--// Configuration for each entity type's search indexing-type SearchEntityConfig = {- entityType: string;- getTitle: (record: Record<string, any>) => string;- getDescription?: (record: Record<string, any>) => string;- getLink: (record: Record<string, any>) => string;- getTags: (record: Record<string, any>) => string[];- getMetadata: (record: Record<string, any>) => Record<string, any>;- enrichRecord?: (- record: Record<string, any>,- client: ReturnType<typeof getCarbonServiceRole>- ) => Promise<Record<string, any>>;-};--// Entity configurations matching the existing sync functions-const SEARCH_ENTITY_CONFIGS: Record<string, SearchEntityConfig> = {- employee: {- entityType: "employee",- getTitle: (r) => r.fullName || "",- getLink: (r) => `/x/person/${r.id}`,- getTags: (r) => [r.employeeTypeName].filter(Boolean),- getMetadata: (r) => ({ active: r.active }),- enrichRecord: async (record, client) => {- const { data: user } = await client- .from("user")- .select("fullName")- .eq("id", record.id)- .single();- const { data: empType } = await client- .from("employeeType")- .select("name")- .eq("id", record.employeeTypeId)- .single();- return {- ...record,- fullName: user?.fullName,- employeeTypeName: empType?.name- };- }- },- customer: {- entityType: "customer",- getTitle: (r) => r.name,- getLink: (r) => `/x/customer/${r.id}`,- getTags: (r) => [r.customerTypeName, r.customerStatusName].filter(Boolean),- getMetadata: (r) => ({ taxId: r.taxId }),- enrichRecord: async (record, client) => {- const { data: custType } = await client- .from("customerType")- .select("name")- .eq("id", record.customerTypeId)- .single();- const { data: custStatus } = await client- .from("customerStatus")- .select("name")- .eq("id", record.customerStatusId)- .single();- const { data: tax } = await (client as any)- .from("customerTax")- .select("taxId")- .eq("customerId", record.id)- .single();- return {- ...record,- customerTypeName: custType?.name,- customerStatusName: custStatus?.name,- taxId: tax?.taxId- };- }- },- supplier: {- entityType: "supplier",- getTitle: (r) => r.name,- getLink: (r) => `/x/supplier/${r.id}`,- getTags: (r) => [r.supplierTypeName, r.supplierStatus].filter(Boolean),- getMetadata: (r) => ({ taxId: r.taxId }),- enrichRecord: async (record, client) => {- const { data: suppType } = await client- .from("supplierType")- .select("name")- .eq("id", record.supplierTypeId)- .single();- const { data: tax } = await (client as any)- .from("supplierTax")- .select("taxId")- .eq("supplierId", record.id)- .single();- return {- ...record,- supplierTypeName: suppType?.name,- taxId: tax?.taxId- };- }- },- item: {- entityType: "item",- getTitle: (r) => r.readableId,- getDescription: (r) => `${r.name} ${r.description || ""}`,- getLink: (r) => {- const typeLinks: Record<string, string> = {- Part: "/x/part/",- Service: "/x/service/",- Tool: "/x/tool/",- Consumable: "/x/consumable/",- Material: "/x/material/",- Fixture: "/x/fixture/"- };- return (typeLinks[r.type] || "/x/part/") + r.id;- },- getTags: (r) => [r.type, r.replenishmentSystem].filter(Boolean),- getMetadata: (r) => ({ active: r.active })- },- job: {- entityType: "job",- getTitle: (r) => r.jobId,- getDescription: (r) => `${r.itemName || ""} ${r.customerName || ""}`,- getLink: (r) => `/x/job/${r.id}`,- getTags: (r) => [r.status, r.deadlineType].filter(Boolean),- getMetadata: (r) => ({ quantity: r.quantity, dueDate: r.dueDate }),- enrichRecord: async (record, client) => {- const { data: item } = await client- .from("item")- .select("name")- .eq("id", record.itemId)- .single();- const { data: customer } = await client- .from("customer")- .select("name")- .eq("id", record.customerId)- .single();- return {- ...record,- itemName: item?.name,- customerName: customer?.name- };- }- },- purchaseOrder: {- entityType: "purchaseOrder",- getTitle: (r) => r.purchaseOrderId,- getDescription: (r) => r.supplierName || "",- getLink: (r) => `/x/purchase-order/${r.id}`,- getTags: (r) => [r.status].filter(Boolean),- getMetadata: (r) => ({- orderDate: r.orderDate,- supplierReference: r.supplierReference- }),- enrichRecord: async (record, client) => {- const { data: supplier } = await client- .from("supplier")- .select("name")- .eq("id", record.supplierId)- .single();- return { ...record, supplierName: supplier?.name };- }- },- salesInvoice: {- entityType: "salesInvoice",- getTitle: (r) => r.invoiceId,- getDescription: (r) => r.customerName || "",- getLink: (r) => `/x/sales-invoice/${r.id}`,- getTags: (r) => [r.status].filter(Boolean),- getMetadata: (r) => ({ totalAmount: r.totalAmount, dateDue: r.dateDue }),- enrichRecord: async (record, client) => {- const { data: customer } = await client- .from("customer")- .select("name")- .eq("id", record.customerId)- .single();- return { ...record, customerName: customer?.name };- }- },- purchaseInvoice: {- entityType: "purchaseInvoice",- getTitle: (r) => r.invoiceId,- getDescription: (r) => r.supplierName || "",- getLink: (r) => `/x/purchase-invoice/${r.id}`,- getTags: (r) => [r.status].filter(Boolean),- getMetadata: (r) => ({ totalAmount: r.totalAmount, dateDue: r.dateDue }),- enrichRecord: async (record, client) => {- const { data: supplier } = await client- .from("supplier")- .select("name")- .eq("id", record.supplierId)- .single();- return { ...record, supplierName: supplier?.name };- }- },- nonConformance: {- entityType: "issue",- getTitle: (r) => r.nonConformanceId,- getDescription: (r) => `${r.name} ${r.description || ""}`,- getLink: (r) => `/x/issue/${r.id}`,- getTags: (r) => [r.status, r.priority, r.ncTypeName].filter(Boolean),- getMetadata: (r) => ({ source: r.source, dueDate: r.dueDate }),- enrichRecord: async (record, client) => {- const { data: ncType } = await client- .from("nonConformanceType")- .select("name")- .eq("id", record.nonConformanceTypeId)- .single();- return { ...record, ncTypeName: ncType?.name };- }- },- gauge: {- entityType: "gauge",- getTitle: (r) => r.gaugeId,- getDescription: (r) => `${r.description || ""} ${r.serialNumber || ""}`,- getLink: (r) => `/x/quality/gauges/${r.id}`,- getTags: (r) =>- [r.gaugeStatus, r.gaugeCalibrationStatus, r.gaugeTypeName].filter(- Boolean- ),- getMetadata: (r) => ({- nextCalibrationDate: r.nextCalibrationDate,- serialNumber: r.serialNumber- }),- enrichRecord: async (record, client) => {- const { data: gaugeType } = await client- .from("gaugeType")- .select("name")- .eq("id", record.gaugeTypeId)- .single();- return { ...record, gaugeTypeName: gaugeType?.name };- }- },- quote: {- entityType: "quote",- getTitle: (r) => r.quoteId,- getDescription: (r) =>- `${r.customerName || ""} ${r.customerReference || ""}`,- getLink: (r) => `/x/quote/${r.id}`,- getTags: (r) => [r.status].filter(Boolean),- getMetadata: (r) => ({- customerId: r.customerId,- expirationDate: r.expirationDate,- customerReference: r.customerReference- }),- enrichRecord: async (record, client) => {- const { data: customer } = await client- .from("customer")- .select("name")- .eq("id", record.customerId)- .single();- return { ...record, customerName: customer?.name };- }- },- salesRfq: {- entityType: "salesRfq",- getTitle: (r) => r.rfqId,- getDescription: (r) => r.customerName || "",- getLink: (r) => `/x/rfq/${r.id}`,- getTags: (r) => [r.status].filter(Boolean),- getMetadata: (r) => ({- customerId: r.customerId,- expirationDate: r.expirationDate- }),- enrichRecord: async (record, client) => {- const { data: customer } = await client- .from("customer")- .select("name")- .eq("id", record.customerId)- .single();- return { ...record, customerName: customer?.name };- }- },- salesOrder: {- entityType: "salesOrder",- getTitle: (r) => r.salesOrderId,- getDescription: (r) =>- `${r.customerName || ""} ${r.customerReference || ""}`,- getLink: (r) => `/x/sales-order/${r.id}`,- getTags: (r) => [r.status].filter(Boolean),- getMetadata: (r) => ({- customerId: r.customerId,- orderDate: r.orderDate,- customerReference: r.customerReference- }),- enrichRecord: async (record, client) => {- const { data: customer } = await client- .from("customer")- .select("name")- .eq("id", record.customerId)- .single();- return { ...record, customerName: customer?.name };- }- },- supplierQuote: {- entityType: "supplierQuote",- getTitle: (r) => r.supplierQuoteId,- getDescription: (r) => r.supplierName || "",- getLink: (r) => `/x/supplier-quote/${r.id}`,- getTags: (r) => [r.status].filter(Boolean),- getMetadata: (r) => ({- supplierId: r.supplierId,- expirationDate: r.expirationDate- }),- enrichRecord: async (record, client) => {- const { data: supplier } = await client- .from("supplier")- .select("name")- .eq("id", record.supplierId)- .single();- return { ...record, supplierName: supplier?.name };- }- }-};+import { planIndexWrites, planLookups, toIndexRow } from "./search-config";const SearchRecordSchema = z.object({event: z.object({@@ -368,12 +42,9 @@ export const searchFunction = inngest.createFunction(const results = {updated: 0,deleted: 0,- skipped: 0,- failed: 0+ skipped: 0};- const client = getCarbonServiceRole() as unknown as SearchRpcClient;-type SearchRecord = (typeof payload.records)[number];const byCompany = groupBy(payload.records, (r) => r.companyId);@@ -386,111 +57,87 @@ export const searchFunction = inngest.createFunction(continue;}- // Process each company's records as a stepconst companyResult = await step.run(`search-index-${companyId}`,async () => {- const stepResults = { updated: 0, deleted: 0, skipped: 0, failed: 0 };-- // Process deletions first- const deletes = records.filter(- (r) =>- r.event.operation === "DELETE" || r.event.operation === "TRUNCATE"+ const { deletes, upserts, skipped } = planIndexWrites(+ records.map((r) => r.event));- for (const del of deletes) {- const config = SEARCH_ENTITY_CONFIGS[del.event.table];- if (!config) {- stepResults.skipped++;- continue;- }-- try {- await client.rpc("delete_from_search_index", {- p_company_id: companyId,- p_entity_type: config.entityType,- p_entity_id: del.event.recordId- });- stepResults.deleted++;- } catch (error) {- logger.error("Failed to delete from search index", {- error,- record: del- });- stepResults.failed++;- }- }-- // Process inserts and updates- const upserts = records.filter(- (r) =>- r.event.operation === "INSERT" || r.event.operation === "UPDATE"+ // The lookup tables are picked from config at runtime, which the+ // typed client cannot express.+ const client = getCarbonServiceRole() as any;+ const resolved = new Map(+ await Promise.all(+ planLookups(upserts).map(async (lookup) => {+ let query = client+ .from(lookup.table)+ .select(`${lookup.matchOn}, ${lookup.column}`)+ .in(lookup.matchOn, lookup.ids);+ if (lookup.companyScoped) {+ query = query.eq("companyId", companyId);+ }+ const { data, error } = await query;++ if (error) {+ logger.error("Failed to read search index lookup", {+ companyId,+ table: lookup.table,+ error+ });+ throw new Error(+ `Search index lookup on "${lookup.table}" failed: ${error.message}`+ );+ }++ const values = new Map<string, unknown>(+ (data as Record<string, unknown>[]).map((row) => [+ String(row[lookup.matchOn]),+ row[lookup.column]+ ])+ );+ return [lookup.key, values] as const;+ })+ ));- for (const upsert of upserts) {- const config = SEARCH_ENTITY_CONFIGS[upsert.event.table];- if (!config) {- stepResults.skipped++;- continue;- }+ const rows = upserts.map((upsert) => toIndexRow(upsert, resolved));+ const pg = getJobDatabaseClient();- try {- let record = upsert.event.new as Record<string, any>;-- // Special handling for employee - skip inactive employees- if (- upsert.event.table === "employee" &&- record.active === false- ) {- await client.rpc("delete_from_search_index", {- p_company_id: companyId,- p_entity_type: config.entityType,- p_entity_id: upsert.event.recordId- });- stepResults.deleted++;- continue;- }-- // Enrich record with related data if needed- if (config.enrichRecord) {- record = await config.enrichRecord(record, client);- }-- const title = config.getTitle(record);- const description = config.getDescription?.(record) || "";- const link = config.getLink(record);- const tags = config.getTags(record);- const metadata = config.getMetadata(record);-- await client.rpc("upsert_to_search_index", {- p_company_id: companyId,- p_entity_type: config.entityType,- p_entity_id: upsert.event.recordId,- p_title: title,- p_description: description,- p_link: link,- p_tags: tags,- p_metadata: metadata- });+ try {+ if (deletes.length > 0) {+ await sql`+ SELECT delete_from_search_index(${companyId}, d.entity_type, d.entity_id)+ FROM jsonb_to_recordset(${JSON.stringify(deletes)}::jsonb)+ AS d(entity_type text, entity_id text)+ `.execute(pg);+ }- stepResults.updated++;- } catch (error) {- logger.error("Failed to update search index", {- error,- record: upsert- });- stepResults.failed++;+ if (rows.length > 0) {+ await sql`+ SELECT upsert_to_search_index(+ ${companyId}, r.entity_type, r.entity_id, r.title,+ r.description, r.link, r.tags, r.metadata+ )+ FROM jsonb_to_recordset(${JSON.stringify(rows)}::jsonb)+ AS r(+ entity_type text, entity_id text, title text,+ description text, link text, tags text[], metadata jsonb+ )+ `.execute(pg);}+ } catch (error) {+ logger.error("Failed to write search index", { companyId, error });+ throw error;}- return stepResults;+ return { updated: rows.length, deleted: deletes.length, skipped };});results.updated += companyResult.updated;results.deleted += companyResult.deleted;results.skipped += companyResult.skipped;- results.failed += companyResult.failed;}logger.info("Search function completed", results);diff --git a/packages/jobs/src/inngest/functions/scheduled/mrp-companies.test.ts b/packages/jobs/src/inngest/functions/scheduled/mrp-companies.test.tsindex 128635740e..90f068e222 100644--- a/packages/jobs/src/inngest/functions/scheduled/mrp-companies.test.ts+++ b/packages/jobs/src/inngest/functions/scheduled/mrp-companies.test.ts@@ -53,3 +53,27 @@ describe("selectCompaniesForMrp", () => {expect(result).toEqual([]);});});++describe("selectCompaniesForMrp with a planning-work lookup", () => {+ it("leaves out a company a run could change nothing for", () => {+ const result = selectCompaniesForMrp(+ companies,+ null,+ new Set(["c1", "c3"])+ );+ expect(result.map((c) => c.id)).toEqual(["c1", "c3"]);+ });++ it("plans for every company when the lookup failed", () => {+ expect(selectCompaniesForMrp(companies, null, null)).toEqual(companies);+ });++ it("still skips a cancelled company that has planning work", () => {+ const result = selectCompaniesForMrp(+ companies,+ [{ id: "c1", stripeSubscriptionStatus: "Canceled" }],+ new Set(["c1", "c2"])+ );+ expect(result.map((c) => c.id)).toEqual(["c2"]);+ });+});diff --git a/packages/jobs/src/inngest/functions/scheduled/mrp-companies.ts b/packages/jobs/src/inngest/functions/scheduled/mrp-companies.tsindex ed36cc9dbc..924a61548d 100644--- a/packages/jobs/src/inngest/functions/scheduled/mrp-companies.ts+++ b/packages/jobs/src/inngest/functions/scheduled/mrp-companies.ts@@ -2,6 +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 { filterEmpty } from "@carbon/utils";+import type { JobDatabase } from "../../../db";+/*** Which companies a scheduled MRP run should plan for. A company with no* `companyPlan` row still runs — MRP is not a paid feature.@@ -12,8 +15,14 @@*/export function selectCompaniesForMrp<T extends { id: string }>(companies: T[],- plans: { id: string; stripeSubscriptionStatus: string | null }[] | null+ plans: { id: string; stripeSubscriptionStatus: string | null }[] | null,+ withPlanningWork: ReadonlySet<string> | null = null): T[] {+ // null = the lookup failed, which means plan for everyone, for the same+ // reason as `plans`.+ if (withPlanningWork) {+ companies = companies.filter((company) => withPlanningWork.has(company.id));+ }if (!plans) return companies;// Only "Canceled" — the status the weekly job deletes on. "Inactive" (e.g.@@ -26,3 +35,47 @@ export function selectCompaniesForMrp<T extends { id: string }>(return companies.filter((company) => !cancelled.has(company.id));}++/**+ * The companies a run can change anything for: open demand or supply to plan,+ * or rows an earlier run wrote that a new one would clear. For every other+ * company `runMrp` reads its inputs, finds nothing and rewrites nothing, which+ * was 93% of scheduled runs and the largest share of server time (2026-10-01+ * traces). Each source is a superset of what `runMrp` reads (projections and+ * actuals are not narrowed to the planning horizon), so a company is only left+ * out when a run would be a no-op.+ */+export async function companiesWithPlanningWork(+ db: JobDatabase+): Promise<Set<string>> {+ const rows = await db+ .selectFrom("openSalesOrderLines")+ .select("companyId")+ .union(db.selectFrom("openJobMaterialLines").select("companyId"))+ .union(db.selectFrom("openProductionOrders").select("companyId"))+ .union(db.selectFrom("openPurchaseOrderLines").select("companyId"))+ .union(db.selectFrom("demandProjection").select("companyId"))+ .union(db.selectFrom("demandForecastSource").select("companyId"))+ .union(db.selectFrom("supplyForecast").select("companyId"))+ .union(+ db+ .selectFrom("demandForecast")+ .select("companyId")+ .where("forecastMethod", "=", "mrp")+ )+ .union(+ db+ .selectFrom("demandActual")+ .select("companyId")+ .where("actualQuantity", "!=", 0)+ )+ .union(+ db+ .selectFrom("supplyActual")+ .select("companyId")+ .where("actualQuantity", "!=", 0)+ )+ .execute();++ return new Set(filterEmpty(rows.map((row) => row.companyId)));+}diff --git a/packages/jobs/src/inngest/functions/scheduled/mrp.ts b/packages/jobs/src/inngest/functions/scheduled/mrp.tsindex ed28bf24d2..a92babb922 100644--- a/packages/jobs/src/inngest/functions/scheduled/mrp.ts+++ b/packages/jobs/src/inngest/functions/scheduled/mrp.ts@@ -8,7 +8,10 @@ import { runMrp } from "@carbon/planning";import { Edition } from "@carbon/utils";import { getJobDatabaseClient } from "../../../db";import { inngest } from "../../client";-import { selectCompaniesForMrp } from "./mrp-companies";+import {+ companiesWithPlanningWork,+ selectCompaniesForMrp+} from "./mrp-companies";export const mrpFunction = inngest.createFunction({ id: "mrp", retries: 2 },@@ -64,7 +67,23 @@ export const mrpFunction = inngest.createFunction(}}- const scheduled = selectCompaniesForMrp(companies.data, plans);+ // Deliberately not a throw: a failed lookup plans for everyone.+ const withPlanningWork = await companiesWithPlanningWork(+ getJobDatabaseClient()+ ).catch((error) => {+ logger.error("Failed to find companies with planning work", { error });+ return null;+ });++ const scheduled = selectCompaniesForMrp(+ companies.data,+ plans,+ withPlanningWork+ );+ logger.info("Companies scheduled for MRP", {+ companies: companies.data.length,+ scheduled: scheduled.length+ });if (scheduled.length === 0) {logger.warn("No companies to run MRP for", {diff --git a/packages/jobs/src/inngest/functions/scheduled/notification-digest.test.ts b/packages/jobs/src/inngest/functions/scheduled/notification-digest.test.tsnew file mode 100644index 0000000000..dfa1f30e94--- /dev/null+++ b/packages/jobs/src/inngest/functions/scheduled/notification-digest.test.ts@@ -0,0 +1,51 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it, vi } from "vitest";++vi.mock("@carbon/auth/client.server", () => ({+ getCarbonServiceRole: vi.fn()+}));+vi.mock("../../../db", () => ({ getJobDatabaseClient: vi.fn() }));+vi.mock("../../client", () => ({+ inngest: { createFunction: vi.fn(() => ({})) }+}));++import { NotificationTopic } from "@carbon/notifications";+import { staleDigests } from "./notification-digest";++const keeper = (id: string, count: number | null) => ({+ id,+ topic: NotificationTopic.Job,+ count+});++describe("staleDigests", () => {+ it("leaves a digest alone when its count has not moved", () => {+ expect(staleDigests([keeper("d1", 7)], new Map([["d1", 7]]))).toEqual([]);+ });++ it("refreshes a digest that absorbed new children", () => {+ expect(+ staleDigests([keeper("d1", 7)], new Map([["d1", 9]])).map((d) => [+ d.id,+ d.total+ ])+ ).toEqual([["d1", 9]]);+ });++ it("refreshes a digest whose children were purged, down to zero", () => {+ expect(+ staleDigests([keeper("d1", 7)], new Map()).map((d) => d.total)+ ).toEqual([0]);+ });++ it("refreshes a digest whose stored count cannot be read", () => {+ expect(+ staleDigests([keeper("d1", null)], new Map([["d1", 3]])).map(+ (d) => d.total+ )+ ).toEqual([3]);+ });+});diff --git a/packages/jobs/src/inngest/functions/scheduled/notification-digest.ts b/packages/jobs/src/inngest/functions/scheduled/notification-digest.tsindex 875accdf1c..35f93504e9 100644--- a/packages/jobs/src/inngest/functions/scheduled/notification-digest.ts+++ b/packages/jobs/src/inngest/functions/scheduled/notification-digest.ts@@ -8,6 +8,7 @@ import {NotificationEvent,type NotificationTopic} from "@carbon/notifications";+import { getJobDatabaseClient } from "../../../db";import { inngest } from "../../client";// Roll up unread, undigested notifications older than DIGEST_MIN_AGE_MIN that@@ -33,7 +34,29 @@ type Candidate = {createdAt: string;};-type ExistingDigest = Candidate;+type ExistingDigest = Candidate & { payload: unknown };++type Keeper = { id: string; topic: NotificationTopic; count: number | null };++/**+ * The digests whose title no longer says how many notifications they hold.+ * Rewriting the rest changed nothing, and was one count and one write per+ * unread digest every fifteen minutes.+ */+export function staleDigests(+ keepers: Keeper[],+ children: ReadonlyMap<string, number>+) {+ return keepers.flatMap((keeper) => {+ const total = children.get(keeper.id) ?? 0;+ return total === keeper.count ? [] : [{ ...keeper, total }];+ });+}++function digestCount(payload: unknown): number | null {+ const count = (payload as { count?: unknown } | null)?.count;+ return typeof count === "number" ? count : null;+}function bucketKey(userId: string, companyId: string, topic: string): string {return `${userId}::${companyId}::${topic}`;@@ -65,7 +88,7 @@ export const notificationDigestFunction = inngest.createFunction(.limit(DIGEST_MAX_CANDIDATES),client.from("notification")- .select("id, userId, companyId, topic, createdAt")+ .select("id, userId, companyId, topic, createdAt, payload").is("readAt", null).is("digestedInto", null).eq("event", NotificationEvent.Digest)@@ -125,6 +148,7 @@ export const notificationDigestFunction = inngest.createFunction(let created = 0;let merged = 0;let absorbed = 0;+ const keepers: Keeper[] = [];for (const group of work) {const newChildren = group.candidates;@@ -238,33 +262,60 @@ export const notificationDigestFunction = inngest.createFunction(absorbed += newChildren.length;}- // Refresh title/count from the authoritative child count.- const { count: childCount, error: countErr } = await client- .from("notification")- .select("id", { count: "exact", head: true })- .eq("digestedInto", keeper.id);-- if (countErr) {- logger.error("Failed to count digest children", { error: countErr });- continue;- }+ keepers.push({+ id: keeper.id,+ topic: keeper.topic,+ count: digestCount(keeper.payload)+ });+ }- const total = childCount ?? 0;- const description = getNotificationTopicPhrase(keeper.topic, total);- const { error: titleErr } = await client- .from("notification")- .update({- payload: {- count: total,- description,- event: NotificationEvent.Digest,- topic: keeper.topic- },- title: description- })- .eq("id", keeper.id);- if (titleErr) {- logger.error("Failed to refresh digest title", { error: titleErr });+ // Refresh title/count from the authoritative child count: one grouped+ // count for every digest, then a write only where the count moved.+ // A failed count skips the refresh rather than failing the step: a+ // retry would replay Case A and insert its digests a second time.+ const counted =+ keepers.length === 0+ ? []+ : await getJobDatabaseClient()+ .selectFrom("notification")+ .select((eb) => ["digestedInto", eb.fn.countAll().as("children")])+ .where(+ "digestedInto",+ "in",+ keepers.map((keeper) => keeper.id)+ )+ .groupBy("digestedInto")+ .execute()+ .catch((error) => {+ logger.error("Failed to count digest children", { error });+ return null;+ });++ if (counted) {+ const children = new Map(+ counted.map((row) => [row.digestedInto ?? "", Number(row.children)])+ );++ for (const keeper of staleDigests(keepers, children)) {+ const description = getNotificationTopicPhrase(+ keeper.topic,+ keeper.total+ );+ const { error: titleErr } = await client+ .from("notification")+ .update({+ payload: {+ count: keeper.total,+ description,+ event: NotificationEvent.Digest,+ topic: keeper.topic+ },+ title: description+ })+ .eq("id", keeper.id);+ if (titleErr) {+ logger.error("Failed to refresh digest title", { error: titleErr });+ }}}diff --git a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts b/packages/jobs/src/inngest/functions/tasks/model-optimize.tsindex 3407964e42..467019b132 100644--- a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts+++ b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts@@ -210,9 +210,7 @@ export const modelOptimizeFunction = inngest.createFunction(// it via the late-mint URL, so the job never holds the bytes) to surface// the reduction against the untouched source `size`.const dir = `${companyId}/models/${modelUploadId}`;- const listed = await storage(client)- .company(companyId)- .list(dir, { search: "optimized.glb" });+ const listed = await storage(client).company(companyId).list(dir);const optimized = listed.data?.find((o) => o.name === "optimized.glb");const optimizedSize = optimized?.metadata?.size ?? null;diff --git a/packages/logger/AGENTS.md b/packages/logger/AGENTS.mdindex ae3390b9a3..98ed49de65 100644--- a/packages/logger/AGENTS.md+++ b/packages/logger/AGENTS.md@@ -82,7 +82,7 @@ pnpm --filter @carbon/logger test| `./config.server` | `ensureLoggingConfigured()` (ANSI dev / JSONL+redacted prod, ALS) || `./config.client` | `ensureLoggingConfigured()` (plain console sink, no ALS) || `./middleware.server` | `requestIdMiddleware`, `requestIdContext`, `getRequestId`, `REQUEST_ID_HEADER`, plus the request-context API re-exported from `context.server`: `requestContextMiddleware`, `getRouterContext`, `getRequestContext`, `oncePerRequest`, `oncePerRead` |-| `./tracing.server` | `createTracing({ serviceName, afterRequest })` — React Router `instrumentations` (OpenTelemetry); `annotateRequestSpan(attributes)`; `queryLog` — Kysely `log` hook, `undefined` when tracing is off |+| `./tracing.server` | `createTracing({ serviceName, afterRequest })` — React Router `instrumentations` (OpenTelemetry); `annotateRequestSpan(attributes)`; `nameRequestSpan(name)`; `namedMiddleware(list)`; `withSpan(name, attributes, run)`; `queryLog` — Kysely `log` hook, `undefined` when tracing is off || `./inngest` | `createInngestLogger()` — adapter passed to `new Inngest({ logger })` |## Wiring (per app)@@ -91,7 +91,7 @@ pnpm --filter @carbon/logger test- `entry.client.tsx`: same from `@carbon/logger/config.client`.- `entry.server.tsx` also exports`instrumentations = createTracing({ serviceName: "carbon-erp", afterRequest })`.-- `root.tsx`: `export const middleware = [requestContextMiddleware, requestIdMiddleware, flashMiddleware]`+- `root.tsx`: `export const middleware = namedMiddleware([requestContextMiddleware, requestIdMiddleware, securityMiddleware, flashMiddleware])`(request context FIRST so every downstream middleware and handler runs insidethe AsyncLocalStorage scope, then request id so downstream logs carry it).@@ -126,12 +126,31 @@ One trace per request:`http.response.status_code` and `carbon.request_id` (the id on every log lineof that request). React Router 7.18's request instrumentation reports neitherthe status nor the pattern, which is why they arrive from those two places.-- **`middleware|loader|action <routeId>`** spans, one per route handler.+ A route that serves many things on one path renames it with+ `nameRequestSpan`: `POST /api/inngest carbon-event-queue`,+ `POST /api/mcp call_tool sales_getCustomers`, `POST /api/v1/sales/getCustomers`.+ Only known function ids and operations go into the name; the same values are+ on `inngest.function.id` / `carbon.operation` for grouping.+- **`middleware|loader|action <routeId>`** spans, one per route handler. React+ Router reports a middleware by its route alone, so the apps wrap the root list+ in `namedMiddleware([...])`, which renames each span after its function+ (`middleware requestIdMiddleware`). Each one contains everything after it.- **Fetch spans** from `@opentelemetry/instrumentation-undici`, only for fetches- made inside a request (`requireParentforSpans`). A PostgREST call is named by- its table or function (`GET /rest/v1/methodMaterial`); anything else by host,- because other paths carry ids. `url.full` and `url.query` get the access log's- `redactSearch` masking.+ made inside a request (`requireParentforSpans`). `fetchSpanName` names a+ Supabase call by what it does — `GET /rest/v1/methodMaterial`,+ `storage download`, `auth GET user`, `function get-method` — and anything else+ by host. Names never carry ids, bucket names or file paths; those are on+ `url.path`. `url.full` and `url.query` get the access log's `redactSearch`+ masking.++- **Operation spans**, from `withSpan`. Every Carbon API operation runs through+ its oRPC procedure (`api+/v1+/lib/router.server.ts`), whose outermost+ middleware opens `operation sales_getCustomers` — so the HTTP API, MCP+ `call_tool`, the agent and workflows are all named in one place. The MCP+ server (`@carbon/ee/mcp.server`) wraps `registerTool` to open+ `mcp call_tool sales_getCustomers` / `mcp search_tools` around each tool call.+ Both also set `carbon.operation` (and `carbon.mcp.tool`) on the request span,+ so a request can be grouped by what it ran without joining spans.- **Query spans** for Kysely, from `queryLog` passed as Kysely's `log` hook atthe three places a client is built (`apps/{erp,mes}/app/services/database.server.ts`,diff --git a/packages/logger/src/context.server.ts b/packages/logger/src/context.server.tsindex d8be09e271..a3bd4452ef 100644--- a/packages/logger/src/context.server.ts+++ b/packages/logger/src/context.server.ts@@ -72,6 +72,17 @@ export function getRequestContext<T>(context: RouterContext<T>): T | undefined {return storage.getStore()?.get(context);}+export const requestDetailContext = createContext<string | null>(null);++/**+ * What a route that serves many things on one path ran for this request:+ * the Inngest function behind `/api/inngest`, the tool behind `/api/mcp`.+ * The access log prints it after the path. No-op outside a request.+ */+export function describeRequest(detail: string) {+ storage.getStore()?.set(requestDetailContext, detail);+}+/** Backing store for `oncePerRequest`, kept in the router context itself. */const memoContext = createContext<Map<string, unknown> | null>(null);diff --git a/packages/logger/src/http-formatter.ts b/packages/logger/src/http-formatter.tsindex 0bb86dd423..f8c95b6ff0 100644--- a/packages/logger/src/http-formatter.ts+++ b/packages/logger/src/http-formatter.ts@@ -60,7 +60,7 @@ const PID = typeof process !== "undefined" ? process.pid : 0;*/export const httpDevFormatter: TextFormatter = getAnsiColorFormatter({format({ message, record }) {- const { method, pathname, search, status, responseTime, body } =+ const { method, pathname, detail, search, status, responseTime, body } =record.properties;let line = message;@@ -76,7 +76,9 @@ export const httpDevFormatter: TextFormatter = getAnsiColorFormatter({? ` ${DIM}${Math.trunc(responseTime * 10) / 10} ms${RESET}`: "";const methodColor = METHOD_COLOR[method] ?? RESET;- line = `${BOLD}${methodColor}${method}${RESET} ${statusColor(status)}${status}${RESET} ${pathname}${query}${time}`;+ const served =+ typeof detail === "string" ? ` ${BOLD}${detail}${RESET}` : "";+ line = `${BOLD}${methodColor}${method}${RESET} ${statusColor(status)}${status}${RESET} ${pathname}${query}${served}${time}`;// The Morgan line only renders method/path/status/time, so a captured// request body (debug only, already redacted) would otherwise be dropped// — append it dimmed on its own line.diff --git a/packages/logger/src/middleware.server.ts b/packages/logger/src/middleware.server.tsindex 7ec9f5c5d1..ccbffabc9e 100644--- a/packages/logger/src/middleware.server.ts+++ b/packages/logger/src/middleware.server.ts@@ -9,7 +9,7 @@ import {type MiddlewareFunction,type RouterContextProvider} from "react-router";-import { getRequestContext } from "./context.server";+import { getRequestContext, requestDetailContext } from "./context.server";import { isSensitiveKey, REDACTED, redactSearch } from "./redaction";import { annotateRequestSpan } from "./tracing.server";@@ -20,6 +20,7 @@ import { annotateRequestSpan } from "./tracing.server";// package's `exports` and repoint the four importers (both apps' root.tsx,// auth's auth.server.ts and users.server.ts) at it, then drop this re-export.export {+ describeRequest,getRequestContext,getRouterContext,oncePerRead,@@ -168,14 +169,21 @@ export const requestIdMiddleware: MiddlewareFunction<Response> = async (// Rendered as a Morgan "dev"-style colored line in dev (see// http-formatter.ts) and as a structured JSONL record in prod. When a// request body was captured, it rides on the same record (`body`).- log.debug("{method} {pathname} → {status} in {responseTime}ms", {- method,- pathname,- search: redactSearch(search),- status: res.status,- responseTime: performance.now() - start,- ...(body === undefined ? {} : { body })- });+ const detail = context.get(requestDetailContext);+ log.debug(+ detail+ ? "{method} {pathname} {detail} → {status} in {responseTime}ms"+ : "{method} {pathname} → {status} in {responseTime}ms",+ {+ method,+ pathname,+ ...(detail ? { detail } : {}),+ search: redactSearch(search),+ status: res.status,+ responseTime: performance.now() - start,+ ...(body === undefined ? {} : { body })+ }+ );return res;});diff --git a/packages/logger/src/middleware.test.ts b/packages/logger/src/middleware.test.tsindex 6104516985..b1381c7c69 100644--- a/packages/logger/src/middleware.test.ts+++ b/packages/logger/src/middleware.test.ts@@ -8,8 +8,10 @@ import { createLogRecorder } from "@logtape/testing";import { afterEach, beforeEach, describe, expect, it } from "vitest";import { getLogger } from "./logger";import {+ describeRequest,getRequestId,REQUEST_ID_HEADER,+ requestContextMiddleware,requestIdContext,requestIdMiddleware} from "./middleware.server";@@ -230,3 +232,55 @@ describe("requestIdMiddleware body logging", () => {expect(httpRecord()?.properties.search).toBe("");});});++describe("describeRequest", () => {+ it("puts what a shared route served into the access log line", async () => {+ const request = new Request(+ "http://x/api/inngest?fnId=carbon-event-queue",+ {+ method: "POST"+ }+ );+ const context = makeContext();+ const args = { request, context } as never;++ await requestContextMiddleware(+ args,+ async () =>+ (await requestIdMiddleware(args, async () => {+ describeRequest("carbon-event-queue");+ return new Response("ok");+ })) as Response+ );++ const access = recorder.records.find(+ (record) => record.properties.pathname === "/api/inngest"+ );+ expect(access?.properties.detail).toBe("carbon-event-queue");+ expect(access?.message.join("")).toContain(+ "POST /api/inngest carbon-event-queue"+ );+ });++ it("leaves the line alone for a request that says nothing", async () => {+ const context = makeContext();+ const args = {+ request: new Request("http://x/dashboard"),+ context+ } as never;++ await requestContextMiddleware(+ args,+ async () =>+ (await requestIdMiddleware(+ args,+ async () => new Response("ok")+ )) as Response+ );++ const access = recorder.records.find(+ (record) => record.properties.pathname === "/dashboard"+ );+ expect(access?.properties).not.toHaveProperty("detail");+ });+});diff --git a/packages/logger/src/tracing.middleware.test.ts b/packages/logger/src/tracing.middleware.test.tsnew file mode 100644index 0000000000..de3eafd1df--- /dev/null+++ b/packages/logger/src/tracing.middleware.test.ts@@ -0,0 +1,101 @@+// 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 {+ InMemorySpanExporter,+ NodeTracerProvider,+ SimpleSpanProcessor+} from "@opentelemetry/sdk-trace-node";+import { beforeEach, expect, it, vi } from "vitest";++// Tracing is decided when the module loads, and the global provider registers once.+vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4318");+const exporter = new InMemorySpanExporter();+const provider = new NodeTracerProvider({+ spanProcessors: [new SimpleSpanProcessor(exporter)]+});+provider.register();++beforeEach(() => exporter.reset());++it("names each middleware span after its function", async () => {+ const { namedMiddleware, routerInstrumentation } = await import(+ "./tracing.server"+ );++ type Handler = () => Promise<{ error?: Error }>;+ let wrap: (call: Handler, info: never) => Promise<void> = async () =>+ undefined;+ routerInstrumentation(provider.getTracer("test")).route?.({+ id: "root",+ instrument: (handlers: { middleware?: typeof wrap }) => {+ if (handlers.middleware) wrap = handlers.middleware;+ }+ } as never);++ const requestIdMiddleware = async () => undefined;+ const flashMiddleware = async () => undefined;+ for (const run of namedMiddleware([requestIdMiddleware, flashMiddleware])) {+ await wrap(+ async () => {+ await run();+ return {};+ },+ { request: { method: "GET" }, pattern: "x" } as never+ );+ }++ expect(exporter.getFinishedSpans().map((span) => span.name)).toEqual([+ "middleware requestIdMiddleware",+ "middleware flashMiddleware"+ ]);+});++it("wraps a call in a span and marks it failed when the call throws", async () => {+ const { withSpan } = await import("./tracing.server");++ const attributes = { "carbon.operation": "sales_getCustomers" };+ await expect(+ withSpan("operation sales_getCustomers", attributes, async () => 1)+ ).resolves.toBe(1);+ await expect(+ withSpan("operation sales_getCustomers", attributes, async () => {+ throw new Error("denied");+ })+ ).rejects.toThrow("denied");++ const [ok, failed] = exporter.getFinishedSpans();+ expect(ok?.name).toBe("operation sales_getCustomers");+ expect(ok?.attributes).toEqual(attributes);+ expect(failed?.status).toEqual({ code: 2, message: "denied" });+});++it("names the request span after what a shared route served", async () => {+ const { nameRequestSpan, routerInstrumentation } = await import(+ "./tracing.server"+ );++ type Handle = () => Promise<{ error?: Error }>;+ let wrap: (handle: Handle, info: never) => Promise<void> = async () =>+ undefined;+ routerInstrumentation(provider.getTracer("test")).handler?.({+ instrument: (handlers: { request?: typeof wrap }) => {+ if (handlers.request) wrap = handlers.request;+ }+ } as never);++ await wrap(+ async () => {+ nameRequestSpan("POST /api/inngest carbon-event-queue");+ return {};+ },+ {+ request: new Request("http://localhost/api/inngest", { method: "POST" })+ } as never+ );++ expect(exporter.getFinishedSpans().map((span) => span.name)).toEqual([+ "POST /api/inngest carbon-event-queue"+ ]);+});diff --git a/packages/logger/src/tracing.server.test.ts b/packages/logger/src/tracing.server.test.tsnew file mode 100644index 0000000000..be70262a6e--- /dev/null+++ b/packages/logger/src/tracing.server.test.ts@@ -0,0 +1,87 @@+// 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 { afterEach, describe, expect, it, vi } from "vitest";+import { fetchSpanName, redactedUrl } from "./tracing.server";++describe("redactedUrl", () => {+ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it("removes the Inngest event key from the path", () => {+ expect(redactedUrl("https://inn.gs", "/e/secret-event-key")).toEqual({+ "url.full": "https://inn.gs/e/[REDACTED]",+ "url.path": "/e/[REDACTED]",+ "url.query": ""+ });+ });++ it("removes the key behind a configured base URL with a path prefix", () => {+ vi.stubEnv("INNGEST_EVENT_API_BASE_URL", "https://events.example.com/x/");+ expect(+ redactedUrl("https://events.example.com", "/x/e/secret-event-key")+ ).toEqual({+ "url.full": "https://events.example.com/x/e/[REDACTED]",+ "url.path": "/x/e/[REDACTED]",+ "url.query": ""+ });+ });++ it("leaves other hosts' paths alone and still redacts the query", () => {+ expect(+ redactedUrl("https://api.example.com", "/e/thing?token=abc&page=2")+ ).toEqual({+ "url.full": "https://api.example.com/e/thing?token=%5BREDACTED%5D&page=2",+ "url.path": "/e/thing",+ "url.query": "?token=%5BREDACTED%5D&page=2"+ });+ });+});++describe("fetchSpanName", () => {+ const supabase = "https://api.example.com";++ it.each([+ ["GET", "/rest/v1/item?select=*", "GET /rest/v1/item"],+ [+ "POST",+ "/rest/v1/rpc/get_part_details",+ "POST /rest/v1/rpc/get_part_details"+ ],+ ["GET", "/storage/v1/object/co_123/parts/a.png", "storage download"],+ [+ "GET",+ "/storage/v1/object/authenticated/co_123/a.png",+ "storage download"+ ],+ ["POST", "/storage/v1/object/co_123/parts/a.png", "storage upload"],+ ["HEAD", "/storage/v1/object/co_123/a.png", "storage exists"],+ ["DELETE", "/storage/v1/object/co_123", "storage delete"],+ ["POST", "/storage/v1/object/list-v2/co_123", "storage list"],+ ["POST", "/storage/v1/object/sign/co_123/a.png", "storage sign"],+ ["POST", "/storage/v1/object/move", "storage move"],+ [+ "GET",+ "/storage/v1/render/image/authenticated/co_123/a.png",+ "storage transform"+ ],+ ["GET", "/auth/v1/user", "auth GET user"],+ ["POST", "/auth/v1/token?grant_type=refresh_token", "auth POST token"],+ [+ "PUT",+ "/auth/v1/admin/users/0b6e2c1a-1111-4222-8333-444455556666",+ "auth PUT admin/users"+ ],+ ["POST", "/functions/v1/get-method", "function get-method"]+ ])("%s %s is %s", (method, path, name) => {+ expect(fetchSpanName(method, supabase, path)).toBe(name);+ });++ it("names any other call by host", () => {+ expect(+ fetchSpanName("GET", "https://api.xero.com", "/api.xro/2.0/Invoices/abc")+ ).toBe("GET api.xero.com");+ });+});diff --git a/packages/logger/src/tracing.server.ts b/packages/logger/src/tracing.server.tsindex da7e3c2611..40d16f5bf5 100644--- a/packages/logger/src/tracing.server.ts+++ b/packages/logger/src/tracing.server.ts@@ -23,7 +23,8 @@ import {} from "@opentelemetry/resources";import {BatchSpanProcessor,- NodeTracerProvider+ NodeTracerProvider,+ type SpanProcessor} from "@opentelemetry/sdk-trace-node";import {ATTR_HTTP_REQUEST_METHOD,@@ -34,7 +35,7 @@ import {ATTR_URL_QUERY} from "@opentelemetry/semantic-conventions";import type { ServerInstrumentation } from "react-router";-import { redactSearch } from "./redaction";+import { REDACTED, redactSearch } from "./redaction";const REQUEST_SPAN = createContextKey("carbon.request-span");const PROVIDER = Symbol.for("carbon.tracing.provider");@@ -52,15 +53,18 @@ export type TracingOptions = {* each request with a flush to keep alive. Elsewhere the batch timer exports.*/afterRequest?: (flush: () => Promise<void>) => void;+ /** Extra processors beside the OTLP exporter, e.g. Inngest's. */+ spanProcessors?: SpanProcessor[];};export function createTracing({serviceName,- afterRequest+ afterRequest,+ spanProcessors = []}: TracingOptions): ServerInstrumentation[] {if (!enabled) return [];- const provider = ensureProvider(serviceName);+ const provider = ensureProvider(serviceName, spanProcessors);const flush = () => provider.forceFlush().catch(() => undefined);return [routerInstrumentation(@@ -71,7 +75,10 @@ export function createTracing({}// On `globalThis` because Vite re-evaluates this module in dev.-function ensureProvider(serviceName: string): NodeTracerProvider {+function ensureProvider(+ serviceName: string,+ spanProcessors: SpanProcessor[]+): NodeTracerProvider {const g = globalThis as Record<PropertyKey, unknown>;const existing = g[PROVIDER] as NodeTracerProvider | undefined;if (existing) return existing;@@ -81,7 +88,10 @@ function ensureProvider(serviceName: string): NodeTracerProvider {resource: defaultResource().merge(resourceFromAttributes({ [ATTR_SERVICE_NAME]: serviceName })).merge(detectResources({ detectors: [envDetector] })),- spanProcessors: [new BatchSpanProcessor(new OTLPTraceExporter())]+ spanProcessors: [+ new BatchSpanProcessor(new OTLPTraceExporter()),+ ...spanProcessors+ ]});provider.register();@@ -102,20 +112,106 @@ function ensureProvider(serviceName: string): NodeTracerProvider {return provider;}-/** PostgREST calls by table or function; anything else by host, since other paths carry ids. */+const STORAGE_OPERATIONS: [prefix: string, operation: string][] = [+ ["object/list", "list"],+ ["object/info", "info"],+ ["object/sign", "sign"],+ ["object/upload/sign", "sign upload"],+ ["object/copy", "copy"],+ ["object/move", "move"],+ ["render", "transform"],+ ["bucket", "bucket"]+];++const STORAGE_OBJECT_METHODS: Record<string, string> = {+ GET: "download",+ HEAD: "exists",+ DELETE: "delete"+};++function storageOperation(method: string, rest: string) {+ const named = STORAGE_OPERATIONS.find(([prefix]) => rest.startsWith(prefix));+ return named?.[1] ?? STORAGE_OBJECT_METHODS[method] ?? "upload";+}++/**+ * Supabase calls by what they do (`GET /rest/v1/item`, `storage download`,+ * `auth GET user`, `function get-method`); anything else by host. Names stay+ * free of ids, bucket names and file paths, which are on `url.path`.+ */export function fetchSpanName(method: string, origin: string, path: string) {const pathname = path.split("?")[0] ?? "";if (pathname.startsWith("/rest/v1/")) return `${method} ${pathname}`;++ const [, service, rest = ""] =+ pathname.match(/^\/(storage|auth|functions)\/v1\/(.*)$/) ?? [];+ if (service === "storage") {+ return `storage ${storageOperation(method, rest)}`;+ }+ if (service === "functions") return `function ${rest.split("/")[0]}`;+ if (service === "auth") {+ // Leading lowercase words only: `admin/users/<uuid>` is `admin/users`.+ const segments = rest.split("/");+ const end = segments.findIndex((segment) => !/^[a-z_]+$/.test(segment));+ const words = segments.slice(0, end === -1 ? 2 : Math.min(end, 2));+ return `auth ${method} ${words.join("/")}`;+ }+return `${method} ${origin.replace(/^https?:\/\//, "")}`;}-/** The instrumentation records the query string in both attributes. */+/**+ * React Router reports a middleware by its route alone, so four root+ * middleware are four spans named `middleware root`. Wrapping the list names+ * each span after its function.+ */+export function namedMiddleware<+ Middleware extends (...args: never[]) => unknown+>(middleware: Middleware[]): Middleware[] {+ if (!enabled) return middleware;+ return middleware.map(+ (run) =>+ ((...args) => {+ if (run.name)+ trace.getActiveSpan()?.updateName(`middleware ${run.name}`);+ return run(...args);+ }) as Middleware+ );+}++// Inngest's event API takes the event key as a path segment (`POST /e/<key>`),+// so the path is a secret there and must not reach the trace backend. A+// configured base URL may carry a path prefix (`/prefix/e/<key>`).+const INNGEST_EVENT_PATH = /\/e\/[^/]+/;++function originOf(url: string | undefined) {+ if (!url) return null;+ try {+ return new URL(url).origin;+ } catch {+ return null;+ }+}++function isInngestEventApi(origin: string) {+ const configured = [+ process.env.INNGEST_EVENT_API_BASE_URL,+ process.env.INNGEST_BASE_URL+ ].map(originOf);+ return origin === "https://inn.gs" || configured.includes(origin);+}++/** The instrumentation records the path and the query string unredacted. */export function redactedUrl(origin: string, path: string) {const queryStart = path.indexOf("?");- const pathname = queryStart === -1 ? path : path.slice(0, queryStart);+ const rawPathname = queryStart === -1 ? path : path.slice(0, queryStart);+ const pathname = isInngestEventApi(origin)+ ? rawPathname.replace(INNGEST_EVENT_PATH, `/e/${REDACTED}`)+ : rawPathname;const query = queryStart === -1 ? "" : redactSearch(path.slice(queryStart));return {[ATTR_URL_FULL]: `${origin}${pathname}${query}`,+ [ATTR_URL_PATH]: pathname,[ATTR_URL_QUERY]: query};}@@ -168,6 +264,17 @@ export function annotateRequestSpan(attributes: Attributes) {);}+/**+ * For a route that serves many things on one path (`/api/inngest`, `/api/mcp`):+ * say which one in the request span's name. Keep it to a bounded set of values.+ */+export function nameRequestSpan(name: string) {+ if (!enabled) return;+ (context.active().getValue(REQUEST_SPAN) as Span | undefined)?.updateName(+ name+ );+}+function end(span: Span, error: Error | undefined) {if (error) {span.recordException(error);@@ -176,6 +283,27 @@ function end(span: Span, error: Error | undefined) {span.end();}+/** Runs `run` in a child span of whatever is active; a plain call when tracing is off. */+export function withSpan<T>(+ name: string,+ attributes: Attributes,+ run: () => Promise<T>+): Promise<T> {+ if (!enabled) return run();+ return trace+ .getTracer("carbon")+ .startActiveSpan(name, { attributes }, async (span) => {+ try {+ const result = await run();+ span.end();+ return result;+ } catch (error) {+ end(span, error instanceof Error ? error : new Error(String(error)));+ throw error;+ }+ });+}+export function routerInstrumentation(tracer: Tracer,onRequestEnd?: () => voiddiff --git a/packages/planning/src/scheduling/scheduling-engine.test.ts b/packages/planning/src/scheduling/scheduling-engine.test.tsnew file mode 100644index 0000000000..4fba9e5772--- /dev/null+++ b/packages/planning/src/scheduling/scheduling-engine.test.ts@@ -0,0 +1,61 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import {+ DummyDriver,+ Kysely,+ PostgresAdapter,+ PostgresIntrospector,+ PostgresQueryCompiler+} from "kysely";+import { describe, expect, it } from "vitest";+import { isDistinctFromAny } from "./scheduling-engine.ts";++const db = new Kysely<any>({+ dialect: {+ createAdapter: () => new PostgresAdapter(),+ createDriver: () => new DummyDriver(),+ createIntrospector: (kysely) => new PostgresIntrospector(kysely),+ createQueryCompiler: () => new PostgresQueryCompiler()+ }+});++describe("isDistinctFromAny", () => {+ it("guards an update on the columns it would change, skipping undefined", () => {+ const query = db+ .updateTable("jobOperation")+ .set({ startDate: "2026-10-05" })+ .where("id", "=", "op_1")+ .where(+ isDistinctFromAny({+ startDate: "2026-10-05",+ priority: undefined,+ dueDate: null+ })+ )+ .compile();++ expect(query.sql).toBe(+ 'update "jobOperation" set "startDate" = $1 where "id" = $2 and ("startDate" is distinct from $3 or "dueDate" is distinct from $4)'+ );+ expect(query.parameters).toEqual([+ "2026-10-05",+ "op_1",+ "2026-10-05",+ null+ ]);+ });++ it("lets the write through when there is nothing to compare", () => {+ const query = db+ .updateTable("jobOperation")+ .set({ updatedBy: "u_1" })+ .where(isDistinctFromAny({ priority: undefined }))+ .compile();++ expect(query.sql).toBe(+ 'update "jobOperation" set "updatedBy" = $1 where true'+ );+ });+});diff --git a/packages/planning/src/scheduling/scheduling-engine.ts b/packages/planning/src/scheduling/scheduling-engine.tsindex f129296676..63e64fe592 100644--- a/packages/planning/src/scheduling/scheduling-engine.ts+++ b/packages/planning/src/scheduling/scheduling-engine.ts@@ -74,6 +74,21 @@ export { SCHEDULING_HORIZON_DAYS } from "./finite-context.ts";const log = getFunctionLogger("schedule");+/**+ * True when writing `values` would change the row. Compared in Postgres so a+ * stored DATE or timestamptz is matched in its own type, not as a JS string.+ * With nothing to compare it is true, so the write goes ahead.+ */+export function isDistinctFromAny(values: Record<string, unknown>) {+ const comparisons = Object.entries(values)+ .filter(([, value]) => value !== undefined)+ .map(+ ([column, value]) => sql`${sql.ref(column)} is distinct from ${value}`+ );+ if (comparisons.length === 0) return sql<boolean>`true`;+ return sql<boolean>`(${sql.join(comparisons, sql` or `)})`;+}+/*** Unified Scheduling Engine* Orchestrates all scheduling operations for both initial scheduling and rescheduling@@ -492,6 +507,7 @@ export class SchedulingEngine {.set({ status: "Ready" }).where("id", "=", opId).where("status", "not in", [+ "Ready","Done","Canceled","In Progress",@@ -918,27 +934,32 @@ export class SchedulingEngine {// dueDate is the backward need-by target and is DIFF-written: only// when the computed value differs from the stored one (a quiet regen// touches zero dueDate values), and never for a pinned op —- // manuallyScheduled means a human owns that target. The forward- // results (startDate day + projectedCompletionAt instant) are written- // for every op.+ // manuallyScheduled means a human owns that target.const needBy = this.needByByOperation.get(op.id) ?? null;const storedDueDate = toIsoDate(originalOp?.dueDate ?? null);const writeDueDate = !isManuallyScheduled && needBy !== storedDueDate;+ const placement = {+ startDate: op.startDate,+ projectedCompletionAt: op.projectedCompletionAt ?? null,+ ...(writeDueDate ? { dueDate: needBy } : {}),+ ...(op.priority != null ? { priority: op.priority } : {}),+ workCenterId,+ hasConflict: op.hasConflict,+ conflictReason: op.conflictReason+ };++ // Every UPDATE is queued for the audit/search handlers, so an op whose+ // placement is unchanged must not be written at all.await trx.updateTable("jobOperation").set({- startDate: op.startDate,- projectedCompletionAt: op.projectedCompletionAt ?? null,- ...(writeDueDate ? { dueDate: needBy } : {}),- priority: op.priority ?? undefined,- workCenterId,- hasConflict: op.hasConflict,- conflictReason: op.conflictReason,+ ...placement,updatedAt: datetime.timestamp(),updatedBy: this.userId}).where("id", "=", op.id)+ .where(isDistinctFromAny(placement)).execute();}@@ -995,6 +1016,13 @@ export class SchedulingEngine {}).where("id", "=", this.jobId).where("companyId", "=", this.companyId)+ .where(+ isDistinctFromAny({+ projectedCompletionAt: this.projectedCompletionAt,+ scheduleOutdatedReason: null,+ scheduleOutdatedAt: null+ })+ ).execute();});diff --git a/packages/printing/src/service.ts b/packages/printing/src/service.tsindex 61e96953fd..e7d2036d82 100644--- a/packages/printing/src/service.ts+++ b/packages/printing/src/service.ts@@ -154,7 +154,7 @@ export async function updatePrintJobStatus(status: PrintJobStatus,opts?: { error?: string }) {- const update: Record<string, unknown> = {+ const update: Database["public"]["Tables"]["printJob"]["Update"] = {status,updatedAt: new Date().toISOString()};diff --git a/packages/utils/src/object.ts b/packages/utils/src/object.tsindex 7469c3e0b6..207c69a249 100644--- a/packages/utils/src/object.ts+++ b/packages/utils/src/object.ts@@ -51,3 +51,11 @@ export const get = <T extends Record<string, any>, K extends keyof T>(const value = obj[key];return value === undefined ? defaultValue : value;};++/**+ * Passes a value TypeScript cannot check to a typed parameter: a patch or+ * filter whose column or table is only known at runtime. Never use it for a+ * typed payload that carries keys the table lacks — strip those instead, or+ * PostgREST rejects the write (PGRST204) and the compiler no longer warns.+ */+export const unchecked = (value: unknown) => value as never;diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 769e346031..8f1b2b8c23 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -133,17 +133,17 @@ catalogs:specifier: 7.10.0version: 7.10.0'@supabase/functions-js':- specifier: 2.1.5- version: 2.1.5+ specifier: 2.117.2+ version: 2.117.2'@supabase/postgrest-js':- specifier: 2.80.0- version: 2.80.0+ specifier: 2.117.2+ version: 2.117.2'@supabase/storage-js':- specifier: 2.80.0- version: 2.80.0+ specifier: 2.117.2+ version: 2.117.2'@supabase/supabase-js':- specifier: 2.80.0- version: 2.80.0+ specifier: 2.117.2+ version: 2.117.2'@tailwindcss/typography':specifier: 0.5.19version: 0.5.19@@ -541,10 +541,10 @@ importers:version: 7.18.0(@react-router/[email protected](patch_hash=10eab9c1af1b5cc376e67a81f64216bb5d6fcd8a94fc807eb46ecf1982b2cde4)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])'@supabase/functions-js':specifier: 'catalog:'- version: 2.1.5+ version: 2.117.2'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])'@tailwindcss/typography':specifier: 'catalog:'version: 0.5.19([email protected])@@ -806,16 +806,16 @@ importers:version: 13.3.0'@supabase/functions-js':specifier: 'catalog:'- version: 2.1.5+ version: 2.117.2'@supabase/postgrest-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2'@supabase/storage-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])'@tanstack/react-query':specifier: 5.97.0version: 5.97.0([email protected])@@ -1257,13 +1257,13 @@ importers:version: 13.3.0'@supabase/functions-js':specifier: 'catalog:'- version: 2.1.5+ version: 2.117.2'@supabase/storage-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])'@tailwindcss/typography':specifier: 'catalog:'version: 0.5.19([email protected])@@ -1501,10 +1501,10 @@ importers:version: 7.18.0(@react-router/[email protected](patch_hash=10eab9c1af1b5cc376e67a81f64216bb5d6fcd8a94fc807eb46ecf1982b2cde4)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])'@supabase/functions-js':specifier: 'catalog:'- version: 2.1.5+ version: 2.117.2'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])'@tailwindcss/typography':specifier: 'catalog:'version: 0.5.19([email protected])@@ -1616,7 +1616,7 @@ importers:dependencies:'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])dotenv:specifier: 16.3.1version: 16.3.1@@ -1653,10 +1653,10 @@ importers:version: 7.14.0(@react-router/[email protected](patch_hash=10eab9c1af1b5cc376e67a81f64216bb5d6fcd8a94fc807eb46ecf1982b2cde4)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])'@supabase/functions-js':specifier: 'catalog:'- version: 2.1.5+ version: 2.117.2'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])'@vercel/react-router':specifier: 'catalog:'version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=10eab9c1af1b5cc376e67a81f64216bb5d6fcd8a94fc807eb46ecf1982b2cde4)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])@@ -1732,10 +1732,10 @@ importers:version: 7.14.0(@react-router/[email protected](patch_hash=10eab9c1af1b5cc376e67a81f64216bb5d6fcd8a94fc807eb46ecf1982b2cde4)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected])'@supabase/functions-js':specifier: 'catalog:'- version: 2.1.5+ version: 2.117.2'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])'@vercel/react-router':specifier: 'catalog:'version: 1.2.6(patch_hash=fdc988df95f5639f888c552079014d0e615cb4c762f8c25a16d43e4498e21a6a)(@react-router/[email protected](patch_hash=10eab9c1af1b5cc376e67a81f64216bb5d6fcd8a94fc807eb46ecf1982b2cde4)(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))(@types/[email protected])([email protected])([email protected])([email protected])([email protected]([email protected]([email protected]))([email protected]))([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected]))(@react-router/[email protected]([email protected]([email protected]([email protected]))([email protected]))([email protected]))([email protected])([email protected]([email protected]))([email protected])@@ -1982,10 +1982,10 @@ importers:version: 13.3.0'@supabase/functions-js':specifier: 'catalog:'- version: 2.1.5+ version: 2.117.2'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])'@vercel/analytics':specifier: 'catalog:'version: 1.6.1([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])@@ -2143,7 +2143,7 @@ importers:version: 2.2.3(@logtape/[email protected])'@supabase/postgrest-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2cookie:specifier: 'catalog:'version: 1.1.1@@ -2183,7 +2183,7 @@ importers:version: link:../config'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])'@types/node':specifier: 20.19.39version: 20.19.39@@ -2452,7 +2452,7 @@ importers:version: 7.10.0'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])ai:specifier: 'catalog:'version: 7.0.116([email protected])@@ -2571,10 +2571,10 @@ importers:version: 1.5.0'@supabase/storage-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])libheif-js:specifier: 1.23.2version: 1.23.2@@ -2789,10 +2789,10 @@ importers:version: 7.10.0'@supabase/functions-js':specifier: 'catalog:'- version: 2.1.5+ version: 2.117.2'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])ai:specifier: 'catalog:'version: 7.0.116([email protected])@@ -2941,7 +2941,7 @@ importers:version: 7.10.0'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])inngest:specifier: 3.54.0version: 3.54.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected])([email protected])([email protected](@babel/[email protected])(@opentelemetry/[email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected])([email protected])@@ -3124,7 +3124,7 @@ importers:version: 5.9.4(@lingui/[email protected]([email protected])([email protected]))([email protected])([email protected])'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])react:specifier: 18.3.1version: 18.3.1@@ -3170,7 +3170,7 @@ importers:version: 3.12.0'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])kysely:specifier: 'catalog:'version: 0.28.17@@ -3226,7 +3226,7 @@ importers:version: link:../database'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])'@types/node':specifier: 20.19.39version: 20.19.39@@ -3379,7 +3379,7 @@ importers:version: 4.2.0'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])'@tailwindcss/typography':specifier: 'catalog:'version: 0.5.19([email protected])@@ -3596,7 +3596,7 @@ importers:version: link:../utils'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])stripe:specifier: 22.4.0version: 22.4.0(@types/[email protected])@@ -3790,7 +3790,7 @@ importers:version: 3.12.0'@supabase/supabase-js':specifier: 'catalog:'- version: 2.80.0+ version: 2.117.2(@opentelemetry/[email protected])'@tiptap/react':specifier: 'catalog:'version: 2.27.2(@tiptap/[email protected](@tiptap/[email protected]))(@tiptap/[email protected])([email protected]([email protected]))([email protected])@@ -9515,36 +9515,37 @@ packages:'@standard-schema/[email protected]':resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}- '@supabase/[email protected]':- resolution: {integrity: sha512-q2LyCVJGN4p7d92cOI7scWOoNwxJhZuFRwiimSUGJGI5zX7ubf1WUPznwOmYEn8WVo3Io+MyMinA7era6j5KPw==}- engines: {node: '>=20.0.0'}-- '@supabase/[email protected]':- resolution: {integrity: sha512-BNzC5XhCzzCaggJ8s53DP+WeHHGT/NfTsx2wUSSGKR2/ikLFQTBCDzMvGz/PxYMqRko/LwncQtKXGOYp1PkPaw==}+ '@supabase/[email protected]':+ resolution: {integrity: sha512-Z3WnGwrphYZubrLbxp5Iv0tLA9A5GhvKzJ/ZXglxqwd2QEH2R4dXRltjVJ8sIn4xEW2BSFIGT0yALVJIgZeDYw==}+ engines: {node: '>=22.0.0'}- '@supabase/[email protected]':- resolution: {integrity: sha512-0S/k8LRtoblrbzy4ir9m4WuvU/XTkb1EwL/33/oJexCUHCXtsqaPJ3eKfr1GWtNqTa1zryv6sXs3Fpv7lKCsMQ==}- engines: {node: '>=20.0.0'}+ '@supabase/[email protected]':+ resolution: {integrity: sha512-6DT4ZIjmZxa9ANKaBIrjc86AyKrX8M376ynvNeOBBVad3eP7x3UHqWfDR2ynFkHGzCuOpr1A+kObmnahxuwuog==}+ engines: {node: '>=22.0.0'}- '@supabase/[email protected]':- resolution: {integrity: sha512-1ibVeYUacxWYi9i0cf5efil6adJ9WRyZBLivgjs+AUpewx1F3xPi7gLgaASI2SmIQxPoCEjAsLAzKPgMJVgOUQ==}- engines: {node: 4.x || >=6.0.0}+ '@supabase/[email protected]':+ resolution: {integrity: sha512-aAn9H9ovVyeApKy11OWOrrOGq8DV68yWeH4ud2lN9fzn4aO8Zb5GLL9m1pUg9nLqIcT+ZDfAcsZe0E/nqdv2lw==}- '@supabase/[email protected]':- resolution: {integrity: sha512-yKzehXlRbDoXIQefdRQnvaI9BEogoWIp/7+y/m5enZDKW2IP9aAgq5tU72sThcwftDJvknnIpEHAABG3qviEng==}- engines: {node: '>=20.0.0'}+ '@supabase/[email protected]':+ resolution: {integrity: sha512-V1Qhn+M8xzJqCasOxHZ2KG19Fj39PxU7weEAmOK65/KTsWCRXboB4hcQwFvxRvM7ZikeP9IZWNvQkfjvSxzYFw==}+ engines: {node: '>=22.0.0'}- '@supabase/[email protected]':- resolution: {integrity: sha512-cXK6Gs4UDylN8oz40omi01QK0cSCBVj0efXC1WodpENTuDnrkUs28W8/eslEnAtlawaVtikC1Q92mpz9+o85Mg==}- engines: {node: '>=20.0.0'}+ '@supabase/[email protected]':+ resolution: {integrity: sha512-lYXSAIg3eAKA58riUED6Vb+TCzF8jtx18uOoiCaVJ7ZMre6FWBpwB1MPeW+B6vykJT/hPdiuqwcSB7ILMS21ew==}+ engines: {node: '>=22.0.0'}- '@supabase/[email protected]':- resolution: {integrity: sha512-Iepod83h2WoMCaLC9pGb3QOT67Kn3RlUdbXpo3uvbDKfPU8EgytS4RVaPmDjhqDjj8AGaiz9mk/ppd2Q2WS+gw==}- engines: {node: '>=20.0.0'}+ '@supabase/[email protected]':+ resolution: {integrity: sha512-8gAJoVaxZa/War2kFRfJMxGk4M190Q7lJ70BofwGlRxU/u9pIodd6XyTvmXkxOKXWuIYtkDaYPZrIAUt1T/7FQ==}+ engines: {node: '>=22.0.0'}- '@supabase/[email protected]':- resolution: {integrity: sha512-n8pkXQxuo5zCWXX5cbSNZj1vuWS8IVNGWTmP1m31Iq1k0e8lPZ07PF08TRV79HHq3mEPP/Ko//BQuflHvY2o8w==}- engines: {node: '>=20.0.0'}+ '@supabase/[email protected]':+ resolution: {integrity: sha512-eSG2VKnHR+Clp1PmidZ1/weJ8PJwoybjva3L2GgKqFG4YDS1Iqmc61psKGZP5xw6OMT2O7ZorPR42PY6q1BOXg==}+ engines: {node: '>=22.0.0'}+ peerDependencies:+ '@opentelemetry/api': '>=1.0.0'+ peerDependenciesMeta:+ '@opentelemetry/api':+ optional: true'@swc/[email protected]':resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==}@@ -10368,9 +10369,6 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-NoaMtzhxOrubeL/7UZuNTrejB4MPAJ0RpxZqXQf2qXuVlTPuG6Y8p4u9dKRaue4yjmC7ZhzVO2/Yyyn25znrPQ==}- '@types/[email protected]':- resolution: {integrity: sha512-oN9ive//QSBkf19rfDv45M7eZPi0eEXylht2OLEXicu5b4KoQ1OzXIw+xDSGWxSxe1JmepRR/ZH283vsu518/Q==}-'@types/[email protected]':resolution: {integrity: sha512-vqlvI7qlMvcCBbVe0AKAb4f97//Hy0EBTaiW8AalRnG/xAN5zOiWWyrNqNXeq8+KAuvRewjCVY1+IPxk4RdNYw==}@@ -12840,6 +12838,10 @@ packages:resolution: {integrity: sha512-kvL8xYl5QMTh+LwohVN72ciOxC0OEV79IPdJSTwEXok9y9QHebXGdFgrED4sWfiax/ODx++CAMk3hMy4XPJPOw==}+ resolution: {integrity: sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==}+ engines: {node: '>=20.0.0'}+resolution: {integrity: sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==}engines: {node: '>=0.10.0'}@@ -23722,50 +23724,39 @@ snapshots:'@standard-schema/[email protected]': {}- '@supabase/[email protected]':+ '@supabase/[email protected]':dependencies:tslib: 2.8.1- '@supabase/[email protected]':- dependencies:- '@supabase/node-fetch': 2.6.15-- '@supabase/[email protected]':+ '@supabase/[email protected]':dependencies:tslib: 2.8.1- '@supabase/[email protected]':- dependencies:- whatwg-url: 5.0.0+ '@supabase/[email protected]': {}- '@supabase/[email protected]':+ '@supabase/[email protected]':dependencies:tslib: 2.8.1- '@supabase/[email protected]':+ '@supabase/[email protected]':dependencies:- '@types/phoenix': 1.6.7- '@types/ws': 8.18.1+ '@supabase/phoenix': 0.4.5tslib: 2.8.1- ws: 8.21.0- transitivePeerDependencies:- - bufferutil- - utf-8-validate- '@supabase/[email protected]':+ '@supabase/[email protected]':dependencies:+ iceberg-js: 0.8.1tslib: 2.8.1- '@supabase/[email protected]':+ '@supabase/[email protected](@opentelemetry/[email protected])':dependencies:- '@supabase/auth-js': 2.80.0- '@supabase/functions-js': 2.80.0- '@supabase/postgrest-js': 2.80.0- '@supabase/realtime-js': 2.80.0- '@supabase/storage-js': 2.80.0- transitivePeerDependencies:- - bufferutil- - utf-8-validate+ '@supabase/auth-js': 2.117.2+ '@supabase/functions-js': 2.117.2+ '@supabase/postgrest-js': 2.117.2+ '@supabase/realtime-js': 2.117.2+ '@supabase/storage-js': 2.117.2+ optionalDependencies:+ '@opentelemetry/api': 1.9.0'@swc/[email protected]':dependencies:@@ -24615,8 +24606,6 @@ snapshots:pg-protocol: 1.13.0pg-types: 2.2.0- '@types/[email protected]': {}-'@types/[email protected]': {}'@types/[email protected]': {}@@ -27522,6 +27511,8 @@ snapshots:+ [email protected]: {}+dependencies:safer-buffer: 2.1.2diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 3f79d97e75..a5e082754e 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -96,10 +96,10 @@ catalog:'@shikijs/themes': 4.2.0'@shikijs/types': 4.2.0'@slack/web-api': 7.10.0- '@supabase/functions-js': 2.1.5- '@supabase/postgrest-js': 2.80.0- '@supabase/storage-js': 2.80.0- '@supabase/supabase-js': 2.80.0+ '@supabase/functions-js': 2.117.2+ '@supabase/postgrest-js': 2.117.2+ '@supabase/storage-js': 2.117.2+ '@supabase/supabase-js': 2.117.2'@tailwindcss/container-queries': 0.2.2'@tailwindcss/typography': 0.5.19'@tailwindcss/vite': 4.3.0