All files / routes/pro/blogs my-blogs.routes.ts

97.08% Statements 200/206
98% Branches 147/150
94.11% Functions 16/17
97.05% Lines 198/204

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 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603                                                                          8x 8x 2x           27x       6x     1x                     1x                         1x     1x     1x 4x 4x 4x 4x   4x 1x     3x 3x   1x         1x 9x 9x 9x 9x   9x 1x     8x     8x 6x       6x     9x 6x 1x 1x       6x                             5x       5x   4x 1x   3x         1x 6x 6x 6x   6x 1x     5x 6x   6x 6x   6x     6x           6x         4x           2x         1x 5x 5x 5x   5x 1x     4x   4x 4x 1x       3x       2x       1x         1x           4x         1x 14x 14x 14x   14x 1x     13x 13x   13x 12x 1x       11x       1x       10x 1x           9x 2x       8x                                                 8x 2x     2x 2x 2x             8x   6x 1x   5x         1x 4x 4x 4x   4x 1x     3x   3x 3x 1x       2x       1x     1x   1x   3x         1x 5x 5x 5x   5x 1x     4x   4x 4x 1x       3x       1x       2x 1x     1x       1x   4x         1x 5x 5x 5x   5x 1x     4x   4x 4x 1x       3x       1x       2x 1x     1x       1x   4x         1x 13x 13x 13x   13x 1x     12x   12x 12x 1x       11x       1x       10x 1x       9x 1x           8x 13x 1x         7x     7x             6x         6x 5x                       6x         6x   6x 6x 6x 2x 2x             2x 1x           1x       2x                   6x         7x         1x                     1x 4x 4x 4x   4x 4x 2x         2x     2x 2x 1x     1x           1x   2x          
// Pro Blog Authoring Routes (Create/Edit their own blogs)
import { Hono } from "hono";
import type { Dal } from "../../../dal";
import type { Services } from "../../../services";
import {
	success,
	successWithPagination,
	handleError,
} from "../../../lib/response";
import { buildPaginationMeta, generateId, generateSlug } from "../../../lib/utils";
import {
	ValidationError,
	NotFoundError,
	ForbiddenError,
	BadRequestError,
} from "../../../lib/errors";
import { requireProManager } from "../../../middleware";
import * as schema from "../../../db/schema";
import { eq } from "drizzle-orm";
import { z } from "zod";
import { purgeEdgeCache } from "../../../lib/edge-cache";
import { checkBlogWordLimit } from "@interioring/utils/validation/blog";
import { logger } from "../../../lib/logger";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
		proId: string;
		proRole: string;
	};
};
 
function assertBlogWordLimit(content: string) {
	const result = checkBlogWordLimit(content);
	if (!result.withinLimit) {
		throw new ValidationError(result.message ?? "Blog content exceeds the word limit.");
	}
}
 
/** Blog idea sources that indicate a pro created/owns the blog */
function isProOwnedBlog(ideaSource: string | null): boolean {
	return ideaSource === "pro_request" || ideaSource === "ai_suggestion";
}
 
function sanitizeHtml(html: string): string {
	return html.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "");
}
 
const createBlogSchema = z.object({
	title: z.string().min(1, "Title is required").max(200),
	slug: z.string().max(200).optional(),
	content: z.string().max(50000).optional(),
	metaDescription: z.string().max(500).optional().nullable(),
	blogType: z.enum(["general", "project_spotlight", "hybrid"]).optional(),
	primaryKeyword: z.string().max(100).optional().nullable(),
	secondaryKeywords: z.array(z.string().max(100)).max(10).optional(),
	ideaSource: z.enum(["pro_request", "ai_suggestion", "editorial"]).optional(),
});
 
const updateBlogSchema = z.object({
	title: z.string().min(1).max(200).optional(),
	slug: z.string().max(200).optional(),
	content: z.string().max(50000).optional(),
	metaDescription: z.string().max(500).optional().nullable(),
	blogType: z.enum(["general", "project_spotlight", "hybrid"]).optional(),
	primaryKeyword: z.string().max(100).optional().nullable(),
	secondaryKeywords: z.array(z.string().max(100)).max(10).optional(),
	featuredImageUrl: z.string().max(500).optional().nullable(),
	featuredImageAlt: z.string().max(200).optional().nullable(),
	tagIds: z.array(z.string()).max(20).optional(),
});
 
