All files / routes/pro social-drafts.routes.ts

90.28% Statements 158/175
87.95% Branches 146/166
80% Functions 8/10
91.22% Lines 156/171

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                                        4x 4x                                             1x     1x 2x 2x 2x   2x 2x                                   1x       5x 5x 5x 5x   5x 1x           4x 4x       4x 4x 2x               2x                 5x   2x           1x 3x 3x 3x 3x   3x 3x 2x     1x   2x         1x 30x 30x 30x 30x   30x                                                                               30x   30x 1x                   29x 29x 1x                         28x 28x 3x                 25x     30x 23x 23x 1x                             24x 2x                       1x 2x 1x 1x                           22x 1x                     1x 1x               21x 1x                     1x 1x               20x 12x 12x 12x         12x 12x 12x   12x 1x         11x 1x         10x 1x         9x 1x             8x 8x           8x 1x         7x 9x 9x           9x 1x         8x 1x         7x           7x 9x 2x 1x                     12x 2x 2x 1x         1x 1x               10x 10x     10x 10x                                 2x 2x 1x                     1x                 8x                                               8x 8x 2x 2x               1x 1x     1x 1x                           7x   5x         1x 8x 8x 8x 8x   8x 8x 2x     6x 2x           4x 1x           3x 3x 1x           2x 2x               2x         1x 4x 4x 4x 4x   4x 4x 2x     2x 2x 1x     2x 2x   2x          
// Pro Social Drafts Routes - Manage social media draft generation
import { Hono } from "hono";
import { eq, and, inArray } from "drizzle-orm";
import type { Dal } from "../../dal";
import type { getDb } from "../../db";
import type { Services } from "../../services";
import * as schema from "../../db/schema";
import { success, handleError } from "../../lib/response";
import { generateId } from "../../lib/utils";
import { NotFoundError } from "../../lib/errors";
import { requireProAccess } from "../../middleware";
import { generateVoiceoverScript } from "../../lib/voiceover-script";
import { logger } from "../../lib/logger";
 
// Shape the DAL returns for each draft. We parse JSON blobs before sending
// to the Portal so the client doesn't have to re-parse or deal with string
// vs object ambiguity on the voiceoverConfig field.
function serializeDraft<T extends { voiceoverConfig?: string | null }>(
	draft: T,
): T & { voiceoverConfig?: unknown } {
	Eif (!draft.voiceoverConfig) {
		return draft;
	}
	try {
		return { ...draft, voiceoverConfig: JSON.parse(draft.voiceoverConfig) };
	} catch {
		// Malformed JSON — drop the field rather than crash the list response
		return { ...draft, voiceoverConfig: undefined };
	}
}
 
type Env = {
	Bindings: CloudflareBindings;
	Variables: {
		user: { id: string; name: string; email: string } | null;
		session: unknown;
		dal: Dal;
		services: Services;
		db: ReturnType<typeof getDb>;
		proId: string;
		proRole: string;
	};
};
 
const socialDrafts = new Hono<Env>();
 
