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
+109
View File
@@ -0,0 +1,109 @@
import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/session';
import { db } from '@/lib/db';
import { timeSlots } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
import { logActivity, ACTIONS, ENTITY_TYPES } from '@/lib/activity-logger';
export async function PUT(request: NextRequest, { params }: { params: { id: string } }) {
try {
const session = await getSession();
if (!session || session.role !== 'admin') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { id } = params;
const { dayOfWeek, startTime, endTime, isActive } = await request.json();
// Check if time slot exists
const existingTimeSlot = await db.select().from(timeSlots).where(eq(timeSlots.id, id)).limit(1);
if (existingTimeSlot.length === 0) {
return NextResponse.json({ error: 'Time slot not found' }, { status: 404 });
}
// Validate inputs if provided
if (dayOfWeek !== undefined && (dayOfWeek < 0 || dayOfWeek > 6)) {
return NextResponse.json(
{ error: 'dayOfWeek must be between 0 (Sunday) and 6 (Saturday)' },
{ status: 400 }
);
}
const timeRegex = /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/;
if (startTime && !timeRegex.test(startTime)) {
return NextResponse.json(
{ error: 'Invalid startTime format. Use HH:MM format' },
{ status: 400 }
);
}
if (endTime && !timeRegex.test(endTime)) {
return NextResponse.json(
{ error: 'Invalid endTime format. Use HH:MM format' },
{ status: 400 }
);
}
const updatedTimeSlot = await db
.update(timeSlots)
.set({
...(dayOfWeek !== undefined && { dayOfWeek }),
...(startTime && { startTime }),
...(endTime && { endTime }),
...(isActive !== undefined && { isActive }),
updatedAt: new Date(),
})
.where(eq(timeSlots.id, id))
.returning();
await logActivity({
userId: session.userId,
action: ACTIONS.TIME_SLOT_UPDATE,
entityType: ENTITY_TYPES.TIME_SLOT,
entityId: id,
details: { dayOfWeek, startTime, endTime, isActive },
});
return NextResponse.json({
message: 'Time slot updated successfully',
timeSlot: updatedTimeSlot[0],
});
} catch (error) {
console.error('Error updating time slot:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function DELETE(request: NextRequest, { params }: { params: { id: string } }) {
try {
const session = await getSession();
if (!session || session.role !== 'admin') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { id } = params;
// Check if time slot exists
const existingTimeSlot = await db.select().from(timeSlots).where(eq(timeSlots.id, id)).limit(1);
if (existingTimeSlot.length === 0) {
return NextResponse.json({ error: 'Time slot not found' }, { status: 404 });
}
await db.delete(timeSlots).where(eq(timeSlots.id, id));
await logActivity({
userId: session.userId,
action: ACTIONS.TIME_SLOT_DELETE,
entityType: ENTITY_TYPES.TIME_SLOT,
entityId: id,
details: { deleted: existingTimeSlot[0] },
});
return NextResponse.json({
message: 'Time slot deleted successfully',
});
} catch (error) {
console.error('Error deleting time slot:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+91
View File
@@ -0,0 +1,91 @@
import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/session';
import { db } from '@/lib/db';
import { timeSlots } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
import { logActivity, ACTIONS, ENTITY_TYPES } from '@/lib/activity-logger';
export async function GET(request: NextRequest) {
try {
const session = await getSession();
if (!session || session.role !== 'admin') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const allTimeSlots = await db
.select()
.from(timeSlots)
.orderBy(timeSlots.dayOfWeek, timeSlots.startTime);
return NextResponse.json({
timeSlots: allTimeSlots,
});
} catch (error) {
console.error('Error fetching time slots:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function POST(request: NextRequest) {
try {
const session = await getSession();
if (!session || session.role !== 'admin') {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { dayOfWeek, startTime, endTime, isActive = true } = await request.json();
if (dayOfWeek === undefined || !startTime || !endTime) {
return NextResponse.json(
{ error: 'Missing required fields: dayOfWeek, startTime, endTime' },
{ status: 400 }
);
}
// Validate day of week (0-6)
if (dayOfWeek < 0 || dayOfWeek > 6) {
return NextResponse.json(
{ error: 'dayOfWeek must be between 0 (Sunday) and 6 (Saturday)' },
{ status: 400 }
);
}
// Validate time format (HH:MM)
const timeRegex = /^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/;
if (!timeRegex.test(startTime) || !timeRegex.test(endTime)) {
return NextResponse.json(
{ error: 'Invalid time format. Use HH:MM format' },
{ status: 400 }
);
}
const newTimeSlot = await db
.insert(timeSlots)
.values({
id: crypto.randomUUID(),
dayOfWeek,
startTime,
endTime,
isActive,
createdAt: new Date(),
updatedAt: new Date(),
})
.returning();
await logActivity({
userId: session.userId,
action: ACTIONS.TIME_SLOT_CREATE,
entityType: ENTITY_TYPES.TIME_SLOT,
entityId: newTimeSlot[0].id,
details: { dayOfWeek, startTime, endTime },
});
return NextResponse.json({
message: 'Time slot created successfully',
timeSlot: newTimeSlot[0],
});
} catch (error) {
console.error('Error creating time slot:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+56
View File
@@ -0,0 +1,56 @@
import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/session';
import { db } from '@/lib/db';
import { bookings, courts, users } from '@/lib/db/schema';
import { eq, and } from 'drizzle-orm';
export async function GET(request: NextRequest) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { searchParams } = new URL(request.url);
const date = searchParams.get('date');
// Build query conditions
const whereConditions = [];
whereConditions.push(eq(bookings.status, 'active'));
if (date) {
whereConditions.push(eq(bookings.date, date));
}
// Get all active bookings with user and court information
const allBookings = await db
.select({
id: bookings.id,
courtId: bookings.courtId,
date: bookings.date,
startTime: bookings.startTime,
endTime: bookings.endTime,
status: bookings.status,
notes: bookings.notes,
createdAt: bookings.createdAt,
court: {
id: courts.id,
name: courts.name,
},
user: {
id: users.id,
name: users.name,
surname: users.surname,
},
})
.from(bookings)
.innerJoin(courts, eq(bookings.courtId, courts.id))
.innerJoin(users, eq(bookings.userId, users.id))
.where(whereConditions.length > 1 ? and(...whereConditions) : whereConditions[0]);
return NextResponse.json({ bookings: allBookings });
} catch (error) {
console.error('Error fetching all bookings:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
-129
View File
@@ -1,129 +0,0 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { bookings, courts } from '@/lib/db/schema';
import { eq, and } from 'drizzle-orm';
import { getSession } from '@/lib/session';
export async function GET(request: NextRequest) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const userBookings = await db
.select({
id: bookings.id,
courtId: bookings.courtId,
date: bookings.date,
startTime: bookings.startTime,
endTime: bookings.endTime,
status: bookings.status,
createdAt: bookings.createdAt,
})
.from(bookings)
.where(eq(bookings.userId, session.userId));
return NextResponse.json({ bookings: userBookings });
} catch (error) {
console.error('Error fetching bookings:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function POST(request: NextRequest) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { courtId, date, timeSlot } = await request.json();
if (!courtId || !date || !timeSlot) {
return NextResponse.json(
{
error: 'Missing required fields: courtId, date, timeSlot',
},
{ status: 400 }
);
}
// Parse timeSlot (e.g., "14:00") to get start and end times
const startTime = timeSlot;
const [hours, minutes] = timeSlot.split(':').map(Number);
const endTime = `${String(hours + 1).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
// Validate booking date is not in the past
const bookingDate = new Date(date);
const today = new Date();
today.setHours(0, 0, 0, 0);
if (bookingDate < today) {
return NextResponse.json(
{
error: 'Cannot book dates in the past',
},
{ status: 400 }
);
}
// Check if court exists and is active
const court = await db.select().from(courts).where(eq(courts.id, courtId)).limit(1);
if (court.length === 0 || !court[0].isActive) {
return NextResponse.json(
{
error: 'Court not found or inactive',
},
{ status: 400 }
);
}
// Check if slot is already booked
const existingBooking = await db
.select()
.from(bookings)
.where(
and(
eq(bookings.courtId, courtId),
eq(bookings.date, date),
eq(bookings.startTime, startTime),
eq(bookings.status, 'active')
)
)
.limit(1);
if (existingBooking.length > 0) {
return NextResponse.json(
{
error: 'Time slot already booked',
},
{ status: 400 }
);
}
// Create the booking
const [newBooking] = await db
.insert(bookings)
.values({
id: crypto.randomUUID(),
userId: session.userId,
courtId,
date,
startTime,
endTime,
status: 'active',
createdAt: new Date(),
updatedAt: new Date(),
})
.returning();
return NextResponse.json({
booking: newBooking,
message: 'Booking created successfully',
});
} catch (error) {
console.error('Error creating booking:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
-129
View File
@@ -1,129 +0,0 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { bookings, courts } from '@/lib/db/schema';
import { eq, and } from 'drizzle-orm';
import { getSession } from '@/lib/session';
export async function GET(request: NextRequest) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const userBookings = await db
.select({
id: bookings.id,
courtId: bookings.courtId,
date: bookings.date,
startTime: bookings.startTime,
endTime: bookings.endTime,
status: bookings.status,
createdAt: bookings.createdAt,
})
.from(bookings)
.where(eq(bookings.userId, session.userId));
return NextResponse.json({ bookings: userBookings });
} catch (error) {
console.error('Error fetching bookings:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function POST(request: NextRequest) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { courtId, date, timeSlot } = await request.json();
if (!courtId || !date || !timeSlot) {
return NextResponse.json(
{
error: 'Missing required fields: courtId, date, timeSlot',
},
{ status: 400 }
);
}
// Parse timeSlot (e.g., "14:00") to get start and end times
const startTime = timeSlot;
const [hours, minutes] = timeSlot.split(':').map(Number);
const endTime = `${String(hours + 1).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`;
// Validate booking date is not in the past
const bookingDate = new Date(date);
const today = new Date();
today.setHours(0, 0, 0, 0);
if (bookingDate < today) {
return NextResponse.json(
{
error: 'Cannot book dates in the past',
},
{ status: 400 }
);
}
// Check if court exists and is active
const court = await db.select().from(courts).where(eq(courts.id, courtId)).limit(1);
if (court.length === 0 || !court[0].isActive) {
return NextResponse.json(
{
error: 'Court not found or inactive',
},
{ status: 400 }
);
}
// Check if slot is already booked
const existingBooking = await db
.select()
.from(bookings)
.where(
and(
eq(bookings.courtId, courtId),
eq(bookings.date, date),
eq(bookings.startTime, startTime),
eq(bookings.status, 'active')
)
)
.limit(1);
if (existingBooking.length > 0) {
return NextResponse.json(
{
error: 'Time slot already booked',
},
{ status: 400 }
);
}
// Create the booking
const [newBooking] = await db
.insert(bookings)
.values({
id: crypto.randomUUID(),
userId: session.userId,
courtId,
date,
startTime,
endTime,
status: 'active',
createdAt: new Date(),
updatedAt: new Date(),
})
.returning();
return NextResponse.json({
booking: newBooking,
message: 'Booking created successfully',
});
} catch (error) {
console.error('Error creating booking:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+41 -1
View File
@@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { bookings, courts } from '@/lib/db/schema';
import { bookings, courts, timeSlots } from '@/lib/db/schema';
import { eq, and } from 'drizzle-orm';
import { getSession } from '@/lib/session';
import { logActivity, ACTIONS, ENTITY_TYPES } from '@/lib/activity-logger';
@@ -86,6 +86,46 @@ export async function POST(request: NextRequest) {
);
}
// CRITICAL: Validate that booking is allowed for this day and time
const dayOfWeek = bookingDate.getDay();
const availableTimeSlots = await db
.select()
.from(timeSlots)
.where(
and(
eq(timeSlots.dayOfWeek, dayOfWeek),
eq(timeSlots.isActive, true)
)
);
// Check if any time slots are configured for this day
if (availableTimeSlots.length === 0) {
return NextResponse.json(
{
error: `No bookings are allowed on ${['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][dayOfWeek]}s. The facility is closed on this day.`,
},
{ status: 400 }
);
}
// Check if the requested time slot is within any of the allowed time ranges
const requestedHour = parseInt(startTime.split(':')[0]);
const isTimeSlotValid = availableTimeSlots.some(slot => {
const slotStartHour = parseInt(slot.startTime.split(':')[0]);
const slotEndHour = parseInt(slot.endTime.split(':')[0]);
return requestedHour >= slotStartHour && requestedHour < slotEndHour;
});
if (!isTimeSlotValid) {
const allowedRanges = availableTimeSlots.map(slot => `${slot.startTime}-${slot.endTime}`).join(', ');
return NextResponse.json(
{
error: `Time slot ${startTime} is not available on ${['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][dayOfWeek]}s. Available times: ${allowedRanges}`,
},
{ status: 400 }
);
}
// Check if slot is already booked
const existingBooking = await db
.select()
+28
View File
@@ -0,0 +1,28 @@
import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/session';
import { db } from '@/lib/db';
import { timeSlots } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
export async function GET(request: NextRequest) {
try {
const session = await getSession();
if (!session) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
// Get all active time slots
const allTimeSlots = await db
.select()
.from(timeSlots)
.where(eq(timeSlots.isActive, true))
.orderBy(timeSlots.dayOfWeek, timeSlots.startTime);
return NextResponse.json({
timeSlots: allTimeSlots,
});
} catch (error) {
console.error('Error fetching time slots:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}