Files
app-padel/apps/web/app/api/courts/route.ts
Ivan da8a730867 fix: handle isOpenPlay and map form values to Prisma enums in court API
- Add isOpenPlay field to POST and PUT routes
- Accept both hourlyRate and pricePerHour (form vs API naming)
- Map lowercase type/status from form to uppercase Prisma enums

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 23:21:36 +00:00

183 lines
4.7 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { db } from '@/lib/db';
// GET /api/courts - List courts filtered by organization and optionally by siteId
export async function GET(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
const { searchParams } = new URL(request.url);
const siteId = searchParams.get('siteId');
// Build the where clause
const whereClause: {
site: {
organizationId: string;
id?: string;
};
} = {
site: {
organizationId: session.user.organizationId,
},
};
// If a specific siteId is provided in query params, use it
if (siteId) {
whereClause.site.id = siteId;
} else if (session.user.siteId) {
// Otherwise, if user has a siteId assigned, filter by that
whereClause.site.id = session.user.siteId;
}
const courts = await db.court.findMany({
where: whereClause,
include: {
site: {
select: {
id: true,
name: true,
slug: true,
openTime: true,
closeTime: true,
timezone: true,
},
},
},
orderBy: [
{ site: { name: 'asc' } },
{ displayOrder: 'asc' },
{ name: 'asc' },
],
});
return NextResponse.json(courts);
} catch (error) {
console.error('Error fetching courts:', error);
return NextResponse.json(
{ error: 'Failed to fetch courts' },
{ status: 500 }
);
}
}
// POST /api/courts - Create a new court
export async function POST(request: NextRequest) {
try {
const session = await getServerSession(authOptions);
if (!session?.user) {
return NextResponse.json(
{ error: 'Unauthorized' },
{ status: 401 }
);
}
// Check if user has admin role
const allowedRoles = ['SUPER_ADMIN', 'SITE_ADMIN'];
if (!allowedRoles.includes(session.user.role)) {
return NextResponse.json(
{ error: 'Forbidden: Insufficient permissions' },
{ status: 403 }
);
}
const body = await request.json();
const {
siteId,
name,
type,
status,
pricePerHour,
hourlyRate,
description,
features,
displayOrder,
isActive,
isOpenPlay,
} = body;
const price = pricePerHour ?? hourlyRate;
// Map lowercase form values to Prisma enum values
const typeMap: Record<string, string> = { indoor: 'INDOOR', outdoor: 'OUTDOOR', covered: 'COVERED' };
const statusMap: Record<string, string> = { active: 'AVAILABLE', maintenance: 'MAINTENANCE', inactive: 'CLOSED' };
const mappedType = typeMap[type?.toLowerCase()] || type || 'INDOOR';
const mappedStatus = statusMap[status?.toLowerCase()] || status || 'AVAILABLE';
// Validate required fields
if (!siteId || !name || price === undefined) {
return NextResponse.json(
{ error: 'Missing required fields: siteId, name, pricePerHour' },
{ status: 400 }
);
}
// Verify site belongs to user's organization
const site = await db.site.findFirst({
where: {
id: siteId,
organizationId: session.user.organizationId,
},
});
if (!site) {
return NextResponse.json(
{ error: 'Site not found or does not belong to your organization' },
{ status: 404 }
);
}
// If user is SITE_ADMIN, verify they have access to this site
if (session.user.role === 'SITE_ADMIN' && session.user.siteId !== siteId) {
return NextResponse.json(
{ error: 'Forbidden: You do not have access to this site' },
{ status: 403 }
);
}
const court = await db.court.create({
data: {
siteId,
name,
type: mappedType,
status: mappedStatus,
pricePerHour: price,
description: description || null,
features: features || [],
displayOrder: displayOrder ?? 0,
isOpenPlay: isOpenPlay ?? false,
isActive: isActive ?? true,
},
include: {
site: {
select: {
id: true,
name: true,
slug: true,
openTime: true,
closeTime: true,
timezone: true,
},
},
},
});
return NextResponse.json(court, { status: 201 });
} catch (error) {
console.error('Error creating court:', error);
return NextResponse.json(
{ error: 'Failed to create court' },
{ status: 500 }
);
}
}