-
Notifications
You must be signed in to change notification settings - Fork 3.6k
Expand file tree
/
Copy pathroute.ts
More file actions
153 lines (129 loc) · 4.57 KB
/
route.ts
File metadata and controls
153 lines (129 loc) · 4.57 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
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { getSession } from '@/lib/auth'
import { getUserUsageLimitInfo, updateUserUsageLimit } from '@/lib/billing'
import {
getOrganizationBillingData,
isOrganizationOwnerOrAdmin,
} from '@/lib/billing/core/organization'
import { createLogger } from '@/lib/logs/console/logger'
const logger = createLogger('UnifiedUsageAPI')
const usageContextEnum = z.enum(['user', 'organization'])
const usageUpdateSchema = z
.object({
limit: z.number().min(0, 'Limit must be a positive number'),
context: usageContextEnum.optional().default('user'),
organizationId: z.string().optional(),
})
.refine((data) => data.context !== 'organization' || data.organizationId, {
message: 'Organization ID is required when context is organization',
})
/**
* Unified Usage Endpoint
* GET/PUT /api/usage?context=user|organization&userId=<id>&organizationId=<id>
*
*/
export async function GET(request: NextRequest) {
const session = await getSession()
try {
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const { searchParams } = new URL(request.url)
const context = searchParams.get('context') || 'user'
const userId = searchParams.get('userId') || session.user.id
const organizationId = searchParams.get('organizationId')
if (!['user', 'organization'].includes(context)) {
return NextResponse.json(
{ error: 'Invalid context. Must be "user" or "organization"' },
{ status: 400 }
)
}
if (context === 'user' && userId !== session.user.id) {
return NextResponse.json(
{ error: "Cannot view other users' usage information" },
{ status: 403 }
)
}
if (context === 'organization') {
if (!organizationId) {
return NextResponse.json(
{ error: 'Organization ID is required when context=organization' },
{ status: 400 }
)
}
const org = await getOrganizationBillingData(organizationId)
return NextResponse.json({
success: true,
context,
userId,
organizationId,
data: org,
})
}
const usageLimitInfo = await getUserUsageLimitInfo(userId)
return NextResponse.json({
success: true,
context,
userId,
organizationId,
data: usageLimitInfo,
})
} catch (error) {
logger.error('Failed to get usage limit info', {
userId: session?.user?.id,
error,
})
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}
export async function PUT(request: NextRequest) {
const session = await getSession()
try {
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const body = await request.json()
const validation = usageUpdateSchema.safeParse(body)
if (!validation.success) {
const firstError = validation.error.errors[0]
logger.error('Validation error:', firstError)
return NextResponse.json({ error: firstError.message }, { status: 400 })
}
const { limit, context, organizationId } = validation.data
const userId = session.user.id
if (context === 'user') {
const result = await updateUserUsageLimit(userId, limit)
if (!result.success) {
return NextResponse.json({ error: result.error }, { status: 400 })
}
} else if (context === 'organization') {
// organizationId is guaranteed to exist by Zod refinement
const hasPermission = await isOrganizationOwnerOrAdmin(session.user.id, organizationId!)
if (!hasPermission) {
return NextResponse.json({ error: 'Permission denied' }, { status: 403 })
}
const { updateOrganizationUsageLimit } = await import('@/lib/billing/core/organization')
const result = await updateOrganizationUsageLimit(organizationId!, limit)
if (!result.success) {
return NextResponse.json({ error: result.error }, { status: 400 })
}
const updated = await getOrganizationBillingData(organizationId!)
return NextResponse.json({ success: true, context, userId, organizationId, data: updated })
}
const updatedInfo = await getUserUsageLimitInfo(userId)
return NextResponse.json({
success: true,
context,
userId,
organizationId,
data: updatedInfo,
})
} catch (error) {
logger.error('Failed to update usage limit', {
userId: session?.user?.id,
error,
})
return NextResponse.json({ error: 'Internal server error' }, { status: 500 })
}
}