ManiCandles/src/pages/BusinessAccountsPage.tsx

231 lines
12 KiB
TypeScript

import { useRef, useState } from "react";
import { useLocation } from "wouter";
import { useQueryClient } from "@tanstack/react-query";
import { z } from "zod";
import Alert from "@mui/material/Alert";
import { WorkspaceShell } from "@/components/WorkspaceShell";
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
import { ConfirmAction } from "@/components/ConfirmAction";
import { businessAccount, businessEvent, businessInput, businessProfile, businessSearch, decisionInput, submissionInput } from "@/lib/business";
import { isUnknownOutcome } from "@/lib/api";
import { uuid } from "@/lib/commerce";
import { usePlatform } from "@/lib/platform";
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
const route = "/admin/business-accounts";
const api = "/b2b/accounts";
type Account = z.infer<typeof businessAccount>;
type Profile = z.infer<typeof businessProfile>;
const fields = [
{ name: "legalName", label: "Legal name", maxLength: 160 },
{ name: "tradingName", label: "Trading name", maxLength: 160, optional: true },
{ name: "registrationNumber", label: "Registration number", maxLength: 64 },
{ name: "taxIdentifier", label: "Tax identifier", maxLength: 64, optional: true },
{ name: "countryCode", label: "Country code", maxLength: 2 },
{ name: "contactEmail", label: "Contact email", maxLength: 254, type: "email" },
{ name: "contactPhone", label: "Contact phone", maxLength: 24, type: "tel", optional: true },
{ name: "billingLine1", label: "Billing address", maxLength: 200 },
{ name: "billingCity", label: "Billing city", maxLength: 100 },
{ name: "billingRegion", label: "Billing region", maxLength: 100 },
{ name: "billingPostalCode", label: "Billing postal code", maxLength: 20 },
] as const satisfies readonly { name: keyof Profile; label: string; maxLength: number; optional?: boolean; type?: string }[];
function AccountList() {
const { can } = usePlatform();
const [search, setSearch] = useState("");
const [offset, setOffset] = useState(0);
const params = new URLSearchParams({ limit: "25", offset: String(offset), ...(search ? { search } : {}) });
const query = usePrivateQuery(`${api}?${params}`, z.array(businessAccount));
return <Panel title="Business directory">
{can("b2b.manage") && <p><WorkspaceLink href={`${route}/new`}>Create business account</WorkspaceLink></p>}
<ActionForm label="Search businesses" reset={false}
read={(form) => ({ search: readText(form, "search") })}
submit={async (value) => {
setSearch(z.object({ search: businessSearch }).parse(value).search);
setOffset(0);
}}>
<Field name="search" label="Business name or code" required={false} maxLength={100} />
</ActionForm>
<QueryView query={query}>{(rows) => <>
<Table head={["Business", "Code", "Country", "Status"]} rowKeys={rows.map((row) => row.id)}
rows={rows.map((row) => [
<WorkspaceLink href={`${route}/${row.id}`}>{row.legalName}</WorkspaceLink>,
row.code, row.countryCode, row.status,
])} />
<Pager offset={offset} count={rows.length} onPage={setOffset} />
</>}</QueryView>
</Panel>;
}
function ProfileFields({ account }: { account?: Account }) {
return <>
{!account && <Field name="code" label="Business code" maxLength={32} helper="The business code is permanent." />}
{fields.map((field) => (
<Field key={field.name} name={field.name} label={field.label} maxLength={field.maxLength}
required={!("optional" in field)} type={"type" in field ? field.type : undefined}
value={account?.[field.name] ?? ""} />
))}
</>;
}
function readProfile(form: FormData) {
return Object.fromEntries(fields.map((field) => {
const value = readText(form, field.name).trim();
return [field.name, "optional" in field ? value || null : value];
}));
}
function ReadProfile({ profile }: { profile: Profile }) {
return <dl className="permission-list">
{fields.map((field) => <div key={field.name}><dt>{field.label}</dt><dd>{profile[field.name] ?? "—"}</dd></div>)}
</dl>;
}
function CreateAccount({ refreshDirectory }: { refreshDirectory: () => Promise<void> }) {
const { can, request } = usePlatform();
const [, navigate] = useLocation();
const [uncertainCode, setUncertainCode] = useState("");
if (!can("b2b.manage")) return <Alert severity="warning">Your account does not have permission to create business profiles.</Alert>;
return <Panel title="New business profile">
{uncertainCode ? <Alert severity="warning">The server may have saved {uncertainCode}. Search the business directory for that code before creating it again.</Alert> :
<ActionForm label="Save business draft" reset={false}
read={(form) => businessInput.parse({ ...readProfile(form), code: readText(form, "code") })}
submit={async (value) => {
const body = businessInput.parse(value);
try {
const saved = await request(api, businessAccount, { method: "POST", body });
await refreshDirectory();
navigate(`${route}/${saved.id}`);
} catch (error) {
if (isUnknownOutcome(error)) {
setUncertainCode(body.code);
await refreshDirectory();
}
throw error;
}
}}>
<ProfileFields />
</ActionForm>}
</Panel>;
}
function Details({ id, refreshDirectory }: { id: string; refreshDirectory: () => Promise<void> }) {
const { can } = usePlatform();
const path = `${api}/${id}`;
const query = usePrivateQuery(path, businessAccount);
const events = usePrivateQuery(`${path}/events`, z.array(businessEvent));
async function refresh() {
await Promise.all([query.refetch(), events.refetch(), refreshDirectory()]);
}
return <QueryView query={query}>{(account) => <>
<Panel title={account.legalName}>
<p>Business {account.code} · {account.status} · Profile version {account.profileVersion}</p>
{can("b2b.price.read") && <WorkspaceLink href={`/admin/b2b-price-lists/account/${account.id}`}>Business price lists</WorkspaceLink>}
<ReadProfile profile={account} />
</Panel>
<Review key={`${account.profileVersion}:${account.latestEvent?.sequence ?? 0}`} account={account} path={path} refresh={refresh} />
<Panel title="Verification history">
<QueryView query={events}>{(rows) => (
<Table head={["Sequence", "Event", "Date", "Staff ID", "Note"]} rowKeys={rows.map((row) => row.id)}
rows={rows.map((row) => [
row.sequence, row.profileSnapshot ? <details>
<summary>Submitted profile version {row.profileSnapshot.profileVersion}</summary>
<ReadProfile profile={row.profileSnapshot} />
</details> : row.kind, new Date(row.createdAt).toLocaleString(), row.actorId, row.note ?? "—",
])} />
)}</QueryView>
</Panel>
</>}</QueryView>;
}
function Review({ account, path, refresh }: { account: Account; path: string; refresh: () => Promise<void> }) {
const { can, principal, request } = usePlatform();
const sequence = account.latestEvent?.sequence ?? 0;
const submit = useIdempotentCommand(`${path}/submit`, submissionInput, businessEvent, `profile:${account.profileVersion}:${sequence}`);
const decision = useIdempotentCommand(`${path}/decision`, decisionInput, businessEvent, `submission:${sequence}`);
const editable = account.status === "DRAFT" || account.status === "REJECTED";
const ownSubmission = account.latestEvent?.actorId === principal?.userId.toLowerCase();
const latest = account.latestEvent;
const [busy, setBusy] = useState(false);
const updating = useRef(false);
async function whileCurrent(action: () => Promise<unknown>) {
if (updating.current) throw new Error("A profile or review update is already in progress.");
updating.current = true;
setBusy(true);
try {
const current = await request(path, businessAccount);
if (current.profileVersion !== account.profileVersion || current.latestEvent?.id !== latest?.id) {
throw new Error("The business profile or review has changed. Open the latest version.");
}
await action();
} finally {
try {
await refresh();
} finally {
updating.current = false;
setBusy(false);
}
}
}
return <>
{editable && can("b2b.manage") && <Panel title="Prepare for verification">
{submit.pending ? (
<ActionForm label="Retry verification submission" read={() => ({})} submit={() => whileCurrent(() => submit.run({}))}>
<Alert severity="warning">Retrying uses the original submission key for this profile version.</Alert>
</ActionForm>
) : <>
<ActionForm label="Save profile changes" reset={false} lockFields={busy}
read={(form) => businessProfile.parse(readProfile(form))}
submit={(body) => whileCurrent(() => request(path, businessAccount, { method: "PATCH", body }))}>
<ProfileFields account={account} />
</ActionForm>
<ConfirmAction label="Submit for verification" disabled={busy}
message={`Send saved profile version ${account.profileVersion} for review? Confirm that any edits have been saved.`}
onConfirm={() => whileCurrent(() => submit.run({}))} />
</>}
</Panel>}
{account.status === "PENDING" && latest?.kind === "SUBMITTED" && latest.profileSnapshot && <Panel title="Submitted profile for review">
<p>Profile version {latest.profileSnapshot.profileVersion} · Submitted {new Date(latest.createdAt).toLocaleString()}</p>
<ReadProfile profile={latest.profileSnapshot} />
{can("b2b.verify") && (ownSubmission ? <Alert severity="info">A different staff member must review this submission.</Alert> :
<ActionForm key={decision.pending ? "retry" : "decide"} label={decision.pending ? "Retry verification decision" : "Record verification decision"}
read={(form) => decision.pending ? {} : ({ decision: readText(form, "decision"), note: readText(form, "note") })}
submit={(value) => whileCurrent(() => decision.run(value))}>
{decision.pending ? <Alert severity="warning">Retrying uses the saved {decision.pending.decision.toLowerCase()} decision and note.</Alert> : <>
<p>Record the outcome of your manual review of this submitted profile.</p>
<Field name="decision" label="Review outcome" options={[
{ value: "", label: "Choose an outcome" }, { value: "APPROVED", label: "Approve" }, { value: "REJECTED", label: "Reject" },
]} />
<Field name="note" label="Review note" maxLength={500} helper="Describe the basis for the decision." />
</>}
</ActionForm>)}
</Panel>}
</>;
}
function Accounts({ id, create }: { id?: string; create?: boolean }) {
const { scope } = usePlatform();
const client = useQueryClient();
const refreshDirectory = () => client.invalidateQueries({
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
typeof queryKey[2] === "string" && queryKey[2].startsWith(`${api}?`),
});
const parsed = uuid.safeParse(id);
if (!create && !id) return <AccountList />;
return <>
<WorkspaceLink href={route}>All business accounts</WorkspaceLink>
{create ? <CreateAccount refreshDirectory={refreshDirectory} /> : parsed.success ?
<Details key={parsed.data} id={parsed.data} refreshDirectory={refreshDirectory} /> :
<Alert severity="warning">Invalid business account ID.</Alert>}
</>;
}
export default function BusinessAccountsPage(props: { id?: string; create?: boolean }) {
return <WorkspaceShell title="B2B Business Accounts" permission="b2b.read">
<Accounts {...props} />
</WorkspaceShell>;
}