All files / src/components/crm AddLeadModal.tsx

92.02% Statements 127/138
85.14% Branches 86/101
91.3% Functions 21/23
94.61% Lines 123/130

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                                                      120x 120x     120x 120x 120x 120x 120x 120x 120x 120x 120x     120x 120x 120x 120x 120x 120x 120x     120x 120x     120x         120x 38x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x         120x   8x 8x       8x 8x 8x 4x 2x 2x   2x 2x                 120x   11x 11x   11x 11x 11x 11x   11x 10x   1x             120x   4x     2x     2x     2x   2x 2x 2x 2x 2x       120x 10x 10x 10x 10x           10x 10x 2x 2x   8x 1x 1x   7x 7x 10x 1x 1x   6x       6x 1x 1x       5x 5x 1x       1x 1x           1x       4x                       120x 120x     120x                                             120x                         10x 10x                               1x     840x                   11x                                                                         5x 5x         120x                                         2x 2x   2x                           5x 5x     4x 4x 1x 1x   3x       3x                                                                                                                          
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { AlertCircle, CheckCircle } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { isValidPhoneNumber, type CountryCode } from "libphonenumber-js";
import { useLeadSources } from "../../hooks/queries/useCrmQueries";
import { crmApi } from "../../lib/api";
import type { CreateLeadInput } from "../../lib/api/pro/crm";
import { queryKeys } from "../../lib/query-keys";
import { extractFieldErrors, getFormSubmitError } from "../../lib/form-errors";
import { isValidEmail } from "../../lib/validation";
import {
	customerNameErrorMessage,
	validateCustomerName,
} from "@interioring/utils/validation/customer-name";
import {
	freeTextErrorMessage,
	validateFreeText,
} from "@interioring/utils/validation/free-text";
import { Button } from "../ui/button";
import { CharCountTextarea } from "../ui/char-count-textarea";
import { DrawerDialog } from "../ui/drawer-dialog";
import { Label } from "../ui/field";
import { Input } from "../ui/input";
import { Select } from "../ui/select";
import { COUNTRY_CODES, PROJECT_TYPES, BUDGET_RANGES, type AddLeadModalProps } from "./add-lead-modal.config";
 
