All files / src/components/crm LeadOverview.tsx

100% Statements 73/73
98.38% Branches 61/62
100% Functions 33/33
100% Lines 69/69

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                      4x                   4x                 4x 28x     4x 24x                     157x 157x 157x 157x 157x   157x 9x     9x         157x   7x   7x 7x       157x   2x           157x       157x 11x 11x     157x   5x 5x         157x 2x 2x     157x                                 4x           2x 2x         1099x                                   2x           1x 1x         942x                         5x             2x   2x 2x           1x                                             2x                                                                                         7x 7x                                         2x 2x 2x                 1x                                                                           450x                                                                           166x 166x   166x 8x 8x     166x 3x 3x 2x   3x     166x 2x 2x     166x                 3x   3x 3x                                                                                      
import { useState, useCallback } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Pencil, Check, X, IndianRupee, Trophy, FileText } from "lucide-react";
import { crmApi } from "../../lib/api";
import type { Lead, UpdateLeadInput } from "../../lib/api/pro/crm";
import { queryKeys } from "../../lib/query-keys";
import { formatPaise, parseCurrencyInput } from "../../lib/currency-utils";
import { CharCountTextarea } from "../ui/char-count-textarea";
 
// ─── Constants ───────────────────────────────────────────────────────────────
 
const PROJECT_TYPE_LABELS: Record<string, string> = {
	modular_kitchen: "Modular Kitchen",
	full_interior: "Full Interior",
	wardrobe: "Wardrobe",
	tv_unit: "TV Unit",
	pooja_unit: "Pooja Unit",
	kitchen_renovation: "Kitchen Renovation",
	other: "Other",
};
 
const BUDGET_RANGE_LABELS: Record<string, string> = {
	under_1l: "Under ₹1 Lakh",
	"1_3l": "₹1-3 Lakhs",
	"3_5l": "₹3-5 Lakhs",
	"5_10l": "₹5-10 Lakhs",
	"10_20l": "₹10-20 Lakhs",
	above_20l: "Above ₹20 Lakhs",
};
 
const PROJECT_TYPES = Object.entries(PROJECT_TYPE_LABELS).map(
	([value, label]) => ({ value, label }),
);
 
const BUDGET_RANGES = Object.entries(BUDGET_RANGE_LABELS).map(
	([value, label]) => ({ value, label }),
);
 
// ─── Component ───────────────────────────────────────────────────────────────
 
type LeadOverviewProps = {
	lead: Lead;
	proId: string;
};
 
