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:
1 parent
d69962528e
commit
f546971000
6 files changed
+351
-9
No files matched your search
@@ -5,7 +5,7 @@ import { db } from "../db/client.js";
|
||||
import { costItems } from "../db/schema.js";
|
||||
import { requireAuth, requireRole } from "../auth/middleware.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 { localDate } from "../services/agenda.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. */
|
||||
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");
|
||||
res.json({
|
||||
items: items.map((r) => shape(r, today)),
|
||||
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)])],
|
||||
});
|
||||
}));
|
||||
|
||||
@@ -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
|
||||
* 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
|
||||
* same day next year), and that is what "Coming up" shows.
|
||||
*/
|
||||
import { and, eq } from "drizzle-orm";
|
||||
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 { getSettings } from "./settingsStore.js";
|
||||
|
||||
export const PERIODS = ["month", "year"] as const;
|
||||
export type Period = (typeof PERIODS)[number];
|
||||
@@ -55,6 +59,8 @@ export interface AutomaticCost {
|
||||
link: string;
|
||||
/** Whether it was read lately; a stale figure is still shown (and counted), with that said. */
|
||||
stale: boolean;
|
||||
/** Which category the totals file it under; Hosting when it does not say. */
|
||||
category?: string;
|
||||
}
|
||||
|
||||
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". */
|
||||
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 add = (currency: string, category: string, monthly: 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);
|
||||
};
|
||||
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()]
|
||||
.map(([currency, e]) => ({
|
||||
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));
|
||||
}
|
||||
|
||||
/** 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[]> {
|
||||
const rows = await db
|
||||
.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(" · ");
|
||||
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;
|
||||
}
|
||||
@@ -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]]);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user