// `umtool ledger` (weight video rev 9): a MEASURE ledger's rows from a // terminal -- listed, added, patched, removed -- through the manifest's own // writers (manifest.mjs addLedgerRow / updateLedgerRow / removeLedgerRow), so // every row written is checked against the manifest's ledgerSchema // (ledgerRows.mjs) exactly as the instruments will read it. // // umtool ledger [ls] [--scope S] [--population P] [--json] // umtool ledger add --date D --scope S --population P [--value V] --scopeBasis "…" [-- V …] [--row '{…}'] [--json] // umtool ledger set -- V … [--unset k,k] [--json] // umtool ledger rm [--json] import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { readManifest } from "../projects/report.mjs"; import { addLedgerRow, removeLedgerRow, updateLedgerRow } from "./manifest.mjs"; import { isMeasureLedger, parseLedgerValue } from "./ledgerRows.mjs"; export const LEDGER_USAGE = [ "usage: umtool ledger [ls] [--scope S] [--population P] [--json] the ledger's rows", " umtool ledger add --date D --scope S --population P [--value V] --scopeBasis \"…\" [-- V …] [--row '{…}'] [--json]", " umtool ledger set -- V … [--unset k,k] [--json]", " umtool ledger rm [--json]", "", "A measure ledger's rows (ledgerSchema.kind \"measure\"), written only through these: each row is checked against", "the schema -- a scope that is a track, a form it names (and the promise forms: promise / promise_check /", "promise_claim / promise_outcome), a number in its unit or a declared regime with an event, the six adjudication fields (a new row defaults", "scopeConfidence read, valueKind uttered, flags []; --scopeBasis is never defaulted) and the declared fields.", "-- sets any built-in key (date asOf scope population value event display label quote deadline src channel", "video cite citeFrom scopeBasis scopeConfidence valueKind flags (a|b) hedged unsourced entryId authorNote, and the", "instruments' own: run (a loss claim's run, his words placing it), retro (a loss told in the past with no asOf:", "off the odometer), promise (a promise_check's or promise_claim's promise), kept, due (YYYY-MM-DD), speaker (another", "party's key: a promise_claim's -- her rows move none of his numbers), paidOn (YYYY-MM-DD), outcome (a", "promise_outcome's: kept, refunded, withdrawn), stampNote (a promise_outcome's: the words under its stamp on the", "promise clock in place of \"by · no video\" -- one line; the strip shows its first clause; `umtool lint` warns", "past 26 characters)) or a declared field; `null`", "clears a value. rm refuses a row a timeline entry pins or another row names.", ].join("\n"); class CliError extends Error {} /** `--key value` pairs (the rest: words), `--json`/`--help` alone. */ function parseArgs(args) { const flags = new Map(); const words = []; for (let i = 0; i < args.length; i += 1) { const a = args[i]; if (a === "--json" || a === "--help") { flags.set(a.slice(2), true); continue; } if (a.startsWith("--")) { const eq = a.indexOf("="); if (eq > 0) { flags.set(a.slice(2, eq), a.slice(eq + 1)); continue; } if (i + 1 >= args.length) throw new CliError(`${a} needs a value`); flags.set(a.slice(2), args[i + 1]); i += 1; continue; } words.push(a); } return { flags, words }; } /** The row patch the flags spell: `--row` JSON first, then each `--`. */ function patchOf(flags, skip) { let patch = {}; if (flags.has("row")) { try { patch = JSON.parse(String(flags.get("row"))); } catch (e) { throw new CliError(`--row is not JSON: ${e instanceof Error ? e.message : e}`); } if (!patch || typeof patch !== "object" || Array.isArray(patch)) throw new CliError("--row must be a JSON object"); } for (const [k, v] of flags) { if (skip.has(k)) continue; patch[k] = parseLedgerValue(k, v); } return patch; } const line = (r) => [ String(r.id).padEnd(6), String(r.date ?? "").padEnd(10), String(r.scope ?? "").padEnd(9), String(r.population ?? "").padEnd(14), String(r.display ?? r.value ?? "—").padEnd(22), r.entryId ? `@${r.entryId}` : "", Number.isInteger(r.run) ? `run ${r.run}` : "", r.retro ? "retro" : "", r.promise ? `-> ${r.promise}` : "", r.speaker ? `by ${r.speaker}` : "", r.paidOn ? `paid ${r.paidOn}` : "", r.outcome ? String(r.outcome).toUpperCase() : "", r.kept ? "kept" : "", String(r.label ?? "").slice(0, 70), ].filter(Boolean).join(" "); /** * @param {string[]} args the words after `ledger` * @param {{ root?: string, out?: (s: string) => void, err?: (s: string) => void }} [opts] * @returns {Promise} the exit code */ export async function ledgerCommand(args, { root = REPORTS_ROOT, out = (s) => console.log(s), err = (s) => console.error(s) } = {}) { try { const { flags, words } = parseArgs(args); const [projectArg, verb = "ls", id] = words; if (!projectArg || flags.get("help")) { err(LEDGER_USAGE); return 2; } const json = flags.get("json") === true; const r = await resolveProject(projectArg, root); if (r.ambiguous) throw new CliError(`"${projectArg}" is the name of ${r.ambiguous.length} projects — pass its id`); if (!r.project) throw new CliError(`no project matches "${projectArg}"`); const project = r.project; const manifest = await readManifest(project.dir); if (!manifest) throw new CliError(`${project.id} has no manifest`); if (verb === "ls") { const rows = (manifest.ledger ?? []).filter((x) => (!flags.has("scope") || x.scope === flags.get("scope")) && (!flags.has("population") || x.population === flags.get("population"))); if (json) out(JSON.stringify({ project: project.id, kind: isMeasureLedger(manifest) ? "measure" : "headcount", rows }, null, 2)); else { for (const x of rows) out(line(x)); out(`${rows.length} of ${(manifest.ledger ?? []).length} row(s)`); } return 0; } if (!isMeasureLedger(manifest)) throw new CliError(`${project.id} has no measure ledger (ledgerSchema.kind "measure"): these writers are a measure ledger's`); if (!id) throw new CliError(`${verb} needs a row id`); if (verb === "add") { const patch = { ...patchOf(flags, new Set(["json", "help"])), id }; const done = await addLedgerRow(project.dir, patch); if (json) out(JSON.stringify({ project: project.id, added: done.row }, null, 2)); else out(`added ${line(done.row)}`); return 0; } if (verb === "set") { const unset = flags.has("unset") ? String(flags.get("unset")).split(",").map((s) => s.trim()).filter(Boolean) : []; const patch = patchOf(flags, new Set(["json", "help", "unset"])); if (!Object.keys(patch).length && !unset.length) throw new CliError("set needs -- or --unset "); const done = await updateLedgerRow(project.dir, id, patch, { unset }); if (json) out(JSON.stringify({ project: project.id, row: done.row }, null, 2)); else out(`set ${line(done.row)}`); return 0; } if (verb === "rm") { const done = await removeLedgerRow(project.dir, id); if (json) out(JSON.stringify({ project: project.id, removed: done.row.id }, null, 2)); else out(`removed ${done.row.id}`); return 0; } throw new CliError(`unknown: ledger ${verb} — ls, add, set or rm`); } catch (e) { err(`umtool ledger: ${e instanceof Error ? e.message : String(e)}`); return 1; } }