All files / src/pages/admin projects.tsx

98.18% Statements 54/55
90% Branches 45/50
100% Functions 21/21
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                                                                                    144x 144x   144x 144x         144x                       144x   144x 144x     144x 144x 105x 105x 92x   105x     144x   52x 52x   2x 1x         52x 52x                   144x       4x     144x 2x 2x 1x   1x       144x             12x                 1x   11x 11x 6x 5x 3x   2x   9x   2x       144x       144x                                 14x 13x             3x                                 380x                                             1x             2x               1x                 186x 186x                           12x                                                                                                                                                   2x                                                                                                
import { useCallback, useMemo } from "react";
import { Link } from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
import { Search, Eye, Image, FolderOpen, Star } 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 {
	STATUS_CODE_TYPE,
	STATUS_INK,
	STATUS_TINT,
} from "../../components/ui/status-ink";
import { adminApi, type Project, type Pro, getImageUrl } from "../../lib/api";
import { queryKeys } from "../../lib/query-keys";
import { cn, formatDate } from "../../lib/utils";
import { useListFilter } from "../../lib/admin-list-search";
import {
	useAdminProjectsList,
	useAdminProLookup,
} from "../../hooks/queries/useAdminQueries";
import { useConfirmDialog } from "../../hooks";
import { useSortable } from "../../hooks/useSortable";
import { SortableTableHead } from "../../components/admin/SortableTableHead";
import { Select } from "../../components/ui/select";
import {
	Table,
	TableBody,
	TableCaption,
	TableCell,
	TableHead,
	TableHeader,
	TableRow,
} from "../../components/ui/table";
import {
	AdminBand,
	AdminPageHead,
	AdminToolbar,
} from "../../components/admin/AdminPageHead";
 
