All files / src/components/crm LeadHeader.tsx

96.96% Statements 128/132
86.77% Branches 105/121
100% Functions 34/34
99.12% Lines 113/114

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                                                        5x 5x 5x 5x 3x 3x 2x                                                             377x 377x 377x     377x 377x 377x 377x 144x       377x 377x 377x 377x   377x 390x 377x   377x 16x     16x     16x         377x   8x       377x   6x   6x 6x 6x 6x 6x       377x   34x 11x   10x       9x             1x           377x 5x 5x 5x 1x 1x   5x 2x 2x   5x     377x 2x 2x 2x 2x     377x   2x           377x 2x 2x 2x   2x     377x 14x 14x     377x   8x 8x   8x   4x 4x 1x 1x     3x 4x 3x   3x 3x 3x   4x 1x   3x 8x 3x   3x 3x     377x   377x 3x 3x 3x     3x     377x                                                   35x     35x 35x 1x 1x               5x                                                           11x   1468x                                 2x                                                                       6x 4x                             4x 2x                             4x 2x                                                                                                                                                                                       1113x               69x     71x 71x                                                
import { useState, useCallback, useRef, useEffect } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
import { notify } from "../../lib/notify";
import {
	ArrowLeft,
	Phone,
	Mail,
	MapPin,
	Archive,
	ArchiveRestore,
} from "lucide-react";
import { cn } from "../../lib/utils";
import { crmApi } from "../../lib/api";
import type { Lead, PipelineStage, LeadSource, UpdateLeadInput } from "../../lib/api/pro/crm";
import { queryKeys } from "../../lib/query-keys";
import { LOSS_REASON_LABELS } from "../../lib/crm-constants";
import { parseCurrencyInput } from "../../lib/currency-utils";
import { StageChangeDialogs, type PendingDrop } from "./StageChangeDialogs";
import type { ChangeStageInput } from "../../lib/api/pro/crm";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Select } from "../ui/select";
import { StatusBadge } from "../ui/status-badge";
 
// ─── Helpers ─────────────────────────────────────────────────────────────────
 
function formatRelativeTime(dateStr: string): string {
	const diff = Date.now() - new Date(dateStr).getTime();
	const hours = diff / (1000 * 60 * 60);
	Iif (hours < 1) return "just now";
	if (hours < 24) return `${Math.floor(hours)}h ago`;
	const days = Math.floor(hours / 24);
	if (days === 1) return "yesterday";
	Eif (days < 30) return `${days}d ago`;
	return new Date(dateStr).toLocaleDateString("en-IN", {
		day: "numeric",
		month: "short",
	});
}
 
// ─── Component ───────────────────────────────────────────────────────────────
 
type LeadHeaderProps = {
	lead: Lead;
	proId: string;
	stages: PipelineStage[];
	sources: LeadSource[];
	/** Whether this member may edit the lead's own fields. False for staff. */
	canEditLead?: boolean;
	/** Whether this member may move the lead between stages. False for staff. */
	canChangeStage?: boolean;
	/** Whether this member may archive or unarchive the lead. False for staff. */
	canManageLeads?: boolean;
};
 
