Merge pull request 'feat: record and reverse B2B partner payment receipts' (#30) from feat/b2b-partner-payments into main
continuous-integration/drone/push Build is failing Details

Reviewed-on: #30
This commit is contained in:
Mihir Motiyani 2026-11-20 13:22:40 +05:30
commit 4a5cac2593
8 changed files with 345 additions and 1 deletions

View File

@ -62,4 +62,6 @@ Customer and administration screens are implemented, with recovery, pricing, sto
- Artwork UAT should use separate uploader, reviewer, and reader accounts. Exercise the 2 MiB upload limit through ingress, approval and rejection, download permissions, and preservation of prior approved versions.
- Partner orders support conversion from accepted, unexpired quotations, immutable merchandise snapshots, and reasoned cancellation.
- Partner order UAT should verify expired quotes, duplicate references and quote conversion, exact retries, and cancellation blocked by an active payment receipt.
- Partner payments, custom requests and reporting remain open.
- Partner payments support manual external receipts, exact paid and outstanding merchandise balances, receipt details, and confirmed reasoned reversals. Read and manage permissions are separate, and payment readers can open an order's payment history without order-read permission.
- Partner payment UAT should exercise partial and full receipts, duplicate references, overpayments, cancelled orders, exact retries for recording and reversal, restored balances, and cancellation after reversing all active receipts. References normalize to uppercase and remain reserved after reversal.
- Custom requests and reporting remain open.

View File

@ -36,6 +36,7 @@ const CreditPoliciesPage = lazy(() => import("@/pages/CreditPoliciesPage"));
const SamplesPage = lazy(() => import("@/pages/SamplesPage"));
const ArtworkPage = lazy(() => import("@/pages/ArtworkPage"));
const PartnerOrdersPage = lazy(() => import("@/pages/PartnerOrdersPage"));
const PartnerPaymentsPage = lazy(() => import("@/pages/PartnerPaymentsPage"));
const MaterialCostRatesPage = lazy(() => import("@/pages/MaterialCostRatesPage"));
const ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
const BomPage = lazy(() => import("@/pages/BomPage"));
@ -130,6 +131,10 @@ function Router() {
<Route path="/admin/b2b-artwork/:id">
{(params) => <ArtworkPage id={params.id} />}
</Route>
<Route path="/admin/b2b-payments">{() => <PartnerPaymentsPage />}</Route>
<Route path="/admin/b2b-partner-orders/:orderId/payments">
{(params) => <PartnerPaymentsPage orderId={params.orderId} />}
</Route>
<Route path="/admin/b2b-partner-orders">{() => <PartnerOrdersPage />}</Route>
<Route path="/admin/b2b-partner-orders/new">{() => <PartnerOrdersPage create />}</Route>
<Route path="/admin/b2b-partner-orders/new/:quoteId">

View File

@ -77,6 +77,7 @@ export function WorkspaceNavigation() {
{ label: "B2B samples", path: "/admin/b2b-samples", permission: "b2b.sample.read" },
{ label: "B2B artwork", path: "/admin/b2b-artwork", permission: "b2b.artwork.read" },
{ label: "B2B partner orders", path: "/admin/b2b-partner-orders", permission: "b2b.order.read" },
{ label: "B2B partner payments", path: "/admin/b2b-payments", permission: "b2b.payment.read" },
];
return (
<nav className="workspace-links" aria-label="Workspace navigation">

View File

@ -0,0 +1,29 @@
import { z } from "zod";
import { currency, uuid } from "./commerce.ts";
import { paymentMethods } from "./supplier-finance.ts";
const amount = z.string().regex(/^(0|[1-9]\d{0,15})\.\d{2}$/, "Use two decimal places");
const reason = z.string().trim().min(3).max(500)
.regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text");
const timestamp = z.string().datetime({ offset: true });
export const partnerPaymentInput = z.object({
idempotencyKey: uuid,
reference: z.string().trim().min(1).max(80).regex(/^[A-Za-z0-9][A-Za-z0-9._/-]*$/).toUpperCase(),
method: paymentMethods,
amount: amount.refine((value) => value !== "0.00", "Amount must be positive"),
receivedOn: z.string().date(),
}).strict();
export const reversePartnerPaymentInput = z.object({ reason, idempotencyKey: uuid }).strict();
export const partnerPayment = z.object({
id: uuid, orderId: uuid, recordedById: uuid,
reference: z.string(), method: paymentMethods, currency, amount,
receivedOn: timestamp, createdAt: timestamp,
reversal: z.object({ reason, reversedById: uuid, createdAt: timestamp }).nullable(),
});
export const partnerPaymentHistory = z.object({
orderId: uuid, currency, merchandiseTotal: amount, paidTotal: amount, outstandingTotal: amount,
payments: z.array(partnerPayment),
});

View File

@ -123,6 +123,7 @@ function PartnerOrderDetail({ id }: { id: string }) {
<p>Recorded {new Date(order.createdAt).toLocaleString()} by {order.createdById}</p>
{order.note && <p>{order.note}</p>}
<WorkspaceLink href={`${route}/account/${order.accountId}`}>All orders for this business</WorkspaceLink>
{can("b2b.payment.read") && <p><WorkspaceLink href={`${route}/${id}/payments`}>Partner receipts and balance</WorkspaceLink></p>}
{can("b2b.quote.read") && <p><WorkspaceLink href={`/admin/b2b-quotes/${order.quoteId}`}>Source quotation</WorkspaceLink></p>}
<BusinessSnapshot account={order.accountSnapshot} />
<Table head={["Variant", "Quantity", "Minimum", "Unit price", "Line total"]}

View File

@ -0,0 +1,114 @@
import { useState } from "react";
import { useLocation } from "wouter";
import { useQueryClient } from "@tanstack/react-query";
import Alert from "@mui/material/Alert";
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 { uuid } from "@/lib/commerce";
import { partnerPayment, partnerPaymentHistory, partnerPaymentInput, reversePartnerPaymentInput } from "@/lib/partner-payments";
import { paymentMethods } from "@/lib/supplier-finance";
import { usePlatform } from "@/lib/platform";
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
const route = "/admin/b2b-partner-orders";
export default function PartnerPaymentsPage({ orderId }: { orderId?: string }) {
const [, navigate] = useLocation();
const id = uuid.safeParse(orderId);
return <WorkspaceShell title="B2B Partner Payments" permission="b2b.payment.read">
{orderId ? id.success ? <PaymentHistory key={id.data} orderId={id.data} /> :
<Alert severity="warning">Invalid partner order ID.</Alert> :
<Panel title="Find partner receipts">
<ActionForm label="View partner payments" read={(form) => uuid.parse(readText(form, "orderId").trim())}
submit={async (value) => { navigate(`${route}/${uuid.parse(value)}/payments`); }}>
<Field name="orderId" label="Partner order ID" maxLength={36} />
</ActionForm>
</Panel>}
</WorkspaceShell>;
}
function PaymentHistory({ orderId }: { orderId: string }) {
const { can } = usePlatform();
const [offset, setOffset] = useState(0);
const [selected, select] = useState("");
const path = `/b2b/partner-orders/${orderId}/payments`;
const query = usePrivateQuery(`${path}?limit=25&offset=${offset}`, partnerPaymentHistory);
const command = useIdempotentCommand(path, partnerPaymentInput, partnerPayment, orderId);
return <>
{can("b2b.order.read") && <WorkspaceLink href={`${route}/${orderId}`}>View partner order</WorkspaceLink>}
<Panel title="Partner receipt history">
<p className="workspace-id">Partner order {orderId}</p>
<QueryView query={query}>{(data) => <>
<dl>
<dt>Merchandise total</dt><dd>{data.currency} {data.merchandiseTotal}</dd>
<dt>Paid total</dt><dd>{data.currency} {data.paidTotal}</dd>
<dt>Outstanding total</dt><dd>{data.currency} {data.outstandingTotal}</dd>
</dl>
<Table head={["Reference", "Received", "Method", "Amount", "Status", "Actions"]}
rowKeys={data.payments.map((payment) => payment.id)} rows={data.payments.map((payment) => [
payment.reference, payment.receivedOn.slice(0, 10), payment.method.replaceAll("_", " "),
`${payment.currency} ${payment.amount}`, payment.reversal ? "Reversed" : "Recorded",
<Button onClick={() => select(payment.id)} aria-pressed={selected === payment.id}>View receipt {payment.reference}</Button>,
])} />
<Pager offset={offset} count={data.payments.length} onPage={setOffset} />
{can("b2b.payment.manage") && (command.pending || data.outstandingTotal !== "0.00") &&
<ActionForm key={command.pending ? "retry" : "record"}
label={command.pending ? "Retry partner receipt" : "Record partner receipt"}
read={(form) => command.pending ? {} : Object.fromEntries(form)}
submit={async (input) => {
await command.run(input);
if (offset) setOffset(0);
await query.refetch();
}}>
{command.pending ? <Alert severity="warning">
The server may have recorded this receipt. Retrying reuses reference {command.pending.reference},
amount {data.currency} {command.pending.amount}, and the original key.
</Alert> : <>
<p>Record an external payment after verifying the receipt. The server checks the remaining merchandise balance.</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={`Receipt amount (${data.currency})`} helper="Use two decimal places." maxLength={19} />
<Field name="receivedOn" label="Received on (YYYY-MM-DD)" maxLength={10} />
</>}
</ActionForm>}
</>}</QueryView>
</Panel>
{selected && <ReceiptDetails key={selected} path={`${path}/${selected}`} refresh={query.refetch} />}
</>;
}
function ReceiptDetails({ path, refresh }: { path: string; refresh: () => Promise<unknown> }) {
const { can, scope } = usePlatform();
const client = useQueryClient();
const query = usePrivateQuery(path, partnerPayment);
const command = useIdempotentCommand(`${path}/reverse`, reversePartnerPaymentInput, partnerPayment, path);
return <QueryView query={query}>{(payment) => <Panel title={`Receipt ${payment.reference}`}>
<p>{payment.currency} {payment.amount} · {payment.method.replaceAll("_", " ")} · Received {payment.receivedOn.slice(0, 10)}</p>
<p className="workspace-id">Recorded by {payment.recordedById} on {new Date(payment.createdAt).toLocaleString()}</p>
{payment.reversal && <>
<Alert severity="info">Receipt reversed.</Alert>
<p>{payment.reversal.reason}</p>
<p className="workspace-id">Reversed by {payment.reversal.reversedById} on {new Date(payment.reversal.createdAt).toLocaleString()}</p>
</>}
{can("b2b.payment.manage") && (command.pending || !payment.reversal) &&
<ActionForm key={command.pending ? "retry" : "reverse"}
label={command.pending ? "Retry receipt reversal" : "Reverse partner receipt"}
read={(form) => {
if (command.pending) return {};
if (!form.has("confirmed")) throw new Error("Confirm the receipt reversal before continuing.");
return { reason: readText(form, "reason") };
}} submit={async (input) => {
const saved = await command.run(input);
client.setQueryData(["private", scope, path], saved);
await refresh();
}}>
{command.pending ? <Alert severity="warning">The server may have reversed this receipt. Retrying uses the original reason and key.</Alert> : <>
<p>Reversal corrects the recorded receipt. Arrange any external refund through your payment provider.</p>
<Field name="reason" label="Reversal reason" maxLength={500} />
<Check name="confirmed" label={`Confirm reversal of ${payment.reference}`} />
</>}
</ActionForm>}
</Panel>}</QueryView>;
}

View File

@ -0,0 +1,32 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { partnerPaymentInput, partnerPaymentHistory, reversePartnerPaymentInput } from "../src/lib/partner-payments.ts";
const idempotencyKey = "d66c798a-f764-4b88-8d13-ace328ff1010";
const receipt = { idempotencyKey, reference: " utr-123 ", method: "BANK_TRANSFER", amount: "9007199254740993.25", receivedOn: "2026-11-20" };
test("partner receipt input normalizes references and preserves the backend's full decimal range", () => {
assert.deepEqual(partnerPaymentInput.parse(receipt), { ...receipt, reference: "UTR-123" });
for (const amount of ["0.00", "1", "1.001", "01.00", "-1.00", "10000000000000000.00"]) {
assert.equal(partnerPaymentInput.safeParse({ ...receipt, amount }).success, false);
}
assert.equal(partnerPaymentInput.safeParse({ ...receipt, receivedOn: "2026-02-30" }).success, false);
assert.equal(partnerPaymentInput.safeParse({ ...receipt, orderId: idempotencyKey }).success, false);
});
test("partner payment reversals require a plain-text reason and a replay key", () => {
assert.deepEqual(reversePartnerPaymentInput.parse({ reason: " Wrong receipt ", idempotencyKey }), { reason: "Wrong receipt", idempotencyKey });
for (const reason of ["", "ab", "<script>", "bad\nreason"]) {
assert.equal(reversePartnerPaymentInput.safeParse({ reason, idempotencyKey }).success, false);
}
});
test("partner payment history retains exact authoritative balances and strips command metadata", () => {
const result = partnerPaymentHistory.parse({
orderId: idempotencyKey, currency: "INR", merchandiseTotal: "9999999999999999.99",
paidTotal: "9007199254740993.25", outstandingTotal: "992800745259006.74", payments: [], requestHash: "private",
});
assert.equal(result.paidTotal, receipt.amount);
assert.equal(result.outstandingTotal, "992800745259006.74");
assert.equal("requestHash" in result, false);
});

View File

@ -0,0 +1,160 @@
import { fireEvent, render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider } from "@mui/material/styles";
import { afterEach, expect, test, vi } from "vitest";
import axe from "axe-core";
import { PlatformProvider, usePlatform } from "../src/lib/platform";
import PartnerPaymentsPage from "../src/pages/PartnerPaymentsPage";
import theme from "../src/theme";
const orderId = "d66c798a-f764-4b88-8d13-ace328ff1010";
const userId = "d66c798a-f764-4b88-8d13-ace328ff1011";
const paymentId = "d66c798a-f764-4b88-8d13-ace328ff1012";
const timestamp = "2026-11-20T00:00:00.000Z";
const path = `/b2b/partner-orders/${orderId}/payments`;
const payment = {
id: paymentId, orderId, recordedById: userId, reference: "UTR-123", method: "BANK_TRANSFER",
currency: "INR", amount: "100.25", receivedOn: timestamp, createdAt: timestamp, reversal: null,
};
const history = {
orderId, currency: "INR", merchandiseTotal: "1000.00", paidTotal: "0.00", outstandingTotal: "1000.00", payments: [],
};
const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status });
function Login() {
const { signIn } = usePlatform();
return <button onClick={() => signIn("staff@example.com", "test password")}>Test login</button>;
}
function show(permissions: string[], handle: (url: string, options?: RequestInit) => Promise<Response>, id = orderId) {
const fetch = vi.fn(async (url: string, options?: RequestInit) => {
if (url.endsWith("/auth/login")) return json({ accessToken: "opaque", tokenType: "Bearer", expiresAt: new Date(Date.now() + 3600000).toISOString() });
if (url.endsWith("/auth/me")) return json({ userId, organizationId: orderId, sessionId: userId, permissions });
return handle(url, options);
});
vi.stubGlobal("fetch", fetch);
localStorage.setItem("mani.organization", orderId);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(<ThemeProvider theme={theme}><QueryClientProvider client={client}>
<PlatformProvider><Login /><PartnerPaymentsPage orderId={id} /></PlatformProvider>
</QueryClientProvider></ThemeProvider>);
return fetch;
}
afterEach(() => vi.unstubAllGlobals());
test("recording a lost-response receipt replays the exact normalized body and refreshes authoritative balances", async () => {
const attempts: unknown[] = [];
let saved = false;
const fetch = show(["b2b.payment.read", "b2b.payment.manage"], async (url, options) => {
if (url.endsWith(path) && options?.method === "POST") {
attempts.push(JSON.parse(String(options.body)));
if (attempts.length === 1) throw new Error("Response lost");
saved = true;
return json(payment);
}
if (url.includes(`${path}?`)) return json(saved ? { ...history, paidTotal: "100.25", outstandingTotal: "899.75", payments: [payment] } : history);
throw new Error(`Unexpected request ${url}`);
});
expect(fetch).not.toHaveBeenCalled();
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
fireEvent.change(await screen.findByRole("textbox", { name: "Payment reference" }), { target: { value: " utr-123 " } });
fireEvent.change(screen.getByRole("textbox", { name: "Receipt amount (INR)" }), { target: { value: "100.25" } });
fireEvent.change(screen.getByRole("textbox", { name: "Received on (YYYY-MM-DD)" }), { target: { value: "2026-11-20" } });
await user.click(screen.getByRole("button", { name: "Record partner receipt" }));
await user.click(await screen.findByRole("button", { name: "Retry partner receipt" }));
await screen.findByText("INR 899.75");
expect(attempts[0]).toEqual({ reference: "UTR-123", method: "BANK_TRANSFER", amount: "100.25", receivedOn: "2026-11-20", idempotencyKey: expect.any(String) });
expect(attempts).toEqual([attempts[0], attempts[0]]);
});
test("reversal requires confirmation and replays its reason and key after a lost response", async () => {
const attempts: unknown[] = [];
const reason = "Receipt recorded against wrong bank entry";
let current: object = payment;
const user = userEvent.setup();
show(["b2b.payment.read", "b2b.payment.manage"], async (url, options) => {
if (url.endsWith(`${path}/${paymentId}/reverse`)) {
attempts.push(JSON.parse(String(options?.body)));
if (attempts.length === 1) throw new Error("Response lost");
current = { ...payment, reversal: { reason, reversedById: userId, createdAt: timestamp } };
return json(current);
}
if (url.endsWith(`${path}/${paymentId}`)) return json(current);
if (url.includes(`${path}?`)) return json({ ...history, payments: [current] });
throw new Error(`Unexpected request ${url}`);
});
await user.click(screen.getByRole("button", { name: "Test login" }));
await user.click(await screen.findByRole("button", { name: "View receipt UTR-123" }));
fireEvent.change(await screen.findByRole("textbox", { name: "Reversal reason" }), { target: { value: reason } });
await user.click(screen.getByRole("button", { name: "Reverse partner receipt" }));
expect(attempts).toEqual([]);
await screen.findByText("Confirm the receipt reversal before continuing.");
await user.click(screen.getByRole("checkbox", { name: "Confirm reversal of UTR-123" }));
await user.click(screen.getByRole("button", { name: "Reverse partner receipt" }));
await user.click(await screen.findByRole("button", { name: "Retry receipt reversal" }));
await screen.findByText(reason, { exact: true });
expect(attempts).toEqual([{ reason, idempotencyKey: expect.any(String) }, { reason, idempotencyKey: expect.any(String) }]);
expect(attempts[1]).toEqual(attempts[0]);
expect(screen.queryByRole("button", { name: "Reverse partner receipt" })).toBeNull();
});
test("payment readers can inspect history without order permissions or mutation controls", async () => {
show(["b2b.payment.read"], async () => json({ ...history, paidTotal: "9007199254740993.25", payments: [payment] }));
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await screen.findByText("INR 9007199254740993.25");
expect(screen.queryByRole("button", { name: "Record partner receipt" })).toBeNull();
});
test("missing payment permission and invalid order IDs never issue a payment request", async () => {
const handle = vi.fn(async () => json(history));
show(["b2b.order.read"], handle, "invalid");
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await screen.findByText("Your account does not have permission to view this page.");
expect(handle).not.toHaveBeenCalled();
});
test("invalid order IDs are rejected before querying even for payment readers", async () => {
const handle = vi.fn(async () => json(history));
show(["b2b.payment.read"], handle, "invalid");
await userEvent.setup().click(screen.getByRole("button", { name: "Test login" }));
await screen.findByText("Invalid partner order ID.");
expect(handle).not.toHaveBeenCalled();
});
test("a confirmed overpayment conflict displays the backend reason and permits correction", async () => {
let attempts = 0;
show(["b2b.payment.read", "b2b.payment.manage"], async (_url, options) => {
if (options?.method === "POST") {
attempts++;
return json({ message: "Payment exceeds the partner order balance", code: "B2B_PAYMENT_AMOUNT_LIMIT" }, 409);
}
return json(history);
});
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
fireEvent.change(await screen.findByRole("textbox", { name: "Payment reference" }), { target: { value: "UTR-123" } });
fireEvent.change(screen.getByRole("textbox", { name: "Receipt amount (INR)" }), { target: { value: "1001.00" } });
fireEvent.change(screen.getByRole("textbox", { name: "Received on (YYYY-MM-DD)" }), { target: { value: "2026-11-20" } });
await user.click(screen.getByRole("button", { name: "Record partner receipt" }));
await screen.findByText("Payment exceeds the partner order balance");
expect(attempts).toBe(1);
expect(screen.queryByRole("button", { name: "Retry partner receipt" })).toBeNull();
expect(screen.getByRole("textbox", { name: "Receipt amount (INR)" })).toHaveProperty("value", "1001.00");
});
test("fully paid orders keep their receipt history and hide new recording controls", async () => {
show(["b2b.payment.read", "b2b.payment.manage"], async () => json({ ...history, paidTotal: "1000.00", outstandingTotal: "0.00", payments: [payment] }));
await userEvent.setup().click(screen.getByRole("button", { name: "Test login" }));
await screen.findByRole("button", { name: "View receipt UTR-123" });
expect(screen.queryByRole("button", { name: "Record partner receipt" })).toBeNull();
});
test("the populated receipt form has no serious or critical axe violations", async () => {
show(["b2b.payment.read", "b2b.payment.manage"], async () => json(history));
await userEvent.setup().click(screen.getByRole("button", { name: "Test login" }));
await screen.findByRole("textbox", { name: "Payment reference" });
const result = await axe.run(document.body, { rules: { "color-contrast": { enabled: false } } });
expect(result.violations.filter(({ impact }) => impact === "serious" || impact === "critical")).toEqual([]);
});