All files / routes/admin/blogs lifecycle.routes.ts

90.07% Statements 127/141
97.91% Branches 47/48
100% Functions 10/10
90% Lines 126/140

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                                                          2x     2x 9x 9x 9x     9x 9x 1x   8x 1x         7x   6x 1x       5x         9x 2x         2x 1x                 1x             5x 5x               5x 5x 5x             5x 5x   5x 5x                       5x                                                           5x   4x         2x 4x 4x 4x   3x 1x       2x 2x 2x             2x   2x         2x 4x 4x 4x 4x   4x 4x 1x     3x 3x 3x   3x 1x     2x           4x   4x 2x       2x 2x         2x   2x                 2x 8x 8x 8x 8x   8x 2x         6x 5x 1x     4x 4x 1x     3x                   3x 3x   1x 1x                                                 3x   5x         2x 4x 4x 4x 4x   4x 3x 1x     2x 2x 1x     1x   3x                 2x 6x 6x 6x 6x   6x 1x     5x 4x 1x     3x 3x 1x     2x             2x   4x         2x 5x 5x 5x 5x   5x 4x   4x 2x     2x 2x 1x     1x   4x          
// Blog lifecycle endpoints — publish / unpublish / cover upload — plus the
// blog-pros and blog-projects association mutations. Split out of
// admin/blogs/index.ts to keep the main file focused on core CRUD + barrel
// mounts.
 
import { Hono } from "hono";
import type { Dal } from "../../../dal";
import type { DualCache } from "../../../lib/cache";
import { invalidateEntity } from "../../../lib/cache-invalidation";
import { NotFoundError, ValidationError } from "../../../lib/errors";
import { validateUploadedFile } from "../../../lib/file-validation";
import { pingIndexNow } from "../../../lib/indexnow";
import { logger } from "../../../lib/logger";
import { handleError, success } from "../../../lib/response";
import { generateId } from "../../../lib/utils";
import { purgeEdgeCache } from "../../../lib/edge-cache";
import type { Services } from "../../../services";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
		cache: DualCache;
	};
};
 
const lifecycle = new Hono<Env>();
 
