New booking panel

This commit is contained in:
Jose Selesan
2026-05-05 10:16:38 -03:00
parent 546a020003
commit c089215835
19 changed files with 1991 additions and 1072 deletions

View File

@@ -1,62 +1,9 @@
import { Button } from '@/components/ui/button';
import { DatePicker } from '@/components/ui/date-picker';
import { Field, FieldError, FieldLabel } from '@/components/ui/field';
import { Input } from '@/components/ui/input';
import {
ResponsiveDialog,
ResponsiveDialogClose,
ResponsiveDialogContent,
ResponsiveDialogDescription,
ResponsiveDialogFooter,
ResponsiveDialogHeader,
ResponsiveDialogTitle,
ResponsiveDialogTrigger,
} from '@/components/ui/responsive-dialog';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Booking } from '@/features/booking/booking';
import { ApiClientError, apiClient } from '@/lib/api-client';
import { useCurrentComplexStore } from '@/lib/stores/current-complex-store';
import { zodResolver } from '@hookform/resolvers/zod';
import type { AdminBooking } from '@repo/api-contract';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from '@tanstack/react-router';
import { Check, Copy } from 'lucide-react';
import { useEffect, useMemo, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
const manualBookingSchema = z.object({
customerName: z
.string()
.trim()
.min(2, 'Ingresa un nombre válido.')
.max(120, 'El nombre no puede superar los 120 caracteres.'),
customerPhone: z
.string()
.trim()
.min(6, 'Ingresa un telefono válido.')
.max(30, 'El telefono no puede superar los 30 caracteres.'),
});
type ManualBookingForm = z.infer<typeof manualBookingSchema>;
function toIsoDateLocal(date: Date) {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
}
function fromIsoDateLocal(dateIso: string): Date | undefined {
const [year, month, day] = dateIso.split('-').map(Number);
if (!year || !month || !day) return undefined;
return new Date(year, month - 1, day);
}
import { useEffect } from 'react';
function extractMessage(error: unknown, fallback: string) {
if (error instanceof ApiClientError) {
@@ -66,71 +13,9 @@ function extractMessage(error: unknown, fallback: string) {
return fallback;
}
function formatDateLabel(dateIso: string) {
const [year, month, day] = dateIso.split('-').map(Number);
if (!year || !month || !day) return dateIso;
const date = new Date(year, month - 1, day);
return new Intl.DateTimeFormat('es-AR', {
weekday: 'long',
day: '2-digit',
month: 'long',
}).format(date);
}
function getEffectiveStatus(
booking: AdminBooking
): 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NO_SHOW' {
if (booking.status !== 'CONFIRMED') {
return booking.status;
}
// Check if booking is past end time and still confirmed
const now = new Date();
const bookingDateTime = new Date(`${booking.date}T${booking.endTime}:00`);
if (now > bookingDateTime) {
return 'NO_SHOW';
}
return 'CONFIRMED';
}
function effectiveStatusLabel(status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NO_SHOW') {
if (status === 'NO_SHOW') return 'No show';
if (status === 'COMPLETED') return 'Cumplida';
if (status === 'CANCELLED') return 'Cancelada';
return 'Confirmada';
}
function effectiveStatusClassName(status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED' | 'NO_SHOW') {
if (status === 'NO_SHOW') {
return 'border-orange-200 bg-orange-50 text-orange-700';
}
if (status === 'COMPLETED') {
return 'border-emerald-200 bg-emerald-50 text-emerald-700';
}
if (status === 'CANCELLED') {
return 'border-rose-200 bg-rose-50 text-rose-700';
}
return 'border-sky-200 bg-sky-50 text-sky-700';
}
export function HomePage() {
const queryClient = useQueryClient();
const navigate = useNavigate();
const todayIso = useMemo(() => toIsoDateLocal(new Date()), []);
const [fromDate, setFromDate] = useState(todayIso);
const [manualDate, setManualDate] = useState(todayIso);
const [selectedSportId, setSelectedSportId] = useState<string | undefined>();
const [selectedCourtId, setSelectedCourtId] = useState<string>('');
const [selectedStartTime, setSelectedStartTime] = useState<string>('');
const [isManualBookingOpen, setIsManualBookingOpen] = useState(false);
const [urlCopied, setUrlCopied] = useState(false);
const currentComplexQuery = useQuery({
queryKey: ['current-complex'],
@@ -152,6 +37,7 @@ export function HomePage() {
queryClient.invalidateQueries({ queryKey: ['admin-bookings'] });
}
});
return unsubscribe;
}, [queryClient]);
@@ -191,7 +77,6 @@ export function HomePage() {
if (!selectedComplex?.id) return;
const channel = `complex-${selectedComplex.id}`;
let eventSource: EventSource | null = null;
let reconnectTimeout: ReturnType<typeof setTimeout> | null = null;
let reconnectAttempts = 0;
@@ -199,27 +84,32 @@ export function HomePage() {
let lastEventId: string | null = null;
let pollInterval: ReturnType<typeof setInterval> | null = null;
const startPolling = () => {
if (pollInterval) return;
pollInterval = setInterval(() => {
void queryClient.invalidateQueries({ queryKey: ['admin-bookings', selectedComplex.id] });
}, 10000);
};
const connect = () => {
if (eventSource) {
eventSource.close();
}
if (reconnectAttempts >= maxReconnectAttempts) {
console.log('[SSE] Max reconnect attempts reached, switching to polling');
startPolling();
return;
}
const url = `${import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000'}/api/events/${encodeURIComponent(channel)}`;
const baseUrl = import.meta.env.VITE_API_BASE_URL || 'http://localhost:3000';
const url = `${baseUrl}/api/events/${encodeURIComponent(channel)}`;
eventSource = new EventSource(url);
eventSource.onerror = () => {
if (eventSource?.readyState === EventSource.CLOSED) {
reconnectAttempts++;
console.log(
`[SSE] Connection closed, retry ${reconnectAttempts}/${maxReconnectAttempts}`
);
reconnectTimeout = setTimeout(() => {
connect();
}, 2000);
@@ -239,15 +129,6 @@ export function HomePage() {
});
};
const startPolling = () => {
if (pollInterval) return;
console.log('[SSE] Starting polling fallback');
pollInterval = setInterval(() => {
void queryClient.invalidateQueries({ queryKey: ['admin-bookings', selectedComplex.id] });
}, 10000);
};
connect();
return () => {
@@ -261,526 +142,21 @@ export function HomePage() {
};
}, [selectedComplex?.id, queryClient]);
const bookingsQuery = useQuery({
queryKey: ['admin-bookings', selectedComplex?.id, fromDate],
enabled: Boolean(selectedComplex?.id),
queryFn: () =>
apiClient.adminBookings.listByComplex(selectedComplex?.id as string, {
fromDate,
}),
});
const manualAvailabilityQuery = useQuery({
queryKey: [
'manual-booking-availability',
selectedComplex?.complexSlug,
manualDate,
selectedSportId,
],
enabled: Boolean(selectedComplex?.complexSlug && manualDate),
queryFn: () =>
apiClient.publicBookings.getAvailability(selectedComplex?.complexSlug as string, {
date: manualDate,
...(selectedSportId ? { sportId: selectedSportId } : {}),
}),
});
useEffect(() => {
const availability = manualAvailabilityQuery.data;
if (!availability) return;
if (!availability.sportSelectionRequired) {
if (availability.sports[0] && !selectedSportId) {
setSelectedSportId(availability.sports[0].id);
}
} else if (
selectedSportId &&
!availability.sports.some((sport) => sport.id === selectedSportId)
) {
setSelectedSportId(undefined);
}
}, [manualAvailabilityQuery.data, selectedSportId]);
useEffect(() => {
if (!manualAvailabilityQuery.data) return;
if (
selectedCourtId &&
!manualAvailabilityQuery.data.courts.some((court) => court.courtId === selectedCourtId)
) {
setSelectedCourtId('');
setSelectedStartTime('');
}
}, [manualAvailabilityQuery.data, selectedCourtId]);
const selectedCourt = useMemo(() => {
return manualAvailabilityQuery.data?.courts.find((court) => court.courtId === selectedCourtId);
}, [manualAvailabilityQuery.data?.courts, selectedCourtId]);
useEffect(() => {
if (!selectedCourt) {
setSelectedStartTime('');
return;
}
if (!selectedCourt.availableSlots.some((slot) => slot.startTime === selectedStartTime)) {
setSelectedStartTime('');
}
}, [selectedCourt, selectedStartTime]);
const groupedBookings = useMemo(() => {
const groups = new Map<string, AdminBooking[]>();
for (const booking of bookingsQuery.data?.bookings ?? []) {
const current = groups.get(booking.date) ?? [];
current.push(booking);
groups.set(booking.date, current);
}
return [...groups.entries()];
}, [bookingsQuery.data?.bookings]);
const updateStatusMutation = useMutation({
mutationFn: (payload: { bookingId: string; status: 'CANCELLED' | 'COMPLETED' }) =>
apiClient.adminBookings.updateStatus(payload.bookingId, { status: payload.status }),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ['admin-bookings', selectedComplex?.id] });
void queryClient.invalidateQueries({
queryKey: ['manual-booking-availability', selectedComplex?.complexSlug],
});
},
});
const {
register,
handleSubmit,
reset,
formState: { errors, isValid },
} = useForm<ManualBookingForm>({
resolver: zodResolver(manualBookingSchema),
mode: 'onChange',
defaultValues: {
customerName: '',
customerPhone: '',
},
});
const createManualBookingMutation = useMutation({
mutationFn: async (values: ManualBookingForm) => {
if (!selectedComplex?.id) {
throw new Error('No se encontró el complejo actual.');
}
if (!selectedCourtId || !selectedStartTime) {
throw new Error('Debes seleccionar cancha y horario.');
}
return apiClient.adminBookings.create(selectedComplex.id, {
date: manualDate,
courtId: selectedCourtId,
startTime: selectedStartTime,
customerName: values.customerName,
customerPhone: values.customerPhone,
});
},
onSuccess: async () => {
reset();
setSelectedCourtId('');
setSelectedStartTime('');
setIsManualBookingOpen(false);
await queryClient.invalidateQueries({ queryKey: ['admin-bookings', selectedComplex?.id] });
await queryClient.invalidateQueries({
queryKey: ['manual-booking-availability', selectedComplex?.complexSlug],
});
},
});
const onSubmitManualBooking = async (values: ManualBookingForm) => {
await createManualBookingMutation.mutateAsync(values);
};
const publicBookingUrl = selectedComplex
? `${window.location.origin}/${selectedComplex.complexSlug}/booking`
: '';
const copyToClipboard = async () => {
await navigator.clipboard.writeText(publicBookingUrl);
setUrlCopied(true);
setTimeout(() => {
setUrlCopied(false);
}, 3000);
};
if (myComplexesQuery.isLoading) {
return (
<main className="mx-auto w-full max-w-6xl px-6 py-8">
<p className="text-sm text-muted-foreground">Cargando panel...</p>
</main>
);
return <p className="text-sm text-muted-foreground">Cargando panel...</p>;
}
if (myComplexesQuery.isError) {
return (
<main className="mx-auto w-full max-w-6xl px-6 py-8">
<p className="text-sm text-destructive">
{extractMessage(myComplexesQuery.error, 'No pudimos cargar tus complejos.')}
</p>
</main>
<p className="text-sm text-destructive">
{extractMessage(myComplexesQuery.error, 'No pudimos cargar tus complejos.')}
</p>
);
}
if (!selectedComplex) {
return (
<main className="mx-auto w-full max-w-6xl px-6 py-8">
<p className="text-sm text-muted-foreground">No tienes complejos asignados todavía.</p>
</main>
);
return <p className="text-sm text-muted-foreground">No tienes complejos asignados todavía.</p>;
}
return (
<main className="mx-auto flex w-full max-w-6xl flex-col gap-6 px-6 py-6">
<section className="rounded-xl border bg-card p-5 shadow-sm">
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
<div>
<h1 className="text-2xl font-semibold">Panel de reservas</h1>
<p className="mt-2 text-sm text-muted-foreground">
Gestiona turnos del día y futuros para {selectedComplex.complexName}.
</p>
<div className="mt-2 flex items-center gap-2">
<a
href={publicBookingUrl}
target="_blank"
rel="noopener noreferrer"
className="text-sm text-muted-foreground underline hover:text-foreground"
>
{publicBookingUrl}
</a>
<button
type="button"
onClick={copyToClipboard}
className="text-muted-foreground hover:text-foreground"
title="Copiar URL"
>
{urlCopied ? (
<Check className="h-4 w-4 text-emerald-500" />
) : (
<Copy className="h-4 w-4" />
)}
</button>
</div>
</div>
<ResponsiveDialog
open={isManualBookingOpen}
onOpenChange={(open) => {
setIsManualBookingOpen(open);
if (!open) {
reset();
setManualDate(todayIso);
setSelectedSportId(undefined);
setSelectedCourtId('');
setSelectedStartTime('');
}
}}
>
<ResponsiveDialogTrigger asChild>
<Button>Nueva Reserva</Button>
</ResponsiveDialogTrigger>
<ResponsiveDialogContent
className="data-[variant=dialog]:max-w-lg"
onOpenAutoFocus={(e) => e.preventDefault()}
>
<ResponsiveDialogHeader>
<ResponsiveDialogTitle>Reserva manual</ResponsiveDialogTitle>
<ResponsiveDialogDescription>
Crea un turno para atención telefónica o mostrador.
</ResponsiveDialogDescription>
</ResponsiveDialogHeader>
<form
id="manual-booking-form"
className="grid gap-4"
onSubmit={handleSubmit(onSubmitManualBooking)}
>
<div className="grid gap-3 md:grid-cols-2">
<Field>
<FieldLabel htmlFor="manualDate">Fecha</FieldLabel>
<DatePicker
value={fromIsoDateLocal(manualDate)}
onChange={(date) => {
const isoDate = date ? toIsoDateLocal(date) : todayIso;
setManualDate(isoDate);
setSelectedCourtId('');
setSelectedStartTime('');
}}
minDate={new Date()}
placeholder="Selecciona una fecha"
/>
</Field>
{manualAvailabilityQuery.data?.sportSelectionRequired && (
<Field>
<FieldLabel>Deporte</FieldLabel>
<Select
value={selectedSportId ?? ''}
onValueChange={(value) => {
setSelectedSportId(value);
setSelectedCourtId('');
setSelectedStartTime('');
}}
>
<SelectTrigger>
<SelectValue placeholder="Selecciona un deporte" />
</SelectTrigger>
<SelectContent>
{manualAvailabilityQuery.data?.sports.map((sport) => (
<SelectItem key={sport.id} value={sport.id}>
{sport.name}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
)}
<Field>
<FieldLabel>Cancha</FieldLabel>
<Select
value={selectedCourtId}
onValueChange={(value) => {
setSelectedCourtId(value);
setSelectedStartTime('');
}}
>
<SelectTrigger>
<SelectValue placeholder="Selecciona una cancha" />
</SelectTrigger>
<SelectContent>
{(manualAvailabilityQuery.data?.courts ?? []).map((court) => (
<SelectItem key={court.courtId} value={court.courtId}>
{court.courtName} · {court.sport.name}
</SelectItem>
))}
</SelectContent>
</Select>
</Field>
<Field>
<FieldLabel>Horario</FieldLabel>
<Select value={selectedStartTime} onValueChange={setSelectedStartTime}>
<SelectTrigger>
<SelectValue placeholder="Selecciona un horario" />
</SelectTrigger>
<SelectContent>
{(selectedCourt?.availableSlots ?? []).map((slot) => {
const isToday = manualDate === todayIso;
const currentTime = new Date();
const currentHours = currentTime.getHours().toString().padStart(2, '0');
const currentMinutes = currentTime
.getMinutes()
.toString()
.padStart(2, '0');
const currentTimeStr = `${currentHours}:${currentMinutes}`;
const isPastSlot = isToday && slot.startTime <= currentTimeStr;
if (isPastSlot) return null;
return (
<SelectItem key={slot.startTime} value={slot.startTime}>
{slot.startTime}
</SelectItem>
);
})}
</SelectContent>
</Select>
</Field>
</div>
{manualAvailabilityQuery.isLoading && (
<p className="text-sm text-muted-foreground">Cargando horarios disponibles...</p>
)}
{manualAvailabilityQuery.isError && (
<p className="text-sm text-destructive">
{extractMessage(
manualAvailabilityQuery.error,
'No pudimos cargar disponibilidad para la reserva manual.'
)}
</p>
)}
<Field data-invalid={Boolean(errors.customerName)}>
<FieldLabel htmlFor="customerName">Nombre</FieldLabel>
<Input
id="customerName"
placeholder="Ej: Juan Perez"
aria-invalid={Boolean(errors.customerName)}
{...register('customerName')}
/>
<FieldError errors={[errors.customerName]} />
</Field>
<Field data-invalid={Boolean(errors.customerPhone)}>
<FieldLabel htmlFor="customerPhone">Teléfono</FieldLabel>
<Input
id="customerPhone"
type="tel"
placeholder="Ej: 3875551234"
aria-invalid={Boolean(errors.customerPhone)}
{...register('customerPhone')}
/>
<FieldError errors={[errors.customerPhone]} />
</Field>
{createManualBookingMutation.isError && (
<p className="text-sm text-destructive">
{extractMessage(
createManualBookingMutation.error,
'No pudimos crear la reserva manual.'
)}
</p>
)}
</form>
<ResponsiveDialogFooter>
<ResponsiveDialogClose asChild>
<Button variant="outline">Cancelar</Button>
</ResponsiveDialogClose>
<Button
type="submit"
form="manual-booking-form"
disabled={
!isValid ||
createManualBookingMutation.isPending ||
!selectedCourtId ||
!selectedStartTime
}
>
{createManualBookingMutation.isPending ? 'Guardando...' : 'Crear reserva'}
</Button>
</ResponsiveDialogFooter>
</ResponsiveDialogContent>
</ResponsiveDialog>
</div>
</section>
<section className="rounded-xl border bg-card p-5 shadow-sm">
<div className="flex flex-col gap-3 sm:flex-row sm:items-end">
<Field>
<FieldLabel htmlFor="fromDate">Mostrar desde</FieldLabel>
<DatePicker
value={fromIsoDateLocal(fromDate)}
onChange={(date) => {
const isoDate = date ? toIsoDateLocal(date) : todayIso;
setFromDate(isoDate);
}}
disabled={(date) => {
const today = new Date();
today.setHours(0, 0, 0, 0);
const checkDate = new Date(date);
checkDate.setHours(0, 0, 0, 0);
return checkDate < today;
}}
placeholder="Selecciona una fecha"
/>
</Field>
</div>
{bookingsQuery.isLoading && (
<p className="mt-4 text-sm text-muted-foreground">Cargando reservas...</p>
)}
{bookingsQuery.isError && (
<p className="mt-4 text-sm text-destructive">
{extractMessage(bookingsQuery.error, 'No pudimos cargar las reservas.')}
</p>
)}
{!bookingsQuery.isLoading && !bookingsQuery.isError && groupedBookings.length === 0 && (
<p className="mt-4 text-sm text-muted-foreground">
No hay reservas para la fecha seleccionada en adelante.
</p>
)}
<div className="mt-4 space-y-4">
{groupedBookings.map(([date, bookings]) => (
<article key={date} className="rounded-lg border bg-background p-3">
<h2 className="text-sm font-semibold capitalize">{formatDateLabel(date)}</h2>
<div className="mt-3 space-y-2">
{bookings.map((booking) => {
const effectiveStatus = getEffectiveStatus(booking);
const canManage =
booking.status === 'CONFIRMED' && effectiveStatus === 'CONFIRMED';
const isMutating = updateStatusMutation.isPending;
return (
<div
key={booking.id}
className="flex flex-col gap-2 rounded-md border p-3 sm:flex-row sm:items-center sm:justify-between"
>
<div>
<p className="text-sm font-medium">
{booking.startTime} - {booking.endTime} · {booking.courtName}
</p>
<p className="text-xs text-muted-foreground">
{booking.customerName} ({booking.customerPhone}) · Código{' '}
{booking.bookingCode}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<span
className={`inline-flex rounded-full border px-2 py-1 text-xs font-medium ${effectiveStatusClassName(effectiveStatus)}`}
>
{effectiveStatusLabel(effectiveStatus)}
</span>
{canManage && (
<>
<Button
type="button"
size="sm"
variant="outline"
disabled={isMutating}
onClick={() => {
updateStatusMutation.mutate({
bookingId: booking.id,
status: 'COMPLETED',
});
}}
>
Marcar cumplida
</Button>
<Button
type="button"
size="sm"
variant="destructive"
disabled={isMutating}
onClick={() => {
updateStatusMutation.mutate({
bookingId: booking.id,
status: 'CANCELLED',
});
}}
>
Cancelar
</Button>
</>
)}
</div>
</div>
);
})}
</div>
</article>
))}
</div>
{updateStatusMutation.isError && (
<p className="mt-4 text-sm text-destructive">
{extractMessage(updateStatusMutation.error, 'No pudimos actualizar la reserva.')}
</p>
)}
</section>
</main>
);
return <Booking complex={selectedComplex} />;
}