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 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("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();
});