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.

OEE providers: Sense machine monitoring and Unattributed Time (#1909)

Brad Barbin0934a7349dd7
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 4bf5943c0f..e1cb383510 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -3669,3 +3669,23 @@ The write was then removed (nothing reads it), so the rail always starts collaps
**Rule:** Leave an item out only when the sub-ledger can say it is closed: an invoice is marked Paid the day before the cutover by the enable. Refuse it when Carbon settles it on or after the cutover (`settledFromCutoverIds`). Any other item type (memo, payment, WIP, lease, inventory, fixed asset) has no such state and stays in the opening journal.
**Applies to:** `packages/database/src/accounting-cutover/trial-balance.ts`, `packages/server-functions/src/activate-accounting/`.
+
+## A second foreign key between two tables breaks every PostgREST embed between them
+
+**Context:** The OEE provider work (2026-10-13) added `workCenter."loadedJobOperationId"` with a foreign key to `jobOperation`, which already had `"workCenterId"` → `workCenter`.
+
+**Problem:** With two relationships between the same pair of tables, PostgREST cannot pick one, and every existing embed of one from the other (`jobOperation` → `workCenter(name)`: batches, the batch PDF, notifications) failed at runtime with PGRST201. Typecheck passed, because the generated types still compiled; only a request to an affected screen showed it.
+
+**Rule:** Before adding a foreign key, grep for embeds between the two tables in both directions (`table(` inside `.select(…)` strings). If any exist, either leave the new column without a foreign key and keep it consistent another way (an interceptor that clears it on delete), or disambiguate every embed with `table!constraint_name(…)` in the same change. When replacing a foreign key (a composite one for tenancy), drop the old one in the same migration, never add beside it.
+
+**Applies to:** migrations that add a foreign key, especially to widely embedded tables (`workCenter`, `jobOperation`, `item`, `job`).
+
+## One fact, one source: a pointer beside its own history lost the order of loads
+
+**Context:** The OEE work (2026-10-13) kept the loaded operation twice: the pointer `workCenter."loadedJobOperationId"` + `"loadedAt"`, and the history table `workCenterLoad` that the same interceptors wrote.
+
+**Problem:** The unload cleared `loadedAt` with the pointer. That timestamp was the only watermark that ordered loads: the rule "an older start never replaces a newer load" compared against it. After an unload there was nothing to compare, so a late event (a start older than the unload) loaded the operation that had been replaced, and opened a history row that overlapped its neighbours. The pointer and the history then disagreed, and the sync gave run time to the wrong operation.
+
+**Rule:** Keep one source for a fact. When a history exists, the current value is a row of it (here the open `workCenterLoad` row), not a second column to keep in step. Order writes against the history itself: refuse a write that is older than the newest boundary (any `loadedAt` or `unloadedAt`), and back it with constraints (a CHECK that an interval does not end before it starts, a partial unique index for one open row).
+
+**Applies to:** `workCenterLoad` and its interceptors (`sync_load_work_center_operation`, `sync_unload_work_center_operation`), and any "current pointer + history" pair (statuses with a status log, assignments with an assignment history).
diff --git a/.ai/plans/2026-10-12-oee-provider-integration.md b/.ai/plans/2026-10-12-oee-provider-integration.md
new file mode 100644
index 0000000000..c557629a4c
--- /dev/null
+++ b/.ai/plans/2026-10-12-oee-provider-integration.md
@@ -0,0 +1,1076 @@
+# OEE Provider integration (Sense) — implementation plan
+
+**Spec:** .ai/specs/2026-10-12-oee-provider-integration.md
+**Research:** .ai/research/oee-provider-integration.md
+**Closest sibling:** accounting providers (provider class), Rillet (API-key descriptor), Ramp (role-targeted polling), Account Mapping (Devices tab), Production → Batches (list page), job events (assign drawer)
+**Branch:** find-oee-job-operation-transcript
+
+## Progress
+
+- [x] Task 1: Write the schema migration
+- [x] Task 2: Add the interceptors, attachments and authz rules
+- [x] Task 3: Apply, ship the generated migration, regenerate types
+- [x] Task 4: Test the load and unload interceptors in SQL
+- [x] Task 5: Add the shared device lock in `@carbon/database`
+- [x] Task 6: Widen the provider role to `oee`
+- [x] Task 7: Write the OEE types and the attribution engine with tests
+- [x] Task 8: Write the Sense adapter with tests
+- [x] Task 9: Register Sense and write the OEE server functions
+- [x] Task 10: Write the sweep and sync Inngest functions
+- [x] Task 11: Add the Devices tab to the integration drawer
+- [x] Task 12: Add the Unattributed Machine Time list and drawer
+- [x] Task 13: Apply the manual-press rules in MES
+- [x] Task 14: Show the device state and the loaded operation in MES
+- [x] Task 15: Write the docs, the rule and the AGENTS.md updates
+- [x] Task 16: Run the gates and verify in the browser
+
+## Dependencies
+
+- Task 2 needs Task 1. Task 3 needs Tasks 1 and 2. Task 4 needs Task 3.
+- Task 5 needs Task 3 (types).
+- Tasks 6, 7 and 8 need nothing and can run in parallel with Tasks 1–5.
+- Task 8 needs Task 7 (the `OeeProvider` type).
+- Task 9 needs Tasks 3, 6, 7 and 8.
+- Task 10 needs Tasks 5 and 9.
+- Tasks 11 and 12 need Task 9. They are independent of each other.
+- Task 13 needs Task 5. Task 14 needs Task 3. Tasks 13 and 14 are independent of Tasks 10–12.
+- Task 15 can run after Task 9. Task 16 runs last.
+
+## Conventions for every task
+
+- Start every new source file with its SPDX header. Run `pnpm license:headers -- <paths>` after you create files.
+- Files under `packages/ee/` and files named `*.ee.tsx` get the commercial header. All others get AGPL.
+- Never use JS `Date` for parsing or arithmetic. One exception: `Date.parse` to compare two UTC instants (`.claude/rules/date-handling.md` → "Narrow exception").
+- Kysely returns `timestamptz` as a JS `Date`. Normalize it to an ISO string before you compare it or pass it on.
+- Mark every user-facing string with Lingui (`t` / `<Trans>` from `@lingui/react/macro`, `msg` for breadcrumbs).
+
+---
+
+## Task 1: Write the schema migration
+
+**Depends on:** none
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_oee-provider.sql` (from the command below)
+- Copy from (precedent): `packages/database/supabase/migrations/20260924133915_integration-provider-role.sql` (role CHECK and trigger), `packages/database/supabase/migrations/20260905132037_job-operation-batching.sql` lines 74–127 (the two views)
+
+**Steps:**
+1. Run `pnpm db:migrate:new oee-provider`.
+2. Paste the SQL below into the new file.
+3. Replace the view placeholder with lines 74–127 of `20260905132037_job-operation-batching.sql`, copied verbatim.
+
+```sql
+-- OEE provider integration (spec: .ai/specs/2026-10-12-oee-provider-integration.md)
+
+-- 1. Provider role 'oee'
+ALTER TABLE "integration" DROP CONSTRAINT IF EXISTS "integration_providerRole_check";
+ALTER TABLE "integration" ADD CONSTRAINT "integration_providerRole_check"
+ CHECK ("providerRole" IS NULL OR "providerRole" IN ('accounting', 'spend', 'oee'));
+
+-- Forked from 20260924133915_integration-provider-role.sql. One change: the
+-- 'oee' role may have several active integrations per company.
+CREATE OR REPLACE FUNCTION public.check_single_active_provider_role()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_role TEXT;
+ v_conflict TEXT;
+BEGIN
+ IF NEW."active" IS NOT TRUE THEN
+ RETURN NEW;
+ END IF;
+
+ IF TG_OP = 'UPDATE' AND OLD."active" IS TRUE THEN
+ RETURN NEW;
+ END IF;
+
+ SELECT "providerRole" INTO v_role FROM "integration" WHERE id = NEW."id";
+ IF v_role IS NULL THEN
+ RETURN NEW;
+ END IF;
+
+ -- Several OEE providers may be active at once. The one-device-per-work-center
+ -- rule lives on "workCenterDevice" instead.
+ IF v_role = 'oee' THEN
+ RETURN NEW;
+ END IF;
+
+ PERFORM pg_advisory_xact_lock(
+ hashtextextended(
+ NEW."companyId" || E'\x1f' || 'providerRole' || E'\x1f' || v_role, 0
+ )
+ );
+
+ SELECT ci."id" INTO v_conflict
+ FROM "companyIntegration" ci
+ JOIN "integration" i ON i.id = ci."id"
+ WHERE ci."companyId" = NEW."companyId"
+ AND ci."active" IS TRUE
+ AND ci."id" <> NEW."id"
+ AND i."providerRole" = v_role
+ LIMIT 1;
+
+ IF v_conflict IS NOT NULL THEN
+ RAISE EXCEPTION
+ 'Only one active % integration is allowed per company; % is already active',
+ v_role, v_conflict
+ USING ERRCODE = '23505';
+ END IF;
+
+ RETURN NEW;
+END;
+$$;
+
+INSERT INTO "integration" ("id", "jsonschema")
+VALUES ('sense', '{"type": "object", "properties": {}}'::json)
+ON CONFLICT ("id") DO NOTHING;
+
+UPDATE "integration" SET "providerRole" = 'oee'
+ WHERE "id" = 'sense' AND "providerRole" IS DISTINCT FROM 'oee';
+
+-- 2. Loaded operation (community)
+ALTER TABLE "workCenter"
+ ADD COLUMN IF NOT EXISTS "loadedJobOperationId" TEXT REFERENCES "jobOperation"("id") ON DELETE SET NULL,
+ ADD COLUMN IF NOT EXISTS "loadedAt" TIMESTAMP WITH TIME ZONE;
+
+CREATE INDEX IF NOT EXISTS "workCenter_loadedJobOperationId_idx"
+ ON "workCenter" ("loadedJobOperationId");
+
+-- 3. Machine state
+DO $$ BEGIN
+ CREATE TYPE "machineState" AS ENUM ('Running', 'Idle', 'Down', 'Offline');
+EXCEPTION WHEN duplicate_object THEN NULL;
+END $$;
+
+DO $$ BEGIN
+ CREATE TYPE "unattributedMachineTimeStatus" AS ENUM ('Open', 'Assigned', 'Dismissed');
+EXCEPTION WHEN duplicate_object THEN NULL;
+END $$;
+
+CREATE TABLE IF NOT EXISTS "workCenterDevice" (
+ "id" TEXT NOT NULL DEFAULT id('wcd'),
+ "companyId" TEXT NOT NULL,
+ "workCenterId" TEXT NOT NULL REFERENCES "workCenter"("id") ON DELETE CASCADE,
+ "integration" TEXT NOT NULL REFERENCES "integration"("id"),
+ "externalDeviceId" TEXT NOT NULL,
+ "externalSiteId" TEXT,
+ "siteTimezone" TEXT,
+ "deviceName" TEXT NOT NULL,
+ "currentState" "machineState",
+ "currentStateAt" TIMESTAMP WITH TIME ZONE,
+ "appliedThrough" TIMESTAMP WITH TIME ZONE,
+ "lastEventAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "lastManualChangeAt" TIMESTAMP WITH TIME ZONE,
+ "lastSyncedAt" TIMESTAMP WITH TIME ZONE,
+ "lastSyncError" TEXT,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "workCenterDevice_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "workCenterDevice_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "workCenterDevice_workCenter_key" UNIQUE ("workCenterId", "companyId"),
+ CONSTRAINT "workCenterDevice_device_key" UNIQUE ("integration", "externalDeviceId", "companyId")
+);
+
+CREATE INDEX IF NOT EXISTS "workCenterDevice_companyId_idx" ON "workCenterDevice" ("companyId");
+CREATE INDEX IF NOT EXISTS "workCenterDevice_integration_idx" ON "workCenterDevice" ("integration");
+CREATE INDEX IF NOT EXISTS "workCenterDevice_createdBy_idx" ON "workCenterDevice" ("createdBy");
+
+CREATE TABLE IF NOT EXISTS "machineStateChange" (
+ "id" TEXT NOT NULL DEFAULT id('msc'),
+ "companyId" TEXT NOT NULL,
+ "workCenterDeviceId" TEXT NOT NULL,
+ "workCenterId" TEXT NOT NULL REFERENCES "workCenter"("id") ON DELETE CASCADE,
+ "externalEventId" TEXT NOT NULL,
+ "state" "machineState" NOT NULL,
+ "changedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ CONSTRAINT "machineStateChange_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "machineStateChange_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "machineStateChange_event_key"
+ UNIQUE ("workCenterDeviceId", "externalEventId", "companyId")
+);
+
+CREATE INDEX IF NOT EXISTS "machineStateChange_companyId_idx" ON "machineStateChange" ("companyId");
+CREATE INDEX IF NOT EXISTS "machineStateChange_workCenter_changedAt_idx"
+ ON "machineStateChange" ("workCenterId", "changedAt");
+CREATE INDEX IF NOT EXISTS "machineStateChange_device_changedAt_idx"
+ ON "machineStateChange" ("workCenterDeviceId", "changedAt");
+
+CREATE TABLE IF NOT EXISTS "unattributedMachineTime" (
+ "id" TEXT NOT NULL DEFAULT id('umt'),
+ "companyId" TEXT NOT NULL,
+ "workCenterId" TEXT NOT NULL REFERENCES "workCenter"("id") ON DELETE CASCADE,
+ "startTime" TIMESTAMP WITH TIME ZONE NOT NULL,
+ "endTime" TIMESTAMP WITH TIME ZONE,
+ "status" "unattributedMachineTimeStatus" NOT NULL DEFAULT 'Open',
+ "productionEventId" TEXT REFERENCES "productionEvent"("id") ON DELETE SET NULL,
+ "dismissReason" TEXT,
+ "resolvedBy" TEXT REFERENCES "user"("id"),
+ "resolvedAt" TIMESTAMP WITH TIME ZONE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "unattributedMachineTime_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "unattributedMachineTime_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "unattributedMachineTime_dismiss_check"
+ CHECK ("status" <> 'Dismissed' OR "dismissReason" IS NOT NULL)
+);
+
+CREATE INDEX IF NOT EXISTS "unattributedMachineTime_companyId_idx" ON "unattributedMachineTime" ("companyId");
+CREATE INDEX IF NOT EXISTS "unattributedMachineTime_workCenterId_idx" ON "unattributedMachineTime" ("workCenterId");
+CREATE INDEX IF NOT EXISTS "unattributedMachineTime_productionEventId_idx" ON "unattributedMachineTime" ("productionEventId");
+CREATE INDEX IF NOT EXISTS "unattributedMachineTime_createdBy_idx" ON "unattributedMachineTime" ("createdBy");
+CREATE INDEX IF NOT EXISTS "unattributedMachineTime_open_idx"
+ ON "unattributedMachineTime" ("companyId", "workCenterId") WHERE "status" = 'Open';
+
+-- 4. The engine reads the open events of one work center
+CREATE INDEX IF NOT EXISTS "productionEvent_workCenterId_open_idx"
+ ON "productionEvent" ("workCenterId") WHERE "endTime" IS NULL;
+
+-- 5. Re-declare the work-center views so wc.* includes the new columns.
+-- DROP first, not CREATE OR REPLACE: the new wc.* columns expand before
+-- "locationName". Forked verbatim from 20260905132037_job-operation-batching.sql.
+-- <paste lines 74-127 of 20260905132037_job-operation-batching.sql here>
+```
+
+4. Do not write any `CREATE POLICY`, `attach_event_trigger` or handler function. Task 2 owns those.
+
+**Verify:**
+```bash
+grep -c "CREATE POLICY\|attach_event_trigger" packages/database/supabase/migrations/*_oee-provider.sql
+# Expected: 0
+grep -c 'DROP VIEW IF EXISTS "workCenters' packages/database/supabase/migrations/*_oee-provider.sql
+# Expected: 2
+```
+
+**Out of scope:** the `integration` view, any other work-center view, data backfills.
+
+---
+
+## Task 2: Add the interceptors, attachments and authz rules
+
+**Depends on:** Task 1
+**Files:**
+- Create: `packages/database/src/event-system/handlers/sync_load_work_center_operation.sql`
+- Create: `packages/database/src/event-system/handlers/sync_unload_work_center_operation.sql`
+- Modify: `packages/database/src/event-system/attachments.ts` — `productionEvent`, `jobOperation`, two new entries
+- Modify: `packages/database/src/authz/manifest.ts` — three new entries
+- Copy from (precedent): `packages/database/src/event-system/handlers/sync_set_job_operation_in_progress.sql`
+
+**Steps:**
+1. Create `sync_load_work_center_operation.sql` with this body:
+
+```sql
+CREATE OR REPLACE FUNCTION public.sync_load_work_center_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ IF p_operation != 'INSERT' THEN RETURN; END IF;
+
+ -- Only a starting event loads: an event inserted with an endTime (an ERP
+ -- entry, an assigned interval, a closed sensor run) never does.
+ IF (p_new->>'endTime') IS NOT NULL OR (p_new->>'workCenterId') IS NULL THEN
+ RETURN;
+ END IF;
+
+ UPDATE "workCenter"
+ SET "loadedJobOperationId" = p_new->>'jobOperationId',
+ "loadedAt" = (p_new->>'startTime')::timestamptz
+ WHERE "id" = p_new->>'workCenterId'
+ AND ("loadedAt" IS NULL OR "loadedAt" <= (p_new->>'startTime')::timestamptz)
+ AND "loadedJobOperationId" IS DISTINCT FROM p_new->>'jobOperationId';
+END;
+$function$;
+```
+
+2. Create `sync_unload_work_center_operation.sql` with this body:
+
+```sql
+CREATE OR REPLACE FUNCTION public.sync_unload_work_center_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ IF p_operation != 'UPDATE' THEN RETURN; END IF;
+ IF (p_new->>'status') NOT IN ('Done', 'Canceled') THEN RETURN; END IF;
+ IF (p_old->>'status') = (p_new->>'status') THEN RETURN; END IF;
+
+ UPDATE "workCenter"
+ SET "loadedJobOperationId" = NULL,
+ "loadedAt" = NULL
+ WHERE "loadedJobOperationId" = p_new->>'id';
+END;
+$function$;
+```
+
+3. In `attachments.ts`, add `after: ["sync_load_work_center_operation"]` to the `productionEvent` entry. Keep its `before`.
+4. In `attachments.ts`, append `"sync_unload_work_center_operation"` to the `after` array of the `jobOperation` entry.
+5. In `attachments.ts`, add these two entries in alphabetical order:
+
+```ts
+unattributedMachineTime: { statement: ["broadcast_table_changes"] },
+workCenterDevice: { statement: ["broadcast_table_changes"] },
+```
+
+6. In `manifest.ts`, add these three entries in alphabetical order:
+
+```ts
+machineStateChange: company("production"),
+unattributedMachineTime: company("production"),
+workCenterDevice: company("resources"),
+```
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/database
+# Expected: Tasks: 1 successful
+```
+
+**Out of scope:** `sync_finish_job_operation`, `sync_set_job_operation_in_progress`. Do not edit either handler.
+
+---
+
+## Task 3: Apply, ship the generated migration, regenerate types
+
+**Depends on:** Tasks 1, 2
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_oee-provider-rls.sql` (generated — never edit)
+- Modify: `packages/database/src/types.ts` (generated)
+- Modify: `packages/database/src/swagger-docs-schema.ts` (generated)
+
+**Steps:**
+1. Run `pnpm db:migrate`. It applies Task 1 and syncs the authz rules and handlers locally.
+2. Run `pnpm --filter @carbon/database authz migration oee-provider-rls`.
+3. Run `pnpm run generate:types`.
+4. If `pnpm db:migrate` fails on the role CHECK, STOP and report. Do not edit migration `20260924133915`.
+
+**Verify:**
+```bash
+grep -c '"workCenterDevice"\|"machineStateChange"\|"unattributedMachineTime"' packages/database/src/types.ts
+# Expected: a number greater than 6
+grep -c "loadedJobOperationId" packages/database/src/types.ts
+# Expected: a number greater than 2 (table plus the two views)
+pnpm --filter @carbon/database exec vitest run src/authz
+# Expected: all tests pass
+```
+
+**Out of scope:** `pnpm db:check:backups` and `pnpm db:check:datasets` run in Task 16.
+
+---
+
+## Task 4: Test the load and unload interceptors in SQL
+
+**Depends on:** Task 3
+**Files:**
+- Create: `packages/database/supabase/tests/work-center-loaded-operation.test.sql`
+- Copy from (precedent): `packages/database/supabase/tests/job-completion-terminal-operations.test.sql` (its `pg_temp.make_job` and `pg_temp.add_operation` fixtures, the header and the `ROLLBACK`)
+
+**Steps:**
+1. Copy the header, the `BEGIN;` and the fixture functions from the precedent.
+2. Create one work center for the fixture company.
+3. Create one job with two operations, A and B, on that work center.
+4. Assert each case below inside one `DO $cases$` block with `ASSERT`:
+ 1. Insert an open Setup event on A at 10:00. `loadedJobOperationId` is A and `loadedAt` is 10:00.
+ 2. Insert a Machine event on B with `startTime` 09:00 and `endTime` 09:30. The work center still loads A.
+ 3. Insert an open Labor event on B at 09:50. The work center still loads A (older start).
+ 4. Insert an open Labor event on B at 10:10. The work center loads B.
+ 5. Set B to `Done`. `loadedJobOperationId` and `loadedAt` are NULL.
+ 6. Insert a temporary `integration` row `oee-test` with `providerRole = 'oee'`. Activate `sense` and `oee-test` for the company. Both activations succeed.
+ 7. Activate two integrations with `providerRole = 'accounting'` for the company. The second one raises SQLSTATE `23505`.
+5. End with `RAISE NOTICE 'ALL work-center-loaded-operation TESTS PASSED';` and `ROLLBACK;`.
+
+**Verify:**
+```bash
+pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -f packages/database/supabase/tests/work-center-loaded-operation.test.sql
+# Expected: NOTICE: ALL work-center-loaded-operation TESTS PASSED
+```
+
+If the precedent fixtures need columns that changed since they were written, STOP and report — do not improvise.
+
+**Out of scope:** tests for the sync job. Task 7 covers its rules.
+
+---
+
+## Task 5: Add the shared device lock in `@carbon/database`
+
+**Depends on:** Task 3
+**Files:**
+- Create: `packages/database/src/machine-time.ts` (AGPL)
+- Modify: `packages/database/package.json` — add `"./machine-time": "./src/machine-time.ts"` next to `"./quality"`
+- Copy from (precedent): `lockIssueDispositions` in `packages/database/src/quality.ts:1481`
+
+**Steps:**
+1. Create `machine-time.ts` with these two exports:
+
+```ts
+import type { KyselyTx } from "./client";
+
+export async function lockWorkCenterDevice(
+ trx: KyselyTx,
+ args: { workCenterId: string; companyId: string }
+) {
+ return trx
+ .selectFrom("workCenterDevice")
+ .selectAll()
+ .where("workCenterId", "=", args.workCenterId)
+ .where("companyId", "=", args.companyId)
+ .forUpdate()
+ .executeTakeFirst();
+}
+
+/**
+ * An operator pressed Machine Start or Stop on a work center. If the work
+ * center has a device, end its open Machine events at the press time and
+ * record the press, so an older sensor change never undoes it.
+ */
+export async function recordManualMachinePress(
+ trx: KyselyTx,
+ args: { workCenterId: string; companyId: string; userId: string; pressedAt: string }
+): Promise<{ mapped: boolean; endedEventIds: string[] }> {
+ const device = await lockWorkCenterDevice(trx, args);
+ if (!device) return { mapped: false, endedEventIds: [] };
+
+ const ended = await trx
+ .updateTable("productionEvent")
+ .set({ endTime: args.pressedAt, updatedBy: args.userId, updatedAt: args.pressedAt })
+ .where("workCenterId", "=", args.workCenterId)
+ .where("companyId", "=", args.companyId)
+ .where("type", "=", "Machine")
+ .where("endTime", "is", null)
+ .returning("id")
+ .execute();
+
+ await trx
+ .updateTable("workCenterDevice")
+ .set({ lastManualChangeAt: args.pressedAt, updatedBy: args.userId, updatedAt: args.pressedAt })
+ .where("id", "=", device.id)
+ .where("companyId", "=", args.companyId)
+ .execute();
+
+ return { mapped: true, endedEventIds: ended.map((row) => row.id) };
+}
+```
+
+2. If `KyselyTx` is not exported from `./client`, STOP and report.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/database
+# Expected: Tasks: 1 successful
+```
+
+**Out of scope:** any MES change. Task 13 calls these functions.
+
+---
+
+## Task 6: Widen the provider role to `oee`
+
+**Depends on:** none
+**Files:**
+- Modify: `packages/ee/src/types.ts:220` — `providerRole?: "accounting" | "spend" | "oee";`
+- Modify: `packages/ee/src/index.ts:118` — `export type ProviderRole = "accounting" | "spend" | "oee";`
+- Modify: `packages/ee/src/sync/topology.ts:26` — `export type ProviderRole = "accounting" | "spend" | "oee";`
+- Modify: `packages/ee/src/integrations/secrets.ts` — add `sense: ["apiKey"],` to `SECRET_KEYS`
+- Modify: `packages/checks/src/conformance/no-integration-id-branching.ts` — add `"sense"` to `INTEGRATION_IDS` and to the provider-directory regex in `EXCLUDED`
+- Modify: `apps/erp/app/routes/x+/settings+/integrations.$id.tsx:695` and `:1893`, `apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx:87`, `apps/erp/app/routes/api+/integrations.$id.connect.ts:56` — add `| "oee"` to each inline role cast
+
+**Steps:**
+1. Make the six edits above.
+2. In `integrations.$id.tsx` (about line 706), change `producesSyncOperations` to `providerRole !== undefined && providerRole !== "oee" && integrationData.data.active`.
+3. In `IntegrationCard.tsx` (lines 86–90), skip the `roleIncumbent` lookup when `providerRole === "oee"`.
+4. In `integrations.$id.tsx` (lines 1908–1915), add `"sense"` on its own line to `FORM_SECRET_INTEGRATIONS`.
+5. Do not change `packages/ee/src/__tests__/provider-role.test.ts`. Its regex ignores `oee`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/ee
+# Expected: Tasks: 1 successful
+pnpm --filter @carbon/checks exec vitest run src/conformance/no-integration-id-branching
+# Expected: all tests pass
+```
+
+**Out of scope:** `buildIntegrationTopology`. It picks only `accounting` and `spend`, so leave it.
+
+---
+
+## Task 7: Write the OEE types and the attribution engine with tests
+
+**Depends on:** none
+**Files:**
+- Create: `packages/ee/src/oee/types.ts`
+- Create: `packages/ee/src/oee/engine.ts`
+- Create: `packages/ee/src/oee/engine.test.ts`
+- Create: `packages/ee/src/oee/index.ts` — `export * from "./types"; export * from "./engine";`
+- Modify: `packages/ee/package.json` — add `"./oee": "./src/oee/index.ts"`
+- Copy from (precedent): `packages/ee/src/ramp/config.test.ts` (test file shape)
+
+**Steps:**
+1. Write `types.ts` with the types from spec section 1: `MachineState`, `OeeDevice`, `OeeStateChange`, `OeeProvider`. Add `export type OeeProviderId = "sense";`.
+2. Write `engine.ts` with no imports outside `./types`. Export these types and `planMachineTime`:
+
+```ts
+export type StoredStateChange = { changedAt: string; state: MachineState };
+
+export type PlanMachineTimeInput = {
+ now: string;
+ minimumStateSeconds: number;
+ mappedAt: string;
+ currentState: MachineState | null;
+ currentStateAt: string | null;
+ lastManualChangeAt: string | null;
+ loadedJobOperationId: string | null;
+ loadedAt: string | null;
+ isBlocked: boolean;
+ openMachineEvent: { id: string; startTime: string } | null;
+ openUnattributed: { id: string; startTime: string } | null;
+ lastMachineEventEndTime: string | null;
+ /** Stored changes after appliedThrough, ascending by changedAt. */
+ changes: StoredStateChange[];
+};
+
+export type MachineTimeWrite =
+ | { kind: "insertMachineEvent"; jobOperationId: string; startTime: string; endTime: string | null }
+ | { kind: "closeMachineEvent"; productionEventId: string; endTime: string }
+ | { kind: "insertUnattributed"; startTime: string; endTime: string | null }
+ | { kind: "closeUnattributed"; unattributedId: string; endTime: string };
+
+export type PlanMachineTimeResult = {
+ writes: MachineTimeWrite[];
+ currentState: MachineState | null;
+ currentStateAt: string | null;
+ /** changedAt of the last consumed change; null when nothing was consumed. */
+ appliedThrough: string | null;
+};
+```
+
+3. Implement `planMachineTime` with these rules, in this order. Compare instants with `Date.parse`.
+ 1. Keep two local slots: `openEvent` and `openUnattr`. Each holds `{ id?: string; startTime: string; jobOperationId?: string }`. Seed them from the input.
+ 2. **First sync.** If `currentState` is null, split `changes` at `mappedAt`. Take the last change at or before `mappedAt` as the seed. Apply it at `mappedAt` with rule 4. Keep only the changes after `mappedAt`.
+ 3. **Debounce.** For each change, its duration ends at the next change, or at `now` for the last one. If the duration is under `minimumStateSeconds` and a next change exists, drop it and consume it. If it is the last change, stop and leave it pending.
+ 4. **Apply** `(state, at)`: set the local state and `stateAt = at`, unless the state equals the current state. If `lastManualChangeAt` is set and `at <= lastManualChangeAt`, change no slot.
+ - `Running`: if `openEvent` or `openUnattr` is set, do nothing. If not blocked, an operation is loaded and `loadedAt <= at`, open `openEvent` on it. Otherwise open `openUnattr`.
+ - `Idle`, `Down`, `Offline`: close `openEvent` and `openUnattr` at `at`. Skip a close where `at <= startTime`.
+ 5. **Close** a slot: if it has an `id`, push `closeMachineEvent` or `closeUnattributed`. If it has no `id`, push an insert with `endTime = at`.
+ 6. **Steady state.** After the loop: the state is `Running`, `stateAt > lastManualChangeAt` (or no press), and both slots are empty. Open time at `max(stateAt, lastMachineEventEndTime)` with the `Running` branch of rule 4.
+ 7. Push an insert with `endTime: null` for each new slot still open.
+ 8. Return the writes, the state, `stateAt` and the `changedAt` of the last consumed change.
+4. Write `engine.test.ts` with one `it` per case. Use fixed ISO strings and `minimumStateSeconds: 60`.
+ 1. Running with A loaded since before → one open `insertMachineEvent` on A.
+ 2. Running at 10:00, Idle at 10:30 → one `insertMachineEvent` 10:00–10:30.
+ 3. Idle with an existing open event → `closeMachineEvent`.
+ 4. Running with nothing loaded → open `insertUnattributed`.
+ 5. Running while blocked → open `insertUnattributed`.
+ 6. Running at 10:00, `loadedAt` 10:05 → open `insertUnattributed`.
+ 7. Override example: event open since 10:00, press Stop 10:03 (event closed, `lastManualChangeAt` 10:03), changes Idle 11:00 and Running 11:05 → one open `insertMachineEvent` from 11:05.
+ 8. A change at 10:02 with `lastManualChangeAt` 10:03 → no writes.
+ 9. Running 10:00, Idle 10:20:00, Running 10:20:30, Idle 11:00 → one event 10:00–11:00.
+ 10. Last change 30 s before `now` → no writes and `appliedThrough` before it.
+ 11. First sync: Running at 09:00, mapping at 10:00 → open event from 10:00.
+ 12. Steady state: Running since 09:00, nothing loaded, no slots, last event end 10:00 → open unattributed from 10:00.
+ 13. Steady state with `lastManualChangeAt` 10:03 after `stateAt` 09:00 → no writes.
+ 14. Down and Offline each close an open event.
+ 15. Running with an open manual event → no writes.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/ee exec vitest run src/oee/engine.test.ts
+# Expected: 15 passed
+```
+
+**Out of scope:** database reads and writes. Task 10 applies the writes.
+
+---
+
+## Task 8: Write the Sense adapter with tests
+
+**Depends on:** Task 7
+**Files:**
+- Create: `packages/ee/src/sense/provider.ts`
+- Create: `packages/ee/src/sense/provider.test.ts`
+- Copy from (precedent): `packages/ee/src/accounting/providers/rillet/provider.ts:421-503` (host by environment, bearer header)
+
+**Steps:**
+1. Before writing code, run this request once to confirm the date format. Expect HTTP 200.
+
+```bash
+curl -sS -o /dev/null -w "%{http_code}\n" -G "http://bifrost-staging.sensemfg.com/v1/public/companies/sites/87c419ff-42b5-4429-b54d-72a50a7dac99/stations/e1c19226-06ed-4073-8c78-373e9a4816f9/events" \
+ -H "Authorization: Bearer $SENSE_API_KEY" \
+ --data-urlencode "start_datetime=2026-10-12T00:00:00.000Z" --data-urlencode "end_datetime=2026-10-12T12:00:00.000Z" \
+ --data-urlencode "order=asc" --data-urlencode "limit=500" --data-urlencode "offset=0"
+```
+
+2. If the request does not return 200, STOP and report. (Verified 2026-10-13: Sense ignores `offset`, and `offset=0` returns 400. Steps 11–13 page by time for that reason.) Ask the user for `SENSE_API_KEY`; never commit it.
+3. Write `class SenseProvider implements OeeProvider` with `id = "sense" as const`.
+4. Use the constructor args `{ apiKey: string; environment: "production" | "staging" }`. Production is `https://bifrost.sensemfg.com`. Staging is `http://bifrost-staging.sensemfg.com`.
+5. Write a private `get<T>(path, query)`. It calls `fetch` with `Authorization: Bearer <apiKey>` and `signal: AbortSignal.timeout(15_000)`.
+6. If the response is not OK, throw `SenseApiError(status, body text)`. Export that class.
+7. `validate()` calls `GET /v1/public/companies/sites`. It returns `{ valid: true }`, or `{ valid: false, error }` on any throw.
+8. `listDevices()` calls `GET /v1/public/companies/stations` and `GET /v1/public/companies/sites` in parallel. It joins each station to its site by `site_id`.
+9. Map each station: `id`→`externalDeviceId`, `machine_name`→`name`, `site_id`→`externalSiteId`, the site's `name`→`siteName` and `timezone`→`siteTimezone`, `machine_manufacturer`→`manufacturer`, `machine_model`→`model`, `machine_type`→`machineType`.
+10. Map `last_calibration_attempt_status` to `calibrated`: `"CALIBRATED"` → true, null → null, any other value → false.
+11. `listStateChanges(device, window)` calls `GET /v1/public/companies/sites/{site}/stations/{station}/events` with `start_datetime`, `end_datetime`, `order=asc` and `limit=500`. Never send `offset`.
+12. Page by time. If a page has 500 events, request again from the last event's `created_at`.
+13. Drop events whose `id` was already returned. Stop when a page has fewer than 500 events or adds no new event.
+14. If `externalSiteId` is null, throw `SenseApiError(0, "Station has no site")`.
+15. Map `status` with this allowlist: `Active`→`Running`, `Idle`→`Idle`, `Alert`→`Down`, `Offline`→`Offline`. Throw `SenseApiError(0, "Unknown Sense status: <value>")` for any other value.
+16. Return `{ externalEventId: event.id, state, changedAt: event.created_at }`.
+17. Write `provider.test.ts` with `vi.stubGlobal("fetch", …)`. Cover four cases:
+ 1. The status allowlist maps all four values.
+ 2. An unknown status throws `SenseApiError`.
+ 3. A full page of 500 events, then a page that repeats the last event plus 3 new ones, make exactly 2 calls and return 503 changes. The second call starts at the last event's `created_at` and sends no `offset`.
+ 4. `listDevices` joins the site name and timezone.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/ee exec vitest run src/sense/provider.test.ts
+# Expected: 4 passed
+```
+
+**Out of scope:** telemetry, calibration and partner endpoints.
+
+---
+
+## Task 9: Register Sense and write the OEE server functions
+
+**Depends on:** Tasks 3, 6, 7, 8
+**Files:**
+- Create: `packages/ee/src/sense/config.tsx`
+- Create: `packages/ee/src/sense/hooks.server.ts`
+- Create: `packages/ee/src/oee/registry.ts`
+- Create: `packages/ee/src/oee/service.server.ts`
+- Modify: `packages/ee/src/index.ts` — import and add `Sense` to `integrations`; `export { Sense } from "./sense/config";`
+- Modify: `packages/ee/src/hooks.server.ts` — add `sense: { onHealthcheck: senseHealthcheck },`
+- Modify: `packages/ee/package.json` — add `"./oee.server": "./src/oee/service.server.ts"` and `"./sense/hooks.server": "./src/sense/hooks.server.ts"`
+- Copy from (precedent): `packages/ee/src/rillet/config.tsx`, `packages/ee/src/rillet/hooks.server.ts`, `packages/ee/src/rules/service.server.ts:90` (`requireEntitlement` call)
+
+**Steps:**
+1. Write `config.tsx` from the Rillet descriptor. Use `id: "sense"`, `name: "Sense"`, `category: "Machine Monitoring"` and `providerRole: "oee" as const`.
+2. Give it 3 settings in one group, "Connection":
+ - `apiKey`: `type: "secret"`, required.
+ - `environment`: `type: "options"`. Production (`bifrost.sensemfg.com`) and Staging (`bifrost-staging.sensemfg.com — testing only, plain HTTP`). Default `production`.
+ - `minimumStateSeconds`: `type: "number"`, default `60`.
+3. Use this schema: `z.object({ apiKey: z.string(), environment: z.enum(["production", "staging"]).default("production"), minimumStateSeconds: z.coerce.number().int().min(0).default(60) })`.
+4. Write `SetupInstructions`: "Create a company API key in Sense, paste it below, then map each station on the Devices tab."
+5. Write `registry.ts`:
+
+```ts
+import { SenseProvider } from "../sense/provider";
+import type { OeeProvider } from "./types";
+
+type OeeProviderFactory = (args: { apiKey: string; environment: string }) => OeeProvider;
+
+export const OEE_PROVIDERS: Record<string, OeeProviderFactory> = {
+ sense: (args) =>
+ new SenseProvider({
+ apiKey: args.apiKey,
+ environment: args.environment === "staging" ? "staging" : "production"
+ })
+};
+```
+
+6. Write `service.server.ts` with these exports. Every write takes `client` first and `db: Kysely<KyselyDatabase>` second, and returns `{ data, error }`.
+ - `getOeeProvider(serviceClient, companyId, integrationId)` → `{ data: { provider: OeeProvider; minimumStateSeconds: number } | null; error: string | null }`.
+ 1. If `companyHasFeature(serviceClient, companyId, { feature: "INTEGRATIONS" })` is false, return the error `"Not entitled"`.
+ 2. Read `companyIntegration` (`metadata`, `secretRef`, `active`) for the company and integration.
+ 3. Run `resolveIntegrationSecrets(serviceClient, companyId, integrationId, metadata, secretRef)`.
+ 4. Look up `OEE_PROVIDERS[integrationId]`. If it is missing, or `metadata.apiKey` is empty, return an error.
+ 5. Build the provider. Read `minimumStateSeconds` from metadata (default 60).
+ - `upsertWorkCenterDevice(client, db, { companyId, userId, integration, externalDeviceId, externalSiteId, siteTimezone, deviceName, workCenterId })`.
+ 1. Call `requireEntitlement(client, companyId, "INTEGRATIONS")`.
+ 2. In one transaction, read the row for `(integration, externalDeviceId, companyId)`.
+ 3. If its `workCenterId` already equals the input, return it unchanged.
+ 4. Read the row of the target work center. If it belongs to another device, return the error `"<work center> already has <deviceName> from <integration>"`.
+ 5. Delete the old row of this device, then insert a new one with `createdBy = userId`. A remap starts fresh: new `createdAt`, null state.
+ - `deleteWorkCenterDevice(client, db, { companyId, integration, externalDeviceId })` calls `requireEntitlement`, then deletes the row.
+ - `assignUnattributedMachineTime(client, db, { companyId, userId, unattributedMachineTimeId, jobOperationId })`.
+ 1. Call `requireEntitlement`.
+ 2. In one transaction, lock the row with `forUpdate()`. Require `status = 'Open'` and a non-null `endTime`.
+ 3. Read the operation. Require the same `companyId` and a status that is not `Done` or `Canceled`.
+ 4. Insert a `productionEvent` with `type: "Machine"`, the row's `workCenterId`, `startTime` and `endTime`, `employeeId: null` and `createdBy: userId`. Return its `id`.
+ 5. Set the row to `Assigned` with `productionEventId`, `resolvedBy`, `resolvedAt`, `updatedBy` and `updatedAt`. Use `datetime.timestamp()` for the times.
+ - `dismissUnattributedMachineTime(client, db, { companyId, userId, unattributedMachineTimeId, dismissReason })` calls `requireEntitlement`. It requires `status = 'Open'`, then sets `Dismissed`, the reason, `resolvedBy` and `resolvedAt`.
+ - Wrap each body in `try/catch`. Return `{ data: null, error: message }` on failure, and let `EntitlementError` propagate.
+7. Write `hooks.server.ts`. `senseHealthcheck(companyId, metadata)` builds the provider from `metadata.apiKey` and `metadata.environment` through `OEE_PROVIDERS.sense`. It returns `{ healthy: valid, reason: error }`.
+8. Run `pnpm license:headers -- packages/ee/src/oee packages/ee/src/sense`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/ee
+# Expected: Tasks: 1 successful
+pnpm --filter @carbon/ee test
+# Expected: all tests pass
+```
+
+**Out of scope:** any route. `config.tsx` must not import a `.server` module (`packages/ee/AGENTS.md`).
+
+---
+
+## Task 10: Write the sweep and sync Inngest functions
+
+**Depends on:** Tasks 5, 9
+**Files:**
+- Create: `packages/jobs/src/inngest/functions/integrations/oee-sweep.ts`
+- Create: `packages/jobs/src/inngest/functions/integrations/oee-sync.ts`
+- Create: `packages/jobs/src/inngest/functions/integrations/oee-sync-device.ts`
+- Modify: `packages/jobs/src/inngest/functions/integrations/index.ts` — export both functions
+- Modify: `packages/jobs/src/inngest/index.ts` — import both and add them to `functions` under `// Integrations`
+- Modify: `packages/lib/src/events.ts` — add the `carbon/oee-sync` event type
+- Copy from (precedent): `packages/jobs/src/inngest/functions/integrations/ramp-sweep.ts`, `ramp-sync.ts:48-57`, `ramp-sync-bill-stage.ts:63-82` (Kysely transaction with `forUpdate`)
+
+**Steps:**
+1. Add the event type to `events.ts`, next to `"carbon/ramp-sync"`:
+
+```ts
+ "carbon/oee-sync": {
+ data: {
+ companyId: string;
+ integrationId: string;
+ };
+ };
+```
+
+2. Write `oee-sweep.ts` from `ramp-sweep.ts`. Use id `"oee-sweep"` and cron `"*/2 * * * *"`.
+3. In one `step.run("find-oee-sync-targets")`, select distinct `(companyId, integration)` pairs with Kysely (`getJobDatabaseClient()`).
+4. Join `workCenterDevice` to `companyIntegration` on `id = integration` and `companyId`. Filter on `active = true` and `integration IN getIntegrationIdsByRole("oee")`.
+5. Send one `carbon/oee-sync` event per pair with `step.sendEvent("dispatch-oee-sync", …)`.
+6. Write `oee-sync.ts` from `ramp-sync.ts`: id `"oee-sync"`, `retries: 2`, `concurrency: { key: "event.data.companyId", limit: 1 }`.
+7. In one `step.run("sync-devices")`:
+ 1. Call `getOeeProvider(getCarbonServiceRole(), companyId, integrationId)`. If it errors, return `{ skipped: error }`.
+ 2. Read every `workCenterDevice` row of the company and integration.
+ 3. For each device, `await syncOeeDevice(...)` inside `try/catch`.
+ 4. On a throw, set `lastSyncError` (the message, at most 500 characters) on that device only.
+8. Write `oee-sync-device.ts` with `export async function syncOeeDevice({ db, provider, device, minimumStateSeconds })`:
+ 1. Set `now = datetime.timestamp()`.
+ 2. Set `since`: if `device.currentState` is null, use `mappedAt − 24 h`. Otherwise use `device.lastEventAt − 10 min`. Compute both with `parseAbsolute(iso, "UTC").subtract(...).toAbsoluteString()` from `@internationalized/date`.
+ 3. Call `provider.listStateChanges({ externalDeviceId, externalSiteId }, { since, until: now })`.
+ 4. Insert each change into `machineStateChange` with `onConflict((oc) => oc.columns(["workCenterDeviceId", "externalEventId", "companyId"]).doNothing())`. Do not set `createdBy`.
+ 5. Open `db.transaction().execute(async (trx) => …)`.
+ 6. Call `lockWorkCenterDevice(trx, …)` from `@carbon/database/machine-time`. If it returns nothing, a user removed the mapping. Return.
+ 7. Read the `planMachineTime` inputs:
+ - `workCenter.loadedJobOperationId` and `loadedAt`.
+ - `workCentersWithBlockingStatus.isBlocked`.
+ - The open Machine `productionEvent` of the work center (`endTime IS NULL`, any creator).
+ - The open `unattributedMachineTime` row (`status = 'Open'`, `endTime IS NULL`).
+ - The latest `endTime` of a Machine event on the work center.
+ - The `machineStateChange` rows with `changedAt > appliedThrough` (or `> since` when null), ascending.
+ 8. Normalize every `Date` from Kysely to an ISO string with a local `toInstant(value)` helper.
+ 9. Call `planMachineTime`.
+ 10. Apply each write in order:
+ - `insertMachineEvent` → insert into `productionEvent` with `type: "Machine"`, `workCenterId`, `employeeId: null`, `companyId` and `createdBy: "system"`.
+ - `closeMachineEvent` → update `endTime`, `updatedBy: "system"` and `updatedAt: now`, where `endTime IS NULL`.
+ - `insertUnattributed` → insert with `createdBy: "system"`.
+ - `closeUnattributed` → update `endTime`, `updatedBy: "system"` and `updatedAt: now`.
+ 11. Update the device: `currentState`, `currentStateAt`, `appliedThrough` (only when not null), `lastEventAt = now`, `lastSyncedAt = now` and `lastSyncError = null`.
+9. Export both functions from `integrations/index.ts` and register them in `inngest/index.ts`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/jobs
+# Expected: Tasks: 1 successful
+pnpm --filter @carbon/jobs test
+# Expected: all tests pass
+```
+
+If Kysely has no type for the view `workCentersWithBlockingStatus`, read `maintenanceDispatch` directly with the view's predicate (`status = 'In Progress'`, `oeeImpact IN ('Down', 'Planned')`).
+
+**Out of scope:** GL posting. The existing operation-finish sweep posts these events.
+
+---
+
+## Task 11: Add the Devices tab to the integration drawer
+
+**Depends on:** Task 9
+**Files:**
+- Create: `apps/erp/app/modules/settings/ui/Integrations/OeeDevices.ee.tsx`
+- Modify: `apps/erp/app/modules/settings/settings.models.ts` — add `workCenterDeviceUpsertValidator`
+- Modify: `apps/erp/app/routes/x+/settings+/integrations.$id.tsx` — loader data, tab, action intent
+- Copy from (precedent): `apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsx` (`AccountMappingRowForm`, lines 418–560; props and `tabs` slot, lines 94–110, 299–301)
+
+**Steps:**
+1. Add the validator to `settings.models.ts`:
+
+```ts
+export const workCenterDeviceUpsertValidator = z.object({
+ intent: z.literal("upsert-work-center-device"),
+ externalDeviceId: z.string().min(1, { message: "Device is required" }),
+ deviceName: z.string().min(1, { message: "Device name is required" }),
+ externalSiteId: zfd.text(z.string().optional()),
+ siteTimezone: zfd.text(z.string().optional()),
+ workCenterId: zfd.text(z.string().optional())
+});
+```
+
+2. In the route file, add a module-level `async function getOeeDevicesTabData(client, companyId, integrationId)`. Model it on `getAccountMappingTabData` (lines 280–324). It returns `{ devices, mappings, takenWorkCenters, workCenters, error }`:
+ 1. `getOeeProvider(getCarbonServiceRole(), companyId, integrationId)`, then `provider.listDevices()`. On a throw, set `devices: []` and `error` to the message.
+ 2. `mappings`: `workCenterDevice` rows (`externalDeviceId, workCenterId, currentState, lastSyncedAt, lastSyncError`) for this company and integration.
+ 3. `takenWorkCenters`: `workCenterDevice` rows (`workCenterId, deviceName, integration`) for this company with another integration.
+ 4. `workCenters`: `workCenter` rows `id, name, location(timezone)`, filtered on `companyId` and `active = true`.
+3. In the loader, compute `devices = providerRole === "oee" && integrationData.data.active ? await getOeeDevicesTabData(...) : null`. Add `devices` to the return at lines 1141–1150. Add `devices: null` to the early return at lines 679–690.
+4. Add the action branch, before the install fall-through:
+ 1. Validate with `workCenterDeviceUpsertValidator`.
+ 2. If `workCenterId` is empty, call `deleteWorkCenterDevice(client, getDatabaseClient(), …)`.
+ 3. Otherwise call `upsertWorkCenterDevice(client, getDatabaseClient(), …)`.
+ 4. On error, return `data({}, await flash(request, error(result.error, "Failed to save device mapping")))`.
+ 5. On success, return `data({}, await flash(request, success("Saved device mapping")))`.
+5. Write `OeeDevices.ee.tsx` from `AccountMapping.tsx`. Use local structural row types; do not import them from `@carbon/ee` (TS2589). Show `tabs` first inside `DrawerBody`.
+6. Give each device one row form, keyed `` `${device.externalDeviceId}:${mapping?.workCenterId ?? ""}` ``.
+ - Left: the device name, then manufacturer, model and machine type as muted text, then the site name.
+ - Show a "Calibrated" or "Not calibrated" badge.
+ - Show `currentState`, `lastSyncedAt` (`formatTimeAgo`) and `lastSyncError` in red when set.
+ - Right: a `Combobox name="workCenterId"` of `workCenters`, a `Submit` and the hidden fields of the validator.
+7. Leave the work centers in `takenWorkCenters` out of the options.
+8. If the device's `siteTimezone` differs from the selected work center's `location.timezone`, show `LuTriangleAlert` with a `Tooltip`. The tooltip text is "Sense site is in <siteTimezone>; Carbon uses <locationTimezone>".
+9. If `error` is set, show it above the list.
+10. If `usePlanGate({ feature: "INTEGRATIONS" }).isGated`, render `RulesUpgradeOverlay` (`~/components/RulesUpgradeOverlay`) in place of the list.
+11. Push the tab first in the `tabs` array (lines 2172–2189): `{ value: "devices", label: <Trans>Devices</Trans>, content: (tabBar) => <OeeDevices tabs={tabBar} {...devices} /> }`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: Tasks: 1 successful
+```
+
+**Out of scope:** Sync Activity for `oee` (Task 6 hides it). Matching by name and AI suggestions are out of scope.
+
+---
+
+## Task 12: Add the Unattributed Machine Time list and drawer
+
+**Depends on:** Task 9
+**Files:**
+- Create: `apps/erp/app/routes/x+/production+/machine-time.tsx`
+- Create: `apps/erp/app/routes/x+/production+/machine-time.$id.tsx`
+- Create: `apps/erp/app/modules/production/ui/MachineTime/MachineTimeTable.ee.tsx`
+- Create: `apps/erp/app/modules/production/ui/MachineTime/MachineTimeDrawer.ee.tsx`
+- Create: `apps/erp/app/modules/production/ui/MachineTime/MachineTimeUpgradeOverlay.ee.tsx`
+- Modify: `apps/erp/app/modules/production/production.service.ts` — 3 reads
+- Modify: `apps/erp/app/modules/production/production.models.ts` — 2 validators and `unattributedMachineTimeStatuses`
+- Modify: `apps/erp/app/utils/path.ts` — 2 paths
+- Modify: `apps/erp/app/modules/production/ui/useProductionSubmodules.tsx` — 1 nav item
+- Copy from (precedent): `apps/erp/app/routes/x+/production+/batches.tsx` and `batches.$batchId.tsx` (list and drawer routes); `apps/erp/app/modules/production/ui/ScrapReasons/ScrapReasonsTable.tsx` (table skeleton); the status column of `BatchesTable.tsx`; `apps/erp/app/modules/production/ui/Jobs/ProductionEventForm.tsx` (Drawer and ValidatedForm); `apps/erp/app/modules/settings/ui/Webhooks/WebhooksUpgradeOverlay.tsx` (overlay); `apps/erp/app/routes/x+/production+/scrap-reasons.$scrapReasonId.tsx` (action shape)
+
+**Steps:**
+1. Add to `path.ts`, in alphabetical order:
+ - `` unattributedMachineTime: (id: string) => generatePath(`${x}/production/machine-time/${id}`), ``
+ - `` unattributedMachineTimes: `${x}/production/machine-time`, ``
+2. Add to `production.models.ts`:
+
+```ts
+export const unattributedMachineTimeStatuses = ["Open", "Assigned", "Dismissed"] as const;
+
+export const assignMachineTimeValidator = z.object({
+ intent: z.literal("assign"),
+ jobOperationId: z.string().min(1, { message: "Operation is required" })
+});
+
+export const dismissMachineTimeValidator = z.object({
+ intent: z.literal("dismiss"),
+ dismissReason: z.string().min(1, { message: "Reason is required" })
+});
+```
+
+3. Add three reads to `production.service.ts`:
+ - `getUnattributedMachineTimes(client, companyId, args: GenericQueryFilters & { search: string | null })`: select `*, workCenter(name, location(timezone))` with `{ count: LIST_COUNT }`. If `search` is set, filter `workCenter.name` with `ilike`. Use the default sort `startTime` descending (copy `getJobOperationBatches`).
+ - `getUnattributedMachineTime(client, id, companyId)`: the same select, `.single()`.
+ - `getMachineTimeOperationCandidates(client, { workCenterId, companyId })`. Run two queries in `Promise.all`, then rank in memory:
+ 1. `jobOperation` rows `id, description, status, job(jobId)` on the work center, status not `Done` or `Canceled`, `limit(500)`.
+ 2. `productionEvent` rows `jobOperationId, startTime` on the work center, latest first, `limit(200)`.
+ 3. Put `In Progress` first, then the latest event start, then the description.
+ 4. Return `{ value, label: "<jobId> · <description>", helper: status }[]`.
+4. Write `machine-time.tsx` from `batches.tsx`:
+ - `handle.breadcrumb: msg\`Unattributed Machine Time\``.
+ - `requirePermissions({ view: "production", role: "employee" })`.
+ - Render `<MachineTimeTable>` and `<RecordOutlet />`.
+ - If `usePlanGate({ feature: "INTEGRATIONS" }).isGated`, render `<MachineTimeUpgradeOverlay />`.
+5. Write `MachineTimeTable.ee.tsx` from `ScrapReasonsTable.tsx`. Use 5 columns:
+ - Work center: a `Hyperlink` to the row id.
+ - Start and End: `formatDateTimeInZone(value, timeZone, locale)` inside `DateTime` with `locationTimeZone`, as `TimelineDetail.tsx:152-159` does.
+ - Duration: `formatPreciseDuration`, or "Running" while `endTime` is null.
+ - Status: a static filter over `unattributedMachineTimeStatuses`.
+ - No `primaryAction`.
+6. Write `machine-time.$id.tsx` from `scrap-reasons.$scrapReasonId.tsx`:
+ 1. The loader calls `requirePermissions({ view: "production", role: "employee" })`, `getUnattributedMachineTime` and `getMachineTimeOperationCandidates`.
+ 2. The action calls `assertIsPost` and `requirePermissions({ update: "production" })`, then branches on `intent`.
+ 3. `assign`: validate, then read the operation's `jobId`.
+ 4. Apply the job-lock check copied from `$jobId.events.new.tsx` (`requireUnlocked` / `isJobLocked`).
+ 5. Call `assignUnattributedMachineTime(client, getDatabaseClient(), …)`. Do not post to the GL.
+ 6. `dismiss`: validate, then call `dismissUnattributedMachineTime(client, getDatabaseClient(), …)`.
+ 7. On success, `throw redirect(path.to.unattributedMachineTimes, await flash(request, success(...)))`. On error, return `data({}, await flash(request, error(...)))`.
+7. Write `MachineTimeDrawer.ee.tsx` from `ProductionEventForm.tsx`: `Drawer open onOpenChange`, `DrawerHeader` "Unattributed machine time".
+ - Show the work center, start, end and duration as read-only text.
+ - If `status` is not `Open`, show the status and the resolution only.
+ - If `endTime` is null, show "The machine is still running" and no forms.
+ - Otherwise show two `ValidatedForm`s: Assign (`Combobox name="jobOperationId"` with the candidates, `Submit` "Assign") and Dismiss (`TextArea name="dismissReason"`, `Submit` "Dismiss").
+ - Each form has a hidden `intent`.
+8. Write `MachineTimeUpgradeOverlay.ee.tsx` from `WebhooksUpgradeOverlay.tsx`. Show 3 mock rows and the title "Unattributed machine time".
+9. Add the nav item after Batches: `{ name: t\`Unattributed Machine Time\`, to: \`${path.to.unattributedMachineTimes}?filter=status:eq:Open\`, icon: <LuTimerOff />, role: "employee" }`.
+10. If the nav item does not show as active with the query string, use `path.to.unattributedMachineTimes` alone.
+11. In that case, add no default filter.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: Tasks: 1 successful
+```
+
+**Out of scope:** splitting one row across operations, bulk assign, and an MES prompt.
+
+---
+
+## Task 13: Apply the manual-press rules in MES
+
+**Depends on:** Task 5
+**Files:**
+- Modify: `apps/mes/app/routes/x+/event.tsx` — Start and End branches
+- Modify: `apps/mes/app/routes/x+/start.$operationId.tsx` — Machine branch (lines 242–281)
+- Copy from (precedent): `apps/mes/app/services/quality.server.ts:885-930` (MES Kysely transaction)
+
+**Steps:**
+1. In `event.tsx`, import `recordManualMachinePress` from `@carbon/database/machine-time`.
+2. Set `const pressedAt = datetime.timestamp();` once, after validation.
+3. **Start branch.** If `d.type === "Machine"` and `d.workCenterId` is set, run this before `startProductionEvent`:
+ `await getDatabaseClient().transaction().execute((trx) => recordManualMachinePress(trx, { workCenterId: d.workCenterId!, companyId, userId, pressedAt }))`.
+4. Pass `startTime: pressedAt` to `startProductionEvent`.
+5. **End branch.** If `d.type === "Machine"` and `d.workCenterId` is set, run the same call before `endProductionEvent`.
+6. Pass `endTime: pressedAt` to `endProductionEvent`. Keep the existing GL posting step unchanged.
+7. In `start.$operationId.tsx`, inside `if (type === "Machine")`, set `pressedAt = datetime.timestamp()`.
+8. If `jobOperation.data.workCenterId` is set, call `recordManualMachinePress` with it first.
+9. Pass `startTime: pressedAt` to `startProductionEvent` for every type.
+10. Leave the Setup and Labor paths unchanged.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=mes
+# Expected: Tasks: 1 successful
+pnpm --filter mes test
+# Expected: all tests pass
+```
+
+**Out of scope:** End Shift and maintenance Down. They keep their current behavior; the steady-state rule reopens time after them.
+
+---
+
+## Task 14: Show the device state and the loaded operation in MES
+
+**Depends on:** Task 3
+**Files:**
+- Modify: `apps/mes/app/services/operations.service.ts` — add `getWorkCenterDevice` after `getWorkCenter` (line 2114)
+- Modify: `apps/mes/app/routes/x+/operation.$operationId.tsx` — load the device
+- Modify: `apps/mes/app/components/JobOperation/JobOperation.tsx` — prop, realtime, pass-through
+- Modify: `apps/mes/app/components/JobOperation/components/Controls.tsx` — badge in `WorkTypeToggle` (lines 240–254)
+- Modify: `apps/mes/app/services/display.service.ts` — loaded operation and device state
+- Modify: `apps/mes/app/routes/display+/$workCenterId.work.tsx` — render them
+- Copy from (precedent): `useChangedRows` on `productionEvent` in `apps/mes/app/components/JobOperation/hooks/useOperation.tsx:135-165`; `Badge` usage in `JobOperation.tsx:943`
+
+**Steps:**
+1. Add `getWorkCenterDevice(client, { workCenterId, companyId })`. It selects `id, deviceName, currentState, currentStateAt` from `workCenterDevice` and calls `.maybeSingle()`.
+2. In the operation loader, await it with `serviceRole` when the operation has a `workCenterId`. Return it as `workCenterDevice`.
+3. In `JobOperation.tsx`, keep the device in state.
+4. Subscribe with `useChangedRows({ companyId, table: "workCenterDevice", filter: \`workCenterId=eq.${operation.workCenterId}\`, onChange })` and update the state.
+5. Pass `deviceState={device?.currentState ?? null}` to `WorkTypeToggle`.
+6. In `WorkTypeToggle`, under the Machine label, render `<Badge>` when `deviceState` is set:
+ - `Running` → variant `green`, text "Running".
+ - `Idle` → `outline`, "Idle".
+ - `Down` → `red`, "Down".
+ - `Offline` → `outline`, "Offline".
+ - Translate each text with `t`.
+7. In `display.service.ts`, add `loadedJobOperationId` to the `DisplayWorkCenter` type and to the select in `getDisplayWorkCenter`. The view now carries the column.
+8. Add `getDisplayLoadedOperation(client, { jobOperationId, companyId })`. It selects `id, description, job:jobId(jobId)` from `jobOperation`.
+9. In `$workCenterId.work.tsx`, load the loaded operation and `getWorkCenterDevice`. Render one line above the active work: "Loaded: <jobId> · <description>", plus the device badge from step 6.
+10. Hide each part that has no data.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=mes
+# Expected: Tasks: 1 successful
+```
+
+**Out of scope:** an MES prompt for unattributed time.
+
+---
+
+## Task 15: Write the docs, the rule and the AGENTS.md updates
+
+**Depends on:** Task 9
+**Files:**
+- Create: `docs/content/docs/integrations/oee.mdx`
+- Modify: `docs/content/docs/integrations/meta.json` — add `"oee"`
+- Modify: `docs/content/docs/reference/work-centers.mdx` — add a "Loaded operation" section
+- Create: `.claude/rules/oee-provider.md` (with `paths:` frontmatter for `packages/ee/src/oee/**`, `packages/ee/src/sense/**`, `packages/jobs/src/inngest/functions/integrations/oee-*.ts`, `packages/database/src/machine-time.ts`)
+- Modify: `AGENTS.md` — add a Task Router row "OEE providers / machine monitoring" → `.claude/rules/oee-provider.md`
+- Modify: `packages/jobs/AGENTS.md` — add `oee-sweep` and `oee-sync` to "Durable Entry Points"
+- Modify: `apps/erp/app/modules/production/AGENTS.md` — add the loaded operation and unattributed machine time
+- Copy from (precedent): `docs/content/docs/integrations/accounting.mdx` (guide shape), `.claude/rules/ramp-integration.md` (rule shape)
+
+**Steps:**
+1. Load the `carbon-docs` skill before you write the docs page.
+2. Write the guide in four sections:
+ 1. What an OEE provider is.
+ 2. Install Sense: Settings → Integrations → Sense.
+ 3. Map devices on the Devices tab.
+ 4. How machine time reaches a job: the loaded operation, the Machine button override, unattributed time.
+3. Ground each claim in the code from Tasks 9–14.
+4. Write the rule file. Summarize the attribution rules from spec section 5 and the sync from section 7, and name the files.
+5. Write all prose in STE-80.
+
+**Verify:**
+```bash
+pnpm --filter docs typecheck
+# Expected: no errors
+```
+
+**Out of scope:** a changelog entry. Write it when the feature ships.
+
+---
+
+## Task 16: Run the gates and verify in the browser
+
+**Depends on:** all tasks
+**Files:** generated artifacts only
+
+**Steps:**
+1. Run `pnpm lingui:extract`. Then run `/translate` for the new strings.
+2. Run `pnpm generate:mcp`, because new reads in `production.service.ts` become MCP tools.
+3. Run the gates below in order. Fix each failure before the next one.
+4. Run `/test` with this playbook. Get the staging key from the user; never commit it.
+ 1. Install Sense with the staging key. The connection is healthy, and the Devices tab lists 55 stations.
+ 2. Map Station 0002 to work center W1. Try a second station on W1; the message names Station 0002.
+ 3. Map a `Reston - 2` station to a work center in `America/New_York`. The timezone warning shows.
+ 4. In MES, start and stop Setup on operation A at W1. W1 loads A (the work-center display shows it).
+ 5. Wait for 2 sweep runs (4 minutes) with the station Active. A shows a Machine event with no employee.
+ 6. Press Machine Stop in MES. The event ends at the press. The next sync does not reopen it.
+ 7. Complete A while the station is Active. Production → Machine Time shows an Open row.
+ 8. Wait until the station is Idle. Assign the row to operation B. B's Events tab shows the Machine event.
+ 9. Dismiss another row without a reason. Validation fails. With a reason, the row is Dismissed.
+ 10. Finish operation A in MES. Run `select "postedToGL" from "productionEvent" where "jobOperationId" = '<A>' and "type" = 'Machine'`. Every row is `true`.
+ 11. On a work center with no device, start and stop the Machine timer. It behaves as before: no badge, and the event posts on Stop.
+ 12. If the dev company has no `INTEGRATIONS` feature, check that the Devices tab and the list show the upgrade overlay. Otherwise report this step as skipped.
+
+**Verify:**
+```bash
+pnpm run lint
+# Expected: no errors
+pnpm exec turbo run typecheck --filter=@carbon/database --filter=@carbon/ee --filter=@carbon/jobs --filter=erp --filter=mes
+# Expected: Tasks: 5 successful
+pnpm --filter @carbon/ee test && pnpm --filter @carbon/jobs test && pnpm --filter mes test
+# Expected: all tests pass
+pnpm --filter @carbon/checks clobbers
+# Expected: no clobbered definitions
+pnpm db:check:backups
+# Expected: success; packages/jobs/manifests/schema.json updated
+pnpm db:check:datasets
+# Expected: success
+```
+
+**Out of scope:** demo-dataset rows for the new tables, a changelog entry and a production Sense key.
diff --git a/.ai/plans/2026-10-13-oee-review-followups.md b/.ai/plans/2026-10-13-oee-review-followups.md
new file mode 100644
index 0000000000..84b6dd09d7
--- /dev/null
+++ b/.ai/plans/2026-10-13-oee-review-followups.md
@@ -0,0 +1,788 @@
+# OEE provider — review follow-ups — implementation plan
+
+**Spec:** .ai/specs/2026-10-12-oee-provider-integration.md
+**Rule:** .claude/rules/oee-provider.md
+**Source of the work:** the nuclear self-review of PR #1909. Its six Must-fix items are done in `5bb79d0b1a`. This plan covers every remaining Risk and Suggestion.
+**Closest sibling:** none. No new record type.
+**Branch:** find-oee-job-operation-transcript
+
+## Progress
+- [x] Task 1: Make the OEE work center foreign keys company-scoped and fix the indexes
+- [x] Task 2: Unload an operation when it moves to another work center
+- [x] Task 3: Ignore load-pointer changes in the event and broadcast filters
+- [x] Task 4: Tidy the engine slots, always close a slot, and merge repeated states
+- [x] Task 5: Stop a sync run when the provider is unavailable
+- [x] Task 6: Fix the sync cursor, log late events, and close Canceled operations
+- [x] Task 7: Test `syncOeeDevice` against the local database
+- [x] Task 8: Resolve an OEE provider in one place
+- [x] Task 9: Make machine time one stream per work center
+- [x] Task 10: End the MES event on its own work center
+- [x] Task 11: Hide a stale device state on the work center display
+- [x] Task 12: Fix the machine time service reads
+- [x] Task 13: Add filters to the Unattributed Time list
+- [x] Task 14: Make the review queue match the filtered list and skip running rows
+- [x] Task 15: Polish the review drawer
+- [x] Task 16: Move the Devices tab server code out of the route and fix its gaps
+- [x] Task 17: Update the rule, AGENTS.md files and the guide
+- [x] Task 18: Verify in the browser
+
+## Decisions taken
+
+The human approves these with the plan. Each one closes a review item.
+
+| Review item | Decision | Why |
+|---|---|---|
+| A Pause ends every Machine event on the work center | Keep it, and make it true on every work center. A machine has one machine time. A Machine press ends every open Machine event on its work center, from any operator or the sensor. | The human's rule: separate operators share a single machine time. Without a device, two operators' Machine timers can overlap today. |
+| The MES press and the event write are not atomic | Keep the press before the event write. No task. | If the start fails, the operator sees the error and retries, and the retry repairs it. The reverse order risks double-counted time that nothing repairs. |
+| Late events before `appliedThrough` are dropped | Do not replan history. Fix the cursor and log each late event. | Replanning means rewriting closed events, maybe already posted to the GL. |
+| The queue ignores the list's search and sort | The queue honors the list's search and filters. The list allows no column sort. | One order for the list and the queue: newest start first, then `id`. |
+| The list has no filters | Add 5 filters: work center, location, start date, end date, and state (Running / Stopped) | The human asked for date and column filters. |
+| Date filters on a timestamp column | The route turns each date range into instants at the company's day boundaries. The generic `between` filter is not used for them. | The generic filter compares a timestamp with a bare date: it drops the last day and uses UTC days. |
+| Review opens a running row | The queue holds stopped rows only. A running row opens but is outside the queue. | A running row cannot be answered. |
+| A sync run piles up during a Sense outage | Stop the run at the first "provider unavailable" error. Add `singleton` skip per company and integration. | The sweep sends a new run every 2 minutes anyway. |
+| Device state goes stale on the display | Hide the state when `lastSyncError` is set or `lastSyncedAt` is more than 10 minutes old | 10 minutes is 5 sync periods. |
+| The Devices tab calls Sense after each pick | Cache the provider's device list in Redis for 60 seconds | A mapping change does not change the provider's device list. |
+
+## Not doing
+
+| Review item | Why not |
+|---|---|
+| Fold the create-then-drop migrations into the first two | Three of the branch's migrations are generated authz migrations, and those are never hand-edited. Local databases have also applied them. |
+| Stop webhook and workflow events for load-pointer changes | `dispatch_event_batch` sends every UPDATE to WEBHOOK, WORKFLOW and SYNC subscriptions by design: their payload is a contract. Task 3 stops the audit, search and broadcast noise. |
+| Clean up state changes stored before a remap guard returns | The daily `util.purge_machine_state_changes()` already deletes rows of a device that no longer exists. |
+| Extract one shared `DetailRow` component | Six other modules have their own copy. Changing them is outside this plan. Task 15 fixes the comment only. |
+
+## Dependencies
+- Task 1 runs first. It changes the schema, so `pnpm run generate:types` follows it.
+- Tasks 2 and 3 each generate an authz migration. Run them one after the other, not in parallel.
+- Task 4 is independent.
+- Task 5 is independent.
+- Task 6 needs Task 4 (engine types).
+- Task 7 needs Tasks 4, 6 and 9 (it seeds Machine events).
+- Task 8 needs Task 5 (both edit `packages/ee/src/sense/`).
+- Tasks 9, 10 and 11 are independent of each other.
+- Task 13 needs Task 12. Task 14 needs Task 13. Task 15 needs Task 14.
+- Task 16 is independent.
+- Task 17 needs Tasks 1 to 16.
+- Task 18 needs Task 17.
+
+## Shared commands
+
+Run these from the worktree root, `/Users/barbinbrad/conductor/workspaces/carbon/albany`.
+
+```bash
+# The shell exports a stale SUPABASE_DB_URL. Use the worktree's value first.
+export SUPABASE_DB_URL=$(grep '^SUPABASE_DB_URL' .env.local | cut -d= -f2- | tr -d '"')
+# Postgres container for this worktree (psql is not installed on the host):
+PG=carbon-carbon-find-oee-job-operation-transcript-postgres-1
+```
+
+🛑 Never stop or restart a `crbn up` process. It tears down the whole stack for this worktree, including the human's.
+
+---
+
+## Task 1: Make the OEE work center foreign keys company-scoped and fix the indexes
+
+**Depends on:** none
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_oee-company-scoped-work-center.sql` (from `pnpm db:migrate:new`)
+- Copy from (precedent): `packages/database/supabase/migrations/20261013191915_oee-tenancy-and-retention.sql`
+
+**Steps:**
+1. Run `pnpm db:migrate:new oee-company-scoped-work-center < /dev/null`.
+2. Write this SQL into the new file:
+
+```sql
+-- machineStateChange and unattributedMachineTime carry the work center the
+-- sync read from the device. Their FKs carry the company too, like
+-- workCenterDevice's (20261013191915). Each REPLACES the single-column FK:
+-- two FKs to workCenter would make PostgREST embeds ambiguous (PGRST201).
+ALTER TABLE "machineStateChange"
+ DROP CONSTRAINT IF EXISTS "machineStateChange_workCenterId_fkey";
+ALTER TABLE "machineStateChange"
+ ADD CONSTRAINT "machineStateChange_workCenterId_fkey"
+ FOREIGN KEY ("workCenterId", "companyId")
+ REFERENCES "workCenter" ("id", "companyId") ON DELETE CASCADE;
+
+ALTER TABLE "unattributedMachineTime"
+ DROP CONSTRAINT IF EXISTS "unattributedMachineTime_workCenterId_fkey";
+ALTER TABLE "unattributedMachineTime"
+ ADD CONSTRAINT "unattributedMachineTime_workCenterId_fkey"
+ FOREIGN KEY ("workCenterId", "companyId")
+ REFERENCES "workCenter" ("id", "companyId") ON DELETE CASCADE;
+
+-- Every FK has an index.
+CREATE INDEX IF NOT EXISTS "workCenterDevice_updatedBy_idx"
+ ON "workCenterDevice" ("updatedBy");
+CREATE INDEX IF NOT EXISTS "unattributedMachineTime_updatedBy_idx"
+ ON "unattributedMachineTime" ("updatedBy");
+
+-- ("companyId", "startTime" DESC) from 20261013170425 covers it.
+DROP INDEX IF EXISTS "unattributedMachineTime_companyId_idx";
+```
+
+3. Run `pnpm db:migrate < /dev/null`. It applies the migration and runs `pnpm run generate:types`.
+
+**Verify:**
+```bash
+docker exec -i $PG psql -U postgres -At -c "select conname, pg_get_constraintdef(oid) from pg_constraint where conname in ('machineStateChange_workCenterId_fkey','unattributedMachineTime_workCenterId_fkey')"
+# Expected: both rows show FOREIGN KEY ("workCenterId", "companyId") REFERENCES "workCenter"(id, "companyId")
+pnpm exec turbo run typecheck --filter=erp --filter=@carbon/jobs
+# Expected: "Tasks: N successful, N total", no "error TS"
+```
+
+**Out of scope:** `workCenterDevice`'s FK (already composite).
+
+---
+
+## Task 2: Unload an operation when it moves to another work center
+
+**Depends on:** Task 1
+**Files:**
+- Modify: `packages/database/src/event-system/handlers/sync_unload_work_center_operation.sql` — add a work center change case.
+- Modify: `packages/database/supabase/tests/work-center-loaded-operation.test.sql` — add a test case.
+- Create: a generated authz migration (from the `authz migration` command).
+
+**Steps:**
+1. In `sync_unload_work_center_operation.sql`, after the `DELETE` branch, add this branch before `IF p_operation != 'UPDATE' THEN RETURN; END IF;`:
+
+```sql
+ -- An operation moved to another work center leaves the old one: its sensor
+ -- time there is no longer this operation's.
+ IF p_operation = 'UPDATE'
+ AND (p_old->>'workCenterId') IS DISTINCT FROM (p_new->>'workCenterId') THEN
+ UPDATE "workCenter"
+ SET "loadedJobOperationId" = NULL,
+ "loadedAt" = NULL
+ WHERE "id" = p_old->>'workCenterId'
+ AND "companyId" = p_old->>'companyId'
+ AND "loadedJobOperationId" = p_new->>'id';
+ END IF;
+```
+
+2. Keep the existing Done / Canceled branch after it unchanged.
+3. In the SQL test, after the "Deleting the loaded operation" case, add a case:
+ 1. Create operation `v_e` on `v_work_center` with `pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 5)`.
+ 2. Load it with `pg_temp.add_event(v_e, v_work_center, 'Setup', v_day + time '12:30', NULL)`.
+ 3. Create a second work center `v_work_center_2` in the same company (copy the `INSERT INTO "workCenter"` line, name `'Haas 3'`).
+ 4. Run `UPDATE "jobOperation" SET "workCenterId" = v_work_center_2, "updatedBy" = 'system' WHERE id = v_e`.
+ 5. Assert `pg_temp.loaded(v_work_center) = 'none@none'` with message `'moving E unloads the old work center'`.
+4. Declare `v_e text; v_work_center_2 text;` in the `DECLARE` block.
+5. Run `pnpm db:migrate < /dev/null`. It syncs the handler to the local database.
+6. Run `pnpm --filter @carbon/database authz migration unload-on-work-center-move < /dev/null`.
+
+**Verify:**
+```bash
+docker exec -i $PG psql -U postgres -X < packages/database/supabase/tests/work-center-loaded-operation.test.sql 2>&1 | grep -E "NOTICE|ERROR"
+# Expected: NOTICE: ALL work-center-loaded-operation TESTS PASSED
+ls packages/database/supabase/migrations | grep unload-on-work-center-move
+# Expected: one file
+pnpm --filter @carbon/database exec vitest run src/authz
+# Expected: all tests pass (the shipping test sees the new migration)
+```
+
+**Out of scope:** the load interceptor `sync_load_work_center_operation.sql`.
+
+---
+
+## Task 3: Ignore load-pointer changes in the event and broadcast filters
+
+**Depends on:** Task 2 (both generate authz migrations)
+**Files:**
+- Modify: `packages/database/src/audit.config.ts` — `skipFields`.
+- Modify: the `ignored_columns` constant in these 6 files under `packages/database/src/event-system/functions/`: `dispatch_event_batch.sql`, `broadcast_table_changes.sql`, `broadcast_reference_changes.sql`, `broadcast_user_changes.sql`, `log_table_changes.sql`, `log_user_changes.sql`.
+- Create: a generated authz migration.
+
+**Steps:**
+1. In `audit.config.ts`, set `skipFields` to `["updatedAt", "updatedBy", "embedding", "loadedJobOperationId", "loadedAt"]`.
+2. In each of the 6 SQL files, set `ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding', 'loadedJobOperationId', 'loadedAt'];`.
+3. Add this comment above `skipFields`: `// loadedJobOperationId / loadedAt change on every timer start (workCenter); they are machine state, not an edit.`
+4. Run `pnpm db:migrate < /dev/null`.
+5. Run `pnpm --filter @carbon/database authz migration skip-load-pointer-changes < /dev/null`.
+
+If the `authz migration` command reports more functions than the 6 named above, STOP and report. Do not improvise.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/database exec vitest run src/event-dispatch.test.ts src/authz
+# Expected: all tests pass ("ignores exactly the columns the audit diff skips" for all 6 files)
+```
+
+**Out of scope:** WEBHOOK, WORKFLOW and SYNC subscriptions. They still receive every UPDATE (see "Not doing").
+
+---
+
+## Task 4: Tidy the engine slots, always close a slot, and merge repeated states
+
+**Depends on:** none
+**Files:**
+- Modify: `packages/ee/src/oee/engine.ts`
+- Modify: `packages/ee/src/oee/engine.test.ts`
+
+**Steps:**
+1. Add 3 failing tests to `engine.test.ts` first:
+ 1. "drops a new slot that would close at or before its start". Use `minimumStateSeconds: 0`. Add 2 changes: Running and Idle, both at `t("10:00:00")`. Expect `writes` to equal `[]` and `currentState` to be `"Idle"`.
+ 2. "closes an existing slot at its start when the end is earlier": `currentState: "Running"`, `openMachineEvent: { id: "pe1", startTime: t("10:30:00") }`, changes Idle at `t("10:20:00")`. Expect `[{ kind: "closeMachineEvent", productionEventId: "pe1", endTime: t("10:30:00") }]`.
+ 3. "treats repeated same-state changes as one run for the debounce". Add 3 Running changes: `t("10:00:00")`, `t("10:00:30")`, `t("10:00:50")`. Use `now: t("10:05:00")`. Expect one `insertMachineEvent` with `startTime: t("10:00:00")`.
+2. Run the tests. Confirm the 3 new tests fail.
+3. Replace `type Slot` and `type EventSlot` with a union, and remove the `jobOperationId: ""` placeholder and both `as` casts:
+
+```ts
+/** An open interval this run found (`existing`, closed by id) or opened (`new`). */
+type EventSlot =
+ | { kind: "existing"; id: string; startTime: string }
+ | { kind: "new"; jobOperationId: string; startTime: string };
+type UnattributedSlot =
+ | { kind: "existing"; id: string; startTime: string }
+ | { kind: "new"; startTime: string };
+```
+
+4. In `closeEvent` and `closeUnattributed`, always clear the slot:
+ 1. If the slot is `new` and `end <= startTime`, drop it with no write.
+ 2. If the slot is `existing` and `end <= startTime`, close it at its own `startTime`.
+ 3. Else write the close or insert as before.
+5. Before the debounce loop, merge consecutive changes with the same `state`. Keep the first of each run.
+6. Run the tests again.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/ee exec vitest run src/oee/engine.test.ts
+# Expected: all tests pass, including the 3 new ones
+pnpm exec turbo run typecheck --filter=@carbon/ee --filter=@carbon/jobs
+# Expected: no "error TS"
+```
+
+**Out of scope:** the `blockedSince` logic. Keep its behavior and its 4 tests unchanged.
+
+---
+
+## Task 5: Stop a sync run when the provider is unavailable
+
+**Depends on:** none
+**Files:**
+- Modify: `packages/ee/src/oee/types.ts` — add the error class.
+- Modify: `packages/ee/src/oee/index.ts` — no change needed if it already does `export * from "./types"`.
+- Modify: `packages/ee/src/sense/provider.ts` — throw the error.
+- Modify: `packages/ee/src/sense/provider.test.ts` — test it.
+- Modify: `packages/jobs/src/inngest/functions/integrations/oee-sync.ts` — stop the loop, add `singleton`.
+
+**Steps:**
+1. In `oee/types.ts`, add:
+
+```ts
+/**
+ * The provider cannot be reached (network failure, timeout, 5xx). The sync
+ * stops the run: every other device would fail the same way.
+ */
+export class OeeProviderUnavailableError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "OeeProviderUnavailableError";
+ }
+}
+```
+
+2. In `SenseProvider.get`, wrap the `fetch` call in `try`/`catch`. On a thrown error, throw `new OeeProviderUnavailableError(\`Sense ${path} failed: ${message}\`)`.
+3. In `SenseProvider.get`, if `response.status >= 500`, throw `OeeProviderUnavailableError` instead of `SenseApiError`.
+4. In `provider.test.ts`, add 2 tests with a stubbed global `fetch` (copy the stubbing in that file):
+ 1. A rejected `fetch` makes `listDevices()` throw `OeeProviderUnavailableError`.
+ 2. A 503 response makes `listDevices()` throw `OeeProviderUnavailableError`.
+5. In `oee-sync.ts`, in the device loop `catch`: if `error instanceof OeeProviderUnavailableError`, record the error on this device, then `break`.
+6. Return `stopped: error.message` in the step result when the loop broke.
+7. Add `singleton: { key: "event.data.companyId + '-' + event.data.integrationId", mode: "skip" }` to the function options.
+
+If Inngest rejects the `singleton` key expression at registration, STOP and report. Read `.claude/skills/inngest/SKILL.md` before you change the syntax.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/ee exec vitest run src/sense
+# Expected: all tests pass, including the 2 new ones
+pnpm exec turbo run typecheck --filter=@carbon/ee --filter=@carbon/jobs
+# Expected: no "error TS"
+```
+
+**Out of scope:** retries of one device. `SenseApiError` for 4xx and data errors stays per device.
+
+---
+
+## Task 6: Fix the sync cursor, log late events, and close Canceled operations
+
+**Depends on:** Task 4
+**Files:**
+- Modify: `packages/jobs/src/inngest/functions/integrations/oee-sync-device.ts`
+
+**Steps:**
+1. In `toInstant`, parse a string with `parseAbsolute(value, "UTC").toAbsoluteString()`. Keep `value.toISOString()` for a `Date`. Remove `new Date(value)`.
+2. Type the `max("endTime")` select with `sql<Date | null>` and remove the `as Date | string | null | undefined` cast.
+3. Set `lastEventAt` to the newest `changedAt` this sync stored, not to `now`. If the sync stored no change, keep the previous `lastEventAt`.
+4. After the insert into `machineStateChange`, count the inserted rows with `changedAt <= appliedThrough`. Use `.returning("changedAt")` on the insert to get them.
+5. If that count is more than 0, call `console.warn` with the device id, the count and `appliedThrough`. Do not replan them.
+6. In the open-event read, also select `createdBy` and the operation's `status` and `updatedAt` (join `jobOperation` on `id` and `companyId`).
+7. If the open event has `createdBy = 'system'` and its operation `status = 'Canceled'`:
+ 1. Close the event at the operation's `updatedAt`, under the same device lock.
+ 2. Pass `openMachineEvent: null` to `planMachineTime`.
+ 3. Pass that `updatedAt` as `lastMachineEventEndTime`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/jobs
+# Expected: no "error TS"
+pnpm --filter @carbon/checks no-local-timezone < /dev/null 2>&1 | tail -3
+# Expected: no finding for oee-sync-device.ts
+```
+If `pnpm --filter @carbon/checks no-local-timezone` is not a script, run `pnpm --filter @carbon/checks conformance < /dev/null` instead and check the same file.
+
+**Out of scope:** replanning history (see "Decisions taken").
+
+---
+
+## Task 7: Test `syncOeeDevice` against the local database
+
+**Depends on:** Tasks 4, 6, 9
+**Files:**
+- Create: `packages/jobs/src/inngest/functions/integrations/oee-sync-device.database.test.ts`
+- Copy from (precedent): `packages/database/src/machine-time.test.ts` (the `SavepointDriver` harness, `session_replication_role = replica`, rollback per test) and `packages/jobs/src/invoicing/lease-reminders.database.test.ts` (naming, skip without `SUPABASE_DB_URL`).
+
+**Steps:**
+1. Build a fake provider object that implements `OeeProvider`. It returns a fixed `listStateChanges` array and records each `window` it receives. It is the external boundary, so `.claude/rules/testing-no-mock-theater.md` allows a fake.
+2. Seed per test: a `workCenter` id, a `jobOperation` row, and a `workCenterDevice` row. FKs are off under `replica`.
+3. Write 6 tests:
+ 1. A first sync reads from `createdAt` minus 24 hours.
+ 2. A later sync reads from `lastEventAt` minus 10 minutes.
+ 3. A Running change opens a `system` Machine event on the loaded operation.
+ 4. The engine does not plan a change stored at or before `appliedThrough`. The sync calls `console.warn` once.
+ 5. A device removed during the read (delete its row before the lock) writes no events.
+ 6. The sync closes an open `system` event on a Canceled operation at the operation's `updatedAt`.
+4. Add the license header with `git add -N <file>` and `pnpm --filter @carbon/checks license-headers`.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/jobs exec vitest run src/inngest/functions/integrations/oee-sync-device.database.test.ts
+# Expected: "Tests 6 passed (6)"
+```
+
+**Out of scope:** the Sense HTTP adapter (`provider.test.ts` covers it).
+
+---
+
+## Task 8: Resolve an OEE provider in one place
+
+**Depends on:** Task 5
+**Files:**
+- Modify: `packages/ee/src/oee/types.ts` — add `DEFAULT_MINIMUM_STATE_SECONDS = 60`.
+- Modify: `packages/ee/src/oee/registry.ts` — typed registry and `createOeeProvider`.
+- Modify: `packages/ee/src/oee/service.server.ts` — use it in `getOeeProvider` and `upsertWorkCenterDevice`.
+- Modify: `packages/ee/src/sense/hooks.server.ts` — use it.
+- Modify: `packages/ee/src/sense/config.tsx` — use the default constant.
+
+**Steps:**
+1. In `registry.ts`, type the registry as `Record<OeeProviderId, OeeProviderFactory>`.
+2. Add `isOeeProviderId(id: string): id is OeeProviderId`.
+3. Add `createOeeProvider(integrationId: string, metadata: Record<string, unknown>): { provider: OeeProvider; minimumStateSeconds: number }`. It throws in 3 cases:
+ 1. The id is not an OEE provider.
+ 2. `apiKey` is empty ("No API key").
+ 3. The factory throws.
+4. Make `createOeeProvider` read `minimumStateSeconds` with `DEFAULT_MINIMUM_STATE_SECONDS` as the default.
+5. In `getOeeProvider`, call `createOeeProvider` inside the existing `try`. Remove the factory lookup, the API key check and the minimum parsing.
+6. In `senseHealthcheck`, call `createOeeProvider("sense", metadata)` in a `try`. On a throw, return `{ healthy: false, reason: error.message }`.
+7. In `upsertWorkCenterDevice`, replace `OEE_PROVIDERS[args.integration]` with `isOeeProviderId(args.integration)`.
+8. In `config.tsx`, use `.default(DEFAULT_MINIMUM_STATE_SECONDS)` from `../oee/types`.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/ee exec vitest run src/oee src/sense
+# Expected: all tests pass
+pnpm exec turbo run typecheck --filter=@carbon/ee --filter=@carbon/jobs --filter=erp
+# Expected: no "error TS"
+grep -n "OEE_PROVIDERS\[" packages/ee/src/oee/service.server.ts packages/ee/src/sense/hooks.server.ts
+# Expected: no output
+```
+
+**Out of scope:** the Sense staging refusal. Keep `SENSE_STAGING_REFUSED` and its check in the factory.
+
+---
+
+## Task 9: Make machine time one stream per work center
+
+**Depends on:** none
+**Files:**
+- Modify: `packages/database/src/machine-time.ts` — `recordManualMachinePress`.
+- Modify: `packages/database/src/machine-time.test.ts` — tests.
+- Modify: `apps/mes/app/routes/x+/event.tsx` — the press helper comment.
+- Modify: `apps/mes/app/routes/x+/start.$operationId.tsx` — the press comment.
+
+A machine has one machine time. A Machine press (Start or Pause) ends every open Machine event on the work center, from any operator or the sensor. Then a Start opens the new one.
+
+**Steps:**
+1. Add 3 tests in the `recordManualMachinePress` block. Run them. Confirm that tests 2 and 3 fail:
+ 1. "ends another operator's Machine event": seed an open Machine event with `createdBy: operator` on a mapped work center. After the press, assert `endedAt` is `true`.
+ 2. "does not end an event that starts after the press": seed a Machine event with `startTime: after`. After the press, assert `endedAt` is `null`.
+ 3. "ends Machine events on a work center with no device": seed an open Machine event and no `workCenterDevice`. After the press, assert `endedAt` is `true`. Assert `result.mapped` is `false`.
+2. Change the existing test "does nothing on a work center with no device". Keep its assertion that the unattributed row stays open.
+3. In `recordManualMachinePress`, end the open Machine events before the device lookup:
+ 1. Run the `productionEvent` update with `.where("startTime", "<=", args.pressedAt)` added.
+ 2. Then call `lockWorkCenterDevice`.
+ 3. If there is no device, return `{ mapped: false, endedEventIds }`.
+ 4. Else end the running unattributed time and set `lastManualChangeAt`, as today.
+4. Start the function's doc comment with "A machine has one machine time."
+5. In the same comment, name what the press ends on any work center. Then name what it adds on a mapped one.
+6. Update the press comments in `event.tsx` and `start.$operationId.tsx` to match.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/database exec vitest run src/machine-time.test.ts
+# Expected: all tests pass, including the 3 new ones
+pnpm exec turbo run typecheck --filter=mes --filter=@carbon/database
+# Expected: no "error TS"
+```
+
+**Out of scope:** `endSensorMachineTime`. A device that leaves a work center ends only the sensor's events.
+
+---
+
+## Task 10: End the MES event on its own work center
+
+**Depends on:** none
+**Files:**
+- Modify: `apps/mes/app/routes/x+/event.tsx` — the End branch.
+
+**Steps:**
+1. In the End branch, before `recordMachinePress()`, read the event: `client.from("productionEvent").select("workCenterId, type").eq("id", id).eq("companyId", companyId).maybeSingle()`.
+2. If the read fails or returns no row, return the existing "Failed to end event" flash.
+3. Change `recordMachinePress` to take `{ type, workCenterId }` as arguments.
+4. In the End branch, pass the event's own `type` and `workCenterId`.
+5. In the Start branch, pass `d.type` and `d.workCenterId`, as today.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=mes
+# Expected: no "error TS"
+grep -n "d.workCenterId" apps/mes/app/routes/x+/event.tsx
+# Expected: only the Start branch uses it
+```
+
+**Out of scope:** `start.$operationId.tsx`. It reads the work center from the operation already.
+
+---
+
+## Task 11: Hide a stale device state on the work center display
+
+**Depends on:** none
+**Files:**
+- Modify: `apps/mes/app/services/display.service.ts` — add `getDisplayDeviceState`.
+- Modify: `apps/mes/app/services/operations.service.ts` — remove `getWorkCenterDevice` and the `WorkCenterDevice` type.
+- Modify: `apps/mes/app/routes/display+/$workCenterId.work.tsx` — use the new function.
+
+**Steps:**
+1. In `display.service.ts`, add `getDisplayDeviceState(client, { workCenterId, companyId, now })`.
+2. Make it select `currentState, lastSyncedAt, lastSyncError` from `workCenterDevice` for the work center and company, with `maybeSingle()`.
+3. Make it return `null` when there is no row, when `lastSyncError` is set, or when `lastSyncedAt` is null.
+4. Make it return `null` when `Date.parse(now) - Date.parse(lastSyncedAt)` is more than `10 * 60 * 1000`. Comparing absolute instants is the date rule's narrow exception.
+5. Else make it return `currentState`.
+6. In the route loader, call it with `now: datetime.timestamp()` (from `@carbon/utils`). Return `deviceState` from it.
+7. Delete `getWorkCenterDevice` and `WorkCenterDevice` from `operations.service.ts`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=mes
+# Expected: no "error TS"
+grep -rn "getWorkCenterDevice\|WorkCenterDevice\b" apps/mes/app
+# Expected: no output
+```
+
+**Out of scope:** the `isBlocked` view the display uses.
+
+---
+
+## Task 12: Fix the machine time service reads
+
+**Depends on:** none
+**Files:**
+- Modify: `apps/erp/app/modules/production/production.service.ts`
+
+**Steps:**
+1. In `getUnattributedMachineTimes`, add the default sort `{ column: "id", ascending: false }` after `{ column: "startTime", ascending: false }`.
+2. In `getUnattributedMachineTime`, replace `.single()` with `.maybeSingle()`.
+3. In `getMachineTimeOperationCandidates`, read this work center's operations in their own query: `.eq("workCenterId", args.workCenterId)`, `.limit(1000)`.
+4. Keep the location query. Add `.neq("workCenterId", args.workCenterId)` and `.order("updatedAt", { ascending: false })` to it.
+5. Merge the 2 results, this work center's first. Keep the existing ranking after the merge.
+6. Replace `"(Completed,Closed,Cancelled)"` with `` `(${JOB_LOCKED_STATUSES.join(",")})` ``.
+7. If `events.error` is set, return `{ data: null, error: events.error }`.
+8. Remove the cast in `helper: operation.workCenter?.name ?? (operation.status as string)`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no "error TS"
+```
+
+**Out of scope:** the list filters (Task 13) and the drawer (Task 14).
+
+---
+
+## Task 13: Add filters to the Unattributed Time list
+
+**Depends on:** Task 12
+**Files:**
+- Create: `apps/erp/app/modules/production/ui/MachineTime/machine-time-filters.ee.ts` — pure filter parser.
+- Create: `apps/erp/test/machine-time-filters.ee.test.ts`
+- Modify: `apps/erp/app/modules/production/production.service.ts` — `getUnattributedMachineTimes` applies the parsed filters.
+- Modify: `apps/erp/app/routes/x+/production+/machine-time.tsx` — loader.
+- Modify: `apps/erp/app/modules/production/ui/MachineTime/MachineTimeTable.ee.tsx` — columns and filters.
+- Copy from (precedent): `apps/erp/app/modules/production/ui/Jobs/ProductionEventsTable.tsx` (work center filter, `type: "static"`), `apps/erp/app/modules/inventory/ui/StockMovements/StockMovementsTable.tsx` (`type: "dateRange"`), `apps/erp/app/routes/x+/job+/$jobId.events.tsx` (`getWorkCentersList` in the loader).
+
+The list gets 5 filters:
+
+| Column | Filter key | Filter type | Rows kept |
+|---|---|---|---|
+| Work Center | `workCenterId` | `static`, options from `getWorkCentersList` | `workCenterId` in the chosen ids |
+| Location | `locationId` | `static`, options from `getLocationsList` | the work center's `locationId` in the chosen ids |
+| Start | `startTime` | `dateRange` | `startTime` inside the chosen company days |
+| End | `endTime` | `dateRange` | `endTime` inside the chosen company days |
+| State | `state` | `static`, options Running and Stopped | Running: `endTime` is null. Stopped: `endTime` is not null. |
+
+**Steps:**
+1. Create `machine-time-filters.ee.ts` with this contract:
+
+```ts
+export type MachineTimeListFilters = {
+ search: string | null;
+ workCenterIds: string[];
+ locationIds: string[];
+ /** Instants: inclusive start, exclusive end, at the company's day bounds. */
+ start: { from: string | null; until: string | null };
+ end: { from: string | null; until: string | null };
+ state: "Running" | "Stopped" | null;
+};
+
+export function parseMachineTimeListFilters(
+ searchParams: URLSearchParams,
+ timeZone: string
+): MachineTimeListFilters;
+```
+
+2. In `parseMachineTimeListFilters`, read the `search` param and every `filter` param (`column:operator:value`).
+3. For `workCenterId` and `locationId`, split the value on `,` into ids.
+4. For `startTime` and `endTime` with operator `between`, read `from,to` with `parseRangeFilter` from `~/utils/query`.
+5. Turn `from` into `toZoned(parseDate(from), timeZone).toAbsoluteString()`.
+6. Turn `to` into `toZoned(parseDate(to).add({ days: 1 }), timeZone).toAbsoluteString()`. The bound is exclusive.
+7. For `state`, keep `Running` or `Stopped`. Ignore any other value.
+8. Ignore unknown columns.
+9. Write `apps/erp/test/machine-time-filters.ee.test.ts` with 4 tests:
+ 1. A `startTime` range in `America/Chicago` gives `from` at 05:00Z and an exclusive `until` at 05:00Z the day after `to`.
+ 2. An open-ended range (`2026-10-01,`) gives `until: null`.
+ 3. `filter=workCenterId:in:a,b` gives `workCenterIds: ["a", "b"]`.
+ 4. `filter=state:eq:Paused` gives `state: null`.
+10. Change `getUnattributedMachineTimes(client, companyId, args)` to take `args: { filters: MachineTimeListFilters; limit; offset }`.
+11. Select `*, workCenter!inner(name, locationId, location(name, timezone))`.
+12. Add one exported helper in the same service file, `applyMachineTimeListFilters(query, filters)`. It applies:
+ 1. `search`: `.ilike("workCenter.name", \`%${search}%\`)`.
+ 2. `workCenterIds`: `.in("workCenterId", ids)` when not empty.
+ 3. `locationIds`: `.in("workCenter.locationId", ids)` when not empty.
+ 4. `start.from` / `start.until`: `.gte("startTime", from)` / `.lt("startTime", until)`.
+ 5. `end.from` / `end.until`: `.gte("endTime", from)` / `.lt("endTime", until)`.
+ 6. `state`: `.is("endTime", null)` for Running, `.not("endTime", "is", null)` for Stopped.
+13. In `getUnattributedMachineTimes`, call `applyMachineTimeListFilters`. Then call `setGenericQueryFilters` with the limit, offset and the default sorts only, and with no `filters`.
+14. In `machine-time.tsx`, read the company timezone with `getCompanyTimeZone` from `~/modules/shared/timezone.server`.
+15. In `machine-time.tsx`, call `parseMachineTimeListFilters(searchParams, timeZone)`.
+16. In `machine-time.tsx`, load `getWorkCentersList(client, companyId)` and `getLocationsList(client, companyId)` in the same `Promise.all`. Return both as filter options.
+17. In `MachineTimeTable.ee.tsx`, take `workCenters` and `locations` props. Copy the `ProductionEventsTable` work center column:
+ 1. Use `accessorKey: "workCenterId"`.
+ 2. Show the name with `Enumerable`.
+ 3. Keep `meta.exportValue` returning the name.
+18. Add a Location column with `id: "locationId"`, the location name as `Enumerable`, and a static filter.
+19. Add `meta.filter: { type: "dateRange" }` to the Start and End columns.
+20. Add a State column with `id: "state"`. Show `<Status color="green">Running</Status>` or `<Status color="blue">Stopped</Status>`. Green matches the MES dot for a running machine.
+21. Give the State column a static filter with those 2 options and `isExclusive: true`. Render each option label with the same `Status`.
+22. Give the Location and State columns `meta.exportValue`. The export reads a flat row field, and neither field is on the row.
+23. In `MachineTimeUpgradeOverlay.ee.tsx`, pass `workCenters={[]}` and `locations={[]}`.
+
+If the Table sends a static filter with an operator other than `in` or `eq`, STOP and report the operator. Do not guess.
+
+**Verify:**
+```bash
+(cd apps/erp && pnpm exec vitest run test/machine-time-filters.ee.test.ts)
+# Expected: "Tests 4 passed (4)"
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no "error TS"
+```
+
+**Out of scope:** a duration filter. The review asked for date and column filters only.
+
+---
+
+## Task 14: Make the review queue match the filtered list and skip running rows
+
+**Depends on:** Task 13
+**Files:**
+- Modify: `apps/erp/app/modules/production/production.service.ts` — `getUnattributedMachineTimeNeighbors`.
+- Modify: `apps/erp/app/routes/x+/production+/machine-time.$id.tsx` — loader and action.
+- Modify: `apps/erp/app/modules/production/ui/MachineTime/MachineTimeTable.ee.tsx` — sorting and Review.
+- Modify: `apps/erp/app/modules/production/ui/MachineTime/MachineTimeDrawer.ee.tsx` — header for a running row.
+- Copy from (precedent): `apps/erp/app/modules/accounting/ui/ExchangeRates/ExchangeRatesTable.tsx` (`enableSorting: false`).
+
+**Steps:**
+1. Add a `filters: MachineTimeListFilters` argument to `getUnattributedMachineTimeNeighbors`.
+2. In all 4 of its queries, select `id, workCenter!inner(name, locationId)` and call `applyMachineTimeListFilters(query, filters)`.
+3. In all 4 of its queries, add `.not("endTime", "is", null)`. The queue holds stopped rows only, whatever the State filter says.
+4. Make it return `position: null` when the current row has no `endTime`.
+5. In the drawer route's loader and action, read the company timezone. Call `parseMachineTimeListFilters` on the request URL. Pass the result.
+6. In `MachineTimeTable.ee.tsx`, add `enableSorting: false` to every column.
+7. In `MachineTimeTable.ee.tsx`, set `firstId` to the first row of `data` with an `endTime`.
+8. In `MachineTimeDrawer.ee.tsx`, show "Running" in place of "N of M" when `queue.position` is `null`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no "error TS"
+grep -c "enableSorting: false" apps/erp/app/modules/production/ui/MachineTime/MachineTimeTable.ee.tsx
+# Expected: 7 or more (one per column)
+```
+
+**Out of scope:** the filters themselves (Task 13).
+
+---
+
+## Task 15: Polish the review drawer
+
+**Depends on:** Task 14
+**Files:**
+- Modify: `apps/erp/app/modules/production/ui/MachineTime/machine-time-suggestions.ee.ts`
+- Modify: `apps/erp/app/modules/production/ui/MachineTime/MachineTimeDrawer.ee.tsx`
+- Modify: `apps/erp/app/modules/production/ui/MachineTime/MachineTimeTable.ee.tsx` — the duration hook.
+- Modify: `apps/erp/app/shortcuts.ts`
+- Modify: `apps/erp/app/routes/x+/production+/machine-time.$id.tsx` — loader error.
+
+**Steps:**
+1. In `machine-time-suggestions.ee.ts`, export `MACHINE_TIME_SUGGESTION_LIMIT = 6` and use it as the default `limit`.
+2. In `shortcuts.ts`, set `choose` to `["1", "2", "3", "4", "5", "6"]`. Add a comment that it matches `MACHINE_TIME_SUGGESTION_LIMIT`.
+3. In `machine-time-suggestions.ee.ts`, import `JOB_LOCKED_STATUSES` from `../../production.models` and remove `LOCKED_JOB_STATUSES`.
+4. Run `apps/erp/test/machine-time-suggestions.ee.test.ts`. If it fails to import because of Lingui macros, revert step 3. Then keep the local constant with a comment that names `JOB_LOCKED_STATUSES` as the source.
+5. In `MachineTimeTable.ee.tsx`, give `useMachineTimeDuration` a second formatter for a length in milliseconds: `formatPreciseDuration("1970-01-01T00:00:00.000Z", locale, ms).text`.
+6. In the drawer cards, use that formatter in place of `formatDurationMilliseconds`. Remove the `formatDurationMilliseconds` import.
+7. In the drawer, change the `DetailRow` comment to "Same row as the fixed asset page's DetailRow: label left, value right."
+8. In the route loader, split the failure path:
+ 1. If `machineTime.error` is set, log it with `logger.error` and throw a redirect with the flash "Failed to load machine time".
+ 2. If `machineTime.data` is null, keep the flash "That machine time is no longer open".
+
+**Verify:**
+```bash
+(cd apps/erp && pnpm exec vitest run test/machine-time-suggestions.ee.test.ts)
+# Expected: "Tests 7 passed (7)"
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no "error TS"
+```
+
+**Out of scope:** the `DetailRow` copies in other modules.
+
+---
+
+## Task 16: Move the Devices tab server code out of the route and fix its gaps
+
+**Depends on:** none
+**Files:**
+- Create: `apps/erp/app/modules/settings/oee-devices.server.ts` (name it `oee-devices.server.ee.ts` if `pnpm --filter @carbon/checks license-headers` requires a commercial file. It calls `@carbon/ee/oee.server`).
+- Modify: `apps/erp/app/routes/x+/settings+/integrations.$id.tsx` — call the new module.
+- Modify: `apps/erp/app/modules/settings/ui/Integrations/OeeDevices.ee.tsx` — status dot.
+- Copy from (precedent): `apps/erp/app/modules/shared/timezone.server.ts` (Redis cache with `redis` from `@carbon/kv`).
+
+**Steps:**
+1. Move `getOeeDevicesTabData` into the new module unchanged. Export it.
+2. Move the `upsert-work-center-device` action branch body into an exported `saveWorkCenterDeviceMapping(request, …)` in the same module. The route keeps the `if (intent === …)` line and calls it.
+3. In `getOeeDevicesTabData`, cache `provider.listDevices()` in Redis for 60 seconds, keyed `oee-devices:${companyId}:${integrationId}`.
+4. Do not cache a provider error.
+5. In the `workCenters` query, replace `.eq("active", true)` with `.or(\`active.eq.true,id.in.(${mappedIds.join(",")})\`)`. `mappedIds` is the `workCenterId` list from `mappings`. If `mappedIds` is empty, keep `.eq("active", true)`.
+6. Read `mappings` before `workCenters`, because step 5 needs it.
+7. In `DeviceStatusDot`, add `tabIndex={0}` and `aria-label={labelText}` to the trigger `span`. `labelText` is a plain string version of the tooltip text.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: no "error TS"
+wc -l apps/erp/app/routes/x+/settings+/integrations.\$id.tsx
+# Expected: fewer lines than 2472
+pnpm --filter @carbon/checks license-headers < /dev/null 2>&1 | grep fixed
+# Expected: "0 fixed." after a second run
+```
+
+**Out of scope:** the accounting tabs of the same route.
+
+---
+
+## Task 17: Update the rule, AGENTS.md files and the guide
+
+**Depends on:** Tasks 1–16
+**Files:**
+- Modify: `.claude/rules/oee-provider.md`
+- Modify: `apps/erp/app/modules/production/AGENTS.md`
+- Modify: `packages/ee/AGENTS.md` — the `./oee` and `./oee.server` rows.
+- Modify: `docs/content/docs/integrations/oee.mdx`
+
+**Steps:**
+1. In the rule, rename "The MES Machine button on a mapped work center" to "The MES Machine button". State 4 facts:
+ 1. A machine has one machine time.
+ 2. On every work center, a press ends each open Machine event from any operator or the sensor.
+ 3. It skips an event that starts after the press.
+ 4. On a mapped work center, the press also ends running unattributed time and sets `lastManualChangeAt`.
+2. In the rule, under "The sync", state 4 facts:
+ 1. `lastEventAt` is the newest stored `changedAt`.
+ 2. The sync logs a late event at or before `appliedThrough`. It does not replan it.
+ 3. A `system` event on a Canceled operation closes at the operation's `updatedAt`.
+ 4. `OeeProviderUnavailableError` stops the run, and `singleton` skips an overlapping run.
+3. In the rule, under "The loaded operation", add the unload on a work center move.
+4. In the rule, add the composite FKs of Task 1 next to the `workCenterDevice` FK paragraph.
+5. In the rule, add the ignored load-pointer columns of Task 3.
+6. In the rule, under "Unattributed machine time", state 4 facts about the list and the queue:
+ 1. The list has 5 filters: work center, location, start date, end date and state. Name `parseMachineTimeListFilters` and `applyMachineTimeListFilters`.
+ 2. The route turns each date range into company day bounds. The service does not pass them to the generic `between` filter.
+ 3. The queue holds stopped rows only. It honors the list's search and filters.
+ 4. The list has no column sort.
+7. In the rule's Files table, name `createOeeProvider` (registry), `oee-sync-device.database.test.ts` and `machine-time-filters.ee.ts`.
+8. In `packages/ee/AGENTS.md`, add `OeeProviderUnavailableError`, `DEFAULT_MINIMUM_STATE_SECONDS` and `createOeeProvider`.
+9. In the guide, state that the work center display hides the device state after 10 minutes with no sync.
+10. In the guide, state that a running row is outside the review queue until the machine stops.
+11. In the guide, list the 5 filters of Production → Unattributed Time.
+12. In the guide's MES section, state that a machine has one machine time.
+13. In the guide's MES section, state that a Machine press ends every open Machine timer on that work center.
+14. In `apps/erp/app/modules/production/AGENTS.md`, add the 5 filters and the 2 filter functions to the unattributed machine time paragraph.
+
+**Verify:**
+```bash
+grep -n "OeeProviderUnavailableError\|createOeeProvider" .claude/rules/oee-provider.md packages/ee/AGENTS.md
+# Expected: at least one hit in each file
+pnpm --filter docs typecheck
+# Expected: exit 0
+```
+
+**Out of scope:** the spec. Its divergence list already points to the rule.
+
+---
+
+## Task 18: Verify in the browser
+
+**Depends on:** Task 17
+**Files:** none
+
+**Steps:**
+1. Ask the human to restart their `crbn up` if the ERP returns 502. Do not restart it yourself.
+2. Run the `/test` skill on this branch with these checks:
+ 1. Production → Unattributed Time: the columns have no sort control.
+ 2. Production → Unattributed Time: Review opens the newest stopped row.
+ 3. Search "CNC" in the list, then open Review: `j` / `k` move only through rows whose work center matches.
+ 4. In the review drawer, a running row shows "Running" in place of "N of M".
+ 5. Settings → Integrations → Sense → Devices: a station mapped to an inactive work center shows that work center's name.
+ 6. On the Devices tab, two picks in a row make one Sense call, not two. Check the ERP log.
+ 7. MES work center display: set `lastSyncedAt` more than 10 minutes back with `UPDATE "workCenterDevice"` in the container. Expect the device state to hide.
+ 8. Unattributed Time filters: filter by work center, by location, by a start date range, and by State = Stopped. Expect the rows and the count to match each filter.
+ 9. Set a start date range of one day. Expect every row that started on that day in the company's timezone, its last hour too.
+ 10. With a filter set, open Review. Expect `j` / `k` and "N of M" to cover only the filtered, stopped rows.
+ 11. MES: two operators start Machine on the same work center one after the other. Expect the first operator's Machine timer to end when the second starts.
+3. Take a screenshot at 1440 px of the drawer and the Devices tab.
+
+**Verify:**
+```bash
+ls .ai/playbooks/ | grep -i oee
+# Expected: the /test skill updated or wrote an OEE playbook
+```
+
+**Out of scope:** the Must-fix items. `5bb79d0b1a` already verified them.
diff --git a/.ai/plans/2026-10-14-oee-load-history.md b/.ai/plans/2026-10-14-oee-load-history.md
new file mode 100644
index 0000000000..3819008ea3
--- /dev/null
+++ b/.ai/plans/2026-10-14-oee-load-history.md
@@ -0,0 +1,36 @@
+# OEE: load history and time after a press
+
+## Goal
+
+Every second the sensor reports as Running is recorded exactly once, in
+whatever order the reports and the presses arrive. The sensor decides whether
+the machine ran. The load at that time decides which operation gets it. A
+press decides only what happens after it.
+
+## Decisions
+
+| # | Decision |
+|---|---|
+| 1 | A new table `workCenterLoad` records each load: work center, operation, `loadedAt`, `unloadedAt` (null while loaded). |
+| 2 | The load and unload interceptors write it. The pointer `workCenter.loadedJobOperationId` stays as the current value. |
+| 3 | `jobOperationId` has no foreign key: a table with keys to both `workCenter` and `jobOperation` can make PostgREST embeds ambiguous (`.ai/lessons.md`, PGRST201). |
+| 4 | pg_cron deletes a load 7 days after its `unloadedAt`. An open load is never deleted. |
+| 5 | The engine takes `loads` (periods with `assignable`) in place of `loadedJobOperationId` / `loadedAt`. Time goes to the load at the moment the run starts. |
+| 6 | A load is `assignable` while its operation is not Done or Canceled and its job is not locked. Otherwise the time goes to the queue. |
+| 7 | A run reported late, before a press, splits by load: a loaded, unblocked part becomes a closed system Machine event; the rest becomes unattributed time. |
+| 8 | A run that was already Running at the press and continues after it: the uncovered time after the press is unattributed time, never the loaded operation (the operator said stop charging it). The live row opens only once the machine has run `minimumStateSeconds` past the press. |
+| 9 | Each sync deletes the closed unattributed rows on its work center shorter than `minimumStateSeconds`, whoever closed them. |
+
+## Tasks
+
+- [x] 1. Migration: `workCenterLoad`, the backfill of current loads, the retention function and its cron job.
+- [x] 2. Authz manifest: SELECT only, for employees of the company.
+- [x] 3. Interceptors: the load closes the open period and opens one; the unload closes it.
+- [x] 4. Run `pnpm db:migrate`, then `authz migration`, then `pnpm run generate:types`.
+- [x] 5. SQL test: history rows on load, reload, Done, delete and move.
+- [x] 6. Engine: `loads`, `loadAt`, the split of late gaps, the time after a press.
+- [x] 7. Engine tests: both arrival orders for case B and for the Pause case.
+- [x] 8. Sync: read the loads with `assignable`, widen `recordedIntervals`, delete short rows.
+- [x] 9. Sync database tests for case B with a load and for the Pause case.
+- [x] 10. Docs: the OEE rule, the production `AGENTS.md`, the integration guide.
+- [x] 11. Verify: typecheck, tests, Biome, dataset and backup checks. Commit and push.
diff --git a/.ai/plans/2026-10-14-oee-review-fixes.md b/.ai/plans/2026-10-14-oee-review-fixes.md
new file mode 100644
index 0000000000..77336ab625
--- /dev/null
+++ b/.ai/plans/2026-10-14-oee-review-fixes.md
@@ -0,0 +1,61 @@
+# OEE: fixes from the strict self-review
+
+Source: the nuclear self-review of PR #1909 on 2026-10-14. Each task names the
+finding it fixes.
+
+## Decisions
+
+| # | Decision |
+|---|---|
+| 1 | The open `workCenterLoad` row is the load. The migration drops `workCenter.loadedJobOperationId` and `loadedAt`. Readers use the open row. |
+| 2 | A load is refused when its start is earlier than the newest boundary in the work center's history (a `loadedAt` or an `unloadedAt`). (A starting event reopens a Done operation first, so status needs no rule.) |
+| 3 | An unload ends the open row at `GREATEST(NOW(), "loadedAt")`. A CHECK refuses `unloadedAt < loadedAt`. A partial unique index allows one open row per work center. |
+| 4 | A press records the earliest press since the last sync in `workCenterDevice.unplannedPressAt`. The sync clears it. |
+| 5 | Time after a press, in the same run, goes to the queue. Time in a run with no press before it goes to the operation loaded at that moment. The engine applies one owner rule to every piece. |
+| 6 | An open system slot follows its owner: it closes where the owner changes (a load change, a block start or end, an unassignable operation) and the next owner opens. This replaces the Canceled special case. |
+| 7 | A late stop before a press trims the closed unattributed rows it overlaps. The engine never trims a Machine event. |
+| 8 | A press takes its time under the lock, and it serializes on a transaction advisory lock for each work center. |
+| 9 | The routes post every event a press ends, except batch events. |
+| 10 | The migrations are not squashed: squashing needs a database rebuild, which the user must run. |
+| 11 | Load rows stay 7 days after the unload (the user's decision). The purge keeps a row that a device has not planned past yet. |
+
+## Tasks
+
+### Database
+- [x] 1. Migration: drop the pointer columns. Add the CHECK, the one-open index and the index for the sync's Machine-event reads. Add `unplannedPressAt`. Change the retention guard.
+- [x] 2. Interceptors: write only `workCenterLoad`, with the boundary rule. (The status rule was dropped: see decision 2.)
+- [x] 3. Event functions and `auditConfig.skipFields`: remove the pointer columns.
+- [x] 4. The MES display view and service: read the open row.
+- [x] 5. `packages/jobs/src/backups/id-refs.ts`: add `workCenterLoad.jobOperationId` and `machineStateChange.workCenterDeviceId`.
+- [x] 6. SQL test: an older event after an unload, a reload, the CHECK, the index, the purge.
+
+### Engine and sync
+- [x] 7. Engine: the owner rule, slots that follow their owner, the trim of late idle time, `firstUnplannedPressAt`.
+- [x] 8. Engine tests that run the same facts in different orders and compare the result.
+- [x] 9. Sync: bounded reads, `recordedIntervals` with ids, `unplannedPressAt`, the trims, `lastEventAt` from stored changes, guarded close, no Canceled block.
+- [x] 10. One pure `machineTimeRefusal` in `@carbon/ee/oee`, used by the sync, the ee service and the ERP.
+- [x] 11. The `companyId` join in `service.server.ts`.
+
+### Press (MES)
+- [x] 12. `recordManualMachinePress`: advisory lock, press time taken under the lock, `GREATEST` on `lastManualChangeAt`, `unplannedPressAt`. Test that a press records itself.
+- [x] 13. `startMachineProductionEvent` runs a Machine start (press, event, tracked activity) in one transaction. Remove the hook.
+- [x] 14. `endMachineProductionEvent` in the service. The End route uses it and checks `endedEventIds`.
+- [x] 15. Routes: check permission before any write (both routes), post the ended events, scope `endProductionEvent` by `companyId`, give a clear message for a refused End.
+
+### ERP (subagent)
+- [x] 16. Row link and close keep the list filters. Queue moves replace history.
+- [x] 17. Drawer: log and show load errors. Suggestions span the interval's days.
+- [x] 18. Search candidates include operations with no work center.
+- [x] 19. Timezone: treat `''` as missing.
+- [x] 20. Devices tab: store the matched device's fields. The picker hides work centers mapped to another device. A light module holds the cache key. The provider read runs in parallel.
+- [x] 21. Lingui named placeholders, one casing. CSV duration and times.
+- [x] 22. Tests: the queue keyset, more filter cases.
+
+### Deactivation
+- [x] 23. Uninstalling or deactivating an OEE integration ends the sensor time of its devices.
+
+### Docs
+- [x] 24. The OEE rule, the production `AGENTS.md`, the database and jobs `AGENTS.md`, `oee.mdx`, `work-centers.mdx`, the spec, and one lesson.
+
+### Verify
+- [x] 25. Typecheck, tests, Biome, Lingui, dataset and backup checks. Commit and push.
diff --git a/.ai/playbooks/oee-provider.md b/.ai/playbooks/oee-provider.md
new file mode 100644
index 0000000000..0d1d241827
--- /dev/null
+++ b/.ai/playbooks/oee-provider.md
@@ -0,0 +1,56 @@
+# OEE Provider (Sense)
+
+Last tested: 2026-10-13
+Routes: /x/settings/integrations/sense, /x/production/machine-time, MES /x/operation/:id, MES /display/:workCenterId/work
+
+## Prerequisites
+- A seeded company (`crbn up` seeds one): at least one work center with open operations. "CNC Mill" in the satellite demo data has 4.
+- The Sense staging API key from the user. Never write it to a file.
+- The Inngest dev container must be running: the `oee-sweep` cron fires every 2 minutes.
+- If a shell `SUPABASE_DB_URL` points at another worktree's port, export this worktree's URL from `crbn status` before running DB checks.
+
+## Steps
+### 1. Install
+- Open `${ERP_URL}/x/settings/integrations/sense`.
+- Fill the first textbox (the API key, a password field). Click the "Staging" radio.
+- requestSubmit the form whose submit button text includes "Install".
+- Verify in SQL: `companyIntegration` row `sense` is active, `metadata` has `environment: staging` and NO apiKey (it is in Vault, `secretRef` set).
+
+### 2. Map a device
+- Open `?tab=devices`. Expect 55 "Station NNNN" rows (staging company).
+- Click the combobox of the "Station 0002" row (first row), pick "CNC Mill".
+- requestSubmit the row's form: the forms with a hidden `intent=upsert-work-center-device`, index 0.
+- Verify: a `workCenterDevice` row; a warning icon on the row (site timezone UTC vs location America/Chicago).
+
+### 3. Refuse a second device
+- Pick "CNC Mill" on row index 1 (Station 0006) and requestSubmit form index 1.
+- Poll `[data-sonner-toast]` every 0.5 s right away (the revalidation re-reads Sense and can take 10 s+).
+- Expected toast: "Failed to save device mapping: CNC Mill already has Station 0002 from Sense".
+
+### 4. Sync and attribution (inject state changes)
+Sense staging stations change state only every few hours, so inject `machineStateChange` rows. Insert ONE row per statement with explicit casts (`'Idle'::"machineState"`, `'…'::timestamptz`); a UNION drops the literal types.
+- Wait for `workCenterDevice.lastSyncedAt` to pass a time (use an `until` loop; one sync every 2 minutes).
+- First sync: `currentState` set, `currentStateAt` = the mapping time.
+- MES: open the operation of an In Progress job at CNC Mill. The Machine toggle shows a state badge.
+- Select the "Toggle machine" radio. Press "Pause" (stop) or "Start". Verify `workCenterDevice.lastManualChangeAt` = the press time; Start loads the operation (`workCenter.loadedJobOperationId`).
+- Inject Idle at press+~1 min and Running a minute later. After the sync, the operator's event ends at the Idle time and a new Machine event (no employee, `createdBy = system`) opens on the loaded operation.
+- Set that operation to Done in SQL (pick one that is not the job's last). The next sync opens an `unattributedMachineTime` row starting at the completion time.
+- Inject Idle / Running / Idle to get closed rows.
+
+### 5. Unattributed Machine Time
+- `${ERP_URL}/x/production/machine-time` lists the rows; times show in the work center's location timezone.
+- Open a row, open the Operation combobox, pick a candidate (Done operations are not offered), requestSubmit the form with hidden `intent=assign`. Verify the row is Assigned and a Machine `productionEvent` has the row's start and end, `employeeId` null, `postedToGL` false.
+- Open another closed row, requestSubmit `intent=dismiss` with no reason → "Reason is required". Fill the reason textbox and submit → Dismissed.
+
+### 6. Display
+- MES `${MES_URL}/display/<workCenterId>/work` shows the device state badge; the "Loaded:" line appears only when an operation is loaded.
+
+## Selector Notes
+- Device rows: one `ValidatedForm` per device, find by `input[name=intent][value=upsert-work-center-device]`, index = row order.
+- Machine time drawer: two forms, `intent=assign` and `intent=dismiss`.
+- MES work type toggle: radios "Toggle setup" / "Toggle labor" / "Toggle machine"; the action button reads "Start" or "Pause".
+
+## Common Failures
+- "The operation was aborted due to timeout" on a device or the Devices tab: Sense staging latency spikes past 15 s. The next sync usually succeeds; the tab still lists mapped devices.
+- Authz tests "must be owner of function sync_…": `crbn migrate` created the handler as `supabase_admin`. Run `ALTER FUNCTION … OWNER TO postgres` locally.
+- No `psql` on the host: pipe SQL test files into `docker exec -i <postgres container> psql -U postgres -d postgres`.
diff --git a/.ai/research/oee-provider-integration.md b/.ai/research/oee-provider-integration.md
new file mode 100644
index 0000000000..bef3d4c0e4
--- /dev/null
+++ b/.ai/research/oee-provider-integration.md
@@ -0,0 +1,405 @@
+# OEE Provider Integration Research: Best Practices Survey
+
+## Summary
+
+This survey covers how machine-monitoring vendors, ERP/MES products and standards attribute sensed machine time to a job. The input is a Carbon "OEE provider", such as Sense Manufacturing. It reports per-station states (Active / Idle / Alert / Offline) over a polled REST API. No surveyed product infers the job from an on/off signal. Every product keeps an explicit **active job per machine**, and a person or a system sets it. The sources are an operator "start" on a tablet, a barcode scan, an ERP clock-in, or a CNC program number.
+
+A current clip cannot see a program number, so program matching is not available to Carbon. MachineMetrics documents the best answer for time that has no job. It records that time as an "Unknown Job" with its own record, and a person assigns it later. In most products, machine time reaches the ledger after a confirmation step. SAP lets that step be automatic, and Odoo costs the time at once.
+
+## Competitors Surveyed
+
+- **SAP Digital Manufacturing (DM) + S/4HANA** — the enterprise reference. Resource status model, active SFC on a resource, time records with approval.
+- **Epicor Kinetic + Advanced MES (Mattec)** — the discrete-manufacturing ERP row. Machine Interface Unit (MIU), scheduled labor export.
+- **Plex (Rockwell)** — a workcenter Control Panel with a "current job" that a setup loads.
+- **Siemens Opcenter** — an Automation Gateway binds machine tags to the active work order operation.
+- **Odoo Manufacturing** — open source, so the data model is exact. Work center productivity rows with loss types.
+- **ProShop, JobBOSS², Global Shop Solutions (GSS), Fulcrum Pro** — job-shop ERPs. Each one gets machine time through a partner (MachineMetrics, Datanomix, Amper).
+- **MachineMetrics** — the most complete public documentation. Operator, Program and ERP-driven job modes, the Unknown Job, and ERP connectors.
+- **Guidewheel, FourJaw, Amper** — current-clamp vendors. These match Sense's hardware most closely.
+- **Evocon, Vorne XL, Datanomix, Tulip, Shoplogix, Redzone** — other OEE and MES vendors.
+- **Sense Manufacturing** — the first provider. Its public material covers hardware only.
+- **Standards** — ISA-95 / IEC 62264, MTConnect, OPC UA (40001-1, 40501-1), ISO 22400, SEMI E10.
+
+## Key Consensus Patterns
+
+### 1. An explicit "active job per machine", set by a person or the ERP — never inferred from power
+
+- **SAP**: An SFC goes to Active when an operator starts it at a resource in the POD (Production Operator Dashboard). A sensor through Plant Connectivity (PCo) can also start or complete an SFC, but the order context comes from DM.
+- **MachineMetrics**: Each machine has a "Jobs selected by" mode. In Operator mode, the operator picks the job from the Dispatch Schedule, and the machine runs one job at a time. In ERP-driven mode, the ERP's clock-ins decide the job.
+- **FourJaw**: The operator "books on" a work order operation from a list in priority order. On the tablet, starting a second job pauses the current one.
+- **Vorne XL**: A barcode scan starts a "Part Run". A Job scan adds a Job ID to the current run.
+- **Evocon**: The operator marks a "product changeover" and picks an order. A green "Active order" tag shows the current order on each station.
+- **Plex**: A setup loads the job onto the workcenter. The Control Panel then shows "the current job".
+- **Siemens Opcenter**: The MES dispatches the order to the station. The gateway reads the machine values during the active step.
+- **Guidewheel**: The operator starts and stops a "production run" in Sidekick Runs. The API also accepts production entries.
+- **Odoo**: The operator presses Start on the work order (`button_start`). That opens a `mrp.workcenter.productivity` row.
+- **Rationale**: The sensor knows the state of the machine. Only the shop floor knows which job is on it. Each product therefore stores the job as a separate fact with its own start and end. The machine signal then fills that fact with run time.
+
+### 2. Program matching is the only automatic attribution, and it needs a CNC controller
+
+- **MachineMetrics**: Auto Production Monitoring (APM) matches the running program to open jobs "based on part numbers and program data". If several open work orders share one part operation, the result is "Suggested", not "Matched".
+- **Datanomix**: It reads the part number and the G-code program comments from the CNC. It matches them to ProShop part numbers.
+- **MTConnect**: `Program`, `PartId`, `PartCount` and `ProcessAggregateId.OrderNumber` carry this data.
+- **OPC UA 40501-1**: The `ProductionJob` has an `OrderIdentifier`. It is visible only when the MES sent the order to the controller.
+- **Rationale**: A current clip reports power only. It has no program, no part count and no order number. Carbon cannot use this pattern with Sense.
+
+### 3. Run time with no job goes to a visible "unknown" bucket, and a person assigns it later
+
+- **MachineMetrics**: A run with no match "is tracked as an Unknown Job with its own labor ticket, so the time and parts are not lost". The operator can assign a job, reassign, split or merge tickets before submission. A supervisor can use "Add Production Run" to create a run for a past period.
+- **Evocon**: The operator can put a product changeover on a past signal or a past stop.
+- **Guidewheel**: A manual production entry has a machine, a start time, a stop time and a product. The API accepts `POST`/`PUT` on production entries.
+- **Amper**: It recommends a "No Job to Run" downtime code. It also recommends a report of unlabeled events one hour before the shift ends, so supervisors can correct them.
+- **GSS (through MachineMetrics)**: Operations with an unknown work center go to a synthetic "UNASSIGNED" resource.
+- **SAP, Epicor, Plex, Opcenter**: The public documentation does not say what happens to run time with no active order.
+- **Rationale**: If the system drops this time, the job is under-costed and nobody sees the gap. If the system guesses, the cost goes to the wrong job. A queue that a person clears keeps the cost and the audit trail.
+
+### 4. Machine time posts after a confirmation step, and the step can be automatic
+
+- **SAP**: DM writes time records. A user adjusts and approves them in Manage Time Records. "Enable Auto-Approval for Time Records" makes the approval automatic. In S/4HANA, the confirmation carries machine time, and the activity type (for example Machine Hours) carries the rate.
+- **MachineMetrics**: A labor ticket goes from Draft to Confirmed to Closed. Draft and Confirmed tickets stay editable. "Submission is the point of no return." Connectors to JobBOSS², ProShop and GSS write the ticket to the ERP only on submission.
+- **Epicor Advanced MES**: It exports labor details to Kinetic on a schedule. Users report a 15-minute schedule.
+- **Odoo**: `_cal_cost` sums `duration * workcenter_id.costs_hour` over the productivity rows. It needs no confirmation.
+- **Rationale**: Sensed time is a measurement, not a decision. A short review window lets a person fix a wrong job before the cost reaches the job and the GL.
+
+### 5. One external machine maps to one resource, and many machines can share one resource
+
+- **SAP**: A resource belongs to only one work center. Each machine (an asset, or "digital twin") maps to a resource.
+- **MachineMetrics**: "Only one resource per machine" applies. "Multiple machines can map labor to the same ERP resource." ERP-driven mode needs an individual resource, not a group.
+- **Epicor**: An Advanced MES machine maps to a Kinetic resource. Two physical machines can share one machine record if you only need run and down state.
+- **MRPeasy**: A workstation belongs to exactly one workstation group.
+- **ISA-95**: A work center is "the grouping of equipment scheduled by Level 4 or Level 3". The work unit is the lowest level that Level 3 schedules.
+- **Rationale**: The ERP resource carries the cost rate and the schedule. The machine carries the signal. Many-to-one keeps the cost model simple. Attribution must still use the machine, because two machines in one group run different jobs.
+
+### 6. A small fixed state set, and only "running" is productive time
+
+- **SAP DM**: Resource statuses are Productive, Standby, Scheduled Down, Unscheduled Down, Unknown, Enabled and Disabled. These follow SEMI E10. "The system logs the time … in Productive status as the utilized machine time."
+- **Guidewheel**: The API states are online, idle, offline, planned downtime and nodata. Thresholds on load (kW) separate running, idle and offline.
+- **FourJaw**: The API classes are `UPTIME`, `DOWNTIME` ("stopped while staffed") and `OFFLINE` ("outside planned production").
+- **Vorne XL**: Down, Changeover and Maintenance count in OEE. Not Scheduled, No Production and Not Monitored do not.
+- **OPC UA 40001-1**: `MachineryItemState` is NotAvailable, OutOfService, NotExecuting or Executing.
+- **Odoo**: `loss_type` is `productive`, `performance`, `availability` or `quality`.
+- **Rationale**: A current clip can tell running from not running, and it can tell power from no power. Any finer state (setup, starved, feed hold) needs a person or a controller.
+
+### 7. A minimum state duration filters noise and micro-stops
+
+- **MachineMetrics**: "Microstop Duration" is 60 s by default. Shorter stops "typically [are] not categorized". The edge `debounce` transform filters "brief changes … less [than] the specified window".
+- **Tulip**: An example trigger holds "Running" until 30 consecutive seconds pass below the threshold.
+- **Vorne XL**: The Down threshold is 3 minutes with no signal by default. A shorter gap is a small stop.
+- **FourJaw**: A stop needs no reason for 5 minutes by default.
+- **Guidewheel**: An issue opens when, for example, the load is "below the idle threshold for more than 2 minutes".
+- **Rationale**: Raw current crosses the threshold many times in one cycle. Without a minimum duration, a single run becomes hundreds of short events.
+
+## Answers to Research Questions
+
+1. **How do OEE vendors attribute machine time to a job?** — With an explicit active job per machine. No vendor infers the job from the dispatch order. 4 sources set the active job:
+ - An operator on a tablet: MachineMetrics Operator mode, FourJaw, Guidewheel Sidekick Runs, Evocon, Tulip.
+ - A barcode scan: Vorne XL, MachineMetrics ShopPulse.
+ - ERP clock-ins: MachineMetrics ERP-driven mode.
+ - The CNC program number: MachineMetrics APM, Datanomix.
+
+ The ERP pushes the job list in: FourJaw by CSV or API, Evocon by API, Vorne by the XL API, Redzone by schedule import. FourJaw prompts the operator when the machine runs and nobody has booked on. It also books the job off by itself when the machine stops being productive.
+2. **How do ERP/MES products ingest machine signals?**
+ - (a) **Connector abstraction.** Every enterprise product has a connector layer:
+ - SAP: PCo and the production connector.
+ - Epicor: the MIU (CF-MIU) and Epicor IoT.
+ - Plex: Kepware with Automation & Orchestration.
+ - Siemens: the Automation Gateway and Industrial Edge connectors.
+
+ Job-shop ERPs (ProShop, JobBOSS², GSS, Fulcrum) have no connector layer of their own. They rely on fixed partners: MachineMetrics, Datanomix and Amper.
+ - (b) **Mapping.** One machine maps to one resource. Many machines can map to one resource or group (SAP, MachineMetrics, Epicor, MRPeasy).
+ - (c) **Unattributed time.** MachineMetrics uses the Unknown Job. GSS uses an "UNASSIGNED" resource. Amper uses a "No Job to Run" code. SAP, Epicor, Plex and Opcenter do not document it.
+ - (d) **Posting.** SAP posts after approval, which can be automatic. MachineMetrics posts on ticket submission. Epicor posts on a scheduled export. Odoo costs at once.
+ - (e) **States.** SAP uses the SEMI E10 states, and availability = net production time ÷ loading time. Scheduled Down is outside loading time. Odoo has 4 loss types and computes OEE as productive time ÷ (productive + blocked).
+3. **Standards.**
+ - ISA-95 records "which job ran on which equipment" as a Job Response with an Equipment Actual. Level 3 (the MES) writes it, not the equipment.
+ - MTConnect has `Execution` (ACTIVE, READY, INTERRUPTED, FEED_HOLD, STOPPED and 4 more), `ControllerMode`, `Availability`, `Program`, `PartCount`, `PartId` and `ProcessAggregateId.OrderNumber`.
+ - A current clip can give only ACTIVE versus not active, plus a link state close to MTConnect `Availability`. It cannot give the program, the part count, the controller mode or the order number.
+ - OPC UA `MachineryItemState` (4 states) carries no job. OPC 40501-1 `ProductionJob.OrderIdentifier` carries a job only when the MES sent it.
+ - ISO 22400 defines availability as APT ÷ PBT. Planned down time (PDOT) is outside PBT.
+4. **Practical concerns.**
+ - **Debounce.** See pattern 7: 30 s (Tulip) to 3 min (Vorne), with micro-stops at 60 s (MachineMetrics).
+ - **Offline gaps.** The MachineMetrics edge device buffers during an internet outage and backfills over "several minutes to a few hours". A power loss loses data. The Evocon device stores 5 days to 2 weeks. FourJaw shows "Awaiting data", and more than 10 minutes means a fault.
+ - **Gaps and availability.** No vendor documents whether gap time counts against availability. Guidewheel and the MachineMetrics API report the gap as its own state (`nodata`, `UNAVAILABLE`).
+ - **Timezone and shifts.** MachineMetrics has one timezone and a Start of Day per company. Vorne sets a timezone and a weekly schedule per device. Evocon sets shift templates per station. FourJaw Classic has one timezone per account. MachineMetrics treats a machine with no shifts as scheduled 24/7.
+ - **Polling.** Guidewheel allows 1000 calls/day and 50 per minute. FourJaw allows 100 requests per minute per key. MachineMetrics GraphQL allows 1000 requests per minute per company. The MachineMetrics JobBOSS² connector polls every 5 minutes.
+ - **Idempotency.** MachineMetrics identifies a state by `machineRef` + `metricKey` + `eventTime`, with no event id. Its data "can contain records of unchanged states". MTConnect clients page by sequence number and reset when `instanceId` changes.
+ - **Threshold changes.** A Guidewheel threshold change applies only from that point on. Support can backfill the history.
+ - **Sense API.** The Sense API (`bifrost.sensemfg.com/docs`) did not load, and no archive copy exists. Its states, cadence, limits and event ids are **unanswered**.
+
+## Competitor-Specific Details
+
+### SAP Digital Manufacturing / S/4HANA
+
+- The resource status is the unit of state. Down and Unknown block an SFC start.
+- DM can set Unscheduled Down by itself when a machine stops. It can also finish an SFC when a status tag changes.
+- The Time Tracking service writes resource usage records with start and stop events. Records reach S/4HANA only if "Report duration of Production time to ERP" is on.
+- The S/4HANA confirmation proposes routing standard values. The actual machine time can replace them.
+
+### Epicor Kinetic / Advanced MES
+
+- Standard Kinetic MES "does not do anything with machine data". The "Machine MES" flag only syncs with Advanced MES.
+- When a machine stops, Advanced MES forces the operator to pick a downtime reason, or it alerts the supervisor.
+- Epicor IoT can link a device to a record. A link to a job operation needs custom BPM work.
+
+### Plex and Siemens Opcenter
+
+- Plex Production Monitoring needs "one simple connection to a machine's cycle counter". Cycle counts become production against the current job.
+- The Opcenter gateway binds OPC UA nodes to data collection fields "on active work order operations". The order context comes from dispatch.
+
+### Odoo
+
+- The `mrp.workcenter.productivity` fields are `workcenter_id` (required), `workorder_id` (optional), `loss_id` (required), `loss_type`, `date_start`, `date_end`, `duration` and `user_id`.
+- `workorder_id` is optional, so a row with no work order is legal. That row is Odoo's version of the unknown bucket.
+- Odoo does not split time between concurrent work orders. Each work order gets its own full timeline.
+
+### MachineMetrics
+
+- It has three job modes per machine: Operator, Program (APM) and ERP Driven.
+- The ignore list removes warmup and probe programs (for example O9xxx) from matching.
+- A "stale" program that runs after its job is Complete is "not attributed to any job". The views show "Waiting for Work".
+- The "Unattended Inactive Threshold" (for example 30 minutes) turns idle time on an unattended shift into unscheduled time. That time does not lower availability.
+- The "Record labor as" setting points a machine at one ERP resource. "Schedule jobs as" can point at several resources.
+- Through the GSS connector, it splits overlapped labor evenly across concurrent jobs. "Two jobs run in parallel from 8:00 to 12:00 are each charged two hours rather than four."
+- It also posts uncovered machine time as a record for a "phantom employee with a $0 pay rate", so only the work center rate applies. "Each work center that ran carries its run window exactly once."
+
+### Guidewheel (current clip)
+
+- The unit is a "production entry": one production run on one device, with a start and an end.
+- It can create entries from the Plant Schedule before each shift. These entries have "no product, quantity, or crew".
+- A user can create a missing downtime issue by hand for a time window.
+
+### FourJaw (current clamp)
+
+- The work order CSV needs 5 fields: work order number, operation number, part number, quantity and machine. The machine name must match exactly.
+- `booked-time-periods` returns `machine_id`, `operation_id`, start and end. The end is null while the booking is open.
+- "Actual run time" is the booked tablet time, including all downtime. FourJaw does not measure performance.
+
+### Vorne XL
+
+- "Manual Run Detection" accepts a Run, Down or "Run + Down" digital signal. This is the closest match to an on/off clip.
+- Vorne recommends a Down threshold that gives no more than 25 down events per shift.
+
+### Sense Manufacturing
+
+- The hardware is a clip-on Power Monitor and a stick-on Vibration Monitor. The public states are "Running, idle, or faulted".
+- The control unit processes data locally and sends it over WiFi or ethernet. MTConnect is optional.
+- The pricing page lists no job or work order feature. Sense has no job concept to import.
+
+## Recommended Approach for Carbon
+
+Carbon facts that constrain the design:
+
+- `productionEvent.jobOperationId` is `NOT NULL`. A Machine event cannot exist without an operation.
+- `productionEvent.type` is `Setup`, `Labor` or `Machine`. Costing reads `workCenter.machineRate` for `Machine` events.
+- `jobOperation.status` already has `In Progress`, `Paused` and `Done`.
+- The closest sibling for a pluggable provider is the accounting provider layer (`packages/ee/src/accounting/providers/`: `quickbooks-online`, `xero`, `rillet`).
+
+Recommendations:
+
+1. **Add a provider adapter with a narrow contract** (SAP PCo, Epicor MIU and Siemens gateway pattern). The adapter lists stations and returns state intervals since a cursor. Copy the accounting provider layout. An Inngest cron polls each connection.
+2. **Map each provider state to one Carbon state**: `Running`, `Idle`, `Down` or `Offline` (pattern 6). For Sense, Active → `Running`, Idle → `Idle`, Alert → `Down`, Offline → `Offline`.
+3. **Map one station to one work center, and allow many stations per work center** (SAP, MachineMetrics, Epicor). The work center keeps the machine rate. Key every interval and every attribution on the station, not on the work center. Two machines in one work center run different jobs.
+4. **Keep an explicit "operation on station" binding** (MachineMetrics Operator mode, FourJaw book-on, Plex setup, SAP active SFC). An operator sets the binding when the operator starts Setup or Labor on an operation at that station in MES. The binding must outlive the operator's clock-out. This is what makes unattended run time attributable. The binding ends in 3 cases:
+ 1. The operator completes or pauses the operation.
+ 2. The operation goes to `Done`.
+ 3. Another operation starts on the same station. FourJaw pauses the current job in this case.
+
+ Do not use the dispatch queue order. No surveyed product does.
+5. **Create a Machine `productionEvent` only for `Running` time inside a binding.** The event carries the station's work center and the bound `jobOperationId`. Cost follows the existing `machineRate` path, as in Odoo.
+6. **Store `Running` time with no binding as unattributed run time, never as a guess** (MachineMetrics Unknown Job). It needs its own table, because `productionEvent` requires an operation. Show a reconciliation list per work center. In that list, a supervisor assigns a block to an operation, splits it, or marks it as not job time. This list also covers late bindings (Evocon past changeover, MachineMetrics "Add Production Run").
+ - Offer candidate operations from the station's work center in that window. The system proposes, and a person confirms, as with a MachineMetrics "Suggested" match.
+7. **Make posting a decision for the spec.** The consensus is a confirmation step (SAP approval, MachineMetrics submission). In Carbon, the job completion function posts unposted production events as absorption journal entries. So a Machine event can change until the job completes. Automatic creation inside a binding therefore matches SAP with auto-approval.
+ - Create Machine events for bound time automatically.
+ - Assign unattributed time by hand.
+8. **Apply a minimum state duration per connection** (MachineMetrics 60 s micro-stop, Tulip 30 s hold). Merge a `Running` → not-running → `Running` sequence when the gap is shorter than the threshold. Drop a `Running` block shorter than the threshold. Start with 60 s.
+9. **Treat `Offline` as no data, never as running and never as down.** Close an open `Running` interval at the last confirmed timestamp. If the provider backfills buffered data later, re-read that window. MachineMetrics backfill takes minutes to hours.
+10. **Poll with an overlapping window and write idempotently.** Key each interval on (connection, station, start time). Re-read a fixed overlap behind the cursor. A provider may send unchanged states again, and a still-open interval grows on each poll. Use a 5-minute cadence: it fits Guidewheel's 1000 calls/day limit and the MachineMetrics JobBOSS² default.
+11. **Store UTC and show times in the work center location's timezone** (Vorne per device, MachineMetrics per company). Leave planned downtime and OEE availability for a later phase. Run time and job cost are the v1 value.
+12. **Allow one binding per station in v1** (MachineMetrics Operator mode, FourJaw). Concurrent operations on one station need a split rule, and the products disagree. GSS splits time evenly, and Odoo gives each operation the full time. Carry this into the spec as an open question.
+
+Open questions for the spec:
+
+- What is the Sense API shape? This covers state names, interval or event form, an event id, the cursor, rate limits and backfill after an outage. This research could not read `bifrost.sensemfg.com/docs`.
+- Does Carbon need a station entity below the work center? The other option is a provider station table that points at a work center.
+- Must the binding come only from MES Setup and Labor starts, or also from a "load on machine" action that has no labor time?
+- Who may reconcile unattributed time, and does it expire?
+- Which rule applies to concurrent operations on one station: an even split, or full time to each?
+
+## Sources
+
+- https://docs.machinemetrics.com/docs/product-guides/production-tracking/job-tracking-guide
+- https://docs.machinemetrics.com/docs/product-guides/production-tracking/operations-production-runs-guide
+- https://docs.machinemetrics.com/docs/product-guides/production-tracking/apm-guide
+- https://docs.machinemetrics.com/docs/product-guides/production-tracking/machine-production-settings
+- https://docs.machinemetrics.com/docs/product-guides/mes/erp-driven-mes
+- https://docs.machinemetrics.com/docs/product-guides/mes/mes-admin-guide/
+- https://docs.machinemetrics.com/docs/product-guides/downtime/downtime-guide
+- https://docs.machinemetrics.com/docs/product-guides/downtime/automatic-downtime-categorization-guide
+- https://docs.machinemetrics.com/docs/integrations/erp-connectors/
+- https://docs.machinemetrics.com/docs/integrations/erp-connectors/jobboss2-connector
+- https://docs.machinemetrics.com/docs/integrations/erp-connectors/proshop-connector
+- https://docs.machinemetrics.com/docs/integrations/erp-connectors/global-shop-solutions-connector/
+- https://docs.machinemetrics.com/docs/security-compliance/edge-device-security
+- https://docs.machinemetrics.com/docs/getting-started/edge-device-setup-guide
+- https://docs.machinemetrics.com/docs/system-settings/machine-schedules
+- https://docs.machinemetrics.com/docs/system-settings/company
+- https://developers.machinemetrics.com/docs/adapter-scripts/transforms/debounce
+- https://developers.machinemetrics.com/docs/adapter-scripts/transforms/off-delay
+- https://developers.machinemetrics.com/docs/adapter-scripts/transforms/threshold
+- https://developers.machinemetrics.com/docs/adapter-scripts/transforms/when-unavailable
+- https://developers.machinemetrics.com/docs/data-and-apis/graphql/limits
+- https://developers.machinemetrics.com/docs/data-and-apis/graphql/examples
+- https://developers.machinemetrics.com/docs/data-and-apis/graphql/reference/operations/queries/state-intervals
+- https://developers.machinemetrics.com/docs/data-and-apis/data-catalog/machine-data
+- https://www.machinemetrics.com/production-scheduling-software
+- https://support.guidewheel.app/en/articles/16925627-start-and-stop-a-production-run-in-sidekick-runs
+- https://support.guidewheel.app/en/articles/9290142-how-to-add-manual-production-entries
+- https://support.guidewheel.app/en/articles/15696169-guidewheel-api-cmms-erp-integration-guide
+- https://support.guidewheel.app/en/articles/12384073-automatically-create-production-entries-from-your-plant-schedule
+- https://support.guidewheel.app/en/articles/7829820-oee-calculation-settings
+- https://support.guidewheel.app/en/articles/8006558-how-to-set-thresholds-for-machine-states
+- https://support.guidewheel.app/en/articles/11773806-what-s-the-difference-between-an-alert-and-an-issue
+- https://support.guidewheel.app/en/articles/16925686-create-a-missing-downtime-issue-in-sidekick-runs
+- https://support.guidewheel.app/en/articles/8880065-how-to-set-up-and-track-planned-downtime
+- https://support.guidewheel.app/en/articles/11773727-will-my-runtime-percentage-automatically-recalculate-when-i-update-my-thresholds
+- https://support.guidewheel.app/en/articles/11773757-no-data-available-error-on-the-uptime-page
+- https://support.guidewheel.app/en/articles/11492347-how-to-create-and-manage-shifts
+- https://support.guidewheel.app/en/articles/6732403-api-integrate-with-guidewheel
+- https://support.guidewheel.app/en/articles/12749717-understanding-device-lists-vs-device-groups-in-guidewheel
+- https://github.com/api-evangelist/guidewheel
+- https://help.fourjaw.com/knowledge/operate-book-jobs-on-and-off-fourjaw-classic
+- https://fourjaw.com/blog/intelligent-shop-floor-data-capture-with-the-power-of-machine-monitoring
+- https://help.fourjaw.com/knowledge/finding-and-starting-jobs-on-the-tablet
+- https://help.fourjaw.com/knowledge/importing-work-orders
+- https://fourjaw.app/api/v1/openapi.json
+- https://help.fourjaw.com/knowledge/work-order-auto-csv-import
+- https://help.fourjaw.com/knowledge/managing-work-orders
+- https://help.fourjaw.com/knowledge/how-does-fourjaw-machinelink-work
+- https://help.fourjaw.com/knowledge/what-does-no-reason-provided-or-no-reason-required-mean
+- https://help.fourjaw.com/knowledge/tablet-downtime-auto-labeller
+- https://help.fourjaw.com/knowledge/what-is-the-difference-between-productive-and-unproductive-downtime
+- https://help.fourjaw.com/knowledge/how-does-fourjaw-calculate-oee
+- https://help.fourjaw.com/knowledge/signal-calibration
+- https://help.fourjaw.com/knowledge/what-does-awaiting-data-mean
+- https://help.fourjaw.com/knowledge/what-happens-if-the-fourjaw-hardware-is-unplugged
+- https://help.fourjaw.com/knowledge/what-happens-if-our-wi-fi-goes-down
+- https://help.fourjaw.com/knowledge/timezone-settings-fourjaw-classic
+- https://help.fourjaw.com/knowledge/fourjaw-api-documentation
+- http://web.archive.org/web/20250323022749/https://www.amper.xyz/features/job-tracking
+- https://www.ecisolutions.com/products/amper/
+- https://www.ecisolutions.com/products/amper/amper-for-eci-customers/
+- http://web.archive.org/web/20230206184038/https://blog.amper.xyz/how-to-label-machine-downtime-using-amper
+- https://www.moldmakingtechnology.com/articles/oee-monitoring-system-addresses-root-cause-of-machine-downtime-
+- https://support.evocon.com/ (Help Desk articles: "Marking product changeovers", "Adding and managing products", "Evocon API Integrations", "Shift View colors", "Marking reasons for production stops", "Shift scheduling", "Downtime auto-commenting", "Setting maximum duration for stop reasons", "For how many days can the Evocon device keep stored data?", "Live/offline indicator", "Evocon Advanced Analytics & reporting API access", "Managing stations")
+- https://evocon.com/articles/evocon-sap-erp-integration/
+- https://evocon.com/articles/evocon-erp-integrations/
+- https://evocon.com/articles/feature/shift-view-real-time-production-monitoring-system
+- https://evocon.com/kb/the-six-big-losses-in-manufacturing
+- https://evocon.com/enterprise-package/
+- https://evocon.com/articles/track-monitor-machine-working-time/
+- https://www.sensemfg.com/how-it-works
+- https://www.sensemfg.com/resources/a-text-alert-saved-atlas-tool-works-from-12-hours-of-lost-machine-time
+- https://www.sensemfg.com/resources
+- https://www.sensemfg.com/pricing
+- https://www.vorne.com/support/product-manuals/configure-xl.pdf
+- https://www.vorne.com/support/product-manuals/meet-xl.pdf
+- https://www.vorne.com/support/deploy-xl-manual-run-detection.pdf
+- https://www.vorne.com/products/xl-past-software-versions/
+- https://www.vorne.com/support/product-manuals/xl-api/
+- https://datanomix.io/production-monitoring/
+- https://datanomix.io/2022/09/09/proshop-mms/
+- https://datanomix.io/data_faq/
+- https://datanomix.io/2025/09/30/datanomix-launches-universal-erp-connector/
+- https://datanomix.io/2022/06/21/datanomix-announces-automated-downtime-insights/
+- https://datanomix.io/fulcrum/
+- https://support.tulip.co/docs/machine-monitoring-data-model
+- https://support.tulip.co/docs/machine-attributes-downtime-reasons-and-states
+- https://support.tulip.co/docs/machine-monitoring-app-based-architecture-patterns
+- https://support.tulip.co/docs/create-your-first-machine-trigger
+- https://support.tulip.co/docs/machine-monitoring-performance-scalability
+- https://support.tulip.co/docs/machine-monitoring-terminal-1
+- https://support.tulip.co/docs/machine-monitoring-troubleshooting
+- https://shoplogix.com/pricing-platform/
+- https://shoplogix.com/core-products/
+- https://www.rzsoftware.com/product/integrations
+- https://www.rzsoftware.com/product/productivity
+- https://www.rzsoftware.com/product/scheduling
+- https://www.igz.com/en/competences/sap-manufacturing/machine-connection/
+- https://learning.sap.com/courses/implementing-machine-integration-in-sap-digital-manufacturing/describing-sap-digital-manufacturing-machine-integration-architecture
+- https://learning.sap.com/courses/exploring-customization-in-sap-digital-manufacturing/different-ways-to-trigger-production-processes-in-sap-dm
+- https://help.sap.com/docs/sap-digital-manufacturing/execution/manage-work-centers
+- https://help.sap.com/docs/sap-digital-manufacturing/execution/sfcs
+- https://community.sap.com/t5/product-lifecycle-management-blog-posts-by-members/auto-start-complete-with-pco-in-sap-digital-manufacturing/ba-p/13574025
+- https://help.sap.com/docs/sap-digital-manufacturing/apis/time-tracking
+- https://help.sap.com/docs/sap-digital-manufacturing/execution/manage-time-records
+- https://community.sap.com/t5/product-lifecycle-management-q-a/labor-tracking-hours-posting-to-erp-from-digital-manufacturing/qaq-p/13755236
+- https://learning.sap.com/courses/exploring-business-processes-in-sap-s4-hana-discrete-shopfloor-control/confirming-production-orders_d5811bf4-fb07-411d-8bdb-0f9cec11e4db
+- https://erpcorp.com/sap-controlling-blog/activity-postings-1-activity-types-in-review
+- https://learning.sap.com/courses/configuring-sap-digital-manufacturing-for-execution-basic-data-and-configuration/creating-resources
+- https://help.sap.com/docs/sap-digital-manufacturing/execution/tool-status
+- https://learning.sap.com/courses/analyzing-manufacturing-data-in-sap-digital-manufacturing/oee-calculation-in-dm
+- https://www.e3s-conferences.org/articles/e3sconf/pdf/2018/13/e3sconf_icemee2018_02027.pdf
+- https://www.top10erp.org/products/epicor-mattec-advanced-mes
+- https://encompass-inc.com/advanced-mes-connected-factory-machine-interface-unit-epicor-kinetic/
+- https://www.gingerhelp.com/knowledgebase-epicor-erp/integrating-iiot-devices-with-epicor
+- https://www.epiusers.help/t/mes-machine-utilization/91778
+- https://www.epiusers.help/t/mattec-advanced-mes-machines/81080
+- https://www.epiusers.help/t/mattec-mes/84042
+- https://support.machinemetrics.com/hc/en-us/articles/360026062834-Epicor-Installation-and-Integration-ERP-Systems-
+- https://scaledsolutionsgroup.com/deep-dive-how-epicor-kinetic-advanced-mes-transforms-shop-floor-control/
+- https://www.epicor.com/en-us/products/manufacturing-execution-software-mes/advanced-mes/data-exchange/
+- https://www.rockwellautomation.com/en-us/products/software/factorytalk/operationsuite/mes/plex-production-monitoring.html
+- https://plex.rockwellautomation.com/en-us/resources/10285-m-e-s-automation-orchestration-brochure-2.html
+- https://blog.themerlanos.com/2026/06/production-monitoring-in-plex-erp.html
+- https://www.vanmeterinc.com/rockwell-plex/production-monitoring
+- https://www.cumulus-erp.com/plex-ao-apm/
+- https://www.siemens.com/en-us/content/architecture-hub/op-center/
+- https://blogs.sw.siemens.com/opcenter/the-essentials-of-siemens-opcenter-execution-process-3-0/
+- https://www.connectedmanufacturing.com/knowledge-topics/opcenter-and-sap-integration
+- https://www.siemens.com/en-us/products/opcenter/execution/foundation-oee/
+- https://github.com/industrial-edge/Performance-Insight-OEE-Dashboard
+- https://github.com/odoo/odoo/blob/18.0/addons/mrp/models/mrp_workcenter.py
+- https://github.com/odoo/odoo/blob/18.0/addons/mrp/models/mrp_workorder.py
+- https://github.com/odoo/odoo/blob/18.0/addons/mrp/data/mrp_data.xml
+- https://www.odoo.com/documentation/18.0/applications/inventory_and_mrp/manufacturing/advanced_configuration/using_work_centers.html
+- https://www.odoo.com/documentation/16.0/applications/productivity/iot/devices/footswitch.html
+- https://www.odoo.com/documentation/19.0/applications/inventory_and_mrp/manufacturing/reporting/oee.html
+- https://www.sensflo.ai/articles/how-sensflo-helps-high-value-job-shops-measure-monitor-spindle-hours
+- https://proshoperp.com/blog/keep-making-chips/
+- https://proshoperp.com/blog/cost-accounting/
+- https://supergood.ai/docs/e2-shop-system-api
+- https://www.globalshopsolutions.com/shop-floor-data-collection-for-manufacturing
+- https://fulcrumpro.com/fulcrum-integrations
+- https://fulcrumpro.com/c/operations
+- https://fulcrumpro.com/article/streamline-production-with-work-orders-in-fulcrum
+- https://fulcrumpro.com/manufacturing-software/job-tracking
+- https://www.mrpeasy.com/blog/overall-equipment-effectiveness/
+- https://www.mrpeasy.com/resources/user-manual/production-planning/work-station-types/reports/
+- https://www.mrpeasy.com/resources/user-manual/production-planning/work-stations/
+- https://katanamrp.com/features/manufacturing/
+- https://reference.opcfoundation.org/ISA-95/v100/docs/7.4.1
+- https://reference.opcfoundation.org/specs/OPC-10030/8.2
+- https://reference.opcfoundation.org/ISA95JOBCONTROL/v200/docs/4
+- https://reference.opcfoundation.org/ISA95JOBCONTROL/v200/docs/4.3
+- https://reference.opcfoundation.org/specs/OPC-10031-4/6.2.1.1
+- https://github.com/MESAInternational/B2MML-BatchML/tree/master/Schema
+- https://reference.opcfoundation.org/specs/OPC-30050/6.3.8
+- https://beckhoff-usa-community.github.io/SPT-Libraries/References/PackML.html
+- https://model.mtconnect.org/Version2.6/Profile/DataTypes/ExecutionEnum/
+- https://model.mtconnect.org/Version2.6/Profile/DataTypes/ControllerModeEnum/
+- https://model.mtconnect.org/Version2.6/Profile/DataTypes/AvailabilityEnum/
+- https://model.mtconnect.org/Version2.6/ObservationInformationModel/ObservationTypes/EventTypes/ProgramHeader/
+- https://model.mtconnect.org/Version2.6/ObservationInformationModel/ObservationTypes/EventTypes/PartCount/
+- https://model.mtconnect.org/Version2.6/ObservationInformationModel/ObservationTypes/EventTypes/PartId/
+- https://model.mtconnect.org/Version2.6/ObservationInformationModel/ObservationTypes/EventTypes/WorkOffset/
+- https://model.mtconnect.org/Version2.6/ObservationInformationModel/ObservationTypes/EventTypes/ProcessAggregateIdOrderNumber/
+- https://model.mtconnect.org/Version2.6/ObservationInformationModel/ObservationTypes/EventTypes/PartUniqueId/
+- https://model.mtconnect.org/Version2.6/ObservationInformationModel/ObservationTypes/EventTypes/ProcessOccurrenceId/
+- https://docs.mtconnect.org/MTC_Part_1_Overview+V1.2.pdf
+- https://reference.opcfoundation.org/specs/OPC-40001-1/12.2
+- https://reference.opcfoundation.org/specs/OPC-40001-1/13
+- https://reference.opcfoundation.org/specs/OPC-40501-1/8.4
+- https://reference.opcfoundation.org/specs/OPC-40001-3/7
+- https://tsapps.nist.gov/publication/get_pdf.cfm?pub_id=919754
+- https://standards.iteh.ai/catalog/standards/iso/8a9efc01-6c74-42a2-ad8f-ec19e84b48f0/iso-22400-2-2014
+- https://www.oee.com/oee-glossary/
diff --git a/.ai/specs/2026-10-12-oee-provider-integration.md b/.ai/specs/2026-10-12-oee-provider-integration.md
new file mode 100644
index 0000000000..9ff3f5cf92
--- /dev/null
+++ b/.ai/specs/2026-10-12-oee-provider-integration.md
@@ -0,0 +1,770 @@
+# OEE Provider integration (first provider: Sense)
+
+> Status: implemented (PR #1909)
+> Author: barbinbrad
+> Date: 2026-10-12
+
+> **Where the build differs from the first draft (the code wins; `.claude/rules/oee-provider.md`):**
+> - Unattributed machine time is a review queue with no status. Assign and
+> dismiss delete the row. There is no dismiss reason and no Reopen.
+> - The MES operation page shows no device badge. Only the work center
+> display shows the device state.
+> - The loaded operation is a history table, `workCenterLoad`. The open row
+> is the load. `workCenter` has no pointer column.
+> - The engine gives each moment of a run to an owner. Open sensor time
+> follows its owner when a load, a block or a press changes it.
+> - The MES press rules apply on every work center, with or without a device.
+> - The OEE tables are read-only through the API. A device maps only to its
+> own company's work center (composite FK). Carbon refuses Sense staging
+> (plain HTTP) in production.
+
+## TLDR
+
+An **OEE provider** is a machine-monitoring vendor. It reports whether each
+machine is running. OEE providers are a new class of integration, like
+accounting providers. A company can have more than one OEE provider active.
+Every provider uses the same interface, the same sync job and the same
+mapping screen.
+
+Sense is the first provider. Sense clips a current sensor
+onto each machine and reports state changes per **device**. Sense calls a
+device a station.
+
+The first step is the **device mapping**: the user pairs each provider device
+with one Carbon work center. When a device reports that its machine runs,
+Carbon creates a Machine `productionEvent` on that work center. The event
+goes to the work center's **loaded operation**. That is the job operation
+that a person last started on that work center. If nothing is loaded, the run
+goes to an **unattributed machine time** list. A supervisor assigns it to a
+job operation or dismisses it.
+
+## Overview diagram
+
+```mermaid
+sequenceDiagram
+ participant S as Sense API
+ participant J as oee-sync job
+ participant D as Carbon database
+ participant O as MES operator
+ participant V as ERP supervisor
+ O->>D: Start Setup on op A (loads A)
+ J->>S: GET device events since cursor
+ S-->>J: Active at 10:00
+ J->>D: Open Machine event on op A
+ O->>D: Press Machine Pause at 10:30 (ends the event)
+ S-->>J: Idle at 11:00, Active at 11:05
+ J->>D: Queue 10:30 to 11:00, open new event on A at 11:05
+ D->>D: Op A Done unloads A
+ J->>D: End A's event at the unload, queue the rest of the run
+ V->>D: Assign the queued time to op B
+```
+
+## Problem Statement
+
+Carbon records machine time only when an operator starts and stops the
+Machine timer in MES. Operators forget, and machines often run unattended
+after setup. So job cost is low, and the work center utilization KPI is
+wrong.
+
+Shops already install machine-monitoring sensors. A current clip knows only
+whether the machine is on. It does not know which job runs. Carbon cannot use
+the top of the schedule: operators skip operations for missing parts and
+expedites. Carbon cannot use the operator's clock-in either: an operator sets
+up a machine, stops the timer and walks away while the machine runs.
+
+Sense is the first vendor. Its public API
+(`http://bifrost-staging.sensemfg.com/docs`) has these endpoints:
+
+| Endpoint | Returns |
+|---|---|
+| `GET /v1/public/companies/sites` | sites, each with `id`, `name`, `timezone` |
+| `GET /v1/public/companies/stations` | stations, each with `id`, `machine_name`, `machine_manufacturer`, `machine_type`, `machine_model`, `site_id`, `last_calibration_attempt_status` |
+| `GET /v1/public/companies/sites/{site_id}/stations/{station_id}/events` | state changes, each with `id`, `status`, `created_at` (UTC). Query: `start_datetime`, `end_datetime`, `order`, `limit`, `offset`, `statuses` |
+| `GET …/stations/{station_id}/telemetry` | power and vibration samples, one per minute (not used in v1) |
+
+The `status` values are `Active`, `Idle`, `Alert` and `Offline`. Sense has no
+webhooks, so Carbon must poll. The API key is company-scoped: Sense finds the
+company from the key. On 2026-10-12 the staging company had 3 sites and 55
+stations. One site (`Reston - 2`) had the timezone `UTC`.
+
+Research: `.ai/research/oee-provider-integration.md`. No surveyed product
+infers the job from an on/off signal. Each product keeps one active job per
+machine, and a person or the ERP sets it. MachineMetrics keeps unmatched run
+time as an "Unknown Job" that a person assigns later. This spec copies both
+patterns.
+
+## Proposed Solution
+
+### 1. The OEE provider class
+
+An OEE provider is an integration with `providerRole: "oee"`. Every OEE
+provider implements one interface in `packages/ee/src/oee/types.ts`:
+
+```ts
+type MachineState = "Running" | "Idle" | "Down" | "Offline";
+
+interface OeeDevice {
+ externalDeviceId: string;
+ name: string;
+ externalSiteId: string | null;
+ siteName: string | null;
+ siteTimezone: string | null;
+ manufacturer: string | null;
+ model: string | null;
+ machineType: string | null;
+ calibrated: boolean | null;
+}
+
+interface OeeStateChange {
+ externalEventId: string;
+ state: MachineState;
+ changedAt: string; // UTC ISO 8601
+}
+
+interface OeeProvider {
+ id: OeeProviderId;
+ validate(): Promise<{ valid: boolean; error?: string }>;
+ listDevices(): Promise<OeeDevice[]>;
+ listStateChanges(
+ device: { externalDeviceId: string; externalSiteId: string | null },
+ window: { since: string; until: string }
+ ): Promise<OeeStateChange[]>;
+}
+```
+
+`getOeeProvider(client, companyId, integrationId)` builds the provider from
+the company's `companyIntegration` row. It reads the API key from Vault with
+`resolveIntegrationSecrets`.
+
+`getOeeProvider` finds the constructor in a registry,
+`OEE_PROVIDERS` (`packages/ee/src/oee/registry.ts`), which maps an
+integration id to a factory. Code outside the registry never branches on an
+integration id. The `no-integration-id-branching` check enforces this, so
+add `"sense"` to its `INTEGRATION_IDS` and its provider-directory exclusion.
+Code that must find the OEE integrations calls
+`getIntegrationIdsByRole("oee")`. A second provider adds one adapter and one
+registry entry. The sync job, the mapping screen and the attribution engine
+stay the same.
+
+The Sense adapter (`packages/ee/src/sense/`) maps Sense statuses to
+`MachineState` with an explicit allowlist:
+
+| Sense `status` | `MachineState` |
+|---|---|
+| `Active` | `Running` |
+| `Idle` | `Idle` |
+| `Alert` | `Down` |
+| `Offline` | `Offline` |
+
+If Sense returns another status, the adapter throws. The sync job then fails
+that device and keeps its cursor (`.ai/lessons.md` → "Financial
+discriminators require explicit verified allowlists").
+
+Sense ignores `offset`, and `offset=0` returns HTTP 400 (verified against
+staging on 2026-10-13). So the adapter pages by time: it requests
+`order=asc&limit=500`, and if the page is full it requests again from the last
+event's `created_at`. It drops events it has already seen, by `id`, and stops
+when a page is short or adds nothing new.
+
+### 2. Installing Sense
+
+Settings → Integrations → Sense. The descriptor `packages/ee/src/sense/config.tsx`
+copies the Rillet descriptor. It has 3 settings:
+
+| Setting | Type | Default |
+|---|---|---|
+| `apiKey` | `secret` | none (required) |
+| `environment` | `options`: Production (`https://bifrost.sensemfg.com`), Staging (`http://bifrost-staging.sensemfg.com`) | Production |
+| `minimumStateSeconds` | `number` | 60 |
+
+`onHealthcheck` calls `validate()`, which calls `GET /v1/public/companies/sites`.
+
+### 3. Device mapping
+
+The drawer of each OEE integration gets a **Devices** tab. The loader calls
+`listDevices()` and reads the mappings in parallel. Redis caches the device
+list for 60 seconds. Each integration save clears the cache. The tab shows one
+row per device:
+
+| Column | Source |
+|---|---|
+| Device | `name`, then manufacturer, model and machine type as muted text |
+| Site | `siteName` |
+| Calibrated | `calibrated` as a badge |
+| Work center | a `Combobox` of active work centers, plus a mapped work center that is inactive |
+
+Rules:
+
+1. The user picks a work center and saves the row. The action upserts a
+ `workCenterDevice` row. It stores the name, site and site timezone of the
+ device in the current provider list, not the form's values.
+2. If the device is not in the current provider list, the action refuses.
+3. If the work center already has a device from any OEE provider, the action
+ refuses. The message names the other device and provider. The combobox
+ leaves out the work centers that another device holds.
+4. If the device's site timezone differs from the work center's location
+ timezone, the row shows a warning icon. The tooltip names both timezones.
+ A location with no timezone (null or `''`) uses the company's. Carbon uses
+ the location timezone for all local time.
+5. The user clears the combobox to unmap. The action ends the time that the
+ device's sensor opened on the work center (`endSensorMachineTime`). Then it
+ deletes the `workCenterDevice` row. A remap does the same on the old work
+ center and inserts a new row.
+6. A new mapping charges no time before the moment of the save. The first
+ sync reads the 24 hours before the mapping only to learn the starting
+ state.
+
+### 4. The loaded operation (community)
+
+The table `workCenterLoad` holds the loads of each work center. Each row has
+`jobOperationId`, `loadedAt` and `unloadedAt`. The row with `unloadedAt` null
+is the loaded operation. The loaded operation is the operation that is
+physically on the machine. It does not depend on a sensor, so it is AGPL code.
+It exists on every work center, with or without a device.
+
+Two interceptors write the table. The API can only read it.
+
+1. A writer inserts a `productionEvent` row with `endTime IS NULL` and a
+ `workCenterId`. Then `sync_load_work_center_operation` loads the row's
+ operation. Setup, Labor and Machine starts all load. So does the QR start
+ (`/x/start/:operationId`).
+2. The interceptor takes a transaction advisory lock for the work center.
+ Loads on one work center run one at a time.
+3. If the event's `startTime` is earlier than the newest `loadedAt` or
+ `unloadedAt` of the work center, the interceptor writes nothing. A late
+ event never undoes a later load or unload.
+4. If the operation is already loaded, the interceptor writes nothing.
+5. Else the interceptor ends the open row at `startTime`. Then it inserts a
+ row with `loadedAt` = `startTime`.
+6. A row inserted with an `endTime` (an ERP entry or an assigned interval)
+ never loads. An event loads only its own company's operation onto its own
+ company's work center.
+7. `sync_unload_work_center_operation` ends the operation's open row. It does
+ this when the status changes to `Done` or `Canceled`, when the operation
+ is deleted, and when it moves to another work center. It sets
+ `unloadedAt` = `GREATEST(NOW(), loadedAt)`.
+8. Stopping a timer does not unload the operation. That is what lets an
+ unattended run reach the job.
+
+The interceptor has no status rule. A starting event reopens a Done operation
+first (`sync_set_job_operation_in_progress`, a BEFORE interceptor).
+
+A CHECK refuses `unloadedAt < loadedAt`. A partial unique index allows one
+open row per work center. `jobOperationId` has no foreign key. A second
+relationship between `jobOperation` and `workCenter` makes PostgREST refuse
+the existing embeds between the two tables (PGRST201).
+
+The sync reads this history. A run that the provider reports late goes to
+the operation that was loaded when the machine ran.
+
+The MES work-center display (`/display/:workCenterId/work`) shows the loaded
+operation. It reads `loadedJobOperationId` from the view
+`workCentersWithBlockingStatus`, which takes it from the open row. If the work
+center has a `workCenterDevice`, the display also shows the machine state.
+
+pg_cron deletes a row 7 days after its `unloadedAt`. It keeps the row longer
+while a device on the work center has not planned past the unload
+(`appliedThrough` is null or earlier than `unloadedAt`). It never deletes an
+open row.
+
+### 5. Attribution rules
+
+The engine is a pure function, `planMachineTime`, in
+`packages/ee/src/oee/engine.ts`. It returns a list of writes. The sync job
+applies them.
+
+**Inputs.**
+
+| Input | Meaning |
+|---|---|
+| `loads` | The work center's loads in the planned window. Each has `jobOperationId`, `from`, `to` and `assignable`. |
+| `blocks` | The periods when maintenance blocks the work center (`from`, `to`). |
+| `lastManualChangeAt` | The latest operator press. |
+| `firstUnplannedPressAt` | The earliest press since the last sync (`workCenterDevice.unplannedPressAt`). |
+| `openMachineEvent` | The newest open Machine event on the work center: `id`, `jobOperationId`, `startTime`, and `system` (true when the sync created it). |
+| `openUnattributed` | The open unattributed row. |
+| `lastMachineEventEndTime` | The latest Machine `endTime` after `currentStateAt`. |
+| `recordedIntervals` | The Machine events and unattributed rows in the window: `id`, `kind`, `startTime`, `endTime`. |
+| `currentState`, `currentStateAt` | The applied state. |
+| `mappedAt`, `minimumStateSeconds`, `now` | The mapping time, the debounce and the clock. |
+| `changes` | The stored changes after `appliedThrough`, in time order. |
+
+`assignable` is false when the operation is Done or Canceled, when its job is
+locked (Completed, Closed or Cancelled), or when the operation no longer
+exists. `machineTimeRefusal` (`packages/ee/src/oee/assignable.ts`) holds this
+rule. The sync, the assign write and the ERP suggestion cards all use it.
+
+**The owner rule.** The sensor decides whether the machine ran. The owner of
+each moment of a run decides who gets the time:
+
+1. If maintenance blocks the work center at that moment, the owner is the
+ queue.
+2. If an operator pressed Machine after the run started, and at or before
+ that moment, the owner is the queue. The press stopped the operator's
+ time, not the machine.
+3. Else, if the operation loaded at that moment is `assignable`, the owner is
+ that operation.
+4. Else the owner is the queue.
+
+"The queue" is `unattributedMachineTime`. The owner changes only at an edge:
+a load begins or ends, a block begins or ends, or a press. The engine splits
+each stretch of run time at these edges and gives each piece to its owner. It
+never records time that a Machine event or an unattributed row already holds.
+So the same facts give the same result in any order of arrival.
+
+A closed piece for an operation becomes a Machine event with `employeeId` =
+null and `createdBy` = `system`. The engine drops a closed queue piece shorter
+than `minimumStateSeconds`. A piece that reaches the present while the
+machine runs stays open. A queue piece opens only after it lasts
+`minimumStateSeconds`.
+
+**Debounce.** The engine drops a state that lasts less than
+`minimumStateSeconds`. The previous state continues through it. The engine
+applies a state change only after the change has lasted
+`minimumStateSeconds`, or after the next change confirms it. Repeated reports
+of one state count as one run.
+
+**Applied state.** `currentState` is the state the engine applied last.
+`currentStateAt` is the time that state began. `appliedThrough` is the
+`changedAt` of the last stored change the engine consumed, applied or dropped.
+Each sync reads the `machineStateChange` rows after `appliedThrough`. A change
+that has not yet lasted `minimumStateSeconds` stays pending, and the next sync
+reads it again.
+
+**First sync.** A new device has no `currentState`. The first sync reads from 24
+hours before the mapping. The engine takes the last change before the mapping
+as the starting state, at the time of the mapping. So a machine that was
+already running when the user mapped it opens time from the mapping, never
+earlier.
+
+**State changes.** For each new state change, in time order:
+
+1. If the state does not change, skip it.
+2. If `changedAt <= lastManualChangeAt`, the provider reported the change
+ late. The press already decided the time after it. A late run is recorded
+ closed by the owner rule, up to the press or up to an earlier stop. A late
+ stop trims the queue (see "Time around a press").
+3. If the state is `Running` and a Machine event or an unattributed row is
+ open, do nothing.
+4. If the state is `Running`, open time for the owner at `changedAt`: a
+ Machine event on the loaded operation, or an unattributed row.
+5. If the state is `Idle`, `Down` or `Offline`, end the open Machine event and
+ the open unattributed row at `changedAt`.
+
+**Open time follows its owner.** An open sensor event or open unattributed
+row closes at the first edge where its owner changes. The new owner gets the
+rest of the run. Examples:
+
+- An operator starts Setup on operation B while a sensor event runs on A. The
+ next sync ends the event on A at B's `loadedAt`. It opens an event on B at
+ the same instant.
+- Maintenance ends while the machine runs. The open unattributed row ends,
+ and an event on the loaded operation opens.
+- Operation A goes Done while the machine runs. The unload ends A's load, so
+ A's event ends at the unload. The rest of the run goes to the queue.
+
+An operator's open Machine event follows only the start of a block. A load
+change does not move it.
+
+**Blocked work center.** A `Down` dispatch blocks the work center from its
+`createdAt` until it is Completed or Cancelled. A `Planned` dispatch blocks it
+from `actualStartTime` while it is In Progress. The view
+`workCentersWithBlockingStatus` counts In Progress dispatches only. The engine
+uses the broader periods, because the MES ends every event on the work center
+when a user creates a Down dispatch. A supervisor dismisses the queued time
+as maintenance.
+
+**Steady state.** After the changes, the engine checks one more case. The
+device is `Running`, `currentStateAt > lastManualChangeAt`, and nothing is
+open. Then the engine records the run up to now, by the owner rule. The start
+is the latest Machine `endTime` after `currentStateAt`, or `currentStateAt`
+when that is later. This rule covers a Machine event that a maintenance
+dispatch or End Shift closed during a run.
+
+**Time around a press.**
+
+- **Running past a press.** The machine runs at a press and keeps running.
+ The time after the press goes to the queue. If the machine stops within
+ `minimumStateSeconds` of the press, the engine records nothing.
+- **Two presses between syncs.** The sync passes the earliest press since the
+ last sync. If the machine ran through it, the time between the presses that
+ nothing holds goes to the queue.
+- **A late stop.** A stop can arrive after a press and fall inside a queue
+ row that the press ended. The engine cuts the row to the time the machine
+ ran: it updates, splits or deletes the row. The engine never trims a
+ Machine event. Queue rows do not post, so a trim is safe.
+
+**Short rows.** Each sync deletes the closed unattributed rows on its work
+center that are shorter than `minimumStateSeconds`.
+
+### 6. The MES Machine button (community)
+
+The Machine timer stays visible. It shows the open Machine event, as it does
+today (`useOperation` treats an open Machine event as active for every
+operator). The MES operation page shows no device badge. The work center
+display shows the device state.
+
+A machine has one machine time, and operators share it. The press rules apply
+on every work center, with or without a device:
+
+1. **Start** on operation C: end every open Machine event on the work center
+ at the press time, from any operator or the sensor. Insert a Machine event
+ on C that starts at the press time. The insert loads C.
+2. **Pause**: end every open Machine event on the work center at the press
+ time. The operation stays loaded.
+
+A press does not end an event that starts after the press time. On a work
+center with a device, the press also does 2 things:
+
+1. It ends the open unattributed row at the press time.
+2. It sets `lastManualChangeAt` to the later of its value and the press time.
+ It sets `unplannedPressAt` to the earlier of its value and the press time.
+ The sync clears `unplannedPressAt`.
+
+Example: the machine is Active. The operator presses Pause at 10:03. Machine
+time on the operation stops at 10:03. If the machine runs on, the time after
+10:03 goes to the queue until the machine stops.
+
+**Locks.** A press takes its locks in one order:
+
+1. The `workCenterDevice` row `FOR UPDATE` (`lockWorkCenterDevice`). The sync
+ takes this lock first too.
+2. A transaction advisory lock on the work center. It exists with or without
+ a device.
+3. For an End only: the event row `FOR UPDATE`, while the event is open.
+
+`lockMachinePress` (`@carbon/database/machine-time`) takes the first 2 locks.
+`recordManualMachinePress` reads the press time under them. So presses on one
+work center run one at a time, and the recorded press never moves backwards.
+
+**Start and End.** `startMachineProductionEvent` (MES
+`operations.service.ts`) runs the press, the event insert and the tracked
+activity in one Kysely transaction. If one write fails, nothing ends.
+`endMachineProductionEvent` refuses an event that has already ended, and an
+event that starts after the press. The route then says "This event has
+already ended". The End route reads the event's own work center and type, not
+the form's values.
+
+**Permissions.** The Kysely writes skip RLS. So `event.tsx` and
+`start.$operationId.tsx` check `create` or `update` on `production` before
+any write. `event.tsx` returns a flash message when it refuses.
+
+**Posting.** The routes post every event that a press ends, except batch
+events (`postEndedProductionEvents`). The QR start with `type=Machine`
+follows rule 1. After the start, it ends the operation's Setup and Labor
+events and posts them.
+
+### 7. The sync job
+
+1. The Inngest cron `oee-sweep` runs every 2 minutes. It selects active
+ `companyIntegration` rows whose integration has `providerRole = 'oee'` and
+ at least 1 `workCenterDevice`. It sends one `carbon/oee-sync` event per
+ (company, integration). It copies `ramp-sweep.ts`.
+2. `oee-sync` runs with concurrency 1 per company and a `singleton` (skip)
+ per company and integration. It syncs all devices of the integration
+ inside one `step.run`. One step per device would multiply the Inngest cost
+ by the device count.
+3. If the company is not entitled to `INTEGRATIONS`, the integration is
+ inactive, or the key is empty, `getOeeProvider` returns an error. The job
+ skips the integration.
+4. For each device, the job reads state changes from `lastEventAt − 10
+ minutes` to now. The overlap catches events that Sense stores late. The
+ first sync reads from 24 hours before the mapping.
+5. The job inserts the changes into `machineStateChange` with
+ `ON CONFLICT DO NOTHING`. The unique key is
+ (`workCenterDeviceId`, `externalEventId`, `companyId`).
+6. The job opens one Kysely transaction per device. It locks the
+ `workCenterDevice` row `FOR UPDATE`. The MES press takes the same lock
+ first, so a press and a sync never interleave.
+7. The job reads the open Machine event, the open unattributed row, the
+ latest Machine `endTime` and the stored changes. It computes the start of
+ the window: the earliest instant this plan can touch. It reads the loads,
+ the block periods and the recorded intervals inside the window.
+8. The job runs `planMachineTime` and applies the writes. A close matches
+ only a row that is still open.
+9. The job deletes the closed unattributed rows on the work center that are
+ shorter than `minimumStateSeconds`.
+10. In the same transaction, the job sets `currentState`, `currentStateAt`,
+ `appliedThrough`, `lastEventAt` and `lastSyncedAt`. It clears
+ `unplannedPressAt` and `lastSyncError`. `lastEventAt` follows the newest
+ stored change, never the clock.
+11. If one device fails, the job writes `lastSyncError` on that device and
+ keeps its cursor. The other devices continue. An
+ `OeeProviderUnavailableError` (network failure, timeout, 5xx) stops the
+ run, because every device would fail the same way.
+
+The job never posts to the GL. Carbon has no scheduled sweep that posts
+production events. An event posts at one of 3 moments:
+
+1. At a press: the MES routes post every event that the press ended, except
+ batch events.
+2. At operation finish: `finishJobOperation` (MES) and `completeOperation`
+ (ERP) post the operation's ended, unposted events.
+3. At job completion: `complete_job_to_inventory` posts every ended, unposted
+ event of the job.
+
+A sensor event that the sync closes posts at operation finish or job
+completion. Until it posts, a supervisor can edit it on the job's Events tab.
+
+When a user uninstalls Sense, its `onUninstall` hook (`senseOnUninstall`) ends
+the open sensor time of every Sense device of the company. The mappings stay.
+
+### 8. Unattributed machine time (ERP)
+
+Production → **Unattributed Time** (`x+/production+/machine-time.tsx`). The
+nav item shows only while an OEE integration is active. The list copies the
+Batches list.
+
+| Column | Value |
+|---|---|
+| Work center | name |
+| Location | the work center's location |
+| Start, End | in the work center's location timezone |
+| Duration | `endTime − startTime`; "Running" while open |
+| State | "Running" (blue) or "Stopped" (green) |
+
+The list has 5 filters: work center, location, start date, end date and
+state. The date filters use the same timezone as the list (the view
+`unattributedMachineTimes`). The list has no sort.
+
+`unattributedMachineTime` is a review queue, not a record. It has no status. A
+row leaves the queue in 3 ways:
+
+1. **Assign**: the action inserts a Machine `productionEvent` with the row's
+ `startTime` and `endTime`, `employeeId` = null and `createdBy` = the user.
+ Then it deletes the row. The event is the record.
+2. **Not job time** (dismiss): the action deletes the row. It takes no
+ reason.
+3. pg_cron deletes the row 30 days after its `endTime`.
+
+Assign and dismiss refuse a row that has no `endTime`: the machine is still
+running. Assign also refuses a Done or Canceled operation and a locked job. It
+checks them under row locks, inside its transaction.
+
+The drawer (`machine-time.$id.tsx`) reviews the rows of the filtered list one
+at a time:
+
+- Suggestion cards show the operations that ran on the work center on the
+ days the row covers, best match first. Keys 1 to 6 assign a card.
+- A search card lists the open operations at the work center's location,
+ including operations with no work center.
+- "Not job time" dismisses the row. Skip, j and k move between rows.
+
+Each answer moves to the next row. Closing the drawer returns to the list with
+its filters.
+
+### 9. Out of scope for v1
+
+| Item | Why not now |
+|---|---|
+| An MES prompt ("What's running on W1?") | User decision (Q3). The ERP list comes first. |
+| Splitting one unattributed row across 2 operations | A run without a load is normally one job. The supervisor can edit the event on the job's Events tab. |
+| An OEE availability or downtime report | `machineStateChange` stores the data for it. The report is a later spec. |
+| Telemetry, cycle counts, program numbers | A current clip gives no program. Telemetry is not needed to attribute time. |
+| Sense partner tokens (`/v1/public/partners/…`) | Sense issues company-scoped keys to customers. |
+| A pool work center with several devices | The mapping is 1:1 (Q1). |
+| Importing history from before the mapping | No loaded operation exists for that period. |
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|---|---|---|
+| Provider cardinality | Several OEE providers can be active at once. A work center has at most 1 device across all providers. | User decision (Q1). Shops mix vendors. The single-active trigger skips the `oee` role. `UNIQUE(workCenterId, companyId)` on `workCenterDevice` holds the real rule. |
+| Mapping cardinality | 1 device ↔ 1 work center | User decision (Q1). The scheduler treats a work center as capacity 1 (`.claude/rules/scheduling-data-structures.md`). A pool work center ("VF2 ×3") must be split into one work center per machine. |
+| Mapping storage | New table `workCenterDevice`, not `externalIntegrationMapping` | The row also holds the cursor, the live state and `lastManualChangeAt`. The cross-provider unique rule is a plain UNIQUE here. In `externalIntegrationMapping` the unique key includes `integration`, so it cannot enforce it. |
+| Attribution | The loaded operation per work center. It is never the top of the schedule. Carbon never infers a job. | User decision (Q2). Research: every vendor keeps an explicit active job per machine. |
+| How an operation is loaded | Any open `productionEvent` insert on the work center | Setup, Labor, Machine and the QR start already insert one. Shops change nothing. |
+| Unattributed time | Its own table, cleared from an ERP list | User decision (Q3). `productionEvent.jobOperationId` is NOT NULL, so unattributed time cannot be a production event. |
+| Manual Machine timer | Kept on every work center. A press ends every open Machine event on the work center. The time after a press in the same run goes to the queue. Pause keeps the operation loaded. | User decision (Q4, Q4b, Q4c). A work center has one machine time, so time is never counted twice. |
+| GL posting | Sensor events post at operation finish or job completion. Events that a press ends post at the press. There is no posting sweep. | User decision (Q5). A wrong sensor attribution stays editable until the operation is done. |
+| License boundary | Provider, sync, mapping and the unattributed list are commercial (`packages/ee`, `.ee.tsx`), gated by `INTEGRATIONS`. The loaded operation, the MES button rules and the display are AGPL. | User decision (Q6). Matches every other integration. |
+| Timezone | Store UTC instants. Use the work center's `location.timezone` for local time. Warn on a site/location mismatch. | User decision (Q7). |
+| Polling | Inngest cron every 2 minutes, 10-minute overlap, idempotent insert | Sense has no webhooks. A 2-minute delay keeps the work center display useful. The overlap plus the unique key makes a re-read safe. |
+| Debounce | `minimumStateSeconds`, default 60 | Research: MachineMetrics uses 60 s for micro-stops. Vendors use 30 s to 3 min. |
+| `Alert` and `Offline` | Both end machine time. `Offline` means "no data", not "down". | Research: vendors treat a sensor gap as unknown, never as running. |
+| Blocked work center | Running time goes to the unattributed list | Maintenance run time must not reach a job. The supervisor dismisses it as maintenance. |
+| Backfill | None. A mapping charges no time before the moment of the save. | The first sync reads the 24 hours before the mapping only to learn the starting state. |
+| Load storage | The history table `workCenterLoad`. The open row is the load. | A pointer column held the same fact twice. Clearing its timestamp on unload let a late event load a replaced operation (`.ai/lessons.md`). |
+| Who gets each moment | The owner rule (section 5) | The same facts give the same result in any order of arrival. |
+| Sync errors | `lastSyncError` and `lastSyncedAt` on `workCenterDevice`, shown in the Devices tab | `accountingSyncOperation.direction` allows only accounting directions. A per-device column is enough for v1. |
+| Heuristic 1: multi-tenancy | Every new table has `companyId`, composite PK `("id", "companyId")` and `id('prefix')` | `.claude/rules/conventions-database.md` |
+| Heuristic 2: service shape | Service functions take `client` first and return `{ data, error }`. The ee write functions call `requireEntitlement(client, companyId, "INTEGRATIONS")` first. | `.claude/rules/conventions-services.md`, `.claude/rules/commercial-licensing.md` |
+| Heuristic 3: RLS | `workCenterDevice`, `machineStateChange`, `unattributedMachineTime` and `workCenterLoad` are SELECT-only for company employees (`packages/database/src/authz/manifest.ts`). | Every write goes through Kysely in the sync, the MES press, the Sense uninstall hook, an entitlement-gated ee function or an interceptor (`.claude/rules/authz-manifest.md`). |
+| Heuristic 4: permissions | Devices tab: `settings_update`. Unattributed list: `production_view`. Assign or dismiss: `production_update`. MES Machine start: `production_create`. MES Machine end: `production_update`. | Same scopes as integration settings and job events. The MES routes check them because the Kysely writes skip RLS. |
+| Heuristic 5: forms | The drawer submits Assign and Dismiss with a fetcher. The route action validates them with zod validators in `production.models.ts`. | `.claude/rules/conventions-forms.md` |
+| Heuristic 6: module layout | ERP UI in `modules/production/ui/MachineTime/*.ee.tsx` and `modules/settings/ui/Integrations/OeeDevices.ee.tsx`. Reads in `production.service.ts`. Writes in `@carbon/ee/oee.server`. | One service and one models file per module. Gated writes live in `packages/ee`. |
+| Heuristic 7: compatibility | Additive, with one change for work centers with no device: a Machine press ends every open Machine event on the work center. | No public contract changes. |
+
+## Data Model Changes
+
+```mermaid
+erDiagram
+ workCenter ||--o| workCenterDevice : "mapped to"
+ workCenter ||--o{ workCenterLoad : "loads"
+ workCenterLoad }o--|| jobOperation : "loaded operation (no FK)"
+ workCenterDevice ||--o{ machineStateChange : "reports"
+ workCenter ||--o{ unattributedMachineTime : "has"
+ jobOperation ||--o{ productionEvent : "has"
+```
+
+The migrations, in order:
+
+| Migration | Change |
+|---|---|
+| `20261013030022_oee-provider.sql` | The role, the `machineState` enum and the three OEE tables |
+| `20261013170425_unattributed-time-queue.sql` | The queue drops its status columns |
+| `20261013191915`, `20261013201722` | Composite foreign keys to `workCenter`, and retention |
+| `20261013233811` | The view `unattributedMachineTimes` |
+| `20261014010130_work-center-load-history.sql` | The table `workCenterLoad` |
+| `20261014024119_oee-load-is-history.sql` | Drops the pointer columns. Adds the constraints, `unplannedPressAt` and the sync's indexes |
+
+| Table | Columns and constraints |
+|---|---|
+| `integration` | `providerRole` CHECK allows `'oee'`. `check_single_active_provider_role()` returns early for `oee`. Row `sense` with `providerRole = 'oee'`. |
+| `workCenterDevice` (`id('wcd')`) | `workCenterId`, `integration`, `externalDeviceId`, `externalSiteId`, `siteTimezone`, `deviceName`, `currentState` (`machineState`), `currentStateAt`, `appliedThrough`, `lastEventAt`, `lastManualChangeAt`, `unplannedPressAt`, `lastSyncedAt`, `lastSyncError`, audit columns. `UNIQUE (workCenterId, companyId)`, `UNIQUE (integration, externalDeviceId, companyId)`. FK `(workCenterId, companyId)` → `workCenter`. |
+| `machineStateChange` (`id('msc')`) | `workCenterDeviceId`, `workCenterId`, `externalEventId`, `state`, `changedAt`. `UNIQUE (workCenterDeviceId, externalEventId, companyId)`. FK `(workCenterId, companyId)` → `workCenter`. pg_cron deletes rows older than 30 days and rows of an unmapped device. |
+| `unattributedMachineTime` (`id('umt')`) | `workCenterId`, `startTime`, `endTime`, audit columns. No status. FK `(workCenterId, companyId)` → `workCenter`. pg_cron deletes rows 30 days after `endTime`. |
+| `workCenterLoad` (`id('wcl')`) | `workCenterId`, `jobOperationId` (no FK), `loadedAt`, `unloadedAt`, `createdAt`. CHECK `unloadedAt IS NULL OR unloadedAt >= loadedAt`. Partial unique index: one open row per work center. FK `(workCenterId, companyId)` → `workCenter`. |
+
+`machineState` is the enum `'Running', 'Idle', 'Down', 'Offline'`. The view
+`workCentersWithBlockingStatus` exposes `loadedJobOperationId` from the open
+`workCenterLoad` row. Two indexes serve the sync: `productionEvent
+(workCenterId, endTime) WHERE type = 'Machine'` and `maintenanceDispatch
+(workCenterId)`.
+
+The migrations write no policies. The authz manifest renders them: the four
+OEE tables are SELECT-only for company employees. Every write goes through
+Kysely in the sync, the MES press, the Sense uninstall hook or an
+entitlement-gated `@carbon/ee/oee.server` function. The two interceptors are
+AFTER interceptors in `packages/database/src/event-system/attachments.ts`:
+`sync_load_work_center_operation` on `productionEvent` and
+`sync_unload_work_center_operation` on `jobOperation`. The dispatchers are
+`SECURITY DEFINER`, so the interceptors write `workCenterLoad` for an
+operator who has no `resources_update` permission.
+`workCenterDevice` and `unattributedMachineTime` have a statement broadcast
+(`broadcast_table_changes`). Backups remap
+`workCenterLoad.jobOperationId` and `machineStateChange.workCenterDeviceId`
+(`packages/jobs/src/backups/id-refs.ts`).
+
+`SECRET_KEYS` (`packages/ee/src/integrations/secrets.ts`) gets
+`sense: ["apiKey"]`. The key stays at `metadata.apiKey`, as Linear's does, so
+the install path needs no credential fold. `FORM_SECRET_INTEGRATIONS` in
+`integrations.$id.tsx` gets `"sense"`. Three unions get `"oee"`: the
+descriptor type (`packages/ee/src/types.ts`), `ProviderRole`
+(`packages/ee/src/index.ts`) and `ProviderRole` (`packages/ee/src/sync/topology.ts`).
+The topology picks only the accounting and spend roles, so an `oee` row never
+enters it. The integration drawer hides Sync Activity for the `oee` role, and
+`IntegrationCard` does not treat an active `oee` integration as an incumbent.
+
+## API / Service Changes
+
+| Location | Function | Purpose |
+|---|---|---|
+| `packages/ee/src/oee/types.ts` | `OeeProvider`, `MachineState`, `OeeDevice`, `OeeStateChange` | The provider contract |
+| `packages/ee/src/oee/engine.ts` | `planMachineTime` | Pure attribution rules (section 5). Unit-tested. |
+| `packages/ee/src/oee/assignable.ts` | `machineTimeRefusal` | Can an operation take machine time |
+| `packages/ee/src/oee/service.server.ts` | `getOeeProvider`, `upsertWorkCenterDevice`, `deleteWorkCenterDevice`, `assignUnattributedMachineTime`, `dismissUnattributedMachineTime` | The writes call `requireEntitlement` first. |
+| `packages/ee/src/sense/provider.ts` | `SenseProvider` | The Sense adapter |
+| `packages/ee/src/sense/config.tsx`, `hooks.server.ts` | `Sense` descriptor, `senseHealthcheck`, `senseOnUninstall` | Install, health and uninstall |
+| `packages/database/src/machine-time.ts` | `lockWorkCenterDevice`, `lockMachinePress`, `recordManualMachinePress`, `endSensorMachineTime` | The locks and the writes that end machine time |
+| `packages/jobs/src/inngest/functions/integrations/oee-sweep.ts` | cron, every 2 minutes | Sends `carbon/oee-sync` per company and integration |
+| `packages/jobs/src/inngest/functions/integrations/oee-sync.ts`, `oee-sync-device.ts` | `oeeSyncFunction`, `syncOeeDevice` | Section 7 |
+| `apps/erp/app/modules/production/production.service.ts` | `getUnattributedMachineTimes`, `getUnattributedMachineTime`, `getUnattributedMachineTimeNeighbors`, `getWorkCenterDayEvents`, `getMachineTimeOperationCandidates` | Reads for the list and the drawer |
+| `apps/erp/app/modules/production/production.models.ts` | `assignMachineTimeValidator`, `dismissMachineTimeValidator` | Form validators |
+| `apps/erp/app/modules/settings/oee-devices.server.ts` | `getOeeDevicesTabData`, `saveWorkCenterDeviceMapping` | Devices tab loader and action |
+| `apps/mes/app/services/operations.service.ts` | `startMachineProductionEvent`, `endMachineProductionEvent`, `postEndedProductionEvents` | Section 6 |
+| `apps/mes/app/routes/x+/event.tsx`, `start.$operationId.tsx` | Machine start and end on every work center | Section 6 |
+| `apps/mes/app/services/display.service.ts` | `getDisplayWorkCenter`, `getDisplayDeviceState` | Work-center display |
+
+## Closest Sibling
+
+| Part | Sibling | Files copied |
+|---|---|---|
+| Provider class | Accounting providers (`providerRole: "accounting"`) | `packages/ee/src/accounting/core/types.ts` (provider interface shape), `packages/ee/src/index.ts` (`getIntegrationIdsByRole`) |
+| Descriptor and API-key settings | Rillet | `packages/ee/src/rillet/config.tsx`, `rillet/hooks.server.ts` |
+| Role-targeted polling | Ramp | `packages/jobs/src/inngest/functions/integrations/ramp-sweep.ts`, `ramp-sync.ts` |
+| Devices tab | Account Mapping | `apps/erp/app/modules/settings/ui/Integrations/AccountMapping.tsx` (row form, `Combobox`, per-row save). The row is flipped: the provider object is on the left and the Carbon record is the combobox. |
+| Unattributed list | Production → Batches | `apps/erp/app/routes/x+/production+/batches.tsx`, `modules/production/ui/Batches/BatchesTable.tsx` |
+| Assign drawer | Job events | `apps/erp/app/routes/x+/job+/$jobId.events.new.tsx`, `ProductionEventForm` |
+
+The feature deviates from its siblings in 3 places. Each one is a row in
+Design Decisions:
+
+1. The mapping lives in its own table, not `externalIntegrationMapping`.
+2. The `oee` role allows several active providers.
+3. Sync errors are columns on the device, not Sync Activity rows.
+
+## UI Changes
+
+| Surface | Change | Archetype |
+|---|---|---|
+| ERP Settings → Integrations → Sense | New integration card. Drawer with Connection settings and a **Devices** tab. | Integration drawer (same as Rillet) |
+| ERP Production nav | New item **Unattributed Time** in the Production group, after Batches. It shows only while an OEE integration is active. | List page with a drawer (same as Batches) |
+| ERP Production → Unattributed Time → row | Review drawer: suggestion cards, a search card, "Not job time" and Skip | Drawer |
+| MES operation screen | No change. The Machine toggle's dot already marks running time. Button rules in section 6. | No new archetype |
+| MES work-center display | Loaded operation, and the device state when mapped | Existing display |
+| Docs | `docs/content/docs/integrations/oee.mdx`, added to `meta.json`; a "Loaded operation" section in `docs/content/docs/reference/work-centers.mdx` | Integration guide |
+
+If the company is not entitled to `INTEGRATIONS`, the Devices tab and the
+Unattributed Time page render the upgrade overlay (`usePlanGate`). The
+Unattributed Time nav item shows only while an OEE integration is active, so
+a company with no OEE integration does not see it.
+
+## Acceptance Criteria
+
+- [ ] With the staging API key, installing Sense shows a healthy connection. The Devices tab lists the 55 Sense stations with their site names.
+- [ ] Mapping Station 0002 to work center W1 saves a `workCenterDevice` row. The action refuses a second station on W1. Its message names Station 0002.
+- [ ] Mapping a station from site `Reston - 2` (UTC) to a work center whose location is in `America/New_York` shows the timezone warning.
+- [ ] Activating Sense while another `oee` integration is active succeeds. The single-active trigger still refuses a second active `accounting` integration.
+- [ ] An operator starts Setup on operation A at W1 and stops it. The open `workCenterLoad` row of W1 names A.
+- [ ] An event that starts before the newest `loadedAt` or `unloadedAt` of W1 loads nothing.
+- [ ] Sense reports Active at T1 and Idle at T2 for the mapped station. Within 2 sync runs, a Machine `productionEvent` on A exists with `startTime` = T1, `endTime` = T2, `employeeId` null and `postedToGL` false.
+- [ ] After operation A is finished, that event has `postedToGL` = true. Its cost is (T2 − T1) × W1's machine rate plus overhead.
+- [ ] With nothing loaded on W1, an Active change creates an open `unattributedMachineTime` row. The row appears on Production → Unattributed Time.
+- [ ] Assigning a stopped row to operation B creates a Machine event on B with the row's start and end, and deletes the row.
+- [ ] Dismissing a stopped row deletes it, and no event exists. Dismissing a running row fails.
+- [ ] The machine is Active and the operator presses Pause at 10:03. The event ends at 10:03. The time after 10:03 until the machine stops goes to an unattributed row. The next Idle→Active change opens a new event on the same operation.
+- [ ] A sensor event runs on A, and the operator presses Machine Start on operation C. A's event ends at the press time. C's event starts at the press time. C is loaded.
+- [ ] A sensor event runs on A, and an operator starts Setup on operation B. The next sync ends A's event at B's `loadedAt` and opens an event on B at that instant.
+- [ ] Running the sync twice over the same window creates no duplicate `machineStateChange`, `productionEvent` or `unattributedMachineTime` rows.
+- [ ] A state that lasts 30 seconds with `minimumStateSeconds` = 60 creates no event and does not close an open one.
+- [ ] If Sense returns a status outside the allowlist, that station gets `lastSyncError` and keeps its cursor. Other stations still sync.
+- [ ] W1 has an In Progress maintenance dispatch with OEE impact Down. Running time on W1 creates an unattributed row, not an event on the loaded operation.
+- [ ] Operation A goes Done while the machine runs. The event ends at the unload, and the rest of the run becomes an unattributed row that starts at that time.
+- [ ] On a work center with no `workCenterDevice`, a Machine press ends every open Machine event on the work center and writes no device column.
+- [ ] Uninstalling Sense ends the open sensor events and unattributed rows of its devices. The `workCenterDevice` rows stay.
+- [ ] On a plan without `INTEGRATIONS`, the Devices tab and the list show the upgrade overlay. Calling `assignUnattributedMachineTime` throws `EntitlementError`.
+- [ ] `planMachineTime` has unit tests for every rule in section 5 and the press examples in section 6, including the same facts in different orders of arrival.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|---|---|---|
+| A stale loaded operation: nobody finishes or reloads it, so another job's run time goes to it | Med | The work center display shows the loaded operation. Any timer start on the right operation reloads. A supervisor can edit the event on the job's Events tab until the operation is finished. |
+| The staging host is plain HTTP, so the API key travels unencrypted | Med | Production uses HTTPS. The Staging option says "testing only" in its description. |
+| Sense rate limits and backfill behavior are not documented | Med | Verify with one curl before the job is wired into the cron (`.ai/lessons.md` → "A VERIFY-flagged provider endpoint in a cron loop is an outage"). The 10-minute overlap tolerates late events. Confirm the limits with Sense before launch. |
+| Inngest cost of a 2-minute cron | Low | The sweep sends events only for companies with at least one mapped device. |
+| `sync_set_job_operation_in_progress` reopens a Done operation on an open-event insert | Low | The engine opens an event only on an `assignable` operation, which is never Done or Canceled. Assign inserts a closed event and refuses a Done or Canceled operation. |
+| A long Sensor Offline gap hides real run time | Low | Offline ends machine time. The Devices tab shows `currentState` = Offline and the time of the last sync. |
+| An operator presses Machine Start while the machine is Idle. The event runs until the sensor reports the next change. | Med | This is the override the user chose (Q4c). The work center display shows the sensor's Idle state. The supervisor can edit the event until the operation is finished. |
+| One work center models a pool of machines | Low | Out of scope. The mapping refuses a second device, and the docs say to split the work center. |
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until these are answered.
+
+- [x] Can a company have more than one OEE provider active at once? — **Answer:** Yes. A work center has at most one device across all providers.
+- [x] How does Carbon pick the job operation for sensor run time? — **Answer:** The loaded operation per work center. The latest Setup, Labor or Machine start there sets it, and it survives clock-out. Run time with nothing loaded is unattributed. Never the top of the schedule. No inference from In Progress operations.
+- [x] Where is unattributed time resolved in v1? — **Answer:** An ERP supervisor list only. Assign to a job operation, or dismiss. The MES prompt is later work. (Shipped: dismiss takes no reason and deletes the row.)
+- [x] What happens to the manual MES Machine timer on a mapped work center? — **Answer:** It stays visible and in sync with the sensor. There is one Machine event at a time, so no duplicates.
+- [x] What does the Machine button do when the sensor drives the timer? — **Answer:** It overrides the sensor for the operator's time. Pause keeps the operation loaded. (Shipped as the owner rule: the time after a press in the same run goes to the queue.)
+- [x] When does sensor machine time post to the GL? — **Answer:** At operation finish or job completion. (Shipped: there is no posting sweep; section 7 lists the 3 moments an event posts.)
+- [x] Which parts are commercial? — **Answer:** The provider, the sync, the mapping and the unattributed list are in `packages/ee`, gated by `INTEGRATIONS`. The loaded operation and its MES display are AGPL.
+- [x] Which timezone wins for local time? — **Answer:** The work center's location timezone. Store UTC. Warn when the Sense site timezone differs.
+
+## Changelog
+
+- 2026-10-14: Fixes from the strict self-review (`.ai/plans/2026-10-14-oee-review-fixes.md`). The open `workCenterLoad` row is the load: the migration drops `workCenter.loadedJobOperationId` and `loadedAt`. A load older than the newest boundary in the history writes nothing. An unload ends the open row at `GREATEST(NOW(), loadedAt)`. The engine applies one owner rule to every piece of a run. Open sensor time follows its owner across load, block and press edges. A late stop trims the closed queue rows. A press takes its time under the locks and records `unplannedPressAt`. A Machine start writes the press, the event and the tracked activity in one transaction. The routes check permission before any write and post every event a press ends. Uninstalling Sense ends its open sensor time. The ERP review keeps the list filters and spans the days of the row.
+- 2026-10-13: Build changes. Unattributed time became a queue with no status. Maintenance blocks became periods. The load gained its history table, `workCenterLoad`. The OEE tables became read-only through the API, with composite foreign keys to `workCenter`. The MES press rules apply on every work center.
+- 2026-10-12: Planning pass. Corrected the secret path, the interceptor timing, the view recreation and the indexes. Added the engine's inputs, applied state (`appliedThrough`) and first-sync rules. The steady-state rule now reopens time on the loaded operation when the rules allow it.
+- 2026-10-12: Created. Research: `.ai/research/oee-provider-integration.md`. Prior thinking: the kyoto session of 2026-10-07 ("Current clip job identification").
diff --git a/.claude/rules/oee-provider.md b/.claude/rules/oee-provider.md
new file mode 100644
index 0000000000..a34464c925
--- /dev/null
+++ b/.claude/rules/oee-provider.md
@@ -0,0 +1,511 @@
+---
+paths:
+ - packages/ee/src/oee/**
+ - packages/ee/src/sense/**
+ - packages/jobs/src/inngest/functions/integrations/oee-*.ts
+ - packages/database/src/machine-time.ts
+---
+
+# OEE Providers (machine monitoring)
+
+An OEE provider reports when each machine runs. Carbon records that run time
+as Machine `productionEvent` rows on the operation loaded on the work center.
+Sense is the only provider today. Spec:
+`.ai/specs/2026-10-12-oee-provider-integration.md`. Where the spec and the
+code differ, the code wins.
+
+The descriptor `Sense` (`packages/ee/src/sense/config.tsx`) declares
+`providerRole: "oee"` and category "Machine Monitoring". The sweep finds OEE
+integrations through `getIntegrationIdsByRole("oee")`. Several OEE
+integrations may be active at once:
+`check_single_active_provider_role()` returns early for the `oee` role
+(migration `20261013030022_oee-provider.sql`). The real rule is on
+`workCenterDevice`: `UNIQUE(workCenterId, companyId)`, so a work center has at
+most one device across every OEE provider.
+Its `workCenterId` FK is composite, `(workCenterId, companyId)` →
+`workCenter (id, companyId)` (migration `20261013191915`), so a device can
+only map to its own company's work center; `upsertWorkCenterDevice` also
+checks it first ("Work center not found"). `machineStateChange` and
+`unattributedMachineTime` carry the same composite FK (migration
+`20261013201722`).
+
+## Files
+
+| File | Role |
+|---|---|
+| `packages/ee/src/oee/types.ts` | `OeeProvider` contract (`validate`, `listDevices`, `listStateChanges`), `MachineState`, `OeeDevice`, `OeeStateChange` |
+| `packages/ee/src/oee/engine.ts` | `planMachineTime`: the pure attribution engine. No database, no env. Pinned by `engine.test.ts` |
+| `packages/ee/src/oee/assignable.ts` | `machineTimeRefusal(operationStatus, jobStatus)`: `"Done"`, `"Canceled"`, `"Locked"` or null. The one rule for "can this operation take machine time", used by the sync (a load's `assignable`), `assignUnattributedMachineTime` and the review's suggestion cards. Built on `isJobLocked` / `JOB_LOCKED_STATUSES` (`packages/utils/src/job-status.ts`, re-exported by the ERP's `production.models.ts`) |
+| `packages/ee/src/oee/registry.ts` | `OEE_PROVIDERS` (keyed by `OeeProviderId`): provider id → factory, the one place a provider is named. `isOeeProviderId`, and `createOeeProvider(integrationId, metadata)`: the one resolution (id check, "No API key", the `DEFAULT_MINIMUM_STATE_SECONDS` default, the factory) behind `getOeeProvider` and the Sense healthcheck |
+| `packages/ee/src/oee/service.server.ts` | `getOeeProvider` (runtime, degrades through `companyHasFeature("INTEGRATIONS")`), and 4 authoring writes that embed `requireEntitlement("INTEGRATIONS")`: `upsertWorkCenterDevice`, `deleteWorkCenterDevice`, `assignUnattributedMachineTime`, `dismissUnattributedMachineTime` |
+| `packages/ee/src/sense/provider.ts` | `SenseProvider`, the Sense HTTP adapter. Pinned by `provider.test.ts` |
+| `packages/ee/src/sense/config.tsx` | The descriptor: `apiKey` (secret), `environment`, `minimumStateSeconds` (default 60) |
+| `packages/ee/src/sense/hooks.server.ts` | `senseHealthcheck` (calls `provider.validate()`) and `senseOnUninstall` (registered in `packages/ee/src/hooks.server.ts`; see "Uninstalling Sense") |
+| `packages/jobs/src/inngest/functions/integrations/oee-sweep.ts` | Cron `*/2 * * * *`. Sends one `carbon/oee-sync` per (company, OEE integration) that is active and has at least 1 mapped device |
+| `packages/jobs/src/inngest/functions/integrations/oee-sync.ts` | `carbon/oee-sync`, concurrency 1 per company, `singleton` (skip) per company and integration. Syncs every device of the integration in ONE `step.run` |
+| `packages/jobs/src/inngest/functions/integrations/oee-sync-device.ts` | `syncOeeDevice`: read, store, then plan and apply under the device lock. Pinned by `oee-sync-device.database.test.ts` (needs `SUPABASE_DB_URL`) |
+| `packages/database/src/machine-time.ts` | `lockWorkCenterDevice` (`FOR UPDATE` on the device row), `lockMachinePress` (the device lock, then a transaction advisory lock per work center), `recordManualMachinePress` and `endSensorMachineTime`. Shared by the sync, the MES, the device mapping writes and the Sense uninstall hook. Pinned by `machine-time.test.ts` (needs `SUPABASE_DB_URL`) |
+| `apps/mes/app/services/operations.service.ts` | `startMachineProductionEvent` (press, event and tracked activity in one Kysely transaction), `endMachineProductionEvent` (press locks, then the open event's row lock), `postEndedProductionEvents` (posts the events a press ended), `endProductionEvent` (ends an open event, scoped by `companyId`) |
+| `packages/database/src/event-system/handlers/sync_load_work_center_operation.sql` | `productionEvent` AFTER INSERT: writes a load into `workCenterLoad` (see "The loaded operation") |
+| `packages/database/src/event-system/handlers/sync_unload_work_center_operation.sql` | `jobOperation` AFTER UPDATE / DELETE: ends the operation's open `workCenterLoad` row when it becomes Done or Canceled, is deleted, or moves to another work center |
+
+UI:
+
+- **Devices tab** — `apps/erp/app/modules/settings/ui/Integrations/OeeDevices.ee.tsx`,
+ rendered by `x+/settings+/integrations.$id.tsx` only for an active `oee`
+ integration. Its loader and action live in
+ `modules/settings/oee-devices.server.ts` (`getOeeDevicesTabData`,
+ `saveWorkCenterDeviceMapping`). The loader reads the provider's devices and
+ the mappings in parallel. The provider's device list (`listOeeDevices`) is
+ cached in Redis for 60 s (`oeeDevicesCacheKey` in
+ `modules/settings/oee-devices-cache.ts`: `oee-devices:<companyId>:<integrationId>`,
+ never an error); `clearCompanyIntegrationCache` (`settings.server.ts`)
+ deletes it on every integration save, so a new API key or environment never
+ shows the old stations. A mapping save refuses a station that is not in the
+ current list, and it stores that listed device's name, site and site
+ timezone, not the form's. The work center picker of a row leaves out the
+ work centers another integration maps and the ones another device of this
+ integration holds. A mapped work center shows even when inactive. A
+ location timezone of `''` counts as none: the timezone warning compares the
+ site with the company's timezone then.
+- **Production → "Unattributed Time"** — `x+/production+/machine-time*.tsx`
+ and `modules/production/ui/MachineTime/`. The nav item appears only while an
+ `oee` integration is active (`useProductionSubmodules`, through
+ `getIntegrationIdsByRole("oee")` and `useIntegrations`).
+- **MES press rules** — `apps/mes/app/routes/x+/event.tsx` and
+ `x+/start.$operationId.tsx`.
+- **MES machine state** — the work center display
+ (`display+/$workCenterId.work.tsx`) shows `DeviceStateBadge`
+ (`components/Display/`) and "Loaded: …". `getDisplayWorkCenter`
+ (`display.service.ts`) reads `loadedJobOperationId` from the view
+ `workCentersWithBlockingStatus`, which takes it from the open
+ `workCenterLoad` row. `getDisplayDeviceState` hides the state when the
+ device has a sync error or has not synced for 10 minutes. The operation
+ page shows no device badge: its Machine toggle's green dot already marks
+ running time.
+
+## The loaded operation (community)
+
+`workCenterLoad` records which operation was loaded on a work center, and
+when (migration `20261014010130`). The open row (`unloadedAt` null) IS the
+load: there is no pointer column (migration `20261014024119` dropped
+`workCenter."loadedJobOperationId"` and `"loadedAt"`). It exists on every work
+center, with or without a device. The view `workCentersWithBlockingStatus`
+exposes the open row's operation as `loadedJobOperationId`.
+
+- **Load.** Any `productionEvent` INSERT with `endTime` null and a
+ `workCenterId` loads its operation: Setup, Labor, Machine and the QR start.
+ An event inserted with an `endTime` never loads. The interceptor loads only
+ when the work center and the operation are the event's own company. It
+ takes a transaction advisory lock per work center
+ (`workCenterLoad:<workCenterId>`), so loads on one work center run one at a
+ time. It ends the open row at the event's `startTime` and opens a new row
+ with `loadedAt` = `startTime`.
+- **Older starts are refused.** A start earlier than the newest boundary in
+ the work center's history (the latest `loadedAt` or `unloadedAt`) writes
+ nothing, so a late event never undoes a later load or unload. A reload of
+ the operation already loaded writes nothing. There is no status rule: a
+ starting event reopens a Done operation first
+ (`sync_set_job_operation_in_progress`, a BEFORE interceptor).
+- **Unload.** A `jobOperation` status change to `Done` or `Canceled` ends the
+ operation's open row, and so does deleting the operation or moving it to
+ another work center (the old work center unloads). An unload sets
+ `unloadedAt` = `GREATEST(NOW(), "loadedAt")`. A Pause does not unload.
+- **Constraints.** A CHECK refuses `unloadedAt < loadedAt`, and a partial
+ unique index (`workCenterLoad_one_open_idx`) allows one open row per work
+ center.
+- **No foreign key.** `workCenterLoad.jobOperationId` has none: a second
+ `jobOperation`↔`workCenter` relationship made PostgREST refuse every
+ existing embed of one from the other (PGRST201), so the unload interceptor
+ also handles DELETE instead. Backups remap it through `ID_REF_COLUMNS`
+ (`packages/jobs/src/backups/id-refs.ts`), with
+ `machineStateChange.workCenterDeviceId`.
+- **Read-only.** `workCenterLoad` is SELECT-only through the API (authz
+ manifest); only the two interceptors write it. No event function lists a
+ load column in `ignored_columns`, and `auditConfig.skipFields` has none.
+- **Retention.** pg_cron `work-center-load-retention` (04:35 UTC) runs
+ `util.purge_work_center_loads()`. It deletes a row more than 7 days after
+ its `unloadedAt`, unless a device on its work center has not planned past
+ that unload yet (`appliedThrough` null or earlier than `unloadedAt`). An
+ open row is never deleted. Pinned by
+ `supabase/tests/work-center-loaded-operation.test.sql`.
+
+Carbon never infers a job from the schedule. Only the load attributes time,
+read from the history at the moment each piece of a run happened: the order
+in which reports and presses arrive does not change the operation.
+
+## Attribution rules (`planMachineTime`)
+
+The sensor decides WHETHER the machine ran. The **owner** of each moment of a
+run decides WHO gets it:
+
+1. A moment while maintenance blocks the work center → the queue.
+2. A moment after an operator press in the same run (a press after the run
+ started, at or before the moment) → the queue. The press stopped the
+ operator's time, not the machine.
+3. Else the operation loaded at that moment (the load whose period holds it),
+ if it is `assignable`.
+4. Else the queue.
+
+`assignable` is `machineTimeRefusal(...) === null`: false once the operation
+is Done or Canceled, its job is locked (Completed, Closed, Cancelled), or the
+operation no longer exists. "The queue" is `unattributedMachineTime`.
+
+The owner can change only at an **edge**: a load begins or ends, a block
+begins or ends, or a press. The engine never records time that a Machine
+event or an unattributed row already holds (`recordedIntervals`).
+
+**Recording a stretch.** The engine takes the parts of the stretch that no
+recorded interval holds, splits them at the edges, and gives each piece to its
+owner. A closed operation piece becomes a system Machine event
+(`employeeId` null, `createdBy` `system`). A closed queue piece shorter than
+`minimumStateSeconds` is dropped. A piece that reaches now while the machine
+runs opens instead: an operation piece at once, a queue piece only once it
+has lasted `minimumStateSeconds`.
+
+**Inputs.** `loads` (`LoadPeriod`: `jobOperationId`, `from`, `to`,
+`assignable`), `blocks` (`BlockPeriod`: `from`, `to`), `lastManualChangeAt`
+(the latest press), `firstUnplannedPressAt` (the earliest press since the last
+sync), `openMachineEvent` (`id`, `jobOperationId`, `startTime`, `system`),
+`openUnattributed`, `lastMachineEventEndTime`, `recordedIntervals` (`id`,
+`kind` `event` | `unattributed`, `startTime`, `endTime`), the applied state,
+and the stored changes after `appliedThrough`.
+
+The engine reads the changes in time order:
+
+1. If the state does not change, skip it.
+2. If `changedAt <= lastManualChangeAt`, the provider reported it late. The
+ press already decided what came after it, so the change fills only the
+ time the press could not see. A late `Running` opens nothing: the run, up
+ to the press or to an earlier stop, is recorded closed by owner. That is
+ what an earlier report would have recorded.
+3. If the state is `Running` and a Machine event or an unattributed row is
+ open, do nothing.
+4. If the state is `Running`, open time for the owner at `changedAt`: a
+ system Machine event on the loaded operation, else an unattributed row.
+5. If the state is `Idle`, `Down` or `Offline`, open time follows its owner
+ up to the stop. Then the open Machine event (an operator's too) and the
+ open unattributed row end at `changedAt`.
+
+**Open time follows its owner.** At each stop and at the end of every plan,
+an open system slot (a sensor Machine event or an unattributed row) closes at
+the first edge where the owner changes, and the new owner records the rest.
+So a load change mid-run moves the sensor's time to the newly loaded
+operation, the end of maintenance hands queue time back to the operation, and
+an unload ends the operation's event and queues the rest. An operator's open
+Machine event follows only a block start: maintenance stops it, a load change
+does not. This replaces the old special case that closed a system event on a
+Canceled operation.
+
+**Blocked.** The sync passes the work center's `blocks`. A `Down` dispatch
+blocks from its `createdAt` (the MES ends every event on the work center when
+one is created, `dispatch.new.tsx`) until it is Completed or Cancelled; while
+it is `Open`, `Assigned` or `In Progress` the block has no end. A `Planned`
+dispatch blocks from `actualStartTime` (else `updatedAt`, else `createdAt`)
+while `In Progress`; a Completed or Cancelled one counts only when it has an
+`actualStartTime`. A closed block ends at `completedAt`, else
+`actualEndTime`, else `updatedAt`, else `createdAt`. This is broader than the
+view `workCentersWithBlockingStatus` (In Progress only), which the MES display
+and the QR start still use. An operator Machine event started after the block
+began stays open. Pinned by `engine.test.ts`.
+
+**Debounce.** Repeated reports of one state are one run: the first starts it,
+the last is how far it was read. The engine drops a state shorter than
+`minimumStateSeconds`. The last change stays pending until it has lasted the
+minimum. The next sync reads it again.
+
+**First sync.** A new device has no `currentState`. The sync reads from 24
+hours before `createdAt` (the mapping time). The engine takes the last change
+before the mapping as the start state, at the mapping time. The engine never
+charges time before the mapping. A remap deletes the row and inserts a new one, so
+the mapping time and the applied state start again.
+
+**Unmap and remap.** No later sync closes time on a work center the device
+has left. So `deleteWorkCenterDevice` and the remap path of
+`upsertWorkCenterDevice` first call `endSensorMachineTime` on the OLD work
+center, under the device row lock: it ends, at now, the open Machine events
+created by `system` and the unattributed rows with no `endTime`. An
+operator's own open Machine event stays open.
+
+**Uninstalling Sense.** The integration card's **Uninstall** posts to
+`x+/settings+/integrations.deactivate.$id.tsx`, which deactivates the
+integration and runs its `onUninstall` hook.
+`senseOnUninstall` ends the sensor time of every Sense device of the company
+at one instant: per device, `lockWorkCenterDevice` then
+`endSensorMachineTime` (`userId` `system`). The mappings stay, so a
+reconnect resumes each device from its cursor.
+
+**Steady state.** After the changes, if the device is `Running`, nothing is
+open, and no press came after the run started
+(`currentStateAt > lastManualChangeAt`), the engine records the run again by
+owner, up to now. The start is the latest Machine `endTime` on the work
+center after `currentStateAt` (`lastMachineEventEndTime`), or
+`currentStateAt` when that is later. This covers a Machine event that a
+maintenance dispatch or End Shift closed, and an operation that went Done
+mid-run. Time while the work center is blocked opens as unattributed time.
+
+**A load change mid-run.** The sensor's open event follows its owner: the
+next sync ends it on the old operation at the new load's `loadedAt` and opens
+an event on the new operation from that instant. An operator's open event
+stays on its operation. A Machine Start on the new operation ends every open
+Machine event anyway (the press).
+
+**Late reports around a press.** A run reported only after a press goes to
+the operation loaded when each piece ran, as a report on time would have. Two
+more cases:
+
+- **Two presses between syncs.** The sync passes the earliest press since the
+ last sync (`unplannedPressAt`). When the machine ran through it, the time
+ from that press to the last press that no event or row holds is recorded,
+ by the owner rule (so to the queue: it follows a press in the same run).
+- **A late stop trims the queue.** A stop reported only after a press may
+ fall inside a queue row that the press closed. The engine cuts every closed
+ unattributed row that overlaps the idle stretch (from the stop to the next
+ `Running` change, else to the last press): `deleteUnattributed` when
+ nothing is left, `updateUnattributed` (plus an `insertUnattributed` for the
+ part after the idle stretch) otherwise. Queue rows are not posted, so this
+ is safe. The engine never trims a Machine event.
+
+**Running past a press.** A machine that is `Running` at the press
+(`currentStateAt <= lastManualChangeAt`) and runs on after it: the press, a
+Pause, stopped the operator's time, not the machine. The time after the
+press that no event or row holds goes to the queue, never to the loaded
+operation. A sync while the machine still runs opens the row once it has run
+`minimumStateSeconds` past the press; a stop reported with no sync between
+records the same interval closed. A machine that stops sooner, as it winds
+down after a Pause, records nothing. After a Start the operator's open event
+holds the time, so nothing is recorded.
+
+**Short rows.** Each sync deletes the closed unattributed rows on its work
+center shorter than `minimumStateSeconds`, whoever closed them (the sync, a
+press or an unmapping).
+
+## The MES Machine button
+
+A machine has one machine time: operators share it. A "Start" or "Pause"
+press with "Machine" selected calls `recordManualMachinePress` inside a Kysely
+transaction:
+
+1. It takes the press locks (`lockMachinePress`): the device row
+ (`FOR UPDATE`, as the sync and the mapping writes take it first), then a
+ transaction advisory lock on the work center
+ (`machinePress:<workCenterId>`), which exists with or without a device.
+ The reverse order deadlocked with a running sync. Presses on one work
+ center therefore run one at a time.
+2. It reads the press time under the locks (`clock_timestamp()`), unless the
+ caller passes `pressedAt`. It returns `pressedAt`.
+3. On every work center, with or without a device, it ends each open Machine
+ event at the press time, from any operator or the sensor. It skips an event
+ that starts after the press, so no duration goes negative. It returns the
+ ended ids (`endedEventIds`).
+4. On a mapped work center, it also ends the open unattributed time at the
+ press time. Without this, a Start on a running machine with no loaded
+ operation counted the same minutes on the operator's event and in the
+ supervisor queue.
+5. On a mapped work center, it sets `lastManualChangeAt` to
+ `GREATEST(lastManualChangeAt, pressedAt)`, so the latest press never moves
+ backwards, and `unplannedPressAt` to `LEAST(unplannedPressAt, pressedAt)`,
+ the earliest press since the last sync. The sync clears `unplannedPressAt`.
+
+**Start.** `startMachineProductionEvent` (MES `operations.service.ts`) runs the
+press, inserts the operator's Machine event with `startTime` = `pressedAt`
+(the insert loads the operation), and writes the tracked activity and its
+output when a tracked entity is given, in ONE transaction. If any part fails,
+nothing was ended. `event.tsx` and the QR start `start.$operationId.tsx` use
+it for a Machine start on an operation with a work center.
+
+**End.** `event.tsx` reads the event's own work center, type and `endTime`
+(scoped by `companyId`), not the form's. An event that has already ended is
+refused ("This event has already ended"). For a Machine event,
+`endMachineProductionEvent` takes the press locks, then the event row
+`FOR UPDATE` while it is still open, then presses. It returns null, and
+rolls back, when the event is no longer open or the press could not end it
+(it starts after the press). Any other event ends through
+`endProductionEvent`, which matches only while `endTime` is null and scoped
+by `companyId` ("This event has already ended, or you cannot end it"). A
+repeated End therefore never moves an end time or ends a newer event.
+
+**Permissions.** The Machine writes go through Kysely and skip RLS, so the
+routes check permission before any write: `create: "production"` for a
+Machine start, `update: "production"` for a Machine end. `event.tsx` returns a
+flash on refusal ("You do not have permission to start machine time" / "… to
+end machine time"); the QR route throws through `requirePermissions`.
+
+**Posting.** The routes post every event a press ended:
+`postEndedProductionEvents` invokes `post-production-event` per event and
+skips batch events (`jobOperationBatchId` set: batch timers post at batch
+completion). A failure is logged, never thrown. `event.tsx` also posts an
+operator's own ended non-Machine event, and the events an `exclusive` start
+ended. After a successful QR Machine start, the QR route ends the operation's
+open Setup and Labor events and posts them with the events the press ended.
+The QR route reads the `jobOperation` scoped by `companyId`.
+
+After a Pause on a running machine, the time until it stops goes to the queue
+("Running past a press").
+
+## The sync
+
+1. `oee-sweep` (every 2 minutes) sends `carbon/oee-sync` per (company,
+ integration). An installed integration with no mapped device costs nothing.
+2. `oee-sync` resolves the provider with `getOeeProvider`. If the company is
+ not entitled, the integration is inactive, or the key is empty, the run
+ returns `skipped`.
+3. For each device, `syncOeeDevice` reads changes from
+ `lastEventAt − 10 minutes` to now. The overlap catches events that the
+ provider stores late. The first sync reads from the mapping time minus 24
+ hours.
+4. It inserts the changes into `machineStateChange` with
+ `ON CONFLICT DO NOTHING` on (`workCenterDeviceId`, `externalEventId`,
+ `companyId`), in chunks of 500. A stored change at or before
+ `appliedThrough` is logged (`console.warn`), not replanned: replanning
+ would rewrite closed, maybe posted, events.
+5. It opens one transaction and locks the device. If the device was removed
+ or remapped meanwhile, it stops. It reads the open Machine event, the open
+ unattributed row, the latest Machine `endTime` after `currentStateAt`, and
+ the stored changes after `appliedThrough`.
+6. It computes `windowFrom`: the earliest of the first stored change,
+ `unplannedPressAt`, `lastManualChangeAt`, the run's start (the later of
+ `currentStateAt` and the latest Machine end; the mapping time on a first
+ sync), and the open event's and row's starts. It then reads, bounded by the
+ window: the loads (open, or unloaded after `windowFrom`, joined to the
+ operation and job for `assignable`), the block periods ("Blocked"), and the
+ recorded intervals (Machine events and unattributed rows that are open or
+ end after `windowFrom`).
+7. It runs `planMachineTime` and applies the writes. Each close matches only
+ while `endTime` is null.
+8. It deletes the closed unattributed rows on the work center shorter than
+ `minimumStateSeconds`.
+9. In the same transaction it sets `currentState`, `currentStateAt`,
+ `appliedThrough`, `lastEventAt`, `lastSyncedAt`, clears `unplannedPressAt`
+ and `lastSyncError`. `lastEventAt` is the newest stored `changedAt`, never
+ earlier than before, not the sync time; it also follows changes stored by
+ an earlier attempt whose plan failed (their insert conflicts now and
+ returns nothing).
+10. If a device fails, the job writes `lastSyncError` (500 characters at most)
+ on that device. Its cursor does not move. The other devices continue,
+ unless the error is `OeeProviderUnavailableError` (network failure,
+ timeout, 5xx): then the run stops, since every device would fail the same
+ way. `oee-sync` is a `singleton` (skip) per company and integration.
+
+Kysely returns `timestamptz` as a JS `Date`. `syncOeeDevice` normalizes every
+instant with `toInstant` before the engine compares it.
+
+**GL posting.** The sync never posts. There is no scheduled sweep that posts
+production events. An event posts at one of three moments:
+
+1. At a press: the MES routes post every event the press ended
+ (`postEndedProductionEvents`, skipping batch events).
+2. At operation finish: MES `finishJobOperation` and ERP `completeOperation`
+ post the operation's ended, unposted events.
+3. At job completion: `complete_job_to_inventory` posts every ended,
+ unposted event of the job with a duration.
+
+A sensor event that the sync closes is an ordinary Machine event with no
+employee: it posts at operation finish or job completion. An assigned
+unattributed row also does not post at assign time.
+
+## Unattributed machine time
+
+`unattributedMachineTime` is a review queue, not a record: it has no status
+(migration `20261013170425_unattributed-time-queue.sql`).
+`assignUnattributedMachineTime` inserts a Machine event for the row's
+interval and deletes the row; the event is the record. It refuses a row with
+no `endTime` ("The machine is still running"), a `Done` or `Canceled`
+operation ("The operation is Done" / "The operation is Canceled") and a locked
+job ("Cannot modify a locked job. Reopen it first."), checked with
+`machineTimeRefusal` under row locks on the operation and the job inside its
+transaction (the route's own check is only the friendly redirect).
+`dismissUnattributedMachineTime` deletes the row only when it has an
+`endTime`; otherwise it returns "Machine time not found, or the machine is
+still running".
+
+The three tables the sync writes (`workCenterDevice`, `machineStateChange`,
+`unattributedMachineTime`) are SELECT-only through the API (authz manifest):
+every write goes through Kysely: in the sync, the MES press
+(`recordManualMachinePress`) and `senseOnUninstall`, all under the device
+lock, or in an entitlement-gated `@carbon/ee/oee.server` function (the
+mapping writes lock the device row; assign locks the unattributed row;
+dismiss deletes only a stopped row).
+`upsertWorkCenterDevice` maps devices only for an integration in
+`OEE_PROVIDERS` that is active for the company.
+
+pg_cron `unattributed-machine-time-retention` (04:23 UTC) runs
+`util.purge_unattributed_machine_time()`, which deletes rows whose `endTime`
+is more than 30 days old. A running row is never purged.
+
+The drawer (`x+/production+/machine-time.$id.tsx`, `MachineTimeDrawer.ee.tsx`)
+walks the queue in the list's order (`startTime` desc, then `id`; the list
+has no sort, `sort={null}`). `machineTimeQueueKeyset`
+(`machine-time-filters.ee.ts`) builds the PostgREST filters for the rows above
+and below a row. A row link carries the list's query string, so the drawer
+walks the filtered list; closing the drawer goes back to the list with its
+filters (not history back), and a queue move replaces the history entry. The
+list has 5 filters: work center, location, start date, end date, and state
+(Running blue / Stopped green: `Status` draws blue as a spinner and green as
+a check). The list shows each row in its location's timezone (a `''`
+timezone counts as none: the company's), and its CSV export writes the
+start, end and duration the same way. The date filters use the same days:
+the list and the queue read the view `unattributedMachineTimes` (migration
+`20261013233811`), which adds `startDate` and `endDate` in the location's
+timezone (else the company's, else UTC). `parseMachineTimeListFilters`
+(`machine-time-filters.ee.ts`, pinned by
+`apps/erp/test/machine-time-filters.ee.test.ts`) reads each range as two
+inclusive `YYYY-MM-DD` days, and `applyMachineTimeListFilters` applies them to
+the list and to the queue alike. The queue holds stopped rows only; a running row opens but shows
+"Running" in place of N of M:
+`getUnattributedMachineTimeNeighbors` gives the position and the rows above
+and below, and every answer redirects to the row below, else the row above,
+else the list. The suggestion cards come from `getWorkCenterDayEvents` (every
+production event on the work center overlapping the row's days: from the
+start of the day it started to the end of the day it ended, or of today while
+it runs, in the location's timezone) ranked by the pure
+`suggestMachineTimeOperations` (`machine-time-suggestions.ee.ts`, its
+`window` argument; pinned by
+`apps/erp/test/machine-time-suggestions.ee.test.ts`): operations that can take
+the time first, then by the gap to the row's interval (0 when they overlap),
+then by time run in the window; operations that `machineTimeRefusal` refuses
+show disabled. The search card reads `getMachineTimeOperationCandidates` (open
+operations on open jobs at the work center's location, this work center's
+first, then the rest of the location, including operations with no work
+center). If the
+queue, the events or the candidates fail to load, the loader logs it and the
+drawer says which part did not load (`loadErrors`) rather than showing it
+empty. Keys (`MACHINE_TIME_REVIEW_SHORTCUTS`): 1–6 assign a card
+(`MACHINE_TIME_SUGGESTION_LIMIT` = 6 cards), j/k move
+(the table behind binds the arrows); a repeated keydown is ignored and one
+answer per row is posted.
+
+**State change retention.** pg_cron `machine-state-change-retention` (04:29
+UTC) runs `util.purge_machine_state_changes()`: it deletes `machineStateChange`
+rows older than 30 days, and rows whose device was unmapped or remapped. The
+engine only reads rows after `appliedThrough`, so neither is ever read again.
+
+## Sense adapter
+
+- Base URL: `https://bifrost.sensemfg.com` (production) or
+ `http://bifrost-staging.sensemfg.com` (staging). Auth is
+ `Authorization: Bearer <apiKey>`. The key is company-scoped.
+- Staging has no HTTPS endpoint, so the `sense` factory in `OEE_PROVIDERS`
+ refuses it when `APP_ENV` is `production` (`SENSE_STAGING_REFUSED`); the
+ sync skips with that error and the healthcheck reports it.
+- Status allowlist: `Active` → `Running`, `Idle` → `Idle`, `Alert` → `Down`,
+ `Offline` → `Offline`. An unknown status throws, and the device records
+ the error. Never guess a state.
+- Events need the station's site. A station with no `site_id` throws
+ "Station has no site".
+- **Sense ignores `offset`, and returns 400 for `offset=0`.** So
+ `listStateChanges` pages by time. After a full page (500 events), it asks
+ again from the last event's `created_at` and drops the event ids it has
+ already seen. It stops on a short page or a page with no new event.
+
+## Local tooling
+
+`crbn migrate`'s authz sync can create new handler functions owned by
+`supabase_admin`. Then a later migration that replaces the function (a
+generated authz migration such as `20261014030025`) fails with "must be
+owner". Fix it locally:
+
+```sql
+ALTER FUNCTION public.sync_load_work_center_operation(text, text, jsonb, jsonb) OWNER TO postgres;
+ALTER FUNCTION public.sync_unload_work_center_operation(text, text, jsonb, jsonb) OWNER TO postgres;
+```
diff --git a/AGENTS.md b/AGENTS.md
index cad1f04292..0854dbeca2 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -135,6 +135,7 @@ IMPORTANT: Before any research or coding, match the task to this table. A single
| Ramp integration (charges, accounting-provider sync) | `.claude/rules/ramp-integration.md` |
| Jira integration | `.claude/rules/jira-integration.md` |
| Linear integration | `.claude/rules/linear-integration.md` |
+| OEE providers / machine monitoring (Sense, loaded operation, unattributed machine time) | `.claude/rules/oee-provider.md` + `apps/erp/app/modules/production/AGENTS.md` |
| Xero API / webhooks | `.claude/rules/xero-api-contact-structure.md` + `.claude/rules/xero-webhooks.md` |
| Redis (shared dev) | `.claude/rules/dev-shared-redis.md` |
| Client cache (`cachedClientLoader`, `useLoaderQuery`, `useAction`) | `.claude/rules/clientAction-patterns.md` + `packages/query/AGENTS.md` |
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index ca674aa83a..cb651145d0 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -28,6 +28,14 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced
- **Make to Asset branch.** A job with `fixedAssetClassId` completes into one new `fixedAsset` per unit (status `Active`, or `Under Construction` when the class `isConstructionInProgress`; `acquisitionCost` = swept WIP ÷ units; one Posted `fixedAssetTransfer` per asset, `type 'Capitalization'`, `sourceType 'Job'`); a job with `fixedAssetId` sweeps its WIP onto that Construction in Progress asset as one `fixedAssetCipCost` row + one transfer. The units never enter stock: no `itemLedger`, `costLedger`, `pickMethod` or `itemCost` write, and the WIP discharge posts Dr class `assetAccountId` / Cr WIP as an `'Asset Transfer'` journal (both lines still `documentId = jobId`, so the per-job WIP balance nets to zero). Each serial unit goes `Consumed` with `attributes["Fixed Asset"]` and a `'Capitalize'` `trackedActivity`; every company writes the asset cost (the journal is Provisional before the accounting cutover). Guards raise before anything moves: `'A job linked to a sales order line cannot complete to a fixed asset'`; `'A job that completes to a fixed asset class needs a serialized item'` (any quantity — every asset a class job makes is a fleet unit followed by its serial); `'Make to Asset needs a serialized item or a quantity of one'` (a job attached to an asset under construction); a job attached to a non-CIP asset is also refused (`'… is not in a Construction in Progress class'`). The item rule is `makeToAssetItemError` (`production.models.ts`), applied by `x+/job+/new.tsx` and `$jobId.details.tsx` on save (a field error on the item), by `x+/job+/update.tsx` on a property-panel item change and by `$jobId.status.tsx` when a job goes `Ready`, with the sales order line gate. Covered by `packages/database/supabase/tests/job-completion-to-asset.test.sql`. Full flow: `.claude/rules/fixed-asset-lifecycle.md`.
- Dialog logic lives in `ui/Jobs/job-complete-logic.ts` (pure, no JSX/lingui, unit-tested by `apps/erp/test/job-complete-logic.test.ts`); the SQL is covered by `packages/database/supabase/tests/job-completion-received-quantity.test.sql`, hand-run like its siblings (nothing in CI runs `supabase/tests/`).
+### Loaded operation and unattributed machine time
+
+- **Loaded operation** (community) — the open `workCenterLoad` row (`unloadedAt` null) IS the load; there is no pointer column on `workCenter` (migration `20261014024119` dropped `loadedJobOperationId`/`loadedAt`). The `productionEvent` interceptor `sync_load_work_center_operation` loads the operation of any event inserted with `endTime` null and a `workCenterId` (Setup, Labor, Machine, the MES QR start): it ends the open row at the event's `startTime` and opens a new one. An event inserted with an `endTime` never loads; a start earlier than the newest `loadedAt`/`unloadedAt` in the work center's history writes nothing, and a reload of the loaded operation writes nothing. `sync_unload_work_center_operation` (on `jobOperation`) ends the open row (`unloadedAt` = `GREATEST(NOW(), loadedAt)`) when the operation becomes `Done` or `Canceled`, is deleted, or moves to another work center; a Pause does not unload. An event loads only its own company's operation onto its own company's work center. A CHECK refuses `unloadedAt < loadedAt`, and a partial unique index allows one open row per work center. `jobOperationId` has no foreign key on purpose: a second `jobOperation`↔`workCenter` relationship makes PostgREST refuse embeds like `jobOperation` → `workCenter(name)` (PGRST201). The MES work center display shows it as "Loaded: …", read from `workCentersWithBlockingStatus.loadedJobOperationId`. It exists on every work center, with or without a device. Rows are deleted 7 days after the unload, unless a device on the work center has not planned past it. The OEE sync reads this history to give each piece of a run to the operation loaded when it ran.
+- **Machine time from an OEE device** — when a `workCenterDevice` (Settings → Integrations → Sense → Devices) maps a machine to the work center, the `oee-sync` job records its Running time as Machine `productionEvent` rows on the loaded operation: `employeeId` null, `createdBy` `system`. The sensor's open event follows the load: a Setup or Labor start on another operation moves the time to it. Those events post to the GL only when the operation finishes (MES `finishJobOperation`, ERP `completeOperation`) or the job completes (`complete_job_to_inventory`) — never at sync or assign time. There is no posting sweep.
+- **Unattributed machine time** — `unattributedMachineTime` is a review queue of Running time that no operation can take: nothing is loaded; the work center is blocked by maintenance (a `Down` dispatch from its `createdAt` until Completed or Cancelled, a `Planned` one from its actual start while `In Progress`); the loaded operation is Done or Canceled or its job is locked (`machineTimeRefusal`); or the machine ran on after an operator's Machine press in the same run (a Pause). It has no status: assigning (`assignUnattributedMachineTime`, inserts a Machine event for the interval) or dismissing (`dismissUnattributedMachineTime`) deletes the row, and pg_cron deletes rows 30 days after their `endTime`. Production → "Unattributed Time" (shown in the nav only while an `oee` integration is active; `x+/production+/machine-time.tsx`, `ui/MachineTime/*.ee.tsx`). The drawer (`machine-time.$id.tsx`) is a one-at-a-time review: suggestion cards from `getWorkCenterDayEvents` over the days the row touches, ranked by `suggestMachineTimeOperations` (`ui/MachineTime/machine-time-suggestions.ee.ts`), a search card over `getMachineTimeOperationCandidates` (open operations at the work center's location, including ones with no work center), "Not job time", Skip, and j/k; each answer redirects to the next row (`getUnattributedMachineTimeNeighbors`, keyset from `machineTimeQueueKeyset`). A row link and the drawer's close keep the list's filters; a queue move replaces the history entry; a failed read shows in the drawer (`loadErrors`). Both writes are `@carbon/ee/oee.server` behind `requireEntitlement("INTEGRATIONS")`; both refuse a row with no `endTime`, and assign refuses a locked job or a Done/Canceled operation. The list has 5 filters (work center, location, start date, end date, state Running in blue / Stopped in green): `parseMachineTimeListFilters` (`ui/MachineTime/machine-time-filters.ee.ts`, pure, inclusive `YYYY-MM-DD` days) and `applyMachineTimeListFilters` (service), shared by the list and the review queue; both read the view `unattributedMachineTimes`, whose `startDate`/`endDate` are the row's days in its location's timezone, the timezone the list shows (a `''` timezone counts as none). The list has no sort. The list renders `MachineTimeUpgradeOverlay` when gated.
+
+Engine, sync and press rules: `.claude/rules/oee-provider.md`.
+
## Safety
### Always
@@ -144,5 +152,6 @@ import { jobValidator, isJobLocked, jobStatus } from "~/modules/production";
## Rules References
- `.claude/rules/scheduling-data-structures.md` — scheduling engine architecture, trigger chain, RPCs
+- `.claude/rules/oee-provider.md` — OEE providers, the attribution engine, the loaded operation and unattributed machine time
- `.claude/rules/mrp-system.md` — MRP run flow, planning data model, and planning UI
- `.claude/rules/method-material-sourcing.md` — how material methodType drives procurement
diff --git a/apps/erp/app/modules/production/production.models.ts b/apps/erp/app/modules/production/production.models.ts
index d54f602e02..f2396513b2 100644
--- a/apps/erp/app/modules/production/production.models.ts
+++ b/apps/erp/app/modules/production/production.models.ts
@@ -106,17 +106,8 @@ export function isJobEditableFromPlanning(
return PLANNING_EDITABLE_JOB_STATUSES.some((editable) => editable === status);
}
-export const JOB_LOCKED_STATUSES = [
- "Completed",
- "Closed",
- "Cancelled"
-] as const;
-
-export function isJobLocked(status: string | null | undefined): boolean {
- return JOB_LOCKED_STATUSES.includes(
- status as (typeof JOB_LOCKED_STATUSES)[number]
- );
-}
+// The one definition lives in @carbon/utils, shared with the OEE sync.
+export { isJobLocked, JOB_LOCKED_STATUSES } from "@carbon/utils";
export const DATE_COLUMN_SENTINELS = [
"unscheduled",
@@ -1048,6 +1039,15 @@ export const productionEventValidator = z
}
);
+export const assignMachineTimeValidator = z.object({
+ intent: z.literal("assign"),
+ jobOperationId: z.string().min(1, { message: "Operation is required" })
+});
+
+export const dismissMachineTimeValidator = z.object({
+ intent: z.literal("dismiss")
+});
+
export const productionOrderValidator = z.object({
startDate: zfd.text(z.string().nullable()),
dueDate: zfd.text(z.string().nullable()),
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index d0df1ec692..697f0f7916 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -128,6 +128,10 @@ import {
outsideOperationsNeedingPurchaseOrders,
resolveOperationSupplier
} from "./ui/Jobs/job-release-logic";
+import {
+ type MachineTimeListFilters,
+ machineTimeQueueKeyset
+} from "./ui/MachineTime/machine-time-filters.ee";
const logger = getLogger("erp", "production");
@@ -6661,6 +6665,289 @@ export async function getJobOperationBatches(
return query;
}
+// The filters the Unattributed Time list and its review queue share. The
+// query reads the view `unattributedMachineTimes` (for `startDate` and
+// `endDate`) and must embed `workCenter!inner(name, locationId)`: the search
+// and the location filter read the work center. `workCenterId` is NOT NULL, so the
+// inner join drops no row.
+type MachineTimeFilterableQuery<Q> = {
+ ilike(column: string, pattern: string): Q;
+ in(column: string, values: readonly string[]): Q;
+ gte(column: string, value: string): Q;
+ lte(column: string, value: string): Q;
+ is(column: string, value: null): Q;
+ not(column: string, operator: string, value: null): Q;
+};
+
+export function applyMachineTimeListFilters<
+ Q extends MachineTimeFilterableQuery<Q>
+>(query: Q, filters: MachineTimeListFilters): Q {
+ let filtered = query;
+ if (filters.search) {
+ filtered = filtered.ilike("workCenter.name", `%${filters.search}%`);
+ }
+ if (filters.workCenterIds.length > 0) {
+ filtered = filtered.in("workCenterId", filters.workCenterIds);
+ }
+ if (filters.locationIds.length > 0) {
+ filtered = filtered.in("workCenter.locationId", filters.locationIds);
+ }
+ // Days in the row's location timezone: the view's `startDate`/`endDate`.
+ if (filters.start.from)
+ filtered = filtered.gte("startDate", filters.start.from);
+ if (filters.start.to) filtered = filtered.lte("startDate", filters.start.to);
+ if (filters.end.from) filtered = filtered.gte("endDate", filters.end.from);
+ if (filters.end.to) filtered = filtered.lte("endDate", filters.end.to);
+ if (filters.state === "Running") filtered = filtered.is("endTime", null);
+ if (filters.state === "Stopped") {
+ filtered = filtered.not("endTime", "is", null);
+ }
+ return filtered;
+}
+
+// Machine run time the OEE sync could not attribute to a loaded operation,
+// newest start first, then `id`: the review queue walks the same order.
+export async function getUnattributedMachineTimes(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args: {
+ filters: MachineTimeListFilters;
+ limit: number;
+ offset: number;
+ }
+) {
+ let query = applyMachineTimeListFilters(
+ client
+ .from("unattributedMachineTimes")
+ .select(
+ "*, workCenter!inner(name, locationId, location(name, timezone))",
+ {
+ count: LIST_COUNT
+ }
+ )
+ .eq("companyId", companyId),
+ args.filters
+ );
+
+ // No `filters` and no `sorts`: the filters above replace the generic ones,
+ // and the list allows no column sort.
+ query = setGenericQueryFilters(
+ query,
+ { limit: args.limit, offset: args.offset },
+ [
+ { column: "startTime", ascending: false },
+ { column: "id", ascending: false }
+ ]
+ );
+
+ // A view types every column nullable; these come from the table's own
+ // NOT NULL columns.
+ return query.overrideTypes<
+ Database["public"]["Tables"]["unattributedMachineTime"]["Row"][]
+ >();
+}
+
+export async function getUnattributedMachineTime(
+ client: SupabaseClient<Database>,
+ id: string,
+ companyId: string
+) {
+ return client
+ .from("unattributedMachineTime")
+ .select("*, workCenter!inner(name, locationId)")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .maybeSingle();
+}
+
+// Where a row sits in the queue, in the list's order (newest start first,
+// then `id`) and under the list's search and filters: its position, the
+// total, and its neighbours above and below. The queue holds stopped rows
+// only, whatever the State filter says: a running row cannot be answered. So a
+// running row has no position, but its neighbours are still the stopped rows
+// around it.
+export async function getUnattributedMachineTimeNeighbors(
+ client: SupabaseClient<Database>,
+ args: {
+ companyId: string;
+ id: string;
+ startTime: string;
+ endTime: string | null;
+ filters: MachineTimeListFilters;
+ }
+) {
+ const keyset = machineTimeQueueKeyset(args);
+ const queue = (options?: { count: "exact"; head: true }) =>
+ applyMachineTimeListFilters(
+ client
+ .from("unattributedMachineTimes")
+ .select("id, workCenter!inner(name, locationId)", options)
+ .eq("companyId", args.companyId)
+ .not("endTime", "is", null),
+ args.filters
+ );
+
+ const [total, above, previous, next] = await Promise.all([
+ queue({ count: "exact", head: true }),
+ queue({ count: "exact", head: true }).or(keyset.above),
+ queue()
+ .or(keyset.above)
+ .order("startTime", { ascending: true })
+ .order("id", { ascending: true })
+ .limit(1),
+ queue()
+ .or(keyset.below)
+ .order("startTime", { ascending: false })
+ .order("id", { ascending: false })
+ .limit(1)
+ ]);
+
+ const error = total.error ?? above.error ?? previous.error ?? next.error;
+ if (error) return { data: null, error };
+
+ return {
+ data: {
+ position: args.endTime ? (above.count ?? 0) + 1 : null,
+ total: total.count ?? 0,
+ previousId: previous.data?.[0]?.id ?? null,
+ nextId: next.data?.[0]?.id ?? null
+ },
+ error: null
+ };
+}
+
+// The operation a supervisor assigns machine time to, with its job. The id
+// comes from the form, so the read is scoped to the company.
+export async function getMachineTimeAssignTarget(
+ client: SupabaseClient<Database>,
+ args: { jobOperationId: string; companyId: string }
+) {
+ return client
+ .from("jobOperation")
+ .select("id, job!inner(jobId, status)")
+ .eq("id", args.jobOperationId)
+ .eq("companyId", args.companyId)
+ .maybeSingle();
+}
+
+// Every production event on the work center that overlaps the window (the
+// days of the unattributed time), with its operation and job: what ran there,
+// for the suggestion cards.
+export async function getWorkCenterDayEvents(
+ client: SupabaseClient<Database>,
+ args: {
+ companyId: string;
+ workCenterId: string;
+ dayStart: string;
+ dayEnd: string;
+ }
+) {
+ return client
+ .from("productionEvent")
+ .select(
+ "jobOperationId, startTime, endTime, jobOperation(id, description, status, job(id, jobId, status, item(readableIdWithRevision)))"
+ )
+ .eq("companyId", args.companyId)
+ .eq("workCenterId", args.workCenterId)
+ .lt("startTime", args.dayEnd)
+ .or(`endTime.is.null,endTime.gt."${args.dayStart}"`)
+ .order("startTime", { ascending: true })
+ .limit(1000);
+}
+
+// The operations a supervisor can search to assign machine time to: open
+// operations on open jobs at the work center's location (or on the work
+// center itself when it has no location), this work center's first, In
+// Progress next, then the most recent production event there.
+export async function getMachineTimeOperationCandidates(
+ client: SupabaseClient<Database>,
+ args: { workCenterId: string; locationId: string | null; companyId: string }
+) {
+ const operationSelect =
+ "id, description, status, workCenterId, workCenter(name), job!inner(jobId, locationId, status)";
+ const lockedJobStatuses = `(${JOB_LOCKED_STATUSES.join(",")})`;
+
+ const [here, elsewhere, events] = await Promise.all([
+ client
+ .from("jobOperation")
+ .select(operationSelect)
+ .eq("companyId", args.companyId)
+ .eq("workCenterId", args.workCenterId)
+ .not("status", "in", "(Done,Canceled)")
+ .not("job.status", "in", lockedJobStatuses)
+ .limit(1000),
+ args.locationId
+ ? client
+ .from("jobOperation")
+ .select(operationSelect)
+ .eq("companyId", args.companyId)
+ .eq("job.locationId", args.locationId)
+ // `neq` alone drops an operation with no work center (NULL).
+ .or(`workCenterId.is.null,workCenterId.neq.${args.workCenterId}`)
+ .not("status", "in", "(Done,Canceled)")
+ .not("job.status", "in", lockedJobStatuses)
+ // The rank below sets the order; this one decides which rows the
+ // cap keeps: the most recently touched.
+ .order("updatedAt", { ascending: false })
+ .limit(1000)
+ : null,
+ client
+ .from("productionEvent")
+ .select("jobOperationId, startTime")
+ .eq("workCenterId", args.workCenterId)
+ .eq("companyId", args.companyId)
+ .order("startTime", { ascending: false })
+ .limit(200)
+ ]);
+
+ if (here.error) return { data: null, error: here.error };
+ if (elsewhere?.error) return { data: null, error: elsewhere.error };
+ if (events.error) return { data: null, error: events.error };
+
+ // This work center's operations first, then the rest of the location.
+ const operations = [...(here.data ?? []), ...(elsewhere?.data ?? [])];
+
+ // Events arrive latest first, so the first start seen per operation is its
+ // latest. ISO timestamps from PostgREST share one format, so string order is
+ // chronological.
+ const latestEventStart = new Map<string, string>();
+ for (const event of events.data ?? []) {
+ if (!latestEventStart.has(event.jobOperationId)) {
+ latestEventStart.set(event.jobOperationId, event.startTime);
+ }
+ }
+
+ const rank = (operation: (typeof operations)[number]) => [
+ operation.workCenterId === args.workCenterId ? 0 : 1,
+ operation.status === "In Progress" ? 0 : 1
+ ];
+
+ const ranked = operations.sort((a, b) => {
+ const [aHere, aInProgress] = rank(a);
+ const [bHere, bInProgress] = rank(b);
+ if (aHere !== bHere) return aHere - bHere;
+ if (aInProgress !== bInProgress) return aInProgress - bInProgress;
+
+ const aStart = latestEventStart.get(a.id) ?? "";
+ const bStart = latestEventStart.get(b.id) ?? "";
+ if (aStart !== bStart) return aStart < bStart ? 1 : -1;
+
+ return (a.description ?? "").localeCompare(b.description ?? "");
+ });
+
+ return {
+ data: ranked.map((operation) => ({
+ value: operation.id,
+ label: `${operation.job?.jobId ?? ""} · ${operation.description ?? ""}`,
+ // The drawer shows the status when there is no work center: it
+ // translates it, so it stays the enum here.
+ workCenterName: operation.workCenter?.name ?? null,
+ status: operation.status
+ })),
+ error: null
+ };
+}
+
// The members' shared work-center name: null when they disagree (or none are
// set), the single distinct name when they all agree. The list stats and the
// detail drawer both fall back to this when the batch has no header work center
diff --git a/apps/erp/app/modules/production/ui/MachineTime/MachineTimeDrawer.ee.tsx b/apps/erp/app/modules/production/ui/MachineTime/MachineTimeDrawer.ee.tsx
new file mode 100644
index 0000000000..51da816d9c
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/MachineTime/MachineTimeDrawer.ee.tsx
@@ -0,0 +1,406 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import type { Database } from "@carbon/database";
+import {
+ Badge,
+ Button,
+ Combobox,
+ cn,
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerDescription,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerTitle,
+ IconButton,
+ Kbd,
+ useShortcutKeys,
+ VStack
+} from "@carbon/react";
+import { formatDateTimeInZone } from "@carbon/utils";
+import { Trans, useLingui } from "@lingui/react/macro";
+import { useLocale } from "@react-aria/i18n";
+import type { ReactNode } from "react";
+import { useEffect, useRef } from "react";
+import {
+ LuChevronDown,
+ LuChevronRight,
+ LuChevronUp,
+ LuLoaderCircle
+} from "react-icons/lu";
+import { useFetcher, useNavigate, useSearchParams } from "react-router";
+import { FieldEmptyState } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { MACHINE_TIME_REVIEW_SHORTCUTS } from "~/shortcuts";
+import { path } from "~/utils/path";
+import type { getUnattributedMachineTime } from "../../production.service";
+import {
+ MachineTimeInstant,
+ useMachineTimeDuration
+} from "./MachineTimeTable.ee";
+import type { MachineTimeSuggestion } from "./machine-time-suggestions.ee";
+
+type JobOperationStatus = Database["public"]["Enums"]["jobOperationStatus"];
+
+type MachineTime = NonNullable<
+ Awaited<ReturnType<typeof getUnattributedMachineTime>>["data"]
+>;
+
+type MachineTimeDrawerProps = {
+ machineTime: MachineTime;
+ timeZone: string;
+ queue: {
+ /** Null for a running row: the queue holds stopped rows only. */
+ position: number | null;
+ total: number;
+ previousId: string | null;
+ nextId: string | null;
+ };
+ suggestions: MachineTimeSuggestion[];
+ operationOptions: {
+ value: string;
+ label: string;
+ workCenterName: string | null;
+ status: JobOperationStatus | null;
+ }[];
+ /** The reads that failed: the drawer says so instead of showing them empty. */
+ loadErrors: { queue: boolean; suggestions: boolean; operations: boolean };
+ onClose: () => void;
+};
+
+const MachineTimeDrawer = ({
+ machineTime,
+ timeZone,
+ queue,
+ suggestions,
+ operationOptions,
+ loadErrors,
+ onClose
+}: MachineTimeDrawerProps) => {
+ const { t } = useLingui();
+ const { locale } = useLocale();
+ const permissions = usePermissions();
+ const duration = useMachineTimeDuration();
+ const navigate = useNavigate();
+ const [searchParams] = useSearchParams();
+ const fetcher = useFetcher();
+
+ const isRunning = !machineTime.endTime;
+ const isBusy = fetcher.state !== "idle";
+ const canAnswer = permissions.can("update", "production") && !isRunning;
+ const pendingOperationId = fetcher.formData?.get("jobOperationId");
+ const isDismissing = fetcher.formData?.get("intent") === "dismiss";
+ const workCenterName =
+ machineTime.workCenter?.name ?? machineTime.workCenterId;
+
+ // A queue move replaces the entry, so Back leaves the review instead of
+ // walking back through every row.
+ const goTo = (id: string | null) => {
+ if (!id) return;
+ navigate(`${path.to.unattributedMachineTime(id)}?${searchParams}`, {
+ replace: true
+ });
+ };
+
+ const statusLabels: Record<JobOperationStatus, string> = {
+ Todo: t`Todo`,
+ Ready: t`Ready`,
+ Waiting: t`Waiting`,
+ "In Progress": t`In Progress`,
+ Paused: t`Paused`,
+ Done: t`Done`,
+ Canceled: t`Canceled`
+ };
+ const searchOptions = operationOptions.map(
+ ({ workCenterName, status, ...option }) => ({
+ ...option,
+ helper: workCenterName ?? (status ? statusLabels[status] : undefined)
+ })
+ );
+
+ const position = queue.position;
+ const total = queue.total;
+
+ // One answer per row: a held key, or a second click before the fetcher
+ // re-renders as busy, must not post twice.
+ const answered = useRef(false);
+ // A failed answer leaves the drawer on this row; let it be answered again.
+ useEffect(() => {
+ if (fetcher.state === "idle") answered.current = false;
+ }, [fetcher.state]);
+ const answer = (submission: Record<string, string>) => {
+ if (!canAnswer || isBusy || answered.current) return;
+ answered.current = true;
+ fetcher.submit(submission, { method: "post" });
+ };
+ const assign = (jobOperationId: string) =>
+ answer({ intent: "assign", jobOperationId });
+ const dismiss = () => answer({ intent: "dismiss" });
+
+ const assignable = suggestions.filter((s) => s.blockedBy === null);
+
+ useShortcutKeys({
+ shortcut: [...MACHINE_TIME_REVIEW_SHORTCUTS.choose],
+ action: (event) => {
+ if (event.repeat) return;
+ const suggestion = assignable[Number(event.key) - 1];
+ if (suggestion) assign(suggestion.jobOperationId);
+ },
+ disabled: !canAnswer || isBusy
+ });
+ useShortcutKeys({
+ shortcut: MACHINE_TIME_REVIEW_SHORTCUTS.next,
+ action: (event) => {
+ if (!event.repeat) goTo(queue.nextId);
+ },
+ disabled: isBusy || !queue.nextId
+ });
+ useShortcutKeys({
+ shortcut: MACHINE_TIME_REVIEW_SHORTCUTS.previous,
+ action: (event) => {
+ if (!event.repeat) goTo(queue.previousId);
+ },
+ disabled: isBusy || !queue.previousId
+ });
+
+ const time = (value: string) =>
+ formatDateTimeInZone(value, timeZone, locale, {
+ dateStyle: undefined,
+ timeStyle: "short"
+ });
+
+ return (
+ <Drawer
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ {/* No autofocus: it would ring the Previous button on every row. */}
+ <DrawerContent onOpenAutoFocus={(event) => event.preventDefault()}>
+ <DrawerHeader className="flex-row items-center justify-between gap-4 pr-14">
+ <div className="flex min-w-0 flex-col gap-1">
+ <DrawerTitle>{workCenterName}</DrawerTitle>
+ <DrawerDescription>
+ <Trans>Unattributed Time</Trans>
+ </DrawerDescription>
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
+ <span className="mr-1 text-xs tabular-nums text-muted-foreground">
+ {loadErrors.queue ? null : position === null ? (
+ <Trans>Running</Trans>
+ ) : (
+ <Trans>
+ {position} of {total}
+ </Trans>
+ )}
+ </span>
+ <IconButton
+ aria-label={t`Previous`}
+ icon={<LuChevronUp />}
+ variant="ghost"
+ isDisabled={!queue.previousId || isBusy}
+ onClick={() => goTo(queue.previousId)}
+ />
+ <IconButton
+ aria-label={t`Next`}
+ icon={<LuChevronDown />}
+ variant="ghost"
+ isDisabled={!queue.nextId || isBusy}
+ onClick={() => goTo(queue.nextId)}
+ />
+ </div>
+ </DrawerHeader>
+ <DrawerBody>
+ <VStack spacing={4}>
+ <div className="w-full divide-y divide-border border-y border-border">
+ <DetailRow label={t`Start`}>
+ <MachineTimeInstant
+ value={machineTime.startTime}
+ timeZone={timeZone}
+ />
+ </DetailRow>
+ <DetailRow label={t`End`}>
+ {machineTime.endTime ? (
+ <MachineTimeInstant
+ value={machineTime.endTime}
+ timeZone={timeZone}
+ />
+ ) : (
+ <Trans>Running</Trans>
+ )}
+ </DetailRow>
+ <DetailRow label={t`Duration`}>
+ {duration.between(
+ machineTime.startTime,
+ machineTime.endTime
+ ) ?? <Trans>Running</Trans>}
+ </DetailRow>
+ </div>
+
+ <div className="flex w-full flex-col gap-2">
+ <h3 className="text-sm font-medium">
+ <Trans>Which operation was this?</Trans>
+ </h3>
+ {isRunning && (
+ <p className="text-sm text-muted-foreground">
+ <Trans>
+ The machine is still running. Assign this time after it
+ stops.
+ </Trans>
+ </p>
+ )}
+
+ {loadErrors.suggestions ? (
+ <p className="text-sm text-muted-foreground">
+ <Trans>Could not load what ran on {workCenterName}.</Trans>
+ </p>
+ ) : suggestions.length === 0 ? (
+ <p className="text-sm text-muted-foreground">
+ <Trans>Nothing else ran on {workCenterName} that day.</Trans>
+ </p>
+ ) : (
+ suggestions.map((suggestion) => {
+ const shortcutIndex = assignable.indexOf(suggestion);
+ const isPending =
+ pendingOperationId === suggestion.jobOperationId;
+ const isDisabled =
+ !canAnswer || isBusy || suggestion.blockedBy !== null;
+ return (
+ <button
+ key={suggestion.jobOperationId}
+ type="button"
+ disabled={isDisabled}
+ onClick={() => assign(suggestion.jobOperationId)}
+ className={cn(
+ "group flex w-full items-center gap-3 rounded-lg border border-border bg-card p-3 text-left transition-colors",
+ "hover:bg-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ "disabled:cursor-not-allowed",
+ suggestion.blockedBy !== null && "opacity-60"
+ )}
+ >
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <div className="flex min-w-0 items-center gap-2 text-sm">
+ <span className="shrink-0 whitespace-nowrap font-medium">
+ {suggestion.jobReadableId}
+ </span>
+ <span className="truncate">
+ {suggestion.description}
+ </span>
+ </div>
+ <span className="truncate text-xs text-muted-foreground">
+ {[
+ `${time(suggestion.firstStart)} – ${
+ suggestion.lastEnd
+ ? time(suggestion.lastEnd)
+ : t`now`
+ }`,
+ duration.length(suggestion.totalMs),
+ suggestion.itemReadableId
+ ]
+ .filter(Boolean)
+ .join(" · ")}
+ </span>
+ </div>
+ {suggestion.blockedBy !== null ? (
+ <Badge variant="gray" className="shrink-0">
+ {suggestion.blockedBy === "Locked"
+ ? t`Job locked`
+ : suggestion.blockedBy === "Done"
+ ? t`Done`
+ : t`Canceled`}
+ </Badge>
+ ) : suggestion.overlaps ? (
+ <Badge variant="green" className="shrink-0">
+ <Trans>Ran at the time</Trans>
+ </Badge>
+ ) : null}
+ {isPending ? (
+ <LuLoaderCircle className="size-4 shrink-0 animate-spin text-muted-foreground" />
+ ) : suggestion.blockedBy !== null ? null : shortcutIndex <
+ MACHINE_TIME_REVIEW_SHORTCUTS.choose.length ? (
+ <Kbd className="shrink-0">{shortcutIndex + 1}</Kbd>
+ ) : (
+ <LuChevronRight className="size-4 shrink-0 text-muted-foreground" />
+ )}
+ </button>
+ );
+ })
+ )}
+
+ <div className="flex w-full flex-col gap-2 rounded-lg border border-dashed border-border p-3">
+ <span className="text-xs text-muted-foreground">
+ <Trans>Another job or operation</Trans>
+ </span>
+ <Combobox
+ size="sm"
+ value=""
+ options={searchOptions}
+ placeholder={t`Search jobs and operations`}
+ emptyMessage={
+ loadErrors.operations ? (
+ <FieldEmptyState
+ title={t`Could not load operations`}
+ description={t`Reload the page to try again.`}
+ />
+ ) : (
+ <FieldEmptyState
+ title={t`No open operations`}
+ description={t`No job at this location has an open operation.`}
+ />
+ )
+ }
+ isReadOnly={!canAnswer || isBusy}
+ onChange={(jobOperationId) => {
+ if (jobOperationId) assign(jobOperationId);
+ }}
+ />
+ </div>
+ </div>
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <Button
+ variant="secondary"
+ isDisabled={!canAnswer || isBusy}
+ isLoading={isDismissing}
+ onClick={dismiss}
+ >
+ <Trans>Not job time</Trans>
+ </Button>
+ <Button
+ variant="secondary"
+ isDisabled={!queue.nextId || isBusy}
+ rightIcon={<LuChevronDown />}
+ onClick={() => goTo(queue.nextId)}
+ >
+ <Trans>Skip</Trans>
+ </Button>
+ </DrawerFooter>
+ </DrawerContent>
+ </Drawer>
+ );
+};
+
+// Same row as the fixed asset page's DetailRow: label left, value right.
+function DetailRow({
+ label,
+ children
+}: {
+ label: string;
+ children: ReactNode;
+}) {
+ return (
+ <div className="flex items-center justify-between gap-4 py-3 text-base sm:text-sm">
+ <span className="shrink-0 text-muted-foreground">{label}</span>
+ <span className="min-w-0 truncate text-right font-medium">
+ {children}
+ </span>
+ </div>
+ );
+}
+
+export default MachineTimeDrawer;
diff --git a/apps/erp/app/modules/production/ui/MachineTime/MachineTimeTable.ee.tsx b/apps/erp/app/modules/production/ui/MachineTime/MachineTimeTable.ee.tsx
new file mode 100644
index 0000000000..2a8bf2bf69
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/MachineTime/MachineTimeTable.ee.tsx
@@ -0,0 +1,306 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import {
+ Button,
+ MENU_ITEM_SHORTCUTS,
+ MenuIcon,
+ MenuItem,
+ Status
+} from "@carbon/react";
+import { formatDateTimeInZone, formatPreciseDuration } from "@carbon/utils";
+import { useLingui } from "@lingui/react/macro";
+import { useLocale } from "@react-aria/i18n";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo } from "react";
+import {
+ LuActivity,
+ LuCalendar,
+ LuEye,
+ LuFactory,
+ LuHourglass,
+ LuMapPin
+} from "react-icons/lu";
+import { useNavigate } from "react-router";
+import { DateTime, Hyperlink, Table } from "~/components";
+import { Enumerable } from "~/components/Enumerable";
+import { useUrlParams } from "~/hooks";
+import { useCompanyTimeZone } from "~/hooks/useCompanyTimeZone";
+import { path } from "~/utils/path";
+import type { getUnattributedMachineTimes } from "../../production.service";
+
+export type UnattributedMachineTime = NonNullable<
+ Awaited<ReturnType<typeof getUnattributedMachineTimes>>["data"]
+>[number];
+
+/** The text of an instant on the work center's clock: the cell and the CSV. */
+function formatMachineTimeInstant(
+ value: string,
+ timeZone: string,
+ locale: string
+) {
+ return formatDateTimeInZone(value, timeZone, locale, { timeStyle: "short" });
+}
+
+/** An instant on the work center's clock (its location), else the company's. */
+export function MachineTimeInstant({
+ value,
+ timeZone
+}: {
+ value: string;
+ timeZone: string;
+}) {
+ const { locale } = useLocale();
+ return (
+ <DateTime value={value} locationTimeZone={timeZone} side="left">
+ <span className="tabular-nums">
+ {formatMachineTimeInstant(value, timeZone, locale)}
+ </span>
+ </DateTime>
+ );
+}
+
+/** Machine time lengths in words, one style for the list and the drawer. */
+export function useMachineTimeDuration() {
+ const { locale } = useLocale();
+ return useMemo(
+ () => ({
+ /** `endTime − startTime`, or null while the machine is running. */
+ between: (startTime: string, endTime: string | null) =>
+ endTime
+ ? formatPreciseDuration(startTime, locale, Date.parse(endTime)).text
+ : null,
+ /** A length in milliseconds. */
+ length: (ms: number) =>
+ formatPreciseDuration("1970-01-01T00:00:00.000Z", locale, ms).text
+ }),
+ [locale]
+ );
+}
+
+export function useMachineTimeZone() {
+ const companyTimeZone = useCompanyTimeZone();
+ return useCallback(
+ // `||`: a location with no timezone of its own may store ''.
+ (row: Pick<UnattributedMachineTime, "workCenter">) =>
+ row.workCenter?.location?.timezone || companyTimeZone,
+ [companyTimeZone]
+ );
+}
+
+type MachineTimeTableProps = {
+ data: UnattributedMachineTime[];
+ count: number;
+ workCenters: { id: string | null; name: string | null }[];
+ locations: { id: string; name: string }[];
+};
+
+const MachineTimeTable = memo(
+ ({ data, count, workCenters, locations }: MachineTimeTableProps) => {
+ const [params] = useUrlParams();
+ const { t } = useLingui();
+ const { locale } = useLocale();
+ const navigate = useNavigate();
+ const duration = useMachineTimeDuration();
+ const timeZoneOf = useMachineTimeZone();
+
+ const columns = useMemo<ColumnDef<UnattributedMachineTime>[]>(
+ () => [
+ {
+ accessorKey: "workCenterId",
+ header: t`Work Center`,
+ enableSorting: false,
+ cell: ({ row }) => (
+ <Hyperlink
+ to={`${path.to.unattributedMachineTime(row.original.id)}?${params.toString()}`}
+ >
+ <Enumerable
+ value={
+ row.original.workCenter?.name ?? row.original.workCenterId
+ }
+ />
+ </Hyperlink>
+ ),
+ meta: {
+ mobile: "P1",
+ icon: <LuFactory />,
+ filter: {
+ type: "static",
+ options: workCenters.flatMap((workCenter) =>
+ workCenter.id
+ ? [
+ {
+ value: workCenter.id,
+ label: <Enumerable value={workCenter.name} />
+ }
+ ]
+ : []
+ )
+ },
+ exportValue: (row: UnattributedMachineTime) =>
+ row.workCenter?.name ?? null
+ }
+ },
+ {
+ id: "locationId",
+ header: t`Location`,
+ enableSorting: false,
+ cell: ({ row }) => (
+ <Enumerable
+ value={row.original.workCenter?.location?.name ?? null}
+ />
+ ),
+ meta: {
+ icon: <LuMapPin />,
+ filter: {
+ type: "static",
+ options: locations.map((location) => ({
+ value: location.id,
+ label: <Enumerable value={location.name} />
+ }))
+ },
+ exportValue: (row: UnattributedMachineTime) =>
+ row.workCenter?.location?.name ?? null
+ }
+ },
+ {
+ accessorKey: "startTime",
+ header: t`Start`,
+ enableSorting: false,
+ cell: ({ row }) => (
+ <MachineTimeInstant
+ value={row.original.startTime}
+ timeZone={timeZoneOf(row.original)}
+ />
+ ),
+ meta: {
+ mobile: "P2",
+ icon: <LuCalendar />,
+ filter: { type: "dateRange" },
+ exportValue: (row: UnattributedMachineTime) =>
+ formatMachineTimeInstant(row.startTime, timeZoneOf(row), locale)
+ }
+ },
+ {
+ accessorKey: "endTime",
+ header: t`End`,
+ enableSorting: false,
+ cell: ({ row }) =>
+ row.original.endTime ? (
+ <MachineTimeInstant
+ value={row.original.endTime}
+ timeZone={timeZoneOf(row.original)}
+ />
+ ) : null,
+ meta: {
+ icon: <LuCalendar />,
+ filter: { type: "dateRange" },
+ exportValue: (row: UnattributedMachineTime) =>
+ row.endTime
+ ? formatMachineTimeInstant(row.endTime, timeZoneOf(row), locale)
+ : null
+ }
+ },
+ {
+ id: "duration",
+ header: t`Duration`,
+ enableSorting: false,
+ cell: ({ row }) =>
+ duration.between(row.original.startTime, row.original.endTime) ?? (
+ <span className="text-muted-foreground">{t`Running`}</span>
+ ),
+ meta: {
+ mobile: "P3",
+ icon: <LuHourglass />,
+ exportValue: (row: UnattributedMachineTime) =>
+ duration.between(row.startTime, row.endTime) ?? t`Running`
+ }
+ },
+ {
+ id: "state",
+ header: t`State`,
+ enableSorting: false,
+ cell: ({ row }) =>
+ row.original.endTime ? (
+ <Status color="green">{t`Stopped`}</Status>
+ ) : (
+ // Blue is in progress (a spinner); green is finished (a check).
+ <Status color="blue">{t`Running`}</Status>
+ ),
+ meta: {
+ icon: <LuActivity />,
+ filter: {
+ type: "static",
+ isExclusive: true,
+ options: [
+ {
+ value: "Running",
+ label: <Status color="blue">{t`Running`}</Status>
+ },
+ {
+ value: "Stopped",
+ label: <Status color="green">{t`Stopped`}</Status>
+ }
+ ]
+ },
+ exportValue: (row: UnattributedMachineTime) =>
+ row.endTime ? t`Stopped` : t`Running`
+ }
+ }
+ ],
+ [duration, locale, locations, params, t, timeZoneOf, workCenters]
+ );
+
+ const renderContextMenu = useCallback(
+ (row: UnattributedMachineTime) => (
+ <MenuItem
+ shortcut={MENU_ITEM_SHORTCUTS.view}
+ onClick={() => {
+ navigate(
+ `${path.to.unattributedMachineTime(row.id)}?${params.toString()}`
+ );
+ }}
+ >
+ <MenuIcon icon={<LuEye />} />
+ {t`View Machine Time`}
+ </MenuItem>
+ ),
+ [navigate, params, t]
+ );
+
+ // The drawer walks the queue in this list's order, so Review starts at
+ // the top row. The queue holds stopped rows only: a running row cannot
+ // be answered yet.
+ const firstId = data.find((row) => row.endTime)?.id;
+
+ return (
+ <Table<UnattributedMachineTime>
+ data={data}
+ columns={columns}
+ count={count}
+ // The review queue walks one fixed order (newest start, then id), so
+ // the list offers no sort.
+ sort={null}
+ renderContextMenu={renderContextMenu}
+ title={t`Unattributed Time`}
+ primaryAction={
+ firstId ? (
+ <Button
+ onClick={() =>
+ navigate(
+ `${path.to.unattributedMachineTime(firstId)}?${params.toString()}`
+ )
+ }
+ >
+ {t`Review`}
+ </Button>
+ ) : undefined
+ }
+ />
+ );
+ }
+);
+
+MachineTimeTable.displayName = "MachineTimeTable";
+export default MachineTimeTable;
diff --git a/apps/erp/app/modules/production/ui/MachineTime/MachineTimeUpgradeOverlay.ee.tsx b/apps/erp/app/modules/production/ui/MachineTime/MachineTimeUpgradeOverlay.ee.tsx
new file mode 100644
index 0000000000..bb46431760
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/MachineTime/MachineTimeUpgradeOverlay.ee.tsx
@@ -0,0 +1,106 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { Trans } from "@lingui/react/macro";
+import { LuTimerOff } from "react-icons/lu";
+import {
+ UpgradeOverlay,
+ UpgradeOverlayActions,
+ UpgradeOverlayCard,
+ UpgradeOverlayContent,
+ UpgradeOverlayDescription,
+ UpgradeOverlayIcon,
+ UpgradeOverlayPreview,
+ UpgradeOverlayTitle,
+ UpgradeOverlayUpgradeButton
+} from "~/components/UpgradeOverlay";
+import type { UnattributedMachineTime } from "./MachineTimeTable.ee";
+import MachineTimeTable from "./MachineTimeTable.ee";
+
+const mockRow = {
+ companyId: "mock",
+ createdAt: "2026-05-05T06:00:00Z",
+ createdBy: "mock-user-1",
+ updatedAt: null,
+ updatedBy: null
+} as const;
+
+const mockMachineTimes: UnattributedMachineTime[] = [
+ {
+ ...mockRow,
+ id: "mock-1",
+ workCenterId: "mock-wc-1",
+ workCenter: {
+ name: "Haas VF-2",
+ locationId: "mock-location",
+ location: { name: "Main Plant", timezone: "UTC" }
+ },
+ startTime: "2026-05-05T06:12:00Z",
+ endTime: "2026-05-05T07:47:00Z",
+ startDate: "2026-05-05",
+ endDate: "2026-05-05"
+ },
+ {
+ ...mockRow,
+ id: "mock-2",
+ workCenterId: "mock-wc-2",
+ workCenter: {
+ name: "Mazak QTN-200",
+ locationId: "mock-location",
+ location: { name: "Main Plant", timezone: "UTC" }
+ },
+ startTime: "2026-05-05T09:30:00Z",
+ endTime: "2026-05-05T09:52:00Z",
+ startDate: "2026-05-05",
+ endDate: "2026-05-05"
+ },
+ {
+ ...mockRow,
+ id: "mock-3",
+ workCenterId: "mock-wc-1",
+ workCenter: {
+ name: "Haas VF-2",
+ locationId: "mock-location",
+ location: { name: "Main Plant", timezone: "UTC" }
+ },
+ startTime: "2026-05-05T13:05:00Z",
+ endTime: null,
+ startDate: "2026-05-05",
+ endDate: null
+ }
+];
+
+export default function MachineTimeUpgradeOverlay() {
+ return (
+ <UpgradeOverlay>
+ <UpgradeOverlayPreview>
+ <MachineTimeTable
+ data={mockMachineTimes}
+ count={mockMachineTimes.length}
+ workCenters={[]}
+ locations={[]}
+ />
+ </UpgradeOverlayPreview>
+ <UpgradeOverlayCard>
+ <UpgradeOverlayIcon>
+ <LuTimerOff className="size-6 text-muted-foreground" />
+ </UpgradeOverlayIcon>
+ <UpgradeOverlayContent>
+ <UpgradeOverlayTitle>
+ <Trans>Unattributed Time</Trans>
+ </UpgradeOverlayTitle>
+ <UpgradeOverlayDescription>
+ <Trans>
+ Assign machine run time that no loaded operation claimed to the
+ right job, or dismiss it.
+ </Trans>
+ </UpgradeOverlayDescription>
+ </UpgradeOverlayContent>
+ <UpgradeOverlayActions>
+ <UpgradeOverlayUpgradeButton />
+ </UpgradeOverlayActions>
+ </UpgradeOverlayCard>
+ </UpgradeOverlay>
+ );
+}
diff --git a/apps/erp/app/modules/production/ui/MachineTime/machine-time-filters.ee.ts b/apps/erp/app/modules/production/ui/MachineTime/machine-time-filters.ee.ts
new file mode 100644
index 0000000000..84681beb1e
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/MachineTime/machine-time-filters.ee.ts
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+/**
+ * The Unattributed Time list's search and filters, read from the URL. The
+ * list and the review queue both apply them, so the queue walks the rows the
+ * list shows. Pure, so it is tested without a database
+ * (`apps/erp/test/machine-time-filters.ee.test.ts`).
+ *
+ * `startTime` and `endTime` are instants, but their filters pick days. The
+ * list shows each row in its location's timezone, so the date ranges filter
+ * the view's `startDate` / `endDate`: the row's dates in that same timezone.
+ */
+
+import { parseDate } from "@internationalized/date";
+
+export type MachineTimeListFilters = {
+ search: string | null;
+ workCenterIds: string[];
+ locationIds: string[];
+ /** `YYYY-MM-DD` days in the row's location timezone, both inclusive. */
+ start: { from: string | null; to: string | null };
+ end: { from: string | null; to: string | null };
+ state: "Running" | "Stopped" | null;
+};
+
+/** The date itself, or null if it is not a `YYYY-MM-DD` date. */
+function validDate(date: string | undefined) {
+ if (!date) return null;
+ try {
+ return parseDate(date).toString();
+ } catch {
+ return null;
+ }
+}
+
+function dayRange(value: string) {
+ // Same `from,to` split as `parseRangeFilter` (`~/utils/query`). That module
+ // imports `@carbon/auth`, whose Lingui macros fail outside the Vite build,
+ // so this pure file cannot import it.
+ const [from, to] = value.split(",");
+ return { from: validDate(from), to: validDate(to) };
+}
+
+export function parseMachineTimeListFilters(
+ searchParams: URLSearchParams
+): MachineTimeListFilters {
+ const filters: MachineTimeListFilters = {
+ search: searchParams.get("search") || null,
+ workCenterIds: [],
+ locationIds: [],
+ start: { from: null, to: null },
+ end: { from: null, to: null },
+ state: null
+ };
+
+ for (const filter of searchParams.getAll("filter")) {
+ const [column, operator, value] = filter.split(":");
+ if (!column || !operator || !value) continue;
+
+ switch (column) {
+ case "workCenterId":
+ filters.workCenterIds = value.split(",").filter(Boolean);
+ break;
+ case "locationId":
+ filters.locationIds = value.split(",").filter(Boolean);
+ break;
+ case "startTime":
+ if (operator === "between") filters.start = dayRange(value);
+ break;
+ case "endTime":
+ if (operator === "between") filters.end = dayRange(value);
+ break;
+ case "state":
+ if (value === "Running" || value === "Stopped") filters.state = value;
+ break;
+ }
+ }
+
+ return filters;
+}
+
+/**
+ * PostgREST `or` filters for the rows above and below a row in the queue's
+ * order (newest start first, then `id`, both descending). A tie on
+ * `startTime` falls to `id`, so every row has exactly one place.
+ */
+export function machineTimeQueueKeyset(row: { id: string; startTime: string }) {
+ const at = `"${row.startTime}"`;
+ return {
+ above: `startTime.gt.${at},and(startTime.eq.${at},id.gt.${row.id})`,
+ below: `startTime.lt.${at},and(startTime.eq.${at},id.lt.${row.id})`
+ };
+}
diff --git a/apps/erp/app/modules/production/ui/MachineTime/machine-time-suggestions.ee.ts b/apps/erp/app/modules/production/ui/MachineTime/machine-time-suggestions.ee.ts
new file mode 100644
index 0000000000..1e71c62bd8
--- /dev/null
+++ b/apps/erp/app/modules/production/ui/MachineTime/machine-time-suggestions.ee.ts
@@ -0,0 +1,131 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+/**
+ * The best guesses for a slice of unattributed machine time: the operations
+ * that ran on the same work center on the days it touches. Pure, so it is
+ * tested without a database (`apps/erp/test/machine-time-suggestions.ee.test.ts`).
+ *
+ * Instants are compared as epoch milliseconds, which is safe for absolute
+ * instants (`.claude/rules/date-handling.md` → Narrow exception).
+ */
+
+import { type MachineTimeRefusal, machineTimeRefusal } from "@carbon/ee/oee";
+
+export type DayEvent = {
+ jobOperationId: string;
+ startTime: string;
+ endTime: string | null;
+ jobOperation: {
+ id: string;
+ description: string | null;
+ status: string | null;
+ job: {
+ id: string;
+ jobId: string;
+ status: string | null;
+ item: { readableIdWithRevision: string | null } | null;
+ } | null;
+ } | null;
+};
+
+export type MachineTimeSuggestion = {
+ jobOperationId: string;
+ jobReadableId: string;
+ description: string;
+ itemReadableId: string | null;
+ firstStart: string;
+ lastEnd: string | null;
+ /** Time the operation's events covered inside the window. */
+ totalMs: number;
+ /** An event of the operation overlaps the unattributed interval. */
+ overlaps: boolean;
+ /** Why it cannot take the time, or null when it can. */
+ blockedBy: MachineTimeRefusal | null;
+};
+
+/** The most cards the drawer shows; one shortcut key each. */
+export const MACHINE_TIME_SUGGESTION_LIMIT = 6;
+
+export function suggestMachineTimeOperations(args: {
+ events: DayEvent[];
+ interval: { startTime: string; endTime: string | null };
+ /**
+ * The start of the interval's first day to the end of its last day (the
+ * end of today for a running interval), in the work center's timezone. An
+ * interval across midnight takes suggestions from both days.
+ */
+ window: { start: string; end: string };
+ nowMs: number;
+ limit?: number;
+}): MachineTimeSuggestion[] {
+ const windowStart = Date.parse(args.window.start);
+ const windowEnd = Date.parse(args.window.end);
+ const from = Date.parse(args.interval.startTime);
+ const to = args.interval.endTime
+ ? Date.parse(args.interval.endTime)
+ : args.nowMs;
+
+ type Group = MachineTimeSuggestion & { gapMs: number };
+ const groups = new Map<string, Group>();
+
+ for (const event of args.events) {
+ const operation = event.jobOperation;
+ const job = operation?.job;
+ if (!operation || !job) continue;
+
+ const start = Date.parse(event.startTime);
+ const end = event.endTime ? Date.parse(event.endTime) : args.nowMs;
+ const covered = Math.max(
+ 0,
+ Math.min(end, windowEnd) - Math.max(start, windowStart)
+ );
+ const overlaps = start < to && end > from;
+ const gapMs = overlaps ? 0 : start >= to ? start - to : from - end;
+
+ const group = groups.get(operation.id);
+ if (group) {
+ group.totalMs += covered;
+ group.overlaps ||= overlaps;
+ group.gapMs = Math.min(group.gapMs, gapMs);
+ if (event.startTime < group.firstStart) {
+ group.firstStart = event.startTime;
+ }
+ if (group.lastEnd !== null) {
+ group.lastEnd =
+ event.endTime === null
+ ? null
+ : event.endTime > group.lastEnd
+ ? event.endTime
+ : group.lastEnd;
+ }
+ continue;
+ }
+
+ groups.set(operation.id, {
+ jobOperationId: operation.id,
+ jobReadableId: job.jobId,
+ description: operation.description ?? "",
+ itemReadableId: job.item?.readableIdWithRevision ?? null,
+ firstStart: event.startTime,
+ lastEnd: event.endTime,
+ totalMs: covered,
+ overlaps,
+ gapMs,
+ blockedBy: machineTimeRefusal(operation.status, job.status)
+ });
+ }
+
+ return [...groups.values()]
+ .sort((a, b) => {
+ // An operation that can take the time comes before one that cannot.
+ if ((a.blockedBy === null) !== (b.blockedBy === null)) {
+ return a.blockedBy === null ? -1 : 1;
+ }
+ if (a.gapMs !== b.gapMs) return a.gapMs - b.gapMs;
+ return b.totalMs - a.totalMs;
+ })
+ .slice(0, args.limit ?? MACHINE_TIME_SUGGESTION_LIMIT)
+ .map(({ gapMs: _gapMs, ...suggestion }) => suggestion);
+}
diff --git a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx b/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
index f70d06d9cc..eb5486964a 100644
--- a/apps/erp/app/modules/production/ui/useProductionSubmodules.tsx
+++ b/apps/erp/app/modules/production/ui/useProductionSubmodules.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 { getIntegrationIdsByRole } from "@carbon/ee";
import { useLingui } from "@lingui/react/macro";
import {
LuChartBarBig,
@@ -13,11 +14,13 @@ import {
LuSquareChartGantt,
LuSquareKanban,
LuStepForward,
+ LuTimerOff,
LuTrash,
LuTruck
} from "react-icons/lu";
import { GroupedContentSidebar } from "~/components/Layout";
import { usePermissions } from "~/hooks";
+import { useIntegrations } from "~/hooks/useIntegrations";
import { useSavedViews } from "~/hooks/useSavedViews";
import type { AuthenticatedRouteGroup } from "~/types";
import { path } from "~/utils/path";
@@ -25,6 +28,15 @@ import { path } from "~/utils/path";
export default function useProductionSubmodules() {
const { t } = useLingui();
const permissions = usePermissions();
+ // Unattributed Time only exists once an OEE provider is reporting machines.
+ const integrations = useIntegrations();
+ const oeeIntegrationIds = new Set<string>(getIntegrationIdsByRole("oee"));
+ const hasOeeProvider = integrations.list.some(
+ (integration) =>
+ integration.active &&
+ integration.id !== null &&
+ oeeIntegrationIds.has(integration.id)
+ );
const productionRoutes: AuthenticatedRouteGroup[] = [
{
@@ -41,7 +53,17 @@ export default function useProductionSubmodules() {
to: path.to.operationBatches,
icon: <LuLayers />,
table: "jobOperationBatch"
- }
+ },
+ ...(hasOeeProvider
+ ? [
+ {
+ name: t`Unattributed Time`,
+ to: path.to.unattributedMachineTimes,
+ icon: <LuTimerOff />,
+ role: "employee" as const
+ }
+ ]
+ : [])
]
},
{
diff --git a/apps/erp/app/modules/settings/oee-devices-cache.ts b/apps/erp/app/modules/settings/oee-devices-cache.ts
new file mode 100644
index 0000000000..5be8091d84
--- /dev/null
+++ b/apps/erp/app/modules/settings/oee-devices-cache.ts
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+/**
+ * The Redis key of an OEE integration's cached device list. Its own module so
+ * `settings.server.ts` can clear the key without importing the provider code
+ * in `oee-devices.server.ts`.
+ */
+export const oeeDevicesCacheKey = (companyId: string, integrationId: string) =>
+ `oee-devices:${companyId}:${integrationId}`;
diff --git a/apps/erp/app/modules/settings/oee-devices.server.ts b/apps/erp/app/modules/settings/oee-devices.server.ts
new file mode 100644
index 0000000000..8cdd954ea5
--- /dev/null
+++ b/apps/erp/app/modules/settings/oee-devices.server.ts
@@ -0,0 +1,261 @@
+// 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 { error, success } from "@carbon/auth";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { flash } from "@carbon/auth/session.server";
+import type { Database } from "@carbon/database";
+import { EntitlementError } from "@carbon/ee/entitlements.server";
+import type { OeeDevice } from "@carbon/ee/oee";
+import {
+ deleteWorkCenterDevice,
+ getOeeProvider,
+ upsertWorkCenterDevice
+} from "@carbon/ee/oee.server";
+import { validationError, validator } from "@carbon/form";
+import { redis } from "@carbon/kv";
+import { getLogger } from "@carbon/logger";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { data } from "react-router";
+import { getDatabaseClient } from "~/services/database.server";
+import { oeeDevicesCacheKey } from "./oee-devices-cache";
+import { workCenterDeviceUpsertValidator } from "./settings.models";
+
+const logger = getLogger("erp", "oee-devices");
+
+// Picking a work center revalidates the tab, and a mapping change does not
+// change the provider's device list. A short TTL keeps those revalidations off
+// the provider. A change to the integration's connection (its API key or
+// environment) clears it: `clearCompanyIntegrationCache` deletes these keys.
+// The @carbon/kv wrapper fails soft: a Redis miss or outage just calls the
+// provider.
+const DEVICES_TTL_SECONDS = 60;
+
+async function getCachedDevices(
+ companyId: string,
+ integrationId: string
+): Promise<OeeDevice[] | null> {
+ const key = oeeDevicesCacheKey(companyId, integrationId);
+ const cached = await redis.get(key);
+ if (!cached) return null;
+ try {
+ return JSON.parse(cached) as OeeDevice[];
+ } catch (err) {
+ logger.error("Failed to parse cached OEE devices", {
+ companyId,
+ integrationId,
+ error: err
+ });
+ await redis.del(key);
+ return null;
+ }
+}
+
+/**
+ * The provider's devices for an OEE integration, cached for 60 seconds. A
+ * provider error is never cached.
+ */
+async function listOeeDevices(
+ companyId: string,
+ integrationId: string
+): Promise<{ devices: OeeDevice[]; error: string | null }> {
+ const cached = await getCachedDevices(companyId, integrationId);
+ if (cached) return { devices: cached, error: null };
+
+ let error: string | null = null;
+ try {
+ const oee = await getOeeProvider(
+ getCarbonServiceRole(),
+ companyId,
+ integrationId
+ );
+ if (oee.error || !oee.data) {
+ error = oee.error ?? "Could not connect to the provider";
+ } else {
+ const devices = await oee.data.provider.listDevices();
+ await redis.set(
+ oeeDevicesCacheKey(companyId, integrationId),
+ JSON.stringify(devices),
+ "EX",
+ DEVICES_TTL_SECONDS
+ );
+ return { devices, error: null };
+ }
+ } catch (err) {
+ error = err instanceof Error ? err.message : String(err);
+ }
+ logger.error("Failed to list OEE devices", {
+ companyId,
+ integrationId,
+ error
+ });
+ return { devices: [], error };
+}
+
+/**
+ * Device-mapping data for an OEE integration's Devices tab: the provider's
+ * devices, this integration's saved mappings, the work centers another OEE
+ * integration already holds, and the active work centers (plus any inactive
+ * one a device of this integration is still mapped to) with their location
+ * timezone. A provider failure renders the mappings with no devices and the
+ * error above the list rather than failing the drawer. The device list is
+ * cached for 60 seconds; a provider error is never cached.
+ */
+export async function getOeeDevicesTabData(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ integrationId: string
+) {
+ // The provider read runs alongside the mappings. Mappings come before the
+ // work centers: the work center list must include an inactive work center a
+ // device is still mapped to, or its row shows no work center.
+ const [{ devices, error: providerError }, mappings] = await Promise.all([
+ listOeeDevices(companyId, integrationId),
+ client
+ .from("workCenterDevice")
+ .select(
+ "externalDeviceId, deviceName, externalSiteId, siteTimezone, workCenterId, currentState, lastSyncedAt, lastSyncError"
+ )
+ .eq("companyId", companyId)
+ .eq("integration", integrationId)
+ ]);
+
+ const mappedIds = (mappings.data ?? []).map((m) => m.workCenterId);
+ const workCentersQuery = client
+ .from("workCenter")
+ .select("id, name, location(timezone)")
+ .eq("companyId", companyId);
+
+ const [takenWorkCenters, workCenters] = await Promise.all([
+ client
+ .from("workCenterDevice")
+ .select("workCenterId, deviceName, integration")
+ .eq("companyId", companyId)
+ .neq("integration", integrationId),
+ (mappedIds.length > 0
+ ? workCentersQuery.or(`active.eq.true,id.in.(${mappedIds.join(",")})`)
+ : workCentersQuery.eq("active", true)
+ ).order("name")
+ ]);
+
+ for (const result of [mappings, takenWorkCenters, workCenters]) {
+ if (result.error) {
+ logger.error("Failed to load OEE device mapping data", {
+ companyId,
+ integrationId,
+ error: result.error
+ });
+ }
+ }
+
+ return {
+ devices,
+ mappings: mappings.data ?? [],
+ takenWorkCenters: takenWorkCenters.data ?? [],
+ workCenters: (workCenters.data ?? []).map((workCenter) => ({
+ id: workCenter.id,
+ name: workCenter.name,
+ // Null when the location inherits the company's timezone ('' or null):
+ // the tab falls back to the company's.
+ locationTimezone: workCenter.location?.timezone || null
+ })),
+ error: providerError
+ };
+}
+
+/**
+ * Map or unmap one device (Devices tab of an OEE integration). An empty work
+ * center unmaps. Returns the action response: the tab stays on the page and
+ * revalidates in place.
+ */
+export async function saveWorkCenterDeviceMapping(
+ request: Request,
+ formData: FormData,
+ {
+ client,
+ companyId,
+ userId,
+ integrationId
+ }: {
+ client: SupabaseClient<Database>;
+ companyId: string;
+ userId: string;
+ integrationId: string;
+ }
+) {
+ const validation = await validator(workCenterDeviceUpsertValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { externalDeviceId, deviceName, workCenterId } = validation.data;
+
+ // Map only a station the current connection reports: a list read before
+ // the API key changed could name a station this provider does not have,
+ // and its mapping would never sync. The stored name, site and timezone are
+ // the provider's, not the form's.
+ let device: OeeDevice | undefined;
+ if (workCenterId) {
+ const provider = await listOeeDevices(companyId, integrationId);
+ device = provider.devices.find(
+ (candidate) => candidate.externalDeviceId === externalDeviceId
+ );
+ if (!device) {
+ const message =
+ provider.error ?? `${deviceName} is not a station of this provider`;
+ return data(
+ {},
+ await flash(
+ request,
+ error(message, `Failed to save device mapping: ${message}`)
+ )
+ );
+ }
+ }
+
+ let result: { error: string | null };
+ try {
+ result =
+ workCenterId && device
+ ? await upsertWorkCenterDevice(client, getDatabaseClient(), {
+ companyId,
+ userId,
+ integration: integrationId,
+ externalDeviceId,
+ externalSiteId: device.externalSiteId,
+ siteTimezone: device.siteTimezone,
+ deviceName: device.name,
+ workCenterId
+ })
+ : await deleteWorkCenterDevice(client, getDatabaseClient(), {
+ companyId,
+ userId,
+ integration: integrationId,
+ externalDeviceId
+ });
+ } catch (err) {
+ if (!(err instanceof EntitlementError)) throw err;
+ logger.error("OEE device mapping refused: not entitled", {
+ companyId,
+ integrationId,
+ error: err
+ });
+ result = { error: err.message };
+ }
+
+ if (result.error) {
+ return data(
+ {},
+ await flash(
+ request,
+ error(result.error, `Failed to save device mapping: ${result.error}`)
+ )
+ );
+ }
+
+ return data({}, await flash(request, success("Saved device mapping")));
+}
diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.ts
index 389f1e1d9e..29b47e1ab7 100644
--- a/apps/erp/app/modules/settings/settings.models.ts
+++ b/apps/erp/app/modules/settings/settings.models.ts
@@ -557,6 +557,15 @@ export const accountMappingUpsertValidator = z.object({
externalName: zfd.text(z.string().optional())
});
+export const workCenterDeviceUpsertValidator = z.object({
+ intent: z.literal("upsert-work-center-device"),
+ externalDeviceId: z.string().min(1, { message: "Device is required" }),
+ deviceName: z.string().min(1, { message: "Device name is required" }),
+ externalSiteId: zfd.text(z.string().optional()),
+ siteTimezone: zfd.text(z.string().optional()),
+ workCenterId: zfd.text(z.string().optional())
+});
+
const accountMappingEntrySchema = z.object({
accountId: z.string().min(1),
externalId: z.string().min(1),
diff --git a/apps/erp/app/modules/settings/settings.server.ts b/apps/erp/app/modules/settings/settings.server.ts
index c6e6d8000d..4716b4a4c9 100644
--- a/apps/erp/app/modules/settings/settings.server.ts
+++ b/apps/erp/app/modules/settings/settings.server.ts
@@ -22,6 +22,7 @@ import type { SupabaseClient } from "@supabase/supabase-js";
import type { z } from "zod";
import type { Integration } from "~/modules/settings/types";
import { sanitize } from "~/utils/supabase";
+import { oeeDevicesCacheKey } from "./oee-devices-cache";
import type { customFieldValidator } from "./settings.models";
const INTEGRATION_CACHE_TTL = 3600;
@@ -80,8 +81,15 @@ export async function clearCompanyIntegrationCache(
const cacheKey = `integrations:${companyId}`;
try {
- // Clear both old and new key formats
- await redis.del(cacheKey, `json:${cacheKey}`);
+ // Clear both old and new key formats, and the OEE device lists: a new API
+ // key or environment can name different stations.
+ await redis.del(
+ cacheKey,
+ `json:${cacheKey}`,
+ ...getIntegrationIdsByRole("oee").map((integrationId) =>
+ oeeDevicesCacheKey(companyId, integrationId)
+ )
+ );
} catch (error) {
logger.error("Redis cache invalidation error", { error });
}
diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx
index 99d6dc6aa2..e73a1a6501 100644
--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx
+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx
@@ -84,11 +84,14 @@ export function IntegrationCard({
// refusal as a failed install — and it names the incumbent, so the next step
// is obvious.
const providerRole = (
- integration as { providerRole?: "accounting" | "spend" }
+ integration as { providerRole?: "accounting" | "spend" | "oee" }
).providerRole;
- const roleIncumbent = providerRole
- ? (routeData?.activeRoles?.[providerRole] ?? null)
- : null;
+ // Several OEE providers may be active at once (the database exempts the
+ // role), so an active one is never an incumbent.
+ const roleIncumbent =
+ providerRole && providerRole !== "oee"
+ ? (routeData?.activeRoles?.[providerRole] ?? null)
+ : null;
const modes =
(
integration as {
diff --git a/apps/erp/app/modules/settings/ui/Integrations/OeeDevices.ee.tsx b/apps/erp/app/modules/settings/ui/Integrations/OeeDevices.ee.tsx
new file mode 100644
index 0000000000..d68059a44e
--- /dev/null
+++ b/apps/erp/app/modules/settings/ui/Integrations/OeeDevices.ee.tsx
@@ -0,0 +1,510 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import {
+ Combobox,
+ cn,
+ DrawerBody,
+ Input,
+ InputGroup,
+ InputLeftElement,
+ Table,
+ Tbody,
+ Td,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+ Tr
+} from "@carbon/react";
+import { Trans, useLingui } from "@lingui/react/macro";
+import type { ReactNode } from "react";
+import { Fragment, useMemo, useState } from "react";
+import { LuSearch, LuTriangleAlert } from "react-icons/lu";
+import { useFetcher } from "react-router";
+import RulesUpgradeOverlay from "~/components/RulesUpgradeOverlay";
+import { useDateFormatter, usePermissions } from "~/hooks";
+import { useCompanyTimeZone } from "~/hooks/useCompanyTimeZone";
+import { usePlanGate } from "~/hooks/usePlanGate";
+
+/**
+ * Local structural mirrors of @carbon/ee/oee's OeeDevice and the
+ * workCenterDevice rows. Deliberately NOT imported (even type-only) for the
+ * same TS2589 reason as AccountMapping.tsx. The route's loader passes real
+ * rows, so any drift fails typecheck there.
+ */
+export type OeeDeviceRow = {
+ externalDeviceId: string;
+ name: string;
+ externalSiteId: string | null;
+ siteName: string | null;
+ siteTimezone: string | null;
+ manufacturer: string | null;
+ model: string | null;
+ machineType: string | null;
+ calibrated: boolean | null;
+};
+
+export type OeeDeviceMappingRow = {
+ externalDeviceId: string;
+ deviceName: string;
+ externalSiteId: string | null;
+ siteTimezone: string | null;
+ workCenterId: string;
+ currentState: "Running" | "Idle" | "Down" | "Offline" | null;
+ lastSyncedAt: string | null;
+ lastSyncError: string | null;
+};
+
+export type OeeTakenWorkCenterRow = {
+ workCenterId: string;
+ deviceName: string;
+ integration: string;
+};
+
+export type OeeWorkCenterRow = {
+ id: string;
+ name: string;
+ /** Null when the location inherits the company's timezone. */
+ locationTimezone: string | null;
+};
+
+type OeeDevicesProps = {
+ /** Shared tab bar, rendered at the top of this tab's body card. */
+ tabs?: ReactNode;
+ devices: OeeDeviceRow[];
+ mappings: OeeDeviceMappingRow[];
+ /** Work centers another OEE integration already holds. */
+ takenWorkCenters: OeeTakenWorkCenterRow[];
+ workCenters: OeeWorkCenterRow[];
+ /** The provider's device list failed to load. */
+ error: string | null;
+};
+
+export function OeeDevices({
+ tabs,
+ devices,
+ mappings,
+ takenWorkCenters,
+ workCenters,
+ error
+}: OeeDevicesProps) {
+ const { t } = useLingui();
+ const permissions = usePermissions();
+ const { isGated } = usePlanGate({ feature: "INTEGRATIONS" });
+
+ return (
+ <DrawerBody className="gap-4">
+ {tabs}
+ {isGated ? (
+ <RulesUpgradeOverlay
+ preview={
+ <OeeDeviceList
+ devices={mockDevices}
+ mappings={[]}
+ takenWorkCenters={[]}
+ workCenters={[]}
+ canUpdate={false}
+ />
+ }
+ title={t`Machine monitoring`}
+ description={t`Connect machine monitoring devices to work centers so machine time is recorded against the operation that is loaded.`}
+ />
+ ) : (
+ <>
+ {error && (
+ <p className="flex w-full items-start gap-2 text-sm text-muted-foreground">
+ <LuTriangleAlert className="mt-0.5 size-4 shrink-0 text-red-500" />
+ <span className="min-w-0">
+ <Trans>
+ Could not list the provider's devices. Mapped devices are
+ still shown.
+ </Trans>{" "}
+ <span className="text-xs">{error}</span>
+ </span>
+ </p>
+ )}
+ <OeeDeviceList
+ devices={devices}
+ mappings={mappings}
+ takenWorkCenters={takenWorkCenters}
+ workCenters={workCenters}
+ canUpdate={permissions.can("update", "settings")}
+ />
+ </>
+ )}
+ </DrawerBody>
+ );
+}
+
+const mockDevices: OeeDeviceRow[] = [
+ {
+ externalDeviceId: "mock-1",
+ name: "Haas VF-2",
+ externalSiteId: "mock-site",
+ siteName: "Main Plant",
+ siteTimezone: null,
+ manufacturer: "Haas",
+ model: "VF-2",
+ machineType: null,
+ calibrated: true
+ },
+ {
+ externalDeviceId: "mock-2",
+ name: "Mazak QT-250",
+ externalSiteId: "mock-site",
+ siteName: "Main Plant",
+ siteTimezone: null,
+ manufacturer: "Mazak",
+ model: "QT-250",
+ machineType: null,
+ calibrated: true
+ }
+];
+
+type SiteGroup = {
+ key: string;
+ name: string | null;
+ timezone: string | null;
+ devices: OeeDeviceRow[];
+};
+
+function OeeDeviceList({
+ devices,
+ mappings,
+ takenWorkCenters,
+ workCenters,
+ canUpdate
+}: {
+ devices: OeeDeviceRow[];
+ mappings: OeeDeviceMappingRow[];
+ takenWorkCenters: OeeTakenWorkCenterRow[];
+ workCenters: OeeWorkCenterRow[];
+ canUpdate: boolean;
+}) {
+ const { t } = useLingui();
+ const [search, setSearch] = useState("");
+
+ const mappedByDeviceId = useMemo(
+ () =>
+ new Map(mappings.map((mapping) => [mapping.externalDeviceId, mapping])),
+ [mappings]
+ );
+ const workCenterById = useMemo(
+ () => new Map(workCenters.map((workCenter) => [workCenter.id, workCenter])),
+ [workCenters]
+ );
+ // A work center holds one device across every OEE provider: leave the ones
+ // another integration already maps out of the options. The ones another
+ // device of this integration holds are left out per row, below.
+ const workCenterOptions = useMemo(() => {
+ const taken = new Set(takenWorkCenters.map((row) => row.workCenterId));
+ return workCenters
+ .filter((workCenter) => !taken.has(workCenter.id))
+ .map((workCenter) => ({ value: workCenter.id, label: workCenter.name }));
+ }, [workCenters, takenWorkCenters]);
+ const deviceIdByWorkCenterId = useMemo(
+ () =>
+ new Map(
+ mappings.map((mapping) => [
+ mapping.workCenterId,
+ mapping.externalDeviceId
+ ])
+ ),
+ [mappings]
+ );
+
+ // A mapped device stays listed when the provider cannot list its devices
+ // (a slow or failing API), so it can still be seen and unmapped.
+ const rows = useMemo(() => {
+ const listed = new Set(devices.map((device) => device.externalDeviceId));
+ const mappedOnly: OeeDeviceRow[] = mappings
+ .filter((mapping) => !listed.has(mapping.externalDeviceId))
+ .map((mapping) => ({
+ externalDeviceId: mapping.externalDeviceId,
+ name: mapping.deviceName,
+ externalSiteId: mapping.externalSiteId,
+ siteName: null,
+ siteTimezone: mapping.siteTimezone,
+ manufacturer: null,
+ model: null,
+ machineType: null,
+ calibrated: null
+ }));
+ return [...mappedOnly, ...devices];
+ }, [devices, mappings]);
+
+ const groups = useMemo(() => {
+ const term = search.trim().toLowerCase();
+ const matches = term
+ ? rows.filter((device) =>
+ [device.name, device.manufacturer, device.model, device.siteName]
+ .filter((value): value is string => Boolean(value))
+ .some((value) => value.toLowerCase().includes(term))
+ )
+ : rows;
+ const bySite = new Map<string, SiteGroup>();
+ for (const device of matches) {
+ const key = device.externalSiteId ?? "";
+ const group = bySite.get(key) ?? {
+ key,
+ name: device.siteName,
+ timezone: device.siteTimezone,
+ devices: []
+ };
+ group.name ??= device.siteName;
+ group.devices.push(device);
+ bySite.set(key, group);
+ }
+ const collator = new Intl.Collator(undefined, { numeric: true });
+ return [...bySite.values()]
+ .map((group) => ({
+ ...group,
+ devices: group.devices.sort((a, b) => collator.compare(a.name, b.name))
+ }))
+ .sort((a, b) => collator.compare(a.name ?? "", b.name ?? ""));
+ }, [rows, search]);
+
+ const mappedCount = rows.filter((device) =>
+ mappedByDeviceId.has(device.externalDeviceId)
+ ).length;
+ const totalCount = rows.length;
+
+ return (
+ <div className="flex w-full flex-col gap-3">
+ <div className="flex w-full items-center justify-between gap-3">
+ <div className="w-full max-w-[280px]">
+ <InputGroup size="sm">
+ <InputLeftElement>
+ <LuSearch className="size-4 text-muted-foreground" />
+ </InputLeftElement>
+ <Input
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ placeholder={t`Search devices`}
+ />
+ </InputGroup>
+ </div>
+ <span className="shrink-0 text-xs tabular-nums text-muted-foreground">
+ <Trans>
+ {mappedCount} of {totalCount} mapped
+ </Trans>
+ </span>
+ </div>
+
+ {groups.length === 0 ? (
+ <p className="w-full py-8 text-center text-sm text-muted-foreground">
+ {rows.length === 0 ? (
+ <Trans>No devices found</Trans>
+ ) : (
+ <Trans>No devices match your search</Trans>
+ )}
+ </p>
+ ) : (
+ <Table full>
+ <Tbody>
+ {groups.map((group) => (
+ <Fragment key={group.key}>
+ <Tr className="border-b border-border">
+ <Td
+ colSpan={2}
+ className="px-0 pb-2 pt-5 text-xs font-medium text-muted-foreground"
+ >
+ {group.name ?? <Trans>Mapped devices</Trans>}
+ {group.timezone && (
+ <span className="font-normal"> · {group.timezone}</span>
+ )}
+ </Td>
+ </Tr>
+ {group.devices.map((device) => {
+ const mapping = mappedByDeviceId.get(device.externalDeviceId);
+ return (
+ <OeeDeviceTableRow
+ key={`${device.externalDeviceId}:${mapping?.workCenterId ?? ""}`}
+ device={device}
+ mapping={mapping ?? null}
+ workCenterById={workCenterById}
+ workCenterOptions={workCenterOptions}
+ deviceIdByWorkCenterId={deviceIdByWorkCenterId}
+ canUpdate={canUpdate}
+ />
+ );
+ })}
+ </Fragment>
+ ))}
+ </Tbody>
+ </Table>
+ )}
+ </div>
+ );
+}
+
+/**
+ * One provider device → Carbon work center. Picking a work center saves at
+ * once (intent upsert-work-center-device); clearing it unmaps the device.
+ */
+function OeeDeviceTableRow({
+ device,
+ mapping,
+ workCenterById,
+ workCenterOptions,
+ deviceIdByWorkCenterId,
+ canUpdate
+}: {
+ device: OeeDeviceRow;
+ mapping: OeeDeviceMappingRow | null;
+ workCenterById: Map<string, OeeWorkCenterRow>;
+ workCenterOptions: { value: string; label: string }[];
+ /** This integration's mappings: work center → the device it holds. */
+ deviceIdByWorkCenterId: Map<string, string>;
+ canUpdate: boolean;
+}) {
+ const { t } = useLingui();
+ const companyTimeZone = useCompanyTimeZone();
+ const fetcher = useFetcher();
+ const isSaving = fetcher.state !== "idle";
+
+ // While a save is in flight show the pick; afterwards the loader's mapping
+ // is the truth, so a refused save falls back to what is stored.
+ const pendingWorkCenterId = isSaving
+ ? String(fetcher.formData?.get("workCenterId") ?? "")
+ : null;
+ const workCenterId = pendingWorkCenterId ?? mapping?.workCenterId ?? "";
+
+ // The work center keeps time on its location's clock, else the company's.
+ const workCenter = workCenterId ? workCenterById.get(workCenterId) : null;
+ const locationTimezone = workCenter
+ ? workCenter.locationTimezone || companyTimeZone
+ : null;
+ const siteTimezone = device.siteTimezone;
+ const timezoneMismatch =
+ siteTimezone !== null &&
+ locationTimezone !== null &&
+ siteTimezone !== locationTimezone;
+
+ // A work center another device of this integration holds is refused on
+ // save, so it is not offered; this row's own stays.
+ const options = workCenterOptions.filter((option) => {
+ const holder = deviceIdByWorkCenterId.get(option.value);
+ return holder === undefined || holder === device.externalDeviceId;
+ });
+
+ const save = (nextWorkCenterId: string) => {
+ if (nextWorkCenterId === (mapping?.workCenterId ?? "")) return;
+ const formData = new FormData();
+ formData.set("intent", "upsert-work-center-device");
+ formData.set("externalDeviceId", device.externalDeviceId);
+ formData.set("deviceName", device.name);
+ formData.set("externalSiteId", device.externalSiteId ?? "");
+ formData.set("siteTimezone", device.siteTimezone ?? "");
+ formData.set("workCenterId", nextWorkCenterId);
+ fetcher.submit(formData, { method: "post" });
+ };
+
+ const machine = [device.manufacturer, device.model].filter(Boolean).join(" ");
+
+ return (
+ <Tr className="border-b border-border last:border-b-0">
+ <Td className="px-0 py-2.5">
+ <div className="flex min-w-0 items-center gap-3">
+ <DeviceStatusDot mapping={mapping} />
+ <div className="flex min-w-0 flex-col">
+ <span className="truncate text-sm font-medium">{device.name}</span>
+ {(machine || device.calibrated === false) && (
+ <span className="truncate text-xs text-muted-foreground">
+ {machine}
+ {machine && device.calibrated === false && " · "}
+ {device.calibrated === false && <Trans>Not calibrated</Trans>}
+ </span>
+ )}
+ </div>
+ </div>
+ </Td>
+ <Td className="w-[240px] py-2.5 pl-3 pr-0">
+ <div className="flex items-center justify-end gap-2">
+ {timezoneMismatch && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="shrink-0">
+ <LuTriangleAlert className="size-3.5 text-amber-500" />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs">
+ <Trans>
+ The device's site is in {siteTimezone}; Carbon uses{" "}
+ {locationTimezone}
+ </Trans>
+ </TooltipContent>
+ </Tooltip>
+ )}
+ <div className="w-[200px] shrink-0">
+ <Combobox
+ size="sm"
+ value={workCenterId}
+ options={options}
+ placeholder={t`Not mapped`}
+ isClearable
+ isLoading={isSaving}
+ isReadOnly={!canUpdate}
+ onChange={save}
+ />
+ </div>
+ </div>
+ </Td>
+ </Tr>
+ );
+}
+
+/** A status dot for the machine's state, with the details on hover. */
+function DeviceStatusDot({ mapping }: { mapping: OeeDeviceMappingRow | null }) {
+ const { t } = useLingui();
+ const { formatTimeAgo } = useDateFormatter();
+
+ const stateLabels = {
+ Running: t`Running`,
+ Idle: t`Idle`,
+ Down: t`Down`,
+ Offline: t`Offline`
+ } as const;
+ const stateDots = {
+ Running: "bg-emerald-500",
+ Idle: "bg-amber-400",
+ Down: "bg-red-500",
+ Offline: "bg-muted-foreground/40"
+ } as const;
+
+ let dotClassName = "border border-muted-foreground/40";
+ // A plain string: it is both the tooltip and the trigger's aria-label.
+ let labelText = t`Not mapped`;
+ if (mapping?.lastSyncError) {
+ dotClassName = "bg-red-500";
+ labelText = mapping.lastSyncError;
+ } else if (mapping?.currentState) {
+ const state = stateLabels[mapping.currentState];
+ dotClassName = stateDots[mapping.currentState];
+ const syncedAgo = mapping.lastSyncedAt
+ ? formatTimeAgo(mapping.lastSyncedAt)
+ : null;
+ labelText = syncedAgo ? t`${state} · synced ${syncedAgo}` : state;
+ } else if (mapping) {
+ dotClassName = "bg-muted-foreground/40";
+ labelText = t`Waiting for the first sync`;
+ }
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span
+ // focusable: the tooltip is the only place the state is shown
+ tabIndex={0}
+ role="img"
+ aria-label={labelText}
+ className="flex size-4 shrink-0 items-center justify-center rounded-sm outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <span className={cn("size-2 rounded-full", dotClassName)} />
+ </span>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-xs">{labelText}</TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/apps/erp/app/routes/api+/integrations.$id.connect.ts b/apps/erp/app/routes/api+/integrations.$id.connect.ts
index 616ecf3d5e..2666b48847 100644
--- a/apps/erp/app/routes/api+/integrations.$id.connect.ts
+++ b/apps/erp/app/routes/api+/integrations.$id.connect.ts
@@ -53,9 +53,11 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
// database enforces this too (`companyIntegration_single_active_role`), but
// reaching that refusal AFTER the customer has authorized at the provider
// leaves them with a live grant and no install.
- const role = (integration as { providerRole?: "accounting" | "spend" })
- .providerRole;
- if (role) {
+ const role = (
+ integration as { providerRole?: "accounting" | "spend" | "oee" }
+ ).providerRole;
+ // Several OEE providers may be active at once, so the role has no incumbent.
+ if (role && role !== "oee") {
const roleIds = new Set<string>(getIntegrationIdsByRole(role));
const existing = await client
.from("companyIntegration")
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index e997e6e248..da390980ec 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -1145,7 +1145,7 @@
{"name":"resources_getWorkCenters","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"0340d99e8700","injectAuth":"companyId","permission":"resources:view","paginates":true,"defaults":"always"},
{"name":"resources_getWorkCentersByLocation","classification":"READ","paramCount":1,"schema":"de371a276a58","response":"f602591e2bf5","injectAuth":"companyId","permission":"resources:view","paginates":false},
{"name":"resources_getWorkCentersList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"0340d99e8700","injectAuth":"companyId","permission":"resources:view","paginates":false},
- {"name":"resources_getWorkCentersListWithBlockingStatus","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"63fcba641f9a","injectAuth":"companyId","permission":"resources:view","paginates":false},
+ {"name":"resources_getWorkCentersListWithBlockingStatus","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"fcb9583f02e0","injectAuth":"companyId","permission":"resources:view","paginates":false},
{"name":"resources_insertMaintenanceDispatch","classification":"WRITE","paramCount":14,"schema":"b192bab74c65","response":"ede36af7307d","injectAuth":"companyId+createdBy+updatedBy","permission":"resources:create","paginates":false},
{"name":"resources_processDeactivate","classification":"WRITE","paramCount":1,"schema":"01edb53077b2","response":"bcde375ebd4c","injectAuth":"companyId","permission":"resources:update","paginates":false},
{"name":"resources_resolveEmployeeAbilityExpiresAt","classification":"WRITE","paramCount":3,"schema":"ec5fc6dfaa43","response":"174e29b899b9","injectAuth":"companyId","permission":"resources:update","paginates":false},
diff --git a/apps/erp/app/routes/x+/production+/machine-time.$id.tsx b/apps/erp/app/routes/x+/production+/machine-time.$id.tsx
new file mode 100644
index 0000000000..3a40c0a5db
--- /dev/null
+++ b/apps/erp/app/routes/x+/production+/machine-time.$id.tsx
@@ -0,0 +1,358 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { assertIsPost, error, notFound, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import {
+ assignUnattributedMachineTime,
+ dismissUnattributedMachineTime
+} from "@carbon/ee/oee.server";
+import { requireFeature } from "@carbon/ee/plan.server";
+import { validationError, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
+import { redirect } from "@carbon/utils";
+import {
+ now,
+ parseAbsolute,
+ toCalendarDate,
+ toZoned
+} from "@internationalized/date";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import {
+ data,
+ useLoaderData,
+ useNavigate,
+ useSearchParams
+} from "react-router";
+import {
+ assignMachineTimeValidator,
+ dismissMachineTimeValidator,
+ getMachineTimeAssignTarget,
+ getMachineTimeOperationCandidates,
+ getUnattributedMachineTime,
+ getUnattributedMachineTimeNeighbors,
+ getWorkCenterDayEvents,
+ isJobLocked
+} from "~/modules/production";
+import MachineTimeDrawer from "~/modules/production/ui/MachineTime/MachineTimeDrawer.ee";
+import { parseMachineTimeListFilters } from "~/modules/production/ui/MachineTime/machine-time-filters.ee";
+import { suggestMachineTimeOperations } from "~/modules/production/ui/MachineTime/machine-time-suggestions.ee";
+import {
+ getCompanyTimeZone,
+ getLocationTimeZone
+} from "~/modules/shared/timezone.server";
+import { getDatabaseClient } from "~/services/database.server";
+import { requireUnlocked } from "~/utils/lockedGuard.server";
+import { getParams, path } from "~/utils/path";
+
+const logger = getLogger("erp", "production", "machine-time");
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "production",
+ role: "employee"
+ });
+
+ const { id } = params;
+ if (!id) throw notFound("id not found");
+
+ const machineTime = await getUnattributedMachineTime(client, id, companyId);
+ if (machineTime.error) {
+ logger.error("Failed to load machine time", {
+ companyId,
+ id,
+ error: machineTime.error
+ });
+ throw redirect(
+ `${path.to.unattributedMachineTimes}?${getParams(request)}`,
+ await flash(
+ request,
+ error(machineTime.error, "Failed to load machine time")
+ )
+ );
+ }
+ if (!machineTime.data) {
+ // Assigned, dismissed or aged out since the link was made.
+ throw redirect(
+ `${path.to.unattributedMachineTimes}?${getParams(request)}`,
+ await flash(request, error(null, "That machine time is no longer open"))
+ );
+ }
+
+ const { workCenterId, startTime, endTime, workCenter } = machineTime.data;
+ // `getLocationTimeZone` falls back to the company's itself; read the
+ // company's directly only when there is no location.
+ const timeZone = workCenter.locationId
+ ? await getLocationTimeZone(client, workCenter.locationId, companyId)
+ : await getCompanyTimeZone(client, companyId);
+
+ // The queue walks the list's rows: the same search and filters, read from
+ // the list's query string.
+ const filters = parseMachineTimeListFilters(
+ new URL(request.url).searchParams
+ );
+
+ // The work center's calendar days the time touches: from the start of the
+ // day it started to the end of the day it ended (today, while it runs).
+ const firstDay = toCalendarDate(parseAbsolute(startTime, timeZone));
+ const lastDay = toCalendarDate(
+ endTime ? parseAbsolute(endTime, timeZone) : now(timeZone)
+ );
+ const days = {
+ start: toZoned(firstDay, timeZone).toAbsoluteString(),
+ end: toZoned(lastDay.add({ days: 1 }), timeZone).toAbsoluteString()
+ };
+
+ const [neighbors, events, candidates] = await Promise.all([
+ getUnattributedMachineTimeNeighbors(client, {
+ companyId,
+ id,
+ startTime,
+ endTime,
+ filters
+ }),
+ getWorkCenterDayEvents(client, {
+ companyId,
+ workCenterId,
+ dayStart: days.start,
+ dayEnd: days.end
+ }),
+ getMachineTimeOperationCandidates(client, {
+ workCenterId,
+ locationId: workCenter.locationId,
+ companyId
+ })
+ ]);
+
+ // A failed read leaves the drawer usable: the drawer says which part did
+ // not load rather than showing it empty.
+ if (neighbors.error) {
+ logger.error("Failed to load the machine time queue", {
+ companyId,
+ id,
+ error: neighbors.error
+ });
+ }
+ if (events.error) {
+ logger.error("Failed to load the work center's production events", {
+ companyId,
+ id,
+ error: events.error
+ });
+ }
+ if (candidates.error) {
+ logger.error("Failed to load the machine time operation candidates", {
+ companyId,
+ id,
+ error: candidates.error
+ });
+ }
+
+ return {
+ machineTime: machineTime.data,
+ timeZone,
+ queue: neighbors.data ?? {
+ position: null,
+ total: 0,
+ previousId: null,
+ nextId: null
+ },
+ suggestions: suggestMachineTimeOperations({
+ events: events.data ?? [],
+ interval: { startTime, endTime },
+ window: days,
+ nowMs: Date.now()
+ }),
+ operationOptions: candidates.data ?? [],
+ loadErrors: {
+ queue: Boolean(neighbors.error),
+ suggestions: Boolean(events.error),
+ operations: Boolean(candidates.error)
+ }
+ };
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production"
+ });
+
+ const { id } = params;
+ if (!id) throw notFound("id not found");
+
+ const query = getParams(request);
+ const detailPath = `${path.to.unattributedMachineTime(id)}?${query}`;
+ const listPath = `${path.to.unattributedMachineTimes}?${query}`;
+
+ await requireFeature({
+ request,
+ client,
+ companyId,
+ feature: "INTEGRATIONS",
+ redirectTo: listPath
+ });
+
+ // Answering one moves on: to the row below, else the row above, else the
+ // list. Read before the write, which deletes this row. A failed read only
+ // loses the move: the answer still goes back to the list.
+ const machineTime = await getUnattributedMachineTime(client, id, companyId);
+ if (machineTime.error) {
+ logger.error("Failed to load machine time", {
+ companyId,
+ id,
+ error: machineTime.error
+ });
+ }
+ const filters = parseMachineTimeListFilters(
+ new URL(request.url).searchParams
+ );
+ const neighbors = machineTime.data
+ ? await getUnattributedMachineTimeNeighbors(client, {
+ companyId,
+ id,
+ startTime: machineTime.data.startTime,
+ endTime: machineTime.data.endTime,
+ filters
+ })
+ : null;
+ if (neighbors?.error) {
+ logger.error("Failed to load the machine time queue", {
+ companyId,
+ id,
+ error: neighbors.error
+ });
+ }
+ const nextId = neighbors?.data?.nextId ?? neighbors?.data?.previousId;
+ const nextPath = nextId
+ ? `${path.to.unattributedMachineTime(nextId)}?${query}`
+ : listPath;
+
+ const formData = await request.formData();
+ const intent = formData.get("intent");
+
+ if (intent === "assign") {
+ const validation = await validator(assignMachineTimeValidator).validate(
+ formData
+ );
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { jobOperationId } = validation.data;
+ const target = await getMachineTimeAssignTarget(client, {
+ jobOperationId,
+ companyId
+ });
+ if (target.error || !target.data) {
+ return data(
+ {},
+ await flash(request, error(target.error, "Failed to get operation"))
+ );
+ }
+ const job = target.data.job;
+
+ // A friendly redirect only: the service re-checks the lock under a row
+ // lock inside its transaction.
+ await requireUnlocked({
+ request,
+ isLocked: isJobLocked(job.status),
+ redirectTo: detailPath,
+ message: "Cannot modify a locked job. Reopen it first."
+ });
+
+ // Sensor-derived time is NOT posted to the GL here: the operation's
+ // machine time posts when the operation finishes.
+ const assignment = await assignUnattributedMachineTime(
+ client,
+ getDatabaseClient(),
+ {
+ companyId,
+ userId,
+ unattributedMachineTimeId: id,
+ jobOperationId
+ }
+ );
+ if (assignment.error) {
+ return data(
+ {},
+ await flash(
+ request,
+ error(
+ assignment.error,
+ `Failed to assign machine time: ${assignment.error}`
+ )
+ )
+ );
+ }
+
+ throw redirect(
+ nextPath,
+ await flash(request, success(`Assigned to ${job.jobId ?? "the job"}`))
+ );
+ }
+
+ if (intent === "dismiss") {
+ const validation = await validator(dismissMachineTimeValidator).validate(
+ formData
+ );
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const dismissal = await dismissUnattributedMachineTime(
+ client,
+ getDatabaseClient(),
+ { companyId, unattributedMachineTimeId: id }
+ );
+ if (dismissal.error) {
+ return data(
+ {},
+ await flash(
+ request,
+ error(
+ dismissal.error,
+ `Failed to dismiss machine time: ${dismissal.error}`
+ )
+ )
+ );
+ }
+
+ throw redirect(nextPath, await flash(request, success("Dismissed")));
+ }
+
+ return data({}, await flash(request, error(null, "Unknown intent")));
+}
+
+export default function MachineTimeDetailRoute() {
+ const {
+ machineTime,
+ timeZone,
+ queue,
+ suggestions,
+ operationOptions,
+ loadErrors
+ } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+ // The drawer's query string is the list's search and filters.
+ const [searchParams] = useSearchParams();
+
+ return (
+ <MachineTimeDrawer
+ key={machineTime.id}
+ machineTime={machineTime}
+ timeZone={timeZone}
+ queue={queue}
+ suggestions={suggestions}
+ operationOptions={operationOptions}
+ loadErrors={loadErrors}
+ // Back to the list, with its filters. Not history back: the queue's
+ // moves replace the entry, and the drawer may be the first page.
+ onClose={() =>
+ navigate(`${path.to.unattributedMachineTimes}?${searchParams}`)
+ }
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/production+/machine-time.tsx b/apps/erp/app/routes/x+/production+/machine-time.tsx
new file mode 100644
index 0000000000..39d1a10a27
--- /dev/null
+++ b/apps/erp/app/routes/x+/production+/machine-time.tsx
@@ -0,0 +1,83 @@
+// 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 { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { RecordOutlet, VStack } from "@carbon/react";
+import { redirect } from "@carbon/utils";
+import { msg } from "@lingui/core/macro";
+import type { LoaderFunctionArgs } from "react-router";
+import { useLoaderData } from "react-router";
+import { usePlanGate } from "~/hooks/usePlanGate";
+import { getUnattributedMachineTimes } from "~/modules/production";
+import MachineTimeTable from "~/modules/production/ui/MachineTime/MachineTimeTable.ee";
+import MachineTimeUpgradeOverlay from "~/modules/production/ui/MachineTime/MachineTimeUpgradeOverlay.ee";
+import { parseMachineTimeListFilters } from "~/modules/production/ui/MachineTime/machine-time-filters.ee";
+import { getLocationsList, getWorkCentersList } from "~/modules/resources";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export const handle: Handle = {
+ breadcrumb: msg`Unattributed Time`,
+ to: path.to.unattributedMachineTimes
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "production",
+ role: "employee"
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const { limit, offset } = getGenericQueryFilters(searchParams);
+ const filters = parseMachineTimeListFilters(searchParams);
+
+ const [machineTimes, workCenters, locations] = await Promise.all([
+ getUnattributedMachineTimes(client, companyId, { filters, limit, offset }),
+ getWorkCentersList(client, companyId),
+ getLocationsList(client, companyId)
+ ]);
+
+ if (machineTimes.error) {
+ throw redirect(
+ path.to.production,
+ await flash(
+ request,
+ error(machineTimes.error, "Failed to load unattributed machine time")
+ )
+ );
+ }
+
+ return {
+ machineTimes: machineTimes.data ?? [],
+ count: machineTimes.count ?? 0,
+ workCenters: workCenters.data ?? [],
+ locations: locations.data ?? []
+ };
+}
+
+export default function MachineTimeRoute() {
+ const { machineTimes, count, workCenters, locations } =
+ useLoaderData<typeof loader>();
+ const { isGated } = usePlanGate({ feature: "INTEGRATIONS" });
+
+ if (isGated) {
+ return <MachineTimeUpgradeOverlay />;
+ }
+
+ return (
+ <VStack spacing={0} className="h-full">
+ <MachineTimeTable
+ data={machineTimes}
+ count={count}
+ workCenters={workCenters}
+ locations={locations}
+ />
+ <RecordOutlet />
+ </VStack>
+ );
+}
diff --git a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
index 373a511990..1150137988 100644
--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
@@ -114,6 +114,10 @@ import {
SyncActivity,
syncOperationTransitionValidator
} from "~/modules/settings";
+import {
+ getOeeDevicesTabData,
+ saveWorkCenterDeviceMapping
+} from "~/modules/settings/oee-devices.server";
import {
accountMappingAiSuggestValidator,
accountMappingBulkUpsertValidator,
@@ -134,6 +138,7 @@ import { AccountMapping } from "~/modules/settings/ui/Integrations/AccountMappin
import { DimensionMapping } from "~/modules/settings/ui/Integrations/DimensionMapping";
import type { IntegrationFormTab } from "~/modules/settings/ui/Integrations/IntegrationForm";
import { useMountActionStates } from "~/modules/settings/ui/Integrations/MountPublishStatus";
+import { OeeDevices } from "~/modules/settings/ui/Integrations/OeeDevices.ee";
import { PostingSyncSettings } from "~/modules/settings/ui/Integrations/PostingSyncSettings";
import type { SyncReconciliationReport } from "~/modules/settings/ui/Integrations/SyncActivity";
import { getDatabaseClient } from "~/services/database.server";
@@ -689,24 +694,35 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
accountMapping: null,
accountingSync: null,
postingSync: null,
- dimensionSync: null
+ dimensionSync: null,
+ devices: null
};
}
// The DECLARED role, not the display category and not an id literal.
const providerRole = (
- integration as { providerRole?: "accounting" | "spend" }
+ integration as { providerRole?: "accounting" | "spend" | "oee" }
).providerRole;
const isAccountingInstalled =
providerRole === "accounting" && integrationData.data.active;
+ // The OEE Devices tab reads the provider (cached for 60 seconds). Started
+ // here and awaited at the end, so it runs alongside the reads below.
+ const devicesPromise =
+ providerRole === "oee" && integrationData.data.active
+ ? getOeeDevicesTabData(client, companyId, integrationId)
+ : Promise.resolve(null);
+
// Any provider-role integration writes accountingSyncOperation rows — a spend
// provider records its own inbound/outbound dispositions there — so it gets
// the same Sync Activity inbox. The accounting-only tie-out/reconciliation
// surfaces stay gated on isAccountingInstalled below.
+ // OEE providers record their sync state on each device, not here.
const producesSyncOperations =
- providerRole !== undefined && integrationData.data.active;
+ providerRole !== undefined &&
+ providerRole !== "oee" &&
+ integrationData.data.active;
// Sync-operation inbox (RLS SELECT covers employees, so the user-scoped
// client is enough). Params are prefixed (syncStatus/syncPage) to avoid
@@ -1142,6 +1158,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
: null;
+ const devices = await devicesPromise;
+
return {
installed: integrationData.data.active,
metadata: flattenedMetadata,
@@ -1150,7 +1168,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
accountMapping,
accountingSync,
postingSync,
- dimensionSync
+ dimensionSync,
+ devices
};
}
@@ -1789,6 +1808,17 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // Map or unmap one device (Devices tab of an OEE integration). An empty
+ // work center unmaps. Stays on the page so the tab revalidates in place.
+ if (formData.get("intent") === "upsert-work-center-device") {
+ return saveWorkCenterDeviceMapping(request, formData, {
+ client,
+ companyId,
+ userId,
+ integrationId
+ });
+ }
+
if (!isIntegrationWhitelisted(integrationId)) {
await requireFeature({
request,
@@ -1893,8 +1923,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
// OAuth providers make the same decision in their callbacks.
if (
!wasInstalled &&
- (integration as { providerRole?: "accounting" | "spend" }).providerRole ===
- "accounting"
+ (integration as { providerRole?: "accounting" | "spend" | "oee" })
+ .providerRole === "accounting"
) {
metadata.settings = {
...((metadata.settings as Record<string, unknown> | undefined) ?? {}),
@@ -1914,7 +1944,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
"paperless-parts",
"email",
"ramp",
- "rillet"
+ "rillet",
+ "sense"
]);
if (
FORM_SECRET_INTEGRATIONS.has(integrationId) ||
@@ -2157,7 +2188,8 @@ export default function IntegrationRoute() {
accountMapping,
accountingSync,
postingSync,
- dimensionSync
+ dimensionSync,
+ devices
} = useLoaderData<typeof loader>();
const navigate = useNavigate();
@@ -2171,6 +2203,13 @@ export default function IntegrationRoute() {
// and Sync Activity tabs next to the Settings form (deep-linkable via
// ?tab=<value>).
const tabs: IntegrationFormTab[] = [];
+ if (devices) {
+ tabs.push({
+ value: "devices",
+ label: <Trans>Devices</Trans>,
+ content: (tabBar) => <OeeDevices tabs={tabBar} {...devices} />
+ });
+ }
if (accountMapping) {
tabs.push({
value: "account-mapping",
diff --git a/apps/erp/app/shortcuts.ts b/apps/erp/app/shortcuts.ts
index b066789096..11dd4d98e9 100644
--- a/apps/erp/app/shortcuts.ts
+++ b/apps/erp/app/shortcuts.ts
@@ -64,6 +64,18 @@ export const PAGINATION_SHORTCUTS = {
next: "arrowright"
} as const satisfies Record<string, ShortcutInput>;
+/**
+ * Unattributed Time review drawer. The table behind it pages on the arrows,
+ * so the queue moves on j/k; 1–6 assign the matching suggestion card.
+ */
+export const MACHINE_TIME_REVIEW_SHORTCUTS = {
+ previous: "k",
+ next: "j",
+ // One key per card: matches MACHINE_TIME_SUGGESTION_LIMIT
+ // (ui/MachineTime/machine-time-suggestions.ee.ts).
+ choose: ["1", "2", "3", "4", "5", "6"]
+} as const satisfies Record<string, ShortcutInput | readonly ShortcutInput[]>;
+
/**
* g-then-letter module go-to, keyed by the stable module `key` from
* useModules() — never by position, since module order and visibility are
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 6c3faed089..2ac1aeef02 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -2582,6 +2582,9 @@ export const path = {
trialBalance: `${x}/reports/trial-balance`,
trialBalanceLedger: (id: string) =>
generatePath(`${x}/reports/trial-balance/${id}`),
+ unattributedMachineTime: (id: string) =>
+ generatePath(`${x}/production/machine-time/${id}`),
+ unattributedMachineTimes: `${x}/production/machine-time`,
uom: (id: string) => generatePath(`${x}/items/uom/${id}`),
uoms: `${x}/items/uom`,
updateAssemblyUnit: (id: string, unitId: string) =>
diff --git a/apps/erp/test/machine-time-filters.ee.test.ts b/apps/erp/test/machine-time-filters.ee.test.ts
new file mode 100644
index 0000000000..2e8f991529
--- /dev/null
+++ b/apps/erp/test/machine-time-filters.ee.test.ts
@@ -0,0 +1,104 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import {
+ machineTimeQueueKeyset,
+ parseMachineTimeListFilters
+} from "../app/modules/production/ui/MachineTime/machine-time-filters.ee";
+
+function parse(query: string) {
+ return parseMachineTimeListFilters(new URLSearchParams(query));
+}
+
+describe("parseMachineTimeListFilters", () => {
+ it("reads a startTime range as two inclusive days", () => {
+ const filters = parse("filter=startTime:between:2026-10-01,2026-10-05");
+
+ expect(filters.start).toEqual({ from: "2026-10-01", to: "2026-10-05" });
+ expect(filters.end).toEqual({ from: null, to: null });
+ });
+
+ it("leaves an open-ended range open", () => {
+ const filters = parse("filter=endTime:between:2026-10-01,");
+
+ expect(filters.end).toEqual({ from: "2026-10-01", to: null });
+ });
+
+ it("drops a bound that is not a date", () => {
+ const filters = parse("filter=startTime:between:2026-13-40,yesterday");
+
+ expect(filters.start).toEqual({ from: null, to: null });
+ });
+
+ it("splits a work center filter into ids", () => {
+ const filters = parse("filter=workCenterId:in:a,b");
+
+ expect(filters.workCenterIds).toEqual(["a", "b"]);
+ });
+
+ it("ignores a state that is not Running or Stopped", () => {
+ const filters = parse("filter=state:eq:Paused");
+
+ expect(filters.state).toBeNull();
+ });
+
+ it("reads the search, and none when it is empty", () => {
+ expect(parse("search=Haas").search).toBe("Haas");
+ expect(parse("search=").search).toBeNull();
+ expect(parse("").search).toBeNull();
+ });
+
+ it("splits a location filter into ids", () => {
+ const filters = parse("filter=locationId:in:loc1,loc2");
+
+ expect(filters.locationIds).toEqual(["loc1", "loc2"]);
+ expect(filters.workCenterIds).toEqual([]);
+ });
+
+ it("reads the Stopped state", () => {
+ expect(parse("filter=state:eq:Stopped").state).toBe("Stopped");
+ });
+
+ it("reads several filters together", () => {
+ const filters = parse(
+ [
+ "search=Mill",
+ "filter=workCenterId:in:wc1",
+ "filter=locationId:in:loc1",
+ "filter=startTime:between:2026-10-01,2026-10-05",
+ "filter=endTime:between:,2026-10-06",
+ "filter=state:eq:Running"
+ ].join("&")
+ );
+
+ expect(filters).toEqual({
+ search: "Mill",
+ workCenterIds: ["wc1"],
+ locationIds: ["loc1"],
+ start: { from: "2026-10-01", to: "2026-10-05" },
+ end: { from: null, to: "2026-10-06" },
+ state: "Running"
+ });
+ });
+});
+
+describe("machineTimeQueueKeyset", () => {
+ const keyset = machineTimeQueueKeyset({
+ id: "umt_b",
+ startTime: "2026-10-12T15:00:00+00:00"
+ });
+
+ it("puts a later start, or the same start and a greater id, above", () => {
+ expect(keyset.above).toBe(
+ 'startTime.gt."2026-10-12T15:00:00+00:00",and(startTime.eq."2026-10-12T15:00:00+00:00",id.gt.umt_b)'
+ );
+ });
+
+ it("puts an earlier start, or the same start and a smaller id, below", () => {
+ expect(keyset.below).toBe(
+ 'startTime.lt."2026-10-12T15:00:00+00:00",and(startTime.eq."2026-10-12T15:00:00+00:00",id.lt.umt_b)'
+ );
+ });
+});
diff --git a/apps/erp/test/machine-time-suggestions.ee.test.ts b/apps/erp/test/machine-time-suggestions.ee.test.ts
new file mode 100644
index 0000000000..83f8b8dc74
--- /dev/null
+++ b/apps/erp/test/machine-time-suggestions.ee.test.ts
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import type { DayEvent } from "../app/modules/production/ui/MachineTime/machine-time-suggestions.ee";
+import { suggestMachineTimeOperations } from "../app/modules/production/ui/MachineTime/machine-time-suggestions.ee";
+
+// One day in America/Chicago (UTC−5 in October).
+const day = {
+ start: "2026-10-12T05:00:00.000Z",
+ end: "2026-10-13T05:00:00.000Z"
+};
+const interval = {
+ startTime: "2026-10-12T15:00:00.000Z",
+ endTime: "2026-10-12T15:30:00.000Z"
+};
+const nowMs = Date.parse("2026-10-13T12:00:00.000Z");
+
+function event(
+ operationId: string,
+ startTime: string,
+ endTime: string | null,
+ overrides: {
+ operationStatus?: string;
+ jobStatus?: string;
+ } = {}
+): DayEvent {
+ return {
+ jobOperationId: operationId,
+ startTime,
+ endTime,
+ jobOperation: {
+ id: operationId,
+ description: `Op ${operationId}`,
+ status: overrides.operationStatus ?? "In Progress",
+ job: {
+ id: `job-${operationId}`,
+ jobId: `J-${operationId}`,
+ status: overrides.jobStatus ?? "In Progress",
+ item: { readableIdWithRevision: "PART-1" }
+ }
+ }
+ };
+}
+
+const suggest = (events: DayEvent[], limit?: number) =>
+ suggestMachineTimeOperations({
+ events,
+ interval,
+ window: day,
+ nowMs,
+ limit
+ });
+
+describe("suggestMachineTimeOperations", () => {
+ it("puts the operation that ran during the time first", () => {
+ const result = suggest([
+ // Ran most of the day, but not during the interval.
+ event("long", "2026-10-12T06:00:00.000Z", "2026-10-12T14:00:00.000Z"),
+ event("during", "2026-10-12T15:10:00.000Z", "2026-10-12T15:20:00.000Z")
+ ]);
+ expect(result.map((s) => s.jobOperationId)).toEqual(["during", "long"]);
+ expect(result[0]?.overlaps).toBe(true);
+ expect(result[1]?.overlaps).toBe(false);
+ });
+
+ it("ranks the rest by how close they ran to the time", () => {
+ const result = suggest([
+ event("far", "2026-10-12T07:00:00.000Z", "2026-10-12T08:00:00.000Z"),
+ event("after", "2026-10-12T15:45:00.000Z", "2026-10-12T16:00:00.000Z"),
+ event("before", "2026-10-12T14:00:00.000Z", "2026-10-12T14:55:00.000Z")
+ ]);
+ // 5 minutes before, 15 minutes after, 7 hours before.
+ expect(result.map((s) => s.jobOperationId)).toEqual([
+ "before",
+ "after",
+ "far"
+ ]);
+ });
+
+ it("groups an operation's events and counts only time inside the window", () => {
+ const [suggestion] = suggest([
+ // Started the evening before: only the 1 hour after the window starts counts.
+ event("op", "2026-10-12T03:00:00.000Z", "2026-10-12T06:00:00.000Z"),
+ event("op", "2026-10-12T15:00:00.000Z", "2026-10-12T15:30:00.000Z")
+ ]);
+ expect(suggestion?.totalMs).toBe(90 * 60 * 1000);
+ expect(suggestion?.firstStart).toBe("2026-10-12T03:00:00.000Z");
+ expect(suggestion?.lastEnd).toBe("2026-10-12T15:30:00.000Z");
+ });
+
+ it("keeps a running event open-ended and counts it to now", () => {
+ const [suggestion] = suggest([
+ event("op", "2026-10-12T15:00:00.000Z", "2026-10-12T15:05:00.000Z"),
+ event("op", "2026-10-13T04:00:00.000Z", null)
+ ]);
+ expect(suggestion?.lastEnd).toBeNull();
+ // 5 minutes, plus the running event clipped at the window's end.
+ expect(suggestion?.totalMs).toBe((5 + 60) * 60 * 1000);
+ });
+
+ it("marks operations that cannot take the time and puts them last", () => {
+ const result = suggest([
+ event("done", "2026-10-12T15:00:00.000Z", "2026-10-12T15:30:00.000Z", {
+ operationStatus: "Done"
+ }),
+ event("locked", "2026-10-12T15:00:00.000Z", "2026-10-12T15:30:00.000Z", {
+ jobStatus: "Completed"
+ }),
+ event("open", "2026-10-12T08:00:00.000Z", "2026-10-12T09:00:00.000Z")
+ ]);
+ expect(result.map((s) => [s.jobOperationId, s.blockedBy])).toEqual([
+ ["open", null],
+ ["done", "Done"],
+ ["locked", "Locked"]
+ ]);
+ });
+
+ it("suggests from both days of an interval across midnight", () => {
+ // 23:30 to 00:30 local: the window runs from the start of the first day
+ // to the end of the second.
+ const result = suggestMachineTimeOperations({
+ events: [
+ event("before", "2026-10-13T03:00:00.000Z", "2026-10-13T04:00:00.000Z"),
+ event("after", "2026-10-13T06:00:00.000Z", "2026-10-13T07:00:00.000Z")
+ ],
+ interval: {
+ startTime: "2026-10-13T04:30:00.000Z",
+ endTime: "2026-10-13T05:30:00.000Z"
+ },
+ window: {
+ start: "2026-10-12T05:00:00.000Z",
+ end: "2026-10-14T05:00:00.000Z"
+ },
+ nowMs
+ });
+ expect(result.map((s) => [s.jobOperationId, s.totalMs])).toEqual([
+ ["before", 60 * 60 * 1000],
+ ["after", 60 * 60 * 1000]
+ ]);
+ });
+
+ it("returns at most the limit", () => {
+ const events = Array.from({ length: 10 }, (_, i) =>
+ event(`op${i}`, "2026-10-12T15:00:00.000Z", "2026-10-12T15:10:00.000Z")
+ );
+ expect(suggest(events)).toHaveLength(6);
+ expect(suggest(events, 3)).toHaveLength(3);
+ });
+
+ it("skips an event whose operation or job could not be read", () => {
+ const orphan: DayEvent = {
+ jobOperationId: "gone",
+ startTime: "2026-10-12T15:00:00.000Z",
+ endTime: "2026-10-12T15:10:00.000Z",
+ jobOperation: null
+ };
+ expect(suggest([orphan])).toEqual([]);
+ });
+});
diff --git a/apps/mes/app/components/Display/DeviceStateBadge.tsx b/apps/mes/app/components/Display/DeviceStateBadge.tsx
new file mode 100644
index 0000000000..5d1127bee8
--- /dev/null
+++ b/apps/mes/app/components/Display/DeviceStateBadge.tsx
@@ -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 type { Database } from "@carbon/database";
+import { Badge } from "@carbon/react";
+import { useLingui } from "@lingui/react/macro";
+
+type MachineState = Database["public"]["Enums"]["machineState"];
+
+/** The live state an OEE device reports for the work center's machine. */
+export function DeviceStateBadge({
+ state,
+ className
+}: {
+ state: MachineState;
+ className?: string;
+}) {
+ const { t } = useLingui();
+ const display: Record<
+ MachineState,
+ { variant: "green" | "outline" | "red"; label: string }
+ > = {
+ Running: { variant: "green", label: t`Running` },
+ Idle: { variant: "outline", label: t`Idle` },
+ Down: { variant: "red", label: t`Down` },
+ Offline: { variant: "outline", label: t`Offline` }
+ };
+ const { variant, label } = display[state];
+ return (
+ <Badge variant={variant} className={className}>
+ {label}
+ </Badge>
+ );
+}
diff --git a/apps/mes/app/components/Display/index.ts b/apps/mes/app/components/Display/index.ts
index 644951fd57..3615c5b789 100644
--- a/apps/mes/app/components/Display/index.ts
+++ b/apps/mes/app/components/Display/index.ts
@@ -3,6 +3,7 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
export { ActiveWorkPanel } from "./ActiveWorkPanel";
+export { DeviceStateBadge } from "./DeviceStateBadge";
export { DisplayFrame } from "./DisplayFrame";
export type { QueueRow } from "./QueueTable";
export { QueueTable } from "./QueueTable";
diff --git a/apps/mes/app/routes/display+/$workCenterId.work.tsx b/apps/mes/app/routes/display+/$workCenterId.work.tsx
index 58933d8c13..9869825cc3 100644
--- a/apps/mes/app/routes/display+/$workCenterId.work.tsx
+++ b/apps/mes/app/routes/display+/$workCenterId.work.tsx
@@ -5,16 +5,20 @@
import { notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { datetime } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData } from "react-router";
import {
ActiveWorkPanel,
+ DeviceStateBadge,
DisplayFrame,
QueueTable
} from "~/components/Display";
import { userContext } from "~/context";
import {
+ getDisplayDeviceState,
+ getDisplayLoadedOperation,
getDisplayWorkCenter,
getWorkDisplayData
} from "~/services/display.service";
@@ -43,18 +47,54 @@ export async function loader({ context, params, request }: LoaderFunctionArgs) {
workCenter.locationId ?? context.get(userContext)?.locationId;
if (!locationId) throw notFound("Location not found");
- const { activeWork, queue, lastEventEndedAt } = await getWorkDisplayData(
- serviceRole,
- { workCenterId, companyId, locationId }
- );
+ const [
+ { activeWork, queue, lastEventEndedAt },
+ loadedOperation,
+ deviceState
+ ] = await Promise.all([
+ getWorkDisplayData(serviceRole, { workCenterId, companyId, locationId }),
+ // The operation loaded on the machine (the last timer started here), and
+ // the OEE device's live state when a device is mapped and its sync is
+ // current.
+ workCenter.loadedJobOperationId
+ ? getDisplayLoadedOperation(serviceRole, {
+ jobOperationId: workCenter.loadedJobOperationId,
+ companyId
+ })
+ : null,
+ getDisplayDeviceState(serviceRole, {
+ workCenterId,
+ companyId,
+ now: datetime.timestamp()
+ })
+ ]);
- return { workCenter, activeWork, queue, lastEventEndedAt };
+ return {
+ workCenter,
+ activeWork,
+ queue,
+ lastEventEndedAt,
+ loadedOperation,
+ deviceState
+ };
}
export default function WorkDisplayRoute() {
const { t } = useLingui();
- const { workCenter, activeWork, queue, lastEventEndedAt } =
- useLoaderData<typeof loader>();
+ const {
+ workCenter,
+ activeWork,
+ queue,
+ lastEventEndedAt,
+ loadedOperation,
+ deviceState
+ } = useLoaderData<typeof loader>();
+
+ const loadedLabel = loadedOperation
+ ? [loadedOperation.jobReadableId, loadedOperation.description]
+ .filter(Boolean)
+ .join(" · ")
+ : null;
const state = getWorkDisplayState({
activeEventCount: activeWork.length,
@@ -83,6 +123,19 @@ export default function WorkDisplayRoute() {
}
refreshInterval={15_000}
>
+ {loadedLabel || deviceState ? (
+ <div
+ className="flex min-w-0 items-center gap-[1vw] px-[2vw] pt-[1.5vw] text-white/70"
+ style={{ fontSize: "clamp(0.8rem, 1.4vw, 1.6rem)" }}
+ >
+ {loadedLabel ? (
+ <span className="truncate">
+ <Trans>Loaded: {loadedLabel}</Trans>
+ </span>
+ ) : null}
+ {deviceState ? <DeviceStateBadge state={deviceState} /> : null}
+ </div>
+ ) : null}
<ActiveWorkPanel
activeWork={activeWork}
lastEventEndedAt={lastEventEndedAt}
diff --git a/apps/mes/app/routes/x+/event.tsx b/apps/mes/app/routes/x+/event.tsx
index e30115e4d6..fe945ee86f 100644
--- a/apps/mes/app/routes/x+/event.tsx
+++ b/apps/mes/app/routes/x+/event.tsx
@@ -7,15 +7,17 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { serverFns } from "@carbon/server-functions";
import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { getDatabaseClient } from "~/services/database.server";
import { productionEventValidator } from "~/services/models";
import {
+ endMachineProductionEvent,
endProductionEvent,
getOperationEligibility,
+ postEndedProductionEvents,
+ startMachineProductionEvent,
startProductionEvent
} from "~/services/operations.service";
import { OUTSIDE_PROCESSING_REFUSAL } from "~/utils/operationView";
@@ -42,7 +44,38 @@ export async function action({ request }: ActionFunctionArgs) {
...d
} = validation.data;
+ // A Machine press writes over Kysely, which skips RLS, so the permission RLS
+ // would check is checked here, before anything is written. A refusal stays
+ // on the page as a message.
+ const permitted = async (
+ permission: { create: "production" } | { update: "production" }
+ ) => {
+ try {
+ await requirePermissions(request, permission);
+ return true;
+ } catch (thrown) {
+ if (thrown instanceof Response) return false;
+ throw thrown;
+ }
+ };
+ const refused = async (message: string) =>
+ data({}, await flash(request, error(null, message)));
+
+ // A machine has one machine time. A Machine press ends every open Machine
+ // event on the work center, from any operator or the sensor, in the same
+ // transaction as the write it belongs to: the new event on a Start, the
+ // end of this event on an End. The routes post every event it ended.
+ const db = getDatabaseClient();
+ const postEnded = (ids: string[]) =>
+ postEndedProductionEvents(client, db, { companyId, userId, ids });
+
if (productionAction === "Start") {
+ const machineWorkCenterId =
+ d.type === "Machine" ? d.workCenterId : undefined;
+ if (machineWorkCenterId && !(await permitted({ create: "production" }))) {
+ return refused("You do not have permission to start machine time");
+ }
+
// Ability gate: the shop-floor Start button posts here, so the
// qualification check must run on this path (not only in the
// start.$operationId loader)
@@ -54,10 +87,7 @@ export async function action({ request }: ActionFunctionArgs) {
.eq("companyId", companyId)
.maybeSingle();
if (operation.data?.operationType === "Outside Processing") {
- return data(
- {},
- await flash(request, error(null, OUTSIDE_PROCESSING_REFUSAL))
- );
+ return refused(OUTSIDE_PROCESSING_REFUSAL);
}
const eligibility = await getOperationEligibility(serviceRole, {
@@ -66,15 +96,8 @@ export async function action({ request }: ActionFunctionArgs) {
companyId
});
if (!eligibility.eligible) {
- return data(
- {},
- await flash(
- request,
- error(
- null,
- eligibility.reason ?? "Not qualified to start this operation"
- )
- )
+ return refused(
+ eligibility.reason ?? "Not qualified to start this operation"
);
}
@@ -87,42 +110,42 @@ export async function action({ request }: ActionFunctionArgs) {
.select("id")
.eq("jobOperationId", d.jobOperationId)
.eq("employeeId", userId)
+ .eq("companyId", companyId)
.is("endTime", null)
.neq("type", d.type);
if (openOthers.data && openOthers.data.length > 0) {
const endTime = datetime.timestamp();
+ const ended: string[] = [];
for (const ev of openOthers.data) {
- const ended = await endProductionEvent(client, {
+ const result = await endProductionEvent(client, {
id: ev.id,
endTime,
- employeeId: userId
+ employeeId: userId,
+ companyId
});
- if (ended.data && ended.data.length > 0) {
- await serverFns
- .system({
- db: getDatabaseClient(),
- companyId,
- userId
- })
- .invoke("post-production-event", {
- productionEventId: ended.data[0].id
- });
- }
+ const row = result.data?.[0];
+ if (row) ended.push(row.id);
}
+ await postEnded(ended);
}
}
- const startEvent = await startProductionEvent(
- client,
- {
- ...d,
- startTime: datetime.timestamp(),
- employeeId: userId,
- companyId,
- createdBy: userId
- },
- trackedEntityId,
- unitIndex
- );
+
+ const event = {
+ ...d,
+ startTime: datetime.timestamp(),
+ employeeId: userId,
+ companyId,
+ createdBy: userId
+ };
+ const startEvent = machineWorkCenterId
+ ? await startMachineProductionEvent(
+ db,
+ client,
+ { ...event, workCenterId: machineWorkCenterId },
+ trackedEntityId,
+ unitIndex
+ )
+ : await startProductionEvent(client, event, trackedEntityId, unitIndex);
if (startEvent.error) {
return data(
@@ -130,45 +153,90 @@ export async function action({ request }: ActionFunctionArgs) {
await flash(request, error(startEvent.error, "Failed to start event"))
);
}
+ if (startEvent.data && "endedEventIds" in startEvent.data) {
+ await postEnded(startEvent.data.endedEventIds);
+ }
return data(
startEvent.data,
await flash(request, success(`Started ${d.type.toLowerCase()} operation`))
);
- } else {
- if (!id) {
- return data({}, await flash(request, error("No event id provided")));
- }
- const endEvent = await endProductionEvent(client, {
- id,
- endTime: datetime.timestamp(),
- employeeId: userId
- });
- if (endEvent.error) {
- return data(
- {},
- await flash(request, error(endEvent.error, "Failed to end event"))
- );
+ }
+
+ if (!id) {
+ return data({}, await flash(request, error("No event id provided")));
+ }
+ // End on the event's own work center and type, not the form's.
+ const event = await client
+ .from("productionEvent")
+ .select("workCenterId, type, endTime")
+ .eq("id", id)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ if (event.error || !event.data) {
+ return data(
+ {},
+ await flash(request, error(event.error, "Failed to end event"))
+ );
+ }
+ const typeLabel = (event.data.type ?? d.type).toLowerCase();
+ // A repeated End must not end it again, nor end a newer event through the
+ // press.
+ if (event.data.endTime) return refused("This event has already ended");
+
+ if (event.data.type === "Machine" && event.data.workCenterId) {
+ if (!(await permitted({ update: "production" }))) {
+ return refused("You do not have permission to end machine time");
}
- if (endEvent.data && endEvent.data.length > 0) {
- // Batch timers post cost at batch completion, when the aggregate event is
- // sliced per member (batch-operations). Posting it here too would
- // double-book the cost, so skip post-production-event for a batch event.
- if (!endEvent.data[0].jobOperationBatchId) {
- await serverFns
- .system({
- db: getDatabaseClient(),
- companyId,
- userId
- })
- .invoke("post-production-event", {
- productionEventId: endEvent.data[0].id
- });
- }
+ let press: Awaited<ReturnType<typeof endMachineProductionEvent>>;
+ try {
+ press = await endMachineProductionEvent(db, {
+ id,
+ workCenterId: event.data.workCenterId,
+ companyId,
+ userId
+ });
+ } catch (err) {
+ return data({}, await flash(request, error(err, "Failed to end event")));
}
+ if (!press) return refused("This event has already ended");
+ // The press ended this event with every other one on the work center.
+ await postEnded(press.endedEventIds);
+ const ended = await client
+ .from("productionEvent")
+ .select("*")
+ .eq("id", id)
+ .eq("companyId", companyId);
return data(
- endEvent.data,
- await flash(request, success(`Ended ${d.type.toLowerCase()} operation`))
+ ended.data,
+ await flash(request, success(`Ended ${typeLabel} operation`))
);
}
+
+ const endEvent = await endProductionEvent(client, {
+ id,
+ endTime: datetime.timestamp(),
+ employeeId: userId,
+ companyId
+ });
+ if (endEvent.error) {
+ return data(
+ {},
+ await flash(request, error(endEvent.error, "Failed to end event"))
+ );
+ }
+ const ended = endEvent.data?.[0];
+ if (!ended) {
+ // Open when read, but the update matched nothing: another End won the
+ // race, or RLS refused the update.
+ return refused("This event has already ended, or you cannot end it");
+ }
+ // Batch timers post cost at batch completion, when the aggregate event is
+ // sliced per member (batch-operations). Posting it here too would
+ // double-book the cost, so postEnded skips a batch event.
+ await postEnded([ended.id]);
+ return data(
+ endEvent.data,
+ await flash(request, success(`Ended ${typeLabel} operation`))
+ );
}
diff --git a/apps/mes/app/routes/x+/start.$operationId.tsx b/apps/mes/app/routes/x+/start.$operationId.tsx
index 00c5b74117..715e3843e8 100644
--- a/apps/mes/app/routes/x+/start.$operationId.tsx
+++ b/apps/mes/app/routes/x+/start.$operationId.tsx
@@ -12,11 +12,14 @@ import { evaluateLinesForSurface, isBlocked } from "@carbon/ee/rules.server";
import { getLogger } from "@carbon/logger";
import { datetime, redirect } from "@carbon/utils";
import type { LoaderFunctionArgs } from "react-router";
+import { getDatabaseClient } from "~/services/database.server";
import { getWorkCenterWithBlockingStatus } from "~/services/maintenance.service";
import {
getNextIncompleteSerialEntity,
getOperationEligibility,
getTrackedEntitiesByMakeMethodId,
+ postEndedProductionEvents,
+ startMachineProductionEvent,
startProductionEvent
} from "~/services/operations.service";
import { OUTSIDE_PROCESSING_REFUSAL } from "~/utils/operationView";
@@ -47,6 +50,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
.from("jobOperation")
.select("*")
.eq("id", operationId)
+ .eq("companyId", companyId)
.maybeSingle();
if (jobOperation.error || !jobOperation.data) {
@@ -239,37 +243,42 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
}
- // If type is Machine, cancel all setup and labor production events for this operation
- if (type === "Machine") {
- const currentTime = datetime.timestamp();
-
- await serviceRole
- .from("productionEvent")
- .update({
- endTime: currentTime,
- updatedAt: currentTime,
- updatedBy: userId
- })
- .eq("jobOperationId", operationId)
- .in("type", ["Setup", "Labor"])
- .is("endTime", null);
+ // A machine has one machine time: a Machine start ends every open Machine
+ // event on the work center (from any operator or the sensor) and, with a
+ // device, the open unattributed time, in one transaction with the new
+ // event. That write skips RLS, so its permission is checked first.
+ const machineWorkCenterId =
+ type === "Machine" ? jobOperation.data.workCenterId : null;
+ if (machineWorkCenterId) {
+ await requirePermissions(request, { create: "production" });
}
- const startEvent = await startProductionEvent(
- serviceRole,
- {
- type,
- jobOperationId: operationId,
- workCenterId: jobOperation.data.workCenterId!,
- startTime: datetime.timestamp(),
- employeeId: userId,
- companyId,
- createdBy: userId
- },
- trackedEntityId || undefined,
- undefined,
- "mes_qr"
- );
+ const db = getDatabaseClient();
+ const event = {
+ type,
+ jobOperationId: operationId,
+ workCenterId: jobOperation.data.workCenterId!,
+ startTime: datetime.timestamp(),
+ employeeId: userId,
+ companyId,
+ createdBy: userId
+ };
+ const startEvent = machineWorkCenterId
+ ? await startMachineProductionEvent(
+ db,
+ serviceRole,
+ { ...event, workCenterId: machineWorkCenterId },
+ trackedEntityId || undefined,
+ undefined,
+ "mes_qr"
+ )
+ : await startProductionEvent(
+ serviceRole,
+ event,
+ trackedEntityId || undefined,
+ undefined,
+ "mes_qr"
+ );
if (startEvent.error) {
throw redirect(
@@ -278,5 +287,36 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ // A Machine start ends this operation's Setup and Labor timers, once the
+ // Machine time is running. Every event ended here is posted.
+ const ended =
+ startEvent.data && "endedEventIds" in startEvent.data
+ ? [...startEvent.data.endedEventIds]
+ : [];
+ if (type === "Machine") {
+ const endTime = datetime.timestamp();
+ const setupAndLabor = await serviceRole
+ .from("productionEvent")
+ .update({ endTime, updatedAt: endTime, updatedBy: userId })
+ .eq("jobOperationId", operationId)
+ .eq("companyId", companyId)
+ .in("type", ["Setup", "Labor"])
+ .is("endTime", null)
+ .select("id");
+ if (setupAndLabor.error) {
+ logger.error("Failed to end Setup and Labor at a Machine start", {
+ companyId,
+ operationId,
+ error: setupAndLabor.error
+ });
+ }
+ for (const row of setupAndLabor.data ?? []) ended.push(row.id);
+ }
+ await postEndedProductionEvents(serviceRole, db, {
+ companyId,
+ userId,
+ ids: ended
+ });
+
throw redirect(path.to.operation(operationId));
}
diff --git a/apps/mes/app/services/display.service.ts b/apps/mes/app/services/display.service.ts
index 9d474de531..12540f339c 100644
--- a/apps/mes/app/services/display.service.ts
+++ b/apps/mes/app/services/display.service.ts
@@ -34,6 +34,8 @@ export type DisplayWorkCenter = {
isBlocked: boolean;
blockingDispatchId: string | null;
blockingDispatchReadableId: string | null;
+ /** The operation loaded on this work center (the last timer started there), if any. */
+ loadedJobOperationId: string | null;
};
/**
@@ -48,7 +50,7 @@ export async function getDisplayWorkCenter(
const { data, error } = await client
.from("workCentersWithBlockingStatus")
.select(
- "id, name, locationId, locationName, isBlocked, blockingDispatchId, blockingDispatchReadableId"
+ "id, name, locationId, locationName, isBlocked, blockingDispatchId, blockingDispatchReadableId, loadedJobOperationId"
)
.eq("id", args.workCenterId)
.eq("companyId", args.companyId)
@@ -63,10 +65,66 @@ export async function getDisplayWorkCenter(
locationName: data.locationName ?? null,
isBlocked: data.isBlocked ?? false,
blockingDispatchId: data.blockingDispatchId ?? null,
- blockingDispatchReadableId: data.blockingDispatchReadableId ?? null
+ blockingDispatchReadableId: data.blockingDispatchReadableId ?? null,
+ loadedJobOperationId: data.loadedJobOperationId ?? null
};
}
+/** The operation loaded onto a work center: its job and description. */
+export async function getDisplayLoadedOperation(
+ client: SupabaseClient<Database>,
+ args: { jobOperationId: string; companyId: string }
+) {
+ const { data } = await client
+ .from("jobOperation")
+ .select("id, description, job:jobId(jobId)")
+ .eq("id", args.jobOperationId)
+ .eq("companyId", args.companyId)
+ .maybeSingle();
+
+ if (!data) return null;
+
+ const job = data.job as { jobId: string | null } | null;
+ return {
+ id: data.id,
+ description: data.description ?? null,
+ jobReadableId: job?.jobId ?? null
+ };
+}
+
+/** A device state older than this is hidden: the sync may have stopped. */
+const DEVICE_STATE_MAX_AGE_MS = 10 * 60 * 1000;
+
+/**
+ * The live state of the OEE device mapped to a work center, or null when there
+ * is no device, its last sync failed, it has never synced, or it last synced
+ * more than 10 minutes before `now`. A wall display must not show "Running"
+ * from a sync that stopped hours ago.
+ */
+export async function getDisplayDeviceState(
+ client: SupabaseClient<Database>,
+ args: { workCenterId: string; companyId: string; now: string }
+): Promise<Database["public"]["Enums"]["machineState"] | null> {
+ const { data } = await client
+ .from("workCenterDevice")
+ .select("currentState, lastSyncedAt, lastSyncError")
+ .eq("workCenterId", args.workCenterId)
+ .eq("companyId", args.companyId)
+ .maybeSingle();
+
+ if (!data || data.lastSyncError || !data.lastSyncedAt) return null;
+
+ // Comparing two absolute instants: the date rule's narrow exception.
+ if (
+ Date.parse(args.now) - Date.parse(data.lastSyncedAt) >
+ DEVICE_STATE_MAX_AGE_MS
+ ) {
+ return null;
+ }
+
+ return data.currentState;
+}
+
export async function getWorkCentersForDisplayPicker(
client: SupabaseClient<Database>,
args: { companyId: string; locationId: string }
diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.ts
index 7916d18fc1..19a1df597a 100644
--- a/apps/mes/app/services/operations.service.ts
+++ b/apps/mes/app/services/operations.service.ts
@@ -5,6 +5,11 @@
import type { Database, Json } from "@carbon/database";
import { activeJobStatuses, getCompanyTimeZone } from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { toJson } from "@carbon/database/json";
+import {
+ lockMachinePress,
+ recordManualMachinePress
+} from "@carbon/database/machine-time";
import { storage } from "@carbon/files";
import type { WorkSource } from "@carbon/lib/telemetry";
import { trackWorkEvent } from "@carbon/lib/telemetry";
@@ -2467,15 +2472,102 @@ export async function endProductionEvent(
id: string;
endTime: string;
employeeId: string;
+ companyId: string;
}
) {
+ // Only an open event ends: a repeated End must not move its end time.
return client
.from("productionEvent")
.update({ endTime: data.endTime, updatedBy: data.employeeId })
.eq("id", data.id)
+ .eq("companyId", data.companyId)
+ .is("endTime", null)
.select("*");
}
+/** A Machine press refused to end an event (already ended, or started later). */
+class MachineEventNotEnded extends Error {}
+
+/**
+ * Ends an operator's open Machine event with a press: the press ends every
+ * open Machine event on the work center, this one included, in one
+ * transaction. Null when the event is no longer open, or the press could not
+ * end it (it starts after the press), and then nothing was ended. Skips RLS:
+ * the caller checks that the user may update production events first.
+ */
+export async function endMachineProductionEvent(
+ db: Kysely<KyselyDatabase>,
+ args: { id: string; workCenterId: string; companyId: string; userId: string }
+) {
+ try {
+ return await db.transaction().execute(async (trx) => {
+ await lockMachinePress(trx, args);
+ const open = await trx
+ .selectFrom("productionEvent")
+ .select("id")
+ .where("id", "=", args.id)
+ .where("companyId", "=", args.companyId)
+ .where("endTime", "is", null)
+ .forUpdate()
+ .executeTakeFirst();
+ if (!open) throw new MachineEventNotEnded();
+ const press = await recordManualMachinePress(trx, args);
+ if (!press.endedEventIds.includes(args.id)) {
+ throw new MachineEventNotEnded();
+ }
+ return press;
+ });
+ } catch (error) {
+ if (error instanceof MachineEventNotEnded) return null;
+ throw error;
+ }
+}
+
+/**
+ * Posts the events a press ended (machine cost to WIP), as an operator's own
+ * End posts theirs. Batch timers post at batch completion, so they are left.
+ * A failure is logged, never thrown: the operation-finish catch-up posts what
+ * is still unposted.
+ */
+export async function postEndedProductionEvents(
+ client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
+ args: { companyId: string; userId: string; ids: string[] }
+) {
+ if (args.ids.length === 0) return;
+ const events = await client
+ .from("productionEvent")
+ .select("id")
+ .in("id", args.ids)
+ .eq("companyId", args.companyId)
+ .is("jobOperationBatchId", null);
+ if (events.error) {
+ log.error("Failed to read the events a press ended", {
+ companyId: args.companyId,
+ error: events.error
+ });
+ return;
+ }
+ const functions = serverFns.system({
+ db,
+ companyId: args.companyId,
+ userId: args.userId
+ });
+ for (const event of events.data ?? []) {
+ try {
+ await functions.invoke("post-production-event", {
+ productionEventId: event.id
+ });
+ } catch (error) {
+ log.error("Failed to post an event a press ended", {
+ companyId: args.companyId,
+ productionEventId: event.id,
+ error
+ });
+ }
+ }
+}
+
export async function endProductionEventsForJobOperation(
client: SupabaseClient<Database>,
args: {
@@ -2775,6 +2867,115 @@ export async function startProductionEvent(
return eventInsert;
}
+/**
+ * A Machine start on a work center: the press, which ends the work center's
+ * open machine time, the new event and its tracked activity commit in one
+ * transaction, at the press time read under the press locks. If any of it
+ * fails, nothing was ended. Skips RLS: the caller checks that the user may
+ * create production events first.
+ */
+export async function startMachineProductionEvent(
+ db: Kysely<KyselyDatabase>,
+ client: SupabaseClient<Database>,
+ data: Parameters<typeof startProductionEvent>[1] & { workCenterId: string },
+ trackedEntityId: string | undefined,
+ unitIndex?: number,
+ source: WorkSource = "mes"
+): Promise<{
+ data: { id: string; endedEventIds: string[] } | null;
+ error: unknown;
+}> {
+ const refs = await verifyProductionEventRefs(client, {
+ companyId: data.companyId,
+ jobOperationId: data.jobOperationId,
+ workCenterId: data.workCenterId,
+ jobOperationBatchId: data.jobOperationBatchId,
+ trackedEntityId
+ });
+ if (!refs.ok) return notFoundResponse(refs.message);
+
+ // The tracked entity is the separate argument; productionEvent has no column for it.
+ const { trackedEntityId: _trackedEntityId, ...event } = data;
+
+ try {
+ const started = await db.transaction().execute(async (trx) => {
+ const press = await recordManualMachinePress(trx, {
+ workCenterId: data.workCenterId,
+ companyId: data.companyId,
+ userId: data.createdBy
+ });
+ const inserted = await trx
+ .insertInto("productionEvent")
+ .values({ ...event, startTime: press.pressedAt })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+
+ if (trackedEntityId) {
+ const operation = await trx
+ .selectFrom("jobOperation")
+ .select(["description", "jobId"])
+ .where("id", "=", data.jobOperationId)
+ .where("companyId", "=", data.companyId)
+ .executeTakeFirstOrThrow();
+ const activityId = nanoid();
+ await trx
+ .insertInto("trackedActivity")
+ .values({
+ id: activityId,
+ type: `${operation.description} (${data.type})`,
+ sourceDocument: "Production Event",
+ sourceDocumentId: inserted.id,
+ attributes: toJson({
+ Job: operation.jobId,
+ "Job Operation": data.jobOperationId,
+ "Production Event": inserted.id,
+ "Work Center": data.workCenterId,
+ Employee: data.employeeId,
+ ...(typeof unitIndex === "number" ? { Unit: unitIndex } : {})
+ }),
+ companyId: data.companyId,
+ createdBy: data.createdBy
+ })
+ .execute();
+ await trx
+ .insertInto("trackedActivityOutput")
+ .values({
+ trackedActivityId: activityId,
+ trackedEntityId,
+ quantity: 1,
+ companyId: data.companyId,
+ createdBy: data.createdBy
+ })
+ .execute();
+ }
+
+ return { id: inserted.id, endedEventIds: press.endedEventIds };
+ });
+
+ await autoStartJobAndOperation(client, {
+ jobOperationId: data.jobOperationId,
+ userId: data.createdBy,
+ companyId: data.companyId
+ });
+ trackWorkEvent("job_operation_started", {
+ companyId: data.companyId,
+ userId: data.createdBy,
+ productionEventId: started.id,
+ jobOperationId: data.jobOperationId,
+ eventType: data.type,
+ source
+ });
+ return { data: started, error: null };
+ } catch (error) {
+ log.error("Failed to start the Machine event", {
+ companyId: data.companyId,
+ workCenterId: data.workCenterId,
+ error
+ });
+ return { data: null, error };
+ }
+}
+
type JobMethod = {
id: string;
methodMaterialId: string;
diff --git a/docs/content/docs/integrations/index.mdx b/docs/content/docs/integrations/index.mdx
index 28e4e3e6e7..87cb4b848e 100644
--- a/docs/content/docs/integrations/index.mdx
+++ b/docs/content/docs/integrations/index.mdx
@@ -45,6 +45,9 @@ Available integrations depend on deployment configuration. **Xero**, **Jira**, a
<Card title="CAD" href="/docs/integrations/cad">
Sync CAD data from Onshape.
</Card>
+ <Card title="Machine monitoring" href="/docs/integrations/oee">
+ Record machine time from Sense machine sensors.
+ </Card>
<Card title="Estimating & quoting" href="/docs/integrations/estimating">
Pull quotes and BOMs from Paperless Parts.
</Card>
diff --git a/docs/content/docs/integrations/meta.json b/docs/content/docs/integrations/meta.json
index 0b5c624473..b330b1d899 100644
--- a/docs/content/docs/integrations/meta.json
+++ b/docs/content/docs/integrations/meta.json
@@ -5,6 +5,7 @@
"accounting",
"project-management",
"cad",
+ "oee",
"estimating",
"email",
"assistant"
diff --git a/docs/content/docs/integrations/oee.mdx b/docs/content/docs/integrations/oee.mdx
new file mode 100644
index 0000000000..dfc85eb8ac
--- /dev/null
+++ b/docs/content/docs/integrations/oee.mdx
@@ -0,0 +1,156 @@
+---
+title: Machine monitoring
+plan: Business
+description: Record machine time on job operations from Sense machine sensors, and assign the run time that no operation claims.
+---
+
+An **OEE provider** is a machine-monitoring service that reports when each machine runs. Carbon reads those reports and records machine time on the operation loaded on the <Term>work center</Term>, so an operator does not have to start a Machine timer for every run. Carbon supports **Sense**, which clips a current sensor onto each machine.
+
+Machine monitoring requires Enterprise Edition or the Carbon Cloud Business plan.
+
+## What an OEE provider does
+
+Each provider device maps to one work center. Sense calls a device a **station**. Sense has no webhooks, so Carbon polls it every 2 minutes and stores each state change it reads. Carbon maps the four Sense statuses to four machine states:
+
+| Sense status | Carbon machine state |
+| --- | --- |
+| Active | Running |
+| Idle | Idle |
+| Alert | Down |
+| Offline | Offline |
+
+A **Running** state opens machine time. Any other state ends it.
+
+<Callout type="note" title="One device per work center, across every provider">
+You can install several OEE providers at once, for a shop that mixes vendors. A work center still holds at most one device in total. A pool work center that stands for three machines must become three work centers before you map it.
+</Callout>
+
+## Install Sense
+
+You need the `settings` update permission and a company API key from Sense.
+
+<Steps>
+ <Step>
+ ### Open Sense
+
+ Open **Settings → Integrations** and select **Sense**.
+ </Step>
+ <Step>
+ ### Enter the connection fields
+
+ Paste the API key and set the fields below.
+ </Step>
+ <Step>
+ ### Install
+
+ Select **Install**. Then open **Sense** again. The drawer now has a **Devices** tab.
+ </Step>
+</Steps>
+
+<FieldTable>
+ <Field name="API key" required>A company API key from Sense. It gives Carbon read access to your sites and stations. Stored as a secret.</Field>
+ <Field name="Environment" required>**Production** (`bifrost.sensemfg.com`) or **Staging**, which is for testing only. Staging uses plain HTTP, so Carbon refuses it in production.</Field>
+ <Field name="Minimum state (seconds)" required>Carbon ignores a run or a stop shorter than this, so a brief blip does not split machine time. The default is 60.</Field>
+</FieldTable>
+
+## Map devices to work centers
+
+The **Devices** tab lists every Sense station by site, with its manufacturer and model. A station that has not been calibrated says **"Not calibrated"**. Select a work center for a station and Carbon saves it at once. To unmap a station, clear its work center. The dot before each station shows its machine state; hover it to see when it last synced.
+
+Carbon records a station's state changes from the moment you save the mapping. Carbon never charges time before the mapping. If the machine already runs when you map it, its time starts at the mapping. Mapping a station to a different work center starts again from the new mapping.
+
+After each sync, the row shows the machine state, when it last synced, and the last sync error in red. A warning icon appears when the Sense site's time zone differs from the time zone of the work center's location (or the company's, when the location has none). A station's work center list leaves out the work centers that another station already holds.
+
+When you uninstall Sense (**Settings → Integrations**, then **Uninstall** on its card), Carbon ends the machine time that its stations have open at that moment. The mappings stay, so after you install Sense again each station continues from where it stopped.
+
+<Screenshot label="Sense integration drawer on the Devices tab, with stations mapped to work centers and their machine state dots" />
+
+## How machine time reaches a job
+
+### The loaded operation
+
+Each work center has a [loaded operation](/docs/reference/work-centers#loaded-operation): the operation of the latest <Term>production event</Term> started there. A Setup, Labor or Machine start loads it, so operators change nothing in how they work. The operation stays loaded until it is **"Done"** or **"Canceled"**, is deleted, or moves to another work center.
+
+Carbon keeps the history of the loads on each work center. A run that the station reports late still goes to the operation that was loaded when the machine ran.
+
+### Running time
+
+When a station reports Running, Carbon opens a Machine production event on the loaded operation at the time of the change. When the station reports Idle, Down or Offline, Carbon ends the event. A sensor event has no employee.
+
+If an operator starts Setup or Labor on operation B while the machine runs on operation A, B becomes the loaded operation. The sensor's machine time moves to B from that moment: the event on A ends there, and a new event on B starts. If the operator starts a Machine timer on B, the press ends the running event on A instead (see below). An operator's own Machine timer stays on its operation when another operation loads.
+
+<Callout type="note" title="Sensor time posts when the operation finishes">
+Carbon posts a sensor event to the general ledger when its operation finishes or the job completes. If an operator's Machine press ends the event first, it posts at the press. Until it posts, you can correct the event in the job's **Production Events** view.
+</Callout>
+
+### One machine time per work center
+
+A machine has one machine time, and operators share it. On any work center, a **"Start"** or **"Pause"** press with **"Machine"** selected ends every open Machine timer on that work center at the press, whoever started it. A Start then opens the new one.
+
+Carbon posts every Machine timer that a press ends to the general ledger at the press. A batch timer is the exception: it posts when its batch completes.
+
+On a work center with a mapped device, the press decides the operator's machine time, and the station decides whether the machine ran. A late poll never undoes a press. For example, the machine runs and the operator selects **"Pause"** at 10:03. Machine time on the operation stops at 10:03. If the machine runs on until 10:20, the time from 10:03 to 10:20 goes to unattributed time for a supervisor to review. A machine that stops within the **Minimum state** of the Pause (60 seconds by default) adds nothing.
+
+A station can report a start late. For example, the machine starts at 10:00, the operator selects **"Start"** at 10:03, and the station reports the 10:00 start after the press. The operator's machine time starts at 10:03. The time from 10:00 to 10:03 goes to the operation that was loaded at 10:00, the same result as a report on time. If nothing was loaded then, it goes to unattributed time. Carbon never records the same minutes twice.
+
+A station can also report a stop late. If the stop falls inside unattributed time that a press already ended, Carbon shortens that unattributed time to the minutes the machine ran. Carbon never shortens machine time on an operation.
+
+The work center display shows the station's state. It hides the state when the station has a sync error or has not synced for 10 minutes.
+
+### Unattributed time
+
+Carbon cannot charge run time to an operation in four cases. Then the time goes to **Production → Unattributed Time**, which appears once an OEE provider is installed:
+
+- No operation is loaded on the work center at that moment. This includes the part of a run before an operation was loaded, and a run that the station reported only after an operator's Machine press when nothing was loaded then.
+- The work center is blocked by [maintenance](/docs/reference/maintenance): a dispatch with an OEE impact of **"Down"** from the moment it is reported until it is completed or cancelled, or one with **"Planned"** from its start while it is In Progress. A Machine event already running when maintenance starts stops there, and the rest of the run goes to unattributed time. When the maintenance ends while the machine still runs, the time goes back to the loaded operation.
+- The loaded operation is **"Done"** or **"Canceled"**, or its job is Completed, Closed or Cancelled. When an operation finishes while the machine keeps running, the rest of the run goes there.
+- The machine runs on after an operator's Machine press in the same run, such as a **"Pause"**. The time until it stops goes there.
+
+Carbon removes unattributed time shorter than the **Minimum state**.
+
+The list holds only time that still needs an answer. Each row shows the work center, location, start, end, duration and state (**"Running"** or **"Stopped"**), in the time zone of the work center's location. Filter the list by work center, location, start date, end date or state. The dates follow the time zone of each work center's location, the same time zone the list shows.
+
+Select **Review**, or open a row, to work through the rows the list shows, one at a time. A row whose machine still runs is outside the review until the machine stops:
+
+- **Which operation was this?** shows a card for each operation that ran on the same work center on the days the time covers, best match first. An operation that ran during the time says **"Ran at the time"**. Select a card, or press its number key, to assign the time to it.
+- **Another job or operation** searches the open operations at the work center's location, including operations with no work center.
+- **Not job time** dismisses the time, for example warm-up, prove-out or maintenance.
+- **Skip**, or <kbd>J</kbd> and <kbd>K</kbd>, move to the next and previous row.
+
+Each answer takes you to the next row. Closing the review returns you to the list with your filters. Assigning creates a Machine production event for the row's interval and removes the row. Dismissing removes the row. A row that nobody answers is removed 30 days after the machine stopped.
+
+You cannot answer a row while the machine still runs. You cannot assign time to a Done or Canceled operation, or to a locked job. Answering needs the `production` update permission.
+
+<Screenshot label="Unattributed Time drawer with operation cards for the work center's day, the search card, and Not job time and Skip" />
+
+<AgentContext>
+Tables: `workCenterDevice` (one row per mapped device; `UNIQUE(workCenterId, companyId)` across every OEE integration; holds `currentState`, `currentStateAt`, `appliedThrough`, `lastEventAt`, `lastManualChangeAt`, `unplannedPressAt`, `lastSyncedAt`, `lastSyncError`), `machineStateChange` (every state change read, unique per device and provider event id), `unattributedMachineTime` (a review queue: a row is deleted when it is assigned or dismissed, and 30 days after its `endTime`). `workCenterLoad` holds the history of loads (one row per load, `loadedAt` and `unloadedAt`); the row with no `unloadedAt` is the loaded operation. `workCenterDevice.unplannedPressAt` holds the earliest Machine press since the last sync.
+
+Exact errors and causes:
+
+- Devices tab shows a red provider error and no stations: the API key is wrong, the integration is inactive ("Integration is not active"), or the key is empty ("No API key").
+- "Failed to save device mapping" with `{work center} already has {device} from {integration}`: the work center already holds a device. Unmap that device first.
+- A device row shows `Unknown Sense status: {status}`: Sense sent a status outside Active, Idle, Alert and Offline. The device keeps its cursor and retries on the next sync.
+- A device row shows "Station has no site": the Sense station is not in a site, so Carbon cannot read its events.
+- "The machine is still running" (assign) or "Machine time not found, or the machine is still running" (dismiss): the unattributed row has no end time yet, or another user already answered it. Wait for the machine to stop.
+- "This event has already ended" in the MES: the timer was already ended, for example by another operator's Machine press on the same work center.
+- "You do not have permission to start machine time" / "You do not have permission to end machine time" in the MES: the user lacks the `production` create or update permission.
+- "That machine time is no longer open": another user answered the row, or it aged out after 30 days.
+- "The operation is Done" / "The operation is Canceled": pick an open operation.
+- "Cannot modify a locked job. Reopen it first.": the operation's job is Completed, Closed or Cancelled.
+- Unattributed time appears after a Pause press while the machine runs: expected. The machine ran, and a supervisor decides whose time it was.
+</AgentContext>
+
+## Related
+
+<Cards>
+ <Card title="Work centers" href="/docs/reference/work-centers">
+ Where operations run, and the loaded operation that receives machine time.
+ </Card>
+ <Card title="MES" href="/docs/reference/mes">
+ The shop-floor Machine timer and the work center display.
+ </Card>
+ <Card title="Maintenance" href="/docs/reference/maintenance">
+ Dispatches that block a work center and send its run time to the unattributed list.
+ </Card>
+</Cards>
diff --git a/docs/content/docs/reference/work-centers.mdx b/docs/content/docs/reference/work-centers.mdx
index 2a258e93ee..fee34564b3 100644
--- a/docs/content/docs/reference/work-centers.mdx
+++ b/docs/content/docs/reference/work-centers.mdx
@@ -43,6 +43,14 @@ A work center is a **finite resource**: the [scheduler](/docs/reference/scheduli
An open maintenance task that takes the work center offline subtracts its downtime from those hours (lights-out machines included), so the scheduler routes work around a machine that's down rather than booking it.
+## Loaded operation
+
+Each work center has a **loaded operation**: the operation of the latest <Term>production event</Term> started there. A Setup, Labor or Machine start loads it. An event that you enter with an end time does not, and neither does an event that starts before the work center's latest load or unload. The operation stays loaded until it is **"Done"** or **"Canceled"**, is deleted, or moves to another work center. A **"Pause"** in the MES does not unload it.
+
+Carbon keeps the history of the loads on each work center for at least 7 days after each unload.
+
+The MES work center display shows the loaded operation as **"Loaded:"** with the job and the operation. When a [machine monitoring](/docs/integrations/oee) device is mapped to the work center, Carbon records the machine's run time on the operation that was loaded when the machine ran.
+
## Related
<Cards>
@@ -52,4 +60,7 @@ An open maintenance task that takes the work center offline subtracts its downti
<Card title="Manufacturing accounting" href="/guides/job-costing">
How a work center's rates become a job's labor and machine cost.
</Card>
+ <Card title="Machine monitoring" href="/docs/integrations/oee">
+ Machine time from Sense sensors, recorded on the loaded operation.
+ </Card>
</Cards>
diff --git a/packages/checks/src/conformance/no-integration-id-branching.ts b/packages/checks/src/conformance/no-integration-id-branching.ts
index de7f758a9c..c0c32d6569 100644
--- a/packages/checks/src/conformance/no-integration-id-branching.ts
+++ b/packages/checks/src/conformance/no-integration-id-branching.ts
@@ -16,6 +16,7 @@ const INTEGRATION_IDS = [
"quickbooks",
"rillet",
"ramp",
+ "sense",
"slack",
"jira",
"linear",
@@ -47,7 +48,7 @@ const EXCLUDED = [
/^packages\/ee\/src\/sync\//,
/^apps\/erp\/app\/modules\/settings\/integration-errors\.ts$/,
// A provider's own directory may name itself.
- /^packages\/ee\/src\/(xero|quickbooks|rillet|ramp|slack|jira|linear|onshape|paperless-parts|email|sage|stripe-connect)\//
+ /^packages\/ee\/src\/(xero|quickbooks|rillet|ramp|slack|jira|linear|onshape|paperless-parts|email|sage|stripe-connect|sense)\//
];
export const noIntegrationIdBranching: ConformanceCheck = {
diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.md
index 5841ddd3e8..282176b6eb 100644
--- a/packages/database/AGENTS.md
+++ b/packages/database/AGENTS.md
@@ -82,6 +82,7 @@ pnpm --filter @carbon/database authz migration <name> # ship unshipped rules/h
| `./supersession-pick` | The supersession rules shared by MRP, get-method and picking (`buildSupersessionRedirectMap`, `buildConsumeFirstHops`, `settleConsumeFirstLine`, `resolveMadeLinePull`, `consumableInWholeAssemblies`, …) |
| `./supplier-part-price` | Supplier part prices are stored as quoted (per purchase unit, in the part's `currencyCode`); `convertUnitPrice` puts one on a purchase document in its currency, `buildSupplierPriceMap` turns them into base per-inventory-unit costing breaks. Shared by the ERP, `methods.ts` and the server functions so every reader converts the same way |
| `./picked-consumption` | Consumption follows what was picked (`linesideCredit`, `getPickedBudgets`, `allocateAcrossBudgets`, …) — the one definition of usable lineside stock shared by the pick-list generator and the `issue` backflush |
+| `./machine-time` | Every function takes a Kysely transaction (`KyselyTx`). The locks and writes that end machine time, shared by the OEE sync, the MES Machine button, the device mapping writes and the Sense uninstall hook: `lockWorkCenterDevice` (`FOR UPDATE` on the work center's `workCenterDevice` row), `lockMachinePress` (that lock, then a transaction advisory lock per work center — the one lock order every writer takes), `recordManualMachinePress` (a Machine Start/Pause: takes the press time under the locks unless given, ends every open Machine event on the work center at it, and on a mapped work center ends the open unattributed time and sets `lastManualChangeAt` via `GREATEST` and `unplannedPressAt` via `LEAST`; returns `{ mapped, endedEventIds, pressedAt }`), `endSensorMachineTime` (ends the `system` Machine events and the open unattributed time when a device leaves a work center). Pinned by `machine-time.test.ts` (needs `SUPABASE_DB_URL`). See `.claude/rules/oee-provider.md` |
| `./posting` | `buildPaymentJournal` / `buildMemoJournal` (`src/build-payment-journal.ts`, `src/build-memo-journal.ts`) for the `post-payment` / `post-memo` server functions and the dataset tiers |
| `./precision` / `./accounting-currency` / `./accounting-posting` / `./sales-posting-amounts` / `./ledger` | The pure numeric-precision API, FX conversion, journal role vocabulary, sales posting amounts, and ledger helpers (`AccountType`, `AccountClass`, `isAccountClass`, `credit`, `debit`, `accountTypeFromClass`, `debitSigned` — the debit-signed value of a natural-signed amount on a class, and back; `toStoredAmount` — the natural-signed amount of a debit or a credit). They live here, not in `@carbon/utils`, because the posting builders need them and this package cannot import `@carbon/utils` (turbo cycle); `@carbon/utils` re-exports them, so app code imports them from there. Keep them free of imports outside each other |
| `./run-journals` | Client-safe, pure. The one construction of the period-run and scrap journals: `buildDepreciationJournals`, `buildDeferredTaxJournals` (with `deferredTaxSettings` and `DEFERRED_TAX_MIN_AMOUNT`), `buildDisposalJournal`, `buildRecognitionJournals` (with `recognitionAccountWithoutClass`; its `sources.leases` / `sources.leaseAssets` are required, and a lessee row whose lease or asset is not in them throws). Lines carry dimension values by entity type; the caller writes the journal, its period and status, line references and dimension ids. Used by the ERP's `postDepreciationRun` / `postDisposal` / `postRevenueRecognitionRun` (`accounting.server.ts`) and the enable's legacy backfill (`activate-accounting/legacy/runs.ts`), pinned by `run-journals.test.ts` |
diff --git a/packages/database/package.json b/packages/database/package.json
index 1d3864b824..0897f076fb 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -44,6 +44,7 @@
"./posting": "./src/posting.ts",
"./datasets": "./src/datasets/index.ts",
"./event": "./src/event.ts",
+ "./machine-time": "./src/machine-time.ts",
"./quality": "./src/quality.ts",
"./ratelimit": "./src/ratelimit.ts",
"./sampling": "./src/sampling.ts",
diff --git a/packages/database/src/authz/manifest.ts b/packages/database/src/authz/manifest.ts
index da4a9fe499..0b4cd9c6ce 100644
--- a/packages/database/src/authz/manifest.ts
+++ b/packages/database/src/authz/manifest.ts
@@ -925,6 +925,9 @@ export const manifest = {
insert: owner("userId")
}),
location: company("resources"),
+ // Written only by the OEE sync and the entitlement-gated @carbon/ee/oee.server
+ // functions, over Kysely and under the device lock: read-only through the API.
+ machineStateChange: policies({ select: inCompany("companyId", "employee") }),
maintenanceDispatch: company("resources", {
create: "employee",
update: "employee"
@@ -1600,6 +1603,11 @@ export const manifest = {
delete: inCompany("companyId", "resources_delete")
}),
trainingQuestion: company("people"),
+ // Written only by the OEE sync and the entitlement-gated @carbon/ee/oee.server
+ // functions, over Kysely and under the device lock: read-only through the API.
+ unattributedMachineTime: policies({
+ select: inCompany("companyId", "employee")
+ }),
unitOfMeasure: company("parts", { read: "member" }),
user: custom(
"bespoke: five overlapping policies — self, shared company membership, employee/customer/supplier accounts, users_update, and an API-key EXISTS on userToCompany",
@@ -1696,6 +1704,11 @@ export const manifest = {
webhook: company("settings", { read: "settings_view" }),
webhookTable: policies({ select: authenticated }),
workCenter: company("resources"),
+ // Written only by the OEE sync and the entitlement-gated @carbon/ee/oee.server
+ // functions, over Kysely and under the device lock: read-only through the API.
+ workCenterDevice: policies({ select: inCompany("companyId", "employee") }),
+ // Written only by the load and unload interceptors: read-only through the API.
+ workCenterLoad: policies({ select: inCompany("companyId", "employee") }),
workCenterProcess: company("resources"),
workCenterReplacementPart: company("resources", { read: "resources_view" }),
workCenterShift: company("resources"),
diff --git a/packages/database/src/event-system/attachments.ts b/packages/database/src/event-system/attachments.ts
index 740842a2c4..c0b75cf42d 100644
--- a/packages/database/src/event-system/attachments.ts
+++ b/packages/database/src/event-system/attachments.ts
@@ -177,7 +177,8 @@ export const attachments = {
before: ["sync_finish_job_operation"],
after: [
"set_shelf_life_on_operation_done",
- "set_shelf_life_on_operation_started"
+ "set_shelf_life_on_operation_started",
+ "sync_unload_work_center_operation"
],
events: true,
statement: ["broadcast_table_changes"]
@@ -267,6 +268,7 @@ export const attachments = {
process: { statement: ["broadcast_reference_changes"] },
productionEvent: {
before: ["sync_set_job_operation_in_progress"],
+ after: ["sync_load_work_center_operation"],
events: true,
statement: ["broadcast_table_changes"]
},
@@ -430,6 +432,7 @@ export const attachments = {
},
trackedActivity: { statement: ["broadcast_table_changes"] },
trackedEntity: { statement: ["broadcast_table_changes"] },
+ unattributedMachineTime: { statement: ["broadcast_table_changes"] },
unitOfMeasure: { statement: ["broadcast_reference_changes"] },
user: {
after: [
@@ -450,6 +453,7 @@ export const attachments = {
},
webhook: { after: ["sync_webhook_subscription"], events: true },
workCenter: { events: true, statement: ["broadcast_reference_changes"] },
+ workCenterDevice: { statement: ["broadcast_table_changes"] },
workCenterProcess: { events: true },
workflowRun: { statement: ["broadcast_table_changes"] },
workflowStepRun: { statement: ["broadcast_table_changes"] }
diff --git a/packages/database/src/event-system/handlers/sync_load_work_center_operation.sql b/packages/database/src/event-system/handlers/sync_load_work_center_operation.sql
new file mode 100644
index 0000000000..cdc46d69bf
--- /dev/null
+++ b/packages/database/src/event-system/handlers/sync_load_work_center_operation.sql
@@ -0,0 +1,66 @@
+CREATE OR REPLACE FUNCTION public.sync_load_work_center_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ v_work_center_id text := p_new->>'workCenterId';
+ v_company_id text := p_new->>'companyId';
+ v_operation_id text := p_new->>'jobOperationId';
+ v_start timestamptz := (p_new->>'startTime')::timestamptz;
+ v_boundary timestamptz;
+ v_loaded text;
+BEGIN
+ IF p_operation != 'INSERT' THEN RETURN; END IF;
+
+ -- Only a starting event loads: an event inserted with an endTime (an ERP
+ -- entry, an assigned interval, a closed sensor run) never does.
+ IF (p_new->>'endTime') IS NOT NULL OR v_work_center_id IS NULL THEN
+ RETURN;
+ END IF;
+
+ -- This runs as the owner (the dispatchers are SECURITY DEFINER), and the
+ -- event's workCenterId and jobOperationId are single-column FKs: an event
+ -- may only load its OWN company's operation onto its own company's work
+ -- center, or another company's sensor time would land on it. (A starting
+ -- event reopens a Done operation first: sync_set_job_operation_in_progress.)
+ IF NOT EXISTS (
+ SELECT 1 FROM "workCenter"
+ WHERE "id" = v_work_center_id AND "companyId" = v_company_id
+ ) OR NOT EXISTS (
+ SELECT 1 FROM "jobOperation"
+ WHERE "id" = v_operation_id AND "companyId" = v_company_id
+ ) THEN
+ RETURN;
+ END IF;
+
+ -- One load at a time per work center.
+ PERFORM pg_advisory_xact_lock(hashtextextended('workCenterLoad:' || v_work_center_id, 0));
+
+ -- The open row is the load. A start older than the newest boundary in the
+ -- history (a load or an unload) never loads: a late event must not undo a
+ -- load or an unload that came after it.
+ SELECT max(GREATEST("loadedAt", COALESCE("unloadedAt", "loadedAt")))
+ INTO v_boundary
+ FROM "workCenterLoad"
+ WHERE "workCenterId" = v_work_center_id AND "companyId" = v_company_id;
+ IF v_boundary IS NOT NULL AND v_start < v_boundary THEN RETURN; END IF;
+
+ -- A reload of the operation already loaded writes nothing.
+ SELECT "jobOperationId" INTO v_loaded
+ FROM "workCenterLoad"
+ WHERE "workCenterId" = v_work_center_id
+ AND "companyId" = v_company_id
+ AND "unloadedAt" IS NULL;
+ IF v_loaded = v_operation_id THEN RETURN; END IF;
+
+ UPDATE "workCenterLoad"
+ SET "unloadedAt" = v_start
+ WHERE "workCenterId" = v_work_center_id
+ AND "companyId" = v_company_id
+ AND "unloadedAt" IS NULL;
+
+ INSERT INTO "workCenterLoad" ("companyId", "workCenterId", "jobOperationId", "loadedAt")
+ VALUES (v_company_id, v_work_center_id, v_operation_id, v_start);
+END;
+$function$;
diff --git a/packages/database/src/event-system/handlers/sync_unload_work_center_operation.sql b/packages/database/src/event-system/handlers/sync_unload_work_center_operation.sql
new file mode 100644
index 0000000000..2ac11df5fe
--- /dev/null
+++ b/packages/database/src/event-system/handlers/sync_unload_work_center_operation.sql
@@ -0,0 +1,41 @@
+CREATE OR REPLACE FUNCTION public.sync_unload_work_center_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ -- An unload ends the operation's open load now, never before it began.
+ -- A deleted operation unloads too: the load has no foreign key, because one
+ -- would make PostgREST embeds between workCenter and jobOperation ambiguous.
+ IF p_operation = 'DELETE' THEN
+ UPDATE "workCenterLoad"
+ SET "unloadedAt" = GREATEST(NOW(), "loadedAt")
+ WHERE "jobOperationId" = p_old->>'id'
+ AND "companyId" = p_old->>'companyId'
+ AND "unloadedAt" IS NULL;
+ RETURN;
+ END IF;
+
+ IF p_operation != 'UPDATE' THEN RETURN; END IF;
+
+ -- An operation moved to another work center leaves the old one: its sensor
+ -- time there is no longer this operation's.
+ IF (p_old->>'workCenterId') IS DISTINCT FROM (p_new->>'workCenterId') THEN
+ UPDATE "workCenterLoad"
+ SET "unloadedAt" = GREATEST(NOW(), "loadedAt")
+ WHERE "workCenterId" = p_old->>'workCenterId'
+ AND "companyId" = p_old->>'companyId'
+ AND "jobOperationId" = p_new->>'id'
+ AND "unloadedAt" IS NULL;
+ END IF;
+
+ IF (p_new->>'status') NOT IN ('Done', 'Canceled') THEN RETURN; END IF;
+ IF (p_old->>'status') = (p_new->>'status') THEN RETURN; END IF;
+
+ UPDATE "workCenterLoad"
+ SET "unloadedAt" = GREATEST(NOW(), "loadedAt")
+ WHERE "jobOperationId" = p_new->>'id'
+ AND "companyId" = p_new->>'companyId'
+ AND "unloadedAt" IS NULL;
+END;
+$function$;
diff --git a/packages/database/src/machine-time.test.ts b/packages/database/src/machine-time.test.ts
new file mode 100644
index 0000000000..6612f39bcb
--- /dev/null
+++ b/packages/database/src/machine-time.test.ts
@@ -0,0 +1,291 @@
+// 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 { randomUUID } from "node:crypto";
+import type { DatabaseConnection } from "kysely";
+import { CompiledQuery, Kysely, PostgresDialect, PostgresDriver } from "kysely";
+import { Client } from "pg";
+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import type { KyselyDatabase } from "./client.ts";
+import {
+ endSensorMachineTime,
+ recordManualMachinePress
+} from "./machine-time.ts";
+
+// Runs against the local database, like the authz tests:
+// SUPABASE_DB_URL=… pnpm --filter @carbon/database test -- machine-time
+//
+// Each test runs inside one transaction that is always rolled back, so it
+// writes nothing. Fixtures are inserted with `session_replication_role =
+// replica` (FKs and triggers off), so a Machine event needs no job behind it.
+const url = process.env.SUPABASE_DB_URL;
+
+class SavepointDriver extends PostgresDriver {
+ override async beginTransaction(connection: DatabaseConnection) {
+ await connection.executeQuery(CompiledQuery.raw("SAVEPOINT engine"));
+ }
+ override async commitTransaction(connection: DatabaseConnection) {
+ await connection.executeQuery(
+ CompiledQuery.raw("RELEASE SAVEPOINT engine")
+ );
+ }
+ override async rollbackTransaction(connection: DatabaseConnection) {
+ await connection.executeQuery(
+ CompiledQuery.raw("ROLLBACK TO SAVEPOINT engine")
+ );
+ }
+}
+
+type Row = Record<string, unknown>;
+
+describe.skipIf(!url)("machine time against a migrated database", () => {
+ const client = new Client({ connectionString: url });
+ const config = {
+ pool: {
+ connect: async () => Object.assign(client, { release: () => undefined }),
+ end: async () => undefined
+ }
+ };
+ const dialect = new PostgresDialect(config);
+ const db = new Kysely<KyselyDatabase>({
+ dialect: {
+ createAdapter: () => dialect.createAdapter(),
+ createDriver: () => new SavepointDriver(config),
+ createIntrospector: (k) => dialect.createIntrospector(k),
+ createQueryCompiler: () => dialect.createQueryCompiler()
+ }
+ });
+
+ const run = randomUUID().slice(0, 8);
+ const id = (name: string) => `t-${run}-${name}`;
+ const companyId = id("company");
+ const workCenterId = id("wc");
+ const otherWorkCenterId = id("wc-other");
+ const operator = id("operator");
+
+ const before = "2026-10-13T08:00:00.000Z";
+ const at = "2026-10-13T09:00:00.000Z";
+ const after = "2026-10-13T09:30:00.000Z";
+
+ async function insert(table: string, given: Row) {
+ const row: Row = { companyId, createdBy: "system", ...given };
+ const columns = Object.keys(row);
+ await client.query(
+ `INSERT INTO "${table}" (${columns.map((c) => `"${c}"`).join(", ")})
+ VALUES (${columns.map((_, i) => `$${i + 1}`).join(", ")})`,
+ Object.values(row)
+ );
+ }
+
+ async function machineEvent(rowId: string, given: Row = {}) {
+ await insert("productionEvent", {
+ id: id(rowId),
+ jobOperationId: id("op"),
+ workCenterId,
+ type: "Machine",
+ startTime: before,
+ ...given
+ });
+ }
+
+ async function unattributed(rowId: string, given: Row = {}) {
+ await insert("unattributedMachineTime", {
+ id: id(rowId),
+ workCenterId,
+ startTime: before,
+ ...given
+ });
+ }
+
+ /** Whether the row ended exactly at `at`, or is still open (null). */
+ async function endedAt(table: string, rowId: string) {
+ const result = await client.query(
+ `SELECT "endTime" IS NULL AS open, "endTime" = $2::timestamptz AS "atPress"
+ FROM "${table}" WHERE "id" = $1`,
+ [id(rowId), at]
+ );
+ const row = result.rows[0] as { open: boolean; atPress: boolean | null };
+ return row.open ? null : row.atPress;
+ }
+
+ async function seed() {
+ await client.query("BEGIN");
+ await client.query("SET LOCAL session_replication_role = replica");
+ await insert("workCenterDevice", {
+ id: id("device"),
+ workCenterId,
+ integration: "sense",
+ externalDeviceId: id("station"),
+ deviceName: "Station"
+ });
+ }
+
+ beforeAll(async () => {
+ await client.connect();
+ });
+
+ afterEach(async () => {
+ await client.query("ROLLBACK");
+ });
+
+ afterAll(async () => {
+ await client.end();
+ });
+
+ describe("recordManualMachinePress", () => {
+ it("ends open unattributed time at the press, so it is not counted twice", async () => {
+ await seed();
+ await unattributed("running");
+ await unattributed("later", { startTime: after });
+ await unattributed("other-wc", { workCenterId: otherWorkCenterId });
+
+ const result = await db.transaction().execute((trx) =>
+ recordManualMachinePress(trx, {
+ workCenterId,
+ companyId,
+ userId: operator,
+ pressedAt: at
+ })
+ );
+
+ expect(result.mapped).toBe(true);
+ expect(await endedAt("unattributedMachineTime", "running")).toBe(true);
+ // Started after the press: the sync still owns it.
+ expect(await endedAt("unattributedMachineTime", "later")).toBeNull();
+ expect(await endedAt("unattributedMachineTime", "other-wc")).toBeNull();
+ });
+
+ it("records the press: never earlier than the last one, and keeps the earliest unplanned one", async () => {
+ await seed();
+ const press = (pressedAt: string) =>
+ db.transaction().execute((trx) =>
+ recordManualMachinePress(trx, {
+ workCenterId,
+ companyId,
+ userId: operator,
+ pressedAt
+ })
+ );
+ // A late press with an earlier time must not move the latest back.
+ await press(at);
+ await press(after);
+ await press(before);
+
+ const result = await client.query(
+ `SELECT "lastManualChangeAt" = $2::timestamptz AS "latest",
+ "unplannedPressAt" = $3::timestamptz AS "earliest"
+ FROM "workCenterDevice" WHERE "id" = $1`,
+ [id("device"), after, before]
+ );
+ expect(result.rows[0]).toEqual({ latest: true, earliest: true });
+ });
+
+ it("takes the press time under the lock when none is given", async () => {
+ await seed();
+ const result = await db.transaction().execute((trx) =>
+ recordManualMachinePress(trx, {
+ workCenterId,
+ companyId,
+ userId: operator
+ })
+ );
+ expect(Number.isNaN(Date.parse(result.pressedAt))).toBe(false);
+ });
+
+ it("ends another operator's Machine event", async () => {
+ await seed();
+ await machineEvent("operator", { createdBy: operator });
+
+ await db.transaction().execute((trx) =>
+ recordManualMachinePress(trx, {
+ workCenterId,
+ companyId,
+ userId: id("other-operator"),
+ pressedAt: at
+ })
+ );
+
+ expect(await endedAt("productionEvent", "operator")).toBe(true);
+ });
+
+ it("does not end an event that starts after the press", async () => {
+ await seed();
+ await machineEvent("later", { startTime: after });
+
+ await db.transaction().execute((trx) =>
+ recordManualMachinePress(trx, {
+ workCenterId,
+ companyId,
+ userId: operator,
+ pressedAt: at
+ })
+ );
+
+ expect(await endedAt("productionEvent", "later")).toBeNull();
+ });
+
+ it("ends Machine events on a work center with no device", async () => {
+ await client.query("BEGIN");
+ await client.query("SET LOCAL session_replication_role = replica");
+ await machineEvent("running");
+
+ const result = await db.transaction().execute((trx) =>
+ recordManualMachinePress(trx, {
+ workCenterId,
+ companyId,
+ userId: operator,
+ pressedAt: at
+ })
+ );
+
+ expect(result.mapped).toBe(false);
+ expect(await endedAt("productionEvent", "running")).toBe(true);
+ });
+
+ it("leaves unattributed time on a work center with no device", async () => {
+ await client.query("BEGIN");
+ await client.query("SET LOCAL session_replication_role = replica");
+ await unattributed("running");
+
+ const result = await db.transaction().execute((trx) =>
+ recordManualMachinePress(trx, {
+ workCenterId,
+ companyId,
+ userId: operator,
+ pressedAt: at
+ })
+ );
+
+ expect(result.mapped).toBe(false);
+ expect(await endedAt("unattributedMachineTime", "running")).toBeNull();
+ });
+ });
+
+ describe("endSensorMachineTime", () => {
+ it("ends the sensor's open time and leaves the operator's", async () => {
+ await seed();
+ await machineEvent("sensor");
+ await machineEvent("operator", { createdBy: operator });
+ await machineEvent("other-wc", { workCenterId: otherWorkCenterId });
+ await unattributed("running");
+ await unattributed("stopped", { endTime: before });
+
+ await db.transaction().execute((trx) =>
+ endSensorMachineTime(trx, {
+ workCenterId,
+ companyId,
+ userId: operator,
+ at
+ })
+ );
+
+ expect(await endedAt("productionEvent", "sensor")).toBe(true);
+ expect(await endedAt("productionEvent", "operator")).toBeNull();
+ expect(await endedAt("productionEvent", "other-wc")).toBeNull();
+ expect(await endedAt("unattributedMachineTime", "running")).toBe(true);
+ // Already stopped: its end stays where the sync put it.
+ expect(await endedAt("unattributedMachineTime", "stopped")).toBe(false);
+ });
+ });
+});
diff --git a/packages/database/src/machine-time.ts b/packages/database/src/machine-time.ts
new file mode 100644
index 0000000000..9144a7bdaf
--- /dev/null
+++ b/packages/database/src/machine-time.ts
@@ -0,0 +1,161 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { sql } from "kysely";
+import type { KyselyTx } from "./client";
+
+export async function lockWorkCenterDevice(
+ trx: KyselyTx,
+ args: { workCenterId: string; companyId: string }
+) {
+ return trx
+ .selectFrom("workCenterDevice")
+ .selectAll()
+ .where("workCenterId", "=", args.workCenterId)
+ .where("companyId", "=", args.companyId)
+ .forUpdate()
+ .executeTakeFirst();
+}
+
+type CloseArgs = {
+ workCenterId: string;
+ companyId: string;
+ userId: string;
+ at: string;
+};
+
+/**
+ * End the work center's open unattributed time at `at`. A row that starts
+ * after `at` stays open for the sync to close.
+ */
+async function endOpenUnattributedTime(trx: KyselyTx, args: CloseArgs) {
+ await trx
+ .updateTable("unattributedMachineTime")
+ .set({ endTime: args.at, updatedBy: args.userId, updatedAt: args.at })
+ .where("workCenterId", "=", args.workCenterId)
+ .where("companyId", "=", args.companyId)
+ .where("endTime", "is", null)
+ .where("startTime", "<=", args.at)
+ .execute();
+}
+
+/**
+ * A device leaves a work center (unmapped or remapped). End the time its
+ * sensor opened there — Machine events created by `system` and running
+ * unattributed time — because no later sync of that device will close it. An operator's
+ * own Machine event stays open. Call it under `lockWorkCenterDevice`.
+ */
+export async function endSensorMachineTime(trx: KyselyTx, args: CloseArgs) {
+ await trx
+ .updateTable("productionEvent")
+ .set({ endTime: args.at, updatedBy: args.userId, updatedAt: args.at })
+ .where("workCenterId", "=", args.workCenterId)
+ .where("companyId", "=", args.companyId)
+ .where("type", "=", "Machine")
+ .where("createdBy", "=", "system")
+ .where("endTime", "is", null)
+ .where("startTime", "<=", args.at)
+ .execute();
+ await endOpenUnattributedTime(trx, args);
+}
+
+/**
+ * The locks a Machine press holds, in the one order every writer takes them:
+ * the device row first (the sync locks it, then ends events), then a lock on
+ * the work center itself, which exists with or without a device. Anything
+ * that ends a Machine event under a press takes these before any event row.
+ * Returns the device, if the work center has one.
+ */
+export async function lockMachinePress(
+ trx: KyselyTx,
+ args: { workCenterId: string; companyId: string }
+) {
+ const device = await lockWorkCenterDevice(trx, args);
+ await sql`SELECT pg_advisory_xact_lock(hashtextextended(${`machinePress:${args.workCenterId}`}, 0))`.execute(
+ trx
+ );
+ return device;
+}
+
+/** The time now, read inside the transaction (an absolute instant). */
+async function lockedNow(trx: KyselyTx) {
+ const { rows } = await sql<{
+ now: Date;
+ }>`SELECT clock_timestamp() AS now`.execute(trx);
+ const now = rows[0]?.now;
+ if (!now) throw new Error("Could not read the time");
+ return now.toISOString();
+}
+
+/**
+ * A machine has one machine time. An operator pressed Machine Start or Pause
+ * on a work center: separate operators share a single machine time, so on
+ * any work center, with or without a device, the press ends every open
+ * Machine event there at the press time — from any operator or the sensor.
+ * An event that starts after the press stays open. A Start then opens the
+ * new one in the same transaction.
+ *
+ * On a work center with a device, the press also ends the open unattributed
+ * time at the press time and records the press, so an older sensor change
+ * never undoes it. Without the unattributed close, a Start on a running
+ * machine with no loaded operation counted the same minutes twice: once on
+ * the operator's event and once in the supervisor queue.
+ *
+ * Presses on one work center run one at a time, and the press time is read
+ * under the locks (unless the caller fixes it), so two presses never leave
+ * two Machine events open and the recorded press never moves backwards.
+ */
+export async function recordManualMachinePress(
+ trx: KyselyTx,
+ args: {
+ workCenterId: string;
+ companyId: string;
+ userId: string;
+ pressedAt?: string;
+ }
+): Promise<{ mapped: boolean; endedEventIds: string[]; pressedAt: string }> {
+ const device = await lockMachinePress(trx, args);
+ const pressedAt = args.pressedAt ?? (await lockedNow(trx));
+
+ const ended = await trx
+ .updateTable("productionEvent")
+ .set({
+ endTime: pressedAt,
+ updatedBy: args.userId,
+ updatedAt: pressedAt
+ })
+ .where("workCenterId", "=", args.workCenterId)
+ .where("companyId", "=", args.companyId)
+ .where("type", "=", "Machine")
+ .where("endTime", "is", null)
+ .where("startTime", "<=", pressedAt)
+ .returning("id")
+ .execute();
+ const endedEventIds = ended.map((row) => row.id);
+
+ if (!device) return { mapped: false, endedEventIds, pressedAt };
+
+ await endOpenUnattributedTime(trx, {
+ workCenterId: args.workCenterId,
+ companyId: args.companyId,
+ userId: args.userId,
+ at: pressedAt
+ });
+
+ // The latest press never moves backwards, and the earliest one since the
+ // last sync is kept for the sync to plan from.
+ await trx
+ .updateTable("workCenterDevice")
+ .set({
+ lastManualChangeAt: sql`GREATEST(COALESCE("lastManualChangeAt", ${pressedAt}::timestamptz), ${pressedAt}::timestamptz)`,
+ unplannedPressAt: sql`LEAST(COALESCE("unplannedPressAt", ${pressedAt}::timestamptz), ${pressedAt}::timestamptz)`,
+ updatedBy: args.userId,
+ updatedAt: pressedAt
+ })
+ .where("id", "=", device.id)
+ .where("companyId", "=", args.companyId)
+ .execute();
+
+ return { mapped: true, endedEventIds, pressedAt };
+}
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index eeae056501..2c9d610619 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -17352,6 +17352,177 @@ export default {
tags: ["inventoryCountLine"]
}
},
+ "/unattributedMachineTime": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.workCenterId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.startTime"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.endTime"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.updatedAt"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/unattributedMachineTime"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["unattributedMachineTime"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.unattributedMachineTime"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["unattributedMachineTime"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.workCenterId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.startTime"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.endTime"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.updatedAt"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["unattributedMachineTime"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.workCenterId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.startTime"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.endTime"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTime.updatedAt"
+ },
+ {
+ $ref: "#/parameters/body.unattributedMachineTime"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["unattributedMachineTime"]
+ }
+ },
"/gauges": {
get: {
parameters: [
@@ -30276,6 +30447,159 @@ export default {
tags: ["purchasingRfq"]
}
},
+ "/workCenterLoad": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.workCenterId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.jobOperationId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.loadedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.unloadedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.createdAt"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/workCenterLoad"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["workCenterLoad"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.workCenterLoad"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["workCenterLoad"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.workCenterId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.jobOperationId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.loadedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.unloadedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.createdAt"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["workCenterLoad"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.workCenterId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.jobOperationId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.loadedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.unloadedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterLoad.createdAt"
+ },
+ {
+ $ref: "#/parameters/body.workCenterLoad"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["workCenterLoad"]
+ }
+ },
"/workCenters": {
get: {
parameters: [
@@ -30534,6 +30858,81 @@ export default {
tags: ["enforcementRuleWorkCenterAssignment"]
}
},
+ "/unattributedMachineTimes": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTimes.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTimes.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTimes.workCenterId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTimes.startTime"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTimes.endTime"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTimes.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTimes.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTimes.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTimes.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTimes.startDate"
+ },
+ {
+ $ref: "#/parameters/rowFilter.unattributedMachineTimes.endDate"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/unattributedMachineTimes"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["unattributedMachineTimes"]
+ }
+ },
"/contractorAbility": {
get: {
parameters: [
@@ -88752,6 +89151,9 @@ export default {
{
$ref: "#/parameters/rowFilter.workCentersWithBlockingStatus.blockingDispatchReadableId"
},
+ {
+ $ref: "#/parameters/rowFilter.workCentersWithBlockingStatus.loadedJobOperationId"
+ },
{
$ref: "#/parameters/select"
},
@@ -89070,6 +89472,168 @@ export default {
tags: ["salesReturnOrderLine"]
}
},
+ "/machineStateChange": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.workCenterDeviceId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.workCenterId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.externalEventId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.state"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.changedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.createdAt"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/machineStateChange"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["machineStateChange"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.machineStateChange"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["machineStateChange"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.workCenterDeviceId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.workCenterId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.externalEventId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.state"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.changedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.createdAt"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["machineStateChange"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.workCenterDeviceId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.workCenterId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.externalEventId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.state"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.changedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.machineStateChange.createdAt"
+ },
+ {
+ $ref: "#/parameters/body.machineStateChange"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["machineStateChange"]
+ }
+ },
"/purchaseOrderDelivery": {
get: {
parameters: [
@@ -95517,6 +96081,276 @@ export default {
tags: ["workCenter"]
}
},
+ "/workCenterDevice": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.workCenterId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.integration"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.externalDeviceId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.externalSiteId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.siteTimezone"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.deviceName"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.currentState"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.currentStateAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.appliedThrough"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.lastEventAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.lastManualChangeAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.lastSyncedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.lastSyncError"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.unplannedPressAt"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/order"
+ },
+ {
+ $ref: "#/parameters/range"
+ },
+ {
+ $ref: "#/parameters/rangeUnit"
+ },
+ {
+ $ref: "#/parameters/offset"
+ },
+ {
+ $ref: "#/parameters/limit"
+ },
+ {
+ $ref: "#/parameters/preferCount"
+ }
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/workCenterDevice"
+ },
+ type: "array"
+ }
+ },
+ "206": {
+ description: "Partial Content"
+ }
+ },
+ tags: ["workCenterDevice"]
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.workCenterDevice"
+ },
+ {
+ $ref: "#/parameters/select"
+ },
+ {
+ $ref: "#/parameters/preferPost"
+ }
+ ],
+ responses: {
+ "201": {
+ description: "Created"
+ }
+ },
+ tags: ["workCenterDevice"]
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.workCenterId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.integration"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.externalDeviceId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.externalSiteId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.siteTimezone"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.deviceName"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.currentState"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.currentStateAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.appliedThrough"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.lastEventAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.lastManualChangeAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.lastSyncedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.lastSyncError"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.unplannedPressAt"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["workCenterDevice"]
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.id"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.companyId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.workCenterId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.integration"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.externalDeviceId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.externalSiteId"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.siteTimezone"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.deviceName"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.currentState"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.currentStateAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.appliedThrough"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.lastEventAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.lastManualChangeAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.lastSyncedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.lastSyncError"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.createdBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.createdAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.updatedBy"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.updatedAt"
+ },
+ {
+ $ref: "#/parameters/rowFilter.workCenterDevice.unplannedPressAt"
+ },
+ {
+ $ref: "#/parameters/body.workCenterDevice"
+ },
+ {
+ $ref: "#/parameters/preferReturn"
+ }
+ ],
+ responses: {
+ "204": {
+ description: "No Content"
+ }
+ },
+ tags: ["workCenterDevice"]
+ }
+ },
"/itemSupersession": {
get: {
parameters: [
@@ -115579,6 +116413,51 @@ export default {
tags: ["(rpc) xid_counter"]
}
},
+ "/rpc/sync_load_work_center_operation": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_new: {
+ format: "jsonb"
+ },
+ p_old: {
+ format: "jsonb"
+ },
+ p_operation: {
+ format: "text",
+ type: "string"
+ },
+ p_table: {
+ format: "text",
+ type: "string"
+ }
+ },
+ required: ["p_table", "p_operation", "p_new", "p_old"],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) sync_load_work_center_operation"]
+ }
+ },
"/rpc/storage_unit_enforce_no_cycle": {
post: {
parameters: [
@@ -115978,6 +116857,51 @@ export default {
tags: ["(rpc) sync_update_stock_transfer_status"]
}
},
+ "/rpc/sync_unload_work_center_operation": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_new: {
+ format: "jsonb"
+ },
+ p_old: {
+ format: "jsonb"
+ },
+ p_operation: {
+ format: "text",
+ type: "string"
+ },
+ p_table: {
+ format: "text",
+ type: "string"
+ }
+ },
+ required: ["p_table", "p_operation", "p_new", "p_old"],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) sync_unload_work_center_operation"]
+ }
+ },
"/rpc/get_purchasing_planning": {
post: {
parameters: [
@@ -125001,6 +125925,64 @@ export default {
},
type: "object"
},
+ unattributedMachineTime: {
+ required: [
+ "id",
+ "companyId",
+ "workCenterId",
+ "startTime",
+ "createdBy",
+ "createdAt"
+ ],
+ properties: {
+ id: {
+ default: "public.id('umt'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ workCenterId: {
+ format: "text",
+ type: "string"
+ },
+ startTime: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ endTime: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
gauges: {
properties: {
id: {
@@ -131285,6 +132267,52 @@ export default {
},
type: "object"
},
+ workCenterLoad: {
+ required: [
+ "id",
+ "companyId",
+ "workCenterId",
+ "jobOperationId",
+ "loadedAt",
+ "createdAt"
+ ],
+ properties: {
+ id: {
+ default: "public.id('wcl'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ workCenterId: {
+ format: "text",
+ type: "string"
+ },
+ jobOperationId: {
+ format: "text",
+ type: "string"
+ },
+ loadedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ unloadedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
workCenters: {
properties: {
id: {
@@ -131463,6 +132491,62 @@ export default {
},
type: "object"
},
+ unattributedMachineTimes: {
+ properties: {
+ id: {
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ workCenterId: {
+ format: "text",
+ type: "string"
+ },
+ startTime: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ endTime: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ startDate: {
+ format: "date",
+ type: "string"
+ },
+ endDate: {
+ format: "date",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
contractorAbility: {
required: [
"contractorId",
@@ -159047,6 +160131,10 @@ export default {
blockingDispatchReadableId: {
format: "text",
type: "string"
+ },
+ loadedJobOperationId: {
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -159191,6 +160279,59 @@ export default {
},
type: "object"
},
+ machineStateChange: {
+ required: [
+ "id",
+ "companyId",
+ "workCenterDeviceId",
+ "workCenterId",
+ "externalEventId",
+ "state",
+ "changedAt",
+ "createdAt"
+ ],
+ properties: {
+ id: {
+ default: "public.id('msc'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ workCenterDeviceId: {
+ format: "text",
+ type: "string"
+ },
+ workCenterId: {
+ format: "text",
+ type: "string"
+ },
+ externalEventId: {
+ format: "text",
+ type: "string"
+ },
+ state: {
+ enum: ["Running", "Idle", "Down", "Offline"],
+ format: 'public."machineState"',
+ type: "string"
+ },
+ changedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
purchaseOrderDelivery: {
required: ["id", "dropShipment", "companyId", "supplierShippingCost"],
properties: {
@@ -162698,6 +163839,115 @@ export default {
},
type: "object"
},
+ workCenterDevice: {
+ required: [
+ "id",
+ "companyId",
+ "workCenterId",
+ "integration",
+ "externalDeviceId",
+ "deviceName",
+ "lastEventAt",
+ "createdBy",
+ "createdAt"
+ ],
+ properties: {
+ id: {
+ default: "public.id('wcd'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string"
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ workCenterId: {
+ format: "text",
+ type: "string"
+ },
+ integration: {
+ description:
+ "Note:\nThis is a Foreign Key to `integration.id`.<fk table='integration' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ externalDeviceId: {
+ format: "text",
+ type: "string"
+ },
+ externalSiteId: {
+ format: "text",
+ type: "string"
+ },
+ siteTimezone: {
+ format: "text",
+ type: "string"
+ },
+ deviceName: {
+ format: "text",
+ type: "string"
+ },
+ currentState: {
+ enum: ["Running", "Idle", "Down", "Offline"],
+ format: 'public."machineState"',
+ type: "string"
+ },
+ currentStateAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ appliedThrough: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ lastEventAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ lastManualChangeAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ lastSyncedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ lastSyncError: {
+ format: "text",
+ type: "string"
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string"
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ },
+ unplannedPressAt: {
+ format: "timestamp with time zone",
+ type: "string"
+ }
+ },
+ type: "object"
+ },
itemSupersession: {
required: [
"itemId",
@@ -175431,6 +176681,69 @@ export default {
in: "query",
type: "string"
},
+ "body.unattributedMachineTime": {
+ name: "unattributedMachineTime",
+ description: "unattributedMachineTime",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/unattributedMachineTime"
+ }
+ },
+ "rowFilter.unattributedMachineTime.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTime.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTime.workCenterId": {
+ name: "workCenterId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTime.startTime": {
+ name: "startTime",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTime.endTime": {
+ name: "endTime",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTime.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTime.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTime.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTime.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.gauges": {
name: "gauges",
description: "gauges",
@@ -182557,6 +183870,57 @@ export default {
in: "query",
type: "string"
},
+ "body.workCenterLoad": {
+ name: "workCenterLoad",
+ description: "workCenterLoad",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/workCenterLoad"
+ }
+ },
+ "rowFilter.workCenterLoad.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterLoad.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterLoad.workCenterId": {
+ name: "workCenterId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterLoad.jobOperationId": {
+ name: "jobOperationId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterLoad.loadedAt": {
+ name: "loadedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterLoad.unloadedAt": {
+ name: "unloadedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterLoad.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.workCenters": {
name: "workCenters",
description: "workCenters",
@@ -182755,6 +184119,81 @@ export default {
in: "query",
type: "string"
},
+ "body.unattributedMachineTimes": {
+ name: "unattributedMachineTimes",
+ description: "unattributedMachineTimes",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/unattributedMachineTimes"
+ }
+ },
+ "rowFilter.unattributedMachineTimes.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTimes.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTimes.workCenterId": {
+ name: "workCenterId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTimes.startTime": {
+ name: "startTime",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTimes.endTime": {
+ name: "endTime",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTimes.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTimes.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTimes.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTimes.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTimes.startDate": {
+ name: "startDate",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.unattributedMachineTimes.endDate": {
+ name: "endDate",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.contractorAbility": {
name: "contractorAbility",
description: "contractorAbility",
@@ -213516,6 +214955,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.workCentersWithBlockingStatus.loadedJobOperationId": {
+ name: "loadedJobOperationId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.salesReturnOrderLine": {
name: "salesReturnOrderLine",
description: "salesReturnOrderLine",
@@ -213651,6 +215096,63 @@ export default {
in: "query",
type: "string"
},
+ "body.machineStateChange": {
+ name: "machineStateChange",
+ description: "machineStateChange",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/machineStateChange"
+ }
+ },
+ "rowFilter.machineStateChange.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.machineStateChange.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.machineStateChange.workCenterDeviceId": {
+ name: "workCenterDeviceId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.machineStateChange.workCenterId": {
+ name: "workCenterId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.machineStateChange.externalEventId": {
+ name: "externalEventId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.machineStateChange.state": {
+ name: "state",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.machineStateChange.changedAt": {
+ name: "changedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.machineStateChange.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.purchaseOrderDelivery": {
name: "purchaseOrderDelivery",
description: "purchaseOrderDelivery",
@@ -217609,6 +219111,135 @@ export default {
in: "query",
type: "string"
},
+ "body.workCenterDevice": {
+ name: "workCenterDevice",
+ description: "workCenterDevice",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/workCenterDevice"
+ }
+ },
+ "rowFilter.workCenterDevice.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.workCenterId": {
+ name: "workCenterId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.integration": {
+ name: "integration",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.externalDeviceId": {
+ name: "externalDeviceId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.externalSiteId": {
+ name: "externalSiteId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.siteTimezone": {
+ name: "siteTimezone",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.deviceName": {
+ name: "deviceName",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.currentState": {
+ name: "currentState",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.currentStateAt": {
+ name: "currentStateAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.appliedThrough": {
+ name: "appliedThrough",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.lastEventAt": {
+ name: "lastEventAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.lastManualChangeAt": {
+ name: "lastManualChangeAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.lastSyncedAt": {
+ name: "lastSyncedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.lastSyncError": {
+ name: "lastSyncError",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
+ "rowFilter.workCenterDevice.unplannedPressAt": {
+ name: "unplannedPressAt",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.itemSupersession": {
name: "itemSupersession",
description: "itemSupersession",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 17e70a332d..e2c62832b1 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -32516,6 +32516,89 @@ export type Database = {
}
]
}
+ machineStateChange: {
+ Row: {
+ changedAt: string
+ companyId: string
+ createdAt: string
+ externalEventId: string
+ id: string
+ state: Database["public"]["Enums"]["machineState"]
+ workCenterDeviceId: string
+ workCenterId: string
+ }
+ Insert: {
+ changedAt: string
+ companyId: string
+ createdAt?: string
+ externalEventId: string
+ id?: string
+ state: Database["public"]["Enums"]["machineState"]
+ workCenterDeviceId: string
+ workCenterId: string
+ }
+ Update: {
+ changedAt?: string
+ companyId?: string
+ createdAt?: string
+ externalEventId?: string
+ id?: string
+ state?: Database["public"]["Enums"]["machineState"]
+ workCenterDeviceId?: string
+ workCenterId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "machineStateChange_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "machineStateChange_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "machineStateChange_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "machineStateChange_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "machineStateChange_workCenterId_fkey"
+ columns: ["workCenterId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workCenter"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "machineStateChange_workCenterId_fkey"
+ columns: ["workCenterId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workCenters"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "machineStateChange_workCenterId_fkey"
+ columns: ["workCenterId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workCentersWithBlockingStatus"
+ referencedColumns: ["id", "companyId"]
+ }
+ ]
+ }
maintenanceDispatch: {
Row: {
actualEndTime: string | null
@@ -69982,6 +70065,162 @@ export type Database = {
}
]
}
+ unattributedMachineTime: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ endTime: string | null
+ id: string
+ startTime: string
+ updatedAt: string | null
+ updatedBy: string | null
+ workCenterId: string
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ endTime?: string | null
+ id?: string
+ startTime: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ workCenterId: string
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ endTime?: string | null
+ id?: string
+ startTime?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ workCenterId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "unattributedMachineTime_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_workCenterId_fkey"
+ columns: ["workCenterId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workCenter"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_workCenterId_fkey"
+ columns: ["workCenterId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workCenters"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_workCenterId_fkey"
+ columns: ["workCenterId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workCentersWithBlockingStatus"
+ referencedColumns: ["id", "companyId"]
+ }
+ ]
+ }
unitOfMeasure: {
Row: {
active: boolean
@@ -71760,6 +71999,289 @@ export type Database = {
}
]
}
+ workCenterDevice: {
+ Row: {
+ appliedThrough: string | null
+ companyId: string
+ createdAt: string
+ createdBy: string
+ currentState: Database["public"]["Enums"]["machineState"] | null
+ currentStateAt: string | null
+ deviceName: string
+ externalDeviceId: string
+ externalSiteId: string | null
+ id: string
+ integration: string
+ lastEventAt: string
+ lastManualChangeAt: string | null
+ lastSyncedAt: string | null
+ lastSyncError: string | null
+ siteTimezone: string | null
+ unplannedPressAt: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ workCenterId: string
+ }
+ Insert: {
+ appliedThrough?: string | null
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ currentState?: Database["public"]["Enums"]["machineState"] | null
+ currentStateAt?: string | null
+ deviceName: string
+ externalDeviceId: string
+ externalSiteId?: string | null
+ id?: string
+ integration: string
+ lastEventAt?: string
+ lastManualChangeAt?: string | null
+ lastSyncedAt?: string | null
+ lastSyncError?: string | null
+ siteTimezone?: string | null
+ unplannedPressAt?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ workCenterId: string
+ }
+ Update: {
+ appliedThrough?: string | null
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ currentState?: Database["public"]["Enums"]["machineState"] | null
+ currentStateAt?: string | null
+ deviceName?: string
+ externalDeviceId?: string
+ externalSiteId?: string | null
+ id?: string
+ integration?: string
+ lastEventAt?: string
+ lastManualChangeAt?: string | null
+ lastSyncedAt?: string | null
+ lastSyncError?: string | null
+ siteTimezone?: string | null
+ unplannedPressAt?: string | null
+ updatedAt?: string | null
+ updatedBy?: string | null
+ workCenterId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "workCenterDevice_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_integration_fkey"
+ columns: ["integration"]
+ isOneToOne: false
+ referencedRelation: "integration"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_integration_fkey"
+ columns: ["integration"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_workCenterId_fkey"
+ columns: ["workCenterId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workCenter"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_workCenterId_fkey"
+ columns: ["workCenterId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workCenters"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "workCenterDevice_workCenterId_fkey"
+ columns: ["workCenterId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workCentersWithBlockingStatus"
+ referencedColumns: ["id", "companyId"]
+ }
+ ]
+ }
+ workCenterLoad: {
+ Row: {
+ companyId: string
+ createdAt: string
+ id: string
+ jobOperationId: string
+ loadedAt: string
+ unloadedAt: string | null
+ workCenterId: string
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ id?: string
+ jobOperationId: string
+ loadedAt: string
+ unloadedAt?: string | null
+ workCenterId: string
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ id?: string
+ jobOperationId?: string
+ loadedAt?: string
+ unloadedAt?: string | null
+ workCenterId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "workCenterLoad_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "workCenterLoad_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "workCenterLoad_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "workCenterLoad_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "workCenterLoad_workCenterId_fkey"
+ columns: ["workCenterId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workCenter"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "workCenterLoad_workCenterId_fkey"
+ columns: ["workCenterId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workCenters"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "workCenterLoad_workCenterId_fkey"
+ columns: ["workCenterId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workCentersWithBlockingStatus"
+ referencedColumns: ["id", "companyId"]
+ }
+ ]
+ }
workCenterProcess: {
Row: {
companyId: string
@@ -90653,6 +91175,142 @@ export type Database = {
}
]
}
+ unattributedMachineTimes: {
+ Row: {
+ companyId: string | null
+ createdAt: string | null
+ createdBy: string | null
+ endDate: string | null
+ endTime: string | null
+ id: string | null
+ startDate: string | null
+ startTime: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ workCenterId: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "unattributedMachineTime_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_workCenterId_fkey"
+ columns: ["workCenterId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workCenter"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_workCenterId_fkey"
+ columns: ["workCenterId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workCenters"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "unattributedMachineTime_workCenterId_fkey"
+ columns: ["workCenterId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "workCentersWithBlockingStatus"
+ referencedColumns: ["id", "companyId"]
+ }
+ ]
+ }
userDefaults: {
Row: {
companyId: string | null
@@ -90870,6 +91528,7 @@ export type Database = {
id: string | null
isBlocked: boolean | null
laborRate: number | null
+ loadedJobOperationId: string | null
locationId: string | null
locationName: string | null
machineRate: number | null
@@ -93969,6 +94628,10 @@ export type Database = {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
}
+ sync_load_work_center_operation: {
+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
+ Returns: undefined
+ }
sync_on_maintenance_dispatch_complete: {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
@@ -93993,6 +94656,10 @@ export type Database = {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
}
+ sync_unload_work_center_operation: {
+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
+ Returns: undefined
+ }
sync_update_customer_type_group: {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
@@ -94661,6 +95328,7 @@ export type Database = {
| "Cancelled"
lesseeClassification: "Operating" | "Finance" | "Short-Term"
lessorClassification: "Rental" | "Sale" | "Financing"
+ machineState: "Running" | "Idle" | "Down" | "Offline"
macrsConvention: "Half-Year" | "Mid-Quarter"
macrsPropertyClass: "3" | "5" | "7" | "10" | "15" | "20" | "27.5" | "39"
maintenanceDispatchPriority: "Low" | "Medium" | "High" | "Critical"
@@ -96205,6 +96873,7 @@ export const Constants = {
],
lesseeClassification: ["Operating", "Finance", "Short-Term"],
lessorClassification: ["Rental", "Sale", "Financing"],
+ machineState: ["Running", "Idle", "Down", "Offline"],
macrsConvention: ["Half-Year", "Mid-Quarter"],
macrsPropertyClass: ["3", "5", "7", "10", "15", "20", "27.5", "39"],
maintenanceDispatchPriority: ["Low", "Medium", "High", "Critical"],
diff --git a/packages/database/supabase/migrations/20261013030022_oee-provider.sql b/packages/database/supabase/migrations/20261013030022_oee-provider.sql
new file mode 100644
index 0000000000..2fc02a6d73
--- /dev/null
+++ b/packages/database/supabase/migrations/20261013030022_oee-provider.sql
@@ -0,0 +1,233 @@
+-- OEE provider integration (spec: .ai/specs/2026-10-12-oee-provider-integration.md)
+
+-- 1. Provider role 'oee'
+ALTER TABLE "integration" DROP CONSTRAINT IF EXISTS "integration_providerRole_check";
+ALTER TABLE "integration" ADD CONSTRAINT "integration_providerRole_check"
+ CHECK ("providerRole" IS NULL OR "providerRole" IN ('accounting', 'spend', 'oee'));
+
+-- Forked from 20260924133915_integration-provider-role.sql. One change: the
+-- 'oee' role may have several active integrations per company.
+CREATE OR REPLACE FUNCTION public.check_single_active_provider_role()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ v_role TEXT;
+ v_conflict TEXT;
+BEGIN
+ IF NEW."active" IS NOT TRUE THEN
+ RETURN NEW;
+ END IF;
+
+ IF TG_OP = 'UPDATE' AND OLD."active" IS TRUE THEN
+ RETURN NEW;
+ END IF;
+
+ SELECT "providerRole" INTO v_role FROM "integration" WHERE id = NEW."id";
+ IF v_role IS NULL THEN
+ RETURN NEW;
+ END IF;
+
+ -- Several OEE providers may be active at once. The one-device-per-work-center
+ -- rule lives on "workCenterDevice" instead.
+ IF v_role = 'oee' THEN
+ RETURN NEW;
+ END IF;
+
+ PERFORM pg_advisory_xact_lock(
+ hashtextextended(
+ NEW."companyId" || E'\x1f' || 'providerRole' || E'\x1f' || v_role, 0
+ )
+ );
+
+ SELECT ci."id" INTO v_conflict
+ FROM "companyIntegration" ci
+ JOIN "integration" i ON i.id = ci."id"
+ WHERE ci."companyId" = NEW."companyId"
+ AND ci."active" IS TRUE
+ AND ci."id" <> NEW."id"
+ AND i."providerRole" = v_role
+ LIMIT 1;
+
+ IF v_conflict IS NOT NULL THEN
+ RAISE EXCEPTION
+ 'Only one active % integration is allowed per company; % is already active',
+ v_role, v_conflict
+ USING ERRCODE = '23505';
+ END IF;
+
+ RETURN NEW;
+END;
+$$;
+
+INSERT INTO "integration" ("id", "jsonschema")
+VALUES ('sense', '{"type": "object", "properties": {}}'::json)
+ON CONFLICT ("id") DO NOTHING;
+
+UPDATE "integration" SET "providerRole" = 'oee'
+ WHERE "id" = 'sense' AND "providerRole" IS DISTINCT FROM 'oee';
+
+-- 2. Loaded operation (community)
+ALTER TABLE "workCenter"
+ ADD COLUMN IF NOT EXISTS "loadedJobOperationId" TEXT REFERENCES "jobOperation"("id") ON DELETE SET NULL,
+ ADD COLUMN IF NOT EXISTS "loadedAt" TIMESTAMP WITH TIME ZONE;
+
+CREATE INDEX IF NOT EXISTS "workCenter_loadedJobOperationId_idx"
+ ON "workCenter" ("loadedJobOperationId");
+
+-- 3. Machine state
+DO $$ BEGIN
+ CREATE TYPE "machineState" AS ENUM ('Running', 'Idle', 'Down', 'Offline');
+EXCEPTION WHEN duplicate_object THEN NULL;
+END $$;
+
+DO $$ BEGIN
+ CREATE TYPE "unattributedMachineTimeStatus" AS ENUM ('Open', 'Assigned', 'Dismissed');
+EXCEPTION WHEN duplicate_object THEN NULL;
+END $$;
+
+CREATE TABLE IF NOT EXISTS "workCenterDevice" (
+ "id" TEXT NOT NULL DEFAULT id('wcd'),
+ "companyId" TEXT NOT NULL,
+ "workCenterId" TEXT NOT NULL REFERENCES "workCenter"("id") ON DELETE CASCADE,
+ "integration" TEXT NOT NULL REFERENCES "integration"("id"),
+ "externalDeviceId" TEXT NOT NULL,
+ "externalSiteId" TEXT,
+ "siteTimezone" TEXT,
+ "deviceName" TEXT NOT NULL,
+ "currentState" "machineState",
+ "currentStateAt" TIMESTAMP WITH TIME ZONE,
+ "appliedThrough" TIMESTAMP WITH TIME ZONE,
+ "lastEventAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "lastManualChangeAt" TIMESTAMP WITH TIME ZONE,
+ "lastSyncedAt" TIMESTAMP WITH TIME ZONE,
+ "lastSyncError" TEXT,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "workCenterDevice_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "workCenterDevice_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "workCenterDevice_workCenter_key" UNIQUE ("workCenterId", "companyId"),
+ CONSTRAINT "workCenterDevice_device_key" UNIQUE ("integration", "externalDeviceId", "companyId")
+);
+
+CREATE INDEX IF NOT EXISTS "workCenterDevice_companyId_idx" ON "workCenterDevice" ("companyId");
+CREATE INDEX IF NOT EXISTS "workCenterDevice_integration_idx" ON "workCenterDevice" ("integration");
+CREATE INDEX IF NOT EXISTS "workCenterDevice_createdBy_idx" ON "workCenterDevice" ("createdBy");
+
+CREATE TABLE IF NOT EXISTS "machineStateChange" (
+ "id" TEXT NOT NULL DEFAULT id('msc'),
+ "companyId" TEXT NOT NULL,
+ "workCenterDeviceId" TEXT NOT NULL,
+ "workCenterId" TEXT NOT NULL REFERENCES "workCenter"("id") ON DELETE CASCADE,
+ "externalEventId" TEXT NOT NULL,
+ "state" "machineState" NOT NULL,
+ "changedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ CONSTRAINT "machineStateChange_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "machineStateChange_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "machineStateChange_event_key"
+ UNIQUE ("workCenterDeviceId", "externalEventId", "companyId")
+);
+
+CREATE INDEX IF NOT EXISTS "machineStateChange_companyId_idx" ON "machineStateChange" ("companyId");
+CREATE INDEX IF NOT EXISTS "machineStateChange_workCenter_changedAt_idx"
+ ON "machineStateChange" ("workCenterId", "changedAt");
+CREATE INDEX IF NOT EXISTS "machineStateChange_device_changedAt_idx"
+ ON "machineStateChange" ("workCenterDeviceId", "changedAt");
+
+CREATE TABLE IF NOT EXISTS "unattributedMachineTime" (
+ "id" TEXT NOT NULL DEFAULT id('umt'),
+ "companyId" TEXT NOT NULL,
+ "workCenterId" TEXT NOT NULL REFERENCES "workCenter"("id") ON DELETE CASCADE,
+ "startTime" TIMESTAMP WITH TIME ZONE NOT NULL,
+ "endTime" TIMESTAMP WITH TIME ZONE,
+ "status" "unattributedMachineTimeStatus" NOT NULL DEFAULT 'Open',
+ "productionEventId" TEXT REFERENCES "productionEvent"("id") ON DELETE SET NULL,
+ "dismissReason" TEXT,
+ "resolvedBy" TEXT REFERENCES "user"("id"),
+ "resolvedAt" TIMESTAMP WITH TIME ZONE,
+ "createdBy" TEXT NOT NULL REFERENCES "user"("id"),
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedBy" TEXT REFERENCES "user"("id"),
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ CONSTRAINT "unattributedMachineTime_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "unattributedMachineTime_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "unattributedMachineTime_dismiss_check"
+ CHECK ("status" <> 'Dismissed' OR "dismissReason" IS NOT NULL)
+);
+
+CREATE INDEX IF NOT EXISTS "unattributedMachineTime_companyId_idx" ON "unattributedMachineTime" ("companyId");
+CREATE INDEX IF NOT EXISTS "unattributedMachineTime_workCenterId_idx" ON "unattributedMachineTime" ("workCenterId");
+CREATE INDEX IF NOT EXISTS "unattributedMachineTime_productionEventId_idx" ON "unattributedMachineTime" ("productionEventId");
+CREATE INDEX IF NOT EXISTS "unattributedMachineTime_createdBy_idx" ON "unattributedMachineTime" ("createdBy");
+CREATE INDEX IF NOT EXISTS "unattributedMachineTime_open_idx"
+ ON "unattributedMachineTime" ("companyId", "workCenterId") WHERE "status" = 'Open';
+
+-- 4. The engine reads the open events of one work center
+CREATE INDEX IF NOT EXISTS "productionEvent_workCenterId_open_idx"
+ ON "productionEvent" ("workCenterId") WHERE "endTime" IS NULL;
+
+-- 5. Re-declare the work-center views so wc.* includes the new columns.
+-- DROP first, not CREATE OR REPLACE: the new wc.* columns expand before
+-- "locationName". Forked verbatim from 20260905132037_job-operation-batching.sql.
+DROP VIEW IF EXISTS "workCenters";
+CREATE VIEW "workCenters" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ wc.*,
+ l.name as "locationName",
+ d.name as "departmentName",
+ wcp.processes
+ FROM "workCenter" wc
+ LEFT JOIN "location" l
+ ON wc."locationId" = l.id
+ LEFT JOIN "department" d
+ ON wc."departmentId" = d.id
+ LEFT JOIN (
+ SELECT
+ "workCenterId",
+ array_agg("processId"::text) as processes
+ FROM "workCenterProcess" wcp
+ INNER JOIN "process" p ON wcp."processId" = p.id
+ GROUP BY "workCenterId"
+ ) wcp ON wc.id = wcp."workCenterId";
+
+DROP VIEW IF EXISTS "workCentersWithBlockingStatus";
+CREATE VIEW "workCentersWithBlockingStatus" WITH (security_invoker = true) AS
+SELECT
+ wc.*,
+ l.name AS "locationName",
+ COALESCE(
+ (SELECT COUNT(*) > 0
+ FROM "maintenanceDispatch" md
+ WHERE md."workCenterId" = wc.id
+ AND md.status = 'In Progress'
+ AND md."oeeImpact" IN ('Down', 'Planned')
+ ), false
+ ) AS "isBlocked",
+ (
+ SELECT md.id
+ FROM "maintenanceDispatch" md
+ WHERE md."workCenterId" = wc.id
+ AND md.status = 'In Progress'
+ AND md."oeeImpact" IN ('Down', 'Planned')
+ ORDER BY md."createdAt" DESC
+ LIMIT 1
+ ) AS "blockingDispatchId",
+ (
+ SELECT md."maintenanceDispatchId"
+ FROM "maintenanceDispatch" md
+ WHERE md."workCenterId" = wc.id
+ AND md.status = 'In Progress'
+ AND md."oeeImpact" IN ('Down', 'Planned')
+ ORDER BY md."createdAt" DESC
+ LIMIT 1
+ ) AS "blockingDispatchReadableId"
+FROM "workCenter" wc
+LEFT JOIN "location" l ON wc."locationId" = l.id;
diff --git a/packages/database/supabase/migrations/20261013030121_oee-provider-rls.sql b/packages/database/supabase/migrations/20261013030121_oee-provider-rls.sql
new file mode 100644
index 0000000000..531be882b9
--- /dev/null
+++ b/packages/database/supabase/migrations/20261013030121_oee-provider-rls.sql
@@ -0,0 +1,96 @@
+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.
+
+-- Ships these rules to databases where `authz sync` does not run after migrations yet.
+
+CREATE OR REPLACE FUNCTION public.sync_load_work_center_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ IF p_operation != 'INSERT' THEN RETURN; END IF;
+
+ -- Only a starting event loads: an event inserted with an endTime (an ERP
+ -- entry, an assigned interval, a closed sensor run) never does.
+ IF (p_new->>'endTime') IS NOT NULL OR (p_new->>'workCenterId') IS NULL THEN
+ RETURN;
+ END IF;
+
+ UPDATE "workCenter"
+ SET "loadedJobOperationId" = p_new->>'jobOperationId',
+ "loadedAt" = (p_new->>'startTime')::timestamptz
+ WHERE "id" = p_new->>'workCenterId'
+ AND ("loadedAt" IS NULL OR "loadedAt" <= (p_new->>'startTime')::timestamptz)
+ AND "loadedJobOperationId" IS DISTINCT FROM p_new->>'jobOperationId';
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.sync_unload_work_center_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ IF p_operation != 'UPDATE' THEN RETURN; END IF;
+ IF (p_new->>'status') NOT IN ('Done', 'Canceled') THEN RETURN; END IF;
+ IF (p_old->>'status') = (p_new->>'status') THEN RETURN; END IF;
+
+ UPDATE "workCenter"
+ SET "loadedJobOperationId" = NULL,
+ "loadedAt" = NULL
+ WHERE "loadedJobOperationId" = p_new->>'id';
+END;
+$function$;
+
+-- machineStateChange
+DO $authz$
+DECLARE p record;
+BEGIN
+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'machineStateChange' LOOP
+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'machineStateChange');
+ END LOOP;
+END
+$authz$;
+ALTER TABLE public."machineStateChange" ENABLE ROW LEVEL SECURITY;
+CREATE POLICY "SELECT" ON "public"."machineStateChange" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));
+CREATE POLICY "INSERT" ON "public"."machineStateChange" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('production_create'))::text[]));
+CREATE POLICY "UPDATE" ON "public"."machineStateChange" FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('production_update'))::text[]));
+CREATE POLICY "DELETE" ON "public"."machineStateChange" FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('production_delete'))::text[]));
+
+-- unattributedMachineTime
+DO $authz$
+DECLARE p record;
+BEGIN
+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'unattributedMachineTime' LOOP
+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'unattributedMachineTime');
+ END LOOP;
+END
+$authz$;
+ALTER TABLE public."unattributedMachineTime" ENABLE ROW LEVEL SECURITY;
+CREATE POLICY "SELECT" ON "public"."unattributedMachineTime" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));
+CREATE POLICY "INSERT" ON "public"."unattributedMachineTime" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('production_create'))::text[]));
+CREATE POLICY "UPDATE" ON "public"."unattributedMachineTime" FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('production_update'))::text[]));
+CREATE POLICY "DELETE" ON "public"."unattributedMachineTime" FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('production_delete'))::text[]));
+
+-- workCenterDevice
+DO $authz$
+DECLARE p record;
+BEGIN
+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'workCenterDevice' LOOP
+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'workCenterDevice');
+ END LOOP;
+END
+$authz$;
+ALTER TABLE public."workCenterDevice" ENABLE ROW LEVEL SECURITY;
+CREATE POLICY "SELECT" ON "public"."workCenterDevice" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));
+CREATE POLICY "INSERT" ON "public"."workCenterDevice" FOR INSERT WITH CHECK ("companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_create'))::text[]));
+CREATE POLICY "UPDATE" ON "public"."workCenterDevice" FOR UPDATE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_update'))::text[]));
+CREATE POLICY "DELETE" ON "public"."workCenterDevice" FOR DELETE USING ("companyId" = ANY ((SELECT get_companies_with_employee_permission('resources_delete'))::text[]));
+
+-- event triggers (packages/database/src/event-system/attachments.ts)
+SET lock_timeout = '5s';
+SELECT set_event_triggers('jobOperation', ARRAY['sync_finish_job_operation']::text[], ARRAY['set_shelf_life_on_operation_done', 'set_shelf_life_on_operation_started', 'sync_unload_work_center_operation']::text[], true, ARRAY['broadcast_table_changes']::text[]);
+SELECT set_event_triggers('productionEvent', ARRAY['sync_set_job_operation_in_progress']::text[], ARRAY['sync_load_work_center_operation']::text[], true, ARRAY['broadcast_table_changes']::text[]);
+SELECT set_event_triggers('unattributedMachineTime', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);
+SELECT set_event_triggers('workCenterDevice', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['broadcast_table_changes']::text[]);
+RESET lock_timeout;
diff --git a/packages/database/supabase/migrations/20261013170425_unattributed-time-queue.sql b/packages/database/supabase/migrations/20261013170425_unattributed-time-queue.sql
new file mode 100644
index 0000000000..3e37ab4fcd
--- /dev/null
+++ b/packages/database/supabase/migrations/20261013170425_unattributed-time-queue.sql
@@ -0,0 +1,56 @@
+-- Unattributed time is a review queue, not a record. A row leaves the queue
+-- when a supervisor assigns it (it becomes a Machine productionEvent, which is
+-- the record), when they dismiss it, or 30 days after the machine stopped. So
+-- the row needs no status, and nothing points back at the event.
+
+-- Rows already answered leave the queue now.
+DELETE FROM "unattributedMachineTime" WHERE "status" <> 'Open';
+
+DROP INDEX IF EXISTS "unattributedMachineTime_open_idx";
+DROP INDEX IF EXISTS "unattributedMachineTime_productionEventId_idx";
+
+ALTER TABLE "unattributedMachineTime"
+ DROP CONSTRAINT IF EXISTS "unattributedMachineTime_dismiss_check",
+ DROP COLUMN IF EXISTS "status",
+ DROP COLUMN IF EXISTS "productionEventId",
+ DROP COLUMN IF EXISTS "dismissReason",
+ DROP COLUMN IF EXISTS "resolvedBy",
+ DROP COLUMN IF EXISTS "resolvedAt";
+
+DROP TYPE IF EXISTS "unattributedMachineTimeStatus";
+
+-- The queue reads newest first per company; retention reads the stop time.
+CREATE INDEX IF NOT EXISTS "unattributedMachineTime_companyId_startTime_idx"
+ ON "unattributedMachineTime" ("companyId", "startTime" DESC);
+CREATE INDEX IF NOT EXISTS "unattributedMachineTime_endTime_idx"
+ ON "unattributedMachineTime" ("endTime")
+ WHERE "endTime" IS NOT NULL;
+
+-- Retention, daily. A row still running has no endTime and stays: the sync
+-- owns it until the machine stops.
+CREATE OR REPLACE FUNCTION util.purge_unattributed_machine_time()
+RETURNS void
+LANGUAGE sql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+ DELETE FROM "unattributedMachineTime"
+ WHERE "endTime" < NOW() - INTERVAL '30 days';
+$$;
+
+REVOKE ALL ON FUNCTION util.purge_unattributed_machine_time() FROM PUBLIC;
+
+DO $$
+BEGIN
+ IF EXISTS (
+ SELECT 1 FROM cron.job WHERE jobname = 'unattributed-machine-time-retention'
+ ) THEN
+ PERFORM cron.unschedule('unattributed-machine-time-retention');
+ END IF;
+ PERFORM cron.schedule(
+ 'unattributed-machine-time-retention',
+ '23 4 * * *',
+ 'SELECT util.purge_unattributed_machine_time();'
+ );
+END;
+$$;
diff --git a/packages/database/supabase/migrations/20261013172620_loaded-operation-without-fk.sql b/packages/database/supabase/migrations/20261013172620_loaded-operation-without-fk.sql
new file mode 100644
index 0000000000..29d2940011
--- /dev/null
+++ b/packages/database/supabase/migrations/20261013172620_loaded-operation-without-fk.sql
@@ -0,0 +1,8 @@
+-- workCenter."loadedJobOperationId" keeps no foreign key. With one, PostgREST
+-- saw two relationships between jobOperation and workCenter (this pointer and
+-- jobOperation."workCenterId"), so every existing embed of one from the other
+-- (`jobOperation` → `workCenter(name)`, …) failed with PGRST201. The pointer is
+-- cleared by the sync_unload_work_center_operation interceptor instead: when
+-- the operation becomes Done or Canceled, and when it is deleted.
+ALTER TABLE "workCenter"
+ DROP CONSTRAINT IF EXISTS "workCenter_loadedJobOperationId_fkey";
diff --git a/packages/database/supabase/migrations/20261013173718_unload-on-operation-delete.sql b/packages/database/supabase/migrations/20261013173718_unload-on-operation-delete.sql
new file mode 100644
index 0000000000..bdcf587785
--- /dev/null
+++ b/packages/database/supabase/migrations/20261013173718_unload-on-operation-delete.sql
@@ -0,0 +1,30 @@
+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.
+
+-- Ships these rules to databases where `authz sync` does not run after migrations yet.
+
+CREATE OR REPLACE FUNCTION public.sync_unload_work_center_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ -- A deleted operation unloads too: the pointer has no foreign key, because
+ -- one would make PostgREST embeds of workCenter from jobOperation ambiguous.
+ IF p_operation = 'DELETE' THEN
+ UPDATE "workCenter"
+ SET "loadedJobOperationId" = NULL,
+ "loadedAt" = NULL
+ WHERE "loadedJobOperationId" = p_old->>'id';
+ RETURN;
+ END IF;
+
+ IF p_operation != 'UPDATE' THEN RETURN; END IF;
+ IF (p_new->>'status') NOT IN ('Done', 'Canceled') THEN RETURN; END IF;
+ IF (p_old->>'status') = (p_new->>'status') THEN RETURN; END IF;
+
+ UPDATE "workCenter"
+ SET "loadedJobOperationId" = NULL,
+ "loadedAt" = NULL
+ WHERE "loadedJobOperationId" = p_new->>'id';
+END;
+$function$;
diff --git a/packages/database/supabase/migrations/20261013191915_oee-tenancy-and-retention.sql b/packages/database/supabase/migrations/20261013191915_oee-tenancy-and-retention.sql
new file mode 100644
index 0000000000..dd6447b528
--- /dev/null
+++ b/packages/database/supabase/migrations/20261013191915_oee-tenancy-and-retention.sql
@@ -0,0 +1,53 @@
+-- A device maps to a work center of its OWN company. The single-column FK let
+-- a caller-supplied work center id from another company through, and the
+-- sync would then write Machine events and unattributed time against that
+-- foreign work center. workCenter has UNIQUE (id, companyId), so the FK can
+-- carry the company. It REPLACES the old one: two FKs to workCenter would
+-- give PostgREST two relationships and make embeds ambiguous (PGRST201).
+ALTER TABLE "workCenterDevice"
+ DROP CONSTRAINT IF EXISTS "workCenterDevice_workCenterId_fkey";
+ALTER TABLE "workCenterDevice"
+ ADD CONSTRAINT "workCenterDevice_workCenterId_fkey"
+ FOREIGN KEY ("workCenterId", "companyId")
+ REFERENCES "workCenter" ("id", "companyId") ON DELETE CASCADE;
+
+-- machineStateChange keeps every state change the sync reads. The engine
+-- only reads rows after the device's appliedThrough, so old rows are dead
+-- data, and a remap or unmap leaves the old device's rows with no device.
+CREATE INDEX IF NOT EXISTS "machineStateChange_changedAt_idx"
+ ON "machineStateChange" ("changedAt");
+
+-- Retention, daily, next to the unattributed time purge. 30 days is far past
+-- anything a sync re-reads (the cursor overlap is 10 minutes, a first sync
+-- reaches 24 hours back).
+CREATE OR REPLACE FUNCTION util.purge_machine_state_changes()
+RETURNS void
+LANGUAGE sql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+ DELETE FROM "machineStateChange" m
+ WHERE m."changedAt" < NOW() - INTERVAL '30 days'
+ OR NOT EXISTS (
+ SELECT 1 FROM "workCenterDevice" d
+ WHERE d."id" = m."workCenterDeviceId"
+ AND d."companyId" = m."companyId"
+ );
+$$;
+
+REVOKE ALL ON FUNCTION util.purge_machine_state_changes() FROM PUBLIC;
+
+DO $$
+BEGIN
+ IF EXISTS (
+ SELECT 1 FROM cron.job WHERE jobname = 'machine-state-change-retention'
+ ) THEN
+ PERFORM cron.unschedule('machine-state-change-retention');
+ END IF;
+ PERFORM cron.schedule(
+ 'machine-state-change-retention',
+ '29 4 * * *',
+ 'SELECT util.purge_machine_state_changes();'
+ );
+END;
+$$;
diff --git a/packages/database/supabase/migrations/20261013194325_oee-read-only-and-tenant-load.sql b/packages/database/supabase/migrations/20261013194325_oee-read-only-and-tenant-load.sql
new file mode 100644
index 0000000000..5815323f2c
--- /dev/null
+++ b/packages/database/supabase/migrations/20261013194325_oee-read-only-and-tenant-load.sql
@@ -0,0 +1,72 @@
+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.
+
+-- Ships these rules to databases where `authz sync` does not run after migrations yet.
+
+CREATE OR REPLACE FUNCTION public.sync_load_work_center_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ IF p_operation != 'INSERT' THEN RETURN; END IF;
+
+ -- Only a starting event loads: an event inserted with an endTime (an ERP
+ -- entry, an assigned interval, a closed sensor run) never does.
+ IF (p_new->>'endTime') IS NOT NULL OR (p_new->>'workCenterId') IS NULL THEN
+ RETURN;
+ END IF;
+
+ -- This runs as the owner (the dispatchers are SECURITY DEFINER), and the
+ -- event's workCenterId and jobOperationId are single-column FKs: an event
+ -- may only load its OWN company's operation onto its own company's work
+ -- center, or another company's sensor time would land on it.
+ UPDATE "workCenter"
+ SET "loadedJobOperationId" = p_new->>'jobOperationId',
+ "loadedAt" = (p_new->>'startTime')::timestamptz
+ WHERE "id" = p_new->>'workCenterId'
+ AND "companyId" = p_new->>'companyId'
+ AND ("loadedAt" IS NULL OR "loadedAt" <= (p_new->>'startTime')::timestamptz)
+ AND "loadedJobOperationId" IS DISTINCT FROM p_new->>'jobOperationId'
+ AND EXISTS (
+ SELECT 1 FROM "jobOperation"
+ WHERE "id" = p_new->>'jobOperationId'
+ AND "companyId" = p_new->>'companyId'
+ );
+END;
+$function$;
+
+-- machineStateChange
+DO $authz$
+DECLARE p record;
+BEGIN
+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'machineStateChange' LOOP
+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'machineStateChange');
+ END LOOP;
+END
+$authz$;
+ALTER TABLE public."machineStateChange" ENABLE ROW LEVEL SECURITY;
+CREATE POLICY "SELECT" ON "public"."machineStateChange" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));
+
+-- unattributedMachineTime
+DO $authz$
+DECLARE p record;
+BEGIN
+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'unattributedMachineTime' LOOP
+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'unattributedMachineTime');
+ END LOOP;
+END
+$authz$;
+ALTER TABLE public."unattributedMachineTime" ENABLE ROW LEVEL SECURITY;
+CREATE POLICY "SELECT" ON "public"."unattributedMachineTime" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));
+
+-- workCenterDevice
+DO $authz$
+DECLARE p record;
+BEGIN
+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'workCenterDevice' LOOP
+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'workCenterDevice');
+ END LOOP;
+END
+$authz$;
+ALTER TABLE public."workCenterDevice" ENABLE ROW LEVEL SECURITY;
+CREATE POLICY "SELECT" ON "public"."workCenterDevice" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));
diff --git a/packages/database/supabase/migrations/20261013201722_oee-company-scoped-work-center.sql b/packages/database/supabase/migrations/20261013201722_oee-company-scoped-work-center.sql
new file mode 100644
index 0000000000..5ef757536f
--- /dev/null
+++ b/packages/database/supabase/migrations/20261013201722_oee-company-scoped-work-center.sql
@@ -0,0 +1,26 @@
+-- machineStateChange and unattributedMachineTime carry the work center the
+-- sync read from the device. Their FKs carry the company too, like
+-- workCenterDevice's (20261013191915). Each REPLACES the single-column FK:
+-- two FKs to workCenter would make PostgREST embeds ambiguous (PGRST201).
+ALTER TABLE "machineStateChange"
+ DROP CONSTRAINT IF EXISTS "machineStateChange_workCenterId_fkey";
+ALTER TABLE "machineStateChange"
+ ADD CONSTRAINT "machineStateChange_workCenterId_fkey"
+ FOREIGN KEY ("workCenterId", "companyId")
+ REFERENCES "workCenter" ("id", "companyId") ON DELETE CASCADE;
+
+ALTER TABLE "unattributedMachineTime"
+ DROP CONSTRAINT IF EXISTS "unattributedMachineTime_workCenterId_fkey";
+ALTER TABLE "unattributedMachineTime"
+ ADD CONSTRAINT "unattributedMachineTime_workCenterId_fkey"
+ FOREIGN KEY ("workCenterId", "companyId")
+ REFERENCES "workCenter" ("id", "companyId") ON DELETE CASCADE;
+
+-- Every FK has an index.
+CREATE INDEX IF NOT EXISTS "workCenterDevice_updatedBy_idx"
+ ON "workCenterDevice" ("updatedBy");
+CREATE INDEX IF NOT EXISTS "unattributedMachineTime_updatedBy_idx"
+ ON "unattributedMachineTime" ("updatedBy");
+
+-- ("companyId", "startTime" DESC) from 20261013170425 covers it.
+DROP INDEX IF EXISTS "unattributedMachineTime_companyId_idx";
diff --git a/packages/database/supabase/migrations/20261013202702_unload-on-work-center-move.sql b/packages/database/supabase/migrations/20261013202702_unload-on-work-center-move.sql
new file mode 100644
index 0000000000..3931fb02df
--- /dev/null
+++ b/packages/database/supabase/migrations/20261013202702_unload-on-work-center-move.sql
@@ -0,0 +1,42 @@
+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.
+
+-- Ships these rules to databases where `authz sync` does not run after migrations yet.
+
+CREATE OR REPLACE FUNCTION public.sync_unload_work_center_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ -- A deleted operation unloads too: the pointer has no foreign key, because
+ -- one would make PostgREST embeds of workCenter from jobOperation ambiguous.
+ IF p_operation = 'DELETE' THEN
+ UPDATE "workCenter"
+ SET "loadedJobOperationId" = NULL,
+ "loadedAt" = NULL
+ WHERE "loadedJobOperationId" = p_old->>'id';
+ RETURN;
+ END IF;
+
+ -- An operation moved to another work center leaves the old one: its sensor
+ -- time there is no longer this operation's.
+ IF p_operation = 'UPDATE'
+ AND (p_old->>'workCenterId') IS DISTINCT FROM (p_new->>'workCenterId') THEN
+ UPDATE "workCenter"
+ SET "loadedJobOperationId" = NULL,
+ "loadedAt" = NULL
+ WHERE "id" = p_old->>'workCenterId'
+ AND "companyId" = p_old->>'companyId'
+ AND "loadedJobOperationId" = p_new->>'id';
+ END IF;
+
+ IF p_operation != 'UPDATE' THEN RETURN; END IF;
+ IF (p_new->>'status') NOT IN ('Done', 'Canceled') THEN RETURN; END IF;
+ IF (p_old->>'status') = (p_new->>'status') THEN RETURN; END IF;
+
+ UPDATE "workCenter"
+ SET "loadedJobOperationId" = NULL,
+ "loadedAt" = NULL
+ WHERE "loadedJobOperationId" = p_new->>'id';
+END;
+$function$;
diff --git a/packages/database/supabase/migrations/20261013204442_skip-load-pointer-changes.sql b/packages/database/supabase/migrations/20261013204442_skip-load-pointer-changes.sql
new file mode 100644
index 0000000000..f1c01ae312
--- /dev/null
+++ b/packages/database/supabase/migrations/20261013204442_skip-load-pointer-changes.sql
@@ -0,0 +1,561 @@
+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.
+
+-- Ships these rules to databases where `authz sync` does not run after migrations yet.
+
+CREATE OR REPLACE FUNCTION public.broadcast_reference_changes()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO ''
+AS $function$
+DECLARE
+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding', 'loadedJobOperationId', 'loadedAt'];
+ changed_rows TEXT;
+ rec RECORD;
+BEGIN
+ -- A database without Supabase Realtime (a self-hosted install that does not
+ -- run it) has nothing to send to: the write must still succeed.
+ IF to_regprocedure('realtime.send(jsonb,text,text,boolean)') IS NULL THEN
+ RETURN NULL;
+ END IF;
+
+ -- Tells the company's clients that a reference list changed (one shared topic, company:<companyId>:reference).
+ -- Statement-level (attach_statement_handler): one message per company per
+ -- statement, whatever the row count. No row data leaves the database: a client
+ -- re-reads what it needs through PostgREST, so table RLS still decides what it sees.
+ IF TG_OP = 'UPDATE' THEN
+ -- A row whose only changes are in ignored_columns drops out (the rule
+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).
+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n
+ EXCEPT
+ SELECT to_jsonb(o) - $1 FROM batched_old o';
+ ELSIF TG_OP = 'DELETE' THEN
+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';
+ ELSE
+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';
+ END IF;
+
+ FOR rec IN EXECUTE format(
+ 'SELECT DISTINCT c->>''companyId'' AS company_id FROM (%s) changed',
+ changed_rows
+ ) USING ignored_columns
+ LOOP
+ CONTINUE WHEN rec.company_id IS NULL;
+ PERFORM realtime.send(
+ jsonb_build_object('table', TG_TABLE_NAME, 'op', TG_OP),
+ TG_OP,
+ 'company:' || rec.company_id || ':reference',
+ true
+ );
+ END LOOP;
+ RETURN NULL;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.broadcast_table_changes()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO ''
+AS $function$
+DECLARE
+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding', 'loadedJobOperationId', 'loadedAt'];
+ -- Tables whose rows hang off a record through another table. Each hop is
+ -- [column of the row, table it points at, column to read there]: its value is
+ -- added to the message under that column's name, so a job page can follow
+ -- "jobId" on a table that only knows its operation.
+ -- A hop with a fourth element looks the other way: the rows of that table
+ -- whose fourth column holds this row's value ("id" is the row's own id). A
+ -- payment has no invoice column; its settlements name the invoices it pays.
+ -- packages/database/src/realtime-tables.ts lists the same columns
+ -- (REALTIME_ANCESTOR_COLUMNS; realtime-tables.test.ts keeps them equal).
+ ancestors CONSTANT JSONB := '{
+ "productionEvent": [["jobOperationId", "jobOperation", "jobId"]],
+ "jobOperationStep": [["operationId", "jobOperation", "jobId"]],
+ "jobOperationStepRecord": [["jobOperationStepId", "jobOperationStep", "operationId"], ["operationId", "jobOperation", "jobId"]],
+ "trackedActivity": [["sourceDocumentId", "productionEvent", "jobOperationId"]],
+ "payment": [["id", "invoiceSettlement", "targetSalesInvoiceId", "paymentId"], ["id", "invoiceSettlement", "targetPurchaseInvoiceId", "paymentId"]]
+ }';
+ changed_rows TEXT;
+ parent_rows TEXT;
+ parents JSONB;
+ sent_columns TEXT[];
+ found JSONB;
+ hop JSONB;
+ rec RECORD;
+BEGIN
+ -- A database without Supabase Realtime (a self-hosted install that does not
+ -- run it) has nothing to send to: the write must still succeed.
+ IF to_regprocedure('realtime.send(jsonb,text,text,boolean)') IS NULL THEN
+ RETURN NULL;
+ END IF;
+
+ -- Tells the company's clients which rows of this table changed (topic company:<companyId>:<table>).
+ -- Statement-level (attach_statement_handler): one message per company per
+ -- statement, whatever the row count. No row data leaves the database: a client
+ -- re-reads what it needs through PostgREST, so table RLS still decides what it sees.
+ -- The columns a message may name: the table's foreign keys, and the columns
+ -- its ancestors add. A column that merely ends in "Id" is the row's own data
+ -- (a part number in "readableId", an order number, a tax id) and stays here.
+ SELECT coalesce(array_agg(DISTINCT a.attname::text), ARRAY[]::text[])
+ INTO sent_columns
+ FROM pg_catalog.pg_constraint k
+ JOIN pg_catalog.pg_attribute a
+ ON a.attrelid = k.conrelid AND a.attnum = ANY (k.conkey)
+ WHERE k.conrelid = TG_RELID AND k.contype = 'f';
+ IF ancestors ? TG_TABLE_NAME THEN
+ sent_columns := sent_columns || ARRAY(
+ SELECT value->>2 FROM jsonb_array_elements(ancestors->TG_TABLE_NAME)
+ );
+ END IF;
+
+ IF TG_OP = 'UPDATE' THEN
+ -- A row whose only changes are in ignored_columns drops out (the rule
+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).
+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n
+ EXCEPT
+ SELECT to_jsonb(o) - $1 FROM batched_old o';
+ -- The rows as they were, too: a row moved to another parent concerns the
+ -- parent it left as much as the one it joined.
+ parent_rows := '(' || changed_rows || ')
+ UNION ALL
+ (SELECT to_jsonb(o) - $1 FROM batched_old o
+ EXCEPT
+ SELECT to_jsonb(n) - $1 FROM batched_new n)';
+ ELSIF TG_OP = 'DELETE' THEN
+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';
+ parent_rows := changed_rows;
+ ELSE
+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';
+ parent_rows := changed_rows;
+ END IF;
+
+ FOR rec IN EXECUTE format(
+ -- implementationHub has no companyId: its id is the company id.
+ 'WITH keyed AS (
+ SELECT coalesce(c->>''companyId'',
+ CASE WHEN $2::text = ''implementationHub'' THEN c->>''id'' END) AS company_id,
+ c
+ FROM (%1$s) changed
+ ),
+ related AS (
+ SELECT coalesce(c->>''companyId'',
+ CASE WHEN $2::text = ''implementationHub'' THEN c->>''id'' END) AS company_id,
+ c
+ FROM (%2$s) changed
+ )
+ SELECT k.company_id,
+ count(*) AS n,
+ -- itemSupersession has no id: its row belongs to the item it describes.
+ jsonb_agg(coalesce(k.c->''id'', k.c->''itemId''))
+ FILTER (WHERE k.c ? ''id'' OR k.c ? ''itemId'') AS ids,
+ -- The records these rows belong to: each "<name>Id" column and its
+ -- values (narrowed to the foreign keys before sending), so a page showing one job (or quote, or order) can ignore
+ -- changes to another''s rows. A column with more than 20 values is
+ -- left out, and a client treats a missing column as "may concern me".
+ -- Only computed for a statement small enough to list its ids.
+ CASE WHEN count(*) <= 100 THEN (
+ SELECT jsonb_object_agg(p.key, p.vals)
+ FROM (
+ SELECT e.key, jsonb_agg(DISTINCT e.value) AS vals
+ FROM related k2, jsonb_each(k2.c) e
+ WHERE k2.company_id = k.company_id
+ AND e.key LIKE ''%%Id'' AND e.key <> ''companyId''
+ AND jsonb_typeof(e.value) = ''string''
+ GROUP BY e.key
+ HAVING count(DISTINCT e.value) <= 20
+ ) p
+ ) END AS parents
+ FROM keyed k
+ GROUP BY k.company_id',
+ changed_rows, parent_rows
+ ) USING ignored_columns, TG_TABLE_NAME
+ LOOP
+ CONTINUE WHEN rec.company_id IS NULL;
+
+ parents := rec.parents;
+ IF parents IS NOT NULL AND ancestors ? TG_TABLE_NAME THEN
+ FOR hop IN SELECT value FROM jsonb_array_elements(ancestors->TG_TABLE_NAME) LOOP
+ found := CASE WHEN hop->>0 = 'id' THEN rec.ids ELSE parents->(hop->>0) END;
+ -- A column that was left out (no value, or too many) leaves its
+ -- ancestor out as well: the client then takes the change as its own.
+ CONTINUE WHEN found IS NULL;
+ EXECUTE format(
+ 'SELECT jsonb_agg(DISTINCT %1$I) FROM public.%2$I
+ WHERE "companyId" = $1 AND %1$I IS NOT NULL
+ AND %3$I IN (SELECT jsonb_array_elements_text($2))',
+ hop->>2, hop->>1, coalesce(hop->>3, 'id')
+ ) INTO found USING rec.company_id, found;
+ IF found IS NOT NULL THEN
+ parents := parents || jsonb_build_object(hop->>2, found);
+ ELSIF jsonb_array_length(hop) = 4 THEN
+ -- Looked for and not there: no such record has this row.
+ parents := parents || jsonb_build_object(hop->>2, '[]'::jsonb);
+ END IF;
+ END LOOP;
+ END IF;
+ -- An ancestor hop may read a column that is not sent (a polymorphic
+ -- "sourceDocumentId"), so the narrowing comes last.
+ IF parents IS NOT NULL THEN
+ parents := coalesce(
+ (SELECT jsonb_object_agg(e.key, e.value)
+ FROM jsonb_each(parents) e
+ WHERE e.key = ANY (sent_columns)),
+ '{}'::jsonb
+ );
+ END IF;
+ PERFORM realtime.send(
+ jsonb_build_object(
+ 'table', TG_TABLE_NAME,
+ 'op', TG_OP,
+ -- null = "many rows changed, or the table has no id: resync"
+ 'ids', CASE WHEN rec.n <= 100 THEN rec.ids END,
+ 'parents', parents
+ ),
+ TG_OP,
+ 'company:' || rec.company_id || ':' || TG_TABLE_NAME,
+ true
+ );
+ END LOOP;
+ RETURN NULL;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.broadcast_user_changes()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO ''
+AS $function$
+DECLARE
+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding', 'loadedJobOperationId', 'loadedAt'];
+ changed_rows TEXT;
+ rec RECORD;
+BEGIN
+ -- A database without Supabase Realtime (a self-hosted install that does not
+ -- run it) has nothing to send to: the write must still succeed.
+ IF to_regprocedure('realtime.send(jsonb,text,text,boolean)') IS NULL THEN
+ RETURN NULL;
+ END IF;
+
+ -- Tells one user which of their rows changed (topic user:<userId>:<table>).
+ -- Statement-level (attach_statement_handler): one message per user per
+ -- statement, whatever the row count. No row data leaves the database: a client
+ -- re-reads what it needs through PostgREST, so table RLS still decides what it sees.
+ IF TG_OP = 'UPDATE' THEN
+ -- A row whose only changes are in ignored_columns drops out (the rule
+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).
+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n
+ EXCEPT
+ SELECT to_jsonb(o) - $1 FROM batched_old o';
+ ELSIF TG_OP = 'DELETE' THEN
+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';
+ ELSE
+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';
+ END IF;
+
+ FOR rec IN EXECUTE format(
+ 'SELECT c->>''userId'' AS user_id,
+ count(*) AS n,
+ jsonb_agg(c->''id'') FILTER (WHERE c ? ''id'') AS ids
+ FROM (%s) changed
+ GROUP BY 1',
+ changed_rows
+ ) USING ignored_columns
+ LOOP
+ CONTINUE WHEN rec.user_id IS NULL;
+ PERFORM realtime.send(
+ jsonb_build_object(
+ 'table', TG_TABLE_NAME,
+ 'op', TG_OP,
+ 'ids', CASE WHEN rec.n <= 100 THEN rec.ids END
+ ),
+ TG_OP,
+ 'user:' || rec.user_id || ':' || TG_TABLE_NAME,
+ true
+ );
+ END LOOP;
+ RETURN NULL;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.dispatch_event_batch()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pgmq', 'extensions'
+AS $function$
+DECLARE
+ sub RECORD;
+ msg_batch JSONB[];
+ rec_company_id TEXT;
+ has_subs BOOLEAN;
+ current_actor_id TEXT;
+ current_workflow_run_id TEXT;
+ pk_columns TEXT[];
+ pk_join TEXT;
+ record_id_expr TEXT;
+ query_text TEXT;
+ did_enqueue BOOLEAN := FALSE;
+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding', 'loadedJobOperationId', 'loadedAt'];
+BEGIN
+ current_actor_id := auth.uid()::TEXT;
+ current_workflow_run_id :=
+ (nullif(current_setting('request.jwt.claims', true), '')::jsonb)->>'workflow_run_id';
+ IF TG_OP = 'DELETE' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_old t LIMIT 1;
+ ELSIF TG_OP = 'INSERT' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ ELSE
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ END IF;
+
+ IF rec_company_id IS NULL THEN RETURN NULL; END IF;
+
+ SELECT EXISTS (
+ SELECT 1 FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ AND ("handlerType" NOT IN ('SYNC','WEBHOOK','WORKFLOW')
+ OR current_setting('app.sync_in_progress', true) IS DISTINCT FROM 'true')
+ ) INTO has_subs;
+
+ IF NOT has_subs THEN RETURN NULL; END IF;
+
+ -- Looked up only once a subscription exists: almost no company subscribes
+ -- to most tables, and this catalog read ran on every write statement.
+ pk_columns := public.get_primary_key_columns(TG_TABLE_NAME);
+
+ -- Pair UPDATE rows on the full key: single-column pairing cross-joins rows
+ -- on tables with composite identity.
+ SELECT string_agg(format('n.%I = o.%I', col, col), ' AND ')
+ INTO pk_join
+ FROM unnest(pk_columns) AS col;
+
+ -- recordId names one row. "id" does that wherever it is part of the key
+ -- ((id, companyId) tables); a primary key without one is every column joined
+ -- by ':', since a single column of it is shared by many rows. A table with no
+ -- primary key keeps the one column it always sent: the audit log files
+ -- itemPlanning (unique on itemId + locationId) under its itemId.
+ -- %1$s is the row alias.
+ IF 'id' = ANY(pk_columns) THEN
+ record_id_expr := '%1$s."id"::TEXT';
+ ELSIF EXISTS (
+ SELECT 1 FROM pg_index WHERE indrelid = TG_RELID AND indisprimary
+ ) THEN
+ SELECT 'concat_ws('':'', ' || string_agg(format('%%1$s.%I::TEXT', col), ', ') || ')'
+ INTO record_id_expr
+ FROM unnest(pk_columns) AS col;
+ ELSE
+ record_id_expr := format('%%1$s.%I::TEXT', public.get_primary_key_column(TG_TABLE_NAME));
+ END IF;
+
+ FOR sub IN
+ SELECT * FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ AND ("handlerType" NOT IN ('SYNC','WEBHOOK','WORKFLOW')
+ OR current_setting('app.sync_in_progress', true) IS DISTINCT FROM 'true')
+ LOOP
+
+ IF TG_OP = 'INSERT' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''workflowRunId'', $10,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', %s,
+ ''new'', row_to_json(t)::jsonb,
+ ''old'', null,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_new t
+ WHERE t."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
+ ', format(record_id_expr, 't'));
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
+ current_workflow_run_id;
+
+ ELSIF TG_OP = 'DELETE' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''workflowRunId'', $10,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', %s,
+ ''new'', null,
+ ''old'', row_to_json(t)::jsonb,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_old t
+ WHERE t."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
+ ', format(record_id_expr, 't'));
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
+ current_workflow_run_id;
+
+ ELSIF TG_OP = 'UPDATE' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''workflowRunId'', $10,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', %s,
+ ''new'', row_to_json(n)::jsonb,
+ ''old'', row_to_json(o)::jsonb,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_new n
+ JOIN batched_old o ON %s
+ WHERE n."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(n)::jsonb @> $9)
+ AND (NOT $11 OR (to_jsonb(n) - $12) IS DISTINCT FROM (to_jsonb(o) - $12))
+ ', format(record_id_expr, 'n'), pk_join);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
+ current_workflow_run_id,
+ sub."handlerType" IN ('AUDIT', 'SEARCH', 'EMBEDDING'),
+ ignored_columns;
+ END IF;
+
+ IF msg_batch IS NOT NULL AND array_length(msg_batch, 1) > 0 THEN
+ PERFORM pgmq.send_batch('event_system', msg_batch);
+ did_enqueue := TRUE;
+ END IF;
+
+ END LOOP;
+
+ -- Wake the Inngest drainer once per transaction: the GUC is txn-local, so a
+ -- bulk import posts a single doorbell instead of one per statement.
+ IF did_enqueue
+ AND current_setting('carbon.event_wake_sent', true) IS DISTINCT FROM 'true' THEN
+ PERFORM util.wake_event_queue();
+ PERFORM set_config('carbon.event_wake_sent', 'true', true);
+ END IF;
+
+ RETURN NULL;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.log_table_changes()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO ''
+AS $function$
+DECLARE
+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding', 'loadedJobOperationId', 'loadedAt'];
+ changed_rows TEXT;
+BEGIN
+ -- Records which rows of this table changed, in public."tableChange", so a
+ -- client that kept a copy of a list can ask "what changed since I last
+ -- looked?" (table_changes_since) and re-read only those rows instead of the
+ -- whole table. A broadcast tells an open tab the same thing; this is for the
+ -- tab that was closed, or disconnected, when it happened.
+ IF TG_OP = 'UPDATE' THEN
+ -- A row whose only changes are in ignored_columns drops out (the rule
+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).
+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n
+ EXCEPT
+ SELECT to_jsonb(o) - $1 FROM batched_old o';
+ ELSIF TG_OP = 'DELETE' THEN
+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';
+ ELSE
+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';
+ END IF;
+
+ EXECUTE format(
+ -- One log row per changed row. Past 100 rows in one statement, a single row
+ -- with a null "rowId" says "this table changed a lot: read it again".
+ -- itemSupersession has no id: its row belongs to the item it describes.
+ 'INSERT INTO public."tableChange" ("companyId", "table", "rowId")
+ SELECT DISTINCT company_id, $2::text, CASE WHEN n <= 100 THEN row_id END
+ FROM (
+ SELECT c->>''companyId'' AS company_id,
+ coalesce(c->>''id'', c->>''itemId'') AS row_id,
+ count(*) OVER (PARTITION BY c->>''companyId'') AS n
+ FROM (%s) changed
+ ) rows
+ WHERE company_id IS NOT NULL',
+ changed_rows
+ ) USING ignored_columns, TG_TABLE_NAME;
+ RETURN NULL;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.log_user_changes()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO ''
+AS $function$
+DECLARE
+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding', 'loadedJobOperationId', 'loadedAt'];
+ changed_rows TEXT;
+BEGIN
+ -- A person's name and avatar live on the global "user" row, which has no
+ -- company. Each company that person belongs to shows them in its people list
+ -- (the employees view), so a change is logged once per company, as a change
+ -- to that company's "employee" row.
+ IF TG_OP = 'UPDATE' THEN
+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n
+ EXCEPT
+ SELECT to_jsonb(o) - $1 FROM batched_old o';
+ ELSIF TG_OP = 'DELETE' THEN
+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';
+ ELSE
+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';
+ END IF;
+
+ EXECUTE format(
+ 'INSERT INTO public."tableChange" ("companyId", "table", "rowId")
+ SELECT DISTINCT m."companyId", ''employee'', changed.c->>''id''
+ FROM (%s) changed
+ JOIN public."userToCompany" m ON m."userId" = changed.c->>''id''',
+ changed_rows
+ ) USING ignored_columns;
+ RETURN NULL;
+END;
+$function$;
diff --git a/packages/database/supabase/migrations/20261013233811_unattributed-machine-time-local-dates.sql b/packages/database/supabase/migrations/20261013233811_unattributed-machine-time-local-dates.sql
new file mode 100644
index 0000000000..36d485856c
--- /dev/null
+++ b/packages/database/supabase/migrations/20261013233811_unattributed-machine-time-local-dates.sql
@@ -0,0 +1,22 @@
+-- The Unattributed Time list shows each row's times in its work center's
+-- location timezone, but its date filters cut days in the company timezone.
+-- When the two differ, a row shown as 9 PM on the 12th matched a filter for
+-- the 13th. This view gives each row its start and end date in the location's
+-- timezone (else the company's, else UTC: the precedence of
+-- getLocationTimeZone), so the list and its review queue filter on the dates
+-- the list shows.
+CREATE OR REPLACE VIEW "unattributedMachineTimes" WITH (SECURITY_INVOKER = true) AS
+SELECT
+ u.*,
+ (u."startTime" AT TIME ZONE tz.name)::date AS "startDate",
+ (u."endTime" AT TIME ZONE tz.name)::date AS "endDate"
+FROM "unattributedMachineTime" u
+LEFT JOIN "workCenter" w
+ ON w."id" = u."workCenterId" AND w."companyId" = u."companyId"
+LEFT JOIN "location" l
+ ON l."id" = w."locationId" AND l."companyId" = u."companyId"
+LEFT JOIN "company" c
+ ON c."id" = u."companyId"
+CROSS JOIN LATERAL (
+ SELECT COALESCE(NULLIF(l."timezone", ''), NULLIF(c."timezone", ''), 'UTC') AS name
+) tz;
diff --git a/packages/database/supabase/migrations/20261014010130_work-center-load-history.sql b/packages/database/supabase/migrations/20261014010130_work-center-load-history.sql
new file mode 100644
index 0000000000..68cc42f363
--- /dev/null
+++ b/packages/database/supabase/migrations/20261014010130_work-center-load-history.sql
@@ -0,0 +1,71 @@
+-- Which operation was loaded on a work center, and when. The pointer
+-- workCenter."loadedJobOperationId" holds only the current load, so a sensor
+-- run reported after the load changed could not be given to the operation
+-- loaded when it ran. The load and unload interceptors write this history;
+-- the OEE sync reads it. Rows are deleted 7 days after they are unloaded.
+--
+-- "jobOperationId" has no foreign key, like the pointer: a table with keys to
+-- both workCenter and jobOperation can make PostgREST embeds between the two
+-- ambiguous (PGRST201).
+CREATE TABLE IF NOT EXISTS "workCenterLoad" (
+ "id" TEXT NOT NULL DEFAULT id('wcl'),
+ "companyId" TEXT NOT NULL,
+ "workCenterId" TEXT NOT NULL,
+ "jobOperationId" TEXT NOT NULL,
+ "loadedAt" TIMESTAMP WITH TIME ZONE NOT NULL,
+ "unloadedAt" TIMESTAMP WITH TIME ZONE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ CONSTRAINT "workCenterLoad_pkey" PRIMARY KEY ("id", "companyId"),
+ CONSTRAINT "workCenterLoad_companyId_fkey" FOREIGN KEY ("companyId")
+ REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "workCenterLoad_workCenterId_fkey"
+ FOREIGN KEY ("workCenterId", "companyId")
+ REFERENCES "workCenter"("id", "companyId") ON DELETE CASCADE
+);
+
+CREATE INDEX IF NOT EXISTS "workCenterLoad_companyId_idx"
+ ON "workCenterLoad" ("companyId");
+CREATE INDEX IF NOT EXISTS "workCenterLoad_workCenter_loadedAt_idx"
+ ON "workCenterLoad" ("workCenterId", "loadedAt");
+CREATE INDEX IF NOT EXISTS "workCenterLoad_jobOperation_open_idx"
+ ON "workCenterLoad" ("jobOperationId") WHERE "unloadedAt" IS NULL;
+
+-- The loads in place now start the history.
+INSERT INTO "workCenterLoad" ("companyId", "workCenterId", "jobOperationId", "loadedAt")
+SELECT w."companyId", w."id", w."loadedJobOperationId", w."loadedAt"
+FROM "workCenter" w
+WHERE w."loadedJobOperationId" IS NOT NULL
+ AND w."loadedAt" IS NOT NULL
+ AND NOT EXISTS (
+ SELECT 1 FROM "workCenterLoad" l
+ WHERE l."workCenterId" = w."id"
+ AND l."companyId" = w."companyId"
+ AND l."unloadedAt" IS NULL
+ );
+
+CREATE OR REPLACE FUNCTION util.purge_work_center_loads()
+RETURNS void
+LANGUAGE sql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+ DELETE FROM "workCenterLoad"
+ WHERE "unloadedAt" < NOW() - INTERVAL '7 days';
+$$;
+
+REVOKE ALL ON FUNCTION util.purge_work_center_loads() FROM PUBLIC;
+
+DO $$
+BEGIN
+ IF EXISTS (
+ SELECT 1 FROM cron.job WHERE jobname = 'work-center-load-retention'
+ ) THEN
+ PERFORM cron.unschedule('work-center-load-retention');
+ END IF;
+ PERFORM cron.schedule(
+ 'work-center-load-retention',
+ '35 4 * * *',
+ 'SELECT util.purge_work_center_loads();'
+ );
+END;
+$$;
diff --git a/packages/database/supabase/migrations/20261014010232_work-center-load-history-authz.sql b/packages/database/supabase/migrations/20261014010232_work-center-load-history-authz.sql
new file mode 100644
index 0000000000..8ecf40f677
--- /dev/null
+++ b/packages/database/supabase/migrations/20261014010232_work-center-load-history-authz.sql
@@ -0,0 +1,120 @@
+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.
+
+-- Ships these rules to databases where `authz sync` does not run after migrations yet.
+
+CREATE OR REPLACE FUNCTION public.sync_load_work_center_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ IF p_operation != 'INSERT' THEN RETURN; END IF;
+
+ -- Only a starting event loads: an event inserted with an endTime (an ERP
+ -- entry, an assigned interval, a closed sensor run) never does.
+ IF (p_new->>'endTime') IS NOT NULL OR (p_new->>'workCenterId') IS NULL THEN
+ RETURN;
+ END IF;
+
+ -- This runs as the owner (the dispatchers are SECURITY DEFINER), and the
+ -- event's workCenterId and jobOperationId are single-column FKs: an event
+ -- may only load its OWN company's operation onto its own company's work
+ -- center, or another company's sensor time would land on it.
+ UPDATE "workCenter"
+ SET "loadedJobOperationId" = p_new->>'jobOperationId',
+ "loadedAt" = (p_new->>'startTime')::timestamptz
+ WHERE "id" = p_new->>'workCenterId'
+ AND "companyId" = p_new->>'companyId'
+ AND ("loadedAt" IS NULL OR "loadedAt" <= (p_new->>'startTime')::timestamptz)
+ AND "loadedJobOperationId" IS DISTINCT FROM p_new->>'jobOperationId'
+ AND EXISTS (
+ SELECT 1 FROM "jobOperation"
+ WHERE "id" = p_new->>'jobOperationId'
+ AND "companyId" = p_new->>'companyId'
+ );
+ IF NOT FOUND THEN RETURN; END IF;
+
+ -- The history: the previous load ends where this one starts. The OEE sync
+ -- gives a run to the operation loaded when it started.
+ UPDATE "workCenterLoad"
+ SET "unloadedAt" = (p_new->>'startTime')::timestamptz
+ WHERE "workCenterId" = p_new->>'workCenterId'
+ AND "companyId" = p_new->>'companyId'
+ AND "unloadedAt" IS NULL;
+
+ INSERT INTO "workCenterLoad" ("companyId", "workCenterId", "jobOperationId", "loadedAt")
+ VALUES (
+ p_new->>'companyId',
+ p_new->>'workCenterId',
+ p_new->>'jobOperationId',
+ (p_new->>'startTime')::timestamptz
+ );
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.sync_unload_work_center_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ -- A deleted operation unloads too: the pointer has no foreign key, because
+ -- one would make PostgREST embeds of workCenter from jobOperation ambiguous.
+ IF p_operation = 'DELETE' THEN
+ UPDATE "workCenter"
+ SET "loadedJobOperationId" = NULL,
+ "loadedAt" = NULL
+ WHERE "loadedJobOperationId" = p_old->>'id';
+ UPDATE "workCenterLoad"
+ SET "unloadedAt" = NOW()
+ WHERE "jobOperationId" = p_old->>'id'
+ AND "companyId" = p_old->>'companyId'
+ AND "unloadedAt" IS NULL;
+ RETURN;
+ END IF;
+
+ -- An operation moved to another work center leaves the old one: its sensor
+ -- time there is no longer this operation's.
+ IF p_operation = 'UPDATE'
+ AND (p_old->>'workCenterId') IS DISTINCT FROM (p_new->>'workCenterId') THEN
+ UPDATE "workCenter"
+ SET "loadedJobOperationId" = NULL,
+ "loadedAt" = NULL
+ WHERE "id" = p_old->>'workCenterId'
+ AND "companyId" = p_old->>'companyId'
+ AND "loadedJobOperationId" = p_new->>'id';
+ UPDATE "workCenterLoad"
+ SET "unloadedAt" = NOW()
+ WHERE "workCenterId" = p_old->>'workCenterId'
+ AND "companyId" = p_old->>'companyId'
+ AND "jobOperationId" = p_new->>'id'
+ AND "unloadedAt" IS NULL;
+ END IF;
+
+ IF p_operation != 'UPDATE' THEN RETURN; END IF;
+ IF (p_new->>'status') NOT IN ('Done', 'Canceled') THEN RETURN; END IF;
+ IF (p_old->>'status') = (p_new->>'status') THEN RETURN; END IF;
+
+ UPDATE "workCenter"
+ SET "loadedJobOperationId" = NULL,
+ "loadedAt" = NULL
+ WHERE "loadedJobOperationId" = p_new->>'id';
+ UPDATE "workCenterLoad"
+ SET "unloadedAt" = NOW()
+ WHERE "jobOperationId" = p_new->>'id'
+ AND "companyId" = p_new->>'companyId'
+ AND "unloadedAt" IS NULL;
+END;
+$function$;
+
+-- workCenterLoad
+DO $authz$
+DECLARE p record;
+BEGIN
+ FOR p IN SELECT policyname FROM pg_policies WHERE schemaname = 'public' AND tablename = 'workCenterLoad' LOOP
+ EXECUTE format('DROP POLICY %I ON public.%I', p.policyname, 'workCenterLoad');
+ END LOOP;
+END
+$authz$;
+ALTER TABLE public."workCenterLoad" ENABLE ROW LEVEL SECURITY;
+CREATE POLICY "SELECT" ON "public"."workCenterLoad" FOR SELECT USING ("companyId" = ANY ((SELECT get_companies_with_employee_role())::text[]));
diff --git a/packages/database/supabase/migrations/20261014024119_oee-load-is-history.sql b/packages/database/supabase/migrations/20261014024119_oee-load-is-history.sql
new file mode 100644
index 0000000000..6346c8390f
--- /dev/null
+++ b/packages/database/supabase/migrations/20261014024119_oee-load-is-history.sql
@@ -0,0 +1,139 @@
+-- The open workCenterLoad row is the load. workCenter."loadedJobOperationId"
+-- and "loadedAt" held the same fact twice, and an unload cleared "loadedAt",
+-- which let a late event load an operation that had been replaced and made
+-- history rows overlap. The interceptors now write only the history.
+
+-- 1. Repair the history before the constraints: an end before its start
+-- becomes the start, and only the newest open row per work center stays
+-- open (an older one ends where the newer one starts).
+UPDATE "workCenterLoad"
+SET "unloadedAt" = "loadedAt"
+WHERE "unloadedAt" < "loadedAt";
+
+UPDATE "workCenterLoad" l
+SET "unloadedAt" = GREATEST(newer."loadedAt", l."loadedAt")
+FROM (
+ SELECT "id", "companyId", "workCenterId", "loadedAt",
+ row_number() OVER (
+ PARTITION BY "workCenterId", "companyId" ORDER BY "loadedAt" DESC, "createdAt" DESC
+ ) AS position
+ FROM "workCenterLoad"
+ WHERE "unloadedAt" IS NULL
+) newer
+WHERE newer.position = 1
+ AND l."unloadedAt" IS NULL
+ AND l."workCenterId" = newer."workCenterId"
+ AND l."companyId" = newer."companyId"
+ AND l."id" <> newer."id";
+
+ALTER TABLE "workCenterLoad"
+ DROP CONSTRAINT IF EXISTS "workCenterLoad_interval_check",
+ ADD CONSTRAINT "workCenterLoad_interval_check"
+ CHECK ("unloadedAt" IS NULL OR "unloadedAt" >= "loadedAt");
+
+CREATE UNIQUE INDEX IF NOT EXISTS "workCenterLoad_one_open_idx"
+ ON "workCenterLoad" ("workCenterId", "companyId")
+ WHERE "unloadedAt" IS NULL;
+
+-- 2. The work center display reads the load from the open row. Both views
+-- select wc.*, so they are rebuilt around the dropped columns.
+DROP VIEW IF EXISTS "workCentersWithBlockingStatus";
+DROP VIEW IF EXISTS "workCenters";
+
+ALTER TABLE "workCenter"
+ DROP COLUMN IF EXISTS "loadedJobOperationId",
+ DROP COLUMN IF EXISTS "loadedAt";
+
+CREATE VIEW "workCenters" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ wc.*,
+ l.name as "locationName",
+ d.name as "departmentName",
+ wcp.processes
+ FROM "workCenter" wc
+ LEFT JOIN "location" l
+ ON wc."locationId" = l.id
+ LEFT JOIN "department" d
+ ON wc."departmentId" = d.id
+ LEFT JOIN (
+ SELECT
+ "workCenterId",
+ array_agg("processId"::text) as processes
+ FROM "workCenterProcess" wcp
+ INNER JOIN "process" p ON wcp."processId" = p.id
+ GROUP BY "workCenterId"
+ ) wcp ON wc.id = wcp."workCenterId";
+
+CREATE VIEW "workCentersWithBlockingStatus" WITH (security_invoker = true) AS
+SELECT
+ wc.*,
+ l.name AS "locationName",
+ COALESCE(
+ (SELECT COUNT(*) > 0
+ FROM "maintenanceDispatch" md
+ WHERE md."workCenterId" = wc.id
+ AND md.status = 'In Progress'
+ AND md."oeeImpact" IN ('Down', 'Planned')
+ ), false
+ ) AS "isBlocked",
+ (
+ SELECT md.id
+ FROM "maintenanceDispatch" md
+ WHERE md."workCenterId" = wc.id
+ AND md.status = 'In Progress'
+ AND md."oeeImpact" IN ('Down', 'Planned')
+ ORDER BY md."createdAt" DESC
+ LIMIT 1
+ ) AS "blockingDispatchId",
+ (
+ SELECT md."maintenanceDispatchId"
+ FROM "maintenanceDispatch" md
+ WHERE md."workCenterId" = wc.id
+ AND md.status = 'In Progress'
+ AND md."oeeImpact" IN ('Down', 'Planned')
+ ORDER BY md."createdAt" DESC
+ LIMIT 1
+ ) AS "blockingDispatchReadableId",
+ (
+ SELECT wl."jobOperationId"
+ FROM "workCenterLoad" wl
+ WHERE wl."workCenterId" = wc.id
+ AND wl."companyId" = wc."companyId"
+ AND wl."unloadedAt" IS NULL
+ ) AS "loadedJobOperationId"
+FROM "workCenter" wc
+LEFT JOIN "location" l ON wc."locationId" = l.id;
+
+-- 3. The earliest press since the last sync. A press sets it; the sync plans
+-- from it and clears it, so two presses between syncs both count.
+ALTER TABLE "workCenterDevice"
+ ADD COLUMN IF NOT EXISTS "unplannedPressAt" TIMESTAMP WITH TIME ZONE;
+
+-- 4. The sync reads a work center's Machine events (the latest end, and the
+-- time already recorded) and its maintenance dispatches every 2 minutes.
+CREATE INDEX IF NOT EXISTS "productionEvent_machine_workCenter_endTime_idx"
+ ON "productionEvent" ("workCenterId", "endTime")
+ WHERE "type" = 'Machine';
+CREATE INDEX IF NOT EXISTS "maintenanceDispatch_workCenterId_idx"
+ ON "maintenanceDispatch" ("workCenterId");
+
+-- 5. A load stays 7 days after its unload, and longer while a device on its
+-- work center has not planned past it: a device that fails for a week
+-- still finds the loads its late runs belong to.
+CREATE OR REPLACE FUNCTION util.purge_work_center_loads()
+RETURNS void
+LANGUAGE sql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+ DELETE FROM "workCenterLoad" l
+ WHERE l."unloadedAt" < NOW() - INTERVAL '7 days'
+ AND NOT EXISTS (
+ SELECT 1 FROM "workCenterDevice" d
+ WHERE d."workCenterId" = l."workCenterId"
+ AND d."companyId" = l."companyId"
+ AND (d."appliedThrough" IS NULL OR d."appliedThrough" < l."unloadedAt")
+ );
+$$;
+
+REVOKE ALL ON FUNCTION util.purge_work_center_loads() FROM PUBLIC;
diff --git a/packages/database/supabase/migrations/20261014030025_oee-load-is-history-authz.sql b/packages/database/supabase/migrations/20261014030025_oee-load-is-history-authz.sql
new file mode 100644
index 0000000000..04c4c668d9
--- /dev/null
+++ b/packages/database/supabase/migrations/20261014030025_oee-load-is-history-authz.sql
@@ -0,0 +1,670 @@
+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.
+
+-- Ships these rules to databases where `authz sync` does not run after migrations yet.
+
+CREATE OR REPLACE FUNCTION public.broadcast_reference_changes()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO ''
+AS $function$
+DECLARE
+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];
+ changed_rows TEXT;
+ rec RECORD;
+BEGIN
+ -- A database without Supabase Realtime (a self-hosted install that does not
+ -- run it) has nothing to send to: the write must still succeed.
+ IF to_regprocedure('realtime.send(jsonb,text,text,boolean)') IS NULL THEN
+ RETURN NULL;
+ END IF;
+
+ -- Tells the company's clients that a reference list changed (one shared topic, company:<companyId>:reference).
+ -- Statement-level (attach_statement_handler): one message per company per
+ -- statement, whatever the row count. No row data leaves the database: a client
+ -- re-reads what it needs through PostgREST, so table RLS still decides what it sees.
+ IF TG_OP = 'UPDATE' THEN
+ -- A row whose only changes are in ignored_columns drops out (the rule
+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).
+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n
+ EXCEPT
+ SELECT to_jsonb(o) - $1 FROM batched_old o';
+ ELSIF TG_OP = 'DELETE' THEN
+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';
+ ELSE
+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';
+ END IF;
+
+ FOR rec IN EXECUTE format(
+ 'SELECT DISTINCT c->>''companyId'' AS company_id FROM (%s) changed',
+ changed_rows
+ ) USING ignored_columns
+ LOOP
+ CONTINUE WHEN rec.company_id IS NULL;
+ PERFORM realtime.send(
+ jsonb_build_object('table', TG_TABLE_NAME, 'op', TG_OP),
+ TG_OP,
+ 'company:' || rec.company_id || ':reference',
+ true
+ );
+ END LOOP;
+ RETURN NULL;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.broadcast_table_changes()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO ''
+AS $function$
+DECLARE
+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];
+ -- Tables whose rows hang off a record through another table. Each hop is
+ -- [column of the row, table it points at, column to read there]: its value is
+ -- added to the message under that column's name, so a job page can follow
+ -- "jobId" on a table that only knows its operation.
+ -- A hop with a fourth element looks the other way: the rows of that table
+ -- whose fourth column holds this row's value ("id" is the row's own id). A
+ -- payment has no invoice column; its settlements name the invoices it pays.
+ -- packages/database/src/realtime-tables.ts lists the same columns
+ -- (REALTIME_ANCESTOR_COLUMNS; realtime-tables.test.ts keeps them equal).
+ ancestors CONSTANT JSONB := '{
+ "productionEvent": [["jobOperationId", "jobOperation", "jobId"]],
+ "jobOperationStep": [["operationId", "jobOperation", "jobId"]],
+ "jobOperationStepRecord": [["jobOperationStepId", "jobOperationStep", "operationId"], ["operationId", "jobOperation", "jobId"]],
+ "trackedActivity": [["sourceDocumentId", "productionEvent", "jobOperationId"]],
+ "payment": [["id", "invoiceSettlement", "targetSalesInvoiceId", "paymentId"], ["id", "invoiceSettlement", "targetPurchaseInvoiceId", "paymentId"]]
+ }';
+ changed_rows TEXT;
+ parent_rows TEXT;
+ parents JSONB;
+ sent_columns TEXT[];
+ found JSONB;
+ hop JSONB;
+ rec RECORD;
+BEGIN
+ -- A database without Supabase Realtime (a self-hosted install that does not
+ -- run it) has nothing to send to: the write must still succeed.
+ IF to_regprocedure('realtime.send(jsonb,text,text,boolean)') IS NULL THEN
+ RETURN NULL;
+ END IF;
+
+ -- Tells the company's clients which rows of this table changed (topic company:<companyId>:<table>).
+ -- Statement-level (attach_statement_handler): one message per company per
+ -- statement, whatever the row count. No row data leaves the database: a client
+ -- re-reads what it needs through PostgREST, so table RLS still decides what it sees.
+ -- The columns a message may name: the table's foreign keys, and the columns
+ -- its ancestors add. A column that merely ends in "Id" is the row's own data
+ -- (a part number in "readableId", an order number, a tax id) and stays here.
+ SELECT coalesce(array_agg(DISTINCT a.attname::text), ARRAY[]::text[])
+ INTO sent_columns
+ FROM pg_catalog.pg_constraint k
+ JOIN pg_catalog.pg_attribute a
+ ON a.attrelid = k.conrelid AND a.attnum = ANY (k.conkey)
+ WHERE k.conrelid = TG_RELID AND k.contype = 'f';
+ IF ancestors ? TG_TABLE_NAME THEN
+ sent_columns := sent_columns || ARRAY(
+ SELECT value->>2 FROM jsonb_array_elements(ancestors->TG_TABLE_NAME)
+ );
+ END IF;
+
+ IF TG_OP = 'UPDATE' THEN
+ -- A row whose only changes are in ignored_columns drops out (the rule
+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).
+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n
+ EXCEPT
+ SELECT to_jsonb(o) - $1 FROM batched_old o';
+ -- The rows as they were, too: a row moved to another parent concerns the
+ -- parent it left as much as the one it joined.
+ parent_rows := '(' || changed_rows || ')
+ UNION ALL
+ (SELECT to_jsonb(o) - $1 FROM batched_old o
+ EXCEPT
+ SELECT to_jsonb(n) - $1 FROM batched_new n)';
+ ELSIF TG_OP = 'DELETE' THEN
+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';
+ parent_rows := changed_rows;
+ ELSE
+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';
+ parent_rows := changed_rows;
+ END IF;
+
+ FOR rec IN EXECUTE format(
+ -- implementationHub has no companyId: its id is the company id.
+ 'WITH keyed AS (
+ SELECT coalesce(c->>''companyId'',
+ CASE WHEN $2::text = ''implementationHub'' THEN c->>''id'' END) AS company_id,
+ c
+ FROM (%1$s) changed
+ ),
+ related AS (
+ SELECT coalesce(c->>''companyId'',
+ CASE WHEN $2::text = ''implementationHub'' THEN c->>''id'' END) AS company_id,
+ c
+ FROM (%2$s) changed
+ )
+ SELECT k.company_id,
+ count(*) AS n,
+ -- itemSupersession has no id: its row belongs to the item it describes.
+ jsonb_agg(coalesce(k.c->''id'', k.c->''itemId''))
+ FILTER (WHERE k.c ? ''id'' OR k.c ? ''itemId'') AS ids,
+ -- The records these rows belong to: each "<name>Id" column and its
+ -- values (narrowed to the foreign keys before sending), so a page showing one job (or quote, or order) can ignore
+ -- changes to another''s rows. A column with more than 20 values is
+ -- left out, and a client treats a missing column as "may concern me".
+ -- Only computed for a statement small enough to list its ids.
+ CASE WHEN count(*) <= 100 THEN (
+ SELECT jsonb_object_agg(p.key, p.vals)
+ FROM (
+ SELECT e.key, jsonb_agg(DISTINCT e.value) AS vals
+ FROM related k2, jsonb_each(k2.c) e
+ WHERE k2.company_id = k.company_id
+ AND e.key LIKE ''%%Id'' AND e.key <> ''companyId''
+ AND jsonb_typeof(e.value) = ''string''
+ GROUP BY e.key
+ HAVING count(DISTINCT e.value) <= 20
+ ) p
+ ) END AS parents
+ FROM keyed k
+ GROUP BY k.company_id',
+ changed_rows, parent_rows
+ ) USING ignored_columns, TG_TABLE_NAME
+ LOOP
+ CONTINUE WHEN rec.company_id IS NULL;
+
+ parents := rec.parents;
+ IF parents IS NOT NULL AND ancestors ? TG_TABLE_NAME THEN
+ FOR hop IN SELECT value FROM jsonb_array_elements(ancestors->TG_TABLE_NAME) LOOP
+ found := CASE WHEN hop->>0 = 'id' THEN rec.ids ELSE parents->(hop->>0) END;
+ -- A column that was left out (no value, or too many) leaves its
+ -- ancestor out as well: the client then takes the change as its own.
+ CONTINUE WHEN found IS NULL;
+ EXECUTE format(
+ 'SELECT jsonb_agg(DISTINCT %1$I) FROM public.%2$I
+ WHERE "companyId" = $1 AND %1$I IS NOT NULL
+ AND %3$I IN (SELECT jsonb_array_elements_text($2))',
+ hop->>2, hop->>1, coalesce(hop->>3, 'id')
+ ) INTO found USING rec.company_id, found;
+ IF found IS NOT NULL THEN
+ parents := parents || jsonb_build_object(hop->>2, found);
+ ELSIF jsonb_array_length(hop) = 4 THEN
+ -- Looked for and not there: no such record has this row.
+ parents := parents || jsonb_build_object(hop->>2, '[]'::jsonb);
+ END IF;
+ END LOOP;
+ END IF;
+ -- An ancestor hop may read a column that is not sent (a polymorphic
+ -- "sourceDocumentId"), so the narrowing comes last.
+ IF parents IS NOT NULL THEN
+ parents := coalesce(
+ (SELECT jsonb_object_agg(e.key, e.value)
+ FROM jsonb_each(parents) e
+ WHERE e.key = ANY (sent_columns)),
+ '{}'::jsonb
+ );
+ END IF;
+ PERFORM realtime.send(
+ jsonb_build_object(
+ 'table', TG_TABLE_NAME,
+ 'op', TG_OP,
+ -- null = "many rows changed, or the table has no id: resync"
+ 'ids', CASE WHEN rec.n <= 100 THEN rec.ids END,
+ 'parents', parents
+ ),
+ TG_OP,
+ 'company:' || rec.company_id || ':' || TG_TABLE_NAME,
+ true
+ );
+ END LOOP;
+ RETURN NULL;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.broadcast_user_changes()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO ''
+AS $function$
+DECLARE
+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];
+ changed_rows TEXT;
+ rec RECORD;
+BEGIN
+ -- A database without Supabase Realtime (a self-hosted install that does not
+ -- run it) has nothing to send to: the write must still succeed.
+ IF to_regprocedure('realtime.send(jsonb,text,text,boolean)') IS NULL THEN
+ RETURN NULL;
+ END IF;
+
+ -- Tells one user which of their rows changed (topic user:<userId>:<table>).
+ -- Statement-level (attach_statement_handler): one message per user per
+ -- statement, whatever the row count. No row data leaves the database: a client
+ -- re-reads what it needs through PostgREST, so table RLS still decides what it sees.
+ IF TG_OP = 'UPDATE' THEN
+ -- A row whose only changes are in ignored_columns drops out (the rule
+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).
+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n
+ EXCEPT
+ SELECT to_jsonb(o) - $1 FROM batched_old o';
+ ELSIF TG_OP = 'DELETE' THEN
+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';
+ ELSE
+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';
+ END IF;
+
+ FOR rec IN EXECUTE format(
+ 'SELECT c->>''userId'' AS user_id,
+ count(*) AS n,
+ jsonb_agg(c->''id'') FILTER (WHERE c ? ''id'') AS ids
+ FROM (%s) changed
+ GROUP BY 1',
+ changed_rows
+ ) USING ignored_columns
+ LOOP
+ CONTINUE WHEN rec.user_id IS NULL;
+ PERFORM realtime.send(
+ jsonb_build_object(
+ 'table', TG_TABLE_NAME,
+ 'op', TG_OP,
+ 'ids', CASE WHEN rec.n <= 100 THEN rec.ids END
+ ),
+ TG_OP,
+ 'user:' || rec.user_id || ':' || TG_TABLE_NAME,
+ true
+ );
+ END LOOP;
+ RETURN NULL;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.dispatch_event_batch()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pgmq', 'extensions'
+AS $function$
+DECLARE
+ sub RECORD;
+ msg_batch JSONB[];
+ rec_company_id TEXT;
+ has_subs BOOLEAN;
+ current_actor_id TEXT;
+ current_workflow_run_id TEXT;
+ pk_columns TEXT[];
+ pk_join TEXT;
+ record_id_expr TEXT;
+ query_text TEXT;
+ did_enqueue BOOLEAN := FALSE;
+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];
+BEGIN
+ current_actor_id := auth.uid()::TEXT;
+ current_workflow_run_id :=
+ (nullif(current_setting('request.jwt.claims', true), '')::jsonb)->>'workflow_run_id';
+ IF TG_OP = 'DELETE' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_old t LIMIT 1;
+ ELSIF TG_OP = 'INSERT' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ ELSE
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ END IF;
+
+ IF rec_company_id IS NULL THEN RETURN NULL; END IF;
+
+ SELECT EXISTS (
+ SELECT 1 FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ AND ("handlerType" NOT IN ('SYNC','WEBHOOK','WORKFLOW')
+ OR current_setting('app.sync_in_progress', true) IS DISTINCT FROM 'true')
+ ) INTO has_subs;
+
+ IF NOT has_subs THEN RETURN NULL; END IF;
+
+ -- Looked up only once a subscription exists: almost no company subscribes
+ -- to most tables, and this catalog read ran on every write statement.
+ pk_columns := public.get_primary_key_columns(TG_TABLE_NAME);
+
+ -- Pair UPDATE rows on the full key: single-column pairing cross-joins rows
+ -- on tables with composite identity.
+ SELECT string_agg(format('n.%I = o.%I', col, col), ' AND ')
+ INTO pk_join
+ FROM unnest(pk_columns) AS col;
+
+ -- recordId names one row. "id" does that wherever it is part of the key
+ -- ((id, companyId) tables); a primary key without one is every column joined
+ -- by ':', since a single column of it is shared by many rows. A table with no
+ -- primary key keeps the one column it always sent: the audit log files
+ -- itemPlanning (unique on itemId + locationId) under its itemId.
+ -- %1$s is the row alias.
+ IF 'id' = ANY(pk_columns) THEN
+ record_id_expr := '%1$s."id"::TEXT';
+ ELSIF EXISTS (
+ SELECT 1 FROM pg_index WHERE indrelid = TG_RELID AND indisprimary
+ ) THEN
+ SELECT 'concat_ws('':'', ' || string_agg(format('%%1$s.%I::TEXT', col), ', ') || ')'
+ INTO record_id_expr
+ FROM unnest(pk_columns) AS col;
+ ELSE
+ record_id_expr := format('%%1$s.%I::TEXT', public.get_primary_key_column(TG_TABLE_NAME));
+ END IF;
+
+ FOR sub IN
+ SELECT * FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ AND ("handlerType" NOT IN ('SYNC','WEBHOOK','WORKFLOW')
+ OR current_setting('app.sync_in_progress', true) IS DISTINCT FROM 'true')
+ LOOP
+
+ IF TG_OP = 'INSERT' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''workflowRunId'', $10,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', %s,
+ ''new'', row_to_json(t)::jsonb,
+ ''old'', null,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_new t
+ WHERE t."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
+ ', format(record_id_expr, 't'));
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
+ current_workflow_run_id;
+
+ ELSIF TG_OP = 'DELETE' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''workflowRunId'', $10,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', %s,
+ ''new'', null,
+ ''old'', row_to_json(t)::jsonb,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_old t
+ WHERE t."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
+ ', format(record_id_expr, 't'));
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
+ current_workflow_run_id;
+
+ ELSIF TG_OP = 'UPDATE' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''workflowRunId'', $10,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', %s,
+ ''new'', row_to_json(n)::jsonb,
+ ''old'', row_to_json(o)::jsonb,
+ ''timestamp'', clock_timestamp()
+ )
+ )
+ )
+ FROM batched_new n
+ JOIN batched_old o ON %s
+ WHERE n."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(n)::jsonb @> $9)
+ AND (NOT $11 OR (to_jsonb(n) - $12) IS DISTINCT FROM (to_jsonb(o) - $12))
+ ', format(record_id_expr, 'n'), pk_join);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
+ current_workflow_run_id,
+ sub."handlerType" IN ('AUDIT', 'SEARCH', 'EMBEDDING'),
+ ignored_columns;
+ END IF;
+
+ IF msg_batch IS NOT NULL AND array_length(msg_batch, 1) > 0 THEN
+ PERFORM pgmq.send_batch('event_system', msg_batch);
+ did_enqueue := TRUE;
+ END IF;
+
+ END LOOP;
+
+ -- Wake the Inngest drainer once per transaction: the GUC is txn-local, so a
+ -- bulk import posts a single doorbell instead of one per statement.
+ IF did_enqueue
+ AND current_setting('carbon.event_wake_sent', true) IS DISTINCT FROM 'true' THEN
+ PERFORM util.wake_event_queue();
+ PERFORM set_config('carbon.event_wake_sent', 'true', true);
+ END IF;
+
+ RETURN NULL;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.log_table_changes()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO ''
+AS $function$
+DECLARE
+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];
+ changed_rows TEXT;
+BEGIN
+ -- Records which rows of this table changed, in public."tableChange", so a
+ -- client that kept a copy of a list can ask "what changed since I last
+ -- looked?" (table_changes_since) and re-read only those rows instead of the
+ -- whole table. A broadcast tells an open tab the same thing; this is for the
+ -- tab that was closed, or disconnected, when it happened.
+ IF TG_OP = 'UPDATE' THEN
+ -- A row whose only changes are in ignored_columns drops out (the rule
+ -- dispatch_event_batch applies; event-dispatch.test.ts keeps the lists equal).
+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n
+ EXCEPT
+ SELECT to_jsonb(o) - $1 FROM batched_old o';
+ ELSIF TG_OP = 'DELETE' THEN
+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';
+ ELSE
+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';
+ END IF;
+
+ EXECUTE format(
+ -- One log row per changed row. Past 100 rows in one statement, a single row
+ -- with a null "rowId" says "this table changed a lot: read it again".
+ -- itemSupersession has no id: its row belongs to the item it describes.
+ 'INSERT INTO public."tableChange" ("companyId", "table", "rowId")
+ SELECT DISTINCT company_id, $2::text, CASE WHEN n <= 100 THEN row_id END
+ FROM (
+ SELECT c->>''companyId'' AS company_id,
+ coalesce(c->>''id'', c->>''itemId'') AS row_id,
+ count(*) OVER (PARTITION BY c->>''companyId'') AS n
+ FROM (%s) changed
+ ) rows
+ WHERE company_id IS NOT NULL',
+ changed_rows
+ ) USING ignored_columns, TG_TABLE_NAME;
+ RETURN NULL;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.log_user_changes()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO ''
+AS $function$
+DECLARE
+ ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];
+ changed_rows TEXT;
+BEGIN
+ -- A person's name and avatar live on the global "user" row, which has no
+ -- company. Each company that person belongs to shows them in its people list
+ -- (the employees view), so a change is logged once per company, as a change
+ -- to that company's "employee" row.
+ IF TG_OP = 'UPDATE' THEN
+ changed_rows := 'SELECT to_jsonb(n) - $1 AS c FROM batched_new n
+ EXCEPT
+ SELECT to_jsonb(o) - $1 FROM batched_old o';
+ ELSIF TG_OP = 'DELETE' THEN
+ changed_rows := 'SELECT to_jsonb(o) AS c FROM batched_old o';
+ ELSE
+ changed_rows := 'SELECT to_jsonb(n) AS c FROM batched_new n';
+ END IF;
+
+ EXECUTE format(
+ 'INSERT INTO public."tableChange" ("companyId", "table", "rowId")
+ SELECT DISTINCT m."companyId", ''employee'', changed.c->>''id''
+ FROM (%s) changed
+ JOIN public."userToCompany" m ON m."userId" = changed.c->>''id''',
+ changed_rows
+ ) USING ignored_columns;
+ RETURN NULL;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.sync_load_work_center_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ v_work_center_id text := p_new->>'workCenterId';
+ v_company_id text := p_new->>'companyId';
+ v_operation_id text := p_new->>'jobOperationId';
+ v_start timestamptz := (p_new->>'startTime')::timestamptz;
+ v_boundary timestamptz;
+ v_loaded text;
+BEGIN
+ IF p_operation != 'INSERT' THEN RETURN; END IF;
+
+ -- Only a starting event loads: an event inserted with an endTime (an ERP
+ -- entry, an assigned interval, a closed sensor run) never does.
+ IF (p_new->>'endTime') IS NOT NULL OR v_work_center_id IS NULL THEN
+ RETURN;
+ END IF;
+
+ -- This runs as the owner (the dispatchers are SECURITY DEFINER), and the
+ -- event's workCenterId and jobOperationId are single-column FKs: an event
+ -- may only load its OWN company's operation onto its own company's work
+ -- center, or another company's sensor time would land on it. (A starting
+ -- event reopens a Done operation first: sync_set_job_operation_in_progress.)
+ IF NOT EXISTS (
+ SELECT 1 FROM "workCenter"
+ WHERE "id" = v_work_center_id AND "companyId" = v_company_id
+ ) OR NOT EXISTS (
+ SELECT 1 FROM "jobOperation"
+ WHERE "id" = v_operation_id AND "companyId" = v_company_id
+ ) THEN
+ RETURN;
+ END IF;
+
+ -- One load at a time per work center.
+ PERFORM pg_advisory_xact_lock(hashtextextended('workCenterLoad:' || v_work_center_id, 0));
+
+ -- The open row is the load. A start older than the newest boundary in the
+ -- history (a load or an unload) never loads: a late event must not undo a
+ -- load or an unload that came after it.
+ SELECT max(GREATEST("loadedAt", COALESCE("unloadedAt", "loadedAt")))
+ INTO v_boundary
+ FROM "workCenterLoad"
+ WHERE "workCenterId" = v_work_center_id AND "companyId" = v_company_id;
+ IF v_boundary IS NOT NULL AND v_start < v_boundary THEN RETURN; END IF;
+
+ -- A reload of the operation already loaded writes nothing.
+ SELECT "jobOperationId" INTO v_loaded
+ FROM "workCenterLoad"
+ WHERE "workCenterId" = v_work_center_id
+ AND "companyId" = v_company_id
+ AND "unloadedAt" IS NULL;
+ IF v_loaded = v_operation_id THEN RETURN; END IF;
+
+ UPDATE "workCenterLoad"
+ SET "unloadedAt" = v_start
+ WHERE "workCenterId" = v_work_center_id
+ AND "companyId" = v_company_id
+ AND "unloadedAt" IS NULL;
+
+ INSERT INTO "workCenterLoad" ("companyId", "workCenterId", "jobOperationId", "loadedAt")
+ VALUES (v_company_id, v_work_center_id, v_operation_id, v_start);
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.sync_unload_work_center_operation(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+BEGIN
+ -- An unload ends the operation's open load now, never before it began.
+ -- A deleted operation unloads too: the load has no foreign key, because one
+ -- would make PostgREST embeds between workCenter and jobOperation ambiguous.
+ IF p_operation = 'DELETE' THEN
+ UPDATE "workCenterLoad"
+ SET "unloadedAt" = GREATEST(NOW(), "loadedAt")
+ WHERE "jobOperationId" = p_old->>'id'
+ AND "companyId" = p_old->>'companyId'
+ AND "unloadedAt" IS NULL;
+ RETURN;
+ END IF;
+
+ IF p_operation != 'UPDATE' THEN RETURN; END IF;
+
+ -- An operation moved to another work center leaves the old one: its sensor
+ -- time there is no longer this operation's.
+ IF (p_old->>'workCenterId') IS DISTINCT FROM (p_new->>'workCenterId') THEN
+ UPDATE "workCenterLoad"
+ SET "unloadedAt" = GREATEST(NOW(), "loadedAt")
+ WHERE "workCenterId" = p_old->>'workCenterId'
+ AND "companyId" = p_old->>'companyId'
+ AND "jobOperationId" = p_new->>'id'
+ AND "unloadedAt" IS NULL;
+ END IF;
+
+ IF (p_new->>'status') NOT IN ('Done', 'Canceled') THEN RETURN; END IF;
+ IF (p_old->>'status') = (p_new->>'status') THEN RETURN; END IF;
+
+ UPDATE "workCenterLoad"
+ SET "unloadedAt" = GREATEST(NOW(), "loadedAt")
+ WHERE "jobOperationId" = p_new->>'id'
+ AND "companyId" = p_new->>'companyId'
+ AND "unloadedAt" IS NULL;
+END;
+$function$;
diff --git a/packages/database/supabase/tests/work-center-loaded-operation.test.sql b/packages/database/supabase/tests/work-center-loaded-operation.test.sql
new file mode 100644
index 0000000000..3afc6fd76d
--- /dev/null
+++ b/packages/database/supabase/tests/work-center-loaded-operation.test.sql
@@ -0,0 +1,267 @@
+-- An open production event loads its operation onto the work center
+-- (sync_load_work_center_operation); the operation going Done or Canceled
+-- unloads it (sync_unload_work_center_operation), and so does deleting it or
+-- moving it to another work center; a Pause does not. The open workCenterLoad
+-- row is the load; closed rows are the history the OEE sync reads. A start
+-- older than the newest load or unload never loads, and an event only loads its own company's operation onto its own
+-- company's work center. The oee provider role may
+-- have several active integrations; the other roles still allow one.
+-- Isolated fixture company; no existing business data is read or edited. Always rolls back.
+-- Run: pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -f packages/database/supabase/tests/work-center-loaded-operation.test.sql
+\set ON_ERROR_STOP on
+BEGIN;
+SET LOCAL statement_timeout = '60s';
+
+-- A released job for p_item_id with p_quantity units (from
+-- job-completion-terminal-operations.test.sql).
+CREATE FUNCTION pg_temp.make_job(
+ p_company_id text, p_location_id text, p_item_id text, p_readable_id text, p_quantity numeric
+) RETURNS text LANGUAGE plpgsql AS $fn$
+DECLARE
+ v_job_id text;
+BEGIN
+ INSERT INTO job ("jobId", "itemId", quantity, "locationId", "companyId", "createdBy", "unitOfMeasureCode")
+ VALUES (p_readable_id, p_item_id, p_quantity, p_location_id, p_company_id, 'system', 'EA')
+ RETURNING id INTO v_job_id;
+ UPDATE job SET status = 'In Progress' WHERE id = v_job_id;
+ RETURN v_job_id;
+END;
+$fn$;
+
+-- An operation on the job's top-level make method.
+CREATE FUNCTION pg_temp.add_operation(
+ p_job_id text, p_company_id text, p_process_id text, p_work_center_id text, p_order numeric
+) RETURNS text LANGUAGE plpgsql AS $fn$
+DECLARE v_operation text;
+BEGIN
+ INSERT INTO "jobOperation" ("jobId", "jobMakeMethodId", "processId", "workCenterId",
+ "operationQuantity", "targetQuantity", "order", status, "companyId", "createdBy")
+ SELECT p_job_id, m.id, p_process_id, p_work_center_id,
+ 1, 1, p_order, 'Ready', p_company_id, 'system'
+ FROM "jobMakeMethod" m WHERE m."jobId" = p_job_id AND m."parentMaterialId" IS NULL
+ RETURNING id INTO v_operation;
+ RETURN v_operation;
+END;
+$fn$;
+
+CREATE FUNCTION pg_temp.add_event(
+ p_operation_id text, p_work_center_id text, p_type text, p_start timestamptz, p_end timestamptz
+) RETURNS void LANGUAGE sql AS $fn$
+ INSERT INTO "productionEvent" ("jobOperationId", "workCenterId", type, "startTime", "endTime", "companyId", "createdBy")
+ SELECT p_operation_id, p_work_center_id, p_type::"productionEventType", p_start, p_end, "companyId", 'system'
+ FROM "jobOperation" WHERE id = p_operation_id;
+$fn$;
+
+-- The open load as operation@loadedAt, or none@none.
+CREATE FUNCTION pg_temp.loaded(p_work_center_id text) RETURNS text LANGUAGE sql AS $fn$
+ SELECT COALESCE(
+ (SELECT "jobOperationId" || '@' || to_char("loadedAt" AT TIME ZONE 'UTC', 'HH24:MI')
+ FROM "workCenterLoad"
+ WHERE "workCenterId" = p_work_center_id AND "unloadedAt" IS NULL),
+ 'none@none');
+$fn$;
+
+-- The work center's load history: operation@loaded-unloaded, oldest first.
+-- The test day is in the future, so an unload (at now()) clamps to the load.
+CREATE FUNCTION pg_temp.history(p_work_center_id text) RETURNS text LANGUAGE sql AS $fn$
+ SELECT COALESCE(string_agg(
+ "jobOperationId" || '@' || to_char("loadedAt" AT TIME ZONE 'UTC', 'HH24:MI') || '-' ||
+ CASE
+ WHEN "unloadedAt" IS NULL THEN 'open'
+ ELSE to_char("unloadedAt" AT TIME ZONE 'UTC', 'HH24:MI')
+ END,
+ ' ' ORDER BY "loadedAt"), 'none')
+ FROM "workCenterLoad" WHERE "workCenterId" = p_work_center_id;
+$fn$;
+
+DO $cases$
+DECLARE
+ v_group_id text; v_company_id text; v_location_id text;
+ v_item text; v_process text; v_work_center text;
+ v_job text; v_a text; v_b text; v_c text; v_d text; v_e text; v_work_center_2 text;
+ v_other_company text; v_other_location text; v_other_item text;
+ v_other_process text; v_other_work_center text; v_other_job text; v_other_op text;
+ -- Tomorrow: every start is later than now(), so an unload ends at its load.
+ v_day date := (now() AT TIME ZONE 'UTC')::date + 1;
+ v_state text;
+BEGIN
+ INSERT INTO "companyGroup" (name, "createdBy") VALUES ('Loaded op test', 'system') RETURNING id INTO v_group_id;
+ INSERT INTO company (name, "companyGroupId", "baseCurrencyCode", timezone)
+ VALUES ('Loaded op test', v_group_id, 'USD', 'UTC') RETURNING id INTO v_company_id;
+ INSERT INTO location (name, "addressLine1", city, "postalCode", "companyId", "createdBy", timezone)
+ VALUES ('Plant', '1 Test Way', 'Testville', '00000', v_company_id, 'system', 'UTC') RETURNING id INTO v_location_id;
+ INSERT INTO "unitOfMeasure" (code, name, "companyId", "createdBy")
+ VALUES ('EA', 'Each', v_company_id, 'system') ON CONFLICT DO NOTHING;
+ INSERT INTO item ("readableId", name, type, "replenishmentSystem", "itemTrackingType", "unitOfMeasureCode", "companyId", "createdBy")
+ VALUES ('T-PART', 'Part', 'Part', 'Make', 'Inventory', 'EA', v_company_id, 'system') RETURNING id INTO v_item;
+ INSERT INTO process (name, "processType", "defaultStandardFactor", "companyId", "createdBy")
+ VALUES ('Milling', 'Process', 'Hours/Piece', v_company_id, 'system') RETURNING id INTO v_process;
+ INSERT INTO "workCenter" (name, "locationId", "laborRate", "machineRate", "overheadRate", "defaultStandardFactor", "companyId", "createdBy")
+ VALUES ('Haas 2', v_location_id, 0, 0, 0, 'Hours/Piece', v_company_id, 'system') RETURNING id INTO v_work_center;
+
+ v_job := pg_temp.make_job(v_company_id, v_location_id, v_item, 'J-LOAD', 1);
+ v_a := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 1);
+ v_b := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 2);
+ -- A third operation keeps B's completion from finishing the job.
+ v_c := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 3);
+
+ -- 1. An open Setup event loads A.
+ PERFORM pg_temp.add_event(v_a, v_work_center, 'Setup', v_day + time '10:00', NULL);
+ v_state := pg_temp.loaded(v_work_center);
+ ASSERT v_state = v_a || '@10:00', 'open event loads A: ' || v_state;
+ v_state := pg_temp.history(v_work_center);
+ ASSERT v_state = v_a || '@10:00-open', 'A opens a load: ' || v_state;
+
+ -- 2. An event inserted with an endTime never loads.
+ PERFORM pg_temp.add_event(v_b, v_work_center, 'Machine', v_day + time '09:00', v_day + time '09:30');
+ v_state := pg_temp.loaded(v_work_center);
+ ASSERT v_state = v_a || '@10:00', 'closed event does not load: ' || v_state;
+
+ -- 3. An open event that started before the current load does not replace it.
+ PERFORM pg_temp.add_event(v_b, v_work_center, 'Labor', v_day + time '09:50', NULL);
+ v_state := pg_temp.loaded(v_work_center);
+ ASSERT v_state = v_a || '@10:00', 'older open event does not load: ' || v_state;
+ v_state := pg_temp.history(v_work_center);
+ ASSERT v_state = v_a || '@10:00-open', 'no load for a closed or older event: ' || v_state;
+
+ -- 4. A later open event loads B.
+ PERFORM pg_temp.add_event(v_b, v_work_center, 'Labor', v_day + time '10:10', NULL);
+ v_state := pg_temp.loaded(v_work_center);
+ ASSERT v_state = v_b || '@10:10', 'later open event loads B: ' || v_state;
+ v_state := pg_temp.history(v_work_center);
+ ASSERT v_state = v_a || '@10:00-10:10 ' || v_b || '@10:10-open',
+ 'B''s load ends A''s where it starts: ' || v_state;
+
+ -- A Pause keeps the load.
+ UPDATE "jobOperation" SET status = 'Paused', "updatedBy" = 'system' WHERE id = v_b;
+ v_state := pg_temp.loaded(v_work_center);
+ ASSERT v_state = v_b || '@10:10', 'Paused keeps B loaded: ' || v_state;
+ v_state := pg_temp.history(v_work_center);
+ ASSERT v_state = v_a || '@10:00-10:10 ' || v_b || '@10:10-open',
+ 'Paused keeps B''s load open: ' || v_state;
+
+ -- 5. B going Done unloads it.
+ UPDATE "jobOperation" SET status = 'Done', "updatedBy" = 'system' WHERE id = v_b;
+ v_state := pg_temp.loaded(v_work_center);
+ ASSERT v_state = 'none@none', 'Done unloads B: ' || v_state;
+ v_state := pg_temp.history(v_work_center);
+ ASSERT v_state = v_a || '@10:00-10:10 ' || v_b || '@10:10-10:10',
+ 'Done ends B''s load: ' || v_state;
+
+ -- A start older than the newest unload never loads: a late event cannot
+ -- undo the unload that came after it.
+ PERFORM pg_temp.add_event(v_a, v_work_center, 'Machine', v_day + time '10:05', NULL);
+ v_state := pg_temp.loaded(v_work_center);
+ ASSERT v_state = 'none@none', 'a start before the unload does not load: ' || v_state;
+
+ -- Canceled unloads too.
+ PERFORM pg_temp.add_event(v_c, v_work_center, 'Setup', v_day + time '11:00', NULL);
+ ASSERT pg_temp.loaded(v_work_center) = v_c || '@11:00', 'C loads';
+ UPDATE "jobOperation" SET status = 'Canceled', "updatedBy" = 'system' WHERE id = v_c;
+ v_state := pg_temp.loaded(v_work_center);
+ ASSERT v_state = 'none@none', 'Canceled unloads C: ' || v_state;
+ v_state := pg_temp.history(v_work_center);
+ ASSERT v_state LIKE '% ' || v_c || '@11:00-11:00', 'Canceled ends C''s load: ' || v_state;
+
+ -- Deleting the loaded operation unloads it (the pointer has no FK).
+ v_d := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 4);
+ PERFORM pg_temp.add_event(v_d, v_work_center, 'Setup', v_day + time '12:00', NULL);
+ ASSERT pg_temp.loaded(v_work_center) = v_d || '@12:00', 'D loads';
+ DELETE FROM "productionEvent" WHERE "jobOperationId" = v_d;
+ DELETE FROM "jobOperation" WHERE id = v_d;
+ v_state := pg_temp.loaded(v_work_center);
+ ASSERT v_state = 'none@none', 'deleting D unloads it: ' || v_state;
+ v_state := pg_temp.history(v_work_center);
+ ASSERT v_state LIKE '% ' || v_d || '@12:00-12:00', 'deleting D ends its load: ' || v_state;
+
+ -- Moving the loaded operation to another work center unloads the old one.
+ v_e := pg_temp.add_operation(v_job, v_company_id, v_process, v_work_center, 5);
+ PERFORM pg_temp.add_event(v_e, v_work_center, 'Setup', v_day + time '12:30', NULL);
+ ASSERT pg_temp.loaded(v_work_center) = v_e || '@12:30', 'E loads';
+ INSERT INTO "workCenter" (name, "locationId", "laborRate", "machineRate", "overheadRate", "defaultStandardFactor", "companyId", "createdBy")
+ VALUES ('Haas 3', v_location_id, 0, 0, 0, 'Hours/Piece', v_company_id, 'system') RETURNING id INTO v_work_center_2;
+ UPDATE "jobOperation" SET "workCenterId" = v_work_center_2, "updatedBy" = 'system' WHERE id = v_e;
+ v_state := pg_temp.loaded(v_work_center);
+ ASSERT v_state = 'none@none', 'moving E unloads the old work center: ' || v_state;
+ v_state := pg_temp.history(v_work_center);
+ ASSERT v_state LIKE '% ' || v_e || '@12:30-12:30', 'moving E ends its load there: ' || v_state;
+
+ -- Another company's event never loads onto this company's work center:
+ -- its own operation on our work center, or our operation under its company.
+ INSERT INTO company (name, "companyGroupId", "baseCurrencyCode", timezone)
+ VALUES ('Loaded op other', v_group_id, 'USD', 'UTC') RETURNING id INTO v_other_company;
+ INSERT INTO location (name, "addressLine1", city, "postalCode", "companyId", "createdBy", timezone)
+ VALUES ('Other plant', '2 Test Way', 'Testville', '00000', v_other_company, 'system', 'UTC') RETURNING id INTO v_other_location;
+ INSERT INTO "unitOfMeasure" (code, name, "companyId", "createdBy")
+ VALUES ('EA', 'Each', v_other_company, 'system') ON CONFLICT DO NOTHING;
+ INSERT INTO item ("readableId", name, type, "replenishmentSystem", "itemTrackingType", "unitOfMeasureCode", "companyId", "createdBy")
+ VALUES ('T-OTHER', 'Other part', 'Part', 'Make', 'Inventory', 'EA', v_other_company, 'system') RETURNING id INTO v_other_item;
+ INSERT INTO process (name, "processType", "defaultStandardFactor", "companyId", "createdBy")
+ VALUES ('Milling', 'Process', 'Hours/Piece', v_other_company, 'system') RETURNING id INTO v_other_process;
+ INSERT INTO "workCenter" (name, "locationId", "laborRate", "machineRate", "overheadRate", "defaultStandardFactor", "companyId", "createdBy")
+ VALUES ('Other Haas', v_other_location, 0, 0, 0, 'Hours/Piece', v_other_company, 'system') RETURNING id INTO v_other_work_center;
+ v_other_job := pg_temp.make_job(v_other_company, v_other_location, v_other_item, 'J-OTHER', 1);
+ v_other_op := pg_temp.add_operation(v_other_job, v_other_company, v_other_process, v_other_work_center, 1);
+
+ PERFORM pg_temp.add_event(v_other_op, v_work_center, 'Machine', v_day + time '13:00', NULL);
+ v_state := pg_temp.loaded(v_work_center);
+ ASSERT v_state = 'none@none', 'another company''s event does not load our work center: ' || v_state;
+
+ INSERT INTO "productionEvent" ("jobOperationId", "workCenterId", type, "startTime", "companyId", "createdBy")
+ VALUES (v_other_op, v_work_center, 'Machine', v_day + time '13:05', v_company_id, 'system');
+ v_state := pg_temp.loaded(v_work_center);
+ ASSERT v_state = 'none@none', 'another company''s operation does not load: ' || v_state;
+ ASSERT (SELECT count(*) FROM "workCenterLoad" WHERE "jobOperationId" = v_other_op) = 0,
+ 'another company''s operation has no load';
+
+ -- The history refuses an end before its start and a second open load.
+ BEGIN
+ INSERT INTO "workCenterLoad" ("companyId", "workCenterId", "jobOperationId", "loadedAt", "unloadedAt")
+ VALUES (v_company_id, v_work_center, v_a, v_day + time '14:00', v_day + time '13:00');
+ RAISE EXCEPTION 'FAIL: an end before the start was allowed';
+ EXCEPTION WHEN check_violation THEN NULL;
+ END;
+ PERFORM pg_temp.add_event(v_a, v_work_center, 'Setup', v_day + time '14:00', NULL);
+ BEGIN
+ INSERT INTO "workCenterLoad" ("companyId", "workCenterId", "jobOperationId", "loadedAt")
+ VALUES (v_company_id, v_work_center, v_c, v_day + time '14:30');
+ RAISE EXCEPTION 'FAIL: a second open load was allowed';
+ EXCEPTION WHEN unique_violation THEN NULL;
+ END;
+
+ -- Retention: an unload older than 7 days goes, an open load stays.
+ INSERT INTO "workCenterLoad" ("companyId", "workCenterId", "jobOperationId", "loadedAt", "unloadedAt")
+ VALUES (v_company_id, v_work_center_2, v_a, now() - interval '9 days', now() - interval '8 days'),
+ (v_company_id, v_work_center_2, v_c, now() - interval '3 days', now() - interval '2 days');
+ PERFORM util.purge_work_center_loads();
+ ASSERT (SELECT count(*) FROM "workCenterLoad" WHERE "workCenterId" = v_work_center_2 AND "jobOperationId" = v_a
+ AND "loadedAt" < now() - interval '7 days') = 0, 'a load unloaded 8 days ago is purged';
+ ASSERT (SELECT count(*) FROM "workCenterLoad" WHERE "workCenterId" = v_work_center_2 AND "jobOperationId" = v_c
+ AND "loadedAt" < now()) = 1, 'a load unloaded 2 days ago stays';
+ ASSERT pg_temp.loaded(v_work_center) = v_a || '@14:00', 'the open load is never purged';
+
+ -- 6. Several active integrations of the oee role are allowed.
+ INSERT INTO "integration" (id, jsonschema, "providerRole")
+ VALUES ('oee-test', '{"type": "object", "properties": {}}'::json, 'oee');
+ INSERT INTO "companyIntegration" (id, "companyId", metadata, active, "updatedBy")
+ VALUES ('sense', v_company_id, '{}'::json, true, 'system');
+ INSERT INTO "companyIntegration" (id, "companyId", metadata, active, "updatedBy")
+ VALUES ('oee-test', v_company_id, '{}'::json, true, 'system');
+ ASSERT (SELECT count(*) FROM "companyIntegration" WHERE "companyId" = v_company_id AND active) = 2,
+ 'two active oee integrations';
+
+ -- 7. The accounting role still allows one.
+ INSERT INTO "companyIntegration" (id, "companyId", metadata, active, "updatedBy")
+ VALUES ('xero', v_company_id, '{}'::json, true, 'system');
+ BEGIN
+ INSERT INTO "companyIntegration" (id, "companyId", metadata, active, "updatedBy")
+ VALUES ('quickbooks', v_company_id, '{}'::json, true, 'system');
+ RAISE EXCEPTION 'FAIL: a second active accounting integration was allowed';
+ EXCEPTION WHEN unique_violation THEN NULL;
+ END;
+
+ RAISE NOTICE 'ALL work-center-loaded-operation TESTS PASSED';
+END;
+$cases$;
+
+ROLLBACK;
diff --git a/packages/ee/AGENTS.md b/packages/ee/AGENTS.md
index 929fdb5f14..30bcb01c6b 100644
--- a/packages/ee/AGENTS.md
+++ b/packages/ee/AGENTS.md
@@ -40,6 +40,9 @@ pnpm --filter @carbon/ee typecheck
| `./integrations/secrets` | `patchIntegrationState`, Vault split/persist/resolve helpers, `SECRET_KEYS` |
| `./ramp.server` | Ramp client, schemas, service operations, money/coding helpers, and key-owned state patches |
| `./ramp/hooks.server` | `rampOnInstall`, `rampOnUpdate`, `rampOnUninstall`, `rampHealthcheck` |
+| `./oee` | Client-safe OEE provider contract (`OeeProvider`, `OeeDevice`, `OeeStateChange`, `MachineState`, `OeeProviderUnavailableError` — network failure, timeout or 5xx; the sync stops its run on it — and `DEFAULT_MINIMUM_STATE_SECONDS`), the pure attribution engine `planMachineTime` (`LoadPeriod`, `BlockPeriod`, `RecordedInterval`, `MachineTimeWrite`), and `machineTimeRefusal(operationStatus, jobStatus)` (`oee/assignable.ts`: `"Done"`, `"Canceled"`, `"Locked"` or null — the one "can this operation take machine time" rule for the sync, the assign write and the ERP suggestion cards) |
+| `./oee.server` | `getOeeProvider` (runtime, degrades through `companyHasFeature("INTEGRATIONS")`; resolves through `createOeeProvider` in `oee/registry.ts`, the one provider resolution, also behind the Sense healthcheck) and the authoring writes `upsertWorkCenterDevice`, `deleteWorkCenterDevice`, `assignUnattributedMachineTime`, `dismissUnattributedMachineTime` (each embeds `requireEntitlement("INTEGRATIONS")`). See `.claude/rules/oee-provider.md` |
+| `./sense/hooks.server` | `senseHealthcheck`, `senseOnUninstall` (the `onUninstall` hook that Settings → Integrations → Uninstall runs, registered in `hooks.server.ts`: ends the open sensor Machine events and running unattributed time of every Sense device of the company, under each device lock; the mappings stay) |
| `./hooks.server` | `getIntegrationServerHooks()` registry |
| `./approvals/document.server` | The document-level approval lifecycle shared by every approval document type: `getDocumentApprovalState`, `openApprovalRequests` (bulk; caller sends the notification), `cancelPendingApprovals` (bulk, optional requester-or-approver guard), `decideApprovalRequest`. Form validator: `approvalDecisionValidator` in `./approvals`; modal: `~/components/Modals/ApprovalDecision` in the ERP. Used by change notices, quality documents and suppliers; purchase orders keep their own amount-tiered flow |
| `./plan`, `./plan.server` | Client/server edition and feature-plan gates |
@@ -70,11 +73,11 @@ pnpm --filter @carbon/ee typecheck
- **Permissions** (`./permissions.server`, `src/permissions.server.ts`): the licensed RBAC-authoring logic, gated to Business via the `PERMISSIONS` feature. `updatePermissions` (builds/persists the flattened `userPermission.permissions` object + audit diff + claims-cache bust), `updateEmployee`, employee-type CRUD (`insert/upsert/deleteEmployeeType`, `upsertEmployeeTypePermissions`), and the translators (`makeEmptyPermissionsFromModules`, `makeCompanyPermissionsFromClaims`, `makeCompanyPermissionsFromEmployeeType`). This is the ONLY copy of `updatePermissions` — the `@carbon/jobs` `carbon/update-permissions` (bulk-edit) task imports it here. **Server-only.** The ERP authoring UI stays `.ee.tsx` in `apps/erp` (couples to `~/components/Form`); routes stay in the app and gate with `requireFeature({ feature: "PERMISSIONS" })`. The community invite primitives (`setUserPermissions`, `makePermissionsFromEmployeeType`) deliberately stay in the app's `users.server.ts`. Console/kiosk mode is a sibling: `./console.server` — `updateConsoleSetting(client, db, companyId, enabled, userId?)` → `{ error, pin, pinError }` writes `companySettings.consoleEnabled` over `db` (a trigger refuses API-role writes) behind `requireEntitlement("PERMISSIONS")`, provisions the protected "Console Operator" employee type and a PIN for the enabling user (returned once as `pin`; `pinError` when it could not be created); `isConsoleModeEnabledForCompany(client, companyId, { consoleEnabled? })` is the runtime DEGRADE gate (flag AND entitlement; `null` when the settings read failed — never tear a live console session down on `null`); `generateConsolePin`, `setEmployeePin(db, …)`, `verifyEmployeePin(db, …)` → `{ hasPin, valid }` work on the bcrypt `employeePin` table, reachable only over the server's Kysely connection.
- **Commercial entitlement pattern** (`./entitlements.server`, `./plan.server`, and the per-feature `.server` modules): `requireEntitlement(client, companyId, feature)` (throws `EntitlementError`) is embedded at the top of every commercial authoring function so the gate lives in commercial code, not a strippable open route. Feature bodies moved here with in-code gates: `./approvals` (approval rules), `./rules.server` (sales + storage rules), `./api-keys.server`, `./webhooks.server`, `./two-factor.server` (the `requireMfa` policy), `./forecast.server` (demand forecasts + projections), `./customer-portals.server`, `./audit.server` (the audit-log engine — `enableAuditLog` embeds `requireEntitlement("AUDIT_LOG")`, skipped under `CONTROLLED_ENVIRONMENT` where audit is mandatory; `auditConfig`/types stay client-safe in `@carbon/database`), `./email-notifications.server` (`emailNotificationsEnabled` — the EMAIL notification-channel gate, runtime DEGRADE; `sendEmail` transactional transport stays ungated in `@carbon/lib`), `./backups.server` (`requireBackupsEntitlement(companyId)` — embedded at the top of the Inngest backup/restore/import durable functions in `@carbon/jobs`, `IS_LOCAL_DEV`-exempt; the engine is Inngest-coupled and stays in jobs), plus permissions/console above. Runtime paths that must degrade (not throw) use `companyHasFeature` (e.g. email notifications, webhook delivery). Full rationale: `.claude/rules/commercial-licensing.md`.
- **Ramp state helpers**: `src/ramp/lib/service.ts` is a compatibility facade. Put connection/auth in `connection.ts`, coding masters in `chart-of-accounts.ts`/`cost-centers.ts`, parties in `suppliers.ts`, PO/bill transport in `spend.ts`, confirms in `sync-confirmation.ts`, remote webhook lifecycle in `webhooks.ts`, and metadata/Vault writes in `state.ts`; `@carbon/ee/ramp.server` remains stable
-- **Provider roles**: every integration that participates in sync declares `providerRole: "accounting" | "spend"` on its descriptor. That ONE declaration replaces the id lists that used to answer "which are accounting providers" five different ways, and the database enforces at most one ACTIVE integration per role per company (`companyIntegration_single_active_role`, migration `20260924133915`). `getIntegrationsByRole`/`getIntegrationIdsByRole` (barrel) are the lookups; `no-integration-id-branching` (`@carbon/checks`) stops new id branching. NOTE the barrel cannot be imported from a `*.service.ts` (browser-bundled) or from most tests — it reaches `@carbon/auth`, which validates the full server env at import time; that is why `./sync` takes the registry slice as an argument instead of importing it
+- **Provider roles**: every integration that participates in sync declares `providerRole: "accounting" | "spend" | "oee"` on its descriptor. That ONE declaration replaces the id lists that used to answer "which are accounting providers" five different ways, and the database enforces at most one ACTIVE integration per role per company (`companyIntegration_single_active_role`, migration `20260924133915`) — except `oee`, which may have several active integrations at once (`check_single_active_provider_role()` skips it, migration `20261013030022`); its one-device-per-work-center rule is `UNIQUE(workCenterId, companyId)` on `workCenterDevice` instead (`.claude/rules/oee-provider.md`). `getIntegrationsByRole`/`getIntegrationIdsByRole` (barrel) are the lookups; `no-integration-id-branching` (`@carbon/checks`) stops new id branching. NOTE the barrel cannot be imported from a `*.service.ts` (browser-bundled) or from most tests — it reaches `@carbon/auth`, which validates the full server env at import time; that is why `./sync` takes the registry slice as an argument instead of importing it
- **Ledger delegation**: when a spend provider's mode declares `ownsLedgerFamilies`, `applyLedgerDelegation` sets that family to `"none"` AND disables its backing entities — derived from `POSTING_POLICY`, never a hard-coded `"bill"`. Each half alone is wrong (families-only leaves the document pushing; entity-only parks a `DOC_SYNC_DISABLED` Warning forever). `getJournalPostingPolicyDecision` accepts only `EffectivePostingSyncSettings`, so the compiler refuses a posting decision made from raw settings
- **Integration pattern**: `defineIntegration()` → config with id, name, settings, OAuth, actions
- **SAML SSO** (`./sso.server`, `src/sso/`): `isSsoEnabled()` (`gate.ts` — Enterprise edition AND `sso` in `AUTH_PROVIDERS`) is the ONE flag; the connection lookups and admin mutations self-gate on it. `provider.server.ts` = GoTrue admin API wrappers + `getSamlSpUrls`; `connections.server.ts` = `ssoConnection` lookups (each attaches a computed `domains: string[]` of VERIFIED `ssoDomain` claims), `isSsoRequiredForEmail`, `getSsoAwareInviteLink`, upsert/requireSso/deactivate mutations, and the domain-claim flows `addSsoDomain`/`verifySsoDomain`/`removeSsoDomain`; `verification.server.ts` = the DNS TXT ownership challenge (`_carbon-challenge.<domain>` → `carbon-domain-verification=<token>`, `checkDomainVerification` with pinned public resolvers, one-shot manual verify — no polling or re-verification); `session.server.ts` = amr-based session classification (`getSsoProviderIdFromSession` for enforcement, never `getSsoProviderIdFromUser`); `provisioning.server.ts` = identity linking + invite-first migration + `deleteJitSsoUser` (full removal of a rejected throwaway JIT user — auth user AND its trigger-created `user`/`userPermission` rows, guarded on zero memberships; takes a `Kysely<KyselyDatabase>` param — callers pass their own db client) + the **pre-seed** helpers `seedSsoIdentityForUser` / `backfillSsoIdentitiesForDomain` / `removeSsoIdentitiesForDomain` (+ pure `emailDomain` / `ssoProviderColumn`). Pre-seeding is the account-linking fix under `GOTRUE_DISABLE_SIGNUP=true`: a row in `auth.identities` with `identity_data.email = lower(email)` makes GoTrue link a SAML sign-in to the existing user via its **email-column** fallback — provider-agnostic (works for any IdP: Okta/Entra/OneLogin/Ping/…, whose NameID shapes differ), keyed on the generated `email` column NOT `provider_id`. `verifySsoDomain` backfills every existing on-domain user when a domain is verified; the three account-creation flows (`apps/erp/.../users.server.ts`) seed newly-invited users; `removeSsoDomain` tears the domain's identities down. A DB guard trigger on `auth.sso_domains` (migration `…_sso-domain-guard.sql`, `ssoReservedDomain` table) blocks registering an unclaimed/reserved domain. Only verified domains ever reach GoTrue. Full architecture + the provider-agnostic linking rationale: `.claude/rules/authentication-system.md` (Enterprise SAML SSO section); design: `.ai/specs/2026-08-29-saml-sso-account-linking.md`
-- **Exports**: `./accounting`, `./plan`, `./plan.server`, `./entitlements.server`, `./permissions.server`, `./console.server`, `./approvals`, `./audit.server`, `./backups.server`, `./email-notifications.server`, `./api-keys.server`, `./webhooks.server`, `./two-factor.server`, `./forecast.server`, `./customer-portals.server`, `./mcp`, `./mcp.server`, `./rules` (client-safe storage + sales rule query services/UI), `./rules.server` (both evaluators AND the entitlement-gated authoring writes — `upsertEnforcementRule`/`deleteEnforcementRule`/`assign*`/`unassign*` in `rules/service.server.ts`, each embedding `requireEntitlement("SALES_RULES"|"STORAGE_RULES")`), `./workflows`, `./workflows/help`, `./workflows/labels`, `./workflows.server`, `./slack.server`, `./hooks.server`, `./sso.server`, `./jira`, `./linear`, `./rillet/hooks.server`, `./xero/hooks.server`, `./ramp.server`, `./ramp/hooks.server`, etc.
+- **Exports**: `./accounting`, `./plan`, `./plan.server`, `./entitlements.server`, `./permissions.server`, `./console.server`, `./approvals`, `./audit.server`, `./backups.server`, `./email-notifications.server`, `./api-keys.server`, `./webhooks.server`, `./two-factor.server`, `./forecast.server`, `./customer-portals.server`, `./mcp`, `./mcp.server`, `./rules` (client-safe storage + sales rule query services/UI), `./rules.server` (both evaluators AND the entitlement-gated authoring writes — `upsertEnforcementRule`/`deleteEnforcementRule`/`assign*`/`unassign*` in `rules/service.server.ts`, each embedding `requireEntitlement("SALES_RULES"|"STORAGE_RULES")`), `./workflows`, `./workflows/help`, `./workflows/labels`, `./workflows.server`, `./slack.server`, `./hooks.server`, `./sso.server`, `./jira`, `./linear`, `./rillet/hooks.server`, `./xero/hooks.server`, `./ramp.server`, `./ramp/hooks.server`, `./oee`, `./oee.server`, `./sense/hooks.server`, etc.
## Cross-References
diff --git a/packages/ee/package.json b/packages/ee/package.json
index 03e8225356..1e1576f927 100644
--- a/packages/ee/package.json
+++ b/packages/ee/package.json
@@ -20,6 +20,8 @@
"./mcp.server": "./src/mcp/server.ts",
"./integrations/secrets": "./src/integrations/secrets.ts",
"./action-task-entity": "./src/lib/actionTaskEntity.ts",
+ "./oee": "./src/oee/index.ts",
+ "./oee.server": "./src/oee/service.server.ts",
"./rules": "./src/rules/index.ts",
"./rules.server": "./src/rules/server.ts",
"./jira": "./src/jira/lib/index.ts",
@@ -45,6 +47,7 @@
"./ramp/entities": "./src/ramp/entities/index.ts",
"./ramp/hooks.server": "./src/ramp/hooks.server.ts",
"./rillet/hooks.server": "./src/rillet/hooks.server.ts",
+ "./sense/hooks.server": "./src/sense/hooks.server.ts",
"./xero/hooks.server": "./src/xero/hooks.server.ts",
"./stripe-connect.server": "./src/stripe-connect/payment.server.ts",
"./two-factor.server": "./src/two-factor.server.ts",
diff --git a/packages/ee/src/hooks.server.ts b/packages/ee/src/hooks.server.ts
index 6428ad308c..9bde0ef71b 100644
--- a/packages/ee/src/hooks.server.ts
+++ b/packages/ee/src/hooks.server.ts
@@ -22,6 +22,7 @@ import {
rilletOnInstall,
rilletOnUninstall
} from "./rillet/hooks.server";
+import { senseHealthcheck, senseOnUninstall } from "./sense/hooks.server";
import {
stripeConnectHealthcheck,
stripeConnectOnInstall,
@@ -91,6 +92,10 @@ const serverHooks: Record<string, IntegrationServerHooks> = {
onUpdate: rilletOnInstall,
onUninstall: rilletOnUninstall
},
+ sense: {
+ onHealthcheck: senseHealthcheck,
+ onUninstall: senseOnUninstall
+ },
xero: {
onHealthcheck: xeroHealthcheck,
onInstall: xeroOnInstall,
diff --git a/packages/ee/src/index.ts b/packages/ee/src/index.ts
index e77352f27a..429aedf0a3 100644
--- a/packages/ee/src/index.ts
+++ b/packages/ee/src/index.ts
@@ -13,6 +13,7 @@ import { QuickBooks } from "./quickbooks/config";
import { Ramp } from "./ramp/config";
import { Rillet } from "./rillet/config";
import { Sage } from "./sage/config";
+import { Sense } from "./sense/config";
import { Slack } from "./slack/config";
import { StripeConnect } from "./stripe-connect/config";
import type { QuickInstallConnector } from "./types";
@@ -66,6 +67,7 @@ export const integrations = [
Ramp,
Rillet,
Sage,
+ Sense,
Slack,
Xero,
StripeConnect
@@ -92,6 +94,7 @@ export { PaperlessPartsClient } from "./paperless-parts/lib/client";
export { QuickBooks } from "./quickbooks/config";
export { Ramp } from "./ramp/config";
export { Rillet } from "./rillet/config";
+export { Sense } from "./sense/config";
export { Slack } from "./slack/config";
export * from "./slack/lib/messages";
export { StripeConnect } from "./stripe-connect/config";
@@ -115,7 +118,7 @@ export const getIntegrationConfigById = (id: IntegrationID) => {
* in the accounting layout, and `.eq("id","ramp")` in the Ramp sweep. A new
* provider joins by declaring its role, not by being added to a list.
*/
-export type ProviderRole = "accounting" | "spend";
+export type ProviderRole = "accounting" | "spend" | "oee";
/**
* `integrations` is a union of concrete descriptor types, and only the four
diff --git a/packages/ee/src/integrations/secrets.ts b/packages/ee/src/integrations/secrets.ts
index c5e06da92e..1e398baf59 100644
--- a/packages/ee/src/integrations/secrets.ts
+++ b/packages/ee/src/integrations/secrets.ts
@@ -52,6 +52,7 @@ export const SECRET_KEYS: Record<string, string[]> = {
],
rillet: ["credentials.apiKey", "credentials.providerMetadata.webhookToken"],
"paperless-parts": ["apiKey", "secretKey"],
+ sense: ["apiKey"],
resend: ["apiKey"],
// email carries a secret in EITHER variant: Resend `apiKey` or SMTP `password`
// (top-level). splitSecrets omits whichever is absent for the active provider.
diff --git a/packages/ee/src/oee/assignable.ts b/packages/ee/src/oee/assignable.ts
new file mode 100644
index 0000000000..6eeca1419b
--- /dev/null
+++ b/packages/ee/src/oee/assignable.ts
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { isJobLocked } from "@carbon/utils";
+
+/** Why an operation cannot take machine time. */
+export type MachineTimeRefusal = "Done" | "Canceled" | "Locked";
+
+/**
+ * Why an operation cannot take machine time, or null when it can: it is Done
+ * or Canceled, or its job is locked. The one rule for the sync, the assign
+ * write and the review's suggestion cards.
+ */
+export function machineTimeRefusal(
+ operationStatus: string | null | undefined,
+ jobStatus: string | null | undefined
+): MachineTimeRefusal | null {
+ if (operationStatus === "Done" || operationStatus === "Canceled") {
+ return operationStatus;
+ }
+ return isJobLocked(jobStatus) ? "Locked" : null;
+}
diff --git a/packages/ee/src/oee/engine.test.ts b/packages/ee/src/oee/engine.test.ts
new file mode 100644
index 0000000000..f170b9343e
--- /dev/null
+++ b/packages/ee/src/oee/engine.test.ts
@@ -0,0 +1,1169 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { describe, expect, it } from "vitest";
+import { type PlanMachineTimeInput, planMachineTime } from "./engine";
+
+const t = (hhmmss: string) => `2026-10-12T${hhmmss}.000Z`;
+
+const base = (
+ overrides: Partial<PlanMachineTimeInput>
+): PlanMachineTimeInput => ({
+ now: t("12:00:00"),
+ minimumStateSeconds: 60,
+ mappedAt: t("06:00:00"),
+ currentState: "Idle",
+ currentStateAt: t("08:00:00"),
+ lastManualChangeAt: null,
+ loads: [
+ { jobOperationId: "A", from: t("07:00:00"), to: null, assignable: true }
+ ],
+ firstUnplannedPressAt: null,
+ blocks: [],
+ openMachineEvent: null,
+ openUnattributed: null,
+ lastMachineEventEndTime: null,
+ recordedIntervals: [],
+ changes: [],
+ ...overrides
+});
+
+describe("planMachineTime", () => {
+ it("opens a Machine event on the loaded operation when the machine runs", () => {
+ const result = planMachineTime(
+ base({ changes: [{ state: "Running", changedAt: t("10:00:00") }] })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertMachineEvent",
+ jobOperationId: "A",
+ startTime: t("10:00:00"),
+ endTime: null
+ }
+ ]);
+ expect(result.currentState).toBe("Running");
+ expect(result.currentStateAt).toBe(t("10:00:00"));
+ expect(result.appliedThrough).toBe(t("10:00:00"));
+ });
+
+ it("inserts a closed event for a run that starts and ends in one sync", () => {
+ const result = planMachineTime(
+ base({
+ changes: [
+ { state: "Running", changedAt: t("10:00:00") },
+ { state: "Idle", changedAt: t("10:30:00") }
+ ]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertMachineEvent",
+ jobOperationId: "A",
+ startTime: t("10:00:00"),
+ endTime: t("10:30:00")
+ }
+ ]);
+ });
+
+ it("closes the open event when the machine goes idle", () => {
+ const result = planMachineTime(
+ base({
+ currentState: "Running",
+ currentStateAt: t("10:00:00"),
+ openMachineEvent: {
+ id: "pe1",
+ jobOperationId: "A",
+ startTime: t("10:00:00"),
+ system: true
+ },
+ changes: [{ state: "Idle", changedAt: t("10:45:00") }]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "closeMachineEvent",
+ productionEventId: "pe1",
+ endTime: t("10:45:00")
+ }
+ ]);
+ });
+
+ it("records unattributed time when nothing is loaded", () => {
+ const result = planMachineTime(
+ base({
+ loads: [],
+ changes: [{ state: "Running", changedAt: t("10:00:00") }]
+ })
+ );
+ expect(result.writes).toEqual([
+ { kind: "insertUnattributed", startTime: t("10:00:00"), endTime: null }
+ ]);
+ });
+
+ it("records unattributed time while maintenance blocks the work center", () => {
+ const result = planMachineTime(
+ base({
+ blocks: [{ from: t("09:00:00"), to: null }],
+ changes: [{ state: "Running", changedAt: t("10:00:00") }]
+ })
+ );
+ expect(result.writes).toEqual([
+ { kind: "insertUnattributed", startTime: t("10:00:00"), endTime: null }
+ ]);
+ });
+
+ it("stops a running event when maintenance starts and keeps the rest unattributed", () => {
+ const result = planMachineTime(
+ base({
+ currentState: "Running",
+ currentStateAt: t("09:00:00"),
+ openMachineEvent: {
+ id: "pe1",
+ jobOperationId: "A",
+ startTime: t("09:00:00"),
+ system: true
+ },
+ blocks: [{ from: t("10:30:00"), to: null }]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "closeMachineEvent",
+ productionEventId: "pe1",
+ endTime: t("10:30:00")
+ },
+ { kind: "insertUnattributed", startTime: t("10:30:00"), endTime: null }
+ ]);
+ });
+
+ it("splits a run that straddles the start of maintenance", () => {
+ const result = planMachineTime(
+ base({
+ blocks: [{ from: t("10:30:00"), to: null }],
+ changes: [
+ { state: "Running", changedAt: t("10:00:00") },
+ { state: "Idle", changedAt: t("11:00:00") }
+ ]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertMachineEvent",
+ jobOperationId: "A",
+ startTime: t("10:00:00"),
+ endTime: t("10:30:00")
+ },
+ {
+ kind: "insertUnattributed",
+ startTime: t("10:30:00"),
+ endTime: t("11:00:00")
+ }
+ ]);
+ });
+
+ it("does not reopen job time after maintenance closed the event", () => {
+ // A Down dispatch ends the work center's events when it is created; the
+ // machine still runs, so the time after it is unattributed, not the job's.
+ const result = planMachineTime(
+ base({
+ currentState: "Running",
+ currentStateAt: t("09:00:00"),
+ lastMachineEventEndTime: t("10:30:00"),
+ blocks: [{ from: t("10:30:00"), to: null }]
+ })
+ );
+ expect(result.writes).toEqual([
+ { kind: "insertUnattributed", startTime: t("10:30:00"), endTime: null }
+ ]);
+ });
+
+ it("leaves an event the operator started after maintenance began", () => {
+ const result = planMachineTime(
+ base({
+ currentState: "Running",
+ currentStateAt: t("09:00:00"),
+ lastManualChangeAt: t("10:45:00"),
+ openMachineEvent: {
+ id: "pe2",
+ jobOperationId: "A",
+ startTime: t("10:45:00"),
+ system: false
+ },
+ blocks: [{ from: t("10:30:00"), to: null }]
+ })
+ );
+ expect(result.writes).toEqual([]);
+ });
+
+ it("queues a run until an operation loads, then charges the operation", () => {
+ const result = planMachineTime(
+ base({
+ loads: [
+ {
+ jobOperationId: "A",
+ from: t("10:05:00"),
+ to: null,
+ assignable: true
+ }
+ ],
+ changes: [{ state: "Running", changedAt: t("10:00:00") }]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertUnattributed",
+ startTime: t("10:00:00"),
+ endTime: t("10:05:00")
+ },
+ {
+ kind: "insertMachineEvent",
+ jobOperationId: "A",
+ startTime: t("10:05:00"),
+ endTime: null
+ }
+ ]);
+ });
+
+ it("after an operator's Stop on a running machine, queues the time until it stops; the next run goes to the operation", () => {
+ // The event was open since 10:00; the operator pressed Stop at 10:03,
+ // which closed it. The machine ran on until 11:00, then started again.
+ const result = planMachineTime(
+ base({
+ currentState: "Running",
+ currentStateAt: t("10:00:00"),
+ lastManualChangeAt: t("10:03:00"),
+ changes: [
+ { state: "Idle", changedAt: t("11:00:00") },
+ { state: "Running", changedAt: t("11:05:00") }
+ ]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertUnattributed",
+ startTime: t("10:03:00"),
+ endTime: t("11:00:00")
+ },
+ {
+ kind: "insertMachineEvent",
+ jobOperationId: "A",
+ startTime: t("11:05:00"),
+ endTime: null
+ }
+ ]);
+ });
+
+ it("ignores a sensor change older than the operator's press", () => {
+ const result = planMachineTime(
+ base({
+ currentState: "Running",
+ currentStateAt: t("09:00:00"),
+ lastManualChangeAt: t("10:03:00"),
+ changes: [{ state: "Idle", changedAt: t("10:02:00") }]
+ })
+ );
+ expect(result.writes).toEqual([]);
+ expect(result.currentState).toBe("Idle");
+ });
+
+ describe("a run reported only after the operator's press", () => {
+ // The machine started at 10:00. The operator pressed Start at 10:03,
+ // which opened the operator's event; the provider reported 10:00 later.
+ // Nothing was loaded before the press.
+ const pressed = {
+ lastManualChangeAt: t("10:03:00"),
+ loads: [],
+ recordedIntervals: [
+ {
+ id: "r1",
+ kind: "event" as const,
+ startTime: t("10:03:00"),
+ endTime: null
+ }
+ ]
+ };
+
+ it("records the time before the press as unattributed when nothing was loaded", () => {
+ const result = planMachineTime(
+ base({
+ ...pressed,
+ changes: [{ state: "Running", changedAt: t("10:00:00") }]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertUnattributed",
+ startTime: t("10:00:00"),
+ endTime: t("10:03:00")
+ }
+ ]);
+ expect(result.currentState).toBe("Running");
+ });
+
+ it("records nothing that an event already holds", () => {
+ const result = planMachineTime(
+ base({
+ lastManualChangeAt: t("10:03:00"),
+ loads: [],
+ recordedIntervals: [
+ {
+ id: "r2",
+ kind: "event" as const,
+ startTime: t("09:30:00"),
+ endTime: t("10:03:00")
+ }
+ ],
+ // The machine stops 30 seconds after the press: no time after it.
+ changes: [
+ { state: "Running", changedAt: t("10:00:00") },
+ { state: "Idle", changedAt: t("10:03:30") }
+ ]
+ })
+ );
+ expect(result.writes).toEqual([]);
+ });
+
+ it("records only the part no event holds", () => {
+ const result = planMachineTime(
+ base({
+ lastManualChangeAt: t("10:05:00"),
+ loads: [],
+ recordedIntervals: [
+ {
+ id: "r3",
+ kind: "event" as const,
+ startTime: t("10:02:00"),
+ endTime: t("10:05:00")
+ },
+ {
+ id: "r4",
+ kind: "event" as const,
+ startTime: t("10:05:00"),
+ endTime: null
+ }
+ ],
+ changes: [{ state: "Running", changedAt: t("10:00:00") }]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertUnattributed",
+ startTime: t("10:00:00"),
+ endTime: t("10:02:00")
+ }
+ ]);
+ });
+
+ it("ends the time where the machine stopped before the press", () => {
+ const result = planMachineTime(
+ base({
+ ...pressed,
+ changes: [
+ { state: "Running", changedAt: t("09:58:00") },
+ { state: "Idle", changedAt: t("10:01:00") }
+ ]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertUnattributed",
+ startTime: t("09:58:00"),
+ endTime: t("10:01:00")
+ }
+ ]);
+ });
+
+ it("ends the time at the press when a later change follows", () => {
+ const result = planMachineTime(
+ base({
+ ...pressed,
+ changes: [
+ { state: "Running", changedAt: t("10:00:00") },
+ { state: "Idle", changedAt: t("10:30:00") }
+ ]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertUnattributed",
+ startTime: t("10:00:00"),
+ endTime: t("10:03:00")
+ }
+ ]);
+ });
+
+ it("drops time shorter than the minimum", () => {
+ const result = planMachineTime(
+ base({
+ ...pressed,
+ changes: [{ state: "Running", changedAt: t("10:02:30") }]
+ })
+ );
+ expect(result.writes).toEqual([]);
+ });
+
+ it("ends the time at a stop still pending before the press", () => {
+ const result = planMachineTime(
+ base({
+ now: t("10:03:00"),
+ lastManualChangeAt: t("10:02:45"),
+ loads: [],
+ recordedIntervals: [
+ {
+ id: "r5",
+ kind: "event" as const,
+ startTime: t("10:02:45"),
+ endTime: null
+ }
+ ],
+ changes: [
+ { state: "Running", changedAt: t("10:00:00") },
+ { state: "Idle", changedAt: t("10:02:30") }
+ ]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertUnattributed",
+ startTime: t("10:00:00"),
+ endTime: t("10:02:30")
+ }
+ ]);
+ });
+ });
+
+ it("drops a state shorter than the minimum", () => {
+ const result = planMachineTime(
+ base({
+ changes: [
+ { state: "Running", changedAt: t("10:00:00") },
+ { state: "Idle", changedAt: t("10:20:00") },
+ { state: "Running", changedAt: t("10:20:30") },
+ { state: "Idle", changedAt: t("11:00:00") }
+ ]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertMachineEvent",
+ jobOperationId: "A",
+ startTime: t("10:00:00"),
+ endTime: t("11:00:00")
+ }
+ ]);
+ expect(result.appliedThrough).toBe(t("11:00:00"));
+ });
+
+ it("leaves a change younger than the minimum pending", () => {
+ const result = planMachineTime(
+ base({
+ currentState: "Running",
+ currentStateAt: t("10:00:00"),
+ openMachineEvent: {
+ id: "pe1",
+ jobOperationId: "A",
+ startTime: t("10:00:00"),
+ system: true
+ },
+ changes: [{ state: "Idle", changedAt: t("11:59:30") }]
+ })
+ );
+ expect(result.writes).toEqual([]);
+ expect(result.appliedThrough).toBeNull();
+ expect(result.currentState).toBe("Running");
+ });
+
+ it("starts a newly mapped device at the mapping, never before it", () => {
+ const result = planMachineTime(
+ base({
+ currentState: null,
+ currentStateAt: null,
+ mappedAt: t("10:00:00"),
+ loads: [
+ {
+ jobOperationId: "A",
+ from: t("08:00:00"),
+ to: null,
+ assignable: true
+ }
+ ],
+ changes: [{ state: "Running", changedAt: t("09:00:00") }]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertMachineEvent",
+ jobOperationId: "A",
+ startTime: t("10:00:00"),
+ endTime: null
+ }
+ ]);
+ expect(result.currentStateAt).toBe(t("10:00:00"));
+ expect(result.appliedThrough).toBe(t("09:00:00"));
+ });
+
+ it("makes the rest of a run unattributed after its operation is done", () => {
+ const result = planMachineTime(
+ base({
+ currentState: "Running",
+ currentStateAt: t("09:00:00"),
+ loads: [],
+ lastMachineEventEndTime: t("10:00:00")
+ })
+ );
+ expect(result.writes).toEqual([
+ { kind: "insertUnattributed", startTime: t("10:00:00"), endTime: null }
+ ]);
+ });
+
+ it("queues the time a machine keeps running after the operator stopped the run", () => {
+ const result = planMachineTime(
+ base({
+ currentState: "Running",
+ currentStateAt: t("09:00:00"),
+ lastManualChangeAt: t("10:03:00"),
+ lastMachineEventEndTime: t("10:03:00"),
+ recordedIntervals: [
+ {
+ id: "r6",
+ kind: "event" as const,
+ startTime: t("09:00:00"),
+ endTime: t("10:03:00")
+ }
+ ]
+ })
+ );
+ expect(result.writes).toEqual([
+ { kind: "insertUnattributed", startTime: t("10:03:00"), endTime: null }
+ ]);
+ });
+
+ describe("the same facts in either order of arrival", () => {
+ // The machine starts at 10:00 while X is loaded. The operator presses
+ // Start on Y at 10:03, which loads Y.
+ const loads = [
+ {
+ jobOperationId: "X",
+ from: t("09:00:00"),
+ to: t("10:03:00"),
+ assignable: true
+ },
+ { jobOperationId: "Y", from: t("10:03:00"), to: null, assignable: true }
+ ];
+
+ it("gives a start reported before the press to the operation loaded then", () => {
+ const result = planMachineTime(
+ base({
+ loads: [loads[0]!].map((load) => ({ ...load, to: null })),
+ changes: [{ state: "Running", changedAt: t("10:00:00") }]
+ })
+ );
+ // The press then ends this event at 10:03.
+ expect(result.writes).toEqual([
+ {
+ kind: "insertMachineEvent",
+ jobOperationId: "X",
+ startTime: t("10:00:00"),
+ endTime: null
+ }
+ ]);
+ });
+
+ it("gives a start reported after the press to the operation loaded then", () => {
+ const result = planMachineTime(
+ base({
+ lastManualChangeAt: t("10:03:00"),
+ loads,
+ recordedIntervals: [
+ {
+ id: "r7",
+ kind: "event" as const,
+ startTime: t("10:03:00"),
+ endTime: null
+ }
+ ],
+ changes: [{ state: "Running", changedAt: t("10:00:00") }]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertMachineEvent",
+ jobOperationId: "X",
+ startTime: t("10:00:00"),
+ endTime: t("10:03:00")
+ }
+ ]);
+ });
+
+ it("queues the part of a late run after its load ended", () => {
+ const result = planMachineTime(
+ base({
+ lastManualChangeAt: t("10:03:00"),
+ loads: [{ ...loads[0]!, to: t("10:01:30") }],
+ recordedIntervals: [
+ {
+ id: "r8",
+ kind: "event" as const,
+ startTime: t("10:03:00"),
+ endTime: null
+ }
+ ],
+ changes: [{ state: "Running", changedAt: t("10:00:00") }]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertMachineEvent",
+ jobOperationId: "X",
+ startTime: t("10:00:00"),
+ endTime: t("10:01:30")
+ },
+ {
+ kind: "insertUnattributed",
+ startTime: t("10:01:30"),
+ endTime: t("10:03:00")
+ }
+ ]);
+ });
+
+ it("queues a late run whose operation can no longer take time", () => {
+ const result = planMachineTime(
+ base({
+ lastManualChangeAt: t("10:03:00"),
+ loads: [{ ...loads[0]!, assignable: false }],
+ recordedIntervals: [
+ {
+ id: "r9",
+ kind: "event" as const,
+ startTime: t("10:03:00"),
+ endTime: null
+ }
+ ],
+ changes: [{ state: "Running", changedAt: t("10:00:00") }]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertUnattributed",
+ startTime: t("10:00:00"),
+ endTime: t("10:03:00")
+ }
+ ]);
+ });
+
+ // The operator's event ran 10:10-10:20 and a Pause ended it; the machine
+ // ran on until 10:30.
+ const paused = {
+ currentState: "Running" as const,
+ currentStateAt: t("10:00:00"),
+ lastManualChangeAt: t("10:20:00")
+ };
+
+ it("after a Pause, a sync while the machine still runs opens the time, and the stop closes it", () => {
+ const running = planMachineTime(
+ base({
+ ...paused,
+ now: t("10:21:30"),
+ recordedIntervals: [
+ {
+ id: "r10",
+ kind: "event" as const,
+ startTime: t("10:10:00"),
+ endTime: t("10:20:00")
+ }
+ ]
+ })
+ );
+ expect(running.writes).toEqual([
+ { kind: "insertUnattributed", startTime: t("10:20:00"), endTime: null }
+ ]);
+
+ const stopped = planMachineTime(
+ base({
+ ...paused,
+ openUnattributed: { id: "u1", startTime: t("10:20:00") },
+ recordedIntervals: [
+ {
+ id: "r11",
+ kind: "event" as const,
+ startTime: t("10:10:00"),
+ endTime: t("10:20:00")
+ },
+ {
+ id: "u1",
+ kind: "unattributed" as const,
+ startTime: t("10:20:00"),
+ endTime: null
+ }
+ ],
+ changes: [{ state: "Idle", changedAt: t("10:30:00") }]
+ })
+ );
+ expect(stopped.writes).toEqual([
+ {
+ kind: "closeUnattributed",
+ unattributedId: "u1",
+ endTime: t("10:30:00")
+ }
+ ]);
+ });
+
+ it("after a Pause, a stop reported with no sync between records the same time", () => {
+ const result = planMachineTime(
+ base({
+ ...paused,
+ recordedIntervals: [
+ {
+ id: "r13",
+ kind: "event" as const,
+ startTime: t("10:10:00"),
+ endTime: t("10:20:00")
+ }
+ ],
+ changes: [{ state: "Idle", changedAt: t("10:30:00") }]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertUnattributed",
+ startTime: t("10:20:00"),
+ endTime: t("10:30:00")
+ }
+ ]);
+ });
+
+ it("records nothing when the machine stops soon after a Pause", () => {
+ const waiting = planMachineTime(base({ ...paused, now: t("10:20:30") }));
+ expect(waiting.writes).toEqual([]);
+
+ const stopped = planMachineTime(
+ base({
+ ...paused,
+ changes: [{ state: "Idle", changedAt: t("10:20:40") }]
+ })
+ );
+ expect(stopped.writes).toEqual([]);
+ });
+ });
+
+ it("closes the open event when the machine goes down or offline", () => {
+ for (const state of ["Down", "Offline"] as const) {
+ const result = planMachineTime(
+ base({
+ currentState: "Running",
+ currentStateAt: t("10:00:00"),
+ openMachineEvent: {
+ id: "pe1",
+ jobOperationId: "A",
+ startTime: t("10:00:00"),
+ system: true
+ },
+ changes: [{ state, changedAt: t("10:30:00") }]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "closeMachineEvent",
+ productionEventId: "pe1",
+ endTime: t("10:30:00")
+ }
+ ]);
+ }
+ });
+
+ it("leaves an operator's open Machine event alone when the machine runs", () => {
+ const result = planMachineTime(
+ base({
+ lastManualChangeAt: t("10:00:00"),
+ openMachineEvent: {
+ id: "pe-manual",
+ jobOperationId: "A",
+ startTime: t("10:00:00"),
+ system: false
+ },
+ changes: [{ state: "Running", changedAt: t("10:01:00") }]
+ })
+ );
+ expect(result.writes).toEqual([]);
+ expect(result.currentState).toBe("Running");
+ });
+
+ it("drops a new slot that would close at or before its start", () => {
+ const result = planMachineTime(
+ base({
+ minimumStateSeconds: 0,
+ changes: [
+ { state: "Running", changedAt: t("10:00:00") },
+ { state: "Idle", changedAt: t("10:00:00") }
+ ]
+ })
+ );
+ expect(result.writes).toEqual([]);
+ expect(result.currentState).toBe("Idle");
+ });
+
+ it("closes an existing slot at its start when the end is earlier", () => {
+ const result = planMachineTime(
+ base({
+ currentState: "Running",
+ openMachineEvent: {
+ id: "pe1",
+ jobOperationId: "A",
+ startTime: t("10:30:00"),
+ system: true
+ },
+ changes: [{ state: "Idle", changedAt: t("10:20:00") }]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "closeMachineEvent",
+ productionEventId: "pe1",
+ endTime: t("10:30:00")
+ }
+ ]);
+ });
+
+ it("treats repeated same-state changes as one run for the debounce", () => {
+ const result = planMachineTime(
+ base({
+ now: t("10:05:00"),
+ changes: [
+ { state: "Running", changedAt: t("10:00:00") },
+ { state: "Running", changedAt: t("10:00:30") },
+ { state: "Running", changedAt: t("10:00:50") }
+ ]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertMachineEvent",
+ jobOperationId: "A",
+ startTime: t("10:00:00"),
+ endTime: null
+ }
+ ]);
+ });
+
+ describe("two presses and late stops, in any order", () => {
+ // The machine runs from 09:00. The operator's Machine time ran 09:30 to
+ // 10:00 (Pause), and again from 10:10 (Start).
+ const running = {
+ currentState: "Running" as const,
+ currentStateAt: t("09:00:00"),
+ loads: []
+ };
+
+ it("records the time between a Pause and a Start with no sync between", () => {
+ const result = planMachineTime(
+ base({
+ ...running,
+ now: t("10:15:00"),
+ firstUnplannedPressAt: t("10:00:00"),
+ lastManualChangeAt: t("10:10:00"),
+ openMachineEvent: {
+ id: "op2",
+ jobOperationId: "A",
+ startTime: t("10:10:00"),
+ system: false
+ },
+ recordedIntervals: [
+ {
+ id: "op1",
+ kind: "event" as const,
+ startTime: t("09:30:00"),
+ endTime: t("10:00:00")
+ },
+ {
+ id: "op2",
+ kind: "event" as const,
+ startTime: t("10:10:00"),
+ endTime: null
+ }
+ ]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "insertUnattributed",
+ startTime: t("10:00:00"),
+ endTime: t("10:10:00")
+ }
+ ]);
+ });
+
+ it("records the same time when a sync ran between the presses", () => {
+ const between = planMachineTime(
+ base({
+ ...running,
+ now: t("10:05:00"),
+ firstUnplannedPressAt: t("10:00:00"),
+ lastManualChangeAt: t("10:00:00"),
+ recordedIntervals: [
+ {
+ id: "op1",
+ kind: "event" as const,
+ startTime: t("09:30:00"),
+ endTime: t("10:00:00")
+ }
+ ]
+ })
+ );
+ expect(between.writes).toEqual([
+ { kind: "insertUnattributed", startTime: t("10:00:00"), endTime: null }
+ ]);
+
+ // The Start at 10:10 closed that row; the next sync adds nothing.
+ const after = planMachineTime(
+ base({
+ ...running,
+ now: t("10:15:00"),
+ firstUnplannedPressAt: t("10:10:00"),
+ lastManualChangeAt: t("10:10:00"),
+ openMachineEvent: {
+ id: "op2",
+ jobOperationId: "A",
+ startTime: t("10:10:00"),
+ system: false
+ },
+ recordedIntervals: [
+ {
+ id: "op1",
+ kind: "event" as const,
+ startTime: t("09:30:00"),
+ endTime: t("10:00:00")
+ },
+ {
+ id: "u1",
+ kind: "unattributed" as const,
+ startTime: t("10:00:00"),
+ endTime: t("10:10:00")
+ },
+ {
+ id: "op2",
+ kind: "event" as const,
+ startTime: t("10:10:00"),
+ endTime: null
+ }
+ ]
+ })
+ );
+ expect(after.writes).toEqual([]);
+ });
+
+ it("trims a queue row to the running time when a stop is reported late", () => {
+ // A queue row ran from the Pause at 10:00 until a Start closed it at
+ // 10:20, but the machine had stopped at 10:10.
+ const result = planMachineTime(
+ base({
+ ...running,
+ lastManualChangeAt: t("10:20:00"),
+ firstUnplannedPressAt: t("10:20:00"),
+ recordedIntervals: [
+ {
+ id: "u1",
+ kind: "unattributed" as const,
+ startTime: t("10:00:00"),
+ endTime: t("10:20:00")
+ },
+ {
+ id: "op2",
+ kind: "event" as const,
+ startTime: t("10:20:00"),
+ endTime: null
+ }
+ ],
+ changes: [{ state: "Idle", changedAt: t("10:10:00") }]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "updateUnattributed",
+ unattributedId: "u1",
+ startTime: t("10:00:00"),
+ endTime: t("10:10:00")
+ }
+ ]);
+ });
+
+ it("splits a queue row around an idle stretch reported late", () => {
+ const result = planMachineTime(
+ base({
+ ...running,
+ lastManualChangeAt: t("10:20:00"),
+ firstUnplannedPressAt: t("10:20:00"),
+ recordedIntervals: [
+ {
+ id: "u1",
+ kind: "unattributed" as const,
+ startTime: t("10:00:00"),
+ endTime: t("10:20:00")
+ },
+ {
+ id: "op2",
+ kind: "event" as const,
+ startTime: t("10:20:00"),
+ endTime: null
+ }
+ ],
+ changes: [
+ { state: "Idle", changedAt: t("10:10:00") },
+ { state: "Running", changedAt: t("10:14:00") }
+ ]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "updateUnattributed",
+ unattributedId: "u1",
+ startTime: t("10:00:00"),
+ endTime: t("10:10:00")
+ },
+ {
+ kind: "insertUnattributed",
+ startTime: t("10:14:00"),
+ endTime: t("10:20:00")
+ }
+ ]);
+ });
+ });
+
+ describe("an open slot follows its owner", () => {
+ const running = {
+ currentState: "Running" as const,
+ currentStateAt: t("10:00:00")
+ };
+
+ it("hands the time back to the operation when maintenance ends", () => {
+ const result = planMachineTime(
+ base({
+ ...running,
+ blocks: [{ from: t("10:30:00"), to: t("11:00:00") }],
+ openUnattributed: { id: "u1", startTime: t("10:30:00") },
+ recordedIntervals: [
+ {
+ id: "u1",
+ kind: "unattributed" as const,
+ startTime: t("10:30:00"),
+ endTime: null
+ }
+ ]
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "closeUnattributed",
+ unattributedId: "u1",
+ endTime: t("11:00:00")
+ },
+ {
+ kind: "insertMachineEvent",
+ jobOperationId: "A",
+ startTime: t("11:00:00"),
+ endTime: null
+ }
+ ]);
+ });
+
+ it("queues the rest of a run after its operation is unloaded", () => {
+ const result = planMachineTime(
+ base({
+ ...running,
+ loads: [
+ {
+ jobOperationId: "A",
+ from: t("07:00:00"),
+ to: t("11:00:00"),
+ assignable: false
+ }
+ ],
+ openMachineEvent: {
+ id: "pe1",
+ jobOperationId: "A",
+ startTime: t("10:00:00"),
+ system: true
+ }
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "closeMachineEvent",
+ productionEventId: "pe1",
+ endTime: t("11:00:00")
+ },
+ { kind: "insertUnattributed", startTime: t("11:00:00"), endTime: null }
+ ]);
+ });
+
+ it("moves the sensor's time to the operation loaded next", () => {
+ const result = planMachineTime(
+ base({
+ ...running,
+ loads: [
+ {
+ jobOperationId: "A",
+ from: t("07:00:00"),
+ to: t("11:00:00"),
+ assignable: true
+ },
+ {
+ jobOperationId: "B",
+ from: t("11:00:00"),
+ to: null,
+ assignable: true
+ }
+ ],
+ openMachineEvent: {
+ id: "pe1",
+ jobOperationId: "A",
+ startTime: t("10:00:00"),
+ system: true
+ }
+ })
+ );
+ expect(result.writes).toEqual([
+ {
+ kind: "closeMachineEvent",
+ productionEventId: "pe1",
+ endTime: t("11:00:00")
+ },
+ {
+ kind: "insertMachineEvent",
+ jobOperationId: "B",
+ startTime: t("11:00:00"),
+ endTime: null
+ }
+ ]);
+ });
+
+ it("leaves an operator's event on its operation when another loads", () => {
+ const result = planMachineTime(
+ base({
+ ...running,
+ loads: [
+ {
+ jobOperationId: "A",
+ from: t("07:00:00"),
+ to: t("11:00:00"),
+ assignable: true
+ },
+ {
+ jobOperationId: "B",
+ from: t("11:00:00"),
+ to: null,
+ assignable: true
+ }
+ ],
+ openMachineEvent: {
+ id: "op1",
+ jobOperationId: "A",
+ startTime: t("10:00:00"),
+ system: false
+ }
+ })
+ );
+ expect(result.writes).toEqual([]);
+ });
+ });
+});
diff --git a/packages/ee/src/oee/engine.ts b/packages/ee/src/oee/engine.ts
new file mode 100644
index 0000000000..9fc196207d
--- /dev/null
+++ b/packages/ee/src/oee/engine.ts
@@ -0,0 +1,581 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import type { MachineState } from "./types";
+
+/**
+ * The attribution engine: which job operation gets a device's run time.
+ * Pure — no database, no env — so it imports nothing but types. The rules are
+ * in `.claude/rules/oee-provider.md` → "Attribution rules".
+ *
+ * The sensor decides WHETHER the machine ran. The owner of each moment of a
+ * run decides WHO gets it:
+ *
+ * - a moment while maintenance blocks the work center → the queue;
+ * - a moment after an operator press in the same run → the queue (the press
+ * stopped the operator's time, not the machine);
+ * - else the operation loaded at that moment, if it can still take time;
+ * - else the queue.
+ *
+ * The facts give the same owners whatever order they arrive in. Time that a
+ * Machine event or an unattributed row already holds is never recorded again.
+ *
+ * Instants are compared with `Date.parse`: they are absolute UTC instants,
+ * the narrow exception in `.claude/rules/date-handling.md`.
+ */
+
+export type StoredStateChange = { changedAt: string; state: MachineState };
+
+/**
+ * One load of an operation on the work center (`workCenterLoad`): from
+ * `from` until `to` (null while it is still loaded). `assignable` is false
+ * once the operation is Done or Canceled or its job is locked.
+ */
+export type LoadPeriod = {
+ jobOperationId: string;
+ from: string;
+ to: string | null;
+ assignable: boolean;
+};
+
+/** A period maintenance blocks the work center (`to` null while it does). */
+export type BlockPeriod = { from: string; to: string | null };
+
+/** Time a Machine event or an unattributed row already holds. */
+export type RecordedInterval = {
+ id: string;
+ kind: "event" | "unattributed";
+ startTime: string;
+ endTime: string | null;
+};
+
+export type PlanMachineTimeInput = {
+ now: string;
+ minimumStateSeconds: number;
+ /** When the device was mapped to the work center. */
+ mappedAt: string;
+ currentState: MachineState | null;
+ currentStateAt: string | null;
+ /** The latest operator press. */
+ lastManualChangeAt: string | null;
+ /** The earliest press since the last sync, or null when there was none. */
+ firstUnplannedPressAt: string | null;
+ /** The work center's loads that may overlap the time planned. */
+ loads: LoadPeriod[];
+ /** The work center's maintenance blocks that may overlap the time planned. */
+ blocks: BlockPeriod[];
+ /** The newest open Machine event; `system` when the sync created it. */
+ openMachineEvent: {
+ id: string;
+ jobOperationId: string;
+ startTime: string;
+ system: boolean;
+ } | null;
+ openUnattributed: { id: string; startTime: string } | null;
+ lastMachineEventEndTime: string | null;
+ /** Machine events and unattributed rows around the presses. */
+ recordedIntervals: RecordedInterval[];
+ /** Stored changes after `appliedThrough`, ascending by `changedAt`. */
+ changes: StoredStateChange[];
+};
+
+export type MachineTimeWrite =
+ | {
+ kind: "insertMachineEvent";
+ jobOperationId: string;
+ startTime: string;
+ endTime: string | null;
+ }
+ | { kind: "closeMachineEvent"; productionEventId: string; endTime: string }
+ | { kind: "insertUnattributed"; startTime: string; endTime: string | null }
+ | { kind: "closeUnattributed"; unattributedId: string; endTime: string }
+ | {
+ kind: "updateUnattributed";
+ unattributedId: string;
+ startTime: string;
+ endTime: string;
+ }
+ | { kind: "deleteUnattributed"; unattributedId: string };
+
+export type PlanMachineTimeResult = {
+ writes: MachineTimeWrite[];
+ currentState: MachineState | null;
+ currentStateAt: string | null;
+ /** `changedAt` of the last consumed change; null when nothing was consumed. */
+ appliedThrough: string | null;
+};
+
+type Interval = { startTime: string; endTime: string };
+
+/**
+ * An open interval: an event or a queue row this run found (`id` set) or
+ * opened. `owner` is the operation, or null for the queue; `system` is false
+ * only for an operator's event.
+ */
+type Slot = {
+ id: string | null;
+ owner: string | null;
+ startTime: string;
+ system: boolean;
+};
+
+const at = (iso: string) => Date.parse(iso);
+
+const contains = (
+ period: { from: string; to: string | null },
+ instant: string
+) =>
+ at(period.from) <= at(instant) &&
+ (period.to === null || at(instant) < at(period.to));
+
+/** The parts of `[start, end)` that no recorded interval holds. */
+function unrecordedParts(
+ start: string,
+ end: string,
+ recorded: { startTime: string; endTime: string | null }[]
+): Interval[] {
+ const parts: Interval[] = [];
+ let cursor = start;
+ const sorted = [...recorded].sort(
+ (a, b) => at(a.startTime) - at(b.startTime)
+ );
+ for (const interval of sorted) {
+ if (at(cursor) >= at(end)) break;
+ if (interval.endTime !== null && at(interval.endTime) <= at(cursor)) {
+ continue;
+ }
+ if (at(interval.startTime) >= at(end)) break;
+ if (at(interval.startTime) > at(cursor)) {
+ parts.push({ startTime: cursor, endTime: interval.startTime });
+ }
+ if (interval.endTime === null) return parts;
+ if (at(interval.endTime) > at(cursor)) cursor = interval.endTime;
+ }
+ if (at(cursor) < at(end)) parts.push({ startTime: cursor, endTime: end });
+ return parts;
+}
+
+/** `interval` less `cut`: zero, one or two intervals. */
+function subtract(interval: Interval, cut: Interval): Interval[] {
+ return [
+ { startTime: interval.startTime, endTime: cut.startTime },
+ { startTime: cut.endTime, endTime: interval.endTime }
+ ]
+ .map((part) => ({
+ startTime:
+ at(part.startTime) < at(interval.startTime)
+ ? interval.startTime
+ : part.startTime,
+ endTime:
+ at(part.endTime) > at(interval.endTime)
+ ? interval.endTime
+ : part.endTime
+ }))
+ .filter((part) => at(part.endTime) > at(part.startTime));
+}
+
+export function planMachineTime(
+ input: PlanMachineTimeInput
+): PlanMachineTimeResult {
+ const writes: MachineTimeWrite[] = [];
+ const minimumMs = input.minimumStateSeconds * 1000;
+ const lastPress = input.lastManualChangeAt;
+ const presses = [input.firstUnplannedPressAt, lastPress].filter(
+ (press): press is string => press !== null
+ );
+ const recorded = [...input.recordedIntervals];
+
+ let state = input.currentState;
+ let stateAt = input.currentStateAt;
+ let appliedThrough: string | null = null;
+
+ const slots: Slot[] = [];
+ if (input.openMachineEvent) {
+ slots.push({
+ id: input.openMachineEvent.id,
+ owner: input.openMachineEvent.jobOperationId,
+ startTime: input.openMachineEvent.startTime,
+ system: input.openMachineEvent.system
+ });
+ }
+ if (input.openUnattributed) {
+ slots.push({
+ id: input.openUnattributed.id,
+ owner: null,
+ startTime: input.openUnattributed.startTime,
+ system: true
+ });
+ }
+
+ // ── Owners ──────────────────────────────────────────────────────────────
+ const blocked = (instant: string) =>
+ input.blocks.some((block) => contains(block, instant));
+ const pressedInRun = (instant: string, runStart: string) =>
+ presses.some(
+ (press) => at(runStart) < at(press) && at(press) <= at(instant)
+ );
+ const ownerAt = (instant: string, runStart: string) => {
+ if (blocked(instant) || pressedInRun(instant, runStart)) return null;
+ const load = input.loads.find((period) => contains(period, instant));
+ return load?.assignable ? load.jobOperationId : null;
+ };
+ // Where an owner can change: a load or a block begins or ends, or a press.
+ const edges = [
+ ...input.loads.flatMap((load) => [load.from, load.to]),
+ ...input.blocks.flatMap((block) => [block.from, block.to]),
+ ...presses
+ ]
+ .filter((edge): edge is string => edge !== null)
+ .sort((a, b) => at(a) - at(b));
+ const edgesWithin = (start: string, end: string) =>
+ edges.filter((edge) => at(edge) > at(start) && at(edge) < at(end));
+
+ // ── Writes ──────────────────────────────────────────────────────────────
+ // Closed time goes to its owner. Queue time shorter than the minimum is
+ // dropped, like a short state.
+ const writeClosed = (
+ { startTime, endTime }: Interval,
+ owner: string | null
+ ) => {
+ const interval = { startTime, endTime };
+ if (owner) {
+ writes.push({
+ kind: "insertMachineEvent",
+ jobOperationId: owner,
+ ...interval
+ });
+ } else if (at(interval.endTime) - at(interval.startTime) >= minimumMs) {
+ writes.push({ kind: "insertUnattributed", ...interval });
+ } else {
+ return;
+ }
+ recorded.push({
+ id: "",
+ kind: owner ? "event" : "unattributed",
+ ...interval
+ });
+ };
+
+ // A slot that ends at or before its start writes nothing new, and an
+ // existing one closes at its own start.
+ const closeSlot = (slot: Slot, end: string) => {
+ const ends = at(end) > at(slot.startTime);
+ if (slot.id === null) {
+ if (ends)
+ writeClosed({ startTime: slot.startTime, endTime: end }, slot.owner);
+ return;
+ }
+ const endTime = ends ? end : slot.startTime;
+ writes.push(
+ slot.owner === null
+ ? { kind: "closeUnattributed", unattributedId: slot.id, endTime }
+ : { kind: "closeMachineEvent", productionEventId: slot.id, endTime }
+ );
+ // The interval it held now ends: replace the open one read from the
+ // database, if there is one.
+ const held = recorded.findIndex((interval) => interval.id === slot.id);
+ if (held >= 0) recorded.splice(held, 1);
+ recorded.push({
+ id: slot.id,
+ kind: slot.owner === null ? "unattributed" : "event",
+ startTime: slot.startTime,
+ endTime
+ });
+ };
+
+ const closeSlots = (end: string, which: (slot: Slot) => boolean) => {
+ for (const slot of slots.filter(which)) {
+ slots.splice(slots.indexOf(slot), 1);
+ closeSlot(slot, end);
+ }
+ };
+
+ // The pieces of `[start, end)` that nothing holds, split where the owner
+ // changes, each written to its owner. A piece that reaches `now` while the
+ // machine runs opens instead (a queue piece once it has lasted the
+ // minimum, so a machine winding down after a Pause records nothing).
+ const recordRun = (start: string, end: string, runStart: string) => {
+ for (const part of unrecordedParts(start, end, recorded)) {
+ const bounds = [
+ part.startTime,
+ ...edgesWithin(part.startTime, part.endTime),
+ part.endTime
+ ];
+ const pieces: (Interval & { owner: string | null })[] = [];
+ for (const [i, startTime] of bounds.slice(0, -1).entries()) {
+ const endTime = bounds[i + 1] ?? startTime;
+ if (at(endTime) <= at(startTime)) continue;
+ const owner = ownerAt(startTime, runStart);
+ const last = pieces.at(-1);
+ if (last && last.owner === owner) last.endTime = endTime;
+ else pieces.push({ owner, startTime, endTime });
+ }
+ for (const piece of pieces) {
+ if (piece.endTime !== input.now || state !== "Running") {
+ writeClosed(piece, piece.owner);
+ } else if (
+ piece.owner ||
+ at(input.now) - at(piece.startTime) >= minimumMs
+ ) {
+ slots.push({
+ id: null,
+ owner: piece.owner,
+ startTime: piece.startTime,
+ system: true
+ });
+ }
+ }
+ }
+ };
+
+ // Open slots follow their owner up to `until`: where the owner changes, a
+ // slot closes and the new owner records the rest. An operator's event
+ // follows only maintenance: a block stops it, a load change does not.
+ const follow = (until: string) => {
+ const runStart = stateAt ?? until;
+ for (const slot of [...slots]) {
+ const change = slot.system
+ ? edgesWithin(slot.startTime, until).find(
+ (edge) => ownerAt(edge, runStart) !== slot.owner
+ )
+ : input.blocks
+ .map((block) => block.from)
+ .find(
+ (from) => at(from) > at(slot.startTime) && at(from) < at(until)
+ );
+ if (!change) continue;
+ slots.splice(slots.indexOf(slot), 1);
+ closeSlot(slot, change);
+ recordRun(change, until, runStart);
+ }
+ };
+
+ // ── Late stops trim the queue ──────────────────────────────────────────
+ // A stop reported only after a press: a queue row that the press closed
+ // may hold time the machine was idle. Queue rows are not posted, so they
+ // are cut to the running time. Machine events are never trimmed.
+ const trimIdle = (idle: Interval) => {
+ for (const interval of [...recorded]) {
+ if (
+ interval.kind !== "unattributed" ||
+ !interval.id ||
+ interval.endTime === null ||
+ at(idle.endTime) <= at(interval.startTime) ||
+ at(idle.startTime) >= at(interval.endTime)
+ ) {
+ continue;
+ }
+ const row = { startTime: interval.startTime, endTime: interval.endTime };
+ const [first, second] = subtract(row, idle);
+ recorded.splice(recorded.indexOf(interval), 1);
+ if (!first) {
+ writes.push({
+ kind: "deleteUnattributed",
+ unattributedId: interval.id
+ });
+ continue;
+ }
+ writes.push({
+ kind: "updateUnattributed",
+ unattributedId: interval.id,
+ ...first
+ });
+ recorded.push({ ...interval, ...first });
+ if (second) {
+ writes.push({ kind: "insertUnattributed", ...second });
+ recorded.push({ id: "", kind: "unattributed", ...second });
+ }
+ }
+ };
+
+ // ── The time around the presses ────────────────────────────────────────
+ // Time before the last press that no sync planned yet: from the earliest
+ // unplanned press when the machine already ran then, or from a late
+ // Running change. It ends at a late stop, or at the last press.
+ let unplanned: { from: string; runStart: string } | null =
+ state === "Running" &&
+ stateAt !== null &&
+ input.firstUnplannedPressAt !== null &&
+ at(stateAt) <= at(input.firstUnplannedPressAt)
+ ? { from: input.firstUnplannedPressAt, runStart: stateAt }
+ : null;
+ let idleFrom: string | null = null;
+ // A machine running at the last press and still running after it.
+ // (Typed by a cast: only the closures below assign it, which TypeScript's
+ // narrowing cannot see.)
+ let pastPress = null as { from: string; runStart: string } | null;
+ let pressCrossed = false;
+
+ // Leaving the time before the last press. `end` is a stop still pending
+ // before the press: the run may end there, so nothing past it is recorded
+ // until it settles.
+ const crossPress = (end: string | null) => {
+ if (pressCrossed || lastPress === null) return;
+ pressCrossed = true;
+ if (unplanned) {
+ recordRun(unplanned.from, end ?? lastPress, unplanned.runStart);
+ }
+ unplanned = null;
+ if (idleFrom !== null)
+ trimIdle({ startTime: idleFrom, endTime: lastPress });
+ idleFrom = null;
+ if (
+ end === null &&
+ state === "Running" &&
+ stateAt !== null &&
+ at(stateAt) <= at(lastPress)
+ ) {
+ pastPress = { from: lastPress, runStart: stateAt };
+ }
+ };
+
+ const apply = (next: MachineState, changedAt: string) => {
+ if (next === state) return;
+ // A change at or before the last press: the press decided what came
+ // after it, so this fills only the time the press could not see.
+ if (lastPress !== null && at(changedAt) <= at(lastPress)) {
+ if (next === "Running") {
+ if (idleFrom !== null) {
+ trimIdle({ startTime: idleFrom, endTime: changedAt });
+ idleFrom = null;
+ }
+ unplanned = { from: changedAt, runStart: changedAt };
+ } else {
+ if (unplanned) {
+ recordRun(unplanned.from, changedAt, unplanned.runStart);
+ unplanned = null;
+ }
+ idleFrom = changedAt;
+ }
+ state = next;
+ stateAt = changedAt;
+ return;
+ }
+ crossPress(null);
+ if (next === "Running") {
+ state = next;
+ stateAt = changedAt;
+ if (slots.length === 0) {
+ slots.push({
+ id: null,
+ owner: ownerAt(changedAt, changedAt),
+ startTime: changedAt,
+ system: true
+ });
+ }
+ return;
+ }
+ follow(changedAt);
+ if (pastPress) {
+ recordRun(pastPress.from, changedAt, pastPress.runStart);
+ pastPress = null;
+ }
+ closeSlots(changedAt, () => true);
+ state = next;
+ stateAt = changedAt;
+ };
+
+ let changes = input.changes;
+
+ // First sync: the last change before the mapping is the starting state, at
+ // the time of the mapping. Time before the mapping is never charged.
+ if (state === null) {
+ const mappedAt = at(input.mappedAt);
+ const before = changes.filter((c) => at(c.changedAt) <= mappedAt);
+ changes = changes.filter((c) => at(c.changedAt) > mappedAt);
+ const seed = before.at(-1);
+ if (seed) {
+ appliedThrough = seed.changedAt;
+ apply(seed.state, input.mappedAt);
+ }
+ }
+
+ // Repeated reports of one state are one run: the first starts it, the last
+ // is how far it was read.
+ const runs: (StoredStateChange & { through: string })[] = [];
+ for (const change of changes) {
+ const last = runs.at(-1);
+ if (last && last.state === change.state) last.through = change.changedAt;
+ else runs.push({ ...change, through: change.changedAt });
+ }
+
+ // Debounce: a state shorter than the minimum is dropped; the last change
+ // stays pending until it has lasted the minimum.
+ let pending: StoredStateChange | null = null;
+ for (const [i, run] of runs.entries()) {
+ const next = runs[i + 1];
+ const end = next ? next.changedAt : input.now;
+ if (at(end) - at(run.changedAt) < minimumMs) {
+ if (!next) {
+ pending = run;
+ break;
+ }
+ appliedThrough = run.through;
+ continue;
+ }
+ apply(run.state, run.changedAt);
+ appliedThrough = run.through;
+ }
+
+ if (lastPress !== null) {
+ crossPress(
+ pending && at(pending.changedAt) <= at(lastPress)
+ ? pending.changedAt
+ : null
+ );
+ }
+
+ if (state === "Running") {
+ // Still running past the press: the time after it that nothing holds.
+ if (pastPress && slots.length === 0) {
+ recordRun(pastPress.from, input.now, pastPress.runStart);
+ }
+ // Steady state: the machine runs, nothing holds its time, and no press
+ // decided it — an operation went Done mid-run, or maintenance or End
+ // Shift closed the event.
+ if (
+ slots.length === 0 &&
+ stateAt !== null &&
+ (lastPress === null || at(stateAt) > at(lastPress))
+ ) {
+ const lastEnd = input.lastMachineEventEndTime;
+ recordRun(
+ lastEnd && at(lastEnd) > at(stateAt) ? lastEnd : stateAt,
+ input.now,
+ stateAt
+ );
+ }
+ follow(input.now);
+ } else if (stateAt !== null) {
+ // Stopped by a late change before the press: the engine's own open time
+ // ends at the stop (or at its start, when it opened after the stop).
+ closeSlots(stateAt, (slot) => slot.system);
+ }
+
+ // A slot this run opened and did not close is inserted open.
+ for (const slot of slots) {
+ if (slot.id !== null) continue;
+ writes.push(
+ slot.owner === null
+ ? {
+ kind: "insertUnattributed",
+ startTime: slot.startTime,
+ endTime: null
+ }
+ : {
+ kind: "insertMachineEvent",
+ jobOperationId: slot.owner,
+ startTime: slot.startTime,
+ endTime: null
+ }
+ );
+ }
+
+ return {
+ writes,
+ currentState: state,
+ currentStateAt: stateAt,
+ appliedThrough
+ };
+}
diff --git a/packages/ee/src/oee/index.ts b/packages/ee/src/oee/index.ts
new file mode 100644
index 0000000000..65443eb176
--- /dev/null
+++ b/packages/ee/src/oee/index.ts
@@ -0,0 +1,7 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+export * from "./assignable";
+export * from "./engine";
+export * from "./types";
diff --git a/packages/ee/src/oee/registry.ts b/packages/ee/src/oee/registry.ts
new file mode 100644
index 0000000000..0b1f182c79
--- /dev/null
+++ b/packages/ee/src/oee/registry.ts
@@ -0,0 +1,71 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { APP_ENV } from "@carbon/env";
+import { SenseProvider } from "../sense/provider";
+import {
+ DEFAULT_MINIMUM_STATE_SECONDS,
+ type OeeProvider,
+ type OeeProviderId
+} from "./types";
+
+type OeeProviderFactory = (args: {
+ apiKey: string;
+ environment: string;
+}) => OeeProvider;
+
+/**
+ * Integration id → provider factory. The one place an OEE provider is named;
+ * everything else finds OEE integrations through `getIntegrationIdsByRole("oee")`.
+ */
+export const OEE_PROVIDERS: Record<OeeProviderId, OeeProviderFactory> = {
+ sense: (args) => {
+ // Sense staging has no HTTPS endpoint, so its bearer key would travel in
+ // plain text. Testing only: never in a production deployment.
+ if (args.environment === "staging" && APP_ENV === "production") {
+ throw new Error(SENSE_STAGING_REFUSED);
+ }
+ return new SenseProvider({
+ apiKey: args.apiKey,
+ environment: args.environment === "staging" ? "staging" : "production"
+ });
+ }
+};
+
+export const SENSE_STAGING_REFUSED =
+ "Sense staging uses plain HTTP and is not available in production. Choose Production.";
+
+export function isOeeProviderId(id: string): id is OeeProviderId {
+ return Object.hasOwn(OEE_PROVIDERS, id);
+}
+
+/**
+ * Builds the provider for an integration from its metadata (with the vaulted
+ * `apiKey` already resolved). Throws when the id is not an OEE provider, when
+ * the API key is empty, or when the provider's factory refuses the settings.
+ */
+export function createOeeProvider(
+ integrationId: string,
+ metadata: Record<string, unknown>
+): { provider: OeeProvider; minimumStateSeconds: number } {
+ if (!isOeeProviderId(integrationId)) {
+ throw new Error(`${integrationId} is not an OEE provider`);
+ }
+ const apiKey = typeof metadata.apiKey === "string" ? metadata.apiKey : "";
+ if (!apiKey) throw new Error("No API key");
+
+ const provider = OEE_PROVIDERS[integrationId]({
+ apiKey,
+ environment: String(metadata.environment ?? "production")
+ });
+
+ const minimum = Number(metadata.minimumStateSeconds);
+ return {
+ provider,
+ minimumStateSeconds:
+ Number.isFinite(minimum) && minimum >= 0
+ ? minimum
+ : DEFAULT_MINIMUM_STATE_SECONDS
+ };
+}
diff --git a/packages/ee/src/oee/service.server.ts b/packages/ee/src/oee/service.server.ts
new file mode 100644
index 0000000000..b4693f5da7
--- /dev/null
+++ b/packages/ee/src/oee/service.server.ts
@@ -0,0 +1,346 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import type { Database } from "@carbon/database";
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { endSensorMachineTime } from "@carbon/database/machine-time";
+import { datetime } from "@carbon/utils";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { EntitlementError, requireEntitlement } from "../entitlements.server";
+import { integrations } from "../index";
+import { resolveIntegrationSecrets } from "../integrations/secrets";
+import { companyHasFeature } from "../plan.server";
+import { machineTimeRefusal } from "./assignable";
+import { createOeeProvider, isOeeProviderId } from "./registry";
+import type { OeeProvider } from "./types";
+
+/**
+ * OEE provider server functions. The authoring writes embed
+ * `requireEntitlement("INTEGRATIONS")`; `getOeeProvider` is the runtime path
+ * and degrades through `companyHasFeature` instead of throwing.
+ */
+
+type Result<T> = { data: T; error: null } | { data: null; error: string };
+
+const fail = (error: unknown): { data: null; error: string } => {
+ if (error instanceof EntitlementError) throw error;
+ return {
+ data: null,
+ error: error instanceof Error ? error.message : String(error)
+ };
+};
+
+export async function getOeeProvider(
+ serviceClient: SupabaseClient<Database>,
+ companyId: string,
+ integrationId: string
+): Promise<Result<{ provider: OeeProvider; minimumStateSeconds: number }>> {
+ try {
+ const entitled = await companyHasFeature(serviceClient, companyId, {
+ feature: "INTEGRATIONS"
+ });
+ if (!entitled) return { data: null, error: "Not entitled" };
+
+ const integration = await serviceClient
+ .from("companyIntegration")
+ .select("metadata, secretRef, active")
+ .eq("companyId", companyId)
+ .eq("id", integrationId)
+ .maybeSingle();
+ if (integration.error) return fail(integration.error.message);
+ if (!integration.data?.active) {
+ return { data: null, error: "Integration is not active" };
+ }
+
+ const metadata = (await resolveIntegrationSecrets(
+ serviceClient,
+ companyId,
+ integrationId,
+ integration.data.metadata,
+ integration.data.secretRef
+ )) as Record<string, unknown>;
+
+ return { data: createOeeProvider(integrationId, metadata), error: null };
+ } catch (error) {
+ return fail(error);
+ }
+}
+
+export async function upsertWorkCenterDevice(
+ client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
+ args: {
+ companyId: string;
+ userId: string;
+ integration: string;
+ externalDeviceId: string;
+ externalSiteId: string | null;
+ siteTimezone: string | null;
+ deviceName: string;
+ workCenterId: string;
+ }
+): Promise<Result<{ id: string }>> {
+ await requireEntitlement(client, args.companyId, "INTEGRATIONS");
+ try {
+ // Only an active OEE integration maps devices: a row for any other
+ // integration would hold the work center's one device slot, and nothing
+ // would ever sync it.
+ if (!isOeeProviderId(args.integration)) {
+ return {
+ data: null,
+ error: `${args.integration} is not an OEE provider`
+ };
+ }
+ return await db.transaction().execute(async (trx) => {
+ const integration = await trx
+ .selectFrom("companyIntegration")
+ .select("active")
+ .where("id", "=", args.integration)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+ if (!integration?.active) {
+ return { data: null, error: "Integration is not active" };
+ }
+
+ // Kysely skips RLS, and the id comes from the form: the work center
+ // must be this company's (the composite FK refuses it too).
+ const workCenter = await trx
+ .selectFrom("workCenter")
+ .select("id")
+ .where("id", "=", args.workCenterId)
+ .where("companyId", "=", args.companyId)
+ .executeTakeFirst();
+ if (!workCenter) return { data: null, error: "Work center not found" };
+
+ const current = await trx
+ .selectFrom("workCenterDevice")
+ .select(["id", "workCenterId"])
+ .where("integration", "=", args.integration)
+ .where("externalDeviceId", "=", args.externalDeviceId)
+ .where("companyId", "=", args.companyId)
+ .forUpdate()
+ .executeTakeFirst();
+ if (current?.workCenterId === args.workCenterId) {
+ return { data: { id: current.id }, error: null };
+ }
+
+ const taken = await trx
+ .selectFrom("workCenterDevice")
+ .innerJoin("workCenter", (join) =>
+ join
+ .onRef("workCenter.id", "=", "workCenterDevice.workCenterId")
+ .onRef("workCenter.companyId", "=", "workCenterDevice.companyId")
+ )
+ .select([
+ "workCenterDevice.deviceName",
+ "workCenterDevice.integration",
+ "workCenter.name as workCenterName"
+ ])
+ .where("workCenterDevice.workCenterId", "=", args.workCenterId)
+ .where("workCenterDevice.companyId", "=", args.companyId)
+ .executeTakeFirst();
+ if (taken) {
+ return {
+ data: null,
+ error: `${taken.workCenterName} already has ${taken.deviceName} from ${
+ integrations.find((entry) => entry.id === taken.integration)
+ ?.name ?? taken.integration
+ }`
+ };
+ }
+
+ // A remap starts fresh: a new mapping time and no applied state. The
+ // time the device opened on its old work center ends now; no later
+ // sync of the old mapping will close it.
+ if (current) {
+ await endSensorMachineTime(trx, {
+ workCenterId: current.workCenterId,
+ companyId: args.companyId,
+ userId: args.userId,
+ at: datetime.timestamp()
+ });
+ await trx
+ .deleteFrom("workCenterDevice")
+ .where("id", "=", current.id)
+ .where("companyId", "=", args.companyId)
+ .execute();
+ }
+
+ const inserted = await trx
+ .insertInto("workCenterDevice")
+ .values({
+ companyId: args.companyId,
+ workCenterId: args.workCenterId,
+ integration: args.integration,
+ externalDeviceId: args.externalDeviceId,
+ externalSiteId: args.externalSiteId,
+ siteTimezone: args.siteTimezone,
+ deviceName: args.deviceName,
+ createdBy: args.userId
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ return { data: { id: inserted.id }, error: null };
+ });
+ } catch (error) {
+ return fail(error);
+ }
+}
+
+export async function deleteWorkCenterDevice(
+ client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
+ args: {
+ companyId: string;
+ userId: string;
+ integration: string;
+ externalDeviceId: string;
+ }
+): Promise<Result<null>> {
+ await requireEntitlement(client, args.companyId, "INTEGRATIONS");
+ try {
+ await db.transaction().execute(async (trx) => {
+ const device = await trx
+ .selectFrom("workCenterDevice")
+ .select(["id", "workCenterId"])
+ .where("integration", "=", args.integration)
+ .where("externalDeviceId", "=", args.externalDeviceId)
+ .where("companyId", "=", args.companyId)
+ .forUpdate()
+ .executeTakeFirst();
+ if (!device) return;
+
+ // Nothing syncs this work center after the delete, so the time its
+ // sensor opened ends now instead of staying open forever.
+ await endSensorMachineTime(trx, {
+ workCenterId: device.workCenterId,
+ companyId: args.companyId,
+ userId: args.userId,
+ at: datetime.timestamp()
+ });
+ await trx
+ .deleteFrom("workCenterDevice")
+ .where("id", "=", device.id)
+ .where("companyId", "=", args.companyId)
+ .execute();
+ });
+ return { data: null, error: null };
+ } catch (error) {
+ return fail(error);
+ }
+}
+
+/**
+ * Assign unattributed time to an operation: insert a Machine event for its
+ * interval and delete the row. The event is the record; the row was only a
+ * question waiting for an answer.
+ */
+export async function assignUnattributedMachineTime(
+ client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
+ args: {
+ companyId: string;
+ userId: string;
+ unattributedMachineTimeId: string;
+ jobOperationId: string;
+ }
+): Promise<Result<{ productionEventId: string }>> {
+ await requireEntitlement(client, args.companyId, "INTEGRATIONS");
+ try {
+ return await db.transaction().execute(async (trx) => {
+ const row = await trx
+ .selectFrom("unattributedMachineTime")
+ .select(["workCenterId", "startTime", "endTime"])
+ .where("id", "=", args.unattributedMachineTimeId)
+ .where("companyId", "=", args.companyId)
+ .forUpdate()
+ .executeTakeFirst();
+ if (!row) return { data: null, error: "Machine time not found" };
+ if (!row.endTime) {
+ return { data: null, error: "The machine is still running" };
+ }
+
+ // Checked under row locks, in this transaction: a job closed between
+ // the route's check and this insert must still refuse the time.
+ const operation = await trx
+ .selectFrom("jobOperation")
+ .innerJoin("job", (join) =>
+ join
+ .onRef("job.id", "=", "jobOperation.jobId")
+ .onRef("job.companyId", "=", "jobOperation.companyId")
+ )
+ .select(["jobOperation.status", "job.status as jobStatus"])
+ .where("jobOperation.id", "=", args.jobOperationId)
+ .where("jobOperation.companyId", "=", args.companyId)
+ .forUpdate()
+ .executeTakeFirst();
+ if (!operation) return { data: null, error: "Operation not found" };
+ const refusal = machineTimeRefusal(operation.status, operation.jobStatus);
+ if (refusal === "Locked") {
+ return {
+ data: null,
+ error: "Cannot modify a locked job. Reopen it first."
+ };
+ }
+ if (refusal) return { data: null, error: `The operation is ${refusal}` };
+
+ const event = await trx
+ .insertInto("productionEvent")
+ .values({
+ type: "Machine",
+ jobOperationId: args.jobOperationId,
+ workCenterId: row.workCenterId,
+ startTime: row.startTime,
+ endTime: row.endTime,
+ employeeId: null,
+ companyId: args.companyId,
+ createdBy: args.userId
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+
+ await trx
+ .deleteFrom("unattributedMachineTime")
+ .where("id", "=", args.unattributedMachineTimeId)
+ .where("companyId", "=", args.companyId)
+ .execute();
+
+ return { data: { productionEventId: event.id }, error: null };
+ });
+ } catch (error) {
+ return fail(error);
+ }
+}
+
+/** Dismiss unattributed time: it was not job time, so the row is deleted. */
+export async function dismissUnattributedMachineTime(
+ client: SupabaseClient<Database>,
+ db: Kysely<KyselyDatabase>,
+ args: {
+ companyId: string;
+ unattributedMachineTimeId: string;
+ }
+): Promise<Result<null>> {
+ await requireEntitlement(client, args.companyId, "INTEGRATIONS");
+ try {
+ // A running row is still the sync's to close: deleting it would let the
+ // next sync open the same time again.
+ const deleted = await db
+ .deleteFrom("unattributedMachineTime")
+ .where("id", "=", args.unattributedMachineTimeId)
+ .where("companyId", "=", args.companyId)
+ .where("endTime", "is not", null)
+ .returning("id")
+ .executeTakeFirst();
+ if (!deleted) {
+ return {
+ data: null,
+ error: "Machine time not found, or the machine is still running"
+ };
+ }
+ return { data: null, error: null };
+ } catch (error) {
+ return fail(error);
+ }
+}
diff --git a/packages/ee/src/oee/types.ts b/packages/ee/src/oee/types.ts
new file mode 100644
index 0000000000..49eceb3ac8
--- /dev/null
+++ b/packages/ee/src/oee/types.ts
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+/** Mirrors the `machineState` database enum. */
+export type MachineState = "Running" | "Idle" | "Down" | "Offline";
+
+export type OeeProviderId = "sense";
+
+/**
+ * A run or a stop shorter than this many seconds is ignored, unless the
+ * integration sets its own `minimumStateSeconds`.
+ */
+export const DEFAULT_MINIMUM_STATE_SECONDS = 60;
+
+/** A machine-monitoring device as its provider reports it. */
+export interface OeeDevice {
+ externalDeviceId: string;
+ name: string;
+ externalSiteId: string | null;
+ siteName: string | null;
+ siteTimezone: string | null;
+ manufacturer: string | null;
+ model: string | null;
+ machineType: string | null;
+ calibrated: boolean | null;
+}
+
+/** One state change of one device. `changedAt` is a UTC ISO 8601 instant. */
+export interface OeeStateChange {
+ externalEventId: string;
+ state: MachineState;
+ changedAt: string;
+}
+
+/**
+ * The provider cannot be reached (network failure, timeout, 5xx). The sync
+ * stops the run: every other device would fail the same way.
+ */
+export class OeeProviderUnavailableError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "OeeProviderUnavailableError";
+ }
+}
+
+/**
+ * The contract every OEE provider implements. The sync job, the device
+ * mapping screen and the attribution engine know only this interface.
+ */
+export interface OeeProvider {
+ id: OeeProviderId;
+ validate(): Promise<{ valid: boolean; error?: string }>;
+ listDevices(): Promise<OeeDevice[]>;
+ listStateChanges(
+ device: { externalDeviceId: string; externalSiteId: string | null },
+ window: { since: string; until: string }
+ ): Promise<OeeStateChange[]>;
+}
diff --git a/packages/ee/src/sense/config.tsx b/packages/ee/src/sense/config.tsx
new file mode 100644
index 0000000000..2c5543a0f6
--- /dev/null
+++ b/packages/ee/src/sense/config.tsx
@@ -0,0 +1,136 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import type { ComponentProps } from "react";
+import { z } from "zod";
+import { defineIntegration } from "../fns";
+import { DEFAULT_MINIMUM_STATE_SECONDS } from "../oee/types";
+
+const SenseSettingsSchema = z.object({
+ // Empty means "keep the existing vaulted secret"; presence enforced at install.
+ apiKey: z.string(),
+ environment: z.enum(["production", "staging"]).default("production"),
+ minimumStateSeconds: z.coerce
+ .number()
+ .int()
+ .min(0)
+ .default(DEFAULT_MINIMUM_STATE_SECONDS)
+});
+
+export const Sense = defineIntegration({
+ name: "Sense",
+ id: "sense",
+ active: true,
+ category: "Machine Monitoring",
+ providerRole: "oee" as const,
+ logo: Logo,
+ setupInstructions: SetupInstructions,
+ description:
+ "Sense clips a current sensor onto each machine and reports when it runs. Map each Sense station to a work center, and Carbon records machine time on the operation loaded on that work center. Run time with no loaded operation waits under Production → Unattributed Time for a supervisor.",
+ shortDescription: "Record machine time from Sense machine sensors.",
+ images: [],
+ settingGroups: [
+ {
+ name: "Connection",
+ description: "API access to your Sense company"
+ }
+ ],
+ settings: [
+ {
+ name: "apiKey",
+ label: "API key",
+ description:
+ "A company API key from Sense. It gives Carbon read access to your sites and stations.",
+ group: "Connection",
+ type: "secret" as const,
+ required: true,
+ value: ""
+ },
+ {
+ name: "environment",
+ label: "Environment",
+ group: "Connection",
+ type: "options" as const,
+ listOptions: [
+ {
+ value: "production",
+ label: "Production",
+ description: "bifrost.sensemfg.com"
+ },
+ {
+ value: "staging",
+ label: "Staging",
+ description:
+ "bifrost-staging.sensemfg.com — testing only, plain HTTP, refused in production"
+ }
+ ],
+ required: true,
+ value: "production"
+ },
+ {
+ name: "minimumStateSeconds",
+ label: "Minimum state (seconds)",
+ description:
+ "A run or a stop shorter than this is ignored, so a brief blip does not split machine time.",
+ group: "Connection",
+ type: "number" as const,
+ required: true,
+ value: DEFAULT_MINIMUM_STATE_SECONDS
+ }
+ ],
+ schema: SenseSettingsSchema
+});
+
+function SetupInstructions() {
+ return (
+ <p className="text-sm text-muted-foreground">
+ Create a company API key in Sense and paste it below. Then open the
+ Devices tab and map each Sense station to the work center it measures.
+ </p>
+ );
+}
+
+// The Sense Manufacturing wordmark, monochrome so it follows the theme like
+// the other integration logos. Wide (2737x1118): the shared render sites size
+// logos by height, so clamp the height and let the width follow.
+function Logo(props: ComponentProps<"svg">) {
+ return (
+ <svg
+ {...props}
+ viewBox="0 0 2737 1118"
+ fill="currentColor"
+ xmlns="http://www.w3.org/2000/svg"
+ style={{
+ // Two-line wordmark: taller than the one-line marks to stay legible.
+ height: "2rem",
+ width: "auto",
+ maxWidth: "100%",
+ // Caller's style last, so a render site that sizes the mark wins.
+ ...props.style
+ }}
+ >
+ <path d="M2324.94 827.909V339.751H2718.95V453.422H2457.44V714.238H2729.41V827.909H2324.94ZM2393.28 634.04V526.646H2691.06V634.04H2393.28Z" />
+ <path d="M1133.83 339.751V827.909H1267.03V682.856C1267.03 664.725 1266.8 648.453 1266.33 634.04C1265.87 619.628 1267.26 559.789 1266.33 548.631L1502.04 827.909H1629.66V339.751H1496.46V442.264V491.08C1496.46 505.027 1496 605.395 1496.46 617.948L1260.06 339.751H1133.83Z" />
+ <path d="M587.652 827.909V339.751H981.664V453.422H720.152V714.238H992.125V827.909H587.652ZM655.994 634.04V526.646H953.77V634.04H655.994Z" />
+ <path d="M246.171 834.882C208.048 834.882 173.877 831.163 143.658 823.724C113.438 816.286 86.706 805.825 63.4604 792.343C40.2149 778.396 19.0614 762.589 0 744.922L71.8288 646.593C102.048 674.953 132.965 694.479 164.579 705.172C196.193 715.4 225.715 720.514 253.144 720.514C263.837 720.514 274.53 719.584 285.223 717.725C295.916 715.865 304.517 712.378 311.026 707.264C318 702.15 321.486 694.712 321.486 684.948C321.486 678.905 319.394 673.558 315.21 668.909C311.491 664.26 306.144 660.541 299.171 657.751C292.197 654.497 284.061 651.707 274.763 649.383C265.465 647.058 255.701 645.198 245.473 643.804C235.245 641.944 224.32 640.317 212.697 638.922C182.943 634.273 156.443 627.764 133.197 619.396C109.952 611.027 90.4253 600.335 74.6183 587.317C58.8113 574.299 46.7236 559.422 38.3552 542.685C30.4517 525.484 26.5 505.957 26.5 484.107C26.5 460.396 32.0789 438.778 43.2368 419.251C54.8596 399.725 70.6666 383.221 90.6578 369.738C111.114 355.791 134.127 345.33 159.697 338.357C185.732 330.918 213.162 327.199 241.987 327.199C277.785 327.199 308.469 330.453 334.039 336.962C360.074 343.471 382.39 352.537 400.986 364.159C419.583 375.317 435.39 388.102 448.407 402.515L375.184 487.593C363.561 477.365 350.311 468.997 335.434 462.488C320.557 455.979 305.214 451.098 289.407 447.843C274.065 444.124 258.723 442.265 243.381 442.265C228.504 442.265 215.487 443.427 204.329 445.751C193.636 448.076 185.035 451.795 178.526 456.909C172.017 461.558 168.763 468.067 168.763 476.436C168.763 483.409 172.017 489.221 178.526 493.87C185.035 498.519 193.403 502.471 203.631 505.725C213.859 508.979 224.552 511.536 235.71 513.396C246.868 514.791 257.096 516.185 266.394 517.58C292.894 521.764 318 527.111 341.71 533.62C365.421 540.128 386.342 548.962 404.473 560.12C422.605 571.277 436.784 585.922 447.013 604.054C457.241 622.185 462.355 644.734 462.355 671.698C462.355 706.567 452.824 736.321 433.763 760.961C414.701 785.137 388.899 803.501 356.355 816.053C323.811 828.606 287.083 834.882 246.171 834.882Z" />
+ <path d="M2644.93 1117.6C2631.17 1117.6 2618.45 1115.7 2606.75 1111.91C2595.21 1107.96 2585.25 1102.34 2576.88 1095.07C2568.5 1087.64 2561.94 1078.55 2557.2 1067.81C2552.61 1057.06 2550.32 1044.96 2550.32 1031.53C2550.32 1019.2 2552.77 1007.9 2557.67 997.622C2562.57 987.19 2569.45 978.101 2578.3 970.355C2587.15 962.61 2597.58 956.603 2609.6 952.335C2621.77 948.067 2634.97 945.933 2649.19 945.933C2660.42 945.933 2670.69 947.198 2680.02 949.727C2689.5 952.256 2697.88 955.576 2705.15 959.686C2712.58 963.795 2718.66 968.379 2723.41 973.438L2698.99 999.993C2694.56 996.358 2689.82 993.196 2684.76 990.509C2679.7 987.822 2674.17 985.688 2668.16 984.107C2662.31 982.369 2655.91 981.499 2648.96 981.499C2640.89 981.499 2633.39 982.764 2626.43 985.293C2619.63 987.822 2613.63 991.379 2608.41 995.963C2603.35 1000.39 2599.4 1005.68 2596.56 1011.85C2593.87 1017.86 2592.52 1024.42 2592.52 1031.53C2592.52 1039.91 2594.03 1047.26 2597.03 1053.58C2600.03 1059.9 2604.14 1065.2 2609.36 1069.47C2614.58 1073.57 2620.58 1076.74 2627.38 1078.95C2634.18 1081 2641.45 1082.03 2649.19 1082.03C2655.99 1082.03 2662.31 1081.24 2668.16 1079.66C2674.17 1078.08 2679.31 1075.95 2683.57 1073.26C2687.84 1070.41 2691.16 1067.09 2693.53 1063.3C2696.06 1059.51 2697.33 1055.32 2697.33 1050.73V1045.52L2702.78 1054.53H2645.64V1023.47H2735.5C2735.82 1025.52 2736.05 1027.97 2736.21 1030.82C2736.37 1033.66 2736.45 1036.35 2736.45 1038.88C2736.61 1041.25 2736.68 1042.91 2736.68 1043.86C2736.68 1055.4 2734.47 1065.75 2730.05 1074.92C2725.62 1084.09 2719.3 1091.83 2711.08 1098.15C2703.02 1104.32 2693.37 1109.14 2682.15 1112.62C2670.93 1115.94 2658.52 1117.6 2644.93 1117.6Z" />
+ <path d="M2326.44 1115.23V949.253H2363.91L2469.42 1067.81L2463.02 1066.62C2462.07 1060.93 2461.36 1055.55 2460.88 1050.5C2460.41 1045.28 2459.93 1040.22 2459.46 1035.32C2459.14 1030.42 2458.83 1025.6 2458.51 1020.86C2458.35 1016.12 2458.27 1011.22 2458.27 1006.16C2458.27 1001.1 2458.27 995.805 2458.27 990.272V949.253H2497.4V1115.23H2459.46L2350.15 992.88L2360.82 994.54C2361.46 999.124 2362.01 1003.47 2362.48 1007.58C2362.96 1011.53 2363.35 1015.48 2363.67 1019.44C2364.14 1023.39 2364.54 1027.42 2364.85 1031.53C2365.17 1035.48 2365.33 1039.83 2365.33 1044.57C2365.49 1049.15 2365.57 1054.21 2365.57 1059.74V1115.23H2326.44Z" />
+ <path d="M2146.1 1115.23V1080.37H2183.32V984.107H2146.1V949.253H2261.09V984.107H2223.63V1080.37H2261.09V1115.23H2146.1Z" />
+ <path d="M1936.52 1115.23V949.253H2023.06C2035.23 949.253 2045.82 951.466 2054.83 955.892C2063.84 960.318 2070.8 966.562 2075.7 974.623C2080.76 982.527 2083.28 991.774 2083.28 1002.36C2083.28 1012.8 2080.6 1022.28 2075.22 1030.82C2070.01 1039.19 2062.81 1045.75 2053.65 1050.5C2044.64 1055.24 2034.52 1057.61 2023.3 1057.61H1974.93V1115.23H1936.52ZM2045.35 1115.23L1995.08 1040.3L2036.81 1034.37L2091.82 1115.23H2045.35ZM1974.93 1026.79H2019.03C2023.61 1026.79 2027.64 1025.84 2031.12 1023.94C2034.76 1022.04 2037.6 1019.44 2039.66 1016.12C2041.87 1012.64 2042.98 1008.69 2042.98 1004.26C2042.98 999.835 2041.79 996.042 2039.42 992.88C2037.21 989.719 2034.2 987.269 2030.41 985.53C2026.62 983.791 2022.19 982.922 2017.13 982.922H1974.93V1026.79Z" />
+ <path d="M1793.88 1116.65C1777.92 1116.65 1763.85 1113.49 1751.68 1107.16C1739.66 1100.84 1730.26 1092.07 1723.46 1080.85C1716.82 1069.62 1713.5 1056.9 1713.5 1042.67V949.253H1754.29V1041.25C1754.29 1049 1755.94 1055.87 1759.26 1061.88C1762.74 1067.88 1767.48 1072.55 1773.49 1075.87C1779.5 1079.19 1786.29 1080.85 1793.88 1080.85C1801.63 1080.85 1808.58 1079.19 1814.75 1075.87C1820.91 1072.55 1825.73 1067.88 1829.21 1061.88C1832.85 1055.87 1834.66 1049 1834.66 1041.25V949.253H1874.02V1042.67C1874.02 1056.9 1870.62 1069.62 1863.83 1080.85C1857.19 1092.07 1847.78 1100.84 1835.61 1107.16C1823.6 1113.49 1809.69 1116.65 1793.88 1116.65Z" />
+ <path d="M1566.81 1115.23V984.819H1508.01V949.253H1666.87V984.819H1607.12V1115.23H1566.81Z" />
+ <path d="M1403.38 1117.6C1389.79 1117.6 1377.22 1115.54 1365.68 1111.43C1354.14 1107.32 1344.03 1101.47 1335.33 1093.89C1326.64 1086.14 1319.92 1077.05 1315.18 1066.62C1310.44 1056.03 1308.07 1044.33 1308.07 1031.53C1308.07 1019.04 1310.52 1007.58 1315.42 997.148C1320.47 986.715 1327.27 977.626 1335.81 969.881C1344.5 962.136 1354.62 956.208 1366.16 952.098C1377.85 947.988 1390.42 945.933 1403.86 945.933C1413.18 945.933 1422.27 947.04 1431.12 949.253C1439.98 951.466 1448.12 954.548 1455.55 958.5C1463.13 962.452 1469.53 966.957 1474.75 972.015L1451.04 1002.36C1447.09 998.729 1442.66 995.488 1437.76 992.643C1433.02 989.64 1427.73 987.348 1421.88 985.767C1416.03 984.028 1409.47 983.159 1402.2 983.159C1395.4 983.159 1388.84 984.265 1382.52 986.478C1376.35 988.691 1370.74 991.853 1365.68 995.963C1360.78 1000.07 1356.83 1005.21 1353.83 1011.37C1350.98 1017.38 1349.56 1024.26 1349.56 1032C1349.56 1039.59 1351.06 1046.47 1354.06 1052.63C1357.07 1058.64 1361.18 1063.77 1366.39 1068.04C1371.77 1072.15 1377.85 1075.31 1384.65 1077.53C1391.61 1079.58 1398.96 1080.61 1406.7 1080.61C1414.13 1080.61 1420.77 1079.66 1426.62 1077.76C1432.47 1075.71 1437.76 1073.18 1442.5 1070.18C1447.25 1067.02 1451.44 1064.01 1455.07 1061.17L1474.28 1092.23C1469.85 1096.34 1463.92 1100.37 1456.49 1104.32C1449.22 1108.11 1441 1111.27 1431.84 1113.8C1422.83 1116.33 1413.34 1117.6 1403.38 1117.6Z" />
+ <path d="M1097.07 1115.23L1172 949.253H1208.28L1282.96 1115.23H1241.71L1200.45 1022.99C1198.87 1019.67 1197.37 1016.35 1195.95 1013.03C1194.68 1009.56 1193.42 1006.16 1192.15 1002.84C1190.89 999.361 1189.7 995.963 1188.6 992.643C1187.49 989.166 1186.46 985.846 1185.51 982.685L1193.81 982.448C1192.71 986.083 1191.6 989.561 1190.49 992.88C1189.39 996.2 1188.12 999.598 1186.7 1003.08C1185.44 1006.4 1184.09 1009.71 1182.67 1013.03C1181.25 1016.35 1179.82 1019.75 1178.4 1023.23L1137.38 1115.23H1097.07ZM1132.17 1084.88L1144.97 1054.53H1234.36L1242.89 1084.88H1132.17Z" />
+ <path d="M948.734 1115.23V949.253H989.042V1115.23H948.734ZM965.806 1053.1V1019.44H1069.18V1053.1H965.806ZM967.702 984.819V949.253H1078.9V984.819H967.702Z" />
+ <path d="M806.099 1116.65C790.134 1116.65 776.065 1113.49 763.894 1107.16C751.881 1100.84 742.476 1092.07 735.679 1080.85C729.04 1069.62 725.72 1056.9 725.72 1042.67V949.253H766.502V1041.25C766.502 1049 768.162 1055.87 771.481 1061.88C774.959 1067.88 779.701 1072.55 785.708 1075.87C791.714 1079.19 798.511 1080.85 806.099 1080.85C813.844 1080.85 820.799 1079.19 826.964 1075.87C833.129 1072.55 837.95 1067.88 841.427 1061.88C845.063 1055.87 846.881 1049 846.881 1041.25V949.253H886.24V1042.67C886.24 1056.9 882.842 1069.62 876.045 1080.85C869.406 1092.07 860.001 1100.84 847.829 1107.16C835.816 1113.49 821.906 1116.65 806.099 1116.65Z" />
+ <path d="M492.122 1115.23V949.253H529.584L635.096 1067.81L628.694 1066.62C627.746 1060.93 627.407 1077.75 626.933 1072.69C626.459 1067.47 625.612 1076.19 625.138 1071.29C624.822 1066.39 624.505 1025.6 624.189 1020.86C624.031 1016.12 623.952 1011.22 623.952 1006.16C623.952 1001.1 623.952 995.805 623.952 990.272V949.253H663.074V1115.23H625.138L515.832 992.88L526.502 994.54C527.134 999.124 527.688 1000.24 528.162 1004.34C528.636 1008.3 529.031 996.46 529.347 1000.41C529.822 1004.36 530.217 981.908 530.533 986.018C530.849 989.97 531.007 949.211 531.007 953.953C531.165 958.537 531.244 1054.21 531.244 1059.74V1115.23H492.122Z" />
+ <path d="M265.355 1115.23L340.28 949.253H376.557L451.245 1115.23H409.989L368.733 1022.99C367.152 1019.67 365.65 1016.35 364.228 1013.03C362.963 1009.56 361.699 1006.16 360.434 1002.84C359.17 999.361 357.984 995.963 356.878 992.643C355.771 989.166 354.744 985.846 353.795 982.685L362.094 982.448C360.987 986.083 359.881 989.561 358.774 992.88C357.668 996.2 356.403 999.598 354.981 1003.08C353.716 1006.4 352.373 1009.71 350.95 1013.03C349.527 1016.35 348.105 1019.75 346.682 1023.23L305.663 1115.23H265.355ZM300.447 1084.88L313.25 1054.53H402.639L411.175 1084.88H300.447Z" />
+ <path d="M38.9828 1115.23V949.253H75.0227L144.02 1045.04L119.836 1044.81L189.07 949.253H224.636V1115.23H185.514V1062.11C185.514 1048.52 185.83 1036.03 186.462 1024.65C187.094 1013.11 188.359 1001.5 190.256 989.798L194.287 1002.84L139.278 1074.92H123.629L68.858 1002.6L73.363 989.798C75.2598 1001.18 76.5244 1012.56 77.1567 1023.94C77.789 1035.32 78.1051 1048.05 78.1051 1062.11V1115.23H38.9828Z" />
+ <path d="M1880.95 823.725C1911.17 831.163 1945.34 834.882 1983.46 834.882C2024.37 834.882 2061.1 828.606 2093.64 816.054C2126.19 803.501 2151.99 785.137 2171.05 760.962C2190.11 736.321 2199.64 706.567 2199.64 671.698C2199.64 644.734 2194.53 622.185 2184.3 604.054C2174.07 585.922 2159.89 571.278 2141.76 560.12C2123.63 548.962 2102.71 540.129 2079 533.62C2055.29 527.111 2030.18 521.765 2003.68 517.58C1994.39 516.186 1984.16 514.791 1973 513.396C1961.84 511.536 1951.15 508.979 1940.92 505.725C1919.42 498.885 1901.56 486.32 1887.49 468.684L1815.25 378.109C1797.81 392.754 1792.15 399.725 1780.53 419.251C1769.37 438.778 1763.79 460.396 1763.79 484.107C1763.79 505.958 1767.74 525.484 1775.65 542.686C1784.01 559.422 1796.1 574.3 1811.91 587.317C1827.72 600.335 1847.24 611.028 1870.49 619.396C1893.73 627.764 1920.23 634.273 1949.99 638.922C1961.61 640.317 1972.54 641.944 1982.76 643.804C1992.99 645.199 2002.75 647.058 2012.05 649.383C2021.35 651.707 2029.49 654.497 2036.46 657.751C2043.43 660.541 2048.78 664.26 2052.5 668.909C2056.68 673.558 2058.78 678.905 2058.78 684.948C2058.78 694.712 2055.29 702.15 2048.32 707.264C2041.81 712.378 2033.21 715.865 2022.51 717.725C2011.82 719.584 2001.13 720.514 1990.43 720.514C1963 720.514 1933.48 715.4 1901.87 705.172C1870.25 694.479 1839.34 674.953 1809.12 646.593L1737.29 744.922C1756.35 762.589 1777.5 778.396 1800.75 792.343C1824 805.826 1850.73 816.286 1880.95 823.725Z" />
+ <path d="M1749.04 232.616C1893.84 130.009 2087.94 129.104 2233.79 230.855L2162.03 325.392C2059.49 256.229 1925.13 256.511 1822.99 325.608L1784.56 276.99C1784.54 276.962 1784.52 276.932 1784.5 276.904L1749.04 232.616Z" />
+ <path d="M1843.83 351.974C1933.86 292.081 2051.12 290.235 2143.26 348.23L2144.23 348.839L2072.11 443.848C2023.8 417.274 1965.19 418.081 1917.77 445.533L1843.83 351.974Z" />
+ <path d="M1652.04 111.455C1849.92 -38.5421 2125.02 -36.8863 2321.81 114.895L2250.13 209.326C2096.28 90.1677 1881.32 88.2353 1726.17 204.047L1652.04 111.455Z" />
+ </svg>
+ );
+}
diff --git a/packages/ee/src/sense/hooks.server.ts b/packages/ee/src/sense/hooks.server.ts
new file mode 100644
index 0000000000..0f3538f7b5
--- /dev/null
+++ b/packages/ee/src/sense/hooks.server.ts
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import type { KyselyDatabase } from "@carbon/database/client";
+import { getPostgresClient, getProcessPool } from "@carbon/database/client";
+import {
+ endSensorMachineTime,
+ lockWorkCenterDevice
+} from "@carbon/database/machine-time";
+import { datetime } from "@carbon/utils";
+import { PostgresDriver } from "kysely";
+import { createOeeProvider } from "../oee/registry";
+import type { IntegrationHealthcheckResult } from "../types";
+
+/** `metadata` arrives with the vaulted `apiKey` already resolved. */
+export async function senseHealthcheck(
+ _companyId: string,
+ metadata: Record<string, unknown>
+): Promise<IntegrationHealthcheckResult> {
+ let provider: ReturnType<typeof createOeeProvider>["provider"];
+ try {
+ provider = createOeeProvider("sense", metadata).provider;
+ } catch (error) {
+ return {
+ healthy: false,
+ reason: error instanceof Error ? error.message : String(error)
+ };
+ }
+ const { valid, error } = await provider.validate();
+ return { healthy: valid, reason: error };
+}
+
+/**
+ * Disconnecting Sense stops its sync, so nothing would ever close the time its
+ * sensors opened: each device's open sensor Machine event and running
+ * unattributed time end now, under the device lock. The device mappings stay,
+ * so reconnecting resumes from where each device left off.
+ */
+export async function senseOnUninstall(companyId: string) {
+ const db = getPostgresClient<KyselyDatabase>(
+ getProcessPool(),
+ PostgresDriver
+ );
+ const devices = await db
+ .selectFrom("workCenterDevice")
+ .select("workCenterId")
+ .where("companyId", "=", companyId)
+ .where("integration", "=", "sense")
+ .execute();
+ const at = datetime.timestamp();
+ for (const { workCenterId } of devices) {
+ await db.transaction().execute(async (trx) => {
+ await lockWorkCenterDevice(trx, { workCenterId, companyId });
+ await endSensorMachineTime(trx, {
+ workCenterId,
+ companyId,
+ userId: "system",
+ at
+ });
+ });
+ }
+}
diff --git a/packages/ee/src/sense/provider.test.ts b/packages/ee/src/sense/provider.test.ts
new file mode 100644
index 0000000000..963f7924aa
--- /dev/null
+++ b/packages/ee/src/sense/provider.test.ts
@@ -0,0 +1,183 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { OeeProviderUnavailableError } from "../oee/types";
+import { SenseApiError, SenseProvider } from "./provider";
+
+const device = { externalDeviceId: "st-1", externalSiteId: "site-1" };
+const window = {
+ since: "2026-10-12T00:00:00.000Z",
+ until: "2026-10-13T00:00:00.000Z"
+};
+
+const json = (body: unknown) =>
+ new Response(JSON.stringify(body), {
+ status: 200,
+ headers: { "Content-Type": "application/json" }
+ });
+
+const event = (n: number, status = "Active") => ({
+ id: `ev-${n}`,
+ device_id: "st-1",
+ status,
+ created_at: `2026-10-12T10:${String(Math.floor(n / 60) % 60).padStart(2, "0")}:${String(n % 60).padStart(2, "0")}.000Z`
+});
+
+const provider = () =>
+ new SenseProvider({ apiKey: "test-key", environment: "staging" });
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("SenseProvider", () => {
+ it("maps every Sense status through the allowlist", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ json({
+ events: [
+ event(1, "Active"),
+ event(2, "Idle"),
+ event(3, "Alert"),
+ event(4, "Offline")
+ ]
+ })
+ )
+ );
+ const changes = await provider().listStateChanges(device, window);
+ expect(changes.map((c) => c.state)).toEqual([
+ "Running",
+ "Idle",
+ "Down",
+ "Offline"
+ ]);
+ expect(changes[0]).toEqual({
+ externalEventId: "ev-1",
+ state: "Running",
+ changedAt: event(1).created_at
+ });
+ });
+
+ it("refuses a status outside the allowlist", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => json({ events: [event(1, "Calibrating")] }))
+ );
+ await expect(provider().listStateChanges(device, window)).rejects.toThrow(
+ SenseApiError
+ );
+ });
+
+ it("reports the provider unavailable when the request fails", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => {
+ throw new TypeError("fetch failed");
+ })
+ );
+ await expect(provider().listDevices()).rejects.toThrow(
+ OeeProviderUnavailableError
+ );
+ });
+
+ it("reports the provider unavailable on a 5xx response", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => new Response("Service Unavailable", { status: 503 }))
+ );
+ await expect(provider().listDevices()).rejects.toThrow(
+ OeeProviderUnavailableError
+ );
+ });
+
+ it("pages by time, never by offset, and drops repeated events", async () => {
+ const firstPage = Array.from({ length: 500 }, (_, i) => event(i));
+ const lastOfFirst = firstPage[499]!;
+ const secondPage = [lastOfFirst, event(500), event(501), event(502)];
+ const fetchMock = vi
+ .fn()
+ .mockResolvedValueOnce(json({ events: firstPage }))
+ .mockResolvedValueOnce(json({ events: secondPage }));
+ vi.stubGlobal("fetch", fetchMock);
+
+ const changes = await provider().listStateChanges(device, window);
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(changes).toHaveLength(503);
+ const second = new URL(String(fetchMock.mock.calls[1]![0]));
+ expect(second.searchParams.get("start_datetime")).toBe(
+ lastOfFirst.created_at
+ );
+ expect(second.searchParams.has("offset")).toBe(false);
+ expect(second.searchParams.get("order")).toBe("asc");
+ });
+
+ it("joins each station to its site's name and timezone", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async (input: URL | string) => {
+ const url = String(input);
+ if (url.endsWith("/v1/public/companies/stations")) {
+ return json({
+ stations: [
+ {
+ id: "st-1",
+ machine_name: "Station 0002",
+ machine_manufacturer: "Mazak",
+ machine_type: "Mill - 4 Axis",
+ machine_model: "Nexus 4000",
+ site_id: "site-1",
+ last_calibration_attempt_status: "CALIBRATED"
+ },
+ {
+ id: "st-2",
+ machine_name: "Station 0010",
+ machine_manufacturer: "Matsuura",
+ machine_type: "Mill - 5 Axis",
+ machine_model: null,
+ site_id: "site-2",
+ last_calibration_attempt_status: "NOT_CALIBRATED"
+ }
+ ]
+ });
+ }
+ return json({
+ sites: [
+ { id: "site-1", name: "Reston - 2", timezone: "UTC" },
+ { id: "site-2", name: "Cleveland", timezone: "America/New_York" }
+ ]
+ });
+ })
+ );
+
+ const devices = await provider().listDevices();
+
+ expect(devices).toEqual([
+ {
+ externalDeviceId: "st-1",
+ name: "Station 0002",
+ externalSiteId: "site-1",
+ siteName: "Reston - 2",
+ siteTimezone: "UTC",
+ manufacturer: "Mazak",
+ model: "Nexus 4000",
+ machineType: "Mill - 4 Axis",
+ calibrated: true
+ },
+ {
+ externalDeviceId: "st-2",
+ name: "Station 0010",
+ externalSiteId: "site-2",
+ siteName: "Cleveland",
+ siteTimezone: "America/New_York",
+ manufacturer: "Matsuura",
+ model: null,
+ machineType: "Mill - 5 Axis",
+ calibrated: false
+ }
+ ]);
+ });
+});
diff --git a/packages/ee/src/sense/provider.ts b/packages/ee/src/sense/provider.ts
new file mode 100644
index 0000000000..09f033a4bf
--- /dev/null
+++ b/packages/ee/src/sense/provider.ts
@@ -0,0 +1,197 @@
+// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
+// Carbon Enterprise file, licensed only under the Carbon Commercial License
+// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
+
+import {
+ type MachineState,
+ type OeeDevice,
+ type OeeProvider,
+ OeeProviderUnavailableError,
+ type OeeStateChange
+} from "../oee/types";
+
+/**
+ * Sense Manufacturing — clip-on current sensors, one "station" per machine.
+ * The public API is company-scoped by its key (`/v1/public/companies/...`)
+ * and has no webhooks, so the OEE sync polls it.
+ */
+
+const SENSE_HOSTS = {
+ production: "https://bifrost.sensemfg.com",
+ staging: "http://bifrost-staging.sensemfg.com"
+} as const;
+
+export type SenseEnvironment = keyof typeof SENSE_HOSTS;
+
+const PAGE_SIZE = 500;
+const REQUEST_TIMEOUT_MS = 15_000;
+
+/**
+ * The status → state allowlist. An unknown status fails the station rather
+ * than being guessed (`.ai/lessons.md` → explicit verified allowlists).
+ */
+const SENSE_STATES: Record<string, MachineState> = {
+ Active: "Running",
+ Idle: "Idle",
+ Alert: "Down",
+ Offline: "Offline"
+};
+
+export class SenseApiError extends Error {
+ constructor(
+ readonly status: number,
+ message: string
+ ) {
+ super(message);
+ this.name = "SenseApiError";
+ }
+}
+
+type SenseSite = { id: string; name: string; timezone: string | null };
+
+type SenseStation = {
+ id: string;
+ machine_name: string | null;
+ machine_manufacturer: string | null;
+ machine_type: string | null;
+ machine_model: string | null;
+ site_id: string | null;
+ last_calibration_attempt_status: string | null;
+};
+
+type SenseEvent = { id: string; status: string; created_at: string };
+
+export class SenseProvider implements OeeProvider {
+ readonly id = "sense" as const;
+ private readonly host: string;
+ private readonly apiKey: string;
+
+ constructor(args: { apiKey: string; environment: SenseEnvironment }) {
+ this.apiKey = args.apiKey;
+ this.host = SENSE_HOSTS[args.environment];
+ }
+
+ private async get<T>(
+ path: string,
+ query: Record<string, string> = {}
+ ): Promise<T> {
+ const url = new URL(path, this.host);
+ for (const [key, value] of Object.entries(query)) {
+ url.searchParams.set(key, value);
+ }
+ let response: Response;
+ try {
+ response = await fetch(url, {
+ headers: {
+ Authorization: `Bearer ${this.apiKey}`,
+ Accept: "application/json"
+ },
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
+ });
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ throw new OeeProviderUnavailableError(`Sense ${path} failed: ${message}`);
+ }
+ if (!response.ok) {
+ const body = await response.text().catch(() => "");
+ if (response.status >= 500) {
+ throw new OeeProviderUnavailableError(
+ `Sense ${path} failed with ${response.status}: ${body.slice(0, 300)}`
+ );
+ }
+ throw new SenseApiError(
+ response.status,
+ `Sense ${path} failed with ${response.status}: ${body.slice(0, 300)}`
+ );
+ }
+ return (await response.json()) as T;
+ }
+
+ async validate(): Promise<{ valid: boolean; error?: string }> {
+ try {
+ await this.get<{ sites: SenseSite[] }>("/v1/public/companies/sites");
+ return { valid: true };
+ } catch (error) {
+ return {
+ valid: false,
+ error: error instanceof Error ? error.message : String(error)
+ };
+ }
+ }
+
+ async listDevices(): Promise<OeeDevice[]> {
+ const [stations, sites] = await Promise.all([
+ this.get<{ stations: SenseStation[] }>("/v1/public/companies/stations"),
+ this.get<{ sites: SenseSite[] }>("/v1/public/companies/sites")
+ ]);
+ const siteById = new Map(sites.sites.map((site) => [site.id, site]));
+
+ return stations.stations.map((station) => {
+ const site = station.site_id ? siteById.get(station.site_id) : undefined;
+ const calibration = station.last_calibration_attempt_status;
+ return {
+ externalDeviceId: station.id,
+ name: station.machine_name ?? station.id,
+ externalSiteId: station.site_id,
+ siteName: site?.name ?? null,
+ siteTimezone: site?.timezone ?? null,
+ manufacturer: station.machine_manufacturer,
+ model: station.machine_model,
+ machineType: station.machine_type,
+ calibrated: calibration === null ? null : calibration === "CALIBRATED"
+ };
+ });
+ }
+
+ /**
+ * Sense ignores `offset` (and rejects `offset=0`), so this pages by time:
+ * a full page is followed by a request from its last event's `created_at`,
+ * and events already returned are dropped by id.
+ */
+ async listStateChanges(
+ device: { externalDeviceId: string; externalSiteId: string | null },
+ window: { since: string; until: string }
+ ): Promise<OeeStateChange[]> {
+ if (!device.externalSiteId) {
+ throw new SenseApiError(0, "Station has no site");
+ }
+ const path = `/v1/public/companies/sites/${encodeURIComponent(
+ device.externalSiteId
+ )}/stations/${encodeURIComponent(device.externalDeviceId)}/events`;
+
+ const seen = new Set<string>();
+ const changes: OeeStateChange[] = [];
+ let start = window.since;
+
+ for (;;) {
+ const page = await this.get<{ events: SenseEvent[] }>(path, {
+ start_datetime: start,
+ end_datetime: window.until,
+ order: "asc",
+ limit: String(PAGE_SIZE)
+ });
+
+ let added = 0;
+ for (const event of page.events) {
+ if (seen.has(event.id)) continue;
+ seen.add(event.id);
+ const state = SENSE_STATES[event.status];
+ if (!state) {
+ throw new SenseApiError(0, `Unknown Sense status: ${event.status}`);
+ }
+ changes.push({
+ externalEventId: event.id,
+ state,
+ changedAt: event.created_at
+ });
+ added++;
+ }
+
+ const last = page.events.at(-1);
+ if (page.events.length < PAGE_SIZE || added === 0 || !last) break;
+ start = last.created_at;
+ }
+
+ return changes;
+ }
+}
diff --git a/packages/ee/src/sync/topology.ts b/packages/ee/src/sync/topology.ts
index 51f66da390..1880d4bfae 100644
--- a/packages/ee/src/sync/topology.ts
+++ b/packages/ee/src/sync/topology.ts
@@ -23,7 +23,7 @@ import {
} from "./capabilities";
/** An integration's behavioural role. Mirrors `IntegrationConfig.providerRole`. */
-export type ProviderRole = "accounting" | "spend";
+export type ProviderRole = "accounting" | "spend" | "oee";
/**
* The registry slice this core needs, INJECTED rather than imported.
diff --git a/packages/ee/src/types.ts b/packages/ee/src/types.ts
index e53e01a13f..2246ccd802 100644
--- a/packages/ee/src/types.ts
+++ b/packages/ee/src/types.ts
@@ -217,7 +217,7 @@ export type IntegrationConfig = {
* Email and Stripe Connect declare no role and are never in conflict with
* anything.
*/
- providerRole?: "accounting" | "spend";
+ providerRole?: "accounting" | "spend" | "oee";
/** Logo component for the integration */
logo: React.FC<React.ComponentProps<"svg">>;
/** Brief one-liner description */
diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.md
index 6caedcc7f5..578d672aca 100644
--- a/packages/jobs/AGENTS.md
+++ b/packages/jobs/AGENTS.md
@@ -57,6 +57,8 @@ pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id> # MRP +
| `accounting-reconciliation` | `0 3 * * 1` | Remote presence/tie-out checks |
| `ramp-sync` | `carbon/ramp-sync` | Company-serialized Ramp family sync |
| `ramp-sweep` | `0 * * * *` | Dispatch Ramp sync for every active install |
+| `oee-sweep` | `*/2 * * * *` | Sends one `carbon/oee-sync` per (company, OEE integration) that is active and has at least 1 `workCenterDevice`. OEE providers have no webhooks, so this poll is the only input |
+| `oee-sync` | `carbon/oee-sync` (concurrency 1 per company; `singleton` with `mode: "skip"` per company and integration, so an event that arrives while a run is live is dropped) | Syncs every mapped device of one OEE integration in ONE `step.run` (`syncOeeDevice`, `oee-sync-device.ts`): reads the provider's state changes from `lastEventAt − 10 minutes` (24 hours before the mapping on a first sync), stores them in `machineStateChange`, then under `lockWorkCenterDevice` reads the loads (`workCenterLoad`), maintenance block periods and recorded machine time in a bounded window, runs `planMachineTime` and writes Machine `productionEvent` / `unattributedMachineTime` rows; it clears `workCenterDevice.unplannedPressAt` and deletes closed unattributed rows shorter than `minimumStateSeconds`. A failed device gets `lastSyncError` and keeps its cursor; the others continue, except on `OeeProviderUnavailableError` (network failure, timeout, 5xx), which stops the run. Skipped (no error) when the company is not entitled, the integration is inactive or the key is empty. Never posts to the GL. See `.claude/rules/oee-provider.md` |
| `mount-publish` | `carbon/mount-publish` | One company's push to Mount: a step per batch of 200 until nothing is stale, a batch publishes nothing, or 50 batches; progress and outcome in `companyIntegration.metadata.lastPublish.{entityType}`, which the integration page reads |
| `mount-sweep` | `30 2 * * *` | Dispatch a scheduled `mount-publish` for every active Mount install |
| `workflow-run` | `carbon/workflow-run.queued` | Execute one owner-scoped workflow graph |
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index d3f55d2fe2..aa71a473e5 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -1,11 +1,11 @@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20261013171656",
+ "schemaVersion": "20261014030025",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-10-13T19:01:57.412Z",
+ "exportedAt": "2026-10-14T03:20:40.736Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",
@@ -3568,6 +3568,20 @@
"outputLotNumber"
]
},
+ {
+ "name": "machineStateChange",
+ "rows": 0,
+ "columns": [
+ "id",
+ "companyId",
+ "workCenterDeviceId",
+ "workCenterId",
+ "externalEventId",
+ "state",
+ "changedAt",
+ "createdAt"
+ ]
+ },
{
"name": "maintenanceSchedule",
"rows": 0,
@@ -3812,6 +3826,21 @@
"sortMethod"
]
},
+ {
+ "name": "unattributedMachineTime",
+ "rows": 0,
+ "columns": [
+ "id",
+ "companyId",
+ "workCenterId",
+ "startTime",
+ "endTime",
+ "createdBy",
+ "createdAt",
+ "updatedBy",
+ "updatedAt"
+ ]
+ },
{
"name": "warehouseTransferLine",
"rows": 0,
@@ -3836,6 +3865,45 @@
"customFields"
]
},
+ {
+ "name": "workCenterDevice",
+ "rows": 0,
+ "columns": [
+ "id",
+ "companyId",
+ "workCenterId",
+ "integration",
+ "externalDeviceId",
+ "externalSiteId",
+ "siteTimezone",
+ "deviceName",
+ "currentState",
+ "currentStateAt",
+ "appliedThrough",
+ "lastEventAt",
+ "lastManualChangeAt",
+ "lastSyncedAt",
+ "lastSyncError",
+ "createdBy",
+ "createdAt",
+ "updatedBy",
+ "updatedAt",
+ "unplannedPressAt"
+ ]
+ },
+ {
+ "name": "workCenterLoad",
+ "rows": 0,
+ "columns": [
+ "id",
+ "companyId",
+ "workCenterId",
+ "jobOperationId",
+ "loadedAt",
+ "unloadedAt",
+ "createdAt"
+ ]
+ },
{
"name": "workCenterProcess",
"rows": 0,
diff --git a/packages/jobs/src/backups/id-refs.ts b/packages/jobs/src/backups/id-refs.ts
index d741116ab7..97d6ae36b5 100644
--- a/packages/jobs/src/backups/id-refs.ts
+++ b/packages/jobs/src/backups/id-refs.ts
@@ -81,6 +81,7 @@ export const ID_REF_COLUMNS: Partial<Record<string, readonly string[]>> = {
journalLine: ["documentId"],
journalLineDimension: ["valueId"],
leasePayment: ["purchaseInvoiceLineId", "voidedPurchaseInvoiceId"],
+ machineStateChange: ["workCenterDeviceId"],
nonConformance: ["requiredActionIds"],
nonConformancePurchaseReturnOrderLine: ["purchaseReturnOrderId"],
nonConformanceSalesReturnOrderLine: ["salesReturnOrderId"],
@@ -110,5 +111,6 @@ export const ID_REF_COLUMNS: Partial<Record<string, readonly string[]>> = {
trackedActivity: ["sourceDocumentId"],
trackedEntity: ["sourceDocumentId"],
trainingAssignment: ["groupIds"],
+ workCenterLoad: ["jobOperationId"],
workflowRun: ["causedByRunId", "rootRunId", "triggerRecordId"]
} satisfies IdRefColumns;
diff --git a/packages/jobs/src/inngest/functions/integrations/index.ts b/packages/jobs/src/inngest/functions/integrations/index.ts
index dc2b9aa7c6..3338c0641d 100644
--- a/packages/jobs/src/inngest/functions/integrations/index.ts
+++ b/packages/jobs/src/inngest/functions/integrations/index.ts
@@ -12,6 +12,8 @@ export { jiraSyncFunction, syncIssueFromJiraSchema } from "./jira";
export { linearSyncFunction, syncIssueFromLinearSchema } from "./linear";
export { mountPublishFunction } from "./mount-publish";
export { mountSweepFunction } from "./mount-sweep";
+export { oeeSweepFunction } from "./oee-sweep";
+export { oeeSyncFunction } from "./oee-sync";
export { onshapeBackfillFunction } from "./onshape-backfill";
export { onshapeRevisionSyncFunction } from "./onshape-revision-sync";
export { paperlessPartsFunction } from "./paperless-parts";
diff --git a/packages/jobs/src/inngest/functions/integrations/oee-sweep.ts b/packages/jobs/src/inngest/functions/integrations/oee-sweep.ts
new file mode 100644
index 0000000000..084a421585
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/integrations/oee-sweep.ts
@@ -0,0 +1,55 @@
+// 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.
+
+/**
+ * OEE sweep — OEE providers have no webhooks, so this poll is the only way
+ * machine state reaches Carbon. Every 2 minutes it fires one `carbon/oee-sync`
+ * per (company, OEE integration) that is active AND has at least one mapped
+ * device, so an installed-but-unmapped integration costs nothing.
+ */
+import { getIntegrationIdsByRole } from "@carbon/ee";
+import { getJobDatabaseClient } from "../../../db";
+import { inngest } from "../../client";
+
+export const oeeSweepFunction = inngest.createFunction(
+ { id: "oee-sweep", retries: 2 },
+ { cron: "*/2 * * * *" },
+ async ({ step }) => {
+ const targets = await step.run("find-oee-sync-targets", async () => {
+ const integrationIds = getIntegrationIdsByRole("oee");
+ if (integrationIds.length === 0) return [];
+ return getJobDatabaseClient()
+ .selectFrom("workCenterDevice")
+ .innerJoin("companyIntegration", (join) =>
+ join
+ .onRef("companyIntegration.id", "=", "workCenterDevice.integration")
+ .onRef(
+ "companyIntegration.companyId",
+ "=",
+ "workCenterDevice.companyId"
+ )
+ )
+ .where("companyIntegration.active", "=", true)
+ .where("workCenterDevice.integration", "in", integrationIds)
+ .select(["workCenterDevice.companyId", "workCenterDevice.integration"])
+ .distinct()
+ .execute();
+ });
+
+ if (targets.length === 0) return { targets: 0 };
+
+ await step.sendEvent(
+ "dispatch-oee-sync",
+ targets.map((target) => ({
+ name: "carbon/oee-sync" as const,
+ data: {
+ companyId: target.companyId,
+ integrationId: target.integration
+ }
+ }))
+ );
+
+ return { targets: targets.length };
+ }
+);
diff --git a/packages/jobs/src/inngest/functions/integrations/oee-sync-device.database.test.ts b/packages/jobs/src/inngest/functions/integrations/oee-sync-device.database.test.ts
new file mode 100644
index 0000000000..ae274defd7
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/integrations/oee-sync-device.database.test.ts
@@ -0,0 +1,743 @@
+// 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.
+
+// One OEE device's sync against a live local database: the read window it
+// asks the provider for, and the Machine time it writes under the device lock.
+// SUPABASE_DB_URL=… pnpm --filter @carbon/jobs exec vitest run oee-sync-device
+//
+// Each test runs inside one transaction that is always rolled back, so it
+// writes nothing. Fixtures are inserted with `session_replication_role =
+// replica` (FKs and triggers off): the load interceptor does not run, so the
+// work center's loaded operation is set directly. The provider is the one
+// fake — it is the HTTP boundary — and the wall clock is pinned.
+
+import { randomUUID } from "node:crypto";
+import type { KyselyDatabase } from "@carbon/database/client";
+import type { OeeProvider, OeeStateChange } from "@carbon/ee/oee";
+import type { DatabaseConnection } from "kysely";
+import { CompiledQuery, Kysely, PostgresDialect, PostgresDriver } from "kysely";
+import { Client } from "pg";
+import {
+ afterAll,
+ afterEach,
+ beforeAll,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi
+} from "vitest";
+import { syncOeeDevice } from "./oee-sync-device";
+
+const LOCAL_HOSTS = ["localhost", "127.0.0.1", "[::1]"];
+const hasLocalDatabase = (() => {
+ try {
+ return LOCAL_HOSTS.includes(
+ new URL(process.env.SUPABASE_DB_URL ?? "").hostname
+ );
+ } catch {
+ return false;
+ }
+})();
+
+/** `syncOeeDevice` opens its own transaction: run it as a savepoint. */
+class SavepointDriver extends PostgresDriver {
+ override async beginTransaction(connection: DatabaseConnection) {
+ await connection.executeQuery(CompiledQuery.raw("SAVEPOINT sync"));
+ }
+ override async commitTransaction(connection: DatabaseConnection) {
+ await connection.executeQuery(CompiledQuery.raw("RELEASE SAVEPOINT sync"));
+ }
+ override async rollbackTransaction(connection: DatabaseConnection) {
+ await connection.executeQuery(
+ CompiledQuery.raw("ROLLBACK TO SAVEPOINT sync")
+ );
+ }
+}
+
+type Row = Record<string, unknown>;
+
+/** A timestamptz column as a UTC ISO string, whatever the session timezone. */
+const iso = (column: string) =>
+ `to_char("${column}" AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"')`;
+
+describe.skipIf(!hasLocalDatabase)(
+ "syncOeeDevice against a migrated database",
+ () => {
+ const client = new Client({
+ connectionString: process.env.SUPABASE_DB_URL
+ });
+ const config = {
+ pool: {
+ connect: async () =>
+ Object.assign(client, { release: () => undefined }),
+ end: async () => undefined
+ }
+ };
+ const dialect = new PostgresDialect(config);
+ const db = new Kysely<KyselyDatabase>({
+ dialect: {
+ createAdapter: () => dialect.createAdapter(),
+ createDriver: () => new SavepointDriver(config),
+ createIntrospector: (k) => dialect.createIntrospector(k),
+ createQueryCompiler: () => dialect.createQueryCompiler()
+ }
+ });
+
+ const run = randomUUID().slice(0, 8);
+ const id = (name: string) => `t-${run}-${name}`;
+ const companyId = id("company");
+ const workCenterId = id("wc");
+ const deviceId = id("device");
+ const operationId = id("op");
+
+ const now = "2026-10-13T12:00:00.000Z";
+ const mappedAt = "2026-10-13T08:00:00.000Z";
+
+ async function insert(table: string, given: Row) {
+ const row: Row = { companyId, createdBy: "system", ...given };
+ const columns = Object.keys(row);
+ await client.query(
+ `INSERT INTO "${table}" (${columns.map((c) => `"${c}"`).join(", ")})
+ VALUES (${columns.map((_, i) => `$${i + 1}`).join(", ")})`,
+ Object.values(row)
+ );
+ }
+
+ /**
+ * A work center with a mapped device and one job operation. `workCenter`
+ * sets its loaded operation; `device` the device's sync state.
+ */
+ async function seed({
+ workCenter = {},
+ device = {},
+ operation = {}
+ }: {
+ workCenter?: Row;
+ device?: Row;
+ operation?: Row;
+ } = {}) {
+ await client.query("BEGIN");
+ await client.query("SET LOCAL session_replication_role = replica");
+ // The load lives in workCenterLoad; a seeded load is written there.
+ const { loadedJobOperationId, loadedAt, ...workCenterColumns } =
+ workCenter;
+ await insert("workCenter", {
+ id: workCenterId,
+ name: "Mill",
+ ...workCenterColumns
+ });
+ await insert("jobOperation", {
+ id: operationId,
+ jobId: id("job"),
+ processId: id("process"),
+ status: "In Progress",
+ ...operation
+ });
+ // Triggers are off here, so the load the interceptor would write is
+ // seeded directly.
+ if (loadedJobOperationId && loadedAt) {
+ await client.query(
+ `INSERT INTO "workCenterLoad" ("companyId", "workCenterId", "jobOperationId", "loadedAt")
+ VALUES ($1, $2, $3, $4)`,
+ [companyId, workCenterId, loadedJobOperationId, loadedAt]
+ );
+ }
+ await insert("workCenterDevice", {
+ id: deviceId,
+ workCenterId,
+ integration: "sense",
+ externalDeviceId: id("station"),
+ deviceName: "Station",
+ createdAt: mappedAt,
+ ...device
+ });
+ }
+
+ /** The device row as the sweep reads it. */
+ async function readDevice() {
+ return db
+ .selectFrom("workCenterDevice")
+ .selectAll()
+ .where("id", "=", deviceId)
+ .executeTakeFirstOrThrow();
+ }
+
+ /** A provider that returns fixed changes and records each read window. */
+ function fakeProvider(
+ changes: OeeStateChange[],
+ onRead: () => Promise<void> = async () => undefined
+ ) {
+ const windows: { since: string; until: string }[] = [];
+ const provider: OeeProvider = {
+ id: "sense",
+ validate: async () => ({ valid: true }),
+ listDevices: async () => [],
+ listStateChanges: async (_device, window) => {
+ windows.push(window);
+ await onRead();
+ return changes;
+ }
+ };
+ return { provider, windows };
+ }
+
+ async function sync(provider: OeeProvider) {
+ return syncOeeDevice({
+ db,
+ provider,
+ device: await readDevice(),
+ minimumStateSeconds: 60
+ });
+ }
+
+ async function machineEvents() {
+ const result = await client.query(
+ `SELECT "jobOperationId", "createdBy", "employeeId",
+ ${iso("startTime")} AS "startTime", ${iso("endTime")} AS "endTime"
+ FROM "productionEvent"
+ WHERE "workCenterId" = $1 AND "type" = 'Machine'
+ ORDER BY "startTime"`,
+ [workCenterId]
+ );
+ return result.rows as Row[];
+ }
+
+ async function unattributedTime() {
+ const result = await client.query(
+ `SELECT ${iso("startTime")} AS "startTime", ${iso("endTime")} AS "endTime"
+ FROM "unattributedMachineTime"
+ WHERE "workCenterId" = $1
+ ORDER BY "startTime"`,
+ [workCenterId]
+ );
+ return result.rows as Row[];
+ }
+
+ async function deviceState() {
+ const result = await client.query(
+ `SELECT "currentState", ${iso("appliedThrough")} AS "appliedThrough",
+ ${iso("lastEventAt")} AS "lastEventAt"
+ FROM "workCenterDevice" WHERE "id" = $1`,
+ [deviceId]
+ );
+ return result.rows[0] as Row;
+ }
+
+ beforeAll(async () => {
+ await client.connect();
+ });
+
+ beforeEach(() => {
+ vi.useFakeTimers({ toFake: ["Date"] });
+ vi.setSystemTime(now);
+ });
+
+ afterEach(async () => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ await client.query("ROLLBACK");
+ });
+
+ afterAll(async () => {
+ await client.end();
+ });
+
+ it("reads a first sync from 24 hours before the mapping", async () => {
+ await seed();
+ const { provider, windows } = fakeProvider([]);
+
+ await sync(provider);
+
+ expect(windows).toEqual([
+ { since: "2026-10-12T08:00:00.000Z", until: now }
+ ]);
+ });
+
+ it("reads a later sync from 10 minutes before the last event", async () => {
+ await seed({
+ device: {
+ lastSyncedAt: "2026-10-13T11:58:00.000Z",
+ lastEventAt: "2026-10-13T11:00:00.000Z"
+ }
+ });
+ const { provider, windows } = fakeProvider([]);
+
+ await sync(provider);
+
+ expect(windows).toEqual([
+ { since: "2026-10-13T10:50:00.000Z", until: now }
+ ]);
+ });
+
+ it("opens a system Machine event on the loaded operation when the machine runs", async () => {
+ await seed({
+ workCenter: {
+ loadedJobOperationId: operationId,
+ loadedAt: "2026-10-13T10:00:00.000Z"
+ },
+ device: {
+ currentState: "Idle",
+ currentStateAt: "2026-10-13T09:00:00.000Z",
+ appliedThrough: "2026-10-13T09:00:00.000Z",
+ lastEventAt: "2026-10-13T09:00:00.000Z",
+ lastSyncedAt: "2026-10-13T11:58:00.000Z"
+ }
+ });
+ const { provider } = fakeProvider([
+ {
+ externalEventId: "run",
+ state: "Running",
+ changedAt: "2026-10-13T11:00:00.000Z"
+ }
+ ]);
+
+ await sync(provider);
+
+ expect(await machineEvents()).toEqual([
+ {
+ jobOperationId: operationId,
+ createdBy: "system",
+ employeeId: null,
+ startTime: "2026-10-13T11:00:00.000Z",
+ endTime: null
+ }
+ ]);
+ expect(await unattributedTime()).toEqual([]);
+ expect(await deviceState()).toEqual({
+ currentState: "Running",
+ appliedThrough: "2026-10-13T11:00:00.000Z",
+ lastEventAt: "2026-10-13T11:00:00.000Z"
+ });
+ });
+
+ it("does not plan a change stored at or before appliedThrough, and warns once", async () => {
+ await seed({
+ workCenter: {
+ loadedJobOperationId: operationId,
+ loadedAt: "2026-10-13T09:00:00.000Z"
+ },
+ device: {
+ currentState: "Running",
+ currentStateAt: "2026-10-13T10:00:00.000Z",
+ appliedThrough: "2026-10-13T11:00:00.000Z",
+ lastEventAt: "2026-10-13T11:00:00.000Z",
+ lastSyncedAt: "2026-10-13T11:58:00.000Z"
+ }
+ });
+ await insert("productionEvent", {
+ id: id("running"),
+ jobOperationId: operationId,
+ workCenterId,
+ type: "Machine",
+ startTime: "2026-10-13T10:00:00.000Z"
+ });
+ const warn = vi
+ .spyOn(console, "warn")
+ .mockImplementation(() => undefined);
+ // Stored late: the provider reports a stop older than what was applied.
+ const { provider } = fakeProvider([
+ {
+ externalEventId: "late-stop",
+ state: "Idle",
+ changedAt: "2026-10-13T10:30:00.000Z"
+ }
+ ]);
+
+ await sync(provider);
+
+ expect(warn).toHaveBeenCalledTimes(1);
+ // Planned, the stop would have ended the event at 10:30.
+ expect(await machineEvents()).toEqual([
+ {
+ jobOperationId: operationId,
+ createdBy: "system",
+ employeeId: null,
+ startTime: "2026-10-13T10:00:00.000Z",
+ endTime: null
+ }
+ ]);
+ expect(await deviceState()).toEqual({
+ currentState: "Running",
+ appliedThrough: "2026-10-13T11:00:00.000Z",
+ lastEventAt: "2026-10-13T11:00:00.000Z"
+ });
+ });
+
+ it("writes no time for a device removed while the provider was read", async () => {
+ await seed({
+ workCenter: {
+ loadedJobOperationId: operationId,
+ loadedAt: "2026-10-13T10:00:00.000Z"
+ },
+ device: {
+ currentState: "Idle",
+ currentStateAt: "2026-10-13T09:00:00.000Z",
+ appliedThrough: "2026-10-13T09:00:00.000Z",
+ lastEventAt: "2026-10-13T09:00:00.000Z",
+ lastSyncedAt: "2026-10-13T11:58:00.000Z"
+ }
+ });
+ const { provider } = fakeProvider(
+ [
+ {
+ externalEventId: "run",
+ state: "Running",
+ changedAt: "2026-10-13T11:00:00.000Z"
+ }
+ ],
+ async () => {
+ await client.query(`DELETE FROM "workCenterDevice" WHERE "id" = $1`, [
+ deviceId
+ ]);
+ }
+ );
+
+ await sync(provider);
+
+ expect(await machineEvents()).toEqual([]);
+ expect(await unattributedTime()).toEqual([]);
+ });
+
+ it("closes an open system event where its Canceled operation was unloaded", async () => {
+ // Canceling the operation at 10:45 ended its load there.
+ await seed({
+ operation: {
+ status: "Canceled",
+ updatedAt: "2026-10-13T10:45:00.000Z"
+ },
+ device: {
+ currentState: "Running",
+ currentStateAt: "2026-10-13T10:00:00.000Z",
+ appliedThrough: "2026-10-13T10:00:00.000Z",
+ lastEventAt: "2026-10-13T10:00:00.000Z",
+ lastSyncedAt: "2026-10-13T11:58:00.000Z"
+ }
+ });
+ await insert("productionEvent", {
+ id: id("running"),
+ jobOperationId: operationId,
+ workCenterId,
+ type: "Machine",
+ startTime: "2026-10-13T10:00:00.000Z"
+ });
+ await client.query(
+ `INSERT INTO "workCenterLoad" ("companyId", "workCenterId", "jobOperationId", "loadedAt", "unloadedAt")
+ VALUES ($1, $2, $3, $4, $5)`,
+ [
+ companyId,
+ workCenterId,
+ operationId,
+ "2026-10-13T09:00:00.000Z",
+ "2026-10-13T10:45:00.000Z"
+ ]
+ );
+ const { provider } = fakeProvider([]);
+
+ await sync(provider);
+
+ expect(await machineEvents()).toEqual([
+ {
+ jobOperationId: operationId,
+ createdBy: "system",
+ employeeId: null,
+ startTime: "2026-10-13T10:00:00.000Z",
+ endTime: "2026-10-13T10:45:00.000Z"
+ }
+ ]);
+ // The machine still runs with nothing loaded: the rest is unattributed.
+ expect(await unattributedTime()).toEqual([
+ { startTime: "2026-10-13T10:45:00.000Z", endTime: null }
+ ]);
+ });
+
+ it("records a run reported after the operator's press as unattributed, up to the press", async () => {
+ // The machine started at 11:00; the operator pressed Start at 11:03,
+ // before the provider reported the run.
+ await seed({
+ workCenter: {
+ loadedJobOperationId: operationId,
+ loadedAt: "2026-10-13T11:03:00.000Z"
+ },
+ device: {
+ currentState: "Idle",
+ currentStateAt: "2026-10-13T09:00:00.000Z",
+ appliedThrough: "2026-10-13T09:00:00.000Z",
+ lastEventAt: "2026-10-13T09:00:00.000Z",
+ lastManualChangeAt: "2026-10-13T11:03:00.000Z",
+ lastSyncedAt: "2026-10-13T11:02:00.000Z"
+ }
+ });
+ await insert("productionEvent", {
+ id: id("operator"),
+ jobOperationId: operationId,
+ workCenterId,
+ type: "Machine",
+ startTime: "2026-10-13T11:03:00.000Z",
+ createdBy: "operator"
+ });
+ const { provider } = fakeProvider([
+ {
+ externalEventId: "run",
+ state: "Running",
+ changedAt: "2026-10-13T11:00:00.000Z"
+ }
+ ]);
+
+ await sync(provider);
+
+ expect(await unattributedTime()).toEqual([
+ {
+ startTime: "2026-10-13T11:00:00.000Z",
+ endTime: "2026-10-13T11:03:00.000Z"
+ }
+ ]);
+ // The operator's event is untouched, and the sensor opens none.
+ expect(await machineEvents()).toEqual([
+ {
+ jobOperationId: operationId,
+ createdBy: "operator",
+ employeeId: null,
+ startTime: "2026-10-13T11:03:00.000Z",
+ endTime: null
+ }
+ ]);
+ });
+
+ it("records nothing for a late run that an operator's event already holds", async () => {
+ // The operator ran Machine time from 10:30 and pressed Pause at 11:03.
+ await seed({
+ device: {
+ currentState: "Idle",
+ currentStateAt: "2026-10-13T09:00:00.000Z",
+ appliedThrough: "2026-10-13T09:00:00.000Z",
+ lastEventAt: "2026-10-13T09:00:00.000Z",
+ lastManualChangeAt: "2026-10-13T11:03:00.000Z",
+ lastSyncedAt: "2026-10-13T11:02:00.000Z"
+ }
+ });
+ await insert("productionEvent", {
+ id: id("operator"),
+ jobOperationId: operationId,
+ workCenterId,
+ type: "Machine",
+ startTime: "2026-10-13T10:30:00.000Z",
+ endTime: "2026-10-13T11:03:00.000Z",
+ createdBy: "operator"
+ });
+ // The machine stops 30 seconds after the Pause: no time after it.
+ const { provider } = fakeProvider([
+ {
+ externalEventId: "run",
+ state: "Running",
+ changedAt: "2026-10-13T11:00:00.000Z"
+ },
+ {
+ externalEventId: "stop",
+ state: "Idle",
+ changedAt: "2026-10-13T11:03:30.000Z"
+ }
+ ]);
+
+ await sync(provider);
+
+ expect(await unattributedTime()).toEqual([]);
+ });
+
+ it("gives a run reported after a press to the operation loaded when it started", async () => {
+ // X was loaded from 10:00. The machine started at 11:00; at 11:03 the
+ // operator pressed Start on Y, which loaded Y, before the provider
+ // reported the run.
+ await seed({
+ workCenter: {
+ loadedJobOperationId: operationId,
+ loadedAt: "2026-10-13T11:03:00.000Z"
+ },
+ device: {
+ currentState: "Idle",
+ currentStateAt: "2026-10-13T09:00:00.000Z",
+ appliedThrough: "2026-10-13T09:00:00.000Z",
+ lastEventAt: "2026-10-13T09:00:00.000Z",
+ lastManualChangeAt: "2026-10-13T11:03:00.000Z",
+ lastSyncedAt: "2026-10-13T11:02:00.000Z"
+ }
+ });
+ const earlier = id("op-x");
+ await insert("jobOperation", {
+ id: earlier,
+ jobId: id("job"),
+ processId: id("process"),
+ status: "In Progress"
+ });
+ await client.query(
+ `INSERT INTO "workCenterLoad" ("companyId", "workCenterId", "jobOperationId", "loadedAt", "unloadedAt")
+ VALUES ($1, $2, $3, $4, $5)`,
+ [
+ companyId,
+ workCenterId,
+ earlier,
+ "2026-10-13T10:00:00.000Z",
+ "2026-10-13T11:03:00.000Z"
+ ]
+ );
+ await insert("productionEvent", {
+ id: id("operator"),
+ jobOperationId: operationId,
+ workCenterId,
+ type: "Machine",
+ startTime: "2026-10-13T11:03:00.000Z",
+ createdBy: "operator"
+ });
+ const { provider } = fakeProvider([
+ {
+ externalEventId: "run",
+ state: "Running",
+ changedAt: "2026-10-13T11:00:00.000Z"
+ }
+ ]);
+
+ await sync(provider);
+
+ expect(await machineEvents()).toEqual([
+ {
+ jobOperationId: earlier,
+ createdBy: "system",
+ employeeId: null,
+ startTime: "2026-10-13T11:00:00.000Z",
+ endTime: "2026-10-13T11:03:00.000Z"
+ },
+ {
+ jobOperationId: operationId,
+ createdBy: "operator",
+ employeeId: null,
+ startTime: "2026-10-13T11:03:00.000Z",
+ endTime: null
+ }
+ ]);
+ expect(await unattributedTime()).toEqual([]);
+ });
+
+ it("queues the time a machine runs on after a Pause, up to its stop", async () => {
+ // The operator ran Machine time from 10:30 and pressed Pause at 11:03;
+ // the machine, running since 10:00, stopped at 11:30.
+ await seed({
+ workCenter: {
+ loadedJobOperationId: operationId,
+ loadedAt: "2026-10-13T10:30:00.000Z"
+ },
+ device: {
+ currentState: "Running",
+ currentStateAt: "2026-10-13T10:00:00.000Z",
+ appliedThrough: "2026-10-13T10:00:00.000Z",
+ lastEventAt: "2026-10-13T10:00:00.000Z",
+ lastManualChangeAt: "2026-10-13T11:03:00.000Z",
+ lastSyncedAt: "2026-10-13T11:02:00.000Z"
+ }
+ });
+ await insert("productionEvent", {
+ id: id("operator"),
+ jobOperationId: operationId,
+ workCenterId,
+ type: "Machine",
+ startTime: "2026-10-13T10:30:00.000Z",
+ endTime: "2026-10-13T11:03:00.000Z",
+ createdBy: "operator"
+ });
+ const { provider } = fakeProvider([
+ {
+ externalEventId: "stop",
+ state: "Idle",
+ changedAt: "2026-10-13T11:30:00.000Z"
+ }
+ ]);
+
+ await sync(provider);
+
+ expect(await unattributedTime()).toEqual([
+ {
+ startTime: "2026-10-13T11:03:00.000Z",
+ endTime: "2026-10-13T11:30:00.000Z"
+ }
+ ]);
+ });
+
+ it("deletes closed unattributed time shorter than the minimum", async () => {
+ await seed({
+ device: {
+ currentState: "Idle",
+ currentStateAt: "2026-10-13T09:00:00.000Z",
+ appliedThrough: "2026-10-13T09:00:00.000Z",
+ lastEventAt: "2026-10-13T09:00:00.000Z",
+ lastSyncedAt: "2026-10-13T11:58:00.000Z"
+ }
+ });
+ await insert("unattributedMachineTime", {
+ workCenterId,
+ startTime: "2026-10-13T10:00:00.000Z",
+ endTime: "2026-10-13T10:00:20.000Z"
+ });
+ await insert("unattributedMachineTime", {
+ workCenterId,
+ startTime: "2026-10-13T10:30:00.000Z",
+ endTime: "2026-10-13T10:35:00.000Z"
+ });
+
+ await sync(fakeProvider([]).provider);
+
+ expect(await unattributedTime()).toEqual([
+ {
+ startTime: "2026-10-13T10:30:00.000Z",
+ endTime: "2026-10-13T10:35:00.000Z"
+ }
+ ]);
+ });
+
+ it("records the time between two presses no sync saw, and clears the press marker", async () => {
+ // The machine runs from 09:00. The operator paused at 10:00 and started
+ // again at 10:10, with no sync between.
+ await seed({
+ device: {
+ currentState: "Running",
+ currentStateAt: "2026-10-13T09:00:00.000Z",
+ appliedThrough: "2026-10-13T09:00:00.000Z",
+ lastEventAt: "2026-10-13T09:00:00.000Z",
+ lastManualChangeAt: "2026-10-13T10:10:00.000Z",
+ unplannedPressAt: "2026-10-13T10:00:00.000Z",
+ lastSyncedAt: "2026-10-13T09:58:00.000Z"
+ }
+ });
+ await insert("productionEvent", {
+ id: id("first"),
+ jobOperationId: operationId,
+ workCenterId,
+ type: "Machine",
+ startTime: "2026-10-13T09:30:00.000Z",
+ endTime: "2026-10-13T10:00:00.000Z",
+ createdBy: "operator"
+ });
+ await insert("productionEvent", {
+ id: id("second"),
+ jobOperationId: operationId,
+ workCenterId,
+ type: "Machine",
+ startTime: "2026-10-13T10:10:00.000Z",
+ createdBy: "operator"
+ });
+
+ await sync(fakeProvider([]).provider);
+
+ expect(await unattributedTime()).toEqual([
+ {
+ startTime: "2026-10-13T10:00:00.000Z",
+ endTime: "2026-10-13T10:10:00.000Z"
+ }
+ ]);
+ const marker = await client.query(
+ `SELECT "unplannedPressAt" FROM "workCenterDevice" WHERE "id" = $1`,
+ [deviceId]
+ );
+ expect(marker.rows[0]?.unplannedPressAt).toBeNull();
+ });
+ }
+);
diff --git a/packages/jobs/src/inngest/functions/integrations/oee-sync-device.ts b/packages/jobs/src/inngest/functions/integrations/oee-sync-device.ts
new file mode 100644
index 0000000000..2a59823756
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/integrations/oee-sync-device.ts
@@ -0,0 +1,482 @@
+// 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.
+
+/**
+ * One OEE device's sync: read its state changes from the provider, store them,
+ * then — under the device row lock the MES Machine button also takes — let the
+ * attribution engine decide the Machine events and unattributed time, and
+ * apply its writes. Spec: `.ai/specs/2026-10-12-oee-provider-integration.md`
+ * → "The sync job".
+ */
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import { lockWorkCenterDevice } from "@carbon/database/machine-time";
+import {
+ type MachineState,
+ machineTimeRefusal,
+ type OeeProvider,
+ planMachineTime
+} from "@carbon/ee/oee";
+import { datetime } from "@carbon/utils";
+import { parseAbsolute } from "@internationalized/date";
+import { sql } from "kysely";
+
+const INSERT_CHUNK = 500;
+
+export type OeeSyncDevice = {
+ id: string;
+ companyId: string;
+ workCenterId: string;
+ externalDeviceId: string;
+ externalSiteId: string | null;
+ currentState: MachineState | null;
+ currentStateAt: Date | string | null;
+ appliedThrough: Date | string | null;
+ lastEventAt: Date | string;
+ lastManualChangeAt: Date | string | null;
+ lastSyncedAt: Date | string | null;
+ createdAt: Date | string;
+};
+
+/**
+ * Kysely hands `timestamptz` over as a JS `Date` while the types say string.
+ * Normalize every instant to an ISO string before it is compared or passed on
+ * (`.claude/rules/numeric-precision.md` → "Runtime type decoding").
+ */
+function toInstant(value: Date | string): string;
+function toInstant(value: Date | string | null | undefined): string | null;
+function toInstant(value: Date | string | null | undefined): string | null {
+ if (value === null || value === undefined) return null;
+ return value instanceof Date
+ ? value.toISOString()
+ : parseAbsolute(value, "UTC").toAbsoluteString();
+}
+
+const minus = (iso: string, duration: { hours?: number; minutes?: number }) =>
+ parseAbsolute(iso, "UTC").subtract(duration).toAbsoluteString();
+
+const compareInstants = (a: string, b: string) =>
+ parseAbsolute(a, "UTC").compare(parseAbsolute(b, "UTC"));
+
+/** The later of two ISO instants. */
+const later = (a: string, b: string) => (compareInstants(a, b) >= 0 ? a : b);
+
+export async function syncOeeDevice({
+ db,
+ provider,
+ device,
+ minimumStateSeconds
+}: {
+ db: Kysely<KyselyDatabase>;
+ provider: OeeProvider;
+ device: OeeSyncDevice;
+ minimumStateSeconds: number;
+}) {
+ const now = datetime.timestamp();
+ const mappedAt = toInstant(device.createdAt);
+ const firstLook = minus(mappedAt, { hours: 24 });
+
+ // The first sync looks back a day to learn the state at the mapping; later
+ // syncs re-read 10 minutes so an event the provider stored late is caught.
+ const since =
+ device.lastSyncedAt === null
+ ? firstLook
+ : minus(toInstant(device.lastEventAt), { minutes: 10 });
+
+ const changes = await provider.listStateChanges(
+ {
+ externalDeviceId: device.externalDeviceId,
+ externalSiteId: device.externalSiteId
+ },
+ { since, until: now }
+ );
+
+ // `changedAt` of every row this sync stored; a row already stored by an
+ // earlier sync conflicts and is not returned.
+ const inserted: string[] = [];
+ for (let i = 0; i < changes.length; i += INSERT_CHUNK) {
+ const rows = await db
+ .insertInto("machineStateChange")
+ .values(
+ changes.slice(i, i + INSERT_CHUNK).map((change) => ({
+ companyId: device.companyId,
+ workCenterDeviceId: device.id,
+ workCenterId: device.workCenterId,
+ externalEventId: change.externalEventId,
+ state: change.state,
+ changedAt: change.changedAt
+ }))
+ )
+ .onConflict((oc) =>
+ oc
+ .columns(["workCenterDeviceId", "externalEventId", "companyId"])
+ .doNothing()
+ )
+ .returning("changedAt")
+ .execute();
+ for (const row of rows) inserted.push(toInstant(row.changedAt));
+ }
+
+ // A change stored at or before `appliedThrough` came in late: the engine
+ // has already planned past it and never reads it. History is not replanned
+ // (it may already be posted), so it is only logged.
+ const previouslyApplied = toInstant(device.appliedThrough);
+ if (previouslyApplied !== null) {
+ const late = inserted.filter(
+ (changedAt) => compareInstants(changedAt, previouslyApplied) <= 0
+ ).length;
+ if (late > 0) {
+ console.warn(
+ `OEE device ${device.id}: ${late} late state change(s) at or before appliedThrough ${previouslyApplied}, not replanned`
+ );
+ }
+ }
+
+ // The read cursor follows the newest change stored, never the clock: a
+ // change the provider stores late with an older timestamp is still inside
+ // the next sync's 10-minute overlap. With nothing stored it stays put.
+ const lastEventAt = inserted.reduce(later, toInstant(device.lastEventAt));
+
+ await db.transaction().execute(async (trx) => {
+ const locked = await lockWorkCenterDevice(trx, {
+ workCenterId: device.workCenterId,
+ companyId: device.companyId
+ });
+ // A user removed or remapped the device while the provider was read.
+ if (!locked || locked.id !== device.id) return;
+
+ const appliedThrough = toInstant(locked.appliedThrough);
+ const currentStateAt = toInstant(locked.currentStateAt);
+ const lastManualChangeAt = toInstant(locked.lastManualChangeAt);
+ const firstUnplannedPressAt = toInstant(locked.unplannedPressAt);
+
+ const [openEvent, openUnattributed, lastEnd, stored] = await Promise.all([
+ trx
+ .selectFrom("productionEvent")
+ .select(["id", "jobOperationId", "startTime", "createdBy"])
+ .where("workCenterId", "=", device.workCenterId)
+ .where("companyId", "=", device.companyId)
+ .where("type", "=", "Machine")
+ .where("endTime", "is", null)
+ .orderBy("startTime", "desc")
+ .executeTakeFirst(),
+ trx
+ .selectFrom("unattributedMachineTime")
+ .select(["id", "startTime"])
+ .where("workCenterId", "=", device.workCenterId)
+ .where("companyId", "=", device.companyId)
+ .where("endTime", "is", null)
+ .orderBy("startTime", "desc")
+ .executeTakeFirst(),
+ // The latest Machine end in the current run: where steady-state time
+ // starts again.
+ trx
+ .selectFrom("productionEvent")
+ .select(sql<Date | null>`max("endTime")`.as("lastEnd"))
+ .where("workCenterId", "=", device.workCenterId)
+ .where("companyId", "=", device.companyId)
+ .where("type", "=", "Machine")
+ .where("endTime", ">", currentStateAt ?? mappedAt)
+ .executeTakeFirst(),
+ trx
+ .selectFrom("machineStateChange")
+ .select(["state", "changedAt"])
+ .where("workCenterDeviceId", "=", device.id)
+ .where("companyId", "=", device.companyId)
+ .where("changedAt", ">", appliedThrough ?? firstLook)
+ .orderBy("changedAt", "asc")
+ .execute()
+ ]);
+
+ const lastMachineEventEndTime = toInstant(lastEnd?.lastEnd);
+ const changeInstants = stored.map((row) => toInstant(row.changedAt));
+
+ // The earliest instant this plan can touch: loads, blocks and recorded
+ // time are read from here on.
+ const windowFrom = [
+ changeInstants[0] ?? null,
+ firstUnplannedPressAt,
+ lastManualChangeAt,
+ currentStateAt === null
+ ? mappedAt
+ : lastMachineEventEndTime === null
+ ? currentStateAt
+ : later(currentStateAt, lastMachineEventEndTime),
+ openEvent ? toInstant(openEvent.startTime) : null,
+ openUnattributed ? toInstant(openUnattributed.startTime) : null
+ ]
+ .filter((instant): instant is string => instant !== null)
+ .reduce((a, b) => (compareInstants(a, b) <= 0 ? a : b), now);
+
+ const [loadRows, blockRows, recordedRows] = await Promise.all([
+ // The work center's loads: time goes to the operation loaded when it
+ // ran, not the current one.
+ trx
+ .selectFrom("workCenterLoad")
+ .leftJoin("jobOperation", (join) =>
+ join
+ .onRef("jobOperation.id", "=", "workCenterLoad.jobOperationId")
+ .onRef("jobOperation.companyId", "=", "workCenterLoad.companyId")
+ )
+ .leftJoin("job", (join) =>
+ join
+ .onRef("job.id", "=", "jobOperation.jobId")
+ .onRef("job.companyId", "=", "jobOperation.companyId")
+ )
+ .select([
+ "workCenterLoad.jobOperationId",
+ "workCenterLoad.loadedAt",
+ "workCenterLoad.unloadedAt",
+ "jobOperation.status as operationStatus",
+ "job.status as jobStatus"
+ ])
+ .where("workCenterLoad.workCenterId", "=", device.workCenterId)
+ .where("workCenterLoad.companyId", "=", device.companyId)
+ .where((eb) =>
+ eb.or([
+ eb("workCenterLoad.unloadedAt", "is", null),
+ eb("workCenterLoad.unloadedAt", ">", windowFrom)
+ ])
+ )
+ .orderBy("workCenterLoad.loadedAt", "asc")
+ .execute(),
+ // When maintenance blocked the work center. A Down dispatch blocks from
+ // the moment it is reported (the MES ends every event on the work
+ // center when one is created) until it is Completed or Cancelled; a
+ // Planned one blocks from its actual start. Broader than the view
+ // "workCentersWithBlockingStatus", which counts In Progress only.
+ trx
+ .selectFrom("maintenanceDispatch")
+ .select([
+ sql<
+ Date | string
+ >`CASE WHEN "oeeImpact" = 'Down' THEN "createdAt" ELSE COALESCE("actualStartTime", "updatedAt", "createdAt") END`.as(
+ "blockedFrom"
+ ),
+ sql<
+ Date | string | null
+ >`CASE WHEN "status" IN ('Open', 'Assigned', 'In Progress') THEN NULL ELSE COALESCE("completedAt", "actualEndTime", "updatedAt", "createdAt") END`.as(
+ "blockedTo"
+ )
+ ])
+ .where("workCenterId", "=", device.workCenterId)
+ .where("companyId", "=", device.companyId)
+ .where((eb) =>
+ eb.or([
+ eb.and([
+ eb("oeeImpact", "=", "Down"),
+ eb("status", "in", ["Open", "Assigned", "In Progress"])
+ ]),
+ eb.and([
+ eb("oeeImpact", "=", "Planned"),
+ eb("status", "=", "In Progress")
+ ]),
+ eb.and([
+ eb("oeeImpact", "in", ["Down", "Planned"]),
+ eb("status", "in", ["Completed", "Cancelled"]),
+ eb.or([
+ eb("oeeImpact", "=", "Down"),
+ eb("actualStartTime", "is not", null)
+ ]),
+ eb(
+ sql`COALESCE("completedAt", "actualEndTime", "updatedAt", "createdAt")`,
+ ">",
+ windowFrom
+ )
+ ])
+ ])
+ )
+ .execute(),
+ // Time already recorded on the work center in the window: a late run
+ // or the time after a press is recorded less what these hold, and a
+ // late stop trims the queue rows among them.
+ trx
+ .selectFrom("productionEvent")
+ .select([
+ "id",
+ "startTime",
+ "endTime",
+ sql<"event" | "unattributed">`'event'`.as("kind")
+ ])
+ .where("workCenterId", "=", device.workCenterId)
+ .where("companyId", "=", device.companyId)
+ .where("type", "=", "Machine")
+ .where((eb) =>
+ eb.or([eb("endTime", "is", null), eb("endTime", ">", windowFrom)])
+ )
+ .unionAll(
+ trx
+ .selectFrom("unattributedMachineTime")
+ .select([
+ "id",
+ "startTime",
+ "endTime",
+ sql<"event" | "unattributed">`'unattributed'`.as("kind")
+ ])
+ .where("workCenterId", "=", device.workCenterId)
+ .where("companyId", "=", device.companyId)
+ .where((eb) =>
+ eb.or([eb("endTime", "is", null), eb("endTime", ">", windowFrom)])
+ )
+ )
+ .execute()
+ ]);
+
+ const plan = planMachineTime({
+ now,
+ minimumStateSeconds,
+ mappedAt,
+ currentState: locked.currentState,
+ currentStateAt,
+ lastManualChangeAt,
+ firstUnplannedPressAt,
+ loads: loadRows.map((row) => ({
+ jobOperationId: row.jobOperationId,
+ from: toInstant(row.loadedAt),
+ to: toInstant(row.unloadedAt),
+ assignable:
+ row.operationStatus !== null &&
+ machineTimeRefusal(row.operationStatus, row.jobStatus) === null
+ })),
+ blocks: blockRows.map((row) => ({
+ from: toInstant(row.blockedFrom),
+ to: toInstant(row.blockedTo)
+ })),
+ openMachineEvent: openEvent
+ ? {
+ id: openEvent.id,
+ jobOperationId: openEvent.jobOperationId,
+ startTime: toInstant(openEvent.startTime),
+ system: openEvent.createdBy === "system"
+ }
+ : null,
+ openUnattributed: openUnattributed
+ ? {
+ id: openUnattributed.id,
+ startTime: toInstant(openUnattributed.startTime)
+ }
+ : null,
+ lastMachineEventEndTime,
+ recordedIntervals: recordedRows.map((row) => ({
+ id: row.id,
+ kind: row.kind,
+ startTime: toInstant(row.startTime),
+ endTime: toInstant(row.endTime)
+ })),
+ changes: stored.map((row, i) => ({
+ state: row.state,
+ changedAt: changeInstants[i] ?? toInstant(row.changedAt)
+ }))
+ });
+
+ for (const write of plan.writes) {
+ switch (write.kind) {
+ case "insertMachineEvent":
+ await trx
+ .insertInto("productionEvent")
+ .values({
+ type: "Machine",
+ jobOperationId: write.jobOperationId,
+ workCenterId: device.workCenterId,
+ startTime: write.startTime,
+ endTime: write.endTime,
+ employeeId: null,
+ companyId: device.companyId,
+ createdBy: "system"
+ })
+ .execute();
+ break;
+ case "closeMachineEvent":
+ await trx
+ .updateTable("productionEvent")
+ .set({
+ endTime: write.endTime,
+ updatedBy: "system",
+ updatedAt: now
+ })
+ .where("id", "=", write.productionEventId)
+ .where("companyId", "=", device.companyId)
+ .where("endTime", "is", null)
+ .execute();
+ break;
+ case "insertUnattributed":
+ await trx
+ .insertInto("unattributedMachineTime")
+ .values({
+ companyId: device.companyId,
+ workCenterId: device.workCenterId,
+ startTime: write.startTime,
+ endTime: write.endTime,
+ createdBy: "system"
+ })
+ .execute();
+ break;
+ case "closeUnattributed":
+ await trx
+ .updateTable("unattributedMachineTime")
+ .set({
+ endTime: write.endTime,
+ updatedBy: "system",
+ updatedAt: now
+ })
+ .where("id", "=", write.unattributedId)
+ .where("companyId", "=", device.companyId)
+ .where("endTime", "is", null)
+ .execute();
+ break;
+ case "updateUnattributed":
+ await trx
+ .updateTable("unattributedMachineTime")
+ .set({
+ startTime: write.startTime,
+ endTime: write.endTime,
+ updatedBy: "system",
+ updatedAt: now
+ })
+ .where("id", "=", write.unattributedId)
+ .where("companyId", "=", device.companyId)
+ .execute();
+ break;
+ case "deleteUnattributed":
+ await trx
+ .deleteFrom("unattributedMachineTime")
+ .where("id", "=", write.unattributedId)
+ .where("companyId", "=", device.companyId)
+ .execute();
+ break;
+ }
+ }
+
+ // Unattributed time shorter than the minimum is not kept, whoever closed
+ // it: the sync, an operator's press or an unmapping. Like a short state,
+ // it is noise in the review queue.
+ await trx
+ .deleteFrom("unattributedMachineTime")
+ .where("workCenterId", "=", device.workCenterId)
+ .where("companyId", "=", device.companyId)
+ .where("endTime", "is not", null)
+ .where(
+ sql<boolean>`"endTime" - "startTime" < make_interval(secs => ${minimumStateSeconds})`
+ )
+ .execute();
+
+ await trx
+ .updateTable("workCenterDevice")
+ .set({
+ currentState: plan.currentState,
+ currentStateAt: plan.currentStateAt,
+ ...(plan.appliedThrough ? { appliedThrough: plan.appliedThrough } : {}),
+ // The cursor also follows changes stored by an earlier attempt whose
+ // plan failed: their insert conflicts now and returns nothing.
+ lastEventAt: changeInstants.reduce(later, lastEventAt),
+ unplannedPressAt: null,
+ lastSyncedAt: now,
+ lastSyncError: null
+ })
+ .where("id", "=", device.id)
+ .where("companyId", "=", device.companyId)
+ .execute();
+ });
+
+ return { changes: changes.length };
+}
diff --git a/packages/jobs/src/inngest/functions/integrations/oee-sync.ts b/packages/jobs/src/inngest/functions/integrations/oee-sync.ts
new file mode 100644
index 0000000000..1dcd87bc38
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/integrations/oee-sync.ts
@@ -0,0 +1,113 @@
+// 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.
+
+/**
+ * Syncs every mapped device of one company's OEE integration. All devices run
+ * in ONE step: a step per device would multiply the Inngest cost by the device
+ * count every 2 minutes. Each device is isolated — a failure is recorded on
+ * that device (`lastSyncError`) and keeps its cursor; the others continue.
+ * An `OeeProviderUnavailableError` stops the run instead: every remaining
+ * device would fail the same way.
+ */
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
+import { OeeProviderUnavailableError } from "@carbon/ee/oee";
+import { getOeeProvider } from "@carbon/ee/oee.server";
+import { getJobDatabaseClient } from "../../../db";
+import { inngest } from "../../client";
+import { syncOeeDevice } from "./oee-sync-device";
+
+const MAX_ERROR_LENGTH = 500;
+
+export const oeeSyncFunction = inngest.createFunction(
+ {
+ id: "oee-sync",
+ retries: 2,
+ concurrency: { key: "event.data.companyId", limit: 1 },
+ singleton: {
+ key: "event.data.companyId + '-' + event.data.integrationId",
+ mode: "skip"
+ }
+ },
+ { event: "carbon/oee-sync" },
+ async ({ event, step }) => {
+ const { companyId, integrationId } = event.data as {
+ companyId: string;
+ integrationId: string;
+ };
+
+ return step.run("sync-devices", async () => {
+ const resolved = await getOeeProvider(
+ getCarbonServiceRole(),
+ companyId,
+ integrationId
+ );
+ if (resolved.error !== null) {
+ return { companyId, integrationId, skipped: resolved.error };
+ }
+ const { provider, minimumStateSeconds } = resolved.data;
+
+ const db = getJobDatabaseClient();
+ const devices = await db
+ .selectFrom("workCenterDevice")
+ .select([
+ "id",
+ "companyId",
+ "workCenterId",
+ "externalDeviceId",
+ "externalSiteId",
+ "currentState",
+ "currentStateAt",
+ "appliedThrough",
+ "lastEventAt",
+ "lastManualChangeAt",
+ "lastSyncedAt",
+ "createdAt"
+ ])
+ .where("companyId", "=", companyId)
+ .where("integration", "=", integrationId)
+ .execute();
+
+ const failed: string[] = [];
+ let stopped: string | undefined;
+ for (const device of devices) {
+ try {
+ await syncOeeDevice({ db, provider, device, minimumStateSeconds });
+ } catch (error) {
+ const message =
+ error instanceof Error ? error.message : String(error);
+ console.error(
+ `[OEE SYNC] ${companyId}/${integrationId}: device ${device.id} failed`,
+ error
+ );
+ failed.push(device.id);
+ await db
+ .updateTable("workCenterDevice")
+ .set({ lastSyncError: message.slice(0, MAX_ERROR_LENGTH) })
+ .where("id", "=", device.id)
+ .where("companyId", "=", companyId)
+ .execute()
+ .catch((writeError) =>
+ console.error(
+ `[OEE SYNC] ${companyId}: could not record the error on ${device.id}`,
+ writeError
+ )
+ );
+ // The provider is down: every other device would fail the same way.
+ if (error instanceof OeeProviderUnavailableError) {
+ stopped = message;
+ break;
+ }
+ }
+ }
+
+ return {
+ companyId,
+ integrationId,
+ devices: devices.length,
+ failed,
+ ...(stopped ? { stopped } : {})
+ };
+ });
+ }
+);
diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.ts
index a4a050a970..debfbcdd9e 100644
--- a/packages/jobs/src/inngest/index.ts
+++ b/packages/jobs/src/inngest/index.ts
@@ -45,6 +45,8 @@ import {
linearSyncFunction,
mountPublishFunction,
mountSweepFunction,
+ oeeSweepFunction,
+ oeeSyncFunction,
onshapeBackfillFunction,
onshapeRevisionSyncFunction,
paperlessPartsFunction,
@@ -194,6 +196,8 @@ export const functions = [
onshapeRevisionSyncFunction,
rampSyncFunction,
rampSweepFunction,
+ oeeSweepFunction,
+ oeeSyncFunction,
syncExternalAccountingFunction,
slackDocumentCreatedFunction,
slackDocumentStatusUpdateFunction,
diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.ts
index 2bee576058..114bdd7c13 100644
--- a/packages/lib/src/events.ts
+++ b/packages/lib/src/events.ts
@@ -719,6 +719,12 @@ export type Events = {
reason?: string;
};
};
+ "carbon/oee-sync": {
+ data: {
+ companyId: string;
+ integrationId: string;
+ };
+ };
// Paperless parts integration (full webhook payload)
"carbon/paperless-parts": {
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 8025c2b979..85ee19c841 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -542,6 +542,9 @@ msgstr "{load} in Warteschlange"
msgid "{locationName} (the lease's)"
msgstr "{locationName} (des Leasings)"
+msgid "{mappedCount} of {totalCount} mapped"
+msgstr "{mappedCount} von {totalCount} zugeordnet"
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB-Limit"
@@ -616,6 +619,9 @@ msgstr "{passing} von {total} Anlagen"
msgid "{percent} picked"
msgstr "{percent} kommissioniert"
+msgid "{position} of {total}"
+msgstr "{position} von {total}"
+
msgid "{purgeRowCount, plural, one {Permanently delete # row?} other {Permanently delete # rows?}}"
msgstr "{purgeRowCount, plural, one {# Zeile dauerhaft löschen?} other {# Zeilen dauerhaft löschen?}}"
@@ -640,6 +646,9 @@ msgstr "{sectionLineCount} Positionen"
msgid "{selectedCount} selected"
msgstr "{selectedCount} ausgewählt"
+msgid "{state} · synced {syncedAgo}"
+msgstr "{state} · synchronisiert {syncedAgo}"
+
msgid "{termMonths, plural, one {# month} other {# months}}"
msgstr "{termMonths, plural, one {# Monat} other {# Monate}}"
@@ -2668,6 +2677,9 @@ msgstr "Jährlich. Startet ab dem inkrementellen Kreditzins des Unternehmens"
msgid "Another cost center this one rolls up into, letting you nest a sub-department under its parent for hierarchical cost reporting."
msgstr "Ein anderes Kostenzentrum, dem dieses untergeordnet ist, was es ermöglicht, eine Unterkostenstelle unter ihrer Muttergesellschaft für hierarchische Kostenberichterstattung zu verschachteln."
+msgid "Another job or operation"
+msgstr "Anderer Auftrag oder Arbeitsgang"
+
msgid "Another spend integration is already active"
msgstr "Eine andere Ausgabenintegration ist bereits aktiv"
@@ -3540,6 +3552,9 @@ msgstr "Vermögenswerte"
msgid "Assets, liabilities and equity as of a date"
msgstr "Vermögenswerte, Verbindlichkeiten und Eigenkapital an einem bestimmten Stichtag"
+msgid "Assign machine run time that no loaded operation claimed to the right job, or dismiss it."
+msgstr "Weisen Sie die Maschinenbearbeitungszeit, die kein geladener Arbeitsgang beansprucht hat, dem richtigen Fertigungsauftrag zu oder lehnen Sie sie ab."
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Weisen Sie Druckern Standorte zu. Versand, Wareneingang und Arbeitsplätze erben die Standort-Standardeinstellungen, sofern nicht manuell überschrieben."
@@ -5425,6 +5440,9 @@ msgstr "Jira-Problem verbinden"
msgid "Connect Linear issue"
msgstr "Linear-Problem verbinden"
+msgid "Connect machine monitoring devices to work centers so machine time is recorded against the operation that is loaded."
+msgstr "Verbinden Sie Maschinenüberwachungsgeräte mit Arbeitsplätzen, damit die Maschinenzeit für den geladenen Arbeitsgang aufgezeichnet wird."
+
msgid "Connect Slack under Settings → Integrations first."
msgstr "Verbinden Sie Slack zuerst unter Einstellungen → Integrationen."
@@ -6001,6 +6019,15 @@ msgstr "PDF konnte nicht erstellt werden. Versuchen Sie es erneut."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "Konnte {0} nicht auflösen: {1} — Produktion bereits erfasst"
+msgid "Could not list the provider's devices. Mapped devices are still shown."
+msgstr "Die Geräte des Anbieters konnten nicht abgerufen werden. Zugeordnete Geräte werden weiterhin angezeigt."
+
+msgid "Could not load operations"
+msgstr "Arbeitsgänge konnten nicht geladen werden"
+
+msgid "Could not load what ran on {workCenterName}."
+msgstr "Konnte nicht laden, was auf {workCenterName} gelaufen ist."
+
msgid "Could not predict lead time"
msgstr "Beschaffungszeit konnte nicht vorhergesagt werden"
@@ -7660,6 +7687,9 @@ msgstr "Erkannt vom Bewegungsplaner"
msgid "Developer"
msgstr "Entwickler"
+msgid "Devices"
+msgstr "Geräte"
+
msgid "Difference"
msgstr "Differenz"
@@ -7928,6 +7958,9 @@ msgstr "Doppelklicken Sie, um diese Unterbaugruppe zu öffnen"
msgid "Double-click to play this step"
msgstr "Doppelklicken Sie, um diesen Schritt abzuspielen"
+msgid "Down"
+msgstr "Stillstand"
+
msgid "Download"
msgstr "Herunterladen"
@@ -11028,6 +11061,9 @@ msgstr "Identitätsanbieter"
msgid "Identity provider (IdP)"
msgstr "Identitätsanbieter (IdP)"
+msgid "Idle"
+msgstr "Leerlauf"
+
msgid "IdP Metadata URL"
msgstr "IdP-Metadaten-URL"
@@ -11936,6 +11972,9 @@ msgstr "Auftrag in Bearbeitung"
msgid "Job Location"
msgstr "Auftragsort"
+msgid "Job locked"
+msgstr "Auftrag gesperrt"
+
msgid "Job make method"
msgstr "Auftragsfertigungsmethode"
@@ -12758,6 +12797,9 @@ msgstr "Maschinenkosten"
msgid "Machine Hours"
msgstr "Maschinenstunden"
+msgid "Machine monitoring"
+msgstr "Maschinenüberwachung"
+
msgid "Machine rate"
msgstr "Maschinensatz"
@@ -12969,6 +13011,9 @@ msgstr "Ordnen Sie Ihren Kontenplan dem des Anbieters zu. Buchungs-Standardkonte
msgid "Map your current process, systems, and data"
msgstr "Ordnen Sie Ihren aktuellen Prozess, Ihre Systeme und Daten"
+msgid "Mapped devices"
+msgstr "Zugeordnete Geräte"
+
msgid "Mapped values"
msgstr "Zugeordnete Werte"
@@ -14340,6 +14385,12 @@ msgstr "Für diese Vereinbarung wurde keine Anzahlung eingezogen."
msgid "No depreciation run happens before the cutover. Enter each asset's accumulated depreciation as of the day before the cutover."
msgstr "Keine Abschreibungslaufzahl erfolgt vor dem Stichtag. Geben Sie die kumulierte Abschreibung jedes Vermögenswerts vom Tag vor dem Stichtag ein."
+msgid "No devices found"
+msgstr "Keine Geräte gefunden"
+
+msgid "No devices match your search"
+msgstr "Keine Geräte entsprechen Ihrer Suche"
+
msgid "No dimension slots configured"
msgstr "Keine Dimensions-Slots konfiguriert"
@@ -14475,6 +14526,9 @@ msgstr "Keine Artikel"
msgid "No items have inventory activity here yet."
msgstr "Hier gibt es noch keine Bestandsbewegungen."
+msgid "No job at this location has an open operation."
+msgstr "Kein Fertigungsauftrag an diesem Standort hat einen offenen Arbeitsgang."
+
msgid "No jobs are scheduled at this location yet — release a job to see work-center load."
msgstr "Noch keine Fertigungsaufträge an diesem Standort geplant — geben Sie einen Fertigungsauftrag frei, um die Arbeitszentrums-Auslastung zu sehen."
@@ -14568,6 +14622,9 @@ msgstr "Keine offenen Positionen. Fügen Sie eine Dienstleistung hinzu, um zu ä
msgid "No open memos"
msgstr "Keine offenen Notizen"
+msgid "No open operations"
+msgstr "Keine offenen Arbeitsgänge"
+
msgid "No open orders for this item are available to link."
msgstr "Für diesen Artikel sind keine offenen Bestellungen zum Verknüpfen verfügbar."
@@ -14932,6 +14989,9 @@ msgstr "Normal"
msgid "Not a table but a general-ledger balance: cost accumulates as job materials are issued and clears when the job is received to stock."
msgstr "Nicht eine Tabelle, sondern ein Hauptbuch-Saldo: Kosten sammeln sich, wenn Auftragsmaterialien ausgegeben werden, und werden gelöscht, wenn der Auftrag im Bestand empfangen wird."
+msgid "Not calibrated"
+msgstr "Nicht kalibriert"
+
msgid "Not certified"
msgstr "Nicht zertifiziert"
@@ -14953,6 +15013,12 @@ msgstr "Nicht genug Einheitendaten"
msgid "Not feasible"
msgstr "Nicht machbar"
+msgid "Not job time"
+msgstr "Keine Auftragszeit"
+
+msgid "Not mapped"
+msgstr "Nicht zugeordnet"
+
msgid "Not now"
msgstr "Jetzt nicht"
@@ -15017,6 +15083,9 @@ msgstr "In MES noch nichts abgeschlossen"
msgid "Nothing else at this location has stock to pull from."
msgstr "Keine anderen Artikel an diesem Ort haben Bestand zum Entnehmen."
+msgid "Nothing else ran on {workCenterName} that day."
+msgstr "An diesem Tag lief sonst nichts auf {workCenterName}."
+
msgid "Nothing here matches your search and filters."
msgstr "Nichts hier entspricht Ihrer Suche und Ihren Filtern."
@@ -15074,6 +15143,9 @@ msgstr "Benachrichtigen"
msgid "Notify someone"
msgstr "Jemanden benachrichtigen"
+msgid "now"
+msgstr "jetzt"
+
msgid "Number"
msgstr "Zahl"
@@ -15117,6 +15189,9 @@ msgstr "Aus — außerhalb der Synchronisierung behandelt"
msgid "Off — released revisions stay editable"
msgstr "Aus — ausgegebene Revisionen bleiben bearbeitbar"
+msgid "Offline"
+msgstr "Offline"
+
msgid "Offset Account"
msgstr "Gegenkonto"
@@ -16069,6 +16144,9 @@ msgstr "Pfad"
msgid "Pause"
msgstr "Unterbrechen"
+msgid "Paused"
+msgstr "Pausiert"
+
msgid "Pay"
msgstr "Zahlen"
@@ -17579,6 +17657,9 @@ msgstr "Ramp hat keinen Autorisierungscode zurückgegeben"
msgid "Ramp rejected the authorization"
msgstr "Ramp hat die Autorisierung abgelehnt"
+msgid "Ran at the time"
+msgstr "Lief zu dieser Zeit"
+
msgid "Rate"
msgstr "Kurs"
@@ -18107,6 +18188,9 @@ msgstr "Freigegeben mit Problemen: {0}"
msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
msgstr "Die Freigabe des Loses gibt seine Fertigungsaufträge frei, und jeder muss für die Werkstatt bereit sein."
+msgid "Reload the page to try again."
+msgstr "Seite neu laden, um es erneut zu versuchen."
+
msgid "Remaining"
msgstr "Verbleibend"
@@ -19595,6 +19679,9 @@ msgstr "Kunden und Typen durchsuchen..."
msgid "Search customers or types..."
msgstr "Kunden oder Typen durchsuchen..."
+msgid "Search devices"
+msgstr "Geräte suchen"
+
msgid "Search employees..."
msgstr "Mitarbeiter durchsuchen..."
@@ -19619,6 +19706,9 @@ msgstr "Artikel oder Lagerplätze suchen"
msgid "Search Job"
msgstr "Job durchsuchen"
+msgid "Search jobs and operations"
+msgstr "Aufträge und Arbeitsgänge suchen"
+
msgid "Search jobs or items"
msgstr "Fertigungsaufträge oder Artikel durchsuchen"
@@ -20945,6 +21035,9 @@ msgstr "Wird gestartet…"
msgid "Starts"
msgstr "Startet"
+msgid "State"
+msgstr "Zustand"
+
msgid "State / Province"
msgstr "Bundesland / Provinz"
@@ -21096,6 +21189,9 @@ msgstr "Versand stoppen"
msgid "Stop using {0} in this step"
msgstr "Verwendung von {0} in diesem Schritt beenden"
+msgid "Stopped"
+msgstr "Gestoppt"
+
msgid "Stops new purchase suggestions after this date."
msgstr "Beendet neue Kaufvorschläge nach diesem Datum."
@@ -22187,6 +22283,9 @@ msgstr "Der Steuersatz, der auf die Angebots- und Kundenauftrags-Positionen dies
msgid "The department this one rolls up under for reporting and headcount hierarchies; leave empty for a top-level department."
msgstr "Die Abteilung, unter die diese für Berichterstattung und Kopfzahlen-Hierarchien untergeordnet ist; leer lassen für eine Abteilung der obersten Ebene."
+msgid "The device's site is in {siteTimezone}; Carbon uses {locationTimezone}"
+msgstr "Der Standort des Geräts liegt in {siteTimezone}; Carbon verwendet {locationTimezone}"
+
msgid "The early hours, {name}."
msgstr "Die frühen Stunden, {name}."
@@ -22459,6 +22558,9 @@ msgstr "Der Stichprobenplan pro Merkmal der Charge wird aus dem ausgewählten Do
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "Der niedrigste Betrag, den dieser Lieferant für dieses Verfahren berechnet, unabhängig von der Menge; Fertigungsaufträge unter dem Break-Even-Volumen kosten mindestens diesen Betrag."
+msgid "The machine is still running. Assign this time after it stops."
+msgstr "Die Maschine läuft noch. Ordnen Sie diese Zeit zu, nachdem sie stoppt."
+
msgid "The machines, cells, and stations your work runs through"
msgstr "Die Maschinen, Zellen und Stationen, durch die Ihre Arbeit läuft"
@@ -24068,6 +24170,9 @@ msgstr "Regel entfernen"
msgid "Unassigned"
msgstr "Nicht zugewiesen"
+msgid "Unattributed Time"
+msgstr "Nicht zugeordnete Zeit"
+
msgid "Unbalanced"
msgstr "Nicht ausgeglichen"
@@ -24843,6 +24948,9 @@ msgstr "Buchungszeile anzeigen"
msgid "View Lists"
msgstr "Listen anzeigen"
+msgid "View Machine Time"
+msgstr "Maschinenzeit anzeigen"
+
msgid "View maintenance dispatch"
msgstr "Instandhaltungsauftrag anzeigen"
@@ -25022,6 +25130,12 @@ msgstr "Das Stornieren dieser Lieferung wird:"
msgid "Waited"
msgstr "Wartezeit"
+msgid "Waiting"
+msgstr "Wartet"
+
+msgid "Waiting for the first sync"
+msgstr "Warten auf die erste Synchronisierung"
+
msgid "Walk each area with your champion and toggle anything out of scope. Codes read Module.Area.Number (ACC.GL.01 = Accounting, General Ledger, item 1)."
msgstr "Gehen Sie mit Ihrem Champion jeden Bereich durch und deaktivieren Sie alles, das außerhalb des Umfangs liegt. Codes werden gelesen als Modul.Bereich.Nummer (ACC.GL.01 = Buchhaltung, Hauptbuch, Position 1)."
@@ -25528,6 +25642,9 @@ msgstr "Welche Art von Anfrage zu senden ist: GET liest etwas, POST erstellt, PU
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Welches Fertigungsereignis die Lagerfrist-Uhr startet — z. B. Füllen, Versiegeln oder endgültiges QS."
+msgid "Which operation was this?"
+msgstr "Welcher Arbeitsgang war das?"
+
msgid "While this dispatch is open, the work center is unavailable to the schedule (until the planned end time, or until the dispatch is completed)."
msgstr "Während dieser Instandhaltungsauftrag offen ist, ist der Arbeitsplatz für den Terminplan nicht verfügbar (bis zur geplanten Endzeit oder bis der Instandhaltungsauftrag fertiggestellt ist)."
diff --git a/packages/locale/locales/de/mes.po b/packages/locale/locales/de/mes.po
index 68aecbcbe1..bcb86e88ee 100644
--- a/packages/locale/locales/de/mes.po
+++ b/packages/locale/locales/de/mes.po
@@ -820,6 +820,9 @@ msgstr "Ich arbeite noch"
msgid "Ideas, suggestions or problems?"
msgstr "Ideen, Vorschläge oder Probleme?"
+msgid "Idle"
+msgstr "Leerlauf"
+
msgid "Idle for"
msgstr "Untätig seit"
@@ -965,6 +968,9 @@ msgstr "Listenansicht"
msgid "Load list"
msgstr "Liste laden"
+msgid "Loaded: {loadedLabel}"
+msgstr "Beladen: {loadedLabel}"
+
msgid "Loading item details..."
msgstr "Artikeldetails werden geladen..."
@@ -1286,6 +1292,9 @@ msgstr "OEM erforderlich"
msgid "of {0}"
msgstr "von {0}"
+msgid "Offline"
+msgstr "Offline"
+
msgid "Oldest first"
msgstr "Älteste zuerst"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index be9929d01c..d4d09ec159 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -542,6 +542,9 @@ msgstr "{load} in queue"
msgid "{locationName} (the lease's)"
msgstr "{locationName} (the lease's)"
+msgid "{mappedCount} of {totalCount} mapped"
+msgstr "{mappedCount} of {totalCount} mapped"
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB limit"
@@ -616,6 +619,9 @@ msgstr "{passing} of {total} assets"
msgid "{percent} picked"
msgstr "{percent} picked"
+msgid "{position} of {total}"
+msgstr "{position} of {total}"
+
msgid "{purgeRowCount, plural, one {Permanently delete # row?} other {Permanently delete # rows?}}"
msgstr "{purgeRowCount, plural, one {Permanently delete # row?} other {Permanently delete # rows?}}"
@@ -640,6 +646,9 @@ msgstr "{sectionLineCount} lines"
msgid "{selectedCount} selected"
msgstr "{selectedCount} selected"
+msgid "{state} · synced {syncedAgo}"
+msgstr "{state} · synced {syncedAgo}"
+
msgid "{termMonths, plural, one {# month} other {# months}}"
msgstr "{termMonths, plural, one {# month} other {# months}}"
@@ -2668,6 +2677,9 @@ msgstr "Annual. Starts from the company's incremental borrowing rate"
msgid "Another cost center this one rolls up into, letting you nest a sub-department under its parent for hierarchical cost reporting."
msgstr "Another cost center this one rolls up into, letting you nest a sub-department under its parent for hierarchical cost reporting."
+msgid "Another job or operation"
+msgstr "Another job or operation"
+
msgid "Another spend integration is already active"
msgstr "Another spend integration is already active"
@@ -3540,6 +3552,9 @@ msgstr "Assets"
msgid "Assets, liabilities and equity as of a date"
msgstr "Assets, liabilities and equity as of a date"
+msgid "Assign machine run time that no loaded operation claimed to the right job, or dismiss it."
+msgstr "Assign machine run time that no loaded operation claimed to the right job, or dismiss it."
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
@@ -5425,6 +5440,9 @@ msgstr "Connect Jira issue"
msgid "Connect Linear issue"
msgstr "Connect Linear issue"
+msgid "Connect machine monitoring devices to work centers so machine time is recorded against the operation that is loaded."
+msgstr "Connect machine monitoring devices to work centers so machine time is recorded against the operation that is loaded."
+
msgid "Connect Slack under Settings → Integrations first."
msgstr "Connect Slack under Settings → Integrations first."
@@ -6001,6 +6019,15 @@ msgstr "Could not build PDF. Try again."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "Could not dissolve {0}: {1} — production already recorded"
+msgid "Could not list the provider's devices. Mapped devices are still shown."
+msgstr "Could not list the provider's devices. Mapped devices are still shown."
+
+msgid "Could not load operations"
+msgstr "Could not load operations"
+
+msgid "Could not load what ran on {workCenterName}."
+msgstr "Could not load what ran on {workCenterName}."
+
msgid "Could not predict lead time"
msgstr "Could not predict lead time"
@@ -7660,6 +7687,9 @@ msgstr "Detected by the motion planner"
msgid "Developer"
msgstr "Developer"
+msgid "Devices"
+msgstr "Devices"
+
msgid "Difference"
msgstr "Difference"
@@ -7928,6 +7958,9 @@ msgstr "Double-click to open this sub-assembly"
msgid "Double-click to play this step"
msgstr "Double-click to play this step"
+msgid "Down"
+msgstr "Down"
+
msgid "Download"
msgstr "Download"
@@ -11028,6 +11061,9 @@ msgstr "Identity Provider"
msgid "Identity provider (IdP)"
msgstr "Identity provider (IdP)"
+msgid "Idle"
+msgstr "Idle"
+
msgid "IdP Metadata URL"
msgstr "IdP Metadata URL"
@@ -11936,6 +11972,9 @@ msgstr "Job in progress"
msgid "Job Location"
msgstr "Job Location"
+msgid "Job locked"
+msgstr "Job locked"
+
msgid "Job make method"
msgstr "Job make method"
@@ -12758,6 +12797,9 @@ msgstr "Machine Costs"
msgid "Machine Hours"
msgstr "Machine Hours"
+msgid "Machine monitoring"
+msgstr "Machine monitoring"
+
msgid "Machine rate"
msgstr "Machine rate"
@@ -12969,6 +13011,9 @@ msgstr "Map your chart of accounts to the provider's. Posting-default and expens
msgid "Map your current process, systems, and data"
msgstr "Map your current process, systems, and data"
+msgid "Mapped devices"
+msgstr "Mapped devices"
+
msgid "Mapped values"
msgstr "Mapped values"
@@ -14340,6 +14385,12 @@ msgstr "No deposit has been received for this agreement."
msgid "No depreciation run happens before the cutover. Enter each asset's accumulated depreciation as of the day before the cutover."
msgstr "No depreciation run happens before the cutover. Enter each asset's accumulated depreciation as of the day before the cutover."
+msgid "No devices found"
+msgstr "No devices found"
+
+msgid "No devices match your search"
+msgstr "No devices match your search"
+
msgid "No dimension slots configured"
msgstr "No dimension slots configured"
@@ -14475,6 +14526,9 @@ msgstr "No items"
msgid "No items have inventory activity here yet."
msgstr "No items have inventory activity here yet."
+msgid "No job at this location has an open operation."
+msgstr "No job at this location has an open operation."
+
msgid "No jobs are scheduled at this location yet — release a job to see work-center load."
msgstr "No jobs are scheduled at this location yet — release a job to see work-center load."
@@ -14568,6 +14622,9 @@ msgstr "No open lines. Add a service to amend."
msgid "No open memos"
msgstr "No open memos"
+msgid "No open operations"
+msgstr "No open operations"
+
msgid "No open orders for this item are available to link."
msgstr "No open orders for this item are available to link."
@@ -14932,6 +14989,9 @@ msgstr "Normal"
msgid "Not a table but a general-ledger balance: cost accumulates as job materials are issued and clears when the job is received to stock."
msgstr "Not a table but a general-ledger balance: cost accumulates as job materials are issued and clears when the job is received to stock."
+msgid "Not calibrated"
+msgstr "Not calibrated"
+
msgid "Not certified"
msgstr "Not certified"
@@ -14953,6 +15013,12 @@ msgstr "Not enough unit data"
msgid "Not feasible"
msgstr "Not feasible"
+msgid "Not job time"
+msgstr "Not job time"
+
+msgid "Not mapped"
+msgstr "Not mapped"
+
msgid "Not now"
msgstr "Not now"
@@ -15017,6 +15083,9 @@ msgstr "Nothing completed in MES yet"
msgid "Nothing else at this location has stock to pull from."
msgstr "Nothing else at this location has stock to pull from."
+msgid "Nothing else ran on {workCenterName} that day."
+msgstr "Nothing else ran on {workCenterName} that day."
+
msgid "Nothing here matches your search and filters."
msgstr "Nothing here matches your search and filters."
@@ -15074,6 +15143,9 @@ msgstr "Notify"
msgid "Notify someone"
msgstr "Notify someone"
+msgid "now"
+msgstr "now"
+
msgid "Number"
msgstr "Number"
@@ -15117,6 +15189,9 @@ msgstr "Off — handled outside the sync"
msgid "Off — released revisions stay editable"
msgstr "Off — released revisions stay editable"
+msgid "Offline"
+msgstr "Offline"
+
msgid "Offset Account"
msgstr "Offset Account"
@@ -16069,6 +16144,9 @@ msgstr "Path"
msgid "Pause"
msgstr "Pause"
+msgid "Paused"
+msgstr "Paused"
+
msgid "Pay"
msgstr "Pay"
@@ -17579,6 +17657,9 @@ msgstr "Ramp didn't return an authorization code"
msgid "Ramp rejected the authorization"
msgstr "Ramp rejected the authorization"
+msgid "Ran at the time"
+msgstr "Ran at the time"
+
msgid "Rate"
msgstr "Rate"
@@ -18107,6 +18188,9 @@ msgstr "Released with problems: {0}"
msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
msgstr "Releasing the batch releases its jobs, and each one must be ready for the floor."
+msgid "Reload the page to try again."
+msgstr "Reload the page to try again."
+
msgid "Remaining"
msgstr "Remaining"
@@ -19595,6 +19679,9 @@ msgstr "Search customers and types..."
msgid "Search customers or types..."
msgstr "Search customers or types..."
+msgid "Search devices"
+msgstr "Search devices"
+
msgid "Search employees..."
msgstr "Search employees..."
@@ -19619,6 +19706,9 @@ msgstr "Search items or bins"
msgid "Search Job"
msgstr "Search Job"
+msgid "Search jobs and operations"
+msgstr "Search jobs and operations"
+
msgid "Search jobs or items"
msgstr "Search jobs or items"
@@ -20945,6 +21035,9 @@ msgstr "Starting…"
msgid "Starts"
msgstr "Starts"
+msgid "State"
+msgstr "State"
+
msgid "State / Province"
msgstr "State / Province"
@@ -21096,6 +21189,9 @@ msgstr "Stop Shipping"
msgid "Stop using {0} in this step"
msgstr "Stop using {0} in this step"
+msgid "Stopped"
+msgstr "Stopped"
+
msgid "Stops new purchase suggestions after this date."
msgstr "Stops new purchase suggestions after this date."
@@ -22187,6 +22283,9 @@ msgstr "The default tax rate applied to this customer's quote and sales-order li
msgid "The department this one rolls up under for reporting and headcount hierarchies; leave empty for a top-level department."
msgstr "The department this one rolls up under for reporting and headcount hierarchies; leave empty for a top-level department."
+msgid "The device's site is in {siteTimezone}; Carbon uses {locationTimezone}"
+msgstr "The device's site is in {siteTimezone}; Carbon uses {locationTimezone}"
+
msgid "The early hours, {name}."
msgstr "The early hours, {name}."
@@ -22459,6 +22558,9 @@ msgstr "The lot's per-characteristic sampling plan will be re-resolved from the
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
+msgid "The machine is still running. Assign this time after it stops."
+msgstr "The machine is still running. Assign this time after it stops."
+
msgid "The machines, cells, and stations your work runs through"
msgstr "The machines, cells, and stations your work runs through"
@@ -24068,6 +24170,9 @@ msgstr "Unassign rule"
msgid "Unassigned"
msgstr "Unassigned"
+msgid "Unattributed Time"
+msgstr "Unattributed Time"
+
msgid "Unbalanced"
msgstr "Unbalanced"
@@ -24843,6 +24948,9 @@ msgstr "View Journal Entry"
msgid "View Lists"
msgstr "View Lists"
+msgid "View Machine Time"
+msgstr "View Machine Time"
+
msgid "View maintenance dispatch"
msgstr "View maintenance dispatch"
@@ -25022,6 +25130,12 @@ msgstr "Voiding this shipment will:"
msgid "Waited"
msgstr "Waited"
+msgid "Waiting"
+msgstr "Waiting"
+
+msgid "Waiting for the first sync"
+msgstr "Waiting for the first sync"
+
msgid "Walk each area with your champion and toggle anything out of scope. Codes read Module.Area.Number (ACC.GL.01 = Accounting, General Ledger, item 1)."
msgstr "Walk each area with your champion and toggle anything out of scope. Codes read Module.Area.Number (ACC.GL.01 = Accounting, General Ledger, item 1)."
@@ -25528,6 +25642,9 @@ msgstr "Which kind of request to send: GET reads something, POST creates, PUT an
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
+msgid "Which operation was this?"
+msgstr "Which operation was this?"
+
msgid "While this dispatch is open, the work center is unavailable to the schedule (until the planned end time, or until the dispatch is completed)."
msgstr "While this dispatch is open, the work center is unavailable to the schedule (until the planned end time, or until the dispatch is completed)."
diff --git a/packages/locale/locales/en/mes.po b/packages/locale/locales/en/mes.po
index 705b8c5be2..4e73833644 100644
--- a/packages/locale/locales/en/mes.po
+++ b/packages/locale/locales/en/mes.po
@@ -820,6 +820,9 @@ msgstr "I'm Still Working"
msgid "Ideas, suggestions or problems?"
msgstr "Ideas, suggestions or problems?"
+msgid "Idle"
+msgstr "Idle"
+
msgid "Idle for"
msgstr "Idle for"
@@ -965,6 +968,9 @@ msgstr "List view"
msgid "Load list"
msgstr "Load list"
+msgid "Loaded: {loadedLabel}"
+msgstr "Loaded: {loadedLabel}"
+
msgid "Loading item details..."
msgstr "Loading item details..."
@@ -1286,6 +1292,9 @@ msgstr "OEM Required"
msgid "of {0}"
msgstr "of {0}"
+msgid "Offline"
+msgstr "Offline"
+
msgid "Oldest first"
msgstr "Oldest first"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 8099d97488..f5866af8ed 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -542,6 +542,9 @@ msgstr "{load} en cola"
msgid "{locationName} (the lease's)"
msgstr "{locationName} (del arrendamiento)"
+msgid "{mappedCount} of {totalCount} mapped"
+msgstr "{mappedCount} de {totalCount} asignados"
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB límite"
@@ -616,6 +619,9 @@ msgstr "{passing} de {total} activos"
msgid "{percent} picked"
msgstr "{percent} preparados"
+msgid "{position} of {total}"
+msgstr "{position} de {total}"
+
msgid "{purgeRowCount, plural, one {Permanently delete # row?} other {Permanently delete # rows?}}"
msgstr "{purgeRowCount, plural, one {¿Eliminar permanentemente # fila?} other {¿Eliminar permanentemente # filas?}}"
@@ -640,6 +646,9 @@ msgstr "{sectionLineCount} líneas"
msgid "{selectedCount} selected"
msgstr "{selectedCount} seleccionados"
+msgid "{state} · synced {syncedAgo}"
+msgstr "{state} · sincronizado {syncedAgo}"
+
msgid "{termMonths, plural, one {# month} other {# months}}"
msgstr "{termMonths, plural, one {# mes} other {# meses}}"
@@ -2668,6 +2677,9 @@ msgstr "Anual. Comienza desde la tasa de endeudamiento incremental de la empresa
msgid "Another cost center this one rolls up into, letting you nest a sub-department under its parent for hierarchical cost reporting."
msgstr "Otro centro de costos al que este se agrupa, permitiéndole anidar un subcentro de costos bajo su principal para reportes de costos jerárquicos."
+msgid "Another job or operation"
+msgstr "Otro trabajo u operación"
+
msgid "Another spend integration is already active"
msgstr "Otra integración de gastos ya está activa"
@@ -3540,6 +3552,9 @@ msgstr "Activos"
msgid "Assets, liabilities and equity as of a date"
msgstr "Activos, pasivos y patrimonio a una fecha"
+msgid "Assign machine run time that no loaded operation claimed to the right job, or dismiss it."
+msgstr "Asigne el Tiempo de máquina que ninguna Operación cargada reclamó a la Orden de trabajo correcta, o descarte."
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Asigna impresoras a ubicaciones. Envíos, recepciones y centros de trabajo heredan la ubicación predeterminada a menos que se anulen."
@@ -5425,6 +5440,9 @@ msgstr "Conectar problema de Jira"
msgid "Connect Linear issue"
msgstr "Conectar problema de Linear"
+msgid "Connect machine monitoring devices to work centers so machine time is recorded against the operation that is loaded."
+msgstr "Conecte los dispositivos de monitoreo de máquinas a los Centros de trabajo para que el Tiempo de máquina se registre en la Operación que está cargada."
+
msgid "Connect Slack under Settings → Integrations first."
msgstr "Conecta Slack en Configuración → Integraciones primero."
@@ -6001,6 +6019,15 @@ msgstr "No se pudo crear el PDF. Intenta de nuevo."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "No se pudo disolver {0}: {1} — producción ya registrada"
+msgid "Could not list the provider's devices. Mapped devices are still shown."
+msgstr "No se pudieron listar los dispositivos del proveedor. Los dispositivos asignados se siguen mostrando."
+
+msgid "Could not load operations"
+msgstr "No se pudieron cargar las operaciones"
+
+msgid "Could not load what ran on {workCenterName}."
+msgstr "No se pudo cargar lo que se ejecutó en {workCenterName}."
+
msgid "Could not predict lead time"
msgstr "No se pudo predecir el plazo de entrega"
@@ -7660,6 +7687,9 @@ msgstr "Detectado por el planificador de movimiento"
msgid "Developer"
msgstr "Desarrollador"
+msgid "Devices"
+msgstr "Dispositivos"
+
msgid "Difference"
msgstr "Diferencia"
@@ -7928,6 +7958,9 @@ msgstr "Haz doble clic para abrir este subensamblaje"
msgid "Double-click to play this step"
msgstr "Doble clic para reproducir este paso"
+msgid "Down"
+msgstr "Fuera de servicio"
+
msgid "Download"
msgstr "Descargar"
@@ -11028,6 +11061,9 @@ msgstr "Proveedor de identidad"
msgid "Identity provider (IdP)"
msgstr "Proveedor de identidad (IdP)"
+msgid "Idle"
+msgstr "Parado"
+
msgid "IdP Metadata URL"
msgstr "URL de metadatos de IdP"
@@ -11936,6 +11972,9 @@ msgstr "Trabajo en curso"
msgid "Job Location"
msgstr "Ubicación del Trabajo"
+msgid "Job locked"
+msgstr "Trabajo bloqueado"
+
msgid "Job make method"
msgstr "Método de fabricación de la Orden de trabajo"
@@ -12758,6 +12797,9 @@ msgstr "Costos de máquina"
msgid "Machine Hours"
msgstr "Horas de Máquina"
+msgid "Machine monitoring"
+msgstr "Monitoreo de máquinas"
+
msgid "Machine rate"
msgstr "Tarifa de máquina"
@@ -12969,6 +13011,9 @@ msgstr "Asigne su Plan de cuentas al del proveedor. Las cuentas predeterminadas
msgid "Map your current process, systems, and data"
msgstr "Mapea tu proceso actual, sistemas y datos"
+msgid "Mapped devices"
+msgstr "Dispositivos asignados"
+
msgid "Mapped values"
msgstr "Valores mapeados"
@@ -14340,6 +14385,12 @@ msgstr "No se ha recibido depósito para este acuerdo."
msgid "No depreciation run happens before the cutover. Enter each asset's accumulated depreciation as of the day before the cutover."
msgstr "Ninguna ejecución de Depreciación ocurre antes del corte. Ingrese la Depreciación acumulada de cada activo al día anterior al corte."
+msgid "No devices found"
+msgstr "No se encontraron dispositivos"
+
+msgid "No devices match your search"
+msgstr "Ningún dispositivo coincide con su búsqueda"
+
msgid "No dimension slots configured"
msgstr "No hay espacios de dimensión configurados"
@@ -14475,6 +14526,9 @@ msgstr "Sin artículos"
msgid "No items have inventory activity here yet."
msgstr "Aún no hay actividad de inventario de artículos aquí."
+msgid "No job at this location has an open operation."
+msgstr "Ninguna orden de trabajo en esta ubicación tiene una operación abierta."
+
msgid "No jobs are scheduled at this location yet — release a job to see work-center load."
msgstr "No hay órdenes de trabajo programadas en esta ubicación aún — libera una orden de trabajo para ver la carga del centro de trabajo."
@@ -14568,6 +14622,9 @@ msgstr "No hay líneas abiertas. Añada un servicio para modificar."
msgid "No open memos"
msgstr "Sin memorandos abiertos"
+msgid "No open operations"
+msgstr "Sin operaciones abiertas"
+
msgid "No open orders for this item are available to link."
msgstr "No hay pedidos abiertos disponibles para este artículo."
@@ -14932,6 +14989,9 @@ msgstr "Normal"
msgid "Not a table but a general-ledger balance: cost accumulates as job materials are issued and clears when the job is received to stock."
msgstr "No es una tabla, sino un saldo del mayor general: el costo se acumula cuando se emiten los materiales de la orden de trabajo y se liquida cuando la orden se recibe en existencias."
+msgid "Not calibrated"
+msgstr "No calibrado"
+
msgid "Not certified"
msgstr "No certificado"
@@ -14953,6 +15013,12 @@ msgstr "Datos de unidad insuficientes"
msgid "Not feasible"
msgstr "No es viable"
+msgid "Not job time"
+msgstr "No es tiempo de trabajo"
+
+msgid "Not mapped"
+msgstr "Sin asignar"
+
msgid "Not now"
msgstr "Ahora no"
@@ -15017,6 +15083,9 @@ msgstr "Aún no se ha completado nada en MES"
msgid "Nothing else at this location has stock to pull from."
msgstr "Nada más en esta ubicación tiene stock para extraer."
+msgid "Nothing else ran on {workCenterName} that day."
+msgstr "No se ejecutó nada más en {workCenterName} ese día."
+
msgid "Nothing here matches your search and filters."
msgstr "Nada aquí coincide con tu búsqueda y filtros."
@@ -15074,6 +15143,9 @@ msgstr "Notificar"
msgid "Notify someone"
msgstr "Notificar a alguien"
+msgid "now"
+msgstr "ahora"
+
msgid "Number"
msgstr "Número"
@@ -15117,6 +15189,9 @@ msgstr "Off — manejado fuera de la sincronización"
msgid "Off — released revisions stay editable"
msgstr "Desactivado — las revisiones lanzadas permanecen editables"
+msgid "Offline"
+msgstr "Sin conexión"
+
msgid "Offset Account"
msgstr "Cuenta de compensación"
@@ -16069,6 +16144,9 @@ msgstr "Ruta"
msgid "Pause"
msgstr "Pausar"
+msgid "Paused"
+msgstr "Pausado"
+
msgid "Pay"
msgstr "Pagar"
@@ -17579,6 +17657,9 @@ msgstr "Ramp no devolvió un código de autorización"
msgid "Ramp rejected the authorization"
msgstr "Ramp rechazó la autorización"
+msgid "Ran at the time"
+msgstr "Se ejecutó en ese momento"
+
msgid "Rate"
msgstr "Tipo de cambio"
@@ -18107,6 +18188,9 @@ msgstr "Liberado con problemas: {0}"
msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
msgstr "Liberar el lote de producción libera sus órdenes de trabajo, y cada una debe estar lista para la planta."
+msgid "Reload the page to try again."
+msgstr "Recargue la página para intentar de nuevo."
+
msgid "Remaining"
msgstr "Restante"
@@ -19595,6 +19679,9 @@ msgstr "Buscar clientes y tipos..."
msgid "Search customers or types..."
msgstr "Buscar clientes o tipos..."
+msgid "Search devices"
+msgstr "Buscar dispositivos"
+
msgid "Search employees..."
msgstr "Buscar empleados..."
@@ -19619,6 +19706,9 @@ msgstr "Buscar artículos o contenedores"
msgid "Search Job"
msgstr "Buscar trabajo"
+msgid "Search jobs and operations"
+msgstr "Buscar trabajos y operaciones"
+
msgid "Search jobs or items"
msgstr "Busca Órdenes de trabajo o Artículos"
@@ -20945,6 +21035,9 @@ msgstr "Iniciando…"
msgid "Starts"
msgstr "Comienza"
+msgid "State"
+msgstr "Estado"
+
msgid "State / Province"
msgstr "Estado / Provincia"
@@ -21096,6 +21189,9 @@ msgstr "Detener envío"
msgid "Stop using {0} in this step"
msgstr "Dejar de usar {0} en este paso"
+msgid "Stopped"
+msgstr "Detenido"
+
msgid "Stops new purchase suggestions after this date."
msgstr "Detiene las sugerencias de compra después de esta fecha."
@@ -22187,6 +22283,9 @@ msgstr "La tasa fiscal predeterminada aplicada a las líneas de cotización y or
msgid "The department this one rolls up under for reporting and headcount hierarchies; leave empty for a top-level department."
msgstr "El departamento bajo el cual se agrupa para informes y jerarquías de conteo de encabezados; dejar en blanco para un departamento de nivel superior."
+msgid "The device's site is in {siteTimezone}; Carbon uses {locationTimezone}"
+msgstr "El sitio del dispositivo está en {siteTimezone}; Carbon usa {locationTimezone}"
+
msgid "The early hours, {name}."
msgstr "Las primeras horas, {name}."
@@ -22459,6 +22558,9 @@ msgstr "El plan de muestreo por característica del lote será determinado nueva
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "El monto mínimo que este proveedor cobrará por este proceso, independientemente de la cantidad; las órdenes de trabajo por debajo del volumen de equilibrio aún cuestan como mínimo esto."
+msgid "The machine is still running. Assign this time after it stops."
+msgstr "La máquina sigue en marcha. Asigne este tiempo cuando se detenga."
+
msgid "The machines, cells, and stations your work runs through"
msgstr "Las máquinas, celdas y estaciones por las que pasa tu trabajo"
@@ -24068,6 +24170,9 @@ msgstr "Desasignar regla"
msgid "Unassigned"
msgstr "Sin asignar"
+msgid "Unattributed Time"
+msgstr "Tiempo no atribuido"
+
msgid "Unbalanced"
msgstr "Desequilibrado"
@@ -24843,6 +24948,9 @@ msgstr "Ver apunte"
msgid "View Lists"
msgstr "Ver Listas"
+msgid "View Machine Time"
+msgstr "Ver Tiempo de máquina"
+
msgid "View maintenance dispatch"
msgstr "Ver orden de mantenimiento"
@@ -25022,6 +25130,12 @@ msgstr "Anular este envío hará lo siguiente:"
msgid "Waited"
msgstr "Esperado"
+msgid "Waiting"
+msgstr "Esperando"
+
+msgid "Waiting for the first sync"
+msgstr "Esperando la primera sincronización"
+
msgid "Walk each area with your champion and toggle anything out of scope. Codes read Module.Area.Number (ACC.GL.01 = Accounting, General Ledger, item 1)."
msgstr "Recorre cada área con tu campeón y marca cualquier cosa como fuera del alcance. Los códigos se leen como Módulo.Área.Número (ACC.GL.01 = Contabilidad, Libro mayor, elemento 1)."
@@ -25528,6 +25642,9 @@ msgstr "Qué tipo de solicitud enviar: GET lee algo, POST crea, PUT y PATCH actu
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Qué evento de manufactura inicia el reloj de vida de anaquel — por ejemplo, llenado, sellado o QC final."
+msgid "Which operation was this?"
+msgstr "¿Qué operación fue esta?"
+
msgid "While this dispatch is open, the work center is unavailable to the schedule (until the planned end time, or until the dispatch is completed)."
msgstr "Mientras este envío esté abierto, el centro de trabajo no estará disponible para el cronograma (hasta la hora de finalización planeada, o hasta que se complete el envío)."
diff --git a/packages/locale/locales/es/mes.po b/packages/locale/locales/es/mes.po
index a56b2174fa..38b905477b 100644
--- a/packages/locale/locales/es/mes.po
+++ b/packages/locale/locales/es/mes.po
@@ -820,6 +820,9 @@ msgstr "Sigo trabajando"
msgid "Ideas, suggestions or problems?"
msgstr "¿Ideas, sugerencias o problemas?"
+msgid "Idle"
+msgstr "Parado"
+
msgid "Idle for"
msgstr "Inactivo durante"
@@ -965,6 +968,9 @@ msgstr "Vista de lista"
msgid "Load list"
msgstr "Cargar lista"
+msgid "Loaded: {loadedLabel}"
+msgstr "Cargado: {loadedLabel}"
+
msgid "Loading item details..."
msgstr "Cargando detalles del artículo..."
@@ -1286,6 +1292,9 @@ msgstr "Requiere OEM"
msgid "of {0}"
msgstr "de {0}"
+msgid "Offline"
+msgstr "Sin conexión"
+
msgid "Oldest first"
msgstr "Más antiguo primero"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 1de164c3df..2a2a933cbf 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -542,6 +542,9 @@ msgstr "{load} en attente"
msgid "{locationName} (the lease's)"
msgstr "{locationName} (de la location)"
+msgid "{mappedCount} of {totalCount} mapped"
+msgstr "{mappedCount} sur {totalCount} associés"
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB limite"
@@ -616,6 +619,9 @@ msgstr "{passing} sur {total} actifs"
msgid "{percent} picked"
msgstr "{percent} prélevé"
+msgid "{position} of {total}"
+msgstr "{position} sur {total}"
+
msgid "{purgeRowCount, plural, one {Permanently delete # row?} other {Permanently delete # rows?}}"
msgstr "{purgeRowCount, plural, one {Supprimer définitivement # ligne ?} other {Supprimer définitivement # lignes ?}}"
@@ -640,6 +646,9 @@ msgstr "{sectionLineCount} lignes"
msgid "{selectedCount} selected"
msgstr "{selectedCount} sélectionnés"
+msgid "{state} · synced {syncedAgo}"
+msgstr "{state} · synchronisé {syncedAgo}"
+
msgid "{termMonths, plural, one {# month} other {# months}}"
msgstr "{termMonths, plural, one {# mois} other {# mois}}"
@@ -2668,6 +2677,9 @@ msgstr "Annuel. Commence à partir du taux d'emprunt supplémentaire de la Soci
msgid "Another cost center this one rolls up into, letting you nest a sub-department under its parent for hierarchical cost reporting."
msgstr "Un autre centre de coûts auquel celui-ci se rapporte, vous permettant d'imbriquer un sous-centre de coûts sous son supérieur pour des rapports de coûts hiérarchiques."
+msgid "Another job or operation"
+msgstr "Autre ordre ou opération"
+
msgid "Another spend integration is already active"
msgstr "Une autre intégration de dépenses est déjà active"
@@ -3540,6 +3552,9 @@ msgstr "Actifs"
msgid "Assets, liabilities and equity as of a date"
msgstr "Actifs, passifs et capitaux propres à une date"
+msgid "Assign machine run time that no loaded operation claimed to the right job, or dismiss it."
+msgstr "Attribuer au bon ordre de fabrication le temps machine qu'aucune opération chargée n'a revendiqué, ou le rejeter."
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Attribuer des imprimantes aux sites. L'expédition, la réception et les postes de travail héritent du paramètre par défaut du site sauf s'ils sont remplacés."
@@ -5425,6 +5440,9 @@ msgstr "Connecter un problème Jira"
msgid "Connect Linear issue"
msgstr "Connecter un problème Linear"
+msgid "Connect machine monitoring devices to work centers so machine time is recorded against the operation that is loaded."
+msgstr "Connectez les dispositifs de surveillance machine aux postes de travail pour que le temps machine soit enregistré par rapport à l'opération chargée."
+
msgid "Connect Slack under Settings → Integrations first."
msgstr "Connectez d'abord Slack sous Paramètres → Intégrations."
@@ -6001,6 +6019,15 @@ msgstr "Impossible de créer le PDF. Réessayez."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "Impossible de dissoudre {0}: {1} — production déjà enregistrée"
+msgid "Could not list the provider's devices. Mapped devices are still shown."
+msgstr "Impossible de lister les appareils du fournisseur. Les appareils associés restent affichés."
+
+msgid "Could not load operations"
+msgstr "Impossible de charger les opérations"
+
+msgid "Could not load what ran on {workCenterName}."
+msgstr "Impossible de charger ce qui s'est exécuté sur {workCenterName}."
+
msgid "Could not predict lead time"
msgstr "Impossible de prédire le délai d'approvisionnement"
@@ -7660,6 +7687,9 @@ msgstr "Détecté par le planificateur de mouvement"
msgid "Developer"
msgstr "Développeur"
+msgid "Devices"
+msgstr "Dispositifs"
+
msgid "Difference"
msgstr "Différence"
@@ -7928,6 +7958,9 @@ msgstr "Double-cliquez pour ouvrir ce sous-ensemble"
msgid "Double-click to play this step"
msgstr "Double-cliquez pour jouer cette étape"
+msgid "Down"
+msgstr "En panne"
+
msgid "Download"
msgstr "Télécharger"
@@ -11028,6 +11061,9 @@ msgstr "Fournisseur d'identité"
msgid "Identity provider (IdP)"
msgstr "Fournisseur d'identité (IdP)"
+msgid "Idle"
+msgstr "Disponible"
+
msgid "IdP Metadata URL"
msgstr "URL des métadonnées IdP"
@@ -11936,6 +11972,9 @@ msgstr "Tâche en cours"
msgid "Job Location"
msgstr "Localisation du travail"
+msgid "Job locked"
+msgstr "Ordre verrouillé"
+
msgid "Job make method"
msgstr "Méthode de fabrication du travail"
@@ -12758,6 +12797,9 @@ msgstr "Coûts Machine"
msgid "Machine Hours"
msgstr "Heures de machine"
+msgid "Machine monitoring"
+msgstr "Surveillance machine"
+
msgid "Machine rate"
msgstr "Taux machine"
@@ -12969,6 +13011,9 @@ msgstr "Mappez votre plan comptable au plan comptable du fournisseur. Les compte
msgid "Map your current process, systems, and data"
msgstr "Cartographiez votre processus actuel, vos systèmes et vos données"
+msgid "Mapped devices"
+msgstr "Appareils associés"
+
msgid "Mapped values"
msgstr "Valeurs mappées"
@@ -14340,6 +14385,12 @@ msgstr "Aucun acompte n'a été reçu pour cet accord."
msgid "No depreciation run happens before the cutover. Enter each asset's accumulated depreciation as of the day before the cutover."
msgstr "Aucune exécution d'amortissement ne se produit avant le cutover. Entrez l'amortissement cumulé de chaque actif au jour avant le cutover."
+msgid "No devices found"
+msgstr "Aucun dispositif trouvé"
+
+msgid "No devices match your search"
+msgstr "Aucun appareil ne correspond à votre recherche"
+
msgid "No dimension slots configured"
msgstr "Aucun emplacement d'axe analytique configuré"
@@ -14475,6 +14526,9 @@ msgstr "Aucun article"
msgid "No items have inventory activity here yet."
msgstr "Aucun article n'a encore d'activité d'inventaire ici."
+msgid "No job at this location has an open operation."
+msgstr "Aucun ordre de fabrication sur ce site n'a d'opération ouverte."
+
msgid "No jobs are scheduled at this location yet — release a job to see work-center load."
msgstr "Aucun ordre de fabrication n'est programmé sur ce site pour l'instant — lancez un ordre de fabrication pour voir la charge du poste de travail."
@@ -14568,6 +14622,9 @@ msgstr "Aucune ligne ouverte. Ajoutez un service pour modifier."
msgid "No open memos"
msgstr "Aucun mémo ouvert"
+msgid "No open operations"
+msgstr "Aucune opération ouverte"
+
msgid "No open orders for this item are available to link."
msgstr "Aucune commande ouverte pour cet article n'est disponible pour la liaison."
@@ -14932,6 +14989,9 @@ msgstr "Normal"
msgid "Not a table but a general-ledger balance: cost accumulates as job materials are issued and clears when the job is received to stock."
msgstr "Pas une table mais un solde du grand livre : le coût s'accumule à mesure que les composants d'OF sont émis et s'annule lorsque l'OF est reçu en stock."
+msgid "Not calibrated"
+msgstr "Non étalonné"
+
msgid "Not certified"
msgstr "Non certifié"
@@ -14953,6 +15013,12 @@ msgstr "Pas assez de données sur l'unité"
msgid "Not feasible"
msgstr "Non réalisable"
+msgid "Not job time"
+msgstr "Pas du temps de production"
+
+msgid "Not mapped"
+msgstr "Non associé"
+
msgid "Not now"
msgstr "Pas maintenant"
@@ -15017,6 +15083,9 @@ msgstr "Rien n'a encore été terminé dans MES"
msgid "Nothing else at this location has stock to pull from."
msgstr "Aucun autre article à cet endroit n'a de stock à prélever."
+msgid "Nothing else ran on {workCenterName} that day."
+msgstr "Rien d'autre n'a tourné sur {workCenterName} ce jour-là."
+
msgid "Nothing here matches your search and filters."
msgstr "Rien ici ne correspond à votre recherche et vos filtres."
@@ -15074,6 +15143,9 @@ msgstr "Notifier"
msgid "Notify someone"
msgstr "Notifier quelqu'un"
+msgid "now"
+msgstr "maintenant"
+
msgid "Number"
msgstr "Nombre"
@@ -15117,6 +15189,9 @@ msgstr "Off — géré en dehors de la synchronisation"
msgid "Off — released revisions stay editable"
msgstr "Désactivé — les révisions publiées restent modifiables"
+msgid "Offline"
+msgstr "Hors ligne"
+
msgid "Offset Account"
msgstr "Compte de contrepartie"
@@ -16069,6 +16144,9 @@ msgstr "Chemin"
msgid "Pause"
msgstr "Mettre en pause"
+msgid "Paused"
+msgstr "Suspendu"
+
msgid "Pay"
msgstr "Payer"
@@ -17579,6 +17657,9 @@ msgstr "Ramp n’a pas renvoyé de code d’autorisation"
msgid "Ramp rejected the authorization"
msgstr "Ramp a rejeté l’autorisation"
+msgid "Ran at the time"
+msgstr "A tourné à ce moment"
+
msgid "Rate"
msgstr "Taux"
@@ -18107,6 +18188,9 @@ msgstr "Lancé avec des problèmes : {0}"
msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
msgstr "Lancer le lot de production lance ses ordres de fabrication, et chacun doit être prêt pour l'atelier."
+msgid "Reload the page to try again."
+msgstr "Rechargez la page pour réessayer."
+
msgid "Remaining"
msgstr "Restant"
@@ -19595,6 +19679,9 @@ msgstr "Rechercher les clients et les types..."
msgid "Search customers or types..."
msgstr "Rechercher des clients ou des types..."
+msgid "Search devices"
+msgstr "Rechercher des appareils"
+
msgid "Search employees..."
msgstr "Rechercher des employés..."
@@ -19619,6 +19706,9 @@ msgstr "Rechercher des articles ou des casiers"
msgid "Search Job"
msgstr "Rechercher un travail"
+msgid "Search jobs and operations"
+msgstr "Rechercher des ordres et des opérations"
+
msgid "Search jobs or items"
msgstr "Rechercher des ordres de fabrication ou des articles"
@@ -20945,6 +21035,9 @@ msgstr "Démarrage…"
msgid "Starts"
msgstr "Commence"
+msgid "State"
+msgstr "État"
+
msgid "State / Province"
msgstr "État / Province"
@@ -21096,6 +21189,9 @@ msgstr "Arrêter l'expédition"
msgid "Stop using {0} in this step"
msgstr "Arrêter d'utiliser {0} dans cette étape"
+msgid "Stopped"
+msgstr "Arrêté"
+
msgid "Stops new purchase suggestions after this date."
msgstr "Arrête les nouvelles suggestions d'achat après cette date."
@@ -22187,6 +22283,9 @@ msgstr "Le taux de taxe par défaut appliqué aux lignes de devis et de commande
msgid "The department this one rolls up under for reporting and headcount hierarchies; leave empty for a top-level department."
msgstr "Le département sous lequel celui-ci se cumule pour la déclaration et les hiérarchies de dénombrement; laisser vide pour un département au niveau supérieur."
+msgid "The device's site is in {siteTimezone}; Carbon uses {locationTimezone}"
+msgstr "Le site de l'appareil est en {siteTimezone} ; Carbon utilise {locationTimezone}"
+
msgid "The early hours, {name}."
msgstr "Les premières heures, {name}."
@@ -22459,6 +22558,9 @@ msgstr "Le plan d'échantillonnage par caractéristique du lot sera redétermin
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "Le montant minimum que ce fournisseur facturera pour ce procédé, indépendamment de la quantité; les ordres de fabrication en dessous du volume de rentabilité coûtent au moins ce montant."
+msgid "The machine is still running. Assign this time after it stops."
+msgstr "La machine tourne encore. Attribuez ce temps après son arrêt."
+
msgid "The machines, cells, and stations your work runs through"
msgstr "Les machines, cellules et postes par lesquels votre travail passe"
@@ -24068,6 +24170,9 @@ msgstr "Retirer la règle"
msgid "Unassigned"
msgstr "Non assigné"
+msgid "Unattributed Time"
+msgstr "Temps non attribué"
+
msgid "Unbalanced"
msgstr "Déséquilibré"
@@ -24843,6 +24948,9 @@ msgstr "Afficher la ligne d'écriture"
msgid "View Lists"
msgstr "Afficher les listes"
+msgid "View Machine Time"
+msgstr "Afficher le temps machine"
+
msgid "View maintenance dispatch"
msgstr "Afficher l'intervention de maintenance"
@@ -25022,6 +25130,12 @@ msgstr "L'invalidation de cette expédition :"
msgid "Waited"
msgstr "En attente"
+msgid "Waiting"
+msgstr "En attente"
+
+msgid "Waiting for the first sync"
+msgstr "En attente de la première synchronisation"
+
msgid "Walk each area with your champion and toggle anything out of scope. Codes read Module.Area.Number (ACC.GL.01 = Accounting, General Ledger, item 1)."
msgstr "Parcourez chaque domaine avec votre responsable et désactivez tout ce qui est hors du champ. Les codes se lisent Module.Domaine.Numéro (ACC.GL.01 = Comptabilité, Grand livre, article 1)."
@@ -25528,6 +25642,9 @@ msgstr "Quel type de requête envoyer : GET lit quelque chose, POST crée, PUT e
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Quel événement de production démarre l'horloge de durée de vie — par exemple, remplissage, scellage, ou QC final."
+msgid "Which operation was this?"
+msgstr "De quelle opération s'agissait-il ?"
+
msgid "While this dispatch is open, the work center is unavailable to the schedule (until the planned end time, or until the dispatch is completed)."
msgstr "Tant que cette intervention est ouverte, le poste de travail n'est pas disponible pour la planification (jusqu'à l'heure de fin prévue, ou jusqu'à ce que l'intervention soit terminée)."
diff --git a/packages/locale/locales/fr/mes.po b/packages/locale/locales/fr/mes.po
index de000f7455..55ee663efd 100644
--- a/packages/locale/locales/fr/mes.po
+++ b/packages/locale/locales/fr/mes.po
@@ -820,6 +820,9 @@ msgstr "Je travaille encore"
msgid "Ideas, suggestions or problems?"
msgstr "Des idées, suggestions ou problèmes ?"
+msgid "Idle"
+msgstr "Disponible"
+
msgid "Idle for"
msgstr "Inactif depuis"
@@ -965,6 +968,9 @@ msgstr "Vue liste"
msgid "Load list"
msgstr "Charger la liste"
+msgid "Loaded: {loadedLabel}"
+msgstr "Chargée : {loadedLabel}"
+
msgid "Loading item details..."
msgstr "Chargement des détails de l'article..."
@@ -1286,6 +1292,9 @@ msgstr "Intervention OEM requise"
msgid "of {0}"
msgstr "de {0}"
+msgid "Offline"
+msgstr "Hors ligne"
+
msgid "Oldest first"
msgstr "Le plus ancien en premier"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index c523361756..6f16c096b5 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -542,6 +542,9 @@ msgstr "{load} कतार में"
msgid "{locationName} (the lease's)"
msgstr "{locationName} (पट्टे का)"
+msgid "{mappedCount} of {totalCount} mapped"
+msgstr "{totalCount} में से {mappedCount} मैप किए गए"
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB सीमा"
@@ -616,6 +619,9 @@ msgstr "{total} संपत्तियों में से {passing}"
msgid "{percent} picked"
msgstr "{percent} पिक किया गया"
+msgid "{position} of {total}"
+msgstr "{position} में से {total}"
+
msgid "{purgeRowCount, plural, one {Permanently delete # row?} other {Permanently delete # rows?}}"
msgstr "{purgeRowCount, plural, one {# पंक्ति को स्थायी रूप से हटाएँ?} other {# पंक्तियों को स्थायी रूप से हटाएँ?}}"
@@ -640,6 +646,9 @@ msgstr "{sectionLineCount} पंक्तियाँ"
msgid "{selectedCount} selected"
msgstr "{selectedCount} चयनित"
+msgid "{state} · synced {syncedAgo}"
+msgstr "{state} · {syncedAgo} सिंक हुआ"
+
msgid "{termMonths, plural, one {# month} other {# months}}"
msgstr "{termMonths, plural, one {# महीना} other {# महीने}}"
@@ -2668,6 +2677,9 @@ msgstr "वार्षिक। कंपनी की वृद्धिशी
msgid "Another cost center this one rolls up into, letting you nest a sub-department under its parent for hierarchical cost reporting."
msgstr "एक अन्य लागत केंद्र जिसमें यह रोल हो जाता है, आपको एक उप-लागत केंद्र को इसके मूल के अंतर्गत घोंसले के लिए सक्षम करता है जो पदानुक्रमित लागत रिपोर्टिंग के लिए।"
+msgid "Another job or operation"
+msgstr "कोई अन्य जॉब या ऑपरेशन"
+
msgid "Another spend integration is already active"
msgstr "एक अन्य व्यय एकीकरण पहले से सक्रिय है"
@@ -3540,6 +3552,9 @@ msgstr "संपत्तियां"
msgid "Assets, liabilities and equity as of a date"
msgstr "एक तारीख तक संपत्ति, देनदारियां और इक्विटी"
+msgid "Assign machine run time that no loaded operation claimed to the right job, or dismiss it."
+msgstr "असाइन करें मशीन रन समय जो किसी लोड किए गए ऑपरेशन ने क्लेम नहीं किया, सही जॉब को, या इसे खारिज करें।"
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "प्रिंटर को स्थानों को असाइन करें। शिपिंग, रिसीविंग और वर्क सेंटर स्थान डिफ़ॉल्ट को विरासत में लेते हैं जब तक कि ओवरराइड न किया जाए।"
@@ -5425,6 +5440,9 @@ msgstr "Jira समस्या से कनेक्ट करें"
msgid "Connect Linear issue"
msgstr "Linear समस्या से कनेक्ट करें"
+msgid "Connect machine monitoring devices to work centers so machine time is recorded against the operation that is loaded."
+msgstr "मशीन मॉनिटरिंग डिवाइस को वर्क सेंटर से कनेक्ट करें ताकि मशीन समय लोड किए गए ऑपरेशन के विरुद्ध रिकॉर्ड किया जाए।"
+
msgid "Connect Slack under Settings → Integrations first."
msgstr "पहले सेटिंग्स → एकीकरण के तहत Slack कनेक्ट करें।"
@@ -6001,6 +6019,15 @@ msgstr "PDF नहीं बना सके। फिर से कोशिश
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "{0} को भंग नहीं कर सके: {1} — उत्पादन पहले से दर्ज है"
+msgid "Could not list the provider's devices. Mapped devices are still shown."
+msgstr "प्रदाता के डिवाइस सूचीबद्ध नहीं किए जा सके। मैप किए गए डिवाइस अब भी दिखाए जा रहे हैं।"
+
+msgid "Could not load operations"
+msgstr "ऑपरेशन लोड नहीं कर सके"
+
+msgid "Could not load what ran on {workCenterName}."
+msgstr "{workCenterName} पर चलने वाले डेटा को लोड नहीं कर सके।"
+
msgid "Could not predict lead time"
msgstr "लीड टाइम की भविष्यवाणी नहीं कर सके"
@@ -7660,6 +7687,9 @@ msgstr "गति योजनाकार द्वारा पहचाना
msgid "Developer"
msgstr "डेवलपर"
+msgid "Devices"
+msgstr "डिवाइस"
+
msgid "Difference"
msgstr "अंतर"
@@ -7928,6 +7958,9 @@ msgstr "इस उप-विधानसभा को खोलने के ल
msgid "Double-click to play this step"
msgstr "इस चरण को चलाने के लिए डबल-क्लिक करें"
+msgid "Down"
+msgstr "डाउन"
+
msgid "Download"
msgstr "डाउनलोड करें"
@@ -11028,6 +11061,9 @@ msgstr "आइडेंटिटी प्रदाता"
msgid "Identity provider (IdP)"
msgstr "आइडेंटिटी प्रदाता (IdP)"
+msgid "Idle"
+msgstr "निष्क्रिय"
+
msgid "IdP Metadata URL"
msgstr "IdP मेटाडेटा URL"
@@ -11936,6 +11972,9 @@ msgstr "प्रगति में जॉब"
msgid "Job Location"
msgstr "जॉब स्थान"
+msgid "Job locked"
+msgstr "जॉब लॉक है"
+
msgid "Job make method"
msgstr "जॉब निर्माण विधि"
@@ -12758,6 +12797,9 @@ msgstr "मशीन लागत"
msgid "Machine Hours"
msgstr "मशीन घंटे"
+msgid "Machine monitoring"
+msgstr "मशीन मॉनिटरिंग"
+
msgid "Machine rate"
msgstr "मशीन दर"
@@ -12969,6 +13011,9 @@ msgstr "अपने खातों का चार्ट को प्रद
msgid "Map your current process, systems, and data"
msgstr "अपनी वर्तमान प्रक्रिया, सिस्टम और डेटा को मैप करें"
+msgid "Mapped devices"
+msgstr "मैप किए गए डिवाइस"
+
msgid "Mapped values"
msgstr "मैप किए गए मान"
@@ -14340,6 +14385,12 @@ msgstr "इस समझौते के लिए कोई जमा राश
msgid "No depreciation run happens before the cutover. Enter each asset's accumulated depreciation as of the day before the cutover."
msgstr "संक्रमण से पहले कोई मूल्यह्रास चलाया नहीं जाता। संक्रमण से पहले के दिन तक प्रत्येक परिसंपत्ति का संचित मूल्यह्रास दर्ज करें।"
+msgid "No devices found"
+msgstr "कोई डिवाइस नहीं मिला"
+
+msgid "No devices match your search"
+msgstr "आपकी खोज से कोई डिवाइस मेल नहीं खाता"
+
msgid "No dimension slots configured"
msgstr "कोई आयाम स्लॉट कॉन्फ़िगर नहीं किया गया"
@@ -14475,6 +14526,9 @@ msgstr "कोई आइटम नहीं"
msgid "No items have inventory activity here yet."
msgstr "अभी तक यहाँ कोई आइटम इन्वेंटरी गतिविधि नहीं है।"
+msgid "No job at this location has an open operation."
+msgstr "इस स्थान पर कोई जॉब खुला ऑपरेशन नहीं है।"
+
msgid "No jobs are scheduled at this location yet — release a job to see work-center load."
msgstr "इस स्थान पर अभी तक कोई जॉब शेड्यूल नहीं किया गया है — वर्क-सेंटर लोड देखने के लिए एक जॉब जारी करें।"
@@ -14568,6 +14622,9 @@ msgstr "कोई खुली पंक्ति नहीं। संशो
msgid "No open memos"
msgstr "कोई खुला ज्ञापन नहीं"
+msgid "No open operations"
+msgstr "कोई खुला ऑपरेशन नहीं"
+
msgid "No open orders for this item are available to link."
msgstr "इस आइटम के लिए लिंक करने के लिए कोई खुले ऑर्डर उपलब्ध नहीं हैं।"
@@ -14932,6 +14989,9 @@ msgstr "सामान्य"
msgid "Not a table but a general-ledger balance: cost accumulates as job materials are issued and clears when the job is received to stock."
msgstr "एक तालिका नहीं बल्कि एक सामान्य खाता बही शेष: लागत जमा होती है जब जॉब सामग्री जारी की जाती है और साफ़ होती है जब जॉब स्टॉक में प्राप्त होता है।"
+msgid "Not calibrated"
+msgstr "कैलिब्रेट नहीं किया गया"
+
msgid "Not certified"
msgstr "प्रमाणित नहीं"
@@ -14953,6 +15013,12 @@ msgstr "पर्याप्त यूनिट डेटा नहीं"
msgid "Not feasible"
msgstr "संभव नहीं"
+msgid "Not job time"
+msgstr "जॉब का समय नहीं"
+
+msgid "Not mapped"
+msgstr "मैप नहीं किया गया"
+
msgid "Not now"
msgstr "अभी नहीं"
@@ -15017,6 +15083,9 @@ msgstr "MES में अभी तक कुछ भी पूर्ण नह
msgid "Nothing else at this location has stock to pull from."
msgstr "इस स्थान पर कोई अन्य स्टॉक नहीं है जहां से खींचा जा सकता है।"
+msgid "Nothing else ran on {workCenterName} that day."
+msgstr "उस दिन {workCenterName} पर और कुछ नहीं चला।"
+
msgid "Nothing here matches your search and filters."
msgstr "यहां कुछ भी आपकी खोज और फ़िल्टर से मेल नहीं खाता।"
@@ -15074,6 +15143,9 @@ msgstr "सूचित करें"
msgid "Notify someone"
msgstr "किसी को सूचित करें"
+msgid "now"
+msgstr "अभी"
+
msgid "Number"
msgstr "संख्या"
@@ -15117,6 +15189,9 @@ msgstr "बंद — सिंक के बाहर संभाला गय
msgid "Off — released revisions stay editable"
msgstr "बंद — जारी किए गए रिवीजन संपादन योग्य रहते हैं"
+msgid "Offline"
+msgstr "ऑफलाइन"
+
msgid "Offset Account"
msgstr "ऑफसेट खाता"
@@ -16069,6 +16144,9 @@ msgstr "पथ"
msgid "Pause"
msgstr "रोकें"
+msgid "Paused"
+msgstr "रुका हुआ"
+
msgid "Pay"
msgstr "भुगतान करें"
@@ -17579,6 +17657,9 @@ msgstr "Ramp ने प्राधिकरण कोड नहीं लौट
msgid "Ramp rejected the authorization"
msgstr "Ramp ने प्राधिकरण अस्वीकार कर दिया"
+msgid "Ran at the time"
+msgstr "उस समय चल रहा था"
+
msgid "Rate"
msgstr "दर"
@@ -18107,6 +18188,9 @@ msgstr "समस्याओं के साथ जारी: {0}"
msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
msgstr "बैच जारी करने से इसकी जॉब्स जारी हो जाती हैं, और प्रत्येक को शॉप फ्लोर के लिए तैयार होना चाहिए।"
+msgid "Reload the page to try again."
+msgstr "फिर से कोशिश करने के लिए पृष्ठ पुनः लोड करें।"
+
msgid "Remaining"
msgstr "शेष"
@@ -19595,6 +19679,9 @@ msgstr "ग्राहकों और प्रकारों को खो
msgid "Search customers or types..."
msgstr "ग्राहकों या प्रकारों को खोजें..."
+msgid "Search devices"
+msgstr "डिवाइस खोजें"
+
msgid "Search employees..."
msgstr "कर्मचारियों को खोजें..."
@@ -19619,6 +19706,9 @@ msgstr "आइटम या बिन खोजें"
msgid "Search Job"
msgstr "Job खोजें"
+msgid "Search jobs and operations"
+msgstr "जॉब और ऑपरेशन खोजें"
+
msgid "Search jobs or items"
msgstr "जॉब या आइटम खोजें"
@@ -20945,6 +21035,9 @@ msgstr "शुरू हो रहा है…"
msgid "Starts"
msgstr "शुरू होता है"
+msgid "State"
+msgstr "स्थिति"
+
msgid "State / Province"
msgstr "राज्य / प्रांत"
@@ -21096,6 +21189,9 @@ msgstr "शिपिंग बंद करें"
msgid "Stop using {0} in this step"
msgstr "इस चरण में {0} का उपयोग बंद करें"
+msgid "Stopped"
+msgstr "रुका हुआ"
+
msgid "Stops new purchase suggestions after this date."
msgstr "इस तारीख के बाद नई खरीद सुझाव बंद करता है।"
@@ -22187,6 +22283,9 @@ msgstr "डिफ़ॉल्ट कर दर इस ग्राहक की
msgid "The department this one rolls up under for reporting and headcount hierarchies; leave empty for a top-level department."
msgstr "विभाग जिसके अंतर्गत यह रिपोर्टिंग और हेडकाउंट पदानुक्रमों के लिए रोल अप करता है; शीर्ष स्तरीय विभाग के लिए खाली छोड़ें।"
+msgid "The device's site is in {siteTimezone}; Carbon uses {locationTimezone}"
+msgstr "डिवाइस की साइट {siteTimezone} में है; Carbon {locationTimezone} का उपयोग करता है"
+
msgid "The early hours, {name}."
msgstr "सुबह के शुरुआती घंटे, {name}।"
@@ -22459,6 +22558,9 @@ msgstr "लॉट की प्रति-विशेषता नमूना
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "यह न्यूनतम राशि जो यह आपूर्तिकर्ता इस प्रक्रिया के लिए चार्ज करेगा, मात्रा की परवाह किए बिना; ब्रेकइवन वॉल्यूम के नीचे जॉब की लागत कम से कम यह राशि ही होगी।"
+msgid "The machine is still running. Assign this time after it stops."
+msgstr "मशीन अभी भी चल रही है। रुकने के बाद यह समय असाइन करें।"
+
msgid "The machines, cells, and stations your work runs through"
msgstr "वे मशीनें, सेल और स्टेशन जिनके माध्यम से आपका काम चलता है"
@@ -24068,6 +24170,9 @@ msgstr "नियम को अनअसाइन करें"
msgid "Unassigned"
msgstr "अनुत्तरित"
+msgid "Unattributed Time"
+msgstr "अनिर्दिष्ट समय"
+
msgid "Unbalanced"
msgstr "असंतुलित"
@@ -24843,6 +24948,9 @@ msgstr "जर्नल प्रविष्टि देखें"
msgid "View Lists"
msgstr "सूचियाँ देखें"
+msgid "View Machine Time"
+msgstr "मशीन समय देखें"
+
msgid "View maintenance dispatch"
msgstr "रखरखाव कार्य देखें"
@@ -25022,6 +25130,12 @@ msgstr "इस शिपमेंट को रद्द करने से:"
msgid "Waited"
msgstr "प्रतीक्षा की"
+msgid "Waiting"
+msgstr "प्रतीक्षा में"
+
+msgid "Waiting for the first sync"
+msgstr "पहले सिंक की प्रतीक्षा है"
+
msgid "Walk each area with your champion and toggle anything out of scope. Codes read Module.Area.Number (ACC.GL.01 = Accounting, General Ledger, item 1)."
msgstr "अपने चैंपियन के साथ प्रत्येक क्षेत्र पर चलें और स्कोप से बाहर कुछ भी टॉगल करें। कोड मॉड्यूल.क्षेत्र.संख्या पढ़ता है (ACC.GL.01 = लेखांकन, सामान्य खाता बही, आइटम 1)।"
@@ -25528,6 +25642,9 @@ msgstr "किस प्रकार का अनुरोध भेजना
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "कौन सी विनिर्माण घटना शेल्फ-जीवन घड़ी शुरू करती है — उदाहरण के लिए, भरना, सील करना, या अंतिम क्यूसी।"
+msgid "Which operation was this?"
+msgstr "यह कौन-सा ऑपरेशन था?"
+
msgid "While this dispatch is open, the work center is unavailable to the schedule (until the planned end time, or until the dispatch is completed)."
msgstr "जबकि यह रखरखाव कार्य खुला है, वर्क सेंटर शेड्यूल के लिए अनुपलब्ध है (योजनाबद्ध समाप्ति समय तक, या जब तक रखरखाव कार्य पूर्ण नहीं हो जाता)।"
diff --git a/packages/locale/locales/hi/mes.po b/packages/locale/locales/hi/mes.po
index 160a1a0469..a186ff5efa 100644
--- a/packages/locale/locales/hi/mes.po
+++ b/packages/locale/locales/hi/mes.po
@@ -820,6 +820,9 @@ msgstr "मैं अभी भी काम कर रहा हूँ"
msgid "Ideas, suggestions or problems?"
msgstr "विचार, सुझाव या समस्याएं?"
+msgid "Idle"
+msgstr "निष्क्रिय"
+
msgid "Idle for"
msgstr "के लिए निष्क्रिय"
@@ -965,6 +968,9 @@ msgstr "सूची दृश्य"
msgid "Load list"
msgstr "सूची लोड करें"
+msgid "Loaded: {loadedLabel}"
+msgstr "लोड किया गया: {loadedLabel}"
+
msgid "Loading item details..."
msgstr "आइटम विवरण लोड हो रहे हैं..."
@@ -1286,6 +1292,9 @@ msgstr "OEM आवश्यक"
msgid "of {0}"
msgstr "का {0}"
+msgid "Offline"
+msgstr "ऑफलाइन"
+
msgid "Oldest first"
msgstr "सबसे पुराना पहले"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 0aa5df15a2..3717eddbe2 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -542,6 +542,9 @@ msgstr "{load} in coda"
msgid "{locationName} (the lease's)"
msgstr "{locationName} (del leasing)"
+msgid "{mappedCount} of {totalCount} mapped"
+msgstr "{mappedCount} di {totalCount} associati"
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB limite"
@@ -616,6 +619,9 @@ msgstr "{passing} di {total} beni"
msgid "{percent} picked"
msgstr "{percent} prelevato"
+msgid "{position} of {total}"
+msgstr "{position} di {total}"
+
msgid "{purgeRowCount, plural, one {Permanently delete # row?} other {Permanently delete # rows?}}"
msgstr "{purgeRowCount, plural, one {Eliminare definitivamente # riga?} other {Eliminare definitivamente # righe?}}"
@@ -640,6 +646,9 @@ msgstr "{sectionLineCount} righe"
msgid "{selectedCount} selected"
msgstr "{selectedCount} selezionati"
+msgid "{state} · synced {syncedAgo}"
+msgstr "{state} · sincronizzato {syncedAgo}"
+
msgid "{termMonths, plural, one {# month} other {# months}}"
msgstr "{termMonths, plural, one {# mese} other {# mesi}}"
@@ -2668,6 +2677,9 @@ msgstr "Annuale. Inizia dal tasso di prestito incrementale dell'azienda"
msgid "Another cost center this one rolls up into, letting you nest a sub-department under its parent for hierarchical cost reporting."
msgstr "Un altro centro di costo in cui questa aggregazione, permettendoti di annidare un sottocenter di costo sotto il suo padre per il reporting del costo gerarchico."
+msgid "Another job or operation"
+msgstr "Altro lavoro o operazione"
+
msgid "Another spend integration is already active"
msgstr "Un'altra integrazione di spesa è già attiva"
@@ -3540,6 +3552,9 @@ msgstr "Cespiti"
msgid "Assets, liabilities and equity as of a date"
msgstr "Attività, passività e patrimonio netto a una data"
+msgid "Assign machine run time that no loaded operation claimed to the right job, or dismiss it."
+msgstr "Assegna il tempo macchina che nessuna operazione caricata ha rivendicato all'ordine di produzione corretto, oppure scartalo."
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Assegna stampanti alle posizioni. Spedizione, ricezione e centri di lavoro ereditano l'impostazione predefinita della posizione se non sovrascritti."
@@ -5425,6 +5440,9 @@ msgstr "Connetti problema Jira"
msgid "Connect Linear issue"
msgstr "Connetti problema Linear"
+msgid "Connect machine monitoring devices to work centers so machine time is recorded against the operation that is loaded."
+msgstr "Collega i dispositivi di monitoraggio delle macchine ai centri di lavoro in modo che il tempo macchina sia registrato rispetto all'operazione caricata."
+
msgid "Connect Slack under Settings → Integrations first."
msgstr "Connetti Slack in Impostazioni → Integrazioni prima."
@@ -6001,6 +6019,15 @@ msgstr "Impossibile creare il PDF. Riprova."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "Impossibile dissolvere {0}: {1} — produzione già registrata"
+msgid "Could not list the provider's devices. Mapped devices are still shown."
+msgstr "Impossibile elencare i dispositivi del fornitore. I dispositivi associati sono ancora visibili."
+
+msgid "Could not load operations"
+msgstr "Impossibile caricare le operazioni"
+
+msgid "Could not load what ran on {workCenterName}."
+msgstr "Impossibile caricare ciò che è stato eseguito su {workCenterName}."
+
msgid "Could not predict lead time"
msgstr "Impossibile prevedere il lead time"
@@ -7660,6 +7687,9 @@ msgstr "Rilevato dal pianificatore di movimento"
msgid "Developer"
msgstr "Sviluppatore"
+msgid "Devices"
+msgstr "Dispositivi"
+
msgid "Difference"
msgstr "Differenza"
@@ -7928,6 +7958,9 @@ msgstr "Fai doppio clic per aprire questo sottoassembly"
msgid "Double-click to play this step"
msgstr "Fai doppio clic per riprodurre questo passo"
+msgid "Down"
+msgstr "Fermo"
+
msgid "Download"
msgstr "Scarica"
@@ -11028,6 +11061,9 @@ msgstr "Provider di Identità"
msgid "Identity provider (IdP)"
msgstr "Provider di identità (IdP)"
+msgid "Idle"
+msgstr "Inattivo"
+
msgid "IdP Metadata URL"
msgstr "URL Metadati IdP"
@@ -11936,6 +11972,9 @@ msgstr "Lavoro in corso"
msgid "Job Location"
msgstr "Ubicazione Lavoro"
+msgid "Job locked"
+msgstr "Lavoro bloccato"
+
msgid "Job make method"
msgstr "Metodo di produzione dell'ordine"
@@ -12758,6 +12797,9 @@ msgstr "Costi macchina"
msgid "Machine Hours"
msgstr "Ore di macchina"
+msgid "Machine monitoring"
+msgstr "Monitoraggio delle macchine"
+
msgid "Machine rate"
msgstr "Tariffa macchina"
@@ -12969,6 +13011,9 @@ msgstr "Associa il tuo piano dei conti a quello del provider. I conti di registr
msgid "Map your current process, systems, and data"
msgstr "Mappa il tuo processo attuale, i sistemi e i dati"
+msgid "Mapped devices"
+msgstr "Dispositivi associati"
+
msgid "Mapped values"
msgstr "Valori mappati"
@@ -14340,6 +14385,12 @@ msgstr "Nessun deposito è stato ricevuto per questo accordo."
msgid "No depreciation run happens before the cutover. Enter each asset's accumulated depreciation as of the day before the cutover."
msgstr "Non viene eseguito nessun ammortamento prima della transizione contabile. Inserisci il fondo ammortamento di ogni asset al giorno precedente la transizione contabile."
+msgid "No devices found"
+msgstr "Nessun dispositivo trovato"
+
+msgid "No devices match your search"
+msgstr "Nessun dispositivo corrisponde alla ricerca"
+
msgid "No dimension slots configured"
msgstr "Nessuno slot dimensionale configurato"
@@ -14475,6 +14526,9 @@ msgstr "Nessun articolo"
msgid "No items have inventory activity here yet."
msgstr "Nessun articolo ha attività di inventario qui ancora."
+msgid "No job at this location has an open operation."
+msgstr "Nessun ordine di produzione in questa ubicazione ha un'operazione aperta."
+
msgid "No jobs are scheduled at this location yet — release a job to see work-center load."
msgstr "Nessun ordine di produzione programmato in questa ubicazione ancora — rilascia un ordine di produzione per visualizzare il carico del centro di lavoro."
@@ -14568,6 +14622,9 @@ msgstr "Nessuna riga aperta. Aggiungi un servizio per modificare."
msgid "No open memos"
msgstr "Nessun memo aperto"
+msgid "No open operations"
+msgstr "Nessuna operazione aperta"
+
msgid "No open orders for this item are available to link."
msgstr "Nessun ordine aperto per questo articolo disponibile per il collegamento."
@@ -14932,6 +14989,9 @@ msgstr "Normale"
msgid "Not a table but a general-ledger balance: cost accumulates as job materials are issued and clears when the job is received to stock."
msgstr "Non è una tabella ma un saldo della contabilità generale: il costo si accumula man mano che i materiali dell'ordine di produzione vengono emessi e si azzera quando l'ordine viene ricevuto in magazzino."
+msgid "Not calibrated"
+msgstr "Non calibrato"
+
msgid "Not certified"
msgstr "Non certificato"
@@ -14953,6 +15013,12 @@ msgstr "Non ci sono dati sufficienti sull'unità"
msgid "Not feasible"
msgstr "Non fattibile"
+msgid "Not job time"
+msgstr "Non è tempo di lavoro"
+
+msgid "Not mapped"
+msgstr "Non associato"
+
msgid "Not now"
msgstr "Non ora"
@@ -15017,6 +15083,9 @@ msgstr "Nulla ancora completato in MES"
msgid "Nothing else at this location has stock to pull from."
msgstr "Niente altro in questa posizione ha stock da cui prelevare."
+msgid "Nothing else ran on {workCenterName} that day."
+msgstr "Nient'altro ha lavorato su {workCenterName} quel giorno."
+
msgid "Nothing here matches your search and filters."
msgstr "Niente qui corrisponde alla tua ricerca e ai tuoi filtri."
@@ -15074,6 +15143,9 @@ msgstr "Notifica"
msgid "Notify someone"
msgstr "Notifica qualcuno"
+msgid "now"
+msgstr "ora"
+
msgid "Number"
msgstr "Numero"
@@ -15117,6 +15189,9 @@ msgstr "Disattivato — gestito al di fuori della sincronizzazione"
msgid "Off — released revisions stay editable"
msgstr "Disattivato — le revisioni rilasciate rimangono modificabili"
+msgid "Offline"
+msgstr "Non in linea"
+
msgid "Offset Account"
msgstr "Conto di compensazione"
@@ -16069,6 +16144,9 @@ msgstr "Percorso"
msgid "Pause"
msgstr "Sospendi"
+msgid "Paused"
+msgstr "In pausa"
+
msgid "Pay"
msgstr "Paga"
@@ -17579,6 +17657,9 @@ msgstr "Ramp non ha restituito un codice di autorizzazione"
msgid "Ramp rejected the authorization"
msgstr "Ramp ha rifiutato l'autorizzazione"
+msgid "Ran at the time"
+msgstr "In lavorazione in quel momento"
+
msgid "Rate"
msgstr "Tasso"
@@ -18107,6 +18188,9 @@ msgstr "Rilasciato con problemi: {0}"
msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
msgstr "Rilasciare il lotto di produzione rilascia i suoi ordini di produzione, e ognuno deve essere pronto per l'officina."
+msgid "Reload the page to try again."
+msgstr "Ricarica la pagina per riprovare."
+
msgid "Remaining"
msgstr "Rimanente"
@@ -19595,6 +19679,9 @@ msgstr "Cerca clienti e tipi..."
msgid "Search customers or types..."
msgstr "Cerca clienti o tipi..."
+msgid "Search devices"
+msgstr "Cerca dispositivi"
+
msgid "Search employees..."
msgstr "Cerca dipendenti..."
@@ -19619,6 +19706,9 @@ msgstr "Cerca articoli o contenitori"
msgid "Search Job"
msgstr "Cerca Job"
+msgid "Search jobs and operations"
+msgstr "Cerca lavori e operazioni"
+
msgid "Search jobs or items"
msgstr "Cerca ordini di produzione o articoli"
@@ -20945,6 +21035,9 @@ msgstr "Avvio in corso…"
msgid "Starts"
msgstr "Inizia"
+msgid "State"
+msgstr "Stato"
+
msgid "State / Province"
msgstr "Stato / Provincia"
@@ -21096,6 +21189,9 @@ msgstr "Arresta spedizione"
msgid "Stop using {0} in this step"
msgstr "Smetti di usare {0} in questo passo"
+msgid "Stopped"
+msgstr "Fermo"
+
msgid "Stops new purchase suggestions after this date."
msgstr "Interrompe le nuove proposte di acquisto dopo questa data."
@@ -22187,6 +22283,9 @@ msgstr "L'aliquota fiscale predefinita applicata alle righe di offerta e ordine
msgid "The department this one rolls up under for reporting and headcount hierarchies; leave empty for a top-level department."
msgstr "Il reparto sotto il quale questo si aggrega per la reportistica e le gerarchie organizzative; lasciare vuoto per un reparto di primo livello."
+msgid "The device's site is in {siteTimezone}; Carbon uses {locationTimezone}"
+msgstr "Il sito del dispositivo è in {siteTimezone}; Carbon usa {locationTimezone}"
+
msgid "The early hours, {name}."
msgstr "Le prime ore, {name}."
@@ -22459,6 +22558,9 @@ msgstr "Il piano di campionamento per caratteristica del lotto verrà nuovamente
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "L'importo minimo che questo fornitore addebiterà per questo processo, indipendentemente dalla quantità; gli ordini di produzione al di sotto del volume di pareggio costano ancora almeno questo importo."
+msgid "The machine is still running. Assign this time after it stops."
+msgstr "La macchina è ancora in funzione. Assegna questo tempo dopo che si ferma."
+
msgid "The machines, cells, and stations your work runs through"
msgstr "Le macchine, celle e stazioni attraverso cui passa il tuo lavoro"
@@ -24068,6 +24170,9 @@ msgstr "Annulla assegnazione regola"
msgid "Unassigned"
msgstr "Non assegnato"
+msgid "Unattributed Time"
+msgstr "Tempo non attribuito"
+
msgid "Unbalanced"
msgstr "Sbilanciato"
@@ -24843,6 +24948,9 @@ msgstr "Visualizza riga di registrazione"
msgid "View Lists"
msgstr "Visualizza Elenchi"
+msgid "View Machine Time"
+msgstr "Visualizza tempo macchina"
+
msgid "View maintenance dispatch"
msgstr "Visualizza intervento di manutenzione"
@@ -25022,6 +25130,12 @@ msgstr "Annullare questa spedizione comporterà:"
msgid "Waited"
msgstr "Atteso"
+msgid "Waiting"
+msgstr "In attesa"
+
+msgid "Waiting for the first sync"
+msgstr "In attesa della prima sincronizzazione"
+
msgid "Walk each area with your champion and toggle anything out of scope. Codes read Module.Area.Number (ACC.GL.01 = Accounting, General Ledger, item 1)."
msgstr "Esamina ogni area con il tuo champion e attiva/disattiva tutto ciò che è fuori ambito. I codici seguono il formato Modulo.Area.Numero (ACC.GL.01 = Contabilità, Contabilità generale, voce 1)."
@@ -25528,6 +25642,9 @@ msgstr "Quale tipo di richiesta inviare: GET legge qualcosa, POST crea, PUT e PA
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Quale evento di produzione avvia l'orologio della vita di magazzino — ad esempio, riempimento, sigillatura o QC finale."
+msgid "Which operation was this?"
+msgstr "Di quale operazione si trattava?"
+
msgid "While this dispatch is open, the work center is unavailable to the schedule (until the planned end time, or until the dispatch is completed)."
msgstr "Mentre questo dispatch è aperto, il centro di lavoro non è disponibile per la pianificazione (fino all'ora di fine pianificata, o fino al completamento del dispatch)."
diff --git a/packages/locale/locales/it/mes.po b/packages/locale/locales/it/mes.po
index deb7cb1914..82382baed8 100644
--- a/packages/locale/locales/it/mes.po
+++ b/packages/locale/locales/it/mes.po
@@ -820,6 +820,9 @@ msgstr "Sto Ancora Lavorando"
msgid "Ideas, suggestions or problems?"
msgstr "Idee, proposte o problemi?"
+msgid "Idle"
+msgstr "Inattivo"
+
msgid "Idle for"
msgstr "Inattivo per"
@@ -965,6 +968,9 @@ msgstr "Vista elenco"
msgid "Load list"
msgstr "Carica elenco"
+msgid "Loaded: {loadedLabel}"
+msgstr "Caricato: {loadedLabel}"
+
msgid "Loading item details..."
msgstr "Caricamento dettagli articolo..."
@@ -1286,6 +1292,9 @@ msgstr "Richiesto OEM"
msgid "of {0}"
msgstr "di {0}"
+msgid "Offline"
+msgstr "Non in linea"
+
msgid "Oldest first"
msgstr "Più vecchio prima"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 7c5151e9b8..d39faab09a 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -542,6 +542,9 @@ msgstr "キューに{load}件"
msgid "{locationName} (the lease's)"
msgstr "{locationName}(リースの拠点)"
+msgid "{mappedCount} of {totalCount} mapped"
+msgstr "{totalCount} 件中 {mappedCount} 件をマッピング済み"
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB制限"
@@ -616,6 +619,9 @@ msgstr "{passing}/{total}の資産"
msgid "{percent} picked"
msgstr "{percent}ピッキング済"
+msgid "{position} of {total}"
+msgstr "{position}/{total}"
+
msgid "{purgeRowCount, plural, one {Permanently delete # row?} other {Permanently delete # rows?}}"
msgstr "{purgeRowCount, plural, one {# 行を永久に削除しますか?} other {# 行を永久に削除しますか?}}"
@@ -640,6 +646,9 @@ msgstr "{sectionLineCount} 明細"
msgid "{selectedCount} selected"
msgstr "{selectedCount} 件が選択されています"
+msgid "{state} · synced {syncedAgo}"
+msgstr "{state} · {syncedAgo} に同期"
+
msgid "{termMonths, plural, one {# month} other {# months}}"
msgstr "{termMonths, plural, one {# ヶ月} other {# ヶ月}}"
@@ -2668,6 +2677,9 @@ msgstr "年間。会社の増分借入金利から開始します"
msgid "Another cost center this one rolls up into, letting you nest a sub-department under its parent for hierarchical cost reporting."
msgstr "このコストセンターがロールアップされる別の原価センター。親の下に部門をネストさせて、階層的なコスト報告を実現します"
+msgid "Another job or operation"
+msgstr "別のジョブまたは工程"
+
msgid "Another spend integration is already active"
msgstr "別の支出統合が既にアクティブです"
@@ -3540,6 +3552,9 @@ msgstr "資産"
msgid "Assets, liabilities and equity as of a date"
msgstr "特定の日付時点での資産、負債および純資産"
+msgid "Assign machine run time that no loaded operation claimed to the right job, or dismiss it."
+msgstr "読み込まれた工程に割り当てられていない機械加工時間を正しい製造指図に割り当てるか、却下してください。"
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "プリンターを拠点に割り当てます。出荷、入荷受付、および作業区は、上書きされない限り拠点のデフォルトを継承します。"
@@ -5425,6 +5440,9 @@ msgstr "Jira課題に接続"
msgid "Connect Linear issue"
msgstr "Linear イシューを接続"
+msgid "Connect machine monitoring devices to work centers so machine time is recorded against the operation that is loaded."
+msgstr "機械監視デバイスを作業区に接続して、読み込まれた工程に対して機械時間を記録します。"
+
msgid "Connect Slack under Settings → Integrations first."
msgstr "まず設定→連携の下でSlackに接続します。"
@@ -6001,6 +6019,15 @@ msgstr "PDFを作成できませんでした。もう一度お試しください
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "{0}を解除できません: {1} — 生産がすでに記録されています"
+msgid "Could not list the provider's devices. Mapped devices are still shown."
+msgstr "プロバイダーのデバイスを取得できませんでした。マッピング済みのデバイスは引き続き表示されます。"
+
+msgid "Could not load operations"
+msgstr "工程を読み込むことができませんでした"
+
+msgid "Could not load what ran on {workCenterName}."
+msgstr "{workCenterName}で実行された内容を読み込むことができませんでした。"
+
msgid "Could not predict lead time"
msgstr "リードタイムを予測できませんでした"
@@ -7660,6 +7687,9 @@ msgstr "モーションプランナーで検出されました"
msgid "Developer"
msgstr "開発者"
+msgid "Devices"
+msgstr "デバイス"
+
msgid "Difference"
msgstr "差異"
@@ -7928,6 +7958,9 @@ msgstr "ダブルクリックするとこのサブアセンブリが開きます
msgid "Double-click to play this step"
msgstr "このステップを再生するにはダブルクリック"
+msgid "Down"
+msgstr "停止"
+
msgid "Download"
msgstr "ダウンロード"
@@ -11028,6 +11061,9 @@ msgstr "IDプロバイダー"
msgid "Identity provider (IdP)"
msgstr "IDプロバイダー(IdP)"
+msgid "Idle"
+msgstr "待機中"
+
msgid "IdP Metadata URL"
msgstr "IdP メタデータURL"
@@ -11936,6 +11972,9 @@ msgstr "ジョブ進行中"
msgid "Job Location"
msgstr "ジョブロケーション"
+msgid "Job locked"
+msgstr "ジョブはロック済み"
+
msgid "Job make method"
msgstr "ジョブ製造方法"
@@ -12758,6 +12797,9 @@ msgstr "機械費"
msgid "Machine Hours"
msgstr "機械時間"
+msgid "Machine monitoring"
+msgstr "機械監視"
+
msgid "Machine rate"
msgstr "機械費率"
@@ -12969,6 +13011,9 @@ msgstr "勘定科目表をプロバイダーの表にマップしてください
msgid "Map your current process, systems, and data"
msgstr "現在のプロセス、システム、データをマップする"
+msgid "Mapped devices"
+msgstr "マッピング済みのデバイス"
+
msgid "Mapped values"
msgstr "マップされた値"
@@ -14340,6 +14385,12 @@ msgstr "この契約の前受金が受け取られていません。"
msgid "No depreciation run happens before the cutover. Enter each asset's accumulated depreciation as of the day before the cutover."
msgstr "会計開始日前には減価償却は実行されません。会計開始日の前日時点での各資産の減価償却累計額を入力してください。"
+msgid "No devices found"
+msgstr "デバイスが見つかりません"
+
+msgid "No devices match your search"
+msgstr "検索に一致するデバイスはありません"
+
msgid "No dimension slots configured"
msgstr "ディメンションスロットが構成されていません"
@@ -14475,6 +14526,9 @@ msgstr "アイテムなし"
msgid "No items have inventory activity here yet."
msgstr "ここにはまだアイテムの在庫活動がありません。"
+msgid "No job at this location has an open operation."
+msgstr "この拠点の製造指図にはオープン状態の工程がありません。"
+
msgid "No jobs are scheduled at this location yet — release a job to see work-center load."
msgstr "この拠点ではまだ製造指図がスケジュール化されていません — 製造指図をリリースして作業区負荷を確認してください。"
@@ -14568,6 +14622,9 @@ msgstr "未完了の明細はありません。変更するにはサービスを
msgid "No open memos"
msgstr "オープンなメモはありません"
+msgid "No open operations"
+msgstr "オープン状態の工程がありません"
+
msgid "No open orders for this item are available to link."
msgstr "この品目のオープン注文はリンク可能なものがありません。"
@@ -14932,6 +14989,9 @@ msgstr "通常"
msgid "Not a table but a general-ledger balance: cost accumulates as job materials are issued and clears when the job is received to stock."
msgstr "テーブルではなく総勘定元帳の残高です。指図材料が払い出されると原価が累積され、製造指図が在庫として受領されたときにクリアされます。"
+msgid "Not calibrated"
+msgstr "検定されていない"
+
msgid "Not certified"
msgstr "認定されていない"
@@ -14953,6 +15013,12 @@ msgstr "個データが不足しています"
msgid "Not feasible"
msgstr "実現不可能"
+msgid "Not job time"
+msgstr "ジョブの時間ではない"
+
+msgid "Not mapped"
+msgstr "未マッピング"
+
msgid "Not now"
msgstr "後で"
@@ -15017,6 +15083,9 @@ msgstr "MESでまだ何も完了していません"
msgid "Nothing else at this location has stock to pull from."
msgstr "この場所には他に引き出す在庫がありません。"
+msgid "Nothing else ran on {workCenterName} that day."
+msgstr "その日、{workCenterName} では他に何も稼働していません。"
+
msgid "Nothing here matches your search and filters."
msgstr "検索と絞り込み条件に一致するものがありません"
@@ -15074,6 +15143,9 @@ msgstr "通知"
msgid "Notify someone"
msgstr "誰かに通知"
+msgid "now"
+msgstr "現在"
+
msgid "Number"
msgstr "数字"
@@ -15117,6 +15189,9 @@ msgstr "オフ — 同期外で処理"
msgid "Off — released revisions stay editable"
msgstr "オフ - リリースされたリビジョンは編集可能なままです"
+msgid "Offline"
+msgstr "オフライン"
+
msgid "Offset Account"
msgstr "相殺勘定"
@@ -16069,6 +16144,9 @@ msgstr "パス"
msgid "Pause"
msgstr "一時停止"
+msgid "Paused"
+msgstr "一時停止"
+
msgid "Pay"
msgstr "支払う"
@@ -17579,6 +17657,9 @@ msgstr "Ramp が認可コードを返しませんでした"
msgid "Ramp rejected the authorization"
msgstr "Ramp が認可を拒否しました"
+msgid "Ran at the time"
+msgstr "その時間に稼働"
+
msgid "Rate"
msgstr "レート"
@@ -18107,6 +18188,9 @@ msgstr "リリース済(警告あり): {0}"
msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
msgstr "バッチをリリースするとその製造指図がリリースされ、それぞれが製造現場に対応可能である必要があります。"
+msgid "Reload the page to try again."
+msgstr "ページを再度読み込んで、もう一度試してください。"
+
msgid "Remaining"
msgstr "残高"
@@ -19595,6 +19679,9 @@ msgstr "得意先とタイプを検索..."
msgid "Search customers or types..."
msgstr "得意先またはタイプを検索..."
+msgid "Search devices"
+msgstr "デバイスを検索"
+
msgid "Search employees..."
msgstr "従業員を検索..."
@@ -19619,6 +19706,9 @@ msgstr "アイテムまたはビンを検索"
msgid "Search Job"
msgstr "ジョブを検索"
+msgid "Search jobs and operations"
+msgstr "ジョブと工程を検索"
+
msgid "Search jobs or items"
msgstr "製造指図または品目を検索"
@@ -20945,6 +21035,9 @@ msgstr "開始中…"
msgid "Starts"
msgstr "開始"
+msgid "State"
+msgstr "状態"
+
msgid "State / Province"
msgstr "都道府県"
@@ -21096,6 +21189,9 @@ msgstr "配送を停止"
msgid "Stop using {0} in this step"
msgstr "{0} をこのステップで使用しない"
+msgid "Stopped"
+msgstr "停止"
+
msgid "Stops new purchase suggestions after this date."
msgstr "この日付以降、新規の購買提案が行われなくなります。"
@@ -22187,6 +22283,9 @@ msgstr "得意先の見積および販売注文明細に適用される既定の
msgid "The department this one rolls up under for reporting and headcount hierarchies; leave empty for a top-level department."
msgstr "レポートとヘッドカウント階層のために、このロールアップが行われるセクション。トップレベル部門の場合は空白のままにしてください。"
+msgid "The device's site is in {siteTimezone}; Carbon uses {locationTimezone}"
+msgstr "デバイスのサイトは {siteTimezone} にあります。Carbon は {locationTimezone} を使用します"
+
msgid "The early hours, {name}."
msgstr "早朝の時間、{name}。"
@@ -22459,6 +22558,9 @@ msgstr "ロットの特性別抜取検査方式は選択された文書から再
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "この仕入先がこの工法に対して請求する最低金額(数量に関係なく)。損益分岐点量以下の製造指図でも、最低でもこの金額がかかります。"
+msgid "The machine is still running. Assign this time after it stops."
+msgstr "機械はまだ稼働中です。停止後にこの時間を割り当ててください。"
+
msgid "The machines, cells, and stations your work runs through"
msgstr "あなたの仕事が実行される機械、セル、およびステーション"
@@ -24068,6 +24170,9 @@ msgstr "ルールの割り当てを解除"
msgid "Unassigned"
msgstr "未割り当て"
+msgid "Unattributed Time"
+msgstr "未割り当て時間"
+
msgid "Unbalanced"
msgstr "差額有り"
@@ -24843,6 +24948,9 @@ msgstr "仕訳行を表示"
msgid "View Lists"
msgstr "リストを表示"
+msgid "View Machine Time"
+msgstr "機械時間を表示"
+
msgid "View maintenance dispatch"
msgstr "保全指示を表示"
@@ -25022,6 +25130,12 @@ msgstr "この出荷をキャンセルすると、以下のようになります
msgid "Waited"
msgstr "待機"
+msgid "Waiting"
+msgstr "待機中"
+
+msgid "Waiting for the first sync"
+msgstr "最初の同期を待っています"
+
msgid "Walk each area with your champion and toggle anything out of scope. Codes read Module.Area.Number (ACC.GL.01 = Accounting, General Ledger, item 1)."
msgstr "チャンピオンと一緒に各エリアを確認し、範囲外のものをトグルしてください。コードはModule.Area.Numberを読みます(ACC.GL.01 = 会計、総勘定元帳、品目1)。"
@@ -25528,6 +25642,9 @@ msgstr "送信するリクエストの種類を選択します:GETは何かを
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "どの製造イベントが保存期間時計を開始するか — たとえば、塗りつぶし、シール、または最終QC。"
+msgid "Which operation was this?"
+msgstr "これはどの工程でしたか?"
+
msgid "While this dispatch is open, the work center is unavailable to the schedule (until the planned end time, or until the dispatch is completed)."
msgstr "このディスパッチがオープンの間、作業区はスケジュールに対して利用できません(計画終了時刻まで、またはディスパッチが完了するまで)。"
diff --git a/packages/locale/locales/ja/mes.po b/packages/locale/locales/ja/mes.po
index 4afe8b1f3c..2aedc4c198 100644
--- a/packages/locale/locales/ja/mes.po
+++ b/packages/locale/locales/ja/mes.po
@@ -820,6 +820,9 @@ msgstr "まだ作業中です"
msgid "Ideas, suggestions or problems?"
msgstr "アイデア、提案、または問題はありますか?"
+msgid "Idle"
+msgstr "待機中"
+
msgid "Idle for"
msgstr "待機時間"
@@ -965,6 +968,9 @@ msgstr "リスト表示"
msgid "Load list"
msgstr "リストをロード"
+msgid "Loaded: {loadedLabel}"
+msgstr "ロード済み: {loadedLabel}"
+
msgid "Loading item details..."
msgstr "品目詳細を読み込み中..."
@@ -1286,6 +1292,9 @@ msgstr "OEM対応必要"
msgid "of {0}"
msgstr "の{0}"
+msgid "Offline"
+msgstr "オフライン"
+
msgid "Oldest first"
msgstr "最も古い順"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 42e4ed5962..28b4c567a3 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -542,6 +542,9 @@ msgstr "큐에 {load}개 대기 중"
msgid "{locationName} (the lease's)"
msgstr "{locationName} (리스의 사업장)"
+msgid "{mappedCount} of {totalCount} mapped"
+msgstr "{totalCount}개 중 {mappedCount}개 매핑됨"
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB 제한"
@@ -616,6 +619,9 @@ msgstr "총 {total}개 자산 중 {passing}개"
msgid "{percent} picked"
msgstr "{percent} 피킹 완료"
+msgid "{position} of {total}"
+msgstr "{position}/{total}"
+
msgid "{purgeRowCount, plural, one {Permanently delete # row?} other {Permanently delete # rows?}}"
msgstr "{purgeRowCount, plural, one {# 행을 영구 삭제하시겠습니까?} other {# 행을 영구 삭제하시겠습니까?}}"
@@ -640,6 +646,9 @@ msgstr "{sectionLineCount} 라인"
msgid "{selectedCount} selected"
msgstr "{selectedCount}개 선택됨"
+msgid "{state} · synced {syncedAgo}"
+msgstr "{state} · {syncedAgo} 동기화됨"
+
msgid "{termMonths, plural, one {# month} other {# months}}"
msgstr "{termMonths, plural, one {# 개월} other {# 개월}}"
@@ -2668,6 +2677,9 @@ msgstr "연간. 회사의 증분 차입 이율부터 시작합니다."
msgid "Another cost center this one rolls up into, letting you nest a sub-department under its parent for hierarchical cost reporting."
msgstr "이 원가 센터가 롤업되는 다른 원가 센터로, 계층적 원가 보고를 위해 부서를 상위 항목 아래에 중첩시킬 수 있게 함"
+msgid "Another job or operation"
+msgstr "다른 작업 또는 공정"
+
msgid "Another spend integration is already active"
msgstr "다른 지출 통합이 이미 활성화되어 있습니다"
@@ -3540,6 +3552,9 @@ msgstr "자산"
msgid "Assets, liabilities and equity as of a date"
msgstr "특정 날짜 기준 자산, 부채 및 자본"
+msgid "Assign machine run time that no loaded operation claimed to the right job, or dismiss it."
+msgstr "로드된 공정이 청구하지 않은 기계 시간을 올바른 작업 지시에 할당하거나 거부하세요."
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "사업장에 프린터를 할당합니다. 출하, 입고, 및 작업장은 사업장 기본값을 상속하며 재정의할 수 있습니다."
@@ -5425,6 +5440,9 @@ msgstr "Jira 이슈 연결"
msgid "Connect Linear issue"
msgstr "Linear 이슈 연결"
+msgid "Connect machine monitoring devices to work centers so machine time is recorded against the operation that is loaded."
+msgstr "기계 모니터링 기기를 작업장에 연결하여 로드된 공정에 대해 기계 시간을 기록하세요."
+
msgid "Connect Slack under Settings → Integrations first."
msgstr "설정 → 연동에서 먼저 Slack을 연결합니다."
@@ -6001,6 +6019,15 @@ msgstr "PDF를 생성할 수 없습니다. 다시 시도하세요."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "{0}을(를) 해제할 수 없습니다: {1} — 생산이 이미 기록됨"
+msgid "Could not list the provider's devices. Mapped devices are still shown."
+msgstr "공급자의 장치 목록을 가져올 수 없습니다. 매핑된 장치는 계속 표시됩니다."
+
+msgid "Could not load operations"
+msgstr "공정을 로드할 수 없습니다"
+
+msgid "Could not load what ran on {workCenterName}."
+msgstr "{workCenterName}에서 실행된 항목을 로드할 수 없습니다."
+
msgid "Could not predict lead time"
msgstr "리드타임을 예측할 수 없습니다"
@@ -7660,6 +7687,9 @@ msgstr "모션 플래너가 감지함"
msgid "Developer"
msgstr "개발자"
+msgid "Devices"
+msgstr "기기"
+
msgid "Difference"
msgstr "차액"
@@ -7928,6 +7958,9 @@ msgstr "이 하위 조립품을 열려면 이중 클릭하세요"
msgid "Double-click to play this step"
msgstr "이 단계를 재생하려면 더블 클릭"
+msgid "Down"
+msgstr "가동중단"
+
msgid "Download"
msgstr "다운로드"
@@ -11028,6 +11061,9 @@ msgstr "자격 증명 공급자"
msgid "Identity provider (IdP)"
msgstr "자격 증명 공급자(IdP)"
+msgid "Idle"
+msgstr "유휴"
+
msgid "IdP Metadata URL"
msgstr "IdP 메타데이터 URL"
@@ -11936,6 +11972,9 @@ msgstr "진행 중인 작업"
msgid "Job Location"
msgstr "작업 위치"
+msgid "Job locked"
+msgstr "작업 잠김"
+
msgid "Job make method"
msgstr "작업 지시 생산 방법"
@@ -12758,6 +12797,9 @@ msgstr "기계 비용"
msgid "Machine Hours"
msgstr "기계 시간"
+msgid "Machine monitoring"
+msgstr "기계 모니터링"
+
msgid "Machine rate"
msgstr "기계비율"
@@ -12969,6 +13011,9 @@ msgstr "계정과목표를 공급자와 매핑하세요. 전기 기본 및 비
msgid "Map your current process, systems, and data"
msgstr "현재 프로세스, 시스템, 데이터를 매핑하세요"
+msgid "Mapped devices"
+msgstr "매핑된 장치"
+
msgid "Mapped values"
msgstr "매핑된 값"
@@ -14340,6 +14385,12 @@ msgstr "이 계약에 대해 보증금이 수령되지 않았습니다."
msgid "No depreciation run happens before the cutover. Enter each asset's accumulated depreciation as of the day before the cutover."
msgstr "전환 이전에는 감가상각이 실행되지 않습니다. 전환 이전 날 기준으로 각 자산의 감가상각누계액을 입력하세요."
+msgid "No devices found"
+msgstr "기기를 찾을 수 없음"
+
+msgid "No devices match your search"
+msgstr "검색과 일치하는 장치가 없습니다"
+
msgid "No dimension slots configured"
msgstr "구성된 차원 슬롯이 없습니다"
@@ -14475,6 +14526,9 @@ msgstr "품목 없음"
msgid "No items have inventory activity here yet."
msgstr "아직 여기에 재고 활동이 있는 항목이 없습니다."
+msgid "No job at this location has an open operation."
+msgstr "이 사업장에는 미결 공정이 있는 작업 지시가 없습니다."
+
msgid "No jobs are scheduled at this location yet — release a job to see work-center load."
msgstr "아직 이 사업장에 스케줄된 작업 지시가 없습니다 — 작업 지시를 릴리스하여 작업장 부하를 확인하세요."
@@ -14568,6 +14622,9 @@ msgstr "열린 라인이 없습니다. 변경하려면 서비스를 추가하세
msgid "No open memos"
msgstr "미결 메모 없음"
+msgid "No open operations"
+msgstr "미결 공정 없음"
+
msgid "No open orders for this item are available to link."
msgstr "이 품목에 연결할 수 있는 미결 발주서가 없습니다."
@@ -14932,6 +14989,9 @@ msgstr "일반"
msgid "Not a table but a general-ledger balance: cost accumulates as job materials are issued and clears when the job is received to stock."
msgstr "표가 아니라 총계정원장 잔액입니다: 작업 지시 자재가 지급될 때 원가가 누적되고 작업 지시가 재고로 입고될 때 원가가 소거됩니다."
+msgid "Not calibrated"
+msgstr "보정되지 않음"
+
msgid "Not certified"
msgstr "인증되지 않음"
@@ -14953,6 +15013,12 @@ msgstr "개에 대한 데이터가 부족합니다."
msgid "Not feasible"
msgstr "불가능"
+msgid "Not job time"
+msgstr "작업 시간 아님"
+
+msgid "Not mapped"
+msgstr "매핑되지 않음"
+
msgid "Not now"
msgstr "나중에"
@@ -15017,6 +15083,9 @@ msgstr "MES에서 아직 완료된 항목이 없습니다"
msgid "Nothing else at this location has stock to pull from."
msgstr "이 위치에는 더 이상 가져올 재고가 없습니다."
+msgid "Nothing else ran on {workCenterName} that day."
+msgstr "그날 {workCenterName}에서 실행된 다른 것이 없습니다."
+
msgid "Nothing here matches your search and filters."
msgstr "검색 및 필터와 일치하는 항목이 없습니다."
@@ -15074,6 +15143,9 @@ msgstr "알림"
msgid "Notify someone"
msgstr "누군가에게 알림"
+msgid "now"
+msgstr "지금"
+
msgid "Number"
msgstr "번호"
@@ -15117,6 +15189,9 @@ msgstr "끔 — 동기화 외부에서 처리됨"
msgid "Off — released revisions stay editable"
msgstr "꺼짐 — 릴리스된 리비전은 편집 가능한 상태로 유지됨"
+msgid "Offline"
+msgstr "오프라인"
+
msgid "Offset Account"
msgstr "상계 계정"
@@ -16069,6 +16144,9 @@ msgstr "경로"
msgid "Pause"
msgstr "일시 중지"
+msgid "Paused"
+msgstr "일시 중지됨"
+
msgid "Pay"
msgstr "지불"
@@ -17579,6 +17657,9 @@ msgstr "Ramp에서 인증 코드를 반환하지 않았습니다"
msgid "Ramp rejected the authorization"
msgstr "Ramp에서 인증을 거부했습니다"
+msgid "Ran at the time"
+msgstr "해당 시간에 실행됨"
+
msgid "Rate"
msgstr "환율"
@@ -18107,6 +18188,9 @@ msgstr "릴리스됨 (문제 있음): {0}"
msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
msgstr "배치를 릴리스하면 포함된 작업 지시들도 릴리스되고, 각각은 현장에 준비되어야 합니다."
+msgid "Reload the page to try again."
+msgstr "페이지를 새로고침하여 다시 시도하세요."
+
msgid "Remaining"
msgstr "남음"
@@ -19595,6 +19679,9 @@ msgstr "고객 및 유형 검색..."
msgid "Search customers or types..."
msgstr "고객 또는 유형 검색..."
+msgid "Search devices"
+msgstr "장치 검색"
+
msgid "Search employees..."
msgstr "직원 검색..."
@@ -19619,6 +19706,9 @@ msgstr "품목 또는 빈 검색"
msgid "Search Job"
msgstr "작업 검색"
+msgid "Search jobs and operations"
+msgstr "작업 및 공정 검색"
+
msgid "Search jobs or items"
msgstr "작업 지시 또는 품목 검색"
@@ -20945,6 +21035,9 @@ msgstr "시작 중…"
msgid "Starts"
msgstr "시작"
+msgid "State"
+msgstr "상태"
+
msgid "State / Province"
msgstr "주/도"
@@ -21096,6 +21189,9 @@ msgstr "배송 중지"
msgid "Stop using {0} in this step"
msgstr "이 단계에서 {0} 사용 중지"
+msgid "Stopped"
+msgstr "정지됨"
+
msgid "Stops new purchase suggestions after this date."
msgstr "이 날짜 이후로 새로운 구매 제안을 중단합니다."
@@ -22187,6 +22283,9 @@ msgstr "이 고객의 견적 및 판매주문 라인에 적용되는 기본 세
msgid "The department this one rolls up under for reporting and headcount hierarchies; leave empty for a top-level department."
msgstr "보고 및 인원 계층구조에서 이 부서가 속하는 상위 부서입니다. 최상위 부서인 경우 비워두세요."
+msgid "The device's site is in {siteTimezone}; Carbon uses {locationTimezone}"
+msgstr "장치 사이트는 {siteTimezone}에 있습니다. Carbon은 {locationTimezone}을(를) 사용합니다"
+
msgid "The early hours, {name}."
msgstr "이른 시간, {name}."
@@ -22459,6 +22558,9 @@ msgstr "로트의 특성별 샘플링 계획은 선택한 문서에서 다시
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "이 공급업체가 수량과 관계없이 이 공법에 대해 청구할 최소 금액; 손익분기점 이하의 작업 지시도 최소한 이 금액이 들어갑니다."
+msgid "The machine is still running. Assign this time after it stops."
+msgstr "기계가 아직 가동 중입니다. 멈춘 후에 이 시간을 할당하세요."
+
msgid "The machines, cells, and stations your work runs through"
msgstr "작업이 거쳐가는 기계, 셀, 스테이션"
@@ -24068,6 +24170,9 @@ msgstr "규칙 할당 해제"
msgid "Unassigned"
msgstr "미배정"
+msgid "Unattributed Time"
+msgstr "미귀속 시간"
+
msgid "Unbalanced"
msgstr "불균형"
@@ -24843,6 +24948,9 @@ msgstr "분개 보기"
msgid "View Lists"
msgstr "목록 보기"
+msgid "View Machine Time"
+msgstr "기계 시간 보기"
+
msgid "View maintenance dispatch"
msgstr "유지보수 지시 보기"
@@ -25022,6 +25130,12 @@ msgstr "이 출하를 무효화하면 다음과 같은 결과가 발생합니다
msgid "Waited"
msgstr "대기함"
+msgid "Waiting"
+msgstr "대기 중"
+
+msgid "Waiting for the first sync"
+msgstr "첫 동기화를 기다리는 중"
+
msgid "Walk each area with your champion and toggle anything out of scope. Codes read Module.Area.Number (ACC.GL.01 = Accounting, General Ledger, item 1)."
msgstr "담당자와 함께 각 영역을 살펴보고 범위에서 벗어난 항목은 토글로 제외하세요. 코드는 모듈.영역.번호 형식입니다(ACC.GL.01 = 회계, 총계정원장, 1번 항목)."
@@ -25528,6 +25642,9 @@ msgstr "전송할 요청의 종류: GET은 무언가를 읽고, POST는 생성
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "유효기간 계산이 시작되는 제조 이벤트 — 예를 들어 충전, 밀봉, 또는 최종 품질검사."
+msgid "Which operation was this?"
+msgstr "어떤 공정이었나요?"
+
msgid "While this dispatch is open, the work center is unavailable to the schedule (until the planned end time, or until the dispatch is completed)."
msgstr "이 유지보수 지시가 열려 있는 동안 작업장은 일정에 사용할 수 없습니다(계획된 종료 시간까지 또는 지시가 완료될 때까지)."
diff --git a/packages/locale/locales/ko/mes.po b/packages/locale/locales/ko/mes.po
index ebccd70c17..e77cc2f6c6 100644
--- a/packages/locale/locales/ko/mes.po
+++ b/packages/locale/locales/ko/mes.po
@@ -820,6 +820,9 @@ msgstr "아직 작업 중입니다"
msgid "Ideas, suggestions or problems?"
msgstr "아이디어, 제안, 또는 문제가 있으신가요?"
+msgid "Idle"
+msgstr "유휴"
+
msgid "Idle for"
msgstr "유휴 상태"
@@ -965,6 +968,9 @@ msgstr "목록 보기"
msgid "Load list"
msgstr "목록 불러오기"
+msgid "Loaded: {loadedLabel}"
+msgstr "로드됨: {loadedLabel}"
+
msgid "Loading item details..."
msgstr "품목 세부정보를 불러오는 중..."
@@ -1286,6 +1292,9 @@ msgstr "OEM 필요"
msgid "of {0}"
msgstr "/{0}"
+msgid "Offline"
+msgstr "오프라인"
+
msgid "Oldest first"
msgstr "오래된순"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 168585384a..62b1788658 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -542,6 +542,9 @@ msgstr "{load} w kolejce"
msgid "{locationName} (the lease's)"
msgstr "{locationName} (z leasingu)"
+msgid "{mappedCount} of {totalCount} mapped"
+msgstr "Przypisano {mappedCount} z {totalCount}"
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB limit"
@@ -616,6 +619,9 @@ msgstr "{passing} z {total} aktyw"
msgid "{percent} picked"
msgstr "{percent} pobrano"
+msgid "{position} of {total}"
+msgstr "{position} z {total}"
+
msgid "{purgeRowCount, plural, one {Permanently delete # row?} other {Permanently delete # rows?}}"
msgstr "{purgeRowCount, plural, one {Trwale usuń # wiersz?} other {Trwale usuń # wierszy?}}"
@@ -640,6 +646,9 @@ msgstr "{sectionLineCount} pozycji"
msgid "{selectedCount} selected"
msgstr "{selectedCount} zaznaczonych"
+msgid "{state} · synced {syncedAgo}"
+msgstr "{state} · zsynchronizowano {syncedAgo}"
+
msgid "{termMonths, plural, one {# month} other {# months}}"
msgstr "{termMonths, plural, one {# miesiąc} other {# miesięcy}}"
@@ -2668,6 +2677,9 @@ msgstr "Rocznie. Zaczyna się od przyrostowej stopy oprocentowania firmy."
msgid "Another cost center this one rolls up into, letting you nest a sub-department under its parent for hierarchical cost reporting."
msgstr "Inne miejsce powstawania kosztów, w które się to sumuje, pozwalające na zagnieżdżenie podrzędnego działu pod jego jednostką nadrzędną dla hierarchicznego raportowania kosztów."
+msgid "Another job or operation"
+msgstr "Inne zlecenie lub operacja"
+
msgid "Another spend integration is already active"
msgstr "Inna integracja wydatków jest już aktywna"
@@ -3540,6 +3552,9 @@ msgstr "Aktywa"
msgid "Assets, liabilities and equity as of a date"
msgstr "Aktywa, pasywa i kapitał własny na określony dzień"
+msgid "Assign machine run time that no loaded operation claimed to the right job, or dismiss it."
+msgstr "Przypisz czas obróbki, który żadna załadowana operacja nie roszczył sobie do właściwego zlecenia produkcyjnego, lub odrzuć to."
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Przypisz drukarki do lokalizacji. Wysyłka, otrzymywanie i stanowiska robocze dziedziczą domyślne lokalizacje, chyba że nastąpi nadpisanie."
@@ -5425,6 +5440,9 @@ msgstr "Połącz problem Jiry"
msgid "Connect Linear issue"
msgstr "Połącz problem Linear"
+msgid "Connect machine monitoring devices to work centers so machine time is recorded against the operation that is loaded."
+msgstr "Podłącz urządzenia do monitorowania maszyn do stanowisk roboczych, aby czas maszynowy był rejestrowany dla załadowanej operacji."
+
msgid "Connect Slack under Settings → Integrations first."
msgstr "Najpierw połącz Slack w Ustawienia → Integracje."
@@ -6001,6 +6019,15 @@ msgstr "Nie można było zbudować pliku PDF. Spróbuj ponownie."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "Nie można rozwiązać {0}: {1} — produkcja już zapisana"
+msgid "Could not list the provider's devices. Mapped devices are still shown."
+msgstr "Nie udało się pobrać listy urządzeń dostawcy. Przypisane urządzenia są nadal widoczne."
+
+msgid "Could not load operations"
+msgstr "Nie można załadować operacji"
+
+msgid "Could not load what ran on {workCenterName}."
+msgstr "Nie można załadować operacje uruchomione na {workCenterName}."
+
msgid "Could not predict lead time"
msgstr "Nie można było przewidzieć czasu realizacji"
@@ -7660,6 +7687,9 @@ msgstr "Wykryte przez planer ruchu"
msgid "Developer"
msgstr "Deweloper"
+msgid "Devices"
+msgstr "Urządzenia"
+
msgid "Difference"
msgstr "Różnica"
@@ -7928,6 +7958,9 @@ msgstr "Kliknij dwukrotnie, aby otworzyć ten podzespół"
msgid "Double-click to play this step"
msgstr "Kliknij dwukrotnie, aby odtworzyć ten krok"
+msgid "Down"
+msgstr "Awaria"
+
msgid "Download"
msgstr "Pobierz"
@@ -11028,6 +11061,9 @@ msgstr "Dostawca tożsamości"
msgid "Identity provider (IdP)"
msgstr "Dostawca tożsamości (IdP)"
+msgid "Idle"
+msgstr "Bezczynny"
+
msgid "IdP Metadata URL"
msgstr "Adres URL metadanych IdP"
@@ -11936,6 +11972,9 @@ msgstr "Zadanie w toku"
msgid "Job Location"
msgstr "Lokalizacja Zadania"
+msgid "Job locked"
+msgstr "Zlecenie zablokowane"
+
msgid "Job make method"
msgstr "Metoda produkcji zlecenia"
@@ -12758,6 +12797,9 @@ msgstr "Koszty maszyny"
msgid "Machine Hours"
msgstr "Godziny Maszyn"
+msgid "Machine monitoring"
+msgstr "Monitorowanie maszyn"
+
msgid "Machine rate"
msgstr "Stawka maszyny"
@@ -12969,6 +13011,9 @@ msgstr "Zmapuj swój plan kont na plan kont dostawcy. Konta domyślne dla księg
msgid "Map your current process, systems, and data"
msgstr "Zmapuj swój obecny proces, systemy i dane"
+msgid "Mapped devices"
+msgstr "Przypisane urządzenia"
+
msgid "Mapped values"
msgstr "Zmapowane wartości"
@@ -14340,6 +14385,12 @@ msgstr "Nie otrzymano zaliczki dla tej umowy."
msgid "No depreciation run happens before the cutover. Enter each asset's accumulated depreciation as of the day before the cutover."
msgstr "Żadne uruchomienie amortyzacji nie następuje przed zmianą. Wpisz umorzenie każdego składnika majątku na dzień przed zmianą."
+msgid "No devices found"
+msgstr "Nie znaleziono urządzeń"
+
+msgid "No devices match your search"
+msgstr "Żadne urządzenie nie pasuje do wyszukiwania"
+
msgid "No dimension slots configured"
msgstr "Brak skonfigurowanych slotów wymiarów"
@@ -14475,6 +14526,9 @@ msgstr "Brak artykułów"
msgid "No items have inventory activity here yet."
msgstr "Brak aktywności magazynowej tutaj."
+msgid "No job at this location has an open operation."
+msgstr "Żadne zlecenie produkcyjne w tej lokalizacji nie ma otwartej operacji."
+
msgid "No jobs are scheduled at this location yet — release a job to see work-center load."
msgstr "Żadne zlecenia produkcyjne nie są zaplanowane w tej lokalizacji — zwolnij zlecenie produkcyjne, aby zobaczyć obciążenie stanowiska roboczego."
@@ -14568,6 +14622,9 @@ msgstr "Brak otwartych pozycji. Dodaj usługę, aby wprowadzić zmianę."
msgid "No open memos"
msgstr "Brak otwartych notatek"
+msgid "No open operations"
+msgstr "Brak otwartych operacji"
+
msgid "No open orders for this item are available to link."
msgstr "Brak dostępnych otwartych zamówień dla tego produktu do powiązania."
@@ -14932,6 +14989,9 @@ msgstr "Normalny"
msgid "Not a table but a general-ledger balance: cost accumulates as job materials are issued and clears when the job is received to stock."
msgstr "To nie jest tabela, lecz saldo konta głównego: koszt gromadzi się gdy materiały zlecenia produkcyjnego są wydawane i czyszczą się gdy zlecenie jest przyjęte do zapasów."
+msgid "Not calibrated"
+msgstr "Nieskalibowany"
+
msgid "Not certified"
msgstr "Nie certyfikowany"
@@ -14953,6 +15013,12 @@ msgstr "Niewystarczająco danych sztuki"
msgid "Not feasible"
msgstr "Niemożliwe do wykonania"
+msgid "Not job time"
+msgstr "To nie czas zlecenia"
+
+msgid "Not mapped"
+msgstr "Nieprzypisane"
+
msgid "Not now"
msgstr "Nie teraz"
@@ -15017,6 +15083,9 @@ msgstr "W MES nic jeszcze nie ukończono"
msgid "Nothing else at this location has stock to pull from."
msgstr "W tym miejscu nic innego nie ma zapasów do pobrania."
+msgid "Nothing else ran on {workCenterName} that day."
+msgstr "Tego dnia na {workCenterName} nie pracowało nic więcej."
+
msgid "Nothing here matches your search and filters."
msgstr "Nic tutaj nie odpowiada Twojemu wyszukiwaniu i filtrom."
@@ -15074,6 +15143,9 @@ msgstr "Powiadom"
msgid "Notify someone"
msgstr "Powiadom kogoś"
+msgid "now"
+msgstr "teraz"
+
msgid "Number"
msgstr "Liczba"
@@ -15117,6 +15189,9 @@ msgstr "Wyłączone — obsługiwane poza synchronizacją"
msgid "Off — released revisions stay editable"
msgstr "Wyłączone — zwolnione rewizje pozostają edytowalne"
+msgid "Offline"
+msgstr "Offline"
+
msgid "Offset Account"
msgstr "Konto równoważące"
@@ -16069,6 +16144,9 @@ msgstr "Ścieżka"
msgid "Pause"
msgstr "Wstrzymaj"
+msgid "Paused"
+msgstr "Wstrzymane"
+
msgid "Pay"
msgstr "Opłacić"
@@ -17579,6 +17657,9 @@ msgstr "Ramp nie zwrócił kodu autoryzacyjnego"
msgid "Ramp rejected the authorization"
msgstr "Ramp odrzucił autoryzację"
+msgid "Ran at the time"
+msgstr "Pracowało w tym czasie"
+
msgid "Rate"
msgstr "Kurs"
@@ -18107,6 +18188,9 @@ msgstr "Zwolniono z problemami: {0}"
msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
msgstr "Zwolnienie partii produkcyjnej zwalnia jej zlecenia produkcyjne, a każde musi być gotowe na halę produkcyjną."
+msgid "Reload the page to try again."
+msgstr "Odśwież stronę, aby spróbować ponownie."
+
msgid "Remaining"
msgstr "Pozostało"
@@ -19595,6 +19679,9 @@ msgstr "Wyszukaj klientów i typy..."
msgid "Search customers or types..."
msgstr "Szukaj klientów lub typów..."
+msgid "Search devices"
+msgstr "Szukaj urządzeń"
+
msgid "Search employees..."
msgstr "Szukaj pracowników..."
@@ -19619,6 +19706,9 @@ msgstr "Szukaj przedmiotów lub pojemników"
msgid "Search Job"
msgstr "Szukaj zadania"
+msgid "Search jobs and operations"
+msgstr "Szukaj zleceń i operacji"
+
msgid "Search jobs or items"
msgstr "Szukaj zleceń produkcyjnych lub artykułów"
@@ -20945,6 +21035,9 @@ msgstr "Uruchamianie…"
msgid "Starts"
msgstr "Rozpoczyna się"
+msgid "State"
+msgstr "Stan"
+
msgid "State / Province"
msgstr "Stan / Prowincja"
@@ -21096,6 +21189,9 @@ msgstr "Zatrzymaj wysyłkę"
msgid "Stop using {0} in this step"
msgstr "Przestań używać {0} w tym kroku"
+msgid "Stopped"
+msgstr "Zatrzymany"
+
msgid "Stops new purchase suggestions after this date."
msgstr "Wstrzymuje nowe propozycje zakupów po tej dacie."
@@ -22187,6 +22283,9 @@ msgstr "Domyślna stawka podatku stosowana do pozycji ofert i zamówień sprzeda
msgid "The department this one rolls up under for reporting and headcount hierarchies; leave empty for a top-level department."
msgstr "Dział, pod którym ten się zlicza dla raportowania i hierarchii liczby pracowników; pozostaw puste dla departamentu najwyższego poziomu."
+msgid "The device's site is in {siteTimezone}; Carbon uses {locationTimezone}"
+msgstr "Lokalizacja urządzenia jest w strefie {siteTimezone}; Carbon używa {locationTimezone}"
+
msgid "The early hours, {name}."
msgstr "Wczesne godziny, {name}."
@@ -22459,6 +22558,9 @@ msgstr "Plan kontroli wyrywkowej dla każdej cechy partii zostanie ponownie usta
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "Najniższa kwota, którą dostawca będzie pobierać za ten proces, niezależnie od ilości; zlecenia produkcyjne poniżej progu rentowności kosztują przynajmniej tyle."
+msgid "The machine is still running. Assign this time after it stops."
+msgstr "Maszyna nadal pracuje. Przypisz ten czas po jej zatrzymaniu."
+
msgid "The machines, cells, and stations your work runs through"
msgstr "Maszyny, komórki i stanowiska, przez które przechodzi Twoja praca"
@@ -24068,6 +24170,9 @@ msgstr "Usuń przypisanie reguły"
msgid "Unassigned"
msgstr "Nieprzydzielone"
+msgid "Unattributed Time"
+msgstr "Czas nieprzypisany"
+
msgid "Unbalanced"
msgstr "Niezrównoważony"
@@ -24843,6 +24948,9 @@ msgstr "Wyświetl zapis księgowy"
msgid "View Lists"
msgstr "Wyświetl listy"
+msgid "View Machine Time"
+msgstr "Wyświetl Czas maszynowy"
+
msgid "View maintenance dispatch"
msgstr "Wyświetl zlecenie utrzymania ruchu"
@@ -25022,6 +25130,12 @@ msgstr "Unieważnienie tej wysyłki spowoduje:"
msgid "Waited"
msgstr "Czekał"
+msgid "Waiting"
+msgstr "Oczekiwanie"
+
+msgid "Waiting for the first sync"
+msgstr "Oczekiwanie na pierwszą synchronizację"
+
msgid "Walk each area with your champion and toggle anything out of scope. Codes read Module.Area.Number (ACC.GL.01 = Accounting, General Ledger, item 1)."
msgstr "Przejdź przez każdy obszar ze swoim mistrzem i przełącz wszystko, co jest poza zakresem. Kody czytają Moduł.Obszar.Numer (ACC.GL.01 = Księgowość, Księga główna, pozycja 1)."
@@ -25528,6 +25642,9 @@ msgstr "Jaki rodzaj żądania wysłać: GET odczytuje, POST tworzy, PUT i PATCH
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Które zdarzenie produkcyjne uruchamia zegar czasu przechowywania — na przykład napełnianie, uszczelnianie lub ostateczną kontrolę jakości."
+msgid "Which operation was this?"
+msgstr "Która to była operacja?"
+
msgid "While this dispatch is open, the work center is unavailable to the schedule (until the planned end time, or until the dispatch is completed)."
msgstr "Dopóki to zlecenie utrzymania ruchu jest otwarte, stanowisko robocze jest niedostępne dla harmonogramu (do zaplanowanego czasu zakończenia lub do czasu ukończenia zlecenia)."
diff --git a/packages/locale/locales/pl/mes.po b/packages/locale/locales/pl/mes.po
index 1eb1781cc9..d2e7fba283 100644
--- a/packages/locale/locales/pl/mes.po
+++ b/packages/locale/locales/pl/mes.po
@@ -820,6 +820,9 @@ msgstr "Nadal pracuję"
msgid "Ideas, suggestions or problems?"
msgstr "Pomysły, propozycje czy problemy?"
+msgid "Idle"
+msgstr "Bezczynny"
+
msgid "Idle for"
msgstr "Bezczynny przez"
@@ -965,6 +968,9 @@ msgstr "Widok listy"
msgid "Load list"
msgstr "Załaduj listę"
+msgid "Loaded: {loadedLabel}"
+msgstr "Załadowany: {loadedLabel}"
+
msgid "Loading item details..."
msgstr "Ładowanie szczegółów pozycji..."
@@ -1286,6 +1292,9 @@ msgstr "Wymagany OEM"
msgid "of {0}"
msgstr "z {0}"
+msgid "Offline"
+msgstr "Offline"
+
msgid "Oldest first"
msgstr "Najstarsze pierwsze"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index b2508fdb30..a1ad80459f 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -542,6 +542,9 @@ msgstr "{load} na fila"
msgid "{locationName} (the lease's)"
msgstr "{locationName} (do arrendamento)"
+msgid "{mappedCount} of {totalCount} mapped"
+msgstr "{mappedCount} de {totalCount} mapeados"
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB limit"
@@ -616,6 +619,9 @@ msgstr "{passing} de {total} ativos"
msgid "{percent} picked"
msgstr "{percent} separado"
+msgid "{position} of {total}"
+msgstr "{position} de {total}"
+
msgid "{purgeRowCount, plural, one {Permanently delete # row?} other {Permanently delete # rows?}}"
msgstr "{purgeRowCount, plural, one {Excluir permanentemente # linha?} other {Excluir permanentemente # linhas?}}"
@@ -640,6 +646,9 @@ msgstr "{sectionLineCount} linhas"
msgid "{selectedCount} selected"
msgstr "{selectedCount} selecionados"
+msgid "{state} · synced {syncedAgo}"
+msgstr "{state} · sincronizado {syncedAgo}"
+
msgid "{termMonths, plural, one {# month} other {# months}}"
msgstr "{termMonths, plural, one {# mês} other {# meses}}"
@@ -2668,6 +2677,9 @@ msgstr "Anual. Começa a partir da taxa de empréstimo incremental da empresa."
msgid "Another cost center this one rolls up into, letting you nest a sub-department under its parent for hierarchical cost reporting."
msgstr "Outro centro de custo ao qual este agrega, permitindo aninhar um subcentro de custo sob seu pai para relatórios de custo hierárquicos."
+msgid "Another job or operation"
+msgstr "Outro trabalho ou operação"
+
msgid "Another spend integration is already active"
msgstr "Outra integração de despesas já está ativa"
@@ -3540,6 +3552,9 @@ msgstr "Ativos"
msgid "Assets, liabilities and equity as of a date"
msgstr "Ativos, passivos e patrimônio líquido em uma data"
+msgid "Assign machine run time that no loaded operation claimed to the right job, or dismiss it."
+msgstr "Atribua o tempo de execução de máquina que nenhuma operação carregada reivindicou para a ordem de produção correta, ou descarte-o."
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Atribua impressoras a locais. Envio, recebimento e centros de trabalho herdam o padrão do local, a menos que sejam substituídos."
@@ -5425,6 +5440,9 @@ msgstr "Conectar problema do Jira"
msgid "Connect Linear issue"
msgstr "Conectar problema do Linear"
+msgid "Connect machine monitoring devices to work centers so machine time is recorded against the operation that is loaded."
+msgstr "Conecte dispositivos de monitoramento de máquinas aos centros de trabalho para que o tempo de máquina seja registrado contra a operação que está carregada."
+
msgid "Connect Slack under Settings → Integrations first."
msgstr "Conecte Slack em Configurações → Integrações primeiro."
@@ -6001,6 +6019,15 @@ msgstr "Não foi possível criar o PDF. Tente novamente."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "Não foi possível dissolver {0}: {1} — produção já registrada"
+msgid "Could not list the provider's devices. Mapped devices are still shown."
+msgstr "Não foi possível listar os dispositivos do provedor. Os dispositivos mapeados continuam visíveis."
+
+msgid "Could not load operations"
+msgstr "Não foi possível carregar operações"
+
+msgid "Could not load what ran on {workCenterName}."
+msgstr "Não foi possível carregar o que foi executado em {workCenterName}."
+
msgid "Could not predict lead time"
msgstr "Não foi possível prever o Lead time"
@@ -7660,6 +7687,9 @@ msgstr "Detectado pelo planejador de movimento"
msgid "Developer"
msgstr "Desenvolvedor"
+msgid "Devices"
+msgstr "Dispositivos"
+
msgid "Difference"
msgstr "Diferença"
@@ -7928,6 +7958,9 @@ msgstr "Clique duas vezes para abrir esta sub-montagem"
msgid "Double-click to play this step"
msgstr "Clique duas vezes para reproduzir esta etapa"
+msgid "Down"
+msgstr "Parado"
+
msgid "Download"
msgstr "Baixar"
@@ -11028,6 +11061,9 @@ msgstr "Provedor de Identidade"
msgid "Identity provider (IdP)"
msgstr "Provedor de identidade (IdP)"
+msgid "Idle"
+msgstr "Ocioso"
+
msgid "IdP Metadata URL"
msgstr "URL de Metadados IdP"
@@ -11936,6 +11972,9 @@ msgstr "Trabalho em andamento"
msgid "Job Location"
msgstr "Localização do Trabalho"
+msgid "Job locked"
+msgstr "Trabalho bloqueado"
+
msgid "Job make method"
msgstr "Método de fabricação da ordem"
@@ -12758,6 +12797,9 @@ msgstr "Custos de máquina"
msgid "Machine Hours"
msgstr "Horas de Máquina"
+msgid "Machine monitoring"
+msgstr "Monitoramento de máquina"
+
msgid "Machine rate"
msgstr "Taxa de máquina"
@@ -12969,6 +13011,9 @@ msgstr "Mapeie seu plano de contas para o do provedor. Contas padrão de lançam
msgid "Map your current process, systems, and data"
msgstr "Mapeie seu processo, sistemas e dados atuais"
+msgid "Mapped devices"
+msgstr "Dispositivos mapeados"
+
msgid "Mapped values"
msgstr "Valores mapeados"
@@ -14340,6 +14385,12 @@ msgstr "Nenhum depósito foi recebido para este acordo."
msgid "No depreciation run happens before the cutover. Enter each asset's accumulated depreciation as of the day before the cutover."
msgstr "Nenhuma execução de depreciação ocorre antes do corte. Insira a depreciação acumulada de cada ativo a partir do dia anterior ao corte."
+msgid "No devices found"
+msgstr "Nenhum dispositivo encontrado"
+
+msgid "No devices match your search"
+msgstr "Nenhum dispositivo corresponde à sua pesquisa"
+
msgid "No dimension slots configured"
msgstr "Nenhum slot de dimensão configurado"
@@ -14475,6 +14526,9 @@ msgstr "Nenhum item"
msgid "No items have inventory activity here yet."
msgstr "Nenhum item teve atividade de inventário aqui ainda."
+msgid "No job at this location has an open operation."
+msgstr "Nenhuma ordem de produção neste local tem uma operação aberta."
+
msgid "No jobs are scheduled at this location yet — release a job to see work-center load."
msgstr "Nenhuma ordem de produção está programada neste local ainda — libere uma ordem de produção para ver a carga do centro de trabalho."
@@ -14568,6 +14622,9 @@ msgstr "Nenhuma linha aberta. Adicione um serviço para alterar."
msgid "No open memos"
msgstr "Sem memorandos abertos"
+msgid "No open operations"
+msgstr "Nenhuma operação aberta"
+
msgid "No open orders for this item are available to link."
msgstr "Nenhum pedido aberto para este item está disponível para vincular."
@@ -14932,6 +14989,9 @@ msgstr "Normal"
msgid "Not a table but a general-ledger balance: cost accumulates as job materials are issued and clears when the job is received to stock."
msgstr "Não é uma tabela, mas um saldo da razão: o custo se acumula conforme os materiais da ordem são emitidos e é zerado quando a ordem é recebida em estoque."
+msgid "Not calibrated"
+msgstr "Não calibrado"
+
msgid "Not certified"
msgstr "Não certificado"
@@ -14953,6 +15013,12 @@ msgstr "Dados de unidade insuficientes"
msgid "Not feasible"
msgstr "Não é viável"
+msgid "Not job time"
+msgstr "Não é tempo de trabalho"
+
+msgid "Not mapped"
+msgstr "Não mapeado"
+
msgid "Not now"
msgstr "Não agora"
@@ -15017,6 +15083,9 @@ msgstr "Nada concluído no MES ainda"
msgid "Nothing else at this location has stock to pull from."
msgstr "Nada mais neste local tem estoque para puxar."
+msgid "Nothing else ran on {workCenterName} that day."
+msgstr "Nada mais funcionou em {workCenterName} nesse dia."
+
msgid "Nothing here matches your search and filters."
msgstr "Nada aqui corresponde à sua pesquisa e filtros."
@@ -15074,6 +15143,9 @@ msgstr "Notificar"
msgid "Notify someone"
msgstr "Notificar alguém"
+msgid "now"
+msgstr "agora"
+
msgid "Number"
msgstr "Número"
@@ -15117,6 +15189,9 @@ msgstr "Desativado — tratado fora da sincronização"
msgid "Off — released revisions stay editable"
msgstr "Desativado — revisões lançadas permanecem editáveis"
+msgid "Offline"
+msgstr "Desconectado"
+
msgid "Offset Account"
msgstr "Conta de Compensação"
@@ -16069,6 +16144,9 @@ msgstr "Caminho"
msgid "Pause"
msgstr "Pausar"
+msgid "Paused"
+msgstr "Pausado"
+
msgid "Pay"
msgstr "Pagar"
@@ -17579,6 +17657,9 @@ msgstr "O Ramp não retornou um código de autorização"
msgid "Ramp rejected the authorization"
msgstr "O Ramp rejeitou a autorização"
+msgid "Ran at the time"
+msgstr "Funcionou nesse momento"
+
msgid "Rate"
msgstr "Taxa"
@@ -18107,6 +18188,9 @@ msgstr "Liberado com problemas: {0}"
msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
msgstr "Liberar o lote de produção libera suas ordens de produção, e cada uma deve estar pronta para o chão de fábrica."
+msgid "Reload the page to try again."
+msgstr "Recarregue a página para tentar novamente."
+
msgid "Remaining"
msgstr "Restante"
@@ -19595,6 +19679,9 @@ msgstr "Pesquisar clientes e tipos..."
msgid "Search customers or types..."
msgstr "Pesquisar clientes ou tipos..."
+msgid "Search devices"
+msgstr "Pesquisar dispositivos"
+
msgid "Search employees..."
msgstr "Pesquisar funcionários..."
@@ -19619,6 +19706,9 @@ msgstr "Pesquisar itens ou compartimentos"
msgid "Search Job"
msgstr "Pesquisar Trabalho"
+msgid "Search jobs and operations"
+msgstr "Pesquisar trabalhos e operações"
+
msgid "Search jobs or items"
msgstr "Pesquisar ordens de produção ou itens"
@@ -20945,6 +21035,9 @@ msgstr "Iniciando…"
msgid "Starts"
msgstr "Inicia"
+msgid "State"
+msgstr "Estado"
+
msgid "State / Province"
msgstr "Estado / Província"
@@ -21096,6 +21189,9 @@ msgstr "Parar Envio"
msgid "Stop using {0} in this step"
msgstr "Parar de usar {0} nesta etapa"
+msgid "Stopped"
+msgstr "Parado"
+
msgid "Stops new purchase suggestions after this date."
msgstr "Interrompe novas sugestões de compra após esta data."
@@ -22187,6 +22283,9 @@ msgstr "A alíquota padrão de imposto aplicada aos orçamentos e linhas do pedi
msgid "The department this one rolls up under for reporting and headcount hierarchies; leave empty for a top-level department."
msgstr "O departamento sob o qual este se acumula para relatórios e hierarquias de contagem de cabeçalho; deixar em branco para um departamento de nível superior."
+msgid "The device's site is in {siteTimezone}; Carbon uses {locationTimezone}"
+msgstr "O site do dispositivo está em {siteTimezone}; o Carbon usa {locationTimezone}"
+
msgid "The early hours, {name}."
msgstr "As primeiras horas, {name}."
@@ -22459,6 +22558,9 @@ msgstr "O plano de amostragem por característica do lote será recalculado a pa
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "O menor valor que este fornecedor cobrará por este processo, independentemente da quantidade; ordens de produção abaixo do volume de equilíbrio ainda custarão no mínimo este valor."
+msgid "The machine is still running. Assign this time after it stops."
+msgstr "A máquina ainda está em funcionamento. Atribua este tempo depois que ela parar."
+
msgid "The machines, cells, and stations your work runs through"
msgstr "As máquinas, células e estações por onde seu trabalho passa"
@@ -24068,6 +24170,9 @@ msgstr "Desatribuir regra"
msgid "Unassigned"
msgstr "Não atribuído"
+msgid "Unattributed Time"
+msgstr "Tempo não atribuído"
+
msgid "Unbalanced"
msgstr "Desequilibrado"
@@ -24843,6 +24948,9 @@ msgstr "Ver Lançamento"
msgid "View Lists"
msgstr "Ver Listas"
+msgid "View Machine Time"
+msgstr "Visualizar tempo de máquina"
+
msgid "View maintenance dispatch"
msgstr "Ver Ordem de Manutenção"
@@ -25022,6 +25130,12 @@ msgstr "Anular esta remessa vai:"
msgid "Waited"
msgstr "Aguardado"
+msgid "Waiting"
+msgstr "Aguardando"
+
+msgid "Waiting for the first sync"
+msgstr "Aguardando a primeira sincronização"
+
msgid "Walk each area with your champion and toggle anything out of scope. Codes read Module.Area.Number (ACC.GL.01 = Accounting, General Ledger, item 1)."
msgstr "Caminhe por cada área com seu campeão e alterne qualquer coisa fora do escopo. Os códigos lêem Módulo.Área.Número (ACC.GL.01 = Contabilidade, Livro razão, item 1)."
@@ -25528,6 +25642,9 @@ msgstr "Que tipo de solicitação enviar: GET lê algo, POST cria, PUT e PATCH a
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Qual evento de manufatura inicia o relógio de vida de prateleira — por exemplo, preenchimento, vedação ou Controle de Qualidade final."
+msgid "Which operation was this?"
+msgstr "Qual operação foi esta?"
+
msgid "While this dispatch is open, the work center is unavailable to the schedule (until the planned end time, or until the dispatch is completed)."
msgstr "Enquanto este despacho estiver aberto, o centro de trabalho estará indisponível para o cronograma (até a hora de término planejada ou até que o despacho seja concluído)."
diff --git a/packages/locale/locales/pt/mes.po b/packages/locale/locales/pt/mes.po
index 242d8d8fd4..a5e30db752 100644
--- a/packages/locale/locales/pt/mes.po
+++ b/packages/locale/locales/pt/mes.po
@@ -820,6 +820,9 @@ msgstr "Ainda Estou Trabalhando"
msgid "Ideas, suggestions or problems?"
msgstr "Ideias, sugestões ou problemas?"
+msgid "Idle"
+msgstr "Ocioso"
+
msgid "Idle for"
msgstr "Inativo por"
@@ -965,6 +968,9 @@ msgstr "Visualização em lista"
msgid "Load list"
msgstr "Carregar lista"
+msgid "Loaded: {loadedLabel}"
+msgstr "Carregado: {loadedLabel}"
+
msgid "Loading item details..."
msgstr "Carregando detalhes do item..."
@@ -1286,6 +1292,9 @@ msgstr "OEM Necessário"
msgid "of {0}"
msgstr "de {0}"
+msgid "Offline"
+msgstr "Desconectado"
+
msgid "Oldest first"
msgstr "Mais antigo primeiro"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index fcfadbd726..d4391020f9 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -542,6 +542,9 @@ msgstr "{load} в очереди"
msgid "{locationName} (the lease's)"
msgstr "{locationName} (площадка аренды)"
+msgid "{mappedCount} of {totalCount} mapped"
+msgstr "Сопоставлено {mappedCount} из {totalCount}"
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}МБ максимум"
@@ -616,6 +619,9 @@ msgstr "{passing} из {total} активов"
msgid "{percent} picked"
msgstr "{percent} отобрано"
+msgid "{position} of {total}"
+msgstr "{position} из {total}"
+
msgid "{purgeRowCount, plural, one {Permanently delete # row?} other {Permanently delete # rows?}}"
msgstr "{purgeRowCount, plural, one {Окончательно удалить # строку?} other {Окончательно удалить # строк?}}"
@@ -640,6 +646,9 @@ msgstr "{sectionLineCount} строк"
msgid "{selectedCount} selected"
msgstr "{selectedCount} выбрано"
+msgid "{state} · synced {syncedAgo}"
+msgstr "{state} · синхронизировано {syncedAgo}"
+
msgid "{termMonths, plural, one {# month} other {# months}}"
msgstr "{termMonths, plural, one {# месяц} few {# месяца} many {# месяцев} other {# месяцев}}"
@@ -2668,6 +2677,9 @@ msgstr "Ежегодно. Начинается с дополнительной
msgid "Another cost center this one rolls up into, letting you nest a sub-department under its parent for hierarchical cost reporting."
msgstr "Еще один центр затрат, в который входит этот, позволяя вложить подразделение под его родительский центр затрат для иерархической отчетности по затратам."
+msgid "Another job or operation"
+msgstr "Другое задание или операция"
+
msgid "Another spend integration is already active"
msgstr "Другая интеграция расходов уже активна"
@@ -3540,6 +3552,9 @@ msgstr "Активы"
msgid "Assets, liabilities and equity as of a date"
msgstr "Активы, обязательства и собственный капитал на определенную дату"
+msgid "Assign machine run time that no loaded operation claimed to the right job, or dismiss it."
+msgstr "Назначьте машинное время обработки, которое ни одна загруженная операция не требовала, правильному производственному заказу, или отклоните его."
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Назначьте принтеры местоположениям. Доставка, получение и рабочие центры наследуют значение по умолчанию для местоположения, если не переопределено."
@@ -5425,6 +5440,9 @@ msgstr "Подключить проблему Jira"
msgid "Connect Linear issue"
msgstr "Подключить Linear issue"
+msgid "Connect machine monitoring devices to work centers so machine time is recorded against the operation that is loaded."
+msgstr "Подключите устройства мониторинга станков к рабочим центрам, чтобы машинное время записывалось против загруженной операции."
+
msgid "Connect Slack under Settings → Integrations first."
msgstr "Сначала подключите Slack в разделе Настройки → Интеграции."
@@ -6001,6 +6019,15 @@ msgstr "Не удалось создать PDF. Попробуйте еще ра
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "Не удалось растворить {0}: {1} — производство уже записано"
+msgid "Could not list the provider's devices. Mapped devices are still shown."
+msgstr "Не удалось получить список устройств поставщика. Сопоставленные устройства по-прежнему отображаются."
+
+msgid "Could not load operations"
+msgstr "Не удалось загрузить операции"
+
+msgid "Could not load what ran on {workCenterName}."
+msgstr "Не удалось загрузить то, что выполнялось на {workCenterName}."
+
msgid "Could not predict lead time"
msgstr "Не удалось предсказать срок поставки"
@@ -7660,6 +7687,9 @@ msgstr "Обнаружено планировщиком движения"
msgid "Developer"
msgstr "Разработчик"
+msgid "Devices"
+msgstr "Устройства"
+
msgid "Difference"
msgstr "Разница"
@@ -7928,6 +7958,9 @@ msgstr "Дважды щелкните, чтобы открыть эту подс
msgid "Double-click to play this step"
msgstr "Дважды щелкните, чтобы воспроизвести этот шаг"
+msgid "Down"
+msgstr "Простой"
+
msgid "Download"
msgstr "Скачать"
@@ -11028,6 +11061,9 @@ msgstr "Поставщик удостоверений"
msgid "Identity provider (IdP)"
msgstr "Поставщик удостоверений (IdP)"
+msgid "Idle"
+msgstr "Ожидание"
+
msgid "IdP Metadata URL"
msgstr "URL метаданных IdP"
@@ -11936,6 +11972,9 @@ msgstr "Задание в работе"
msgid "Job Location"
msgstr "Местоположение задания"
+msgid "Job locked"
+msgstr "Задание заблокировано"
+
msgid "Job make method"
msgstr "Метод производства заказа"
@@ -12758,6 +12797,9 @@ msgstr "Стоимость станка"
msgid "Machine Hours"
msgstr "Часы станка"
+msgid "Machine monitoring"
+msgstr "Мониторинг станков"
+
msgid "Machine rate"
msgstr "Ставка станка"
@@ -12969,6 +13011,9 @@ msgstr "Сопоставьте ваш план счетов с планом сч
msgid "Map your current process, systems, and data"
msgstr "Сопоставьте ваш текущий процесс, системы и данные"
+msgid "Mapped devices"
+msgstr "Сопоставленные устройства"
+
msgid "Mapped values"
msgstr "Отображенные значения"
@@ -14340,6 +14385,12 @@ msgstr "Авансовый платеж не получен по этому со
msgid "No depreciation run happens before the cutover. Enter each asset's accumulated depreciation as of the day before the cutover."
msgstr "До даты перехода не производится расчет амортизации. Введите накопленную амортизацию каждого актива на день перед датой перехода."
+msgid "No devices found"
+msgstr "Устройства не найдены"
+
+msgid "No devices match your search"
+msgstr "Нет устройств, соответствующих поиску"
+
msgid "No dimension slots configured"
msgstr "Слоты измерений не настроены"
@@ -14475,6 +14526,9 @@ msgstr "Нет позиций"
msgid "No items have inventory activity here yet."
msgstr "Здесь еще нет активности с товарами."
+msgid "No job at this location has an open operation."
+msgstr "Ни один производственный заказ на этой площадке не имеет открытой операции."
+
msgid "No jobs are scheduled at this location yet — release a job to see work-center load."
msgstr "На этой площадке еще не запланированы производственные заказы — запустите производственный заказ в работу, чтобы увидеть нагрузку на рабочий центр."
@@ -14568,6 +14622,9 @@ msgstr "Нет открытых строк. Добавьте услугу, чт
msgid "No open memos"
msgstr "Нет открытых служебных записок"
+msgid "No open operations"
+msgstr "Нет открытых операций"
+
msgid "No open orders for this item are available to link."
msgstr "Нет открытых заказов для этого товара, доступных для связи."
@@ -14932,6 +14989,9 @@ msgstr "Обычный"
msgid "Not a table but a general-ledger balance: cost accumulates as job materials are issued and clears when the job is received to stock."
msgstr "Это не таблица, а остаток главной книги: себестоимость накапливается по мере выдачи материалов производственного заказа и очищается при получении заказа на запас."
+msgid "Not calibrated"
+msgstr "Не откалиброван"
+
msgid "Not certified"
msgstr "Не сертифицировано"
@@ -14953,6 +15013,12 @@ msgstr "Недостаточно данных единицы"
msgid "Not feasible"
msgstr "Невозможно выполнить"
+msgid "Not job time"
+msgstr "Не время задания"
+
+msgid "Not mapped"
+msgstr "Не сопоставлено"
+
msgid "Not now"
msgstr "Не сейчас"
@@ -15017,6 +15083,9 @@ msgstr "В MES пока ничего не завершено"
msgid "Nothing else at this location has stock to pull from."
msgstr "На этом месте больше нечего извлекать из запаса."
+msgid "Nothing else ran on {workCenterName} that day."
+msgstr "В тот день на {workCenterName} больше ничего не работало."
+
msgid "Nothing here matches your search and filters."
msgstr "Здесь нет ничего, соответствующего вашему поиску и фильтрам."
@@ -15074,6 +15143,9 @@ msgstr "Уведомить"
msgid "Notify someone"
msgstr "Уведомить кого-то"
+msgid "now"
+msgstr "сейчас"
+
msgid "Number"
msgstr "Число"
@@ -15117,6 +15189,9 @@ msgstr "Отключено — обработано вне синхрониза
msgid "Off — released revisions stay editable"
msgstr "Отключено — выпущенные ревизии остаются редактируемыми"
+msgid "Offline"
+msgstr "Отключено"
+
msgid "Offset Account"
msgstr "Счет компенсации"
@@ -16069,6 +16144,9 @@ msgstr "Путь"
msgid "Pause"
msgstr "Приостановить"
+msgid "Paused"
+msgstr "Приостановлено"
+
msgid "Pay"
msgstr "Оплатить"
@@ -17579,6 +17657,9 @@ msgstr "Ramp не вернул код авторизации"
msgid "Ramp rejected the authorization"
msgstr "Ramp отклонил авторизацию"
+msgid "Ran at the time"
+msgstr "Работало в это время"
+
msgid "Rate"
msgstr "Курс"
@@ -18107,6 +18188,9 @@ msgstr "Запущено с проблемами: {0}"
msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
msgstr "Запуск серии запускает её производственные заказы, и каждый должен быть готов к цеху."
+msgid "Reload the page to try again."
+msgstr "Перезагрузите страницу и попробуйте снова."
+
msgid "Remaining"
msgstr "Остаток"
@@ -19595,6 +19679,9 @@ msgstr "Поиск покупателей и типов..."
msgid "Search customers or types..."
msgstr "Поиск покупателей или типов..."
+msgid "Search devices"
+msgstr "Поиск устройств"
+
msgid "Search employees..."
msgstr "Поиск сотрудников..."
@@ -19619,6 +19706,9 @@ msgstr "Поиск номенклатуры или ячеек"
msgid "Search Job"
msgstr "Поиск задания"
+msgid "Search jobs and operations"
+msgstr "Поиск заданий и операций"
+
msgid "Search jobs or items"
msgstr "Поиск производственных заказов или номенклатуры"
@@ -20945,6 +21035,9 @@ msgstr "Начинаю…"
msgid "Starts"
msgstr "Начинается"
+msgid "State"
+msgstr "Состояние"
+
msgid "State / Province"
msgstr "Штат / Провинция"
@@ -21096,6 +21189,9 @@ msgstr "Остановить отправку"
msgid "Stop using {0} in this step"
msgstr "Прекратить использование {0} на этом шаге"
+msgid "Stopped"
+msgstr "Остановлено"
+
msgid "Stops new purchase suggestions after this date."
msgstr "Останавливает новые предложения по закупкам после этой даты."
@@ -22187,6 +22283,9 @@ msgstr "Налоговая ставка по умолчанию, применя
msgid "The department this one rolls up under for reporting and headcount hierarchies; leave empty for a top-level department."
msgstr "Отдел, под который это накапливается для отчетности и иерархий подсчета; оставить пусто для отдела верхнего уровня."
+msgid "The device's site is in {siteTimezone}; Carbon uses {locationTimezone}"
+msgstr "Площадка устройства находится в {siteTimezone}; Carbon использует {locationTimezone}"
+
msgid "The early hours, {name}."
msgstr "Ранние часы, {name}."
@@ -22459,6 +22558,9 @@ msgstr "План выборочного контроля для каждой х
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "Минимальная сумма, которую этот поставщик будет взимать за этот процесс, независимо от количества; производственные заказы ниже объема безубыточности все равно стоят как минимум столько."
+msgid "The machine is still running. Assign this time after it stops."
+msgstr "Машина ещё работает. Назначьте это время после её остановки."
+
msgid "The machines, cells, and stations your work runs through"
msgstr "Машины, ячейки и станции, через которые проходит ваша работа"
@@ -24068,6 +24170,9 @@ msgstr "Отменить назначение правила"
msgid "Unassigned"
msgstr "Не назначено"
+msgid "Unattributed Time"
+msgstr "Неучтённое время"
+
msgid "Unbalanced"
msgstr "Не сбалансировано"
@@ -24843,6 +24948,9 @@ msgstr "Просмотр Проводки"
msgid "View Lists"
msgstr "Просмотр списков"
+msgid "View Machine Time"
+msgstr "Просмотр машинного времени"
+
msgid "View maintenance dispatch"
msgstr "Просмотр Заявки на техобслуживание"
@@ -25022,6 +25130,12 @@ msgstr "Аннулирование этой отгрузки приведет к
msgid "Waited"
msgstr "Ожидание"
+msgid "Waiting"
+msgstr "Ожидание"
+
+msgid "Waiting for the first sync"
+msgstr "Ожидание первой синхронизации"
+
msgid "Walk each area with your champion and toggle anything out of scope. Codes read Module.Area.Number (ACC.GL.01 = Accounting, General Ledger, item 1)."
msgstr "Проведите обзор каждой области вместе с вашим лидером и отключите всё, что выходит за границы проекта. Коды читаются как Модуль.Область.Номер (ACC.GL.01 = Бухгалтерия, Главная книга, элемент 1)."
@@ -25528,6 +25642,9 @@ msgstr "Какой вид запроса отправить: GET читает ч
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Какое производственное событие запускает часы срока хранения — например, заполнение, уплотнение или окончательный контроль качества."
+msgid "Which operation was this?"
+msgstr "Какая это была операция?"
+
msgid "While this dispatch is open, the work center is unavailable to the schedule (until the planned end time, or until the dispatch is completed)."
msgstr "Пока это отправление открыто, рабочий центр недоступен для расписания (до запланированного времени окончания или до завершения отправления)."
diff --git a/packages/locale/locales/ru/mes.po b/packages/locale/locales/ru/mes.po
index 1f826c15d9..a053d9f9d8 100644
--- a/packages/locale/locales/ru/mes.po
+++ b/packages/locale/locales/ru/mes.po
@@ -820,6 +820,9 @@ msgstr "Я ещё работаю"
msgid "Ideas, suggestions or problems?"
msgstr "Идеи, предложения или проблемы?"
+msgid "Idle"
+msgstr "Ожидание"
+
msgid "Idle for"
msgstr "Простой в течение"
@@ -965,6 +968,9 @@ msgstr "Вид списка"
msgid "Load list"
msgstr "Загрузить список"
+msgid "Loaded: {loadedLabel}"
+msgstr "Загружена: {loadedLabel}"
+
msgid "Loading item details..."
msgstr "Загрузка данных номенклатуры..."
@@ -1286,6 +1292,9 @@ msgstr "Требуется OEM"
msgid "of {0}"
msgstr "из {0}"
+msgid "Offline"
+msgstr "Отключено"
+
msgid "Oldest first"
msgstr "Самые старые первыми"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index e0c75eda13..2743004e29 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -542,6 +542,9 @@ msgstr "{load} kuyruğunda"
msgid "{locationName} (the lease's)"
msgstr "{locationName} (kiralamanın)"
+msgid "{mappedCount} of {totalCount} mapped"
+msgstr "{totalCount} cihazdan {mappedCount} eşlendi"
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB sınırı"
@@ -616,6 +619,9 @@ msgstr "{passing} / {total} varlık"
msgid "{percent} picked"
msgstr "{percent} toplandı"
+msgid "{position} of {total}"
+msgstr "{position} / {total}"
+
msgid "{purgeRowCount, plural, one {Permanently delete # row?} other {Permanently delete # rows?}}"
msgstr "{purgeRowCount, plural, one {# satırı kalıcı olarak sil?} other {# satırı kalıcı olarak sil?}}"
@@ -640,6 +646,9 @@ msgstr "{sectionLineCount} satır"
msgid "{selectedCount} selected"
msgstr "{selectedCount} seçildi"
+msgid "{state} · synced {syncedAgo}"
+msgstr "{state} · {syncedAgo} eşitlendi"
+
msgid "{termMonths, plural, one {# month} other {# months}}"
msgstr "{termMonths, plural, one {# ay} other {# ay}}"
@@ -2668,6 +2677,9 @@ msgstr "Yıllık. Şirketin marjinal borçlanma oranından başlar"
msgid "Another cost center this one rolls up into, letting you nest a sub-department under its parent for hierarchical cost reporting."
msgstr "Bu toplandığı başka bir maliyet merkezi, hiyerarşik maliyet raporlaması için bir alt maliyet merkezini ana kütesinin altında iç içe geçirmenizi sağlar."
+msgid "Another job or operation"
+msgstr "Başka bir iş veya operasyon"
+
msgid "Another spend integration is already active"
msgstr "Başka bir harcama entegrasyonu zaten etkin"
@@ -3540,6 +3552,9 @@ msgstr "Varlıklar"
msgid "Assets, liabilities and equity as of a date"
msgstr "Bir tarih itibariyle varlıklar, yükümlülükler ve özkaynak"
+msgid "Assign machine run time that no loaded operation claimed to the right job, or dismiss it."
+msgstr "Yüklü bir operasyonun talep etmediği makine süresini doğru işe atayın veya göz ardı edin."
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "Yazıcıları konumlara atayın. Sevkiyat, kabul ve iş merkezleri, geçersiz kılınmadıkça konum varsayılanını miras alır."
@@ -5425,6 +5440,9 @@ msgstr "Jira sorununu bağla"
msgid "Connect Linear issue"
msgstr "Linear sorununu bağla"
+msgid "Connect machine monitoring devices to work centers so machine time is recorded against the operation that is loaded."
+msgstr "Makine izleme cihazlarını iş merkezlerine bağlayın, böylece makine süresi yüklü operasyona karşı kaydedilsin."
+
msgid "Connect Slack under Settings → Integrations first."
msgstr "Önce Ayarlar → Entegrasyonlar altında Slack'i bağlayın."
@@ -6001,6 +6019,15 @@ msgstr "PDF oluşturulamadı. Lütfen tekrar deneyin."
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "{0} çözülemedi: {1} — üretim zaten kaydedildi"
+msgid "Could not list the provider's devices. Mapped devices are still shown."
+msgstr "Sağlayıcının cihazları listelenemedi. Eşlenen cihazlar yine de gösteriliyor."
+
+msgid "Could not load operations"
+msgstr "Operasyonlar yüklenemedi"
+
+msgid "Could not load what ran on {workCenterName}."
+msgstr "{workCenterName} üzerinde çalışan operasyonlar yüklenemedi."
+
msgid "Could not predict lead time"
msgstr "Tedarik süresi tahmin edilemedi"
@@ -7660,6 +7687,9 @@ msgstr "Hareket planlayıcısı tarafından algılandı"
msgid "Developer"
msgstr "Geliştirici"
+msgid "Devices"
+msgstr "Cihazlar"
+
msgid "Difference"
msgstr "Fark"
@@ -7928,6 +7958,9 @@ msgstr "Bu alt montajı açmak için çift tıkla"
msgid "Double-click to play this step"
msgstr "Bu adımı oynatmak için çift tıklayın"
+msgid "Down"
+msgstr "Arızalı"
+
msgid "Download"
msgstr "İndir"
@@ -11028,6 +11061,9 @@ msgstr "Kimlik Sağlayıcı"
msgid "Identity provider (IdP)"
msgstr "Kimlik Sağlayıcı (IdP)"
+msgid "Idle"
+msgstr "Boş"
+
msgid "IdP Metadata URL"
msgstr "IdP Meta Veri URL'si"
@@ -11936,6 +11972,9 @@ msgstr "İş devam ediyor"
msgid "Job Location"
msgstr "İş Yeri Konumu"
+msgid "Job locked"
+msgstr "İş kilitli"
+
msgid "Job make method"
msgstr "İş emri üretim yöntemi"
@@ -12758,6 +12797,9 @@ msgstr "Makine Maliyetleri"
msgid "Machine Hours"
msgstr "Makine Saatleri"
+msgid "Machine monitoring"
+msgstr "Makine izleme"
+
msgid "Machine rate"
msgstr "Makine oranı"
@@ -12969,6 +13011,9 @@ msgstr "Hesap planınızı sağlayıcının hesap planına eşleyin. Muhasebele
msgid "Map your current process, systems, and data"
msgstr "Mevcut sürecinizi, sistemlerinizi ve verilerinizi eşleyin"
+msgid "Mapped devices"
+msgstr "Eşlenen cihazlar"
+
msgid "Mapped values"
msgstr "Eşlenen değerler"
@@ -14340,6 +14385,12 @@ msgstr "Bu anlaşma için depozito alınmamıştır."
msgid "No depreciation run happens before the cutover. Enter each asset's accumulated depreciation as of the day before the cutover."
msgstr "Kesme tarihinden önce amortisman çalışması yapılmaz. Her varlığın kesme tarihinden bir gün önceki birikmiş amortismanını girin."
+msgid "No devices found"
+msgstr "Cihaz bulunamadı"
+
+msgid "No devices match your search"
+msgstr "Aramanızla eşleşen cihaz yok"
+
msgid "No dimension slots configured"
msgstr "Yapılandırılmış boyut yuvası yok"
@@ -14475,6 +14526,9 @@ msgstr "Öğe yok"
msgid "No items have inventory activity here yet."
msgstr "Burada henüz hiçbir maddenin envanter hareketi yok."
+msgid "No job at this location has an open operation."
+msgstr "Bu lokasyonda açık bir operasyonu olan İş emri yok."
+
msgid "No jobs are scheduled at this location yet — release a job to see work-center load."
msgstr "Bu Lokasyonda henüz İş emri planlanmamış — çalışma merkezinin yükünü görmek için İş emrini Serbest bırakın."
@@ -14568,6 +14622,9 @@ msgstr "Açık satır yok. Değişiklik için bir hizmet ekleyin."
msgid "No open memos"
msgstr "Açık muhasebe notları yok"
+msgid "No open operations"
+msgstr "Açık operasyon yok"
+
msgid "No open orders for this item are available to link."
msgstr "Bu Stok kartı için bağlantı kurmak amacıyla Açık siparişler bulunmamaktadır."
@@ -14932,6 +14989,9 @@ msgstr "Normal"
msgid "Not a table but a general-ledger balance: cost accumulates as job materials are issued and clears when the job is received to stock."
msgstr "Bir tablo değil, büyük defter bakiyesi: iş emri malzemeleri çıktıkça maliyet birikir ve iş emri stoka alındığında temizlenir."
+msgid "Not calibrated"
+msgstr "Kalibre edilmedi"
+
msgid "Not certified"
msgstr "Sertifikalı değil"
@@ -14953,6 +15013,12 @@ msgstr "Yetersiz adet verisi"
msgid "Not feasible"
msgstr "Gerçekleştirilemez"
+msgid "Not job time"
+msgstr "İş süresi değil"
+
+msgid "Not mapped"
+msgstr "Eşlenmedi"
+
msgid "Not now"
msgstr "Şimdi değil"
@@ -15017,6 +15083,9 @@ msgstr "MES'te henüz hiçbir şey tamamlanmadı"
msgid "Nothing else at this location has stock to pull from."
msgstr "Bu konumda çekilecek başka hiçbir stok yok."
+msgid "Nothing else ran on {workCenterName} that day."
+msgstr "O gün {workCenterName} üzerinde başka bir şey çalışmadı."
+
msgid "Nothing here matches your search and filters."
msgstr "Burada arama ve filtrelerinizle eşleşen hiçbir şey yok."
@@ -15074,6 +15143,9 @@ msgstr "Bildir"
msgid "Notify someone"
msgstr "Birisine bildir"
+msgid "now"
+msgstr "şimdi"
+
msgid "Number"
msgstr "Numara"
@@ -15117,6 +15189,9 @@ msgstr "Kapalı — senkronizasyon dışında işlenir"
msgid "Off — released revisions stay editable"
msgstr "Kapalı — yayınlanan revizyonlar düzenlenebilir kalır"
+msgid "Offline"
+msgstr "Çevrimdışı"
+
msgid "Offset Account"
msgstr "Karşı Hesap"
@@ -16069,6 +16144,9 @@ msgstr "Yol"
msgid "Pause"
msgstr "Duraklat"
+msgid "Paused"
+msgstr "Durdurulmuş"
+
msgid "Pay"
msgstr "Öde"
@@ -17579,6 +17657,9 @@ msgstr "Ramp bir yetkilendirme kodu döndürmedi"
msgid "Ramp rejected the authorization"
msgstr "Ramp yetkilendirmeyi reddetti"
+msgid "Ran at the time"
+msgstr "O sırada çalıştı"
+
msgid "Rate"
msgstr "Kur"
@@ -18107,6 +18188,9 @@ msgstr "Sorunlarla serbest bırakıldı: {0}"
msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
msgstr "Partiyi serbest bırakmak iş emirlerini serbest bırakır ve her birinin atölye için hazır olması gerekir."
+msgid "Reload the page to try again."
+msgstr "Sayfayı yeniden yükleyin ve tekrar deneyin."
+
msgid "Remaining"
msgstr "Kalan"
@@ -19595,6 +19679,9 @@ msgstr "Müşterileri ve türleri ara..."
msgid "Search customers or types..."
msgstr "Müşterileri veya türleri arayın..."
+msgid "Search devices"
+msgstr "Cihaz ara"
+
msgid "Search employees..."
msgstr "Çalışanları ara..."
@@ -19619,6 +19706,9 @@ msgstr "Stok kartlarını veya gözleri ara"
msgid "Search Job"
msgstr "İş Ara"
+msgid "Search jobs and operations"
+msgstr "İş ve operasyon ara"
+
msgid "Search jobs or items"
msgstr "İş emirlerini veya Stok kartlarını Ara"
@@ -20945,6 +21035,9 @@ msgstr "Başlanıyor…"
msgid "Starts"
msgstr "Başlar"
+msgid "State"
+msgstr "Durum"
+
msgid "State / Province"
msgstr "Eyalet / İl"
@@ -21096,6 +21189,9 @@ msgstr "Gönderimi Durdur"
msgid "Stop using {0} in this step"
msgstr "Bu adımda {0} kullanmayı durdur"
+msgid "Stopped"
+msgstr "Durdu"
+
msgid "Stops new purchase suggestions after this date."
msgstr "Bu tarihten sonra yeni satın alma önerilerini durdurur."
@@ -22187,6 +22283,9 @@ msgstr "Bu müşterinin alıntı ve satış siparişi satırlarına uygulanan va
msgid "The department this one rolls up under for reporting and headcount hierarchies; leave empty for a top-level department."
msgstr "Bu departmanın raporlama ve personel sayısı hiyerarşisinde bağlı olduğu departman; üst seviye bir departman için boş bırakın."
+msgid "The device's site is in {siteTimezone}; Carbon uses {locationTimezone}"
+msgstr "Cihazın sahası {siteTimezone} saat diliminde; Carbon {locationTimezone} kullanıyor"
+
msgid "The early hours, {name}."
msgstr "Sabah saatleri, {name}."
@@ -22459,6 +22558,9 @@ msgstr "Lotun her karakteristiği için örnekleme planı seçilen belgeden yeni
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "Bu Tedarikçinin bu Proses için Miktar ne olursa olsun talep edebileceği en düşük tutar; başabaş hacminin altındaki İş emirleri en az bu tutardan maliyetlidir."
+msgid "The machine is still running. Assign this time after it stops."
+msgstr "Makine hâlâ çalışıyor. Bu süreyi makine durduktan sonra atayın."
+
msgid "The machines, cells, and stations your work runs through"
msgstr "Çalışmanızın geçtiği makineler, hücreler ve istasyonlar"
@@ -24068,6 +24170,9 @@ msgstr "Kuralı kaldır"
msgid "Unassigned"
msgstr "Atanmamış"
+msgid "Unattributed Time"
+msgstr "Atanmamış Süre"
+
msgid "Unbalanced"
msgstr "Dengesiz"
@@ -24843,6 +24948,9 @@ msgstr "Yevmiye kaydını görüntüle"
msgid "View Lists"
msgstr "Listeleri Görüntüle"
+msgid "View Machine Time"
+msgstr "Makine Süresini Görüntüle"
+
msgid "View maintenance dispatch"
msgstr "Bakım emrini görüntüle"
@@ -25022,6 +25130,12 @@ msgstr "Bu sevkiyatı geçersiz kılmak şunları yapacaktır:"
msgid "Waited"
msgstr "Beklemede"
+msgid "Waiting"
+msgstr "Beklemede"
+
+msgid "Waiting for the first sync"
+msgstr "İlk eşitleme bekleniyor"
+
msgid "Walk each area with your champion and toggle anything out of scope. Codes read Module.Area.Number (ACC.GL.01 = Accounting, General Ledger, item 1)."
msgstr "Şampiyon ile her alanı gözden geçirin ve kapsam dışında kalan öğeleri seçin/seçimi kaldırın. Kodlar Modül.Alan.Numara olarak okunur (ACC.GL.01 = Muhasebe, Büyük defter, öğe 1)."
@@ -25528,6 +25642,9 @@ msgstr "Gönderilecek isteğin türü: GET bir şey okur, POST oluşturur, PUT v
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "Hangi üretim olayı raf ömrü saatini başlatır — örneğin, doldurma, mühürleme veya nihai QC."
+msgid "Which operation was this?"
+msgstr "Bu hangi operasyondu?"
+
msgid "While this dispatch is open, the work center is unavailable to the schedule (until the planned end time, or until the dispatch is completed)."
msgstr "Bu sevkiyat açık olsa da, iş merkezi plana kullanılamaz (planlanan bitiş saatine veya sevkiyat tamamlanana kadar)."
diff --git a/packages/locale/locales/tr/mes.po b/packages/locale/locales/tr/mes.po
index 89e06422c3..2554a9019e 100644
--- a/packages/locale/locales/tr/mes.po
+++ b/packages/locale/locales/tr/mes.po
@@ -820,6 +820,9 @@ msgstr "Hala Çalışıyorum"
msgid "Ideas, suggestions or problems?"
msgstr "Fikirler, öneriler veya sorunlar?"
+msgid "Idle"
+msgstr "Boş"
+
msgid "Idle for"
msgstr "Boş olma süresi"
@@ -965,6 +968,9 @@ msgstr "Liste görünümü"
msgid "Load list"
msgstr "Listeyi yükle"
+msgid "Loaded: {loadedLabel}"
+msgstr "Yüklendi: {loadedLabel}"
+
msgid "Loading item details..."
msgstr "Ürün detayları yükleniyor..."
@@ -1286,6 +1292,9 @@ msgstr "OEM Gerekli"
msgid "of {0}"
msgstr "/{0}"
+msgid "Offline"
+msgstr "Çevrimdışı"
+
msgid "Oldest first"
msgstr "En eski önce"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index e9943fd4aa..e1e0e9333a 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -542,6 +542,9 @@ msgstr "{load} 在队列中"
msgid "{locationName} (the lease's)"
msgstr "{locationName}(该租赁的地点)"
+msgid "{mappedCount} of {totalCount} mapped"
+msgstr "已映射 {mappedCount} / {totalCount}"
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB 限制"
@@ -616,6 +619,9 @@ msgstr "{passing} 项,共 {total} 项资产"
msgid "{percent} picked"
msgstr "{percent}已拣货"
+msgid "{position} of {total}"
+msgstr "{position}/{total}"
+
msgid "{purgeRowCount, plural, one {Permanently delete # row?} other {Permanently delete # rows?}}"
msgstr "{purgeRowCount, plural, one {永久删除 # 行?} other {永久删除 # 行?}}"
@@ -640,6 +646,9 @@ msgstr "{sectionLineCount} 行"
msgid "{selectedCount} selected"
msgstr "{selectedCount} 已选择"
+msgid "{state} · synced {syncedAgo}"
+msgstr "{state} · {syncedAgo} 已同步"
+
msgid "{termMonths, plural, one {# month} other {# months}}"
msgstr "{termMonths, plural, one {# 个月} other {# 个月}}"
@@ -2668,6 +2677,9 @@ msgstr "每年。从公司的增量借款利率开始"
msgid "Another cost center this one rolls up into, letting you nest a sub-department under its parent for hierarchical cost reporting."
msgstr "该成本中心所归属的另一个成本中心,允许您在其父级下嵌套子成本中心,以进行分层成本报告。"
+msgid "Another job or operation"
+msgstr "其他工单或工序"
+
msgid "Another spend integration is already active"
msgstr "另一个支出集成已处于活跃状态"
@@ -3540,6 +3552,9 @@ msgstr "资产"
msgid "Assets, liabilities and equity as of a date"
msgstr "某一日期的资产、负债和所有者权益"
+msgid "Assign machine run time that no loaded operation claimed to the right job, or dismiss it."
+msgstr "将未被加载工序认领的机器工时分配给正确的工单,或将其放弃。"
+
msgid "Assign printers to locations. Shipping, receiving, and work centers inherit the location default unless overridden."
msgstr "将打印机分配到位置。运输、接收和工作中心继承位置默认值,除非被覆盖。"
@@ -5425,6 +5440,9 @@ msgstr "连接 Jira 问题"
msgid "Connect Linear issue"
msgstr "连接 Linear 问题"
+msgid "Connect machine monitoring devices to work centers so machine time is recorded against the operation that is loaded."
+msgstr "将机器监测设备连接到工作中心,以便将机器工时记录到已加载的工序。"
+
msgid "Connect Slack under Settings → Integrations first."
msgstr "先在设置 → 集成中连接 Slack。"
@@ -6001,6 +6019,15 @@ msgstr "无法生成 PDF。请重试。"
msgid "Could not dissolve {0}: {1} — production already recorded"
msgstr "无法解散 {0}: {1} — 生产已记录"
+msgid "Could not list the provider's devices. Mapped devices are still shown."
+msgstr "无法列出提供商的设备。已映射的设备仍会显示。"
+
+msgid "Could not load operations"
+msgstr "无法加载工序"
+
+msgid "Could not load what ran on {workCenterName}."
+msgstr "无法加载在 {workCenterName} 上运行的内容。"
+
msgid "Could not predict lead time"
msgstr "无法预测提前期"
@@ -7660,6 +7687,9 @@ msgstr "由运动规划器检测"
msgid "Developer"
msgstr "开发人员"
+msgid "Devices"
+msgstr "设备"
+
msgid "Difference"
msgstr "差异"
@@ -7928,6 +7958,9 @@ msgstr "双击以打开此子装配"
msgid "Double-click to play this step"
msgstr "双击播放此步骤"
+msgid "Down"
+msgstr "停机"
+
msgid "Download"
msgstr "下载"
@@ -11028,6 +11061,9 @@ msgstr "身份提供商"
msgid "Identity provider (IdP)"
msgstr "身份提供商 (IdP)"
+msgid "Idle"
+msgstr "空闲"
+
msgid "IdP Metadata URL"
msgstr "IdP 元数据 URL"
@@ -11936,6 +11972,9 @@ msgstr "作业进行中"
msgid "Job Location"
msgstr "工作地点"
+msgid "Job locked"
+msgstr "工单已锁定"
+
msgid "Job make method"
msgstr "工单制造方法"
@@ -12758,6 +12797,9 @@ msgstr "机器成本"
msgid "Machine Hours"
msgstr "机器小时"
+msgid "Machine monitoring"
+msgstr "机器监测"
+
msgid "Machine rate"
msgstr "机器费率"
@@ -12969,6 +13011,9 @@ msgstr "将您的会计科目表映射到提供商的。过账默认账户和费
msgid "Map your current process, systems, and data"
msgstr "映射您当前的流程、系统和数据"
+msgid "Mapped devices"
+msgstr "已映射的设备"
+
msgid "Mapped values"
msgstr "已映射的值"
@@ -14340,6 +14385,12 @@ msgstr "未收到此协议的押金。"
msgid "No depreciation run happens before the cutover. Enter each asset's accumulated depreciation as of the day before the cutover."
msgstr "在截断前不进行折旧计算。输入每项资产截断前一天的累计折旧。"
+msgid "No devices found"
+msgstr "未找到设备"
+
+msgid "No devices match your search"
+msgstr "没有与搜索匹配的设备"
+
msgid "No dimension slots configured"
msgstr "未配置维度插槽"
@@ -14475,6 +14526,9 @@ msgstr "没有物料"
msgid "No items have inventory activity here yet."
msgstr "此处尚无物料库存活动。"
+msgid "No job at this location has an open operation."
+msgstr "此地点没有工单有未结工序。"
+
msgid "No jobs are scheduled at this location yet — release a job to see work-center load."
msgstr "此地点还没有排程工单——下达工单以查看工作中心负荷。"
@@ -14568,6 +14622,9 @@ msgstr "没有未结行。添加服务以进行修改。"
msgid "No open memos"
msgstr "无未结单据"
+msgid "No open operations"
+msgstr "没有未结工序"
+
msgid "No open orders for this item are available to link."
msgstr "此物料没有未结订单可供链接。"
@@ -14932,6 +14989,9 @@ msgstr "正常"
msgid "Not a table but a general-ledger balance: cost accumulates as job materials are issued and clears when the job is received to stock."
msgstr "不是表,而是总账余额:成本随着工单物料的领料而累积,工单收到库存时清空。"
+msgid "Not calibrated"
+msgstr "未校准"
+
msgid "Not certified"
msgstr "未认证"
@@ -14953,6 +15013,12 @@ msgstr "单位数据不足"
msgid "Not feasible"
msgstr "不可行"
+msgid "Not job time"
+msgstr "不是工单时间"
+
+msgid "Not mapped"
+msgstr "未映射"
+
msgid "Not now"
msgstr "暂不"
@@ -15017,6 +15083,9 @@ msgstr "MES中尚未完成任何内容"
msgid "Nothing else at this location has stock to pull from."
msgstr "此位置没有其他可提取的库存。"
+msgid "Nothing else ran on {workCenterName} that day."
+msgstr "当天 {workCenterName} 上没有其他运行记录。"
+
msgid "Nothing here matches your search and filters."
msgstr "没有与您的搜索和过滤条件匹配的内容。"
@@ -15074,6 +15143,9 @@ msgstr "通知"
msgid "Notify someone"
msgstr "通知某人"
+msgid "now"
+msgstr "现在"
+
msgid "Number"
msgstr "数字"
@@ -15117,6 +15189,9 @@ msgstr "关闭 — 在同步外处理"
msgid "Off — released revisions stay editable"
msgstr "关闭 — 已下达修订版保持可编辑"
+msgid "Offline"
+msgstr "离线"
+
msgid "Offset Account"
msgstr "抵消账户"
@@ -16069,6 +16144,9 @@ msgstr "路径"
msgid "Pause"
msgstr "暂停"
+msgid "Paused"
+msgstr "已暂停"
+
msgid "Pay"
msgstr "支付"
@@ -17579,6 +17657,9 @@ msgstr "Ramp 未返回授权代码"
msgid "Ramp rejected the authorization"
msgstr "Ramp 拒绝了授权"
+msgid "Ran at the time"
+msgstr "当时在运行"
+
msgid "Rate"
msgstr "汇率"
@@ -18107,6 +18188,9 @@ msgstr "已下达,存在问题:{0}"
msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."
msgstr "下达生产批次会下达其工单,每个工单都必须为车间做好准备。"
+msgid "Reload the page to try again."
+msgstr "重新加载页面以重试。"
+
msgid "Remaining"
msgstr "剩余"
@@ -19595,6 +19679,9 @@ msgstr "搜索客户和类型..."
msgid "Search customers or types..."
msgstr "搜索客户或类型..."
+msgid "Search devices"
+msgstr "搜索设备"
+
msgid "Search employees..."
msgstr "搜索员工..."
@@ -19619,6 +19706,9 @@ msgstr "搜索物料或料箱"
msgid "Search Job"
msgstr "搜索任务"
+msgid "Search jobs and operations"
+msgstr "搜索工单和工序"
+
msgid "Search jobs or items"
msgstr "搜索工单或物品"
@@ -20945,6 +21035,9 @@ msgstr "正在启动…"
msgid "Starts"
msgstr "开始"
+msgid "State"
+msgstr "状态"
+
msgid "State / Province"
msgstr "州/省"
@@ -21096,6 +21189,9 @@ msgstr "停止发货"
msgid "Stop using {0} in this step"
msgstr "在此步骤中停止使用 {0}"
+msgid "Stopped"
+msgstr "已停止"
+
msgid "Stops new purchase suggestions after this date."
msgstr "在此日期之后停止新采购建议。"
@@ -22187,6 +22283,9 @@ msgstr "适用于此客户的报价和销售订单行的默认税率,在每行
msgid "The department this one rolls up under for reporting and headcount hierarchies; leave empty for a top-level department."
msgstr "该部门汇总用于报告和人员数量层级的部门;对于顶级部门,请留空。"
+msgid "The device's site is in {siteTimezone}; Carbon uses {locationTimezone}"
+msgstr "设备所在站点位于 {siteTimezone};Carbon 使用 {locationTimezone}"
+
msgid "The early hours, {name}."
msgstr "早晨时刻,{name}。"
@@ -22459,6 +22558,9 @@ msgstr "该批次各特征的抽样方案将从所选文件重新确定。"
msgid "The lowest amount this supplier will charge for this process, regardless of quantity; jobs below the breakeven volume still cost at least this much."
msgstr "此供应商对此工艺收费的最低金额,无论数量如何;低于盈亏平衡量的工单仍至少成本此金额。"
+msgid "The machine is still running. Assign this time after it stops."
+msgstr "机器仍在运行。请在停止后分配此时间。"
+
msgid "The machines, cells, and stations your work runs through"
msgstr "您的工作运行所经过的机器、单元和工作站"
@@ -24068,6 +24170,9 @@ msgstr "取消分配规则"
msgid "Unassigned"
msgstr "未分配"
+msgid "Unattributed Time"
+msgstr "未归属时间"
+
msgid "Unbalanced"
msgstr "不平衡"
@@ -24843,6 +24948,9 @@ msgstr "查看日记账分录"
msgid "View Lists"
msgstr "查看列表"
+msgid "View Machine Time"
+msgstr "查看机器工时"
+
msgid "View maintenance dispatch"
msgstr "查看维护工单"
@@ -25022,6 +25130,12 @@ msgstr "作废此发货将:"
msgid "Waited"
msgstr "已等待"
+msgid "Waiting"
+msgstr "等待中"
+
+msgid "Waiting for the first sync"
+msgstr "正在等待首次同步"
+
msgid "Walk each area with your champion and toggle anything out of scope. Codes read Module.Area.Number (ACC.GL.01 = Accounting, General Ledger, item 1)."
msgstr "与您的冠军一起查看每个区域,切换任何超出范围的内容。代码格式为 Module.Area.Number(ACC.GL.01 = 会计、总账、项目 1)。"
@@ -25528,6 +25642,9 @@ msgstr "发送哪种类型的请求:GET 读取内容,POST 创建,PUT 和 P
msgid "Which manufacturing event starts the shelf-life clock — for example, fill, seal, or final QC."
msgstr "哪个制造事件启动保质期时钟 — 例如填充、密封或最终QC。"
+msgid "Which operation was this?"
+msgstr "这是哪个工序?"
+
msgid "While this dispatch is open, the work center is unavailable to the schedule (until the planned end time, or until the dispatch is completed)."
msgstr "当此派遣打开时,工作中心对计划不可用(直到计划结束时间或派遣完成)。"
diff --git a/packages/locale/locales/zh/mes.po b/packages/locale/locales/zh/mes.po
index 05a1c5d7f6..e60ca0908c 100644
--- a/packages/locale/locales/zh/mes.po
+++ b/packages/locale/locales/zh/mes.po
@@ -820,6 +820,9 @@ msgstr "我还在工作"
msgid "Ideas, suggestions or problems?"
msgstr "有想法、建议或问题?"
+msgid "Idle"
+msgstr "空闲"
+
msgid "Idle for"
msgstr "闲置时间"
@@ -965,6 +968,9 @@ msgstr "列表视图"
msgid "Load list"
msgstr "加载列表"
+msgid "Loaded: {loadedLabel}"
+msgstr "已加载: {loadedLabel}"
+
msgid "Loading item details..."
msgstr "正在加载物料详情..."
@@ -1286,6 +1292,9 @@ msgstr "需要 OEM"
msgid "of {0}"
msgstr "/"
+msgid "Offline"
+msgstr "离线"
+
msgid "Oldest first"
msgstr "最早优先"
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index f6ca039afa..8e62499186 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -41,6 +41,7 @@ export * from "./hash";
export * from "./headers";
export * from "./intercompany-capture";
export * from "./items";
+export * from "./job-status";
export * from "./journal-dimensions";
export * from "./keyboard";
export * from "./labels";
diff --git a/packages/utils/src/job-status.ts b/packages/utils/src/job-status.ts
new file mode 100644
index 0000000000..86add22f04
--- /dev/null
+++ b/packages/utils/src/job-status.ts
@@ -0,0 +1,16 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+/** A job in one of these statuses is locked: no edits and no more time. */
+export const JOB_LOCKED_STATUSES = [
+ "Completed",
+ "Closed",
+ "Cancelled"
+] as const;
+
+export function isJobLocked(status: string | null | undefined): boolean {
+ return JOB_LOCKED_STATUSES.includes(
+ status as (typeof JOB_LOCKED_STATUSES)[number]
+ );
+}