feat: issue B2B quotations and record responses #22

Merged
mihir merged 1 commits from feat/b2b-quotations into main 2026-11-15 14:17:49 +05:30
12 changed files with 398 additions and 26 deletions

View File

@ -52,4 +52,6 @@ Customer and administration screens are implemented, with recovery, pricing, sto
- B2B UAT should use distinct submitting and reviewing accounts. Verify self-review is blocked, rejection allows correction and resubmission, and a verified profile is read-only.
- B2B price lists support draft variant prices and minimum quantities, activation, archiving, and active-list merchandise previews.
- Price-list UAT should verify that unverified accounts and competing active lists cannot activate a draft, archived terms stay read-only, and price checks reject quantities below the variant minimum.
- Quotes, credit policies, samples, artwork, partner orders and payments, custom requests and reporting remain open.
- Staff can issue B2B quotations from account-specific price lists, review saved profile and pricing snapshots, and record acceptance, decline, or withdrawal before expiry.
- Quotation UAT should verify minimum quantities, expiry, immutable snapshots after archiving a price list, and exact retries for issuance and responses.
- Credit policies, samples, artwork, partner orders and payments, custom requests and reporting remain open.

View File

@ -31,6 +31,7 @@ const InventoryPage = lazy(() => import("@/pages/InventoryPage"));
const MaterialStockPage = lazy(() => import("@/pages/MaterialStockPage"));
const BusinessAccountsPage = lazy(() => import("@/pages/BusinessAccountsPage"));
const PriceListsPage = lazy(() => import("@/pages/PriceListsPage"));
const QuotesPage = lazy(() => import("@/pages/QuotesPage"));
const MaterialCostRatesPage = lazy(() => import("@/pages/MaterialCostRatesPage"));
const ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
const BomPage = lazy(() => import("@/pages/BomPage"));
@ -81,6 +82,17 @@ function Router() {
<Route path="/admin/b2b-price-lists/:id">
{(params) => <PriceListsPage id={params.id} />}
</Route>
<Route path="/admin/b2b-quotes">{() => <QuotesPage />}</Route>
<Route path="/admin/b2b-quotes/new">{() => <QuotesPage issue />}</Route>
<Route path="/admin/b2b-quotes/new/:accountId/:priceListId">
{(params) => <QuotesPage issue accountId={params.accountId} priceListId={params.priceListId} />}
</Route>
<Route path="/admin/b2b-quotes/account/:accountId">
{(params) => <QuotesPage accountId={params.accountId} />}
</Route>
<Route path="/admin/b2b-quotes/:id">
{(params) => <QuotesPage 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,30 @@
import { useRef, useState } from "react";
import Button from "@mui/material/Button";
import { Field } from "./WorkspaceTools";
export function readVariantQuantities(form: FormData) {
const quantities = form.getAll("quantity");
return form.getAll("variantId").map((id, index) => ({
variantId: String(id).trim(),
quantity: Number(quantities[index]),
}));
}
export function VariantQuantityFields({ options }: { options?: { value: string; label: string }[] }) {
const next = useRef(1);
const [rows, setRows] = useState([0]);
const limit = Math.min(100, options?.length ?? 100);
return <>
{rows.map((key, index) => <fieldset className="record-picker" key={key}>
<legend>Line {index + 1}</legend>
<Field name="variantId" label={`Variant for line ${index + 1}`} maxLength={36}
options={options && [{ value: "", label: "Choose a variant" }, ...options]} />
<Field name="quantity" label={`Quantity for line ${index + 1}`} type="number" />
<Button type="button" disabled={rows.length === 1} onClick={() => setRows(rows.filter((row) => row !== key))}>Remove line {index + 1}</Button>
</fieldset>)}
<Button type="button" disabled={rows.length >= limit} onClick={() => {
const key = next.current++;
setRows([...rows, key]);
}}>Add line</Button>
</>;
}

View File

@ -72,6 +72,7 @@ export function WorkspaceNavigation() {
{ label: "Audit", path: "/admin/audit", permission: "audit.read" },
{ label: "Business accounts", path: "/admin/business-accounts", permission: "b2b.read" },
{ label: "B2B price lists", path: "/admin/b2b-price-lists", permission: "b2b.price.read" },
{ label: "B2B quotations", path: "/admin/b2b-quotes", permission: "b2b.quote.read" },
];
return (
<nav className="workspace-links" aria-label="Workspace navigation">

View File

@ -22,7 +22,7 @@ export const businessInput = businessProfile.extend({
code: z.string().trim().toUpperCase().max(32).regex(/^[A-Z0-9][A-Z0-9_-]*$/, "Use letters, numbers, hyphens or underscores"),
});
export const profileVersion = z.number().int().positive();
const profileSnapshot = businessProfile.extend({ profileVersion });
export const profileSnapshot = businessProfile.extend({ profileVersion });
export const submissionInput = z.object({ idempotencyKey: uuid }).strict();
export const decisionInput = submissionInput.extend({

48
src/lib/quotes.ts Normal file
View File

@ -0,0 +1,48 @@
import { z } from "zod";
import { profileSnapshot } from "./business.ts";
import { currency, uuid } from "./commerce.ts";
import { priceCheck, priceCheckInput } from "./price-lists.ts";
const plainText = (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 });
export const responseKind = z.enum(["ACCEPTED", "DECLINED", "WITHDRAWN"]);
export const quoteResponseInput = z.object({
kind: responseKind,
note: plainText(500, 3),
idempotencyKey: uuid,
}).strict();
export const issueQuoteInput = z.object({
accountId: uuid,
priceListId: uuid,
expiresAt: timestamp,
customerReference: plainText(100).nullable().optional(),
lines: priceCheckInput.shape.lines,
idempotencyKey: uuid,
}).strict();
export function quoteExpiry(value: string, now = Date.now()) {
const expiry = Date.parse(timestamp.parse(value));
if (!(expiry > now && expiry - now <= 90 * 24 * 60 * 60 * 1000)) {
throw new Error("Choose an expiry in the next 90 days.");
}
return new Date(expiry).toISOString();
}
export const quoteSummary = z.object({
id: uuid,
accountId: uuid,
number: z.string(),
accountSnapshot: profileSnapshot,
currency,
merchandiseTotal: priceCheck.shape.merchandiseTotal,
expiresAt: timestamp,
status: z.enum(["ISSUED", "EXPIRED", ...responseKind.options]),
});
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() })),
response: z.object({ kind: responseKind, note: z.string(), createdAt: timestamp }).nullable(),
});

