@@ -130,13 +130,12 @@ export async function checkAndBillOverageThreshold(userId: string): Promise<void
130130 return
131131 }
132132
133- const isTeamPlan = userSubscription . plan === 'team'
134-
135- if ( isTeamPlan && userSubscription . referenceId !== userId ) {
136- logger . debug ( 'User is team member - skipping individual threshold billing' , {
133+ if ( userSubscription . plan === 'team' ) {
134+ logger . debug ( 'Team plan detected - triggering org-level threshold billing' , {
137135 userId,
138136 organizationId : userSubscription . referenceId ,
139137 } )
138+ await checkAndBillOrganizationOverageThreshold ( userSubscription . referenceId )
140139 return
141140 }
142141
@@ -262,15 +261,33 @@ export async function checkAndBillOrganizationOverageThreshold(
262261 }
263262
264263 const members = await db
265- . select ( { userId : member . userId } )
264+ . select ( { userId : member . userId , role : member . role } )
266265 . from ( member )
267266 . where ( eq ( member . organizationId , organizationId ) )
268267
269268 if ( members . length === 0 ) {
270269 return
271270 }
272271
272+ const owner = members . find ( ( m ) => m . role === 'owner' )
273+ if ( ! owner ) {
274+ logger . error ( 'No owner found for organization' , { organizationId } )
275+ return
276+ }
277+
273278 await db . transaction ( async ( tx ) => {
279+ const ownerStatsLock = await tx
280+ . select ( )
281+ . from ( userStats )
282+ . where ( eq ( userStats . userId , owner . userId ) )
283+ . for ( 'update' )
284+ . limit ( 1 )
285+
286+ if ( ownerStatsLock . length === 0 ) {
287+ logger . error ( 'Owner stats not found' , { organizationId, ownerId : owner . userId } )
288+ return
289+ }
290+
274291 let totalTeamUsage = 0
275292 let totalBilledOverage = 0
276293
@@ -354,17 +371,16 @@ export async function checkAndBillOrganizationOverageThreshold(
354371 idempotencyKey,
355372 } )
356373
357- if ( members . length > 0 ) {
358- await tx
359- . update ( userStats )
360- . set ( {
361- billedOverageThisPeriod : sql `${ userStats . billedOverageThisPeriod } + ${ amountToBill } ` ,
362- } )
363- . where ( eq ( userStats . userId , members [ 0 ] . userId ) )
364- }
374+ await tx
375+ . update ( userStats )
376+ . set ( {
377+ billedOverageThisPeriod : sql `${ userStats . billedOverageThisPeriod } + ${ amountToBill } ` ,
378+ } )
379+ . where ( eq ( userStats . userId , owner . userId ) )
365380
366381 logger . info ( 'Successfully created and finalized organization threshold overage invoice' , {
367382 organizationId,
383+ ownerId : owner . userId ,
368384 amountBilled : amountToBill ,
369385 invoiceId,
370386 } )
0 commit comments