All files / web/src/app/api/billing/checkout route.ts

0% Statements 0/49
0% Branches 0/1
0% Functions 0/1
0% Lines 0/49

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50                                                                                                   
import { NextResponse } from 'next/server'
import { withAuth } from '@/lib/auth/withAuth'
import { getStripe, getActivePricing } from '@/lib/stripe'
import { eq } from 'drizzle-orm'
import { db, schema } from '@/db'

const APP_URL = process.env.NEXT_PUBLIC_APP_URL || 'https://abaci.one'

/**
 * POST /api/billing/checkout
 *
 * Create a Stripe Checkout session for the Family plan.
 * Body: { interval: 'month' | 'year' }
 */
export const POST = withAuth(
  async (request, { userId, userEmail }) => {
    const { interval = 'month' } = await request.json()

    const pricing = await getActivePricing()
    const priceId =
      interval === 'year' ? pricing.family.annual.priceId : pricing.family.monthly.priceId
    if (!priceId) {
      return NextResponse.json({ error: 'Stripe price not configured' }, { status: 500 })
    }

    // Check if user already has a Stripe customer ID
    const existing = await db
      .select({ stripeCustomerId: schema.subscriptions.stripeCustomerId })
      .from(schema.subscriptions)
      .where(eq(schema.subscriptions.userId, userId))
      .get()

    const session = await getStripe().checkout.sessions.create({
      mode: 'subscription',
      payment_method_types: ['card'],
      line_items: [{ price: priceId, quantity: 1 }],
      success_url: `${APP_URL}/settings?billing=success&session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${APP_URL}/settings?billing=canceled`,
      client_reference_id: userId,
      ...(existing?.stripeCustomerId
        ? { customer: existing.stripeCustomerId }
        : { customer_email: userEmail || undefined }),
      metadata: { userId },
    })

    return NextResponse.json({ url: session.url })
  },
  { role: 'user' }
)