All files / src/pages/admin search.tsx

93.87% Statements 46/49
84.21% Branches 32/38
100% Functions 12/12
97.67% Lines 42/43

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                              2x 2x 2x       1x               20x 20x 20x           20x       20x 9x 9x     8x           9x 9x         3x 3x 3x 3x 2x 2x   1x 1x   3x         2x 2x 2x 1x 1x 1x         1x   1x 1x   2x       20x                                                     80x 80x     80x 80x 80x 80x                                                         2x                                                   5x                                                                                              
import { useEffect, useState } from "react";
import { RefreshCw, Search } from "lucide-react";
import { AdminMetric, AdminMetrics } from "../../components/admin/AdminMetric";
import { AdminBand, AdminPageHead } from "../../components/admin/AdminPageHead";
import { Button } from "../../components/ui/button";
import { Card } from "../../components/ui/card";
import { formatDateTime } from "../../lib/utils";
import { adminApi } from "../../lib/api/admin";
import type {
	SearchIndexStatus,
	SearchRebuildStats,
} from "../../lib/api/admin";
import { toast } from "react-hot-toast";
 
function formatBytes(bytes: number | null): string {
	Iif (bytes == null) return "โ€”";
	Iif (bytes < 1024) return `${bytes} B`;
	Eif (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
	return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
 
const ENTITY_TYPES = [
	{ key: "pro", label: "Pros" },
	{ key: "project", label: "Projects" },
	{ key: "room", label: "Rooms" },
	{ key: "blog", label: "Blogs" },
] as const;
 
export function AdminSearchPage() {
	const [isRebuilding, setIsRebuilding] = useState(false);
	const [rebuildingType, setRebuildingType] = useState<string | null>(null);
	const [lastRebuild, setLastRebuild] = useState<SearchRebuildStats | null>(
		null,
	);
	// #358: mirror real R2 state so the cards show "โ€” KB, built <when>"
	// instead of "not built yet" before the admin ever clicks rebuild.
	// The hourly cron keeps these indexes populated; only the UI was blind.
	const [indexStatus, setIndexStatus] = useState<SearchIndexStatus | null>(
		null,
	);
 
	useEffect(() => {
		let cancelled = false;
		adminApi
			.getStatus()
			.then((res) => {
				if (!cancelled && res.data) setIndexStatus(res.data);
			})
			.catch(() => {
				// Fail-soft: the cards fall back to the existing "not built yet"
				// rendering if status can't load. No toast โ€” rebuild still works.
			});
		return () => {
			cancelled = true;
		};
	}, []);
 
	async function handleRebuildAll() {
		setIsRebuilding(true);
		setRebuildingType(null);
		try {
			const response = await adminApi.rebuildIndex();
			if (response.data) setLastRebuild(response.data);
			toast.success("All search indexes rebuilt successfully");
		} catch (error) {
			toast.error("Failed to rebuild search indexes");
			console.error("Rebuild failed:", error);
		} finally {
			setIsRebuilding(false);
		}
	}
 
	async function handleRebuildType(type: string) {
		setRebuildingType(type);
		try {
			const response = await adminApi.rebuildIndex(type);
			Eif (response.data) {
				const data = response.data;
				setLastRebuild((prev) => ({
					rebuilt: { ...prev?.rebuilt, ...data.rebuilt },
					timestamp: data.timestamp,
				}));
			}
			toast.success(`${type} search index rebuilt`);
		} catch (error) {
			toast.error(`Failed to rebuild ${type} index`);
			console.error("Rebuild failed:", error);
		} finally {
			setRebuildingType(null);
		}
	}
 
	return (
		<div className="space-y-8">
			<AdminPageHead
				title={
					<>
						<Search aria-hidden="true" className="size-5" />
						Search Management
					</>
				}
				description="Manage search indexes for the marketplace. Indexes are pre-built and stored in R2 for fast fuzzy search."
				actions={
					<Button
						onClick={handleRebuildAll}
						disabled={isRebuilding || !!rebuildingType}
					>
						<RefreshCw
							aria-hidden="true"
							className={isRebuilding ? "animate-spin" : ""}
						/>
						{isRebuilding ? "Rebuilding All..." : "Rebuild All Indexes"}
					</Button>
				}
			/>
 
			{/* One index per figure: a label, a rule, a number. No boxes. */}
			<AdminMetrics className="gap-y-4">
				{ENTITY_TYPES.map((entity) => {
					const stats = lastRebuild?.rebuilt?.[entity.key];
					const isThisRebuilding = rebuildingType === entity.key;
					// Prefer fresh rebuild response; fall back to the R2-head
					// snapshot from mount.
					const status = indexStatus?.indexes[entity.key];
					const hasStats = !!stats;
					const hasIndex = hasStats || !!status?.exists;
					return (
						<div key={entity.key}>
							{hasStats ? (
								<AdminMetric
									label={entity.label}
									value={stats.documents.toLocaleString("en-IN")}
									note={`documents indexed (${stats.size})`}
								/>
							) : hasIndex ? (
								<AdminMetric
									label={entity.label}
									value={formatBytes(status?.sizeBytes ?? null)}
									note={
										status?.lastModified
											? `index built ยท ${formatDateTime(status.lastModified)}`
											: "index built"
									}
								/>
							) : (
								<AdminMetric
									label={entity.label}
									value="--"
									note="not built yet"
								/>
							)}
							<Button
								variant="outline"
								size="sm"
								className="mt-2 w-full"
								onClick={() => handleRebuildType(entity.key)}
								disabled={isRebuilding || !!rebuildingType}
							>
								<RefreshCw
									aria-hidden="true"
									className={isThisRebuilding ? "animate-spin" : ""}
								/>
								{isThisRebuilding ? "Rebuilding..." : `Rebuild ${entity.label}`}
							</Button>
						</div>
					);
				})}
			</AdminMetrics>
 
			{/* Last Rebuild Info */}
			{lastRebuild && (
				<section className="space-y-2">
					<AdminBand title="Last Rebuild" quiet />
					<p className="text-sm text-foreground-muted">
						Completed at{" "}
						<span className="font-medium tabular-nums text-foreground-default">
							{formatDateTime(lastRebuild.timestamp)}
						</span>
					</p>
					<AdminMetrics>
						{Object.entries(lastRebuild.rebuilt).map(([type, stats]) => (
							<AdminMetric
								key={type}
								label={type}
								value={stats.documents.toLocaleString("en-IN")}
								note={stats.size}
							/>
						))}
					</AdminMetrics>
				</section>
			)}
 
			{/* How it works */}
			<section className="space-y-2">
				<AdminBand title="How Search Works" quiet />
				<Card className="space-y-2 p-4 text-sm text-foreground-muted">
					<p>
						Search indexes are pre-built using MiniSearch and stored in
						Cloudflare R2.
					</p>
					<p>
						When a user searches, the API loads the indexes from R2 (cached in
						memory for subsequent requests) and runs fuzzy matching with typo
						correction.
					</p>
					<p>
						Indexes should be rebuilt when pros, projects, rooms, or blogs are
						published or updated. A daily automatic rebuild runs as a safety
						net.
					</p>
					<p className="font-medium text-foreground-default">
						Visibility rules:
					</p>
					<ul className="list-disc list-inside space-y-1 ml-2">
						<li>Only published pros are indexed</li>
						<li>Projects are indexed only if parent pro is published</li>
						<li>
							Rooms are indexed only if parent project and pro are published
						</li>
						<li>
							Blogs are indexed if editorial, or if the author pro is published
						</li>
					</ul>
				</Card>
			</section>
		</div>
	);
}