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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
94e1e7fdde
commit
7fe8dcc8a5
3 files changed
+665
No files matched your search
@@ -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<typeof import("@/app/lib/services/adminEventLeads")>()),
|
||||
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<string, unknown> } = {}) =>
|
||||
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(<NewEventLeadPage />);
|
||||
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(<NewEventLeadPage />);
|
||||
expect(screen.getByTestId("not-authorized")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("step 1 has phone-friendly mobile and email inputs of at least 44px", () => {
|
||||
render(<NewEventLeadPage />);
|
||||
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(<NewEventLeadPage />);
|
||||
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(<NewEventLeadPage />);
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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<string, string> = {
|
||||
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<string, string> = { 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<string, string> = { EVENT_DISABLED: "LeadEventDisabled", ALREADY_CAPTURED: "LeadAlreadyCaptured" };
|
||||
|
||||
type Errors = { fields: Record<string, string>; form: string | null; code?: string; details: Record<string, unknown> };
|
||||
|
||||
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<string, unknown> } | undefined) : undefined;
|
||||
const code = data?.code;
|
||||
const details = data?.details ?? {};
|
||||
const fields: Record<string, string> = {};
|
||||
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<Step>("match");
|
||||
const [candidates, setCandidates] = useState<LeadCandidate[] | null>(null);
|
||||
const [match, setMatch] = useState<LeadMatchResult | null>(null);
|
||||
const [existing, setExisting] = useState<LeadCandidate | null>(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<string>("OPEN");
|
||||
const [interestIds, setInterestIds] = useState<number[]>([]);
|
||||
const [nextFollowUpDate, setNextFollowUpDate] = useState("");
|
||||
const [notes, setNotes] = useState("");
|
||||
const [salespeople, setSalespeople] = useState<SalespersonOption[]>([]);
|
||||
const [interests, setInterests] = useState<InterestOption[]>([]);
|
||||
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
|
||||
const [formError, setFormError] = useState<string | null>(null);
|
||||
const [optionsError, setOptionsError] = useState<string | null>(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] ? <p id={`lead-${f}-error`} role="alert" className="text-sm text-destructive">{fieldErrors[f]}</p> : 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) => (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor={`lead-${f}`}>{label}</Label>
|
||||
{control}
|
||||
{fieldError(f)}
|
||||
</div>
|
||||
);
|
||||
const textInput = (f: string, label: string, value: string, set: (v: string) => void, extra: React.ComponentProps<typeof Input> = {}) =>
|
||||
field(f, label, <Input {...fieldProps(f)} className={TALL} value={value} onChange={(e) => set(e.target.value)} disabled={busy} {...extra} />);
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-xl">
|
||||
<PageHeader title={t("LeadAddLead")} />
|
||||
{optionsError && <ErrorState message={optionsError} />}
|
||||
{formError && <ErrorState message={formError} />}
|
||||
|
||||
{step === "match" && !candidates && (
|
||||
<form onSubmit={onMatch} className="space-y-4" noValidate>
|
||||
{textInput("mobile", t("LeadMobile"), mobile, setMobile, { type: "tel", inputMode: "tel", autoComplete: "tel" })}
|
||||
{textInput("email", t("Email"), email, setEmail, { type: "email", autoComplete: "email" })}
|
||||
<Button type="submit" className={`${TALL} w-full sm:w-auto`} disabled={busy}>{t("LeadNext")}</Button>
|
||||
</form>
|
||||
)}
|
||||
|
||||
{step === "match" && candidates && match && (
|
||||
<div className="space-y-4">
|
||||
<ul className="space-y-3">
|
||||
{candidates.map((c) => (
|
||||
<li key={c.leadUuid} className="space-y-2 rounded-lg border p-4">
|
||||
<p className="font-medium">{c.name}</p>
|
||||
{c.mobile && <p className="text-sm">{c.mobile}</p>}
|
||||
{c.email && <p className="text-sm">{c.email}</p>}
|
||||
{c.companyName && <p className="text-sm text-muted-foreground">{c.companyName}</p>}
|
||||
{c.eventLeadUuid ? (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<span className="text-sm font-medium">{t("LeadAlreadyCaptured")}</span>
|
||||
<Button asChild variant="outline" className={TALL}>
|
||||
<Link href={`/event-leads/${eventUuid}/${c.eventLeadUuid}`}>{t("LeadOpen")}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<Button type="button" className={`${TALL} w-full sm:w-auto`} onClick={() => startDetails(match, c)}>{t("LeadThisPerson")}</Button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="flex flex-col gap-3 sm:flex-row">
|
||||
<Button type="button" variant="outline" className={TALL} onClick={() => startDetails(match, null)}>{t("LeadDifferentPerson")}</Button>
|
||||
<Button type="button" variant="ghost" className={TALL} onClick={() => setCandidates(null)}>{t("Back")}</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === "details" && (
|
||||
<form onSubmit={onSave} className="space-y-4" noValidate>
|
||||
{existing ? (
|
||||
<div className="space-y-1 rounded-lg border p-4">
|
||||
<p className="font-medium">{existing.name}</p>
|
||||
{existing.mobile && <p className="text-sm">{existing.mobile}</p>}
|
||||
{existing.email && <p className="text-sm">{existing.email}</p>}
|
||||
{existing.companyName && <p className="text-sm text-muted-foreground">{existing.companyName}</p>}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{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"),
|
||||
<select {...fieldProps("salespersonId")} className={SELECT_CLASS} value={salespersonId} onChange={(e) => setSalespersonId(e.target.value)} disabled={busy}>
|
||||
<option value="">{t("LeadNone")}</option>
|
||||
{salespeople.map((s) => <option key={s.id} value={String(s.id)}>{s.name}</option>)}
|
||||
</select>)}
|
||||
{field("temperature", t("LeadTemperature"),
|
||||
<select {...fieldProps("temperature")} className={SELECT_CLASS} value={temperature} onChange={(e) => setTemperature(e.target.value)} disabled={busy}>
|
||||
<option value="">{t("LeadNone")}</option>
|
||||
{TEMPERATURES.map(([v, k]) => <option key={v} value={v}>{t(k)}</option>)}
|
||||
</select>)}
|
||||
{field("status", t("LeadStatus"),
|
||||
<select {...fieldProps("status")} className={SELECT_CLASS} value={status} onChange={(e) => setStatus(e.target.value)} disabled={busy}>
|
||||
{STATUSES.map(([v, k]) => <option key={v} value={v}>{t(k)}</option>)}
|
||||
</select>)}
|
||||
|
||||
<fieldset {...fieldProps("interestIds")} className="space-y-1">
|
||||
<legend className="mb-1.5 text-sm font-medium">{t("LeadInterests")}</legend>
|
||||
{interests.map((i) => (
|
||||
<label key={i.id} className="flex min-h-11 items-center gap-3 text-sm">
|
||||
<input type="checkbox" className="size-5" checked={interestIds.includes(i.id)} onChange={() => toggleInterest(i.id)} disabled={busy} />
|
||||
{i.name}
|
||||
</label>
|
||||
))}
|
||||
{fieldError("interestIds")}
|
||||
</fieldset>
|
||||
|
||||
{field("nextFollowUpDate", t("LeadNextFollowUp"),
|
||||
<DatePicker {...fieldProps("nextFollowUpDate")} className="h-11" value={nextFollowUpDate} onChange={setNextFollowUpDate} disabled={busy} />)}
|
||||
{field("notes", t("LeadNotes"),
|
||||
<textarea {...fieldProps("notes")} className={`${SELECT_CLASS} py-2`} rows={3} value={notes} onChange={(e) => setNotes(e.target.value)} disabled={busy} />)}
|
||||
|
||||
<div className="flex flex-col-reverse gap-3 sm:flex-row">
|
||||
<Button type="button" variant="outline" className={TALL} onClick={() => { setFieldErrors({}); setFormError(null); setStep("match"); }} disabled={busy}>{t("Back")}</Button>
|
||||
<Button type="submit" className={TALL} disabled={busy}>{t("Save")}</Button>
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function NewEventLeadPage() {
|
||||
return (
|
||||
<RequireModule pathname="/event-leads">
|
||||
<NewEventLead />
|
||||
</RequireModule>
|
||||
);
|
||||
}
|
||||
@@ -255,4 +255,26 @@ export const DEFAULT_MESSAGES: Record<string, string> = {
|
||||
LeadLost: "Lost",
|
||||
LeadNew: "New",
|
||||
LeadExisting: "Existing",
|
||||
LeadCompany: "Company",
|
||||
LeadJobTitle: "Job title",
|
||||
LeadStatus: "Status",
|
||||
LeadNotes: "Notes",
|
||||
LeadNext: "Next",
|
||||
LeadNone: "None",
|
||||
LeadAlreadyCaptured: "Already captured",
|
||||
LeadThisPerson: "This person",
|
||||
LeadDifferentPerson: "Different person",
|
||||
LeadOptionsLoadFailed: "Failed to load salespeople or interests",
|
||||
LeadEventDisabled: "This event is closed for new leads.",
|
||||
LeadSaveFailed: "Could not save the lead. Please try again.",
|
||||
LeadMatchFailed: "Could not look up this contact. Please try again.",
|
||||
LeadErrRequiredContact: "Mobile or email is required.",
|
||||
LeadErrRequired: "This field is required.",
|
||||
LeadErrTooLong: "Too long.",
|
||||
LeadErrInvalidMobile: "Enter a valid mobile number.",
|
||||
LeadErrInvalidEmail: "Enter a valid email address.",
|
||||
LeadErrInvalidDate: "Enter a valid date.",
|
||||
LeadErrNotOnTeam: "This person is not on the event team.",
|
||||
LeadErrInactiveInterest: "An interest is no longer active.",
|
||||
LeadErrInvalidValue: "Invalid value.",
|
||||
};
|
||||
Reference in new issue
Block a user