From 7fe8dcc8a56070e8ea2d5c09a44a3b7c3a39a858 Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 13:31:29 +0800 Subject: [PATCH] feat(admin-portal): two-step event lead key-in form Step 1 matches on mobile or email and offers each candidate (or opens an already-captured one). Step 2 captures a new or picked lead with salesperson, temperature, status, interests and follow-up date. A picked lead only gets contact values that are its own, so no two people merge. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../event-leads/[eventUuid]/new/page.test.tsx | 337 ++++++++++++++++++ .../app/event-leads/[eventUuid]/new/page.tsx | 306 ++++++++++++++++ .../app/lib/i18n/defaultMessages.ts | 22 ++ 3 files changed, 665 insertions(+) create mode 100644 solvway-admin-portal/app/event-leads/[eventUuid]/new/page.test.tsx create mode 100644 solvway-admin-portal/app/event-leads/[eventUuid]/new/page.tsx diff --git a/solvway-admin-portal/app/event-leads/[eventUuid]/new/page.test.tsx b/solvway-admin-portal/app/event-leads/[eventUuid]/new/page.test.tsx new file mode 100644 index 0000000..d9806b8 --- /dev/null +++ b/solvway-admin-portal/app/event-leads/[eventUuid]/new/page.test.tsx @@ -0,0 +1,337 @@ +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(() => ({ + matchLead: vi.fn(), + captureEventLead: vi.fn(), + listEventSalespeople: vi.fn(), + listEventLeadInterests: vi.fn(), + useAdminAuth: vi.fn(), +})); +vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({ + ...(await importActual()), + matchLead: mocks.matchLead, + captureEventLead: mocks.captureEventLead, + 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" }), +})); + +import { ApiError } from "@/app/lib/clientApi"; +import { memoryRouter } from "@/test/memoryRouter"; +import NewEventLeadPage from "./page"; + +const SERVER_MSG = "Server says: internal detail xyz"; +const apiError = (code: string, extra: { errors?: string[]; details?: Record } = {}) => + new ApiError(SERVER_MSG, 400, { code, errors: [], details: {}, ...extra }); + +const CAPTURED = { leadUuid: "l-1", name: "Ann Captured", mobile: "+6591111111", email: "ann@x.com", companyName: "Acme", jobTitle: "CEO", eventLeadUuid: "el-9" }; +const FRESH = { leadUuid: "l-2", name: "Bob Fresh", mobile: "+6592222222", email: "bob@x.com", companyName: "Globex", jobTitle: "CTO", eventLeadUuid: null }; + +async function toStep1Match(candidates: unknown[], match = { mobile: "+6591234567", email: "a@b.com" }) { + mocks.matchLead.mockResolvedValue({ ...match, candidates }); + const user = userEvent.setup(); + render(); + await user.type(screen.getByLabelText("Mobile"), "91234567"); + await user.type(screen.getByLabelText("Email"), "a@b.com"); + await user.click(screen.getByRole("button", { name: "Next" })); + return user; +} + +beforeEach(() => { + memoryRouter.reset("/event-leads/evt-1/new"); + mocks.matchLead.mockReset(); + mocks.captureEventLead.mockReset().mockResolvedValue({ eventLeadUuid: "el-new" }); + mocks.listEventSalespeople.mockReset().mockResolvedValue([{ id: 7, name: "Jane Sales", username: "jane" }]); + mocks.listEventLeadInterests.mockReset().mockResolvedValue([ + { id: 1, name: "Product A", active: true }, + { id: 2, name: "Product B", active: false }, + ]); + mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, hasModule: () => true }); +}); + +describe("NewEventLeadPage", { 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("step 1 has phone-friendly mobile and email inputs of at least 44px", () => { + render(); + const mobile = screen.getByLabelText("Mobile"); + expect(mobile).toHaveAttribute("type", "tel"); + expect(mobile).toHaveAttribute("inputmode", "tel"); + expect(mobile).toHaveAttribute("autocomplete", "tel"); + expect(mobile).toHaveClass("min-h-11"); + const email = screen.getByLabelText("Email"); + expect(email).toHaveAttribute("type", "email"); + expect(email).toHaveAttribute("autocomplete", "email"); + expect(email).toHaveClass("min-h-11"); + expect(screen.getByRole("button", { name: "Next" })).toHaveClass("min-h-11"); + }); + + it("Next calls matchLead with the typed values, null for empty ones", async () => { + mocks.matchLead.mockResolvedValue({ mobile: null, email: null, candidates: [] }); + const user = userEvent.setup(); + render(); + await user.type(screen.getByLabelText("Mobile"), "91234567"); + await user.click(screen.getByRole("button", { name: "Next" })); + await waitFor(() => expect(mocks.matchLead).toHaveBeenCalledWith("evt-1", { mobile: "91234567", email: null })); + }); + + it("shows each candidate as a card; captured ones link to the lead, others offer This person", async () => { + await toStep1Match([CAPTURED, FRESH]); + const ann = (await screen.findByText("Ann Captured")).closest("li")!; + expect(within(ann).getByText("+6591111111")).toBeVisible(); + expect(within(ann).getByText("ann@x.com")).toBeVisible(); + expect(within(ann).getByText("Acme")).toBeVisible(); + expect(within(ann).getByText("Already captured")).toBeVisible(); + expect(within(ann).getByRole("link", { name: "Open" })).toHaveAttribute("href", "/event-leads/evt-1/el-9"); + expect(within(ann).queryByRole("button", { name: "This person" })).toBeNull(); + const bob = screen.getByText("Bob Fresh").closest("li")!; + expect(within(bob).getByText("Globex")).toBeVisible(); + expect(within(bob).getByRole("button", { name: "This person" })).toHaveClass("min-h-11"); + expect(within(bob).queryByText("Already captured")).toBeNull(); + expect(screen.getByRole("button", { name: "Different person" })).toBeVisible(); + }); + + it("goes straight to step 2 as new, prefilled with the normalised match values, when nothing matches", async () => { + await toStep1Match([]); + expect(await screen.findByLabelText("Name")).toHaveValue(""); + expect(screen.getByLabelText("Mobile")).toHaveValue("+6591234567"); + expect(screen.getByLabelText("Email")).toHaveValue("a@b.com"); + expect(screen.getByLabelText("Company")).toBeVisible(); + expect(screen.getByLabelText("Job title")).toBeVisible(); + }); + + it("Different person goes to step 2 as new", async () => { + const user = await toStep1Match([FRESH]); + await user.click(await screen.findByRole("button", { name: "Different person" })); + expect(await screen.findByLabelText("Name")).toHaveValue(""); + expect(screen.getByLabelText("Mobile")).toHaveValue("+6591234567"); + }); + + it.each([ + ["REQUIRED_FIELD", ["mobile", "email"], "Mobile or email is required.", ["Mobile", "Email"]], + ["INVALID_MOBILE", [], "Enter a valid mobile number.", ["Mobile"]], + ["INVALID_EMAIL", [], "Enter a valid email address.", ["Email"]], + ])("step 1 %s shows the mapped message under the field", async (code, errors, text, labels) => { + mocks.matchLead.mockRejectedValue(apiError(code, { errors })); + const user = userEvent.setup(); + render(); + await user.click(screen.getByRole("button", { name: "Next" })); + const msgs = await screen.findAllByText(text); + expect(msgs).toHaveLength(labels.length); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + for (const label of labels) { + const input = screen.getByLabelText(label); + expect(input).toHaveAttribute("aria-invalid", "true"); + const described = document.getElementById(input.getAttribute("aria-describedby")!); + expect(described).toHaveTextContent(text); + } + }); + + it("This person shows the lead read-only and saves with leadUuid, filling only its blank contact field", async () => { + // Matched on mobile; the lead has no email yet, so the entered email fills it. + const picked = { ...FRESH, mobile: "+60198887777", email: null }; + const user = await toStep1Match([picked], { mobile: "+60198887777", email: "a@b.com" }); + await user.click(await screen.findByRole("button", { name: "This person" })); + expect(await screen.findByText("Bob Fresh")).toBeVisible(); + expect(screen.queryByLabelText("Name")).toBeNull(); + expect(screen.queryByLabelText("Company")).toBeNull(); + await user.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(mocks.captureEventLead).toHaveBeenCalledTimes(1)); + const [uuid, payload] = mocks.captureEventLead.mock.calls[0]; + expect(uuid).toBe("evt-1"); + expect(payload).toMatchObject({ leadUuid: "l-2", name: "Bob Fresh", mobile: "+60198887777", email: "a@b.com", status: "OPEN" }); + await waitFor(() => expect(memoryRouter.push).toHaveBeenCalledWith("/event-leads/evt-1")); + }); + + it("picking one of two people never copies the other person's contact onto it", async () => { + // Mobile matched A, email matched B. Picking A must not send B's email (no merge). + const a = { ...FRESH, leadUuid: "l-a", name: "Amy Mobile", mobile: "+60198887777", email: null }; + const b = { ...FRESH, leadUuid: "l-b", name: "Ben Email", mobile: null, email: "a@b.com" }; + const user = await toStep1Match([a, b], { mobile: "+60198887777", email: "a@b.com" }); + await user.click((await screen.findAllByRole("button", { name: "This person" }))[0]); + await user.click(await screen.findByRole("button", { name: "Save" })); + await waitFor(() => expect(mocks.captureEventLead).toHaveBeenCalledTimes(1)); + expect(mocks.captureEventLead.mock.calls[0][1]).toMatchObject({ leadUuid: "l-a", mobile: "+60198887777", email: null }); + }); + + it("step 2 offers salespeople, interests (active only), temperature and status, and saves a new lead", async () => { + const user = await toStep1Match([]); + await user.type(await screen.findByLabelText("Name"), "Carl New"); + await user.type(screen.getByLabelText("Company"), "Initech"); + await user.type(screen.getByLabelText("Job title"), "COO"); + await user.type(screen.getByLabelText("Notes"), "Met at booth"); + expect(screen.getByLabelText("Status")).toHaveValue("OPEN"); + expect(screen.getByLabelText("Status")).toHaveClass("min-h-11"); + expect(within(screen.getByLabelText("Temperature")).getByRole("option", { name: "Hot" })).toBeInTheDocument(); + expect(await screen.findByRole("option", { name: "Jane Sales" })).toBeInTheDocument(); + await user.selectOptions(screen.getByLabelText("Salesperson"), "7"); + await user.selectOptions(screen.getByLabelText("Temperature"), "HOT"); + await user.selectOptions(screen.getByLabelText("Status"), "QUALIFIED"); + expect(screen.queryByLabelText("Product B")).toBeNull(); + await user.click(await screen.findByLabelText("Product A")); + pickDate("Next follow-up", "2026-12-05"); + await user.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(mocks.captureEventLead).toHaveBeenCalledTimes(1)); + expect(mocks.captureEventLead).toHaveBeenCalledWith("evt-1", { + name: "Carl New", + mobile: "+6591234567", + email: "a@b.com", + companyName: "Initech", + jobTitle: "COO", + salespersonId: 7, + temperature: "HOT", + status: "QUALIFIED", + interestIds: [1], + nextFollowUpDate: "2026-12-05", + notes: "Met at booth", + }); + await waitFor(() => expect(memoryRouter.push).toHaveBeenCalledWith("/event-leads/evt-1")); + }); + + it("Back returns to step 1", async () => { + const user = await toStep1Match([]); + await user.click(await screen.findByRole("button", { name: "Back" })); + expect(await screen.findByRole("button", { name: "Next" })).toBeVisible(); + }); + + it("step 2 REQUIRED_FIELD marks each field in errors[]", async () => { + mocks.captureEventLead.mockRejectedValue(apiError("REQUIRED_FIELD", { errors: ["name", "salespersonId"] })); + const user = await toStep1Match([]); + await user.click(await screen.findByRole("button", { name: "Save" })); + const msgs = await screen.findAllByText("This field is required."); + expect(msgs).toHaveLength(2); + for (const label of ["Name", "Salesperson"]) { + const el = screen.getByLabelText(label); + expect(el).toHaveAttribute("aria-invalid", "true"); + expect(document.getElementById(el.getAttribute("aria-describedby")!)).toHaveTextContent("This field is required."); + } + expect(screen.getByLabelText("Company")).not.toHaveAttribute("aria-invalid", "true"); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + }); + + it.each([ + ["TOO_LONG", "name", "Name", "Too long."], + ["TOO_LONG", "companyName", "Company", "Too long."], + ["TOO_LONG", "jobTitle", "Job title", "Too long."], + ["INVALID_MOBILE", "mobile", "Mobile", "Enter a valid mobile number."], + ["INVALID_EMAIL", "email", "Email", "Enter a valid email address."], + ["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."], + ])("step 2 %s on %s shows the mapped message under the field", async (code, field, label, text) => { + mocks.captureEventLead.mockRejectedValue(apiError(code, { details: { field } })); + const user = await toStep1Match([]); + await user.click(await screen.findByRole("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("step 2 INACTIVE_INTEREST shows the mapped message under the interests group", async () => { + mocks.captureEventLead.mockRejectedValue(apiError("INACTIVE_INTEREST", { details: { field: "interestIds" } })); + const user = await toStep1Match([]); + await screen.findByLabelText("Product A"); + 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("step 2 ALREADY_CAPTURED navigates to the existing event lead", async () => { + mocks.captureEventLead.mockRejectedValue(apiError("ALREADY_CAPTURED", { details: { eventLeadUuid: "el-77" } })); + const user = await toStep1Match([]); + await user.click(await screen.findByRole("button", { name: "Save" })); + await waitFor(() => expect(memoryRouter.push).toHaveBeenCalledWith("/event-leads/evt-1/el-77")); + }); + + it("step 2 other errors show a form-level message", async () => { + mocks.captureEventLead.mockRejectedValue(apiError("SOMETHING_ELSE")); + const user = await toStep1Match([]); + await user.click(await screen.findByRole("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("picked lead: a field error for a field not shown on this step still gives a form-level message", async () => { + mocks.captureEventLead.mockRejectedValue(apiError("REQUIRED_FIELD", { errors: ["name"] })); + const user = await toStep1Match([FRESH]); + await user.click(await screen.findByRole("button", { name: "This person" })); + await user.click(await screen.findByRole("button", { name: "Save" })); + expect(await screen.findByRole("alert")).toHaveTextContent("Could not save the lead. Please try again."); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + }); + + it("unknown field in a field error gives a form-level message", async () => { + mocks.captureEventLead.mockRejectedValue(apiError("TOO_LONG", { details: { field: "bogus" } })); + const user = await toStep1Match([]); + await user.click(await screen.findByRole("button", { name: "Save" })); + expect(await screen.findByRole("alert")).toHaveTextContent("Could not save the lead. Please try again."); + }); + + it("Back on the candidate list returns to editable mobile and email", async () => { + const user = await toStep1Match([FRESH]); + await screen.findByText("Bob Fresh"); + await user.click(screen.getByRole("button", { name: "Back" })); + expect(screen.queryByText("Bob Fresh")).toBeNull(); + expect(screen.getByLabelText("Mobile")).toHaveValue("91234567"); + expect(screen.getByRole("button", { name: "Next" })).toBeVisible(); + }); + + it("preselects the capturing user as salesperson when on the team", async () => { + mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => true, id: 7 }); + const user = await toStep1Match([]); + await screen.findByRole("option", { name: "Jane Sales" }); + await waitFor(() => expect(screen.getByLabelText("Salesperson")).toHaveValue("7")); + await user.click(screen.getByRole("button", { name: "Save" })); + await waitFor(() => expect(mocks.captureEventLead).toHaveBeenCalledWith("evt-1", expect.objectContaining({ salespersonId: 7 }))); + }); + + it("leaves the salesperson empty when the capturing user is not on the team", async () => { + mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: () => true, id: 99 }); + await toStep1Match([]); + await screen.findByRole("option", { name: "Jane Sales" }); + expect(screen.getByLabelText("Salesperson")).toHaveValue(""); + }); + + it("keeps the options-load failure visible after matching", async () => { + mocks.listEventSalespeople.mockRejectedValue(new Error("boom")); + await toStep1Match([]); + expect(await screen.findByText("Failed to load salespeople or interests")).toBeVisible(); + await screen.findByLabelText("Name"); + expect(screen.getByText("Failed to load salespeople or interests")).toBeVisible(); + }); + + it("step 2 EVENT_DISABLED shows a specific form-level message", async () => { + mocks.captureEventLead.mockRejectedValue(apiError("EVENT_DISABLED")); + const user = await toStep1Match([]); + await user.click(await screen.findByRole("button", { name: "Save" })); + expect(await screen.findByRole("alert")).toHaveTextContent("This event is closed for new leads."); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + }); + + it("step 2 ALREADY_CAPTURED without an event lead uuid shows Already captured", async () => { + mocks.captureEventLead.mockRejectedValue(apiError("ALREADY_CAPTURED")); + const user = await toStep1Match([]); + await user.click(await screen.findByRole("button", { name: "Save" })); + expect(await screen.findByRole("alert")).toHaveTextContent("Already captured"); + expect(memoryRouter.push).not.toHaveBeenCalled(); + }); +}); diff --git a/solvway-admin-portal/app/event-leads/[eventUuid]/new/page.tsx b/solvway-admin-portal/app/event-leads/[eventUuid]/new/page.tsx new file mode 100644 index 0000000..39065e0 --- /dev/null +++ b/solvway-admin-portal/app/event-leads/[eventUuid]/new/page.tsx @@ -0,0 +1,306 @@ +"use client"; + +import { useEffect, useState, type FormEvent } from "react"; +import { useParams, useRouter } from "next/navigation"; +import Link from "next/link"; +import { Button } from "@/app/components/ui/button"; +import { DatePicker } from "@/app/components/ui/date-picker"; +import { Input } from "@/app/components/ui/input"; +import { Label } from "@/app/components/ui/label"; +import { PageHeader } from "@/app/components/ui/page-header"; +import { ErrorState } from "@/app/components/ui/states"; +import { RequireModule } from "@/app/lib/RequireModule"; +import { useAdminAuth } from "@/app/lib/AdminAuthContext"; +import { ApiError } from "@/app/lib/clientApi"; +import { captureEventLead, listEventLeadInterests, listEventSalespeople, matchLead } from "@/app/lib/services/adminEventLeads"; +import type { InterestOption, LeadCandidate, LeadMatchResult, 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 = { + REQUIRED_FIELD: "LeadErrRequired", + TOO_LONG: "LeadErrTooLong", + INVALID_MOBILE: "LeadErrInvalidMobile", + INVALID_EMAIL: "LeadErrInvalidEmail", + INVALID_DATE: "LeadErrInvalidDate", + NOT_ON_TEAM: "LeadErrNotOnTeam", + INACTIVE_INTEREST: "LeadErrInactiveInterest", + INVALID_VALUE: "LeadErrInvalidValue", +}; +// Codes that name their field themselves when the server omits details.field. +const IMPLIED_FIELD: Record = { INVALID_MOBILE: "mobile", INVALID_EMAIL: "email" }; +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 Step = "match" | "details"; +const STEP1_FIELDS = ["mobile", "email"]; +const PICKED_FIELDS = ["salespersonId", "temperature", "status", "interestIds", "nextFollowUpDate", "notes"]; +const NEW_FIELDS = [...PICKED_FIELDS, "name", "mobile", "email", "companyName", "jobTitle"]; +// Codes that are never tied to a field. +const FORM_CODE_MESSAGE: Record = { EVENT_DISABLED: "LeadEventDisabled", ALREADY_CAPTURED: "LeadAlreadyCaptured" }; + +type Errors = { fields: Record; form: string | null; code?: string; details: Record }; + +function readError(err: unknown, t: (k: string) => string, fallbackKey: string, rendered: string[], requiredKey?: string): Errors { + const data = err instanceof ApiError ? (err.data as { code?: string; errors?: string[]; details?: Record } | undefined) : undefined; + const code = data?.code; + const details = data?.details ?? {}; + const fields: Record = {}; + let hidden = false; // a named field this step does not render must not make the failure silent + const mark = (f: string, key: string) => { + if (rendered.includes(f)) fields[f] = t(key); + else hidden = true; + }; + if (code === "REQUIRED_FIELD") { + for (const f of data?.errors ?? []) mark(f, requiredKey ?? CODE_MESSAGE.REQUIRED_FIELD); + } else if (code && CODE_MESSAGE[code]) { + const field = typeof details.field === "string" ? details.field : IMPLIED_FIELD[code]; + if (field) mark(field, CODE_MESSAGE[code]); + } + const key = (code && FORM_CODE_MESSAGE[code]) || fallbackKey; + const form = hidden || !Object.keys(fields).length ? t(key) : null; + return { fields, form, code, details }; +} + +function NewEventLead() { + const t = useT(); + const router = useRouter(); + const { id: myId } = useAdminAuth(); + const { eventUuid } = useParams<{ eventUuid: string }>(); + const [step, setStep] = useState("match"); + const [candidates, setCandidates] = useState(null); + const [match, setMatch] = useState(null); + const [existing, setExisting] = useState(null); + const [mobile, setMobile] = useState(""); + const [email, setEmail] = useState(""); + const [name, setName] = useState(""); + const [companyName, setCompanyName] = useState(""); + const [jobTitle, setJobTitle] = useState(""); + const [salespersonId, setSalespersonId] = useState(""); + const [temperature, setTemperature] = useState(""); + const [status, setStatus] = useState("OPEN"); + const [interestIds, setInterestIds] = useState([]); + const [nextFollowUpDate, setNextFollowUpDate] = useState(""); + const [notes, setNotes] = useState(""); + const [salespeople, setSalespeople] = useState([]); + const [interests, setInterests] = useState([]); + const [fieldErrors, setFieldErrors] = useState>({}); + const [formError, setFormError] = useState(null); + const [optionsError, setOptionsError] = useState(null); + const [busy, setBusy] = useState(false); + + useEffect(() => { + let cancelled = false; + Promise.all([listEventSalespeople(eventUuid), listEventLeadInterests()]) + .then(([s, i]) => { + if (cancelled) return; + setSalespeople(s); + setInterests(i.filter((o) => o.active)); + if (myId != null && s.some((o) => o.id === myId)) setSalespersonId(String(myId)); + }) + .catch(() => { if (!cancelled) setOptionsError(t("LeadOptionsLoadFailed")); }); + return () => { cancelled = true; }; + }, [eventUuid, t, myId]); + + 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; + + function fail(e: Errors) { + setFieldErrors(e.fields); + setFormError(e.form); + } + + async function onMatch(event: FormEvent) { + event.preventDefault(); + setFieldErrors({}); + setFormError(null); + setBusy(true); + try { + const result = await matchLead(eventUuid, { mobile: mobile.trim() || null, email: email.trim() || null }); + setMatch(result); + if (result.candidates.length === 0) startDetails(result, null); + else setCandidates(result.candidates); + } catch (err) { + fail(readError(err, t, "LeadMatchFailed", STEP1_FIELDS, "LeadErrRequiredContact")); + } finally { + setBusy(false); + } + } + + function startDetails(result: LeadMatchResult, lead: LeadCandidate | null) { + setExisting(lead); + setMobile(result.mobile ?? ""); + setEmail(result.email ?? ""); + setFieldErrors({}); + setFormError(null); + setStep("details"); + } + + // A picked lead gets an entered contact value only if it is already its own, or fills its blank field and + // belongs to no other candidate: copying another person's mobile or email onto it would merge two people. + function ownValue(field: "mobile" | "email"): string | null { + const value = match?.[field] ?? null; + if (!value || !existing) return null; + if (existing[field] === value) return value; + if (existing[field]) return null; + return candidates?.some((c) => c.leadUuid !== existing.leadUuid && c[field] === value) ? null : value; + } + + async function onSave(event: FormEvent) { + event.preventDefault(); + setFieldErrors({}); + setFormError(null); + setBusy(true); + try { + await captureEventLead(eventUuid, { + ...(existing + ? { leadUuid: existing.leadUuid, name: existing.name, mobile: ownValue("mobile"), email: ownValue("email") } + : { name: name.trim(), mobile: mobile.trim() || null, email: email.trim() || null, companyName: companyName.trim() || null, jobTitle: jobTitle.trim() || null }), + 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(`/event-leads/${eventUuid}`); + } catch (err) { + const e = readError(err, t, "LeadSaveFailed", existing ? PICKED_FIELDS : NEW_FIELDS); + if (e.code === "ALREADY_CAPTURED" && typeof e.details.eventLeadUuid === "string") { + router.push(`/event-leads/${eventUuid}/${e.details.eventLeadUuid}`); + return; + } + fail(e); + setBusy(false); + } + } + + const toggleInterest = (id: number) => + setInterestIds((prev) => (prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id])); + + const field = (f: string, label: string, control: React.ReactNode) => ( +
+ + {control} + {fieldError(f)} +
+ ); + const textInput = (f: string, label: string, value: string, set: (v: string) => void, extra: React.ComponentProps = {}) => + field(f, label, set(e.target.value)} disabled={busy} {...extra} />); + + return ( +
+ + {optionsError && } + {formError && } + + {step === "match" && !candidates && ( +
+ {textInput("mobile", t("LeadMobile"), mobile, setMobile, { type: "tel", inputMode: "tel", autoComplete: "tel" })} + {textInput("email", t("Email"), email, setEmail, { type: "email", autoComplete: "email" })} + +
+ )} + + {step === "match" && candidates && match && ( +
+
    + {candidates.map((c) => ( +
  • +

    {c.name}

    + {c.mobile &&

    {c.mobile}

    } + {c.email &&

    {c.email}

    } + {c.companyName &&

    {c.companyName}

    } + {c.eventLeadUuid ? ( +
    + {t("LeadAlreadyCaptured")} + +
    + ) : ( + + )} +
  • + ))} +
+
+ + +
+
+ )} + + {step === "details" && ( +
+ {existing ? ( +
+

{existing.name}

+ {existing.mobile &&

{existing.mobile}

} + {existing.email &&

{existing.email}

} + {existing.companyName &&

{existing.companyName}

} +
+ ) : ( + <> + {textInput("name", t("LeadName"), name, setName)} + {textInput("mobile", t("LeadMobile"), mobile, setMobile, { type: "tel", inputMode: "tel", autoComplete: "tel" })} + {textInput("email", t("Email"), email, setEmail, { type: "email", autoComplete: "email" })} + {textInput("companyName", t("LeadCompany"), companyName, setCompanyName)} + {textInput("jobTitle", t("LeadJobTitle"), jobTitle, setJobTitle)} + + )} + + {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"), +