From 3d99cce0e40cf2a81935bbdfeef42d38ff05714a Mon Sep 17 00:00:00 2001 From: mihir Date: Thu, 12 Nov 2026 00:42:36 +0530 Subject: [PATCH] feat: record and inspect purchase order deliveries --- docs/PHASES.md | 3 +- src/lib/procurement.ts | 59 +++++++++++++- src/pages/ProcurementPage.tsx | 2 + src/pages/PurchaseOrderReceipts.tsx | 119 ++++++++++++++++++++++++++++ test/procurement.test.ts | 19 +++++ 5 files changed, 200 insertions(+), 2 deletions(-) create mode 100644 src/pages/PurchaseOrderReceipts.tsx diff --git a/docs/PHASES.md b/docs/PHASES.md index 604568e..ef40e47 100644 --- a/docs/PHASES.md +++ b/docs/PHASES.md @@ -31,5 +31,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. -- Receipts and QC, supplier invoices/payments/documents, BOMs, production and packaging, costing, and material warehouse stock remain open. +- 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. - 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/lib/procurement.ts b/src/lib/procurement.ts index e2adbe8..58a9d08 100644 --- a/src/lib/procurement.ts +++ b/src/lib/procurement.ts @@ -20,7 +20,8 @@ export const materialInput = directoryInput.extend({ 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"); +const fixedQuantity = z.string().regex(/^(0|[1-9]\d{0,8})\.\d{3}$/, "Enter exactly three decimal places"); +const quantity = fixedQuantity.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), @@ -67,3 +68,59 @@ export const purchaseOrder = z.object({ lineTotal: decimalResponse, })), }); + +export const receiptInput = z.object({ + deliveryNote: z.string().trim().min(1).max(80).optional(), + lines: z.array(z.object({ purchaseOrderLineId: uuid, quantity }).strict()).min(1).max(100) + .refine((lines) => new Set(lines.map((line) => line.purchaseOrderLineId)).size === lines.length), +}).strict(); + +const inspection = z.object({ + acceptedQuantity: decimalResponse, + rejectedQuantity: decimalResponse, + rejectionReason: z.string().nullable(), +}); + +export const goodsReceipt = z.object({ + id: uuid, + deliveryNote: z.string().nullable(), + createdAt: z.string().datetime(), + lines: z.array(z.object({ + id: uuid, + purchaseOrderLineId: uuid, + quantity: z.string().regex(/^\d+(\.\d{1,3})?$/), + inspection: inspection.nullable(), + })).min(1), +}); + +const inspectionInput = z.object({ + lines: z.array(z.object({ + receiptLineId: uuid, + acceptedQuantity: fixedQuantity, + rejectedQuantity: fixedQuantity, + rejectionReason: z.string().trim().min(1).max(500).optional(), + }).strict()).min(1).max(100), +}).strict(); + +const thousandths = (value: string) => { + const [whole, fraction = ""] = value.split("."); + return BigInt(whole + fraction.padEnd(3, "0")); +}; + +export function parseInspection(value: unknown, receipt: z.infer) { + const input = inspectionInput.parse(value); + const received = new Map(receipt.lines.map((line) => [line.id, line.quantity])); + if (input.lines.length !== received.size || new Set(input.lines.map((line) => line.receiptLineId)).size !== received.size) { + throw new Error("Enter one decision for each receipt line."); + } + for (const line of input.lines) { + const delivered = received.get(line.receiptLineId); + if (!delivered || thousandths(line.acceptedQuantity) + thousandths(line.rejectedQuantity) !== thousandths(delivered)) { + throw new Error("Accepted and rejected quantities must add up to the delivered quantity on each line."); + } + if (line.rejectedQuantity !== "0.000" && !line.rejectionReason) { + throw new Error("Enter a rejection reason for each rejected quantity."); + } + } + return input; +} diff --git a/src/pages/ProcurementPage.tsx b/src/pages/ProcurementPage.tsx index 61ce9af..9491cb9 100644 --- a/src/pages/ProcurementPage.tsx +++ b/src/pages/ProcurementPage.tsx @@ -10,6 +10,7 @@ import { useLocation } from "wouter"; import Alert from "@mui/material/Alert"; import { ConfirmAction } from "@/components/ConfirmAction"; import { isUnknownOutcome } from "@/lib/api"; +import { PurchaseOrderReceipts } from "./PurchaseOrderReceipts"; type Supplier = z.infer; type Material = z.infer; @@ -191,6 +192,7 @@ function PurchaseOrderDetails({ id }: { id: string }) { `${order.currency} ${line.unitPrice}`, `${order.currency} ${line.lineTotal}`, ])} />

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

+ {order.status === "ISSUED" && } {can("procurement.manage") && order.status === "DRAFT" && <> { diff --git a/src/pages/PurchaseOrderReceipts.tsx b/src/pages/PurchaseOrderReceipts.tsx new file mode 100644 index 0000000..446bcfb --- /dev/null +++ b/src/pages/PurchaseOrderReceipts.tsx @@ -0,0 +1,119 @@ +import { useState } from "react"; +import { z } from "zod"; +import Alert from "@mui/material/Alert"; +import Button from "@mui/material/Button"; +import { ActionForm, Field, Panel, QueryView, Table, readText, usePrivateQuery } from "@/components/WorkspaceTools"; +import { isUnknownOutcome } from "@/lib/api"; +import { goodsReceipt, parseInspection, purchaseOrder, receiptInput } from "@/lib/procurement"; +import { usePlatform } from "@/lib/platform"; + +type Order = z.infer; +type Receipt = z.infer; + +export function PurchaseOrderReceipts({ order }: { order: Order }) { + const { can, request } = usePlatform(); + const path = `/purchase-orders/${order.id}/receipts`; + const query = usePrivateQuery(path, z.array(goodsReceipt)); + const [selected, select] = useState(""); + const [uncertain, setUncertain] = useState(false); + const lineNames = new Map(order.lines.map((line) => [line.id, `${line.materialName} (${line.materialCode}) · ${line.unit}`])); + return ( + + {(receipts) => { + const receipt = receipts.find((entry) => entry.id === selected); + return <> + entry.id)} + rows={receipts.map((entry) => [ + new Date(entry.createdAt).toLocaleString(), entry.deliveryNote || "—", + entry.lines.every((line) => line.inspection) ? "Inspected" : "Pending", + , + ])} /> + {receipt && +
line.id)} + rows={receipt.lines.map((line) => [ + lineNames.get(line.purchaseOrderLineId) ?? line.purchaseOrderLineId, + line.quantity, line.inspection?.acceptedQuantity ?? "—", line.inspection?.rejectedQuantity ?? "—", + line.inspection?.rejectionReason ?? "—", + ])} /> + {can("procurement.manage") && receipt.lines.every((line) => !line.inspection) && ( + + )} + } + {can("procurement.manage") && (uncertain ? ( + The server may have saved this receipt. Review the receipt list before recording the delivery again. + ) : ( + receiptInput.parse({ + deliveryNote: readText(data, "deliveryNote").trim() || undefined, + lines: order.lines.flatMap((line) => { + const quantity = readText(data, line.id).trim(); + return quantity ? [{ purchaseOrderLineId: line.id, quantity }] : []; + }), + })} + submit={async (body) => { + try { + const saved = await request(path, goodsReceipt, { method: "POST", body }); + await query.refetch(); + select(saved.id); + } catch (error) { + if (isUnknownOutcome(error)) { + setUncertain(true); + await query.refetch(); + } + throw error; + } + }}> + + {order.lines.map((line) => ( + + ))} + + ))} + ; + }} + + ); +} + +function InspectionForm({ receipt, lineNames, refresh }: { + receipt: Receipt; + lineNames: Map; + refresh: () => Promise; +}) { + const { request } = usePlatform(); + return ( + parseInspection({ + lines: receipt.lines.map((line) => ({ + receiptLineId: line.id, + acceptedQuantity: readText(data, `${line.id}-accepted`).trim(), + rejectedQuantity: readText(data, `${line.id}-rejected`).trim(), + rejectionReason: readText(data, `${line.id}-reason`).trim() || undefined, + })), + }, receipt)} + submit={async (body) => { + try { + await request(`/goods-receipts/${receipt.id}/inspect`, goodsReceipt, { method: "POST", body }); + } catch (error) { + if (isUnknownOutcome(error)) await refresh(); + throw error; + } + await refresh(); + }}> +

Inspection is final. Enter accepted and rejected quantities with three decimal places for every line.

+ {receipt.lines.map((line) => ( +
+ {lineNames.get(line.purchaseOrderLineId) ?? line.purchaseOrderLineId} · Delivered {line.quantity} + + + +
+ ))} +
+ ); +} diff --git a/test/procurement.test.ts b/test/procurement.test.ts index 781857c..eba230f 100644 --- a/test/procurement.test.ts +++ b/test/procurement.test.ts @@ -1,8 +1,27 @@ import { test } from "node:test"; import assert from "node:assert/strict"; +import { goodsReceipt, parseInspection, receiptInput } from "../src/lib/procurement.ts"; import { materialInput, purchaseOrderInput, supplierInput, supplyTerms, supplyTermsInput } from "../src/lib/procurement.ts"; const id = "d66c798a-f764-4b88-8d13-ace328ff1010"; +test("partial receipts accept positive quantities and reject duplicate order lines", () => { + const line = { purchaseOrderLineId: id, quantity: "0.125" }; + assert.equal(receiptInput.safeParse({ lines: [line] }).success, true); + assert.equal(receiptInput.safeParse({ lines: [line, line] }).success, false); + assert.equal(receiptInput.safeParse({ lines: [{ ...line, quantity: "0.000" }] }).success, false); +}); + +test("inspection reconciles exact decimal quantities and requires a reason for rejects", () => { + const receipt = goodsReceipt.parse({ + id, deliveryNote: null, createdAt: "2026-11-12T00:00:00.000Z", + lines: [{ id, purchaseOrderLineId: id, quantity: "0.3", inspection: null }], + }); + const decision = { receiptLineId: id, acceptedQuantity: "0.100", rejectedQuantity: "0.200", rejectionReason: "Damaged" }; + assert.deepEqual(parseInspection({ lines: [decision] }, receipt), { lines: [decision] }); + assert.throws(() => parseInspection({ lines: [{ ...decision, acceptedQuantity: "0.101" }] }, receipt), /add up/); + assert.throws(() => parseInspection({ lines: [{ ...decision, rejectionReason: undefined }] }, receipt), /rejection reason/); + assert.throws(() => parseInspection({ lines: [decision, decision] }, receipt), /one decision/); +}); const terms = { supplierSku: "", leadTimeDays: 10, -- 2.40.1