dashboard: the co-op charts come from the shared definitions (Money included)
ci/woodpecker/push/woodpecker Pipeline was successful
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:
1 parent
c5d4677ec3
commit
d10b817fdc
2 files changed
+169
-71
No files matched your search
+122
-71
@@ -196,6 +196,25 @@ async def api_metrics(request: Request):
|
|||||||
return JSONResponse({"error": e.detail}, status_code=e.status_code)
|
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")
|
@app.post("/api/keys")
|
||||||
async def api_create_key(request: Request):
|
async def api_create_key(request: Request):
|
||||||
identity = get_user_identity(request)
|
identity = get_user_identity(request)
|
||||||
@@ -579,6 +598,9 @@ PAGE_HTML = """<!DOCTYPE html>
|
|||||||
.coop-stats .lbl { font-size: 12px; color: var(--muted); }
|
.coop-stats .lbl { font-size: 12px; color: var(--muted); }
|
||||||
.trend-group { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
.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-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 {
|
.board-row {
|
||||||
display: flex; align-items: flex-start; gap: 14px;
|
display: flex; align-items: flex-start; gap: 14px;
|
||||||
padding: 12px 0; border-top: 1px solid #f0ede6;
|
padding: 12px 0; border-top: 1px solid #f0ede6;
|
||||||
@@ -811,20 +833,19 @@ PAGE_HTML = """<!DOCTYPE html>
|
|||||||
<div id="view-coop" style="display:none;">
|
<div id="view-coop" style="display:none;">
|
||||||
<div class="coop-trend">
|
<div class="coop-trend">
|
||||||
<div class="coop-trend-head">
|
<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>
|
||||||
<div class="coop-stats">
|
<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-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 class="stat"><div class="num" id="coop-own">—</div><div class="lbl">of which the co-op's own accounts</div></div>
|
||||||
</div>
|
</div>
|
||||||
<div class="coop-trend-controls">
|
<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>
|
<span class="board-note" style="margin:0;">Show</span>
|
||||||
<button class="mode-btn active" id="tm-members" onclick="setTrendMetric('members')">Members</button>
|
<!-- The metric buttons are rendered from CoOpChart.CHART_METRICS, so
|
||||||
<button class="mode-btn" id="tm-requests" onclick="setTrendMetric('requests')">Requests</button>
|
this dashboard and the admin panel offer the same metrics, in the
|
||||||
<button class="mode-btn" id="tm-spend" onclick="setTrendMetric('spend')">Spend</button>
|
same order, with the same titles. Do not hand-write them here. -->
|
||||||
<button class="mode-btn" id="tm-energy" onclick="setTrendMetric('energy')">Energy</button>
|
|
||||||
<button class="mode-btn" id="tm-co2e" onclick="setTrendMetric('co2e')">Carbon</button>
|
|
||||||
</span>
|
</span>
|
||||||
<span class="trend-group">
|
<span class="trend-group">
|
||||||
<span class="board-note" style="margin:0;">Period</span>
|
<span class="board-note" style="margin:0;">Period</span>
|
||||||
@@ -1034,7 +1055,8 @@ function fmtDay(s) {
|
|||||||
async function loadGuests() {
|
async function loadGuests() {
|
||||||
try {
|
try {
|
||||||
const r = await fetch('/api/guests');
|
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(() => ({}));
|
const d = await r.json().catch(() => ({}));
|
||||||
renderGuests(d);
|
renderGuests(d);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -1322,14 +1344,67 @@ let trendsData = null;
|
|||||||
let trendMetric = "members"; // members | requests | spend
|
let trendMetric = "members"; // members | requests | spend
|
||||||
let trendDays = 90; // 0 = all time
|
let trendDays = 90; // 0 = all time
|
||||||
|
|
||||||
const TREND_CONF = {
|
// The chart definitions live in the shared module (CoOpChart.CHART_METRICS),
|
||||||
members: { kind: "line", title: "The co-op over time", cont: false },
|
// which the admin panel reads too: same metrics, same order, same titles, same
|
||||||
requests: { kind: "bar", title: "Requests the co-op served", cont: false },
|
// shapes. This page owns only which fetch feeds each metric (METRIC_SOURCE) and
|
||||||
spend: { kind: "bar", title: "What the co-op spent (members + the co-op's own accounts)", cont: true },
|
// its own DOM. Hand-writing a metric list here is what let the two UIs drift.
|
||||||
energy: { kind: "bar", title: "Energy the co-op used", cont: true },
|
const METRIC_SOURCE = {
|
||||||
co2e: { kind: "bar", title: "Carbon the co-op emitted", cont: true }
|
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() {
|
async function loadMetrics() {
|
||||||
if (trendsData) { renderCoopTotals(); renderTrends(); return; }
|
if (trendsData) { renderCoopTotals(); renderTrends(); return; }
|
||||||
const host = $("trend-body");
|
const host = $("trend-body");
|
||||||
@@ -1362,12 +1437,8 @@ function renderCoopTotals() {
|
|||||||
|
|
||||||
function setTrendMetric(m) {
|
function setTrendMetric(m) {
|
||||||
trendMetric = m;
|
trendMetric = m;
|
||||||
$("tm-members").className = "mode-btn" + (m === "members" ? " active" : "");
|
syncMetricButtons();
|
||||||
$("tm-requests").className = "mode-btn" + (m === "requests" ? " active" : "");
|
loadForMetric();
|
||||||
$("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();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function setTrendDays(d) {
|
function setTrendDays(d) {
|
||||||
@@ -1378,14 +1449,6 @@ function setTrendDays(d) {
|
|||||||
renderTrends();
|
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 ----
|
// ---- Shared chart module ----
|
||||||
// Chart rendering + the exact-value hover tooltips come from the shared
|
// Chart rendering + the exact-value hover tooltips come from the shared
|
||||||
// CoOpChart module (canonical: ops-docs scripts/shared/coop_chart.js,
|
// CoOpChart module (canonical: ops-docs scripts/shared/coop_chart.js,
|
||||||
@@ -1396,58 +1459,46 @@ function trendVal(row) {
|
|||||||
const {
|
const {
|
||||||
registerChartTips, hideChartTip, showChartTip, moveChartTip, chartTipTarget,
|
registerChartTips, hideChartTip, showChartTip, moveChartTip, chartTipTarget,
|
||||||
chartTipData, niceStep, measuredRuns, chartFrame, dateMarks, drawBars,
|
chartTipData, niceStep, measuredRuns, chartFrame, dateMarks, drawBars,
|
||||||
drawLineRuns, hoverTargets
|
drawLineRuns, hoverTargets,
|
||||||
|
CHART_METRICS, metricDef, fmtMetric, renderChart
|
||||||
} = CoOpChart;
|
} = 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) {
|
let moneyData = null; // the money metric's rows (a different endpoint)
|
||||||
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();
|
|
||||||
}
|
|
||||||
|
|
||||||
function renderTrends() {
|
function renderTrends() {
|
||||||
const host = $("trend-body");
|
const host = $("trend-body");
|
||||||
if (!host || !trendsData) return;
|
if (!host) return;
|
||||||
hideChartTip();
|
hideChartTip();
|
||||||
const conf = TREND_CONF[trendMetric];
|
const def = metricDef(trendMetric);
|
||||||
const rows = trendDays === 0 ? trendsData : trendsData.slice(-trendDays);
|
const legendEl = $("trend-legend");
|
||||||
|
$("trend-title").textContent = def.title;
|
||||||
const vals = rows.map(trendVal);
|
const all = metricRows(trendMetric);
|
||||||
// Exact-value hover tooltips (the shared module's contract): register one
|
if (!all) {
|
||||||
// point per row, straight from the data — same convention as the panel.
|
// A metric this page has no source for, versus one it has not fetched yet.
|
||||||
registerChartTips("trend-body", rows.map((row, i) => ({
|
host.innerHTML = METRIC_SOURCE[trendMetric]
|
||||||
label: row.day,
|
? "<div class=empty>Loading</div>"
|
||||||
series: [[conf.title, trendLabel(vals[i])]]
|
: "<div class=empty>Not available here.</div>";
|
||||||
})));
|
if (legendEl) legendEl.innerHTML = "";
|
||||||
const have = vals.filter(v => v !== null && v !== undefined);
|
|
||||||
if (have.length < 2) {
|
|
||||||
host.innerHTML = "<div class=empty>Not enough history yet.</div>";
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const maxV = Math.max.apply(null, have);
|
const rows = trendDays === 0 ? all : all.slice(-trendDays);
|
||||||
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, conf.cont);
|
// The shared renderer: it draws the chart, registers the exact tooltip values
|
||||||
const fr = chartFrame({
|
// and hands back the legend, so this chart is the same chart the panel draws.
|
||||||
n: vals.length,
|
const out = renderChart({ host: "trend-body", def, rows, gridStroke: "var(--border, #e4e0d8)" });
|
||||||
top: step * 4,
|
if (out.empty) {
|
||||||
step,
|
host.innerHTML = "<div class=empty>Not enough history yet.</div>";
|
||||||
tickLabel: trendLabel,
|
if (legendEl) legendEl.innerHTML = "";
|
||||||
aria: conf.title,
|
return;
|
||||||
gridStroke: "var(--border, #e4e0d8)"
|
}
|
||||||
});
|
host.innerHTML = out.svg;
|
||||||
|
if (legendEl) {
|
||||||
if (conf.kind === "bar") {
|
legendEl.innerHTML = out.legend.map(it =>
|
||||||
drawBars(fr, vals, { color: "var(--green-mid)", host: "trend-body" });
|
'<span class="key"><span class="sw" style="background:' + it.color + '"></span>'
|
||||||
} else {
|
+ escapeHtml(it.name) + "</span>").join("");
|
||||||
// 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");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
dateMarks(fr, rows.map(r => r.day));
|
|
||||||
fr.parts.push("</svg>");
|
|
||||||
host.innerHTML = fr.parts.join("");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- My usage over time (chart) ----
|
// ---- My usage over time (chart) ----
|
||||||
|
|||||||
@@ -124,5 +124,52 @@ function mkDaily() {
|
|||||||
assert(box.style.display === "none", "tooltip hides off-chart");
|
assert(box.style.display === "none", "tooltip hides off-chart");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ---- the money metric: the SHARED definition, the same chart the panel draws ----
|
||||||
|
{
|
||||||
|
moneyData = { series: [
|
||||||
|
{ day: "2026-11-01", revenue_cum: 100, spend_cum: 20, oc_balance: null },
|
||||||
|
{ day: "2026-11-02", revenue_cum: 220, spend_cum: 45, oc_balance: null },
|
||||||
|
{ day: "2026-11-03", revenue_cum: 260, spend_cum: 51, oc_balance: 1160.25 },
|
||||||
|
] };
|
||||||
|
setTrendMetric("money");
|
||||||
|
const body = document.getElementById("trend-body").innerHTML;
|
||||||
|
const def = metricDef("money");
|
||||||
|
assert(def.series.length === 3, "the shared money definition carries 3 series");
|
||||||
|
assert((body.match(/<polyline /g) || []).length === 2,
|
||||||
|
"money chart draws revenue + spend as lines");
|
||||||
|
assert(/<circle cx="[^"]+" cy="[^"]+" r="3"/.test(body),
|
||||||
|
"the balance (one measured day) renders as a marker, not a line through gaps");
|
||||||
|
const legend = document.getElementById("trend-legend").innerHTML;
|
||||||
|
for (const sr of def.series) {
|
||||||
|
assert(legend.indexOf(sr.name) !== -1, "legend is the definition's series: " + sr.name);
|
||||||
|
}
|
||||||
|
const pts = chartTipData["trend-body"];
|
||||||
|
assert(pts[0].series.length === 3, "the tooltip lists EVERY series at that x");
|
||||||
|
assert(pts[0].series[2][1] === "not measured",
|
||||||
|
"the balance before snapshots began reads not measured, never $0.00");
|
||||||
|
assert(pts[2].series[2][1] === "$1,160.25" || pts[2].series[2][1] === "$1160.25",
|
||||||
|
"the balance value is exact (got " + pts[2].series[2][1] + ")");
|
||||||
|
|
||||||
|
// The metric row comes from the shared list, filtered to what this page can fetch.
|
||||||
|
buildMetricButtons();
|
||||||
|
let expected = 0;
|
||||||
|
for (const m of CHART_METRICS) if (METRIC_SOURCE[m.id]) expected++;
|
||||||
|
let rendered = 0;
|
||||||
|
for (const m of CHART_METRICS) if (document.getElementById("tm-" + m.id)) rendered++;
|
||||||
|
assert(rendered === expected && expected === 6,
|
||||||
|
"every shared metric this page can fetch has a button (got " + rendered + "/" + expected + ")");
|
||||||
|
assert(document.getElementById("tm-money") !== null,
|
||||||
|
"Money is a metric here too, not an admin-only tab");
|
||||||
|
|
||||||
|
// A metric in the shared list with no source here must SAY so.
|
||||||
|
const savedIntro = METRIC_SOURCE.energy;
|
||||||
|
delete METRIC_SOURCE.energy;
|
||||||
|
setTrendMetric("energy");
|
||||||
|
assert(document.getElementById("trend-body").innerHTML.indexOf("Not available here") !== -1,
|
||||||
|
"a metric this page cannot fetch says so instead of drawing another chart");
|
||||||
|
METRIC_SOURCE.energy = savedIntro;
|
||||||
|
buildMetricButtons();
|
||||||
|
}
|
||||||
|
|
||||||
console.log("DASHBOARD CHART HARNESS OK: shared module tooltips, exact values, gaps, toggles");
|
console.log("DASHBOARD CHART HARNESS OK: shared module tooltips, exact values, gaps, toggles");
|
||||||
})().catch((e) => { console.error("FAIL: " + (e && e.stack || e)); process.exit(1); });
|
})().catch((e) => { console.error("FAIL: " + (e && e.stack || e)); process.exit(1); });
|
||||||
Reference in new issue
Block a user