Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfiCVCgCVJZq4NDEqZs
383 lines
16 KiB
TypeScript
383 lines
16 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useMemo, useState } from "react";
|
|
import { useParams } from "next/navigation";
|
|
import Link from "next/link";
|
|
import { Download, Plus } from "lucide-react";
|
|
import type { ColumnDef } from "@tanstack/react-table";
|
|
import { Badge } from "@/app/components/ui/badge";
|
|
import { Button } from "@/app/components/ui/button";
|
|
import { FilterField, FilterPanel, FilterSelect } from "@/app/components/ui/filter-panel";
|
|
import { DataTable } from "@/app/components/ui/data-table";
|
|
import { PageHeader } from "@/app/components/ui/page-header";
|
|
import { EmptyState, ErrorState } from "@/app/components/ui/states";
|
|
import { RequireModule } from "@/app/lib/RequireModule";
|
|
import { useAdminAuth } from "@/app/lib/AdminAuthContext";
|
|
import { ApiError } from "@/app/lib/clientApi";
|
|
import { useListFilters } from "@/app/lib/hooks/useListFilters";
|
|
import { useFitPageSize, MIN_PAGE_SIZE } from "@/app/lib/hooks/useFitPageSize";
|
|
import { exportEventLeads, listEventLeads, listEventSalespeople, listEventLeadInterests, listEventLeadEvents } from "@/app/lib/services/adminEventLeads";
|
|
import type { EventLeadRow, InterestOption, SalespersonOption } from "@/app/lib/types";
|
|
import { useCompanyScope } from "@/app/lib/CompanyScope";
|
|
import { useT } from "@/app/lib/i18n/MessagesProvider";
|
|
import { formatDmy } from "@/app/lib/date-input";
|
|
import { WhatsAppButton } from "@/app/components/app/WhatsAppButton";
|
|
|
|
const DEFAULTS = { salespersonId: "", temperature: "", status: "", interestId: "", leadType: "", attended: "" };
|
|
const TEMPERATURE_OPTIONS = [{ value: "HOT", label: "LeadHot" }, { value: "WARM", label: "LeadWarm" }, { value: "COLD", label: "LeadCold" }];
|
|
const STATUS_OPTIONS = [{ value: "OPEN", label: "LeadOpen" }, { value: "CONTACTED", label: "LeadContacted" }, { value: "QUALIFIED", label: "LeadQualified" }, { value: "WON", label: "LeadWon" }, { value: "LOST", label: "LeadLost" }];
|
|
const LEAD_TYPE_OPTIONS = [{ value: "NEW", label: "LeadNew" }, { value: "EXISTING", label: "LeadExisting" }];
|
|
const ATTENDED_OPTIONS = [{ value: "true", label: "GuestAttended" }, { value: "false", label: "LeadNotAttended" }];
|
|
const SOURCE_LABEL = { STAFF: "LeadSourceStaff", QR: "LeadSourceQr", INVITE: "LeadSourceInvite", WEB: "LeadSourceWeb", TICKET: "LeadSourceTicket" } as const;
|
|
const TEMPERATURE_BADGE = { HOT: "negative", WARM: "warning", COLD: "neutral" } as const;
|
|
const STATUS_BADGE = { OPEN: "neutral", CONTACTED: "neutral", QUALIFIED: "contrast", WON: "positive", LOST: "negative" } as const;
|
|
|
|
function EventLeadsDetailPageContent() {
|
|
const t = useT();
|
|
const { companyId, showCompanyColumn, codeOf } = useCompanyScope();
|
|
const { hasModule } = useAdminAuth();
|
|
const { eventUuid } = useParams<{ eventUuid: string }>();
|
|
const { tableRef, pageSize } = useFitPageSize();
|
|
const { filters, page, set, setPage, clear, activeCount } = useListFilters(DEFAULTS);
|
|
const [data, setData] = useState<{ items: EventLeadRow[]; total: number }>({ items: [], total: 0 });
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [reloadKey, setReloadKey] = useState(0);
|
|
const [salespeople, setSalespeople] = useState<SalespersonOption[]>([]);
|
|
const [interests, setInterests] = useState<InterestOption[]>([]);
|
|
// undefined while loading; null when the event is unknown or the lookup failed.
|
|
const [eventName, setEventName] = useState<string | null | undefined>(undefined);
|
|
|
|
// Load event name from the events list
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
(companyId ? listEventLeadEvents(companyId) : listEventLeadEvents())
|
|
.then((events) => {
|
|
if (!cancelled) {
|
|
const found = events.find((e) => e.uuid === eventUuid);
|
|
setEventName(found ? found.name : null);
|
|
}
|
|
})
|
|
.catch(() => { if (!cancelled) setEventName(null); });
|
|
return () => { cancelled = true; };
|
|
}, [eventUuid, companyId]);
|
|
|
|
const [exporting, setExporting] = useState(false);
|
|
const [exportError, setExportError] = useState<string | null>(null);
|
|
|
|
const runExport = () => {
|
|
setExporting(true);
|
|
setExportError(null);
|
|
(companyId ? exportEventLeads(eventUuid, filters, companyId) : exportEventLeads(eventUuid, filters))
|
|
.catch((err: unknown) => {
|
|
const tooLarge = err instanceof ApiError && (err.data as { code?: string } | undefined)?.code === "EXPORT_TOO_LARGE";
|
|
setExportError(tooLarge ? t("LeadsExportTooLarge") : err instanceof Error ? err.message : t("LeadListLoadFailed"));
|
|
})
|
|
.finally(() => setExporting(false));
|
|
};
|
|
|
|
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
|
|
|
|
// Load lookup options
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
Promise.allSettled([
|
|
listEventSalespeople(eventUuid),
|
|
listEventLeadInterests(),
|
|
]).then(([salesRes, interestRes]) => {
|
|
if (!cancelled) {
|
|
if (salesRes.status === "fulfilled") setSalespeople(salesRes.value);
|
|
if (interestRes.status === "fulfilled") setInterests(interestRes.value);
|
|
}
|
|
});
|
|
return () => { cancelled = true; };
|
|
}, [eventUuid]);
|
|
|
|
// Fetch leads
|
|
useEffect(() => {
|
|
if (pageSize == null) return;
|
|
let cancelled = false;
|
|
// eslint-disable-next-line react-hooks/set-state-in-effect -- resets loading/error before the eventUuid/page/reloadKey-triggered fetch below.
|
|
setLoading(true);
|
|
setError(null);
|
|
setExportError(null);
|
|
listEventLeads(eventUuid, { page, pageSize, ...filters, companyId })
|
|
.then((result) => {
|
|
if (!cancelled) setData(result);
|
|
})
|
|
.catch((err: unknown) => {
|
|
if (!cancelled) setError(err instanceof Error ? err.message : "LeadListLoadFailed");
|
|
})
|
|
.finally(() => {
|
|
if (!cancelled) setLoading(false);
|
|
});
|
|
return () => { cancelled = true; };
|
|
}, [eventUuid, filters, page, pageSize, reloadKey, companyId]);
|
|
|
|
const salespersonOptions = useMemo(
|
|
() => salespeople.map((o) => ({ value: String(o.id), label: o.name })),
|
|
[salespeople],
|
|
);
|
|
|
|
const interestOptions = useMemo(
|
|
() => interests.map((o) => ({ value: String(o.id), label: o.name })),
|
|
[interests],
|
|
);
|
|
|
|
const temperatureOptions = useMemo(
|
|
() => TEMPERATURE_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
|
|
[t],
|
|
);
|
|
|
|
const statusOptions = useMemo(
|
|
() => STATUS_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
|
|
[t],
|
|
);
|
|
|
|
const leadTypeOptions = useMemo(
|
|
() => LEAD_TYPE_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
|
|
[t],
|
|
);
|
|
|
|
const attendedOptions = useMemo(
|
|
() => ATTENDED_OPTIONS.map((o) => ({ value: o.value, label: t(o.label) })),
|
|
[t],
|
|
);
|
|
|
|
const columns = useMemo<ColumnDef<EventLeadRow, unknown>[]>(
|
|
() => [
|
|
...(showCompanyColumn ? [{ id: "company", cell: ({ row }) => codeOf(row.original.companyId ?? 0), header: t("Company"), enableSorting: false } as ColumnDef<EventLeadRow, unknown>] : []),
|
|
{
|
|
accessorKey: "name",
|
|
header: t("LeadName"),
|
|
cell: ({ row }) => (
|
|
<Link
|
|
href={`/event-leads/${row.original.eventUuid}/${row.original.eventLeadUuid}`}
|
|
className="font-medium text-primary underline-offset-4 hover:underline focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none min-h-11 flex items-center"
|
|
>
|
|
{row.original.name}
|
|
</Link>
|
|
),
|
|
},
|
|
{
|
|
accessorKey: "mobile",
|
|
header: t("LeadMobile"),
|
|
cell: ({ row }) => (
|
|
<span className="inline-flex items-center gap-1">
|
|
{row.original.mobile || "—"}
|
|
<WhatsAppButton target={{ eventLeadUuid: row.original.eventLeadUuid }} mobile={row.original.mobile} />
|
|
</span>
|
|
),
|
|
},
|
|
{
|
|
accessorKey: "email",
|
|
header: t("Email"),
|
|
cell: ({ row }) => <span>{row.original.email || "—"}</span>,
|
|
},
|
|
{
|
|
accessorKey: "leadType",
|
|
header: t("LeadType"),
|
|
enableSorting: false,
|
|
cell: ({ row }) => (
|
|
<Badge variant={row.original.leadType === "NEW" ? "default" : "secondary"}>
|
|
{t(row.original.leadType === "NEW" ? "LeadNew" : "LeadExisting")}
|
|
</Badge>
|
|
),
|
|
},
|
|
{
|
|
accessorKey: "salesperson",
|
|
header: t("LeadSalesperson"),
|
|
enableSorting: false,
|
|
cell: ({ row }) => <span>{row.original.salesperson?.name || "—"}</span>,
|
|
},
|
|
{
|
|
accessorKey: "temperature",
|
|
header: t("LeadTemperature"),
|
|
enableSorting: false,
|
|
cell: ({ row }) => {
|
|
const temp = row.original.temperature;
|
|
if (!temp) return <span>—</span>;
|
|
return <Badge variant={TEMPERATURE_BADGE[temp]}>{t(TEMPERATURE_OPTIONS.find((o) => o.value === temp)!.label)}</Badge>;
|
|
},
|
|
},
|
|
{
|
|
accessorKey: "status",
|
|
header: t("Status"),
|
|
enableSorting: false,
|
|
cell: ({ row }) => {
|
|
const s = row.original.status;
|
|
return <Badge variant={STATUS_BADGE[s]}>{t(STATUS_OPTIONS.find((o) => o.value === s)!.label)}</Badge>;
|
|
},
|
|
},
|
|
{
|
|
accessorKey: "interests",
|
|
header: t("LeadInterests"),
|
|
enableSorting: false,
|
|
cell: ({ row }) => <span>{row.original.interests.map(i => i.name).join(", ") || "—"}</span>,
|
|
},
|
|
{
|
|
accessorKey: "nextFollowUpDate",
|
|
header: t("LeadNextFollowUp"),
|
|
enableSorting: false,
|
|
cell: ({ row }) => <span className="tabular">{row.original.nextFollowUpDate ? formatDmy(row.original.nextFollowUpDate) : "—"}</span>,
|
|
},
|
|
{
|
|
accessorKey: "attended",
|
|
header: t("GuestAttended"),
|
|
enableSorting: false,
|
|
cell: ({ row }) => <span>{row.original.attended == null ? "—" : t(row.original.attended ? "Yes" : "No")}</span>,
|
|
},
|
|
{
|
|
accessorKey: "source",
|
|
header: t("LeadSource"),
|
|
enableSorting: false,
|
|
cell: ({ row }) => <span>{row.original.source ? t(SOURCE_LABEL[row.original.source]) : "—"}</span>,
|
|
},
|
|
],
|
|
[t, showCompanyColumn, codeOf],
|
|
);
|
|
|
|
return (
|
|
<>
|
|
<PageHeader
|
|
title={eventName === undefined ? "…" : (eventName ?? t("BO_EVENT_LEADS"))}
|
|
actions={
|
|
<>
|
|
{hasModule("BO_LEADS_EXPORT") && (
|
|
<Button variant="outline" disabled={exporting} onClick={runExport}>
|
|
<Download aria-hidden="true" className="size-4" />
|
|
{t("Export")}
|
|
</Button>
|
|
)}
|
|
<Button asChild>
|
|
<Link href={`/event-leads/${eventUuid}/new`}>
|
|
<Plus aria-hidden="true" className="size-4" />
|
|
{t("LeadAddLead")}
|
|
</Link>
|
|
</Button>
|
|
</>
|
|
}
|
|
/>
|
|
|
|
{exportError && <ErrorState message={exportError} className="mb-4" />}
|
|
|
|
{error && <ErrorState message={t(error)} onRetry={refetch} className="mb-4" />}
|
|
|
|
<FilterPanel activeCount={activeCount} onClear={clear}>
|
|
<FilterField label={t("LeadSalespersonFilter")}>
|
|
<FilterSelect className="w-full" aria-label={t("LeadSalespersonFilter")} allLabel={t("All")} options={salespersonOptions} value={filters.salespersonId} onChange={salespersonId => set({ salespersonId })} />
|
|
</FilterField>
|
|
<FilterField label={t("LeadTemperatureFilter")}>
|
|
<FilterSelect className="w-full" aria-label={t("LeadTemperatureFilter")} allLabel={t("All")} options={temperatureOptions} value={filters.temperature} onChange={temperature => set({ temperature })} />
|
|
</FilterField>
|
|
<FilterField label={t("LeadStatusFilter")}>
|
|
<FilterSelect className="w-full" aria-label={t("LeadStatusFilter")} allLabel={t("All")} options={statusOptions} value={filters.status} onChange={status => set({ status })} />
|
|
</FilterField>
|
|
<FilterField label={t("LeadInterestFilter")}>
|
|
<FilterSelect className="w-full" aria-label={t("LeadInterestFilter")} allLabel={t("All")} options={interestOptions} value={filters.interestId} onChange={interestId => set({ interestId })} />
|
|
</FilterField>
|
|
<FilterField label={t("LeadLeadTypeFilter")}>
|
|
<FilterSelect className="w-full" aria-label={t("LeadLeadTypeFilter")} allLabel={t("All")} options={leadTypeOptions} value={filters.leadType} onChange={leadType => set({ leadType })} />
|
|
</FilterField>
|
|
<FilterField label={t("LeadAttendedFilter")}>
|
|
<FilterSelect className="w-full" aria-label={t("LeadAttendedFilter")} allLabel={t("All")} options={attendedOptions} value={filters.attended} onChange={attended => set({ attended })} />
|
|
</FilterField>
|
|
</FilterPanel>
|
|
|
|
{/* Desktop table (md+) */}
|
|
<div className="hidden md:block">
|
|
<DataTable
|
|
label={t("BO_EVENT_LEADS")}
|
|
columns={columns}
|
|
data={data.items}
|
|
total={data.total}
|
|
page={page}
|
|
pageSize={pageSize ?? MIN_PAGE_SIZE}
|
|
tableRef={tableRef}
|
|
onPageChange={setPage}
|
|
isLoading={loading}
|
|
rowKey={(e) => String(e.eventLeadUuid)}
|
|
empty={<EmptyState title={activeCount > 0 ? t("LeadNoMatch") : t("LeadNoLeads")} />}
|
|
/>
|
|
</div>
|
|
|
|
{/* Mobile cards (below md) */}
|
|
<div className="md:hidden space-y-3" aria-busy={loading}>
|
|
{data.items.map((lead) => (
|
|
<Link
|
|
key={lead.eventLeadUuid}
|
|
href={`/event-leads/${lead.eventUuid}/${lead.eventLeadUuid}`}
|
|
data-testid="lead-card"
|
|
className={`flex flex-col gap-1 rounded-lg border p-3 transition-colors hover:bg-accent min-h-11${loading ? " opacity-60" : ""}`}
|
|
>
|
|
<div className="flex items-center justify-between">
|
|
<span className="font-medium">{lead.name}</span>
|
|
<Badge variant={lead.leadType === "NEW" ? "default" : "secondary"}>{t(lead.leadType === "NEW" ? "LeadNew" : "LeadExisting")}</Badge>
|
|
</div>
|
|
<div className="text-sm text-muted-foreground">
|
|
{lead.mobile || "—"}
|
|
</div>
|
|
<div className="flex items-center gap-2 text-sm">
|
|
{lead.temperature && <Badge variant={TEMPERATURE_BADGE[lead.temperature]} className="shrink-0">{t(TEMPERATURE_OPTIONS.find((o) => o.value === lead.temperature)!.label)}</Badge>}
|
|
<Badge variant={STATUS_BADGE[lead.status]} className="shrink-0">{t(STATUS_OPTIONS.find((o) => o.value === lead.status)!.label)}</Badge>
|
|
</div>
|
|
<div className="text-sm text-muted-foreground">
|
|
{t("LeadNextFollowUp")}: {lead.nextFollowUpDate ? formatDmy(lead.nextFollowUpDate) : "—"}
|
|
</div>
|
|
<div className="text-sm text-muted-foreground">
|
|
{t("GuestAttended")}: {lead.attended == null ? "—" : t(lead.attended ? "Yes" : "No")}
|
|
</div>
|
|
<div className="text-sm text-muted-foreground">
|
|
{t("LeadSource")}: {lead.source ? t(SOURCE_LABEL[lead.source]) : "—"}
|
|
</div>
|
|
</Link>
|
|
))}
|
|
{data.items.length === 0 && !loading && (
|
|
<EmptyState title={activeCount > 0 ? t("LeadNoMatch") : t("LeadNoLeads")} />
|
|
)}
|
|
{/* Phone pager: 44px targets; DataTable has its own above md */}
|
|
{data.total > (pageSize ?? MIN_PAGE_SIZE) && (
|
|
<div className="flex items-center justify-between mt-4">
|
|
<div className="text-sm text-muted-foreground">
|
|
{t("PagerRange", {
|
|
first: data.total === 0 ? 0 : (page - 1) * (pageSize ?? MIN_PAGE_SIZE) + 1,
|
|
last: Math.min(page * (pageSize ?? MIN_PAGE_SIZE), data.total),
|
|
total: data.total,
|
|
})}
|
|
</div>
|
|
<div className="flex items-center gap-2">
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
disabled={page <= 1}
|
|
onClick={() => setPage(page - 1)}
|
|
className="min-h-11"
|
|
>
|
|
{t("PagerPrevious")}
|
|
</Button>
|
|
<Button
|
|
variant="outline"
|
|
size="sm"
|
|
disabled={page * (pageSize ?? MIN_PAGE_SIZE) >= data.total}
|
|
onClick={() => setPage(page + 1)}
|
|
className="min-h-11"
|
|
>
|
|
{t("PagerNext")}
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
)}
|
|
</div>
|
|
|
|
</>
|
|
);
|
|
}
|
|
|
|
export default function EventLeadsDetailPage() {
|
|
return (
|
|
<RequireModule pathname="/event-leads">
|
|
<EventLeadsDetailPageContent />
|
|
</RequireModule>
|
|
);
|
|
}
|