// Publish blog
lifecycle.post("/:id/publish", async (c) => {
	try {
		const dal = c.get("dal");
		const id = c.req.param("id");
 
		// Validate cover image before publishing
		const existing = await dal.blogs.findById(id);
		if (!existing) {
			throw new NotFoundError("Blog not found");
		}
		if (!existing.featuredImageUrl) {
			throw new ValidationError(
				"A cover image is required to publish. Please add a cover image first.",
			);
		}
 
		const blog = await dal.blogs.publish(id);
 
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Notify IndexNow that the blog post is live (no-op until secret is set).
		c.executionCtx.waitUntil(pingIndexNow(c.env, [`/blog/${blog.slug ?? id}`]));
 
		// Auto-add author attribution for the pro if the blog is associated
		// with a pro (ideaSourceProId) and no author entry exists yet.
		// This ensures the pro is always credited as author, not the admin.
		if (existing.ideaSourceProId) {
			const existingAuthors = await dal.blogPros.findAll({
				blogId: id,
				proId: existing.ideaSourceProId,
				attributionType: "author",
			});
			if (existingAuthors.length === 0) {
				await dal.blogPros.create({
					id: generateId(),
					blogId: id,
					proId: existing.ideaSourceProId,
					attributionType: "author",
					approvalStatus: "approved",
					approvalRequestedAt: new Date(),
					approvedAt: new Date(),
				});
				logger.info(
					`[Blog Publish] Auto-added author attribution for pro ${existing.ideaSourceProId} on blog ${id}`,
				);
			}
		}
 
		// Purge edge cache so the new blog appears in marketplace immediately
		try {
			c.executionCtx.waitUntil(
				purgeEdgeCache(`${c.env.BETTER_AUTH_URL}/api/marketplace/blogs`),
			);
		} catch {
			/* executionCtx unavailable in tests */
		}
 
		// Invalidate KV caches for the now-published blog.
		try {
			const cache = c.get("cache");
			c.executionCtx.waitUntil(
				invalidateEntity(cache, "blog", { slug: blog.slug }),
			);
		} catch {
			/* executionCtx unavailable in tests */
		}
 
		try {
			c.executionCtx.waitUntil(
				(async () => {
					try {
						const { CommunicationGateway } = await import(
							"../../../lib/communication/gateway"
						);
						const { BlogLifecycleHandler } = await import(
							"../../../lib/communication/handlers/blog-lifecycle.handler"
						);
						const gateway = new CommunicationGateway(dal, c.env);
						const handler = new BlogLifecycleHandler(gateway, dal);
						const blogProsMap = await dal.blogPros.findByBlogIds([id]);
						/* v8 ignore start -- V8 artifact: ?? fallback */
						const blogPros = blogProsMap.get(id) ?? [];
						/* v8 ignore stop */
						for (const bp of blogPros) {
							await handler.handlePublished({
								proId: bp.proId,
								blogId: id,
								blogTitle: blog.title,
							});
							try {
								await c.get("services").notification.notify({
									proId: bp.proId,
									eventType: "blog_published",
									title: "Your blog post has been published!",
									body: `"${blog.title}" is now live on the marketplace`,
									data: { url: `/blogs`, blogId: id },
								});
							} catch (notifErr) {
								logger.error(
									"[BLOG] Failed to send push notification:",
									notifErr,
								);
							}
						}
					} catch (err) {
						logger.error("[BLOG] Failed to send published notification:", err);
					}
				})(),
			);
		} catch {
			/* executionCtx unavailable in tests */
		}
 
		return success(c, blog);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Unpublish blog
lifecycle.post("/:id/unpublish", async (c) => {
	try {
		const dal = c.get("dal");
		const blog = await dal.blogs.unpublish(c.req.param("id"));
 
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Unpublished blogs must disappear from the marketplace list and detail cache.
		try {
			const cache = c.get("cache");
			c.executionCtx.waitUntil(
				invalidateEntity(cache, "blog", { slug: blog.slug }),
			);
		} catch {
			/* executionCtx unavailable in tests */
		}
 
		return success(c, blog);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Upload cover image for blog (admin)
lifecycle.post("/:id/upload-cover", async (c) => {
	try {
		const dal = c.get("dal");
		const r2 = c.env.R2;
		const blogId = c.req.param("id");
 
		const blog = await dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		const formData = await c.req.formData();
		const file = formData.get("file") as File | null;
		const altText = formData.get("altText") as string | null;
 
		if (!file) {
			throw new ValidationError("No file provided");
		}
 
		validateUploadedFile(file);
 
		// Store under admin path since there may be no associated pro
		/* v8 ignore start -- V8 artifact: || fallback */
		const ext = file.name.split(".").pop() || "jpg";
		/* v8 ignore stop */
		const filename = `admin/blogs/${blogId}/cover-${generateId()}.${ext}`;
 
		const arrayBuffer = await file.arrayBuffer();
		await r2.put(filename, arrayBuffer, {
			httpMetadata: { contentType: file.type },
		});
 
		const imageUrl = `/api/images/${filename}`;
		const updated = await dal.blogs.update(blogId, {
			featuredImageUrl: imageUrl,
			featuredImageAlt: altText || null,
		});
 
		return success(c, { blog: updated, imageUrl });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// ============================================================================
// BLOG PROS — association mutations
// ============================================================================
 
// Add pro to blog
lifecycle.post("/:id/pros", async (c) => {
	try {
		const dal = c.get("dal");
		const body = await c.req.json();
		const blogId = c.req.param("id");
 
		if (!body.proId || !body.attributionType) {
			throw new ValidationError(
				"Missing required fields: proId, attributionType",
			);
		}
 
		const blog = await dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		const pro = await dal.pros.findById(body.proId);
		if (!pro) {
			throw new NotFoundError("Pro not found");
		}
 
		const blogPro = await dal.blogPros.create({
			id: generateId(),
			blogId,
			proId: body.proId,
			attributionType: body.attributionType,
			approvalStatus: body.approvalStatus || "pending",
			approvalRequestedAt:
				body.approvalStatus === "pending" ? new Date() : null,
		});
 
		try {
			c.executionCtx.waitUntil(
				(async () => {
					try {
						const { CommunicationGateway } = await import(
							"../../../lib/communication/gateway"
						);
						const { BlogLifecycleHandler } = await import(
							"../../../lib/communication/handlers/blog-lifecycle.handler"
						);
						const gateway = new CommunicationGateway(dal, c.env);
						const handler = new BlogLifecycleHandler(gateway, dal);
						await handler.handleApprovalRequest({
							proId: body.proId,
							blogId,
							blogTitle: blog.title,
						});
					} catch (err) {
						logger.error(
							"[BLOG] Failed to send approval request notification:",
							err,
						);
					}
				})(),
			);
		} catch {
			/* executionCtx unavailable in tests */
		}
 
		return success(c, blogPro, 201);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Remove pro from blog
lifecycle.delete("/:id/pros/:proId", async (c) => {
	try {
		const dal = c.get("dal");
		const blogId = c.req.param("id");
		const proId = c.req.param("proId");
 
		const blogPros = await dal.blogPros.findAll({ blogId, proId });
		if (blogPros.length === 0) {
			throw new NotFoundError("Blog pro association not found");
		}
 
		const deleted = await dal.blogPros.delete(blogPros[0].id);
		if (!deleted) {
			throw new NotFoundError("Blog pro association not found");
		}
 
		return success(c, { message: "Pro removed from blog successfully" });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// ============================================================================
// BLOG PROJECTS — association mutations
// ============================================================================
 
// Add project to blog
lifecycle.post("/:id/projects", async (c) => {
	try {
		const dal = c.get("dal");
		const body = await c.req.json();
		const blogId = c.req.param("id");
 
		if (!body.projectId) {
			throw new ValidationError("Missing required field: projectId");
		}
 
		const blog = await dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		const project = await dal.projects.findById(body.projectId);
		if (!project) {
			throw new NotFoundError("Project not found");
		}
 
		const blogProject = await dal.blogProjects.create({
			id: generateId(),
			blogId,
			projectId: body.projectId,
			displayOrder: body.displayOrder ?? 0,
		});
 
		return success(c, blogProject, 201);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Remove project from blog
lifecycle.delete("/:id/projects/:projectId", async (c) => {
	try {
		const dal = c.get("dal");
		const blogId = c.req.param("id");
		const projectId = c.req.param("projectId");
 
		const blogProjects = await dal.blogProjects.findByBlogId(blogId);
		const blogProject = blogProjects.find((bp) => bp.projectId === projectId);
 
		if (!blogProject) {
			throw new NotFoundError("Blog project association not found");
		}
 
		const deleted = await dal.blogProjects.delete(blogProject.id);
		if (!deleted) {
			throw new NotFoundError("Blog project association not found");
		}
 
		return success(c, { message: "Project removed from blog successfully" });
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default lifecycle;