Add an electricity estimate to the Costs page

The typical draws in the Inventory, the price of a kWh and the currency set
there give a cost per device and in all, counted in the totals under an
Electricity category when there is a draw, a price and a three-letter currency,
and said plainly (with what is missing) when there is not.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-10 20:59:50 +01:00
1 parent d69962528e
commit f546971000
6 files changed
+351 -9

No files matched your search

+2
View File
@@ -833,6 +833,8 @@ needed.
**Costs** (Records → Costs). What the homelab costs, in one place: the domains, VPN, licences and subscriptions you type in (an amount per month or per year, a currency, a kind, and optionally the day it is billed) and a Hetzner project's estimate, read by itself. Each currency has its own monthly and yearly total and a split by kind — none is converted into another. A day a bill falls on is an anchor: the next time it falls (the same day next month, or next year) is worked out and shows in **Coming up** as *Renewals*. Everyone signed in sees it; an administrator changes it. **Costs** (Records → Costs). What the homelab costs, in one place: the domains, VPN, licences and subscriptions you type in (an amount per month or per year, a currency, a kind, and optionally the day it is billed) and a Hetzner project's estimate, read by itself. Each currency has its own monthly and yearly total and a split by kind — none is converted into another. A day a bill falls on is an anchor: the next time it falls (the same day next month, or next year) is worked out and shows in **Coming up** as *Renewals*. Everyone signed in sees it; an administrator changes it.
**Electricity** (the *Electricity* card on Records → Costs). The typical power draw you enter for each piece of hardware in the **Inventory**, the **price of a kWh** and the **currency** set under Inventory (Running cost) give an estimate: the draws added up, run all day every day (730 hours a month), at one price — shown as watts, kWh and a cost per month and per year, with **each device’s own cost and share, biggest first**, and how many pieces of hardware have no draw entered. When there is a draw, a price and a currency that is a **three-letter code** (SEK, EUR …) it is also **counted in the totals** above under its own *Electricity* category, listed with the other things that are read, and kept in the cost history; with a currency typed as “kr” it is worked out and shown but not counted (the totals are per ISO currency), and without a price the card says what to set. It is an estimate of what the hardware draws, not a reading from the meter.
**Cost history** (the *History* card at the bottom of Records → Costs). What the homelab cost **in each past month**, per currency (6 to 36 months back): a bar for each month — the items you typed in, and the darker part for Hetzner's estimate — and beneath it the figure for each month and how much it moved from the month before. A month's figure is the monthly amount of everything that was in force at the month's end (a yearly bill counts a twelfth, as the totals do; the month that is not over is as of now), so an item that was dearer last spring, or has since been removed, is in the months it was there. Under it, **what changed**: items added, changed (*what it was → what it is*, and a rename or a new kind) and removed, and the day a Hetzner estimate moved from one figure to another. It starts when the app began keeping it: 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 written down once a day, so it is kept from the first day it was. Each item's earlier amounts are kept even after the item is removed. Everyone signed in sees it. **Cost history** (the *History* card at the bottom of Records → Costs). What the homelab cost **in each past month**, per currency (6 to 36 months back): a bar for each month — the items you typed in, and the darker part for Hetzner's estimate — and beneath it the figure for each month and how much it moved from the month before. A month's figure is the monthly amount of everything that was in force at the month's end (a yearly bill counts a twelfth, as the totals do; the month that is not over is as of now), so an item that was dearer last spring, or has since been removed, is in the months it was there. Under it, **what changed**: items added, changed (*what it was → what it is*, and a rename or a new kind) and removed, and the day a Hetzner estimate moved from one figure to another. It starts when the app began keeping it: 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 written down once a day, so it is kept from the first day it was. Each item's earlier amounts are kept even after the item is removed. Everyone signed in sees it.
**Status pages** are the other thing a share link can open: a page for family or housemates **Status pages** are the other thing a share link can open: a page for family or housemates
+4 -2
View File
@@ -5,7 +5,7 @@ import { db } from "../db/client.js";
import { costItems } from "../db/schema.js"; import { costItems } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js"; import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js"; import { recordAudit } from "../services/audit.js";
import { automaticCosts, costTotals, DEFAULT_CATEGORIES, isYmd, listCostItems, monthlyOf, nextRenewal, PERIODS, type CostRow } from "../services/costs.js"; import { automaticCosts, costTotals, currentElectricity, DEFAULT_CATEGORIES, isYmd, listCostItems, monthlyOf, nextRenewal, PERIODS, type CostRow } from "../services/costs.js";
import { buildHistory, reconcileVersions } from "../services/costHistory.js"; import { buildHistory, reconcileVersions } from "../services/costHistory.js";
import { localDate } from "../services/agenda.js"; import { localDate } from "../services/agenda.js";
import { getSettings } from "../services/settingsStore.js"; import { getSettings } from "../services/settingsStore.js";
@@ -45,12 +45,14 @@ const shape = (r: CostRow, today: string) => ({
/** What it costs: the items typed in, the estimates that can be read, and the totals per currency. Everyone signed in can see it. */ /** What it costs: the items typed in, the estimates that can be read, and the totals per currency. Everyone signed in can see it. */
costsRouter.get("/", asyncHandler(async (_req, res) => { costsRouter.get("/", asyncHandler(async (_req, res) => {
const [items, automatic, settings] = await Promise.all([listCostItems(), automaticCosts(), getSettings()]); const [items, automatic, settings, electricity] = await Promise.all([listCostItems(), automaticCosts(), getSettings(), currentElectricity()]);
const today = localDate(new Date(), settings.notifications.timezone || "UTC"); const today = localDate(new Date(), settings.notifications.timezone || "UTC");
res.json({ res.json({
items: items.map((r) => shape(r, today)), items: items.map((r) => shape(r, today)),
automatic, automatic,
totals: costTotals(items, automatic), totals: costTotals(items, automatic),
/** What the electricity costs and what it is made of, whether or not it is counted in the totals. */
electricity,
categories: [...new Set([...DEFAULT_CATEGORIES, ...items.map((i) => i.category)])], categories: [...new Set([...DEFAULT_CATEGORIES, ...items.map((i) => i.category)])],
}); });
})); }));
+84 -4
View File
@@ -3,13 +3,17 @@
* estimate), added up per currency as a monthly and a yearly figure. No currency is converted into another: a total in EUR and one in SEK are two totals, because a rate is a guess * estimate), added up per currency as a monthly and a yearly figure. No currency is converted into another: a total in EUR and one in SEK are two totals, because a rate is a guess
* made on the day it is read and a bill is not. * made on the day it is read and a bill is not.
* *
* **Electricity** is one of the things that are read rather than typed: the typical draw of each piece of hardware in the Inventory, the price of a kWh and the currency set under Settings → Inventory
* give a monthly cost (draw × the hours in an average month × the price), counted in the totals under the Electricity category once there is a draw, a price and a currency that is a three-letter code.
*
* Each item may carry the day it is billed. That day is an anchor, not a date that has to be kept up to date: the next time it falls is worked out from it (the same day next month, or the * Each item may carry the day it is billed. That day is an anchor, not a date that has to be kept up to date: the next time it falls is worked out from it (the same day next month, or the
* same day next year), and that is what "Coming up" shows. * same day next year), and that is what "Coming up" shows.
*/ */
import { and, eq } from "drizzle-orm"; import { and, eq } from "drizzle-orm";
import { db } from "../db/client.js"; import { db } from "../db/client.js";
import { costItems, hetznerState, integrations } from "../db/schema.js"; import { assets, costItems, hetznerState, integrations } from "../db/schema.js";
import { costOf } from "./hetznerSync.js"; import { costOf } from "./hetznerSync.js";
import { getSettings } from "./settingsStore.js";
export const PERIODS = ["month", "year"] as const; export const PERIODS = ["month", "year"] as const;
export type Period = (typeof PERIODS)[number]; export type Period = (typeof PERIODS)[number];
@@ -55,6 +59,8 @@ export interface AutomaticCost {
link: string; link: string;
/** Whether it was read lately; a stale figure is still shown (and counted), with that said. */ /** Whether it was read lately; a stale figure is still shown (and counted), with that said. */
stale: boolean; stale: boolean;
/** Which category the totals file it under; Hosting when it does not say. */
category?: string;
} }
export interface CurrencyTotal { export interface CurrencyTotal {
@@ -67,7 +73,7 @@ export interface CurrencyTotal {
} }
/** Pure: the totals per currency of manual items and automatic ones. Hetzner's estimate is filed under "Hosting". */ /** Pure: the totals per currency of manual items and automatic ones. Hetzner's estimate is filed under "Hosting". */
export function costTotals(items: Pick<CostRow, "amount" | "currency" | "period" | "category">[], automatic: Pick<AutomaticCost, "currency" | "monthly">[]): CurrencyTotal[] { export function costTotals(items: Pick<CostRow, "amount" | "currency" | "period" | "category">[], automatic: Pick<AutomaticCost, "currency" | "monthly" | "category">[]): CurrencyTotal[] {
const byCurrency = new Map<string, { monthly: number; items: number; categories: Map<string, number> }>(); const byCurrency = new Map<string, { monthly: number; items: number; categories: Map<string, number> }>();
const add = (currency: string, category: string, monthly: number) => { const add = (currency: string, category: string, monthly: number) => {
const e = byCurrency.get(currency) ?? { monthly: 0, items: 0, categories: new Map<string, number>() }; const e = byCurrency.get(currency) ?? { monthly: 0, items: 0, categories: new Map<string, number>() };
@@ -77,7 +83,7 @@ export function costTotals(items: Pick<CostRow, "amount" | "currency" | "period"
byCurrency.set(currency, e); byCurrency.set(currency, e);
}; };
for (const i of items) add(i.currency, i.category, monthlyOf(i.amount, i.period)); for (const i of items) add(i.currency, i.category, monthlyOf(i.amount, i.period));
for (const a of automatic) add(a.currency, "Hosting", a.monthly); for (const a of automatic) add(a.currency, a.category ?? "Hosting", a.monthly);
return [...byCurrency.entries()] return [...byCurrency.entries()]
.map(([currency, e]) => ({ .map(([currency, e]) => ({
currency, currency,
@@ -93,7 +99,77 @@ export async function listCostItems(): Promise<CostRow[]> {
return (await db.select().from(costItems)).sort((a, b) => a.name.localeCompare(b.name)); return (await db.select().from(costItems)).sort((a, b) => a.name.localeCompare(b.name));
} }
/** What can be read rather than typed: each Hetzner project's estimate. */ /** An average month: a year of hours over twelve. */
export const HOURS_PER_MONTH = (24 * 365) / 12;
export interface ElectricityDevice {
id: number;
name: string;
kind: string;
watts: number;
/** Per month at the price; null without one. */
monthly: number | null;
/** Its share of the whole draw, 0–100. */
share: number;
}
export interface Electricity {
/** The typical draw of everything in the inventory, in watts. */
watts: number;
/** Largest draw first. */
devices: ElectricityDevice[];
/** Pieces of hardware with no draw entered, so not in any of this. */
withoutDraw: number;
pricePerKwh: number | null;
/** The currency as it was typed under Settings → Inventory ("SEK", "kr", "$"); empty when none. */
currencyLabel: string;
/** The currency as the totals need it — three letters — or null when what was typed is not one. */
currency: string | null;
kwhPerMonth: number | null;
monthly: number | null;
yearly: number | null;
/** Whether it is counted in the totals: there is a draw, a price and a three-letter currency. */
includedInTotals: boolean;
/** What is missing for it to be counted, when it is not. */
missing: "draw" | "price" | "currency" | null;
}
const round1 = (n: number) => Math.round(n * 10) / 10;
/** Pure: what the electricity costs, from the hardware's draws, the price of a kWh and the currency typed in the Inventory settings. */
export function electricityEstimate(hardware: { id: number; name: string; kind: string; powerWatts: number | null }[], settings: { pricePerKwh: number | null; currency: string }): Electricity {
const drawing = hardware.filter((h) => h.powerWatts !== null && h.powerWatts > 0);
const watts = drawing.reduce((n, h) => n + (h.powerWatts as number), 0);
const price = settings.pricePerKwh !== null && settings.pricePerKwh > 0 ? settings.pricePerKwh : null;
const label = settings.currency.trim();
const currency = /^[A-Za-z]{3}$/.test(label) ? label.toUpperCase() : null;
const kwhOf = (w: number) => (w / 1000) * HOURS_PER_MONTH;
const monthly = price !== null && watts > 0 ? round2(kwhOf(watts) * price) : null;
const missing: Electricity["missing"] = watts <= 0 ? "draw" : price === null ? "price" : currency === null ? "currency" : null;
return {
watts,
devices: drawing
.map((h) => ({ id: h.id, name: h.name, kind: h.kind, watts: h.powerWatts as number, monthly: price !== null ? round2(kwhOf(h.powerWatts as number) * price) : null, share: watts > 0 ? round1(((h.powerWatts as number) / watts) * 100) : 0 }))
.sort((a, b) => b.watts - a.watts || a.name.localeCompare(b.name)),
withoutDraw: hardware.length - drawing.length,
pricePerKwh: price,
currencyLabel: label,
currency,
kwhPerMonth: watts > 0 ? round2(kwhOf(watts)) : null,
monthly,
yearly: monthly !== null ? round2(monthly * 12) : null,
includedInTotals: missing === null,
missing,
};
}
/** The electricity as it is now, from the Inventory and its settings. */
export async function currentElectricity(): Promise<Electricity> {
const [hardware, settings] = await Promise.all([db.select({ id: assets.id, name: assets.name, kind: assets.kind, powerWatts: assets.powerWatts }).from(assets), getSettings()]);
return electricityEstimate(hardware, settings.inventory);
}
/** What can be read rather than typed: each Hetzner project's estimate, and the electricity. */
export async function automaticCosts(nowMs: number = Date.now(), staleAfterMs = 20 * 60_000): Promise<AutomaticCost[]> { export async function automaticCosts(nowMs: number = Date.now(), staleAfterMs = 20 * 60_000): Promise<AutomaticCost[]> {
const rows = await db const rows = await db
.select({ id: integrations.id, name: integrations.name, state: hetznerState }) .select({ id: integrations.id, name: integrations.name, state: hetznerState })
@@ -107,5 +183,9 @@ export async function automaticCosts(nowMs: number = Date.now(), staleAfterMs =
const parts = [`servers ${cost.servers.toFixed(2)}`, `backups ${cost.backups.toFixed(2)}`, `volumes ${cost.volumes.toFixed(2)}`, `snapshots ${cost.snapshots.toFixed(2)}`, `IPs ${cost.ips.toFixed(2)}`].join(" · "); const parts = [`servers ${cost.servers.toFixed(2)}`, `backups ${cost.backups.toFixed(2)}`, `volumes ${cost.volumes.toFixed(2)}`, `snapshots ${cost.snapshots.toFixed(2)}`, `IPs ${cost.ips.toFixed(2)}`].join(" · ");
out.push({ key: `hetzner:${r.id}`, source: "Hetzner Cloud", name: r.name, currency: cost.currency, monthly: cost.total, detail: `${parts} — an estimate at list prices, including VAT`, link: "/hetzner", stale: nowMs - Date.parse(r.state.updatedAt) > staleAfterMs }); out.push({ key: `hetzner:${r.id}`, source: "Hetzner Cloud", name: r.name, currency: cost.currency, monthly: cost.total, detail: `${parts} — an estimate at list prices, including VAT`, link: "/hetzner", stale: nowMs - Date.parse(r.state.updatedAt) > staleAfterMs });
} }
const power = await currentElectricity();
if (power.includedInTotals && power.currency && power.monthly !== null) {
out.push({ key: "electricity", source: "Inventory", name: "Electricity", currency: power.currency, monthly: power.monthly, detail: `${power.watts} W typical draw × ${Math.round(HOURS_PER_MONTH)} hours a month × ${power.pricePerKwh} per kWh — an estimate from the draws in the Inventory`, link: "/inventory", stale: false, category: "Electricity" });
}
return out; return out;
} }
+144
View File
@@ -0,0 +1,144 @@
/**
* The electricity estimate under Costs: the typical draws in the Inventory, the price of a kWh and the currency set there give a cost per device and in all, counted in the totals when there is a draw,
* a price and a three-letter currency — and said plainly, with what is missing, when there is not.
*
* 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-electricity-"));
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, assets, costSnapshots } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js");
const costs = await import("../src/services/costs.js");
const history = await import("../src/services/costHistory.js");
const { costsRouter } = await import("../src/routes/costs.js");
const { updateSettings } = await import("../src/services/settingsStore.js");
await runMigrations();
const hw = (id: number, name: string, watts: number | null, kind = "server") => ({ id, name, kind, powerWatts: watts });
describe("the estimate", () => {
test("a steady draw over an average month at the price: watts × 730 hours, in kWh, times the price", () => {
assert.equal(Math.round(costs.HOURS_PER_MONTH), 730);
const e = costs.electricityEstimate([hw(1, "nas", 50)], { pricePerKwh: 2, currency: "SEK" });
// 50 W × 730 h = 36.5 kWh; × 2 = 73.00
assert.deepEqual([e.watts, e.kwhPerMonth, e.monthly, e.yearly, e.currency, e.includedInTotals, e.missing], [50, 36.5, 73, 876, "SEK", true, null]);
});
test("each device has its own cost and its share, the biggest first, and what is left out is counted", () => {
const e = costs.electricityEstimate([hw(1, "switch", 20, "network"), hw(2, "pve1", 150), hw(3, "ups", null, "power"), hw(4, "pi", 5), hw(5, "off", 0)], { pricePerKwh: 1.5, currency: "eur" });
assert.deepEqual(e.devices.map((d) => [d.name, d.watts, d.share]), [["pve1", 150, 85.7], ["switch", 20, 11.4], ["pi", 5, 2.9]]);
assert.equal(e.watts, 175);
assert.equal(e.withoutDraw, 2, "a missing draw and a draw of nothing are both without one");
assert.equal(e.devices[0].monthly, Math.round(0.15 * 730 * 1.5 * 100) / 100);
assert.equal(e.currency, "EUR", "a code is made capitals");
});
test("devices with the same draw come by name", () => {
const e = costs.electricityEstimate([hw(1, "b", 10), hw(2, "a", 10)], { pricePerKwh: 1, currency: "SEK" });
assert.deepEqual(e.devices.map((d) => d.name), ["a", "b"]);
});
test("without a draw there is nothing to say; without a price there is the draw but no cost; with a currency that is not a code it is worked out but not counted", () => {
const none = costs.electricityEstimate([hw(1, "x", null)], { pricePerKwh: 2, currency: "SEK" });
assert.deepEqual([none.watts, none.monthly, none.includedInTotals, none.missing], [0, null, false, "draw"]);
const noPrice = costs.electricityEstimate([hw(1, "x", 100)], { pricePerKwh: null, currency: "SEK" });
assert.deepEqual([noPrice.watts, noPrice.monthly, noPrice.devices[0].monthly, noPrice.missing, noPrice.includedInTotals], [100, null, null, "price", false]);
const kr = costs.electricityEstimate([hw(1, "x", 100)], { pricePerKwh: 2, currency: "kr" });
assert.deepEqual([kr.monthly, kr.currency, kr.currencyLabel, kr.missing, kr.includedInTotals], [146, null, "kr", "currency", false]);
for (const bad of ["", "SE", "SEKK", "€", "12"]) assert.equal(costs.electricityEstimate([hw(1, "x", 100)], { pricePerKwh: 2, currency: bad }).currency, null, JSON.stringify(bad));
});
test("a price of zero or less is no price", () => {
for (const price of [0, -1, null]) assert.equal(costs.electricityEstimate([hw(1, "x", 100)], { pricePerKwh: price, currency: "SEK" }).monthly, null);
});
});
describe("in the totals", () => {
test("a read estimate is filed under its own category, and Hosting when it says none", () => {
const t = costs.costTotals([], [{ currency: "SEK", monthly: 100, category: "Electricity" }, { currency: "SEK", monthly: 50 }]);
assert.deepEqual(t[0].categories, [{ category: "Electricity", monthly: 100 }, { category: "Hosting", monthly: 50 }]);
});
});
describe("through the page's route", () => {
let app: Server;
let base = "";
before(async () => {
await db.insert(users).values({ oidcSub: "viewer", name: "Vic", role: "viewer" });
await db.insert(assets).values([
{ name: "pve1", kind: "server", powerWatts: 150, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() },
{ name: "nas", kind: "storage", powerWatts: 50, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() },
{ name: "shelf", kind: "other", powerWatts: null, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString() },
]);
const a = express();
a.use(express.json());
a.use((req, _res, next) => {
(req as unknown as { session: unknown }).session = { user: { sub: "viewer" } };
next();
});
a.use("/api/costs", costsRouter);
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/costs`;
});
after(async () => {
app.close();
await updateSettings({ inventory: { currency: "", pricePerKwh: null } });
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
const report = async () => (await (await fetch(base)).json()) as { electricity: Awaited<ReturnType<typeof costs.currentElectricity>>; automatic: { key: string; monthly: number; category?: string; currency: string; link: string }[]; totals: { currency: string; monthly: number; categories: { category: string; monthly: number }[] }[] };
test("with draws but no price it says what is missing, shows the draw, and adds nothing to the totals", async () => {
await updateSettings({ inventory: { currency: "SEK", pricePerKwh: null } });
const r = await report();
assert.deepEqual([r.electricity.watts, r.electricity.missing, r.electricity.includedInTotals, r.electricity.monthly], [200, "price", false, null]);
assert.equal(r.automatic.some((a) => a.key === "electricity"), false);
assert.deepEqual(r.totals, []);
});
test("with a price and a three-letter currency it is counted in the totals, under Electricity, and anyone signed in sees it", async () => {
await updateSettings({ inventory: { currency: "SEK", pricePerKwh: 2 } });
const r = await report();
// 200 W × 730 h = 146 kWh × 2 = 292
assert.deepEqual([r.electricity.monthly, r.electricity.yearly, r.electricity.includedInTotals], [292, 3504, true]);
assert.deepEqual(r.electricity.devices.map((d) => d.name), ["pve1", "nas"]);
const auto = r.automatic.find((a) => a.key === "electricity")!;
assert.deepEqual([auto.monthly, auto.currency, auto.category, auto.link], [292, "SEK", "Electricity", "/inventory"]);
assert.deepEqual(r.totals.map((t) => [t.currency, t.monthly, t.categories]), [["SEK", 292, [{ category: "Electricity", monthly: 292 }]]]);
});
test("a currency that is not a code leaves it out of the totals but still works it out", async () => {
await updateSettings({ inventory: { currency: "kr", pricePerKwh: 2 } });
const r = await report();
assert.deepEqual([r.electricity.monthly, r.electricity.currency, r.electricity.includedInTotals, r.electricity.missing], [292, null, false, "currency"]);
assert.deepEqual(r.totals, []);
});
test("a change in the draws or the price is a new figure the next time it is read, and the daily snapshot keeps it for the history", async () => {
await updateSettings({ inventory: { currency: "SEK", pricePerKwh: 3 } });
assert.equal((await report()).electricity.monthly, 438);
await history.snapshotAutomatic(new Date("2026-11-10T12:00:00Z"));
const snaps = (await db.select().from(costSnapshots)).filter((s) => s.key === "electricity");
assert.deepEqual(snaps.map((s) => [s.day, s.currency, s.monthly]), [["2026-11-10", "SEK", 438]]);
});
});
+18 -1
View File
@@ -1832,12 +1832,29 @@ export interface CostInput {
export interface CostsReport { export interface CostsReport {
items: CostItem[]; items: CostItem[];
/** What can be read rather than typed: a Hetzner project's estimate. */ /** What can be read rather than typed: a Hetzner project's estimate. */
automatic: { key: string; source: string; name: string; currency: string; monthly: number; detail: string; link: string; stale: boolean }[]; automatic: { key: string; source: string; name: string; currency: string; monthly: number; detail: string; link: string; stale: boolean; category?: string }[];
/** Per currency; none is converted into another. */ /** Per currency; none is converted into another. */
totals: { currency: string; monthly: number; yearly: number; items: number; categories: { category: string; monthly: number }[] }[]; totals: { currency: string; monthly: number; yearly: number; items: number; categories: { category: string; monthly: number }[] }[];
/** What the electricity costs and what it is made of, whether or not it is counted in the totals. */
electricity: Electricity;
categories: string[]; categories: string[];
} }
/** The electricity estimate: the draws in the Inventory, the price of a kWh and the currency set under Settings → Inventory. */
export interface Electricity {
watts: number;
devices: { id: number; name: string; kind: string; watts: number; monthly: number | null; share: number }[];
withoutDraw: number;
pricePerKwh: number | null;
currencyLabel: string;
currency: string | null;
kwhPerMonth: number | null;
monthly: number | null;
yearly: number | null;
includedInTotals: boolean;
missing: "draw" | "price" | "currency" | null;
}
/** What the homelab cost, month by month for each currency, and what changed. */ /** What the homelab cost, month by month for each currency, and what changed. */
export interface CostHistory { export interface CostHistory {
/** From the first month there is anything to say about, to this one. */ /** From the first month there is anything to say about, to this one. */
+99 -2
View File
@@ -1,6 +1,6 @@
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { api, type CostInput, type CostItem, type CostsReport, type CurrentUser } from "../api/client"; import { api, type CostInput, type CostItem, type CostsReport, type CurrentUser, type Electricity } from "../api/client";
import CostHistory from "../components/CostHistory"; import CostHistory from "../components/CostHistory";
import EmptyState from "../components/EmptyState"; import EmptyState from "../components/EmptyState";
import { BlockSkeleton } from "../components/Skeleton"; import { BlockSkeleton } from "../components/Skeleton";
@@ -19,6 +19,101 @@ const money = (n: number, currency: string) => {
} }
}; };
/** An amount in the currency as it was typed in the Inventory settings ("SEK", "kr"): a three-letter code is formatted as money, anything else is written after the number. */
const moneyIn = (n: number, label: string, code: string | null) => (code ? money(n, code) : `${n.toLocaleString(undefined, { maximumFractionDigits: 2 })}${label ? ` ${label}` : ""}`);
/**
* What the electricity costs: the typical draw of each piece of hardware in the Inventory, at the price of a kWh set there. Shows what it is made of, biggest first, and says what is missing when there
* is not enough to work it out (a draw, a price, a currency that is a three-letter code) — and whether it is counted in the totals above.
*/
function ElectricityCard({ e }: { e: Electricity }) {
const none = e.watts <= 0;
const hint =
e.missing === "draw"
? "Enter each piece of hardware's typical power draw (watts) in the Inventory to estimate it."
: e.missing === "price"
? "Set the price of a kWh under Inventory → Running cost to put a cost on it."
: e.missing === "currency"
? `The currency in the Inventory settings (${e.currencyLabel ? `“${e.currencyLabel}”` : "none"}) is not a three-letter code, so this is not counted in the totals — set it to SEK, EUR … to count it.`
: null;
return (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Electricity</h3>
<div className="card-actions">
<Link to="/inventory" className="btn btn-sm">
Open the Inventory
</Link>
</div>
</div>
<div className="card-body">
{none ? (
<div className="text-secondary">{hint}</div>
) : (
<div className="row g-3 mb-3">
<div className="col-6 col-md-3">
<div className="text-secondary small">Typical draw</div>
<div className="h2 mb-0">{e.watts.toLocaleString()} W</div>
<div className="text-secondary small">{e.kwhPerMonth?.toLocaleString(undefined, { maximumFractionDigits: 0 })} kWh a month</div>
</div>
<div className="col-6 col-md-3">
<div className="text-secondary small">Per month</div>
<div className="h2 mb-0">{e.monthly !== null ? moneyIn(e.monthly, e.currencyLabel, e.currency) : "—"}</div>
<div className="text-secondary small">{e.pricePerKwh !== null ? `at ${e.pricePerKwh} per kWh` : "no price set"}</div>
</div>
<div className="col-6 col-md-3">
<div className="text-secondary small">Per year</div>
<div className="h2 mb-0">{e.yearly !== null ? moneyIn(e.yearly, e.currencyLabel, e.currency) : "—"}</div>
</div>
<div className="col-6 col-md-3">
<div className="text-secondary small">In the totals</div>
<div className="h2 mb-0">{e.includedInTotals ? "Yes" : "No"}</div>
<div className="text-secondary small">{e.includedInTotals ? "under Electricity" : "see below"}</div>
</div>
</div>
)}
{!none && hint && <div className="text-yellow small mb-3">{hint}</div>}
{e.devices.length > 0 && (
<div className="table-responsive">
<table className="table table-sm table-vcenter mb-0">
<thead>
<tr>
<th>Hardware</th>
<th className="text-end">Draw</th>
<th className="text-end">Per month</th>
<th style={{ minWidth: 140 }}>Share</th>
</tr>
</thead>
<tbody>
{e.devices.map((d) => (
<tr key={d.id}>
<td>
<Link to={`/inventory?q=${encodeURIComponent(d.name)}`}>{d.name}</Link> <span className="text-secondary small">{d.kind}</span>
</td>
<td className="text-end">{d.watts} W</td>
<td className="text-end">{d.monthly !== null ? moneyIn(d.monthly, e.currencyLabel, e.currency) : "—"}</td>
<td>
<div className="progress progress-sm" title={`${d.share}% of the draw`}>
<div className="progress-bar" style={{ width: `${Math.max(2, d.share)}%` }} />
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
{e.withoutDraw > 0 && (
<div className="text-secondary small mt-2">
{e.withoutDraw} piece{e.withoutDraw === 1 ? "" : "s"} of hardware in the Inventory {e.withoutDraw === 1 ? "has" : "have"} no power draw entered and {e.withoutDraw === 1 ? "is" : "are"} not in this.
</div>
)}
<div className="text-secondary small mt-2">An estimate: the typical draws added up and run all day, every day ({Math.round((24 * 365) / 12)} hours a month), at one price. What the meter says is what counts.</div>
</div>
</div>
);
}
const blank = (currency: string): CostInput => ({ name: "", amount: 0, currency, period: "month", category: "Subscriptions", renewsOn: null, note: null }); const blank = (currency: string): CostInput => ({ name: "", amount: 0, currency, period: "month", category: "Subscriptions", renewsOn: null, note: null });
function ItemForm({ initial, categories, currencies, saving, onSave, onCancel }: { initial: CostInput; categories: string[]; currencies: string[]; saving: boolean; onSave: (v: CostInput) => void; onCancel: () => void }) { function ItemForm({ initial, categories, currencies, saving, onSave, onCancel }: { initial: CostInput; categories: string[]; currencies: string[]; saving: boolean; onSave: (v: CostInput) => void; onCancel: () => void }) {
@@ -183,6 +278,8 @@ export default function Costs({ user }: { user: CurrentUser }) {
</div> </div>
)} )}
{report && <ElectricityCard e={report.electricity} />}
{form && ( {form && (
<div className="card mb-3"> <div className="card mb-3">
<div className="card-header"> <div className="card-header">
@@ -224,7 +321,7 @@ export default function Costs({ user }: { user: CurrentUser }) {
<strong>{a.name}</strong> <span className="badge bg-blue-lt text-blue">read from {a.source}</span> <strong>{a.name}</strong> <span className="badge bg-blue-lt text-blue">read from {a.source}</span>
<div className="text-secondary small text-break">{a.detail}{a.stale ? " — not read lately, so this may be out of date" : ""}</div> <div className="text-secondary small text-break">{a.detail}{a.stale ? " — not read lately, so this may be out of date" : ""}</div>
</td> </td>
<td className="text-secondary">Hosting</td> <td className="text-secondary">{a.category ?? "Hosting"}</td>
<td className="text-secondary">estimate</td> <td className="text-secondary">estimate</td>
<td>{money(a.monthly, a.currency)}</td> <td>{money(a.monthly, a.currency)}</td>
<td className="text-secondary">—</td> <td className="text-secondary">—</td>