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

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

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                                                                     
import { NextResponse } from 'next/server'
import { withAuth } from '@/lib/auth/withAuth'
import { getStripe } 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/portal
 *
 * Create a Stripe Customer Portal session for managing subscription.
 */
export const POST = withAuth(
  async (_request, { userId }) => {
    const sub = await db
      .select({ stripeCustomerId: schema.subscriptions.stripeCustomerId })
      .from(schema.subscriptions)
      .where(eq(schema.subscriptions.userId, userId))
      .get()

    if (!sub?.stripeCustomerId) {
      return NextResponse.json({ error: 'No billing account found' }, { status: 404 })
    }

    const session = await getStripe().billingPortal.sessions.create({
      customer: sub.stripeCustomerId,
      return_url: `${APP_URL}/settings`,
    })

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