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 SamplesPage from "../src/pages/SamplesPage";
import theme from "../src/theme";
const accountId = "d66c798a-f764-4b88-8d13-ace328ff1010";
const requesterId = "d66c798a-f764-4b88-8d13-ace328ff1011";
const reviewerId = "d66c798a-f764-4b88-8d13-ace328ff1012";
const variantId = "d66c798a-f764-4b88-8d13-ace328ff1013";
const sampleId = "d66c798a-f764-4b88-8d13-ace328ff1014";
const createdAt = "2026-11-16T08:00:00.000Z";
const api = "/b2b/samples";
const route = "/admin/b2b-samples";
const requestPath = `${api}/${sampleId}`;
const sample = {
id: sampleId,
organizationId: accountId,
accountId,
variantId,
requestedById: requesterId,
sku: "VANILLA-TIN",
variantName: "Vanilla tin",
quantity: 4,
purpose: "Fragrance evaluation",
status: "REQUESTED",
createdAt,
updatedAt: createdAt,
events: [],
};
const json = (body: unknown) => new Response(JSON.stringify(body));
function staffSession(url: string, userId: 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 showSamples(children: ReactNode) {
localStorage.setItem("mani.organization", accountId);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(
{children}
);
}
afterEach(() => {
vi.unstubAllGlobals();
history.replaceState(null, "", "/");
});
test("an uncertain sample request retries with its original account, variant, quantity, purpose, and key", async () => {
const attempts: unknown[] = [];
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
const auth = staffSession(url, requesterId, ["b2b.sample.read", "b2b.sample.request"]);
if (auth) return auth;
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(sample);
}
if (url.endsWith(requestPath) && options?.method !== "POST") return json(sample);
throw new Error(`Unexpected request ${url}`);
}));
history.replaceState(null, "", `${route}/new/${accountId}`);
showSamples(
{(params) => }
{(params) => }
);
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
fireEvent.change(await screen.findByRole("textbox", { name: /Variant ID/ }), { target: { value: variantId } });
fireEvent.change(screen.getByRole("spinbutton", { name: /Sample quantity/ }), { target: { value: "4" } });
fireEvent.change(screen.getByRole("textbox", { name: /Sample purpose/ }), { target: { value: sample.purpose } });
await user.click(screen.getByRole("button", { name: "Request samples" }));
await user.click(await screen.findByRole("button", { name: "Retry sample request" }));
await screen.findByText(sample.purpose);
expect(location.pathname).toBe(`${route}/${sampleId}`);
expect(attempts[0]).toEqual({ accountId, variantId, quantity: 4, purpose: sample.purpose, idempotencyKey: expect.any(String) });
expect(attempts).toEqual([attempts[0], attempts[0]]);
});
test("a sample requester cannot review their own request or dispatch it before approval", async () => {
const fetch = vi.fn(async (url: string) => {
const auth = staffSession(url, requesterId, ["b2b.sample.read", "b2b.sample.review", "b2b.sample.dispatch"]);
if (auth) return auth;
if (url.endsWith(requestPath)) return json(sample);
throw new Error(`Unexpected request ${url}`);
});
vi.stubGlobal("fetch", fetch);
showSamples();
expect(fetch).not.toHaveBeenCalled();
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await screen.findByText(sample.purpose);
expect(screen.queryByRole("button", { name: "Record sample decision" })).toBeNull();
expect(screen.queryByRole("button", { name: "Record dispatch" })).toBeNull();
});
test("an independent reviewer can approve a request and retry a manual dispatch", async () => {
const approved = {
id: requesterId, actorId: reviewerId, sequence: 1, kind: "APPROVED", note: "Approved for evaluation",
dispatchReference: null, createdAt,
};
const dispatched = {
...approved, id: reviewerId, sequence: 2, kind: "DISPATCHED", note: "Handed to the carrier",
dispatchReference: "TRACK-01",
};
let decision: unknown;
let current: object = sample;
const dispatches: unknown[] = [];
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
const auth = staffSession(url, reviewerId, ["b2b.sample.read", "b2b.sample.review", "b2b.sample.dispatch"]);
if (auth) return auth;
if (url.endsWith(requestPath)) return json(current);
if (url.endsWith(`${requestPath}/decision`) && options?.method === "POST") {
decision = JSON.parse(String(options.body));
current = { ...sample, status: "APPROVED", events: [approved] };
return json(current);
}
if (url.endsWith(`${requestPath}/dispatch`) && options?.method === "POST") {
dispatches.push(JSON.parse(String(options.body)));
current = { ...sample, status: "DISPATCHED", events: [approved, dispatched] };
if (dispatches.length === 1) throw new Error("Response lost");
return json(current);
}
throw new Error(`Unexpected request ${url}`);
}));
showSamples();
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await user.selectOptions(await screen.findByRole("combobox", { name: /Review decision/ }), "APPROVED");
await user.type(screen.getByRole("textbox", { name: /Review note/ }), approved.note);
await user.click(screen.getByRole("button", { name: "Record sample decision" }));
await user.type(await screen.findByRole("textbox", { name: /Dispatch reference/ }), dispatched.dispatchReference);
await user.type(screen.getByRole("textbox", { name: /Dispatch note/ }), dispatched.note);
await user.click(screen.getByRole("button", { name: "Record dispatch" }));
await user.click(await screen.findByRole("button", { name: "Retry dispatch" }));
await screen.findByRole("cell", { name: dispatched.dispatchReference });
expect(screen.getByRole("cell", { name: approved.note })).toBeTruthy();
expect(screen.getByRole("cell", { name: dispatched.note })).toBeTruthy();
expect(screen.queryByRole("button", { name: "Record dispatch" })).toBeNull();
expect(decision).toEqual({ decision: "APPROVED", note: approved.note, idempotencyKey: expect.any(String) });
expect(dispatches[0]).toEqual({ dispatchReference: dispatched.dispatchReference, note: dispatched.note, idempotencyKey: expect.any(String) });
expect(dispatches).toEqual([dispatches[0], dispatches[0]]);
});