View File

@ -122,6 +122,7 @@ function Details({ id, refreshDirectory }: { id: string; refreshDirectory: () =>
<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>}
{can("b2b.quote.read") && <p><WorkspaceLink href={`/admin/b2b-quotes/account/${account.id}`}>Business quotations</WorkspaceLink></p>}
<ReadProfile profile={account} />
</Panel>
<Review key={`${account.profileVersion}:${account.latestEvent?.sequence ?? 0}`} account={account} path={path} refresh={refresh} />

View File

@ -1,42 +1,26 @@
import { useRef, useState } from "react";
import { useState } from "react";
import { z } from "zod";
import Button from "@mui/material/Button";
import { ActionForm, Field, Panel, Table, readNumber, readText } from "@/components/WorkspaceTools";
import { ActionForm, Panel, Table } from "@/components/WorkspaceTools";
import { VariantQuantityFields, readVariantQuantities } from "@/components/VariantQuantityFields";
import { priceCheck, priceCheckInput, priceListDetail } from "@/lib/price-lists";
import { money } from "@/lib/commerce";
import { usePlatform } from "@/lib/platform";
export function PriceListCheck({ list }: { list: z.infer<typeof priceListDetail> }) {
const { request } = usePlatform();
const next = useRef(1);
const [rows, setRows] = useState([0]);
const [checked, setChecked] = useState<z.infer<typeof priceCheck>>();
const options = [
{ value: "", label: "Choose a variant" },
...list.items.map((item) => ({
const options = list.items.map((item) => ({
value: item.variantId, label: `${item.variantId} · ${list.currency} ${money(item.unitPrice)} · minimum ${item.minQuantity}`,
})),
];
}));
return <Panel title="Check order quantities">
<p>The preview covers merchandise only. Enter quantities for up to 100 distinct variants.</p>
<ActionForm label="Check partner prices" reset={false} read={(form) => {
setChecked(undefined);
return priceCheckInput.parse({ lines: rows.map((key) => ({
variantId: readText(form, `variant-${key}`), quantity: readNumber(form, `quantity-${key}`),
})) });
return priceCheckInput.parse({ lines: readVariantQuantities(form) });
}} submit={async (body) => {
setChecked(await request(`/b2b/price-lists/${list.id}/price-check`, priceCheck, { method: "POST", body }));
}}>
{rows.map((key, index) => <fieldset className="record-picker" key={key}>
<legend>Line {index + 1}</legend>
<Field name={`variant-${key}`} label={`Variant for line ${index + 1}`} options={options} />
<Field name={`quantity-${key}`} label={`Quantity for line ${index + 1}`} type="number" />
<Button type="button" disabled={rows.length === 1} onClick={() => setRows(rows.filter((row) => row !== key))}>Remove line {index + 1}</Button>
</fieldset>)}
<Button type="button" disabled={rows.length >= Math.min(100, list.items.length)} onClick={() => {
const key = next.current++;
setRows([...rows, key]);
}}>Add line</Button>
<VariantQuantityFields options={options} />
</ActionForm>
{checked && <>
<h3>Last price check</h3>

View File

@ -168,7 +168,10 @@ function PriceListDetails({ id }: { id: string }) {
<Field name="minQuantity" label="Minimum order quantity" type="number" value={item?.minQuantity} />
</ActionForm>
</Panel>}
{list.status === "ACTIVE" && <PriceListCheck list={list} />}
{list.status === "ACTIVE" && <>
{can("b2b.quote.read") && can("b2b.quote.manage") && <WorkspaceLink href={`/admin/b2b-quotes/new/${list.accountId}/${list.id}`}>Issue a quotation from this list</WorkspaceLink>}
<PriceListCheck list={list} />
</>}
</>;
}}</QueryView>;
}

