- Add TimeSlot component with available/booked visual states - Add BookingCalendar component with date navigation and court columns - Add BookingDialog for creating bookings and viewing/cancelling existing ones - Add bookings page with calendar integration - Fix sidebar navigation paths for route group structure Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
507 lines
17 KiB
TypeScript
507 lines
17 KiB
TypeScript
"use client";
|
|
|
|
import { useState, useEffect, useCallback } from "react";
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
Card,
|
|
CardContent,
|
|
CardHeader,
|
|
CardTitle,
|
|
CardFooter,
|
|
} from "@/components/ui/card";
|
|
import { Input } from "@/components/ui/input";
|
|
import { cn, formatTime, formatCurrency, formatDate } from "@/lib/utils";
|
|
import type { SelectedSlot } from "./booking-calendar";
|
|
|
|
interface Client {
|
|
id: string;
|
|
firstName: string;
|
|
lastName: string;
|
|
email: string | null;
|
|
phone: string | null;
|
|
level: string | null;
|
|
memberships: Array<{
|
|
id: string;
|
|
status: string;
|
|
remainingHours: number | null;
|
|
plan: {
|
|
id: string;
|
|
name: string;
|
|
discountPercent: number | null;
|
|
};
|
|
}>;
|
|
}
|
|
|
|
interface ClientsResponse {
|
|
data: Client[];
|
|
pagination: {
|
|
total: number;
|
|
limit: number;
|
|
offset: number;
|
|
hasMore: boolean;
|
|
};
|
|
}
|
|
|
|
interface BookingInfo {
|
|
id: string;
|
|
startTime: string;
|
|
endTime: string;
|
|
status: string;
|
|
totalPrice: number;
|
|
paymentType: string;
|
|
client: {
|
|
id: string;
|
|
firstName: string;
|
|
lastName: string;
|
|
email: string | null;
|
|
phone: string | null;
|
|
};
|
|
court: {
|
|
id: string;
|
|
name: string;
|
|
type: string;
|
|
};
|
|
}
|
|
|
|
interface BookingDialogProps {
|
|
courtId: string;
|
|
date: string;
|
|
slot: SelectedSlot;
|
|
onClose: () => void;
|
|
onBookingCreated?: () => void;
|
|
onBookingCancelled?: () => void;
|
|
}
|
|
|
|
export function BookingDialog({
|
|
courtId,
|
|
date,
|
|
slot,
|
|
onClose,
|
|
onBookingCreated,
|
|
onBookingCancelled,
|
|
}: BookingDialogProps) {
|
|
const [searchQuery, setSearchQuery] = useState("");
|
|
const [clients, setClients] = useState<Client[]>([]);
|
|
const [selectedClient, setSelectedClient] = useState<Client | null>(null);
|
|
const [loadingClients, setLoadingClients] = useState(false);
|
|
const [loadingBooking, setLoadingBooking] = useState(false);
|
|
const [booking, setBooking] = useState<BookingInfo | null>(null);
|
|
const [loadingBookingInfo, setLoadingBookingInfo] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const [creatingBooking, setCreatingBooking] = useState(false);
|
|
const [cancellingBooking, setCancellingBooking] = useState(false);
|
|
|
|
// Parse slot time to Date for display
|
|
const [hours, minutes] = slot.time.split(":").map(Number);
|
|
const slotDate = new Date(date);
|
|
slotDate.setHours(hours, minutes, 0, 0);
|
|
|
|
// Fetch booking info if slot is not available
|
|
const fetchBookingInfo = useCallback(async () => {
|
|
if (!slot.bookingId) return;
|
|
|
|
setLoadingBookingInfo(true);
|
|
try {
|
|
const response = await fetch(`/api/bookings/${slot.bookingId}`);
|
|
if (!response.ok) {
|
|
throw new Error("Error al cargar la reserva");
|
|
}
|
|
const data = await response.json();
|
|
setBooking(data);
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : "Error desconocido");
|
|
} finally {
|
|
setLoadingBookingInfo(false);
|
|
}
|
|
}, [slot.bookingId]);
|
|
|
|
// Fetch clients based on search
|
|
const fetchClients = useCallback(async (search: string) => {
|
|
if (!search || search.trim().length < 2) {
|
|
setClients([]);
|
|
return;
|
|
}
|
|
|
|
setLoadingClients(true);
|
|
try {
|
|
const response = await fetch(
|
|
`/api/clients?search=${encodeURIComponent(search)}&limit=10`
|
|
);
|
|
if (!response.ok) {
|
|
throw new Error("Error al buscar clientes");
|
|
}
|
|
const data: ClientsResponse = await response.json();
|
|
setClients(data.data);
|
|
} catch (err) {
|
|
console.error("Error fetching clients:", err);
|
|
setClients([]);
|
|
} finally {
|
|
setLoadingClients(false);
|
|
}
|
|
}, []);
|
|
|
|
// Load booking info on mount if slot is booked
|
|
useEffect(() => {
|
|
if (!slot.available && slot.bookingId) {
|
|
fetchBookingInfo();
|
|
}
|
|
}, [slot.available, slot.bookingId, fetchBookingInfo]);
|
|
|
|
// Debounce client search
|
|
useEffect(() => {
|
|
const timer = setTimeout(() => {
|
|
fetchClients(searchQuery);
|
|
}, 300);
|
|
|
|
return () => clearTimeout(timer);
|
|
}, [searchQuery, fetchClients]);
|
|
|
|
// Handle booking creation
|
|
const handleCreateBooking = async () => {
|
|
if (!selectedClient) return;
|
|
|
|
setCreatingBooking(true);
|
|
setError(null);
|
|
|
|
try {
|
|
// Calculate end time (1 hour later)
|
|
const endDate = new Date(slotDate);
|
|
endDate.setHours(endDate.getHours() + 1);
|
|
|
|
const response = await fetch("/api/bookings", {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
courtId,
|
|
clientId: selectedClient.id,
|
|
startTime: slotDate.toISOString(),
|
|
endTime: endDate.toISOString(),
|
|
paymentType: "CASH",
|
|
}),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const data = await response.json();
|
|
throw new Error(data.error || "Error al crear la reserva");
|
|
}
|
|
|
|
onBookingCreated?.();
|
|
onClose();
|
|
} catch (err) {
|
|
setError(err instanceof Error ? err.message : "Error al crear la reserva");
|
|
} finally {
|
|
setCreatingBooking(false);
|
|
}
|
|
};
|
|
|
|
// Handle booking cancellation
|
|
const handleCancelBooking = async () => {
|
|
if (!slot.bookingId) return;
|
|
|
|
setCancellingBooking(true);
|
|
setError(null);
|
|
|
|
try {
|
|
const response = await fetch(`/api/bookings/${slot.bookingId}`, {
|
|
method: "DELETE",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({
|
|
cancelReason: "Cancelada por el administrador",
|
|
}),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const data = await response.json();
|
|
throw new Error(data.error || "Error al cancelar la reserva");
|
|
}
|
|
|
|
onBookingCancelled?.();
|
|
onClose();
|
|
} catch (err) {
|
|
setError(
|
|
err instanceof Error ? err.message : "Error al cancelar la reserva"
|
|
);
|
|
} finally {
|
|
setCancellingBooking(false);
|
|
}
|
|
};
|
|
|
|
// Handle click outside to close
|
|
const handleOverlayClick = (e: React.MouseEvent) => {
|
|
if (e.target === e.currentTarget) {
|
|
onClose();
|
|
}
|
|
};
|
|
|
|
return (
|
|
<div
|
|
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
|
|
onClick={handleOverlayClick}
|
|
>
|
|
<Card className="w-full max-w-md max-h-[90vh] overflow-hidden flex flex-col">
|
|
<CardHeader className="pb-4">
|
|
<div className="flex items-center justify-between">
|
|
<CardTitle className="text-lg">
|
|
{slot.available ? "Nueva Reserva" : "Detalle de Reserva"}
|
|
</CardTitle>
|
|
<button
|
|
onClick={onClose}
|
|
className="rounded-full p-1 hover:bg-primary-100 transition-colors"
|
|
>
|
|
<svg
|
|
className="h-5 w-5 text-primary-500"
|
|
fill="none"
|
|
stroke="currentColor"
|
|
viewBox="0 0 24 24"
|
|
>
|
|
<path
|
|
strokeLinecap="round"
|
|
strokeLinejoin="round"
|
|
strokeWidth={2}
|
|
d="M6 18L18 6M6 6l12 12"
|
|
/>
|
|
</svg>
|
|
</button>
|
|
</div>
|
|
<div className="text-sm text-primary-600 space-y-1 mt-2">
|
|
<p>
|
|
<span className="font-medium">Cancha:</span> {slot.courtName}
|
|
</p>
|
|
<p>
|
|
<span className="font-medium">Fecha:</span> {formatDate(date)}
|
|
</p>
|
|
<p>
|
|
<span className="font-medium">Hora:</span> {formatTime(slotDate)}
|
|
</p>
|
|
<p>
|
|
<span className="font-medium">Precio:</span>{" "}
|
|
{formatCurrency(slot.price)}
|
|
</p>
|
|
</div>
|
|
</CardHeader>
|
|
|
|
<CardContent className="flex-1 overflow-y-auto">
|
|
{error && (
|
|
<div className="mb-4 rounded-md bg-red-50 border border-red-200 p-3 text-sm text-red-700">
|
|
{error}
|
|
</div>
|
|
)}
|
|
|
|
{/* Available slot - show client search */}
|
|
{slot.available && (
|
|
<div className="space-y-4">
|
|
<div>
|
|
<label className="block text-sm font-medium text-primary-700 mb-2">
|
|
Buscar Cliente
|
|
</label>
|
|
<Input
|
|
type="text"
|
|
placeholder="Nombre, email o telefono..."
|
|
value={searchQuery}
|
|
onChange={(e) => setSearchQuery(e.target.value)}
|
|
autoFocus
|
|
/>
|
|
</div>
|
|
|
|
{/* Client search results */}
|
|
<div className="space-y-2">
|
|
{loadingClients && (
|
|
<div className="flex items-center justify-center py-4">
|
|
<div className="h-5 w-5 animate-spin rounded-full border-2 border-primary-200 border-t-primary-600" />
|
|
</div>
|
|
)}
|
|
|
|
{!loadingClients && searchQuery.length >= 2 && clients.length === 0 && (
|
|
<p className="text-sm text-primary-500 text-center py-4">
|
|
No se encontraron clientes.
|
|
</p>
|
|
)}
|
|
|
|
{!loadingClients &&
|
|
clients.map((client) => (
|
|
<button
|
|
key={client.id}
|
|
type="button"
|
|
onClick={() => setSelectedClient(client)}
|
|
className={cn(
|
|
"w-full rounded-md border p-3 text-left transition-all",
|
|
"hover:border-primary-400 hover:bg-primary-50",
|
|
selectedClient?.id === client.id
|
|
? "border-primary-500 bg-primary-50 ring-2 ring-primary-500"
|
|
: "border-primary-200 bg-white"
|
|
)}
|
|
>
|
|
<div className="flex items-center justify-between">
|
|
<div>
|
|
<p className="font-medium text-primary-800">
|
|
{client.firstName} {client.lastName}
|
|
</p>
|
|
<p className="text-xs text-primary-500">
|
|
{client.email || client.phone || "Sin contacto"}
|
|
</p>
|
|
</div>
|
|
{client.memberships.length > 0 && (
|
|
<span className="text-xs bg-accent-100 text-accent-700 px-2 py-1 rounded-full">
|
|
{client.memberships[0].plan.name}
|
|
</span>
|
|
)}
|
|
</div>
|
|
</button>
|
|
))}
|
|
</div>
|
|
|
|
{/* Selected client summary */}
|
|
{selectedClient && (
|
|
<div className="mt-4 rounded-md border border-accent-200 bg-accent-50 p-3">
|
|
<p className="text-sm font-medium text-accent-800">
|
|
Cliente seleccionado:
|
|
</p>
|
|
<p className="text-sm text-accent-700">
|
|
{selectedClient.firstName} {selectedClient.lastName}
|
|
</p>
|
|
{selectedClient.memberships.length > 0 && (
|
|
<p className="text-xs text-accent-600 mt-1">
|
|
Membresia: {selectedClient.memberships[0].plan.name}
|
|
{selectedClient.memberships[0].remainingHours !== null &&
|
|
selectedClient.memberships[0].remainingHours > 0 && (
|
|
<span className="ml-2">
|
|
({selectedClient.memberships[0].remainingHours}h restantes)
|
|
</span>
|
|
)}
|
|
</p>
|
|
)}
|
|
</div>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
{/* Booked slot - show booking info */}
|
|
{!slot.available && (
|
|
<div className="space-y-4">
|
|
{loadingBookingInfo && (
|
|
<div className="flex items-center justify-center py-8">
|
|
<div className="h-6 w-6 animate-spin rounded-full border-2 border-primary-200 border-t-primary-600" />
|
|
</div>
|
|
)}
|
|
|
|
{!loadingBookingInfo && booking && (
|
|
<div className="space-y-4">
|
|
<div className="rounded-md border border-primary-200 bg-primary-50 p-4 space-y-3">
|
|
<div>
|
|
<p className="text-xs text-primary-500">Cliente</p>
|
|
<p className="font-medium text-primary-800">
|
|
{booking.client.firstName} {booking.client.lastName}
|
|
</p>
|
|
{booking.client.phone && (
|
|
<p className="text-sm text-primary-600">
|
|
{booking.client.phone}
|
|
</p>
|
|
)}
|
|
{booking.client.email && (
|
|
<p className="text-sm text-primary-600">
|
|
{booking.client.email}
|
|
</p>
|
|
)}
|
|
</div>
|
|
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<div>
|
|
<p className="text-xs text-primary-500">Estado</p>
|
|
<p
|
|
className={cn(
|
|
"text-sm font-medium",
|
|
booking.status === "CONFIRMED" && "text-accent-600",
|
|
booking.status === "PENDING" && "text-yellow-600",
|
|
booking.status === "CANCELLED" && "text-red-600"
|
|
)}
|
|
>
|
|
{booking.status === "CONFIRMED" && "Confirmada"}
|
|
{booking.status === "PENDING" && "Pendiente"}
|
|
{booking.status === "CANCELLED" && "Cancelada"}
|
|
{booking.status === "COMPLETED" && "Completada"}
|
|
{booking.status === "NO_SHOW" && "No asistio"}
|
|
</p>
|
|
</div>
|
|
<div>
|
|
<p className="text-xs text-primary-500">Tipo de Pago</p>
|
|
<p className="text-sm text-primary-800">
|
|
{booking.paymentType === "CASH" && "Efectivo"}
|
|
{booking.paymentType === "CARD" && "Tarjeta"}
|
|
{booking.paymentType === "TRANSFER" && "Transferencia"}
|
|
{booking.paymentType === "MEMBERSHIP" && "Membresia"}
|
|
{booking.paymentType === "FREE" && "Gratuito"}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
|
|
<div>
|
|
<p className="text-xs text-primary-500">Total</p>
|
|
<p className="text-lg font-semibold text-primary-800">
|
|
{formatCurrency(Number(booking.totalPrice))}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{!loadingBookingInfo && !booking && (
|
|
<div className="text-center py-4 text-primary-500">
|
|
<p>No se pudo cargar la informacion de la reserva.</p>
|
|
</div>
|
|
)}
|
|
</div>
|
|
)}
|
|
</CardContent>
|
|
|
|
<CardFooter className="border-t border-primary-200 bg-primary-50 pt-4">
|
|
<div className="flex w-full gap-3">
|
|
<Button variant="outline" onClick={onClose} className="flex-1">
|
|
Cerrar
|
|
</Button>
|
|
|
|
{slot.available && (
|
|
<Button
|
|
variant="accent"
|
|
onClick={handleCreateBooking}
|
|
disabled={!selectedClient || creatingBooking}
|
|
className="flex-1"
|
|
>
|
|
{creatingBooking ? (
|
|
<span className="flex items-center gap-2">
|
|
<div className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" />
|
|
Creando...
|
|
</span>
|
|
) : (
|
|
"Crear Reserva"
|
|
)}
|
|
</Button>
|
|
)}
|
|
|
|
{!slot.available && booking && booking.status !== "CANCELLED" && (
|
|
<Button
|
|
variant="destructive"
|
|
onClick={handleCancelBooking}
|
|
disabled={cancellingBooking}
|
|
className="flex-1"
|
|
>
|
|
{cancellingBooking ? (
|
|
<span className="flex items-center gap-2">
|
|
<div className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" />
|
|
Cancelando...
|
|
</span>
|
|
) : (
|
|
"Cancelar Reserva"
|
|
)}
|
|
</Button>
|
|
)}
|
|
</div>
|
|
</CardFooter>
|
|
</Card>
|
|
</div>
|
|
);
|
|
}
|