|
| 1 | +import { NextRequest, NextResponse } from 'next/server'; |
| 2 | +import { getAdminFirestore } from '../../../firebase/admin'; |
| 3 | +import { getCollectionName } from '../../../utils/environmentConfig'; |
| 4 | +import { createApiResponse, createErrorResponse } from '../../../utils/apiUtils'; |
| 5 | + |
| 6 | +interface TokenAnalyticsData { |
| 7 | + unfundedLoggedOut: { |
| 8 | + totalTokens: number; |
| 9 | + totalUsdValue: number; |
| 10 | + allocations: number; |
| 11 | + }; |
| 12 | + unfundedLoggedIn: { |
| 13 | + totalTokens: number; |
| 14 | + totalUsdValue: number; |
| 15 | + allocations: number; |
| 16 | + }; |
| 17 | + funded: { |
| 18 | + totalTokens: number; |
| 19 | + totalUsdValue: number; |
| 20 | + allocations: number; |
| 21 | + }; |
| 22 | + totalSubscriptionRevenue: number; |
| 23 | + totalWriterPayouts: number; |
| 24 | + platformFeeRevenue: number; |
| 25 | +} |
| 26 | + |
| 27 | +interface DateRange { |
| 28 | + startDate: Date; |
| 29 | + endDate: Date; |
| 30 | +} |
| 31 | + |
| 32 | +export async function GET(request: NextRequest) { |
| 33 | + try { |
| 34 | + const { searchParams } = new URL(request.url); |
| 35 | + const startDate = searchParams.get('startDate'); |
| 36 | + const endDate = searchParams.get('endDate'); |
| 37 | + |
| 38 | + if (!startDate || !endDate) { |
| 39 | + return createErrorResponse('BAD_REQUEST', 'startDate and endDate are required'); |
| 40 | + } |
| 41 | + |
| 42 | + const dateRange: DateRange = { |
| 43 | + startDate: new Date(startDate), |
| 44 | + endDate: new Date(endDate) |
| 45 | + }; |
| 46 | + |
| 47 | + console.log('🔍 [Token Analytics] Fetching token analytics data...', dateRange); |
| 48 | + |
| 49 | + const db = getAdminFirestore(); |
| 50 | + const analytics = await getTokenAnalytics(db, dateRange); |
| 51 | + |
| 52 | + return createApiResponse({ |
| 53 | + success: true, |
| 54 | + data: analytics, |
| 55 | + dateRange: { |
| 56 | + startDate: dateRange.startDate.toISOString(), |
| 57 | + endDate: dateRange.endDate.toISOString() |
| 58 | + } |
| 59 | + }); |
| 60 | + |
| 61 | + } catch (error) { |
| 62 | + console.error('Error fetching token analytics:', error); |
| 63 | + return createErrorResponse('INTERNAL_ERROR', 'Failed to fetch token analytics'); |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +async function getTokenAnalytics(db: any, dateRange: DateRange): Promise<TokenAnalyticsData> { |
| 68 | + console.log('🔍 [Token Analytics] Starting comprehensive token analytics calculation...'); |
| 69 | + |
| 70 | + // Initialize analytics data |
| 71 | + const analytics: TokenAnalyticsData = { |
| 72 | + unfundedLoggedOut: { totalTokens: 0, totalUsdValue: 0, allocations: 0 }, |
| 73 | + unfundedLoggedIn: { totalTokens: 0, totalUsdValue: 0, allocations: 0 }, |
| 74 | + funded: { totalTokens: 0, totalUsdValue: 0, allocations: 0 }, |
| 75 | + totalSubscriptionRevenue: 0, |
| 76 | + totalWriterPayouts: 0, |
| 77 | + platformFeeRevenue: 0 |
| 78 | + }; |
| 79 | + |
| 80 | + try { |
| 81 | + // 1. Get unfunded tokens from logged-out users (simulated tokens) |
| 82 | + // Note: This data is stored in localStorage, so we can't query it directly |
| 83 | + // We'll need to estimate based on analytics events or provide a separate endpoint |
| 84 | + console.log('📊 [Token Analytics] Calculating unfunded logged-out tokens...'); |
| 85 | + // For now, we'll set this to 0 and add a TODO to implement proper tracking |
| 86 | + analytics.unfundedLoggedOut = { totalTokens: 0, totalUsdValue: 0, allocations: 0 }; |
| 87 | + |
| 88 | + // 2. Get unfunded tokens from logged-in users without subscriptions |
| 89 | + console.log('📊 [Token Analytics] Calculating unfunded logged-in tokens...'); |
| 90 | + const unfundedLoggedIn = await getUnfundedLoggedInTokens(db, dateRange); |
| 91 | + analytics.unfundedLoggedIn = unfundedLoggedIn; |
| 92 | + |
| 93 | + // 3. Get funded token allocations |
| 94 | + console.log('📊 [Token Analytics] Calculating funded token allocations...'); |
| 95 | + const fundedTokens = await getFundedTokenAllocations(db, dateRange); |
| 96 | + analytics.funded = fundedTokens; |
| 97 | + |
| 98 | + // 4. Get total subscription revenue |
| 99 | + console.log('📊 [Token Analytics] Calculating subscription revenue...'); |
| 100 | + const subscriptionRevenue = await getSubscriptionRevenue(db, dateRange); |
| 101 | + analytics.totalSubscriptionRevenue = subscriptionRevenue; |
| 102 | + |
| 103 | + // 5. Get total writer payouts |
| 104 | + console.log('📊 [Token Analytics] Calculating writer payouts...'); |
| 105 | + const writerPayouts = await getWriterPayouts(db, dateRange); |
| 106 | + analytics.totalWriterPayouts = writerPayouts; |
| 107 | + |
| 108 | + // 6. Calculate platform fee revenue (7% of writer payouts) |
| 109 | + console.log('📊 [Token Analytics] Calculating platform fee revenue...'); |
| 110 | + analytics.platformFeeRevenue = writerPayouts * 0.07; |
| 111 | + |
| 112 | + console.log('✅ [Token Analytics] Analytics calculation completed:', analytics); |
| 113 | + return analytics; |
| 114 | + |
| 115 | + } catch (error) { |
| 116 | + console.error('❌ [Token Analytics] Error calculating analytics:', error); |
| 117 | + throw error; |
| 118 | + } |
| 119 | +} |
| 120 | + |
| 121 | +async function getUnfundedLoggedInTokens(db: any, dateRange: DateRange) { |
| 122 | + try { |
| 123 | + // Query token allocations and cross-reference with user subscription status |
| 124 | + const tokenAllocationsRef = db.collection(getCollectionName('tokenAllocations')); |
| 125 | + const allocationsSnapshot = await tokenAllocationsRef |
| 126 | + .where('createdAt', '>=', dateRange.startDate) |
| 127 | + .where('createdAt', '<=', dateRange.endDate) |
| 128 | + .get(); |
| 129 | + |
| 130 | + let totalTokens = 0; |
| 131 | + let allocations = 0; |
| 132 | + |
| 133 | + // Process each allocation and check if the user had an active subscription |
| 134 | + for (const doc of allocationsSnapshot.docs) { |
| 135 | + const allocation = doc.data(); |
| 136 | + const userId = allocation.userId; |
| 137 | + const allocationDate = allocation.createdAt?.toDate() || new Date(); |
| 138 | + |
| 139 | + // Check if user had active subscription at time of allocation |
| 140 | + const subscriptionsRef = db.collection(getCollectionName('subscriptions')); |
| 141 | + const userSubscriptionsSnapshot = await subscriptionsRef |
| 142 | + .where('userId', '==', userId) |
| 143 | + .where('status', 'in', ['active', 'past_due']) |
| 144 | + .where('currentPeriodStart', '<=', allocationDate) |
| 145 | + .where('currentPeriodEnd', '>=', allocationDate) |
| 146 | + .get(); |
| 147 | + |
| 148 | + // If no active subscription at time of allocation, it's unfunded |
| 149 | + if (userSubscriptionsSnapshot.empty) { |
| 150 | + totalTokens += allocation.tokens || 0; |
| 151 | + allocations++; |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + return { |
| 156 | + totalTokens, |
| 157 | + totalUsdValue: totalTokens * 0.1, // 10 tokens = $1 |
| 158 | + allocations |
| 159 | + }; |
| 160 | + } catch (error) { |
| 161 | + console.error('Error calculating unfunded logged-in tokens:', error); |
| 162 | + return { totalTokens: 0, totalUsdValue: 0, allocations: 0 }; |
| 163 | + } |
| 164 | +} |
| 165 | + |
| 166 | +async function getFundedTokenAllocations(db: any, dateRange: DateRange) { |
| 167 | + try { |
| 168 | + const tokenAllocationsRef = db.collection(getCollectionName('tokenAllocations')); |
| 169 | + const allocationsSnapshot = await tokenAllocationsRef |
| 170 | + .where('createdAt', '>=', dateRange.startDate) |
| 171 | + .where('createdAt', '<=', dateRange.endDate) |
| 172 | + .where('status', '==', 'active') |
| 173 | + .get(); |
| 174 | + |
| 175 | + let totalTokens = 0; |
| 176 | + let allocations = 0; |
| 177 | + |
| 178 | + // Process each allocation and check if the user had an active subscription |
| 179 | + for (const doc of allocationsSnapshot.docs) { |
| 180 | + const allocation = doc.data(); |
| 181 | + const userId = allocation.userId; |
| 182 | + const allocationDate = allocation.createdAt?.toDate() || new Date(); |
| 183 | + |
| 184 | + // Check if user had active subscription at time of allocation |
| 185 | + const subscriptionsRef = db.collection(getCollectionName('subscriptions')); |
| 186 | + const userSubscriptionsSnapshot = await subscriptionsRef |
| 187 | + .where('userId', '==', userId) |
| 188 | + .where('status', 'in', ['active', 'past_due']) |
| 189 | + .where('currentPeriodStart', '<=', allocationDate) |
| 190 | + .where('currentPeriodEnd', '>=', allocationDate) |
| 191 | + .get(); |
| 192 | + |
| 193 | + // If user had active subscription at time of allocation, it's funded |
| 194 | + if (!userSubscriptionsSnapshot.empty) { |
| 195 | + totalTokens += allocation.tokens || 0; |
| 196 | + allocations++; |
| 197 | + } |
| 198 | + } |
| 199 | + |
| 200 | + return { |
| 201 | + totalTokens, |
| 202 | + totalUsdValue: totalTokens * 0.1, // 10 tokens = $1 |
| 203 | + allocations |
| 204 | + }; |
| 205 | + } catch (error) { |
| 206 | + console.error('Error calculating funded token allocations:', error); |
| 207 | + return { totalTokens: 0, totalUsdValue: 0, allocations: 0 }; |
| 208 | + } |
| 209 | +} |
| 210 | + |
| 211 | +async function getSubscriptionRevenue(db: any, dateRange: DateRange): Promise<number> { |
| 212 | + try { |
| 213 | + // Get all subscription payments/charges within the date range |
| 214 | + // This should look at actual payment events, not just subscription creation |
| 215 | + |
| 216 | + // For now, we'll calculate based on active subscriptions and their billing cycles |
| 217 | + const subscriptionsRef = db.collection(getCollectionName('subscriptions')); |
| 218 | + const subscriptionsSnapshot = await subscriptionsRef |
| 219 | + .where('status', 'in', ['active', 'past_due']) |
| 220 | + .get(); |
| 221 | + |
| 222 | + let totalRevenue = 0; |
| 223 | + |
| 224 | + subscriptionsSnapshot.forEach(doc => { |
| 225 | + const subscription = doc.data(); |
| 226 | + const amount = subscription.amount || 0; |
| 227 | + const currentPeriodStart = subscription.currentPeriodStart?.toDate(); |
| 228 | + const currentPeriodEnd = subscription.currentPeriodEnd?.toDate(); |
| 229 | + |
| 230 | + // Check if the billing period overlaps with our date range |
| 231 | + if (currentPeriodStart && currentPeriodEnd) { |
| 232 | + const periodOverlapsRange = ( |
| 233 | + currentPeriodStart <= dateRange.endDate && |
| 234 | + currentPeriodEnd >= dateRange.startDate |
| 235 | + ); |
| 236 | + |
| 237 | + if (periodOverlapsRange) { |
| 238 | + totalRevenue += amount; |
| 239 | + } |
| 240 | + } |
| 241 | + }); |
| 242 | + |
| 243 | + return totalRevenue; |
| 244 | + } catch (error) { |
| 245 | + console.error('Error calculating subscription revenue:', error); |
| 246 | + return 0; |
| 247 | + } |
| 248 | +} |
| 249 | + |
| 250 | +async function getWriterPayouts(db: any, dateRange: DateRange): Promise<number> { |
| 251 | + try { |
| 252 | + const payoutsRef = db.collection(getCollectionName('tokenPayouts')); |
| 253 | + const payoutsSnapshot = await payoutsRef |
| 254 | + .where('completedAt', '>=', dateRange.startDate) |
| 255 | + .where('completedAt', '<=', dateRange.endDate) |
| 256 | + .where('status', '==', 'completed') |
| 257 | + .get(); |
| 258 | + |
| 259 | + let totalPayouts = 0; |
| 260 | + |
| 261 | + payoutsSnapshot.forEach(doc => { |
| 262 | + const payout = doc.data(); |
| 263 | + totalPayouts += payout.amount || 0; |
| 264 | + }); |
| 265 | + |
| 266 | + return totalPayouts; |
| 267 | + } catch (error) { |
| 268 | + console.error('Error calculating writer payouts:', error); |
| 269 | + return 0; |
| 270 | + } |
| 271 | +} |
0 commit comments