feat(dashboard): add dashboard with statistics

- Add dashboard stats API endpoint with key metrics
- Add stat-card component for displaying metrics
- Add occupancy-chart component for court occupancy visualization
- Add recent-bookings component for today's bookings list
- Add quick-actions component for common admin actions
- Update dashboard page with full implementation

Stats include: today's bookings, revenue, occupancy rate,
active members, pending bookings, and upcoming tournaments.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Ivan
2026-02-01 07:31:23 +00:00
parent 973588e861
commit 83fc48d7df
7 changed files with 1314 additions and 5 deletions

View File

@@ -1,10 +1,306 @@
"use client";
import { useSession } from "next-auth/react";
import { useEffect, useState } from "react";
import { formatCurrency, formatDate } from "@/lib/utils";
import { StatCard, StatCardSkeleton } from "@/components/dashboard/stat-card";
import { OccupancyChart, OccupancyChartSkeleton } from "@/components/dashboard/occupancy-chart";
import { RecentBookings, RecentBookingsSkeleton } from "@/components/dashboard/recent-bookings";
import { QuickActions } from "@/components/dashboard/quick-actions";
interface DashboardStats {
todayBookings: number;
todayRevenue: number;
occupancyRate: number;
activeMembers: number;
pendingBookings: number;
upcomingTournaments: number;
}
interface CourtOccupancy {
courtId: string;
courtName: string;
availableHours: number;
bookedHours: number;
occupancyPercent: number;
}
interface RecentBooking {
id: string;
startTime: string;
endTime: string;
status: string;
court: {
id: string;
name: string;
};
client: {
id: string;
name: string;
} | null;
}
interface DashboardData {
stats: DashboardStats;
courtOccupancy: CourtOccupancy[];
recentBookings: RecentBooking[];
date: string;
}
export default function DashboardPage() {
const { data: session } = useSession();
const [dashboardData, setDashboardData] = useState<DashboardData | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
async function fetchDashboardData() {
try {
setIsLoading(true);
setError(null);
const response = await fetch("/api/dashboard/stats");
if (!response.ok) {
throw new Error("Error al cargar los datos del dashboard");
}
const data = await response.json();
setDashboardData(data);
} catch (err) {
console.error("Dashboard fetch error:", err);
setError(err instanceof Error ? err.message : "Error desconocido");
} finally {
setIsLoading(false);
}
}
fetchDashboardData();
}, []);
const userName = session?.user?.name?.split(" ")[0] || "Usuario";
const today = new Date();
return (
<div>
<h1 className="text-2xl font-bold text-primary-800">Dashboard</h1>
<p className="mt-2 text-primary-600">
Bienvenido al panel de administración de Padel Pro.
</p>
<div className="space-y-6">
{/* Welcome Section */}
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<div>
<h1 className="text-2xl font-bold text-primary-800">
Bienvenido, {userName}
</h1>
<p className="text-primary-500 mt-1">
{formatDate(today)} - Panel de administracion
</p>
</div>
{session?.user?.siteName && (
<div className="flex items-center gap-2 px-4 py-2 bg-primary-50 rounded-lg">
<svg
className="w-5 h-5 text-primary-500"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z"
/>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M15 11a3 3 0 11-6 0 3 3 0 016 0z"
/>
</svg>
<span className="text-sm font-medium text-primary-700">
{session.user.siteName}
</span>
</div>
)}
</div>
{/* Error State */}
{error && (
<div className="p-4 bg-red-50 border border-red-200 rounded-lg text-red-700">
<div className="flex items-center gap-2">
<svg
className="w-5 h-5"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
<span>{error}</span>
</div>
</div>
)}
{/* Stats Cards Row */}
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
{isLoading ? (
<>
<StatCardSkeleton />
<StatCardSkeleton />
<StatCardSkeleton />
<StatCardSkeleton />
</>
) : dashboardData ? (
<>
<StatCard
title="Reservas Hoy"
value={dashboardData.stats.todayBookings}
color="blue"
icon={
<svg
className="w-6 h-6"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z"
/>
</svg>
}
/>
<StatCard
title="Ingresos Hoy"
value={formatCurrency(dashboardData.stats.todayRevenue)}
color="green"
icon={
<svg
className="w-6 h-6"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
}
/>
<StatCard
title="Ocupacion"
value={`${dashboardData.stats.occupancyRate}%`}
color="purple"
icon={
<svg
className="w-6 h-6"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"
/>
</svg>
}
/>
<StatCard
title="Miembros Activos"
value={dashboardData.stats.activeMembers}
color="accent"
icon={
<svg
className="w-6 h-6"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
/>
</svg>
}
/>
</>
) : null}
</div>
{/* Secondary Stats Row */}
{!isLoading && dashboardData && (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<StatCard
title="Reservas Pendientes"
value={dashboardData.stats.pendingBookings}
color="orange"
icon={
<svg
className="w-6 h-6"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
}
/>
<StatCard
title="Torneos Proximos"
value={dashboardData.stats.upcomingTournaments}
color="primary"
icon={
<svg
className="w-6 h-6"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z"
/>
</svg>
}
/>
</div>
)}
{/* Two Column Layout: Occupancy + Recent Bookings */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
{isLoading ? (
<>
<OccupancyChartSkeleton />
<RecentBookingsSkeleton />
</>
) : dashboardData ? (
<>
<OccupancyChart data={dashboardData.courtOccupancy} />
<RecentBookings bookings={dashboardData.recentBookings} />
</>
) : null}
</div>
{/* Quick Actions */}
<QuickActions />
</div>
);
}

