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
185 lines
10 KiB
TypeScript
185 lines
10 KiB
TypeScript
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
|
import type { NextRequest } from "next/server";
|
|
|
|
const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() }));
|
|
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi }));
|
|
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
|
|
|
|
import { GET as list } from "./route";
|
|
import { GET as unread } from "./unread-count/route";
|
|
import { GET as byKey } from "./by-key/route";
|
|
import { POST as start } from "./start/route";
|
|
import { POST as preview } from "./broadcasts/preview/route";
|
|
import { GET as broadcastList, POST as broadcast } from "./broadcasts/route";
|
|
import { GET as thread } from "./[uuid]/route";
|
|
import { GET as messages, POST as reply } from "./[uuid]/messages/route";
|
|
import { POST as read } from "./[uuid]/read/route";
|
|
import { GET as image } from "./[uuid]/messages/[messageUuid]/images/[index]/route";
|
|
import { POST as upload } from "./images/route";
|
|
|
|
const B = "http://localhost/api/admin/member-messages";
|
|
const req = (url: string, body?: unknown, method = body === undefined ? "GET" : "POST") =>
|
|
new Request(url, { method, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }) as unknown as NextRequest;
|
|
const c1 = { params: Promise.resolve({ uuid: "c1" }) };
|
|
|
|
beforeEach(() => {
|
|
mocks.callMobileApi.mockReset().mockResolvedValue({ ok: true, data: { fine: 1 } });
|
|
mocks.getToken.mockReset().mockResolvedValue("jwt");
|
|
process.env.MOBILE_API_BASE_URL = "http://up";
|
|
process.env.MOBILE_API_KEY = "k";
|
|
});
|
|
afterEach(() => vi.unstubAllGlobals());
|
|
|
|
const reply_ = { body: "hi", imageRefs: ["messages/admin/a.png"] };
|
|
const cases: [string, () => Promise<Response>, string, "GET" | "POST", unknown?][] = [
|
|
["list", () => list(req(`${B}?types=S&page=0&size=20`)), "/api/admin/member-messages?types=S&page=0&size=20", "GET"],
|
|
["unread-count", () => unread(req(`${B}/unread-count`)), "/api/admin/member-messages/unread-count", "GET"],
|
|
["by-key", () => byKey(req(`${B}/by-key?member=MY5`)), "/api/admin/member-messages/by-key?member=MY5", "GET"],
|
|
["thread", () => thread(req(`${B}/c1`), c1), "/api/admin/member-messages/c1", "GET"],
|
|
["messages GET", () => messages(req(`${B}/c1/messages?before=m9&size=30`), c1), "/api/admin/member-messages/c1/messages?before=m9&size=30", "GET"],
|
|
["reply", () => reply(req(`${B}/c1/messages`, reply_), c1), "/api/admin/member-messages/c1/messages", "POST", reply_],
|
|
["read", () => read(req(`${B}/c1/read`, undefined, "POST"), c1), "/api/admin/member-messages/c1/read", "POST"],
|
|
["start", () => start(req(`${B}/start`, { memberCode: "MY5", body: "yo", imageRefs: [] })), "/api/admin/member-messages/start", "POST", { memberCode: "MY5", body: "yo", imageRefs: [] }],
|
|
["preview", () => preview(req(`${B}/broadcasts/preview`, { target: { kind: "ALL" } })), "/api/admin/member-messages/broadcasts/preview", "POST", { target: { kind: "ALL" } }],
|
|
["broadcast", () => broadcast(req(`${B}/broadcasts`, { target: { kind: "ALL" }, subject: "s", body: "b", imageRefs: [] })), "/api/admin/member-messages/broadcasts", "POST", { target: { kind: "ALL" }, subject: "s", body: "b", imageRefs: [] }],
|
|
];
|
|
|
|
describe("admin messages BFF relays", () => {
|
|
it.each(cases)("%s forwards to mobile-api and returns its data", async (_n, call, path, method, body) => {
|
|
const res = await call();
|
|
expect(res.status).toBe(200);
|
|
expect(await res.json()).toEqual({ fine: 1 });
|
|
expect(mocks.callMobileApi).toHaveBeenCalledWith(
|
|
path,
|
|
expect.objectContaining({ method, token: "jwt", ...(body === undefined ? {} : { body }) }),
|
|
);
|
|
});
|
|
|
|
it.each(cases)("%s returns 401 with no session and never calls upstream", async (_n, call) => {
|
|
mocks.getToken.mockResolvedValue(null);
|
|
expect((await call()).status).toBe(401);
|
|
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
|
});
|
|
|
|
// mobile-api has no `code` field: the reason text is the whole error, so the relay derives the code.
|
|
it.each([
|
|
["EMPTY_TARGET", 400, 500],
|
|
["NOT_IN_NETWORK", 403, 500],
|
|
["MESSAGE_INVALID", 400, 500],
|
|
["MESSAGE_IMAGE_NOT_OWNED", 400, 500],
|
|
["MESSAGE_COMMIT_FAILED", 502, 500],
|
|
["MESSAGE_UPLOAD_FAILED", 502, 400],
|
|
])("derives code %s from the upstream reason text and answers %i", async (code, status, upstreamStatus) => {
|
|
mocks.callMobileApi.mockResolvedValue({ ok: false, error: `${code}: details`, status: upstreamStatus });
|
|
const res = await broadcast(req(`${B}/broadcasts`, { target: { kind: "LIST", codes: [] } }));
|
|
expect(res.status).toBe(status);
|
|
expect(await res.json()).toEqual({ error: code, code });
|
|
});
|
|
|
|
it("keeps 401 as 401, passes 404 through and adds no code to an unknown failure", async () => {
|
|
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Session expired", status: 401 });
|
|
expect((await thread(req(`${B}/c1`), c1)).status).toBe(401);
|
|
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Conversation not found", status: 404 });
|
|
const nf = await thread(req(`${B}/c1`), c1);
|
|
expect(nf.status).toBe(404);
|
|
expect(await nf.json()).toEqual({ error: "Conversation not found" });
|
|
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Something odd", status: 500 });
|
|
expect((await (await thread(req(`${B}/c1`), c1)).json()).code).toBeUndefined();
|
|
});
|
|
|
|
it("rejects a path-like conversation id before any upstream call", async () => {
|
|
const res = await thread(req(`${B}/x`), { params: Promise.resolve({ uuid: "../admin" }) });
|
|
expect(res.status).toBe(400);
|
|
expect(mocks.callMobileApi).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects a non-JSON body on POST", async () => {
|
|
const bad = new Request(`${B}/start`, { method: "POST", body: "{nope" }) as unknown as NextRequest;
|
|
expect((await start(bad)).status).toBe(400);
|
|
});
|
|
});
|
|
|
|
describe("GET image stream", () => {
|
|
const ctx = (index: string) => ({ params: Promise.resolve({ uuid: "c1", messageUuid: "m1", index }) });
|
|
|
|
it("streams the bytes with no-store and the upstream content type", async () => {
|
|
const f = vi.fn().mockResolvedValue(new Response(new Uint8Array([1, 2, 3]), { status: 200, headers: { "content-type": "image/png" } }));
|
|
vi.stubGlobal("fetch", f);
|
|
const res = await image(req(`${B}/c1/messages/m1/images/0`), ctx("0"));
|
|
expect(f.mock.calls[0][0]).toBe("http://up/api/admin/member-messages/c1/messages/m1/images/0");
|
|
expect(res.status).toBe(200);
|
|
expect(res.headers.get("content-type")).toBe("image/png");
|
|
expect(res.headers.get("cache-control")).toBe("private, no-store");
|
|
expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([1, 2, 3]));
|
|
});
|
|
|
|
it("maps upstream 404 to 404 and rejects a bad index", async () => {
|
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response("", { status: 404 })));
|
|
expect((await image(req(`${B}/c1/messages/m1/images/0`), ctx("0"))).status).toBe(404);
|
|
expect((await image(req(`${B}/c1/messages/m1/images/x`), ctx("x"))).status).toBe(400);
|
|
});
|
|
|
|
it("returns 401 with no session", async () => {
|
|
mocks.getToken.mockResolvedValue(null);
|
|
expect((await image(req(`${B}/c1/messages/m1/images/0`), ctx("0"))).status).toBe(401);
|
|
});
|
|
});
|
|
|
|
describe("POST images (multipart pass-through)", () => {
|
|
const withFile = (file: File | null) =>
|
|
({ formData: async () => ({ get: () => file }) }) as unknown as NextRequest;
|
|
|
|
it("forwards a valid png and returns the ref", async () => {
|
|
const f = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ref: "messages/admin/a.png" }), { status: 200 }));
|
|
vi.stubGlobal("fetch", f);
|
|
const res = await upload(withFile(new File(["x"], "a.png", { type: "image/png" })));
|
|
expect(res.status).toBe(200);
|
|
expect(await res.json()).toEqual({ ref: "messages/admin/a.png" });
|
|
expect(f.mock.calls[0][0]).toBe("http://up/api/admin/member-messages/images");
|
|
expect(f.mock.calls[0][1].headers.Authorization).toBe("Bearer jwt");
|
|
});
|
|
|
|
it("rejects a non-image type, an oversize file and a missing file without calling upstream", async () => {
|
|
const f = vi.fn();
|
|
vi.stubGlobal("fetch", f);
|
|
expect((await upload(withFile(new File(["x"], "a.gif", { type: "image/gif" })))).status).toBe(400);
|
|
expect((await upload(withFile(new File([new Uint8Array(5 * 1024 * 1024 + 1)], "a.png", { type: "image/png" })))).status).toBe(400);
|
|
expect((await upload(withFile(null))).status).toBe(400);
|
|
expect(f).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("derives the code from an upstream reason text (no code field upstream)", async () => {
|
|
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(JSON.stringify({ message: "MESSAGE_UPLOAD_FAILED" }), { status: 500 })));
|
|
const res = await upload(withFile(new File(["x"], "a.png", { type: "image/png" })));
|
|
expect(res.status).toBe(502);
|
|
expect(await res.json()).toEqual({ error: "MESSAGE_UPLOAD_FAILED", code: "MESSAGE_UPLOAD_FAILED" });
|
|
});
|
|
|
|
it("returns 401 with no session", async () => {
|
|
mocks.getToken.mockResolvedValue(null);
|
|
expect((await upload(withFile(null))).status).toBe(401);
|
|
});
|
|
});
|
|
|
|
// BABYBOO-54 B2: the list relay forwards sortBy/sortDir (param order not asserted).
|
|
describe("member-messages list sort forwarding", () => {
|
|
it("forwards sortBy and sortDir", async () => {
|
|
await list(req(`${B}?sortBy=time&sortDir=desc&page=0&size=20`));
|
|
const [url] = mocks.callMobileApi.mock.calls.at(-1)!;
|
|
const sp = new URLSearchParams(String(url).split("?")[1]);
|
|
expect(String(url).startsWith("/api/admin/member-messages?")).toBe(true);
|
|
expect([sp.get("sortBy"), sp.get("sortDir"), sp.get("page"), sp.get("size")]).toEqual(["time", "desc", "0", "20"]);
|
|
});
|
|
});
|
|
|
|
// BABYBOO-54 2.4: broadcasts relay forwards sortBy/sortDir.
|
|
describe("member-messages broadcasts sort forwarding", () => {
|
|
it("forwards sortBy and sortDir", async () => {
|
|
await broadcastList(req(`${B}/broadcasts?sortBy=read&sortDir=desc&page=0&size=20`));
|
|
const [url] = mocks.callMobileApi.mock.calls.at(-1)!;
|
|
const sp = new URLSearchParams(String(url).split("?")[1]);
|
|
expect(String(url).startsWith("/api/admin/member-messages/broadcasts?")).toBe(true);
|
|
expect([sp.get("sortBy"), sp.get("sortDir")]).toEqual(["read", "desc"]);
|
|
});
|
|
});
|