All files / src/pages/admin web-leads.tsx

100% Statements 83/83
85% Branches 102/120
100% Functions 35/35
100% Lines 81/81

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656                                                                                                      1x 1x   1x                       1x                       1x     1x       1x                 156x       138x           1x                         137x           112x                           18x 18x 18x 18x 18x 18x   18x 18x     4x 4x     4x               1x 1x       18x                                                                                                   2x       108x                       4x                                                                   1x                                                                         137x   137x       6x                         1x                   1x                                                                                                 1x 1x                                           1x     8x                         38x 38x 38x 38x 38x 38x 38x 38x   38x 38x     38x                 38x           38x 38x 38x         38x 26x 1x       38x       11x 11x 11x         1x 1x 1x 1x 1x 1x 1x 1x     38x                                                         1x           2x           228x                 2x           114x                 1x                         2x                   2x           1x                                                                           333x                                     130x                                              
import { useEffect, useState } from "react";
import {
	ChevronDown,
	ChevronRight,
	Download,
	Inbox,
	MessageCircle,
	Phone,
} from "lucide-react";
 
import { Card } from "../../components/ui/card";
import { Button } from "../../components/ui/button";
import { Pagination } from "../../components/ui/pagination";
import { EmptyState } from "../../components/ui/empty-state";
import { Input } from "../../components/ui/input";
import { StatusBadge } from "../../components/ui/status-badge";
import {
	adminApi,
	type LandingLead,
	type LeadEntryType,
	type LeadFilters,
	type LeadStatus,
} from "../../lib/api";
import { telUrl, whatsappUrl } from "../../lib/crm-constants";
import { useDebouncedValue } from "../../hooks/useDebouncedValue";
import {
	useAdminLandingLead,
	useAdminLandingLeads,
	useUpdateLandingLead,
} from "../../hooks/queries/useAdminQueries";
import { Select } from "../../components/ui/select";
import {
	AdminBand,
	AdminPageHead,
	AdminToolbar,
} from "../../components/admin/AdminPageHead";
import { Textarea } from "../../components/ui/textarea";
import {
	Table,
	TableBody,
	TableCaption,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "../../components/ui/table";
import { Alert } from "../../components/ui/alert";
 
// Admin → Web leads (#1085): the lead store, one row per person, whatever
// brought them in. Mirrors pages/admin/consultations.tsx.
 
const PAGE_SIZE = 20;
const COLUMNS = 10;
 
const STATUSES: LeadStatus[] = [
	"new",
	"contacted",
	"qualified",
	"matched",
	"closed",
	"junk",
];
 
// Every value a row can hold, including the retired ones — this is the DISPLAY
// map, so a legacy row renders "Partner referral" and not a raw slug. Do not
// prune it when a lead source is retired: the rows outlive the programme.
const ENTRY_TYPE_LABELS: Record<LeadEntryType, string> = {
	form: "Form",
	calculator: "Calculator",
	whatsapp: "WhatsApp",
	// F-21 is retired and nothing writes this any more. Kept so historical
	// rows read as words. See apps/api/src/db/schema/enums.ts.
	partner_referral: "Partner referral",
};
 
// What the filter dropdown offers: only the sources still arriving. Narrower
// than ENTRY_TYPE_LABELS on purpose — a filter for a type no row will ever
// gain again is a dead end in the UI, while its label is still needed above.
const ENTRY_TYPE_FILTERS: LeadEntryType[] = ["form", "calculator", "whatsapp"];
 
const selectClass =
	"h-10 rounded-md border border-border-default bg-background-base px-3 py-2 text-sm text-foreground-default focus:outline-none focus:ring-2 focus:ring-primary-500";
 
// The team works in Hyderabad: every time on this page is IST, whatever the
// browser's own zone.
const IST = new Intl.DateTimeFormat("en-IN", {
	timeZone: "Asia/Kolkata",
	day: "2-digit",
	month: "short",
	hour: "2-digit",
	minute: "2-digit",
});
 
function ist(iso: string | null): string {
	return iso ? `${IST.format(new Date(iso))} IST` : "—";
}
 
function entryLabel(type: LeadEntryType | null): string {
	return type ? (ENTRY_TYPE_LABELS[type] ?? "—") : "—";
}
 
// ─── Status badge ────────────────────────────────────────────────────────────
 
/** Lead statuses onto the design system's badge variants. */
const STATUS_VARIANT = {
	new: "info",
	contacted: "warning",
	qualified: "success",
	matched: "success",
	closed: "default",
	junk: "error",
} as const satisfies Record<
	LeadStatus,
	"info" | "warning" | "success" | "default" | "error"
>;
 
function LeadStatusBadge({ status }: { status: LeadStatus }) {
	return <StatusBadge status={status} variant={STATUS_VARIANT[status]} />;
}
 
// ─── Row detail: work the lead, see its touches ──────────────────────────────
 
function Detail({ label, value }: { label: string; value: string | null }) {
	return (
		<div>
			<span className="text-foreground-muted font-medium">{label}:</span>{" "}
			<span className="text-foreground-default break-all">{value || "—"}</span>
		</div>
	);
}
 
/**
 * The editor starts from the server's values. The parent keys it on
 * `lastUpdated`, so after any save (ours or another admin's) it remounts with
 * fresh values instead of holding stale ones that a Save would write back.
 */
function RowDetail({ lead }: { lead: LandingLead }) {
	const { data, isLoading } = useAdminLandingLead(lead.id, true);
	const update = useUpdateLandingLead();
	const touches = data?.data?.touches ?? [];
	const [status, setStatus] = useState<LeadStatus>(lead.status);
	const [notes, setNotes] = useState(lead.adminNotes ?? "");
	const [saveError, setSaveError] = useState<string | null>(null);
	// The server trims notes; compare the way it will store them.
	const notesChanged = notes.trim() !== (lead.adminNotes ?? "");
	const statusChanged = status !== lead.status;
 
	async function save() {
		setSaveError(null);
		try {
			// Only what changed, so a status change never rewrites someone
			// else's notes (or the reverse).
			await update.mutateAsync({
				id: lead.id,
				patch: {
					...(statusChanged ? { status } : {}),
					...(notesChanged ? { adminNotes: notes.trim() } : {}),
				},
			});
		} catch (err) {
			console.error("Failed to update lead:", err);
			setSaveError("Could not save. Please try again.");
		}
	}
 
	return (
		<TableRow>
			<TableCell colSpan={COLUMNS}>
				<div className="rounded-lg bg-background-subtle border border-border-default p-4 text-sm space-y-4">
					<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
						<Detail label="Source" value={lead.source} />
						<Detail label="Offer" value={lead.offer} />
						<Detail label="Page" value={lead.pagePath} />
						<Detail label="Email" value={lead.email} />
						<Detail label="Locality" value={lead.locality} />
						<Detail
							label="UTM content / term"
							value={[lead.utmContent, lead.utmTerm]
								.filter(Boolean)
								.join(" / ")}
						/>
						<Detail label="Click id" value={lead.gclid ?? lead.fbclid} />
						<Detail
							label="Consent"
							value={
								lead.consentState
									? `${lead.consentState} (${lead.consentVersion ?? "no version"}) · ${ist(lead.consentAt)}`
									: "none recorded"
							}
						/>
					</div>
					{lead.notes && (
						<div>
							<p className="text-foreground-muted font-medium mb-1">
								From the homeowner:
							</p>
							<p className="text-foreground-default whitespace-pre-wrap text-xs bg-background-base rounded p-2">
								{lead.notes}
							</p>
						</div>
					)}
 
					{/* Work the lead */}
					<div className="space-y-2">
						<div className="flex flex-col sm:flex-row gap-3 sm:items-center">
							<label
								className="text-foreground-muted font-medium"
								htmlFor={`lead-status-${lead.id}`}
							>
								Status
							</label>
							<Select
								id={`lead-status-${lead.id}`}
								aria-label="Lead status"
								value={status}
								onChange={(e) => setStatus(e.target.value as LeadStatus)}
								className={selectClass}
							>
								{STATUSES.map((s) => (
									<option key={s} value={s}>
										{s}
									</option>
								))}
							</Select>
						</div>
						<Textarea
							aria-label="Admin notes"
							value={notes}
							maxLength={1000}
							rows={3}
							placeholder="Call notes, next step…"
							onChange={(e) => setNotes(e.target.value)}
							className="w-full"
						/>
						<div className="flex items-center gap-3">
							<Button
								size="sm"
								onClick={save}
								disabled={(!statusChanged && !notesChanged) || update.isPending}
								isLoading={update.isPending}
							>
								Save
							</Button>
							{saveError && (
								<span role="alert" className="text-xs text-error">
									{saveError}
								</span>
							)}
						</div>
					</div>
 
					{/* Touch history */}
					<div>
						<p className="text-foreground-muted font-medium mb-2">
							Touch history
						</p>
						{isLoading ? (
							<div className="h-5 bg-background-muted rounded animate-pulse" />
						) : touches.length === 0 ? (
							<p className="text-xs text-foreground-muted">
								No touches recorded.
							</p>
						) : (
							<ol className="space-y-1" aria-label="Touch history">
								{touches.map((t) => (
									<li
										key={t.id}
										className="text-xs text-foreground-default flex flex-wrap gap-x-3"
									>
										<span className="text-foreground-muted whitespace-nowrap">
											{ist(t.at)}
										</span>
										<span>{entryLabel(t.entryType)}</span>
										<span>{t.channel ?? "—"}</span>
										{t.utmSource && (
											<span>
												{[t.utmSource, t.utmMedium, t.utmCampaign]
													.filter(Boolean)
													.join(" / ")}
											</span>
										)}
										{t.ref && <span className="font-mono">{t.ref}</span>}
										{t.consentState && (
											<span className="text-foreground-muted">
												consent: {t.consentState}
												{t.consentVersion ? ` (${t.consentVersion})` : ""}
											</span>
										)}
									</li>
								))}
							</ol>
						)}
					</div>
				</div>
			</TableCell>
		</TableRow>
	);
}
 
// ─── Table row ───────────────────────────────────────────────────────────────
 
function LeadRow({ lead }: { lead: LandingLead }) {
	const [expanded, setExpanded] = useState(false);
 
	return (
		<>
			<TableRow
				className="cursor-pointer"
				onClick={() => setExpanded((v) => !v)}
			>
				<TableCell className="text-xs text-foreground-muted whitespace-nowrap">
					{ist(lead.dateCreated)}
				</TableCell>
				<TableCell className="text-sm text-foreground-default">
					{lead.name}
				</TableCell>
				<TableCell className="text-sm whitespace-nowrap">
					{lead.phone ? (
						<span className="inline-flex items-center gap-2">
							<a
								href={telUrl(lead.phone)}
								onClick={(e) => e.stopPropagation()}
								className="inline-flex items-center gap-1 text-primary-600 hover:underline tabular-nums"
							>
								<Phone className="h-3.5 w-3.5" aria-hidden="true" />
								{lead.phone}
							</a>
							<a
								href={whatsappUrl(lead.phone)}
								target="_blank"
								rel="noopener noreferrer"
								onClick={(e) => e.stopPropagation()}
								aria-label={`WhatsApp ${lead.name}`}
								className="text-whatsapp-green hover:opacity-80"
							>
								<MessageCircle className="h-4 w-4" aria-hidden="true" />
							</a>
						</span>
					) : (
						<span className="text-foreground-muted">{lead.email ?? "—"}</span>
					)}
				</TableCell>
				<TableCell className="text-sm text-foreground-default">
					{lead.city}
				</TableCell>
				<TableCell className="text-sm text-foreground-default whitespace-nowrap">
					{entryLabel(lead.entryType)}
				</TableCell>
				<TableCell className="text-xs text-foreground-default">
					{lead.utmSource ? (
						<span>
							{lead.utmSource}
							<span className="text-foreground-muted">
								{" / "}
								{lead.utmMedium ?? "—"}
								{" / "}
								{lead.utmCampaign ?? "—"}
							</span>
						</span>
					) : (
						<span className="text-foreground-muted">—</span>
					)}
				</TableCell>
				<TableCell className="text-xs text-foreground-default">
					{lead.priceTestArm ?? "—"}
				</TableCell>
				<TableCell className="text-xs text-foreground-default">
					{lead.qualified ?? "—"}
				</TableCell>
				<TableCell>
					<LeadStatusBadge status={lead.status} />
				</TableCell>
				<TableCell>
					{/* The keyboard / screen-reader way in; the row click is a
					    mouse shortcut to the same toggle. */}
					<button
						type="button"
						aria-expanded={expanded}
						aria-label={`${expanded ? "Hide" : "Show"} details for ${lead.name}`}
						onClick={(e) => {
							e.stopPropagation();
							setExpanded((v) => !v);
						}}
						className="rounded p-1 text-foreground-subtle hover:bg-background-muted focus:outline-none focus:ring-2 focus:ring-primary-500"
					>
						{expanded ? (
							<ChevronDown className="h-4 w-4" aria-hidden="true" />
						) : (
							<ChevronRight className="h-4 w-4" aria-hidden="true" />
						)}
					</button>
				</TableCell>
			</TableRow>
			{expanded && (
				<RowDetail key={`${lead.id}-${lead.lastUpdated ?? ""}`} lead={lead} />
			)}
		</>
	);
}
 
// ─── Skeleton rows ───────────────────────────────────────────────────────────
 
function SkeletonRows() {
	return (
		<>
			{[1, 2, 3, 4, 5, 6, 7, 8].map((i) => (
				<TableRow key={i}>
					<TableCell colSpan={COLUMNS}>
						<div className="h-5 bg-background-muted rounded animate-pulse" />
					</TableCell>
				</TableRow>
			))}
		</>
	);
}
 
// ─── Main page ───────────────────────────────────────────────────────────────
 
export function AdminWebLeadsPage() {
	const [search, setSearch] = useState("");
	const [status, setStatus] = useState<LeadStatus | "">("");
	const [entryType, setEntryType] = useState<LeadEntryType | "">("");
	const [utmSource, setUtmSource] = useState("");
	const [from, setFrom] = useState("");
	const [to, setTo] = useState("");
	const [qualifiedOpen, setQualifiedOpen] = useState(false);
	const [page, setPage] = useState(1);
 
	const q = useDebouncedValue(search.trim());
	const utm = useDebouncedValue(utmSource.trim());
 
	// Everything but paging: the export takes the same filter as the table.
	const filter: LeadFilters = {
		q: q || undefined,
		status: status || undefined,
		entryType: entryType || undefined,
		utmSource: utm || undefined,
		from: from || undefined,
		to: to || undefined,
		...(qualifiedOpen ? { qualified: "yes" as const, open: true } : {}),
	};
	const { data, isLoading, error } = useAdminLandingLeads({
		...filter,
		page,
		limit: PAGE_SIZE,
	});
 
	const items: LandingLead[] = data?.data ?? [];
	const total = data?.meta?.total ?? 0;
	const totalPages = data?.meta?.totalPages ?? 1;
 
	// A save can shrink the filtered list under the current page (e.g. the
	// last lead on page 2 marked contacted while filtering "new"). Step back
	// rather than strand the admin on an empty page with no pager.
	useEffect(() => {
		if (!isLoading && page > 1 && page > totalPages) {
			setPage(Math.max(1, totalPages));
		}
	}, [isLoading, page, totalPages]);
	const filtered =
		search || status || entryType || utmSource || from || to || qualifiedOpen;
 
	// Any filter change goes back to page 1.
	function filterSetter<T>(set: (v: T) => void) {
		return (v: T) => {
			set(v);
			setPage(1);
		};
	}
 
	function clearFilters() {
		setSearch("");
		setStatus("");
		setEntryType("");
		setUtmSource("");
		setFrom("");
		setTo("");
		setQualifiedOpen(false);
		setPage(1);
	}
 
	return (
		<div className="space-y-6">
			<AdminPageHead
				title="Web leads"
				description="Everyone who contacted us, from any form, the calculator or WhatsApp. One row per phone number."
				actions={
					<>
						{isLoading && (
							<span className="text-xs font-semibold uppercase tracking-wider text-foreground-muted">
								Loading...
							</span>
						)}
						<Button asChild variant="outline">
							<a href={adminApi.landingLeadsExportUrl(filter)} download>
								<Download className="h-4 w-4" aria-hidden="true" />
								Export CSV
							</a>
						</Button>
					</>
				}
			/>
 
			{/* A filter strip is a toolbar, not a boxed card. */}
			<AdminToolbar aria-label="Lead filters" className="space-y-3">
				<div className="grid w-full grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-4">
					<Input
						aria-label="Search by name or phone"
						placeholder="Search name or phone"
						value={search}
						onChange={(e) => filterSetter(setSearch)(e.target.value)}
					/>
					<Select
						aria-label="Filter by status"
						value={status}
						onChange={(e) =>
							filterSetter(setStatus)(e.target.value as LeadStatus | "")
						}
						className={selectClass}
					>
						<option value="">All statuses</option>
						{STATUSES.map((s) => (
							<option key={s} value={s}>
								{s}
							</option>
						))}
					</Select>
					<Select
						aria-label="Filter by entry type"
						value={entryType}
						onChange={(e) =>
							filterSetter(setEntryType)(e.target.value as LeadEntryType | "")
						}
						className={selectClass}
					>
						<option value="">All entry types</option>
						{ENTRY_TYPE_FILTERS.map((value) => (
							<option key={value} value={value}>
								{ENTRY_TYPE_LABELS[value]}
							</option>
						))}
					</Select>
					<Input
						aria-label="Filter by UTM source"
						placeholder="UTM source, e.g. meta"
						value={utmSource}
						onChange={(e) => filterSetter(setUtmSource)(e.target.value)}
					/>
				</div>
				<div className="flex w-full flex-col gap-3 sm:flex-row sm:items-center">
					<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-foreground-muted">
						<span aria-hidden="true">From</span>
						<Input
							type="date"
							aria-label="Created from"
							value={from}
							// An inverted range just reads "No leads found", which
							// looks like no leads rather than a mistake (#1085 QA).
							max={to || undefined}
							onChange={(e) => filterSetter(setFrom)(e.target.value)}
						/>
					</div>
					<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-foreground-muted">
						<span aria-hidden="true">To</span>
						<Input
							type="date"
							aria-label="Created to"
							value={to}
							min={from || undefined}
							onChange={(e) => filterSetter(setTo)(e.target.value)}
						/>
					</div>
					<Button
						variant={qualifiedOpen ? "default" : "outline"}
						aria-pressed={qualifiedOpen}
						onClick={() => filterSetter(setQualifiedOpen)(!qualifiedOpen)}
					>
						Qualified and open
					</Button>
					{filtered && (
						<Button variant="ghost" onClick={clearFilters}>
							Clear
						</Button>
					)}
				</div>
			</AdminToolbar>
 
			<section className="space-y-2">
				<AdminBand title="Leads" count={isLoading ? undefined : total} quiet />
 
				{error ? (
					<Alert variant="error">
						Failed to load leads. Please refresh the page.
					</Alert>
				) : (
					<Card className="overflow-hidden">
						<Table density="dense">
							<TableCaption>
								Homeowner leads from the marketplace, newest first.
							</TableCaption>
							<TableHeader>
								<TableRow>
									{[
										"Created",
										"Name",
										"Phone",
										"City",
										"Entry",
										"UTM source / medium / campaign",
										"Price test",
										"Qualified",
										"Status",
									].map((heading) => (
										<TableHead key={heading}>{heading}</TableHead>
									))}
									<TableHead className="w-8" />
								</TableRow>
							</TableHeader>
							<TableBody>
								{isLoading ? (
									<SkeletonRows />
								) : items.length === 0 ? (
									<TableRow>
										<TableCell colSpan={COLUMNS}>
											<EmptyState
												icon={Inbox}
												title="No leads found"
												description="Try adjusting your filters or check back later."
											/>
										</TableCell>
									</TableRow>
								) : (
									items.map((lead) => <LeadRow key={lead.id} lead={lead} />)
								)}
							</TableBody>
						</Table>
 
						{/* Pagination — the primitive owns the status line and the pager. */}
						{!isLoading && total > PAGE_SIZE && (
							<Pagination
								className="border-t border-border-default px-4 py-3"
								density="dense"
								label="Lead store pages"
								page={page}
								totalPages={totalPages}
								total={total}
								onPageChange={setPage}
							/>
						)}
					</Card>
				)}
			</section>
		</div>
	);
}