51 lines
1.5 KiB
TypeScript
51 lines
1.5 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { redis } from '@/lib/redis'
|
|
import { getAllPolls } from '@/lib/polls'
|
|
|
|
export async function GET(req: NextRequest) {
|
|
try {
|
|
const { searchParams } = new URL(req.url)
|
|
const period = searchParams.get('period') || 'daily'
|
|
|
|
const polls = await getAllPolls()
|
|
const allUsers = await redis.keys('user:*')
|
|
|
|
const now = Date.now()
|
|
const periodMs = period === 'daily' ? 24 * 60 * 60 * 1000 :
|
|
period === 'weekly' ? 7 * 24 * 60 * 60 * 1000 :
|
|
30 * 24 * 60 * 60 * 1000
|
|
|
|
let totalVotes = 0
|
|
let totalVolume = 0
|
|
let activeUsers = 0
|
|
|
|
for (const poll of polls) {
|
|
if (now - poll.createdAt <= periodMs) {
|
|
totalVotes += poll.totalVotes
|
|
totalVolume += poll.totalAmount
|
|
}
|
|
}
|
|
|
|
for (const userKey of allUsers) {
|
|
const votes = await redis.lrange(userKey.replace('user:', 'votes:'), 0, -1)
|
|
const recentVotes = votes.filter(v => {
|
|
const vote = JSON.parse(v)
|
|
return now - vote.timestamp <= periodMs
|
|
})
|
|
if (recentVotes.length > 0) activeUsers++
|
|
}
|
|
|
|
return NextResponse.json({
|
|
period,
|
|
totalVotes,
|
|
totalVolume,
|
|
activeUsers,
|
|
avgVotesPerUser: activeUsers > 0 ? totalVotes / activeUsers : 0,
|
|
avgVolumePerUser: activeUsers > 0 ? totalVolume / activeUsers : 0
|
|
})
|
|
} catch (error) {
|
|
console.error('Platform analytics error:', error)
|
|
return NextResponse.json({ error: 'Failed to fetch analytics' }, { status: 500 })
|
|
}
|
|
}
|