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

100% Statements 56/56
84.9% Branches 45/53
100% Functions 26/26
100% Lines 52/52

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                                                              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             1x                                 19x   19x       19x       57x   19x 57x     19x                                         57x                                                          
import { useParams } from "@tanstack/react-router";
import { useMemo, useState } from "react";
import { STATUS_BAND_TINT, STATUS_INK } from "../../components/ui/status-ink";
import type { StatusTone } from "../../components/ui/status-ink";
import { AdminBand, AdminPageHead } from "../../components/admin/AdminPageHead";
import { Alert } from "../../components/ui/alert";
import { Button } from "../../components/ui/button";
import { Card } from "../../components/ui/card";
import { StatusBadge } from "../../components/ui/status-badge";
import type {
	MaterializeSelection,
	ScrapedProject,
	TaxonomyMatch,
} from "../../lib/api/admin";
import {
	useAdminImport,
	useAdminImportEvents,
	useApproveImport,
	useCancelImport,
} from "../../hooks/queries/useAdminImports";
import { Checkbox } from "../../components/ui/checkbox";
import {
	Table,
	TableBody,
	TableCaption,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "../../components/ui/table";
 
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="text-xs font-semibold uppercase tracking-wider text-foreground-muted">
				Loading…
			</p>
		);
	}
	if (error || !data) {
		return (
			<Alert variant="error">
				{(error as Error)?.message ?? "Import not found"}
			</Alert>
		);
	}
 
	const row = data.import;
 
	return (
		<div className="space-y-6">
			<AdminPageHead
				title={
					<>
						<span className="font-mono">Import {row.id}</span>
						{/* State is a printed code, not a bolded word in a sentence. */}
						<StatusBadge
							status={row.status}
							variant={IMPORT_STATUS_TONES[row.status] ?? "default"}
						/>
					</>
				}
			>
				{/* `.spec` rows: the read-only facts of this import, ruled. */}
				<dl className="mb-3 space-y-0 text-sm">
					<div className="grid grid-cols-[8.5rem_minmax(0,1fr)] gap-3 border-t border-border-default py-1.5">
						<dt className="text-foreground-muted">Pro</dt>
						<dd className="min-w-0 truncate text-foreground-default">
							{row.proBusinessName ?? (
								<span className="font-mono">{row.proId}</span>
							)}
						</dd>
					</div>
					<div className="grid grid-cols-[8.5rem_minmax(0,1fr)] gap-3 border-t border-border-default py-1.5">
						<dt className="text-foreground-muted">Source URL</dt>
						<dd className="min-w-0 truncate">
							<a
								href={row.sourceUrl}
								target="_blank"
								rel="noreferrer"
								className="text-primary-600 underline"
							>
								{row.sourceUrl}
							</a>
						</dd>
					</div>
				</dl>
				{row.errorMessage && (
					<Alert variant="error" className="mb-3">
						{row.errorCode ? `[${row.errorCode}] ` : ""}
						{row.errorMessage}
					</Alert>
				)}
			</AdminPageHead>
 
			{isRunning && (
				<section className={`rounded-md p-4 ${STATUS_BAND_TINT.info}`}>
					<h2
						className={`mb-2 text-xs font-semibold uppercase tracking-wider ${STATUS_INK.info}`}
					>
						Live progress
					</h2>
					<ul className="max-h-64 space-y-1 overflow-y-auto font-mono text-xs text-foreground-default">
						{(eventsData?.events ?? []).map((evt) => (
							<li key={evt.id}>
								<span className={STATUS_INK.info}>[{evt.kind}]</span>{" "}
								{JSON.stringify(evt.payloadJson)}
							</li>
						))}
					</ul>
					<Button
						variant="outline"
						size="sm"
						className="mt-3"
						onClick={() => cancel.mutate()}
						disabled={cancel.isPending}
					>
						Cancel import
					</Button>
				</section>
			)}
 
			{row.status === "completed" && parsed && (
				<>
					<section className="space-y-2">
						<AdminBand title="Profile fields" quiet />
						<div className="space-y-2 rounded-lg border border-border-default bg-background-elevated p-4">
							{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 (
									<Checkbox
										key={field}
										className="mt-1 self-start"
										checked={selectedFields.has(field)}
										onChange={() => setSelectedFields((s) => toggle(s, field))}
									>
										<strong>{label}:</strong> {String(value).slice(0, 200)}
									</Checkbox>
								);
							})}
						</div>
					</section>
 
					{data.taxonomy && <TaxonomySection taxonomy={data.taxonomy} />}
 
					<section className="space-y-2">
						<AdminBand title="Projects" count={parsed.projects.length} quiet />
						<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-error self-center">
								{(approve.error as Error).message}
							</span>
						)}
						{approve.isSuccess && (
							<span className="text-sm text-success self-center">
								Approved: {approve.data?.projectsCreated} project(s),{" "}
								{approve.data?.photosCopied} photo(s)
							</span>
						)}
						<Button
							onClick={() => approve.mutate(selection)}
							disabled={approve.isPending}
						>
							{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-background-elevated border border-border-default rounded-lg p-4">
			<Checkbox
				className="mb-2"
				checked={isIncluded}
				onChange={onToggleProject}
			>
				<span className="font-medium text-foreground-default">
					{project.title}
				</span>{" "}
				<span className="text-xs text-foreground-muted">({project.slug})</span>
			</Checkbox>
			{project.description && (
				<p className="text-sm text-foreground-muted mb-3">
					{project.description}
				</p>
			)}
			<div className="grid grid-cols-4 gap-2">
				{project.photos.map((photo) => {
					const key = `${project.slug}:${photo.file}`;
					return (
						<div key={photo.file} className="text-xs">
							<Checkbox
								className="mb-1"
								checked={selectedPhotos.has(key)}
								onChange={() => onTogglePhoto(photo.file)}
							>
								<span className="block truncate" title={photo.file}>
									{photo.file.split("/").pop()}
								</span>
							</Checkbox>
							{photo.isCover && (
								<span className="text-primary-600">★ cover</span>
							)}
						</div>
					);
				})}
			</div>
		</div>
	);
}
 