View File

@@ -0,0 +1,322 @@
import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { db } from '@/lib/db';
// GET /api/dashboard/stats - Get dashboard statistics
export async function GET(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user) {
return NextResponse.json(
{ error: 'No autorizado' },
{ status: 401 }
);
}
const { searchParams } = new URL(request.url);
const siteId = searchParams.get('siteId') || session.user.siteId;
const dateParam = searchParams.get('date');
// Default to today
const targetDate = dateParam ? new Date(dateParam) : new Date();
const startOfDay = new Date(targetDate);
startOfDay.setHours(0, 0, 0, 0);
const endOfDay = new Date(targetDate);
endOfDay.setHours(23, 59, 59, 999);
// Build where clause for site filtering
interface SiteFilter {
organizationId: string;
id?: string;
}
const siteFilter: SiteFilter = {
organizationId: session.user.organizationId,
};
if (siteId) {
siteFilter.id = siteId;
}
// Get sites matching the filter
const sites = await db.site.findMany({
where: siteFilter,
select: { id: true, openTime: true, closeTime: true },
});
const siteIds = sites.map(s => s.id);
// 1. Today's bookings count
const todayBookings = await db.booking.count({
where: {
siteId: { in: siteIds },
startTime: {
gte: startOfDay,
lte: endOfDay,
},
status: {
in: ['PENDING', 'CONFIRMED', 'COMPLETED'],
},
},
});
// 2. Today's revenue (from sales + booking payments)
// Get sales from today
const todaySales = await db.sale.aggregate({
where: {
createdBy: {
organizationId: session.user.organizationId,
},
createdAt: {
gte: startOfDay,
lte: endOfDay,
},
...(siteId
? {
cashRegister: {
siteId,
},
}
: {}),
},
_sum: {
total: true,
},
});
// Get booking payments from today
const todayBookingPayments = await db.booking.aggregate({
where: {
siteId: { in: siteIds },
startTime: {
gte: startOfDay,
lte: endOfDay,
},
status: 'COMPLETED',
},
_sum: {
paidAmount: true,
},
});
const salesTotal = Number(todaySales._sum.total || 0);
const bookingPaymentsTotal = Number(todayBookingPayments._sum.paidAmount || 0);
const todayRevenue = salesTotal + bookingPaymentsTotal;
// 3. Calculate occupancy rate
// Get all courts for the sites
const courts = await db.court.findMany({
where: {
siteId: { in: siteIds },
isActive: true,
status: 'AVAILABLE',
},
include: {
site: {
select: {
openTime: true,
closeTime: true,
},
},
},
});
// Calculate total available hours per court for the day
let totalAvailableSlots = 0;
let bookedSlots = 0;
for (const court of courts) {
// Parse open/close times (format: "HH:MM")
const openTime = court.site.openTime || '08:00';
const closeTime = court.site.closeTime || '22:00';
const [openHour] = openTime.split(':').map(Number);
const [closeHour] = closeTime.split(':').map(Number);
// Each slot is 1 hour
const availableHours = closeHour - openHour;
totalAvailableSlots += availableHours;
// Count booked hours for this court today
const courtBookings = await db.booking.findMany({
where: {
courtId: court.id,
startTime: {
gte: startOfDay,
lte: endOfDay,
},
status: {
in: ['PENDING', 'CONFIRMED', 'COMPLETED'],
},
},
select: {
startTime: true,
endTime: true,
},
});
// Calculate booked hours
for (const booking of courtBookings) {
const durationMs = booking.endTime.getTime() - booking.startTime.getTime();
const durationHours = durationMs / (1000 * 60 * 60);
bookedSlots += durationHours;
}
}
const occupancyRate = totalAvailableSlots > 0
? Math.round((bookedSlots / totalAvailableSlots) * 100)
: 0;
// 4. Active memberships count
const now = new Date();
const activeMembers = await db.membership.count({
where: {
status: 'ACTIVE',
endDate: {
gte: now,
},
plan: {
organizationId: session.user.organizationId,
},
},
});
// 5. Pending bookings (awaiting payment/confirmation)
const pendingBookings = await db.booking.count({
where: {
siteId: { in: siteIds },
status: 'PENDING',
startTime: {
gte: startOfDay,
},
},
});
// 6. Upcoming tournaments (next 30 days)
const thirtyDaysFromNow = new Date();
thirtyDaysFromNow.setDate(thirtyDaysFromNow.getDate() + 30);
const upcomingTournaments = await db.tournament.count({
where: {
organizationId: session.user.organizationId,
...(siteId ? { siteId } : {}),
startDate: {
gte: now,
lte: thirtyDaysFromNow,
},
status: {
in: ['DRAFT', 'REGISTRATION_OPEN', 'REGISTRATION_CLOSED', 'IN_PROGRESS'],
},
},
});
// Get court occupancy details for chart
const courtOccupancy = await Promise.all(
courts.map(async (court) => {
const openTime = court.site.openTime || '08:00';
const closeTime = court.site.closeTime || '22:00';
const [openHour] = openTime.split(':').map(Number);
const [closeHour] = closeTime.split(':').map(Number);
const availableHours = closeHour - openHour;
const courtBookings = await db.booking.findMany({
where: {
courtId: court.id,
startTime: {
gte: startOfDay,
lte: endOfDay,
},
status: {
in: ['PENDING', 'CONFIRMED', 'COMPLETED'],
},
},
select: {
startTime: true,
endTime: true,
},
});
let bookedHours = 0;
for (const booking of courtBookings) {
const durationMs = booking.endTime.getTime() - booking.startTime.getTime();
bookedHours += durationMs / (1000 * 60 * 60);
}
return {
courtId: court.id,
courtName: court.name,
availableHours,
bookedHours: Math.round(bookedHours * 10) / 10,
occupancyPercent: availableHours > 0
? Math.round((bookedHours / availableHours) * 100)
: 0,
};
})
);
// Get recent bookings for the day
const recentBookings = await db.booking.findMany({
where: {
siteId: { in: siteIds },
startTime: {
gte: startOfDay,
lte: endOfDay,
},
},
include: {
court: {
select: {
id: true,
name: true,
},
},
client: {
select: {
id: true,
firstName: true,
lastName: true,
},
},
},
orderBy: {
startTime: 'asc',
},
take: 10,
});
return NextResponse.json({
stats: {
todayBookings,
todayRevenue,
occupancyRate,
activeMembers,
pendingBookings,
upcomingTournaments,
},
courtOccupancy,
recentBookings: recentBookings.map((booking) => ({
id: booking.id,
startTime: booking.startTime,
endTime: booking.endTime,
status: booking.status,
court: booking.court,
client: booking.client
? {
id: booking.client.id,
name: `${booking.client.firstName} ${booking.client.lastName}`,
}
: null,
})),
date: targetDate.toISOString().split('T')[0],
});
} catch (error) {
console.error('Error fetching dashboard stats:', error);
return NextResponse.json(
{ error: 'Error al obtener estadísticas del dashboard' },
{ status: 500 }
);
}
}