feat: add private supplier document workflows #14

Merged
mihir merged 1 commits from feat/supplier-documents into main 2026-11-12 01:06:42 +05:30
12 changed files with 399 additions and 26 deletions

View File

@ -34,5 +34,7 @@ Customer and administration screens are implemented, with recovery, pricing, sto
- Issued orders support partial goods receipts and final quality inspections, with exact accepted and rejected quantities and rejection reasons.
- Inspected receipts support idempotent posting to a warehouse. Staff can review material balances and movement ledgers.
- Issued orders support supplier invoices, payment records, reversals and voids. The backend enforces accepted quantities, outstanding balances and correction rules.
- Supplier documents, BOMs, production and packaging, costing, warehouse transfers and adjustments remain open.
- Private supplier PDFs support version uploads, independent review decisions, and authenticated downloads.
- BOMs, production and packaging, costing, warehouse transfers and adjustments remain open.
- Live acceptance requires an organization and procurement test users. Exercise read-only and manage roles, inactive suppliers and materials, mixed currencies, below-minimum quantities, price snapshots and purchase order state conflicts.
- Supplier document UAT requires an uploader, an independent reviewer, and a read-only account. Through the deployed ingress, upload a valid PDF near the 2 MiB limit, verify that the uploader cannot decide on it, and check that a reader can download it only after approval.

View File

