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

97.95% Statements 48/49
97.05% Branches 33/34
100% Functions 3/3
97.95% Lines 48/49

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                                                            1x         1x       5x 5x 5x 5x   5x 1x           4x 4x       4x 4x 2x               2x                 5x   2x           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 read/edit endpoints — preview-script, R2 download stream,
// caption PATCH. Split out of social-drafts.routes.ts to keep that file
// focused on the heavy create flow.
//
// IMPORTANT: the `preview-script` route must be registered (and mounted)
// BEFORE any `/:proId/social-drafts/:draftId` matcher in the parent file,
// otherwise Hono would treat `preview-script` as a `:draftId` segment.
 
import { Hono } from "hono";
import type { Dal } from "../../../dal";
import type { getDb } from "../../../db";
import { NotFoundError } from "../../../lib/errors";
import { handleError, success } from "../../../lib/response";
import { generateVoiceoverScript } from "../../../lib/voiceover-script";
import { requireProAccess } from "../../../middleware";
import type { Services } from "../../../services";
 
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 readEdit = new Hono<Env>();
 
// Preview the voiceover script that would be generated for a project —
// surfaces what the worker job-data resolver would build at render time so
// the pro can review before kicking off a paid generation.
readEdit.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);
		}
	},
);
 
// Download a social draft reel — streams directly from R2
readEdit.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)
readEdit.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 readEdit;