diff --git a/docs/PHASES.md b/docs/PHASES.md index 6f05e2e..fef9e85 100644 --- a/docs/PHASES.md +++ b/docs/PHASES.md @@ -39,8 +39,9 @@ Customer and administration screens are implemented, with recovery, pricing, sto - 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. - Completed batches support packaging runs, production and packaging material debits, and receipt of good finished pieces into warehouse stock. - Costing supports immutable material rate revisions, current-rate BOM estimates, and completed-batch cost snapshots with exact totals and saved rate revisions. -- Warehouse transfers and adjustments remain open. +- Material warehouse transfers post matched debits and credits. Authorized adjusters can record signed corrections with reasons, including positive corrections for materials with no balance at the selected warehouse. - 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. - Costing UAT should revise a material rate and verify that future BOM estimates use the new revision while an existing batch snapshot retains its original amounts and rates. Test missing rates, missing usage, and fully rejected output. +- Warehouse movement UAT should verify both ledgers and unchanged combined stock after a transfer, rejection of insufficient stock, and one ledger entry for a retried adjustment. diff --git a/src/App.tsx b/src/App.tsx index e38cee0..22610d7 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -73,6 +73,10 @@ function Router() { {() => } {() => } + {() => } + + {(params) => } + {(params) => } diff --git a/src/components/WarehousePostingForm.tsx b/src/components/WarehousePostingForm.tsx index 696ae31..a81ca04 100644 --- a/src/components/WarehousePostingForm.tsx +++ b/src/components/WarehousePostingForm.tsx @@ -1,29 +1,37 @@ -import { useState } from "react"; +import { useState, type ReactNode } 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 }: { +export function WarehousePostingForm({ label, instruction, warehouseLabel = "Warehouse", excludeWarehouseId, read, children, reset = false, submit }: { label: string; instruction: string; warehouseLabel?: string; + excludeWarehouseId?: string; + read?: (data: FormData) => unknown; + children?: ReactNode; + reset?: boolean; 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}> + return {(rows) => { + const options = rows.filter((row) => row.id !== excludeWarehouseId); + return <> + {options.length ? ({ warehouseId: readText(data, "warehouseId") }))} submit={submit}>

{instruction}

({ value: row.id, label: row.name })), + ...options.map((row) => ({ value: row.id, label: row.name })), ]} /> + {children}
: <> - No warehouses on this page. - {offset > 0 && } + No eligible warehouses on this page. + {(offset > 0 || rows.length === 25) && } } - }
; + ; + }}
; } diff --git a/src/lib/material-stock.ts b/src/lib/material-stock.ts index 1765366..d936d0a 100644 --- a/src/lib/material-stock.ts +++ b/src/lib/material-stock.ts @@ -3,6 +3,8 @@ import { uuid, warehouse } from "./commerce.ts"; import { material } from "./procurement.ts"; const quantity = z.string().regex(/^\d{1,9}\.\d{3}$/); +const positiveQuantity = quantity.refine((value) => value !== "0.000"); +const signedQuantity = z.string().regex(/^-?\d{1,9}\.\d{3}$/); export const receiptPostingInput = z.object({ warehouseId: uuid, @@ -33,6 +35,43 @@ export const materialStockItem = z.object({ export const materialStockEntry = z.object({ id: uuid, kind: z.string(), - delta: z.string().regex(/^-?\d{1,9}\.\d{3}$/), + delta: signedQuantity, createdAt: z.string().datetime(), }); + +const transferFields = z.object({ + materialId: uuid, + fromWarehouseId: uuid, + toWarehouseId: uuid, +}); +export const materialTransferInput = transferFields.extend({ + quantity: z.string().regex(/^(?:0|[1-9]\d{0,8})\.\d{3}$/, "Use three decimal places") + .refine((value) => value !== "0.000", "Enter a positive quantity"), + idempotencyKey: uuid, +}).strict().refine((value) => value.fromWarehouseId !== value.toWarehouseId, { + path: ["toWarehouseId"], + message: "Choose a different destination warehouse.", +}); + +export const materialTransfer = transferFields.extend({ + id: uuid, + fromStockItemId: uuid, + toStockItemId: uuid, + quantity: positiveQuantity, + createdAt: z.string().datetime(), +}); + +export const materialAdjustmentInput = z.object({ + materialId: uuid, + warehouseId: uuid, + delta: z.string().regex(/^-?(?:0|[1-9]\d{0,8})\.\d{3}$/, "Use three decimal places and a minus sign for decreases") + .refine((value) => value !== "0.000" && value !== "-0.000", "Enter a nonzero change"), + reason: z.string().trim().min(3).max(200), + idempotencyKey: uuid, +}).strict(); + +export const materialAdjustment = materialAdjustmentInput.omit({ idempotencyKey: true }).extend({ + id: uuid, + stockItemId: uuid, + createdAt: z.string().datetime(), +}).strip(); diff --git a/src/pages/MaterialStockMovements.tsx b/src/pages/MaterialStockMovements.tsx new file mode 100644 index 0000000..7feee85 --- /dev/null +++ b/src/pages/MaterialStockMovements.tsx @@ -0,0 +1,137 @@ +import { useState } from "react"; +import { useQueryClient } from "@tanstack/react-query"; +import { z } from "zod"; +import Alert from "@mui/material/Alert"; +import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools"; +import { WarehousePostingForm } from "@/components/WarehousePostingForm"; +import { materialAdjustment, materialAdjustmentInput, materialStockItem, materialTransfer, materialTransferInput } from "@/lib/material-stock"; +import { usePlatform } from "@/lib/platform"; +import { useIdempotentCommand } from "@/lib/use-idempotent-command"; + +const transferPath = "/inventory/material-transfers"; +const adjustmentPath = "/inventory/material-adjustments"; +const stockRoute = "/admin/material-stock"; +type Stock = z.infer; +type Adjustment = z.infer; + +function useRefreshMovements(path: string) { + const { scope } = usePlatform(); + const client = useQueryClient(); + return () => client.invalidateQueries({ + predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope && + typeof queryKey[2] === "string" && + (queryKey[2].startsWith("/inventory/material-stock-items") || queryKey[2].startsWith(path)), + }); +} + +export function MaterialStockMovements({ stock }: { stock: Stock }) { + const { can } = usePlatform(); + return <> + + + {can("inventory.adjust") && } + ; +} + +function Transfers({ stock, write }: { stock: Stock; write: boolean }) { + const [offset, setOffset] = useState(0); + const [saved, setSaved] = useState>(); + const query = usePrivateQuery( + `${transferPath}?materialId=${stock.material.id}&limit=25&offset=${offset}`, + z.array(materialTransfer), + ); + const command = useIdempotentCommand(transferPath, materialTransferInput, materialTransfer, stock.id); + const refresh = useRefreshMovements(transferPath); + const pending = command.pending; + async function submit(value: unknown) { + const transfer = await command.run(value); + setSaved(transfer); + setOffset(0); + await refresh(); + } + return + {saved && Transferred {saved.quantity} {stock.material.unit}. Open destination ledger} + {write && (pending ? ( + ({})} submit={submit}> + Retrying uses the original quantity {pending.quantity} {stock.material.unit} and destination warehouse {pending.toWarehouseId}. + + ) : ({ + materialId: stock.material.id, + fromWarehouseId: stock.warehouse.id, + toWarehouseId: readText(data, "warehouseId"), + quantity: readText(data, "quantity").trim(), + })} submit={submit}> + + )} + {(rows) => <> + row.id)} + rows={rows.map((row) => [ + new Date(row.createdAt).toLocaleString(), `${row.quantity} ${stock.material.unit}`, + {row.fromWarehouseId === stock.warehouse.id ? stock.warehouse.name : "Source ledger"}, + {row.toWarehouseId === stock.warehouse.id ? stock.warehouse.name : "Destination ledger"}, + ])} /> + + } + ; +} + +function AdjustmentHistory({ materialId, warehouseId, unit }: { materialId: string; warehouseId: string; unit: string }) { + const [offset, setOffset] = useState(0); + const query = usePrivateQuery( + `${adjustmentPath}?materialId=${materialId}&warehouseId=${warehouseId}&limit=25&offset=${offset}`, + z.array(materialAdjustment), + ); + return + {(rows) => <> +
row.id)} + rows={rows.map((row) => [new Date(row.createdAt).toLocaleString(), `${signed(row.delta)} ${unit}`, row.reason])} /> + + } + ; +} + +export function MaterialAdjustmentForm({ stock, materialId }: { stock?: Stock; materialId?: string }) { + const [saved, setSaved] = useState(); + const command = useIdempotentCommand(adjustmentPath, materialAdjustmentInput, materialAdjustment, stock?.id ?? materialId ?? "new"); + const refresh = useRefreshMovements(adjustmentPath); + const pending = command.pending; + const instruction = "Record a counted discrepancy or stock correction. Use a minus sign for decreases."; + const fields = <> + {!stock && !materialId && } + + + ; + function read(data: FormData) { + return { + materialId: stock?.material.id ?? materialId ?? readText(data, "materialId").trim(), + warehouseId: stock?.warehouse.id ?? readText(data, "warehouseId"), + delta: readText(data, "delta").trim(), + reason: readText(data, "reason"), + }; + } + async function submit(input: unknown) { + setSaved(await command.run(input)); + await refresh(); + } + return + {materialId &&

Material ID {materialId}

} + {saved && Recorded {signed(saved.delta)}. Open adjusted stock ledger} + {pending ? ( + ({})} submit={submit}> + Retrying uses the original change {signed(pending.delta)} and reason. Warehouse {pending.warehouseId}. + + ) : stock ? ( + +

{instruction}

+ {fields} +
+ ) : {fields}} +
; +} + +function signed(delta: string) { + return delta.startsWith("-") ? delta : `+${delta}`; +} diff --git a/src/pages/MaterialStockPage.tsx b/src/pages/MaterialStockPage.tsx index 0caa232..bb5f2af 100644 --- a/src/pages/MaterialStockPage.tsx +++ b/src/pages/MaterialStockPage.tsx @@ -5,13 +5,17 @@ import { WorkspaceShell } from "@/components/WorkspaceShell"; import { Pager, Panel, QueryView, Table, WorkspaceLink, usePrivateQuery } from "@/components/WorkspaceTools"; import { uuid } from "@/lib/commerce"; import { materialStockEntry, materialStockItem } from "@/lib/material-stock"; +import { usePlatform } from "@/lib/platform"; +import { MaterialAdjustmentForm, MaterialStockMovements } from "./MaterialStockMovements"; const stockPath = "/inventory/material-stock-items"; function StockList() { + const { can } = usePlatform(); const [offset, setOffset] = useState(0); const query = usePrivateQuery(`${stockPath}?limit=25&offset=${offset}`, z.array(materialStockItem)); return + {can("inventory.adjust") &&

Record a material adjustment

} {(rows) => <>
row.id)} rows={rows.map((row) => [ @@ -41,14 +45,26 @@ function StockLedger({ id }: { id: string }) { ])} /> } + {(row) => } ; } -export default function MaterialStockPage({ id }: { id?: string }) { +export default function MaterialStockPage({ id, adjust = false }: { id?: string; adjust?: boolean }) { const parsed = uuid.safeParse(id); return - {!id ? : parsed.success ? ( + {adjust ? : !id ? : parsed.success ? ( ) : Invalid stock item ID.} ; } + +function AdjustmentRoute({ materialId }: { materialId?: string }) { + const { can } = usePlatform(); + const id = uuid.safeParse(materialId); + return <> + All material stock + {!can("inventory.adjust") ? Your account does not have permission to adjust material stock. : + materialId && !id.success ? Invalid material ID. : + } + ; +} diff --git a/src/pages/ProcurementPage.tsx b/src/pages/ProcurementPage.tsx index d729cbe..ad3e7ae 100644 --- a/src/pages/ProcurementPage.tsx +++ b/src/pages/ProcurementPage.tsx @@ -39,6 +39,9 @@ function Directory({ materials }: { materials: boolean }) { <> {can("procurement.manage") && } {"kind" in row && can("cost.read") && Cost rates for {row.name}} + {"kind" in row && can("inventory.adjust") && can("inventory.read") && ( +
Adjust stock for {row.name}
+ )} {"contactName" in row && Supply terms and orders for {row.name}} {"contactName" in row && can("supplier_document.read") && ( <> · Documents for {row.name} diff --git a/test/material-stock.test.ts b/test/material-stock.test.ts new file mode 100644 index 0000000..e723f0e --- /dev/null +++ b/test/material-stock.test.ts @@ -0,0 +1,28 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { materialAdjustment, materialAdjustmentInput, materialTransferInput } from "../src/lib/material-stock.ts"; + +const id = "d66c798a-f764-4b88-8d13-ace328ff1010"; +const warehouseId = "d66c798a-f764-4b88-8d13-ace328ff1011"; + +test("warehouse transfers require distinct locations and positive exact quantities", () => { + const transfer = { materialId: id, fromWarehouseId: id, toWarehouseId: warehouseId, quantity: "0.125", idempotencyKey: id }; + assert.deepEqual(materialTransferInput.parse(transfer), transfer); + assert.equal(materialTransferInput.safeParse({ ...transfer, toWarehouseId: id.toUpperCase() }).success, false); + for (const quantity of ["0.000", "-0.125", "0.12", "01.000"]) { + assert.equal(materialTransferInput.safeParse({ ...transfer, quantity }).success, false); + } +}); + +test("material adjustments preserve exact signed values and require a trimmed reason", () => { + const input = { materialId: id, warehouseId, delta: "-0.125", reason: " Cycle count ", idempotencyKey: id }; + assert.deepEqual(materialAdjustmentInput.parse(input), { ...input, reason: "Cycle count" }); + for (const delta of ["-0.000", "0.000", "+0.125", "0.1250"]) { + assert.equal(materialAdjustmentInput.safeParse({ ...input, delta }).success, false); + } + assert.equal(materialAdjustmentInput.safeParse({ ...input, reason: " ok " }).success, false); + const { idempotencyKey: _key, ...record } = input; + assert.equal(materialAdjustment.parse({ + ...record, id, stockItemId: id, createdAt: "2026-11-14T00:00:00.000Z", ledgerEntryId: id, + }).delta, "-0.125"); +}); diff --git a/test/workflows.ui.test.tsx b/test/workflows.ui.test.tsx index 677f7a3..2371db5 100644 --- a/test/workflows.ui.test.tsx +++ b/test/workflows.ui.test.tsx @@ -20,6 +20,7 @@ import ProductionBatchesPage from "../src/pages/ProductionBatchesPage"; import { CompletedBatchOperations } from "../src/pages/CompletedBatchOperations"; import { BatchCostSnapshot } from "../src/pages/CostingPanels"; import MaterialCostRatesPage from "../src/pages/MaterialCostRatesPage"; +import MaterialStockPage from "../src/pages/MaterialStockPage"; import { batchDetail } from "../src/lib/production"; import theme from "../src/theme"; import { Switch, Route } from "wouter"; @@ -183,6 +184,78 @@ function harness(children: ReactNode) { return { client, ...result }; } +test("material transfers exclude the source warehouse and retry with the same key", async () => { + const destination = "d66c798a-f764-4b88-8d13-ace328ff1011"; + const stock = { + id, warehouse: { id, name: "Main warehouse" }, + material: { id, name: "Wax", code: "WAX", unit: "GRAM", kind: "WAX", active: true }, + onHand: "2.000", + }; + const attempts: unknown[] = []; + const transfer = { + id, materialId: id, fromWarehouseId: id, toWarehouseId: destination, + fromStockItemId: id, toStockItemId: destination, quantity: "0.125", + createdAt: "2026-11-14T00:00:00.000Z", + }; + 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: ["inventory.read", "inventory.manage"] }); + if (url.includes("/inventory/warehouses?")) return json([stock.warehouse, { id: destination, name: "Overflow" }]); + if (url.endsWith(`/inventory/material-stock-items/${id}`)) return json({ ...stock, onHand: attempts.length ? "1.875" : "2.000" }); + if (url.includes("/ledger?") || url.includes("/material-adjustments?")) return json([]); + if (url.includes("/material-transfers?")) return json(attempts.length ? [transfer] : []); + if (url.endsWith("/material-transfers") && options?.method === "POST") { + attempts.push(JSON.parse(String(options.body))); + if (attempts.length === 1) throw new Error("Response lost"); + return json(transfer); + } + throw new Error(`Unexpected request ${url}`); + })); + harness(); + const user = userEvent.setup(); + await user.click(screen.getByText("Test login")); + const select = await screen.findByRole("combobox", { name: /Destination warehouse/ }); + expect(within(select).queryByRole("option", { name: "Main warehouse" })).toBeNull(); + expect(screen.queryByRole("button", { name: "Record stock adjustment" })).toBeNull(); + await user.selectOptions(select, destination); + await user.type(screen.getByRole("textbox", { name: /Quantity to transfer/ }), "0.125"); + await user.click(screen.getByRole("button", { name: "Transfer material" })); + await user.click(await screen.findByRole("button", { name: "Retry material transfer" })); + await screen.findByText(/On hand 1.875 GRAM/); + expect(screen.getByRole("link", { name: "Open destination ledger" }).getAttribute("href")).toBe(`/admin/material-stock/${destination}`); + expect(attempts).toEqual([ + { materialId: id, fromWarehouseId: id, toWarehouseId: destination, quantity: "0.125", idempotencyKey: expect.any(String) }, + attempts[0], + ]); +}); + +test("positive adjustments can create a warehouse balance and link to its ledger", async () => { + let 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: ["inventory.read", "inventory.adjust"] }); + if (url.includes("/inventory/warehouses?")) return json([{ id, name: "Main warehouse" }]); + if (url.endsWith("/material-adjustments") && options?.method === "POST") { + body = JSON.parse(String(options.body)); + return json({ + id, materialId: id, warehouseId: id, stockItemId: id, delta: "0.125", reason: "Cycle count", + createdAt: "2026-11-14T00:00:00.000Z", + }); + } + throw new Error(`Unexpected request ${url}`); + })); + harness(); + const user = userEvent.setup(); + await user.click(screen.getByText("Test login")); + await user.selectOptions(await screen.findByRole("combobox", { name: /Warehouse/ }), id); + await user.type(screen.getByRole("textbox", { name: /Quantity change/ }), "0.125"); + await user.type(screen.getByRole("textbox", { name: /Adjustment reason/ }), "Cycle count"); + await user.click(screen.getByRole("button", { name: "Record stock adjustment" })); + const link = await screen.findByRole("link", { name: "Open adjusted stock ledger" }); + expect(link.getAttribute("href")).toBe(`/admin/material-stock/${id}`); + expect(body).toEqual({ materialId: id, warehouseId: id, delta: "0.125", reason: "Cycle count", idempotencyKey: expect.any(String) }); +}); + test("recording a material rate refreshes the selected currency history", async () => { let body: unknown; let finish: (() => void) | undefined;