208
src/pages/QuotesPage.tsx Normal file
View File

@ -0,0 +1,208 @@
import { useEffect, useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useLocation } from "wouter";
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 { VariantQuantityFields, readVariantQuantities } from "@/components/VariantQuantityFields";
import { ApiError } from "@/lib/api";
import { money, uuid } from "@/lib/commerce";
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";
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() {
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 QuoteList({ accountId }: { accountId?: string }) {
const { can } = usePlatform();
const [offset, setOffset] = useState(0);
const query = usePrivateQuery(
`${api}?limit=25&offset=${offset}${accountId ? `&accountId=${accountId}` : ""}`,
z.array(quoteSummary),
);
return <Panel title="Quotation history">
{accountId && <p className="workspace-id">Business account {accountId}</p>}
{can("b2b.quote.manage") && <p><WorkspaceLink href={`${route}/new`}>Issue a quotation</WorkspaceLink></p>}
<QueryView query={query}>{(rows) => <>
<Table head={["Quotation", "Business", "Status", "Merchandise total", "Expires"]}
rowKeys={rows.map((row) => row.id)} rows={rows.map((row) => [
<WorkspaceLink href={`${route}/${row.id}`}>{row.number}</WorkspaceLink>,
row.accountSnapshot.legalName, visibleStatus(row),
`${row.currency} ${row.merchandiseTotal}`, new Date(row.expiresAt).toLocaleString(),
])} />
<Pager offset={offset} count={rows.length} onPage={setOffset} />
</>}</QueryView>
</Panel>;
}
function IssueQuote({ source }: { source?: Source }) {
const { can } = usePlatform();
const [, navigate] = useLocation();
const refresh = useRefreshQuoteLists();
const command = useIdempotentCommand(api, issueQuoteInput, quote, "issue");
if (!can("b2b.quote.manage")) return <Alert severity="warning">Your account does not have permission to issue quotations.</Alert>;
async function submit(input: unknown) {
const saved = await command.run(input);
await refresh();
navigate(`${route}/${saved.id}`);
}
return <Panel title="Issue a quotation">
<p>{terms} Issuing saves the account and price terms in the quotation.</p>
{command.pending ? <ActionForm label="Retry quotation issuance" read={() => ({})} submit={submit}>
<Alert severity="warning">The server may have issued this quotation. Retrying uses the original quantities, expiry, and price list.</Alert>
<p className="workspace-id">Price list {command.pending.priceListId}</p>
</ActionForm> : source && can("b2b.price.read") ? <IssueFromList source={source} submit={submit} /> :
<IssueForm source={source} submit={submit} />}
</Panel>;
}
function IssueFromList({ source, submit }: { source: Source; submit: (input: unknown) => Promise<void> }) {
const query = usePrivateQuery(`/b2b/price-lists/${source.priceListId}`, priceListDetail);
return <QueryView query={query}>{(list) => {
if (list.status !== "ACTIVE" || list.accountId !== source.accountId) {
return <Alert severity="warning">Choose an active price list for this business account.</Alert>;
}
return <>
<p>{list.name} · {list.currency}</p>
<IssueForm source={source} submit={submit} options={list.items.map((item) => ({
value: item.variantId, label: `${item.variantId} · ${list.currency} ${money(item.unitPrice)} · minimum ${item.minQuantity}`,
}))} />
</>;
}}</QueryView>;
}
function IssueForm({ source, options, submit }: {
source?: Source;
options?: { value: string; label: string }[];
submit: (input: unknown) => Promise<void>;
}) {
const { can } = usePlatform();
return <ActionForm label="Issue quotation" reset={false}
read={(form) => ({
accountId: source?.accountId ?? readText(form, "accountId").trim(),
priceListId: source?.priceListId ?? readText(form, "priceListId").trim(),
expiresAt: quoteExpiry(readText(form, "expiresAt").trim()),
customerReference: readText(form, "customerReference").trim() || null,
lines: readVariantQuantities(form),
})} submit={submit}>
{!source && <>
<p>Use an active price list for a verified business account. {can("b2b.price.read") &&
<WorkspaceLink href="/admin/b2b-price-lists">Browse account price lists</WorkspaceLink>}</p>
<Field name="accountId" label="Business account ID" maxLength={36} />
<Field name="priceListId" label="Active price list ID" maxLength={36} />
</>}
<Field name="expiresAt" label="Expiry with timezone" maxLength={35}
helper="Use YYYY-MM-DDTHH:mm:ss with a timezone offset, such as +05:30, or Z for UTC." />
<Field name="customerReference" label="Customer reference" required={false} maxLength={100} />
<VariantQuantityFields options={options} />
</ActionForm>;
}
function visibleStatus(record: z.infer<typeof quoteSummary>) {
return record.status === "ISSUED" && Date.parse(record.expiresAt) <= Date.now() ? "EXPIRED" : record.status;
}
function QuoteDetails({ id }: { id: string }) {
const { can, scope } = usePlatform();
const client = useQueryClient();
const refresh = useRefreshQuoteLists();
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 [, setExpired] = useState(false);
useEffect(() => {
if (!expiry) return;
let timer: number;
function tick(at: string) {
const remaining = Date.parse(at) - Date.now();
if (remaining <= 0) setExpired(true);
else timer = window.setTimeout(() => tick(at), Math.min(remaining, 2_147_483_647));
}
tick(expiry);
return () => window.clearTimeout(timer);
}, [expiry]);
async function respond(input: unknown) {
try {
const saved = await command.run(input);
client.setQueryData(["private", scope, path], saved);
await refresh();
} catch (error) {
if (error instanceof ApiError && ["B2B_QUOTE_EXPIRED", "B2B_QUOTE_ALREADY_RESOLVED"].includes(error.code ?? "")) {
await Promise.all([query.refetch(), refresh()]);
}
throw error;
}
}
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} />
<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,
`${record.currency} ${line.unitPrice}`, `${record.currency} ${line.lineTotal}`,
])} />
<p>Merchandise total {record.currency} {record.merchandiseTotal}</p>
<p>{terms}</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"}
read={(form) => command.pending ? {} : ({ kind: readText(form, "kind"), note: readText(form, "note") })}
submit={respond}>
{command.pending ? <Alert severity="warning">Retrying reuses the original response and note.</Alert> : <>
<p>Record the customer’s decision or a staff withdrawal. The saved response is final.</p>
<Field name="kind" label="Quotation response" options={[
{ value: "", label: "Choose a response" },
...responseKind.options.map((value) => ({ value, label: value.toLowerCase() })),
]} />
<Field name="note" label="Response note" maxLength={500} helper="Record the basis for the response." />
</>}
</ActionForm>
)}
</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;
}) {
const account = uuid.safeParse(accountId);
const list = uuid.safeParse(priceListId);
const quoteId = uuid.safeParse(id);
const source = account.success && list.success ? { accountId: account.data, priceListId: list.data } : undefined;
return <WorkspaceShell title="B2B Quotations" permission="b2b.quote.read">
{(id || issue || accountId) && <WorkspaceLink href={route}>All quotations</WorkspaceLink>}
{(id && !quoteId.success) || (accountId && !account.success) || (priceListId && !source) ?
<Alert severity="warning">Invalid quotation, account, or price list ID.</Alert> :
issue ? <IssueQuote key={source?.priceListId ?? "new"} source={source} /> :
quoteId.success ? <QuoteDetails key={quoteId.data} id={quoteId.data} /> :
<QuoteList key={account.data ?? "all"} accountId={account.data} />}
</WorkspaceShell>;
}

