|
| 1 | +import { db } from '@sim/db' |
| 2 | +import { user } from '@sim/db/schema' |
| 3 | +import { createLogger } from '@sim/logger' |
| 4 | +import { eq } from 'drizzle-orm' |
| 5 | +import { type NextRequest, NextResponse } from 'next/server' |
| 6 | +import { getInvoicesContract } from '@/lib/api/contracts/subscription' |
| 7 | +import { parseRequest } from '@/lib/api/server' |
| 8 | +import { getSession } from '@/lib/auth' |
| 9 | +import { getOrganizationSubscription } from '@/lib/billing/core/billing' |
| 10 | +import { isOrganizationOwnerOrAdmin } from '@/lib/billing/core/organization' |
| 11 | +import { getStripeClient } from '@/lib/billing/stripe-client' |
| 12 | +import { withRouteHandler } from '@/lib/core/utils/with-route-handler' |
| 13 | + |
| 14 | +const logger = createLogger('BillingInvoices') |
| 15 | + |
| 16 | +/** Cap the number of invoices returned to the most recent statements. */ |
| 17 | +const MAX_INVOICES = 12 |
| 18 | + |
| 19 | +/** |
| 20 | + * Lists finalized Stripe invoices for the caller's billing customer (personal |
| 21 | + * or organization-scoped). Returns an empty list when there is no Stripe |
| 22 | + * customer yet or when Stripe is not configured, so the UI can simply hide the |
| 23 | + * Invoices section instead of surfacing an error. |
| 24 | + */ |
| 25 | +export const GET = withRouteHandler(async (request: NextRequest) => { |
| 26 | + const session = await getSession() |
| 27 | + if (!session?.user?.id) { |
| 28 | + return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) |
| 29 | + } |
| 30 | + |
| 31 | + const parsed = await parseRequest(getInvoicesContract, request, {}) |
| 32 | + if (!parsed.success) return parsed.response |
| 33 | + |
| 34 | + const { context, organizationId } = parsed.data.query |
| 35 | + |
| 36 | + if (context === 'organization' && !organizationId) { |
| 37 | + return NextResponse.json( |
| 38 | + { error: 'organizationId is required when context=organization' }, |
| 39 | + { status: 400 } |
| 40 | + ) |
| 41 | + } |
| 42 | + |
| 43 | + let stripeCustomerId: string | null = null |
| 44 | + |
| 45 | + if (context === 'organization') { |
| 46 | + const hasPermission = await isOrganizationOwnerOrAdmin(session.user.id, organizationId!) |
| 47 | + if (!hasPermission) { |
| 48 | + return NextResponse.json({ error: 'Permission denied' }, { status: 403 }) |
| 49 | + } |
| 50 | + |
| 51 | + // Resolve the org's customer via the canonical resolver so we deterministically |
| 52 | + // pick the same subscription (most recent entitled, ordered) the rest of the |
| 53 | + // billing UI uses — a bare limit(1) here could select a stale row. |
| 54 | + const orgSubscription = await getOrganizationSubscription(organizationId!) |
| 55 | + stripeCustomerId = orgSubscription?.stripeCustomerId ?? null |
| 56 | + } else { |
| 57 | + const rows = await db |
| 58 | + .select({ customer: user.stripeCustomerId }) |
| 59 | + .from(user) |
| 60 | + .where(eq(user.id, session.user.id)) |
| 61 | + .limit(1) |
| 62 | + |
| 63 | + stripeCustomerId = rows.length > 0 ? rows[0].customer || null : null |
| 64 | + } |
| 65 | + |
| 66 | + const stripe = getStripeClient() |
| 67 | + if (!stripeCustomerId || !stripe) { |
| 68 | + return NextResponse.json({ success: true, invoices: [], hasMore: false }) |
| 69 | + } |
| 70 | + |
| 71 | + try { |
| 72 | + const result = await stripe.invoices.list({ customer: stripeCustomerId, limit: MAX_INVOICES }) |
| 73 | + |
| 74 | + const invoices = result.data |
| 75 | + .filter((invoice) => invoice.id && invoice.status && invoice.status !== 'draft') |
| 76 | + .map((invoice) => ({ |
| 77 | + id: invoice.id as string, |
| 78 | + number: invoice.number ?? null, |
| 79 | + created: invoice.created, |
| 80 | + total: invoice.total, |
| 81 | + amountPaid: invoice.amount_paid, |
| 82 | + currency: invoice.currency, |
| 83 | + status: invoice.status ?? null, |
| 84 | + hostedInvoiceUrl: invoice.hosted_invoice_url ?? null, |
| 85 | + invoicePdf: invoice.invoice_pdf ?? null, |
| 86 | + })) |
| 87 | + |
| 88 | + return NextResponse.json({ success: true, invoices, hasMore: result.has_more }) |
| 89 | + } catch (error) { |
| 90 | + logger.error('Failed to list invoices', { error, userId: session.user.id, context }) |
| 91 | + return NextResponse.json({ error: 'Failed to list invoices' }, { status: 500 }) |
| 92 | + } |
| 93 | +}) |
0 commit comments