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 ArtworkPage from "../src/pages/ArtworkPage";
import theme from "../src/theme";
const accountId = "d66c798a-f764-4b88-8d13-ace328ff1010";
const artworkId = "d66c798a-f764-4b88-8d13-ace328ff1011";
const firstVersionId = "d66c798a-f764-4b88-8d13-ace328ff1012";
const secondVersionId = "d66c798a-f764-4b88-8d13-ace328ff1013";
const uploaderId = "d66c798a-f764-4b88-8d13-ace328ff1014";
const reviewerId = "d66c798a-f764-4b88-8d13-ace328ff1015";
const createdAt = "2026-11-16T08:00:00.000Z";
const api = "/b2b/artworks";
const path = `${api}/${artworkId}`;
const route = "/admin/b2b-artwork";
const project = {
id: artworkId, accountId, name: "Seasonal gift branding", placement: "PACKAGING",
brief: "Use the supplied mark on a matte kraft box", createdAt,
};
const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
const first = {
id: firstVersionId, artworkId, uploadedById: uploaderId, version: 1, filename: "artwork-v1.png",
mimeType: "image/png", size: png.length, sha256: "a".repeat(64), createdAt,
};
const pendingVersion = { ...first, version: 2, id: secondVersionId, filename: "artwork-v2.png", decision: null };
const previousVersion = {
...first,
decision: { outcome: "APPROVED", note: "Original file approved", reviewerId, createdAt },
};
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 showArtwork(children: ReactNode) {
localStorage.setItem("mani.organization", accountId);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(
{children}
);
}
afterEach(() => {
vi.unstubAllGlobals();
history.replaceState(null, "", "/");
});
test("artwork readers can download approved versions but cannot download pending versions", async () => {
const fetch = vi.fn(async (url: string) => {
const auth = staffSession(url, reviewerId, ["b2b.artwork.read"]);
if (auth) return auth;
if (url.endsWith(path)) return json({ ...project, versions: [pendingVersion, previousVersion] });
throw new Error(`Unexpected request ${url}`);
});
vi.stubGlobal("fetch", fetch);
showArtwork();
expect(fetch).not.toHaveBeenCalled();
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await screen.findByRole("button", { name: "Download artwork version 1" });
expect(screen.getByText(/^artwork-v2\.png /)).toBeTruthy();
expect(screen.queryByRole("button", { name: "Download artwork version 2" })).toBeNull();
expect(screen.queryByRole("button", { name: "Record artwork decision" })).toBeNull();
expect(screen.queryByRole("button", { name: "Upload artwork version" })).toBeNull();
});
test("the uploader can download their pending file and must wait for independent review", async () => {
vi.stubGlobal("fetch", vi.fn(async (url: string) => {
const auth = staffSession(url, uploaderId, ["b2b.artwork.read", "b2b.artwork.manage", "b2b.artwork.review"]);
if (auth) return auth;
if (url.endsWith(path)) return json({ ...project, versions: [pendingVersion, previousVersion] });
throw new Error(`Unexpected request ${url}`);
}));
showArtwork();
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await screen.findByText("A different staff member must review this version.");
expect(screen.getByRole("button", { name: "Download artwork version 2" })).toBeTruthy();
expect(screen.queryByRole("button", { name: "Record artwork decision" })).toBeNull();
expect(screen.queryByRole("button", { name: "Upload artwork version" })).toBeNull();
});
test("an independent reviewer can approve the latest artwork version", async () => {
const note = "Brand mark is legible";
let submitted: unknown;
let current: typeof pendingVersion | typeof previousVersion = pendingVersion;
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
const auth = staffSession(url, reviewerId, ["b2b.artwork.read", "b2b.artwork.review"]);
if (auth) return auth;
if (url.endsWith(path)) return json({ ...project, versions: [current, previousVersion] });
if (url.endsWith(`/b2b/artwork-versions/${secondVersionId}/decision`) && options?.method === "POST") {
submitted = JSON.parse(String(options.body));
current = { ...pendingVersion, decision: { outcome: "APPROVED", note, reviewerId, createdAt } };
return json(current);
}
throw new Error(`Unexpected request ${url}`);
}));
showArtwork();
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/ }), note);
await user.click(screen.getByRole("button", { name: "Record artwork decision" }));
await screen.findByText(new RegExp(note));
expect(submitted).toEqual({ outcome: "APPROVED", note });
expect(screen.getByText(/Original file approved/)).toBeTruthy();
expect(screen.queryByRole("button", { name: "Record artwork decision" })).toBeNull();
});
test("a staff member can create a project and upload its first private PNG version", async () => {
const version = { ...first, decision: null };
let projectBody: unknown;
let uploadBody: FormData | undefined;
// jsdom reads its internal file list when constructing FormData, while user-event exposes the selected file on the input.
vi.stubGlobal("FormData", class extends FormData {
constructor(form?: HTMLFormElement) {
super(form);
const file = form?.querySelector("input[type=file]")?.files?.[0];
if (file) this.set("file", file);
}
});
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
const auth = staffSession(url, uploaderId, ["b2b.artwork.read", "b2b.artwork.manage"]);
if (auth) return auth;
if (url.endsWith(api) && options?.method === "POST") {
projectBody = JSON.parse(String(options.body));
return json(project);
}
if (url.endsWith(path)) return json({ ...project, versions: uploadBody ? [version] : [] });
if (url.endsWith(`${path}/versions`) && options?.method === "POST" && options.body instanceof FormData) {
uploadBody = options.body;
return json(version);
}
throw new Error(`Unexpected request ${url}`);
}));
history.replaceState(null, "", `${route}/new/${accountId}`);
showArtwork(
{(params) => }
{(params) => }
);
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await user.type(await screen.findByRole("textbox", { name: /Project name/ }), project.name);
await user.selectOptions(screen.getByRole("combobox", { name: /Artwork placement/ }), project.placement);
await user.type(screen.getByRole("textbox", { name: /Artwork brief/ }), project.brief);
await user.click(screen.getByRole("button", { name: "Create artwork project" }));
const input = await screen.findByLabelText(/Artwork file/);
const file = new File([png], first.filename, { type: first.mimeType });
await user.upload(input, file);
expect(input.files?.[0]).toBe(file);
// The native required check also reads jsdom's internal list, so start at the submit event.
fireEvent.submit(screen.getByRole("form", { name: "Upload artwork version" }));
await screen.findByRole("button", { name: "Download artwork version 1" });
expect(location.pathname).toBe(`${route}/${artworkId}`);
expect(projectBody).toEqual({ accountId, name: project.name, placement: project.placement, brief: project.brief });
expect(uploadBody?.get("file")).toMatchObject({ name: first.filename, type: first.mimeType, size: png.length });
expect(screen.queryByRole("button", { name: "Upload artwork version" })).toBeNull();
});