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
439 lines
17 KiB
TypeScript
439 lines
17 KiB
TypeScript
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
|
import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
|
|
import userEvent from "@testing-library/user-event";
|
|
import type { StockOnHandPage as StockOnHandPageData } from "@/app/lib/types";
|
|
import * as xlsxModule from "@/app/lib/xlsx";
|
|
import { xlsxRows } from "@/test/readXlsx";
|
|
import { memoryRouter } from "@/test/memoryRouter";
|
|
|
|
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
|
|
|
|
// ─── mock adminStock service ──────────────────────────────────────────────────
|
|
|
|
const svc = vi.hoisted(() => ({
|
|
getStockOnHand: vi.fn(),
|
|
}));
|
|
vi.mock("@/app/lib/services/adminStock", () => ({
|
|
getStockOnHand: (params: unknown) => svc.getStockOnHand(params),
|
|
}));
|
|
|
|
// ─── mock adminWarehouses service (warehouse filter, 8B) ─────────────────────
|
|
|
|
const warehouseSvc = vi.hoisted(() => ({
|
|
listAdminWarehouses: vi.fn(),
|
|
}));
|
|
vi.mock("@/app/lib/services/adminWarehouses", () => ({
|
|
listAdminWarehouses: warehouseSvc.listAdminWarehouses,
|
|
}));
|
|
|
|
import { StockOnHandReport } from "./StockOnHandReport";
|
|
|
|
// ─── fixture data ─────────────────────────────────────────────────────────────
|
|
|
|
const ONE_ROW_PAGE: StockOnHandPageData = {
|
|
content: [
|
|
{
|
|
skuCode: "SKU-001",
|
|
skuVariationId: "501",
|
|
variation: null,
|
|
skuName: "Baby Milk 200g",
|
|
stockOnHand: 100,
|
|
committedQty: 10,
|
|
availableQty: 90,
|
|
outQty: 5,
|
|
details: [],
|
|
},
|
|
],
|
|
number: 0,
|
|
size: 20,
|
|
totalElements: 1,
|
|
totalPages: 1,
|
|
};
|
|
|
|
const TWO_PAGE_RESULT: StockOnHandPageData = {
|
|
content: [
|
|
{
|
|
skuCode: "SKU-002",
|
|
skuVariationId: "502",
|
|
variation: null,
|
|
skuName: "Baby Lotion 100ml",
|
|
stockOnHand: 200,
|
|
committedQty: 20,
|
|
availableQty: 180,
|
|
outQty: 3,
|
|
details: [],
|
|
},
|
|
],
|
|
number: 0,
|
|
size: 20,
|
|
totalElements: 25,
|
|
totalPages: 2,
|
|
};
|
|
|
|
// ─── warehouse fixtures (8B) ──────────────────────────────────────────────────
|
|
|
|
const WAREHOUSES = [
|
|
{ id: 11, code: "MYB-M", name: "MYB-Master store", type: "M", parentId: null, status: "Y" },
|
|
{ id: 10, code: "MYB-W", name: "MYB-HQ", type: "W", parentId: null, status: "Y" },
|
|
];
|
|
|
|
// The warehouse and search filters live in the URL (soh. prefix); the page is told the warehouse.
|
|
function renderPage(onViewMovements: (id: string) => void = () => {}, onWarehouseChange: (id: string | undefined) => void = () => {}) {
|
|
return render(<StockOnHandReport onWarehouseChange={onWarehouseChange} onViewMovements={onViewMovements} reloadKey={0} />);
|
|
}
|
|
|
|
beforeEach(() => {
|
|
memoryRouter.reset("/inventory");
|
|
svc.getStockOnHand.mockReset();
|
|
svc.getStockOnHand.mockResolvedValue(ONE_ROW_PAGE);
|
|
warehouseSvc.listAdminWarehouses.mockReset();
|
|
warehouseSvc.listAdminWarehouses.mockResolvedValue(WAREHOUSES);
|
|
});
|
|
|
|
// ─── data rendering ───────────────────────────────────────────────────────────
|
|
|
|
describe("stock on hand table — data rendering", () => {
|
|
it("marks negative available stock in the negative tone", async () => {
|
|
svc.getStockOnHand.mockResolvedValue({
|
|
...ONE_ROW_PAGE,
|
|
content: [{ ...ONE_ROW_PAGE.content[0], availableQty: -3 }],
|
|
});
|
|
renderPage();
|
|
|
|
expect(await screen.findByText("-3")).toHaveClass("text-negative");
|
|
});
|
|
|
|
it("renders skuCode, skuName, stockOnHand, committedQty, availableQty for a row", async () => {
|
|
svc.getStockOnHand.mockResolvedValue(ONE_ROW_PAGE);
|
|
renderPage();
|
|
|
|
// Wait for the async fetch to resolve
|
|
expect(await screen.findByText("SKU-001")).toBeInTheDocument();
|
|
expect(screen.getByText("Baby Milk 200g")).toBeInTheDocument();
|
|
expect(screen.getByText("100")).toBeInTheDocument(); // stockOnHand
|
|
expect(screen.getByText("10")).toBeInTheDocument(); // committedQty
|
|
expect(screen.getByText("90")).toBeInTheDocument(); // availableQty
|
|
});
|
|
|
|
it("renders outQty for the row", async () => {
|
|
svc.getStockOnHand.mockResolvedValue(ONE_ROW_PAGE);
|
|
renderPage();
|
|
|
|
expect(await screen.findByText("SKU-001")).toBeInTheDocument();
|
|
expect(screen.getByText("5")).toBeInTheDocument(); // outQty
|
|
});
|
|
|
|
it("shows empty state when content is empty", async () => {
|
|
svc.getStockOnHand.mockResolvedValue({
|
|
content: [],
|
|
number: 0,
|
|
size: 20,
|
|
totalElements: 0,
|
|
totalPages: 0,
|
|
});
|
|
renderPage();
|
|
|
|
await waitFor(() => expect(svc.getStockOnHand).toHaveBeenCalled());
|
|
expect(await screen.findByText(/no stock/i)).toBeInTheDocument();
|
|
});
|
|
});
|
|
|
|
// ─── pagination ───────────────────────────────────────────────────────────────
|
|
|
|
describe("pagination", () => {
|
|
// fit-admin-listing-pages: the shared pager is the only "Page x of y" on screen.
|
|
it("shows the page count once, in the shared pager", async () => {
|
|
svc.getStockOnHand.mockResolvedValue(TWO_PAGE_RESULT);
|
|
renderPage();
|
|
await screen.findByText("SKU-002");
|
|
expect(document.body.textContent!.match(/Page\s*1\s*of\s*2/g)).toHaveLength(1);
|
|
});
|
|
|
|
it("shows Next button enabled when totalPages > 1", async () => {
|
|
svc.getStockOnHand.mockResolvedValue(TWO_PAGE_RESULT);
|
|
renderPage();
|
|
|
|
await screen.findByText("SKU-002");
|
|
const nextBtn = screen.getByRole("button", { name: /next/i });
|
|
expect(nextBtn).not.toBeDisabled();
|
|
});
|
|
|
|
it("fetches page 2 when Next is clicked", async () => {
|
|
const user = userEvent.setup();
|
|
svc.getStockOnHand.mockResolvedValue(TWO_PAGE_RESULT);
|
|
renderPage();
|
|
|
|
await screen.findByText("SKU-002");
|
|
|
|
const nextBtn = screen.getByRole("button", { name: /next/i });
|
|
await user.click(nextBtn);
|
|
|
|
await waitFor(() => {
|
|
const calls = svc.getStockOnHand.mock.calls;
|
|
const lastCall = calls[calls.length - 1][0] as { page?: number };
|
|
expect(lastCall.page).toBe(1);
|
|
});
|
|
});
|
|
});
|
|
|
|
// ─── warehouse filter (8B) ────────────────────────────────────────────────────
|
|
|
|
describe("warehouse filter", () => {
|
|
it("calls getStockOnHand with warehouseId when a warehouse is selected", async () => {
|
|
const user = userEvent.setup();
|
|
renderPage();
|
|
|
|
// Wait for the warehouse filter combobox to appear.
|
|
const warehouseFilter = await screen.findByRole("combobox", { name: /warehouse filter/i });
|
|
|
|
// Open the select and choose MYB-HQ (id=10).
|
|
await user.click(warehouseFilter);
|
|
await user.click(await screen.findByRole("option", { name: /MYB-HQ/i }));
|
|
|
|
await waitFor(() => {
|
|
const calls = svc.getStockOnHand.mock.calls;
|
|
const lastCall = calls[calls.length - 1][0] as { warehouseId?: string };
|
|
expect(lastCall.warehouseId).toBe("10");
|
|
});
|
|
});
|
|
|
|
it("calls getStockOnHand without warehouseId when All warehouses is selected", async () => {
|
|
const user = userEvent.setup();
|
|
renderPage();
|
|
|
|
const warehouseFilter = await screen.findByRole("combobox", { name: /warehouse filter/i });
|
|
|
|
// Select a specific warehouse first.
|
|
await user.click(warehouseFilter);
|
|
await user.click(await screen.findByRole("option", { name: /MYB-HQ/i }));
|
|
|
|
await waitFor(() => {
|
|
const calls = svc.getStockOnHand.mock.calls;
|
|
const lastCall = calls[calls.length - 1][0] as { warehouseId?: string };
|
|
expect(lastCall.warehouseId).toBe("10");
|
|
});
|
|
|
|
// Now clear the filter by selecting "All warehouses".
|
|
await user.click(warehouseFilter);
|
|
await user.click(await screen.findByRole("option", { name: /all warehouses/i }));
|
|
|
|
await waitFor(() => {
|
|
const calls = svc.getStockOnHand.mock.calls;
|
|
const lastCall = calls[calls.length - 1][0] as { warehouseId?: string };
|
|
expect(lastCall.warehouseId).toBeUndefined();
|
|
});
|
|
});
|
|
});
|
|
|
|
// ─── Inventory page hooks (merge-inventory-page) ──────────────────────────────
|
|
|
|
describe("inventory page hooks", () => {
|
|
// fix-stock-on-hand-row-identity: several rows can share a SKU code, so View movements reports
|
|
// the row's own sku variation id, not its code.
|
|
it("View movements reports the row's sku variation id", async () => {
|
|
const user = userEvent.setup();
|
|
const onView = vi.fn();
|
|
renderPage(onView);
|
|
|
|
await user.click(await screen.findByRole("button", { name: /view movements for SKU-001/i }));
|
|
expect(onView).toHaveBeenCalledWith("501");
|
|
});
|
|
|
|
it("refetches when reloadKey changes", async () => {
|
|
const props = { onWarehouseChange: () => {}, onViewMovements: () => {} };
|
|
const { rerender } = render(<StockOnHandReport {...props} reloadKey={0} />);
|
|
await waitFor(() => expect(svc.getStockOnHand).toHaveBeenCalledTimes(1));
|
|
|
|
rerender(<StockOnHandReport {...props} reloadKey={1} />);
|
|
await waitFor(() => expect(svc.getStockOnHand).toHaveBeenCalledTimes(2));
|
|
});
|
|
});
|
|
|
|
// ─── one row per sku variation (fix-stock-on-hand-row-identity) ──────────────
|
|
|
|
const bra = (skuVariationId: string, variation: string, stockOnHand: number) => ({
|
|
skuCode: "BA-002",
|
|
skuVariationId,
|
|
variation,
|
|
skuName: "Nursing Bra",
|
|
stockOnHand,
|
|
committedQty: 0,
|
|
availableQty: stockOnHand,
|
|
outQty: 0,
|
|
details: [],
|
|
});
|
|
const braPage = (rows: ReturnType<typeof bra>[]): StockOnHandPageData => ({
|
|
content: rows,
|
|
number: 0,
|
|
size: 20,
|
|
totalElements: rows.length,
|
|
totalPages: 1,
|
|
});
|
|
|
|
describe("rows sharing a SKU code", () => {
|
|
it("shows each row's variation label", async () => {
|
|
svc.getStockOnHand.mockResolvedValue(braPage([bra("17", "Colour: Black", 1), bra("18", "Colour: Blue", 2)]));
|
|
renderPage();
|
|
|
|
expect(await screen.findByText("Colour: Black")).toBeInTheDocument();
|
|
expect(screen.getByText("Colour: Blue")).toBeInTheDocument();
|
|
});
|
|
|
|
it("renders exactly the reloaded rows, with nothing left over from before", async () => {
|
|
const props = { onWarehouseChange: () => {}, onViewMovements: () => {} };
|
|
svc.getStockOnHand.mockResolvedValueOnce(
|
|
braPage([bra("17", "Colour: Black", 7), bra("18", "Colour: Blue", 8), bra("19", "Size: S", 9)]),
|
|
);
|
|
const { rerender } = render(<StockOnHandReport {...props} reloadKey={0} />);
|
|
expect(await screen.findByText("Size: S")).toBeInTheDocument();
|
|
|
|
svc.getStockOnHand.mockResolvedValueOnce(braPage([bra("18", "Colour: Blue", 5), bra("17", "Colour: Black", 4)]));
|
|
rerender(<StockOnHandReport {...props} reloadKey={1} />);
|
|
|
|
await waitFor(() => expect(screen.queryByText("Size: S")).not.toBeInTheDocument());
|
|
const rows = screen.getAllByRole("row").slice(1); // drop the header row
|
|
expect(rows).toHaveLength(2);
|
|
expect(rows.map(r => r.textContent)).toEqual([
|
|
expect.stringContaining("Colour: Blue"),
|
|
expect.stringContaining("Colour: Black"),
|
|
]);
|
|
});
|
|
});
|
|
|
|
// ─── Excel export ─────────────────────────────────────────────────────────────
|
|
|
|
describe("stock on hand — Excel export", () => {
|
|
it("downloads stock-on-hand.xlsx with the header and every row", async () => {
|
|
const downloadSpy = vi.spyOn(xlsxModule, "downloadXlsx").mockImplementation(() => {});
|
|
renderPage();
|
|
await screen.findByText("SKU-001");
|
|
|
|
await userEvent.setup().click(screen.getByRole("button", { name: /export \.xlsx/i }));
|
|
|
|
await waitFor(() => expect(downloadSpy).toHaveBeenCalledTimes(1));
|
|
const [filename, bytes] = downloadSpy.mock.calls[0];
|
|
expect(filename).toBe("stock-on-hand.xlsx");
|
|
expect(await xlsxRows(bytes)).toEqual([
|
|
["SKU code", "SKU name", "Stock on hand", "Committed", "Available", "Out qty"],
|
|
["SKU-001", "Baby Milk 200g", 100, 10, 90, 5],
|
|
]);
|
|
downloadSpy.mockRestore();
|
|
});
|
|
});
|
|
|
|
// ─── standard filter bar (standardize-admin-list-filters) ─────────────────────
|
|
|
|
describe("filter bar", () => {
|
|
afterEach(() => vi.useRealTimers());
|
|
|
|
it("sends q once after the 300 ms debounce when typing in SKU code or name", async () => {
|
|
renderPage();
|
|
await screen.findByText("SKU-001");
|
|
vi.useFakeTimers();
|
|
svc.getStockOnHand.mockClear();
|
|
|
|
const box = screen.getByRole("searchbox", { name: "SKU code or name" });
|
|
// fireEvent: userEvent typing stalls under fake timers
|
|
fireEvent.change(box, { target: { value: "milk" } });
|
|
await act(async () => { vi.advanceTimersByTime(300); });
|
|
|
|
expect(svc.getStockOnHand).toHaveBeenCalledTimes(1);
|
|
expect(svc.getStockOnHand).toHaveBeenLastCalledWith(expect.objectContaining({ q: "milk", page: 0 }));
|
|
expect(memoryRouter.getSearch().get("soh.q")).toBe("milk");
|
|
});
|
|
|
|
it("choosing a warehouse writes the URL, calls the service and tells the page", async () => {
|
|
const user = userEvent.setup();
|
|
const onWh = vi.fn();
|
|
renderPage(undefined, onWh);
|
|
|
|
await user.click(await screen.findByRole("combobox", { name: /warehouse filter/i }));
|
|
await user.click(await screen.findByRole("option", { name: /MYB-HQ/i }));
|
|
|
|
await waitFor(() => expect(svc.getStockOnHand).toHaveBeenLastCalledWith(expect.objectContaining({ warehouseId: "10", page: 0 })));
|
|
expect(memoryRouter.getSearch().get("soh.warehouse")).toBe("10");
|
|
expect(onWh).toHaveBeenLastCalledWith("10");
|
|
});
|
|
|
|
it("populates the controls and the request from the URL on mount", async () => {
|
|
memoryRouter.reset("/inventory", "soh.q=milk&soh.warehouse=10");
|
|
renderPage();
|
|
|
|
await waitFor(() => expect(svc.getStockOnHand).toHaveBeenCalledWith(expect.objectContaining({ q: "milk", warehouseId: "10" })));
|
|
expect(screen.getByRole("searchbox", { name: "SKU code or name" })).toHaveValue("milk");
|
|
});
|
|
|
|
it("Clear filters empties the URL and has no Apply button", async () => {
|
|
memoryRouter.reset("/inventory", "soh.q=milk&soh.warehouse=10");
|
|
const user = userEvent.setup();
|
|
renderPage();
|
|
|
|
await user.click(await screen.findByRole("button", { name: "Clear filters" }));
|
|
|
|
expect(memoryRouter.getSearch().toString()).toBe("");
|
|
expect(screen.queryByRole("button", { name: /apply/i })).not.toBeInTheDocument();
|
|
});
|
|
});
|
|
|
|
// ─── BABYBOO-54 B3: header sorting (URL prefix "soh.") ────────────────────────
|
|
|
|
describe("header sorting", () => {
|
|
it.each([
|
|
["SKU code", "skuCode"],
|
|
["SKU name", "skuName"],
|
|
["Stock on hand", "stockOnHand"],
|
|
["Committed", "committedQty"],
|
|
["Available", "availableQty"],
|
|
["Out qty", "outQty"],
|
|
])("clicking %s sorts server-side by %s, then desc", async (header, key) => {
|
|
const user = userEvent.setup();
|
|
renderPage();
|
|
await screen.findByText("SKU-001");
|
|
|
|
await user.click(screen.getByRole("button", { name: header }));
|
|
await waitFor(() => expect(svc.getStockOnHand).toHaveBeenLastCalledWith(expect.objectContaining({ sortBy: key, sortDir: "asc" })));
|
|
expect(memoryRouter.getSearch().get("soh.sortBy")).toBe(key);
|
|
expect(memoryRouter.getSearch().get("soh.sortDir")).toBe("asc");
|
|
|
|
await user.click(screen.getByRole("button", { name: header }));
|
|
await waitFor(() => expect(svc.getStockOnHand).toHaveBeenLastCalledWith(expect.objectContaining({ sortBy: key, sortDir: "desc" })));
|
|
});
|
|
|
|
it("is unsorted by default: no sortBy/sortDir sent", async () => {
|
|
renderPage();
|
|
await screen.findByText("SKU-001");
|
|
const arg = svc.getStockOnHand.mock.calls[0][0] as Record<string, unknown>;
|
|
expect(arg.sortBy).toBeUndefined();
|
|
expect(arg.sortDir).toBeUndefined();
|
|
});
|
|
|
|
it("sorting clears soh.page", async () => {
|
|
memoryRouter.reset("/inventory", "soh.page=2");
|
|
svc.getStockOnHand.mockResolvedValue(TWO_PAGE_RESULT);
|
|
const user = userEvent.setup();
|
|
renderPage();
|
|
await screen.findByText("SKU-002");
|
|
|
|
await user.click(screen.getByRole("button", { name: "SKU code" }));
|
|
|
|
await waitFor(() => expect(memoryRouter.getSearch().get("soh.sortBy")).toBe("skuCode"));
|
|
expect(memoryRouter.getSearch().get("soh.page")).toBeNull();
|
|
});
|
|
|
|
it("the export uses the chosen sort", async () => {
|
|
const downloadSpy = vi.spyOn(xlsxModule, "downloadXlsx").mockImplementation(() => {});
|
|
const user = userEvent.setup();
|
|
renderPage();
|
|
await screen.findByText("SKU-001");
|
|
await user.click(screen.getByRole("button", { name: "SKU name" }));
|
|
await waitFor(() => expect(svc.getStockOnHand).toHaveBeenLastCalledWith(expect.objectContaining({ sortBy: "skuName" })));
|
|
svc.getStockOnHand.mockClear();
|
|
|
|
await user.click(screen.getByRole("button", { name: /export \.xlsx/i }));
|
|
|
|
await waitFor(() => expect(downloadSpy).toHaveBeenCalledTimes(1));
|
|
expect(svc.getStockOnHand).toHaveBeenCalledWith(expect.objectContaining({ sortBy: "skuName", sortDir: "asc" }));
|
|
downloadSpy.mockRestore();
|
|
});
|
|
});
|