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

98.07% Statements 102/104
90.14% Branches 64/71
100% Functions 27/27
97.89% Lines 93/95

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                                                    59x 59x 59x           59x 1x     59x 30x         1x             5x 22x           29x 5x       1x   2x         2x               24x       67x 67x 67x 67x     67x 67x 67x     67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x   67x 5x 4x       67x 1x     67x 1x   1x         67x 4x 3x       67x 1x     67x 1x 2x   1x       67x   67x 8x   1x                         1x       7x 7x                             6x   6x 6x     6x 1x             5x             5x     67x 8x 1x 1x     7x 7x 7x 5x 5x   5x   2x   7x       67x   2x 2x 2x 1x   1x   1x 1x 1x 1x 1x         67x                                                                     1x                                                              
import { useState, useCallback } from "react";
import { useNavigate } from "@tanstack/react-router";
import { useQueryClient } from "@tanstack/react-query";
import { ArrowLeft } from "lucide-react";
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 { useAdminBlogCategories, useAdminBlogTags } from "../../../hooks/queries/useAdminBlogQueries";
import { useCities } from "../../../hooks/queries/useTaxonomyQueries";
import type { BlogType } from "../../../lib/api/blogs";
import type { Pro, Project } from "../../../lib/api/pro";
import type { AttributionType } from "../../../lib/api/blogs";
import { UnifiedBlogEditor } from "../../../components/blogs/UnifiedBlogEditor";
import { BlogStartChoiceScreen } from "../../../components/blogs/BlogStartChoiceScreen";
import { AdminAIPreStep } from "../../../components/admin/blogs/AdminAIPreStep";
 
interface SelectedPro {
	pro: Pro;
	attributionType: AttributionType;
}
 
export function AdminBlogCreatePage() {
	const navigate = useNavigate();
	const [view, setView] = useState<"choice" | "ai" | "scratch">("choice");
	const [prefill, setPrefill] = useState<{
		title?: string;
		blogType?: string;
		primaryKeyword?: string;
	} | null>(null);
 
	const handleDraftCreated = (blogId: string) => {
		navigate({ to: "/admin/blogs/$id/edit", params: { id: blogId } });
	};
 
	if (view === "choice") {
		return (
			<div className="max-w-5xl mx-auto">
				<div className="flex items-center gap-4 mb-6">
					<button
						type="button"
						onClick={() => navigate({ to: "/admin/blogs" })}
						className="p-2 hover:bg-background-muted rounded-md"
					>
						<ArrowLeft className="h-5 w-5" />
					</button>
				</div>
				<BlogStartChoiceScreen
					onStartWithAI={() => setView("ai")}
					onStartFromScratch={() => setView("scratch")}
				/>
			</div>
		);
	}
 
	if (view === "ai") {
		return (
			<div className="max-w-5xl mx-auto">
				<AdminAIPreStep
					onDraftCreated={handleDraftCreated}
					onBack={() => setView("choice")}
					onUseAsStartingPoint={(suggestion) => {
						setPrefill({
							title: suggestion.title,
							blogType: suggestion.blog_type,
							primaryKeyword: suggestion.primary_keyword,
						});
						setView("scratch");
					}}
				/>
			</div>
		);
	}
 
	// view === "scratch"
	return <AdminBlogCreateScratch prefill={prefill} />;
}
 
function AdminBlogCreateScratch({ prefill }: { prefill?: { title?: string; blogType?: string; primaryKeyword?: string } | null }) {
	const navigate = useNavigate();
	const queryClient = useQueryClient();
	const [saving, setSaving] = useState(false);
	const [blogId, setBlogId] = useState<string | null>(null);
 
	// Query hooks
	const { data: categories = [] } = useAdminBlogCategories();
	const { data: availableTags = [] } = useAdminBlogTags();
	const { data: cities = [] } = useCities();
 
	// Form state
	const [title, setTitle] = useState(prefill?.title ?? "");
	const [slug, setSlug] = useState("");
	const [metaDescription, setMetaDescription] = useState("");
	const [content, setContent] = useState("");
	const [blogType, setBlogType] = useState<BlogType>((prefill?.blogType as BlogType) ?? "general");
	const [primaryKeyword, setPrimaryKeyword] = useState(prefill?.primaryKeyword ?? "");
	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[]>([]);
 
	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);
	};
 
	// Determine ideaSource based on selected pros
	const hasAuthorPro = selectedPros.some((sp) => sp.attributionType === "author");
 
	const createOrUpdateBlog = useCallback(async (): Promise<string> => {
		if (blogId) {
			// Update existing draft
			await adminApi.updateBlog(blogId, {
				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,
			});
			return blogId;
		}
 
		// Create new blog
		const authorPro = selectedPros.find((sp) => sp.attributionType === "author");
		const result = await adminApi.createBlog({
			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,
			ideaSource: hasAuthorPro ? "pro_request" : "editorial",
			ideaSourceProId: authorPro?.pro?.id || undefined,
			tagIds: tagIds.length > 0 ? tagIds : undefined,
		});
 
		Iif (!result.data) throw new Error("Failed to create blog");
 
		const newId = result.data.id;
		setBlogId(newId);
 
		// Add pros
		for (const sv of selectedPros) {
			await adminApi.addBlogPro(newId, {
				proId: sv.pro.id,
				attributionType: sv.attributionType,
			});
		}
 
		// Add projects
		for (let i = 0; i < selectedProjects.length; i++) {
			await adminApi.addBlogProject(newId, {
				projectId: selectedProjects[i].id,
				displayOrder: i,
			});
		}
 
		return newId;
	}, [blogId, title, slug, metaDescription, content, blogType, primaryKeyword, secondaryKeywords, categoryId, cityId, coverImageUrl, coverImageAlt, selectedPros, selectedProjects, hasAuthorPro, tagIds]);
 
	const handleSave = async () => {
		if (!title.trim()) {
			notify.error("Title is required");
			return;
		}
 
		try {
			setSaving(true);
			const createdId = await createOrUpdateBlog();
			await queryClient.invalidateQueries({ queryKey: queryKeys.admin.blogs.all });
			notify.success("Draft saved!");
			// Navigate to edit page so auto-save kicks in
			navigate({ to: "/admin/blogs/$id/edit", params: { id: createdId } });
		} catch {
			notify.error(GENERIC_ERROR_MESSAGE);
		} finally {
			setSaving(false);
		}
	};
 
	const handleUploadCover = async (file: File): Promise<string> => {
		// Need to create blog first if it doesn't exist
		let targetBlogId = blogId;
		Eif (!targetBlogId) {
			if (!title.trim()) {
				throw new Error("Please enter a title before uploading a cover image");
			}
			targetBlogId = await createOrUpdateBlog();
		}
		const result = await adminApi.uploadBlogCover(targetBlogId, file);
		Eif (result.data) {
			const data = result.data as { imageUrl: string };
			setCoverImageUrl(data.imageUrl);
			return data.imageUrl;
		}
		throw new Error("Failed to upload cover image");
	};
 
	return (
		<UnifiedBlogEditor
			mode="admin"
			blogId={blogId || "new"}
			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="draft"
			onSave={handleSave}
			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>
			}
		/>
	);
}