- Runbooks: notes per server/integration, shown next to matching alerts - Backup coverage page across Proxmox and PBS, with a digest section - Hardware inventory with warranty, power and running cost - Authentik group to role mapping with preview and safeguards - /metrics (bearer token) and signed outgoing event webhooks - Docs: README, DATABASE, NOTIFICATIONS, ROLES and new API.md Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
184 lines
8.4 KiB
TypeScript
184 lines
8.4 KiB
TypeScript
/**
|
|
* The hardware inventory: warranty and running-cost arithmetic, and the routes.
|
|
*
|
|
* 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-inventory-"));
|
|
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, auditLog } = await import("../src/db/schema.js");
|
|
const { runMigrations } = await import("../src/db/migrate.js");
|
|
const { inventoryRouter } = await import("../src/routes/inventory.js");
|
|
const { isRealDate, warrantyDaysLeft, warrantyStatus, yearlyKwh, yearlyCost } = await import("../src/services/inventory.js");
|
|
const { buildDigest } = await import("../src/services/weeklyDigest.js");
|
|
const { getSettings } = await import("../src/services/settingsStore.js");
|
|
const { eq } = await import("drizzle-orm");
|
|
|
|
await runMigrations();
|
|
|
|
const NOW = new Date("2026-10-17T12:30:00Z");
|
|
|
|
describe("dates and warranties", () => {
|
|
test("only real calendar dates", () => {
|
|
assert.equal(isRealDate("2026-10-17"), true);
|
|
assert.equal(isRealDate("2024-02-29"), true);
|
|
for (const bad of ["2026-02-30", "2026-13-01", "17/10/2026", "2026-1-5", "", "yesterday"]) assert.equal(isRealDate(bad), false, bad);
|
|
});
|
|
|
|
test("days left count whole days from today, and go negative once it has ended", () => {
|
|
assert.equal(warrantyDaysLeft("2026-10-17", NOW), 0, "ends today: still covered");
|
|
assert.equal(warrantyDaysLeft("2026-10-27", NOW), 10);
|
|
assert.equal(warrantyDaysLeft("2026-10-10", NOW), -7);
|
|
assert.equal(warrantyDaysLeft(null, NOW), null);
|
|
assert.equal(warrantyDaysLeft("garbage", NOW), null);
|
|
});
|
|
|
|
test("status: none, ok, expiring within 90 days, expired", () => {
|
|
assert.equal(warrantyStatus(null, NOW), "none");
|
|
assert.equal(warrantyStatus("2028-01-01", NOW), "ok");
|
|
assert.equal(warrantyStatus("2027-01-10", NOW), "expiring", "86 days");
|
|
assert.equal(warrantyStatus("2027-01-20", NOW), "ok", "95 days");
|
|
assert.equal(warrantyStatus("2026-10-17", NOW), "expiring");
|
|
assert.equal(warrantyStatus("2026-10-16", NOW), "expired");
|
|
});
|
|
});
|
|
|
|
describe("running cost", () => {
|
|
test("a steady draw over a year, at a price per kWh", () => {
|
|
assert.equal(yearlyKwh(100), 876);
|
|
assert.equal(yearlyCost(100, 2), 1752);
|
|
assert.equal(yearlyCost(45, 1.5), Math.round(0.045 * 8760 * 1.5));
|
|
});
|
|
test("no draw or no price is no cost, not zero", () => {
|
|
assert.equal(yearlyCost(null, 2), null);
|
|
assert.equal(yearlyCost(0, 2), null);
|
|
assert.equal(yearlyCost(100, null), null);
|
|
assert.equal(yearlyCost(100, 0), null);
|
|
});
|
|
});
|
|
|
|
describe("the inventory routes", () => {
|
|
let app: Server;
|
|
let base = "";
|
|
let who = "operator";
|
|
let elsa = 0;
|
|
|
|
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" },
|
|
]);
|
|
elsa = (await db.insert(servers).values({ name: "elsa", apiTokenHash: "a", apiTokenPrefix: "a" }).returning())[0].id;
|
|
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) });
|
|
|
|
let nasId = 0;
|
|
|
|
test("an operator adds hardware, and blanks mean no value", async () => {
|
|
const res = await send("POST", "/", { name: "Synology DS920+", kind: "storage", manufacturer: "Synology", model: "DS920+", serial: " ", purchaseDate: "2024-03-01", purchasePrice: 5200, warrantyUntil: "2027-03-01", location: "Rack, U12", rackUnit: "U12", powerWatts: 45, notes: "" });
|
|
assert.equal(res.status, 201);
|
|
const row = (await res.json()).asset;
|
|
nasId = row.id;
|
|
assert.equal(row.serial, null);
|
|
assert.equal(row.notes, null);
|
|
assert.equal(row.powerWatts, 45);
|
|
assert.equal((await send("POST", "/", { name: "elsa's box", kind: "server", serverId: elsa, powerWatts: 120, warrantyUntil: new Date(Date.now() + 20 * 86_400_000).toISOString().slice(0, 10) })).status, 201);
|
|
});
|
|
|
|
test("everyone signed in can read the list, with the linked server's name and the price of power", async () => {
|
|
who = "viewer";
|
|
const body = await (await send("GET", "/")).json();
|
|
assert.equal(body.assets.length, 2);
|
|
const box = body.assets.find((a: { name: string }) => a.name === "elsa's box");
|
|
assert.deepEqual(box.server, { id: elsa, name: "elsa" });
|
|
assert.equal(body.assets.find((a: { name: string }) => a.name.startsWith("Synology")).server, null);
|
|
assert.deepEqual(body.config, { currency: "", pricePerKwh: null });
|
|
assert.deepEqual(body.servers, [{ id: elsa, name: "elsa" }]);
|
|
who = "operator";
|
|
});
|
|
|
|
test("only operators change it, and only an administrator sets the price of power", async () => {
|
|
who = "viewer";
|
|
assert.equal((await send("POST", "/", { name: "x", kind: "other" })).status, 403);
|
|
assert.equal((await send("PUT", `/${nasId}`, { name: "x", kind: "other" })).status, 403);
|
|
assert.equal((await send("DELETE", `/${nasId}`)).status, 403);
|
|
who = "operator";
|
|
assert.equal((await send("PUT", "/config", { currency: "SEK", pricePerKwh: 1.8 })).status, 403);
|
|
who = "admin";
|
|
const ok = await send("PUT", "/config", { currency: "SEK", pricePerKwh: 1.8 });
|
|
assert.equal(ok.status, 200);
|
|
assert.deepEqual((await getSettings()).inventory, { currency: "SEK", pricePerKwh: 1.8 });
|
|
assert.equal((await send("PUT", "/config", { currency: "SEK", pricePerKwh: -1 })).status, 400);
|
|
who = "operator";
|
|
});
|
|
|
|
test("a bad entry is refused: no name, made-up kind, impossible date, negative price, unknown server", async () => {
|
|
for (const bad of [
|
|
{ name: "", kind: "other" },
|
|
{ name: "x", kind: "toaster" },
|
|
{ name: "x", kind: "other", purchaseDate: "2026-02-30" },
|
|
{ name: "x", kind: "other", warrantyUntil: "next year" },
|
|
{ name: "x", kind: "other", purchasePrice: -5 },
|
|
{ name: "x", kind: "other", powerWatts: 1.5 },
|
|
{ name: "x", kind: "other", serverId: 99999 },
|
|
]) {
|
|
assert.equal((await send("POST", "/", bad)).status, 400, JSON.stringify(bad));
|
|
}
|
|
});
|
|
|
|
test("editing and removing work, and are in the audit log", async () => {
|
|
const put = await send("PUT", `/${nasId}`, { name: "Synology DS920+ (hall)", kind: "storage", powerWatts: 50 });
|
|
assert.equal(put.status, 200);
|
|
const row = (await put.json()).asset;
|
|
assert.equal(row.name, "Synology DS920+ (hall)");
|
|
assert.equal(row.manufacturer, null, "a field left out is cleared, not kept: this replaces the entry");
|
|
assert.equal((await send("PUT", "/99999", { name: "x", kind: "other" })).status, 404);
|
|
assert.equal((await send("DELETE", `/${nasId}`)).status, 204);
|
|
assert.equal((await send("DELETE", `/${nasId}`)).status, 404);
|
|
const actions = (await db.select().from(auditLog)).filter((e) => e.category === "inventory").map((e) => e.action);
|
|
for (const a of ["create", "update", "delete", "update_config"]) assert.ok(actions.includes(a), a);
|
|
});
|
|
|
|
test("a warranty about to end is in the weekly digest, with a date", async () => {
|
|
await db.update(servers).set({ lastSeenAt: new Date().toISOString() }).where(eq(servers.id, elsa));
|
|
const digest = await buildDigest(new Date());
|
|
assert.match(digest.message, /EXPIRING\n- Warranty on elsa's box ends in (19|20|21) days \(\d{4}-\d{2}-\d{2}\)/);
|
|
});
|
|
});
|