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 {accountId &&

Business account {accountId}

} {can("b2b.order.manage") &&

Record a partner order

} {(rows) => <> row.id)} rows={rows.map((row) => [ {row.number}, row.accountSnapshot.legalName, row.partnerReference, row.status, `${row.currency} ${row.merchandiseTotal}`, new Date(row.createdAt).toLocaleString(), ])} /> } ; } 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 Your account does not have permission to record partner orders.; async function submit(input: unknown) { const saved = await command.run(input); await refresh(); navigate(`${route}/${saved.id}`); } return

Use an accepted, unexpired quotation for a verified business. The order copies the quotation’s merchandise terms.

{pending ? ({})} submit={submit}> The server may have recorded this order. Retrying reuses the original reference {pending.partnerReference} and quotation {pending.quoteId}. : quoteId && can("b2b.quote.read") ? : }
; } function OrderFromQuote({ quoteId, submit }: { quoteId: string; submit: (input: unknown) => Promise }) { const query = usePrivateQuery(`/b2b/quotes/${quoteId}`, quote); return {(source) => <>

{source.number} · {source.accountSnapshot.legalName} · {source.currency} {source.merchandiseTotal}

Expires {new Date(source.expiresAt).toLocaleString()}

{partnerOrderEligible(source) ? { if (!partnerOrderEligible(source)) throw new Error("This quotation has expired."); await submit(input); }} /> : Only an accepted, unexpired quotation can be converted.} }
; } function OrderForm({ quoteId, submit }: { quoteId?: string; submit: (input: unknown) => Promise }) { const { can } = usePlatform(); return ({ quoteId: quoteId ?? readText(form, "quoteId").trim(), partnerReference: readText(form, "partnerReference"), note: readText(form, "note").trim() || null, })} submit={submit}> {quoteId ?

Quotation ID {quoteId}

: <> {can("b2b.quote.read") && Find a quotation} }
; } 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 {(order) =>

{order.status} · Partner reference {order.partnerReference}

Recorded {new Date(order.createdAt).toLocaleString()} by {order.createdById}

{order.note &&

{order.note}

} All orders for this business {can("b2b.quote.read") &&

Source quotation

}
line.id)} rows={order.lines.map((line) => [ `${line.name} (${line.sku})`, line.quantity, line.minQuantity, `${order.currency} ${line.unitPrice}`, `${order.currency} ${line.lineTotal}`, ])} />

Merchandise total {order.currency} {order.merchandiseTotal}

{order.cancellation ?

{order.cancellation.reason}

Recorded {new Date(order.cancellation.createdAt).toLocaleString()} by {order.cancellation.actorId}

: can("b2b.order.manage") && order.status === "RECEIVED" && cancel.pending ? {} : ({ reason: readText(form, "reason") })} submit={cancelOrder}> {cancel.pending ? Retrying reuses the original cancellation reason and key. : <>

Cancellation is permanent. Any active payment receipts must be reversed first.

}
} }; } 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 {(id || accountId || create) && All partner orders} {invalid ? Invalid order, account, or quotation ID. : create ? : order.success ? : } ; }