// --------------------------------------------------------------------------- // A day's API spend, job by job, from the editor's usage ledger // (common/controller/generationUsage.ts: one row per model per finished Claude // API job, the day in UTC). /settings/generation says it under the policy: the // total against the daily cap, and each job -- when it ended, its task, the // article and iteration, the models it called, what it cost. P2b's rail says // only the total ("$0.42 today"). // // Plain ESM: `node --test` reads it with no bundler. // --------------------------------------------------------------------------- /** * @param {{ at: string, day: string, jobId: string, article: string, iteration: number, task: string, model: string, usd: number }[]} rows * @param {string} day YYYY-MM-DD (UTC) * @returns {{ day: string, usd: number, jobs: { jobId: string, at: string, task: string, article: string, iteration: number, models: string[], usd: number }[] }} */ export function daySpend(rows, day) { /** @type {Map} */ const jobs = new Map(); for (const r of rows) { // A local row (route "local", demo epic D3) is a model called, not spend. if (!r || r.day !== day || typeof r.usd !== "number" || r.route === "local") continue; const j = jobs.get(r.jobId) ?? { jobId: r.jobId, at: r.at, task: r.task, article: r.article, iteration: r.iteration, models: [], usd: 0 }; j.usd += r.usd; if (!j.models.includes(r.model)) j.models.push(r.model); if (r.at > j.at) j.at = r.at; jobs.set(r.jobId, j); } const list = [...jobs.values()] .map((j) => ({ ...j, usd: Math.round(j.usd * 10_000) / 10_000 })) .sort((a, b) => b.at.localeCompare(a.at)); return { day, usd: Math.round(list.reduce((s, j) => s + j.usd, 0) * 10_000) / 10_000, jobs: list }; } /** * The last `n` days' totals, newest first, a day with no spend included as 0. * @param {{ day: string, usd: number }[]} rows * @param {string} today YYYY-MM-DD * @param {number} [n] */ export function recentDays(rows, today, n = 7) { const by = new Map(); for (const r of rows) if (r && typeof r.usd === "number") by.set(r.day, (by.get(r.day) ?? 0) + r.usd); const out = []; const t = Date.parse(`${today}T00:00:00Z`); for (let i = 0; i < n; i++) { const day = new Date(t - i * 86_400_000).toISOString().slice(0, 10); out.push({ day, usd: Math.round((by.get(day) ?? 0) * 100) / 100 }); } return out; }