All files / src/components/crm LeadDocuments.tsx

92.3% Statements 84/91
81.42% Branches 57/70
100% Functions 26/26
94.18% Lines 81/86

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                                        4x                               28x         4x                   4x     37x 19x         19x                                   107x 107x 107x 107x 107x 107x   107x   1x   1x     1x     1x       107x 20x       107x       20x   19x     107x                               1x         749x               12x                                     19x   19x       19x                                                                                                         3x                                     4x 4x                       1x 1x                             36x 36x 36x 36x 36x   36x   3x 3x           2x     2x     2x     1x 1x   1x     1x         36x   9x 9x   9x 1x     1x   8x 1x 1x     7x 7x   7x 7x           36x   6x 6x   6x 1x 1x   5x           5x 1x 1x   4x 1x 1x     3x         36x                                                                                                                           1x                                 3x         252x                                                      
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
	AlertCircle,
	Download,
	FileText,
	Trash2,
	Upload,
	X,
} from "lucide-react";
import { useCallback, useState } from "react";
import { useLeadDocuments } from "../../hooks/queries/useCrmQueries";
import { crmApi } from "../../lib/api";
import type { LeadDocument } from "../../lib/api/pro/crm";
import { queryKeys } from "../../lib/query-keys";
import { cn } from "../../lib/utils";
import { Button } from "../ui/button";
import { ConfirmDialog } from "../ui/confirm-dialog";
 
// ─── Constants ───────────────────────────────────────────────────────────────
 
const DOC_TYPE_CONFIG: Record<string, { label: string; color: string }> = {
	quote: { label: "Quote", color: "bg-warning/10 text-warning" },
	design: { label: "Design", color: "bg-info/10 text-info" },
	measurement: {
		label: "Measurement",
		color: "bg-secondary-100 text-secondary-700",
	},
	contract: { label: "Contract", color: "bg-primary-100 text-primary-700" },
	invoice: { label: "Invoice", color: "bg-success/10 text-success" },
	reference: {
		label: "Reference",
		color: "bg-background-muted text-foreground-muted",
	},
	other: { label: "Other", color: "bg-background-muted text-foreground-muted" },
};
 
const DOC_TYPES = Object.entries(DOC_TYPE_CONFIG).map(([value, cfg]) => ({
	value,
	label: cfg.label,
}));
 
const ALLOWED_TYPES = [
	"application/pdf",
	"image/jpeg",
	"image/png",
	"image/webp",
	"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
	"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
	"application/vnd.ms-excel",
];
 
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
 
