From 82b6943474b5f766b63f6b4216f8ac73299f5fca Mon Sep 17 00:00:00 2001 From: ngqile Date: Fri, 27 Nov 2026 16:53:44 +0800 Subject: [PATCH] feat(admin-portal): leads listing and lead detail Lead Listing with search and server paging, lead detail with event history, shared-contact warning and an edit form under BO_LEADS_EDIT, and a View lead link from the event lead edit page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM --- .../changes/add-lead-listing-export/tasks.md | 2 +- .../app/api/leads/[[...path]]/route.test.ts | 58 +++++ .../app/api/leads/[[...path]]/route.ts | 23 ++ .../[eventUuid]/[eventLeadUuid]/page.tsx | 7 + .../[eventLeadUuid]/view-lead.test.tsx | 47 ++++ .../app/leads/[leadUuid]/page.test.tsx | 218 ++++++++++++++++++ .../app/leads/[leadUuid]/page.tsx | 216 +++++++++++++++++ solvway-admin-portal/app/leads/page.test.tsx | 71 ++++++ solvway-admin-portal/app/leads/page.tsx | 100 ++++++++ .../app/lib/i18n/defaultMessages.ts | 11 + .../app/lib/routeModules.test.ts | 3 +- solvway-admin-portal/app/lib/routeModules.ts | 1 + .../app/lib/services/adminLeads.test.ts | 37 +++ .../app/lib/services/adminLeads.ts | 17 ++ solvway-admin-portal/app/lib/types.ts | 52 +++++ 15 files changed, 861 insertions(+), 2 deletions(-) create mode 100644 solvway-admin-portal/app/api/leads/[[...path]]/route.test.ts create mode 100644 solvway-admin-portal/app/api/leads/[[...path]]/route.ts create mode 100644 solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/view-lead.test.tsx create mode 100644 solvway-admin-portal/app/leads/[leadUuid]/page.test.tsx create mode 100644 solvway-admin-portal/app/leads/[leadUuid]/page.tsx create mode 100644 solvway-admin-portal/app/leads/page.test.tsx create mode 100644 solvway-admin-portal/app/leads/page.tsx create mode 100644 solvway-admin-portal/app/lib/services/adminLeads.test.ts create mode 100644 solvway-admin-portal/app/lib/services/adminLeads.ts diff --git a/openspec/changes/add-lead-listing-export/tasks.md b/openspec/changes/add-lead-listing-export/tasks.md index 61bcf4c..d4f007f 100644 --- a/openspec/changes/add-lead-listing-export/tasks.md +++ b/openspec/changes/add-lead-listing-export/tasks.md @@ -71,7 +71,7 @@ Design: `design.md` (decision numbers below refer to it). All tasks run serially ## 4. Portal -- [ ] 4.1 Add the Lead Listing and lead detail (design decision 6): +- [x] 4.1 Add the Lead Listing and lead detail (design decision 6): - the leads data layer: route `app/api/leads/[...path]`, service, types, and `/leads` mapped to `BO_LEADS`; - the `/leads` listing with search; - the `/leads/[leadUuid]` detail page, with an edit form when the user has `BO_LEADS_EDIT`, the shared-contact warning, the event history and not-found; diff --git a/solvway-admin-portal/app/api/leads/[[...path]]/route.test.ts b/solvway-admin-portal/app/api/leads/[[...path]]/route.test.ts new file mode 100644 index 0000000..763d618 --- /dev/null +++ b/solvway-admin-portal/app/api/leads/[[...path]]/route.test.ts @@ -0,0 +1,58 @@ +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ callMobileApi: vi.fn(), getToken: vi.fn() })); +vi.mock("@/app/lib/server/mobileApi", () => ({ callMobileApi: mocks.callMobileApi })); +vi.mock("@/app/lib/server/session", () => ({ getToken: mocks.getToken })); + +import { GET, PUT } from "./route"; + +type Req = Parameters[0]; +const ctx = (...path: string[]) => ({ params: Promise.resolve({ path: path.length ? path : undefined }) }); +const req = (url: string, init?: RequestInit) => new Request(`http://localhost${url}`, init) as unknown as Req; + +beforeEach(() => { + mocks.callMobileApi.mockReset(); + mocks.getToken.mockReset(); + mocks.getToken.mockResolvedValue("jwt-abc"); + mocks.callMobileApi.mockResolvedValue({ ok: true, data: { ok: 1 } }); +}); + +describe("/api/leads/[[...path]]", () => { + it("returns 401 without a session", async () => { + mocks.getToken.mockResolvedValue(null); + const res = await GET(req("/api/leads"), ctx()); + expect(res.status).toBe(401); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("forwards the list call (no path) with the query string", async () => { + const res = await GET(req("/api/leads?q=ann&page=0&size=20"), ctx()); + expect(res.status).toBe(200); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/leads?q=ann&page=0&size=20", { token: "jwt-abc" }); + }); + + it("forwards the detail GET and the PUT body", async () => { + await GET(req("/api/leads/l-1"), ctx("l-1")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/leads/l-1", { token: "jwt-abc" }); + await PUT(req("/api/leads/l-1", { method: "PUT", body: JSON.stringify({ name: "Ann" }) }), ctx("l-1")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/leads/l-1", { method: "PUT", body: { name: "Ann" }, token: "jwt-abc" }); + }); + + it("rejects dot segments so the proxy cannot leave /api/admin/leads", async () => { + const res = await GET(req("/api/leads/x"), ctx("..", "users")); + expect(res.status).toBe(400); + expect(mocks.callMobileApi).not.toHaveBeenCalled(); + }); + + it("encodes path segments", async () => { + await GET(req("/api/leads/a"), ctx("a/b")); + expect(mocks.callMobileApi).toHaveBeenCalledWith("/api/admin/leads/a%2Fb", { token: "jwt-abc" }); + }); + + it("passes upstream 404 with its code", async () => { + mocks.callMobileApi.mockResolvedValue({ ok: false, error: "Lead not found", status: 404, code: "LEAD_NOT_FOUND" }); + const res = await GET(req("/api/leads/zz"), ctx("zz")); + expect(res.status).toBe(404); + expect(((await res.json()) as Record).code).toBe("LEAD_NOT_FOUND"); + }); +}); diff --git a/solvway-admin-portal/app/api/leads/[[...path]]/route.ts b/solvway-admin-portal/app/api/leads/[[...path]]/route.ts new file mode 100644 index 0000000..f8237f5 --- /dev/null +++ b/solvway-admin-portal/app/api/leads/[[...path]]/route.ts @@ -0,0 +1,23 @@ +import { NextResponse, type NextRequest } from "next/server"; +import { callMobileApi } from "@/app/lib/server/mobileApi"; +import { getToken } from "@/app/lib/server/session"; +import { badRequest, errorResponse, unauthorized } from "@/app/lib/server/apiRoute"; + +// One proxy for every /api/admin/leads endpoint; mobile-api owns validation and the BO_LEADS guards. +type Ctx = { params: Promise<{ path?: string[] }> }; + +async function forward(req: NextRequest, { params }: Ctx, method?: "PUT") { + const token = await getToken(); + if (!token) return unauthorized(); + const { path = [] } = await params; // [[...path]]: the list call has no segment + if (path.some((s) => s === "." || s === "..")) return badRequest("Invalid path."); + const target = `/api/admin/leads${path.map(encodeURIComponent).map((s) => `/${s}`).join("")}${new URL(req.url).search}`; + const result = method + ? await callMobileApi(target, { method, body: await req.json().catch(() => ({})), token }) + : await callMobileApi(target, { token }); + if (!result.ok) return errorResponse(result); + return NextResponse.json(result.data); +} + +export const GET = (req: NextRequest, ctx: Ctx) => forward(req, ctx); +export const PUT = (req: NextRequest, ctx: Ctx) => forward(req, ctx, "PUT"); diff --git a/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.tsx b/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.tsx index dbccea6..5bc3ed0 100644 --- a/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.tsx +++ b/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/page.tsx @@ -9,6 +9,7 @@ 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 { useAdminAuth } from "@/app/lib/AdminAuthContext"; import { RequireModule } from "@/app/lib/RequireModule"; import { ApiError } from "@/app/lib/clientApi"; import { formatDmy } from "@/app/lib/date-input"; @@ -35,6 +36,7 @@ type LoadState = "loading" | "notFound" | "error" | Loaded; function EventLead() { const t = useT(); const router = useRouter(); + const { hasModule } = useAdminAuth(); const { eventUuid, eventLeadUuid } = useParams<{ eventUuid: string; eventLeadUuid: string }>(); const [state, setState] = useState("loading"); const [reloadKey, setReloadKey] = useState(0); @@ -145,6 +147,11 @@ function EventLead() { {lead.email &&

