1- import { db } from '@sim/db'
2- import { userStats } from '@sim/db/schema'
3- import { eq } from 'drizzle-orm'
41import { type NextRequest , NextResponse } from 'next/server'
2+ import { checkServerSideUsageLimits } from '@/lib/billing/calculations/usage-monitor'
53import { checkInternalApiKey } from '@/lib/copilot/utils'
64import { createLogger } from '@/lib/logs/console/logger'
75
@@ -24,30 +22,18 @@ export async function POST(req: NextRequest) {
2422
2523 logger . info ( '[API VALIDATION] Validating usage limit' , { userId } )
2624
27- const usage = await db
28- . select ( {
29- currentPeriodCost : userStats . currentPeriodCost ,
30- totalCost : userStats . totalCost ,
31- currentUsageLimit : userStats . currentUsageLimit ,
32- } )
33- . from ( userStats )
34- . where ( eq ( userStats . userId , userId ) )
35- . limit ( 1 )
36-
37- logger . info ( '[API VALIDATION] Usage limit validated' , { userId, usage } )
38-
39- if ( usage . length > 0 ) {
40- const currentUsage = Number . parseFloat (
41- ( usage [ 0 ] . currentPeriodCost ?. toString ( ) as string ) ||
42- ( usage [ 0 ] . totalCost as unknown as string ) ||
43- '0'
44- )
45- const limit = Number . parseFloat ( ( usage [ 0 ] . currentUsageLimit as unknown as string ) || '0' )
46-
47- if ( ! Number . isNaN ( limit ) && limit > 0 && currentUsage >= limit ) {
48- logger . info ( '[API VALIDATION] Usage exceeded' , { userId, currentUsage, limit } )
49- return new NextResponse ( null , { status : 402 } )
50- }
25+ const { isExceeded, currentUsage, limit } = await checkServerSideUsageLimits ( userId )
26+
27+ logger . info ( '[API VALIDATION] Usage limit validated' , {
28+ userId,
29+ currentUsage,
30+ limit,
31+ isExceeded,
32+ } )
33+
34+ if ( isExceeded ) {
35+ logger . info ( '[API VALIDATION] Usage exceeded' , { userId, currentUsage, limit } )
36+ return new NextResponse ( null , { status : 402 } )
5137 }
5238
5339 return new NextResponse ( null , { status : 200 } )
0 commit comments