dashboard: the co-op charts come from the shared definitions (Money included)
ci/woodpecker/push/woodpecker Pipeline was successful

The dashboard kept its own TREND_CONF with its own titles ("The co-op over time",
"What the co-op spent (members + the co-op's own accounts)") and its own toggles —
the other half of the drift the panel just lost. The metric list is now
CoOpChart.CHART_METRICS, the chart is drawn by the shared renderChart(), and the
buttons are built from the shared list, so members and stewards read the same
charts with the same names.

Money arrives as a metric here too, fed by a new /api/money-series proxy to the
portal's /broker/money-series — the co-op's cumulative revenue, cumulative token
spend and OC balance (a gap before snapshots began, never a zero). Deleting the
local TREND_CONF/trendVal/trendLabel also removes the second set of formatters.

Two page-blanking bugs caught by check-page-js.sh before they could ship: a
destructured fmtMoney colliding with this page's own (duplicate const), and `esc`
(which the panel defines and this page does not — it uses escapeHtml).

Harness extended: the money metric draws 2 lines + a single-point balance marker,
the tooltip lists every series and reports the unmeasured balance as not
measured, the metric row equals the shared list filtered by METRIC_SOURCE, and a
metric with no source says so. Geometry proof: 15 captured renders (5 metrics x 3
ranges) byte-identical to the predecessor with aria stripped.
This commit is contained in:
inference-admin committed 2026-11-13 21:01:38 +00:00
1 parent c5d4677ec3
commit d10b817fdc
2 files changed
+169 -71

No files matched your search