22
test/quotes.test.ts Normal file
View File

@ -0,0 +1,22 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { issueQuoteInput, quoteExpiry, quoteResponseInput } from "../src/lib/quotes.ts";
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
test("quotation expiry requires an explicit timezone and a future instant within 90 days", () => {
const now = Date.parse("2026-11-15T00:00:00.000Z");
assert.equal(quoteExpiry("2026-11-16T15:30:00+05:30", now), "2026-11-16T10:00:00.000Z");
assert.throws(() => quoteExpiry("2026-11-16T15:30:00", now));
assert.throws(() => quoteExpiry("2026-11-15T00:00:00Z", now), /next 90 days/);
assert.throws(() => quoteExpiry("2027-03-01T00:00:00Z", now), /next 90 days/);
});
test("quotation commands enforce unique variant lines and a trimmed response note", () => {
const payload = { accountId: id, priceListId: id, expiresAt: "2026-11-16T10:00:00Z", idempotencyKey: id,
lines: [{ variantId: id, quantity: 12 }] };
assert.deepEqual(issueQuoteInput.parse(payload), payload);
assert.equal(issueQuoteInput.safeParse({ ...payload, lines: [...payload.lines, { variantId: id.toUpperCase(), quantity: 13 }] }).success, false);
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);
});

