@@ -2,7 +2,10 @@ import { trackEvent } from '@codebuff/common/analytics'
22import { AnalyticsEvent } from '@codebuff/common/constants/analytics-events'
33import db from '@codebuff/internal/db'
44import * as schema from '@codebuff/internal/db/schema'
5- import { stripeServer } from '@codebuff/internal/util/stripe'
5+ import {
6+ getUserByStripeCustomerId ,
7+ stripeServer ,
8+ } from '@codebuff/internal/util/stripe'
69import { eq } from 'drizzle-orm'
710
811import { handleSubscribe } from './subscription'
@@ -21,20 +24,6 @@ function mapStripeStatus(status: Stripe.Subscription.Status): SubscriptionStatus
2124 return 'active'
2225}
2326
24- /**
25- * Looks up a user ID by Stripe customer ID.
26- */
27- async function getUserIdByCustomerId (
28- customerId : string ,
29- ) : Promise < string | null > {
30- const userRecord = await db
31- . select ( { id : schema . user . id } )
32- . from ( schema . user )
33- . where ( eq ( schema . user . stripe_customer_id , customerId ) )
34- . limit ( 1 )
35- return userRecord [ 0 ] ?. id ?? null
36- }
37-
3827// ---------------------------------------------------------------------------
3928// invoice.paid
4029// ---------------------------------------------------------------------------
@@ -82,7 +71,7 @@ export async function handleSubscriptionInvoicePaid(params: {
8271 }
8372
8473 // Look up the user for this customer
85- const userId = await getUserIdByCustomerId ( customerId )
74+ const userId = ( await getUserByStripeCustomerId ( customerId ) ) ?. id ?? null
8675
8776 // On first invoice, migrate renewal date & credits (Option B)
8877 if ( invoice . billing_reason === 'subscription_create' ) {
@@ -163,7 +152,7 @@ export async function handleSubscriptionInvoicePaymentFailed(params: {
163152 ? invoice . customer
164153 : invoice . customer ?. id
165154 const userId = customerId
166- ? await getUserIdByCustomerId ( customerId )
155+ ? ( await getUserByStripeCustomerId ( customerId ) ) ?. id ?? null
167156 : null
168157
169158 await db
@@ -214,7 +203,7 @@ export async function handleSubscriptionUpdated(params: {
214203 typeof stripeSubscription . customer === 'string'
215204 ? stripeSubscription . customer
216205 : stripeSubscription . customer . id
217- const userId = await getUserIdByCustomerId ( customerId )
206+ const userId = ( await getUserByStripeCustomerId ( customerId ) ) ?. id ?? null
218207
219208 const status = mapStripeStatus ( stripeSubscription . status )
220209
@@ -280,7 +269,7 @@ export async function handleSubscriptionDeleted(params: {
280269 typeof stripeSubscription . customer === 'string'
281270 ? stripeSubscription . customer
282271 : stripeSubscription . customer . id
283- const userId = await getUserIdByCustomerId ( customerId )
272+ const userId = ( await getUserByStripeCustomerId ( customerId ) ) ?. id ?? null
284273
285274 await db
286275 . update ( schema . subscription )
0 commit comments