From 1f14df39d53be11600980a09f4fb26cdc6d64a99 Mon Sep 17 00:00:00 2001 From: mihir Date: Thu, 12 Nov 2026 00:30:57 +0530 Subject: [PATCH] feat: add supplier procurement and purchase order workflows --- docs/PHASES.md | 9 +- src/App.tsx | 13 ++ src/components/WorkspaceShell.tsx | 3 + src/lib/procurement.ts | 69 +++++++++ src/pages/ProcurementPage.tsx | 228 ++++++++++++++++++++++++++++++ test/procurement.test.ts | 46 ++++++ test/workflows.ui.test.tsx | 19 +++ 7 files changed, 386 insertions(+), 1 deletion(-) create mode 100644 src/lib/procurement.ts create mode 100644 src/pages/ProcurementPage.tsx create mode 100644 test/procurement.test.ts diff --git a/docs/PHASES.md b/docs/PHASES.md index 02b25d6..604568e 100644 --- a/docs/PHASES.md +++ b/docs/PHASES.md @@ -25,4 +25,11 @@ Use existing MUI theme and React Query. Query keys include organization. Search ## Phase 2 implementation status — 12 October 2026 -Customer and administration screens are implemented, with recovery, pricing, stock lifecycle and quality gates. See UAT-PHASE2.md and RELEASE-CHECKLIST.md. Authenticated UAT, container/ingress verification and production sign-off remain pending; Phase 3 has not started. +Customer and administration screens are implemented, with recovery, pricing, stock lifecycle and quality gates. See UAT-PHASE2.md and RELEASE-CHECKLIST.md. Authenticated UAT, container/ingress verification and production sign-off remain pending. + +## Phase 3 implementation status + +- 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. +- Receipts and QC, supplier invoices/payments/documents, BOMs, production and packaging, costing, and material warehouse stock 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 1e8eb63..1bb0518 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -28,6 +28,10 @@ const AuditPage = lazy(() => ); const CatalogAdminPage = lazy(() => import("@/pages/CatalogAdminPage")); const InventoryPage = lazy(() => import("@/pages/InventoryPage")); +const ProcurementPage = lazy(() => import("@/pages/ProcurementPage")); +const PurchaseOrdersPage = lazy(() => + import("@/pages/ProcurementPage").then((module) => ({ default: module.PurchaseOrdersPage })), +); const OffersPage = lazy(() => import("@/pages/OffersPage")); const RecoveryPage = lazy(() => import("@/pages/RecoveryPage")); const NotFound = lazy(() => import("@/pages/not-found")); @@ -67,6 +71,15 @@ function Router() { {(params) => } {() => } + {() => } + {() => } + + {(params) => } + + {() => } + + {(params) => } + {() => } {() => } {() => } diff --git a/src/components/WorkspaceShell.tsx b/src/components/WorkspaceShell.tsx index 87a6653..998b233 100644 --- a/src/components/WorkspaceShell.tsx +++ b/src/components/WorkspaceShell.tsx @@ -58,6 +58,9 @@ export function WorkspaceNavigation() { permission: "inventory.read", }, { label: "Coupons", path: "/admin/coupons", permission: "coupons.manage" }, + { 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: "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/procurement.ts b/src/lib/procurement.ts new file mode 100644 index 0000000..e2adbe8 --- /dev/null +++ b/src/lib/procurement.ts @@ -0,0 +1,69 @@ +import { z } from "zod"; +import { currency, uuid } from "./commerce.ts"; + +const plainText = (max: number, min = 1) => + z.string().trim().min(min).max(max).regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text"); +const directoryInput = z.object({ + name: plainText(160), + code: z.string().trim().toUpperCase().max(32).regex(/^[A-Z0-9][A-Z0-9_-]*$/, "Use letters, numbers, hyphens or underscores"), + active: z.boolean(), +}); +export const supplierInput = directoryInput.extend({ + contactName: plainText(160), + email: z.string().email().max(254).toLowerCase(), + phone: z.string().trim().regex(/^\+?[0-9 ()-]{7,24}$/, "Enter a valid phone number").max(24), +}).strict(); +export const materialInput = directoryInput.extend({ + kind: z.enum(["WAX", "FRAGRANCE", "WICK", "DYE", "VESSEL", "PACKAGING", "LABEL", "OTHER"]), + unit: z.enum(["GRAM", "KILOGRAM", "MILLILITRE", "LITRE", "PIECE", "METRE"]), +}).strict(); +export const supplier = supplierInput.extend({ id: uuid }).strip(); +export const material = materialInput.extend({ id: uuid }).strip(); + +const quantity = z.string().regex(/^(0|[1-9]\d{0,8})\.\d{3}$/, "Enter exactly three decimal places").refine((value) => value !== "0.000", "Quantity must be positive"); +export const supplyTermsInput = z.object({ + supplierSku: plainText(64, 0), + leadTimeDays: z.number().int().min(0).max(365), + minOrderQuantity: quantity, + unitPrice: z.string().regex(/^(0|[1-9]\d{0,8})\.\d{2}$/, "Enter exactly two decimal places"), + currency, + active: z.boolean(), +}).strict(); + +// Prisma serializes Decimal values without trailing zeroes. +const decimalResponse = z.string().regex(/^\d+(\.\d+)?$/); +export const supplyTerms = supplyTermsInput.extend({ + id: uuid, + materialId: uuid, + minOrderQuantity: decimalResponse, + unitPrice: decimalResponse, +}).strip(); +export const supplierMaterial = supplyTerms.extend({ material }); + +export const purchaseOrderInput = z.object({ + supplierId: uuid, + expectedDeliveryDate: z.string().date().optional(), + lines: z.array(z.object({ materialId: uuid, quantity }).strict()).min(1, "Enter a quantity for at least one material").max(100).refine( + (lines) => new Set(lines.map((line) => line.materialId)).size === lines.length, + "Select each material once", + ), +}).strict(); + +export const purchaseOrder = z.object({ + id: uuid, + reference: z.string(), + status: z.enum(["DRAFT", "ISSUED", "CANCELLED"]), + currency, + supplier: supplier.pick({ id: true, name: true }), + expectedDeliveryAt: z.string().datetime().nullable(), + merchandiseTotal: decimalResponse, + lines: z.array(z.object({ + id: uuid, + materialName: z.string(), + materialCode: z.string(), + quantity: decimalResponse, + unit: materialInput.shape.unit, + unitPrice: decimalResponse, + lineTotal: decimalResponse, + })), +}); diff --git a/src/pages/ProcurementPage.tsx b/src/pages/ProcurementPage.tsx new file mode 100644 index 0000000..61ce9af --- /dev/null +++ b/src/pages/ProcurementPage.tsx @@ -0,0 +1,228 @@ +import { useState } from "react"; +import { z } from "zod"; +import Button from "@mui/material/Button"; +import { WorkspaceShell } from "@/components/WorkspaceShell"; +import { ActionForm, Check, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools"; +import { usePlatform } from "@/lib/platform"; +import { currency, uuid } from "@/lib/commerce"; +import { material, materialInput, purchaseOrder, purchaseOrderInput, supplier, supplierInput, supplierMaterial, supplyTerms, supplyTermsInput } from "@/lib/procurement"; +import { useLocation } from "wouter"; +import Alert from "@mui/material/Alert"; +import { ConfirmAction } from "@/components/ConfirmAction"; +import { isUnknownOutcome } from "@/lib/api"; + +type Supplier = z.infer; +type Material = z.infer; +const options = (values: readonly string[]) => values.map((value) => ({ value, label: value })); + +function Directory({ materials }: { materials: boolean }) { + const { can, request } = usePlatform(); + const [offset, setOffset] = useState(0); + const [selected, select] = useState(""); + const path = materials ? "/materials" : "/suppliers"; + const schema = z.union([supplier, material]); + const listSchema: z.ZodType<(Supplier | Material)[]> = materials ? z.array(material) : z.array(supplier); + const query = usePrivateQuery(`${path}?limit=25&offset=${offset}`, listSchema); + return ( + + + {(rows) => { + const record = rows.find((row) => row.id === selected); + return <> + row.id)} + rows={rows.map((row) => [ + row.name, row.code, + "kind" in row ? <>{row.kind} · {row.unit}
ID: {row.id} : `${row.contactName} · ${row.email} · ${row.phone}`, + row.active ? "Active" : "Inactive", + <> + {can("procurement.manage") && } + {"contactName" in row && Supply terms and orders for {row.name}} + , + ])} /> + { select(""); setOffset(next); }} /> + {can("procurement.manage") && <> + {record && } + { + await request(record ? `${path}/${record.id}` : path, schema, { + method: record ? "PUT" : "POST", + body: (materials ? materialInput : supplierInput).parse(value), + }); + await query.refetch(); + }} /> + } + ; + }} + + + ); +} + +function DirectoryForm({ materials, record, submit }: { + materials: boolean; + record?: Supplier | Material; + submit: (value: unknown) => Promise; +}) { + const detail = record && "kind" in record ? record : undefined; + const contact = record && "contactName" in record ? record : undefined; + return ( + ({ ...Object.fromEntries(data), active: data.has("active") })}> + + + {materials ? <> + + + : <> + + + + } + + + ); +} + +function SupplierTerms({ id }: { id: string }) { + const { can, request } = usePlatform(); + const [, navigate] = useLocation(); + const query = usePrivateQuery(`/suppliers/${id}/materials`, z.array(supplierMaterial)); + const [selected, select] = useState(""); + const [draftUncertain, setDraftUncertain] = useState(false); + return + Supplier directory + {(rows) => { + const terms = rows.find((row) => row.materialId === selected); + return <> +
row.id)} rows={rows.map((row) => [ + row.material.name, row.supplierSku || "—", `${row.minOrderQuantity} ${row.material.unit}`, + `${row.currency} ${row.unitPrice}`, `${row.leadTimeDays} days`, row.active ? "Active" : "Inactive", + can("procurement.manage") && , + ])} /> + {can("procurement.manage") && <> + {terms && } + ({ + materialId: terms?.materialId ?? uuid.parse(readText(data, "materialId").trim()), + body: supplyTermsInput.parse({ + ...Object.fromEntries([...data].filter(([name]) => name !== "materialId")), + leadTimeDays: Number(readText(data, "leadTimeDays")), + active: data.has("active"), + }), + })} + submit={async (value) => { + const input = z.object({ materialId: uuid, body: supplyTermsInput }).parse(value); + await request(`/suppliers/${id}/materials/${input.materialId}`, supplyTerms, { method: "PUT", body: input.body }); + await query.refetch(); + }}> + {terms ?

{terms.material.name}

: } + + + + + + +
+ } + {can("procurement.manage") && rows.some((row) => row.active && row.material.active) && ( + + Enter quantities for the materials to order. The backend applies current supplier terms and snapshots prices when the draft is saved. + {draftUncertain ? + The server may have saved the draft. Check purchase orders before submitting again. + : purchaseOrderInput.parse({ + supplierId: id, + expectedDeliveryDate: readText(data, "expectedDeliveryDate") || undefined, + lines: rows.filter((row) => row.active && row.material.active).flatMap((row) => { + const quantity = readText(data, row.materialId).trim(); + return quantity ? [{ materialId: row.materialId, quantity }] : []; + }), + })} + submit={async (body) => { + try { + const order = await request("/purchase-orders", purchaseOrder, { method: "POST", body }); + navigate(`/admin/purchase-orders/${order.id}`); + } catch (error) { + if (isUnknownOutcome(error)) setDraftUncertain(true); + throw error; + } + }}> + + {rows.filter((row) => row.active && row.material.active).map((row) => ( + + ))} + } + + )} + ; + }} + ; +} + +function PurchaseOrders() { + const [offset, setOffset] = useState(0); + const query = usePrivateQuery(`/purchase-orders?limit=25&offset=${offset}`, z.array(purchaseOrder)); + return +

To create a draft, choose a supplier and open its supply terms.

+ Supplier directory + {(rows) => <> +
row.id)} + rows={rows.map((row) => [ + {row.reference}, + row.supplier.name, row.status, `${row.currency} ${row.merchandiseTotal}`, + ])} /> + + } + ; +} + +function PurchaseOrderDetails({ id }: { id: string }) { + const { can, request } = usePlatform(); + const query = usePrivateQuery(`/purchase-orders/${id}`, purchaseOrder); + return {(order) => + All purchase orders +

{order.supplier.name} · {order.status}

+ {order.expectedDeliveryAt &&

Expected delivery {order.expectedDeliveryAt.slice(0, 10)}

} +
line.id)} + rows={order.lines.map((line) => [ + `${line.materialName} (${line.materialCode})`, `${line.quantity} ${line.unit}`, + `${order.currency} ${line.unitPrice}`, `${order.currency} ${line.lineTotal}`, + ])} /> +

