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(scheduling): re-plan on staffing and timezone changes; keep deadline type in step with board dates
naveenkashe0634e3d9eea
diff --git a/.claude/rules/scheduling-data-structures.md b/.claude/rules/scheduling-data-structures.mdindex c9c13b720e..8256256313 100644--- a/.claude/rules/scheduling-data-structures.md+++ b/.claude/rules/scheduling-data-structures.md@@ -74,7 +74,9 @@ Spec/plan: `.ai/specs/2026-09-22-quote-lead-time-prediction.md`.sequence and work center only — does not reschedule. Change dates on the Dates board."*)and `dates.tsx` (jobs-by-due-date Kanban; drag →`dates.update.tsx` → `api.production.moveScheduleJob`, which writes `job.dueDate` +- `priority`, **then calls `notifyScheduleInputsChanged(…, "reorder", …)`** — which only stamps the+ `priority` and, in the same UPDATE, the deadline type the date implies+ (`deadlineTypeForDueDate`: a dated No Deadline job becomes Soft Deadline, an undated+ Hard / Soft Deadline job becomes No Deadline), **then calls `notifyScheduleInputsChanged(…, "reorder", …)`** — which only stamps thejobs schedule-outdated; the debounced wave regenerates the whole location. Thereis no immediate single-job path). `people.tsx` is the Peoplepage with a segmented view switcher (`?view=`): the People **board** (manning@@ -218,7 +220,10 @@ Two Inngest functions listen on that eventcount), or on a process those stations run (`processesOfWorkCenters`: an unstarted opcan 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.+ another location sends kind `location` instead, so the stations it left re-plan too.+ Changing a location's staffing requirement (`updateProductionSettings`) or its+ timezone (`updateLocation`, shifts are local times) also sends kind `location`,+ only when the value actually changed. 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/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex 7a18321daa..64f48ee811 100644--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@ -131,7 +131,7 @@ pnpm --filter erp test- `getJobReceiptSnapshot(db, jobId, companyId)` — a job's `quantityReceivedToInventory` plus the `trackedEntity` ids its `Job Receipt` ledger rows already posted, in ONE statement so the two can never come from different moments. Kysely because `itemLedger` is RLS-hidden from users without inventory/accounting view. Served by `api/production/job/:jobId/receipts`, read when the Complete dialog opens- `getActiveJobOperationsByLocation` — schedule board data (RPC `get_active_job_operations_by_location`, now also returns `processBatchable`/`jobOperationBatchId`/`batchReadableId`; never lists an Outside Processing operation, even one holding a stale work center)- `getBatchableOperations` / `getBatchableProcesses` — batch builder candidate data (RPC `get_batchable_operations` with per-op BOM material properties), served via `api/production/batchable-operations`. `getBatchableProcesses` also selects `batchRules` so the builder can resolve per-process compatibility rules-- `createJobOperationBatch` / `updateJobOperationBatch` — operation batch mutations (call the `batch-operations` posting: create/add/remove/update/dissolve). These are building blocks (never tools): `x+/priority+/batching.update.tsx` makes one call per intent to the service functions `createBatch` (creates the batch Planned; on Create & Release then releases the member jobs and the batch and tells the scheduler, taking the batch apart again when the jobs' checks refuse), `updateBatch` (add / remove / work center / dissolve), `releaseBatches`, `unreleaseBatch` (then tells the scheduler), `reprioritizeBatch` (a batch card's dispatch order) and `mergeBatchOutputs` (`production.server.ts`). The schedule boards' drops are `reorderScheduleOperations` (operations board, one card or a column; tells the scheduler on a work-center change) and `moveScheduleJob` (dates board)+- `createJobOperationBatch` / `updateJobOperationBatch` — operation batch mutations (call the `batch-operations` posting: create/add/remove/update/dissolve). These are building blocks (never tools): `x+/priority+/batching.update.tsx` makes one call per intent to the service functions `createBatch` (creates the batch Planned; on Create & Release then releases the member jobs and the batch and tells the scheduler, taking the batch apart again when the jobs' checks refuse), `updateBatch` (add / remove / work center / dissolve), `releaseBatches`, `unreleaseBatch` (then tells the scheduler), `reprioritizeBatch` (a batch card's dispatch order) and `mergeBatchOutputs` (`production.server.ts`). The schedule boards' drops are `reorderScheduleOperations` (operations board, one card or a column; tells the scheduler on a work-center change) and `moveScheduleJob` (dates board; the deadline type follows the date, `deadlineTypeForDueDate`)- `getBatchOutputLots` — a completed batch's MERGEABLE output lots: each member's WIP `trackedEntity` (by `attributes->>Job Make Method`), narrowed in-query to `Available` with stock. Drives the drawer's "Merge output lots"; a merged batch returns none (parents `Consumed`). The merge itself is `inventory`'s `mergeTrackedEntities` wrapper over `issue` `mergeTrackedEntities`- `getUnbatchedBatchableOperationCount` — head count of open (Todo/Ready/Waiting) unbatched operations on a batchable process for live jobs, mirroring the `get_batchable_operations` candidate branch; drives the production dashboard's "Unbatched Operations" card (links to `/x/production/batches/new`)- `getJobOperationBatches` / `getJobOperationBatchMemberStats` / `getJobOperationBatchMembers` / `getJobOperationBatchWithMembers` — the `/x/production/batches` list (filterable, member count + summed quantity merged in the loader; `getJobOperationBatchMembers` is a single grouped `.in()` read of the page's member rows — job/item/quantity — powering the table's expandable member sub-rows, mirroring the ECO change-notices table's `renderExpandedRow`) and its detail drawerdiff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.tsindex 6cc3a61acf..894e695e02 100644--- a/apps/erp/app/modules/production/production.server.ts+++ b/apps/erp/app/modules/production/production.server.ts@@ -1296,6 +1296,8 @@ export const reorderScheduleOperations = defineServiceFn({* `columnId` is a date (`YYYY-MM-DD`) or one of the board's undated columns,* which clears the due date. Writes the due date and priority of a job at* `locationId` that is not locked; a job elsewhere or locked is a `conflict`.+ * The deadline type follows the date: a dated "No Deadline" job becomes "Soft+ * Deadline", and an undated Hard or Soft Deadline job becomes "No Deadline".* Then the scheduler is told; the debounced wave regenerates the location in* due date, then priority, order. A failed notice is logged and not returned.*@@ -1312,17 +1314,37 @@ export const moveScheduleJob = defineServiceFn({return ctx.error("validation", "Invalid form data");}+ const current = await ctx.asCaller.supabase+ .from("job")+ .select("deadlineType")+ .eq("id", id)+ .eq("companyId", companyId)+ .eq("locationId", locationId)+ .not("status", "in", `(${JOB_LOCKED_STATUSES.join(",")})`)+ .maybeSingle();+ if (current.error) {+ return ctx.error("internal", current.error.message, current.error);+ }+ if (current.data === null) {+ return ctx.error("conflict", "Job unavailable or locked");+ }+const { data, error } = await ctx.asCaller.supabase.from("job").update({dueDate,priority,+ deadlineType: service.deadlineTypeForDueDate(+ current.data.deadlineType,+ dueDate+ ),updatedBy: ctx.auditUserId,updatedAt: datetime.timestamp()}).eq("id", id).eq("companyId", companyId).eq("locationId", locationId)+ .eq("deadlineType", current.data.deadlineType).not("status", "in", `(${JOB_LOCKED_STATUSES.join(",")})`).select("id").maybeSingle();diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 5f309f6d9a..295adc8337 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -649,13 +649,6 @@ const DEADLINE_TYPE_PRIORITY: Record<DeadlineType, number> = {"No Deadline": 3};-/**- * The priority of a job placed among `siblings` — the jobs that share its due- * date (or lack of one) at its location, in priority order. Fractional- * indexing: before the first job whose deadline type ranks lower than this- * one's, else at the end. Pure, so a batch can place several jobs on one date- * in turn by appending each result to the siblings it passes for the next.- *//*** The deadline type a job carries once planning gives it a due date. The job* form hides the due-date field for "No Deadline" (`deadlineRequiresDueDate`),@@ -669,6 +662,29 @@ export function deadlineTypeForPlanningDate(return deadlineType === "No Deadline" ? "Soft Deadline" : deadlineType;}+/**+ * The type a job carries once its due date is set or cleared outside the job+ * form. A dated job leaves "No Deadline" (`deadlineTypeForPlanningDate`); an+ * undated Hard or Soft Deadline job becomes "No Deadline", since those two+ * require a date. ASAP ignores the date either way.+ */+export function deadlineTypeForDueDate(+ deadlineType: DeadlineType,+ dueDate: string | null+): DeadlineType {+ if (dueDate !== null) return deadlineTypeForPlanningDate(deadlineType);+ return deadlineType === "Hard Deadline" || deadlineType === "Soft Deadline"+ ? "No Deadline"+ : deadlineType;+}++/**+ * The priority of a job placed among `siblings` — the jobs that share its due+ * date (or lack of one) at its location, in priority order. Fractional+ * indexing: before the first job whose deadline type ranks lower than this+ * one's, else at the end. Pure, so a batch can place several jobs on one date+ * in turn by appending each result to the siblings it passes for the next.+ */export function nextJobPriority(siblings: { priority: number | null; deadlineType: DeadlineType }[],deadlineType: DeadlineTypediff --git a/apps/erp/app/modules/resources/AGENTS.md b/apps/erp/app/modules/resources/AGENTS.mdindex b3d051b075..4a01597e4f 100644--- a/apps/erp/app/modules/resources/AGENTS.md+++ b/apps/erp/app/modules/resources/AGENTS.md@@ -68,7 +68,7 @@ Each operation is one `defineServiceFn` const in `resources.server.ts`. A route|---|---|---|| `createAbility` / `deactivateAbility` | `x+/resources+/abilities.new.tsx`, `abilities.delete.$id.tsx` | The process must be the company's; turns `requiresAbility` on; the scheduler is told || `addEmployeeAbility` / `updateEmployeeAbility` / `removeEmployeeAbility` | `ability.$id.employee.new.tsx`, `person.$personId.ability.new.tsx`, `ability.$id.employee.$employeeAbilityId.tsx`, `ability.$id.employee.delete.$employeeAbilityId.tsx` | The ability must be the company's; a blank expiry comes from the recertification period; the scheduler is told |-| `createLocation` / `updateLocation` | `locations.new.tsx`, `locations.$locationId.tsx` | An update needs `resources` create and update (the old route's gate and the row's policy) and drops the cached timezone |+| `createLocation` / `updateLocation` | `locations.new.tsx`, `locations.$locationId.tsx` | An update needs `resources` create and update (the old route's gate and the row's policy) and drops the cached timezone; a new timezone re-plans the location (kind `location`) || `createProcess` / `updateProcess` | `processes.new.tsx`, `processes.$processId.tsx` | `resources` create; an update needs create, update and delete (it replaces the work centers on the system connection); `requiresAbility` creates the ability, and is rolled back when that fails; a change of it tells the scheduler || `createWorkCenter` / `updateWorkCenter` / `reactivateWorkCenter` / `deactivateWorkCenter` | `work-centers.new.tsx`, `work-centers.$id.tsx`, `work-centers.activate.$id.tsx`, `work-centers.delete.$id.tsx` | A create needs `resources` create and update; deactivate is a soft delete; each tells the scheduler || `createMaintenanceSchedule` / `updateMaintenanceSchedule` | `scheduled-maintenance.new.tsx`, `scheduled-maintenance.$scheduleId.tsx` | Generates the schedule's dispatches now (`generate-maintenance`) |diff --git a/apps/erp/app/modules/resources/resources.server.ts b/apps/erp/app/modules/resources/resources.server.tsindex 73e45e7919..1518aa7f8d 100644--- a/apps/erp/app/modules/resources/resources.server.ts+++ b/apps/erp/app/modules/resources/resources.server.ts@@ -255,7 +255,8 @@ export const createLocation = defineServiceFn({* Update a location.** @remarks- * The location's timezone may change, so its cached timezone is dropped.+ * The location's timezone may change, so its cached timezone is dropped, and+ * a new timezone re-plans the schedule: shifts are local times.** @mcp*/@@ -268,6 +269,19 @@ export const updateLocation = defineServiceFn({permission: { create: "resources", update: "resources" },async run(ctx, { id, ...location }) {+ const previous = await ctx.asCaller.supabase+ .from("location")+ .select("timezone")+ .eq("id", id)+ .eq("companyId", ctx.company.id)+ .maybeSingle();+ if (previous.error) {+ return ctx.error(+ "internal",+ "Failed to update location.",+ previous.error+ );+ }const update = await service.upsertLocation(ctx.asCaller.supabase, {id,...location,@@ -278,6 +292,17 @@ export const updateLocation = defineServiceFn({}await invalidateLocationTimeZone(id, ctx.company.id);+ if (+ previous.data !== null &&+ previous.data.timezone !== location.timezone+ ) {+ await notifyScheduleInputsChanged(+ ctx.company.id,+ "location",+ "Location timezone changed",+ id+ );+ }return { id };}});diff --git a/apps/erp/app/modules/settings/AGENTS.md b/apps/erp/app/modules/settings/AGENTS.mdindex 75779cb4aa..dae5de35d2 100644--- a/apps/erp/app/modules/settings/AGENTS.md+++ b/apps/erp/app/modules/settings/AGENTS.md@@ -75,7 +75,7 @@ A settings page has ONE update operation, `update<Page>Settings` (`updateAccount|---|---|---|| `updateAccountingSettings` / `writeMissingJournals` | `x+/settings+/accounting.tsx` | The deferred tax accounts go to `accountDefault`; the repair runs `journal-legacy-documents` under the operation's own gate and needs `update: accounting` too, so it is not published (the API gate takes one module) || `updateInvoicingSettings`, `updatePurchasingSettings` | `invoicing.tsx`, `purchasing.tsx` | The centralized billing address (a null field clears it); Stripe must be connected for "Post and Send via Stripe" |-| `updateProductionSettings` | `production.tsx` | A location's staffing rule is written as the system, for the company's own location only |+| `updateProductionSettings` | `production.tsx` | A location's staffing rule is written as the system, for the company's own location only; a change re-plans the location (kind `location`) || `updatePeopleSettings` | `people.tsx` | Console mode through `@carbon/ee/console.server` (the plan lock); returns a generated PIN once, never to a key caller. Not published || `updateSecuritySettings` | `security.tsx` | Requiring two-factor through `@carbon/ee/two-factor.server`; emails the company on off → on, never in a controlled environment || `updatePlanningSettings` | `planning.tsx` | Every employee named must be the company's; a location hidden by RLS is refused |diff --git a/apps/erp/app/modules/settings/settings.server.ts b/apps/erp/app/modules/settings/settings.server.tsindex 6322f52a56..26680e6183 100644--- a/apps/erp/app/modules/settings/settings.server.ts+++ b/apps/erp/app/modules/settings/settings.server.ts@@ -70,6 +70,7 @@ import { parseTime } from "@internationalized/date";import { nanoid } from "nanoid";import { z } from "zod";import { plmReleaseControl } from "~/modules/items/items.models";+import { notifyScheduleInputsChanged } from "~/modules/production/production.service";import {invalidateCompanyTimeZone,invokePosting,@@ -373,7 +374,7 @@ export const updateItemsSettings = defineServiceFn({* location requires an assigned operator before the scheduler places work* there. The staffing rule lives on the location row and is written for the* company's own location only, so a settings admin without the resources- * permission can still set it.+ * permission can still set it. Changing it re-plans the location.** @mcp*/@@ -406,20 +407,47 @@ export const updateProductionSettings = defineServiceFn({if (saved) return saved;if (locationStaffing) {- const { data, error } = await ctx.asSystem.supabase+ const { locationId, requiresStaffing } = locationStaffing;+ const current = await ctx.asSystem.supabase.from("location")- .update({ requiresStaffing: locationStaffing.requiresStaffing })- .eq("id", locationStaffing.locationId)+ .select("requiresStaffing")+ .eq("id", locationId).eq("companyId", ctx.company.id)- .select("id");- if (error) {+ .maybeSingle();+ if (current.error) {return ctx.error("internal","Failed to update the staffing requirement",- error+ current.error+ );+ }+ if (current.data === null) {+ return ctx.error("notFound", "Location not found");+ }+ if (current.data.requiresStaffing !== requiresStaffing) {+ const { error } = await ctx.asSystem.supabase+ .from("location")+ .update({ requiresStaffing })+ .eq("id", locationId)+ .eq("companyId", ctx.company.id);+ if (error) {+ return ctx.error(+ "internal",+ "Failed to update the staffing requirement",+ error+ );+ }+ // The scheduler places work only where an operator is manned while+ // this is on, so the location's plan changes either way.+ await notifyScheduleInputsChanged(+ ctx.company.id,+ "location",+ requiresStaffing+ ? "Staffing requirement enabled"+ : "Staffing requirement disabled",+ locationId);}- if (data.length === 0) return ctx.error("notFound", "Location not found");}return input;}diff --git a/apps/erp/test/resources-operations.test.ts b/apps/erp/test/resources-operations.test.tsindex f4e1965002..26d8f641c1 100644--- a/apps/erp/test/resources-operations.test.ts+++ b/apps/erp/test/resources-operations.test.ts@@ -32,6 +32,8 @@ vi.mock("../app/modules/shared/shared.service", async (importOriginal) => {};});vi.mock("@carbon/jobs", () => ({ trigger }));+// The location timezone cache.+vi.mock("@carbon/kv", () => ({ redis: { del: vi.fn() } }));import { createServiceContext } from "@carbon/api/service-fn.server";@@ -44,6 +46,7 @@ const {createTrainingAssignment,completeTrainingAssignment,issueMaintenancePart,+ updateLocation,updateMaintenanceDispatchField,updateTrainingField} = await import("../app/modules/resources/resources.server");@@ -398,3 +401,38 @@ describe("a training's guide or video", () => {expect(result.error?.category).toBe("rule");});});++describe("a location's timezone", () => {+ const location = {+ id: "loc-1",+ name: "Plant",+ addressLine1: "1 Main St",+ city: "Chicago",+ postalCode: "60601",+ countryCode: "US",+ timezone: "America/New_York"+ };++ // Shifts are local times, so the whole plan moves with the timezone.+ it("re-plans the location when the timezone changes", async () => {+ const { ctx } = contextWith({ location: { timezone: "America/Chicago" } });++ const result = await updateLocation(ctx, location);++ expect(result).toEqual({ data: { id: "loc-1" }, error: null });+ expect(scheduleNotices()).toEqual([+ [+ "schedule-inputs-changed",+ expect.objectContaining({ kind: "location", entityId: "loc-1" })+ ]+ ]);+ });++ it("tells no scheduler when only other fields change", async () => {+ const { ctx } = contextWith({ location: { timezone: "America/New_York" } });++ await updateLocation(ctx, location);++ expect(scheduleNotices()).toEqual([]);+ });+});diff --git a/apps/erp/test/schedule-moves.test.ts b/apps/erp/test/schedule-moves.test.tsindex 733e53200b..1a56dfd8f3 100644--- a/apps/erp/test/schedule-moves.test.ts+++ b/apps/erp/test/schedule-moves.test.ts@@ -15,6 +15,7 @@ import {moveScheduleJob,reorderScheduleOperations} from "../app/modules/production/production.server";+import { deadlineTypeForDueDate } from "../app/modules/production/production.service";import { createServiceContext } from "@carbon/api/service-fn.server";type Answer = { data: unknown; error: { message: string } | null };@@ -22,16 +23,19 @@ type Answer = { data: unknown; error: { message: string } | null };/** The user client: one answer per table, whatever the query. */function callerWith(answers: Record<string, Answer>) {const writes: string[] = [];+ const updates: unknown[] = [];return {writes,+ updates,client: {from: (table: string) => {const chain: Record<string, unknown> = {};for (const method of ["select", "eq", "in", "not"]) {chain[method] = () => chain;}- chain.update = () => {+ chain.update = (payload: unknown) => {writes.push(table);+ updates.push(payload);return chain;};const answer = () => answers[table] ?? { data: null, error: null };@@ -172,7 +176,7 @@ describe("moveScheduleJob", () => {});it("writes the date, then tells the scheduler", async () => {- const caller = callerWith({ job: { data: { id: "j1" }, error: null } });+ const caller = callerWith({ job: { data: { id: "j1", deadlineType: "Soft Deadline" }, error: null } });const result = await move(caller);expect(result.error).toBeNull();expect(caller.writes).toEqual(["job"]);@@ -199,7 +203,64 @@ describe("moveScheduleJob", () => {it("keeps the move when the scheduler cannot be told", async () => {trigger.mockRejectedValueOnce(new Error("event bus down"));- const result = await move(callerWith({ job: { data: { id: "j1" }, error: null } }));+ const result = await move(callerWith({ job: { data: { id: "j1", deadlineType: "Soft Deadline" }, error: null } }));expect(result.error).toBeNull();});});++describe("deadlineTypeForDueDate", () => {+ it.each([+ ["No Deadline", "2026-10-30", "Soft Deadline"],+ ["Soft Deadline", "2026-10-30", "Soft Deadline"],+ ["Hard Deadline", "2026-10-30", "Hard Deadline"],+ ["ASAP", "2026-10-30", "ASAP"],+ ["Soft Deadline", null, "No Deadline"],+ ["Hard Deadline", null, "No Deadline"],+ ["ASAP", null, "ASAP"],+ ["No Deadline", null, "No Deadline"]+ ] as const)("a %s job given due date %s is %s", (type, dueDate, expected) => {+ expect(deadlineTypeForDueDate(type, dueDate)).toBe(expected);+ });+});++describe("moveScheduleJob keeps the deadline type in step with the date", () => {+ const move = (deadlineType: string, columnId: string) => {+ const caller = callerWith({+ job: { data: { id: "j1", deadlineType }, error: null }+ });+ return moveScheduleJob(contextWith(caller.client), {+ id: "j1",+ locationId: "loc1",+ columnId,+ priority: -2+ }).then((result) => ({ result, caller }));+ };++ // The job form hides the date of a "No Deadline" job.+ it("makes a No Deadline job dropped on a date a Soft Deadline", async () => {+ const { result, caller } = await move("No Deadline", "2026-10-30");+ expect(result.error).toBeNull();+ expect(caller.updates).toEqual([+ expect.objectContaining({+ dueDate: "2026-10-30",+ priority: -2,+ deadlineType: "Soft Deadline"+ })+ ]);+ });++ // A Hard or Soft Deadline requires a date the board just cleared.+ it("makes a Soft Deadline job dropped on an undated column No Deadline", async () => {+ const { caller } = await move("Soft Deadline", "unscheduled");+ expect(caller.updates).toEqual([+ expect.objectContaining({ dueDate: null, deadlineType: "No Deadline" })+ ]);+ });++ it("leaves an ASAP job's type alone", async () => {+ const { caller } = await move("ASAP", "2026-10-30");+ expect(caller.updates).toEqual([+ expect.objectContaining({ deadlineType: "ASAP" })+ ]);+ });+});diff --git a/apps/erp/test/settings-operations.test.ts b/apps/erp/test/settings-operations.test.tsindex 30342ba7ae..1ae664f3bd 100644--- a/apps/erp/test/settings-operations.test.ts+++ b/apps/erp/test/settings-operations.test.ts@@ -10,6 +10,7 @@ const {consoleSetting,requireMfaSetting,batchTrigger,+ trigger,unmappedRequiredAccounts} = vi.hoisted(() => ({stripeAccount: vi.fn(),@@ -17,6 +18,8 @@ const {requireMfaSetting: vi.fn(),// Inngest: the two-factor announcement is sent through it.batchTrigger: vi.fn(),+ // Inngest: scheduler notices are sent through it.+ trigger: vi.fn(),unmappedRequiredAccounts: vi.fn()}));vi.mock("@carbon/ee/accounting", async (importOriginal) => ({@@ -38,7 +41,7 @@ vi.mock("@carbon/ee/two-factor.server", () => ({vi.mock("@carbon/printing/printing.server", () => ({invalidatePrinterCache: vi.fn()}));-vi.mock("@carbon/jobs", () => ({ batchTrigger, trigger: vi.fn() }));+vi.mock("@carbon/jobs", () => ({ batchTrigger, trigger }));import { EntitlementError } from "@carbon/ee/entitlements.server";import { createServiceContext } from "@carbon/api/service-fn.server";@@ -52,6 +55,7 @@ import {updatePeopleSettings,updatePlanningSettings,updatePostingSync,+ updateProductionSettings,updateSecuritySettings,updateSubsidiaryDetails} from "../app/modules/settings/settings.server";@@ -479,3 +483,45 @@ describe("retrying or skipping sync operations", () => {expect(sent[1]?.url.searchParams.get("id")).toBe("in.(op-2,op-3)");});});++describe("a location's staffing requirement", () => {+ const scheduleNotices = () =>+ trigger.mock.calls.filter(([event]) => event === "schedule-inputs-changed");++ // While it is on, the scheduler places work only where someone is manned.+ it("re-plans the location when the requirement changes", async () => {+ const { ctx, writes } = contextWith({+ location: { requiresStaffing: false }+ });++ const result = await updateProductionSettings(ctx, {+ locationStaffing: { locationId: "loc-1", requiresStaffing: true }+ });++ expect(result.error).toBeNull();+ expect(writes).toContainEqual({+ table: "location",+ method: "update",+ values: { requiresStaffing: true }+ });+ expect(scheduleNotices()).toEqual([+ [+ "schedule-inputs-changed",+ expect.objectContaining({ kind: "location", entityId: "loc-1" })+ ]+ ]);+ });++ it("writes nothing and tells no scheduler when the requirement is unchanged", async () => {+ const { ctx, writes } = contextWith({+ location: { requiresStaffing: true }+ });++ await updateProductionSettings(ctx, {+ locationStaffing: { locationId: "loc-1", requiresStaffing: true }+ });++ expect(writes.filter((w) => w.table === "location")).toEqual([]);+ expect(scheduleNotices()).toEqual([]);+ });+});