All files / src/components/crm LeadDocuments.tsx

92.04% Statements 81/88
82.66% Branches 62/75
100% Functions 23/23
93.97% Lines 78/83

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                                                                            4x                   28x         4x                   4x     41x 23x                                                           114x 114x 114x 114x 114x 114x   114x   1x   1x     1x     1x       114x 24x       114x       24x   23x     114x                                   1x                   12x                                                   23x   23x       23x                                                                                                               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                                                    
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
	AlertCircle,
	Download,
	FileText,
	Trash2,
	Upload,
	X,
} from "lucide-react";
import { useCallback, useState } from "react";
import { formatDate } from "@interioring/utils/format/date";
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 { Button } from "../ui/button";
import { ConfirmDialog } from "../ui/confirm-dialog";
import { Label } from "../ui/field";
import { Input } from "../ui/input";
import { Select } from "../ui/select";
import { StatusBadge } from "../ui/status-badge";
import type { StatusTone } from "../ui/status-ink";
import { DENSE_BUTTON } from "./lead-controls";
 
// ─── Constants ───────────────────────────────────────────────────────────────
 
/**
 * A document's type, as a printed code.
 *
 * The ink is a `StatusTone` from the shared registry, not a hand-mixed
 * tint/ink pair. The seven types used to carry seven pairs invented here —
 * `bg-warning/10 text-warning`, `bg-secondary-100 text-secondary-700` and so
 * on — which were both a second status vocabulary and unmeasured for contrast
 * (`status-ink.ts` records why the alpha-tint pairs failed AA). Four of the
 * seven resolve to the neutral tone, which is correct: the WORD distinguishes
 * a measurement from a contract, and the Job Book does not spend a colour
 * family on a distinction the label already makes.
 */
const DOC_TYPE_CONFIG: Record<string, { label: string; tone: StatusTone }> = {
	quote: { label: "Quote", tone: "warning" },
	design: { label: "Design", tone: "info" },
	measurement: { label: "Measurement", tone: "default" },
	contract: { label: "Contract", tone: "default" },
	invoice: { label: "Invoice", tone: "success" },
	reference: { label: "Reference", tone: "default" },
	other: { label: "Other", tone: "default" },
};
 
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`;
}
 
// ─── Component ───────────────────────────────────────────────────────────────
 
/**
 * Documents are a lead write staff do not have: no
 * `/crm/leads/:id/documents` route is on the server's staff allowlist, so
 * uploading or deleting would 403. `canManage` is false for them and the panel
 * becomes read-only — downloads stay, because reading is never gated. See
 * `lead-write-scope.ts`.
 */
type LeadDocumentsProps = {
	leadId: number;
	proId: string;
	/** When true, auto-open the upload modal (controlled from parent) */
	/** False for staff: upload and delete are hidden. Defaults to true. */
	canManage?: boolean;
	externalOpen?: boolean;
	onExternalClose?: () => void;
};
 
export function LeadDocuments({
	leadId,
	proId,
	canManage = true,
	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
						tier="dense"
						aria-label="Filter by document type"
						value={typeFilter}
						onChange={(e) => setTypeFilter(e.target.value)}
						placeholder="All types"
						options={DOC_TYPES}
						className="w-auto"
					/>
					{canManage && (
						<Button
							size="sm"
							variant="outline"
							className={DENSE_BUTTON}
							onClick={() => setShowUpload(true)}
						>
							<Upload className="h-3.5 w-3.5" aria-hidden="true" />
							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>
			) : (
				/*
				 * Ruled rows, full-bleed across the panel: hairline dividers, not
				 * boxes. Each row used to be its own `rounded-md border` card inside
				 * this already-bordered panel — a box in a box. Rows TINT on hover;
				 * the lift belongs to draggables, and a document is not one.
				 */
				<div className="-mx-5 border-t border-border-default">
					{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="group flex items-center gap-3 border-b border-border-default px-5 py-2.5 transition-colors hover:bg-foreground-default/7"
							>
								{/* The type, as a printed code. */}
								<StatusBadge
									status={`${typeConfig.label}${
										doc.quoteRevisionNumber != null
											? ` v${doc.quoteRevisionNumber}`
											: ""
									}`}
									variant={typeConfig.tone}
									className="shrink-0"
								/>
 
								{/* 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 && (
											<StatusBadge status="Latest" variant="success" />
										)}
									</div>
									<p className="text-xs text-foreground-subtle truncate">
										{doc.originalFilename} &middot;{" "}
										{formatFileSize(doc.fileSizeBytes)} &middot;{" "}
										{formatDate(doc.dateCreated)}
									</p>
								</div>
 
								{/* Actions */}
								{/*
								 * `focus-within` is load-bearing, not symmetry: hover-only
								 * reveal hid Download and Delete from every keyboard user,
								 * who could tab to them while they stayed invisible.
								 */}
								<div className="flex items-center gap-1 opacity-0 transition-opacity focus-within:opacity-100 group-hover:opacity-100">
									<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>
									{canManage && (
									<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 cursor-default bg-overlay-dark"
				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">
							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">
							Document Name <span className="text-error">*</span>
						</Label>
						<Input
							id="doc-upload-name"
							type="text"
							value={name}
							onChange={(e) => setName(e.target.value)}
							placeholder="e.g., Kitchen Quote v2"
						/>
					</div>
 
					{/* Type */}
					<div>
						<Label htmlFor="doc-upload-type">
							Document Type <span className="text-error">*</span>
						</Label>
						<Select
							id="doc-upload-type"
							value={documentType}
							onChange={(e) => setDocumentType(e.target.value)}
							placeholder="Select a type"
							options={DOC_TYPES}
						/>
					</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>
	);
}