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 | 2x 2x 2x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 129x 46x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 37x 129x 5x 5x 5x 5x 5x 3x 2x 2x 1x 1x 129x 11x 11x 11x 11x 11x 11x 11x 10x 1x 129x 4x 2x 2x 2x 2x 2x 2x 2x 2x 129x 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 129x 129x 129x 129x 10x 10x 1x 903x 11x 5x 5x 129x 2x 2x 2x 5x 5x 4x 4x 1x 1x 3x 3x 903x 774x | 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";
// ─── Constants ───────────────────────────────────────────────────────────────
const COUNTRY_CODES: { iso: CountryCode; dial: string; label: string }[] = [
{ iso: "IN", dial: "+91", label: "IN +91" },
{ iso: "AE", dial: "+971", label: "AE +971" },
{ iso: "US", dial: "+1", label: "US +1" },
{ iso: "GB", dial: "+44", label: "GB +44" },
{ iso: "SG", dial: "+65", label: "SG +65" },
{ iso: "AU", dial: "+61", label: "AU +61" },
{ iso: "DE", dial: "+49", label: "DE +49" },
];
const PROJECT_TYPES = [
{ value: "modular_kitchen", label: "Modular Kitchen" },
{ value: "full_interior", label: "Full Interior" },
{ value: "wardrobe", label: "Wardrobe" },
{ value: "tv_unit", label: "TV Unit" },
{ value: "pooja_unit", label: "Pooja Unit" },
{ value: "kitchen_renovation", label: "Kitchen Renovation" },
{ value: "other", label: "Other" },
];
const BUDGET_RANGES = [
{ value: "under_1l", label: "Under ₹1 Lakh" },
{ value: "1_3l", label: "₹1-3 Lakhs" },
{ value: "3_5l", label: "₹3-5 Lakhs" },
{ value: "5_10l", label: "₹5-10 Lakhs" },
{ value: "10_20l", label: "₹10-20 Lakhs" },
{ value: "above_20l", label: "Above ₹20 Lakhs" },
];
// ─── Component ───────────────────────────────────────────────────────────────
type AddLeadModalProps = {
open: boolean;
onClose: () => void;
proId: string;
};
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"
className="block text-sm font-medium text-foreground-default mb-1"
>
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}
aria-invalid={nameError ? true : undefined}
aria-describedby={nameError ? "lead-name-error" : undefined}
className={`w-full h-10 px-3 rounded-md border bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500 focus:border-transparent ${nameError ? "border-error focus:ring-error" : "border-border-default"}`}
placeholder="e.g., Priya Sharma"
/>
{nameError && (
<p id="lead-name-error" className="mt-1 text-xs text-error">{nameError}</p>
)}
</div>
{/* Phone */}
<div>
<label
htmlFor="lead-phone"
className="block text-sm font-medium text-foreground-default mb-1"
>
Phone Number <span className="text-error">*</span>
</label>
<div className="relative flex">
<select
value={countryCode}
onChange={(e) => setCountryCode(e.target.value as CountryCode)}
className="h-10 pl-2 pr-1 rounded-l-md border border-r-0 border-border-default bg-background-muted text-sm text-foreground-default focus:ring-2 focus:ring-primary-500 focus:z-10"
aria-label="Country code"
>
{COUNTRY_CODES.map((cc) => (
<option key={cc.iso} value={cc.iso}>
{cc.label}
</option>
))}
</select>
<div className="relative flex-1">
<input
id="lead-phone"
type="tel"
value={phone}
onChange={(e) => handlePhoneChange(e.target.value)}
className="w-full h-10 px-3 pr-8 rounded-r-md border border-border-default bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500 focus:border-transparent"
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"
className="block text-sm font-medium text-foreground-default mb-1"
>
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);
}}
aria-invalid={sourceError ? true : undefined}
aria-describedby={sourceError ? "lead-source-error" : undefined}
className={`w-full h-10 px-3 rounded-md border bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500 focus:border-transparent ${sourceError ? "border-error focus:ring-error" : "border-border-default"}`}
>
<option value="">Select source...</option>
{(sources || []).map((s) => (
<option key={s.id} value={s.id}>
{s.name}
</option>
))}
</select>
{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"
className="block text-sm font-medium text-foreground-default mb-1"
>
Email
</label>
<input
id="lead-email"
type="email"
value={email}
onChange={(e) => {
setEmail(e.target.value);
Iif (emailServerError) setEmailServerError(null);
}}
onBlur={() => setEmailTouched(true)}
aria-invalid={emailError ? true : undefined}
aria-describedby={emailError ? "lead-email-error" : undefined}
className={`w-full h-10 px-3 rounded-md border bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500 focus:border-transparent ${emailError ? "border-error focus:ring-error" : "border-border-default"}`}
placeholder="priya@email.com"
/>
{emailError && (
<p id="lead-email-error" className="mt-1 text-xs text-error">{emailError}</p>
)}
</div>
<div>
<label
htmlFor="lead-location"
className="block text-sm font-medium text-foreground-default mb-1"
>
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,
);
}}
aria-invalid={locationError ? true : undefined}
aria-describedby={locationError ? "lead-location-error" : undefined}
className={`w-full h-10 px-3 rounded-md border bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500 focus:border-transparent ${
locationError
? "border-error focus:ring-error"
: "border-border-default"
}`}
placeholder="Banjara Hills"
/>
{locationError && (
<p
id="lead-location-error"
className="mt-1 text-xs text-error"
>
{locationError}
</p>
)}
</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"
className="block text-sm font-medium text-foreground-default mb-1"
>
Project Type
</label>
<select
id="lead-project-type"
value={projectType}
onChange={(e) => setProjectType(e.target.value)}
className="w-full h-10 px-3 rounded-md border border-border-default bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500 focus:border-transparent"
>
<option value="">Select type...</option>
{PROJECT_TYPES.map((t) => (
<option key={t.value} value={t.value}>
{t.label}
</option>
))}
</select>
</div>
<div>
<label
htmlFor="lead-budget"
className="block text-sm font-medium text-foreground-default mb-1"
>
Budget Range
</label>
<select
id="lead-budget"
value={budgetRange}
onChange={(e) => setBudgetRange(e.target.value)}
className="w-full h-10 px-3 rounded-md border border-border-default bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500 focus:border-transparent"
>
<option value="">Select budget...</option>
{BUDGET_RANGES.map((b) => (
<option key={b.value} value={b.value}>
{b.label}
</option>
))}
</select>
</div>
</div>
{/* Requirement */}
<div>
<label
htmlFor="lead-requirement"
className="block text-sm font-medium text-foreground-default mb-1"
>
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>
);
}
|