All files / src/pages/admin imports-detail.tsx

100% Statements 55/55
84.31% Branches 43/51
100% Functions 26/26
100% Lines 51/51

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                            1x               23x 23x   23x 23x     23x 23x   23x   23x     23x     23x       23x 23x   19x       19x 2x           23x 15x 15x 10x 15x     23x 1x   22x 1x             21x   21x                                             1x               1x                             76x 76x 57x           9x                                             19x           3x     3x 3x                                           2x                                                       19x                               19x 19x               3x                                 1x                             19x   19x       19x       57x   19x 57x     19x                                     57x                                                            
import { useParams } from "@tanstack/react-router";
import { useMemo, useState } from "react";
import type {
	MaterializeSelection,
	ScrapedProject,
	TaxonomyMatch,
} from "../../lib/api/admin";
import {
	useAdminImport,
	useAdminImportEvents,
	useApproveImport,
	useCancelImport,
} from "../../hooks/queries/useAdminImports";
 
const PROFILE_FIELD_LABELS: Record<string, string> = {
	tagline: "Tagline",
	about: "About / description",
	whatsapp: "WhatsApp",
	email: "Email",
};
 
export function AdminImportsDetailPage() {
	const { importId } = useParams({ strict: false }) as { importId: string };
	const { data, isLoading, error } = useAdminImport(importId);
	const isRunning =
		data?.import.status === "queued" || data?.import.status === "running";
	const { data: eventsData } = useAdminImportEvents(importId, undefined, {
		refetchInterval: isRunning ? 2000 : false,
	});
	const approve = useApproveImport(importId);
	const cancel = useCancelImport(importId);
 
	const parsed = data?.yamlParsed?.ok ? data.yamlParsed.data : null;
 
	const [selectedFields, setSelectedFields] = useState<Set<string>>(
		new Set(),
	);
	const [selectedProjects, setSelectedProjects] = useState<Set<string>>(
		new Set(),
	);
	const [selectedPhotos, setSelectedPhotos] = useState<Set<string>>(
		new Set(),
	);
 
	const selection: MaterializeSelection = useMemo(
		() => ({
			profile: { fields: Array.from(selectedFields) },
			projects: (parsed?.projects ?? []).map((p) => ({
				scrapedSlug: p.slug,
				include: selectedProjects.has(p.slug),
				photos: p.photos
					.filter((ph) => selectedPhotos.has(`${p.slug}:${ph.file}`))
					.map((ph) => ph.file),
			})),
		}),
		[parsed, selectedFields, selectedProjects, selectedPhotos],
	);
 
	const toggle = <T,>(set: Set<T>, value: T) => {
		const next = new Set(set);
		if (next.has(value)) next.delete(value);
		else next.add(value);
		return next;
	};
 
	if (isLoading) {
		return <p className="p-6 text-stone-500">Loading…</p>;
	}
	if (error || !data) {
		return (
			<p className="p-6 text-red-600">
				{(error as Error)?.message ?? "Import not found"}
			</p>
		);
	}
 
	const row = data.import;
 
	return (
		<div className="p-6 max-w-6xl mx-auto">
			<div className="mb-6">
				<h1 className="text-2xl font-semibold text-stone-900">
					Import {row.id}
				</h1>
				<div className="flex flex-wrap items-center gap-3 text-sm text-stone-500 mt-1">
					<span>Status: <strong>{row.status}</strong></span>
					<span>Pro: {row.proBusinessName ? <strong>{row.proBusinessName}</strong> : <code>{row.proId}</code>}</span>
					<span>URL: <a href={row.sourceUrl} target="_blank" rel="noreferrer" className="text-orange-600 underline">{row.sourceUrl}</a></span>
				</div>
				{row.errorMessage && (
					<p className="mt-2 text-sm text-red-600">
						Error: {row.errorCode ? `[${row.errorCode}] ` : ""}{row.errorMessage}
					</p>
				)}
			</div>
 
			{isRunning && (
				<section className="mb-6 p-4 bg-blue-50 border border-blue-200 rounded">
					<h2 className="font-medium text-blue-900 mb-2">Live progress</h2>
					<ul className="space-y-1 text-sm text-blue-800 max-h-64 overflow-y-auto">
						{(eventsData?.events ?? []).map((evt) => (
							<li key={evt.id}>
								<span className="text-blue-500">[{evt.kind}]</span>{" "}
								{JSON.stringify(evt.payloadJson)}
							</li>
						))}
					</ul>
					<button
						type="button"
						onClick={() => cancel.mutate()}
						disabled={cancel.isPending}
						className="mt-3 px-3 py-1 text-sm border border-red-300 text-red-700 rounded hover:bg-red-50"
					>
						Cancel import
					</button>
				</section>
			)}
 
			{row.status === "completed" && parsed && (
				<>
					<section className="mb-6 bg-white border border-stone-200 rounded-lg p-4">
						<h2 className="font-medium text-stone-900 mb-3">Profile fields</h2>
						<div className="space-y-2">
							{Object.entries(PROFILE_FIELD_LABELS).map(([field, label]) => {
								const value = (parsed.pro as unknown as Record<string, unknown>)[field];
								if (value === "" || value == null) return null;
								return (
									<label key={field} className="flex items-start gap-2 text-sm">
										<input
											type="checkbox"
											checked={selectedFields.has(field)}
											onChange={() =>
												setSelectedFields((s) => toggle(s, field))
											}
											className="mt-1"
										/>
										<span>
											<strong>{label}:</strong> {String(value).slice(0, 200)}
										</span>
									</label>
								);
							})}
						</div>
					</section>
 
					{data.taxonomy && (
						<TaxonomySection taxonomy={data.taxonomy} />
					)}
 
					<section className="mb-6">
						<h2 className="font-medium text-stone-900 mb-3">
							Projects ({parsed.projects.length})
						</h2>
						<div className="space-y-4">
							{parsed.projects.map((p) => (
								<ProjectCard
									key={p.slug}
									project={p}
									isIncluded={selectedProjects.has(p.slug)}
									selectedPhotos={selectedPhotos}
									onToggleProject={() =>
										setSelectedProjects((s) => toggle(s, p.slug))
									}
									onTogglePhoto={(photoFile) =>
										setSelectedPhotos((s) =>
											toggle(s, `${p.slug}:${photoFile}`),
										)
									}
								/>
							))}
						</div>
					</section>
 
					<div className="flex justify-end gap-2">
						{approve.isError && (
							<span className="text-sm text-red-600 self-center">
								{(approve.error as Error).message}
							</span>
						)}
						{approve.isSuccess && (
							<span className="text-sm text-green-700 self-center">
								Approved: {approve.data?.projectsCreated} project(s),{" "}
								{approve.data?.photosCopied} photo(s)
							</span>
						)}
						<button
							type="button"
							onClick={() => approve.mutate(selection)}
							disabled={approve.isPending}
							className="px-4 py-2 bg-orange-600 text-white text-sm font-medium rounded-md hover:bg-orange-700 disabled:opacity-50"
						>
							{approve.isPending ? "Approving…" : "Approve selected"}
						</button>
					</div>
				</>
			)}
		</div>
	);
}
 
