Merge pull request 'feat: post batch materials and receive finished goods' (#17) from feat/production-stock into main
continuous-integration/drone/push Build is failing Details

Reviewed-on: #17
This commit is contained in:
Mihir Motiyani 2026-11-14 00:13:30 +05:30
commit 16dfcf0235
11 changed files with 440 additions and 44 deletions

View File

@ -37,7 +37,8 @@ Customer and administration screens are implemented, with recovery, pricing, sto
- 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 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.
- Completed batches support packaging runs, production and packaging material debits, and receipt of good finished pieces into warehouse stock.
- 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.

View File

@ -0,0 +1,29 @@
import { useState } from "react";
import Alert from "@mui/material/Alert";
import { z } from "zod";
import { ActionForm, Field, Pager, QueryView, readText, usePrivateQuery } from "@/components/WorkspaceTools";
import { warehouse } from "@/lib/commerce";
export function WarehousePostingForm({ label, instruction, warehouseLabel = "Warehouse", submit }: {
label: string;
instruction: string;
warehouseLabel?: string;
submit: (input: unknown) => Promise<void>;
}) {
const [offset, setOffset] = useState(0);
const query = usePrivateQuery(`/inventory/warehouses?limit=25&offset=${offset}`, z.array(warehouse));
return <QueryView query={query}>{(rows) => <>
{rows.length ? <ActionForm key={offset} label={label} reset={false}
read={(data) => ({ warehouseId: readText(data, "warehouseId") })} submit={submit}>
<p>{instruction}</p>
<Field name="warehouseId" label={warehouseLabel} options={[
{ value: "", label: "Choose a warehouse" },
...rows.map((row) => ({ value: row.id, label: row.name })),
]} />
<Pager offset={offset} count={rows.length} onPage={setOffset} />
</ActionForm> : <>
<Alert severity="info">No warehouses on this page.</Alert>
{offset > 0 && <Pager offset={offset} count={0} onPage={setOffset} />}
</>}
</>}</QueryView>;
}

View File

@ -0,0 +1,21 @@
import { useQuery } from "@tanstack/react-query";
import { z } from "zod";
import { ApiError } from "@/lib/api";
import { usePlatform } from "@/lib/platform";
export function useOptionalPrivateQuery<T>(path: string, schema: z.ZodType<T>, missingCode: string) {
const { request, scope } = usePlatform();
return useQuery({
queryKey: ["private", scope, path],
enabled: Boolean(scope),
retry: false,
queryFn: async ({ signal }) => {
try {
return await request(path, schema, { signal });
} catch (error) {
if (error instanceof ApiError && error.status === 404 && error.code === missingCode) return null;
throw error;
}
},
});
}

View File

@ -29,6 +29,7 @@ export const bomSummary = z.object({
export const bomDetail = bomSummary.extend({
lines: z.array(z.object({
id: uuid,
materialId: uuid,
materialName: z.string(),
materialCode: z.string(),
unit: materialInput.shape.unit,

View File

@ -0,0 +1,64 @@
import { z } from "zod";
import { uuid } from "./commerce.ts";
import { bomDetail } from "./bom.ts";
const quantity = z.string().regex(/^(0|[1-9]\d{0,8})\.\d{3}$/, "Use three decimal places");
const signedQuantity = z.string().regex(/^-?\d+\.\d{3}$/);
const packagingLine = z.object({
bomLineId: uuid,
usedQuantity: quantity,
wastedQuantity: quantity,
wasteReason: z.string().trim().min(1).max(500).optional(),
}).strict().refine((line) => line.wastedQuantity === "0.000" || Boolean(line.wasteReason), {
path: ["wasteReason"],
message: "Enter a reason for wasted material.",
});
export const packagingRunInput = z.object({
bomId: uuid,
idempotencyKey: uuid,
lines: z.array(packagingLine).min(1).max(100)
.refine((lines) => new Set(lines.map((line) => line.bomLineId)).size === lines.length, "Record each material once."),
}).strict();
const record = z.object({
id: uuid,
batchId: uuid,
createdAt: z.string().datetime(),
});
export const packagingRun = record.extend({
bomId: uuid,
lines: z.array(z.object({
bomLineId: uuid,
materialId: uuid,
materialName: z.string(),
materialCode: z.string(),
unit: bomDetail.shape.lines.element.shape.unit,
plannedQuantity: quantity,
usedQuantity: quantity,
wastedQuantity: quantity,
varianceQuantity: signedQuantity,
wasteReason: z.string().nullable(),
})),
});
const stockMovement = record.extend({ warehouseId: uuid });
const debit = z.object({
id: uuid,
materialId: uuid,
stockItemId: uuid,
delta: signedQuantity.refine((value) => value.startsWith("-") && value !== "-0.000"),
});
export const productionDebit = stockMovement.extend({
entries: z.array(debit.extend({ kind: z.enum(["PRODUCTION_CONSUMED", "PRODUCTION_WASTED"]) })),
});
export const packagingDebit = stockMovement.extend({
entries: z.array(debit.extend({ kind: z.enum(["PACKAGING_USED", "PACKAGING_WASTED"]) })),
});
export const finishedGoodsReceipt = stockMovement.extend({
variantId: uuid,
stockItemId: uuid,
ledgerEntryId: uuid,
quantity: z.number().int().min(1).max(100000),
});

134
src/pages/BatchStock.tsx Normal file
View File

@ -0,0 +1,134 @@
import { useQueryClient } from "@tanstack/react-query";
import { z } from "zod";
import Alert from "@mui/material/Alert";
import { ActionForm, Panel, QueryView, Table, WorkspaceLink } from "@/components/WorkspaceTools";
import { WarehousePostingForm } from "@/components/WarehousePostingForm";
import { useOptionalPrivateQuery } from "@/components/useOptionalPrivateQuery";
import { ApiError } from "@/lib/api";
import { receiptPostingInput } from "@/lib/material-stock";
import { usePlatform } from "@/lib/platform";
import { finishedGoodsReceipt, packagingDebit, productionDebit } from "@/lib/production-stock";
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
const material = {
endpoint: "material-stock-posting",
missing: "PRODUCTION_STOCK_POSTING_NOT_FOUND",
duplicate: "PRODUCTION_STOCK_ALREADY_POSTED",
cachePath: "/inventory/material-stock-items",
title: "Production material stock",
label: "Post production material",
instruction: "Choose the warehouse to debit for the batch’s consumed and wasted materials. Every BOM material needs a usage record.",
schema: productionDebit,
};
const packaging = {
endpoint: "packaging-stock-posting",
missing: "PACKAGING_STOCK_POSTING_NOT_FOUND",
duplicate: "PACKAGING_STOCK_ALREADY_POSTED",
cachePath: material.cachePath,
title: "Packaging material stock",
label: "Post packaging material",
instruction: "Choose the warehouse to debit for used and wasted packaging material.",
schema: packagingDebit,
};
const finished = {
endpoint: "finished-goods-receipt",
missing: "FINISHED_GOODS_RECEIPT_NOT_FOUND",
duplicate: "FINISHED_GOODS_ALREADY_POSTED",
cachePath: "/inventory/stock-items",
title: "Finished-goods receipt",
label: "Receive finished goods",
schema: finishedGoodsReceipt,
};
export function BatchStock({ batchId, goodQuantity, names, packagingRecorded }: {
batchId: string;
goodQuantity: number;
names: Map<string, string>;
packagingRecorded?: boolean;
}) {
const path = `/production-batches/${batchId}`;
const productionQuery = useOptionalPrivateQuery(`${path}/${material.endpoint}`, material.schema, material.missing);
const packagingQuery = useOptionalPrivateQuery(`${path}/${packaging.endpoint}`, packaging.schema, packaging.missing);
const receiptQuery = useOptionalPrivateQuery(`${path}/${finished.endpoint}`, finished.schema, finished.missing);
return <>
<StockStep batchId={batchId} config={material} query={productionQuery}>
{(posting) => <DebitSummary posting={posting} names={names} />}
</StockStep>
<StockStep batchId={batchId} config={packaging} query={packagingQuery}
blocked={packagingRecorded === false ? "Record the packaging run before posting its material." : undefined}>
{(posting) => <DebitSummary posting={posting} names={names} />}
</StockStep>
<StockStep batchId={batchId} config={{ ...finished, instruction: `Choose the warehouse that will receive the ${goodQuantity} good pieces.` }}
query={receiptQuery} blocked={goodQuantity === 0 ? "This batch has no good pieces to receive." :
!productionQuery.data || !packagingQuery.data ? "Post production and packaging material stock before receiving finished goods." : undefined}>
{(receipt) => <>
<p>Received {receipt.quantity} pieces into warehouse {receipt.warehouseId} on {new Date(receipt.createdAt).toLocaleString()}.</p>
<WorkspaceLink href={`/admin/inventory/${receipt.stockItemId}`}>View finished-goods stock ledger</WorkspaceLink>
</>}
</StockStep>
</>;
}
type StepConfig<T> = {
endpoint: string;
duplicate: string;
cachePath: string;
title: string;
label: string;
instruction: string;
schema: z.ZodType<T>;
};
function StockStep<T>({ batchId, config, query, blocked, children }: {
batchId: string;
config: StepConfig<T>;
query: ReturnType<typeof useOptionalPrivateQuery<T>>;
blocked?: string;
children: (record: T) => React.ReactNode;
}) {
const { can, scope } = usePlatform();
const client = useQueryClient();
const path = `/production-batches/${batchId}/${config.endpoint}`;
const command = useIdempotentCommand(path, receiptPostingInput, config.schema, batchId);
const pending = command.pending;
async function submit(input: unknown) {
let record: T;
try {
record = await command.run(input);
} catch (error) {
if (error instanceof ApiError && error.code === config.duplicate) await query.refetch();
throw error;
}
client.setQueryData(["private", scope, path], record);
await client.invalidateQueries({
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
typeof queryKey[2] === "string" && queryKey[2].startsWith(config.cachePath),
});
}
return <Panel title={config.title}>
<QueryView query={query}>{(record) => {
if (record) return children(record);
if (!can("inventory.manage")) return <Alert severity="info">Awaiting warehouse posting.</Alert>;
if (pending) return <ActionForm label={`Retry ${config.label.toLowerCase()}`} read={() => ({})} submit={submit}>
<Alert severity="warning">The server may have saved the movement. Retrying uses the original warehouse {pending.warehouseId}.</Alert>
</ActionForm>;
if (blocked) return <Alert severity="info">{blocked}</Alert>;
return <WarehousePostingForm label={config.label} instruction={config.instruction} submit={submit} />;
}}</QueryView>
</Panel>;
}
function DebitSummary({ posting, names }: {
posting: z.infer<typeof productionDebit> | z.infer<typeof packagingDebit>;
names: Map<string, string>;
}) {
return <>
<p>Posted from warehouse {posting.warehouseId} on {new Date(posting.createdAt).toLocaleString()}.</p>
{posting.entries.length ? <Table head={["Material", "Movement", "Quantity change", "Ledger"]}
rowKeys={posting.entries.map((entry) => entry.id)} rows={posting.entries.map((entry) => [
names.get(entry.materialId) ?? entry.materialId, entry.kind.replaceAll("_", " ").toLowerCase(),
entry.delta, <WorkspaceLink href={`/admin/material-stock/${entry.stockItemId}`}>View material ledger</WorkspaceLink>,
])} /> : <p>The posting recorded zero material movements.</p>}
</>;
}

View File

@ -0,0 +1,102 @@
import { useQueryClient } from "@tanstack/react-query";
import { z } from "zod";
import Alert from "@mui/material/Alert";
import { ActionForm, Field, Panel, QueryView, Table, readText } from "@/components/WorkspaceTools";
import { useOptionalPrivateQuery } from "@/components/useOptionalPrivateQuery";
import { ApiError } from "@/lib/api";
import { bomDetail } from "@/lib/bom";
import { usePlatform } from "@/lib/platform";
import { batchDetail } from "@/lib/production";
import { packagingRun, packagingRunInput } from "@/lib/production-stock";
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
import { BatchStock } from "./BatchStock";
type Batch = z.infer<typeof batchDetail>;
type Run = z.infer<typeof packagingRun>;
export function CompletedBatchOperations({ batch }: { batch: Batch }) {
const { can } = usePlatform();
const good = batch.completion?.goodQuantity ?? 0;
return can("packaging.read") ? <PackagingOperations batch={batch} good={good} /> :
can("inventory.read") ? <BatchStock batchId={batch.id} goodQuantity={good} names={materialNames(batch)} /> : null;
}
function materialNames(batch: Batch, run?: Run | null) {
return new Map([...batch.plannedMaterials, ...(run?.lines ?? [])].map((line) => [
line.materialId, `${line.materialName} (${line.materialCode}) · ${line.unit}`,
]));
}
function PackagingOperations({ batch, good }: { batch: Batch; good: number }) {
const { can, scope } = usePlatform();
const client = useQueryClient();
const path = `/production-batches/${batch.id}/packaging`;
const query = useOptionalPrivateQuery(path, packagingRun, "PACKAGING_RUN_NOT_FOUND");
const command = useIdempotentCommand(path, packagingRunInput, packagingRun, batch.id);
async function submit(input: unknown) {
try {
const saved = await command.run(input);
client.setQueryData(["private", scope, path], saved);
} catch (error) {
if (error instanceof ApiError && error.code === "PACKAGING_ALREADY_RECORDED") await query.refetch();
throw error;
}
}
return <>
<Panel title="Packaging run">
<QueryView query={query}>{(run) => {
if (run) return <>
<p>Recorded {new Date(run.createdAt).toLocaleString()} using BOM {run.bomId}.</p>
<Table head={["Material", "Planned", "Used", "Wasted", "Variance", "Waste reason"]}
rowKeys={run.lines.map((line) => line.bomLineId)} rows={run.lines.map((line) => [
`${line.materialName} (${line.materialCode}) · ${line.unit}`, line.plannedQuantity,
line.usedQuantity, line.wastedQuantity, line.varianceQuantity, line.wasteReason ?? "—",
])} />
</>;
if (!good) return <Alert severity="info">This batch has no good pieces to package.</Alert>;
if (!can("packaging.record")) return <Alert severity="info">Awaiting a packaging run.</Alert>;
if (command.pending) return <ActionForm label="Retry packaging run" read={() => ({})} submit={submit}>
<Alert severity="warning">The server may have recorded the run. Retrying uses the original BOM and quantities.</Alert>
</ActionForm>;
return <PackagingForm variantId={batch.bom.variantId} good={good} submit={submit} />;
}}</QueryView>
</Panel>
{can("inventory.read") && (
<BatchStock batchId={batch.id} goodQuantity={good} names={materialNames(batch, query.data)}
packagingRecorded={good === 0 ? false : query.data === undefined ? undefined : query.data !== null} />
)}
</>;
}
function PackagingForm({ variantId, good, submit }: {
variantId: string;
good: number;
submit: (input: unknown) => Promise<void>;
}) {
const query = useOptionalPrivateQuery(`/variants/${variantId}/packaging-boms/active`, bomDetail, "BOM_NOT_FOUND");
return <QueryView query={query}>{(bom) => {
if (!bom) return <Alert severity="info">Activate a packaging BOM for this variant before recording its run.</Alert>;
if (good % bom.outputQuantity !== 0) return <Alert severity="warning">
The {good} good pieces must be a multiple of the active packaging BOM yield of {bom.outputQuantity}.
</Alert>;
return <ActionForm key={bom.id} label="Record packaging run" read={(form) => ({
bomId: bom.id,
lines: bom.lines.map((line) => ({
bomLineId: line.id,
usedQuantity: readText(form, `${line.id}-used`).trim(),
wastedQuantity: readText(form, `${line.id}-wasted`).trim(),
wasteReason: readText(form, `${line.id}-reason`).trim() || undefined,
})),
})} submit={submit}>
<p>Record actual packaging for {good} good pieces using revision {bom.revision}. This record is final.</p>
{bom.lines.map((line) => (
<fieldset className="record-picker" key={line.id}>
<legend>{line.materialName} ({line.materialCode}) · {line.unit}</legend>
<Field name={`${line.id}-used`} label={`Used quantity for ${line.materialName}`} maxLength={13} helper="Use three decimal places." />
<Field name={`${line.id}-wasted`} label={`Wasted quantity for ${line.materialName}`} value="0.000" maxLength={13} />
<Field name={`${line.id}-reason`} label={`Waste reason for ${line.materialName}`} required={false} maxLength={500} />
</fieldset>
))}
</ActionForm>;
}}</QueryView>;
}

View File

@ -10,6 +10,7 @@ import { isUnknownOutcome } from "@/lib/api";
import { usePlatform } from "@/lib/platform";
import { batchDetail, batchInput, batchStatus, cancelBatchInput, parseCompletion, productionBatch } from "@/lib/production";
import { BatchMaterialUsage } from "./BatchMaterialUsage";
import { CompletedBatchOperations } from "./CompletedBatchOperations";
const route = "/admin/production-batches";
const api = "/production-batches";
@ -101,6 +102,7 @@ function BatchDetails({ id }: { id: string }) {
)}
</Panel>
<BatchMaterialUsage batch={batch} />
{batch.status === "COMPLETED" && <CompletedBatchOperations 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>

View File

@ -1,10 +1,9 @@
import { useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { z } from "zod";
import { useQueryClient } from "@tanstack/react-query";
import Alert from "@mui/material/Alert";
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
import { ActionForm, Panel, QueryView, Table, WorkspaceLink } from "@/components/WorkspaceTools";
import { WarehousePostingForm } from "@/components/WarehousePostingForm";
import { useOptionalPrivateQuery } from "@/components/useOptionalPrivateQuery";
import { ApiError } from "@/lib/api";
import { warehouse } from "@/lib/commerce";
import { receiptPosting, receiptPostingInput } from "@/lib/material-stock";
import { usePlatform } from "@/lib/platform";
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
@ -13,20 +12,9 @@ export function ReceiptStockPosting({ receiptId, lineNames }: {
receiptId: string;
lineNames: Map<string, string>;
}) {
const { can, scope, request } = usePlatform();
const { can } = usePlatform();
const path = `/goods-receipts/${receiptId}/stock-posting`;
const query = useQuery({
queryKey: ["private", scope, path],
retry: false,
queryFn: async ({ signal }) => {
try {
return await request(path, receiptPosting, { signal });
} catch (error) {
if (error instanceof ApiError && error.status === 404 && error.code === "MATERIAL_POSTING_NOT_FOUND") return null;
throw error;
}
},
});
const query = useOptionalPrivateQuery(path, receiptPosting, "MATERIAL_POSTING_NOT_FOUND");
return <Panel title="Material warehouse posting">
<QueryView query={query}>{(posting) => posting ? <>
<p>Posted to warehouse {posting.warehouseId} on {new Date(posting.createdAt).toLocaleString()}.</p>
@ -69,24 +57,6 @@ function PostReceipt({ path, receiptId, refresh }: {
<ActionForm label="Retry warehouse posting" read={() => ({})} submit={submit}>
<Alert severity="warning">The server may have posted this receipt. Retrying uses the same request and warehouse {command.pending.warehouseId}.</Alert>
</ActionForm>
) : <WarehousePicker submit={submit} />;
}
function WarehousePicker({ submit }: { submit: (input: unknown) => Promise<void> }) {
const [offset, setOffset] = useState(0);
const query = usePrivateQuery(`/inventory/warehouses?limit=25&offset=${offset}`, z.array(warehouse));
return <QueryView query={query}>{(rows) => <>
{rows.length ? <ActionForm key={offset} label="Post accepted material" reset={false}
read={(data) => ({ warehouseId: readText(data, "warehouseId") })} submit={submit}>
<p>Choose the warehouse to credit with all accepted quantities from this receipt. A receipt can be posted once.</p>
<Field name="warehouseId" label="Destination warehouse" options={[
{ value: "", label: "Choose a warehouse" },
...rows.map((row) => ({ value: row.id, label: row.name })),
]} />
<Pager offset={offset} count={rows.length} onPage={setOffset} />
</ActionForm> : <>
<Alert severity="info">No warehouses on this page.</Alert>
{offset > 0 && <Pager offset={offset} count={0} onPage={setOffset} />}
</>}
</>}</QueryView>;
) : <WarehousePostingForm label="Post accepted material" warehouseLabel="Destination warehouse" submit={submit}
instruction="Choose the warehouse to credit with all accepted quantities from this receipt. A receipt can be posted once." />;
}

View File

@ -19,6 +19,6 @@ test("revision lists accept metadata without lines and details accept serialized
const metadata = { id, variantId: id, kind: "PACKAGING", status: "DRAFT", revision: 1, outputQuantity: 10, activatedAt: null };
assert.deepEqual(bomSummary.parse(metadata), metadata);
assert.equal(bomDetail.safeParse(metadata).success, false);
const line = { id, materialName: "Label", materialCode: "LABEL", unit: "PIECE", quantity: "10" };
const line = { id, materialId: id, materialName: "Label", materialCode: "LABEL", unit: "PIECE", quantity: "10" };
assert.deepEqual(bomDetail.parse({ ...metadata, lines: [line] }).lines, [line]);
});

View File

@ -1,5 +1,5 @@
import { type ReactNode } from "react";
import { act, render, screen, waitFor } from "@testing-library/react";
import { act, render, screen, waitFor, within } from "@testing-library/react";
import { Table } from "../src/components/WorkspaceTools";
import { ConfirmAction } from "../src/components/ConfirmAction";
import userEvent from "@testing-library/user-event";
@ -17,6 +17,8 @@ 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 { CompletedBatchOperations } from "../src/pages/CompletedBatchOperations";
import { batchDetail } from "../src/lib/production";
import theme from "../src/theme";
import { Switch, Route } from "wouter";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
@ -179,12 +181,82 @@ function harness(children: ReactNode) {
return { client, ...result };
}
test("completed production posts both material debits before receiving good pieces and retries with the same key", async () => {
const date = "2026-11-14T00:00:00.000Z";
const labelId = "d66c798a-f764-4b88-8d13-ace328ff1011";
const wax = { id, materialId: id, materialName: "Wax", materialCode: "WAX", unit: "GRAM", quantity: "1" };
const label = { id: labelId, materialId: labelId, materialName: "Label", materialCode: "LABEL", unit: "PIECE", quantity: "1" };
const bom = { id, variantId: id, kind: "PRODUCTION", status: "ACTIVE", revision: 1, outputQuantity: 1, activatedAt: date };
const batch = batchDetail.parse({
id, bom, reference: "BATCH-20", plannedQuantity: 20, status: "COMPLETED", scheduledDate: null, startedAt: date,
plannedMaterials: [{ ...wax, plannedQuantity: "20.000" }], cancellation: null,
completion: { goodQuantity: 18, rejectedQuantity: 2, rejectionReason: "Defects", createdAt: date },
});
const base = { id, batchId: id, createdAt: date, warehouseId: id };
const expected = {
packaging: { ...base, bomId: labelId, lines: [{ ...label, bomLineId: labelId, plannedQuantity: "18.000", usedQuantity: "18.000", wastedQuantity: "0.000", varianceQuantity: "0.000", wasteReason: null }] },
"material-stock-posting": { ...base, entries: [{ id, materialId: id, stockItemId: id, kind: "PRODUCTION_CONSUMED", delta: "-20.000" }] },
"packaging-stock-posting": { ...base, entries: [{ id, materialId: labelId, stockItemId: labelId, kind: "PACKAGING_USED", delta: "-18.000" }] },
"finished-goods-receipt": { ...base, stockItemId: id, variantId: id, ledgerEntryId: id, quantity: 18 },
};
const missing = {
packaging: "PACKAGING_RUN_NOT_FOUND",
"material-stock-posting": "PRODUCTION_STOCK_POSTING_NOT_FOUND",
"packaging-stock-posting": "PACKAGING_STOCK_POSTING_NOT_FOUND",
"finished-goods-receipt": "FINISHED_GOODS_RECEIPT_NOT_FOUND",
};
const saved = new Set<string>();
const attempts: { step: string; body: unknown }[] = [];
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", "packaging.read", "packaging.record", "inventory.read", "inventory.manage",
] });
if (url.endsWith("/packaging-boms/active")) return json({ ...bom, id: labelId, kind: "PACKAGING", lines: [label] });
if (url.includes("/inventory/warehouses?")) return json([{ id, name: "Main warehouse" }]);
const step = url.split("/").at(-1) as keyof typeof expected;
if (!Object.hasOwn(expected, step)) throw new Error(`Unexpected request ${url}`);
if (options?.method !== "POST") return saved.has(step) ? json(expected[step]) : json({ code: missing[step] }, 404);
attempts.push({ step, body: JSON.parse(String(options.body)) });
if (step === "finished-goods-receipt" && !saved.has(step)) {
saved.add(step);
throw new Error("Response lost");
}
saved.add(step);
return json(expected[step]);
}));
function AuthorizedOperations() {
return usePlatform().can("production.read") ? <CompletedBatchOperations batch={batch} /> : null;
}
harness(<AuthorizedOperations />);
const user = userEvent.setup();
await user.click(screen.getByText("Test login"));
await screen.findByText("Post production and packaging material stock before receiving finished goods.");
expect(screen.queryByRole("button", { name: "Receive finished goods" })).toBeNull();
await user.type(await screen.findByRole("textbox", { name: /Used quantity for Label/ }), "18.000");
await user.click(screen.getByRole("button", { name: "Record packaging run" }));
for (const action of ["Post production material", "Post packaging material", "Receive finished goods"]) {
const form = within(await screen.findByRole("form", { name: action }));
await user.selectOptions(form.getByRole("combobox", { name: /Warehouse/ }), id);
await user.click(form.getByRole("button", { name: action }));
}
await user.click(await screen.findByRole("button", { name: "Retry receive finished goods" }));
await screen.findByText(/Received 18 pieces into warehouse/);
expect(attempts.map(({ step }) => step)).toEqual(["packaging", "material-stock-posting", "packaging-stock-posting", "finished-goods-receipt", "finished-goods-receipt"]);
expect(attempts[0].body).toEqual({
bomId: labelId, idempotencyKey: expect.any(String),
lines: [{ bomLineId: labelId, usedQuantity: "18.000", wastedQuantity: "0.000" }],
});
expect(attempts[3].body).toEqual({ warehouseId: id, idempotencyKey: expect.any(String) });
expect(attempts[4]).toEqual(attempts[3]);
});
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 plannedMaterial = { id, materialId: 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,
@ -252,7 +324,7 @@ test("packaging staff draft and activate an independent BOM with eligible materi
const draft = {
id: draftId, variantId: id, kind: "PACKAGING", status: "DRAFT", revision: 2,
outputQuantity: 10, activatedAt: null,
lines: [{ id, materialName: "Label", materialCode: "LABEL", unit: "PIECE", quantity: "10" }],
lines: [{ id, materialId: id, materialName: "Label", materialCode: "LABEL", unit: "PIECE", quantity: "10" }],
};
const first = { ...draft, id, revision: 1, status: "ACTIVE", activatedAt: "2026-11-12T00:00:00.000Z" };
let created = false;
@ -309,7 +381,7 @@ test("production BOM observers can review a draft without seeing write controls"
if (url.endsWith("/auth/me")) return json({ ...me, permissions: ["bom.read"] });
if (url.includes(`/variants/${id}/boms?`)) return json([revision]);
if (url.endsWith(`/boms/${id}`)) return json({
...revision, lines: [{ id, materialName: "Wax", materialCode: "WAX", unit: "GRAM", quantity: "125.5" }],
...revision, lines: [{ id, materialId: id, materialName: "Wax", materialCode: "WAX", unit: "GRAM", quantity: "125.5" }],
});
throw new Error(`Unexpected request ${url}`);
});