feat(admin-portal): leads listing and lead detail

Lead Listing with search and server paging, lead detail with event
history, shared-contact warning and an edit form under BO_LEADS_EDIT,
and a View lead link from the event lead edit 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 16:53:44 +08:00
1 parent eab4053c06
commit 82b6943474
15 files changed
+861 -2

No files matched your search

@@ -71,7 +71,7 @@ Design: `design.md` (decision numbers below refer to it). All tasks run serially
## 4. Portal
- [ ] 4.1 Add the Lead Listing and lead detail (design decision 6):
- [x] 4.1 Add the Lead Listing and lead detail (design decision 6):
- the leads data layer: route `app/api/leads/[...path]`, service, types, and `/leads` mapped to `BO_LEADS`;
- the `/leads` listing with search;
- the `/leads/[leadUuid]` detail page, with an edit form when the user has `BO_LEADS_EDIT`, the shared-contact warning, the event history and not-found;
@@ -0,0 +1,58 @@
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, PUT } from "./route";
type Req = Parameters<typeof GET>[0];
const ctx = (...path: string[]) => ({ params: Promise.resolve({ path: path.length ? path : undefined }) });
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/leads/[[...path]]", () => {
it("returns 401 without a session", async () => {
mocks.getToken.mockResolvedValue(null);
const res = await GET(req("/api/leads"), ctx());
expect(res.status).toBe(401);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("forwards the list call (no path) with the query string", async () => {
const res = await GET(req("/api/leads?q=ann&page=0&size=20"), ctx());
expect(res.status).toBe(200);
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/leads?q=ann&page=0&size=20", { token: "jwt-abc" });
});
it("forwards the detail GET and the PUT body", async () => {
await GET(req("/api/leads/l-1"), ctx("l-1"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/leads/l-1", { token: "jwt-abc" });
await PUT(req("/api/leads/l-1", { method: "PUT", body: JSON.stringify({ name: "Ann" }) }), ctx("l-1"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/leads/l-1", { method: "PUT", body: { name: "Ann" }, token: "jwt-abc" });
});
it("rejects dot segments so the proxy cannot leave /api/admin/leads", async () => {
const res = await GET(req("/api/leads/x"), ctx("..", "users"));
expect(res.status).toBe(400);
expect(mocks.callMobileApi).not.toHaveBeenCalled();
});
it("encodes path segments", async () => {
await GET(req("/api/leads/a"), ctx("a/b"));
expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/leads/a%2Fb", { token: "jwt-abc" });
});
it("passes upstream 404 with its code", async () => {
mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Lead not found", status: 404, code: "LEAD_NOT_FOUND" });
const res = await GET(req("/api/leads/zz"), ctx("zz"));
expect(res.status).toBe(404);
expect(((await res.json()) as Record<string, unknown>).code).toBe("LEAD_NOT_FOUND");
});
});
@@ -0,0 +1,23 @@
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/leads endpoint; mobile-api owns validation and the BO_LEADS guards.
type Ctx = { params: Promise<{ path?: string[] }> };
async function forward(req: NextRequest, { params }: Ctx, method?: "PUT") {
const token = await getToken();
if (!token) return unauthorized();
const { path = [] } = await params; // [[...path]]: the list call has no segment
if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path.");
const target = `/api/admin/leads${path.map(encodeURIComponent).map((s) => `/${s}`).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 PUT = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "PUT");
@@ -9,6 +9,7 @@ import { DatePicker } from "@/app/components/ui/date-picker";
import { Label } from "@/app/components/ui/label";
import { PageHeader } from "@/app/components/ui/page-header";
import { EmptyState, ErrorState, TableSkeleton } from "@/app/components/ui/states";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { RequireModule } from "@/app/lib/RequireModule";
import { ApiError } from "@/app/lib/clientApi";
import { formatDmy } from "@/app/lib/date-input";
@@ -35,6 +36,7 @@ type LoadState = "loading" | "notFound" | "error" | Loaded;
function EventLead() {
const t = useT();
const router = useRouter();
const { hasModule } = useAdminAuth();
const { eventUuid, eventLeadUuid } = useParams<{ eventUuid: string; eventLeadUuid: string }>();
const [state, setState] = useState<LoadState>("loading");
const [reloadKey, setReloadKey] = useState(0);
@@ -145,6 +147,11 @@ function EventLead() {
{lead.email && <p className="text-sm">{lead.email}</p>}
{lead.companyName && <p className="text-sm text-muted-foreground">{lead.companyName}</p>}
{lead.jobTitle && <p className="text-sm text-muted-foreground">{lead.jobTitle}</p>}
{hasModule("BO_LEADS") && (
<Button asChild variant="outline" className={TALL}>
<Link href={`/leads/${lead.leadUuid}`}>{t("LeadsViewLead")}</Link>
</Button>
)}
<p className="text-sm text-muted-foreground">{t("LeadCaptured")} {formatDmy(lead.capturedAt.slice(0, 10))}</p>
</div>
@@ -0,0 +1,47 @@
import { render, screen } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({
getEventLead: vi.fn(), listEventSalespeople: vi.fn(), listEventLeadInterests: vi.fn(), useAdminAuth: vi.fn(),
}));
vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({
...(await importActual<typeof import("@/app/lib/services/adminEventLeads")>()),
getEventLead: mocks.getEventLead,
listEventSalespeople: mocks.listEventSalespeople,
listEventLeadInterests: mocks.listEventLeadInterests,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("next/navigation", async () => ({
...(await import("@/test/memoryRouter")).navigationMock,
useParams: () => ({ eventUuid: "evt-1", eventLeadUuid: "el-1" }),
}));
import EventLeadPage from "./page";
const grant = (...modules: string[]) =>
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => modules.includes(m) });
beforeEach(() => {
mocks.getEventLead.mockReset().mockResolvedValue({
eventLeadUuid: "el-1", eventUuid: "evt-1", leadUuid: "l-1", name: "Ann Lead", mobile: null, email: "ann@x.com",
companyName: null, jobTitle: null, leadType: "NEW", salesperson: null, temperature: null, status: "OPEN",
interests: [], nextFollowUpDate: null, notes: null, capturedAt: "2026-11-20T09:30:00Z",
});
mocks.listEventSalespeople.mockReset().mockResolvedValue([]);
mocks.listEventLeadInterests.mockReset().mockResolvedValue([]);
});
describe("EventLeadPage View lead link", () => {
it("links to the lead with BO_LEADS", async () => {
grant("BO_EVENT_LEADS", "BO_LEADS");
render(<EventLeadPage />);
expect(await screen.findByRole("link", { name: "View lead" })).toHaveAttribute("href", "/leads/l-1");
});
it("hides the link without BO_LEADS", async () => {
grant("BO_EVENT_LEADS");
render(<EventLeadPage />);
await screen.findByLabelText("Status");
expect(screen.queryByRole("link", { name: "View lead" })).toBeNull();
});
});
@@ -0,0 +1,218 @@
import { render, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ getLead: vi.fn(), updateLead: vi.fn(), useAdminAuth: vi.fn() }));
vi.mock("@/app/lib/services/adminLeads", async (importActual) => ({
...(await importActual<typeof import("@/app/lib/services/adminLeads")>()),
getLead: mocks.getLead,
updateLead: mocks.updateLead,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("next/navigation", async () => ({
...(await import("@/test/memoryRouter")).navigationMock,
useParams: () => ({ leadUuid: "l-1" }),
}));
import { ApiError } from "@/app/lib/clientApi";
import { memoryRouter } from "@/test/memoryRouter";
import LeadPage from "./page";
const SERVER_MSG = "Server says: internal detail xyz";
const apiError = (code: string, extra: Record<string, unknown> = {}, status = 400) =>
new ApiError(SERVER_MSG, status, { code, errors: [], details: {}, ...extra });
const LEAD = {
leadUuid: "l-1", name: "Aisyah", mobile: "+60123456701", email: "a@x.test", companyName: "Example Co", jobTitle: "CEO",
notes: "VIP", createdAt: "2026-11-01T00:00:00Z", updatedAt: "2026-11-02T00:00:00Z", updatedBy: "admin",
history: [
{ eventLeadUuid: "el-2", eventUuid: "e-2", eventName: "Penang Expo", eventStart: "2026-11-20T00:00:00", eventEnd: "2026-11-22T00:00:00",
leadType: "EXISTING", salesperson: null, temperature: "COLD", status: "OPEN", capturedAt: "2026-11-20T09:30:00Z" },
{ eventLeadUuid: "el-1", eventUuid: "e-1", eventName: "KL Food Fair", eventStart: "2026-10-05T00:00:00", eventEnd: "2026-10-06T00:00:00",
leadType: "NEW", salesperson: { id: 7, name: "Ali" }, temperature: "HOT", status: "WON", capturedAt: "2026-10-05T10:00:00Z" },
],
sharedContacts: [] as unknown[],
};
const PAYLOAD = { name: "Aisyah", mobile: "+60123456701", email: "a@x.test", companyName: "Example Co", jobTitle: "CEO", notes: "VIP" };
const grant = (...modules: string[]) =>
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => modules.includes(m) });
async function open(lead: Record<string, unknown> = {}) {
mocks.getLead.mockResolvedValue({ ...LEAD, ...lead });
render(<LeadPage />);
await screen.findByText("Penang Expo");
return userEvent.setup();
}
beforeEach(() => {
memoryRouter.reset("/leads/l-1");
mocks.getLead.mockReset();
mocks.updateLead.mockReset().mockResolvedValue(LEAD);
grant("BO_LEADS", "BO_LEADS_EDIT", "BO_EVENT_LEADS");
});
describe("LeadPage", { timeout: 20000 }, () => {
it("renders NotAuthorized without BO_LEADS", () => {
grant("BO_LEADS_EDIT");
render(<LeadPage />);
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
expect(mocks.getLead).not.toHaveBeenCalled();
});
it("lists event history newest first with type, salesperson, temperature, status and dates", async () => {
await open();
const cards = screen.getAllByTestId("history-card");
expect(cards.map((c) => within(c).getByText(/Penang Expo|KL Food Fair/).textContent)).toEqual(["Penang Expo", "KL Food Fair"]);
const first = within(cards[1]);
expect(first.getByText("New")).toBeVisible();
expect(first.getByText("Ali")).toBeVisible();
expect(first.getByText("Hot")).toBeVisible();
expect(first.getByText("Won")).toBeVisible();
expect(first.getByText("05/10/2026 - 06/10/2026")).toBeVisible();
expect(first.getByText("Captured 05/10/2026")).toBeVisible();
});
it("links history cards to the event lead only with BO_EVENT_LEADS", async () => {
await open();
expect(screen.getAllByTestId("history-card")[0].closest("a") ?? within(screen.getAllByTestId("history-card")[0]).getByRole("link"))
.toHaveAttribute("href", "/event-leads/e-2/el-2");
});
it("shows plain history cards without BO_EVENT_LEADS", async () => {
grant("BO_LEADS");
await open();
expect(screen.getAllByTestId("history-card")).toHaveLength(2);
expect(screen.queryByRole("link", { name: /Penang Expo/ })).toBeNull();
});
it("warns about a shared mobile and links the other lead", async () => {
await open({ sharedContacts: [{ leadUuid: "l-2", name: "Test Visitor Two", sameMobile: true, sameEmail: false }] });
const alert = screen.getByRole("alert");
expect(alert).toHaveTextContent("Same mobile as");
expect(within(alert).getByRole("link", { name: "Test Visitor Two" })).toHaveAttribute("href", "/leads/l-2");
});
it("shows no warning without shared contacts", async () => {
await open();
expect(screen.queryByRole("alert")).toBeNull();
});
it("prefills an edit form with phone-friendly inputs", async () => {
await open();
const mobile = screen.getByLabelText("Mobile");
expect(mobile).toHaveValue("+60123456701");
expect(mobile).toHaveAttribute("type", "tel");
expect(mobile).toHaveAttribute("inputmode", "tel");
expect(mobile).toHaveAttribute("autocomplete", "tel");
expect(screen.getByLabelText("Email")).toHaveAttribute("type", "email");
expect(screen.getByLabelText("Notes")).toHaveValue("VIP");
});
it("saves the exact payload and shows the returned values with a success message", async () => {
const user = await open();
mocks.updateLead.mockResolvedValue({ ...LEAD, email: "aisyah@example.test", companyName: "Example Co Ltd" });
await user.clear(screen.getByLabelText("Email"));
await user.type(screen.getByLabelText("Email"), " Aisyah@Example.TEST ");
await user.clear(screen.getByLabelText("Company"));
await user.type(screen.getByLabelText("Company"), "Example Co Ltd");
await user.click(screen.getByRole("button", { name: "Save" }));
expect(mocks.updateLead).toHaveBeenCalledWith("l-1", { ...PAYLOAD, email: "Aisyah@Example.TEST", companyName: "Example Co Ltd" });
expect(await screen.findByText("Lead saved.")).toBeVisible();
expect(screen.getByLabelText("Email")).toHaveValue("aisyah@example.test");
expect(memoryRouter.push).not.toHaveBeenCalled();
});
it("sends blank optional fields as null", async () => {
const user = await open();
await user.clear(screen.getByLabelText("Company"));
await user.clear(screen.getByLabelText("Notes"));
await user.click(screen.getByRole("button", { name: "Save" }));
expect(mocks.updateLead).toHaveBeenCalledWith("l-1", { ...PAYLOAD, companyName: null, notes: null });
});
it("shows an invalid mobile under the Mobile field with the mapped text", async () => {
const user = await open();
mocks.updateLead.mockRejectedValue(apiError("INVALID_MOBILE", { details: { field: "mobile" } }));
await user.click(screen.getByRole("button", { name: "Save" }));
const mobile = await screen.findByLabelText("Mobile");
expect(mobile).toHaveAttribute("aria-invalid", "true");
const err = document.getElementById(mobile.getAttribute("aria-describedby")!)!;
expect(err).toHaveTextContent("Enter a valid mobile number.");
expect(screen.queryByText(SERVER_MSG)).toBeNull();
});
it("marks every field listed by REQUIRED_FIELD", async () => {
const user = await open();
mocks.updateLead.mockRejectedValue(apiError("REQUIRED_FIELD", { errors: ["name", "email"] }));
await user.click(screen.getByRole("button", { name: "Save" }));
await screen.findAllByText("This field is required.");
expect(screen.getByLabelText("Name")).toHaveAttribute("aria-invalid", "true");
expect(screen.getByLabelText("Email")).toHaveAttribute("aria-invalid", "true");
expect(screen.getByLabelText("Mobile")).not.toHaveAttribute("aria-invalid");
});
it("never fails silently: unknown codes show a form-level message", async () => {
const user = await open();
mocks.updateLead.mockRejectedValue(apiError("SOMETHING_ELSE", {}, 500));
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText("Could not save the lead. Please try again.")).toBeVisible();
expect(screen.queryByText(SERVER_MSG)).toBeNull();
});
it("is read-only without BO_LEADS_EDIT", async () => {
grant("BO_LEADS");
await open();
expect(screen.queryByRole("button", { name: "Save" })).toBeNull();
expect(screen.queryByRole("textbox")).toBeNull();
expect(screen.getByText("+60123456701")).toBeVisible();
expect(screen.getByText("a@x.test")).toBeVisible();
expect(screen.getByText("VIP")).toBeVisible();
});
it("shows not-found with a Back link on LEAD_NOT_FOUND", async () => {
mocks.getLead.mockRejectedValue(apiError("LEAD_NOT_FOUND", {}, 404));
render(<LeadPage />);
expect(await screen.findByText("Lead not found")).toBeVisible();
expect(screen.getByRole("link", { name: "Back" })).toHaveAttribute("href", "/leads");
});
it("shows an error state with retry on other load failures", async () => {
mocks.getLead.mockRejectedValueOnce(apiError("BOOM", {}, 500));
render(<LeadPage />);
expect(await screen.findByText("Failed to load the lead")).toBeVisible();
mocks.getLead.mockResolvedValue(LEAD);
await userEvent.click(screen.getByRole("button", { name: /retry/i }));
expect(await screen.findByText("Penang Expo")).toBeVisible();
});
it("shows the shared-contact warning returned by a save", async () => {
const user = await open();
mocks.updateLead.mockResolvedValue({ ...LEAD, sharedContacts: [{ leadUuid: "l-9", name: "Other Person", sameMobile: true, sameEmail: false }] });
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByRole("link", { name: "Other Person" })).toHaveAttribute("href", "/leads/l-9");
});
it("clears the saved message once the user edits again", async () => {
const user = await open();
await user.click(screen.getByRole("button", { name: "Save" }));
expect(await screen.findByText("Lead saved.")).toBeVisible();
await user.type(screen.getByLabelText("Notes"), "!");
expect(screen.queryByText("Lead saved.")).toBeNull();
});
it("names each read-only value by its label", async () => {
grant("BO_LEADS");
await open();
const email = screen.getByText("a@x.test");
expect(email.tagName).toBe("DD");
expect(email.previousElementSibling?.tagName).toBe("DT");
expect(email.previousElementSibling).toHaveTextContent("Email");
});
it("hides the dates line of an event without dates", async () => {
await open({ history: [{ ...LEAD.history[0], eventStart: null, eventEnd: null }] });
const card = screen.getByTestId("history-card");
expect(card.textContent).not.toMatch(/\s-\s/);
});
});
@@ -0,0 +1,216 @@
"use client";
import { useEffect, useState, type FormEvent } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import { Alert } from "@/app/components/ui/alert";
import { Badge } from "@/app/components/ui/badge";
import { Button } from "@/app/components/ui/button";
import { Label } from "@/app/components/ui/label";
import { PageHeader } from "@/app/components/ui/page-header";
import { EmptyState, ErrorState, TableSkeleton } from "@/app/components/ui/states";
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
import { RequireModule } from "@/app/lib/RequireModule";
import { ApiError } from "@/app/lib/clientApi";
import { formatDmy } from "@/app/lib/date-input";
import { getLead, updateLead } from "@/app/lib/services/adminLeads";
import type { LeadDetail } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
const TEMPERATURES: Record<string, string> = { HOT: "LeadHot", WARM: "LeadWarm", COLD: "LeadCold" };
const STATUSES: Record<string, string> = { OPEN: "LeadOpen", CONTACTED: "LeadContacted", QUALIFIED: "LeadQualified", WON: "LeadWon", LOST: "LeadLost" };
const CODE_MESSAGE: Record<string, string> = {
REQUIRED_FIELD: "LeadErrRequired",
TOO_LONG: "LeadErrTooLong",
INVALID_MOBILE: "LeadErrInvalidMobile",
INVALID_EMAIL: "LeadErrInvalidEmail",
};
// Codes that name their field themselves when the server omits details.field.
const IMPLIED_FIELD: Record<string, string> = { INVALID_MOBILE: "mobile", INVALID_EMAIL: "email" };
const FIELDS = [
["name", "LeadName"], ["mobile", "LeadMobile"], ["email", "Email"], ["companyName", "LeadCompany"], ["jobTitle", "LeadJobTitle"], ["notes", "LeadNotes"],
] as const;
type Field = (typeof FIELDS)[number][0];
const INPUT_CLASS = "min-h-11 w-full rounded-md border border-input bg-transparent px-3 text-base shadow-sm outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 aria-[invalid=true]:border-destructive dark:bg-input/30";
const INPUT_ATTRS: Partial<Record<Field, Record<string, string>>> = {
mobile: { type: "tel", inputMode: "tel", autoComplete: "tel" },
email: { type: "email", autoComplete: "email" },
};
const TALL = "min-h-11";
type LoadState = "loading" | "notFound" | "error" | LeadDetail;
const blankToNull = (v: string) => (v.trim() === "" ? null : v);
const toValues = (l: LeadDetail): Record<Field, string> => ({
name: l.name, mobile: l.mobile ?? "", email: l.email ?? "", companyName: l.companyName ?? "", jobTitle: l.jobTitle ?? "", notes: l.notes ?? "",
});
function Lead() {
const t = useT();
const { hasModule } = useAdminAuth();
const { leadUuid } = useParams<{ leadUuid: string }>();
const [state, setState] = useState<LoadState>("loading");
const [reloadKey, setReloadKey] = useState(0);
const [values, setValues] = useState<Record<Field, string>>(toValues({ name: "", mobile: null, email: null, companyName: null, jobTitle: null, notes: null } as LeadDetail));
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const [formError, setFormError] = useState<string | null>(null);
const [saved, setSaved] = useState(false);
const [busy, setBusy] = useState(false);
useEffect(() => {
let cancelled = false;
getLead(leadUuid)
.then((lead) => {
if (cancelled) return;
setValues(toValues(lead));
setState(lead);
})
.catch((err) => {
if (cancelled) return;
const code = err instanceof ApiError ? (err.data as { code?: string } | undefined)?.code : undefined;
setState(code === "LEAD_NOT_FOUND" ? "notFound" : "error");
});
return () => { cancelled = true; };
}, [leadUuid, reloadKey]);
if (state === "loading") return <TableSkeleton rows={4} columns={2} />;
if (state === "notFound") {
return (
<EmptyState
title={t("LeadNotFound")}
action={<Button asChild variant="outline" className={TALL}><Link href="/leads">{t("Back")}</Link></Button>}
/>
);
}
if (state === "error") {
return <ErrorState message={t("LeadGetFailed")} onRetry={() => { setState("loading"); setReloadKey((k) => k + 1); }} />;
}
const lead = state;
const canEdit = hasModule("BO_LEADS_EDIT");
async function onSave(event: FormEvent) {
event.preventDefault();
setFieldErrors({});
setFormError(null);
setSaved(false);
setBusy(true);
try {
const updated = await updateLead(leadUuid, {
name: values.name,
mobile: blankToNull(values.mobile),
email: blankToNull(values.email),
companyName: blankToNull(values.companyName),
jobTitle: blankToNull(values.jobTitle),
notes: blankToNull(values.notes),
});
setValues(toValues(updated));
setState(updated);
setSaved(true);
} catch (err) {
const data = err instanceof ApiError
? (err.data as { code?: string; errors?: string[]; details?: { field?: unknown } } | undefined)
: undefined;
const code = data?.code;
const named = code === "REQUIRED_FIELD" ? data?.errors ?? [] : [typeof data?.details?.field === "string" ? data.details.field : IMPLIED_FIELD[code ?? ""]];
const known = FIELDS.map(([f]) => f as string);
const fields = named.filter((f): f is string => !!f && known.includes(f));
// A named field the form does not render, or an unmapped code, must not make the failure silent.
if (code && CODE_MESSAGE[code] && fields.length && fields.length === named.length) {
setFieldErrors(Object.fromEntries(fields.map((f) => [f, t(CODE_MESSAGE[code])])));
} else {
setFormError(t("LeadSaveFailed"));
}
} finally {
setBusy(false);
}
}
const sharedLabel = (s: LeadDetail["sharedContacts"][number]) =>
t(s.sameMobile && s.sameEmail ? "LeadsSameMobileEmailAs" : s.sameMobile ? "LeadsSameMobileAs" : "LeadsSameEmailAs");
return (
<div className="mx-auto max-w-xl space-y-6">
<PageHeader title={lead.name} />
{lead.sharedContacts.length > 0 && (
<Alert>
<div className="col-start-2 space-y-1">
{lead.sharedContacts.map((s) => (
<p key={s.leadUuid}>
{sharedLabel(s)}{" "}
<Link href={`/leads/${s.leadUuid}`} className="inline-flex min-h-11 items-center font-medium text-primary underline-offset-4 hover:underline">{s.name}</Link>
</p>
))}
</div>
</Alert>
)}
{formError && <ErrorState message={formError} />}
{saved && <p role="status" className="text-sm text-muted-foreground">{t("LeadsSaved")}</p>}
{canEdit ? (
<form onSubmit={onSave} className="space-y-4" noValidate>
{FIELDS.map(([f, label]) => {
const err = fieldErrors[f];
return (
<div key={f} className="space-y-1.5">
<Label htmlFor={`lead-${f}`}>{t(label)}</Label>
{f === "notes" ? (
<textarea id="lead-notes" className={`${INPUT_CLASS} py-2`} rows={3} value={values.notes} disabled={busy}
aria-invalid={err ? true : undefined} aria-describedby={err ? "lead-notes-error" : undefined}
onChange={(e) => { setSaved(false); setValues({ ...values, notes: e.target.value }); }} />
) : (
<input id={`lead-${f}`} className={INPUT_CLASS} value={values[f]} disabled={busy} {...INPUT_ATTRS[f]}
aria-invalid={err ? true : undefined} aria-describedby={err ? `lead-${f}-error` : undefined}
onChange={(e) => { setSaved(false); setValues({ ...values, [f]: e.target.value }); }} />
)}
{err && <p id={`lead-${f}-error`} role="alert" className="text-sm text-destructive">{err}</p>}
</div>
);
})}
<Button type="submit" className={TALL} disabled={busy}>{t("Save")}</Button>
</form>
) : (
<dl className="space-y-4">
{FIELDS.map(([f, label]) => (
<div key={f} className="space-y-1.5">
<dt className="text-sm font-medium">{t(label)}</dt>
<dd className="min-h-6 whitespace-pre-wrap text-sm">{values[f]}</dd>
</div>
))}
</dl>
)}
<section className="space-y-3">
<h2 className="text-lg font-medium">{t("LeadsHistory")}</h2>
{lead.history.map((h) => {
const card = (
<div data-testid="history-card" className="min-h-11 space-y-1 rounded-lg border p-4">
<p className="font-medium">{h.eventName}</p>
{h.eventStart && h.eventEnd && (
<p className="text-sm text-muted-foreground">{formatDmy(h.eventStart.slice(0, 10))} - {formatDmy(h.eventEnd.slice(0, 10))}</p>
)}
<div className="flex flex-wrap items-center gap-2">
<Badge variant={h.leadType === "NEW" ? "default" : "secondary"}>{t(h.leadType === "NEW" ? "LeadNew" : "LeadExisting")}</Badge>
{h.temperature && <Badge variant="neutral">{t(TEMPERATURES[h.temperature])}</Badge>}
<Badge variant="neutral">{t(STATUSES[h.status])}</Badge>
</div>
<p className="text-sm">{h.salesperson?.name ?? t("LeadNone")}</p>
<p className="text-sm text-muted-foreground">{t("LeadCaptured")} {formatDmy(h.capturedAt.slice(0, 10))}</p>
</div>
);
return hasModule("BO_EVENT_LEADS")
? <Link key={h.eventLeadUuid} href={`/event-leads/${h.eventUuid}/${h.eventLeadUuid}`} className="block rounded-lg focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">{card}</Link>
: <div key={h.eventLeadUuid}>{card}</div>;
})}
</section>
</div>
);
}
export default function LeadPage() {
return (
<RequireModule pathname="/leads">
<Lead />
</RequireModule>
);
}
@@ -0,0 +1,71 @@
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() }));
vi.mock("@/app/lib/services/adminLeads", async (importActual) => ({
...(await importActual<typeof import("@/app/lib/services/adminLeads")>()),
listLeads: mocks.listLeads,
}));
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";
const ROW = {
leadUuid: "l-1", name: "Aisyah", mobile: "+60123456701", email: "a@x.test", companyName: "Example Co", jobTitle: null,
eventCount: 2, lastEvent: { uuid: "e-2", name: "Penang Expo" }, lastCapturedAt: "2026-11-20T09:30:00Z",
latestSalesperson: { id: 7, name: "Ali" },
};
beforeEach(() => {
memoryRouter.reset("/leads");
mocks.listLeads.mockReset().mockResolvedValue({ items: [ROW], total: 1 });
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true });
});
describe("LeadsPage", () => {
it("renders NotAuthorized without BO_LEADS", () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
render(<LeadsPage />);
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
expect(mocks.listLeads).not.toHaveBeenCalled();
});
it("shows events count, last event and latest salesperson, with the name linking to the detail", async () => {
render(<LeadsPage />);
const row = (await screen.findByRole("link", { name: "Aisyah" })).closest("tr")!;
expect(screen.getByRole("link", { name: "Aisyah" })).toHaveAttribute("href", "/leads/l-1");
const r = within(row);
for (const text of ["+60123456701", "a@x.test", "Example Co", "2", "Penang Expo", "Ali"]) expect(r.getByText(text)).toBeVisible();
});
it("sends q as page 1 after the search box changes", async () => {
const user = userEvent.setup();
render(<LeadsPage />);
await waitFor(() => expect(mocks.listLeads).toHaveBeenCalled());
await user.type(screen.getByRole("searchbox", { name: "Search name, mobile or email" }), "aisyah");
await waitFor(() => expect(mocks.listLeads).toHaveBeenLastCalledWith(expect.objectContaining({ q: "aisyah", page: 1 })));
expect(memoryRouter.getSearch().get("q")).toBe("aisyah");
});
it("shows the empty state, and a no-match variant while searching", async () => {
mocks.listLeads.mockResolvedValue({ items: [], total: 0 });
const { unmount } = render(<LeadsPage />);
expect(await screen.findByText("No leads found")).toBeVisible();
unmount();
memoryRouter.reset("/leads", "q=zzz");
render(<LeadsPage />);
expect(await screen.findByText("No leads match your filters")).toBeVisible();
});
it("shows the error state and retries", async () => {
mocks.listLeads.mockRejectedValueOnce(new Error("Server says: boom xyz"));
render(<LeadsPage />);
expect(await screen.findByText("Failed to load leads")).toBeVisible();
expect(screen.queryByText(/boom xyz/)).toBeNull();
await userEvent.click(screen.getByRole("button", { name: /retry/i }));
expect(await screen.findByRole("link", { name: "Aisyah" })).toBeVisible();
});
});
+100
View File
@@ -0,0 +1,100 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import Link from "next/link";
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 { PageHeader } from "@/app/components/ui/page-header";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { RequireModule } from "@/app/lib/RequireModule";
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 type { LeadRow } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
const DEFAULTS = { q: "" };
function LeadsPageContent() {
const t = useT();
const { tableRef, pageSize } = useFitPageSize();
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
const [data, setData] = useState<{ items: LeadRow[]; total: number }>({ items: [], total: 0 });
const [loading, setLoading] = useState(true);
const [failed, setFailed] = useState(false);
const [reloadKey, setReloadKey] = useState(0);
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
useEffect(() => {
if (pageSize == null) return;
let cancelled = false;
// 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);
listLeads({ q: filters.q || undefined, page, pageSize })
.then((result) => { if (!cancelled) setData(result); })
.catch(() => { if (!cancelled) setFailed(true); })
.finally(() => { if (!cancelled) setLoading(false); });
return () => { cancelled = true; };
}, [filters, page, reloadKey, pageSize]);
const columns = useMemo<ColumnDef<LeadRow, unknown>[]>(
() => [
{
accessorKey: "name",
header: t("Name"),
enableSorting: false,
cell: ({ row }) => (
<Link href={`/leads/${row.original.leadUuid}`} className="font-medium text-primary underline-offset-4 hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none">
{row.original.name}
</Link>
),
},
{ accessorKey: "mobile", header: t("LeadMobile"), enableSorting: false },
{ accessorKey: "email", header: t("Email"), enableSorting: false },
{ accessorKey: "companyName", header: t("LeadCompany"), enableSorting: false },
{ accessorKey: "eventCount", header: t("LeadsEvents"), enableSorting: false },
{ id: "lastEvent", header: t("LeadsLastEvent"), enableSorting: false, cell: ({ row }) => row.original.lastEvent?.name ?? "" },
{ id: "latestSalesperson", header: t("LeadsLatestSalesperson"), enableSorting: false, cell: ({ row }) => row.original.latestSalesperson?.name ?? "" },
],
[t],
);
return (
<>
<PageHeader title={t("BO_LEADS")} />
{failed && <ErrorState message={t("LeadListLoadFailed")} onRetry={refetch} className="mb-4" />}
<FilterPanel activeCount={activeCount} onClear={clear}>
<FilterField label={t("LeadsSearch")}>
<FilterSearch className="w-full" aria-label={t("LeadsSearch")} placeholder={t("LeadsSearch")} value={filters.q} onChange={(q) => set({ q })} />
</FilterField>
</FilterPanel>
<DataTable
label={t("BO_LEADS")}
columns={columns}
data={data.items}
total={data.total}
page={page}
pageSize={pageSize ?? MIN_PAGE_SIZE}
tableRef={tableRef}
onPageChange={setPage}
isLoading={loading}
rowKey={(l) => l.leadUuid}
empty={<EmptyState title={activeCount > 0 ? t("LeadNoMatch") : t("LeadNoLeads")} />}
/>
</>
);
}
export default function LeadsPage() {
return (
<RequireModule pathname="/leads">
<LeadsPageContent />
</RequireModule>
);
}
@@ -280,4 +280,15 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
LeadCaptured: "Captured",
LeadNotFound: "Lead not found",
LeadGetFailed: "Failed to load the lead",
BO_LEADS: "Leads",
LeadsSearch: "Search name, mobile or email",
LeadsEvents: "Events",
LeadsLastEvent: "Last event",
LeadsLatestSalesperson: "Latest salesperson",
LeadsHistory: "Event history",
LeadsSaved: "Lead saved.",
LeadsSameMobileAs: "Same mobile as",
LeadsSameEmailAs: "Same email as",
LeadsSameMobileEmailAs: "Same mobile and email as",
LeadsViewLead: "View lead",
};
@@ -14,6 +14,7 @@ describe("routeModules", () => {
it("leaves other routes ungated", () => {
expect(requiredModuleFor("/")).toBeUndefined();
expect(requiredModulesFor("/members")).toBeUndefined();
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/event-leads", "/events", "/interests", "/roles", "/users"]);
expect(Object.keys(ROUTE_MODULES).sort()).toEqual(["/event-leads", "/events", "/interests", "/leads", "/roles", "/users"]);
expect(requiredModuleFor("/leads")).toBe("BO_LEADS");
});
});
@@ -8,6 +8,7 @@ export const ROUTE_MODULES: Record<string, string> = {
"/events": "BO_EVENTS",
"/interests": "BO_INTERESTS",
"/event-leads": "BO_EVENT_LEADS",
"/leads": "BO_LEADS",
};
export function requiredModuleFor(pathname: string): string | undefined {
@@ -0,0 +1,37 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPut: vi.fn() }));
vi.mock("@/app/lib/clientApi", () => mocks);
import { getLead, listLeads, updateLead } from "./adminLeads";
beforeEach(() => {
mocks.apiGet.mockReset();
mocks.apiPut.mockReset();
});
describe("adminLeads", () => {
it("lists with a 0-based page and q", async () => {
mocks.apiGet.mockResolvedValue({ content: [{ leadUuid: "1" }], totalElements: 41 });
const out = await listLeads({ q: "ann", page: 3, pageSize: 20 });
expect(mocks.apiGet).toHaveBeenCalledWith("/api/leads?q=ann&page=2&size=20");
expect(out).toEqual({ items: [{ leadUuid: "1" }], total: 41 });
});
it("omits a blank q and tolerates an empty body", async () => {
mocks.apiGet.mockResolvedValue(null);
const out = await listLeads({ q: "", page: 1, pageSize: 10 });
expect(mocks.apiGet).toHaveBeenCalledWith("/api/leads?page=0&size=10");
expect(out).toEqual({ items: [], total: 0 });
});
it("gets and updates one lead", async () => {
mocks.apiGet.mockResolvedValue({ leadUuid: "l-1" });
mocks.apiPut.mockResolvedValue({ leadUuid: "l-1" });
await getLead("l-1");
const payload = { name: "A", mobile: null, email: "a@x.com", companyName: null, jobTitle: null, notes: null };
await updateLead("l-1", payload);
expect(mocks.apiGet).toHaveBeenCalledWith("/api/leads/l-1");
expect(mocks.apiPut).toHaveBeenCalledWith("/api/leads/l-1", payload);
});
});
@@ -0,0 +1,17 @@
import { apiGet, apiPut } from "@/app/lib/clientApi";
import type { LeadDetail, LeadRow, LeadUpdatePayload } from "@/app/lib/types";
const BASE = "/api/leads";
export async function listLeads(params: { q?: string; /** 1-based. */ page: number; pageSize: number }): Promise<{ items: LeadRow[]; total: number }> {
const qs = new URLSearchParams();
if (params.q) qs.set("q", params.q);
qs.set("page", String(Math.max(0, params.page - 1)));
qs.set("size", String(params.pageSize));
const raw = await apiGet<{ content?: LeadRow[]; totalElements?: number } | null>(`${BASE}?${qs}`);
const items = Array.isArray(raw?.content) ? raw.content : [];
return { items, total: typeof raw?.totalElements === "number" ? raw.totalElements : items.length };
}
export const getLead = (uuid: string) => apiGet<LeadDetail>(`${BASE}/${uuid}`);
export const updateLead = (uuid: string, payload: LeadUpdatePayload) => apiPut<LeadDetail>(`${BASE}/${uuid}`, payload);
+52
View File
@@ -233,3 +233,55 @@ export interface EventLeadCapturePayload extends EventLeadUpdatePayload {
companyName?: string | null;
jobTitle?: string | null;
}
/** Lead records (`/api/admin/leads`). */
export interface LeadRow {
leadUuid: string;
name: string;
mobile: string | null;
email: string | null;
companyName: string | null;
jobTitle: string | null;
eventCount: number;
lastEvent: { uuid: string; name: string } | null;
lastCapturedAt: string | null;
latestSalesperson: { id: number; name: string } | null;
}
export interface LeadHistoryEntry {
eventLeadUuid: string;
eventUuid: string;
eventName: string;
eventStart: string | null;
eventEnd: string | null;
leadType: LeadType;
salesperson: { id: number; name: string } | null;
temperature: LeadTemperature | null;
status: LeadStatus;
capturedAt: string;
}
export interface SharedContact {
leadUuid: string;
name: string;
sameMobile: boolean;
sameEmail: boolean;
}
export interface LeadUpdatePayload {
name: string;
mobile: string | null;
email: string | null;
companyName: string | null;
jobTitle: string | null;
notes: string | null;
}
export interface LeadDetail extends LeadUpdatePayload {
leadUuid: string;
createdAt: string;
updatedAt: string;
updatedBy: string | null;
history: LeadHistoryEntry[];
sharedContacts: SharedContact[];
}