feat(admin-portal): xlsx export buttons on both lead listings

A binary mobile-api call with the same error shape, export proxy routes
that pass Content-Type and Content-Disposition through, and an Export
button under BO_LEADS_EXPORT that downloads with the current search or
filters and shows EXPORT_TOO_LARGE on the page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
ngqileandClaude Opus 5.5 committed 2026-11-27 17:09:23 +08:00
1 parent 82b6943474
commit 5f4f2705e8
16 files changed
+510 -80

No files matched your search

@@ -81,7 +81,7 @@ Design: `design.md` (decision numbers below refer to it). All tasks run serially
- Scope: `solvway-admin-portal/app/leads/**`, `solvway-admin-portal/app/api/leads/**`, `solvway-admin-portal/app/lib/**`, `solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/**`
- Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`.
- [ ] 4.2 Add the Export buttons (design decision 6):
- [x] 4.2 Add the Export buttons (design decision 6):
- a binary variant of `callMobileApi` with the same error shape;
- the `app/api/leads/export` and `app/api/event-leads/[eventUuid]/export` routes, which pass through `Content-Type` and `Content-Disposition`;
- an Export button on both listings when the user has `BO_LEADS_EXPORT`. It sends the current search or filters, downloads via Blob under the server's filename, shows `EXPORT_TOO_LARGE` and other errors on the page, and is disabled while running.
@@ -0,0 +1,45 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApiBinary: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApiBinary: mocks.callMobileApiBinary }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
type Req = Parameters<typeof GET>[0];
const req = (url: string) => new Request(`http://localhost${url}`) as unknown as Req;
const ctx = (eventUuid: string) => ({ params: Promise.resolve({ eventUuid }) });
beforeEach(() => {
mocks.callMobileApiBinary.mockReset();
mocks.getToken.mockReset().mockResolvedValue("jwt-abc");
});
describe("/api/event-leads/[eventUuid]/export", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await GET(req("/x"), ctx("e-1"))).status).toBe(401);
expect(mocks.callMobileApiBinary).not.toHaveBeenCalled();
});
it("forwards the query string and passes bytes and headers through", async () => {
mocks.callMobileApiBinary.mockResolvedValue({ ok: true, data: { body: new Uint8Array([9]).buffer, contentType: "application/x-xlsx", contentDisposition: 'attachment; filename="e.xlsx"' } });
const res = await GET(req("/x?status=OPEN&leadType=NEW"), ctx("e-1"));
expect(mocks.callMobileApiBinary).toHaveBeenCalledWith("/api/admin/event-leads/e-1/export?status=OPEN&leadType=NEW", { token: "jwt-abc" });
expect(res.headers.get("content-type")).toBe("application/x-xlsx");
expect(res.headers.get("content-disposition")).toBe('attachment; filename="e.xlsx"');
expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([9]));
});
it("maps a failure through errorResponse, keeping code and details", async () => {
mocks.callMobileApiBinary.mockResolvedValue({ ok: false, error: "Too many", status: 422, code: "EXPORT_TOO_LARGE", details: { limit: 20000 } });
const res = await GET(req("/x"), ctx("e-1"));
expect(res.status).toBe(422);
expect(await res.json()).toMatchObject({ code: "EXPORT_TOO_LARGE", details: { limit: 20000 } });
});
it("rejects dot segments", async () => {
expect((await GET(req("/x"), ctx(".."))).status).toBe(400);
expect(mocks.callMobileApiBinary).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,23 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApiBinary } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
// xlsx export of one event's leads; mobile-api owns validation and the BO_EVENT_LEADS + BO_LEADS_EXPORT guards.
type Ctx = { params: Promise<{ eventUuid: string }> };
export async function GET(req: NextRequest, { params }: Ctx) {
const token = await getToken();
if (!token) return unauthorized();
const { eventUuid } = await params;
if (eventUuid === "." || eventUuid === "..") return badRequest("Invalid path.");
const result = await callMobileApiBinary(`/api/admin/event-leads/${encodeURIComponent(eventUuid)}/export${new URL(req.url).search}`, { token });
if (!result.ok) return errorResponse(result);
const { body, contentType, contentDisposition } = result.data;
return new NextResponse(body, {
headers: {
...(contentType ? { "Content-Type": contentType } : {}),
...(contentDisposition ? { "Content-Disposition": contentDisposition } : {}),
},
});
}
@@ -0,0 +1,40 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ callMobileApiBinary: vi.fn(), getToken: vi.fn() }));
vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApiBinary: mocks.callMobileApiBinary }));
vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken }));
import { GET } from "./route";
type Req = Parameters<typeof GET>[0];
const req = (url: string) => new Request(`http://localhost${url}`) as unknown as Req;
beforeEach(() => {
mocks.callMobileApiBinary.mockReset();
mocks.getToken.mockReset().mockResolvedValue("jwt-abc");
});
describe("/api/leads/export", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
expect((await GET(req("/api/leads/export"))).status).toBe(401);
expect(mocks.callMobileApiBinary).not.toHaveBeenCalled();
});
it("forwards the query string and passes bytes and headers through", async () => {
mocks.callMobileApiBinary.mockResolvedValue({ ok: true, data: { body: new Uint8Array([1, 2, 3]).buffer, contentType: "application/x-xlsx", contentDisposition: 'attachment; filename="l.xlsx"' } });
const res = await GET(req("/api/leads/export?q=ann"));
expect(mocks.callMobileApiBinary).toHaveBeenCalledWith("/api/admin/leads/export?q=ann", { token: "jwt-abc" });
expect(res.status).toBe(200);
expect(res.headers.get("content-type")).toBe("application/x-xlsx");
expect(res.headers.get("content-disposition")).toBe('attachment; filename="l.xlsx"');
expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([1, 2, 3]));
});
it("maps a failure through errorResponse, keeping code and details", async () => {
mocks.callMobileApiBinary.mockResolvedValue({ ok: false, error: "Too many", status: 422, code: "EXPORT_TOO_LARGE", details: { limit: 20000 } });
const res = await GET(req("/api/leads/export"));
expect(res.status).toBe(422);
expect(await res.json()).toEqual({ error: "Too many", code: "EXPORT_TOO_LARGE", details: { limit: 20000 } });
});
});
@@ -0,0 +1,19 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApiBinary } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
// xlsx export of the lead listing; mobile-api owns validation and the BO_LEADS + BO_LEADS_EXPORT guards.
export async function GET(req: NextRequest) {
const token = await getToken();
if (!token) return unauthorized();
const result = await callMobileApiBinary(`/api/admin/leads/export${new URL(req.url).search}`, { token });
if (!result.ok) return errorResponse(result);
const { body, contentType, contentDisposition } = result.data;
return new NextResponse(body, {
headers: {
...(contentType ? { "Content-Type": contentType } : {}),
...(contentDisposition ? { "Content-Disposition": contentDisposition } : {}),
},
});
}
@@ -5,6 +5,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest";
// --- test mocks ---
const mocks = vi.hoisted(() => ({
listEventLeads: vi.fn(),
exportEventLeads: vi.fn(),
listEventSalespeople: vi.fn(),
listEventLeadInterests: vi.fn(),
listEventLeadEvents: vi.fn(),
@@ -13,6 +14,7 @@ const mocks = vi.hoisted(() => ({
vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({
...(await importActual<typeof import("@/app/lib/services/adminEventLeads")>()),
listEventLeads: mocks.listEventLeads,
exportEventLeads: mocks.exportEventLeads,
listEventSalespeople: mocks.listEventSalespeople,
listEventLeadInterests: mocks.listEventLeadInterests,
listEventLeadEvents: mocks.listEventLeadEvents,
@@ -25,10 +27,12 @@ vi.mock("next/navigation", async () => ({
import { memoryRouter } from "@/test/memoryRouter";
import EventLeadsDetailPage from "./page";
import { ApiError } from "@/app/lib/clientApi";
beforeEach(() => {
memoryRouter.reset("/event-leads/evt-1");
mocks.listEventLeads.mockReset().mockResolvedValue({ items: [], total: 0 });
mocks.exportEventLeads.mockReset().mockResolvedValue(undefined);
mocks.listEventSalespeople.mockReset().mockResolvedValue([{ id: 1, name: "Jane Sales", username: "jane" }]);
mocks.listEventLeadInterests.mockReset().mockResolvedValue([{ id: 1, name: "Product A", active: true }]);
mocks.listEventLeadEvents.mockReset().mockResolvedValue([{ uuid: "evt-1", name: "Test Event", location: "Hall A", startDate: "2025-06-01", endDate: "2025-06-02" }]);
@@ -209,3 +213,54 @@ describe("EventLeadsDetailPage (listing)", { timeout: 20000 }, () => {
expect(await screen.findByRole("option", { name: "Hot" })).toBeInTheDocument();
});
});
describe("EventLeadsDetailPage export", () => {
it("hides Export without BO_LEADS_EXPORT", async () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => m !== "BO_LEADS_EXPORT" });
render(<EventLeadsDetailPage />);
await screen.findByText("Test Event");
expect(screen.queryByRole("button", { name: "Export" })).toBeNull();
});
it("exports with the current filters (no paging) and is disabled while running", async () => {
let done!: () => void;
mocks.exportEventLeads.mockReturnValue(new Promise<void>((r) => { done = r; }));
memoryRouter.reset("/event-leads/evt-1", "status=OPEN&temperature=HOT");
const user = userEvent.setup();
render(<EventLeadsDetailPage />);
await user.click(await screen.findByRole("button", { name: "Export" }));
expect(mocks.exportEventLeads).toHaveBeenCalledTimes(1);
const [uuid, filters] = mocks.exportEventLeads.mock.calls[0];
expect(uuid).toBe("evt-1");
expect(filters).toMatchObject({ status: "OPEN", temperature: "HOT" });
expect(filters).not.toHaveProperty("page");
expect(screen.getByRole("button", { name: "Export" })).toBeDisabled();
done();
await waitFor(() => expect(screen.getByRole("button", { name: "Export" })).toBeEnabled());
});
it("shows the too-large message on EXPORT_TOO_LARGE", async () => {
mocks.exportEventLeads.mockRejectedValue(new ApiError("Too many", 422, { code: "EXPORT_TOO_LARGE", details: { limit: 20000 } }));
render(<EventLeadsDetailPage />);
await userEvent.click(await screen.findByRole("button", { name: "Export" }));
expect(await screen.findByText("More than 20,000 rows. Narrow the search or filters.")).toBeVisible();
});
it("clears the export error once a filter changes", async () => {
const user = userEvent.setup();
mocks.exportEventLeads.mockRejectedValue(new ApiError("Too many", 422, { code: "EXPORT_TOO_LARGE", details: { limit: 20000 } }));
render(<EventLeadsDetailPage />);
await user.click(await screen.findByRole("button", { name: "Export" }));
await screen.findByText("More than 20,000 rows. Narrow the search or filters.");
await user.click(screen.getByRole("combobox", { name: /temperature filter/i }));
await user.click(await screen.findByRole("option", { name: "Hot" }));
await waitFor(() => expect(screen.queryByText("More than 20,000 rows. Narrow the search or filters.")).toBeNull());
});
it("shows the error message for other failures", async () => {
mocks.exportEventLeads.mockRejectedValue(new ApiError("Boom happened", 400));
render(<EventLeadsDetailPage />);
await userEvent.click(await screen.findByRole("button", { name: "Export" }));
expect(await screen.findByText("Boom happened")).toBeVisible();
});
});
@@ -3,7 +3,7 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import { Plus } from "lucide-react";
import { Download, Plus } from "lucide-react";
import type { ColumnDef } from "@tanstack/react-table";
import { Badge } from "@/app/components/ui/badge";
import { Button } from "@/app/components/ui/button";
@@ -12,9 +12,11 @@ import { DataTable } from "@/app/components/ui/data-table";
import { PageHeader } from "@/app/components/ui/page-header";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { RequireModule } from "@/app/lib/RequireModule";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { ApiError } from "@/app/lib/clientApi";
import { useListFilters } from "@/app/lib/hooks/useListFilters";
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
import { listEventLeads, listEventSalespeople, listEventLeadInterests, listEventLeadEvents } from "@/app/lib/services/adminEventLeads";
import { exportEventLeads, listEventLeads, listEventSalespeople, listEventLeadInterests, listEventLeadEvents } from "@/app/lib/services/adminEventLeads";
import type { EventLeadRow, InterestOption, SalespersonOption } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { formatDmy } from "@/app/lib/date-input";
@@ -28,6 +30,7 @@ const STATUS_BADGE = { OPEN: "neutral", CONTACTED: "neutral", QUALIFIED: "contra
function EventLeadsDetailPageContent() {
const t = useT();
const { hasModule } = useAdminAuth();
const { eventUuid } = useParams<{ eventUuid: string }>();
const { tableRef, pageSize } = useFitPageSize();
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
@@ -54,6 +57,20 @@ function EventLeadsDetailPageContent() {
return () => { cancelled = true; };
}, [eventUuid]);
const [exporting, setExporting] = useState(false);
const [exportError, setExportError] = useState<string | null>(null);
const runExport = () => {
setExporting(true);
setExportError(null);
exportEventLeads(eventUuid, filters)
.catch((err: unknown) => {
const tooLarge = err instanceof ApiError && (err.data as { code?: string } | undefined)?.code === "EXPORT_TOO_LARGE";
setExportError(tooLarge ? t("LeadsExportTooLarge") : err instanceof Error ? err.message : t("LeadListLoadFailed"));
})
.finally(() => setExporting(false));
};
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
// Load lookup options
@@ -78,6 +95,7 @@ function EventLeadsDetailPageContent() {
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the eventUuid/page/reloadKey-triggered fetch below.
setLoading(true);
setError(null);
setExportError(null);
listEventLeads(eventUuid, { page, pageSize, ...filters })
.then((result) => {
if (!cancelled) setData(result);
@@ -196,15 +214,25 @@ function EventLeadsDetailPageContent() {
<PageHeader
title={eventName === undefined ? "…" : (eventName ?? t("BO_EVENT_LEADS"))}
actions={
<Button asChild>
<Link href={`/event-leads/${eventUuid}/new`}>
<Plus aria-hidden="true" className="size-4" />
{t("LeadAddLead")}
</Link>
</Button>
<>
{hasModule("BO_LEADS_EXPORT") && (
<Button variant="outline" disabled={exporting} onClick={runExport}>
<Download aria-hidden="true" className="size-4" />
{t("Export")}
</Button>
)}
<Button asChild>
<Link href={`/event-leads/${eventUuid}/new`}>
<Plus aria-hidden="true" className="size-4" />
{t("LeadAddLead")}
</Link>
</Button>
</>
}
/>
{exportError && <ErrorState message={exportError} className="mb-4" />}
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
<FilterPanel activeCount={activeCount} onClear={clear}>
+50 -1
View File
@@ -2,16 +2,18 @@ import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ listLeads: vi.fn(), useAdminAuth: vi.fn() }));
const mocks = vi.hoisted(() => ({ listLeads: vi.fn(), exportLeads: vi.fn(), useAdminAuth: vi.fn() }));
vi.mock("@/app/lib/services/adminLeads", async (importActual) => ({
...(await importActual<typeof import("@/app/lib/services/adminLeads")>()),
listLeads: mocks.listLeads,
exportLeads: mocks.exportLeads,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { memoryRouter } from "@/test/memoryRouter";
import LeadsPage from "./page";
import { ApiError } from "@/app/lib/clientApi";
const ROW = {
leadUuid: "l-1", name: "Aisyah", mobile: "+60123456701", email: "a@x.test", companyName: "Example Co", jobTitle: null,
@@ -22,6 +24,7 @@ const ROW = {
beforeEach(() => {
memoryRouter.reset("/leads");
mocks.listLeads.mockReset().mockResolvedValue({ items: [ROW], total: 1 });
mocks.exportLeads.mockReset().mockResolvedValue(undefined);
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
});
@@ -69,3 +72,49 @@ describe("LeadsPage", () => {
expect(await screen.findByRole("link", { name: "Aisyah" })).toBeVisible();
});
});
describe("LeadsPage export", () => {
it("hides Export without BO_LEADS_EXPORT", async () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => m !== "BO_LEADS_EXPORT" });
render(<LeadsPage />);
await screen.findByRole("link", { name: "Aisyah" });
expect(screen.queryByRole("button", { name: "Export" })).toBeNull();
});
it("exports with the current q and is disabled while running", async () => {
let done!: () => void;
mocks.exportLeads.mockReturnValue(new Promise<void>((r) => { done = r; }));
memoryRouter.reset("/leads", "q=aisyah");
const user = userEvent.setup();
render(<LeadsPage />);
await user.click(await screen.findByRole("button", { name: "Export" }));
expect(mocks.exportLeads).toHaveBeenCalledWith({ q: "aisyah" });
expect(screen.getByRole("button", { name: "Export" })).toBeDisabled();
done();
await waitFor(() => expect(screen.getByRole("button", { name: "Export" })).toBeEnabled());
});
it("shows the too-large message on EXPORT_TOO_LARGE", async () => {
mocks.exportLeads.mockRejectedValue(new ApiError("Too many", 422, { code: "EXPORT_TOO_LARGE", details: { limit: 20000 } }));
render(<LeadsPage />);
await userEvent.click(await screen.findByRole("button", { name: "Export" }));
expect(await screen.findByText("More than 20,000 rows. Narrow the search or filters.")).toBeVisible();
});
it("clears the export error once the search changes", async () => {
const user = userEvent.setup();
mocks.exportLeads.mockRejectedValue(new ApiError("Too many", 422, { code: "EXPORT_TOO_LARGE", details: { limit: 20000 } }));
render(<LeadsPage />);
await user.click(await screen.findByRole("button", { name: "Export" }));
await screen.findByText("More than 20,000 rows. Narrow the search or filters.");
await user.type(screen.getByRole("searchbox", { name: "Search name, mobile or email" }), "aisyah");
await waitFor(() => expect(screen.queryByText("More than 20,000 rows. Narrow the search or filters.")).toBeNull());
});
it("shows the error message for other failures", async () => {
mocks.exportLeads.mockRejectedValue(new ApiError("Boom happened", 400));
render(<LeadsPage />);
await userEvent.click(await screen.findByRole("button", { name: "Export" }));
expect(await screen.findByText("Boom happened")).toBeVisible();
});
});
+32 -2
View File
@@ -2,15 +2,19 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { Download } from "lucide-react";
import type { ColumnDef } from "@tanstack/react-table";
import { FilterField, FilterPanel, FilterSearch } from "@/app/components/ui/filter-panel";
import { DataTable } from "@/app/components/ui/data-table";
import { Button } from "@/app/components/ui/button";
import { PageHeader } from "@/app/components/ui/page-header";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { RequireModule } from "@/app/lib/RequireModule";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { ApiError } from "@/app/lib/clientApi";
import { useListFilters } from "@/app/lib/hooks/useListFilters";
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
import { listLeads } from "@/app/lib/services/adminLeads";
import { exportLeads, listLeads } from "@/app/lib/services/adminLeads";
import type { LeadRow } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
@@ -18,6 +22,7 @@ const DEFAULTS = { q: "" };
function LeadsPageContent() {
const t = useT();
const { hasModule } = useAdminAuth();
const { tableRef, pageSize } = useFitPageSize();
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
const [data, setData] = useState<{ items: LeadRow[]; total: number }>({ items: [], total: 0 });
@@ -25,6 +30,20 @@ function LeadsPageContent() {
const [failed, setFailed] = useState(false);
const [reloadKey, setReloadKey] = useState(0);
const [exporting, setExporting] = useState(false);
const [exportError, setExportError] = useState<string | null>(null);
const runExport = () => {
setExporting(true);
setExportError(null);
exportLeads({ q: filters.q || undefined })
.catch((err: unknown) => {
const tooLarge = err instanceof ApiError && (err.data as { code?: string } | undefined)?.code === "EXPORT_TOO_LARGE";
setExportError(tooLarge ? t("LeadsExportTooLarge") : err instanceof Error ? err.message : t("LeadListLoadFailed"));
})
.finally(() => setExporting(false));
};
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
useEffect(() => {
@@ -33,6 +52,7 @@ function LeadsPageContent() {
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the filter/page/reloadKey-triggered fetch below, which is the actual synchronization.
setLoading(true);
setFailed(false);
setExportError(null);
listLeads({ q: filters.q || undefined, page, pageSize })
.then((result) => { if (!cancelled) setData(result); })
.catch(() => { if (!cancelled) setFailed(true); })
@@ -64,7 +84,17 @@ function LeadsPageContent() {
return (
<>
<PageHeader title={t("BO_LEADS")} />
<PageHeader
title={t("BO_LEADS")}
actions={hasModule("BO_LEADS_EXPORT") && (
<Button variant="outline" disabled={exporting} onClick={runExport}>
<Download aria-hidden="true" className="size-4" />
{t("Export")}
</Button>
)}
/>
{exportError && <ErrorState message={exportError} className="mb-4" />}
{failed && <ErrorState message={t("LeadListLoadFailed")} onRetry={refetch} className="mb-4" />}
+43 -1
View File
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { apiGet, apiPost, apiPut, apiDelete, ApiError } from "./clientApi";
import { apiGet, apiPost, apiPut, apiDelete, apiDownload, ApiError } from "./clientApi";
function jsonResponse(body: unknown, status: number): Response {
return new Response(JSON.stringify(body), {
@@ -132,3 +132,45 @@ describe("clientApi", () => {
await expect(apiGet("/api/x")).rejects.toBe(abort);
});
});
describe("apiDownload", () => {
const originalFetch = global.fetch;
afterEach(() => { global.fetch = originalFetch; vi.restoreAllMocks(); });
function stubUrl() {
const create = vi.fn(() => "blob:x");
const revoke = vi.fn();
Object.assign(URL, { createObjectURL: create, revokeObjectURL: revoke });
const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
return { create, revoke, click };
}
it("downloads using the filename from Content-Disposition and revokes the URL", async () => {
const { create, revoke, click } = stubUrl();
global.fetch = vi.fn().mockResolvedValue(new Response("bytes", { status: 200, headers: { "Content-Disposition": 'attachment; filename="leads-2026.xlsx"' } }));
let name = "";
click.mockImplementation(function (this: HTMLAnchorElement) { name = this.download; });
await apiDownload("/api/leads/export?q=a", "leads.xlsx");
expect(global.fetch).toHaveBeenCalledWith("/api/leads/export?q=a", expect.anything());
expect(create).toHaveBeenCalled();
expect(name).toBe("leads-2026.xlsx");
await vi.waitFor(() => expect(revoke).toHaveBeenCalledWith("blob:x"));
});
it("falls back to the given filename", async () => {
const { click } = stubUrl();
global.fetch = vi.fn().mockResolvedValue(new Response("bytes", { status: 200 }));
let name = "";
click.mockImplementation(function (this: HTMLAnchorElement) { name = this.download; });
await apiDownload("/api/leads/export", "leads.xlsx");
expect(name).toBe("leads.xlsx");
});
it("throws an ApiError carrying code and details on failure", async () => {
stubUrl();
global.fetch = vi.fn().mockResolvedValue(jsonResponse({ error: "Too many", code: "EXPORT_TOO_LARGE", details: { limit: 20000 } }, 422));
await expect(apiDownload("/api/leads/export", "leads.xlsx")).rejects.toMatchObject({
name: "ApiError", status: 422, message: "Too many", data: { code: "EXPORT_TOO_LARGE", details: { limit: 20000 } },
});
});
});
+39 -22
View File
@@ -32,7 +32,8 @@ function safeJson(text: string): unknown {
}
}
async function clientFetch<T>(path: string, init?: RequestInit): Promise<T> {
/** fetch + the shared error handling: a non-2xx response throws ApiError carrying the parsed body. */
async function fetchOrThrow(path: string, init?: RequestInit): Promise<Response> {
let res: Response;
try {
res = await fetch(path, {
@@ -45,30 +46,46 @@ async function clientFetch<T>(path: string, init?: RequestInit): Promise<T> {
// fetch only rejects when the request never got a response (offline, DNS, connection reset).
throw new ApiError("Couldn't reach the server. Check your connection and retry.", 0);
}
if (res.ok) return res;
const text = await res.text();
const body = text ? safeJson(text) : undefined;
if (!res.ok) {
const message =
(body && typeof body === "object" && "error" in body
? String((body as Record<string, unknown>).error)
: null) || `Request failed (${res.status})`;
// 401 means the session is missing/expired — bounce to login. The login call itself is
// exempt: its 401 is "bad credentials"/"account disabled", and the login page must show it.
if (res.status === 401 && path !== "/api/auth/login" && typeof window !== "undefined") {
window.location.assign(loginUrl(window.location.pathname + window.location.search));
}
// A pending first-sign-in password reset blocks every admin API until it is completed.
if (
res.status === 403 &&
(body as { code?: unknown } | undefined)?.code === "PASSWORD_RESET_REQUIRED" &&
typeof window !== "undefined"
) {
window.location.assign("/reset-password");
}
throw new ApiError(message, res.status, body);
const message =
(body && typeof body === "object" && "error" in body
? String((body as Record<string, unknown>).error)
: null) || `Request failed (${res.status})`;
// 401 means the session is missing/expired — bounce to login. The login call itself is
// exempt: its 401 is "bad credentials"/"account disabled", and the login page must show it.
if (res.status === 401 && path !== "/api/auth/login" && typeof window !== "undefined") {
window.location.assign(loginUrl(window.location.pathname + window.location.search));
}
return body as T;
// A pending first-sign-in password reset blocks every admin API until it is completed.
if (
res.status === 403 &&
(body as { code?: unknown } | undefined)?.code === "PASSWORD_RESET_REQUIRED" &&
typeof window !== "undefined"
) {
window.location.assign("/reset-password");
}
throw new ApiError(message, res.status, body);
}
async function clientFetch<T>(path: string, init?: RequestInit): Promise<T> {
const text = await (await fetchOrThrow(path, init)).text();
return (text ? safeJson(text) : undefined) as T;
}
/** GET a file and save it through a temporary <a download>; the name comes from Content-Disposition. */
export async function apiDownload(path: string, fallbackName: string): Promise<void> {
const res = await fetchOrThrow(path);
const blob = await res.blob();
const name = /filename="?([^";]+)"?/i.exec(res.headers.get("Content-Disposition") ?? "")?.[1] ?? fallbackName;
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = name;
a.click();
setTimeout(() => URL.revokeObjectURL(url), 0); // revoking synchronously can cancel the download in older browsers
}
export const apiGet = <T>(path: string): Promise<T> => clientFetch<T>(path);
@@ -282,6 +282,7 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
LeadGetFailed: "Failed to load the lead",
BO_LEADS: "Leads",
LeadsSearch: "Search name, mobile or email",
LeadsExportTooLarge: "More than 20,000 rows. Narrow the search or filters.",
LeadsEvents: "Events",
LeadsLastEvent: "Last event",
LeadsLatestSalesperson: "Latest salesperson",
@@ -1,7 +1,7 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { callMobileApi } from "./mobileApi";
import { callMobileApi, callMobileApiBinary } from "./mobileApi";
const BASE = "https://mobile.example.test";
const KEY = "test-api-key";
@@ -336,3 +336,40 @@ describe("callMobileApi — X-Client-Ip forwarding", () => {
expect(headers.get("X-Client-Ip")).toBeNull();
});
});
describe("callMobileApiBinary", () => {
it("returns the bytes with the upstream content type and disposition", async () => {
const bytes = new Uint8Array([80, 75, 3, 4]);
fetchMock.mockResolvedValue(new Response(bytes, { status: 200, headers: { "Content-Type": "application/x-xlsx", "Content-Disposition": 'attachment; filename="leads.xlsx"' } }));
const r = await callMobileApiBinary("/api/admin/leads/export?q=a", { token: "jwt-1" });
expect(r.ok).toBe(true);
if (r.ok) {
expect(new Uint8Array(r.data.body)).toEqual(bytes);
expect(r.data.contentType).toBe("application/x-xlsx");
expect(r.data.contentDisposition).toBe('attachment; filename="leads.xlsx"');
}
const [url, init] = fetchMock.mock.calls[0];
expect(url).toBe(`${BASE}/api/admin/leads/export?q=a`);
const h = new Headers(init.headers);
expect(h.get("api-key")).toBe(KEY);
expect(h.get("authorization")).toBe("Bearer jwt-1");
});
it("maps a 422 to the same failure shape as callMobileApi", async () => {
fetchMock.mockResolvedValue(makeRes(JSON.stringify({ code: "EXPORT_TOO_LARGE", message: "Too many", details: { limit: 20000 } }), { ok: false, status: 422 }));
const r = await callMobileApiBinary("/api/admin/leads/export", { token: "t" });
expect(r).toMatchObject({ ok: false, status: 422, code: "EXPORT_TOO_LARGE", details: { limit: 20000 } });
});
it("maps the expired-token signal to expired", async () => {
fetchMock.mockResolvedValue(makeRes("Expired token", { ok: false, status: 500 }));
const r = await callMobileApiBinary("/api/admin/leads/export", { token: "t" });
expect(r).toMatchObject({ ok: false, expired: true });
});
it("rejects traversal paths", async () => {
const r = await callMobileApiBinary("/api/admin/../x", { token: "t" });
expect(r).toMatchObject({ ok: false, status: 400 });
expect(fetchMock).not.toHaveBeenCalled();
});
});
@@ -60,17 +60,48 @@ function extractError(parsed: unknown): string | undefined {
return undefined;
}
export async function callMobileApi<T>(
path: string,
opts: MobileCallOptions = {},
): Promise<ApiResult<T>> {
type Failure = Extract<ApiResult<never>, { ok: false }>;
/** The ApiResult failure for a non-2xx upstream response; `raw` is the response body text. */
function upstreamFailure(status: number, raw: string): Failure {
let parsed: unknown = undefined;
if (raw) {
try {
parsed = JSON.parse(raw);
} catch {
parsed = raw;
}
}
if (isExpiredSignal(status, raw)) {
return { ok: false, error: "Your session has expired. Please sign in again.", status, expired: true };
}
const details = extractDetails(parsed);
return {
ok: false,
// public-error-text (F39): only a business message reaches the browser; a non-JSON body (an HTML error page,
// a stack trace) never does.
error: publicError(typeof parsed === "object" ? extractError(parsed) : undefined),
status,
...(parsed && typeof parsed === "object" && typeof (parsed as { code?: unknown }).code === "string"
? { code: (parsed as { code: string }).code }
: {}),
...(parsed && typeof parsed === "object" && Array.isArray((parsed as { errors?: unknown }).errors) &&
(parsed as { errors: string[] }).errors.every(v => typeof v === "string")
? { errors: (parsed as { errors: string[] }).errors }
: {}),
...(details ? { details } : {}),
};
}
/** Sends the upstream request (guard, config, headers, timeout); a Response or the failure to report. */
async function upstreamFetch(path: string, opts: MobileCallOptions): Promise<{ res: Response } | { fail: Failure }> {
if (isTraversalPath(path)) {
return { ok: false, error: "Invalid request path", status: 400 };
return { fail: { ok: false, error: "Invalid request path", status: 400 } };
}
const base = process.env.MOBILE_API_BASE_URL;
const key = process.env.MOBILE_API_KEY;
if (!base || !key) {
return { ok: false, error: "Mobile API is not configured" };
return { fail: { ok: false, error: "Mobile API is not configured" } };
}
const forwardedIp = await forwardedClientIpHeaders();
@@ -85,27 +116,33 @@ export async function callMobileApi<T>(
if (opts.token) headers["Authorization"] = `Bearer ${opts.token}`;
if (opts.body !== undefined) headers["Content-Type"] = "application/json";
let res: Response;
try {
res = await fetch(`${base}${path}`, {
return { res: await fetch(`${base}${path}`, {
method: opts.method ?? "GET",
headers,
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
cache: "no-store",
signal: AbortSignal.timeout(opts.timeoutMs ?? DEFAULT_TIMEOUT_MS),
});
}) };
} catch (err) {
if (err instanceof DOMException && (err.name === "TimeoutError" || err.name === "AbortError")) {
return {
ok: false,
error: "The server is taking too long to respond. Please try again.",
timedOut: true,
};
return { fail: { ok: false, error: "The server is taking too long to respond. Please try again.", timedOut: true } };
}
return { ok: false, error: "Unable to reach the server. Please try again." };
return { fail: { ok: false, error: "Unable to reach the server. Please try again." } };
}
}
export async function callMobileApi<T>(
path: string,
opts: MobileCallOptions = {},
): Promise<ApiResult<T>> {
const up = await upstreamFetch(path, opts);
if ("fail" in up) return up.fail;
const { res } = up;
const raw = await res.text();
if (!res.ok) return upstreamFailure(res.status, raw);
let parsed: unknown = undefined;
if (raw) {
try {
@@ -115,33 +152,6 @@ export async function callMobileApi<T>(
}
}
if (!res.ok) {
if (isExpiredSignal(res.status, raw)) {
return {
ok: false,
error: "Your session has expired. Please sign in again.",
status: res.status,
expired: true,
};
}
const details = extractDetails(parsed);
return {
ok: false,
// public-error-text (F39): only a business message reaches the browser; a non-JSON body (an HTML error page,
// a stack trace) never does.
error: publicError(typeof parsed === "object" ? extractError(parsed) : undefined),
status: res.status,
...(parsed && typeof parsed === "object" && typeof (parsed as { code?: unknown }).code === "string"
? { code: (parsed as { code: string }).code }
: {}),
...(parsed && typeof parsed === "object" && Array.isArray((parsed as { errors?: unknown }).errors) &&
(parsed as { errors: string[] }).errors.every(v => typeof v === "string")
? { errors: (parsed as { errors: string[] }).errors }
: {}),
...(details ? { details } : {}),
};
}
// 2xx, but the body may still encode a logical failure.
if (parsed && typeof parsed === "object") {
const obj = parsed as Record<string, unknown>;
@@ -163,3 +173,28 @@ export async function callMobileApi<T>(
return { ok: true, data: parsed as T };
}
export interface BinaryPayload {
body: ArrayBuffer;
contentType: string | null;
contentDisposition: string | null;
}
/** GET a binary upstream response (e.g. an xlsx export); failures use the same shape as callMobileApi. */
export async function callMobileApiBinary(
path: string,
opts: Pick<MobileCallOptions, "token" | "timeoutMs"> = {},
): Promise<ApiResult<BinaryPayload>> {
const up = await upstreamFetch(path, opts);
if ("fail" in up) return up.fail;
const { res } = up;
if (!res.ok) return upstreamFailure(res.status, await res.text());
return {
ok: true,
data: {
body: await res.arrayBuffer(),
contentType: res.headers.get("Content-Type"),
contentDisposition: res.headers.get("Content-Disposition"),
},
};
}
@@ -1,4 +1,4 @@
import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi";
import { apiDownload, apiGet, apiPost, apiPut } from "@/app/lib/clientApi";
import type {
EventLeadCapturePayload,
EventLeadEvent,
@@ -43,3 +43,9 @@ export const getEventLead = (eventUuid: string, eventLeadUuid: string) =>
apiGet<EventLeadRow>(`${BASE}/${eventUuid}/leads/${eventLeadUuid}`);
export const updateEventLead = (eventUuid: string, eventLeadUuid: string, payload: EventLeadUpdatePayload) =>
apiPut<EventLeadRow>(`${BASE}/${eventUuid}/leads/${eventLeadUuid}`, payload);
export function exportEventLeads(eventUuid: string, filters: EventLeadFilters) {
const qs = new URLSearchParams();
for (const key of FILTERS) if (filters[key]) qs.set(key, filters[key]);
return apiDownload(`${BASE}/${eventUuid}/export${qs.size ? `?${qs}` : ""}`, "event-leads.xlsx");
}
@@ -1,4 +1,4 @@
import { apiGet, apiPut } from "@/app/lib/clientApi";
import { apiDownload, apiGet, apiPut } from "@/app/lib/clientApi";
import type { LeadDetail, LeadRow, LeadUpdatePayload } from "@/app/lib/types";
const BASE = "/api/leads";
@@ -15,3 +15,6 @@ export async function listLeads(params: { q?: string; /** 1-based. */ page: numb
export const getLead = (uuid: string) => apiGet<LeadDetail>(`${BASE}/${uuid}`);
export const updateLead = (uuid: string, payload: LeadUpdatePayload) => apiPut<LeadDetail>(`${BASE}/${uuid}`, payload);
export const exportLeads = (params: { q?: string }) =>
apiDownload(`${BASE}/export${params.q ? `?${new URLSearchParams({ q: params.q })}` : ""}`, "leads.xlsx");