g1t/apps/sudo/app/routes/enterprise.tsx

235 lines11,108 bytesCodeBlame

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Billing on Stripe's pages, month-end charges, warnings; sudo by workspace1import { ArrowLeft, Plus, Trash2 } from "lucide-react";
2import { data, Link, redirect, useLocation } from "react-router";
3
4import { type AdminOwner, type Limit, httpStatus } from "@g1t/contracts";
5
6import type { Route } from "./+types/enterprise";
7import { AuditSection, CreditForm, Figure, LedgerSection, ReviewPanel, TermsForm } from "~/components/billing";
8import { Avatar, Badge, Button, EmptyState, ExposureBar, Field, Input, Notice, Section, StateBadge, TermsBadge, TrustBadge, When } from "~/components/ui";
9import { type Subject, billingAction } from "~/lib/billing-actions.server";
10import { usd } from "~/lib/money";
11import { type ActionData, type SectionError, doneMessage } from "~/lib/review";
12import { admin, identity } from "~/lib/services.server";
13import { requireStaff } from "~/lib/staff";
14import { legacyAccountPath } from "~/lib/workspaces";
15
16export const meta: Route.MetaFunction = ({ loaderData }) => [
17 { title: `${loaderData?.detail.summary.account.name ?? "Enterprise"} · sudo` },
18 { name: "robots", content: "noindex, nofollow" },
19];
20
21const ENTERPRISE_ID = /^ent_[a-z0-9_-]{1,80}$/;
22
23async function load(raw: string) {
24 const id = raw.trim().toLowerCase();
25 if (!ENTERPRISE_ID.test(id)) {
26 // A workspace's id or slug: its own page.
27 const path = legacyAccountPath(id);
28 if (path) throw redirect(path);
29 throw data("That is not an enterprise.", { status: 404 });
30 }
31 const result = await admin.account(id);
32 if (!result.ok) throw data(result.error.message, { status: httpStatus(result.error) });
33 const detail = result.value;
34 const { account } = detail.summary;
35 if (account.kind !== "enterprise") throw data("That is not an enterprise.", { status: 404 });
36 const subject: Subject = { kind: "enterprise", accountId: account.id, name: account.name, terms: account.terms, workspaces: account.workspaces };
37 return { detail, subject };
38}
39
40export async function loader({ request, params, context }: Route.LoaderArgs) {
41 requireStaff(context);
42 const { detail } = await load(params.id);
43 const slugs = detail.summary.account.workspaces;
44 const listed = await identity.workspaces();
45 const people = new Map(listed.map((workspace) => [workspace.slug, { name: workspace.name, owners: workspace.owners }]));
46 // Members older than identity's list: look them up one by one.
47 const missing = slugs.filter((slug) => !people.has(slug)).slice(0, 25);
48 for (const found of await Promise.all(missing.map((slug) => identity.workspace(slug)))) {
49 if (found) {
50 people.set(found.slug, {
51 name: found.name,
52 owners: found.members.filter((member) => member.role === "owner").map(({ username, email }) => ({ username, email })),
53 });
54 }
55 }
56 const limits = new Map(detail.workspaces.map((limit) => [limit.workspace, limit]));
57 const shares = new Map((detail.summary.byWorkspace ?? []).map((share) => [share.workspace, share]));
58 const members = slugs.map((slug) => ({
59 slug,
60 name: people.get(slug)?.name ?? null,
61 owners: people.get(slug)?.owners ?? ([] as AdminOwner[]),
62 limit: limits.get(slug) ?? null,
63 chargedMicros: shares.get(slug)?.chargedMicros ?? 0,
64 }));
65 return { detail, members, done: doneMessage(request.url) };
66}
67
68export async function action({ request, params, context }: Route.ActionArgs) {
69 const staff = requireStaff(context);
70 // What is acted on comes from billing, not from the form.
71 const { subject } = await load(params.id);
72 return billingAction(request, staff, subject, `/enterprises/${encodeURIComponent(subject.accountId)}`);
73}
74
75type Member = Route.ComponentProps["loaderData"]["members"][number];
76
77export default function Enterprise({ loaderData, actionData }: Route.ComponentProps) {
78 const { detail, members, done } = loaderData;
79 const { summary } = detail;
80 const { account, limit } = summary;
81 const { pathname } = useLocation();
82 const result = actionData as ActionData | undefined;
83 const review = result && "review" in result ? result.review : null;
84 const error = (section: string): SectionError => (result && "error" in result && result.section === section ? result : null);
85
86 return (
87 <main id="top" className="mx-auto max-w-6xl scroll-mt-20 px-4 py-8 sm:py-10">
88 <Link to="/enterprises" className="inline-flex items-center gap-1.5 text-sm text-muted hover:text-fg">
89 <ArrowLeft size={14} />
90 Enterprises
91 </Link>
92
93 <div className="mt-4 flex flex-wrap items-start justify-between gap-4">
94 <div className="flex min-w-0 items-start gap-3">
95 <Avatar name={account.name} size={40} />
96 <div className="min-w-0">
97 <h1 className="truncate text-2xl font-semibold tracking-tight">{account.name}</h1>
98 <p className="mt-0.5 text-xs text-faint">
99 Enterprise since <When at={account.createdAt} /> · pays for {members.length} workspace{members.length === 1 ? "" : "s"}
100 </p>
101 <div className="mt-2 flex flex-wrap gap-1.5">
102 <Badge tone="lavender">Enterprise</Badge>
103 <TermsBadge terms={account.terms} />
104 {account.terms.kind !== "comped" && <TrustBadge trust={limit.trust} />}
105 <StateBadge state={limit.state} />
106 </div>
107 </div>
108 </div>
109 <p className="text-xs text-faint">
110 Billing account id <span className="font-mono">{account.id}</span>
111 </p>
112 </div>
113
114 <div className="mt-6 space-y-3">
115 {done && <Notice tone="ok">{done}</Notice>}
116 {error("top") && <Notice tone="error">{error("top")?.error}</Notice>}
117 {limit.message && <Notice tone={limit.state === "stopped" ? "error" : limit.state === "warning" ? "warn" : "info"}>{limit.message}</Notice>}
118 {review && <ReviewPanel review={review} pathname={pathname} />}
119 </div>
120
121 <div className="mt-6 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
122 <div className="rounded-lg border border-line bg-surface px-4 py-3 sm:col-span-2">
123 <p className="mb-2 text-xs text-muted">Usage this month against the limit, all workspaces together</p>
124 <ExposureBar limit={limit} wide />
125 <p className="mt-2 text-xs text-faint">
126 Limit from trust {usd(limit.trustCeilingMicros)}
127 {account.terms.ceilingMicros != null && <> · custom limit {usd(account.terms.ceilingMicros)}</>}
128 </p>
129 </div>
130 <Figure label="Charged this month" value={usd(summary.chargedMicros)} hint={`Cost to g1t ${usd(summary.costMicros)}`} />
131 <Figure label="Paid ever" value={usd(summary.paidMicros)} hint={`Margin this month ${usd(summary.chargedMicros - summary.costMicros)}`} />
132 </div>
133
134 <div className="mt-6 grid gap-6 lg:grid-cols-[minmax(0,3fr)_minmax(0,2fr)]">
135 <div className="space-y-6">
136 <MembersSection members={members} pathname={pathname} error={error("members")} />
137 <TermsForm terms={account.terms} pathname={pathname} error={error("terms")} />
138 <LedgerSection ledger={detail.ledger} showWorkspace description="Recent lines for every workspace it pays for, newest first." />
139 </div>
140 <div className="space-y-6">
141 <CreditForm workspaces={account.workspaces} pathname={pathname} error={error("credit")} />
142 <AuditSection audit={detail.audit} />
143 </div>
144 </div>
145 </main>
146 );
147}
148
149function MembersSection({ members, pathname, error }: { members: Member[]; pathname: string; error: SectionError }) {
150 return (
151 <Section id="members" title="Workspaces" description="Billed together: one bill, one limit, one set of terms.">
152 {error && (
153 <div className="mb-4">
154 <Notice tone="error">{error.error}</Notice>
155 </div>
156 )}
157 {members.length === 0 ? (
158 <EmptyState title="No workspaces yet">Add one below to bill it to this enterprise.</EmptyState>
159 ) : (
160 <ul className="divide-y divide-line rounded-md border border-line">
161 {members.map((member) => (
162 <li key={member.slug} className="flex flex-col gap-3 p-3 sm:flex-row sm:items-center">
163 <div className="flex min-w-0 grow items-start gap-2.5">
164 <Avatar name={member.slug} size={22} />
165 <div className="min-w-0">
166 <Link to={`/workspaces/${encodeURIComponent(member.slug)}`} className="font-medium hover:underline hover:underline-offset-4">
167 {member.name ?? member.slug}
168 </Link>
169 <p className="truncate text-xs text-faint">
170 <span className="font-mono">{member.slug}</span>
171 {member.owners.length > 0 && (
172 <>
173 {" · "}
174 {member.owners.map((owner, index) => (
175 <span key={owner.username} title={owner.email ?? "No email"}>
176 {index > 0 && ", "}
177 {owner.username}
178 </span>
179 ))}
180 </>
181 )}
182 </p>
183 {member.limit?.message && <p className="mt-1 text-xs text-muted">{member.limit.message}</p>}
184 </div>
185 </div>
186 <div className="flex items-center justify-between gap-3 sm:w-56 sm:justify-end">
187 <p className="tabular text-right text-xs text-muted">
188 Charged <span className="text-fg-soft">{usd(member.chargedMicros)}</span>
189 {member.limit && <MemberState limit={member.limit} />}
190 </p>
191 <DetachButton workspace={member.slug} pathname={pathname} />
192 </div>
193 </li>
194 ))}
195 </ul>
196 )}
197 <form method="post" action={`${pathname}#review`} className="mt-4 flex flex-col gap-2 sm:flex-row sm:items-end">
198 <input type="hidden" name="intent" value="attach" />
199 <Field label="Add a workspace" className="grow">
200 <Input name="workspace" required placeholder="workspace-slug" defaultValue={error?.values?.workspace ?? ""} className="font-mono" />
201 </Field>
202 <Button type="submit" variant="quiet">
203 <Plus size={14} />
204 Add
205 </Button>
206 </form>
207 </Section>
208 );
209}
210
211function MemberState({ limit }: { limit: Limit }) {
212 if (limit.state === "ok") return null;
213 return (
214 <span className="mt-1 block">
215 <StateBadge state={limit.state} />
216 </span>
217 );
218}
219
220function DetachButton({ workspace, pathname }: { workspace: string; pathname: string }) {
221 return (
222 <form method="post" action={`${pathname}#review`} className="shrink-0">
223 <input type="hidden" name="intent" value="detach" />
224 <input type="hidden" name="workspace" value={workspace} />
225 <button
226 type="submit"
227 aria-label={`Remove ${workspace}`}
228 title={`Remove ${workspace}`}
229 className="rounded-md border border-line p-2 text-muted transition-colors hover:border-danger/50 hover:text-danger"
230 >
231 <Trash2 size={14} />
232 </button>
233 </form>
234 );
235}