diff --git a/app/coop_chart.js b/app/coop_chart.js
index d1a4953..7124a74 100644
--- a/app/coop_chart.js
+++ b/app/coop_chart.js
@@ -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("");
+ 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("");
+ 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);
diff --git a/app/main.py b/app/main.py
index 7a3c5c6..feb7724 100644
--- a/app/main.py
+++ b/app/main.py
@@ -484,7 +484,7 @@ PAGE_HTML = """
-
+
@@ -552,13 +552,13 @@ PAGE_HTML = """
-
+ Show
-
-
-
-
-
+
Period
@@ -570,34 +570,12 @@ PAGE_HTML = """
Members
+
Loading
-
-
-
- Period
-
-
-
-
-
- Token spend
-
-
-
-
-
-
- Revenue, spend and balance
-
-
-
Loading
-
-
-
Agents
Bot and sandbox accounts. Not members — excluded from member counts; their usage is a collective expense.
@@ -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 += '";
+ }
+ 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 = "
Forbidden
"; return; }
+ const d = await r.json();
+ if (d.error) { host.innerHTML = "
";
+ }
+}
+
+// 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 = "
Not enough history yet.
";
+ 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]
+ ? "
Loading
"
+ : "
Not available on this page.
";
+ 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 = "
Not enough history yet.
";
+ if (legendEl) legendEl.innerHTML = "";
+ return;
+ }
+ host.innerHTML = out.svg;
+ if (legendEl) {
+ legendEl.innerHTML = out.legend.map(it =>
+ ''
+ + esc(it.name) + "").join("");
}
-
- dateMarks(fr, rows.map(r => r.day));
- fr.parts.push("");
- 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 = "
Forbidden
"; return; }
- const d = await r.json();
- if (d.error) { host.innerHTML = "