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>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-18 23:18:42 +02:00
1 parent 92726568b7
commit 846af02851
50 files changed
+4434 -233

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
ALTER TABLE `assets` ADD `end_of_support` text;--> statement-breakpoint
ALTER TABLE `assets` ADD `replacement_cost` real;
File diff suppressed because it is too large. Load diff
+7
View File
@@ -281,6 +281,13 @@
"when": 1792356659440,
"tag": "0039_old_blur",
"breakpoints": true
},
{
"idx": 40,
"version": "6",
"when": 1792357895858,
"tag": "0040_petite_invaders",
"breakpoints": true
}
]
}
+2
View File
@@ -820,6 +820,8 @@ export const assets = sqliteTable("assets", {
purchaseDate: text("purchase_date"), // YYYY-MM-DD
purchasePrice: real("purchase_price"), // in the currency set under Settings → Inventory
warrantyUntil: text("warranty_until"), // YYYY-MM-DD
endOfSupport: text("end_of_support"), // YYYY-MM-DD — when the maker stops patching it, or you plan to retire it; what the lifecycle report goes by
replacementCost: real("replacement_cost"), // what replacing it is expected to cost, in the same currency; the lifecycle report falls back to the purchase price
location: text("location"), // room, rack, shelf
rackUnit: text("rack_unit"), // e.g. "U12" or "U12-13"
powerWatts: integer("power_watts"), // typical draw, for the running cost
+13 -1
View File
@@ -5,7 +5,7 @@ import { db } from "../db/client.js";
import { assetKinds, assets, servers } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js";
import { isRealDate } from "../services/inventory.js";
import { isRealDate, lifecycleReport } from "../services/inventory.js";
import { blanksToFill, differences, hardwareOf } from "../services/inventoryAutofill.js";
import { getSettings, updateSettings } from "../services/settingsStore.js";
import { asyncHandler } from "../utils/asyncHandler.js";
@@ -26,6 +26,8 @@ const assetSchema = z.object({
purchaseDate: date,
purchasePrice: z.number().min(0).max(1_000_000_000).nullable().optional(),
warrantyUntil: date,
endOfSupport: date,
replacementCost: z.number().min(0).max(1_000_000_000).nullable().optional(),
location: text(120),
rackUnit: text(30),
powerWatts: z.number().int().min(0).max(100_000).nullable().optional(),
@@ -46,6 +48,8 @@ function values(d: z.infer<typeof assetSchema>) {
purchaseDate: clean(d.purchaseDate),
purchasePrice: d.purchasePrice ?? null,
warrantyUntil: clean(d.warrantyUntil),
endOfSupport: clean(d.endOfSupport),
replacementCost: d.replacementCost ?? null,
location: clean(d.location),
rackUnit: clean(d.rackUnit),
powerWatts: d.powerWatts ?? null,
@@ -83,6 +87,14 @@ inventoryRouter.get("/", asyncHandler(async (_req, res) => {
});
}));
// What ages out when, for planning what to replace: this year, the next few, later, and what has no date.
inventoryRouter.get("/lifecycle", asyncHandler(async (req, res) => {
const asked = Number(req.query.years);
const years = Number.isInteger(asked) && asked >= 1 && asked <= 10 ? asked : 5;
const [rows, settings] = await Promise.all([db.select().from(assets), getSettings()]);
res.json({ ...lifecycleReport(rows, new Date(), years), currency: settings.inventory.currency });
}));
const configSchema = z.object({
currency: z.string().trim().max(8),
pricePerKwh: z.number().min(0).max(1000).nullable(),
+78
View File
@@ -30,6 +30,84 @@ export function warrantyStatus(warrantyUntil: string | null, now: Date = new Dat
return days <= warnDays ? "expiring" : "ok";
}
// ─── Lifecycle planning ─────────────────────────────────────────────────────
export interface LifecycleItem {
id: number;
name: string;
kind: string;
/** YYYY-MM-DD — when it ages out. */
endsOn: string;
/** What that date is: the end of support the maker gives (or you set), or, with none set, the end of the warranty. */
basis: "support" | "warranty";
daysLeft: number;
/** What replacing it is expected to cost, and where that figure comes from; null when there is none. */
cost: number | null;
costBasis: "replacement" | "purchase" | null;
}
export interface LifecycleYear {
year: number;
items: LifecycleItem[];
/** The sum of the figures that exist. */
totalCost: number;
/** How many have no figure, so the total is understood to be at least that. */
unpriced: number;
}
export interface LifecycleReport {
/** Already past their date. */
past: LifecycleItem[];
/** The years from this one on. */
years: LifecycleYear[];
/** Further off than the years shown. */
later: LifecycleItem[];
/** With no date at all: no end of support and no warranty. */
undated: { id: number; name: string; kind: string }[];
}
type LifecycleSource = { id: number; name: string; kind: string; endOfSupport: string | null; warrantyUntil: string | null; replacementCost: number | null; purchasePrice: number | null };
/**
* What ages out when, for planning what to replace. The date is the end of support where there is one, otherwise the end of the warranty (said
* so, since that is only a stand-in); the cost is the replacement cost where there is one, otherwise what it was bought for. Things already past
* their date, those in each of the next `yearsAhead` calendar years, those later, and those with no date at all are kept apart.
*/
export function lifecycleReport(assets: LifecycleSource[], now: Date = new Date(), yearsAhead = 5): LifecycleReport {
const thisYear = now.getUTCFullYear();
const years: LifecycleYear[] = Array.from({ length: yearsAhead }, (_, i) => ({ year: thisYear + i, items: [], totalCost: 0, unpriced: 0 }));
const past: LifecycleItem[] = [];
const later: LifecycleItem[] = [];
const undated: LifecycleReport["undated"] = [];
for (const a of assets) {
const support = a.endOfSupport && isRealDate(a.endOfSupport) ? a.endOfSupport : null;
const warranty = a.warrantyUntil && isRealDate(a.warrantyUntil) ? a.warrantyUntil : null;
const endsOn = support ?? warranty;
if (!endsOn) {
undated.push({ id: a.id, name: a.name, kind: a.kind });
continue;
}
const cost = a.replacementCost ?? a.purchasePrice ?? null;
const item: LifecycleItem = { id: a.id, name: a.name, kind: a.kind, endsOn, basis: support ? "support" : "warranty", daysLeft: warrantyDaysLeft(endsOn, now) ?? 0, cost, costBasis: a.replacementCost !== null ? "replacement" : a.purchasePrice !== null ? "purchase" : null };
if (item.daysLeft < 0) past.push(item);
else {
const bucket = years.find((y) => y.year === Number(endsOn.slice(0, 4)));
if (bucket) bucket.items.push(item);
else later.push(item);
}
}
const byDate = (x: LifecycleItem, y: LifecycleItem) => x.endsOn.localeCompare(y.endsOn) || x.name.localeCompare(y.name);
past.sort(byDate);
later.sort(byDate);
for (const y of years) {
y.items.sort(byDate);
y.totalCost = Math.round(y.items.reduce((n, i) => n + (i.cost ?? 0), 0));
y.unpriced = y.items.filter((i) => i.cost === null).length;
}
undated.sort((a, b) => a.name.localeCompare(b.name));
return { past, years, later, undated };
}
/** Kilowatt-hours a steady draw uses in a year. */
export function yearlyKwh(watts: number): number {
return Math.round((watts / 1000) * 24 * 365 * 100) / 100;
+6 -1
View File
@@ -185,11 +185,16 @@ export async function buildDigest(now: Date = new Date()): Promise<Digest> {
expiring.push({ daysLeft: d.daysLeft, text: d.daysLeft < 0 ? `Domain ${d.name} expired ${plural(Math.abs(d.daysLeft), "day")} ago` : `Domain ${d.name} expires in ${plural(d.daysLeft, "day")} (${d.expiresAt})` });
}
// A warranty about to end is worth knowing while there is still time to claim on it; one that ended long ago is not news.
for (const a of await db.select({ name: assets.name, warrantyUntil: assets.warrantyUntil }).from(assets)) {
for (const a of await db.select({ name: assets.name, warrantyUntil: assets.warrantyUntil, endOfSupport: assets.endOfSupport }).from(assets)) {
const days = warrantyDaysLeft(a.warrantyUntil, now);
if (days !== null && days >= -30 && days <= 60) {
expiring.push({ daysLeft: days, text: days < 0 ? `Warranty on ${a.name} ended ${plural(Math.abs(days), "day")} ago` : `Warranty on ${a.name} ends in ${plural(days, "day")} (${a.warrantyUntil})` });
}
// The end of support gives more notice: it is when something has to be replaced, not claimed on.
const supportDays = warrantyDaysLeft(a.endOfSupport, now);
if (supportDays !== null && supportDays >= -30 && supportDays <= 90) {
expiring.push({ daysLeft: supportDays, text: supportDays < 0 ? `Support for ${a.name} ended ${plural(Math.abs(supportDays), "day")} ago` : `Support for ${a.name} ends in ${plural(supportDays, "day")} (${a.endOfSupport})` });
}
}
if (expiring.length > 0) {
expiring.sort((a, b) => a.daysLeft - b.daysLeft);
+145
View File
@@ -0,0 +1,145 @@
/**
* 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}\)/);
});
});