All files / src/pages/admin pros.tsx

92% Statements 46/50
84.21% Branches 32/38
84.21% Functions 16/19
93.61% Lines 44/47

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                                                                  155x 155x       155x 155x             155x         155x 155x               155x           155x 155x   155x   56x 56x   2x 1x         56x 56x                   155x             155x 3x 3x 2x   1x       155x             5x                 1x   4x 4x 2x 2x 1x   1x   3x   1x       155x       155x           7x                                                     14x 11x             6x                     1x                         410x                                                                           145x                                                           2x              
import { useState, useCallback } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { Search, Plus, Store } from "lucide-react";
 
import { Card } from "../../components/ui/card";
import { Button } from "../../components/ui/button";
import { EmptyState } from "../../components/ui/empty-state";
import { Input } from "../../components/ui/input";
import { Checkbox } from "../../components/ui/checkbox";
import { Select } from "../../components/ui/select";
import {
	Table,
	TableBody,
	TableCaption,
	TableHead,
	TableHeader,
	TableRow,
} from "../../components/ui/table";
import { CreateProModal, ProTableRow } from "../../components/admin/pros";
import { adminApi, type Pro } from "../../lib/api";
import { queryKeys } from "../../lib/query-keys";
import { useListFilter } from "../../lib/admin-list-search";
import { useAdminProsList } from "../../hooks/queries/useAdminQueries";
import { useConfirmDialog } from "../../hooks";
import { useSortable } from "../../hooks/useSortable";
import { SortableTableHead } from "../../components/admin/SortableTableHead";
import {
	AdminBand,
	AdminPageHead,
	AdminToolbar,
} from "../../components/admin/AdminPageHead";
 
