Files
admin-panel/tests/money-chart-harness.js
inference-admin fba50e3f93
ci/woodpecker/push/woodpecker Pipeline failed
Trends: one chart area for every metric, Money included, drawn by the shared module
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).
2026-11-13 20:55:59 +00:00

156 lines
7.1 KiB
JavaScript

// Money-chart harness: exercises the REAL shared renderer through the panel's
// renderTrends() with the money metric selected, against a realistic fixture
// (spend from 09-04, revenue from 09-06, balance only on the last day — the
// deploy-day shape). Asserts chart invariants, not the shape we happened to see.
//
// WHAT CHANGED AND WHY THIS HARNESS IS DIFFERENT
// Money used to be its own tab with its own renderers (renderMoney,
// renderMoneyCumulative, renderMoneyDaily, renderMoneyLegend) and its own
// period/spend-mode toggles. It is now one metric among the others, defined in
// the shared module (CoOpChart.CHART_METRICS) and drawn by the one shared
// renderer — the same chart the member dashboard draws. So this harness drives
// the metric the way the page does, and asserts the invariants that must hold
// wherever the chart is drawn.
function mkSeries() {
const rows = [];
const start = new Date(Date.UTC(2026, 8, 4)); // 2026-09-04
for (let i = 0; i < 66; i++) {
const d = new Date(start.getTime() + i * 86400000);
const key = d.toISOString().slice(0, 10);
const rev = key >= "2026-09-06" ? 100 + i * 2 : 0; // cumulative climbs
rows.push({
day: key,
revenue_cum: rev,
spend_day: 5 + i,
spend_cum: (5 + i) * (i + 1) / 2,
oc_balance: i === 65 ? 1160.25 : null,
});
}
return rows;
}
function mkMetrics() {
return mkSeries().map((r, i) => ({
day: r.day, members_total: 100 + i, requests: 10 + i,
spend_usd: 1.5 + (i % 7), energy_wh: 40 + i, co2e_g: 12 + i,
operator_spend_usd: 0.5,
}));
}
moneyData = {
caveat: "Balance history begins 2026-11-08: the Open Collective API exposes only the current balance.",
balance_history_start: "2026-11-08",
balance_current: { value: 1160.25, currency: "USD" },
errors: [],
series: mkSeries(),
};
trendsData = mkMetrics();
trendDays = 0;
const count = (re) => (svg.match(re) || []).length;
// --- the metric buttons come from the SHARED list (Money included) ---
buildMetricButtons();
for (const def of CHART_METRICS) {
if (!$("tm-" + def.id)) throw new Error("metric button missing for the shared metric: " + def.id);
}
if (!CHART_METRICS.some(d => d.id === "money")) {
throw new Error("the shared metric list must carry Money — it is one of the charts now");
}
// --- money metric: cumulative lines, exact tooltips, gap-safe balance ---
trendMetric = "money";
renderTrends();
svg = $("trend-body").innerHTML;
const polys = count(/<polyline /g);
const rects = count(/<rect /g);
if (polys !== 2) throw new Error("expected 2 cumulative polylines (revenue+spend; balance is single-point), got " + polys);
if (rects !== 0) throw new Error("cumulative mode must not draw bars, got " + rects);
if (!count(/<circle cx="[^"]+" cy="[^"]+" r="3" fill="#a97a2a"/)) throw new Error("single balance point marker missing");
if (!count(/data-tip-host="trend-body"/)) throw new Error("hover targets missing");
// The legend must be the DEFINITION's series names — not a second hand-written
// list that can drift from the chart it labels.
const legend = $("trend-legend").innerHTML;
const def = metricDef("money");
for (const s of def.series) {
if (!legend.includes(s.name)) throw new Error("legend missing series: " + s.name);
}
if ((legend.match(/class="key"/g) || []).length !== def.series.length) {
throw new Error("legend lists " + (legend.match(/class="key"/g) || []).length
+ " series, the definition has " + def.series.length);
}
// No caveat anywhere, in any rendering state — the panel deliberately has no
// caption under the money chart, even though the fixture carries the caveat.
function assertNoCaveat() {
const rendered = $("trend-body").innerHTML + " " + $("trend-legend").innerHTML;
for (const bad of ["Balance history begins", "history begins", "Open Collective API exposes", "money-caption"]) {
if (rendered.includes(bad)) throw new Error("caveat/caption text rendered: " + bad);
}
}
assertNoCaveat();
// Axis: tick labels bottom-first — values ascend while their y descends; the
// top tick must clear the data max. Date labels share text-anchor="end" with
// the y labels, so filter dash-shaped strings before numeric parsing.
const texts = [...svg.matchAll(/<text x="([^"]+)" y="([^"]+)"[^>]*>([^<]*)<\/text>/g)].map(m => ({ x: m[1], y: m[2], t: m[3] }));
const yTicks = texts.filter(o => !/^\d{2}-\d{2}$/.test(o.t) && o.t.startsWith("$"));
if (yTicks.length !== 5) throw new Error("expected 5 y ticks, got " + yTicks.length + ": " + JSON.stringify(yTicks));
const vals = yTicks.map(o => parseFloat(o.t.replace(/[$,]/g, "")));
for (let k = 1; k < vals.length; k++) {
if (!(vals[k] > vals[k - 1])) throw new Error("tick values not ascending bottom-first: " + vals);
if (!(parseFloat(yTicks[k].y) < parseFloat(yTicks[k - 1].y))) throw new Error("tick positions not descending");
}
if (vals[vals.length - 1] < 1828) throw new Error("top tick " + vals[4] + " does not clear max cumulative 1828");
const xTicks = texts.filter(o => /^\d{2}-\d{2}$/.test(o.t));
if (xTicks.length !== 3) throw new Error("expected 3 date marks, got " + xTicks.length);
// Zero tick must sit lowest.
const ys = yTicks.map(o => parseFloat(o.y));
if (Math.min.apply(null, ys) !== Math.max.apply(null, ys) && ys[0] !== Math.max.apply(null, ys)) throw new Error("zero tick not lowest");
// --- the daily token-spend view is now the shared `spend` metric ---
trendMetric = "spend";
renderTrends();
svg = $("trend-body").innerHTML;
const bars = count(/<rect /g);
if (bars !== 66) throw new Error("spend metric: expected 66 bars, got " + bars);
if (count(/<polyline /g) !== 0) throw new Error("a bar metric must draw no lines");
if ($("trend-legend").innerHTML.includes("OC balance")) throw new Error("the spend metric must not list money series");
// --- period slice: 30 days → 30 bars, no refetch ---
trendDays = 30;
renderTrends();
svg = $("trend-body").innerHTML;
const bars30 = count(/<rect /g);
if (bars30 !== 30) throw new Error("30-day slice: expected 30 bars, got " + bars30);
trendMetric = "money";
renderTrends();
svg = $("trend-body").innerHTML;
const revPoints = (svg.match(/<polyline points="([^"]+)"/) || [])[1];
const nPoints = revPoints ? revPoints.trim().split(/\s+/).length : 0;
if (nPoints !== 30) throw new Error("30-day money slice: expected 30 points, got " + nPoints);
trendDays = 0;
renderTrends();
assertNoCaveat();
// --- a metric this page has no source for says so, instead of drawing another ---
const savedSource = METRIC_SOURCE.energy;
delete METRIC_SOURCE.energy;
trendMetric = "energy";
renderTrends();
if ($("trend-body").innerHTML.indexOf("Not available on this page") === -1) {
throw new Error("a metric with no source must say so, not render something else");
}
METRIC_SOURCE.energy = savedSource;
// --- balance-only deploy-day shape: one point renders as a marker, no crash ---
moneyData.series = [{ day: "2026-11-08", revenue_cum: null, spend_day: null, spend_cum: null, oc_balance: 1160.25 }];
trendMetric = "money";
renderTrends();
const svg2 = $("trend-body").innerHTML;
if (svg2.indexOf("trend-empty") === -1 && svg2.indexOf("<circle") === -1 && svg2.indexOf("<polyline") === -1) {
throw new Error("single-row series rendered nothing");
}