Merge pull request 'feat: record and cancel B2B partner orders' (#26) from feat/b2b-partner-orders into main
continuous-integration/drone/push Build is failing Details

Reviewed-on: #26
This commit is contained in:
Mihir Motiyani 2026-11-17 00:25:39 +05:30
commit c86d4fd3bb
12 changed files with 517 additions and 16 deletions

View File

@ -60,4 +60,6 @@ Customer and administration screens are implemented, with recovery, pricing, sto
- Sample UAT should verify ineligible accounts and variants, self-review, dispatch only after approval, and replay with the original payload and key.
- B2B artwork supports private PDF, PNG, and JPEG version uploads, independent review, and permission-based downloads.
- Artwork UAT should use separate uploader, reviewer, and reader accounts. Exercise the 2 MiB upload limit through ingress, approval and rejection, download permissions, and preservation of prior approved versions.
- Partner orders and payments, custom requests and reporting remain open.
- Partner orders support conversion from accepted, unexpired quotations, immutable merchandise snapshots, and reasoned cancellation.
- Partner order UAT should verify expired quotes, duplicate references and quote conversion, exact retries, and cancellation blocked by an active payment receipt.
- Partner payments, custom requests and reporting remain open.

View File

@ -35,6 +35,7 @@ const QuotesPage = lazy(() => import("@/pages/QuotesPage"));
const CreditPoliciesPage = lazy(() => import("@/pages/CreditPoliciesPage"));
const SamplesPage = lazy(() => import("@/pages/SamplesPage"));
const ArtworkPage = lazy(() => import("@/pages/ArtworkPage"));
const PartnerOrdersPage = lazy(() => import("@/pages/PartnerOrdersPage"));
const MaterialCostRatesPage = lazy(() => import("@/pages/MaterialCostRatesPage"));
const ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
const BomPage = lazy(() => import("@/pages/BomPage"));
@ -129,6 +130,17 @@ function Router() {
<Route path="/admin/b2b-artwork/:id">
{(params) => <ArtworkPage id={params.id} />}
</Route>
<Route path="/admin/b2b-partner-orders">{() => <PartnerOrdersPage />}</Route>
<Route path="/admin/b2b-partner-orders/new">{() => <PartnerOrdersPage create />}</Route>
<Route path="/admin/b2b-partner-orders/new/:quoteId">
{(params) => <PartnerOrdersPage create quoteId={params.quoteId} />}
</Route>
<Route path="/admin/b2b-partner-orders/account/:accountId">
{(params) => <PartnerOrdersPage accountId={params.accountId} />}
</Route>
<Route path="/admin/b2b-partner-orders/:id">
{(params) => <PartnerOrdersPage id={params.id} />}
</Route>
<Route path="/admin/catalog">{() => <CatalogAdminPage />}</Route>
<Route path="/admin/catalog/:id">
{(params) => <CatalogAdminPage id={params.id} />}

View File

@ -0,0 +1,12 @@
import type { z } from "zod";
import type { profileSnapshot } from "@/lib/business";
export function BusinessSnapshot({ account }: { account: z.infer<typeof profileSnapshot> }) {
return <section className="workspace-id">
<h3>Business at quotation issuance</h3>
<p>{account.legalName}{account.tradingName && ` · ${account.tradingName}`} · Profile version {account.profileVersion}</p>
<p>Registration {account.registrationNumber}{account.taxIdentifier && ` · Tax ID ${account.taxIdentifier}`}</p>
<p>{account.contactEmail}{account.contactPhone && ` · ${account.contactPhone}`}</p>
<p>{[account.billingLine1, account.billingCity, account.billingRegion, account.billingPostalCode, account.countryCode].join(", ")}</p>
</section>;
}

View File

@ -76,6 +76,7 @@ export function WorkspaceNavigation() {
{ label: "B2B credit policies", path: "/admin/b2b-credit-policies", permission: "b2b.credit.read" },
{ label: "B2B samples", path: "/admin/b2b-samples", permission: "b2b.sample.read" },
{ label: "B2B artwork", path: "/admin/b2b-artwork", permission: "b2b.artwork.read" },
{ label: "B2B partner orders", path: "/admin/b2b-partner-orders", permission: "b2b.order.read" },
];
return (
<nav className="workspace-links" aria-label="Workspace navigation">

53
src/lib/partner-orders.ts Normal file
View File

@ -0,0 +1,53 @@
import { z } from "zod";
import { profileSnapshot } from "./business.ts";
import { currency, uuid } from "./commerce.ts";
import { quote, quoteSummary } from "./quotes.ts";
const text = (max: number, min = 1) =>
z.string().trim().min(min).max(max).regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text");
const timestamp = z.string().datetime({ offset: true });
const partnerReference = text(80);
const orderNote = text(500, 3);
export const createPartnerOrderInput = z.object({
quoteId: uuid,
partnerReference,
note: orderNote.nullable().optional(),
idempotencyKey: uuid,
}).strict();
export const cancelPartnerOrderInput = z.object({
reason: orderNote,
idempotencyKey: uuid,
}).strict();
export const partnerOrderSummary = z.object({
id: uuid,
accountId: uuid,
quoteId: uuid,
number: z.string(),
partnerReference,
accountSnapshot: profileSnapshot.pick({ legalName: true }).strip(),
currency,
merchandiseTotal: quoteSummary.shape.merchandiseTotal,
status: z.enum(["RECEIVED", "CANCELLED"]),
createdAt: timestamp,
});
export const partnerOrder = partnerOrderSummary.extend({
accountSnapshot: profileSnapshot,
createdById: uuid,
note: orderNote.nullable(),
lines: z.array(quote.shape.lines.element),
cancellation: z.object({
actorId: uuid,
reason: orderNote,
createdAt: timestamp,
}).nullable(),
});
export function partnerOrderEligible(
quote: Pick<z.infer<typeof quoteSummary>, "status" | "expiresAt">,
now = Date.now(),
) {
return quote.status === "ACCEPTED" && Date.parse(quote.expiresAt) > now;
}

View File

@ -43,6 +43,6 @@ export const quote = quoteSummary.extend({
priceListName: z.string(),
customerReference: z.string().nullable(),
createdAt: timestamp,
lines: z.array(priceCheck.shape.lines.element.extend({ id: uuid, sku: z.string(), name: z.string() })),
lines: z.array(priceCheck.shape.lines.element.extend({ id: uuid, sku: z.string(), name: z.string() }).strip()),
response: z.object({ kind: responseKind, note: z.string(), createdAt: timestamp }).nullable(),
});

View File

@ -130,6 +130,7 @@ function Details({ id, refreshDirectory }: { id: string; refreshDirectory: () =>
{account.status === "VERIFIED" && can("b2b.sample.read") && can("b2b.sample.request") &&
<p><WorkspaceLink href={`/admin/b2b-samples/new/${account.id}`}>Request samples for this business</WorkspaceLink></p>}
{can("b2b.artwork.read") && <p><WorkspaceLink href={`/admin/b2b-artwork/account/${account.id}`}>Business artwork projects</WorkspaceLink></p>}
{can("b2b.order.read") && <p><WorkspaceLink href={`/admin/b2b-partner-orders/account/${account.id}`}>Business partner orders</WorkspaceLink></p>}
{account.status === "VERIFIED" && can("b2b.artwork.read") && can("b2b.artwork.manage") &&
<p><WorkspaceLink href={`/admin/b2b-artwork/new/${account.id}`}>Create artwork project for this business</WorkspaceLink></p>}
<ReadProfile profile={account} />

View File

@ -0,0 +1,164 @@
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>;
}

View File

@ -4,6 +4,7 @@ import { useLocation } from "wouter";
import { z } from "zod";
import Alert from "@mui/material/Alert";
import { WorkspaceShell } from "@/components/WorkspaceShell";
import { BusinessSnapshot } from "@/components/BusinessSnapshot";
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readText, usePrivateQuery } from "@/components/WorkspaceTools";
import { VariantQuantityFields, readVariantQuantities } from "@/components/VariantQuantityFields";
import { ApiError } from "@/lib/api";
@ -12,11 +13,11 @@ import { usePlatform } from "@/lib/platform";
import { priceListDetail } from "@/lib/price-lists";
import { issueQuoteInput, quote, quoteExpiry, quoteResponseInput, quoteSummary, responseKind } from "@/lib/quotes";
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
import { partnerOrderEligible } from "@/lib/partner-orders";
const api = "/b2b/quotes";
const route = "/admin/b2b-quotes";
const terms = "Merchandise only. Tax, shipping, stock reservation, credit, and payment are outside this quotation.";
type Quote = z.infer<typeof quote>;
type Source = { accountId: string; priceListId: string };
function useRefreshQuoteLists() {
@ -124,7 +125,7 @@ function QuoteDetails({ id }: { id: string }) {
const path = `${api}/${id}`;
const query = usePrivateQuery(path, quote);
const command = useIdempotentCommand(`${path}/response`, quoteResponseInput, quote, id);
const expiry = query.data?.status === "ISSUED" ? query.data.expiresAt : undefined;
const expiry = query.data && (query.data.status === "ISSUED" || query.data.status === "ACCEPTED") ? query.data.expiresAt : undefined;
const [, setExpired] = useState(false);
useEffect(() => {
if (!expiry) return;
@ -154,7 +155,7 @@ function QuoteDetails({ id }: { id: string }) {
return <QueryView query={query}>{(record) => <Panel title={record.number}>
<p>{visibleStatus(record)} · Issued {new Date(record.createdAt).toLocaleString()} · Expires {new Date(record.expiresAt).toLocaleString()}</p>
<p>Price list {record.priceListName}{record.customerReference && ` · Customer reference ${record.customerReference}`}</p>
<AccountSnapshot account={record.accountSnapshot} />
<BusinessSnapshot account={record.accountSnapshot} />
<Table head={["Variant", "Quantity", "Minimum", "Unit price", "Line total"]} rowKeys={record.lines.map((line) => line.id)}
rows={record.lines.map((line) => [
`${line.name} (${line.sku})`, line.quantity, line.minQuantity,
@ -162,6 +163,8 @@ function QuoteDetails({ id }: { id: string }) {
])} />
<p>Merchandise total {record.currency} {record.merchandiseTotal}</p>
<p>{terms}</p>
{partnerOrderEligible(record) && can("b2b.order.read") && can("b2b.order.manage") &&
<p><WorkspaceLink href={`/admin/b2b-partner-orders/new/${record.id}`}>Record partner order from this quotation</WorkspaceLink></p>}
{record.response ? <Alert severity="info">{record.response.kind} on {new Date(record.response.createdAt).toLocaleString()} · {record.response.note}</Alert> :
can("b2b.quote.manage") && (command.pending || visibleStatus(record) === "ISSUED") && (
<ActionForm key={command.pending ? "retry" : "response"} label={command.pending ? "Retry quotation response" : "Record quotation response"}
@ -180,16 +183,6 @@ function QuoteDetails({ id }: { id: string }) {
</Panel>}</QueryView>;
}
function AccountSnapshot({ account }: { account: Quote["accountSnapshot"] }) {
return <section>
<h3>Business at issuance</h3>
<p>{account.legalName}{account.tradingName && ` · ${account.tradingName}`} · Profile version {account.profileVersion}</p>
<p>Registration {account.registrationNumber}{account.taxIdentifier && ` · Tax ID ${account.taxIdentifier}`}</p>
<p className="workspace-id">{account.contactEmail}{account.contactPhone && ` · ${account.contactPhone}`}</p>
<p>{[account.billingLine1, account.billingCity, account.billingRegion, account.billingPostalCode, account.countryCode].join(", ")}</p>
</section>;
}
export default function QuotesPage({ id, accountId, priceListId, issue = false }: {
id?: string; accountId?: string; priceListId?: string; issue?: boolean;
}) {

View File

@ -0,0 +1,75 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import {
cancelPartnerOrderInput,
createPartnerOrderInput,
partnerOrder,
partnerOrderEligible,
partnerOrderSummary,
} from "../src/lib/partner-orders.ts";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
const createdAt = "2026-11-17T00:00:00.000Z";
const accountSnapshot = {
legalName: "Northlight Studio",
tradingName: null,
registrationNumber: "REG-100",
taxIdentifier: null,
countryCode: "IN",
contactEmail: "buyer@example.com",
contactPhone: null,
billingLine1: "30 Market Road",
billingCity: "Mumbai",
billingRegion: "Maharashtra",
billingPostalCode: "400001",
profileVersion: 2,
};
test("partner order inputs retain reference case and require the exact payload", () => {
const input = { quoteId: id, partnerReference: " Customer-PO/42 ", note: null, idempotencyKey: id };
assert.deepEqual(createPartnerOrderInput.parse(input), { ...input, partnerReference: "Customer-PO/42" });
assert.equal(createPartnerOrderInput.safeParse({ ...input, note: "x" }).success, false);
assert.equal(createPartnerOrderInput.safeParse({ ...input, partnerReference: "x".repeat(81) }).success, false);
assert.equal(createPartnerOrderInput.safeParse({ ...input, partnerReference: "<reference>" }).success, false);
assert.equal(createPartnerOrderInput.safeParse({ ...input, accountId: id }).success, false);
assert.deepEqual(cancelPartnerOrderInput.parse({ reason: " Partner withdrew ", idempotencyKey: id }), {
reason: "Partner withdrew", idempotencyKey: id,
});
assert.equal(cancelPartnerOrderInput.safeParse({ reason: " ", idempotencyKey: id }).success, false);
});
test("an accepted quotation is eligible only before its expiry instant", () => {
const expiresAt = "2026-11-17T10:00:00+05:30";
const expiry = Date.parse(expiresAt);
assert.equal(partnerOrderEligible({ status: "ACCEPTED", expiresAt }, expiry - 1), true);
assert.equal(partnerOrderEligible({ status: "ACCEPTED", expiresAt }, expiry), false);
assert.equal(partnerOrderEligible({ status: "ISSUED", expiresAt }, expiry - 1), false);
assert.equal(partnerOrderEligible({ status: "ACCEPTED", expiresAt: "invalid" }, expiry - 1), false);
});
test("order parsers preserve immutable snapshots and exact amounts while dropping backend metadata", () => {
const order = {
id, accountId: id, quoteId: id, createdById: id, number: "BO-123", status: "CANCELLED",
partnerReference: "Customer-PO/42", note: null, currency: "INR", createdAt,
merchandiseTotal: "9999999999999999.99",
accountSnapshot,
organizationId: id,
requestHash: "opaque",
lines: [{
id, orderId: id, organizationId: id, variantId: id, sku: "AMBER", name: "Amber candle",
quantity: 12, minQuantity: 6, unitPrice: "123.45", lineTotal: "1481.40",
}],
cancellation: { actorId: id, reason: "Partner withdrew", createdAt, orderId: id, requestHash: "opaque" },
};
const detail = partnerOrder.parse(order);
assert.equal(detail.merchandiseTotal, order.merchandiseTotal);
assert.equal(detail.lines[0].lineTotal, "1481.40");
assert.equal(detail.accountSnapshot.profileVersion, 2);
assert.deepEqual(detail.cancellation, { actorId: id, reason: "Partner withdrew", createdAt });
assert.equal("requestHash" in detail, false);
assert.equal("organizationId" in detail.lines[0], false);
const summary = partnerOrderSummary.parse(order);
assert.deepEqual(summary.accountSnapshot, { legalName: accountSnapshot.legalName });
assert.equal("lines" in summary, false);
assert.equal(partnerOrder.safeParse({ ...order, merchandiseTotal: 123.45 }).success, false);
});

View File

@ -0,0 +1,181 @@
import { type ReactNode } from "react";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ThemeProvider } from "@mui/material/styles";
import { afterEach, expect, test, vi } from "vitest";
import { Route, Switch } from "wouter";
import { PlatformProvider, usePlatform } from "../src/lib/platform";
import PartnerOrdersPage from "../src/pages/PartnerOrdersPage";
import theme from "../src/theme";
const accountId = "d66c798a-f764-4b88-8d13-ace328ff1010";
const userId = "d66c798a-f764-4b88-8d13-ace328ff1011";
const quoteId = "d66c798a-f764-4b88-8d13-ace328ff1012";
const orderId = "d66c798a-f764-4b88-8d13-ace328ff1013";
const variantId = "d66c798a-f764-4b88-8d13-ace328ff1014";
const lineId = "d66c798a-f764-4b88-8d13-ace328ff1015";
const createdAt = "2026-11-17T08:00:00.000Z";
const route = "/admin/b2b-partner-orders";
const api = "/b2b/partner-orders";
const detail = `${api}/${orderId}`;
const profile = {
legalName: "Vanilla Gift Company", tradingName: null, registrationNumber: "REG-019", taxIdentifier: null,
countryCode: "IN", contactEmail: "partner@example.com", contactPhone: null, billingLine1: "42 Sample Road",
billingCity: "Mumbai", billingRegion: "Maharashtra", billingPostalCode: "400001", profileVersion: 1,
};
const line = {
id: lineId, variantId, sku: "VANILLA-TIN", name: "Vanilla tin",
quantity: 10, minQuantity: 8, unitPrice: "100.00", lineTotal: "1000.00",
};
const quote = {
id: quoteId, accountId, number: "BQ-ORDER-01", accountSnapshot: profile,
currency: "INR", merchandiseTotal: "1000.00", expiresAt: new Date(Date.now() + 86_400_000).toISOString(),
status: "ACCEPTED", priceListName: "Wholesale INR", customerReference: null, createdAt,
lines: [line], response: { kind: "ACCEPTED", note: "Customer accepted by email", createdAt },
};
const order = {
id: orderId, accountId, quoteId, createdById: userId, number: "BPO-ORDER-01",
partnerReference: "CUSTOMER-PO-123", note: "Requested by the purchasing team",
accountSnapshot: profile, currency: "INR", merchandiseTotal: "1000.00", createdAt,
status: "RECEIVED", lines: [line], cancellation: null,
};
const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status });
function staffSession(url: string, permissions: string[]) {
if (url.endsWith("/auth/login")) return json({
accessToken: "test-opaque", tokenType: "Bearer",
expiresAt: new Date(Date.now() + 3_600_000).toISOString(),
});
if (url.endsWith("/auth/me")) return json({
userId, organizationId: accountId, sessionId: accountId, permissions,
});
}
function Login() {
const { signIn } = usePlatform();
return <button onClick={() => signIn("staff@example.com", "test password")}>Test login</button>;
}
function showOrders(children: ReactNode) {
localStorage.setItem("mani.organization", accountId);
const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(<ThemeProvider theme={theme}>
<QueryClientProvider client={client}>
<PlatformProvider><Login />{children}</PlatformProvider>
</QueryClientProvider>
</ThemeProvider>);
}
afterEach(() => {
vi.unstubAllGlobals();
history.replaceState(null, "", "/");
});
test("conversion retries the same accepted quote, reference, note, and key after a lost response", async () => {
const attempts: unknown[] = [];
const fetch = vi.fn(async (url: string, options?: RequestInit) => {
const auth = staffSession(url, ["b2b.order.read", "b2b.order.manage", "b2b.quote.read"]);
if (auth) return auth;
if (url.endsWith(`/b2b/quotes/${quoteId}`)) return json(quote);
if (url.endsWith(api) && options?.method === "POST") {
attempts.push(JSON.parse(String(options.body)));
if (attempts.length === 1) throw new Error("Response lost");
return json(order);
}
if (url.endsWith(detail)) return json(order);
throw new Error(`Unexpected request ${url}`);
});
vi.stubGlobal("fetch", fetch);
history.replaceState(null, "", `${route}/new/${quoteId}`);
showOrders(<Switch>
<Route path={`${route}/new/:quoteId`}>{(params) => <PartnerOrdersPage create quoteId={params.quoteId} />}</Route>
<Route path={`${route}/:id`}>{(params) => <PartnerOrdersPage id={params.id} />}</Route>
</Switch>);
expect(fetch).not.toHaveBeenCalled();
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await user.type(await screen.findByRole("textbox", { name: /Partner reference/ }), order.partnerReference);
await user.type(screen.getByRole("textbox", { name: /Order note/ }), order.note);
await user.click(screen.getByRole("button", { name: "Record partner order" }));
await user.click(await screen.findByRole("button", { name: "Retry partner order" }));
await screen.findByRole("button", { name: "Cancel partner order" });
expect(location.pathname).toBe(`${route}/${orderId}`);
expect(attempts[0]).toEqual({ quoteId, partnerReference: order.partnerReference, note: order.note, idempotencyKey: expect.any(String) });
expect(attempts).toEqual([attempts[0], attempts[0]]);
});
test("a received partner order can be cancelled and the same cancellation key can be replayed", async () => {
const reason = "Partner withdrew purchase order";
let current: object = order;
const attempts: unknown[] = [];
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
const auth = staffSession(url, ["b2b.order.read", "b2b.order.manage"]);
if (auth) return auth;
if (url.endsWith(detail)) return json(current);
if (url.endsWith(`${detail}/cancel`) && options?.method === "POST") {
attempts.push(JSON.parse(String(options.body)));
current = { ...order, status: "CANCELLED", cancellation: { orderId, reason, actorId: userId, createdAt } };
if (attempts.length === 1) throw new Error("Response lost");
return json(current);
}
throw new Error(`Unexpected request ${url}`);
}));
showOrders(<PartnerOrdersPage id={orderId} />);
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await user.type(await screen.findByRole("textbox", { name: /Cancellation reason/ }), reason);
await user.click(screen.getByRole("button", { name: "Cancel partner order" }));
await user.click(await screen.findByRole("button", { name: "Retry cancellation" }));
await screen.findByText(new RegExp(reason));
expect(screen.queryByRole("button", { name: "Cancel partner order" })).toBeNull();
expect(attempts[0]).toEqual({ reason, idempotencyKey: expect.any(String) });
expect(attempts).toEqual([attempts[0], attempts[0]]);
});
test("a read-only staff member can see the saved order without cancellation controls", async () => {
const fetch = vi.fn(async (url: string) => {
const auth = staffSession(url, ["b2b.order.read"]);
if (auth) return auth;
if (url.endsWith(detail)) return json(order);
throw new Error(`Unexpected request ${url}`);
});
vi.stubGlobal("fetch", fetch);
showOrders(<PartnerOrdersPage id={orderId} />);
expect(fetch).not.toHaveBeenCalled();
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await screen.findByText(/Vanilla tin/);
expect(screen.queryByRole("textbox", { name: /Cancellation reason/ })).toBeNull();
expect(screen.queryByRole("button", { name: "Cancel partner order" })).toBeNull();
});
test("a cancellation blocked by an active receipt keeps the saved order and explains the conflict", async () => {
const fetch = vi.fn(async (url: string, options?: RequestInit) => {
const auth = staffSession(url, ["b2b.order.read", "b2b.order.manage"]);
if (auth) return auth;
if (url.endsWith(detail)) return json(order);
if (url.endsWith(`${detail}/cancel`) && options?.method === "POST") return json({
message: "Reverse active payments before cancelling the order", code: "B2B_PAYMENT_CANCEL_BLOCKED",
}, 409);
throw new Error(`Unexpected request ${url}`);
});
vi.stubGlobal("fetch", fetch);
showOrders(<PartnerOrdersPage id={orderId} />);
const user = userEvent.setup();
await user.click(screen.getByRole("button", { name: "Test login" }));
await user.type(await screen.findByRole("textbox", { name: /Cancellation reason/ }), "Partner changed the order");
await user.click(screen.getByRole("button", { name: "Cancel partner order" }));
await screen.findByText("Reverse active payments before cancelling the order");
expect(screen.getByRole("button", { name: "Cancel partner order" })).toBeTruthy();
expect(screen.queryByRole("button", { name: "Retry cancellation" })).toBeNull();
});

View File

@ -1,6 +1,6 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { issueQuoteInput, quoteExpiry, quoteResponseInput } from "../src/lib/quotes.ts";
import { issueQuoteInput, quote, quoteExpiry, quoteResponseInput } from "../src/lib/quotes.ts";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
@ -20,3 +20,10 @@ test("quotation commands enforce unique variant lines and a trimmed response not
assert.equal(quoteResponseInput.parse({ kind: "ACCEPTED", note: " Confirmed by email ", idempotencyKey: id }).note, "Confirmed by email");
assert.equal(quoteResponseInput.safeParse({ kind: "DECLINED", note: " ", idempotencyKey: id }).success, false);
});
test("saved quotation lines retain price terms and strip database metadata", () => {
const line = { id, variantId: id, sku: "TIN-01", name: "Tin candle", quantity: 12, minQuantity: 6,
unitPrice: "10.50", lineTotal: "126.00" };
assert.deepEqual(quote.shape.lines.element.parse({ ...line, organizationId: id, quoteId: id }), line);
assert.equal(issueQuoteInput.shape.lines.element.safeParse({ variantId: id, quantity: 12, quoteId: id }).success, false);
});