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
131 lines
6.3 KiB
TypeScript
131 lines
6.3 KiB
TypeScript
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
|
import { existsSync, readdirSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
|
|
const api = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn() }));
|
|
vi.mock("@/app/lib/clientApi", async (orig) => ({
|
|
...(await orig<typeof import("@/app/lib/clientApi")>()),
|
|
apiGet: api.apiGet,
|
|
apiPost: api.apiPost,
|
|
}));
|
|
import { ApiError } from "@/app/lib/clientApi";
|
|
import * as svc from "./adminMessages";
|
|
|
|
beforeEach(() => {
|
|
api.apiGet.mockReset().mockResolvedValue({});
|
|
api.apiPost.mockReset().mockResolvedValue({});
|
|
});
|
|
afterEach(() => vi.unstubAllGlobals());
|
|
|
|
describe("adminMessages client", () => {
|
|
it("maps inbox tabs to query params (page is 1-based in, 0-based out)", async () => {
|
|
await svc.listAdminConversations({ tab: "ALL", q: "" }, 1, 20);
|
|
await svc.listAdminConversations({ tab: "UNREAD", q: "" }, 2, 20);
|
|
await svc.listAdminConversations({ tab: "S", q: "ahmad" }, 1, 20);
|
|
await svc.listAdminConversations({ tab: "B", q: "" }, 1, 20);
|
|
expect(api.apiGet.mock.calls.map((c) => c[0])).toEqual([
|
|
"/api/admin/member-messages?page=0&size=20",
|
|
"/api/admin/member-messages?unreadOnly=true&page=1&size=20",
|
|
"/api/admin/member-messages?types=S&q=ahmad&page=0&size=20",
|
|
"/api/admin/member-messages?types=B&page=0&size=20",
|
|
]);
|
|
});
|
|
|
|
it("builds thread, paging and mutation calls", async () => {
|
|
await svc.listAdminMessages("c1");
|
|
await svc.listAdminMessages("c1", "m9", 10);
|
|
await svc.sendAdminMessage("c1", "hi", ["r1"]);
|
|
await svc.markAdminRead("c1");
|
|
await svc.startAdminConversation("MY5", "yo", []);
|
|
expect(api.apiGet.mock.calls.map((c) => c[0])).toEqual([
|
|
"/api/admin/member-messages/c1/messages?size=30",
|
|
"/api/admin/member-messages/c1/messages?before=m9&size=10",
|
|
]);
|
|
expect(api.apiPost.mock.calls).toEqual([
|
|
["/api/admin/member-messages/c1/messages", { body: "hi", imageRefs: ["r1"] }],
|
|
["/api/admin/member-messages/c1/read"],
|
|
["/api/admin/member-messages/start", { memberCode: "MY5", body: "yo", imageRefs: [] }],
|
|
]);
|
|
});
|
|
|
|
it("previews and sends broadcasts", async () => {
|
|
const target = { kind: "DOWNLINE", code: "MY2", includeSelf: true } as const;
|
|
await svc.previewBroadcast(target);
|
|
await svc.sendBroadcast(target, "Subj", "Body", ["r1"]);
|
|
expect(api.apiPost.mock.calls).toEqual([
|
|
["/api/admin/member-messages/broadcasts/preview", { target }],
|
|
["/api/admin/member-messages/broadcasts", { target, subject: "Subj", body: "Body", imageRefs: ["r1"] }],
|
|
]);
|
|
});
|
|
|
|
it("validates images by type and size", () => {
|
|
const f = (type: string, size = 10) => new File([new Uint8Array(size)], "x", { type });
|
|
expect(svc.validateImage(f("image/png"))).toBeNull();
|
|
expect(svc.validateImage(f("image/jpeg", svc.MAX_IMAGE_BYTES))).toBeNull();
|
|
expect(svc.validateImage(f("image/webp"))).toBe("type");
|
|
expect(svc.validateImage(f("image/gif"))).toBe("type");
|
|
expect(svc.validateImage(f("image/png", svc.MAX_IMAGE_BYTES + 1))).toBe("size");
|
|
});
|
|
|
|
it("messageErrorText maps a known reason (coded or raw text) to its friendly key and keeps other text", () => {
|
|
const t = (k: string) => `[${k}]`;
|
|
expect(svc.messageErrorText(new ApiError("EMPTY_TARGET", 400, { error: "EMPTY_TARGET", code: "EMPTY_TARGET" }), t)).toBe("[MsgErr_EMPTY_TARGET]");
|
|
expect(svc.messageErrorText(new Error("EMPTY_TARGET"), t)).toBe("[MsgErr_EMPTY_TARGET]");
|
|
expect(svc.messageErrorText(new Error("MESSAGE_INVALID: body too long"), t)).toBe("[MsgErr_MESSAGE_INVALID]");
|
|
expect(svc.messageErrorText(new Error("Upstream down"), t)).toBe("Upstream down");
|
|
expect(svc.messageErrorText("not an error", t, "MsgSendFailed")).toBe("[MsgSendFailed]");
|
|
});
|
|
|
|
it("uploads multipart and surfaces the BFF error message", async () => {
|
|
const fetchMock = vi.fn().mockResolvedValueOnce(new Response(JSON.stringify({ ref: "messages/admin/a.png" }), { status: 200 }));
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
const file = new File(["x"], "a.png", { type: "image/png" });
|
|
expect(await svc.uploadAdminMessageImage(file)).toEqual({ ref: "messages/admin/a.png" });
|
|
expect(fetchMock.mock.calls[0][0]).toBe("/api/admin/member-messages/images");
|
|
expect(fetchMock.mock.calls[0][1].body).toBeInstanceOf(FormData);
|
|
|
|
fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ error: "Too big" }), { status: 400 }));
|
|
await expect(svc.uploadAdminMessageImage(file)).rejects.toThrow("Too big");
|
|
});
|
|
});
|
|
|
|
// Memory lesson: a service URL that matches no route.ts 404s in production while mocked tests stay green.
|
|
function routeExists(url: string): boolean {
|
|
const root = join(__dirname, "..", "..", "api");
|
|
const segs = url.split("?")[0].replace(/^\/api\//, "").split("/");
|
|
const walk = (dir: string, i: number): boolean => {
|
|
if (i === segs.length) return existsSync(join(dir, "route.ts"));
|
|
if (existsSync(join(dir, segs[i])) && walk(join(dir, segs[i]), i + 1)) return true;
|
|
return readdirSync(dir, { withFileTypes: true }).some(
|
|
(d) => d.isDirectory() && /^\[\w+\]$/.test(d.name) && walk(join(dir, d.name), i + 1),
|
|
);
|
|
};
|
|
return walk(root, 0);
|
|
}
|
|
|
|
describe("every service URL has a BFF route.ts", () => {
|
|
it("resolves each URL the client can produce to an existing route file", async () => {
|
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("{}", { status: 200 })));
|
|
const t = { kind: "ALL" } as const;
|
|
await svc.listAdminConversations({ tab: "ALL", q: "" }, 1, 20);
|
|
await svc.getAdminUnreadCount();
|
|
await svc.getAdminConversationByMember("MY5");
|
|
await svc.getAdminConversation("c1");
|
|
await svc.listAdminMessages("c1");
|
|
await svc.sendAdminMessage("c1", "x", []);
|
|
await svc.markAdminRead("c1");
|
|
await svc.startAdminConversation("MY5", "x", []);
|
|
await svc.previewBroadcast(t);
|
|
await svc.sendBroadcast(t, "s", "b", []);
|
|
await svc.uploadAdminMessageImage(new File(["x"], "a.png", { type: "image/png" }));
|
|
const urls = [
|
|
...api.apiGet.mock.calls.map((c) => c[0] as string),
|
|
...api.apiPost.mock.calls.map((c) => c[0] as string),
|
|
(vi.mocked(fetch).mock.calls[0][0] as string),
|
|
svc.adminMessageImageUrl("c1", "m1", 0),
|
|
];
|
|
expect(urls.length).toBeGreaterThanOrEqual(12);
|
|
for (const u of urls) expect(routeExists(u), u).toBe(true);
|
|
});
|
|
});
|