All files / src/pages/blogs my-blogs.tsx

88.29% Statements 83/94
91.8% Branches 56/61
92.59% Functions 25/27
87.64% Lines 78/89

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 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474                                                                        73x 73x 73x                   73x   73x 73x 51x   73x 51x 51x                 73x   73x 51x 50x 50x       49x           73x 51x 51x 51x                   73x   73x       73x 7x     73x 5x               1x     4x 4x 3x 3x   1x       73x 4x                 1x     3x 3x 2x 2x   1x           73x 1x                       1x 1x 1x 1x           73x                                         73x 1x 1x 1x         73x 51x 70x 70x 70x           73x 52x 52x 71x   52x 1x 1x   1x                   73x   73x       1x                           72x 1x                                   71x                                     1x                                                                       9x                 9x                                                                                       1x                                                                     2x 2x                                                                 57x                         2x                                
import { useState, useEffect, useCallback, useMemo } from "react";
import { Link } from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
import { notify } from "../../lib/notify";
import { StickyPageHeader } from "../../components/ui/sticky-page-header";
import {
	PlusCircle,
	FileText,
	Loader2,
	Search,
	LayoutGrid,
	List,
	FileEdit,
	Globe,
	Archive,
	ArrowUpDown,
	AlertCircle,
} from "lucide-react";
import { Button } from "../../components/ui/button";
import { Input } from "../../components/ui/input";
import { Skeleton } from "../../components/ui/skeleton";
import { FacetedFilter } from "../../components/ui/faceted-filter";
import { BlogCard } from "../../components/blogs/BlogCard";
import { BlogListItem } from "../../components/blogs/BlogListItem";
import { usePro } from "../../lib/pro-context";
import { GENERIC_ERROR_MESSAGE } from "../../lib/api";
import { proApi } from "../../lib/api/pro";
import { aiApi } from "../../lib/api/ai";
import type { GenerationJob } from "../../lib/api/ai";
import type { Blog } from "../../lib/api/blogs";
import { queryKeys } from "../../lib/query-keys";
import { useMyBlogs } from "../../hooks/queries/useBlogQueries";
import { useConfirmDialog } from "../../hooks";
import { useSortable } from "../../hooks/useSortable";
 
