1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
|
import { Hono } from "hono";
import { desc, eq } from "drizzle-orm";
import { db } from "../db";
import { users, userQuotas } from "../db/schema";
import { Layout } from "../views/layout";
import { softAuth, requireAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import { isSiteAdmin } from "../lib/admin";
import { audit } from "../lib/notify";
import {
formatPrice,
getUserQuota,
listPlans,
setUserPlan,
} from "../lib/billing";
import {
createBillingPortalSession,
createCheckoutSession,
findOrCreateCustomer,
} from "../lib/stripe";
import { config } from "../lib/config";
const billing = new Hono<AuthEnv>();
billing.use("*", softAuth);
billing.get("/settings/billing", requireAuth, async (c) => {
const user = c.get("user")!;
const [quota, plans] = await Promise.all([
getUserQuota(user.id),
listPlans(),
]);
const bar = (pct: number) => {
const color = pct >= 90 ? "var(--red)" : pct >= 70 ? "#f0b72f" : "var(--green)";
return (
<div
style="background:var(--bg-secondary);height:8px;border-radius:4px;overflow:hidden"
>
<div
style={`width:${pct}%;height:100%;background:${color};transition:width .2s`}
/>
</div>
);
};
const bigBar = (pct: number) => {
const color = pct >= 90 ? "var(--red)" : pct >= 70 ? "#f0b72f" : "var(--green)";
return (
<div
style="background:var(--bg-secondary);height:14px;border-radius:7px;overflow:hidden;border:1px solid var(--border-subtle)"
>
<div
style={`width:${pct}%;height:100%;background:${color};transition:width .3s`}
/>
</div>
);
};
return c.html(
<Layout title="Billing — Gluecron" user={user}>
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
<h2>Billing & usage</h2>
<a href="/settings" class="btn btn-sm">
Back to settings
</a>
</div>
{/* L8 — "here's what you've used this month" hero panel. */}
<div
class="panel"
style="padding:20px;margin-bottom:20px;background:linear-gradient(180deg,rgba(140,109,255,0.05),transparent 70%),var(--bg-elevated);border-color:rgba(140,109,255,0.20)"
>
<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:16px;flex-wrap:wrap;margin-bottom:16px">
<div>
<div style="font-size:11px;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.14em;font-family:var(--font-mono);margin-bottom:6px">
Hey, here's what you've used this month
</div>
<div style="font-size:14px;color:var(--text-muted)">
On the <strong style="color:var(--text-strong)">{quota.plan.name}</strong> plan —{" "}
{formatPrice(quota.plan.priceCents)}
</div>
</div>
{quota.planSlug === "free" && (
<form method="post" action="/billing/upgrade/pro">
<button type="submit" class="btn btn-primary">
Upgrade to Pro →
</button>
</form>
)}
</div>
<div style="display:flex;flex-direction:column;gap:14px">
<div>
<div style="display:flex;justify-content:space-between;margin-bottom:6px;font-size:13px">
<span style="color:var(--text-strong);font-weight:500">Repos</span>
<span style="color:var(--text-muted);font-family:var(--font-mono)">
{Math.min(quota.plan.repoLimit, quota.plan.repoLimit)} max on plan
</span>
</div>
{bigBar(0)}
</div>
<div>
<div style="display:flex;justify-content:space-between;margin-bottom:6px;font-size:13px">
<span style="color:var(--text-strong);font-weight:500">AI calls</span>
<span style="color:var(--text-muted);font-family:var(--font-mono)">
{quota.usage.aiTokensUsedThisMonth.toLocaleString()} /{" "}
{quota.plan.aiTokensMonthly.toLocaleString()} ({quota.percent.aiTokens}%)
</span>
</div>
{bigBar(quota.percent.aiTokens)}
</div>
<div>
<div style="display:flex;justify-content:space-between;margin-bottom:6px;font-size:13px">
<span style="color:var(--text-strong);font-weight:500">Storage</span>
<span style="color:var(--text-muted);font-family:var(--font-mono)">
{quota.usage.storageMbUsed} / {quota.plan.storageMbLimit} MB ({quota.percent.storage}%)
</span>
</div>
{bigBar(quota.percent.storage)}
</div>
</div>
</div>
<div class="panel" style="padding:16px;margin-bottom:20px">
<div style="display:flex;justify-content:space-between;align-items:center">
<div>
<div style="font-size:12px;color:var(--text-muted);text-transform:uppercase">
Current plan
</div>
<div style="font-size:22px;font-weight:700">{quota.plan.name}</div>
<div style="font-size:13px;color:var(--text-muted)">
{formatPrice(quota.plan.priceCents)}
</div>
</div>
<div style="text-align:right;font-size:12px;color:var(--text-muted)">
{quota.cycleStart
? `Cycle started ${new Date(quota.cycleStart).toLocaleDateString()}`
: "No cycle recorded"}
</div>
</div>
</div>
<h3>Usage this cycle</h3>
<div class="panel" style="padding:16px;margin-bottom:20px">
<div class="form-group">
<div style="display:flex;justify-content:space-between;margin-bottom:4px">
<span>Storage</span>
<span style="color:var(--text-muted);font-family:var(--font-mono)">
{quota.usage.storageMbUsed} / {quota.plan.storageMbLimit} MB
</span>
</div>
{bar(quota.percent.storage)}
</div>
<div class="form-group">
<div style="display:flex;justify-content:space-between;margin-bottom:4px">
<span>AI tokens (monthly)</span>
<span style="color:var(--text-muted);font-family:var(--font-mono)">
{quota.usage.aiTokensUsedThisMonth.toLocaleString()} /{" "}
{quota.plan.aiTokensMonthly.toLocaleString()}
</span>
</div>
{bar(quota.percent.aiTokens)}
</div>
<div class="form-group" style="margin-bottom:0">
<div style="display:flex;justify-content:space-between;margin-bottom:4px">
<span>Bandwidth (monthly)</span>
<span style="color:var(--text-muted);font-family:var(--font-mono)">
{quota.usage.bandwidthGbUsedThisMonth} /{" "}
{quota.plan.bandwidthGbMonthly} GB
</span>
</div>
{bar(quota.percent.bandwidth)}
</div>
</div>
<h3>Available plans</h3>
<div
style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px"
>
{plans.map((p) => {
const isCurrent = p.slug === quota.planSlug;
return (
<div
class="panel"
style={`padding:16px${isCurrent ? ";border-color:var(--green)" : ""}`}
>
<div style="font-size:16px;font-weight:700">{p.name}</div>
<div style="font-size:18px;margin:6px 0">
{formatPrice(p.priceCents)}
</div>
<div style="font-size:12px;color:var(--text-muted);line-height:1.6">
<div>{p.repoLimit.toLocaleString()} repos</div>
<div>{p.storageMbLimit.toLocaleString()} MB storage</div>
<div>{p.aiTokensMonthly.toLocaleString()} AI tokens/mo</div>
<div>{p.bandwidthGbMonthly} GB bandwidth/mo</div>
<div>
{p.privateRepos ? "Private repos ✓" : "Public repos only"}
</div>
</div>
{isCurrent && (
<div
style="margin-top:10px;font-size:11px;color:var(--green);font-weight:600"
>
CURRENT PLAN
</div>
)}
{!isCurrent && p.slug !== "free" && p.priceCents > 0 && (
<form
method="post"
action={`/billing/upgrade/${p.slug}`}
style="margin-top:10px"
>
<button
type="submit"
class="btn btn-primary"
style="width:100%;font-size:13px"
>
{quota.planSlug === "free" ? "Upgrade" : "Switch"} to {p.name}
</button>
</form>
)}
</div>
);
})}
</div>
{quota.planSlug !== "free" && (
<div style="margin-top:16px">
<form method="post" action="/billing/manage" style="display:inline">
<button
type="submit"
class="btn"
style="font-size:13px"
>
Manage subscription (Stripe Customer Portal)
</button>
</form>
<span
style="font-size:12px;color:var(--text-muted);margin-left:12px"
>
— change card, download invoices, cancel anytime.
</span>
</div>
)}
{!process.env.STRIPE_SECRET_KEY && (
<p
style="font-size:12px;color:var(--text-muted);margin-top:12px;font-style:italic"
>
(Stripe not yet configured on this instance — upgrade buttons will
return a setup error. Run the Stripe Bootstrap workflow to enable.)
</p>
)}
{/* L8 — detailed plan comparison link, points at the public /pricing page. */}
<p style="font-size:13px;color:var(--text-muted);margin-top:24px;text-align:center">
Want the full breakdown of what's included?{" "}
<a href="/pricing" style="color:var(--accent);font-weight:500">
Detailed plan comparison →
</a>
</p>
</Layout>
);
});
billing.post("/billing/upgrade/:plan", requireAuth, async (c) => {
const user = c.get("user")!;
const planSlug = c.req.param("plan");
if (planSlug !== "pro" && planSlug !== "team" && planSlug !== "enterprise") {
return c.redirect("/settings/billing?error=invalid-plan");
}
const quota = await getUserQuota(user.id);
const customer = await findOrCreateCustomer({
userId: user.id,
email: user.email ?? `${user.username}@gluecron.local`,
existingCustomerId: quota.stripeCustomerId ?? null,
});
if (!customer.ok) {
console.error(`[billing/upgrade] customer: ${customer.error}`);
return c.redirect(
`/settings/billing?error=${encodeURIComponent(customer.error)}`
);
}
const base = (config.appBaseUrl || "").replace(/\/$/, "") || "";
const session = await createCheckoutSession({
customerId: customer.customerId,
planSlug,
successUrl: `${base}/billing/success?session_id={CHECKOUT_SESSION_ID}`,
cancelUrl: `${base}/billing/cancel`,
userId: user.id,
});
if (!session.ok) {
console.error(`[billing/upgrade] checkout: ${session.error}`);
return c.redirect(
`/settings/billing?error=${encodeURIComponent(session.error)}`
);
}
await db
.update(userQuotas)
.set({ stripeCustomerId: customer.customerId, updatedAt: new Date() })
.where(eq(userQuotas.userId, user.id));
return c.redirect(session.url, 303);
});
billing.get("/billing/success", requireAuth, async (c) => {
return c.redirect("/settings/billing?upgraded=1");
});
billing.get("/billing/cancel", requireAuth, async (c) => {
return c.redirect("/settings/billing?canceled=1");
});
billing.post("/billing/manage", requireAuth, async (c) => {
const user = c.get("user")!;
const quota = await getUserQuota(user.id);
if (!quota.stripeCustomerId) {
return c.redirect("/settings/billing?error=no-subscription");
}
const base = (config.appBaseUrl || "").replace(/\/$/, "") || "";
const session = await createBillingPortalSession({
customerId: quota.stripeCustomerId,
returnUrl: `${base}/settings/billing`,
});
if (!session.ok) {
console.error(`[billing/manage] portal: ${session.error}`);
return c.redirect(
`/settings/billing?error=${encodeURIComponent(session.error)}`
);
}
return c.redirect(session.url, 303);
});
billing.get("/admin/billing", async (c) => {
const user = c.get("user");
if (!user) return c.redirect("/login?next=/admin/billing");
if (!(await isSiteAdmin(user.id))) {
return c.html(
<Layout title="Forbidden" user={user}>
<div class="empty-state">
<h2>403 — Not a site admin</h2>
</div>
</Layout>,
403
);
}
const plans = await listPlans();
const rows = await db
.select({
id: users.id,
username: users.username,
planSlug: userQuotas.planSlug,
storageMbUsed: userQuotas.storageMbUsed,
aiTokensUsedThisMonth: userQuotas.aiTokensUsedThisMonth,
})
.from(users)
.leftJoin(userQuotas, eq(users.id, userQuotas.userId))
.orderBy(desc(users.createdAt))
.limit(200);
return c.html(
<Layout title="Admin — Billing" user={user}>
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
<h2>Billing — all users</h2>
<a href="/admin" class="btn btn-sm">
Back
</a>
</div>
<div class="panel">
{rows.length === 0 ? (
<div class="panel-empty">No users.</div>
) : (
rows.map((r) => (
<div class="panel-item" style="justify-content:space-between">
<div style="flex:1;min-width:0">
<a href={`/${r.username}`} style="font-weight:600">
{r.username}
</a>
<div style="font-size:12px;color:var(--text-muted);margin-top:2px">
Plan: <strong>{r.planSlug || "free"}</strong> ·{" "}
{r.storageMbUsed || 0} MB ·{" "}
{(r.aiTokensUsedThisMonth || 0).toLocaleString()} tokens
</div>
</div>
<form
method="post"
action={`/admin/billing/${r.id}/plan`}
style="display:flex;gap:6px;align-items:center"
>
<select name="slug" style="font-size:12px">
{plans.map((p) => (
<option
value={p.slug}
selected={(r.planSlug || "free") === p.slug}
>
{p.name}
</option>
))}
</select>
<button type="submit" class="btn btn-sm">
Set
</button>
</form>
</div>
))
)}
</div>
</Layout>
);
});
billing.post("/admin/billing/:userId/plan", async (c) => {
const user = c.get("user");
if (!user) return c.redirect("/login?next=/admin/billing");
if (!(await isSiteAdmin(user.id))) {
return c.text("Forbidden", 403);
}
const userId = c.req.param("userId");
const body = await c.req.parseBody();
const slug = String(body.slug || "free");
await setUserPlan(userId, slug);
await audit({
userId: user.id,
action: "admin.billing.set_plan",
targetType: "user",
targetId: userId,
metadata: { plan: slug },
});
return c.redirect("/admin/billing");
});
export default billing;
|