export function LeadOverview({ lead, proId }: LeadOverviewProps) {
	const queryClient = useQueryClient();
	const [editing, setEditing] = useState<string | null>(null);
	const [editValue, setEditValue] = useState("");
	const [isEditingRequirement, setIsEditingRequirement] = useState(false);
	const [requirementValue, setRequirementValue] = useState("");
 
	const invalidate = useCallback(() => {
		queryClient.invalidateQueries({
			queryKey: queryKeys.crm.lead(proId, String(lead.id)),
		});
		queryClient.invalidateQueries({
			queryKey: queryKeys.crm.kanban(proId),
		});
	}, [queryClient, proId, lead.id]);
 
	const updateMutation = useMutation({
		mutationFn: async (data: UpdateLeadInput) =>
			crmApi.updateLead(proId, lead.id, data),
		onSuccess: () => {
			invalidate();
			setEditing(null);
		},
	});
 
	const quoteValueMutation = useMutation({
		mutationFn: async (valuePaise: number) =>
			crmApi.updateQuoteValue(proId, lead.id, valuePaise),
		onSuccess: invalidate,
	});
 
	// Calculate delta if both values exist
	const delta =
		lead.quoteValuePaise != null && lead.orderValuePaise != null
			? lead.orderValuePaise - lead.quoteValuePaise
			: null;
 
	const startEdit = useCallback((field: string, currentValue: string) => {
		setEditing(field);
		setEditValue(currentValue);
	}, []);
 
	const saveEdit = useCallback(
		(field: string) => {
			const value = editValue.trim();
			updateMutation.mutate({ [field]: value || undefined } as UpdateLeadInput);
		},
		[editValue, updateMutation],
	);
 
	const cancelEdit = useCallback(() => {
		setEditing(null);
		setEditValue("");
	}, []);
 
	return (
		<div className="rounded-lg border border-border-default bg-background-elevated p-5 overflow-hidden">
			<h3 className="text-sm font-semibold text-foreground-default mb-4">
				Project Details
			</h3>
			<dl className="space-y-3">
				{/* Project Type */}
				<EditableField
					label="Project Type"
					value={lead.projectType}
					displayValue={
						lead.projectType
							? PROJECT_TYPE_LABELS[lead.projectType] || lead.projectType
							: null
					}
					isEditing={editing === "projectType"}
					onStartEdit={() =>
						startEdit("projectType", lead.projectType || "")
					}
					onCancel={cancelEdit}
				>
					<select
						value={editValue}
						onChange={(e) => setEditValue(e.target.value)}
						onBlur={() => saveEdit("projectType")}
						className="h-8 px-2 text-sm rounded border border-border-default bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500"
					>
						<option value="">None</option>
						{PROJECT_TYPES.map((t) => (
							<option key={t.value} value={t.value}>
								{t.label}
							</option>
						))}
					</select>
				</EditableField>
 
				{/* Budget Range */}
				<EditableField
					label="Budget Range"
					value={lead.budgetRange}
					displayValue={
						lead.budgetRange
							? BUDGET_RANGE_LABELS[lead.budgetRange] || lead.budgetRange
							: null
					}
					isEditing={editing === "budgetRange"}
					onStartEdit={() =>
						startEdit("budgetRange", lead.budgetRange || "")
					}
					onCancel={cancelEdit}
				>
					<select
						value={editValue}
						onChange={(e) => setEditValue(e.target.value)}
						onBlur={() => saveEdit("budgetRange")}
						className="h-8 px-2 text-sm rounded border border-border-default bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500"
					>
						<option value="">None</option>
						{BUDGET_RANGES.map((b) => (
							<option key={b.value} value={b.value}>
								{b.label}
							</option>
						))}
					</select>
				</EditableField>
 
				{/* Location */}
				<EditableField
					label="Location"
					value={lead.location}
					displayValue={lead.location}
					isEditing={editing === "location"}
					onStartEdit={() => startEdit("location", lead.location || "")}
					onCancel={cancelEdit}
				>
					<div className="flex items-center gap-1">
						<input
							type="text"
							value={editValue}
							onChange={(e) => setEditValue(e.target.value)}
							onKeyDown={(e) => {
								if (e.key === "Enter") saveEdit("location");
								if (e.key === "Escape") cancelEdit();
							}}
							className="h-8 px-2 text-sm rounded border border-border-default bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500 flex-1"
						/>
						<button
							type="button"
							onClick={() => saveEdit("location")}
							className="p-1 text-success hover:text-success/80"
						>
							<Check className="h-3.5 w-3.5" />
						</button>
						<button
							type="button"
							onClick={cancelEdit}
							className="p-1 text-foreground-subtle hover:text-foreground-muted"
						>
							<X className="h-3.5 w-3.5" />
						</button>
					</div>
				</EditableField>
			</dl>
 
			{/* Financials */}
			<div className="mt-4 pt-4 border-t border-border-default space-y-3">
				<h4 className="text-xs font-semibold text-foreground-subtle uppercase tracking-wider">
					Financials
				</h4>
				<QuoteValueField
					valuePaise={lead.quoteValuePaise}
					onSave={(paise) => quoteValueMutation.mutate(paise)}
					isSaving={quoteValueMutation.isPending}
				/>
				<div className="flex items-center justify-between">
					<span className="text-sm text-foreground-muted">Order Value</span>
					{lead.orderValuePaise != null ? (
						<span className="text-sm font-semibold text-foreground-default">
							₹{formatPaise(lead.orderValuePaise)}
						</span>
					) : (
						<span className="text-sm text-foreground-subtle italic flex items-center gap-1">
							<Trophy className="h-3 w-3" />
							Set when marking Won
						</span>
					)}
				</div>
				{delta !== null && (
					<div className="flex items-center justify-between pt-2 border-t border-border-default">
						<span className="text-sm text-foreground-muted">Difference</span>
						<span
							className={`text-sm font-medium ${
								delta > 0
									? "text-success"
									: delta < 0
										? "text-error"
										: "text-foreground-muted"
							}`}
						>
							{delta > 0 ? "+" : ""}₹{formatPaise(Math.abs(delta))}
						</span>
					</div>
				)}
			</div>
 
			{/* Requirement */}
			<div className="mt-4 pt-4 border-t border-border-default">
				<div className="flex items-center justify-between mb-2">
					<h4 className="text-xs font-semibold text-foreground-subtle uppercase tracking-wider flex items-center gap-1.5">
						<FileText className="h-3.5 w-3.5" />
						Requirement
					</h4>
					{!isEditingRequirement && (
						<button
							type="button"
							onClick={() => {
								setRequirementValue(lead.requirement || "");
								setIsEditingRequirement(true);
							}}
							className="p-1 text-foreground-subtle hover:text-foreground-muted transition-colors"
						>
							<Pencil className="h-3.5 w-3.5" />
						</button>
					)}
				</div>
				{isEditingRequirement ? (
					<div className="space-y-2">
						<CharCountTextarea
							value={requirementValue}
							onChange={setRequirementValue}
							maxLength={2000}
							rows={6}
							placeholder="Describe the customer's requirements..."
						/>
						<div className="flex justify-end gap-1">
							<button
								type="button"
								onClick={() => {
									const value = requirementValue.trim();
									updateMutation.mutate({ requirement: value || undefined } as UpdateLeadInput);
									setIsEditingRequirement(false);
								}}
								disabled={updateMutation.isPending}
								className="p-1 text-success hover:text-success/80"
							>
								<Check className="h-4 w-4" />
							</button>
							<button
								type="button"
								onClick={() => setIsEditingRequirement(false)}
								className="p-1 text-foreground-subtle hover:text-foreground-muted"
							>
								<X className="h-4 w-4" />
							</button>
						</div>
					</div>
				) : (
					<p className="text-sm text-foreground-default whitespace-pre-wrap break-words">
						{lead.requirement || (
							<span className="text-foreground-subtle italic">Not set</span>
						)}
					</p>
				)}
			</div>
		</div>
	);
}
 
