- Speedtest Tracker integration: charts, alerts for a slow line (median of the last three tests under a share of what is paid for) and for failing tests. - Costs page (Records): things paid for by hand plus Hetzner's estimate, totals per currency, bills rolled forward into Coming up as Renewals. - Status pages: a "Having trouble" state for things that answer but have an open alert; Speedtest reads as the internet. - Integrations page and kind picker grouped like the sidebar (one shared types file); Notifications "What to send" shown one group at a time; Dashboard integration sections follow the menu groups, with tiles for integrations that have no widget. - Docs, tests, and ROLES.md menu table brought up to date. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
190 lines
12 KiB
TypeScript
190 lines
12 KiB
TypeScript
/**
|
|
* Costs: the next day a bill falls (rolled forward from the day given), the monthly and yearly figures per currency (never converted), what is read from Hetzner, the routes
|
|
* (everyone signed in sees, an administrator changes) and how a bill's day reaches "Coming up".
|
|
*
|
|
* Run with: npm test --workspace server
|
|
*/
|
|
import { test, describe, before, after } from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { mkdtempSync, rmSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import type { AddressInfo } from "node:net";
|
|
import type { Server } from "node:http";
|
|
|
|
const dir = mkdtempSync(join(tmpdir(), "hm-costs-"));
|
|
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, integrations, auditLog } = await import("../src/db/schema.js");
|
|
const { runMigrations } = await import("../src/db/migrate.js");
|
|
const costs = await import("../src/services/costs.js");
|
|
const hz = await import("../src/services/hetznerSync.js");
|
|
const { costsRouter } = await import("../src/routes/costs.js");
|
|
const { agendaFromData, loadAgendaData, AGENDA_KINDS, buildIcs } = await import("../src/services/agenda.js");
|
|
const { eq } = await import("drizzle-orm");
|
|
|
|
await runMigrations();
|
|
|
|
describe("the next day a bill falls", () => {
|
|
const next = costs.nextRenewal;
|
|
test("a day still ahead is that day; a day gone by is rolled forward by the period", () => {
|
|
assert.equal(next("2026-12-24", "month", "2026-10-26"), "2026-12-24", "the first bill has not come yet");
|
|
assert.equal(next("2026-01-15", "month", "2026-10-26"), "2026-11-15");
|
|
assert.equal(next("2026-01-15", "month", "2026-10-15"), "2026-10-15", "today counts");
|
|
assert.equal(next("2026-01-15", "month", "2026-10-10"), "2026-10-15");
|
|
assert.equal(next("2024-03-20", "year", "2026-10-26"), "2027-03-20");
|
|
assert.equal(next("2024-11-20", "year", "2026-10-26"), "2026-11-20");
|
|
});
|
|
test("December rolls into the next year, and a day a month does not have falls on its last day", () => {
|
|
assert.equal(next("2026-01-05", "month", "2026-12-20"), "2027-01-05");
|
|
assert.equal(next("2026-01-31", "month", "2026-02-10"), "2026-02-28");
|
|
assert.equal(next("2026-01-31", "month", "2026-04-10"), "2026-04-30");
|
|
assert.equal(next("2024-02-29", "year", "2026-03-01"), "2027-02-28");
|
|
assert.equal(next("2024-02-29", "year", "2027-01-01"), "2027-02-28");
|
|
});
|
|
test("no day, or a day that is not one, is no renewal", () => {
|
|
assert.equal(next(null, "month", "2026-10-26"), null);
|
|
assert.equal(next("2026-13-40", "month", "2026-10-26"), null);
|
|
assert.equal(next("soon", "year", "2026-10-26"), null);
|
|
});
|
|
});
|
|
|
|
describe("the totals", () => {
|
|
const item = (amount: number, currency: string, period: string, category: string) => ({ amount, currency, period, category });
|
|
test("a yearly cost is a twelfth of it each month; each currency is its own total, never converted; categories add up, largest first", () => {
|
|
const t = costs.costTotals([item(12, "EUR", "year", "Domains"), item(5, "EUR", "month", "Subscriptions"), item(100, "SEK", "month", "Subscriptions"), item(24, "EUR", "year", "Domains")], []);
|
|
assert.deepEqual(t.map((x) => [x.currency, x.monthly, x.yearly, x.items]), [["SEK", 100, 1200, 1], ["EUR", 8, 96, 3]]);
|
|
assert.deepEqual(t.find((x) => x.currency === "EUR")!.categories, [{ category: "Subscriptions", monthly: 5 }, { category: "Domains", monthly: 3 }]);
|
|
});
|
|
test("an estimate that was read is added to its currency under Hosting", () => {
|
|
const t = costs.costTotals([item(5, "EUR", "month", "Subscriptions")], [{ currency: "EUR", monthly: 19.53 }]);
|
|
assert.deepEqual([t[0].monthly, t[0].yearly, t[0].items], [24.53, 294.36, 2]);
|
|
assert.deepEqual(t[0].categories, [{ category: "Hosting", monthly: 19.53 }, { category: "Subscriptions", monthly: 5 }]);
|
|
assert.deepEqual(costs.costTotals([], []), []);
|
|
});
|
|
});
|
|
|
|
describe("through the routes", () => {
|
|
let app: Server;
|
|
let base = "";
|
|
let who = "admin";
|
|
const call = async (method: string, path: string, body?: unknown) => {
|
|
const res = await fetch(`${base}${path}`, { method, headers: { "content-type": "application/json", connection: "close" }, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
return { status: res.status, body: (await res.json().catch(() => null)) as any };
|
|
};
|
|
before(async () => {
|
|
await db.insert(users).values([
|
|
{ oidcSub: "admin", name: "Ada", role: "admin" },
|
|
{ oidcSub: "operator", name: "Olga", role: "operator" },
|
|
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
|
|
]);
|
|
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/costs", costsRouter);
|
|
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/costs`;
|
|
});
|
|
after(() => {
|
|
app.close();
|
|
try {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
} catch {
|
|
// Windows keeps the database file locked until the process exits.
|
|
}
|
|
});
|
|
|
|
test("an administrator adds, changes and removes an item, each in the audit log; the currency is made capitals and a bad body is refused with a sentence", async () => {
|
|
const created = await call("POST", "", { name: " tooweb.se ", amount: 12, currency: "eur", period: "year", category: "Domains", renewsOn: "2026-03-20", note: "at the registrar" });
|
|
assert.equal(created.status, 201);
|
|
const id = created.body.id as number;
|
|
let list = await call("GET", "");
|
|
const item = list.body.items.find((i: { id: number }) => i.id === id);
|
|
assert.deepEqual([item.name, item.currency, item.period, item.monthly, item.renewsOn, item.note], ["tooweb.se", "EUR", "year", 1, "2026-03-20", "at the registrar"]);
|
|
assert.match(item.nextRenewal, /^\d{4}-03-20$/, "worked out from the day given");
|
|
assert.ok(item.nextRenewal >= new Date().toISOString().slice(0, 10));
|
|
assert.equal((await call("PUT", `/${id}`, { name: "tooweb.se", amount: 15, currency: "EUR", period: "year", category: "Domains" })).status, 200);
|
|
list = await call("GET", "");
|
|
assert.deepEqual([list.body.items.find((i: { id: number }) => i.id === id).amount, list.body.items.find((i: { id: number }) => i.id === id).renewsOn], [15, null]);
|
|
for (const bad of [{ name: "", amount: 1, currency: "EUR", period: "month" }, { name: "x", amount: 0, currency: "EUR", period: "month" }, { name: "x", amount: -4, currency: "EUR", period: "month" }, { name: "x", amount: 1, currency: "EURO", period: "month" }, { name: "x", amount: 1, currency: "EUR", period: "week" }, { name: "x", amount: 1, currency: "EUR", period: "month", renewsOn: "2026-02-31" }]) {
|
|
const r = await call("POST", "", bad);
|
|
assert.equal(r.status, 400, JSON.stringify(bad));
|
|
assert.match(r.body.message, /three-letter currency/);
|
|
}
|
|
assert.equal((await call("DELETE", `/${id}`)).status, 204);
|
|
assert.equal((await call("DELETE", `/${id}`)).status, 404);
|
|
assert.equal((await call("PUT", "/99999", { name: "x", amount: 1, currency: "EUR", period: "month" })).status, 404);
|
|
const actions = (await db.select().from(auditLog).where(eq(auditLog.category, "cost"))).map((e) => e.action);
|
|
assert.deepEqual(actions, ["create", "update", "delete"]);
|
|
});
|
|
|
|
test("anyone signed in sees the costs; an operator and a viewer cannot change them", async () => {
|
|
await call("POST", "", { name: "VPN", amount: 5, currency: "EUR", period: "month", category: "Subscriptions" });
|
|
for (const sub of ["operator", "viewer"]) {
|
|
who = sub;
|
|
assert.equal((await call("GET", "")).status, 200);
|
|
assert.equal((await call("POST", "", { name: "x", amount: 1, currency: "EUR", period: "month" })).status, 403);
|
|
assert.equal((await call("PUT", "/1", { name: "x", amount: 1, currency: "EUR", period: "month" })).status, 403);
|
|
assert.equal((await call("DELETE", "/1")).status, 403);
|
|
}
|
|
who = "admin";
|
|
});
|
|
|
|
test("a Hetzner project's estimate is in the totals under Hosting, saying it is an estimate, and is marked when it was not read lately", async () => {
|
|
const id = (await db.insert(integrations).values({ type: "hetzner", name: "Prod", baseUrl: "https://api.hetzner.cloud", config: "{}" }).returning({ id: integrations.id }))[0].id;
|
|
const server = { id: 1, name: "web", status: "running", created: null, type: "cx22", cores: 2, memoryGb: 4, diskGb: 40, location: "fsn1", city: null, os: null, ipv4: null, ipv6: null, privateIps: [], locked: false, rescueEnabled: false, backupWindow: null, includedTraffic: null, outgoingTraffic: null, ingoingTraffic: null, monthlyPrice: 10 };
|
|
await hz.storeRead(id, { servers: [server], volumes: [], images: [], primaryIps: [], prices: { currency: "EUR", imagePerGb: 0.01, volumePerGb: 0.05, backupPercent: 20, primaryIps: [] } }, new Date());
|
|
let report = await call("GET", "");
|
|
assert.deepEqual(report.body.automatic.map((a: { name: string; source: string; monthly: number; stale: boolean }) => [a.name, a.source, a.monthly, a.stale]), [["Prod", "Hetzner Cloud", 10, false]]);
|
|
assert.match(report.body.automatic[0].detail, /an estimate at list prices, including VAT/);
|
|
const eur = report.body.totals.find((t: { currency: string }) => t.currency === "EUR");
|
|
assert.equal(eur.categories.find((c: { category: string }) => c.category === "Hosting").monthly, 10);
|
|
const old = await costs.automaticCosts(Date.now() + 3_600_000);
|
|
assert.equal(old[0].stale, true);
|
|
await db.delete(integrations).where(eq(integrations.id, id));
|
|
report = await call("GET", "");
|
|
assert.deepEqual(report.body.automatic, []);
|
|
});
|
|
});
|
|
|
|
describe("a bill's day in Coming up", () => {
|
|
const NOW = new Date("2026-10-26T12:00:00Z");
|
|
const empty = { secrets: [], domains: [], endpoints: [], tailscale: [], assets: [], windows: [], schedules: [], patchPlans: [], restoreTests: [], restoreLimitDays: 0, updates: [], todos: [], notes: [] };
|
|
|
|
test("it is a kind of its own, and the bill is on the coming day with what it costs and a link to Costs", () => {
|
|
assert.ok((AGENDA_KINDS as readonly string[]).includes("renewal"));
|
|
const a = agendaFromData({ ...empty, renewals: [{ id: 3, name: "tooweb.se domain", amount: 12, currency: "EUR", period: "year", nextRenewal: "2026-11-20" }, { id: 4, name: "VPN", amount: 5.5, currency: "EUR", period: "month", nextRenewal: "2026-11-02" }] }, NOW, "UTC", 90);
|
|
assert.deepEqual(a.items.map((i) => [i.kind, i.at, i.title, i.link]), [["renewal", "2026-11-02", "VPN is billed — 5.50 EUR a month", "/costs"], ["renewal", "2026-11-20", "tooweb.se domain is billed — 12 EUR a year", "/costs"]]);
|
|
});
|
|
|
|
test("one beyond the horizon is not listed; data with no renewals at all (older callers) still works", () => {
|
|
const far = agendaFromData({ ...empty, renewals: [{ id: 3, name: "X", amount: 1, currency: "EUR", period: "year", nextRenewal: "2027-09-01" }] }, NOW, "UTC", 90);
|
|
assert.deepEqual(far.items, []);
|
|
assert.deepEqual(agendaFromData(empty, NOW, "UTC", 90).items, []);
|
|
});
|
|
|
|
test("read from what is stored, a monthly bill whose day has gone by comes up on its next day; the feed with no names says only that a bill is due", async () => {
|
|
await db.insert((await import("../src/db/schema.js")).costItems).values({ name: "Plex pass", amount: 5, currency: "EUR", period: "month", category: "Subscriptions", renewsOn: "2026-01-15", note: null, createdAt: NOW.toISOString(), updatedAt: NOW.toISOString() });
|
|
const data = await loadAgendaData(NOW);
|
|
const r = data.renewals!.find((x) => x.name === "Plex pass")!;
|
|
assert.equal(r.nextRenewal, "2026-11-15");
|
|
const agenda = agendaFromData(data, NOW, "UTC", 90);
|
|
const item = agenda.items.find((i) => i.kind === "renewal" && /Plex pass/.test(i.title))!;
|
|
assert.ok(item);
|
|
const feed = (detail: "summary" | "names") => buildIcs({ ...agenda, items: agenda.items.filter((i) => i.kind === "renewal") }, { name: "Coming up", detail });
|
|
assert.match(feed("summary"), /SUMMARY:A bill is due/);
|
|
assert.doesNotMatch(feed("summary"), /Plex/);
|
|
assert.match(feed("names"), /SUMMARY:Plex pass is billed/);
|
|
});
|
|
});
|