Service-level targets with error budgets, and quarterly and annual reports

Monitoring -> Service levels: a target (99.9 %) on an endpoint check, a server or an
integration, measured over calendar months. Shows the figure, downtime used, the
error budget left, and how the last six months went. 80 % of the budget used is a
warning and an overspent budget a critical alert. Endpoints are measured day by day,
servers and integrations to the minute from the audit log.

The report page gains Quarter and Year (same figures, with a Service levels section),
and two settings send the quarterly and annual report after the month that ends them.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-21 22:20:07 +02:00
1 parent 31044b2b64
commit 3b31b16796
31 files changed
+7706 -61

No files matched your search

+369
View File
@@ -0,0 +1,369 @@
/**
* Service-level targets: the error budget of a target over a month, how a thing is measured (an endpoint from its daily figures, a server and an integration from the audit
* log, to the minute), how the months before it went, when it is an alert, and the quarterly and annual reports that carry the results.
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { createServer as createHttpServer, type Server } from "node:http";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
const dir = mkdtempSync(join(tmpdir(), "hm-slo-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
process.env.HEALTH_STARTUP_GRACE_MS = "0";
const express = (await import("express")).default;
const { db } = await import("../src/db/client.js");
const { users, servers, integrations, endpointChecks, endpointDaily, auditLog, serviceLevels } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const slo = await import("../src/services/serviceLevels.js");
const uptime = await import("../src/services/uptimeHistory.js");
const report = await import("../src/services/monthlyReport.js");
const { sendMonthlyReport } = await import("../src/services/monthlyReportScheduler.js");
const { evaluateHealth, collectSnapshot } = await import("../src/services/healthMonitor.js");
const { buildMetrics } = await import("../src/services/metrics.js");
const { serviceLevelsRouter } = await import("../src/routes/serviceLevels.js");
const { reportsRouter } = await import("../src/routes/reports.js");
const { setInternalFlag, updateSettings } = await import("../src/services/settingsStore.js");
const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js");
const { eq } = await import("drizzle-orm");
await runMigrations();
const MIN = 60_000;
const DAY = 86_400_000;
/** The 20th of October, noon: 19.5 days into a 31-day month. */
const NOW = new Date("2026-10-20T12:00:00Z");
const OCT_MINUTES = 31 * 1440;
describe("the error budget", () => {
const m = (down: number, percent: number | null = 99): import("../src/services/serviceLevels.js").Measure => ({ percent, downMinutes: down, knownMinutes: 1000 });
test("a target allows the minutes it leaves over, and says how much of that is used", () => {
const ok = slo.judgeBudget(99.9, OCT_MINUTES, 28_080, m(10));
assert.equal(Math.round(ok.allowedMinutes * 100) / 100, 44.64);
assert.deepEqual([ok.state, ok.usedPercent, Math.round(ok.remainingMinutes * 10) / 10], ["ok", 22.4, 34.6]);
assert.equal(slo.judgeBudget(99.9, OCT_MINUTES, 28_080, m(36)).state, "at_risk", "80 % or more used");
assert.equal(slo.judgeBudget(99.9, OCT_MINUTES, 28_080, m(35)).state, "ok", "78 %");
const over = slo.judgeBudget(99.9, OCT_MINUTES, 28_080, m(50));
assert.deepEqual([over.state, over.usedPercent, Math.round(over.remainingMinutes)], ["breached", 112, -5]);
assert.equal(slo.judgeBudget(99.9, OCT_MINUTES, 28_080, m(44)).state, "at_risk", "within the budget, though barely");
});
test("no figure is no data, and a budget of nothing is overspent by any downtime", () => {
assert.equal(slo.judgeBudget(99.9, OCT_MINUTES, 100, m(0, null)).state, "no_data");
assert.equal(slo.judgeBudget(100, OCT_MINUTES, 100, m(1)).state, "breached");
assert.equal(slo.judgeBudget(100, OCT_MINUTES, 100, m(0)).state, "ok");
});
test("the pace so far is projected to the end of the month, but not from the first hours", () => {
assert.equal(slo.judgeBudget(99.9, OCT_MINUTES, 14_400, m(10)).projectedPercent, 69, "10 minutes in 10 days → 31 in the month → 69 % of 44.6");
assert.equal(slo.judgeBudget(99.9, OCT_MINUTES, 600, m(10)).projectedPercent, null, "ten hours into the month says little");
});
test("the words an alert uses", () => {
const m1 = m(36);
const b1 = slo.judgeBudget(99.9, OCT_MINUTES, 28_080, m1);
assert.equal(slo.budgetMessage("Gitea", 99.9, "October 2026", b1, m1), "Gitea: 81% of the error budget for its 99.9% target is used up for October 2026 — down 36 min of 45 min allowed, 9 min left");
const m2 = m(50);
assert.equal(slo.budgetMessage("Gitea", 99.9, "October 2026", slo.judgeBudget(99.9, OCT_MINUTES, 28_080, m2), m2), "Gitea has missed its 99.9% target for October 2026: down 50 min, 45 min allowed");
assert.equal(slo.budgetWords(0.4), "under a minute");
});
});
describe("measuring", () => {
let checkId = 0;
let emptyCheckId = 0;
let serverId = 0;
let integrationId = 0;
before(async () => {
checkId = (await db.insert(endpointChecks).values({ name: "Gitea", kind: "http", target: "https://git.lab/" }).returning({ id: endpointChecks.id }))[0].id;
emptyCheckId = (await db.insert(endpointChecks).values({ name: "Unasked", kind: "http", target: "https://x.lab/" }).returning({ id: endpointChecks.id }))[0].id;
// October: 288 checks a day, ten of them failed on the 5th; the 20th is half done. September: a whole day failed.
const day = (d: string, total: number, ok: number) => db.insert(endpointDaily).values({ checkId, day: d, total, ok, msSum: 0, msCount: 0 });
for (let d = 1; d <= 19; d++) await day(`2026-10-${String(d).padStart(2, "0")}`, 288, d === 5 ? 278 : 288);
await day("2026-10-20", 144, 144);
for (let d = 1; d <= 30; d++) await day(`2026-09-${String(d).padStart(2, "0")}`, 288, d === 10 ? 0 : 288);
serverId = (await db.insert(servers).values({ name: "nas", apiTokenHash: "n", apiTokenPrefix: "n", createdAt: "2026-01-01 00:00:00", lastSeenAt: NOW.toISOString() }).returning({ id: servers.id }))[0].id;
integrationId = (await db.insert(integrations).values({ type: "gitea", name: "Gitea", baseUrl: "", createdAt: "2026-01-01 00:00:00" }).returning({ id: integrations.id }))[0].id;
const audit = (action: string, at: string, extra: Record<string, string>) => db.insert(auditLog).values({ category: "server", action, targetType: "server", createdAt: at, ...extra });
await audit("went_offline", "2026-10-05 10:00:00", { targetId: String(serverId) });
await audit("back_online", "2026-10-05 10:30:00", { targetId: String(serverId) });
// an outage that straddles the start of the month: only the part in October counts
await audit("went_offline", "2026-09-30 23:00:00", { targetId: String(serverId) });
await audit("back_online", "2026-10-01 01:00:00", { targetId: String(serverId) });
await db.insert(auditLog).values([
{ category: "integration", action: "went_failing", targetType: "integration_type", targetId: "gitea", createdAt: "2026-10-12 08:00:00" },
{ category: "integration", action: "recovered", targetType: "integration_type", targetId: "gitea", createdAt: "2026-10-12 08:20:00" },
]);
await setInternalFlag("integration_history_since", "2026-01-01T00:00:00.000Z");
uptime.resetHistoryStartForTests();
});
const oct = { start: new Date("2026-10-01T00:00:00Z"), end: new Date("2026-11-01T00:00:00Z") };
test("an endpoint: the share of checks that failed, over the time that has passed", async () => {
const r = await slo.measure("endpoint", checkId, oct.start, oct.end, slo.newContext(NOW));
assert.deepEqual([r.percent, r.downMinutes, r.knownMinutes], [99.822, 50, 28_080]);
assert.deepEqual(await slo.measure("endpoint", emptyCheckId, oct.start, oct.end, slo.newContext(NOW)), { percent: null, downMinutes: 0, knownMinutes: 0 }, "no checks, no figure");
assert.equal((await slo.measure("endpoint", checkId, new Date("2026-11-01T00:00:00Z"), new Date("2026-12-01T00:00:00Z"), slo.newContext(NOW))).percent, null, "a month that has not begun");
});
test("a server: the minutes the audit log says it was away, only those within the period", async () => {
const r = await slo.measure("server", serverId, oct.start, oct.end, slo.newContext(NOW));
assert.deepEqual([r.downMinutes, r.knownMinutes], [90, 28_080], "30 on the 5th and the 60 of the night that began in September");
assert.equal(r.percent, 99.679);
const sept = await slo.measure("server", serverId, new Date("2026-09-01T00:00:00Z"), oct.start, slo.newContext(NOW));
assert.equal(sept.downMinutes, 60, "and in September, the hour before midnight");
});
test("an integration is measured by the kind of service it is", async () => {
const r = await slo.measure("integration", integrationId, oct.start, oct.end, slo.newContext(NOW));
assert.deepEqual([r.downMinutes, r.percent], [20, 99.929]);
});
test("each stretch of the audit log is read once for everything measured over the same period", async () => {
const ctx = slo.newContext(NOW);
await Promise.all([slo.measure("server", serverId, oct.start, oct.end, ctx), slo.measure("integration", integrationId, oct.start, oct.end, ctx)]);
assert.equal(ctx.uptime.size, 1);
});
test("the exact range is what the whole-day figures are made of", async () => {
const range = await uptime.getUptimeRange(new Date(NOW.getTime() - 3 * DAY), NOW, NOW);
assert.deepEqual(Object.keys(range.servers).map(Number), [serverId]);
assert.deepEqual(await uptime.getUptimeRange(NOW, new Date(NOW.getTime() - MIN), NOW), { servers: {}, integrations: {} }, "an empty range");
const seg = uptime.segmentsOf([{ at: 100 * MIN, down: true }, { at: 130 * MIN, down: false }], 0, 200 * MIN);
assert.deepEqual(uptime.minutesWithin(seg, 90 * MIN, 120 * MIN), { known: 30, down: 20 });
assert.deepEqual(uptime.minutesWithin(seg, 300 * MIN, 400 * MIN), { known: 0, down: 0 });
});
test("this month's budget, with how each of the months before it went", async () => {
await db.insert(serviceLevels).values([
{ name: "Gitea answers", subjectType: "endpoint", subjectId: checkId, target: 99.9 },
{ name: "NAS up", subjectType: "server", subjectId: serverId, target: 99 },
{ name: "Gitea service", subjectType: "integration", subjectId: integrationId, target: 99.9, alert: false },
{ name: "Nobody asks", subjectType: "endpoint", subjectId: emptyCheckId, target: 99.9 },
]);
const all = await slo.levelStatuses(NOW);
const by = Object.fromEntries(all.map((s) => [s.name, s]));
assert.deepEqual([by["Gitea answers"].budget.state, by["Gitea answers"].measure.percent, by["Gitea answers"].subjectName], ["breached", 99.822, "Gitea"]);
assert.deepEqual([by["NAS up"].budget.state, Math.round(by["NAS up"].budget.allowedMinutes)], ["ok", 446], "99 % of 31 days leaves 446 minutes");
assert.equal(by["Nobody asks"].budget.state, "no_data");
assert.deepEqual([by["Gitea answers"].period.id, by["Gitea answers"].period.label, by["Gitea answers"].period.totalMinutes, by["Gitea answers"].period.elapsedMinutes], ["2026-10", "October 2026", OCT_MINUTES, 28_080]);
// the months before: September had a whole failed day; August has no figures
const hist = by["Gitea answers"].history;
assert.deepEqual(hist.map((h) => h.id), ["2026-09", "2026-08", "2026-07", "2026-06", "2026-05", "2026-04"]);
assert.deepEqual([hist[0].percent, hist[0].met, Math.round(hist[0].downMinutes)], [96.667, false, 1440]);
assert.deepEqual([hist[1].percent, hist[1].met], [null, null]);
assert.equal((await slo.levelStatuses(NOW, { history: false }))[0].history.length, 0, "left out when it isn't wanted");
});
test("a target whose thing has been removed has nothing to measure, and says so", async () => {
await db.insert(serviceLevels).values({ name: "Gone", subjectType: "server", subjectId: 99999, target: 99.9 });
const gone = (await slo.levelStatuses(NOW)).find((s) => s.name === "Gone")!;
assert.deepEqual([gone.subjectName, gone.budget.state], [null, "no_data"]);
await db.delete(serviceLevels).where(eq(serviceLevels.name, "Gone"));
});
test("only targets that are to alert, and whose budget is mostly or wholly used, are findings", async () => {
const found = await slo.levelFindings(NOW);
assert.deepEqual(found.map((f) => [f.name, f.state, f.severity]), [["Gitea answers", "breached", "critical"]]);
assert.match(found[0].message, /^Gitea answers has missed its 99.9% target for October 2026: down 50 min, 45 min allowed$/);
assert.equal(slo.levelKey(found[0]), `slo:${found[0].levelId}`);
});
test("how each did over a period, for a report: the missed first", async () => {
const results = await slo.levelResultsFor(oct.start, oct.end, NOW);
assert.deepEqual(results.map((r) => [r.name, r.met]), [["Gitea answers", false], ["Gitea service", true], ["NAS up", true]], "the missed first, then the most used");
assert.ok(results.every((r) => r.name !== "Nobody asks"), "one with no figure is left out");
assert.equal(results[0].allowedMinutes, 44.6);
});
});
describe("quarters and years", () => {
test("which are which, and what can be asked for", () => {
assert.equal(report.periodKind("2026-Q3"), "quarter");
assert.equal(report.periodKind("2026"), "year");
assert.equal(report.periodKind("2026-09"), "month");
for (const ok of ["2026-09", "2026-Q1", "2026"]) assert.equal(report.isPeriodId(ok), true, ok);
for (const bad of ["2026-Q5", "2026-Q0", "26", "2026-13", "Q3", "", undefined, 2026]) assert.equal(report.isPeriodId(bad), false, String(bad));
assert.deepEqual([report.periodLabel("2026-Q3"), report.periodLabel("2026"), report.periodLabel("2026-09")], ["Q3 2026", "2026", "September 2026"]);
assert.equal(report.lastFullQuarter(new Date("2026-10-02T09:00:00Z"), "UTC"), "2026-Q3");
assert.equal(report.lastFullQuarter(new Date("2027-01-02T09:00:00Z"), "UTC"), "2026-Q4", "across the new year");
assert.equal(report.lastFullYear(new Date("2027-01-02T09:00:00Z"), "UTC"), "2026");
const options = report.recentPeriods(new Date("2026-10-19T12:00:00Z"), "UTC");
assert.deepEqual([options.months.length, options.quarters.length, options.years.length], [12, 8, 3]);
assert.deepEqual([options.quarters[0], options.quarters[1], options.quarters[7]], [{ id: "2026-Q4", label: "Q4 2026" }, { id: "2026-Q3", label: "Q3 2026" }, { id: "2025-Q1", label: "Q1 2025" }]);
assert.deepEqual(options.years.map((y) => y.id), ["2026", "2025", "2024"]);
});
test("a quarter and a year begin and end where the clock of the time zone says", () => {
const q3 = report.periodBounds("2026-Q3", "UTC");
assert.deepEqual([q3.start.toISOString(), q3.end.toISOString(), q3.firstDay, q3.nextFirstDay], ["2026-07-01T00:00:00.000Z", "2026-10-01T00:00:00.000Z", "2026-07-01", "2026-10-01"]);
const q4 = report.periodBounds("2026-Q4", "Europe/Stockholm");
assert.deepEqual([q4.start.toISOString(), q4.end.toISOString(), q4.nextFirstDay], ["2026-09-30T22:00:00.000Z", "2026-12-31T23:00:00.000Z", "2027-01-01"], "summer time at the start, winter at the end");
const y = report.periodBounds("2026", "UTC");
assert.deepEqual([y.start.toISOString(), y.end.toISOString(), y.nextFirstDay], ["2026-01-01T00:00:00.000Z", "2027-01-01T00:00:00.000Z", "2027-01-01"]);
assert.equal(report.periodBounds("2026-09", "UTC").nextFirstDay, "2026-10-01", "a month is as it was");
});
test("a quarter's report is the same report over longer, with the targets in it", async () => {
const q = await report.buildMonthlyReport("2026-Q3", NOW);
assert.deepEqual([q.period, q.month, q.label, q.partial, q.from, q.to], ["quarter", "2026-Q3", "Q3 2026", false, "2026-07-01T00:00:00.000Z", "2026-10-01T00:00:00.000Z"]);
assert.deepEqual(q.serviceLevels.map((l) => [l.name, l.met]), [["Gitea answers", false], ["NAS up", true], ["Gitea service", true]], "only September has endpoint figures: a whole failed day");
const text = report.monthlyReportText(q);
assert.equal(text.title, "Homelab quarterly report — Q3 2026");
assert.match(text.message, /SERVICE LEVELS\n2 of 3 targets met\.\n- Gitea answers: 96\.667% against 99\.9% — MISSED \(down 1 d, 2 h 13 min allowed\)/);
const year = await report.buildMonthlyReport("2026", NOW);
assert.deepEqual([year.period, year.label, year.partial], ["year", "2026", true]);
assert.equal(report.monthlyReportText(year).title, "Homelab annual report — 2026 (so far)");
const month = await report.buildMonthlyReport("2026-10", NOW);
assert.equal(month.period, "month");
assert.deepEqual(month.serviceLevels.map((l) => [l.name, l.met]), [["Gitea answers", false], ["Gitea service", true], ["NAS up", true]]);
assert.equal(report.monthlyReportText(month).title, "Homelab monthly report — October 2026 (so far)");
});
});
describe("as alerts, in /metrics, in the routes and as scheduled messages", () => {
let app: Server;
let base = "";
let who = "admin";
let hook: Server;
const messages: string[] = [];
before(async () => {
await db.insert(users).values([
{ oidcSub: "admin", name: "Ada", role: "admin" },
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
]);
hook = createHttpServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (c) => chunks.push(c));
req.on("end", () => {
messages.push(String(JSON.parse(Buffer.concat(chunks).toString()).content));
res.end("{}");
});
});
await new Promise<void>((r) => hook.listen(0, "127.0.0.1", r));
await updateSettings({ webhook: { enabled: true, url: `http://127.0.0.1:${(hook.address() as AddressInfo).port}/` } });
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: who } };
next();
});
a.use("/api/service-levels", serviceLevelsRouter);
a.use("/api/reports", reportsRouter);
app = await new Promise<Server>((resolve) => {
const s = a.listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`;
});
after(() => {
app.close();
hook.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
const send = (method: string, path: string, body?: unknown) => fetch(`${base}${path}`, { method, headers: { "content-type": "application/json", connection: "close" }, body: body === undefined ? undefined : JSON.stringify(body) });
test("a finding is an ordinary health condition", async () => {
const found = await slo.levelFindings(NOW);
const list = evaluateHealth({ servers: [], proxmox: [], synology: [], levels: found }, { serverOfflineMinutes: 60, diskUsagePercent: 90 }, NOW.getTime());
const c = list.find((x) => x.key === `slo:${found[0].levelId}`)!;
assert.deepEqual([c.source, c.severity], ["slo", "critical"]);
const { snapshot } = await collectSnapshot();
assert.ok(Array.isArray(snapshot.levels), "the health pass looks");
});
test("the Alerts page says it, with a link to the page", async () => {
// measured against the real clock: put a target on something that is down now
await db.insert(servers).values({ name: "down-now", apiTokenHash: "d", apiTokenPrefix: "d", createdAt: "2020-01-01 00:00:00", lastSeenAt: new Date().toISOString() });
const [s] = await db.select().from(servers).where(eq(servers.name, "down-now"));
const startOfMonth = new Date(Date.UTC(new Date().getUTCFullYear(), new Date().getUTCMonth(), 1)).toISOString().slice(0, 19).replace("T", " ");
await db.insert(auditLog).values({ category: "server", action: "went_offline", targetType: "server", targetId: String(s.id), createdAt: startOfMonth });
await db.insert(serviceLevels).values({ name: "Always up", subjectType: "server", subjectId: s.id, target: 99.9 });
invalidateAlertsCache();
const found = (await getAlerts(true)).alerts.find((a) => a.message.startsWith("Always up has missed"));
assert.ok(found, "the alert is there");
assert.deepEqual([found.severity, found.category, found.source, found.link], ["critical", "monitoring", "Service level", "/service-levels"]);
});
test("/metrics has each target, how it is doing and what is left", async () => {
const text = await buildMetrics();
assert.match(text, /homelab_service_level_target_percent\{name="Gitea answers"[^}]*\} 99\.9/);
assert.match(text, /homelab_service_level_error_budget_remaining_minutes\{name="Always up"[^}]*\} -\d/);
});
test("anyone signed in can look; only an administrator sets, changes and removes targets, with a reason when it is wrong", async () => {
who = "viewer";
const list = (await (await send("GET", "/service-levels")).json()) as any;
assert.ok(list.levels.length >= 4 && list.subjects.endpoint.length >= 1 && list.subjects.server.length >= 1);
assert.equal((await send("POST", "/service-levels", { name: "x", subjectType: "server", subjectId: 1, target: 99.9 })).status, 403);
who = "admin";
const [e] = list.subjects.endpoint;
const good = { name: "Wiki", subjectType: "endpoint", subjectId: e.id, target: 99.95 };
const res = await send("POST", "/service-levels", good);
assert.equal(res.status, 201);
const id = ((await res.json()) as { id: number }).id;
for (const bad of [{ ...good, target: 89.9 }, { ...good, target: 100 }, { ...good, name: " " }, { ...good, subjectType: "dns" }, { ...good, subjectId: 99999 }]) {
const r = await send("POST", "/service-levels", bad);
assert.equal(r.status, 400, JSON.stringify(bad));
}
assert.match(((await (await send("POST", "/service-levels", { ...good, target: 100 })).json()) as { message: string }).message, /100% leaves no room/);
assert.equal((await send("PUT", `/service-levels/${id}`, { ...good, target: 99.5, name: "Wiki up" })).status, 200);
const [row] = await db.select().from(serviceLevels).where(eq(serviceLevels.id, id));
assert.deepEqual([row.name, row.target], ["Wiki up", 99.5]);
assert.equal((await send("PUT", "/service-levels/99999", good)).status, 404);
const audited = await db.select().from(auditLog).where(eq(auditLog.category, "service_level"));
assert.deepEqual(audited.map((a) => a.action).sort(), ["create", "update"]);
who = "viewer";
assert.equal((await send("DELETE", `/service-levels/${id}`)).status, 403);
who = "admin";
assert.equal((await send("DELETE", `/service-levels/${id}`)).status, 204);
assert.equal((await send("DELETE", `/service-levels/${id}`)).status, 404);
});
test("the report route takes a month, a quarter or a year, and offers all three", async () => {
who = "viewer";
const body = (await (await send("GET", "/reports/monthly?month=2026-Q3")).json()) as any;
assert.deepEqual([body.report.period, body.report.label], ["quarter", "Q3 2026"]);
assert.deepEqual([body.months.length, body.quarters.length, body.years.length], [12, 8, 3]);
assert.equal((await send("GET", `/reports/monthly?month=${new Date().getUTCFullYear()}`)).status, 200);
for (const bad of ["2026-Q9", "1999", "1999-Q1", "abc"]) assert.equal((await send("GET", `/reports/monthly?month=${bad}`)).status, 400, bad);
const text = (await (await send("GET", "/reports/monthly?month=2026-Q3&format=text")).json()) as { title: string };
assert.equal(text.title, "Homelab quarterly report — Q3 2026");
who = "admin";
});
test("a quarter's and a year's report follow the monthly one when they are switched on, and only after the month that closes them", async () => {
const titles = () => messages.map((m) => /Homelab (monthly|quarterly|annual) report — [^*]+/.exec(m)?.[0] ?? "").filter(Boolean);
const base = { enabled: true, day: 1, time: "08:00" };
messages.length = 0;
await updateSettings({ monthlyReport: { ...base, quarterly: false, annual: false } });
await sendMonthlyReport(new Date("2026-10-02T09:00:00Z"));
assert.deepEqual(titles(), ["Homelab monthly report — September 2026"]);
messages.length = 0;
await updateSettings({ monthlyReport: { ...base, quarterly: true, annual: true } });
await sendMonthlyReport(new Date("2026-10-02T09:00:00Z"));
assert.deepEqual(titles(), ["Homelab monthly report — September 2026", "Homelab quarterly report — Q3 2026"], "September closes a quarter, not the year");
messages.length = 0;
await sendMonthlyReport(new Date("2026-11-02T09:00:00Z"));
assert.deepEqual(titles(), ["Homelab monthly report — October 2026"], "October closes nothing");
messages.length = 0;
await sendMonthlyReport(new Date("2027-01-02T09:00:00Z"));
assert.deepEqual(titles(), ["Homelab monthly report — December 2026", "Homelab quarterly report — Q4 2026", "Homelab annual report — 2026"]);
});
});