feat: manage B2B credit policy proposals and reviews
continuous-integration/drone/push Build is passing
Details
continuous-integration/drone/push Build is passing
Details
This commit is contained in:
parent
f2f9a41618
commit
089f5682b0
|
|
@ -54,4 +54,6 @@ Customer and administration screens are implemented, with recovery, pricing, sto
|
|||
- 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.
|
||||
- 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.
|
||||
- B2B credit policies support immutable proposals, independent approval or rejection, and suspension with decision history.
|
||||
- Credit policy UAT should verify that unverified accounts and self-review are rejected, a second active policy in the same currency cannot be approved, and suspension permits a replacement.
|
||||
- Samples, artwork, partner orders and payments, custom requests and reporting remain open.
|
||||
|
|
|
|||
12
src/App.tsx
12
src/App.tsx
|
|
@ -32,6 +32,7 @@ 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 CreditPoliciesPage = lazy(() => import("@/pages/CreditPoliciesPage"));
|
||||
const MaterialCostRatesPage = lazy(() => import("@/pages/MaterialCostRatesPage"));
|
||||
const ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
|
||||
const BomPage = lazy(() => import("@/pages/BomPage"));
|
||||
|
|
@ -93,6 +94,17 @@ function Router() {
|
|||
<Route path="/admin/b2b-quotes/:id">
|
||||
{(params) => <QuotesPage id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/b2b-credit-policies">{() => <CreditPoliciesPage />}</Route>
|
||||
<Route path="/admin/b2b-credit-policies/new">{() => <CreditPoliciesPage propose />}</Route>
|
||||
<Route path="/admin/b2b-credit-policies/new/:accountId">
|
||||
{(params) => <CreditPoliciesPage propose accountId={params.accountId} />}
|
||||
</Route>
|
||||
<Route path="/admin/b2b-credit-policies/account/:accountId">
|
||||
{(params) => <CreditPoliciesPage accountId={params.accountId} />}
|
||||
</Route>
|
||||
<Route path="/admin/b2b-credit-policies/:id">
|
||||
{(params) => <CreditPoliciesPage id={params.id} />}
|
||||
</Route>
|
||||
<Route path="/admin/catalog">{() => <CatalogAdminPage />}</Route>
|
||||
<Route path="/admin/catalog/:id">
|
||||
{(params) => <CatalogAdminPage id={params.id} />}
|
||||
|
|
|
|||
|
|
@ -73,6 +73,7 @@ export function WorkspaceNavigation() {
|
|||
{ 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" },
|
||||
{ label: "B2B credit policies", path: "/admin/b2b-credit-policies", permission: "b2b.credit.read" },
|
||||
];
|
||||
return (
|
||||
<nav className="workspace-links" aria-label="Workspace navigation">
|
||||
|
|
|
|||
|
|
@ -0,0 +1,33 @@
|
|||
import { z } from "zod";
|
||||
import { currency, uuid } from "./commerce.ts";
|
||||
|
||||
const note = z.string().trim().min(3).max(500).regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text");
|
||||
export const creditStatus = z.enum(["PROPOSED", "ACTIVE", "REJECTED", "SUSPENDED"]);
|
||||
export const creditDecision = z.enum(["APPROVED", "REJECTED"]);
|
||||
|
||||
const terms = z.object({
|
||||
accountId: uuid,
|
||||
currency,
|
||||
creditLimit: z.string().regex(/^(0|[1-9]\d{0,13})\.\d{2}$/, "Use exactly two decimal places")
|
||||
.refine((value) => value !== "0.00", "Enter a positive credit limit"),
|
||||
netDays: z.number().int().min(1).max(180),
|
||||
rationale: note,
|
||||
});
|
||||
export const creditProposalInput = terms.extend({ idempotencyKey: uuid }).strict();
|
||||
export const creditSuspensionInput = z.object({ note, idempotencyKey: uuid }).strict();
|
||||
export const creditDecisionInput = creditSuspensionInput.extend({ decision: creditDecision });
|
||||
|
||||
export const creditPolicy = terms.extend({
|
||||
id: uuid,
|
||||
proposedById: uuid,
|
||||
status: creditStatus,
|
||||
createdAt: z.string().datetime(),
|
||||
events: z.array(z.object({
|
||||
id: uuid,
|
||||
actorId: uuid,
|
||||
kind: z.enum([...creditDecision.options, "SUSPENDED"]),
|
||||
sequence: z.number().int().min(1).max(2),
|
||||
note,
|
||||
createdAt: z.string().datetime(),
|
||||
})),
|
||||
});
|
||||
|
|
@ -123,6 +123,9 @@ function Details({ id, refreshDirectory }: { id: string; refreshDirectory: () =>
|
|||
<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>}
|
||||
{can("b2b.credit.read") && <p><WorkspaceLink href={`/admin/b2b-credit-policies/account/${account.id}`}>Business credit policies</WorkspaceLink></p>}
|
||||
{account.status === "VERIFIED" && can("b2b.credit.read") && can("b2b.credit.propose") &&
|
||||
<p><WorkspaceLink href={`/admin/b2b-credit-policies/new/${account.id}`}>Propose credit terms for this business</WorkspaceLink></p>}
|
||||
<ReadProfile profile={account} />
|
||||
</Panel>
|
||||
<Review key={`${account.profileVersion}:${account.latestEvent?.sequence ?? 0}`} account={account} path={path} refresh={refresh} />
|
||||
|
|
|
|||
|
|
@ -0,0 +1,171 @@
|
|||
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 { WorkspaceShell } from "@/components/WorkspaceShell";
|
||||
import { ActionForm, Field, Pager, Panel, QueryView, Table, WorkspaceLink, readNumber, readText, usePrivateQuery } from "@/components/WorkspaceTools";
|
||||
import { ApiError } from "@/lib/api";
|
||||
import { currency, uuid } from "@/lib/commerce";
|
||||
import { creditDecisionInput, creditPolicy, creditProposalInput, creditStatus, creditSuspensionInput } from "@/lib/credit";
|
||||
import { usePlatform } from "@/lib/platform";
|
||||
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||||
|
||||
const api = "/b2b/credit-policies";
|
||||
const route = "/admin/b2b-credit-policies";
|
||||
type Policy = z.infer<typeof creditPolicy>;
|
||||
|
||||
function useRefreshCreditLists() {
|
||||
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 PolicyList({ accountId }: { accountId?: string }) {
|
||||
const { can } = usePlatform();
|
||||
const [offset, setOffset] = useState(0);
|
||||
const [status, setStatus] = useState("ALL");
|
||||
const params = new URLSearchParams({ limit: "25", offset: String(offset) });
|
||||
if (accountId) params.set("accountId", accountId);
|
||||
if (status !== "ALL") params.set("status", status);
|
||||
const query = usePrivateQuery(`${api}?${params}`, z.array(creditPolicy));
|
||||
return <Panel title="Policy history">
|
||||
{accountId && <p className="workspace-id">Business account {accountId}</p>}
|
||||
{can("b2b.credit.propose") && <p><WorkspaceLink href={`${route}/new${accountId ? `/${accountId}` : ""}`}>Propose credit terms</WorkspaceLink></p>}
|
||||
<Field name="status" label="Policy status" value={status} onChange={(value) => { setStatus(value); setOffset(0); }}
|
||||
options={[{ value: "ALL", label: "All statuses" }, ...creditStatus.options.map((value) => ({ value, label: value }))]} />
|
||||
<QueryView query={query}>{(rows) => <>
|
||||
<Table head={["Business account ID", "Credit limit", "Net days", "Status", "Proposed"]}
|
||||
rowKeys={rows.map((row) => row.id)}
|
||||
rows={rows.map((row) => [
|
||||
<WorkspaceLink href={`${route}/${row.id}`}>{row.accountId}</WorkspaceLink>,
|
||||
`${row.currency} ${row.creditLimit}`, row.netDays, row.status, new Date(row.createdAt).toLocaleString(),
|
||||
])} />
|
||||
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||
</>}</QueryView>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function ProposePolicy({ accountId }: { accountId?: string }) {
|
||||
const { can } = usePlatform();
|
||||
const [, navigate] = useLocation();
|
||||
const refresh = useRefreshCreditLists();
|
||||
const command = useIdempotentCommand(api, creditProposalInput, creditPolicy, "propose");
|
||||
const pending = command.pending;
|
||||
if (!can("b2b.credit.propose")) return <Alert severity="warning">Your account does not have permission to propose credit terms.</Alert>;
|
||||
return <Panel title="Propose credit terms">
|
||||
<p>Propose terms for a verified business account. A different staff member must review them.</p>
|
||||
<ActionForm key={pending ? "retry" : "new"} label={pending ? "Retry credit proposal" : "Submit credit proposal"} reset={false}
|
||||
read={(form) => pending ? {} : ({
|
||||
accountId: accountId ?? readText(form, "accountId").trim(),
|
||||
currency: readText(form, "currency"),
|
||||
creditLimit: readText(form, "creditLimit").trim(),
|
||||
netDays: readNumber(form, "netDays"),
|
||||
rationale: readText(form, "rationale"),
|
||||
})}
|
||||
submit={async (input) => {
|
||||
const saved = await command.run(input);
|
||||
await refresh();
|
||||
navigate(`${route}/${saved.id}`);
|
||||
}}>
|
||||
{pending ? <Alert severity="warning">
|
||||
The server may have saved this proposal. Retrying reuses {pending.currency} {pending.creditLimit} with net {pending.netDays} days for account {pending.accountId}.
|
||||
</Alert> : <>
|
||||
{accountId ? <p className="workspace-id">Business account {accountId}</p> :
|
||||
<Field name="accountId" label="Business account ID" maxLength={36} helper={can("b2b.read") ? "Find the account ID in the business directory." : undefined} />}
|
||||
{!accountId && can("b2b.read") && <WorkspaceLink href="/admin/business-accounts">Business directory</WorkspaceLink>}
|
||||
<Field name="currency" label="Policy currency" value="INR" options={currency.options.map((value) => ({ value, label: value }))} />
|
||||
<Field name="creditLimit" label="Credit limit" maxLength={17} helper="Use two decimal places." />
|
||||
<Field name="netDays" label="Net days" type="number" helper="Enter 1 to 180 days." />
|
||||
<Field name="rationale" label="Proposal rationale" maxLength={500} />
|
||||
</>}
|
||||
</ActionForm>
|
||||
</Panel>;
|
||||
}
|
||||
|
||||
function PolicyDetail({ id }: { id: string }) {
|
||||
const { can } = usePlatform();
|
||||
const query = usePrivateQuery(`${api}/${id}`, creditPolicy);
|
||||
return <QueryView query={query}>{(policy) => <>
|
||||
<Panel title="Credit terms">
|
||||
<p>{policy.status} · {policy.currency} {policy.creditLimit} · Net {policy.netDays} days</p>
|
||||
<p className="workspace-id">Business account {policy.accountId}</p>
|
||||
<WorkspaceLink href={`${route}/account/${policy.accountId}`}>All policies for this business</WorkspaceLink>
|
||||
{can("b2b.read") && <p><WorkspaceLink href={`/admin/business-accounts/${policy.accountId}`}>Business profile</WorkspaceLink></p>}
|
||||
<p>Proposed {new Date(policy.createdAt).toLocaleString()} by {policy.proposedById}</p>
|
||||
<p>{policy.rationale}</p>
|
||||
<PolicyReview policy={policy} refresh={query.refetch} />
|
||||
</Panel>
|
||||
<Panel title="Decision history">
|
||||
<Table head={["Sequence", "Event", "Staff ID", "Recorded", "Note"]}
|
||||
rowKeys={policy.events.map((event) => event.id)} rows={policy.events.map((event) => [
|
||||
event.sequence, event.kind, event.actorId, new Date(event.createdAt).toLocaleString(), event.note,
|
||||
])} />
|
||||
</Panel>
|
||||
</>}</QueryView>;
|
||||
}
|
||||
|
||||
function PolicyReview({ policy, refresh }: { policy: Policy; refresh: () => Promise<unknown> }) {
|
||||
const { can, principal, scope } = usePlatform();
|
||||
const client = useQueryClient();
|
||||
const refreshLists = useRefreshCreditLists();
|
||||
const path = `${api}/${policy.id}`;
|
||||
const decision = useIdempotentCommand(`${path}/decision`, creditDecisionInput, creditPolicy, policy.id);
|
||||
const suspend = useIdempotentCommand(`${path}/suspend`, creditSuspensionInput, creditPolicy, policy.id);
|
||||
if (!can("b2b.credit.review")) return null;
|
||||
if (policy.status === "PROPOSED" && policy.proposedById === principal?.userId.toLowerCase()) {
|
||||
return <Alert severity="info">A different staff member must approve or reject this proposal.</Alert>;
|
||||
}
|
||||
if (policy.status !== "PROPOSED" && policy.status !== "ACTIVE") return null;
|
||||
|
||||
const reviewing = policy.status === "PROPOSED";
|
||||
const command = reviewing ? decision : suspend;
|
||||
const pending = command.pending;
|
||||
const pendingDecision = reviewing ? decision.pending?.decision : undefined;
|
||||
const label = reviewing ? "Record credit decision" : "Suspend credit policy";
|
||||
return <ActionForm key={`${policy.status}:${Boolean(pending)}`} label={pending ? `Retry ${reviewing ? "credit decision" : "suspension"}` : label}
|
||||
read={(form) => pending ? {} : ({
|
||||
note: readText(form, "note"),
|
||||
...(reviewing ? { decision: readText(form, "decision") } : {}),
|
||||
})}
|
||||
submit={async (input) => {
|
||||
try {
|
||||
const saved = await command.run(input);
|
||||
client.setQueryData(["private", scope, path], saved);
|
||||
await refreshLists();
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && ["B2B_CREDIT_REVIEW_STATE", "B2B_CREDIT_SUSPEND_STATE"].includes(error.code ?? "")) {
|
||||
await Promise.all([refresh(), refreshLists()]);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}}>
|
||||
{pending ? <Alert severity="warning">Retrying reuses the original {pendingDecision?.toLowerCase() ?? "suspension"} and note.</Alert> : <>
|
||||
{reviewing ? <>
|
||||
<p>Approval is final. The business can have one active policy in {policy.currency}.</p>
|
||||
<Field name="decision" label="Credit decision" options={[
|
||||
{ value: "", label: "Choose an outcome" },
|
||||
{ value: "APPROVED", label: "Approve" },
|
||||
{ value: "REJECTED", label: "Reject" },
|
||||
]} />
|
||||
</> : <p>Suspending retires these terms and frees the active slot for a new policy.</p>}
|
||||
<Field name="note" label={reviewing ? "Decision note" : "Suspension note"} maxLength={500} />
|
||||
</>}
|
||||
</ActionForm>;
|
||||
}
|
||||
|
||||
export default function CreditPoliciesPage({ id, accountId, propose = false }: { id?: string; accountId?: string; propose?: boolean }) {
|
||||
const policy = uuid.safeParse(id);
|
||||
const account = uuid.safeParse(accountId);
|
||||
return <WorkspaceShell title="B2B Credit Policies" permission="b2b.credit.read">
|
||||
{(id || accountId || propose) && <WorkspaceLink href={route}>All credit policies</WorkspaceLink>}
|
||||
<p>These policies record credit limits and terms. Checkout and receivables are separate workflows.</p>
|
||||
{(id && !policy.success) || (accountId && !account.success) ? <Alert severity="warning">Invalid policy or business account ID.</Alert> :
|
||||
propose ? <ProposePolicy key={account.data ?? "new"} accountId={account.data} /> :
|
||||
policy.success ? <PolicyDetail key={policy.data} id={policy.data} /> :
|
||||
<PolicyList key={account.data ?? "all"} accountId={account.data} />}
|
||||
</WorkspaceShell>;
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { creditDecisionInput, creditPolicy, creditProposalInput, creditSuspensionInput } from "../src/lib/credit.ts";
|
||||
|
||||
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
|
||||
const proposal = {
|
||||
accountId: id, currency: "INR", creditLimit: "99999999999999.99",
|
||||
netDays: 180, rationale: "Established customer", idempotencyKey: id,
|
||||
};
|
||||
|
||||
test("credit terms preserve exact limits and enforce the backend bounds", () => {
|
||||
assert.deepEqual(creditProposalInput.parse(proposal), proposal);
|
||||
for (const creditLimit of ["100000000000000.00", "0.00", "1.2", "-1.00"]) {
|
||||
assert.equal(creditProposalInput.safeParse({ ...proposal, creditLimit }).success, false);
|
||||
}
|
||||
assert.equal(creditProposalInput.safeParse({ ...proposal, netDays: 0 }).success, false);
|
||||
assert.equal(creditProposalInput.safeParse({ ...proposal, netDays: 181 }).success, false);
|
||||
assert.equal(creditPolicy.parse({
|
||||
...proposal, id, proposedById: id, status: "PROPOSED", createdAt: "2026-11-15T00:00:00Z", events: [],
|
||||
}).creditLimit, proposal.creditLimit);
|
||||
});
|
||||
|
||||
test("review and suspension use distinct payloads with a required note", () => {
|
||||
const body = { idempotencyKey: id, note: " Reviewed documents " };
|
||||
assert.equal(creditDecisionInput.parse({ ...body, decision: "APPROVED" }).note, "Reviewed documents");
|
||||
assert.equal(creditSuspensionInput.safeParse({ ...body, decision: "APPROVED" }).success, false);
|
||||
assert.equal(creditSuspensionInput.safeParse({ ...body, note: " " }).success, false);
|
||||
});
|
||||
|
|
@ -24,6 +24,7 @@ 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 CreditPoliciesPage from "../src/pages/CreditPoliciesPage";
|
||||
import { batchDetail } from "../src/lib/production";
|
||||
import theme from "../src/theme";
|
||||
import { Switch, Route } from "wouter";
|
||||
|
|
@ -252,6 +253,99 @@ test("an independent business reviewer retries the same decision before approval
|
|||
expect(attempts[1]).toEqual(attempts[0]);
|
||||
});
|
||||
|
||||
const creditFixture = {
|
||||
id, accountId: id, proposedById: id, currency: "INR", creditLimit: "99999999999999.99",
|
||||
netDays: 30, rationale: "Established customer", status: "PROPOSED", createdAt: "2026-11-15T00:00:00Z", events: [],
|
||||
};
|
||||
|
||||
test("credit proposals retry without changing the account or exact terms", async () => {
|
||||
const attempts: 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.credit.read", "b2b.credit.propose"] });
|
||||
if (url.endsWith("/b2b/credit-policies") && options?.method === "POST") {
|
||||
attempts.push(JSON.parse(String(options.body)));
|
||||
if (attempts.length === 1) throw new Error("Response lost");
|
||||
return json(creditFixture);
|
||||
}
|
||||
if (url.endsWith(`/b2b/credit-policies/${id}`)) return json(creditFixture);
|
||||
throw new Error(`Unexpected request ${url}`);
|
||||
}));
|
||||
history.replaceState(null, "", `/admin/b2b-credit-policies/new/${id}`);
|
||||
harness(<Switch>
|
||||
<Route path="/admin/b2b-credit-policies/new/:accountId">
|
||||
{(params) => <CreditPoliciesPage propose accountId={params.accountId} />}
|
||||
</Route>
|
||||
<Route path="/admin/b2b-credit-policies/:id">{(params) => <CreditPoliciesPage id={params.id} />}</Route>
|
||||
</Switch>);
|
||||
const user = userEvent.setup();
|
||||
await user.click(screen.getByText("Test login"));
|
||||
await user.type(await screen.findByRole("textbox", { name: /Credit limit/ }), creditFixture.creditLimit);
|
||||
await user.type(screen.getByRole("spinbutton", { name: /Net days/ }), "30");
|
||||
await user.type(screen.getByRole("textbox", { name: "Proposal rationale" }), creditFixture.rationale);
|
||||
await user.click(screen.getByRole("button", { name: "Submit credit proposal" }));
|
||||
await user.click(await screen.findByRole("button", { name: "Retry credit proposal" }));
|
||||
await screen.findByText(/PROPOSED · INR 99999999999999.99/);
|
||||
expect(attempts).toEqual([{
|
||||
accountId: id, currency: "INR", creditLimit: creditFixture.creditLimit, netDays: 30,
|
||||
rationale: creditFixture.rationale, idempotencyKey: expect.any(String),
|
||||
}, attempts[0]]);
|
||||
});
|
||||
|
||||
test("credit policy proposers cannot decide on their own terms", async () => {
|
||||
vi.stubGlobal("fetch", vi.fn(async (url: string) => {
|
||||
if (url.endsWith("/auth/login")) return json(session);
|
||||
if (url.endsWith("/auth/me")) return json({ ...me, permissions: ["b2b.credit.read", "b2b.credit.review"] });
|
||||
if (url.endsWith(`/b2b/credit-policies/${id}`)) return json(creditFixture);
|
||||
throw new Error(`Unexpected request ${url}`);
|
||||
}));
|
||||
harness(<CreditPoliciesPage id={id} />);
|
||||
await userEvent.setup().click(screen.getByText("Test login"));
|
||||
await screen.findByText("A different staff member must approve or reject this proposal.");
|
||||
expect(screen.queryByRole("button", { name: "Record credit decision" })).toBeNull();
|
||||
});
|
||||
|
||||
test("an independent reviewer can approve terms and retry an uncertain suspension", async () => {
|
||||
const reviewer = "d66c798a-f764-4b88-8d13-ace328ff1011";
|
||||
let policy: object = creditFixture;
|
||||
let approval: unknown;
|
||||
const suspensions: unknown[] = [];
|
||||
const approved = { id, actorId: reviewer, sequence: 1, kind: "APPROVED", note: "Reviewed documents", createdAt: creditFixture.createdAt };
|
||||
const suspended = { ...approved, id: reviewer, sequence: 2, kind: "SUSPENDED", note: "Temporary hold" };
|
||||
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, userId: reviewer, permissions: ["b2b.credit.read", "b2b.credit.review"] });
|
||||
if (url.endsWith(`/b2b/credit-policies/${id}`)) return json(policy);
|
||||
if (url.endsWith("/decision") && options?.method === "POST") {
|
||||
approval = JSON.parse(String(options.body));
|
||||
policy = { ...creditFixture, status: "ACTIVE", events: [approved] };
|
||||
return json(policy);
|
||||
}
|
||||
if (url.endsWith("/suspend") && options?.method === "POST") {
|
||||
suspensions.push(JSON.parse(String(options.body)));
|
||||
policy = { ...creditFixture, status: "SUSPENDED", events: [approved, suspended] };
|
||||
if (suspensions.length === 1) throw new Error("Response lost");
|
||||
return json(policy);
|
||||
}
|
||||
throw new Error(`Unexpected request ${url}`);
|
||||
}));
|
||||
harness(<CreditPoliciesPage id={id} />);
|
||||
const user = userEvent.setup();
|
||||
await user.click(screen.getByText("Test login"));
|
||||
await user.selectOptions(await screen.findByRole("combobox", { name: "Credit decision" }), "APPROVED");
|
||||
await user.type(screen.getByRole("textbox", { name: "Decision note" }), approved.note);
|
||||
await user.click(screen.getByRole("button", { name: "Record credit decision" }));
|
||||
await screen.findByText(/ACTIVE · INR 99999999999999.99/);
|
||||
expect(approval).toEqual({ decision: "APPROVED", note: approved.note, idempotencyKey: expect.any(String) });
|
||||
await user.type(screen.getByRole("textbox", { name: "Suspension note" }), suspended.note);
|
||||
await user.click(screen.getByRole("button", { name: "Suspend credit policy" }));
|
||||
await user.click(await screen.findByRole("button", { name: "Retry suspension" }));
|
||||
await screen.findByText(/SUSPENDED · INR 99999999999999.99/);
|
||||
expect(suspensions).toEqual([{ note: suspended.note, idempotencyKey: expect.any(String) }, suspensions[0]]);
|
||||
expect(screen.getByRole("cell", { name: approved.note })).toBeTruthy();
|
||||
expect(screen.getByRole("cell", { name: suspended.note })).toBeTruthy();
|
||||
});
|
||||
|
||||
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",
|
||||
|
|
|
|||
Loading…
Reference in New Issue