export function LeadHeader({
	lead,
	proId,
	stages,
	sources,
	canEditLead = true,
	canChangeStage = true,
	canManageLeads = true,
}: LeadHeaderProps) {
	const queryClient = useQueryClient();
	const [isEditingName, setIsEditingName] = useState(false);
	const [editName, setEditName] = useState(lead.customerName);
 
	// Inline edit state for contact fields
	const [editingField, setEditingField] = useState<"phone" | "email" | "location" | null>(null);
	const [editFieldValue, setEditFieldValue] = useState("");
	const fieldInputRef = useRef<HTMLInputElement>(null);
	useEffect(() => {
		if (editingField) fieldInputRef.current?.focus();
	}, [editingField]);
 
	// Terminal stage dialog state
	const [pendingDrop, setPendingDrop] = useState<PendingDrop | null>(null);
	const [dialogOrderValue, setDialogOrderValue] = useState("");
	const [dialogLossReasonCategory, setDialogLossReasonCategory] = useState("");
	const [dialogLossReason, setDialogLossReason] = useState("");
 
	const currentSource = sources.find((s) => s.id === lead.leadSourceId);
	const currentStage = stages.find((s) => s.id === lead.currentStageId);
	const isLostStage = currentStage?.stageType === "system_terminal_lost";
 
	const invalidateLeadQueries = useCallback(() => {
		queryClient.invalidateQueries({
			queryKey: queryKeys.crm.lead(proId, String(lead.id)),
		});
		queryClient.invalidateQueries({
			queryKey: queryKeys.crm.kanban(proId),
		});
		queryClient.invalidateQueries({
			queryKey: queryKeys.crm.activities(proId, String(lead.id)),
		});
	}, [queryClient, proId, lead.id]);
 
	const updateMutation = useMutation({
		mutationFn: async (data: UpdateLeadInput) =>
			crmApi.updateLead(proId, lead.id, data),
		onSuccess: invalidateLeadQueries,
	});
 
	const changeStageMutation = useMutation({
		mutationFn: async (data: ChangeStageInput) =>
			crmApi.changeStage(proId, lead.id, data),
		onSuccess: () => {
			invalidateLeadQueries();
			setPendingDrop(null);
			setDialogOrderValue("");
			setDialogLossReasonCategory("");
			setDialogLossReason("");
		},
	});
 
	const handleStageChange = useCallback(
		(stageId: number) => {
			const stage = stages.find((s) => s.id === stageId);
			if (!stage || stageId === lead.currentStageId) return;
 
			if (
				stage.stageType === "system_terminal_won" ||
				stage.stageType === "system_terminal_lost"
			) {
				setPendingDrop({
					leadId: lead.id,
					stageId: stage.id,
					stageName: stage.name,
					stageType: stage.stageType,
				});
			} else {
				changeStageMutation.mutate({ stageId });
			}
		},
		[stages, lead.currentStageId, lead.id, changeStageMutation],
	);
 
	const handleDialogConfirm = useCallback(() => {
		Iif (!pendingDrop) return;
		const data: ChangeStageInput = { stageId: pendingDrop.stageId };
		if (pendingDrop.stageType === "system_terminal_won" && dialogOrderValue.trim()) {
			const paise = parseCurrencyInput(dialogOrderValue);
			Eif (paise !== null && paise >= 0) data.orderValuePaise = paise;
		}
		if (pendingDrop.stageType === "system_terminal_lost") {
			if (dialogLossReasonCategory) data.lossReasonCategory = dialogLossReasonCategory;
			if (dialogLossReason.trim()) data.lossReason = dialogLossReason.trim();
		}
		changeStageMutation.mutate(data);
	}, [pendingDrop, dialogOrderValue, dialogLossReasonCategory, dialogLossReason, changeStageMutation]);
 
	const handleDialogCancel = useCallback(() => {
		setPendingDrop(null);
		setDialogOrderValue("");
		setDialogLossReasonCategory("");
		setDialogLossReason("");
	}, []);
 
	const archiveMutation = useMutation({
		mutationFn: async () =>
			lead.isArchived
				? crmApi.unarchiveLead(proId, lead.id)
				: crmApi.archiveLead(proId, lead.id),
		onSuccess: invalidateLeadQueries,
	});
 
	const handleNameSave = useCallback(() => {
		const trimmed = editName.trim();
		Eif (trimmed && trimmed !== lead.customerName) {
			updateMutation.mutate({ customerName: trimmed });
		}
		setIsEditingName(false);
	}, [editName, lead.customerName, updateMutation]);
 
	const startFieldEdit = useCallback((field: "phone" | "email" | "location") => {
		setEditingField(field);
		setEditFieldValue(lead[field] ?? "");
	}, [lead]);
 
	const handleFieldSave = useCallback((field: "phone" | "email" | "location") => {
		// Skip save if the edit was cancelled (e.g. Escape key)
		Iif (cancellingRef.current) return;
		const trimmed = editFieldValue.trim();
		// Validation
		if (field === "phone" && trimmed) {
			// Strip common prefixes (+91, 91) and formatting (spaces, dashes, parens)
			const cleaned = trimmed.replace(/[\s\-()]/g, "").replace(/^\+?91/, "");
			if (!/^\d{10}$/.test(cleaned)) {
				notify.error("Please enter a valid 10-digit phone number");
				return; // Don't save invalid phone
			}
			// Save the cleaned 10-digit number
			const currentValue = lead[field] ?? "";
			if (cleaned !== currentValue) {
				updateMutation.mutate({ [field]: cleaned } as UpdateLeadInput);
			}
			setEditingField(null);
			setEditFieldValue("");
			return;
		}
		if (field === "email" && trimmed && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmed)) {
			return; // Don't save invalid email
		}
		const currentValue = lead[field] ?? "";
		if (trimmed !== currentValue) {
			updateMutation.mutate({ [field]: trimmed || undefined } as UpdateLeadInput);
		}
		setEditingField(null);
		setEditFieldValue("");
	}, [editFieldValue, lead, updateMutation]);
 
	const cancellingRef = useRef(false);
 
	const cancelFieldEdit = useCallback(() => {
		cancellingRef.current = true;
		setEditingField(null);
		setEditFieldValue("");
		// Reset after a tick so the onBlur handler (which fires synchronously
		// when Escape unmounts the input) is properly ignored
		setTimeout(() => { cancellingRef.current = false; }, 0);
	}, []);
 
	return (
		<div className="space-y-4">
			{/* Back link — hidden on mobile (MobileFullPage provides back) */}
			<Link
				to="/leads"
				className="hidden sm:inline-flex items-center gap-1 text-sm text-foreground-muted hover:text-foreground-default transition-colors"
			>
				<ArrowLeft className="h-4 w-4" aria-hidden="true" />
				Back to leads
			</Link>
 
			{/* Name + Stage + Archive row — name hidden on mobile (shown in MobileFullPage header) */}
			<div className="hidden gap-3 sm:flex sm:flex-row sm:items-center sm:justify-between">
				<div className="flex items-center gap-3">
					{/*
					 * The four-colour contact-recency dot is gone. Its only label
					 * was a `title`, so it signalled state in colour alone — and one
					 * of its four colours was red, which the Index Red Rule reserves
					 * for marking the current item, never for state. The same fact
					 * is printed as "Last contact …" in the row below, in words.
					 */}
					{isEditingName ? (
						<Input
							type="text"
							aria-label="Lead name"
							value={editName}
							onChange={(e) => setEditName(e.target.value)}
							onBlur={handleNameSave}
							onKeyDown={(e) => {
								if (e.key === "Enter") handleNameSave();
								if (e.key === "Escape") {
									setEditName(lead.customerName);
									setIsEditingName(false);
								}
							}}
							className="text-xl font-semibold"
						/>
					) : canEditLead ? (
						<button
							type="button"
							onClick={() => setIsEditingName(true)}
							className="text-left text-xl font-semibold text-foreground-default underline-offset-4 transition-colors hover:underline"
							title="Click to edit"
						>
							{lead.customerName}
						</button>
					) : (
						<h2 className="text-xl font-semibold text-foreground-default">
							{lead.customerName}
						</h2>
					)}
 
					{/* A status is a printed code, never a pill. */}
					{lead.isArchived && (
						<StatusBadge status="Archived" variant="default" />
					)}
				</div>
 
				{/* Stage + archive — hidden on mobile (stage is in MobileFullPage header) */}
				<div className="hidden items-center gap-2 sm:flex">
					{/*
					 * Staff get the stage as a printed fact, not a control: the API
					 * refuses `PATCH …/stage` for them, and offering a select the
					 * server will reject is worse than not offering one.
					 */}
					{canChangeStage ? (
						<Select
							tier="dense"
							aria-label="Pipeline stage"
							value={lead.currentStageId}
							onChange={(e) => handleStageChange(Number(e.target.value))}
							className="w-auto"
							options={stages.map((stage) => ({
								value: String(stage.id),
								label: stage.name,
							}))}
						/>
					) : (
						currentStage && (
							<span className="text-xs font-semibold uppercase tracking-wider text-foreground-muted">
								{currentStage.name}
							</span>
						)
					)}
 
					{canManageLeads && (
						<Button
							variant="ghost"
							size="sm"
							onClick={() => archiveMutation.mutate()}
							isLoading={archiveMutation.isPending}
							title={lead.isArchived ? "Unarchive lead" : "Archive lead"}
						>
							{lead.isArchived ? (
								<ArchiveRestore className="h-4 w-4" aria-hidden="true" />
							) : (
								<Archive className="h-4 w-4" aria-hidden="true" />
							)}
							<span className="sr-only">
								{lead.isArchived ? "Unarchive lead" : "Archive lead"}
							</span>
						</Button>
					)}
				</div>
			</div>
 
			{/*
			 * Contact info row. The three inline-editable fields share one
			 * sub-component rather than being written out three times — they
			 * were identical bar the icon, the width and the placeholder, and
			 * one of the three always drifted.
			 */}
			<div className="flex flex-wrap items-center gap-4 text-sm">
				<InlineField
					icon={<Phone className="h-4 w-4 text-foreground-subtle" aria-hidden="true" />}
					label="Phone"
					printed={lead.phone}
					placeholder="10-digit phone"
					widthClassName="w-32"
					tabular
					canEdit={canEditLead}
					isEditing={editingField === "phone"}
					value={editFieldValue}
					inputRef={fieldInputRef}
					onChange={setEditFieldValue}
					onStartEdit={() => startFieldEdit("phone")}
					onSave={() => handleFieldSave("phone")}
					onCancel={cancelFieldEdit}
				/>
 
				<InlineField
					icon={<Mail className="h-4 w-4 text-foreground-subtle" aria-hidden="true" />}
					label="Email"
					printed={lead.email || "Add email"}
					placeholder="email@example.com"
					widthClassName="w-52"
					canEdit={canEditLead}
					isEditing={editingField === "email"}
					value={editFieldValue}
					inputRef={fieldInputRef}
					onChange={setEditFieldValue}
					onStartEdit={() => startFieldEdit("email")}
					onSave={() => handleFieldSave("email")}
					onCancel={cancelFieldEdit}
				/>
 
				<InlineField
					icon={<MapPin className="h-4 w-4 text-foreground-subtle" aria-hidden="true" />}
					label="Locality"
					printed={lead.location || "Add location"}
					placeholder="City or area"
					widthClassName="w-44"
					canEdit={canEditLead}
					isEditing={editingField === "location"}
					value={editFieldValue}
					inputRef={fieldInputRef}
					onChange={setEditFieldValue}
					onStartEdit={() => startFieldEdit("location")}
					onSave={() => handleFieldSave("location")}
					onCancel={cancelFieldEdit}
				/>
 
				{/* The source, as a printed code rather than a teal pill. */}
				{currentSource && (
					<span className="text-xs font-semibold uppercase tracking-wider text-foreground-muted">
						{currentSource.name}
					</span>
				)}
 
				{/* The fact the recency dot used to signal in colour alone. */}
				<span className="text-xs tabular-nums text-foreground-subtle">
					{lead.lastContactedAt
						? `Last contact ${formatRelativeTime(lead.lastContactedAt)}${
								lead.lastContactMethod ? ` via ${lead.lastContactMethod}` : ""
							}`
						: "Not contacted yet"}
				</span>
			</div>
 
			{/* Why this lead was lost — a printed code and the note beside it. */}
			{isLostStage && lead.lossReasonCategory && (
				<div className="flex flex-wrap items-center gap-2 rounded-sm bg-error-light px-3 py-2 text-sm">
					<StatusBadge
						status={
							LOSS_REASON_LABELS[lead.lossReasonCategory] ??
							lead.lossReasonCategory
						}
						variant="error"
					/>
					{lead.lossReason && (
						<span className="text-foreground-default">{lead.lossReason}</span>
					)}
				</div>
			)}
 
			{/* Won/Lost dialog for terminal stage changes */}
			<StageChangeDialogs
				pendingDrop={pendingDrop}
				orderValue={dialogOrderValue}
				onOrderValueChange={setDialogOrderValue}
				lossReasonCategory={dialogLossReasonCategory}
				onLossReasonCategoryChange={setDialogLossReasonCategory}
				lossReason={dialogLossReason}
				onLossReasonChange={setDialogLossReason}
				onConfirm={handleDialogConfirm}
				onCancel={handleDialogCancel}
				isPending={changeStageMutation.isPending}
			/>
		</div>
	);
}
 
