feat: transfer and adjust material warehouse stock
continuous-integration/drone/push Build is passing Details

This commit is contained in:
mihir 2026-11-14 00:35:45 +05:30
parent 24ac154b82
commit 15d4b3397c
9 changed files with 322 additions and 13 deletions

View File

@ -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. - 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. - 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. - 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. - Live acceptance requires an organization and procurement test users. Exercise read-only and manage roles, inactive suppliers and materials, mixed currencies, below-minimum quantities, price snapshots and purchase order state conflicts.
- Supplier document UAT requires an uploader, an independent reviewer, and a read-only account. Through the deployed ingress, upload a valid PDF near the 2 MiB limit, verify that the uploader cannot decide on it, and check that a reader can download it only after approval. - Supplier document UAT requires an uploader, an independent reviewer, and a read-only account. Through the deployed ingress, upload a valid PDF near the 2 MiB limit, verify that the uploader cannot decide on it, and check that a reader can download it only after approval.
- BOM UAT should activate a second revision and confirm the previous revision becomes superseded. Repeat for the other BOM type and verify its active revision is independent. Check that inactive materials and stale drafts are rejected. - BOM UAT should activate a second revision and confirm the previous revision becomes superseded. Repeat for the other BOM type and verify its active revision is independent. Check that inactive materials and stale drafts are rejected.
- 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. - 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.

View File

