Files
Epicure/apps/web/app/admin/billing/page.tsx
T
Arnaud f871f4f588 feat: real Stripe billing -- Checkout, Customer Portal, admin billing dashboard (v0.73.0)
Implements plans/STRIPE_PLAN.md sections 1-9 for solo Pro/Family
billing (family multi-user sharing, section 1a, deliberately deferred
-- flagged in that plan as the most novel/error-prone piece).

Decisions locked in: cancel/downgrade at period end (Stripe Portal
default), no trial period.

- lib/stripe.ts: single client factory reading STRIPE_SECRET_KEY via
  site-settings (DB overrides env, same pattern as every other
  provider key in this codebase).
- Webhook route rewritten on the real `stripe` SDK
  (stripe.webhooks.constructEvent replaces the hand-rolled HMAC
  verifier) and now handles the full event set: checkout.session.completed,
  customer.subscription.{updated,deleted}, invoice.{payment_failed,paid}.
  past_due deliberately never downgrades tier on its own -- Stripe
  retries the card first, recovering via invoice.paid or eventually
  giving up via subscription.deleted. Every handler audit-logs under
  billing.<event>. Dedup via the existing processed_stripe_events
  table, unchanged.
- Schema: tierDefinitions gained stripe{ProductId,PriceIdMonthly,
  PriceIdYearly} (the lookup table mapping a Price back to a tier on
  checkout); users gained stripeSubscriptionId/subscriptionStatus/
  currentPeriodEnd.
