usage charts on the shared chart module: my-usage chart + co-op trend tooltips

Both usage views get charts. The co-op trend refactor onto the shared
coop_chart.js module replaces its native <title> tooltips with the panel's
exact-value hover tooltips (registerChartTips contract). NEW: the my-usage
view gets a per-day chart (Spend/Requests metric toggle, 30/90/all-time
period toggle) fed by /broker/usage's new daily series, same shared module,
same tooltip contract. No chart library, no CDN.
CI: .woodpecker.yml (oidc + chart sync pins, both harnesses via the vendored
check-page-js.sh, which splices the module as the app does).
Verified: rendering captured across all chart states matches the panel's
shared-module output; harnesses exercise exact values, zero days, gaps,
clamping, no-refetch toggles.
This commit is contained in:
inference-bot committed 2026-11-13 16:11:23 +00:00
1 parent 622982a371
commit 8c469c1242
6 files changed
+750 -67

No files matched your search

+156 -67
View File
@@ -18,6 +18,7 @@ Environment (all provided by Cloudron env vars):
import os
import logging
from pathlib import Path
import re
import httpx
@@ -426,6 +427,12 @@ def render_page(identity: str) -> str:
)
# The shared chart module (canonical: ops-docs scripts/shared/coop_chart.js,
# byte-identical copy at app/coop_chart.js — tests/test_chart_sync.py pins it)
# is spliced into the page's single <script> block at import time, above the
# page JS, which destructures CoOpChart into bare function names.
CHART_MODULE_JS = (Path(__file__).resolve().parent / "coop_chart.js").read_text()
PAGE_HTML = """<!DOCTYPE html>
<html lang="en">
<head>
@@ -537,7 +544,17 @@ PAGE_HTML = """<!DOCTYPE html>
.model-sub { color: var(--muted); font-size: 12px; }
.model-spend { font-size: 13px; font-weight: 600; color: var(--ink); text-align: right; }
/* Shared chart module tooltip (same block as the admin panel's, so the
hover boxes read identically on both UIs). */
.chart-tip { position: fixed; display: none; z-index: 60; pointer-events: none; background: #fff; border: 1px solid var(--border, #e4e0d8); border-radius: 8px; box-shadow: 0 2px 10px rgba(45,51,39,0.16); padding: 7px 10px; font-size: 12px; max-width: 280px; }
.chart-tip .tip-day { color: var(--muted); font-size: 11px; margin-bottom: 3px; }
.chart-tip .tip-row { display: flex; justify-content: space-between; gap: 14px; }
.chart-tip .tip-row span { color: var(--muted); }
.chart-tip .tip-row b { color: var(--ink); font-variant-numeric: tabular-nums; }
.mine-chart { margin-top: 18px; }
.mine-chart .coop-trend-body { margin-top: 10px; }
/* Usage mode switch */
.usage-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 14px; }
.usage-header h2 { margin-bottom: 0; }
.mode-switch { display: inline-flex; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
@@ -772,6 +789,22 @@ PAGE_HTML = """<!DOCTYPE html>
<button class="cancel-keep" onclick="hideCancelGuest()">Keep it</button>
</span>
</div>
<div class="mine-chart" id="mine-chart" style="display:none;">
<div class="coop-trend-controls">
<span class="trend-group">
<span class="board-note" style="margin:0;">Show</span>
<button class="mode-btn active" id="mm-spend" onclick="setMineMetric('spend')">Spend</button>
<button class="mode-btn" id="mm-requests" onclick="setMineMetric('requests')">Requests</button>
</span>
<span class="trend-group">
<span class="board-note" style="margin:0;">Period</span>
<button class="mode-btn" id="md-30" onclick="setMineDays(30)">30 days</button>
<button class="mode-btn active" id="md-90" onclick="setMineDays(90)">90 days</button>
<button class="mode-btn" id="md-all" onclick="setMineDays(0)">All time</button>
</span>
</div>
<div id="mine-chart-body" class="coop-trend-body"></div>
</div>
<div class="models" id="models"></div>
</div>
@@ -881,6 +914,7 @@ PAGE_HTML = """<!DOCTYPE html>
</footer>
<script>
/*@@CHART_MODULE@@*/
const $ = (id) => document.getElementById(id);
function flash(msg, ok) {
@@ -1169,6 +1203,8 @@ async function load() {
$('alltime').textContent = fmtMoney(d.all_time_spend ?? 0);
$('calls').textContent = calls.toLocaleString();
mineData = d.daily || [];
renderMineChart();
renderModels(d.models || []);
renderBoard(d.coop_models || []);
renderKeys(d.keys || [], d.key_spend || []);
@@ -1287,11 +1323,11 @@ let trendMetric = "members"; // members | requests | spend
let trendDays = 90; // 0 = all time
const TREND_CONF = {
members: { kind: "line", title: "The co-op over time" },
requests: { kind: "bar", title: "Requests the co-op served" },
spend: { kind: "bar", title: "What the co-op spent (members + the co-op's own accounts)" },
energy: { kind: "bar", title: "Energy the co-op used" },
co2e: { kind: "bar", title: "Carbon the co-op emitted" }
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 }
};
async function loadMetrics() {
@@ -1350,18 +1386,18 @@ function trendVal(row) {
return row.requests;
}
// Y-axis step: counts are people and things, so ticks stay whole numbers;
// money uses the 1/2/5 x 10^k rule so ticks read $10.00, not $4.92.
function niceStep(raw) {
if (trendMetric === "spend" || trendMetric === "energy" || trendMetric === "co2e") {
const mag = Math.pow(10, Math.floor(Math.log10(Math.max(raw, 1e-9))));
const norm = raw / mag;
const nice = norm <= 1 ? 1 : (norm <= 2 ? 2 : (norm <= 5 ? 5 : 10));
return nice * mag;
}
const p = Math.pow(10, Math.floor(Math.log10(Math.max(raw, 1))));
return Math.max(1, Math.ceil(raw / (p / 2)) * (p / 2));
}
// ---- Shared chart module ----
// Chart rendering + the exact-value hover tooltips come from the shared
// CoOpChart module (canonical: ops-docs scripts/shared/coop_chart.js,
// byte-identical copy shipped in this image and spliced in above). The full
// contract (stamp data-tip-host/i, then registerChartTips with the EXACT
// values; NULL renders as a gap, never a zero) is documented in the module
// header.
const {
registerChartTips, hideChartTip, showChartTip, moveChartTip, chartTipTarget,
chartTipData, niceStep, measuredRuns, chartFrame, dateMarks, drawBars,
drawLineRuns, hoverTargets
} = CoOpChart;
function trendLabel(v) {
if (v === null || v === undefined) return "not measured";
@@ -1374,73 +1410,120 @@ function trendLabel(v) {
function renderTrends() {
const host = $("trend-body");
if (!host || !trendsData) 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>";
return;
}
const maxV = Math.max.apply(null, have);
const step = niceStep((maxV <= 0 ? 1 : maxV * 1.08) / 4);
const top = step * 4;
const W = 1000, H = 250, padL = 62, padR = 14, padT = 14, padB = 30;
const plotW = W - padL - padR, plotH = H - padT - padB;
const baseY = padT + plotH;
const n = vals.length;
const xAt = i => padL + (n <= 1 ? plotW / 2 : (plotW * i) / (n - 1));
const yAt = v => baseY - (plotH * v) / top;
const parts = [];
parts.push('<svg viewBox="0 0 ' + W + ' ' + H + '" role="img" aria-label="' + conf.title + '">');
for (let g = 0; g <= 4; g++) {
const yy = baseY - (plotH * g) / 4;
parts.push('<line x1="' + padL + '" y1="' + yy + '" x2="' + (W - padR) + '" y2="' + yy + '" stroke="var(--border, #e4e0d8)"/>');
parts.push('<text x="' + (padL - 8) + '" y="' + (yy + 4) + '" text-anchor="end" font-size="11" fill="var(--muted)">' + trendLabel(step * g) + '</text>');
}
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") {
const bw = Math.max(1, plotW / n - 1);
for (let i = 0; i < n; i++) {
const v = vals[i];
if (v === null || v === undefined) continue;
const yy = yAt(v);
parts.push('<rect x="' + (xAt(i) - bw / 2) + '" y="' + yy + '" width="' + bw + '" height="' + Math.max(0.6, baseY - yy) + '" fill="var(--green-mid)"><title>' + rows[i].day + ": " + trendLabel(v) + "</title></rect>");
}
drawBars(fr, vals, { color: "var(--green-mid)", host: "trend-body" });
} else {
// Contiguous measured runs: a day we never recorded stays a gap.
const runs = [];
let run = [];
for (let i = 0; i < n; i++) {
if (vals[i] === null || vals[i] === undefined) { if (run.length) runs.push(run); run = []; }
else run.push(i);
}
if (run.length) runs.push(run);
for (let s = 0; s < runs.length; s++) {
const r0 = runs[s];
parts.push('<path d="M' + xAt(r0[0]) + "," + baseY + " L" + r0.map(i => xAt(i) + "," + yAt(vals[i])).join(" L") + " L" + xAt(r0[r0.length - 1]) + "," + baseY + ' Z" fill="var(--green-deep)" fill-opacity="0.10"/>');
parts.push('<polyline points="' + r0.map(i => xAt(i) + "," + yAt(vals[i])).join(" ") + '" fill="none" stroke="var(--green-deep)" stroke-width="2" stroke-linejoin="round"/>');
}
for (let i = 0; i < n; i++) {
if (vals[i] === null || vals[i] === undefined) continue;
parts.push('<circle cx="' + xAt(i) + '" cy="' + yAt(vals[i]) + '" r="7" fill="transparent"><title>' + rows[i].day + ": " + trendLabel(vals[i]) + "</title></circle>");
}
// 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 marks = n > 2 ? [0, Math.floor((n - 1) / 2), n - 1] : [0, n - 1];
for (let mi = 0; mi < marks.length; mi++) {
const i = marks[mi];
const anchor = mi === 0 ? "start" : (mi === marks.length - 1 ? "end" : "middle");
parts.push('<text x="' + xAt(i) + '" y="' + (H - 9) + '" text-anchor="' + anchor + '" font-size="11" fill="var(--muted)">' + String(rows[i].day).slice(5) + '</text>');
}
parts.push("</svg>");
host.innerHTML = parts.join("");
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
host.innerHTML = fr.parts.join("");
}
let usageMode = 'mine'; // 'mine' | 'coop'
// ---- My usage over time (chart) ----
// Per-day spend/requests for the signed-in member, from /api/usage's `daily`
// series (the portal builds it from the same spend logs the co-op charts read;
// interior zero days are explicit, so spacing is true). Fetched once at the
// widest range with the usage payload; the toggles re-render client-side.
let mineData = null; // [{day, spend, requests}]
let mineMetric = "spend"; // spend | requests
let mineDays = 90; // 0 = all time
const MINE_CONF = {
spend: { title: "What you used per day", cont: true, val: r => r.spend },
requests: { title: "Requests you made per day", cont: false, val: r => r.requests }
};
function mineLabel(v) {
if (v === null || v === undefined) return "not measured";
if (mineMetric === "spend") return fmtMoney(v);
return Number(v).toLocaleString();
}
function setMineMetric(m) {
mineMetric = m;
$("mm-spend").className = "mode-btn" + (m === "spend" ? " active" : "");
$("mm-requests").className = "mode-btn" + (m === "requests" ? " active" : "");
renderMineChart();
}
function setMineDays(d) {
mineDays = d;
$("md-30").className = "mode-btn" + (d === 30 ? " active" : "");
$("md-90").className = "mode-btn" + (d === 90 ? " active" : "");
$("md-all").className = "mode-btn" + (d === 0 ? " active" : "");
renderMineChart();
}
function renderMineChart() {
const block = $("mine-chart");
if (!block) return;
const all = mineData || [];
// No usage rows at all: no chart yet (the empty state would be noise).
if (!all.length) { block.style.display = "none"; return; }
block.style.display = "";
const rows = mineDays === 0 ? all : all.slice(-mineDays);
block.style.display = "";
const host = $("mine-chart-body");
const conf = MINE_CONF[mineMetric];
const vals = rows.map(conf.val);
// Exact-value hover tooltips, same contract as every other chart here.
registerChartTips("mine-chart-body", rows.map((row, i) => ({
label: row.day,
series: [[conf.title, mineLabel(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>";
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: mineLabel,
aria: conf.title,
gridStroke: "var(--border, #e4e0d8)"
});
drawBars(fr, vals, { color: "var(--green-mid)", host: "mine-chart-body" });
dateMarks(fr, rows.map(r => r.day));
fr.parts.push("</svg>");
host.innerHTML = fr.parts.join("");
}
let usageMode = 'mine'; // 'mine' | 'coop'
function setUsageMode(mode) {
usageMode = mode;
@@ -1579,6 +1662,12 @@ load();
</body>
</html>"""
# Splice the shared chart module into the page's single <script> block. The
# placeholder is a JS comment, so the extracted-and-checked block stays valid
# even before the splice (check-page-js.sh performs the same splice when it
# runs the harnesses).
PAGE_HTML = PAGE_HTML.replace("/*@@CHART_MODULE@@*/", CHART_MODULE_JS)
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):