export function AdminProjectsPage() {
	const queryClient = useQueryClient();
	const { confirm, dialog: confirmDialog } = useConfirmDialog();
	// Filters live in the URL so they survive opening a project and coming back (#1153).
	const [search, setSearch] = useListFilter("/admin/projects", "q", "");
	const [statusFilter, setStatusFilter] = useListFilter(
		"/admin/projects",
		"status",
		"",
	);
	const [sort, setSort] = useListFilter(
		"/admin/projects",
		"sort",
		"-dateCreated",
	);
 
	const {
		data,
		isLoading,
		isFetchingNextPage: isLoadingMore,
		hasNextPage: hasMore,
		fetchNextPage,
	} = useAdminProjectsList({ status: statusFilter, search });
 
	const projects = data?.pages?.flatMap((p) => p.data || []) ?? [];
	const total = data?.pages?.[0]?.meta?.total ?? 0;
 
	// Pro lookup for displaying pro names
	const { data: proList } = useAdminProLookup();
	const pros = useMemo(() => {
		const lookup: Record<string, Pro> = {};
		(proList || []).forEach((v) => {
			lookup[v.id] = v;
		});
		return lookup;
	}, [proList]);
 
	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: sortedProjects,
		sortKey,
		sortOrder,
		toggleSort,
	} = useSortable(
		projects,
		sort.replace(/^-/, "") as keyof Project,
		sort.startsWith("-") ? "desc" : "asc",
		(key, order) => setSort(`${order === "desc" ? "-" : ""}${String(key)}`),
	);
 
	const toggleFeatured = async (project: Project) => {
		try {
			await adminApi.setProjectFeatured(project.id, !project.isFeatured);
			queryClient.invalidateQueries({ queryKey: queryKeys.admin.projects.all });
		} catch (err) {
			console.error("Failed to toggle featured:", err);
		}
	};
 
	const updateStatus = async (
		project: Project,
		status: "draft" | "published" | "archived",
	) => {
		// Archiving pulls the project off the marketplace. 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 project",
				description: `Archive "${project.title}"? It is removed from the marketplace until it is published again.`,
				confirmLabel: "Archive project",
				variant: "destructive",
			}))
		) {
			return;
		}
		try {
			if (status === "published") {
				await adminApi.publishProject(project.id);
			} else if (status === "archived") {
				await adminApi.archiveProject(project.id);
			} else {
				await adminApi.updateProject(project.id, { status });
			}
			queryClient.invalidateQueries({ queryKey: queryKeys.admin.projects.all });
		} catch (err) {
			console.error("Failed to update status:", err);
		}
	};
 
	const handleSearch = () => {
		// Filters are reactive via useAdminProjectsList — search state change triggers refetch
	};
 
	return (
		<div className="space-y-6">
			<AdminPageHead
				title="Projects"
				description="Manage all projects on the platform."
			/>
 
			<AdminToolbar aria-label="Project filters">
				<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 projects..."
						aria-label="Search projects"
						value={search}
						onChange={(e) => setSearch(e.target.value)}
						onKeyDown={(e) => e.key === "Enter" && handleSearch()}
						className="pl-10"
					/>
				</div>
				<Select
					aria-label="Filter by status"
					value={statusFilter}
					onChange={(e) => setStatusFilter(e.target.value)}
					className="sm:w-44"
				>
					<option value="">All Statuses</option>
					<option value="draft">Draft</option>
					<option value="published">Published</option>
					<option value="archived">Archived</option>
				</Select>
				<Button onClick={handleSearch}>Search</Button>
			</AdminToolbar>
 
			<section className="space-y-2">
				<AdminBand title="Projects" 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>
				) : projects.length === 0 ? (
					<EmptyState
						icon={FolderOpen}
						title="No projects found"
						description="Try adjusting your search or filters."
					/>
				) : (
					<Card className="overflow-hidden">
						<Table density="dense">
							<TableCaption>
								{`Every project across every pro, ${sortedProjects.length} shown`}
							</TableCaption>
							<TableHeader>
								<TableRow>
									{/* Status leads, as it does in `projects-list.html`. */}
									<SortableTableHead
										label="Status"
										sortKey="status"
										currentSortKey={sortKey as string}
										sortOrder={sortOrder}
										onSort={(key) => toggleSort(key as keyof Project)}
									/>
									<SortableTableHead
										label="Project"
										sortKey="title"
										currentSortKey={sortKey as string}
										sortOrder={sortOrder}
										onSort={(key) => toggleSort(key as keyof Project)}
									/>
									<TableHead>Pro</TableHead>
									<SortableTableHead
										label="Created"
										sortKey="dateCreated"
										currentSortKey={sortKey as string}
										sortOrder={sortOrder}
										onSort={(key) => toggleSort(key as keyof Project)}
										numeric
									/>
									<TableHead>Featured</TableHead>
									<TableHead>Actions</TableHead>
								</TableRow>
							</TableHeader>
							<TableBody>
								{sortedProjects.map((project) => {
									const pro = pros[project.proId];
									return (
										<TableRow key={project.id}>
											<TableCell>
												{/*
												 * A printed code that is also the control that changes it — 2px
												 * radius, `.label` caps, status ink on its own tint, never a pill's
												 * full radius. The archive confirmation lives in `updateStatus`
												 * above, so it survives this shape.
												 */}
												<Select
													tier="dense"
													aria-label={`Status for ${project.title}`}
													value={project.status}
													onChange={(e) =>
														updateStatus(
															project,
															e.target.value as
																| "draft"
																| "published"
																| "archived",
														)
													}
													className={cn(
														"w-auto min-w-28 cursor-pointer rounded-sm border-transparent",
														STATUS_CODE_TYPE,
														project.status === "published"
															? `${STATUS_TINT.success} ${STATUS_INK.success}`
															: project.status === "draft"
																? `${STATUS_TINT.warning} ${STATUS_INK.warning}`
																: `${STATUS_TINT.default} ${STATUS_INK.default}`,
													)}
												>
													<option value="draft">Draft</option>
													<option value="published">Published</option>
													<option value="archived">Archived</option>
												</Select>
											</TableCell>
											<TableCell>
												<div className="flex items-center gap-3">
													{project.coverImage ? (
														<img
															src={getImageUrl(project.coverImage)}
															alt=""
															className="size-8 rounded-sm object-cover"
															loading="lazy"
														/>
													) : (
														<div className="flex size-8 items-center justify-center rounded-sm bg-background-muted">
															<Image className="h-4 w-4 text-foreground-subtle" />
														</div>
													)}
													<Link
														to={`/admin/projects/${project.id}`}
														className="font-medium text-foreground-default hover:text-primary-600"
													>
														{project.title}
													</Link>
												</div>
											</TableCell>
											<TableCell>
												{pro ? (
													<Link
														to={`/admin/pros/${pro.id}`}
														className="text-foreground-muted hover:text-primary-600"
													>
														{pro.businessName}
													</Link>
												) : (
													<span className="text-foreground-subtle">
														Unknown
													</span>
												)}
											</TableCell>
											{/* `en-IN` from one place. */}
											<TableCell
												numeric
												className="whitespace-nowrap text-foreground-muted"
											>
												{formatDate(project.dateCreated)}
											</TableCell>
											<TableCell>
												<button
													type="button"
													title={
														project.isFeatured
															? "Remove from featured"
															: "Add to featured"
													}
													onClick={() => toggleFeatured(project)}
													className="p-1 rounded hover:bg-background-muted transition-colors"
												>
													<Star
														className={`h-4 w-4 ${
															project.isFeatured
																? "fill-rating text-rating"
																: "text-foreground-subtle"
														}`}
													/>
												</button>
											</TableCell>
											<TableCell>
												<Link to={`/admin/projects/${project.id}`}>
													<Button variant="ghost" size="sm">
														<Eye className="h-4 w-4" />
														<span className="sr-only">View project</span>
													</Button>
												</Link>
											</TableCell>
										</TableRow>
									);
								})}
							</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 && projects.length > 0 && (
								<p className="text-xs font-semibold uppercase tracking-wider text-foreground-muted">
									No more projects
								</p>
							)}
						</div>
					</Card>
				)}
			</section>
 
			{confirmDialog}
		</div>
	);
}