Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

Slow-request fixes: scheduler writes, schedule board, realtime reloads (#1850)

Sidc1ae854f80a3
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 4eaca55929..f3ad30e058 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -3025,3 +3025,25 @@ And a delete whose failure the caller ignores is not a delete: return the error.
**Rule:** A prefetch only helps if the browser may reuse its response. Give a prefetch response (`Sec-Purpose: prefetch`) a short `private` lifetime and leave every other response uncached; `prefetchCacheMiddleware` (`@carbon/utils`) does it in each app's root `middleware`, the fix React Router points to (remix-run/react-router#13255). Measure a prefetch by click-to-page time, not by whether the request was sent. A first fix removed the prefetch instead (`6e3bdf7bc6`); it worked but threw away the head start.
**Applies to:** `packages/react/src/PrefetchLink.tsx`; `packages/utils/src/prefetch.ts`; any `<Link prefetch>` or `PrefetchPageLinks`; a revalidation started while a navigation to the same URL is loading.
+
+
+## A revalidation during the navigation after a save loses the save
+
+**Context:** 186 layouts export `shouldRevalidate` and skip a GET navigation that leaves their params unchanged. Realtime calls `revalidate()` 300 ms after a broadcast.
+
+**Problem:** A save's own broadcast arrives while its redirect is still loading. `revalidate()` during a loading navigation restarts it with `overrideNavigation: state.navigation`, and for a fetcher submission that carries no `formMethod`. The restarted navigation looks like a plain one, so each layout returned `false` and kept its data from before the save: a new quote line was missing from the quote's explorer until a reload (2026-10-05). In single fetch `defaultShouldRevalidate` is `true` for every route on every navigation, so a predicate cannot tell a forced reload from a plain one. A first fix assumed React Router's default was `false` after a redirect with no cookie; logging the predicate's arguments in the browser showed the default was `true` and the first pass did include the layout.
+
+**Rule:** Never call React Router's `revalidate()` directly. Import `useRevalidator` from `@carbon/query`: it holds a call made while a navigation is in flight or a fetcher is submitting and runs it when the router is idle. The `no-raw-revalidator` check (`@carbon/checks`) fails an import of React Router's. Before explaining a skipped loader, log what `shouldRevalidate` received: wrap the route's `shouldRevalidate` on `window.__reactRouterDataRouter.routes` and read `formMethod`, `defaultShouldRevalidate` and both URLs for each call.
+
+**Applies to:** `packages/query/src/useRevalidator.ts`; every `revalidate()` call (realtime, polling timers, upload callbacks); every route that exports `shouldRevalidate`.
+
+
+## A drag re-rendered every card on the board
+
+**Context:** The schedule boards (operations, dates, batches) render one sortable card per operation or job, each with a form, avatars, tooltips and a menu.
+
+**Problem:** A drag stuttered: with 82 cards, six frames of a 90-frame sweep took over 100 ms. Two causes. dnd-kit re-renders every `useSortable` consumer when the drop target changes, and the hook sat inside the card, so every card's whole body rendered each time. And `useSensor(KeyboardSensor, { coordinateGetter })` passed a new options object on every render: dnd-kit memoizes the sensor on it, so every draggable got new `listeners`, which defeats `memo` on anything that takes them.
+
+**Rule:** A sortable card is a thin shell that calls `useSortable` and a `memo`ized body that takes plain props (`sortableCardProps` in `Schedule/Kanban/cardShell.ts`). `useSensor` options are a module constant (`no-inline-sensor-options` check). A context every card reads must have a stable value. To find what re-renders, count renders per component during a scripted drag; do not guess.
+
+**Applies to:** `apps/erp/app/modules/production/ui/Schedule/Kanban/**`; any dnd-kit board or list with more than a few dozen items.
diff --git a/.ai/plans/2026-10-06-slow-request-fixes.md b/.ai/plans/2026-10-06-slow-request-fixes.md
new file mode 100644
index 0000000000..52aad07c50
--- /dev/null
+++ b/.ai/plans/2026-10-06-slow-request-fixes.md
@@ -0,0 +1,120 @@
+# Slow request fixes: scheduler writes, maintenance dispatch, webhook timeout
+
+## Context
+
+Axiom traces for 2026-10-05 showed three avoidable costs. None is a slow query; each is too many sequential round trips.
+
+- **Reschedule (4.9 s of a 6.7 s job release, also operation delete).** `runLocationSchedule` re-plans every open job at the location. Each job costs about 17 statements in two transactions, so 28 jobs is about 500 statements. In prod 88% of jobs get new operation dates on every run, so skipping unchanged writes would not help. The fix is to compute every job in memory and write the location once.
+- **`carbon-dispatch` (40.7 s).** One `maintenanceSchedule` read per company. The company list is read without paging, so it stops at 1,000 of 1,284 companies: 284 companies never get preventive-maintenance dispatches. Only 31 companies have an active schedule.
+- **Webhook delivery.** `axios.post` to the customer URL has no timeout, so a hung endpoint holds the step until the platform kills it.
+
+Decisions already made with the user: keep the reschedule inline (no background wave); go the full depth (in-memory compute plus one write); a database error in that write fails the whole location run instead of one job. Inline PDFs are out of scope.
+
+Work on a new branch `perf/slow-request-fixes` off `main`, one commit per part. Copy this plan to `.ai/plans/2026-10-06-slow-request-fixes.md` first. No push without asking.
+
+---
+
+## Part 1: Maintenance dispatch (smallest, fixes a live bug)
+
+File: `packages/jobs/src/inngest/functions/scheduled/dispatch.ts`, the `dispatchFunction` body (lines 395-459).
+
+1. Replace the company loop with one paged read of every due schedule across companies: `fetchAllFromTable` (`@carbon/database`, same helper `scheduled/mrp.ts` uses) on `maintenanceSchedule`, `active = true` and `nextDueAt is null or <= now`.
+2. Read `companySettings (id, maintenanceDispatchNotificationGroup)` only for the companies that have a due schedule, with `.in("id", ids)` in chunks of 200.
+3. Loop the due schedules and call the existing `generateDispatchesForSchedule` unchanged (it stays one schedule at a time; that part is inherent and small).
+4. A failed read now throws so Inngest retries, instead of silently skipping a company.
+
+`generateMaintenanceForScheduleFunction` (on-demand, one schedule) is untouched.
+
+Expected: about 1,000 reads become 2-3; run time about 40 s to about 10 s; all 1,284 companies covered.
+
+## Part 2: Webhook timeout
+
+File: `packages/jobs/src/inngest/functions/events/webhook.ts:62`.
+
+- Add `timeout: 30_000` to the `axios.post` options.
+- 30 s, not 10 s: yesterday's handlers that took 8-14 s ended in `increment_webhook_success`, so a 10 s limit would turn deliveries that succeed today into failures and retries.
+- Add one line to `docs/content/docs/building/webhooks.mdx`: an endpoint that does not answer within 30 seconds counts as a failed attempt and is retried.
+
+## Part 3: Scheduler computes in memory, writes once
+
+All under `packages/planning/src/scheduling/`. `SchedulingEngine` is constructed only in `run-schedule.ts`, so the engine's write contract can change without touching callers.
+
+### 3a. Engine stops writing; it returns a write set
+
+`scheduling-engine.ts`, `material-manager.ts`.
+
+The engine has four write sites today. Each one records into a `JobWrites` value instead (`engine.getWrites()`):
+
+| Today | Becomes |
+|---|---|
+| `materialManager.assignOperationsToMaterials` (one UPDATE per material) and `assignMaterials` | `materialLinks: { materialId, jobOperationId }[]` |
+| `createDependencies` transaction (lock, delete, insert) | `dependencies: { reworkOpIds, records } \| null`, null when the computed edges equal the stored non-rework edges (already in memory from `initialize`) |
+| `createDependencies` Ready update | `readyOperationIds` |
+| `persistChanges` | `placements`, `reservations`, `job: { projectedCompletionAt }`, plus the existing newly-late calculation |
+
+Reads that used to follow the engine's own writes now apply the links in memory:
+- `assignMaterials`: unassigned Make to Order materials minus the ones already linked in this run.
+- `createDependencies`: `getMaterialsWithMakeMethod` rows with `jobOperationId` filled from the links.
+
+Side effect: the expedite what-if (`persist: false`) now sees the same material links a real run does. Today it skips them. This is the only intended behavior difference inside a run.
+
+### 3b. Provider serves earlier jobs' results from memory
+
+`master-data-provider.ts`. The provider already holds per-run state (`preload`, `companyCache`); add a run overlay next to it.
+
+- **Reservations.** `beginRun(batch)` loads live reservations once (no exclusions) and splits them: rows later jobs always see (non-batch jobs, batch-tagged rows) and each batch job's own old rows. `getLiveReservations` then answers from memory. After a job computes, its planned reservations replace its old rows, keeping today's visibility rules: not a placeholder, `endAt > now`, job status in `capacityHoldingJobStatuses`. A job that fails to compute keeps its old rows visible, as today.
+- **Cross-job operations** (`getCrossJobOperationsAtWorkCenters`). Cache the DB rows per work center id; keep a map of operations placed by already-run jobs (row built from the preloaded operation plus the new placement). Answer = cached rows not in that map, plus placed operations at the requested work centers.
+- **Materials.** With no mid-run writes, the preloaded rows are always the stored state: serve `getMaterialsWithMakeMethod` and `getUnassignedMakeToOrderMaterials` from the preload for preloaded jobs and delete the `materialsAreLinked` gate (add `methodType` to the `unlinked` preload select).
+- **Process requirements.** Cache per process id instead of per id-set.
+
+The overlay rules are pure functions (`visibleReservations`, `mergeCrossJobOperations`, `dependencyEdgesEqual`) so they are unit-tested without a database. Outside a location run (no `beginRun`) every method reads the database as today.
+
+### 3c. One transaction per location
+
+`run-schedule.ts`, new `persist-location.ts`.
+
+`runLocationSchedule`: batch pre-pass (unchanged, keeps its own transaction) → `preloadJobs` → `beginRun` → per job: `engine.run()`, `provider.recordJob(writes)` → `persistLocationWrites(db, writes[], { companyId, userId })`.
+
+`persistLocationWrites` is one transaction, every statement scoped by `companyId`:
+1. Material links: one `UPDATE jobMaterial ... FROM (VALUES ...)`.
+2. Dependencies, only for jobs whose edges changed: advisory lock, delete, insert (existing logic moved).
+3. Ready: one guarded `UPDATE jobOperation SET status = 'Ready'`.
+4. Placements: existing `updatePlacements`, one statement per column shape across all jobs.
+5. Reservations: one `DELETE ... WHERE jobId IN (...)` (same predicates), one bulk insert.
+6. Jobs: one `UPDATE job ... FROM (VALUES ...)` with the existing is-distinct guard.
+
+Bulk VALUES and inserts are chunked at 1,000 rows (Postgres caps a statement at 65,535 parameters).
+
+Failure handling: a job that throws while computing is logged, counted in `jobsFailed`, left out of the write, and stays stamped stale, as today. A database error in the write rolls back the location and `runLocationSchedule` throws. All five callers already catch (`$jobId.status.tsx`, `recalculateJobOperationDependencies`, `api+/schedule.ts`, `api+/kanban.$id.tsx`, the replan wave, `tasks/recalculate.ts`).
+
+`runExpediteWhatIf` uses the same engine and never calls the persist function.
+
+Expected: about 500 statements to about 60; reschedule from 4.9 s to under 1 s. This is an estimate until measured in the check below.
+
+### 3d. Docs
+
+Update `.claude/rules/scheduling-data-structures.md` (sections "Whole-location, deterministic run" and "`persistChanges`") to describe in-memory claiming and the single location transaction, and the comment on `companyCache` in the provider that says reservations are never cached.
+
+---
+
+## Verification
+
+Run typechecks one package at a time (`--concurrency=1`).
+
+**Part 1**
+- `pnpm exec turbo run typecheck --filter=@carbon/jobs --concurrency=1`
+- Against the running local stack (do not restart it): set one seeded schedule's `nextDueAt` to yesterday, invoke `dispatch` from the Inngest dev UI, confirm one dispatch is created, `nextDueAt` advances, and a second invoke creates nothing.
+
+**Part 2**
+- `pnpm --filter @carbon/jobs test` (`webhook.test.ts` pins the body contract).
+- `pnpm --filter docs typecheck`.
+
+**Part 3**
+- `pnpm --filter @carbon/planning test`: existing determinism, envelope, batch-scheduler and selector suites, plus new tests for the three pure overlay functions.
+- **Old-versus-new parity with a fixed clock.** Use the two-stack parity setup at `~/Documents/crbnos/carbon-parity` (main and branch on the same seed; confirm it still runs before relying on it). A temporary script mocks `Date.now`, runs `runLocationSchedule` for every location of the seeded company on each stack, and dumps `jobOperation` placement columns, `capacityReservation` (without id and createdAt), `jobOperationDependency`, `jobMaterial.jobOperationId` and `job.projectedCompletionAt`. The two dumps must be identical. Run it twice: once on a fresh seed (everything gets written) and once again (steady state). Delete the script before committing.
+- **Statement count.** The same script builds its Kysely client with a `log` callback and prints the number of statements per location run, before and after.
+- `pnpm exec turbo run typecheck --filter=@carbon/planning --concurrency=1`, then `--filter=@carbon/jobs`, then `--filter=erp`.
+- `pnpm run lint`.
+- Browser check with `/auth`: release a seeded job with "schedule", confirm dates appear on its operations and the Forecast shows it; delete an operation and confirm the job reschedules.
+
+After deploy, recheck in Axiom: `POST /x/job/:jobId/status` p95 and the SQL statement count on its traces, and the `carbon-dispatch` run time and `maintenanceSchedule` call count.
diff --git a/.claude/rules/realtime-system.md b/.claude/rules/realtime-system.md
index f3855d1f26..0fe756cbbe 100644
--- a/.claude/rules/realtime-system.md
+++ b/.claude/rules/realtime-system.md
@@ -96,8 +96,12 @@ export const handle: Handle = {
the matched routes and, 300 ms after the last message, invalidates the cached
loader entries and revalidates the page. A burst is one reload; a route and a
component following the same table reload once; a reload waits while a fetcher
-is submitting (React Router drops a fetcher's redirect when a revalidation
-starts during its action) and runs when it finishes.
+is submitting or a navigation is in flight, and runs when both are done
+(`useRevalidator` from `@carbon/query`, the only one app code may import). During
+an action React Router drops the fetcher's redirect; during the navigation that
+follows a save, a revalidation restarts it WITHOUT the submission, and every
+layout whose `shouldRevalidate` skips a plain navigation then keeps its data
+from before the save. The save's own broadcast arrives in exactly that window.
- Update the list when the loader starts reading a new table. Nothing checks
that a list is COMPLETE, only that each name can broadcast.
diff --git a/.claude/rules/scheduling-data-structures.md b/.claude/rules/scheduling-data-structures.md
index adc3ec8253..7ebfc0d90a 100644
--- a/.claude/rules/scheduling-data-structures.md
+++ b/.claude/rules/scheduling-data-structures.md
@@ -248,8 +248,8 @@ is a separate per-job backward re-plan, not a whole-location regen.
## Engine pipeline (`scheduling-engine.ts` `run()`)
`initialize → assignMaterials → createDependencies → calculateDates →
-computeNeedBys → selectWorkCenters → calculatePriorities → persistChanges` (the last
-is skipped when `persist: false`, i.e. the expedite what-if). **There is no backward
+computeNeedBys → selectWorkCenters → calculatePriorities → buildWrites` (the engine
+writes nothing; the location run stores the result, the expedite what-if drops it). **There is no backward
JIT pass in PLACEMENT and no `initial`/`reschedule` mode split** — everything places
FORWARD-ASAP, and the projected finish IS the overdue forecast (slack is real). The
backward need-by pass (`computeNeedBys`, below) computes demand-anchored TARGETS
@@ -263,8 +263,18 @@ only; its output is read by nothing in the placement path (spec
`dueDate ASC NULLS LAST → job.priority ASC → createdAt ASC` — so a no-due-date ASAP
order claims capacity first. Each job's engine run **excludes the jobs not yet run
(itself + later)** from the reservation snapshot, so it sees non-batch reservations
- plus the just-persisted placements of already-run jobs → sequential capacity
- claiming, no pre-clear step.
+ plus the placements of already-run jobs → sequential capacity
+ claiming, no pre-clear step. **Nothing is written while the jobs run.** The
+ engine only computes: `engine.getWrites()` returns a `JobWrites`
+ (`run-overlay.ts`), `provider.recordJob(writes)` makes that job's reservations
+ and operation placements visible to the jobs after it (`beginRun` reads the
+ live reservations once; the rules are the pure `visibleReservations` /
+ `mergeCrossJobOperations`), and `persistLocationWrites`
+ (`persist-location.ts`) stores the whole location in ONE transaction at the
+ end. A job that throws while computing is left out of the write and keeps its
+ stored reservations visible to later jobs; a database error in the write
+ rolls the location back and `runLocationSchedule` throws. This replaced a
+ write per job (about 17 statements each, 500 for a 28-job location).
- **Sequencing** (`dependency-manager.ts`): the `jobOperation."operationOrder"` enum
(`methodOperationOrder` = `'After Previous' | 'With Previous'`) decides serial vs
parallel, plus assembly edges (a sub-make-method's last op feeds the parent's
@@ -369,19 +379,20 @@ only; its output is read by nothing in the placement path (spec
dispatch-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 only
sequence.
-- **`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
+- **`persistLocationWrites` (one transaction per location run; the expedite what-if
+ never calls it)** writes, for every op whose
+ values changed (an `is distinct from` guard in the UPDATE, so a quiet regen writes no
`jobOperation` or `job` row and queues no audit/search event), the
forward 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 and
is DIFF-written: only when the computed target differs from the stored value (a
quiet regen touches zero `dueDate`s), and never for a `manuallyScheduled` op — a
- human owns that target. It rebuilds this job's `capacityReservation` rows
- (delete-by-job where `scenarioId IS NULL`, then bulk insert — a materialized OUTPUT,
+ human owns that target. It rebuilds the jobs' `capacityReservation` rows
+ (one delete for all the run's jobs where `scenarioId IS NULL`, then bulk insert — a materialized OUTPUT,
`WorkCenter`/`Employee` kinds); and writes `job.projectedCompletionAt` (= the max
placed end, the forecast finish) while clearing
- `scheduleOutdatedReason`/`scheduleOutdatedAt` for that job. It also computes the
+ `scheduleOutdatedReason`/`scheduleOutdatedAt` for each job. The engine's `buildWrites` also computes the
**newly-late** flag (was on-time-or-unforecast before, now projected past `dueDate`
on the location calendar) for the wave's digest.
- **Behind-target attribution (informational only):** when the JOB's verdict is late,
@@ -401,7 +412,7 @@ only; its output is read by nothing in the placement path (spec
(`20260525143721_manual-scheduling.sql` — adds only this column). Under dual dates a
pin means **a human owns the need-by TARGET**, not the placement: the backward pass
takes the pinned op's stored `dueDate` as-is and derives upstream ops' targets from
-it (the pin propagates), and `persistChanges()` never writes `dueDate` for a pinned
+it (the pin propagates), and the location write never includes `dueDate` for a pinned
op. Forward placement schedules pinned ops **normally** — the old frozen-window
branch (reserve the pinned span, skip placement) was REMOVED with the dual-dates
split, so a pinned op's `startDate`/`projectedCompletionAt` are re-projected every
diff --git a/apps/erp/app/components/ActionTasks/Jira/IssueDialog.tsx b/apps/erp/app/components/ActionTasks/Jira/IssueDialog.tsx
index 951f8e522c..29a5ed58f8 100644
--- a/apps/erp/app/components/ActionTasks/Jira/IssueDialog.tsx
+++ b/apps/erp/app/components/ActionTasks/Jira/IssueDialog.tsx
@@ -4,6 +4,7 @@
import type { ActionTaskEntityType } from "@carbon/ee/action-task-entity";
import { JiraIssueMappingSchema } from "@carbon/ee/jira";
+import { useRevalidator } from "@carbon/query";
import {
Badge,
Button,
@@ -26,7 +27,7 @@ import { Trans, useLingui } from "@lingui/react/macro";
import { useState } from "react";
import { LuExternalLink } from "react-icons/lu";
import { PiLinkBreak } from "react-icons/pi";
-import { Link, useRevalidator } from "react-router";
+import { Link } from "react-router";
import { JiraIcon, JiraIssueStatusBadge } from "~/components/Icons";
import { useAsyncFetcher } from "~/hooks/useAsyncFetcher";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/components/ActionTasks/Linear/IssueDialog.tsx b/apps/erp/app/components/ActionTasks/Linear/IssueDialog.tsx
index eb1f71d31e..2d393f165c 100644
--- a/apps/erp/app/components/ActionTasks/Linear/IssueDialog.tsx
+++ b/apps/erp/app/components/ActionTasks/Linear/IssueDialog.tsx
@@ -4,6 +4,7 @@
import type { ActionTaskEntityType } from "@carbon/ee/action-task-entity";
import { LinearIssueSchema } from "@carbon/ee/linear";
+import { useRevalidator } from "@carbon/query";
import {
Badge,
Button,
@@ -26,7 +27,7 @@ import { Trans, useLingui } from "@lingui/react/macro";
import { useState } from "react";
import { LuExternalLink } from "react-icons/lu";
import { PiLinkBreak } from "react-icons/pi";
-import { Link, useRevalidator } from "react-router";
+import { Link } from "react-router";
import { LinearIcon, LinearIssueStateBadge } from "~/components/Icons";
import { useAsyncFetcher } from "~/hooks/useAsyncFetcher";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/components/AttachmentsList.tsx b/apps/erp/app/components/AttachmentsList.tsx
index 4b5d781287..af9e768405 100644
--- a/apps/erp/app/components/AttachmentsList.tsx
+++ b/apps/erp/app/components/AttachmentsList.tsx
@@ -9,6 +9,7 @@ import {
storage
} from "@carbon/files";
import { MediaUploader, wasConvertedFromHeic } from "@carbon/files/media";
+import { useRevalidator } from "@carbon/query";
import {
Badge,
HStack,
@@ -26,7 +27,6 @@ import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useMemo, useState } from "react";
import { useDropzone } from "react-dropzone";
import { LuCloudUpload, LuFileText, LuX } from "react-icons/lu";
-import { useRevalidator } from "react-router";
import { useUser } from "~/hooks";
import { stripSpecialCharacters } from "~/utils/string";
diff --git a/apps/erp/app/components/CadModel.tsx b/apps/erp/app/components/CadModel.tsx
index 8993b7d3fa..7dd31fc3fc 100644
--- a/apps/erp/app/components/CadModel.tsx
+++ b/apps/erp/app/components/CadModel.tsx
@@ -5,6 +5,7 @@
import { useCarbon } from "@carbon/auth";
import { convertKbToString, TEMP_STAGING_BUCKET } from "@carbon/files";
import { supportedModelTypes } from "@carbon/files/cad";
+import { useRevalidator } from "@carbon/query";
import {
Button,
CardHeader,
@@ -32,7 +33,7 @@ import { nanoid } from "nanoid";
import { useState } from "react";
import { useDropzone } from "react-dropzone";
import { LuCloudUpload, LuRefreshCw, LuZap } from "react-icons/lu";
-import { useFetcher, useRevalidator } from "react-router";
+import { useFetcher } from "react-router";
import { useModelUpload, useUser } from "~/hooks";
import type { ModelUpload } from "~/types";
import type { ViewDirection } from "~/utils/model-thumbnail";
diff --git a/apps/erp/app/components/DefaultAttachmentsPanel.tsx b/apps/erp/app/components/DefaultAttachmentsPanel.tsx
index 04012a5ff4..70b1afe7c0 100644
--- a/apps/erp/app/components/DefaultAttachmentsPanel.tsx
+++ b/apps/erp/app/components/DefaultAttachmentsPanel.tsx
@@ -6,6 +6,7 @@ import { useCarbon } from "@carbon/auth";
import { convertKbToString, downloadUrl, storage } from "@carbon/files";
import { wasConvertedFromHeic } from "@carbon/files/media";
import { getLogger } from "@carbon/logger";
+import { useRevalidator } from "@carbon/query";
import {
Card,
CardContent,
@@ -33,7 +34,6 @@ import type { FileObject } from "@supabase/storage-js";
import type { ReactNode } from "react";
import { useCallback, useState } from "react";
import { LuDownload, LuEllipsisVertical, LuTrash } from "react-icons/lu";
-import { useRevalidator } from "react-router";
import DocumentIcon from "~/components/DocumentIcon";
import DocumentPreview from "~/components/DocumentPreview";
import FileDropzone from "~/components/FileDropzone";
diff --git a/apps/erp/app/components/DeferredFiles.tsx b/apps/erp/app/components/DeferredFiles.tsx
index 1c05a8a0cf..d6afc513e5 100644
--- a/apps/erp/app/components/DeferredFiles.tsx
+++ b/apps/erp/app/components/DeferredFiles.tsx
@@ -2,6 +2,7 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+import { useRevalidator } from "@carbon/query";
import {
Button,
Card,
@@ -13,7 +14,7 @@ import {
import { Trans } from "@lingui/react/macro";
import { Suspense } from "react";
import { LuRefreshCw, LuTriangleAlert } from "react-icons/lu";
-import { Await, useRevalidator } from "react-router";
+import { Await } from "react-router";
function DocumentsSkeleton() {
return (
diff --git a/apps/erp/app/components/DocumentTemplateEditor/BlockList.tsx b/apps/erp/app/components/DocumentTemplateEditor/BlockList.tsx
index cf1a19c442..7c7ae6d532 100644
--- a/apps/erp/app/components/DocumentTemplateEditor/BlockList.tsx
+++ b/apps/erp/app/components/DocumentTemplateEditor/BlockList.tsx
@@ -67,6 +67,10 @@ import {
} from "./context";
import { HEADER_LOGO_ID, useHeaderConfig } from "./useHeaderConfig";
+// Module constants: a new options object makes a new sensor, and with it new
+// listeners for every draggable on every render.
+const POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 8 } };
+
const ADD_OPTIONS: {
type: AddableBlockType;
icon: ReactNode;
@@ -133,7 +137,7 @@ export function BlockList() {
? bodyBlocks.filter((b) => b.id !== summaryBlock.id)
: bodyBlocks;
const sensors = useSensors(
- useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
+ useSensor(PointerSensor, POINTER_SENSOR_OPTIONS),
useSensor(KeyboardSensor)
);
diff --git a/apps/erp/app/components/Documents.tsx b/apps/erp/app/components/Documents.tsx
index 46d3f21db4..a5d09157ae 100644
--- a/apps/erp/app/components/Documents.tsx
+++ b/apps/erp/app/components/Documents.tsx
@@ -5,6 +5,7 @@
import { useCarbon } from "@carbon/auth";
import { convertKbToString, downloadUrl, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
+import { useRevalidator } from "@carbon/query";
import {
Card,
CardAction,
@@ -32,7 +33,7 @@ import { Trans, useLingui } from "@lingui/react/macro";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
import { LuAxis3D, LuEllipsisVertical, LuUpload } from "react-icons/lu";
-import { Link, useFetchers, useRevalidator, useSubmit } from "react-router";
+import { Link, useFetchers, useSubmit } from "react-router";
import {
DocumentPreview,
FileDropzone,
diff --git a/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx b/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
index 63b8b117b7..00182233f8 100644
--- a/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
+++ b/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
@@ -52,6 +52,10 @@ import { NavigationEditBar } from "./NavigationEditBar";
import { SortableNavItem } from "./SortableNavItem";
import { useNavigationEditMode } from "./useNavigationEditMode";
+// Module constants: a new options object makes a new sensor, and with it new
+// listeners for every draggable on every render.
+const POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 8 } };
+
// Search and Customize are actions, not destinations — they keep the neutral
// accent hover instead of the active-tinted one module links use.
const ACTION_HOVER = "hover:bg-accent hover:text-accent-foreground";
@@ -142,7 +146,7 @@ const PrimaryNavigation = () => {
const isSearchModalOpen = useUIStore((s) => s.isSearchModalOpen);
const sensors = useSensors(
- useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
+ useSensor(PointerSensor, POINTER_SENSOR_OPTIONS),
useSensor(KeyboardSensor)
);
diff --git a/apps/erp/app/components/LineReorder/ReorderableLineList.tsx b/apps/erp/app/components/LineReorder/ReorderableLineList.tsx
index a3793b2d01..315f088565 100644
--- a/apps/erp/app/components/LineReorder/ReorderableLineList.tsx
+++ b/apps/erp/app/components/LineReorder/ReorderableLineList.tsx
@@ -23,6 +23,10 @@ import type { ReactNode } from "react";
import { createPortal } from "react-dom";
import type { DragHandleBindings, ReorderableLine } from "./types";
+// Module constants: a new options object makes a new sensor, and with it new
+// listeners for every draggable on every render.
+const POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 8 } };
+
type ReorderableLineListProps<T extends ReorderableLine> = {
lines: T[];
activeLine: T | null;
@@ -41,7 +45,7 @@ export function ReorderableLineList<T extends ReorderableLine>({
renderOverlay
}: ReorderableLineListProps<T>) {
const sensors = useSensors(
- useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
+ useSensor(PointerSensor, POINTER_SENSOR_OPTIONS),
useSensor(KeyboardSensor)
);
diff --git a/apps/erp/app/components/RecordDocuments.tsx b/apps/erp/app/components/RecordDocuments.tsx
index 7fb1d67a8f..e19861d21e 100644
--- a/apps/erp/app/components/RecordDocuments.tsx
+++ b/apps/erp/app/components/RecordDocuments.tsx
@@ -5,6 +5,7 @@
import { useCarbon } from "@carbon/auth";
import { convertKbToString, downloadUrl, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
+import { useRevalidator } from "@carbon/query";
import {
Card,
CardAction,
@@ -32,7 +33,7 @@ import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
import { LuEllipsisVertical, LuExternalLink, LuUpload } from "react-icons/lu";
-import { useFetchers, useRevalidator, useSubmit } from "react-router";
+import { useFetchers, useSubmit } from "react-router";
import { DateTime, DocumentPreview, FileDropzone } from "~/components";
import DocumentIcon from "~/components/DocumentIcon";
import { useFileUpload, usePermissions, useUser } from "~/hooks";
diff --git a/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx b/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx
index df8378b919..c8c9022c48 100644
--- a/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx
+++ b/apps/erp/app/modules/documents/ui/Documents/DocumentsTable.tsx
@@ -4,6 +4,7 @@
import { getBrowserEnv } from "@carbon/auth";
import { convertKbToString } from "@carbon/files";
+import { useRevalidator } from "@carbon/query";
import {
Badge,
BadgeCloseButton,
@@ -42,7 +43,6 @@ import {
LuUsers
} from "react-icons/lu";
import { RxCheck } from "react-icons/rx";
-import { useRevalidator } from "react-router";
import { DateTime, EmployeeAvatar, Hyperlink, Table } from "~/components";
import DocumentIcon from "~/components/DocumentIcon";
import { Enumerable } from "~/components/Enumerable";
diff --git a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCount.tsx b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCount.tsx
index e8f8c25bf6..cea8595f12 100644
--- a/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCount.tsx
+++ b/apps/erp/app/modules/inventory/ui/InventoryCount/InventoryCount.tsx
@@ -2,6 +2,7 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+import { useRevalidator } from "@carbon/query";
import {
Button,
HStack,
@@ -23,7 +24,7 @@ import {
LuRotateCcw,
LuSend
} from "react-icons/lu";
-import { useFetcher, useRevalidator } from "react-router";
+import { useFetcher } from "react-router";
import { usePermissions } from "~/hooks";
import type {
InventoryCountLine,
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
index 71dee6e110..07d674891c 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
@@ -5,7 +5,7 @@
import { useCarbon } from "@carbon/auth";
import { isPreviewableDocumentType, storage } from "@carbon/files";
import { Number, Submit, ValidatedForm } from "@carbon/form";
-import { useAction } from "@carbon/query";
+import { useAction, useRevalidator } from "@carbon/query";
import {
Button,
Card,
@@ -61,7 +61,6 @@ import {
useFetcher,
useFetchers,
useParams,
- useRevalidator,
useSubmit
} from "react-router";
import {
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
index 8888c90177..4e600f5960 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -7,7 +7,7 @@ import { useCarbon } from "@carbon/auth";
import { getCompanyPrivateBucket, storage } from "@carbon/files";
import { convertHeicToJpeg, isHeic } from "@carbon/files/media";
import { Array as ArrayInput, Input, ValidatedForm } from "@carbon/form";
-import { useAction } from "@carbon/query";
+import { useAction, useRevalidator } from "@carbon/query";
import type { JSONContent } from "@carbon/react";
import {
Alert,
@@ -73,12 +73,7 @@ import {
LuSquareFunction,
LuTriangleAlert
} from "react-icons/lu";
-import {
- useFetcher,
- useFetchers,
- useParams,
- useRevalidator
-} from "react-router";
+import { useFetcher, useFetchers, useParams } from "react-router";
import { z } from "zod";
import {
DateTime,
diff --git a/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx b/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
index 21fcbc76d1..cae76a5c0d 100644
--- a/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
+++ b/apps/erp/app/modules/items/ui/Item/ItemDocuments.tsx
@@ -5,6 +5,7 @@
import { useCarbon } from "@carbon/auth";
import { convertKbToString, downloadUrl, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
+import { useRevalidator } from "@carbon/query";
import {
Card,
CardAction,
@@ -33,7 +34,7 @@ import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
import { LuAxis3D, LuEllipsisVertical, LuUpload } from "react-icons/lu";
-import { Link, useFetchers, useRevalidator, useSubmit } from "react-router";
+import { Link, useFetchers, useSubmit } from "react-router";
import {
DateTime,
DocumentPreview,
diff --git a/apps/erp/app/modules/items/ui/Parts/ConfigurationParameters.tsx b/apps/erp/app/modules/items/ui/Parts/ConfigurationParameters.tsx
index 495783bf5b..2fcc2a5c2b 100644
--- a/apps/erp/app/modules/items/ui/Parts/ConfigurationParameters.tsx
+++ b/apps/erp/app/modules/items/ui/Parts/ConfigurationParameters.tsx
@@ -177,9 +177,7 @@ export default function ConfigurationParametersForm({
const sensors = useSensors(
useSensor(MouseSensor),
useSensor(TouchSensor),
- useSensor(KeyboardSensor, {
- coordinateGetter
- })
+ useSensor(KeyboardSensor, KEYBOARD_SENSOR_OPTIONS)
);
return (
@@ -1337,3 +1335,8 @@ export function hasDraggableData<T extends Active | Over>(
return false;
}
+
+// Declared after `coordinateGetter`. A module constant: a new options object
+// makes a new sensor, and with it new listeners for every draggable on every
+// render.
+const KEYBOARD_SENSOR_OPTIONS = { coordinateGetter };
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index 4ede641ae0..e08a5129a8 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -1014,6 +1014,23 @@ export const scheduleOperationUpdateValidator = z.object({
priority: schedulePriorityValidator
});
+// A drop that renumbers several cards of one column, sent as one request.
+export const scheduleOperationReorderValidator = z.object({
+ columnId: z.string().min(1, { message: "Column is required" }),
+ updates: z
+ .array(
+ z.object({
+ id: z.string().min(1),
+ priority: z.number().refine(Number.isFinite, "Priority must be finite")
+ })
+ )
+ .min(1)
+ .max(1000)
+ .refine((rows) => new Set(rows.map((r) => r.id)).size === rows.length, {
+ message: "Each operation may appear once"
+ })
+});
+
export const scheduleJobUpdateValidator = z.object({
id: z.string().min(1, { message: "ID is required" }),
locationId: z.string().trim().min(1, { message: "Location is required" }),
diff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.ts
index ffcb69655f..cb3e8a1572 100644
--- a/apps/erp/app/modules/production/production.server.ts
+++ b/apps/erp/app/modules/production/production.server.ts
@@ -9,6 +9,8 @@ import { ASSEMBLER_SERVICE_URL } from "@carbon/env";
import { serverFns } from "@carbon/server-functions";
import { datetime, getErrorMessage } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
+import { sql } from "kysely";
+import { isJobLocked } from "./production.models";
import {
getJobReleaseReadiness,
recalculateJobRequirements,
@@ -232,3 +234,145 @@ export async function releaseBatchMemberJobs({
purchaseOrdersBySupplierId: purchaseOrders
});
}
+
+/**
+ * Write the priorities (and work center) a drop on the schedule board gives
+ * several operations of one column, as one all-or-nothing statement. The
+ * checks are the single-operation update's, made once for the set: every
+ * operation exists and is open, its job is unlocked and at the work center's
+ * location, and the work center runs its process.
+ */
+export async function reorderScheduleOperations(
+ client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
+ args: {
+ companyId: string;
+ userId: string;
+ columnId: string;
+ updates: { id: string; priority: number }[];
+ }
+): Promise<
+ | { success: true; workCenterChanged: boolean }
+ | { success: false; message: string }
+> {
+ const { companyId, userId, columnId, updates } = args;
+ const invalid = {
+ success: false as const,
+ message: "Invalid scheduling request"
+ };
+ const ids = updates.map((u) => u.id);
+
+ const [operations, workCenter] = await Promise.all([
+ client
+ .from("jobOperation")
+ .select("id, jobId, processId, status, workCenterId")
+ .eq("companyId", companyId)
+ .in("id", ids),
+ client
+ .from("workCenter")
+ .select("id, active, locationId")
+ .eq("id", columnId)
+ .eq("companyId", companyId)
+ .maybeSingle()
+ ]);
+ if (
+ operations.error ||
+ workCenter.error ||
+ !workCenter.data?.active ||
+ operations.data.length !== ids.length ||
+ operations.data.some((o) => o.status === "Done" || o.status === "Canceled")
+ ) {
+ return invalid;
+ }
+
+ const destination = workCenter.data;
+ const jobIds = [...new Set(operations.data.map((o) => o.jobId))];
+ const processIds = [...new Set(operations.data.map((o) => o.processId))];
+ const [jobs, processes] = await Promise.all([
+ client
+ .from("job")
+ .select("id, locationId, status")
+ .eq("companyId", companyId)
+ .in("id", jobIds),
+ client
+ .from("workCenterProcess")
+ .select("processId")
+ .eq("workCenterId", destination.id)
+ .eq("companyId", companyId)
+ .in("processId", processIds)
+ ]);
+ if (
+ jobs.error ||
+ processes.error ||
+ jobs.data.length !== jobIds.length ||
+ jobs.data.some(
+ (j) => isJobLocked(j.status) || j.locationId !== destination.locationId
+ ) ||
+ new Set(processes.data.map((p) => p.processId)).size !== processIds.length
+ ) {
+ return invalid;
+ }
+
+ const processByOperation = new Map(
+ operations.data.map((o) => [o.id, o.processId])
+ );
+
+ try {
+ await db.transaction().execute(async (trx) => {
+ // Read again under a lock: a job completed or moved since the first read
+ // must not have its operations rescheduled.
+ const current = await trx
+ .selectFrom("job")
+ .select(["status", "locationId"])
+ .where("companyId", "=", companyId)
+ .where("id", "in", jobIds)
+ .forShare()
+ .execute();
+ if (
+ current.length !== jobIds.length ||
+ current.some(
+ (j) =>
+ isJobLocked(j.status) || j.locationId !== destination.locationId
+ )
+ ) {
+ throw new Error("Job unavailable");
+ }
+
+ const written = await sql<{ id: string }>`
+ UPDATE "jobOperation" AS o
+ SET "workCenterId" = ${destination.id},
+ "priority" = v."priority"::float8,
+ "updatedBy" = ${userId},
+ "updatedAt" = ${datetime.timestamp()}
+ FROM (VALUES ${sql.join(
+ updates.map(
+ (u) =>
+ sql`(${u.id}, ${u.priority}, ${processByOperation.get(u.id) ?? null})`
+ )
+ )}) AS v("id", "priority", "processId")
+ WHERE o."id" = v."id"
+ AND o."processId" IS NOT DISTINCT FROM v."processId"
+ AND o."companyId" = ${companyId}
+ AND o."status" NOT IN ('Done', 'Canceled')
+ RETURNING o."id"
+ `.execute(trx);
+ // An operation that finished, left or changed process since the read:
+ // none are written.
+ if (written.rows.length !== ids.length) {
+ throw new Error("Operation unavailable");
+ }
+ });
+ } catch (err) {
+ return {
+ success: false,
+ message: getErrorMessage(err, "Failed to reorder operations")
+ };
+ }
+
+ return {
+ success: true,
+ workCenterChanged: operations.data.some(
+ (o) => o.workCenterId !== destination.id
+ )
+ };
+}
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx
index b2c4a3ad06..f94de024d4 100644
--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyInstructionExplorer.tsx
@@ -2,6 +2,7 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+import { useRevalidator } from "@carbon/query";
import {
Button,
cn,
@@ -42,12 +43,7 @@ import {
LuTriangleAlert,
LuWaypoints
} from "react-icons/lu";
-import {
- useFetcher,
- useParams,
- useRevalidator,
- useSearchParams
-} from "react-router";
+import { useFetcher, useParams, useSearchParams } from "react-router";
import { Empty } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
import { usePermissions, useRealtime } from "~/hooks";
diff --git a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepList.tsx b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepList.tsx
index 1e0c647fcf..3a3e526dfc 100644
--- a/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepList.tsx
+++ b/apps/erp/app/modules/production/ui/Assemblies/AssemblyStepList.tsx
@@ -91,6 +91,10 @@ import {
useStepStatusLabel
} from "./AssemblyStepStatus";
+// Module constants: a new options object makes a new sensor, and with it new
+// listeners for every draggable on every render.
+const POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 8 } };
+
/** The search param that opens a sub-assembly: the list and player show only its steps. */
export const SUB_ASSEMBLY_PARAM = "subAssembly";
@@ -427,8 +431,8 @@ export default function AssemblyStepList({
const [headerToDelete, setHeaderToDelete] = useState<string | null>(null);
const sensors = useSensors(
- useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
- useSensor(KeyboardSensor, { coordinateGetter })
+ useSensor(PointerSensor, POINTER_SENSOR_OPTIONS),
+ useSensor(KeyboardSensor, KEYBOARD_SENSOR_OPTIONS)
);
/**
@@ -1248,3 +1252,8 @@ function RowIcon({ label, children }: { label: string; children: ReactNode }) {
</Tooltip>
);
}
+
+// Declared after `coordinateGetter`. A module constant: a new options object
+// makes a new sensor, and with it new listeners for every draggable on every
+// render.
+const KEYBOARD_SENSOR_OPTIONS = { coordinateGetter };
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index e07c4e0d21..c75e0630c5 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -9,7 +9,7 @@ import { getCompanyPrivateBucket, storage } from "@carbon/files";
import { convertHeicToJpeg, isHeic } from "@carbon/files/media";
import { Array as ArrayInput, Input, ValidatedForm } from "@carbon/form";
import { getLogger } from "@carbon/logger";
-import { useAction, useChangedRows } from "@carbon/query";
+import { useAction, useChangedRows, useRevalidator } from "@carbon/query";
import type { JSONContent } from "@carbon/react";
import {
Alert,
@@ -89,13 +89,7 @@ import {
LuShieldX,
LuTriangleAlert
} from "react-icons/lu";
-import {
- Link,
- useFetcher,
- useFetchers,
- useParams,
- useRevalidator
-} from "react-router";
+import { Link, useFetcher, useFetchers, useParams } from "react-router";
import type { z } from "zod";
import {
Assignee,
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx b/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx
index 5b9e70ae9e..5397cc717b 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobDocuments.tsx
@@ -5,6 +5,7 @@
import { useCarbon } from "@carbon/auth";
import { convertKbToString, downloadUrl, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
+import { useRevalidator } from "@carbon/query";
import {
Card,
CardAction,
@@ -39,7 +40,7 @@ import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
import { LuEllipsisVertical, LuUpload } from "react-icons/lu";
-import { Link, useFetchers, useRevalidator, useSubmit } from "react-router";
+import { Link, useFetchers, useSubmit } from "react-router";
import {
DateTime,
DocumentPreview,
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/DateKanban.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/DateKanban.tsx
index 50d106ae8b..e494fe286a 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/DateKanban.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/DateKanban.tsx
@@ -50,6 +50,12 @@ import {
import type { Column, DisplaySettings, JobItem, Progress } from "./types";
import { hasDraggableData, kanbanCollisionDetection } from "./utils";
+// Module constants: a new options object makes a new sensor, and with it new
+// listeners for every draggable on every render.
+const KEYBOARD_SENSOR_OPTIONS = {
+ coordinateGetter: sortableKeyboardCoordinates
+};
+
const logger = getLogger("erp", "datekanban");
type DateKanbanProps = {
@@ -305,9 +311,7 @@ const DateKanban = ({
const sensors = useSensors(
useSensor(PointerSensor),
- useSensor(KeyboardSensor, {
- coordinateGetter: sortableKeyboardCoordinates
- })
+ useSensor(KeyboardSensor, KEYBOARD_SENSOR_OPTIONS)
);
function clearDragState() {
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/Kanban.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/Kanban.tsx
index ee68d285e6..e52554de8e 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/Kanban.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/Kanban.tsx
@@ -22,7 +22,14 @@ import {
useSensors
} from "@dnd-kit/core";
import { arrayMove, SortableContext } from "@dnd-kit/sortable";
-import { createContext, useContext, useEffect, useRef, useState } from "react";
+import {
+ createContext,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState
+} from "react";
import { createPortal } from "react-dom";
import { useFetchers, useSubmit } from "react-router";
import { path } from "~/utils/path";
@@ -71,6 +78,11 @@ type KanbanDragState = {
const KanbanDragPreviewContext = createContext<KanbanDragState | null>(null);
+// A new options object makes a new sensor, and with it new listeners for
+// every card on every render of the board.
+const KEYBOARD_SENSOR_OPTIONS = { coordinateGetter };
+const NO_ITEMS: Item[] = [];
+
function PreviewItemCard({
item,
isOverlay,
@@ -411,21 +423,36 @@ const Kanban = ({
localStorage.setItem(COLUMN_ORDER_KEY, JSON.stringify(columnOrder));
}, [columnOrder]);
- const itemsById = new Map<string, Item>(
- initialItems.map((item) => [item.id, item])
- );
const pendingItems = usePendingItems();
-
- // merge pending items and existing items
- for (const pendingItem of pendingItems) {
- const item = itemsById.get(pendingItem.id);
- if (item) {
- itemsById.set(pendingItem.id, { ...item, ...pendingItem });
+ // The board re-renders on every drag state change. Deriving these once per
+ // change of the data keeps each column's item array (and so its cards) the
+ // same object across those renders.
+ const pendingKey = JSON.stringify(pendingItems);
+ // biome-ignore lint/correctness/useExhaustiveDependencies: pendingItems is keyed by value
+ const { items, itemsById, itemsByColumn } = useMemo(() => {
+ const byId = new Map<string, Item>(
+ initialItems.map((item) => [item.id, item])
+ );
+ // merge pending items and existing items
+ for (const pendingItem of pendingItems) {
+ const item = byId.get(pendingItem.id);
+ if (item) {
+ byId.set(pendingItem.id, { ...item, ...pendingItem });
+ }
}
- }
-
- const items = Array.from(itemsById.values()).sort(comparePriorityThenId);
- const columnsById = new Map(columns.map((column) => [column.id, column]));
+ const sorted = Array.from(byId.values()).sort(comparePriorityThenId);
+ const byColumn = new Map<string, Item[]>();
+ for (const item of sorted) {
+ const column = byColumn.get(item.columnId);
+ if (column) column.push(item);
+ else byColumn.set(item.columnId, [item]);
+ }
+ return { items: sorted, itemsById: byId, itemsByColumn: byColumn };
+ }, [initialItems, pendingKey]);
+ const columnsById = useMemo(
+ () => new Map(columns.map((column) => [column.id, column])),
+ [columns]
+ );
const pickedUpItemColumn = useRef<string | null>(null);
const dragOriginRef = useRef<OperationDragOrigin | null>(null);
@@ -437,9 +464,7 @@ const Kanban = ({
const sensors = useSensors(
useSensor(MouseSensor),
useSensor(TouchSensor),
- useSensor(KeyboardSensor, {
- coordinateGetter
- })
+ useSensor(KeyboardSensor, KEYBOARD_SENSOR_OPTIONS)
);
function getDraggingItemData(itemId: UniqueIdentifier, columnId: string) {
@@ -576,7 +601,7 @@ const Kanban = ({
<ColumnCard
key={col.id}
column={col}
- items={items.filter((item) => item.columnId === col.id)}
+ items={itemsByColumn.get(col.id) ?? NO_ITEMS}
progressByItemId={progressByItemId}
CardComponent={PreviewItemCard}
/>
@@ -593,9 +618,7 @@ const Kanban = ({
<ColumnCard
isOverlay
column={activeColumn}
- items={items.filter(
- (item) => item.columnId === activeColumn.id
- )}
+ items={itemsByColumn.get(activeColumn.id) ?? NO_ITEMS}
progressByItemId={progressByItemId}
/>
)}
@@ -757,8 +780,37 @@ const Kanban = ({
// its priority (+ work center), a batch card writes every member's
// priority so min(member) lands at the batch's new dispatch slot.
const flushSync = commit.updates.length === 1;
+ const isBatchCard = (id: string) => {
+ const target = itemsById.get(id);
+ return !!target && isBatchItem(target);
+ };
+ // Several operations renumbered by one drop go in ONE request. One
+ // request per card meant one page reload per card, and the board
+ // stuttered for seconds after the drop.
+ const operationUpdates = commit.updates.filter(
+ (update) => !isBatchCard(update.id)
+ );
+ if (operationUpdates.length > 1) {
+ submit(
+ {
+ columnId: commit.columnId,
+ updates: JSON.stringify(operationUpdates)
+ },
+ {
+ method: "post",
+ action: path.to.priorityOperationUpdate,
+ navigate: false,
+ // Not the card's own key: a later move of that card would
+ // replace this fetcher and drop the other cards' pending order.
+ fetcherKey: `reorder:${commit.columnId}`
+ }
+ );
+ }
for (const update of commit.updates) {
const target = itemsById.get(update.id);
+ if (operationUpdates.length > 1 && !isBatchCard(update.id)) {
+ continue;
+ }
if (target && isBatchItem(target)) {
submit(
{
@@ -836,16 +888,25 @@ function usePendingItems() {
.filter((fetcher): fetcher is PendingItem => {
return fetcher.formAction === path.to.priorityOperationUpdate;
})
- .map((fetcher) => {
- let columnId = String(fetcher.formData.get("columnId"));
- let id = String(fetcher.formData.get("id"));
- let priority = Number(fetcher.formData.get("priority"));
- let item: { id: string; priority?: number; columnId: string } = {
- id,
- priority,
- columnId
- };
- return item;
+ .flatMap((fetcher) => {
+ const columnId = String(fetcher.formData.get("columnId"));
+ const updates = fetcher.formData.get("updates");
+ const rows: { id: string; priority: number }[] =
+ typeof updates === "string"
+ ? JSON.parse(updates)
+ : [
+ {
+ id: String(fetcher.formData.get("id")),
+ priority: Number(fetcher.formData.get("priority"))
+ }
+ ];
+ return rows.map(
+ (row): { id: string; priority?: number; columnId: string } => ({
+ id: row.id,
+ priority: row.priority,
+ columnId
+ })
+ );
});
// A batch work-center reassignment in flight: keep the batch card in its
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/cardShell.ts b/apps/erp/app/modules/production/ui/Schedule/Kanban/cardShell.ts
index e1df631dd1..2f97031082 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/cardShell.ts
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/cardShell.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 type { useSortable } from "@dnd-kit/sortable";
+import { CSS } from "@dnd-kit/utilities";
+
// The shared visual shell for every schedule-board card (operation, job, batch):
// card background, hover, and the dark-mode elevated-surface shadow. Kept in one
// place so the batch card is visually locked to the operation/job cards instead
@@ -10,3 +13,32 @@
// utility is a separate, app-wide change.)
export const KANBAN_CARD_SHELL =
"bg-card hover:bg-muted/30 dark:border-none dark:shadow-[inset_0_0.5px_0_rgb(255_255_255_/_0.08),_inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)]";
+
+type Sortable = ReturnType<typeof useSortable>;
+
+/**
+ * What a card's body needs from `useSortable`, as values `memo` can compare.
+ *
+ * A card is a thin shell that calls `useSortable` and a memoized body that
+ * takes these as props. dnd-kit re-renders every sortable whenever the drop
+ * target changes; with the hook inside the body, every card on the board
+ * rendered in full on each change (a form, avatars and menus per card) and a
+ * drag stuttered. Now only the cards that move or change drag state do.
+ */
+export type SortableCardProps = {
+ setNodeRef: Sortable["setNodeRef"];
+ attributes: Sortable["attributes"];
+ listeners: Sortable["listeners"];
+ transform: string | undefined;
+ transition: string | undefined;
+ isDragging: boolean;
+};
+
+export const sortableCardProps = (sortable: Sortable): SortableCardProps => ({
+ setNodeRef: sortable.setNodeRef,
+ attributes: sortable.attributes,
+ listeners: sortable.listeners,
+ transform: CSS.Translate.toString(sortable.transform),
+ transition: sortable.transition,
+ isDragging: sortable.isDragging
+});
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/BatchItemCard.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/BatchItemCard.tsx
index 9fd578f032..208dcddfd3 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/BatchItemCard.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/BatchItemCard.tsx
@@ -19,9 +19,8 @@ import {
MENU_ITEM_SHORTCUTS
} from "@carbon/react";
import { useSortable } from "@dnd-kit/sortable";
-import { CSS } from "@dnd-kit/utilities";
import { useLingui } from "@lingui/react/macro";
-import { useState } from "react";
+import { memo, useState } from "react";
import {
LuCircleCheck,
LuEllipsisVertical,
@@ -39,10 +38,13 @@ import { CustomerAvatar, OperationStatusIcon } from "~/components";
import { ConfirmDelete } from "~/components/Modals";
import { useDateFormatter } from "~/hooks";
import { path } from "~/utils/path";
-import { KANBAN_CARD_SHELL } from "../cardShell";
+import {
+ KANBAN_CARD_SHELL,
+ type SortableCardProps,
+ sortableCardProps
+} from "../cardShell";
import { useKanban } from "../context/KanbanContext";
import type { BatchItem, OperationItem } from "../types";
-import { useScheduleToday } from "../useScheduleToday";
import { CardMaterialChips, CardSummaryRows } from "./CardSummaryRows";
// The order a batch summary reports its members' statuses in: the most "live"
@@ -78,41 +80,42 @@ function rollupStatus(members: OperationItem[]): OperationItem["status"] {
// card's information design — the same display-setting rows (status, progress,
// due date, customer, duration, materials) rolled up across members — rather
// than dropping them; the member list sits beneath that summary.
-export function BatchItemCard({
- item,
- isOverlay
-}: {
+type BatchItemCardProps = {
item: BatchItem;
isOverlay?: boolean;
-}) {
+};
+
+export function BatchItemCard(props: BatchItemCardProps) {
+ const sortable = useSortable({
+ id: props.item.id,
+ data: { type: "item", item: props.item },
+ attributes: { roleDescription: "item" },
+ disabled: props.item.batchStatus === "Completing"
+ });
+ return <BatchItemCardBody {...props} {...sortableCardProps(sortable)} />;
+}
+
+const BatchItemCardBody = memo(function BatchItemCardBody({
+ item,
+ isOverlay,
+ setNodeRef,
+ attributes,
+ listeners,
+ transform,
+ transition,
+ isDragging
+}: BatchItemCardProps & SortableCardProps) {
const { t } = useLingui();
const { formatRelativeTime } = useDateFormatter();
- const { displaySettings } = useKanban();
- const scheduleToday = useScheduleToday();
+ const { displaySettings, scheduleToday } = useKanban();
const fetcher = useFetcher();
const isCompleting = item.batchStatus === "Completing";
// Planned = composed but not yet on the floor. Visually distinct (dashed
// border, outline badge) but still draggable — work-center reassignment is
// legal pre-release.
const isPlanned = item.batchStatus === "Planned";
- const {
- setNodeRef,
- attributes,
- listeners,
- transform,
- transition,
- isDragging
- } = useSortable({
- id: item.id,
- data: { type: "item", item },
- attributes: { roleDescription: "item" },
- disabled: isCompleting
- });
- const style = {
- transition,
- transform: CSS.Translate.toString(transform)
- };
+ const style = { transition, transform };
const members = item.members;
const totalQty = members.reduce((sum, m) => sum + (m.quantity ?? 0), 0);
@@ -363,4 +366,4 @@ export function BatchItemCard({
)}
</>
);
-}
+});
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx
index 564a94f468..0bbd4edcc8 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/ItemCard.tsx
@@ -29,6 +29,7 @@ import { CSS } from "@dnd-kit/utilities";
import { parseDate } from "@internationalized/date";
import { useLingui } from "@lingui/react/macro";
import { cva } from "class-variance-authority";
+import { memo } from "react";
import {
LuCalendarClock,
LuCircleCheck,
@@ -59,7 +60,6 @@ import { KANBAN_CARD_SHELL } from "../cardShell";
import { useKanban } from "../context/KanbanContext";
import type { Item, OperationItem } from "../types";
import { isBatchItem } from "../types";
-import { useScheduleToday } from "../useScheduleToday";
import { CardMaterialChips, CardSummaryRows } from "./CardSummaryRows";
interface Progress {
@@ -117,10 +117,7 @@ function OperationCard({
isOverlay?: boolean;
progressByItemId: Record<string, Progress>;
}) {
- const { t } = useLingui();
- const { formatRelativeTime } = useDateFormatter();
- const { displaySettings, selectedGroup, setSelectedGroup, tags } =
- useKanban();
+ const { selectedGroup } = useKanban();
const {
setNodeRef,
attributes,
@@ -140,13 +137,61 @@ function OperationCard({
});
const isHighlighted = selectedGroup === item.jobReadableId;
- const scheduleToday = useScheduleToday();
+ const itemProgress = progressByItemId[item.id];
+ const status = itemProgress?.active ? "In Progress" : item.status;
const style = {
transition,
transform: CSS.Translate.toString(transform)
};
+ // This shell re-renders whenever the drop target changes; the body does
+ // not. It is the expensive part (a form, avatars and menus per card), and
+ // rendering every card's body on each change made a drag stutter.
+ return (
+ <Card
+ ref={setNodeRef}
+ style={style}
+ className={cn(
+ "group/card max-w-[330px]",
+ item.hasConflict && "border-red-500 border-2",
+ cardVariants({
+ dragging: isOverlay ? "overlay" : isDragging ? "over" : undefined,
+ // @ts-expect-error TS2322 - TODO: fix type
+ status: status,
+ highlighted: isHighlighted
+ })
+ )}
+ >
+ <OperationCardBody
+ item={item}
+ itemProgress={itemProgress}
+ isHighlighted={isHighlighted}
+ attributes={attributes}
+ listeners={listeners}
+ />
+ </Card>
+ );
+}
+
+const OperationCardBody = memo(function OperationCardBody({
+ item,
+ itemProgress,
+ isHighlighted,
+ attributes,
+ listeners
+}: {
+ item: Exclude<Item, { batchId: string }>;
+ itemProgress: Progress | undefined;
+ isHighlighted: boolean;
+ attributes: ReturnType<typeof useSortable>["attributes"];
+ listeners: ReturnType<typeof useSortable>["listeners"];
+}) {
+ const { t } = useLingui();
+ const { formatRelativeTime } = useDateFormatter();
+ const { displaySettings, setSelectedGroup, tags, scheduleToday } =
+ useKanban();
+
const isOverdue =
item.deadlineType !== "No Deadline" && item.dueDate
? item.dueDate < scheduleToday
@@ -163,29 +208,14 @@ function OperationCard({
: 0;
const isBehindTarget = daysBehindTarget > 0;
- const progress = progressByItemId[item.id]?.progress ?? 0;
- const status = progressByItemId[item.id]?.active
- ? "In Progress"
- : item.status;
- const employeeIds = progressByItemId[item.id]?.employees
- ? Array.from(progressByItemId[item.id].employees!)
+ const progress = itemProgress?.progress ?? 0;
+ const status = itemProgress?.active ? "In Progress" : item.status;
+ const employeeIds = itemProgress?.employees
+ ? Array.from(itemProgress.employees)
: undefined;
return (
- <Card
- ref={setNodeRef}
- style={style}
- className={cn(
- "group/card max-w-[330px]",
- item.hasConflict && "border-red-500 border-2",
- cardVariants({
- dragging: isOverlay ? "overlay" : isDragging ? "over" : undefined,
- // @ts-expect-error TS2322 - TODO: fix type
- status: status,
- highlighted: isHighlighted
- })
- )}
- >
+ <>
<CardHeader className="flex flex-col justify-between relative gap-2">
<div className="flex w-full max-w-full justify-between items-start gap-0">
<div className="flex flex-col space-y-0 min-w-0">
@@ -443,9 +473,9 @@ function OperationCard({
<JobOperationTags operation={item} availableTags={tags} />
</HStack>
</CardFooter>
- </Card>
+ </>
);
-}
+});
function JobOperationTags({
operation,
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx
index af3fba426c..be4f4ff9c4 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/components/JobCard.tsx
@@ -23,10 +23,10 @@ import {
TooltipTrigger
} from "@carbon/react";
import { useSortable } from "@dnd-kit/sortable";
-import { CSS } from "@dnd-kit/utilities";
import { parseDate } from "@internationalized/date";
import { useLingui } from "@lingui/react/macro";
import { cva } from "class-variance-authority";
+import { memo } from "react";
import { AiOutlinePartition } from "react-icons/ai";
import {
LuCalendarDays,
@@ -48,7 +48,11 @@ import { getDeadlineIcon } from "~/modules/production/ui/Jobs/Deadline";
import { useCustomers } from "~/stores";
import { getPrivateUrl, path } from "~/utils/path";
import JobStatus from "../../../Jobs/JobStatus";
-import { KANBAN_CARD_SHELL } from "../cardShell";
+import {
+ KANBAN_CARD_SHELL,
+ type SortableCardProps,
+ sortableCardProps
+} from "../cardShell";
import { useKanban } from "../context/KanbanContext";
import {
getDateOnly,
@@ -56,7 +60,6 @@ import {
isDateColumnId
} from "../date-utils";
import type { JobItem } from "../types";
-import { useScheduleToday } from "../useScheduleToday";
interface Progress {
totalDuration: number;
@@ -100,41 +103,46 @@ type JobCardProps = {
progressByItemId: Record<string, Progress>;
};
-export function JobCard({
- item,
- locationId,
- isOverlay,
- progressByItemId
-}: JobCardProps) {
- const { t } = useLingui();
- const submit = useSubmit();
- // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
- const { displaySettings, selectedGroup, setSelectedGroup, tags, columnIds } =
- useKanban();
- const {
- setNodeRef,
- attributes,
- listeners,
- transform,
- transition,
- isDragging
- } = useSortable({
- id: item.id,
+export function JobCard(props: JobCardProps) {
+ const sortable = useSortable({
+ id: props.item.id,
data: {
type: "item",
- item
+ item: props.item
},
attributes: {
roleDescription: "item"
}
});
+ return <JobCardBody {...props} {...sortableCardProps(sortable)} />;
+}
+
+const JobCardBody = memo(function JobCardBody({
+ item,
+ locationId,
+ isOverlay,
+ progressByItemId,
+ setNodeRef,
+ attributes,
+ listeners,
+ transform,
+ transition,
+ isDragging
+}: JobCardProps & SortableCardProps) {
+ const { t } = useLingui();
+ const submit = useSubmit();
+ // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
+ const {
+ displaySettings,
+ selectedGroup,
+ setSelectedGroup,
+ columnIds,
+ scheduleToday
+ } = useKanban();
const isHighlighted = selectedGroup === item.jobReadableId;
- const style = {
- transition,
- transform: CSS.Translate.toString(transform)
- };
+ const style = { transition, transform };
const status = progressByItemId[item.id]?.active
? "In Progress"
@@ -146,7 +154,6 @@ export function JobCard({
const [customers] = useCustomers();
const customer = customers.find((s) => s.id === item.customerId);
- const scheduleToday = useScheduleToday();
const dueDate = getDateOnly(item.dueDate);
const isDueDateValid = Boolean(dueDate && isDateColumnId(dueDate));
const dueDateValue = isDueDateValid && dueDate ? dueDate : null;
@@ -445,4 +452,4 @@ export function JobCard({
</CardFooter>
</Card>
);
-}
+});
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/context/KanbanContext.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/context/KanbanContext.tsx
index 7ea50f431b..c56ecc9c07 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/context/KanbanContext.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/context/KanbanContext.tsx
@@ -2,9 +2,11 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+import { replaceEqualDeep } from "@tanstack/react-query";
import type { ReactNode } from "react";
-import { createContext, useContext } from "react";
+import { createContext, useContext, useMemo, useRef } from "react";
import type { DisplaySettings } from "../types";
+import { useScheduleToday } from "../useScheduleToday";
interface KanbanContextType {
displaySettings: DisplaySettings;
@@ -12,6 +14,8 @@ interface KanbanContextType {
setSelectedGroup: (jobId: string | null) => void;
tags: { name: string }[];
columnIds?: string[];
+ /** Today on the board's calendar; see `useScheduleToday`. */
+ scheduleToday: string;
}
const KanbanContext = createContext<KanbanContextType | null>(null);
@@ -33,21 +37,46 @@ export function KanbanProvider({
tags,
columnIds
}: KanbanProviderProps) {
+ // Every card reads this context, so its value must change only when its
+ // contents do. The board passes the display settings as a fresh object on
+ // every render, and a reload hands over a new `tags` array.
+ const stableSettings = useStable(displaySettings);
+ const stableTags = useStable(tags);
+ const stableColumnIds = useStable(columnIds);
+ // Read once for the board. In each card it subscribed the card to the
+ // router: every fetcher and revalidation state change re-rendered them all.
+ const scheduleToday = useScheduleToday();
+ const value = useMemo(
+ () => ({
+ displaySettings: stableSettings,
+ selectedGroup,
+ setSelectedGroup,
+ tags: stableTags,
+ columnIds: stableColumnIds,
+ scheduleToday
+ }),
+ [
+ stableSettings,
+ selectedGroup,
+ setSelectedGroup,
+ stableTags,
+ stableColumnIds,
+ scheduleToday
+ ]
+ );
+
return (
- <KanbanContext.Provider
- value={{
- displaySettings,
- selectedGroup,
- setSelectedGroup,
- tags,
- columnIds
- }}
- >
- {children}
- </KanbanContext.Provider>
+ <KanbanContext.Provider value={value}>{children}</KanbanContext.Provider>
);
}
+/** The previous value for as long as the new one is deeply equal to it. */
+function useStable<T>(value: T): T {
+ const ref = useRef(value);
+ ref.current = replaceEqualDeep(ref.current, value);
+ return ref.current;
+}
+
export function useKanban() {
const context = useContext(KanbanContext);
if (!context) {
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.tsx
index 08bd26f318..bdd06f90c5 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/drag-lifecycle.test.tsx
@@ -69,7 +69,9 @@ vi.mock("@carbon/logger", () => ({
vi.mock("@carbon/react", () => ({
ClientOnly: () => null,
cn: (...classes: unknown[]) => classes.filter(Boolean).join(" "),
- toast: { error: vi.fn() }
+ toast: { error: vi.fn() },
+ // The board's provider reads the dates route's timezone once for its cards.
+ useRouteData: () => undefined
}));
vi.mock("@lingui/react/macro", () => ({
useLingui: () => ({ t: () => "translated" })
diff --git a/apps/erp/app/modules/production/ui/Schedule/People/PeopleBoard.tsx b/apps/erp/app/modules/production/ui/Schedule/People/PeopleBoard.tsx
index 3d74e320a6..ad7475452b 100644
--- a/apps/erp/app/modules/production/ui/Schedule/People/PeopleBoard.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/People/PeopleBoard.tsx
@@ -40,6 +40,13 @@ import {
UNASSIGNED
} from "./peopleShared";
+// Module constants: a new options object makes a new sensor, and with it new
+// listeners for every draggable on every render.
+const POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 5 } };
+const KEYBOARD_SENSOR_OPTIONS = {
+ coordinateGetter: sortableKeyboardCoordinates
+};
+
export type {
PeopleAbsence,
PeopleAssignment,
@@ -139,8 +146,8 @@ const PeopleBoard = ({
const sensors = useSensors(
// under ~5px of travel is a tap (opens the editor), beyond it a drag
- useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
- useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
+ useSensor(PointerSensor, POINTER_SENSOR_OPTIONS),
+ useSensor(KeyboardSensor, KEYBOARD_SENSOR_OPTIONS)
);
const pendingMoves = usePendingMoves();
diff --git a/apps/erp/app/modules/production/ui/Schedule/People/PeopleWeekBoard.tsx b/apps/erp/app/modules/production/ui/Schedule/People/PeopleWeekBoard.tsx
index 9b0f7596ad..b8fc75d809 100644
--- a/apps/erp/app/modules/production/ui/Schedule/People/PeopleWeekBoard.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/People/PeopleWeekBoard.tsx
@@ -31,6 +31,12 @@ import { BoardContainer } from "../Kanban/components/ColumnCard";
import { hasDraggableData } from "../Kanban/utils";
import { assignmentMatchesShift } from "./peopleShared";
+// Module constants: a new options object makes a new sensor, and with it new
+// listeners for every draggable on every render.
+const KEYBOARD_SENSOR_OPTIONS = {
+ coordinateGetter: sortableKeyboardCoordinates
+};
+
const UNASSIGNED = "unassigned";
type WeekEmployee = {
@@ -277,7 +283,7 @@ const PeopleWeekBoard = ({
const sensors = useSensors(
useSensor(PointerSensor),
- useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
+ useSensor(KeyboardSensor, KEYBOARD_SENSOR_OPTIONS)
);
// shift-less rows resolve through the person's own shift, like the hours do
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/ReturnableReceiptLinesModal.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/ReturnableReceiptLinesModal.tsx
index 6161f231e3..68aa9a31ed 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/ReturnableReceiptLinesModal.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseReturnOrders/ReturnableReceiptLinesModal.tsx
@@ -2,6 +2,7 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+import { useRevalidator } from "@carbon/query";
import {
Badge,
Button,
@@ -28,7 +29,7 @@ import { INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useEffect, useState } from "react";
import { LuSearch } from "react-icons/lu";
-import { useFetcher, useParams, useRevalidator } from "react-router";
+import { useFetcher, useParams } from "react-router";
import type { loader as returnableLinesLoader } from "~/routes/x+/purchase-return-order+/returnable-lines";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsx b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsx
index aab0eec4b4..90272b8ced 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionDocuments.tsx
@@ -5,6 +5,7 @@
import { useCarbon } from "@carbon/auth";
import { convertKbToString, downloadUrl, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
+import { useRevalidator } from "@carbon/query";
import {
Card,
CardAction,
@@ -32,7 +33,7 @@ import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
import { LuEllipsisVertical, LuUpload } from "react-icons/lu";
-import { Outlet, useFetchers, useRevalidator, useSubmit } from "react-router";
+import { Outlet, useFetchers, useSubmit } from "react-router";
import { DateTime, DocumentPreview, FileDropzone } from "~/components";
import DocumentIcon from "~/components/DocumentIcon";
import { useFileUpload, usePermissions, useUser } from "~/hooks";
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineDocuments.tsx b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineDocuments.tsx
index 36b4ae4626..8aabe11777 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineDocuments.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierInteraction/SupplierInteractionLineDocuments.tsx
@@ -5,6 +5,7 @@
import { useCarbon } from "@carbon/auth";
import { convertKbToString, downloadUrl, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
+import { useRevalidator } from "@carbon/query";
import {
Card,
CardAction,
@@ -32,7 +33,7 @@ import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
import { LuEllipsisVertical, LuUpload } from "react-icons/lu";
-import { useFetchers, useRevalidator, useSubmit } from "react-router";
+import { useFetchers, useSubmit } from "react-router";
import { DateTime, DocumentPreview, FileDropzone } from "~/components";
import DocumentIcon from "~/components/DocumentIcon";
import { useFileUpload, usePermissions, useUser } from "~/hooks";
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteHeader.tsx b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteHeader.tsx
index 8abd76e6fe..dac3b1d0f9 100644
--- a/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteHeader.tsx
+++ b/apps/erp/app/modules/purchasing/ui/SupplierQuote/SupplierQuoteHeader.tsx
@@ -2,6 +2,7 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+import { useRevalidator } from "@carbon/query";
import {
Alert,
AlertDescription,
@@ -52,7 +53,7 @@ import {
LuTriangleAlert
} from "react-icons/lu";
import type { FetcherWithComponents } from "react-router";
-import { Link, useFetcher, useParams, useRevalidator } from "react-router";
+import { Link, useFetcher, useParams } from "react-router";
import { usePanels } from "~/components/Layout";
import ConfirmDelete from "~/components/Modals/ConfirmDelete";
import {
diff --git a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchNotes.tsx b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchNotes.tsx
index c3a22d0f76..ef9c0ee290 100644
--- a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchNotes.tsx
+++ b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchNotes.tsx
@@ -10,6 +10,7 @@ import {
storage
} from "@carbon/files";
import { getLogger } from "@carbon/logger";
+import { useRevalidator } from "@carbon/query";
import type { JSONContent } from "@carbon/react";
import {
Card,
@@ -41,7 +42,7 @@ import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
import { Suspense, useCallback, useState } from "react";
import { LuEllipsisVertical, LuUpload } from "react-icons/lu";
-import { Await, useRevalidator } from "react-router";
+import { Await } from "react-router";
import { DocumentPreview, FileDropzone } from "~/components";
import DocumentIcon from "~/components/DocumentIcon";
import {
diff --git a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx
index 7e45ca59ff..4d5c5e4415 100644
--- a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx
+++ b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityDocuments.tsx
@@ -5,6 +5,7 @@
import { useCarbon } from "@carbon/auth";
import { convertKbToString, downloadUrl, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
+import { useRevalidator } from "@carbon/query";
import {
Badge,
Card,
@@ -40,7 +41,7 @@ import {
LuShoppingCart,
LuUpload
} from "react-icons/lu";
-import { Outlet, useFetchers, useRevalidator, useSubmit } from "react-router";
+import { Outlet, useFetchers, useSubmit } from "react-router";
import { DateTime, DocumentPreview, FileDropzone } from "~/components";
import DocumentIcon from "~/components/DocumentIcon";
import { useFileUpload, usePermissions, useUser } from "~/hooks";
diff --git a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
index 29a744d87b..9f5744f364 100644
--- a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
+++ b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
@@ -5,6 +5,7 @@
import { useCarbon } from "@carbon/auth";
import { convertKbToString, downloadUrl, storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
+import { useRevalidator } from "@carbon/query";
import {
Card,
CardAction,
@@ -39,7 +40,7 @@ import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
import { LuEllipsisVertical, LuUpload } from "react-icons/lu";
-import { Link, useFetchers, useRevalidator, useSubmit } from "react-router";
+import { Link, useFetchers, useSubmit } from "react-router";
import {
DateTime,
DocumentPreview,
diff --git a/apps/erp/app/modules/sales/ui/SalesReturnOrders/ReturnableLinesModal.tsx b/apps/erp/app/modules/sales/ui/SalesReturnOrders/ReturnableLinesModal.tsx
index f53f92c67e..cf91eb2558 100644
--- a/apps/erp/app/modules/sales/ui/SalesReturnOrders/ReturnableLinesModal.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesReturnOrders/ReturnableLinesModal.tsx
@@ -2,6 +2,7 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+import { useRevalidator } from "@carbon/query";
import {
Button,
Checkbox,
@@ -27,7 +28,7 @@ import { INPUT_FORMAT, INPUT_STEP } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useEffect, useState } from "react";
import { LuSearch } from "react-icons/lu";
-import { useFetcher, useParams, useRevalidator } from "react-router";
+import { useFetcher, useParams } from "react-router";
import type { loader as returnableLinesLoader } from "~/routes/x+/sales-return-order+/returnable-lines";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx b/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx
index 18608999a3..865a5f7a1d 100644
--- a/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx
+++ b/apps/erp/app/modules/settings/ui/Backups/BackupProgressModal.tsx
@@ -2,6 +2,7 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+import { useRevalidator } from "@carbon/query";
import {
BarProgress,
Button,
@@ -15,7 +16,7 @@ import {
import { Trans } from "@lingui/react/macro";
import { useEffect, useState } from "react";
import { LuCheck, LuLoaderCircle, LuTriangleAlert } from "react-icons/lu";
-import { useFetcher, useRevalidator } from "react-router";
+import { useFetcher } from "react-router";
import { formatElapsed } from "./format";
// The job reports progress as a stable phase KEY + done/total; these order the
diff --git a/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx b/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx
index 413b0df95e..768ac75599 100644
--- a/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx
+++ b/apps/erp/app/modules/settings/ui/Backups/BackupSourcePicker.tsx
@@ -4,6 +4,7 @@
import { TEMP_STAGING_BUCKET } from "@carbon/files";
import { useControlField } from "@carbon/form";
+import { useRevalidator } from "@carbon/query";
import {
Command,
CommandEmpty,
@@ -26,7 +27,6 @@ import {
LuLoaderCircle,
LuUpload
} from "react-icons/lu";
-import { useRevalidator } from "react-router";
import { UploadProgress } from "~/components/UploadProgress";
import { uploadToSignedUrlWithProgress } from "~/utils/signed-upload";
import { formatBackupDate, formatBackupName } from "./format";
diff --git a/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx b/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx
index 0b9b6f3f2c..23a172f643 100644
--- a/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx
+++ b/apps/erp/app/modules/settings/ui/Integrations/SyncActivity.tsx
@@ -2,6 +2,7 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+import { useRevalidator } from "@carbon/query";
import {
Badge,
Button,
@@ -43,7 +44,7 @@ import {
LuSend,
LuTriangleAlert
} from "react-icons/lu";
-import { Link, useFetcher, useRevalidator } from "react-router";
+import { Link, useFetcher } from "react-router";
import { useDateFormatter, usePermissions, useUrlParams } from "~/hooks";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/modules/workflows/ui/Builder/config/forms/ConditionForm.tsx b/apps/erp/app/modules/workflows/ui/Builder/config/forms/ConditionForm.tsx
index 9e42c483c5..d94ba7f3b9 100644
--- a/apps/erp/app/modules/workflows/ui/Builder/config/forms/ConditionForm.tsx
+++ b/apps/erp/app/modules/workflows/ui/Builder/config/forms/ConditionForm.tsx
@@ -34,6 +34,10 @@ import { CombinatorToggle } from "../CombinatorToggle";
import { FormStack } from "../layout";
import type { NodeFormProps } from "./index";
+// Module constants: a new options object makes a new sensor, and with it new
+// listeners for every draggable on every render.
+const POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 8 } };
+
const newClause = (): Clause => ({
left: {
kind: "literal",
@@ -224,7 +228,7 @@ export function ConditionForm({
const context = { nodeId: node.id, inLoop: false };
const sensors = useSensors(
- useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
+ useSensor(PointerSensor, POINTER_SENSOR_OPTIONS),
useSensor(KeyboardSensor)
);
diff --git a/apps/erp/app/routes/share+/_layout.tsx b/apps/erp/app/routes/share+/_layout.tsx
index 4c48f4647c..aaf23dd219 100644
--- a/apps/erp/app/routes/share+/_layout.tsx
+++ b/apps/erp/app/routes/share+/_layout.tsx
@@ -2,6 +2,7 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+import { useRevalidator } from "@carbon/query";
import {
DropdownMenu,
DropdownMenuContent,
@@ -14,7 +15,7 @@ import {
} from "@carbon/react";
import { useLingui } from "@lingui/react/macro";
import { LuMoon, LuRefreshCw, LuSun } from "react-icons/lu";
-import { Outlet, useFetcher, useRevalidator } from "react-router";
+import { Outlet, useFetcher } from "react-router";
import type { action } from "~/root";
export default function ExternalLayout() {
diff --git a/apps/erp/app/routes/x+/account+/security.tsx b/apps/erp/app/routes/x+/account+/security.tsx
index aa50988233..70f18421c1 100644
--- a/apps/erp/app/routes/x+/account+/security.tsx
+++ b/apps/erp/app/routes/x+/account+/security.tsx
@@ -14,6 +14,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { TotpFactor } from "@carbon/auth/mfa.server";
import { getTotpFactors } from "@carbon/auth/mfa.server";
import { flash } from "@carbon/auth/session.server";
+import { useRevalidator } from "@carbon/query";
import {
Alert,
AlertDescription,
@@ -47,7 +48,7 @@ import {
LuTrash2
} from "react-icons/lu";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-import { data, useFetcher, useLoaderData, useRevalidator } from "react-router";
+import { data, useFetcher, useLoaderData } from "react-router";
import { DateTime } from "~/components";
import {
INVALID_CODE_MESSAGE,
diff --git a/apps/erp/app/routes/x+/assembly+/$id.tsx b/apps/erp/app/routes/x+/assembly+/$id.tsx
index e0098c5cbc..76415eb7ee 100644
--- a/apps/erp/app/routes/x+/assembly+/$id.tsx
+++ b/apps/erp/app/routes/x+/assembly+/$id.tsx
@@ -6,6 +6,7 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
+import { useRevalidator } from "@carbon/query";
import {
Button,
ClientOnly,
@@ -40,7 +41,6 @@ import {
useFetcher,
useLoaderData,
useParams,
- useRevalidator,
useSearchParams
} from "react-router";
import { Empty } from "~/components";
diff --git a/apps/erp/app/routes/x+/priority+/dates.tsx b/apps/erp/app/routes/x+/priority+/dates.tsx
index afa2ca0539..a967cda34f 100644
--- a/apps/erp/app/routes/x+/priority+/dates.tsx
+++ b/apps/erp/app/routes/x+/priority+/dates.tsx
@@ -39,6 +39,7 @@ import {
import { msg } from "@lingui/core/macro";
import { Trans, useLingui } from "@lingui/react/macro";
import { useLocale } from "@react-aria/i18n";
+import { replaceEqualDeep } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
import { LuChevronLeft, LuChevronRight, LuSettings2 } from "react-icons/lu";
import type {
@@ -582,8 +583,10 @@ function DateKanbanSchedule() {
defaultDisplaySettings
);
+ // A reload hands over new objects for every card. Keeping the ones that did
+ // not change lets their memoized cards skip the render.
useEffect(() => {
- setItems(initialItems);
+ setItems((previous) => replaceEqualDeep(previous, initialItems));
}, [initialItems]);
const sortItems = useCallback((items: JobItem[]) => {
diff --git a/apps/erp/app/routes/x+/priority+/operations.tsx b/apps/erp/app/routes/x+/priority+/operations.tsx
index b92dde5f13..4768262527 100644
--- a/apps/erp/app/routes/x+/priority+/operations.tsx
+++ b/apps/erp/app/routes/x+/priority+/operations.tsx
@@ -35,6 +35,7 @@ import {
} from "@internationalized/date";
import { msg } from "@lingui/core/macro";
import { Trans, useLingui } from "@lingui/react/macro";
+import { replaceEqualDeep } from "@tanstack/react-query";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
LuCirclePlus,
@@ -595,8 +596,10 @@ function KanbanSchedule() {
[displaySettings]
);
+ // A reload hands over new objects for every card. Keeping the ones that did
+ // not change lets their memoized cards skip the render.
useEffect(() => {
- setItems(initialItems);
+ setItems((previous) => replaceEqualDeep(previous, initialItems));
}, [initialItems]);
const sortItems = useCallback((items: Item[]) => {
diff --git a/apps/erp/app/routes/x+/priority+/operations.update.tsx b/apps/erp/app/routes/x+/priority+/operations.update.tsx
index 473ff626ab..2d6c5a5cfe 100644
--- a/apps/erp/app/routes/x+/priority+/operations.update.tsx
+++ b/apps/erp/app/routes/x+/priority+/operations.update.tsx
@@ -7,9 +7,12 @@ import { validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import {
isJobLocked,
+ scheduleOperationReorderValidator,
scheduleOperationUpdateValidator
} from "~/modules/production/production.models";
+import { reorderScheduleOperations } from "~/modules/production/production.server";
import { notifyScheduleInputsChanged } from "~/modules/production/production.service";
+import { getDatabaseClient } from "~/services/database.server";
const invalidSchedulingRequest = () => ({
success: false,
@@ -20,8 +23,49 @@ export async function action({ request }: ActionFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {
update: "production"
});
+ const formData = await request.formData();
+
+ // A drop that renumbers several cards of a column sends them all at once.
+ const updates = formData.get("updates");
+ if (typeof updates === "string") {
+ let rows: unknown;
+ try {
+ rows = JSON.parse(updates);
+ } catch {
+ return { success: false, message: "Invalid form data" };
+ }
+ const reorder = scheduleOperationReorderValidator.safeParse({
+ columnId: formData.get("columnId"),
+ updates: rows
+ });
+ if (!reorder.success) {
+ return { success: false, message: "Invalid form data" };
+ }
+ const result = await reorderScheduleOperations(
+ client,
+ getDatabaseClient(),
+ {
+ companyId,
+ userId,
+ ...reorder.data
+ }
+ );
+ if (!result.success) return result;
+ // Same rule as the single move below: only a work-center change
+ // reschedules.
+ if (result.workCenterChanged) {
+ await notifyScheduleInputsChanged(
+ companyId,
+ "work-center",
+ "Operation reassigned to a different work center",
+ reorder.data.columnId
+ );
+ }
+ return { success: true };
+ }
+
const validation = await validator(scheduleOperationUpdateValidator).validate(
- await request.formData()
+ formData
);
if (validation.error) {
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/update.tsx b/apps/erp/app/routes/x+/purchase-invoice+/update.tsx
index b1c8eb8801..f08fcdb399 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/update.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/update.tsx
@@ -74,10 +74,14 @@ export async function action({ request }: ActionFunctionArgs) {
}
}
+ // A supplier with no currency keeps the invoice's own. The contact and
+ // location belonged to the previous invoice supplier.
return await client
.from("purchaseInvoice")
.update({
- supplierId: value ?? undefined,
+ invoiceSupplierId: value ?? undefined,
+ invoiceSupplierContactId: null,
+ invoiceSupplierLocationId: null,
updatedBy: userId,
updatedAt: new Date().toISOString()
})
diff --git a/apps/erp/app/routes/x+/sales-invoice+/update.tsx b/apps/erp/app/routes/x+/sales-invoice+/update.tsx
index c9c875ae3c..fda0753a0a 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/update.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/update.tsx
@@ -73,10 +73,14 @@ export async function action({ request }: ActionFunctionArgs) {
}
}
+ // A customer with no currency keeps the invoice's own. The contact and
+ // location belonged to the previous invoice customer.
return await client
.from("salesInvoice")
.update({
- customerId: value ?? undefined,
+ invoiceCustomerId: value ?? undefined,
+ invoiceCustomerContactId: null,
+ invoiceCustomerLocationId: null,
updatedBy: userId,
updatedAt: new Date().toISOString()
})
diff --git a/apps/erp/app/routes/x+/settings+/backups.tsx b/apps/erp/app/routes/x+/settings+/backups.tsx
index 30b104a090..27844a3000 100644
--- a/apps/erp/app/routes/x+/settings+/backups.tsx
+++ b/apps/erp/app/routes/x+/settings+/backups.tsx
@@ -18,6 +18,7 @@ import {
validationError,
validator
} from "@carbon/form";
+import { useRevalidator } from "@carbon/query";
import {
Badge,
Button,
@@ -40,13 +41,7 @@ import { Plural, Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useEffect, useRef, useState } from "react";
import { LuLoaderCircle } from "react-icons/lu";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-import {
- data,
- useFetcher,
- useFetchers,
- useLoaderData,
- useRevalidator
-} from "react-router";
+import { data, useFetcher, useFetchers, useLoaderData } from "react-router";
import { z } from "zod";
import { DateTime } from "~/components";
import { Confirm } from "~/components/Modals";
diff --git a/apps/erp/app/routes/x+/settings+/demo-data.tsx b/apps/erp/app/routes/x+/settings+/demo-data.tsx
index 25184615dc..aa46af0706 100644
--- a/apps/erp/app/routes/x+/settings+/demo-data.tsx
+++ b/apps/erp/app/routes/x+/settings+/demo-data.tsx
@@ -7,12 +7,13 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { DATASETS, datasetKeys } from "@carbon/database/datasets";
+import { useRevalidator } from "@carbon/query";
import { Heading, toast, VStack } from "@carbon/react";
import { msg } from "@lingui/core/macro";
import { Trans } from "@lingui/react/macro";
import { useEffect, useMemo, useRef, useState } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-import { data, useFetcher, useLoaderData, useRevalidator } from "react-router";
+import { data, useFetcher, useLoaderData } from "react-router";
import type { CompanyTemplateRun } from "~/modules/settings";
import { getCompanyTemplateRun } from "~/modules/settings";
import { purgeCorruptedRows } from "~/modules/settings/backups.server";
diff --git a/apps/mes/app/components/ConsolePill.tsx b/apps/mes/app/components/ConsolePill.tsx
index ab8614452a..cb4f2424bf 100644
--- a/apps/mes/app/components/ConsolePill.tsx
+++ b/apps/mes/app/components/ConsolePill.tsx
@@ -4,10 +4,10 @@
"use client";
+import { useRevalidator } from "@carbon/query";
import { Avatar } from "@carbon/react";
import { useState } from "react";
import { LuChevronDown } from "react-icons/lu";
-import { useRevalidator } from "react-router";
import type { PinnedInUser } from "~/types";
import { PinInOverlay } from "./PinInOverlay";
diff --git a/apps/mes/app/components/Display/DisplayFrame.tsx b/apps/mes/app/components/Display/DisplayFrame.tsx
index abdddd8afa..c783a6d51b 100644
--- a/apps/mes/app/components/Display/DisplayFrame.tsx
+++ b/apps/mes/app/components/Display/DisplayFrame.tsx
@@ -2,10 +2,10 @@
// 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 { useRevalidator } from "@carbon/query";
import { cn, useInterval } from "@carbon/react";
import { Trans } from "@lingui/react/macro";
import { useEffect, useState } from "react";
-import { useRevalidator } from "react-router";
import type { DisplayStatus } from "~/utils/display";
/**
diff --git a/apps/mes/app/components/Kanban/Kanban.tsx b/apps/mes/app/components/Kanban/Kanban.tsx
index 80bdfbd643..4f4611aacd 100644
--- a/apps/mes/app/components/Kanban/Kanban.tsx
+++ b/apps/mes/app/components/Kanban/Kanban.tsx
@@ -25,6 +25,10 @@ import { BoardContainer, ColumnCard } from "./components/ColumnCard";
import type { Column, DisplaySettings, Item } from "./types";
import { coordinateGetter, hasDraggableData } from "./utils";
+// Module constants: a new options object makes a new sensor, and with it new
+// listeners for every draggable on every render.
+const KEYBOARD_SENSOR_OPTIONS = { coordinateGetter };
+
interface Progress {
totalDuration: number;
progress: number;
@@ -74,9 +78,7 @@ const Kanban = ({
const sensors = useSensors(
useSensor(MouseSensor),
useSensor(TouchSensor),
- useSensor(KeyboardSensor, {
- coordinateGetter
- })
+ useSensor(KeyboardSensor, KEYBOARD_SENSOR_OPTIONS)
);
const announcements: Announcements = {
diff --git a/crates/converter/examples/convert_file.rs b/crates/converter/examples/convert_file.rs
index 05c618f5d3..3f8a22ea73 100644
--- a/crates/converter/examples/convert_file.rs
+++ b/crates/converter/examples/convert_file.rs
@@ -3,18 +3,25 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
//! Convert a STEP file and write its graph.json. Usage:
-//! cargo run -p converter --example convert_file -- <in.step> <out.graph.json>
+//! cargo run -p converter --example convert_file -- <in.step> <out.graph.json> [angular] [out.glb]
+//!
+//! `angular` is the angular deflection in radians (default 0.5); with `out.glb`
+//! the mesh is written too, to compare detail levels by eye.
fn main() {
let args: Vec<String> = std::env::args().collect();
let step = &args[1];
let out = &args[2];
+ let ang = args.get(3).and_then(|a| a.parse().ok()).unwrap_or(0.5);
let text = std::fs::read_to_string(step).unwrap_or_default();
let t = std::time::Instant::now();
- let conv = converter::convert::convert_step(step, &text, 0.1, 0.5).expect("convert");
+ let conv = converter::convert::convert_step(step, &text, 0.1, ang).expect("convert");
std::fs::write(out, serde_json::to_vec(&conv.graph).unwrap()).unwrap();
+ if let Some(glb) = args.get(4) {
+ std::fs::write(glb, &conv.glb).unwrap();
+ }
eprintln!(
- "comps={} tris={} {:.1}s -> {out}",
+ "ang={ang} comps={} tris={} {:.1}s -> {out}",
conv.component_count,
conv.triangles,
t.elapsed().as_secs_f64()
diff --git a/docs/content/docs/building/webhooks.mdx b/docs/content/docs/building/webhooks.mdx
index 61408a2212..965448e2d8 100644
--- a/docs/content/docs/building/webhooks.mdx
+++ b/docs/content/docs/building/webhooks.mdx
@@ -57,7 +57,7 @@ Carbon tracks success and error counts and the latest timestamp for each outcome
Webhook delivery is asynchronous and normally occurs a few seconds after the database change.
-Delivery is **at least once**. If the endpoint does not return a success status, Carbon retries with exponential backoff before marking the change as failed. Design for these conditions:
+Delivery is **at least once**. If the endpoint does not return a success status within 30 seconds, Carbon retries with exponential backoff before marking the change as failed. Design for these conditions:
- **Handle duplicates.** A request can be retried after your service has processed it. De-duplicate on `eventId`, not `type` and `record.id`, because separate changes to the same record share the latter values.
- **Reconcile after outages.** After retries are exhausted, Carbon drops the change and increments the error count. Query the API when complete event processing is required.
diff --git a/packages/checks/src/conformance/no-inline-sensor-options.test.ts b/packages/checks/src/conformance/no-inline-sensor-options.test.ts
new file mode 100644
index 0000000000..1d6e621f16
--- /dev/null
+++ b/packages/checks/src/conformance/no-inline-sensor-options.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 { noInlineSensorOptions } from "./no-inline-sensor-options";
+
+const scan = (contents: string) =>
+ noInlineSensorOptions.scan(
+ "apps/erp/app/modules/production/ui/Schedule/Kanban/Kanban.tsx",
+ contents
+ );
+
+describe("noInlineSensorOptions", () => {
+ it("flags an inline options object, on one line or several", () => {
+ expect(
+ scan(
+ `const sensors = useSensors(\n useSensor(PointerSensor, { activationConstraint: { distance: 8 } })\n);\n`
+ )
+ ).toHaveLength(1);
+ const violations = scan(
+ `const sensors = useSensors(\n useSensor(MouseSensor),\n useSensor(KeyboardSensor, {\n coordinateGetter\n })\n);\n`
+ );
+ expect(violations).toHaveLength(1);
+ expect(violations[0]!.line).toBe(3);
+ });
+
+ it("accepts a sensor with no options or a module constant", () => {
+ expect(
+ scan(
+ `const sensors = useSensors(\n useSensor(MouseSensor),\n useSensor(KeyboardSensor, KEYBOARD_SENSOR_OPTIONS)\n);\n`
+ )
+ ).toEqual([]);
+ });
+});
diff --git a/packages/checks/src/conformance/no-inline-sensor-options.ts b/packages/checks/src/conformance/no-inline-sensor-options.ts
new file mode 100644
index 0000000000..d2c3615ea3
--- /dev/null
+++ b/packages/checks/src/conformance/no-inline-sensor-options.ts
@@ -0,0 +1,45 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { ConformanceCheck, Violation } from "../check";
+
+// dnd-kit's `useSensor(sensor, options)` memoizes on the options object. An
+// inline literal is a new object on every render, so the sensor is new, and
+// with it the listeners of every draggable under the context: a memoized card
+// then re-renders on each render of its board. On the schedule board that was
+// every card's full body each time the drop target changed, and a drag
+// stuttered (frames over 100 ms with 82 cards).
+const INLINE_OPTIONS = /^useSensor\(\s*\w+\s*,\s*\{/;
+
+export const noInlineSensorOptions: ConformanceCheck = {
+ id: "no-inline-sensor-options",
+ description:
+ "useSensor options must be a module constant, not an object literal created on every render",
+ provenance: {
+ deprecates: "useSensor(KeyboardSensor, { coordinateGetter })",
+ replacedBy:
+ "a module-level constant: useSensor(KeyboardSensor, KEYBOARD_SENSOR_OPTIONS)",
+ since: "2026-10-06"
+ },
+ scan(file: string, contents: string): Violation[] {
+ const violations: Violation[] = [];
+ const lines = contents.split("\n");
+ lines.forEach((text, index) => {
+ const at = text.search(/\buseSensor\(/);
+ if (at < 0) return;
+ // From the call onward, with the next lines: the options may start on
+ // one of them.
+ const call = `${text.slice(at)}\n${lines[index + 1] ?? ""}\n${lines[index + 2] ?? ""}`;
+ if (!INLINE_OPTIONS.test(call)) return;
+ violations.push({
+ file,
+ line: index + 1,
+ snippet: text.trim(),
+ message:
+ "Hoist the options to a module constant: an inline object makes a new sensor, and new listeners for every draggable, on every render"
+ });
+ });
+ return violations;
+ }
+};
diff --git a/packages/checks/src/conformance/no-raw-revalidator.test.ts b/packages/checks/src/conformance/no-raw-revalidator.test.ts
new file mode 100644
index 0000000000..7a2ff824bb
--- /dev/null
+++ b/packages/checks/src/conformance/no-raw-revalidator.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 { describe, expect, it } from "vitest";
+import { noRawRevalidator } from "./no-raw-revalidator";
+
+const scan = (
+ contents: string,
+ file = "apps/erp/app/components/Documents.tsx"
+) => noRawRevalidator.scan(file, contents);
+
+describe("noRawRevalidator", () => {
+ it("flags React Router's hook, alone or among other imports", () => {
+ expect(
+ scan(`import { useRevalidator } from "react-router";\n`)
+ ).toHaveLength(1);
+ const violations = scan(
+ `import { z } from "zod";\nimport {\n useFetcher,\n useRevalidator\n} from "react-router";\n`
+ );
+ expect(violations).toHaveLength(1);
+ expect(violations[0]!.line).toBe(2);
+ });
+
+ it("accepts the held one, and other react-router imports", () => {
+ expect(
+ scan(
+ `import { useRevalidator } from "@carbon/query";\nimport { useFetcher, useNavigate } from "react-router";\n`
+ )
+ ).toEqual([]);
+ });
+
+ it("lets the wrapper take React Router's", () => {
+ expect(
+ scan(
+ `import { useRevalidator as useRouterRevalidator } from "react-router";\n`,
+ "packages/query/src/useRevalidator.ts"
+ )
+ ).toEqual([]);
+ });
+});
diff --git a/packages/checks/src/conformance/no-raw-revalidator.ts b/packages/checks/src/conformance/no-raw-revalidator.ts
new file mode 100644
index 0000000000..934fbbccea
--- /dev/null
+++ b/packages/checks/src/conformance/no-raw-revalidator.ts
@@ -0,0 +1,43 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { ConformanceCheck, Violation } from "../check";
+
+// React Router's `revalidate()` during the navigation that follows a save
+// restarts that navigation without the submission. Every layout whose
+// `shouldRevalidate` skips a plain navigation then keeps its data from before
+// the save: a new quote line was missing from the quote's explorer until a
+// reload, because the save's own realtime broadcast revalidated mid-redirect.
+// `useRevalidator` from `@carbon/query` holds the call until the router is idle.
+const ROUTER_IMPORT =
+ /import\s*(?:type\s*)?\{([^}]*)\}\s*from\s*["']react-router["']/g;
+// The wrapper itself: the one place that takes React Router's.
+const DEFINITION = "packages/query/src/useRevalidator.ts";
+
+export const noRawRevalidator: ConformanceCheck = {
+ id: "no-raw-revalidator",
+ description:
+ "useRevalidator must come from @carbon/query, which holds a revalidation while a save is in flight",
+ provenance: {
+ deprecates: 'import { useRevalidator } from "react-router"',
+ replacedBy: 'import { useRevalidator } from "@carbon/query"',
+ since: "2026-10-06"
+ },
+ scan(file: string, contents: string): Violation[] {
+ if (file === DEFINITION) return [];
+ const violations: Violation[] = [];
+ for (const match of contents.matchAll(ROUTER_IMPORT)) {
+ if (!/\buseRevalidator\b/.test(match[1]!)) continue;
+ const line = contents.slice(0, match.index).split("\n").length;
+ violations.push({
+ file,
+ line,
+ snippet: contents.split("\n")[line - 1]?.trim() ?? "",
+ message:
+ 'Import `useRevalidator` from "@carbon/query": React Router\'s restarts the navigation after a save and the layouts skip their reload'
+ });
+ }
+ return violations;
+ }
+};
diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.ts
index 0c476c676d..64b3e22544 100644
--- a/packages/checks/src/run.ts
+++ b/packages/checks/src/run.ts
@@ -29,6 +29,7 @@ import {
SHARED_APP_DIRS
} from "./conformance/no-duplicated-app-file";
import { noInlineFractionDigits } from "./conformance/no-inline-fraction-digits";
+import { noInlineSensorOptions } from "./conformance/no-inline-sensor-options";
import { noIntegrationIdBranching } from "./conformance/no-integration-id-branching";
import { noInterpolatedErrorLog } from "./conformance/no-interpolated-error-log";
import { noLegacyRls } from "./conformance/no-legacy-rls";
@@ -39,6 +40,7 @@ import { noNumericPrecision } from "./conformance/no-numeric-precision";
import { noPostgresChanges } from "./conformance/no-postgres-changes";
import { noRawForwardedHeaders } from "./conformance/no-raw-forwarded-headers";
import { noRawRedirect } from "./conformance/no-raw-redirect";
+import { noRawRevalidator } from "./conformance/no-raw-revalidator";
import { noRawRounding } from "./conformance/no-raw-rounding";
import { noRequiredColumnWithoutDefault } from "./conformance/no-required-column-without-default";
import { noUnguardedSubmit } from "./conformance/no-unguarded-submit";
@@ -171,6 +173,10 @@ export function collectFindings(root: string = repoRoot()): Finding[] {
noInterpolatedErrorLog,
noRawRedirect
]),
+ ...scanAll(loadTypescriptFiles(root), [
+ noRawRevalidator,
+ noInlineSensorOptions
+ ]),
...scanAll(loadTypescriptFiles(root, ROUTE_ROOTS), [
indexRedirectBeforeLoaders
]),
diff --git a/packages/jobs/src/inngest/functions/events/webhook.ts b/packages/jobs/src/inngest/functions/events/webhook.ts
index e400605016..d0b36f3304 100644
--- a/packages/jobs/src/inngest/functions/events/webhook.ts
+++ b/packages/jobs/src/inngest/functions/events/webhook.ts
@@ -9,6 +9,8 @@ import { inngest } from "../../client.ts";
import { toWebhookBody, webhookPayloadSchema } from "./webhook-body.ts";
const RETRIES = 3;
+// A documented part of the webhook contract (docs: building/webhooks).
+const WEBHOOK_TIMEOUT_MS = 30_000;
export const webhookFunction = inngest.createFunction(
{
@@ -63,7 +65,8 @@ export const webhookFunction = inngest.createFunction(
headers: {
"Content-Type": "application/json",
...payload.config.headers
- }
+ },
+ timeout: WEBHOOK_TIMEOUT_MS
});
} catch (err) {
// Count one failure per event, not per attempt — otherwise retries
diff --git a/packages/jobs/src/inngest/functions/scheduled/company-cleanup.ts b/packages/jobs/src/inngest/functions/scheduled/company-cleanup.ts
index a7bc117ea5..00e82f218e 100644
--- a/packages/jobs/src/inngest/functions/scheduled/company-cleanup.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/company-cleanup.ts
@@ -18,6 +18,7 @@ import {
selectInactiveCompanies
} from "./inactive-companies";
import {
+ dropCompanyTables,
purgeCompany,
removeCompanyFiles,
removeCompanySecrets
@@ -212,8 +213,8 @@ type CleanupTarget = Pick<CompanyCandidate, "id" | "name" | "companyGroupId">;
/**
* Delete each company with everything it owns: its storage bucket and legacy
- * files first, then its rows and Vault secrets in one transaction, then its
- * search index and audit log tables. `stillDue` is asked before the files go and
+ * files first, then its rows, Vault secrets and its search index and audit log
+ * tables in one transaction. `stillDue` is asked before the files go and
* again inside the transaction, so a plan bought since the list was built stops
* the delete. A company that cannot be deleted is logged and skipped; the table
* catalog is read once for the whole list.
@@ -258,6 +259,7 @@ export async function deleteCompanies(
if (!(await stillDue(trx, company.id))) return false;
await purgeCompany(trx, catalog, company.id, { replica });
await removeCompanySecrets(trx, company.id);
+ await dropCompanyTables(trx, company.id);
return true;
});
if (!purged) {
@@ -271,20 +273,6 @@ export async function deleteCompanies(
continue;
}
- // Per-company tables, named after the company and so outside the catalog.
- for (const fn of [
- "drop_company_search_index",
- "drop_audit_log_table"
- ] as const) {
- const { error } = await serviceRole.rpc(fn, { p_company_id: company.id });
- if (error) {
- logger.error("Failed to run {fn} for a deleted company", {
- fn,
- ...company,
- error
- });
- }
- }
logger.info("Deleted company", company);
results.push({ id: company.id, deleted: true });
}
diff --git a/packages/jobs/src/inngest/functions/scheduled/dispatch.ts b/packages/jobs/src/inngest/functions/scheduled/dispatch.ts
index 5163854762..6c64d9a281 100644
--- a/packages/jobs/src/inngest/functions/scheduled/dispatch.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/dispatch.ts
@@ -3,8 +3,10 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { fetchAllFromTable } from "@carbon/database";
import { getLogger } from "@carbon/logger";
import { NotificationEvent } from "@carbon/notifications";
+import { pluckUnique } from "@carbon/utils";
import {
getDayOfWeek,
now,
@@ -16,6 +18,9 @@ import { inngest } from "../../client";
const log = getLogger("jobs", "dispatch");
+// Company ids per companySettings read: keeps the `in` filter inside a URL.
+const SETTINGS_CHUNK = 200;
+
// Day of week mapping (0 = Sunday, 1 = Monday, etc.)
const dayOfWeekFields = [
"sunday",
@@ -393,68 +398,76 @@ export const dispatchFunction = inngest.createFunction(
});
try {
- // Generate for every company; the schedule query below is the real
- // gate (only active schedules that are due within the advance window).
- const { data: companiesWithSettings, error: settingsError } =
- await serviceRole
- .from("companySettings")
- .select("id, maintenanceDispatchNotificationGroup");
+ // Every active schedule that is already due (or never generated), in
+ // one paged read across companies. Generation is catch-up only, so
+ // future-dated schedules are skipped. Paged because max_rows would
+ // silently truncate the list.
+ const dueSchedules = await fetchAllFromTable<
+ MaintenanceSchedule & { companyId: string }
+ >(serviceRole, "maintenanceSchedule", "*", (query) =>
+ query
+ .eq("active", true)
+ .or(
+ `nextDueAt.is.null,nextDueAt.lte.${currentDateTime.toAbsoluteString()}`
+ )
+ .order("id")
+ );
- if (settingsError) {
- logger.error("Failed to fetch company settings", {
- error: settingsError
+ if (dueSchedules.error) {
+ logger.error("Failed to fetch due schedules", {
+ error: dueSchedules.error
});
- return;
+ // Throwing, not returning: a return is a step that succeeds having
+ // generated nothing, and never spends the configured retries.
+ throw dueSchedules.error;
}
- logger.info("Found companies", {
- count: companiesWithSettings?.length || 0
+ const schedules = dueSchedules.data ?? [];
+ const companyIds = pluckUnique(schedules, (s) => s.companyId);
+
+ logger.info("Schedules due", {
+ schedules: schedules.length,
+ companies: companyIds.length
});
- let totalDispatchesCreated = 0;
+ const notificationGroupByCompany = new Map<string, string[]>();
+ for (let i = 0; i < companyIds.length; i += SETTINGS_CHUNK) {
+ const { data: settings, error: settingsError } = await serviceRole
+ .from("companySettings")
+ .select("id, maintenanceDispatchNotificationGroup")
+ .in("id", companyIds.slice(i, i + SETTINGS_CHUNK));
- for (const settings of companiesWithSettings ?? []) {
- // Active schedules that are already due (or never generated).
- // Generation is catch-up only, so future-dated schedules are skipped.
- const { data: dueSchedules, error: schedulesError } =
- await serviceRole
- .from("maintenanceSchedule")
- .select("*")
- .eq("companyId", settings.id)
- .eq("active", true)
- .or(
- `nextDueAt.is.null,nextDueAt.lte.${currentDateTime.toAbsoluteString()}`
- );
-
- if (schedulesError) {
- logger.error("Failed to fetch schedules for company", {
- companyId: settings.id,
- error: schedulesError
+ if (settingsError) {
+ logger.error("Failed to fetch company settings", {
+ error: settingsError
});
- continue;
+ throw settingsError;
}
+ for (const row of settings ?? []) {
+ notificationGroupByCompany.set(
+ row.id,
+ row.maintenanceDispatchNotificationGroup ?? []
+ );
+ }
+ }
- logger.info("Schedules due for company", {
- companyId: settings.id,
- count: dueSchedules?.length || 0
- });
+ let totalDispatchesCreated = 0;
- for (const schedule of dueSchedules ?? []) {
- try {
- totalDispatchesCreated += await generateDispatchesForSchedule({
- serviceRole,
- schedule: schedule as MaintenanceSchedule,
- companyId: settings.id,
- currentDateTime,
- notificationGroup:
- settings.maintenanceDispatchNotificationGroup ?? []
- });
- } catch (err) {
- logger.error("Error processing schedule", {
- scheduleId: schedule.id,
- error: err
- });
- }
+ for (const schedule of schedules) {
+ try {
+ totalDispatchesCreated += await generateDispatchesForSchedule({
+ serviceRole,
+ schedule,
+ companyId: schedule.companyId,
+ currentDateTime,
+ notificationGroup:
+ notificationGroupByCompany.get(schedule.companyId) ?? []
+ });
+ } catch (err) {
+ logger.error("Error processing schedule", {
+ scheduleId: schedule.id,
+ error: err
+ });
}
}
diff --git a/packages/jobs/src/inngest/functions/scheduled/purge-company.integration.test.ts b/packages/jobs/src/inngest/functions/scheduled/purge-company.integration.test.ts
index 3612003398..69961494ed 100644
--- a/packages/jobs/src/inngest/functions/scheduled/purge-company.integration.test.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/purge-company.integration.test.ts
@@ -10,7 +10,11 @@ import {
canSetReplicationRole,
getCompanyTableCatalog
} from "../tasks/company-backup";
-import { purgeCompany } from "./purge-company";
+import {
+ dropCompanyTables,
+ dropOrphanCompanyTables,
+ purgeCompany
+} from "./purge-company";
const runDatabaseTests = process.env.RUN_PURGE_DB_TESTS === "true";
@@ -88,6 +92,13 @@ describe.skipIf(!runDatabaseTests)("purgeCompany (Postgres)", () => {
.execute();
expect(left).toEqual([]);
+ await dropCompanyTables(trx, companyId);
+ const tables = await sql<{ search: string | null }>`
+ SELECT to_regclass(${`public."searchIndex_${companyId}"`})::text AS search`.execute(
+ trx
+ );
+ expect(tables.rows[0]!.search).toBeNull();
+
const after = await danglingForeignKeys(trx);
const added = [...after].filter(
([key, n]) => n > (before.get(key) ?? 0)
@@ -97,4 +108,35 @@ describe.skipIf(!runDatabaseTests)("purgeCompany (Postgres)", () => {
})
).rejects.toBeInstanceOf(Rollback);
}, 300_000);
+
+ it("drops a company table whose company is gone, and no other", async () => {
+ const db = getJobDatabaseClient();
+ await expect(
+ db.transaction().execute(async (trx) => {
+ await sql`CREATE TABLE public."searchIndex_purgetestorphan0000000" (id text)`.execute(
+ trx
+ );
+ // Shares the prefix, but the rest is not a company id: never dropped.
+ await sql`CREATE TABLE public."searchIndex_staging" (id text)`.execute(
+ trx
+ );
+ const live = await sql<{ name: string }>`
+ SELECT 'searchIndex_' || id AS name FROM "company"`.execute(trx);
+
+ const dropped = await dropOrphanCompanyTables(trx, 10_000);
+
+ expect(dropped).toContain("searchIndex_purgetestorphan0000000");
+ expect(dropped).not.toContain("searchIndex_staging");
+ for (const { name } of live.rows) expect(dropped).not.toContain(name);
+ const left = await sql<{ n: number }>`
+ SELECT count(*)::int AS n FROM pg_class c
+ JOIN pg_namespace ns ON ns.oid = c.relnamespace
+ WHERE ns.nspname = 'public' AND c.relname = ANY(${dropped})`.execute(
+ trx
+ );
+ expect(left.rows[0]!.n).toBe(0);
+ throw new Rollback();
+ })
+ ).rejects.toBeInstanceOf(Rollback);
+ }, 300_000);
});
diff --git a/packages/jobs/src/inngest/functions/scheduled/purge-company.ts b/packages/jobs/src/inngest/functions/scheduled/purge-company.ts
index ee048c98c3..0762c573ab 100644
--- a/packages/jobs/src/inngest/functions/scheduled/purge-company.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/purge-company.ts
@@ -102,6 +102,61 @@ export async function removeCompanySecrets(
);
}
+// Tables named after a company (`searchIndex_<id>`, `auditLog_<id>`), which the
+// table catalog cannot list.
+const COMPANY_TABLE_PREFIXES = ["searchIndex_", "auditLog_"] as const;
+
+/**
+ * A company's own tables. Run inside the purge transaction, so they go with
+ * the rows or not at all. Dropped over the direct connection because it owns
+ * them: the service role does not, and its `drop_company_search_index` call
+ * was refused for every purged company, leaving the table behind.
+ */
+export async function dropCompanyTables(
+ trx: Kysely<KyselyDatabase>,
+ companyId: string
+): Promise<void> {
+ for (const prefix of COMPANY_TABLE_PREFIXES) {
+ await sql`DROP TABLE IF EXISTS ${sql.id("public", prefix + companyId)} CASCADE`.execute(
+ trx
+ );
+ }
+}
+
+/**
+ * Drop company tables whose company no longer exists, and return their names.
+ * One statement per table, so each drop takes and releases its own locks.
+ */
+export async function dropOrphanCompanyTables(
+ db: Kysely<KyselyDatabase>,
+ limit: number
+): Promise<string[]> {
+ // starts_with, not LIKE: `_` is a LIKE wildcard. The rest of the name must
+ // look like a company id (xid or base58), so a table that only shares the
+ // prefix is never dropped.
+ const { rows } = await sql<{ name: string }>`
+ SELECT c.relname AS name
+ FROM pg_class c
+ JOIN pg_namespace n ON n.oid = c.relnamespace
+ JOIN unnest(${[...COMPANY_TABLE_PREFIXES]}::text[]) AS p(prefix)
+ ON starts_with(c.relname, p.prefix)
+ WHERE n.nspname = 'public'
+ AND c.relkind = 'r'
+ AND substr(c.relname, length(p.prefix) + 1) ~ '^[A-Za-z0-9]{20,}$'
+ AND NOT EXISTS (
+ SELECT 1 FROM "company" co WHERE p.prefix || co.id = c.relname
+ )
+ ORDER BY c.relname
+ LIMIT ${limit}`.execute(db);
+
+ for (const { name } of rows) {
+ await sql`DROP TABLE IF EXISTS ${sql.id("public", name)} CASCADE`.execute(
+ db
+ );
+ }
+ return rows.map((row) => row.name);
+}
+
/**
* A company's files: its own storage bucket, and pre-bucket-migration files
* under `<companyId>/` in the shared private bucket. Returns the failures; each
diff --git a/packages/jobs/src/inngest/functions/scheduled/weekly.ts b/packages/jobs/src/inngest/functions/scheduled/weekly.ts
index b5a204a175..a6ce92359c 100644
--- a/packages/jobs/src/inngest/functions/scheduled/weekly.ts
+++ b/packages/jobs/src/inngest/functions/scheduled/weekly.ts
@@ -18,6 +18,7 @@ import {
import { chunkArray, datetime, Edition, formatDate } from "@carbon/utils";
import { render } from "@react-email/components";
import type { Kysely } from "kysely";
+import { getJobDatabaseClient } from "../../../db";
import { inngest } from "../../client";
import {
deleteCompanies,
@@ -31,6 +32,7 @@ import {
splitByWarning,
type Warning
} from "./inactive-companies";
+import { dropOrphanCompanyTables } from "./purge-company";
/**
* Keeps a backlog under Inngest's per-run step limit (ten companies a step, for
@@ -319,6 +321,21 @@ export const weeklyFunction = inngest.createFunction(
}
}
+ // Tables left by purges whose table drop was refused. Bounded per run:
+ // every drop makes PostgREST reload its schema cache.
+ try {
+ const dropped = await step.run("drop-orphan-company-tables", () =>
+ dropOrphanCompanyTables(getJobDatabaseClient(), 200)
+ );
+ if (dropped.length > 0) {
+ logger.info("Dropped orphan company tables", {
+ count: dropped.length
+ });
+ }
+ } catch (error) {
+ logger.error("Failed to drop orphan company tables", { error });
+ }
+
// Build inside a memoized step, send via step.sendEvent — sending
// mid-step would double-deliver on a retry after a partial send.
const reminders = await step.run("build-training-reminders", async () => {
diff --git a/packages/planning/src/scheduling/master-data-provider.ts b/packages/planning/src/scheduling/master-data-provider.ts
index 1aea22d943..fa57cf48f8 100644
--- a/packages/planning/src/scheduling/master-data-provider.ts
+++ b/packages/planning/src/scheduling/master-data-provider.ts
@@ -31,6 +31,11 @@ import {
resolveWorkCenterWindows,
type WorkCenterAvailabilityInput
} from "./machine-availability.ts";
+import {
+ type JobWrites,
+ mergeCrossJobOperations,
+ visibleReservations
+} from "./run-overlay.ts";
import {
type BaseOperation,
capacityHoldingJobStatuses,
@@ -51,6 +56,7 @@ const peopleDateUpperBound = (instant: number, timeZone: string) =>
parseDate(businessDayFromMs(instant, timeZone)).add({ days: 1 }).toString();
export type JobMaterialWithMakeMethod = {
+ id: string | null;
jobMaterialMakeMethodId: string | null;
jobOperationId: string | null;
};
@@ -254,12 +260,29 @@ function toJob<
type Row<T extends keyof DB> = Selectable<DB[T]>;
+/**
+ * What the jobs of a location run have computed so far. Nothing is written
+ * until the run ends, so a later job reads the earlier jobs' results here.
+ */
+type RunOverlay = {
+ now: number;
+ /** Rows no job of the run rewrites: other jobs' and batch-tagged ones. */
+ fixedReservations: LiveReservation[];
+ /** Per job of the run: its stored rows, then its new ones once it has run. */
+ reservationsByJob: Map<string, LiveReservation[]>;
+ storedOperationsByWorkCenter: Map<string, CrossJobOperation[]>;
+ placedOperations: Map<string, CrossJobOperation>;
+};
+
type JobPreload = {
jobIds: Set<string>;
jobs: Map<string, Job>;
operations: Record<string, Row<"jobOperation">[]>;
dependencies: Record<string, Row<"jobOperationDependency">[]>;
- unlinked: Record<string, { id: string; jobMakeMethodId: string }[]>;
+ unlinked: Record<
+ string,
+ { id: string; jobMakeMethodId: string; methodType: string }[]
+ >;
materials: Row<"jobMaterialWithMakeMethodId">[];
jobIdByMakeMethodId: Map<string, string>;
rootByJobId: Map<string, { id: string; itemId: string | null }>;
@@ -283,13 +306,18 @@ export class KyselyMasterDataProvider implements MasterDataProvider {
* Batch mode: when several jobs are scheduled in one invocation, the
* company's STATIC master data (processes, work centers, qualifications,
* shift windows, dispatch policies) is identical for every job — cache it
- * on first read instead of re-querying per job. Live reservations are
- * NEVER cached: they must stay DB-fresh so each job in the batch sees the
- * previous jobs' just-persisted placements. Job-scoped rows (operations,
+ * on first read instead of re-querying per job. Job-scoped rows (operations,
* dependencies, method trees) are read once for the batch by `preloadJobs`.
+ * Live reservations and other jobs' operations change as the batch runs:
+ * `beginRun` reads them once and `recordJob` keeps them current.
*/
private companyCache: Map<string, Promise<unknown>> | null = null;
private preload: JobPreload | null = null;
+ private run: RunOverlay | null = null;
+ private processRequirements = new Map<
+ string,
+ Promise<ProcessRequirementRow[]>
+ >();
constructor(
db: Kysely<DB>,
@@ -318,9 +346,9 @@ export class KyselyMasterDataProvider implements MasterDataProvider {
/**
* Read every job-scoped row the engine needs for these jobs in one query per
* table, so a location run does not repeat ~15 reads per job. Call it after
- * anything that writes those rows for the batch (the batch pre-pass). Each
- * job's rows are served to that job's own engine, which reads them before it
- * writes any of them; reads that follow a write stay live.
+ * anything that writes those rows for the batch (the batch pre-pass). The
+ * engine writes nothing while the batch runs, so the rows stay the stored
+ * state for the whole run.
*/
async preloadJobs(jobIds: string[]): Promise<void> {
if (jobIds.length === 0) return;
@@ -348,7 +376,7 @@ export class KyselyMasterDataProvider implements MasterDataProvider {
.execute(),
this.db
.selectFrom("jobMaterial")
- .select(["id", "jobMakeMethodId", "jobId"])
+ .select(["id", "jobMakeMethodId", "jobId", "methodType"])
.where("jobId", "in", jobIds)
.where("companyId", "=", this.companyId)
.where("jobOperationId", "is", null)
@@ -513,7 +541,7 @@ export class KyselyMasterDataProvider implements MasterDataProvider {
return [];
}
- if (this.materialsAreLinked(makeMethodIds)) {
+ if (this.arePreloaded(makeMethodIds)) {
const ids = new Set(makeMethodIds);
return this.preload!.materials.filter(
(m) => m.jobMakeMethodId && ids.has(m.jobMakeMethodId)
@@ -534,7 +562,14 @@ export class KyselyMasterDataProvider implements MasterDataProvider {
return [];
}
- if (this.materialsAreLinked(makeMethodIds)) return [];
+ if (this.arePreloaded(makeMethodIds)) {
+ const ids = new Set(makeMethodIds);
+ return Object.values(this.preload!.unlinked)
+ .flat()
+ .filter(
+ (m) => m.methodType === "Make to Order" && ids.has(m.jobMakeMethodId)
+ );
+ }
return await this.db
.selectFrom("jobMaterial")
@@ -546,17 +581,14 @@ export class KyselyMasterDataProvider implements MasterDataProvider {
}
/**
- * True when these make methods belong to preloaded jobs that had every
- * material on an operation. A run only ever links unlinked materials, so
- * for such a job the preloaded material rows are still what is stored.
+ * True when these ids come from a preloaded job's method tree. The tree
+ * also carries the ids of its bought materials, which are no make method's
+ * id and match no row, so one known make method is enough to tell.
*/
- private materialsAreLinked(makeMethodIds: string[]): boolean {
+ private arePreloaded(makeMethodIds: string[]): boolean {
const preload = this.preload;
if (!preload) return false;
- return makeMethodIds.every((id) => {
- const jobId = preload.jobIdByMakeMethodId.get(id);
- return jobId !== undefined && !preload.unlinked[jobId]?.length;
- });
+ return makeMethodIds.some((id) => preload.jobIdByMakeMethodId.has(id));
}
async getUnlinkedMaterials(jobId: string): Promise<UnlinkedMaterial[]> {
@@ -672,6 +704,33 @@ export class KyselyMasterDataProvider implements MasterDataProvider {
return [];
}
+ const run = this.run;
+ if (!run) return this.readCrossJobOperations(workCenterIds);
+
+ const missing = workCenterIds.filter(
+ (id) => !run.storedOperationsByWorkCenter.has(id)
+ );
+ if (missing.length > 0) {
+ const rows = groupBy(
+ await this.readCrossJobOperations(missing),
+ (op) => op.workCenterId as string
+ );
+ for (const id of missing) {
+ run.storedOperationsByWorkCenter.set(id, rows[id] ?? []);
+ }
+ }
+ return mergeCrossJobOperations(
+ workCenterIds.flatMap(
+ (id) => run.storedOperationsByWorkCenter.get(id) ?? []
+ ),
+ run.placedOperations,
+ workCenterIds
+ );
+ }
+
+ private async readCrossJobOperations(
+ workCenterIds: string[]
+ ): Promise<CrossJobOperation[]> {
return await this.db
.selectFrom("jobOperation as jo")
.innerJoin("job as j", "j.id", "jo.jobId")
@@ -706,6 +765,97 @@ export class KyselyMasterDataProvider implements MasterDataProvider {
async getLiveReservations(
fromDate: number,
excludeJobIds: string[]
+ ): Promise<LiveReservation[]> {
+ const run = this.run;
+ if (!run || run.now !== fromDate) {
+ return this.readLiveReservations(fromDate, excludeJobIds);
+ }
+ const excluded = new Set(excludeJobIds);
+ const rows = [...run.fixedReservations];
+ for (const [jobId, reservations] of run.reservationsByJob) {
+ if (!excluded.has(jobId)) rows.push(...reservations);
+ }
+ return rows;
+ }
+
+ /**
+ * Start a location run over these jobs: read the live reservations once.
+ * Call it after the batch pre-pass, which rewrites the batch-tagged rows.
+ */
+ async beginRun(jobIds: string[], now: number): Promise<void> {
+ const batch = new Set(jobIds);
+ const fixedReservations: LiveReservation[] = [];
+ const reservationsByJob = new Map<string, LiveReservation[]>();
+ for (const row of await this.readLiveReservations(now, [])) {
+ // The same split as the read's excludeJobIds filter: a batch-tagged row
+ // is never excluded.
+ if (row.jobOperationBatchId !== null || !batch.has(row.jobId)) {
+ fixedReservations.push(row);
+ continue;
+ }
+ const rows = reservationsByJob.get(row.jobId);
+ if (rows) rows.push(row);
+ else reservationsByJob.set(row.jobId, [row]);
+ }
+ this.run = {
+ now,
+ fixedReservations,
+ reservationsByJob,
+ storedOperationsByWorkCenter: new Map(),
+ placedOperations: new Map()
+ };
+ }
+
+ /** Make a job's result visible to the jobs that run after it. */
+ recordJob(writes: JobWrites): void {
+ const run = this.run;
+ const job = this.preload?.jobs.get(writes.jobId);
+ if (!run || !job) return;
+
+ run.reservationsByJob.set(
+ writes.jobId,
+ visibleReservations(writes, job.readableJobId ?? "", run.now)
+ );
+
+ // Terminal jobs never compete in dispatch order (the stored read's filter).
+ if (["Cancelled", "Completed", "Closed"].includes(job.status ?? "")) return;
+ const stored = new Map(
+ (this.preload?.operations[writes.jobId] ?? []).map((o) => [o.id, o])
+ );
+ for (const { id, placement } of writes.placements) {
+ const op = stored.get(id);
+ if (!op) continue;
+ run.placedOperations.set(id, {
+ id,
+ dueDate:
+ placement.dueDate !== undefined
+ ? (placement.dueDate as string | null)
+ : (op.dueDate as string | null),
+ startDate: placement.startDate as string | null,
+ priority:
+ placement.priority !== undefined
+ ? (placement.priority as number)
+ : op.priority,
+ deadlineType: job.deadlineType ?? null,
+ jobPriority: job.priority ?? null,
+ workCenterId: placement.workCenterId as string | null,
+ createdAt: op.createdAt,
+ projectedCompletionAt: placement.projectedCompletionAt as string | null,
+ setupTime: op.setupTime,
+ setupUnit: op.setupUnit,
+ laborTime: op.laborTime,
+ laborUnit: op.laborUnit,
+ machineTime: op.machineTime,
+ machineUnit: op.machineUnit,
+ operationQuantity: op.operationQuantity,
+ operationLeadTime: op.operationLeadTime
+ });
+ }
+ }
+
+ private async readLiveReservations(
+ fromDate: number,
+ excludeJobIds: string[]
): Promise<LiveReservation[]> {
let query = this.db
.selectFrom("capacityReservation as cr")
@@ -833,10 +983,25 @@ export class KyselyMasterDataProvider implements MasterDataProvider {
async getProcessRequirements(
processIds: string[]
): Promise<ProcessRequirementRow[]> {
- return this.cached(
- `processRequirements:${[...processIds].sort().join(",")}`,
- () => this.loadProcessRequirements(processIds)
+ if (!this.companyCache) return this.loadProcessRequirements(processIds);
+
+ // Cached per process, so two jobs sharing a process share its read.
+ const missing = processIds.filter(
+ (id) => !this.processRequirements.has(id)
+ );
+ if (missing.length > 0) {
+ const loaded = this.loadProcessRequirements(missing);
+ for (const id of missing) {
+ this.processRequirements.set(
+ id,
+ loaded.then((rows) => rows.filter((r) => r.processId === id))
+ );
+ }
+ }
+ const rows = await Promise.all(
+ processIds.map((id) => this.processRequirements.get(id)!)
);
+ return rows.flat();
}
private async loadProcessRequirements(
diff --git a/packages/planning/src/scheduling/material-manager.ts b/packages/planning/src/scheduling/material-manager.ts
index a88c9c9711..eca2a48723 100644
--- a/packages/planning/src/scheduling/material-manager.ts
+++ b/packages/planning/src/scheduling/material-manager.ts
@@ -2,21 +2,17 @@
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-import type { DB } from "@carbon/database/client";
-import type { Kysely } from "kysely";
import type { MasterDataProvider } from "./master-data-provider.ts";
import type { BaseOperation } from "./types.ts";
class MaterialManager {
- private db: Kysely<DB>;
private provider: MasterDataProvider;
private materialsWithoutOperations: {
id: string;
jobMakeMethodId: string;
}[] = [];
- constructor(db: Kysely<DB>, provider: MasterDataProvider) {
- this.db = db;
+ constructor(provider: MasterDataProvider) {
this.provider = provider;
this.materialsWithoutOperations = [];
}
@@ -38,16 +34,16 @@ class MaterialManager {
}, []);
}
- async assignOperationsToMaterials(
+ /** Each unlinked material, paired with the first operation of its method. */
+ assignOperationsToMaterials(
validMaterialIds: string[],
operationsByJobMakeMethodId: Record<string, BaseOperation[]>
- ) {
+ ): { materialId: string; operationId: string }[] {
+ const valid = new Set(validMaterialIds);
const updates: { materialId: string; operationId: string }[] = [];
- for await (const material of this.materialsWithoutOperations) {
- if (!validMaterialIds.includes(material.id)) {
- continue;
- }
+ for (const material of this.materialsWithoutOperations) {
+ if (!valid.has(material.id)) continue;
const operations =
operationsByJobMakeMethodId[material.jobMakeMethodId] || [];
@@ -61,17 +57,7 @@ class MaterialManager {
}
}
- if (updates.length > 0) {
- for await (const update of updates) {
- await this.db
- .updateTable("jobMaterial")
- .set({
- jobOperationId: update.operationId
- })
- .where("id", "=", update.materialId)
- .execute();
- }
- }
+ return updates;
}
getMaterialIds(): string[] {
diff --git a/packages/planning/src/scheduling/persist-location.ts b/packages/planning/src/scheduling/persist-location.ts
new file mode 100644
index 0000000000..8a51de27dc
--- /dev/null
+++ b/packages/planning/src/scheduling/persist-location.ts
@@ -0,0 +1,227 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { DB } from "@carbon/database/client";
+import { datetime } from "@carbon/utils";
+import { type Kysely, sql, type Transaction } from "kysely";
+import { msToInstantIso } from "./date-utils.ts";
+import {
+ type JobWrites,
+ PLACEMENT_CASTS,
+ type PlacementColumn,
+ type PlacementWrite
+} from "./run-overlay.ts";
+
+const PLACEMENT_COLUMNS = Object.keys(PLACEMENT_CASTS) as PlacementColumn[];
+
+// Postgres takes at most 65,535 parameters per statement.
+const CHUNK = 1000;
+
+function chunks<T>(rows: T[]): T[][] {
+ const out: T[][] = [];
+ for (let i = 0; i < rows.length; i += CHUNK) {
+ out.push(rows.slice(i, i + CHUNK));
+ }
+ return out;
+}
+
+/**
+ * Write the placements of operations that all set the same columns, in one
+ * statement. Every UPDATE is queued for the audit/search handlers, so a row
+ * whose placement is unchanged is not written at all.
+ */
+async function updatePlacements(
+ trx: Transaction<DB>,
+ rows: { id: string; placement: PlacementWrite }[],
+ companyId: string,
+ userId: string
+) {
+ const columns = PLACEMENT_COLUMNS.filter(
+ (column) => rows[0]!.placement[column] !== undefined
+ );
+ const value = (column: PlacementColumn) =>
+ sql`v.${sql.ref(column)}::${sql.raw(PLACEMENT_CASTS[column])}`;
+
+ await sql`
+ update "jobOperation" as o
+ set ${sql.join([
+ ...columns.map((c) => sql`${sql.ref(c)} = ${value(c)}`),
+ sql`"updatedAt" = ${datetime.timestamp()}`,
+ sql`"updatedBy" = ${userId}`
+ ])}
+ from (values ${sql.join(
+ rows.map(
+ (row) =>
+ sql`(${sql.join([row.id, ...columns.map((c) => row.placement[c])])})`
+ )
+ )}) as v(${sql.join(["id", ...columns].map((c) => sql.ref(c)))})
+ where o."id" = v."id"
+ and o."companyId" = ${companyId}
+ and ${
+ columns.length === 0
+ ? sql`true`
+ : sql`(${sql.join(
+ columns.map(
+ (c) => sql`o.${sql.ref(c)} is distinct from ${value(c)}`
+ ),
+ sql` or `
+ )})`
+ }
+ `.execute(trx);
+}
+
+/**
+ * Write a whole location run in ONE transaction: a partial write (one job's
+ * reservations deleted but not re-inserted, or half the jobs on the new plan)
+ * would free or double-book capacity for the next run.
+ */
+export async function persistLocationWrites(
+ db: Kysely<DB>,
+ writes: JobWrites[],
+ scope: { companyId: string; userId: string }
+): Promise<void> {
+ if (writes.length === 0) return;
+ const { companyId, userId } = scope;
+
+ await db.transaction().execute(async (trx) => {
+ const links = writes.flatMap((w) => w.materialLinks);
+ for (const rows of chunks(links)) {
+ await sql`
+ update "jobMaterial" as m
+ set "jobOperationId" = v."jobOperationId"
+ from (values ${sql.join(
+ rows.map((r) => sql`(${r.materialId}, ${r.jobOperationId})`)
+ )}) as v("id", "jobOperationId")
+ where m."id" = v."id" and m."companyId" = ${companyId}
+ `.execute(trx);
+ }
+
+ // The advisory lock serializes the rebuild per job: two runs for one job
+ // can overlap (a retry racing a still-running invocation), and interleaved
+ // delete/insert then violates jobOperationDependency_pk. onConflict
+ // absorbs any edge that survives a race with trigger-rework's inserts.
+ for (const { jobId, dependencies } of writes) {
+ if (!dependencies) continue;
+ await sql`SELECT pg_advisory_xact_lock(hashtextextended(${`schedule:dependencies:${jobId}`}, 0))`.execute(
+ trx
+ );
+ let deleteQuery = trx
+ .deleteFrom("jobOperationDependency")
+ .where("jobId", "=", jobId)
+ .where("companyId", "=", companyId);
+ // Rework operation dependencies are preserved.
+ if (dependencies.reworkOpIds.length > 0) {
+ deleteQuery = deleteQuery
+ .where("operationId", "not in", dependencies.reworkOpIds)
+ .where("dependsOnId", "not in", dependencies.reworkOpIds);
+ }
+ await deleteQuery.execute();
+ for (const edges of chunks(dependencies.edges)) {
+ await trx
+ .insertInto("jobOperationDependency")
+ .values(edges.map((e) => ({ ...e, jobId, companyId })))
+ .onConflict((oc) =>
+ oc.columns(["operationId", "dependsOnId"]).doNothing()
+ )
+ .execute();
+ }
+ }
+
+ // Never re-open work that is finished (Done/Canceled) or in flight (In
+ // Progress/Paused): only Waiting/Todo become Ready.
+ for (const ids of chunks(writes.flatMap((w) => w.readyOperationIds))) {
+ await trx
+ .updateTable("jobOperation")
+ .set({ status: "Ready" })
+ .where("id", "in", ids)
+ .where("companyId", "=", companyId)
+ .where("status", "not in", [
+ "Ready",
+ "Done",
+ "Canceled",
+ "In Progress",
+ "Paused"
+ ])
+ .execute();
+ }
+
+ // Rows that write the same columns go in one statement.
+ const byShape = new Map<
+ string,
+ { id: string; placement: PlacementWrite }[]
+ >();
+ for (const row of writes.flatMap((w) => w.placements)) {
+ const shape = PLACEMENT_COLUMNS.filter(
+ (column) => row.placement[column] !== undefined
+ ).join();
+ const group = byShape.get(shape);
+ if (group) group.push(row);
+ else byShape.set(shape, [row]);
+ }
+ for (const group of byShape.values()) {
+ for (const rows of chunks(group)) {
+ await updatePlacements(trx, rows, companyId, userId);
+ }
+ }
+
+ // Rebuild the jobs' live capacity reservations from this run's placements.
+ // Batch-tagged rows are spared: a member job's regen must never destroy
+ // the batch's coalesced reservation.
+ for (const jobIds of chunks(writes.map((w) => w.jobId))) {
+ await trx
+ .deleteFrom("capacityReservation")
+ .where("jobId", "in", jobIds)
+ .where("companyId", "=", companyId)
+ .where("scenarioId", "is", null)
+ .where("jobOperationBatchId", "is", null)
+ .execute();
+ }
+ const reservations = writes.flatMap((w) =>
+ w.reservations.map((p) => ({
+ resourceKind: p.resourceKind,
+ resourceId: p.resourceId,
+ operationId: p.operationId,
+ jobId: w.jobId,
+ companyId,
+ startAt: msToInstantIso(p.startAt),
+ endAt: msToInstantIso(p.endAt),
+ earliestStartAt:
+ p.earliestStartAt !== undefined
+ ? msToInstantIso(p.earliestStartAt)
+ : null,
+ scheduleNote: p.scheduleNote ?? null,
+ workHours: p.workHours ?? null,
+ isPlaceholder: p.isPlaceholder ?? false,
+ createdBy: userId
+ }))
+ );
+ for (const rows of chunks(reservations)) {
+ await trx.insertInto("capacityReservation").values(rows).execute();
+ }
+
+ // The forecast, and the stale-schedule stamps cleared with it. The
+ // scheduler is status-neutral: releasing a job to Ready is the app's
+ // job-status flow, never a side effect of scheduling.
+ for (const rows of chunks(writes)) {
+ await sql`
+ update "job" as j
+ set "projectedCompletionAt" = v."projectedCompletionAt"::timestamptz,
+ "scheduleOutdatedReason" = null,
+ "scheduleOutdatedAt" = null,
+ "updatedAt" = ${datetime.timestamp()},
+ "updatedBy" = ${userId}
+ from (values ${sql.join(
+ rows.map((w) => sql`(${w.jobId}, ${w.projectedCompletionAt})`)
+ )}) as v("id", "projectedCompletionAt")
+ where j."id" = v."id"
+ and j."companyId" = ${companyId}
+ and (
+ j."projectedCompletionAt" is distinct from v."projectedCompletionAt"::timestamptz
+ or j."scheduleOutdatedReason" is not null
+ or j."scheduleOutdatedAt" is not null
+ )
+ `.execute(trx);
+ }
+ });
+}
diff --git a/packages/planning/src/scheduling/run-overlay.test.ts b/packages/planning/src/scheduling/run-overlay.test.ts
new file mode 100644
index 0000000000..b32181b653
--- /dev/null
+++ b/packages/planning/src/scheduling/run-overlay.test.ts
@@ -0,0 +1,147 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it } from "vitest";
+import type { CrossJobOperation } from "./master-data-provider.ts";
+import {
+ dependencyEdgesEqual,
+ mergeCrossJobOperations,
+ visibleReservations
+} from "./run-overlay.ts";
+import type { PlannedReservation } from "./types.ts";
+
+const NOW = 1_000;
+
+const reservation = (
+ overrides: Partial<PlannedReservation> = {}
+): PlannedReservation => ({
+ resourceKind: "WorkCenter",
+ resourceId: "wc1",
+ operationId: "op1",
+ startAt: NOW + 10,
+ endAt: NOW + 20,
+ ...overrides
+});
+
+const operation = (
+ id: string,
+ workCenterId: string | null,
+ priority = 1
+): CrossJobOperation => ({
+ id,
+ workCenterId,
+ priority,
+ dueDate: null,
+ startDate: null,
+ deadlineType: null,
+ jobPriority: null,
+ createdAt: null,
+ projectedCompletionAt: null,
+ setupTime: null,
+ setupUnit: null,
+ laborTime: null,
+ laborUnit: null,
+ machineTime: null,
+ machineUnit: null,
+ operationQuantity: null,
+ operationLeadTime: null
+});
+
+describe("dependencyEdgesEqual", () => {
+ const a = { operationId: "b", dependsOnId: "a" };
+ const b = { operationId: "c", dependsOnId: "b" };
+
+ it("ignores order", () => {
+ expect(dependencyEdgesEqual([a, b], [b, a])).toBe(true);
+ });
+
+ it("sees an added, a removed and a reversed edge", () => {
+ expect(dependencyEdgesEqual([a], [a, b])).toBe(false);
+ expect(dependencyEdgesEqual([a, b], [a])).toBe(false);
+ expect(
+ dependencyEdgesEqual([a], [{ operationId: "a", dependsOnId: "b" }])
+ ).toBe(false);
+ });
+
+ it("treats two empty sets as equal", () => {
+ expect(dependencyEdgesEqual([], [])).toBe(true);
+ });
+});
+
+describe("visibleReservations", () => {
+ const writes = (
+ jobStatus: string | null,
+ reservations: PlannedReservation[]
+ ) => ({ jobId: "job1", jobStatus, reservations });
+
+ it("carries a released job's reservation to the jobs after it", () => {
+ expect(
+ visibleReservations(writes("Ready", [reservation()]), "J1", NOW)
+ ).toEqual([
+ {
+ resourceKind: "WorkCenter",
+ resourceId: "wc1",
+ startAt: NOW + 10,
+ endAt: NOW + 20,
+ jobId: "job1",
+ readableJobId: "J1",
+ jobOperationBatchId: null
+ }
+ ]);
+ });
+
+ it("drops placeholders and reservations that ended by now", () => {
+ const rows = visibleReservations(
+ writes("In Progress", [
+ reservation({ isPlaceholder: true }),
+ reservation({ startAt: NOW - 20, endAt: NOW })
+ ]),
+ "J1",
+ NOW
+ );
+ expect(rows).toEqual([]);
+ });
+
+ it("holds no capacity for a job that is not released", () => {
+ for (const status of ["Draft", "Planned", "Completed", null]) {
+ expect(
+ visibleReservations(writes(status, [reservation()]), "J1", NOW)
+ ).toEqual([]);
+ }
+ });
+});
+
+describe("mergeCrossJobOperations", () => {
+ it("replaces a stored operation with its new placement", () => {
+ const merged = mergeCrossJobOperations(
+ [operation("a", "wc1", 1), operation("b", "wc1", 2)],
+ new Map([["a", operation("a", "wc1", 9)]]),
+ ["wc1"]
+ );
+ expect(merged.map((o) => [o.id, o.priority])).toEqual([
+ ["b", 2],
+ ["a", 9]
+ ]);
+ });
+
+ it("moves an operation to the work center it was placed at", () => {
+ const placed = new Map([["a", operation("a", "wc2")]]);
+ expect(
+ mergeCrossJobOperations([operation("a", "wc1")], placed, ["wc1"])
+ ).toEqual([]);
+ expect(
+ mergeCrossJobOperations([], placed, ["wc2"]).map((o) => o.id)
+ ).toEqual(["a"]);
+ });
+
+ it("leaves out a placed operation with no work center", () => {
+ expect(
+ mergeCrossJobOperations(
+ [operation("a", "wc1")],
+ new Map([["a", operation("a", null)]]),
+ ["wc1"]
+ )
+ ).toEqual([]);
+ });
+});
diff --git a/packages/planning/src/scheduling/run-overlay.ts b/packages/planning/src/scheduling/run-overlay.ts
new file mode 100644
index 0000000000..515ddac4c6
--- /dev/null
+++ b/packages/planning/src/scheduling/run-overlay.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 type {
+ CrossJobOperation,
+ LiveReservation
+} from "./master-data-provider.ts";
+import {
+ capacityHoldingJobStatuses,
+ type PlannedReservation
+} from "./types.ts";
+
+/**
+ * A location run computes every job in memory and writes once at the end, so
+ * a later job cannot read an earlier job's result from the database. These
+ * are the rules for what it sees instead; each one states what the database
+ * would have returned had the earlier job been written first.
+ */
+
+export const PLACEMENT_CASTS = {
+ startDate: "date",
+ projectedCompletionAt: "timestamptz",
+ dueDate: "date",
+ priority: "float8",
+ workCenterId: "text",
+ hasConflict: "boolean",
+ conflictReason: "text"
+} as const;
+
+export type PlacementColumn = keyof typeof PLACEMENT_CASTS;
+export type PlacementWrite = Partial<Record<PlacementColumn, unknown>>;
+
+export type DependencyEdge = { operationId: string; dependsOnId: string };
+
+/** Everything one job's schedule run wants written. */
+export type JobWrites = {
+ jobId: string;
+ jobStatus: string | null;
+ materialLinks: { materialId: string; jobOperationId: string }[];
+ /** Null when the stored non-rework edges already equal the computed ones. */
+ dependencies: { reworkOpIds: string[]; edges: DependencyEdge[] } | null;
+ readyOperationIds: string[];
+ placements: { id: string; placement: PlacementWrite }[];
+ reservations: PlannedReservation[];
+ projectedCompletionAt: string | null;
+};
+
+export function dependencyEdgesEqual(
+ stored: DependencyEdge[],
+ computed: DependencyEdge[]
+): boolean {
+ const key = (e: DependencyEdge) => `${e.operationId}\u0000${e.dependsOnId}`;
+ const storedKeys = new Set(stored.map(key));
+ const computedKeys = new Set(computed.map(key));
+ if (storedKeys.size !== computedKeys.size) return false;
+ for (const k of computedKeys) if (!storedKeys.has(k)) return false;
+ return true;
+}
+
+/**
+ * The reservations of a just-scheduled job that hold capacity against the
+ * jobs after it: the filters of the live-reservation read, applied to rows
+ * that are not stored yet.
+ */
+export function visibleReservations(
+ writes: Pick<JobWrites, "jobId" | "jobStatus" | "reservations">,
+ readableJobId: string,
+ now: number
+): LiveReservation[] {
+ if (
+ !(capacityHoldingJobStatuses as readonly string[]).includes(
+ writes.jobStatus ?? ""
+ )
+ ) {
+ return [];
+ }
+ return writes.reservations
+ .filter((r) => !r.isPlaceholder && r.endAt > now)
+ .map((r) => ({
+ resourceKind: r.resourceKind,
+ resourceId: r.resourceId,
+ startAt: r.startAt,
+ endAt: r.endAt,
+ jobId: writes.jobId,
+ readableJobId,
+ jobOperationBatchId: null
+ }));
+}
+
+/**
+ * Operations at these work centers: the stored rows, with every operation an
+ * earlier job of the run placed replaced by its new placement. A placed
+ * operation appears only at the work center it now has.
+ */
+export function mergeCrossJobOperations(
+ stored: CrossJobOperation[],
+ placed: ReadonlyMap<string, CrossJobOperation>,
+ workCenterIds: string[]
+): CrossJobOperation[] {
+ const requested = new Set(workCenterIds);
+ const merged = stored.filter((op) => !op.id || !placed.has(op.id));
+ for (const op of placed.values()) {
+ if (op.workCenterId && requested.has(op.workCenterId)) merged.push(op);
+ }
+ return merged;
+}
diff --git a/packages/planning/src/scheduling/run-schedule.ts b/packages/planning/src/scheduling/run-schedule.ts
index dcb1682285..ed18113ae0 100644
--- a/packages/planning/src/scheduling/run-schedule.ts
+++ b/packages/planning/src/scheduling/run-schedule.ts
@@ -11,7 +11,9 @@ import type { BatchPlacement } from "./batch-scheduler.ts";
import { placeReleasedBatches } from "./batch-scheduler.ts";
import { toInstantMs } from "./date-utils.ts";
import { KyselyMasterDataProvider } from "./master-data-provider.ts";
+import { persistLocationWrites } from "./persist-location.ts";
import { DEADLINE_PRIORITY } from "./priority-calculator.ts";
+import type { JobWrites } from "./run-overlay.ts";
import {
SCHEDULING_HORIZON_DAYS,
SchedulingEngine
@@ -135,8 +137,10 @@ export async function loadOrderedBatch(
/**
* Regenerate every open job in a location sequentially. Each run excludes the
* jobs NOT YET run (self + later) from the reservation snapshot, so it sees
- * non-batch reservations plus the just-persisted placements of already-run batch
- * jobs — sequential capacity claiming, no pre-clear step.
+ * non-batch reservations plus the placements of already-run batch jobs —
+ * sequential capacity claiming, no pre-clear step. The jobs are computed in
+ * memory (the provider carries each job's result to the next) and the whole
+ * location is written in one transaction at the end.
*/
export async function runLocationSchedule(
params: BaseParams
@@ -179,9 +183,11 @@ export async function runLocationSchedule(
});
}
- // After the pre-pass, which writes member operations.
+ // After the pre-pass, which writes member operations and batch reservations.
await provider.preloadJobs(batch);
+ await provider.beginRun(batch, now);
+ const writes: JobWrites[] = [];
let conflictsDetected = 0;
const failedJobIds: string[] = [];
const newlyLate: NewlyLateJob[] = [];
@@ -196,15 +202,17 @@ export async function runLocationSchedule(
companyId,
userId,
now,
- persist: true,
excludeJobIds: batch.slice(i),
batchPlacements
});
- // One job's failure must not abandon the rest of the batch — its stale
- // stamp only clears inside the persist transaction, so a failed job stays
- // stamped for a later wave while the jobs behind it still run
+ // One job's failure must not abandon the rest of the batch — it is left
+ // out of the write, so it stays stamped stale for a later wave and the
+ // jobs behind it still see its stored reservations.
try {
const result = await engine.run();
+ const jobWrites = engine.getWrites();
+ provider.recordJob(jobWrites);
+ writes.push(jobWrites);
conflictsDetected += result.conflictsDetected;
if (engine.isNewlyLate()) {
newlyLate.push({
@@ -225,6 +233,8 @@ export async function runLocationSchedule(
}
}
+ await persistLocationWrites(db, writes, { companyId, userId });
+
return {
locationId,
jobsScheduled: batch.length - failedJobIds.length,
@@ -280,7 +290,6 @@ export async function runExpediteWhatIf(
companyId,
userId,
now,
- persist: false,
excludeJobIds: batch,
batchPlacements
});
diff --git a/packages/planning/src/scheduling/scheduling-engine.test.ts b/packages/planning/src/scheduling/scheduling-engine.test.ts
deleted file mode 100644
index 4fba9e5772..0000000000
--- a/packages/planning/src/scheduling/scheduling-engine.test.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
-// including ports, remain AGPLv3; serving them over a network requires releasing their source.
-
-import {
- 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.ts
index 3e6035b40e..0feba886c6 100644
--- a/packages/planning/src/scheduling/scheduling-engine.ts
+++ b/packages/planning/src/scheduling/scheduling-engine.ts
@@ -5,9 +5,8 @@
import { type Database, getCompanyTimeZone } from "@carbon/database";
import type { DB } from "@carbon/database/client";
import { getLogger } from "@carbon/logger";
-import { datetime } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
-import { type Kysely, sql } from "kysely";
+import type { Kysely } from "kysely";
import {
AssemblyHandler,
buildMakeMethodDependencies
@@ -47,6 +46,11 @@ import {
calculatePrioritiesByWorkCenter,
toOperationWithJobInfo
} from "./priority-calculator.ts";
+import {
+ dependencyEdgesEqual,
+ type JobWrites,
+ type PlacementWrite
+} from "./run-overlay.ts";
import type {
AssemblyNode,
BaseOperation,
@@ -68,79 +72,6 @@ export { SCHEDULING_HORIZON_DAYS } from "./finite-context.ts";
const log = getLogger("planning", "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 `)})`;
-}
-
-const PLACEMENT_CASTS = {
- startDate: "date",
- projectedCompletionAt: "timestamptz",
- dueDate: "date",
- priority: "float8",
- workCenterId: "text",
- hasConflict: "boolean",
- conflictReason: "text"
-} as const;
-
-type PlacementColumn = keyof typeof PLACEMENT_CASTS;
-type PlacementWrite = Partial<Record<PlacementColumn, unknown>>;
-
-const PLACEMENT_COLUMNS = Object.keys(PLACEMENT_CASTS) as PlacementColumn[];
-
-/**
- * Write the placements of operations that all set the same columns, in one
- * statement. Every UPDATE is queued for the audit/search handlers, so a row
- * whose placement is unchanged is not written at all.
- */
-async function updatePlacements(
- trx: Kysely<DB>,
- rows: { id: string; placement: PlacementWrite }[],
- userId: string
-) {
- const columns = PLACEMENT_COLUMNS.filter(
- (column) => rows[0]!.placement[column] !== undefined
- );
- const value = (column: PlacementColumn) =>
- sql`v.${sql.ref(column)}::${sql.raw(PLACEMENT_CASTS[column])}`;
-
- await sql`
- update "jobOperation" as o
- set ${sql.join([
- ...columns.map((c) => sql`${sql.ref(c)} = ${value(c)}`),
- sql`"updatedAt" = ${datetime.timestamp()}`,
- sql`"updatedBy" = ${userId}`
- ])}
- from (values ${sql.join(
- rows.map(
- (row) =>
- sql`(${sql.join([row.id, ...columns.map((c) => row.placement[c])])})`
- )
- )}) as v(${sql.join(["id", ...columns].map((c) => sql.ref(c)))})
- where o."id" = v."id"
- and ${
- columns.length === 0
- ? sql`true`
- : sql`(${sql.join(
- columns.map(
- (c) => sql`o.${sql.ref(c)} is distinct from ${value(c)}`
- ),
- sql` or `
- )})`
- }
- `.execute(trx);
-}
-
/**
* Unified Scheduling Engine
* Orchestrates all scheduling operations for both initial scheduling and rescheduling
@@ -176,8 +107,15 @@ export class SchedulingEngine {
* epoch-ms.
*/
private now: number;
- /** When false, run() simulates without writing anything (expedite what-if). */
- private persist: boolean;
+ /**
+ * The engine writes nothing: run() leaves what it wants stored here, and the
+ * caller persists it (or, for the expedite what-if, drops it).
+ */
+ private writes: JobWrites | null = null;
+ /** Materials this run puts on an operation: material id → operation id. */
+ private materialLinks = new Map<string, string>();
+ private dependencyWrite: JobWrites["dependencies"] = null;
+ private readyOperationIds: string[] = [];
/**
* Job ids whose live reservations to EXCLUDE from the snapshot — the whole
* batch, so each run sees only non-batch reservations plus the in-run
@@ -192,7 +130,7 @@ export class SchedulingEngine {
/**
* Backward need-by targets per operation id ("YYYY-MM-DD" | null), computed
* by computeNeedBys() BEFORE placement and read by NOTHING in the placement
- * path — persistChanges diff-writes them to jobOperation.dueDate
+ * path — the location write diff-writes them to jobOperation.dueDate
* (spec 2026-08-15 dual dates).
*/
private needByByOperation: Map<string, string | null> = new Map();
@@ -220,8 +158,6 @@ export class SchedulingEngine {
provider?: MasterDataProvider;
/** Shared run clock (epoch-ms); defaults to a fresh clock if omitted. */
now?: number;
- /** Simulate-only when false (no writes). Defaults to true. */
- persist?: boolean;
/** Batch job ids to exclude from the reservation snapshot. */
excludeJobIds?: string[];
/**
@@ -238,7 +174,6 @@ export class SchedulingEngine {
this.companyId = options.companyId;
this.userId = options.userId;
this.now = options.now ?? Date.now();
- this.persist = options.persist ?? true;
this.batchPlacements = options.batchPlacements ?? null;
this.excludeJobIds =
options.excludeJobIds && options.excludeJobIds.length > 0
@@ -250,7 +185,7 @@ export class SchedulingEngine {
new KyselyMasterDataProvider(this.db, this.client, this.companyId);
this.assemblyHandler = new AssemblyHandler(this.provider);
- this.materialManager = new MaterialManager(this.db, this.provider);
+ this.materialManager = new MaterialManager(this.provider);
}
/**
@@ -295,9 +230,8 @@ export class SchedulingEngine {
// Initialize material manager
await this.materialManager.initialize(this.jobId);
- // Assign operations to materials that don't have one. Dry-run (expedite
- // what-if) writes nothing, so skip this DB mutation.
- if (this.operations.length > 0 && this.persist) {
+ // Assign operations to materials that don't have one.
+ if (this.operations.length > 0) {
const operationsByJobMakeMethodId = this.operations.reduce<
Record<string, BaseOperation[]>
>((acc, op) => {
@@ -309,10 +243,12 @@ export class SchedulingEngine {
}, {});
const materialIds = this.materialManager.getMaterialIds();
- await this.materialManager.assignOperationsToMaterials(
+ for (const link of this.materialManager.assignOperationsToMaterials(
materialIds,
operationsByJobMakeMethodId
- );
+ )) {
+ this.materialLinks.set(link.materialId, link.operationId);
+ }
}
// Build assembly tree and get depth
@@ -397,8 +333,11 @@ export class SchedulingEngine {
const jobMakeMethodToOperationId: Record<string, string | null> = {};
for (const m of jobMaterials) {
if (m.jobMaterialMakeMethodId) {
+ // A material this run put on an operation is not stored yet.
jobMakeMethodToOperationId[m.jobMaterialMakeMethodId] =
- m.jobOperationId;
+ m.jobOperationId ??
+ (m.id ? this.materialLinks.get(m.id) : undefined) ??
+ null;
}
}
@@ -469,7 +408,6 @@ export class SchedulingEngine {
}
}
- // Delete existing dependencies, preserving rework operation dependencies
const reworkOpIds = allOperations
.filter((op) => op.reworkId)
.map((op) => op.id!);
@@ -480,99 +418,54 @@ export class SchedulingEngine {
this.companyId
);
- // Dry-run (expedite what-if) computes the dependency graph in memory but
- // writes nothing. One transaction otherwise: a partial rebuild (edges
- // deleted but not re-inserted) would corrupt the graph for the next run.
- //
- // Rebuild atomically with a per-job advisory lock: two schedule runs for
- // the same job can overlap (an Inngest retry racing a still-running
- // invocation, or a direct in-process run alongside the queued one);
- // interleaved delete/insert then violates jobOperationDependency_pk. The
- // lock serializes the rebuild per job, and onConflict absorbs any edge that
- // survives a race with trigger-rework's inserts.
- if (this.persist) {
- await this.db.transaction().execute(async (trx) => {
- await sql`SELECT pg_advisory_xact_lock(hashtextextended(${`schedule:dependencies:${this.jobId}`}, 0))`.execute(
- trx
- );
-
- let deleteQuery = trx
- .deleteFrom("jobOperationDependency")
- .where("jobId", "=", this.jobId);
-
- if (reworkOpIds.length > 0) {
- deleteQuery = deleteQuery
- .where("operationId", "not in", reworkOpIds)
- .where("dependsOnId", "not in", reworkOpIds);
- }
-
- await deleteQuery.execute();
-
- if (records.length > 0) {
- await trx
- .insertInto("jobOperationDependency")
- .values(records)
- .onConflict((oc) =>
- oc.columns(["operationId", "dependsOnId"]).doNothing()
- )
- .execute();
- }
- });
- }
+ // The non-rework edges are rebuilt only when they differ from the stored
+ // ones: a routing changes far less often than its schedule does.
+ const reworkOps = new Set(reworkOpIds);
+ const storedEdges = this.dependencies.filter(
+ (d) => !reworkOps.has(d.operationId) && !reworkOps.has(d.dependsOnId)
+ );
+ this.dependencyWrite = dependencyEdgesEqual(storedEdges, records)
+ ? null
+ : {
+ reworkOpIds,
+ edges: records.map((r) => ({
+ operationId: r.operationId,
+ dependsOnId: r.dependsOnId
+ }))
+ };
- if (this.persist) {
- // Unblock dependency-free operations to Ready (outside the rebuild txn so
- // the advisory lock is held only for the delete/insert). Two guards keep
- // this from RE-OPENING work that is already finished or in flight:
- //
- // 1. Only OPEN jobs. A terminal job (Completed/Closed/Cancelled) or a
- // pre-release Draft/Planned job is never re-opened by a regen. Open
- // work is `capacityHoldingJobStatuses`; the batch loader already
- // filters to these, so this is defense-in-depth for any direct caller.
- // 2. Only resettable operation statuses. Never overwrite an operation
- // that is Done/Canceled (finished) or In Progress/Paused (running) —
- // only Ready/Waiting/Todo become Ready. Without this, a first op that
- // an operator already completed was flipped back to Ready, and because
- // `is_last_job_operation` requires EVERY op Done, the finished job
- // could then never auto-complete (it sat stuck as open work).
- const jobIsOpen =
- this.job?.status != null &&
- (capacityHoldingJobStatuses as readonly string[]).includes(
- this.job.status
- );
- if (jobIsOpen) {
- const resettable = new Set(
- allOperations
- .filter(
- (op) =>
- ![
- "Ready",
- "Done",
- "Canceled",
- "In Progress",
- "Paused"
- ].includes(op.status ?? "")
- )
- .map((op) => op.id)
- );
- const unblocked = [...allDependencies]
- .filter(([opId, deps]) => deps.size === 0 && resettable.has(opId))
- .map(([opId]) => opId);
- if (unblocked.length > 0) {
- await this.db
- .updateTable("jobOperation")
- .set({ status: "Ready" })
- .where("id", "in", unblocked)
- .where("status", "not in", [
- "Ready",
- "Done",
- "Canceled",
- "In Progress",
- "Paused"
- ])
- .execute();
- }
- }
+ // Unblock dependency-free operations to Ready. Two guards keep this from
+ // RE-OPENING work that is already finished or in flight:
+ //
+ // 1. Only OPEN jobs. A terminal job (Completed/Closed/Cancelled) or a
+ // pre-release Draft/Planned job is never re-opened by a regen. Open
+ // work is `capacityHoldingJobStatuses`; the batch loader already
+ // filters to these, so this is defense-in-depth for any direct caller.
+ // 2. Only resettable operation statuses. Never overwrite an operation
+ // that is Done/Canceled (finished) or In Progress/Paused (running) —
+ // only Ready/Waiting/Todo become Ready. Without this, a first op that
+ // an operator already completed was flipped back to Ready, and because
+ // `is_last_job_operation` requires EVERY op Done, the finished job
+ // could then never auto-complete (it sat stuck as open work).
+ const jobIsOpen =
+ this.job?.status != null &&
+ (capacityHoldingJobStatuses as readonly string[]).includes(
+ this.job.status
+ );
+ if (jobIsOpen) {
+ const resettable = new Set(
+ allOperations
+ .filter(
+ (op) =>
+ !["Ready", "Done", "Canceled", "In Progress", "Paused"].includes(
+ op.status ?? ""
+ )
+ )
+ .map((op) => op.id)
+ );
+ this.readyOperationIds = [...allDependencies]
+ .filter(([opId, deps]) => deps.size === 0 && resettable.has(opId))
+ .map(([opId]) => opId);
}
// Store dependencies for date calculation (non-rework edges rebuilt above)
@@ -631,7 +524,7 @@ export class SchedulingEngine {
* Backward need-by pass (spec 2026-08-15 dual dates): demand-anchored
* targets walked back from the job's due date on the same calendar physics
* as placement (shared windows fetch). The result is persisted to
- * jobOperation.dueDate by persistChanges and read by NOTHING in the
+ * jobOperation.dueDate by the location write and read by NOTHING in the
* placement path — targets are outputs, never constraints.
*/
private async computeNeedBys(): Promise<void> {
@@ -901,9 +794,11 @@ export class SchedulingEngine {
const makeMethodIds =
this.assemblyHandler.getAllJobMakeMethodIds(assemblyTree);
- // Get materials that need assignment
- const materials =
- await this.provider.getUnassignedMakeToOrderMaterials(makeMethodIds);
+ // Materials that still need assignment: the stored ones, less those
+ // initialize() already put on an operation in this run.
+ const materials = (
+ await this.provider.getUnassignedMakeToOrderMaterials(makeMethodIds)
+ ).filter((m) => !m.id || !this.materialLinks.has(m.id));
// Group non-rework operations by jobMakeMethodId
const operationsByMethod = new Map<string, BaseOperation[]>();
@@ -917,7 +812,6 @@ export class SchedulingEngine {
}
// Assign first operation of each method to its materials
- const materialIdsByFirstOp = new Map<string, string[]>();
for (const material of materials) {
if (!material.jobMakeMethodId) continue;
@@ -927,26 +821,14 @@ export class SchedulingEngine {
);
const firstOpId = sortedOps[0]?.id;
if (!firstOpId || !material.id) continue;
- const ids = materialIdsByFirstOp.get(firstOpId) ?? [];
- ids.push(material.id);
- materialIdsByFirstOp.set(firstOpId, ids);
- }
-
- // Dry-run writes nothing (expedite what-if).
- if (!this.persist) return;
- for (const [jobOperationId, ids] of materialIdsByFirstOp) {
- await this.db
- .updateTable("jobMaterial")
- .set({ jobOperationId })
- .where("id", "in", ids)
- .execute();
+ this.materialLinks.set(material.id, firstOpId);
}
}
/**
- * Persist all changes to the database
+ * Collect everything this run wants stored.
*/
- async persistChanges(): Promise<void> {
+ private buildWrites(): void {
// Zero-duration operations (all times = 0) place a start === end slot,
// which occupies no capacity and violates the endAt > startAt check.
const planned = (
@@ -972,121 +854,59 @@ export class SchedulingEngine {
this.newlyLate = false;
}
- // One transaction: a partial write (reservations deleted but not
- // re-inserted) would free this job's capacity to other jobs' replans
- // while its operations already carry the new plan.
- await this.db.transaction().execute(async (trx) => {
- const placements = new Map<
- string,
- { id: string; placement: PlacementWrite }[]
- >();
- for (const op of this.scheduledOperations.values()) {
- const originalOp = this.operations.find((o) => o.id === op.id);
- const isManuallyScheduled = originalOp?.manuallyScheduled ?? false;
- // Never clobber a work center the user (or method) already set.
- // Auto-selection may only fill null/empty work centers.
- const originalWorkCenterId = originalOp?.workCenterId;
- const workCenterId =
- originalWorkCenterId != null && originalWorkCenterId !== ""
- ? originalWorkCenterId
- : op.workCenterId;
-
- // 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.
- const needBy = this.needByByOperation.get(op.id) ?? null;
- const storedDueDate = toIsoDate(originalOp?.dueDate ?? null);
- const writeDueDate = !isManuallyScheduled && needBy !== storedDueDate;
-
- const placement: PlacementWrite = {
- startDate: op.startDate,
- projectedCompletionAt: op.projectedCompletionAt ?? null,
- ...(writeDueDate ? { dueDate: needBy } : {}),
- ...(op.priority != null ? { priority: op.priority } : {}),
- workCenterId,
- hasConflict: op.hasConflict,
- conflictReason: op.conflictReason
- };
- // Rows that write the same columns go in one statement.
- const shape = PLACEMENT_COLUMNS.filter(
- (column) => placement[column] !== undefined
- ).join();
- const group = placements.get(shape);
- if (group) group.push({ id: op.id, placement });
- else placements.set(shape, [{ id: op.id, placement }]);
- }
-
- for (const rows of placements.values()) {
- await updatePlacements(trx, rows, this.userId);
- }
-
- // Rebuild this job's live capacity reservations from this run's
- // placements (reservations are authoritative across jobs and runs).
- // Batch-tagged rows are spared: a member job's regen must never destroy
- // the batch's coalesced reservation.
- await trx
- .deleteFrom("capacityReservation")
- .where("jobId", "=", this.jobId)
- .where("companyId", "=", this.companyId)
- .where("scenarioId", "is", null)
- .where("jobOperationBatchId", "is", null)
- .execute();
-
- if (planned.length > 0) {
- await trx
- .insertInto("capacityReservation")
- .values(
- planned.map((p) => ({
- resourceKind: p.resourceKind,
- resourceId: p.resourceId,
- operationId: p.operationId,
- jobId: this.jobId,
- companyId: this.companyId,
- startAt: msToInstantIso(p.startAt),
- endAt: msToInstantIso(p.endAt),
- earliestStartAt:
- p.earliestStartAt !== undefined
- ? msToInstantIso(p.earliestStartAt)
- : null,
- scheduleNote: p.scheduleNote ?? null,
- workHours: p.workHours ?? null,
- isPlaceholder: p.isPlaceholder ?? false,
- createdBy: this.userId
- }))
- )
- .execute();
- }
-
- // Write the forecast and clear the stale-schedule stamps for this job in
- // the SAME transaction. The scheduler is status-neutral: it forecasts and
- // reserves capacity for jobs already released (Ready/In Progress/Paused).
- // Releasing a job to Ready is the app's job-status flow (which raises
- // jobReleased), never a side effect of scheduling.
- await trx
- .updateTable("job")
- .set({
- projectedCompletionAt: this.projectedCompletionAt,
- scheduleOutdatedReason: null,
- scheduleOutdatedAt: null,
- updatedAt: datetime.timestamp(),
- updatedBy: this.userId
- })
- .where("id", "=", this.jobId)
- .where("companyId", "=", this.companyId)
- .where(
- isDistinctFromAny({
- projectedCompletionAt: this.projectedCompletionAt,
- scheduleOutdatedReason: null,
- scheduleOutdatedAt: null
- })
- )
- .execute();
- });
-
+ const placements: JobWrites["placements"] = [];
+ for (const op of this.scheduledOperations.values()) {
+ const originalOp = this.operations.find((o) => o.id === op.id);
+ const isManuallyScheduled = originalOp?.manuallyScheduled ?? false;
+ // Never clobber a work center the user (or method) already set.
+ // Auto-selection may only fill null/empty work centers.
+ const originalWorkCenterId = originalOp?.workCenterId;
+ const workCenterId =
+ originalWorkCenterId != null && originalWorkCenterId !== ""
+ ? originalWorkCenterId
+ : op.workCenterId;
+
+ // 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.
+ const needBy = this.needByByOperation.get(op.id) ?? null;
+ const storedDueDate = toIsoDate(originalOp?.dueDate ?? null);
+ const writeDueDate = !isManuallyScheduled && needBy !== storedDueDate;
+
+ const placement: PlacementWrite = {
+ startDate: op.startDate,
+ projectedCompletionAt: op.projectedCompletionAt ?? null,
+ ...(writeDueDate ? { dueDate: needBy } : {}),
+ ...(op.priority != null ? { priority: op.priority } : {}),
+ workCenterId,
+ hasConflict: op.hasConflict,
+ conflictReason: op.conflictReason
+ };
+ placements.push({ id: op.id, placement });
+ }
+
+ this.writes = {
+ jobId: this.jobId,
+ jobStatus: this.job?.status ?? null,
+ materialLinks: [...this.materialLinks].map(
+ ([materialId, jobOperationId]) => ({ materialId, jobOperationId })
+ ),
+ dependencies: this.dependencyWrite,
+ readyOperationIds: this.readyOperationIds,
+ placements,
+ reservations: planned,
+ projectedCompletionAt: this.projectedCompletionAt
+ };
this.reservationsWritten = planned.length;
}
+ /** What this run wants stored; available after run(). */
+ getWrites(): JobWrites {
+ if (!this.writes) throw new Error("getWrites() called before run()");
+ return this.writes;
+ }
+
/**
* Get the scheduling result
*/
@@ -1121,7 +941,7 @@ export class SchedulingEngine {
/**
* Job-level behind-target attribution (spec 2026-08-15 dual dates). Only
- * when the JOB's verdict is late — the same judgment persistChanges uses
+ * when the JOB's verdict is late — the same judgment buildWrites uses
* for newly-late: projected finish past the due date on the FACTORY
* calendar — walk the operations in topological order and name the first
* one whose projected finish misses its backward need-by target. Purely
@@ -1176,9 +996,9 @@ export class SchedulingEngine {
}
/**
- * Run the full scheduling process. When `persist` is false (expedite
- * what-if), everything runs EXCEPT the write — the forecast is computed and
- * returned but nothing touches the database.
+ * Run the full scheduling process. Nothing is written: the forecast is
+ * computed in memory and the caller stores getWrites() — or does not (the
+ * expedite what-if).
*/
async run(): Promise<SchedulingResult> {
await this.initialize();
@@ -1196,9 +1016,7 @@ export class SchedulingEngine {
await this.selectWorkCenters();
await this.calculatePriorities();
- if (this.persist) {
- await this.persistChanges();
- }
+ this.buildWrites();
return this.getResult();
}
diff --git a/packages/planning/src/scheduling/work-center-selector.ts b/packages/planning/src/scheduling/work-center-selector.ts
index 1a466ad9d3..ec91e05321 100644
--- a/packages/planning/src/scheduling/work-center-selector.ts
+++ b/packages/planning/src/scheduling/work-center-selector.ts
@@ -562,7 +562,7 @@ export class WorkCenterSelector {
// Remaining-work netting: a started operation reserves only the work
// left. Labor + machine scale by remaining quantity; setup is done once
// any production event exists. A fully-complete op nets to 0 hours and is
- // filtered from the reservation set in persistChanges (endAt > startAt).
+ // filtered from the reservation set in buildWrites (endAt > startAt).
const { setup: setupFrac, work: workFrac } = remainingFractions(
op,
ctx.operationsWithEvents.has(op.id)
diff --git a/packages/query/AGENTS.md b/packages/query/AGENTS.md
index e36368b9ac..cd7bc1b3c7 100644
--- a/packages/query/AGENTS.md
+++ b/packages/query/AGENTS.md
@@ -39,8 +39,9 @@ pnpm --filter @carbon/query test
| `cachedApiQuery(url)` | The same read from an event handler or an effect |
| `useAction({ onSuccess, onError, onSettled })` | A mutation fetcher with callbacks. `onSettled` runs whenever a submission finishes, also when the action redirects and returns no data; `onSuccess` / `onError` need data |
| `setClientCompanyId(companyId, userId)` / `getCompanyId` | The shell layout sets both during render; the `companyId` cookie is httpOnly and unreadable in the browser. A different user empties the cache; leaving a company drops its loader entries |
+| `useRevalidator()` | React Router's `useRevalidator`, held while a fetcher is submitting or a navigation is in flight. The only one app code may import (`no-raw-revalidator` check): a revalidation during the redirect after a save restarts it as a plain navigation and the layouts skip their reload |
| `createInvalidationMiddleware({ getCache, skipPaths })` | Root `clientMiddleware`; skip POSTs that change no data (`/refresh-session`) |
-| `RouteRealtime`, `useRealtimeTable`, `useTableChanges`, `useRealtimeRevalidator` | Realtime over private broadcast topics. Revalidation waits for a submitting fetcher. A route entry `{ table, column, param }` and a `<name>Id=eq.` filter follow one record's rows only (`matchesFilter`) |
+| `RouteRealtime`, `useRealtimeTable`, `useTableChanges`, `useRealtimeRevalidator` | Realtime over private broadcast topics. Reloads go through `useRevalidator`, so they wait for a save in flight. A route entry `{ table, column, param }` and a `<name>Id=eq.` filter follow one record's rows only (`matchesFilter`) |
| `useRealtimeChannel` | One channel with retry, `private` and `onSubscribed(isReconnect)`. It reconnects when the tab returns after 5 minutes hidden or with a channel that is not joined — every reconnect reloads the page's data, so time in another tab does not |
| `LiveLists`, `useLiveList`, `LiveList` | Whole lists kept in the cache (items, customers, suppliers, people). IndexedDB first (the stored copy is keyed by company AND user: it is that user's RLS view); then `table_changes_since(cursor)` names the rows that changed since the stored copy and only those are re-read. The full list is fetched once per device, and again only when the log cannot answer (no cursor, a server restart, a cursor older than 7 days, more than 500 changed rows). Broadcasts patch it in memory while the tab is open; the stored copy is written only when the log is read (a patch does not move the cursor, so storing it buys nothing). Stored lists are removed from the device when they are no longer the user's: another user's or a company outside `companyIds` at page load, the current company when `table_changes_since` answers `42501`, everything on the login page, and any list not written for 24 hours (`STORED_LIST_MAX_AGE_MS`). An open page repeats the check every hour and asks the log again, which rewrites its own lists and notices a user who has left the company |
diff --git a/packages/query/src/index.ts b/packages/query/src/index.ts
index 536c0f9f24..1deba5044d 100644
--- a/packages/query/src/index.ts
+++ b/packages/query/src/index.ts
@@ -21,3 +21,4 @@ export {
useTopic
} from "./useRealtime";
export { useRealtimeChannel } from "./useRealtimeChannel";
+export { useRevalidator } from "./useRevalidator";
diff --git a/packages/query/src/useRealtime.tsx b/packages/query/src/useRealtime.tsx
index 6e6860e50d..392d3973ef 100644
--- a/packages/query/src/useRealtime.tsx
+++ b/packages/query/src/useRealtime.tsx
@@ -13,11 +13,12 @@ import {
useRef,
useSyncExternalStore
} from "react";
-import { useFetchers, useMatches, useRevalidator } from "react-router";
+import { useMatches } from "react-router";
import { getClientCache } from "./cache";
import { invalidateLoaderEntries } from "./invalidation";
import { matchesFilter } from "./realtimeFilter";
import { useRealtimeChannel } from "./useRealtimeChannel";
+import { useRevalidator } from "./useRevalidator";
/** What `broadcast_table_changes` sends: no row data, only which rows changed. */
export type BroadcastChange = {
@@ -148,31 +149,12 @@ const requestRevalidation = (revalidate: () => void) => {
};
/**
- * `revalidate()` that waits for submitting fetchers. React Router drops a
- * fetcher's redirect when a revalidation starts during its action, so a change
- * that arrives mid-submit is held and applied once the fetcher is done.
+ * The page reload a realtime change asks for: debounced across the tables a
+ * page follows, and held while a save is in flight (see `useRevalidator`).
*/
export function useRealtimeRevalidator() {
- const revalidator = useRevalidator();
- const submitting = useFetchers().some((f) => f.state === "submitting");
- const submittingRef = useRef(submitting);
- submittingRef.current = submitting;
- const held = useRef(false);
-
- useEffect(() => {
- if (!submitting && held.current) {
- held.current = false;
- requestRevalidation(revalidator.revalidate);
- }
- }, [submitting, revalidator]);
-
- return useCallback(() => {
- if (submittingRef.current) {
- held.current = true;
- return;
- }
- requestRevalidation(revalidator.revalidate);
- }, [revalidator]);
+ const { revalidate } = useRevalidator();
+ return useCallback(() => requestRevalidation(revalidate), [revalidate]);
}
/**
@@ -267,6 +249,9 @@ function TableSubscription(props: {
* `api+` loaders rather than a matched route. Render it once, in the shell.
*/
export function RouteRealtime({ companyId }: { companyId: string }) {
+ // Mounted for the whole session, so a held revalidation always has a caller
+ // left to run it.
+ useRevalidator();
const matches = useMatches();
const tables = useMemo(() => {
const followed = new Map<
diff --git a/packages/query/src/useRevalidator.ts b/packages/query/src/useRevalidator.ts
new file mode 100644
index 0000000000..d6a5935c9d
--- /dev/null
+++ b/packages/query/src/useRevalidator.ts
@@ -0,0 +1,60 @@
+// 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 { useCallback, useEffect, useMemo, useRef } from "react";
+import {
+ useFetchers,
+ useNavigation,
+ useRevalidator as useRouterRevalidator
+} from "react-router";
+
+// A revalidation asked for while the router was busy. Module state, not a ref:
+// the component that asked (a modal, a row menu) is often gone by the time the
+// router is idle, and any mounted caller of the hook can run it then.
+let held = false;
+
+/**
+ * `useRevalidator` whose `revalidate` never starts during a save. Import this
+ * one, never React Router's (the `no-raw-revalidator` check enforces it).
+ *
+ * A revalidation that starts during a save does harm twice over:
+ * - during the action, React Router drops the fetcher's redirect;
+ * - during the navigation that follows the save, it restarts that navigation
+ * without the submission. The restarted one looks like a plain navigation,
+ * so every layout whose `shouldRevalidate` skips those keeps its data from
+ * before the save (a new quote line was missing from the quote's explorer
+ * until a reload: the save's own realtime broadcast arrived mid-redirect).
+ *
+ * A call made while a fetcher is submitting or a navigation is in flight is
+ * held and runs once the router is idle. The promise of a held call resolves
+ * at once, before that reload: awaiting it does not wait for the data.
+ */
+export function useRevalidator() {
+ const revalidator = useRouterRevalidator();
+ const navigating = useNavigation().state !== "idle";
+ const submitting = useFetchers().some((f) => f.state === "submitting");
+ const busy = navigating || submitting;
+ const busyRef = useRef(busy);
+ busyRef.current = busy;
+
+ const revalidate = useCallback(async () => {
+ if (busyRef.current) {
+ held = true;
+ return;
+ }
+ await revalidator.revalidate();
+ }, [revalidator]);
+
+ useEffect(() => {
+ if (!busy && held) {
+ held = false;
+ void revalidator.revalidate();
+ }
+ }, [busy, revalidator]);
+
+ return useMemo(
+ () => ({ revalidate, state: revalidator.state }),
+ [revalidate, revalidator.state]
+ );
+}