feat: manage private B2B artwork versions and approvals
continuous-integration/drone/push Build is failing Details

This commit is contained in:
mihir 2026-11-16 20:16:06 +05:30
parent 8bc34f0535
commit 5ba3619d9a
12 changed files with 622 additions and 11 deletions

View File

@ -58,4 +58,6 @@ Customer and administration screens are implemented, with recovery, pricing, sto
- Credit policy UAT should verify that unverified accounts and self-review are rejected, a second active policy in the same currency cannot be approved, and suspension permits a replacement. - Credit policy UAT should verify that unverified accounts and self-review are rejected, a second active policy in the same currency cannot be approved, and suspension permits a replacement.
- B2B samples support requests for published variants, independent approval or rejection, and manual dispatch records with staff and reference history. - B2B samples support requests for published variants, independent approval or rejection, and manual dispatch records with staff and reference history.
- Sample UAT should verify ineligible accounts and variants, self-review, dispatch only after approval, and replay with the original payload and key. - Sample UAT should verify ineligible accounts and variants, self-review, dispatch only after approval, and replay with the original payload and key.
- Artwork, partner orders and payments, custom requests and reporting remain open. - B2B artwork supports private PDF, PNG, and JPEG version uploads, independent review, and permission-based downloads.
- Artwork UAT should use separate uploader, reviewer, and reader accounts. Exercise the 2 MiB upload limit through ingress, approval and rejection, download permissions, and preservation of prior approved versions.
- Partner orders and payments, custom requests and reporting remain open.

View File