Merchandise total {order.currency} {order.merchandiseTotal}

+ {can("procurement.manage") && order.status === "DRAFT" && <> + { + await request(`/purchase-orders/${id}/issue`, purchaseOrder, { method: "POST" }); + await query.refetch(); + }} /> + { + await request(`/purchase-orders/${id}/cancel`, purchaseOrder, { method: "POST" }); + await query.refetch(); + }} /> + } + }; +} + +export function PurchaseOrdersPage({ orderId }: { orderId?: string }) { + const id = uuid.safeParse(orderId); + return + {orderId ? id.success ? : Invalid purchase order ID. : } + ; +} + +function padDecimal(value: string, scale: number) { + const [whole, fraction = ""] = value.split("."); + return `${whole}.${fraction.padEnd(scale, "0")}`; +} + +export default function ProcurementPage({ materials = false, supplierId }: { materials?: boolean; supplierId?: string }) { + const id = uuid.safeParse(supplierId); + return ( + + {supplierId ? id.success ? :

Invalid supplier ID.

: } +
+ ); +} diff --git a/test/procurement.test.ts b/test/procurement.test.ts new file mode 100644 index 0000000..781857c --- /dev/null +++ b/test/procurement.test.ts @@ -0,0 +1,46 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { materialInput, purchaseOrderInput, supplierInput, supplyTerms, supplyTermsInput } from "../src/lib/procurement.ts"; + +const id = "d66c798a-f764-4b88-8d13-ace328ff1010"; +const terms = { + supplierSku: "", + leadTimeDays: 10, + minOrderQuantity: "0.125", + unitPrice: "900000000.01", + currency: "INR", + active: true, +}; + +test("supplier directory normalizes business codes and email addresses", () => { + const value = supplierInput.parse({ + name: " Candle supply ", code: " wax_1 ", contactName: "Supplier contact", + email: "CONTACT@example.com", phone: "+91 1234567890", active: true, + }); + assert.equal(value.name, "Candle supply"); + assert.equal(value.code, "WAX_1"); + assert.equal(value.email, "contact@example.com"); +}); + +test("material directory enforces backend material kinds and units", () => { + const value = { name: "Wax", code: "WAX", kind: "WAX", unit: "GRAM", active: true }; + assert.equal(materialInput.safeParse(value).success, true); + assert.equal(materialInput.safeParse({ ...value, unit: "BOX" }).success, false); +}); + +test("supply terms preserve precise string quantities and enforce request scale", () => { + assert.deepEqual(supplyTermsInput.parse(terms), terms); + assert.equal(supplyTermsInput.safeParse({ ...terms, minOrderQuantity: "0.000" }).success, false); + assert.equal(supplyTermsInput.safeParse({ ...terms, unitPrice: "2.1" }).success, false); + assert.equal(supplyTermsInput.safeParse({ ...terms, leadTimeDays: 366 }).success, false); + assert.equal(supplyTerms.parse({ ...terms, id, materialId: id, unitPrice: "2", minOrderQuantity: "1.5" }).unitPrice, "2"); +}); + +test("draft orders require distinct materials, exact quantities and a calendar date", () => { + const line = { materialId: id, quantity: "1.001" }; + const input = { supplierId: id, expectedDeliveryDate: "2026-12-01", lines: [line] }; + assert.deepEqual(purchaseOrderInput.parse(input), input); + assert.equal(purchaseOrderInput.safeParse({ ...input, lines: [line, { ...line, materialId: id.toUpperCase() }] }).success, false); + assert.equal(purchaseOrderInput.safeParse({ ...input, expectedDeliveryDate: "2026-02-31" }).success, false); + assert.equal(purchaseOrderInput.safeParse({ ...input, lines: [] }).success, false); +}); diff --git a/test/workflows.ui.test.tsx b/test/workflows.ui.test.tsx index 43a0706..49dd859 100644 --- a/test/workflows.ui.test.tsx +++ b/test/workflows.ui.test.tsx @@ -11,6 +11,7 @@ import { PlatformProvider, usePlatform } from "../src/lib/platform"; 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 theme from "../src/theme"; import { Switch, Route } from "wouter"; const id = "d66c798a-f764-4b88-8d13-ace328ff1010"; @@ -69,6 +70,24 @@ const session = { tokenType: "Bearer", expiresAt: new Date(Date.now() + 3600000).toISOString(), }; +test("procurement observers can read suppliers and cannot see write controls", async () => { + const fetch = vi.fn(async (url: string) => + url.endsWith("/auth/login") + ? json(session) + : url.endsWith("/auth/me") + ? json({ ...me, permissions: ["procurement.read"] }) + : url.includes("/suppliers?") + ? json([{ id, name: "Wax Supplier", code: "WAX", contactName: "Contact", email: "contact@example.com", phone: "+919999999999", active: true }]) + : Promise.reject(new Error("Unexpected private request")), + ); + vi.stubGlobal("fetch", fetch); + harness(); + await userEvent.setup().click(screen.getByText("Test login")); + const terms = await screen.findByRole("link", { name: "Supply terms and orders for Wax Supplier" }); + expect(terms.getAttribute("href")).toBe(`/admin/procurement/suppliers/${id}`); + expect(screen.queryByRole("button", { name: "Edit Wax Supplier" })).toBeNull(); + expect(screen.queryByRole("button", { name: "Create supplier" })).toBeNull(); +}); const address = { id, recipient: "Test Recipient", -- 2.40.1