diff --git a/docs/PHASES.md b/docs/PHASES.md index ef40e47..4b5a31d 100644 --- a/docs/PHASES.md +++ b/docs/PHASES.md @@ -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. diff --git a/src/App.tsx b/src/App.tsx index 1bb0518..dd5cb4d 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -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) => } {() => } + {() => } + + {(params) => } + {(params) => } diff --git a/src/components/WorkspaceShell.tsx b/src/components/WorkspaceShell.tsx index 998b233..80ed3e8 100644 --- a/src/components/WorkspaceShell.tsx +++ b/src/components/WorkspaceShell.tsx @@ -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" }, diff --git a/src/lib/material-stock.ts b/src/lib/material-stock.ts new file mode 100644 index 0000000..1765366 --- /dev/null +++ b/src/lib/material-stock.ts @@ -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(), +}); diff --git a/src/lib/use-idempotent-command.ts b/src/lib/use-idempotent-command.ts index 19ee160..79bb8d4 100644 --- a/src/lib/use-idempotent-command.ts +++ b/src/lib/use-idempotent-command.ts @@ -40,5 +40,5 @@ export function useIdempotentCommand( throw error; } } - return { run, uncertain }; + return { run, uncertain, pending: uncertain ? intent.current : null }; } diff --git a/src/pages/MaterialStockPage.tsx b/src/pages/MaterialStockPage.tsx new file mode 100644 index 0000000..0caa232 --- /dev/null +++ b/src/pages/MaterialStockPage.tsx @@ -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 + {(rows) => <> + row.id)} + rows={rows.map((row) => [ + `${row.material.name} (${row.material.code})`, row.warehouse.name, + `${row.onHand} ${row.material.unit}`, + Ledger for {row.material.name} at {row.warehouse.name}, + ])} /> + + } + ; +} + +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 + All material stock + {(row) => ( +

{row.material.name} at {row.warehouse.name} ยท On hand {row.onHand} {row.material.unit}

+ )}
+ {(rows) => <> +
row.id)} + rows={rows.map((row) => [ + new Date(row.createdAt).toLocaleString(), row.kind.replaceAll("_", " ").toLowerCase(), + row.delta.startsWith("-") ? row.delta : `+${row.delta}`, + ])} /> + + } + ; +} + +export default function MaterialStockPage({ id }: { id?: string }) { + const parsed = uuid.safeParse(id); + return + {!id ? : parsed.success ? ( + + ) : Invalid stock item ID.} + ; +} diff --git a/src/pages/PurchaseOrderReceipts.tsx b/src/pages/PurchaseOrderReceipts.tsx index 446bcfb..403ad99 100644 --- a/src/pages/PurchaseOrderReceipts.tsx +++ b/src/pages/PurchaseOrderReceipts.tsx @@ -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; type Receipt = z.infer; @@ -42,6 +43,10 @@ export function PurchaseOrderReceipts({ order }: { order: Order }) { {can("procurement.manage") && receipt.lines.every((line) => !line.inspection) && ( )} + {can("inventory.read") && receipt.lines.every((line) => line.inspection) && ( + [line.id, lineNames.get(line.purchaseOrderLineId) ?? line.purchaseOrderLineId]))} /> + )} } {can("procurement.manage") && (uncertain ? ( The server may have saved this receipt. Review the receipt list before recording the delivery again. diff --git a/src/pages/ReceiptStockPosting.tsx b/src/pages/ReceiptStockPosting.tsx new file mode 100644 index 0000000..4020b3c --- /dev/null +++ b/src/pages/ReceiptStockPosting.tsx @@ -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; +}) { + 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 + {(posting) => posting ? <> +

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

+
entry.id)} + rows={posting.entries.map((entry) => [ + lineNames.get(entry.receiptLineId) ?? entry.receiptLineId, + entry.delta, + View stock ledger, + ])} /> + {!posting.entries.length &&

The inspection accepted zero material. The posting recorded no stock movements.

} + : can("inventory.manage") ? ( + + ) : This receipt is awaiting warehouse posting.} + ; +} + +function PostReceipt({ path, receiptId, refresh }: { + path: string; + receiptId: string; + refresh: () => Promise; +}) { + 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 ? ( + ({})} 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/workflows.ui.test.tsx b/test/workflows.ui.test.tsx index 49dd859..db262ce 100644 --- a/test/workflows.ui.test.tsx +++ b/test/workflows.ui.test.tsx @@ -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") ? : null; + } + harness(); + 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;