View File

@ -23,6 +23,7 @@ import MaterialCostRatesPage from "../src/pages/MaterialCostRatesPage";
import MaterialStockPage from "../src/pages/MaterialStockPage";
import BusinessAccountsPage from "../src/pages/BusinessAccountsPage";
import PriceListsPage from "../src/pages/PriceListsPage";
import QuotesPage from "../src/pages/QuotesPage";
import { batchDetail } from "../src/lib/production";
import theme from "../src/theme";
import { Switch, Route } from "wouter";
@ -251,6 +252,66 @@ test("an independent business reviewer retries the same decision before approval
expect(attempts[1]).toEqual(attempts[0]);
});
test("quotation issuance and its response reuse their original requests after lost responses", async () => {
const expiresAt = new Date(Date.now() + 86_400_000).toISOString();
const priceList = { id, accountId: id, name: "Wholesale", currency: "INR", status: "ACTIVE",
items: [{ id, variantId: id, unitPrice: "12.5", minQuantity: 12 }] };
const quote = {
id, accountId: id, number: "BQ-42", accountSnapshot: businessProfileFixture, currency: "INR",
status: "ISSUED", merchandiseTotal: "150.00", expiresAt, createdAt: new Date().toISOString(),
priceListName: "Wholesale", customerReference: null, response: null,
lines: [{ id, variantId: id, sku: "WAX-01", name: "Candle", quantity: 12, minQuantity: 12, unitPrice: "12.50", lineTotal: "150.00" }],
};
const issueAttempts: unknown[] = [];
const responses: unknown[] = [];
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
if (url.endsWith("/auth/login")) return json(session);
if (url.endsWith("/auth/me")) return json({ ...me, permissions: ["b2b.quote.read", "b2b.quote.manage", "b2b.price.read"] });
if (url.endsWith(`/b2b/price-lists/${id}`)) return json(priceList);
if (url.endsWith("/b2b/quotes") && options?.method === "POST") {
issueAttempts.push(JSON.parse(String(options.body)));
if (issueAttempts.length === 1) throw new Error("Response lost");
return json(quote);
}
if (url.endsWith(`/b2b/quotes/${id}`)) return json(quote);
if (url.endsWith("/response") && options?.method === "POST") {
responses.push(JSON.parse(String(options.body)));
if (responses.length === 1) throw new Error("Response lost");
return json({ ...quote, status: "ACCEPTED",
response: { kind: "ACCEPTED", note: "Confirmed by email", createdAt: quote.createdAt } });
}
throw new Error(`Unexpected request ${url}`);
}));
history.replaceState(null, "", `/admin/b2b-quotes/new/${id}/${id}`);
harness(<Switch>
<Route path="/admin/b2b-quotes/new/:accountId/:priceListId">
{(params) => <QuotesPage issue accountId={params.accountId} priceListId={params.priceListId} />}
</Route>
<Route path="/admin/b2b-quotes/:id">{(params) => <QuotesPage id={params.id} />}</Route>
</Switch>);
const user = userEvent.setup();
await user.click(screen.getByText("Test login"));
await user.selectOptions(await screen.findByRole("combobox", { name: /Variant for line 1/ }), id);
await user.type(screen.getByRole("textbox", { name: /Expiry with timezone/ }), expiresAt);
await user.type(screen.getByRole("spinbutton", { name: /Quantity for line 1/ }), "12");
await user.click(screen.getByRole("button", { name: "Issue quotation" }));
await user.click(await screen.findByRole("button", { name: "Retry quotation issuance" }));
await screen.findByRole("heading", { name: "BQ-42" });
expect(issueAttempts).toHaveLength(2);
expect(issueAttempts[0]).toEqual({ accountId: id, priceListId: id, expiresAt, customerReference: null,
lines: [{ variantId: id, quantity: 12 }], idempotencyKey: expect.any(String) });
expect(issueAttempts[1]).toEqual(issueAttempts[0]);
expect(screen.getByText("Merchandise total INR 150.00")).toBeTruthy();
await user.selectOptions(screen.getByRole("combobox", { name: "Quotation response" }), "ACCEPTED");
await user.type(screen.getByRole("textbox", { name: /Response note/ }), "Confirmed by email");
await user.click(screen.getByRole("button", { name: "Record quotation response" }));
await user.click(await screen.findByRole("button", { name: "Retry quotation response" }));
await screen.findByText(/ACCEPTED on .*Confirmed by email/);
expect(responses).toHaveLength(2);
expect(responses[0]).toEqual({ kind: "ACCEPTED", note: "Confirmed by email", idempotencyKey: expect.any(String) });
expect(responses[1]).toEqual(responses[0]);
});
test("a price list freezes draft terms on activation and checks order minimums before archiving", async () => {
const variantId = "d66c798a-f764-4b88-8d13-ace328ff1011";
let status = "DRAFT";