feat: add B2B account onboarding and verification #20
|
|
@ -45,3 +45,9 @@ Customer and administration screens are implemented, with recovery, pricing, sto
|
||||||
- BOM UAT should activate a second revision and confirm the previous revision becomes superseded. Repeat for the other BOM type and verify its active revision is independent. Check that inactive materials and stale drafts are rejected.
|
- BOM UAT should activate a second revision and confirm the previous revision becomes superseded. Repeat for the other BOM type and verify its active revision is independent. Check that inactive materials and stale drafts are rejected.
|
||||||
- Costing UAT should revise a material rate and verify that future BOM estimates use the new revision while an existing batch snapshot retains its original amounts and rates. Test missing rates, missing usage, and fully rejected output.
|
- Costing UAT should revise a material rate and verify that future BOM estimates use the new revision while an existing batch snapshot retains its original amounts and rates. Test missing rates, missing usage, and fully rejected output.
|
||||||
- Warehouse movement UAT should verify both ledgers and unchanged combined stock after a transfer, rejection of insufficient stock, and one ledger entry for a retried adjustment.
|
- Warehouse movement UAT should verify both ledgers and unchanged combined stock after a transfer, rejection of insufficient stock, and one ledger entry for a retried adjustment.
|
||||||
|
|
||||||
|
## Phase 4 implementation status
|
||||||
|
|
||||||
|
- Staff can create, edit, submit and review B2B business accounts. Verification uses submitted profile snapshots, separate permissions for submission and review, and an immutable event history.
|
||||||
|
- 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.
|
||||||
|
- Price lists, minimum order quantities, quotes, credit policies, samples, artwork, partner orders and payments, custom requests and reporting remain open.
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ const AuditPage = lazy(() =>
|
||||||
const CatalogAdminPage = lazy(() => import("@/pages/CatalogAdminPage"));
|
const CatalogAdminPage = lazy(() => import("@/pages/CatalogAdminPage"));
|
||||||
const InventoryPage = lazy(() => import("@/pages/InventoryPage"));
|
const InventoryPage = lazy(() => import("@/pages/InventoryPage"));
|
||||||
const MaterialStockPage = lazy(() => import("@/pages/MaterialStockPage"));
|
const MaterialStockPage = lazy(() => import("@/pages/MaterialStockPage"));
|
||||||
|
const BusinessAccountsPage = lazy(() => import("@/pages/BusinessAccountsPage"));
|
||||||
const MaterialCostRatesPage = lazy(() => import("@/pages/MaterialCostRatesPage"));
|
const MaterialCostRatesPage = lazy(() => import("@/pages/MaterialCostRatesPage"));
|
||||||
const ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
|
const ProcurementPage = lazy(() => import("@/pages/ProcurementPage"));
|
||||||
const BomPage = lazy(() => import("@/pages/BomPage"));
|
const BomPage = lazy(() => import("@/pages/BomPage"));
|
||||||
|
|
@ -67,6 +68,11 @@ function Router() {
|
||||||
<Route path="/admin/access" component={AccessPage} />
|
<Route path="/admin/access" component={AccessPage} />
|
||||||
<Route path="/admin/roles" component={RolesPage} />
|
<Route path="/admin/roles" component={RolesPage} />
|
||||||
<Route path="/admin/audit" component={AuditPage} />
|
<Route path="/admin/audit" component={AuditPage} />
|
||||||
|
<Route path="/admin/business-accounts">{() => <BusinessAccountsPage />}</Route>
|
||||||
|
<Route path="/admin/business-accounts/new">{() => <BusinessAccountsPage create />}</Route>
|
||||||
|
<Route path="/admin/business-accounts/:id">
|
||||||
|
{(params) => <BusinessAccountsPage id={params.id} />}
|
||||||
|
</Route>
|
||||||
<Route path="/admin/catalog">{() => <CatalogAdminPage />}</Route>
|
<Route path="/admin/catalog">{() => <CatalogAdminPage />}</Route>
|
||||||
<Route path="/admin/catalog/:id">
|
<Route path="/admin/catalog/:id">
|
||||||
{(params) => <CatalogAdminPage id={params.id} />}
|
{(params) => <CatalogAdminPage id={params.id} />}
|
||||||
|
|
|
||||||
|
|
@ -70,6 +70,7 @@ export function WorkspaceNavigation() {
|
||||||
{ label: "Pricing", path: "/admin/pricing", permission: "pricing.manage" },
|
{ label: "Pricing", path: "/admin/pricing", permission: "pricing.manage" },
|
||||||
{ label: "All orders", path: "/admin/orders", permission: "orders.read" },
|
{ label: "All orders", path: "/admin/orders", permission: "orders.read" },
|
||||||
{ label: "Audit", path: "/admin/audit", permission: "audit.read" },
|
{ label: "Audit", path: "/admin/audit", permission: "audit.read" },
|
||||||
|
{ label: "Business accounts", path: "/admin/business-accounts", permission: "b2b.read" },
|
||||||
];
|
];
|
||||||
return (
|
return (
|
||||||
<nav className="workspace-links" aria-label="Workspace navigation">
|
<nav className="workspace-links" aria-label="Workspace navigation">
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,49 @@
|
||||||
|
import { z } from "zod";
|
||||||
|
import { uuid } from "./commerce.ts";
|
||||||
|
|
||||||
|
const text = (max: number, min = 1) =>
|
||||||
|
z.string().trim().min(min).max(max).regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text");
|
||||||
|
|
||||||
|
export const businessProfile = z.object({
|
||||||
|
legalName: text(160),
|
||||||
|
tradingName: text(160).nullable(),
|
||||||
|
registrationNumber: text(64, 3),
|
||||||
|
taxIdentifier: text(64).nullable(),
|
||||||
|
countryCode: z.string().trim().toUpperCase().regex(/^[A-Z]{2}$/, "Use a two-letter country code"),
|
||||||
|
contactEmail: z.string().trim().email().max(254).toLowerCase(),
|
||||||
|
contactPhone: z.string().trim().regex(/^\+?[0-9 ()-]{7,24}$/, "Enter a valid phone number").nullable(),
|
||||||
|
billingLine1: text(200),
|
||||||
|
billingCity: text(100),
|
||||||
|
billingRegion: text(100),
|
||||||
|
billingPostalCode: text(20),
|
||||||
|
}).strict();
|
||||||
|
|
||||||
|
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 submissionInput = z.object({ idempotencyKey: uuid }).strict();
|
||||||
|
export const decisionInput = submissionInput.extend({
|
||||||
|
decision: z.enum(["APPROVED", "REJECTED"]),
|
||||||
|
note: text(500, 3),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const businessEvent = z.object({
|
||||||
|
id: uuid,
|
||||||
|
actorId: uuid,
|
||||||
|
sequence: z.number().int().positive(),
|
||||||
|
kind: z.enum(["SUBMITTED", "APPROVED", "REJECTED"]),
|
||||||
|
profileSnapshot: profileSnapshot.nullable(),
|
||||||
|
note: z.string().nullable(),
|
||||||
|
createdAt: z.string().datetime(),
|
||||||
|
});
|
||||||
|
export const businessAccount = businessInput.extend({
|
||||||
|
id: uuid,
|
||||||
|
profileVersion,
|
||||||
|
status: z.enum(["DRAFT", "PENDING", "VERIFIED", "REJECTED"]),
|
||||||
|
latestEvent: businessEvent.nullable(),
|
||||||
|
}).strip();
|
||||||
|
|
||||||
|
export const businessSearch = text(100, 0);
|
||||||
|
|
@ -0,0 +1,228 @@
|
||||||
|
import { useRef, useState } from "react";
|
||||||
|
import { useLocation } from "wouter";
|
||||||
|
import { useQueryClient } from "@tanstack/react-query";
|
||||||
|
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 { ConfirmAction } from "@/components/ConfirmAction";
|
||||||
|
import { businessAccount, businessEvent, businessInput, businessProfile, businessSearch, decisionInput, submissionInput } from "@/lib/business";
|
||||||
|
import { isUnknownOutcome } from "@/lib/api";
|
||||||
|
import { uuid } from "@/lib/commerce";
|
||||||
|
import { usePlatform } from "@/lib/platform";
|
||||||
|
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||||||
|
|
||||||
|
const route = "/admin/business-accounts";
|
||||||
|
const api = "/b2b/accounts";
|
||||||
|
type Account = z.infer<typeof businessAccount>;
|
||||||
|
type Profile = z.infer<typeof businessProfile>;
|
||||||
|
|
||||||
|
const fields = [
|
||||||
|
{ name: "legalName", label: "Legal name", maxLength: 160 },
|
||||||
|
{ name: "tradingName", label: "Trading name", maxLength: 160, optional: true },
|
||||||
|
{ name: "registrationNumber", label: "Registration number", maxLength: 64 },
|
||||||
|
{ name: "taxIdentifier", label: "Tax identifier", maxLength: 64, optional: true },
|
||||||
|
{ name: "countryCode", label: "Country code", maxLength: 2 },
|
||||||
|
{ name: "contactEmail", label: "Contact email", maxLength: 254, type: "email" },
|
||||||
|
{ name: "contactPhone", label: "Contact phone", maxLength: 24, type: "tel", optional: true },
|
||||||
|
{ name: "billingLine1", label: "Billing address", maxLength: 200 },
|
||||||
|
{ name: "billingCity", label: "Billing city", maxLength: 100 },
|
||||||
|
{ name: "billingRegion", label: "Billing region", maxLength: 100 },
|
||||||
|
{ name: "billingPostalCode", label: "Billing postal code", maxLength: 20 },
|
||||||
|
] as const satisfies readonly { name: keyof Profile; label: string; maxLength: number; optional?: boolean; type?: string }[];
|
||||||
|
|
||||||
|
function AccountList() {
|
||||||
|
const { can } = usePlatform();
|
||||||
|
const [search, setSearch] = useState("");
|
||||||
|
const [offset, setOffset] = useState(0);
|
||||||
|
const params = new URLSearchParams({ limit: "25", offset: String(offset), ...(search ? { search } : {}) });
|
||||||
|
const query = usePrivateQuery(`${api}?${params}`, z.array(businessAccount));
|
||||||
|
return <Panel title="Business directory">
|
||||||
|
{can("b2b.manage") && <p><WorkspaceLink href={`${route}/new`}>Create business account</WorkspaceLink></p>}
|
||||||
|
<ActionForm label="Search businesses" reset={false}
|
||||||
|
read={(form) => ({ search: readText(form, "search") })}
|
||||||
|
submit={async (value) => {
|
||||||
|
setSearch(z.object({ search: businessSearch }).parse(value).search);
|
||||||
|
setOffset(0);
|
||||||
|
}}>
|
||||||
|
<Field name="search" label="Business name or code" required={false} maxLength={100} />
|
||||||
|
</ActionForm>
|
||||||
|
<QueryView query={query}>{(rows) => <>
|
||||||
|
<Table head={["Business", "Code", "Country", "Status"]} rowKeys={rows.map((row) => row.id)}
|
||||||
|
rows={rows.map((row) => [
|
||||||
|
<WorkspaceLink href={`${route}/${row.id}`}>{row.legalName}</WorkspaceLink>,
|
||||||
|
row.code, row.countryCode, row.status,
|
||||||
|
])} />
|
||||||
|
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||||
|
</>}</QueryView>
|
||||||
|
</Panel>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProfileFields({ account }: { account?: Account }) {
|
||||||
|
return <>
|
||||||
|
{!account && <Field name="code" label="Business code" maxLength={32} helper="The business code is permanent." />}
|
||||||
|
{fields.map((field) => (
|
||||||
|
<Field key={field.name} name={field.name} label={field.label} maxLength={field.maxLength}
|
||||||
|
required={!("optional" in field)} type={"type" in field ? field.type : undefined}
|
||||||
|
value={account?.[field.name] ?? ""} />
|
||||||
|
))}
|
||||||
|
</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function readProfile(form: FormData) {
|
||||||
|
return Object.fromEntries(fields.map((field) => {
|
||||||
|
const value = readText(form, field.name).trim();
|
||||||
|
return [field.name, "optional" in field ? value || null : value];
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function ReadProfile({ profile }: { profile: Profile }) {
|
||||||
|
return <dl className="permission-list">
|
||||||
|
{fields.map((field) => <div key={field.name}><dt>{field.label}</dt><dd>{profile[field.name] ?? "—"}</dd></div>)}
|
||||||
|
</dl>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function CreateAccount({ refreshDirectory }: { refreshDirectory: () => Promise<void> }) {
|
||||||
|
const { can, request } = usePlatform();
|
||||||
|
const [, navigate] = useLocation();
|
||||||
|
const [uncertainCode, setUncertainCode] = useState("");
|
||||||
|
if (!can("b2b.manage")) return <Alert severity="warning">Your account does not have permission to create business profiles.</Alert>;
|
||||||
|
return <Panel title="New business profile">
|
||||||
|
{uncertainCode ? <Alert severity="warning">The server may have saved {uncertainCode}. Search the business directory for that code before creating it again.</Alert> :
|
||||||
|
<ActionForm label="Save business draft" reset={false}
|
||||||
|
read={(form) => businessInput.parse({ ...readProfile(form), code: readText(form, "code") })}
|
||||||
|
submit={async (value) => {
|
||||||
|
const body = businessInput.parse(value);
|
||||||
|
try {
|
||||||
|
const saved = await request(api, businessAccount, { method: "POST", body });
|
||||||
|
await refreshDirectory();
|
||||||
|
navigate(`${route}/${saved.id}`);
|
||||||
|
} catch (error) {
|
||||||
|
if (isUnknownOutcome(error)) {
|
||||||
|
setUncertainCode(body.code);
|
||||||
|
await refreshDirectory();
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}}>
|
||||||
|
<ProfileFields />
|
||||||
|
</ActionForm>}
|
||||||
|
</Panel>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Details({ id, refreshDirectory }: { id: string; refreshDirectory: () => Promise<void> }) {
|
||||||
|
const path = `${api}/${id}`;
|
||||||
|
const query = usePrivateQuery(path, businessAccount);
|
||||||
|
const events = usePrivateQuery(`${path}/events`, z.array(businessEvent));
|
||||||
|
async function refresh() {
|
||||||
|
await Promise.all([query.refetch(), events.refetch(), refreshDirectory()]);
|
||||||
|
}
|
||||||
|
return <QueryView query={query}>{(account) => <>
|
||||||
|
<Panel title={account.legalName}>
|
||||||
|
<p>Business {account.code} · {account.status} · Profile version {account.profileVersion}</p>
|
||||||
|
<ReadProfile profile={account} />
|
||||||
|
</Panel>
|
||||||
|
<Review key={`${account.profileVersion}:${account.latestEvent?.sequence ?? 0}`} account={account} path={path} refresh={refresh} />
|
||||||
|
<Panel title="Verification history">
|
||||||
|
<QueryView query={events}>{(rows) => (
|
||||||
|
<Table head={["Sequence", "Event", "Date", "Staff ID", "Note"]} rowKeys={rows.map((row) => row.id)}
|
||||||
|
rows={rows.map((row) => [
|
||||||
|
row.sequence, row.profileSnapshot ? <details>
|
||||||
|
<summary>Submitted profile version {row.profileSnapshot.profileVersion}</summary>
|
||||||
|
<ReadProfile profile={row.profileSnapshot} />
|
||||||
|
</details> : row.kind, new Date(row.createdAt).toLocaleString(), row.actorId, row.note ?? "—",
|
||||||
|
])} />
|
||||||
|
)}</QueryView>
|
||||||
|
</Panel>
|
||||||
|
</>}</QueryView>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Review({ account, path, refresh }: { account: Account; path: string; refresh: () => Promise<void> }) {
|
||||||
|
const { can, principal, request } = usePlatform();
|
||||||
|
const sequence = account.latestEvent?.sequence ?? 0;
|
||||||
|
const submit = useIdempotentCommand(`${path}/submit`, submissionInput, businessEvent, `profile:${account.profileVersion}:${sequence}`);
|
||||||
|
const decision = useIdempotentCommand(`${path}/decision`, decisionInput, businessEvent, `submission:${sequence}`);
|
||||||
|
const editable = account.status === "DRAFT" || account.status === "REJECTED";
|
||||||
|
const ownSubmission = account.latestEvent?.actorId === principal?.userId.toLowerCase();
|
||||||
|
const latest = account.latestEvent;
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const updating = useRef(false);
|
||||||
|
|
||||||
|
async function whileCurrent(action: () => Promise<unknown>) {
|
||||||
|
if (updating.current) throw new Error("A profile or review update is already in progress.");
|
||||||
|
updating.current = true;
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const current = await request(path, businessAccount);
|
||||||
|
if (current.profileVersion !== account.profileVersion || current.latestEvent?.id !== latest?.id) {
|
||||||
|
throw new Error("The business profile or review has changed. Open the latest version.");
|
||||||
|
}
|
||||||
|
await action();
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
await refresh();
|
||||||
|
} finally {
|
||||||
|
updating.current = false;
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return <>
|
||||||
|
{editable && can("b2b.manage") && <Panel title="Prepare for verification">
|
||||||
|
{submit.pending ? (
|
||||||
|
<ActionForm label="Retry verification submission" read={() => ({})} submit={() => whileCurrent(() => submit.run({}))}>
|
||||||
|
<Alert severity="warning">Retrying uses the original submission key for this profile version.</Alert>
|
||||||
|
</ActionForm>
|
||||||
|
) : <>
|
||||||
|
<ActionForm label="Save profile changes" reset={false} lockFields={busy}
|
||||||
|
read={(form) => businessProfile.parse(readProfile(form))}
|
||||||
|
submit={(body) => whileCurrent(() => request(path, businessAccount, { method: "PATCH", body }))}>
|
||||||
|
<ProfileFields account={account} />
|
||||||
|
</ActionForm>
|
||||||
|
<ConfirmAction label="Submit for verification" disabled={busy}
|
||||||
|
message={`Send saved profile version ${account.profileVersion} for review? Confirm that any edits have been saved.`}
|
||||||
|
onConfirm={() => whileCurrent(() => submit.run({}))} />
|
||||||
|
</>}
|
||||||
|
</Panel>}
|
||||||
|
{account.status === "PENDING" && latest?.kind === "SUBMITTED" && latest.profileSnapshot && <Panel title="Submitted profile for review">
|
||||||
|
<p>Profile version {latest.profileSnapshot.profileVersion} · Submitted {new Date(latest.createdAt).toLocaleString()}</p>
|
||||||
|
<ReadProfile profile={latest.profileSnapshot} />
|
||||||
|
{can("b2b.verify") && (ownSubmission ? <Alert severity="info">A different staff member must review this submission.</Alert> :
|
||||||
|
<ActionForm key={decision.pending ? "retry" : "decide"} label={decision.pending ? "Retry verification decision" : "Record verification decision"}
|
||||||
|
read={(form) => decision.pending ? {} : ({ decision: readText(form, "decision"), note: readText(form, "note") })}
|
||||||
|
submit={(value) => whileCurrent(() => decision.run(value))}>
|
||||||
|
{decision.pending ? <Alert severity="warning">Retrying uses the saved {decision.pending.decision.toLowerCase()} decision and note.</Alert> : <>
|
||||||
|
<p>Record the outcome of your manual review of this submitted profile.</p>
|
||||||
|
<Field name="decision" label="Review outcome" options={[
|
||||||
|
{ value: "", label: "Choose an outcome" }, { value: "APPROVED", label: "Approve" }, { value: "REJECTED", label: "Reject" },
|
||||||
|
]} />
|
||||||
|
<Field name="note" label="Review note" maxLength={500} helper="Describe the basis for the decision." />
|
||||||
|
</>}
|
||||||
|
</ActionForm>)}
|
||||||
|
</Panel>}
|
||||||
|
</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Accounts({ id, create }: { id?: string; create?: boolean }) {
|
||||||
|
const { scope } = usePlatform();
|
||||||
|
const client = useQueryClient();
|
||||||
|
const refreshDirectory = () => client.invalidateQueries({
|
||||||
|
predicate: ({ queryKey }) => queryKey[0] === "private" && queryKey[1] === scope &&
|
||||||
|
typeof queryKey[2] === "string" && queryKey[2].startsWith(`${api}?`),
|
||||||
|
});
|
||||||
|
const parsed = uuid.safeParse(id);
|
||||||
|
if (!create && !id) return <AccountList />;
|
||||||
|
return <>
|
||||||
|
<WorkspaceLink href={route}>All business accounts</WorkspaceLink>
|
||||||
|
{create ? <CreateAccount refreshDirectory={refreshDirectory} /> : parsed.success ?
|
||||||
|
<Details key={parsed.data} id={parsed.data} refreshDirectory={refreshDirectory} /> :
|
||||||
|
<Alert severity="warning">Invalid business account ID.</Alert>}
|
||||||
|
</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function BusinessAccountsPage(props: { id?: string; create?: boolean }) {
|
||||||
|
return <WorkspaceShell title="B2B Business Accounts" permission="b2b.read">
|
||||||
|
<Accounts {...props} />
|
||||||
|
</WorkspaceShell>;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,28 @@
|
||||||
|
import { test } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { businessEvent, businessInput, businessProfile, decisionInput } from "../src/lib/business.ts";
|
||||||
|
|
||||||
|
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
|
||||||
|
const profile = {
|
||||||
|
legalName: "Studio", tradingName: null, registrationNumber: "REG-42", taxIdentifier: null,
|
||||||
|
countryCode: "IN", contactEmail: "buyer@example.com", contactPhone: null, billingLine1: "42 Example Road",
|
||||||
|
billingCity: "Mumbai", billingRegion: "Maharashtra", billingPostalCode: "400001",
|
||||||
|
};
|
||||||
|
|
||||||
|
test("business drafts normalize identifiers and keep optional details nullable", () => {
|
||||||
|
assert.deepEqual(businessInput.parse({ ...profile, code: " studio ", countryCode: "in", contactEmail: "BUYER@example.com" }),
|
||||||
|
{ ...profile, code: "STUDIO" });
|
||||||
|
assert.equal(businessProfile.safeParse({ ...profile, code: "CANNOT_CHANGE" }).success, false);
|
||||||
|
assert.equal(businessProfile.safeParse({ ...profile, legalName: "<invalid>" }).success, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("review events preserve submitted profile versions without command metadata", () => {
|
||||||
|
const event = businessEvent.parse({
|
||||||
|
id, actorId: id, sequence: 1, kind: "SUBMITTED", profileSnapshot: { ...profile, profileVersion: 2 },
|
||||||
|
note: null, createdAt: "2026-11-14T00:00:00.000Z", requestHash: "internal", idempotencyKey: id,
|
||||||
|
});
|
||||||
|
assert.equal(event.profileSnapshot?.profileVersion, 2);
|
||||||
|
assert.equal("requestHash" in event, false);
|
||||||
|
assert.equal(decisionInput.safeParse({ decision: "APPROVED", note: " ", idempotencyKey: id }).success, false);
|
||||||
|
assert.equal(decisionInput.parse({ decision: "REJECTED", note: " Details differ ", idempotencyKey: id }).note, "Details differ");
|
||||||
|
});
|
||||||
|
|
@ -21,6 +21,7 @@ import { CompletedBatchOperations } from "../src/pages/CompletedBatchOperations"
|
||||||
import { BatchCostSnapshot } from "../src/pages/CostingPanels";
|
import { BatchCostSnapshot } from "../src/pages/CostingPanels";
|
||||||
import MaterialCostRatesPage from "../src/pages/MaterialCostRatesPage";
|
import MaterialCostRatesPage from "../src/pages/MaterialCostRatesPage";
|
||||||
import MaterialStockPage from "../src/pages/MaterialStockPage";
|
import MaterialStockPage from "../src/pages/MaterialStockPage";
|
||||||
|
import BusinessAccountsPage from "../src/pages/BusinessAccountsPage";
|
||||||
import { batchDetail } from "../src/lib/production";
|
import { batchDetail } from "../src/lib/production";
|
||||||
import theme from "../src/theme";
|
import theme from "../src/theme";
|
||||||
import { Switch, Route } from "wouter";
|
import { Switch, Route } from "wouter";
|
||||||
|
|
@ -184,6 +185,71 @@ function harness(children: ReactNode) {
|
||||||
return { client, ...result };
|
return { client, ...result };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const businessProfileFixture = {
|
||||||
|
legalName: "Studio", tradingName: null, registrationNumber: "REG-42", taxIdentifier: null,
|
||||||
|
countryCode: "IN", contactEmail: "buyer@example.com", contactPhone: null, billingLine1: "42 Example Road",
|
||||||
|
billingCity: "Mumbai", billingRegion: "Maharashtra", billingPostalCode: "400001", profileVersion: 1,
|
||||||
|
};
|
||||||
|
const submittedBusiness = {
|
||||||
|
id, actorId: id, sequence: 1, kind: "SUBMITTED", profileSnapshot: businessProfileFixture,
|
||||||
|
note: null, createdAt: "2026-11-14T00:00:00.000Z",
|
||||||
|
};
|
||||||
|
|
||||||
|
test("a business submitter sees the submitted profile and cannot verify it", async () => {
|
||||||
|
const fetch = vi.fn(async (url: string) => {
|
||||||
|
if (url.endsWith("/auth/login")) return json(session);
|
||||||
|
if (url.endsWith("/auth/me")) return json({ ...me, permissions: ["b2b.read", "b2b.manage", "b2b.verify"] });
|
||||||
|
if (url.endsWith("/events")) return json([submittedBusiness]);
|
||||||
|
if (url.endsWith(`/b2b/accounts/${id}`)) return json({
|
||||||
|
...businessProfileFixture, id, code: "STUDIO", status: "PENDING", latestEvent: submittedBusiness,
|
||||||
|
});
|
||||||
|
throw new Error(`Unexpected request ${url}`);
|
||||||
|
});
|
||||||
|
vi.stubGlobal("fetch", fetch);
|
||||||
|
harness(<BusinessAccountsPage id={id} />);
|
||||||
|
expect(fetch).not.toHaveBeenCalled();
|
||||||
|
await userEvent.setup().click(screen.getByText("Test login"));
|
||||||
|
await screen.findByText("A different staff member must review this submission.");
|
||||||
|
expect(screen.queryByRole("button", { name: "Record verification decision" })).toBeNull();
|
||||||
|
expect(screen.queryByRole("button", { name: "Save profile changes" })).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an independent business reviewer retries the same decision before approval is confirmed", async () => {
|
||||||
|
const reviewer = "d66c798a-f764-4b88-8d13-ace328ff1011";
|
||||||
|
const approved = { ...submittedBusiness, id: reviewer, actorId: reviewer, sequence: 2,
|
||||||
|
kind: "APPROVED", profileSnapshot: null, note: "Details checked" };
|
||||||
|
let verified = false;
|
||||||
|
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, userId: reviewer, permissions: ["b2b.read", "b2b.verify"] });
|
||||||
|
if (url.endsWith("/events")) return json(verified ? [submittedBusiness, approved] : [submittedBusiness]);
|
||||||
|
if (url.endsWith(`/b2b/accounts/${id}`)) return json({
|
||||||
|
...businessProfileFixture, id, code: "STUDIO", status: verified ? "VERIFIED" : "PENDING",
|
||||||
|
latestEvent: verified ? approved : submittedBusiness,
|
||||||
|
});
|
||||||
|
if (url.endsWith("/decision") && options?.method === "POST") {
|
||||||
|
attempts.push(JSON.parse(String(options.body)));
|
||||||
|
if (attempts.length === 1) throw new Error("Response lost");
|
||||||
|
verified = true;
|
||||||
|
return json(approved);
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected request ${url}`);
|
||||||
|
}));
|
||||||
|
harness(<BusinessAccountsPage id={id} />);
|
||||||
|
const user = userEvent.setup();
|
||||||
|
await user.click(screen.getByText("Test login"));
|
||||||
|
await user.selectOptions(await screen.findByRole("combobox", { name: /Review outcome/ }), "APPROVED");
|
||||||
|
await user.type(screen.getByRole("textbox", { name: /Review note/ }), "Details checked");
|
||||||
|
await user.click(screen.getByRole("button", { name: "Record verification decision" }));
|
||||||
|
await user.click(await screen.findByRole("button", { name: "Retry verification decision" }));
|
||||||
|
await screen.findByText(/Business STUDIO · VERIFIED/);
|
||||||
|
expect(await screen.findByRole("cell", { name: "Details checked" })).toBeTruthy();
|
||||||
|
expect(attempts).toHaveLength(2);
|
||||||
|
expect(attempts[0]).toEqual({ decision: "APPROVED", note: "Details checked", idempotencyKey: expect.any(String) });
|
||||||
|
expect(attempts[1]).toEqual(attempts[0]);
|
||||||
|
});
|
||||||
|
|
||||||
test("material transfers exclude the source warehouse and retry with the same key", async () => {
|
test("material transfers exclude the source warehouse and retry with the same key", async () => {
|
||||||
const destination = "d66c798a-f764-4b88-8d13-ace328ff1011";
|
const destination = "d66c798a-f764-4b88-8d13-ace328ff1011";
|
||||||
const stock = {
|
const stock = {
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue