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

+4 -2
View File
@@ -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)])],
});
}));
+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
* 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;
}