Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/__tests__/services/gift-service.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { stripe } from '@/lib/stripe-server'
import { GiftService } from '@/pages/api/stripe/services/gift-service'
import { describe, expect, it, vi } from 'vitest'

vi.mock('@/lib/stripe-server', () => ({
stripe: {
checkout: { sessions: { list: vi.fn().mockResolvedValue({ data: [] }) } },
customers: { createBalanceTransaction: vi.fn() },
},
}))

const tx: any = {
user: { findUnique: vi.fn() },
giftTransaction: { findFirst: vi.fn() },
subscription: { updateMany: vi.fn() },
}

describe('GiftService.processGiftRefund', () => {
it('returns early when no refund amount', async () => {
const service = new GiftService(tx)
const charge: any = { amount_refunded: 0 }
await service.processGiftRefund(charge)
expect(stripe.checkout.sessions.list).not.toHaveBeenCalled()
})
})
17 changes: 17 additions & 0 deletions src/__tests__/services/subscription-service.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { SubscriptionService } from '@/pages/api/stripe/services/subscription-service'
import { SubscriptionStatus } from '@prisma/client'
import { describe, expect, it } from 'vitest'

describe('SubscriptionService.mapStripeStatus', () => {
it('maps active status', () => {
expect(SubscriptionService.mapStripeStatus('active')).toBe(SubscriptionStatus.ACTIVE)
})

it('maps trialing status', () => {
expect(SubscriptionService.mapStripeStatus('trialing')).toBe(SubscriptionStatus.TRIALING)
})

it('maps unknown status to canceled', () => {
expect(SubscriptionService.mapStripeStatus('unknown')).toBe(SubscriptionStatus.CANCELED)
})
})
85 changes: 3 additions & 82 deletions src/pages/api/stripe/create-checkout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { GRACE_PERIOD_END, getSubscription, isInGracePeriod } from '@/utils/subs
import { Prisma, type TransactionType } from '@prisma/client'
import type { NextApiRequest, NextApiResponse } from 'next'
import type Stripe from 'stripe'
import { CustomerService } from './services/customer-service'

// Add crypto as a supported payment method type
type ExtendedPaymentMethodType = Stripe.Checkout.SessionCreateParams.PaymentMethodType | 'crypto'
Expand Down Expand Up @@ -49,7 +50,8 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
// Handle customer and subscription logic in a transaction
const checkoutUrl = await prisma.$transaction(
async (tx) => {
const customerId = await ensureCustomer(session.user, tx)
const customerService = new CustomerService(tx)
const customerId = await customerService.ensureCustomer(session.user)
const subscriptionData = await getSubscription(session.user.id, tx)
return await createCheckoutSession({
customerId,
Expand Down Expand Up @@ -82,87 +84,6 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
}
}

async function ensureCustomer(
user: {
id: string
email?: string | null
name?: string | null
image?: string | null
locale?: string | null
twitchId?: string | null
},
tx: Prisma.TransactionClient,
): Promise<string> {
// Look for any existing subscription to get a customer ID
const subscription = await tx.subscription.findFirst({
where: { userId: user.id },
select: { stripeCustomerId: true },
orderBy: { createdAt: 'desc' }, // Use the most recent subscription
})

let customerId = subscription?.stripeCustomerId

// Verify existing customer
if (customerId) {
try {
await stripe.customers.retrieve(customerId)
} catch (error) {
console.error('Invalid customer ID found:', error)
customerId = null
}
}

// Create or find customer if needed
if (!customerId && user.email) {
const existingCustomers = await stripe.customers.list({
email: user.email,
limit: 1,
})

if (existingCustomers.data.length > 0) {
customerId = existingCustomers.data[0].id
} else {
const newCustomer = await createStripeCustomer(user)
customerId = newCustomer.id
}

if (!subscription?.stripeCustomerId) {
// Update existing subscriptions with no customer ID
await tx.subscription.updateMany({
where: { userId: user.id, stripeCustomerId: null },
data: { stripeCustomerId: customerId, updatedAt: new Date() },
})
}
}

if (!customerId) {
throw new Error('Unable to establish customer ID')
}

return customerId
}

async function createStripeCustomer(user: {
id: string
email?: string | null
name?: string | null
image?: string | null
locale?: string | null
twitchId?: string | null
}) {
return stripe.customers.create({
email: user.email ?? undefined,
metadata: {
userId: user.id,
email: user.email ?? '',
name: user.name ?? '',
image: user.image ?? '',
locale: user.locale ?? '',
twitchId: user.twitchId ?? '',
},
})
}

interface CheckoutSessionParams {
customerId: string
priceId: string
Expand Down
Loading