1065 lines
55 KiB
TypeScript
1065 lines
55 KiB
TypeScript
import { type ReactNode } from "react";
|
|
import { act, render, screen, waitFor, within } from "@testing-library/react";
|
|
import { Table } from "../src/components/WorkspaceTools";
|
|
import { ConfirmAction } from "../src/components/ConfirmAction";
|
|
import userEvent from "@testing-library/user-event";
|
|
import { afterEach, expect, test, vi } from "vitest";
|
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
import { ThemeProvider } from "@mui/material/styles";
|
|
import axe from "axe-core";
|
|
import { PlatformProvider, usePlatform } from "../src/lib/platform";
|
|
import CartPage from "../src/pages/CartPage";
|
|
import AccessPage, { RolesPage } from "../src/pages/AccessPage";
|
|
import OrdersPage from "../src/pages/OrdersPage";
|
|
import ProcurementPage from "../src/pages/ProcurementPage";
|
|
import { ReceiptStockPosting } from "../src/pages/ReceiptStockPosting";
|
|
import { PurchaseOrderInvoices } from "../src/pages/PurchaseOrderInvoices";
|
|
import SupplierDocumentsPage from "../src/pages/SupplierDocumentsPage";
|
|
import BomPage from "../src/pages/BomPage";
|
|
import ProductionBatchesPage from "../src/pages/ProductionBatchesPage";
|
|
import { CompletedBatchOperations } from "../src/pages/CompletedBatchOperations";
|
|
import { BatchCostSnapshot } from "../src/pages/CostingPanels";
|
|
import MaterialCostRatesPage from "../src/pages/MaterialCostRatesPage";
|
|
import MaterialStockPage from "../src/pages/MaterialStockPage";
|
|
import BusinessAccountsPage from "../src/pages/BusinessAccountsPage";
|
|
import PriceListsPage from "../src/pages/PriceListsPage";
|
|
import QuotesPage from "../src/pages/QuotesPage";
|
|
import CreditPoliciesPage from "../src/pages/CreditPoliciesPage";
|
|
import { batchDetail } from "../src/lib/production";
|
|
import theme from "../src/theme";
|
|
import { Switch, Route } from "wouter";
|
|
const id = "d66c798a-f764-4b88-8d13-ace328ff1010";
|
|
test("table refresh keeps an open confirmation bound to its original record", async () => {
|
|
const approve = vi.fn(async (_id: string) => undefined);
|
|
const table = (ids: string[]) => (
|
|
<Table
|
|
head={["Name", "Action"]}
|
|
rowKeys={ids}
|
|
rows={ids.map((id) => [
|
|
id,
|
|
<ConfirmAction
|
|
label="Approve"
|
|
message={`Approve ${id}?`}
|
|
onConfirm={() => approve(id)}
|
|
/>,
|
|
])}
|
|
/>
|
|
);
|
|
const view = render(table(["A", "B"])),
|
|
user = userEvent.setup();
|
|
await user.click(screen.getAllByRole("button", { name: "Approve" })[0]);
|
|
view.rerender(table(["B", "A"]));
|
|
await user.click(screen.getByRole("button", { name: "Confirm" }));
|
|
expect(approve).toHaveBeenCalledWith("A");
|
|
});
|
|
test("role-read accounts can view roles without user-read access", async () => {
|
|
const fetch = vi.fn(async (url: string) =>
|
|
url.endsWith("/auth/login")
|
|
? json(session)
|
|
: url.endsWith("/auth/me")
|
|
? json({ ...me, permissions: ["roles.read"] })
|
|
: url.includes("/roles?")
|
|
? json([
|
|
{
|
|
id,
|
|
name: "Observer",
|
|
permissions: [],
|
|
isSystem: false,
|
|
organizationId: id,
|
|
},
|
|
])
|
|
: Promise.reject(new Error("Unexpected private request")),
|
|
);
|
|
vi.stubGlobal("fetch", fetch);
|
|
harness(<RolesPage />);
|
|
const user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
await screen.findByText("Observer");
|
|
expect(fetch.mock.calls.some(([url]) => url.includes("/users"))).toBe(false);
|
|
expect(screen.queryByRole("link", { name: "Access" })).toBeNull();
|
|
});
|
|
const me = { userId: id, organizationId: id, sessionId: id, permissions: [] };
|
|
const session = {
|
|
accessToken: "test-opaque",
|
|
tokenType: "Bearer",
|
|
expiresAt: new Date(Date.now() + 3600000).toISOString(),
|
|
};
|
|
test("procurement observers can read suppliers and cannot see write controls", async () => {
|
|
const fetch = vi.fn(async (url: string) =>
|
|
url.endsWith("/auth/login")
|
|
? json(session)
|
|
: url.endsWith("/auth/me")
|
|
? json({ ...me, permissions: ["procurement.read"] })
|
|
: url.includes("/suppliers?")
|
|
? json([{ id, name: "Wax Supplier", code: "WAX", contactName: "Contact", email: "contact@example.com", phone: "+919999999999", active: true }])
|
|
: Promise.reject(new Error("Unexpected private request")),
|
|
);
|
|
vi.stubGlobal("fetch", fetch);
|
|
harness(<ProcurementPage />);
|
|
await userEvent.setup().click(screen.getByText("Test login"));
|
|
const terms = await screen.findByRole("link", { name: "Supply terms and orders for Wax Supplier" });
|
|
expect(terms.getAttribute("href")).toBe(`/admin/procurement/suppliers/${id}`);
|
|
expect(screen.queryByRole("button", { name: "Edit Wax Supplier" })).toBeNull();
|
|
expect(screen.queryByRole("button", { name: "Create supplier" })).toBeNull();
|
|
});
|
|
const address = {
|
|
id,
|
|
recipient: "Test Recipient",
|
|
line1: "Test Street",
|
|
line2: "",
|
|
city: "Test City",
|
|
region: "Test State",
|
|
postalCode: "123456",
|
|
countryCode: "IN",
|
|
phone: "+919999999999",
|
|
isDefault: true,
|
|
};
|
|
const line = {
|
|
variantId: id,
|
|
quantity: 1,
|
|
variant: {
|
|
name: "Small",
|
|
sku: "TEST",
|
|
price: "10",
|
|
currency: "INR",
|
|
active: true,
|
|
product: { name: "Test candle", status: "PUBLISHED" },
|
|
},
|
|
};
|
|
const { id: _addressId, isDefault: _isDefault, ...snapshotAddress } = address;
|
|
const order = {
|
|
id,
|
|
status: "PENDING_PAYMENT",
|
|
currency: "INR",
|
|
merchandiseTotal: "10",
|
|
subtotal: "10",
|
|
discount: "0",
|
|
createdAt: new Date().toISOString(),
|
|
expiresAt: new Date(Date.now() + 900000).toISOString(),
|
|
pricingStatus: "UNFINALIZED",
|
|
taxTotal: null,
|
|
shippingTotal: null,
|
|
payableTotal: null,
|
|
paymentAvailable: false,
|
|
address: snapshotAddress,
|
|
lines: [
|
|
{
|
|
variantId: id,
|
|
sku: "TEST",
|
|
productName: "Test candle",
|
|
variantName: "Small",
|
|
quantity: 1,
|
|
unitPrice: "10",
|
|
lineTotal: "10",
|
|
},
|
|
],
|
|
};
|
|
const json = (body: unknown, status = 200) =>
|
|
new Response(JSON.stringify(body), { status });
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
history.replaceState(null, "", "/");
|
|
});
|
|
function Login() {
|
|
const platform = usePlatform();
|
|
return (
|
|
<button
|
|
onClick={() => platform.signIn("staff@example.com", "test password")}
|
|
>
|
|
Test login
|
|
</button>
|
|
);
|
|
}
|
|
function harness(children: ReactNode) {
|
|
localStorage.setItem("mani.organization", id);
|
|
const client = new QueryClient({
|
|
defaultOptions: { queries: { retry: false } },
|
|
});
|
|
const result = render(
|
|
<ThemeProvider theme={theme}>
|
|
<QueryClientProvider client={client}>
|
|
<PlatformProvider>
|
|
<Login />
|
|
{children}
|
|
</PlatformProvider>
|
|
</QueryClientProvider>
|
|
</ThemeProvider>,
|
|
);
|
|
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]);
|
|
});
|
|
|
|
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",
|
|
items: [{ id, variantId: id, unitPrice: "12.5", minQuantity: 12 }] };
|
|
const quote = {
|
|
id, accountId: id, number: "BQ-42", accountSnapshot: businessProfileFixture, currency: "INR",
|
|
status: "ISSUED", merchandiseTotal: "150.00", expiresAt, createdAt: new Date().toISOString(),
|
|
priceListName: "Wholesale", customerReference: null, response: null,
|
|
lines: [{ id, variantId: id, sku: "WAX-01", name: "Candle", quantity: 12, minQuantity: 12, unitPrice: "12.50", lineTotal: "150.00" }],
|
|
};
|
|
const issueAttempts: unknown[] = [];
|
|
const responses: unknown[] = [];
|
|
vi.stubGlobal("fetch", vi.fn(async (url: string, options?: RequestInit) => {
|
|
if (url.endsWith("/auth/login")) return json(session);
|
|
if (url.endsWith("/auth/me")) return json({ ...me, permissions: ["b2b.quote.read", "b2b.quote.manage", "b2b.price.read"] });
|
|
if (url.endsWith(`/b2b/price-lists/${id}`)) return json(priceList);
|
|
if (url.endsWith("/b2b/quotes") && options?.method === "POST") {
|
|
issueAttempts.push(JSON.parse(String(options.body)));
|
|
if (issueAttempts.length === 1) throw new Error("Response lost");
|
|
return json(quote);
|
|
}
|
|
if (url.endsWith(`/b2b/quotes/${id}`)) return json(quote);
|
|
if (url.endsWith("/response") && options?.method === "POST") {
|
|
responses.push(JSON.parse(String(options.body)));
|
|
if (responses.length === 1) throw new Error("Response lost");
|
|
return json({ ...quote, status: "ACCEPTED",
|
|
response: { kind: "ACCEPTED", note: "Confirmed by email", createdAt: quote.createdAt } });
|
|
}
|
|
throw new Error(`Unexpected request ${url}`);
|
|
}));
|
|
history.replaceState(null, "", `/admin/b2b-quotes/new/${id}/${id}`);
|
|
harness(<Switch>
|
|
<Route path="/admin/b2b-quotes/new/:accountId/:priceListId">
|
|
{(params) => <QuotesPage issue accountId={params.accountId} priceListId={params.priceListId} />}
|
|
</Route>
|
|
<Route path="/admin/b2b-quotes/:id">{(params) => <QuotesPage id={params.id} />}</Route>
|
|
</Switch>);
|
|
const user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
await user.selectOptions(await screen.findByRole("combobox", { name: /Variant for line 1/ }), id);
|
|
await user.type(screen.getByRole("textbox", { name: /Expiry with timezone/ }), expiresAt);
|
|
await user.type(screen.getByRole("spinbutton", { name: /Quantity for line 1/ }), "12");
|
|
await user.click(screen.getByRole("button", { name: "Issue quotation" }));
|
|
await user.click(await screen.findByRole("button", { name: "Retry quotation issuance" }));
|
|
await screen.findByRole("heading", { name: "BQ-42" });
|
|
expect(issueAttempts).toHaveLength(2);
|
|
expect(issueAttempts[0]).toEqual({ accountId: id, priceListId: id, expiresAt, customerReference: null,
|
|
lines: [{ variantId: id, quantity: 12 }], idempotencyKey: expect.any(String) });
|
|
expect(issueAttempts[1]).toEqual(issueAttempts[0]);
|
|
expect(screen.getByText("Merchandise total INR 150.00")).toBeTruthy();
|
|
await user.selectOptions(screen.getByRole("combobox", { name: "Quotation response" }), "ACCEPTED");
|
|
await user.type(screen.getByRole("textbox", { name: /Response note/ }), "Confirmed by email");
|
|
await user.click(screen.getByRole("button", { name: "Record quotation response" }));
|
|
await user.click(await screen.findByRole("button", { name: "Retry quotation response" }));
|
|
await screen.findByText(/ACCEPTED on .*Confirmed by email/);
|
|
expect(responses).toHaveLength(2);
|
|
expect(responses[0]).toEqual({ kind: "ACCEPTED", note: "Confirmed by email", idempotencyKey: expect.any(String) });
|
|
expect(responses[1]).toEqual(responses[0]);
|
|
});
|
|
|
|
test("a price list freezes draft terms on activation and checks order minimums before archiving", async () => {
|
|
const variantId = "d66c798a-f764-4b88-8d13-ace328ff1011";
|
|
let status = "DRAFT";
|
|
let terms: { unitPrice: string; minQuantity: number } | undefined;
|
|
const priceList = () => ({ id, accountId: id, name: "Wholesale", currency: "INR", status });
|
|
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.price.read", "b2b.price.manage"] });
|
|
if (url.endsWith(`/b2b/price-lists/${id}`)) return json({
|
|
...priceList(), items: terms ? [{ id, variantId, ...terms, unitPrice: "12.5" }] : [],
|
|
});
|
|
if (url.endsWith(`/items/${variantId}`) && options?.method === "PUT") {
|
|
terms = JSON.parse(String(options.body));
|
|
return json({ id, variantId, ...terms });
|
|
}
|
|
if (url.endsWith("/activate") && options?.method === "POST") {
|
|
status = "ACTIVE";
|
|
return json(priceList());
|
|
}
|
|
if (url.endsWith("/archive") && options?.method === "POST") {
|
|
status = "ARCHIVED";
|
|
return json(priceList());
|
|
}
|
|
if (url.endsWith("/price-check") && options?.method === "POST") {
|
|
const { lines } = JSON.parse(String(options.body));
|
|
if (lines[0].quantity < 12) return json({ code: "B2B_PRICE_MINIMUM_QUANTITY", message: "Quantity below the minimum" }, 409);
|
|
return json({ priceListId: id, currency: "INR", merchandiseTotal: "150.00",
|
|
lines: [{ variantId, quantity: 12, minQuantity: 12, unitPrice: "12.50", lineTotal: "150.00" }] });
|
|
}
|
|
throw new Error(`Unexpected request ${url}`);
|
|
}));
|
|
harness(<PriceListsPage id={id} />);
|
|
const user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
await user.type(await screen.findByRole("textbox", { name: /Variant ID/ }), variantId);
|
|
await user.type(screen.getByRole("textbox", { name: /Unit price in INR/ }), "12.50");
|
|
await user.type(screen.getByRole("spinbutton", { name: /Minimum order quantity/ }), "12");
|
|
await user.click(screen.getByRole("button", { name: "Save variant terms" }));
|
|
await screen.findByRole("cell", { name: "INR 12.50" });
|
|
expect(terms).toEqual({ unitPrice: "12.50", minQuantity: 12 });
|
|
await user.click(screen.getByRole("button", { name: "Activate price list" }));
|
|
await user.click(screen.getByRole("button", { name: "Confirm" }));
|
|
await user.selectOptions(await screen.findByRole("combobox", { name: /Variant for line 1/ }), variantId);
|
|
expect(screen.queryByRole("button", { name: "Save variant terms" })).toBeNull();
|
|
const quantity = screen.getByRole("spinbutton", { name: /Quantity for line 1/ });
|
|
await user.type(quantity, "11");
|
|
await user.click(screen.getByRole("button", { name: "Check partner prices" }));
|
|
await screen.findByText("Quantity below the minimum");
|
|
await user.clear(quantity);
|
|
await user.type(quantity, "12");
|
|
await user.click(screen.getByRole("button", { name: "Check partner prices" }));
|
|
await screen.findByText("Merchandise total INR 150.00");
|
|
await user.click(screen.getByRole("button", { name: "Archive price list" }));
|
|
await user.click(screen.getByRole("button", { name: "Confirm" }));
|
|
await screen.findByText("INR · ARCHIVED");
|
|
expect(screen.queryByRole("button", { name: "Check partner prices" })).toBeNull();
|
|
});
|
|
|
|
test("material transfers exclude the source warehouse and retry with the same key", async () => {
|
|
const destination = "d66c798a-f764-4b88-8d13-ace328ff1011";
|
|
const stock = {
|
|
id, warehouse: { id, name: "Main warehouse" },
|
|
material: { id, name: "Wax", code: "WAX", unit: "GRAM", kind: "WAX", active: true },
|
|
onHand: "2.000",
|
|
};
|
|
const attempts: unknown[] = [];
|
|
const transfer = {
|
|
id, materialId: id, fromWarehouseId: id, toWarehouseId: destination,
|
|
fromStockItemId: id, toStockItemId: destination, quantity: "0.125",
|
|
createdAt: "2026-11-14T00:00:00.000Z",
|
|
};
|
|
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: ["inventory.read", "inventory.manage"] });
|
|
if (url.includes("/inventory/warehouses?")) return json([stock.warehouse, { id: destination, name: "Overflow" }]);
|
|
if (url.endsWith(`/inventory/material-stock-items/${id}`)) return json({ ...stock, onHand: attempts.length ? "1.875" : "2.000" });
|
|
if (url.includes("/ledger?") || url.includes("/material-adjustments?")) return json([]);
|
|
if (url.includes("/material-transfers?")) return json(attempts.length ? [transfer] : []);
|
|
if (url.endsWith("/material-transfers") && options?.method === "POST") {
|
|
attempts.push(JSON.parse(String(options.body)));
|
|
if (attempts.length === 1) throw new Error("Response lost");
|
|
return json(transfer);
|
|
}
|
|
throw new Error(`Unexpected request ${url}`);
|
|
}));
|
|
harness(<MaterialStockPage id={id} />);
|
|
const user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
const select = await screen.findByRole("combobox", { name: /Destination warehouse/ });
|
|
expect(within(select).queryByRole("option", { name: "Main warehouse" })).toBeNull();
|
|
expect(screen.queryByRole("button", { name: "Record stock adjustment" })).toBeNull();
|
|
await user.selectOptions(select, destination);
|
|
await user.type(screen.getByRole("textbox", { name: /Quantity to transfer/ }), "0.125");
|
|
await user.click(screen.getByRole("button", { name: "Transfer material" }));
|
|
await user.click(await screen.findByRole("button", { name: "Retry material transfer" }));
|
|
await screen.findByText(/On hand 1.875 GRAM/);
|
|
expect(screen.getByRole("link", { name: "Open destination ledger" }).getAttribute("href")).toBe(`/admin/material-stock/${destination}`);
|
|
expect(attempts).toEqual([
|
|
{ materialId: id, fromWarehouseId: id, toWarehouseId: destination, quantity: "0.125", idempotencyKey: expect.any(String) },
|
|
attempts[0],
|
|
]);
|
|
});
|
|
|
|
test("positive adjustments can create a warehouse balance and link to its ledger", async () => {
|
|
let body: 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: ["inventory.read", "inventory.adjust"] });
|
|
if (url.includes("/inventory/warehouses?")) return json([{ id, name: "Main warehouse" }]);
|
|
if (url.endsWith("/material-adjustments") && options?.method === "POST") {
|
|
body = JSON.parse(String(options.body));
|
|
return json({
|
|
id, materialId: id, warehouseId: id, stockItemId: id, delta: "0.125", reason: "Cycle count",
|
|
createdAt: "2026-11-14T00:00:00.000Z",
|
|
});
|
|
}
|
|
throw new Error(`Unexpected request ${url}`);
|
|
}));
|
|
harness(<MaterialStockPage adjust id={id} />);
|
|
const user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
await user.selectOptions(await screen.findByRole("combobox", { name: /Warehouse/ }), id);
|
|
await user.type(screen.getByRole("textbox", { name: /Quantity change/ }), "0.125");
|
|
await user.type(screen.getByRole("textbox", { name: /Adjustment reason/ }), "Cycle count");
|
|
await user.click(screen.getByRole("button", { name: "Record stock adjustment" }));
|
|
const link = await screen.findByRole("link", { name: "Open adjusted stock ledger" });
|
|
expect(link.getAttribute("href")).toBe(`/admin/material-stock/${id}`);
|
|
expect(body).toEqual({ materialId: id, warehouseId: id, delta: "0.125", reason: "Cycle count", idempotencyKey: expect.any(String) });
|
|
});
|
|
|
|
test("recording a material rate refreshes the selected currency history", async () => {
|
|
let body: unknown;
|
|
let finish: (() => void) | undefined;
|
|
const rate = { id, materialId: id, currency: "USD", revision: 1, unitCost: "0.125", createdAt: "2026-11-14T00:00:00.000Z" };
|
|
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: ["cost.read", "cost.manage"] });
|
|
if (url.endsWith(`/materials/${id}/cost-rates`) && options?.method === "POST") {
|
|
body = JSON.parse(String(options.body));
|
|
return new Promise<Response>((resolve) => { finish = () => resolve(json(rate)); });
|
|
}
|
|
if (url.includes(`/materials/${id}/cost-rates?`)) return json(body && url.includes("currency=USD") ? [rate] : []);
|
|
throw new Error(`Unexpected request ${url}`);
|
|
}));
|
|
harness(<MaterialCostRatesPage materialId={id} />);
|
|
const user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
const currency = await screen.findByRole("combobox", { name: /Rate currency/ });
|
|
await user.selectOptions(currency, "USD");
|
|
await user.type(screen.getByRole("textbox", { name: /Unit cost in USD/ }), "0.1250");
|
|
await user.click(screen.getByRole("button", { name: "Record standard cost rate" }));
|
|
await waitFor(() => expect(finish).toBeDefined());
|
|
expect(currency.matches(":disabled")).toBe(true);
|
|
await act(async () => { finish?.(); });
|
|
await screen.findByRole("cell", { name: "USD 0.125" });
|
|
expect(body).toEqual({ currency: "USD", unitCost: "0.1250" });
|
|
await user.selectOptions(currency, "INR");
|
|
await waitFor(() => expect(screen.queryByRole("cell", { name: "USD 0.125" })).toBeNull());
|
|
});
|
|
|
|
test("a batch cost snapshot retries in the original currency and displays the saved totals", async () => {
|
|
const attempts: unknown[] = [];
|
|
const snapshot = {
|
|
id, batchId: id, currency: "USD", goodQuantity: 10, createdAt: "2026-11-14T00:00:00.000Z",
|
|
productionTotal: "12.34", packagingTotal: "0.66", total: "13.00",
|
|
lines: [{
|
|
kind: "PRODUCTION", bomLineId: id, materialId: id, materialCode: "WAX", materialName: "Wax", unit: "GRAM",
|
|
rateId: id, rateRevision: 2, unitCost: "0.1234", usedQuantity: "100.000", wastedQuantity: "0.000", lineCost: "12.34",
|
|
}],
|
|
};
|
|
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: ["cost.read", "cost.manage"] });
|
|
if (!url.endsWith(`/production-batches/${id}/cost-snapshot`)) throw new Error(`Unexpected request ${url}`);
|
|
if (options?.method !== "POST") return attempts.length ? json(snapshot) : json({ code: "BATCH_COST_NOT_FOUND" }, 404);
|
|
attempts.push(JSON.parse(String(options.body)));
|
|
if (attempts.length === 1) throw new Error("Response lost");
|
|
return json(snapshot);
|
|
}));
|
|
function AuthorizedSnapshot() {
|
|
return usePlatform().can("cost.read") ? <BatchCostSnapshot batchId={id} goodQuantity={10} /> : null;
|
|
}
|
|
harness(<AuthorizedSnapshot />);
|
|
const user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
await user.selectOptions(await screen.findByRole("combobox", { name: /Snapshot currency/ }), "USD");
|
|
await user.click(screen.getByRole("button", { name: "Create cost snapshot" }));
|
|
await user.click(await screen.findByRole("button", { name: "Retry cost snapshot" }));
|
|
await screen.findByText("USD 13.00");
|
|
expect(attempts).toHaveLength(2);
|
|
expect(attempts[0]).toEqual({ currency: "USD", idempotencyKey: expect.any(String) });
|
|
expect(attempts[1]).toEqual(attempts[0]);
|
|
expect(screen.getByRole("cell", { name: "USD 0.1234" })).toBeTruthy();
|
|
expect(screen.queryByRole("button", { name: "Create cost snapshot" })).toBeNull();
|
|
});
|
|
|
|
test("completed production posts both material debits before receiving good pieces and retries with the same key", async () => {
|
|
const date = "2026-11-14T00:00:00.000Z";
|
|
const labelId = "d66c798a-f764-4b88-8d13-ace328ff1011";
|
|
const wax = { id, materialId: id, materialName: "Wax", materialCode: "WAX", unit: "GRAM", quantity: "1" };
|
|
const label = { id: labelId, materialId: labelId, materialName: "Label", materialCode: "LABEL", unit: "PIECE", quantity: "1" };
|
|
const bom = { id, variantId: id, kind: "PRODUCTION", status: "ACTIVE", revision: 1, outputQuantity: 1, activatedAt: date };
|
|
const batch = batchDetail.parse({
|
|
id, bom, reference: "BATCH-20", plannedQuantity: 20, status: "COMPLETED", scheduledDate: null, startedAt: date,
|
|
plannedMaterials: [{ ...wax, plannedQuantity: "20.000" }], cancellation: null,
|
|
completion: { goodQuantity: 18, rejectedQuantity: 2, rejectionReason: "Defects", createdAt: date },
|
|
});
|
|
const base = { id, batchId: id, createdAt: date, warehouseId: id };
|
|
const expected = {
|
|
packaging: { ...base, bomId: labelId, lines: [{ ...label, bomLineId: labelId, plannedQuantity: "18.000", usedQuantity: "18.000", wastedQuantity: "0.000", varianceQuantity: "0.000", wasteReason: null }] },
|
|
"material-stock-posting": { ...base, entries: [{ id, materialId: id, stockItemId: id, kind: "PRODUCTION_CONSUMED", delta: "-20.000" }] },
|
|
"packaging-stock-posting": { ...base, entries: [{ id, materialId: labelId, stockItemId: labelId, kind: "PACKAGING_USED", delta: "-18.000" }] },
|
|
"finished-goods-receipt": { ...base, stockItemId: id, variantId: id, ledgerEntryId: id, quantity: 18 },
|
|
};
|
|
const missing = {
|
|
packaging: "PACKAGING_RUN_NOT_FOUND",
|
|
"material-stock-posting": "PRODUCTION_STOCK_POSTING_NOT_FOUND",
|
|
"packaging-stock-posting": "PACKAGING_STOCK_POSTING_NOT_FOUND",
|
|
"finished-goods-receipt": "FINISHED_GOODS_RECEIPT_NOT_FOUND",
|
|
};
|
|
const saved = new Set<string>();
|
|
const attempts: { step: string; body: 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: [
|
|
"production.read", "packaging.read", "packaging.record", "inventory.read", "inventory.manage",
|
|
] });
|
|
if (url.endsWith("/packaging-boms/active")) return json({ ...bom, id: labelId, kind: "PACKAGING", lines: [label] });
|
|
if (url.includes("/inventory/warehouses?")) return json([{ id, name: "Main warehouse" }]);
|
|
const step = url.split("/").at(-1) as keyof typeof expected;
|
|
if (!Object.hasOwn(expected, step)) throw new Error(`Unexpected request ${url}`);
|
|
if (options?.method !== "POST") return saved.has(step) ? json(expected[step]) : json({ code: missing[step] }, 404);
|
|
attempts.push({ step, body: JSON.parse(String(options.body)) });
|
|
if (step === "finished-goods-receipt" && !saved.has(step)) {
|
|
saved.add(step);
|
|
throw new Error("Response lost");
|
|
}
|
|
saved.add(step);
|
|
return json(expected[step]);
|
|
}));
|
|
function AuthorizedOperations() {
|
|
return usePlatform().can("production.read") ? <CompletedBatchOperations batch={batch} /> : null;
|
|
}
|
|
harness(<AuthorizedOperations />);
|
|
const user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
await screen.findByText("Post production and packaging material stock before receiving finished goods.");
|
|
expect(screen.queryByRole("button", { name: "Receive finished goods" })).toBeNull();
|
|
await user.type(await screen.findByRole("textbox", { name: /Used quantity for Label/ }), "18.000");
|
|
await user.click(screen.getByRole("button", { name: "Record packaging run" }));
|
|
for (const action of ["Post production material", "Post packaging material", "Receive finished goods"]) {
|
|
const form = within(await screen.findByRole("form", { name: action }));
|
|
await user.selectOptions(form.getByRole("combobox", { name: /Warehouse/ }), id);
|
|
await user.click(form.getByRole("button", { name: action }));
|
|
}
|
|
await user.click(await screen.findByRole("button", { name: "Retry receive finished goods" }));
|
|
await screen.findByText(/Received 18 pieces into warehouse/);
|
|
expect(attempts.map(({ step }) => step)).toEqual(["packaging", "material-stock-posting", "packaging-stock-posting", "finished-goods-receipt", "finished-goods-receipt"]);
|
|
expect(attempts[0].body).toEqual({
|
|
bomId: labelId, idempotencyKey: expect.any(String),
|
|
lines: [{ bomLineId: labelId, usedQuantity: "18.000", wastedQuantity: "0.000" }],
|
|
});
|
|
expect(attempts[3].body).toEqual({ warehouseId: id, idempotencyKey: expect.any(String) });
|
|
expect(attempts[4]).toEqual(attempts[3]);
|
|
});
|
|
|
|
test("a production batch starts, safely retries usage and completes with reconciled output", async () => {
|
|
const date = "2026-11-12T00:00:00.000Z";
|
|
let status = "DRAFT";
|
|
let completion: unknown = null;
|
|
const attempts: unknown[] = [];
|
|
const plannedMaterial = { id, materialId: id, materialName: "Wax", materialCode: "WAX", unit: "GRAM", quantity: "100", plannedQuantity: "200.000" };
|
|
const event = { id, bomLineId: id, kind: "WASTED", quantity: "0.125", reason: "Spill", createdAt: date };
|
|
const batch = () => ({
|
|
id, reference: "BATCH-20", plannedQuantity: 20, status, scheduledDate: null,
|
|
startedAt: status === "DRAFT" ? null : date,
|
|
bom: { id, variantId: id, kind: "PRODUCTION", revision: 2, status: "ACTIVE", outputQuantity: 10, activatedAt: date },
|
|
plannedMaterials: [plannedMaterial], completion, cancellation: null,
|
|
});
|
|
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: ["production.read", "production.manage", "production.material.record"],
|
|
});
|
|
if (url.endsWith(`/production-batches/${id}`)) return json(batch());
|
|
if (url.endsWith("/start") && options?.method === "POST") {
|
|
status = "IN_PROGRESS";
|
|
return json(batch());
|
|
}
|
|
if (url.endsWith("/material-usage") && options?.method === "POST") {
|
|
attempts.push(JSON.parse(String(options.body)));
|
|
if (attempts.length === 1) throw new Error("Response lost");
|
|
return json(event);
|
|
}
|
|
if (url.includes("/material-usage?")) return json({
|
|
total: attempts.length ? 1 : 0,
|
|
events: attempts.length ? [event] : [],
|
|
materials: [{
|
|
...plannedMaterial, bomLineId: id, consumedQuantity: "0.000",
|
|
wastedQuantity: attempts.length ? "0.125" : "0.000", varianceQuantity: attempts.length ? "199.875" : "200.000",
|
|
}],
|
|
});
|
|
if (url.endsWith("/complete") && options?.method === "POST") {
|
|
const body = JSON.parse(String(options.body));
|
|
completion = { ...body, createdAt: date };
|
|
status = "COMPLETED";
|
|
return json(batch());
|
|
}
|
|
throw new Error(`Unexpected request ${url}`);
|
|
}));
|
|
harness(<ProductionBatchesPage batchId={id} />);
|
|
const user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
await user.click(await screen.findByRole("button", { name: "Start batch" }));
|
|
await user.click(screen.getByRole("button", { name: "Confirm" }));
|
|
await user.selectOptions(await screen.findByRole("combobox", { name: /Usage type/ }), "WASTED");
|
|
await user.type(screen.getByRole("textbox", { name: /Actual quantity/ }), "0.125");
|
|
await user.type(screen.getByRole("textbox", { name: /Usage reason/ }), "Spill");
|
|
await user.click(screen.getByRole("button", { name: "Record material usage" }));
|
|
await user.click(await screen.findByRole("button", { name: "Retry material usage" }));
|
|
await screen.findByRole("cell", { name: "199.875" });
|
|
expect(attempts).toHaveLength(2);
|
|
expect(attempts[0]).toEqual({ bomLineId: id, kind: "WASTED", quantity: "0.125", reason: "Spill", idempotencyKey: expect.any(String) });
|
|
expect(attempts[1]).toEqual(attempts[0]);
|
|
await user.type(screen.getByRole("spinbutton", { name: /Good pieces/ }), "18");
|
|
const rejected = screen.getByRole("spinbutton", { name: /Rejected pieces/ });
|
|
await user.clear(rejected);
|
|
await user.type(rejected, "2");
|
|
await user.type(screen.getByRole("textbox", { name: /Rejection reason/ }), "Surface defects");
|
|
await user.click(screen.getByRole("button", { name: "Complete batch" }));
|
|
await screen.findByText(/18 good · 2 rejected · Surface defects/);
|
|
expect(screen.queryByRole("button", { name: "Record material usage" })).toBeNull();
|
|
});
|
|
|
|
test("packaging staff draft and activate an independent BOM with eligible materials", async () => {
|
|
const draftId = "d66c798a-f764-4b88-8d13-ace328ff1011";
|
|
const draft = {
|
|
id: draftId, variantId: id, kind: "PACKAGING", status: "DRAFT", revision: 2,
|
|
outputQuantity: 10, activatedAt: null,
|
|
lines: [{ id, materialId: id, materialName: "Label", materialCode: "LABEL", unit: "PIECE", quantity: "10" }],
|
|
};
|
|
const first = { ...draft, id, revision: 1, status: "ACTIVE", activatedAt: "2026-11-12T00:00:00.000Z" };
|
|
let created = false;
|
|
let activated = false;
|
|
let draftBody: unknown;
|
|
const 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: ["packaging.read", "packaging.manage", "procurement.read"] });
|
|
if (url.includes("/materials?")) return json([
|
|
{ id, name: "Label", code: "LABEL", kind: "LABEL", unit: "PIECE", active: true },
|
|
{ id: draftId, name: "Wax", code: "WAX", kind: "WAX", unit: "GRAM", active: true },
|
|
]);
|
|
const current = activated ? { ...draft, status: "ACTIVE", activatedAt: first.activatedAt } : draft;
|
|
if (url.includes(`/variants/${id}/packaging-boms?`))
|
|
return json(created ? [current, { ...first, status: activated ? "SUPERSEDED" : "ACTIVE" }] : [first]);
|
|
if (url.endsWith(`/variants/${id}/packaging-boms`) && options?.method === "POST") {
|
|
draftBody = JSON.parse(String(options.body));
|
|
created = true;
|
|
return json(draft);
|
|
}
|
|
if (url.endsWith(`/packaging-boms/${draftId}`)) return json(current);
|
|
if (url.endsWith(`/packaging-boms/${draftId}/activate`) && options?.method === "POST") {
|
|
activated = true;
|
|
return json({ ...draft, status: "ACTIVE", activatedAt: first.activatedAt });
|
|
}
|
|
throw new Error(`Unexpected request ${url}`);
|
|
});
|
|
vi.stubGlobal("fetch", fetch);
|
|
harness(<BomPage variantId={id} packaging />);
|
|
expect(fetch).not.toHaveBeenCalled();
|
|
const user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
await user.click(await screen.findByRole("button", { name: "Add Label" }));
|
|
expect(screen.queryByRole("button", { name: "Add Wax" })).toBeNull();
|
|
await user.type(screen.getByRole("spinbutton", { name: /Finished pieces/ }), "10");
|
|
await user.type(screen.getByRole("textbox", { name: /Quantity for Label/ }), "10.000");
|
|
await user.click(screen.getByRole("button", { name: "Create draft revision" }));
|
|
await user.click(await screen.findByRole("button", { name: "Activate revision 2" }));
|
|
await user.click(screen.getByRole("button", { name: "Confirm" }));
|
|
await screen.findByText("ACTIVE · Yields 10 finished pieces");
|
|
await screen.findByRole("cell", { name: "SUPERSEDED" });
|
|
expect(draftBody).toEqual({ outputQuantity: 10, lines: [{ materialId: id, quantity: "10.000" }] });
|
|
expect(screen.queryByRole("link", { name: "Production BOMs" })).toBeNull();
|
|
expect(fetch.mock.calls.some(([url]) => url.includes(`/variants/${id}/boms`))).toBe(false);
|
|
});
|
|
|
|
test("production BOM observers can review a draft without seeing write controls", async () => {
|
|
const revision = {
|
|
id, variantId: id, kind: "PRODUCTION", status: "DRAFT", revision: 1,
|
|
outputQuantity: 1, activatedAt: null,
|
|
};
|
|
const fetch = vi.fn(async (url: string) => {
|
|
if (url.endsWith("/auth/login")) return json(session);
|
|
if (url.endsWith("/auth/me")) return json({ ...me, permissions: ["bom.read"] });
|
|
if (url.includes(`/variants/${id}/boms?`)) return json([revision]);
|
|
if (url.endsWith(`/boms/${id}`)) return json({
|
|
...revision, lines: [{ id, materialId: id, materialName: "Wax", materialCode: "WAX", unit: "GRAM", quantity: "125.5" }],
|
|
});
|
|
throw new Error(`Unexpected request ${url}`);
|
|
});
|
|
vi.stubGlobal("fetch", fetch);
|
|
harness(<BomPage variantId={id} />);
|
|
const user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
await user.click(await screen.findByRole("button", { name: "View revision 1" }));
|
|
await screen.findByRole("cell", { name: "125.5" });
|
|
expect(screen.queryByRole("button", { name: "Create draft revision" })).toBeNull();
|
|
expect(screen.queryByRole("button", { name: "Activate revision 1" })).toBeNull();
|
|
expect(fetch.mock.calls.some(([url]) => url.includes("/materials"))).toBe(false);
|
|
});
|
|
|
|
test("supplier document reviewer sees only permitted actions for their own upload", async () => {
|
|
const version = {
|
|
id, uploadedById: id, version: 1, filename: "certificate.pdf", mimeType: "application/pdf",
|
|
size: 20, createdAt: "2026-11-12T00:00:00.000Z", decision: null,
|
|
};
|
|
const record = { id, code: "TAX-CERT", kind: "TAX_CERTIFICATE", title: "Certificate" };
|
|
const fetch = vi.fn(async (url: string) => {
|
|
if (url.endsWith("/auth/login")) return json(session);
|
|
if (url.endsWith("/auth/me")) return json({ ...me, permissions: ["supplier_document.read", "supplier_document.validate"] });
|
|
if (url.includes("/documents?")) return json([record]);
|
|
if (url.endsWith(`/supplier-documents/${id}`)) return json({ ...record, versions: [version] });
|
|
throw new Error(`Unexpected request ${url}`);
|
|
});
|
|
vi.stubGlobal("fetch", fetch);
|
|
harness(<SupplierDocumentsPage supplierId={id} />);
|
|
expect(fetch).not.toHaveBeenCalled();
|
|
const user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
await user.click(await screen.findByRole("button", { name: "Open TAX-CERT" }));
|
|
await user.click(await screen.findByRole("button", { name: "View version 1" }));
|
|
await screen.findByText("Another reviewer must decide on this version.");
|
|
expect(screen.getByRole("button", { name: "Download PDF" })).toBeTruthy();
|
|
expect(screen.queryByRole("button", { name: "Save review decision" })).toBeNull();
|
|
expect(screen.queryByRole("button", { name: "Upload PDF version" })).toBeNull();
|
|
});
|
|
|
|
test("supplier payment retry preserves the payment payload and refreshes the balance", async () => {
|
|
const attempts: unknown[] = [];
|
|
const record = {
|
|
id, invoiceNumber: "INV/42", invoiceDate: "2026-11-12T00:00:00.000Z",
|
|
currency: "INR", merchandiseTotal: "10", taxAmount: "0", shippingAmount: "0",
|
|
payableTotal: "10", void: null, lines: [],
|
|
};
|
|
const payment = {
|
|
id, reference: "BANK/42", method: "BANK_TRANSFER", amount: "10", currency: "INR",
|
|
paidAt: record.invoiceDate, reversal: null,
|
|
};
|
|
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: ["procurement.read", "supplier_payment.manage"] });
|
|
if (url.includes("/invoices?")) return json([record]);
|
|
if (url.endsWith(`/supplier-invoices/${id}`)) return json(record);
|
|
if (url.endsWith("/payments") && options?.method === "POST") {
|
|
attempts.push(JSON.parse(String(options.body)));
|
|
if (attempts.length === 1) throw new Error("Response lost");
|
|
return json(payment);
|
|
}
|
|
if (url.includes("/payments?")) return json({
|
|
currency: "INR", payableTotal: "10.00",
|
|
paidTotal: attempts.length ? "10.00" : "0.00",
|
|
outstandingTotal: attempts.length ? "0.00" : "10.00",
|
|
payments: attempts.length ? [payment] : [],
|
|
});
|
|
throw new Error(`Unexpected request ${url}`);
|
|
}));
|
|
function AuthorizedInvoices() {
|
|
const { can } = usePlatform();
|
|
return can("procurement.read") ? <PurchaseOrderInvoices order={{
|
|
id, reference: "PO-42", status: "ISSUED", supplier: { id, name: "Supplier" },
|
|
currency: "INR", expectedDeliveryAt: null, merchandiseTotal: "10", lines: [],
|
|
}} /> : null;
|
|
}
|
|
harness(<AuthorizedInvoices />);
|
|
const user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
await user.click(await screen.findByRole("button", { name: "View invoice INV/42" }));
|
|
await user.type(await screen.findByRole("textbox", { name: /Payment reference/ }), "bank/42");
|
|
await user.type(screen.getByRole("textbox", { name: /Payment amount/ }), "10.00");
|
|
await user.type(screen.getByRole("textbox", { name: /Payment date/ }), "2026-11-12");
|
|
await user.click(screen.getByRole("button", { name: "Record supplier payment" }));
|
|
await user.click(await screen.findByRole("button", { name: "Retry supplier payment record" }));
|
|
await screen.findByText("Paid INR 10.00 · Outstanding INR 0.00");
|
|
expect(attempts).toHaveLength(2);
|
|
expect(attempts[1]).toEqual(attempts[0]);
|
|
expect(screen.queryByRole("button", { name: "Record supplier invoice" })).toBeNull();
|
|
});
|
|
|
|
test("receipt posting retries the same warehouse and key after a lost response", async () => {
|
|
const attempts: unknown[] = [];
|
|
const posting = {
|
|
id, receiptId: id, warehouseId: id, createdAt: "2026-11-12T00:00:00.000Z",
|
|
entries: [{ id, stockItemId: id, receiptLineId: id, kind: "RECEIPT_ACCEPTED", delta: "0.125" }],
|
|
};
|
|
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: ["inventory.read", "inventory.manage"] });
|
|
if (url.includes("/inventory/warehouses?")) return json([{ id, name: "Main warehouse" }]);
|
|
if (url.endsWith("/stock-posting")) {
|
|
if (options?.method === "POST") {
|
|
attempts.push(JSON.parse(String(options.body)));
|
|
if (attempts.length === 1) throw new Error("Response lost");
|
|
return json(posting);
|
|
}
|
|
return attempts.length ? json(posting) : json({ code: "MATERIAL_POSTING_NOT_FOUND" }, 404);
|
|
}
|
|
throw new Error(`Unexpected request ${url}`);
|
|
}));
|
|
function AuthorizedPosting() {
|
|
const { can } = usePlatform();
|
|
return can("inventory.read") ? <ReceiptStockPosting receiptId={id} lineNames={new Map([[id, "Wax"]])} /> : null;
|
|
}
|
|
harness(<AuthorizedPosting />);
|
|
const user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
await user.selectOptions(await screen.findByRole("combobox", { name: "Destination warehouse" }), id);
|
|
await user.click(screen.getByRole("button", { name: "Post accepted material" }));
|
|
await user.click(await screen.findByRole("button", { name: "Retry warehouse posting" }));
|
|
const ledger = await screen.findByRole("link", { name: "View stock ledger" });
|
|
expect(ledger.getAttribute("href")).toBe(`/admin/material-stock/${id}`);
|
|
expect(attempts).toHaveLength(2);
|
|
expect(attempts[0]).toEqual({ warehouseId: id, idempotencyKey: expect.any(String) });
|
|
expect(attempts[1]).toEqual(attempts[0]);
|
|
expect(screen.getByText("0.125")).toBeTruthy();
|
|
});
|
|
|
|
test("uncertain checkout replays identical input after the cart version changes", async () => {
|
|
const attempts: unknown[] = [];
|
|
let cartChanged = false;
|
|
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);
|
|
if (url.endsWith("/addresses")) return json([address]);
|
|
if (url.endsWith("/cart"))
|
|
return json({
|
|
version: cartChanged ? 1 : 0,
|
|
lines: cartChanged ? [] : [line],
|
|
});
|
|
if (url.endsWith("/checkout")) {
|
|
attempts.push(JSON.parse(String(options?.body)));
|
|
cartChanged = true;
|
|
if (attempts.length === 1) throw new Error("Response lost");
|
|
return json(order);
|
|
}
|
|
if (url.includes("/orders?")) return json([]);
|
|
if (url.includes(`/orders/${id}`)) return json(order);
|
|
throw new Error(`Unexpected ${url}`);
|
|
}),
|
|
);
|
|
history.replaceState(null, "", "/cart");
|
|
const h = harness(
|
|
<Switch>
|
|
<Route path="/cart" component={CartPage} />
|
|
<Route path="/orders">{() => <OrdersPage />}</Route>
|
|
<Route path="/orders/:id">
|
|
{(params) => <OrdersPage id={params.id} />}
|
|
</Route>
|
|
</Switch>,
|
|
),
|
|
user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
await screen.findByText("Test candle · Small");
|
|
await user.click(screen.getByRole("combobox", { name: "Delivery address" }));
|
|
await user.click(await screen.findByRole("option"));
|
|
await user.click(screen.getByRole("button", { name: "Review checkout" }));
|
|
await user.click(screen.getByRole("button", { name: "Confirm order" }));
|
|
await screen.findByRole("button", { name: "Retry original checkout" });
|
|
await act(() => h.client.invalidateQueries({ queryKey: ["private"] }));
|
|
await screen.findByText(/Your cart is empty/);
|
|
await user.click(screen.getByRole("link", { name: "Check orders" }));
|
|
await screen.findByText("Order history");
|
|
await user.click(screen.getByRole("link", { name: "My cart" }));
|
|
await user.click(
|
|
screen.getByRole("button", { name: "Retry original checkout" }),
|
|
);
|
|
await waitFor(() => expect(attempts).toHaveLength(2));
|
|
expect(attempts[1]).toEqual(attempts[0]);
|
|
expect(attempts[0]).toMatchObject({ cartVersion: 0, addressId: id });
|
|
await waitFor(() => expect(location.pathname).toBe(`/orders/${id}`));
|
|
});
|
|
|
|
test("a changed cart invalidates checkout review instead of adopting a new version", async () => {
|
|
let changed = 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);
|
|
if (url.endsWith("/addresses")) return json([address]);
|
|
if (url.endsWith("/cart"))
|
|
return json({
|
|
version: changed ? 2 : 0,
|
|
lines: [{ ...line, quantity: changed ? 3 : 1 }],
|
|
});
|
|
attempts.push(options?.body);
|
|
return json(order);
|
|
}),
|
|
);
|
|
const h = harness(<CartPage />),
|
|
user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
await screen.findByText("Test candle · Small");
|
|
await user.click(screen.getByRole("combobox", { name: "Delivery address" }));
|
|
await user.click(await screen.findByRole("option"));
|
|
await user.click(screen.getByRole("button", { name: "Review checkout" }));
|
|
changed = true;
|
|
await act(() => h.client.invalidateQueries({ queryKey: ["private"] }));
|
|
await screen.findByText(/Review the updated quantities/);
|
|
expect(screen.queryByRole("button", { name: "Confirm order" })).toBeNull();
|
|
expect(attempts).toEqual([]);
|
|
});
|
|
test("permission-denied administration never fetches private staff records", async () => {
|
|
const fetch = vi.fn(async (url: string) =>
|
|
url.endsWith("/auth/login")
|
|
? json(session)
|
|
: url.endsWith("/auth/me")
|
|
? json(me)
|
|
: Promise.reject(new Error("Private records must not be fetched")),
|
|
);
|
|
vi.stubGlobal("fetch", fetch);
|
|
const h = harness(<AccessPage />),
|
|
user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
await screen.findByText(/does not have permission/);
|
|
expect(fetch.mock.calls.some(([url]) => url.includes("/users"))).toBe(false);
|
|
const result = await axe.run(h.container, {
|
|
rules: { "color-contrast": { enabled: false } },
|
|
});
|
|
expect(
|
|
result.violations.filter(
|
|
(v) => v.impact === "serious" || v.impact === "critical",
|
|
),
|
|
).toEqual([]);
|
|
});
|
|
test("unfinalized order charges are never shown as zero or payable", async () => {
|
|
vi.stubGlobal(
|
|
"fetch",
|
|
vi.fn(async (url: string) =>
|
|
url.endsWith("/auth/login")
|
|
? json(session)
|
|
: url.endsWith("/auth/me")
|
|
? json(me)
|
|
: json(order),
|
|
),
|
|
);
|
|
harness(<OrdersPage id={id} />);
|
|
const user = userEvent.setup();
|
|
await user.click(screen.getByText("Test login"));
|
|
await screen.findByText(/Order .*PENDING_PAYMENT/);
|
|
expect(screen.getAllByText("Unfinalized")).toHaveLength(3);
|
|
expect(screen.queryByRole("button", { name: /pay now/i })).toBeNull();
|
|
expect(screen.getByText(/Payment collection is unavailable/)).toBeTruthy();
|
|
});
|