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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import Link from "next/link";
|
||||
import { Shield, Users, BookOpen, Settings, BarChart3, ClipboardList, HardDrive, Bot, ArrowLeft, Gauge, Mail, Flag, History, LifeBuoy, TrendingUp, Webhook } from "lucide-react";
|
||||
import { Shield, Users, BookOpen, Settings, BarChart3, ClipboardList, HardDrive, Bot, ArrowLeft, Gauge, Mail, Flag, History, LifeBuoy, TrendingUp, Webhook, CreditCard } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { getStaffRole } from "@/lib/require-admin-page";
|
||||
import { redirect } from "next/navigation";
|
||||
@@ -16,6 +16,7 @@ const adminNav = [
|
||||
{ href: "/admin/reports", label: "Reports", icon: Flag, adminOnly: false },
|
||||
{ href: "/admin/support", label: "Support", icon: LifeBuoy, adminOnly: true },
|
||||
{ href: "/admin/tiers", label: "Tier Limits", icon: Gauge, adminOnly: true },
|
||||
{ href: "/admin/billing", label: "Billing", icon: CreditCard, adminOnly: true },
|
||||
{ href: "/admin/webhooks", label: "Webhooks", icon: Webhook, adminOnly: true },
|
||||
{ href: "/admin/audit-logs", label: "Audit Logs", icon: ClipboardList, adminOnly: true },
|
||||
{ href: "/admin/storage", label: "Storage", icon: HardDrive, adminOnly: true },
|
||||
|
||||
@@ -27,6 +27,9 @@ const ALLOWED_KEYS: SiteSettingKey[] = [
|
||||
"GITEA_REPO",
|
||||
"GITEA_WEBHOOK_SECRET",
|
||||
"USDA_API_KEY",
|
||||
"STRIPE_SECRET_KEY",
|
||||
"STRIPE_PUBLISHABLE_KEY",
|
||||
"STRIPE_WEBHOOK_SECRET",
|
||||
];
|
||||
|
||||
export async function PUT(req: NextRequest) {
|
||||
|
||||
@@ -11,6 +11,9 @@ interface RouteContext {
|
||||
const NUMERIC_FIELDS = ["maxRecipes", "aiCallsPerMonth", "storageMb", "maxPublicRecipes"] as const;
|
||||
type NumericField = (typeof NUMERIC_FIELDS)[number];
|
||||
|
||||
const STRIPE_FIELDS = ["stripeProductId", "stripePriceIdMonthly", "stripePriceIdYearly"] as const;
|
||||
type StripeField = (typeof STRIPE_FIELDS)[number];
|
||||
|
||||
export async function PATCH(req: NextRequest, { params }: RouteContext) {
|
||||
const { session, response } = await requireAdmin();
|
||||
if (response) return response;
|
||||
@@ -20,8 +23,8 @@ export async function PATCH(req: NextRequest, { params }: RouteContext) {
|
||||
return NextResponse.json({ error: "Invalid tier" }, { status: 400 });
|
||||
}
|
||||
|
||||
const body = (await req.json()) as Partial<Record<NumericField, number>>;
|
||||
const updateData: Partial<Record<NumericField, number>> = {};
|
||||
const body = (await req.json()) as Partial<Record<NumericField, number>> & Partial<Record<StripeField, string | null>>;
|
||||
const updateData: Partial<Record<NumericField, number>> & Partial<Record<StripeField, string | null>> = {};
|
||||
|
||||
for (const field of NUMERIC_FIELDS) {
|
||||
const value = body[field];
|
||||
@@ -32,6 +35,15 @@ export async function PATCH(req: NextRequest, { params }: RouteContext) {
|
||||
updateData[field] = value;
|
||||
}
|
||||
|
||||
for (const field of STRIPE_FIELDS) {
|
||||
const value = body[field];
|
||||
if (value === undefined) continue;
|
||||
if (value !== null && typeof value !== "string") {
|
||||
return NextResponse.json({ error: `Invalid value for ${field}` }, { status: 400 });
|
||||
}
|
||||
updateData[field] = value?.trim() || null;
|
||||
}
|
||||
|
||||
const [updated] = await db
|
||||
.update(tierDefinitions)
|
||||
.set(updateData)
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { db, users, tierDefinitions, eq } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { getStripeClient } from "@/lib/stripe";
|
||||
|
||||
const Schema = z.object({
|
||||
tier: z.enum(["pro", "family"]),
|
||||
interval: z.enum(["month", "year"]),
|
||||
});
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
|
||||
const limited = await applyRateLimit(`rl:billing:checkout:${session!.user.id}`, 10, 60);
|
||||
if (limited) return limited;
|
||||
|
||||
const parsed = Schema.safeParse(await req.json());
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: "Validation error", issues: parsed.error.issues }, { status: 400 });
|
||||
}
|
||||
|
||||
const stripe = await getStripeClient();
|
||||
if (!stripe) {
|
||||
return NextResponse.json({ error: "Billing is not configured" }, { status: 400 });
|
||||
}
|
||||
|
||||
const tierDef = await db.query.tierDefinitions.findFirst({ where: eq(tierDefinitions.tier, parsed.data.tier) });
|
||||
const priceId = parsed.data.interval === "year" ? tierDef?.stripePriceIdYearly : tierDef?.stripePriceIdMonthly;
|
||||
if (!priceId) {
|
||||
return NextResponse.json({ error: `No ${parsed.data.interval}ly price configured for ${parsed.data.tier}` }, { status: 400 });
|
||||
}
|
||||
|
||||
const [dbUser] = await db.select({ stripeCustomerId: users.stripeCustomerId, email: users.email }).from(users).where(eq(users.id, session!.user.id)).limit(1);
|
||||
|
||||
const baseUrl = process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000";
|
||||
|
||||
const checkoutSession = await stripe.checkout.sessions.create({
|
||||
mode: "subscription",
|
||||
customer: dbUser?.stripeCustomerId ?? undefined,
|
||||
customer_email: dbUser?.stripeCustomerId ? undefined : dbUser?.email,
|
||||
client_reference_id: session!.user.id,
|
||||
metadata: { userId: session!.user.id },
|
||||
line_items: [{ price: priceId, quantity: 1 }],
|
||||
allow_promotion_codes: true,
|
||||
success_url: `${baseUrl}/settings/billing?checkout=success`,
|
||||
cancel_url: `${baseUrl}/settings/billing?checkout=canceled`,
|
||||
});
|
||||
|
||||
if (!checkoutSession.url) {
|
||||
return NextResponse.json({ error: "Failed to create checkout session" }, { status: 500 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ url: checkoutSession.url });
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { db, users, eq } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
import { applyRateLimit } from "@/lib/rate-limit";
|
||||
import { getStripeClient } from "@/lib/stripe";
|
||||
|
||||
export async function POST() {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
|
||||
const limited = await applyRateLimit(`rl:billing:portal:${session!.user.id}`, 10, 60);
|
||||
if (limited) return limited;
|
||||
|
||||
const stripe = await getStripeClient();
|
||||
if (!stripe) {
|
||||
return NextResponse.json({ error: "Billing is not configured" }, { status: 400 });
|
||||
}
|
||||
|
||||
const [dbUser] = await db.select({ stripeCustomerId: users.stripeCustomerId }).from(users).where(eq(users.id, session!.user.id)).limit(1);
|
||||
if (!dbUser?.stripeCustomerId) {
|
||||
return NextResponse.json({ error: "No billing account yet — subscribe first" }, { status: 400 });
|
||||
}
|
||||
|
||||
const baseUrl = process.env["BETTER_AUTH_URL"] ?? "http://localhost:3000";
|
||||
const portalSession = await stripe.billingPortal.sessions.create({
|
||||
customer: dbUser.stripeCustomerId,
|
||||
return_url: `${baseUrl}/settings/billing`,
|
||||
});
|
||||
|
||||
return NextResponse.json({ url: portalSession.url });
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { db, users, eq } from "@epicure/db";
|
||||
import { requireSession } from "@/lib/api-auth";
|
||||
|
||||
export async function GET() {
|
||||
const { session, response } = await requireSession();
|
||||
if (response) return response;
|
||||
|
||||
const [dbUser] = await db
|
||||
.select({
|
||||
tier: users.tier,
|
||||
subscriptionStatus: users.subscriptionStatus,
|
||||
currentPeriodEnd: users.currentPeriodEnd,
|
||||
stripeCustomerId: users.stripeCustomerId,
|
||||
})
|
||||
.from(users)
|
||||
.where(eq(users.id, session!.user.id))
|
||||
.limit(1);
|
||||
|
||||
return NextResponse.json({
|
||||
tier: dbUser?.tier ?? "free",
|
||||
subscriptionStatus: dbUser?.subscriptionStatus ?? null,
|
||||
currentPeriodEnd: dbUser?.currentPeriodEnd?.toISOString() ?? null,
|
||||
hasStripeCustomer: !!dbUser?.stripeCustomerId,
|
||||
});
|
||||
}
|
||||
@@ -1,117 +1,171 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import crypto from "node:crypto";
|
||||
import { db, users, processedStripeEvents, eq } from "@epicure/db";
|
||||
import { randomUUID } from "crypto";
|
||||
import type Stripe from "stripe";
|
||||
import { db, users, tierDefinitions, processedStripeEvents, auditLogs, eq, or } from "@epicure/db";
|
||||
import { getStripeClient } from "@/lib/stripe";
|
||||
import { getSiteSetting } from "@/lib/site-settings";
|
||||
|
||||
// Stripe webhook handler — verifies stripe-signature header using HMAC-SHA256.
|
||||
// Handles:
|
||||
// - checkout.session.completed → upgrade user to pro
|
||||
// - customer.subscription.deleted → downgrade user to free
|
||||
type SubscriptionStatus = "active" | "trialing" | "past_due" | "canceled" | "incomplete";
|
||||
|
||||
const STRIPE_TOLERANCE_SECONDS = 300; // 5 minutes
|
||||
|
||||
function verifyStripeSignature(
|
||||
rawBody: string,
|
||||
sigHeader: string,
|
||||
secret: string
|
||||
): { valid: boolean; payload: string | null } {
|
||||
// sigHeader format: "t=<timestamp>,v1=<hmac>[,v1=<hmac>...]"
|
||||
const parts = sigHeader.split(",");
|
||||
const tPart = parts.find((p) => p.startsWith("t="));
|
||||
const v1Parts = parts.filter((p) => p.startsWith("v1="));
|
||||
|
||||
if (!tPart || v1Parts.length === 0) {
|
||||
return { valid: false, payload: null };
|
||||
}
|
||||
|
||||
const timestamp = tPart.slice(2);
|
||||
const tsNum = parseInt(timestamp, 10);
|
||||
if (isNaN(tsNum)) return { valid: false, payload: null };
|
||||
|
||||
// Reject stale webhooks
|
||||
const nowSec = Math.floor(Date.now() / 1000);
|
||||
if (Math.abs(nowSec - tsNum) > STRIPE_TOLERANCE_SECONDS) {
|
||||
return { valid: false, payload: null };
|
||||
}
|
||||
|
||||
const signedPayload = `${timestamp}.${rawBody}`;
|
||||
const expected = crypto
|
||||
.createHmac("sha256", secret)
|
||||
.update(signedPayload, "utf8")
|
||||
.digest();
|
||||
|
||||
const matched = v1Parts.some((v1Part) => {
|
||||
const provided = v1Part.slice(3); // strip "v1="
|
||||
let providedBuf: Buffer;
|
||||
try {
|
||||
providedBuf = Buffer.from(provided, "hex");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (providedBuf.length !== expected.length) return false;
|
||||
return crypto.timingSafeEqual(expected, providedBuf);
|
||||
async function resolveTierFromPriceId(priceId: string | null | undefined): Promise<"pro" | "family" | null> {
|
||||
if (!priceId) return null;
|
||||
const row = await db.query.tierDefinitions.findFirst({
|
||||
where: or(eq(tierDefinitions.stripePriceIdMonthly, priceId), eq(tierDefinitions.stripePriceIdYearly, priceId)),
|
||||
});
|
||||
return row?.tier === "pro" || row?.tier === "family" ? row.tier : null;
|
||||
}
|
||||
|
||||
return { valid: matched, payload: matched ? rawBody : null };
|
||||
function mapStripeStatus(status: Stripe.Subscription.Status): SubscriptionStatus {
|
||||
switch (status) {
|
||||
case "trialing": return "trialing";
|
||||
case "past_due": return "past_due";
|
||||
case "canceled":
|
||||
case "unpaid": return "canceled";
|
||||
case "incomplete":
|
||||
case "incomplete_expired": return "incomplete";
|
||||
default: return "active";
|
||||
}
|
||||
}
|
||||
|
||||
// The billing-period fields moved from the Subscription object onto its
|
||||
// items in a 2025 Stripe API revision — read the item first, fall back to
|
||||
// the top-level field for older API versions. Verify against whichever
|
||||
// API version the configured account is actually pinned to before
|
||||
// switching on real (non-test) keys, per the plan's Stripe-CLI test note.
|
||||
function currentPeriodEnd(subscription: Stripe.Subscription): Date | null {
|
||||
const itemPeriodEnd = subscription.items.data[0]?.current_period_end;
|
||||
const legacyPeriodEnd = (subscription as unknown as { current_period_end?: number }).current_period_end;
|
||||
const unix = itemPeriodEnd ?? legacyPeriodEnd;
|
||||
return unix ? new Date(unix * 1000) : null;
|
||||
}
|
||||
|
||||
async function logBillingEvent(userId: string, action: string, metadata: unknown): Promise<void> {
|
||||
await db.insert(auditLogs).values({
|
||||
id: randomUUID(),
|
||||
userId,
|
||||
action: `billing.${action}`,
|
||||
targetType: "user",
|
||||
targetId: userId,
|
||||
metadata: JSON.stringify(metadata),
|
||||
createdAt: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
async function findUserByCustomerId(customerId: string) {
|
||||
const [user] = await db.select({ id: users.id, subscriptionStatus: users.subscriptionStatus }).from(users).where(eq(users.stripeCustomerId, customerId));
|
||||
return user;
|
||||
}
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
const body = await req.text();
|
||||
const sig = req.headers.get("stripe-signature");
|
||||
const webhookSecret = process.env["STRIPE_WEBHOOK_SECRET"];
|
||||
|
||||
if (!sig || !webhookSecret) {
|
||||
const stripe = await getStripeClient();
|
||||
const webhookSecret = await getSiteSetting("STRIPE_WEBHOOK_SECRET");
|
||||
if (!stripe || !webhookSecret) {
|
||||
return NextResponse.json({ error: "Stripe not configured" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { valid } = verifyStripeSignature(body, sig, webhookSecret);
|
||||
if (!valid) {
|
||||
const rawBody = await req.text();
|
||||
const signature = req.headers.get("stripe-signature");
|
||||
if (!signature) {
|
||||
return NextResponse.json({ error: "Missing signature" }, { status: 400 });
|
||||
}
|
||||
|
||||
let event: Stripe.Event;
|
||||
try {
|
||||
event = stripe.webhooks.constructEvent(rawBody, signature, webhookSecret);
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid signature" }, { status: 400 });
|
||||
}
|
||||
|
||||
let event: { id: string; type: string; data: { object: Record<string, unknown> } };
|
||||
try {
|
||||
event = JSON.parse(body) as typeof event;
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
|
||||
}
|
||||
|
||||
if (!event.id) {
|
||||
return NextResponse.json({ error: "Missing event id" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Dedup: Stripe may redeliver the same event within its retry/tolerance
|
||||
// window. Record the event id before processing; if it's already been
|
||||
// recorded, skip processing (but still ack with 200 so Stripe stops
|
||||
// retrying).
|
||||
// Dedup: Stripe may redeliver the same event within its retry window.
|
||||
const [inserted] = await db
|
||||
.insert(processedStripeEvents)
|
||||
.values({ id: event.id, type: event.type })
|
||||
.onConflictDoNothing()
|
||||
.returning({ id: processedStripeEvents.id });
|
||||
|
||||
if (!inserted) {
|
||||
return NextResponse.json({ received: true, duplicate: true });
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case "checkout.session.completed": {
|
||||
// client_reference_id is set to our internal userId when the Checkout Session is created.
|
||||
const userId = event.data.object["client_reference_id"];
|
||||
const customerId = event.data.object["customer"];
|
||||
if (typeof userId === "string" && typeof customerId === "string") {
|
||||
await db.update(users).set({ tier: "pro", stripeCustomerId: customerId }).where(eq(users.id, userId));
|
||||
}
|
||||
const session = event.data.object as Stripe.Checkout.Session;
|
||||
const userId = session.client_reference_id ?? (session.metadata?.["userId"] ?? null);
|
||||
const customerId = typeof session.customer === "string" ? session.customer : session.customer?.id;
|
||||
const subscriptionId = typeof session.subscription === "string" ? session.subscription : session.subscription?.id;
|
||||
if (!userId || !customerId || !subscriptionId) break;
|
||||
|
||||
const subscription = await stripe.subscriptions.retrieve(subscriptionId);
|
||||
const tier = await resolveTierFromPriceId(subscription.items.data[0]?.price.id);
|
||||
if (!tier) break;
|
||||
|
||||
await db.update(users).set({
|
||||
tier,
|
||||
stripeCustomerId: customerId,
|
||||
stripeSubscriptionId: subscriptionId,
|
||||
subscriptionStatus: mapStripeStatus(subscription.status),
|
||||
currentPeriodEnd: currentPeriodEnd(subscription),
|
||||
updatedAt: new Date(),
|
||||
}).where(eq(users.id, userId));
|
||||
await logBillingEvent(userId, "checkout_completed", { tier, subscriptionId });
|
||||
break;
|
||||
}
|
||||
|
||||
case "customer.subscription.updated": {
|
||||
const subscription = event.data.object as Stripe.Subscription;
|
||||
const customerId = typeof subscription.customer === "string" ? subscription.customer : subscription.customer.id;
|
||||
const user = await findUserByCustomerId(customerId);
|
||||
if (!user) break;
|
||||
|
||||
const tier = await resolveTierFromPriceId(subscription.items.data[0]?.price.id);
|
||||
await db.update(users).set({
|
||||
...(tier ? { tier } : {}),
|
||||
subscriptionStatus: mapStripeStatus(subscription.status),
|
||||
currentPeriodEnd: currentPeriodEnd(subscription),
|
||||
updatedAt: new Date(),
|
||||
}).where(eq(users.id, user.id));
|
||||
await logBillingEvent(user.id, "subscription_updated", { tier, status: subscription.status });
|
||||
break;
|
||||
}
|
||||
|
||||
case "customer.subscription.deleted": {
|
||||
const customerId = event.data.object["customer"];
|
||||
if (typeof customerId === "string") {
|
||||
await db.update(users).set({ tier: "free" }).where(eq(users.stripeCustomerId, customerId));
|
||||
const subscription = event.data.object as Stripe.Subscription;
|
||||
const customerId = typeof subscription.customer === "string" ? subscription.customer : subscription.customer.id;
|
||||
const user = await findUserByCustomerId(customerId);
|
||||
if (!user) break;
|
||||
|
||||
await db.update(users).set({ tier: "free", subscriptionStatus: "canceled", updatedAt: new Date() }).where(eq(users.id, user.id));
|
||||
await logBillingEvent(user.id, "subscription_deleted", {});
|
||||
break;
|
||||
}
|
||||
|
||||
case "invoice.payment_failed": {
|
||||
const invoice = event.data.object as Stripe.Invoice;
|
||||
const customerId = typeof invoice.customer === "string" ? invoice.customer : invoice.customer?.id;
|
||||
if (!customerId) break;
|
||||
const user = await findUserByCustomerId(customerId);
|
||||
if (!user) break;
|
||||
|
||||
// Deliberately does NOT downgrade tier — Stripe retries the card
|
||||
// automatically, recovering via invoice.paid or eventually giving up
|
||||
// via customer.subscription.deleted.
|
||||
await db.update(users).set({ subscriptionStatus: "past_due", updatedAt: new Date() }).where(eq(users.id, user.id));
|
||||
await logBillingEvent(user.id, "payment_failed", {});
|
||||
break;
|
||||
}
|
||||
|
||||
case "invoice.paid": {
|
||||
const invoice = event.data.object as Stripe.Invoice;
|
||||
const customerId = typeof invoice.customer === "string" ? invoice.customer : invoice.customer?.id;
|
||||
if (!customerId) break;
|
||||
const user = await findUserByCustomerId(customerId);
|
||||
if (user?.subscriptionStatus === "past_due") {
|
||||
await db.update(users).set({ subscriptionStatus: "active", updatedAt: new Date() }).where(eq(users.id, user.id));
|
||||
await logBillingEvent(user.id, "payment_recovered", {});
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
// ignore unhandled event types
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
@@ -16,12 +16,21 @@ const FIELDS = [
|
||||
{ key: "maxPublicRecipes", label: "Max Public Recipes" },
|
||||
] as const;
|
||||
|
||||
const STRIPE_FIELDS = [
|
||||
{ key: "stripeProductId", label: "Stripe Product ID", placeholder: "prod_..." },
|
||||
{ key: "stripePriceIdMonthly", label: "Monthly Price ID", placeholder: "price_..." },
|
||||
{ key: "stripePriceIdYearly", label: "Yearly Price ID", placeholder: "price_... (optional)" },
|
||||
] as const;
|
||||
|
||||
type TierDefinition = {
|
||||
tier: string;
|
||||
maxRecipes: number;
|
||||
aiCallsPerMonth: number;
|
||||
storageMb: number;
|
||||
maxPublicRecipes: number;
|
||||
stripeProductId: string | null;
|
||||
stripePriceIdMonthly: string | null;
|
||||
stripePriceIdYearly: string | null;
|
||||
};
|
||||
|
||||
export function TierLimitsForm({ tierDefinition }: { tierDefinition: TierDefinition }) {
|
||||
@@ -31,6 +40,11 @@ export function TierLimitsForm({ tierDefinition }: { tierDefinition: TierDefinit
|
||||
storageMb: tierDefinition.storageMb,
|
||||
maxPublicRecipes: tierDefinition.maxPublicRecipes,
|
||||
});
|
||||
const [stripeValues, setStripeValues] = useState<Record<string, string>>({
|
||||
stripeProductId: tierDefinition.stripeProductId ?? "",
|
||||
stripePriceIdMonthly: tierDefinition.stripePriceIdMonthly ?? "",
|
||||
stripePriceIdYearly: tierDefinition.stripePriceIdYearly ?? "",
|
||||
});
|
||||
// Remembers the last finite value per field so toggling "Unlimited" off restores it.
|
||||
const [lastFinite, setLastFinite] = useState<Record<string, number>>({
|
||||
maxRecipes: tierDefinition.maxRecipes === UNLIMITED ? 0 : tierDefinition.maxRecipes,
|
||||
@@ -46,7 +60,7 @@ export function TierLimitsForm({ tierDefinition }: { tierDefinition: TierDefinit
|
||||
const res = await fetch(`/api/v1/admin/tiers/${tierDefinition.tier}`, {
|
||||
method: "PATCH",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(values),
|
||||
body: JSON.stringify({ ...values, ...stripeValues }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
@@ -106,6 +120,26 @@ export function TierLimitsForm({ tierDefinition }: { tierDefinition: TierDefinit
|
||||
})}
|
||||
</div>
|
||||
|
||||
{tierDefinition.tier !== "free" && (
|
||||
<div className="space-y-3 border-t pt-4">
|
||||
<p className="text-xs font-medium text-muted-foreground">Stripe (maps a checkout Price back to this tier)</p>
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
{STRIPE_FIELDS.map(({ key, label, placeholder }) => (
|
||||
<div key={key} className="space-y-1.5">
|
||||
<Label htmlFor={`${tierDefinition.tier}-${key}`} className="text-xs">{label}</Label>
|
||||
<Input
|
||||
id={`${tierDefinition.tier}-${key}`}
|
||||
value={stripeValues[key] ?? ""}
|
||||
placeholder={placeholder}
|
||||
onChange={(e) => setStripeValues((prev) => ({ ...prev, [key]: e.target.value }))}
|
||||
className="font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button onClick={() => { void handleSave(); }} disabled={saving} size="sm">
|
||||
{saving ? "Saving…" : "Save"}
|
||||
</Button>
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Check } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type Tier = "free" | "pro" | "family";
|
||||
|
||||
type PlanCard = {
|
||||
tier: Tier;
|
||||
name: string;
|
||||
monthlyPrice: string;
|
||||
yearlyPrice: string | null;
|
||||
features: string[];
|
||||
purchasable: boolean;
|
||||
};
|
||||
|
||||
export function BillingPlanCards({ currentTier, plans }: { currentTier: Tier; plans: PlanCard[] }) {
|
||||
const [checkingOut, setCheckingOut] = useState<Tier | null>(null);
|
||||
|
||||
async function checkout(tier: "pro" | "family") {
|
||||
setCheckingOut(tier);
|
||||
try {
|
||||
const res = await fetch("/api/v1/billing/checkout", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ tier, interval: "month" }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
throw new Error((data as { error?: string }).error ?? "Checkout failed");
|
||||
}
|
||||
const { url } = (await res.json()) as { url: string };
|
||||
window.location.assign(url);
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : "Checkout failed");
|
||||
setCheckingOut(null);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
|
||||
{plans.map((plan) => {
|
||||
const isCurrent = plan.tier === currentTier;
|
||||
return (
|
||||
<Card key={plan.tier} className={cn(isCurrent && "border-primary")}>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>{plan.name}</CardTitle>
|
||||
{isCurrent && <Badge>Current plan</Badge>}
|
||||
</div>
|
||||
<p className="text-2xl font-bold">{plan.monthlyPrice}</p>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<ul className="space-y-1.5 text-sm">
|
||||
{plan.features.map((f) => (
|
||||
<li key={f} className="flex items-start gap-2">
|
||||
<Check className="h-4 w-4 text-primary shrink-0 mt-0.5" />
|
||||
<span>{f}</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{!isCurrent && plan.purchasable && plan.tier !== "free" && (
|
||||
<Button
|
||||
className="w-full"
|
||||
disabled={checkingOut !== null}
|
||||
onClick={() => { void checkout(plan.tier as "pro" | "family"); }}
|
||||
>
|
||||
{checkingOut === plan.tier ? "Redirecting…" : `Switch to ${plan.name}`}
|
||||
</Button>
|
||||
)}
|
||||
{!isCurrent && !plan.purchasable && plan.tier !== "free" && (
|
||||
<p className="text-xs text-muted-foreground">Not available yet — pricing not configured.</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
export function ManageBillingButton() {
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
async function openPortal() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch("/api/v1/billing/portal", { method: "POST" });
|
||||
if (!res.ok) throw new Error();
|
||||
const { url } = (await res.json()) as { url: string };
|
||||
window.location.assign(url);
|
||||
} catch {
|
||||
toast.error("Couldn't open the billing portal");
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Button variant="outline" disabled={loading} onClick={() => { void openPortal(); }}>
|
||||
{loading ? "Opening…" : "Manage billing"}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
@@ -3,12 +3,13 @@
|
||||
import Link from "next/link";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { User, Shield, Bot, Bell, Apple, Key, Webhook, SlidersHorizontal } from "lucide-react";
|
||||
import { User, Shield, Bot, Bell, Apple, Key, Webhook, SlidersHorizontal, CreditCard } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const NAV_ITEMS = [
|
||||
{ href: "/settings", key: "profile", icon: User, exact: true },
|
||||
{ href: "/settings/security", key: "security", icon: Shield, exact: false },
|
||||
{ href: "/settings/billing", key: "billing", icon: CreditCard, exact: false },
|
||||
{ href: "/settings/ai", key: "aiModels", icon: Bot, exact: false },
|
||||
{ href: "/settings/notifications", key: "notifications", icon: Bell, exact: false },
|
||||
{ href: "/settings/features", key: "features", icon: SlidersHorizontal, exact: false },
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Mirrors CHANGELOG.md at the repo root — update both together.
|
||||
export const APP_VERSION = "0.72.0";
|
||||
export const APP_VERSION = "0.73.0";
|
||||
|
||||
export type ChangelogEntry = {
|
||||
version: string;
|
||||
@@ -11,6 +11,15 @@ export type ChangelogEntry = {
|
||||
};
|
||||
|
||||
export const CHANGELOG: ChangelogEntry[] = [
|
||||
{
|
||||
version: "0.73.0",
|
||||
date: "2026-07-23 14:00",
|
||||
added: [
|
||||
"Real Stripe billing for Pro/Family: subscribe and manage your plan yourself at Settings -> Billing (Checkout + Stripe's hosted Customer Portal for cancel/upgrade/card updates), instead of only an admin being able to change your tier. Cancel takes effect at the end of the paid period.",
|
||||
"Admin -> Billing: connection status, subscriber counts, past-due payments needing attention, recent billing events. Admin -> Tier Limits gained Stripe Product/Price ID fields per tier.",
|
||||
],
|
||||
notes: "Family tier is purchasable solo but doesn't yet support inviting other accounts into a shared subscription — that's a separate, larger piece tracked in plans/STRIPE_PLAN.md, deliberately shipped after solo billing.",
|
||||
},
|
||||
{
|
||||
version: "0.72.0",
|
||||
date: "2026-07-23 09:30",
|
||||
|
||||
+12
-1
@@ -535,6 +535,14 @@ export function generateOpenApiSpec(): object {
|
||||
registry.registerPath({ method: "get", path: "/api/v1/users/me/feature-prefs", summary: "Get your feature visibility preferences", description: "Features with no saved row default to visible.", security, responses: { 200: { description: "Preferences", content: { "application/json": { schema: z.object({ data: FeaturePrefsRef }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "put", path: "/api/v1/users/me/feature-prefs", summary: "Set your feature visibility preferences", description: "Purely cosmetic (hides nav items) — does not restrict access to the underlying pages.", security, request: { body: { content: { "application/json": { schema: UpdateFeaturePrefsRef } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Invalid request", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "patch", path: "/api/v1/users/me/developer-access", summary: "Self-serve enable or disable developer access", description: "Enabling requires a paid tier (free at no extra charge) — free-tier users need an admin grant instead. Disabling is always allowed, regardless of tier or who originally granted it. Only covers webhooks/API keys — BYOK is a separate, admin-only permission.", security, request: { body: { content: { "application/json": { schema: z.object({ enabled: z.boolean() }) } }, required: true } }, responses: { 200: { description: "Updated", content: { "application/json": { schema: z.object({ ok: z.boolean(), isDeveloper: z.boolean() }) } } }, 400: { description: "Validation error", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 403: { description: "Free tier — upgrade or ask an admin", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
const BillingStatusRef = registry.register("BillingStatus", z.object({
|
||||
tier: z.enum(["free", "pro", "family"]), subscriptionStatus: z.enum(["active", "trialing", "past_due", "canceled", "incomplete"]).nullable(),
|
||||
currentPeriodEnd: z.string().datetime().nullable(), hasStripeCustomer: z.boolean(),
|
||||
}));
|
||||
registry.registerPath({ method: "get", path: "/api/v1/billing/status", summary: "Get your current tier, subscription status, and renewal date", security, responses: { 200: { description: "Status", content: { "application/json": { schema: BillingStatusRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "post", path: "/api/v1/billing/checkout", summary: "Start a Stripe Checkout session to subscribe or switch plans", description: "Rate-limited: 10 req/min. Redirects to the returned url. Promotion codes are enabled on the Checkout page.", security, request: { body: { content: { "application/json": { schema: z.object({ tier: z.enum(["pro", "family"]), interval: z.enum(["month", "year"]) }) } }, required: true } }, responses: { 200: { description: "Checkout URL", content: { "application/json": { schema: z.object({ url: z.string() }) } } }, 400: { description: "Billing not configured, or no price set for that tier/interval", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 429: { description: "Rate limited", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "post", path: "/api/v1/billing/portal", summary: "Open the Stripe Customer Portal to manage or cancel your subscription", description: "Rate-limited: 10 req/min. Requires having been through Checkout at least once.", security, responses: { 200: { description: "Portal URL", content: { "application/json": { schema: z.object({ url: z.string() }) } } }, 400: { description: "Billing not configured, or no billing account yet", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } }, 429: { description: "Rate limited", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
|
||||
registry.registerPath({ method: "get", path: "/api/v1/users/me/nutrition-diary", summary: "Get a day's cooked-recipe nutrition totals vs. your goals, or a multi-day trend", description: "Pass `range` (7, 30, or 90) instead of `date` for a daily calorie/macro trend over that many days — days with nothing cooked appear with zero totals.", security, request: { query: z.object({ date: z.string().optional().describe("ISO date YYYY-MM-DD, defaults to today (UTC). Ignored if range is set."), range: z.enum(["7", "30", "90"]).optional().describe("Switches to trend mode: returns { range, days: [{date, calories, proteinG, carbsG, fatG}], goalCalories } instead of the single-day shape.") }) }, responses: { 200: { description: "Diary or trend", content: { "application/json": { schema: z.union([NutritionDiaryRef, NutritionTrendRef]) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "get", path: "/api/v1/users/me/nutrition-goals", summary: "Get your daily nutrition goals", security, responses: { 200: { description: "Goals", content: { "application/json": { schema: z.object({ data: NutritionGoalsRef2 }) } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
registry.registerPath({ method: "put", path: "/api/v1/users/me/nutrition-goals", summary: "Set your daily nutrition goals", security, request: { body: { content: { "application/json": { schema: UpdateNutritionGoalsRef } }, required: true } }, responses: { 200: { description: "Saved", content: { "application/json": { schema: z.object({ ok: z.boolean() }) } } }, 400: { description: "Invalid request", content: { "application/json": { schema: ApiErrorRef } } }, 401: { description: "Unauthorized", content: { "application/json": { schema: ApiErrorRef } } } } });
|
||||
@@ -864,10 +872,13 @@ export function generateOpenApiSpec(): object {
|
||||
const UpdateTierDefinitionBodyRef = registry.register("UpdateTierDefinitionBody", z.object({
|
||||
maxRecipes: z.number().int().optional(), aiCallsPerMonth: z.number().int().optional(),
|
||||
storageMb: z.number().int().optional(), maxPublicRecipes: z.number().int().optional(),
|
||||
}).describe("Each field must be a non-negative integer, or -1 for unlimited."));
|
||||
stripeProductId: z.string().nullable().optional(), stripePriceIdMonthly: z.string().nullable().optional(),
|
||||
stripePriceIdYearly: z.string().nullable().optional(),
|
||||
}).describe("Numeric fields must be a non-negative integer, or -1 for unlimited. Stripe fields map a checkout Price back to this tier — null clears."));
|
||||
const TierDefinitionRef = registry.register("TierDefinition", z.object({
|
||||
tier: z.enum(["free", "pro", "family"]), maxRecipes: z.number().int(), aiCallsPerMonth: z.number().int(),
|
||||
storageMb: z.number().int(), maxPublicRecipes: z.number().int(),
|
||||
stripeProductId: z.string().nullable(), stripePriceIdMonthly: z.string().nullable(), stripePriceIdYearly: z.string().nullable(),
|
||||
}));
|
||||
|
||||
const AdminCreateUserBodyRef = registry.register("AdminCreateUserBody", z.object({
|
||||
|
||||
@@ -23,7 +23,10 @@ export type SiteSettingKey =
|
||||
| "GITEA_TOKEN"
|
||||
| "GITEA_REPO"
|
||||
| "GITEA_WEBHOOK_SECRET"
|
||||
| "USDA_API_KEY";
|
||||
| "USDA_API_KEY"
|
||||
| "STRIPE_SECRET_KEY"
|
||||
| "STRIPE_PUBLISHABLE_KEY"
|
||||
| "STRIPE_WEBHOOK_SECRET";
|
||||
|
||||
const SECRET_KEYS: SiteSettingKey[] = [
|
||||
"OPENAI_API_KEY",
|
||||
@@ -33,6 +36,8 @@ const SECRET_KEYS: SiteSettingKey[] = [
|
||||
"GITEA_TOKEN",
|
||||
"GITEA_WEBHOOK_SECRET",
|
||||
"USDA_API_KEY",
|
||||
"STRIPE_SECRET_KEY",
|
||||
"STRIPE_WEBHOOK_SECRET",
|
||||
];
|
||||
|
||||
export function isSecretKey(key: SiteSettingKey): boolean {
|
||||
@@ -77,6 +82,9 @@ export async function getAllSiteSettings(): Promise<Record<string, { value: stri
|
||||
"GITEA_REPO",
|
||||
"GITEA_WEBHOOK_SECRET",
|
||||
"USDA_API_KEY",
|
||||
"STRIPE_SECRET_KEY",
|
||||
"STRIPE_PUBLISHABLE_KEY",
|
||||
"STRIPE_WEBHOOK_SECRET",
|
||||
];
|
||||
|
||||
const result: Record<string, { value: string | null; isSecret: boolean; fromDb: boolean }> = {};
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import Stripe from "stripe";
|
||||
import { getSiteSetting } from "@/lib/site-settings";
|
||||
|
||||
/** Single Stripe client construction point — mirrors lib/ai/factory.ts's
|
||||
* provider-factory pattern (one place resolves the secret from
|
||||
* site-settings, DB taking precedence over env, everything else imports
|
||||
* the resolved client from here). Returns null if unconfigured so callers
|
||||
* can fail with a clear "billing not configured" message rather than a
|
||||
* cryptic Stripe SDK error. */
|
||||
export async function getStripeClient(): Promise<Stripe | null> {
|
||||
const secretKey = await getSiteSetting("STRIPE_SECRET_KEY");
|
||||
if (!secretKey) return null;
|
||||
return new Stripe(secretKey);
|
||||
}
|
||||
|
||||
export function isStripeTestMode(secretKey: string): boolean {
|
||||
return secretKey.startsWith("sk_test_");
|
||||
}
|
||||
@@ -414,6 +414,7 @@
|
||||
"metric": "Metric",
|
||||
"imperial": "Imperial",
|
||||
"security": "Security",
|
||||
"billing": "Billing",
|
||||
"aiModels": "AI & Models",
|
||||
"notifications": "Notifications",
|
||||
"features": "Features",
|
||||
|
||||
@@ -414,6 +414,7 @@
|
||||
"metric": "Métrique",
|
||||
"imperial": "Impérial",
|
||||
"security": "Sécurité",
|
||||
"billing": "Facturation",
|
||||
"aiModels": "IA et modèles",
|
||||
"notifications": "Notifications",
|
||||
"features": "Fonctionnalités",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@epicure/web",
|
||||
"version": "0.72.0",
|
||||
"version": "0.73.0",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
@@ -45,6 +45,7 @@
|
||||
"react-markdown": "^10.1.0",
|
||||
"shadcn": "^4.11.0",
|
||||
"sonner": "^2.0.7",
|
||||
"stripe": "^22.3.2",
|
||||
"tailwind-merge": "^3.6.0",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"undici": "^7.28.0",
|
||||
|
||||
Reference in New Issue
Block a user