Trends: one chart area for every metric, Money included, drawn by the shared module
ci/woodpecker/push/woodpecker Pipeline failed

Money was its own tab with its own renderers (renderMoney, renderMoneyCumulative,
renderMoneyDaily, renderMoneyLegend), its own period and spend-mode toggles, and
its own titles. It is now a metric of Trends like the others: the definitions come
from CoOpChart.CHART_METRICS, the chart is drawn by the shared renderChart(), and
the Money tab is a shortcut into Trends with that metric selected.

Removed: TREND_CONF, trendVal, trendLabel, the four money renderers, the
period/spend-mode toggles (the single Period row governs every metric now) — 5.1k
chars of duplicate chart code. Added: METRIC_SOURCE (which fetch each metric
needs), buildMetricButtons() (buttons rendered from the shared list, so the panel
and dashboard describe the same charts in the same order), and the metric-aware
renderTrends() that delegates.

The daily token-spend view is now the shared "spend" metric — the same numbers the
metrics endpoint already served, so nothing is lost by dropping the second source.
No caption under the money chart, as before.

Harness rewritten for the new path (it drove renderMoney): invariants preserved —
2 cumulative polylines + single-point balance marker, shared tooltip host, legend
that IS the definition's series list, 5 ascending ticks with the top clearing the
max, 30-day slice. New: every shared metric has a button, and a metric with no
source says so instead of drawing another chart. Tests green (page JS, pins,
guest guard).
This commit is contained in:
inference-admin committed 2026-11-13 20:55:59 +00:00
1 parent 79f3f00165
commit fba50e3f93
5 files changed
+390 -288

No files matched your search

