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>
This commit is contained in:
@@ -0,0 +1,109 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth/server";
|
||||
import { db, users, tierDefinitions, tierEnum, userUsage, eq, and } from "@epicure/db";
|
||||
import { getRecipeCount, getStorageUsedMb, UNLIMITED } from "@/lib/tiers";
|
||||
import { BillingPlanCards } from "@/components/settings/billing-plan-cards";
|
||||
import { ManageBillingButton } from "@/components/settings/manage-billing-button";
|
||||
import { UsageQuotaSection } from "@/components/settings/usage-quota-section";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
export const metadata: Metadata = {};
|
||||
|
||||
const TIER_NAMES: Record<string, string> = { free: "Free", pro: "Pro", family: "Family" };
|
||||
|
||||
function describeLimit(n: number, unit: string): string {
|
||||
return n === UNLIMITED ? `Unlimited ${unit}` : `${n} ${unit}`;
|
||||
}
|
||||
|
||||
export default async function BillingPage({ searchParams }: { searchParams: Promise<{ checkout?: string }> }) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) return null;
|
||||
const { checkout } = await searchParams;
|
||||
|
||||
const currentMonth = new Date().toISOString().slice(0, 7);
|
||||
|
||||
const [dbUser, allTierDefs, usage, recipeCount, storageUsedMb] = await Promise.all([
|
||||
db.query.users.findFirst({
|
||||
where: eq(users.id, session.user.id),
|
||||
columns: { tier: true, subscriptionStatus: true, currentPeriodEnd: true, stripeCustomerId: true },
|
||||
}),
|
||||
db.select().from(tierDefinitions),
|
||||
db.query.userUsage.findFirst({ where: and(eq(userUsage.userId, session.user.id), eq(userUsage.month, currentMonth)) }),
|
||||
getRecipeCount(session.user.id),
|
||||
getStorageUsedMb(session.user.id),
|
||||
]);
|
||||
|
||||
const currentTier = dbUser?.tier ?? "free";
|
||||
const currentTierDef = allTierDefs.find((t) => t.tier === currentTier);
|
||||
|
||||
const asLimit = (n: number | undefined) => (n === undefined || n === UNLIMITED ? null : n);
|
||||
const usageMetrics = [
|
||||
{ label: "AI calls", used: usage?.aiCallsUsed ?? 0, limit: asLimit(currentTierDef?.aiCallsPerMonth), unlimitedLabel: "Unlimited" },
|
||||
{ label: "Recipes created", used: recipeCount, limit: asLimit(currentTierDef?.maxRecipes), unlimitedLabel: "Unlimited" },
|
||||
{ label: "Storage", used: storageUsedMb, limit: asLimit(currentTierDef?.storageMb), unit: " MB", unlimitedLabel: "Unlimited" },
|
||||
];
|
||||
|
||||
const plans = tierEnum.enumValues.map((tier) => {
|
||||
const def = allTierDefs.find((t) => t.tier === tier);
|
||||
return {
|
||||
tier,
|
||||
name: TIER_NAMES[tier] ?? tier,
|
||||
monthlyPrice: tier === "free" ? "€0" : "Contact for pricing",
|
||||
yearlyPrice: null,
|
||||
features: def
|
||||
? [
|
||||
describeLimit(def.maxRecipes, "recipes"),
|
||||
describeLimit(def.aiCallsPerMonth, "AI calls/month"),
|
||||
describeLimit(def.storageMb, "MB storage"),
|
||||
]
|
||||
: [],
|
||||
purchasable: tier === "free" || !!(def?.stripePriceIdMonthly),
|
||||
};
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-8">
|
||||
{checkout === "success" && (
|
||||
<div className="rounded-lg border border-primary/40 bg-primary/5 p-4 text-sm">
|
||||
Payment received — your plan updates within a few seconds as Stripe confirms it. Refresh if it doesn't show up right away.
|
||||
</div>
|
||||
)}
|
||||
{checkout === "canceled" && (
|
||||
<div className="rounded-lg border p-4 text-sm text-muted-foreground">
|
||||
Checkout canceled — no changes made.
|
||||
</div>
|
||||
)}
|
||||
|
||||
<section className="rounded-xl border p-6 space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h2 className="font-semibold text-lg">Current plan: {TIER_NAMES[currentTier] ?? currentTier}</h2>
|
||||
{dbUser?.currentPeriodEnd && (
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Renews {dbUser.currentPeriodEnd.toLocaleDateString()}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
{dbUser?.subscriptionStatus === "past_due" && (
|
||||
<Badge variant="destructive">Payment failed — update your card</Badge>
|
||||
)}
|
||||
</div>
|
||||
{dbUser?.stripeCustomerId && <ManageBillingButton />}
|
||||
</section>
|
||||
|
||||
<section className="rounded-xl border p-6 space-y-4">
|
||||
<div>
|
||||
<h2 className="font-semibold text-lg">Usage this month</h2>
|
||||
<p className="text-sm text-muted-foreground mt-1">AI calls reset monthly. Recipes and storage are lifetime totals.</p>
|
||||
</div>
|
||||
<UsageQuotaSection metrics={usageMetrics} />
|
||||
</section>
|
||||
|
||||
<section className="space-y-4">
|
||||
<h2 className="font-semibold text-lg">Plans</h2>
|
||||
<BillingPlanCards currentTier={currentTier} plans={plans} />
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user