|
| 1 | +import { AnalyticsEvent } from '@codebuff/common/constants/analytics-events' |
| 2 | +import { INVALID_AUTH_TOKEN_MESSAGE } from '@codebuff/common/old-constants' |
| 3 | +import { NextResponse } from 'next/server' |
| 4 | +import { z } from 'zod/v4' |
| 5 | + |
| 6 | +import type { TrackEventFn } from '@codebuff/common/types/contracts/analytics' |
| 7 | +import type { |
| 8 | + GetUserInfoFromApiKeyFn, |
| 9 | +} from '@codebuff/common/types/contracts/database' |
| 10 | +import type { Logger } from '@codebuff/common/types/contracts/logger' |
| 11 | +import type { NextRequest } from 'next/server' |
| 12 | + |
| 13 | +import type { GetOrganizationUsageResponseFn, GetUserUsageDataFn } from '@codebuff/common/types/contracts/billing' |
| 14 | + |
| 15 | +const usageRequestSchema = z.object({ |
| 16 | + fingerprintId: z.string(), |
| 17 | + authToken: z.string().optional(), |
| 18 | + orgId: z.string().optional(), |
| 19 | +}) |
| 20 | + |
| 21 | +export async function postUsage(params: { |
| 22 | + req: NextRequest |
| 23 | + getUserInfoFromApiKey: GetUserInfoFromApiKeyFn |
| 24 | + getUserUsageData: GetUserUsageDataFn |
| 25 | + getOrganizationUsageResponse: GetOrganizationUsageResponseFn |
| 26 | + trackEvent: TrackEventFn |
| 27 | + logger: Logger |
| 28 | +}) { |
| 29 | + const { |
| 30 | + req, |
| 31 | + getUserInfoFromApiKey, |
| 32 | + getUserUsageData, |
| 33 | + getOrganizationUsageResponse, |
| 34 | + trackEvent, |
| 35 | + logger, |
| 36 | + } = params |
| 37 | + |
| 38 | + try { |
| 39 | + let body: unknown |
| 40 | + try { |
| 41 | + body = await req.json() |
| 42 | + } catch (error) { |
| 43 | + return NextResponse.json( |
| 44 | + { message: 'Invalid JSON in request body' }, |
| 45 | + { status: 400 }, |
| 46 | + ) |
| 47 | + } |
| 48 | + |
| 49 | + const parseResult = usageRequestSchema.safeParse(body) |
| 50 | + if (!parseResult.success) { |
| 51 | + return NextResponse.json( |
| 52 | + { message: 'Invalid request body', issues: parseResult.error.issues }, |
| 53 | + { status: 400 }, |
| 54 | + ) |
| 55 | + } |
| 56 | + |
| 57 | + const { fingerprintId, authToken, orgId } = parseResult.data |
| 58 | + |
| 59 | + if (!authToken) { |
| 60 | + return NextResponse.json( |
| 61 | + { message: 'Authentication required' }, |
| 62 | + { status: 401 }, |
| 63 | + ) |
| 64 | + } |
| 65 | + |
| 66 | + const userInfo = await getUserInfoFromApiKey({ |
| 67 | + apiKey: authToken, |
| 68 | + fields: ['id'], |
| 69 | + logger, |
| 70 | + }) |
| 71 | + |
| 72 | + if (!userInfo) { |
| 73 | + trackEvent({ |
| 74 | + event: AnalyticsEvent.USAGE_API_AUTH_ERROR, |
| 75 | + userId: 'unknown', |
| 76 | + properties: { |
| 77 | + reason: 'Invalid API key', |
| 78 | + }, |
| 79 | + logger, |
| 80 | + }) |
| 81 | + return NextResponse.json( |
| 82 | + { message: INVALID_AUTH_TOKEN_MESSAGE }, |
| 83 | + { status: 401 }, |
| 84 | + ) |
| 85 | + } |
| 86 | + |
| 87 | + const userId = userInfo.id |
| 88 | + |
| 89 | + trackEvent({ |
| 90 | + event: AnalyticsEvent.USAGE_API_REQUEST, |
| 91 | + userId, |
| 92 | + properties: { |
| 93 | + fingerprintId, |
| 94 | + hasOrgId: !!orgId, |
| 95 | + }, |
| 96 | + logger, |
| 97 | + }) |
| 98 | + |
| 99 | + // If orgId is provided, return organization usage data |
| 100 | + if (orgId) { |
| 101 | + try { |
| 102 | + const orgUsageResponse = await getOrganizationUsageResponse({ |
| 103 | + organizationId: orgId, |
| 104 | + userId, |
| 105 | + logger, |
| 106 | + }) |
| 107 | + return NextResponse.json(orgUsageResponse) |
| 108 | + } catch (error) { |
| 109 | + logger.error( |
| 110 | + { error, orgId, userId }, |
| 111 | + 'Error fetching organization usage', |
| 112 | + ) |
| 113 | + // If organization usage fails, fall back to personal usage |
| 114 | + logger.info( |
| 115 | + { orgId, userId }, |
| 116 | + 'Falling back to personal usage due to organization error', |
| 117 | + ) |
| 118 | + } |
| 119 | + } |
| 120 | + |
| 121 | + // Return personal usage data (default behavior) |
| 122 | + const usageData = await getUserUsageData({ userId, logger }) |
| 123 | + |
| 124 | + // Format response to match backend API format |
| 125 | + const usageResponse = { |
| 126 | + type: 'usage-response' as const, |
| 127 | + usage: usageData.usageThisCycle, |
| 128 | + remainingBalance: usageData.balance.totalRemaining, |
| 129 | + balanceBreakdown: usageData.balance.breakdown, |
| 130 | + next_quota_reset: usageData.nextQuotaReset, |
| 131 | + } |
| 132 | + |
| 133 | + return NextResponse.json(usageResponse) |
| 134 | + } catch (error) { |
| 135 | + logger.error({ error }, 'Error handling /api/v1/usage request') |
| 136 | + return NextResponse.json( |
| 137 | + { error: 'Internal server error' }, |
| 138 | + { status: 500 }, |
| 139 | + ) |
| 140 | + } |
| 141 | +} |
0 commit comments