Files
Homelab-manager/server/test/inventoryLifecycle.test.ts
T
bobbanandClaude Sonnet 5.5 846af02851 Lifecycle planning, and consistent empty and loading states
- Inventory: end of support and replacement cost per asset; a Lifecycle page showing what ages out year by year and what replacing it will cost; support ending within 90 days in the weekly digest
- Lists: a shared empty state saying what is missing, why, and the one thing to do; "nothing matches" with a clear button; skeleton rows instead of empty-looking lists while loading

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-18 23:18:42 +02:00

146 lines
7.5 KiB
TypeScript

/**
* Lifecycle planning: what ages out when, what replacing it is expected to cost, the route, and the weekly digest's word about support ending.
*
* 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-lifecycle-"));
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 } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const { inventoryRouter } = await import("../src/routes/inventory.js");
const { lifecycleReport } = await import("../src/services/inventory.js");
const { buildDigest } = await import("../src/services/weeklyDigest.js");
const { updateSettings } = await import("../src/services/settingsStore.js");
await runMigrations();
const NOW = new Date("2026-10-18T12:00:00Z");
const asset = (id: number, name: string, extra: Partial<{ endOfSupport: string | null; warrantyUntil: string | null; replacementCost: number | null; purchasePrice: number | null }> = {}) => ({
id, name, kind: "server", endOfSupport: null, warrantyUntil: null, replacementCost: null, purchasePrice: null, ...extra,
});
describe("what ages out when", () => {
const report = lifecycleReport(
[
asset(1, "NAS", { endOfSupport: "2026-12-31", replacementCost: 6000, purchasePrice: 5200 }),
asset(2, "Switch", { warrantyUntil: "2027-03-01", purchasePrice: 300 }),
asset(3, "Old router", { endOfSupport: "2025-01-01", purchasePrice: 100 }),
asset(4, "Shelf"),
asset(5, "New UPS", { endOfSupport: "2035-06-01", replacementCost: 900 }),
asset(6, "Mini PC", { endOfSupport: "2027-06-01" }),
asset(7, "Today's", { endOfSupport: "2026-10-18", replacementCost: 10 }),
asset(8, "Garbage date", { endOfSupport: "2027-02-30" }),
],
NOW,
3,
);
test("each thing goes where its date puts it: already past, one of the next years, later, or no date", () => {
assert.deepEqual(report.past.map((i) => i.name), ["Old router"]);
assert.deepEqual(report.years.map((y) => [y.year, y.items.map((i) => i.name)]), [[2026, ["Today's", "NAS"]], [2027, ["Switch", "Mini PC"]], [2028, []]]);
assert.deepEqual(report.later.map((i) => i.name), ["New UPS"]);
assert.deepEqual(report.undated.map((u) => u.name), ["Garbage date", "Shelf"], "an impossible date is no date");
});
test("the date is the end of support, or the warranty's end when none is set, and the report says which", () => {
const nas = report.years[0].items.find((i) => i.name === "NAS")!;
const sw = report.years[1].items.find((i) => i.name === "Switch")!;
assert.deepEqual([nas.basis, nas.endsOn], ["support", "2026-12-31"]);
assert.deepEqual([sw.basis, sw.endsOn], ["warranty", "2027-03-01"]);
assert.equal(report.years[0].items.find((i) => i.name === "Today's")!.daysLeft, 0, "today is not yet past");
});
test("the cost is the replacement cost, or what it was bought for, and a year's total says how many have no figure", () => {
const [y2026, y2027] = report.years;
assert.deepEqual(y2026.items.map((i) => [i.name, i.cost, i.costBasis]), [["Today's", 10, "replacement"], ["NAS", 6000, "replacement"]], "6000 and not the 5200 it was bought for");
assert.equal(y2026.totalCost, 6010);
assert.deepEqual(y2027.items.map((i) => [i.name, i.cost, i.costBasis]), [["Switch", 300, "purchase"], ["Mini PC", null, null]]);
assert.deepEqual([y2027.totalCost, y2027.unpriced], [300, 1], "the total is at least this much");
});
});
describe("through the route and the digest", () => {
let app: Server;
let base = "";
let who = "operator";
before(async () => {
await db.insert(users).values([
{ oidcSub: "operator", name: "Olga", role: "operator" },
{ oidcSub: "viewer", name: "Vic", role: "viewer" },
]);
await db.insert(servers).values({ name: "elsa", apiTokenHash: "e", apiTokenPrefix: "e", lastSeenAt: new Date().toISOString() });
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/inventory", inventoryRouter);
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/inventory`;
});
after(() => {
app.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" }, body: body === undefined ? undefined : JSON.stringify(body) });
const inDays = (n: number) => new Date(Date.now() + n * 86_400_000).toISOString().slice(0, 10);
test("an end of support and a replacement cost are kept; a wrong one is refused", async () => {
const res = await send("POST", "/", { name: "Synology DS920+", kind: "storage", endOfSupport: inDays(45), replacementCost: 6500, purchasePrice: 5200 });
assert.equal(res.status, 201);
const row = (await res.json()).asset;
assert.equal(row.endOfSupport, inDays(45));
assert.equal(row.replacementCost, 6500);
assert.equal((await send("POST", "/", { name: "x", kind: "other", endOfSupport: "next year" })).status, 400);
assert.equal((await send("POST", "/", { name: "x", kind: "other", replacementCost: -5 })).status, 400);
const blank = (await (await send("POST", "/", { name: "Blank", kind: "other", endOfSupport: null, replacementCost: null })).json()).asset;
assert.deepEqual([blank.endOfSupport, blank.replacementCost], [null, null]);
});
test("the report is for everyone signed in, with the currency, and the number of years can be asked for", async () => {
await updateSettings({ inventory: { currency: "SEK" } });
who = "viewer";
const res = await send("GET", "/lifecycle?years=2");
assert.equal(res.status, 200);
const body = await res.json();
assert.equal(body.currency, "SEK");
assert.equal(body.years.length, 2);
assert.equal(body.undated.some((u: { name: string }) => u.name === "Blank"), true);
assert.equal((await (await send("GET", "/lifecycle?years=nonsense")).json()).years.length, 5, "five by default");
assert.equal((await (await send("GET", "/lifecycle?years=99")).json()).years.length, 5, "and never absurd");
const all = [...body.past, ...body.years.flatMap((y: { items: unknown[] }) => y.items), ...body.later] as { name: string; basis: string; cost: number }[];
const nas = all.find((i) => i.name === "Synology DS920+")!;
assert.deepEqual([nas.basis, nas.cost], ["support", 6500]);
who = "operator";
});
test("support about to end is in the weekly digest, with its date", async () => {
const digest = await buildDigest(new Date());
assert.match(digest.message, /EXPIRING\n- Support for Synology DS920\+ ends in (44|45|46) days \(\d{4}-\d{2}-\d{2}\)/);
});
});