feat: manage B2B sample requests and dispatch
continuous-integration/drone/push Build is passing
Details
continuous-integration/drone/push Build is passing
Details
This commit is contained in:
parent
d511979324
commit
70d3f04567
|
|
@ -56,4 +56,6 @@ Customer and administration screens are implemented, with recovery, pricing, sto
|
||||||
- Quotation UAT should verify minimum quantities, expiry, immutable snapshots after archiving a price list, and exact retries for issuance and responses.
|
- Quotation UAT should verify minimum quantities, expiry, immutable snapshots after archiving a price list, and exact retries for issuance and responses.
|
||||||
- B2B credit policies support immutable proposals, independent approval or rejection, and suspension with decision history.
|
- 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.
|
- 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.
|
- B2B samples support requests for published variants, independent approval or rejection, and manual dispatch records with staff and reference history.
|
||||||
|
- Sample UAT should verify ineligible accounts and variants, self-review, dispatch only after approval, and replay with the original payload and key.
|
||||||
|
- Artwork, partner orders and payments, custom requests and reporting remain open.
|
||||||
|
|
|
||||||
12
src/App.tsx
12
src/App.tsx
|
|
@ -33,6 +33,7 @@ const BusinessAccountsPage = lazy(() => import("@/pages/BusinessAccountsPage"));
|
||||||
const PriceListsPage = lazy(() => import("@/pages/PriceListsPage"));
|
const PriceListsPage = lazy(() => import("@/pages/PriceListsPage"));
|
||||||
const QuotesPage = lazy(() => import("@/pages/QuotesPage"));
|
const QuotesPage = lazy(() => import("@/pages/QuotesPage"));
|
||||||
const CreditPoliciesPage = lazy(() => import("@/pages/CreditPoliciesPage"));
|
const CreditPoliciesPage = lazy(() => import("@/pages/CreditPoliciesPage"));
|
||||||
|
const SamplesPage = lazy(() => import("@/pages/SamplesPage"));
|
||||||
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"));
|
||||||
|
|
@ -105,6 +106,17 @@ function Router() {
|
||||||
<Route path="/admin/b2b-credit-policies/:id">
|
<Route path="/admin/b2b-credit-policies/:id">
|
||||||
{(params) => <CreditPoliciesPage id={params.id} />}
|
{(params) => <CreditPoliciesPage id={params.id} />}
|
||||||
</Route>
|
</Route>
|
||||||
|
<Route path="/admin/b2b-samples">{() => <SamplesPage />}</Route>
|
||||||
|
<Route path="/admin/b2b-samples/new">{() => <SamplesPage create />}</Route>
|
||||||
|
<Route path="/admin/b2b-samples/new/:accountId">
|
||||||
|
{(params) => <SamplesPage create accountId={params.accountId} />}
|
||||||
|
</Route>
|
||||||
|
<Route path="/admin/b2b-samples/account/:accountId">
|
||||||
|
{(params) => <SamplesPage accountId={params.accountId} />}
|
||||||
|
</Route>
|
||||||
|
<Route path="/admin/b2b-samples/:id">
|
||||||
|
{(params) => <SamplesPage 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} />}
|
||||||
|
|
|
||||||
|
|
@ -74,6 +74,7 @@ export function WorkspaceNavigation() {
|
||||||
{ label: "B2B price lists", path: "/admin/b2b-price-lists", permission: "b2b.price.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 quotations", path: "/admin/b2b-quotes", permission: "b2b.quote.read" },
|
||||||
{ label: "B2B credit policies", path: "/admin/b2b-credit-policies", permission: "b2b.credit.read" },
|
{ label: "B2B credit policies", path: "/admin/b2b-credit-policies", permission: "b2b.credit.read" },
|
||||||
|
{ label: "B2B samples", path: "/admin/b2b-samples", permission: "b2b.sample.read" },
|
||||||
];
|
];
|
||||||
return (
|
return (
|
||||||
<nav className="workspace-links" aria-label="Workspace navigation">
|
<nav className="workspace-links" aria-label="Workspace navigation">
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,39 @@
|
||||||
|
import { z } from "zod";
|
||||||
|
import { uuid } from "./commerce.ts";
|
||||||
|
|
||||||
|
const text = (max: number) =>
|
||||||
|
z.string().trim().min(3).max(max).regex(/^[^<>\u0000-\u001f\u007f]*$/, "Use plain text");
|
||||||
|
const note = text(500);
|
||||||
|
const decision = z.enum(["APPROVED", "REJECTED"]);
|
||||||
|
export const sampleStatus = z.enum(["REQUESTED", ...decision.options, "DISPATCHED"]);
|
||||||
|
|
||||||
|
const requestFields = z.object({
|
||||||
|
accountId: uuid,
|
||||||
|
variantId: uuid,
|
||||||
|
quantity: z.number().int().min(1).max(100),
|
||||||
|
purpose: text(500),
|
||||||
|
});
|
||||||
|
const key = { idempotencyKey: uuid };
|
||||||
|
export const sampleRequestInput = requestFields.extend(key).strict();
|
||||||
|
export const sampleDecisionInput = z.object({ decision, note, ...key }).strict();
|
||||||
|
export const sampleDispatchInput = z.object({ dispatchReference: text(100), note, ...key }).strict();
|
||||||
|
|
||||||
|
const sampleEvent = z.object({
|
||||||
|
id: uuid,
|
||||||
|
actorId: uuid,
|
||||||
|
sequence: z.number().int().min(1).max(2),
|
||||||
|
kind: z.enum([...decision.options, "DISPATCHED"]),
|
||||||
|
note,
|
||||||
|
dispatchReference: text(100).nullable(),
|
||||||
|
createdAt: z.string().datetime(),
|
||||||
|
});
|
||||||
|
|
||||||
|
export const sampleRequest = requestFields.extend({
|
||||||
|
id: uuid,
|
||||||
|
requestedById: uuid,
|
||||||
|
sku: z.string(),
|
||||||
|
variantName: z.string(),
|
||||||
|
status: sampleStatus,
|
||||||
|
createdAt: z.string().datetime(),
|
||||||
|
events: z.array(sampleEvent),
|
||||||
|
});
|
||||||
|
|
@ -126,6 +126,9 @@ function Details({ id, refreshDirectory }: { id: string; refreshDirectory: () =>
|
||||||
{can("b2b.credit.read") && <p><WorkspaceLink href={`/admin/b2b-credit-policies/account/${account.id}`}>Business credit policies</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") &&
|
{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>}
|
<p><WorkspaceLink href={`/admin/b2b-credit-policies/new/${account.id}`}>Propose credit terms for this business</WorkspaceLink></p>}
|
||||||
|
{can("b2b.sample.read") && <p><WorkspaceLink href={`/admin/b2b-samples/account/${account.id}`}>Business sample requests</WorkspaceLink></p>}
|
||||||
|
{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>}
|
||||||
<ReadProfile profile={account} />
|
<ReadProfile profile={account} />
|
||||||
</Panel>
|
</Panel>
|
||||||
<Review key={`${account.profileVersion}:${account.latestEvent?.sequence ?? 0}`} account={account} path={path} refresh={refresh} />
|
<Review key={`${account.profileVersion}:${account.latestEvent?.sequence ?? 0}`} account={account} path={path} refresh={refresh} />
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,168 @@
|
||||||
|
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 { uuid } from "@/lib/commerce";
|
||||||
|
import { usePlatform } from "@/lib/platform";
|
||||||
|
import { sampleDecisionInput, sampleDispatchInput, sampleRequest, sampleRequestInput, sampleStatus } from "@/lib/samples";
|
||||||
|
import { useIdempotentCommand } from "@/lib/use-idempotent-command";
|
||||||
|
|
||||||
|
const api = "/b2b/samples";
|
||||||
|
const route = "/admin/b2b-samples";
|
||||||
|
type Sample = z.infer<typeof sampleRequest>;
|
||||||
|
|
||||||
|
function useRefreshSampleLists() {
|
||||||
|
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 SampleList({ 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(sampleRequest));
|
||||||
|
|
||||||
|
return <Panel title="Sample request history">
|
||||||
|
{accountId && <p className="workspace-id">Business account {accountId}</p>}
|
||||||
|
{can("b2b.sample.request") && <p><WorkspaceLink href={`${route}/new${accountId ? `/${accountId}` : ""}`}>Request samples</WorkspaceLink></p>}
|
||||||
|
<Field name="status" label="Sample status" value={status} onChange={(value) => { setStatus(value); setOffset(0); }}
|
||||||
|
options={[{ value: "ALL", label: "All statuses" }, ...sampleStatus.options.map((value) => ({ value, label: value }))]} />
|
||||||
|
<QueryView query={query}>{(rows) => <>
|
||||||
|
<Table head={["Sample", "Business account ID", "Quantity", "Status", "Requested"]}
|
||||||
|
rowKeys={rows.map((row) => row.id)} rows={rows.map((row) => [
|
||||||
|
<WorkspaceLink href={`${route}/${row.id}`}>{row.variantName} ({row.sku})</WorkspaceLink>,
|
||||||
|
row.accountId, row.quantity, row.status, new Date(row.createdAt).toLocaleString(),
|
||||||
|
])} />
|
||||||
|
<Pager offset={offset} count={rows.length} onPage={setOffset} />
|
||||||
|
</>}</QueryView>
|
||||||
|
</Panel>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function RequestSamples({ accountId }: { accountId?: string }) {
|
||||||
|
const { can } = usePlatform();
|
||||||
|
const [, navigate] = useLocation();
|
||||||
|
const refresh = useRefreshSampleLists();
|
||||||
|
const command = useIdempotentCommand(api, sampleRequestInput, sampleRequest, "request");
|
||||||
|
const pending = command.pending;
|
||||||
|
if (!can("b2b.sample.request")) return <Alert severity="warning">Your account does not have permission to request samples.</Alert>;
|
||||||
|
return <Panel title="New sample request">
|
||||||
|
<p>Use a verified business account and an active variant of a published product.</p>
|
||||||
|
<ActionForm key={pending ? "retry" : "new"} label={pending ? "Retry sample request" : "Request samples"} reset={false}
|
||||||
|
read={(form) => pending ? {} : ({
|
||||||
|
accountId: accountId ?? readText(form, "accountId").trim(),
|
||||||
|
variantId: readText(form, "variantId").trim(),
|
||||||
|
quantity: readNumber(form, "quantity"),
|
||||||
|
purpose: readText(form, "purpose"),
|
||||||
|
})}
|
||||||
|
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 request. Retrying reuses account {pending.accountId}, variant {pending.variantId}, and quantity {pending.quantity}.
|
||||||
|
</Alert> : <>
|
||||||
|
{accountId ? <p className="workspace-id">Business account {accountId}</p> :
|
||||||
|
<Field name="accountId" label="Business account ID" maxLength={36} />}
|
||||||
|
{!accountId && can("b2b.read") && <WorkspaceLink href="/admin/business-accounts">Business directory</WorkspaceLink>}
|
||||||
|
<Field name="variantId" label="Variant ID" maxLength={36} />
|
||||||
|
{can("catalog.read") && <WorkspaceLink href="/admin/catalog">Find variant IDs in the product catalog</WorkspaceLink>}
|
||||||
|
<Field name="quantity" label="Sample quantity" type="number" helper="Enter 1 to 100." />
|
||||||
|
<Field name="purpose" label="Sample purpose" maxLength={500} />
|
||||||
|
</>}
|
||||||
|
</ActionForm>
|
||||||
|
</Panel>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SampleDetail({ id }: { id: string }) {
|
||||||
|
const { can } = usePlatform();
|
||||||
|
const query = usePrivateQuery(`${api}/${id}`, sampleRequest);
|
||||||
|
return <QueryView query={query}>{(sample) => <div className="workspace-id">
|
||||||
|
<Panel title={`${sample.variantName} (${sample.sku})`}>
|
||||||
|
<p>{sample.status} · Quantity {sample.quantity}</p>
|
||||||
|
<p>{sample.purpose}</p>
|
||||||
|
<p>Business account {sample.accountId}</p>
|
||||||
|
<WorkspaceLink href={`${route}/account/${sample.accountId}`}>All sample requests for this business</WorkspaceLink>
|
||||||
|
{can("b2b.read") && <p><WorkspaceLink href={`/admin/business-accounts/${sample.accountId}`}>Business profile</WorkspaceLink></p>}
|
||||||
|
<p>Requested {new Date(sample.createdAt).toLocaleString()} by {sample.requestedById}</p>
|
||||||
|
<SampleAction sample={sample} refresh={query.refetch} />
|
||||||
|
</Panel>
|
||||||
|
<Panel title="Review and dispatch history">
|
||||||
|
<Table head={["Event", "Recorded", "Staff ID", "Note", "Dispatch reference"]}
|
||||||
|
rowKeys={sample.events.map((event) => event.id)} rows={sample.events.map((event) => [
|
||||||
|
event.kind, new Date(event.createdAt).toLocaleString(), event.actorId, event.note, event.dispatchReference ?? "—",
|
||||||
|
])} />
|
||||||
|
</Panel>
|
||||||
|
</div>}</QueryView>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SampleAction({ sample, refresh }: { sample: Sample; refresh: () => Promise<unknown> }) {
|
||||||
|
const { can, principal, scope } = usePlatform();
|
||||||
|
const client = useQueryClient();
|
||||||
|
const refreshLists = useRefreshSampleLists();
|
||||||
|
const path = `${api}/${sample.id}`;
|
||||||
|
const review = useIdempotentCommand(`${path}/decision`, sampleDecisionInput, sampleRequest, sample.id);
|
||||||
|
const dispatch = useIdempotentCommand(`${path}/dispatch`, sampleDispatchInput, sampleRequest, sample.id);
|
||||||
|
const reviewing = sample.status === "REQUESTED" && can("b2b.sample.review");
|
||||||
|
const dispatching = sample.status === "APPROVED" && can("b2b.sample.dispatch");
|
||||||
|
if (!reviewing && !dispatching) return null;
|
||||||
|
if (reviewing && sample.requestedById === principal?.userId.toLowerCase()) {
|
||||||
|
return <Alert severity="info">A different staff member must review this sample request.</Alert>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const command = reviewing ? review : dispatch;
|
||||||
|
const pending = command.pending;
|
||||||
|
const label = reviewing ? (pending ? "Retry sample decision" : "Record sample decision") :
|
||||||
|
(pending ? "Retry dispatch" : "Record dispatch");
|
||||||
|
return <ActionForm key={`${sample.status}:${Boolean(pending)}`} label={label}
|
||||||
|
read={(form) => pending ? {} : ({
|
||||||
|
note: readText(form, "note"),
|
||||||
|
...(reviewing ? { decision: readText(form, "decision") } :
|
||||||
|
{ dispatchReference: readText(form, "dispatchReference") }),
|
||||||
|
})}
|
||||||
|
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_SAMPLE_REVIEW_STATE", "B2B_SAMPLE_DISPATCH_STATE"].includes(error.code ?? "")) {
|
||||||
|
await Promise.all([refresh(), refreshLists()]);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}}>
|
||||||
|
{pending ? <Alert severity="warning">The server may have saved this action. Retrying reuses the original details.</Alert> : <>
|
||||||
|
{reviewing ? <Field name="decision" label="Review decision" options={[
|
||||||
|
{ value: "", label: "Choose an outcome" }, { value: "APPROVED", label: "Approve" }, { value: "REJECTED", label: "Reject" },
|
||||||
|
]} /> : <>
|
||||||
|
<p>Record dispatch after the physical handoff. Enter the shipment or handoff reference.</p>
|
||||||
|
<Field name="dispatchReference" label="Dispatch reference" maxLength={100} />
|
||||||
|
</>}
|
||||||
|
<Field name="note" label={reviewing ? "Review note" : "Dispatch note"} maxLength={500} />
|
||||||
|
</>}
|
||||||
|
</ActionForm>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function SamplesPage({ id, accountId, create = false }: { id?: string; accountId?: string; create?: boolean }) {
|
||||||
|
const sample = uuid.safeParse(id);
|
||||||
|
const account = uuid.safeParse(accountId);
|
||||||
|
return <WorkspaceShell title="B2B Samples" permission="b2b.sample.read">
|
||||||
|
{(id || accountId || create) && <WorkspaceLink href={route}>All sample requests</WorkspaceLink>}
|
||||||
|
{(id && !sample.success) || (accountId && !account.success) ? <Alert severity="warning">Invalid sample or business account ID.</Alert> :
|
||||||
|
create ? <RequestSamples key={account.data ?? "new"} accountId={account.data} /> :
|
||||||
|
sample.success ? <SampleDetail key={sample.data} id={sample.data} /> :
|
||||||
|
<SampleList key={account.data ?? "all"} accountId={account.data} />}
|
||||||
|
</WorkspaceShell>;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,40 @@
|
||||||
|
import { test } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { sampleDecisionInput, sampleDispatchInput, sampleRequest, sampleRequestInput } from "../src/lib/samples.ts";
|
||||||
|
|
||||||
|
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
|
||||||
|
const requestedAt = "2026-11-16T00:00:00.000Z";
|
||||||
|
const request = { accountId: id, variantId: id, quantity: 4, purpose: "Fragrance evaluation", idempotencyKey: id };
|
||||||
|
|
||||||
|
test("sample requests accept 1 to 100 units and trim their purpose", () => {
|
||||||
|
assert.deepEqual(sampleRequestInput.parse({ ...request, purpose: " Fragrance evaluation " }), request);
|
||||||
|
for (const quantity of [0, 101, 4.5]) {
|
||||||
|
assert.equal(sampleRequestInput.safeParse({ ...request, quantity }).success, false);
|
||||||
|
}
|
||||||
|
assert.equal(sampleRequestInput.safeParse({ ...request, purpose: "<invalid>" }).success, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("sample decisions and dispatch accept separate payloads with notes", () => {
|
||||||
|
const decision = { decision: "APPROVED", note: "Approved for evaluation", idempotencyKey: id };
|
||||||
|
const dispatch = { dispatchReference: "Carrier-42", note: "Handed to carrier", idempotencyKey: id };
|
||||||
|
assert.deepEqual(sampleDecisionInput.parse(decision), decision);
|
||||||
|
assert.deepEqual(sampleDispatchInput.parse({ ...dispatch, dispatchReference: " Carrier-42 " }), dispatch);
|
||||||
|
assert.equal(sampleDispatchInput.safeParse(decision).success, false);
|
||||||
|
assert.equal(sampleDecisionInput.safeParse({ ...decision, note: " " }).success, false);
|
||||||
|
assert.equal(sampleDispatchInput.safeParse({ ...dispatch, dispatchReference: "1" }).success, false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("sample history preserves reference and actor while stripping internal metadata", () => {
|
||||||
|
const history = [
|
||||||
|
{ id, actorId: id, sequence: 1, kind: "APPROVED", note: "Approved for evaluation", dispatchReference: null, createdAt: requestedAt },
|
||||||
|
{ id, actorId: id, sequence: 2, kind: "DISPATCHED", note: "Handed to carrier", dispatchReference: "Carrier-42", createdAt: requestedAt },
|
||||||
|
];
|
||||||
|
const result = sampleRequest.parse({
|
||||||
|
...request, id, requestedById: id, sku: "SAMPLE-1", variantName: "Vanilla",
|
||||||
|
status: "DISPATCHED", createdAt: requestedAt, requestHash: "internal",
|
||||||
|
events: history.map((entry) => ({ ...entry, idempotencyKey: id, requestHash: "internal" })),
|
||||||
|
});
|
||||||
|
assert.deepEqual(result.events, history);
|
||||||
|
assert.equal("idempotencyKey" in result, false);
|
||||||
|
assert.equal("requestHash" in result, false);
|
||||||
|
});
|
||||||
|
|
@ -0,0 +1,173 @@
|
||||||
|
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 SamplesPage from "../src/pages/SamplesPage";
|
||||||
|
import theme from "../src/theme";
|
||||||
|
|
||||||
|
const accountId = "d66c798a-f764-4b88-8d13-ace328ff1010";
|
||||||
|
const requesterId = "d66c798a-f764-4b88-8d13-ace328ff1011";
|
||||||
|
const reviewerId = "d66c798a-f764-4b88-8d13-ace328ff1012";
|
||||||
|
const variantId = "d66c798a-f764-4b88-8d13-ace328ff1013";
|
||||||
|
const sampleId = "d66c798a-f764-4b88-8d13-ace328ff1014";
|
||||||
|
const createdAt = "2026-11-16T08:00:00.000Z";
|
||||||
|
const api = "/b2b/samples";
|
||||||
|
const route = "/admin/b2b-samples";
|
||||||
|
const requestPath = `${api}/${sampleId}`;
|
||||||
|
const sample = {
|
||||||
|
id: sampleId,
|
||||||
|
organizationId: accountId,
|
||||||
|
accountId,
|
||||||
|
variantId,
|
||||||
|
requestedById: requesterId,
|
||||||
|
sku: "VANILLA-TIN",
|
||||||
|
variantName: "Vanilla tin",
|
||||||
|
quantity: 4,
|
||||||
|
purpose: "Fragrance evaluation",
|
||||||
|
status: "REQUESTED",
|
||||||
|
createdAt,
|
||||||
|
updatedAt: createdAt,
|
||||||
|
events: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
const json = (body: unknown) => new Response(JSON.stringify(body));
|
||||||
|
|
||||||
|
function staffSession(url: string, userId: 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 showSamples(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("an uncertain sample request retries with its original account, variant, quantity, purpose, and key", async () => {
|
||||||
|
const attempts: unknown[] = [];
|
||||||
|
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
|
||||||
|
const auth = staffSession(url, requesterId, ["b2b.sample.read", "b2b.sample.request"]);
|
||||||
|
if (auth) return auth;
|
||||||
|
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(sample);
|
||||||
|
}
|
||||||
|
if (url.endsWith(requestPath) && options?.method !== "POST") return json(sample);
|
||||||
|
throw new Error(`Unexpected request ${url}`);
|
||||||
|
}));
|
||||||
|
history.replaceState(null, "", `${route}/new/${accountId}`);
|
||||||
|
showSamples(<Switch>
|
||||||
|
<Route path={`${route}/new/:accountId`}>
|
||||||
|
{(params) => <SamplesPage create accountId={params.accountId} />}
|
||||||
|
</Route>
|
||||||
|
<Route path={`${route}/:id`}>{(params) => <SamplesPage id={params.id} />}</Route>
|
||||||
|
</Switch>);
|
||||||
|
|
||||||
|
const user = userEvent.setup();
|
||||||
|
await user.click(screen.getByRole("button", { name: "Test login" }));
|
||||||
|
await user.type(await screen.findByRole("textbox", { name: /Variant ID/ }), variantId);
|
||||||
|
const quantity = screen.getByRole("spinbutton", { name: /Sample quantity/ });
|
||||||
|
await user.clear(quantity);
|
||||||
|
await user.type(quantity, "4");
|
||||||
|
await user.type(screen.getByRole("textbox", { name: /Sample purpose/ }), sample.purpose);
|
||||||
|
await user.click(screen.getByRole("button", { name: "Request samples" }));
|
||||||
|
await user.click(await screen.findByRole("button", { name: "Retry sample request" }));
|
||||||
|
await screen.findByText(sample.purpose);
|
||||||
|
expect(location.pathname).toBe(`${route}/${sampleId}`);
|
||||||
|
expect(attempts[0]).toEqual({ accountId, variantId, quantity: 4, purpose: sample.purpose, idempotencyKey: expect.any(String) });
|
||||||
|
expect(attempts).toEqual([attempts[0], attempts[0]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a sample requester cannot review their own request or dispatch it before approval", async () => {
|
||||||
|
const fetch = vi.fn(async (url: string) => {
|
||||||
|
const auth = staffSession(url, requesterId, ["b2b.sample.read", "b2b.sample.review", "b2b.sample.dispatch"]);
|
||||||
|
if (auth) return auth;
|
||||||
|
if (url.endsWith(requestPath)) return json(sample);
|
||||||
|
throw new Error(`Unexpected request ${url}`);
|
||||||
|
});
|
||||||
|
vi.stubGlobal("fetch", fetch);
|
||||||
|
showSamples(<SamplesPage id={sampleId} />);
|
||||||
|
expect(fetch).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
const user = userEvent.setup();
|
||||||
|
await user.click(screen.getByRole("button", { name: "Test login" }));
|
||||||
|
await screen.findByText(sample.purpose);
|
||||||
|
expect(screen.queryByRole("button", { name: "Record sample decision" })).toBeNull();
|
||||||
|
expect(screen.queryByRole("button", { name: "Record dispatch" })).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an independent reviewer can approve a request and retry a manual dispatch", async () => {
|
||||||
|
const approved = {
|
||||||
|
id: requesterId, actorId: reviewerId, sequence: 1, kind: "APPROVED", note: "Approved for evaluation",
|
||||||
|
dispatchReference: null, createdAt,
|
||||||
|
};
|
||||||
|
const dispatched = {
|
||||||
|
...approved, id: reviewerId, sequence: 2, kind: "DISPATCHED", note: "Handed to the carrier",
|
||||||
|
dispatchReference: "TRACK-01",
|
||||||
|
};
|
||||||
|
let decision: unknown;
|
||||||
|
let current: object = sample;
|
||||||
|
const dispatches: unknown[] = [];
|
||||||
|
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
|
||||||
|
const auth = staffSession(url, reviewerId, ["b2b.sample.read", "b2b.sample.review", "b2b.sample.dispatch"]);
|
||||||
|
if (auth) return auth;
|
||||||
|
if (url.endsWith(requestPath)) return json(current);
|
||||||
|
if (url.endsWith(`${requestPath}/decision`) && options?.method === "POST") {
|
||||||
|
decision = JSON.parse(String(options.body));
|
||||||
|
current = { ...sample, status: "APPROVED", events: [approved] };
|
||||||
|
return json(current);
|
||||||
|
}
|
||||||
|
if (url.endsWith(`${requestPath}/dispatch`) && options?.method === "POST") {
|
||||||
|
dispatches.push(JSON.parse(String(options.body)));
|
||||||
|
current = { ...sample, status: "DISPATCHED", events: [approved, dispatched] };
|
||||||
|
if (dispatches.length === 1) throw new Error("Response lost");
|
||||||
|
return json(current);
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected request ${url}`);
|
||||||
|
}));
|
||||||
|
showSamples(<SamplesPage id={sampleId} />);
|
||||||
|
|
||||||
|
const user = userEvent.setup();
|
||||||
|
await user.click(screen.getByRole("button", { name: "Test login" }));
|
||||||
|
await user.selectOptions(await screen.findByRole("combobox", { name: /Review decision/ }), "APPROVED");
|
||||||
|
await user.type(screen.getByRole("textbox", { name: /Review note/ }), approved.note);
|
||||||
|
await user.click(screen.getByRole("button", { name: "Record sample decision" }));
|
||||||
|
await user.type(await screen.findByRole("textbox", { name: /Dispatch reference/ }), dispatched.dispatchReference);
|
||||||
|
await user.type(screen.getByRole("textbox", { name: /Dispatch note/ }), dispatched.note);
|
||||||
|
await user.click(screen.getByRole("button", { name: "Record dispatch" }));
|
||||||
|
await user.click(await screen.findByRole("button", { name: "Retry dispatch" }));
|
||||||
|
await screen.findByRole("cell", { name: dispatched.dispatchReference });
|
||||||
|
expect(screen.getByRole("cell", { name: approved.note })).toBeTruthy();
|
||||||
|
expect(screen.getByRole("cell", { name: dispatched.note })).toBeTruthy();
|
||||||
|
expect(screen.queryByRole("button", { name: "Record dispatch" })).toBeNull();
|
||||||
|
expect(decision).toEqual({ decision: "APPROVED", note: approved.note, idempotencyKey: expect.any(String) });
|
||||||
|
expect(dispatches[0]).toEqual({ dispatchReference: dispatched.dispatchReference, note: dispatched.note, idempotencyKey: expect.any(String) });
|
||||||
|
expect(dispatches).toEqual([dispatches[0], dispatches[0]]);
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue