import { type ReactNode } from "react"; 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 { Route, Switch } from "wouter"; import { PlatformProvider, usePlatform } from "../src/lib/platform"; import PartnerOrdersPage from "../src/pages/PartnerOrdersPage"; import theme from "../src/theme"; const accountId = "d66c798a-f764-4b88-8d13-ace328ff1010"; const userId = "d66c798a-f764-4b88-8d13-ace328ff1011"; const quoteId = "d66c798a-f764-4b88-8d13-ace328ff1012"; const orderId = "d66c798a-f764-4b88-8d13-ace328ff1013"; const variantId = "d66c798a-f764-4b88-8d13-ace328ff1014"; const lineId = "d66c798a-f764-4b88-8d13-ace328ff1015"; const createdAt = "2026-11-17T08:00:00.000Z"; const route = "/admin/b2b-partner-orders"; const api = "/b2b/partner-orders"; const detail = `${api}/${orderId}`; const profile = { legalName: "Vanilla Gift Company", tradingName: null, registrationNumber: "REG-019", taxIdentifier: null, countryCode: "IN", contactEmail: "partner@example.com", contactPhone: null, billingLine1: "42 Sample Road", billingCity: "Mumbai", billingRegion: "Maharashtra", billingPostalCode: "400001", profileVersion: 1, }; const line = { id: lineId, variantId, sku: "VANILLA-TIN", name: "Vanilla tin", quantity: 10, minQuantity: 8, unitPrice: "100.00", lineTotal: "1000.00", }; const quote = { id: quoteId, accountId, number: "BQ-ORDER-01", accountSnapshot: profile, currency: "INR", merchandiseTotal: "1000.00", expiresAt: new Date(Date.now() + 86_400_000).toISOString(), status: "ACCEPTED", priceListName: "Wholesale INR", customerReference: null, createdAt, lines: [line], response: { kind: "ACCEPTED", note: "Customer accepted by email", createdAt }, }; const order = { id: orderId, accountId, quoteId, createdById: userId, number: "BPO-ORDER-01", partnerReference: "CUSTOMER-PO-123", note: "Requested by the purchasing team", accountSnapshot: profile, currency: "INR", merchandiseTotal: "1000.00", createdAt, status: "RECEIVED", lines: [line], cancellation: null, }; const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status }); function staffSession(url: string, permissions: string[]) { if (url.endsWith("/auth/login")) return json({ accessToken: "test-opaque", tokenType: "Bearer", expiresAt: new Date(Date.now() + 3_600_000).toISOString(), }); if (url.endsWith("/auth/me")) return json({ userId, organizationId: accountId, sessionId: accountId, permissions, }); } function Login() { const { signIn } = usePlatform(); return ; } function showOrders(children: ReactNode) { localStorage.setItem("mani.organization", accountId); const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }); render( {children} ); } afterEach(() => { vi.unstubAllGlobals(); history.replaceState(null, "", "/"); }); test("conversion retries the same accepted quote, reference, note, and key after a lost response", async () => { const attempts: unknown[] = []; const fetch = vi.fn(async (url: string, options?: RequestInit) => { const auth = staffSession(url, ["b2b.order.read", "b2b.order.manage", "b2b.quote.read"]); if (auth) return auth; if (url.endsWith(`/b2b/quotes/${quoteId}`)) return json(quote); if (url.endsWith(api) && options?.method === "POST") { attempts.push(JSON.parse(String(options.body))); if (attempts.length === 1) throw new Error("Response lost"); return json(order); } if (url.endsWith(detail)) return json(order); throw new Error(`Unexpected request ${url}`); }); vi.stubGlobal("fetch", fetch); history.replaceState(null, "", `${route}/new/${quoteId}`); showOrders( {(params) => } {(params) => } ); expect(fetch).not.toHaveBeenCalled(); const user = userEvent.setup(); await user.click(screen.getByRole("button", { name: "Test login" })); fireEvent.change(await screen.findByRole("textbox", { name: /Partner reference/ }), { target: { value: order.partnerReference }, }); fireEvent.change(screen.getByRole("textbox", { name: /Order note/ }), { target: { value: order.note }, }); await user.click(screen.getByRole("button", { name: "Record partner order" })); expect(attempts).toEqual([{ quoteId, partnerReference: order.partnerReference, note: order.note, idempotencyKey: expect.any(String), }]); await user.click(await screen.findByRole("button", { name: "Retry partner order" })); await screen.findByRole("button", { name: "Cancel partner order" }); expect(location.pathname).toBe(`${route}/${orderId}`); expect(attempts).toEqual([attempts[0], attempts[0]]); }); test("a received partner order can be cancelled and the same cancellation key can be replayed", async () => { const reason = "Partner withdrew purchase order"; let current: object = order; const attempts: unknown[] = []; vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => { const auth = staffSession(url, ["b2b.order.read", "b2b.order.manage"]); if (auth) return auth; if (url.endsWith(detail)) return json(current); if (url.endsWith(`${detail}/cancel`) && options?.method === "POST") { attempts.push(JSON.parse(String(options.body))); current = { ...order, status: "CANCELLED", cancellation: { orderId, reason, actorId: userId, createdAt } }; if (attempts.length === 1) throw new Error("Response lost"); return json(current); } throw new Error(`Unexpected request ${url}`); })); showOrders(); const user = userEvent.setup(); await user.click(screen.getByRole("button", { name: "Test login" })); fireEvent.change(await screen.findByRole("textbox", { name: /Cancellation reason/ }), { target: { value: reason } }); await user.click(screen.getByRole("button", { name: "Cancel partner order" })); expect(attempts).toEqual([{ reason, idempotencyKey: expect.any(String) }]); await user.click(await screen.findByRole("button", { name: "Retry cancellation" })); await screen.findByText(new RegExp(reason)); expect(screen.queryByRole("button", { name: "Cancel partner order" })).toBeNull(); expect(attempts).toEqual([attempts[0], attempts[0]]); }); test("a read-only staff member can see the saved order without cancellation controls", async () => { const fetch = vi.fn(async (url: string) => { const auth = staffSession(url, ["b2b.order.read"]); if (auth) return auth; if (url.endsWith(detail)) return json(order); throw new Error(`Unexpected request ${url}`); }); vi.stubGlobal("fetch", fetch); showOrders(); expect(fetch).not.toHaveBeenCalled(); const user = userEvent.setup(); await user.click(screen.getByRole("button", { name: "Test login" })); await screen.findByText(/Vanilla tin/); expect(screen.queryByRole("textbox", { name: /Cancellation reason/ })).toBeNull(); expect(screen.queryByRole("button", { name: "Cancel partner order" })).toBeNull(); }); test("a cancellation blocked by an active receipt keeps the saved order and explains the conflict", async () => { const fetch = vi.fn(async (url: string, options?: RequestInit) => { const auth = staffSession(url, ["b2b.order.read", "b2b.order.manage"]); if (auth) return auth; if (url.endsWith(detail)) return json(order); if (url.endsWith(`${detail}/cancel`) && options?.method === "POST") return json({ message: "Reverse active payments before cancelling the order", code: "B2B_PAYMENT_CANCEL_BLOCKED", }, 409); throw new Error(`Unexpected request ${url}`); }); vi.stubGlobal("fetch", fetch); showOrders(); const user = userEvent.setup(); await user.click(screen.getByRole("button", { name: "Test login" })); fireEvent.change(await screen.findByRole("textbox", { name: /Cancellation reason/ }), { target: { value: "Partner changed the order" }, }); await user.click(screen.getByRole("button", { name: "Cancel partner order" })); await screen.findByText("Reverse active payments before cancelling the order"); expect(screen.getByRole("button", { name: "Cancel partner order" })).toBeTruthy(); expect(screen.queryByRole("button", { name: "Retry cancellation" })).toBeNull(); });