Files
co-lite/solvway-admin-portal/app/inventory/page.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

286 lines
11 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
// The Inventory page (merge-inventory-page): Stock on hand and History tabs plus the Stock in /
// Transfer / Adjust forms, each gated by its own module, with tab, form and History filters in the
// URL. The reports and forms are stubbed; they have their own tests.
const auth = vi.hoisted(() => ({ hasModule: vi.fn(), loading: false }));
vi.mock("@/app/lib/AdminAuthContext", () => ({
useAdminAuth: () => ({ hasModule: auth.hasModule, loading: auth.loading }),
}));
const router = vi.hoisted(() => {
let search = new URLSearchParams();
const listeners = new Set<() => void>();
return {
getSearch: () => search,
subscribe: (l: () => void) => {
listeners.add(l);
return () => listeners.delete(l);
},
replace: vi.fn((url: string) => {
search = new URLSearchParams(url.split("?")[1] ?? "");
listeners.forEach(l => l());
}),
set: (qs: string) => {
search = new URLSearchParams(qs);
},
};
});
vi.mock("next/navigation", async () => {
const { useSyncExternalStore } = await import("react");
return {
usePathname: () => "/inventory",
useSearchParams: () => useSyncExternalStore(router.subscribe, router.getSearch, router.getSearch),
useRouter: () => ({ replace: router.replace }),
};
});
vi.mock("@/app/components/inventory/StockOnHandReport", () => ({
StockOnHandReport: (p: {
onViewMovements: (skuCode: string) => void;
onWarehouseChange: (id?: string) => void;
reloadKey: number;
}) => (
<div>
<p>SOH</p>
<p>reload={p.reloadKey}</p>
<button onClick={() => p.onViewMovements("17")}>view variation 17</button>
<button onClick={() => p.onWarehouseChange("7")}>pick warehouse 7</button>
</div>
),
}));
vi.mock("@/app/components/inventory/MovementHistoryReport", () => ({
MovementHistoryReport: () => <p>HISTORY</p>,
}));
vi.mock("@/app/components/inventory/StockCountsTab", () => ({
StockCountsTab: () => <p>COUNTS</p>,
}));
type FormStubProps = { defaultWarehouseId?: string; onSubmitted?: () => void; onDirtyChange?: (d: boolean) => void };
// Hoisted so the vi.mock factories below can use it.
const { formStub } = vi.hoisted(() => ({
formStub: (label: string) =>
function FormStub(p: FormStubProps) {
return (
<div>
<p>
{label} default={p.defaultWarehouseId ?? ""}
</p>
<button onClick={() => p.onDirtyChange?.(true)}>make dirty</button>
<button onClick={() => p.onSubmitted?.()}>fake submit</button>
</div>
);
},
}));
vi.mock("@/app/components/inventory/StockInForm", () => ({ StockInForm: formStub("STOCK IN FORM") }));
vi.mock("@/app/components/inventory/TransferForm", () => ({ TransferForm: formStub("TRANSFER FORM") }));
vi.mock("@/app/components/inventory/AdjustmentForm", () => ({ AdjustmentForm: formStub("ADJUST FORM") }));
import InventoryPage from "./page";
const ALL = ["BO_STOCK_ON_HAND", "BO_MOVEMENT_HISTORY", "BO_STOCK_IN", "BO_STOCK_TRANSFER", "BO_STOCK_ADJUSTMENT"];
const grant = (...mods: string[]) => auth.hasModule.mockImplementation((m: string) => mods.includes(m));
beforeEach(() => {
auth.hasModule.mockReset();
auth.loading = false;
router.replace.mockClear();
router.set("");
});
describe("Inventory page — tabs, actions and gating", () => {
// add-stock-count-event-closeout: the Stock counts tab shows to either stock count module.
it("shows the Stock counts tab to a count-only or approve-only user", async () => {
for (const moduleName of ["BO_STOCK_COUNT", "BO_STOCK_COUNT_APPROVE"]) {
grant(moduleName);
router.set("tab=counts");
const { unmount } = render(<InventoryPage />);
expect(await screen.findByText("COUNTS")).toBeInTheDocument();
expect(screen.getByRole("tab", { name: "Stock counts", selected: true })).toBeInTheDocument();
unmount();
}
});
it("hides the Stock counts tab without a stock count module", async () => {
grant(...ALL);
render(<InventoryPage />);
await screen.findByText("SOH");
expect(screen.queryByRole("tab", { name: "Stock counts" })).not.toBeInTheDocument();
});
it("opens on Stock on hand with all three actions for a full user", async () => {
grant(...ALL);
render(<InventoryPage />);
expect(await screen.findByText("SOH")).toBeInTheDocument();
expect(screen.getByRole("heading", { level: 1, name: "Inventory" })).toBeInTheDocument();
expect(screen.getByRole("tab", { name: "Stock on hand", selected: true })).toBeInTheDocument();
for (const name of ["Stock in", "Transfer", "Adjust"]) {
expect(screen.getByRole("button", { name })).toBeInTheDocument();
}
});
it("restores the History tab from the URL", async () => {
grant(...ALL);
router.set("tab=history");
render(<InventoryPage />);
expect(await screen.findByText(/HISTORY/)).toBeInTheDocument();
expect(screen.getByRole("tab", { name: "History", selected: true })).toBeInTheDocument();
});
it("switches tab through the URL", async () => {
const user = userEvent.setup();
grant(...ALL);
render(<InventoryPage />);
await user.click(await screen.findByRole("tab", { name: "History" }));
expect(router.replace).toHaveBeenLastCalledWith("/inventory?tab=history", { scroll: false });
expect(await screen.findByText(/HISTORY/)).toBeInTheDocument();
});
it("lands a History-only user on History with no Stock on hand tab", async () => {
grant("BO_MOVEMENT_HISTORY");
render(<InventoryPage />);
expect(await screen.findByText(/HISTORY/)).toBeInTheDocument();
expect(screen.queryByRole("tab", { name: "Stock on hand" })).not.toBeInTheDocument();
});
it("ignores a tab the user does not hold", async () => {
grant("BO_STOCK_ON_HAND");
router.set("tab=history");
render(<InventoryPage />);
expect(await screen.findByText("SOH")).toBeInTheDocument();
expect(screen.queryByText(/HISTORY/)).not.toBeInTheDocument();
});
it("hides an action the user does not hold, even when the URL names it", async () => {
grant("BO_STOCK_ON_HAND", "BO_STOCK_IN");
router.set("action=adjust");
render(<InventoryPage />);
await screen.findByText("SOH");
expect(screen.queryByRole("button", { name: "Adjust" })).not.toBeInTheDocument();
expect(screen.queryByText(/ADJUST FORM/)).not.toBeInTheDocument();
});
it("shows actions and the no-reports message to a form-only user", async () => {
grant("BO_STOCK_IN");
render(<InventoryPage />);
expect(await screen.findByText("No stock reports on your role")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Stock in" })).toBeInTheDocument();
expect(screen.queryByRole("tab")).not.toBeInTheDocument();
});
it("is not authorised without any inventory module", async () => {
grant();
render(<InventoryPage />);
expect(await screen.findByTestId("not-authorized")).toBeInTheDocument();
});
it("View movements writes mv.sku and mv.warehouse and clears the other mv.* filters", async () => {
const user = userEvent.setup();
grant(...ALL);
router.set("mv.sku=OLD&mv.type=TRF&mv.from=2026-09-01&mv.to=2026-09-30&mv.page=3");
render(<InventoryPage />);
await user.click(await screen.findByRole("button", { name: "pick warehouse 7" }));
await user.click(screen.getByRole("button", { name: "view variation 17" }));
const q = new URLSearchParams((router.replace.mock.lastCall?.[0] as string).split("?")[1]);
expect(Object.fromEntries(q)).toEqual({ tab: "history", "mv.sku": "17", "mv.warehouse": "7" });
expect(await screen.findByText("HISTORY")).toBeInTheDocument();
});
it("rewrites an external ?variation=&warehouse= link once to mv.sku and mv.warehouse", async () => {
grant(...ALL);
router.set("tab=history&variation=123&warehouse=7");
render(<InventoryPage />);
await waitFor(() => expect(router.replace).toHaveBeenCalledTimes(1));
const q = new URLSearchParams((router.replace.mock.lastCall?.[0] as string).split("?")[1]);
expect(Object.fromEntries(q)).toEqual({ tab: "history", "mv.sku": "123", "mv.warehouse": "7" });
});
});
describe("Inventory page — side panel", () => {
it("opens the Transfer form in a panel pre-filled with the Stock on hand warehouse filter", async () => {
const user = userEvent.setup();
grant(...ALL);
render(<InventoryPage />);
await user.click(await screen.findByRole("button", { name: "pick warehouse 7" }));
await user.click(screen.getByRole("button", { name: "Transfer" }));
expect(router.replace).toHaveBeenLastCalledWith("/inventory?action=transfer", { scroll: false });
expect(await screen.findByText("TRANSFER FORM default=7")).toBeInTheDocument();
expect(screen.getByRole("dialog", { name: "Transfer" })).toBeInTheDocument();
});
it("opens the form named by the URL", async () => {
grant(...ALL);
router.set("tab=history&action=transfer");
render(<InventoryPage />);
expect(await screen.findByText(/HISTORY/)).toBeInTheDocument();
expect(await screen.findByText(/TRANSFER FORM/)).toBeInTheDocument();
});
it("a submit reloads the open tab and keeps the panel open", async () => {
const user = userEvent.setup();
grant(...ALL);
router.set("action=stock-in");
render(<InventoryPage />);
expect(await screen.findByText("reload=0")).toBeInTheDocument();
await user.click(await screen.findByRole("button", { name: "fake submit" }));
expect(await screen.findByText("reload=1")).toBeInTheDocument();
expect(screen.getByText(/STOCK IN FORM/)).toBeInTheDocument();
});
it("closing a clean panel removes action from the URL", async () => {
const user = userEvent.setup();
grant(...ALL);
router.set("action=stock-in");
render(<InventoryPage />);
await screen.findByText(/STOCK IN FORM/);
await user.click(screen.getByRole("button", { name: "Close" }));
expect(router.replace).toHaveBeenLastCalledWith("/inventory", { scroll: false });
await waitFor(() => expect(screen.queryByText(/STOCK IN FORM/)).not.toBeInTheDocument());
});
it("closing a dirty panel asks first; Keep editing keeps it, Discard closes it", async () => {
const user = userEvent.setup();
grant(...ALL);
router.set("action=adjust");
render(<InventoryPage />);
await user.click(await screen.findByRole("button", { name: "make dirty" }));
await user.click(screen.getByRole("button", { name: "Close" }));
expect(await screen.findByText("Discard changes?")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "Keep editing" }));
await waitFor(() => expect(screen.queryByText("Discard changes?")).not.toBeInTheDocument());
expect(screen.getByText(/ADJUST FORM/)).toBeInTheDocument();
expect(router.replace).not.toHaveBeenCalled();
await user.click(screen.getByRole("button", { name: "Close" }));
await user.click(await screen.findByRole("button", { name: "Discard" }));
expect(router.replace).toHaveBeenLastCalledWith("/inventory", { scroll: false });
await waitFor(() => expect(screen.queryByText(/ADJUST FORM/)).not.toBeInTheDocument());
});
});