feat: manage production batches and material usage #16

Merged
mihir merged 1 commits from feat/production-batches into main 2026-11-14 00:00:41 +05:30
9 changed files with 414 additions and 1 deletions

View File

@ -36,7 +36,8 @@ Customer and administration screens are implemented, with recovery, pricing, sto
- Issued orders support supplier invoices, payment records, reversals and voids. The backend enforces accepted quantities, outstanding balances and correction rules. - Issued orders support supplier invoices, payment records, reversals and voids. The backend enforces accepted quantities, outstanding balances and correction rules.
- Private supplier PDFs support version uploads, independent review decisions, and authenticated downloads. - Private supplier PDFs support version uploads, independent review decisions, and authenticated downloads.
- Production and packaging BOMs support separate revision histories, draft creation, material snapshots and confirmed activation. - Production and packaging BOMs support separate revision histories, draft creation, material snapshots and confirmed activation.
- Production batches, material usage, packaging runs, costing, warehouse transfers and adjustments remain open. - Production batches support draft planning, start, completion, cancellation, and exact planned material quantities. Staff can log consumption and waste and reconcile the results against the plan.
- Production stock posting, finished-goods receipts, packaging runs, costing, warehouse transfers and adjustments remain open.
- Live acceptance requires an organization and procurement test users. Exercise read-only and manage roles, inactive suppliers and materials, mixed currencies, below-minimum quantities, price snapshots and purchase order state conflicts. - Live acceptance requires an organization and procurement test users. Exercise read-only and manage roles, inactive suppliers and materials, mixed currencies, below-minimum quantities, price snapshots and purchase order state conflicts.
- Supplier document UAT requires an uploader, an independent reviewer, and a read-only account. Through the deployed ingress, upload a valid PDF near the 2 MiB limit, verify that the uploader cannot decide on it, and check that a reader can download it only after approval. - Supplier document UAT requires an uploader, an independent reviewer, and a read-only account. Through the deployed ingress, upload a valid PDF near the 2 MiB limit, verify that the uploader cannot decide on it, and check that a reader can download it only after approval.
- BOM UAT should activate a second revision and confirm the previous revision becomes superseded. Repeat for the other BOM type and verify its active revision is independent. Check that inactive materials and stale drafts are rejected. - BOM UAT should activate a second revision and confirm the previous revision becomes superseded. Repeat for the other BOM type and verify its active revision is independent. Check that inactive materials and stale drafts are rejected.

View File

