chore: import upstream snapshot with attribution
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,110 @@
|
||||
/**
|
||||
* @vitest-environment node
|
||||
*/
|
||||
import { createMockRequest, dbChainMock, dbChainMockFns } from '@sim/testing'
|
||||
import { generateShortId } from '@sim/utils/id'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { mockGetSession, mockGetStripeClient, mockStripeInvoicesList } = vi.hoisted(() => ({
|
||||
mockGetSession: vi.fn(),
|
||||
mockGetStripeClient: vi.fn(),
|
||||
mockStripeInvoicesList: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@sim/db', () => dbChainMock)
|
||||
|
||||
vi.mock('@/lib/auth', () => ({
|
||||
auth: { api: { getSession: vi.fn() } },
|
||||
getSession: mockGetSession,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/billing/stripe-client', () => ({
|
||||
getStripeClient: mockGetStripeClient,
|
||||
}))
|
||||
|
||||
import { GET } from '@/app/api/billing/invoices/route'
|
||||
|
||||
function makeInvoice(overrides: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: `in_${generateShortId()}`,
|
||||
number: 'INV-1',
|
||||
created: 1700000000,
|
||||
total: 1000,
|
||||
amount_paid: 1000,
|
||||
currency: 'usd',
|
||||
status: 'paid',
|
||||
hosted_invoice_url: 'https://stripe.test/invoice',
|
||||
invoice_pdf: 'https://stripe.test/invoice.pdf',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('GET /api/billing/invoices', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockGetSession.mockResolvedValue({ user: { id: 'user-1' } })
|
||||
dbChainMockFns.limit.mockResolvedValue([{ customer: 'cus_1' }])
|
||||
mockGetStripeClient.mockReturnValue({ invoices: { list: mockStripeInvoicesList } })
|
||||
})
|
||||
|
||||
it('does not surface hasMore when the trailing raw invoice beyond MAX_INVOICES is a draft', async () => {
|
||||
const finalized = Array.from({ length: 10 }, () => makeInvoice())
|
||||
mockStripeInvoicesList.mockResolvedValueOnce({
|
||||
data: [...finalized, makeInvoice({ status: 'draft' })],
|
||||
has_more: false,
|
||||
})
|
||||
|
||||
const request = createMockRequest('GET')
|
||||
const response = await GET(request)
|
||||
const body = await response.json()
|
||||
|
||||
expect(body.invoices).toHaveLength(10)
|
||||
expect(body.hasMore).toBe(false)
|
||||
})
|
||||
|
||||
it('reports hasMore when there are genuinely more finalized invoices', async () => {
|
||||
const finalized = Array.from({ length: 11 }, () => makeInvoice())
|
||||
mockStripeInvoicesList.mockResolvedValueOnce({ data: finalized, has_more: false })
|
||||
|
||||
const request = createMockRequest('GET')
|
||||
const response = await GET(request)
|
||||
const body = await response.json()
|
||||
|
||||
expect(body.invoices).toHaveLength(10)
|
||||
expect(body.hasMore).toBe(true)
|
||||
})
|
||||
|
||||
it('pages through further drafts to confirm hasMore when the first page is inconclusive', async () => {
|
||||
const firstPage = Array.from({ length: 11 }, () => makeInvoice({ status: 'draft' }))
|
||||
mockStripeInvoicesList
|
||||
.mockResolvedValueOnce({ data: firstPage, has_more: true })
|
||||
.mockResolvedValueOnce({ data: [makeInvoice()], has_more: false })
|
||||
|
||||
const request = createMockRequest('GET')
|
||||
const response = await GET(request)
|
||||
const body = await response.json()
|
||||
|
||||
expect(mockStripeInvoicesList).toHaveBeenCalledTimes(2)
|
||||
expect(mockStripeInvoicesList).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({ starting_after: firstPage.at(-1)?.id })
|
||||
)
|
||||
expect(body.invoices).toHaveLength(1)
|
||||
expect(body.hasMore).toBe(false)
|
||||
})
|
||||
|
||||
it('reports hasMore when the MAX_STRIPE_PAGES safety cap is hit while Stripe still has more', async () => {
|
||||
mockStripeInvoicesList.mockResolvedValue({
|
||||
data: Array.from({ length: 11 }, () => makeInvoice({ status: 'draft' })),
|
||||
has_more: true,
|
||||
})
|
||||
|
||||
const request = createMockRequest('GET')
|
||||
const response = await GET(request)
|
||||
const body = await response.json()
|
||||
|
||||
expect(mockStripeInvoicesList).toHaveBeenCalledTimes(5)
|
||||
expect(body.invoices).toHaveLength(0)
|
||||
expect(body.hasMore).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,150 @@
|
||||
import { db } from '@sim/db'
|
||||
import { user } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import type Stripe from 'stripe'
|
||||
import { getInvoicesContract } from '@/lib/api/contracts/subscription'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { getSession } from '@/lib/auth'
|
||||
import { getOrganizationSubscription } from '@/lib/billing/core/billing'
|
||||
import { isOrganizationOwnerOrAdmin } from '@/lib/billing/core/organization'
|
||||
import { getStripeClient } from '@/lib/billing/stripe-client'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
|
||||
const logger = createLogger('BillingInvoices')
|
||||
|
||||
/** Cap the number of invoices returned to the most recent statements. */
|
||||
const MAX_INVOICES = 10
|
||||
|
||||
/** Stripe page size when scanning for finalized invoices; also bounds the has-more probe. */
|
||||
const STRIPE_PAGE_SIZE = MAX_INVOICES + 1
|
||||
|
||||
/** Safety cap on pagination when a customer has many draft invoices interspersed. */
|
||||
const MAX_STRIPE_PAGES = 5
|
||||
|
||||
interface FinalizedInvoicesPage {
|
||||
invoices: Stripe.Invoice[]
|
||||
/**
|
||||
* Whether Stripe's raw cursor still had more records after the scan
|
||||
* stopped — either because `invoices.length` became conclusive, or the
|
||||
* `MAX_STRIPE_PAGES` safety cap was hit first. Callers must OR this into
|
||||
* `hasMore` so hitting the cap never silently hides a "View all" that a
|
||||
* customer with many consecutive drafts genuinely has.
|
||||
*/
|
||||
stripeHasMore: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Pages through a customer's Stripe invoices, keeping only finalized ones,
|
||||
* until either more than `MAX_INVOICES` have been collected or Stripe's list
|
||||
* is exhausted (bounded by `MAX_STRIPE_PAGES`).
|
||||
*
|
||||
* Stripe's raw pagination cursor (`has_more`) counts draft invoices, which
|
||||
* the caller filters out — so a single page can under-report finalized
|
||||
* invoices while `has_more` is still true. Paging until the finalized count
|
||||
* is conclusive is what lets the caller derive an accurate `hasMore` for the
|
||||
* "View all" affordance.
|
||||
*/
|
||||
async function collectFinalizedInvoices(
|
||||
stripe: Stripe,
|
||||
stripeCustomerId: string
|
||||
): Promise<FinalizedInvoicesPage> {
|
||||
const invoices: Stripe.Invoice[] = []
|
||||
let startingAfter: string | undefined
|
||||
let stripeHasMore = true
|
||||
|
||||
for (
|
||||
let page = 0;
|
||||
page < MAX_STRIPE_PAGES && stripeHasMore && invoices.length <= MAX_INVOICES;
|
||||
page++
|
||||
) {
|
||||
const result = await stripe.invoices.list({
|
||||
customer: stripeCustomerId,
|
||||
limit: STRIPE_PAGE_SIZE,
|
||||
starting_after: startingAfter,
|
||||
})
|
||||
|
||||
invoices.push(
|
||||
...result.data.filter((invoice) => invoice.id && invoice.status && invoice.status !== 'draft')
|
||||
)
|
||||
stripeHasMore = result.has_more
|
||||
startingAfter = result.data.at(-1)?.id
|
||||
}
|
||||
|
||||
return { invoices, stripeHasMore }
|
||||
}
|
||||
|
||||
/**
|
||||
* Lists finalized Stripe invoices for the caller's billing customer (personal
|
||||
* or organization-scoped). Returns an empty list when there is no Stripe
|
||||
* customer yet or when Stripe is not configured, so the UI can simply hide the
|
||||
* Invoices section instead of surfacing an error.
|
||||
*/
|
||||
export const GET = withRouteHandler(async (request: NextRequest) => {
|
||||
const session = await getSession()
|
||||
if (!session?.user?.id) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
}
|
||||
|
||||
const parsed = await parseRequest(getInvoicesContract, request, {})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { context, organizationId } = parsed.data.query
|
||||
|
||||
if (context === 'organization' && !organizationId) {
|
||||
return NextResponse.json(
|
||||
{ error: 'organizationId is required when context=organization' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
let stripeCustomerId: string | null = null
|
||||
|
||||
if (context === 'organization') {
|
||||
const hasPermission = await isOrganizationOwnerOrAdmin(session.user.id, organizationId!)
|
||||
if (!hasPermission) {
|
||||
return NextResponse.json({ error: 'Permission denied' }, { status: 403 })
|
||||
}
|
||||
|
||||
// Resolve the org's customer via the canonical resolver so we deterministically
|
||||
// pick the same subscription (most recent entitled, ordered) the rest of the
|
||||
// billing UI uses — a bare limit(1) here could select a stale row.
|
||||
const orgSubscription = await getOrganizationSubscription(organizationId!)
|
||||
stripeCustomerId = orgSubscription?.stripeCustomerId ?? null
|
||||
} else {
|
||||
const rows = await db
|
||||
.select({ customer: user.stripeCustomerId })
|
||||
.from(user)
|
||||
.where(eq(user.id, session.user.id))
|
||||
.limit(1)
|
||||
|
||||
stripeCustomerId = rows.length > 0 ? rows[0].customer || null : null
|
||||
}
|
||||
|
||||
const stripe = getStripeClient()
|
||||
if (!stripeCustomerId || !stripe) {
|
||||
return NextResponse.json({ success: true, invoices: [], hasMore: false })
|
||||
}
|
||||
|
||||
try {
|
||||
const finalized = await collectFinalizedInvoices(stripe, stripeCustomerId)
|
||||
const hasMore = finalized.invoices.length > MAX_INVOICES || finalized.stripeHasMore
|
||||
const invoices = finalized.invoices.slice(0, MAX_INVOICES).map((invoice) => ({
|
||||
id: invoice.id as string,
|
||||
number: invoice.number ?? null,
|
||||
created: invoice.created,
|
||||
total: invoice.total,
|
||||
amountPaid: invoice.amount_paid,
|
||||
currency: invoice.currency,
|
||||
status: invoice.status ?? null,
|
||||
hostedInvoiceUrl: invoice.hosted_invoice_url ?? null,
|
||||
invoicePdf: invoice.invoice_pdf ?? null,
|
||||
}))
|
||||
|
||||
return NextResponse.json({ success: true, invoices, hasMore })
|
||||
} catch (error) {
|
||||
logger.error('Failed to list invoices', { error, userId: session.user.id, context })
|
||||
return NextResponse.json({ error: 'Failed to list invoices' }, { status: 500 })
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user