From cd6def2f7fa8fcbd00c7f4a671b30bcc09ff6ebe Mon Sep 17 00:00:00 2001 From: mihir Date: Thu, 12 Nov 2026 00:57:04 +0530 Subject: [PATCH] feat: record supplier invoices and payments --- docs/PHASES.md | 3 +- src/lib/supplier-finance.ts | 69 ++++++++++ src/pages/ProcurementPage.tsx | 2 + src/pages/PurchaseOrderInvoices.tsx | 190 ++++++++++++++++++++++++++++ test/supplier-finance.test.ts | 31 +++++ test/workflows.ui.test.tsx | 52 ++++++++ 6 files changed, 346 insertions(+), 1 deletion(-) create mode 100644 src/lib/supplier-finance.ts create mode 100644 src/pages/PurchaseOrderInvoices.tsx create mode 100644 test/supplier-finance.test.ts diff --git a/docs/PHASES.md b/docs/PHASES.md index 4b5a31d..e1ff9bb 100644 --- a/docs/PHASES.md +++ b/docs/PHASES.md @@ -33,5 +33,6 @@ Customer and administration screens are implemented, with recovery, pricing, sto - 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. - 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. +- Issued orders support supplier invoices, payment records, reversals and voids. The backend enforces accepted quantities, outstanding balances and correction rules. +- Supplier 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/lib/supplier-finance.ts b/src/lib/supplier-finance.ts new file mode 100644 index 0000000..08d9dac --- /dev/null +++ b/src/lib/supplier-finance.ts @@ -0,0 +1,69 @@ +import { z } from "zod"; +import { currency, uuid } from "./commerce.ts"; + +const reference = (max: number) => + z.string().trim().min(1).max(max).regex(/^[A-Za-z0-9][A-Za-z0-9._/-]*$/).toUpperCase(); +const amount = z.string().regex(/^(0|[1-9]\d{0,9})\.\d{2}$/, "Use two decimal places"); +const decimal = z.string().regex(/^\d+(\.\d+)?$/); +const reason = z.string().trim().min(1).max(500); +const correction = z.object({ reason }); +export const correctionInput = correction.strict(); + +export const invoiceInput = z.object({ + invoiceNumber: reference(64), + invoiceDate: z.string().date(), + taxAmount: amount, + shippingAmount: amount, + lines: z.array(z.object({ + purchaseOrderLineId: uuid, + quantity: z.string().regex(/^(0|[1-9]\d{0,8})\.\d{3}$/, "Use three decimal places") + .refine((value) => value !== "0.000", "Quantity must be positive"), + }).strict()).min(1, "Enter a quantity for at least one line").max(100) + .refine((lines) => new Set(lines.map((line) => line.purchaseOrderLineId)).size === lines.length), +}).strict(); + +export const supplierInvoice = z.object({ + id: uuid, + invoiceNumber: z.string(), + invoiceDate: z.string().datetime(), + currency, + merchandiseTotal: decimal, + taxAmount: decimal, + shippingAmount: decimal, + payableTotal: decimal, + void: correction.nullable(), + lines: z.array(z.object({ + id: uuid, + purchaseOrderLineId: uuid, + quantity: decimal, + unitPrice: decimal, + lineTotal: decimal, + })), +}); + +export const paymentMethods = z.enum(["BANK_TRANSFER", "UPI", "CHEQUE", "CASH", "OTHER"]); +export const paymentInput = z.object({ + idempotencyKey: uuid, + reference: reference(80), + method: paymentMethods, + amount: amount.refine((value) => value !== "0.00", "Amount must be positive"), + paidDate: z.string().date(), +}).strict(); + +export const supplierPayment = z.object({ + id: uuid, + reference: z.string(), + method: paymentMethods, + currency, + amount: decimal, + paidAt: z.string().datetime(), + reversal: correction.nullable(), +}); + +export const paymentHistory = z.object({ + currency, + payableTotal: amount, + paidTotal: amount, + outstandingTotal: amount, + payments: z.array(supplierPayment), +}); diff --git a/src/pages/ProcurementPage.tsx b/src/pages/ProcurementPage.tsx index 9491cb9..5ea2536 100644 --- a/src/pages/ProcurementPage.tsx +++ b/src/pages/ProcurementPage.tsx @@ -11,6 +11,7 @@ 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; @@ -193,6 +194,7 @@ function PurchaseOrderDetails({ id }: { id: string }) { ])} />

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