{lead.email}

} {lead.companyName &&

{lead.companyName}

} {lead.jobTitle &&

{lead.jobTitle}

} + {hasModule("BO_LEADS") && ( + + )}

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

diff --git a/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/view-lead.test.tsx b/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/view-lead.test.tsx new file mode 100644 index 0000000..08ee325 --- /dev/null +++ b/solvway-admin-portal/app/event-leads/[eventUuid]/[eventLeadUuid]/view-lead.test.tsx @@ -0,0 +1,47 @@ +import { render, screen } from "@testing-library/react"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ + getEventLead: vi.fn(), listEventSalespeople: vi.fn(), listEventLeadInterests: vi.fn(), useAdminAuth: vi.fn(), +})); +vi.mock("@/app/lib/services/adminEventLeads", async (importActual) => ({ + ...(await importActual()), + getEventLead: mocks.getEventLead, + 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 EventLeadPage from "./page"; + +const grant = (...modules: string[]) => + mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => modules.includes(m) }); + +beforeEach(() => { + mocks.getEventLead.mockReset().mockResolvedValue({ + eventLeadUuid: "el-1", eventUuid: "evt-1", leadUuid: "l-1", name: "Ann Lead", mobile: null, email: "ann@x.com", + companyName: null, jobTitle: null, leadType: "NEW", salesperson: null, temperature: null, status: "OPEN", + interests: [], nextFollowUpDate: null, notes: null, capturedAt: "2026-11-20T09:30:00Z", + }); + mocks.listEventSalespeople.mockReset().mockResolvedValue([]); + mocks.listEventLeadInterests.mockReset().mockResolvedValue([]); +}); + +describe("EventLeadPage View lead link", () => { + it("links to the lead with BO_LEADS", async () => { + grant("BO_EVENT_LEADS", "BO_LEADS"); + render(); + expect(await screen.findByRole("link", { name: "View lead" })).toHaveAttribute("href", "/leads/l-1"); + }); + + it("hides the link without BO_LEADS", async () => { + grant("BO_EVENT_LEADS"); + render(); + await screen.findByLabelText("Status"); + expect(screen.queryByRole("link", { name: "View lead" })).toBeNull(); + }); +}); diff --git a/solvway-admin-portal/app/leads/[leadUuid]/page.test.tsx b/solvway-admin-portal/app/leads/[leadUuid]/page.test.tsx new file mode 100644 index 0000000..68c0b2a --- /dev/null +++ b/solvway-admin-portal/app/leads/[leadUuid]/page.test.tsx @@ -0,0 +1,218 @@ +import { render, screen, within } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { describe, it, expect, vi, beforeEach } from "vitest"; + +const mocks = vi.hoisted(() => ({ getLead: vi.fn(), updateLead: vi.fn(), useAdminAuth: vi.fn() })); +vi.mock("@/app/lib/services/adminLeads", async (importActual) => ({ + ...(await importActual()), + getLead: mocks.getLead, + updateLead: mocks.updateLead, +})); +vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth })); +vi.mock("next/navigation", async () => ({ + ...(await import("@/test/memoryRouter")).navigationMock, + useParams: () => ({ leadUuid: "l-1" }), +})); + +import { ApiError } from "@/app/lib/clientApi"; +import { memoryRouter } from "@/test/memoryRouter"; +import LeadPage from "./page"; + +const SERVER_MSG = "Server says: internal detail xyz"; +const apiError = (code: string, extra: Record = {}, status = 400) => + new ApiError(SERVER_MSG, status, { code, errors: [], details: {}, ...extra }); + +const LEAD = { + leadUuid: "l-1", name: "Aisyah", mobile: "+60123456701", email: "a@x.test", companyName: "Example Co", jobTitle: "CEO", + notes: "VIP", createdAt: "2026-11-01T00:00:00Z", updatedAt: "2026-11-02T00:00:00Z", updatedBy: "admin", + history: [ + { eventLeadUuid: "el-2", eventUuid: "e-2", eventName: "Penang Expo", eventStart: "2026-11-20T00:00:00", eventEnd: "2026-11-22T00:00:00", + leadType: "EXISTING", salesperson: null, temperature: "COLD", status: "OPEN", capturedAt: "2026-11-20T09:30:00Z" }, + { eventLeadUuid: "el-1", eventUuid: "e-1", eventName: "KL Food Fair", eventStart: "2026-10-05T00:00:00", eventEnd: "2026-10-06T00:00:00", + leadType: "NEW", salesperson: { id: 7, name: "Ali" }, temperature: "HOT", status: "WON", capturedAt: "2026-10-05T10:00:00Z" }, + ], + sharedContacts: [] as unknown[], +}; +const PAYLOAD = { name: "Aisyah", mobile: "+60123456701", email: "a@x.test", companyName: "Example Co", jobTitle: "CEO", notes: "VIP" }; + +const grant = (...modules: string[]) => + mocks.useAdminAuth.mockReturnValue({ loading: false, hasModule: (m: string) => modules.includes(m) }); + +async function open(lead: Record = {}) { + mocks.getLead.mockResolvedValue({ ...LEAD, ...lead }); + render(); + await screen.findByText("Penang Expo"); + return userEvent.setup(); +} + +beforeEach(() => { + memoryRouter.reset("/leads/l-1"); + mocks.getLead.mockReset(); + mocks.updateLead.mockReset().mockResolvedValue(LEAD); + grant("BO_LEADS", "BO_LEADS_EDIT", "BO_EVENT_LEADS"); +}); + +describe("LeadPage", { timeout: 20000 }, () => { + it("renders NotAuthorized without BO_LEADS", () => { + grant("BO_LEADS_EDIT"); + render(); + expect(screen.getByTestId("not-authorized")).toBeInTheDocument(); + expect(mocks.getLead).not.toHaveBeenCalled(); + }); + + it("lists event history newest first with type, salesperson, temperature, status and dates", async () => { + await open(); + const cards = screen.getAllByTestId("history-card"); + expect(cards.map((c) => within(c).getByText(/Penang Expo|KL Food Fair/).textContent)).toEqual(["Penang Expo", "KL Food Fair"]); + const first = within(cards[1]); + expect(first.getByText("New")).toBeVisible(); + expect(first.getByText("Ali")).toBeVisible(); + expect(first.getByText("Hot")).toBeVisible(); + expect(first.getByText("Won")).toBeVisible(); + expect(first.getByText("05/10/2026 - 06/10/2026")).toBeVisible(); + expect(first.getByText("Captured 05/10/2026")).toBeVisible(); + }); + + it("links history cards to the event lead only with BO_EVENT_LEADS", async () => { + await open(); + expect(screen.getAllByTestId("history-card")[0].closest("a") ?? within(screen.getAllByTestId("history-card")[0]).getByRole("link")) + .toHaveAttribute("href", "/event-leads/e-2/el-2"); + }); + + it("shows plain history cards without BO_EVENT_LEADS", async () => { + grant("BO_LEADS"); + await open(); + expect(screen.getAllByTestId("history-card")).toHaveLength(2); + expect(screen.queryByRole("link", { name: /Penang Expo/ })).toBeNull(); + }); + + it("warns about a shared mobile and links the other lead", async () => { + await open({ sharedContacts: [{ leadUuid: "l-2", name: "Test Visitor Two", sameMobile: true, sameEmail: false }] }); + const alert = screen.getByRole("alert"); + expect(alert).toHaveTextContent("Same mobile as"); + expect(within(alert).getByRole("link", { name: "Test Visitor Two" })).toHaveAttribute("href", "/leads/l-2"); + }); + + it("shows no warning without shared contacts", async () => { + await open(); + expect(screen.queryByRole("alert")).toBeNull(); + }); + + it("prefills an edit form with phone-friendly inputs", async () => { + await open(); + const mobile = screen.getByLabelText("Mobile"); + expect(mobile).toHaveValue("+60123456701"); + expect(mobile).toHaveAttribute("type", "tel"); + expect(mobile).toHaveAttribute("inputmode", "tel"); + expect(mobile).toHaveAttribute("autocomplete", "tel"); + expect(screen.getByLabelText("Email")).toHaveAttribute("type", "email"); + expect(screen.getByLabelText("Notes")).toHaveValue("VIP"); + }); + + it("saves the exact payload and shows the returned values with a success message", async () => { + const user = await open(); + mocks.updateLead.mockResolvedValue({ ...LEAD, email: "aisyah@example.test", companyName: "Example Co Ltd" }); + await user.clear(screen.getByLabelText("Email")); + await user.type(screen.getByLabelText("Email"), " Aisyah@Example.TEST "); + await user.clear(screen.getByLabelText("Company")); + await user.type(screen.getByLabelText("Company"), "Example Co Ltd"); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(mocks.updateLead).toHaveBeenCalledWith("l-1", { ...PAYLOAD, email: "Aisyah@Example.TEST", companyName: "Example Co Ltd" }); + expect(await screen.findByText("Lead saved.")).toBeVisible(); + expect(screen.getByLabelText("Email")).toHaveValue("aisyah@example.test"); + expect(memoryRouter.push).not.toHaveBeenCalled(); + }); + + it("sends blank optional fields as null", async () => { + const user = await open(); + await user.clear(screen.getByLabelText("Company")); + await user.clear(screen.getByLabelText("Notes")); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(mocks.updateLead).toHaveBeenCalledWith("l-1", { ...PAYLOAD, companyName: null, notes: null }); + }); + + it("shows an invalid mobile under the Mobile field with the mapped text", async () => { + const user = await open(); + mocks.updateLead.mockRejectedValue(apiError("INVALID_MOBILE", { details: { field: "mobile" } })); + await user.click(screen.getByRole("button", { name: "Save" })); + const mobile = await screen.findByLabelText("Mobile"); + expect(mobile).toHaveAttribute("aria-invalid", "true"); + const err = document.getElementById(mobile.getAttribute("aria-describedby")!)!; + expect(err).toHaveTextContent("Enter a valid mobile number."); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + }); + + it("marks every field listed by REQUIRED_FIELD", async () => { + const user = await open(); + mocks.updateLead.mockRejectedValue(apiError("REQUIRED_FIELD", { errors: ["name", "email"] })); + await user.click(screen.getByRole("button", { name: "Save" })); + await screen.findAllByText("This field is required."); + expect(screen.getByLabelText("Name")).toHaveAttribute("aria-invalid", "true"); + expect(screen.getByLabelText("Email")).toHaveAttribute("aria-invalid", "true"); + expect(screen.getByLabelText("Mobile")).not.toHaveAttribute("aria-invalid"); + }); + + it("never fails silently: unknown codes show a form-level message", async () => { + const user = await open(); + mocks.updateLead.mockRejectedValue(apiError("SOMETHING_ELSE", {}, 500)); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByText("Could not save the lead. Please try again.")).toBeVisible(); + expect(screen.queryByText(SERVER_MSG)).toBeNull(); + }); + + it("is read-only without BO_LEADS_EDIT", async () => { + grant("BO_LEADS"); + await open(); + expect(screen.queryByRole("button", { name: "Save" })).toBeNull(); + expect(screen.queryByRole("textbox")).toBeNull(); + expect(screen.getByText("+60123456701")).toBeVisible(); + expect(screen.getByText("a@x.test")).toBeVisible(); + expect(screen.getByText("VIP")).toBeVisible(); + }); + + it("shows not-found with a Back link on LEAD_NOT_FOUND", async () => { + mocks.getLead.mockRejectedValue(apiError("LEAD_NOT_FOUND", {}, 404)); + render(); + expect(await screen.findByText("Lead not found")).toBeVisible(); + expect(screen.getByRole("link", { name: "Back" })).toHaveAttribute("href", "/leads"); + }); + + it("shows an error state with retry on other load failures", async () => { + mocks.getLead.mockRejectedValueOnce(apiError("BOOM", {}, 500)); + render(); + expect(await screen.findByText("Failed to load the lead")).toBeVisible(); + mocks.getLead.mockResolvedValue(LEAD); + await userEvent.click(screen.getByRole("button", { name: /retry/i })); + expect(await screen.findByText("Penang Expo")).toBeVisible(); + }); + + it("shows the shared-contact warning returned by a save", async () => { + const user = await open(); + mocks.updateLead.mockResolvedValue({ ...LEAD, sharedContacts: [{ leadUuid: "l-9", name: "Other Person", sameMobile: true, sameEmail: false }] }); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByRole("link", { name: "Other Person" })).toHaveAttribute("href", "/leads/l-9"); + }); + + it("clears the saved message once the user edits again", async () => { + const user = await open(); + await user.click(screen.getByRole("button", { name: "Save" })); + expect(await screen.findByText("Lead saved.")).toBeVisible(); + await user.type(screen.getByLabelText("Notes"), "!"); + expect(screen.queryByText("Lead saved.")).toBeNull(); + }); + + it("names each read-only value by its label", async () => { + grant("BO_LEADS"); + await open(); + const email = screen.getByText("a@x.test"); + expect(email.tagName).toBe("DD"); + expect(email.previousElementSibling?.tagName).toBe("DT"); + expect(email.previousElementSibling).toHaveTextContent("Email"); + }); + + it("hides the dates line of an event without dates", async () => { + await open({ history: [{ ...LEAD.history[0], eventStart: null, eventEnd: null }] }); + const card = screen.getByTestId("history-card"); + expect(card.textContent).not.toMatch(/\s-\s/); + }); +}); diff --git a/solvway-admin-portal/app/leads/[leadUuid]/page.tsx b/solvway-admin-portal/app/leads/[leadUuid]/page.tsx new file mode 100644 index 0000000..3198c69 --- /dev/null +++ b/solvway-admin-portal/app/leads/[leadUuid]/page.tsx @@ -0,0 +1,216 @@ +"use client"; + +import { useEffect, useState, type FormEvent } from "react"; +import { useParams } from "next/navigation"; +import Link from "next/link"; +import { Alert } from "@/app/components/ui/alert"; +import { Badge } from "@/app/components/ui/badge"; +import { Button } from "@/app/components/ui/button"; +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 { useAdminAuth } from "@/app/lib/AdminAuthContext"; +import { RequireModule } from "@/app/lib/RequireModule"; +import { ApiError } from "@/app/lib/clientApi"; +import { formatDmy } from "@/app/lib/date-input"; +import { getLead, updateLead } from "@/app/lib/services/adminLeads"; +import type { LeadDetail } from "@/app/lib/types"; +import { useT } from "@/app/lib/i18n/MessagesProvider"; + +const TEMPERATURES: Record = { HOT: "LeadHot", WARM: "LeadWarm", COLD: "LeadCold" }; +const STATUSES: Record = { 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", +}; +// Codes that name their field themselves when the server omits details.field. +const IMPLIED_FIELD: Record = { INVALID_MOBILE: "mobile", INVALID_EMAIL: "email" }; +const FIELDS = [ + ["name", "LeadName"], ["mobile", "LeadMobile"], ["email", "Email"], ["companyName", "LeadCompany"], ["jobTitle", "LeadJobTitle"], ["notes", "LeadNotes"], +] as const; +type Field = (typeof FIELDS)[number][0]; +const INPUT_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 INPUT_ATTRS: Partial>> = { + mobile: { type: "tel", inputMode: "tel", autoComplete: "tel" }, + email: { type: "email", autoComplete: "email" }, +}; +const TALL = "min-h-11"; + +type LoadState = "loading" | "notFound" | "error" | LeadDetail; +const blankToNull = (v: string) => (v.trim() === "" ? null : v); +const toValues = (l: LeadDetail): Record => ({ + name: l.name, mobile: l.mobile ?? "", email: l.email ?? "", companyName: l.companyName ?? "", jobTitle: l.jobTitle ?? "", notes: l.notes ?? "", +}); + +function Lead() { + const t = useT(); + const { hasModule } = useAdminAuth(); + const { leadUuid } = useParams<{ leadUuid: string }>(); + const [state, setState] = useState("loading"); + const [reloadKey, setReloadKey] = useState(0); + const [values, setValues] = useState>(toValues({ name: "", mobile: null, email: null, companyName: null, jobTitle: null, notes: null } as LeadDetail)); + const [fieldErrors, setFieldErrors] = useState>({}); + const [formError, setFormError] = useState(null); + const [saved, setSaved] = useState(false); + const [busy, setBusy] = useState(false); + + useEffect(() => { + let cancelled = false; + getLead(leadUuid) + .then((lead) => { + if (cancelled) return; + setValues(toValues(lead)); + setState(lead); + }) + .catch((err) => { + if (cancelled) return; + const code = err instanceof ApiError ? (err.data as { code?: string } | undefined)?.code : undefined; + setState(code === "LEAD_NOT_FOUND" ? "notFound" : "error"); + }); + return () => { cancelled = true; }; + }, [leadUuid, reloadKey]); + + if (state === "loading") return ; + if (state === "notFound") { + return ( + {t("Back")}} + /> + ); + } + if (state === "error") { + return { setState("loading"); setReloadKey((k) => k + 1); }} />; + } + const lead = state; + const canEdit = hasModule("BO_LEADS_EDIT"); + + async function onSave(event: FormEvent) { + event.preventDefault(); + setFieldErrors({}); + setFormError(null); + setSaved(false); + setBusy(true); + try { + const updated = await updateLead(leadUuid, { + name: values.name, + mobile: blankToNull(values.mobile), + email: blankToNull(values.email), + companyName: blankToNull(values.companyName), + jobTitle: blankToNull(values.jobTitle), + notes: blankToNull(values.notes), + }); + setValues(toValues(updated)); + setState(updated); + setSaved(true); + } catch (err) { + const data = err instanceof ApiError + ? (err.data as { code?: string; errors?: string[]; details?: { field?: unknown } } | undefined) + : undefined; + const code = data?.code; + const named = code === "REQUIRED_FIELD" ? data?.errors ?? [] : [typeof data?.details?.field === "string" ? data.details.field : IMPLIED_FIELD[code ?? ""]]; + const known = FIELDS.map(([f]) => f as string); + const fields = named.filter((f): f is string => !!f && known.includes(f)); + // A named field the form does not render, or an unmapped code, must not make the failure silent. + if (code && CODE_MESSAGE[code] && fields.length && fields.length === named.length) { + setFieldErrors(Object.fromEntries(fields.map((f) => [f, t(CODE_MESSAGE[code])]))); + } else { + setFormError(t("LeadSaveFailed")); + } + } finally { + setBusy(false); + } + } + + const sharedLabel = (s: LeadDetail["sharedContacts"][number]) => + t(s.sameMobile && s.sameEmail ? "LeadsSameMobileEmailAs" : s.sameMobile ? "LeadsSameMobileAs" : "LeadsSameEmailAs"); + + return ( +
+ + + {lead.sharedContacts.length > 0 && ( + +
+ {lead.sharedContacts.map((s) => ( +

+ {sharedLabel(s)}{" "} + {s.name} +

+ ))} +
+
+ )} + + {formError && } + {saved &&

{t("LeadsSaved")}

} + + {canEdit ? ( +
+ {FIELDS.map(([f, label]) => { + const err = fieldErrors[f]; + return ( +
+ + {f === "notes" ? ( +