refactors, specific day playtime controls

This commit is contained in:
mikicvi
2025-09-22 22:46:33 +01:00
parent c8062cf96b
commit 6d3202e385
27 changed files with 1710 additions and 1365 deletions
@@ -0,0 +1,347 @@
'use client';
import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Switch } from '@/components/ui/switch';
import { Plus, Edit, Trash2, Clock } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
interface TimeSlot {
id: string;
dayOfWeek: number;
startTime: string;
endTime: string;
isActive: boolean;
createdAt: string;
updatedAt: string;
}
const DAYS = [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
];
export function AdminTimeSlotManagement() {
const [timeSlots, setTimeSlots] = useState<TimeSlot[]>([]);
const [loading, setLoading] = useState(false);
const [showDialog, setShowDialog] = useState(false);
const [editingSlot, setEditingSlot] = useState<TimeSlot | null>(null);
const [formData, setFormData] = useState({
dayOfWeek: 0,
startTime: '',
endTime: '',
isActive: true,
});
const { toast } = useToast();
useEffect(() => {
fetchTimeSlots();
}, []);
const fetchTimeSlots = async () => {
try {
setLoading(true);
const response = await fetch('/api/admin/time-slots');
if (response.ok) {
const data = await response.json();
setTimeSlots(data.timeSlots);
} else {
toast({
title: 'Error',
description: 'Failed to fetch time slots',
variant: 'destructive',
});
}
} catch (error) {
console.error('Error fetching time slots:', error);
toast({
title: 'Error',
description: 'Failed to fetch time slots',
variant: 'destructive',
});
} finally {
setLoading(false);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
try {
setLoading(true);
const url = editingSlot
? `/api/admin/time-slots/${editingSlot.id}`
: '/api/admin/time-slots';
const method = editingSlot ? 'PUT' : 'POST';
const response = await fetch(url, {
method,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
});
if (response.ok) {
toast({
title: 'Success',
description: editingSlot
? 'Time slot updated successfully'
: 'Time slot created successfully',
});
fetchTimeSlots();
setShowDialog(false);
resetForm();
} else {
const error = await response.json();
toast({
title: 'Error',
description: error.error || 'Failed to save time slot',
variant: 'destructive',
});
}
} catch (error) {
console.error('Error saving time slot:', error);
toast({
title: 'Error',
description: 'Failed to save time slot',
variant: 'destructive',
});
} finally {
setLoading(false);
}
};
const handleDelete = async (id: string) => {
if (!confirm('Are you sure you want to delete this time slot?')) {
return;
}
try {
setLoading(true);
const response = await fetch(`/api/admin/time-slots/${id}`, {
method: 'DELETE',
});
if (response.ok) {
toast({
title: 'Success',
description: 'Time slot deleted successfully',
});
fetchTimeSlots();
} else {
const error = await response.json();
toast({
title: 'Error',
description: error.error || 'Failed to delete time slot',
variant: 'destructive',
});
}
} catch (error) {
console.error('Error deleting time slot:', error);
toast({
title: 'Error',
description: 'Failed to delete time slot',
variant: 'destructive',
});
} finally {
setLoading(false);
}
};
const handleEdit = (slot: TimeSlot) => {
setEditingSlot(slot);
setFormData({
dayOfWeek: slot.dayOfWeek,
startTime: slot.startTime,
endTime: slot.endTime,
isActive: slot.isActive,
});
setShowDialog(true);
};
const resetForm = () => {
setEditingSlot(null);
setFormData({
dayOfWeek: 0,
startTime: '',
endTime: '',
isActive: true,
});
};
const groupedTimeSlots = timeSlots.reduce((acc, slot) => {
if (!acc[slot.dayOfWeek]) {
acc[slot.dayOfWeek] = [];
}
acc[slot.dayOfWeek].push(slot);
return acc;
}, {} as Record<number, TimeSlot[]>);
return (
<Card>
<CardHeader>
<div className="flex justify-between items-center">
<CardTitle className="flex items-center gap-2">
<Clock className="h-5 w-5" />
Time Slot Management
</CardTitle>
<Dialog open={showDialog} onOpenChange={setShowDialog}>
<DialogTrigger asChild>
<Button onClick={resetForm}>
<Plus className="h-4 w-4 mr-2" />
Add Time Slot
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>
{editingSlot ? 'Edit Time Slot' : 'Add New Time Slot'}
</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<Label htmlFor="dayOfWeek">Day of Week</Label>
<Select
value={formData.dayOfWeek.toString()}
onValueChange={(value) =>
setFormData({ ...formData, dayOfWeek: parseInt(value) })
}
>
<SelectTrigger>
<SelectValue placeholder="Select day" />
</SelectTrigger>
<SelectContent>
{DAYS.map((day, index) => (
<SelectItem key={index} value={index.toString()}>
{day}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="startTime">Start Time</Label>
<Input
id="startTime"
type="time"
value={formData.startTime}
onChange={(e) =>
setFormData({ ...formData, startTime: e.target.value })
}
required
/>
</div>
<div>
<Label htmlFor="endTime">End Time</Label>
<Input
id="endTime"
type="time"
value={formData.endTime}
onChange={(e) =>
setFormData({ ...formData, endTime: e.target.value })
}
required
/>
</div>
<div className="flex items-center space-x-2">
<Switch
id="isActive"
checked={formData.isActive}
onCheckedChange={(checked) =>
setFormData({ ...formData, isActive: checked })
}
/>
<Label htmlFor="isActive">Active</Label>
</div>
<div className="flex justify-end space-x-2">
<Button
type="button"
variant="outline"
onClick={() => setShowDialog(false)}
>
Cancel
</Button>
<Button type="submit" disabled={loading}>
{loading ? 'Saving...' : editingSlot ? 'Update' : 'Create'}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
</div>
</CardHeader>
<CardContent>
{loading && timeSlots.length === 0 ? (
<div className="text-center py-4">Loading time slots...</div>
) : (
<div className="space-y-6">
{DAYS.map((day, dayIndex) => (
<div key={dayIndex} className="space-y-2">
<h3 className="font-semibold text-lg">{day}</h3>
{groupedTimeSlots[dayIndex]?.length > 0 ? (
<div className="grid gap-2">
{groupedTimeSlots[dayIndex]
.sort((a, b) => a.startTime.localeCompare(b.startTime))
.map((slot) => (
<div
key={slot.id}
className={`flex items-center justify-between p-3 border rounded-lg ${
slot.isActive ? 'bg-green-50 border-green-200' : 'bg-gray-50 border-gray-200'
}`}
>
<div className="flex items-center space-x-3">
<div className="font-medium">
{slot.startTime} - {slot.endTime}
</div>
<div className={`px-2 py-1 rounded-full text-xs ${
slot.isActive
? 'bg-green-100 text-green-800'
: 'bg-gray-100 text-gray-800'
}`}>
{slot.isActive ? 'Active' : 'Inactive'}
</div>
</div>
<div className="flex space-x-2">
<Button
size="sm"
variant="outline"
onClick={() => handleEdit(slot)}
>
<Edit className="h-4 w-4" />
</Button>
<Button
size="sm"
variant="outline"
onClick={() => handleDelete(slot.id)}
className="text-red-600 hover:text-red-700"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
))}
</div>
) : (
<p className="text-gray-500 italic">No time slots configured for {day}</p>
)}
</div>
))}
</div>
)}
</CardContent>
</Card>
);
}
+5 -1
View File
@@ -13,6 +13,7 @@ import { AdminLogs } from './AdminLogs';
import { AdminRecentBookings } from './AdminRecentBookings';
import { AdminCourtManagement } from './AdminCourtManagement';
import { AdminSettingsManagement } from './AdminSettingsManagement';
import { AdminTimeSlotManagement } from './AdminTimeSlotManagement';
export function AdminDashboard() {
const router = useRouter();
@@ -126,7 +127,10 @@ export function AdminDashboard() {
<AdminCourtManagement />
</TabsContent>{' '}
<TabsContent value='settings'>
<AdminSettingsManagement />
<div className="space-y-6">
<AdminSettingsManagement />
<AdminTimeSlotManagement />
</div>
</TabsContent>
<TabsContent value='announcements'>
<AdminAnnouncementManagement />
-101
View File
@@ -1,101 +0,0 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { useToast } from '@/components/ui/use-toast';
export function LoginForm() {
const [isLoading, setIsLoading] = useState(false);
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const router = useRouter();
const { toast } = useToast();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setIsLoading(true);
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
const data = await response.json();
if (response.ok) {
toast({
title: 'Success',
description: 'Logged in successfully',
});
if (data.user.role === 'admin') {
router.push('/admin');
} else {
router.push('/dashboard');
}
} else {
toast({
title: 'Error',
description: data.error || 'Login failed',
variant: 'destructive',
});
}
} catch (error) {
toast({
title: 'Error',
description: 'An unexpected error occurred',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
};
return (
<Card className='w-full max-w-md mx-auto'>
<CardHeader>
<CardTitle>Sign In</CardTitle>
<CardDescription>Enter your email and password to access your account</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className='space-y-4'>
<div className='space-y-2'>
<Label htmlFor='email'>Email</Label>
<Input
id='email'
type='email'
placeholder='Enter your email'
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div className='space-y-2'>
<Label htmlFor='password'>Password</Label>
<Input
id='password'
type='password'
placeholder='Enter your password'
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
<Button type='submit' className='w-full' disabled={isLoading}>
{isLoading ? 'Signing in...' : 'Sign In'}
</Button>
</form>
<div className='mt-4 text-center'>
<Button variant='link' onClick={() => router.push('/register')} className='text-sm'>
Don't have an account? Sign up
</Button>
</div>
</CardContent>
</Card>
);
}
-158
View File
@@ -1,158 +0,0 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Label } from '@/components/ui/label';
import { useToast } from '@/components/ui/use-toast';
export function RegisterForm() {
const [isLoading, setIsLoading] = useState(false);
const [formData, setFormData] = useState({
email: '',
name: '',
surname: '',
password: '',
confirmPassword: '',
});
const router = useRouter();
const { toast } = useToast();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (formData.password !== formData.confirmPassword) {
toast({
title: 'Error',
description: 'Passwords do not match',
variant: 'destructive',
});
return;
}
setIsLoading(true);
try {
const response = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: formData.email,
name: formData.name,
surname: formData.surname,
password: formData.password,
}),
});
const data = await response.json();
if (response.ok) {
toast({
title: 'Success',
description: 'Account created successfully! Please log in.',
});
router.push('/');
} else {
toast({
title: 'Error',
description: data.error || 'Registration failed',
variant: 'destructive',
});
}
} catch (error) {
toast({
title: 'Error',
description: 'An unexpected error occurred',
variant: 'destructive',
});
} finally {
setIsLoading(false);
}
};
const handleInputChange = (field: string, value: string) => {
setFormData((prev) => ({ ...prev, [field]: value }));
};
return (
<Card className='w-full max-w-md mx-auto'>
<CardHeader>
<CardTitle>Create Account</CardTitle>
<CardDescription>Fill in your details to create a new account</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className='space-y-4'>
<div className='grid grid-cols-2 gap-4'>
<div className='space-y-2'>
<Label htmlFor='name'>First Name</Label>
<Input
id='name'
type='text'
placeholder='John'
value={formData.name}
onChange={(e) => handleInputChange('name', e.target.value)}
required
/>
</div>
<div className='space-y-2'>
<Label htmlFor='surname'>Last Name</Label>
<Input
id='surname'
type='text'
placeholder='Doe'
value={formData.surname}
onChange={(e) => handleInputChange('surname', e.target.value)}
required
/>
</div>
</div>
<div className='space-y-2'>
<Label htmlFor='email'>Email</Label>
<Input
id='email'
type='email'
placeholder='john.doe@example.com'
value={formData.email}
onChange={(e) => handleInputChange('email', e.target.value)}
required
/>
</div>
<div className='space-y-2'>
<Label htmlFor='password'>Password</Label>
<Input
id='password'
type='password'
placeholder='Enter your password'
value={formData.password}
onChange={(e) => handleInputChange('password', e.target.value)}
required
minLength={6}
/>
</div>
<div className='space-y-2'>
<Label htmlFor='confirmPassword'>Confirm Password</Label>
<Input
id='confirmPassword'
type='password'
placeholder='Confirm your password'
value={formData.confirmPassword}
onChange={(e) => handleInputChange('confirmPassword', e.target.value)}
required
minLength={6}
/>
</div>
<Button type='submit' className='w-full' disabled={isLoading}>
{isLoading ? 'Creating account...' : 'Create Account'}
</Button>
</form>
<div className='mt-4 text-center'>
<Button variant='link' onClick={() => router.push('/')} className='text-sm'>
Already have an account? Sign in
</Button>
</div>
</CardContent>
</Card>
);
}
-290
View File
@@ -1,290 +0,0 @@
'use client';
import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Calendar, Clock, MapPin, ChevronLeft, ChevronRight } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
interface Court {
id: string;
name: string;
isActive: boolean;
}
interface Booking {
id: string;
courtId: string;
date: string;
startTime: string;
endTime: string;
status: string;
userId: string;
}
interface BookingSlot {
time: string;
courtId: string;
courtName: string;
available: boolean;
bookingId?: string;
}
export function BookingCalendar() {
const [selectedDate, setSelectedDate] = useState(new Date());
const [courts, setCourts] = useState<Court[]>([]);
const [bookings, setBookings] = useState<Booking[]>([]);
const [bookingSlots, setBookingSlots] = useState<BookingSlot[]>([]);
const [loading, setLoading] = useState(false);
const { toast } = useToast();
// Time slots for booking (7 PM to 11 PM)
const timeSlots = ['19:00', '20:00', '21:00', '22:00'];
useEffect(() => {
fetchCourts();
}, []);
useEffect(() => {
if (courts.length > 0) {
fetchBookings();
}
}, [selectedDate, courts]);
const fetchCourts = async () => {
try {
const response = await fetch('/api/admin/courts');
if (response.ok) {
const data = await response.json();
setCourts(data.courts.filter((court: Court) => court.isActive));
}
} catch (error) {
console.error('Error fetching courts:', error);
toast({
title: 'Error',
description: 'Failed to fetch courts',
variant: 'destructive',
});
}
};
const fetchBookings = async () => {
try {
const response = await fetch('/api/bookings');
if (response.ok) {
const data = await response.json();
setBookings(data.bookings);
generateBookingSlots(data.bookings);
}
} catch (error) {
console.error('Error fetching bookings:', error);
toast({
title: 'Error',
description: 'Failed to fetch bookings',
variant: 'destructive',
});
}
};
const generateBookingSlots = (existingBookings: Booking[]) => {
const dateStr = selectedDate.toISOString().split('T')[0];
const slots: BookingSlot[] = [];
courts.forEach((court) => {
timeSlots.forEach((time) => {
const existingBooking = existingBookings.find(
(booking) =>
booking.courtId === court.id &&
booking.date === dateStr &&
booking.startTime === time &&
booking.status === 'active'
);
slots.push({
time,
courtId: court.id,
courtName: court.name,
available: !existingBooking,
bookingId: existingBooking?.id,
});
});
});
setBookingSlots(slots);
};
const handleBookSlot = async (courtId: string, timeSlot: string) => {
setLoading(true);
try {
const dateStr = selectedDate.toISOString().split('T')[0];
const response = await fetch('/api/bookings', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
courtId,
date: dateStr,
timeSlot,
}),
});
const data = await response.json();
if (response.ok) {
toast({
title: 'Success',
description: 'Booking created successfully!',
});
fetchBookings(); // Refresh bookings
} else {
toast({
title: 'Error',
description: data.error || 'Failed to create booking',
variant: 'destructive',
});
}
} catch (error) {
console.error('Error booking slot:', error);
toast({
title: 'Error',
description: 'Failed to create booking',
variant: 'destructive',
});
} finally {
setLoading(false);
}
};
const navigateDate = (direction: 'prev' | 'next') => {
const newDate = new Date(selectedDate);
newDate.setDate(newDate.getDate() + (direction === 'next' ? 1 : -1));
setSelectedDate(newDate);
};
const isToday = (date: Date) => {
const today = new Date();
return date.toDateString() === today.toDateString();
};
const isPastDate = (date: Date) => {
const today = new Date();
today.setHours(0, 0, 0, 0);
return date < today;
};
return (
<Card>
<CardHeader>
<CardTitle className='flex items-center gap-2'>
<Calendar className='h-5 w-5' />
Book Your Court
</CardTitle>
</CardHeader>
<CardContent>
<div className='space-y-6'>
{/* Date Navigation */}
<div className='flex items-center justify-between'>
<Button
variant='outline'
size='sm'
onClick={() => navigateDate('prev')}
disabled={isPastDate(new Date(selectedDate.getTime() - 24 * 60 * 60 * 1000))}
>
<ChevronLeft className='h-4 w-4' />
Previous Day
</Button>
<h3 className='text-lg font-semibold'>
{selectedDate.toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
})}
{isToday(selectedDate) && <span className='text-sm text-blue-600 ml-2'>(Today)</span>}
</h3>
<Button variant='outline' size='sm' onClick={() => navigateDate('next')}>
Next Day
<ChevronRight className='h-4 w-4' />
</Button>
</div>
{/* Loading State */}
{loading && (
<div className='text-center py-8'>
<div className='inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-gray-900'></div>
<p className='mt-2 text-sm text-gray-500'>Loading booking slots...</p>
</div>
)}
{/* No Courts Available */}
{!loading && courts.length === 0 && (
<div className='text-center py-8'>
<p className='text-gray-500'>No courts available for booking</p>
</div>
)}
{/* Past Date Warning */}
{isPastDate(selectedDate) && (
<div className='bg-yellow-50 border border-yellow-200 rounded-lg p-4'>
<p className='text-yellow-800 text-sm'>
You cannot book courts for past dates. Please select a current or future date.
</p>
</div>
)}
{/* Time Slots Grid */}
{!loading && courts.length > 0 && !isPastDate(selectedDate) && (
<div className='grid grid-cols-1 md:grid-cols-2 gap-4'>
{bookingSlots.map((slot, index) => (
<div
key={`${slot.courtId}-${slot.time}`}
className={`p-4 border rounded-lg transition-colors ${
slot.available
? 'border-green-200 bg-green-50 hover:bg-green-100'
: 'border-red-200 bg-red-50'
}`}
>
<div className='flex items-center justify-between'>
<div className='space-y-2'>
<div className='flex items-center gap-2 text-sm font-medium'>
<Clock className='h-4 w-4' />
{slot.time} -{' '}
{String(parseInt(slot.time.split(':')[0]) + 1).padStart(2, '0')}:00
</div>
<div className='flex items-center gap-2 text-sm text-gray-600'>
<MapPin className='h-4 w-4' />
{slot.courtName}
</div>
{!slot.available && (
<div className='text-xs text-red-600'>Already booked</div>
)}
</div>
<Button
size='sm'
disabled={!slot.available || loading}
onClick={() => handleBookSlot(slot.courtId, slot.time)}
className={slot.available ? 'bg-green-600 hover:bg-green-700' : ''}
>
{slot.available ? 'Book' : 'Booked'}
</Button>
</div>
</div>
))}
</div>
)}
{/* No Slots Message */}
{!loading && courts.length > 0 && bookingSlots.length === 0 && !isPastDate(selectedDate) && (
<div className='text-center py-8'>
<p className='text-gray-500'>No booking slots available for this date</p>
</div>
)}
</div>
</CardContent>
</Card>
);
}
+127 -14
View File
@@ -25,6 +25,11 @@ interface Booking {
status: string;
userId: string;
notes?: string;
user?: {
id: string;
name: string;
surname: string;
};
}
interface BookingSlot {
@@ -33,6 +38,15 @@ interface BookingSlot {
courtName: string;
available: boolean;
bookingId?: string;
bookedBy?: string;
}
interface TimeSlot {
id: string;
dayOfWeek: number;
startTime: string;
endTime: string;
isActive: boolean;
}
interface Settings {
@@ -47,6 +61,7 @@ export function EnhancedBookingCalendar() {
const [courts, setCourts] = useState<Court[]>([]);
const [bookings, setBookings] = useState<Booking[]>([]);
const [bookingSlots, setBookingSlots] = useState<BookingSlot[]>([]);
const [timeSlots, setTimeSlots] = useState<TimeSlot[]>([]);
const [settings, setSettings] = useState<Settings | null>(null);
const [loading, setLoading] = useState(false);
const [partnerName, setPartnerName] = useState('');
@@ -58,13 +73,14 @@ export function EnhancedBookingCalendar() {
useEffect(() => {
fetchSettings();
fetchCourts();
fetchTimeSlots();
}, []);
useEffect(() => {
if (courts.length > 0 && settings) {
if (courts.length > 0 && timeSlots.length > 0) {
fetchBookings();
}
}, [selectedDate, courts, settings]);
}, [selectedDate, courts, timeSlots]);
// Fetch settings from public endpoint (not admin)
const fetchSettings = async () => {
@@ -125,9 +141,24 @@ export function EnhancedBookingCalendar() {
}
};
// Fetch time slots for day-specific booking times
const fetchTimeSlots = async () => {
try {
const response = await fetch('/api/time-slots');
if (response.ok) {
const data = await response.json();
setTimeSlots(data.timeSlots);
}
} catch (error) {
console.error('Error fetching time slots:', error);
// If time slots fetch fails, we'll use fallback settings
}
};
const fetchBookings = async () => {
try {
const response = await fetch('/api/bookings');
const dateStr = selectedDate.toISOString().split('T')[0];
const response = await fetch(`/api/bookings/all?date=${dateStr}`);
if (response.ok) {
const data = await response.json();
setBookings(data.bookings);
@@ -144,17 +175,45 @@ export function EnhancedBookingCalendar() {
};
const generateTimeSlots = (): string[] => {
if (!settings) return [];
const dayOfWeek = selectedDate.getDay();
// Get time slots for the selected day
const dayTimeSlots = timeSlots.filter(
slot => slot.dayOfWeek === dayOfWeek && slot.isActive
);
const start = parseInt(settings.booking_start_time.split(':')[0]);
const end = parseInt(settings.booking_end_time.split(':')[0]);
const slots = [];
for (let hour = start; hour < end; hour++) {
slots.push(`${hour.toString().padStart(2, '0')}:00`);
if (dayTimeSlots.length > 0) {
// Use day-specific time slots
const slots: string[] = [];
dayTimeSlots.forEach(timeSlot => {
const start = parseInt(timeSlot.startTime.split(':')[0]);
const end = parseInt(timeSlot.endTime.split(':')[0]);
for (let hour = start; hour < end; hour++) {
slots.push(`${hour.toString().padStart(2, '0')}:00`);
}
});
// Remove duplicates and sort
return [...new Set(slots)].sort();
}
return slots;
// NO FALLBACK - If no day-specific time slots, return empty array
// This prevents booking on days where no play is scheduled
return [];
};
const isDayBookable = (): boolean => {
const dayOfWeek = selectedDate.getDay();
const dayTimeSlots = timeSlots.filter(
slot => slot.dayOfWeek === dayOfWeek && slot.isActive
);
return dayTimeSlots.length > 0;
};
const getDayName = (dayOfWeek: number): string => {
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
return days[dayOfWeek];
};
const generateBookingSlots = (existingBookings: Booking[]) => {
@@ -172,12 +231,17 @@ export function EnhancedBookingCalendar() {
booking.status === 'active'
);
const bookedBy = existingBooking?.user
? `${existingBooking.user.name} ${existingBooking.user.surname}`
: undefined;
slots.push({
time,
courtId: court.id,
courtName: court.name,
available: !existingBooking,
bookingId: existingBooking?.id,
bookedBy,
});
});
});
@@ -202,7 +266,17 @@ export function EnhancedBookingCalendar() {
maxDate.setDate(today.getDate() + parseInt(settings.booking_window_days));
if (selectedDateOnly > maxDate) return false;
// Check weekend restrictions
// CRITICAL: Check if there are any active time slots for this day
const dayOfWeek = selectedDateOnly.getDay();
const dayTimeSlots = timeSlots.filter(
slot => slot.dayOfWeek === dayOfWeek && slot.isActive
);
// If no time slots are configured for this day, it's not selectable
if (dayTimeSlots.length === 0) return false;
// Legacy weekend restriction check (now superseded by time slot configuration)
// Keep for backward compatibility if global settings still matter
if (settings.allow_weekend_bookings === 'false') {
const dayOfWeek = selectedDateOnly.getDay();
if (dayOfWeek === 0 || dayOfWeek === 6) return false; // Sunday or Saturday
@@ -214,6 +288,16 @@ export function EnhancedBookingCalendar() {
const handleSlotClick = (slot: BookingSlot) => {
if (!slot.available) return;
// Double-check that this day is actually bookable
if (!isDayBookable()) {
toast({
title: 'Booking Not Available',
description: `Courts are closed on ${getDayName(selectedDate.getDay())}s`,
variant: 'destructive',
});
return;
}
setSelectedSlot(slot);
setPartnerName('');
setNotes('');
@@ -223,6 +307,17 @@ export function EnhancedBookingCalendar() {
const handleBookingConfirm = async () => {
if (!selectedSlot) return;
// Final validation before API call
if (!isDayBookable()) {
toast({
title: 'Booking Not Available',
description: `Courts are closed on ${getDayName(selectedDate.getDay())}s`,
variant: 'destructive',
});
setShowBookingDialog(false);
return;
}
setLoading(true);
try {
const dateStr = selectedDate.toISOString().split('T')[0];
@@ -426,7 +521,13 @@ export function EnhancedBookingCalendar() {
<MapPin className='h-4 w-4' />
{slot.courtName}
</div>
{!slot.available && (
{!slot.available && slot.bookedBy && (
<div className='flex items-center gap-2 text-xs text-red-600'>
<Users className='h-3 w-3' />
Booked by {slot.bookedBy}
</div>
)}
{!slot.available && !slot.bookedBy && (
<div className='text-xs text-red-600'>Already booked</div>
)}
</div>
@@ -447,7 +548,19 @@ export function EnhancedBookingCalendar() {
{/* No Slots Message */}
{!loading && courts.length > 0 && bookingSlots.length === 0 && (
<div className='text-center py-8'>
<p className='text-gray-500'>No booking slots available for this date</p>
{!isDayBookable() ? (
<div className='space-y-2'>
<div className='text-red-600 font-medium'>
No courts available on {getDayName(selectedDate.getDay())}s
</div>
<p className='text-gray-500 text-sm'>
This facility is closed on {getDayName(selectedDate.getDay())}s.
Please select a different day to make a booking.
</p>
</div>
) : (
<p className='text-gray-500'>No booking slots available for this date</p>
)}
</div>
)}
</div>
-90
View File
@@ -1,90 +0,0 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Bell, LogOut, Settings, User, Calendar } from 'lucide-react';
import { useToast } from '@/hooks/use-toast';
interface DashboardHeaderProps {
user: {
userId: string;
email: string;
role: 'user' | 'admin';
};
}
export function DashboardHeader({ user }: DashboardHeaderProps) {
const router = useRouter();
const { toast } = useToast();
const [isLoggingOut, setIsLoggingOut] = useState(false);
const handleLogout = async () => {
setIsLoggingOut(true);
try {
await fetch('/api/auth/logout', {
method: 'POST',
});
toast({
title: 'Logged out successfully',
description: 'See you next time!',
});
router.push('/login');
router.refresh();
} catch (error) {
toast({
title: 'Logout failed',
description: 'Please try again',
variant: 'destructive',
});
} finally {
setIsLoggingOut(false);
}
};
return (
<header className='bg-white/80 backdrop-blur-md border-b border-gray-200 sticky top-0 z-50'>
<div className='container mx-auto px-4'>
<div className='flex items-center justify-between h-16'>
<div className='flex items-center space-x-4'>
<div className='flex items-center space-x-2'>
<Calendar className='h-6 w-6 text-blue-600' />
<h1 className='text-xl font-bold text-gray-900'>TT Booking</h1>
</div>
{user.role === 'admin' && (
<Badge variant='secondary' className='bg-purple-100 text-purple-800'>
Admin
</Badge>
)}
</div>
<div className='flex items-center space-x-4'>
<Button variant='ghost' size='sm'>
<Bell className='h-4 w-4' />
</Button>
{user.role === 'admin' && (
<Button variant='ghost' size='sm' onClick={() => router.push('/admin')}>
<Settings className='h-4 w-4 mr-2' />
Admin Panel
</Button>
)}
<div className='flex items-center space-x-2'>
<User className='h-4 w-4 text-gray-600' />
<span className='text-sm text-gray-700'>{user.email.split('@')[0]}</span>
</div>
<Button variant='outline' size='sm' onClick={handleLogout} disabled={isLoggingOut}>
<LogOut className='h-4 w-4 mr-2' />
{isLoggingOut ? 'Logging out...' : 'Logout'}
</Button>
</div>
</div>
</div>
</header>
);
}
-135
View File
@@ -1,135 +0,0 @@
'use client';
import { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Calendar, Clock, Users, MapPin, TrendingUp, Activity } from 'lucide-react';
interface DashboardStats {
totalUsers: number;
todayBookings: number;
activeCourts: number;
userBookings: number;
upcomingBookings: number;
}
export function QuickStats() {
const [stats, setStats] = useState<DashboardStats>({
totalUsers: 0,
todayBookings: 0,
activeCourts: 0,
userBookings: 0,
upcomingBookings: 0,
});
const [loading, setLoading] = useState(true);
useEffect(() => {
fetchStats();
}, []);
const fetchStats = async () => {
try {
setLoading(true);
const response = await fetch('/api/dashboard/stats');
if (response.ok) {
const data = await response.json();
setStats(data.stats);
}
} catch (error) {
console.error('Error fetching dashboard stats:', error);
} finally {
setLoading(false);
}
};
if (loading) {
return (
<div className='space-y-4'>
<Card>
<CardContent className='p-6'>
<div className='animate-pulse'>
<div className='h-4 bg-gray-200 rounded w-3/4 mb-4'></div>
<div className='space-y-3'>
{[1, 2, 3, 4].map((i) => (
<div key={i} className='flex justify-between'>
<div className='h-3 bg-gray-200 rounded w-1/2'></div>
<div className='h-3 bg-gray-200 rounded w-1/4'></div>
</div>
))}
</div>
</div>
</CardContent>
</Card>
</div>
);
}
return (
<div className='space-y-4'>
<Card>
<CardHeader className='pb-3'>
<CardTitle className='text-base'>Quick Stats</CardTitle>
</CardHeader>
<CardContent className='space-y-4'>
<div className='flex items-center justify-between'>
<div className='flex items-center gap-2'>
<Calendar className='h-4 w-4 text-blue-600' />
<span className='text-sm'>Your Bookings</span>
</div>
<Badge variant='secondary'>{stats.userBookings} active</Badge>
</div>
<div className='flex items-center justify-between'>
<div className='flex items-center gap-2'>
<Clock className='h-4 w-4 text-green-600' />
<span className='text-sm'>Upcoming</span>
</div>
<Badge variant='secondary'>{stats.upcomingBookings} bookings</Badge>
</div>
<div className='flex items-center justify-between'>
<div className='flex items-center gap-2'>
<MapPin className='h-4 w-4 text-purple-600' />
<span className='text-sm'>Active Courts</span>
</div>
<Badge variant='secondary'>{stats.activeCourts} available</Badge>
</div>
<div className='flex items-center justify-between'>
<div className='flex items-center gap-2'>
<Activity className='h-4 w-4 text-orange-600' />
<span className='text-sm'>Today\'s Bookings</span>
</div>
<Badge variant='secondary'>{stats.todayBookings} total</Badge>
</div>
</CardContent>
</Card>
<Card>
<CardHeader className='pb-3'>
<CardTitle className='text-base'>System Info</CardTitle>
</CardHeader>
<CardContent className='space-y-3'>
<div className='flex items-center justify-between'>
<div className='flex items-center gap-2'>
<Users className='h-4 w-4 text-gray-600' />
<span className='text-sm'>Total Users</span>
</div>
<Badge variant='outline'>{stats.totalUsers}</Badge>
</div>
<div className='flex items-center justify-between'>
<div className='flex items-center gap-2'>
<TrendingUp className='h-4 w-4 text-green-600' />
<span className='text-sm'>System Status</span>
</div>
<div className='flex items-center gap-2'>
<div className='h-2 w-2 bg-green-500 rounded-full' />
<span className='text-xs text-green-600'>Online</span>
</div>
</div>
</CardContent>
</Card>
</div>
);
}