New booking dashboard
This commit is contained in:
@@ -1,67 +1,552 @@
|
||||
import { zodResolver } from '@hookform/resolvers/zod'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useForm } from 'react-hook-form'
|
||||
import { z } from 'zod'
|
||||
import type { AdminBooking } from '@repo/api-contract'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Field, FieldError, FieldLabel } from '@/components/ui/field'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { ApiClientError, apiClient } from '@/lib/api-client'
|
||||
import {
|
||||
getCurrentComplexSlug,
|
||||
setCurrentComplexSlug as persistCurrentComplexSlug,
|
||||
} from '@/lib/current-complex'
|
||||
|
||||
const emailSchema = z.object({
|
||||
email: z.string().email('Ingresa un email válido.'),
|
||||
const manualBookingSchema = z.object({
|
||||
customerName: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(2, 'Ingresa un nombre valido.')
|
||||
.max(120, 'El nombre no puede superar los 120 caracteres.'),
|
||||
customerPhone: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(6, 'Ingresa un telefono valido.')
|
||||
.max(30, 'El telefono no puede superar los 30 caracteres.'),
|
||||
})
|
||||
|
||||
type EmailForm = z.infer<typeof emailSchema>
|
||||
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 extractMessage(error: unknown, fallback: string) {
|
||||
if (error instanceof ApiClientError) {
|
||||
return error.message || fallback
|
||||
}
|
||||
|
||||
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 statusLabel(status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED') {
|
||||
if (status === 'COMPLETED') return 'Cumplida'
|
||||
if (status === 'CANCELLED') return 'Cancelada'
|
||||
return 'Confirmada'
|
||||
}
|
||||
|
||||
function statusClassName(status: 'CONFIRMED' | 'CANCELLED' | 'COMPLETED') {
|
||||
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 {
|
||||
register,
|
||||
handleSubmit,
|
||||
watch,
|
||||
formState: { errors, isValid, isSubmitSuccessful },
|
||||
} = useForm<EmailForm>({
|
||||
resolver: zodResolver(emailSchema),
|
||||
mode: 'onChange',
|
||||
defaultValues: {
|
||||
email: '',
|
||||
const queryClient = useQueryClient()
|
||||
const todayIso = useMemo(() => toIsoDateLocal(new Date()), [])
|
||||
|
||||
const [currentComplexSlug, setCurrentComplexSlug] = useState<string | null>(null)
|
||||
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>('')
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentComplexSlug(getCurrentComplexSlug())
|
||||
}, [])
|
||||
|
||||
const myComplexesQuery = useQuery({
|
||||
queryKey: ['my-complexes'],
|
||||
queryFn: () => apiClient.complexes.listMine(),
|
||||
})
|
||||
|
||||
const selectedComplex = useMemo(() => {
|
||||
const complexes = myComplexesQuery.data ?? []
|
||||
|
||||
if (complexes.length === 0) return null
|
||||
|
||||
if (currentComplexSlug) {
|
||||
const match = complexes.find((complex) => complex.complexSlug === currentComplexSlug)
|
||||
|
||||
if (match) return match
|
||||
}
|
||||
|
||||
return complexes[0]
|
||||
}, [currentComplexSlug, myComplexesQuery.data])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedComplex) return
|
||||
|
||||
setCurrentComplexSlug(selectedComplex.complexSlug)
|
||||
persistCurrentComplexSlug(selectedComplex.complexSlug)
|
||||
}, [selectedComplex])
|
||||
|
||||
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 emailValue = watch('email')
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
reset,
|
||||
formState: { errors, isSubmitting, isValid },
|
||||
} = useForm<ManualBookingForm>({
|
||||
resolver: zodResolver(manualBookingSchema),
|
||||
mode: 'onChange',
|
||||
defaultValues: {
|
||||
customerName: '',
|
||||
customerPhone: '',
|
||||
},
|
||||
})
|
||||
|
||||
const onSubmit = (_data: EmailForm) => {
|
||||
// Demo form: no-op; success state is managed by react-hook-form.
|
||||
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('')
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
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>
|
||||
)
|
||||
}
|
||||
|
||||
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>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<main className="mx-auto flex min-h-[60vh] w-full max-w-6xl items-center justify-center px-6">
|
||||
<section className="w-full max-w-3xl rounded-xl border bg-card p-6 text-card-foreground shadow-sm">
|
||||
<h1 className="mb-2 text-2xl font-semibold">Frontend listo</h1>
|
||||
<p className="mb-4 text-sm text-muted-foreground">
|
||||
React + Vite + TypeScript + shadcn + zod + react-hook-form.
|
||||
<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">
|
||||
<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>
|
||||
</section>
|
||||
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<Field data-invalid={Boolean(errors.email)}>
|
||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||
<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>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="tu@email.com"
|
||||
aria-invalid={Boolean(errors.email)}
|
||||
{...register('email')}
|
||||
id="fromDate"
|
||||
type="date"
|
||||
value={fromDate}
|
||||
min={todayIso}
|
||||
onChange={(event) => {
|
||||
setFromDate(event.target.value)
|
||||
}}
|
||||
/>
|
||||
<FieldError errors={[errors.email]} />
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<Button type="submit" className="mt-3 w-full" disabled={!isValid}>
|
||||
Continuar
|
||||
</Button>
|
||||
</form>
|
||||
{bookingsQuery.isLoading && (
|
||||
<p className="mt-4 text-sm text-muted-foreground">Cargando reservas...</p>
|
||||
)}
|
||||
|
||||
{isSubmitSuccessful && !errors.email && emailValue && (
|
||||
<p className="mt-3 text-sm text-emerald-600">
|
||||
Email válido según esquema zod.
|
||||
{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 canManage = booking.status === '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 ${statusClassName(booking.status)}`}
|
||||
>
|
||||
{statusLabel(booking.status)}
|
||||
</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>
|
||||
|
||||
<section className="rounded-xl border bg-card p-5 shadow-sm">
|
||||
<h2 className="text-lg font-semibold">Reserva manual</h2>
|
||||
<p className="mt-1 text-sm text-muted-foreground">
|
||||
Crea un turno para atención telefónica o mostrador.
|
||||
</p>
|
||||
|
||||
<div className="mt-4 grid gap-3 md:grid-cols-3">
|
||||
<Field>
|
||||
<FieldLabel htmlFor="manualDate">Fecha</FieldLabel>
|
||||
<Input
|
||||
id="manualDate"
|
||||
type="date"
|
||||
min={todayIso}
|
||||
value={manualDate}
|
||||
onChange={(event) => {
|
||||
setManualDate(event.target.value)
|
||||
setSelectedCourtId('')
|
||||
setSelectedStartTime('')
|
||||
}}
|
||||
/>
|
||||
</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>
|
||||
</div>
|
||||
|
||||
<div className="mt-3">
|
||||
<Field>
|
||||
<FieldLabel>Horario</FieldLabel>
|
||||
<Select value={selectedStartTime} onValueChange={setSelectedStartTime}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Selecciona un horario" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{(selectedCourt?.availableSlots ?? []).map((slot) => (
|
||||
<SelectItem key={slot.startTime} value={slot.startTime}>
|
||||
{slot.startTime} - {slot.endTime}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
{manualAvailabilityQuery.isLoading && (
|
||||
<p className="mt-3 text-sm text-muted-foreground">Cargando horarios disponibles...</p>
|
||||
)}
|
||||
|
||||
{manualAvailabilityQuery.isError && (
|
||||
<p className="mt-3 text-sm text-destructive">
|
||||
{extractMessage(
|
||||
manualAvailabilityQuery.error,
|
||||
'No pudimos cargar disponibilidad para la reserva manual.',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<form className="mt-4 grid gap-3 md:grid-cols-2" onSubmit={handleSubmit(onSubmitManualBooking)}>
|
||||
<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 md:col-span-2">
|
||||
{extractMessage(
|
||||
createManualBookingMutation.error,
|
||||
'No pudimos crear la reserva manual.',
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="md:col-span-2"
|
||||
disabled={!isValid || isSubmitting || !selectedCourtId || !selectedStartTime}
|
||||
>
|
||||
{createManualBookingMutation.isPending ? 'Guardando...' : 'Crear reserva manual'}
|
||||
</Button>
|
||||
</form>
|
||||
</section>
|
||||
</main>
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user