@ -19,6 +19,11 @@ server {
proxy_read_timeout 20s;
proxy_hide_header Access-Control-Allow-Origin;
proxy_hide_header Access-Control-Allow-Credentials;
location ~ "^/api/v1/supplier-documents/[0-9a-fA-F-]{36}/versions$" {
client_max_body_size 3m;
proxy_pass https://manicandles-backend.midastix.com;
}
}
location / {

View File

@ -30,6 +30,7 @@ const CatalogAdminPage = lazy(() => import("@/pages/CatalogAdminPage"));
const InventoryPage = lazy(() => import("@/pages/InventoryPage"));
const MaterialStockPage = lazy(() => import("@/pages/MaterialStockPage"));
const ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
const SupplierDocumentsPage = lazy(() => import("@/pages/SupplierDocumentsPage"));
const PurchaseOrdersPage = lazy(() =>
import("@/pages/ProcurementPage").then((module) => ({ default: module.PurchaseOrdersPage })),
);
@ -81,6 +82,10 @@ function Router() {
<Route path="/admin/procurement/suppliers/:id">
{(params) => <ProcurementPage supplierId={params.id} />}
</Route>
<Route path="/admin/supplier-documents">{() => <SupplierDocumentsPage />}</Route>
<Route path="/admin/supplier-documents/:id">
{(params) => <SupplierDocumentsPage supplierId={params.id} />}
</Route>
<Route path="/admin/purchase-orders">{() => <PurchaseOrdersPage />}</Route>
<Route path="/admin/purchase-orders/:id">
{(params) => <PurchaseOrdersPage orderId={params.id} />}

View File

@ -59,6 +59,7 @@ export function WorkspaceNavigation() {
},
{ label: "Coupons", path: "/admin/coupons", permission: "coupons.manage" },
{ label: "Suppliers", path: "/admin/procurement", permission: "procurement.read" },
{ label: "Supplier documents", path: "/admin/supplier-documents", permission: "supplier_document.read" },
{ label: "Materials", path: "/admin/procurement/materials", permission: "procurement.read" },
{ label: "Purchase orders", path: "/admin/purchase-orders", permission: "procurement.read" },
{ label: "Material stock", path: "/admin/material-stock", permission: "inventory.read" },

View File

@ -73,31 +73,37 @@ export function isUnknownOutcome(error: unknown) {
);
}
export async function apiRequest(
type ApiOptions = {
token?: string;
body?: unknown;
method?: string;
signal?: AbortSignal;
};
async function fetchApiResponse(
path: string,
{
token,
body,
method = "GET",
signal,
}: {
token?: string;
body?: unknown;
method?: string;
signal?: AbortSignal;
} = {},
): Promise<unknown> {
pdf = false,
}: ApiOptions & { pdf?: boolean },
) {
let response: Response;
const multipart = body instanceof FormData;
try {
const timeout = AbortSignal.timeout(15000);
response = await fetch(`/api/v1${path}`, {
method,
signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
...(pdf || multipart ? { cache: "no-store", redirect: "error" } : {}),
headers: {
...(body === undefined ? {} : { "Content-Type": "application/json" }),
...(body === undefined || multipart ? {} : { "Content-Type": "application/json" }),
...(pdf ? { Accept: "application/pdf" } : {}),
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
...(body === undefined ? {} : { body: multipart ? body : JSON.stringify(body) }),
});
} catch (error) {
if (error instanceof Error && error.name === "AbortError") throw error;
@ -107,9 +113,8 @@ export async function apiRequest(
"NETWORK_ERROR",
);
}
if (response.status === 204) return null;
const data = await response.json().catch(() => null);
if (!response.ok)
if (!response.ok) {
const data = await response.json().catch(() => null);
throw new ApiError(
typeof data?.message === "string"
? data.message
@ -120,6 +125,14 @@ export async function apiRequest(
? data.requestId
: (response.headers.get("x-request-id") ?? undefined),
);
}
return response;
}
export async function apiRequest(path: string, options: ApiOptions = {}): Promise<unknown> {
const response = await fetchApiResponse(path, options);
if (response.status === 204) return null;
const data = await response.json().catch(() => null);
if (data === null)
throw new ApiError(
"The service returned an unexpected response.",
@ -128,6 +141,15 @@ export async function apiRequest(
);
return data;
}
export async function apiPdf(path: string, size: number, token: string, signal: AbortSignal) {
const response = await fetchApiResponse(path, { token, signal, pdf: true });
const invalidPdf = () => new ApiError("The service returned an unexpected PDF.", response.status, "INVALID_RESPONSE");
if (response.headers.get("content-type")?.split(";")[0].trim().toLowerCase() !== "application/pdf") throw invalidPdf();
const file = await response.blob();
if (file.size !== size) throw invalidPdf();
return file;
}
export function parse<T>(schema: z.ZodType<T>, data: unknown): T {
const result = schema.safeParse(data);
if (!result.success)

View File

@ -11,6 +11,7 @@ import { useQueryClient } from "@tanstack/react-query";
import { z } from "zod";
import {
apiRequest,
apiPdf,
ApiError,
getPrincipal,
login,
@ -34,6 +35,7 @@ const PlatformContext = createContext<{
saveIntent: (key: string, value: unknown) => void;
clearIntent: (key: string, idempotencyKey: string) => void;
can: (permission: string) => boolean;
downloadPdf: (versionId: string, size: number) => Promise<Blob>;
request: <T>(
path: string,
schema: z.ZodType<T>,
@ -150,10 +152,9 @@ export function PlatformProvider({ children }: { children: ReactNode }) {
);
}
}
async function request<T>(
path: string,
schema: z.ZodType<T>,
options: Options = {},
async function withSession<T>(
perform: (token: string, signal: AbortSignal) => Promise<T>,
callerSignal?: AbortSignal,
) {
const active = session;
if (
@ -166,22 +167,18 @@ export function PlatformProvider({ children }: { children: ReactNode }) {
clearSession("Your session expired. Sign in again.");
throw new ApiError("Your session expired.", 401, "SESSION_EXPIRED");
}
const signal = options.signal
? AbortSignal.any([scopeAbort.current.signal, options.signal])
const signal = callerSignal
? AbortSignal.any([scopeAbort.current.signal, callerSignal])
: scopeAbort.current.signal;
try {
const data = await apiRequest(path, {
...options,
token: active.accessToken,
signal,
});
const data = await perform(active.accessToken, signal);
if (current.current !== active || revision.current !== accessRevision)
throw new ApiError(
"Your session changed. Sign in again.",
401,
"SESSION_CHANGED",
);
return parse(schema, data);
return data;
} catch (error) {
if (
current.current === active &&
@ -226,6 +223,17 @@ export function PlatformProvider({ children }: { children: ReactNode }) {
throw error;
}
}
async function request<T>(path: string, schema: z.ZodType<T>, options: Options = {}) {
const data = await withSession(
(token, signal) => apiRequest(path, { ...options, token, signal }),
options.signal,
);
return parse(schema, data);
}
function downloadPdf(versionId: string, size: number) {
const id = z.string().uuid().parse(versionId);
return withSession((token, signal) => apiPdf(`/supplier-document-versions/${id}/download`, size, token, signal));
}
return (
<PlatformContext.Provider
value={{
@ -259,6 +267,7 @@ export function PlatformProvider({ children }: { children: ReactNode }) {
},
can: (permission) =>
Boolean(principal?.permissions.includes(permission)),
downloadPdf,
request,
}}
>

View File

@ -0,0 +1,48 @@
import { z } from "zod";
import { uuid } from "./commerce.ts";
export const maxDocumentBytes = 2 * 1024 * 1024;
const pdfFilename = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,115}\.pdf$/);
const decisionOutcome = z.enum(["APPROVED", "REJECTED"]);
export const documentInput = z.object({
code: z.string().trim().max(32).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/).toUpperCase(),
kind: z.enum(["REGISTRATION", "TAX_CERTIFICATE", "COMPLIANCE_CERTIFICATE", "OTHER"]),
title: z.string().trim().min(1).max(160),
}).strict();
export const supplierDocument = documentInput.extend({ id: uuid }).strip();
export const documentVersion = z.object({
id: uuid,
uploadedById: uuid,
version: z.number().int().min(1).max(20),
filename: pdfFilename,
mimeType: z.literal("application/pdf"),
size: z.number().int().min(1).max(maxDocumentBytes),
createdAt: z.string().datetime(),
decision: z.object({
outcome: decisionOutcome,
reason: z.string().nullable(),
}).nullable(),
});
export const documentDetails = supplierDocument.extend({ versions: z.array(documentVersion).max(20) });
export const documentDecision = z.object({
outcome: decisionOutcome,
reason: z.string().trim().min(1).max(500).optional(),
}).strict().refine((value) => value.outcome !== "REJECTED" || Boolean(value.reason), {
path: ["reason"],
message: "Enter a reason for rejecting this version.",
});
export function prepareDocumentUpload(file: FormDataEntryValue | null) {
if (!(file instanceof File) || !file.size) throw new Error("Choose a PDF file.");
if (file.size > maxDocumentBytes) throw new Error("Choose a PDF up to 2 MiB.");
if (!pdfFilename.safeParse(file.name).success) {
throw new Error("Use a simple .pdf filename with letters, numbers, dots, hyphens or underscores.");
}
if (file.type && file.type !== "application/pdf") throw new Error("Choose a PDF file.");
const body = new FormData();
body.append("file", file.type ? file : new File([file], file.name, { type: "application/pdf" }));
return body;
}

View File

@ -39,6 +39,9 @@ function Directory({ materials }: { materials: boolean }) {
<>
{can("procurement.manage") && <Button onClick={() => select(row.id)} aria-label={`Edit ${row.name}`}>Edit</Button>}
{"contactName" in row && <WorkspaceLink href={`/admin/procurement/suppliers/${row.id}`}>Supply terms and orders for {row.name}</WorkspaceLink>}
{"contactName" in row && can("supplier_document.read") && (
<> · <WorkspaceLink href={`/admin/supplier-documents/${row.id}`}>Documents for {row.name}</WorkspaceLink></>
)}
</>,
])} />
<Pager count={rows.length} offset={offset} onPage={(next) => { select(""); setOffset(next); }} />

View File

@ -0,0 +1,183 @@
import { useId, useState } from "react";
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 { uuid } from "@/lib/commerce";
import { usePlatform } from "@/lib/platform";
import { documentDecision, documentDetails, documentInput, documentVersion, prepareDocumentUpload, supplierDocument } from "@/lib/supplier-documents";
const kindOptions = [
{ value: "REGISTRATION", label: "Registration" },
{ value: "TAX_CERTIFICATE", label: "Tax certificate" },
{ value: "COMPLIANCE_CERTIFICATE", label: "Compliance certificate" },
{ value: "OTHER", label: "Other" },
];
type Version = z.infer<typeof documentVersion>;
function FindSupplier() {
const { can } = usePlatform();
const [, navigate] = useLocation();
return <Panel title="Open supplier documents">
{can("procurement.read") && <p>Choose a supplier in the <WorkspaceLink href="/admin/procurement">supplier directory</WorkspaceLink>.</p>}
<ActionForm label="Open documents" read={(data) => ({ supplierId: readText(data, "supplierId").trim() })}
submit={async (input) => {
const { supplierId } = z.object({ supplierId: uuid }).parse(input);
navigate(`/admin/supplier-documents/${supplierId}`);
}}>
<Field name="supplierId" label="Supplier ID" maxLength={36} helper="Enter the supplier UUID from a supplier document link." />
</ActionForm>
</Panel>;
}
function SupplierDocumentList({ id }: { id: string }) {
const { can, request } = usePlatform();
const [offset, setOffset] = useState(0);
const [selected, select] = useState("");
const path = `/suppliers/${id}/documents`;
const query = usePrivateQuery(`${path}?limit=25&offset=${offset}`, z.array(supplierDocument));
return <>
<p className="workspace-id">Supplier ID {id}</p>
<WorkspaceLink href="/admin/supplier-documents">Open another supplier</WorkspaceLink>
<Panel title="Documents">
<QueryView query={query}>{(rows) => <>
<Table head={["Code", "Title", "Type", "Actions"]} rowKeys={rows.map((row) => row.id)}
rows={rows.map((row) => [
row.code, row.title, kindOptions.find((kind) => kind.value === row.kind)?.label ?? row.kind,
<Button onClick={() => select(row.id)} aria-pressed={selected === row.id}>Open {row.code}</Button>,
])} />
<Pager offset={offset} count={rows.length} onPage={setOffset} />
{can("supplier_document.manage") && <ActionForm label="Create document"
read={(data) => documentInput.parse(Object.fromEntries(data))}
submit={async (body) => {
try {
const result = await request(path, supplierDocument, { method: "POST", body });
select(result.id);
setOffset(0);
} finally {
await query.refetch();
}
}}>
<Field name="code" label="Document code" maxLength={32} />
<Field name="title" label="Document title" maxLength={160} />
<Field name="kind" label="Document type" options={kindOptions} />
</ActionForm>}
</>}</QueryView>
</Panel>
{selected && <DocumentVersions key={selected} id={selected} close={() => select("")} />}
</>;
}
function DocumentVersions({ id, close }: { id: string; close: () => void }) {
const { can, request } = usePlatform();
const [versionId, select] = useState("");
const [uncertain, setUncertain] = useState(false);
const fileId = useId();
const path = `/supplier-documents/${id}`;
const query = usePrivateQuery(path, documentDetails);
return <>
<Button onClick={close}>Close document</Button>
<QueryView query={query}>{(record) => {
const version = record.versions.find((entry) => entry.id === versionId);
return <Panel title={`Versions of ${record.code}`}>
<Table head={["Version", "PDF", "Uploaded", "Review", "Actions"]} rowKeys={record.versions.map((entry) => entry.id)}
rows={record.versions.map((entry) => [
entry.version, entry.filename, new Date(entry.createdAt).toLocaleString(),
entry.decision?.outcome ?? "Pending",
<Button onClick={() => select(entry.id)} aria-pressed={versionId === entry.id}>View version {entry.version}</Button>,
])} />
{version && <VersionActions key={version.id} version={version} refresh={query.refetch} />}
{uncertain ? <Alert severity="warning">
The server may have saved the PDF. Review the version list, then close and reopen the document before uploading again.
<Button onClick={() => query.refetch()}>Refresh versions</Button>
</Alert> : can("supplier_document.manage") && (record.versions.length < 20 ? (
<ActionForm label="Upload PDF version" read={(data) => prepareDocumentUpload(data.get("file"))}
submit={async (body) => {
try {
const saved = await request(`${path}/versions`, documentVersion, { method: "POST", body });
select(saved.id);
} catch (error) {
if (isUnknownOutcome(error)) setUncertain(true);
throw error;
} finally {
await query.refetch();
}
}}>
<label htmlFor={fileId}>PDF file</label>
<input id={fileId} name="file" type="file" accept="application/pdf,.pdf" required aria-describedby={`${fileId}-help`} style={{ maxWidth: "100%" }} />
<p id={`${fileId}-help`}>Maximum 2 MiB. Use a simple .pdf filename.</p>
</ActionForm>
) : <Alert severity="info">This document has reached the 20-version limit.</Alert>)}
</Panel>;
}}</QueryView>
</>;
}
function VersionActions({ version, refresh }: { version: Version; refresh: () => Promise<unknown> }) {
const { can, principal, request, downloadPdf } = usePlatform();
const [busy, setBusy] = useState(false);
const [error, setError] = useState<unknown>(null);
const reviewer = can("supplier_document.validate");
const ownVersion = version.uploadedById === principal?.userId.toLowerCase();
return <Panel title={`Version ${version.version}`}>
<p className="workspace-id">{version.filename}</p>
{version.decision && <p>{version.decision.outcome}{version.decision.reason && ` · ${version.decision.reason}`}</p>}
{(reviewer || version.decision?.outcome === "APPROVED") && <>
<Button disabled={busy} onClick={async () => {
setBusy(true);
setError(null);
try {
const file = await downloadPdf(version.id, version.size);
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 (error) {
setError(error);
} finally {
setBusy(false);
}
}}>{busy ? "Downloading…" : "Download PDF"}</Button>
<ApiNotice error={error} />
</>}
{reviewer && !version.decision && (ownVersion ? (
<Alert severity="info">Another reviewer must decide on this version.</Alert>
) : <ActionForm label="Save review decision" read={(data) => documentDecision.parse({
outcome: readText(data, "outcome"),
reason: readText(data, "reason").trim() || undefined,
})} submit={async (body) => {
try {
await request(`/supplier-document-versions/${version.id}/decision`, documentVersion, { method: "POST", body });
} finally {
await refresh();
}
}}>
<p>Review decisions are final.</p>
<Field name="outcome" label="Review outcome" options={[
{ value: "", label: "Choose an outcome" },
{ value: "APPROVED", label: "Approve" },
{ value: "REJECTED", label: "Reject" },
]} />
<Field name="reason" label="Review reason" maxLength={500} required={false} helper="Required when rejecting a version." />
</ActionForm>)}
</Panel>;
}
export default function SupplierDocumentsPage({ supplierId }: { supplierId?: string }) {
const id = uuid.safeParse(supplierId);
return <WorkspaceShell title="Supplier Documents" permission="supplier_document.read">
{!supplierId ? <FindSupplier /> : id.success ? <SupplierDocumentList key={id.data} id={id.data} /> :
<Alert severity="warning">Invalid supplier ID. <WorkspaceLink href="/admin/supplier-documents">Open supplier documents</WorkspaceLink></Alert>}
</WorkspaceShell>;
}

View File

@ -2,6 +2,7 @@ import { test, afterEach } from "node:test";
import assert from "node:assert/strict";
import {
apiRequest,
apiPdf,
listProducts,
getProduct,
login,
@ -9,11 +10,53 @@ import {
healthCheck,
ApiError,
} from "../src/lib/api.ts";
import { documentDecision, maxDocumentBytes, prepareDocumentUpload } from "../src/lib/supplier-documents.ts";
const originalFetch = globalThis.fetch;
const org = "d66c798a-f764-4b88-8d13-ace328ff1010";
afterEach(() => {
globalThis.fetch = originalFetch;
});
test("supplier document upload sends an authenticated multipart file with a browser-generated boundary", async () => {
const file = new File(["%PDF-1.7\n%%EOF"], "certificate.pdf", { type: "application/pdf" });
const body = prepareDocumentUpload(file);
globalThis.fetch = async (url, options) => {
assert.equal(url, `/api/v1/supplier-documents/${org}/versions`);
assert.equal(options?.method, "POST");
const headers = new Headers(options?.headers);
assert.equal(headers.get("authorization"), "Bearer opaque");
assert.equal(headers.has("content-type"), false);
assert.equal(options?.redirect, "error");
assert.equal(options?.body, body);
assert.equal(body.get("file"), file);
return new Response(JSON.stringify({ version: 1 }));
};
await apiRequest(`/supplier-documents/${org}/versions`, { method: "POST", token: "opaque", body });
assert.throws(() => prepareDocumentUpload(new File(["x"], "unsafe filename.pdf")), /simple .pdf filename/);
assert.throws(() => prepareDocumentUpload(new File([new Uint8Array(maxDocumentBytes + 1)], "large.pdf")), /2 MiB/);
assert.equal(documentDecision.safeParse({ outcome: "REJECTED", reason: " " }).success, false);
assert.equal(documentDecision.safeParse({ outcome: "APPROVED" }).success, true);
});
test("private PDF downloads preserve API denial and require the expected PDF media type and size", async () => {
const controller = new AbortController();
const path = `/supplier-document-versions/${org}/download`;
const content = "%PDF-1.7\n%%EOF";
globalThis.fetch = async (url, options) => {
assert.equal(url, `/api/v1${path}`);
const headers = new Headers(options?.headers);
assert.equal(headers.get("authorization"), "Bearer opaque");
assert.equal(headers.get("accept"), "application/pdf");
assert.equal(options?.cache, "no-store");
assert.equal(options?.redirect, "error");
return new Response(content, { headers: { "Content-Type": "application/pdf" } });
};
assert.equal(await (await apiPdf(path, content.length, "opaque", controller.signal)).text(), content);
await assert.rejects(apiPdf(path, 1, "opaque", controller.signal), { code: "INVALID_RESPONSE" });
globalThis.fetch = async () => new Response(content, { headers: { "Content-Type": "text/html" } });
await assert.rejects(apiPdf(path, content.length, "opaque", controller.signal), { code: "INVALID_RESPONSE" });
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 });
});
test("invalid organization cannot trigger catalog requests", async () => {
globalThis.fetch = async () => {
assert.fail("Must not send a request");

View File

@ -39,6 +39,31 @@ function harness() {
return { client, ...renderHook(() => usePlatform(), { wrapper }) };
}
test("private PDF responses arriving after sign-out are discarded", async () => {
const pdf = "%PDF-1.7\n%%EOF";
let finish: ((response: Response) => void) | undefined;
let downloadSignal: AbortSignal | null | undefined;
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: ["supplier_document.read"] });
if (url.endsWith("/auth/logout")) return new Response(null, { status: 204 });
if (url.endsWith("/download")) {
downloadSignal = options?.signal;
return new Promise<Response>((resolve) => { finish = resolve; });
}
throw new Error(`Unexpected request ${url}`);
}));
const h = harness();
await act(() => h.result.current.signIn("staff@example.com", "test password"));
const pending = h.result.current.downloadPdf(id, pdf.length).catch((error) => error);
await waitFor(() => expect(finish).toBeDefined());
await act(() => h.result.current.signOut());
expect(downloadSignal?.aborted).toBe(true);
finish?.(new Response(pdf, { headers: { "Content-Type": "application/pdf" } }));
expect(await pending).toMatchObject({ code: "SESSION_CHANGED" });
expect(h.client.getQueriesData({ queryKey: ["private"] })).toEqual([]);
});
test("old-session intent callbacks cannot erase a newer session's command", async () => {
vi.stubGlobal(
"fetch",

View File

@ -14,6 +14,7 @@ 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";
@ -176,6 +177,32 @@ function harness(children: ReactNode) {
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(<SupplierDocumentsPage supplierId={id} />);
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 = {