import { withEditNotes } from "@/lib/report/guard";
import { StaleToken, addLedgerRow, manifestToken, removeLedgerRow, updateLedgerRow } from "@/lib/report/manifest.mjs";
import { isMeasureLedger, parseLedgerValue } from "@/lib/report/ledgerRows.mjs";
import { resolveReport } from "@/lib/report/serve.mjs";
import { refuseCaller } from "@/lib/report/caller";
import { crossSiteRefusal } from "@/lib/report/sameOrigin.mjs";
import { EVENTS, PROMISE_FORMS, PROMISE_OUTCOMES, SCOPE_CONFIDENCE, VALUE_KINDS, measureSchema } from "umtool-report-to-video/ledger-totals";
export const dynamic = "force-dynamic";
// A MEASURE LEDGER's ROWS (umtool redesign L6, the inspector's Ledger panel; weight video rev 9): the rows the
// instruments draw from (`manifest.ledger`, read by the build through ledgerSchema), added, changed and removed
// through the manifest's own writers -- addLedgerRow / updateLedgerRow / removeLedgerRow, each row checked by
// ledgerRows.mjs ledgerRowOf against the schema (the CLI's checks, word for word), one undo point each.
// `umtool ledger
add|set|rm` is the same writer.
//
// GET ?project=[&entry=] the schema's vocabulary (tracks, forms, regimes, declared fields,
// events, the six adjudication words), the rows (those pinned to the
// entry when one is named), the token
// POST { project, token, op: "add", row } a new row (its id in it)
// POST { project, token, op: "set", id, patch, unset?: [key…] } a row changed
// POST { project, token, op: "rm", id } a row removed (refused while anything names it)
// A string value is read as the CLI reads a flag's text (ledgerRows.mjs parseLedgerValue: a number key a
// number, true/false, "a|b" a list for flags, "null" clears).
const noStore = { "cache-control": "no-store" };
type Row = Record & { id?: string; entryId?: string };
const parsed = (patch: unknown) => {
const out: Record = {};
if (!patch || typeof patch !== "object" || Array.isArray(patch)) return out;
for (const [k, v] of Object.entries(patch as Record)) out[k] = typeof v === "string" ? parseLedgerValue(k, v) : v;
return out;
};
export async function GET(request: Request) {
const url = new URL(request.url);
const r = await resolveReport(url.searchParams.get("project") ?? "");
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
const m = r.manifest as { ledgerSchema?: Record; ledger?: Row[] };
const rows = Array.isArray(m.ledger) ? m.ledger : [];
const entry = url.searchParams.get("entry");
let schema = null;
let schemaError = null;
if (isMeasureLedger(m)) {
try {
const s = measureSchema(m.ledgerSchema);
schema = {
unit: (m.ledgerSchema?.unit as string | undefined) ?? "",
tracks: s.tracks.map((t: { key: string; label: string; role: string; regimes: string[] | null }) => ({ key: t.key, label: t.label, role: t.role, regimes: t.regimes })),
forms: s.forms,
regimes: s.regimes.map((x: { key: string; label: string }) => ({ key: x.key, label: x.label })),
fields: s.fields.map((f: { key: string; label?: string; kind?: string; options?: unknown }) => ({ key: f.key, label: f.label ?? f.key, kind: f.kind ?? "text", options: Array.isArray(f.options) ? f.options : null })),
events: EVENTS, promiseForms: PROMISE_FORMS, outcomes: PROMISE_OUTCOMES, scopeConfidence: SCOPE_CONFIDENCE, valueKinds: VALUE_KINDS,
};
} catch (e) {
schemaError = e instanceof Error ? e.message : String(e);
}
}
return Response.json(
{
kind: isMeasureLedger(m) ? "measure" : rows.length || m.ledgerSchema ? "headcount" : null,
schema,
schemaError,
total: rows.length,
rows: entry ? rows.filter((x) => x?.entryId === entry) : rows,
entries: ((r.manifest as { timeline?: { id?: string; type?: string }[] }).timeline ?? []).map((e) => String(e?.id ?? "")).filter(Boolean),
token: await manifestToken(r.project.dir),
},
{ headers: noStore },
);
}
export async function POST(request: Request) {
const refused = refuseCaller(request, "/api/report/ledger");
if (refused) return refused;
const cross = crossSiteRefusal(request.headers);
if (cross) return Response.json({ error: cross }, { status: 403 });
let body: Record;
try {
body = await request.json();
} catch {
return Response.json({ error: "expected JSON" }, { status: 400 });
}
const r = await resolveReport(String(body.project ?? ""));
if ("error" in r) return Response.json({ error: r.error }, { status: r.status });
const token = typeof body.token === "string" ? body.token : null;
const id = String(body.id ?? "");
try {
if (body.op === "add") {
const row = parsed(body.row);
const { result, editNotes } = await withEditNotes(r.project, () => addLedgerRow(r.project.dir, row, { token }));
return Response.json({ ok: true, row: result.row, token: result.token, editNotes }, { headers: noStore });
}
if (body.op === "set") {
const unset = Array.isArray(body.unset) ? body.unset.map(String) : [];
const { result, editNotes } = await withEditNotes(r.project, () => updateLedgerRow(r.project.dir, id, parsed(body.patch), { token, unset }));
return Response.json({ ok: true, row: result.row, token: result.token, editNotes }, { headers: noStore });
}
if (body.op === "rm") {
// A removal is checked against the draft this panel read: never a blind delete.
if (!token) return Response.json({ error: "token is required to remove a row: GET the route first" }, { status: 400 });
const { result, editNotes } = await withEditNotes(r.project, () => removeLedgerRow(r.project.dir, id, { token }));
return Response.json({ ok: true, removed: result.row?.id ?? id, token: result.token, editNotes }, { headers: noStore });
}
return Response.json({ error: "op is add, set or rm" }, { status: 400 });
} catch (e) {
if (e instanceof StaleToken) return Response.json({ error: e.message, stale: true }, { status: 409 });
return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 400 });
}
}