import { readFile } from "node:fs/promises"; import path from "node:path"; import { invalidateProjects } from "@/lib/projects"; import { withEditNotes } from "@/lib/report/guard"; import { MANIFEST_NAME, StaleToken, manifestToken } from "@/lib/report/manifest.mjs"; import { applyHandFill, handFillView } from "@/lib/report/hand-fill.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; // FILL BY HAND (release 32 R2; lib/report/hand-fill.mjs): the Media tab's blanks // for every empty media field, written as the operator's -- no model, no mark. // // GET ?project= the view: the empty fields, the clips, // the deck, the flips and threads as they // stand, and the write token // POST {project, token?, fills: [{field, entry?, value}]} // each fill through the manifest writer; // -> {written, refused, token} const noStore = { "cache-control": "no-store" }; async function rawManifest(dir: string): Promise { return JSON.parse(await readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, MANIFEST_NAME), "utf8")); } export async function GET(request: Request) { const r = await resolveReport(new URL(request.url).searchParams.get("project") ?? ""); if ("error" in r) return Response.json({ error: r.error }, { status: r.status, headers: noStore }); return Response.json({ ...handFillView(await rawManifest(r.project.dir)), token: await manifestToken(r.project.dir) }, { headers: noStore }); } export async function POST(request: Request) { const refused = refuseCaller(request, "/api/report/hand-fill"); if (refused) return refused; const body = (await request.json().catch(() => null)) as Record | null; if (!body) return Response.json({ error: "expected JSON" }, { status: 400, headers: noStore }); const r = await resolveReport(String(body.project ?? "")); if ("error" in r) return Response.json({ error: r.error }, { status: r.status, headers: noStore }); try { const token = typeof body.token === "string" ? body.token : null; const { result, editNotes } = await withEditNotes(r.project, () => applyHandFill(r.project.dir, body.fills as unknown[], { token })); if (result.written.length) invalidateProjects(); return Response.json( { ok: !result.refused, ...result, editNotes, ...handFillView(await rawManifest(r.project.dir)), token: await manifestToken(r.project.dir) }, { status: result.refused && !result.written.length ? 400 : 200, headers: noStore }, ); } catch (e) { if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409, headers: noStore }); return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400, headers: noStore }); } }