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; type Profile = z.infer; 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 {can("b2b.manage") &&

Create business account

} ({ search: readText(form, "search") })} submit={async (value) => { setSearch(z.object({ search: businessSearch }).parse(value).search); setOffset(0); }}> {(rows) => <> row.id)} rows={rows.map((row) => [ {row.legalName}, row.code, row.countryCode, row.status, ])} /> } ; } function ProfileFields({ account }: { account?: Account }) { return <> {!account && } {fields.map((field) => ( ))} ; } 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
{fields.map((field) =>
{field.label}
{profile[field.name] ?? "—"}
)}
; } function CreateAccount({ refreshDirectory }: { refreshDirectory: () => Promise }) { const { can, request } = usePlatform(); const [, navigate] = useLocation(); const [uncertainCode, setUncertainCode] = useState(""); if (!can("b2b.manage")) return Your account does not have permission to create business profiles.; return {uncertainCode ? The server may have saved {uncertainCode}. Search the business directory for that code before creating it again. : 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; } }}> } ; } function Details({ id, refreshDirectory }: { id: string; refreshDirectory: () => Promise }) { 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 {(account) => <>

Business {account.code} · {account.status} · Profile version {account.profileVersion}

{can("b2b.price.read") && Business price lists}
{(rows) => (
row.id)} rows={rows.map((row) => [ row.sequence, row.profileSnapshot ?
Submitted profile version {row.profileSnapshot.profileVersion}
: row.kind, new Date(row.createdAt).toLocaleString(), row.actorId, row.note ?? "—", ])} /> )} }; } function Review({ account, path, refresh }: { account: Account; path: string; refresh: () => Promise }) { 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) { 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") && {submit.pending ? ( ({})} submit={() => whileCurrent(() => submit.run({}))}> Retrying uses the original submission key for this profile version. ) : <> businessProfile.parse(readProfile(form))} submit={(body) => whileCurrent(() => request(path, businessAccount, { method: "PATCH", body }))}> whileCurrent(() => submit.run({}))} /> } } {account.status === "PENDING" && latest?.kind === "SUBMITTED" && latest.profileSnapshot &&

Profile version {latest.profileSnapshot.profileVersion} · Submitted {new Date(latest.createdAt).toLocaleString()}

{can("b2b.verify") && (ownSubmission ? A different staff member must review this submission. : decision.pending ? {} : ({ decision: readText(form, "decision"), note: readText(form, "note") })} submit={(value) => whileCurrent(() => decision.run(value))}> {decision.pending ? Retrying uses the saved {decision.pending.decision.toLowerCase()} decision and note. : <>

Record the outcome of your manual review of this submitted profile.

}
)}
} ; } 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 ; return <> All business accounts {create ? : parsed.success ?
: Invalid business account ID.} ; } export default function BusinessAccountsPage(props: { id?: string; create?: boolean }) { return ; }