Skip to content

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

8.8 KB
Raw Blame
// 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 { 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";

function makeOp(
  overrides: Partial<ScheduledOperation> = {}
): ScheduledOperation {
  return {
    id: "op-1",
    jobId: "job-1",
    processId: "process-1",
    startDate: "2026-07-13",
    dueDate: "2026-07-14",
    priority: 1,
    durationHours: 8,
    durationDays: 1,
    hasConflict: false,
    conflictReason: null,
    ...overrides
  };
}

const PRIOR_CONFLICT =
  "Operation must start on 2026-07-13 but current date is 2026-07-14";

it("finite placement sets dates and clears any prior conflict", () => {
  const ops = new Map<string, ScheduledOperation>([
    ["op-1", makeOp({ hasConflict: true, conflictReason: PRIOR_CONFLICT })]
  ]);
  const selections = new Map<string, WorkCenterSelection>([
    [
      "op-1",
      {
        workCenterId: "wc-1",
        priority: 0,
        placedStart: "2026-07-14T00:00:00.000Z",
        placedEnd: "2026-07-14T08:00:00.000Z",
        conflict: null
      }
    ]
  ]);

  const result = applyWorkCenterSelections(ops, selections);
  const op = result.get("op-1");
  assert(op);
  assertEquals(op.startDate, "2026-07-14");
  // The forecast is the EXACT placed-end instant; the stored need-by target
  // (dueDate) is never touched by the forward pass.
  assertEquals(op.projectedCompletionAt, "2026-07-14T08:00:00.000Z");
  assertEquals(op.dueDate, "2026-07-14");
  assertEquals(op.hasConflict, false);
  assertEquals(op.conflictReason, null);
});

it("late finite placement records the finite conflict reason", () => {
  const ops = new Map<string, ScheduledOperation>([
    ["op-1", makeOp({ hasConflict: true, conflictReason: PRIOR_CONFLICT })]
  ]);
  const finiteReason =
    "Finishes 2026-07-16 but the job is due 2026-07-14 — waited for the work center, queued behind J000009 (2 ops)";
  const selections = new Map<string, WorkCenterSelection>([
    [
      "op-1",
      {
        workCenterId: "wc-1",
        priority: 0,
        placedStart: "2026-07-15T00:00:00.000Z",
        placedEnd: "2026-07-16T08:00:00.000Z",
        conflict: finiteReason
      }
    ]
  ]);

  const result = applyWorkCenterSelections(ops, selections);
  const op = result.get("op-1");
  assert(op);
  assertEquals(op.hasConflict, true);
  assertEquals(op.conflictReason, finiteReason);
});

it("selection without a placement leaves the op's dates and conflict untouched (e.g. a pin)", () => {
  const ops = new Map<string, ScheduledOperation>([
    ["op-1", makeOp({ hasConflict: true, conflictReason: PRIOR_CONFLICT })]
  ]);
  const selections = new Map<string, WorkCenterSelection>([
    ["op-1", { workCenterId: "wc-1", priority: 0 }]
  ]);

  const result = applyWorkCenterSelections(ops, selections);
  const op = result.get("op-1");
  assert(op);
  assertEquals(op.startDate, "2026-07-13");
  assertEquals(op.hasConflict, true);
  assertEquals(op.conflictReason, PRIOR_CONFLICT);
});

it("outside placement (no work center) applies dates and clears any prior conflict", () => {
  const ops = new Map<string, ScheduledOperation>([
    [
      "op-1",
      makeOp({
        startDate: "2026-06-17",
        dueDate: "2026-06-18",
        hasConflict: true,
        conflictReason: PRIOR_CONFLICT
      })
    ]
  ]);
  const selections = new Map<string, WorkCenterSelection>([
    [
      "op-1",
      {
        workCenterId: null,
        priority: 0,
        placedStart: "2026-07-15T08:00:00.000Z",
        placedEnd: "2026-07-15T08:00:00.000Z",
        conflict: null
      }
    ]
  ]);

  const result = applyWorkCenterSelections(ops, selections);
  const op = result.get("op-1");
  assert(op);
  assertEquals(op.workCenterId, undefined);
  assertEquals(op.startDate, "2026-07-15");
  assertEquals(op.projectedCompletionAt, "2026-07-15T08:00:00.000Z");
  // The stored need-by target is untouched by placement.
  assertEquals(op.dueDate, "2026-06-18");
  assertEquals(op.hasConflict, false);
  assertEquals(op.conflictReason, null);
});

it("operation without a selection passes through unchanged", () => {
  const original = makeOp({
    hasConflict: true,
    conflictReason: PRIOR_CONFLICT
  });
  const ops = new Map<string, ScheduledOperation>([["op-1", original]]);

  const result = applyWorkCenterSelections(
    ops,
    new Map<string, WorkCenterSelection>()
  );
  assertEquals(result.get("op-1"), original);
});

it("placed start is recorded as the factory's calendar day; the projected finish keeps its exact instant", () => {
  const ops = new Map<string, ScheduledOperation>([["op-1", makeOp({})]]);
  const selections = new Map<string, WorkCenterSelection>([
    [
      "op-1",
      {
        workCenterId: "wc-1",
        priority: 0,
        // 22:00 UTC on the 19th = 03:30 IST on the 20th
        placedStart: "2026-07-19T22:00:00.000Z",
        placedEnd: "2026-07-20T21:34:00.000Z",
        conflict: null
      }
    ]
  ]);

  const utc = applyWorkCenterSelections(ops, selections).get("op-1")!;
  assertEquals(utc.startDate, "2026-07-19");
  assertEquals(utc.projectedCompletionAt, "2026-07-20T21:34:00.000Z");

  const ist = applyWorkCenterSelections(ops, selections, "Asia/Kolkata").get(
    "op-1"
  )!;
  assertEquals(ist.startDate, "2026-07-20");
  // The instant is timezone-independent — no business-day rounding.
  assertEquals(ist.projectedCompletionAt, "2026-07-20T21:34:00.000Z");
  // 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"]
    ]
  );
});