// List social drafts for a pro
socialDrafts.get("/:proId/social-drafts", requireProAccess, async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.get("proId");
 
		const result = await dal.socialDrafts.listByPro(proId);
		return success(c, {
			...result,
			drafts: result.drafts.map(serializeDraft),
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Preview the auto-generated voiceover script for a project. The Portal calls
// this when the pro enables voiceover so they see the generated text in an
// editable textarea BEFORE rendering. On submit, the edited script is sent to
// the Worker as voiceoverConfig.script — render-time auto-generation becomes
// a pure back-compat path.
//
// IMPORTANT: this route must be declared BEFORE `/:proId/social-drafts/:draftId`
// below. Hono matches in registration order and `preview-script` would
// otherwise be captured as a `:draftId` segment.
socialDrafts.get(
	"/:proId/social-drafts/preview-script",
	requireProAccess,
	async (c) => {
		try {
			const dal = c.get("dal");
			const proId = c.get("proId");
			const projectId = c.req.query("projectId");
 
			if (!projectId) {
				return c.json(
					{ success: false, error: { code: "BAD_REQUEST", message: "projectId is required" } },
					400,
				);
			}
 
			const pro = await dal.pros.findById(proId);
			Iif (!pro) {
				throw new NotFoundError("Pro not found");
			}
 
			const project = await dal.projects.findById(projectId);
			if (!project || project.proId !== proId) {
				throw new NotFoundError("Project not found");
			}
 
			// NOTE: matches the Worker's job-data resolver at
			// apps/api/src/routes/internal/social-studio.routes.ts:232-242 — we
			// pass raw tag IDs as labels. The Worker does the same at render time,
			// so the preview matches what would actually ship. Resolving IDs to
			// human labels via taxonomy joins is a future refinement.
			const script = generateVoiceoverScript({
				projectName: project.title,
				proName: pro.businessName,
				workedAreas: project.workedAreaIds ?? [],
				styles: project.styleTagIds ?? [],
				materials: project.materialTagIds ?? [],
				propertyType: project.propertyType ?? null,
			});
 
			return success(c, { script });
		} catch (err) {
			return handleError(c, err);
		}
	},
);
 
// Get a single social draft
socialDrafts.get("/:proId/social-drafts/:draftId", requireProAccess, async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.get("proId");
		const draftId = c.req.param("draftId");
 
		const draft = await dal.socialDrafts.getById(draftId);
		if (!draft || draft.proId !== proId) {
			throw new NotFoundError("Draft not found");
		}
 
		return success(c, serializeDraft(draft));
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Create a social draft for a project (auto or manual with selected photos)
socialDrafts.post("/:proId/social-drafts", requireProAccess, async (c) => {
	try {
		const dal = c.get("dal");
		const db = c.get("db");
		const proId = c.get("proId");
 
		const body = await c.req.json<{
			projectId: string;
			selectedPhotoIds?: number[];
			triggerSource?: "manual";
			musicTrackId?: string;
			brandingEnabled?: boolean;
			overlayConfig?: {
				introEnabled?: boolean;
				introDurationS?: number;
				outroEnabled?: boolean;
				outroDurationS?: number;
				badges?: Array<{
					id?: string;
					label?: unknown;
					style?: unknown;
					position?: unknown;
					customColor?: unknown;
				}>;
				badgeType?: "certified" | "featured" | "new" | null;
				badgePosition?: "top-left" | "top-right" | "bottom-left" | "bottom-right";
			};
			templateId?: string;
			slotAssignments?: Record<number, number>;
			voiceoverConfig?: {
				enabled: boolean;
				voice: string;
				script?: string;
				autoGenerate: boolean;
			};
		}>();
		const {
			projectId,
			selectedPhotoIds,
			triggerSource,
			musicTrackId,
			brandingEnabled,
			overlayConfig,
			templateId,
			slotAssignments,
			voiceoverConfig,
		} = body;
 
		if (!projectId) {
			return c.json(
				{ success: false, error: { code: "BAD_REQUEST", message: "projectId is required" } },
				400,
			);
		}
 
		// Cap slot expansion — mirrors MAX_PHOTO_SLOTS in the Worker's
		// template-engine. Defense in depth: Portal UI also enforces this but
		// we validate server-side to avoid runaway ffmpeg filter_complex on
		// pathological inputs.
		const MAX_PHOTO_SLOTS = 8;
		if (slotAssignments && Object.keys(slotAssignments).length > MAX_PHOTO_SLOTS) {
			return c.json(
				{
					success: false,
					error: {
						code: "BAD_REQUEST",
						message: `Too many slot assignments (max ${MAX_PHOTO_SLOTS})`,
					},
				},
				400,
			);
		}
 
		// Verify the project belongs to this pro before acting on it
		const project = await dal.projects.findById(projectId);
		if (!project || project.proId !== proId) {
			throw new NotFoundError("Project not found");
		}
 
		// W6 pre-flight: in auto mode (no manual photo selection or template slot
		// assignments) the container fetches eligible photos from the project at
		// build time and throws if it finds none. Catching this here saves the
		// pro from clicking Create, watching a 30-second spinner, and seeing a
		// "failed" status. dal.media.findEligibleForReel mirrors the resolver in
		// internal/social-studio.routes.ts: cover OR after OR null photoType.
		const isAutoMode =
			(!selectedPhotoIds || selectedPhotoIds.length === 0) &&
			(!slotAssignments || Object.keys(slotAssignments).length === 0);
		if (isAutoMode) {
			const eligibleRows = await dal.media.findEligibleForReel(projectId);
			if (eligibleRows.length === 0) {
				return c.json(
					{
						success: false,
						error: {
							code: "BAD_REQUEST",
							message:
								"Project has no eligible photos for reel generation. Add cover or 'after' photos to the project first.",
						},
					},
					400,
				);
			}
		}
 
		// Validate that all provided media IDs belong to any project owned by this pro
		if (selectedPhotoIds && selectedPhotoIds.length > 0) {
			const mediaRows = await db
				.select({ id: schema.media.id })
				.from(schema.media)
				.innerJoin(schema.rooms, eq(schema.media.roomId, schema.rooms.id))
				.innerJoin(schema.projects, eq(schema.rooms.projectId, schema.projects.id))
				.where(
					and(
						eq(schema.projects.proId, proId),
						inArray(schema.media.id, selectedPhotoIds),
					),
				);
 
			const foundIds = new Set(mediaRows.map((m) => m.id));
			const invalidIds = selectedPhotoIds.filter((id) => !foundIds.has(id));
			Eif (invalidIds.length > 0) {
				return c.json(
					{
						success: false,
						error: {
							code: "BAD_REQUEST",
							message: `Media IDs do not belong to this pro's projects: ${invalidIds.join(", ")}`,
						},
					},
					400,
				);
			}
		}
 
		// Validate musicTrackId if provided
		if (musicTrackId) {
			const [track] = await db
				.select({ id: schema.socialStudioMusicTracks.id })
				.from(schema.socialStudioMusicTracks)
				.where(
					and(
						eq(schema.socialStudioMusicTracks.id, musicTrackId),
						eq(schema.socialStudioMusicTracks.isActive, true),
					),
				)
				.limit(1);
 
			Eif (!track) {
				return c.json(
					{ success: false, error: { code: "BAD_REQUEST", message: "Music track not found or inactive" } },
					400,
				);
			}
		}
 
		// Validate templateId if provided
		if (templateId) {
			const [tmpl] = await db
				.select({ id: schema.socialStudioTemplates.id })
				.from(schema.socialStudioTemplates)
				.where(
					and(
						eq(schema.socialStudioTemplates.id, templateId),
						eq(schema.socialStudioTemplates.isActive, true),
					),
				)
				.limit(1);
 
			Eif (!tmpl) {
				return c.json(
					{ success: false, error: { code: "BAD_REQUEST", message: "Template not found or inactive" } },
					400,
				);
			}
		}
 
		// Validate overlayConfig structure if provided
		if (overlayConfig) {
			const VALID_BADGE_TYPES = ["certified", "featured", "new", null];
			const VALID_BADGE_POSITIONS = ["top-left", "top-right", "bottom-left", "bottom-right"];
			const VALID_BADGES_POSITIONS = [
				"top-left", "top-center", "top-right",
				"middle-left", "center", "middle-right",
				"bottom-left", "bottom-center", "bottom-right",
			];
			const VALID_BADGE_STYLES = ["certified", "featured", "new", "custom"];
			const HEX_COLOR_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
			const MAX_BADGES = 3;
 
			if (overlayConfig.introDurationS !== undefined && (overlayConfig.introDurationS < 1 || overlayConfig.introDurationS > 5)) {
				return c.json(
					{ success: false, error: { code: "BAD_REQUEST", message: "introDurationS must be between 1 and 5" } },
					400,
				);
			}
			if (overlayConfig.outroDurationS !== undefined && (overlayConfig.outroDurationS < 1 || overlayConfig.outroDurationS > 5)) {
				return c.json(
					{ success: false, error: { code: "BAD_REQUEST", message: "outroDurationS must be between 1 and 5" } },
					400,
				);
			}
			if (overlayConfig.badgeType !== undefined && !VALID_BADGE_TYPES.includes(overlayConfig.badgeType)) {
				return c.json(
					{ success: false, error: { code: "BAD_REQUEST", message: `Invalid badge type: ${overlayConfig.badgeType}` } },
					400,
				);
			}
			if (overlayConfig.badgePosition !== undefined && !VALID_BADGE_POSITIONS.includes(overlayConfig.badgePosition)) {
				return c.json(
					{ success: false, error: { code: "BAD_REQUEST", message: `Invalid badge position: ${overlayConfig.badgePosition}` } },
					400,
				);
			}
 
			// Validate new multi-badge array
			Eif (overlayConfig.badges !== undefined) {
				Iif (!Array.isArray(overlayConfig.badges)) {
					return c.json(
						{ success: false, error: { code: "INVALID_BADGES", message: "badges must be an array" } },
						400,
					);
				}
				if (overlayConfig.badges.length > MAX_BADGES) {
					return c.json(
						{ success: false, error: { code: "INVALID_BADGES", message: `badges must contain at most ${MAX_BADGES} items` } },
						400,
					);
				}
				for (let i = 0; i < overlayConfig.badges.length; i++) {
					const badge = overlayConfig.badges[i];
					Iif (!badge || typeof badge !== "object") {
						return c.json(
							{ success: false, error: { code: "INVALID_BADGES", message: `badges[${i}] must be an object` } },
							400,
						);
					}
					if (typeof badge.label !== "string" || badge.label.length < 1 || badge.label.length > 40) {
						return c.json(
							{ success: false, error: { code: "INVALID_BADGES", message: `badges[${i}].label must be a string between 1 and 40 characters` } },
							400,
						);
					}
					if (typeof badge.position !== "string" || !VALID_BADGES_POSITIONS.includes(badge.position)) {
						return c.json(
							{ success: false, error: { code: "INVALID_BADGES", message: `badges[${i}].position is invalid` } },
							400,
						);
					}
					Iif (badge.style !== undefined && (typeof badge.style !== "string" || !VALID_BADGE_STYLES.includes(badge.style))) {
						return c.json(
							{ success: false, error: { code: "INVALID_BADGES", message: `badges[${i}].style is invalid` } },
							400,
						);
					}
					const effectiveStyle = badge.style ?? "custom";
					if (effectiveStyle === "custom" && badge.customColor !== undefined) {
						if (typeof badge.customColor !== "string" || !HEX_COLOR_RE.test(badge.customColor)) {
							return c.json(
								{ success: false, error: { code: "INVALID_BADGES", message: `badges[${i}].customColor must be a hex color like #RRGGBB` } },
								400,
							);
						}
					}
				}
			}
		}
 
		// Validate voiceoverConfig if provided
		if (voiceoverConfig) {
			const VALID_VOICES = ["alloy", "echo", "fable", "onyx", "nova", "shimmer"];
			if (voiceoverConfig.voice && !VALID_VOICES.includes(voiceoverConfig.voice)) {
				return c.json(
					{ success: false, error: { code: "BAD_REQUEST", message: `Invalid voiceover voice: ${voiceoverConfig.voice}` } },
					400,
				);
			}
			Eif (voiceoverConfig.script && voiceoverConfig.script.length > 2000) {
				return c.json(
					{ success: false, error: { code: "BAD_REQUEST", message: "Voiceover script must be 2000 characters or less" } },
					400,
				);
			}
		}
 
		// Create new draft — unique partial index enforces one pending/processing draft per project
		const id = generateId();
		const jobNonce = generateId();
 
		let draft: Awaited<ReturnType<typeof dal.socialDrafts.create>>;
		try {
			draft = await dal.socialDrafts.create({
				id,
				proId,
				projectId,
				status: "pending",
				jobNonce,
				triggerSource: triggerSource ?? "auto",
				jobDataVersion: 2,
				musicTrackId: musicTrackId ?? null,
				brandingEnabled: brandingEnabled ?? true,
				overlayConfig: overlayConfig ? JSON.stringify(overlayConfig) : null,
				templateId: templateId ?? null,
				slotAssignments: slotAssignments ? JSON.stringify(slotAssignments) : null,
				voiceoverConfig: voiceoverConfig ? JSON.stringify(voiceoverConfig) : null,
			});
		} catch (insertErr) {
			// D1 surfaces SQLite constraint errors as generic errors; check message for UNIQUE
			const message = insertErr instanceof Error ? insertErr.message : String(insertErr);
			if (message.includes("UNIQUE") || message.includes("unique")) {
				return c.json(
					{
						success: false,
						error: {
							code: "CONFLICT",
							message: "A reel is already being generated for this project. Please wait for it to complete.",
						},
					},
					409,
				);
			}
			throw insertErr;
		}
 
		// C2 (Codex F7): photo-rows insert and queue.send are part of the same
		// logical commit as the draft row. If either fails, roll back the draft
		// (FK ON DELETE CASCADE on social_draft_photos cleans up any photo rows
		// that did insert). Previously the photo insert wasn't rolled back on
		// queue.send failure, and queue.send went through executionCtx.waitUntil
		// so a queue failure left the draft pending forever.
		Iif (selectedPhotoIds && selectedPhotoIds.length > 0) {
			try {
				const photoRows = selectedPhotoIds.map((mediaId, index) => ({
					draftId: id,
					mediaId,
					sortOrder: index,
				}));
				await db.insert(schema.socialDraftPhotos).values(photoRows);
			} catch (photoErr) {
				const msg =
					photoErr instanceof Error ? photoErr.message : String(photoErr);
				logger.error(
					`[social-drafts] photo insert failed: ${msg} — rolling back draft ${id}`,
				);
				await dal.socialDrafts.deleteById(id);
				throw photoErr;
			}
		}
 
		// C2 (Codex F6): await queue.send synchronously. Cloudflare Queue +
		// the existing apps/api/src/social-studio/queue-handler.ts (retry +
		// idempotent pending→processing transitions) + dlq-handler.ts already
		// supply the durability we need. The bug was just that
		// executionCtx.waitUntil dropped queue.send failures silently.
		const queue = c.env.SOCIAL_STUDIO_QUEUE;
		if (queue) {
			try {
				await queue.send({
					draftId: id,
					proId,
					projectId,
					timestamp: Date.now(),
				});
			} catch (queueErr) {
				const msg =
					queueErr instanceof Error ? queueErr.message : String(queueErr);
				logger.error(
					`[social-drafts] queue.send failed: ${msg} — rolling back draft ${id}`,
				);
				await dal.socialDrafts.deleteById(id);
				return c.json(
					{
						success: false,
						error: {
							code: "QUEUE_UNAVAILABLE",
							message:
								"Failed to enqueue reel build. Please try again in a moment.",
						},
					},
					503,
				);
			}
		}
 
		return success(c, { draft }, 201);
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Download a social draft reel — streams directly from R2
socialDrafts.get("/:proId/social-drafts/:draftId/download", requireProAccess, async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.get("proId");
		const draftId = c.req.param("draftId");
 
		const draft = await dal.socialDrafts.getById(draftId);
		if (!draft || draft.proId !== proId) {
			throw new NotFoundError("Draft not found");
		}
 
		if (draft.expiresAt && draft.expiresAt < new Date()) {
			return c.json(
				{ success: false, error: { code: "GONE", message: "Draft expired. Please regenerate." } },
				410,
			);
		}
 
		if (!draft.reelR2Key) {
			return c.json(
				{ success: false, error: { code: "NOT_FOUND", message: "Reel not ready yet." } },
				404,
			);
		}
 
		const object = await c.env.R2.get(draft.reelR2Key);
		if (!object) {
			return c.json(
				{ success: false, error: { code: "NOT_FOUND", message: "Reel file not found in storage." } },
				404,
			);
		}
 
		const filename = `reel-${draftId}.mp4`;
		return new Response(object.body, {
			headers: {
				"Content-Type": "video/mp4",
				"Content-Disposition": `attachment; filename="${filename}"`,
				"Cache-Control": "private, no-store",
			},
		});
	} catch (err) {
		return handleError(c, err);
	}
});
 
// Update caption for a social draft (pro-authored edit, auto-saves on blur)
socialDrafts.patch("/:proId/social-drafts/:draftId", requireProAccess, async (c) => {
	try {
		const dal = c.get("dal");
		const proId = c.get("proId");
		const draftId = c.req.param("draftId");
 
		const draft = await dal.socialDrafts.getById(draftId);
		if (!draft || draft.proId !== proId) {
			throw new NotFoundError("Draft not found");
		}
 
		const body = await c.req.json<{ captionEn?: string }>();
		if (body.captionEn !== undefined) {
			await dal.socialDrafts.update(draftId, { captionEn: body.captionEn });
		}
 
		const updated = await dal.socialDrafts.getById(draftId);
		return success(c, { draft: updated });
	} catch (err) {
		return handleError(c, err);
	}
});
 
export default socialDrafts;