import { render, screen, waitFor, fireEvent } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import * as XLSX from "xlsx"; import { describe, it, expect, vi, beforeEach } from "vitest"; // vi.hoisted ensures mocks are hoisted above module imports so vi.mock factory // can reference them. Pattern mirrors app/components/warehouses/WarehouseFormDialog.test.tsx. const mocks = vi.hoisted(() => ({ postStockIn: vi.fn(), getProductVariations: vi.fn(), listAdminWarehouses: vi.fn(), listProducts: vi.fn(), getSkuCatalog: vi.fn(), buildStockInWorkbook: vi.fn(), parseStockInWorkbook: vi.fn(), })); vi.mock("@/app/lib/services/adminStock", () => ({ postStockIn: mocks.postStockIn, getProductVariations: mocks.getProductVariations, getSkuCatalog: mocks.getSkuCatalog, })); vi.mock("@/app/lib/services/adminWarehouses", () => ({ listAdminWarehouses: mocks.listAdminWarehouses, })); vi.mock("@/app/lib/services/adminProduct", () => ({ listProducts: mocks.listProducts, })); vi.mock("@/app/lib/inventory/stockInWorkbook", () => ({ buildStockInWorkbook: mocks.buildStockInWorkbook, parseStockInWorkbook: mocks.parseStockInWorkbook, })); // xlsx is used directly in the form's import handler. Mock it so tests do not // need a real xlsx binary and XLSX.read does not try to parse dummy file bytes. vi.mock("xlsx", () => ({ SSF: {}, read: vi.fn().mockReturnValue({ SheetNames: ["Stock In"], Sheets: { "Stock In": {} }, }), utils: { sheet_to_json: vi.fn().mockReturnValue([]), book_new: vi.fn().mockReturnValue({}), aoa_to_sheet: vi.fn().mockReturnValue({}), book_append_sheet: vi.fn(), write: vi.fn().mockReturnValue(new Uint8Array([0])), }, })); import { StockInForm } from "./StockInForm"; // ─── fixture data ──────────────────────────────────────────────────────────── const MASTER_WAREHOUSE = { id: 11, code: "MYB-M", name: "MYB-Master Store", type: "M", parentId: null, status: "Y", }; const OTHER_WAREHOUSE = { id: 10, code: "MYB-W", name: "MYB-HQ", type: "W", parentId: null, status: "Y", }; const PRODUCTS = [ { id: "1001", productCode: "P001", productName: "Baby Milk", productStatus: "Y" }, { id: "1002", productCode: "P002", productName: "Baby Lotion", productStatus: "Y" }, ]; const VARIATIONS = [ { skuVariationId: "SV-001", variationId: "V-001", label: "100g" }, { skuVariationId: "SV-002", variationId: "V-002", label: "250g" }, ]; // ─── setup ─────────────────────────────────────────────────────────────────── beforeEach(() => { mocks.postStockIn.mockReset(); mocks.getProductVariations.mockReset(); mocks.listAdminWarehouses.mockReset(); mocks.listProducts.mockReset(); mocks.getSkuCatalog.mockReset(); mocks.buildStockInWorkbook.mockReset(); mocks.parseStockInWorkbook.mockReset(); mocks.listAdminWarehouses.mockResolvedValue([OTHER_WAREHOUSE, MASTER_WAREHOUSE]); mocks.listProducts.mockResolvedValue({ items: PRODUCTS, total: 2 }); mocks.getProductVariations.mockResolvedValue(VARIATIONS); // Default: parseStockInWorkbook returns empty result (overridden per test). mocks.parseStockInWorkbook.mockReturnValue({ lines: [], errors: [] }); }); // ─── helpers ───────────────────────────────────────────────────────────────── /** Wait for initial data to load: Destination combobox (select) renders. */ async function waitForLoad() { await screen.findByRole("combobox", { name: /destination/i }); } /** Open the product picker for the first line and select the given product name. */ async function pickProduct(user: ReturnType, productName: string) { // The trigger button has aria-label="Product" and role="combobox". await user.click(screen.getByRole("combobox", { name: /^product$/i })); // cmdk CommandItem renders its text directly; findByText locates it in the portal. await user.click(await screen.findByText(productName)); } /** Select a variation from the variation Select (Radix). */ async function pickVariation(user: ReturnType, label: string) { // After product pick the variation Select appears (aria-label="Variation"). await user.click(await screen.findByRole("combobox", { name: /^variation$/i })); await user.click(await screen.findByRole("option", { name: label })); } // ─── tests ─────────────────────────────────────────────────────────────────── describe("StockInForm", () => { it("defaults the destination to the type-M warehouse", async () => { render(); await waitForLoad(); // The Destination combobox shows the master store label. const destinationCombobox = screen.getByRole("combobox", { name: /destination/i }); expect(destinationCombobox).toHaveTextContent(/MYB-Master Store/); }); it("submits with the type-M warehouseId, selected skuVariationId, and entered quantity", async () => { const user = userEvent.setup(); mocks.postStockIn.mockResolvedValue({ documentNo: "SI-0001" }); render(); await waitForLoad(); // Pick a product. await pickProduct(user, "Baby Milk"); // Variations fetch fires with the product's id. await waitFor(() => expect(mocks.getProductVariations).toHaveBeenCalledWith("1001"), ); // Pick a variation. await pickVariation(user, "100g"); // Set quantity to 5. const qtyInput = screen.getByRole("spinbutton", { name: /quantity/i }); fireEvent.change(qtyInput, { target: { value: "5" } }); // Submit. await user.click(screen.getByRole("button", { name: /^submit$/i })); await waitFor(() => expect(mocks.postStockIn).toHaveBeenCalledWith({ warehouseId: "11", lines: [ expect.objectContaining({ skuVariationId: "SV-001", quantity: 5, }), ], }), ); // Success message shows the returned documentNo. await screen.findByText(/SI-0001/i); }); it("disables Submit and does not call postStockIn when a product is picked but no variation chosen", async () => { const user = userEvent.setup(); render(); await waitForLoad(); // Pick a product — triggers getProductVariations. await pickProduct(user, "Baby Milk"); await waitFor(() => expect(mocks.getProductVariations).toHaveBeenCalledWith("1001")); // Confirm the variation select has rendered (variations loaded). await screen.findByRole("combobox", { name: /^variation$/i }); // Do NOT pick a variation. Submit must be disabled. const submitBtn = screen.getByRole("button", { name: /^submit$/i }); expect(submitBtn).toBeDisabled(); // Click on a disabled button — postStockIn must not be called. await user.click(submitBtn); expect(mocks.postStockIn).not.toHaveBeenCalled(); }); it("shows an error when listAdminWarehouses fails", async () => { mocks.listAdminWarehouses.mockRejectedValue(new Error("Network error")); render(); await screen.findByRole("alert"); expect(screen.getByRole("alert")).toHaveTextContent(/Failed to load warehouses/i); }); // ─── 8A — destination select ──────────────────────────────────────────────── it("renders a destination select listing all active warehouses as options", async () => { const user = userEvent.setup(); render(); await waitForLoad(); const destinationSelect = screen.getByRole("combobox", { name: /destination/i }); // Open the select to reveal options. await user.click(destinationSelect); // Both active warehouses must appear as options. expect(await screen.findByRole("option", { name: /MYB-Master Store/i })).toBeInTheDocument(); expect(screen.getByRole("option", { name: /MYB-HQ/i })).toBeInTheDocument(); }); it("posts the selected non-default warehouse id when a different warehouse is chosen", async () => { const user = userEvent.setup(); mocks.postStockIn.mockResolvedValue({ documentNo: "SI-0002" }); render(); await waitForLoad(); // Change destination to OTHER_WAREHOUSE (MYB-HQ, id=10). const destinationSelect = screen.getByRole("combobox", { name: /destination/i }); await user.click(destinationSelect); await user.click(await screen.findByRole("option", { name: /MYB-HQ/i })); // Pick product + variation. await pickProduct(user, "Baby Milk"); await waitFor(() => expect(mocks.getProductVariations).toHaveBeenCalledWith("1001")); await pickVariation(user, "100g"); await user.click(screen.getByRole("button", { name: /^submit$/i })); await waitFor(() => expect(mocks.postStockIn).toHaveBeenCalledWith( expect.objectContaining({ warehouseId: "10" }), ), ); }); it("shows the backend error message and does NOT show a success message", async () => { const user = userEvent.setup(); mocks.postStockIn.mockRejectedValue(new Error("Warehouse is closed")); render(); await waitForLoad(); await pickProduct(user, "Baby Milk"); await waitFor(() => expect(mocks.getProductVariations).toHaveBeenCalled()); await pickVariation(user, "100g"); const qtyInput = screen.getByRole("spinbutton", { name: /quantity/i }); fireEvent.change(qtyInput, { target: { value: "3" } }); await user.click(screen.getByRole("button", { name: /^submit$/i })); // Error message appears. await screen.findByText(/Warehouse is closed/i); // Success must NOT appear — error and success are mutually exclusive. expect(screen.queryByText(/SI-/i)).not.toBeInTheDocument(); }); // ─── Task 9 — Excel import + Download template ────────────────────────────── it("renders a 'Download template' button", async () => { render(); await waitForLoad(); expect(screen.getByRole("button", { name: /download template/i })).toBeInTheDocument(); }); it("renders a file input for importing .xlsx files", async () => { render(); await waitForLoad(); // The input is labelled by an aria-label or visible label. const input = screen.getByLabelText(/import stock-in file/i); expect(input).toHaveAttribute("type", "file"); expect(input).toHaveAttribute("accept", ".xlsx"); }); it("Download template calls getSkuCatalog and buildStockInWorkbook", async () => { const user = userEvent.setup(); const catalog = [ { skuVariationId: "100001", skuCode: "BB-001", skuName: "Baby Milk", variation: "100g" }, ]; mocks.getSkuCatalog.mockResolvedValue(catalog); mocks.buildStockInWorkbook.mockReturnValue(new Uint8Array([0, 1, 2])); // jsdom does not implement URL.createObjectURL — stub it. const createObjectURL = vi.fn().mockReturnValue("blob://test"); const revokeObjectURL = vi.fn(); vi.stubGlobal("URL", { ...URL, createObjectURL, revokeObjectURL }); render(); await waitForLoad(); await user.click(screen.getByRole("button", { name: /download template/i })); await waitFor(() => expect(mocks.getSkuCatalog).toHaveBeenCalledOnce()); expect(mocks.buildStockInWorkbook).toHaveBeenCalledWith(catalog); vi.unstubAllGlobals(); }); it("import: parses the uploaded file, populates lines for review — submit becomes enabled", async () => { const user = userEvent.setup(); // parseStockInWorkbook returns one valid line with skuVariationId set. mocks.parseStockInWorkbook.mockReturnValue({ lines: [{ skuVariationId: "SV-001", quantity: 5 }], errors: [], }); render(); await waitForLoad(); const fileInput = screen.getByLabelText(/import stock-in file/i); const file = new File( [new Uint8Array([0, 1, 2])], "stock-in.xlsx", { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }, ); await user.upload(fileInput, file); // After import, the line has skuVariationId → Submit is enabled. await waitFor(() => { expect(mocks.parseStockInWorkbook).toHaveBeenCalledOnce(); expect(screen.getByRole("button", { name: /^submit$/i })).not.toBeDisabled(); }); // cellNF keeps cell formats so readSheetRows can tell date cells from plain numbers. expect(XLSX.read).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ cellNF: true })); }); it("import: a fractional quantity shows as-is and blocks Submit until corrected", async () => { const user = userEvent.setup(); mocks.parseStockInWorkbook.mockReturnValue({ lines: [{ skuVariationId: "SV-001", quantity: 2.5 }], errors: [], }); render(); await waitForLoad(); const file = new File([new Uint8Array([0, 1, 2])], "stock-in.xlsx", { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", }); await user.upload(screen.getByLabelText(/import stock-in file/i), file); const qty = (await screen.findByRole("spinbutton", { name: /quantity/i })) as HTMLInputElement; expect(qty.value).toBe("2.5"); await user.click(screen.getByRole("button", { name: /^submit$/i })); expect(await screen.findByText("Enter a quantity of at least 1.")).toBeInTheDocument(); expect(mocks.postStockIn).not.toHaveBeenCalled(); }); it("import: shows errors in the alert area for malformed rows; does not auto-submit", async () => { const user = userEvent.setup(); mocks.parseStockInWorkbook.mockReturnValue({ lines: [], errors: ["Row 2: missing SKU id", "Row 5: expiry must be YYYY-MM-DD"], }); render(); await waitForLoad(); const fileInput = screen.getByLabelText(/import stock-in file/i); await user.upload(fileInput, new File([new Uint8Array([0])], "bad.xlsx")); await screen.findByRole("alert"); const alert = screen.getByRole("alert"); expect(alert).toHaveTextContent(/Row 2: missing SKU id/); expect(alert).toHaveTextContent(/Row 5: expiry must be YYYY-MM-DD/); // Must NOT auto-submit — postStockIn must not have been called. expect(mocks.postStockIn).not.toHaveBeenCalled(); }); it("import: resets the line editor to one empty line when all parsed rows are blank or errored", async () => { // Fix 2 coverage: importing a file that yields parsedLines=[] must unconditionally // replace the current lines with [emptyLine()] so stale data is never left in the editor. const user = userEvent.setup(); // Step 1: import a valid file to populate lines with a skuVariationId (Submit enabled). mocks.parseStockInWorkbook.mockReturnValue({ lines: [{ skuVariationId: "SV-001", quantity: 5 }], errors: [], }); render(); await waitForLoad(); const fileInput = screen.getByLabelText(/import stock-in file/i); await user.upload( fileInput, new File([new Uint8Array([0, 1, 2])], "good.xlsx", { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", }), ); // After the good import, Submit is enabled (the imported line has a skuVariationId). await waitFor(() => { expect(screen.getByRole("button", { name: /^submit$/i })).not.toBeDisabled(); }); // Step 2: import a file where every row is errored / blank → parsedLines=[]. mocks.parseStockInWorkbook.mockReturnValue({ lines: [], errors: ["Row 2: missing SKU id"], }); await user.upload(fileInput, new File([new Uint8Array([0])], "bad.xlsx")); // Errors must be shown in the alert area. await screen.findByRole("alert"); expect(screen.getByRole("alert")).toHaveTextContent(/Row 2: missing SKU id/); // Editor must be reset — Submit is disabled again because the new empty line // has no skuVariationId. Without the fix (if (parsedLines.length > 0) guard), // the stale lines from the good import would remain and Submit would still be enabled. await waitFor(() => { expect(screen.getByRole("button", { name: /^submit$/i })).toBeDisabled(); }); // Must NOT auto-submit. expect(mocks.postStockIn).not.toHaveBeenCalled(); }); // ─── Task 8b — inactive warehouse exclusion ───────────────────────────────── it("does not render an option for an inactive (status N) warehouse in the destination select", async () => { // Fix 4 coverage: listAdminWarehouses may return warehouses with status="N". // The destination select must only show active (status="Y") warehouses. const user = userEvent.setup(); const INACTIVE_WAREHOUSE = { id: 99, code: "MYB-X", name: "Closed Store", type: "W", parentId: null, status: "N", }; mocks.listAdminWarehouses.mockResolvedValue([ OTHER_WAREHOUSE, MASTER_WAREHOUSE, INACTIVE_WAREHOUSE, ]); render(); await waitForLoad(); // Open the destination select to reveal options. const destinationSelect = screen.getByRole("combobox", { name: /destination/i }); await user.click(destinationSelect); // Active warehouses are rendered. expect(await screen.findByRole("option", { name: /MYB-Master Store/i })).toBeInTheDocument(); expect(screen.getByRole("option", { name: /MYB-HQ/i })).toBeInTheDocument(); // The inactive warehouse must NOT appear as an option. expect(screen.queryByRole("option", { name: /Closed Store/i })).not.toBeInTheDocument(); }); }); describe("StockInForm — product picker shows the product code", () => { // Live dev has BA-001 and EVENT-BA-001 with the same display name; name-only options were // indistinguishable, and cmdk (value = name) treated the pair as one item. it("lists same-named products as two distinct options and picks the right one", async () => { const user = userEvent.setup(); mocks.listProducts.mockResolvedValue({ items: [ { id: "1001", productCode: "BA-001", productName: "Pump Bra", productStatus: "Y" }, { id: "1009", productCode: "EVENT-BA-001", productName: "Pump Bra", productStatus: "Y" }, ], total: 2, }); render(); await waitForLoad(); await user.click(screen.getByRole("combobox", { name: /^product$/i })); const options = await screen.findAllByRole("option", { name: /Pump Bra/ }); expect(options).toHaveLength(2); expect(screen.getByRole("option", { name: /EVENT-BA-001/ })).toBeInTheDocument(); await user.click(screen.getByRole("option", { name: /EVENT-BA-001/ })); await waitFor(() => expect(mocks.getProductVariations).toHaveBeenCalledWith("1009")); expect(screen.getByRole("combobox", { name: /^product$/i })).toHaveTextContent("Pump Bra (EVENT-BA-001)"); }); }); // ─── Inventory page panel props (merge-inventory-page) ──────────────────────── describe("StockInForm — panel props", () => { it("pre-selects an active defaultWarehouseId as the destination", async () => { render(); await waitForLoad(); expect(screen.getByRole("combobox", { name: /destination/i })).toHaveTextContent(/MYB-HQ/); }); it("falls back to the Master Store when defaultWarehouseId is not an active warehouse", async () => { render(); await waitForLoad(); expect(screen.getByRole("combobox", { name: /destination/i })).toHaveTextContent(/MYB-Master Store/); }); it("reports dirty after a product is picked, clean after a successful submit, and calls onSubmitted", async () => { const user = userEvent.setup(); const onDirty = vi.fn(); const onSubmitted = vi.fn(); mocks.postStockIn.mockResolvedValue({ documentNo: "SI-0002" }); render(); await waitForLoad(); expect(onDirty).toHaveBeenLastCalledWith(false); await pickProduct(user, "Baby Milk"); await waitFor(() => expect(onDirty).toHaveBeenLastCalledWith(true)); await pickVariation(user, "100g"); await user.click(screen.getByRole("button", { name: /^submit$/i })); await screen.findByText(/SI-0002/); expect(screen.getByRole("status")).toHaveClass("text-positive"); expect(onSubmitted).toHaveBeenCalledTimes(1); await waitFor(() => expect(onDirty).toHaveBeenLastCalledWith(false)); }); it("counts a typed batch number as unsaved work even before a product is picked", async () => { const onDirty = vi.fn(); render(); await waitForLoad(); fireEvent.change(screen.getByLabelText(/batch number/i), { target: { value: "LOT-9" } }); await waitFor(() => expect(onDirty).toHaveBeenLastCalledWith(true)); }); }); describe("StockInForm — clearable quantity", () => { async function readyLine(user: ReturnType) { mocks.postStockIn.mockResolvedValue({ documentNo: "SI-0002" }); render(); await waitForLoad(); await pickProduct(user, "Baby Milk"); await waitFor(() => expect(mocks.getProductVariations).toHaveBeenCalledWith("1001")); await pickVariation(user, "100g"); return screen.getByRole("spinbutton", { name: /quantity/i }) as HTMLInputElement; } it("lets the quantity be cleared and retyped (no stray 1)", async () => { const user = userEvent.setup(); const qty = await readyLine(user); await user.clear(qty); expect(qty.value).toBe(""); await user.type(qty, "5"); expect(qty.value).toBe("5"); await user.click(screen.getByRole("button", { name: /^submit$/i })); await waitFor(() => expect(mocks.postStockIn).toHaveBeenCalledWith({ warehouseId: "11", lines: [expect.objectContaining({ skuVariationId: "SV-001", quantity: 5 })], }), ); }); it("blocks Submit with a visible error when the quantity is cleared", async () => { const user = userEvent.setup(); const qty = await readyLine(user); await user.clear(qty); await user.click(screen.getByRole("button", { name: /^submit$/i })); expect(await screen.findByText("Enter a quantity of at least 1.")).toBeInTheDocument(); expect(qty).toHaveAttribute("aria-invalid", "true"); expect(mocks.postStockIn).not.toHaveBeenCalled(); }); it("blocks Submit the same way when the quantity is 0", async () => { const user = userEvent.setup(); const qty = await readyLine(user); await user.clear(qty); await user.type(qty, "0"); await user.click(screen.getByRole("button", { name: /^submit$/i })); expect(await screen.findByText("Enter a quantity of at least 1.")).toBeInTheDocument(); expect(qty).toHaveAttribute("aria-invalid", "true"); expect(mocks.postStockIn).not.toHaveBeenCalled(); }); it("keeps 1.5 as typed (never rewritten to 15) and blocks Submit", async () => { const user = userEvent.setup(); const qty = await readyLine(user); await user.clear(qty); await user.type(qty, "1.5"); expect(qty.value).toBe("1.5"); await user.click(screen.getByRole("button", { name: /^submit$/i })); expect(await screen.findByText("Enter a quantity of at least 1.")).toBeInTheDocument(); expect(qty).toHaveAttribute("aria-invalid", "true"); expect(qty.value).toBe("1.5"); expect(mocks.postStockIn).not.toHaveBeenCalled(); }); it("clears the error once a valid quantity is typed", async () => { const user = userEvent.setup(); const qty = await readyLine(user); await user.clear(qty); await user.click(screen.getByRole("button", { name: /^submit$/i })); await screen.findByText("Enter a quantity of at least 1."); await user.type(qty, "3"); expect(screen.queryByText("Enter a quantity of at least 1.")).not.toBeInTheDocument(); expect(qty).not.toHaveAttribute("aria-invalid"); }); it("a second blocked attempt after a successful submit drops the old success banner", async () => { const user = userEvent.setup(); const qty = await readyLine(user); await user.click(screen.getByRole("button", { name: /^submit$/i })); await screen.findByText(/SI-0002/); await pickProduct(user, "Baby Milk"); await waitFor(() => expect(screen.getByRole("combobox", { name: /^variation$/i })).toBeInTheDocument()); await pickVariation(user, "100g"); const qty2 = screen.getByRole("spinbutton", { name: /quantity/i }); await user.clear(qty2); await user.click(screen.getByRole("button", { name: /^submit$/i })); await screen.findByText("Enter a quantity of at least 1."); expect(screen.queryByText(/SI-0002/)).not.toBeInTheDocument(); void qty; }); });