Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(production): capacity planning — holidays, shift replans, work-center write-back, qualification expiry
naveenkashfd41f35a0f3e
diff --git a/.ai/lessons.md b/.ai/lessons.mdindex 877e386216..de9ae5a8e0 100644--- a/.ai/lessons.md+++ b/.ai/lessons.md@@ -4099,3 +4099,23 @@ The write was then removed (nothing reads it), so the rail always starts collaps**Rule:** Do not promise a closed-app badge on macOS Chrome. Test the badge with the app hidden (⌘H), not closed, and test the closed case on a platform meant to keep it (an iPhone Home Screen app) before calling it broken.**Applies to:** `apps/erp/app/hooks/useAppBadge.ts`, `apps/erp/public/service-worker.js`, the `send-push` badge count.++## A scheduler decision is only stored when every write-back guard agrees++**Context:** The scheduler balances an operation that has not started onto any work center of its process (F10, 2026-10-26).++**Problem:** Two separate "never overwrite a stored work center" guards sat between the decision and the database: one in `applyWorkCenterSelections`, one in the engine's `buildWrites`. Fixing the first one alone changed nothing in the database. The `capacityReservation` row named the chosen station while `jobOperation.workCenterId` kept the old one, and every unit test still passed.++**Rule:** When you change what the scheduler decides, trace the value to the write (`placementWrites`, `run-overlay.ts`). Test the decision and the write together, then remove the write fix and confirm a test goes red.++**Applies to:** `packages/planning/src/scheduling/` — `apply-work-center-selections.ts`, `run-overlay.ts`, `scheduling-engine.ts`.++## An SQL test that inserts an employee needs the company's root group first++**Context:** Seeding employees in a `supabase/tests/*.test.sql` file (`rpc-privileges.test.sql`, 2026-10-26).++**Problem:** The `employee` insert fires the employee-type group interceptor, which needs the company's "All Employees" root group. A test company made by hand has no root group, so the insert fails. `SET session_replication_role` is not permitted there.++**Rule:** Insert the root group first, with the id `getGroupId` builds: `'00000000-0000-' || substr(c,1,4) || '-' || substr(c,5,4) || '-' || substr(c,9,12)` for company id `c`. Then insert the employee type and the employee.++**Applies to:** SQL tests under `packages/database/supabase/tests/` that create employees.diff --git a/.ai/plans/2026-10-26-capacity-planning-high-fixes.md b/.ai/plans/2026-10-26-capacity-planning-high-fixes.mdnew file mode 100644index 0000000000..2b7831daf6--- /dev/null+++ b/.ai/plans/2026-10-26-capacity-planning-high-fixes.md@@ -0,0 +1,93 @@+# Capacity planning: fix the 8 high findings++Source: the browser test of 2026-10-24 (findings F1, F5, F6, F10, F12, F16, F26, F27).+Decisions from the user on 2026-10-26:++- Scope is the 8 high findings only.+- F10: save the work center that the scheduler picks.+- F26: change the `users_for_groups` guard.+- F27: stop the data loss and correct the help text. No scheduler work for contractors.++Each fix gets a test at its seam (see `.claude/rules/testing.md`), then a browser check.++## Tasks++- [x] **F6 — a batch is placed against bookings that the run will replace.**+ 1. In `packages/planning/src/scheduling/batch-scheduler.ts`, add a pure function `batchBlockingReservations`.+ It keeps the bookings that block a released batch.+ It drops this location's own batch rows and every non-batch row of a job that the run re-plans.+ 2. Call it from `placeReleasedBatches` with `orderedJobIds`.+ 3. Test: `batch-scheduler.test.ts`.+- [x] **F10 — the chosen work center is not saved.**+ 1. Add `isOperationStarted(op)` to `apply-work-center-selections.ts`. The selector uses it too.+ 2. `applyWorkCenterSelections` writes the selected work center when the op is placed and not started.+ A started op and a placeholder keep the stored work center.+ 3. `buildWrites` writes the applied work center.+ 4. Test: `apply-work-center-selections.test.ts`.+- [x] **F12 — an operator is booked after the qualification expires.**+ 1. In `operator-eligibility.ts`, add `clipToQualification(windows, expiresAt, timeZone)`.+ The qualification ends at the start of the `expiresAt` day in the plant timezone.+ 2. `buildEligibleMembers` clips each member's windows. A member with no window left is dropped.+ 3. The People board treats the expiry day as expired (`<=`), like the engine and MES.+ 4. Test: `operator-eligibility.test.ts`.+- [x] **F16 — holidays are ignored.**+ 1. Add `closeHolidays` to `machine-availability.ts` and `withHolidays` to `people-utils.ts`.+ Both use `subtractDates`, which cuts whole days in the plant timezone.+ 2. The provider reads the company's holidays once (`getHolidayDates`).+ 3. The provider removes holidays from every work center that is not lights-out, and from the location default calendar.+ 4. `buildFiniteContext` adds each holiday as an absence for every person.+ 5. The Forecast shades holidays. The Capacity view shows 0 Available on a holiday.+ 6. The holiday operations notify the scheduler. The 3 holiday routes call those operations.+ 7. Tests: `machine-availability.test.ts`, `people-utils.test.ts`, `forecast.test.ts`, `capacity-buckets.test.ts`.+- [x] **F5 — a shift change does not re-plan ungated work.**+ 1. `createShift`, `updateShift` and `deleteShift` notify kind `shift` with the shift id. The delete route calls `deleteShift`.+ 2. Add a pure function `workCentersOnShift` to the jobs package.+ It returns the work centers whose hours come from the shift: explicit links, plus unlinked, not lights-out stations at the shift's location.+ 3. The mark step stamps the jobs with open ops on those work centers, plus the gated jobs as before.+ 4. Test: a unit test for `workCentersOnShift`.+- [x] **F1 — the Capacity view puts hours on nights and weekends.**+ 1. `buildPeopleCapacityBuckets` takes each work center's working windows.+ 2. It divides a booking's `workHours` by the working time inside each day.+ If the booking has no working time, it uses the clock time as before.+ 3. The People loader builds the windows with `resolveWorkCenterWindows` and the holidays.+ 4. Test: `production` unit test with the Potting Station example (8h booking Mon 12:00 → Tue 11:30 = 2.5h + 5.5h).+- [x] **F26 — a training assigned to one person is invisible.**+ 1. Main fixed this first (`699d31dc28`, migration `20261026114317_users-for-groups-identity-groups.sql`). This branch drops its own migration and keeps that fix.+ 2. The browser check of F26 runs against main's fix.+- [x] **F27 — a contractor save deletes the abilities.**+ 1. `upsertContractor` replaces the abilities only when the caller sends `abilities`.+ 2. The edit route stops sending an empty list.+ 3. Correct the glossary text for `contractor-hours-per-week`.+- [x] **Docs:** update `.claude/rules/scheduling-data-structures.md` and the production and resources `AGENTS.md` for F6, F10, F12, F16.+- [x] **Verify:** typecheck (planning, jobs, erp), Biome, unit tests, the SQL test, and a browser check of each finding.++## Result (2026-10-26)++| Check | Result |+|---|---|+| Typecheck: `@carbon/planning`, `@carbon/jobs`, `erp` | Pass |+| Unit tests: planning (358), jobs scheduled (70), ERP (8) | Pass |+| `@carbon/checks` conformance (403) and `clobbers` | Pass |+| Biome on the 32 changed files | No errors |+| `rpc-privileges.test.sql` (main's version) | Pass |+| Browser check of each finding | Pass. Details below. |++- F6: 4 regenerates in a row give the same order and work center per station.+- F10: 0 of 81 bookings name a station other than the op's work center (42 before).+- F1: Capacity for 26 Oct to 1 Nov shows 0 overloaded (8 before), and no weekend hours.+- F5: adding a shift stamped 5 jobs. Editing Swing Shift stamped 11 jobs, and no booking runs past the new end.+- F12: an operator whose qualification ends on 28 Oct is not booked on 29 Oct.+- F16: the holiday stamped 13 jobs. Capacity shows 0 Available on that day, and the Forecast shades it.+- F26: the Assignments list and drawer show the training assigned to one person.+- F27: two contractor saves wrote the hours, and the ability stayed.++The test data is restored: 85 reservations, 0 placeholders, 0 stale jobs.++## Self-review follow-ups (2026-10-26)++1. The `placeReleasedBatches` doc comment is back on its function.+2. `placementWrites` (`run-overlay.ts`) now builds the placement writes, and `buildWrites` calls it. A new test applies a selection and checks the write. With the old rule put back, that test fails.+3. The ERP uses the engine's `closeHolidays` and `subtractDates` (now exported from `@carbon/planning`). It has no copy of its own.+4. The Forecast loader reads holidays in parallel with its other reads.+5. The abilities table takes today from the browser's calendar, not the UTC day.+6. `people.mdx` and `scheduling.mdx` describe holidays. Two lessons are in `.ai/lessons.md`.diff --git a/.ai/playbooks/capacity-planning-fixes.md b/.ai/playbooks/capacity-planning-fixes.mdnew file mode 100644index 0000000000..c649e625a4--- /dev/null+++ b/.ai/playbooks/capacity-planning-fixes.md@@ -0,0 +1,85 @@+# Capacity planning: scheduler, holidays, shifts, qualifications++Last tested: 2026-10-26+Routes: /x/people/shifts, /x/people/holidays, /x/resources/processes, /x/resources/work-centers,+/x/resources/abilities, /x/resources/ability/:id/employee/:eaId, /x/part/new, /x/job/new,+/x/production/batches/new, /x/scheduling/forecast, /x/priority/people?view=capacity|board,+/x/priority/operations, /x/resources/assignments, /x/resources/contractors, MES /x/operations++Covers the 8 fixes in `.ai/plans/2026-10-26-capacity-planning-high-fixes.md` (F1, F5, F6, F10, F12,+F16, F26, F27). Build your own data — do not judge a fix on the demo data's state.++## Prerequisites+- Dev stack up (`crbn up`) INCLUDING the Inngest worker: every input change is applied by the+ debounced replan wave (~30 s). Poll `job.scheduleOutdatedReason IS NOT NULL` to 0 instead of sleeping.+- Demo dataset (satellite) seeded; the Manufacturing Plant location exists.++## Fixture (build it first, all at Manufacturing Plant)+1. Shift — /x/people/shifts/new: Name "QA Shift", Location "Manufacturing Plant", end time 16:00+ (default 08:00–17:00 Mon–Fri; lower the end hour segment once with ArrowDown).+2. Process — /x/resources/processes/new: Name "QA Process", Default Unit "Hours/Piece", Batchable ON.+3. Work centers — /x/resources/work-centers/new twice ("QA Cell A", "QA Cell B"): Processes+ "QA Process", Operating hours "Some Shifts", Shifts "QA Shift".+4. Part — /x/part/new: Part ID "QA-PART-1", Replenishment "Make". Add ONE method operation+ (4 Hours/Piece on QA Process). The BOP editor is hard to drive; inserting the `methodOperation`+ row with SQL is acceptable. Check it shows at /x/part/:itemId/make/:makeMethodId.+5. Jobs — /x/job/new three times (Item QA-PART-1, qty 1, defaults), then release each from the job+ page: button "Release" → dialog button "Release Job".++Expected plan (shift 08:00–16:00, 4 h ops, 2 stations): two jobs start now (one per station) and+finish next morning; the third follows on the first station to free up. Every op's stored+`workCenterId` equals its booking's station.++## Checks+- F1 Capacity (`?view=capacity`): the QA stations' Scheduled split by working time — e.g. a+ 13:00 Mon → 09:00 Tue booking reads 3.0 Mon / 1.0 Tue, never hours on nights or weekends.+- F10: set one QA op's stored work center to the other station (SQL), Regenerate (Forecast+ header refresh button, aria-label "Regenerate") → stored station moves to the booked one.+ Ops board and MES columns must equal stored stations.+- F5: edit QA Shift end time → exactly the QA jobs are stamped "Shift hours changed"; after+ the wave no QA booking falls outside the new hours. Deleting QA Shift stamps them+ "Shift removed".+- F16: create a holiday on a weekday (/x/people/holidays/new) → all released jobs stamped+ "Company holidays changed"; no booking starts/ends that day; Capacity Available 0 and no+ "Nh staffed" note that day; Forecast shades it. Edit it to another day, then delete it.+- F6: batch builder `/x/production/batches/new?location=<loc>&process=<QA Process>` → tick two+ QA rows, "Create & Release" → confirm dialog "Create & Release". The Sequential batch+ (≈ 8 h) starts NOW on a QA station (not behind its members' old bookings) and stays put+ across 3 Regenerates.+- F12: /x/resources/abilities/new → Process "QA Process" (makes it gated). Add Test via+ /x/resources/ability/:id/employee/new (Employee "Test", Expires At). Man Test on a QA cell for+ one day (SQL `peopleAssignment`, shiftId = QA Shift to avoid the per-day unique key). Expiry =+ that day → gated op is a placeholder; expiry = next day → booked that day. People board+ `?view=board&range=day&date=<day>` shows the amber "Missing" triangle only when the expiry is+ that day. Abilities table hides the person when expiry is today.+- F26: /x/resources/training/new "QA Training" → header "Publish" → confirm "Publish". Then+ /x/resources/assignments/new: Training "QA Training", assign-to picker → type "Test" → the+ person row. List shows Assigned 1; drawer lists Test; "Mark Complete" records a completion.+- F27: /x/resources/contractors/new (Supplier, Supplier Contact, Hours per Week). No UI adds+ contractor abilities — insert one `contractorAbility` row with SQL. Save the edit drawer+ unchanged and with new hours → abilities stay 1. Help text reads "…for reference. The+ scheduler does not book contractors on operations."++## Cleanup+Delete, in one transaction: QA capacityReservations, the batch (null `jobOperation.jobOperationBatchId`+first), the 3 jobs, trainingCompletion/assignment/training, contractorAbility/contractor,+peopleAssignments, employeeAbility/ability, workCenterShift/workCenterProcess, methodOperation,+work centers, process, shift, item. Then Regenerate.++## Selector Notes+- Shift/holiday/expiry time and date fields are react-aria spinbuttons: focus the segment+ (`[role=spinbutton]`, index by position) and use ArrowUp/ArrowDown or digit key presses;+ `fill` does not reach them. Check the hidden input (`input[name=endTime|date|expiresAt]`).+- Shift weekday toggles are switches with `id="monday"` … `id="sunday"`.+- Process "Requires Ability"/"Batchable" are `button[role=switch]` with that aria-label.+- Drawer forms: submit with `requestSubmit` on the drawer's own form ("Save").+- Board/People: `range=day` is required for the Day board; the Week board shows no+ missing-qualification warning.+- macOS has no `timeout`; if agent-browser hangs, `agent-browser --session <s> close`, then log in+ again at /login with DEV_BYPASS_EMAIL.++## Common Failures+- Pressing Escape inside a drawer combobox closes the whole drawer.+- A notify sent but nothing re-plans → the Inngest worker is not running.+- A station manned on a day books ungated ops inside the manned window even when it is free+ earlier (existing behaviour, same on main) — remove fixture assignments before timing checks.diff --git a/.ai/playbooks/publish-training.md b/.ai/playbooks/publish-training.mdindex 61d21e049c..6844dfddb0 100644--- a/.ai/playbooks/publish-training.md+++ b/.ai/playbooks/publish-training.md@@ -1,6 +1,6 @@# Publish a Training-Last tested: 2026-08-25+Last tested: 2026-10-26Route: /x/training/{trainingId}## Prerequisites@@ -8,14 +8,13 @@ Route: /x/training/{trainingId}## Steps### 1. Navigate — /x/training/{id}. Header shows the name + a status badge (DRAFT/ACTIVE/ARCHIVED).-### 2. Open the Properties panel — if hidden, click the "Toggle Properties" icon button (LuPanelRight) in the header. The panel is on the right.-### 3. Change Status — the FIRST combobox in the Properties panel is "Status". Click it, then pick "ACTIVE" to publish (or "ARCHIVED" to retire). No Save needed — the change commits immediately via a fetcher to `path.to.bulkUpdateTraining` (routes/x+/training+/update.tsx, field=status).-### 4. Verify — the header badge updates to ACTIVE (e.g. "CNC Training ACTIVE").+### 2. Publish — a Draft training shows a "Publish" button in the HEADER. Click it.+### 3. Confirm — a dialog "Publish Training" opens ("Employees assigned to this training can open it…"). Click its "Publish" button.+### 4. Verify — `training.status` is Active and the header badge reads ACTIVE.## Selector Notes-- "Publish" is NOT a button. Publishing = setting Status from Draft → Active in the right-hand Properties panel.-- The Properties panel has three unlabeled comboboxes in order: Status, Type (Mandatory/Optional), Frequency. Confirm by opening — Status options are DRAFT/ACTIVE/ARCHIVED.-- Status write requires `update: "people"` permission (update.tsx uses the people module gate), NOT resources.+- Status changes only from the header: Draft shows Publish, Active shows Archive, Reopen is in the ⋯ menu. The Properties panel has no Status field any more.+- A new training: /x/resources/training/new (Name, optional Grants Ability) → Save → lands on /x/training/{id}.## Common Failures-- Panel collapsed → no visible status control. Toggle Properties in the header.+- Looking for Status in the Properties panel — it was moved to the header.diff --git a/.claude/rules/scheduling-data-structures.md b/.claude/rules/scheduling-data-structures.mdindex 7ed48c0c92..c6f958d54c 100644--- a/.claude/rules/scheduling-data-structures.md+++ b/.claude/rules/scheduling-data-structures.md@@ -92,11 +92,16 @@ Spec/plan: `.ai/specs/2026-09-22-quote-lead-time-prediction.md`.(`PeopleCapacity.tsx`). Capacity math: Demand = open `jobOperation` hours bydue date via `makeDurations` (Draft/Planned jobs excluded — released workonly; ops overdue up to 28 days land in a Past-due column); Scheduled =- `capacityReservation.workHours` distributed across each reservation's span- per day; Available = people headcount × real shift hours resolved through+ `capacityReservation.workHours` split across the days of the booking by+ the work center's WORKING time in each day (`getWorkCenterWorkingWindows`,+ the same ladder and holidays the engine uses), so a booking from Monday+ noon to Tuesday 11:30 puts its hours in shift time and none on the night+ or a weekend; a booking with no working time falls back to the clock-time+ share; Available = people headcount × real shift hours resolved throughthe ladder assignment `shiftId` → the person's `employeeShift` →most-common shift duration at the location → 8h (unassigned stations fall- back to the location's per-weekday shift calendar); Load renders as hours+ back to the location's per-weekday shift calendar; a company holiday is+ 0, and nobody manned on it counts as staffed); Load renders as hoursover/free (+Xh / Xh free), not %. Shift + location filters live in headerpopovers; the shift filter's "All shifts" option (`shiftId` null ondrag) creates shift-less assignments that resolve hours via the ladder.@@ -138,6 +143,12 @@ never abandons the location run.guard defers to a human pick landing mid-wave). Release therefore neverrequires a work center; no candidates at all degrades to per-memberplacement.+- **What blocks a batch**: `batchBlockingReservations` decides which live+ reservations a batch is placed around. It keeps other jobs' bookings and+ other batches' rows. It drops this location's own batch rows, and every+ non-batch row of a job the run re-plans (`orderedJobIds`): the run replaces+ those bookings, so they must not push the batch later. Before this, the+ batch drifted later on every regen.- **One reservation per Released (`Active`/`Completing`) batch**, tagged`capacityReservation.jobOperationBatchId`; `operationId`/`jobId` stay NOTNULL by anchoring on the min member op id. Placeholder semantics mirror@@ -197,7 +208,12 @@ Two Inngest functions listen on that event- **MARK** (`markScheduleStaleFunction`, immediate, concurrency 1 per company):stamps the affected jobs' `scheduleOutdatedReason` / `scheduleOutdatedAt` (scopedper kind — a qualification change in a shop with no gated ops stamps nothing;- `location` / `reorder` stamp company-wide). Recomputes nothing.+ `location` / `reorder` stamp company-wide). A `shift` event with a shift id also+ stamps every job with an open op on a work center whose hours come from that shift+ (`workCentersOnShift`, `shift-work-centers.ts`: the stations linked to it, plus the+ stations at its location with no link to an active shift; lights-out stations never+ count). An unknown shift id stamps company-wide. `createShift`, `updateShift` and+ `deleteShift` send the id. Recomputes nothing.- **WAVE** (`scheduleReplanWaveFunction`, **debounce 30s / timeout 10m**,concurrency 1 per company): loads the company's stale jobs, groups them by**LOCATION**, and calls `runLocationSchedule({ db: getJobDatabaseClient(),@@ -316,10 +332,18 @@ only; its output is read by nothing in the placement path (specforward from `max(now, placed-dependency-ends)` — **no backward-pass floor** — into thefirst feasible span. Two finite resources gate it: the work center (capacity 1 — one opat a time, decided by actual `capacityReservation` intervals) AND, for ability-gated- processes, ≥1 qualified employee on shift and unreserved. **Work-center selection is- sticky**: an op keeps its `workCenterId` when that work center is in the capacity set;- an op with no work center (or whose WC has no capacity data, e.g. deactivated) gets- earliest-finish selection among its process candidates. A placement past the job's+ processes, ≥1 qualified employee on shift and unreserved. **Only a started op is+ sticky** (`isOperationStarted`, `apply-work-center-selections.ts`: status In Progress+ or Paused, or `quantityComplete > 0`): it stays on its `workCenterId`. An op that has+ not started gets earliest-finish selection across its process's work centers, even+ when it carries a work center (the stored one is the fallback when the process has no+ mapped centers). `applyWorkCenterSelections` then puts the chosen work center on a+ placed op that has not started, and `placementWrites` (`run-overlay.ts`) writes it,+ so `jobOperation.workCenterId` and the op's `capacityReservation` always name the+ same station. A started op and a placeholder+ keep the stored one; an op with no work center gets one either way. Consequence: a+ card dragged to another column on the operations board can move back at the next+ regen when another station finishes it earlier. A placement past the job's`dueDate` sets `hasConflict`/`conflictReason` but keeps the placement.- **Machine availability windows** come from the ladder resolved per work center in`machine-availability.ts` (`resolveWorkCenterWindows`) — the provider's@@ -336,6 +360,21 @@ only; its output is read by nothing in the placement path (specdispatch restores the hours at the next regen. People with no `employeeShift` rows nowdefault to the job LOCATION's calendar (rung 3/4 via `getLocationCalendarWindows`),not 24×7.+- **Company holidays close the plant.** The provider reads the company's `holiday`+ dates once per run (`getHolidayDates`). `closeHolidays` (`machine-availability.ts`)+ removes each holiday's whole day, in the plant timezone, from every work center that+ is not `alwaysOn`; a lights-out station keeps running. `loadLocationCalendarWindows`+ removes them from the location calendar, and `buildFiniteContext` adds each holiday as+ an absence for every person (`withHolidays`, `people-utils.ts`). The ERP reads the same+ dates (`getHolidayDates`, `production.service.ts`): the Forecast shades a holiday as+ closed, and the Capacity view shows 0 Available on it. `createHoliday`,+ `updateHoliday` and `deleteHoliday` (`people.server.ts`) notify kind `location`.+- **A qualification ends at its expiry.** `isEligibleOperator` tests an operator at the+ op's earliest start only. `clipToQualification` (`operator-eligibility.ts`) then cuts+ the operator's windows at the start of the `expiresAt` day in the plant timezone, and+ `buildEligibleMembers` drops an operator with no window left. Without the clip, an op+ that waited for its machine could be booked on a day after the qualification expired.+ The People board treats the expiry day as expired too (`expiresAt <= date`).- **Attended-window labor model is UNCHANGED** (`slot-allocator.ts`): ability gating,manning-board / team mode, attended windows, wait attribution, absence subtraction(`peopleAbsence`), overtime extension (`peopleAssignment.overtimeHours`), split-daydiff --git a/apps/erp/app/modules/people/AGENTS.md b/apps/erp/app/modules/people/AGENTS.mdindex 1d7bdcf1f7..07de7fa2c5 100644--- a/apps/erp/app/modules/people/AGENTS.md+++ b/apps/erp/app/modules/people/AGENTS.md@@ -7,7 +7,7 @@ Employee management, departments, shifts, holidays, time tracking (clock in/out,- **People vs Users vs Employees** — `user` is the global auth identity. `employee` is a per-company record with composite PK `(id, companyId)` where `id → user.id`. `employeeJob` holds title, location, department, shift, and manager. See `.claude/rules/user-employee-job-relationships.md`.- **Departments** — hierarchical organizational units via `parentDepartmentId`. Used for org structure and reporting.- **Shifts** — work schedules with day-of-week boolean flags (`monday`..`sunday`), start/end times, and location. Assigned to employees via `employeeJob.shiftId`.-- **Holidays** — company-specific non-working days with year grouping.+- **Holidays** — company-specific non-working days with year grouping. The scheduler closes every work center that is not lights-out (`workCenter.alwaysOn`) for the whole day in the plant timezone, and treats every person as absent.- **Time Tracking** — `clockIn`/`clockOut` functions manage `timeCardEntry` records. Weekly hours aggregated via `getWeeklyHoursForEmployees`.- **Contacts** — external contacts (not employees) associated with customers/suppliers via the `contact` table.- **Employee Attributes** — custom field system: categories → attributes → values. Each attribute has a data type (text, numeric, boolean, date, user, file, list) from `attributeDataType`. Values stored per user in `userAttributeValue`.@@ -70,7 +70,8 @@ pnpm --filter erp test -- people # vitest filters by file pathEach is a `defineServiceFn` const in `people.server.ts`. The route calls it as `api.people.<name>(input)`; the API and MCP publish the ones tagged `@mcp` as `people_<name>`. Routes validate the request, call one, and answer with `respond(request, result).redirect(…)` (a flash) or the result.-- `createShift` (people create), `updateShift` (people create and update: the old route's gate and the `shift` UPDATE policy; refused `notFound` when the update reaches no row of the company, and only then marks active jobs for rescheduling, `notifyScheduleInputsChanged`). Published.+- `createShift` (people create), `updateShift` (people create and update: the old route's gate and the `shift` UPDATE policy; refused `notFound` when the update reaches no row of the company), `deleteShift` (people delete; sets `active: false`). All three notify the scheduler with kind `shift` and the shift id, so the mark step stamps the jobs on the work centers that run the shift. Published.+- `createHoliday`, `updateHoliday`, `deleteHoliday` — the holiday calendar (`x+/people+/holidays.*`). A holiday closes the plant for the scheduler, so each one notifies kind `location` after it saves.- `updatePersonJob` — the person's job (`updateEmployeeJob`: ids checked against the company, `employeeShift` kept in step, one transaction), then reschedules. Published.- The person timecard page (`x+/person+/$personId.timecard.tsx`): `clockInPerson`, `clockOutPerson`, `addPersonTimeCardEntry`, `updatePersonTimeCardEntry`, `deletePersonTimeCardEntry`. They need only people view, as that page always did, so they stay unpublished. A helper's own refusal ("Already clocked in") is a `rule` error; a database error is `internal`.- `clockInSelf`, `clockOutSelf` for the caller (`api+/people.timecard.ts`, the "Forgot to clock out?" prompt). Unpublished.diff --git a/apps/erp/app/modules/people/people.server.ts b/apps/erp/app/modules/people/people.server.tsindex 94ca33b6a9..067427fa17 100644--- a/apps/erp/app/modules/people/people.server.ts+++ b/apps/erp/app/modules/people/people.server.ts@@ -2,7 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { defineServiceFn } from "@carbon/api/service-fn.server";+import { CarbonError, defineServiceFn } from "@carbon/api/service-fn.server";import { paged, payload, unwrap } from "@carbon/api/service-tools.server";import { z } from "zod";import { notifyScheduleInputsChanged } from "~/modules/production/production.service";@@ -51,6 +51,14 @@ export const createShift = defineServiceFn({if (created.error || !created.data) {return ctx.error("internal", "Failed to create shift", created.error);}+ // A new location shift adds hours to every work center that runs all of+ // the location's shifts.+ await notifyScheduleInputsChanged(+ ctx.company.id,+ "shift",+ "Shift added",+ created.data.id+ );return { id: created.data.id };}});@@ -82,7 +90,8 @@ export const updateShift = defineServiceFn({await notifyScheduleInputsChanged(ctx.company.id,"shift",- "Shift hours changed"+ "Shift hours changed",+ shift.id);return { id: shift.id };}@@ -338,13 +347,20 @@ export const deleteHoliday = defineServiceFn({input: z.looseObject({ holidayId: z.string() }),permission: { delete: "people" },async run(ctx, input) {- return unwrap(+ const deleted = unwrap(ctx,await service.deleteHoliday(ctx.asCaller.supabase,input.holidayId as never));+ if (deleted instanceof CarbonError) return deleted;+ await notifyScheduleInputsChanged(+ ctx.company.id,+ "location",+ "Company holidays changed"+ );+ return deleted;}});@@ -357,10 +373,18 @@ export const deleteShift = defineServiceFn({input: z.looseObject({ shiftId: z.string() }),permission: { delete: "people" },async run(ctx, input) {- return unwrap(+ const deleted = unwrap(ctx,await service.deleteShift(ctx.asCaller.supabase, input.shiftId as never));+ if (deleted instanceof CarbonError) return deleted;+ await notifyScheduleInputsChanged(+ ctx.company.id,+ "shift",+ "Shift removed",+ input.shiftId+ );+ return deleted;}});@@ -962,13 +986,20 @@ export const createHoliday = defineServiceFn({}),permission: { create: "people" },async run(ctx, input) {- return unwrap(+ const saved = unwrap(ctx,await service.upsertHoliday(ctx.asCaller.supabase,payload(ctx, input).forCreate() as never));+ if (saved instanceof CarbonError) return saved;+ await notifyScheduleInputsChanged(+ ctx.company.id,+ "location",+ "Company holidays changed"+ );+ return saved;}});@@ -994,13 +1025,20 @@ export const updateHoliday = defineServiceFn({.required({ id: true }),permission: { update: "people" },async run(ctx, input) {- return unwrap(+ const saved = unwrap(ctx,await service.upsertHoliday(ctx.asCaller.supabase,payload(ctx, input).forUpdate() as never));+ if (saved instanceof CarbonError) return saved;+ await notifyScheduleInputsChanged(+ ctx.company.id,+ "location",+ "Company holidays changed"+ );+ return saved;}});diff --git a/apps/erp/app/modules/production/capacity-buckets.test.ts b/apps/erp/app/modules/production/capacity-buckets.test.tsnew file mode 100644index 0000000000..f58f46fe22--- /dev/null+++ b/apps/erp/app/modules/production/capacity-buckets.test.ts@@ -0,0 +1,119 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import {+ buildPeopleCapacityBuckets,+ getWorkCenterCalendarHoursByDay,+ getWorkCenterWorkingWindows+} from "./production.service";++// America/Chicago is UTC-5 in late October 2026. Day Shift 06:00-14:30 Mon-Fri.+const TZ = "America/Chicago";+const at = (iso: string) => Date.parse(iso);+const WEEK = [+ "2026-10-26",+ "2026-10-27",+ "2026-10-28",+ "2026-10-29",+ "2026-10-30",+ "2026-10-31",+ "2026-11-01"+];+const dayShift = {+ id: "day",+ startTime: "06:00:00",+ endTime: "14:30:00",+ monday: true,+ tuesday: true,+ wednesday: true,+ thursday: true,+ friday: true,+ saturday: false,+ sunday: false+};++const scheduled = (+ reservation: { startAt: string; endAt: string; workHours: number },+ holidayDates = new Set<string>()+) =>+ buildPeopleCapacityBuckets({+ weekDates: WEEK,+ timezone: TZ,+ operations: [],+ reservations: [{ resourceId: "potting", ...reservation }],+ calendarHoursByWorkCenter: new Map(),+ workingWindowsByWorkCenter: getWorkCenterWorkingWindows({+ workCenters: [{ id: "potting", alwaysOn: false }],+ workCenterShifts: [{ workCenterId: "potting", shiftId: "day" }],+ shifts: [dayShift],+ timeZone: TZ,+ holidayDates,+ rangeStart: at("2026-10-20T05:00:00Z"),+ rangeEnd: at("2026-11-10T06:00:00Z")+ })+ }).scheduledByWorkCenter.potting;++describe("buildPeopleCapacityBuckets", () => {+ it("divides an overnight booking over the shift hours of each day", () => {+ // 8h booked Mon 12:00 -> Tue 11:30: Mon 12:00-14:30 + Tue 06:00-11:30.+ expect(+ scheduled({+ startAt: "2026-10-26T17:00:00Z",+ endAt: "2026-10-27T16:30:00Z",+ workHours: 8+ })+ ).toEqual({ "2026-10-26": 2.5, "2026-10-27": 5.5 });+ });++ it("puts no hours on a weekend the station does not work", () => {+ // 24h booked Thu 07:30 -> Mon 14:30: Thu 7h + Fri 8.5h + Mon 8.5h.+ expect(+ scheduled({+ startAt: "2026-10-29T12:30:00Z",+ endAt: "2026-11-02T20:30:00Z",+ workHours: 24+ })+ ).toEqual({ "2026-10-29": 7, "2026-10-30": 8.5 });+ });++ it("puts no hours on a company holiday", () => {+ // 17h booked Mon 06:00 -> Wed 14:30 with Tuesday a holiday: Mon + Wed.+ expect(+ scheduled(+ {+ startAt: "2026-10-26T11:00:00Z",+ endAt: "2026-10-28T19:30:00Z",+ workHours: 17+ },+ new Set(["2026-10-27"])+ )+ ).toEqual({ "2026-10-26": 8.5, "2026-10-28": 8.5 });+ });+});++describe("available hours", () => {+ it("are 0 on a company holiday, except on a lights-out station", () => {+ const hours = getWorkCenterCalendarHoursByDay({+ workCenters: [+ { id: "potting", alwaysOn: false },+ { id: "tvac", alwaysOn: true }+ ],+ workCenterShifts: [{ workCenterId: "potting", shiftId: "day" }],+ locationShifts: [+ {+ id: "day",+ hours: 8.5,+ runsOn: [false, true, true, true, true, true, false]+ }+ ],+ weekDates: WEEK,+ holidayDates: new Set(["2026-10-27"])+ });++ expect(hours.get("potting")?.get("2026-10-26")).toBe(8.5);+ expect(hours.get("potting")?.get("2026-10-27")).toBe(0);+ expect(hours.get("tvac")?.get("2026-10-27")).toBe(24);+ });+});diff --git a/apps/erp/app/modules/production/forecast.test.ts b/apps/erp/app/modules/production/forecast.test.tsindex 4f25169aad..aab3ace91b 100644--- a/apps/erp/app/modules/production/forecast.test.ts+++ b/apps/erp/app/modules/production/forecast.test.ts@@ -73,6 +73,21 @@ describe("getForecastNonWorkingIntervals", () => {]);});+ it("shades a company holiday as closed all day", () => {+ // Monday 17 Aug 2026 is a holiday: the 06:00-14:00 shift does not open.+ const result = getForecastNonWorkingIntervals({+ timeZone: "America/New_York",+ shifts: [shift({ monday: true })],+ windowStartMs: iso("2026-08-17T04:00:00Z"),+ windowEndMs: iso("2026-08-18T04:00:00Z"),+ holidayDates: new Set(["2026-08-17"])+ });++ expect(result).toEqual([+ { start: iso("2026-08-17T04:00:00Z"), end: iso("2026-08-18T04:00:00Z") }+ ]);+ });+it("shades the whole window when it falls on a non-working day", () => {// Saturday 2026-08-22: the stock week is Mon–Fri only, so the entire day is// non-working — one interval spanning the window.diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 6939908640..65c9407bf6 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -105,8 +105,12 @@ import { asJobSource, trackWorkEvent } from "@carbon/lib/telemetry";import { raiseMoment } from "@carbon/lib/workflows";import { getLogger } from "@carbon/logger";import {+ type CalendarWindow,+ closeHolidays,type LadderShiftRow,resolveLocationWindows,+ resolveWorkCenterWindows,+ subtractDates,subtractIntervals} from "@carbon/planning";import type { JSONContent } from "@carbon/react";@@ -11452,16 +11456,37 @@ export function getForecastNonWorkingIntervals(args: {shifts: ShiftRow[];windowStartMs: number;windowEndMs: number;+ /** Company holidays ("YYYY-MM-DD"): shaded as closed all day. */+ holidayDates?: Set<string>;}): { start: number; end: number }[] {const { timeZone, shifts, windowStartMs, windowEndMs } = args;- const locationShiftRows: LadderShiftRow[] = [];+ const working = subtractDates(+ resolveLocationWindows({+ timezone: timeZone,+ locationShiftRows: expandShiftRows(shifts, timeZone),+ rangeStart: windowStartMs,+ rangeEnd: windowEndMs+ }),+ args.holidayDates ?? new Set(),+ timeZone+ );++ return subtractIntervals(+ [{ start: windowStartMs, end: windowEndMs }],+ working+ ).map((w) => ({ start: w.start, end: w.end }));+}++/** A shift's weekday windows in the ladder's row shape (0 = Sunday). */+function expandShiftRows(shifts: ShiftRow[], timeZone: string) {+ const rows: LadderShiftRow[] = [];for (const shift of shifts) {if (!shift.startTime || !shift.endTime) continue;for (let dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {const flag = WEEKDAY_FLAGS[dayOfWeek];if (!flag || !shift[flag]) continue;- locationShiftRows.push({+ rows.push({dayOfWeek,startTime: String(shift.startTime),endTime: String(shift.endTime),@@ -11469,18 +11494,73 @@ export function getForecastNonWorkingIntervals(args: {});}}+ return rows;+}- const working = resolveLocationWindows({- timezone: timeZone,- locationShiftRows,- rangeStart: windowStartMs,- rangeEnd: windowEndMs+/**+ * Each work center's working windows: the scheduler's availability ladder+ * (`resolveWorkCenterWindows`) minus the company's holidays.+ */+export function getWorkCenterWorkingWindows(args: {+ workCenters: { id: string; alwaysOn: boolean }[];+ workCenterShifts: { workCenterId: string; shiftId: string }[];+ /** The location's active shifts. */+ shifts: (ShiftRow & { id: string })[];+ timeZone: string;+ holidayDates: Set<string>;+ rangeStart: number;+ rangeEnd: number;+}): Map<string, CalendarWindow[]> {+ const { workCenters, workCenterShifts, shifts, timeZone } = args;+ const shiftById = new Map(shifts.map((shift) => [shift.id, shift]));+ const ladderWorkCenters = workCenters.map((wc) => ({+ id: wc.id,+ alwaysOn: wc.alwaysOn,+ locationId: "location",+ timezone: timeZone+ }));+ const windows = resolveWorkCenterWindows({+ workCenters: ladderWorkCenters,+ workCenterShiftRows: workCenterShifts.flatMap((link) => {+ const shift = shiftById.get(link.shiftId);+ return shift+ ? expandShiftRows([shift], timeZone).map((row) => ({+ ...row,+ workCenterId: link.workCenterId+ }))+ : [];+ }),+ locationShiftRows: expandShiftRows(shifts, timeZone).map((row) => ({+ ...row,+ locationId: "location"+ })),+ rangeStart: args.rangeStart,+ rangeEnd: args.rangeEnd+ });+ return closeHolidays({+ windowsByWorkCenter: windows,+ workCenters: ladderWorkCenters,+ holidayDates: args.holidayDates});+}- return subtractIntervals(- [{ start: windowStartMs, end: windowEndMs }],- working- ).map((w) => ({ start: w.start, end: w.end }));+/** The company's holiday dates ("YYYY-MM-DD") between two dates, inclusive. */+export async function getHolidayDates(+ client: SupabaseClient<Database>,+ companyId: string,+ args: { from: string; to: string }+): Promise<Set<string>> {+ const { data, error } = await client+ .from("holiday")+ .select("date")+ .eq("companyId", companyId)+ .gte("date", args.from)+ .lte("date", args.to);+ if (error) {+ logger.error("Failed to load holidays", { companyId, error });+ return new Set();+ }+ return new Set((data ?? []).map((row) => row.date.slice(0, 10)));}type CapacityOperation = {workCenterId: string | null;@@ -11535,8 +11615,11 @@ export function getWorkCenterCalendarHoursByDay(args: {workCenterShifts: { workCenterId: string; shiftId: string }[];locationShifts: CapacityShift[];weekDates: string[];+ /** Company holidays: 0 hours, except on a lights-out station. */+ holidayDates?: Set<string>;}): Map<string, Map<string, number>> {const { workCenters, workCenterShifts, locationShifts, weekDates } = args;+ const holidayDates = args.holidayDates ?? new Set<string>();const shiftById = new Map(locationShifts.map((shift) => [shift.id, shift]));const shiftIdsByWorkCenter = new Map<string, string[]>();@@ -11570,6 +11653,8 @@ export function getWorkCenterCalendarHoursByDay(args: {let hours: number;if (workCenter.alwaysOn) {hours = 24;+ } else if (holidayDates.has(day)) {+ hours = 0;} else if (wcShifts.length > 0) {hours = sumShiftHours(wcShifts, dow);} else if (locationShifts.length > 0) {@@ -11584,6 +11669,20 @@ export function getWorkCenterCalendarHoursByDay(args: {return result;}+/** Milliseconds of `windows` inside [from, to). */+function workingOverlapMs(+ windows: CalendarWindow[],+ from: number,+ to: number+): number {+ let total = 0;+ for (const window of windows) {+ const overlap = Math.min(to, window.end) - Math.max(from, window.start);+ if (overlap > 0) total += overlap;+ }+ return total;+}+/*** The Capacity view's week buckets.*@@ -11602,6 +11701,13 @@ export function buildPeopleCapacityBuckets(args: {reservations: CapacityReservation[];/** per-work-center calendar hours (the ladder above) — clamps null-workHours reservations. */calendarHoursByWorkCenter: Map<string, Map<string, number>>;+ /**+ * Each work center's working windows (`getWorkCenterWorkingWindows`). A+ * booking's hours are divided over the working time inside each day, not+ * its wall-clock span: an 8h booking from Monday 12:00 to Tuesday 11:30 on+ * a 06:00–14:30 shift is 2.5h Monday and 5.5h Tuesday, never hours at night.+ */+ workingWindowsByWorkCenter?: Map<string, CalendarWindow[]>;}): {demandByWorkCenter: Record<string,@@ -11614,7 +11720,8 @@ export function buildPeopleCapacityBuckets(args: {timezone,operations,reservations,- calendarHoursByWorkCenter+ calendarHoursByWorkCenter,+ workingWindowsByWorkCenter} = args;const weekStartDate = weekDates[0];@@ -11680,14 +11787,22 @@ export function buildPeopleCapacityBuckets(args: {workMs = Math.min(spanMs, calendarMsWithinSpan);}+ // A booking with no working time (a station with no windows) falls back to+ // the wall-clock share.+ const windows =+ workingWindowsByWorkCenter?.get(reservation.resourceId) ?? [];+ const workingSpanMs = workingOverlapMs(windows, startMs, endMs);for (const { day, startMs: dayStartMs, endMs: dayEndMs } of dayBounds) {- const overlapMs =- Math.min(endMs, dayEndMs) - Math.max(startMs, dayStartMs);- if (overlapMs > 0) {- const byDay = (scheduledByWorkCenter[reservation.resourceId] ??= {});- byDay[day] =- (byDay[day] ?? 0) + (overlapMs / spanMs) * (workMs / HOUR_MS);- }+ const from = Math.max(startMs, dayStartMs);+ const to = Math.min(endMs, dayEndMs);+ if (to <= from) continue;+ const share =+ workingSpanMs > 0+ ? workingOverlapMs(windows, from, to) / workingSpanMs+ : (to - from) / spanMs;+ if (share <= 0) continue;+ const byDay = (scheduledByWorkCenter[reservation.resourceId] ??= {});+ byDay[day] = (byDay[day] ?? 0) + share * (workMs / HOUR_MS);}}diff --git a/apps/erp/app/modules/production/ui/Schedule/People/PeopleBoard.tsx b/apps/erp/app/modules/production/ui/Schedule/People/PeopleBoard.tsxindex ad7475452b..d9fa091589 100644--- a/apps/erp/app/modules/production/ui/Schedule/People/PeopleBoard.tsx+++ b/apps/erp/app/modules/production/ui/Schedule/People/PeopleBoard.tsx@@ -201,7 +201,8 @@ const PeopleBoard = ({const map = new Map<string, Set<string>>();const today = date;for (const row of employeeAbilities) {- if (row.expiresAt && row.expiresAt.slice(0, 10) < today) continue;+ // Expiring today = not qualified today, as in the scheduler and MES.+ if (row.expiresAt && row.expiresAt.slice(0, 10) <= today) continue;const set = map.get(row.employeeId) ?? new Set<string>();set.add(row.abilityId);map.set(row.employeeId, set);diff --git a/apps/erp/app/modules/production/ui/Schedule/People/PeopleCapacity.tsx b/apps/erp/app/modules/production/ui/Schedule/People/PeopleCapacity.tsxindex 5a827e5375..9ba34095b7 100644--- a/apps/erp/app/modules/production/ui/Schedule/People/PeopleCapacity.tsx+++ b/apps/erp/app/modules/production/ui/Schedule/People/PeopleCapacity.tsx@@ -87,6 +87,8 @@ type PeopleCapacityProps = {defaultShiftHours: number;/** per-work-center calendar hours (the availability ladder) — the Available series. */calendarHoursByWorkCenter: Record<string, Record<string, number>>;+ /** Company holidays: the plant is closed, so nobody counts as staffed. */+ holidayDates: string[];/** which ladder rung each work center resolved via (1 explicit, 2 location, 3 stock). */capacityRungByWorkCenter: Record<string, number>;};@@ -148,10 +150,12 @@ export function PeopleCapacity({employeeShiftHours,defaultShiftHours,calendarHoursByWorkCenter,- capacityRungByWorkCenter+ capacityRungByWorkCenter,+ holidayDates}: PeopleCapacityProps) {const [tab, setTab] = useState<CapacityTab>("load");const absentSet = useMemo(() => buildAbsentSet(absences), [absences]);+ const holidaySet = useMemo(() => new Set(holidayDates), [holidayDates]);// present people labor hours per work center per date (all shifts, minus// absent), using each assignment's real shift duration — shown as a secondary@@ -163,7 +167,10 @@ export function PeopleCapacity({// scheduler, which extends the last window of the day.const lastRowByPersonDate = new Map<string, (typeof assignments)[number]>();for (const assignment of assignments) {- if (absentSet.has(`${assignment.employeeId}:${assignment.date}`)) {+ if (+ absentSet.has(`${assignment.employeeId}:${assignment.date}`) ||+ holidaySet.has(assignment.date)+ ) {continue;}const hours = assignmentHours(assignment, {@@ -188,6 +195,7 @@ export function PeopleCapacity({}, [assignments,absentSet,+ holidaySet,shiftHoursById,employeeShiftHours,defaultShiftHoursdiff --git a/apps/erp/app/modules/resources/AGENTS.md b/apps/erp/app/modules/resources/AGENTS.mdindex 7892cc561f..1996636288 100644--- a/apps/erp/app/modules/resources/AGENTS.md+++ b/apps/erp/app/modules/resources/AGENTS.md@@ -7,13 +7,13 @@ Locations, work centers, processes, abilities (skills), partners, contractors, e- **Location** — physical site/facility. Every inventory record, job, and employee is scoped to a location. Has address, timezone, and GPS coordinates. Company-scoped. `requiresStaffing` (BOOLEAN, default false; `20260820151847_location-requires-staffing.sql`) is a per-location scheduling policy edited on the Production settings page (Settings → Production → Scheduling): when true the finite scheduler only places work where an operator is manned (lights-out work centers exempt) — see `.claude/rules/scheduling-data-structures.md`.- **Work Center** — production station within a location. Operations schedule onto work centers. Have rates and active/inactive status. MUST soft-delete via `active: false`. Scheduling is always finite (one operation at a time), and a work center now has **operating hours**: assign it one or more of the location's shifts via `workCenterShift` (empty = all shifts at the location), or set `alwaysOn` for genuine lights-out 24×7. The scheduler resolves hours through a ladder — `alwaysOn` → explicit `workCenterShift` rows → the location's `shift` rows → a stock Mon–Fri 8h week — so even a zero-config shop is bounded by real hours (it is no longer "always open 24×7"). An open maintenance dispatch flagged `takesWorkCenterOffline` subtracts its window(s) from the schedule until closed. The work center form edits both (an "Operating shifts" multiselect + a "Runs 24×7 (lights-out)" toggle), and work-center create/edit/deactivate/reactivate emit the `work-center` schedule input event.- **Process** — type of work (e.g., "CNC Milling", "Welding"). Operations reference a process. Linked to work centers via `workCenterProcess`. MUST soft-delete via `active: false`. `process.requiresAbility` gates scheduling and the MES: toggling it ON auto-creates an ability linked 1:1 to the process (`ability.processId`) via `ensureProcessAbility`. `process.abilityPolicy` (enum `processAbilityPolicy`, `Warn` default / `Block`, edited under the toggle on the process form and read only while it is on) decides what the MES does for an operator without the ability: `Warn` shows a banner, `Block` refuses production work on the operation (MES `abilityBlockRefusal`). The ability stores no name of its own — its name IS the process's name. The `batchable` flag marks a process where multiple jobs can run at once (laser table, furnace, plating) — job operations derive batchability from it (see the production module's Operation Batch concept). `process.batchRules` (JSONB, nullable) holds per-BOM-dimension batch compatibility levels (`{ item?, substance?, grade?, dimension?, form?, finish?: "must"|"guide"|"ignore" }`), edited on the batchable process form (a "Compatibility rules" card, visible only when Batchable is on). It is SPARSE — keys equal to their resolved default are omitted, and an all-default config writes NULL. NULL reproduces the pre-rules behavior exactly (`resolveBatchRules(null)` → substance/grade/dimension = guide, form/finish/item = ignore). "Must" is the only level that BLOCKS (server-enforced in the `batch-operations` posting); "guide" warns and splits the builder's suggestion groups; "ignore" is invisible to batching. Resolution/compaction/enforcement all go through the shared pure module `@carbon/utils` `batch-compatibility` (`resolveBatchRules`, `compactBatchRules`, `mustViolations`). `insertProcess` / `updateProcess` fold the six `batchRule*` form fields into `batchRules` (and `batchRuleInitialValues` back); `updateProcess` writes the process and replaces its `workCenterProcess` rows in one Kysely transaction, linking only the company's own work centers.-- **Ability** — an employee qualification, **always** linked 1:1 to a process (`ability.processId`, NOT NULL, `ON DELETE CASCADE`). An ability stores **no name of its own** — the name derives from the linked process (renaming the process renames the ability), read through the `abilities` view (`ability` INNER JOIN `process`). Abilities are created **only from a process**: the New Ability modal (`x/resources/abilities` → new) is a picker of processes that don't already have an ability (`getProcessesWithoutAbility`); creating one turns that process's `requiresAbility` on and calls `ensureProcessAbility` (idempotent, so no duplicates). Legacy free-form abilities (no `processId`) were **deleted** by `20260917161742_abilities-from-process.sql` (cascading their `employeeAbility`/`contractorAbility` rows, nulling `training.grantsAbilityId`, and first detaching `workCenter.requiredAbilityId` / removing `partner` rows that referenced them). `employeeAbility` is effectively a map of the processes each person can do. Qualification is **presence-based**: an `employeeAbility` row means the person is qualified, subject only to expiry — `qualified = row exists ∧ (expiresAt IS NULL OR expiresAt ≥ today)` where `expiresAt` derives from `ability.recertifyEveryDays`. There is no `active` / `trainingCompleted` gate (dropped `20260812153418_simplify-employee-ability.sql`); "Remove Employee" is a **hard delete**. Admin UI at `x/resources/abilities`; each ability's detail page carries the roster of its qualified employees, and the person page's abilities panel is editable. Training is one path to a row: `training.grantsAbilityId` + the `grant_ability_on_training_completion` trigger upsert `employeeAbility` (sets `lastTrainingDate`, `expiresAt` from `recertifyEveryDays`) on completion — but manually adding the employee qualifies them just as well. **Every path that changes qualification notifies the scheduler** (`notifyScheduleInputsChanged(companyId, "ability", …, abilityId)`): `addEmployeeAbility` / `updateEmployeeAbility` / `removeEmployeeAbility`, `deactivateAbility` (deactivating an ability un-gates its process), and every training completion (`recordTrainingCompletion`, which both `completeTrainingAssignment` and `share/training.$id` call — scoped to `grantsAbilityId` when the training grants one).+- **Ability** — an employee qualification, **always** linked 1:1 to a process (`ability.processId`, NOT NULL, `ON DELETE CASCADE`). An ability stores **no name of its own** — the name derives from the linked process (renaming the process renames the ability), read through the `abilities` view (`ability` INNER JOIN `process`). Abilities are created **only from a process**: the New Ability modal (`x/resources/abilities` → new) is a picker of processes that don't already have an ability (`getProcessesWithoutAbility`); creating one turns that process's `requiresAbility` on and calls `ensureProcessAbility` (idempotent, so no duplicates). Legacy free-form abilities (no `processId`) were **deleted** by `20260917161742_abilities-from-process.sql` (cascading their `employeeAbility`/`contractorAbility` rows, nulling `training.grantsAbilityId`, and first detaching `workCenter.requiredAbilityId` / removing `partner` rows that referenced them). `employeeAbility` is effectively a map of the processes each person can do. Qualification is **presence-based**: an `employeeAbility` row means the person is qualified, subject only to expiry — `qualified = row exists ∧ (expiresAt IS NULL OR expiresAt > today)` — the expiry day itself counts as expired, in the scheduler, MES, the People board and the abilities table; the scheduler also stops booking the person from the start of that day (`clipToQualification`) where `expiresAt` derives from `ability.recertifyEveryDays`. There is no `active` / `trainingCompleted` gate (dropped `20260812153418_simplify-employee-ability.sql`); "Remove Employee" is a **hard delete**. Admin UI at `x/resources/abilities`; each ability's detail page carries the roster of its qualified employees, and the person page's abilities panel is editable. Training is one path to a row: `training.grantsAbilityId` + the `grant_ability_on_training_completion` trigger upsert `employeeAbility` (sets `lastTrainingDate`, `expiresAt` from `recertifyEveryDays`) on completion — but manually adding the employee qualifies them just as well. **Every path that changes qualification notifies the scheduler** (`notifyScheduleInputsChanged(companyId, "ability", …, abilityId)`): `addEmployeeAbility` / `updateEmployeeAbility` / `removeEmployeeAbility`, `deactivateAbility` (deactivating an ability un-gates its process), and every training completion (`recordTrainingCompletion`, which both `completeTrainingAssignment` and `share/training.$id` call — scoped to `grantsAbilityId` when the training grants one).- **Partner** — external supplier location with ability mappings for outsourced work.-- **Contractor** — supplier contact working as contract labor, with hours-per-week and ability assignments via `contractorAbility`.+- **Contractor** — supplier contact working as contract labor, with hours-per-week and ability assignments via `contractorAbility`. Both are for reference: the scheduler does not book contractors on operations. `upsertContractor` replaces the abilities only when the caller sends `abilities`; the edit drawer has no abilities field and sends none, so a save keeps them.- **Maintenance Dispatch** — reactive or scheduled work order for equipment. Statuses: Open → Assigned → In Progress → Completed / Cancelled. Tracks time events, consumed parts, and affected work centers.- **Maintenance Schedule** — preventive maintenance plan with frequency, priority, estimated duration, and required spare parts. `takesWorkCenterOffline` marks the PM as blocking the machine; the nightly generator (`packages/jobs/.../scheduled/dispatch.ts`) copies it onto each generated dispatch and sets `plannedEndTime = plannedStartTime + estimatedDuration` (so the offline window is bounded — the validator requires a duration when offline is on).- **Failure Mode** — categorized failure type used by maintenance dispatches and quality NCRs.-- **Training** — training programs with assignments, quiz questions, and frequency-based recertification. Completion tracked via `trainingCompletion`. **Status changes only from the header** (`TrainingHeader`): Draft shows Publish, Active shows Archive, and Reopen (back to Draft) is in the ⋯ menu — each through a `Confirm` posting `field=status` to `x+/training+/update.tsx` (`updateTrainingField`); Properties has no Status field. The name is edited in Properties (the content editor has no title block). The **Content** card holds a **Write | Upload PDF | YouTube Video** toggle: a training's content is written (`content`) OR one PDF (`training.guidePath`, key `{companyId}/training/{trainingId}/{uploadId}/{file name}`, checked by `isValidTrainingGuideKey`) OR one YouTube video (`training.videoUrl`, `20261022045258_training-video.sql`; any YouTube link is parsed by `getYouTubeVideoId` and stored as `youTubeWatchUrl`), never two — a training with a `guidePath` is a PDF training, one with a `videoUrl` a video training, and the employee page shows the PDF or the video (`TrainingVideoPlayer`, a youtube-nocookie embed) instead of the written content. Setting `guidePath` clears `videoUrl` and setting `videoUrl` clears `guidePath`; switching kinds on the toggle confirms, then clears the saved one. `guidePath` and `videoUrl` change only while Draft (`updateTrainingField` filters its update on `status = 'Draft'` and refuses when no row changed). **External training is an assignment, not a training**: `trainingAssignment.trainingId` is nullable and an external assignment carries only `name` (CHECK `num_nonnulls("trainingId", "name") = 1`, `20261014164752_external-training-assignments.sql`). It is one-time (the status RPCs report frequency `Once`), sends no notifications or weekly reminders, and has no employee page (`share/training.$id` 404s it). The status and summary RPCs LEFT JOIN `training`, return `isExternal`, and the summary is one row per assignment; the assignments list and roster drawer (`assignments.$assignmentId.tsx`, `path.to.trainingAssignmentDetail(assignmentId)`) are keyed by assignment. Every completion — the employee's quiz (`share/training.$id`) and an admin's Mark Complete (`assignments.complete`) — goes through `recordTrainingCompletion` (`resources.service.ts`): it refuses an internal training that is not Active, uploads the OPTIONAL certificate of an external assignment (`validateTrainingCertificate`, async: PDF/PNG/JPG by extension AND file signature, 10 MB; key `{companyId}/training-certificates/{assignmentId}/{employeeId}/…` built on the server), works out the period on the server, removes the uploaded file when the insert fails, treats a duplicate completion as already recorded, and restamps the scheduler for a granted ability. `completeTrainingAssignment` refuses an employee outside the assignment's groups (`users_for_groups`). `updateTrainingAssignment` reads internal/external from the stored assignment, never the input. `uncompleteTrainingAssignment` (`delete: resources`) removes a wrong completion and its certificate file; the granted ability stays (the grant trigger only adds). The status RPC returns each completion's `certificatePath`. The assignment drawer (`assignments.$assignmentId.tsx`) is the only per-employee roster; the edit form has no Status tab.+- **Training** — training programs with assignments, quiz questions, and frequency-based recertification. Completion tracked via `trainingCompletion`. **Status changes only from the header** (`TrainingHeader`): Draft shows Publish, Active shows Archive, and Reopen (back to Draft) is in the ⋯ menu — each through a `Confirm` posting `field=status` to `x+/training+/update.tsx` (`updateTrainingField`); Properties has no Status field. The name is edited in Properties (the content editor has no title block). The **Content** card holds a **Write | Upload PDF | YouTube Video** toggle: a training's content is written (`content`) OR one PDF (`training.guidePath`, key `{companyId}/training/{trainingId}/{uploadId}/{file name}`, checked by `isValidTrainingGuideKey`) OR one YouTube video (`training.videoUrl`, `20261022045258_training-video.sql`; any YouTube link is parsed by `getYouTubeVideoId` and stored as `youTubeWatchUrl`), never two — a training with a `guidePath` is a PDF training, one with a `videoUrl` a video training, and the employee page shows the PDF or the video (`TrainingVideoPlayer`, a youtube-nocookie embed) instead of the written content. Setting `guidePath` clears `videoUrl` and setting `videoUrl` clears `guidePath`; switching kinds on the toggle confirms, then clears the saved one. `guidePath` and `videoUrl` change only while Draft (`updateTrainingField` filters its update on `status = 'Draft'` and refuses when no row changed). **External training is an assignment, not a training**: `trainingAssignment.trainingId` is nullable and an external assignment carries only `name` (CHECK `num_nonnulls("trainingId", "name") = 1`, `20261014164752_external-training-assignments.sql`). It is one-time (the status RPCs report frequency `Once`), sends no notifications or weekly reminders, and has no employee page (`share/training.$id` 404s it). The status and summary RPCs LEFT JOIN `training`, return `isExternal`, and the summary is one row per assignment; the assignments list and roster drawer (`assignments.$assignmentId.tsx`, `path.to.trainingAssignmentDetail(assignmentId)`) are keyed by assignment. Every completion — the employee's quiz (`share/training.$id`) and an admin's Mark Complete (`assignments.complete`) — goes through `recordTrainingCompletion` (`resources.service.ts`): it refuses an internal training that is not Active, uploads the OPTIONAL certificate of an external assignment (`validateTrainingCertificate`, async: PDF/PNG/JPG by extension AND file signature, 10 MB; key `{companyId}/training-certificates/{assignmentId}/{employeeId}/…` built on the server), works out the period on the server, removes the uploaded file when the insert fails, treats a duplicate completion as already recorded, and restamps the scheduler for a granted ability. `completeTrainingAssignment` refuses an employee outside the assignment's groups (`users_for_groups`). A person's own group (`isIdentityGroup`, no `companyId`) counts: `users_for_groups` keeps it when that user belongs to one of the caller's companies (`20261026114317_users-for-groups-identity-groups.sql`). `updateTrainingAssignment` reads internal/external from the stored assignment, never the input. `uncompleteTrainingAssignment` (`delete: resources`) removes a wrong completion and its certificate file; the granted ability stays (the grant trigger only adds). The status RPC returns each completion's `certificatePath`. The assignment drawer (`assignments.$assignmentId.tsx`) is the only per-employee roster; the edit form has no Status tab.## Safetydiff --git a/apps/erp/app/modules/resources/resources.service.ts b/apps/erp/app/modules/resources/resources.service.tsindex 2617a30c00..0f5e022620 100644--- a/apps/erp/app/modules/resources/resources.service.ts+++ b/apps/erp/app/modules/resources/resources.service.ts@@ -1410,13 +1410,17 @@ export async function updateTrainingQuestionOrder(return Promise.all(updatePromises);}+/**+ * `abilities` replaces the contractor's abilities when sent; left out, they are+ * kept (the contractor form has no abilities field).+ */export async function upsertContractor(client: SupabaseClient<Database>,contractorWithAbilities:| {id: string;hoursPerWeek?: number;- abilities: string[];+ abilities?: string[];companyId: string;createdBy: string;customFields?: Json;@@ -1424,7 +1428,7 @@ export async function upsertContractor(| {id: string;hoursPerWeek?: number;- abilities: string[];+ abilities?: string[];companyId: string;updatedBy: string;customFields?: Json;@@ -1439,6 +1443,7 @@ export async function upsertContractor(if (updateContractor.error) {return updateContractor;}+ if (abilities === undefined) return updateContractor;const deleteContractorAbilities = await client.from("contractorAbility").delete()@@ -1453,9 +1458,10 @@ export async function upsertContractor(if (createContractor.error) {return createContractor;}+ if (abilities === undefined) return createContractor;}- const contractorAbilities = abilities.map((ability) => {+ const contractorAbilities = (abilities ?? []).map((ability) => {return {contractorId: contractor.id,abilityId: ability,diff --git a/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsx b/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsxindex 845402b15e..f9c4d2eb9c 100644--- a/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsx+++ b/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsx@@ -3,6 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { MENU_ITEM_SHORTCUTS, MenuIcon, MenuItem } from "@carbon/react";+import { getLocalTimeZone, today } from "@internationalized/date";import { Trans, useLingui } from "@lingui/react/macro";import type { ColumnDef } from "@tanstack/react-table";import { memo, useCallback, useMemo } from "react";@@ -75,9 +76,11 @@ const AbilitiesTable = memo(({ data, count }: AbilitiesTableProps) => {cell: ({ row }) => {// Qualified = has an ability row ∧ not expired. Presence of the row// is the qualification — there is no separate training gate.- const today = new Date().toISOString().slice(0, 10);+ const todayDate = today(getLocalTimeZone()).toString();const employeeIds = (row.original.employeeAbility ?? [])- .filter((ea) => !ea.expiresAt || ea.expiresAt >= today)+ .filter(+ (ea) => !ea.expiresAt || ea.expiresAt.slice(0, 10) > todayDate+ ).map((ea) => ea.employeeId);return employeeIds.length > 0 ? (<EmployeeAvatarGroup employeeIds={employeeIds} />diff --git a/apps/erp/app/routes/x+/people+/holidays.$holidayId.tsx b/apps/erp/app/routes/x+/people+/holidays.$holidayId.tsxindex 7e9fbf052c..b19749a5a8 100644--- a/apps/erp/app/routes/x+/people+/holidays.$holidayId.tsx+++ b/apps/erp/app/routes/x+/people+/holidays.$holidayId.tsx@@ -2,15 +2,16 @@// 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 { carbon, respond } from "@carbon/api/carbon.server";+import { error, notFound } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";-import { validationError, validator } from "@carbon/form";+import { validator } from "@carbon/form";import { redirect } from "@carbon/utils";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData } from "react-router";import { holidayValidator } from "~/modules/people/people.models";-import { getHoliday, upsertHoliday } from "~/modules/people/people.service";+import { getHoliday } from "~/modules/people/people.service";import { HolidayForm } from "~/modules/people/ui/Holidays";import { getCustomFields } from "~/utils/form";import { path } from "~/utils/path";@@ -37,43 +38,16 @@ export async function loader({ request, params }: LoaderFunctionArgs) {};}-export async function action({ request }: ActionFunctionArgs) {- assertIsPost(request);- const { client, userId } = await requirePermissions(request, {- create: "people"- });-- const formData = await request.formData();- const validation = await validator(holidayValidator).validate(formData);-- if (validation.error) {- return validationError(validation.error);- }-- const { id, name, date } = validation.data;+export async function action(args: ActionFunctionArgs) {+ const input = await validator(holidayValidator).request(args);+ if ("invalid" in input) return input.invalid;+ const { id, name, date } = input.data;if (!id) throw notFound("Holiday ID was not found");-- const updateHoliday = await upsertHoliday(client, {- id,- name,- date,- updatedBy: userId+ const api = await carbon(args.request);+ const result = await api.people.updateHoliday({ id, name, date });+ return respond(args.request, result).redirect(path.to.holidays, {+ message: "Holiday updated"});-- if (updateHoliday.error) {- throw redirect(- path.to.holidays,- await flash(- request,- error(updateHoliday.error, "Failed to create holiday.")- )- );- }-- throw redirect(- path.to.holidays,- await flash(request, success("Holiday updated"))- );}export default function HolidayRoute() {diff --git a/apps/erp/app/routes/x+/people+/holidays.delete.$holidayId.tsx b/apps/erp/app/routes/x+/people+/holidays.delete.$holidayId.tsxindex 99ffb527bf..e43f59dbcc 100644--- a/apps/erp/app/routes/x+/people+/holidays.delete.$holidayId.tsx+++ b/apps/erp/app/routes/x+/people+/holidays.delete.$holidayId.tsx@@ -2,7 +2,8 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error, notFound, success } from "@carbon/auth";+import { carbon, respond } from "@carbon/api/carbon.server";+import { error, notFound } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";@@ -10,7 +11,7 @@ import { useLingui } from "@lingui/react/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";-import { deleteHoliday, getHoliday } from "~/modules/people/people.service";+import { getHoliday } from "~/modules/people/people.service";import { path } from "~/utils/path";export async function loader({ request, params }: LoaderFunctionArgs) {@@ -36,33 +37,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}export async function action({ request, params }: ActionFunctionArgs) {- const { client } = await requirePermissions(request, {- delete: "people"- });-const { holidayId } = params;- if (!holidayId) {- throw redirect(- path.to.holidays,- await flash(request, error(params, "Failed to get holiday id"))- );- }-- const { error: deleteHolidayError } = await deleteHoliday(client, holidayId);- if (deleteHolidayError) {- throw redirect(- path.to.holidays,- await flash(- request,- error(deleteHolidayError, "Failed to delete holiday")- )- );- }-- throw redirect(- path.to.holidays,- await flash(request, success("Successfully deleted holiday"))- );+ if (!holidayId) throw notFound("Holiday ID was not found");+ const api = await carbon(request);+ const result = await api.people.deleteHoliday({ holidayId });+ return respond(request, result).redirect(path.to.holidays, {+ message: "Successfully deleted holiday"+ });}export default function DeleteHolidayRoute() {diff --git a/apps/erp/app/routes/x+/people+/holidays.new.tsx b/apps/erp/app/routes/x+/people+/holidays.new.tsxindex f5c7fcb5e3..bd37cc067c 100644--- a/apps/erp/app/routes/x+/people+/holidays.new.tsx+++ b/apps/erp/app/routes/x+/people+/holidays.new.tsx@@ -2,55 +2,26 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { assertIsPost, error, success } from "@carbon/auth";-import { requirePermissions } from "@carbon/auth/auth.server";-import { flash } from "@carbon/auth/session.server";-import { validationError, validator } from "@carbon/form";-import { redirect } from "@carbon/utils";+import { carbon, respond } from "@carbon/api/carbon.server";+import { validator } from "@carbon/form";import type { ActionFunctionArgs } from "react-router";import { holidayValidator } from "~/modules/people/people.models";-import { upsertHoliday } from "~/modules/people/people.service";import { HolidayForm } from "~/modules/people/ui/Holidays";import { setCustomFields } from "~/utils/form";import { path } from "~/utils/path";-export async function action({ request }: ActionFunctionArgs) {- assertIsPost(request);- const { client, companyId, userId } = await requirePermissions(request, {- create: "people"+export async function action(args: ActionFunctionArgs) {+ const input = await validator(holidayValidator).request(args);+ if ("invalid" in input) return input.invalid;+ const { id: _id, ...holiday } = input.data;+ const api = await carbon(args.request);+ const result = await api.people.createHoliday({+ ...holiday,+ customFields: input.formData && setCustomFields(input.formData)});-- const formData = await request.formData();- const validation = await validator(holidayValidator).validate(formData);-- if (validation.error) {- return validationError(validation.error);- }-- // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration- const { id, ...d } = validation.data;-- const createHoliday = await upsertHoliday(client, {- ...d,- companyId,- createdBy: userId,- customFields: setCustomFields(formData)+ return respond(args.request, result).redirect(path.to.holidays, {+ message: "Holiday created"});-- if (createHoliday.error) {- throw redirect(- path.to.holidays,- await flash(- request,- error(createHoliday.error, "Failed to create holiday.")- )- );- }-- throw redirect(- path.to.holidays,- await flash(request, success("Holiday created"))- );}export default function NewHolidayRoute() {diff --git a/apps/erp/app/routes/x+/people+/shifts.delete.$shiftId.tsx b/apps/erp/app/routes/x+/people+/shifts.delete.$shiftId.tsxindex 3d517db94b..e162eb405c 100644--- a/apps/erp/app/routes/x+/people+/shifts.delete.$shiftId.tsx+++ b/apps/erp/app/routes/x+/people+/shifts.delete.$shiftId.tsx@@ -2,7 +2,8 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { error, notFound, success } from "@carbon/auth";+import { carbon, respond } from "@carbon/api/carbon.server";+import { error, notFound } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { redirect } from "@carbon/utils";@@ -10,7 +11,7 @@ import { useLingui } from "@lingui/react/macro";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { useLoaderData, useNavigate, useParams } from "react-router";import { ConfirmDelete } from "~/components/Modals";-import { deleteShift, getShift } from "~/modules/people/people.service";+import { getShift } from "~/modules/people/people.service";import { path } from "~/utils/path";export async function loader({ request, params }: LoaderFunctionArgs) {@@ -36,30 +37,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {}export async function action({ request, params }: ActionFunctionArgs) {- const { client } = await requirePermissions(request, {- delete: "people"- });-const { shiftId } = params;- if (!shiftId) {- throw redirect(- path.to.shifts,- await flash(request, error(params, "Failed to get shift id"))- );- }-- const { error: deleteShiftError } = await deleteShift(client, shiftId);- if (deleteShiftError) {- throw redirect(- path.to.shifts,- await flash(request, error(deleteShiftError, "Failed to delete shift"))- );- }-- throw redirect(- path.to.shifts,- await flash(request, success("Successfully deleted shift"))- );+ if (!shiftId) throw notFound("Shift ID was not found");+ const api = await carbon(request);+ const result = await api.people.deleteShift({ shiftId });+ return respond(request, result).redirect(path.to.shifts, {+ message: "Successfully deleted shift"+ });}export default function DeleteShiftRoute() {diff --git a/apps/erp/app/routes/x+/priority+/people.tsx b/apps/erp/app/routes/x+/priority+/people.tsxindex a239fa27d3..76b9acef8f 100644--- a/apps/erp/app/routes/x+/priority+/people.tsx+++ b/apps/erp/app/routes/x+/priority+/people.tsx@@ -7,6 +7,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { formatDate, redirect } from "@carbon/utils";import {+ fromAbsolute,getLocalTimeZone,now,parseDate,@@ -27,6 +28,7 @@ import {import {buildPeopleCapacityBuckets,getActiveEmployeeAbilities,+ getHolidayDates,getLocationEmployees,getPeopleAbsences,getPeopleAbsencesRange,@@ -36,7 +38,8 @@ import {getWorkCenterCalendarHoursByDay,getWorkCenterRequiredAbilities,getWorkCenterReservationsRange,- getWorkCenterShifts+ getWorkCenterShifts,+ getWorkCenterWorkingWindows} from "~/modules/production/production.service";import { OvertimeDialog } from "~/modules/production/ui/Schedule/People/OvertimeDialog";import { PeopleBoard } from "~/modules/production/ui/Schedule/People/PeopleBoard";@@ -289,6 +292,7 @@ export async function loader({ request }: LoaderFunctionArgs) {// each work center resolved via (the assumption banner) — Capacity view onlylet calendarHoursByWorkCenter: Record<string, Record<string, number>> = {};const capacityRungByWorkCenter: Record<string, number> = {};+ let capacityHolidayDates: string[] = [];if (view !== "board" || range === "week") {const weekStartDate = weekDates[0];@@ -350,8 +354,24 @@ export async function loader({ request }: LoaderFunctionArgs) {// The engine (@carbon/planning) owns the authoritative machine-availability// ladder; this resolves the same rungs at day granularity for display.let calendarHoursMap = new Map<string, Map<string, number>>();+ let workingWindowsByWorkCenter:+ | ReturnType<typeof getWorkCenterWorkingWindows>+ | undefined;if (view === "capacity") {const wcShiftLinks = workCenterShiftRows.data ?? [];+ // A booking can run past the week on either side; its working windows+ // (and holidays) are needed across its whole span to divide its hours.+ let spanStartMs = weekWindowStart.getTime();+ let spanEndMs = weekWindowEnd.getTime();+ for (const reservation of reservations.data ?? []) {+ spanStartMs = Math.min(spanStartMs, Date.parse(reservation.startAt));+ spanEndMs = Math.max(spanEndMs, Date.parse(reservation.endAt));+ }+ const holidayDates = await getHolidayDates(client, companyId, {+ from: toCalendarDate(fromAbsolute(spanStartMs, timezone)).toString(),+ to: toCalendarDate(fromAbsolute(spanEndMs, timezone)).toString()+ });+ capacityHolidayDates = [...holidayDates];const ladderWorkCenters = (workCenters.data ?? []).flatMap((workCenter) =>workCenter.id@@ -380,7 +400,17 @@ export async function loader({ request }: LoaderFunctionArgs) {workCenters: ladderWorkCenters,workCenterShifts: wcShiftLinks,locationShifts: locationLadderShifts,- weekDates+ weekDates,+ holidayDates+ });+ workingWindowsByWorkCenter = getWorkCenterWorkingWindows({+ workCenters: ladderWorkCenters,+ workCenterShifts: wcShiftLinks,+ shifts: shiftRows,+ timeZone: timezone,+ holidayDates,+ rangeStart: spanStartMs,+ rangeEnd: spanEndMs});const wcHasOwnShifts = new Set(wcShiftLinks.map((link) => link.workCenterId)@@ -406,7 +436,8 @@ export async function loader({ request }: LoaderFunctionArgs) {timezone,operations: capacityOperations.data ?? [],reservations: reservations.data ?? [],- calendarHoursByWorkCenter: calendarHoursMap+ calendarHoursByWorkCenter: calendarHoursMap,+ workingWindowsByWorkCenter});demandByWorkCenter = buckets.demandByWorkCenter;scheduledByWorkCenter = buckets.scheduledByWorkCenter;@@ -442,7 +473,8 @@ export async function loader({ request }: LoaderFunctionArgs) {{const byEmployee = new Map<string, Set<string>>();for (const row of employeeAbilities.data ?? []) {- if (row.expiresAt && row.expiresAt.slice(0, 10) < date) continue;+ // Expiring today = not qualified today, as in the scheduler and MES.+ if (row.expiresAt && row.expiresAt.slice(0, 10) <= date) continue;const ability = Array.isArray(row.ability) ? row.ability[0] : row.ability;// The ability's name IS the linked process's name.const process = Array.isArray(ability?.process)@@ -510,7 +542,8 @@ export async function loader({ request }: LoaderFunctionArgs) {defaultShiftEnd,defaultShiftHours,calendarHoursByWorkCenter,- capacityRungByWorkCenter+ capacityRungByWorkCenter,+ capacityHolidayDates};}@@ -549,7 +582,8 @@ export default function SchedulePeopleRoute() {defaultShiftEnd,defaultShiftHours,calendarHoursByWorkCenter,- capacityRungByWorkCenter+ capacityRungByWorkCenter,+ capacityHolidayDates} = useLoaderData<typeof loader>();const { locale } = useLocale();const [overtimeOpen, setOvertimeOpen] = useState(false);@@ -772,6 +806,7 @@ export default function SchedulePeopleRoute() {defaultShiftHours={defaultShiftHours}calendarHoursByWorkCenter={calendarHoursByWorkCenter}capacityRungByWorkCenter={capacityRungByWorkCenter}+ holidayDates={capacityHolidayDates}/>)}</div>diff --git a/apps/erp/app/routes/x+/resources+/contractors.$supplierContactId.tsx b/apps/erp/app/routes/x+/resources+/contractors.$supplierContactId.tsxindex 6d640e2a65..f91b0b1ddc 100644--- a/apps/erp/app/routes/x+/resources+/contractors.$supplierContactId.tsx+++ b/apps/erp/app/routes/x+/resources+/contractors.$supplierContactId.tsx@@ -60,8 +60,6 @@ export async function action({ request }: ActionFunctionArgs) {const updateContractor = await upsertContractor(client, {id,...d,- // @ts-expect-error TS2339 - TODO: fix type- abilities: d.abilities ?? [],customFields: setCustomFields(formData),companyId,updatedBy: userIddiff --git a/apps/erp/app/routes/x+/scheduling+/forecast.tsx b/apps/erp/app/routes/x+/scheduling+/forecast.tsxindex 18b9fb00b2..d692d143ac 100644--- a/apps/erp/app/routes/x+/scheduling+/forecast.tsx+++ b/apps/erp/app/routes/x+/scheduling+/forecast.tsx@@ -9,6 +9,7 @@ import type { CalendarDate } from "@internationalized/date";import {CalendarDateTime,DateFormatter,+ fromAbsolute,getDayOfWeek,now,parseAbsolute,@@ -34,6 +35,7 @@ import {import {getCapacityReservationsForResources,getForecastNonWorkingIntervals,+ getHolidayDates,getMaintenanceDowntimeForResources} from "~/modules/production/production.service";import ForecastUpgradeOverlay from "~/modules/production/ui/ForecastUpgradeOverlay";@@ -208,20 +210,24 @@ export async function loader({ request }: LoaderFunctionArgs) {// from the SAME availability ladder the scheduler uses — so the shaded// background can't disagree with the bars. Shades the axis so a reservation// spanning several days no longer reads as 24h/day.- const nonWorkingIntervals = getForecastNonWorkingIntervals({- timeZone,- shifts,- windowStartMs,- windowEndMs- });-- const [reservations, maintenanceResult] = await Promise.all([+ const [reservations, maintenanceResult, holidayDates] = await Promise.all([getCapacityReservationsForResources(client, companyId, locationId, {from: new Date(windowStartMs).toISOString(),to: new Date(windowEndMs).toISOString()}),- getMaintenanceDowntimeForResources(client, companyId, locationId)+ getMaintenanceDowntimeForResources(client, companyId, locationId),+ getHolidayDates(client, companyId, {+ from: toCalendarDate(fromAbsolute(windowStartMs, timeZone)).toString(),+ to: toCalendarDate(fromAbsolute(windowEndMs, timeZone)).toString()+ })]);+ const nonWorkingIntervals = getForecastNonWorkingIntervals({+ timeZone,+ shifts,+ windowStartMs,+ windowEndMs,+ holidayDates+ });// Open outages that take a work center offline, as [start, end) windows for// the resource lanes. Prefer actual times once work has started; fall back todiff --git a/docs/content/docs/reference/people.mdx b/docs/content/docs/reference/people.mdxindex c0cea6d054..b65ac90ef4 100644--- a/docs/content/docs/reference/people.mdx+++ b/docs/content/docs/reference/people.mdx@@ -62,6 +62,8 @@ Deleting a shift marks it inactive instead of removing it, preserving historicalA **holiday** is a company non-working day: a name and a date. The year is derived from the date automatically, and the list groups by year so you can review one calendar year at a time.+A holiday closes the plant for [scheduling](/docs/reference/scheduling): no operation is placed on that day, except on a lights-out (24×7) work center, and nobody is counted as available. Forecast shades the day as closed, and the capacity view on Resource Planning shows no available hours for it. Adding, editing, or deleting a holiday queues a reschedule.+<FieldTable><Field name="Holiday Name" type="text">What the day is called.</Field><Field name="Date" type="date">The calendar date. Its year is computed from this.</Field>diff --git a/docs/content/docs/reference/scheduling.mdx b/docs/content/docs/reference/scheduling.mdxindex 1bda374b41..1111cebb75 100644--- a/docs/content/docs/reference/scheduling.mdx+++ b/docs/content/docs/reference/scheduling.mdx@@ -23,7 +23,7 @@ Due dates, dispatch order, and manning are all set in the ERP. The MES board refThe engine schedules **forward**: each operation is placed at the earliest feasible moment after *now* and after its predecessors in the [routing](/docs/reference/routings) finish. There is no backward pass that anchors work on the due date; the projected finish that falls out of placement *is* the forecast, and slack is real. Two finite resources gate every placement:-1. **The work center.** One operation at a time, placed only inside its operating hours. Hours come from a ladder: a **lights-out (24×7)** work center is always open; otherwise its own assigned shifts apply; otherwise the location's shifts; otherwise a stock Mon–Fri, 8-hour day. Open [maintenance](/docs/reference/maintenance) dispatches that take a work center offline subtract their downtime from those hours, lights-out machines included.+1. **The work center.** One operation at a time, placed only inside its operating hours. Hours come from a ladder: a **lights-out (24×7)** work center is always open; otherwise its own assigned shifts apply; otherwise the location's shifts; otherwise a stock Mon–Fri, 8-hour day. Open [maintenance](/docs/reference/maintenance) dispatches that take a work center offline subtract their downtime from those hours, lights-out machines included. A company [holiday](/docs/reference/people#holidays) closes every work center for the day, except lights-out ones.2. **Qualified people**, when the operation's process requires an ability. See [the next section](#people-are-part-of-capacity).When a process can run on more than one work center, the engine picks the candidate that **finishes earliest**, so work naturally routes around a backed-up or unstaffed machine. An operation that has already started stays on its work center, and only the *remaining* work is reserved: labor and machine time are scaled by the quantity still open, and setup counts as done once any production event exists.@@ -82,7 +82,7 @@ The engine always produces a complete answer. Late work is placed and flagged, u## When the schedule recomputes-Scheduling reacts to its inputs. Editing anything the engine reads — a due date on the Priorities board, a manning assignment, a shift, a work center's hours or active flag, an operator qualification, a process's ability requirement, machine downtime — stamps the affected jobs **schedule outdated** and queues a **replan wave**. The wave is debounced about 30 seconds, so a burst of edits triggers a single regeneration of each affected location rather than one run per keystroke. The Forecast's **Regenerate** button runs the same whole-location regeneration on demand.+Scheduling reacts to its inputs. Editing anything the engine reads — a due date on the Priorities board, a manning assignment, a shift, a work center's hours or active flag, an operator qualification, a process's ability requirement, machine downtime, a company holiday — stamps the affected jobs **schedule outdated** and queues a **replan wave**. The wave is debounced about 30 seconds, so a burst of edits triggers a single regeneration of each affected location rather than one run per keystroke. The Forecast's **Regenerate** button runs the same whole-location regeneration on demand.Job release or status changes and the kanban auto-release flow reschedule immediately. A nightly pass also recalculates schedules whose planned start is in the past.diff --git a/docs/content/src/glossary/terms.ts b/docs/content/src/glossary/terms.tsindex 8dd8f657d6..5922de5a06 100644--- a/docs/content/src/glossary/terms.ts+++ b/docs/content/src/glossary/terms.ts@@ -1960,7 +1960,7 @@ export const terms = {// ── Resources: Contractors (ContractorForm) ─────────────────────────────"contractor-hours-per-week": {term: msg`Hours per Week`,- definition: msg`The contractor's expected weekly availability; scheduling uses this as the upper bound when assigning this contractor to operations across the week.`+ definition: msg`The contractor's expected weekly availability, for reference. The scheduler does not book contractors on operations.`},// ── Resources: Processes (ProcessForm) ──────────────────────────────────diff --git a/packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.ts b/packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.tsindex d190ab2447..738d0a89c5 100644--- a/packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.ts+++ b/packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.ts@@ -11,6 +11,7 @@ import { NonRetriableError } from "inngest";import { z } from "zod";import { getJobDatabaseClient } from "../../../db";import { inngest } from "../../client";+import { workCentersOnShift } from "./shift-work-centers";const log = getLogger("jobs", "schedule-replan");@@ -64,6 +65,56 @@ const scheduleInputsChangedData = z.object({recoveryAttempt: z.number().int().min(0).optional()});+/**+ * The work centers whose hours come from this shift (`workCentersOnShift`),+ * or null when the shift is not the company's.+ */+async function loadShiftWorkCenterIds(+ serviceRole: ReturnType<typeof getCarbonServiceRole>,+ companyId: string,+ shiftId: string+): Promise<string[] | null> {+ const [shift, workCenters, links, activeShifts] = await Promise.all([+ serviceRole+ .from("shift")+ .select("id, locationId")+ .eq("id", shiftId)+ .eq("companyId", companyId)+ .maybeSingle(),+ fetchAllFromTable<{+ id: string;+ locationId: string | null;+ alwaysOn: boolean;+ }>(serviceRole, "workCenter", "id, locationId, alwaysOn", (query) =>+ query.eq("companyId", companyId).eq("active", true).order("id")+ ),+ fetchAllFromTable<{ workCenterId: string; shiftId: string }>(+ serviceRole,+ "workCenterShift",+ "workCenterId, shiftId",+ (query) =>+ query.eq("companyId", companyId).order("workCenterId").order("shiftId")+ ),+ fetchAllFromTable<{ id: string }>(serviceRole, "shift", "id", (query) =>+ query.eq("companyId", companyId).eq("active", true).order("id")+ )+ ]);+ const failed =+ shift.error ?? workCenters.error ?? links.error ?? activeShifts.error;+ if (failed) {+ throw new Error(+ `Failed to load the shift's work centers: ${failed.message}`+ );+ }+ if (!shift.data) return null;+ return workCentersOnShift({+ shift: { id: shift.data.id, locationId: shift.data.locationId },+ workCenters: workCenters.data ?? [],+ workCenterShifts: links.data ?? [],+ activeShiftIds: new Set((activeShifts.data ?? []).map((row) => row.id))+ });+}+/*** Reactive replanning, part 1 — MARK (immediate, cheap).*@@ -117,6 +168,8 @@ export const markScheduleStaleFunction = inngest.createFunction(// - ability/shift/employee-shift (no id) -> jobs with unfinished ops on ANY// ability-gated process (people-availability changes only matter to gated work;// a company with zero gated ops is untouched)+ // - shift (with id) -> the gated jobs above PLUS jobs with unfinished ops+ // on the work centers that run the shift (machine hours)// - work-center (with id) -> jobs with unfinished ops assigned to that work center// - people (with id) -> same as work-center (entityId = the assigned workCenterId)// - people (no id) -> absence of an unassigned person; only gated ops care@@ -145,44 +198,59 @@ export const markScheduleStaleFunction = inngest.createFunction(processIds = (gated.data ?? []).map((p) => p.id);}+ // A shift is also machine hours: the work centers that run it re-plan+ // too, gated or not.+ let shiftWorkCenterIds: string[] = [];+ if (kind === "shift" && entityId) {+ const scope = await loadShiftWorkCenterIds(+ serviceRole,+ companyId,+ entityId+ );+ if (scope === null) return null; // unknown shift: re-plan everything+ shiftWorkCenterIds = scope;+ }+if (processIds !== null ||((kind === "work-center" || kind === "people") && entityId)) {- if (processIds !== null && processIds.length === 0) {- return []; // nothing gated -> nothing affected- }- // Chunk the .in() filter so a large gated-process set can't blow- // past PostgREST's URL limits- const processIdChunks: (string[] | null)[] =+ const filters: {+ column: "processId" | "workCenterId";+ values: string[];+ }[] =processIds !== null- ? chunkArray(processIds, IN_FILTER_CHUNK_SIZE)- : [null];+ ? [+ { column: "processId", values: processIds },+ { column: "workCenterId", values: shiftWorkCenterIds }+ ]+ : [{ column: "workCenterId", values: [entityId as string] }];const jobIds = new Set<string>();- for (const processIdChunk of processIdChunks) {- const ops = await fetchAllFromTable<{ jobId: string }>(- serviceRole,- "jobOperation",- "jobId",- (query) => {- const scoped = query- .eq("companyId", companyId)- .not("status", "in", '("Done","Canceled")');- return processIdChunk !== null- ? scoped.in("processId", processIdChunk)- : scoped.eq("workCenterId", entityId);- }- );- if (ops.error) {- throw new Error(- `Failed to compute affected jobs: ${ops.error.message}`+ for (const { column, values } of filters) {+ // Chunk the .in() filter so a large set can't blow past+ // PostgREST's URL limits+ for (const chunk of chunkArray(values, IN_FILTER_CHUNK_SIZE)) {+ const ops = await fetchAllFromTable<{ jobId: string }>(+ serviceRole,+ "jobOperation",+ "jobId",+ (query) =>+ query+ .eq("companyId", companyId)+ .not("status", "in", '("Done","Canceled")')+ .in(column, chunk));- }- for (const op of ops.data ?? []) {- jobIds.add(op.jobId);+ if (ops.error) {+ throw new Error(+ `Failed to compute affected jobs: ${ops.error.message}`+ );+ }+ for (const op of ops.data ?? []) {+ jobIds.add(op.jobId);+ }}}- return [...jobIds];+ return [...jobIds]; // empty = nothing affected}return null; // company-wide (location, reorder, or no way to scope)diff --git a/packages/jobs/src/inngest/functions/scheduled/shift-work-centers.test.ts b/packages/jobs/src/inngest/functions/scheduled/shift-work-centers.test.tsnew file mode 100644index 0000000000..3b1e829926--- /dev/null+++ b/packages/jobs/src/inngest/functions/scheduled/shift-work-centers.test.ts@@ -0,0 +1,51 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { workCentersOnShift } from "./shift-work-centers";++// The plant: Day (active) and Weekend (the shift being changed, active).+const base = (+ overrides: Partial<Parameters<typeof workCentersOnShift>[0]> = {}+) =>+ workCentersOnShift({+ shift: { id: "weekend", locationId: "plant" },+ workCenters: [+ { id: "pcb-lab", locationId: "plant", alwaysOn: false }, // all shifts+ { id: "cnc-mill", locationId: "plant", alwaysOn: false }, // Day only+ { id: "tig", locationId: "plant", alwaysOn: false }, // Weekend only+ { id: "tvac", locationId: "plant", alwaysOn: true }, // lights-out+ { id: "flatsat", locationId: "hq", alwaysOn: false } // another location+ ],+ workCenterShifts: [+ { workCenterId: "cnc-mill", shiftId: "day" },+ { workCenterId: "tig", shiftId: "weekend" }+ ],+ activeShiftIds: new Set(["day", "weekend"]),+ ...overrides+ });++describe("workCentersOnShift", () => {+ it("is the stations linked to the shift plus the location's unlinked stations", () => {+ expect(base()).toEqual(["pcb-lab", "tig"]);+ });++ it("keeps a removed shift's own stations: their hours fall back to the location's", () => {+ expect(base({ activeShiftIds: new Set(["day"]) })).toEqual([+ "pcb-lab",+ "tig"+ ]);+ });++ it("treats a station whose only links are inactive shifts as unlinked", () => {+ expect(+ base({+ workCenterShifts: [+ { workCenterId: "cnc-mill", shiftId: "old-night" },+ { workCenterId: "tig", shiftId: "weekend" }+ ]+ })+ ).toEqual(["pcb-lab", "cnc-mill", "tig"]);+ });+});diff --git a/packages/jobs/src/inngest/functions/scheduled/shift-work-centers.ts b/packages/jobs/src/inngest/functions/scheduled/shift-work-centers.tsnew file mode 100644index 0000000000..73770d35ee--- /dev/null+++ b/packages/jobs/src/inngest/functions/scheduled/shift-work-centers.ts@@ -0,0 +1,41 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++/**+ * The work centers whose hours come from a shift: the machine side of a shift+ * change (the people side is the gated-process scoping). Follows the+ * scheduler's availability ladder (`resolveWorkCenterWindows`):+ *+ * - a lights-out (`alwaysOn`) station runs 24×7 and ignores shifts;+ * - a station linked to this shift runs it, so an added, edited or removed+ * shift changes its hours;+ * - a station with no link to an active shift runs every shift at its+ * location, so any shift at that location changes its hours.+ */+export function workCentersOnShift(args: {+ shift: { id: string; locationId: string | null };+ workCenters: { id: string; locationId: string | null; alwaysOn: boolean }[];+ workCenterShifts: { workCenterId: string; shiftId: string }[];+ activeShiftIds: Set<string>;+}): string[] {+ const { shift, workCenters, workCenterShifts, activeShiftIds } = args;+ const linkedToThisShift = new Set<string>();+ const linkedToActiveShift = new Set<string>();+ for (const link of workCenterShifts) {+ if (link.shiftId === shift.id) linkedToThisShift.add(link.workCenterId);+ if (activeShiftIds.has(link.shiftId)) {+ linkedToActiveShift.add(link.workCenterId);+ }+ }+ return workCenters+ .filter(+ (wc) =>+ !wc.alwaysOn &&+ (linkedToThisShift.has(wc.id) ||+ (wc.locationId !== null &&+ wc.locationId === shift.locationId &&+ !linkedToActiveShift.has(wc.id)))+ )+ .map((wc) => wc.id);+}diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 31383a0d5a..1304349a2b 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -23012,8 +23012,8 @@ msgstr "Der Vertrag endet am Enddatum und wird nicht erneuert. Geplante Rechnungmsgid "The contract's invoices will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."msgstr "Die Rechnungen des Vertrags werden dem Stripe-Kunden in Rechnung gestellt, der bereits mit diesem Carbon-Kunden verknüpft ist. Um die Details zu ändern, bearbeiten Sie ihn im Stripe-Dashboard."-msgid "The contractor's expected weekly availability; scheduling uses this as the upper bound when assigning this contractor to operations across the week."-msgstr "Die erwartete wöchentliche Verfügbarkeit des externen Mitarbeiters; die Planung verwendet dies als Obergrenze, wenn dieser externe Mitarbeiter über die Woche hinweg Arbeitsgängen zugewiesen wird."+msgid "The contractor's expected weekly availability, for reference. The scheduler does not book contractors on operations."+msgstr "Die erwartete wöchentliche Verfügbarkeit des externen Mitarbeiters, nur zur Information. Die Planung bucht externe Mitarbeiter nicht auf Arbeitsgänge."msgid "The corrected expiration for this lot/serial; existing on-hand stock is re-evaluated against shelf-life policy after the change."msgstr "Das korrigierte Ablaufdatum für dieses Los/diese Seriennummer; vorhandener Bestand wird nach der Änderung gegen die Haltbarkeitsrichtlinie neu bewertet."diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 418f43518c..fcb5537546 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -23012,8 +23012,8 @@ msgstr "The contract ends on the end date and does not renew. Planned invoices amsgid "The contract's invoices will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."msgstr "The contract's invoices will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."-msgid "The contractor's expected weekly availability; scheduling uses this as the upper bound when assigning this contractor to operations across the week."-msgstr "The contractor's expected weekly availability; scheduling uses this as the upper bound when assigning this contractor to operations across the week."+msgid "The contractor's expected weekly availability, for reference. The scheduler does not book contractors on operations."+msgstr "The contractor's expected weekly availability, for reference. The scheduler does not book contractors on operations."msgid "The corrected expiration for this lot/serial; existing on-hand stock is re-evaluated against shelf-life policy after the change."msgstr "The corrected expiration for this lot/serial; existing on-hand stock is re-evaluated against shelf-life policy after the change."diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex a0f6391a7b..dbe9f99a9e 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -23012,8 +23012,8 @@ msgstr "El contrato termina en la fecha de término y no se renueva. Las facturamsgid "The contract's invoices will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."msgstr "Las facturas del contrato se facturarán al Cliente de Stripe ya vinculado a este Cliente de Carbon. Para cambiar sus detalles, edítalo en el panel de Stripe."-msgid "The contractor's expected weekly availability; scheduling uses this as the upper bound when assigning this contractor to operations across the week."-msgstr "La disponibilidad semanal esperada del contratista; la programación usa esto como límite superior al asignar este contratista a operaciones durante la semana."+msgid "The contractor's expected weekly availability, for reference. The scheduler does not book contractors on operations."+msgstr "La disponibilidad semanal prevista del contratista, como referencia. El planificador no asigna contratistas a las operaciones."msgid "The corrected expiration for this lot/serial; existing on-hand stock is re-evaluated against shelf-life policy after the change."msgstr "La fecha de vencimiento corregida para este lote/número de serie; el inventario existente se reevalúa contra la política de vida útil después del cambio."diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex a4c657b252..e8c3a64a19 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -23012,8 +23012,8 @@ msgstr "Le contrat se termine à la date de fin et ne se renouvelle pas. Les facmsgid "The contract's invoices will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."msgstr "Les factures du contrat seront facturées au client Stripe déjà lié à ce client Carbon. Pour modifier ses détails, modifiez-le dans le tableau de bord Stripe."-msgid "The contractor's expected weekly availability; scheduling uses this as the upper bound when assigning this contractor to operations across the week."-msgstr "La disponibilité hebdomadaire attendue du prestataire ; la planification l'utilise comme limite supérieure lors de l'attribution de ce prestataire aux opérations de la semaine."+msgid "The contractor's expected weekly availability, for reference. The scheduler does not book contractors on operations."+msgstr "La disponibilité hebdomadaire prévue du sous-traitant, à titre indicatif. Le planificateur n'affecte pas les sous-traitants aux opérations."msgid "The corrected expiration for this lot/serial; existing on-hand stock is re-evaluated against shelf-life policy after the change."msgstr "La date d'expiration corrigée pour ce lot/numéro de série; l'inventaire existant est réévalué par rapport à la politique de durée de vie après la modification."diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 5b83b1bed1..dd192c1c25 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -23012,8 +23012,8 @@ msgstr "अनुबंध अंतिम तारीख को समापmsgid "The contract's invoices will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."msgstr "अनुबंध के चालान पहले से इस Carbon ग्राहक से जुड़े Stripe ग्राहक को बिल किए जाएंगे। इसके विवरण बदलने के लिए, इसे Stripe डैशबोर्ड में संपादित करें।"-msgid "The contractor's expected weekly availability; scheduling uses this as the upper bound when assigning this contractor to operations across the week."-msgstr "ठेकेदार की अपेक्षित साप्ताहिक उपलब्धता; शेड्यूलिंग इसे इस सप्ताह भर में इस ठेकेदार को ऑपरेशन के लिए असाइन करते समय ऊपरी सीमा के रूप में उपयोग करती है।"+msgid "The contractor's expected weekly availability, for reference. The scheduler does not book contractors on operations."+msgstr "ठेकेदार की अपेक्षित साप्ताहिक उपलब्धता, केवल संदर्भ के लिए। शेड्यूलर ठेकेदारों को ऑपरेशनों पर नहीं लगाता।"msgid "The corrected expiration for this lot/serial; existing on-hand stock is re-evaluated against shelf-life policy after the change."msgstr "इस लॉट/सीरीज़ के लिए सही की गई समाप्ति तिथि; परिवर्तन के बाद मौजूदा ऑन-हैंड स्टॉक को शेल्फ-लाइफ नीति के विरुद्ध पुनः मूल्यांकन किया जाता है।"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 8262642982..f997bc0624 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -23012,8 +23012,8 @@ msgstr "Il contratto termina alla data di termine e non si rinnova. Le fatture pmsgid "The contract's invoices will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."msgstr "Le fatture del contratto verranno addebitate al cliente Stripe già collegato a questo cliente Carbon. Per modificare i dettagli, modificalo nel cruscotto di Stripe."-msgid "The contractor's expected weekly availability; scheduling uses this as the upper bound when assigning this contractor to operations across the week."-msgstr "La disponibilità settimanale prevista del collaboratore esterno; la programmazione utilizza questo come limite superiore quando assegna questo collaboratore esterno alle operazioni durante la settimana."+msgid "The contractor's expected weekly availability, for reference. The scheduler does not book contractors on operations."+msgstr "La disponibilità settimanale prevista del collaboratore esterno, solo come riferimento. La pianificazione non assegna i collaboratori esterni alle operazioni."msgid "The corrected expiration for this lot/serial; existing on-hand stock is re-evaluated against shelf-life policy after the change."msgstr "La data di scadenza corretta per questo lotto/numero di serie; l'inventario in mano esistente viene rivalutato rispetto alla politica di shelf-life dopo la modifica."diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex b4ba2bad41..db33ae1ac9 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -23012,8 +23012,8 @@ msgstr "契約は終了日に終了し、更新されません。その後の計msgid "The contract's invoices will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."msgstr "この契約の請求書は、このCarbon得意先にリンク済みのStripeカスタマーに請求されます。詳細を変更するにはStripeダッシュボードで編集してください。"-msgid "The contractor's expected weekly availability; scheduling uses this as the upper bound when assigning this contractor to operations across the week."-msgstr "外部作業者の期待される毎週の利用可能性。スケジューリングはこれを、週間を通じてこの外部作業者を工程に割り当てる際の上限として使用します。"+msgid "The contractor's expected weekly availability, for reference. The scheduler does not book contractors on operations."+msgstr "請負業者の想定される週ごとの稼働可能時間(参考値)。スケジューラーは請負業者を作業に割り当てません。"msgid "The corrected expiration for this lot/serial; existing on-hand stock is re-evaluated against shelf-life policy after the change."msgstr "このロット/シリアル番号の修正された有効期限。変更後、既存のオンハンド在庫は棚寿命ポリシーに対して再評価されます。"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex d101745e4a..807b013210 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -23012,8 +23012,8 @@ msgstr "계약이 종료 날짜에 끝나고 갱신되지 않습니다. 그 이msgid "The contract's invoices will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."msgstr "계약의 송장은 이미 이 Carbon 고객에 연결된 Stripe 고객에게 청구됩니다. 세부 정보를 변경하려면 Stripe 대시보드에서 편집하세요."-msgid "The contractor's expected weekly availability; scheduling uses this as the upper bound when assigning this contractor to operations across the week."-msgstr "외주 인력의 예상 주간 가용성; 이 외주 인력을 주 동안의 공정에 할당할 때 스케줄링이 이를 상한선으로 사용합니다."+msgid "The contractor's expected weekly availability, for reference. The scheduler does not book contractors on operations."+msgstr "계약자의 예상 주간 가용 시간(참고용)입니다. 스케줄러는 계약자를 작업에 배정하지 않습니다."msgid "The corrected expiration for this lot/serial; existing on-hand stock is re-evaluated against shelf-life policy after the change."msgstr "이 로트/일련번호의 수정된 유효기한으로, 변경 후 기존 보유 재고가 유통기한 정책에 따라 재평가됩니다."diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex c81daebd19..8efcb52eea 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -23012,8 +23012,8 @@ msgstr "Umowa kończy się w dniu końcowym i nie jest odnawiana. Zaplanowane famsgid "The contract's invoices will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."msgstr "Faktury umowy będą fakturowane wobec klienta Stripe już powiązanego z tym klientem Carbon. Aby zmienić jego szczegóły, edytuj go w panelu Stripe."-msgid "The contractor's expected weekly availability; scheduling uses this as the upper bound when assigning this contractor to operations across the week."-msgstr "Oczekiwana dostępność pracownika zewnętrznego co tydzień; planowanie używa tego jako górnego limitu podczas przydzielania pracownika do operacji w ciągu tygodnia."+msgid "The contractor's expected weekly availability, for reference. The scheduler does not book contractors on operations."+msgstr "Przewidywana tygodniowa dostępność wykonawcy, wyłącznie informacyjnie. Harmonogram nie przydziela wykonawców do operacji."msgid "The corrected expiration for this lot/serial; existing on-hand stock is re-evaluated against shelf-life policy after the change."msgstr "Poprawiona data wygaśnięcia dla tego lotu/numeru seryjnego; istniejące zapasy w ręce są ponownie oceniane na podstawie polityki żywotności przechowywania po zmianie."diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 8f8096b036..ec4bf00961 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -23012,8 +23012,8 @@ msgstr "O contrato termina na data de término e não é renovado. As faturas plmsgid "The contract's invoices will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."msgstr "As faturas do contrato serão faturadas para o cliente do Stripe já vinculado a este cliente do Carbon. Para alterar seus detalhes, edite no painel do Stripe."-msgid "The contractor's expected weekly availability; scheduling uses this as the upper bound when assigning this contractor to operations across the week."-msgstr "A disponibilidade semanal esperada do terceirizado; o agendamento usa isso como o limite superior ao atribuir este terceirizado a operações ao longo da semana."+msgid "The contractor's expected weekly availability, for reference. The scheduler does not book contractors on operations."+msgstr "A disponibilidade semanal prevista do prestador, para referência. O planejador não aloca prestadores em operações."msgid "The corrected expiration for this lot/serial; existing on-hand stock is re-evaluated against shelf-life policy after the change."msgstr "A data de validade corrigida para este lote/número de série; o estoque existente em mãos é reavaliado em relação à política de vida útil após a alteração."diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex f1fc8ad866..80a490a7a4 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -23012,8 +23012,8 @@ msgstr "Контракт завершается в дату окончанияmsgid "The contract's invoices will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."msgstr "Счета-фактуры договора будут выставляться покупателю Stripe, уже связанному с этим покупателем Carbon. Чтобы изменить его данные, измените их в панели управления Stripe."-msgid "The contractor's expected weekly availability; scheduling uses this as the upper bound when assigning this contractor to operations across the week."-msgstr "Ожидаемая еженедельная доступность подрядчика; планирование использует это как верхний предел при назначении подрядчика операциям в течение недели."+msgid "The contractor's expected weekly availability, for reference. The scheduler does not book contractors on operations."+msgstr "Ожидаемая еженедельная доступность подрядчика, для справки. Планировщик не назначает подрядчиков на операции."msgid "The corrected expiration for this lot/serial; existing on-hand stock is re-evaluated against shelf-life policy after the change."msgstr "Исправленная дата истечения для этой партии/серийного номера; существующие запасы переоцениваются в соответствии с политикой полезной жизни после изменения."diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex ac2722b513..097690d317 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -23012,8 +23012,8 @@ msgstr "Sözleşme bitiş tarihinde sona erer ve yenilenmez. Bundan sonraki planmsgid "The contract's invoices will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."msgstr "Sözleşmenin faturaları, bu Carbon müşterisine zaten bağlı olan Stripe müşterisine faturalanacaktır. Ayrıntılarını değiştirmek için Stripe panosunda düzenleyin."-msgid "The contractor's expected weekly availability; scheduling uses this as the upper bound when assigning this contractor to operations across the week."-msgstr "Taşeronun beklenen haftalık kullanılabilirliği; planlama bu taşeronun haftasındaki operasyonlara atanırken bunu üst sınır olarak kullanır."+msgid "The contractor's expected weekly availability, for reference. The scheduler does not book contractors on operations."+msgstr "Yüklenicinin beklenen haftalık müsaitliği, bilgi amaçlıdır. Planlayıcı yüklenicileri operasyonlara atamaz."msgid "The corrected expiration for this lot/serial; existing on-hand stock is re-evaluated against shelf-life policy after the change."msgstr "Bu lot/seri numarası için düzeltilmiş son kullanma tarihi; mevcut eldeki stok, değişiklikten sonra raf ömrü politikasına göre yeniden değerlendirilir."diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 479c4e456a..0e23da725a 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -23012,8 +23012,8 @@ msgstr "合同在期末日期结束,不会续期。之后的已计划发票将msgid "The contract's invoices will be billed to the Stripe customer already linked to this Carbon customer. To change its details, edit it in the Stripe dashboard."msgstr "合同的发票将计费给已与此Carbon客户关联的Stripe客户。要更改其详细信息,请在Stripe仪表板中编辑。"-msgid "The contractor's expected weekly availability; scheduling uses this as the upper bound when assigning this contractor to operations across the week."-msgstr "外协人员的预期每周可用性;排程在整周将此外协人员分配给工序时使用此作为上限。"+msgid "The contractor's expected weekly availability, for reference. The scheduler does not book contractors on operations."+msgstr "承包商的预计每周可用时间,仅供参考。排程不会将承包商分配到工序。"msgid "The corrected expiration for this lot/serial; existing on-hand stock is re-evaluated against shelf-life policy after the change."msgstr "此批次/序列号的修正有效期;更改后,现有库存会根据保质期政策重新评估。"diff --git a/packages/planning/src/index.ts b/packages/planning/src/index.tsindex 10be1fd028..5224cf761b 100644--- a/packages/planning/src/index.ts+++ b/packages/planning/src/index.ts@@ -22,11 +22,13 @@ export {subtractIntervals} from "./scheduling/calendar-utils.ts";export {+ closeHolidays,type LadderShiftRow,resolveLocationWindows,resolveWorkCenterWindows,type WorkCenterAvailabilityInput} from "./scheduling/machine-availability.ts";+export { subtractDates } from "./scheduling/people-utils.ts";export {type QuoteLeadTimeForecast,type QuoteLeadTimeScenario,diff --git a/packages/planning/src/scheduling/apply-work-center-selections.test.ts b/packages/planning/src/scheduling/apply-work-center-selections.test.tsindex 5d3711fdac..a159d6633a 100644--- a/packages/planning/src/scheduling/apply-work-center-selections.test.ts+++ b/packages/planning/src/scheduling/apply-work-center-selections.test.ts@@ -4,6 +4,7 @@import { it } from "vitest";import { applyWorkCenterSelections } from "./apply-work-center-selections.ts";+import { placementWrites } from "./run-overlay.ts";import { assert, assertEquals } from "./test-helpers.ts";import type { ScheduledOperation, WorkCenterSelection } from "./types.ts";@@ -179,3 +180,122 @@ it("placed start is recorded as the factory's calendar day; the projected finish// The stored need-by target survives in every zone.assertEquals(ist.dueDate, "2026-07-14");});++const PLACED = {+ priority: 0,+ placedStart: "2026-07-13T13:00:00.000Z",+ placedEnd: "2026-07-13T15:00:00.000Z"+};++function appliedWorkCenter(+ op: Partial<ScheduledOperation>,+ selection: WorkCenterSelection+): string | null | undefined {+ return applyWorkCenterSelections(+ new Map([["op-1", makeOp(op)]]),+ new Map([["op-1", selection]])+ ).get("op-1")?.workCenterId;+}++it("an unstarted op is stored on the work center the plan placed it on", () => {+ assertEquals(+ appliedWorkCenter(+ { workCenterId: "wc-cnc", status: "Ready" },+ { workCenterId: "wc-tig", ...PLACED }+ ),+ "wc-tig"+ );+});++it.each([+ ["In Progress", 0],+ ["Paused", 0],+ ["Ready", 2]+])(+ "a started op (status %s, %i complete) keeps its work center",+ (status, quantityComplete) => {+ assertEquals(+ appliedWorkCenter(+ {+ workCenterId: "wc-cnc",+ status: status as ScheduledOperation["status"],+ quantityComplete+ },+ { workCenterId: "wc-tig", ...PLACED }+ ),+ "wc-cnc"+ );+ }+);++it("a placeholder keeps its stored work center; its fallback is only where it would run", () => {+ assertEquals(+ appliedWorkCenter(+ { workCenterId: "wc-clean-room", status: "Ready" },+ {+ workCenterId: "wc-potting",+ priority: 0,+ conflict: "No qualified operator available"+ }+ ),+ "wc-clean-room"+ );+});++it("an op with no work center takes the selected one, placed or not", () => {+ assertEquals(+ appliedWorkCenter(+ { workCenterId: null },+ { workCenterId: "wc-potting", priority: 0, conflict: "No slot" }+ ),+ "wc-potting"+ );+});++it("the run writes the work center the plan placed an unstarted op on", () => {+ // Stored on CNC Mill, placed on TIG Welder Cell: the write must say TIG, or+ // the op stays on a station its booking is not on.+ const original = makeOp({ workCenterId: "wc-cnc", status: "Ready" });+ const applied = applyWorkCenterSelections(+ new Map([["op-1", original]]),+ new Map([["op-1", { workCenterId: "wc-tig", ...PLACED }]])+ );++ const [write] = placementWrites({+ scheduled: applied.values(),+ originals: [original],+ needByByOperation: new Map([["op-1", "2026-07-14"]])+ });++ assertEquals(write?.placement.workCenterId, "wc-tig");+});++it("the run never writes the need-by of a pinned op, nor an unchanged one", () => {+ const pinned = makeOp({+ id: "op-pinned",+ workCenterId: "wc-cnc",+ dueDate: "2026-07-20",+ manuallyScheduled: true+ });+ const unchanged = makeOp({ id: "op-same", workCenterId: "wc-cnc" });+ const moved = makeOp({ id: "op-moved", workCenterId: "wc-cnc" });++ const writes = placementWrites({+ scheduled: [pinned, unchanged, moved],+ originals: [pinned, unchanged, moved],+ needByByOperation: new Map([+ ["op-pinned", "2026-07-10"],+ ["op-same", "2026-07-14"],+ ["op-moved", "2026-07-11"]+ ])+ });++ assertEquals(+ writes.map((w) => [w.id, w.placement.dueDate]),+ [+ ["op-pinned", undefined],+ ["op-same", undefined],+ ["op-moved", "2026-07-11"]+ ]+ );+});diff --git a/packages/planning/src/scheduling/apply-work-center-selections.ts b/packages/planning/src/scheduling/apply-work-center-selections.tsindex fcabbd41c6..dda388c089 100644--- a/packages/planning/src/scheduling/apply-work-center-selections.ts+++ b/packages/planning/src/scheduling/apply-work-center-selections.ts@@ -27,6 +27,22 @@ export function hasPreassignedWorkCenter(return workCenterId != null && workCenterId !== "";}+/**+ * True once an operation has begun on the floor. A started op stays on its+ * machine (setups, fixtures and operators live there); an unstarted op may be+ * balanced onto another work center that runs its process.+ */+export function isOperationStarted(op: {+ status?: string | null;+ quantityComplete?: number | null;+}): boolean {+ return (+ op.status === "In Progress" ||+ op.status === "Paused" ||+ (op.quantityComplete ?? 0) > 0+ );+}+export function applyWorkCenterSelections(operations: Map<string, ScheduledOperation>,selections: Map<string, WorkCenterSelection>,@@ -42,9 +58,14 @@ export function applyWorkCenterSelections(}const updated: ScheduledOperation = { ...op };- // Never clobber a pre-assigned work center (user or method default) —- // auto-selection may only fill empty ones.- if (selection.workCenterId && !hasPreassignedWorkCenter(op.workCenterId)) {+ // Store the station the plan books an unstarted op on. A started op stays+ // on its machine; a placeholder's fallback is only where it WOULD run.+ const placed = Boolean(selection.placedStart && selection.placedEnd);+ if (+ selection.workCenterId &&+ (!hasPreassignedWorkCenter(op.workCenterId) ||+ (placed && !isOperationStarted(op)))+ ) {updated.workCenterId = selection.workCenterId;}diff --git a/packages/planning/src/scheduling/batch-scheduler.test.ts b/packages/planning/src/scheduling/batch-scheduler.test.tsindex 57cee9d8e5..085def2216 100644--- a/packages/planning/src/scheduling/batch-scheduler.test.ts+++ b/packages/planning/src/scheduling/batch-scheduler.test.ts@@ -5,8 +5,14 @@import { parseAbsolute } from "@internationalized/date";import { it } from "vitest";import type { BatchMemberInput, BatchToPlace } from "./batch-scheduler.ts";-import { planBatchPlacements } from "./batch-scheduler.ts";-import type { MasterDataProvider } from "./master-data-provider.ts";+import {+ batchBlockingReservations,+ planBatchPlacements+} from "./batch-scheduler.ts";+import type {+ LiveReservation,+ MasterDataProvider+} from "./master-data-provider.ts";import { assert, assertEquals } from "./test-helpers.ts";import type { JobOperationDependency, ScheduledOperation } from "./types.ts";import {@@ -159,6 +165,60 @@ it("two batches on one work center place sequentially in job order", () => {);});+function liveReservation(+ overrides: Partial<LiveReservation> & { jobId: string }+): LiveReservation {+ return {+ resourceKind: "WorkCenter",+ resourceId: "wc1",+ startAt: NOW,+ endAt: NOW + 8 * 60 * MIN,+ readableJobId: overrides.jobId.toUpperCase(),+ jobOperationBatchId: null,+ ...overrides+ };+}++it("a batch places around other jobs and other batches, never around the bookings this run replaces", () => {+ const blocking = batchBlockingReservations({+ reservations: [+ liveReservation({ jobId: "job-a" }), // re-planned this run: replaced+ liveReservation({ jobId: "job-x", startAt: NOW + MIN }), // a job this run does not re-plan: blocks+ liveReservation({ jobId: "job-a", jobOperationBatchId: "b1" }), // this batch's old row+ liveReservation({ jobId: "job-q", jobOperationBatchId: "b-other" }), // another batch: blocks+ liveReservation({+ jobId: "job-x",+ resourceKind: "Employee",+ resourceId: "emp"+ })+ ],+ batchIds: ["b1"],+ rerunJobIds: ["job-a", "job-b", "job-c"]+ });++ assertEquals(+ [...blocking.entries()].map(([wc, list]) => [+ wc,+ list.map((r) => r.readableJobId)+ ]),+ [["wc1", ["JOB-X", "JOB-Q"]]]+ );+});++it("a re-planned job's previous booking does not push the batch later", () => {+ // The previous run booked job-a's own op on wc1 for 8h from NOW. This run+ // re-plans job-a, so the batch must still start at NOW, as it did before.+ const { reservations } = plan([makeBatch({ id: "b1" })], {+ reservationsByWorkCenter: batchBlockingReservations({+ reservations: [liveReservation({ jobId: "job-a" })],+ batchIds: ["b1"],+ rerunJobIds: ["job-a", "job-b", "job-c"]+ })+ });++ assertEquals(reservations[0]?.startAt, NOW);+});+it("no work center AND no candidates → skipped (members place individually)", () => {const { placements, reservations } = plan([makeBatch({ id: "b1", workCenterId: null, candidateWorkCenterIds: [] })diff --git a/packages/planning/src/scheduling/batch-scheduler.ts b/packages/planning/src/scheduling/batch-scheduler.tsindex 5f02d94a63..7eb54b9e31 100644--- a/packages/planning/src/scheduling/batch-scheduler.ts+++ b/packages/planning/src/scheduling/batch-scheduler.ts@@ -11,7 +11,10 @@ import { nextWorkingInstant } from "./calendar-utils.ts";import { composeBatchNoEstimatesConflict } from "./conflict-messages.ts";import { msToInstantIso, toInstantMs } from "./date-utils.ts";import { calculateDurationBreakdown } from "./duration-calculator.ts";-import type { KyselyMasterDataProvider } from "./master-data-provider.ts";+import type {+ KyselyMasterDataProvider,+ LiveReservation+} from "./master-data-provider.ts";import { allocateOperation, isConflict } from "./slot-allocator.ts";/**@@ -323,6 +326,38 @@ export function planBatchPlacements(args: {return { placements, reservations: reservationRows, selectedWorkCenters };}+/**+ * The work-center bookings a released batch places around. The pre-pass runs+ * before the per-job passes, so the stored bookings of jobs this run re-plans+ * are about to be replaced and must not block the batch. This location's own+ * batch rows are rewritten here; other batches' rows always block.+ */+export function batchBlockingReservations(args: {+ reservations: LiveReservation[];+ batchIds: string[];+ rerunJobIds: string[];+}): Map<string, WorkCenterReservationInterval[]> {+ const batchIds = new Set(args.batchIds);+ const rerunJobIds = new Set(args.rerunJobIds);+ const byWorkCenter = new Map<string, WorkCenterReservationInterval[]>();+ for (const r of args.reservations) {+ if (r.resourceKind !== "WorkCenter") continue;+ if (r.jobOperationBatchId) {+ if (batchIds.has(r.jobOperationBatchId)) continue;+ } else if (rerunJobIds.has(r.jobId)) {+ continue;+ }+ const list = byWorkCenter.get(r.resourceId) ?? [];+ list.push({+ startAt: r.startAt,+ endAt: r.endAt,+ readableJobId: r.readableJobId+ });+ byWorkCenter.set(r.resourceId, list);+ }+ return byWorkCenter;+}+/*** I/O wrapper: load Released batches + members + predecessors + availability,* run the pure core, and (when `persist`) rewrite the batch-tagged@@ -573,25 +608,11 @@ export async function placeReleasedBatches(args: {.executeTakeFirst()]);- // Existing reservations per work center, MINUS this location's own batch- // rows (they are being rewritten below and must not block themselves).- const reservationsByWorkCenter = new Map<- string,- WorkCenterReservationInterval[]- >();- for (const r of liveReservations) {- if (r.resourceKind !== "WorkCenter") continue;- if (r.jobOperationBatchId && batchIds.includes(r.jobOperationBatchId)) {- continue;- }- const list = reservationsByWorkCenter.get(r.resourceId) ?? [];- list.push({- startAt: r.startAt,- endAt: r.endAt,- readableJobId: r.readableJobId- });- reservationsByWorkCenter.set(r.resourceId, list);- }+ const reservationsByWorkCenter = batchBlockingReservations({+ reservations: liveReservations,+ batchIds,+ rerunJobIds: orderedJobIds+ });const { placements, reservations, selectedWorkCenters } = planBatchPlacements({diff --git a/packages/planning/src/scheduling/finite-context.ts b/packages/planning/src/scheduling/finite-context.tsindex b23107b1f6..ceee1e5ea2 100644--- a/packages/planning/src/scheduling/finite-context.ts+++ b/packages/planning/src/scheduling/finite-context.ts@@ -16,7 +16,8 @@ import {buildPeopleBudgets,buildPeopleByWorkCenter,extendWindowsByOvertime,- subtractAbsences+ subtractAbsences,+ withHolidays} from "./people-utils.ts";import type { ResourceCapacityData } from "./slot-allocator.ts";import type { JobOperationDependency, ScheduledOperation } from "./types.ts";@@ -146,13 +147,15 @@ export async function buildFiniteContext(args: {processRequirements,peopleRows,absenceRows,- operationsWithEvents+ operationsWithEvents,+ holidayDates] = await Promise.all([provider.getLiveReservations(now, excludeJobIds),provider.getProcessRequirements(processIds),provider.getPeopleAssignments(rangeStart, rangeEnd, timeZone),provider.getPeopleAbsences(rangeStart, rangeEnd, timeZone),- provider.getOperationsWithEvents(operationIds)+ provider.getOperationsWithEvents(operationIds),+ provider.getHolidayDates(rangeStart, rangeEnd)]);const abilityIds = Array.from(@@ -246,7 +249,11 @@ export async function buildFiniteContext(args: {// Absences subtract the person's availability on those dates everywhere —// people-preferred and qualified-fallback paths alike- const absentByEmployee = buildAbsencesByEmployee(absenceRows);+ const absentByEmployee = withHolidays(+ buildAbsencesByEmployee(absenceRows),+ employeeIds,+ holidayDates+ );for (const [employeeId, absentDates] of absentByEmployee) {const windows = windowsByEmployee.get(employeeId);if (windows) {diff --git a/packages/planning/src/scheduling/machine-availability.test.ts b/packages/planning/src/scheduling/machine-availability.test.tsindex 9136ba8389..8eed53d6f7 100644--- a/packages/planning/src/scheduling/machine-availability.test.ts+++ b/packages/planning/src/scheduling/machine-availability.test.ts@@ -11,6 +11,7 @@ import {import { it } from "vitest";import { intersectWindows, subtractIntervals } from "./calendar-utils.ts";import {+ closeHolidays,type LadderShiftRow,resolveLocationWindows,resolveWorkCenterWindows,@@ -262,3 +263,43 @@ it("intersectWindows: multi-window sweep intersects each overlap once", () => {assertEquals(out[1]?.start, utc("2026-01-06T08:00:00.000Z"));assertEquals(out[1]?.end, utc("2026-01-06T12:00:00.000Z"));});++it("a holiday closes a shift-based work center for the whole local day; a lights-out one keeps running", () => {+ // Mon 26 Oct 2026 is a holiday. America/Chicago is UTC-5 that day.+ const dayShift = {+ start: utc("2026-10-26T11:00:00Z"),+ end: utc("2026-10-26T19:30:00Z")+ };+ const tuesday = {+ start: utc("2026-10-27T11:00:00Z"),+ end: utc("2026-10-27T19:30:00Z")+ };+ const around = {+ start: utc("2026-10-25T05:00:00Z"),+ end: utc("2026-10-28T05:00:00Z")+ };+ const result = closeHolidays({+ windowsByWorkCenter: new Map([+ ["wc-shift", [dayShift, tuesday]],+ ["wc-lights-out", [around]]+ ]),+ workCenters: [+ {+ id: "wc-shift",+ alwaysOn: false,+ locationId: "loc",+ timezone: "America/Chicago"+ },+ {+ id: "wc-lights-out",+ alwaysOn: true,+ locationId: "loc",+ timezone: "America/Chicago"+ }+ ],+ holidayDates: new Set(["2026-10-26"])+ });++ assertEquals(result.get("wc-shift"), [tuesday]);+ assertEquals(result.get("wc-lights-out"), [around]);+});diff --git a/packages/planning/src/scheduling/machine-availability.ts b/packages/planning/src/scheduling/machine-availability.tsindex 2c108bebe8..b67032ec3b 100644--- a/packages/planning/src/scheduling/machine-availability.ts+++ b/packages/planning/src/scheduling/machine-availability.ts@@ -27,6 +27,7 @@ import {STOCK_WEEK_SHIFTS,unionWindows} from "./calendar-utils.ts";+import { subtractDates } from "./people-utils.ts";/** One weekday window of a shift, with the timezone it is expressed in. */export type LadderShiftRow = {@@ -172,3 +173,23 @@ export function resolveLocationWindows(args: {timezone || "UTC");}++/**+ * Close every work center on the company's holidays (whole local days in the+ * work center's own timezone). A lights-out (`alwaysOn`) station keeps running.+ */+export function closeHolidays(args: {+ windowsByWorkCenter: Map<string, CalendarWindow[]>;+ workCenters: WorkCenterAvailabilityInput[];+ holidayDates: Set<string>;+}): Map<string, CalendarWindow[]> {+ const { windowsByWorkCenter, workCenters, holidayDates } = args;+ if (holidayDates.size === 0) return windowsByWorkCenter;+ const result = new Map(windowsByWorkCenter);+ for (const wc of workCenters) {+ const windows = result.get(wc.id);+ if (!windows || wc.alwaysOn) continue;+ result.set(wc.id, subtractDates(windows, holidayDates, wc.timezone));+ }+ return result;+}diff --git a/packages/planning/src/scheduling/master-data-provider.ts b/packages/planning/src/scheduling/master-data-provider.tsindex 82366d2222..6dda4e5757 100644--- a/packages/planning/src/scheduling/master-data-provider.ts+++ b/packages/planning/src/scheduling/master-data-provider.ts@@ -26,6 +26,7 @@ import {toIsoDate} from "./date-utils.ts";import {+ closeHolidays,type LadderShiftRow,resolveLocationWindows,resolveWorkCenterWindows,@@ -145,7 +146,11 @@ export type EmployeeShiftRow = {// Row types live in people-utils.ts (pure module) so its tests don't pull the// DB dependency graph-import type { PeopleAbsenceRow, PeopleAssignmentRow } from "./people-utils.ts";+import {+ type PeopleAbsenceRow,+ type PeopleAssignmentRow,+ subtractDates+} from "./people-utils.ts";export type { PeopleAbsenceRow, PeopleAssignmentRow };@@ -232,6 +237,12 @@ export interface MasterDataProvider {rangeEnd: number,timeZone: string): Promise<PeopleAbsenceRow[]>;+ /**+ * The company's holiday dates ("YYYY-MM-DD") around [rangeStart, rangeEnd].+ * A holiday closes every shift-based work center and is a day off for+ * every person.+ */+ getHolidayDates(rangeStart: number, rangeEnd: number): Promise<Set<string>>;}function toJob<@@ -1238,12 +1249,16 @@ export class KyselyMasterDataProvider implements MasterDataProvider {this.expandShiftDays(r).map((d) => ({ ...d, locationId: r.locationId })));- const windowsMap = resolveWorkCenterWindows({+ const windowsMap = closeHolidays({+ windowsByWorkCenter: resolveWorkCenterWindows({+ workCenters,+ workCenterShiftRows,+ locationShiftRows,+ rangeStart,+ rangeEnd+ }),workCenters,- workCenterShiftRows,- locationShiftRows,- rangeStart,- rangeEnd+ holidayDates: await this.getHolidayDates(rangeStart, rangeEnd)});// Machine downtime: subtract open maintenance dispatches flagged@@ -1386,12 +1401,17 @@ export class KyselyMasterDataProvider implements MasterDataProvider {timezone = loc?.timezone ?? "UTC";}- return resolveLocationWindows({- timezone: timezone ?? "UTC",- locationShiftRows,- rangeStart,- rangeEnd- });+ // A holiday closes the plant for people with no shift of their own too.+ return subtractDates(+ resolveLocationWindows({+ timezone: timezone ?? "UTC",+ locationShiftRows,+ rangeStart,+ rangeEnd+ }),+ await this.getHolidayDates(rangeStart, rangeEnd),+ timezone ?? "UTC"+ );}async getPeopleAssignments(@@ -1482,4 +1502,34 @@ export class KyselyMasterDataProvider implements MasterDataProvider {: [];});}++ async getHolidayDates(+ rangeStart: number,+ rangeEnd: number+ ): Promise<Set<string>> {+ return this.cached(`holidays:${rangeStart}:${rangeEnd}`, () =>+ this.loadHolidayDates(rangeStart, rangeEnd)+ );+ }++ private async loadHolidayDates(+ rangeStart: number,+ rangeEnd: number+ ): Promise<Set<string>> {+ // Holidays are company-wide calendar days; pad one day each side so every+ // timezone's local day inside the range is covered.+ const rows = await this.db+ .selectFrom("holiday")+ .select("date")+ .where("companyId", "=", this.companyId)+ .where("date", ">=", peopleDateLowerBound(rangeStart, "UTC"))+ .where("date", "<=", peopleDateUpperBound(rangeEnd, "UTC"))+ .execute();+ return new Set(+ rows.flatMap((r) => {+ const date = toIsoDate(r.date);+ return date ? [date] : [];+ })+ );+ }}diff --git a/packages/planning/src/scheduling/operator-eligibility.test.ts b/packages/planning/src/scheduling/operator-eligibility.test.tsindex 16bca76a93..9c0475dfb5 100644--- a/packages/planning/src/scheduling/operator-eligibility.test.ts+++ b/packages/planning/src/scheduling/operator-eligibility.test.ts@@ -6,6 +6,7 @@ import { parseAbsolute } from "@internationalized/date";import { it } from "vitest";import { toIsoDate } from "./date-utils.ts";import {+ clipToQualification,isEligibleOperator,type QualifiedEmployee} from "./operator-eligibility.ts";@@ -68,3 +69,25 @@ it("expiry boundary respects the factory time zone", () => {assert(isEligibleOperator(employee, start, "UTC"));assert(!isEligibleOperator(employee, start, "Asia/Kolkata"));});++// America/Chicago is UTC-5 in late October 2026.+it("a qualification ends at the start of its expiry day in the factory zone", () => {+ const windows = [+ // Mon 26 Oct 06:00-14:30 local: before expiry, kept whole+ { start: utc("2026-10-26T11:00:00Z"), end: utc("2026-10-26T19:30:00Z") },+ // a night shift Mon 22:00 -> Tue 06:00 local: cut at Tue 00:00 local+ { start: utc("2026-10-27T03:00:00Z"), end: utc("2026-10-27T11:00:00Z") },+ // Thu 29 Oct 06:00-14:30 local: after expiry, dropped+ { start: utc("2026-10-29T11:00:00Z"), end: utc("2026-10-29T19:30:00Z") }+ ];++ assertEquals(clipToQualification(windows, "2026-10-27", "America/Chicago"), [+ { start: utc("2026-10-26T11:00:00Z"), end: utc("2026-10-26T19:30:00Z") },+ { start: utc("2026-10-27T03:00:00Z"), end: utc("2026-10-27T05:00:00Z") }+ ]);+});++it("a qualification with no expiry keeps every window", () => {+ const windows = [{ start: opStart, end: opStart + 3_600_000 }];+ assertEquals(clipToQualification(windows, null, "America/Chicago"), windows);+});diff --git a/packages/planning/src/scheduling/operator-eligibility.ts b/packages/planning/src/scheduling/operator-eligibility.tsindex 4f63147859..e85b494390 100644--- a/packages/planning/src/scheduling/operator-eligibility.ts+++ b/packages/planning/src/scheduling/operator-eligibility.ts@@ -2,6 +2,8 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { parseDate } from "@internationalized/date";+import type { CalendarWindow } from "./calendar-utils.ts";import { businessDayFromMs } from "./date-utils.ts";export type QualifiedEmployee = {@@ -27,3 +29,24 @@ export function isEligibleOperator(const startDateStr = businessDayFromMs(earliestStart, timeZone);return employee.expiresAt === null || employee.expiresAt > startDateStr;}++/**+ * Cut a qualified person's availability at the start of the `expiresAt` day+ * (factory zone), the boundary `isEligibleOperator` and MES use. Eligibility at+ * the op's earliest start is not enough: the op may be placed days later.+ */+export function clipToQualification(+ windows: CalendarWindow[],+ expiresAt: string | null,+ timeZone = "UTC"+): CalendarWindow[] {+ if (expiresAt === null) return windows;+ const qualifiedUntil = parseDate(expiresAt.slice(0, 10))+ .toDate(timeZone)+ .getTime();+ return windows.flatMap((w) =>+ w.start >= qualifiedUntil+ ? []+ : [{ ...w, end: Math.min(w.end, qualifiedUntil) }]+ );+}diff --git a/packages/planning/src/scheduling/people-utils.test.ts b/packages/planning/src/scheduling/people-utils.test.tsindex 53a0a311b1..833c105a27 100644--- a/packages/planning/src/scheduling/people-utils.test.ts+++ b/packages/planning/src/scheduling/people-utils.test.ts@@ -16,7 +16,8 @@ import {dateKeyInTimeZone,extendWindowsByOvertime,subtractAbsences,- subtractDates+ subtractDates,+ withHolidays} from "./people-utils.ts";import { assertEquals, assertStrictEquals } from "./test-helpers.ts";@@ -398,3 +399,19 @@ it("buildAssignmentsByEmployee marks who is on the board (spoken for)", () => {assertEquals(assignments.has("brad"), true); // manned somewhere => not a floaterassertEquals(assignments.has("carol"), false); // never on the board => floater});++it("a company holiday is a day off for every person, on top of their own absences", () => {+ const result = withHolidays(+ new Map([["ann", new Set(["2026-10-30"])]]),+ ["ann", "bob"],+ new Set(["2026-10-26"])+ );++ assertEquals(+ [...result.entries()].map(([id, dates]) => [id, [...dates].sort()]),+ [+ ["ann", ["2026-10-26", "2026-10-30"]],+ ["bob", ["2026-10-26"]]+ ]+ );+});diff --git a/packages/planning/src/scheduling/people-utils.ts b/packages/planning/src/scheduling/people-utils.tsindex 5aa1e82d2c..1b36182709 100644--- a/packages/planning/src/scheduling/people-utils.ts+++ b/packages/planning/src/scheduling/people-utils.ts@@ -191,6 +191,25 @@ export function subtractDates(return mergeSegments(kept);}+/** A company holiday is a day off for every person, on top of their own absences. */+export function withHolidays(+ absentByEmployee: Map<string, Set<string>>,+ employeeIds: string[],+ holidayDates: Set<string>+): Map<string, Set<string>> {+ if (holidayDates.size === 0) return absentByEmployee;+ const result = new Map<string, Set<string>>();+ for (const [employeeId, dates] of absentByEmployee) {+ result.set(employeeId, new Set(dates));+ }+ for (const employeeId of employeeIds) {+ const dates = result.get(employeeId) ?? new Set<string>();+ for (const date of holidayDates) dates.add(date);+ result.set(employeeId, dates);+ }+ return result;+}+/*** Remove the parts of an employee's availability windows that fall on absent* dates. Empty `absentDates` returns the input untouched (empty-board /diff --git a/packages/planning/src/scheduling/run-overlay.ts b/packages/planning/src/scheduling/run-overlay.tsindex 515ddac4c6..bf833c3c63 100644--- a/packages/planning/src/scheduling/run-overlay.ts+++ b/packages/planning/src/scheduling/run-overlay.ts@@ -2,13 +2,16 @@// 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 { toIsoDate } from "./date-utils.ts";import type {CrossJobOperation,LiveReservation} from "./master-data-provider.ts";import {+ type BaseOperation,capacityHoldingJobStatuses,- type PlannedReservation+ type PlannedReservation,+ type ScheduledOperation} from "./types.ts";/**@@ -46,6 +49,45 @@ export type JobWrites = {projectedCompletionAt: string | null;};+/**+ * The `jobOperation` columns one job's run writes, per operation.+ *+ * - `workCenterId` is the one `applyWorkCenterSelections` settled on.+ * - `dueDate` (the backward need-by target) is diff-written: only when it+ * changed, so a quiet regen writes none, and never for a pinned op+ * (`manuallyScheduled`: a human owns that target).+ */+export function placementWrites(args: {+ scheduled: Iterable<ScheduledOperation>;+ /** The stored operations, as the run loaded them. */+ originals: Pick<+ BaseOperation,+ "id" | "workCenterId" | "dueDate" | "manuallyScheduled"+ >[];+ needByByOperation: Map<string, string | null>;+}): JobWrites["placements"] {+ const originalById = new Map(args.originals.map((op) => [op.id, op]));+ const placements: JobWrites["placements"] = [];+ for (const op of args.scheduled) {+ const original = originalById.get(op.id);+ const needBy = args.needByByOperation.get(op.id) ?? null;+ const writeDueDate =+ !(original?.manuallyScheduled ?? false) &&+ needBy !== toIsoDate(original?.dueDate ?? null);+ const placement: PlacementWrite = {+ startDate: op.startDate,+ projectedCompletionAt: op.projectedCompletionAt ?? null,+ ...(writeDueDate ? { dueDate: needBy } : {}),+ ...(op.priority != null ? { priority: op.priority } : {}),+ workCenterId: op.workCenterId ?? original?.workCenterId ?? null,+ hasConflict: op.hasConflict,+ conflictReason: op.conflictReason+ };+ placements.push({ id: op.id, placement });+ }+ return placements;+}+export function dependencyEdgesEqual(stored: DependencyEdge[],computed: DependencyEdge[]diff --git a/packages/planning/src/scheduling/scheduling-engine.ts b/packages/planning/src/scheduling/scheduling-engine.tsindex cd620a01ce..e709b15666 100644--- a/packages/planning/src/scheduling/scheduling-engine.ts+++ b/packages/planning/src/scheduling/scheduling-engine.ts@@ -21,8 +21,7 @@ import {businessDay,msToInstantIso,toInstantIso,- toInstantMs,- toIsoDate+ toInstantMs} from "./date-utils.ts";import {buildOperationDependencies,@@ -49,7 +48,7 @@ import {import {dependencyEdgesEqual,type JobWrites,- type PlacementWrite+ placementWrites} from "./run-overlay.ts";import type {AssemblyNode,@@ -819,37 +818,11 @@ export class SchedulingEngine {this.newlyLate = false;}- const placements: JobWrites["placements"] = [];- for (const op of this.scheduledOperations.values()) {- const originalOp = this.operations.find((o) => o.id === op.id);- const isManuallyScheduled = originalOp?.manuallyScheduled ?? false;- // Never clobber a work center the user (or method) already set.- // Auto-selection may only fill null/empty work centers.- const originalWorkCenterId = originalOp?.workCenterId;- const workCenterId =- originalWorkCenterId != null && originalWorkCenterId !== ""- ? originalWorkCenterId- : op.workCenterId;-- // dueDate is the backward need-by target and is DIFF-written: only- // when the computed value differs from the stored one (a quiet regen- // touches zero dueDate values), and never for a pinned op —- // manuallyScheduled means a human owns that target.- const needBy = this.needByByOperation.get(op.id) ?? null;- const storedDueDate = toIsoDate(originalOp?.dueDate ?? null);- const writeDueDate = !isManuallyScheduled && needBy !== storedDueDate;-- const placement: PlacementWrite = {- startDate: op.startDate,- projectedCompletionAt: op.projectedCompletionAt ?? null,- ...(writeDueDate ? { dueDate: needBy } : {}),- ...(op.priority != null ? { priority: op.priority } : {}),- workCenterId,- hasConflict: op.hasConflict,- conflictReason: op.conflictReason- };- placements.push({ id: op.id, placement });- }+ const placements = placementWrites({+ scheduled: this.scheduledOperations.values(),+ originals: this.operations,+ needByByOperation: this.needByByOperation+ });this.writes = {jobId: this.jobId,diff --git a/packages/planning/src/scheduling/work-center-selector.test.ts b/packages/planning/src/scheduling/work-center-selector.test.tsindex ed826d8c22..7c3225c1bb 100644--- a/packages/planning/src/scheduling/work-center-selector.test.ts+++ b/packages/planning/src/scheduling/work-center-selector.test.ts@@ -45,7 +45,7 @@ it("hasPreassignedWorkCenter is true only for non-empty ids", () => {assertEquals(hasPreassignedWorkCenter(""), false);});-it("applyWorkCenterSelections does not overwrite pre-assigned work centers", () => {+it("applyWorkCenterSelections keeps a pre-assigned work center when the op was not placed", () => {const ops = new Map<string, ScheduledOperation>([["op-pre", makeOp({ id: "op-pre", workCenterId: "user-wc" })],["op-new", makeOp({ id: "op-new", workCenterId: null })]@@ -612,6 +612,46 @@ async function placeGatedOpOnWc1(ctx: FiniteSchedulingContext) {return { selection: selections.get("op-1"), selector };}+it("a qualification that lapses before the machine is free leaves the gated op unschedulable", async () => {+ // brad is qualified at the op's earliest start (Jan 5), but his+ // qualification ends on Jan 6 and wc1 is closed until Jan 7. Booking him on+ // Jan 7 schedules work he may no longer do (MES refuses the start).+ const now = utc("2026-01-05T00:00:00.000Z");+ const bradWindows = [{ start: now, end: utc("2026-01-10T00:00:00.000Z") }];+ const ctx = makeContext({+ capacityByWorkCenter: new Map([+ [+ "wc1",+ {+ workCenter: { id: "wc1" },+ windows: [+ {+ start: utc("2026-01-07T00:00:00.000Z"),+ end: utc("2026-01-08T00:00:00.000Z")+ }+ ],+ reservations: []+ }+ ]+ ]),+ requirementByProcess: new Map([+ ["proc-1", { abilityId: "ab1", abilityName: "Weld" }]+ ]),+ employeesByAbility: new Map([+ [+ "ab1",+ [{ employeeId: "brad", expiresAt: "2026-01-06", windows: bradWindows }]+ ]+ ]),+ windowsByEmployee: new Map([["brad", bradWindows]])+ });++ const { selection } = await placeGatedOpOnWc1(ctx);++ assertEquals(selection?.placedStart, undefined);+ assert(selection?.conflict, "the unplaced op carries a conflict");+});+it("a person on the board is not pulled to another station by the fallback", async () => {// brad is manned at wc2 (Timesaver). He is the only welder, so wc1 (DMU 350)// would previously grab him via the any-qualified fallback — the reporteddiff --git a/packages/planning/src/scheduling/work-center-selector.ts b/packages/planning/src/scheduling/work-center-selector.tsindex a1990d55b4..52add4e738 100644--- a/packages/planning/src/scheduling/work-center-selector.ts+++ b/packages/planning/src/scheduling/work-center-selector.ts@@ -2,6 +2,7 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { isOperationStarted } from "./apply-work-center-selections.ts";import type { BatchPlacement } from "./batch-scheduler.ts";import {type CalendarWindow,@@ -26,6 +27,7 @@ import {} from "./duration-calculator.ts";import type { MasterDataProvider } from "./master-data-provider.ts";import {+ clipToQualification,isEligibleOperator,type QualifiedEmployee} from "./operator-eligibility.ts";@@ -513,10 +515,7 @@ export class WorkCenterSelector {// process has no mapped centers, fall back to the op's assigned center so// a misconfigured pool (or one deactivated since assignment) never strands// the op.- const started =- op.status === "In Progress" ||- op.status === "Paused" ||- (op.quantityComplete ?? 0) > 0;+ const started = isOperationStarted(op);const assignedWorkCenter =op.workCenterId && ctx.capacityByWorkCenter.has(op.workCenterId)? op.workCenterId@@ -955,7 +954,11 @@ export class WorkCenterSelector {const employees = ctx.employeesByAbility.get(requirement.abilityId) ?? [];return employees.filter((e) => isEligibleOperator(e, earliestStart, ctx.timeZone))- .map((e) => ({ employeeId: e.employeeId, windows: e.windows }));+ .map((e) => ({+ employeeId: e.employeeId,+ windows: clipToQualification(e.windows, e.expiresAt, ctx.timeZone)+ }))+ .filter((m) => m.windows.length > 0);}}