diff --git a/docs/PHASES.md b/docs/PHASES.md index 921edcc..b7dc056 100644 --- a/docs/PHASES.md +++ b/docs/PHASES.md @@ -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. diff --git a/src/components/WarehousePostingForm.tsx b/src/components/WarehousePostingForm.tsx new file mode 100644 index 0000000..696ae31 --- /dev/null +++ b/src/components/WarehousePostingForm.tsx @@ -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; +}) { + const [offset, setOffset] = useState(0); + const query = usePrivateQuery(`/inventory/warehouses?limit=25&offset=${offset}`, z.array(warehouse)); + return {(rows) => <> + {rows.length ? ({ warehouseId: readText(data, "warehouseId") })} submit={submit}> +

{instruction}

+ ({ value: row.id, label: row.name })), + ]} /> + +
: <> + No warehouses on this page. + {offset > 0 && } + } + }
; +} diff --git a/src/components/useOptionalPrivateQuery.ts b/src/components/useOptionalPrivateQuery.ts new file mode 100644 index 0000000..ac769b6 --- /dev/null +++ b/src/components/useOptionalPrivateQuery.ts @@ -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(path: string, schema: z.ZodType, 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; + } + }, + }); +} diff --git a/src/lib/bom.ts b/src/lib/bom.ts index 0a89477..68639a9 100644 --- a/src/lib/bom.ts +++ b/src/lib/bom.ts @@ -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, diff --git a/src/lib/production-stock.ts b/src/lib/production-stock.ts new file mode 100644 index 0000000..66dfa93 --- /dev/null +++ b/src/lib/production-stock.ts @@ -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), +}); diff --git a/src/pages/BatchStock.tsx b/src/pages/BatchStock.tsx new file mode 100644 index 0000000..329a4bb --- /dev/null +++ b/src/pages/BatchStock.tsx @@ -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; + 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 <> + + {(posting) => } + + + {(posting) => } + + + {(receipt) => <> +

Received {receipt.quantity} pieces into warehouse {receipt.warehouseId} on {new Date(receipt.createdAt).toLocaleString()}.

+ View finished-goods stock ledger + } +
+ ; +} + +type StepConfig = { + endpoint: string; + duplicate: string; + cachePath: string; + title: string; + label: string; + instruction: string; + schema: z.ZodType; +}; + +function StockStep({ batchId, config, query, blocked, children }: { + batchId: string; + config: StepConfig; + query: ReturnType>; + 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 + {(record) => { + if (record) return children(record); + if (!can("inventory.manage")) return Awaiting warehouse posting.; + if (pending) return ({})} submit={submit}> + The server may have saved the movement. Retrying uses the original warehouse {pending.warehouseId}. + ; + if (blocked) return {blocked}; + return ; + }} + ; +} + +function DebitSummary({ posting, names }: { + posting: z.infer | z.infer; + names: Map; +}) { + return <> +

Posted from warehouse {posting.warehouseId} on {new Date(posting.createdAt).toLocaleString()}.

+ {posting.entries.length ? entry.id)} rows={posting.entries.map((entry) => [ + names.get(entry.materialId) ?? entry.materialId, entry.kind.replaceAll("_", " ").toLowerCase(), + entry.delta, View material ledger, + ])} /> :

The posting recorded zero material movements.

} + ; +} diff --git a/src/pages/CompletedBatchOperations.tsx b/src/pages/CompletedBatchOperations.tsx new file mode 100644 index 0000000..ece2548 --- /dev/null +++ b/src/pages/CompletedBatchOperations.tsx @@ -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; +type Run = z.infer; + +export function CompletedBatchOperations({ batch }: { batch: Batch }) { + const { can } = usePlatform(); + const good = batch.completion?.goodQuantity ?? 0; + return can("packaging.read") ? : + can("inventory.read") ? : 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 <> + + {(run) => { + if (run) return <> +

Recorded {new Date(run.createdAt).toLocaleString()} using BOM {run.bomId}.

+
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 This batch has no good pieces to package.; + if (!can("packaging.record")) return Awaiting a packaging run.; + if (command.pending) return ({})} submit={submit}> + The server may have recorded the run. Retrying uses the original BOM and quantities. + ; + return ; + }} + + {can("inventory.read") && ( + + )} + ; +} + +function PackagingForm({ variantId, good, submit }: { + variantId: string; + good: number; + submit: (input: unknown) => Promise; +}) { + const query = useOptionalPrivateQuery(`/variants/${variantId}/packaging-boms/active`, bomDetail, "BOM_NOT_FOUND"); + return {(bom) => { + if (!bom) return Activate a packaging BOM for this variant before recording its run.; + if (good % bom.outputQuantity !== 0) return + The {good} good pieces must be a multiple of the active packaging BOM yield of {bom.outputQuantity}. + ; + return ({ + 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}> +

Record actual packaging for {good} good pieces using revision {bom.revision}. This record is final.

+ {bom.lines.map((line) => ( +
+ {line.materialName} ({line.materialCode}) · {line.unit} + + + +
+ ))} +
; + }}
; +} diff --git a/src/pages/ProductionBatchesPage.tsx b/src/pages/ProductionBatchesPage.tsx index e6d1e46..626d71e 100644 --- a/src/pages/ProductionBatchesPage.tsx +++ b/src/pages/ProductionBatchesPage.tsx @@ -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 }) { )} + {batch.status === "COMPLETED" && } {can("production.manage") && batch.status === "IN_PROGRESS" && (

Record all material usage before completing production. Completion closes the batch to new usage entries.

diff --git a/src/pages/ReceiptStockPosting.tsx b/src/pages/ReceiptStockPosting.tsx index 4020b3c..14488ff 100644 --- a/src/pages/ReceiptStockPosting.tsx +++ b/src/pages/ReceiptStockPosting.tsx @@ -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; }) { - 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 {(posting) => posting ? <>

Posted to warehouse {posting.warehouseId} on {new Date(posting.createdAt).toLocaleString()}.

@@ -69,24 +57,6 @@ function PostReceipt({ path, receiptId, refresh }: { ({})} submit={submit}> The server may have posted this receipt. Retrying uses the same request and warehouse {command.pending.warehouseId}. - ) : ; -} - -function WarehousePicker({ submit }: { submit: (input: unknown) => Promise }) { - const [offset, setOffset] = useState(0); - const query = usePrivateQuery(`/inventory/warehouses?limit=25&offset=${offset}`, z.array(warehouse)); - return {(rows) => <> - {rows.length ? ({ warehouseId: readText(data, "warehouseId") })} submit={submit}> -

Choose the warehouse to credit with all accepted quantities from this receipt. A receipt can be posted once.

- ({ value: row.id, label: row.name })), - ]} /> - -
: <> - No warehouses on this page. - {offset > 0 && } - } - }
; + ) : ; } diff --git a/test/bom.test.ts b/test/bom.test.ts index fe59ac8..e473eba 100644 --- a/test/bom.test.ts +++ b/test/bom.test.ts @@ -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]); }); diff --git a/test/workflows.ui.test.tsx b/test/workflows.ui.test.tsx index b8f20a9..36fac96 100644 --- a/test/workflows.ui.test.tsx +++ b/test/workflows.ui.test.tsx @@ -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(); + 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") ? : null; + } + harness(); + 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}`); });