161 lines
9.3 KiB
TypeScript
161 lines
9.3 KiB
TypeScript
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([]);
|
|
});
|