export function AddLeadModal({ open, onClose, proId }: AddLeadModalProps) {
	const queryClient = useQueryClient();
	const { data: sources } = useLeadSources(proId);
 
	// Form state
	const [customerName, setCustomerName] = useState("");
	const [phone, setPhone] = useState("");
	const [countryCode, setCountryCode] = useState<CountryCode>("IN");
	const [email, setEmail] = useState("");
	const [location, setLocation] = useState("");
	const [leadSourceId, setLeadSourceId] = useState<number | "">("");
	const [projectType, setProjectType] = useState("");
	const [budgetRange, setBudgetRange] = useState("");
	const [requirement, setRequirement] = useState("");
 
	// Validation state
	const [phoneError, setPhoneError] = useState<string | null>(null);
	const [nameError, setNameError] = useState<string | null>(null);
	const [emailServerError, setEmailServerError] = useState<string | null>(null);
	const [sourceError, setSourceError] = useState<string | null>(null);
	const [emailTouched, setEmailTouched] = useState(false);
	const [locationError, setLocationError] = useState<string | null>(null);
	const [phoneDedupStatus, setPhoneDedupStatus] = useState<
		"idle" | "checking" | "exists" | "clear"
	>("idle");
	const [dedupName, setDedupName] = useState<string | null>(null);
	const [submitError, setSubmitError] = useState<string | null>(null);
 
	// Phone dedup timer
	const dedupTimer = useRef<ReturnType<typeof setTimeout> | undefined>(
		undefined,
	);
 
	// Reset form when modal opens
	useEffect(() => {
		if (open) {
			setCustomerName("");
			setPhone("");
			setCountryCode("IN");
			setEmail("");
			setLocation("");
			setLeadSourceId("");
			setProjectType("");
			setBudgetRange("");
			setRequirement("");
			setPhoneError(null);
			setNameError(null);
			setEmailServerError(null);
			setSourceError(null);
			setEmailTouched(false);
			setLocationError(null);
			setPhoneDedupStatus("idle");
			setDedupName(null);
			setSubmitError(null);
		}
	}, [open]);
 
	// Phone dedup check
	const checkPhoneDedup = useCallback(
		async (rawPhone: string) => {
			const digits = rawPhone.replace(/[^0-9]/g, "");
			Iif (digits.length < 4) {
				setPhoneDedupStatus("idle");
				return;
			}
			setPhoneDedupStatus("checking");
			try {
				const response = await crmApi.checkPhone(proId, digits);
				if (response.data?.exists) {
					setPhoneDedupStatus("exists");
					setDedupName(response.data.lead?.customerName || null);
				} else {
					setPhoneDedupStatus("clear");
					setDedupName(null);
				}
			} catch {
				setPhoneDedupStatus("idle");
			}
		},
		[proId],
	);
 
	const handlePhoneChange = useCallback(
		(value: string) => {
			setPhone(value);
			setPhoneError(null);
 
			Iif (dedupTimer.current) clearTimeout(dedupTimer.current);
			const digits = value.replace(/[^0-9]/g, "");
			const selectedCountry = COUNTRY_CODES.find((c) => c.iso === countryCode);
			const fullNumber = `${selectedCountry?.dial || ""}${digits}`;
 
			if (digits.length >= 4 && isValidPhoneNumber(fullNumber, countryCode)) {
				dedupTimer.current = setTimeout(() => checkPhoneDedup(value), 500);
			} else {
				setPhoneDedupStatus("idle");
			}
		},
		[checkPhoneDedup, countryCode],
	);
 
	// Create mutation
	const createMutation = useMutation({
		mutationFn: async (data: CreateLeadInput) => {
			return crmApi.createLead(proId, data);
		},
		onSuccess: () => {
			queryClient.invalidateQueries({
				queryKey: queryKeys.crm.all,
			});
			onClose();
		},
		onError: (err: unknown) => {
			const fieldErrors = extractFieldErrors(err);
			// Route Zod field messages to their inputs
			setNameError(fieldErrors.customerName || null);
			setPhoneError(fieldErrors.phone || null);
			setEmailServerError(fieldErrors.email || null);
			setSourceError(fieldErrors.leadSourceId || null);
			setSubmitError(getFormSubmitError(err) || (err instanceof Error ? err.message : "Failed to create lead"));
		},
	});
 
	const handleSubmit = (e: React.FormEvent) => {
		e.preventDefault();
		setSubmitError(null);
		setNameError(null);
		setLocationError(null);
 
		// Validate customer name with the shared validator so the rule matches
		// the API's createLeadSchema (issue #563 audit: previously the API ran
		// only `.min(1)` and the client did a presence check — both let
		// numeric-only "46564655" pass).
		const nameErr = validateCustomerName(customerName);
		if (nameErr) {
			setNameError(customerNameErrorMessage(nameErr));
			return;
		}
		if (!phone.trim()) {
			setSubmitError("Phone number is required");
			return;
		}
		const selectedCountry = COUNTRY_CODES.find((c) => c.iso === countryCode);
		const fullNumber = `${selectedCountry?.dial || ""}${phone.replace(/[^0-9]/g, "")}`;
		if (!isValidPhoneNumber(fullNumber, countryCode)) {
			setPhoneError("Enter a valid phone number");
			return;
		}
		Iif (phoneDedupStatus === "exists") {
			setSubmitError(`A lead with this phone already exists: ${dedupName}`);
			return;
		}
		if (!leadSourceId) {
			setSubmitError("Please select a lead source");
			return;
		}
 
		// Validate optional location with the same rule the API enforces.
		const trimmedLocation = location.trim();
		if (trimmedLocation) {
			const locationErr = validateFreeText(trimmedLocation, {
				minLen: 2,
				requireLetter: true,
			});
			Eif (locationErr) {
				setLocationError(
					freeTextErrorMessage(locationErr, {
						minLen: 2,
						requireLetter: true,
					}),
				);
				return;
			}
		}
 
		createMutation.mutate({
			customerName: customerName.trim(),
			phone: phone.replace(/[^0-9]/g, ""),
			email: email.trim() || undefined,
			location: location.trim() || undefined,
			leadSourceId: leadSourceId as number,
			projectType: projectType || undefined,
			budgetRange: budgetRange || undefined,
			requirement: requirement.trim() || undefined,
		});
	};
 
	const clientEmailError = emailTouched && email.trim() && !isValidEmail(email.trim()) ? "Please enter a valid email" : undefined;
	const emailError = emailServerError || clientEmailError;
 
	const footer = (
		<>
			{submitError && (
				<div className="flex items-center gap-2 text-sm text-error mb-3">
					<AlertCircle className="h-4 w-4 flex-shrink-0" />
					{submitError}
				</div>
			)}
			<div className="flex flex-col-reverse sm:flex-row sm:justify-end gap-3">
				<Button type="button" variant="outline" onClick={onClose}>
					Cancel
				</Button>
				<Button
					type="submit"
					form="add-lead-form"
					isLoading={createMutation.isPending}
					disabled={phoneDedupStatus === "exists" || phoneDedupStatus === "checking"}
				>
					Add lead
				</Button>
			</div>
		</>
	);
 
	return (
		<DrawerDialog open={open} onClose={onClose} title="Add New Lead" footer={footer}>
			<form id="add-lead-form" onSubmit={handleSubmit} noValidate className="space-y-4">
				{/* Customer Name */}
				<div>
					<Label htmlFor="lead-name">
						Customer Name <span className="text-error">*</span>
					</Label>
					<Input
						id="lead-name"
						type="text"
						value={customerName}
						onChange={(e) => {
							setCustomerName(e.target.value);
							Iif (nameError) setNameError(null);
						}}
						maxLength={200}
						error={nameError || undefined}
						placeholder="e.g., Priya Sharma"
					/>
				</div>
 
				{/* Phone */}
				<div>
					<Label htmlFor="lead-phone">
						Phone Number <span className="text-error">*</span>
					</Label>
					<div className="relative flex">
						<Select
							value={countryCode}
							onChange={(e) => setCountryCode(e.target.value as CountryCode)}
							className="w-auto rounded-r-none border-r-0 focus:z-10"
							aria-label="Country code"
							options={COUNTRY_CODES.map((cc) => ({
								value: cc.iso,
								label: cc.label,
							}))}
						/>
						<div className="relative flex-1">
							<Input
								id="lead-phone"
								type="tel"
								value={phone}
								onChange={(e) => handlePhoneChange(e.target.value)}
								/* Butted against the country-code Select. */
								className="rounded-l-none pr-8"
								placeholder="9876543210"
							/>
							{phoneDedupStatus === "checking" && (
								<span className="absolute right-3 top-1/2 -translate-y-1/2">
									<div className="h-4 w-4 animate-spin rounded-full border-2 border-foreground-subtle border-t-transparent" />
								</span>
							)}
							{phoneDedupStatus === "clear" && (
								<CheckCircle className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-success" />
							)}
							{phoneDedupStatus === "exists" && (
								<AlertCircle className="absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 text-error" />
							)}
						</div>
					</div>
					{phoneError && (
						<p className="mt-1 text-xs text-error">{phoneError}</p>
					)}
					{phoneDedupStatus === "exists" && (
						<p className="mt-1 text-xs text-error">
							Lead already exists: {dedupName}
						</p>
					)}
				</div>
 
				{/* Lead Source */}
				<div>
					<Label htmlFor="lead-source">
						Lead Source <span className="text-error">*</span>
					</Label>
					<Select
						id="lead-source"
						value={leadSourceId}
						onChange={(e) => {
							setLeadSourceId(e.target.value ? Number(e.target.value) : "");
							Iif (sourceError) setSourceError(null);
						}}
						invalid={!!sourceError}
						aria-describedby={sourceError ? "lead-source-error" : undefined}
						placeholder="Select a source"
						options={(sources || []).map((source) => ({
							value: String(source.id),
							label: source.name,
						}))}
					/>
					{sourceError && (
						<p id="lead-source-error" className="mt-1 text-xs text-error">{sourceError}</p>
					)}
				</div>
 
				{/* Email + Location row */}
				<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
					<div>
						<Label htmlFor="lead-email">
							Email
						</Label>
						<Input
							id="lead-email"
							type="email"
							value={email}
							onChange={(e) => {
								setEmail(e.target.value);
								Iif (emailServerError) setEmailServerError(null);
							}}
							onBlur={() => setEmailTouched(true)}
							error={emailError || undefined}
							placeholder="priya@email.com"
						/>
					</div>
					<div>
						<Label htmlFor="lead-location">
							Location
						</Label>
						<Input
							id="lead-location"
							type="text"
							value={location}
							onChange={(e) => {
								setLocation(e.target.value);
								if (locationError) setLocationError(null);
							}}
							onBlur={(e) => {
								const v = e.target.value.trim();
								if (!v) {
									setLocationError(null);
									return;
								}
								const err = validateFreeText(v, {
									minLen: 2,
									requireLetter: true,
								});
								setLocationError(
									err
										? freeTextErrorMessage(err, {
												minLen: 2,
												requireLetter: true,
											})
										: null,
								);
							}}
							error={locationError || undefined}
							placeholder="Banjara Hills"
						/>
					</div>
				</div>
 
				{/* Project Type + Budget Range row */}
				<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
					<div>
						<Label htmlFor="lead-project-type">
							Project Type
						</Label>
						<Select
							id="lead-project-type"
							value={projectType}
							onChange={(e) => setProjectType(e.target.value)}
							placeholder="Select a scope"
							options={PROJECT_TYPES}
						/>
					</div>
					<div>
						<Label htmlFor="lead-budget">
							Budget Range
						</Label>
						<Select
							id="lead-budget"
							value={budgetRange}
							onChange={(e) => setBudgetRange(e.target.value)}
							placeholder="Select a budget"
							options={BUDGET_RANGES}
						/>
					</div>
				</div>
 
				{/* Requirement */}
				<div>
					<Label htmlFor="lead-requirement">
						Requirement Notes
					</Label>
					<CharCountTextarea
						id="lead-requirement"
						value={requirement}
						onChange={setRequirement}
						maxLength={2000}
						rows={5}
						placeholder="Brief description of what the customer needs..."
					/>
				</div>
			</form>
		</DrawerDialog>
	);
}