Files
member-dashboard/dashboard-chart-harness.js
T
inference-admin d10b817fdc dashboard: the co-op charts come from the shared definitions (Money included)
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.
2026-11-13 21:01:38 +00:00

176 lines
8.7 KiB
JavaScript

// Harness for the member dashboard's USAGE CHARTS (my-usage + co-op trend),
// run through the vendored checker:
// bash tests/check-page-js.sh app/main.py dashboard-chart-harness.js
//
// Both charts render through the SHARED module (ops-docs
// scripts/shared/coop_chart.js). Assert the invariants that matter:
// * my-usage chart: bars render from the portal's `daily` series, hidden
// entirely when the member has no usage rows yet; tooltips carry the
// EXACT values through the page's formatters; the 30/90/all toggles
// re-render client-side without refetching;
// * co-op trend: native <title> tooltips are gone (replaced by the shared
// helper), NULL days are stamped with no tooltip (the gap rule);
// * clamping: the tooltip box stays inside the viewport at the edges.
// The checker evals in CommonJS (no top-level await), so the body is wrapped.
const assert = (cond, msg) => { if (!cond) { console.error("FAIL: " + msg); process.exit(1); } };
function mkDaily() {
// 10 days, one with zero usage (a real zero, not an unmeasured gap) and a
// span long enough to exercise the 30/90 slicing.
const rows = [];
for (let i = 0; i < 10; i++) {
rows.push({
day: "2026-11-0" + (i + 1),
spend: i === 4 ? 0 : +(1.25 * (i + 1)).toFixed(2),
requests: i === 4 ? 0 : 10 * (i + 1),
});
}
return rows;
}
(async () => {
// Drive load() with a realistic /api/usage payload.
globalThis.fetch = async () => ({
status: 200,
json: async () => ({
email: "member@example.com", guest: false,
balance: 15, allowance: 15, credits: 0, credits_remaining: 0,
spend: 6.25, all_time_spend: 68.75, remaining: 8.75,
models: [{ model: "greenpt/glm-5.3-flash", spend: 6.25, tokens: 900, calls: 41 }],
key_spend: [], daily: mkDaily(),
coop_models: [],
}),
});
await load();
// ---- my-usage chart ----
{
const block = document.getElementById("mine-chart");
assert(block.style.display === "", "chart block shown when the member has usage rows");
const body = document.getElementById("mine-chart-body").innerHTML;
assert(/<svg /.test(body), "my-usage chart renders an SVG");
assert(!/<title>/.test(body), "native <title> tooltips are gone (shared helper)");
const bars = (body.match(/data-tip-host="mine-chart-body"/g) || []).length;
assert(bars === 10, "one stamped bar per day incl. the zero day (got " + bars + ")");
// EXACT tooltip values: straight from the payload through the page formatters.
const pts = chartTipData["mine-chart-body"];
assert(Array.isArray(pts) && pts.length === 10, "registry: one point per day");
assert(pts[0].label === "2026-11-01", "registry label is the exact day");
assert(pts[0].series[0][1] === "$1.25", "exact spend for 11-01 (got " + pts[0].series[0][1] + ")");
assert(pts[4].series[0][1] === "$0.00", "a zero-usage day reads $0.00, not not-measured");
assert(pts[9].series[0][1] === "$12.50", "exact spend for 11-10 (got " + pts[9].series[0][1] + ")");
// Metric toggle re-renders from the SAME data (no refetch): exact counts.
setMineMetric("requests");
const ptsReq = chartTipData["mine-chart-body"];
assert(ptsReq[0].series[0][1] === "10", "requests tooltip exact (got " + ptsReq[0].series[0][1] + ")");
const bodyReq = document.getElementById("mine-chart-body").innerHTML;
assert((bodyReq.match(/data-tip-host="mine-chart-body"/g) || []).length === 10,
"requests mode still stamps every day");
setMineMetric("spend");
// Period toggles slice client-side: 30 keeps all 10 rows here; verify the
// all-time toggle does not refetch by watching the fetch counter.
let fetches = 0;
globalThis.fetch = async () => { fetches++; return { status: 200, json: async () => ({}) }; };
setMineDays(30);
setMineDays(0);
setMineDays(90);
assert(fetches === 0, "period toggles re-render client-side, never refetch");
assert(document.getElementById("md-all").className.indexOf("active") === -1,
"the 90d button is active again after the round trip");
}
// ---- my-usage chart hidden for a member with no usage ----
{
mineData = [];
renderMineChart();
assert(document.getElementById("mine-chart").style.display === "none",
"no usage rows: the chart block is hidden, not an empty frame");
// restore
mineData = mkDaily();
renderMineChart();
}
// ---- co-op trend (shared module; portal-shaped rows with a NULL day) ----
{
trendsData = [
{ day: "2026-11-01", members_total: 71, spend_usd: 12.34, requests: 2900, energy_wh: 8400.5, co2e_g: 2100.25 },
{ day: "2026-11-02", members_total: 72, spend_usd: null, requests: null, energy_wh: null, co2e_g: null },
{ day: "2026-11-03", members_total: 74, spend_usd: 5.01, requests: 1204, energy_wh: 9100, co2e_g: 2300 },
];
setTrendMetric("spend");
setTrendDays(90);
const body = document.getElementById("trend-body").innerHTML;
assert(!/<title>/.test(body), "co-op trend: native <title> tooltips are gone");
assert((body.match(/data-tip-host="trend-body"/g) || []).length === 2,
"gap day carries no bar/stamp (2 measured days of 3)");
const pts = chartTipData["trend-body"];
assert(pts[1].series[0][1] === "not measured", "NULL day registers as not measured");
assert(pts[0].series[0][1] === "$12.34" && pts[2].series[0][1] === "$5.01",
"co-op trend tooltips carry exact spend");
// Tooltip box behavior through the shared helper.
showChartTip("trend-body", 0, 500, 300);
const box = globalThis.__lastAppended;
assert(box && box.className === "chart-tip", "tooltip box created on first show");
assert(box.innerHTML.indexOf("2026-11-01") !== -1, "tooltip shows the exact date");
assert(box.innerHTML.indexOf("$12.34") !== -1, "tooltip shows the exact value");
moveChartTip(1430, 890);
const x = parseInt(box.style.left, 10), y = parseInt(box.style.top, 10);
assert(x + 120 <= 1440 && y + 48 <= 900, "clamped inside the viewport (got " + x + "," + y + ")");
hideChartTip();
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");
})().catch((e) => { console.error("FAIL: " + (e && e.stack || e)); process.exit(1); });