feat(admin-portal): event leads data layer

One proxy route for /api/admin/event-leads (dot segments rejected),
service, types, and /event-leads gated by BO_EVENT_LEADS.

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 12:20:47 +08:00
1 parent 18672ba173
commit 90f25debc2
7 files changed
+266 -1

No files matched your search

@@ -0,0 +1,62 @@
import { describe, it, expect, vi, beforeEach } 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, PUT } from "./route";
type Req = Parameters<typeof GET>[0];
const ctx = (...path: string[]) => ({ params: Promise.resolve({ path }) });
const req = (url: string, init?: RequestInit) => new Request(`http://localhost${url}`, init) as unknown as Req;
beforeEach(() => {
mocks.callMobileApi.mockReset();
mocks.getToken.mockReset();
mocks.getToken.mockResolvedValue("jwt-abc");
mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ok: 1 } });
});
describe("/api/event-leads/[...path]", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await GET(req("/api/event-leads/events"), ctx("events"));
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards GET with the query string", async () => {
const res = await GET(req("/api/event-leads/9/leads?status=OPEN&page=0&size=20"), ctx("9", "leads"));
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-leads/9/leads?status=OPEN&page=0&size=20", { token: "jwt-abc" });
});
it("forwards POST and PUT bodies", async () => {
await POST(req("/api/event-leads/9/match", { method: "POST", body: JSON.stringify({ mobile: "0123" }) }), ctx("9", "match"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-leads/9/match", { method: "POST", body: { mobile: "0123" }, token: "jwt-abc" });
await PUT(req("/api/event-leads/9/leads/7", { method: "PUT", body: JSON.stringify({ status: "WON" }) }), ctx("9", "leads", "7"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-leads/9/leads/7", { method: "PUT", body: { status: "WON" }, token: "jwt-abc" });
});
it("rejects dot segments so the proxy cannot leave /api/admin/event-leads", async () => {
const res = await GET(req("/api/event-leads/x"), ctx("..", "users"));
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("encodes path segments", async () => {
await GET(req("/api/event-leads/a"), ctx("a/b"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/event-leads/a%2Fb", { token: "jwt-abc" });
});
it("passes upstream 409 with code and details", async () => {
mocks.callMobileApi.mockResolvedValue({
ok: false, error: "Already captured", status: 409, code: "ALREADY_CAPTURED", details: { eventLeadUuid: "55" },
});
const res = await POST(req("/api/event-leads/9", { method: "POST", body: "{}" }), ctx("9"));
expect(res.status).toBe(409);
const json = (await res.json()) as Record<string, unknown>;
expect(json.code).toBe("ALREADY_CAPTURED");
expect(json.details).toEqual({ eventLeadUuid: "55" });
});
});
@@ -0,0 +1,24 @@
import { NextResponse, type NextRequest } from "next/server";
import { callMobileApi } from "@/app/lib/server/mobileApi";
import { getToken } from "@/app/lib/server/session";
import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute";
// One proxy for every /api/admin/event-leads endpoint; mobile-api owns validation and the BO_EVENT_LEADS guard.
type Ctx = { params: Promise<{ path: string[] }> };
async function forward(req: NextRequest, { params }: Ctx, method?: "POST" | "PUT") {
const token = await getToken();
if (!token) return unauthorized();
const { path } = await params;
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
const target = `/api/admin/event-leads/${path.map(encodeURIComponent).join("/")}${new URL(req.url).search}`;
const result = method
? await callMobileApi<unknown>(target, { method, body: await req.json().catch(() => ({})), token })
: await callMobileApi<unknown>(target, { token });
if (!result.ok) return errorResponse(result);
return NextResponse.json(result.data);
}
export const GET = (req: NextRequest, ctx: Ctx) => forward(req, ctx);
export const POST = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "POST");
export const PUT = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "PUT");
@@ -4,6 +4,7 @@ import { ROUTE_MODULES, requiredModuleFor, requiredModulesFor } from "./routeMod
describe("routeModules", () => {
it("gates /users and /roles by the seeded module name", () => {
expect(requiredModuleFor("/interests")).toBe("BO_INTERESTS");
expect(requiredModuleFor("/event-leads")).toBe("BO_EVENT_LEADS");
expect(requiredModuleFor("/users")).toBe("BO_USERS");
expect(requiredModuleFor("/roles")).toBe("BO_ROLES");
expect(requiredModuleFor("/events")).toBe("BO_EVENTS");
@@ -13,6 +14,6 @@ describe("routeModules", () => {
it("leaves other routes ungated", () => {
expect(requiredModuleFor("/")).toBeUndefined();
expect(requiredModulesFor("/members")).toBeUndefined();
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/events", "/interests", "/roles", "/users"]);
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/event-leads", "/events", "/interests", "/roles", "/users"]);
});
});
@@ -7,6 +7,7 @@ export const ROUTE_MODULES: Record<string, string> = {
"/roles": "BO_ROLES",
"/events": "BO_EVENTS",
"/interests": "BO_INTERESTS",
"/event-leads": "BO_EVENT_LEADS",
};
export function requiredModuleFor(pathname: string): string | undefined {
@@ -0,0 +1,58 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), apiPut: vi.fn() }));
vi.mock("@/app/lib/clientApi", () => mocks);
import {
captureEventLead,
getEventLead,
listEventLeadEvents,
listEventLeadInterests,
listEventLeads,
listEventSalespeople,
matchLead,
updateEventLead,
} from "./adminEventLeads";
beforeEach(() => {
mocks.apiGet.mockReset();
mocks.apiPost.mockReset();
mocks.apiPut.mockReset();
});
describe("adminEventLeads", () => {
it("loads events, interest options and the event's salespeople", async () => {
mocks.apiGet.mockResolvedValue([]);
await listEventLeadEvents();
await listEventLeadInterests();
await listEventSalespeople("9");
expect(mocks.apiGet.mock.calls.map((c) => c[0])).toEqual([
"/api/event-leads/events",
"/api/event-leads/interest-options",
"/api/event-leads/9/salesperson-options",
]);
});
it("lists with only the set filters and a 0-based page", async () => {
mocks.apiGet.mockResolvedValue({ content: [{ eventLeadUuid: "1" }], totalElements: 41 });
const out = await listEventLeads("9", { page: 3, pageSize: 20, status: "OPEN", temperature: "", interestId: "4" });
expect(mocks.apiGet).toHaveBeenCalledWith("/api/event-leads/9/leads?status=OPEN&interestId=4&page=2&size=20");
expect(out).toEqual({ items: [{ eventLeadUuid: "1" }], total: 41 });
});
it("treats a malformed page as empty", async () => {
mocks.apiGet.mockResolvedValue(null);
expect(await listEventLeads("9", { page: 1, pageSize: 20 })).toEqual({ items: [], total: 0 });
});
it("matches, captures, gets and updates under the event", async () => {
await matchLead("9", { mobile: "0123", email: null });
expect(mocks.apiPost).toHaveBeenCalledWith("/api/event-leads/9/match", { mobile: "0123", email: null });
await captureEventLead("9", { name: "A", mobile: "0123" });
expect(mocks.apiPost).toHaveBeenCalledWith("/api/event-leads/9", { name: "A", mobile: "0123" });
await getEventLead("9", "7");
expect(mocks.apiGet).toHaveBeenCalledWith("/api/event-leads/9/leads/7");
await updateEventLead("9", "7", { status: "WON" });
expect(mocks.apiPut).toHaveBeenCalledWith("/api/event-leads/9/leads/7", { status: "WON" });
});
});
@@ -0,0 +1,45 @@
import { apiGet, apiPost, apiPut } from "@/app/lib/clientApi";
import type {
EventLeadCapturePayload,
EventLeadEvent,
EventLeadRow,
EventLeadUpdatePayload,
InterestOption,
LeadMatchResult,
SalespersonOption,
} from "@/app/lib/types";
const BASE = "/api/event-leads";
const FILTERS = ["salespersonId", "temperature", "status", "interestId", "leadType"] as const;
export type EventLeadFilters = Partial<Record<(typeof FILTERS)[number], string>>;
export interface EventLeadListParams extends EventLeadFilters {
/** 1-based. */
page: number;
pageSize: number;
}
export const listEventLeadEvents = () => apiGet<EventLeadEvent[]>(`${BASE}/events`);
export const listEventLeadInterests = () => apiGet<InterestOption[]>(`${BASE}/interest-options`);
export const listEventSalespeople = (eventUuid: string) =>
apiGet<SalespersonOption[]>(`${BASE}/${eventUuid}/salesperson-options`);
export async function listEventLeads(eventUuid: string, params: EventLeadListParams): Promise<{ items: EventLeadRow[]; total: number }> {
const qs = new URLSearchParams();
for (const key of FILTERS) if (params[key]) qs.set(key, params[key]);
qs.set("page", String(Math.max(0, params.page - 1)));
qs.set("size", String(params.pageSize));
const raw = await apiGet<{ content?: EventLeadRow[]; totalElements?: number } | null>(`${BASE}/${eventUuid}/leads?${qs}`);
const items = Array.isArray(raw?.content) ? raw.content : [];
return { items, total: typeof raw?.totalElements === "number" ? raw.totalElements : items.length };
}
export const matchLead = (eventUuid: string, contact: { mobile: string | null; email: string | null }) =>
apiPost<LeadMatchResult>(`${BASE}/${eventUuid}/match`, contact);
export const captureEventLead = (eventUuid: string, payload: EventLeadCapturePayload) =>
apiPost<EventLeadRow>(`${BASE}/${eventUuid}`, payload);
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);
+74
View File
@@ -159,3 +159,77 @@ export interface AdminInterestEntity {
active?: boolean;
sortOrder?: number;
}
/** Event-floor lead capture (`/api/admin/event-leads`). All uuids are strings. */
export type LeadTemperature = "HOT" | "WARM" | "COLD";
export type LeadStatus = "OPEN" | "CONTACTED" | "QUALIFIED" | "WON" | "LOST";
export type LeadType = "NEW" | "EXISTING";
export interface EventLeadEvent {
uuid: string;
name: string;
location: string | null;
startDate: string | null;
endDate: string | null;
}
export interface InterestOption {
id: number;
name: string;
active: boolean;
}
export interface LeadCandidate {
leadUuid: string;
name: string;
mobile: string | null;
email: string | null;
companyName: string | null;
jobTitle: string | null;
/** Set when this lead is already captured at the event. */
eventLeadUuid: string | null;
}
export interface LeadMatchResult {
mobile: string | null;
email: string | null;
candidates: LeadCandidate[];
}
export interface EventLeadRow {
eventLeadUuid: string;
eventUuid: string;
leadUuid: string;
name: string;
mobile: string | null;
email: string | null;
companyName: string | null;
jobTitle: string | null;
leadType: LeadType;
salesperson: { id: number; name: string } | null;
temperature: LeadTemperature | null;
status: LeadStatus;
interests: InterestOption[];
nextFollowUpDate: string | null;
notes: string | null;
capturedAt: string;
}
export interface EventLeadUpdatePayload {
salespersonId?: number | null;
temperature?: LeadTemperature | null;
status?: LeadStatus;
interestIds?: number[];
nextFollowUpDate?: string | null;
notes?: string | null;
}
export interface EventLeadCapturePayload extends EventLeadUpdatePayload {
/** Set to attach an existing lead; omit for a new one. */
leadUuid?: string;
name?: string;
mobile?: string | null;
email?: string | null;
companyName?: string | null;
jobTitle?: string | null;
}