Files
Homelab-manager/web/src/pages/Inventory.tsx
T
bobbanandClaude Sonnet 5.5 18ceed62e8 Racks, notes and to-do, OS support, suggested dependencies, Nginx Proxy Manager and Home Assistant
- Racks page and a network diagram (UniFi tree with servers, printable)
- Notes on servers and devices; To do list shown in Coming up and My work
- Agents report the operating system (Linux 7, Windows 6); end-of-life badge and alert
- Suggested dependencies from where a service is reached
- Nginx Proxy Manager integration: proxy hosts page, certificate and host alerts, suggested checks
- Home Assistant integration: watch chosen entities, history chart, limit and unavailable alerts
- TimeChart gets a "value" scale that fits negatives; docs updated

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-20 21:47:56 +02:00

666 lines
31 KiB
TypeScript

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 <div className={`small ${cls}`}>{days < 0 ? `support ended ${until}` : days === 0 ? "support ends today" : `support ends ${until}`}</div>;
}
function WarrantyBadge({ until }: { until: string | null }) {
const state = warrantyState(until);
const days = warrantyDays(until);
if (state === "none" || days === null) return <span className="text-secondary">—</span>;
if (state === "expired") return <span className="badge bg-red-lt text-red" title={until ?? undefined}>ended {Math.abs(days)} d ago</span>;
if (state === "expiring") return <span className="badge bg-yellow-lt text-yellow" title={until ?? undefined}>ends in {days} d</span>;
return <span className="text-secondary">until {until}</span>;
}
/**
* 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<Asset[] | null>(null);
const [config, setConfig] = useState<InventoryConfig>({ currency: "", pricePerKwh: null });
const [servers, setServers] = useState<{ id: number; name: string }[]>([]);
const [error, setError] = useState<string | null>(null);
const [draft, setDraft] = useState<Draft | null>(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<Set<number>>(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 = <K extends keyof Draft>(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 (
<>
<div className="d-flex align-items-center mb-3">
<h2 className="page-title mb-0">Inventory</h2>
<div className="ms-auto d-flex gap-2">
<Link to="/inventory/racks" className="btn">
Racks
</Link>
<Link to="/inventory/lifecycle" className="btn">
Lifecycle
</Link>
<Link to="/inventory/labels" className="btn">
Print labels
</Link>
{canEdit && !draft && (
<button className="btn btn-primary" onClick={() => setDraft({ ...EMPTY })}>
Add hardware
</button>
)}
</div>
</div>
<ErrorNotice error={error} />
{focused && (
<div className="card mb-3 border-primary">
<div className="card-header">
<h3 className="card-title">{focused.name}</h3>
<div className="card-actions btn-list">
{canEdit && (
<button className="btn btn-sm btn-primary" onClick={() => setDraft(toDraft(focused))}>
Edit
</button>
)}
<button className="btn btn-sm" onClick={() => setParams((p) => { const n = new URLSearchParams(p); n.delete("asset"); return n; }, { replace: true })}>
Close
</button>
</div>
</div>
<div className="card-body">
<dl className="row mb-0">
{([
["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]) => (
<div className="col-md-6 d-flex" key={label}>
<dt className="col-5 text-secondary fw-normal">{label}</dt>
<dd className="col-7">{value ?? "—"}</dd>
</div>
))}
{focused.server && (
<div className="col-md-6 d-flex">
<dt className="col-5 text-secondary fw-normal">Is the server</dt>
<dd className="col-7">
<Link to={`/servers/${focused.server.id}`}>{focused.server.name}</Link>
</dd>
</div>
)}
</dl>
</div>
</div>
)}
{focusId !== null && assets !== null && !focused && <div className="alert alert-warning">That piece of hardware isn't in the inventory any more.</div>}
<div className="row row-cards mb-3">
{cards.map((c) => (
<div className="col-6 col-lg-3" key={c.label}>
<div className="card card-sm">
<div className="card-body">
<div className={`h2 mb-0 ${c.color}`}>{c.value}</div>
<div className="text-secondary">{c.label}</div>
{c.note && <div className="text-secondary small">{c.note}</div>}
</div>
</div>
</div>
))}
</div>
{draft && (
<form id="inventory-form" className="card mb-3" onSubmit={save}>
<div className="card-header">
<h3 className="card-title">{draft.id === null ? "Add hardware" : `Edit ${draft.name || "hardware"}`}</h3>
</div>
<div className="card-body row g-3">
<div className="col-md-5">
<label className="form-label" htmlFor="inv-name">
Name
</label>
<input id="inv-name" className="form-control" required maxLength={120} value={draft.name} onChange={(e) => set("name", e.target.value)} />
</div>
<div className="col-md-3">
<label className="form-label" htmlFor="inv-kind">
Kind
</label>
<select id="inv-kind" className="form-select" value={draft.kind} onChange={(e) => set("kind", e.target.value as AssetKind)}>
{KINDS.map((k) => (
<option key={k} value={k}>
{KIND_LABELS[k]} — {KIND_HINTS[k]}
</option>
))}
</select>
</div>
<div className="col-md-4">
<label className="form-label" htmlFor="inv-server">
Is the server
</label>
<select id="inv-server" className="form-select" value={draft.serverId} onChange={(e) => set("serverId", e.target.value)}>
<option value="">— not a server here —</option>
{servers.map((s) => (
<option key={s.id} value={s.id}>
{s.name}
</option>
))}
</select>
{draft.serverId === "" && suggestion && (
<div className="form-hint small mt-1">
Looks like <strong>{suggestion.name}</strong>.{" "}
<button type="button" className="btn btn-link btn-sm p-0 align-baseline" onClick={() => set("serverId", String(suggestion.id))}>
Link it
</button>
</div>
)}
{draft.serverId !== "" && <div className="form-hint text-secondary small mt-1">Blank maker, model and serial number are filled in from the server's agent when you save.</div>}
</div>
<div className="col-md-4">
<label className="form-label" htmlFor="inv-maker">
Manufacturer
</label>
<input id="inv-maker" className="form-control" maxLength={100} value={draft.manufacturer} onChange={(e) => set("manufacturer", e.target.value)} />
</div>
<div className="col-md-4">
<label className="form-label" htmlFor="inv-model">
Model
</label>
<input id="inv-model" className="form-control" maxLength={100} value={draft.model} onChange={(e) => set("model", e.target.value)} />
</div>
<div className="col-md-4">
<label className="form-label" htmlFor="inv-serial">
Serial number
</label>
<input id="inv-serial" className="form-control" maxLength={100} value={draft.serial} onChange={(e) => set("serial", e.target.value)} />
</div>
<div className="col-md-3">
<label className="form-label" htmlFor="inv-bought">
Bought
</label>
<input id="inv-bought" type="date" className="form-control" value={draft.purchaseDate} onChange={(e) => set("purchaseDate", e.target.value)} />
</div>
<div className="col-md-3">
<label className="form-label" htmlFor="inv-price">
Price {config.currency && <span className="text-secondary">({config.currency})</span>}
</label>
<input id="inv-price" type="number" min={0} step="any" className="form-control" value={draft.purchasePrice} onChange={(e) => set("purchasePrice", e.target.value)} />
</div>
<div className="col-md-3">
<label className="form-label" htmlFor="inv-warranty">
Warranty until
</label>
<input id="inv-warranty" type="date" className="form-control" value={draft.warrantyUntil} onChange={(e) => set("warrantyUntil", e.target.value)} />
</div>
<div className="col-md-3">
<label className="form-label" htmlFor="inv-eos">
End of support
</label>
<input id="inv-eos" type="date" className="form-control" value={draft.endOfSupport} onChange={(e) => set("endOfSupport", e.target.value)} />
<div className="form-hint text-secondary small mt-1">When the maker stops patching it, or you plan to retire it.</div>
</div>
<div className="col-md-3">
<label className="form-label" htmlFor="inv-repl">
Replacement cost {config.currency && <span className="text-secondary">({config.currency})</span>}
</label>
<input id="inv-repl" type="number" min={0} step="any" className="form-control" value={draft.replacementCost} onChange={(e) => set("replacementCost", e.target.value)} />
<div className="form-hint text-secondary small mt-1">What replacing it should cost. Left empty, the purchase price stands in.</div>
</div>
<div className="col-md-3">
<label className="form-label" htmlFor="inv-power">
Typical power draw
</label>
<div className="input-group">
<input id="inv-power" type="number" min={0} max={100000} step={1} className="form-control" value={draft.powerWatts} onChange={(e) => set("powerWatts", e.target.value)} />
<span className="input-group-text">W</span>
</div>
</div>
<div className="col-md-5">
<label className="form-label" htmlFor="inv-location">
Where it is
</label>
<input id="inv-location" className="form-control" maxLength={120} placeholder="e.g. Rack in the cellar" value={draft.location} onChange={(e) => set("location", e.target.value)} />
</div>
<div className="col-md-2">
<label className="form-label" htmlFor="inv-unit">
Rack unit
</label>
<input id="inv-unit" className="form-control" maxLength={30} placeholder="U12" value={draft.rackUnit} onChange={(e) => set("rackUnit", e.target.value)} />
</div>
<div className="col-md-5">
<label className="form-label" htmlFor="inv-notes">
Notes
</label>
<input id="inv-notes" className="form-control" maxLength={2000} value={draft.notes} onChange={(e) => set("notes", e.target.value)} />
</div>
</div>
<div className="card-footer d-flex gap-2">
<button type="submit" className="btn btn-primary" disabled={busy || draft.name.trim() === ""}>
{busy ? "Saving…" : "Save"}
</button>
<button type="button" className="btn" onClick={() => setDraft(null)}>
Cancel
</button>
</div>
</form>
)}
<div className="card mb-3">
<TableToolbar
search={tableSearch.query}
onSearch={tableSearch.setQuery}
placeholder="Search hardware…"
filters={
<>
{canEdit && shownIds.length > 0 && (
<label className="form-check mb-0">
<input
type="checkbox"
className="form-check-input"
checked={allShownPicked}
onChange={(e) =>
setPicked((prev) => {
const next = new Set(prev);
for (const id of shownIds) {
if (e.target.checked) next.add(id);
else next.delete(id);
}
return next;
})
}
/>
<span className="form-check-label">Pick all {shownIds.length} shown</span>
</label>
)}
<select
className="form-select form-select-sm w-auto"
aria-label="Show hardware of kind"
value={kind}
onChange={(e) =>
setParams(
(prev) => {
const next = new URLSearchParams(prev);
if (e.target.value) next.set("kind", e.target.value);
else next.delete("kind");
return next;
},
{ replace: true },
)
}
>
<option value="">Every kind</option>
{KINDS.map((k) => (
<option key={k} value={k}>
{KIND_LABELS[k]}
</option>
))}
</select>
</>
}
shown={sorted?.length}
total={all.length}
onExport={exportCsv}
exportDisabled={!sorted || sorted.length === 0}
/>
<div className="table-responsive">
<table className="table table-vcenter card-table table-stack">
<thead>
<tr>
<SortableTh<Asset> label="Name" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Asset> label="Kind" sortKeyName="kind" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Asset> label="Where" sortKeyName="location" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Asset> label="Bought" sortKeyName="purchaseDate" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Asset> label="Warranty" sortKeyName="warrantyUntil" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Asset> label="Power" sortKeyName="powerWatts" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
{canEdit && <th className="w-1">Actions</th>}
</tr>
</thead>
<tbody>
{assets === null && !error && (
<tr>
<td colSpan={canEdit ? 7 : 6}>
<BlockSkeleton lines={3} />
</td>
</tr>
)}
{page.pageItems?.map((a) => (
<tr key={a.id}>
<td className="stack-wide">
{canEdit && <input type="checkbox" className="form-check-input me-2 align-middle" aria-label={`Pick ${a.name}`} checked={picked.has(a.id)} onChange={() => togglePicked(a.id)} />}
{a.name}
{(a.manufacturer || a.model) && <div className="text-secondary small">{[a.manufacturer, a.model].filter(Boolean).join(" ")}</div>}
{a.server && (
<div className="small">
is <Link to={`/servers/${a.server.id}`}>{a.server.name}</Link>
</div>
)}
{canEdit && a.agent && Object.keys(a.agent.differs).length > 0 && (
<div className="small text-secondary">
The agent says {Object.entries(a.agent.differs).map(([k, v]) => `${k === "manufacturer" ? "maker" : k === "serial" ? "serial number" : k} ${v}`).join(", ")}.{" "}
<button type="button" className="btn btn-link btn-sm p-0 align-baseline" onClick={() => void refreshFromAgent(a)}>
Refresh from agent
</button>
</div>
)}
</td>
<td>{KIND_LABELS[a.kind]}</td>
<td className="stack-label" data-label="Where">
{a.location ?? "—"}
{a.rackUnit && <span className="text-secondary"> · {a.rackUnit}</span>}
</td>
<td className="text-secondary stack-label" data-label="Bought">
{a.purchaseDate ?? "—"}
{a.purchasePrice !== null && <div className="small">{money(a.purchasePrice, config.currency)}</div>}
</td>
<td className="stack-label" data-label="Warranty">
<WarrantyBadge until={a.warrantyUntil} />
{a.endOfSupport && <SupportLine until={a.endOfSupport} />}
</td>
<td className="stack-label" data-label="Power">{a.powerWatts === null ? <span className="text-secondary">—</span> : `${a.powerWatts} W`}</td>
{canEdit && (
<td className="stack-wide">
<div className="btn-list flex-nowrap">
<button className="btn btn-sm btn-outline-secondary" onClick={() => setDraft(toDraft(a))}>
Edit
</button>
<button className="btn btn-sm btn-outline-danger" onClick={() => void remove(a)}>
Remove
</button>
</div>
</td>
)}
</tr>
))}
{assets !== null && sorted?.length === 0 && (
<EmptyRow colSpan={canEdit ? 7 : 6} {...(tableSearch.active || kind ? { filtered: () => { 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 })} />
)}
</tbody>
</table>
</div>
<Pagination page={page.page} pageCount={page.pageCount} totalCount={page.totalCount} onPageChange={page.setPage} />
</div>
{canEdit && pickedIds.length > 0 && (
<>
<div className="has-bulk-bar" />
<BulkBar count={pickedIds.length} noun={pickedIds.length === 1 ? "piece" : "pieces"} onClear={() => setPicked(new Set())}>
<button type="button" className="btn btn-sm btn-primary" onClick={() => setBulkOpen(true)}>
Change where / dates…
</button>
<Link to={`/inventory/labels?only=${pickedIds.join(",")}`} className="btn btn-sm">
Print labels
</Link>
</BulkBar>
</>
)}
{bulkOpen && <HardwareBulkDrawer count={pickedIds.length} onSubmit={bulkChange} onClose={() => setBulkOpen(false)} />}
{isAdmin && (
<form className="card" onSubmit={saveConfig}>
<div className="card-header">
<h3 className="card-title">Price of power</h3>
</div>
<div className="card-body row g-3 align-items-end">
<div className="col-md-3">
<label className="form-label" htmlFor="inv-kwh">
Price per kWh
</label>
<input id="inv-kwh" type="number" min={0} step="any" className="form-control" value={priceText} onChange={(e) => setPriceText(e.target.value)} />
</div>
<div className="col-md-2">
<label className="form-label" htmlFor="inv-cur">
Currency
</label>
<input id="inv-cur" className="form-control" maxLength={8} placeholder="SEK" value={currencyText} onChange={(e) => setCurrencyText(e.target.value)} />
</div>
<div className="col-md-7 text-secondary small">
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.
</div>
</div>
<div className="card-footer">
<button type="submit" className="btn btn-primary">
Save
</button>
</div>
</form>
)}
</>
);
}