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 { 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[]) => ( [ id, 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(); 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(); 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 ( ); } function harness(children: ReactNode) { localStorage.setItem("mani.organization", id); const client = new QueryClient({ defaultOptions: { queries: { retry: false } }, }); const result = render( {children} , ); 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(); 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(); const user = userEvent.setup(); await user.click(screen.getByText("Test login")); await user.selectOptions(await screen.findByRole("combobox", { name: /Review outcome/ }), "APPROVED"); await user.type(screen.getByRole("textbox", { name: /Review note/ }), "Details checked"); await user.click(screen.getByRole("button", { name: "Record verification decision" })); await user.click(await screen.findByRole("button", { name: "Retry verification decision" })); await screen.findByText(/Business STUDIO · VERIFIED/); expect(await screen.findByRole("cell", { name: "Details checked" })).toBeTruthy(); expect(attempts).toHaveLength(2); expect(attempts[0]).toEqual({ decision: "APPROVED", note: "Details checked", idempotencyKey: expect.any(String) }); expect(attempts[1]).toEqual(attempts[0]); }); test("material transfers exclude the source warehouse and retry with the same key", async () => { 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(); 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(); 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((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(); 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") ? : null; } harness(); 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(); 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") ? : null; } harness(); 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(); 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(); 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(); 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(); 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") ? : null; } harness(); 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") ? : null; } harness(); 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( {() => } {(params) => } , ), 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(), 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(), 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(); 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(); });