export function ProMyBlogsPage() {
	const { proId, pro, proRole } = usePro();
	const queryClient = useQueryClient();
	const { confirm, dialog: confirmDialog } = useConfirmDialog();
 
	// #361: the sidebar hides this route for staff (see sidebar.tsx line 45
	// roles allowlist), but the URL was still reachable and useMyBlogs() then
	// 403'd against `requireProManager` on `/api/pro/:proId/blogs/my-blogs`,
	// leaving the page stuck on "Failed to load blogs". Mirror the sidebar's
	// allowlist here so the manual URL shows an access-restricted message
	// instead of issuing a doomed fetch. Platform admin is included (the
	// middleware sets proRole="admin" for admin-acting-as-pro).
	const canAccessBlogs =
		proRole === "owner" || proRole === "manager" || proRole === "admin";
 
	const [searchQuery, setSearchQuery] = useState("");
	const [statusFilter, setStatusFilter] = useState<Set<string>>(
		() => new Set(["draft", "published"]),
	);
	const [viewMode, setViewMode] = useState<"grid" | "list">(() => {
		try {
			return (
				(localStorage.getItem("blogs-view-mode") as "grid" | "list") || "grid"
			);
		} catch {
			return "grid";
		}
	});
 
	// Active generation jobs (for resume-after-close UX)
	const [activeJobs, setActiveJobs] = useState<GenerationJob[]>([]);
 
	const pollJobs = useCallback(async () => {
		if (!proId || !canAccessBlogs) return;
		try {
			const result = await aiApi.listJobs(
				proId,
				"research,outlining,generating,images,seo,review",
			);
			setActiveJobs((result.jobs ?? []).filter((j) => j.status !== "failed"));
		} catch {
			// Silently fail — jobs banner is optional
		}
	}, [proId, canAccessBlogs]);
 
	useEffect(() => {
		pollJobs();
		const interval = setInterval(pollJobs, 5000);
		return () => clearInterval(interval);
	}, [pollJobs]);
 
	// Pass a null proId when the current role can't access blogs so the query
	// is disabled (see useMyBlogs: `enabled: !!proId`). Otherwise staff would
	// fire a doomed request that 403s against `requireProManager`.
	const {
		data: blogs = [],
		isLoading: loading,
		error: loadQueryError,
	} = useMyBlogs(canAccessBlogs ? proId : null);
 
	const loadError = loadQueryError
		? "Failed to load blogs. Please try again."
		: null;
 
	const invalidateBlogs = () => {
		queryClient.invalidateQueries({ queryKey: queryKeys.blogs.all });
	};
 
	const handlePublish = async (blogId: string) => {
		if (
			!(await confirm({
				title: "Publish blog",
				description: "Publish this blog?",
				confirmLabel: "Publish",
				variant: "default",
			}))
		) {
			return;
		}
 
		try {
			await proApi.submitMyBlog(proId as string, blogId);
			notify.success("Blog published successfully!");
			invalidateBlogs();
		} catch (_error) {
			notify.error(GENERIC_ERROR_MESSAGE);
		}
	};
 
	const handleArchive = async (blogId: string) => {
		if (
			!(await confirm({
				title: "Archive blog",
				description:
					"Archive this blog? It will be hidden from the public marketplace.",
				confirmLabel: "Archive",
				variant: "default",
			}))
		) {
			return;
		}
 
		try {
			await proApi.archiveMyBlog(proId as string, blogId);
			notify.success("Blog archived successfully");
			invalidateBlogs();
		} catch (_error) {
			notify.error(GENERIC_ERROR_MESSAGE);
		}
	};
 
	// #587: drafts can be deleted from the list. Published blogs must be
	// archived (not deleted) so we don't break marketplace links.
	const handleDelete = async (blogId: string) => {
		Iif (
			!(await confirm({
				title: "Delete draft",
				description:
					"Delete this draft blog? This action cannot be undone.",
				confirmLabel: "Delete",
				variant: "destructive",
			}))
		) {
			return;
		}
 
		try {
			await proApi.deleteMyBlog(proId as string, blogId);
			notify.success("Draft deleted");
			invalidateBlogs();
		} catch (_error) {
			notify.error(GENERIC_ERROR_MESSAGE);
		}
	};
 
	const handleUnarchive = async (blogId: string) => {
		if (
			!(await confirm({
				title: "Restore blog",
				description: "Restore this blog to published status?",
				confirmLabel: "Restore",
				variant: "default",
			}))
		) {
			return;
		}
 
		try {
			await proApi.unarchiveMyBlog(proId as string, blogId);
			notify.success("Blog restored to published");
			invalidateBlogs();
		} catch (_error) {
			notify.error(GENERIC_ERROR_MESSAGE);
		}
	};
 
	const handleViewModeChange = (mode: "grid" | "list") => {
		setViewMode(mode);
		try {
			localStorage.setItem("blogs-view-mode", mode);
		} catch {}
	};
 
	// Status counts for filter badges
	const statusCounts = useMemo(
		() => ({
			draft: blogs.filter((b) => b.status === "draft").length,
			published: blogs.filter((b) => b.status === "published").length,
			archived: blogs.filter((b) => b.status === "archived").length,
		}),
		[blogs],
	);
 
	// Client-side status + search filter
	const filteredBlogs = useMemo(() => {
		let result = blogs;
		Eif (statusFilter.size > 0) {
			result = result.filter((b) => statusFilter.has(b.status));
		}
		if (!searchQuery.trim()) return result;
		const q = searchQuery.toLowerCase();
		return result.filter(
			(p) =>
				p.title?.toLowerCase().includes(q) ||
				p.metaDescription?.toLowerCase().includes(q),
		);
	}, [blogs, statusFilter, searchQuery]);
 
	const {
		sorted: sortedBlogs,
		sortKey,
		sortOrder,
		setSort,
	} = useSortable(filteredBlogs, "dateUpdated" as keyof Blog, "desc");
 
	if (!canAccessBlogs) {
		// #361: deep-linked staff previously saw a "Failed to load blogs" toast.
		// Give them the same access-restricted message the rest of the portal uses
		// for role-gated surfaces instead of a broken-state screen.
		return (
			<div className="max-w-xl mx-auto py-16 text-center">
				<FileText className="h-10 w-10 mx-auto mb-3 text-foreground-subtle" />
				<h1 className="text-lg font-semibold text-foreground-default">
					Blog management is limited to owners and managers
				</h1>
				<p className="text-sm text-foreground-muted mt-2">
					Ask an owner or manager on your team to publish blog posts. You can
					still browse all other sections of the portal.
				</p>
			</div>
		);
	}
 
	if (loading) {
		return (
			<div className="space-y-6">
				<div className="flex items-center justify-between">
					<div className="space-y-2">
						<Skeleton className="h-8 w-32" />
						<Skeleton className="h-4 w-64" />
					</div>
					<Skeleton className="h-10 w-32" />
				</div>
				<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
					<Skeleton className="h-64 w-full" />
					<Skeleton className="h-64 w-full" />
					<Skeleton className="h-64 w-full" />
				</div>
			</div>
		);
	}
 
	return (
		<div className="space-y-6">
			<StickyPageHeader>
				<div className="flex items-center justify-between w-full">
					<h1 className="text-2xl font-bold text-foreground-default flex items-center gap-2 flex-shrink-0">
						<FileText className="h-6 w-6" />
						Blog Posts
					</h1>
					<div className="flex items-center gap-2">
						<div className="hidden sm:inline-flex items-center h-9 rounded-lg bg-background-muted p-0.5">
							<button
								type="button"
								onClick={() => handleViewModeChange("grid")}
								className={`inline-flex items-center justify-center rounded-md px-2.5 h-8 transition-all ${viewMode === "grid" ? "bg-background-elevated shadow-sm text-foreground-default" : "text-foreground-muted hover:text-foreground-default"}`}
							>
								<LayoutGrid className="h-4 w-4" />
							</button>
							<button
								type="button"
								onClick={() => handleViewModeChange("list")}
								className={`inline-flex items-center justify-center rounded-md px-2.5 h-8 transition-all ${viewMode === "list" ? "bg-background-elevated shadow-sm text-foreground-default" : "text-foreground-muted hover:text-foreground-default"}`}
							>
								<List className="h-4 w-4" />
							</button>
						</div>
						<Link to="/blogs/new">
							<Button size="sm">
								<PlusCircle className="h-4 w-4" />
								New Blog Post
							</Button>
						</Link>
					</div>
				</div>
			</StickyPageHeader>
 
			{/* Unpublished Pro Warning */}
			{pro && pro.status !== "published" && (
				<div className="flex items-start gap-3 rounded-lg border border-amber-200 bg-amber-50 p-4">
					<AlertCircle className="h-5 w-5 text-amber-600 mt-0.5 flex-shrink-0" />
					<div>
						<h3 className="font-medium text-amber-800">
							Your profile is not yet published
						</h3>
						<p className="mt-1 text-sm text-amber-700">
							Blogs you publish will not appear on the marketplace until your
							profile is approved and published.
						</p>
					</div>
				</div>
			)}
 
			{/* AI Generation Jobs Banner */}
			{activeJobs.length > 0 && (
				<div className="space-y-2">
					{activeJobs.map((job) => {
						const stepLabels: Record<string, string> = {
							research: "Researching trends",
							outlining: "Creating outline",
							generating: "Writing content",
							images: "Finding images",
							seo: "Optimizing SEO",
							review: "Final review",
						};
 
						return (
							<div
								key={job.id}
								className="flex items-center justify-between gap-4 px-4 py-3 rounded-lg border bg-primary-500/10 border-primary-500/30"
							>
								<div className="flex items-center gap-3">
									<Loader2 className="h-4 w-4 text-primary-600 animate-spin flex-shrink-0" />
									<span className="text-sm font-medium text-foreground-default">
										{stepLabels[job.status] || "Generating"}... (Step{" "}
										{job.currentStep} of {job.totalSteps})
										{job.title && (
											<span className="text-foreground-muted ml-2">
												— {job.title}
											</span>
										)}
									</span>
								</div>
							</div>
						);
					})}
				</div>
			)}
 
			{loadError && (
				<div className="p-4 bg-notification-error-bg border border-notification-error-border rounded-lg text-notification-error-text flex items-center justify-between">
					<span>{loadError}</span>
					<button
						type="button"
						onClick={invalidateBlogs}
						className="text-sm underline hover:no-underline"
					>
						Retry
					</button>
				</div>
			)}
 
			{/* Search & Faceted Filters */}
			{blogs.length > 0 && (
				<div className="space-y-2 sm:space-y-0 sm:flex sm:flex-wrap sm:items-center sm:gap-2">
					<div className="relative w-full sm:min-w-0 sm:flex-1 sm:basis-40 sm:max-w-sm">
						<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-foreground-subtle" />
						<Input
							placeholder="Filter blogs..."
							value={searchQuery}
							onChange={(e) => setSearchQuery(e.target.value)}
							className="pl-10"
						/>
					</div>
					<div className="flex items-center gap-2">
						<FacetedFilter
							title="Status"
							options={[
								{
									value: "draft",
									label: "Draft",
									icon: <FileEdit className="h-4 w-4" />,
									count: statusCounts.draft,
								},
								{
									value: "published",
									label: "Published",
									icon: <Globe className="h-4 w-4" />,
									count: statusCounts.published,
								},
								{
									value: "archived",
									label: "Archived",
									icon: <Archive className="h-4 w-4" />,
									count: statusCounts.archived,
								},
							]}
							selected={statusFilter}
							onChange={setStatusFilter}
						/>
						<div className="relative shrink-0">
							<ArrowUpDown className="absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-foreground-subtle pointer-events-none" />
							<select
								value={`${sortKey as string}-${sortOrder}`}
								onChange={(e) => {
									const [key, order] = e.target.value.split("-");
									setSort(key as keyof Blog, order as "asc" | "desc");
								}}
								className="h-9 rounded-md border border-dashed border-border-default bg-transparent pl-8 pr-3 text-sm font-medium cursor-pointer hover:bg-background-muted transition-colors focus:outline-none focus:ring-2 focus:ring-primary-500/40 focus:border-primary-500 appearance-none"
							>
								<option value="dateUpdated-desc">Newest</option>
								<option value="dateUpdated-asc">Oldest</option>
								<option value="title-asc">A → Z</option>
								<option value="title-desc">Z → A</option>
							</select>
						</div>
					</div>
				</div>
			)}
 
			{/* Blog Grid / List */}
			{sortedBlogs.length === 0 && blogs.length > 0 ? (
				<div className="py-12 text-center text-foreground-muted">
					No blogs match your{" "}
					{searchQuery.trim() ? "search" : "filter"}.
				</div>
			) : sortedBlogs.length === 0 ? (
				<div className="text-center py-12">
					<FileText className="h-12 w-12 text-foreground-subtle mx-auto mb-4" />
					<p className="text-foreground-subtle mb-4">
						You haven't created any blog posts yet
					</p>
					<Link to="/blogs/new">
						<Button>Create Your First Blog Post</Button>
					</Link>
				</div>
			) : viewMode === "grid" ? (
				<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 sm:gap-6">
					{sortedBlogs.map((blog) => (
						<BlogCard
							key={blog.id}
							blog={blog}
							onPublish={handlePublish}
							onArchive={handleArchive}
							onUnarchive={handleUnarchive}
							onDelete={handleDelete}
						/>
					))}
				</div>
			) : (
				<div className="space-y-2">
					{sortedBlogs.map((blog) => (
						<BlogListItem
							key={blog.id}
							blog={blog}
							onPublish={handlePublish}
							onArchive={handleArchive}
							onUnarchive={handleUnarchive}
							onDelete={handleDelete}
						/>
					))}
				</div>
			)}
 
			{confirmDialog}
		</div>
	);
}