Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

685 linesCodeBlameRaw
1import { ArrowLeft, Building2, LogOut } from "lucide-react";
2import type { ReactNode } from "react";
3import { data, Link, useLocation } from "react-router";
4
5import { type AccountSummary, type AdminAction, type Entitlements, type Limit, type Overage, type Terms, httpStatus } from "@g1t/contracts";
6
7import type { Route } from "./+types/workspace";
8import {
9 AllowancesForm,
10 AuditSection,
11 BillingLinkSection,
12 CreditForm,
13 CreditsSection,
14 Figure,
15 LedgerSection,
16 Owners,
17 PaymentForm,
18 ResetBillingForm,
19 ReviewPanel,
20 TermsForm,
21} from "~/components/billing";
22import { MonthsChart } from "~/components/charts";
23import { SalesSection, StageBadge, WorkspaceInvoicesSection } from "~/components/sales";
24import { WorkspaceTestDetachSection } from "~/components/test-detach";
25import {
26 Avatar,
27 Badge,
28 Button,
29 EmptyState,
30 ExposureBar,
31 Field,
32 Input,
33 Notice,
34 Section,
35 Select,
36 StateBadge,
37 TermsBadge,
38 Textarea,
39 TrustBadge,
40 When,
41 trustAbout,
42} from "~/components/ui";
43import { type Subject, billingAction } from "~/lib/billing-actions.server";
44import { ComplimentarySection } from "~/components/complimentary";
45import { SsoSection } from "~/components/sso";
46import { parseSlug, text } from "~/lib/forms";
47import { usd } from "~/lib/money";
48import { type ActionData, DONE, type SectionError, doneKey } from "~/lib/review";
49import { SALES_INTENTS, salesAction } from "~/lib/sales-actions.server";
50import { goodwillWarning, spikeLabel } from "~/lib/pricing";
51import { admin, entitlements as entitlementsOf, identity, priceBook } from "~/lib/services.server";
52import { settle } from "~/lib/settle";
53import { requireStaff } from "~/lib/staff";
54import { WORKSPACE_DETACH_INTENT, type WorkspaceDetachData, workspaceDetachAction } from "~/lib/test-detach.server";
55import { fullDiscount } from "~/lib/terms";
56import type { Enterprise } from "~/lib/workspaces";
57
58export const meta: Route.MetaFunction = ({ loaderData }) => [
59 { title: `${loaderData?.name ?? "Workspace"} · sudo` },
60 { name: "robots", content: "noindex, nofollow" },
61];
62
63/** Whether an audit line is about `slug`, in an enterprise's log. */
64function mentions(action: AdminAction, slug: string): boolean {
65 // A slug is letters, digits and hyphens, none special in a pattern.
66 return new RegExp(`(^|[^a-z0-9-])${slug}($|[^a-z0-9-])`).test(action.detail.toLowerCase());
67}
68
69async function load(raw: string) {
70 const parsed = parseSlug(raw);
71 if (!parsed.ok) throw data("That is not a workspace slug.", { status: 404 });
72 const slug = parsed.value;
73 const [person, result] = await Promise.all([identity.workspace(slug), admin.account(slug)]);
74 if (!result.ok) throw data(result.error.message, { status: httpStatus(result.error) });
75 const detail = result.value;
76 const { account } = detail.summary;
77 const billedTo: Enterprise | null = account.kind === "enterprise" ? { id: account.id, name: account.name } : null;
78 const known = person != null || billedTo != null || account.createdAt !== "" || detail.ledger.length > 0 || detail.audit.length > 0;
79 if (!known) throw data(`There is no workspace called ${slug}.`, { status: 404 });
80 const subject: Subject = { kind: "workspace", slug, accountId: account.id, terms: account.terms, billedTo };
81 return { slug, person, detail, billedTo, subject };
82}
83
84/** Sales and invoices are newer billing methods; a page still opens without them. */
85const SALES_DONE = new Set(["sales", "note"]);
86
87export async function loader({ request, params, context }: Route.LoaderArgs) {
88 const staff = requireStaff(context);
89 const { slug, person, detail, billedTo, subject } = await load(params.slug);
90 const { summary } = detail;
91 // On an enterprise, the limit is the enterprise's and the figures are
92 // this workspace's share of its bill.
93 const limit = (billedTo && detail.workspaces.find((member) => member.workspace === slug)) || summary.limit;
94 const share = billedTo ? summary.byWorkspace?.find((row) => row.workspace === slug) : null;
95 const figures = billedTo
96 ? { charged: share?.chargedMicros ?? 0, cost: share?.costMicros ?? 0, paid: share?.paidMicros ?? 0 }
97 : { charged: summary.chargedMicros, cost: summary.costMicros, paid: summary.paidMicros };
98 const [enterprises, sales, invoices, plan, overages, book, credits, complimentary, sso] = await Promise.all([
99 billedTo
100 ? Promise.resolve([])
101 : admin
102 .accounts()
103 .then((rows: AccountSummary[]) =>
104 rows
105 .filter((row) => row.account.kind === "enterprise")
106 .map((row) => ({ id: row.account.id, name: row.account.name, members: row.account.workspaces.length })),
107 ),
108 settle(admin.sales(slug)),
109 settle(admin.workspaceInvoices(slug)),
110 settle(entitlementsOf(slug)),
111 settle(admin.overages()),
112 settle(priceBook()),
113 settle(admin.credits({ workspace: slug })),
114 settle(admin.complimentary(slug)),
115 settle(identity.sso(slug)),
116 ]);
117 const done = doneKey(request.url);
118 return {
119 me: staff.email,
120 slug,
121 name: person?.name ?? slug,
122 person,
123 billedTo,
124 terms: subject.terms,
125 allowances: summary.account.allowances,
126 limit,
127 figures,
128 months: summary.months ?? [],
129 enterprises,
130 sales: sales.ok ? sales.value : null,
131 salesError: sales.ok ? null : sales.error,
132 invoices: invoices.ok ? invoices.value : [],
133 invoicesError: invoices.ok ? null : invoices.error,
134 entitlements: plan.ok ? plan.value : null,
135 entitlementsError: plan.ok ? null : plan.error,
136 overage: overages.ok ? (overages.value.find((row) => row.workspace === slug) ?? null) : null,
137 forgiveCap: (book.ok && book.value.free?.overageForgiveCostMicros) || 50_000_000,
138 credits: credits.ok ? { grants: credits.value.grants, leftMicros: credits.value.grants.reduce((sum, grant) => sum + grant.leftMicros, 0) } : null,
139 creditsError: credits.ok ? null : credits.error,
140 complimentary: complimentary.ok ? complimentary.value : null,
141 complimentaryError: complimentary.ok ? null : complimentary.error,
142 sso: sso.ok ? sso.value : null,
143 ssoError: sso.ok ? null : sso.error,
144 ledger: billedTo ? detail.ledger.filter((entry) => !entry.workspace || entry.workspace === slug) : detail.ledger,
145 audit: billedTo ? detail.audit.filter((entry) => mentions(entry, slug)) : detail.audit,
146 done: done && !SALES_DONE.has(done) ? DONE[done] : null,
147 salesDone: done && SALES_DONE.has(done) ? DONE[done] : null,
148 };
149}
150
151export async function action({ request, params, context }: Route.ActionArgs) {
152 const staff = requireStaff(context);
153 // What is acted on comes from billing and identity, not from the form.
154 const { slug, subject } = await load(params.slug);
155 const path = `/workspaces/${encodeURIComponent(slug)}`;
156 const form = await request.clone().formData();
157 if (SALES_INTENTS.has(text(form, "intent"))) return salesAction(form, staff, slug, path);
158 if (text(form, "intent") === WORKSPACE_DETACH_INTENT) return workspaceDetachAction(form, staff, slug, path);
159 return billingAction(request, staff, subject, path);
160}
161
162const SECTIONS = [
163 { id: "members", label: "Members" },
164 { id: "sso", label: "Single sign-on" },
165 { id: "sales", label: "Sales" },
166 { id: "plan", label: "Plan" },
167 { id: "billing", label: "Billing" },
168 { id: "credits", label: "Credits" },
169 { id: "invoices", label: "Invoices" },
170 { id: "ledger", label: "Ledger" },
171 { id: "audit", label: "Audit log" },
172];
173
174export default function Workspace({ loaderData, actionData }: Route.ComponentProps) {
175 const {
176 me,
177 slug,
178 name,
179 person,
180 billedTo,
181 terms,
182 allowances,
183 limit,
184 figures,
185 months,
186 enterprises,
187 sales,
188 salesError,
189 invoices,
190 invoicesError,
191 entitlements,
192 entitlementsError,
193 overage,
194 forgiveCap,
195 credits,
196 creditsError,
197 complimentary,
198 complimentaryError,
199 sso,
200 ssoError,
201 ledger,
202 audit,
203 done,
204 salesDone,
205 } = loaderData;
206 const { pathname } = useLocation();
207 const result = actionData as ActionData | undefined;
208 const review = result && "review" in result ? result.review : null;
209 const link = result && "link" in result ? result.link : null;
210 const detachPreview = actionData && typeof actionData === "object" && "testDetach" in actionData ? (actionData as WorkspaceDetachData).testDetach : null;
211 const error = (section: string): SectionError => (result && "error" in result && result.section === section ? result : null);
212 const owners = person?.members.filter((member) => member.role === "owner") ?? [];
213
214 return (
215 <main id="top" className="mx-auto max-w-6xl scroll-mt-20 px-4 py-8 sm:py-10">
216 <Link to="/workspaces" className="inline-flex items-center gap-1.5 text-sm text-muted hover:text-fg">
217 <ArrowLeft size={14} />
218 Workspaces
219 </Link>
220
221 {/* Header */}
222 <div className="mt-4 flex flex-wrap items-start justify-between gap-4">
223 <div className="flex min-w-0 items-start gap-3">
224 <Avatar name={slug} size={40} />
225 <div className="min-w-0">
226 <h1 className="truncate text-2xl font-semibold tracking-tight">{name}</h1>
227 <p className="mt-0.5 text-xs text-faint">
228 <span className="font-mono">{slug}</span>
229 {person && (
230 <>
231 {" · "}created <When at={person.createdAt} />
232 </>
233 )}
234 </p>
235 {person?.description && <p className="mt-1 text-sm text-muted">{person.description}</p>}
236 <div className="mt-2 flex flex-wrap gap-1.5">
237 {person?.protected && <Badge tone="info">Protected: can never be deleted</Badge>}
238 {person?.suspended && <Badge tone="danger">Suspended</Badge>}
239 <Link to={`/workspaces/${slug}/abuse`} className="self-center text-xs text-accent hover:underline">
240 Suspend and clean up
241 </Link>
242 {billedTo && <Badge tone="lavender">Billed to {billedTo.name}</Badge>}
243 <TermsBadge terms={terms} />
244 {terms.kind !== "standard" && terms.note && <span className="self-center text-xs text-muted">({terms.note})</span>}
245 {!fullDiscount(terms) && <TrustBadge trust={limit.trust} />}
246 <StateBadge state={limit.state} />
247 {sales && sales.stage !== "none" && <StageBadge stage={sales.stage} />}
248 </div>
249 </div>
250 </div>
251 {owners.length > 0 && (
252 <div className="text-xs">
253 <p className="mb-1.5 text-faint">Owners</p>
254 <Owners owners={owners} />
255 </div>
256 )}
257 </div>
258
259 <nav aria-label="On this page" className="mt-6 -mx-4 overflow-x-auto px-4">
260 <ul className="flex gap-1 border-b border-line text-sm">
261 {SECTIONS.map((section) => (
262 <li key={section.id}>
263 <a
264 href={`#${section.id}`}
265 className="block border-b-2 border-transparent px-2.5 py-2 whitespace-nowrap text-muted transition-colors hover:border-line-strong hover:text-fg"
266 >
267 {section.label}
268 </a>
269 </li>
270 ))}
271 </ul>
272 </nav>
273
274 <div className="mt-6 space-y-3 empty:hidden">
275 {done && <Notice tone="ok">{done}</Notice>}
276 {error("top") && <Notice tone="error">{error("top")?.error}</Notice>}
277 {limit.message && <Notice tone={limit.state === "stopped" ? "error" : limit.state === "warning" ? "warn" : "info"}>{limit.message}</Notice>}
278 {review && <ReviewPanel review={review} pathname={pathname} />}
279 </div>
280
281 {/* People */}
282 <Section id="members" title="Members" description="Everyone in the workspace. Owners manage its members and billing." className="mt-6">
283 {!person ? (
284 <Notice tone="warn">Identity has no record of {slug}; only billing knows it. It may have been deleted.</Notice>
285 ) : person.members.length === 0 ? (
286 <EmptyState title="No members" />
287 ) : (
288 <div className="-mx-4 -my-4 overflow-x-auto sm:-mx-5 sm:-my-5">
289 <table className="w-full min-w-120 text-sm">
290 <thead>
291 <tr className="border-b border-line text-left text-xs text-muted">
292 <th className="px-4 py-2 font-medium sm:pl-5">Member</th>
293 <th className="px-4 py-2 font-medium">Email</th>
294 <th className="px-4 py-2 font-medium">Role</th>
295 <th className="px-4 py-2 font-medium sm:pr-5">Joined</th>
296 </tr>
297 </thead>
298 <tbody>
299 {person.members.map((member) => (
300 <tr key={member.username} className="border-b border-line last:border-0">
301 <td className="px-4 py-2.5 sm:pl-5">
302 <span className="inline-flex items-center gap-2 font-mono">
303 <Avatar name={member.username} size={18} square={false} />
304 <Link to={`/users/${member.username}`} className="hover:underline">
305 {member.username}
306 </Link>
307 </span>
308 </td>
309 <td className="px-4 py-2.5 break-all text-muted">{member.email ?? <span className="text-faint">—</span>}</td>
310 <td className="px-4 py-2.5">{member.role === "owner" ? <Badge tone="lavender">Owner</Badge> : <Badge>Member</Badge>}</td>
311 <td className="px-4 py-2.5 text-xs whitespace-nowrap text-muted sm:pr-5">
312 <When at={member.joined} />
313 </td>
314 </tr>
315 ))}
316 </tbody>
317 </table>
318 </div>
319 )}
320 </Section>
321
322 <SsoSection sso={sso} unavailable={ssoError} />
323
324 {/* Sales */}
325 <div className="mt-6">
326 <SalesSection
327 sales={sales}
328 unavailable={salesError}
329 me={me}
330 pathname={pathname}
331 salesError={error("sales")}
332 noteError={error("note")}
333 done={salesDone}
334 />
335 </div>
336
337 {/* Plan */}
338 <div className="mt-6">
339 <PlanSection entitlements={entitlements} unavailable={entitlementsError} />
340 </div>
341
342 {/* Billing */}
343 <h2 id="billing" className="mt-10 scroll-mt-20 text-lg font-semibold tracking-tight">
344 Billing
345 </h2>
346 <div className="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
347 <LimitCard limit={limit} terms={terms} billedTo={billedTo} />
348 <Figure label="Charged this month" value={usd(figures.charged)} hint={`Cost to g1t ${usd(figures.cost)}`} />
349 <Figure label="Paid ever" value={usd(figures.paid)} hint={`Margin this month ${usd(figures.charged - figures.cost)}`} />
350 </div>
351
352 <Section
353 title="Last six months"
354 description={billedTo ? `${billedTo.name}'s figures: every workspace it pays for, together.` : "What it was charged, against what its usage cost g1t."}
355 className="mt-6"
356 >
357 <MonthsChart wide months={months} label={`${billedTo ? billedTo.name : name}: charged and cost by month`} />
358 </Section>
359
360 <div className="mt-6 grid gap-6 lg:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]">
361 <div className="space-y-6">
362 <BilledToSection billedTo={billedTo} enterprises={enterprises} pathname={pathname} error={error("billed-to")} />
363 {billedTo ? (
364 <Section id="terms" title="Terms" description={`Charged on ${billedTo.name}'s terms while it pays for this workspace.`}>
365 <div className="flex flex-wrap items-center justify-between gap-3">
366 <TermsBadge terms={terms} />
367 <Link to={`/enterprises/${encodeURIComponent(billedTo.id)}#terms`} className="text-sm text-accent hover:underline hover:underline-offset-4">
368 Change them on {billedTo.name}
369 </Link>
370 </div>
371 </Section>
372 ) : (
373 <>
374 <ComplimentarySection
375 workspace={slug}
376 standing={complimentary}
377 unavailable={complimentaryError}
378 pathname={pathname}
379 error={error("complimentary")}
380 />
381 <TermsForm terms={terms} pathname={pathname} error={error("terms")} />
382 <AllowancesForm allowances={allowances} comped={fullDiscount(terms)} pathname={pathname} error={error("allowances")} />
383 </>
384 )}
385 <CreditsSection credits={credits} unavailable={creditsError} pathname={pathname} error={error("credits")} />
386 <WorkspaceInvoicesSection invoices={invoices} unavailable={invoicesError} />
387 <div id="ledger" className="scroll-mt-20">
388 <LedgerSection
389 ledger={ledger}
390 description={billedTo ? `This workspace's lines among ${billedTo.name}'s latest 100.` : "Recent lines of the statement, newest first."}
391 />
392 </div>
393 </div>
394
395 <div className="space-y-6">
396 <BillingLinkSection link={link} pathname={pathname} error={error("billing-link")} />
397 {!billedTo && !fullDiscount(terms) && <GoodwillForm overage={overage} cap={forgiveCap} pathname={pathname} error={error("goodwill")} />}
398 <PaymentForm workspace={slug} pathname={pathname} error={error("payment")} />
399 <CreditForm workspaces={[slug]} pathname={pathname} error={error("credit")} />
400 {!billedTo && !fullDiscount(terms) && <ResetBillingForm workspace={slug} pathname={pathname} error={error("reset")} />}
401 {!billedTo && <WorkspaceTestDetachSection workspace={slug} pathname={pathname} preview={detachPreview} error={error("test-detach")} />}
402 <div id="audit" className="scroll-mt-20">
403 <AuditSection
404 audit={audit}
405 description={
406 billedTo ? (
407 <>
408 Changes about this workspace in {billedTo.name}'s log.{" "}
409 <Link to={`/enterprises/${encodeURIComponent(billedTo.id)}`} className="text-accent hover:underline">
410 Full log
411 </Link>
412 </>
413 ) : undefined
414 }
415 />
416 </div>
417 </div>
418 </div>
419 </main>
420 );
421}
422
423/**
424 * The limit, and in words how it is made: trust, the owners' own spend
425 * limit (or the default), the most they may set, and how it grows.
426 */
427function LimitCard({ limit, terms, billedTo }: { limit: Limit; terms: Terms; billedTo: Enterprise | null }) {
428 const lines: { label: string; value: ReactNode }[] = [];
429 if (billedTo) {
430 lines.push({ label: "Limit", value: <>{billedTo.name}'s, shared by every workspace it pays for</> });
431 } else if (!fullDiscount(terms)) {
432 lines.push({
433 label: "From trust",
434 value: (
435 <>
436 {usd(limit.trustCeilingMicros)}. {trustAbout(limit.trust)}
437 </>
438 ),
439 });
440 }
441 if (terms.ceilingMicros != null) lines.push({ label: "Custom limit", value: usd(terms.ceilingMicros) });
442 if (!billedTo && !fullDiscount(terms)) {
443 lines.push({
444 label: "Owners' limit",
445 value: limit.defaultSpendLimit ? (
446 <>The default, {usd(limit.spendLimitMicros ?? 200_000_000)} a month: they have not chosen one</>
447 ) : limit.spendLimitMicros == null ? (
448 "None of their own: they use everything available"
449 ) : (
450 <>{usd(limit.spendLimitMicros)} a month, chosen by the owners</>
451 ),
452 });
453 if (limit.availableMicros !== undefined) {
454 lines.push({
455 label: "Available",
456 value: limit.availableMicros == null ? "No ceiling" : <>Up to {usd(limit.availableMicros)}: the most owners may set; past it, they contact g1t</>,
457 });
458 }
459 }
460 if (limit.growth) lines.push({ label: "Grows", value: limit.growth });
461
462 return (
463 <div className="rounded-lg border border-line bg-surface px-4 py-3 sm:col-span-2">
464 <p className="mb-2 text-xs text-muted">Usage this month against the limit{billedTo && <> · shared with every workspace {billedTo.name} pays for</>}</p>
465 <ExposureBar limit={limit} wide />
466 {lines.length > 0 && (
467 <dl className="mt-3 space-y-1 text-xs">
468 {lines.map((line) => (
469 <div key={line.label} className="grid grid-cols-[6.5rem_minmax(0,1fr)] gap-2">
470 <dt className="text-faint">{line.label}</dt>
471 <dd className="text-fg-soft">{line.value}</dd>
472 </div>
473 ))}
474 </dl>
475 )}
476 </div>
477 );
478}
479
480function BilledToSection({
481 billedTo,
482 enterprises,
483 pathname,
484 error,
485}: {
486 billedTo: Enterprise | null;
487 enterprises: { id: string; name: string; members: number }[];
488 pathname: string;
489 error: SectionError;
490}) {
491 return (
492 <Section id="billed-to" title="Billed to" description="Whether the workspace pays for itself, or an enterprise pays for it.">
493 {error && (
494 <div className="mb-4">
495 <Notice tone="error">{error.error}</Notice>
496 </div>
497 )}
498 {billedTo ? (
499 <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
500 <p className="text-sm text-muted">
501 <Link to={`/enterprises/${encodeURIComponent(billedTo.id)}`} className="font-medium text-fg hover:underline hover:underline-offset-4">
502 {billedTo.name}
503 </Link>{" "}
504 pays for it, under its limit and terms.
505 </p>
506 <form method="post" action={`${pathname}#review`}>
507 <input type="hidden" name="intent" value="detach" />
508 <Button type="submit" variant="danger">
509 <LogOut size={14} />
510 Move off
511 </Button>
512 </form>
513 </div>
514 ) : enterprises.length === 0 ? (
515 <p className="text-sm text-muted">
516 Itself. There are no enterprises to move it onto yet;{" "}
517 <Link to="/enterprises/new" className="text-accent hover:underline hover:underline-offset-4">
518 create one
519 </Link>
520 .
521 </p>
522 ) : (
523 <form method="post" action={`${pathname}#review`} className="flex flex-col gap-2 sm:flex-row sm:items-end">
524 <input type="hidden" name="intent" value="attach" />
525 <Field label="Itself. Move onto" className="grow">
526 <Select name="target" required defaultValue={error?.values?.target ?? ""}>
527 <option value="" disabled>
528 Choose an enterprise
529 </option>
530 {enterprises.map((enterprise) => (
531 <option key={enterprise.id} value={enterprise.id}>
532 {enterprise.name} ({enterprise.members} workspace{enterprise.members === 1 ? "" : "s"})
533 </option>
534 ))}
535 </Select>
536 </Field>
537 <Button type="submit" variant="quiet">
538 <Building2 size={14} />
539 Move
540 </Button>
541 </form>
542 )}
543 </Section>
544 );
545}
546
547const PLAN_LABEL: Record<string, string> = {
548 free: "Free",
549 paid: "The g1t plan",
550 internal: "Internal (100% discount)",
551 enterprise: "Enterprise",
552 complimentary: "Complimentary",
553};
554
555function gigabytes(bytes: number): string {
556 return `${Math.round((bytes / 1e9) * 100) / 100} GB`;
557}
558
559/** What billing tells every service about the workspace now: plan, caps, pause, trial and what the plan gives it. */
560function PlanSection({ entitlements: e, unavailable }: { entitlements: Entitlements | null; unavailable: string | null }) {
561 if (!e) {
562 return (
563 <Section id="plan" title="Plan and entitlements">
564 <Notice tone="warn">Billing did not answer for entitlements{unavailable ? `: ${unavailable}` : "."}</Notice>
565 </Section>
566 );
567 }
568 const spike = e.spike ? spikeLabel(e.spike.status) : null;
569 const facts: [string, string][] = [
570 ["Compute", e.compute ? "Yes" : e.plan === "free" && e.trialVerified && e.trialMicrosLeft > 0 ? "On the trial" : "No"],
571 ["Card check", e.trialVerified ? "Done" : "Not yet"],
572 ["Trial left", usd(e.trialMicrosLeft)],
573 ["First month", e.firstMonth ? "Yes" : "No"],
574 ["Longest run", e.maxRunMinutes ? `${e.maxRunMinutes} min` : "The guardrails'"],
575 ["Ceiling", e.ceilingMicros >= 1e15 ? "None" : usd(e.ceilingMicros)],
576 ["Not yet paid", usd(e.exposureMicros)],
577 ["Held by reservations", usd(e.heldMicros ?? 0)],
578 ["Prepaid", usd(e.prepaidMicros ?? 0)],
579 ["Included usage", e.includedMicros ? `${usd(e.includedUsedMicros ?? 0)} of ${usd(e.includedMicros)}` : "—"],
580 ["Private storage", `${gigabytes(e.privateStorageBytes)} (${gigabytes(e.freePrivateStorageBytes)} free)`],
581 ["Open-source pool paid", usd(e.ossPaidMicros)],
582 ["Build minutes", `${Math.ceil((e.buildSecondsUsed ?? 0) / 60)}, all metered`],
583 [
584 "Git operations",
585 e.gitOperations != null
586 ? `${e.gitOperations.toLocaleString("en-US")}${e.gitOperationsIncluded ? ` (${e.gitOperationsIncluded.toLocaleString("en-US")} free)` : ""}`
587 : "—",
588 ],
589 ["Audit log", `${e.auditRetentionDays} days${e.auditRetentionCustom ? ", set by staff" : ""}`],
590 ];
591 return (
592 <Section
593 id="plan"
594 title="Plan and entitlements"
595 description="What billing tells every service that starts compute for this workspace, now."
596 actions={
597 <span className="flex flex-wrap gap-1.5">
598 <Badge tone={e.plan === "free" ? "plain" : e.plan === "internal" ? "mint" : "lavender"}>{PLAN_LABEL[e.plan] ?? e.plan}</Badge>
599 {spike && <Badge tone={spike.tone === "plain" ? "plain" : spike.tone}>{spike.label}</Badge>}
600 </span>
601 }
602 >
603 {e.paused && (
604 <div className="mb-4">
605 <Notice tone="error">Compute paused: {e.paused}</Notice>
606 </div>
607 )}
608 {(e.alerts ?? []).length > 0 && (
609 <ul className="mb-4 space-y-1 text-sm">
610 {(e.alerts ?? []).map((alert) => (
611 <li key={`${alert.meter}-${alert.level}`} className={alert.level >= 90 ? "text-warn" : "text-muted"}>
612 {alert.level}% · {alert.message || `${alert.meter}: ${usd(alert.usedMicros)} of ${usd(alert.limitMicros)}`}
613 </li>
614 ))}
615 </ul>
616 )}
617 <dl className="grid gap-x-6 gap-y-1 text-xs sm:grid-cols-2 lg:grid-cols-3">
618 {facts.map(([label, value]) => (
619 <div key={label} className="flex justify-between gap-3 border-b border-line/60 py-1">
620 <dt className="text-faint">{label}</dt>
621 <dd className="tabular text-right text-fg-soft">{value}</dd>
622 </div>
623 ))}
624 </dl>
625 <p className="mt-3 text-xs text-faint">Holds are set under Plan, pools and caps below.</p>
626 </Section>
627 );
628}
629
630/** A goodwill credit from the workspace's page; Overages shows the same math for the whole queue. */
631function GoodwillForm({ overage, cap, pathname, error }: { overage: Overage | null; cap: number; pathname: string; error: SectionError }) {
632 const values = error?.values;
633 const quote = overage ? goodwillWarning(null, overage.goodwill, overage.lastGoodwillAt, cap) : null;
634 return (
635 <Section id="goodwill" title="Goodwill credit" description="For usage past what the owners meant. One click, once in 12 months; more needs a reason.">
636 {overage ? (
637 <dl className="mb-4 space-y-1 text-sm">
638 <div className="flex justify-between gap-3">
639 <dt className="text-muted">Over the typical month</dt>
640 <dd className="tabular">{usd(overage.goodwill.overageMicros)}</dd>
641 </div>
642 <div className="flex justify-between gap-3">
643 <dt className="text-muted">g1t's margin, returned</dt>
644 <dd className="tabular text-success">{usd(overage.goodwill.marginMicros)}</dd>
645 </div>
646 <div className="flex justify-between gap-3">
647 <dt className="text-muted">Real cost absorbed</dt>
648 <dd className={`tabular ${quote?.overCap ? "text-danger" : "text-warn"}`}>{usd(overage.goodwill.absorbedMicros)}</dd>
649 </div>
650 <div className="flex justify-between gap-3 border-t border-line pt-1 font-medium">
651 <dt>One-click credit</dt>
652 <dd className="tabular">{usd(overage.goodwill.creditMicros)}</dd>
653 </div>
654 {!overage.goodwillAvailable && (
655 <p className="pt-1 text-xs text-danger">
656 A goodwill credit was given <When at={overage.lastGoodwillAt} />: another needs a reason.
657 </p>
658 )}
659 </dl>
660 ) : (
661 <p className="mb-4 text-sm text-muted">Not in the Overages queue this month: give an amount and a reason.</p>
662 )}
663 <form method="post" action={`${pathname}#goodwill`} className="space-y-3">
664 <input type="hidden" name="intent" value="goodwill" />
665 {error && <Notice tone="error">{error.error}</Notice>}
666 <div className="grid gap-3 sm:grid-cols-2">
667 <Field label="Amount $" hint={overage ? "Blank: the one-click credit." : "Required here."}>
668 <Input name="amount" inputMode="decimal" defaultValue={values?.amount ?? ""} />
669 </Field>
670 <Field label="Day of the usage" hint="Blank: billing chooses.">
671 <Input type="date" name="day" defaultValue={values?.day ?? ""} />
672 </Field>
673 </div>
674 <Field label="Reason" hint={`Needed past the one-click credit. Past ${usd(cap)} of real cost, use Overages to see it in red first.`}>
675 <Textarea name="reason" rows={2} maxLength={500} defaultValue={values?.reason ?? ""} />
676 </Field>
677 <div className="flex justify-end">
678 <Button type="submit" variant="lavender">
679 Give goodwill credit
680 </Button>
681 </div>
682 </form>
683 </Section>
684 );
685}