money chart: cumulative OC revenue, token spend, and OC balance

New Money tab beside Trends, fed by the portal's /admin/money-series
(hourly-cached server-side). One fetch at full range; period (30/90/all)
and spend-mode (cumulative/daily) toggles re-render client-side.

- Cumulative mode: three lines — Revenue (OC contributions, green),
  Token spend (blue), OC balance (amber). NULL balance days render as a
  gap (the OC API exposes only the CURRENT balance; history accrues from
  daily snapshots from the deploy date onward — stated in the caption
  and in the balance legend key).
- Daily mode: token spend per day as bars (spend-only; the other series
  are cumulative and would need a second axis).
- Money ticks use the 1/2/5 x 10^k rule; tooltips reuse the shared
  chart-tip helper (all three series listed per day).
- The caption is a deliberate exception to the no-caption chart rule:
  the operator asked for the honest data-history limits in the UI.
- Harness: tests/money-chart-harness.js (axis invariants, gap handling,
  daily bars, period slice, single-point balance).
This commit is contained in:
inference-bot committed 2026-11-08 01:50:26 +00:00
1 parent bdb5a9c6eb
commit 90294df4c6
2 files changed
+343 -1

No files matched your search

+252 -1
View File
@@ -139,6 +139,22 @@ async def api_metrics(request: Request, days: int = 730):
return JSONResponse({"error": e.detail}, status_code=e.status_code)
@app.get("/api/money-series")
async def api_money_series(request: Request):
"""Revenue / token spend / OC balance series (portal /admin/money-series).
The portal owns this data and caches it hourly (the OC queries are slow);
the panel only reads it. The full history comes back in one payload — the
period and spend-mode toggles slice client-side and never refetch.
"""
if not is_admin(request):
return JSONResponse({"error": "forbidden"}, status_code=403)
try:
return await portal_get("/admin/money-series")
except HTTPException as e:
return JSONResponse({"error": e.detail}, status_code=e.status_code)
@app.post("/api/set-balance")
async def api_set_balance(request: Request):
if not is_admin(request):
@@ -291,6 +307,13 @@ PAGE_HTML = """<!DOCTYPE html>
.chart-tip .tip-row { display: flex; justify-content: space-between; gap: 14px; }
.chart-tip .tip-row span { color: var(--muted); }
.chart-tip .tip-row b { color: var(--ink); font-variant-numeric: tabular-nums; }
/* Money chart: legend keys + the honest-data caption. The caption is a
deliberate exception to the no-caption rule for the Trends charts: the
operator asked for the data-history limits to be stated IN this chart. */
.money-legend { display: inline-flex; gap: 14px; flex-wrap: wrap; font-size: 12px; color: var(--muted); font-weight: 600; }
.money-legend .key { display: inline-flex; align-items: center; gap: 5px; }
.money-legend .sw { display: inline-block; width: 10px; height: 10px; border-radius: 3px; flex-shrink: 0; }
.money-caption { color: var(--muted); font-size: 11px; margin: 8px 0 0; }
@media (max-width: 600px) { .trend-controls { gap: 10px; } .trend-card { padding: 12px 10px; } }
.num { font-variant-numeric: tabular-nums; }
.remaining-col { font-weight: 700; color: var(--green-deep); background: #eaf3ea; }
@@ -345,6 +368,7 @@ PAGE_HTML = """<!DOCTYPE html>
<button class="tab-btn active" id="tab-members" onclick="switchView('members')">Members</button>
<button class="tab-btn" id="tab-models" onclick="switchView('models')">Model usage</button>
<button class="tab-btn" id="tab-trends" onclick="switchView('trends')">Trends</button>
<button class="tab-btn" id="tab-money" onclick="switchView('money')">Money</button>
<span class="range-group" id="member-mode-group">
<button class="range-btn active" id="mmode-balance" onclick="setMemberMode('balance')">Balance</button>
<button class="range-btn" id="mmode-all" onclick="setMemberMode('all')">All time</button>
@@ -401,6 +425,30 @@ PAGE_HTML = """<!DOCTYPE html>
</div>
</div>
<div id="money-section" style="display:none;">
<div class="trend-controls">
<span class="range-group">
<span class="range-label">Period</span>
<button class="range-btn" id="mp-30" onclick="setMoneyPeriod(30)">Last 30 days</button>
<button class="range-btn active" id="mp-90" onclick="setMoneyPeriod(90)">Last 90 days</button>
<button class="range-btn" id="mp-all" onclick="setMoneyPeriod(0)">All time</button>
</span>
<span class="range-group">
<span class="range-label">Token spend</span>
<button class="range-btn active" id="ms-cum" onclick="setMoneySpendMode('cum')">Cumulative</button>
<button class="range-btn" id="ms-daily" onclick="setMoneySpendMode('daily')">Daily</button>
</span>
</div>
<div class="trend-card">
<div class="trend-head">
<span class="trend-title" id="money-title">Revenue, spend and balance</span>
<span id="money-legend" class="money-legend"></span>
</div>
<div id="money-body" class="trend-body"><p class="trend-empty">Loading</p></div>
<p class="money-caption" id="money-caption"></p>
</div>
</div>
<div id="agents-section" style="display:none;">
<h3 style="margin:20px 0 8px;">Agents</h3>
<p style="color:var(--muted);font-size:12px;margin:0 0 8px;">Bot and sandbox accounts. Not members — excluded from member counts; their usage is a collective expense.</p>
@@ -758,6 +806,204 @@ function renderTrends() {
host.innerHTML = parts.join("");
}
// ---- Money: revenue / token spend / OC balance over time ----
// Three series with different provenance, from the portal's
// /admin/money-series (hourly-cached server-side; the OC queries are slow).
// One fetch at full range; the period and spend-mode toggles re-render
// client-side. The balance series exists only from the daily-snapshot
// deployment date onward (the OC API exposes just the CURRENT balance), so
// it renders as a gap before that and the caption says so — never a zero.
let moneyData = null;
let moneyLoaded = false;
let moneyPeriod = 90; // 0 = all time
let moneySpendMode = "cum"; // "cum" = cumulative lines | "daily" = daily bars
const MONEY_COLORS = { revenue: "var(--green-deep)", spend: "#4a6a8a", balance: "#a97a2a" };
async function loadMoney() {
if (moneyLoaded) { renderMoney(); return; }
const host = $("money-body");
try {
const r = await fetch("/api/money-series");
if (r.status === 403) { host.innerHTML = "<p class=trend-empty>Forbidden</p>"; return; }
const d = await r.json();
if (d.error) { host.innerHTML = "<p class=trend-empty>" + esc(d.error) + "</p>"; return; }
moneyData = d;
moneyLoaded = true;
renderMoney();
} catch (e) {
host.innerHTML = "<p class=trend-empty>Could not load the money series.</p>";
}
}
function setMoneyPeriod(d) {
moneyPeriod = d;
$("mp-30").className = "range-btn" + (d === 30 ? " active" : "");
$("mp-90").className = "range-btn" + (d === 90 ? " active" : "");
$("mp-all").className = "range-btn" + (d === 0 ? " active" : "");
renderMoney();
}
function setMoneySpendMode(m) {
moneySpendMode = m;
$("ms-cum").className = "range-btn" + (m === "cum" ? " active" : "");
$("ms-daily").className = "range-btn" + (m === "daily" ? " active" : "");
renderMoney();
}
function moneyFmt(v) {
if (v === null || v === undefined) return "not measured";
return fmt(v);
}
// Money ticks use the 1/2/5 x 10^k rule. Steps at or above $1 are integers;
// below, show cents so a $0.50 tick does not round to $1.
function moneyTickLabel(v) {
return v >= 1 ? "$" + Math.round(v).toLocaleString() : "$" + v.toFixed(2);
}
function moneyStep(raw) {
const mag = Math.pow(10, Math.floor(Math.log10(Math.max(raw, 1e-9))));
const norm = raw / mag;
const nice = norm <= 1 ? 1 : (norm <= 2 ? 2 : (norm <= 5 ? 5 : 10));
return nice * mag;
}
function moneyFrame(rows, top, step, label) {
const W = 1000, H = 250, padL = 62, padR = 14, padT = 14, padB = 30;
const plotW = W - padL - padR, plotH = H - padT - padB;
const baseY = padT + plotH;
const n = rows.length;
const xAt = i => padL + (n <= 1 ? plotW / 2 : (plotW * i) / (n - 1));
const yAt = v => baseY - (plotH * v) / top;
const parts = [];
parts.push('<svg viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="' + label + '">');
for (let g = 0; g <= 4; g++) {
const yy = baseY - (plotH * g) / 4;
parts.push('<line x1="' + padL + '" y1="' + yy + '" x2="' + (W - padR) + '" y2="' + yy + '" stroke="var(--border)"/>');
parts.push('<text x="' + (padL - 8) + '" y="' + (yy + 4) + '" text-anchor="end" font-size="11" fill="var(--muted)">' + moneyTickLabel(step * g) + '</text>');
}
return { W, H, padL, padR, baseY, n, xAt, yAt, parts };
}
function moneyDateMarks(fr, rows) {
const marks = fr.n > 2 ? [0, Math.floor((fr.n - 1) / 2), fr.n - 1] : [0, fr.n - 1];
for (let mi = 0; mi < marks.length; mi++) {
const i = marks[mi];
const anchor = mi === 0 ? "start" : (mi === marks.length - 1 ? "end" : "middle");
fr.parts.push('<text x="' + fr.xAt(i) + '" y="' + (fr.H - 9) + '" text-anchor="' + anchor + '" font-size="11" fill="var(--muted)">' + String(rows[i].day).slice(5) + '</text>');
}
}
function renderMoney() {
const host = $("money-body");
if (!host || !moneyData) return;
hideChartTip();
// The honest-limits caption, required by the operator: the payload carries
// the balance-history caveat and any per-source failures.
let cap = moneyData.caveat || "";
if (moneyData.stale) cap = "(cached — last refresh failed) " + cap;
if (moneyData.errors && moneyData.errors.length) cap += " Series unavailable: " + moneyData.errors.join("; ") + ".";
$("money-caption").textContent = cap;
renderMoneyLegend();
const all = moneyData.series || [];
const rows = moneyPeriod === 0 ? all : all.slice(-moneyPeriod);
if (rows.length < 2) { host.innerHTML = "<p class=trend-empty>Not enough history yet.</p>"; return; }
if (moneySpendMode === "daily") renderMoneyDaily(host, rows);
else renderMoneyCumulative(host, rows);
}
function renderMoneyLegend() {
const items = [
{ c: MONEY_COLORS.revenue, t: "Revenue — OC contributions (cumulative)" },
{ c: MONEY_COLORS.spend, t: moneySpendMode === "daily" ? "Token spend — daily" : "Token spend — cumulative" }
];
if (moneySpendMode !== "daily") {
const start = moneyData.balance_history_start;
items.push({ c: MONEY_COLORS.balance, t: "OC balance" + (start ? " — history begins " + start : "") });
}
$("money-legend").innerHTML = items.map(it =>
'<span class="key"><span class="sw" style="background:' + it.c + '"></span>' + esc(it.t) + '</span>'
).join("");
}
function renderMoneyCumulative(host, rows) {
const series = [
{ name: "Revenue", key: "revenue_cum", color: MONEY_COLORS.revenue },
{ name: "Token spend", key: "spend_cum", color: MONEY_COLORS.spend },
{ name: "OC balance", key: "oc_balance", color: MONEY_COLORS.balance }
];
const tops = [];
for (const s of series) {
for (const r of rows) { const v = r[s.key]; if (v !== null && v !== undefined) tops.push(v); }
}
const maxV = tops.length ? Math.max.apply(null, tops) : 0;
const step = moneyStep((maxV <= 0 ? 1 : maxV * 1.08) / 4);
const fr = moneyFrame(rows, step * 4, step, "Cumulative revenue, token spend and OC balance over time");
registerChartTips("money-body", rows.map(r => ({
label: r.day,
series: series.map(s => [s.name, moneyFmt(r[s.key])])
})));
for (const s of series) {
// Contiguous measured runs: a NULL (the balance before snapshots began)
// stays a gap — the line is never drawn through invented history.
const runs = [];
let run = [];
for (let i = 0; i < fr.n; i++) {
const v = rows[i][s.key];
if (v === null || v === undefined) { if (run.length) runs.push(run); run = []; }
else run.push(i);
}
if (run.length) runs.push(run);
for (const r0 of runs) {
const pts = r0.map(i => fr.xAt(i) + "," + fr.yAt(rows[i][s.key])).join(" ");
if (r0.length > 1) {
fr.parts.push('<polyline points="' + pts + '" fill="none" stroke="' + s.color + '" stroke-width="2" stroke-linejoin="round"/>');
} else {
// A single measured day (e.g. the first balance snapshot) still shows.
fr.parts.push('<circle cx="' + fr.xAt(r0[0]) + '" cy="' + fr.yAt(rows[r0[0]][s.key]) + '" r="3" fill="' + s.color + '"/>');
}
}
}
// Hover targets: one transparent circle per measured point on every series;
// the tooltip lists all three series at that x.
for (const s of series) {
for (let i = 0; i < fr.n; i++) {
const v = rows[i][s.key];
if (v === null || v === undefined) continue;
fr.parts.push('<circle cx="' + fr.xAt(i) + '" cy="' + fr.yAt(v) + '" r="7" fill="transparent" data-tip-host="money-body" data-tip-i="' + i + '"></circle>');
}
}
moneyDateMarks(fr, rows);
fr.parts.push("</svg>");
host.innerHTML = fr.parts.join("");
}
function renderMoneyDaily(host, rows) {
// Daily token spend as bars. Revenue and balance are cumulative figures and
// would need a second axis beside daily ones, so this mode is spend-only —
// the legend says which series is shown.
const vals = rows.map(r => r.spend_day);
const have = vals.filter(v => v !== null && v !== undefined);
if (have.length < 2) { host.innerHTML = "<p class=trend-empty>Not enough history yet.</p>"; return; }
const maxV = Math.max.apply(null, have);
const step = moneyStep((maxV <= 0 ? 1 : maxV * 1.08) / 4);
const fr = moneyFrame(rows, step * 4, step, "Token spend per day");
registerChartTips("money-body", rows.map(r => ({
label: r.day,
series: [["Token spend (daily)", moneyFmt(r.spend_day)]]
})));
const bw = Math.max(1, (fr.W - fr.padL - fr.padR) / fr.n - 1);
for (let i = 0; i < fr.n; i++) {
const v = vals[i];
if (v === null || v === undefined) continue;
const yy = fr.yAt(v);
fr.parts.push('<rect x="' + (fr.xAt(i) - bw / 2) + '" y="' + yy + '" width="' + bw + '" height="' + Math.max(0.6, fr.baseY - yy) + '" fill="' + MONEY_COLORS.spend + '" data-tip-host="money-body" data-tip-i="' + i + '"></rect>');
}
moneyDateMarks(fr, rows);
fr.parts.push("</svg>");
host.innerHTML = fr.parts.join("");
}
// ---- shared state ----
let membersData = [];
let adminsData = [];
@@ -794,15 +1040,20 @@ function switchView(view) {
$('admins-section').style.display = view === 'members' ? '' : 'none';
$('agents-section').style.display = view === 'members' ? '' : 'none';
$('trends-section').style.display = view === 'trends' ? '' : 'none';
$('money-section').style.display = view === 'money' ? '' : 'none';
$('tab-members').className = 'tab-btn' + (view === 'members' ? ' active' : '');
$('tab-models').className = 'tab-btn' + (view === 'models' ? ' active' : '');
$('tab-trends').className = 'tab-btn' + (view === 'trends' ? ' active' : '');
$('view-title').textContent = view === 'members' ? 'Members' : (view === 'models' ? 'Model usage' : 'Trends');
$('tab-money').className = 'tab-btn' + (view === 'money' ? ' active' : '');
$('view-title').textContent = view === 'members' ? 'Members' : (view === 'models' ? 'Model usage' : (view === 'trends' ? 'Trends' : 'Money'));
// Mode groups: Balance/All-time for members; Period for models.
$('range-group').style.display = view === 'models' ? '' : 'none';
$('member-mode-group').style.display = view === 'members' ? '' : 'none';
// Trends renders on first visit only, so the panel's initial load stays fast.
if (view === 'trends') loadMetrics();
// Money renders on first visit only, same rule: one fetch, then the
// period/spend toggles re-render client-side.
if (view === 'money') loadMoney();
render();
}