import { all, first } from "../db"; import { forbidden, notFoundError } from "../errors"; import type { Viewer } from "~/lib/types"; export type BillingAccount = { accountId: string; name: string; kind: "user" | "org"; canEdit: boolean }; /** The account whose usage `viewer` may see: themselves, or an org they belong to (owners may edit). */ export async function billingAccountFor(viewer: Viewer, org: string | null): Promise { if (!org) return { accountId: viewer.id, name: viewer.name, kind: "user", canEdit: true }; const account = await first<{ id: string; name: string }>( "SELECT id, name FROM accounts WHERE name = ? COLLATE NOCASE AND kind = 'org'", org, ); if (!account) throw notFoundError("Organization not found"); const member = await first<{ role: string }>( "SELECT role FROM org_members WHERE org_id = ? AND user_id = ?", account.id, viewer.id, ); if (!member && !viewer.isAdmin) throw notFoundError("Organization not found"); return { accountId: account.id, name: account.name, kind: "org", canEdit: member?.role === "owner" }; } export function requireSiteAdmin(viewer: Viewer): void { if (!viewer.isAdmin) throw forbidden("Site administrators only"); } export type AdminUsageRow = { accountId: string; name: string | null; kind: string | null; meter: string; quantity: number; }; const TOP_PER_METER = 20; /** Site-admin view: the heaviest accounts for each meter this period (counters and gauge peaks). */ export async function topUsage(period: string): Promise { const rows = await all<{ account_id: string; name: string | null; kind: string | null; meter: string; quantity: number; }>( `SELECT r.account_id, a.name, a.kind, r.meter, r.quantity FROM ( SELECT u.*, ROW_NUMBER() OVER (PARTITION BY u.meter ORDER BY u.quantity DESC) AS rank FROM ( SELECT account_id, meter, quantity FROM usage_periods WHERE period = ?1 AND quantity > 0 UNION ALL SELECT account_id, meter, peak AS quantity FROM usage_gauges WHERE period = ?1 AND peak > 0 ) u ) r LEFT JOIN accounts a ON a.id = r.account_id WHERE r.rank <= ?2 ORDER BY r.meter, r.quantity DESC`, period, TOP_PER_METER, ); return rows.map((row) => ({ accountId: row.account_id, name: row.name, kind: row.kind, meter: row.meter, quantity: row.quantity, })); }