/**
 * A taxonomy match's recommendation is a printed code. This page decides the
 * tone only; `StatusBadge` owns the shape and the ink/tint pair.
 */
const REC_TONES: Record<TaxonomyMatch["recommendation"], StatusTone> = {
	auto: "success",
	review: "warning",
	unknown: "default",
};
 
/** An import's status, as a tone. `StatusBadge` prints it. */
const IMPORT_STATUS_TONES: Record<string, StatusTone> = {
	queued: "default",
	running: "info",
	completed: "success",
	failed: "error",
	cancelled: "default",
};
 
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="space-y-2">
			<AdminBand title="Taxonomy review" count={reviewable.length} quiet />
			<p className="text-xs text-foreground-muted">
				{allMatches.length} scraped label(s) mapped to taxonomy IDs.{" "}
				{reviewable.length} need your eye.
			</p>
			<Card className="overflow-hidden">
				<Table density="dense">
					<TableCaption>The taxonomy values this import matched.</TableCaption>
					<TableHeader>
						<TableRow className="uppercase">
							<TableHead>Label</TableHead>
							<TableHead>Scraped text</TableHead>
							<TableHead>Match</TableHead>
							<TableHead numeric>Score</TableHead>
							<TableHead>Band</TableHead>
						</TableRow>
					</TableHeader>
					<TableBody>
						{allMatches.map(({ label, match }) => (
							<TableRow key={`${label}::${match.candidate}`}>
								<TableCell className="text-foreground-default">
									{label}
								</TableCell>
								<TableCell className="text-foreground-muted">
									{match.candidate}
								</TableCell>
								<TableCell className="font-mono text-xs text-foreground-muted">
									{match.id ?? "—"}
								</TableCell>
								<TableCell numeric className="text-foreground-muted">
									{(match.score * 100).toFixed(0)}%
								</TableCell>
								<TableCell>
									<StatusBadge
										status={match.recommendation}
										variant={REC_TONES[match.recommendation]}
									/>
								</TableCell>
							</TableRow>
						))}
					</TableBody>
				</Table>
			</Card>
		</section>
	);
}
 
export default AdminImportsDetailPage;