import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; 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, POST } from "./route"; type Ctx = { params: Promise<{ path: string[] }> }; const ctx = (...path: string[]): Ctx => ({ params: Promise.resolve({ path }) }); function req(method: string, body?: unknown) { return new Request("http://localhost/api/fulfilment/x", { method, body: body === undefined ? undefined : JSON.stringify(body), }) as unknown as Parameters[0]; } const fetchMock = vi.fn(); beforeEach(() => { mocks.callMobileApi.mockReset(); mocks.getToken.mockReset(); mocks.getToken.mockResolvedValue("jwt-abc"); fetchMock.mockReset(); vi.stubGlobal("fetch", fetchMock); vi.stubEnv("MOBILE_API_BASE_URL", "http://mapi"); vi.stubEnv("MOBILE_API_KEY", "k"); }); afterEach(() => { vi.unstubAllGlobals(); vi.unstubAllEnvs(); }); describe("/api/fulfilment/[...path] (add-manual-fulfilment-console)", () => { it("returns 401 without a session and calls nothing", async () => { mocks.getToken.mockResolvedValue(null); expect((await GET(req("GET"), ctx("batches", "7"))).status).toBe(401); expect((await POST(req("POST", {}), ctx("batches"))).status).toBe(401); expect(mocks.callMobileApi).not.toHaveBeenCalled(); expect(fetchMock).not.toHaveBeenCalled(); }); it("forwards batch reads with the admin JWT", async () => { mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 7, status: "RUNNING" } }); const res = await GET(req("GET"), ctx("batches", "7")); expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/fulfilment/batches/7", { token: "jwt-abc" }); expect(await res.json()).toEqual({ id: 7, status: "RUNNING" }); await GET(req("GET"), ctx("batches", "7", "failures")); expect(mocks.callMobileApi).toHaveBeenLastCalledWith("/api/admin/fulfilment/batches/7/failures", { token: "jwt-abc" }); }); it("forwards POSTs for batches, tracking batches and export with their body", async () => { mocks.callMobileApi.mockResolvedValue({ ok: true, data: { id: 1 } }); for (const p of [["batches"], ["batches", "tracking"], ["export"]]) { const res = await POST(req("POST", { type: "ISSUE", uuids: ["a"] }), ctx(...p)); expect(res.status).toBe(200); expect(mocks.callMobileApi).toHaveBeenLastCalledWith(`/api/admin/fulfilment/${p.join("/")}`, { method: "POST", body: { type: "ISSUE", uuids: ["a"] }, token: "jwt-abc" }); } }); it("passes an upstream 400 message through", async () => { mocks.callMobileApi.mockResolvedValue({ ok: false, status: 400, error: "A batch can hold at most 10,000 delivery orders" }); const res = await POST(req("POST", { type: "ISSUE", filter: {} }), ctx("batches")); expect(res.status).toBe(400); expect(await res.json()).toEqual({ error: "A batch can hold at most 10,000 delivery orders" }); }); it("404s any path outside the allow-list without calling upstream", async () => { for (const p of [["..", "users"], ["batches", "x"], ["batches", "7", "items"], ["print", "x"], ["export", "1"]]) { expect((await GET(req("GET"), ctx(...p))).status).toBe(404); expect((await POST(req("POST", {}), ctx(...p))).status).toBe(404); } // GET is only for batch reads; a GET of a POST-only path is also 404 for (const p of [["batches"], ["export"], ["print"], ["batches", "tracking"]]) { expect((await GET(req("GET"), ctx(...p))).status).toBe(404); } // POST is never allowed on a batch read path expect((await POST(req("POST", {}), ctx("batches", "7"))).status).toBe(404); expect(mocks.callMobileApi).not.toHaveBeenCalled(); expect(fetchMock).not.toHaveBeenCalled(); }); it("rejects a non-JSON body with 400", async () => { const bad = new Request("http://localhost/api/fulfilment/batches", { method: "POST", body: "not json" }) as unknown as Parameters[0]; expect((await POST(bad, ctx("batches"))).status).toBe(400); expect(mocks.callMobileApi).not.toHaveBeenCalled(); }); it("print streams the PDF bytes and the skipped-drafts count", async () => { const pdf = new Uint8Array([0x25, 0x50, 0x44, 0x46]); fetchMock.mockResolvedValue(new Response(pdf, { status: 200, headers: { "content-type": "application/pdf", "x-skipped-drafts": "2" }, })); const res = await POST(req("POST", { uuids: ["a", "b"] }), ctx("print")); expect(fetchMock).toHaveBeenCalledTimes(1); const [url, init] = fetchMock.mock.calls[0]; expect(url).toBe("http://mapi/api/admin/fulfilment/print"); expect(init.method).toBe("POST"); expect(init.headers).toMatchObject({ "api-key": "k", Authorization: "Bearer jwt-abc", "Content-Type": "application/json" }); expect(JSON.parse(init.body)).toEqual({ uuids: ["a", "b"] }); expect(res.status).toBe(200); expect(res.headers.get("content-type")).toBe("application/pdf"); expect(res.headers.get("x-skipped-drafts")).toBe("2"); expect(new Uint8Array(await res.arrayBuffer())).toEqual(pdf); }); it("print turns an upstream 400 into a JSON error with its message", async () => { fetchMock.mockResolvedValue(new Response(JSON.stringify({ message: "Print at most 200 delivery orders at a time" }), { status: 400 })); const res = await POST(req("POST", { filter: {} }), ctx("print")); expect(res.status).toBe(400); expect(await res.json()).toEqual({ error: "Print at most 200 delivery orders at a time" }); }); it("print maps an upstream 401 to 401 and a 5xx to 502", async () => { fetchMock.mockResolvedValueOnce(new Response("", { status: 401 })); expect((await POST(req("POST", { uuids: ["a"] }), ctx("print"))).status).toBe(401); fetchMock.mockResolvedValueOnce(new Response("boom", { status: 500 })); expect((await POST(req("POST", { uuids: ["a"] }), ctx("print"))).status).toBe(502); }); });