|
| 1 | +import { |
| 2 | + expireActiveBlockGrants, |
| 3 | + getActiveSubscription, |
| 4 | + getTierPriceId, |
| 5 | +} from '@codebuff/billing' |
| 6 | +import { trackEvent } from '@codebuff/common/analytics' |
| 7 | +import { AnalyticsEvent } from '@codebuff/common/constants/analytics-events' |
| 8 | +import { SUBSCRIPTION_TIERS } from '@codebuff/common/constants/subscription-plans' |
| 9 | +import db from '@codebuff/internal/db' |
| 10 | +import * as schema from '@codebuff/internal/db/schema' |
| 11 | +import { stripeServer } from '@codebuff/internal/util/stripe' |
| 12 | +import { eq } from 'drizzle-orm' |
| 13 | +import { NextResponse } from 'next/server' |
| 14 | +import { getServerSession } from 'next-auth' |
| 15 | + |
| 16 | +import type { SubscriptionTierPrice } from '@codebuff/common/constants/subscription-plans' |
| 17 | +import type { NextRequest } from 'next/server' |
| 18 | + |
| 19 | +import { authOptions } from '@/app/api/auth/[...nextauth]/auth-options' |
| 20 | +import { logger } from '@/util/logger' |
| 21 | + |
| 22 | +export async function POST(req: NextRequest) { |
| 23 | + const session = await getServerSession(authOptions) |
| 24 | + if (!session?.user?.id) { |
| 25 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 26 | + } |
| 27 | + |
| 28 | + const userId = session.user.id |
| 29 | + |
| 30 | + const user = await db.query.user.findFirst({ |
| 31 | + where: eq(schema.user.id, userId), |
| 32 | + columns: { banned: true }, |
| 33 | + }) |
| 34 | + |
| 35 | + if (user?.banned) { |
| 36 | + logger.warn({ userId }, 'Banned user attempted to change subscription tier') |
| 37 | + return NextResponse.json( |
| 38 | + { error: 'Your account has been suspended. Please contact support.' }, |
| 39 | + { status: 403 }, |
| 40 | + ) |
| 41 | + } |
| 42 | + |
| 43 | + const body = await req.json().catch(() => null) |
| 44 | + const rawTier = Number(body?.tier) |
| 45 | + if (!rawTier || !(rawTier in SUBSCRIPTION_TIERS)) { |
| 46 | + return NextResponse.json( |
| 47 | + { error: 'Invalid tier. Must be 100, 200, or 500.' }, |
| 48 | + { status: 400 }, |
| 49 | + ) |
| 50 | + } |
| 51 | + const tier = rawTier as SubscriptionTierPrice |
| 52 | + |
| 53 | + const subscription = await getActiveSubscription({ userId, logger }) |
| 54 | + if (!subscription) { |
| 55 | + return NextResponse.json( |
| 56 | + { error: 'No active subscription found.' }, |
| 57 | + { status: 404 }, |
| 58 | + ) |
| 59 | + } |
| 60 | + |
| 61 | + const previousTier = subscription.tier |
| 62 | + if (previousTier === tier) { |
| 63 | + return NextResponse.json( |
| 64 | + { error: 'Already on the requested tier.' }, |
| 65 | + { status: 400 }, |
| 66 | + ) |
| 67 | + } |
| 68 | + |
| 69 | + const newPriceId = getTierPriceId(tier) |
| 70 | + if (!newPriceId) { |
| 71 | + return NextResponse.json( |
| 72 | + { error: 'Subscription tier not available' }, |
| 73 | + { status: 503 }, |
| 74 | + ) |
| 75 | + } |
| 76 | + |
| 77 | + try { |
| 78 | + const stripeSub = await stripeServer.subscriptions.retrieve( |
| 79 | + subscription.stripe_subscription_id, |
| 80 | + ) |
| 81 | + const itemId = stripeSub.items.data[0]?.id |
| 82 | + if (!itemId) { |
| 83 | + logger.error( |
| 84 | + { userId, subscriptionId: subscription.stripe_subscription_id }, |
| 85 | + 'Stripe subscription has no items', |
| 86 | + ) |
| 87 | + return NextResponse.json( |
| 88 | + { error: 'Subscription configuration error.' }, |
| 89 | + { status: 500 }, |
| 90 | + ) |
| 91 | + } |
| 92 | + |
| 93 | + await stripeServer.subscriptions.update( |
| 94 | + subscription.stripe_subscription_id, |
| 95 | + { |
| 96 | + items: [{ id: itemId, price: newPriceId }], |
| 97 | + proration_behavior: 'create_prorations', |
| 98 | + }, |
| 99 | + ) |
| 100 | + |
| 101 | + try { |
| 102 | + await Promise.all([ |
| 103 | + db |
| 104 | + .update(schema.subscription) |
| 105 | + .set({ tier, stripe_price_id: newPriceId, updated_at: new Date() }) |
| 106 | + .where( |
| 107 | + eq( |
| 108 | + schema.subscription.stripe_subscription_id, |
| 109 | + subscription.stripe_subscription_id, |
| 110 | + ), |
| 111 | + ), |
| 112 | + expireActiveBlockGrants({ |
| 113 | + userId, |
| 114 | + subscriptionId: subscription.stripe_subscription_id, |
| 115 | + logger, |
| 116 | + }), |
| 117 | + ]) |
| 118 | + } catch (dbError) { |
| 119 | + logger.error( |
| 120 | + { error: dbError, userId, subscriptionId: subscription.stripe_subscription_id }, |
| 121 | + 'DB update failed after Stripe tier change — webhook will reconcile', |
| 122 | + ) |
| 123 | + } |
| 124 | + |
| 125 | + trackEvent({ |
| 126 | + event: AnalyticsEvent.SUBSCRIPTION_TIER_CHANGED, |
| 127 | + userId, |
| 128 | + properties: { |
| 129 | + subscriptionId: subscription.stripe_subscription_id, |
| 130 | + previousTier, |
| 131 | + newTier: tier, |
| 132 | + }, |
| 133 | + logger, |
| 134 | + }) |
| 135 | + |
| 136 | + logger.info( |
| 137 | + { |
| 138 | + userId, |
| 139 | + subscriptionId: subscription.stripe_subscription_id, |
| 140 | + previousTier, |
| 141 | + newTier: tier, |
| 142 | + }, |
| 143 | + 'Subscription tier changed', |
| 144 | + ) |
| 145 | + |
| 146 | + return NextResponse.json({ success: true, previousTier, newTier: tier }) |
| 147 | + } catch (error: unknown) { |
| 148 | + const message = error instanceof Error |
| 149 | + ? error.message |
| 150 | + : 'Internal server error changing subscription tier.' |
| 151 | + logger.error( |
| 152 | + { |
| 153 | + error, |
| 154 | + userId, |
| 155 | + subscriptionId: subscription.stripe_subscription_id, |
| 156 | + }, |
| 157 | + 'Failed to change subscription tier', |
| 158 | + ) |
| 159 | + return NextResponse.json({ error: message }, { status: 500 }) |
| 160 | + } |
| 161 | +} |
0 commit comments