@ -20,7 +20,7 @@ server {
proxy_hide_header Access-Control-Allow-Origin; proxy_hide_header Access-Control-Allow-Origin;
proxy_hide_header Access-Control-Allow-Credentials; proxy_hide_header Access-Control-Allow-Credentials;
location ~ "^/api/v1/supplier-documents/[0-9a-fA-F-]{36}/versions$" { location ~ "^/api/v1/(?:supplier-documents|b2b/artworks)/[0-9a-fA-F-]{36}/versions$" {
client_max_body_size 3m; client_max_body_size 3m;
proxy_pass https://manicandles-backend.midastix.com; proxy_pass https://manicandles-backend.midastix.com;
} }

View File

@ -34,6 +34,7 @@ const PriceListsPage = lazy(() => import("@/pages/PriceListsPage"));
const QuotesPage = lazy(() => import("@/pages/QuotesPage")); const QuotesPage = lazy(() => import("@/pages/QuotesPage"));
const CreditPoliciesPage = lazy(() => import("@/pages/CreditPoliciesPage")); const CreditPoliciesPage = lazy(() => import("@/pages/CreditPoliciesPage"));
const SamplesPage = lazy(() => import("@/pages/SamplesPage")); const SamplesPage = lazy(() => import("@/pages/SamplesPage"));
const ArtworkPage = lazy(() => import("@/pages/ArtworkPage"));
const MaterialCostRatesPage = lazy(() => import("@/pages/MaterialCostRatesPage")); const MaterialCostRatesPage = lazy(() => import("@/pages/MaterialCostRatesPage"));
const ProcurementPage = lazy(() => import("@/pages/ProcurementPage")); const ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
const BomPage = lazy(() => import("@/pages/BomPage")); const BomPage = lazy(() => import("@/pages/BomPage"));
@ -117,6 +118,17 @@ function Router() {
<Route path="/admin/b2b-samples/:id"> <Route path="/admin/b2b-samples/:id">
{(params) => <SamplesPage id={params.id} />} {(params) => <SamplesPage id={params.id} />}
</Route> </Route>
<Route path="/admin/b2b-artwork">{() => <ArtworkPage />}</Route>
<Route path="/admin/b2b-artwork/new">{() => <ArtworkPage create />}</Route>
<Route path="/admin/b2b-artwork/new/:accountId">
{(params) => <ArtworkPage create accountId={params.accountId} />}
</Route>
<Route path="/admin/b2b-artwork/account/:accountId">
{(params) => <ArtworkPage accountId={params.accountId} />}
</Route>
<Route path="/admin/b2b-artwork/:id">
{(params) => <ArtworkPage id={params.id} />}
</Route>
<Route path="/admin/catalog">{() => <CatalogAdminPage />}</Route> <Route path="/admin/catalog">{() => <CatalogAdminPage />}</Route>
<Route path="/admin/catalog/:id"> <Route path="/admin/catalog/:id">
{(params) => <CatalogAdminPage id={params.id} />} {(params) => <CatalogAdminPage id={params.id} />}

View File

@ -75,6 +75,7 @@ export function WorkspaceNavigation() {
{ label: "B2B quotations", path: "/admin/b2b-quotes", permission: "b2b.quote.read" }, { label: "B2B quotations", path: "/admin/b2b-quotes", permission: "b2b.quote.read" },
{ label: "B2B credit policies", path: "/admin/b2b-credit-policies", permission: "b2b.credit.read" }, { label: "B2B credit policies", path: "/admin/b2b-credit-policies", permission: "b2b.credit.read" },
{ label: "B2B samples", path: "/admin/b2b-samples", permission: "b2b.sample.read" }, { label: "B2B samples", path: "/admin/b2b-samples", permission: "b2b.sample.read" },
{ label: "B2B artwork", path: "/admin/b2b-artwork", permission: "b2b.artwork.read" },
]; ];
return ( return (
<nav className="workspace-links" aria-label="Workspace navigation"> <nav className="workspace-links" aria-label="Workspace navigation">

View File

@ -87,8 +87,8 @@ async function fetchApiResponse(
body, body,
method = "GET", method = "GET",
signal, signal,
pdf = false, attachmentMime,
}: ApiOptions & { pdf?: boolean }, }: ApiOptions & { attachmentMime?: string },
) { ) {
let response: Response; let response: Response;
const multipart = body instanceof FormData; const multipart = body instanceof FormData;
@ -97,10 +97,10 @@ async function fetchApiResponse(
response = await fetch(`/api/v1${path}`, { response = await fetch(`/api/v1${path}`, {
method, method,
signal: signal ? AbortSignal.any([signal, timeout]) : timeout, signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
...(pdf || multipart ? { cache: "no-store", redirect: "error" } : {}), ...(attachmentMime || multipart ? { cache: "no-store", redirect: "error" } : {}),
headers: { headers: {
...(body === undefined || multipart ? {} : { "Content-Type": "application/json" }), ...(body === undefined || multipart ? {} : { "Content-Type": "application/json" }),
...(pdf ? { Accept: "application/pdf" } : {}), ...(attachmentMime ? { Accept: attachmentMime } : {}),
...(token ? { Authorization: `Bearer ${token}` } : {}), ...(token ? { Authorization: `Bearer ${token}` } : {}),
}, },
...(body === undefined ? {} : { body: multipart ? body : JSON.stringify(body) }), ...(body === undefined ? {} : { body: multipart ? body : JSON.stringify(body) }),
@ -142,14 +142,43 @@ export async function apiRequest(path: string, options: ApiOptions = {}): Promis
return data; return data;
} }
export async function apiPdf(path: string, size: number, token: string, signal: AbortSignal) { async function apiAttachment(
const response = await fetchApiResponse(path, { token, signal, pdf: true }); path: string,
const invalidPdf = () => new ApiError("The service returned an unexpected PDF.", response.status, "INVALID_RESPONSE"); size: number,
if (response.headers.get("content-type")?.split(";")[0].trim().toLowerCase() !== "application/pdf") throw invalidPdf(); attachmentMime: string,
token: string,
signal: AbortSignal,
errorMessage: string,
) {
const response = await fetchApiResponse(path, { token, signal, attachmentMime });
const invalidAttachment = () => new ApiError(errorMessage, response.status, "INVALID_RESPONSE");
if (response.headers.get("content-type")?.split(";")[0].trim().toLowerCase() !== attachmentMime) throw invalidAttachment();
const file = await response.blob(); const file = await response.blob();
if (file.size !== size) throw invalidPdf(); if (file.size !== size) throw invalidAttachment();
return file; return file;
} }
export function apiPdf(path: string, size: number, token: string, signal: AbortSignal) {
return apiAttachment(path, size, "application/pdf", token, signal, "The service returned an unexpected PDF.");
}
const artworkAttachment = z.object({
versionId: z.string().uuid(),
size: z.number().int().min(1).max(2 * 1024 * 1024),
mimeType: z.enum(["application/pdf", "image/png", "image/jpeg"]),
});
export async function apiArtwork(versionId: string, size: number, mimeType: string, token: string, signal: AbortSignal) {
const file = artworkAttachment.parse({ versionId, size, mimeType });
return apiAttachment(
`/b2b/artwork-versions/${file.versionId}/download`,
file.size,
file.mimeType,
token,
signal,
"The service returned an unexpected artwork attachment.",
);
}
export function parse<T>(schema: z.ZodType<T>, data: unknown): T { export function parse<T>(schema: z.ZodType<T>, data: unknown): T {
const result = schema.safeParse(data); const result = schema.safeParse(data);
if (!result.success) if (!result.success)

67
src/lib/artwork.ts Normal file
View File

@ -0,0 +1,67 @@
import { z } from "zod";
import { uuid } from "./commerce.ts";
const plainText = (max: number) =>
z.string().trim().min(3).max(max).regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text");
export const maxArtworkBytes = 2 * 1024 * 1024;
const filename = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,115}\.(pdf|png|jpg|jpeg)$/);
const mimeType = z.enum(["application/pdf", "image/png", "image/jpeg"]);
const fileTypes = new Map<string, z.infer<typeof mimeType>>([
["pdf", "application/pdf"],
["png", "image/png"],
["jpg", "image/jpeg"],
["jpeg", "image/jpeg"],
]);
export const artworkAccept = ".pdf,.png,.jpg,.jpeg";
export const artworkPlacement = z.enum(["LABEL", "PACKAGING", "CANDLE", "OTHER"]);
const outcome = z.enum(["APPROVED", "REJECTED"]);
export const artworkInput = z.object({
accountId: uuid,
name: plainText(160),
placement: artworkPlacement,
brief: plainText(1000),
}).strict();
export const artworkDecision = z.object({ outcome, note: plainText(500) }).strict();
export const artworkProject = artworkInput.extend({
id: uuid,
createdAt: z.string().datetime(),
}).strip();
export const artworkVersion = z.object({
id: uuid,
artworkId: uuid,
uploadedById: uuid,
version: z.number().int().min(1).max(20),
filename,
mimeType,
sha256: z.string().regex(/^[a-f0-9]{64}$/),
size: z.number().int().min(1).max(maxArtworkBytes),
createdAt: z.string().datetime(),
decision: artworkDecision.extend({ reviewerId: uuid, createdAt: z.string().datetime() }).strip().nullable(),
}).refine((version) => matchingType(version.filename) === version.mimeType, {
path: ["mimeType"],
message: "The artwork media type must match its filename.",
});
export const artworkDetails = artworkProject.extend({ versions: z.array(artworkVersion).max(20) });
function matchingType(name: string) {
return fileTypes.get(name.split(".").at(-1) ?? "");
}
export function prepareArtworkUpload(file: FormDataEntryValue | null) {
if (!(file instanceof File) || !file.size) throw new Error("Choose a PDF, PNG, or JPEG file.");
if (file.size > maxArtworkBytes) throw new Error("Choose an artwork file up to 2 MiB.");
const type = matchingType(file.name);
if (!filename.safeParse(file.name).success || !type) {
throw new Error("Use a simple filename ending in .pdf, .png, .jpg or .jpeg.");
}
if (file.type && file.type !== type) throw new Error("The file type must match its extension.");
const body = new FormData();
body.append("file", file.type ? file : new File([file], file.name, { type }));
return body;
}

View File

@ -11,6 +11,7 @@ import { useQueryClient } from "@tanstack/react-query";
import { z } from "zod"; import { z } from "zod";
import { import {
apiRequest, apiRequest,
apiArtwork,
apiPdf, apiPdf,
ApiError, ApiError,
getPrincipal, getPrincipal,
@ -36,6 +37,7 @@ const PlatformContext = createContext<{
clearIntent: (key: string, idempotencyKey: string) => void; clearIntent: (key: string, idempotencyKey: string) => void;
can: (permission: string) => boolean; can: (permission: string) => boolean;
downloadPdf: (versionId: string, size: number) => Promise<Blob>; downloadPdf: (versionId: string, size: number) => Promise<Blob>;
downloadArtwork: (versionId: string, size: number, mimeType: string) => Promise<Blob>;
request: <T>( request: <T>(
path: string, path: string,
schema: z.ZodType<T>, schema: z.ZodType<T>,
@ -234,6 +236,9 @@ export function PlatformProvider({ children }: { children: ReactNode }) {
const id = z.string().uuid().parse(versionId); const id = z.string().uuid().parse(versionId);
return withSession((token, signal) => apiPdf(`/supplier-document-versions/${id}/download`, size, token, signal)); return withSession((token, signal) => apiPdf(`/supplier-document-versions/${id}/download`, size, token, signal));
} }
function downloadArtwork(versionId: string, size: number, mimeType: string) {
return withSession((token, signal) => apiArtwork(versionId, size, mimeType, token, signal));
}
return ( return (
<PlatformContext.Provider <PlatformContext.Provider
value={{ value={{
@ -268,6 +273,7 @@ export function PlatformProvider({ children }: { children: ReactNode }) {
can: (permission) => can: (permission) =>
Boolean(principal?.permissions.includes(permission)), Boolean(principal?.permissions.includes(permission)),
downloadPdf, downloadPdf,
downloadArtwork,
request, request,
}} }}
> >

207
src/pages/ArtworkPage.tsx Normal file
View File

@ -0,0 +1,207 @@
import { useId, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useLocation } from "wouter";
import { z } from "zod";
import Alert from "@mui/material/Alert";
import Button from "@mui/material/Button";
import { ApiNotice } from "@/components/ApiNotice";
import { WorkspaceShell } from "@/components/WorkspaceShell";
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
import { isUnknownOutcome } from "@/lib/api";
import { artworkAccept, artworkDecision, artworkDetails, artworkInput, artworkPlacement, artworkProject, artworkVersion, prepareArtworkUpload } from "@/lib/artwork";
import { uuid } from "@/lib/commerce";
import { usePlatform } from "@/lib/platform";
const api = "/b2b/artworks";
const route = "/admin/b2b-artwork";
const placements = artworkPlacement.options.map((value) => ({ value, label: value[0] + value.slice(1).toLowerCase() }));
type Version = z.infer<typeof artworkVersion>;
function ArtworkList({ accountId }: { accountId?: string }) {
const { can } = usePlatform();
const [offset, setOffset] = useState(0);
const params = new URLSearchParams({ limit: "25", offset: String(offset) });
if (accountId) params.set("accountId", accountId);
const query = usePrivateQuery(`${api}?${params}`, z.array(artworkProject));
return <Panel title="Artwork projects">
{accountId && <p className="workspace-id">Business account {accountId}</p>}
{can("b2b.artwork.manage") && <p><WorkspaceLink href={`${route}/new${accountId ? `/${accountId}` : ""}`}>New artwork project</WorkspaceLink></p>}
<QueryView query={query}>{(rows) => <>
<Table head={["Project", "Placement", "Business account ID", "Created"]} rowKeys={rows.map((row) => row.id)}
rows={rows.map((row) => [
<WorkspaceLink href={`${route}/${row.id}`}>{row.name}</WorkspaceLink>,
row.placement, row.accountId, new Date(row.createdAt).toLocaleString(),
])} />
<Pager offset={offset} count={rows.length} onPage={setOffset} />
</>}</QueryView>
</Panel>;
}
function CreateArtwork({ accountId }: { accountId?: string }) {
const { can, request, scope } = usePlatform();
const [, navigate] = useLocation();
const client = useQueryClient();
const [uncertainAccount, setUncertainAccount] = useState("");
if (!can("b2b.artwork.manage")) return <Alert severity="warning">Your account does not have permission to create artwork projects.</Alert>;
function refreshLists() {
return client.invalidateQueries({
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
typeof queryKey[2] === "string" && queryKey[2].startsWith(`${api}?`),
});
}
return <Panel title="New artwork project">
{uncertainAccount ? <Alert severity="warning">
The server may have saved the project. <WorkspaceLink href={`${route}/account/${uncertainAccount}`}>Check the business’s artwork projects</WorkspaceLink> before creating it again.
</Alert> : <ActionForm label="Create artwork project" reset={false} read={(data) => ({
accountId: accountId ?? readText(data, "accountId").trim(),
name: readText(data, "name"),
placement: readText(data, "placement"),
brief: readText(data, "brief"),
})} submit={async (input) => {
const body = artworkInput.parse(input);
try {
const saved = await request(api, artworkProject, { method: "POST", body });
await refreshLists();
navigate(`${route}/${saved.id}`);
} catch (error) {
if (isUnknownOutcome(error)) {
setUncertainAccount(body.accountId);
await refreshLists();
}
throw error;
}
}}>
<p>Create a project for a verified business account.</p>
{accountId ? <p className="workspace-id">Business account {accountId}</p> :
<Field name="accountId" label="Business account ID" maxLength={36} />}
{!accountId && can("b2b.read") && <WorkspaceLink href="/admin/business-accounts">Business directory</WorkspaceLink>}
<Field name="name" label="Project name" maxLength={160} />
<Field name="placement" label="Artwork placement" value="LABEL" options={placements} />
<Field name="brief" label="Artwork brief" maxLength={1000} />
</ActionForm>}
</Panel>;
}
function ArtworkDetail({ id }: { id: string }) {
const { can, principal, request } = usePlatform();
const [uncertain, setUncertain] = useState(false);
const fileId = useId();
const path = `${api}/${id}`;
const query = usePrivateQuery(path, artworkDetails);
const reviewer = can("b2b.artwork.review");
const userId = principal?.userId.toLowerCase();
return <QueryView query={query}>{(project) => {
const latest = project.versions[0];
const pending = latest && !latest.decision;
return <div className="workspace-id">
<Panel title={project.name}>
<p>{project.placement} · Business account {project.accountId}</p>
<p>{project.brief}</p>
<WorkspaceLink href={`${route}/account/${project.accountId}`}>All artwork projects for this business</WorkspaceLink>
{can("b2b.read") && <p><WorkspaceLink href={`/admin/business-accounts/${project.accountId}`}>Business profile</WorkspaceLink></p>}
</Panel>
<Panel title="Artwork versions">
<Table head={["Version", "File", "Review", "Actions"]}
rowKeys={project.versions.map((version) => version.id)}
rows={project.versions.map((version) => [
version.version,
<><p>{version.filename} · {new Date(version.createdAt).toLocaleString()}</p>
<details><summary>Version identifiers</summary><p>ID {version.id}</p><p>SHA-256 {version.sha256}</p></details></>,
version.decision ? <>{version.decision.outcome} · {version.decision.note}
<p>Reviewed {new Date(version.decision.createdAt).toLocaleString()} by {version.decision.reviewerId}</p></> : "Pending",
(reviewer || version.uploadedById === userId || version.decision?.outcome === "APPROVED") &&
<DownloadArtwork version={version} />,
])} />
{pending && reviewer && (latest.uploadedById === userId ?
<Alert severity="info">A different staff member must review this version.</Alert> :
<ReviewArtwork key={latest.id} version={latest} refresh={query.refetch} />)}
{can("b2b.artwork.manage") && <>
{uncertain && <Alert severity="warning">
The server may have saved the file. Check the version history before attempting another upload.
<Button onClick={() => query.refetch()}>Refresh versions</Button>
</Alert>}
{pending ? <p>The latest version needs a review decision before another file can be uploaded.</p> :
project.versions.length >= 20 ? <p>This project has reached the 20-version limit.</p> :
!uncertain && <ActionForm label="Upload artwork version" read={(data) => prepareArtworkUpload(data.get("file"))}
submit={async (body) => {
try {
await request(`${path}/versions`, artworkVersion, { method: "POST", body });
} catch (error) {
if (isUnknownOutcome(error)) setUncertain(true);
throw error;
} finally {
await query.refetch();
}
}}>
<label htmlFor={fileId}>Artwork file</label>
<input id={fileId} name="file" type="file" accept={artworkAccept} required
aria-describedby={`${fileId}-help`} style={{ maxWidth: "100%" }} />
<p id={`${fileId}-help`}>Choose a PDF, PNG, or JPEG up to 2 MiB with a simple filename.</p>
</ActionForm>}
</>}
</Panel>
</div>;
}}</QueryView>;
}
function ReviewArtwork({ version, refresh }: { version: Version; refresh: () => Promise<unknown> }) {
const { request } = usePlatform();
return <ActionForm label="Record artwork decision" reset={false} read={(data) => artworkDecision.parse({
outcome: readText(data, "outcome"), note: readText(data, "note"),
})} submit={async (body) => {
try {
await request(`/b2b/artwork-versions/${version.id}/decision`, artworkVersion, { method: "POST", body });
} finally {
await refresh();
}
}}>
<p>Review version {version.version}. The decision is permanent and applies to this file.</p>
<Field name="outcome" label="Review decision" options={[
{ value: "", label: "Choose a decision" }, { value: "APPROVED", label: "Approve" }, { value: "REJECTED", label: "Reject" },
]} />
<Field name="note" label="Review note" maxLength={500} />
</ActionForm>;
}
function DownloadArtwork({ version }: { version: Version }) {
const { downloadArtwork } = usePlatform();
const [busy, setBusy] = useState(false);
const [error, setError] = useState<unknown>(null);
return <>
<Button disabled={busy} onClick={async () => {
setBusy(true);
setError(null);
try {
const file = await downloadArtwork(version.id, version.size, version.mimeType);
const url = URL.createObjectURL(file);
const link = document.createElement("a");
link.href = url;
link.download = version.filename;
try {
document.body.append(link);
link.click();
} finally {
link.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
}
} catch (cause) {
setError(cause);
} finally {
setBusy(false);
}
}}>{busy ? "Downloading…" : `Download artwork version ${version.version}`}</Button>
<ApiNotice error={error} />
</>;
}
export default function ArtworkPage({ id, accountId, create = false }: { id?: string; accountId?: string; create?: boolean }) {
const project = uuid.safeParse(id);
const account = uuid.safeParse(accountId);
return <WorkspaceShell title="B2B Artwork" permission="b2b.artwork.read">
{(id || accountId || create) && <WorkspaceLink href={route}>All artwork projects</WorkspaceLink>}
{(id && !project.success) || (accountId && !account.success) ? <Alert severity="warning">Invalid project or business account ID.</Alert> :
create ? <CreateArtwork key={account.data ?? "new"} accountId={account.data} /> :
project.success ? <ArtworkDetail key={project.data} id={project.data} /> :
<ArtworkList key={account.data ?? "all"} accountId={account.data} />}
</WorkspaceShell>;
}

View File

@ -129,6 +129,9 @@ function Details({ id, refreshDirectory }: { id: string; refreshDirectory: () =>
{can("b2b.sample.read") && <p><WorkspaceLink href={`/admin/b2b-samples/account/${account.id}`}>Business sample requests</WorkspaceLink></p>} {can("b2b.sample.read") && <p><WorkspaceLink href={`/admin/b2b-samples/account/${account.id}`}>Business sample requests</WorkspaceLink></p>}
{account.status === "VERIFIED" && can("b2b.sample.read") && can("b2b.sample.request") && {account.status === "VERIFIED" && can("b2b.sample.read") && can("b2b.sample.request") &&
<p><WorkspaceLink href={`/admin/b2b-samples/new/${account.id}`}>Request samples for this business</WorkspaceLink></p>} <p><WorkspaceLink href={`/admin/b2b-samples/new/${account.id}`}>Request samples for this business</WorkspaceLink></p>}
{can("b2b.artwork.read") && <p><WorkspaceLink href={`/admin/b2b-artwork/account/${account.id}`}>Business artwork projects</WorkspaceLink></p>}
{account.status === "VERIFIED" && can("b2b.artwork.read") && can("b2b.artwork.manage") &&
<p><WorkspaceLink href={`/admin/b2b-artwork/new/${account.id}`}>Create artwork project for this business</WorkspaceLink></p>}
<ReadProfile profile={account} /> <ReadProfile profile={account} />
</Panel> </Panel>
<Review key={`${account.profileVersion}:${account.latestEvent?.sequence ?? 0}`} account={account} path={path} refresh={refresh} /> <Review key={`${account.profileVersion}:${account.latestEvent?.sequence ?? 0}`} account={account} path={path} refresh={refresh} />

View File

@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import { import {
apiRequest, apiRequest,
apiPdf, apiPdf,
apiArtwork,
listProducts, listProducts,
getProduct, getProduct,
login, login,
@ -57,6 +58,50 @@ test("private PDF downloads preserve API denial and require the expected PDF med
globalThis.fetch = async () => Response.json({ code: "DOCUMENT_PENDING_REVIEW" }, { status: 403 }); globalThis.fetch = async () => Response.json({ code: "DOCUMENT_PENDING_REVIEW" }, { status: 403 });
await assert.rejects(apiPdf(path, content.length, "opaque", controller.signal), { code: "DOCUMENT_PENDING_REVIEW", status: 403 }); await assert.rejects(apiPdf(path, content.length, "opaque", controller.signal), { code: "DOCUMENT_PENDING_REVIEW", status: 403 });
}); });
test("private artwork downloads authenticate and enforce the declared file type and size", async () => {
const controller = new AbortController();
const content = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
const mimeType = "image/png";
globalThis.fetch = async (url, options) => {
assert.equal(url, `/api/v1/b2b/artwork-versions/${org}/download`);
const headers = new Headers(options?.headers);
assert.equal(headers.get("authorization"), "Bearer opaque");
assert.equal(headers.get("accept"), mimeType);
assert.equal(options?.cache, "no-store");
assert.equal(options?.redirect, "error");
assert.equal(options?.signal?.aborted, false);
return new Response(content, { headers: { "Content-Type": mimeType } });
};
const file = await apiArtwork(org, content.length, mimeType, "opaque", controller.signal);
assert.deepEqual(new Uint8Array(await file.arrayBuffer()), content);
await assert.rejects(apiArtwork(org, 1, mimeType, "opaque", controller.signal), { code: "INVALID_RESPONSE" });
globalThis.fetch = async () =>
new Response(content, { headers: { "Content-Type": "image/jpeg" } });
await assert.rejects(apiArtwork(org, content.length, mimeType, "opaque", controller.signal), { code: "INVALID_RESPONSE" });
globalThis.fetch = async () => Response.json({ code: "B2B_ARTWORK_DOWNLOAD_DENIED" }, { status: 403 });
await assert.rejects(apiArtwork(org, content.length, mimeType, "opaque", controller.signal), {
code: "B2B_ARTWORK_DOWNLOAD_DENIED", status: 403,
});
});
test("artwork download validates metadata before fetch and propagates aborts", async () => {
const controller = new AbortController();
globalThis.fetch = async () => {
assert.fail("Invalid artwork metadata must not send a request");
};
await assert.rejects(apiArtwork("../auth/me", 1, "application/pdf", "opaque", controller.signal), { name: "ZodError" });
await assert.rejects(apiArtwork(org, 1, "text/html", "opaque", controller.signal), { name: "ZodError" });
await assert.rejects(apiArtwork(org, 2 * 1024 * 1024 + 1, "image/jpeg", "opaque", controller.signal), { name: "ZodError" });
globalThis.fetch = async (_url, options) => {
const signal = options?.signal;
assert.ok(signal);
controller.abort(new Error("Test abort"));
assert.equal(signal.aborted, true);
throw new DOMException("Request cancelled", "AbortError");
};
await assert.rejects(apiArtwork(org, 1, "image/jpeg", "opaque", controller.signal), { name: "AbortError" });
});
test("invalid organization cannot trigger catalog requests", async () => { test("invalid organization cannot trigger catalog requests", async () => {
globalThis.fetch = async () => { globalThis.fetch = async () => {
assert.fail("Must not send a request"); assert.fail("Must not send a request");

57
test/artwork.test.ts Normal file
View File

@ -0,0 +1,57 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import {
artworkDecision,
artworkDetails,
artworkInput,
artworkProject,
artworkVersion,
maxArtworkBytes,
prepareArtworkUpload,
} from "../src/lib/artwork.ts";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
const date = "2026-11-16T00:00:00.000Z";
const input = { accountId: id, name: "Brand refresh", placement: "LABEL", brief: "Use the supplied customer logo." };
const version = {
id, artworkId: id, uploadedById: id, version: 1, filename: "brand-proof.jpeg",
mimeType: "image/jpeg", sha256: "a".repeat(64), size: 10, createdAt: date, decision: null,
};
test("artwork creation and decisions enforce placement and trimmed plain-text notes", () => {
assert.deepEqual(artworkInput.parse({ ...input, name: " Brand refresh " }), input);
assert.equal(artworkInput.safeParse({ ...input, placement: "BANNER" }).success, false);
assert.equal(artworkInput.safeParse({ ...input, brief: " " }).success, false);
assert.equal(artworkInput.safeParse({ ...input, brief: "<logo>" }).success, false);
assert.deepEqual(artworkDecision.parse({ outcome: "APPROVED", note: " Looks good " }), { outcome: "APPROVED", note: "Looks good" });
assert.equal(artworkDecision.safeParse({ outcome: "REJECTED", note: "" }).success, false);
});
test("project and version reads retain safe metadata and strip payload bytes", () => {
const project = { ...input, id, createdAt: date };
assert.deepEqual(artworkProject.parse({ ...project, organizationId: id }), project);
assert.deepEqual(artworkDetails.parse({ ...project, versions: [{ ...version, content: [1, 2, 3] }] }),
{ ...project, versions: [version] });
const decision = { outcome: "APPROVED", note: "Reviewed the final logo", reviewerId: id, createdAt: date };
assert.equal(artworkVersion.parse({ ...version, decision }).decision?.reviewerId, id);
assert.equal(artworkVersion.safeParse({ ...version, mimeType: "image/svg+xml" }).success, false);
assert.equal(artworkVersion.safeParse({ ...version, mimeType: "application/pdf" }).success, false);
assert.equal(artworkVersion.safeParse({ ...version, size: maxArtworkBytes + 1 }).success, false);
});
test("artwork uploads use a single multipart file with the permitted media type", () => {
for (const [filename, type] of [["proof.pdf", "application/pdf"], ["proof.png", "image/png"], ["proof.jpg", "image/jpeg"], ["proof.jpeg", "image/jpeg"]]) {
const form = prepareArtworkUpload(new File(["bytes"], filename, { type }));
const selected = form.get("file");
assert.ok(selected instanceof File);
assert.equal(selected.name, filename);
assert.equal(selected.type, type);
assert.deepEqual([...form.keys()], ["file"]);
}
assert.equal((prepareArtworkUpload(new File(["bytes"], "proof.png")).get("file") as File).type, "image/png");
assert.throws(() => prepareArtworkUpload(null));
assert.throws(() => prepareArtworkUpload(new File(["bytes"], "public.svg", { type: "image/svg+xml" })));
assert.throws(() => prepareArtworkUpload(new File(["bytes"], "unsafe name.png", { type: "image/png" })));
assert.throws(() => prepareArtworkUpload(new File(["bytes"], "wrong.png", { type: "image/jpeg" })));
assert.throws(() => prepareArtworkUpload(new File([new Uint8Array(maxArtworkBytes + 1)], "large.pdf", { type: "application/pdf" })));
});

182
test/artwork.ui.test.tsx Normal file
View File

@ -0,0 +1,182 @@
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 <button onClick={() => signIn("staff@example.com", "test password")}>Test login</button>;
}
function showArtwork(children: ReactNode) {
localStorage.setItem("mani.organization", accountId);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(<ThemeProvider theme={theme}>
<QueryClientProvider client={client}>
<PlatformProvider><Login />{children}</PlatformProvider>
</QueryClientProvider>
</ThemeProvider>);
}
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(<ArtworkPage id={artworkId} />);
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(<ArtworkPage id={artworkId} />);
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(<ArtworkPage id={artworkId} />);
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<HTMLInputElement>("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(<Switch>
<Route path={`${route}/new/:accountId`}>
{(params) => <ArtworkPage create accountId={params.accountId} />}
</Route>
<Route path={`${route}/:id`}>{(params) => <ArtworkPage id={params.id} />}</Route>
</Switch>);
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<HTMLInputElement>(/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();
});