pr_01m47d15m3e54sn21z27rpy5n9/apps/sudo/app/components/billing.tsx

484 lines20,791 bytesCodeBlame
1/**
2 * The billing sections shared by a workspace's page and an enterprise's:
3 * confirmations, terms, credit, the Stripe billing link, the ledger and the
4 * audit log. Plain forms; sudo ships no JavaScript.
5 */
6import { CreditCard, Gift, ScrollText, UserRound } from "lucide-react";
7import type { ReactNode } from "react";
8import { Link } from "react-router";
9
10import type { AdminAction, AdminOwner, BillingLink, LedgerEntry, Terms } from "@g1t/contracts";
11
12import { Avatar, Badge, Button, EmptyState, Field, Input, Notice, Section, Select, Textarea, When } from "~/components/ui";
13import { dollarsField, usd } from "~/lib/money";
14import type { Review, SectionError } from "~/lib/review";
15
16export function Hidden({ values }: { values: Record<string, string> }) {
17 return (
18 <>
19 {Object.entries(values).map(([name, value]) => (
20 <input key={name} type="hidden" name={name} value={value} />
21 ))}
22 </>
23 );
24}
25
26export function Figure({ label, value, hint }: { label: string; value: string; hint?: ReactNode }) {
27 return (
28 <div className="rounded-lg border border-line bg-surface px-4 py-3">
29 <p className="text-xs text-muted">{label}</p>
30 <p className="tabular mt-1 text-lg font-semibold tracking-tight">{value}</p>
31 {hint && <p className="mt-0.5 text-xs text-faint">{hint}</p>}
32 </div>
33 );
34}
35
36/** Owners' usernames, each with their email beneath (and on hover). */
37export function Owners({ owners, compact = false }: { owners: AdminOwner[]; compact?: boolean }) {
38 if (owners.length === 0) return <span className="text-faint">No owner</span>;
39 if (compact) {
40 return (
41 <span className="flex flex-col gap-0.5">
42 {owners.map((owner) => (
43 <span key={owner.username} title={owner.email ?? "No email"} className="min-w-0 truncate">
44 <span className="font-mono text-fg-soft">{owner.username}</span>
45 {owner.email && <span className="block truncate text-xs text-faint">{owner.email}</span>}
46 </span>
47 ))}
48 </span>
49 );
50 }
51 return (
52 <ul className="flex flex-wrap gap-2">
53 {owners.map((owner) => (
54 <li key={owner.username} title={owner.email ?? "No email"} className="inline-flex items-center gap-1.5 rounded-md border border-line bg-bg px-2 py-1 text-xs">
55 <Avatar name={owner.username} size={14} square={false} />
56 <span className="font-mono">{owner.username}</span>
57 {owner.email && <span className="text-faint">{owner.email}</span>}
58 </li>
59 ))}
60 </ul>
61 );
62}
63
64// --- Confirmation ------------------------------------------------------------
65
66function describeTerms(terms: Terms): [string, string][] {
67 return [
68 ["Terms", terms.kind === "custom" ? "Custom" : terms.kind === "comped" ? "Comped" : "Standard"],
69 ["Discount", terms.kind === "custom" ? `${terms.discountPercent}%` : "—"],
70 ["Limit", terms.ceilingMicros == null ? "By trust" : usd(terms.ceilingMicros)],
71 ["Until", terms.until ? terms.until.slice(0, 10) : "No end"],
72 ["Note", terms.note || "—"],
73 ];
74}
75
76/** Where a confirmed change lands, when its result is shown in place. */
77const RESULT_ANCHOR: Partial<Record<Review["intent"], string>> = { "billing-link": "billing-link", invoice: "invoices" };
78
79export function ReviewPanel({ review, pathname }: { review: Review; pathname: string }) {
80 let title: string;
81 let body: ReactNode;
82 let danger = false;
83 let confirm = "Confirm";
84 if (review.intent === "terms") {
85 const before = describeTerms(review.before);
86 const after = describeTerms(review.after);
87 title = "Confirm the new terms";
88 danger = review.after.kind === "comped";
89 body = (
90 <>
91 <div className="overflow-x-auto">
92 <table className="w-full text-sm">
93 <thead>
94 <tr className="text-left text-xs text-muted">
95 <th className="py-1.5 pr-4 font-medium" />
96 <th className="py-1.5 pr-4 font-medium">Now</th>
97 <th className="py-1.5 font-medium">After</th>
98 </tr>
99 </thead>
100 <tbody>
101 {after.map(([label, value], index) => (
102 <tr key={label} className="border-t border-line align-top">
103 <td className="py-1.5 pr-4 text-muted">{label}</td>
104 <td className="py-1.5 pr-4 break-words text-faint">{before[index][1]}</td>
105 <td className={`py-1.5 break-words ${value !== before[index][1] ? "font-medium text-fg" : "text-muted"}`}>{value}</td>
106 </tr>
107 ))}
108 </tbody>
109 </table>
110 </div>
111 {review.after.kind === "comped" && (
112 <p className="mt-3 text-sm text-warn">
113 Comped: nothing will be charged{review.after.until ? ` until ${review.after.until.slice(0, 10)}` : ""}. Usage is still recorded
114 at cost.
115 </p>
116 )}
117 </>
118 );
119 } else if (review.intent === "attach") {
120 title = `Bill ${review.workspace} to ${review.targetName}?`;
121 body = (
122 <p className="text-sm text-muted">
123 From now on <span className="font-mono text-fg">{review.workspace}</span>'s usage is billed to{" "}
124 <span className="text-fg">{review.targetName}</span> and counts against its limit and terms, not its own.
125 </p>
126 );
127 } else if (review.intent === "detach") {
128 title = `Move ${review.workspace} off ${review.from}?`;
129 danger = true;
130 body = (
131 <p className="text-sm text-muted">
132 <span className="font-mono text-fg">{review.workspace}</span> goes back to paying for itself, on its own terms and the limit
133 its trust gives it. It may stop at once if its own limit is lower than what it owes.
134 </p>
135 );
136 } else if (review.intent === "billing-email") {
137 title = `Send ${review.name}'s invoices to ${review.after}?`;
138 body = (
139 <p className="text-sm text-muted">
140 Stripe emails its invoices to <span className="font-mono text-fg">{review.after}</span>
141 {review.before ? (
142 <>
143 {" "}
144 instead of <span className="font-mono">{review.before}</span>
145 </>
146 ) : null}
147 , from the next invoice on.{!review.before && " This also sets the enterprise up as a customer on Stripe."}
148 </p>
149 );
150 } else if (review.intent === "invoice") {
151 title = `Invoice ${review.name} now?`;
152 confirm = "Send the invoice";
153 body = (
154 <ul className="list-disc space-y-1 pl-5 text-sm text-muted">
155 <li>Makes one Stripe invoice, with a line for each of its {review.workspaces} workspace{review.workspaces === 1 ? "" : "s"} for what it owes now.</li>
156 <li>Net 30: due in 30 days.</li>
157 <li>
158 Stripe emails it to <span className="font-mono text-fg">{review.email ?? "the invoice email (none set yet)"}</span>, with a link to
159 pay on Stripe's page.
160 </li>
161 </ul>
162 );
163 } else {
164 title = `Make a Stripe billing link for ${review.workspace}?`;
165 confirm = "Make the link";
166 body = (
167 <p className="text-sm text-muted">
168 Opens a one-time session on Stripe's billing page for <span className="font-mono text-fg">{review.workspace}</span>'s
169 customer, where they update their card and see their invoices. Anyone with the link can use it until it expires, so send it
170 only to the workspace's owner. Making it is recorded with your email.
171 </p>
172 );
173 }
174 return (
175 <section id="review" className={`scroll-mt-20 rounded-lg border p-4 sm:p-5 ${danger ? "border-warn/40 bg-warn/5" : "border-merged/40 bg-merged/5"}`}>
176 <h2 className="font-semibold tracking-tight">{title}</h2>
177 <div className="mt-3">{body}</div>
178 <form method="post" action={`${pathname}#${RESULT_ANCHOR[review.intent] ?? "top"}`} className="mt-4 flex flex-wrap items-center gap-2">
179 <Hidden values={review.fields} />
180 <input type="hidden" name="intent" value={review.intent} />
181 <input type="hidden" name="confirm" value="yes" />
182 <Button type="submit" variant={danger ? "danger" : "lavender"}>
183 {confirm}
184 </Button>
185 <Link to={pathname} className="px-2 text-sm text-muted hover:text-fg">
186 Cancel
187 </Link>
188 </form>
189 </section>
190 );
191}
192
193// --- Terms -------------------------------------------------------------------
194
195const KINDS: { value: Terms["kind"]; title: string; text: string }[] = [
196 { value: "standard", title: "Standard", text: "Published prices; the limit comes from trust." },
197 { value: "comped", title: "Comped", text: "Nothing charged. Usage still recorded at cost." },
198 { value: "custom", title: "Custom", text: "A discount, a custom limit, or both." },
199];
200
201export function TermsForm({ terms, pathname, error }: { terms: Terms; pathname: string; error: SectionError }) {
202 const values = error?.values;
203 const kind = values?.kind ?? terms.kind;
204 return (
205 <Section
206 id="terms"
207 title="Terms"
208 description={
209 terms.setBy ? (
210 <>
211 Set by <span className="font-mono">{terms.setBy}</span> on <When at={terms.setAt} />
212 {terms.note && <> · “{terms.note}”</>}
213 </>
214 ) : (
215 "Standard, as everyone starts."
216 )
217 }
218 >
219 <form method="post" action={`${pathname}#review`} className="space-y-4">
220 <input type="hidden" name="intent" value="terms" />
221 {error && <Notice tone="error">{error.error}</Notice>}
222 <fieldset>
223 <legend className="mb-1.5 text-sm font-medium text-muted">Kind</legend>
224 <div className="grid gap-2 sm:grid-cols-3">
225 {KINDS.map((option) => (
226 <label
227 key={option.value}
228 className="flex cursor-pointer gap-2.5 rounded-md border border-line bg-bg p-3 transition-colors hover:border-line-strong has-checked:border-merged/60 has-checked:bg-merged/8"
229 >
230 <input type="radio" name="kind" value={option.value} defaultChecked={kind === option.value} className="mt-0.5" required />
231 <span>
232 <span className="block text-sm font-medium">{option.title}</span>
233 <span className="mt-0.5 block text-xs text-muted">{option.text}</span>
234 </span>
235 </label>
236 ))}
237 </div>
238 </fieldset>
239 <div className="grid gap-4 sm:grid-cols-3">
240 <Field label="Discount %" hint="Custom only.">
241 <Input name="discount" inputMode="numeric" pattern="\d{1,3}" placeholder="0" defaultValue={values?.discount ?? (terms.discountPercent ? String(terms.discountPercent) : "")} />
242 </Field>
243 <Field label="Limit $" hint="Unpaid usage allowed. Blank: trust decides.">
244 <Input name="ceiling" inputMode="decimal" placeholder="By trust" defaultValue={values?.ceiling ?? dollarsField(terms.ceilingMicros)} />
245 </Field>
246 <Field label="Until" hint="Blank: no end. UTC.">
247 <Input type="date" name="until" defaultValue={values?.until ?? (terms.until ? terms.until.slice(0, 10) : "")} />
248 </Field>
249 </div>
250 <Field label="Note" hint="Required. Why, for whoever looks next.">
251 <Textarea name="note" rows={2} required maxLength={500} defaultValue={values?.note ?? ""} placeholder="e.g. Design partner through launch" />
252 </Field>
253 <div className="flex justify-end">
254 <Button type="submit">Review terms</Button>
255 </div>
256 </form>
257 </Section>
258 );
259}
260
261// --- Credit -------------------------------------------------------------------
262
263export function CreditForm({ workspaces, pathname, error }: { workspaces: string[]; pathname: string; error: SectionError }) {
264 const values = error?.values;
265 const single = workspaces.length === 1 ? workspaces[0] : null;
266 return (
267 <Section id="credit" title="Issue credit" description="A refund or goodwill. Added to the workspace's balance at once.">
268 {workspaces.length === 0 ? (
269 <p className="text-sm text-muted">Add a workspace first: credit goes to a workspace.</p>
270 ) : (
271 <form method="post" action={`${pathname}#credit`} className="space-y-4">
272 <input type="hidden" name="intent" value="credit" />
273 {error && <Notice tone="error">{error.error}</Notice>}
274 {single ? (
275 <input type="hidden" name="workspace" value={single} />
276 ) : (
277 <Field label="Workspace">
278 <Select name="workspace" required defaultValue={values?.workspace ?? ""}>
279 <option value="" disabled>
280 Choose a workspace
281 </option>
282 {workspaces.map((slug) => (
283 <option key={slug} value={slug}>
284 {slug}
285 </option>
286 ))}
287 </Select>
288 </Field>
289 )}
290 <Field label="Amount $" hint="Up to $10,000 at a time.">
291 <Input name="amount" inputMode="decimal" required placeholder="25.00" defaultValue={values?.amount ?? ""} />
292 </Field>
293 <Field label="Note" hint="Required. Shown on the workspace's statement.">
294 <Textarea name="note" rows={2} required maxLength={500} placeholder="e.g. Refund for the failed runs on Oct 2" defaultValue={values?.note ?? ""} />
295 </Field>
296 <Field
297 label="Confirm"
298 hint={
299 <>
300 Type the workspace's slug{single && <> (<span className="font-mono text-muted">{single}</span>)</>} to issue it.
301 </>
302 }
303 >
304 <Input name="confirmation" required placeholder={single ?? "workspace-slug"} className="font-mono" />
305 </Field>
306 <div className="flex justify-end">
307 <Button type="submit" variant="lavender">
308 <Gift size={14} />
309 Issue credit
310 </Button>
311 </div>
312 </form>
313 )}
314 </Section>
315 );
316}
317
318// --- Stripe billing link -----------------------------------------------------
319
320/**
321 * Card details, invoices and receipts live on Stripe's own billing page.
322 * sudo never shows a card field: staff send the customer a link instead.
323 */
324export function BillingLinkSection({
325 link,
326 pathname,
327 error,
328}: {
329 link: BillingLink | null;
330 pathname: string;
331 error: SectionError;
332}) {
333 return (
334 <Section
335 id="billing-link"
336 title="Stripe billing page"
337 description="Where the customer updates their card and sees invoices. g1t never takes card numbers."
338 >
339 {error && (
340 <div className="mb-4">
341 <Notice tone="error">{error.error}</Notice>
342 </div>
343 )}
344 {link ? (
345 <div className="space-y-4">
346 <Notice tone="info">Send this to the customer. g1t never takes card numbers; they enter them on Stripe.</Notice>
347 <Field label="One-time link" hint={link.expiresNote}>
348 <Input readOnly value={link.portalUrl} className="font-mono text-xs" aria-label="One-time Stripe billing link" />
349 </Field>
350 {link.loginUrl && (
351 <Field label="Permanent sign-in page" hint={`The customer signs in with ${link.customerEmail ?? "the email Stripe has for them"}.`}>
352 <Input readOnly value={link.loginUrl} className="font-mono text-xs" aria-label="Stripe billing sign-in page" />
353 </Field>
354 )}
355 {!link.loginUrl && link.customerEmail && <p className="text-xs text-faint">Stripe has {link.customerEmail} for this customer.</p>}
356 </div>
357 ) : (
358 <form method="post" action={`${pathname}#review`} className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
359 <input type="hidden" name="intent" value="billing-link" />
360 <p className="text-sm text-muted">
361 Never take card details over the phone or by email. Make a link to Stripe's billing page and send it to the owner.
362 </p>
363 <Button type="submit" variant="quiet" className="shrink-0">
364 <CreditCard size={14} />
365 Make a link
366 </Button>
367 </form>
368 )}
369 </Section>
370 );
371}
372
373// --- Ledger and audit ---------------------------------------------------------
374
375const ENTRY_KIND: Record<string, string> = { top_up: "Top-up", usage: "Usage", credit: "Credit" };
376
377export function LedgerSection({
378 ledger,
379 showWorkspace = false,
380 description = "Recent lines of the statement, newest first.",
381}: {
382 ledger: LedgerEntry[];
383 showWorkspace?: boolean;
384 description?: ReactNode;
385}) {
386 return (
387 <Section title="Ledger" description={description}>
388 {ledger.length === 0 ? (
389 <EmptyState title="Nothing yet" />
390 ) : (
391 <div className="-mx-4 -my-4 overflow-x-auto sm:-mx-5 sm:-my-5">
392 <table className="w-full min-w-[36rem] text-sm">
393 <thead>
394 <tr className="border-b border-line text-left text-xs text-muted">
395 <th className="px-4 py-2 font-medium sm:pl-5">When</th>
396 <th className="px-4 py-2 font-medium">What</th>
397 <th className="px-4 py-2 text-right font-medium sm:pr-5">Amount</th>
398 </tr>
399 </thead>
400 <tbody>
401 {ledger.map((entry) => (
402 <tr key={entry.id} className="border-b border-line align-top last:border-0">
403 <td className="px-4 py-2.5 text-xs whitespace-nowrap text-muted sm:pl-5">
404 <When at={entry.createdAt} time />
405 </td>
406 <td className="px-4 py-2.5">
407 <div className="flex flex-wrap items-center gap-1.5">
408 <Badge tone={entry.amountMicros > 0 ? "mint" : "plain"}>{ENTRY_KIND[entry.kind] ?? entry.kind}</Badge>
409 {showWorkspace && entry.workspace && (
410 <Link to={`/workspaces/${encodeURIComponent(entry.workspace)}`} className="font-mono text-xs text-merged hover:underline">
411 {entry.workspace}
412 </Link>
413 )}
414 <span className="break-words">{entry.description}</span>
415 </div>
416 <p className="mt-0.5 font-mono text-xs text-faint">
417 {[
418 entry.repo && (entry.number != null ? `${entry.repo}#${entry.number}` : entry.repo),
419 entry.task,
420 entry.model,
421 entry.billedTo === "workspace" ? "own provider" : null,
422 entry.createdBy && `by ${entry.createdBy}`,
423 ]
424 .filter(Boolean)
425 .join(" · ")}
426 </p>
427 </td>
428 <td className={`tabular px-4 py-2.5 text-right whitespace-nowrap sm:pr-5 ${entry.amountMicros > 0 ? "text-accent" : "text-fg-soft"}`}>
429 {usd(entry.amountMicros, { signed: true })}
430 </td>
431 </tr>
432 ))}
433 </tbody>
434 </table>
435 </div>
436 )}
437 </Section>
438 );
439}
440
441const ACTION: Record<string, string> = {
442 terms: "Terms changed",
443 create: "Enterprise created",
444 attach: "Workspace added",
445 detach: "Workspace removed",
446 credit: "Credit issued",
447 billing_link: "Billing link made",
448 billing_email: "Invoice email set",
449 invoice: "Invoice sent",
450 dispute: "Payment disputed",
451 stripe: "Stripe",
452 webhook: "Webhook registered",
453};
454
455export function AuditSection({ audit, description = "Every change made in sudo, and by whom." }: { audit: AdminAction[]; description?: ReactNode }) {
456 return (
457 <Section title="Audit log" description={description}>
458 {audit.length === 0 ? (
459 <p className="flex items-center gap-2 text-sm text-muted">
460 <ScrollText size={14} />
461 No changes yet.
462 </p>
463 ) : (
464 <ol className="space-y-3">
465 {audit.map((entry) => (
466 <li key={entry.id} className="border-l-2 border-merged/40 pl-3">
467 <p className="flex flex-wrap items-center gap-x-2 text-sm">
468 <span className="font-medium text-merged">{ACTION[entry.action] ?? entry.action}</span>
469 <span className="text-xs text-faint">
470 <When at={entry.createdAt} time />
471 </span>
472 </p>
473 {entry.detail && <p className="mt-0.5 text-sm break-words text-fg-soft">{entry.detail}</p>}
474 <p className="mt-0.5 flex items-center gap-1 font-mono text-xs text-faint">
475 <UserRound size={11} />
476 {entry.by}
477 </p>
478 </li>
479 ))}
480 </ol>
481 )}
482 </Section>
483 );
484}