additional features, refinement and more control over the app from admin side, better bookings UX
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getSession } from '@/lib/session';
|
||||
import { db } from '@/lib/db';
|
||||
import { users, courts, bookings, metrics } from '@/lib/db/schema';
|
||||
import { eq, and, gte, lte, desc, count } from 'drizzle-orm';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session || session.role !== 'admin') {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
// Get real stats from database
|
||||
const totalUsers = await db.select({ count: count() }).from(users);
|
||||
const activeCourts = await db.select({ count: count() }).from(courts).where(eq(courts.isActive, true));
|
||||
|
||||
// Get today's bookings count
|
||||
const today = new Date().toISOString().split('T')[0];
|
||||
const todaysBookings = await db
|
||||
.select({ count: count() })
|
||||
.from(bookings)
|
||||
.where(and(eq(bookings.date, today), eq(bookings.status, 'active')));
|
||||
|
||||
// Get current month's bookings from metrics table
|
||||
const currentMonth = new Date().toISOString().substring(0, 7); // "2025-09"
|
||||
const monthlyBookings = await db
|
||||
.select()
|
||||
.from(metrics)
|
||||
.where(and(eq(metrics.metricType, 'monthly_bookings'), eq(metrics.period, currentMonth)))
|
||||
.limit(1);
|
||||
|
||||
// Get recent bookings with user names
|
||||
const recentBookings = await db
|
||||
.select({
|
||||
id: bookings.id,
|
||||
date: bookings.date,
|
||||
startTime: bookings.startTime,
|
||||
endTime: bookings.endTime,
|
||||
courtName: courts.name,
|
||||
userName: users.name,
|
||||
userSurname: users.surname,
|
||||
status: bookings.status,
|
||||
createdAt: bookings.createdAt,
|
||||
})
|
||||
.from(bookings)
|
||||
.leftJoin(users, eq(bookings.userId, users.id))
|
||||
.leftJoin(courts, eq(bookings.courtId, courts.id))
|
||||
.orderBy(desc(bookings.createdAt))
|
||||
.limit(10);
|
||||
|
||||
return NextResponse.json({
|
||||
stats: {
|
||||
totalUsers: totalUsers[0]?.count || 0,
|
||||
activeCourts: activeCourts[0]?.count || 0,
|
||||
todaysBookings: todaysBookings[0]?.count || 0,
|
||||
monthlyBookings: monthlyBookings[0]?.value || 0,
|
||||
},
|
||||
recentBookings: recentBookings.map((booking) => ({
|
||||
...booking,
|
||||
userName: `${booking.userName} ${booking.userSurname}`,
|
||||
})),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching admin stats:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user