+
+ {sample.status} · Quantity {sample.quantity}
+ {sample.purpose}
+ Business account {sample.accountId}
+ All sample requests for this business
+ {can("b2b.read") && Business profile
}
+ Requested {new Date(sample.createdAt).toLocaleString()} by {sample.requestedById}
+
+
+
+ event.id)} rows={sample.events.map((event) => [
+ event.kind, new Date(event.createdAt).toLocaleString(), event.actorId, event.note, event.dispatchReference ?? "—",
+ ])} />
+
+ };
+}
+
+function SampleAction({ sample, refresh }: { sample: Sample; refresh: () => Promise }) {
+ 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 A different staff member must review this sample request.;
+ }
+
+ 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 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 ? The server may have saved this action. Retrying reuses the original details. : <>
+ {reviewing ? : <>
+ Record dispatch after the physical handoff. Enter the shipment or handoff reference.
+
+ >}
+
+ >}
+ ;
+}
+
+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
+ {(id || accountId || create) && All sample requests}
+ {(id && !sample.success) || (accountId && !account.success) ? Invalid sample or business account ID. :
+ create ? :
+ sample.success ? :
+ }
+ ;
+}
diff --git a/test/samples.test.ts b/test/samples.test.ts
new file mode 100644
index 0000000..5489e2c
--- /dev/null
+++ b/test/samples.test.ts
@@ -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: "" }).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);
+});
diff --git a/test/samples.ui.test.tsx b/test/samples.ui.test.tsx
new file mode 100644
index 0000000..e23e35a
--- /dev/null
+++ b/test/samples.ui.test.tsx
@@ -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 ;
+}
+
+function showSamples(children: ReactNode) {
+ localStorage.setItem("mani.organization", accountId);
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ render(
+
+ {children}
+
+ );
+}
+
+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(
+
+ {(params) => }
+
+ {(params) => }
+ );
+
+ 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();
+ 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();
+
+ 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]]);
+});