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): address review on capacity planning fixes
naveenkashb2cd637a57fe
diff --git a/.claude/rules/scheduling-data-structures.md b/.claude/rules/scheduling-data-structures.mdindex c6f958d54c..c9c13b720e 100644--- a/.claude/rules/scheduling-data-structures.md+++ b/.claude/rules/scheduling-data-structures.md@@ -94,7 +94,8 @@ Spec/plan: `.ai/specs/2026-09-22-quote-lead-time-prediction.md`.only; ops overdue up to 28 days land in a Past-due column); Scheduled =`capacityReservation.workHours` split across the days of the booking bythe work center's WORKING time in each day (`getWorkCenterWorkingWindows`,- the same ladder and holidays the engine uses), so a booking from Monday+ the same ladder and holidays the engine uses; a station's linked shifts at+ another location are loaded too, `getShiftsWithTimesByIds`), so a booking from Mondaynoon to Tuesday 11:30 puts its hours in shift time and none on the nightor a weekend; a booking with no working time falls back to the clock-timeshare; Available = people headcount × real shift hours resolved through@@ -148,7 +149,9 @@ never abandons the location run.other batches' rows. It drops this location's own batch rows, and everynon-batch row of a job the run re-plans (`orderedJobIds`): the run replacesthose bookings, so they must not push the batch later. Before this, the- batch drifted later on every regen.+ batch drifted later on every regen. A job that throws during the run is left+ out of the write, so `persistLocationWrites` clears its stored bookings too+ (`failedJobIds`): otherwise the batch could sit on top of one.- **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@@ -212,8 +215,10 @@ Two Inngest functions listen on that eventstamps 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 thestations 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.+ count), or on a process those stations run (`processesOfWorkCenters`: an unstarted op+ can move onto them). An unknown shift id stamps company-wide. `createShift`,+ `updateShift` and `deleteShift` send the id; an update that moves the shift to+ another location sends kind `location` instead, so the stations it left re-plan too. 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(),diff --git a/apps/erp/app/modules/people/AGENTS.md b/apps/erp/app/modules/people/AGENTS.mdindex 07de7fa2c5..2543d8a7ef 100644--- a/apps/erp/app/modules/people/AGENTS.md+++ b/apps/erp/app/modules/people/AGENTS.md@@ -70,7 +70,7 @@ 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), `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.+- `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; an update that moves the shift to another location notifies kind `location` (company-wide), since the stations it left lose its hours too. 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`.diff --git a/apps/erp/app/modules/people/people.server.ts b/apps/erp/app/modules/people/people.server.tsindex 067427fa17..562a8500ea 100644--- a/apps/erp/app/modules/people/people.server.ts+++ b/apps/erp/app/modules/people/people.server.ts@@ -78,6 +78,15 @@ export const updateShift = defineServiceFn({// The route gated on create; the write runs under the update policy.permission: { create: "people", update: "people" },async run(ctx, shift) {+ const previous = await ctx.asCaller.supabase+ .from("shift")+ .select("locationId")+ .eq("id", shift.id)+ .eq("companyId", ctx.company.id)+ .maybeSingle();+ if (previous.error) {+ return ctx.error("internal", "Failed to update shift", previous.error);+ }const updated = await service.upsertShift(ctx.asCaller.supabase, {...shift,companyId: ctx.company.id,@@ -87,11 +96,15 @@ export const updateShift = defineServiceFn({return ctx.error("internal", "Failed to update shift", updated.error);}if (!updated.data) return ctx.error("notFound", "Shift not found");+ // A shift moved to another location also changes the hours of the+ // stations it leaves behind, which the shift-scoped notice cannot see.+ const moved =+ previous.data !== null && previous.data.locationId !== shift.locationId;await notifyScheduleInputsChanged(ctx.company.id,- "shift",- "Shift hours changed",- shift.id+ moved ? "location" : "shift",+ moved ? "Shift moved to another location" : "Shift hours changed",+ moved ? undefined : shift.id);return { id: shift.id };}diff --git a/apps/erp/app/modules/people/people.service.ts b/apps/erp/app/modules/people/people.service.tsindex f29e9c5d7c..b8805c3721 100644--- a/apps/erp/app/modules/people/people.service.ts+++ b/apps/erp/app/modules/people/people.service.ts@@ -485,6 +485,25 @@ export async function getShiftsWithTimes(.order("name");}+/**+ * Active shifts by id, with their times. A work center can be linked to a+ * shift of another location, which `getShiftsWithTimes` does not return.+ */+export async function getShiftsWithTimesByIds(+ client: SupabaseClient<Database>,+ companyId: string,+ shiftIds: string[]+) {+ return client+ .from("shift")+ .select(+ "id, name, startTime, endTime, monday, tuesday, wednesday, thursday, friday, saturday, sunday"+ )+ .eq("companyId", companyId)+ .in("id", shiftIds)+ .eq("active", true);+}+export async function insertAttribute(client: SupabaseClient<Database>,attribute: {diff --git a/apps/erp/app/modules/production/capacity-buckets.test.ts b/apps/erp/app/modules/production/capacity-buckets.test.tsindex f58f46fe22..63131b4664 100644--- a/apps/erp/app/modules/production/capacity-buckets.test.ts+++ b/apps/erp/app/modules/production/capacity-buckets.test.ts@@ -117,3 +117,44 @@ describe("available hours", () => {expect(hours.get("tvac")?.get("2026-10-27")).toBe(24);});});++describe("a station linked to a shift of another location", () => {+ const windows = (args: {+ shifts: (typeof dayShift)[];+ linkedShifts?: (typeof dayShift)[];+ }) =>+ getWorkCenterWorkingWindows({+ workCenters: [{ id: "potting", alwaysOn: false }],+ workCenterShifts: [{ workCenterId: "potting", shiftId: "day" }],+ timeZone: TZ,+ holidayDates: new Set(),+ rangeStart: at("2026-10-26T05:00:00Z"),+ rangeEnd: at("2026-10-27T05:00:00Z"),+ ...args+ }).get("potting");++ it("works that shift's hours, not the location's", () => {+ // Monday 06:00-14:30 Chicago, from the linked shift alone.+ expect(windows({ shifts: [], linkedShifts: [dayShift] })).toEqual([+ { start: at("2026-10-26T11:00:00Z"), end: at("2026-10-26T19:30:00Z") }+ ]);+ });++ it("has that shift's hours available", () => {+ const hours = getWorkCenterCalendarHoursByDay({+ workCenters: [{ id: "potting", alwaysOn: false }],+ workCenterShifts: [{ workCenterId: "potting", shiftId: "day" }],+ locationShifts: [],+ linkedShifts: [+ {+ id: "day",+ hours: 8.5,+ runsOn: [false, true, true, true, true, true, false]+ }+ ],+ weekDates: WEEK+ });++ expect(hours.get("potting")?.get("2026-10-26")).toBe(8.5);+ });+});diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 65c9407bf6..5f309f6d9a 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -11506,13 +11506,17 @@ export function getWorkCenterWorkingWindows(args: {workCenterShifts: { workCenterId: string; shiftId: string }[];/** The location's active shifts. */shifts: (ShiftRow & { id: string })[];+ /** Shifts a work center is linked to at another location. */+ linkedShifts?: (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 shiftById = new Map(+ [...shifts, ...(args.linkedShifts ?? [])].map((shift) => [shift.id, shift])+ );const ladderWorkCenters = workCenters.map((wc) => ({id: wc.id,alwaysOn: wc.alwaysOn,@@ -11549,7 +11553,7 @@ export async function getHolidayDates(client: SupabaseClient<Database>,companyId: string,args: { from: string; to: string }-): Promise<Set<string>> {+): Promise<{ data: Set<string>; error: PostgrestError | null }> {const { data, error } = await client.from("holiday").select("date")@@ -11558,9 +11562,12 @@ export async function getHolidayDates(.lte("date", args.to);if (error) {logger.error("Failed to load holidays", { companyId, error });- return new Set();+ return { data: new Set(), error };}- return new Set((data ?? []).map((row) => row.date.slice(0, 10)));+ return {+ data: new Set((data ?? []).map((row) => row.date.slice(0, 10))),+ error: null+ };}type CapacityOperation = {workCenterId: string | null;@@ -11614,6 +11621,8 @@ export function getWorkCenterCalendarHoursByDay(args: {workCenters: { id: string; alwaysOn: boolean }[];workCenterShifts: { workCenterId: string; shiftId: string }[];locationShifts: CapacityShift[];+ /** Shifts a work center is linked to at another location. */+ linkedShifts?: CapacityShift[];weekDates: string[];/** Company holidays: 0 hours, except on a lights-out station. */holidayDates?: Set<string>;@@ -11621,7 +11630,12 @@ export function getWorkCenterCalendarHoursByDay(args: {const { workCenters, workCenterShifts, locationShifts, weekDates } = args;const holidayDates = args.holidayDates ?? new Set<string>();- const shiftById = new Map(locationShifts.map((shift) => [shift.id, shift]));+ const shiftById = new Map(+ [...locationShifts, ...(args.linkedShifts ?? [])].map((shift) => [+ shift.id,+ shift+ ])+ );const shiftIdsByWorkCenter = new Map<string, string[]>();for (const link of workCenterShifts) {const list = shiftIdsByWorkCenter.get(link.workCenterId);diff --git a/apps/erp/app/modules/resources/AGENTS.md b/apps/erp/app/modules/resources/AGENTS.mdindex 1996636288..b3d051b075 100644--- a/apps/erp/app/modules/resources/AGENTS.md+++ b/apps/erp/app/modules/resources/AGENTS.md@@ -9,7 +9,7 @@ Locations, work centers, processes, abilities (skills), partners, contractors, e- **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)` — 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`. 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.+- **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. `abilities` is optional on the `createContractor` / `updateContractor` operations for the same reason.- **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.diff --git a/apps/erp/app/modules/resources/resources.server.ts b/apps/erp/app/modules/resources/resources.server.tsindex c6c8496b5f..73e45e7919 100644--- a/apps/erp/app/modules/resources/resources.server.ts+++ b/apps/erp/app/modules/resources/resources.server.ts@@ -2995,7 +2995,12 @@ export const createContractor = defineServiceFn({"Updates the existing record with this key; creates one when there is none."),hoursPerWeek: z.number().optional(),- abilities: z.array(z.string()),+ abilities: z+ .array(z.string())+ .optional()+ .describe(+ "Replaces the contractor's abilities when sent; left out, they are kept."+ ),customFields: z.unknown().optional()}),permission: { create: "resources" },@@ -3026,7 +3031,12 @@ export const updateContractor = defineServiceFn({"Updates the existing record with this key; creates one when there is none."),hoursPerWeek: z.number().optional(),- abilities: z.array(z.string()),+ abilities: z+ .array(z.string())+ .optional()+ .describe(+ "Replaces the contractor's abilities when sent; left out, they are kept."+ ),customFields: z.unknown().optional()}),permission: { update: "resources" },diff --git a/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsx b/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsxindex f9c4d2eb9c..81edca1ca1 100644--- a/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsx+++ b/apps/erp/app/modules/resources/ui/Abilities/AbilitiesTable.tsx@@ -3,7 +3,6 @@// 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";@@ -17,7 +16,7 @@ import {import { useNavigate } from "react-router";import { EmployeeAvatarGroup, Hyperlink, New, Table } from "~/components";import { Enumerable } from "~/components/Enumerable";-import { usePermissions, useUrlParams } from "~/hooks";+import { useCompanyToday, usePermissions, useUrlParams } from "~/hooks";import type { Abilities } from "~/modules/resources/types";import { usePeople } from "~/stores";import { path } from "~/utils/path";@@ -35,6 +34,8 @@ const AbilitiesTable = memo(({ data, count }: AbilitiesTableProps) => {const [params] = useUrlParams();const permissions = usePermissions();const [people] = usePeople();+ // The company's day, not the viewer's: the list spans every location.+ const todayDate = useCompanyToday();const employeeOptions = useMemo(() => people.map((person) => ({ value: person.id, label: person.name })),@@ -76,7 +77,6 @@ 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 todayDate = today(getLocalTimeZone()).toString();const employeeIds = (row.original.employeeAbility ?? []).filter((ea) => !ea.expiresAt || ea.expiresAt.slice(0, 10) > todayDate@@ -98,7 +98,7 @@ const AbilitiesTable = memo(({ data, count }: AbilitiesTableProps) => {}}];- }, [t, employeeOptions]);+ }, [t, employeeOptions, todayDate]);const renderContextMenu = useCallback<(row: Ability) => JSX.Element>((row) => (diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex 57a2688589..f4551a1492 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -1158,7 +1158,7 @@{"name":"resources_activateProcess","classification":"WRITE","schema":"5631e53ea64f","response":"bcde375ebd4c","permission":"resources:update","paginates":false},{"name":"resources_addEmployeeAbility","classification":"WRITE","schema":"86a9132fd668","response":"3797626bd17e","permission":"resources:update","paginates":false},{"name":"resources_createAbility","classification":"WRITE","schema":"df2e6ccff2a4","response":"3797626bd17e","permission":"resources:create","paginates":false},- {"name":"resources_createContractor","classification":"DESTRUCTIVE","schema":"11891191bd97","response":"bcde375ebd4c","permission":"resources:create","paginates":false},+ {"name":"resources_createContractor","classification":"DESTRUCTIVE","schema":"f2767d28cf12","response":"bcde375ebd4c","permission":"resources:create","paginates":false},{"name":"resources_createFailureMode","classification":"WRITE","schema":"c922337b313e","response":"8394fbabd845","permission":"resources:create","paginates":false},{"name":"resources_createLocation","classification":"WRITE","schema":"140095be5d68","response":"3797626bd17e","permission":"resources:create","paginates":false},{"name":"resources_createMaintenanceDispatch","classification":"WRITE","schema":"629d474dc047","response":"ede36af7307d","permission":"resources:create","paginates":false},@@ -1241,7 +1241,7 @@{"name":"resources_uncompleteTrainingAssignment","classification":"DESTRUCTIVE","schema":"d520f70388c9","response":"d520f70388c9","permission":"resources:delete","paginates":false},{"name":"resources_unissueMaintenancePart","classification":"DESTRUCTIVE","schema":"be5a1d978dcc","response":"3797626bd17e","permission":"resources:delete","paginates":false},{"name":"resources_updateAbility","classification":"WRITE","schema":"9fa76da0d27e","response":"bcde375ebd4c","permission":"resources:update","paginates":false},- {"name":"resources_updateContractor","classification":"DESTRUCTIVE","schema":"11891191bd97","response":"bcde375ebd4c","permission":"resources:update","paginates":false},+ {"name":"resources_updateContractor","classification":"DESTRUCTIVE","schema":"f2767d28cf12","response":"bcde375ebd4c","permission":"resources:update","paginates":false},{"name":"resources_updateEmployeeAbility","classification":"WRITE","schema":"86a9132fd668","response":"3797626bd17e","permission":"resources:update","paginates":false},{"name":"resources_updateFailureMode","classification":"WRITE","schema":"ac1031d30650","response":"8394fbabd845","permission":"resources:update","paginates":false},{"name":"resources_updateLocation","classification":"WRITE","schema":"ce189a85ea7e","response":"3797626bd17e","permission":"resources:create+update","paginates":false},diff --git a/apps/erp/app/routes/x+/priority+/people.tsx b/apps/erp/app/routes/x+/priority+/people.tsxindex 76b9acef8f..5f19c6df53 100644--- a/apps/erp/app/routes/x+/priority+/people.tsx+++ b/apps/erp/app/routes/x+/priority+/people.tsx@@ -23,7 +23,8 @@ import { useLoaderData } from "react-router";import {getEmployeeDepartments,getEmployeeShifts,- getShiftsWithTimes+ getShiftsWithTimes,+ getShiftsWithTimesByIds} from "~/modules/people/people.service";import {buildPeopleCapacityBuckets,@@ -367,10 +368,40 @@ export async function loader({ request }: LoaderFunctionArgs) {spanStartMs = Math.min(spanStartMs, Date.parse(reservation.startAt));spanEndMs = Math.max(spanEndMs, Date.parse(reservation.endAt));}- const holidayDates = await getHolidayDates(client, companyId, {+ const holidays = await getHolidayDates(client, companyId, {from: toCalendarDate(fromAbsolute(spanStartMs, timezone)).toString(),to: toCalendarDate(fromAbsolute(spanEndMs, timezone)).toString()});+ if (holidays.error) {+ throw redirect(+ path.to.production,+ await flash(request, error(holidays.error, "Failed to load holidays"))+ );+ }+ const holidayDates = holidays.data;+ // A station can be linked to a shift of another location.+ const locationShiftIds = new Set(shiftRows.map((shift) => shift.id));+ const otherShiftIds = [+ ...new Set(+ wcShiftLinks+ .map((link) => link.shiftId)+ .filter((id) => !locationShiftIds.has(id))+ )+ ];+ const otherShifts =+ otherShiftIds.length > 0+ ? await getShiftsWithTimesByIds(client, companyId, otherShiftIds)+ : { data: [], error: null };+ if (otherShifts.error) {+ throw redirect(+ path.to.production,+ await flash(+ request,+ error(otherShifts.error, "Failed to load shifts")+ )+ );+ }+ const linkedShiftRows = otherShifts.data ?? [];capacityHolidayDates = [...holidayDates];const ladderWorkCenters = (workCenters.data ?? []).flatMap((workCenter) =>@@ -400,6 +431,21 @@ export async function loader({ request }: LoaderFunctionArgs) {workCenters: ladderWorkCenters,workCenterShifts: wcShiftLinks,locationShifts: locationLadderShifts,+ linkedShifts: linkedShiftRows.map((shift) => ({+ id: shift.id,+ hours:+ shiftDurationHours(shift.startTime, shift.endTime) ??+ defaultShiftHours,+ runsOn: [+ shift.sunday,+ shift.monday,+ shift.tuesday,+ shift.wednesday,+ shift.thursday,+ shift.friday,+ shift.saturday+ ]+ })),weekDates,holidayDates});@@ -407,6 +453,7 @@ export async function loader({ request }: LoaderFunctionArgs) {workCenters: ladderWorkCenters,workCenterShifts: wcShiftLinks,shifts: shiftRows,+ linkedShifts: linkedShiftRows,timeZone: timezone,holidayDates,rangeStart: spanStartMs,diff --git a/apps/erp/app/routes/x+/scheduling+/forecast.tsx b/apps/erp/app/routes/x+/scheduling+/forecast.tsxindex d692d143ac..1afca28c41 100644--- a/apps/erp/app/routes/x+/scheduling+/forecast.tsx+++ b/apps/erp/app/routes/x+/scheduling+/forecast.tsx@@ -2,9 +2,11 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.+import { error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";+import { flash } from "@carbon/auth/session.server";import { Badge, Button, ClientOnly, cn, useDebounce } from "@carbon/react";-import { datetime, formatDate } from "@carbon/utils";+import { datetime, formatDate, redirect } from "@carbon/utils";import type { CalendarDate } from "@internationalized/date";import {CalendarDateTime,@@ -210,7 +212,7 @@ 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 [reservations, maintenanceResult, holidayDates] = await Promise.all([+ const [reservations, maintenanceResult, holidays] = await Promise.all([getCapacityReservationsForResources(client, companyId, locationId, {from: new Date(windowStartMs).toISOString(),to: new Date(windowEndMs).toISOString()@@ -221,12 +223,18 @@ export async function loader({ request }: LoaderFunctionArgs) {to: toCalendarDate(fromAbsolute(windowEndMs, timeZone)).toString()})]);+ if (holidays.error) {+ throw redirect(+ path.to.production,+ await flash(request, error(holidays.error, "Failed to load holidays"))+ );+ }const nonWorkingIntervals = getForecastNonWorkingIntervals({timeZone,shifts,windowStartMs,windowEndMs,- holidayDates+ holidayDates: holidays.data});// Open outages that take a work center offline, as [start, end) windows fordiff --git a/apps/erp/test/people-operations.test.ts b/apps/erp/test/people-operations.test.tsindex e304f335e0..26d79da23b 100644--- a/apps/erp/test/people-operations.test.ts+++ b/apps/erp/test/people-operations.test.ts@@ -42,12 +42,17 @@ describe("timeCardError", () => {// The boundary is PostgREST: a real supabase-js client whose fetch answers the// shift UPDATE with `rows`, as RLS leaves them. An UPDATE that reaches no row-// is not an error there, so the empty answer is the case to refuse.-function shiftCaller(rows: { id: string }[]) {+// is not an error there, so the empty answer is the case to refuse. The read+// before it (the shift's current location) answers with `stored`.+function shiftCaller(+ rows: { id: string }[],+ stored: { locationId: string }[] = rows.map(() => ({ locationId: "loc-1" }))+) {const sent: { method: string; url: URL }[] = [];const fetchStub = async (input: RequestInfo | URL, init?: RequestInit) => {- sent.push({ method: init?.method ?? "GET", url: new URL(String(input)) });- return new Response(JSON.stringify(rows), {+ const method = init?.method ?? "GET";+ sent.push({ method, url: new URL(String(input)) });+ return new Response(JSON.stringify(method === "GET" ? stored : rows), {status: 200,headers: { "Content-Type": "application/json" }});@@ -117,10 +122,10 @@ describe("updateShift", () => {category: "notFound",message: "Shift not found"});- expect(sent).toHaveLength(1);- expect(sent[0]?.method).toBe("PATCH");- expect(sent[0]?.url.searchParams.get("id")).toBe("eq.shift-missing");- expect(sent[0]?.url.searchParams.get("companyId")).toBe("eq.company-1");+ const patch = sent.filter((request) => request.method === "PATCH");+ expect(patch).toHaveLength(1);+ expect(patch[0]?.url.searchParams.get("id")).toBe("eq.shift-missing");+ expect(patch[0]?.url.searchParams.get("companyId")).toBe("eq.company-1");expect(trigger).not.toHaveBeenCalled();});@@ -131,8 +136,28 @@ describe("updateShift", () => {SHIFT);expect(result).toEqual({ data: { id: "shift-1" }, error: null });- expect(trigger.mock.calls.map(([event]) => event)).toEqual([- "schedule-inputs-changed"+ expect(trigger.mock.calls).toEqual([+ [+ "schedule-inputs-changed",+ expect.objectContaining({ kind: "shift", entityId: "shift-1" })+ ]+ ]);+ });++ // The stations at the old location lose the shift's hours too, and the+ // shift-scoped notice only sees the new location.+ it("re-plans the company when the shift moves to another location", async () => {+ const { client } = shiftCaller([{ id: "shift-1" }], [{ locationId: "hq" }]);+ const result = await updateShift(+ shiftContext(client, ["company-1"]),+ SHIFT+ );+ expect(result).toEqual({ data: { id: "shift-1" }, error: null });+ expect(trigger.mock.calls).toEqual([+ [+ "schedule-inputs-changed",+ expect.objectContaining({ kind: "location", entityId: undefined })+ ]]);});});diff --git a/packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.ts b/packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.tsindex 738d0a89c5..e499165432 100644--- a/packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.ts+++ b/packages/jobs/src/inngest/functions/scheduled/schedule-inputs-changed.ts@@ -11,7 +11,10 @@ import { NonRetriableError } from "inngest";import { z } from "zod";import { getJobDatabaseClient } from "../../../db";import { inngest } from "../../client";-import { workCentersOnShift } from "./shift-work-centers";+import {+ processesOfWorkCenters,+ workCentersOnShift+} from "./shift-work-centers";const log = getLogger("jobs", "schedule-replan");@@ -66,53 +69,78 @@ const scheduleInputsChangedData = z.object({});/**- * The work centers whose hours come from this shift (`workCentersOnShift`),- * or null when the shift is not the company's.+ * The work centers whose hours come from this shift (`workCentersOnShift`) and+ * the processes they run, or null when the shift is not the company's.*/-async function loadShiftWorkCenterIds(+async function loadShiftScope(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")- )- ]);+): Promise<{ workCenterIds: string[]; processIds: string[] } | null> {+ const [shift, workCenters, links, activeShifts, processes] =+ 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")+ ),+ fetchAllFromTable<{ workCenterId: string; processId: string }>(+ serviceRole,+ "workCenterProcess",+ "workCenterId, processId",+ (query) =>+ query+ .eq("companyId", companyId)+ .order("workCenterId")+ .order("processId")+ )+ ]);const failed =- shift.error ?? workCenters.error ?? links.error ?? activeShifts.error;+ shift.error ??+ workCenters.error ??+ links.error ??+ activeShifts.error ??+ processes.error;if (failed) {throw new Error(`Failed to load the shift's work centers: ${failed.message}`);}if (!shift.data) return null;- return workCentersOnShift({+ const workCenterIds = 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))});+ return {+ workCenterIds,+ processIds: processesOfWorkCenters({+ workCenterIds,+ workCenterProcesses: processes.data ?? []+ })+ };}/**@@ -169,7 +197,7 @@ export const markScheduleStaleFunction = inngest.createFunction(// 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)+ // on the work centers that run the shift, or on the processes they run// - 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@@ -198,17 +226,16 @@ 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.+ // A shift is also machine hours: the ops on the work centers that run+ // it re-plan too, gated or not, and so do the ops of the processes those+ // work centers run (an unstarted op can move onto one of them).let shiftWorkCenterIds: string[] = [];+ let shiftProcessIds: string[] = [];if (kind === "shift" && entityId) {- const scope = await loadShiftWorkCenterIds(- serviceRole,- companyId,- entityId- );+ const scope = await loadShiftScope(serviceRole, companyId, entityId);if (scope === null) return null; // unknown shift: re-plan everything- shiftWorkCenterIds = scope;+ shiftWorkCenterIds = scope.workCenterIds;+ shiftProcessIds = scope.processIds;}if (@@ -221,7 +248,10 @@ export const markScheduleStaleFunction = inngest.createFunction(}[] =processIds !== null? [- { column: "processId", values: processIds },+ {+ column: "processId",+ values: [...new Set([...processIds, ...shiftProcessIds])]+ },{ column: "workCenterId", values: shiftWorkCenterIds }]: [{ column: "workCenterId", values: [entityId as string] }];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.tsindex 3b1e829926..ed9e642600 100644--- a/packages/jobs/src/inngest/functions/scheduled/shift-work-centers.test.ts+++ b/packages/jobs/src/inngest/functions/scheduled/shift-work-centers.test.ts@@ -3,7 +3,10 @@// 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";+import {+ processesOfWorkCenters,+ workCentersOnShift+} from "./shift-work-centers";// The plant: Day (active) and Weekend (the shift being changed, active).const base = (@@ -49,3 +52,19 @@ describe("workCentersOnShift", () => {).toEqual(["pcb-lab", "cnc-mill", "tig"]);});});++describe("processesOfWorkCenters", () => {+ it("is every process the affected stations run, once each", () => {+ expect(+ processesOfWorkCenters({+ workCenterIds: ["tig", "pcb-lab"],+ workCenterProcesses: [+ { workCenterId: "tig", processId: "welding" },+ { workCenterId: "pcb-lab", processId: "smt" },+ { workCenterId: "pcb-lab", processId: "welding" },+ { workCenterId: "cnc-mill", processId: "machining" }+ ]+ })+ ).toEqual(["welding", "smt"]);+ });+});diff --git a/packages/jobs/src/inngest/functions/scheduled/shift-work-centers.ts b/packages/jobs/src/inngest/functions/scheduled/shift-work-centers.tsindex 73770d35ee..f3c026126e 100644--- a/packages/jobs/src/inngest/functions/scheduled/shift-work-centers.ts+++ b/packages/jobs/src/inngest/functions/scheduled/shift-work-centers.ts@@ -39,3 +39,22 @@ export function workCentersOnShift(args: {).map((wc) => wc.id);}++/**+ * The processes the given work centers run. An op that has not started is+ * balanced across every work center of its process, so a shift change on one+ * of them can move ops stored on another.+ */+export function processesOfWorkCenters(args: {+ workCenterIds: string[];+ workCenterProcesses: { workCenterId: string; processId: string }[];+}): string[] {+ const workCenterIds = new Set(args.workCenterIds);+ return [+ ...new Set(+ args.workCenterProcesses+ .filter((link) => workCenterIds.has(link.workCenterId))+ .map((link) => link.processId)+ )+ ];+}diff --git a/packages/planning/src/scheduling/persist-location.test.ts b/packages/planning/src/scheduling/persist-location.test.tsnew file mode 100644index 0000000000..abc1cf7d9f--- /dev/null+++ b/packages/planning/src/scheduling/persist-location.test.ts@@ -0,0 +1,21 @@+// 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 { jobsClearingReservations } from "./persist-location.ts";++describe("jobsClearingReservations", () => {+ it("is every job the run wrote plus every job that failed, once each", () => {+ expect(+ jobsClearingReservations(+ [{ jobId: "job-a" }, { jobId: "job-b" }],+ ["job-c", "job-a"]+ )+ ).toEqual(["job-a", "job-b", "job-c"]);+ });++ it("still names a failed job when no job wrote", () => {+ expect(jobsClearingReservations([], ["job-c"])).toEqual(["job-c"]);+ });+});diff --git a/packages/planning/src/scheduling/persist-location.ts b/packages/planning/src/scheduling/persist-location.tsindex 8a51de27dc..75ccac889b 100644--- a/packages/planning/src/scheduling/persist-location.ts+++ b/packages/planning/src/scheduling/persist-location.ts@@ -71,17 +71,33 @@ async function updatePlacements(`.execute(trx);}+/**+ * The jobs whose stored reservations a location write replaces: every job it+ * writes, and every job that threw while computing. The batch pre-pass placed+ * around all of the run's jobs as bookings about to be replaced, so a failed+ * job's stored ones must go too, or a batch can sit on top of one. The failed+ * job stays stamped stale, so the next wave plans it again.+ */+export function jobsClearingReservations(+ writes: Pick<JobWrites, "jobId">[],+ failedJobIds: string[]+): string[] {+ return [...new Set([...writes.map((w) => w.jobId), ...failedJobIds])];+}+/*** Write a whole location run in ONE transaction: a partial write (one job's* reservations deleted but not re-inserted, or half the jobs on the new plan)* would free or double-book capacity for the next run.+ * `failedJobIds`: see `jobsClearingReservations`.*/export async function persistLocationWrites(db: Kysely<DB>,writes: JobWrites[],- scope: { companyId: string; userId: string }+ scope: { companyId: string; userId: string },+ failedJobIds: string[] = []): Promise<void> {- if (writes.length === 0) return;+ if (writes.length === 0 && failedJobIds.length === 0) return;const { companyId, userId } = scope;await db.transaction().execute(async (trx) => {@@ -168,7 +184,9 @@ export async function persistLocationWrites(// Rebuild the jobs' live capacity reservations from this run's placements.// Batch-tagged rows are spared: a member job's regen must never destroy// the batch's coalesced reservation.- for (const jobIds of chunks(writes.map((w) => w.jobId))) {+ for (const jobIds of chunks(+ jobsClearingReservations(writes, failedJobIds)+ )) {await trx.deleteFrom("capacityReservation").where("jobId", "in", jobIds)diff --git a/packages/planning/src/scheduling/run-schedule.ts b/packages/planning/src/scheduling/run-schedule.tsindex ed18113ae0..8b7da6dd36 100644--- a/packages/planning/src/scheduling/run-schedule.ts+++ b/packages/planning/src/scheduling/run-schedule.ts@@ -206,8 +206,8 @@ export async function runLocationSchedule(batchPlacements});// One job's failure must not abandon the rest of the batch — it is left- // out of the write, so it stays stamped stale for a later wave and the- // jobs behind it still see its stored reservations.+ // out of the write, so it stays stamped stale for a later wave. The jobs+ // behind it still see its stored reservations; the write then clears them.try {const result = await engine.run();const jobWrites = engine.getWrites();@@ -233,7 +233,7 @@ export async function runLocationSchedule(}}- await persistLocationWrites(db, writes, { companyId, userId });+ await persistLocationWrites(db, writes, { companyId, userId }, failedJobIds);return {locationId,