export function AdminProsPage() {
	const queryClient = useQueryClient();
	const { confirm, dialog: confirmDialog } = useConfirmDialog();
	// Filters live in the URL so they survive opening a pro and coming back
	// (#1153). Issue #613: the dashboard "Pros pending publish" tile deep-links
	// here with ?status=draft.
	const [search, setSearch] = useListFilter("/admin/pros", "q", "");
	const [statusFilter, setStatusFilter] = useListFilter(
		"/admin/pros",
		"status",
		"",
	);
	// Issue #593: hide partially-created onboarding records by default so the
	// admin list isn't cluttered with rows that have no business name.
	const [showIncomplete, setShowIncomplete] = useListFilter(
		"/admin/pros",
		"incomplete",
		false,
	);
	const [sort, setSort] = useListFilter("/admin/pros", "sort", "businessName");
	const [showNewPro, setShowNewPro] = useState(false);
 
	const {
		data,
		isLoading,
		isFetchingNextPage: isLoadingMore,
		hasNextPage: hasMore,
		fetchNextPage,
	} = useAdminProsList({
		status: statusFilter,
		search,
		includeIncomplete: showIncomplete,
	});
 
	const pros = data?.pages?.flatMap((p) => p.data || []) ?? [];
	const total = data?.pages?.[0]?.meta?.total ?? 0;
 
	const loadMoreRef = useCallback(
		(node: HTMLDivElement | null) => {
			Iif (!node) return;
			const observer = new IntersectionObserver(
				(entries) => {
					if (entries[0].isIntersecting && hasMore && !isLoadingMore) {
						fetchNextPage();
					}
				},
				{ threshold: 0.1 },
			);
			observer.observe(node);
			return () => observer.disconnect();
		},
		[hasMore, isLoadingMore, fetchNextPage],
	);
 
	const {
		sorted: sortedPros,
		sortKey,
		sortOrder,
		toggleSort,
	} = useSortable(
		pros,
		sort.replace(/^-/, "") as keyof Pro,
		sort.startsWith("-") ? "desc" : "asc",
		(key, order) => setSort(`${order === "desc" ? "-" : ""}${String(key)}`),
	);
 
	const toggleFeatured = async (pro: Pro) => {
		try {
			await adminApi.setProFeatured(pro.id, !pro.isFeatured);
			queryClient.invalidateQueries({ queryKey: queryKeys.admin.pros.all });
		} catch (err) {
			console.error("Failed to toggle featured:", err);
		}
	};
 
	const updateStatus = async (
		pro: Pro,
		status: "draft" | "published" | "archived",
	) => {
		// Archiving disables the pro and takes their listing down. The status
		// dropdown makes it a one-click move, so confirm the commit (the control
		// itself is left as-is).
		if (
			status === "archived" &&
			!(await confirm({
				title: "Archive pro",
				description: `Archive ${pro.businessName || "this pro"}? Their listing is taken off the marketplace until they are published again.`,
				confirmLabel: "Archive pro",
				variant: "destructive",
			}))
		) {
			return;
		}
		try {
			if (status === "published") {
				await adminApi.enablePro(pro.id);
			} else if (status === "archived") {
				await adminApi.disablePro(pro.id);
			} else {
				await adminApi.updatePro(pro.id, { status });
			}
			queryClient.invalidateQueries({ queryKey: queryKeys.admin.pros.all });
		} catch (err) {
			console.error("Failed to update status:", err);
		}
	};
 
	const handleSearch = () => {
		// Filters are reactive via useAdminProsList — search state change triggers refetch
	};
 
	return (
		<div className="space-y-6">
			<AdminPageHead
				title="Pros"
				description="Manage all pros on the platform."
				actions={
					<Button onClick={() => setShowNewPro(true)}>
						<Plus aria-hidden="true" />
						Add Pro
					</Button>
				}
			/>
 
			{/* A filter strip is a toolbar, not a boxed card. */}
			<AdminToolbar
				aria-label="Pro filters"
				note={
					<>
						To approve a pro's website, find their row below and change their{" "}
						<strong>Publish status</strong> from <em>Draft</em> to{" "}
						<em>Published</em>.
					</>
				}
			>
				<div className="relative min-w-56 grow">
					<Search
						aria-hidden="true"
						className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-foreground-subtle"
					/>
					<Input
						placeholder="Search pros..."
						aria-label="Search pros"
						value={search}
						onChange={(e) => setSearch(e.target.value)}
						onKeyDown={(e) => e.key === "Enter" && handleSearch()}
						className="pl-10"
					/>
				</div>
				<Select
					aria-label="Filter by publish status"
					value={statusFilter}
					onChange={(e) => setStatusFilter(e.target.value)}
					className="sm:w-56"
				>
					<option value="">All publish statuses</option>
					<option value="draft">Draft (waiting for approval)</option>
					<option value="published">Published</option>
					<option value="archived">Archived</option>
				</Select>
				<Button onClick={handleSearch}>Search</Button>
				<Checkbox
					checked={showIncomplete}
					onChange={(e) => setShowIncomplete(e.target.checked)}
				>
					Show incomplete profiles (no name set)
				</Checkbox>
			</AdminToolbar>
 
			{/* The ruled band carries the count. No pill, no card title. */}
			<section className="space-y-2">
				<AdminBand title="Pros" count={total} quiet />
 
				{isLoading ? (
					<div className="space-y-px">
						{[1, 2, 3, 4, 5].map((i) => (
							<div key={i} className="h-12 animate-pulse bg-background-muted" />
						))}
					</div>
				) : pros.length === 0 ? (
					<EmptyState
						icon={Store}
						title="No pros found"
						description="Try adjusting your search or filters."
					/>
				) : (
					<Card className="overflow-hidden">
						<Table density="dense">
							<TableCaption>
								{`Every pro on the platform, ${sortedPros.length} shown`}
							</TableCaption>
							<TableHeader>
								<TableRow>
									<SortableTableHead
										label="Publish status"
										sortKey="status"
										currentSortKey={sortKey as string}
										sortOrder={sortOrder}
										onSort={(key) => toggleSort(key as keyof Pro)}
									/>
									<SortableTableHead
										label="Business Name"
										sortKey="businessName"
										currentSortKey={sortKey as string}
										sortOrder={sortOrder}
										onSort={(key) => toggleSort(key as keyof Pro)}
									/>
									<TableHead>Location</TableHead>
									<TableHead>Featured</TableHead>
									<TableHead>Actions</TableHead>
								</TableRow>
							</TableHeader>
							<TableBody>
								{sortedPros.map((pro) => (
									<ProTableRow
										key={pro.id}
										pro={pro}
										onToggleFeatured={toggleFeatured}
										onUpdateStatus={updateStatus}
									/>
								))}
							</TableBody>
						</Table>
 
						{/* Infinite scroll trigger */}
						<div
							ref={loadMoreRef}
							className="flex h-10 items-center justify-center border-t border-border-default"
						>
							{isLoadingMore && (
								<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary-600" />
							)}
							{!hasMore && pros.length > 0 && (
								<p className="text-xs font-semibold uppercase tracking-wider text-foreground-muted">
									No more pros
								</p>
							)}
						</div>
					</Card>
				)}
			</section>
 
			<CreateProModal
				isOpen={showNewPro}
				onClose={() => setShowNewPro(false)}
			/>
 
			{confirmDialog}
		</div>
	);
}