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"; import { PurchaseOrderReceipts } from "./PurchaseOrderReceipts"; import { PurchaseOrderInvoices } from "./PurchaseOrderInvoices"; 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") && } {"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} )} , ])} /> { 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}

{order.status === "ISSUED" && } {order.status === "ISSUED" && } {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.

: }
); }