ManiCandles/src/pages/SupplierDocumentsPage.tsx

184 lines
8.7 KiB
TypeScript

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>;
}