All files / src/pages/admin projects.tsx

98% Statements 49/50
88.09% Branches 37/42
100% Functions 20/20
100% Lines 47/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 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                                                    134x 134x 134x               134x   134x 134x     134x 134x 103x 103x 90x   103x     134x   51x 51x   2x 1x         51x 51x         134x           134x 2x 2x 1x   1x       134x       11x 11x 6x 5x 3x   2x   9x   2x       134x       134x                                         14x 13x           3x                                           375x                                           2x               1x             1x               159x 159x                                                                                         11x                                                               2x                                                                                            
import { useState, 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,
	CardContent,
	CardHeader,
	CardTitle,
} from "../../components/ui/card";
import { Button } from "../../components/ui/button";
import { EmptyState } from "../../components/ui/empty-state";
import { Input } from "../../components/ui/input";
import {
	adminApi,
	type Project,
	type Pro,
	getImageUrl,
} from "../../lib/api";
import { queryKeys } from "../../lib/query-keys";
import { useAdminProjectsList, useAdminProLookup } from "../../hooks/queries/useAdminQueries";
import { useSortable } from "../../hooks/useSortable";
import { SortableHeader } from "../../components/ui/sortable-header";
 
export function AdminProjectsPage() {
	const queryClient = useQueryClient();
	const [search, setSearch] = useState("");
	const [statusFilter, setStatusFilter] = useState<string>("");
 
	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,
		"dateCreated" as keyof Project,
		"desc",
	);
 
	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",
	) => {
		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">
				{/* Header */}
				<div>
					<h1 className="text-2xl font-bold text-foreground-default">
						Projects
					</h1>
					<p className="text-foreground-muted">
						Manage all projects on the platform.
					</p>
				</div>
 
				{/* Filters */}
				<Card>
					<CardContent className="pt-6">
						<div className="flex flex-col sm:flex-row gap-4">
							<div className="relative flex-1">
								<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-foreground-subtle" />
								<Input
									placeholder="Search projects..."
									value={search}
									onChange={(e) => setSearch(e.target.value)}
									onKeyDown={(e) => e.key === "Enter" && handleSearch()}
									className="pl-10"
								/>
							</div>
							<select
								value={statusFilter}
								onChange={(e) => setStatusFilter(e.target.value)}
								className="h-10 rounded-md border border-border-default bg-background-elevated px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary-500/40 focus:border-primary-500"
							>
								<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>
						</div>
					</CardContent>
				</Card>
 
				{/* Table */}
				<Card>
					<CardHeader>
						<CardTitle className="text-lg">{total} Projects</CardTitle>
					</CardHeader>
					<CardContent>
						{isLoading ? (
							<div className="space-y-4">
								{[1, 2, 3, 4, 5].map((i) => (
									<div
										key={i}
										className="h-16 bg-background-muted rounded animate-pulse"
									/>
								))}
							</div>
						) : projects.length === 0 ? (
							<EmptyState
								icon={FolderOpen}
								title="No projects found"
								description="Try adjusting your search or filters."
							/>
						) : (
							<div className="overflow-x-auto -mx-6 px-6">
								<table className="w-full min-w-[700px]">
									<thead>
										<tr className="border-b text-left text-sm text-foreground-muted">
											<SortableHeader
												label="Project"
												sortKey="title"
												currentSortKey={sortKey as string}
												sortOrder={sortOrder}
												onSort={(key) => toggleSort(key as keyof Project)}
											/>
											<th className="pb-3 font-medium">Pro</th>
											<SortableHeader
												label="Status"
												sortKey="status"
												currentSortKey={sortKey as string}
												sortOrder={sortOrder}
												onSort={(key) => toggleSort(key as keyof Project)}
											/>
											<SortableHeader
												label="Created"
												sortKey="dateCreated"
												currentSortKey={sortKey as string}
												sortOrder={sortOrder}
												onSort={(key) => toggleSort(key as keyof Project)}
											/>
											<th className="pb-3 font-medium">Featured</th>
											<th className="pb-3 font-medium">Actions</th>
										</tr>
									</thead>
									<tbody>
										{sortedProjects.map((project) => {
											const pro = pros[project.proId];
											return (
												<tr
													key={project.id}
													className="border-b last:border-0 hover:bg-background-muted"
												>
													<td className="py-4">
														<div className="flex items-center gap-3">
															{project.coverImage ? (
																<img
																	src={getImageUrl(project.coverImage)}
																	alt=""
																	className="w-12 h-12 rounded object-cover"
																	loading="lazy"
																/>
															) : (
																<div className="w-12 h-12 rounded bg-background-muted flex items-center justify-center">
																	<Image className="h-5 w-5 text-foreground-subtle" />
																</div>
															)}
															<Link
																to={`/admin/projects/${project.id}`}
																className="font-medium text-foreground-default hover:text-primary-600"
															>
																{project.title}
															</Link>
														</div>
													</td>
													<td className="py-4">
														{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>
														)}
													</td>
													<td className="py-4">
														<select
															value={project.status}
															onChange={(e) =>
																updateStatus(
																	project,
																	e.target.value as
																		| "draft"
																		| "published"
																		| "archived",
																)
															}
															className={`text-xs font-medium rounded-full px-3 py-1.5 border-0 cursor-pointer focus:outline-none focus:ring-2 focus:ring-primary-500/40 focus:border-primary-500 ${
																project.status === "published"
																	? "bg-green-100 text-green-800"
																	: project.status === "draft"
																		? "bg-yellow-100 text-yellow-800"
																		: "bg-background-muted text-foreground-default"
															}`}
														>
															<option value="draft">Draft</option>
															<option value="published">Published</option>
															<option value="archived">Archived</option>
														</select>
													</td>
													<td className="py-4 text-foreground-muted">
														{new Date(project.dateCreated).toLocaleDateString()}
													</td>
													<td className="py-4">
														<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-yellow-500 text-yellow-500"
																		: "text-foreground-subtle"
																}`}
															/>
														</button>
													</td>
													<td className="py-4">
														<Link to={`/admin/projects/${project.id}`}>
															<Button variant="ghost" size="sm">
																<Eye className="h-4 w-4" />
															</Button>
														</Link>
													</td>
												</tr>
											);
										})}
									</tbody>
								</table>
 
								{/* Infinite scroll trigger */}
								<div
									ref={loadMoreRef}
									className="h-10 flex items-center justify-center"
								>
									{isLoadingMore && (
										<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary-600" />
									)}
									{!hasMore && projects.length > 0 && (
										<p className="text-sm text-foreground-muted">
											No more projects
										</p>
									)}
								</div>
							</div>
						)}
					</CardContent>
				</Card>
			</div>
	);
}