Files
co-lite/solvway-admin-portal/app/components/inventory/TransferForm.test.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 15:55:45 +08:00

820 lines
37 KiB
TypeScript

import { render, screen, waitFor, fireEvent, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { ApiError } from "@/app/lib/clientApi";
const mocks = vi.hoisted(() => ({
transferStock: vi.fn(),
getProductVariations: vi.fn(),
listAdminWarehouses: vi.fn(),
listProducts: vi.fn(),
getStockOnHand: vi.fn(),
}));
vi.mock("@/app/lib/services/adminStock", () => ({
transferStock: mocks.transferStock,
getProductVariations: mocks.getProductVariations,
getStockOnHand: mocks.getStockOnHand,
}));
vi.mock("@/app/lib/services/adminWarehouses", () => ({
listAdminWarehouses: mocks.listAdminWarehouses,
}));
vi.mock("@/app/lib/services/adminProduct", () => ({
listProducts: mocks.listProducts,
}));
import * as XLSX from "xlsx";
import { TransferForm } from "./TransferForm";
import { buildTransferWorkbook } from "@/app/lib/inventory/transferWorkbook";
import type { StockOnHandRow } from "@/app/lib/types";
// ─── fixture data ────────────────────────────────────────────────────────────
const MASTER_WAREHOUSE = {
id: 11,
code: "MYB-M",
name: "MYB-Master Store",
type: "M",
parentId: null,
status: "Y",
};
const WAREHOUSE_A = {
id: 10,
code: "MYB-W",
name: "MYB-HQ",
type: "W",
parentId: null,
status: "Y",
};
const WAREHOUSE_B = {
id: 12,
code: "MYB-B",
name: "MYB-Branch",
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.transferStock.mockReset();
mocks.getProductVariations.mockReset();
mocks.listAdminWarehouses.mockReset();
mocks.listProducts.mockReset();
mocks.listAdminWarehouses.mockResolvedValue([MASTER_WAREHOUSE, WAREHOUSE_A, WAREHOUSE_B]);
mocks.listProducts.mockResolvedValue({ items: PRODUCTS, total: 2 });
mocks.getProductVariations.mockResolvedValue(VARIATIONS);
});
// ─── helpers ─────────────────────────────────────────────────────────────────
async function waitForLoad() {
await screen.findByRole("combobox", { name: /source warehouse/i });
}
async function pickProduct(user: ReturnType<typeof userEvent.setup>, productName: string) {
await user.click(screen.getByRole("combobox", { name: /^product$/i }));
await user.click(await screen.findByText(productName));
}
async function pickVariation(user: ReturnType<typeof userEvent.setup>, label: string) {
await user.click(await screen.findByRole("combobox", { name: /^variation$/i }));
await user.click(await screen.findByRole("option", { name: label }));
}
// ─── submit disabled states ───────────────────────────────────────────────────
describe("TransferForm — submit gating", () => {
it("disables Submit when no source warehouse is selected", async () => {
render(<TransferForm />);
await waitForLoad();
// Default state: source is not pre-selected (unlike StockInForm which picks the M warehouse)
const submitBtn = screen.getByRole("button", { name: /^submit$/i });
expect(submitBtn).toBeDisabled();
});
it("disables Submit when source is chosen but no destination is chosen", async () => {
const user = userEvent.setup();
render(<TransferForm />);
await waitForLoad();
// Select source
const srcSelect = screen.getByRole("combobox", { name: /source warehouse/i });
await user.click(srcSelect);
await user.click(await screen.findByRole("option", { name: /MYB-Master Store/i }));
expect(screen.getByRole("button", { name: /^submit$/i })).toBeDisabled();
});
it("disables Submit when source and destination are the SAME warehouse", async () => {
const user = userEvent.setup();
render(<TransferForm />);
await waitForLoad();
// Select source = Master Store
const srcSelect = screen.getByRole("combobox", { name: /source warehouse/i });
await user.click(srcSelect);
await user.click(await screen.findByRole("option", { name: /MYB-Master Store/i }));
// Wait for the destination to exclude Master Store; it should have no option for it
const destSelect = screen.getByRole("combobox", { name: /destination warehouse/i });
await user.click(destSelect);
// The source (Master Store) must NOT appear as an option in destination
await waitFor(() =>
expect(screen.queryByRole("option", { name: /MYB-Master Store/i })).not.toBeInTheDocument(),
);
// Close destination dropdown without picking (press Escape)
await user.keyboard("{Escape}");
expect(screen.getByRole("button", { name: /^submit$/i })).toBeDisabled();
});
it("disables Submit when source and destination are chosen but no lines are complete", async () => {
const user = userEvent.setup();
render(<TransferForm />);
await waitForLoad();
// Pick source
await user.click(screen.getByRole("combobox", { name: /source warehouse/i }));
await user.click(await screen.findByRole("option", { name: /MYB-Master Store/i }));
// Pick destination
await user.click(screen.getByRole("combobox", { name: /destination warehouse/i }));
await user.click(await screen.findByRole("option", { name: /MYB-HQ/i }));
// No product/variation chosen — Submit still disabled
expect(screen.getByRole("button", { name: /^submit$/i })).toBeDisabled();
});
});
// ─── destination excludes chosen source ──────────────────────────────────────
describe("TransferForm — destination excludes source", () => {
it("does not render the chosen source warehouse as a destination option", async () => {
const user = userEvent.setup();
render(<TransferForm />);
await waitForLoad();
// Choose WAREHOUSE_A as source
const srcSelect = screen.getByRole("combobox", { name: /source warehouse/i });
await user.click(srcSelect);
await user.click(await screen.findByRole("option", { name: /MYB-HQ/i }));
// Open destination dropdown — MYB-HQ must NOT appear
const destSelect = screen.getByRole("combobox", { name: /destination warehouse/i });
await user.click(destSelect);
await waitFor(() =>
expect(screen.queryByRole("option", { name: /MYB-HQ/i })).not.toBeInTheDocument(),
);
// Other warehouses appear
expect(await screen.findByRole("option", { name: /MYB-Master Store/i })).toBeInTheDocument();
expect(screen.getByRole("option", { name: /MYB-Branch/i })).toBeInTheDocument();
});
});
// ─── success ─────────────────────────────────────────────────────────────────
describe("TransferForm — success", () => {
it("shows the TRF documentNo on success and resets to one empty line", async () => {
const user = userEvent.setup();
// Backend returns the saved Inventory entity; Jackson key is "documentNo" (getDocumentNo()).
mocks.transferStock.mockResolvedValue({ documentNo: "TRF20260906001" });
render(<TransferForm />);
await waitForLoad();
// Pick source
await user.click(screen.getByRole("combobox", { name: /source warehouse/i }));
await user.click(await screen.findByRole("option", { name: /MYB-Master Store/i }));
// Pick destination
await user.click(screen.getByRole("combobox", { name: /destination warehouse/i }));
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");
// Submit
await user.click(screen.getByRole("button", { name: /^submit$/i }));
// Success message shows the exact documentNo returned by the backend (not the "Submitted" fallback).
await screen.findByText(/TRF20260906001/i);
// Form is reset: Submit is disabled again (empty line, no variation chosen)
expect(screen.getByRole("button", { name: /^submit$/i })).toBeDisabled();
});
it("calls transferStock with correct sourceWarehouseId, destWarehouseId, skuVariationId, quantity", async () => {
const user = userEvent.setup();
mocks.transferStock.mockResolvedValue({ documentNo: "TRF20260906002" });
render(<TransferForm />);
await waitForLoad();
await user.click(screen.getByRole("combobox", { name: /source warehouse/i }));
await user.click(await screen.findByRole("option", { name: /MYB-Master Store/i }));
await user.click(screen.getByRole("combobox", { name: /destination warehouse/i }));
await user.click(await screen.findByRole("option", { name: /MYB-HQ/i }));
await pickProduct(user, "Baby Milk");
await waitFor(() => expect(mocks.getProductVariations).toHaveBeenCalledWith("1001"));
await pickVariation(user, "100g");
const qtyInput = screen.getByRole("spinbutton", { name: /quantity/i });
fireEvent.change(qtyInput, { target: { value: "7" } });
await user.click(screen.getByRole("button", { name: /^submit$/i }));
await waitFor(() =>
expect(mocks.transferStock).toHaveBeenCalledWith({
sourceWarehouseId: "11",
destWarehouseId: "10",
lines: [
expect.objectContaining({
skuVariationId: "SV-001",
quantity: 7,
}),
],
}),
);
});
});
// ─── 4xx rejection ───────────────────────────────────────────────────────────
describe("TransferForm — 4xx rejection", () => {
it("renders the error message when transferStock rejects AND keeps the entered lines", async () => {
const user = userEvent.setup();
mocks.transferStock.mockRejectedValue(new Error("Insufficient source stock"));
render(<TransferForm />);
await waitForLoad();
await user.click(screen.getByRole("combobox", { name: /source warehouse/i }));
await user.click(await screen.findByRole("option", { name: /MYB-Master Store/i }));
await user.click(screen.getByRole("combobox", { name: /destination warehouse/i }));
await user.click(await screen.findByRole("option", { name: /MYB-HQ/i }));
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 }));
// Error message is shown
await screen.findByText(/Insufficient source stock/i);
// Lines are DIRECTLY retained: the product label text "Baby Milk" is still in the form
// (lines were not cleared; user can correct the quantity and resubmit).
expect(screen.getByText("Baby Milk (P001)")).toBeInTheDocument();
// The variation combobox is still present (line not reset to empty).
expect(screen.getByRole("combobox", { name: /^variation$/i })).toBeInTheDocument();
// Submit is still enabled (complete line remains, so it's unblocked).
expect(screen.getByRole("button", { name: /^submit$/i })).not.toBeDisabled();
// No success message
expect(screen.queryByText(/TRF-/i)).not.toBeInTheDocument();
});
});
describe("TransferForm — 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(<TransferForm />);
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("TransferForm — panel props", () => {
it("pre-selects an active defaultWarehouseId as the source", async () => {
render(<TransferForm defaultWarehouseId="10" />);
await waitForLoad();
expect(screen.getByRole("combobox", { name: /source warehouse/i })).toHaveTextContent(/MYB-HQ/);
});
it("leaves the source empty when defaultWarehouseId is not an active warehouse", async () => {
render(<TransferForm defaultWarehouseId="999999" />);
await waitForLoad();
const source = screen.getByRole("combobox", { name: /source warehouse/i });
expect(source).not.toHaveTextContent(/MYB-/);
});
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.transferStock.mockResolvedValue({ documentNo: "TRF20260924001" });
render(<TransferForm defaultWarehouseId="11" onDirtyChange={onDirty} onSubmitted={onSubmitted} />);
await waitForLoad();
expect(onDirty).toHaveBeenLastCalledWith(false);
await user.click(screen.getByRole("combobox", { name: /destination warehouse/i }));
await user.click(await screen.findByRole("option", { name: /MYB-HQ/i }));
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(/TRF20260924001/);
expect(onSubmitted).toHaveBeenCalledTimes(1);
await waitFor(() => expect(onDirty).toHaveBeenLastCalledWith(false));
});
it("counts a typed remark as unsaved work", async () => {
const onDirty = vi.fn();
render(<TransferForm onDirtyChange={onDirty} />);
await waitForLoad();
fireEvent.change(screen.getByLabelText(/remark/i), { target: { value: "move for promo" } });
await waitFor(() => expect(onDirty).toHaveBeenLastCalledWith(true));
});
});
describe("TransferForm — clearable quantity", () => {
async function readyLine(user: ReturnType<typeof userEvent.setup>) {
mocks.transferStock.mockResolvedValue({ documentNo: "TRF20260906003" });
render(<TransferForm />);
await waitForLoad();
await user.click(screen.getByRole("combobox", { name: /source warehouse/i }));
await user.click(await screen.findByRole("option", { name: /MYB-Master Store/i }));
await user.click(screen.getByRole("combobox", { name: /destination warehouse/i }));
await user.click(await screen.findByRole("option", { name: /MYB-HQ/i }));
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.transferStock).toHaveBeenCalledWith({
sourceWarehouseId: "11",
destWarehouseId: "10",
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.transferStock).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.transferStock).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.transferStock).not.toHaveBeenCalled();
});
});
// ─── BABYBOO-39: structured insufficient-stock rejection ─────────────────────
describe("TransferForm — insufficient stock names the product", () => {
const MOMCOZY = { id: "2001", productCode: "", productName: "Momcozy Washing Block", productStatus: "Y" };
async function submitMomcozyLine(user: ReturnType<typeof userEvent.setup>) {
mocks.listProducts.mockResolvedValue({ items: [...PRODUCTS, MOMCOZY], total: 3 });
mocks.getProductVariations.mockResolvedValue([{ skuVariationId: "50", variationId: "V-50", label: "DEFAULT" }]);
render(<TransferForm />);
await waitForLoad();
await user.click(screen.getByRole("combobox", { name: /source warehouse/i }));
await user.click(await screen.findByRole("option", { name: /MYB-Master Store/i }));
await user.click(screen.getByRole("combobox", { name: /destination warehouse/i }));
await user.click(await screen.findByRole("option", { name: /MYB-HQ/i }));
await pickProduct(user, "Momcozy Washing Block");
await waitFor(() => expect(mocks.getProductVariations).toHaveBeenCalledWith("2001"));
await pickVariation(user, "DEFAULT");
await user.click(screen.getByRole("button", { name: /^submit$/i }));
}
function insufficient(skuVariationId: number) {
const raw = `Insufficient stock for sku_variation ${skuVariationId}: available 0, requested 10, shortfall 10`;
return new ApiError(raw, 400, {
error: raw,
code: "INSUFFICIENT_STOCK",
details: { skuVariationId, available: 0, requested: 10 },
});
}
it("shows the translated line message, not the raw backend text, and keeps the lines", async () => {
const user = userEvent.setup();
mocks.transferStock.mockRejectedValue(insufficient(50));
await submitMomcozyLine(user);
await screen.findByText("Not enough stock for Momcozy Washing Block — DEFAULT (0 available, 10 requested).");
expect(screen.queryByText(/sku_variation/)).not.toBeInTheDocument();
expect(screen.getByText("Momcozy Washing Block")).toBeInTheDocument();
expect(screen.getByRole("combobox", { name: /^variation$/i })).toBeInTheDocument();
});
it("shows the generic message when no submitted line matches", async () => {
const user = userEvent.setup();
mocks.transferStock.mockRejectedValue(insufficient(999));
await submitMomcozyLine(user);
await screen.findByText("Not enough stock for one of the lines.");
expect(screen.queryByText(/sku_variation/)).not.toBeInTheDocument();
});
});
// ─── Excel template + import ─────────────────────────────────────────────────
const stockRow = (over: Partial<StockOnHandRow>): StockOnHandRow =>
({
skuCode: "BB-001",
skuVariationId: "50",
variation: "100g",
skuName: "Baby Milk",
stockOnHand: 5,
committedQty: 0,
availableQty: 5,
outQty: 0,
details: [],
...over,
}) as StockOnHandRow;
const ONHAND = [stockRow({}), stockRow({ skuVariationId: "60", skuCode: "BB-002", skuName: "Baby Lotion", variation: null, stockOnHand: 20 })];
function page(content: StockOnHandRow[], number = 0, totalPages = 1) {
return { content, totalElements: content.length, totalPages, number, size: 200 };
}
/** A filled template: quantities / batch / expiry by xlsx data-row index (0 = first data row). */
function filledFile(fills: Record<number, { qty: unknown; batch?: string; expiry?: string | XLSX.CellObject }>, rows = ONHAND) {
const wb = XLSX.read(buildTransferWorkbook(rows), { type: "array" });
const ws = wb.Sheets["Stock Transfer"];
for (const [i, f] of Object.entries(fills)) {
const r = Number(i) + 1;
ws[XLSX.utils.encode_cell({ r, c: 4 })] = typeof f.qty === "number" ? { t: "n", v: f.qty } : { t: "s", v: String(f.qty) };
if (f.batch) ws[XLSX.utils.encode_cell({ r, c: 5 })] = { t: "s", v: f.batch };
if (f.expiry) ws[XLSX.utils.encode_cell({ r, c: 6 })] = typeof f.expiry === "string" ? { t: "s", v: f.expiry } : f.expiry;
}
const bytes = new Uint8Array(XLSX.write(wb, { type: "array", bookType: "xlsx" }));
const file = new File([bytes], "t.xlsx");
// jsdom's File may lack arrayBuffer().
if (!file.arrayBuffer) Object.defineProperty(file, "arrayBuffer", { value: async () => bytes.buffer });
return file;
}
async function pickWarehouse(user: ReturnType<typeof userEvent.setup>, label: RegExp, option: RegExp) {
await user.click(screen.getByRole("combobox", { name: label }));
await user.click(await screen.findByRole("option", { name: option }));
}
async function renderWithSource(user: ReturnType<typeof userEvent.setup>) {
render(<TransferForm />);
await waitForLoad();
await pickWarehouse(user, /source warehouse/i, /MYB-Master Store/i);
}
const importFile = (user: ReturnType<typeof userEvent.setup>, file: File) =>
user.upload(screen.getByLabelText(/import stock transfer file/i), file);
const qtyInputs = () => screen.getAllByRole("spinbutton", { name: /quantity/i }) as HTMLInputElement[];
const submitBtn = () => screen.getByRole("button", { name: /^submit$/i });
describe("TransferForm — Excel template and import", () => {
beforeEach(() => {
mocks.getStockOnHand.mockReset();
mocks.getStockOnHand.mockResolvedValue(page(ONHAND));
});
it("disables Download template and Import until a source is chosen", async () => {
const user = userEvent.setup();
render(<TransferForm />);
await waitForLoad();
expect(screen.getByRole("button", { name: /download template/i })).toBeDisabled();
expect(screen.getByRole("button", { name: /^import$/i })).toBeDisabled();
await pickWarehouse(user, /source warehouse/i, /MYB-Master Store/i);
expect(screen.getByRole("button", { name: /download template/i })).toBeEnabled();
expect(screen.getByRole("button", { name: /^import$/i })).toBeEnabled();
});
it("imports filled rows into a review table with on-hand, skipping blank rows", async () => {
const user = userEvent.setup();
await renderWithSource(user);
await importFile(user, filledFile({ 1: { qty: 4, batch: "B9", expiry: "2027-12-31" } }));
const table = await screen.findByRole("table", { name: /imported lines/i });
const cells = within(table).getAllByRole("row");
expect(cells).toHaveLength(2); // header + one line
expect(within(cells[1]).getByText("BB-002")).toBeInTheDocument();
expect(within(cells[1]).getByText("Baby Lotion")).toBeInTheDocument();
expect(within(cells[1]).getByText("B9")).toBeInTheDocument();
expect(within(cells[1]).getByText("2027-12-31")).toBeInTheDocument();
expect(within(cells[1]).getByText("20")).toBeInTheDocument();
expect(qtyInputs()[0].value).toBe("4");
expect(mocks.getStockOnHand).toHaveBeenCalledWith(expect.objectContaining({ warehouseId: "11" }));
// the manual line editor is replaced
expect(screen.queryByRole("combobox", { name: /^product$/i })).not.toBeInTheDocument();
});
it("imports a real Excel date cell as its calendar date", async () => {
const user = userEvent.setup();
await renderWithSource(user);
await importFile(user, filledFile({ 1: { qty: 4, expiry: { t: "n", v: 46752, z: "yyyy-mm-dd" } } }));
const table = await screen.findByRole("table", { name: /imported lines/i });
expect(within(within(table).getAllByRole("row")[1]).getByText("2027-12-31")).toBeInTheDocument();
});
it("shows quantity, on hand and status before batch and expiry, with the variation under the name", async () => {
const user = userEvent.setup();
await renderWithSource(user);
await importFile(user, filledFile({ 0: { qty: 4, batch: "B9", expiry: "2027-12-31" } }));
const table = await screen.findByRole("table", { name: /imported lines/i });
const heads = within(table).getAllByRole("columnheader").map(h => h.textContent);
const idx = (re: RegExp) => heads.findIndex(h => re.test(h ?? ""));
expect(heads).toHaveLength(8); // no separate Variation column
for (const re of [/^quantity$/i, /on hand/i, /^status$/i, /batch/i, /expiry/i]) expect(idx(re)).toBeGreaterThanOrEqual(0);
for (const early of [/^quantity$/i, /on hand/i, /^status$/i]) {
for (const late of [/batch/i, /expiry/i]) expect(idx(early)).toBeLessThan(idx(late));
}
const nameCell = within(within(table).getAllByRole("row")[1]).getByText("Baby Milk").closest("td")!;
expect(within(nameCell).getByText("100g")).toBeInTheDocument();
// long names wrap instead of pushing Status off-screen (jsdom cannot measure layout)
expect(nameCell).toHaveClass("whitespace-normal", "break-words", "max-w-[200px]");
// the Quantity header's column holds the quantity input
const row = within(table).getAllByRole("row")[1];
expect(within(within(row).getAllByRole("cell")[idx(/^quantity$/i)]).getByRole("spinbutton")).toBeInTheDocument();
});
it("renders no variation line for a SKU without a variation", async () => {
const user = userEvent.setup();
await renderWithSource(user);
await importFile(user, filledFile({ 1: { qty: 4 } }));
const table = await screen.findByRole("table", { name: /imported lines/i });
const nameCell = within(within(table).getAllByRole("row")[1]).getByText("Baby Lotion").closest("td")!;
expect(nameCell.querySelector(".text-muted-foreground")).toBeNull();
});
it("marks both lines of an over-drawn SKU short and clears it when corrected", async () => {
const user = userEvent.setup();
await renderWithSource(user);
// two batch lines for the same sku_variation: pad the template with a duplicate row
const dup = [ONHAND[0], ONHAND[0]];
mocks.getStockOnHand.mockResolvedValue(page(dup));
await importFile(user, filledFile({ 0: { qty: 3, batch: "A" }, 1: { qty: 4, batch: "B" } }, dup));
await waitFor(() => expect(screen.getAllByText("Short by 2")).toHaveLength(2));
await pickWarehouse(user, /destination warehouse/i, /MYB-HQ/i);
expect(submitBtn()).toBeDisabled();
fireEvent.change(qtyInputs()[1], { target: { value: "1" } });
await waitFor(() => expect(screen.queryByText(/Short by/)).not.toBeInTheDocument());
expect(submitBtn()).toBeEnabled();
});
it("names the bad row, keeps the good ones, and blocks Submit", async () => {
const user = userEvent.setup();
await renderWithSource(user);
await pickWarehouse(user, /destination warehouse/i, /MYB-HQ/i);
await importFile(user, filledFile({ 0: { qty: "five" }, 1: { qty: 2 } }));
expect(await screen.findByText(/Row 2: quantity must be a number/)).toBeInTheDocument();
expect(qtyInputs()).toHaveLength(1);
expect(submitBtn()).toBeDisabled();
});
it("a new import replaces the table and clears old errors", async () => {
const user = userEvent.setup();
await renderWithSource(user);
await importFile(user, filledFile({ 0: { qty: "five" }, 1: { qty: 2 } }));
await screen.findByText(/Row 2:/);
await importFile(user, filledFile({ 0: { qty: 1 }, 1: { qty: 6 } }));
await waitFor(() => expect(qtyInputs()).toHaveLength(2));
expect(screen.queryByText(/Row 2:/)).not.toBeInTheDocument();
await importFile(user, filledFile({ 1: { qty: 7 } }));
await waitFor(() => expect(qtyInputs()).toHaveLength(1));
expect(qtyInputs()[0].value).toBe("7");
});
it("changing the source clears the imported table", async () => {
const user = userEvent.setup();
await renderWithSource(user);
await importFile(user, filledFile({ 0: { qty: 1 } }));
await screen.findByRole("table", { name: /imported lines/i });
await pickWarehouse(user, /source warehouse/i, /MYB-Branch/i);
expect(screen.queryByRole("table", { name: /imported lines/i })).not.toBeInTheDocument();
expect(screen.getByRole("combobox", { name: /^product$/i })).toBeInTheDocument();
});
it("removing every imported line returns to one empty manual line", async () => {
const user = userEvent.setup();
await renderWithSource(user);
await importFile(user, filledFile({ 0: { qty: 1 } }));
await screen.findByRole("table", { name: /imported lines/i });
await user.click(screen.getByRole("button", { name: /remove line/i }));
expect(screen.queryByRole("table", { name: /imported lines/i })).not.toBeInTheDocument();
expect(screen.getAllByRole("combobox", { name: /^product$/i })).toHaveLength(1);
});
it("blocks Submit while an imported quantity is below 1", async () => {
const user = userEvent.setup();
await renderWithSource(user);
await pickWarehouse(user, /destination warehouse/i, /MYB-HQ/i);
await importFile(user, filledFile({ 0: { qty: 1 } }));
await screen.findByRole("table", { name: /imported lines/i });
expect(submitBtn()).toBeEnabled();
fireEvent.change(qtyInputs()[0], { target: { value: "0" } });
expect(submitBtn()).toBeDisabled();
});
it("submits the imported lines as the transfer payload and clears the table", async () => {
const user = userEvent.setup();
mocks.transferStock.mockResolvedValue({ documentNo: "TRF1" });
const onDirtyChange = vi.fn();
render(<TransferForm onDirtyChange={onDirtyChange} />);
await waitForLoad();
await pickWarehouse(user, /source warehouse/i, /MYB-Master Store/i);
await pickWarehouse(user, /destination warehouse/i, /MYB-HQ/i);
await importFile(user, filledFile({ 0: { qty: 2, batch: "B1", expiry: "2027-12-31" }, 1: { qty: 3 } }));
await screen.findByRole("table", { name: /imported lines/i });
expect(onDirtyChange).toHaveBeenLastCalledWith(true);
await user.click(submitBtn());
await waitFor(() =>
expect(mocks.transferStock).toHaveBeenCalledWith({
sourceWarehouseId: "11",
destWarehouseId: "10",
lines: [
{ skuVariationId: "50", quantity: 2, batchNumber: "B1", expiryDate: "2027-12-31" },
{ skuVariationId: "60", quantity: 3 },
],
}),
);
await screen.findByText(/TRF1/);
expect(screen.queryByRole("table", { name: /imported lines/i })).not.toBeInTheDocument();
});
it("names the product when the server rejects an imported line for insufficient stock", async () => {
const user = userEvent.setup();
mocks.transferStock.mockRejectedValue(
new ApiError("x", 409, { code: "INSUFFICIENT_STOCK", details: { skuVariationId: 50, available: 1, requested: 2 } }),
);
await renderWithSource(user);
await pickWarehouse(user, /destination warehouse/i, /MYB-HQ/i);
await importFile(user, filledFile({ 0: { qty: 2 } }));
await screen.findByRole("table", { name: /imported lines/i });
await user.click(submitBtn());
const alert = await screen.findByRole("alert");
expect(alert).toHaveTextContent("BB-001 — Baby Milk — 100g");
expect(screen.getByRole("table", { name: /imported lines/i })).toBeInTheDocument();
});
it("pages through all on-hand rows when importing", async () => {
const user = userEvent.setup();
mocks.getStockOnHand
.mockResolvedValueOnce(page([ONHAND[0]], 0, 2))
.mockResolvedValueOnce(page([ONHAND[1]], 1, 2));
await renderWithSource(user);
await importFile(user, filledFile({ 0: { qty: 1 }, 1: { qty: 1 } }));
await waitFor(() => expect(qtyInputs()).toHaveLength(2));
expect(mocks.getStockOnHand).toHaveBeenCalledTimes(2);
expect(mocks.getStockOnHand).toHaveBeenNthCalledWith(2, expect.objectContaining({ page: 1 }));
});
it("ignores an import whose source changed while it was loading", async () => {
const user = userEvent.setup();
let release!: (v: ReturnType<typeof page>) => void;
mocks.getStockOnHand.mockImplementationOnce(() => new Promise(r => (release = r)));
await renderWithSource(user);
await importFile(user, filledFile({ 0: { qty: 1 } }));
await pickWarehouse(user, /source warehouse/i, /MYB-HQ/i);
release(page(ONHAND));
await new Promise(r => setTimeout(r, 20));
expect(screen.queryByRole("table", { name: /imported lines/i })).not.toBeInTheDocument();
});
it("ignores an on-hand load failure that belongs to a previous source", async () => {
const user = userEvent.setup();
let fail!: (e: Error) => void;
mocks.getStockOnHand.mockImplementationOnce(() => new Promise((_, rej) => (fail = rej)));
await renderWithSource(user);
await importFile(user, filledFile({ 0: { qty: 1 } }));
await pickWarehouse(user, /source warehouse/i, /MYB-HQ/i);
fail(new Error("boom"));
await new Promise(r => setTimeout(r, 20));
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
});
it("lets the latest of two overlapping imports win", async () => {
const user = userEvent.setup();
let releaseFirst!: (v: ReturnType<typeof page>) => void;
mocks.getStockOnHand.mockImplementationOnce(() => new Promise(r => (releaseFirst = r)));
await renderWithSource(user);
await importFile(user, filledFile({ 0: { qty: 1 } }));
await importFile(user, filledFile({ 1: { qty: 2 } }));
await waitFor(() => expect(qtyInputs()[0].value).toBe("2"));
releaseFirst(page(ONHAND));
await new Promise(r => setTimeout(r, 20));
expect(qtyInputs()).toHaveLength(1);
expect(qtyInputs()[0].value).toBe("2");
});
it("keeps the manual lines and says so when the file has no quantities", async () => {
const user = userEvent.setup();
await renderWithSource(user);
await user.type(screen.getByLabelText(/batch number/i), "KEEP-ME");
await importFile(user, filledFile({}));
expect(await screen.findByRole("alert")).toHaveTextContent("No rows with a quantity were found in the file.");
expect(screen.getByLabelText(/batch number/i)).toHaveValue("KEEP-ME");
expect(screen.queryByRole("table", { name: /imported lines/i })).not.toBeInTheDocument();
});
describe("template download", () => {
afterEach(() => vi.restoreAllMocks());
it("does not discard a pending import when Download template is clicked", async () => {
const user = userEvent.setup();
vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:x");
vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
let release!: (v: ReturnType<typeof page>) => void;
mocks.getStockOnHand.mockImplementationOnce(() => new Promise(r => (release = r)));
await renderWithSource(user);
await importFile(user, filledFile({ 0: { qty: 2 } }));
await user.click(screen.getByRole("button", { name: /download template/i }));
await waitFor(() => expect(URL.createObjectURL).toHaveBeenCalledOnce());
release(page(ONHAND));
await waitFor(() => expect(qtyInputs()[0].value).toBe("2"));
});
it("builds the template from the source's on-hand rows", async () => {
const user = userEvent.setup();
const createObjectURL = vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:x");
vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
await renderWithSource(user);
await user.click(screen.getByRole("button", { name: /download template/i }));
await waitFor(() => expect(createObjectURL).toHaveBeenCalledOnce());
expect(mocks.getStockOnHand).toHaveBeenCalledWith(expect.objectContaining({ warehouseId: "11", page: 0 }));
});
});
});