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 | 3x 3x 3x 3x 3x 3x 11x 1x 10x 10x 10x 10x 10x 3x 3x 2x 1x 10x 10x 10x 10x 5x 5x 5x 5x 4x 1x 3x 1x 2x 1x 5x 3x 7x 1x 6x 6x 6x 6x 6x 1x 5x 5x 5x 1x 4x 3x 1x 3x 3x 3x 3x 3x 3x 3x 1x 2x 1x 1x 3x 2x 2x 2x 2x | // Admin Editorial Blog Routes — AI-powered blog generation without a specific pro
import { Hono } from "hono";
import { z } from "zod";
import { zValidator } from "@hono/zod-validator";
import { sql } from "drizzle-orm";
import { success, error } from "../../../lib/response";
import { requireUser } from "../../../lib/utils";
import { getDb } from "../../../db";
import {
createAIService,
isAIEnabled,
} from "../../../services/ai/claude.service";
import { buildEditorialTopicSuggestionPrompt } from "../../../services/ai/prompts";
import { rateLimit } from "../../../middleware/rate-limit.middleware";
import type { Dal } from "../../../dal";
import type { Services } from "../../../services";
import { logger } from "../../../lib/logger";
type Env = {
Bindings: CloudflareBindings;
Variables: {
user: { id: string; name: string; email: string } | null;
session: unknown;
dal: Dal;
services: Services;
};
};
// Rate limiters for editorial endpoints
const editorialTopicRateLimit = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 30,
message:
"Too many editorial topic suggestion requests. Please try again in an hour.",
});
const editorialGenerateRateLimit = rateLimit({
windowMs: 60 * 60 * 1000, // 1 hour
max: 20,
message:
"Too many editorial generation requests. Please try again in an hour.",
});
// Validation schemas
const suggestTopicsSchema = z.object({
focus: z.string().min(1).max(500),
targetAudience: z.enum(["homeowners", "pros", "both"]),
category: z.string().optional(),
featuredProId: z.string().optional(),
});
const generateFullSchema = z.object({
title: z.string().min(1).max(255).optional(),
blogType: z.enum(["general", "project_spotlight", "hybrid"]).optional(),
primaryKeyword: z.string().min(1).max(100).optional(),
editorial: z.object({
focus: z.string().min(1).max(500),
targetAudience: z.enum(["homeowners", "pros", "both"]),
featuredProId: z.string().optional(),
}),
});
const editorial = new Hono<Env>();
/**
* POST /admin/blogs/editorial/suggest-topics
* Get AI topic suggestions based on editorial focus area
*/
editorial.post(
"/suggest-topics",
editorialTopicRateLimit,
zValidator("json", suggestTopicsSchema),
async (c) => {
if (!isAIEnabled(c.env)) {
return error(
c,
"AI_DISABLED",
"AI-powered features are temporarily unavailable. Please try again later or contact support.",
503,
);
}
const params = c.req.valid("json");
try {
const dal = c.get("dal");
const aiService = createAIService(c.env);
// Gather optional pro context if a featured pro is specified
let proCity: string | undefined;
let proSpecialties: string[] | undefined;
if (params.featuredProId) {
try {
const pro = await dal.pros.findById(params.featuredProId);
if (pro?.cityId) {
proCity = pro.cityId;
}
// Extract specialties from pro data if available
} catch {
// Non-critical — continue without pro context
}
}
// Gather demand signals and top-performing content in parallel
const [topBlogs, recentBlogTitles, leadCounts] = await Promise.all([
dal.blogAnalytics.getTopPerformingBlogs(5, "views").catch(() => []),
dal.blogs
.findAll({ status: "published" }, 0, 20)
.then((blogs) => blogs.map((b) => b.title))
.catch(() => [] as string[]),
// Aggregate leads by projectType across all pros
getDb(c.env.DB)
.all<{ projectType: string; count: number }>(
sql`SELECT project_type as projectType, COUNT(*) as count
FROM leads
WHERE project_type IS NOT NULL AND is_archived = 0
GROUP BY project_type
ORDER BY count DESC
LIMIT 8`,
)
.catch(() => [] as Array<{ projectType: string; count: number }>),
]);
// Build the editorial prompt with research data
const prompt = buildEditorialTopicSuggestionPrompt({
focus: params.focus,
targetAudience: params.targetAudience,
category: params.category,
proCity,
proSpecialties,
recentBlogs: recentBlogTitles,
demandSignals: leadCounts,
topPerformingBlogs: topBlogs.map((b) => ({
title: b.title,
views: b.views30d,
})),
});
// Call Claude directly with our editorial prompt (not suggestTopics,
// which always wraps in the pro-centric prompt builder)
const suggestions = await aiService.generateJSON<
Array<{
title: string;
blog_type: string;
primary_keyword: string;
secondary_keywords: string[];
outline: string;
seo_value: string;
pro_angle: string;
}>
>(prompt, { model: "haiku", temperature: 0.8 });
return success(c, {
suggestions,
count: suggestions.length,
});
} catch (err) {
logger.error("Editorial topic suggestion failed:", err);
let userMessage =
"Failed to suggest editorial topics. Please try again.";
if (err instanceof Error) {
if (err.message.includes("authentication")) {
userMessage =
"AI service authentication error. Please contact support.";
} else if (err.message.includes("rate limit")) {
userMessage =
"AI service rate limit reached. Please try again in a few minutes.";
} else if (err.message.includes("unavailable")) {
userMessage =
"AI service temporarily unavailable. Please try again later.";
}
}
return error(c, "AI_ERROR", userMessage, 500);
}
},
);
/**
* POST /admin/blogs/editorial/generate-full
* Trigger the full blog generation pipeline in editorial mode
*/
editorial.post(
"/generate-full",
editorialGenerateRateLimit,
zValidator("json", generateFullSchema),
async (c) => {
if (!isAIEnabled(c.env)) {
return error(
c,
"AI_DISABLED",
"AI-powered features are temporarily unavailable.",
503,
);
}
const user = requireUser(c.get("user"));
const params = c.req.valid("json");
const dal = c.get("dal");
// Check active job limit (3 max per admin)
const activeJobs = await dal.blogGenerationJobs.findActiveJobsForAdmin(
user.id,
);
if (activeJobs.length >= 3) {
return error(
c,
"TOO_MANY_JOBS",
"You already have 3 active generation jobs. Please wait for them to complete.",
429,
);
}
// Create the generation job
const jobId = crypto.randomUUID();
const job = await dal.blogGenerationJobs.create({
id: jobId,
proId: params.editorial.featuredProId || null,
createdByUserId: user.id,
mode: "one_click",
status: "research",
title: params.title || null,
blogType: params.blogType || "general",
primaryKeyword: params.primaryKeyword || null,
currentStep: 0,
totalSteps: 5,
dateCreated: new Date(),
dateUpdated: new Date(),
});
if (!job) {
return error(
c,
"CREATE_FAILED",
"Failed to create generation job",
500,
);
}
// Enqueue the first pipeline phase with editorial context
if (c.env.BLOG_GENERATION_QUEUE) {
await c.env.BLOG_GENERATION_QUEUE.send({
jobId,
phase: "research",
editorial: {
focus: params.editorial.focus,
targetAudience: params.editorial.targetAudience,
featuredProId: params.editorial.featuredProId,
},
});
} else {
return error(
c,
"QUEUE_UNAVAILABLE",
"Blog generation queue is not configured.",
503,
);
}
return success(c, {
jobId,
status: "research",
message:
"Editorial blog generation started. Poll /api/admin/blogs/editorial/jobs/:jobId for progress.",
});
},
);
/**
* GET /admin/blogs/editorial/jobs/:jobId
* Poll a specific editorial generation job status
*/
editorial.get("/jobs/:jobId", async (c) => {
const user = requireUser(c.get("user"));
const jobId = c.req.param("jobId");
const dal = c.get("dal");
const job = await dal.blogGenerationJobs.findById(jobId);
if (!job) {
return error(c, "NOT_FOUND", "Generation job not found", 404);
}
// Verify the job belongs to this admin
if (job.createdByUserId !== user.id) {
return error(
c,
"FORBIDDEN",
"You do not have access to this job",
403,
);
}
return success(c, {
id: job.id,
status: job.status,
currentStep: job.currentStep,
totalSteps: job.totalSteps,
blogId: job.blogId,
title: job.title,
errorLog: job.errorLog,
qualityScore: job.qualityScore,
dateCreated: job.dateCreated,
dateUpdated: job.dateUpdated,
});
});
/**
* GET /admin/blogs/editorial/jobs
* List active editorial jobs for the current admin
*/
editorial.get("/jobs", async (c) => {
const user = requireUser(c.get("user"));
const dal = c.get("dal");
const jobs = await dal.blogGenerationJobs.findActiveJobsForAdmin(user.id);
return success(c, { jobs });
});
export default editorial;
|