From 94e1e7fddedc4d120e7a5c0fd70afb4eb9574a18 Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 13:09:55 +0800 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../app/event-leads/[eventUuid]/page.test.tsx | 211 ++++++++++++ .../app/event-leads/[eventUuid]/page.tsx | 317 ++++++++++++++++++ .../app/event-leads/page.test.tsx | 108 ++++++ solvway-admin-portal/app/event-leads/page.tsx | 113 +++++++ .../app/lib/i18n/defaultMessages.ts | 30 ++ 5 files changed, 779 insertions(+) create mode 100644 solvway-admin-portal/app/event-leads/[eventUuid]/page.test.tsx create mode 100644 solvway-admin-portal/app/event-leads/[eventUuid]/page.tsx create mode 100644 solvway-admin-portal/app/event-leads/page.test.tsx create mode 100644 solvway-admin-portal/app/event-leads/page.tsx diff --git a/solvway-admin-portal/app/event-leads/[eventUuid]/page.test.tsx b/solvway-admin-portal/app/event-leads/[eventUuid]/page.test.tsx new file mode 100644 index 0000000..b2d37d8 --- /dev/null +++ b/solvway-admin-portal/app/event-leads/[eventUuid]/page.test.tsx @@ -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()), + 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(); + expect(screen.getByTestId("not-authorized")).toBeInTheDocument(); + }); + + it("sends eventUuid and each filter to listEventLeads", async () => { + const user = userEvent.setup(); + render(); + + 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(); + + 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(); + + 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(); + 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(); + 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(); + 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(); + await waitFor(() => expect(screen.getByRole("heading", { level: 1, name: "Test Event" })).toBeInTheDocument()); + }); + + it("shows the empty state when there are no leads", async () => { + render(); + 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(); + 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(); + 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(); + await user.click(screen.getByRole("combobox", { name: /temperature filter/i })); + expect(await screen.findByRole("option", { name: "Hot" })).toBeInTheDocument(); + }); +}); diff --git a/solvway-admin-portal/app/event-leads/[eventUuid]/page.tsx b/solvway-admin-portal/app/event-leads/[eventUuid]/page.tsx new file mode 100644 index 0000000..c2b0bc4 --- /dev/null +++ b/solvway-admin-portal/app/event-leads/[eventUuid]/page.tsx @@ -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(null); + const [reloadKey, setReloadKey] = useState(0); + const [salespeople, setSalespeople] = useState([]); + const [interests, setInterests] = useState([]); + // undefined while loading; null when the event is unknown or the lookup failed. + const [eventName, setEventName] = useState(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[]>( + () => [ + { + accessorKey: "name", + header: t("LeadName"), + cell: ({ row }) => ( + + {row.original.name} + + ), + }, + { + accessorKey: "mobile", + header: t("LeadMobile"), + cell: ({ row }) => {row.original.mobile || "—"}, + }, + { + accessorKey: "email", + header: t("Email"), + cell: ({ row }) => {row.original.email || "—"}, + }, + { + accessorKey: "leadType", + header: t("LeadType"), + enableSorting: false, + cell: ({ row }) => ( + + {t(row.original.leadType === "NEW" ? "LeadNew" : "LeadExisting")} + + ), + }, + { + accessorKey: "salesperson", + header: t("LeadSalesperson"), + enableSorting: false, + cell: ({ row }) => {row.original.salesperson?.name || "—"}, + }, + { + accessorKey: "temperature", + header: t("LeadTemperature"), + enableSorting: false, + cell: ({ row }) => { + const temp = row.original.temperature; + if (!temp) return —; + return {t(TEMPERATURE_OPTIONS.find((o) => o.value === temp)!.label)}; + }, + }, + { + accessorKey: "status", + header: t("Status"), + enableSorting: false, + cell: ({ row }) => { + const s = row.original.status; + return {t(STATUS_OPTIONS.find((o) => o.value === s)!.label)}; + }, + }, + { + accessorKey: "interests", + header: t("LeadInterests"), + enableSorting: false, + cell: ({ row }) => {row.original.interests.map(i => i.name).join(", ") || "—"}, + }, + { + accessorKey: "nextFollowUpDate", + header: t("LeadNextFollowUp"), + enableSorting: false, + cell: ({ row }) => {row.original.nextFollowUpDate ? formatDmy(row.original.nextFollowUpDate) : "—"}, + }, + ], + [t], + ); + + return ( + <> + + +