feat(api): add bookings CRUD and payment endpoints
- Add bookings list/create API with filters (siteId, date, status) - Add booking detail, update, and delete endpoints - Add payment processing endpoint with transaction support - Add clients list/search and create API - Implement membership discounts (free hours and percentage) - Validate requests with Zod schemas from shared package - Include Spanish error messages Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
227
apps/web/app/api/bookings/[id]/pay/route.ts
Normal file
227
apps/web/app/api/bookings/[id]/pay/route.ts
Normal file
@@ -0,0 +1,227 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { authOptions } from '@/lib/auth';
|
||||
import { db } from '@/lib/db';
|
||||
import { z } from 'zod';
|
||||
import { Decimal } from '@prisma/client/runtime/library';
|
||||
|
||||
interface RouteContext {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
// Validation schema for payment
|
||||
const paymentSchema = z.object({
|
||||
paymentType: z.enum(['CASH', 'CARD', 'TRANSFER', 'MEMBERSHIP', 'FREE']),
|
||||
amount: z.number().positive('El monto debe ser mayor a 0').optional(),
|
||||
reference: z.string().max(100).optional(),
|
||||
notes: z.string().max(500).optional(),
|
||||
cashRegisterId: z.string().uuid().optional(),
|
||||
});
|
||||
|
||||
// POST /api/bookings/[id]/pay - Mark booking as paid
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
context: RouteContext
|
||||
) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No autorizado' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { id } = await context.params;
|
||||
|
||||
// Verify booking exists and belongs to user's organization
|
||||
const existingBooking = await db.booking.findFirst({
|
||||
where: {
|
||||
id,
|
||||
site: {
|
||||
organizationId: session.user.organizationId,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
client: true,
|
||||
payments: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!existingBooking) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Reserva no encontrada' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// If user is SITE_ADMIN, verify they have access to this site
|
||||
if (session.user.role === 'SITE_ADMIN' && session.user.siteId !== existingBooking.siteId) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No tiene permiso para procesar pagos en esta reserva' },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Check if booking is already cancelled
|
||||
if (existingBooking.status === 'CANCELLED') {
|
||||
return NextResponse.json(
|
||||
{ error: 'No se puede procesar el pago de una reserva cancelada' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Check if booking is already fully paid
|
||||
const totalPaid = existingBooking.payments.reduce(
|
||||
(sum, p) => sum + Number(p.amount),
|
||||
0
|
||||
);
|
||||
const totalPrice = Number(existingBooking.totalPrice);
|
||||
|
||||
if (totalPaid >= totalPrice) {
|
||||
return NextResponse.json(
|
||||
{ error: 'La reserva ya está completamente pagada' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
|
||||
// Validate input
|
||||
const validationResult = paymentSchema.safeParse(body);
|
||||
if (!validationResult.success) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Datos de pago inválidos',
|
||||
details: validationResult.error.flatten().fieldErrors,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { paymentType, amount, reference, notes, cashRegisterId } = validationResult.data;
|
||||
|
||||
// Calculate payment amount
|
||||
const remainingAmount = totalPrice - totalPaid;
|
||||
const paymentAmount = amount !== undefined ? Math.min(amount, remainingAmount) : remainingAmount;
|
||||
|
||||
if (paymentAmount <= 0) {
|
||||
return NextResponse.json(
|
||||
{ error: 'El monto del pago debe ser mayor a 0' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// If cash register is provided, verify it exists and is open
|
||||
if (cashRegisterId) {
|
||||
const cashRegister = await db.cashRegister.findFirst({
|
||||
where: {
|
||||
id: cashRegisterId,
|
||||
siteId: existingBooking.siteId,
|
||||
closedAt: null, // Only open registers
|
||||
},
|
||||
});
|
||||
|
||||
if (!cashRegister) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Caja registradora no encontrada o no está abierta' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Use transaction for atomicity
|
||||
const result = await db.$transaction(async (tx) => {
|
||||
// Create payment record
|
||||
const payment = await tx.payment.create({
|
||||
data: {
|
||||
bookingId: id,
|
||||
clientId: existingBooking.clientId,
|
||||
amount: new Decimal(paymentAmount),
|
||||
paymentType,
|
||||
reference: reference || null,
|
||||
notes: notes || null,
|
||||
cashRegisterId: cashRegisterId || null,
|
||||
},
|
||||
});
|
||||
|
||||
// Calculate new total paid
|
||||
const newTotalPaid = totalPaid + paymentAmount;
|
||||
const isFullyPaid = newTotalPaid >= totalPrice;
|
||||
|
||||
// Update booking
|
||||
const updatedBooking = await tx.booking.update({
|
||||
where: { id },
|
||||
data: {
|
||||
paidAmount: new Decimal(newTotalPaid),
|
||||
paymentType,
|
||||
// Set status to CONFIRMED if fully paid and was pending
|
||||
...(isFullyPaid && existingBooking.status === 'PENDING' && {
|
||||
status: 'CONFIRMED',
|
||||
}),
|
||||
},
|
||||
include: {
|
||||
court: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
type: true,
|
||||
pricePerHour: true,
|
||||
},
|
||||
},
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
email: true,
|
||||
phone: true,
|
||||
},
|
||||
},
|
||||
site: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
timezone: true,
|
||||
},
|
||||
},
|
||||
payments: {
|
||||
select: {
|
||||
id: true,
|
||||
amount: true,
|
||||
paymentType: true,
|
||||
reference: true,
|
||||
notes: true,
|
||||
createdAt: true,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'desc',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
booking: updatedBooking,
|
||||
payment,
|
||||
isFullyPaid,
|
||||
};
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
message: result.isFullyPaid
|
||||
? 'Pago completado. La reserva ha sido confirmada.'
|
||||
: 'Pago parcial registrado exitosamente.',
|
||||
booking: result.booking,
|
||||
payment: result.payment,
|
||||
remainingAmount: Math.max(0, totalPrice - (totalPaid + paymentAmount)),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error processing payment:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Error al procesar el pago' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
357
apps/web/app/api/bookings/[id]/route.ts
Normal file
357
apps/web/app/api/bookings/[id]/route.ts
Normal file
@@ -0,0 +1,357 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { authOptions } from '@/lib/auth';
|
||||
import { db } from '@/lib/db';
|
||||
import { z } from 'zod';
|
||||
|
||||
interface RouteContext {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
// Validation schema for updating booking
|
||||
const updateBookingSchema = z.object({
|
||||
status: z.enum(['PENDING', 'CONFIRMED', 'CANCELLED', 'COMPLETED', 'NO_SHOW']).optional(),
|
||||
notes: z.string().max(500).optional(),
|
||||
cancelReason: z.string().max(500).optional(),
|
||||
playerNames: z.array(z.string()).optional(),
|
||||
});
|
||||
|
||||
// GET /api/bookings/[id] - Get a single booking by ID
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
context: RouteContext
|
||||
) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No autorizado' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { id } = await context.params;
|
||||
|
||||
const booking = await db.booking.findFirst({
|
||||
where: {
|
||||
id,
|
||||
site: {
|
||||
organizationId: session.user.organizationId,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
court: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
type: true,
|
||||
status: true,
|
||||
pricePerHour: true,
|
||||
features: true,
|
||||
},
|
||||
},
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
email: true,
|
||||
phone: true,
|
||||
level: true,
|
||||
notes: true,
|
||||
},
|
||||
},
|
||||
site: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
address: true,
|
||||
phone: true,
|
||||
email: true,
|
||||
timezone: true,
|
||||
},
|
||||
},
|
||||
createdBy: {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
payments: {
|
||||
select: {
|
||||
id: true,
|
||||
amount: true,
|
||||
paymentType: true,
|
||||
reference: true,
|
||||
notes: true,
|
||||
createdAt: true,
|
||||
},
|
||||
orderBy: {
|
||||
createdAt: 'desc',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!booking) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Reserva no encontrada' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(booking);
|
||||
} catch (error) {
|
||||
console.error('Error fetching booking:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Error al obtener la reserva' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// PUT /api/bookings/[id] - Update a booking
|
||||
export async function PUT(
|
||||
request: NextRequest,
|
||||
context: RouteContext
|
||||
) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No autorizado' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { id } = await context.params;
|
||||
|
||||
// Verify booking exists and belongs to user's organization
|
||||
const existingBooking = await db.booking.findFirst({
|
||||
where: {
|
||||
id,
|
||||
site: {
|
||||
organizationId: session.user.organizationId,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
site: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!existingBooking) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Reserva no encontrada' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// If user is SITE_ADMIN, verify they have access to this site
|
||||
if (session.user.role === 'SITE_ADMIN' && session.user.siteId !== existingBooking.siteId) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No tiene permiso para modificar esta reserva' },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
|
||||
// Validate input
|
||||
const validationResult = updateBookingSchema.safeParse(body);
|
||||
if (!validationResult.success) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Datos de actualización inválidos',
|
||||
details: validationResult.error.flatten().fieldErrors,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { status, notes, cancelReason, playerNames } = validationResult.data;
|
||||
|
||||
// Build update data
|
||||
const updateData: {
|
||||
status?: 'PENDING' | 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NO_SHOW';
|
||||
notes?: string | null;
|
||||
cancelReason?: string | null;
|
||||
cancelledAt?: Date | null;
|
||||
playerNames?: string[];
|
||||
} = {};
|
||||
|
||||
if (status !== undefined) {
|
||||
updateData.status = status;
|
||||
|
||||
// If cancelling, set cancellation timestamp
|
||||
if (status === 'CANCELLED') {
|
||||
updateData.cancelledAt = new Date();
|
||||
if (cancelReason) {
|
||||
updateData.cancelReason = cancelReason;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (notes !== undefined) {
|
||||
updateData.notes = notes || null;
|
||||
}
|
||||
|
||||
if (playerNames !== undefined) {
|
||||
updateData.playerNames = playerNames;
|
||||
}
|
||||
|
||||
const booking = await db.booking.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
include: {
|
||||
court: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
type: true,
|
||||
pricePerHour: true,
|
||||
},
|
||||
},
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
email: true,
|
||||
phone: true,
|
||||
},
|
||||
},
|
||||
site: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
timezone: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(booking);
|
||||
} catch (error) {
|
||||
console.error('Error updating booking:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Error al actualizar la reserva' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// DELETE /api/bookings/[id] - Cancel/delete a booking
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
context: RouteContext
|
||||
) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No autorizado' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { id } = await context.params;
|
||||
|
||||
// Verify booking exists and belongs to user's organization
|
||||
const existingBooking = await db.booking.findFirst({
|
||||
where: {
|
||||
id,
|
||||
site: {
|
||||
organizationId: session.user.organizationId,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
payments: true,
|
||||
},
|
||||
});
|
||||
|
||||
if (!existingBooking) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Reserva no encontrada' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// If user is SITE_ADMIN, verify they have access to this site
|
||||
if (session.user.role === 'SITE_ADMIN' && session.user.siteId !== existingBooking.siteId) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No tiene permiso para cancelar esta reserva' },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
// Check if booking has payments
|
||||
const hasPayments = existingBooking.payments.length > 0;
|
||||
|
||||
// Parse optional cancel reason from query params or body
|
||||
let cancelReason = 'Cancelada por el administrador';
|
||||
try {
|
||||
const body = await request.json();
|
||||
if (body.cancelReason) {
|
||||
cancelReason = body.cancelReason;
|
||||
}
|
||||
} catch {
|
||||
// No body provided, use default reason
|
||||
}
|
||||
|
||||
if (hasPayments) {
|
||||
// If there are payments, just cancel the booking (soft delete)
|
||||
const booking = await db.booking.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: 'CANCELLED',
|
||||
cancelledAt: new Date(),
|
||||
cancelReason,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
message: 'Reserva cancelada exitosamente',
|
||||
booking,
|
||||
note: 'La reserva tiene pagos asociados, por lo que fue cancelada en lugar de eliminada',
|
||||
});
|
||||
} else {
|
||||
// If no payments, allow hard delete for pending bookings only
|
||||
if (existingBooking.status === 'PENDING') {
|
||||
await db.booking.delete({
|
||||
where: { id },
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
message: 'Reserva eliminada exitosamente',
|
||||
});
|
||||
} else {
|
||||
// For non-pending bookings, soft delete
|
||||
const booking = await db.booking.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: 'CANCELLED',
|
||||
cancelledAt: new Date(),
|
||||
cancelReason,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
message: 'Reserva cancelada exitosamente',
|
||||
booking,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error deleting booking:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Error al cancelar la reserva' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
398
apps/web/app/api/bookings/route.ts
Normal file
398
apps/web/app/api/bookings/route.ts
Normal file
@@ -0,0 +1,398 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { authOptions } from '@/lib/auth';
|
||||
import { db } from '@/lib/db';
|
||||
import { createBookingSchema } from '@padel-pro/shared';
|
||||
import { Decimal } from '@prisma/client/runtime/library';
|
||||
|
||||
// Helper function to check if a time is premium (after 18:00 or weekend)
|
||||
function isPremiumTime(date: Date, timeMinutes: number): boolean {
|
||||
const dayOfWeek = date.getDay(); // 0 = Sunday, 6 = Saturday
|
||||
const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
|
||||
const isEveningTime = timeMinutes >= 18 * 60; // After 18:00
|
||||
return isWeekend || isEveningTime;
|
||||
}
|
||||
|
||||
// GET /api/bookings - List bookings with filters
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No autorizado' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const siteId = searchParams.get('siteId');
|
||||
const date = searchParams.get('date');
|
||||
const status = searchParams.get('status');
|
||||
const clientId = searchParams.get('clientId');
|
||||
const courtId = searchParams.get('courtId');
|
||||
|
||||
// Build the where clause
|
||||
interface BookingWhereClause {
|
||||
site: {
|
||||
organizationId: string;
|
||||
id?: string;
|
||||
};
|
||||
status?: 'PENDING' | 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NO_SHOW';
|
||||
clientId?: string;
|
||||
courtId?: string;
|
||||
startTime?: {
|
||||
gte: Date;
|
||||
lt: Date;
|
||||
};
|
||||
}
|
||||
|
||||
const whereClause: BookingWhereClause = {
|
||||
site: {
|
||||
organizationId: session.user.organizationId,
|
||||
},
|
||||
};
|
||||
|
||||
// Filter by site
|
||||
if (siteId) {
|
||||
whereClause.site.id = siteId;
|
||||
} else if (session.user.siteId) {
|
||||
whereClause.site.id = session.user.siteId;
|
||||
}
|
||||
|
||||
// Filter by status
|
||||
if (status) {
|
||||
const validStatuses = ['PENDING', 'CONFIRMED', 'CANCELLED', 'COMPLETED', 'NO_SHOW'] as const;
|
||||
if (validStatuses.includes(status.toUpperCase() as typeof validStatuses[number])) {
|
||||
whereClause.status = status.toUpperCase() as typeof validStatuses[number];
|
||||
}
|
||||
}
|
||||
|
||||
// Filter by client
|
||||
if (clientId) {
|
||||
whereClause.clientId = clientId;
|
||||
}
|
||||
|
||||
// Filter by court
|
||||
if (courtId) {
|
||||
whereClause.courtId = courtId;
|
||||
}
|
||||
|
||||
// Filter by date
|
||||
if (date) {
|
||||
const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
|
||||
if (dateRegex.test(date)) {
|
||||
const startOfDay = new Date(date);
|
||||
startOfDay.setHours(0, 0, 0, 0);
|
||||
const endOfDay = new Date(date);
|
||||
endOfDay.setHours(23, 59, 59, 999);
|
||||
|
||||
whereClause.startTime = {
|
||||
gte: startOfDay,
|
||||
lt: new Date(endOfDay.getTime() + 1),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const bookings = await db.booking.findMany({
|
||||
where: whereClause,
|
||||
include: {
|
||||
court: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
type: true,
|
||||
pricePerHour: true,
|
||||
},
|
||||
},
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
email: true,
|
||||
phone: true,
|
||||
},
|
||||
},
|
||||
site: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
timezone: true,
|
||||
},
|
||||
},
|
||||
createdBy: {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [
|
||||
{ startTime: 'asc' },
|
||||
],
|
||||
});
|
||||
|
||||
return NextResponse.json(bookings);
|
||||
} catch (error) {
|
||||
console.error('Error fetching bookings:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Error al obtener las reservas' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/bookings - Create a new booking
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No autorizado' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
|
||||
// Validate input with Zod schema
|
||||
const validationResult = createBookingSchema.safeParse(body);
|
||||
if (!validationResult.success) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Datos de reserva inválidos',
|
||||
details: validationResult.error.flatten().fieldErrors,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const { courtId, clientId, startTime, endTime, paymentType, notes, participants } = validationResult.data;
|
||||
|
||||
// Check court exists and belongs to user's organization
|
||||
const court = await db.court.findFirst({
|
||||
where: {
|
||||
id: courtId,
|
||||
site: {
|
||||
organizationId: session.user.organizationId,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
site: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
organizationId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!court) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Cancha no encontrada o no pertenece a su organización' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
if (court.status !== 'AVAILABLE' || !court.isActive) {
|
||||
return NextResponse.json(
|
||||
{ error: 'La cancha no está disponible para reservas' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Check client exists and belongs to user's organization
|
||||
const client = await db.client.findFirst({
|
||||
where: {
|
||||
id: clientId,
|
||||
organizationId: session.user.organizationId,
|
||||
},
|
||||
include: {
|
||||
memberships: {
|
||||
where: {
|
||||
status: 'ACTIVE',
|
||||
endDate: {
|
||||
gte: new Date(),
|
||||
},
|
||||
},
|
||||
include: {
|
||||
plan: true,
|
||||
},
|
||||
orderBy: {
|
||||
endDate: 'desc',
|
||||
},
|
||||
take: 1,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!client) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Cliente no encontrado o no pertenece a su organización' },
|
||||
{ status: 404 }
|
||||
);
|
||||
}
|
||||
|
||||
// Check availability - no existing booking at that time
|
||||
const bookingStartTime = new Date(startTime);
|
||||
const bookingEndTime = new Date(endTime);
|
||||
|
||||
const existingBooking = await db.booking.findFirst({
|
||||
where: {
|
||||
courtId,
|
||||
status: {
|
||||
in: ['PENDING', 'CONFIRMED'],
|
||||
},
|
||||
OR: [
|
||||
// New booking starts during existing booking
|
||||
{
|
||||
startTime: { lte: bookingStartTime },
|
||||
endTime: { gt: bookingStartTime },
|
||||
},
|
||||
// New booking ends during existing booking
|
||||
{
|
||||
startTime: { lt: bookingEndTime },
|
||||
endTime: { gte: bookingEndTime },
|
||||
},
|
||||
// New booking encompasses existing booking
|
||||
{
|
||||
startTime: { gte: bookingStartTime },
|
||||
endTime: { lte: bookingEndTime },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
if (existingBooking) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Ya existe una reserva en ese horario. Por favor, seleccione otro horario.' },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
// Calculate duration in minutes
|
||||
const durationMs = bookingEndTime.getTime() - bookingStartTime.getTime();
|
||||
const durationMinutes = durationMs / (1000 * 60);
|
||||
const durationHours = durationMinutes / 60;
|
||||
|
||||
// Calculate price (regular vs premium)
|
||||
const startMinutes = bookingStartTime.getHours() * 60 + bookingStartTime.getMinutes();
|
||||
const isPremium = isPremiumTime(bookingStartTime, startMinutes);
|
||||
const basePrice = Number(court.pricePerHour);
|
||||
const premiumMultiplier = 1.25;
|
||||
const hourlyRate = isPremium ? basePrice * premiumMultiplier : basePrice;
|
||||
let totalPrice = hourlyRate * durationHours;
|
||||
|
||||
// Check client membership for discounts
|
||||
const activeMembership = client.memberships[0];
|
||||
let usedFreeHours = false;
|
||||
let appliedDiscount = 0;
|
||||
let finalPaymentType = paymentType.toUpperCase() as 'CASH' | 'CARD' | 'TRANSFER' | 'MEMBERSHIP' | 'FREE';
|
||||
|
||||
if (activeMembership) {
|
||||
const plan = activeMembership.plan;
|
||||
|
||||
// Check if membership has free hours remaining
|
||||
if (plan.courtHours && activeMembership.remainingHours && activeMembership.remainingHours > 0) {
|
||||
// Client has free hours, use them
|
||||
const hoursToUse = Math.min(activeMembership.remainingHours, durationHours);
|
||||
|
||||
if (hoursToUse >= durationHours) {
|
||||
// Fully covered by free hours
|
||||
totalPrice = 0;
|
||||
usedFreeHours = true;
|
||||
finalPaymentType = 'FREE';
|
||||
} else {
|
||||
// Partial coverage - calculate remaining
|
||||
const remainingHours = durationHours - hoursToUse;
|
||||
totalPrice = hourlyRate * remainingHours;
|
||||
usedFreeHours = true;
|
||||
}
|
||||
} else if (plan.discountPercent) {
|
||||
// Apply booking discount percentage
|
||||
const discountPercent = Number(plan.discountPercent);
|
||||
appliedDiscount = (totalPrice * discountPercent) / 100;
|
||||
totalPrice = totalPrice - appliedDiscount;
|
||||
finalPaymentType = 'MEMBERSHIP';
|
||||
}
|
||||
}
|
||||
|
||||
// Round price to 2 decimal places
|
||||
totalPrice = Math.round(totalPrice * 100) / 100;
|
||||
|
||||
// Create booking with transaction (to update membership hours if needed)
|
||||
const booking = await db.$transaction(async (tx) => {
|
||||
// Update membership hours if free hours were used
|
||||
if (usedFreeHours && activeMembership) {
|
||||
const hoursUsed = Math.min(activeMembership.remainingHours || 0, durationHours);
|
||||
await tx.membership.update({
|
||||
where: { id: activeMembership.id },
|
||||
data: {
|
||||
remainingHours: {
|
||||
decrement: hoursUsed,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Create the booking
|
||||
const newBooking = await tx.booking.create({
|
||||
data: {
|
||||
siteId: court.siteId,
|
||||
courtId,
|
||||
clientId,
|
||||
createdById: session.user.id,
|
||||
startTime: bookingStartTime,
|
||||
endTime: bookingEndTime,
|
||||
status: 'PENDING',
|
||||
paymentType: finalPaymentType,
|
||||
totalPrice: new Decimal(totalPrice),
|
||||
paidAmount: new Decimal(0),
|
||||
notes: notes || null,
|
||||
playerNames: participants?.map(p => p.name) || [],
|
||||
isRecurring: false,
|
||||
},
|
||||
include: {
|
||||
court: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
type: true,
|
||||
pricePerHour: true,
|
||||
},
|
||||
},
|
||||
client: {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
email: true,
|
||||
phone: true,
|
||||
},
|
||||
},
|
||||
site: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
timezone: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return newBooking;
|
||||
});
|
||||
|
||||
return NextResponse.json(booking, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error('Error creating booking:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Error al crear la reserva' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
237
apps/web/app/api/clients/route.ts
Normal file
237
apps/web/app/api/clients/route.ts
Normal file
@@ -0,0 +1,237 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { getServerSession } from 'next-auth';
|
||||
import { authOptions } from '@/lib/auth';
|
||||
import { db } from '@/lib/db';
|
||||
import { createClientSchema } from '@padel-pro/shared';
|
||||
|
||||
// GET /api/clients - List/search clients
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No autorizado' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const search = searchParams.get('search');
|
||||
const isActive = searchParams.get('isActive');
|
||||
const limit = searchParams.get('limit');
|
||||
const offset = searchParams.get('offset');
|
||||
|
||||
// Build the where clause
|
||||
interface ClientWhereClause {
|
||||
organizationId: string;
|
||||
isActive?: boolean;
|
||||
OR?: Array<{
|
||||
firstName?: { contains: string; mode: 'insensitive' };
|
||||
lastName?: { contains: string; mode: 'insensitive' };
|
||||
email?: { contains: string; mode: 'insensitive' };
|
||||
phone?: { contains: string; mode: 'insensitive' };
|
||||
}>;
|
||||
}
|
||||
|
||||
const whereClause: ClientWhereClause = {
|
||||
organizationId: session.user.organizationId,
|
||||
};
|
||||
|
||||
// Filter by active status
|
||||
if (isActive !== null) {
|
||||
whereClause.isActive = isActive !== 'false';
|
||||
}
|
||||
|
||||
// Search filter for name, email, or phone
|
||||
if (search && search.trim().length > 0) {
|
||||
const searchTerm = search.trim();
|
||||
whereClause.OR = [
|
||||
{ firstName: { contains: searchTerm, mode: 'insensitive' } },
|
||||
{ lastName: { contains: searchTerm, mode: 'insensitive' } },
|
||||
{ email: { contains: searchTerm, mode: 'insensitive' } },
|
||||
{ phone: { contains: searchTerm, mode: 'insensitive' } },
|
||||
];
|
||||
}
|
||||
|
||||
// Build pagination options
|
||||
const take = limit ? Math.min(parseInt(limit, 10), 100) : 50;
|
||||
const skip = offset ? parseInt(offset, 10) : 0;
|
||||
|
||||
// Get total count for pagination
|
||||
const totalCount = await db.client.count({
|
||||
where: whereClause,
|
||||
});
|
||||
|
||||
const clients = await db.client.findMany({
|
||||
where: whereClause,
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
email: true,
|
||||
phone: true,
|
||||
level: true,
|
||||
tags: true,
|
||||
isActive: true,
|
||||
createdAt: true,
|
||||
memberships: {
|
||||
where: {
|
||||
status: 'ACTIVE',
|
||||
endDate: {
|
||||
gte: new Date(),
|
||||
},
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
status: true,
|
||||
remainingHours: true,
|
||||
endDate: true,
|
||||
plan: {
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
discountPercent: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
take: 1,
|
||||
},
|
||||
_count: {
|
||||
select: {
|
||||
bookings: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
orderBy: [
|
||||
{ lastName: 'asc' },
|
||||
{ firstName: 'asc' },
|
||||
],
|
||||
take,
|
||||
skip,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
data: clients,
|
||||
pagination: {
|
||||
total: totalCount,
|
||||
limit: take,
|
||||
offset: skip,
|
||||
hasMore: skip + take < totalCount,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching clients:', error);
|
||||
return NextResponse.json(
|
||||
{ error: 'Error al obtener los clientes' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// POST /api/clients - Create a new client
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
if (!session?.user) {
|
||||
return NextResponse.json(
|
||||
{ error: 'No autorizado' },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
|
||||
// Validate input with Zod schema
|
||||
const validationResult = createClientSchema.safeParse(body);
|
||||
if (!validationResult.success) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'Datos del cliente inválidos',
|
||||
details: validationResult.error.flatten().fieldErrors,
|
||||
},
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const {
|
||||
firstName,
|
||||
lastName,
|
||||
email,
|
||||
phone,
|
||||
dateOfBirth,
|
||||
address,
|
||||
city,
|
||||
postalCode,
|
||||
notes,
|
||||
tags,
|
||||
skillLevel,
|
||||
emergencyContact,
|
||||
} = validationResult.data;
|
||||
|
||||
// Check if client with same email already exists in organization
|
||||
if (email) {
|
||||
const existingClient = await db.client.findFirst({
|
||||
where: {
|
||||
organizationId: session.user.organizationId,
|
||||
email,
|
||||
},
|
||||
});
|
||||
|
||||
if (existingClient) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Ya existe un cliente con este correo electrónico en su organización' },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Create the client
|
||||
const client = await db.client.create({
|
||||
data: {
|
||||
organizationId: session.user.organizationId,
|
||||
firstName,
|
||||
lastName,
|
||||
email: email || null,
|
||||
phone: phone || null,
|
||||
dateOfBirth: dateOfBirth || null,
|
||||
address: address || null,
|
||||
notes: notes || null,
|
||||
tags: tags || [],
|
||||
level: skillLevel || null,
|
||||
emergencyContact: emergencyContact?.name || null,
|
||||
emergencyPhone: emergencyContact?.phone || null,
|
||||
isActive: true,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
email: true,
|
||||
phone: true,
|
||||
level: true,
|
||||
tags: true,
|
||||
isActive: true,
|
||||
createdAt: true,
|
||||
},
|
||||
});
|
||||
|
||||
return NextResponse.json(client, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error('Error creating client:', error);
|
||||
|
||||
// Check for unique constraint violation
|
||||
if (error instanceof Error && error.message.includes('Unique constraint')) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Ya existe un cliente con este correo electrónico o DNI' },
|
||||
{ status: 409 }
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json(
|
||||
{ error: 'Error al crear el cliente' },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@
|
||||
"db:studio": "prisma studio"
|
||||
},
|
||||
"dependencies": {
|
||||
"@padel-pro/shared": "*",
|
||||
"@prisma/client": "^5.10.0",
|
||||
"@radix-ui/react-dialog": "^1.0.5",
|
||||
"@radix-ui/react-dropdown-menu": "^2.0.6",
|
||||
@@ -29,7 +30,8 @@
|
||||
"next-auth": "^4.24.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"tailwind-merge": "^2.2.0"
|
||||
"tailwind-merge": "^2.2.0",
|
||||
"zod": "^3.22.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
|
||||
Reference in New Issue
Block a user