All files / src/pages/admin/blogs edit.tsx

92.5% Statements 111/120
74.22% Branches 72/97
87.5% Functions 21/24
92.03% Lines 104/113

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                                                                197x 197x 197x 197x 197x     197x 197x 197x 197x 197x     197x 197x 197x 197x 197x 197x 197x 197x 197x 197x 197x 197x 197x 197x     197x 197x 56x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x     54x 54x 4x               4x           197x                               197x                       197x               197x 3x 2x       197x 1x     197x 1x   1x         197x 5x 4x       197x 1x     197x 1x 1x   1x     197x 10x 2x 2x     8x 8x 8x                           7x 7x   1x   8x       197x 6x         1x   5x 5x   5x                           5x 4x 4x 4x   1x   5x       197x 6x         1x   5x 5x 5x 4x 4x 4x   1x 1x       197x                   197x 59x             138x               138x                                                                               1x                                                                  
import { useState, useEffect, useRef, useCallback } from "react";
import { useNavigate, useParams } from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
import { notify } from "../../../lib/notify";
import { BlogProSelector } from "../../../components/admin/blogs/BlogProSelector";
import { BlogProjectSelector } from "../../../components/admin/blogs/BlogProjectSelector";
import { Card } from "../../../components/ui/card";
import { GENERIC_ERROR_MESSAGE } from "../../../lib/api";
import { adminApi } from "../../../lib/api/admin";
import { queryKeys } from "../../../lib/query-keys";
import { useAdminBlog, useAdminBlogCategories, useAdminBlogTags } from "../../../hooks/queries/useAdminBlogQueries";
import { useCities } from "../../../hooks/queries/useTaxonomyQueries";
import type { BlogType, BlogPro, ApprovalStatus } from "../../../lib/api/blogs";
import type { Pro, Project } from "../../../lib/api/pro";
import type { AttributionType } from "../../../lib/api/blogs";
import { useConfirmDialog } from "../../../hooks";
import { useAutoSave } from "../../../hooks/useAutoSave";
import { UnifiedBlogEditor } from "../../../components/blogs/UnifiedBlogEditor";
 
interface SelectedPro {
	pro: Pro;
	attributionType: AttributionType;
	approvalStatus?: ApprovalStatus;
}
 
// Extended blog response from GET /api/admin/blogs/:id (includes related data)
interface BlogWithRelations {
	pros?: BlogPro[];
	[key: string]: unknown;
}
 