@ -73,6 +73,10 @@ function Router() {
</Route> </Route>
<Route path="/admin/inventory">{() => <InventoryPage />}</Route> <Route path="/admin/inventory">{() => <InventoryPage />}</Route>
<Route path="/admin/material-stock">{() => <MaterialStockPage />}</Route> <Route path="/admin/material-stock">{() => <MaterialStockPage />}</Route>
<Route path="/admin/material-stock/adjust">{() => <MaterialStockPage adjust />}</Route>
<Route path="/admin/material-stock/adjust/:id">
{(params) => <MaterialStockPage adjust id={params.id} />}
</Route>
<Route path="/admin/material-stock/:id"> <Route path="/admin/material-stock/:id">
{(params) => <MaterialStockPage id={params.id} />} {(params) => <MaterialStockPage id={params.id} />}
</Route> </Route>

View File

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

View File

@ -3,6 +3,8 @@ import { uuid, warehouse } from "./commerce.ts";
import { material } from "./procurement.ts"; import { material } from "./procurement.ts";
const quantity = z.string().regex(/^\d{1,9}\.\d{3}$/); 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({ export const receiptPostingInput = z.object({
warehouseId: uuid, warehouseId: uuid,
@ -33,6 +35,43 @@ export const materialStockItem = z.object({
export const materialStockEntry = z.object({ export const materialStockEntry = z.object({
id: uuid, id: uuid,
kind: z.string(), kind: z.string(),
delta: z.string().regex(/^-?\d{1,9}\.\d{3}$/), delta: signedQuantity,
createdAt: z.string().datetime(), 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();

View File

@ -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<typeof materialStockItem>;
type Adjustment = z.infer<typeof materialAdjustment>;
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 <>
<Transfers stock={stock} write={can("inventory.manage")} />
<AdjustmentHistory materialId={stock.material.id} warehouseId={stock.warehouse.id} unit={stock.material.unit} />
{can("inventory.adjust") && <MaterialAdjustmentForm stock={stock} />}
</>;
}
function Transfers({ stock, write }: { stock: Stock; write: boolean }) {
const [offset, setOffset] = useState(0);
const [saved, setSaved] = useState<z.infer<typeof materialTransfer>>();
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 <Panel title="Warehouse transfers for this material">
{saved && <Alert severity="success">Transferred {saved.quantity} {stock.material.unit}. <WorkspaceLink href={`${stockRoute}/${saved.toStockItemId}`}>Open destination ledger</WorkspaceLink></Alert>}
{write && (pending ? (
<ActionForm label="Retry material transfer" read={() => ({})} submit={submit}>
<Alert severity="warning">Retrying uses the original quantity {pending.quantity} {stock.material.unit} and destination warehouse {pending.toWarehouseId}.</Alert>
</ActionForm>
) : <WarehousePostingForm label="Transfer material" warehouseLabel="Destination warehouse" excludeWarehouseId={stock.warehouse.id}
instruction={`Move stock from ${stock.warehouse.name}. Both warehouse ledgers update together.`}
reset read={(data) => ({
materialId: stock.material.id,
fromWarehouseId: stock.warehouse.id,
toWarehouseId: readText(data, "warehouseId"),
quantity: readText(data, "quantity").trim(),
})} submit={submit}>
<Field name="quantity" label={`Quantity to transfer (${stock.material.unit})`} maxLength={13} helper="Enter a positive quantity with three decimal places." />
</WarehousePostingForm>)}
<QueryView query={query}>{(rows) => <>
<Table head={["Time", "Quantity", "Source", "Destination"]} rowKeys={rows.map((row) => row.id)}
rows={rows.map((row) => [
new Date(row.createdAt).toLocaleString(), `${row.quantity} ${stock.material.unit}`,
<WorkspaceLink href={`${stockRoute}/${row.fromStockItemId}`}>{row.fromWarehouseId === stock.warehouse.id ? stock.warehouse.name : "Source ledger"}</WorkspaceLink>,
<WorkspaceLink href={`${stockRoute}/${row.toStockItemId}`}>{row.toWarehouseId === stock.warehouse.id ? stock.warehouse.name : "Destination ledger"}</WorkspaceLink>,
])} />
<Pager offset={offset} count={rows.length} onPage={setOffset} />
</>}</QueryView>
</Panel>;
}
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 <Panel title="Warehouse adjustments for this material">
<QueryView query={query}>{(rows) => <>
<Table head={["Time", "Quantity change", "Reason"]} rowKeys={rows.map((row) => row.id)}
rows={rows.map((row) => [new Date(row.createdAt).toLocaleString(), `${signed(row.delta)} ${unit}`, row.reason])} />
<Pager offset={offset} count={rows.length} onPage={setOffset} />
</>}</QueryView>
</Panel>;
}
export function MaterialAdjustmentForm({ stock, materialId }: { stock?: Stock; materialId?: string }) {
const [saved, setSaved] = useState<Adjustment>();
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 && <Field name="materialId" label="Material ID" maxLength={36} />}
<Field name="delta" label={stock ? `Quantity change (${stock.material.unit})` : "Quantity change"}
maxLength={14} helper="Use three decimal places in the material’s native unit." />
<Field name="reason" label="Adjustment reason" maxLength={200} />
</>;
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 <Panel title="Adjust material stock">
{materialId && <p className="workspace-id">Material ID {materialId}</p>}
{saved && <Alert severity="success">Recorded {signed(saved.delta)}. <WorkspaceLink href={`${stockRoute}/${saved.stockItemId}`}>Open adjusted stock ledger</WorkspaceLink></Alert>}
{pending ? (
<ActionForm label="Retry stock adjustment" read={() => ({})} submit={submit}>
<Alert severity="warning">Retrying uses the original change {signed(pending.delta)} and reason. Warehouse {pending.warehouseId}.</Alert>
</ActionForm>
) : stock ? (
<ActionForm label="Record stock adjustment" read={read} submit={submit}>
<p>{instruction}</p>
{fields}
</ActionForm>
) : <WarehousePostingForm label="Record stock adjustment" instruction={instruction} read={read} submit={submit} reset>{fields}</WarehousePostingForm>}
</Panel>;
}
function signed(delta: string) {
return delta.startsWith("-") ? delta : `+${delta}`;
}

View File

@ -5,13 +5,17 @@ import { WorkspaceShell } from "@/components/WorkspaceShell";
import { Pager, Panel, QueryView, Table, WorkspaceLink, usePrivateQuery } from "@/components/WorkspaceTools"; import { Pager, Panel, QueryView, Table, WorkspaceLink, usePrivateQuery } from "@/components/WorkspaceTools";
import { uuid } from "@/lib/commerce"; import { uuid } from "@/lib/commerce";
import { materialStockEntry, materialStockItem } from "@/lib/material-stock"; import { materialStockEntry, materialStockItem } from "@/lib/material-stock";
import { usePlatform } from "@/lib/platform";
import { MaterialAdjustmentForm, MaterialStockMovements } from "./MaterialStockMovements";
const stockPath = "/inventory/material-stock-items"; const stockPath = "/inventory/material-stock-items";
function StockList() { function StockList() {
const { can } = usePlatform();
const [offset, setOffset] = useState(0); const [offset, setOffset] = useState(0);
const query = usePrivateQuery(`${stockPath}?limit=25&offset=${offset}`, z.array(materialStockItem)); const query = usePrivateQuery(`${stockPath}?limit=25&offset=${offset}`, z.array(materialStockItem));
return <Panel title="Warehouse balances"> return <Panel title="Warehouse balances">
{can("inventory.adjust") && <p><WorkspaceLink href="/admin/material-stock/adjust">Record a material adjustment</WorkspaceLink></p>}
<QueryView query={query}>{(rows) => <> <QueryView query={query}>{(rows) => <>
<Table head={["Material", "Warehouse", "On hand", "Ledger"]} rowKeys={rows.map((row) => row.id)} <Table head={["Material", "Warehouse", "On hand", "Ledger"]} rowKeys={rows.map((row) => row.id)}
rows={rows.map((row) => [ rows={rows.map((row) => [
@ -41,14 +45,26 @@ function StockLedger({ id }: { id: string }) {
])} /> ])} />
<Pager offset={offset} count={rows.length} onPage={setOffset} /> <Pager offset={offset} count={rows.length} onPage={setOffset} />
</>}</QueryView> </>}</QueryView>
<QueryView query={item}>{(row) => <MaterialStockMovements stock={row} />}</QueryView>
</Panel>; </Panel>;
} }
export default function MaterialStockPage({ id }: { id?: string }) { export default function MaterialStockPage({ id, adjust = false }: { id?: string; adjust?: boolean }) {
const parsed = uuid.safeParse(id); const parsed = uuid.safeParse(id);
return <WorkspaceShell title="Material Stock" permission="inventory.read"> return <WorkspaceShell title="Material Stock" permission="inventory.read">
{!id ? <StockList /> : parsed.success ? ( {adjust ? <AdjustmentRoute materialId={id} /> : !id ? <StockList /> : parsed.success ? (
<StockLedger key={parsed.data} id={parsed.data} /> <StockLedger key={parsed.data} id={parsed.data} />
) : <Alert severity="warning">Invalid stock item ID.</Alert>} ) : <Alert severity="warning">Invalid stock item ID.</Alert>}
</WorkspaceShell>; </WorkspaceShell>;
} }
function AdjustmentRoute({ materialId }: { materialId?: string }) {
const { can } = usePlatform();
const id = uuid.safeParse(materialId);
return <>
<WorkspaceLink href="/admin/material-stock">All material stock</WorkspaceLink>
{!can("inventory.adjust") ? <Alert severity="warning">Your account does not have permission to adjust material stock.</Alert> :
materialId && !id.success ? <Alert severity="warning">Invalid material ID.</Alert> :
<MaterialAdjustmentForm key={id.data ?? "new"} materialId={id.data} />}
</>;
}

View File

@ -39,6 +39,9 @@ function Directory({ materials }: { materials: boolean }) {
<> <>
{can("procurement.manage") && <Button onClick={() => select(row.id)} aria-label={`Edit ${row.name}`}>Edit</Button>} {can("procurement.manage") && <Button onClick={() => select(row.id)} aria-label={`Edit ${row.name}`}>Edit</Button>}
{"kind" in row && can("cost.read") && <WorkspaceLink href={`/admin/material-cost-rates/${row.id}`}>Cost rates for {row.name}</WorkspaceLink>} {"kind" in row && can("cost.read") && <WorkspaceLink href={`/admin/material-cost-rates/${row.id}`}>Cost rates for {row.name}</WorkspaceLink>}
{"kind" in row && can("inventory.adjust") && can("inventory.read") && (
<div><WorkspaceLink href={`/admin/material-stock/adjust/${row.id}`}>Adjust stock for {row.name}</WorkspaceLink></div>
)}
{"contactName" in row && <WorkspaceLink href={`/admin/procurement/suppliers/${row.id}`}>Supply terms and orders for {row.name}</WorkspaceLink>} {"contactName" in row && <WorkspaceLink href={`/admin/procurement/suppliers/${row.id}`}>Supply terms and orders for {row.name}</WorkspaceLink>}
{"contactName" in row && can("supplier_document.read") && ( {"contactName" in row && can("supplier_document.read") && (
<> · <WorkspaceLink href={`/admin/supplier-documents/${row.id}`}>Documents for {row.name}</WorkspaceLink></> <> · <WorkspaceLink href={`/admin/supplier-documents/${row.id}`}>Documents for {row.name}</WorkspaceLink></>

View File

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

View File

@ -20,6 +20,7 @@ import ProductionBatchesPage from "../src/pages/ProductionBatchesPage";
import { CompletedBatchOperations } from "../src/pages/CompletedBatchOperations"; import { CompletedBatchOperations } from "../src/pages/CompletedBatchOperations";
import { BatchCostSnapshot } from "../src/pages/CostingPanels"; import { BatchCostSnapshot } from "../src/pages/CostingPanels";
import MaterialCostRatesPage from "../src/pages/MaterialCostRatesPage"; import MaterialCostRatesPage from "../src/pages/MaterialCostRatesPage";
import MaterialStockPage from "../src/pages/MaterialStockPage";
import { batchDetail } from "../src/lib/production"; import { batchDetail } from "../src/lib/production";
import theme from "../src/theme"; import theme from "../src/theme";
import { Switch, Route } from "wouter"; import { Switch, Route } from "wouter";
@ -183,6 +184,78 @@ function harness(children: ReactNode) {
return { client, ...result }; 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(<MaterialStockPage id={id} />);
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(<MaterialStockPage adjust id={id} />);
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 () => { test("recording a material rate refreshes the selected currency history", async () => {
let body: unknown; let body: unknown;
let finish: (() => void) | undefined; let finish: (() => void) | undefined;