+ {batch.status.replaceAll("_", " ")} · Planned {batch.plannedQuantity} pieces
+ BOM revision {batch.bom.revision} · {batch.bom.outputQuantity} pieces per yield
+ {batch.scheduledDate && Scheduled for {batch.scheduledDate.slice(0, 10)}
}
+ {batch.startedAt && Started {new Date(batch.startedAt).toLocaleString()}
}
+ {batch.completion && Completed {new Date(batch.completion.createdAt).toLocaleString()} · {batch.completion.goodQuantity} good · {batch.completion.rejectedQuantity} rejected{batch.completion.rejectionReason && ` · ${batch.completion.rejectionReason}`}
}
+ {batch.cancellation && Cancelled {new Date(batch.cancellation.createdAt).toLocaleString()} · {batch.cancellation.reason}
}
+ Planned materials
+ line.id)}
+ rows={batch.plannedMaterials.map((line) => [line.materialName, line.materialCode, line.unit, line.plannedQuantity])} />
+ {can("production.manage") && batch.status === "DRAFT" && (
+ transition("start")} />
+ )}
+
+
+ {can("production.manage") && batch.status === "IN_PROGRESS" && (
+
+ Record all material usage before completing production. Completion closes the batch to new usage entries.
+ parseCompletion({
+ goodQuantity: readNumber(form, "goodQuantity"),
+ rejectedQuantity: readNumber(form, "rejectedQuantity"),
+ rejectionReason: readText(form, "rejectionReason").trim() || undefined,
+ }, batch.plannedQuantity)} submit={(body) => transition("complete", body)}>
+
+
+
+
+
+ )}
+ {can("production.manage") && (batch.status === "DRAFT" || batch.status === "IN_PROGRESS") && (
+
+ cancelBatchInput.parse({ reason: readText(form, "reason") })}
+ submit={(body) => transition("cancel", body)}>
+
+
+
+ )}
+ >}
+ >;
+}
+
+export default function ProductionBatchesPage({ batchId, create = false, bomId }: {
+ batchId?: string;
+ create?: boolean;
+ bomId?: string;
+}) {
+ const parsedBatch = uuid.safeParse(batchId);
+ const parsedBom = uuid.safeParse(bomId);
+ return
+ {create ? : batchId ? (
+ parsedBatch.success ? : Invalid batch ID.
+ ) : }
+ ;
+}
+
+function CreateRoute({ bomId, parsedBom }: { bomId?: string; parsedBom?: string }) {
+ const { can } = usePlatform();
+ if (!can("production.manage")) return Your account does not have permission to plan production.;
+ if (bomId && !parsedBom) return Invalid production BOM ID.;
+ return ;
+}
diff --git a/test/production.test.ts b/test/production.test.ts
new file mode 100644
index 0000000..c9edee6
--- /dev/null
+++ b/test/production.test.ts
@@ -0,0 +1,27 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { batchInput, parseCompletion, usageInput } from "../src/lib/production.ts";
+
+const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
+
+test("batch plans normalize references and reject invalid quantity and schedule", () => {
+ const plan = { bomId: id, reference: " batch-20 ", plannedQuantity: 20, scheduledDate: "2026-11-12" };
+ assert.deepEqual(batchInput.parse(plan), { ...plan, reference: "BATCH-20" });
+ assert.equal(batchInput.safeParse({ ...plan, plannedQuantity: 1.25 }).success, false);
+ assert.equal(batchInput.safeParse({ ...plan, scheduledDate: "2026-02-30" }).success, false);
+});
+
+test("completion reconciles good and rejected pieces and requires a rejection reason", () => {
+ const completion = { goodQuantity: 18, rejectedQuantity: 2, rejectionReason: " Surface defects " };
+ assert.equal(parseCompletion(completion, 20).rejectionReason, "Surface defects");
+ assert.throws(() => parseCompletion(completion, 21), /must total 21 pieces/);
+ assert.throws(() => parseCompletion({ ...completion, rejectionReason: undefined }, 20), /reason/);
+});
+
+test("material usage preserves exact positive quantities and requires a waste reason", () => {
+ const event = { bomLineId: id, idempotencyKey: id, kind: "WASTED", quantity: "0.125", reason: " Spill " };
+ assert.deepEqual(usageInput.parse(event), { ...event, reason: "Spill" });
+ assert.equal(usageInput.safeParse({ ...event, reason: undefined }).success, false);
+ assert.equal(usageInput.safeParse({ ...event, quantity: "0.000" }).success, false);
+ assert.equal(usageInput.safeParse({ ...event, quantity: "0.12" }).success, false);
+});
diff --git a/test/workflows.ui.test.tsx b/test/workflows.ui.test.tsx
index dbe9264..b8f20a9 100644
--- a/test/workflows.ui.test.tsx
+++ b/test/workflows.ui.test.tsx
@@ -16,6 +16,7 @@ import { ReceiptStockPosting } from "../src/pages/ReceiptStockPosting";
import { PurchaseOrderInvoices } from "../src/pages/PurchaseOrderInvoices";
import SupplierDocumentsPage from "../src/pages/SupplierDocumentsPage";
import BomPage from "../src/pages/BomPage";
+import ProductionBatchesPage from "../src/pages/ProductionBatchesPage";
import theme from "../src/theme";
import { Switch, Route } from "wouter";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
@@ -178,6 +179,74 @@ function harness(children: ReactNode) {
return { client, ...result };
}
+test("a production batch starts, safely retries usage and completes with reconciled output", async () => {
+ const date = "2026-11-12T00:00:00.000Z";
+ let status = "DRAFT";
+ let completion: unknown = null;
+ const attempts: unknown[] = [];
+ const plannedMaterial = { id, materialName: "Wax", materialCode: "WAX", unit: "GRAM", quantity: "100", plannedQuantity: "200.000" };
+ const event = { id, bomLineId: id, kind: "WASTED", quantity: "0.125", reason: "Spill", createdAt: date };
+ const batch = () => ({
+ id, reference: "BATCH-20", plannedQuantity: 20, status, scheduledDate: null,
+ startedAt: status === "DRAFT" ? null : date,
+ bom: { id, variantId: id, kind: "PRODUCTION", revision: 2, status: "ACTIVE", outputQuantity: 10, activatedAt: date },
+ plannedMaterials: [plannedMaterial], completion, cancellation: null,
+ });
+ vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
+ if (url.endsWith("/auth/login")) return json(session);
+ if (url.endsWith("/auth/me")) return json({
+ ...me, permissions: ["production.read", "production.manage", "production.material.record"],
+ });
+ if (url.endsWith(`/production-batches/${id}`)) return json(batch());
+ if (url.endsWith("/start") && options?.method === "POST") {
+ status = "IN_PROGRESS";
+ return json(batch());
+ }
+ if (url.endsWith("/material-usage") && options?.method === "POST") {
+ attempts.push(JSON.parse(String(options.body)));
+ if (attempts.length === 1) throw new Error("Response lost");
+ return json(event);
+ }
+ if (url.includes("/material-usage?")) return json({
+ total: attempts.length ? 1 : 0,
+ events: attempts.length ? [event] : [],
+ materials: [{
+ ...plannedMaterial, bomLineId: id, consumedQuantity: "0.000",
+ wastedQuantity: attempts.length ? "0.125" : "0.000", varianceQuantity: attempts.length ? "199.875" : "200.000",
+ }],
+ });
+ if (url.endsWith("/complete") && options?.method === "POST") {
+ const body = JSON.parse(String(options.body));
+ completion = { ...body, createdAt: date };
+ status = "COMPLETED";
+ return json(batch());
+ }
+ throw new Error(`Unexpected request ${url}`);
+ }));
+ harness();
+ const user = userEvent.setup();
+ await user.click(screen.getByText("Test login"));
+ await user.click(await screen.findByRole("button", { name: "Start batch" }));
+ await user.click(screen.getByRole("button", { name: "Confirm" }));
+ await user.selectOptions(await screen.findByRole("combobox", { name: /Usage type/ }), "WASTED");
+ await user.type(screen.getByRole("textbox", { name: /Actual quantity/ }), "0.125");
+ await user.type(screen.getByRole("textbox", { name: /Usage reason/ }), "Spill");
+ await user.click(screen.getByRole("button", { name: "Record material usage" }));
+ await user.click(await screen.findByRole("button", { name: "Retry material usage" }));
+ await screen.findByRole("cell", { name: "199.875" });
+ expect(attempts).toHaveLength(2);
+ expect(attempts[0]).toEqual({ bomLineId: id, kind: "WASTED", quantity: "0.125", reason: "Spill", idempotencyKey: expect.any(String) });
+ expect(attempts[1]).toEqual(attempts[0]);
+ await user.type(screen.getByRole("spinbutton", { name: /Good pieces/ }), "18");
+ const rejected = screen.getByRole("spinbutton", { name: /Rejected pieces/ });
+ await user.clear(rejected);
+ await user.type(rejected, "2");
+ await user.type(screen.getByRole("textbox", { name: /Rejection reason/ }), "Surface defects");
+ await user.click(screen.getByRole("button", { name: "Complete batch" }));
+ await screen.findByText(/18 good · 2 rejected · Surface defects/);
+ expect(screen.queryByRole("button", { name: "Record material usage" })).toBeNull();
+});
+
test("packaging staff draft and activate an independent BOM with eligible materials", async () => {
const draftId = "d66c798a-f764-4b88-8d13-ace328ff1011";
const draft = {