feat/frontend-phase3 #11

Merged
mihir merged 2 commits from feat/frontend-phase3 into main 2026-11-12 00:46:00 +05:30
5 changed files with 200 additions and 2 deletions

View File

@ -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.

View File

@ -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<typeof goodsReceipt>) {
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;
}

View File

@ -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<typeof supplier>;
type Material = z.infer<typeof material>;
@ -191,6 +192,7 @@ function PurchaseOrderDetails({ id }: { id: string }) {
`${order.currency} ${line.unitPrice}`, `${order.currency} ${line.lineTotal}`,
])} />
<p>Merchandise total {order.currency} {order.merchandiseTotal}</p>
{order.status === "ISSUED" && <PurchaseOrderReceipts order={order} />}
{can("procurement.manage") && order.status === "DRAFT" && <>
<ConfirmAction label="Issue purchase order" message={`Issue ${order.reference} so it can receive deliveries?`}
onConfirm={async () => {

View File

@ -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<typeof purchaseOrder>;
type Receipt = z.infer<typeof goodsReceipt>;
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 (
<Panel title="Goods receipts">
<QueryView query={query}>{(receipts) => {
const receipt = receipts.find((entry) => entry.id === selected);
return <>
<Table head={["Received", "Delivery note", "Inspection", "Actions"]}
rowKeys={receipts.map((entry) => entry.id)}
rows={receipts.map((entry) => [
new Date(entry.createdAt).toLocaleString(), entry.deliveryNote || "—",
entry.lines.every((line) => line.inspection) ? "Inspected" : "Pending",
<Button onClick={() => select(entry.id)} aria-pressed={selected === entry.id}>
View receipt {entry.deliveryNote || entry.id.slice(0, 8)}
</Button>,
])} />
{receipt && <Panel title="Receipt details">
<Table head={["Material", "Delivered", "Accepted", "Rejected", "Reason"]}
rowKeys={receipt.lines.map((line) => 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) && (
<InspectionForm key={receipt.id} receipt={receipt} lineNames={lineNames} refresh={query.refetch} />
)}
</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>
) : (
<ActionForm label="Record goods receipt"
read={(data) => 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;
}
}}>
<Field name="deliveryNote" label="Delivery note" required={false} maxLength={80} />
{order.lines.map((line) => (
<Field key={line.id} name={line.id} label={`Delivered quantity for ${line.materialName} (${line.materialCode})`}
required={false} helper={`Use three decimal places in ${line.unit}. Leave blank for undelivered materials.`} />
))}
</ActionForm>
))}
</>;
}}</QueryView>
</Panel>
);
}
function InspectionForm({ receipt, lineNames, refresh }: {
receipt: Receipt;
lineNames: Map<string, string>;
refresh: () => Promise<unknown>;
}) {
const { request } = usePlatform();
return (
<ActionForm label="Finalize inspection" reset={false}
read={(data) => 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();
}}>
<p>Inspection is final. Enter accepted and rejected quantities with three decimal places for every line.</p>
{receipt.lines.map((line) => (
<fieldset key={line.id}>
<legend>{lineNames.get(line.purchaseOrderLineId) ?? line.purchaseOrderLineId} · Delivered {line.quantity}</legend>
<Field name={`${line.id}-accepted`} label="Accepted quantity" />
<Field name={`${line.id}-rejected`} label="Rejected quantity" value="0.000" />
<Field name={`${line.id}-reason`} label="Rejection reason" required={false} maxLength={500} helper="Required when any quantity is rejected." />
</fieldset>
))}
</ActionForm>
);
}

View File

@ -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,