additional features, refinement and more control over the app from admin side, better bookings UX

This commit is contained in:
mikicvi
2025-09-25 20:23:18 +01:00
parent 6d3202e385
commit b89d91ade2
20 changed files with 1358 additions and 328 deletions
+1 -1
View File
@@ -17,7 +17,7 @@ export async function GET(request: NextRequest) {
// Build query conditions
const whereConditions = [];
whereConditions.push(eq(bookings.status, 'active'));
if (date) {
whereConditions.push(eq(bookings.date, date));
}
+77 -12
View File
@@ -1,6 +1,6 @@
import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { bookings, courts, timeSlots } from '@/lib/db/schema';
import { bookings, courts, timeSlots, settings, metrics } from '@/lib/db/schema';
import { eq, and } from 'drizzle-orm';
import { getSession } from '@/lib/session';
import { logActivity, ACTIONS, ENTITY_TYPES } from '@/lib/activity-logger';
@@ -45,7 +45,7 @@ export async function POST(request: NextRequest) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const { courtId, date, timeSlot } = await request.json();
const { courtId, date, timeSlot, notes } = await request.json();
if (!courtId || !date || !timeSlot) {
return NextResponse.json(
@@ -91,18 +91,15 @@ export async function POST(request: NextRequest) {
const availableTimeSlots = await db
.select()
.from(timeSlots)
.where(
and(
eq(timeSlots.dayOfWeek, dayOfWeek),
eq(timeSlots.isActive, true)
)
);
.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.`,
error: `No bookings are allowed on ${
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][dayOfWeek]
}s. The facility is closed on this day.`,
},
{ status: 400 }
);
@@ -110,17 +107,50 @@ export async function POST(request: NextRequest) {
// 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 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(', ');
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}`,
error: `Time slot ${startTime} is not available on ${
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][dayOfWeek]
}s. Available times: ${allowedRanges}`,
},
{ status: 400 }
);
}
// Check booking restrictions per user per hour per day
const maxBookingsSetting = await db
.select()
.from(settings)
.where(eq(settings.key, 'max_bookings_per_user_per_hour_per_day'))
.limit(1);
const maxBookingsPerHour = maxBookingsSetting.length > 0 ? parseInt(maxBookingsSetting[0].value) : 1; // Default to 1 if setting not found
// Count user's existing bookings for this hour on this day
const userBookingsThisHour = await db
.select()
.from(bookings)
.where(
and(
eq(bookings.userId, session.userId),
eq(bookings.date, date),
eq(bookings.startTime, startTime),
eq(bookings.status, 'active')
)
);
if (userBookingsThisHour.length >= maxBookingsPerHour) {
return NextResponse.json(
{
error: `You have reached the maximum limit of ${maxBookingsPerHour} booking(s) per hour. You already have ${userBookingsThisHour.length} booking(s) at ${startTime} on this date.`,
},
{ status: 400 }
);
@@ -160,6 +190,7 @@ export async function POST(request: NextRequest) {
startTime,
endTime,
status: 'active',
notes: notes || null, // Include notes from the request
createdAt: new Date(),
updatedAt: new Date(),
})
@@ -181,6 +212,40 @@ export async function POST(request: NextRequest) {
request,
});
// Update monthly metrics
const currentMonth = new Date().toISOString().substring(0, 7); // "2025-09"
try {
const existingMetric = await db
.select()
.from(metrics)
.where(and(eq(metrics.metricType, 'monthly_bookings'), eq(metrics.period, currentMonth)))
.limit(1);
if (existingMetric.length > 0) {
// Increment existing metric
await db
.update(metrics)
.set({
value: existingMetric[0].value + 1,
updatedAt: new Date(),
})
.where(eq(metrics.id, existingMetric[0].id));
} else {
// Create new metric for this month
await db.insert(metrics).values({
id: crypto.randomUUID(),
metricType: 'monthly_bookings',
period: currentMonth,
value: 1,
createdAt: new Date(),
updatedAt: new Date(),
});
}
} catch (error) {
console.error('Error updating monthly metrics:', error);
// Don't fail the booking if metrics update fails
}
return NextResponse.json({
booking: newBooking,
message: 'Booking created successfully',