-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathroute.ts
More file actions
197 lines (168 loc) · 6.54 KB
/
route.ts
File metadata and controls
197 lines (168 loc) · 6.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
import { db } from '@sim/db'
import { subscription as subscriptionTable } from '@sim/db/schema'
import { createLogger } from '@sim/logger'
import { eq } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getSession } from '@/lib/auth'
import { getEffectiveBillingStatus } from '@/lib/billing/core/access'
import { isOrganizationOwnerOrAdmin } from '@/lib/billing/core/organization'
import { getHighestPrioritySubscription } from '@/lib/billing/core/plan'
import { writeBillingInterval } from '@/lib/billing/core/subscription'
import { getPlanType, isEnterprise } from '@/lib/billing/plan-helpers'
import { getPlanByName } from '@/lib/billing/plans'
import { requireStripeClient } from '@/lib/billing/stripe-client'
import {
hasUsableSubscriptionAccess,
hasUsableSubscriptionStatus,
isOrgScopedSubscription,
} from '@/lib/billing/subscriptions/utils'
import { isBillingEnabled } from '@/lib/core/config/feature-flags'
import { toError } from '@/lib/core/utils/helpers'
import { captureServerEvent } from '@/lib/posthog/server'
const logger = createLogger('SwitchPlan')
const switchPlanSchema = z.object({
targetPlanName: z.string(),
interval: z.enum(['month', 'year']).optional(),
})
/**
* POST /api/billing/switch-plan
*
* Switches a subscription's tier and/or billing interval via direct Stripe API.
* Covers: Pro <-> Max, monthly <-> annual, and team tier changes.
* Uses proration -- no Billing Portal redirect.
*
* Body:
* targetPlanName: string -- e.g. 'pro_6000', 'team_25000'
* interval?: 'month' | 'year' -- if omitted, keeps the current interval
*/
export async function POST(request: NextRequest) {
const session = await getSession()
try {
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
if (!isBillingEnabled) {
return NextResponse.json({ error: 'Billing is not enabled' }, { status: 400 })
}
const body = await request.json()
const parsed = switchPlanSchema.safeParse(body)
if (!parsed.success) {
return NextResponse.json(
{ error: 'Invalid request', details: parsed.error.flatten() },
{ status: 400 }
)
}
const { targetPlanName, interval } = parsed.data
const userId = session.user.id
const sub = await getHighestPrioritySubscription(userId)
if (!sub || !sub.stripeSubscriptionId) {
return NextResponse.json({ error: 'No active subscription found' }, { status: 404 })
}
const billingStatus = await getEffectiveBillingStatus(userId)
if (!hasUsableSubscriptionAccess(sub.status, billingStatus.billingBlocked)) {
return NextResponse.json({ error: 'An active subscription is required' }, { status: 400 })
}
if (isEnterprise(sub.plan) || isEnterprise(targetPlanName)) {
return NextResponse.json(
{ error: 'Enterprise plan changes must be handled via support' },
{ status: 400 }
)
}
const targetPlan = getPlanByName(targetPlanName)
if (!targetPlan) {
return NextResponse.json({ error: 'Target plan not found' }, { status: 400 })
}
const currentPlanType = getPlanType(sub.plan)
const targetPlanType = getPlanType(targetPlanName)
if (currentPlanType !== targetPlanType) {
return NextResponse.json(
{ error: 'Cannot switch between individual and team plans via this endpoint' },
{ status: 400 }
)
}
if (isOrgScopedSubscription(sub, userId)) {
const hasPermission = await isOrganizationOwnerOrAdmin(userId, sub.referenceId)
if (!hasPermission) {
return NextResponse.json({ error: 'Only team admins can change the plan' }, { status: 403 })
}
}
const stripe = requireStripeClient()
const stripeSubscription = await stripe.subscriptions.retrieve(sub.stripeSubscriptionId)
if (!hasUsableSubscriptionStatus(stripeSubscription.status)) {
return NextResponse.json({ error: 'Stripe subscription is not active' }, { status: 400 })
}
const subscriptionItem = stripeSubscription.items.data[0]
if (!subscriptionItem) {
return NextResponse.json({ error: 'No subscription item found in Stripe' }, { status: 500 })
}
const currentInterval = subscriptionItem.price?.recurring?.interval
const targetInterval = interval ?? currentInterval ?? 'month'
const targetPriceId =
targetInterval === 'year' ? targetPlan.annualDiscountPriceId : targetPlan.priceId
if (!targetPriceId) {
return NextResponse.json(
{ error: `No ${targetInterval} price configured for plan ${targetPlanName}` },
{ status: 400 }
)
}
const alreadyOnStripePrice = subscriptionItem.price?.id === targetPriceId
const alreadyInDb = sub.plan === targetPlanName
if (alreadyOnStripePrice && alreadyInDb) {
return NextResponse.json({ success: true, message: 'Already on this plan and interval' })
}
logger.info('Switching subscription', {
userId,
subscriptionId: sub.id,
stripeSubscriptionId: sub.stripeSubscriptionId,
fromPlan: sub.plan,
toPlan: targetPlanName,
fromInterval: currentInterval,
toInterval: targetInterval,
targetPriceId,
})
if (!alreadyOnStripePrice) {
const currentQuantity = subscriptionItem.quantity ?? 1
await stripe.subscriptions.update(sub.stripeSubscriptionId, {
items: [
{
id: subscriptionItem.id,
price: targetPriceId,
quantity: currentQuantity,
},
],
proration_behavior: 'always_invoice',
})
}
if (!alreadyInDb) {
await db
.update(subscriptionTable)
.set({ plan: targetPlanName })
.where(eq(subscriptionTable.id, sub.id))
}
await writeBillingInterval(sub.id, targetInterval as 'month' | 'year')
logger.info('Subscription switched successfully', {
userId,
subscriptionId: sub.id,
fromPlan: sub.plan,
toPlan: targetPlanName,
interval: targetInterval,
})
captureServerEvent(
userId,
'subscription_changed',
{ from_plan: sub.plan ?? 'unknown', to_plan: targetPlanName, interval: targetInterval },
{ set: { plan: targetPlanName } }
)
return NextResponse.json({ success: true, plan: targetPlanName, interval: targetInterval })
} catch (error) {
logger.error('Failed to switch subscription', {
userId: session?.user?.id,
error: toError(error).message,
})
return NextResponse.json(
{ error: error instanceof Error ? error.message : 'Failed to switch plan' },
{ status: 500 }
)
}
}