feat(admin-portal): event picker and event leads listing

Picker lists events with those running today first. The listing filters
by salesperson, temperature, status, interest and lead type, with a
table at md and up and tappable cards on phones.

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 13:09:55 +08:00
1 parent 90f25debc2
commit 94e1e7fdde
5 files changed
+779

No files matched your search

@@ -0,0 +1,211 @@
import { render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { describe, it, expect, vi, beforeEach } from "vitest";
// --- test mocks ---
const mocks = vi.hoisted(() => ({
listEventLeads: vi.fn(),
listEventSalespeople: vi.fn(),
listEventLeadInterests: vi.fn(),
listEventLeadEvents: vi.fn(),
useAdminAuth: vi.fn(),
}));
vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({
...(await importActual<typeof import("@/app/lib/services/adminEventLeads")>()),
listEventLeads: mocks.listEventLeads,
listEventSalespeople: mocks.listEventSalespeople,
listEventLeadInterests: mocks.listEventLeadInterests,
listEventLeadEvents: mocks.listEventLeadEvents,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("next/navigation", async () => ({
...(await import("@/test/memoryRouter")).navigationMock,
useParams: () => ({ eventUuid: "evt-1" }),
}));
import { memoryRouter } from "@/test/memoryRouter";
import EventLeadsDetailPage from "./page";
beforeEach(() => {
memoryRouter.reset("/event-leads/evt-1");
mocks.listEventLeads.mockReset().mockResolvedValue({ items: [], total: 0 });
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" }]);
mocks.useAdminAuth.mockReset().mockReturnValue({
loading: false,
hasModule: () => true,
});
});
describe("EventLeadsDetailPage (listing)", { timeout: 20000 }, () => {
it("renders NotAuthorized when the EventLeads module is absent", () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
render(<EventLeadsDetailPage />);
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
});
it("sends eventUuid and each filter to listEventLeads", async () => {
const user = userEvent.setup();
render(<EventLeadsDetailPage />);
await waitFor(() => expect(mocks.listEventLeads).toHaveBeenCalledWith("evt-1", expect.objectContaining({ page: 1, pageSize: expect.any(Number) })));
// Filter by temperature
await user.click(screen.getByRole("combobox", { name: /temperature filter/i }));
await user.click(await screen.findByRole("option", { name: "Hot" }));
await waitFor(() =>
expect(mocks.listEventLeads).toHaveBeenLastCalledWith("evt-1", expect.objectContaining({ temperature: "HOT", page: 1 })),
);
// Filter by status
await user.click(screen.getByRole("combobox", { name: /status filter/i }));
await user.click(await screen.findByRole("option", { name: "Won" }));
await waitFor(() =>
expect(mocks.listEventLeads).toHaveBeenLastCalledWith("evt-1", expect.objectContaining({ status: "WON", page: 1 })),
);
// Filter by lead type
await user.click(screen.getByRole("combobox", { name: /lead type filter/i }));
await user.click(await screen.findByRole("option", { name: "New" }));
await waitFor(() =>
expect(mocks.listEventLeads).toHaveBeenLastCalledWith("evt-1", expect.objectContaining({ leadType: "NEW", page: 1 })),
);
// Filter by salesperson
await user.click(screen.getByRole("combobox", { name: /salesperson filter/i }));
await user.click(await screen.findByRole("option", { name: "Jane Sales" }));
await waitFor(() =>
expect(mocks.listEventLeads).toHaveBeenLastCalledWith("evt-1", expect.objectContaining({ salespersonId: "1", page: 1 })),
);
// Filter by interest
await user.click(screen.getByRole("combobox", { name: /interest filter/i }));
await user.click(await screen.findByRole("option", { name: "Product A" }));
await waitFor(() =>
expect(mocks.listEventLeads).toHaveBeenLastCalledWith("evt-1", expect.objectContaining({ interestId: "1", page: 1 })),
);
});
it("renders lead cards on mobile view with data-testid", async () => {
mocks.listEventLeads.mockResolvedValue({
items: [{
eventLeadUuid: "el-1",
eventUuid: "evt-1",
leadUuid: "lead-1",
name: "John Doe",
mobile: "+60123456789",
email: "john@example.com",
companyName: "Acme",
jobTitle: "Manager",
leadType: "NEW",
salesperson: { id: 1, name: "Jane Sales" },
temperature: "HOT",
status: "OPEN",
interests: [{ id: 1, name: "Product A", active: true }],
nextFollowUpDate: "2025-06-15",
notes: null,
capturedAt: "2025-06-01",
}],
total: 1,
});
render(<EventLeadsDetailPage />);
await waitFor(() => {
expect(screen.getByTestId("lead-card")).toBeInTheDocument();
});
});
it("links each lead row/card to its detail page", async () => {
mocks.listEventLeads.mockResolvedValue({
items: [{
eventLeadUuid: "el-1",
eventUuid: "evt-1",
leadUuid: "lead-1",
name: "John Doe",
mobile: "+60123456789",
email: "john@example.com",
companyName: "Acme",
jobTitle: "Manager",
leadType: "NEW",
salesperson: { id: 1, name: "Jane Sales" },
temperature: "HOT",
status: "OPEN",
interests: [{ id: 1, name: "Product A", active: true }],
nextFollowUpDate: "2025-06-15",
notes: null,
capturedAt: "2025-06-01",
}],
total: 1,
});
render(<EventLeadsDetailPage />);
await waitFor(() => {
// The lead card is a link to the detail page
const card = screen.getByTestId("lead-card");
expect(card).toHaveAttribute("href", "/event-leads/evt-1/el-1");
});
const card = within(screen.getByTestId("lead-card"));
for (const text of ["John Doe", "+60123456789", "New", "Hot", "Open"]) expect(card.getByText(text)).toBeInTheDocument();
expect(card.getByText(/Next follow-up.*15\/06\/2025/)).toBeInTheDocument();
});
it("offers each filter's All choice once", async () => {
const user = userEvent.setup();
render(<EventLeadsDetailPage />);
await user.click(screen.getByRole("combobox", { name: /salesperson filter/i }));
await screen.findByRole("option", { name: "Jane Sales" });
expect(screen.getAllByRole("option").map((o) => o.textContent)).toEqual(["All", "Jane Sales"]);
});
it("falls back to the module title when the event is not in the list", async () => {
mocks.listEventLeadEvents.mockResolvedValue([]);
render(<EventLeadsDetailPage />);
await waitFor(() => expect(screen.getByRole("heading", { level: 1, name: "Event leads" })).toBeInTheDocument());
});
it("shows the Add lead link to /event-leads/{eventUuid}/new", async () => {
render(<EventLeadsDetailPage />);
await waitFor(() => expect(screen.getByRole("link", { name: /add lead/i })).toHaveAttribute("href", "/event-leads/evt-1/new"));
});
it("renders the header with the event name", async () => {
render(<EventLeadsDetailPage />);
await waitFor(() => expect(screen.getByRole("heading", { level: 1, name: "Test Event" })).toBeInTheDocument());
});
it("shows the empty state when there are no leads", async () => {
render(<EventLeadsDetailPage />);
await waitFor(() => expect(screen.queryByText("John Doe")).not.toBeInTheDocument());
});
it("shows the error state and lets the user retry on a load failure", async () => {
mocks.listEventLeads.mockRejectedValueOnce(new Error("network down"));
mocks.listEventLeads.mockResolvedValueOnce({ items: [], total: 0 });
render(<EventLeadsDetailPage />);
await waitFor(() => expect(screen.getByText(/network down/i)).toBeInTheDocument());
await userEvent.click(screen.getByRole("button", { name: /retry/i }));
await waitFor(() => expect(mocks.listEventLeads).toHaveBeenCalledTimes(2));
});
it("hides the table below md and shows one pager per layout", async () => {
mocks.listEventLeads.mockResolvedValue({ items: [], total: 45 });
const { container } = render(<EventLeadsDetailPage />);
await waitFor(() => expect(mocks.listEventLeads).toHaveBeenCalled());
const table = screen.getByRole("table").closest("div.hidden");
expect(table).not.toBeNull();
expect(table!.className).toContain("md:block");
// DataTable brings its own pager; the phone pager (44px targets) must sit inside the md:hidden card list.
expect(container.querySelectorAll('[data-slot="table-pager"]')).toHaveLength(1);
const next = screen.getAllByRole("button", { name: /next/i }).find((b) => !b.closest('[data-slot="table-pager"]'));
expect(next?.closest(".md\\:hidden")).not.toBeNull();
});
it("labels temperature and status options through i18n keys", async () => {
const user = userEvent.setup();
render(<EventLeadsDetailPage />);
await user.click(screen.getByRole("combobox", { name: /temperature filter/i }));
expect(await screen.findByRole("option", { name: "Hot" })).toBeInTheDocument();
});
});
@@ -0,0 +1,317 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useParams } from "next/navigation";
import Link from "next/link";
import { 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";
import { FilterField, FilterPanel, FilterSelect } 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 { 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";
const DEFAULTS = { salespersonId: "", temperature: "", status: "", interestId: "", leadType: "" };
const TEMPERATURE_OPTIONS = [{ value: "HOT", label: "LeadHot" }, { value: "WARM", label: "LeadWarm" }, { value: "COLD", label: "LeadCold" }];
const STATUS_OPTIONS = [{ value: "OPEN", label: "LeadOpen" }, { value: "CONTACTED", label: "LeadContacted" }, { value: "QUALIFIED", label: "LeadQualified" }, { value: "WON", label: "LeadWon" }, { value: "LOST", label: "LeadLost" }];
const LEAD_TYPE_OPTIONS = [{ value: "NEW", label: "LeadNew" }, { value: "EXISTING", label: "LeadExisting" }];
const TEMPERATURE_BADGE = { HOT: "negative", WARM: "warning", COLD: "neutral" } as const;
const STATUS_BADGE = { OPEN: "neutral", CONTACTED: "neutral", QUALIFIED: "contrast", WON: "positive", LOST: "negative" } as const;
function EventLeadsDetailPageContent() {
const t = useT();
const { eventUuid } = useParams<{ eventUuid: string }>();
const { tableRef, pageSize } = useFitPageSize();
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
const [data, setData] = useState<{ items: EventLeadRow[]; total: number }>({ items: [], total: 0 });
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [reloadKey, setReloadKey] = useState(0);
const [salespeople, setSalespeople] = useState<SalespersonOption[]>([]);
const [interests, setInterests] = useState<InterestOption[]>([]);
// undefined while loading; null when the event is unknown or the lookup failed.
const [eventName, setEventName] = useState<string | null | undefined>(undefined);
// Load event name from the events list
useEffect(() => {
let cancelled = false;
listEventLeadEvents()
.then((events) => {
if (!cancelled) {
const found = events.find((e) => e.uuid === eventUuid);
setEventName(found ? found.name : null);
}
})
.catch(() => { if (!cancelled) setEventName(null); });
return () => { cancelled = true; };
}, [eventUuid]);
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
// Load lookup options
useEffect(() => {
let cancelled = false;
Promise.allSettled([
listEventSalespeople(eventUuid),
listEventLeadInterests(),
]).then(([salesRes, interestRes]) => {
if (!cancelled) {
if (salesRes.status === "fulfilled") setSalespeople(salesRes.value);
if (interestRes.status === "fulfilled") setInterests(interestRes.value);
}
});
return () => { cancelled = true; };
}, [eventUuid]);
// Fetch leads
useEffect(() => {
if (pageSize == null) return;
let cancelled = false;
// 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);
listEventLeads(eventUuid, { page, pageSize, ...filters })
.then((result) => {
if (!cancelled) setData(result);
})
.catch((err: unknown) => {
if (!cancelled) setError(err instanceof Error ? err.message : "LeadListLoadFailed");
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => { cancelled = true; };
}, [eventUuid, filters, page, pageSize, reloadKey]);
const salespersonOptions = useMemo(
() => salespeople.map((o) => ({ value: String(o.id), label: o.name })),
[salespeople],
);
const interestOptions = useMemo(
() => interests.map((o) => ({ value: String(o.id), label: o.name })),
[interests],
);
const temperatureOptions = useMemo(
() => TEMPERATURE_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
[t],
);
const statusOptions = useMemo(
() => STATUS_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
[t],
);
const leadTypeOptions = useMemo(
() => LEAD_TYPE_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
[t],
);
const columns = useMemo<ColumnDef<EventLeadRow, unknown>[]>(
() => [
{
accessorKey: "name",
header: t("LeadName"),
cell: ({ row }) => (
<Link
href={`/event-leads/${row.original.eventUuid}/${row.original.eventLeadUuid}`}
className="font-medium text-primary underline-offset-4 hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none min-h-11 flex items-center"
>
{row.original.name}
</Link>
),
},
{
accessorKey: "mobile",
header: t("LeadMobile"),
cell: ({ row }) => <span>{row.original.mobile || "—"}</span>,
},
{
accessorKey: "email",
header: t("Email"),
cell: ({ row }) => <span>{row.original.email || "—"}</span>,
},
{
accessorKey: "leadType",
header: t("LeadType"),
enableSorting: false,
cell: ({ row }) => (
<Badge variant={row.original.leadType === "NEW" ? "default" : "secondary"}>
{t(row.original.leadType === "NEW" ? "LeadNew" : "LeadExisting")}
</Badge>
),
},
{
accessorKey: "salesperson",
header: t("LeadSalesperson"),
enableSorting: false,
cell: ({ row }) => <span>{row.original.salesperson?.name || "—"}</span>,
},
{
accessorKey: "temperature",
header: t("LeadTemperature"),
enableSorting: false,
cell: ({ row }) => {
const temp = row.original.temperature;
if (!temp) return <span>—</span>;
return <Badge variant={TEMPERATURE_BADGE[temp]}>{t(TEMPERATURE_OPTIONS.find((o) => o.value === temp)!.label)}</Badge>;
},
},
{
accessorKey: "status",
header: t("Status"),
enableSorting: false,
cell: ({ row }) => {
const s = row.original.status;
return <Badge variant={STATUS_BADGE[s]}>{t(STATUS_OPTIONS.find((o) => o.value === s)!.label)}</Badge>;
},
},
{
accessorKey: "interests",
header: t("LeadInterests"),
enableSorting: false,
cell: ({ row }) => <span>{row.original.interests.map(i => i.name).join(", ") || "—"}</span>,
},
{
accessorKey: "nextFollowUpDate",
header: t("LeadNextFollowUp"),
enableSorting: false,
cell: ({ row }) => <span>{row.original.nextFollowUpDate ? formatDmy(row.original.nextFollowUpDate) : "—"}</span>,
},
],
[t],
);
return (
<>
<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>
}
/>
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
<FilterPanel activeCount={activeCount} onClear={clear}>
<FilterField label={t("LeadSalespersonFilter")}>
<FilterSelect className="w-full" aria-label={t("LeadSalespersonFilter")} allLabel={t("All")} options={salespersonOptions} value={filters.salespersonId} onChange={salespersonId => set({ salespersonId })} />
</FilterField>
<FilterField label={t("LeadTemperatureFilter")}>
<FilterSelect className="w-full" aria-label={t("LeadTemperatureFilter")} allLabel={t("All")} options={temperatureOptions} value={filters.temperature} onChange={temperature => set({ temperature })} />
</FilterField>
<FilterField label={t("LeadStatusFilter")}>
<FilterSelect className="w-full" aria-label={t("LeadStatusFilter")} allLabel={t("All")} options={statusOptions} value={filters.status} onChange={status => set({ status })} />
</FilterField>
<FilterField label={t("LeadInterestFilter")}>
<FilterSelect className="w-full" aria-label={t("LeadInterestFilter")} allLabel={t("All")} options={interestOptions} value={filters.interestId} onChange={interestId => set({ interestId })} />
</FilterField>
<FilterField label={t("LeadLeadTypeFilter")}>
<FilterSelect className="w-full" aria-label={t("LeadLeadTypeFilter")} allLabel={t("All")} options={leadTypeOptions} value={filters.leadType} onChange={leadType => set({ leadType })} />
</FilterField>
</FilterPanel>
{/* Desktop table (md+) */}
<div className="hidden md:block">
<DataTable
label={t("BO_EVENT_LEADS")}
columns={columns}
data={data.items}
total={data.total}
page={page}
pageSize={pageSize ?? MIN_PAGE_SIZE}
tableRef={tableRef}
onPageChange={setPage}
isLoading={loading}
rowKey={(e) => String(e.eventLeadUuid)}
empty={<EmptyState title={activeCount > 0 ? t("LeadNoMatch") : t("LeadNoLeads")} />}
/>
</div>
{/* Mobile cards (below md) */}
<div className="md:hidden space-y-3" aria-busy={loading}>
{data.items.map((lead) => (
<Link
key={lead.eventLeadUuid}
href={`/event-leads/${lead.eventUuid}/${lead.eventLeadUuid}`}
data-testid="lead-card"
className={`flex flex-col gap-1 rounded-lg border p-3 transition-colors hover:bg-accent min-h-11${loading ? " opacity-60" : ""}`}
>
<div className="flex items-center justify-between">
<span className="font-medium">{lead.name}</span>
<Badge variant={lead.leadType === "NEW" ? "default" : "secondary"}>{t(lead.leadType === "NEW" ? "LeadNew" : "LeadExisting")}</Badge>
</div>
<div className="text-sm text-muted-foreground">
{lead.mobile || "—"}
</div>
<div className="flex items-center gap-2 text-sm">
{lead.temperature && <Badge variant={TEMPERATURE_BADGE[lead.temperature]} className="shrink-0">{t(TEMPERATURE_OPTIONS.find((o) => o.value === lead.temperature)!.label)}</Badge>}
<Badge variant={STATUS_BADGE[lead.status]} className="shrink-0">{t(STATUS_OPTIONS.find((o) => o.value === lead.status)!.label)}</Badge>
</div>
<div className="text-sm text-muted-foreground">
{t("LeadNextFollowUp")}: {lead.nextFollowUpDate ? formatDmy(lead.nextFollowUpDate) : "—"}
</div>
</Link>
))}
{data.items.length === 0 && !loading && (
<EmptyState title={activeCount > 0 ? t("LeadNoMatch") : t("LeadNoLeads")} />
)}
{/* Phone pager: 44px targets; DataTable has its own above md */}
{data.total > (pageSize ?? MIN_PAGE_SIZE) && (
<div className="flex items-center justify-between mt-4">
<div className="text-sm text-muted-foreground">
{t("PagerRange", {
first: data.total === 0 ? 0 : (page - 1) * (pageSize ?? MIN_PAGE_SIZE) + 1,
last: Math.min(page * (pageSize ?? MIN_PAGE_SIZE), data.total),
total: data.total,
})}
</div>
<div className="flex items-center gap-2">
<Button
variant="outline"
size="sm"
disabled={page <= 1}
onClick={() => setPage(page - 1)}
className="min-h-11"
>
{t("PagerPrevious")}
</Button>
<Button
variant="outline"
size="sm"
disabled={page * (pageSize ?? MIN_PAGE_SIZE) >= data.total}
onClick={() => setPage(page + 1)}
className="min-h-11"
>
{t("PagerNext")}
</Button>
</div>
</div>
)}
</div>
</>
);
}
export default function EventLeadsDetailPage() {
return (
<RequireModule pathname="/event-leads">
<EventLeadsDetailPageContent />
</RequireModule>
);
}
@@ -0,0 +1,108 @@
import { act, render, screen, waitFor } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach } from "vitest";
const mocks = vi.hoisted(() => ({
listEventLeadEvents: vi.fn(),
useAdminAuth: vi.fn(),
}));
vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({
...(await importActual<typeof import("@/app/lib/services/adminEventLeads")>()),
listEventLeadEvents: mocks.listEventLeadEvents,
}));
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
vi.mock("next/navigation", async () => (await import("@/test/memoryRouter")).navigationMock);
import { memoryRouter } from "@/test/memoryRouter";
import EventLeadsPage from "./page";
beforeEach(() => {
memoryRouter.reset("/event-leads");
mocks.listEventLeadEvents.mockReset();
mocks.useAdminAuth.mockReset();
mocks.useAdminAuth.mockReturnValue({
loading: false,
hasModule: () => true,
});
});
describe("EventLeadsPage (picker)", () => {
it("renders NotAuthorized when the EventLeads module is absent from aclMenu", () => {
mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false });
render(<EventLeadsPage />);
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
});
it("lists events as tappable card links", async () => {
mocks.listEventLeadEvents.mockResolvedValue([
{ uuid: "evt-1", name: "Event Alpha", location: "Hall A", startDate: "2025-06-01", endDate: "2025-06-02" },
{ uuid: "evt-2", name: "Event Beta", location: "Hall B", startDate: "2025-07-01", endDate: "2025-07-02" },
]);
render(<EventLeadsPage />);
await waitFor(() => expect(mocks.listEventLeadEvents).toHaveBeenCalled());
expect(screen.getByText("Event Alpha")).toBeInTheDocument();
expect(screen.getByText("Event Beta")).toBeInTheDocument();
expect(screen.getByRole("link", { name: /Event Alpha/ })).toHaveAttribute("href", "/event-leads/evt-1");
expect(screen.getByRole("link", { name: /Event Beta/ })).toHaveAttribute("href", "/event-leads/evt-2");
});
it("shows location and dates formatted with formatDmy", async () => {
mocks.listEventLeadEvents.mockResolvedValue([
{ uuid: "evt-1", name: "Event Alpha", location: "Hall A", startDate: "2025-06-01", endDate: "2025-06-02" },
]);
render(<EventLeadsPage />);
await waitFor(() => expect(mocks.listEventLeadEvents).toHaveBeenCalled());
expect(screen.getByText("Hall A")).toBeInTheDocument();
expect(screen.getByText(/01\/06\/2025/)).toBeInTheDocument();
expect(screen.getByText(/02\/06\/2025/)).toBeInTheDocument();
});
it("puts events running today first", async () => {
// Use a date that's "today" relative to the test run
const today = new Date();
const iso = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
mocks.listEventLeadEvents.mockResolvedValue([
{ uuid: "evt-far", name: "Far Event", location: "Hall A", startDate: "2099-01-01", endDate: "2099-01-02" },
{ uuid: "evt-today", name: "Today Event", location: "Hall B", startDate: iso, endDate: iso },
]);
render(<EventLeadsPage />);
await waitFor(() => expect(mocks.listEventLeadEvents).toHaveBeenCalled());
const links = Array.from(screen.getAllByRole("link").filter((l) => l.getAttribute("href")?.startsWith("/event-leads/")));
expect(links[0]).toHaveAttribute("href", "/event-leads/evt-today");
expect(links[1]).toHaveAttribute("href", "/event-leads/evt-far");
});
it("shows an error state on load failure", async () => {
mocks.listEventLeadEvents.mockRejectedValueOnce(new Error("network down"));
render(<EventLeadsPage />);
await waitFor(() => expect(screen.getByText(/network down/i)).toBeInTheDocument());
});
it("counts an event that started earlier and ends later as running today", async () => {
const d = (offset: number) => {
const x = new Date();
x.setDate(x.getDate() + offset);
return `${x.getFullYear()}-${String(x.getMonth() + 1).padStart(2, "0")}-${String(x.getDate()).padStart(2, "0")}`;
};
mocks.listEventLeadEvents.mockResolvedValue([
{ uuid: "evt-later", name: "Later", location: null, startDate: d(5), endDate: d(6) },
{ uuid: "evt-running", name: "Running", location: null, startDate: d(-1), endDate: d(1) },
]);
render(<EventLeadsPage />);
await waitFor(() => expect(screen.getByText("Running")).toBeInTheDocument());
const links = screen.getAllByRole("link").filter((l) => l.getAttribute("href")?.startsWith("/event-leads/"));
expect(links[0]).toHaveAttribute("href", "/event-leads/evt-running");
});
it("retries the load after a failure", async () => {
mocks.listEventLeadEvents.mockRejectedValueOnce(new Error("network down"))
.mockResolvedValueOnce([{ uuid: "evt-1", name: "Back", location: null, startDate: null, endDate: null }]);
render(<EventLeadsPage />);
const retry = await screen.findByRole("button", { name: /retry/i });
await act(async () => retry.click());
expect(await screen.findByText("Back")).toBeInTheDocument();
});
});
@@ -0,0 +1,113 @@
"use client";
import { useEffect, useState } from "react";
import Link from "next/link";
import { Calendar, MapPin } from "lucide-react";
import { EmptyState, ErrorState } from "@/app/components/ui/states";
import { RequireModule } from "@/app/lib/RequireModule";
import { PageHeader } from "@/app/components/ui/page-header";
import { listEventLeadEvents } from "@/app/lib/services/adminEventLeads";
import type { EventLeadEvent } from "@/app/lib/types";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { formatDmy } from "@/app/lib/date-input";
const isoToday = () => {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
};
function EventLeadsPageContent() {
const t = useT();
const [events, setEvents] = useState<EventLeadEvent[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [reloadKey, setReloadKey] = useState(0);
useEffect(() => {
let cancelled = false;
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the triggered fetch below, which is the actual synchronization.
setLoading(true);
setError(null);
listEventLeadEvents()
.then((data) => {
if (!cancelled) setEvents(data);
})
.catch((err: unknown) => {
if (!cancelled) setError(err instanceof Error ? err.message : "LeadLoadFailed");
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => { cancelled = true; };
}, [reloadKey]);
const today = isoToday();
const sorted = events
.slice()
.sort((a, b) => {
// ISO dates compare as strings; an event runs today when start <= today <= end.
const running = (e: EventLeadEvent) => (e.startDate ?? "9") <= today && today <= (e.endDate ?? e.startDate ?? "");
return Number(running(b)) - Number(running(a));
});
if (error) {
return (
<>
<PageHeader title={t("BO_EVENT_LEADS")} />
<ErrorState message={t(error)} onRetry={() => setReloadKey((k) => k + 1)} className="mb-4" />
</>
);
}
if (loading) {
return (
<>
<PageHeader title={t("BO_EVENT_LEADS")} />
<div className="space-y-3">
{Array.from({ length: 3 }).map((_, i) => (
<div key={i} className="h-20 animate-pulse rounded-lg bg-muted" />
))}
</div>
</>
);
}
return (
<>
<PageHeader title={t("BO_EVENT_LEADS")} />
{sorted.length === 0 ? (
<EmptyState title={t("LeadNoEvents")} />
) : (
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
{sorted.map((evt) => (
<Link
key={evt.uuid}
href={`/event-leads/${evt.uuid}`}
className="flex flex-col gap-2 rounded-lg border p-4 transition-colors hover:bg-accent min-h-[8.5rem]"
>
<h2 className="font-semibold text-lg">{evt.name}</h2>
{evt.location && (
<div className="flex items-center gap-1 text-sm text-muted-foreground">
<MapPin className="size-3.5 shrink-0" aria-hidden="true" />
<span>{evt.location}</span>
</div>
)}
<div className="flex items-center gap-1 text-sm text-muted-foreground">
<Calendar className="size-3.5 shrink-0" aria-hidden="true" />
<span>{evt.startDate ? formatDmy(evt.startDate) : ""} – {evt.endDate ? formatDmy(evt.endDate) : ""}</span>
</div>
</Link>
))}
</div>
)}
</>
);
}
export default function EventLeadsPage() {
return (
<RequireModule pathname="/event-leads">
<EventLeadsPageContent />
</RequireModule>
);
}
@@ -225,4 +225,34 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
IntDeactivate: "Deactivate",
IntActivateFailed: "Failed to activate interest.",
IntDeactivateFailed: "Failed to deactivate interest.",
// Event leads messages
BO_EVENT_LEADS: "Event leads",
LeadName: "Name",
LeadMobile: "Mobile",
LeadType: "Lead type",
LeadSalesperson: "Salesperson",
LeadTemperature: "Temperature",
LeadInterests: "Interests",
LeadNextFollowUp: "Next follow-up",
LeadAddLead: "Add lead",
LeadNoEvents: "No events found",
LeadNoLeads: "No leads found",
LeadNoMatch: "No leads match your filters",
LeadLoadFailed: "Failed to load events",
LeadListLoadFailed: "Failed to load leads",
LeadSalespersonFilter: "Salesperson filter",
LeadTemperatureFilter: "Temperature filter",
LeadStatusFilter: "Status filter",
LeadInterestFilter: "Interest filter",
LeadLeadTypeFilter: "Lead type filter",
LeadHot: "Hot",
LeadWarm: "Warm",
LeadCold: "Cold",
LeadOpen: "Open",
LeadContacted: "Contacted",
LeadQualified: "Qualified",
LeadWon: "Won",
LeadLost: "Lost",
LeadNew: "New",
LeadExisting: "Existing",
};