feat: record supplier invoices and payments #13

Merged
mihir merged 1 commits from feat/supplier-finance into main 2026-11-12 00:58:19 +05:30
6 changed files with 346 additions and 1 deletions

View File

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

@ -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),
});

View File

@ -11,6 +11,7 @@ import Alert from "@mui/material/Alert";
import { ConfirmAction } from "@/components/ConfirmAction"; import { ConfirmAction } from "@/components/ConfirmAction";
import { isUnknownOutcome } from "@/lib/api"; import { isUnknownOutcome } from "@/lib/api";
import { PurchaseOrderReceipts } from "./PurchaseOrderReceipts"; import { PurchaseOrderReceipts } from "./PurchaseOrderReceipts";
import { PurchaseOrderInvoices } from "./PurchaseOrderInvoices";
type Supplier = z.infer<typeof supplier>; type Supplier = z.infer<typeof supplier>;
type Material = z.infer<typeof material>; type Material = z.infer<typeof material>;
@ -193,6 +194,7 @@ function PurchaseOrderDetails({ id }: { id: string }) {
])} /> ])} />
<p>Merchandise total {order.currency} {order.merchandiseTotal}</p> <p>Merchandise total {order.currency} {order.merchandiseTotal}</p>
{order.status === "ISSUED" && <PurchaseOrderReceipts order={order} />} {order.status === "ISSUED" && <PurchaseOrderReceipts order={order} />}
{order.status === "ISSUED" && <PurchaseOrderInvoices order={order} />}
{can("procurement.manage") && order.status === "DRAFT" && <> {can("procurement.manage") && order.status === "DRAFT" && <>
<ConfirmAction label="Issue purchase order" message={`Issue ${order.reference} so it can receive deliveries?`} <ConfirmAction label="Issue purchase order" message={`Issue ${order.reference} so it can receive deliveries?`}
onConfirm={async () => { onConfirm={async () => {

View File

@ -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<typeof purchaseOrder>;
type Invoice = z.infer<typeof supplierInvoice>;
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 <Panel title="Supplier invoices">
<QueryView query={query}>{(rows) => <>
<Table head={["Invoice", "Date", "Payable", "Status", "Actions"]} rowKeys={rows.map((invoice) => invoice.id)}
rows={rows.map((invoice) => [
invoice.invoiceNumber, invoice.invoiceDate.slice(0, 10),
`${invoice.currency} ${invoice.payableTotal}`, invoice.void ? "Void" : "Recorded",
<Button onClick={() => select(invoice.id)} aria-pressed={selected === invoice.id}>
View invoice {invoice.invoiceNumber}
</Button>,
])} />
<Pager offset={offset} count={rows.length} onPage={setOffset} />
</>}</QueryView>
{selected && <InvoiceDetails key={selected} id={selected} lineNames={lineNames} refreshList={query.refetch} />}
{can("procurement.manage") && (uncertain ? (
<Alert severity="warning">
The server may have recorded this invoice. Check the latest invoices for its number before recording it again.
<Button onClick={() => { if (offset) setOffset(0); else void query.refetch(); }}>Refresh latest invoices</Button>
</Alert>
) : (
<ActionForm label="Record supplier invoice" read={(data) => 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;
}
}}>
<p>Invoice only quantities accepted in quality inspection and still available to bill. The backend uses the purchase order's saved prices.</p>
<Field name="invoiceNumber" label="Supplier invoice number" maxLength={64} />
<Field name="invoiceDate" label="Invoice date (YYYY-MM-DD)" maxLength={10} />
<Field name="taxAmount" label={`Tax amount (${order.currency})`} value="0.00" />
<Field name="shippingAmount" label={`Shipping amount (${order.currency})`} value="0.00" />
{order.lines.map((line) => (
<Field key={line.id} name={line.id} label={`Billed quantity for ${line.materialName} (${line.materialCode})`}
required={false} helper={`Use three decimal places in ${line.unit}. Leave blank to omit this material.`} />
))}
</ActionForm>
))}
</Panel>;
}
function InvoiceDetails({ id, lineNames, refreshList }: {
id: string;
lineNames: Map<string, string>;
refreshList: () => Promise<unknown>;
}) {
const path = `/supplier-invoices/${id}`;
const invoice = usePrivateQuery(path, supplierInvoice);
return <QueryView query={invoice}>{(record) => <Panel title={`Invoice ${record.invoiceNumber}`}>
<Table head={["Material", "Quantity", "Unit price", "Line total"]} rowKeys={record.lines.map((line) => line.id)}
rows={record.lines.map((line) => [
lineNames.get(line.purchaseOrderLineId) ?? line.purchaseOrderLineId,
line.quantity, `${record.currency} ${line.unitPrice}`, `${record.currency} ${line.lineTotal}`,
])} />
<dl>
<dt>Merchandise</dt><dd>{record.currency} {record.merchandiseTotal}</dd>
<dt>Tax</dt><dd>{record.currency} {record.taxAmount}</dd>
<dt>Shipping</dt><dd>{record.currency} {record.shippingAmount}</dd>
<dt>Payable total</dt><dd>{record.currency} {record.payableTotal}</dd>
</dl>
{record.void && <Alert severity="info">Voided. {record.void.reason}</Alert>}
<InvoicePayments invoice={record} refreshInvoice={async () => {
await Promise.all([invoice.refetch(), refreshList()]);
}} />
</Panel>}</QueryView>;
}
function InvoicePayments({ invoice, refreshInvoice }: {
invoice: Invoice;
refreshInvoice: () => Promise<void>;
}) {
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 <Panel title="Supplier payment records">
<QueryView query={query}>{(data) => {
const payment = data.payments.find((entry) => entry.id === reversing && !entry.reversal);
return <>
<p>Paid {data.currency} {data.paidTotal}{!invoice.void && ` · Outstanding ${data.currency} ${data.outstandingTotal}`}</p>
<Table head={["Reference", "Payment date", "Method", "Amount", "Status", "Actions"]}
rowKeys={data.payments.map((entry) => 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 &&
<Button onClick={() => setReversing(entry.id)} aria-label={`Reverse payment ${entry.reference}`}>Reverse</Button>,
])} />
<Pager offset={offset} count={data.payments.length} onPage={(next) => { setReversing(""); setOffset(next); }} />
{payment && can("supplier_payment.manage") && (
<CorrectionForm key={payment.id} label={`Reverse payment ${payment.reference}`}
submit={async (body) => {
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") && (
<ActionForm key={command.pending ? "retry" : "record"} label={command.pending ? "Retry supplier payment record" : "Record supplier payment"}
read={(form) => 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 ? (
<Alert severity="warning">Retrying uses the same reference {command.pending.reference} and amount {invoice.currency} {command.pending.amount}.</Alert>
) : <>
<p>Record a payment already made to the supplier.</p>
<Field name="reference" label="Payment reference" maxLength={80} />
<Field name="method" label="Payment method" options={paymentMethods.options.map((value) => ({ value, label: value.replaceAll("_", " ") }))} />
<Field name="amount" label={`Payment amount (${invoice.currency})`} helper="Use two decimal places." />
<Field name="paidDate" label="Payment date (YYYY-MM-DD)" maxLength={10} />
</>}
</ActionForm>
)}
{!invoice.void && can("procurement.manage") && data.paidTotal === "0.00" && !command.pending && (
<CorrectionForm label={`Void invoice ${invoice.invoiceNumber}`} submit={async (body) => {
try {
await request(`${invoicePath}/void`, supplierInvoice, { method: "POST", body });
} finally {
await Promise.all([refreshInvoice(), query.refetch()]);
}
}} />
)}
</>;
}}</QueryView>
</Panel>;
}
function CorrectionForm({ label, submit }: {
label: string;
submit: (input: z.infer<typeof correctionInput>) => Promise<void>;
}) {
return <ActionForm label={label} read={(data) => ({ reason: readText(data, "reason") })}
submit={(value) => submit(correctionInput.parse(value))}>
<Field name="reason" label={`Reason to ${label.toLowerCase()}`} maxLength={500} />
</ActionForm>;
}

View File

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

View File

@ -13,6 +13,7 @@ import AccessPage, { RolesPage } from "../src/pages/AccessPage";
import OrdersPage from "../src/pages/OrdersPage"; import OrdersPage from "../src/pages/OrdersPage";
import ProcurementPage from "../src/pages/ProcurementPage"; import ProcurementPage from "../src/pages/ProcurementPage";
import { ReceiptStockPosting } from "../src/pages/ReceiptStockPosting"; import { ReceiptStockPosting } from "../src/pages/ReceiptStockPosting";
import { PurchaseOrderInvoices } from "../src/pages/PurchaseOrderInvoices";
import theme from "../src/theme"; import theme from "../src/theme";
import { Switch, Route } from "wouter"; import { Switch, Route } from "wouter";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010"; const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
@ -175,6 +176,57 @@ function harness(children: ReactNode) {
return { client, ...result }; 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") ? <PurchaseOrderInvoices order={{
id, reference: "PO-42", status: "ISSUED", supplier: { id, name: "Supplier" },
currency: "INR", expectedDeliveryAt: null, merchandiseTotal: "10", lines: [],
}} /> : null;
}
harness(<AuthorizedInvoices />);
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 () => { test("receipt posting retries the same warehouse and key after a lost response", async () => {
const attempts: unknown[] = []; const attempts: unknown[] = [];
const posting = { const posting = {