import { beforeEach, describe, expect, it, vi } from "vitest"; import { HttpError } from "@/lib/security/http"; const authorizeMobileSlip = vi.fn(); const consumeMobileSlipLink = vi.fn(); const recordMobileSlipError = vi.fn(); const verifyAndCreateTicket = vi.fn(); const limitRequest = vi.fn(); vi.mock("@/lib/commission/mobile-slip", () => ({ authorizeMobileSlip, consumeMobileSlipLink, recordMobileSlipError, })); vi.mock("@/lib/commission/slip-upload", () => ({ MAX_SLIP_BYTES: 6 * 1024 * 1024, verifyAndCreateTicket })); vi.mock("@/lib/security/rate-limit", () => ({ limitRequest })); const { GET, POST } = await import("./route"); const token = "x".repeat(43); const checkout = { id: "checkout-1", userId: "customer-1", amountBaht: 150 }; function upload(origin = "https://guide.sudloh.com") { const form = new FormData(); form.set("file", new File(["image"], "slip.png", { type: "image/png" })); return new Request("https://guide.sudloh.com/api/commission/mobile-slip", { method: "POST", headers: { Origin: origin, Authorization: `Bearer ${token}` }, body: form, }); } describe("commission phone slip upload", () => { beforeEach(() => { process.env.BETTER_AUTH_URL = "https://guide.sudloh.com"; vi.clearAllMocks(); authorizeMobileSlip.mockResolvedValue({ checkout, ticketId: null, digest: "digest-1" }); verifyAndCreateTicket.mockResolvedValue({ ticketId: "ticket-1", created: true }); consumeMobileSlipLink.mockResolvedValue(undefined); recordMobileSlipError.mockResolvedValue(undefined); }); it("checks the bearer link without requiring a login", async () => { const response = await GET(new Request("https://guide.sudloh.com/api/commission/mobile-slip", { headers: { Authorization: `Bearer ${token}` }, })); expect(response.status).toBe(200); expect(await response.json()).toEqual({ amountBaht: 150, complete: false }); expect(authorizeMobileSlip).toHaveBeenCalledWith(token); }); it("verifies a phone slip and consumes the link", async () => { const response = await POST(upload()); expect(response.status).toBe(201); expect(verifyAndCreateTicket).toHaveBeenCalledWith(checkout, expect.any(File)); expect(consumeMobileSlipLink).toHaveBeenCalledWith("checkout-1", "digest-1"); }); it("rejects cross-origin uploads before using the link", async () => { expect((await POST(upload("https://example.com"))).status).toBe(403); expect(authorizeMobileSlip).not.toHaveBeenCalled(); }); it("reports verification failures for the desktop and permits retry", async () => { const failure = new HttpError(422, "slip-rejected:200402"); verifyAndCreateTicket.mockRejectedValueOnce(failure); const response = await POST(upload()); expect(response.status).toBe(422); expect(recordMobileSlipError).toHaveBeenCalledWith("digest-1", "customer-1", failure); expect(consumeMobileSlipLink).not.toHaveBeenCalled(); }); });