Skip to content
410 linesCodeBlameRaw
1/**
2 * How the billing pages speak of money, read their forms and word a
3 * workspace's alerts. Pure, so it can be tested.
4 */
5
6import type { CreditGrant, Entitlements, FeatureState, Limit, LimitRequest, MeterUsage, PriceBook, Usage, UsageAlert } from "@g1t/contracts";
7
8import { MICROS_PER_DOLLAR, money, wholeDollars } from "./money.ts";
9
10/** Prices on g1t exclude tax; Stripe adds it at checkout from the billing address. */
11export const PLUS_TAX = "plus tax where it applies";
12
13/** A card processing fee: Stripe's percent (in millionths) and fixed fee. */
14export type CardFee = { on: boolean; percentMicros: number; fixedCents: number };
15
16/**
17 * The card fee as the price book lists it (`card_fee_percent` and
18 * `card_fee_fixed`), or null when it does not.
19 */
20export function cardFeeOf(book: PriceBook | null | undefined): CardFee | null {
21 const percent = book?.prices.find((price) => price.meter === "card_fee_percent");
22 const fixed = book?.prices.find((price) => price.meter === "card_fee_fixed");
23 if (!percent || !fixed) return null;
24 return { on: true, percentMicros: percent.priceMicros, fixedCents: Math.max(0, Math.round(fixed.priceMicros / 10_000)) };
25}
26
27/**
28 * The card processing fee on a card payment of `cents`, as billing works it
29 * out (`tax::card_fee_cents`): Stripe's percent and fixed fee grossed up, so
30 * what is left after Stripe's fee is the amount, rounded up to the cent.
31 * 0 when the fee is off.
32 */
33export function cardFeeCents(cents: number, fee: CardFee | null | undefined): number {
34 if (!fee?.on || !(cents > 0)) return 0;
35 const rate = fee.percentMicros / MICROS_PER_DOLLAR;
36 if (!(rate >= 0 && rate < 0.5)) return 0;
37 return Math.max(0, Math.ceil((cents + fee.fixedCents) / (1 - rate)) - cents);
38}
39
40/** "Card processing fee $1.06, plus tax where it applies", as shown before paying. */
41export function feeAndTax(feeCents: number): string {
42 return feeCents > 0 ? `Card processing fee ${money(feeCents * 10_000)}, ${PLUS_TAX}` : `Plus tax where it applies`;
43}
44
45/** A form's dollar amount as micros, or null when it is empty or not a number. */
46export function readDollars(value: FormDataEntryValue | null | undefined): number | null {
47 const text = String(value ?? "").replace(/[$,\s]/g, "");
48 if (!text) return null;
49 const amount = Number(text);
50 if (!Number.isFinite(amount)) return null;
51 return Math.round(amount * MICROS_PER_DOLLAR);
52}
53
54export type Parsed<T> = { ok: true; value: T } | { ok: false; error: string };
55
56/** The smallest prepayment, the most by card, and where bank transfer starts, in dollars. */
57export const PREPAY = { min: 25, maxCard: 10_000, bankFrom: 1_000, presets: [100, 500, 1_000] } as const;
58
59/** A prepayment: a preset or a custom amount, by card or bank transfer. */
60export function parsePrepay(form: {
61 amount?: FormDataEntryValue | null;
62 custom?: FormDataEntryValue | null;
63 method?: FormDataEntryValue | null;
64}): Parsed<{ amountCents: number; method: "card" | "bank_transfer" }> {
65 const micros = readDollars(form.custom) ?? readDollars(form.amount);
66 const method = String(form.method ?? "card") === "bank_transfer" ? "bank_transfer" : "card";
67 if (micros == null) return { ok: false, error: "Choose an amount to prepay." };
68 const amount = micros / MICROS_PER_DOLLAR;
69 if (amount < PREPAY.min) return { ok: false, error: `The smallest prepayment is $${PREPAY.min}.` };
70 if (method === "card" && amount > PREPAY.maxCard)
71 return { ok: false, error: `By card, the most is $${PREPAY.maxCard.toLocaleString("en-US")}; pay more by bank transfer.` };
72 if (method === "bank_transfer" && amount < PREPAY.bankFrom)
73 return { ok: false, error: `Bank transfer is for $${PREPAY.bankFrom.toLocaleString("en-US")} or more.` };
74 return { ok: true, value: { amountCents: Math.round(amount * 100), method } };
75}
76
77/** A request for a higher limit, or for help with usage past what was meant. */
78export function parseLimitRequest(form: {
79 kind?: FormDataEntryValue | null;
80 amount?: FormDataEntryValue | null;
81 reason?: FormDataEntryValue | null;
82 expected?: FormDataEntryValue | null;
83}): Parsed<{ kind: "limit" | "overage"; amountMicros: number; reason: string; expectedMonthlyMicros: number }> {
84 const kind = String(form.kind ?? "limit") === "overage" ? "overage" : "limit";
85 const reason = String(form.reason ?? "").trim();
86 const amount = readDollars(form.amount);
87 const expected = readDollars(form.expected);
88 if (!reason)
89 return {
90 ok: false,
91 error: kind === "limit" ? "Say what the higher limit is for." : "Say what happened, so we can look at it.",
92 };
93 if (kind === "limit") {
94 if (amount == null || amount <= 0) return { ok: false, error: "Say the limit you need, in dollars." };
95 if (expected == null || expected < 0) return { ok: false, error: "Say what you expect to spend in a month." };
96 }
97 return {
98 ok: true,
99 value: {
100 kind,
101 amountMicros: Math.max(0, amount ?? 0),
102 reason: reason.slice(0, 2000),
103 expectedMonthlyMicros: Math.max(0, expected ?? 0),
104 },
105 };
106}
107
108/**
109 * A spend limit as owners set it: automatic, fixed at an amount, as high as
110 * is available, or the one-time raise (an amount, or blank for as high as
111 * it goes, which the page fills in from the limit).
112 */
113export function parseSpendLimit(form: {
114 mode?: FormDataEntryValue | null;
115 limit?: FormDataEntryValue | null;
116}): Parsed<{ micros: number | null; useFull: boolean; raiseOnce: boolean }> {
117 const mode = String(form.mode ?? "automatic");
118 if (mode === "full") return { ok: true, value: { micros: null, useFull: true, raiseOnce: false } };
119 if (mode !== "fixed" && mode !== "raise") return { ok: true, value: { micros: null, useFull: false, raiseOnce: false } };
120 const micros = readDollars(form.limit);
121 if (mode === "raise" && micros == null) return { ok: true, value: { micros: null, useFull: false, raiseOnce: true } };
122 if (micros == null || micros < MICROS_PER_DOLLAR) return { ok: false, error: "A spend limit is a dollar amount, $1 or more." };
123 return { ok: true, value: { micros, useFull: false, raiseOnce: mode === "raise" } };
124}
125
126/**
127 * How far owners may set their spend limit themselves: up to the highest
128 * ceiling the workspace has had plus what is prepaid, and, once, up to
129 * twice that highest ceiling. Null `selfServeMicros` means no ceiling
130 * (g1t's own, or staff set it).
131 */
132export type SpendRange = { selfServeMicros: number | null; raiseOnceMicros: number | null; raisedAt: string | null };
133
134export function spendRange(
135 limit: Pick<Limit, "availableMicros" | "ceilingMicros" | "raiseOnceMicros" | "raisedAt">,
136): SpendRange {
137 const selfServe = limit.availableMicros !== undefined ? limit.availableMicros : limit.ceilingMicros;
138 const once = limit.raiseOnceMicros ?? null;
139 return {
140 selfServeMicros: selfServe ?? null,
141 // The raise only matters when it goes further than owners can already.
142 raiseOnceMicros: once != null && (selfServe == null || once > selfServe) ? once : null,
143 raisedAt: limit.raisedAt ?? null,
144 };
145}
146
147/**
148 * What setting the spend limit to `micros` takes, as billing decides it:
149 * nothing (`self`), the one-time raise (`raise`), or a request to g1t
150 * (`ask`).
151 */
152export function spendPath(micros: number, range: SpendRange): "self" | "raise" | "ask" {
153 if (range.selfServeMicros == null || micros <= range.selfServeMicros) return "self";
154 if (range.raiseOnceMicros != null && micros <= range.raiseOnceMicros) return "raise";
155 return "ask";
156}
157
158/** Where the workspace stands with the g1t plan, for the plan card. */
159export type PlanStatus = {
160 kind: "free" | "trial" | "paid" | "canceling" | "past_due" | "comped" | "enterprise";
161 label: string;
162};
163
164export function planStatus(
165 plan: Pick<FeatureState, "on" | "included" | "subscription"> | null | undefined,
166 entitlements: Pick<Entitlements, "plan" | "trialMicrosLeft" | "trialVerified" | "firstMonth"> | null | undefined,
167): PlanStatus {
168 if (entitlements?.plan === "internal") return { kind: "comped", label: "100% discount from g1t" };
169 if (entitlements?.plan === "enterprise") return { kind: "enterprise", label: "Paid by an enterprise" };
170 if (plan?.included) return { kind: "comped", label: "Included by g1t" };
171 const subscription = plan?.subscription;
172 if (subscription?.status === "past_due") return { kind: "past_due", label: "Payment failed" };
173 if (plan?.on && subscription?.status === "canceling") return { kind: "canceling", label: "Ends at the end of the period" };
174 if ((plan?.on && subscription) || entitlements?.plan === "paid") {
175 return { kind: "paid", label: entitlements?.firstMonth ? "On the g1t plan, first month" : "On the g1t plan" };
176 }
177 if (entitlements?.trialVerified && entitlements.trialMicrosLeft > 0) return { kind: "trial", label: "Free, on the trial" };
178 return { kind: "free", label: "Free" };
179}
180
181/** Meters only the plan runs: a free workspace never builds, serves apps or adds custom domains. */
182const PLAN_ONLY_METERS = new Set(["builds", "requests", "domains"]);
183
184/**
185 * The lines of "This month's usage": every meter on the plan, so it reads
186 * the same each month; without it, only what a free workspace can use,
187 * plus anything that was used anyway (from before the plan ended).
188 */
189export function shownMeters(meters: MeterUsage[], onPlan: boolean): MeterUsage[] {
190 return meters.filter((meter) => onPlan || !PLAN_ONLY_METERS.has(meter.key) || meter.micros > 0);
191}
192
193/** `1 GB`, `500 MB`: storage as it is priced, in powers of ten. */
194export function gigabytes(bytes: number): string {
195 if (bytes >= 1e9) return `${Math.round((bytes / 1e9) * 10) / 10} GB`;
196 return `${Math.round(bytes / 1e6)} MB`;
197}
198
199/** A share from 0 to 1 of `used` against `of`, for a meter. */
200export function share(used: number, of: number | null | undefined): number {
201 if (!of || of <= 0) return 0;
202 return Math.min(1, Math.max(0, used / of));
203}
204
205/** Where the trial stands after a card check, in a sentence for the owner. */
206export function cardCheckResult(
207 entitlements: Pick<Entitlements, "trialVerified" | "trialMicrosLeft">,
208 trialMicros: number,
209): string {
210 if (!entitlements.trialVerified) return "The card check did not finish. Try again; the card is never charged.";
211 if (entitlements.trialMicrosLeft > 0) return `Card checked. Your ${wholeDollars(entitlements.trialMicrosLeft)} trial is ready to use.`;
212 return `Card checked, but no trial started. The ${wholeDollars(trialMicros)} trial needs a credit or debit card that has not started one before, and comes from a monthly pool that can run out. Prepaid cards can still pay for the plan.`;
213}
214
215const METERS: Record<string, string> = {
216 included: "the plan's included usage",
217 spend_limit: "your spend limit",
218 ceiling: "what g1t lets go unpaid",
219};
220
221/** One alert as a sentence: "90% of the plan's included usage: $9.00 of $10.00." */
222export function alertText(alert: UsageAlert): string {
223 const what = METERS[alert.meter] ?? alert.meter.replace(/_/g, " ");
224 const reached = alert.level >= 100 ? `All of ${what}` : `${alert.level}% of ${what}`;
225 return `${reached}: ${money(alert.usedMicros)} of ${money(alert.limitMicros)}.`;
226}
227
228/** How loud an alert is. */
229export function alertTone(level: number): "ok" | "warning" | "stopped" {
230 if (level >= 100) return "stopped";
231 return level >= 75 ? "warning" : "ok";
232}
233
234/** Whether the workspace needs an owner's eye now: compute paused, a spike waiting, or an alert at 90% or more. */
235export function needsAttention(entitlements: Pick<Entitlements, "paused" | "spike" | "alerts"> | null | undefined): boolean {
236 if (!entitlements) return false;
237 if (entitlements.paused) return true;
238 if (entitlements.spike && entitlements.spike.status !== "continued") return true;
239 return (entitlements.alerts ?? []).some((alert) => alert.level >= 90);
240}
241
242/** A request's state as the owner sees it. */
243export function requestStatus(request: LimitRequest): string {
244 if (request.status === "approved")
245 return request.decidedMicros != null ? `Approved at ${wholeDollars(request.decidedMicros)}` : "Approved";
246 if (request.status === "declined") return "Declined";
247 return "Waiting for an answer";
248}
249
250/** What each kind of work is called, and its colour, on Usage and the workspace's overview; the agent kinds are in older months. */
251export const USAGE_TASKS: Record<string, { label: string; color: string }> = {
252 implement: { label: "Making changes", color: "var(--color-merged)" },
253 review: { label: "Reviews", color: "var(--color-info)" },
254 revise: { label: "Revisions", color: "var(--color-warn)" },
255 update: { label: "Catching up", color: "var(--color-success)" },
256 plan: { label: "Planning", color: "#f0a6ca" },
257 /** Time on the workspace's own runners: its minutes, at $0. */
258 self_hosted: { label: "Self-hosted runners ($0)", color: "var(--color-line-strong)" },
259 other: { label: "Other", color: "var(--color-faint)" },
260};
261
262/** A kind of work's words and colour, or Other's. */
263export function usageTask(key: string): { label: string; color: string } {
264 return USAGE_TASKS[key] ?? USAGE_TASKS.other!;
265}
266
267/**
268 * Usage by kind of work with every kind that has no words of its own
269 * added into one Other, last, so Other is listed once.
270 */
271export function foldTasks<T extends { key: string; micros: number; runs: number }>(slices: T[]): T[] {
272 const known = slices.filter((slice) => slice.key !== "other" && slice.key in USAGE_TASKS);
273 const rest = slices.filter((slice) => !known.includes(slice));
274 if (rest.length === 0) return known;
275 const other = rest.reduce(
276 (sum, slice) => ({ ...sum, micros: sum.micros + slice.micros, runs: sum.runs + slice.runs }),
277 { ...rest[0]!, key: "other", micros: 0, runs: 0 },
278 );
279 return [...known, other];
280}
281
282/** The workspace's month at a glance, for the Usage card on its overview. */
283export type UsageGlance = {
284 /**
285 * `beta` while g1t charges nothing; `comped` when g1t or an enterprise
286 * pays; `plan` on the g1t plan; `trial` on trial credit; `forge` with
287 * neither, where only what runs no compute is open.
288 */
289 kind: "beta" | "comped" | "plan" | "trial" | "forge";
290 /** Charged this month, or used at cost while g1t is free. */
291 spentMicros: number;
292 /** What pays first, and how much of it is used: the plan's included usage, or the trial. */
293 credit: { label: string; usedMicros: number; ofMicros: number } | null;
294 /** Charged past what is included, and the spend limit if there is one; null when it does not apply. */
295 onDemand: { micros: number; limitMicros: number | null } | null;
296 /** What it went on, most first. */
297 lines: { key: string; label: string; micros: number; runs: number }[];
298};
299
300export function usageGlance(input: {
301 usage: Pick<Usage, "free" | "spentMicros" | "usedMicros" | "byTask" | "priceMicros">;
302 status: PlanStatus;
303 entitlements: Pick<Entitlements, "includedMicros" | "includedUsedMicros" | "trialMicrosLeft"> | null;
304 limit: Pick<Limit, "spentMicros" | "spendLimitMicros"> | null;
305 trialMicros: number;
306}): UsageGlance {
307 const { usage, status, entitlements, limit, trialMicros } = input;
308 const lines = [...usage.byTask]
309 .filter((slice) => slice.micros > 0)
310 .sort((a, b) => b.micros - a.micros)
311 .map((slice) => ({ key: slice.key, label: usageTask(slice.key).label, micros: slice.micros, runs: slice.runs }));
312 // Usage at price, the one figure every page shows.
313 const spentMicros = usage.free ? usage.usedMicros : (usage.priceMicros ?? usage.spentMicros);
314 const plain = { spentMicros, credit: null, onDemand: null, lines };
315 if (usage.free) return { kind: "beta", ...plain };
316 if (status.kind === "comped" || status.kind === "enterprise") return { kind: "comped", ...plain };
317 if (status.kind === "trial") {
318 const left = Math.max(0, entitlements?.trialMicrosLeft ?? 0);
319 const of = Math.max(trialMicros, left);
320 return { ...plain, kind: "trial", credit: { label: "Trial credit", usedMicros: of - left, ofMicros: of } };
321 }
322 if (status.kind === "free") return { kind: "forge", ...plain };
323 const included = entitlements?.includedMicros ?? 0;
324 const includedUsed = Math.min(entitlements?.includedUsedMicros ?? 0, included);
325 return {
326 ...plain,
327 kind: "plan",
328 credit: included > 0 ? { label: "Included usage", usedMicros: includedUsed, ofMicros: included } : null,
329 onDemand: {
330 micros: limit?.spentMicros ?? Math.max(0, spentMicros - includedUsed),
331 limitMicros: limit?.spendLimitMicros ?? null,
332 },
333 };
334}
335
336/** What a credit from g1t is for, as the Billing page names it. */
337export const CREDIT_KIND: Record<CreditGrant["kind"], string> = {
338 promotional: "Promotional",
339 goodwill: "Goodwill",
340 refund: "Refund",
341 purchased: "Purchased",
342};
343
344/** `Jan 5`, or `Jan 5, 2028` outside this year (UTC). */
345export function shortDay(at: string, now = new Date()): string {
346 const date = new Date(at);
347 const sameYear = date.getUTCFullYear() === now.getUTCFullYear();
348 return date.toLocaleDateString("en-US", { month: "short", day: "numeric", ...(sameYear ? {} : { year: "numeric" }), timeZone: "UTC" });
349}
350
351/**
352 * A credit from g1t in a line: `$25.00 credit, $12.40 left, expires Jan 5`;
353 * once it is spent, expired or withdrawn, says so.
354 */
355export function creditLine(grant: Pick<CreditGrant, "amountMicros" | "leftMicros" | "expiresAt" | "state">, now = new Date()): string {
356 const parts = [`${money(grant.amountMicros)} credit`];
357 if (grant.state === "open") {
358 parts.push(`${money(grant.leftMicros)} left`);
359 if (grant.expiresAt) parts.push(`expires ${shortDay(grant.expiresAt, now)}`);
360 } else {
361 parts.push(grant.state === "used" ? "all used" : grant.state === "expired" ? "expired" : "withdrawn");
362 }
363 return parts.join(", ");
364}
365
366/** The budget's alerts form: the levels ticked, whether usage pauses, and a webhook. */
367export function parseBudgetAlerts(form: {
368 alerts: FormDataEntryValue[];
369 pause?: FormDataEntryValue | null;
370 webhook?: FormDataEntryValue | null;
371}): Parsed<{ alerts: number[]; pauseAtLimit: boolean; webhook: string | null }> {
372 const alerts = [...new Set(form.alerts.map((a) => Number(a)).filter((a) => [50, 75, 90, 100].includes(a)))].sort((a, b) => b - a);
373 const webhook = String(form.webhook ?? "").trim();
374 if (webhook && !/^https:\/\/[^\s/]+\.[^\s]+$/.test(webhook)) return { ok: false, error: "The webhook is an https:// address." };
375 return { ok: true, value: { alerts, pauseAtLimit: form.pause === "on", webhook: webhook || null } };
376}
377
378/** The invoice details form, each field as given (empty clears it on Stripe). */
379export function parseInvoiceDetails(form: FormData): Parsed<{
380 email: string;
381 name: string;
382 address: { line1: string; line2: string; city: string; state: string; postalCode: string; country: string };
383 taxIdType: string;
384 taxId: string;
385 poNumber: string;
386 language: string;
387}> {
388 const text = (name: string) => String(form.get(name) ?? "").trim();
389 const email = text("email");
390 if (email && !/^[^\s@]+@[^\s@]+$/.test(email)) return { ok: false, error: "That is not an email address." };
391 const country = text("country").toUpperCase();
392 if (country && !/^[A-Z]{2}$/.test(country)) return { ok: false, error: "The country is two letters, such as US or DE." };
393 // Stripe Tax places a US customer by ZIP code: without it, tax cannot be worked out.
394 if (country === "US" && !text("postalCode")) return { ok: false, error: "Add the ZIP code: in the US, tax is worked out from it." };
395 const taxIdType = text("taxIdType");
396 const taxId = text("taxId");
397 if (Boolean(taxIdType) !== Boolean(taxId)) return { ok: false, error: "Give the tax ID's kind and its number together." };
398 return {
399 ok: true,
400 value: {
401 email,
402 name: text("name"),
403 address: { line1: text("line1"), line2: text("line2"), city: text("city"), state: text("state"), postalCode: text("postalCode"), country },
404 taxIdType,
405 taxId,
406 poNumber: text("poNumber"),
407 language: text("language"),
408 },
409 };
410}