+161 -1
View File
@@ -44,6 +44,21 @@
* drawBars(fr, vals, opts) bars; NULLs skipped (no zero bars).
* drawLineRuns(fr, vals, opts) lines broken into measured runs.
* hoverTargets(fr, vals, host) transparent hover circles on measured points.
*
* Definition layer — the ONE place a chart is described (both UIs read it):
* CHART_METRICS the metric list, in order: id, title, kind (line|bar|multi),
* cont (continuous axis), fmt (money|count|wh|g), val(row);
* "multi" carries `series` (the money chart). Anything a
* member may see belongs in this list.
* metricDef(id) the definition for a metric id.
* fmtMoney/fmtMetric/fmtMoneyTick shared value formatters, so both apps'
* labels match byte for byte.
* renderChart({host, def, rows, aria}) -> { svg, legend, empty? }
* one renderer for both UIs: registers the EXACT tooltip
* values, breaks lines at NULLs (a gap is never a zero), and
* returns markup plus legend items. The APP writes the DOM —
* element ids, toggle class names and empty-state markup are
* the only parts that legitimately differ per app.
*/
(function (global) {
"use strict";
@@ -241,6 +256,144 @@
}
}
// ==== Chart definitions — the ONE place a chart is described ==============
// A chart is DATA here, not markup: the same metrics, in the same order, with
// the same titles and the same shape in every UI. Each app supplies its own
// data rows and its own DOM (its toggle classes, its empty-state markup, its
// legend element), which is the only thing that legitimately differs.
//
// WHY: the two UIs had drifted while sharing only the drawing primitives —
// the same five metrics shipped with different titles and different chart
// kinds (the panel's "Spend per day" was the dashboard's "What the co-op
// spent (members + the co-op's own accounts)"). Anything a member may see
// belongs in THIS list, so it exists once and cannot drift again.
//
// fmt selects the value formatter: "money" | "count" | "wh" | "g".
// kind is "line" | "bar" | "multi" (multi = N series on one axis, the money
// chart: cumulative revenue, cumulative token spend, and the OC balance,
// which only exists from the day the snapshots began, so it draws as a gap
// before that — never as a zero).
const CHART_METRICS = [
{ id: "members", title: "Members", kind: "line", cont: false, fmt: "count",
val: r => r.members_total },
{ id: "requests", title: "Requests per day", kind: "bar", cont: false, fmt: "count",
val: r => r.requests },
{ id: "spend", title: "Token spend per day", kind: "bar", cont: true, fmt: "money",
val: r => r.spend_usd },
{ id: "money", title: "Money", kind: "multi", cont: true, fmt: "money",
aria: "Cumulative revenue, token spend and OC balance over time",
series: [
{ name: "Revenue", key: "revenue_cum", color: "var(--green-deep)" },
{ name: "Token spend", key: "spend_cum", color: "#4a6a8a" },
{ name: "OC balance", key: "oc_balance", color: "#a97a2a", dotSingle: true }
] },
{ id: "energy", title: "Energy per day", kind: "bar", cont: true, fmt: "wh",
val: r => r.energy_wh },
{ id: "co2e", title: "Carbon per day", kind: "bar", cont: true, fmt: "g",
val: r => r.co2e_g }
];
function metricDef(id) {
for (let i = 0; i < CHART_METRICS.length; i++) if (CHART_METRICS[i].id === id) return CHART_METRICS[i];
return CHART_METRICS[0];
}
// ---- Value formatting (shared so the two apps' labels match byte for byte;
// both already agreed, this only stops them from diverging) ----
function fmtMoney(v) {
const n = Math.abs(Number(v)) < 0.005 ? 0 : (Number(v) || 0);
return "$" + n.toFixed(2);
}
function fmtMetric(def, v) {
if (v === null || v === undefined) return "not measured"; // the gap rule
switch (def && def.fmt) {
case "money": return fmtMoney(v);
case "wh": return Number(v).toLocaleString() + " Wh";
case "g": return Number(v).toLocaleString() + " g";
default: return Number(v).toLocaleString();
}
}
// Money-axis ticks: the 1/2/5 x 10^k rule (niceStep continuous) with integer
// dollars at or above $1 and cents below, so a $0.50 tick does not read "$1".
function fmtMoneyTick(v) {
return v >= 1 ? "$" + Math.round(v).toLocaleString() : "$" + v.toFixed(2);
}
// ---- The chart renderer: one implementation for both UIs ----
// renderChart({ host, def, rows, aria }) -> { svg, legend }
// * registers the EXACT tooltip values (the module's contract) under `host`
// * returns the SVG string and the legend items; the APP writes the DOM,
// because that is the part that differs (element ids, class names)
// * a NULL value stays a GAP: no zero, no bar, and no tooltip stamp
// `rows` for a "multi" chart carry the series keys; otherwise `def.val(row)`.
function renderChart(cfg) {
const def = cfg.def, rows = cfg.rows || [], host = cfg.host;
const legend = [];
if (def.kind === "multi") {
const series = def.series || [];
const vals = series.map(s => rows.map(r => r[s.key]));
const tops = [];
for (let si = 0; si < vals.length; si++) {
for (let i = 0; i < vals[si].length; i++) {
const v = vals[si][i];
if (v !== null && v !== undefined) tops.push(v);
}
}
const maxV = tops.length ? Math.max.apply(null, tops) : 0;
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, true);
const fr = chartFrame({
n: rows.length, top: step * 4, step,
tickLabel: def.fmt === "money" ? fmtMoneyTick : (v => fmtMetric(def, v)),
aria: cfg.aria || def.aria || def.title,
gridStroke: cfg.gridStroke || "var(--border)"
});
registerChartTips(host, rows.map((r, i) => ({
label: r.day,
series: series.map((s, si) => [s.name, fmtMetric(def, vals[si][i])])
})));
for (let si = 0; si < series.length; si++) {
const s = series[si];
drawLineRuns(fr, vals[si], {
color: s.color, dotSingle: s.dotSingle !== false, dotR: 3,
area: !!s.area, areaOpacity: s.areaOpacity
});
hoverTargets(fr, vals[si], host);
legend.push({ color: s.color, name: s.name });
}
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
return { svg: fr.parts.join(""), legend };
}
const vals = rows.map(def.val);
registerChartTips(host, rows.map((r, i) => ({
label: r.day,
series: [[def.title, fmtMetric(def, vals[i])]]
})));
const have = vals.filter(v => v !== null && v !== undefined);
if (have.length < 2) return { svg: "", legend, empty: true };
const maxV = Math.max.apply(null, have);
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, def.cont);
const tickLabel = v => fmtMetric(def, v);
const fr = chartFrame({
n: vals.length, top: step * 4, step, tickLabel,
aria: cfg.aria || (def.title + " over time"),
gridStroke: cfg.gridStroke || "var(--border)"
});
if (def.kind === "bar") {
drawBars(fr, vals, { color: "var(--green-mid)", host });
} else {
drawLineRuns(fr, vals, { color: "var(--green-deep)", area: true });
hoverTargets(fr, vals, host);
}
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
return { svg: fr.parts.join(""), legend };
}
// chartTipData is exported for inspection (harnesses assert on the exact
// registered points); treat it as read-only in page code.
global.CoOpChart = {
@@ -256,6 +409,13 @@
dateMarks,
drawBars,
drawLineRuns,
hoverTargets
hoverTargets,
// the definition layer both UIs read
CHART_METRICS,
metricDef,
fmtMoney,
fmtMetric,
fmtMoneyTick,
renderChart
};
})(typeof globalThis !== "undefined" ? globalThis : window);
+127 -246
View File
@@ -484,7 +484,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>
<button class="tab-btn" id="tab-money" onclick="showMoney()">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>
@@ -552,13 +552,13 @@ PAGE_HTML = """<!DOCTYPE html>
<div id="trends-section" style="display:none;">
<div class="trend-controls">
<span class="range-group">
<span class="range-group" id="trend-metrics">
<span class="range-label">Show</span>
<button class="range-btn active" id="tm-members" onclick="setTrendMetric('members')">Members</button>
<button class="range-btn" id="tm-spend" onclick="setTrendMetric('spend')">Spend</button>
<button class="range-btn" id="tm-energy" onclick="setTrendMetric('energy')">Energy</button>
<button class="range-btn" id="tm-co2e" onclick="setTrendMetric('co2e')">Carbon</button>
<button class="range-btn" id="tm-requests" onclick="setTrendMetric('requests')">Requests</button>
<!-- The metric buttons are rendered from CoOpChart.CHART_METRICS, so this
panel and the member dashboard describe the same charts, in the same
order, with the same titles — Money included, as one metric among the
others. Editing the list here would defeat that: edit the canonical
module (ops-docs scripts/shared/coop_chart.js) instead. -->
</span>
<span class="range-group">
<span class="range-label">Period</span>
@@ -570,34 +570,12 @@ PAGE_HTML = """<!DOCTYPE html>
<div class="trend-card">
<div class="trend-head">
<span class="trend-title" id="trend-title">Members</span>
<span id="trend-legend" class="money-legend"></span>
</div>
<div id="trend-body" class="trend-body"><p class="trend-empty">Loading</p></div>
</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>
</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>
@@ -733,14 +711,43 @@ let trendsData = null;
let trendMetric = "members"; // members | spend | requests
let trendDays = 90; // 0 = all time
const TREND_CONF = {
members: { kind: "line", title: "Members", cont: false },
requests: { kind: "bar", title: "Requests per day", cont: false },
spend: { kind: "bar", title: "Spend per day", cont: true },
energy: { kind: "bar", title: "Energy per day", cont: true },
co2e: { kind: "bar", title: "Carbon per day", cont: true }
// ---- Trends: ONE chart area, described by the shared module ----
// Every metric this page can show — Money included — is defined once in
// CoOpChart.CHART_METRICS (canonical: ops-docs scripts/shared/coop_chart.js),
// which the member dashboard reads as well. This app owns the DATA (which
// endpoint feeds a metric, and which fetch it is allowed to make) and the DOM;
// the chart itself — titles, shape, axis rule, formatters — comes from the
// module, so the two UIs cannot drift apart again.
//
// A metric with no entry here is one this page can draw from ANOTHER source:
// METRIC_SOURCE maps metric -> fetch. Adding a metric to the shared list puts
// its button in both UIs at once; wiring it in one app only is what this map is.
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) {
html += '<button class="range-btn" id="tm-' + def.id + '"'
+ " onclick=\"setTrendMetric('" + def.id + "')\">" + esc(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 = "range-btn" + (def.id === trendMetric ? " active" : "");
}
}
async function loadMetrics() {
if (trendsData) { renderTrends(); return; }
const host = $("trend-body");
@@ -756,14 +763,42 @@ async function loadMetrics() {
}
}
// The money metric's rows come from /api/money-series (the OC queries behind it
// are slow, so the portal caches them server-side). Fetched on first use.
async function loadMoneySeries() {
if (moneyData) { renderTrends(); return; }
const host = $("trend-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;
renderTrends();
} catch (e) {
host.innerHTML = "<p class=trend-empty>Could not load the money series.</p>";
}
}
// Rows for a metric, or null when this page cannot get them. One place decides
// which fetch a metric needs, so setTrendMetric and the first paint agree.
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();
}
function setTrendMetric(m) {
trendMetric = m;
$("tm-members").className = "range-btn" + (m === "members" ? " active" : "");
$("tm-spend").className = "range-btn" + (m === "spend" ? " active" : "");
$("tm-energy").className = "range-btn" + (m === "energy" ? " active" : "");
$("tm-co2e").className = "range-btn" + (m === "co2e" ? " active" : "");
$("tm-requests").className = "range-btn" + (m === "requests" ? " active" : "");
renderTrends();
syncMetricButtons();
loadForMetric();
}
function setTrendDays(d) {
@@ -774,22 +809,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;
}
function trendLabel(v) {
if (v === null || v === undefined) return "not measured";
if (trendMetric === "spend") return fmt(v);
if (trendMetric === "energy") return Number(v).toLocaleString() + " Wh";
if (trendMetric === "co2e") return Number(v).toLocaleString() + " g";
return Number(v).toLocaleString();
}
// ---- Shared chart module ----
// Chart rendering + the exact-value hover tooltips come from the shared
// CoOpChart module (canonical: ops-docs scripts/shared/coop_chart.js,
@@ -800,198 +819,53 @@ function trendLabel(v) {
const {
registerChartTips, hideChartTip, showChartTip, moveChartTip, chartTipTarget,
chartTipData, niceStep, measuredRuns, chartFrame, dateMarks, drawBars,
drawLineRuns, hoverTargets
drawLineRuns, hoverTargets,
CHART_METRICS, metricDef, fmtMetric, fmtMoney, renderChart
} = CoOpChart;
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);
$("trend-title").textContent = conf.title;
const vals = rows.map(trendVal);
// Register the EXACT values the tooltips will show, straight from the data
// rows - one point per index, in the same order as the stamped elements.
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 = "<p class=trend-empty>Not enough history yet.</p>";
const def = metricDef(trendMetric);
const legendEl = $("trend-legend");
$("trend-title").textContent = def.title;
const all = metricRows(trendMetric);
if (!all) {
// Two different situations, said differently: a metric this page HAS a
// source for but has not fetched yet, and one it has no source for at all.
host.innerHTML = METRIC_SOURCE[trendMetric]
? "<p class=trend-empty>Loading</p>"
: "<p class=trend-empty>Not available on this page.</p>";
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 + " over time",
gridStroke: "var(--border)"
});
if (conf.kind === "bar") {
drawBars(fr, vals, { color: "var(--green-mid)", host: "trend-body" });
} else {
// Measured runs only: a gap stays a gap (the module breaks the line).
drawLineRuns(fr, vals, { color: "var(--green-deep)", area: true });
hoverTargets(fr, vals, "trend-body");
const rows = trendDays === 0 ? all : all.slice(-trendDays);
// One renderer for every metric, shared with the member dashboard: it draws
// the chart, registers the exact tooltip values, and hands back the legend.
const out = renderChart({ host: "trend-body", def, rows, gridStroke: "var(--border)" });
if (out.empty) {
host.innerHTML = "<p class=trend-empty>Not enough history yet.</p>";
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>'
+ esc(it.name) + "</span>").join("");
}
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
host.innerHTML = fr.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 — never a zero. No caption under the chart:
// the data explains itself (the operator dropped the balance-history caveat).
// ---- Money is now a metric of Trends, like everything else ------------
// The chart (cumulative revenue, cumulative token spend, and the OC balance —
// which exists only from the day the snapshots began, so it draws as a gap
// before that, never a zero) is DEFINED in the shared module and drawn by
// renderTrends() when the money metric is selected: the same chart the member
// dashboard draws from the same definition. This page keeps only the rows it
// fetched; the period toggle above governs it like every other metric, so the
// separate period/spend-mode controls are gone.
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 (niceStep(raw, true) from the shared
// module). 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 renderMoney() {
const host = $("money-body");
if (!host || !moneyData) return;
hideChartTip();
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") {
items.push({ c: MONEY_COLORS.balance, t: "OC balance" });
}
$("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 = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, true);
const fr = chartFrame({
n: rows.length,
top: step * 4,
step,
tickLabel: moneyTickLabel,
aria: "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) {
// Measured runs only: a NULL (the balance before snapshots began) stays a
// gap — the line is never drawn through invented history.
drawLineRuns(fr, rows.map(r => r[s.key]), { color: s.color, dotSingle: true, dotR: 3 });
}
// 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) {
hoverTargets(fr, rows.map(r => r[s.key]), "money-body");
}
dateMarks(fr, rows.map(r => r.day));
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 = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4, true);
const fr = chartFrame({
n: rows.length,
top: step * 4,
step,
tickLabel: moneyTickLabel,
aria: "Token spend per day"
});
registerChartTips("money-body", rows.map(r => ({
label: r.day,
series: [["Token spend (daily)", moneyFmt(r.spend_day)]]
})));
drawBars(fr, vals, { color: MONEY_COLORS.spend, host: "money-body" });
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
host.innerHTML = fr.parts.join("");
}
// ---- shared state ----
let membersData = [];
@@ -1020,6 +894,14 @@ function clearArrows(table, sortState) {
});
}
// Money: a shortcut into Trends with the money metric selected — one chart
// area, one code path, the same chart the member dashboard draws.
function showMoney() {
buildMetricButtons();
switchView('trends');
setTrendMetric('money');
}
function switchView(view) {
currentView = view;
hideChartTip();
@@ -1031,22 +913,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' : '');
$('tab-money').className = 'tab-btn' + (view === 'money' ? ' active' : '');
$('view-title').textContent = view === 'members' ? 'Members' : (view === 'models' ? 'Model usage' : (view === 'trends' ? 'Trends' : 'Money'));
// Money is a metric of Trends, so its tab shows the Trends title.
$('view-title').textContent = view === 'members' ? 'Members' : (view === 'models' ? 'Model usage' : 'Trends');
// Mode groups: Balance/All-time for members; Period for models; the guest
// invite form belongs to the members view too.
$('range-group').style.display = view === 'models' ? '' : 'none';
$('member-mode-group').style.display = view === 'members' ? '' : 'none';
$('guest-invite-section').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();
// loadForMetric fetches whatever the SELECTED metric needs (the money rows
// come from a different endpoint than the rest).
if (view === 'trends') loadForMetric();
render();
}
@@ -1349,6 +1229,7 @@ async function sendGuestAccess(ev) {
// inviter, credits, expiry and status, exactly like admin-created ones.
// The portal's /admin/guest-ledger still feeds the duplicate-send guard.
buildMetricButtons();
load();
loadModels();
</script>