From fba50e3f93009415ac1a32a7bf61b3ab4e618ca0 Mon Sep 17 00:00:00 2001 From: Inferencebot Date: Fri, 13 Nov 2026 20:55:52 +0000 Subject: [PATCH] Trends: one chart area for every metric, Money included, drawn by the shared module MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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). --- app/coop_chart.js | 162 ++++++++++++++- app/main.py | 373 ++++++++++++----------------------- tests/check-page-js.sh | 20 +- tests/money-chart-harness.js | 121 ++++++++---- tests/test_chart_sync.py | 2 +- 5 files changed, 390 insertions(+), 288 deletions(-) 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 = """