@ -31,6 +31,7 @@ const InventoryPage = lazy(() => import("@/pages/InventoryPage"));
const MaterialStockPage = lazy(() => import("@/pages/MaterialStockPage")); const MaterialStockPage = lazy(() => import("@/pages/MaterialStockPage"));
const ProcurementPage = lazy(() => import("@/pages/ProcurementPage")); const ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
const BomPage = lazy(() => import("@/pages/BomPage")); const BomPage = lazy(() => import("@/pages/BomPage"));
const ProductionBatchesPage = lazy(() => import("@/pages/ProductionBatchesPage"));
const SupplierDocumentsPage = lazy(() => import("@/pages/SupplierDocumentsPage")); const SupplierDocumentsPage = lazy(() => import("@/pages/SupplierDocumentsPage"));
const PurchaseOrdersPage = lazy(() => const PurchaseOrdersPage = lazy(() =>
import("@/pages/ProcurementPage").then((module) => ({ default: module.PurchaseOrdersPage })), import("@/pages/ProcurementPage").then((module) => ({ default: module.PurchaseOrdersPage })),
@ -95,6 +96,14 @@ function Router() {
<Route path="/admin/packaging-boms/:id"> <Route path="/admin/packaging-boms/:id">
{(params) => <BomPage packaging variantId={params.id} />} {(params) => <BomPage packaging variantId={params.id} />}
</Route> </Route>
<Route path="/admin/production-batches">{() => <ProductionBatchesPage />}</Route>
<Route path="/admin/production-batches/new">{() => <ProductionBatchesPage create />}</Route>
<Route path="/admin/production-batches/new/:bomId">
{(params) => <ProductionBatchesPage create bomId={params.bomId} />}
</Route>
<Route path="/admin/production-batches/:id">
{(params) => <ProductionBatchesPage batchId={params.id} />}
</Route>
<Route path="/admin/purchase-orders">{() => <PurchaseOrdersPage />}</Route> <Route path="/admin/purchase-orders">{() => <PurchaseOrdersPage />}</Route>
<Route path="/admin/purchase-orders/:id"> <Route path="/admin/purchase-orders/:id">
{(params) => <PurchaseOrdersPage orderId={params.id} />} {(params) => <PurchaseOrdersPage orderId={params.id} />}

View File

@ -64,6 +64,7 @@ export function WorkspaceNavigation() {
{ label: "Purchase orders", path: "/admin/purchase-orders", permission: "procurement.read" }, { label: "Purchase orders", path: "/admin/purchase-orders", permission: "procurement.read" },
{ label: "Material stock", path: "/admin/material-stock", permission: "inventory.read" }, { label: "Material stock", path: "/admin/material-stock", permission: "inventory.read" },
{ label: "Production BOMs", path: "/admin/boms", permission: "bom.read" }, { label: "Production BOMs", path: "/admin/boms", permission: "bom.read" },
{ label: "Production batches", path: "/admin/production-batches", permission: "production.read" },
{ label: "Packaging BOMs", path: "/admin/packaging-boms", permission: "packaging.read" }, { label: "Packaging BOMs", path: "/admin/packaging-boms", permission: "packaging.read" },
{ label: "Pricing", path: "/admin/pricing", permission: "pricing.manage" }, { label: "Pricing", path: "/admin/pricing", permission: "pricing.manage" },
{ label: "All orders", path: "/admin/orders", permission: "orders.read" }, { label: "All orders", path: "/admin/orders", permission: "orders.read" },

94
src/lib/production.ts Normal file
View File

@ -0,0 +1,94 @@
import { z } from "zod";
import { bomDetail, bomSummary } from "./bom.ts";
import { uuid } from "./commerce.ts";
const reason = z.string().trim().min(1).max(500);
const output = z.number().int().min(0).max(100000);
const decimal = z.string().regex(/^\d+(\.\d{1,3})?$/);
const exactTotal = z.string().regex(/^\d+\.\d{3}$/);
const materialLine = bomDetail.shape.lines.element;
export const batchStatus = z.enum(["DRAFT", "IN_PROGRESS", "COMPLETED", "CANCELLED"]);
export const batchInput = z.object({
bomId: uuid,
reference: z.string().trim().toUpperCase().max(32).regex(/^[A-Z0-9][A-Z0-9_-]*$/),
plannedQuantity: output.min(1),
scheduledDate: z.string().date().optional(),
}).strict();
export const cancelBatchInput = z.object({ reason }).strict();
const completeBatchInput = z.object({
goodQuantity: output,
rejectedQuantity: output,
rejectionReason: reason.optional(),
}).strict().refine((value) => value.rejectedQuantity === 0 || Boolean(value.rejectionReason), {
path: ["rejectionReason"],
message: "Enter a reason for the rejected pieces.",
});
export function parseCompletion(input: unknown, plannedQuantity: number) {
const value = completeBatchInput.parse(input);
if (value.goodQuantity + value.rejectedQuantity !== plannedQuantity) {
throw new Error(`Good and rejected quantities must total ${plannedQuantity} pieces.`);
}
return value;
}
export const productionBatch = z.object({
id: uuid,
reference: z.string(),
plannedQuantity: batchInput.shape.plannedQuantity,
status: batchStatus,
scheduledDate: z.string().datetime().nullable(),
startedAt: z.string().datetime().nullable(),
});
export const batchDetail = productionBatch.extend({
bom: bomSummary,
plannedMaterials: z.array(materialLine.extend({ plannedQuantity: exactTotal })),
completion: z.object({
goodQuantity: output,
rejectedQuantity: output,
rejectionReason: z.string().nullable(),
createdAt: z.string().datetime(),
}).nullable(),
cancellation: z.object({
reason,
createdAt: z.string().datetime(),
}).nullable(),
});
export const usageKind = z.enum(["CONSUMED", "WASTED"]);
export const usageInput = z.object({
bomLineId: uuid,
kind: usageKind,
quantity: z.string().regex(/^(0|[1-9]\d{0,8})\.\d{3}$/, "Use three decimal places")
.refine((value) => value !== "0.000", "Quantity must be positive"),
reason: reason.optional(),
idempotencyKey: uuid,
}).strict().refine((value) => value.kind !== "WASTED" || Boolean(value.reason), {
path: ["reason"],
message: "Enter a reason for the wasted material.",
});
export const usageEvent = z.object({
id: uuid,
bomLineId: uuid,
kind: usageKind,
quantity: decimal,
reason: z.string().nullable(),
createdAt: z.string().datetime(),
});
export const batchUsage = z.object({
total: z.number().int().min(0).max(500),
events: z.array(usageEvent),
materials: z.array(z.object({
bomLineId: uuid,
materialName: z.string(),
materialCode: z.string(),
unit: materialLine.shape.unit,
plannedQuantity: exactTotal,
consumedQuantity: exactTotal,
wastedQuantity: exactTotal,
varianceQuantity: z.string().regex(/^-?\d+\.\d{3}$/),
})),
});

View File

@ -0,0 +1,60 @@
import { useState } from "react";
import { z } from "zod";
import Alert from "@mui/material/Alert";
import { ActionForm, Field, Pager, Panel, QueryView, Table, readText, usePrivateQuery } from "@/components/WorkspaceTools";
import { usePlatform } from "@/lib/platform";
import { batchDetail, batchUsage, usageEvent, usageInput } from "@/lib/production";
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
export function BatchMaterialUsage({ batch }: { batch: z.infer<typeof batchDetail> }) {
const { can } = usePlatform();
const [offset, setOffset] = useState(0);
const path = `/production-batches/${batch.id}/material-usage`;
const query = usePrivateQuery(`${path}?limit=25&offset=${offset}`, batchUsage);
const command = useIdempotentCommand(path, usageInput, usageEvent, batch.id);
const labels = new Map(batch.plannedMaterials.map((line) => [line.id, `${line.materialName} (${line.materialCode}) · ${line.unit}`]));
const pending = command.pending;
return <Panel title="Material usage">
<QueryView query={query}>{(data) => <>
<Table head={["Material", "Planned", "Consumed", "Wasted", "Variance"]}
rowKeys={data.materials.map((line) => line.bomLineId)} rows={data.materials.map((line) => [
`${line.materialName} (${line.materialCode}) · ${line.unit}`, line.plannedQuantity,
line.consumedQuantity, line.wastedQuantity, line.varianceQuantity,
])} />
<h3>Usage history</h3>
<Table head={["Time", "Material", "Event", "Quantity", "Reason"]}
rowKeys={data.events.map((event) => event.id)} rows={data.events.map((event) => [
new Date(event.createdAt).toLocaleString(), labels.get(event.bomLineId) ?? event.bomLineId,
event.kind, event.quantity, event.reason ?? "—",
])} />
<Pager offset={offset} count={offset + data.events.length < data.total ? 25 : 0} onPage={setOffset} />
{can("production.material.record") && (pending || (batch.status === "IN_PROGRESS" && data.total < 500)) && (
<ActionForm key={pending ? "retry" : "record"} label={pending ? "Retry material usage" : "Record material usage"}
read={(form) => pending ? {} : ({
bomLineId: readText(form, "bomLineId"),
kind: readText(form, "kind"),
quantity: readText(form, "quantity").trim(),
reason: readText(form, "reason").trim() || undefined,
})}
submit={async (input) => {
await command.run(input);
const result = await query.refetch();
if (result.data) setOffset(Math.floor(Math.max(0, result.data.total - 1) / 25) * 25);
}}>
{pending ? (
<Alert severity="warning">The server may have saved this entry. Retrying reuses {pending.quantity} for {labels.get(pending.bomLineId) ?? pending.bomLineId} as {pending.kind.toLowerCase()}.</Alert>
) : <>
<Field name="bomLineId" label="Material" value={batch.plannedMaterials[0]?.id}
options={[...labels].map(([value, label]) => ({ value, label }))} />
<Field name="kind" label="Usage type" value="CONSUMED"
options={[{ value: "CONSUMED", label: "Consumed" }, { value: "WASTED", label: "Wasted" }]} />
<Field name="quantity" label="Actual quantity" maxLength={13} helper="Use three decimal places in the material’s unit." />
<Field name="reason" label="Usage reason" required={false} maxLength={500} helper="Required for waste." />
</>}
</ActionForm>
)}
{batch.status === "IN_PROGRESS" && data.total === 500 && <Alert severity="info">This batch has reached the 500-event limit.</Alert>}
</>}</QueryView>
</Panel>;
}

View File

@ -104,6 +104,9 @@ function RevisionDetail({ config, id, refreshList }: {
<Table head={["Material", "Code", "Unit", "Quantity for this yield"]} <Table head={["Material", "Code", "Unit", "Quantity for this yield"]}
rowKeys={revision.lines.map((line) => line.id)} rowKeys={revision.lines.map((line) => line.id)}
rows={revision.lines.map((line) => [line.materialName, line.materialCode, line.unit, line.quantity])} /> rows={revision.lines.map((line) => [line.materialName, line.materialCode, line.unit, line.quantity])} />
{config.kind === "PRODUCTION" && revision.status === "ACTIVE" && can("production.read") && can("production.manage") && (
<WorkspaceLink href={`/admin/production-batches/new/${revision.id}`}>Plan a batch from revision {revision.revision}</WorkspaceLink>
)}
{can(config.manage) && revision.status === "DRAFT" && ( {can(config.manage) && revision.status === "DRAFT" && (
<ConfirmAction label={`Activate revision ${revision.revision}`} <ConfirmAction label={`Activate revision ${revision.revision}`}
message="Activation supersedes the current active revision of this type for this variant." message="Activation supersedes the current active revision of this type for this variant."

View File

@ -0,0 +1,149 @@
import { useRef, useState } from "react";
import { useLocation } from "wouter";
import { z } from "zod";
import Alert from "@mui/material/Alert";
import { ConfirmAction } from "@/components/ConfirmAction";
import { WorkspaceShell } from "@/components/WorkspaceShell";
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readNumber, readText, usePrivateQuery } from "@/components/WorkspaceTools";
import { uuid } from "@/lib/commerce";
import { isUnknownOutcome } from "@/lib/api";
import { usePlatform } from "@/lib/platform";
import { batchDetail, batchInput, batchStatus, cancelBatchInput, parseCompletion, productionBatch } from "@/lib/production";
import { BatchMaterialUsage } from "./BatchMaterialUsage";
const route = "/admin/production-batches";
const api = "/production-batches";
function BatchList() {
const { can } = usePlatform();
const [offset, setOffset] = useState(0);
const [status, setStatus] = useState("ALL");
const query = usePrivateQuery(
`${api}?limit=25&offset=${offset}${status === "ALL" ? "" : `&status=${status}`}`,
z.array(productionBatch),
);
return <Panel title="Batch history">
{can("production.manage") && <p><WorkspaceLink href={`${route}/new`}>Plan a production batch</WorkspaceLink></p>}
<Field name="status" label="Batch status" value={status} onChange={(value) => { setStatus(value); setOffset(0); }}
options={[{ value: "ALL", label: "All statuses" }, ...batchStatus.options.map((value) => ({ value, label: value.replaceAll("_", " ") }))]} />
<QueryView query={query}>{(rows) => <>
<Table head={["Reference", "Status", "Planned pieces", "Scheduled date"]} rowKeys={rows.map((row) => row.id)}
rows={rows.map((row) => [
<WorkspaceLink href={`${route}/${row.id}`}>{row.reference}</WorkspaceLink>,
row.status.replaceAll("_", " "), row.plannedQuantity, row.scheduledDate?.slice(0, 10) ?? "—",
])} />
<Pager offset={offset} count={rows.length} onPage={setOffset} />
</>}</QueryView>
</Panel>;
}
function PlanBatch({ bomId }: { bomId?: string }) {
const { can, request } = usePlatform();
const [, navigate] = useLocation();
const [uncertain, setUncertain] = useState(false);
return <Panel title="Plan a production batch">
<WorkspaceLink href={route}>All production batches</WorkspaceLink>
{can("bom.read") && <p><WorkspaceLink href="/admin/boms">Browse production BOM revisions</WorkspaceLink></p>}
{uncertain ? <Alert severity="warning">The server may have created the batch. Check batch history for its reference before submitting again.</Alert> :
<ActionForm label="Create production batch" reset={false} read={(form) => batchInput.parse({
bomId: bomId ?? readText(form, "bomId").trim(),
reference: readText(form, "reference"),
plannedQuantity: readNumber(form, "plannedQuantity"),
scheduledDate: readText(form, "scheduledDate") || undefined,
})} submit={async (body) => {
try {
const saved = await request(api, batchDetail, { method: "POST", body });
navigate(`${route}/${saved.id}`);
} catch (error) {
if (isUnknownOutcome(error)) setUncertain(true);
throw error;
}
}}>
{bomId ? <p className="workspace-id">Production BOM ID {bomId}</p> :
<Field name="bomId" label="Active production BOM ID" maxLength={36} />}
<Field name="reference" label="Batch reference" maxLength={32} />
<Field name="plannedQuantity" label="Planned pieces" type="number" helper="Enter a multiple of the active BOM’s yield." />
<Field name="scheduledDate" label="Scheduled date (YYYY-MM-DD)" maxLength={10} required={false} />
</ActionForm>}
</Panel>;
}
function BatchDetails({ id }: { id: string }) {
const { can, request } = usePlatform();
const path = `${api}/${id}`;
const query = usePrivateQuery(path, batchDetail);
const running = useRef(false);
async function transition(action: "start" | "complete" | "cancel", body?: unknown) {
if (running.current) throw new Error("A batch update is already in progress.");
running.current = true;
try {
await request(`${path}/${action}`, batchDetail, { method: "POST", body });
} finally {
await query.refetch();
running.current = false;
}
}
return <>
<WorkspaceLink href={route}>All production batches</WorkspaceLink>
<QueryView query={query}>{(batch) => <>
<Panel title={batch.reference}>
<p>{batch.status.replaceAll("_", " ")} · Planned {batch.plannedQuantity} pieces</p>
<p>BOM revision {batch.bom.revision} · {batch.bom.outputQuantity} pieces per yield</p>
{batch.scheduledDate && <p>Scheduled for {batch.scheduledDate.slice(0, 10)}</p>}
{batch.startedAt && <p>Started {new Date(batch.startedAt).toLocaleString()}</p>}
{batch.completion && <p>Completed {new Date(batch.completion.createdAt).toLocaleString()} · {batch.completion.goodQuantity} good · {batch.completion.rejectedQuantity} rejected{batch.completion.rejectionReason && ` · ${batch.completion.rejectionReason}`}</p>}
{batch.cancellation && <p>Cancelled {new Date(batch.cancellation.createdAt).toLocaleString()} · {batch.cancellation.reason}</p>}
<h3>Planned materials</h3>
<Table head={["Material", "Code", "Unit", "Planned quantity"]} rowKeys={batch.plannedMaterials.map((line) => line.id)}
rows={batch.plannedMaterials.map((line) => [line.materialName, line.materialCode, line.unit, line.plannedQuantity])} />
{can("production.manage") && batch.status === "DRAFT" && (
<ConfirmAction label="Start batch" message={`Start production for ${batch.reference}?`} onConfirm={() => transition("start")} />
)}
</Panel>
<BatchMaterialUsage batch={batch} />
{can("production.manage") && batch.status === "IN_PROGRESS" && (
<Panel title="Record batch output">
<p>Record all material usage before completing production. Completion closes the batch to new usage entries.</p>
<ActionForm label="Complete batch" read={(form) => parseCompletion({
goodQuantity: readNumber(form, "goodQuantity"),
rejectedQuantity: readNumber(form, "rejectedQuantity"),
rejectionReason: readText(form, "rejectionReason").trim() || undefined,
}, batch.plannedQuantity)} submit={(body) => transition("complete", body)}>
<Field name="goodQuantity" label="Good pieces" type="number" />
<Field name="rejectedQuantity" label="Rejected pieces" type="number" value={0} />
<Field name="rejectionReason" label="Rejection reason" required={false} maxLength={500} />
</ActionForm>
</Panel>
)}
{can("production.manage") && (batch.status === "DRAFT" || batch.status === "IN_PROGRESS") && (
<Panel title="Cancel production">
<ActionForm label="Cancel batch" read={(form) => cancelBatchInput.parse({ reason: readText(form, "reason") })}
submit={(body) => transition("cancel", body)}>
<Field name="reason" label="Cancellation reason" maxLength={500} />
</ActionForm>
</Panel>
)}
</>}</QueryView>
</>;
}
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 <WorkspaceShell title="Production Batches" permission="production.read">
{create ? <CreateRoute bomId={bomId} parsedBom={parsedBom.success ? parsedBom.data : undefined} /> : batchId ? (
parsedBatch.success ? <BatchDetails key={parsedBatch.data} id={parsedBatch.data} /> : <Alert severity="warning">Invalid batch ID.</Alert>
) : <BatchList />}
</WorkspaceShell>;
}
function CreateRoute({ bomId, parsedBom }: { bomId?: string; parsedBom?: string }) {
const { can } = usePlatform();
if (!can("production.manage")) return <Alert severity="warning">Your account does not have permission to plan production.</Alert>;
if (bomId && !parsedBom) return <Alert severity="warning">Invalid production BOM ID.</Alert>;
return <PlanBatch key={parsedBom ?? "new"} bomId={parsedBom} />;
}

27
test/production.test.ts Normal file
View File

@ -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);
});

View File

@ -16,6 +16,7 @@ import { ReceiptStockPosting } from "../src/pages/ReceiptStockPosting";
import { PurchaseOrderInvoices } from "../src/pages/PurchaseOrderInvoices"; import { PurchaseOrderInvoices } from "../src/pages/PurchaseOrderInvoices";
import SupplierDocumentsPage from "../src/pages/SupplierDocumentsPage"; import SupplierDocumentsPage from "../src/pages/SupplierDocumentsPage";
import BomPage from "../src/pages/BomPage"; import BomPage from "../src/pages/BomPage";
import ProductionBatchesPage from "../src/pages/ProductionBatchesPage";
import theme from "../src/theme"; import theme from "../src/theme";
import { Switch, Route } from "wouter"; import { Switch, Route } from "wouter";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010"; const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
@ -178,6 +179,74 @@ function harness(children: ReactNode) {
return { client, ...result }; 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(<ProductionBatchesPage batchId={id} />);
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 () => { test("packaging staff draft and activate an independent BOM with eligible materials", async () => {
const draftId = "d66c798a-f764-4b88-8d13-ace328ff1011"; const draftId = "d66c798a-f764-4b88-8d13-ace328ff1011";
const draft = { const draft = {