Skip to content
207 linesCodeBlameRaw
1/**
2 * The Invoices and Audit log pages' arithmetic and wording: filters read
3 * from the address, totals, links from billing's account ids to sudo's
4 * pages, and paging. No Workers imports, so it can be tested under Node.
5 */
6import type { AdminAction, InvoiceSummary } from "@g1t/contracts";
7
8// --- Invoices -----------------------------------------------------------------
9
10export const INVOICE_STATUSES = ["open", "overdue", "failed", "paid", "void"] as const;
11export type InvoiceStatusFilter = (typeof INVOICE_STATUSES)[number];
12
13export function parseInvoiceStatus(value: string | null): InvoiceStatusFilter | null {
14 return INVOICE_STATUSES.find((status) => status === value) ?? null;
15}
16
17/** A month as `<input type="month">` sends it: `2026-10`. */
18export function parseMonth(value: string | null): string | null {
19 if (!value || !/^\d{4}-(0[1-9]|1[0-2])$/.test(value)) return null;
20 return value;
21}
22
23/** Not paid and not void: what is still owed. */
24export function isOutstanding(status: string): boolean {
25 return status === "open" || status === "overdue" || status === "failed";
26}
27
28export type InvoiceTotals = { count: number; amountMicros: number; paidMicros: number; outstandingMicros: number; outstanding: number };
29
30export function invoiceTotals(invoices: Pick<InvoiceSummary, "amountMicros" | "status">[]): InvoiceTotals {
31 const totals: InvoiceTotals = { count: invoices.length, amountMicros: 0, paidMicros: 0, outstandingMicros: 0, outstanding: 0 };
32 for (const invoice of invoices) {
33 if (invoice.status === "void") continue;
34 totals.amountMicros += invoice.amountMicros;
35 if (invoice.status === "paid") totals.paidMicros += invoice.amountMicros;
36 if (isOutstanding(invoice.status)) {
37 totals.outstandingMicros += invoice.amountMicros;
38 totals.outstanding += 1;
39 }
40 }
41 return totals;
42}
43
44/** A link to the invoices list with these filters; the defaults are left out. */
45export function invoicesHref({ status, month }: { status?: string | null; month?: string | null }): string {
46 const params = new URLSearchParams();
47 if (status) params.set("status", status);
48 if (month) params.set("month", month);
49 const query = params.toString();
50 return query ? `/invoices?${query}` : "/invoices";
51}
52
53/** Only https links to Stripe are followed. */
54export function safeUrl(url: string | null | undefined): string | null {
55 return url && url.startsWith("https://") ? url : null;
56}
57
58// --- Accounts -------------------------------------------------------------------
59
60const SLUG = /^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,38}$/;
61const ENTERPRISE = /^ent_[a-z0-9_-]{1,80}$/;
62
63/**
64 * The sudo page for one of billing's account ids: `ws_<slug>` is the
65 * workspace's, `ent_…` the enterprise's. Null for anything else, such as
66 * Stripe's own lines.
67 */
68export function accountPath(account: string | null | undefined): string | null {
69 const id = (account ?? "").trim().toLowerCase();
70 // The model catalogue's changes (billing's catalogue.rs).
71 if (id === "models") return "/agents";
72 const status = /^(incident|maintenance):([a-z0-9-]{1,64})$/.exec(id);
73 if (status) return status[1] === "incident" ? `/incidents/${status[2]}` : `/incidents/maintenance/${status[2]}`;
74 if (ENTERPRISE.test(id)) return `/enterprises/${encodeURIComponent(id)}`;
75 if (id.startsWith("ws_") && SLUG.test(id.slice(3))) return `/workspaces/${encodeURIComponent(id.slice(3))}`;
76 return null;
77}
78
79/** What to call an account: a workspace by its slug, an enterprise by its name when known. */
80export function accountName(account: string, names: Map<string, string> = new Map()): string {
81 if (names.has(account)) return names.get(account) as string;
82 if (account === "models") return "Agents & models";
83 if (account.startsWith("incident:")) return "Incident";
84 if (account.startsWith("maintenance:")) return "Maintenance";
85 if (account.startsWith("ws_")) return account.slice(3);
86 if (ENTERPRISE.test(account)) return "an enterprise";
87 return account;
88}
89
90// --- Audit ----------------------------------------------------------------------
91
92/** Each kind of change, as staff read it. */
93export const AUDIT_ACTIONS: Record<string, string> = {
94 terms: "Terms changed",
95 allowances: "Plan, pools and caps changed",
96 payment: "Bank transfer recorded",
97 goodwill: "Goodwill credit",
98 request: "Request answered",
99 create: "Enterprise created",
100 attach: "Workspace added",
101 detach: "Workspace removed",
102 credit: "Credit issued",
103 reset: "Billing reset (testing)",
104 billing_link: "Billing link made",
105 billing_email: "Invoice email set",
106 invoice: "Invoice sent",
107 dispute: "Payment disputed",
108 sales: "Sales record changed",
109 note: "Sales note added",
110 stripe: "From Stripe",
111 webhook: "Stripe webhook registered",
112 close: "Billing closed",
113 // From identity: deleted workspaces staff restored or purged.
114 workspace_restored: "Workspace restored",
115 workspace_purged: "Workspace purged",
116 // From identity: accounts staff deleted, restored or purged.
117 account_deleted: "Account deleted",
118 account_restored: "Account restored",
119 account_purged: "Account purged",
120 // From identity: workspace aliases staff set or removed.
121 alias_added: "Alias added",
122 alias_removed: "Alias removed",
123 // From the status page (apps/status), merged in by the Audit log page.
124 incident_declared: "Incident declared",
125 incident_detected: "Incident detected",
126 incident_update: "Incident update",
127 incident_note: "Incident note",
128 incident_resolved: "Incident resolved",
129 incident_roles: "Incident roles",
130 incident_published: "Incident published",
131 incident_dismissed: "Draft dismissed",
132 incident_followup: "Incident follow-up",
133 postmortem_saved: "Postmortem saved",
134 postmortem_published: "Postmortem published",
135 postmortem_unpublished: "Postmortem taken down",
136 maintenance_scheduled: "Maintenance scheduled",
137 maintenance_update: "Maintenance update",
138 maintenance_started: "Maintenance started",
139 maintenance_completed: "Maintenance completed",
140 maintenance_cancelled: "Maintenance cancelled",
141 credit_revoked: "Credit revoked",
142 credit_expired: "Credit expired",
143 // The model catalogue (Agents & models).
144 models_discovered: "Models found or gone",
145 model_approved: "Model approved",
146 model_retired: "Model retired",
147 model_restored: "Model restored",
148 model_default: "Model default changed",
149};
150
151/**
152 * The status page's audit lines as the Audit log lists billing's: the
153 * account is `incident:<id>` or `maintenance:<id>`, which link to their
154 * pages in sudo.
155 */
156export function statusAuditActions(entries: { id: string; at: string; by: string; action: string; target: string; detail: string }[]): AdminAction[] {
157 return entries.map((e) => ({
158 id: `status-${e.id}`,
159 account: `${e.action.startsWith("maintenance_") ? "maintenance" : "incident"}:${e.target}`,
160 action: e.action,
161 detail: e.detail,
162 by: e.by,
163 createdAt: e.at,
164 }));
165}
166
167/** Billing's lines and the status page's, newest first, one page's worth. */
168export function mergeAudit(a: AdminAction[], b: AdminAction[], page = AUDIT_PAGE): AdminAction[] {
169 return [...a, ...b].sort((x, y) => y.createdAt.localeCompare(x.createdAt)).slice(0, page);
170}
171
172export function actionLabel(action: string): string {
173 return AUDIT_ACTIONS[action] ?? action.replace(/_/g, " ").replace(/^./, (char) => char.toUpperCase());
174}
175
176export const AUDIT_PAGE = 100;
177
178/** Where the next, older page starts: after the last line, if this page was full. */
179export function olderBefore(actions: Pick<AdminAction, "createdAt">[], page = AUDIT_PAGE): string | null {
180 return actions.length >= page ? (actions.at(-1)?.createdAt ?? null) : null;
181}
182
183/** A staff email filter: lowercased, at most one address's length. */
184export function parseBy(value: string | null): string | null {
185 const by = (value ?? "").trim().toLowerCase();
186 return by && by.length <= 254 && !/\s/.test(by) ? by : null;
187}
188
189export function parseAction(value: string | null): string | null {
190 const action = (value ?? "").trim();
191 return /^[a-z_]{1,40}$/.test(action) ? action : null;
192}
193
194/** An RFC 3339 time to page from. */
195export function parseBefore(value: string | null): string | null {
196 if (!value || value.length > 40 || Number.isNaN(new Date(value).getTime())) return null;
197 return value;
198}
199
200export function auditHref({ by, action, before }: { by?: string | null; action?: string | null; before?: string | null }): string {
201 const params = new URLSearchParams();
202 if (by) params.set("by", by);
203 if (action) params.set("action", action);
204 if (before) params.set("before", before);
205 const query = params.toString();
206 return query ? `/audit?${query}` : "/audit";
207}