// ─── One inline-editable contact field ───────────────────────────────────────
 
type InlineFieldProps = {
	icon: React.ReactNode;
	/** The accessible name of the control, e.g. "Phone". */
	label: string;
	/** What is printed when not editing. */
	printed: string;
	placeholder: string;
	widthClassName: string;
	tabular?: boolean;
	/** False prints the value as text, with no affordance to change it. */
	canEdit: boolean;
	isEditing: boolean;
	value: string;
	inputRef: React.RefObject<HTMLInputElement | null>;
	onChange: (value: string) => void;
	onStartEdit: () => void;
	onSave: () => void;
	onCancel: () => void;
};
 
function InlineField({
	icon,
	label,
	printed,
	placeholder,
	widthClassName,
	tabular,
	canEdit,
	isEditing,
	value,
	inputRef,
	onChange,
	onStartEdit,
	onSave,
	onCancel,
}: InlineFieldProps) {
	return (
		<div className="flex items-center gap-1.5 text-foreground-default">
			{icon}
			{isEditing ? (
				<Input
					type="text"
					aria-label={label}
					value={value}
					onChange={(e) => onChange(e.target.value)}
					onBlur={onSave}
					onKeyDown={(e) => {
						if (e.key === "Enter") onSave();
						if (e.key === "Escape") onCancel();
					}}
					ref={inputRef}
					className={cn("h-8", widthClassName, tabular && "tabular-nums")}
					placeholder={placeholder}
				/>
			) : canEdit ? (
				<button
					type="button"
					onClick={onStartEdit}
					className={cn(
						"underline-offset-2 transition-colors hover:underline",
						tabular && "tabular-nums",
					)}
					title={`Click to edit ${label.toLowerCase()}`}
				>
					{printed}
				</button>
			) : (
				<span className={cn(tabular && "tabular-nums")}>{printed}</span>
			)}
		</div>
	);
}