interface ProjectCardProps {
	project: ScrapedProject;
	isIncluded: boolean;
	selectedPhotos: Set<string>;
	onToggleProject: () => void;
	onTogglePhoto: (photoFile: string) => void;
}
 
function ProjectCard({
	project,
	isIncluded,
	selectedPhotos,
	onToggleProject,
	onTogglePhoto,
}: ProjectCardProps) {
	return (
		<div className="bg-white border border-stone-200 rounded-lg p-4">
			<label className="flex items-center gap-2 mb-2">
				<input
					type="checkbox"
					checked={isIncluded}
					onChange={onToggleProject}
				/>
				<span className="font-medium text-stone-900">{project.title}</span>
				<span className="text-xs text-stone-500">({project.slug})</span>
			</label>
			{project.description && (
				<p className="text-sm text-stone-600 mb-3">{project.description}</p>
			)}
			<div className="grid grid-cols-4 gap-2">
				{project.photos.map((photo) => {
					const key = `${project.slug}:${photo.file}`;
					return (
						<label
							key={photo.file}
							className="block text-xs cursor-pointer"
						>
							<input
								type="checkbox"
								checked={selectedPhotos.has(key)}
								onChange={() => onTogglePhoto(photo.file)}
								className="mb-1"
							/>
							<span className="block truncate" title={photo.file}>
								{photo.file.split("/").pop()}
							</span>
							{photo.isCover && (
								<span className="text-orange-600">★ cover</span>
							)}
						</label>
					);
				})}
			</div>
		</div>
	);
}
 
const REC_STYLES: Record<TaxonomyMatch["recommendation"], string> = {
	auto: "bg-green-100 text-green-700",
	review: "bg-amber-100 text-amber-700",
	unknown: "bg-stone-200 text-stone-600",
};
 
interface TaxonomySectionProps {
	taxonomy: {
		city: TaxonomyMatch | null;
		serviceAreas: TaxonomyMatch[];
		materials: TaxonomyMatch[];
	};
}
 
function TaxonomySection({ taxonomy }: TaxonomySectionProps) {
	const allMatches = [
		taxonomy.city ? { label: "Primary city", match: taxonomy.city } : null,
		...taxonomy.serviceAreas.map((m, i) => ({
			label: `Service area ${i + 1}`,
			match: m,
		})),
		...taxonomy.materials.map((m, i) => ({
			label: `Material ${i + 1}`,
			match: m,
		})),
	].filter((x): x is { label: string; match: TaxonomyMatch } => x !== null);
 
	const reviewable = allMatches.filter(
		(x) => x.match.recommendation !== "auto",
	);
 
	return (
		<section className="mb-6 bg-white border border-stone-200 rounded-lg p-4">
			<h2 className="font-medium text-stone-900 mb-1">Taxonomy review</h2>
			<p className="text-xs text-stone-500 mb-3">
				{allMatches.length} scraped label(s) mapped to taxonomy IDs.{" "}
				{reviewable.length} need your eye.
			</p>
			<table className="w-full text-sm">
				<thead>
					<tr className="text-left text-xs text-stone-500 uppercase">
						<th className="py-1">Label</th>
						<th className="py-1">Scraped text</th>
						<th className="py-1">Match</th>
						<th className="py-1">Score</th>
						<th className="py-1">Band</th>
					</tr>
				</thead>
				<tbody>
					{allMatches.map(({ label, match }) => (
						<tr
							key={`${label}::${match.candidate}`}
							className="border-t border-stone-100"
						>
							<td className="py-1 text-stone-700">{label}</td>
							<td className="py-1 text-stone-600">{match.candidate}</td>
							<td className="py-1 font-mono text-xs text-stone-500">
								{match.id ?? "—"}
							</td>
							<td className="py-1 text-stone-500">
								{(match.score * 100).toFixed(0)}%
							</td>
							<td className="py-1">
								<span
									className={`inline-block px-2 py-0.5 text-xs rounded ${
										REC_STYLES[match.recommendation]
									}`}
								>
									{match.recommendation}
								</span>
							</td>
						</tr>
					))}
				</tbody>
			</table>
		</section>
	);
}
 
export default AdminImportsDetailPage;