feat: implement subscription system with conversation limits

Implement complete backend subscription system that limits free users to 10
AI conversations per month and offers Premium tier ($10/month or $100/year)
with unlimited conversations.

Changes:
- Add User subscription fields (tier, status, limits, counters)
- Create Subscription model to track Stripe subscriptions
- Implement conversation limit enforcement in chat API
- Add subscription checkout and customer portal APIs
- Update Stripe webhook to handle subscription events
- Add subscription utility functions (limit checks, tier management)
- Add comprehensive subscription translations (en, ro, es, it)
- Update environment variables for Stripe price IDs
- Update footer "Sponsor Us" link to point to /donate
- Add "Sponsor Us" button to home page hero section

Database:
- User model: subscriptionTier, subscriptionStatus, conversationLimit,
  conversationCount, limitResetDate, stripeCustomerId, stripeSubscriptionId
- Subscription model: tracks Stripe subscription details, periods, status
- SubscriptionStatus enum: ACTIVE, CANCELLED, PAST_DUE, TRIALING, etc.

API Routes:
- POST /api/subscriptions/checkout - Create Stripe checkout session
- POST /api/subscriptions/portal - Get customer portal link
- Webhook handlers for: customer.subscription.created/updated/deleted,
  invoice.payment_succeeded/failed

Features:
- Free tier: 10 conversations/month with automatic monthly reset
- Premium tier: Unlimited conversations
- Automatic limit enforcement before conversation creation
- Returns LIMIT_REACHED error with upgrade URL when limit hit
- Stripe Customer Portal integration for subscription management
- Automatic tier upgrade/downgrade via webhooks

Documentation:
- SUBSCRIPTION_IMPLEMENTATION_PLAN.md - Complete implementation plan
- SUBSCRIPTION_IMPLEMENTATION_STATUS.md - Current status and next steps

Frontend UI still needed: subscription page, upgrade modal, usage display

🤖 Generated with Claude Code (https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-10-12 22:14:22 +00:00
parent be22b5b4fd
commit c3cd353f2f
16 changed files with 3771 additions and 699 deletions

View File

@@ -0,0 +1,172 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { stripe } from '@/lib/stripe-server'
import { prisma } from '@/lib/db'
import { verifyToken } from '@/lib/auth'
export const runtime = 'nodejs'
const checkoutSchema = z.object({
priceId: z.string(),
interval: z.enum(['month', 'year']),
locale: z.string().default('en')
})
export async function POST(request: Request) {
try {
// Verify authentication
const authHeader = request.headers.get('authorization')
if (!authHeader?.startsWith('Bearer ')) {
return NextResponse.json(
{ success: false, error: 'Authentication required' },
{ status: 401 }
)
}
const token = authHeader.substring(7)
let payload
try {
payload = await verifyToken(token)
} catch (error) {
return NextResponse.json(
{ success: false, error: 'Invalid or expired token' },
{ status: 401 }
)
}
const userId = payload.userId
// Get user
const user = await prisma.user.findUnique({
where: { id: userId },
select: {
email: true,
name: true,
stripeCustomerId: true,
subscriptionTier: true,
stripeSubscriptionId: true
}
})
if (!user) {
return NextResponse.json(
{ success: false, error: 'User not found' },
{ status: 404 }
)
}
// Check if already has active premium subscription
if (user.subscriptionTier === 'premium' && user.stripeSubscriptionId) {
// Check if subscription is actually active in Stripe
try {
const subscription = await stripe.subscriptions.retrieve(user.stripeSubscriptionId)
if (subscription.status === 'active' || subscription.status === 'trialing') {
return NextResponse.json(
{
success: false,
error: 'Already subscribed to Premium',
code: 'ALREADY_SUBSCRIBED'
},
{ status: 400 }
)
}
} catch (error) {
console.log('Subscription not found in Stripe, allowing new subscription')
}
}
const body = await request.json()
const { priceId, interval, locale } = checkoutSchema.parse(body)
// Validate price ID
if (!priceId || priceId === 'price_xxxxxxxxxxxxx') {
return NextResponse.json(
{
success: false,
error: 'Invalid price ID. Please configure Stripe price IDs in environment variables.'
},
{ status: 400 }
)
}
// Create or retrieve Stripe customer
let customerId = user.stripeCustomerId
if (!customerId) {
const customer = await stripe.customers.create({
email: user.email,
name: user.name || undefined,
metadata: {
userId,
source: 'subscription'
}
})
customerId = customer.id
await prisma.user.update({
where: { id: userId },
data: { stripeCustomerId: customerId }
})
}
// Create checkout session
const session = await stripe.checkout.sessions.create({
customer: customerId,
mode: 'subscription',
payment_method_types: ['card'],
line_items: [
{
price: priceId,
quantity: 1
}
],
success_url: `${process.env.NEXTAUTH_URL}/${locale}/subscription/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${process.env.NEXTAUTH_URL}/${locale}/subscription`,
metadata: {
userId,
interval
},
subscription_data: {
metadata: {
userId
}
},
allow_promotion_codes: true,
billing_address_collection: 'auto'
})
console.log('✅ Stripe checkout session created:', {
sessionId: session.id,
userId,
priceId,
interval
})
return NextResponse.json({
success: true,
sessionId: session.id,
url: session.url
})
} catch (error) {
console.error('Subscription checkout error:', error)
if (error instanceof z.ZodError) {
return NextResponse.json(
{
success: false,
error: 'Invalid request format',
details: error.errors
},
{ status: 400 }
)
}
return NextResponse.json(
{
success: false,
error: 'Failed to create checkout session'
},
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,106 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { stripe } from '@/lib/stripe-server'
import { prisma } from '@/lib/db'
import { verifyToken } from '@/lib/auth'
export const runtime = 'nodejs'
const portalSchema = z.object({
locale: z.string().default('en')
})
export async function POST(request: Request) {
try {
// Verify authentication
const authHeader = request.headers.get('authorization')
if (!authHeader?.startsWith('Bearer ')) {
return NextResponse.json(
{ success: false, error: 'Authentication required' },
{ status: 401 }
)
}
const token = authHeader.substring(7)
let payload
try {
payload = await verifyToken(token)
} catch (error) {
return NextResponse.json(
{ success: false, error: 'Invalid or expired token' },
{ status: 401 }
)
}
const userId = payload.userId
// Get user
const user = await prisma.user.findUnique({
where: { id: userId },
select: {
stripeCustomerId: true,
subscriptionTier: true
}
})
if (!user) {
return NextResponse.json(
{ success: false, error: 'User not found' },
{ status: 404 }
)
}
if (!user.stripeCustomerId) {
return NextResponse.json(
{
success: false,
error: 'No subscription found',
code: 'NO_SUBSCRIPTION'
},
{ status: 404 }
)
}
const body = await request.json()
const { locale } = portalSchema.parse(body)
// Create billing portal session
const session = await stripe.billingPortal.sessions.create({
customer: user.stripeCustomerId,
return_url: `${process.env.NEXTAUTH_URL}/${locale}/settings`
})
console.log('✅ Customer portal session created:', {
sessionId: session.id,
userId,
customerId: user.stripeCustomerId
})
return NextResponse.json({
success: true,
url: session.url
})
} catch (error) {
console.error('Customer portal error:', error)
if (error instanceof z.ZodError) {
return NextResponse.json(
{
success: false,
error: 'Invalid request format',
details: error.errors
},
{ status: 400 }
)
}
return NextResponse.json(
{
success: false,
error: 'Failed to create portal session'
},
{ status: 500 }
)
}
}