diff --git a/openspec/changes/add-event-lead-capture/tasks.md b/openspec/changes/add-event-lead-capture/tasks.md index d5fd4d5..2a58ace 100644 --- a/openspec/changes/add-event-lead-capture/tasks.md +++ b/openspec/changes/add-event-lead-capture/tasks.md @@ -108,7 +108,7 @@ Design: `design.md` (decision numbers below refer to it). Every task runs serial - Scope: `solvway-admin-portal/app/interests/**`, `solvway-admin-portal/app/api/interests/**`, `solvway-admin-portal/app/lib/**` - Verify: `cd solvway-admin-portal && npx vitest run && npx tsc --noEmit && npm run lint && npm run build`. -- [ ] 4.2 Add the event-floor screens (design decision 10): +- [x] 4.2 Add the event-floor screens (design decision 10): - Pages: - `app/event-leads/page.tsx`: event picker. - `app/event-leads/[eventUuid]/page.tsx`: listing. `DataTable` at `md` and up; a card list below `md`, with filters. diff --git a/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.test.tsx b/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.test.tsx new file mode 100644 index 0000000..93d3a74 --- /dev/null +++ b/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.test.tsx @@ -0,0 +1,236 @@ +import { render, screen, waitFor, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, it, expect, vi, beforeEach } from "vitest"; +import { pickDate } from "@/test/pickDate"; + +const mocks = vi.hoisted(() => ({ + getEventLead: vi.fn(), + updateEventLead: vi.fn(), + listEventSalespeople: vi.fn(), + listEventLeadInterests: vi.fn(), + useAdminAuth: vi.fn(), +})); +vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({ + ...(await importActual()), + getEventLead: mocks.getEventLead, + updateEventLead: mocks.updateEventLead, + 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 { ApiError } from "@/app/lib/clientApi"; +import { memoryRouter } from "@/test/memoryRouter"; +import EventLeadPage from "./page"; + +const SERVER_MSG = "Server says: internal detail xyz"; +const apiError = (code: string, extra: { details?: Record } = {}, status = 400) => + new ApiError(SERVER_MSG, status, { code, errors: [], details: {}, ...extra }); + +const LEAD = { + eventLeadUuid: "el-1", eventUuid: "evt-1", leadUuid: "l-1", + name: "Ann Lead", mobile: "+6591111111", email: "ann@x.com", companyName: "Acme", jobTitle: "CEO", + leadType: "NEW", salesperson: { id: 7, name: "Jane Sales" }, temperature: "WARM", status: "CONTACTED", + interests: [{ id: 1, name: "Product A", active: true }, { id: 2, name: "Product B", active: false }], + nextFollowUpDate: "2026-12-01", notes: "Call back", capturedAt: "2026-11-20T09:30:00Z", +}; +const PAYLOAD = { salespersonId: 7, temperature: "WARM", status: "CONTACTED", interestIds: [1, 2], nextFollowUpDate: "2026-12-01", notes: "Call back" }; + +async function open(lead: Record = {}) { + mocks.getEventLead.mockResolvedValue({ ...LEAD, ...lead }); + render(); + await screen.findByLabelText("Status"); + return userEvent.setup(); +} + +beforeEach(() => { + memoryRouter.reset("/event-leads/evt-1/el-1"); + mocks.getEventLead.mockReset(); + mocks.updateEventLead.mockReset().mockResolvedValue(LEAD); + mocks.listEventSalespeople.mockReset().mockResolvedValue([{ id: 8, name: "Bob Other", username: "bob" }]); + mocks.listEventLeadInterests.mockReset().mockResolvedValue([ + { id: 1, name: "Product A", active: true }, + { id: 3, name: "Product C", active: true }, + ]); + mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true }); +}); + +describe("EventLeadPage", { timeout: 20000 }, () => { + it("renders NotAuthorized when the module is absent", () => { + mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => false }); + render(); + expect(screen.getByTestId("not-authorized")).toBeInTheDocument(); + }); + + it("shows the lead contact read-only with type badge and captured date", async () => { + await open(); + expect(screen.getByText("Ann Lead")).toBeVisible(); + expect(screen.getByText("+6591111111")).toBeVisible(); + expect(screen.getByText("ann@x.com")).toBeVisible(); + expect(screen.getByText("Acme")).toBeVisible(); + expect(screen.getByText("CEO")).toBeVisible(); + expect(screen.getByText("New")).toBeVisible(); + expect(screen.getByText(/20\/11\/2026/)).toBeVisible(); + expect(screen.queryByLabelText("Name")).toBeNull(); + expect(screen.queryByLabelText("Mobile")).toBeNull(); + }); + + it("shows the Existing badge for an existing lead", async () => { + await open({ leadType: "EXISTING" }); + expect(screen.getByText("Existing")).toBeVisible(); + }); + + it("prefills the editable fields from the event lead", async () => { + await open(); + expect(screen.getByLabelText("Salesperson")).toHaveValue("7"); + expect(screen.getByLabelText("Temperature")).toHaveValue("WARM"); + expect(screen.getByLabelText("Status")).toHaveValue("CONTACTED"); + expect(screen.getByLabelText("Product A")).toBeChecked(); + expect(screen.getByLabelText("Next follow-up")).toHaveValue("01/12/2026"); + expect(screen.getByLabelText("Notes")).toHaveValue("Call back"); + }); + + it("keeps the current salesperson selectable when not on the event team list", async () => { + await open(); + const select = screen.getByLabelText("Salesperson"); + expect(within(select).getByRole("option", { name: "Jane Sales" })).toBeInTheDocument(); + expect(within(select).getByRole("option", { name: "Bob Other" })).toBeInTheDocument(); + expect(within(select).getByRole("option", { name: "None" })).toBeInTheDocument(); + }); + + it("lists an inactive interest already on the lead (not in the options list) as checked, once", async () => { + await open(); + expect(screen.getByLabelText("Product A")).toBeChecked(); + expect(screen.getByLabelText("Product B")).toBeChecked(); + expect(screen.getByLabelText("Product C")).not.toBeChecked(); + expect(screen.getAllByLabelText("Product A")).toHaveLength(1); + }); + + it("unchecking the inactive interest saves interestIds without it", async () => { + const user = await open(); + await user.click(screen.getByLabelText("Product B")); + await user.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(mocks.updateEventLead).toHaveBeenCalledTimes(1)); + expect(mocks.updateEventLead).toHaveBeenCalledWith("evt-1", "el-1", { ...PAYLOAD, interestIds: [1] }); + }); + + it("saves unchanged values with all six fields, then goes back to the list", async () => { + const user = await open(); + await user.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(mocks.updateEventLead).toHaveBeenCalledTimes(1)); + expect(mocks.updateEventLead).toHaveBeenCalledWith("evt-1", "el-1", PAYLOAD); + await waitFor(() => expect(memoryRouter.push).toHaveBeenCalledWith("/event-leads/evt-1")); + }); + + it("saves edited values", async () => { + const user = await open(); + await user.selectOptions(screen.getByLabelText("Salesperson"), "8"); + await user.selectOptions(screen.getByLabelText("Temperature"), "HOT"); + await user.selectOptions(screen.getByLabelText("Status"), "WON"); + await user.click(screen.getByLabelText("Product B")); + await user.click(screen.getByLabelText("Product C")); + pickDate("Next follow-up", "2026-12-05"); + const notes = screen.getByLabelText("Notes"); + await user.clear(notes); + await user.type(notes, "Signed"); + await user.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(mocks.updateEventLead).toHaveBeenCalledTimes(1)); + expect(mocks.updateEventLead).toHaveBeenCalledWith("evt-1", "el-1", { + salespersonId: 8, temperature: "HOT", status: "WON", interestIds: [1, 3], nextFollowUpDate: "2026-12-05", notes: "Signed", + }); + }); + + it("sends null for emptied fields", async () => { + const user = await open(); + await user.selectOptions(screen.getByLabelText("Salesperson"), ""); + await user.selectOptions(screen.getByLabelText("Temperature"), ""); + await user.clear(screen.getByLabelText("Notes")); + await user.click(screen.getByLabelText("Product A")); + await user.click(screen.getByLabelText("Product B")); + await user.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(mocks.updateEventLead).toHaveBeenCalledTimes(1)); + expect(mocks.updateEventLead).toHaveBeenCalledWith("evt-1", "el-1", { + salespersonId: null, temperature: null, status: "CONTACTED", interestIds: [], nextFollowUpDate: "2026-12-01", notes: null, + }); + }); + + it("has a Back link to the event's leads", async () => { + await open(); + expect(screen.getByRole("link", { name: "Back" })).toHaveAttribute("href", "/event-leads/evt-1"); + }); + + it("uses touch targets of at least 44px", async () => { + await open(); + for (const label of ["Salesperson", "Temperature", "Status"]) expect(screen.getByLabelText(label)).toHaveClass("min-h-11"); + expect(screen.getByLabelText("Product A").closest("label")).toHaveClass("min-h-11"); + expect(screen.getByRole("button", { name: "Save" })).toHaveClass("min-h-11"); + expect(screen.getByRole("link", { name: "Back" })).toHaveClass("min-h-11"); + }); + + it("shows a not-found state with a Back link for EVENT_LEAD_NOT_FOUND", async () => { + mocks.getEventLead.mockRejectedValue(apiError("EVENT_LEAD_NOT_FOUND", {}, 404)); + render(); + expect(await screen.findByText("Lead not found")).toBeVisible(); + expect(screen.getByRole("link", { name: "Back" })).toHaveAttribute("href", "/event-leads/evt-1"); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + expect(screen.queryByRole("button", { name: "Save" })).toBeNull(); + }); + + it("shows an error with retry for other load failures, and retry reloads", async () => { + mocks.getEventLead.mockRejectedValueOnce(apiError("BOOM", {}, 500)).mockResolvedValue(LEAD); + render(); + expect(await screen.findByRole("alert")).toHaveTextContent("Failed to load the lead"); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + await userEvent.setup().click(screen.getByRole("button", { name: "Retry" })); + expect(await screen.findByLabelText("Status")).toBeVisible(); + }); + + it.each([ + ["TOO_LONG", "notes", "Notes", "Too long."], + ["INVALID_DATE", "nextFollowUpDate", "Next follow-up", "Enter a valid date."], + ["NOT_ON_TEAM", "salespersonId", "Salesperson", "This person is not on the event team."], + ["INVALID_VALUE", "temperature", "Temperature", "Invalid value."], + ["INVALID_VALUE", "status", "Status", "Invalid value."], + ])("%s on %s shows the mapped message under the field", async (code, field, label, text) => { + mocks.updateEventLead.mockRejectedValue(apiError(code, { details: { field } })); + const user = await open(); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByText(text)).toBeVisible(); + const el = screen.getByLabelText(label); + expect(el).toHaveAttribute("aria-invalid", "true"); + expect(document.getElementById(el.getAttribute("aria-describedby")!)).toHaveTextContent(text); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + expect(memoryRouter.push).not.toHaveBeenCalled(); + }); + + it("INACTIVE_INTEREST shows the mapped message under the interests group", async () => { + mocks.updateEventLead.mockRejectedValue(apiError("INACTIVE_INTEREST", { details: { field: "interestIds" } })); + const user = await open(); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByText("An interest is no longer active.")).toBeVisible(); + const group = screen.getByRole("group", { name: "Interests" }); + expect(group).toHaveAttribute("aria-invalid", "true"); + expect(document.getElementById(group.getAttribute("aria-describedby")!)).toHaveTextContent("An interest is no longer active."); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + }); + + it("other save errors show a form-level message and stay on the page", async () => { + mocks.updateEventLead.mockRejectedValue(apiError("SOMETHING_ELSE")); + const user = await open(); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByRole("alert")).toHaveTextContent("Could not save the lead. Please try again."); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + expect(memoryRouter.push).not.toHaveBeenCalled(); + }); + + it("an unknown field in a field error gives a form-level message", async () => { + mocks.updateEventLead.mockRejectedValue(apiError("TOO_LONG", { details: { field: "bogus" } })); + const user = await open(); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByRole("alert")).toHaveTextContent("Could not save the lead. Please try again."); + }); +}); diff --git a/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.tsx b/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.tsx new file mode 100644 index 0000000..dbccea6 --- /dev/null +++ b/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.tsx @@ -0,0 +1,197 @@ +"use client"; + +import { useEffect, useState, type FormEvent } from "react"; +import { useParams, useRouter } from "next/navigation"; +import Link from "next/link"; +import { Badge } from "@/app/components/ui/badge"; +import { Button } from "@/app/components/ui/button"; +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 { RequireModule } from "@/app/lib/RequireModule"; +import { ApiError } from "@/app/lib/clientApi"; +import { formatDmy } from "@/app/lib/date-input"; +import { getEventLead, listEventLeadInterests, listEventSalespeople, updateEventLead } from "@/app/lib/services/adminEventLeads"; +import type { EventLeadRow, InterestOption, LeadStatus, LeadTemperature, SalespersonOption } from "@/app/lib/types"; +import { useT } from "@/app/lib/i18n/MessagesProvider"; + +const TEMPERATURES: [LeadTemperature, string][] = [["HOT", "LeadHot"], ["WARM", "LeadWarm"], ["COLD", "LeadCold"]]; +const STATUSES: [LeadStatus, string][] = [["OPEN", "LeadOpen"], ["CONTACTED", "LeadContacted"], ["QUALIFIED", "LeadQualified"], ["WON", "LeadWon"], ["LOST", "LeadLost"]]; +const CODE_MESSAGE: Record = { + TOO_LONG: "LeadErrTooLong", + INVALID_DATE: "LeadErrInvalidDate", + NOT_ON_TEAM: "LeadErrNotOnTeam", + INACTIVE_INTEREST: "LeadErrInactiveInterest", + INVALID_VALUE: "LeadErrInvalidValue", +}; +const FIELDS = ["salespersonId", "temperature", "status", "interestIds", "nextFollowUpDate", "notes"]; +const SELECT_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 TALL = "min-h-11"; + +type Loaded = { lead: EventLeadRow; salespeople: SalespersonOption[]; interests: InterestOption[] }; +type LoadState = "loading" | "notFound" | "error" | Loaded; + +function EventLead() { + const t = useT(); + const router = useRouter(); + const { eventUuid, eventLeadUuid } = useParams<{ eventUuid: string; eventLeadUuid: string }>(); + const [state, setState] = useState("loading"); + const [reloadKey, setReloadKey] = useState(0); + const [salespersonId, setSalespersonId] = useState(""); + const [temperature, setTemperature] = useState(""); + const [status, setStatus] = useState(""); + const [interestIds, setInterestIds] = useState([]); + const [nextFollowUpDate, setNextFollowUpDate] = useState(""); + const [notes, setNotes] = useState(""); + const [fieldErrors, setFieldErrors] = useState>({}); + const [formError, setFormError] = useState(null); + const [busy, setBusy] = useState(false); + const back = `/event-leads/${eventUuid}`; + + useEffect(() => { + let cancelled = false; + Promise.all([getEventLead(eventUuid, eventLeadUuid), listEventSalespeople(eventUuid), listEventLeadInterests()]) + .then(([lead, salespeople, interests]) => { + if (cancelled) return; + setSalespersonId(lead.salesperson ? String(lead.salesperson.id) : ""); + setTemperature(lead.temperature ?? ""); + setStatus(lead.status); + setInterestIds(lead.interests.map((i) => i.id)); + setNextFollowUpDate(lead.nextFollowUpDate ?? ""); + setNotes(lead.notes ?? ""); + setState({ + lead, + // The current salesperson stays selectable even when no longer on the team list. + salespeople: lead.salesperson && !salespeople.some((s) => s.id === lead.salesperson!.id) + ? [...salespeople, { id: lead.salesperson.id, name: lead.salesperson.name, username: "" }] + : salespeople, + // The options list is active-only; an inactive interest on the lead comes from the lead itself. + interests: [...interests, ...lead.interests.filter((i) => !interests.some((o) => o.id === i.id))], + }); + }) + .catch((err) => { + if (cancelled) return; + const code = err instanceof ApiError ? (err.data as { code?: string } | undefined)?.code : undefined; + setState(code === "EVENT_LEAD_NOT_FOUND" ? "notFound" : "error"); + }); + return () => { cancelled = true; }; + }, [eventUuid, eventLeadUuid, reloadKey]); + + const backLink = ( + + ); + + if (state === "loading") return ; + if (state === "notFound") return ; + if (state === "error") { + return { setState("loading"); setReloadKey((k) => k + 1); }} />; + } + const { lead, salespeople, interests } = state; + + const fieldProps = (f: string) => ({ + id: `lead-${f}`, + "aria-invalid": fieldErrors[f] ? (true as const) : undefined, + "aria-describedby": fieldErrors[f] ? `lead-${f}-error` : undefined, + }); + const fieldError = (f: string) => + fieldErrors[f] ? : null; + const field = (f: string, label: string, control: React.ReactNode) => ( +
+ + {control} + {fieldError(f)} +
+ ); + + async function onSave(event: FormEvent) { + event.preventDefault(); + setFieldErrors({}); + setFormError(null); + setBusy(true); + try { + await updateEventLead(eventUuid, eventLeadUuid, { + salespersonId: salespersonId ? Number(salespersonId) : null, + temperature: (temperature || null) as LeadTemperature | null, + status: status as LeadStatus, + interestIds, + nextFollowUpDate: nextFollowUpDate || null, + notes: notes.trim() || null, + }); + router.push(back); + } catch (err) { + const data = err instanceof ApiError ? (err.data as { code?: string; details?: { field?: unknown } } | undefined) : undefined; + const f = data?.details?.field; + const key = data?.code ? CODE_MESSAGE[data.code] : undefined; + if (key && typeof f === "string" && FIELDS.includes(f)) setFieldErrors({ [f]: t(key) }); + else setFormError(t("LeadSaveFailed")); + setBusy(false); + } + } + + const toggleInterest = (id: number) => + setInterestIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id])); + + return ( +
+ + {formError && } +
+
+ {t(lead.leadType === "NEW" ? "LeadNew" : "LeadExisting")} + {lead.mobile &&

{lead.mobile}

} + {lead.email &&

{lead.email}

} + {lead.companyName &&

{lead.companyName}

} + {lead.jobTitle &&

{lead.jobTitle}

} +

{t("LeadCaptured")} {formatDmy(lead.capturedAt.slice(0, 10))}

+
+ + {field("salespersonId", t("LeadSalesperson"), + )} + {field("temperature", t("LeadTemperature"), + )} + {field("status", t("LeadStatus"), + )} + +
+ {t("LeadInterests")} + {interests.map((i) => ( + + ))} + {fieldError("interestIds")} +
+ + {field("nextFollowUpDate", t("LeadNextFollowUp"), + )} + {field("notes", t("LeadNotes"), +