MCPcopy
hub / github.com/CodebuffAI/codebuff / validateAutoTopupStatus

Function validateAutoTopupStatus

packages/billing/src/auto-topup.ts:43–126  ·  view source on GitHub ↗
(params: {
  userId: string
  logger: Logger
})

Source from the content-addressed store, hash-verified

41}
42
43export async function validateAutoTopupStatus(params: {
44 userId: string
45 logger: Logger
46}): Promise<AutoTopupValidationResult> {
47 const { userId, logger } = params
48
49 try {
50 const user = await db.query.user.findFirst({
51 where: eq(schema.user.id, userId),
52 columns: {
53 stripe_customer_id: true,
54 },
55 })
56
57 if (!user?.stripe_customer_id) {
58 throw new AutoTopupValidationError(
59 `You don't have a valid account with us. Please log in at ${env.NEXT_PUBLIC_CODEBUFF_APP_URL}/login`,
60 )
61 }
62
63 const [cardPaymentMethods, linkPaymentMethods] = await Promise.all([
64 stripeServer.paymentMethods.list({
65 customer: user.stripe_customer_id,
66 type: 'card',
67 }),
68 stripeServer.paymentMethods.list({
69 customer: user.stripe_customer_id,
70 type: 'link',
71 }),
72 ])
73
74 const allPaymentMethods = [
75 ...cardPaymentMethods.data,
76 ...linkPaymentMethods.data,
77 ]
78
79 const validPaymentMethod = allPaymentMethods.find((pm) => {
80 // For card payment methods, check expiration
81 if (pm.type === 'card') {
82 return (
83 pm.card?.exp_year &&
84 pm.card.exp_month &&
85 new Date(pm.card.exp_year, pm.card.exp_month - 1) > new Date()
86 )
87 }
88 // For link payment methods, they're always valid if they exist
89 if (pm.type === 'link') {
90 return true
91 }
92 return false
93 })
94
95 if (!validPaymentMethod) {
96 throw new AutoTopupValidationError(
97 'You need a valid payment method to enable auto top-up. Try buying some credits!',
98 )
99 }
100

Callers 2

GETFunction · 0.90
checkAndTriggerAutoTopupFunction · 0.85

Calls 1

disableAutoTopupFunction · 0.85

Tested by

no test coverage detected