All files / routes/pro/blogs approvals.routes.ts

100% Statements 92/92
100% Branches 34/34
100% Functions 7/7
100% Lines 90/90

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                                                          1x     1x     1x 7x 7x 7x   7x 1x     6x 7x   7x 7x   7x         7x           5x 5x   5x         5x           2x         1x 5x 5x 5x   5x 1x     4x     4x 4x 1x       3x 3x 1x       2x           2x               3x         1x 5x 5x 5x   5x 1x     4x     4x 4x 1x     3x     3x 1x     2x         1x   4x         1x 4x 4x 4x   4x 1x     3x 3x     3x 3x 1x     2x   2x               2x   2x         1x 8x 8x 8x   8x 1x     7x 7x     7x 1x       6x 6x 1x     5x     5x 1x           4x 4x 1x       3x 3x                   2x               2x           6x          
// Pro Blog Approval Routes
import { Hono } from "hono";
import type { Dal } from "../../../dal";
import type { Services } from "../../../services";
import {
	success,
	successWithPagination,
	handleError,
} from "../../../lib/response";
import { buildPaginationMeta, generateId } from "../../../lib/utils";
import {
	ValidationError,
	NotFoundError,
	ForbiddenError,
} from "../../../lib/errors";
import { requireProManager, aiRewriteRateLimit } from "../../../middleware";
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
		proId: string;
		proRole: string;
	};
};
 
const approvals = new Hono<Env>();
 
// Apply pro access middleware to all routes
approvals.use("*", requireProManager);
 
// Get pending approvals for this pro
approvals.get("/pending", 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 filters = {
			proId,
			approvalStatus: ["pending", "rewrite_requested"],
		};
 
		const [blogPros, total] = await Promise.all([
			dal.blogPros.findAll(filters, offset, safeLimit),
			dal.blogPros.count(filters),
		]);
 
		// Bulk fetch the associated blogs (N+1 optimization)
		const blogIds = blogPros.map((bv) => bv.blogId);
		const blogMap = await dal.blogs.findByIds(blogIds);
 
		const results = blogPros.map((bv) => ({
			...bv,
			blog: blogMap.get(bv.blogId),
		}));
 
		return successWithPagination(
			c,
			results,
			buildPaginationMeta(total, page, safeLimit),
		);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Get single blog for preview (pro must be associated with blog)
approvals.get("/:id/preview", 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");
 
		// Check if blog exists
		const blog = await dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Verify pro is associated with this blog
		const blogPros = await dal.blogPros.findAll({ blogId, proId });
		if (blogPros.length === 0) {
			throw new ForbiddenError("You do not have access to preview this blog");
		}
 
		// Fetch related data
		const [tags, pros, projects] = await Promise.all([
			dal.blogTags.findByBlogId(blog.id),
			dal.blogPros.findAll({ blogId }),
			dal.blogProjects.findByBlogId(blog.id),
		]);
 
		return success(c, {
			...blog,
			tags,
			pros,
			projects,
			proApproval: blogPros[0], // Current pro's approval status
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Approve blog
approvals.post("/:id/approve", 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");
 
		// Find the blog pro association
		const blogPros = await dal.blogPros.findAll({ blogId, proId });
		if (blogPros.length === 0) {
			throw new NotFoundError("Blog pro association not found");
		}
 
		const blogPro = blogPros[0];
 
		// Check if already approved
		if (blogPro.approvalStatus === "approved") {
			throw new ValidationError("Blog already approved");
		}
 
		const updated = await dal.blogPros.updateApprovalStatus(
			blogPro.id,
			"approved",
		);
 
		return success(c, updated);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Decline blog
approvals.post("/:id/decline", 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 = await c.req.json();
 
		// Find the blog pro association
		const blogPros = await dal.blogPros.findAll({ blogId, proId });
		if (blogPros.length === 0) {
			throw new NotFoundError("Blog pro association not found");
		}
 
		const blogPro = blogPros[0];
 
		const updated = await dal.blogPros.updateApprovalStatus(
			blogPro.id,
			"declined",
			{
				declineReason: body.reason || null,
			},
		);
 
		return success(c, updated);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Request AI rewrite
approvals.post("/:id/request-rewrite", aiRewriteRateLimit, 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 = await c.req.json();
 
		// Validate required fields
		if (!body.changeDescription) {
			throw new ValidationError("Missing required field: changeDescription");
		}
 
		// Find the blog pro association
		const blogPros = await dal.blogPros.findAll({ blogId, proId });
		if (blogPros.length === 0) {
			throw new NotFoundError("Blog pro association not found");
		}
 
		const blogPro = blogPros[0];
 
		// Check rewrite limit (max 3)
		if (blogPro.rewriteCount >= 3) {
			throw new ValidationError(
				"Maximum rewrite limit reached (3 rewrites per blog)",
			);
		}
 
		// Get current blog
		const blog = await dal.blogs.findById(blogId);
		if (!blog) {
			throw new NotFoundError("Blog not found");
		}
 
		// Create revision record
		const nextVersion = await dal.blogRevisions.getNextVersionNumber(blogId);
		await dal.blogRevisions.create({
			id: generateId(),
			blogId,
			versionNumber: nextVersion,
			content: blog.content,
			changeDescription: body.changeDescription,
			createdBy: "ai_rewrite",
		});
 
		// Update blog pro status
		const updated = await dal.blogPros.updateApprovalStatus(
			blogPro.id,
			"rewrite_requested",
			{
				rewriteCount: blogPro.rewriteCount + 1,
			},
		);
 
		return success(c, {
			...updated,
			message:
				"Rewrite request submitted. The platform team will review and regenerate the content.",
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default approvals;