initial version of the app
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { announcements } from '@/lib/db/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { getSession } from '@/lib/session';
|
||||
|
||||
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 { title, content, priority, expiresAt, isActive } = await request.json();
|
||||
const announcementId = params.id;
|
||||
|
||||
if (!title || !content) {
|
||||
return NextResponse.json({ error: 'Title and content are required' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Check if announcement exists
|
||||
const existing = await db.select().from(announcements).where(eq(announcements.id, announcementId)).limit(1);
|
||||
|
||||
if (existing.length === 0) {
|
||||
return NextResponse.json({ error: 'Announcement not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Update announcement
|
||||
const [updatedAnnouncement] = await db
|
||||
.update(announcements)
|
||||
.set({
|
||||
title,
|
||||
content,
|
||||
priority: priority || 'medium',
|
||||
expiresAt: expiresAt ? new Date(expiresAt) : null,
|
||||
isActive: isActive !== undefined ? isActive : true,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(announcements.id, announcementId))
|
||||
.returning();
|
||||
|
||||
return NextResponse.json({
|
||||
announcement: updatedAnnouncement,
|
||||
message: 'Announcement updated successfully',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating announcement:', 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 announcementId = params.id;
|
||||
|
||||
// Check if announcement exists
|
||||
const existing = await db.select().from(announcements).where(eq(announcements.id, announcementId)).limit(1);
|
||||
|
||||
if (existing.length === 0) {
|
||||
return NextResponse.json({ error: 'Announcement not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Delete announcement
|
||||
await db.delete(announcements).where(eq(announcements.id, announcementId));
|
||||
|
||||
return NextResponse.json({ message: 'Announcement deleted successfully' });
|
||||
} catch (error) {
|
||||
console.error('Error deleting announcement:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { announcements } from '@/lib/db/schema';
|
||||
import { eq, desc } 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 });
|
||||
}
|
||||
|
||||
// Regular users see only active announcements, admins see all
|
||||
const allAnnouncements = await db
|
||||
.select()
|
||||
.from(announcements)
|
||||
.where(session.role === 'admin' ? undefined : eq(announcements.isActive, true))
|
||||
.orderBy(desc(announcements.createdAt));
|
||||
|
||||
return NextResponse.json({ announcements: allAnnouncements });
|
||||
} catch (error) {
|
||||
console.error('Error fetching announcements:', 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 { title, content, priority, expiresAt } = await request.json();
|
||||
|
||||
if (!title || !content) {
|
||||
return NextResponse.json({ error: 'Title and content are required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const [newAnnouncement] = await db
|
||||
.insert(announcements)
|
||||
.values({
|
||||
id: crypto.randomUUID(),
|
||||
title,
|
||||
content,
|
||||
priority: priority || 'medium',
|
||||
expiresAt: expiresAt ? new Date(expiresAt) : null,
|
||||
isActive: true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.returning();
|
||||
|
||||
return NextResponse.json({
|
||||
announcement: newAnnouncement,
|
||||
message: 'Announcement created successfully',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error creating announcement:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { courts } from '@/lib/db/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { getSession } from '@/lib/session';
|
||||
|
||||
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 { name, isActive } = await request.json();
|
||||
const courtId = params.id;
|
||||
|
||||
if (!name) {
|
||||
return NextResponse.json({ error: 'Court name is required' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Check if court exists
|
||||
const existing = await db.select().from(courts).where(eq(courts.id, courtId)).limit(1);
|
||||
|
||||
if (existing.length === 0) {
|
||||
return NextResponse.json({ error: 'Court not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Update court
|
||||
const [updatedCourt] = await db
|
||||
.update(courts)
|
||||
.set({
|
||||
name,
|
||||
isActive: isActive !== undefined ? isActive : true,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(courts.id, courtId))
|
||||
.returning();
|
||||
|
||||
return NextResponse.json({
|
||||
court: updatedCourt,
|
||||
message: 'Court updated successfully',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating court:', 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 courtId = params.id;
|
||||
|
||||
// Check if court exists
|
||||
const existing = await db.select().from(courts).where(eq(courts.id, courtId)).limit(1);
|
||||
|
||||
if (existing.length === 0) {
|
||||
return NextResponse.json({ error: 'Court not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Delete court (this will cascade to bookings due to foreign key)
|
||||
await db.delete(courts).where(eq(courts.id, courtId));
|
||||
|
||||
return NextResponse.json({ message: 'Court deleted successfully' });
|
||||
} catch (error) {
|
||||
console.error('Error deleting court:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { courts } from '@/lib/db/schema';
|
||||
import { eq } 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 });
|
||||
}
|
||||
|
||||
// Regular users see only active courts, admins see all
|
||||
const allCourts = await db
|
||||
.select()
|
||||
.from(courts)
|
||||
.where(session.role === 'admin' ? undefined : eq(courts.isActive, true));
|
||||
|
||||
return NextResponse.json({ courts: allCourts });
|
||||
} catch (error) {
|
||||
console.error('Error fetching courts:', 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 { name, isActive } = await request.json();
|
||||
|
||||
if (!name) {
|
||||
return NextResponse.json({ error: 'Court name is required' }, { status: 400 });
|
||||
}
|
||||
|
||||
const [newCourt] = await db
|
||||
.insert(courts)
|
||||
.values({
|
||||
id: crypto.randomUUID(),
|
||||
name,
|
||||
isActive: isActive !== undefined ? isActive : true,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.returning();
|
||||
|
||||
return NextResponse.json({
|
||||
court: newCourt,
|
||||
message: 'Court created successfully',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error creating court:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { verifySession } from '@/lib/session';
|
||||
import { db } from '@/lib/db';
|
||||
import { activityLogs, users } from '@/lib/db/schema';
|
||||
import { eq, desc, isNull, or } from 'drizzle-orm';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await verifySession();
|
||||
if (!session.isAuth || session.role !== 'admin') {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const limit = parseInt(searchParams.get('limit') || '20');
|
||||
const offset = parseInt(searchParams.get('offset') || '0');
|
||||
|
||||
// Get activity logs with user details
|
||||
const logs = await db
|
||||
.select({
|
||||
id: activityLogs.id,
|
||||
action: activityLogs.action,
|
||||
entityType: activityLogs.entityType,
|
||||
entityId: activityLogs.entityId,
|
||||
details: activityLogs.details,
|
||||
ipAddress: activityLogs.ipAddress,
|
||||
userAgent: activityLogs.userAgent,
|
||||
createdAt: activityLogs.createdAt,
|
||||
user: {
|
||||
id: users.id,
|
||||
name: users.name,
|
||||
surname: users.surname,
|
||||
email: users.email,
|
||||
},
|
||||
})
|
||||
.from(activityLogs)
|
||||
.leftJoin(users, eq(activityLogs.userId, users.id))
|
||||
.orderBy(desc(activityLogs.createdAt))
|
||||
.limit(limit)
|
||||
.offset(offset);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
logs,
|
||||
pagination: {
|
||||
limit,
|
||||
offset,
|
||||
hasMore: logs.length === limit,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching activity logs:', error);
|
||||
return NextResponse.json({ error: 'Failed to fetch activity logs' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { action, entityType, entityId, details, ipAddress, userAgent } = body;
|
||||
|
||||
if (!action || !entityType) {
|
||||
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
|
||||
}
|
||||
|
||||
const session = await verifySession();
|
||||
const userId = session.isAuth ? session.userId : null;
|
||||
|
||||
// Create activity log
|
||||
const [log] = await db
|
||||
.insert(activityLogs)
|
||||
.values({
|
||||
id: crypto.randomUUID(),
|
||||
userId,
|
||||
action,
|
||||
entityType,
|
||||
entityId,
|
||||
details: details ? JSON.stringify(details) : null,
|
||||
ipAddress,
|
||||
userAgent,
|
||||
createdAt: new Date(),
|
||||
})
|
||||
.returning();
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
log,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error creating activity log:', error);
|
||||
return NextResponse.json({ error: 'Failed to create activity log' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { verifySession } from '@/lib/session';
|
||||
import { db } from '@/lib/db';
|
||||
import { bookings, users, courts } from '@/lib/db/schema';
|
||||
import { eq, desc, gte } from 'drizzle-orm';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await verifySession();
|
||||
if (!session.isAuth || session.role !== 'admin') {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const limit = parseInt(searchParams.get('limit') || '10');
|
||||
|
||||
// Get recent bookings with user and court details
|
||||
const recentBookings = await db
|
||||
.select({
|
||||
id: bookings.id,
|
||||
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,
|
||||
email: users.email,
|
||||
},
|
||||
})
|
||||
.from(bookings)
|
||||
.innerJoin(courts, eq(bookings.courtId, courts.id))
|
||||
.innerJoin(users, eq(bookings.userId, users.id))
|
||||
.orderBy(desc(bookings.createdAt))
|
||||
.limit(limit);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
bookings: recentBookings,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching admin recent bookings:', error);
|
||||
return NextResponse.json({ error: 'Failed to fetch recent bookings' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { settings } from '@/lib/db/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { getSession } from '@/lib/session';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session || session.role !== 'admin') {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const allSettings = await db.select().from(settings);
|
||||
|
||||
// Convert to key-value object for easier use
|
||||
const settingsObj = allSettings.reduce((acc: any, setting) => {
|
||||
acc[setting.key] = setting.value;
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
return NextResponse.json({ settings: allSettings });
|
||||
} catch (error) {
|
||||
console.error('Error fetching settings:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: NextRequest) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session || session.role !== 'admin') {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { settings: newSettings } = await request.json();
|
||||
|
||||
if (!newSettings || !Array.isArray(newSettings)) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Invalid settings format. Expected array of {key, value} objects' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Update each setting
|
||||
const updatePromises = newSettings.map(async ({ key, value }) => {
|
||||
if (!key || value === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Try to update existing setting first
|
||||
const result = await db
|
||||
.update(settings)
|
||||
.set({
|
||||
value: String(value),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(settings.key, key));
|
||||
|
||||
// If no rows were updated, insert new setting
|
||||
if (!result.changes) {
|
||||
await db.insert(settings).values({
|
||||
id: crypto.randomUUID(),
|
||||
key,
|
||||
value: String(value),
|
||||
updatedAt: new Date(),
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(updatePromises);
|
||||
|
||||
return NextResponse.json({ message: 'Settings updated successfully' });
|
||||
} catch (error) {
|
||||
console.error('Error updating settings:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { users } from '@/lib/db/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { getSession } from '@/lib/session';
|
||||
import bcrypt from 'bcryptjs';
|
||||
|
||||
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 { name, surname, email, role, password } = await request.json();
|
||||
const userId = params.id;
|
||||
|
||||
if (!name || !surname || !email) {
|
||||
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Check if user exists
|
||||
const existingUser = await db.select().from(users).where(eq(users.id, userId)).limit(1);
|
||||
|
||||
if (existingUser.length === 0) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Prepare update data
|
||||
const updateData: any = {
|
||||
name,
|
||||
surname,
|
||||
email,
|
||||
role: role || 'user',
|
||||
updatedAt: new Date(),
|
||||
};
|
||||
|
||||
// Only hash and update password if provided
|
||||
if (password) {
|
||||
updateData.password = await bcrypt.hash(password, 12);
|
||||
}
|
||||
|
||||
// Update user
|
||||
const [updatedUser] = await db.update(users).set(updateData).where(eq(users.id, userId)).returning({
|
||||
id: users.id,
|
||||
name: users.name,
|
||||
surname: users.surname,
|
||||
email: users.email,
|
||||
role: users.role,
|
||||
createdAt: users.createdAt,
|
||||
updatedAt: users.updatedAt,
|
||||
});
|
||||
|
||||
return NextResponse.json({ user: updatedUser, message: 'User updated successfully' });
|
||||
} catch (error) {
|
||||
console.error('Error updating user:', 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 userId = params.id;
|
||||
|
||||
// Prevent admin from deleting themselves
|
||||
if (session.userId === userId) {
|
||||
return NextResponse.json({ error: 'Cannot delete your own account' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Check if user exists
|
||||
const existingUser = await db.select().from(users).where(eq(users.id, userId)).limit(1);
|
||||
|
||||
if (existingUser.length === 0) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Delete user
|
||||
await db.delete(users).where(eq(users.id, userId));
|
||||
|
||||
return NextResponse.json({ message: 'User deleted successfully' });
|
||||
} catch (error) {
|
||||
console.error('Error deleting user:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { users } from '@/lib/db/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { getSession } from '@/lib/session';
|
||||
import bcrypt from 'bcryptjs';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session || session.role !== 'admin') {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const allUsers = await db
|
||||
.select({
|
||||
id: users.id,
|
||||
name: users.name,
|
||||
surname: users.surname,
|
||||
email: users.email,
|
||||
role: users.role,
|
||||
createdAt: users.createdAt,
|
||||
})
|
||||
.from(users);
|
||||
|
||||
return NextResponse.json({ users: allUsers });
|
||||
} catch (error) {
|
||||
console.error('Error fetching users:', 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 { name, surname, email, password, role } = await request.json();
|
||||
|
||||
if (!name || !surname || !email || !password) {
|
||||
return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Check if user already exists
|
||||
const existingUser = await db.select().from(users).where(eq(users.email, email)).limit(1);
|
||||
|
||||
if (existingUser.length > 0) {
|
||||
return NextResponse.json({ error: 'User with this email already exists' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Hash password
|
||||
const hashedPassword = await bcrypt.hash(password, 12);
|
||||
|
||||
// Create user
|
||||
const [newUser] = await db
|
||||
.insert(users)
|
||||
.values({
|
||||
id: crypto.randomUUID(),
|
||||
name,
|
||||
surname,
|
||||
email,
|
||||
password: hashedPassword,
|
||||
role: role || 'user',
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.returning({
|
||||
id: users.id,
|
||||
name: users.name,
|
||||
surname: users.surname,
|
||||
email: users.email,
|
||||
role: users.role,
|
||||
createdAt: users.createdAt,
|
||||
});
|
||||
|
||||
return NextResponse.json({ user: newUser, message: 'User created successfully' });
|
||||
} catch (error) {
|
||||
console.error('Error creating user:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getSession } from '@/lib/session';
|
||||
import { db } from '@/lib/db';
|
||||
import { announcements } from '@/lib/db/schema';
|
||||
import { desc, 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 announcements, ordered by creation date (newest first)
|
||||
const allAnnouncements = await db
|
||||
.select({
|
||||
id: announcements.id,
|
||||
title: announcements.title,
|
||||
content: announcements.content,
|
||||
priority: announcements.priority,
|
||||
isActive: announcements.isActive,
|
||||
createdAt: announcements.createdAt,
|
||||
})
|
||||
.from(announcements)
|
||||
.where(eq(announcements.isActive, true))
|
||||
.orderBy(desc(announcements.createdAt));
|
||||
|
||||
return NextResponse.json({
|
||||
announcements: allAnnouncements,
|
||||
unreadCount: allAnnouncements.length, // For now, all announcements are considered unread
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching announcements:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { users } from '@/lib/db/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { createSession } from '@/lib/session';
|
||||
import { logActivity, ACTIONS, ENTITY_TYPES } from '@/lib/activity-logger';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const { email, password } = await request.json();
|
||||
|
||||
if (!email || !password) {
|
||||
return NextResponse.json({ error: 'Email and password are required' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Find user by email
|
||||
const user = await db.select().from(users).where(eq(users.email, email)).limit(1);
|
||||
|
||||
if (user.length === 0) {
|
||||
return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
|
||||
}
|
||||
|
||||
// Verify password
|
||||
const isValid = await bcrypt.compare(password, user[0].password);
|
||||
|
||||
if (!isValid) {
|
||||
return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
|
||||
}
|
||||
|
||||
// Create session
|
||||
await createSession({
|
||||
userId: user[0].id,
|
||||
email: user[0].email,
|
||||
role: user[0].role as 'user' | 'admin',
|
||||
});
|
||||
|
||||
// Log the login activity
|
||||
await logActivity({
|
||||
userId: user[0].id,
|
||||
action: ACTIONS.USER_LOGIN,
|
||||
entityType: ENTITY_TYPES.USER,
|
||||
entityId: user[0].id,
|
||||
details: {
|
||||
email: user[0].email,
|
||||
role: user[0].role,
|
||||
},
|
||||
request,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
user: {
|
||||
id: user[0].id,
|
||||
email: user[0].email,
|
||||
name: user[0].name,
|
||||
surname: user[0].surname,
|
||||
role: user[0].role,
|
||||
},
|
||||
message: 'Login successful',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { deleteSession } from '@/lib/session';
|
||||
|
||||
export async function POST() {
|
||||
await deleteSession();
|
||||
return NextResponse.json({ message: 'Logout successful' });
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { users } from '@/lib/db/schema';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { createSession } from '@/lib/session';
|
||||
import { z } from 'zod';
|
||||
|
||||
const registerSchema = z.object({
|
||||
email: z.string().email(),
|
||||
name: z.string().min(1),
|
||||
surname: z.string().min(1),
|
||||
password: z.string().min(6),
|
||||
});
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
const validatedData = registerSchema.parse(body);
|
||||
|
||||
// Check if user already exists
|
||||
const existingUser = await db.select().from(users).where(eq(users.email, validatedData.email)).limit(1);
|
||||
if (existingUser.length > 0) {
|
||||
return NextResponse.json({ error: 'User with this email already exists' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Hash password
|
||||
const hashedPassword = await bcrypt.hash(validatedData.password, 10);
|
||||
|
||||
// Create new user
|
||||
const [newUser] = await db
|
||||
.insert(users)
|
||||
.values({
|
||||
id: crypto.randomUUID(),
|
||||
email: validatedData.email,
|
||||
name: validatedData.name,
|
||||
surname: validatedData.surname,
|
||||
password: hashedPassword,
|
||||
role: 'user',
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.returning();
|
||||
|
||||
// Create session
|
||||
await createSession({
|
||||
userId: newUser.id,
|
||||
email: newUser.email,
|
||||
role: newUser.role as 'user' | 'admin',
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
user: {
|
||||
id: newUser.id,
|
||||
email: newUser.email,
|
||||
name: newUser.name,
|
||||
surname: newUser.surname,
|
||||
role: newUser.role,
|
||||
},
|
||||
message: 'User created successfully',
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
return NextResponse.json({ error: 'Invalid input data', details: error.errors }, { status: 400 });
|
||||
}
|
||||
|
||||
console.error('Registration error:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getSession } from '@/lib/session';
|
||||
import { db } from '@/lib/db';
|
||||
import { bookings } from '@/lib/db/schema';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { logActivity, ACTIONS, ENTITY_TYPES } from '@/lib/activity-logger';
|
||||
|
||||
export async function PATCH(request: NextRequest, { params }: { params: { id: string } }) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { notes } = await request.json();
|
||||
const bookingId = params.id;
|
||||
|
||||
// Check if booking exists and belongs to user
|
||||
const existingBooking = await db
|
||||
.select()
|
||||
.from(bookings)
|
||||
.where(and(eq(bookings.id, bookingId), eq(bookings.userId, session.userId), eq(bookings.status, 'active')))
|
||||
.limit(1);
|
||||
|
||||
if (existingBooking.length === 0) {
|
||||
return NextResponse.json({ error: 'Booking not found or access denied' }, { status: 404 });
|
||||
}
|
||||
|
||||
const booking = existingBooking[0];
|
||||
|
||||
// Check if booking can be modified (more than 2 hours before start time)
|
||||
const bookingDateTime = new Date(`${booking.date}T${booking.startTime}`);
|
||||
const now = new Date();
|
||||
const timeDiff = bookingDateTime.getTime() - now.getTime();
|
||||
const hoursDiff = timeDiff / (1000 * 60 * 60);
|
||||
|
||||
if (hoursDiff <= 2) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Booking can only be modified more than 2 hours before the session' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Update booking notes
|
||||
await db
|
||||
.update(bookings)
|
||||
.set({
|
||||
notes: notes || null,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(bookings.id, bookingId));
|
||||
|
||||
// Log the activity
|
||||
await logActivity({
|
||||
userId: session.userId,
|
||||
action: ACTIONS.BOOKING_UPDATE,
|
||||
entityType: ENTITY_TYPES.BOOKING,
|
||||
entityId: bookingId,
|
||||
details: {
|
||||
oldNotes: booking.notes,
|
||||
newNotes: notes,
|
||||
date: booking.date,
|
||||
startTime: booking.startTime,
|
||||
},
|
||||
request,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Booking updated successfully',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating booking:', 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) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const bookingId = params.id;
|
||||
|
||||
// Check if booking exists and belongs to user
|
||||
const existingBooking = await db
|
||||
.select()
|
||||
.from(bookings)
|
||||
.where(and(eq(bookings.id, bookingId), eq(bookings.userId, session.userId), eq(bookings.status, 'active')))
|
||||
.limit(1);
|
||||
|
||||
if (existingBooking.length === 0) {
|
||||
return NextResponse.json({ error: 'Booking not found or access denied' }, { status: 404 });
|
||||
}
|
||||
|
||||
const booking = existingBooking[0];
|
||||
|
||||
// Check if booking can be cancelled (more than 2 hours before start time)
|
||||
const bookingDateTime = new Date(`${booking.date}T${booking.startTime}`);
|
||||
const now = new Date();
|
||||
const timeDiff = bookingDateTime.getTime() - now.getTime();
|
||||
const hoursDiff = timeDiff / (1000 * 60 * 60);
|
||||
|
||||
if (hoursDiff <= 2) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Booking can only be cancelled more than 2 hours before the session' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Cancel booking (set status to cancelled)
|
||||
await db
|
||||
.update(bookings)
|
||||
.set({
|
||||
status: 'cancelled',
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(bookings.id, bookingId));
|
||||
|
||||
// Log the activity
|
||||
await logActivity({
|
||||
userId: session.userId,
|
||||
action: ACTIONS.BOOKING_CANCEL,
|
||||
entityType: ENTITY_TYPES.BOOKING,
|
||||
entityId: bookingId,
|
||||
details: {
|
||||
date: booking.date,
|
||||
startTime: booking.startTime,
|
||||
endTime: booking.endTime,
|
||||
courtId: booking.courtId,
|
||||
},
|
||||
request,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Booking cancelled successfully',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error cancelling booking:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
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';
|
||||
import { logActivity, ACTIONS, ENTITY_TYPES } from '@/lib/activity-logger';
|
||||
|
||||
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,
|
||||
notes: bookings.notes,
|
||||
createdAt: bookings.createdAt,
|
||||
court: {
|
||||
id: courts.id,
|
||||
name: courts.name,
|
||||
},
|
||||
})
|
||||
.from(bookings)
|
||||
.innerJoin(courts, eq(bookings.courtId, courts.id))
|
||||
.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();
|
||||
|
||||
// Log the activity
|
||||
await logActivity({
|
||||
userId: session.userId,
|
||||
action: ACTIONS.BOOKING_CREATE,
|
||||
entityType: ENTITY_TYPES.BOOKING,
|
||||
entityId: newBooking.id,
|
||||
details: {
|
||||
courtId,
|
||||
courtName: court[0].name,
|
||||
date,
|
||||
startTime,
|
||||
endTime,
|
||||
},
|
||||
request,
|
||||
});
|
||||
|
||||
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 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getSession } from '@/lib/session';
|
||||
import { db } from '@/lib/db';
|
||||
import { courts } 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 courts (users can read courts)
|
||||
const activeCourts = await db.select().from(courts).where(eq(courts.isActive, true));
|
||||
|
||||
return NextResponse.json({
|
||||
courts: activeCourts,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching courts:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { verifySession } from '@/lib/session';
|
||||
import { db } from '@/lib/db';
|
||||
import { bookings, users, courts } from '@/lib/db/schema';
|
||||
import { eq, and, desc, gte } from 'drizzle-orm';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await verifySession();
|
||||
if (!session.isAuth || !session.userId) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const today = new Date();
|
||||
const todayStr = today.toISOString().split('T')[0];
|
||||
|
||||
// Get recent bookings for the current user with court and user details
|
||||
const recentBookings = await db
|
||||
.select({
|
||||
id: bookings.id,
|
||||
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,
|
||||
email: users.email,
|
||||
},
|
||||
})
|
||||
.from(bookings)
|
||||
.innerJoin(courts, eq(bookings.courtId, courts.id))
|
||||
.innerJoin(users, eq(bookings.userId, users.id))
|
||||
.where(
|
||||
and(eq(bookings.userId, session.userId), eq(bookings.status, 'active'), gte(bookings.date, todayStr))
|
||||
)
|
||||
.orderBy(desc(bookings.createdAt))
|
||||
.limit(5);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
bookings: recentBookings,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching recent bookings:', error);
|
||||
return NextResponse.json({ error: 'Failed to fetch recent bookings' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { users, bookings, courts } from '@/lib/db/schema';
|
||||
import { eq, count, and, gte } 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 });
|
||||
}
|
||||
|
||||
// Get current date
|
||||
const today = new Date();
|
||||
const todayStr = today.toISOString().split('T')[0];
|
||||
|
||||
// Get total users count
|
||||
const [totalUsersResult] = await db.select({ count: count() }).from(users);
|
||||
|
||||
// Get today's bookings count
|
||||
const [todayBookingsResult] = await db
|
||||
.select({ count: count() })
|
||||
.from(bookings)
|
||||
.where(and(eq(bookings.date, todayStr), eq(bookings.status, 'active')));
|
||||
|
||||
// Get active courts count
|
||||
const [activeCourtsResult] = await db.select({ count: count() }).from(courts).where(eq(courts.isActive, true));
|
||||
|
||||
// Get user's total bookings
|
||||
const [userBookingsResult] = await db
|
||||
.select({ count: count() })
|
||||
.from(bookings)
|
||||
.where(and(eq(bookings.userId, session.userId), eq(bookings.status, 'active')));
|
||||
|
||||
// Get user's upcoming bookings (today and future)
|
||||
const [upcomingBookingsResult] = await db
|
||||
.select({ count: count() })
|
||||
.from(bookings)
|
||||
.where(
|
||||
and(eq(bookings.userId, session.userId), gte(bookings.date, todayStr), eq(bookings.status, 'active'))
|
||||
);
|
||||
|
||||
return NextResponse.json({
|
||||
stats: {
|
||||
totalUsers: totalUsersResult.count,
|
||||
todayBookings: todayBookingsResult.count,
|
||||
activeCourts: activeCourtsResult.count,
|
||||
userBookings: userBookingsResult.count,
|
||||
upcomingBookings: upcomingBookingsResult.count,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching dashboard stats:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getSession } from '@/lib/session';
|
||||
import { db } from '@/lib/db';
|
||||
import { settings } from '@/lib/db/schema';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
// Get all settings (users can read settings but not modify them)
|
||||
const allSettings = await db.select().from(settings);
|
||||
|
||||
return NextResponse.json({
|
||||
settings: allSettings,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching settings:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getSession } from '@/lib/session';
|
||||
import { db } from '@/lib/db';
|
||||
import { users } 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) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
// Get user profile
|
||||
const [user] = await db
|
||||
.select({
|
||||
id: users.id,
|
||||
email: users.email,
|
||||
name: users.name,
|
||||
surname: users.surname,
|
||||
role: users.role,
|
||||
createdAt: users.createdAt,
|
||||
})
|
||||
.from(users)
|
||||
.where(eq(users.id, session.userId))
|
||||
.limit(1);
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
user: {
|
||||
...user,
|
||||
createdAt: user.createdAt.toISOString(),
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching user profile:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PATCH(request: NextRequest) {
|
||||
try {
|
||||
const session = await getSession();
|
||||
if (!session) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { name, surname } = await request.json();
|
||||
|
||||
// Validate required fields
|
||||
if (!name || !surname) {
|
||||
return NextResponse.json({ error: 'Name and surname are required' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Get current user data for logging
|
||||
const [currentUser] = await db.select().from(users).where(eq(users.id, session.userId)).limit(1);
|
||||
|
||||
if (!currentUser) {
|
||||
return NextResponse.json({ error: 'User not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
// Update user profile
|
||||
await db
|
||||
.update(users)
|
||||
.set({
|
||||
name: name.trim(),
|
||||
surname: surname.trim(),
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(users.id, session.userId));
|
||||
|
||||
// Log the activity
|
||||
await logActivity({
|
||||
userId: session.userId,
|
||||
action: ACTIONS.USER_UPDATE,
|
||||
entityType: ENTITY_TYPES.USER,
|
||||
entityId: session.userId,
|
||||
details: {
|
||||
previousData: {
|
||||
name: currentUser.name,
|
||||
surname: currentUser.surname,
|
||||
},
|
||||
newData: {
|
||||
name: name.trim(),
|
||||
surname: surname.trim(),
|
||||
},
|
||||
},
|
||||
request,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Profile updated successfully',
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error updating user profile:', error);
|
||||
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user