@@ -8,22 +8,17 @@ import { checkInternalApiKey } from '@/lib/copilot/utils'
88import { isBillingEnabled } from '@/lib/environment'
99import { createLogger } from '@/lib/logs/console/logger'
1010import { generateRequestId } from '@/lib/utils'
11- import { calculateCost } from '@/providers/utils'
1211
1312const logger = createLogger ( 'BillingUpdateCostAPI' )
1413
1514const UpdateCostSchema = z . object ( {
1615 userId : z . string ( ) . min ( 1 , 'User ID is required' ) ,
17- input : z . number ( ) . min ( 0 , 'Input tokens must be a non-negative number' ) ,
18- output : z . number ( ) . min ( 0 , 'Output tokens must be a non-negative number' ) ,
19- model : z . string ( ) . min ( 1 , 'Model is required' ) ,
20- inputMultiplier : z . number ( ) . min ( 0 ) ,
21- outputMultiplier : z . number ( ) . min ( 0 ) ,
16+ cost : z . number ( ) . min ( 0 , 'Cost must be a non-negative number' ) ,
2217} )
2318
2419/**
2520 * POST /api/billing/update-cost
26- * Update user cost based on token usage with internal API key auth
21+ * Update user cost with a pre-calculated cost value ( internal API key auth required)
2722 */
2823export async function POST ( req : NextRequest ) {
2924 const requestId = generateRequestId ( )
@@ -77,45 +72,13 @@ export async function POST(req: NextRequest) {
7772 )
7873 }
7974
80- const { userId, input , output , model , inputMultiplier , outputMultiplier } = validation . data
75+ const { userId, cost } = validation . data
8176
8277 logger . info ( `[${ requestId } ] Processing cost update` , {
8378 userId,
84- input,
85- output,
86- model,
87- inputMultiplier,
88- outputMultiplier,
79+ cost,
8980 } )
9081
91- const finalPromptTokens = input
92- const finalCompletionTokens = output
93- const totalTokens = input + output
94-
95- // Calculate cost using provided multiplier (required)
96- const costResult = calculateCost (
97- model ,
98- finalPromptTokens ,
99- finalCompletionTokens ,
100- false ,
101- inputMultiplier ,
102- outputMultiplier
103- )
104-
105- logger . info ( `[${ requestId } ] Cost calculation result` , {
106- userId,
107- model,
108- promptTokens : finalPromptTokens ,
109- completionTokens : finalCompletionTokens ,
110- totalTokens : totalTokens ,
111- inputMultiplier,
112- outputMultiplier,
113- costResult,
114- } )
115-
116- // Follow the exact same logic as ExecutionLogger.updateUserStats but with direct userId
117- const costToStore = costResult . total // No additional multiplier needed since calculateCost already applied it
118-
11982 // Check if user stats record exists (same as ExecutionLogger)
12083 const userStatsRecords = await db . select ( ) . from ( userStats ) . where ( eq ( userStats . userId , userId ) )
12184
@@ -128,25 +91,21 @@ export async function POST(req: NextRequest) {
12891 )
12992 return NextResponse . json ( { error : 'User stats record not found' } , { status : 500 } )
13093 }
131- // Update existing user stats record (same logic as ExecutionLogger)
94+ // Update existing user stats record
13295 const updateFields = {
133- totalTokensUsed : sql `total_tokens_used + ${ totalTokens } ` ,
134- totalCost : sql `total_cost + ${ costToStore } ` ,
135- currentPeriodCost : sql `current_period_cost + ${ costToStore } ` ,
96+ totalCost : sql `total_cost + ${ cost } ` ,
97+ currentPeriodCost : sql `current_period_cost + ${ cost } ` ,
13698 // Copilot usage tracking increments
137- totalCopilotCost : sql `total_copilot_cost + ${ costToStore } ` ,
138- totalCopilotTokens : sql `total_copilot_tokens + ${ totalTokens } ` ,
99+ totalCopilotCost : sql `total_copilot_cost + ${ cost } ` ,
139100 totalCopilotCalls : sql `total_copilot_calls + 1` ,
140- totalApiCalls : sql `total_api_calls` ,
141101 lastActive : new Date ( ) ,
142102 }
143103
144104 await db . update ( userStats ) . set ( updateFields ) . where ( eq ( userStats . userId , userId ) )
145105
146106 logger . info ( `[${ requestId } ] Updated user stats record` , {
147107 userId,
148- addedCost : costToStore ,
149- addedTokens : totalTokens ,
108+ addedCost : cost ,
150109 } )
151110
152111 // Check if user has hit overage threshold and bill incrementally
@@ -157,29 +116,14 @@ export async function POST(req: NextRequest) {
157116 logger . info ( `[${ requestId } ] Cost update completed successfully` , {
158117 userId,
159118 duration,
160- cost : costResult . total ,
161- totalTokens,
119+ cost,
162120 } )
163121
164122 return NextResponse . json ( {
165123 success : true ,
166124 data : {
167125 userId,
168- input,
169- output,
170- totalTokens,
171- model,
172- cost : {
173- input : costResult . input ,
174- output : costResult . output ,
175- total : costResult . total ,
176- } ,
177- tokenBreakdown : {
178- prompt : finalPromptTokens ,
179- completion : finalCompletionTokens ,
180- total : totalTokens ,
181- } ,
182- pricing : costResult . pricing ,
126+ cost,
183127 processedAt : new Date ( ) . toISOString ( ) ,
184128 requestId,
185129 } ,
0 commit comments