const myBlogs = new Hono<Env>();
 
// Apply pro access middleware to all routes
myBlogs.use("*", requireProManager);
 
// Check blog slug availability
myBlogs.get("/my-blogs/check-slug", async (c) => {
	try {
		const dal = c.get("dal");
		const slug = c.req.query("slug");
		const excludeId = c.req.query("excludeId");
 
		if (!slug) {
			throw new ValidationError("slug query parameter is required");
		}
 
		const exists = await dal.blogs.slugExists(slug, excludeId || undefined);
		return success(c, { available: !exists });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Create a new blog (pro-authored)
myBlogs.post("/my-blogs", async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.get("proId");
		const user = c.get("user");
 
		if (!proId || !user) {
			throw new ForbiddenError("Pro ID and user required");
		}
 
		const body = createBlogSchema.parse(await c.req.json());
 
		// Validate word limit
		if (body.content) {
			assertBlogWordLimit(body.content);
		}
 
		// Generate slug from title if not provided
		let slug = body.slug || body.title.toLowerCase().replace(/\s+/g, "-");
 
		// Auto-suffix on slug collision instead of throwing an error
		const slugExists = await dal.blogs.slugExists(slug);
		if (slugExists) {
			const suffix = generateId().slice(0, 6);
			slug = `${slug}-${suffix}`;
		}
 
		// Create blog
		const blog = await dal.blogs.create({
			id: generateId(),
			title: body.title,
			slug,
			content: body.content ? sanitizeHtml(body.content) : "",
			metaDescription: body.metaDescription || null,
			blogType: body.blogType || "general",
			primaryKeyword: body.primaryKeyword || null,
			secondaryKeywords: body.secondaryKeywords || [],
			status: "draft", // Pro blogs start as drafts
			createdBy: user.id,
			ideaSource: body.ideaSource || "pro_request",
			ideaSourceProId: proId,
		});
 
		logger.info(
			`[Pro Blog Create] Created blog ${blog.id} by pro ${proId}`,
		);
 
		return success(c, blog, 201);
	} catch (err) {
		if (err instanceof z.ZodError) {
			return handleError(c, new BadRequestError(`Validation failed: ${err.issues.map((e) => e.message).join(", ")}`));
		}
		return handleError(c, err);
	}
});
 
// Get my authored blogs
myBlogs.get("/my-blogs", async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.get("proId");
 
		if (!proId) {
			throw new ForbiddenError("Pro ID required");
		}
 
		const limitParam = Number(c.req.query("limit") || 20);
		const safeLimit = Math.min(100, Math.max(1, limitParam));
 
		const page = Math.max(1, Number(c.req.query("page") || 1));
		const offset = (page - 1) * safeLimit;
 
		const status = c.req.query("status")?.split(",");
 
		// Find blogs created by this pro (manual or AI-generated)
		const filters = {
			ideaSourceProId: proId,
			ideaSource: ["pro_request", "ai_suggestion"],
			status,
		};
 
		const [blogs, total] = await Promise.all([
			dal.blogs.findAll(filters, offset, safeLimit),
			dal.blogs.count(filters),
		]);
 
		return successWithPagination(
			c,
			blogs,
			buildPaginationMeta(total, page, safeLimit),
		);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Get single blog I authored
myBlogs.get("/my-blogs/:id", async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.get("proId");
 
		if (!proId) {
			throw new ForbiddenError("Pro ID required");
		}
 
		const blogId = c.req.param("id");
 
		const blog = await dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Verify pro owns this blog (pro_request = manual, ai_suggestion = AI pipeline)
		if (
			blog.ideaSourceProId !== proId ||
			!isProOwnedBlog(blog.ideaSource)
		) {
			throw new ForbiddenError("You do not have access to this blog");
		}
 
		// Fetch related data
		const [tags, projects] = await Promise.all([
			dal.blogTags.findByBlogId(blog.id),
			dal.blogProjects.findByBlogId(blog.id),
		]);
 
		return success(c, {
			...blog,
			tags,
			projects,
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Update my blog
myBlogs.put("/my-blogs/:id", async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.get("proId");
 
		if (!proId) {
			throw new ForbiddenError("Pro ID required");
		}
 
		const blogId = c.req.param("id");
		const body = updateBlogSchema.parse(await c.req.json());
 
		const blog = await dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Verify pro owns this blog (pro_request = manual, ai_suggestion = AI pipeline)
		if (
			blog.ideaSourceProId !== proId ||
			!isProOwnedBlog(blog.ideaSource)
		) {
			throw new ForbiddenError("You do not have access to this blog");
		}
 
		// Only allow editing if status is draft, rejected, or published
		if (!["draft", "rejected", "published"].includes(blog.status)) {
			throw new ValidationError(
				"Can only edit blogs in draft, rejected, or published status",
			);
		}
 
		// Validate word limit
		if (body.content) {
			assertBlogWordLimit(body.content);
		}
 
		// Update blog
		const updated = await dal.blogs.update(blogId, {
			title: body.title || blog.title,
			slug: body.slug || blog.slug,
			content: body.content ? sanitizeHtml(body.content) : blog.content,
			metaDescription:
				body.metaDescription !== undefined
					? body.metaDescription
					: blog.metaDescription,
			blogType: body.blogType || blog.blogType,
			primaryKeyword:
				body.primaryKeyword !== undefined
					? body.primaryKeyword
					: blog.primaryKeyword,
			secondaryKeywords: body.secondaryKeywords || blog.secondaryKeywords || [],
			featuredImageUrl:
				body.featuredImageUrl !== undefined
					? body.featuredImageUrl
					: blog.featuredImageUrl,
			featuredImageAlt:
				body.featuredImageAlt !== undefined
					? body.featuredImageAlt
					: blog.featuredImageAlt,
		});
 
		// Replace tags if provided (D1 doesn't support transactions, use sequential ops)
		if (body.tagIds !== undefined) {
			await dal.db
				.delete(schema.blogTagAssignments)
				.where(eq(schema.blogTagAssignments.blogId, blogId));
			Eif (Array.isArray(body.tagIds)) {
				for (const tagId of body.tagIds) {
					await dal.db
						.insert(schema.blogTagAssignments)
						.values({ blogId, tagId });
				}
			}
		}
 
		return success(c, updated);
	} catch (err) {
		if (err instanceof z.ZodError) {
			return handleError(c, new BadRequestError(`Validation failed: ${err.issues.map((e) => e.message).join(", ")}`));
		}
		return handleError(c, err);
	}
});
 
// Delete my blog (any status with confirmation)
myBlogs.delete("/my-blogs/:id", async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.get("proId");
 
		if (!proId) {
			throw new ForbiddenError("Pro ID required");
		}
 
		const blogId = c.req.param("id");
 
		const blog = await dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Verify pro owns this blog (pro_request = manual, ai_suggestion = AI pipeline)
		if (
			blog.ideaSourceProId !== proId ||
			!isProOwnedBlog(blog.ideaSource)
		) {
			throw new ForbiddenError("You do not have access to this blog");
		}
 
		await dal.blogs.delete(blogId);
 
		return success(c, { message: "Blog deleted successfully" });
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Archive blog
myBlogs.post("/my-blogs/:id/archive", async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.get("proId");
 
		if (!proId) {
			throw new ForbiddenError("Pro ID required");
		}
 
		const blogId = c.req.param("id");
 
		const blog = await dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Verify pro owns this blog (pro_request = manual, ai_suggestion = AI pipeline)
		if (
			blog.ideaSourceProId !== proId ||
			!isProOwnedBlog(blog.ideaSource)
		) {
			throw new ForbiddenError("You do not have access to this blog");
		}
 
		// Only allow archiving published blogs
		if (blog.status !== "published") {
			throw new ValidationError("Can only archive published blogs");
		}
 
		const updated = await dal.blogs.update(blogId, {
			status: "archived",
		});
 
		return success(c, updated);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Unarchive blog (restore to published)
myBlogs.post("/my-blogs/:id/unarchive", async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.get("proId");
 
		if (!proId) {
			throw new ForbiddenError("Pro ID required");
		}
 
		const blogId = c.req.param("id");
 
		const blog = await dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Verify pro owns this blog (pro_request = manual, ai_suggestion = AI pipeline)
		if (
			blog.ideaSourceProId !== proId ||
			!isProOwnedBlog(blog.ideaSource)
		) {
			throw new ForbiddenError("You do not have access to this blog");
		}
 
		// Only allow unarchiving archived blogs
		if (blog.status !== "archived") {
			throw new ValidationError("Can only unarchive archived blogs");
		}
 
		const updated = await dal.blogs.update(blogId, {
			status: "published",
		});
 
		return success(c, updated);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Submit blog for approval
myBlogs.post("/my-blogs/:id/submit", async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.get("proId");
 
		if (!proId) {
			throw new ForbiddenError("Pro ID required");
		}
 
		const blogId = c.req.param("id");
 
		const blog = await dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Verify pro owns this blog (pro_request = manual, ai_suggestion = AI pipeline)
		if (
			blog.ideaSourceProId !== proId ||
			!isProOwnedBlog(blog.ideaSource)
		) {
			throw new ForbiddenError("You do not have access to this blog");
		}
 
		// Only allow submitting drafts
		if (blog.status !== "draft") {
			throw new ValidationError("Can only submit blogs in draft status");
		}
 
		// Cover image is required to publish
		if (!blog.featuredImageUrl) {
			throw new ValidationError(
				"A cover image is required to publish. Please add a cover image first.",
			);
		}
 
		// Enforce word count limit
		const wordCheck = checkBlogWordLimit(blog.content || "");
		if (!wordCheck.withinLimit) {
			throw new ValidationError(
				wordCheck.message ?? "Blog content exceeds the word limit.",
			);
		}
 
		const readTimeMinutes = Math.max(1, Math.round(wordCheck.words / 200));
 
		// Publish the blog directly (no approval process)
		const updated = await dal.blogs.update(blogId, {
			status: "published",
			publishedAt: new Date(),
			readTimeMinutes,
		});
 
		// Auto-add author attribution if not already present
		const existingPros = await dal.blogPros.findAll({
			blogId,
			proId,
			attributionType: "author",
		});
		if (existingPros.length === 0) {
			await dal.blogPros.create({
				id: generateId(),
				blogId,
				proId,
				attributionType: "author",
				approvalStatus: "approved",
				approvalRequestedAt: new Date(),
				approvedAt: new Date(),
			});
		}
 
		// Purge edge cache so the new blog appears in marketplace immediately
		c.executionCtx.waitUntil(
			purgeEdgeCache(`${c.env.BETTER_AUTH_URL}/api/marketplace/blogs`),
		);
 
		// Trigger pro site rebuild if the pro has a published website
		c.executionCtx.waitUntil(
			(async () => {
				try {
					const website = await dal.proWebsites.findByProId(proId);
					if (website && website.status === "published") {
						const version = (website.publishedVersion || 0) + 1;
						const buildJob = await dal.websiteBuildJobs.createBuildJob({
							proWebsiteId: website.id,
							version,
							triggeredBy: proId,
							triggerType: "manual",
							status: "pending",
						});
						if (c.env.BUILD_QUEUE && buildJob) {
							await c.env.BUILD_QUEUE.send({
								jobId: buildJob.id,
								proId,
								proWebsiteId: website.id,
								projectName: website.pagesProjectName,
							});
							await dal.websiteBuildJobs.updateBuildJob(buildJob.id, {
								status: "queued",
							});
						}
						logger.info(
							`[Blog Publish] Triggered site rebuild for pro ${proId}`,
						);
					}
				} catch (err) {
					logger.error("[Blog Publish] Failed to trigger site rebuild:", err);
				}
			})(),
		);
 
		return success(c, {
			...updated,
			message: "Blog published successfully!",
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// List all available blog tags (read-only for pros)
myBlogs.get("/blog-tags", async (c) => {
	try {
		const dal = c.get("dal");
		const tags = await dal.blogTags.findAll({}, 0, 500);
		return success(c, tags);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Create a new blog tag (pro-facing)
myBlogs.post("/blog-tags", async (c) => {
	try {
		const dal = c.get("dal");
		const body = await c.req.json<{ name?: string }>();
 
		const name = body.name?.trim();
		if (!name || name.length < 2 || name.length > 50) {
			throw new ValidationError(
				"Tag name is required and must be 2-50 characters",
			);
		}
 
		const slug = generateSlug(name);
 
		// Idempotent: if slug already exists, return the existing tag
		const existing = await dal.blogTags.findBySlug(slug);
		if (existing) {
			return success(c, existing, 200);
		}
 
		const tag = await dal.blogTags.create({
			id: generateId(),
			name,
			slug,
		});
 
		return success(c, tag, 201);
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default myBlogs;