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 | 373x 368x 5x 5x 2x 1x 5x 5x 5x 5x 3x 3x 2x 373x 373x 373x 373x 373x 373x 373x 142x 373x 373x 373x 373x 373x 373x 386x 373x 373x 16x 16x 16x 373x 8x 373x 6x 6x 6x 6x 6x 6x 373x 34x 11x 10x 9x 1x 373x 5x 5x 5x 1x 1x 5x 2x 2x 5x 373x 2x 2x 2x 2x 373x 2x 373x 2x 2x 2x 2x 373x 14x 14x 373x 8x 8x 8x 4x 4x 1x 1x 3x 4x 3x 3x 3x 3x 4x 1x 3x 8x 3x 3x 3x 373x 373x 3x 3x 3x 3x 373x 35x 35x 35x 1x 1x 5x 11x 1460x 2x 29x 1x 29x 29x 6x 29x 30x 30x 4x 11x 12x 12x 4x | 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";
// ─── Helpers ─────────────────────────────────────────────────────────────────
function getContactRecencyInfo(lastContactedAt: string | null) {
if (!lastContactedAt)
return { color: "bg-foreground-subtle", label: "Never contacted" };
const hours =
(Date.now() - new Date(lastContactedAt).getTime()) / (1000 * 60 * 60);
if (hours < 48) return { color: "bg-success", label: "Recently contacted" };
if (hours < 168) return { color: "bg-warning", label: "Contact due" };
return { color: "bg-error", label: "Overdue contact" };
}
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[];
};
export function LeadHeader({
lead,
proId,
stages,
sources,
}: 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 recency = getContactRecencyInfo(lead.lastContactedAt);
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="/crm"
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" />
Back to Pipeline
</Link>
{/* Name + Stage + Archive row — name hidden on mobile (shown in MobileFullPage header) */}
<div className="hidden sm:flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
<div className="flex items-center gap-3">
{/* Contact recency dot */}
<span
className={cn("h-3 w-3 rounded-full flex-shrink-0", recency.color)}
title={recency.label}
/>
{/* Editable name */}
{isEditingName ? (
<input
type="text"
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-bold text-foreground-default bg-transparent border-b-2 border-primary-500 outline-none px-1"
/>
) : (
<button
type="button"
onClick={() => setIsEditingName(true)}
className="text-xl font-bold text-foreground-default hover:text-primary-600 transition-colors text-left"
title="Click to edit"
>
{lead.customerName}
</button>
)}
{/* Archived badge */}
{lead.isArchived && (
<span className="text-xs font-medium text-foreground-subtle bg-background-muted rounded-full px-2 py-0.5">
Archived
</span>
)}
</div>
{/* Stage + archive — hidden on mobile (stage is in MobileFullPage header) */}
<div className="hidden sm:flex items-center gap-2">
{/* Stage selector */}
<select
value={lead.currentStageId}
onChange={(e) =>
handleStageChange(Number(e.target.value))
}
className="h-9 px-3 rounded-md border border-border-default bg-background-elevated text-sm text-foreground-default focus:ring-2 focus:ring-primary-500"
>
{stages.map((s) => (
<option key={s.id} value={s.id}>
{s.name}
</option>
))}
</select>
{/* Archive toggle */}
<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" />
) : (
<Archive className="h-4 w-4" />
)}
</Button>
</div>
</div>
{/* Contact info row */}
<div className="flex flex-wrap items-center gap-4 text-sm">
{/* Phone */}
<div className="flex items-center gap-1.5 text-foreground-default">
<Phone className="h-4 w-4 text-foreground-subtle" />
{editingField === "phone" ? (
<input
type="text"
value={editFieldValue}
onChange={(e) => setEditFieldValue(e.target.value)}
onBlur={() => handleFieldSave("phone")}
onKeyDown={(e) => {
if (e.key === "Enter") handleFieldSave("phone");
if (e.key === "Escape") cancelFieldEdit();
}}
ref={fieldInputRef}
className="bg-transparent border-b-2 border-primary-500 outline-none px-1 text-sm w-28"
placeholder="10-digit phone"
/>
) : (
<button
type="button"
onClick={() => startFieldEdit("phone")}
className="hover:text-primary-600 transition-colors"
title="Click to edit"
>
{lead.phone}
</button>
)}
</div>
{/* Email */}
<div className="flex items-center gap-1.5 text-foreground-muted">
<Mail className="h-4 w-4 text-foreground-subtle" />
{editingField === "email" ? (
<input
type="text"
value={editFieldValue}
onChange={(e) => setEditFieldValue(e.target.value)}
onBlur={() => handleFieldSave("email")}
onKeyDown={(e) => {
if (e.key === "Enter") handleFieldSave("email");
if (e.key === "Escape") cancelFieldEdit();
}}
ref={fieldInputRef}
className="bg-transparent border-b-2 border-primary-500 outline-none px-1 text-sm w-48"
placeholder="email@example.com"
/>
) : (
<button
type="button"
onClick={() => startFieldEdit("email")}
className="hover:text-primary-600 transition-colors"
title="Click to edit"
>
{lead.email || "Add email"}
</button>
)}
</div>
{/* Location */}
<div className="flex items-center gap-1.5 text-foreground-muted">
<MapPin className="h-4 w-4 text-foreground-subtle" />
{editingField === "location" ? (
<input
type="text"
value={editFieldValue}
onChange={(e) => setEditFieldValue(e.target.value)}
onBlur={() => handleFieldSave("location")}
onKeyDown={(e) => {
if (e.key === "Enter") handleFieldSave("location");
if (e.key === "Escape") cancelFieldEdit();
}}
ref={fieldInputRef}
className="bg-transparent border-b-2 border-primary-500 outline-none px-1 text-sm w-40"
placeholder="City or area"
/>
) : (
<button
type="button"
onClick={() => startFieldEdit("location")}
className="hover:text-primary-600 transition-colors"
title="Click to edit"
>
{lead.location || "Add location"}
</button>
)}
</div>
{/* Source badge */}
{currentSource && (
<span className="inline-flex items-center rounded-full bg-primary-100 px-2.5 py-0.5 text-xs font-medium text-primary-700">
{currentSource.name}
</span>
)}
{/* Last contacted */}
{lead.lastContactedAt && (
<span className="text-xs text-foreground-subtle">
Last contact: {formatRelativeTime(lead.lastContactedAt)}
{lead.lastContactMethod && ` via ${lead.lastContactMethod}`}
</span>
)}
</div>
{/* Loss reason banner for lost leads */}
{isLostStage && lead.lossReasonCategory && (
<div className="flex items-center gap-2 text-sm rounded-md bg-error/10 px-3 py-2">
<span className="inline-flex items-center rounded-full bg-error/20 px-2.5 py-0.5 text-xs font-medium text-error">
{LOSS_REASON_LABELS[lead.lossReasonCategory] ?? lead.lossReasonCategory}
</span>
{lead.lossReason && (
<span className="text-foreground-muted">{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>
);
}
|