Files
co-lite/solvway-admin-portal/app/lib/AdminAuthContext.refundsOff.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

145 lines
6.5 KiB
TypeScript

import { render, screen, waitFor } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import type { AdminModule, WebOrderDetail } from "./types";
// BABYBOO-56: admin refunds are switched off by default. Exercised through the real AdminAuthProvider
// with a session whose aclMenu contains BO_REFUND_REQUESTS (no switch module imported or mocked).
const svc = vi.hoisted(() => ({ getRefundEligibility: vi.fn(), raiseRefund: vi.fn(), getShipmentCancelQuote: vi.fn(), cancelShipment: vi.fn() }));
vi.mock("@/app/lib/services/adminRefunds", () => ({
getRefundEligibility: (u: string) => svc.getRefundEligibility(u),
raiseRefund: (b: unknown) => svc.raiseRefund(b),
getShipmentCancelQuote: (u: string) => svc.getShipmentCancelQuote(u),
cancelShipment: (u: string, b: unknown) => svc.cancelShipment(u, b),
}));
import { AdminAuthProvider, useAdminAuth, flattenModules } from "./AdminAuthContext";
import { useAclSidebar } from "./useAclSidebar";
import { RequireModule } from "./RequireModule";
import { CancelShipmentAction } from "@/app/components/refunds/CancelShipmentAction";
import { RaiseRefundAction } from "@/app/orders/web/[uuid]/RaiseRefundAction";
const ACL: AdminModule = {
name: "root",
type: "R",
children: [
{ name: "BO_WEB_ORDERS", type: "M", url: "/orders/web" },
{ name: "BO_REFUND_REQUESTS", type: "M", url: "/orders/refunds" },
],
};
beforeEach(() => {
svc.getShipmentCancelQuote.mockReset().mockResolvedValue({ cancellable: true, lines: [], shippingFee: 0, total: 0 });
svc.getRefundEligibility.mockReset().mockResolvedValue({
eligible: true, reason: null, windowEndsAt: "2026-11-01", member: false, overridable: false,
lines: [{ orderDetailsId: 21, productName: "BA-001", bought: 2, refunded: 0, pending: 0, refundable: 2, netUnitPrice: 35 }],
});
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({
ok: true,
status: 200,
json: async () => ({ name: "Super", roles: [{ name: "ROLE_ADMIN" }], aclMenu: ACL }),
} as Response),
);
});
afterEach(() => {
vi.unstubAllGlobals();
});
function Ready({ children }: { children: React.ReactNode }) {
const { loading } = useAdminAuth();
return loading ? null : <><div data-testid="ready" />{children}</>;
}
const settle = () => new Promise((r) => setTimeout(r, 30));
describe("admin refunds switched off (default)", () => {
it("hides BO_REFUND_REQUESTS from hasModule and the aclMenu tree, keeping other modules", async () => {
let auth!: ReturnType<typeof useAdminAuth>;
function Grab() {
// eslint-disable-next-line react-hooks/globals -- test-only probe that captures the hook's value for the assertions below.
auth = useAdminAuth();
return null;
}
render(<AdminAuthProvider><Ready><Grab /></Ready></AdminAuthProvider>);
await screen.findByTestId("ready");
expect(auth.hasModule("BO_REFUND_REQUESTS")).toBe(false);
expect(auth.hasModule("/orders/refunds")).toBe(false);
expect(flattenModules(auth.aclMenu).map((m) => m.name)).not.toContain("BO_REFUND_REQUESTS");
expect(auth.hasModule("BO_WEB_ORDERS")).toBe(true);
});
it("scenario 1: sidebar has no Refund requests entry", async () => {
function Links() {
const flat = (ls: ReturnType<typeof useAclSidebar>): string[] => ls.flatMap((l) => [`${l.name}|${l.url}`, ...flat(l.children)]);
return <div data-testid="names">{flat(useAclSidebar()).join(",")}</div>;
}
render(<AdminAuthProvider><Ready><Links /></Ready></AdminAuthProvider>);
await screen.findByTestId("ready");
const text = screen.getByTestId("names").textContent ?? "";
expect(text).not.toContain("BO_REFUND_REQUESTS");
expect(text).not.toContain("/orders/refunds");
expect(text).toContain("BO_WEB_ORDERS");
});
it("scenario 2: /orders/refunds renders Not authorised, not the queue", async () => {
render(
<AdminAuthProvider>
<RequireModule pathname="/orders/refunds"><div>refund queue</div></RequireModule>
</AdminAuthProvider>,
);
await waitFor(() => expect(screen.getByTestId("not-authorized")).toBeInTheDocument());
expect(screen.queryByText("refund queue")).toBeNull();
});
it("scenario 3: invoiced order detail does not offer Raise refund", async () => {
const order = { uuid: "O-9", documentNo: "IN00000080", status: "Y" } as WebOrderDetail;
render(<AdminAuthProvider><Ready><RaiseRefundAction order={order} /></Ready></AdminAuthProvider>);
await screen.findByTestId("ready");
await settle();
expect(screen.queryByRole("button", { name: "Refund" })).toBeNull();
expect(svc.getRefundEligibility).not.toHaveBeenCalled();
});
it("hasGrantedModule sees BO_REFUND_REQUESTS while hasModule does not", async () => {
let auth!: ReturnType<typeof useAdminAuth>;
function Grab() {
// eslint-disable-next-line react-hooks/globals -- test-only probe that captures the hook's value for the assertions below.
auth = useAdminAuth();
return null;
}
render(<AdminAuthProvider><Ready><Grab /></Ready></AdminAuthProvider>);
await screen.findByTestId("ready");
expect(auth.hasModule("BO_REFUND_REQUESTS")).toBe(false);
expect(auth.hasGrantedModule("BO_REFUND_REQUESTS")).toBe(true);
expect(auth.hasGrantedModule("/orders/refunds")).toBe(true);
expect(auth.hasGrantedModule("BO_NOT_GRANTED")).toBe(false);
});
it("Cancel shipment stays available when the module is granted", async () => {
render(<AdminAuthProvider><Ready><CancelShipmentAction deliveryOrderUuid="DO-1" /></Ready></AdminAuthProvider>);
await screen.findByTestId("ready");
expect(await screen.findByRole("button", { name: /cancel shipment/i })).toBeInTheDocument();
expect(svc.getShipmentCancelQuote).toHaveBeenCalledWith("DO-1");
});
it("Cancel shipment needs the module", async () => {
const noRefunds: AdminModule = { name: "root", type: "R", children: [{ name: "BO_WEB_ORDERS", type: "M", url: "/orders/web" }] };
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({
ok: true,
status: 200,
json: async () => ({ name: "Super", roles: [{ name: "ROLE_ADMIN" }], aclMenu: noRefunds }),
} as Response),
);
render(<AdminAuthProvider><Ready><CancelShipmentAction deliveryOrderUuid="DO-1" /></Ready></AdminAuthProvider>);
await screen.findByTestId("ready");
await settle();
expect(screen.queryByRole("button", { name: /cancel shipment/i })).toBeNull();
expect(svc.getShipmentCancelQuote).not.toHaveBeenCalled();
});
});