- New POST /api/v1/billing/checkout (creates a subscription Checkout
  Session, allow_promotion_codes: true), POST /api/v1/billing/portal
  (Stripe's hosted self-serve cancel/upgrade/card-update), GET
  /api/v1/billing/status.
- /settings/billing: current plan + renewal date, past_due warning,
  usage-vs-limits (reuses the existing UsageQuotaSection), plan
  comparison cards with per-tier Checkout buttons, manage-billing
  button once a Stripe customer exists.
- /admin/billing: connection status (test/live mode detection),
  subscriber counts, past-due list, recent billing audit events, link
  to Stripe Dashboard. Tier Limits page extended with the three Stripe
  price fields per tier (own render branch, not the numeric+Unlimited-
  switch machinery the existing fields use).

Before going live: an admin needs to create real Products/Prices in
Stripe, enter the IDs on Tier Limits, and configure the Stripe-side
webhook endpoint -- all operational steps the plan always called for,
none of it code.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-23 13:37:14 +02:00

133 lines
5.7 KiB
TypeScript

import type { Metadata } from "next";
import Link from "next/link";
import { ExternalLink } from "lucide-react";
import { db, users, auditLogs, count, eq, sql, like, desc } from "@epicure/db";
import { getAllSiteSettings, getSiteSetting } from "@/lib/site-settings";
import { isStripeTestMode } from "@/lib/stripe";
import { AdminSettingsForm } from "@/components/admin/admin-settings-form";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { requireFullAdminPage } from "@/lib/require-admin-page";
export const metadata: Metadata = {};
const STRIPE_GROUP = {
title: "Stripe Connection",
description:
"Get keys from your Stripe Dashboard (Developers -> API keys). The webhook secret comes from " +
"the endpoint you configure there pointed at /api/webhooks/stripe (events: checkout.session.completed, " +
"customer.subscription.updated, customer.subscription.deleted, invoice.payment_failed, invoice.paid). " +
"Price/Product IDs per tier are set on the Tier Limits page, not here.",
keys: ["STRIPE_SECRET_KEY", "STRIPE_PUBLISHABLE_KEY", "STRIPE_WEBHOOK_SECRET"] as const,
};
export default async function AdminBillingPage() {
await requireFullAdminPage();
const [settings, secretKey] = await Promise.all([
getAllSiteSettings(),
getSiteSetting("STRIPE_SECRET_KEY"),
]);
const [subscriberCounts, pastDueUsers, recentBillingEvents] = await Promise.all([
db.select({ tier: users.tier, count: count() }).from(users).where(sql`${users.tier} != 'free'`).groupBy(users.tier),
db
.select({ id: users.id, name: users.name, email: users.email })
.from(users)
.where(eq(users.subscriptionStatus, "past_due"))
.limit(20),
db
.select({ id: auditLogs.id, action: auditLogs.action, targetId: auditLogs.targetId, metadata: auditLogs.metadata, createdAt: auditLogs.createdAt })
.from(auditLogs)
.where(like(auditLogs.action, "billing.%"))
.orderBy(desc(auditLogs.createdAt))
.limit(20),
]);
const proCount = subscriberCounts.find((r) => r.tier === "pro")?.count ?? 0;
const familyCount = subscriberCounts.find((r) => r.tier === "family")?.count ?? 0;
return (
<div className="space-y-8">
<div>
<h1 className="text-2xl font-bold tracking-tight">Billing</h1>
<p className="text-muted-foreground text-sm mt-1">
Stripe connection status, subscriber insights, and recent billing events. Price mapping per tier
lives on the <Link href="/admin/tiers" className="underline underline-offset-4">Tier Limits</Link> page.
</p>
</div>
<div className="flex items-center gap-2">
{secretKey ? (
<Badge variant={isStripeTestMode(secretKey) ? "secondary" : "default"}>
{isStripeTestMode(secretKey) ? "Test mode" : "Live mode"}
</Badge>
) : (
<Badge variant="outline" className="text-muted-foreground">Not configured</Badge>
)}
<a
href="https://dashboard.stripe.com"
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-sm text-primary hover:underline"
>
Stripe Dashboard
<ExternalLink className="h-3.5 w-3.5" />
</a>
</div>
<AdminSettingsForm group={STRIPE_GROUP} settings={settings} />
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
<Card>
<CardHeader><CardTitle className="text-sm font-medium text-muted-foreground">Pro subscribers</CardTitle></CardHeader>
<CardContent><p className="text-2xl font-bold">{proCount}</p></CardContent>
</Card>
<Card>
<CardHeader><CardTitle className="text-sm font-medium text-muted-foreground">Family subscribers</CardTitle></CardHeader>
<CardContent><p className="text-2xl font-bold">{familyCount}</p></CardContent>
</Card>
<Card>
<CardHeader><CardTitle className="text-sm font-medium text-muted-foreground">Past due</CardTitle></CardHeader>
<CardContent><p className="text-2xl font-bold">{pastDueUsers.length}</p></CardContent>
</Card>
</div>
{pastDueUsers.length > 0 && (
<section className="rounded-xl border p-6 space-y-3">
<h2 className="font-semibold text-lg">Payments needing attention</h2>
<ul className="space-y-1.5">
{pastDueUsers.map((u) => (
<li key={u.id} className="flex items-center justify-between text-sm">
<span>{u.name} <span className="text-muted-foreground">({u.email})</span></span>
<Link href={`/admin/users/${u.id}`} className="text-primary hover:underline">View</Link>
</li>
))}
</ul>
</section>
)}
<section className="rounded-xl border p-6 space-y-3">
<h2 className="font-semibold text-lg">Recent billing events</h2>
{recentBillingEvents.length === 0 ? (
<p className="text-sm text-muted-foreground">Nothing yet.</p>
) : (
<ul className="space-y-1.5">
{recentBillingEvents.map((e) => (
<li key={e.id} className="flex items-center justify-between text-sm border-b last:border-0 pb-1.5">
<span>
<span className="font-mono text-xs">{e.action}</span>
{e.targetId && (
<Link href={`/admin/users/${e.targetId}`} className="text-primary hover:underline ml-2">user</Link>
)}
</span>
<span className="text-muted-foreground text-xs">{e.createdAt.toLocaleString()}</span>
</li>
))}
</ul>
)}
</section>
</div>
);
}