{order.status === "ISSUED" && } + {order.status === "ISSUED" && } {can("procurement.manage") && order.status === "DRAFT" && <> { diff --git a/src/pages/PurchaseOrderInvoices.tsx b/src/pages/PurchaseOrderInvoices.tsx new file mode 100644 index 0000000..4105a9b --- /dev/null +++ b/src/pages/PurchaseOrderInvoices.tsx @@ -0,0 +1,190 @@ +import { useState } from "react"; +import { z } from "zod"; +import Alert from "@mui/material/Alert"; +import Button from "@mui/material/Button"; +import { ActionForm, Field, Pager, Panel, QueryView, Table, readText, usePrivateQuery } from "@/components/WorkspaceTools"; +import { ApiError, isUnknownOutcome } from "@/lib/api"; +import { usePlatform } from "@/lib/platform"; +import { purchaseOrder } from "@/lib/procurement"; +import { correctionInput, invoiceInput, paymentHistory, paymentInput, paymentMethods, supplierInvoice, supplierPayment } from "@/lib/supplier-finance"; +import { useIdempotentCommand } from "@/lib/use-idempotent-command"; + +type Order = z.infer; +type Invoice = z.infer; + +export function PurchaseOrderInvoices({ order }: { order: Order }) { + const { can, request } = usePlatform(); + const [offset, setOffset] = useState(0); + const [selected, select] = useState(""); + const [uncertain, setUncertain] = useState(false); + const path = `/purchase-orders/${order.id}/invoices`; + const query = usePrivateQuery(`${path}?limit=25&offset=${offset}`, z.array(supplierInvoice)); + const lineNames = new Map(order.lines.map((line) => [ + line.id, `${line.materialName} (${line.materialCode}) · ${line.unit}`, + ])); + + return + {(rows) => <> + invoice.id)} + rows={rows.map((invoice) => [ + invoice.invoiceNumber, invoice.invoiceDate.slice(0, 10), + `${invoice.currency} ${invoice.payableTotal}`, invoice.void ? "Void" : "Recorded", + , + ])} /> + + } + {selected && } + {can("procurement.manage") && (uncertain ? ( + + The server may have recorded this invoice. Check the latest invoices for its number before recording it again. + + + ) : ( + invoiceInput.parse({ + invoiceNumber: readText(data, "invoiceNumber"), + invoiceDate: readText(data, "invoiceDate"), + taxAmount: readText(data, "taxAmount").trim(), + shippingAmount: readText(data, "shippingAmount").trim(), + 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, supplierInvoice, { method: "POST", body }); + select(saved.id); + setOffset(0); + await query.refetch(); + } catch (error) { + if (isUnknownOutcome(error)) { + setUncertain(true); + setOffset(0); + await query.refetch(); + } + throw error; + } + }}> +

Invoice only quantities accepted in quality inspection and still available to bill. The backend uses the purchase order's saved prices.

+ + + + + {order.lines.map((line) => ( + + ))} +
+ ))} + ; +} + +function InvoiceDetails({ id, lineNames, refreshList }: { + id: string; + lineNames: Map; + refreshList: () => Promise; +}) { + const path = `/supplier-invoices/${id}`; + const invoice = usePrivateQuery(path, supplierInvoice); + return {(record) => +
line.id)} + rows={record.lines.map((line) => [ + lineNames.get(line.purchaseOrderLineId) ?? line.purchaseOrderLineId, + line.quantity, `${record.currency} ${line.unitPrice}`, `${record.currency} ${line.lineTotal}`, + ])} /> +
+
Merchandise
{record.currency} {record.merchandiseTotal}
+
Tax
{record.currency} {record.taxAmount}
+
Shipping
{record.currency} {record.shippingAmount}
+
Payable total
{record.currency} {record.payableTotal}
+
+ {record.void && Voided. {record.void.reason}} + { + await Promise.all([invoice.refetch(), refreshList()]); + }} /> + }; +} + +function InvoicePayments({ invoice, refreshInvoice }: { + invoice: Invoice; + refreshInvoice: () => Promise; +}) { + const { can, request } = usePlatform(); + const [offset, setOffset] = useState(0); + const [reversing, setReversing] = useState(""); + const invoicePath = `/supplier-invoices/${invoice.id}`; + const path = `${invoicePath}/payments`; + const query = usePrivateQuery(`${path}?limit=25&offset=${offset}`, paymentHistory); + const command = useIdempotentCommand(path, paymentInput, supplierPayment, invoice.id); + + return + {(data) => { + const payment = data.payments.find((entry) => entry.id === reversing && !entry.reversal); + return <> +

Paid {data.currency} {data.paidTotal}{!invoice.void && ` · Outstanding ${data.currency} ${data.outstandingTotal}`}

+
entry.id)} rows={data.payments.map((entry) => [ + entry.reference, entry.paidAt.slice(0, 10), entry.method.replaceAll("_", " "), + `${entry.currency} ${entry.amount}`, entry.reversal ? `Reversed · ${entry.reversal.reason}` : "Recorded", + can("supplier_payment.manage") && !entry.reversal && + , + ])} /> + { setReversing(""); setOffset(next); }} /> + {payment && can("supplier_payment.manage") && ( + { + try { + await request(`/supplier-payments/${payment.id}/reverse`, supplierPayment, { method: "POST", body }); + } finally { + await query.refetch(); + } + }} /> + )} + {!invoice.void && can("supplier_payment.manage") && (command.pending || data.outstandingTotal !== "0.00") && ( + command.pending ? {} : Object.fromEntries(form)} + submit={async (body) => { + try { + await command.run(body); + setOffset(0); + await query.refetch(); + } catch (error) { + if (error instanceof ApiError && error.code === "PAYMENT_INVOICE_VOID") await refreshInvoice(); + throw error; + } + }}> + {command.pending ? ( + Retrying uses the same reference {command.pending.reference} and amount {invoice.currency} {command.pending.amount}. + ) : <> +

Record a payment already made to the supplier.

+ + ({ value, label: value.replaceAll("_", " ") }))} /> + + + } +
+ )} + {!invoice.void && can("procurement.manage") && data.paidTotal === "0.00" && !command.pending && ( + { + try { + await request(`${invoicePath}/void`, supplierInvoice, { method: "POST", body }); + } finally { + await Promise.all([refreshInvoice(), query.refetch()]); + } + }} /> + )} + ; + }} + ; +} + +function CorrectionForm({ label, submit }: { + label: string; + submit: (input: z.infer) => Promise; +}) { + return ({ reason: readText(data, "reason") })} + submit={(value) => submit(correctionInput.parse(value))}> + + ; +} diff --git a/test/supplier-finance.test.ts b/test/supplier-finance.test.ts new file mode 100644 index 0000000..61545be --- /dev/null +++ b/test/supplier-finance.test.ts @@ -0,0 +1,31 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { invoiceInput, paymentInput } from "../src/lib/supplier-finance.ts"; + +const id = "d66c798a-f764-4b88-8d13-ace328ff1010"; + +test("supplier invoices normalize invoice numbers and retain exact money and quantity strings", () => { + const line = { purchaseOrderLineId: id, quantity: "0.125" }; + const input = { + invoiceNumber: " inv/001 ", + invoiceDate: "2026-11-12", + taxAmount: "0.01", + shippingAmount: "0.00", + lines: [line], + }; + assert.deepEqual(invoiceInput.parse(input), { ...input, invoiceNumber: "INV/001" }); + assert.equal(invoiceInput.safeParse({ ...input, lines: [line, line] }).success, false); + assert.equal(invoiceInput.safeParse({ ...input, lines: [{ ...line, quantity: "0.000" }] }).success, false); + assert.equal(invoiceInput.safeParse({ ...input, taxAmount: "0.001" }).success, false); +}); + +test("supplier payment input enforces a positive amount, supported method and valid date", () => { + const input = { + idempotencyKey: id, reference: " bank/42 ", method: "BANK_TRANSFER", + amount: "9999999999.99", paidDate: "2026-11-12", + }; + assert.deepEqual(paymentInput.parse(input), { ...input, reference: "BANK/42" }); + assert.equal(paymentInput.safeParse({ ...input, amount: "0.00" }).success, false); + assert.equal(paymentInput.safeParse({ ...input, method: "CARD" }).success, false); + assert.equal(paymentInput.safeParse({ ...input, paidDate: "2026-02-31" }).success, false); +}); diff --git a/test/workflows.ui.test.tsx b/test/workflows.ui.test.tsx index db262ce..eac2050 100644 --- a/test/workflows.ui.test.tsx +++ b/test/workflows.ui.test.tsx @@ -13,6 +13,7 @@ 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 { PurchaseOrderInvoices } from "../src/pages/PurchaseOrderInvoices"; import theme from "../src/theme"; import { Switch, Route } from "wouter"; const id = "d66c798a-f764-4b88-8d13-ace328ff1010"; @@ -175,6 +176,57 @@ function harness(children: ReactNode) { return { client, ...result }; } +test("supplier payment retry preserves the payment payload and refreshes the balance", async () => { + const attempts: unknown[] = []; + const record = { + id, invoiceNumber: "INV/42", invoiceDate: "2026-11-12T00:00:00.000Z", + currency: "INR", merchandiseTotal: "10", taxAmount: "0", shippingAmount: "0", + payableTotal: "10", void: null, lines: [], + }; + const payment = { + id, reference: "BANK/42", method: "BANK_TRANSFER", amount: "10", currency: "INR", + paidAt: record.invoiceDate, reversal: null, + }; + 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: ["procurement.read", "supplier_payment.manage"] }); + if (url.includes("/invoices?")) return json([record]); + if (url.endsWith(`/supplier-invoices/${id}`)) return json(record); + if (url.endsWith("/payments") && options?.method === "POST") { + attempts.push(JSON.parse(String(options.body))); + if (attempts.length === 1) throw new Error("Response lost"); + return json(payment); + } + if (url.includes("/payments?")) return json({ + currency: "INR", payableTotal: "10.00", + paidTotal: attempts.length ? "10.00" : "0.00", + outstandingTotal: attempts.length ? "0.00" : "10.00", + payments: attempts.length ? [payment] : [], + }); + throw new Error(`Unexpected request ${url}`); + })); + function AuthorizedInvoices() { + const { can } = usePlatform(); + return can("procurement.read") ? : null; + } + harness(); + const user = userEvent.setup(); + await user.click(screen.getByText("Test login")); + await user.click(await screen.findByRole("button", { name: "View invoice INV/42" })); + await user.type(await screen.findByRole("textbox", { name: /Payment reference/ }), "bank/42"); + await user.type(screen.getByRole("textbox", { name: /Payment amount/ }), "10.00"); + await user.type(screen.getByRole("textbox", { name: /Payment date/ }), "2026-11-12"); + await user.click(screen.getByRole("button", { name: "Record supplier payment" })); + await user.click(await screen.findByRole("button", { name: "Retry supplier payment record" })); + await screen.findByText("Paid INR 10.00 · Outstanding INR 0.00"); + expect(attempts).toHaveLength(2); + expect(attempts[1]).toEqual(attempts[0]); + expect(screen.queryByRole("button", { name: "Record supplier invoice" })).toBeNull(); +}); + test("receipt posting retries the same warehouse and key after a lost response", async () => { const attempts: unknown[] = []; const posting = {