@@ -5,7 +5,6 @@ import { buildEnv, serverEnv } from "@cap/env";
55import { stripe } from "@cap/utils" ;
66import { Organisation , User } from "@cap/web-domain" ;
77import { eq } from "drizzle-orm" ;
8- import { revalidatePath } from "next/cache" ;
98import { NextResponse } from "next/server" ;
109import { PostHog } from "posthog-node" ;
1110import type Stripe from "stripe" ;
@@ -244,16 +243,18 @@ export const POST = async (req: Request) => {
244243 inviteQuota,
245244 } ) ;
246245 console . log ( "Session metadata:" , session . metadata ) ;
247- console . log ( "Is onboarding:" , isOnBoarding )
248-
249-
250- await db ( ) . update ( users ) . set ( {
251- stripeSubscriptionId : session . subscription as string ,
252- stripeSubscriptionStatus : subscription . status ,
253- stripeCustomerId : customer . id ,
254- inviteQuota : inviteQuota ,
255- onboarding_completed_at : isOnBoarding ? new Date ( ) : undefined ,
256- } ) . where ( eq ( users . id , dbUser . id ) ) ;
246+ console . log ( "Is onboarding:" , isOnBoarding ) ;
247+
248+ await db ( )
249+ . update ( users )
250+ . set ( {
251+ stripeSubscriptionId : session . subscription as string ,
252+ stripeSubscriptionStatus : subscription . status ,
253+ stripeCustomerId : customer . id ,
254+ inviteQuota : inviteQuota ,
255+ onboarding_completed_at : isOnBoarding ? new Date ( ) : undefined ,
256+ } )
257+ . where ( eq ( users . id , dbUser . id ) ) ;
257258
258259 console . log ( "Successfully updated user in database" ) ;
259260
@@ -304,177 +305,180 @@ export const POST = async (req: Request) => {
304305 }
305306 }
306307
307- if ( event . type === "customer.subscription.updated" ) {
308- console . log ( "Processing customer.subscription.updated event" ) ;
309- const subscription = event . data . object as Stripe . Subscription ;
310- console . log ( "Subscription data:" , {
311- id : subscription . id ,
312- status : subscription . status ,
313- customerId : subscription . customer ,
314- } ) ;
315-
316- const customer = await stripe ( ) . customers . retrieve (
317- subscription . customer as string ,
318- ) ;
319- console . log ( "Retrieved customer:" , {
320- id : customer . id ,
321- email : "email" in customer ? customer . email : undefined ,
322- metadata : "metadata" in customer ? customer . metadata : undefined ,
323- } ) ;
308+ if ( event . type === "customer.subscription.updated" ) {
309+ console . log ( "Processing customer.subscription.updated event" ) ;
310+ const subscription = event . data . object as Stripe . Subscription ;
311+ console . log ( "Subscription data:" , {
312+ id : subscription . id ,
313+ status : subscription . status ,
314+ customerId : subscription . customer ,
315+ } ) ;
324316
325- let foundUserId : User . UserId | undefined ;
326- let customerEmail : string | null | undefined ;
317+ const customer = await stripe ( ) . customers . retrieve (
318+ subscription . customer as string ,
319+ ) ;
320+ console . log ( "Retrieved customer:" , {
321+ id : customer . id ,
322+ email : "email" in customer ? customer . email : undefined ,
323+ metadata : "metadata" in customer ? customer . metadata : undefined ,
324+ } ) ;
327325
328- if ( "metadata" in customer ) {
329- foundUserId = customer . metadata . userId
330- ? User . UserId . make ( customer . metadata . userId )
331- : undefined ;
332- }
333- if ( "email" in customer ) {
334- customerEmail = customer . email ;
335- }
326+ let foundUserId : User . UserId | undefined ;
327+ let customerEmail : string | null | undefined ;
336328
337- console . log ( "Starting user lookup with:" , {
338- foundUserId,
339- customerEmail,
340- } ) ;
329+ if ( "metadata" in customer ) {
330+ foundUserId = customer . metadata . userId
331+ ? User . UserId . make ( customer . metadata . userId )
332+ : undefined ;
333+ }
334+ if ( "email" in customer ) {
335+ customerEmail = customer . email ;
336+ }
341337
342- const dbUser = await findUserWithRetry (
343- customerEmail as string ,
344- foundUserId ,
345- ) ;
338+ console . log ( "Starting user lookup with:" , {
339+ foundUserId ,
340+ customerEmail ,
341+ } ) ;
346342
347- if ( ! dbUser ) {
348- console . log (
349- "No user found after all retries. Returning 202 to allow retry." ,
343+ const dbUser = await findUserWithRetry (
344+ customerEmail as string ,
345+ foundUserId ,
350346 ) ;
351- return new Response ( "User not found, webhook will be retried" , {
352- status : 202 ,
353- } ) ;
354- }
355347
356- console . log ( "Successfully found user:" , {
357- userId : dbUser . id ,
358- email : dbUser . email ,
359- name : dbUser . name ,
360- } ) ;
348+ if ( ! dbUser ) {
349+ console . log (
350+ "No user found after all retries. Returning 202 to allow retry." ,
351+ ) ;
352+ return new Response ( "User not found, webhook will be retried" , {
353+ status : 202 ,
354+ } ) ;
355+ }
361356
362- const subscriptions = await stripe ( ) . subscriptions . list ( {
363- customer : customer . id ,
364- status : "active" ,
365- } ) ;
357+ console . log ( "Successfully found user:" , {
358+ userId : dbUser . id ,
359+ email : dbUser . email ,
360+ name : dbUser . name ,
361+ } ) ;
366362
367- console . log ( "Retrieved all active subscriptions:" , {
368- count : subscriptions . data . length ,
369- } ) ;
363+ const subscriptions = await stripe ( ) . subscriptions . list ( {
364+ customer : customer . id ,
365+ status : "active" ,
366+ } ) ;
370367
371- const inviteQuota = subscriptions . data . reduce ( ( total , sub ) => {
372- return (
373- total +
374- sub . items . data . reduce (
375- ( subTotal , item ) => subTotal + ( item . quantity || 1 ) ,
376- 0 ,
377- )
378- ) ;
379- } , 0 ) ;
368+ console . log ( "Retrieved all active subscriptions:" , {
369+ count : subscriptions . data . length ,
370+ } ) ;
380371
381- console . log ( "Updating user in database with:" , {
382- subscriptionId : subscription . id ,
383- status : subscription . status ,
384- customerId : customer . id ,
385- inviteQuota,
386- } ) ;
372+ const inviteQuota = subscriptions . data . reduce ( ( total , sub ) => {
373+ return (
374+ total +
375+ sub . items . data . reduce (
376+ ( subTotal , item ) => subTotal + ( item . quantity || 1 ) ,
377+ 0 ,
378+ )
379+ ) ;
380+ } , 0 ) ;
387381
388- await db ( )
389- . update ( users )
390- . set ( {
391- stripeSubscriptionId : subscription . id ,
392- stripeSubscriptionStatus : subscription . status ,
393- stripeCustomerId : customer . id ,
394- inviteQuota : inviteQuota ,
395- } )
396- . where ( eq ( users . id , dbUser . id ) ) ;
397-
398- console . log (
399- "Successfully updated user in database with new invite quota:" ,
400- inviteQuota ,
401- ) ;
402- }
382+ console . log ( "Updating user in database with:" , {
383+ subscriptionId : subscription . id ,
384+ status : subscription . status ,
385+ customerId : customer . id ,
386+ inviteQuota,
387+ } ) ;
403388
404- if ( event . type === "customer.subscription.deleted" ) {
405- const subscription = event . data . object as Stripe . Subscription ;
406- const customer = await stripe ( ) . customers . retrieve (
407- subscription . customer as string ,
408- ) ;
409- let foundUserId : User . UserId | undefined ;
410- if ( "metadata" in customer ) {
411- foundUserId = customer . metadata . userId
412- ? User . UserId . make ( customer . metadata . userId )
413- : undefined ;
389+ await db ( )
390+ . update ( users )
391+ . set ( {
392+ stripeSubscriptionId : subscription . id ,
393+ stripeSubscriptionStatus : subscription . status ,
394+ stripeCustomerId : customer . id ,
395+ inviteQuota : inviteQuota ,
396+ } )
397+ . where ( eq ( users . id , dbUser . id ) ) ;
398+
399+ console . log (
400+ "Successfully updated user in database with new invite quota:" ,
401+ inviteQuota ,
402+ ) ;
414403 }
415- if ( ! foundUserId ) {
416- console . log ( "No user found in metadata, checking customer email" ) ;
417- if ( "email" in customer && customer . email ) {
418- const userByEmail = await db ( )
419- . select ( )
420- . from ( users )
421- . where ( eq ( users . email , customer . email ) )
422- . limit ( 1 ) ;
423-
424- if ( userByEmail && userByEmail . length > 0 && userByEmail [ 0 ] ) {
425- foundUserId = userByEmail [ 0 ] . id ;
426- console . log ( `User found by email: ${ foundUserId } ` ) ;
427- await stripe ( ) . customers . update ( customer . id , {
428- metadata : { userId : foundUserId } ,
429- } ) ;
404+
405+ if ( event . type === "customer.subscription.deleted" ) {
406+ const subscription = event . data . object as Stripe . Subscription ;
407+ const customer = await stripe ( ) . customers . retrieve (
408+ subscription . customer as string ,
409+ ) ;
410+ let foundUserId : User . UserId | undefined ;
411+ if ( "metadata" in customer ) {
412+ foundUserId = customer . metadata . userId
413+ ? User . UserId . make ( customer . metadata . userId )
414+ : undefined ;
415+ }
416+ if ( ! foundUserId ) {
417+ console . log ( "No user found in metadata, checking customer email" ) ;
418+ if ( "email" in customer && customer . email ) {
419+ const userByEmail = await db ( )
420+ . select ( )
421+ . from ( users )
422+ . where ( eq ( users . email , customer . email ) )
423+ . limit ( 1 ) ;
424+
425+ if ( userByEmail && userByEmail . length > 0 && userByEmail [ 0 ] ) {
426+ foundUserId = userByEmail [ 0 ] . id ;
427+ console . log ( `User found by email: ${ foundUserId } ` ) ;
428+ await stripe ( ) . customers . update ( customer . id , {
429+ metadata : { userId : foundUserId } ,
430+ } ) ;
431+ } else {
432+ console . log ( "No user found by email" ) ;
433+ return new Response ( "No user found" , {
434+ status : 400 ,
435+ } ) ;
436+ }
430437 } else {
431- console . log ( "No user found by email " ) ;
438+ console . log ( "No email found for customer " ) ;
432439 return new Response ( "No user found" , {
433440 status : 400 ,
434441 } ) ;
435442 }
436- } else {
437- console . log ( "No email found for customer" ) ;
438- return new Response ( "No user found" , {
439- status : 400 ,
440- } ) ;
441443 }
442- }
443444
444- const userResult = await db ( )
445- . select ( )
446- . from ( users )
447- . where ( eq ( users . id , foundUserId ) ) ;
445+ const userResult = await db ( )
446+ . select ( )
447+ . from ( users )
448+ . where ( eq ( users . id , foundUserId ) ) ;
448449
449- if ( ! userResult || userResult . length === 0 ) {
450- console . log ( "No user found in database" ) ;
451- return new Response ( "No user found" , { status : 400 } ) ;
452- }
450+ if ( ! userResult || userResult . length === 0 ) {
451+ console . log ( "No user found in database" ) ;
452+ return new Response ( "No user found" , { status : 400 } ) ;
453+ }
454+
455+ await db ( )
456+ . update ( users )
457+ . set ( {
458+ stripeSubscriptionId : subscription . id ,
459+ stripeSubscriptionStatus : subscription . status ,
460+ inviteQuota : 1 ,
461+ } )
462+ . where ( eq ( users . id , foundUserId ) ) ;
453463
454- await db ( )
455- . update ( users )
456- . set ( {
457- stripeSubscriptionId : subscription . id ,
458- stripeSubscriptionStatus : subscription . status ,
464+ console . log ( "User updated successfully" , {
465+ foundUserId,
459466 inviteQuota : 1 ,
460- } )
461- . where ( eq ( users . id , foundUserId ) ) ;
467+ } ) ;
468+ }
462469
463- console . log ( "User updated successfully" , {
464- foundUserId,
465- inviteQuota : 1 ,
466- } ) ;
470+ return NextResponse . json ( { received : true } ) ;
471+ } catch ( error ) {
472+ console . error ( "❌ Webhook handler failed:" , error ) ;
473+ return new Response (
474+ 'Webhook error: "Webhook handler failed. View logs."' ,
475+ {
476+ status : 400 ,
477+ } ,
478+ ) ;
467479 }
468-
469- return NextResponse . json ( { received : true } ) ;
470480 }
471- catch ( error )
472- console . error ( "❌ Webhook handler failed:" , error ) ;
473- return new Response ( 'Webhook error: "Webhook handler failed. View logs."' , {
474- status : 400 ,
475- } ) ;
476- } ;
477481
478- console . log ( `Unrecognised event: ${ event . type } ` ) ;
479- return new Response ( `Unrecognised event: ${ event . type } ` , { status : 400 } ) ;
480- }
482+ console . log ( `Unrecognised event: ${ event . type } ` ) ;
483+ return new Response ( `Unrecognised event: ${ event . type } ` , { status : 400 } ) ;
484+ } ;
0 commit comments