function formatFileSize(bytes: number): string {
	if (bytes < 1024) return `${bytes} B`;
	Eif (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
	return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
 
function formatDate(dateStr: string): string {
	return new Date(dateStr).toLocaleDateString("en-IN", {
		day: "numeric",
		month: "short",
		year: "numeric",
	});
}
 
// ─── Component ───────────────────────────────────────────────────────────────
 
type LeadDocumentsProps = {
	leadId: number;
	proId: string;
	/** When true, auto-open the upload modal (controlled from parent) */
	externalOpen?: boolean;
	onExternalClose?: () => void;
};
 
export function LeadDocuments({ leadId, proId, externalOpen, onExternalClose }: LeadDocumentsProps) {
	const queryClient = useQueryClient();
	const { data: documents } = useLeadDocuments(proId, String(leadId));
	const [typeFilter, setTypeFilter] = useState<string>("");
	const [showUpload, setShowUpload] = useState(false);
	const isUploadOpen = showUpload || !!externalOpen;
	const [deleteTarget, setDeleteTarget] = useState<LeadDocument | null>(null);
 
	const deleteMutation = useMutation({
		mutationFn: async (docId: number) =>
			crmApi.deleteDocument(proId, leadId, docId),
		onSuccess: () => {
			queryClient.invalidateQueries({
				queryKey: queryKeys.crm.documents(proId, String(leadId)),
			});
			queryClient.invalidateQueries({
				queryKey: queryKeys.crm.activities(proId, String(leadId)),
			});
			setDeleteTarget(null);
		},
	});
 
	const filtered = (documents || []).filter(
		(d) => !typeFilter || d.documentType === typeFilter,
	);
 
	// Find latest quote revision
	const latestQuoteRevision = Math.max(
		0,
		...(documents || [])
			.filter(
				(d) => d.documentType === "quote" && d.quoteRevisionNumber != null,
			)
			.map((d) => d.quoteRevisionNumber ?? 0),
	);
 
	return (
		<div className="rounded-lg border border-border-default bg-background-elevated p-5">
			<div className="flex items-center justify-between flex-wrap gap-2 mb-4">
				<h3 className="text-sm font-semibold text-foreground-default flex items-center gap-2">
					<FileText className="h-4 w-4 text-foreground-subtle" />
					Documents
					{documents && documents.length > 0 && (
						<span className="text-xs font-normal text-foreground-muted">
							({documents.length})
						</span>
					)}
				</h3>
				<div className="flex items-center gap-2 shrink-0">
					{/* Type filter */}
					<select
						value={typeFilter}
						onChange={(e) => setTypeFilter(e.target.value)}
						className="h-8 px-2 text-xs rounded border border-border-default bg-background-elevated text-foreground-default focus:ring-2 focus:ring-primary-500"
					>
						<option value="">All types</option>
						{DOC_TYPES.map((t) => (
							<option key={t.value} value={t.value}>
								{t.label}
							</option>
						))}
					</select>
					<Button
						size="sm"
						variant="outline"
						onClick={() => setShowUpload(true)}
					>
						<Upload className="h-3.5 w-3.5" />
						Upload
					</Button>
				</div>
			</div>
 
			{/* Document list */}
			{filtered.length === 0 ? (
				<p className="text-sm text-foreground-subtle text-center py-6">
					{documents?.length
						? "No documents match the filter"
						: "No documents attached yet"}
				</p>
			) : (
				<div className="space-y-2">
					{filtered.map((doc) => {
						const typeConfig =
							DOC_TYPE_CONFIG[doc.documentType] || DOC_TYPE_CONFIG.other;
						const isLatestQuote =
							doc.documentType === "quote" &&
							doc.quoteRevisionNumber === latestQuoteRevision &&
							latestQuoteRevision > 0;
 
						return (
							<div
								key={doc.id}
								className="flex items-center gap-3 p-2.5 rounded-md border border-border-default hover:bg-background-muted transition-colors group"
							>
								{/* Type badge */}
								<span
									className={cn(
										"text-[10px] font-medium rounded-full px-2 py-0.5 flex-shrink-0",
										typeConfig.color,
									)}
								>
									{typeConfig.label}
									{doc.quoteRevisionNumber != null &&
										` v${doc.quoteRevisionNumber}`}
								</span>
 
								{/* Name + filename */}
								<div className="flex-1 min-w-0">
									<div className="flex items-center gap-1.5">
										<span className="text-sm font-medium text-foreground-default truncate">
											{doc.name}
										</span>
										{isLatestQuote && (
											<span className="text-[10px] font-medium text-success bg-success/10 rounded px-1.5 py-0.5">
												Latest
											</span>
										)}
									</div>
									<p className="text-xs text-foreground-subtle truncate">
										{doc.originalFilename} &middot;{" "}
										{formatFileSize(doc.fileSizeBytes)} &middot;{" "}
										{formatDate(doc.dateCreated)}
									</p>
								</div>
 
								{/* Actions */}
								<div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
									<a
										href={crmApi.getDocumentDownloadUrl(
											proId,
											leadId,
											doc.id,
										)}
										target="_blank"
										rel="noopener noreferrer"
										className="p-1.5 text-foreground-subtle hover:text-primary-600 transition-colors"
										title="Download"
									>
										<Download className="h-3.5 w-3.5" />
									</a>
									<button
										type="button"
										onClick={() => setDeleteTarget(doc)}
										className="p-1.5 text-foreground-subtle hover:text-error transition-colors"
										title="Delete"
									>
										<Trash2 className="h-3.5 w-3.5" />
									</button>
								</div>
							</div>
						);
					})}
				</div>
			)}
 
			{/* Upload modal */}
			{isUploadOpen && (
				<UploadDocumentModal
					proId={proId}
					leadId={leadId}
					onClose={() => {
						setShowUpload(false);
						onExternalClose?.();
					}}
				/>
			)}
 
			{/* Delete confirmation */}
			<ConfirmDialog
				open={!!deleteTarget}
				title="Delete Document"
				description={`Delete "${deleteTarget?.name}"? This cannot be undone.`}
				confirmLabel="Delete"
				variant="destructive"
				onConfirm={() => deleteTarget && deleteMutation.mutate(deleteTarget.id)}
				onCancel={() => setDeleteTarget(null)}
			/>
		</div>
	);
}
 
// ─── Upload Modal ────────────────────────────────────────────────────────────
 
type UploadModalProps = {
	proId: string;
	leadId: number;
	onClose: () => void;
};
 
function UploadDocumentModal({ proId, leadId, onClose }: UploadModalProps) {
	const queryClient = useQueryClient();
	const [file, setFile] = useState<File | null>(null);
	const [name, setName] = useState("");
	const [documentType, setDocumentType] = useState("");
	const [error, setError] = useState<string | null>(null);
 
	const uploadMutation = useMutation({
		mutationFn: async () => {
			Iif (!file) throw new Error("No file selected");
			return crmApi.uploadDocument(proId, leadId, file, {
				name: name.trim(),
				documentType,
			});
		},
		onSuccess: () => {
			queryClient.invalidateQueries({
				queryKey: queryKeys.crm.documents(proId, String(leadId)),
			});
			queryClient.invalidateQueries({
				queryKey: queryKeys.crm.activities(proId, String(leadId)),
			});
			onClose();
		},
		onError: (err: Error) => {
			const msg = err.message || "";
			Iif (msg.includes("No file") || msg.includes("file provided")) {
				setError("Upload failed. The file may be too large (max 10MB).");
			I} else if (msg.includes("Failed to fetch") || msg.includes("network")) {
				setError("Upload failed due to a network error. Please try again.");
			} else {
				setError(msg || "Upload failed. Please try again.");
			}
		},
	});
 
	const handleFileChange = useCallback(
		(e: React.ChangeEvent<HTMLInputElement>) => {
			const selected = e.target.files?.[0];
			Iif (!selected) return;
 
			if (!ALLOWED_TYPES.includes(selected.type)) {
				setError(
					"Unsupported file type. Allowed: PDF, JPG, PNG, WebP, DOCX, XLSX",
				);
				return;
			}
			if (selected.size > MAX_FILE_SIZE) {
				setError("File too large. Maximum 10MB.");
				return;
			}
 
			setFile(selected);
			setError(null);
			// Auto-fill name from filename
			Eif (!name) {
				setName(selected.name.replace(/\.[^.]+$/, ""));
			}
		},
		[name],
	);
 
	const handleSubmit = useCallback(
		(e: React.FormEvent) => {
			e.preventDefault();
			setError(null);
 
			if (!file) {
				setError("Please select a file");
				return;
			}
			Iif (file.size > MAX_FILE_SIZE) {
				setError(
					`File too large (${formatFileSize(file.size)}). Maximum 10MB.`,
				);
				return;
			}
			if (!name.trim()) {
				setError("Document name is required");
				return;
			}
			if (!documentType) {
				setError("Document type is required");
				return;
			}
 
			uploadMutation.mutate();
		},
		[file, name, documentType, uploadMutation],
	);
 
	return (
		<div
			role="dialog"
			className="fixed inset-0 z-[62] flex flex-col justify-end sm:flex-row sm:items-center sm:justify-center"
		>
			<button
				type="button"
				aria-label="Close"
				className="fixed inset-0 bg-black/50 cursor-default"
				onClick={onClose}
				tabIndex={-1}
			/>
			<div className="relative z-10 bg-background-base rounded-t-2xl sm:rounded-lg sm:shadow-xl w-full sm:max-w-md mx-2 sm:mx-4 animate-slide-up sm:animate-none max-h-[85vh] flex flex-col">
				<div className="flex items-center justify-between border-b border-border-default bg-background-elevated px-4 py-3 rounded-t-2xl flex-shrink-0">
					<h2 className="text-lg font-semibold text-foreground-default">
						Upload Document
					</h2>
					<button
						type="button"
						onClick={onClose}
						className="p-1.5 text-foreground-subtle hover:text-foreground-default rounded-md"
						aria-label="Close"
					>
						<X className="h-5 w-5" />
					</button>
				</div>
 
				<form onSubmit={handleSubmit} className="flex-1 overflow-y-auto p-4 space-y-4">
					{/* File input */}
					<div>
						<label
							htmlFor="doc-upload-file"
							className="block text-sm font-medium text-foreground-default mb-1"
						>
							File <span className="text-error">*</span>
						</label>
						<input
							id="doc-upload-file"
							type="file"
							onChange={handleFileChange}
							accept=".pdf,.jpg,.jpeg,.png,.webp,.docx,.xlsx,.xls"
							className="w-full text-sm text-foreground-default file:mr-3 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:text-sm file:font-medium file:bg-primary-100 file:text-primary-700 hover:file:bg-primary-200"
						/>
						{file && (
							<p className="mt-1 text-xs text-foreground-subtle">
								{file.name} ({formatFileSize(file.size)})
							</p>
						)}
					</div>
 
					{/* Name */}
					<div>
						<label
							htmlFor="doc-upload-name"
							className="block text-sm font-medium text-foreground-default mb-1"
						>
							Document Name <span className="text-error">*</span>
						</label>
						<input
							id="doc-upload-name"
							type="text"
							value={name}
							onChange={(e) => setName(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"
							placeholder="e.g., Kitchen Quote v2"
						/>
					</div>
 
					{/* Type */}
					<div>
						<label
							htmlFor="doc-upload-type"
							className="block text-sm font-medium text-foreground-default mb-1"
						>
							Document Type <span className="text-error">*</span>
						</label>
						<select
							id="doc-upload-type"
							value={documentType}
							onChange={(e) => setDocumentType(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"
						>
							<option value="">Select type...</option>
							{DOC_TYPES.map((t) => (
								<option key={t.value} value={t.value}>
									{t.label}
								</option>
							))}
						</select>
					</div>
 
					{error && (
						<div className="flex items-center gap-2 text-sm text-error">
							<AlertCircle className="h-4 w-4 flex-shrink-0" />
							{error}
						</div>
					)}
 
					<div className="flex justify-end gap-3 pt-2">
						<Button type="button" variant="outline" onClick={onClose}>
							Cancel
						</Button>
						<Button type="submit" isLoading={uploadMutation.isPending}>
							Upload
						</Button>
					</div>
				</form>
			</div>
		</div>
	);
}