export function AdminBlogEditPage() {
	const navigate = useNavigate();
	const queryClient = useQueryClient();
	const { id } = useParams({ from: "/_adminLayout/admin/blogs/$id/edit" });
	const { confirm, dialog: confirmDialog } = useConfirmDialog();
	const [saving, setSaving] = useState(false);
 
	// Query hooks for data fetching
	const { data: blog, isLoading: blogLoading } = useAdminBlog(id);
	const { data: categories = [], isLoading: categoriesLoading } = useAdminBlogCategories();
	const { data: availableTags = [], isLoading: tagsLoading } = useAdminBlogTags();
	const { data: cities = [], isLoading: citiesLoading } = useCities();
	const loading = blogLoading || categoriesLoading || tagsLoading || citiesLoading;
 
	// Form state
	const [title, setTitle] = useState("");
	const [slug, setSlug] = useState("");
	const [metaDescription, setMetaDescription] = useState("");
	const [content, setContent] = useState("");
	const [blogType, setBlogType] = useState<BlogType>("general");
	const [primaryKeyword, setPrimaryKeyword] = useState("");
	const [secondaryKeywords, setSecondaryKeywords] = useState<string[]>([]);
	const [categoryId, setCategoryId] = useState("");
	const [cityId, setCityId] = useState("");
	const [coverImageUrl, setCoverImageUrl] = useState<string | null>(null);
	const [coverImageAlt, setCoverImageAlt] = useState("");
	const [tagIds, setTagIds] = useState<string[]>([]);
	const [selectedPros, setSelectedPros] = useState<SelectedPro[]>([]);
	const [selectedProjects, setSelectedProjects] = useState<Project[]>([]);
 
	// Initialize form from query data (one-time)
	const formInitialized = useRef(false);
	useEffect(() => {
		if (blog && !formInitialized.current) {
			formInitialized.current = true;
			setTitle(blog.title);
			setSlug(blog.slug);
			setMetaDescription(blog.metaDescription || "");
			setContent(blog.content || "");
			setBlogType(blog.blogType);
			setPrimaryKeyword(blog.primaryKeyword || "");
			setSecondaryKeywords(blog.secondaryKeywords || []);
			setCategoryId(blog.categoryId || "");
			setCityId(blog.cityId || "");
			setCoverImageUrl(blog.featuredImageUrl || null);
			setCoverImageAlt(blog.featuredImageAlt || "");
			setTagIds(blog.tags?.map((t) => t.id) || []);
 
			// Initialize selectedPros from blog's associated pros
			const blogData = blog as unknown as BlogWithRelations;
			if (blogData.pros && Array.isArray(blogData.pros)) {
				const prosFromBlog: SelectedPro[] = blogData.pros.map((bp) => ({
					pro: {
						id: bp.proId,
						businessName: (bp as Record<string, unknown>).name as string || bp.proId,
					} as Pro,
					attributionType: bp.attributionType,
					approvalStatus: bp.approvalStatus,
				}));
				setSelectedPros(prosFromBlog);
			}
		}
	}, [blog]);
 
	// Auto-save
	const getData = useCallback(
		() => ({
			title,
			content,
			slug,
			metaDescription,
			blogType,
			primaryKeyword,
			secondaryKeywords,
			categoryId,
			cityId,
			tagIds,
		}),
		[title, content, slug, metaDescription, blogType, primaryKeyword, secondaryKeywords, categoryId, cityId, tagIds],
	);
 
	const saveFn = useCallback(
		async (data: Record<string, unknown>) => {
			await adminApi.updateBlog(id, data as {
				title: string;
				content: string;
				blogType: BlogType;
				[key: string]: unknown;
			});
		},
		[id],
	);
 
	const { saveStatus, lastSavedAt } = useAutoSave({
		blogId: formInitialized.current ? id : null,
		proId: "admin",
		getData,
		saveFn,
		enabled: formInitialized.current && blog?.status === "draft",
	});
 
	const handleAddPro = (pro: Pro, attributionType: AttributionType) => {
		if (!selectedPros.find((sv) => sv.pro.id === pro.id)) {
			setSelectedPros([...selectedPros, { pro, attributionType }]);
		}
	};
 
	const handleRemovePro = (proId: string) => {
		setSelectedPros(selectedPros.filter((sv) => sv.pro.id !== proId));
	};
 
	const handleUpdateAttributionType = (proId: string, attributionType: AttributionType) => {
		setSelectedPros(
			selectedPros.map((sv) =>
				sv.pro.id === proId ? { ...sv, attributionType } : sv,
			),
		);
	};
 
	const handleAddProject = (project: Project) => {
		if (!selectedProjects.find((p) => p.id === project.id)) {
			setSelectedProjects([...selectedProjects, project]);
		}
	};
 
	const handleRemoveProject = (projectId: string) => {
		setSelectedProjects(selectedProjects.filter((p) => p.id !== projectId));
	};
 
	const handleReorderProjects = (projectIds: string[]) => {
		const reordered = projectIds
			.map((pid) => selectedProjects.find((p) => p.id === pid))
			.filter(Boolean) as Project[];
		setSelectedProjects(reordered);
	};
 
	const handleSave = async () => {
		if (!title.trim()) {
			notify.error("Title is required");
			return;
		}
 
		try {
			setSaving(true);
			await adminApi.updateBlog(id, {
				title,
				slug: slug || undefined,
				metaDescription: metaDescription || undefined,
				content: content || undefined,
				blogType,
				primaryKeyword: primaryKeyword || undefined,
				secondaryKeywords: secondaryKeywords.length > 0 ? secondaryKeywords : undefined,
				categoryId: categoryId || undefined,
				cityId: cityId || undefined,
				featuredImageUrl: coverImageUrl ?? undefined,
				featuredImageAlt: coverImageAlt || undefined,
				tagIds,
			});
			await queryClient.invalidateQueries({ queryKey: queryKeys.admin.blogs.all });
			notify.success("Changes saved!");
		} catch {
			notify.error(GENERIC_ERROR_MESSAGE);
		} finally {
			setSaving(false);
		}
	};
 
	const handlePublish = async () => {
		if (!(await confirm({
			title: "Publish blog",
			description: "Publish this blog? It will be visible on the marketplace.",
			confirmLabel: "Publish",
			variant: "default",
		}))) return;
 
		try {
			setSaving(true);
			// Save latest changes first
			await adminApi.updateBlog(id, {
				title,
				slug: slug || undefined,
				metaDescription: metaDescription || undefined,
				content: content || undefined,
				blogType,
				primaryKeyword: primaryKeyword || undefined,
				secondaryKeywords: secondaryKeywords.length > 0 ? secondaryKeywords : undefined,
				categoryId: categoryId || undefined,
				cityId: cityId || undefined,
				featuredImageUrl: coverImageUrl ?? undefined,
				featuredImageAlt: coverImageAlt || undefined,
				tagIds,
			});
			await adminApi.publishBlog(id);
			await queryClient.invalidateQueries({ queryKey: queryKeys.admin.blogs.all });
			notify.success("Blog published!");
			navigate({ to: "/admin/blogs" });
		} catch {
			notify.error(GENERIC_ERROR_MESSAGE);
		} finally {
			setSaving(false);
		}
	};
 
	const handleDelete = async () => {
		if (!(await confirm({
			title: "Delete blog",
			description: "Are you sure you want to delete this blog?",
			confirmLabel: "Delete",
			variant: "destructive",
		}))) return;
 
		try {
			setSaving(true);
			await adminApi.deleteBlog(id);
			await queryClient.invalidateQueries({ queryKey: queryKeys.admin.blogs.all });
			notify.success("Blog deleted");
			navigate({ to: "/admin/blogs" });
		} catch {
			notify.error(GENERIC_ERROR_MESSAGE);
			setSaving(false);
		}
	};
 
	const handleUploadCover = async (file: File): Promise<string> => {
		const result = await adminApi.uploadBlogCover(id, file);
		if (result.data) {
			const data = result.data as { imageUrl: string };
			setCoverImageUrl(data.imageUrl);
			return data.imageUrl;
		}
		throw new Error("Failed to upload cover image");
	};
 
	if (loading || !formInitialized.current) {
		return (
			<div className="flex items-center justify-center h-96">
				<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600" />
			</div>
		);
	}
 
	Iif (!blog) {
		return (
			<div className="text-center py-12">
				<p className="text-foreground-subtle">Blog not found</p>
			</div>
		);
	}
 
	return (
		<>
			<UnifiedBlogEditor
				mode="admin"
				blogId={id}
				proId={selectedPros[0]?.pro?.id}
				title={title}
				onTitleChange={setTitle}
				slug={slug}
				onSlugChange={setSlug}
				content={content}
				onContentChange={setContent}
				metaDescription={metaDescription}
				onMetaDescriptionChange={setMetaDescription}
				primaryKeyword={primaryKeyword}
				onPrimaryKeywordChange={setPrimaryKeyword}
				blogType={blogType}
				onBlogTypeChange={setBlogType}
				coverImageUrl={coverImageUrl}
				onCoverImageChange={setCoverImageUrl}
				coverImageAlt={coverImageAlt}
				onCoverImageAltChange={setCoverImageAlt}
				categoryId={categoryId}
				onCategoryChange={setCategoryId}
				cityId={cityId}
				onCityChange={setCityId}
				secondaryKeywords={secondaryKeywords}
				onSecondaryKeywordsChange={setSecondaryKeywords}
				categories={categories}
				cities={cities}
				tagIds={tagIds}
				onTagIdsChange={setTagIds}
				availableTags={availableTags}
				status={blog.status}
				saveStatus={saveStatus}
				lastSavedAt={lastSavedAt}
				onSave={handleSave}
				onPublish={blog.status !== "published" ? handlePublish : undefined}
				onDelete={handleDelete}
				saving={saving}
				onBack={() => navigate({ to: "/admin/blogs" })}
				onUploadCover={handleUploadCover}
				adminPanels={
					<div className="mt-6 space-y-6">
						<Card>
							<div className="p-6">
								<h2 className="text-lg font-semibold mb-4">Featured Pros</h2>
								<BlogProSelector
									selectedPros={selectedPros}
									onAdd={handleAddPro}
									onRemove={handleRemovePro}
									onUpdateAttributionType={handleUpdateAttributionType}
								/>
							</div>
						</Card>
						<Card>
							<div className="p-6">
								<h2 className="text-lg font-semibold mb-4">Featured Projects</h2>
								<BlogProjectSelector
									selectedProjects={selectedProjects}
									onAdd={handleAddProject}
									onRemove={handleRemoveProject}
									onReorder={handleReorderProjects}
								/>
							</div>
						</Card>
					</div>
				}
			/>
			{confirmDialog}
		</>
	);
}