import { useEffect, useState } from "react"; import { Link } from "react-router-dom"; import { api, type Asset, type AssetInput, type AssetKind, type CurrentUser, type InventoryConfig } from "../api/client"; import SortableTh from "../components/SortableTh"; import TableToolbar from "../components/TableToolbar"; import { ErrorNotice } from "../components/Notice"; import { BlockSkeleton } from "../components/Skeleton"; import { usePagination } from "../hooks/usePagination"; import Pagination from "../components/Pagination"; import { useSortable } from "../hooks/useSortable"; import { useTableSearch } from "../hooks/useTableSearch"; import { useSearchParams } from "react-router-dom"; import { downloadCsv } from "../utils/csv"; import { confirmDialog } from "../utils/dialogs"; import { readableError } from "../utils/errors"; import { KIND_HINTS, KIND_LABELS, money, warrantyDays, warrantyState, yearlyCost, yearlyKwh } from "../utils/inventory"; import { toast } from "../utils/toast"; import { EmptyRow } from "../components/EmptyState"; import BulkBar from "../components/BulkBar"; import { HardwareBulkDrawer } from "../components/BulkDrawers"; import { doBulk, plural } from "../utils/bulk"; const KINDS = Object.keys(KIND_LABELS) as AssetKind[]; interface Draft { id: number | null; name: string; kind: AssetKind; manufacturer: string; model: string; serial: string; purchaseDate: string; purchasePrice: string; warrantyUntil: string; endOfSupport: string; replacementCost: string; location: string; rackUnit: string; powerWatts: string; serverId: string; notes: string; } const EMPTY: Draft = { id: null, name: "", kind: "server", manufacturer: "", model: "", serial: "", purchaseDate: "", purchasePrice: "", warrantyUntil: "", endOfSupport: "", replacementCost: "", location: "", rackUnit: "", powerWatts: "", serverId: "", notes: "" }; function toDraft(a: Asset): Draft { return { id: a.id, name: a.name, kind: a.kind, manufacturer: a.manufacturer ?? "", model: a.model ?? "", serial: a.serial ?? "", purchaseDate: a.purchaseDate ?? "", purchasePrice: a.purchasePrice === null ? "" : String(a.purchasePrice), warrantyUntil: a.warrantyUntil ?? "", endOfSupport: a.endOfSupport ?? "", replacementCost: a.replacementCost === null ? "" : String(a.replacementCost), location: a.location ?? "", rackUnit: a.rackUnit ?? "", powerWatts: a.powerWatts === null ? "" : String(a.powerWatts), serverId: a.serverId === null ? "" : String(a.serverId), notes: a.notes ?? "", }; } function toInput(d: Draft): AssetInput { const num = (s: string) => (s.trim() === "" ? null : Number(s)); return { name: d.name.trim(), kind: d.kind, manufacturer: d.manufacturer, model: d.model, serial: d.serial, purchaseDate: d.purchaseDate || null, purchasePrice: num(d.purchasePrice), warrantyUntil: d.warrantyUntil || null, endOfSupport: d.endOfSupport || null, replacementCost: num(d.replacementCost), location: d.location, rackUnit: d.rackUnit, powerWatts: num(d.powerWatts), serverId: d.serverId === "" ? null : Number(d.serverId), notes: d.notes, }; } /** Under the warranty: when support ends, in words that say how soon. */ function SupportLine({ until }: { until: string }) { const days = warrantyDays(until); if (days === null) return null; const cls = days < 0 ? "text-red" : days <= 180 ? "text-yellow" : "text-secondary"; return
{days < 0 ? `support ended ${until}` : days === 0 ? "support ends today" : `support ends ${until}`}
; } function WarrantyBadge({ until }: { until: string | null }) { const state = warrantyState(until); const days = warrantyDays(until); if (state === "none" || days === null) return —; if (state === "expired") return ended {Math.abs(days)} d ago; if (state === "expiring") return ends in {days} d; return until {until}; } /** * The hardware behind it all: what each machine is, when it was bought, how long it is covered, where it sits and what it draws — * and, with a price of power, roughly what the lot costs to run. Everyone signed in can look; operators keep it up to date. */ export default function Inventory({ user }: { user: CurrentUser }) { const canEdit = user.role === "admin" || user.role === "operator"; const isAdmin = user.role === "admin"; const [assets, setAssets] = useState(null); const [config, setConfig] = useState({ currency: "", pricePerKwh: null }); const [servers, setServers] = useState<{ id: number; name: string }[]>([]); const [error, setError] = useState(null); const [draft, setDraft] = useState(null); const [busy, setBusy] = useState(false); const [priceText, setPriceText] = useState(""); const [currencyText, setCurrencyText] = useState(""); // Hardware ticked for a change in one go, and whether that form is open. const [picked, setPicked] = useState>(new Set()); const [bulkOpen, setBulkOpen] = useState(false); const [params, setParams] = useSearchParams(); const kind = (KINDS as string[]).includes(params.get("kind") ?? "") ? (params.get("kind") as AssetKind) : ""; // A scanned label comes here with ?asset=ID: that one piece of hardware is shown first. const focusId = /^\d+$/.test(params.get("asset") ?? "") ? Number(params.get("asset")) : null; const focused = focusId === null ? null : (assets ?? []).find((a) => a.id === focusId) ?? null; function load() { api.inventory .list() .then((res) => { setAssets(res.assets); setConfig(res.config); setServers(res.servers); setPriceText(res.config.pricePerKwh === null ? "" : String(res.config.pricePerKwh)); setCurrencyText(res.config.currency); }) .catch((err) => setError(readableError(err))); } useEffect(load, []); const ofKind = (assets ?? []).filter((a) => kind === "" || a.kind === kind); const tableSearch = useTableSearch(ofKind); const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "name", "asc", { url: true }); const page = usePagination(sorted); const all = assets ?? []; const covered = all.filter((a) => warrantyState(a.warrantyUntil) === "ok").length; const expiring = all.filter((a) => warrantyState(a.warrantyUntil) === "expiring").length; const expired = all.filter((a) => warrantyState(a.warrantyUntil) === "expired").length; const watts = all.reduce((n, a) => n + (a.powerWatts ?? 0), 0); const cost = yearlyCost(watts, config.pricePerKwh); const spent = all.reduce((n, a) => n + (a.purchasePrice ?? 0), 0); async function save(e: React.FormEvent) { e.preventDefault(); if (!draft) return; setBusy(true); setError(null); try { if (draft.id === null) await api.inventory.create(toInput(draft)); else await api.inventory.update(draft.id, toInput(draft)); toast.success(draft.id === null ? `Added ${draft.name}.` : "Saved."); setDraft(null); load(); } catch (err) { setError(readableError(err)); } finally { setBusy(false); } } const pickedIds = (assets ?? []).filter((a) => picked.has(a.id)).map((a) => a.id); const shownIds = (sorted ?? []).map((a) => a.id); const allShownPicked = shownIds.length > 0 && shownIds.every((id) => picked.has(id)); function togglePicked(id: number) { setPicked((prev) => { const next = new Set(prev); if (next.has(id)) next.delete(id); else next.add(id); return next; }); } async function bulkChange(change: { location?: string | null; warrantyUntil?: string | null; endOfSupport?: string | null }) { const r = await doBulk({ call: api.bulk.inventory, body: { action: "change", ids: pickedIds, ...change }, done: (res) => `${plural(res.changed, "piece")} of hardware changed.`, reload: load }); if (r) { setBulkOpen(false); setPicked(new Set()); } } async function remove(a: Asset) { if (!(await confirmDialog({ title: "Remove from the inventory", message: `Remove "${a.name}"?`, confirmLabel: "Remove", danger: true }))) return; try { await api.inventory.remove(a.id); load(); } catch (err) { setError(readableError(err)); } } async function refreshFromAgent(a: Asset) { const d = a.agent?.differs ?? {}; const lines = (Object.keys(d) as (keyof typeof d)[]).map((k) => `${k}: "${a[k] ?? ""}" becomes "${d[k]}"`); if (!(await confirmDialog({ title: "Take over what the agent says", message: `${a.name}: ${lines.join("; ")}.`, confirmLabel: "Replace" }))) return; try { await api.inventory.refreshFromAgent(a.id); toast.success("Updated from the agent."); load(); } catch (err) { setError(readableError(err)); } } async function saveConfig(e: React.FormEvent) { e.preventDefault(); setError(null); try { const price = priceText.trim() === "" ? null : Number(priceText.replace(",", ".")); const res = await api.inventory.setConfig({ currency: currencyText.trim(), pricePerKwh: price }); setConfig(res.config); toast.success("Saved."); } catch (err) { setError(readableError(err)); } } function exportCsv() { if (!sorted) return; downloadCsv( "inventory.csv", ["Name", "Kind", "Manufacturer", "Model", "Serial", "Location", "Rack unit", "Purchased", "Price", "Warranty until", "End of support", "Replacement cost", "Power (W)", "Server", "Notes"], sorted.map((a) => [a.name, KIND_LABELS[a.kind], a.manufacturer ?? "", a.model ?? "", a.serial ?? "", a.location ?? "", a.rackUnit ?? "", a.purchaseDate ?? "", a.purchasePrice ?? "", a.warrantyUntil ?? "", a.endOfSupport ?? "", a.replacementCost ?? "", a.powerWatts ?? "", a.server?.name ?? "", a.notes ?? ""]), ); } // A name that is a server's name (or holds it) is probably that server. const suggestion = (() => { const n = draft?.name.trim().toLowerCase(); if (!n) return null; return servers.find((s) => s.name.toLowerCase() === n) ?? servers.find((s) => s.name.length >= 3 && n.includes(s.name.toLowerCase())) ?? null; })(); // The form can be a long way down (on a phone, below the cards): bring it into view when it opens. useEffect(() => { if (draft) document.getElementById("inventory-form")?.scrollIntoView({ behavior: "smooth", block: "start" }); // eslint-disable-next-line react-hooks/exhaustive-deps }, [draft === null, draft?.id]); const set = (key: K, value: Draft[K]) => setDraft((d) => (d ? { ...d, [key]: value } : d)); const cards: { label: string; value: string; note?: string; color: string }[] = [ { label: "Hardware", value: assets ? String(all.length) : "…", note: spent > 0 ? `${money(spent, config.currency)} paid` : undefined, color: "" }, { label: "Under warranty", value: assets ? String(covered + expiring) : "…", note: expiring > 0 ? `${expiring} ending within 90 days` : expired > 0 ? `${expired} ended` : undefined, color: expiring > 0 ? "text-yellow" : "text-green" }, { label: "Power draw", value: assets ? `${watts} W` : "…", note: watts > 0 ? `${yearlyKwh(watts).toLocaleString("sv-SE")} kWh a year` : undefined, color: "" }, { label: "Running cost", value: cost !== null ? `${money(cost, config.currency)} / year` : "—", note: cost === null ? (config.pricePerKwh === null ? "set a price of power below" : "add power draws to see it") : undefined, color: "", }, ]; return ( <>

Inventory

Racks Lifecycle Print labels {canEdit && !draft && ( )}
{focused && (

{focused.name}

{canEdit && ( )}
{([ ["Kind", KIND_LABELS[focused.kind]], ["Maker and model", [focused.manufacturer, focused.model].filter(Boolean).join(" ") || null], ["Serial number", focused.serial], ["Where", [focused.location, focused.rackUnit].filter(Boolean).join(" · ") || null], ["Bought", focused.purchaseDate], ["Warranty until", focused.warrantyUntil], ["Power draw", focused.powerWatts === null ? null : `${focused.powerWatts} W`], ["Notes", focused.notes], ] as [string, string | null][]).map(([label, value]) => (
{label}
{value ?? "—"}
))} {focused.server && (
Is the server
{focused.server.name}
)}
)} {focusId !== null && assets !== null && !focused &&
That piece of hardware isn't in the inventory any more.
}
{cards.map((c) => (
{c.value}
{c.label}
{c.note &&
{c.note}
}
))}
{draft && (

{draft.id === null ? "Add hardware" : `Edit ${draft.name || "hardware"}`}

set("name", e.target.value)} />
{draft.serverId === "" && suggestion && (
Looks like {suggestion.name}.{" "}
)} {draft.serverId !== "" &&
Blank maker, model and serial number are filled in from the server's agent when you save.
}
set("manufacturer", e.target.value)} />
set("model", e.target.value)} />
set("serial", e.target.value)} />
set("purchaseDate", e.target.value)} />
set("purchasePrice", e.target.value)} />
set("warrantyUntil", e.target.value)} />
set("endOfSupport", e.target.value)} />
When the maker stops patching it, or you plan to retire it.
set("replacementCost", e.target.value)} />
What replacing it should cost. Left empty, the purchase price stands in.
set("powerWatts", e.target.value)} /> W
set("location", e.target.value)} />
set("rackUnit", e.target.value)} />
set("notes", e.target.value)} />
)}
{canEdit && shownIds.length > 0 && ( )} } shown={sorted?.length} total={all.length} onExport={exportCsv} exportDisabled={!sorted || sorted.length === 0} />
label="Name" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Kind" sortKeyName="kind" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Where" sortKeyName="location" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Bought" sortKeyName="purchaseDate" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Warranty" sortKeyName="warrantyUntil" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Power" sortKeyName="powerWatts" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> {canEdit && } {assets === null && !error && ( )} {page.pageItems?.map((a) => ( {canEdit && ( )} ))} {assets !== null && sorted?.length === 0 && ( { tableSearch.setQuery(""); setParams((p) => { const n = new URLSearchParams(p); n.delete("kind"); return n; }, { replace: true }); } } : { title: "Nothing in the inventory yet", hint: "Keep track of the hardware behind it all: what it is, when it was bought, how long it is covered, where it sits and what it draws.", action: canEdit ? { label: "Add the first piece of hardware", onClick: () => setDraft({ ...EMPTY }) } : undefined })} /> )}
Actions
{canEdit && togglePicked(a.id)} />} {a.name} {(a.manufacturer || a.model) &&
{[a.manufacturer, a.model].filter(Boolean).join(" ")}
} {a.server && (
is {a.server.name}
)} {canEdit && a.agent && Object.keys(a.agent.differs).length > 0 && (
The agent says {Object.entries(a.agent.differs).map(([k, v]) => `${k === "manufacturer" ? "maker" : k === "serial" ? "serial number" : k} ${v}`).join(", ")}.{" "}
)}
{KIND_LABELS[a.kind]} {a.location ?? "—"} {a.rackUnit && · {a.rackUnit}} {a.purchaseDate ?? "—"} {a.purchasePrice !== null &&
{money(a.purchasePrice, config.currency)}
}
{a.endOfSupport && } {a.powerWatts === null ? — : `${a.powerWatts} W`}
{canEdit && pickedIds.length > 0 && ( <>
setPicked(new Set())}> Print labels )} {bulkOpen && setBulkOpen(false)} />} {isAdmin && (

Price of power

setPriceText(e.target.value)} />
setCurrencyText(e.target.value)} />
Used for the running cost above: each machine's typical draw, all day, all year, at this price. It is a rough guide — a machine rarely draws its typical figure all the time.
)} ); }