Add cost history to the Costs page: what it cost each month, and what changed

Each cost item's name, amount, currency, period and kind are kept as versions (cost_item_versions), and Hetzner's estimate is written down once a day (cost_snapshots), so a past month's figure and the changes between can be worked out. History card with monthly bars per currency, month-by-month figures and a list of added, changed and removed items.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-04 23:57:59 +01:00
1 parent b29c0b7d04
commit 9f366c37de
15 files changed
+9716 -3

No files matched your search

+12
View File
@@ -1796,6 +1796,17 @@ export interface CostsReport {
categories: string[];
}
/** What the homelab cost, month by month for each currency, and what changed. */
export interface CostHistory {
/** From the first month there is anything to say about, to this one. */
months: string[];
series: { currency: string; points: { month: string; monthly: number; manual: number; automatic: number }[] }[];
/** Newest first: items added, changed and removed, and a read estimate that moved. */
events: { at: string; kind: "added" | "changed" | "removed" | "estimate"; name: string; amount: number; currency: string; period: string; category: string; from: { name: string; amount: number; currency: string; period: string; category: string } | null }[];
/** When the app began keeping the history; null before the first pass. */
startedAt: string | null;
}
/** One Speedtest Tracker (an integration of type speedtest), as its page shows it. Speeds are bits per second. */
export interface SpeedtestInfo {
id: number;
@@ -3610,6 +3621,7 @@ export const api = {
},
costs: {
get: () => request<CostsReport>("/api/costs"),
history: (months = 12) => request<CostHistory>(`/api/costs/history?months=${months}`),
create: (data: CostInput) => request<{ id: number }>("/api/costs", { method: "POST", body: JSON.stringify(data) }),
update: (id: number, data: CostInput) => request<{ id: number }>(`/api/costs/${id}`, { method: "PUT", body: JSON.stringify(data) }),
remove: (id: number) => request<void>(`/api/costs/${id}`, { method: "DELETE" }),
+133
View File
@@ -0,0 +1,133 @@
import { useEffect, useState } from "react";
import { api, type CostHistory as History } from "../api/client";
import { formatDate } from "../utils/date";
import { readableError } from "../utils/errors";
import { ErrorNotice } from "./Notice";
import { eventText, money } from "../utils/costText";
/** "Oct 25" — in UTC, since a month is a month wherever it is looked at from. */
const monthLabel = (m: string) => new Date(`${m}-01T12:00:00Z`).toLocaleDateString(undefined, { month: "short", year: "2-digit", timeZone: "UTC" });
type Ev = History["events"][number];
const KIND_DOT: Record<Ev["kind"], string> = { added: "text-green", changed: "text-yellow", removed: "text-red", estimate: "text-blue" };
const SHOWN_EVENTS = 15;
/** What the homelab cost, month by month, and what changed: a bar for each month (the items typed in, and the estimates that are read), the figures beneath, and the changes. */
export default function CostHistory({ refreshKey }: { refreshKey: unknown }) {
const [data, setData] = useState<History | null>(null);
const [error, setError] = useState<string | null>(null);
const [currency, setCurrency] = useState<string | null>(null);
const [months, setMonths] = useState(12);
const [allEvents, setAllEvents] = useState(false);
useEffect(() => {
api.costs
.history(months)
.then((h) => {
setData(h);
setError(null);
})
.catch((err) => setError(readableError(err)));
}, [refreshKey, months]);
if (error) return <ErrorNotice error={error} />;
if (!data || data.series.length === 0) return null;
const series = data.series.find((s) => s.currency === currency) ?? data.series[0];
// Months before this currency had anything in them are left out, not shown as nothing.
const firstWith = series.points.findIndex((p) => p.monthly > 0);
const points = firstWith > 0 ? series.points.slice(firstWith) : series.points;
const max = Math.max(...points.map((p) => p.monthly), 0.01);
const events = data.events.filter((e) => e.currency === series.currency || (e.from && e.from.currency === series.currency));
const hasAutomatic = points.some((p) => p.automatic > 0);
return (
<div className="card mt-3">
<div className="card-header flex-wrap gap-2">
<h3 className="card-title me-auto">History</h3>
{data.series.length > 1 && (
<div className="btn-group btn-group-sm" role="group" aria-label="Currency">
{data.series.map((s) => (
<button key={s.currency} type="button" className={`btn ${s.currency === series.currency ? "btn-primary" : ""}`} onClick={() => setCurrency(s.currency)}>
{s.currency}
</button>
))}
</div>
)}
<select className="form-select form-select-sm w-auto" value={months} onChange={(e) => setMonths(Number(e.target.value))} aria-label="How far back">
<option value={6}>6 months</option>
<option value={12}>12 months</option>
<option value={24}>24 months</option>
<option value={36}>36 months</option>
</select>
</div>
<div className="card-body">
<div className="text-secondary small mb-2">
What it cost each month, in {series.currency} — the monthly amount of everything in force at the end of the month (a yearly bill counts a twelfth).
{hasAutomatic && " The darker part is Hetzner’s estimate, read from the servers."}
</div>
<div className="d-flex align-items-end gap-1" style={{ height: 140 }} role="img" aria-label={`Monthly cost in ${series.currency}, ${monthLabel(points[0].month)} to ${monthLabel(points[points.length - 1].month)}`}>
{points.map((p) => (
<div key={p.month} className="flex-fill d-flex flex-column justify-content-end" style={{ minWidth: 0, height: "100%" }} title={`${monthLabel(p.month)}: ${money(p.monthly, series.currency)}${p.automatic > 0 ? ` (${money(p.manual, series.currency)} typed in, ${money(p.automatic, series.currency)} estimated)` : ""}`}>
<div style={{ height: `${(p.automatic / max) * 100}%`, minHeight: p.automatic > 0 ? 2 : 0 }} className="bg-azure" />
<div style={{ height: `${(p.manual / max) * 100}%`, minHeight: p.manual > 0 ? 2 : 0 }} className="bg-blue" />
</div>
))}
</div>
<div className="d-flex gap-1 text-secondary mb-3" style={{ fontSize: 11 }}>
{points.map((p, i) => (
<div key={p.month} className="flex-fill text-center text-truncate" style={{ minWidth: 0 }}>
{points.length <= 12 || i % 2 === (points.length - 1) % 2 ? monthLabel(p.month) : ""}
</div>
))}
</div>
<div className="table-responsive mb-3">
<table className="table table-sm table-vcenter">
<thead>
<tr>
<th>Month</th>
<th className="text-end">A month</th>
<th className="text-end">Change</th>
</tr>
</thead>
<tbody>
{[...points].reverse().map((p, k, list) => {
const before = list[k + 1];
const delta = before ? Math.round((p.monthly - before.monthly) * 100) / 100 : null;
return (
<tr key={p.month}>
<td>{monthLabel(p.month)}{k === 0 ? <span className="text-secondary small"> (so far)</span> : null}</td>
<td className="text-end">{money(p.monthly, series.currency)}</td>
<td className={`text-end ${delta === null || delta === 0 ? "text-secondary" : delta > 0 ? "text-red" : "text-green"}`}>{delta === null || delta === 0 ? "—" : `${delta > 0 ? "+" : "−"}${money(Math.abs(delta), series.currency)}`}</td>
</tr>
);
})}
</tbody>
</table>
</div>
<h4>What changed</h4>
{events.length === 0 ? (
<div className="text-secondary small">Nothing yet.</div>
) : (
<ul className="list-unstyled mb-0">
{events.slice(0, allEvents ? undefined : SHOWN_EVENTS).map((e, i) => (
<li key={`${e.at}-${i}`} className="mb-1 text-break">
<span className={`me-2 ${KIND_DOT[e.kind]}`} aria-hidden="true">●</span>
{eventText(e)} <span className="text-secondary small">{formatDate(new Date(e.at))}</span>
</li>
))}
</ul>
)}
{events.length > SHOWN_EVENTS && (
<button className="btn btn-sm mt-2" onClick={() => setAllEvents(!allEvents)}>
{allEvents ? "Show fewer" : `Show all ${events.length}`}
</button>
)}
<div className="text-secondary small mt-3">
{data.startedAt ? `The app began keeping this on ${formatDate(new Date(data.startedAt))}. ` : ""}An item that was there before is shown at its current amount from the day it was added — what it was earlier is not known — and Hetzner’s estimate is kept from the first day it was written down.
</div>
</div>
</div>
);
}
+2
View File
@@ -1,6 +1,7 @@
import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom";
import { api, type CostInput, type CostItem, type CostsReport, type CurrentUser } from "../api/client";
import CostHistory from "../components/CostHistory";
import EmptyState from "../components/EmptyState";
import { BlockSkeleton } from "../components/Skeleton";
import { ErrorNotice } from "../components/Notice";
@@ -264,6 +265,7 @@ export default function Costs({ user }: { user: CurrentUser }) {
</div>
</div>
)}
{report && !empty && <CostHistory refreshKey={report} />}
</>
);
}
+26
View File
@@ -0,0 +1,26 @@
import type { CostHistory } from "../api/client";
export const money = (n: number, currency: string) => {
try {
return new Intl.NumberFormat(undefined, { style: "currency", currency }).format(n);
} catch {
return `${n.toFixed(2)} ${currency}`;
}
};
export const per = (period: string) => (period === "year" ? "a year" : "a month");
export type CostEventRow = CostHistory["events"][number];
/** One line saying what happened to what is paid for, in words. */
export function eventText(e: CostEventRow): string {
if (e.kind === "added") return `Added ${e.name} — ${money(e.amount, e.currency)} ${per(e.period)}`;
if (e.kind === "removed") return `Removed ${e.name} (it was ${money(e.amount, e.currency)} ${per(e.period)})`;
const f = e.from;
if (e.kind === "estimate") return `${e.name}: the estimate went from ${f ? money(f.amount, e.currency) : "—"} to ${money(e.amount, e.currency)} a month`;
const parts: string[] = [];
if (f && (f.amount !== e.amount || f.period !== e.period || f.currency !== e.currency)) parts.push(`${money(f.amount, f.currency)} ${per(f.period)} → ${money(e.amount, e.currency)} ${per(e.period)}`);
if (f && f.name !== e.name) parts.push(`renamed from ${f.name}`);
if (f && f.category !== e.category) parts.push(`kind ${f.category} → ${e.category}`);
return `Changed ${e.name}${parts.length > 0 ? ` — ${parts.join("; ")}` : ""}`;
}