import { projectRef } from "@/lib/projects"; import { kindMakesTakes } from "@/lib/projects/kinds.mjs"; import { askEditor, cancelDraftJob, EditorError, readDraftJob, readPolicy } from "@/lib/articles/generation"; import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, manifestToken } from "@/lib/report/manifest.mjs"; import { GroupsRequestError, acceptGroupProposal, clearGroupsJob, groupProposalsView, groupsDraftBodyOf, groupsJobView, groupsRouteOf, parseGroupsRequest, readGroupsJob, rejectGroupProposals, writeGroupsJob, } from "@/lib/report/groupProposals.mjs"; import { refuseCaller } from "@/lib/report/caller"; export const dynamic = "force-dynamic"; // CLAIM-GROUP PROPOSALS (lane L4) -- optional, every part of it. Propose // groups starts the EDITOR's `report-draft` job, task `propose-groups`, // routed by settings.generation (local by default); its proposals land in // `/group-proposals.json`. This route asks with the shared // WORKER_TOKEN, follows the job, and ACCEPTS on the operator's click: one // group written through the manifest's structural writer (setGroup), // token-guarded (lib/report/groupProposals.mjs). Never applied otherwise. // // GET ?project= { proposals, error, route, editorError, job, token } // GET ?project=&job= that job (ended: forgotten) // POST { project, op: "start", request? } → { jobId, job } // POST { project, op: "accept", id, token, at? } → { accepted, group, token, proposals } | { failed, error } | 409 // POST { project, op: "reject", id?, at? } → { rejected, proposals } // POST ?cancel=&project= stop it const headers = { "cache-control": "no-store" }; async function groupsProject(id: unknown) { const project = await projectRef(String(id ?? "")); if (!project) return { error: Response.json({ error: "no such project" }, { status: 404, headers }) }; if (!kindMakesTakes(project.kind)) return { error: Response.json({ error: "claim groups are a report video's" }, { status: 400, headers }) }; return { project }; } const failed = (e: unknown) => { if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409, headers }); const status = e instanceof EditorError ? e.status : e instanceof GroupsRequestError ? ((e as GroupsRequestError & { status?: number }).status ?? 400) : 500; return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status, headers }); }; async function jobOf(dir: string, id: string) { const rec = await readGroupsJob(dir); const job = await readDraftJob(id, 40); const view = groupsJobView(rec && rec.jobId === id ? rec : null, job); if (view.ended) await clearGroupsJob(dir, id); return view; } export async function GET(request: Request) { const url = new URL(request.url); const r = await groupsProject(url.searchParams.get("project")); if ("error" in r) return r.error; const dir = r.project.dir; const id = url.searchParams.get("job"); if (id) { try { return Response.json(await jobOf(dir, id), { headers }); } catch (e) { return failed(e); } } const view = await groupProposalsView(dir); const policy = await readPolicy().catch((e: unknown) => e as Error); const rec = await readGroupsJob(dir); let job = null; if (rec) { job = await jobOf(dir, rec.jobId).catch(async (e: unknown) => { if (e instanceof EditorError && e.status === 404) await clearGroupsJob(dir, rec.jobId); return null; }); } return Response.json( { ...view, route: policy instanceof Error ? null : groupsRouteOf(policy.generation, dir), editorError: policy instanceof Error ? policy.message : null, job, token: await manifestToken(dir), }, { headers }, ); } export async function POST(request: Request) { const refused = refuseCaller(request, "/api/report/group-proposals"); if (refused) return refused; const url = new URL(request.url); const cancel = url.searchParams.get("cancel"); if (cancel) { const r = await groupsProject(url.searchParams.get("project")); if ("error" in r) return r.error; try { await cancelDraftJob(cancel); return Response.json({ cancelled: true }, { headers }); } catch (e) { return failed(e); } } const body = (await request.json().catch(() => null)) as Record | null; if (!body || typeof body !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); const r = await groupsProject(body.project); if ("error" in r) return r.error; const dir = r.project.dir; const at = typeof body.at === "string" ? body.at : null; try { if (body.op === "accept") { const token = body.token === undefined || body.token === null ? null : String(body.token); const { result, editNotes } = await withEditNotes(r.project, () => acceptGroupProposal(dir, { id: String(body.id ?? ""), token, at })); return Response.json({ ok: true, ...result, editNotes }, { headers }); } if (body.op === "reject") { const id = typeof body.id === "string" && body.id ? body.id : null; return Response.json({ ok: true, ...(await rejectGroupProposals(dir, { id, at })) }, { headers }); } if (body.op !== undefined && body.op !== "start") return Response.json({ error: 'op is "start", "accept" or "reject"' }, { status: 400, headers }); const req = parseGroupsRequest(body); const running = await readGroupsJob(dir); if (running) { const view = await jobOf(dir, running.jobId).catch(() => null); if (view && !view.ended) return Response.json({ error: "groups are already being proposed for this project", job: view }, { status: 409, headers }); } const answer = await askEditor<{ jobId?: string }>("/api/ops/report-draft", { method: "POST", body: groupsDraftBodyOf(dir, req) }); const jobId = String(answer.jobId ?? ""); if (!jobId) return Response.json({ error: "the editor started no job" }, { status: 502, headers }); await writeGroupsJob(dir, { jobId, ...(req.request ? { request: req.request } : {}), at: new Date().toISOString() }); const job = await jobOf(dir, jobId).catch(() => ({ id: jobId, status: "queued", ended: false, queue: null, last: null, summary: null })); return Response.json({ ok: true, jobId, job }, { headers }); } catch (e) { return failed(e); } }