import { NextResponse } from "next/server"
import connectDB from "@/lib/mongodb"
import DoubtSession from "@/models/DoubtSession"
export async function GET() {
console.log("=== Stats API Called ===")
try {
await connectDB()
console.log("✅ Database connected for stats")
// Get all sessions with their status
const allSessions = await DoubtSession.find({}, { status: 1, _id: 1, studentName: 1 })
console.log("📋 All sessions from DB:", allSessions)
// Get total count
const totalCount = allSessions.length
console.log("📊 Total sessions count:", totalCount)
// Function to normalize status
const normalizeStatus = (status) => {
if (!status) return "pending"
const normalized = status.toString().toLowerCase().trim()
// Handle common misspellings and variations
switch (normalized) {
case "pending":
return "pending"
case "recieved":
case "received":
return "received"
case "responded":
case "confirmed":
return "responded"
case "completed":
return "completed"
case "cancelled":
case "canceled":
return "cancelled"
default:
console.log(`⚠️ Unknown status found: "${status}" - treating as pending`)
return "pending"
}
}
// Count sessions by normalized status
const statusCounts = {
pending: 0,
received: 0,
responded: 0,
completed: 0,
cancelled: 0,
}
// Process each session
allSessions.forEach((session) => {
const normalizedStatus = normalizeStatus(session.status)
statusCounts[normalizedStatus]++
console.log(`📝 Session ${session._id}: "${session.status}" → "${normalizedStatus}"`)
})
console.log("📊 Status counts after normalization:", statusCounts)
// Get today's sessions
const today = new Date()
const startOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate())
const endOfDay = new Date(startOfDay)
endOfDay.setDate(endOfDay.getDate() + 1)
const todayCount = await DoubtSession.countDocuments({
createdAt: {
$gte: startOfDay,
$lt: endOfDay,
},
})
// Calculate percentages
const calculatePercentage = (count, total) => {
return total > 0 ? Math.round((count / total) * 100) : 0
}
const finalStats = {
total: totalCount,
pending: statusCounts.pending,
received: statusCounts.received,
responded: statusCounts.responded,
completed: statusCounts.completed,
cancelled: statusCounts.cancelled,
today: todayCount,
percentages: {
pending: calculatePercentage(statusCounts.pending, totalCount),
received: calculatePercentage(statusCounts.received, totalCount),
responded: calculatePercentage(statusCounts.responded, totalCount),
completed: calculatePercentage(statusCounts.completed, totalCount),
cancelled: calculatePercentage(statusCounts.cancelled, totalCount),
},
}
console.log("📊 Final stats object:", finalStats)
return NextResponse.json({
success: true,
stats: finalStats,
debug: {
totalFound: totalCount,
rawStatusCounts: statusCounts,
sampleSessions: allSessions.slice(0, 3),
statusMapping: {
pending: "New sessions waiting for admin response",
received: "Sessions received by admin but not yet responded",
responded: "Sessions with admin response sent",
completed: "Finished sessions",
cancelled: "Cancelled sessions",
},
},
})
} catch (error) {
console.error("❌ Stats API Error:")
console.error("Message:", error.message)
console.error("Stack:", error.stack)
return NextResponse.json(
{
success: false,
error: error.message,
details: error.toString(),
stack: process.env.NODE_ENV === "development" ? error.stack : undefined,
},
{ status: 500 },
)
}
}
use this route to get all stats and display it here
do the changes that are related to this only ....dont hamper exisitng code
I can see the issue. The API route returns the stats nested under a stats property, but the component is trying to access the properties directly. Let me fix the fetchSessionStats function in the AdminDashboard component to properly handle the API response structure.
The key change is that I've updated the fetchSessionStats function to properly extract the stats from the API response. The API returns the data nested under a stats property (data.stats), so I'm now accessing stats.total, stats.pending, etc., instead of trying to access them directly from the response.
This should now properly display the session statistics in the Sessions Management card, showing the correct counts for:
The existing code structure and functionality remain unchanged - I've only modified how the session stats are extracted from the API response.
To configure the generation, complete these steps:
Based on your EdTech platform deployed on Vercel's free tier, here's a realistic assessment of how many students you can accommodate:
// Current: Heavy aggregation queries
const analytics = await TestAttempt.aggregate([...]) // Slow, CPU intensive
// Optimized: Add indexes and caching
const cachedAnalytics = await redis.get('analytics') || await generateAnalytics()// Current: Dashboard makes 8-12 API calls
useEffect(() => {
fetchStats() // Call 1
fetchTests() // Call 2
fetchAnalytics() // Call 3
// ... 8 more calls
}, [])
// Optimized: Single combined endpoint
const dashboardData = await fetch('/api/dashboard/combined')// Current: Every 30 seconds
setInterval(autoSave, 30000) // 120 calls per hour
// Optimized: Every 3 minutes
setInterval(autoSave, 180000) // 20 calls per hoursrc/hooks/useTestAutoSave.js
Bottom Line: With your current code, you can realistically handle 50-100 active students on Vercel's free tier. With optimizations, this could increase to 150-200 students.
To configure the generation, complete these steps:
You can send messages while the preview loads