+122 -71
View File
@@ -196,6 +196,25 @@ async def api_metrics(request: Request):
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, for the Co-op usage view.
Aggregate and non-personal, exactly like /api/metrics: cumulative revenue,
cumulative token spend, and the co-op's Open Collective balance — no member
identities. The co-op's finances are charted beside its other charts so
members and stewards see the same picture, from the same shared chart
definition (CoOpChart.CHART_METRICS "money").
"""
identity = get_user_identity(request)
if not identity:
return JSONResponse({"error": "unauthenticated"}, status_code=401)
try:
return await broker_get(identity, "/broker/money-series")
except HTTPException as e:
return JSONResponse({"error": e.detail}, status_code=e.status_code)
@app.post("/api/keys")
async def api_create_key(request: Request):
identity = get_user_identity(request)
@@ -579,6 +598,9 @@ PAGE_HTML = """<!DOCTYPE html>
.coop-stats .lbl { font-size: 12px; color: var(--muted); }
.trend-group { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.coop-trend-body svg { display: block; width: 100%; height: auto; overflow: visible; }
.coop-legend { display: inline-flex; gap: 12px; flex-wrap: wrap; font-size: 12px; color: var(--muted); font-weight: 600; margin-left: auto; }
.coop-legend .key { display: inline-flex; align-items: center; gap: 5px; }
.coop-legend .sw { display: inline-block; width: 10px; height: 10px; border-radius: 3px; flex-shrink: 0; }
.board-row {
display: flex; align-items: flex-start; gap: 14px;
padding: 12px 0; border-top: 1px solid #f0ede6;
@@ -811,20 +833,19 @@ PAGE_HTML = """<!DOCTYPE html>
<div id="view-coop" style="display:none;">
<div class="coop-trend">
<div class="coop-trend-head">
<span class="coop-trend-title" id="trend-title">The co-op over time</span>
<span class="coop-trend-title" id="trend-title">Members</span>
<span id="trend-legend" class="coop-legend"></span>
</div>
<div class="coop-stats">
<div class="stat"><div class="num" id="coop-total">—</div><div class="lbl">co-op spend, all time</div></div>
<div class="stat"><div class="num" id="coop-own">—</div><div class="lbl">of which the co-op's own accounts</div></div>
</div>
<div class="coop-trend-controls">
<span class="trend-group">
<span class="trend-group" id="trend-metrics">
<span class="board-note" style="margin:0;">Show</span>
<button class="mode-btn active" id="tm-members" onclick="setTrendMetric('members')">Members</button>
<button class="mode-btn" id="tm-requests" onclick="setTrendMetric('requests')">Requests</button>
<button class="mode-btn" id="tm-spend" onclick="setTrendMetric('spend')">Spend</button>
<button class="mode-btn" id="tm-energy" onclick="setTrendMetric('energy')">Energy</button>
<button class="mode-btn" id="tm-co2e" onclick="setTrendMetric('co2e')">Carbon</button>
<!-- The metric buttons are rendered from CoOpChart.CHART_METRICS, so
this dashboard and the admin panel offer the same metrics, in the
same order, with the same titles. Do not hand-write them here. -->
</span>
<span class="trend-group">
<span class="board-note" style="margin:0;">Period</span>
@@ -1034,7 +1055,8 @@ function fmtDay(s) {
async function loadGuests() {
try {
const r = await fetch('/api/guests');
if (r.status === 401) { location.reload(); return; }
if (r.status === 401) { location.rebuildMetricButtons();
load(); return; }
const d = await r.json().catch(() => ({}));
renderGuests(d);
} catch (e) {
@@ -1322,14 +1344,67 @@ let trendsData = null;
let trendMetric = "members"; // members | requests | spend
let trendDays = 90; // 0 = all time
const TREND_CONF = {
members: { kind: "line", title: "The co-op over time", cont: false },
requests: { kind: "bar", title: "Requests the co-op served", cont: false },
spend: { kind: "bar", title: "What the co-op spent (members + the co-op's own accounts)", cont: true },
energy: { kind: "bar", title: "Energy the co-op used", cont: true },
co2e: { kind: "bar", title: "Carbon the co-op emitted", cont: true }
// The chart definitions live in the shared module (CoOpChart.CHART_METRICS),
// which the admin panel reads too: same metrics, same order, same titles, same
// shapes. This page owns only which fetch feeds each metric (METRIC_SOURCE) and
// its own DOM. Hand-writing a metric list here is what let the two UIs drift.
const METRIC_SOURCE = {
members: "metrics", requests: "metrics", spend: "metrics",
energy: "metrics", co2e: "metrics",
money: "money"
};
function buildMetricButtons() {
const row = $("trend-metrics");
if (!row || row.getAttribute("data-built") === "1") return;
let html = "";
for (const def of CHART_METRICS) {
if (!METRIC_SOURCE[def.id]) continue; // a metric this page cannot fetch
html += '<button class="mode-btn" id="tm-' + def.id + '"'
+ " onclick=\"setTrendMetric('" + def.id + "')\">" + escapeHtml(def.title) + "</button>";
}
row.insertAdjacentHTML("beforeend", html);
row.setAttribute("data-built", "1");
syncMetricButtons();
}
function syncMetricButtons() {
for (const def of CHART_METRICS) {
const b = $("tm-" + def.id);
if (b) b.className = "mode-btn" + (def.id === trendMetric ? " active" : "");
}
}
// The money metric's rows come from the broker (the co-op's finances are
// aggregate, non-personal — see the portal's /broker/money-series).
async function loadMoneySeries() {
if (moneyData) { renderTrends(); return; }
const host = $("trend-body");
try {
const r = await fetch("/api/money-series");
if (r.status === 401 || r.status === 403) { host.innerHTML = "<div class=empty>Sign in to see this.</div>"; return; }
const d = await r.json();
if (d.error) { host.innerHTML = "<div class=empty>" + d.error + "</div>"; return; }
moneyData = d;
renderTrends();
} catch (e) {
host.innerHTML = "<div class=empty>Could not load the co-op money chart</div>";
}
}
function metricRows(id) {
const src = METRIC_SOURCE[id];
if (!src) return null;
if (src === "money") return moneyData ? (moneyData.series || []) : null;
return trendsData;
}
function loadForMetric() {
const src = METRIC_SOURCE[trendMetric];
if (src === "money") { if (moneyData) renderTrends(); else loadMoneySeries(); return; }
if (trendsData) renderTrends(); else loadMetrics();
}
async function loadMetrics() {
if (trendsData) { renderCoopTotals(); renderTrends(); return; }
const host = $("trend-body");
@@ -1362,12 +1437,8 @@ function renderCoopTotals() {
function setTrendMetric(m) {
trendMetric = m;
$("tm-members").className = "mode-btn" + (m === "members" ? " active" : "");
$("tm-requests").className = "mode-btn" + (m === "requests" ? " active" : "");
$("tm-spend").className = "mode-btn" + (m === "spend" ? " active" : "");
$("tm-energy").className = "mode-btn" + (m === "energy" ? " active" : "");
$("tm-co2e").className = "mode-btn" + (m === "co2e" ? " active" : "");
renderTrends();
syncMetricButtons();
loadForMetric();
}
function setTrendDays(d) {
@@ -1378,14 +1449,6 @@ function setTrendDays(d) {
renderTrends();
}
function trendVal(row) {
if (trendMetric === "members") return row.members_total;
if (trendMetric === "spend") return row.spend_usd;
if (trendMetric === "energy") return row.energy_wh;
if (trendMetric === "co2e") return row.co2e_g;
return row.requests;
}
// ---- Shared chart module ----
// Chart rendering + the exact-value hover tooltips come from the shared
// CoOpChart module (canonical: ops-docs scripts/shared/coop_chart.js,
@@ -1396,58 +1459,46 @@ function trendVal(row) {
const {
registerChartTips, hideChartTip, showChartTip, moveChartTip, chartTipTarget,
chartTipData, niceStep, measuredRuns, chartFrame, dateMarks, drawBars,
drawLineRuns, hoverTargets
drawLineRuns, hoverTargets,
CHART_METRICS, metricDef, fmtMetric, renderChart
} = CoOpChart;
// (fmtMoney is NOT destructured: this page already defines its own, byte-identical
// one. Two declarations of the same const is a page-blanking SyntaxError — the
// exact failure check-page-js.sh exists to catch, and it did.)
function trendLabel(v) {
if (v === null || v === undefined) return "not measured";
if (trendMetric === "spend") return fmtMoney(v);
if (trendMetric === "energy") return Number(v).toLocaleString() + " Wh";
if (trendMetric === "co2e") return Number(v).toLocaleString() + " g";
return Number(v).toLocaleString();
}
let moneyData = null; // the money metric's rows (a different endpoint)
function renderTrends() {
const host = $("trend-body");
if (!host || !trendsData) return;
if (!host) return;
hideChartTip();
const conf = TREND_CONF[trendMetric];
const rows = trendDays === 0 ? trendsData : trendsData.slice(-trendDays);
const vals = rows.map(trendVal);
// Exact-value hover tooltips (the shared module's contract): register one
// point per row, straight from the data — same convention as the panel.
registerChartTips("trend-body", rows.map((row, i) => ({
label: row.day,
series: [[conf.title, trendLabel(vals[i])]]
})));
const have = vals.filter(v => v !== null && v !== undefined);
if (have.length < 2) {
host.innerHTML = "<div class=empty>Not enough history yet.</div>";
const def = metricDef(trendMetric);
const legendEl = $("trend-legend");
$("trend-title").textContent = def.title;
const all = metricRows(trendMetric);
if (!all) {
// A metric this page has no source for, versus one it has not fetched yet.
host.innerHTML = METRIC_SOURCE[trendMetric]
? "<div class=empty>Loading</div>"
: "<div class=empty>Not available here.</div>";
if (legendEl) legendEl.innerHTML = "";
return;
}
const maxV = Math.max.apply(null, have);
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, conf.cont);
const fr = chartFrame({
n: vals.length,
top: step * 4,
step,
tickLabel: trendLabel,
aria: conf.title,
gridStroke: "var(--border, #e4e0d8)"
});
if (conf.kind === "bar") {
drawBars(fr, vals, { color: "var(--green-mid)", host: "trend-body" });
} else {
// Measured runs only: a day we never recorded stays a gap.
drawLineRuns(fr, vals, { color: "var(--green-deep)", area: true });
hoverTargets(fr, vals, "trend-body");
const rows = trendDays === 0 ? all : all.slice(-trendDays);
// The shared renderer: it draws the chart, registers the exact tooltip values
// and hands back the legend, so this chart is the same chart the panel draws.
const out = renderChart({ host: "trend-body", def, rows, gridStroke: "var(--border, #e4e0d8)" });
if (out.empty) {
host.innerHTML = "<div class=empty>Not enough history yet.</div>";
if (legendEl) legendEl.innerHTML = "";
return;
}
host.innerHTML = out.svg;
if (legendEl) {
legendEl.innerHTML = out.legend.map(it =>
'<span class="key"><span class="sw" style="background:' + it.color + '"></span>'
+ escapeHtml(it.name) + "</span>").join("");
}
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
host.innerHTML = fr.parts.join("");
}
// ---- My usage over time (chart) ----