Merge pull request 'feat: post inspected receipts to material warehouse stock' (#12) from feat/material-warehouse-posting into main
continuous-integration/drone/push Build is failing
Details
continuous-integration/drone/push Build is failing
Details
Reviewed-on: #12
This commit is contained in:
commit
c3d7aeffdc
|
|
@ -32,5 +32,6 @@ Customer and administration screens are implemented, with recovery, pricing, sto
|
|||
- Supplier and material directories support listing, creation and editing. Supplier material terms include SKU, lead time, minimum order quantity and unit price.
|
||||
- Staff can create a purchase order draft from supplier terms, review the backend price snapshots, then issue or cancel the draft.
|
||||
- Issued orders support partial goods receipts and final quality inspections, with exact accepted and rejected quantities and rejection reasons.
|
||||
- Supplier invoices/payments/documents, BOMs, production and packaging, costing, and material warehouse stock posting remain open.
|
||||
- Inspected receipts support idempotent posting to a warehouse. Staff can review material balances and movement ledgers.
|
||||
- Supplier invoices/payments/documents, BOMs, production and packaging, 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.
|
||||
|
|
|
|||
|
|
@ -28,6 +28,7 @@ const AuditPage = lazy(() =>
|
|||
);
|
||||
const CatalogAdminPage = lazy(() => import("@/pages/CatalogAdminPage"));
|
||||
const InventoryPage = lazy(() => import("@/pages/InventoryPage"));
|
||||
const MaterialStockPage = lazy(() => import("@/pages/MaterialStockPage"));
|
||||
const ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
|
||||
const PurchaseOrdersPage = lazy(() =>
|
||||
import("@/pages/ProcurementPage").then((module) => ({ default: module.PurchaseOrdersPage })),
|
||||
|
|
@ -67,6 +68,10 @@ function Router() {
|
|||
{(params) => <CatalogAdminPage id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/inventory">{() => <InventoryPage />}</Route>
|
||||
<Route path="/admin/material-stock">{() => <MaterialStockPage />}</Route>
|
||||
<Route path="/admin/material-stock/:id">
|
||||
{(params) => <MaterialStockPage id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/inventory/:id">
|
||||
{(params) => <InventoryPage id={params.id} />}
|
||||
</Route>
|
||||
|
|
|
|||
|
|
@ -61,6 +61,7 @@ export function WorkspaceNavigation() {
|
|||
{ label: "Suppliers", path: "/admin/procurement", permission: "procurement.read" },
|
||||
{ label: "Materials", path: "/admin/procurement/materials", permission: "procurement.read" },
|
||||
{ label: "Purchase orders", path: "/admin/purchase-orders", permission: "procurement.read" },
|
||||
{ label: "Material stock", path: "/admin/material-stock", permission: "inventory.read" },
|
||||
{ label: "Pricing", path: "/admin/pricing", permission: "pricing.manage" },
|
||||
{ label: "All orders", path: "/admin/orders", permission: "orders.read" },
|
||||
{ label: "Audit", path: "/admin/audit", permission: "audit.read" },
|
||||
|
|
|
|||
|
|
@ -0,0 +1,38 @@
|
|||
import { z } from "zod";
|
||||
import { uuid, warehouse } from "./commerce.ts";
|
||||
import { material } from "./procurement.ts";
|
||||
|
||||
const quantity = z.string().regex(/^\d{1,9}\.\d{3}$/);
|
||||
|
||||
export const receiptPostingInput = z.object({
|
||||
warehouseId: uuid,
|
||||
idempotencyKey: uuid,
|
||||
}).strict();
|
||||
|
||||
export const receiptPosting = z.object({
|
||||
id: uuid,
|
||||
receiptId: uuid,
|
||||
warehouseId: uuid,
|
||||
createdAt: z.string().datetime(),
|
||||
entries: z.array(z.object({
|
||||
id: uuid,
|
||||
stockItemId: uuid,
|
||||
receiptLineId: uuid,
|
||||
kind: z.literal("RECEIPT_ACCEPTED"),
|
||||
delta: quantity.refine((value) => value !== "0.000"),
|
||||
})),
|
||||
});
|
||||
|
||||
export const materialStockItem = z.object({
|
||||
id: uuid,
|
||||
warehouse,
|
||||
material,
|
||||
onHand: quantity,
|
||||
});
|
||||
|
||||
export const materialStockEntry = z.object({
|
||||
id: uuid,
|
||||
kind: z.string(),
|
||||
delta: z.string().regex(/^-?\d{1,9}\.\d{3}$/),
|
||||
createdAt: z.string().datetime(),
|
||||
});
|
||||
|
|
@ -40,5 +40,5 @@ export function useIdempotentCommand<T extends { idempotencyKey: string }, R>(
|
|||
throw error;
|
||||
}
|
||||
}
|
||||
return { run, uncertain };
|
||||
return { run, uncertain, pending: uncertain ? intent.current : null };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,54 @@
|
|||
import { useState } from "react";
|
||||
import { z } from "zod";
|
||||
import Alert from "@mui/material/Alert";
|
||||
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";
|
||||
|
||||
const stockPath = "/inventory/material-stock-items";
|
||||
|
||||
function StockList() {
|
||||
const [offset, setOffset] = useState(0);
|
||||
const query = usePrivateQuery(`${stockPath}?limit=25&offset=${offset}`, z.array(materialStockItem));
|
||||
return <Panel title="Warehouse balances">
|
||||
<QueryView query={query}>{(rows) => <>
|
||||
<Table head={["Material", "Warehouse", "On hand", "Ledger"]} rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [
|
||||
`${row.material.name} (${row.material.code})`, row.warehouse.name,
|
||||
`${row.onHand} ${row.material.unit}`,
|
||||
<WorkspaceLink href={`/admin/material-stock/${row.id}`}>Ledger for {row.material.name} at {row.warehouse.name}</WorkspaceLink>,
|
||||
])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function StockLedger({ id }: { id: string }) {
|
||||
const [offset, setOffset] = useState(0);
|
||||
const item = usePrivateQuery(`${stockPath}/${id}`, materialStockItem);
|
||||
const ledger = usePrivateQuery(`${stockPath}/${id}/ledger?limit=25&offset=${offset}`, z.array(materialStockEntry));
|
||||
return <Panel title="Material stock ledger">
|
||||
<WorkspaceLink href="/admin/material-stock">All material stock</WorkspaceLink>
|
||||
<QueryView query={item}>{(row) => (
|
||||
<p>{row.material.name} at {row.warehouse.name} · On hand {row.onHand} {row.material.unit}</p>
|
||||
)}</QueryView>
|
||||
<QueryView query={ledger}>{(rows) => <>
|
||||
<Table head={["Time", "Movement", "Quantity change"]} rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [
|
||||
new Date(row.createdAt).toLocaleString(), row.kind.replaceAll("_", " ").toLowerCase(),
|
||||
row.delta.startsWith("-") ? row.delta : `+${row.delta}`,
|
||||
])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
export default function MaterialStockPage({ id }: { id?: string }) {
|
||||
const parsed = uuid.safeParse(id);
|
||||
return <WorkspaceShell title="Material Stock" permission="inventory.read">
|
||||
{!id ? <StockList /> : parsed.success ? (
|
||||
<StockLedger key={parsed.data} id={parsed.data} />
|
||||
) : <Alert severity="warning">Invalid stock item ID.</Alert>}
|
||||
</WorkspaceShell>;
|
||||
}
|
||||
|
|
@ -6,6 +6,7 @@ import { ActionForm, Field, Panel, QueryView, Table, readText, usePrivateQuery }
|
|||
import { isUnknownOutcome } from "@/lib/api";
|
||||
import { goodsReceipt, parseInspection, purchaseOrder, receiptInput } from "@/lib/procurement";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { ReceiptStockPosting } from "./ReceiptStockPosting";
|
||||
|
||||
type Order = z.infer<typeof purchaseOrder>;
|
||||
type Receipt = z.infer<typeof goodsReceipt>;
|
||||
|
|
@ -42,6 +43,10 @@ export function PurchaseOrderReceipts({ order }: { order: Order }) {
|
|||
{can("procurement.manage") && receipt.lines.every((line) => !line.inspection) && (
|
||||
<InspectionForm key={receipt.id} receipt={receipt} lineNames={lineNames} refresh={query.refetch} />
|
||||
)}
|
||||
{can("inventory.read") && receipt.lines.every((line) => line.inspection) && (
|
||||
<ReceiptStockPosting key={receipt.id} receiptId={receipt.id}
|
||||
lineNames={new Map(receipt.lines.map((line) => [line.id, lineNames.get(line.purchaseOrderLineId) ?? line.purchaseOrderLineId]))} />
|
||||
)}
|
||||
</Panel>}
|
||||
{can("procurement.manage") && (uncertain ? (
|
||||
<Alert severity="warning">The server may have saved this receipt. Review the receipt list before recording the delivery again. <Button onClick={() => query.refetch()}>Refresh receipts</Button></Alert>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,92 @@
|
|||
import { useState } from "react";
|
||||
import { useQuery, 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 { 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";
|
||||
|
||||
export function ReceiptStockPosting({ receiptId, lineNames }: {
|
||||
receiptId: string;
|
||||
lineNames: Map<string, string>;
|
||||
}) {
|
||||
const { can, scope, request } = 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;
|
||||
}
|
||||
},
|
||||
});
|
||||
return <Panel title="Material warehouse posting">
|
||||
<QueryView query={query}>{(posting) => posting ? <>
|
||||
<p>Posted to warehouse {posting.warehouseId} on {new Date(posting.createdAt).toLocaleString()}.</p>
|
||||
<Table head={["Material", "Quantity posted", "Stock ledger"]}
|
||||
rowKeys={posting.entries.map((entry) => entry.id)}
|
||||
rows={posting.entries.map((entry) => [
|
||||
lineNames.get(entry.receiptLineId) ?? entry.receiptLineId,
|
||||
entry.delta,
|
||||
<WorkspaceLink href={`/admin/material-stock/${entry.stockItemId}`}>View stock ledger</WorkspaceLink>,
|
||||
])} />
|
||||
{!posting.entries.length && <p>The inspection accepted zero material. The posting recorded no stock movements.</p>}
|
||||
</> : can("inventory.manage") ? (
|
||||
<PostReceipt path={path} receiptId={receiptId} refresh={query.refetch} />
|
||||
) : <Alert severity="info">This receipt is awaiting warehouse posting.</Alert>}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function PostReceipt({ path, receiptId, refresh }: {
|
||||
path: string;
|
||||
receiptId: string;
|
||||
refresh: () => Promise<unknown>;
|
||||
}) {
|
||||
const { scope } = usePlatform();
|
||||
const client = useQueryClient();
|
||||
const command = useIdempotentCommand(path, receiptPostingInput, receiptPosting, receiptId);
|
||||
async function submit(input: unknown) {
|
||||
try {
|
||||
await command.run(input);
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.code === "MATERIAL_RECEIPT_ALREADY_POSTED") await refresh();
|
||||
throw error;
|
||||
}
|
||||
await client.invalidateQueries({
|
||||
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
|
||||
typeof queryKey[2] === "string" && queryKey[2].startsWith("/inventory/material-stock-items"),
|
||||
});
|
||||
await refresh();
|
||||
}
|
||||
return command.pending ? (
|
||||
<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>;
|
||||
}
|
||||
|
|
@ -12,6 +12,7 @@ import CartPage from "../src/pages/CartPage";
|
|||
import AccessPage, { RolesPage } from "../src/pages/AccessPage";
|
||||
import OrdersPage from "../src/pages/OrdersPage";
|
||||
import ProcurementPage from "../src/pages/ProcurementPage";
|
||||
import { ReceiptStockPosting } from "../src/pages/ReceiptStockPosting";
|
||||
import theme from "../src/theme";
|
||||
import { Switch, Route } from "wouter";
|
||||
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
|
||||
|
|
@ -173,6 +174,45 @@ function harness(children: ReactNode) {
|
|||
);
|
||||
return { client, ...result };
|
||||
}
|
||||
|
||||
test("receipt posting retries the same warehouse and key after a lost response", async () => {
|
||||
const attempts: unknown[] = [];
|
||||
const posting = {
|
||||
id, receiptId: id, warehouseId: id, createdAt: "2026-11-12T00:00:00.000Z",
|
||||
entries: [{ id, stockItemId: id, receiptLineId: id, kind: "RECEIPT_ACCEPTED", delta: "0.125" }],
|
||||
};
|
||||
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([{ id, name: "Main warehouse" }]);
|
||||
if (url.endsWith("/stock-posting")) {
|
||||
if (options?.method === "POST") {
|
||||
attempts.push(JSON.parse(String(options.body)));
|
||||
if (attempts.length === 1) throw new Error("Response lost");
|
||||
return json(posting);
|
||||
}
|
||||
return attempts.length ? json(posting) : json({ code: "MATERIAL_POSTING_NOT_FOUND" }, 404);
|
||||
}
|
||||
throw new Error(`Unexpected request ${url}`);
|
||||
}));
|
||||
function AuthorizedPosting() {
|
||||
const { can } = usePlatform();
|
||||
return can("inventory.read") ? <ReceiptStockPosting receiptId={id} lineNames={new Map([[id, "Wax"]])} /> : null;
|
||||
}
|
||||
harness(<AuthorizedPosting />);
|
||||
const user = userEvent.setup();
|
||||
await user.click(screen.getByText("Test login"));
|
||||
await user.selectOptions(await screen.findByRole("combobox", { name: "Destination warehouse" }), id);
|
||||
await user.click(screen.getByRole("button", { name: "Post accepted material" }));
|
||||
await user.click(await screen.findByRole("button", { name: "Retry warehouse posting" }));
|
||||
const ledger = await screen.findByRole("link", { name: "View stock ledger" });
|
||||
expect(ledger.getAttribute("href")).toBe(`/admin/material-stock/${id}`);
|
||||
expect(attempts).toHaveLength(2);
|
||||
expect(attempts[0]).toEqual({ warehouseId: id, idempotencyKey: expect.any(String) });
|
||||
expect(attempts[1]).toEqual(attempts[0]);
|
||||
expect(screen.getByText("0.125")).toBeTruthy();
|
||||
});
|
||||
|
||||
test("uncertain checkout replays identical input after the cart version changes", async () => {
|
||||
const attempts: unknown[] = [];
|
||||
let cartChanged = false;
|
||||
|
|
|
|||
Loading…
Reference in New Issue