// ─── Reusable Editable Field ─────────────────────────────────────────────────
 
type EditableFieldProps = {
	label: string;
	value: string | null;
	displayValue: string | null;
	isEditing: boolean;
	onStartEdit: () => void;
	onCancel: () => void;
	children: React.ReactNode;
};
 
function EditableField({
	label,
	displayValue,
	isEditing,
	onStartEdit,
	children,
}: EditableFieldProps) {
	return (
		<div className="flex items-start justify-between gap-2">
			<dt className="text-sm text-foreground-muted w-28 flex-shrink-0 pt-1">
				{label}
			</dt>
			<dd className="flex-1 min-w-0">
				{isEditing ? (
					children
				) : (
					<button
						type="button"
						onClick={onStartEdit}
						className="group flex items-center gap-1 text-sm text-left w-full"
					>
						<span className="text-foreground-default truncate">
							{displayValue || (
								<span className="text-foreground-subtle italic">
									Not set
								</span>
							)}
						</span>
						<Pencil className="h-3 w-3 text-foreground-subtle opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0" />
					</button>
				)}
			</dd>
		</div>
	);
}
 
// ─── Inline editable quote value ────────────────────────────────────────────
 
type QuoteValueFieldProps = {
	valuePaise: number | null;
	onSave: (paise: number) => void;
	isSaving: boolean;
};
 
function QuoteValueField({ valuePaise, onSave, isSaving }: QuoteValueFieldProps) {
	const [isEditing, setIsEditing] = useState(false);
	const [input, setInput] = useState("");
 
	const startEdit = useCallback(() => {
		setIsEditing(true);
		setInput(valuePaise != null ? String(Math.round(valuePaise / 100)) : "");
	}, [valuePaise]);
 
	const handleSave = useCallback(() => {
		const paise = parseCurrencyInput(input);
		if (paise !== null && paise >= 0) {
			onSave(paise);
		}
		setIsEditing(false);
	}, [input, onSave]);
 
	const handleCancel = useCallback(() => {
		setIsEditing(false);
		setInput("");
	}, []);
 
	return (
		<div className="flex items-center justify-between">
			<span className="text-sm text-foreground-muted">Quote Value</span>
			{isEditing ? (
				<div className="flex items-center gap-1">
					<span className="text-sm text-foreground-muted">₹</span>
					<input
						type="text"
						value={input}
						onChange={(e) => setInput(e.target.value)}
						onKeyDown={(e) => {
							if (e.key === "Enter") handleSave();
							if (e.key === "Escape") handleCancel();
						}}
						placeholder="e.g., 4.2L or 420000"
						className="h-7 w-32 px-2 text-sm rounded border border-border-default bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500"
					/>
					<button
						type="button"
						onClick={handleSave}
						className="p-0.5 text-success hover:text-success/80"
					>
						<Check className="h-3.5 w-3.5" />
					</button>
					<button
						type="button"
						onClick={handleCancel}
						className="p-0.5 text-foreground-subtle hover:text-foreground-muted"
					>
						<X className="h-3.5 w-3.5" />
					</button>
				</div>
			) : (
				<button
					type="button"
					onClick={startEdit}
					disabled={isSaving}
					className="group flex items-center gap-1 text-sm"
				>
					{valuePaise != null ? (
						<span className="font-semibold text-foreground-default">
							₹{formatPaise(valuePaise)}
						</span>
					) : (
						<span className="text-foreground-subtle italic flex items-center gap-1">
							<IndianRupee className="h-3 w-3" />
							Add quote value
						</span>
					)}
					<Pencil className="h-3 w-3 text-foreground-subtle opacity-0 group-hover:opacity-100 transition-opacity" />
				</button>
			)}
		</div>
	);
}