diff --git a/docs/PHASES.md b/docs/PHASES.md index 9008e1b..921edcc 100644 --- a/docs/PHASES.md +++ b/docs/PHASES.md @@ -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. - 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 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. - 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. diff --git a/src/App.tsx b/src/App.tsx index 09fc78d..f445eb4 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -31,6 +31,7 @@ const InventoryPage = lazy(() => import("@/pages/InventoryPage")); const MaterialStockPage = lazy(() => import("@/pages/MaterialStockPage")); const ProcurementPage = lazy(() => import("@/pages/ProcurementPage")); const BomPage = lazy(() => import("@/pages/BomPage")); +const ProductionBatchesPage = lazy(() => import("@/pages/ProductionBatchesPage")); const SupplierDocumentsPage = lazy(() => import("@/pages/SupplierDocumentsPage")); const PurchaseOrdersPage = lazy(() => import("@/pages/ProcurementPage").then((module) => ({ default: module.PurchaseOrdersPage })), @@ -95,6 +96,14 @@ function Router() { {(params) => } + {() => } + {() => } + + {(params) => } + + + {(params) => } + {() => } {(params) => } diff --git a/src/components/WorkspaceShell.tsx b/src/components/WorkspaceShell.tsx index fca3129..b5b1c08 100644 --- a/src/components/WorkspaceShell.tsx +++ b/src/components/WorkspaceShell.tsx @@ -64,6 +64,7 @@ export function WorkspaceNavigation() { { label: "Purchase orders", path: "/admin/purchase-orders", permission: "procurement.read" }, { label: "Material stock", path: "/admin/material-stock", permission: "inventory.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: "Pricing", path: "/admin/pricing", permission: "pricing.manage" }, { label: "All orders", path: "/admin/orders", permission: "orders.read" }, diff --git a/src/lib/production.ts b/src/lib/production.ts new file mode 100644 index 0000000..89b1cc0 --- /dev/null +++ b/src/lib/production.ts @@ -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}$/), + })), +}); diff --git a/src/pages/BatchMaterialUsage.tsx b/src/pages/BatchMaterialUsage.tsx new file mode 100644 index 0000000..fcc26ff --- /dev/null +++ b/src/pages/BatchMaterialUsage.tsx @@ -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 }) { + 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 + {(data) => <> + line.bomLineId)} rows={data.materials.map((line) => [ + `${line.materialName} (${line.materialCode}) · ${line.unit}`, line.plannedQuantity, + line.consumedQuantity, line.wastedQuantity, line.varianceQuantity, + ])} /> +

Usage history

+
event.id)} rows={data.events.map((event) => [ + new Date(event.createdAt).toLocaleString(), labels.get(event.bomLineId) ?? event.bomLineId, + event.kind, event.quantity, event.reason ?? "—", + ])} /> + + {can("production.material.record") && (pending || (batch.status === "IN_PROGRESS" && data.total < 500)) && ( + 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 ? ( + The server may have saved this entry. Retrying reuses {pending.quantity} for {labels.get(pending.bomLineId) ?? pending.bomLineId} as {pending.kind.toLowerCase()}. + ) : <> + ({ value, label }))} /> + + + + } + + )} + {batch.status === "IN_PROGRESS" && data.total === 500 && This batch has reached the 500-event limit.} + } + ; +} diff --git a/src/pages/BomPage.tsx b/src/pages/BomPage.tsx index c7a2aac..c98852f 100644 --- a/src/pages/BomPage.tsx +++ b/src/pages/BomPage.tsx @@ -104,6 +104,9 @@ function RevisionDetail({ config, id, refreshList }: {
line.id)} 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") && ( + Plan a batch from revision {revision.revision} + )} {can(config.manage) && revision.status === "DRAFT" && ( + {can("production.manage") &&

Plan a production batch

} + { setStatus(value); setOffset(0); }} + options={[{ value: "ALL", label: "All statuses" }, ...batchStatus.options.map((value) => ({ value, label: value.replaceAll("_", " ") }))]} /> + {(rows) => <> +
row.id)} + rows={rows.map((row) => [ + {row.reference}, + row.status.replaceAll("_", " "), row.plannedQuantity, row.scheduledDate?.slice(0, 10) ?? "—", + ])} /> + + } + ; +} + +function PlanBatch({ bomId }: { bomId?: string }) { + const { can, request } = usePlatform(); + const [, navigate] = useLocation(); + const [uncertain, setUncertain] = useState(false); + return + All production batches + {can("bom.read") &&

Browse production BOM revisions

} + {uncertain ? The server may have created the batch. Check batch history for its reference before submitting again. : + 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 ?

Production BOM ID {bomId}

: + } + + + +
} +
; +} + +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 <> + All production batches + {(batch) => <> + +

{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 = {