165 lines
8.8 KiB
TypeScript
165 lines
8.8 KiB
TypeScript
import { useState } from "react";
|
||
import { useQueryClient } from "@tanstack/react-query";
|
||
import { useLocation } from "wouter";
|
||
import { z } from "zod";
|
||
import Alert from "@mui/material/Alert";
|
||
import { BusinessSnapshot } from "@/components/BusinessSnapshot";
|
||
import { WorkspaceShell } from "@/components/WorkspaceShell";
|
||
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||
import { ApiError } from "@/lib/api";
|
||
import { uuid } from "@/lib/commerce";
|
||
import { cancelPartnerOrderInput, createPartnerOrderInput, partnerOrder, partnerOrderEligible, partnerOrderSummary } from "@/lib/partner-orders";
|
||
import { usePlatform } from "@/lib/platform";
|
||
import { quote } from "@/lib/quotes";
|
||
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||
|
||
const api = "/b2b/partner-orders";
|
||
const route = "/admin/b2b-partner-orders";
|
||
|
||
function useRefreshOrders() {
|
||
const { scope } = usePlatform();
|
||
const client = useQueryClient();
|
||
return () => client.invalidateQueries({
|
||
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
|
||
typeof queryKey[2] === "string" && queryKey[2].startsWith(`${api}?`),
|
||
});
|
||
}
|
||
|
||
function PartnerOrderList({ 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(partnerOrderSummary));
|
||
return <Panel title="Partner order history">
|
||
{accountId && <p className="workspace-id">Business account {accountId}</p>}
|
||
{can("b2b.order.manage") && <p><WorkspaceLink href={`${route}/new`}>Record a partner order</WorkspaceLink></p>}
|
||
<QueryView query={query}>{(rows) => <>
|
||
<Table head={["Order", "Business", "Partner reference", "Status", "Merchandise total", "Recorded"]}
|
||
rowKeys={rows.map((row) => row.id)} rows={rows.map((row) => [
|
||
<WorkspaceLink href={`${route}/${row.id}`}>{row.number}</WorkspaceLink>, row.accountSnapshot.legalName,
|
||
row.partnerReference, row.status, `${row.currency} ${row.merchandiseTotal}`, new Date(row.createdAt).toLocaleString(),
|
||
])} />
|
||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||
</>}</QueryView>
|
||
</Panel>;
|
||
}
|
||
|
||
function CreatePartnerOrder({ quoteId }: { quoteId?: string }) {
|
||
const { can } = usePlatform();
|
||
const [, navigate] = useLocation();
|
||
const refresh = useRefreshOrders();
|
||
const command = useIdempotentCommand(api, createPartnerOrderInput, partnerOrder, "create");
|
||
const pending = command.pending;
|
||
if (!can("b2b.order.manage")) return <Alert severity="warning">Your account does not have permission to record partner orders.</Alert>;
|
||
|
||
async function submit(input: unknown) {
|
||
const saved = await command.run(input);
|
||
await refresh();
|
||
navigate(`${route}/${saved.id}`);
|
||
}
|
||
|
||
return <Panel title="Record a partner purchase order">
|
||
<p>Use an accepted, unexpired quotation for a verified business. The order copies the quotation’s merchandise terms.</p>
|
||
{pending ? <ActionForm label="Retry partner order" read={() => ({})} submit={submit}>
|
||
<Alert severity="warning">The server may have recorded this order. Retrying reuses the original reference {pending.partnerReference} and quotation {pending.quoteId}.</Alert>
|
||
</ActionForm> : quoteId && can("b2b.quote.read") ?
|
||
<OrderFromQuote quoteId={quoteId} submit={submit} /> :
|
||
<OrderForm quoteId={quoteId} submit={submit} />}
|
||
</Panel>;
|
||
}
|
||
|
||
function OrderFromQuote({ quoteId, submit }: { quoteId: string; submit: (input: unknown) => Promise<void> }) {
|
||
const query = usePrivateQuery(`/b2b/quotes/${quoteId}`, quote);
|
||
return <QueryView query={query}>{(source) => <>
|
||
<p><WorkspaceLink href={`/admin/b2b-quotes/${quoteId}`}>{source.number}</WorkspaceLink> · {source.accountSnapshot.legalName} · {source.currency} {source.merchandiseTotal}</p>
|
||
<p>Expires {new Date(source.expiresAt).toLocaleString()}</p>
|
||
{partnerOrderEligible(source) ? <OrderForm quoteId={quoteId} submit={async (input) => {
|
||
if (!partnerOrderEligible(source)) throw new Error("This quotation has expired.");
|
||
await submit(input);
|
||
}} /> : <Alert severity="warning">Only an accepted, unexpired quotation can be converted.</Alert>}
|
||
</>}</QueryView>;
|
||
}
|
||
|
||
function OrderForm({ quoteId, submit }: { quoteId?: string; submit: (input: unknown) => Promise<void> }) {
|
||
const { can } = usePlatform();
|
||
return <ActionForm label="Record partner order" reset={false} read={(form) => ({
|
||
quoteId: quoteId ?? readText(form, "quoteId").trim(),
|
||
partnerReference: readText(form, "partnerReference"),
|
||
note: readText(form, "note").trim() || null,
|
||
})} submit={submit}>
|
||
{quoteId ? <p className="workspace-id">Quotation ID {quoteId}</p> : <>
|
||
{can("b2b.quote.read") && <WorkspaceLink href="/admin/b2b-quotes">Find a quotation</WorkspaceLink>}
|
||
<Field name="quoteId" label="Quotation ID" maxLength={36} />
|
||
</>}
|
||
<Field name="partnerReference" label="Partner reference" maxLength={80} />
|
||
<Field name="note" label="Order note" required={false} maxLength={500} />
|
||
</ActionForm>;
|
||
}
|
||
|
||
function PartnerOrderDetail({ id }: { id: string }) {
|
||
const { can, scope } = usePlatform();
|
||
const client = useQueryClient();
|
||
const refreshLists = useRefreshOrders();
|
||
const path = `${api}/${id}`;
|
||
const query = usePrivateQuery(path, partnerOrder);
|
||
const cancel = useIdempotentCommand(`${path}/cancel`, cancelPartnerOrderInput, partnerOrder, id);
|
||
async function cancelOrder(input: unknown) {
|
||
try {
|
||
const saved = await cancel.run(input);
|
||
client.setQueryData(["private", scope, path], saved);
|
||
await refreshLists();
|
||
} catch (error) {
|
||
if (error instanceof ApiError && error.code === "B2B_ORDER_ALREADY_CANCELLED") {
|
||
await Promise.all([query.refetch(), refreshLists()]);
|
||
}
|
||
throw error;
|
||
}
|
||
}
|
||
|
||
return <QueryView query={query}>{(order) => <div className="workspace-id">
|
||
<Panel title={order.number}>
|
||
<p>{order.status} · Partner reference {order.partnerReference}</p>
|
||
<p>Recorded {new Date(order.createdAt).toLocaleString()} by {order.createdById}</p>
|
||
{order.note && <p>{order.note}</p>}
|
||
<WorkspaceLink href={`${route}/account/${order.accountId}`}>All orders for this business</WorkspaceLink>
|
||
{can("b2b.quote.read") && <p><WorkspaceLink href={`/admin/b2b-quotes/${order.quoteId}`}>Source quotation</WorkspaceLink></p>}
|
||
<BusinessSnapshot account={order.accountSnapshot} />
|
||
<Table head={["Variant", "Quantity", "Minimum", "Unit price", "Line total"]}
|
||
rowKeys={order.lines.map((line) => line.id)} rows={order.lines.map((line) => [
|
||
`${line.name} (${line.sku})`, line.quantity, line.minQuantity,
|
||
`${order.currency} ${line.unitPrice}`, `${order.currency} ${line.lineTotal}`,
|
||
])} />
|
||
<p>Merchandise total {order.currency} {order.merchandiseTotal}</p>
|
||
</Panel>
|
||
{order.cancellation ? <Panel title="Cancellation">
|
||
<p>{order.cancellation.reason}</p>
|
||
<p>Recorded {new Date(order.cancellation.createdAt).toLocaleString()} by {order.cancellation.actorId}</p>
|
||
</Panel> : can("b2b.order.manage") && order.status === "RECEIVED" && <Panel title="Cancel order">
|
||
<ActionForm key={cancel.pending ? "retry" : "cancel"} label={cancel.pending ? "Retry cancellation" : "Cancel partner order"}
|
||
read={(form) => cancel.pending ? {} : ({ reason: readText(form, "reason") })} submit={cancelOrder}>
|
||
{cancel.pending ? <Alert severity="warning">Retrying reuses the original cancellation reason and key.</Alert> : <>
|
||
<p>Cancellation is permanent. Any active payment receipts must be reversed first.</p>
|
||
<Field name="reason" label="Cancellation reason" maxLength={500} />
|
||
</>}
|
||
</ActionForm>
|
||
</Panel>}
|
||
</div>}</QueryView>;
|
||
}
|
||
|
||
export default function PartnerOrdersPage({ id, accountId, quoteId, create = false }: {
|
||
id?: string; accountId?: string; quoteId?: string; create?: boolean;
|
||
}) {
|
||
const order = uuid.safeParse(id);
|
||
const account = uuid.safeParse(accountId);
|
||
const source = uuid.safeParse(quoteId);
|
||
const invalid = (id && !order.success) || (accountId && !account.success) || (quoteId && !source.success);
|
||
return <WorkspaceShell title="B2B Partner Orders" permission="b2b.order.read">
|
||
{(id || accountId || create) && <WorkspaceLink href={route}>All partner orders</WorkspaceLink>}
|
||
{invalid ? <Alert severity="warning">Invalid order, account, or quotation ID.</Alert> :
|
||
create ? <CreatePartnerOrder key={source.data ?? "new"} quoteId={source.data} /> :
|
||
order.success ? <PartnerOrderDetail key={order.data} id={order.data} /> :
|
||
<PartnerOrderList key={account.data ?? "all"} accountId={account.data} />}
|
||
</WorkspaceShell>;
|
||
}
|