import { type ReactNode } from "react"; import { act, render, screen, waitFor } from "@testing-library/react"; import { Table } from "../src/components/WorkspaceTools"; import { ConfirmAction } from "../src/components/ConfirmAction"; import userEvent from "@testing-library/user-event"; import { afterEach, expect, test, vi } from "vitest"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ThemeProvider } from "@mui/material/styles"; import axe from "axe-core"; import { PlatformProvider, usePlatform } from "../src/lib/platform"; import CartPage from "../src/pages/CartPage"; 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 SupplierDocumentsPage from "../src/pages/SupplierDocumentsPage"; import theme from "../src/theme"; import { Switch, Route } from "wouter"; const id = "d66c798a-f764-4b88-8d13-ace328ff1010"; test("table refresh keeps an open confirmation bound to its original record", async () => { const approve = vi.fn(async (_id: string) => undefined); const table = (ids: string[]) => ( [ id, approve(id)} />, ])} /> ); const view = render(table(["A", "B"])), user = userEvent.setup(); await user.click(screen.getAllByRole("button", { name: "Approve" })[0]); view.rerender(table(["B", "A"])); await user.click(screen.getByRole("button", { name: "Confirm" })); expect(approve).toHaveBeenCalledWith("A"); }); test("role-read accounts can view roles without user-read access", async () => { const fetch = vi.fn(async (url: string) => url.endsWith("/auth/login") ? json(session) : url.endsWith("/auth/me") ? json({ ...me, permissions: ["roles.read"] }) : url.includes("/roles?") ? json([ { id, name: "Observer", permissions: [], isSystem: false, organizationId: id, }, ]) : Promise.reject(new Error("Unexpected private request")), ); vi.stubGlobal("fetch", fetch); harness(); const user = userEvent.setup(); await user.click(screen.getByText("Test login")); await screen.findByText("Observer"); expect(fetch.mock.calls.some(([url]) => url.includes("/users"))).toBe(false); expect(screen.queryByRole("link", { name: "Access" })).toBeNull(); }); const me = { userId: id, organizationId: id, sessionId: id, permissions: [] }; const session = { accessToken: "test-opaque", tokenType: "Bearer", expiresAt: new Date(Date.now() + 3600000).toISOString(), }; test("procurement observers can read suppliers and cannot see write controls", async () => { const fetch = vi.fn(async (url: string) => url.endsWith("/auth/login") ? json(session) : url.endsWith("/auth/me") ? json({ ...me, permissions: ["procurement.read"] }) : url.includes("/suppliers?") ? json([{ id, name: "Wax Supplier", code: "WAX", contactName: "Contact", email: "contact@example.com", phone: "+919999999999", active: true }]) : Promise.reject(new Error("Unexpected private request")), ); vi.stubGlobal("fetch", fetch); harness(); await userEvent.setup().click(screen.getByText("Test login")); const terms = await screen.findByRole("link", { name: "Supply terms and orders for Wax Supplier" }); expect(terms.getAttribute("href")).toBe(`/admin/procurement/suppliers/${id}`); expect(screen.queryByRole("button", { name: "Edit Wax Supplier" })).toBeNull(); expect(screen.queryByRole("button", { name: "Create supplier" })).toBeNull(); }); const address = { id, recipient: "Test Recipient", line1: "Test Street", line2: "", city: "Test City", region: "Test State", postalCode: "123456", countryCode: "IN", phone: "+919999999999", isDefault: true, }; const line = { variantId: id, quantity: 1, variant: { name: "Small", sku: "TEST", price: "10", currency: "INR", active: true, product: { name: "Test candle", status: "PUBLISHED" }, }, }; const { id: _addressId, isDefault: _isDefault, ...snapshotAddress } = address; const order = { id, status: "PENDING_PAYMENT", currency: "INR", merchandiseTotal: "10", subtotal: "10", discount: "0", createdAt: new Date().toISOString(), expiresAt: new Date(Date.now() + 900000).toISOString(), pricingStatus: "UNFINALIZED", taxTotal: null, shippingTotal: null, payableTotal: null, paymentAvailable: false, address: snapshotAddress, lines: [ { variantId: id, sku: "TEST", productName: "Test candle", variantName: "Small", quantity: 1, unitPrice: "10", lineTotal: "10", }, ], }; const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status }); afterEach(() => { vi.unstubAllGlobals(); history.replaceState(null, "", "/"); }); function Login() { const platform = usePlatform(); return ( ); } function harness(children: ReactNode) { localStorage.setItem("mani.organization", id); const client = new QueryClient({ defaultOptions: { queries: { retry: false } }, }); const result = render( {children} , ); return { client, ...result }; } test("supplier document reviewer sees only permitted actions for their own upload", async () => { const version = { id, uploadedById: id, version: 1, filename: "certificate.pdf", mimeType: "application/pdf", size: 20, createdAt: "2026-11-12T00:00:00.000Z", decision: null, }; const record = { id, code: "TAX-CERT", kind: "TAX_CERTIFICATE", title: "Certificate" }; const fetch = vi.fn(async (url: string) => { if (url.endsWith("/auth/login")) return json(session); if (url.endsWith("/auth/me")) return json({ ...me, permissions: ["supplier_document.read", "supplier_document.validate"] }); if (url.includes("/documents?")) return json([record]); if (url.endsWith(`/supplier-documents/${id}`)) return json({ ...record, versions: [version] }); throw new Error(`Unexpected request ${url}`); }); vi.stubGlobal("fetch", fetch); harness(); expect(fetch).not.toHaveBeenCalled(); const user = userEvent.setup(); await user.click(screen.getByText("Test login")); await user.click(await screen.findByRole("button", { name: "Open TAX-CERT" })); await user.click(await screen.findByRole("button", { name: "View version 1" })); await screen.findByText("Another reviewer must decide on this version."); expect(screen.getByRole("button", { name: "Download PDF" })).toBeTruthy(); expect(screen.queryByRole("button", { name: "Save review decision" })).toBeNull(); expect(screen.queryByRole("button", { name: "Upload PDF version" })).toBeNull(); }); 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 = { id, receiptId: id, warehouseId: id, createdAt: "2026-11-12T00:00:00.000Z", entries: [{ id, stockItemId: id, receiptLineId: id, kind: "RECEIPT_ACCEPTED", delta: "0.125" }], }; 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: ["inventory.read", "inventory.manage"] }); if (url.includes("/inventory/warehouses?")) return json([{ id, name: "Main warehouse" }]); if (url.endsWith("/stock-posting")) { if (options?.method === "POST") { attempts.push(JSON.parse(String(options.body))); if (attempts.length === 1) throw new Error("Response lost"); return json(posting); } return attempts.length ? json(posting) : json({ code: "MATERIAL_POSTING_NOT_FOUND" }, 404); } throw new Error(`Unexpected request ${url}`); })); function AuthorizedPosting() { const { can } = usePlatform(); return can("inventory.read") ? : null; } harness(); const user = userEvent.setup(); await user.click(screen.getByText("Test login")); await user.selectOptions(await screen.findByRole("combobox", { name: "Destination warehouse" }), id); await user.click(screen.getByRole("button", { name: "Post accepted material" })); await user.click(await screen.findByRole("button", { name: "Retry warehouse posting" })); const ledger = await screen.findByRole("link", { name: "View stock ledger" }); expect(ledger.getAttribute("href")).toBe(`/admin/material-stock/${id}`); expect(attempts).toHaveLength(2); expect(attempts[0]).toEqual({ warehouseId: id, idempotencyKey: expect.any(String) }); expect(attempts[1]).toEqual(attempts[0]); expect(screen.getByText("0.125")).toBeTruthy(); }); test("uncertain checkout replays identical input after the cart version changes", async () => { const attempts: unknown[] = []; let cartChanged = false; 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); if (url.endsWith("/addresses")) return json([address]); if (url.endsWith("/cart")) return json({ version: cartChanged ? 1 : 0, lines: cartChanged ? [] : [line], }); if (url.endsWith("/checkout")) { attempts.push(JSON.parse(String(options?.body))); cartChanged = true; if (attempts.length === 1) throw new Error("Response lost"); return json(order); } if (url.includes("/orders?")) return json([]); if (url.includes(`/orders/${id}`)) return json(order); throw new Error(`Unexpected ${url}`); }), ); history.replaceState(null, "", "/cart"); const h = harness( {() => } {(params) => } , ), user = userEvent.setup(); await user.click(screen.getByText("Test login")); await screen.findByText("Test candle · Small"); await user.click(screen.getByRole("combobox", { name: "Delivery address" })); await user.click(await screen.findByRole("option")); await user.click(screen.getByRole("button", { name: "Review checkout" })); await user.click(screen.getByRole("button", { name: "Confirm order" })); await screen.findByRole("button", { name: "Retry original checkout" }); await act(() => h.client.invalidateQueries({ queryKey: ["private"] })); await screen.findByText(/Your cart is empty/); await user.click(screen.getByRole("link", { name: "Check orders" })); await screen.findByText("Order history"); await user.click(screen.getByRole("link", { name: "My cart" })); await user.click( screen.getByRole("button", { name: "Retry original checkout" }), ); await waitFor(() => expect(attempts).toHaveLength(2)); expect(attempts[1]).toEqual(attempts[0]); expect(attempts[0]).toMatchObject({ cartVersion: 0, addressId: id }); await waitFor(() => expect(location.pathname).toBe(`/orders/${id}`)); }); test("a changed cart invalidates checkout review instead of adopting a new version", async () => { let changed = false; const attempts: unknown[] = []; 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); if (url.endsWith("/addresses")) return json([address]); if (url.endsWith("/cart")) return json({ version: changed ? 2 : 0, lines: [{ ...line, quantity: changed ? 3 : 1 }], }); attempts.push(options?.body); return json(order); }), ); const h = harness(), user = userEvent.setup(); await user.click(screen.getByText("Test login")); await screen.findByText("Test candle · Small"); await user.click(screen.getByRole("combobox", { name: "Delivery address" })); await user.click(await screen.findByRole("option")); await user.click(screen.getByRole("button", { name: "Review checkout" })); changed = true; await act(() => h.client.invalidateQueries({ queryKey: ["private"] })); await screen.findByText(/Review the updated quantities/); expect(screen.queryByRole("button", { name: "Confirm order" })).toBeNull(); expect(attempts).toEqual([]); }); test("permission-denied administration never fetches private staff records", async () => { const fetch = vi.fn(async (url: string) => url.endsWith("/auth/login") ? json(session) : url.endsWith("/auth/me") ? json(me) : Promise.reject(new Error("Private records must not be fetched")), ); vi.stubGlobal("fetch", fetch); const h = harness(), user = userEvent.setup(); await user.click(screen.getByText("Test login")); await screen.findByText(/does not have permission/); expect(fetch.mock.calls.some(([url]) => url.includes("/users"))).toBe(false); const result = await axe.run(h.container, { rules: { "color-contrast": { enabled: false } }, }); expect( result.violations.filter( (v) => v.impact === "serious" || v.impact === "critical", ), ).toEqual([]); }); test("unfinalized order charges are never shown as zero or payable", async () => { vi.stubGlobal( "fetch", vi.fn(async (url: string) => url.endsWith("/auth/login") ? json(session) : url.endsWith("/auth/me") ? json(me) : json(order), ), ); harness(); const user = userEvent.setup(); await user.click(screen.getByText("Test login")); await screen.findByText(/Order .*PENDING_PAYMENT/); expect(screen.getAllByText("Unfinalized")).toHaveLength(3); expect(screen.queryByRole("button", { name: /pay now/i })).toBeNull(); expect(screen.getByText(/Payment collection is unavailable/)).toBeTruthy(); });