New booking panel
This commit is contained in:
@@ -1,67 +1,143 @@
|
|||||||
import { useState } from "react"
|
import {
|
||||||
import { CalendarDays, LogOut, Menu, Settings, User, X } from "lucide-react"
|
CalendarDays,
|
||||||
|
Check,
|
||||||
|
Laptop,
|
||||||
|
LogOut,
|
||||||
|
Menu,
|
||||||
|
Moon,
|
||||||
|
Settings,
|
||||||
|
Sun,
|
||||||
|
User,
|
||||||
|
X,
|
||||||
|
} from 'lucide-react';
|
||||||
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
|
||||||
import PlayzerIcon from "@/assets/playzer-favicon-512-transparent.png"
|
import PlayzerIcon from '@/assets/playzer-favicon-512-transparent.png';
|
||||||
import { Link, useLocation } from "@tanstack/react-router"
|
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { Link, useLocation, useNavigate } from '@tanstack/react-router';
|
||||||
|
|
||||||
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar"
|
import { Button } from '@/components/ui/button';
|
||||||
import { Button } from "@/components/ui/button"
|
|
||||||
import {
|
import {
|
||||||
DropdownMenu,
|
DropdownMenu,
|
||||||
DropdownMenuContent,
|
DropdownMenuContent,
|
||||||
DropdownMenuItem,
|
DropdownMenuItem,
|
||||||
DropdownMenuLabel,
|
DropdownMenuLabel,
|
||||||
|
DropdownMenuRadioGroup,
|
||||||
|
DropdownMenuRadioItem,
|
||||||
DropdownMenuSeparator,
|
DropdownMenuSeparator,
|
||||||
DropdownMenuTrigger,
|
DropdownMenuTrigger,
|
||||||
} from "@/components/ui/dropdown-menu"
|
} from '@/components/ui/dropdown-menu';
|
||||||
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet"
|
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
|
||||||
import { useAuth } from "@/lib/auth"
|
import { UserAvatar } from '@/components/user-avatar';
|
||||||
|
import { apiClient } from '@/lib/api-client';
|
||||||
|
import { useAuth } from '@/lib/auth';
|
||||||
|
import { acceptStoredPendingInvite } from '@/lib/invitations';
|
||||||
|
import { useCurrentComplexStore } from '@/lib/stores/current-complex-store';
|
||||||
|
import { useTheme } from '@/lib/theme';
|
||||||
|
|
||||||
interface NavItemProps {
|
interface NavItemProps {
|
||||||
to: string
|
to: '/' | '/about';
|
||||||
label: string
|
label: string;
|
||||||
isMobile?: boolean
|
isMobile?: boolean;
|
||||||
onClick?: () => void
|
onClick?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
function NavItem({ to, label, isMobile, onClick }: NavItemProps) {
|
function NavItem({ to, label, isMobile, onClick }: NavItemProps) {
|
||||||
const location = useLocation()
|
const location = useLocation();
|
||||||
const currentPath = location.pathname
|
const currentPath = location.pathname;
|
||||||
const isActive = to === "/" ? currentPath === "/" : currentPath.startsWith(to)
|
const isActive = to === '/' ? currentPath === '/' : currentPath.startsWith(to);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Link to={to} onClick={onClick}>
|
<Link to={to} onClick={onClick}>
|
||||||
<Button
|
<Button
|
||||||
variant="ghost"
|
variant="ghost"
|
||||||
size={isMobile ? "default" : "sm"}
|
size={isMobile ? 'default' : 'sm'}
|
||||||
className={[
|
className={[
|
||||||
"rounded-none transition-all duration-200 hover:bg-transparent",
|
'rounded-none transition-all duration-200 hover:bg-transparent',
|
||||||
"focus-visible:ring-2 focus-visible:ring-primary/50",
|
'focus-visible:ring-2 focus-visible:ring-primary/50',
|
||||||
isMobile && "w-full justify-start rounded-2xl",
|
isMobile && 'w-full justify-start rounded-2xl',
|
||||||
isActive
|
isActive
|
||||||
? "text-primary relative after:absolute after:bottom-0 after:left-0 after:right-0 after:h-0.5 after:bg-primary"
|
? 'text-primary relative after:absolute after:bottom-0 after:left-0 after:right-0 after:h-0.5 after:bg-primary'
|
||||||
: "text-muted-foreground hover:text-foreground relative hover:after:absolute hover:after:bottom-0 hover:after:left-0 hover:after:right-0 hover:after:h-0.5 hover:after:bg-primary/50",
|
: 'text-muted-foreground hover:text-foreground relative hover:after:absolute hover:after:bottom-0 hover:after:left-0 hover:after:right-0 hover:after:h-0.5 hover:after:bg-primary/50',
|
||||||
]
|
]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(" ")}
|
.join(' ')}
|
||||||
>
|
>
|
||||||
{label}
|
{label}
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Header() {
|
export function Header() {
|
||||||
const [open, setOpen] = useState(false)
|
const [open, setOpen] = useState(false);
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
const { user, isAuthenticated, displayName, avatarUrl, signOut } = useAuth();
|
const { user, isAuthenticated, displayName, avatarUrl, signOut } = useAuth();
|
||||||
|
const { theme, setTheme } = useTheme();
|
||||||
|
const { currentComplexSlug, setCurrentComplex } = useCurrentComplexStore();
|
||||||
|
const processedInviteForUser = useRef<string | null>(null);
|
||||||
|
const myComplexesQuery = useQuery({
|
||||||
|
queryKey: ['my-complexes'],
|
||||||
|
enabled: isAuthenticated,
|
||||||
|
queryFn: () => apiClient.complexes.listMine(),
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isAuthenticated) {
|
||||||
|
processedInviteForUser.current = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const userKey = user?.email ?? displayName ?? 'authenticated-user';
|
||||||
|
|
||||||
|
if (processedInviteForUser.current === userKey) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
processedInviteForUser.current = userKey;
|
||||||
|
|
||||||
|
void (async () => {
|
||||||
|
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
|
||||||
|
await queryClient.invalidateQueries({ queryKey: ['my-complexes'] });
|
||||||
|
})();
|
||||||
|
}, [displayName, isAuthenticated, queryClient, user?.email]);
|
||||||
|
|
||||||
|
const complexSlug = currentComplexSlug || myComplexesQuery.data?.[0]?.complexSlug;
|
||||||
|
const currentComplexName = useMemo(() => {
|
||||||
|
const complexes = myComplexesQuery.data ?? [];
|
||||||
|
if (complexes.length === 0) return 'Mi complejo';
|
||||||
|
|
||||||
|
const selected = complexes.find((complex) => complex.complexSlug === complexSlug);
|
||||||
|
|
||||||
|
return selected?.complexName ?? complexes[0]?.complexName ?? 'Mi complejo';
|
||||||
|
}, [complexSlug, myComplexesQuery.data]);
|
||||||
|
|
||||||
const menuItems = [
|
const menuItems = [
|
||||||
{ label: "Inicio", to: "/" },
|
{ label: 'Inicio', to: '/' },
|
||||||
{ label: "Reservas", to: "/booking" },
|
{ label: 'About', to: '/about' },
|
||||||
{ label: "Canchas", to: "/canchas" },
|
] as const;
|
||||||
{ label: "Dashboard", to: "/dashboard" },
|
|
||||||
{ label: "Contacto", to: "/contacto" },
|
const handleSelectComplex = async (complexId: string, nextSlug: string) => {
|
||||||
]
|
await apiClient.complexes.select({ complexId });
|
||||||
|
setCurrentComplex(nextSlug);
|
||||||
|
await queryClient.invalidateQueries({ queryKey: ['current-complex'] });
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSignOut = async () => {
|
||||||
|
await signOut();
|
||||||
|
await navigate({ to: '/login' });
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleOpenBookingCreate = async () => {
|
||||||
|
if (location.pathname !== '/') {
|
||||||
|
await navigate({ to: '/' });
|
||||||
|
}
|
||||||
|
|
||||||
|
window.setTimeout(() => {
|
||||||
|
window.dispatchEvent(new Event('playzer:open-booking-create'));
|
||||||
|
}, 0);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="sticky top-0 z-50 w-full border-b border-border/60 bg-background/60 dark:border-primary/20 dark:bg-[#030a10]/90 backdrop-blur-xl">
|
<header className="sticky top-0 z-50 w-full border-b border-border/60 bg-background/60 dark:border-primary/20 dark:bg-[#030a10]/90 backdrop-blur-xl">
|
||||||
@@ -87,66 +163,147 @@ export function Header() {
|
|||||||
<div className="flex-1" />
|
<div className="flex-1" />
|
||||||
|
|
||||||
<div className="hidden items-center gap-2 md:flex">
|
<div className="hidden items-center gap-2 md:flex">
|
||||||
<Button className="rounded-2xl px-5 shadow-lg shadow-primary/20">
|
<Button
|
||||||
|
className="rounded-2xl px-5 shadow-lg shadow-primary/20"
|
||||||
|
onClick={() => {
|
||||||
|
void handleOpenBookingCreate();
|
||||||
|
}}
|
||||||
|
>
|
||||||
<CalendarDays className="mr-2 size-4" />
|
<CalendarDays className="mr-2 size-4" />
|
||||||
Reservar ahora
|
Reservar ahora
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<DropdownMenu>
|
{isAuthenticated ? (
|
||||||
<DropdownMenuTrigger asChild>
|
<DropdownMenu>
|
||||||
<button className="hidden size-10 rounded-full ring-2 ring-transparent transition-all duration-200 hover:ring-primary/30 focus:outline-none md:flex">
|
<DropdownMenuTrigger asChild>
|
||||||
<Avatar className="size-10 border border-border/60 shadow-lg shadow-black/10">
|
<button
|
||||||
<AvatarImage src={avatarUrl!} alt="Usuario" />
|
type="button"
|
||||||
<AvatarFallback className="bg-primary/15 text-primary">
|
className="hidden size-10 rounded-full ring-2 ring-transparent transition-all duration-200 hover:ring-primary/30 focus:outline-none md:flex"
|
||||||
JD
|
>
|
||||||
</AvatarFallback>
|
<UserAvatar
|
||||||
</Avatar>
|
src={avatarUrl}
|
||||||
</button>
|
alt={displayName}
|
||||||
</DropdownMenuTrigger>
|
fallbackText={displayName}
|
||||||
|
className="size-10 border border-border/60 shadow-lg shadow-black/10"
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
</DropdownMenuTrigger>
|
||||||
|
|
||||||
<DropdownMenuContent
|
<DropdownMenuContent
|
||||||
align="end"
|
align="end"
|
||||||
className="w-64 rounded-2xl border-border/60 bg-popover/95 p-2 shadow-xl shadow-black/20 backdrop-blur-xl"
|
className="w-64 rounded-2xl border-border/60 bg-popover/95 p-2 shadow-xl shadow-black/20 backdrop-blur-xl"
|
||||||
>
|
>
|
||||||
<DropdownMenuLabel className="px-2 py-2">
|
<DropdownMenuLabel className="px-2 py-2">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Avatar className="size-9">
|
<UserAvatar
|
||||||
<AvatarImage src={ avatarUrl ?? "https://github.com/shadcn.png"} alt="Usuario" />
|
src={avatarUrl}
|
||||||
<AvatarFallback className="bg-primary/15 text-primary">
|
alt={displayName}
|
||||||
JD
|
fallbackText={displayName}
|
||||||
</AvatarFallback>
|
className="size-9"
|
||||||
</Avatar>
|
/>
|
||||||
|
|
||||||
<div className="flex min-w-0 flex-col">
|
<div className="flex min-w-0 flex-col">
|
||||||
<span className="truncate text-sm font-medium">{displayName}</span>
|
<span className="truncate text-sm font-medium">{displayName}</span>
|
||||||
<span className="truncate text-xs text-muted-foreground">
|
<span className="truncate text-xs text-muted-foreground">{user?.email}</span>
|
||||||
{user?.email}
|
<span className="truncate text-xs text-muted-foreground">
|
||||||
</span>
|
{currentComplexName}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</DropdownMenuLabel>
|
||||||
</DropdownMenuLabel>
|
|
||||||
|
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
|
|
||||||
<DropdownMenuItem className="cursor-pointer rounded-xl">
|
{myComplexesQuery.data && myComplexesQuery.data.length > 1 && (
|
||||||
<User className="mr-2 size-4" />
|
<>
|
||||||
Mi Perfil
|
<DropdownMenuLabel className="px-2 text-xs font-normal text-muted-foreground">
|
||||||
</DropdownMenuItem>
|
Cambiar complejo
|
||||||
|
</DropdownMenuLabel>
|
||||||
|
{myComplexesQuery.data.map((complex) => (
|
||||||
|
<DropdownMenuItem
|
||||||
|
key={complex.id}
|
||||||
|
className="cursor-pointer rounded-xl"
|
||||||
|
onSelect={() => {
|
||||||
|
void handleSelectComplex(complex.id, complex.complexSlug);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span className="mr-2 flex size-4 items-center justify-center">
|
||||||
|
{complex.complexSlug === complexSlug && <Check className="size-4" />}
|
||||||
|
</span>
|
||||||
|
{complex.complexName}
|
||||||
|
</DropdownMenuItem>
|
||||||
|
))}
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
<DropdownMenuItem className="cursor-pointer rounded-xl">
|
<DropdownMenuLabel className="px-2 text-xs font-normal text-muted-foreground">
|
||||||
<Settings className="mr-2 size-4" />
|
Apariencia
|
||||||
Configuración
|
</DropdownMenuLabel>
|
||||||
</DropdownMenuItem>
|
<DropdownMenuRadioGroup
|
||||||
|
value={theme}
|
||||||
|
onValueChange={(value) => setTheme(value as 'light' | 'dark' | 'system')}
|
||||||
|
>
|
||||||
|
<DropdownMenuRadioItem value="light" className="cursor-pointer rounded-xl">
|
||||||
|
<Sun className="mr-2 size-4" />
|
||||||
|
Light
|
||||||
|
</DropdownMenuRadioItem>
|
||||||
|
<DropdownMenuRadioItem value="dark" className="cursor-pointer rounded-xl">
|
||||||
|
<Moon className="mr-2 size-4" />
|
||||||
|
Dark
|
||||||
|
</DropdownMenuRadioItem>
|
||||||
|
<DropdownMenuRadioItem value="system" className="cursor-pointer rounded-xl">
|
||||||
|
<Laptop className="mr-2 size-4" />
|
||||||
|
System
|
||||||
|
</DropdownMenuRadioItem>
|
||||||
|
</DropdownMenuRadioGroup>
|
||||||
|
|
||||||
<DropdownMenuSeparator />
|
<DropdownMenuSeparator />
|
||||||
|
|
||||||
<DropdownMenuItem className="cursor-pointer rounded-xl text-destructive focus:bg-destructive/10 focus:text-destructive">
|
<DropdownMenuItem
|
||||||
<LogOut className="mr-2 size-4" />
|
className="cursor-pointer rounded-xl"
|
||||||
Cerrar sesión
|
onSelect={() => {
|
||||||
</DropdownMenuItem>
|
void navigate({ to: '/profile' });
|
||||||
</DropdownMenuContent>
|
}}
|
||||||
</DropdownMenu>
|
>
|
||||||
|
<User className="mr-2 size-4" />
|
||||||
|
Mi Perfil
|
||||||
|
</DropdownMenuItem>
|
||||||
|
|
||||||
|
{currentComplexSlug && (
|
||||||
|
<DropdownMenuItem
|
||||||
|
className="cursor-pointer rounded-xl"
|
||||||
|
onSelect={() => {
|
||||||
|
void navigate({
|
||||||
|
to: '/complex/$slug/edit',
|
||||||
|
params: { slug: currentComplexSlug },
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Settings className="mr-2 size-4" />
|
||||||
|
Configuración
|
||||||
|
</DropdownMenuItem>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<DropdownMenuSeparator />
|
||||||
|
|
||||||
|
<DropdownMenuItem
|
||||||
|
className="cursor-pointer rounded-xl text-destructive focus:bg-destructive/10 focus:text-destructive"
|
||||||
|
onSelect={() => {
|
||||||
|
void handleSignOut();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<LogOut className="mr-2 size-4" />
|
||||||
|
Cerrar sesión
|
||||||
|
</DropdownMenuItem>
|
||||||
|
</DropdownMenuContent>
|
||||||
|
</DropdownMenu>
|
||||||
|
) : (
|
||||||
|
<Button asChild size="sm" variant="outline" className="hidden rounded-2xl md:inline-flex">
|
||||||
|
<Link to="/login">Login</Link>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
<Sheet open={open} onOpenChange={setOpen}>
|
<Sheet open={open} onOpenChange={setOpen}>
|
||||||
<SheetTrigger asChild>
|
<SheetTrigger asChild>
|
||||||
@@ -162,18 +319,19 @@ export function Header() {
|
|||||||
<div className="mt-6 flex flex-col gap-6">
|
<div className="mt-6 flex flex-col gap-6">
|
||||||
<div className="rounded-3xl border border-border/60 bg-card/70 p-4 shadow-xl shadow-black/10">
|
<div className="rounded-3xl border border-border/60 bg-card/70 p-4 shadow-xl shadow-black/10">
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<Avatar className="size-11">
|
<UserAvatar
|
||||||
<AvatarImage src="https://github.com/shadcn.png" alt="Usuario" />
|
src={avatarUrl}
|
||||||
<AvatarFallback className="bg-primary/15 text-primary">
|
alt={displayName}
|
||||||
JD
|
fallbackText={displayName}
|
||||||
</AvatarFallback>
|
className="size-11"
|
||||||
</Avatar>
|
/>
|
||||||
|
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<p className="truncate text-sm font-medium">John Doe</p>
|
<p className="truncate text-sm font-medium">{displayName}</p>
|
||||||
<p className="truncate text-xs text-muted-foreground">
|
<p className="truncate text-xs text-muted-foreground">{user?.email}</p>
|
||||||
john@example.com
|
{isAuthenticated && (
|
||||||
</p>
|
<p className="truncate text-xs text-muted-foreground">{currentComplexName}</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -192,44 +350,131 @@ export function Header() {
|
|||||||
|
|
||||||
<Button
|
<Button
|
||||||
className="rounded-2xl shadow-lg shadow-primary/20"
|
className="rounded-2xl shadow-lg shadow-primary/20"
|
||||||
onClick={() => setOpen(false)}
|
onClick={() => {
|
||||||
|
setOpen(false);
|
||||||
|
void handleOpenBookingCreate();
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<CalendarDays className="mr-2 size-4" />
|
<CalendarDays className="mr-2 size-4" />
|
||||||
Reservar ahora
|
Reservar ahora
|
||||||
</Button>
|
</Button>
|
||||||
|
|
||||||
<div className="border-t border-border/60 pt-4">
|
<div className="border-t border-border/60 pt-4">
|
||||||
<p className="mb-2 px-2 text-xs font-medium uppercase tracking-wider text-muted-foreground">
|
<div className="mb-2 flex items-center justify-between px-2">
|
||||||
Cuenta
|
<p className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
|
||||||
</p>
|
Cuenta
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
<nav className="flex flex-col gap-1">
|
<nav className="flex flex-col gap-1">
|
||||||
<Button
|
{!isAuthenticated && (
|
||||||
variant="ghost"
|
<Button
|
||||||
className="justify-start rounded-2xl"
|
variant="ghost"
|
||||||
onClick={() => setOpen(false)}
|
className="justify-start rounded-2xl"
|
||||||
>
|
onClick={() => {
|
||||||
<User className="mr-2 size-4" />
|
setOpen(false);
|
||||||
Mi Perfil
|
void navigate({ to: '/login' });
|
||||||
</Button>
|
}}
|
||||||
|
>
|
||||||
|
Login
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
<Button
|
<div className="py-1">
|
||||||
variant="ghost"
|
<p className="px-3 py-1 text-xs text-muted-foreground">Apariencia</p>
|
||||||
className="justify-start rounded-2xl"
|
{[
|
||||||
onClick={() => setOpen(false)}
|
{ value: 'light', label: 'Light', icon: Sun },
|
||||||
>
|
{ value: 'dark', label: 'Dark', icon: Moon },
|
||||||
<Settings className="mr-2 size-4" />
|
{ value: 'system', label: 'System', icon: Laptop },
|
||||||
Configuración
|
].map((item) => {
|
||||||
</Button>
|
const Icon = item.icon;
|
||||||
|
|
||||||
<Button
|
return (
|
||||||
variant="ghost"
|
<Button
|
||||||
className="justify-start rounded-2xl text-destructive hover:bg-destructive/10 hover:text-destructive"
|
key={item.value}
|
||||||
onClick={() => setOpen(false)}
|
variant="ghost"
|
||||||
>
|
className="w-full justify-start rounded-2xl"
|
||||||
<LogOut className="mr-2 size-4" />
|
onClick={() => setTheme(item.value as 'light' | 'dark' | 'system')}
|
||||||
Cerrar sesión
|
>
|
||||||
</Button>
|
<span className="mr-2 flex size-4 items-center justify-center">
|
||||||
|
{theme === item.value ? (
|
||||||
|
<Check className="size-4" />
|
||||||
|
) : (
|
||||||
|
<Icon className="size-4" />
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
{item.label}
|
||||||
|
</Button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{myComplexesQuery.data && myComplexesQuery.data.length > 1 && (
|
||||||
|
<div className="py-1">
|
||||||
|
<p className="px-3 py-1 text-xs text-muted-foreground">Cambiar complejo</p>
|
||||||
|
{myComplexesQuery.data.map((complex) => (
|
||||||
|
<Button
|
||||||
|
key={complex.id}
|
||||||
|
variant="ghost"
|
||||||
|
className="w-full justify-start rounded-2xl"
|
||||||
|
onClick={() => {
|
||||||
|
setOpen(false);
|
||||||
|
void handleSelectComplex(complex.id, complex.complexSlug);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span className="mr-2 flex size-4 items-center justify-center">
|
||||||
|
{complex.complexSlug === complexSlug && <Check className="size-4" />}
|
||||||
|
</span>
|
||||||
|
{complex.complexName}
|
||||||
|
</Button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isAuthenticated && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
className="justify-start rounded-2xl"
|
||||||
|
onClick={() => {
|
||||||
|
setOpen(false);
|
||||||
|
void navigate({ to: '/profile' });
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<User className="mr-2 size-4" />
|
||||||
|
Mi Perfil
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{currentComplexSlug && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
className="justify-start rounded-2xl"
|
||||||
|
onClick={() => {
|
||||||
|
setOpen(false);
|
||||||
|
void navigate({
|
||||||
|
to: '/complex/$slug/edit',
|
||||||
|
params: { slug: currentComplexSlug },
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Settings className="mr-2 size-4" />
|
||||||
|
Configuración
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isAuthenticated && (
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
className="justify-start rounded-2xl text-destructive hover:bg-destructive/10 hover:text-destructive"
|
||||||
|
onClick={() => {
|
||||||
|
setOpen(false);
|
||||||
|
void handleSignOut();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<LogOut className="mr-2 size-4" />
|
||||||
|
Cerrar sesión
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -239,5 +484,5 @@ export function Header() {
|
|||||||
|
|
||||||
<div className="h-px bg-gradient-to-r from-transparent via-primary/40 to-transparent" />
|
<div className="h-px bg-gradient-to-r from-transparent via-primary/40 to-transparent" />
|
||||||
</header>
|
</header>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import type { ReactNode } from "react"
|
import type { ReactNode } from 'react';
|
||||||
import { Header } from "./header"
|
import { Header } from './header';
|
||||||
|
|
||||||
interface LayoutProps {
|
interface LayoutProps {
|
||||||
children: ReactNode
|
children: ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function Layout({ children }: LayoutProps) {
|
export function Layout({ children }: LayoutProps) {
|
||||||
@@ -14,7 +14,7 @@ export function Layout({ children }: LayoutProps) {
|
|||||||
{children}
|
{children}
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function Background() {
|
function Background() {
|
||||||
@@ -30,5 +30,5 @@ function Background() {
|
|||||||
|
|
||||||
<div className="absolute inset-0 bg-[radial-gradient(circle_at_center,transparent_0%,#09131c_78%)]" />
|
<div className="absolute inset-0 bg-[radial-gradient(circle_at_center,transparent_0%,#09131c_78%)]" />
|
||||||
</div>
|
</div>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,30 +1,24 @@
|
|||||||
import * as React from "react"
|
import { Dialog as SheetPrimitive } from 'radix-ui';
|
||||||
import { Dialog as SheetPrimitive } from "radix-ui"
|
import * as React from 'react';
|
||||||
|
|
||||||
import { cn } from "@/lib/utils"
|
import { Button } from '@/components/ui/button';
|
||||||
import { Button } from "@/components/ui/button"
|
import { cn } from '@/lib/utils';
|
||||||
import { XIcon } from "lucide-react"
|
import { XIcon } from 'lucide-react';
|
||||||
|
|
||||||
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
|
||||||
return <SheetPrimitive.Root data-slot="sheet" {...props} />
|
return <SheetPrimitive.Root data-slot="sheet" {...props} />;
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetTrigger({
|
function SheetTrigger({ ...props }: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
|
||||||
...props
|
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
|
||||||
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
|
|
||||||
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetClose({
|
function SheetClose({ ...props }: React.ComponentProps<typeof SheetPrimitive.Close>) {
|
||||||
...props
|
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
|
||||||
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
|
|
||||||
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetPortal({
|
function SheetPortal({ ...props }: React.ComponentProps<typeof SheetPrimitive.Portal>) {
|
||||||
...props
|
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
|
||||||
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
|
|
||||||
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetOverlay({
|
function SheetOverlay({
|
||||||
@@ -35,23 +29,23 @@ function SheetOverlay({
|
|||||||
<SheetPrimitive.Overlay
|
<SheetPrimitive.Overlay
|
||||||
data-slot="sheet-overlay"
|
data-slot="sheet-overlay"
|
||||||
className={cn(
|
className={cn(
|
||||||
"fixed inset-0 z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
|
'fixed inset-0 z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0',
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetContent({
|
function SheetContent({
|
||||||
className,
|
className,
|
||||||
children,
|
children,
|
||||||
side = "right",
|
side = 'right',
|
||||||
showCloseButton = true,
|
showCloseButton = true,
|
||||||
...props
|
...props
|
||||||
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
|
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
|
||||||
side?: "top" | "right" | "bottom" | "left"
|
side?: 'top' | 'right' | 'bottom' | 'left';
|
||||||
showCloseButton?: boolean
|
showCloseButton?: boolean;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<SheetPortal>
|
<SheetPortal>
|
||||||
@@ -60,7 +54,7 @@ function SheetContent({
|
|||||||
data-slot="sheet-content"
|
data-slot="sheet-content"
|
||||||
data-side={side}
|
data-side={side}
|
||||||
className={cn(
|
className={cn(
|
||||||
"fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-[side=bottom]:data-open:slide-in-from-bottom-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:animate-out data-closed:fade-out-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=right]:data-closed:slide-out-to-right-10 data-[side=top]:data-closed:slide-out-to-top-10",
|
'fixed z-50 flex flex-col gap-4 bg-popover bg-clip-padding text-sm text-popover-foreground shadow-lg transition duration-200 ease-in-out data-[side=bottom]:inset-x-0 data-[side=bottom]:bottom-0 data-[side=bottom]:h-auto data-[side=bottom]:border-t data-[side=left]:inset-y-0 data-[side=left]:left-0 data-[side=left]:h-full data-[side=left]:w-3/4 data-[side=left]:border-r data-[side=right]:inset-y-0 data-[side=right]:right-0 data-[side=right]:h-full data-[side=right]:w-3/4 data-[side=right]:border-l data-[side=top]:inset-x-0 data-[side=top]:top-0 data-[side=top]:h-auto data-[side=top]:border-b data-[side=left]:sm:max-w-sm data-[side=right]:sm:max-w-sm data-open:animate-in data-open:fade-in-0 data-[side=bottom]:data-open:slide-in-from-bottom-10 data-[side=left]:data-open:slide-in-from-left-10 data-[side=right]:data-open:slide-in-from-right-10 data-[side=top]:data-open:slide-in-from-top-10 data-closed:animate-out data-closed:fade-out-0 data-[side=bottom]:data-closed:slide-out-to-bottom-10 data-[side=left]:data-closed:slide-out-to-left-10 data-[side=right]:data-closed:slide-out-to-right-10 data-[side=top]:data-closed:slide-out-to-top-10',
|
||||||
className
|
className
|
||||||
)}
|
)}
|
||||||
{...props}
|
{...props}
|
||||||
@@ -68,56 +62,45 @@ function SheetContent({
|
|||||||
{children}
|
{children}
|
||||||
{showCloseButton && (
|
{showCloseButton && (
|
||||||
<SheetPrimitive.Close data-slot="sheet-close" asChild>
|
<SheetPrimitive.Close data-slot="sheet-close" asChild>
|
||||||
<Button
|
<Button variant="ghost" className="absolute top-3 right-3" size="icon-sm">
|
||||||
variant="ghost"
|
<XIcon />
|
||||||
className="absolute top-3 right-3"
|
|
||||||
size="icon-sm"
|
|
||||||
>
|
|
||||||
<XIcon
|
|
||||||
/>
|
|
||||||
<span className="sr-only">Close</span>
|
<span className="sr-only">Close</span>
|
||||||
</Button>
|
</Button>
|
||||||
</SheetPrimitive.Close>
|
</SheetPrimitive.Close>
|
||||||
)}
|
)}
|
||||||
</SheetPrimitive.Content>
|
</SheetPrimitive.Content>
|
||||||
</SheetPortal>
|
</SheetPortal>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
|
function SheetHeader({ className, ...props }: React.ComponentProps<'div'>) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="sheet-header"
|
data-slot="sheet-header"
|
||||||
className={cn("flex flex-col gap-0.5 p-4", className)}
|
className={cn('flex flex-col gap-0.5 p-4', className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
|
function SheetFooter({ className, ...props }: React.ComponentProps<'div'>) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
data-slot="sheet-footer"
|
data-slot="sheet-footer"
|
||||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
className={cn('mt-auto flex flex-col gap-2 p-4', className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetTitle({
|
function SheetTitle({ className, ...props }: React.ComponentProps<typeof SheetPrimitive.Title>) {
|
||||||
className,
|
|
||||||
...props
|
|
||||||
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
|
|
||||||
return (
|
return (
|
||||||
<SheetPrimitive.Title
|
<SheetPrimitive.Title
|
||||||
data-slot="sheet-title"
|
data-slot="sheet-title"
|
||||||
className={cn(
|
className={cn('font-heading text-base font-medium text-foreground', className)}
|
||||||
"font-heading text-base font-medium text-foreground",
|
|
||||||
className
|
|
||||||
)}
|
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function SheetDescription({
|
function SheetDescription({
|
||||||
@@ -127,10 +110,10 @@ function SheetDescription({
|
|||||||
return (
|
return (
|
||||||
<SheetPrimitive.Description
|
<SheetPrimitive.Description
|
||||||
data-slot="sheet-description"
|
data-slot="sheet-description"
|
||||||
className={cn("text-sm text-muted-foreground", className)}
|
className={cn('text-sm text-muted-foreground', className)}
|
||||||
{...props}
|
{...props}
|
||||||
/>
|
/>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export {
|
export {
|
||||||
@@ -142,4 +125,4 @@ export {
|
|||||||
SheetFooter,
|
SheetFooter,
|
||||||
SheetTitle,
|
SheetTitle,
|
||||||
SheetDescription,
|
SheetDescription,
|
||||||
}
|
};
|
||||||
|
|||||||
472
apps/frontend/src/features/booking/booking-provider.tsx
Normal file
472
apps/frontend/src/features/booking/booking-provider.tsx
Normal file
@@ -0,0 +1,472 @@
|
|||||||
|
import { ApiClientError, apiClient } from '@/lib/api-client';
|
||||||
|
import type { AdminBooking, ComplexWithRole, Court } from '@repo/api-contract';
|
||||||
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
|
import {
|
||||||
|
type ReactNode,
|
||||||
|
createContext,
|
||||||
|
useCallback,
|
||||||
|
useContext,
|
||||||
|
useEffect,
|
||||||
|
useMemo,
|
||||||
|
useState,
|
||||||
|
} from 'react';
|
||||||
|
import type {
|
||||||
|
BookingCourtSchedule,
|
||||||
|
BookingSlotDraft,
|
||||||
|
BookingStatusFilter,
|
||||||
|
BookingSummary,
|
||||||
|
BookingTimeRange,
|
||||||
|
BookingTimelineSegment,
|
||||||
|
BookingViewMode,
|
||||||
|
} from './booking.types';
|
||||||
|
import {
|
||||||
|
addDaysIso,
|
||||||
|
formatBookingDate,
|
||||||
|
getDayOfWeek,
|
||||||
|
getNowTime,
|
||||||
|
isTodayIso,
|
||||||
|
minutesToTime,
|
||||||
|
timeToMinutes,
|
||||||
|
toIsoDateLocal,
|
||||||
|
} from './lib/booking-time';
|
||||||
|
|
||||||
|
interface BookingProviderProps {
|
||||||
|
children: ReactNode;
|
||||||
|
complex: ComplexWithRole;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CreateManualBookingPayload {
|
||||||
|
courtId: string;
|
||||||
|
date: string;
|
||||||
|
startTime: string;
|
||||||
|
customerName: string;
|
||||||
|
customerPhone: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BookingContextValue {
|
||||||
|
complex: ComplexWithRole;
|
||||||
|
courts: Court[];
|
||||||
|
bookings: AdminBooking[];
|
||||||
|
schedules: BookingCourtSchedule[];
|
||||||
|
selectedDate: string;
|
||||||
|
selectedSportId: string;
|
||||||
|
selectedStatus: BookingStatusFilter;
|
||||||
|
viewMode: BookingViewMode;
|
||||||
|
visibleTimeRange: BookingTimeRange;
|
||||||
|
timelineHours: string[];
|
||||||
|
summary: BookingSummary;
|
||||||
|
currentTime: string | null;
|
||||||
|
selectedSlot: BookingSlotDraft | null;
|
||||||
|
isLoading: boolean;
|
||||||
|
isError: boolean;
|
||||||
|
errorMessage: string | null;
|
||||||
|
isCreateBookingOpen: boolean;
|
||||||
|
createBookingError: string | null;
|
||||||
|
isCreatingBooking: boolean;
|
||||||
|
setSelectedDate: (date: string) => void;
|
||||||
|
moveSelectedDate: (amount: number) => void;
|
||||||
|
setSelectedSportId: (sportId: string) => void;
|
||||||
|
setSelectedStatus: (status: BookingStatusFilter) => void;
|
||||||
|
setViewMode: (mode: BookingViewMode) => void;
|
||||||
|
setVisibleTimeRange: (range: BookingTimeRange) => void;
|
||||||
|
openCreateBooking: (draft?: Partial<BookingSlotDraft>) => void;
|
||||||
|
closeCreateBooking: () => void;
|
||||||
|
createBooking: (payload: CreateManualBookingPayload) => Promise<void>;
|
||||||
|
updateBookingStatus: (bookingId: string, status: 'CANCELLED' | 'COMPLETED') => void;
|
||||||
|
exportDayReport: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const BookingContext = createContext<BookingContextValue | null>(null);
|
||||||
|
|
||||||
|
const DEFAULT_TIME_RANGE: BookingTimeRange = {
|
||||||
|
start: '08:00',
|
||||||
|
end: '22:00',
|
||||||
|
};
|
||||||
|
|
||||||
|
function extractMessage(error: unknown, fallback: string) {
|
||||||
|
if (error instanceof ApiClientError) {
|
||||||
|
return error.message || fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error instanceof Error) {
|
||||||
|
return error.message || fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeTimelineHours(range: BookingTimeRange) {
|
||||||
|
const start = timeToMinutes(range.start);
|
||||||
|
const end = timeToMinutes(range.end);
|
||||||
|
const hours: string[] = [];
|
||||||
|
|
||||||
|
for (let minute = start; minute <= end; minute += 60) {
|
||||||
|
hours.push(minutesToTime(minute));
|
||||||
|
}
|
||||||
|
|
||||||
|
return hours;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isActiveBooking(booking: AdminBooking) {
|
||||||
|
return booking.status === 'CONFIRMED' || booking.status === 'COMPLETED';
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCourtBookings(court: Court, bookings: AdminBooking[], selectedDate: string) {
|
||||||
|
return bookings
|
||||||
|
.filter(
|
||||||
|
(booking) =>
|
||||||
|
booking.courtId === court.id && booking.date === selectedDate && isActiveBooking(booking)
|
||||||
|
)
|
||||||
|
.sort((a, b) => timeToMinutes(a.startTime) - timeToMinutes(b.startTime));
|
||||||
|
}
|
||||||
|
|
||||||
|
function overlapsBooking(start: number, end: number, booking: AdminBooking) {
|
||||||
|
const bookingStart = timeToMinutes(booking.startTime);
|
||||||
|
const bookingEnd = timeToMinutes(booking.endTime);
|
||||||
|
|
||||||
|
return start < bookingEnd && end > bookingStart;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildSegmentsForCourt(
|
||||||
|
court: Court,
|
||||||
|
bookings: AdminBooking[],
|
||||||
|
selectedDate: string,
|
||||||
|
visibleRange: BookingTimeRange
|
||||||
|
) {
|
||||||
|
const dayOfWeek = getDayOfWeek(selectedDate);
|
||||||
|
const rangeStart = timeToMinutes(visibleRange.start);
|
||||||
|
const rangeEnd = timeToMinutes(visibleRange.end);
|
||||||
|
const courtBookings = getCourtBookings(court, bookings, selectedDate);
|
||||||
|
const segments: BookingTimelineSegment[] = [];
|
||||||
|
const slotDuration = court.slotDurationMinutes;
|
||||||
|
|
||||||
|
const availabilityRanges = court.availability
|
||||||
|
.filter((range) => range.dayOfWeek === dayOfWeek)
|
||||||
|
.map((range) => ({
|
||||||
|
start: Math.max(timeToMinutes(range.startTime), rangeStart),
|
||||||
|
end: Math.min(timeToMinutes(range.endTime), rangeEnd),
|
||||||
|
}))
|
||||||
|
.filter((range) => range.start < range.end)
|
||||||
|
.sort((a, b) => a.start - b.start);
|
||||||
|
|
||||||
|
for (const booking of courtBookings) {
|
||||||
|
const bookingStart = timeToMinutes(booking.startTime);
|
||||||
|
const bookingEnd = timeToMinutes(booking.endTime);
|
||||||
|
|
||||||
|
if (bookingEnd > rangeStart && bookingStart < rangeEnd) {
|
||||||
|
segments.push({
|
||||||
|
id: booking.id,
|
||||||
|
courtId: court.id,
|
||||||
|
status: 'reserved',
|
||||||
|
startTime: booking.startTime,
|
||||||
|
endTime: booking.endTime,
|
||||||
|
startMinutes: Math.max(bookingStart, rangeStart),
|
||||||
|
endMinutes: Math.min(bookingEnd, rangeEnd),
|
||||||
|
booking,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const availability of availabilityRanges) {
|
||||||
|
for (
|
||||||
|
let slotStart = availability.start;
|
||||||
|
slotStart + slotDuration <= availability.end;
|
||||||
|
slotStart += slotDuration
|
||||||
|
) {
|
||||||
|
const slotEnd = slotStart + slotDuration;
|
||||||
|
const isBooked = courtBookings.some((booking) =>
|
||||||
|
overlapsBooking(slotStart, slotEnd, booking)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (isBooked) continue;
|
||||||
|
|
||||||
|
const slotStartTime = minutesToTime(slotStart);
|
||||||
|
const slotEndTime = minutesToTime(slotEnd);
|
||||||
|
|
||||||
|
segments.push({
|
||||||
|
id: `${court.id}-free-${slotStartTime}-${slotEndTime}`,
|
||||||
|
courtId: court.id,
|
||||||
|
status: 'free',
|
||||||
|
startTime: slotStartTime,
|
||||||
|
endTime: slotEndTime,
|
||||||
|
startMinutes: slotStart,
|
||||||
|
endMinutes: slotEnd,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
segments.sort((a, b) => a.startMinutes - b.startMinutes);
|
||||||
|
|
||||||
|
return segments;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSummary(schedules: BookingCourtSchedule[]): BookingSummary {
|
||||||
|
const freeSlots = schedules.reduce((total, schedule) => total + schedule.metrics.free, 0);
|
||||||
|
const reservedSlots = schedules.reduce((total, schedule) => total + schedule.metrics.reserved, 0);
|
||||||
|
const maintenanceSlots = schedules.reduce(
|
||||||
|
(total, schedule) => total + schedule.metrics.maintenance,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
const totalSegments = freeSlots + reservedSlots + maintenanceSlots || 1;
|
||||||
|
|
||||||
|
return {
|
||||||
|
totalReservations: reservedSlots + maintenanceSlots + freeSlots,
|
||||||
|
freeSlots,
|
||||||
|
reservedSlots,
|
||||||
|
maintenanceSlots,
|
||||||
|
freePercent: Math.round((freeSlots / totalSegments) * 100),
|
||||||
|
reservedPercent: Math.round((reservedSlots / totalSegments) * 100),
|
||||||
|
maintenancePercent: Math.round((maintenanceSlots / totalSegments) * 100),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BookingProvider({ children, complex }: BookingProviderProps) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const todayIso = useMemo(() => toIsoDateLocal(new Date()), []);
|
||||||
|
const [selectedDate, setSelectedDate] = useState(todayIso);
|
||||||
|
const [selectedSportId, setSelectedSportId] = useState('all');
|
||||||
|
const [selectedStatus, setSelectedStatus] = useState<BookingStatusFilter>('all');
|
||||||
|
const [viewMode, setViewMode] = useState<BookingViewMode>('panel');
|
||||||
|
const [visibleTimeRange, setVisibleTimeRange] = useState(DEFAULT_TIME_RANGE);
|
||||||
|
const [selectedSlot, setSelectedSlot] = useState<BookingSlotDraft | null>(null);
|
||||||
|
const [isCreateBookingOpen, setIsCreateBookingOpen] = useState(false);
|
||||||
|
|
||||||
|
const courtsQuery = useQuery({
|
||||||
|
queryKey: ['courts', complex.id],
|
||||||
|
queryFn: () => apiClient.courts.listByComplex(complex.id),
|
||||||
|
});
|
||||||
|
|
||||||
|
const bookingsQuery = useQuery({
|
||||||
|
queryKey: ['admin-bookings', complex.id, selectedDate],
|
||||||
|
queryFn: () =>
|
||||||
|
apiClient.adminBookings.listByComplex(complex.id, {
|
||||||
|
fromDate: selectedDate,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const bookings = useMemo(
|
||||||
|
() => (bookingsQuery.data?.bookings ?? []).filter((booking) => booking.date === selectedDate),
|
||||||
|
[bookingsQuery.data?.bookings, selectedDate]
|
||||||
|
);
|
||||||
|
|
||||||
|
const courts = useMemo(() => courtsQuery.data ?? [], [courtsQuery.data]);
|
||||||
|
|
||||||
|
const filteredCourts = useMemo(() => {
|
||||||
|
if (selectedSportId === 'all') return courts;
|
||||||
|
return courts.filter((court) => court.sportId === selectedSportId);
|
||||||
|
}, [courts, selectedSportId]);
|
||||||
|
|
||||||
|
const schedules = useMemo<BookingCourtSchedule[]>(() => {
|
||||||
|
return filteredCourts
|
||||||
|
.map((court) => {
|
||||||
|
const segments = buildSegmentsForCourt(court, bookings, selectedDate, visibleTimeRange);
|
||||||
|
const metrics = {
|
||||||
|
free: segments.filter((segment) => segment.status === 'free').length,
|
||||||
|
reserved: segments.filter((segment) => segment.status === 'reserved').length,
|
||||||
|
maintenance: segments.filter((segment) => segment.status === 'maintenance').length,
|
||||||
|
};
|
||||||
|
|
||||||
|
return { court, segments, metrics };
|
||||||
|
})
|
||||||
|
.filter((schedule) => {
|
||||||
|
if (selectedStatus === 'all') return true;
|
||||||
|
return schedule.segments.some((segment) => segment.status === selectedStatus);
|
||||||
|
});
|
||||||
|
}, [bookings, filteredCourts, selectedDate, selectedStatus, visibleTimeRange]);
|
||||||
|
|
||||||
|
const summary = useMemo(() => getSummary(schedules), [schedules]);
|
||||||
|
const timelineHours = useMemo(() => makeTimelineHours(visibleTimeRange), [visibleTimeRange]);
|
||||||
|
|
||||||
|
const currentTime = useMemo(() => {
|
||||||
|
if (!isTodayIso(selectedDate)) return null;
|
||||||
|
|
||||||
|
const now = getNowTime();
|
||||||
|
const nowMinutes = timeToMinutes(now);
|
||||||
|
const start = timeToMinutes(visibleTimeRange.start);
|
||||||
|
const end = timeToMinutes(visibleTimeRange.end);
|
||||||
|
|
||||||
|
if (nowMinutes < start || nowMinutes > end) return null;
|
||||||
|
return now;
|
||||||
|
}, [selectedDate, visibleTimeRange]);
|
||||||
|
|
||||||
|
const createBookingMutation = useMutation({
|
||||||
|
mutationFn: (payload: CreateManualBookingPayload) =>
|
||||||
|
apiClient.adminBookings.create(complex.id, {
|
||||||
|
date: payload.date,
|
||||||
|
courtId: payload.courtId,
|
||||||
|
startTime: payload.startTime,
|
||||||
|
customerName: payload.customerName,
|
||||||
|
customerPhone: payload.customerPhone,
|
||||||
|
}),
|
||||||
|
onSuccess: async () => {
|
||||||
|
await queryClient.invalidateQueries({ queryKey: ['admin-bookings', complex.id] });
|
||||||
|
await queryClient.invalidateQueries({ queryKey: ['manual-booking-availability'] });
|
||||||
|
setIsCreateBookingOpen(false);
|
||||||
|
setSelectedSlot(null);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateStatusMutation = useMutation({
|
||||||
|
mutationFn: (payload: { bookingId: string; status: 'CANCELLED' | 'COMPLETED' }) =>
|
||||||
|
apiClient.adminBookings.updateStatus(payload.bookingId, { status: payload.status }),
|
||||||
|
onSuccess: async () => {
|
||||||
|
await queryClient.invalidateQueries({ queryKey: ['admin-bookings', complex.id] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const openCreateBooking = useCallback(
|
||||||
|
(draft?: Partial<BookingSlotDraft>) => {
|
||||||
|
setSelectedSlot({
|
||||||
|
date: draft?.date ?? selectedDate,
|
||||||
|
courtId: draft?.courtId,
|
||||||
|
startTime: draft?.startTime,
|
||||||
|
sportId: draft?.sportId,
|
||||||
|
});
|
||||||
|
setIsCreateBookingOpen(true);
|
||||||
|
},
|
||||||
|
[selectedDate]
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleOpenCreateBooking = () => {
|
||||||
|
openCreateBooking();
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('playzer:open-booking-create', handleOpenCreateBooking);
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
window.removeEventListener('playzer:open-booking-create', handleOpenCreateBooking);
|
||||||
|
};
|
||||||
|
}, [openCreateBooking]);
|
||||||
|
|
||||||
|
const closeCreateBooking = useCallback(() => {
|
||||||
|
setIsCreateBookingOpen(false);
|
||||||
|
setSelectedSlot(null);
|
||||||
|
createBookingMutation.reset();
|
||||||
|
}, [createBookingMutation]);
|
||||||
|
|
||||||
|
const createBooking = useCallback(
|
||||||
|
async (payload: CreateManualBookingPayload) => {
|
||||||
|
await createBookingMutation.mutateAsync(payload);
|
||||||
|
},
|
||||||
|
[createBookingMutation]
|
||||||
|
);
|
||||||
|
|
||||||
|
const updateBookingStatus = useCallback(
|
||||||
|
(bookingId: string, status: 'CANCELLED' | 'COMPLETED') => {
|
||||||
|
updateStatusMutation.mutate({ bookingId, status });
|
||||||
|
},
|
||||||
|
[updateStatusMutation]
|
||||||
|
);
|
||||||
|
|
||||||
|
const exportDayReport = useCallback(() => {
|
||||||
|
const rows = [
|
||||||
|
['Fecha', 'Cancha', 'Deporte', 'Inicio', 'Fin', 'Cliente', 'Telefono', 'Estado'],
|
||||||
|
...bookings.map((booking) => [
|
||||||
|
booking.date,
|
||||||
|
booking.courtName,
|
||||||
|
booking.sport.name,
|
||||||
|
booking.startTime,
|
||||||
|
booking.endTime,
|
||||||
|
booking.customerName,
|
||||||
|
booking.customerPhone,
|
||||||
|
booking.status,
|
||||||
|
]),
|
||||||
|
];
|
||||||
|
const csv = rows.map((row) => row.map((cell) => `"${cell}"`).join(',')).join('\n');
|
||||||
|
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8' });
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = url;
|
||||||
|
link.download = `reservas-${complex.complexSlug}-${selectedDate}.csv`;
|
||||||
|
link.click();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}, [bookings, complex.complexSlug, selectedDate]);
|
||||||
|
|
||||||
|
const value = useMemo<BookingContextValue>(
|
||||||
|
() => ({
|
||||||
|
complex,
|
||||||
|
courts,
|
||||||
|
bookings,
|
||||||
|
schedules,
|
||||||
|
selectedDate,
|
||||||
|
selectedSportId,
|
||||||
|
selectedStatus,
|
||||||
|
viewMode,
|
||||||
|
visibleTimeRange,
|
||||||
|
timelineHours,
|
||||||
|
summary,
|
||||||
|
currentTime,
|
||||||
|
selectedSlot,
|
||||||
|
isLoading: courtsQuery.isLoading || bookingsQuery.isLoading,
|
||||||
|
isError: courtsQuery.isError || bookingsQuery.isError,
|
||||||
|
errorMessage:
|
||||||
|
courtsQuery.isError || bookingsQuery.isError
|
||||||
|
? extractMessage(
|
||||||
|
courtsQuery.error ?? bookingsQuery.error,
|
||||||
|
'No pudimos cargar el panel de reservas.'
|
||||||
|
)
|
||||||
|
: null,
|
||||||
|
isCreateBookingOpen,
|
||||||
|
createBookingError: createBookingMutation.isError
|
||||||
|
? extractMessage(createBookingMutation.error, 'No pudimos crear la reserva.')
|
||||||
|
: null,
|
||||||
|
isCreatingBooking: createBookingMutation.isPending,
|
||||||
|
setSelectedDate,
|
||||||
|
moveSelectedDate: (amount) => setSelectedDate((date) => addDaysIso(date, amount)),
|
||||||
|
setSelectedSportId,
|
||||||
|
setSelectedStatus,
|
||||||
|
setViewMode,
|
||||||
|
setVisibleTimeRange,
|
||||||
|
openCreateBooking,
|
||||||
|
closeCreateBooking,
|
||||||
|
createBooking,
|
||||||
|
updateBookingStatus,
|
||||||
|
exportDayReport,
|
||||||
|
}),
|
||||||
|
[
|
||||||
|
bookings,
|
||||||
|
bookingsQuery.error,
|
||||||
|
bookingsQuery.isError,
|
||||||
|
bookingsQuery.isLoading,
|
||||||
|
closeCreateBooking,
|
||||||
|
complex,
|
||||||
|
courts,
|
||||||
|
courtsQuery.error,
|
||||||
|
courtsQuery.isError,
|
||||||
|
courtsQuery.isLoading,
|
||||||
|
createBooking,
|
||||||
|
createBookingMutation.error,
|
||||||
|
createBookingMutation.isError,
|
||||||
|
createBookingMutation.isPending,
|
||||||
|
currentTime,
|
||||||
|
exportDayReport,
|
||||||
|
isCreateBookingOpen,
|
||||||
|
openCreateBooking,
|
||||||
|
schedules,
|
||||||
|
selectedDate,
|
||||||
|
selectedSlot,
|
||||||
|
selectedSportId,
|
||||||
|
selectedStatus,
|
||||||
|
summary,
|
||||||
|
timelineHours,
|
||||||
|
updateBookingStatus,
|
||||||
|
viewMode,
|
||||||
|
visibleTimeRange,
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
return <BookingContext.Provider value={value}>{children}</BookingContext.Provider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useBooking() {
|
||||||
|
const context = useContext(BookingContext);
|
||||||
|
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('useBooking must be used within BookingProvider');
|
||||||
|
}
|
||||||
|
|
||||||
|
return context;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { formatBookingDate };
|
||||||
28
apps/frontend/src/features/booking/booking.tsx
Normal file
28
apps/frontend/src/features/booking/booking.tsx
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import type { ComplexWithRole } from '@repo/api-contract';
|
||||||
|
import { BookingProvider } from './booking-provider';
|
||||||
|
import { BookingCreateDialog } from './components/booking-create-dialog';
|
||||||
|
import { BookingDaySummary, BookingQuickActions } from './components/booking-day-summary';
|
||||||
|
import { BookingHeader } from './components/booking-header';
|
||||||
|
import { BookingTimeline } from './components/booking-timeline';
|
||||||
|
import { BookingToolbar } from './components/booking-toolbar';
|
||||||
|
|
||||||
|
interface BookingProps {
|
||||||
|
complex: ComplexWithRole;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Booking({ complex }: BookingProps) {
|
||||||
|
return (
|
||||||
|
<BookingProvider complex={complex}>
|
||||||
|
<div className="flex flex-col gap-5">
|
||||||
|
<BookingHeader />
|
||||||
|
<BookingToolbar />
|
||||||
|
<BookingTimeline />
|
||||||
|
<div className="grid gap-5 xl:grid-cols-4">
|
||||||
|
<BookingDaySummary />
|
||||||
|
<BookingQuickActions />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<BookingCreateDialog />
|
||||||
|
</BookingProvider>
|
||||||
|
);
|
||||||
|
}
|
||||||
50
apps/frontend/src/features/booking/booking.types.ts
Normal file
50
apps/frontend/src/features/booking/booking.types.ts
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
import type { AdminBooking, Court } from '@repo/api-contract';
|
||||||
|
|
||||||
|
export type BookingViewMode = 'panel' | 'status';
|
||||||
|
export type BookingStatusFilter = 'all' | 'free' | 'reserved' | 'maintenance';
|
||||||
|
export type BookingSegmentStatus = 'free' | 'reserved' | 'maintenance';
|
||||||
|
|
||||||
|
export interface BookingTimeRange {
|
||||||
|
start: string;
|
||||||
|
end: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookingSummary {
|
||||||
|
totalReservations: number;
|
||||||
|
freeSlots: number;
|
||||||
|
reservedSlots: number;
|
||||||
|
maintenanceSlots: number;
|
||||||
|
freePercent: number;
|
||||||
|
reservedPercent: number;
|
||||||
|
maintenancePercent: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookingCourtMetrics {
|
||||||
|
free: number;
|
||||||
|
reserved: number;
|
||||||
|
maintenance: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookingTimelineSegment {
|
||||||
|
id: string;
|
||||||
|
courtId: string;
|
||||||
|
status: BookingSegmentStatus;
|
||||||
|
startTime: string;
|
||||||
|
endTime: string;
|
||||||
|
startMinutes: number;
|
||||||
|
endMinutes: number;
|
||||||
|
booking?: AdminBooking;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookingCourtSchedule {
|
||||||
|
court: Court;
|
||||||
|
segments: BookingTimelineSegment[];
|
||||||
|
metrics: BookingCourtMetrics;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BookingSlotDraft {
|
||||||
|
courtId?: string;
|
||||||
|
date: string;
|
||||||
|
startTime?: string;
|
||||||
|
sportId?: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,285 @@
|
|||||||
|
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,
|
||||||
|
} from '@/components/ui/responsive-dialog';
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from '@/components/ui/select';
|
||||||
|
import { zodResolver } from '@hookform/resolvers/zod';
|
||||||
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
|
import { useForm } from 'react-hook-form';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import { useBooking } from '../booking-provider';
|
||||||
|
import {
|
||||||
|
fromIsoDateLocal,
|
||||||
|
getDayOfWeek,
|
||||||
|
minutesToTime,
|
||||||
|
timeToMinutes,
|
||||||
|
toIsoDateLocal,
|
||||||
|
} from '../lib/booking-time';
|
||||||
|
|
||||||
|
const bookingFormSchema = 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 BookingForm = z.infer<typeof bookingFormSchema>;
|
||||||
|
|
||||||
|
export function BookingCreateDialog() {
|
||||||
|
const {
|
||||||
|
courts,
|
||||||
|
bookings,
|
||||||
|
selectedDate,
|
||||||
|
selectedSlot,
|
||||||
|
isCreateBookingOpen,
|
||||||
|
createBookingError,
|
||||||
|
isCreatingBooking,
|
||||||
|
closeCreateBooking,
|
||||||
|
createBooking,
|
||||||
|
} = useBooking();
|
||||||
|
|
||||||
|
const [date, setDate] = useState(selectedSlot?.date ?? selectedDate);
|
||||||
|
const [sportId, setSportId] = useState(selectedSlot?.sportId ?? 'all');
|
||||||
|
const [courtId, setCourtId] = useState(selectedSlot?.courtId ?? '');
|
||||||
|
const [startTime, setStartTime] = useState(selectedSlot?.startTime ?? '');
|
||||||
|
|
||||||
|
const {
|
||||||
|
register,
|
||||||
|
handleSubmit,
|
||||||
|
reset,
|
||||||
|
formState: { errors, isValid },
|
||||||
|
} = useForm<BookingForm>({
|
||||||
|
resolver: zodResolver(bookingFormSchema),
|
||||||
|
mode: 'onChange',
|
||||||
|
defaultValues: {
|
||||||
|
customerName: '',
|
||||||
|
customerPhone: '',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!isCreateBookingOpen) return;
|
||||||
|
|
||||||
|
setDate(selectedSlot?.date ?? selectedDate);
|
||||||
|
setSportId(selectedSlot?.sportId ?? 'all');
|
||||||
|
setCourtId(selectedSlot?.courtId ?? '');
|
||||||
|
setStartTime(selectedSlot?.startTime ?? '');
|
||||||
|
reset();
|
||||||
|
}, [isCreateBookingOpen, reset, selectedDate, selectedSlot]);
|
||||||
|
|
||||||
|
const sports = [...new Map(courts.map((court) => [court.sport.id, court.sport])).values()];
|
||||||
|
const filteredCourts = useMemo(() => {
|
||||||
|
if (sportId === 'all') return courts;
|
||||||
|
return courts.filter((court) => court.sportId === sportId);
|
||||||
|
}, [courts, sportId]);
|
||||||
|
const selectedCourt = courts.find((court) => court.id === courtId);
|
||||||
|
const availableStartTimes = useMemo(() => {
|
||||||
|
if (!selectedCourt) return [];
|
||||||
|
|
||||||
|
const times: string[] = [];
|
||||||
|
const dayOfWeek = getDayOfWeek(date);
|
||||||
|
const dayAvailability = selectedCourt.availability
|
||||||
|
.filter((range) => range.dayOfWeek === dayOfWeek)
|
||||||
|
.sort((a, b) => timeToMinutes(a.startTime) - timeToMinutes(b.startTime));
|
||||||
|
const courtBookings = bookings.filter(
|
||||||
|
(booking) =>
|
||||||
|
booking.date === date &&
|
||||||
|
booking.courtId === selectedCourt.id &&
|
||||||
|
booking.status !== 'CANCELLED'
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const range of dayAvailability) {
|
||||||
|
const start = timeToMinutes(range.startTime);
|
||||||
|
const end = timeToMinutes(range.endTime);
|
||||||
|
|
||||||
|
for (
|
||||||
|
let minute = start;
|
||||||
|
minute + selectedCourt.slotDurationMinutes <= end;
|
||||||
|
minute += selectedCourt.slotDurationMinutes
|
||||||
|
) {
|
||||||
|
const slotEnd = minute + selectedCourt.slotDurationMinutes;
|
||||||
|
const isBooked = courtBookings.some((booking) => {
|
||||||
|
const bookingStart = timeToMinutes(booking.startTime);
|
||||||
|
const bookingEnd = timeToMinutes(booking.endTime);
|
||||||
|
return minute < bookingEnd && slotEnd > bookingStart;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!isBooked) {
|
||||||
|
times.push(minutesToTime(minute));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return times;
|
||||||
|
}, [bookings, date, selectedCourt]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (startTime && !availableStartTimes.includes(startTime)) {
|
||||||
|
setStartTime('');
|
||||||
|
}
|
||||||
|
}, [availableStartTimes, startTime]);
|
||||||
|
|
||||||
|
const onSubmit = async (values: BookingForm) => {
|
||||||
|
await createBooking({
|
||||||
|
courtId,
|
||||||
|
date,
|
||||||
|
startTime,
|
||||||
|
customerName: values.customerName,
|
||||||
|
customerPhone: values.customerPhone,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<ResponsiveDialog
|
||||||
|
open={isCreateBookingOpen}
|
||||||
|
onOpenChange={(open) => !open && closeCreateBooking()}
|
||||||
|
>
|
||||||
|
<ResponsiveDialogContent
|
||||||
|
className="data-[variant=dialog]:max-w-lg"
|
||||||
|
onOpenAutoFocus={(event) => event.preventDefault()}
|
||||||
|
>
|
||||||
|
<ResponsiveDialogHeader>
|
||||||
|
<ResponsiveDialogTitle>Nueva reserva</ResponsiveDialogTitle>
|
||||||
|
<ResponsiveDialogDescription>
|
||||||
|
Crea un turno para atención telefónica o mostrador.
|
||||||
|
</ResponsiveDialogDescription>
|
||||||
|
</ResponsiveDialogHeader>
|
||||||
|
|
||||||
|
<form id="booking-create-form" className="grid gap-4" onSubmit={handleSubmit(onSubmit)}>
|
||||||
|
<div className="grid gap-3 md:grid-cols-2">
|
||||||
|
<Field>
|
||||||
|
<FieldLabel>Fecha</FieldLabel>
|
||||||
|
<DatePicker
|
||||||
|
value={fromIsoDateLocal(date)}
|
||||||
|
onChange={(nextDate) => {
|
||||||
|
setDate(nextDate ? toIsoDateLocal(nextDate) : selectedDate);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field>
|
||||||
|
<FieldLabel>Deporte</FieldLabel>
|
||||||
|
<Select
|
||||||
|
value={sportId}
|
||||||
|
onValueChange={(value) => {
|
||||||
|
setSportId(value);
|
||||||
|
setCourtId('');
|
||||||
|
setStartTime('');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="all">Todos</SelectItem>
|
||||||
|
{sports.map((sport) => (
|
||||||
|
<SelectItem key={sport.id} value={sport.id}>
|
||||||
|
{sport.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field>
|
||||||
|
<FieldLabel>Cancha</FieldLabel>
|
||||||
|
<Select
|
||||||
|
value={courtId}
|
||||||
|
onValueChange={(value) => {
|
||||||
|
setCourtId(value);
|
||||||
|
setStartTime('');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Selecciona una cancha" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{filteredCourts.map((court) => (
|
||||||
|
<SelectItem key={court.id} value={court.id}>
|
||||||
|
{court.name} · {court.sport.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field>
|
||||||
|
<FieldLabel>Horario</FieldLabel>
|
||||||
|
<Select value={startTime} onValueChange={setStartTime}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue placeholder="Selecciona un horario" />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{availableStartTimes.map((time) => (
|
||||||
|
<SelectItem key={time} value={time}>
|
||||||
|
{time}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
|
||||||
|
{createBookingError && <p className="text-sm text-destructive">{createBookingError}</p>}
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<ResponsiveDialogFooter>
|
||||||
|
<ResponsiveDialogClose asChild>
|
||||||
|
<Button variant="outline">Cancelar</Button>
|
||||||
|
</ResponsiveDialogClose>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
form="booking-create-form"
|
||||||
|
disabled={!isValid || isCreatingBooking || !courtId || !startTime}
|
||||||
|
>
|
||||||
|
{isCreatingBooking ? 'Guardando...' : 'Crear reserva'}
|
||||||
|
</Button>
|
||||||
|
</ResponsiveDialogFooter>
|
||||||
|
</ResponsiveDialogContent>
|
||||||
|
</ResponsiveDialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
import { CalendarDays, Download, Drill, ShieldCheck, UsersRound } from 'lucide-react';
|
||||||
|
import { useBooking } from '../booking-provider';
|
||||||
|
import { formatBookingDate, toIsoDateLocal } from '../lib/booking-time';
|
||||||
|
|
||||||
|
export function BookingDaySummary() {
|
||||||
|
const { selectedDate, summary } = useBooking();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="rounded-lg border bg-card/85 p-5 shadow-sm xl:col-span-3">
|
||||||
|
<div className="mb-4">
|
||||||
|
<h2 className="text-base font-semibold">Resumen del día</h2>
|
||||||
|
<p className="mt-1 text-sm capitalize text-muted-foreground">
|
||||||
|
{formatBookingDate(selectedDate, { year: 'numeric' })}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid gap-3 md:grid-cols-4">
|
||||||
|
<SummaryCard
|
||||||
|
label="Total de bloques"
|
||||||
|
value={summary.totalReservations}
|
||||||
|
icon={CalendarDays}
|
||||||
|
className="border-border bg-background/45"
|
||||||
|
/>
|
||||||
|
<SummaryCard
|
||||||
|
label="Libres"
|
||||||
|
value={summary.freeSlots}
|
||||||
|
detail={`${summary.freePercent}% del total`}
|
||||||
|
icon={UsersRound}
|
||||||
|
className="border-primary/30 bg-primary/10 text-primary"
|
||||||
|
/>
|
||||||
|
<SummaryCard
|
||||||
|
label="Reservados"
|
||||||
|
value={summary.reservedSlots}
|
||||||
|
detail={`${summary.reservedPercent}% del total`}
|
||||||
|
icon={ShieldCheck}
|
||||||
|
className="border-reserved/35 bg-reserved/10 text-reserved"
|
||||||
|
/>
|
||||||
|
<SummaryCard
|
||||||
|
label="Mantenimiento"
|
||||||
|
value={summary.maintenanceSlots}
|
||||||
|
detail={`${summary.maintenancePercent}% del total`}
|
||||||
|
icon={Drill}
|
||||||
|
className="border-maintenance/35 bg-maintenance/10 text-maintenance"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SummaryCardProps {
|
||||||
|
label: string;
|
||||||
|
value: number;
|
||||||
|
detail?: string;
|
||||||
|
icon: typeof CalendarDays;
|
||||||
|
className: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SummaryCard({ label, value, detail, icon: Icon, className }: SummaryCardProps) {
|
||||||
|
return (
|
||||||
|
<article className={`rounded-lg border p-4 ${className}`}>
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="flex size-10 shrink-0 items-center justify-center rounded-md bg-transparent">
|
||||||
|
<Icon className="size-5" />
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<p className="truncate text-sm text-muted-foreground">{label}</p>
|
||||||
|
<p className="text-2xl font-semibold leading-tight">{value}</p>
|
||||||
|
{detail && <p className="mt-1 truncate text-xs text-muted-foreground">{detail}</p>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BookingQuickActions() {
|
||||||
|
const { selectedDate, selectedStatus, setSelectedDate, setSelectedStatus, exportDayReport } =
|
||||||
|
useBooking();
|
||||||
|
const todayIso = toIsoDateLocal(new Date());
|
||||||
|
const isViewingTodayReservations = selectedDate === todayIso && selectedStatus === 'reserved';
|
||||||
|
const isViewingMaintenance = selectedStatus === 'maintenance';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="rounded-lg border bg-card/85 p-5 shadow-sm">
|
||||||
|
<h2 className="text-base font-semibold">Acciones rápidas</h2>
|
||||||
|
<div className="mt-3 grid gap-2">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
setSelectedDate(todayIso);
|
||||||
|
setSelectedStatus(isViewingTodayReservations ? 'all' : 'reserved');
|
||||||
|
}}
|
||||||
|
aria-pressed={isViewingTodayReservations}
|
||||||
|
className="flex h-10 items-center gap-3 rounded-md border bg-background/45 px-3 text-left text-sm transition-colors hover:bg-muted aria-pressed:border-reserved/50 aria-pressed:bg-reserved/10"
|
||||||
|
>
|
||||||
|
<CalendarDays className="size-4 text-muted-foreground" />
|
||||||
|
{isViewingTodayReservations ? 'Ver todos los estados' : 'Ver reservas de hoy'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setSelectedStatus(isViewingMaintenance ? 'all' : 'maintenance')}
|
||||||
|
aria-pressed={isViewingMaintenance}
|
||||||
|
className="flex h-10 items-center gap-3 rounded-md border bg-background/45 px-3 text-left text-sm transition-colors hover:bg-muted aria-pressed:border-maintenance/50 aria-pressed:bg-maintenance/10"
|
||||||
|
>
|
||||||
|
<Drill className="size-4 text-maintenance" />
|
||||||
|
{isViewingMaintenance ? 'Ver todos los estados' : 'Ver mantenimiento'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={exportDayReport}
|
||||||
|
className="flex h-10 items-center gap-3 rounded-md border bg-background/45 px-3 text-left text-sm transition-colors hover:bg-muted"
|
||||||
|
>
|
||||||
|
<Download className="size-4 text-primary" />
|
||||||
|
Exportar reporte
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
import { useBooking } from '../booking-provider';
|
||||||
|
|
||||||
|
export function BookingHeader() {
|
||||||
|
const { complex } = useBooking();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section>
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-semibold tracking-normal text-foreground">
|
||||||
|
Panel de Reservas
|
||||||
|
</h1>
|
||||||
|
<p className="mt-2 text-sm text-muted-foreground">
|
||||||
|
Gestiona las canchas de {complex.complexName}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
const items = [
|
||||||
|
{ label: 'Libre', className: 'bg-primary' },
|
||||||
|
{ label: 'Reservado', className: 'bg-reserved' },
|
||||||
|
{ label: 'Mantenimiento', className: 'bg-maintenance' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function BookingStatusLegend() {
|
||||||
|
return (
|
||||||
|
<div className="flex flex-wrap items-center gap-5 text-sm text-muted-foreground">
|
||||||
|
{items.map((item) => (
|
||||||
|
<span key={item.label} className="inline-flex items-center gap-2">
|
||||||
|
<span className={`size-3 rounded-full ${item.className}`} />
|
||||||
|
{item.label}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,299 @@
|
|||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
import { ChevronLeft, ChevronRight, Dumbbell, Plus, Users } from 'lucide-react';
|
||||||
|
import { useBooking } from '../booking-provider';
|
||||||
|
import type { BookingCourtSchedule, BookingTimelineSegment } from '../booking.types';
|
||||||
|
import { timeToMinutes } from '../lib/booking-time';
|
||||||
|
import { BookingStatusLegend } from './booking-status-legend';
|
||||||
|
|
||||||
|
const courtInfoWidth = 220;
|
||||||
|
const hourWidth = 104;
|
||||||
|
|
||||||
|
export function BookingTimeline() {
|
||||||
|
const {
|
||||||
|
schedules,
|
||||||
|
timelineHours,
|
||||||
|
visibleTimeRange,
|
||||||
|
currentTime,
|
||||||
|
isLoading,
|
||||||
|
isError,
|
||||||
|
errorMessage,
|
||||||
|
} = useBooking();
|
||||||
|
|
||||||
|
const rangeStart = timeToMinutes(visibleTimeRange.start);
|
||||||
|
const rangeEnd = timeToMinutes(visibleTimeRange.end);
|
||||||
|
const totalMinutes = rangeEnd - rangeStart;
|
||||||
|
const gridWidth = Math.max((timelineHours.length - 1) * hourWidth, 760);
|
||||||
|
const timelineMarks = timelineHours.map((hour) => ({
|
||||||
|
hour,
|
||||||
|
left: ((timeToMinutes(hour) - rangeStart) / totalMinutes) * 100,
|
||||||
|
}));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="overflow-hidden rounded-lg border bg-card/85 shadow-sm">
|
||||||
|
<div className="flex items-center justify-between gap-4 border-b px-4 py-4">
|
||||||
|
<BookingStatusLegend />
|
||||||
|
<div className="hidden items-center gap-2 md:flex">
|
||||||
|
<Button type="button" size="icon-sm" variant="ghost">
|
||||||
|
<ChevronLeft className="size-4" />
|
||||||
|
</Button>
|
||||||
|
<Button type="button" size="icon-sm" variant="ghost">
|
||||||
|
<ChevronRight className="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isLoading && (
|
||||||
|
<div className="px-4 py-10 text-sm text-muted-foreground">Cargando reservas...</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isError && !isLoading && (
|
||||||
|
<div className="px-4 py-10 text-sm text-destructive">{errorMessage}</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isLoading && !isError && schedules.length === 0 && (
|
||||||
|
<div className="px-4 py-10 text-sm text-muted-foreground">
|
||||||
|
No hay canchas para los filtros seleccionados.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!isLoading && !isError && schedules.length > 0 && (
|
||||||
|
<div className="booking-scrollbar overflow-x-auto overflow-y-hidden">
|
||||||
|
<div className="relative min-w-full" style={{ width: courtInfoWidth + gridWidth }}>
|
||||||
|
<TimelineHeader
|
||||||
|
timelineMarks={timelineMarks}
|
||||||
|
courtInfoWidth={courtInfoWidth}
|
||||||
|
gridWidth={gridWidth}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="divide-y">
|
||||||
|
{schedules.map((schedule) => (
|
||||||
|
<BookingCourtRow
|
||||||
|
key={schedule.court.id}
|
||||||
|
schedule={schedule}
|
||||||
|
courtInfoWidth={courtInfoWidth}
|
||||||
|
gridWidth={gridWidth}
|
||||||
|
rangeStart={rangeStart}
|
||||||
|
totalMinutes={totalMinutes}
|
||||||
|
timelineMarks={timelineMarks}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{currentTime && (
|
||||||
|
<CurrentTimeIndicator
|
||||||
|
time={currentTime}
|
||||||
|
courtInfoWidth={courtInfoWidth}
|
||||||
|
gridWidth={gridWidth}
|
||||||
|
rangeStart={rangeStart}
|
||||||
|
totalMinutes={totalMinutes}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TimelineHeaderProps {
|
||||||
|
timelineMarks: Array<{ hour: string; left: number }>;
|
||||||
|
courtInfoWidth: number;
|
||||||
|
gridWidth: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function TimelineHeader({ timelineMarks, courtInfoWidth, gridWidth }: TimelineHeaderProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="sticky top-0 z-20 grid border-b bg-card/95"
|
||||||
|
style={{ gridTemplateColumns: `${courtInfoWidth}px ${gridWidth}px` }}
|
||||||
|
>
|
||||||
|
<div className="sticky left-0 z-30 border-r bg-card/95 px-4 py-3 shadow-[8px_0_18px_-18px_oklch(0_0_0/0.45)]" />
|
||||||
|
<div className="relative h-12">
|
||||||
|
{timelineMarks.map((mark) => (
|
||||||
|
<div
|
||||||
|
key={mark.hour}
|
||||||
|
className="absolute top-0 flex h-full items-center border-l px-3 text-sm text-muted-foreground first:border-l-0"
|
||||||
|
style={{ left: `${mark.left}%` }}
|
||||||
|
>
|
||||||
|
{mark.hour}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BookingCourtRowProps {
|
||||||
|
schedule: BookingCourtSchedule;
|
||||||
|
courtInfoWidth: number;
|
||||||
|
gridWidth: number;
|
||||||
|
rangeStart: number;
|
||||||
|
totalMinutes: number;
|
||||||
|
timelineMarks: Array<{ hour: string; left: number }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function BookingCourtRow({
|
||||||
|
schedule,
|
||||||
|
courtInfoWidth,
|
||||||
|
gridWidth,
|
||||||
|
rangeStart,
|
||||||
|
totalMinutes,
|
||||||
|
timelineMarks,
|
||||||
|
}: BookingCourtRowProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="grid min-h-[96px]"
|
||||||
|
style={{ gridTemplateColumns: `${courtInfoWidth}px ${gridWidth}px` }}
|
||||||
|
>
|
||||||
|
<BookingCourtInfo schedule={schedule} />
|
||||||
|
<div className="relative bg-background/20 py-4">
|
||||||
|
<div className="absolute inset-y-0 left-0 right-0 opacity-70">
|
||||||
|
{timelineMarks.map((mark) => (
|
||||||
|
<span
|
||||||
|
key={mark.hour}
|
||||||
|
className="absolute top-0 h-full border-l first:border-l-0"
|
||||||
|
style={{ left: `${mark.left}%` }}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="relative h-16">
|
||||||
|
{schedule.segments.map((segment) => (
|
||||||
|
<BookingSlotBlock
|
||||||
|
key={segment.id}
|
||||||
|
segment={segment}
|
||||||
|
schedule={schedule}
|
||||||
|
rangeStart={rangeStart}
|
||||||
|
totalMinutes={totalMinutes}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function BookingCourtInfo({ schedule }: { schedule: BookingCourtSchedule }) {
|
||||||
|
return (
|
||||||
|
<div className="sticky left-0 z-10 flex items-center gap-3 border-r bg-card/95 px-4 py-4 shadow-[8px_0_18px_-18px_oklch(0_0_0/0.45)]">
|
||||||
|
<div className="flex size-12 shrink-0 items-center justify-center rounded-lg border border-primary/40 bg-primary/15 text-primary">
|
||||||
|
<Dumbbell className="size-6" />
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<h2 className="truncate text-base font-semibold">{schedule.court.name}</h2>
|
||||||
|
<p className="truncate text-sm text-muted-foreground">{schedule.court.sport.name}</p>
|
||||||
|
<div className="mt-1 flex items-center gap-3 text-xs text-muted-foreground">
|
||||||
|
<span className="inline-flex items-center gap-1">
|
||||||
|
<span className="size-2 rounded-full bg-primary" />
|
||||||
|
{schedule.metrics.free}
|
||||||
|
</span>
|
||||||
|
<span className="inline-flex items-center gap-1">
|
||||||
|
<span className="size-2 rounded-full bg-reserved" />
|
||||||
|
{schedule.metrics.reserved}
|
||||||
|
</span>
|
||||||
|
<span className="inline-flex items-center gap-1">
|
||||||
|
<span className="size-2 rounded-full bg-maintenance" />
|
||||||
|
{schedule.metrics.maintenance}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BookingSlotBlockProps {
|
||||||
|
segment: BookingTimelineSegment;
|
||||||
|
schedule: BookingCourtSchedule;
|
||||||
|
rangeStart: number;
|
||||||
|
totalMinutes: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function BookingSlotBlock({ segment, schedule, rangeStart, totalMinutes }: BookingSlotBlockProps) {
|
||||||
|
const { openCreateBooking, updateBookingStatus } = useBooking();
|
||||||
|
const left = ((segment.startMinutes - rangeStart) / totalMinutes) * 100;
|
||||||
|
const width = ((segment.endMinutes - segment.startMinutes) / totalMinutes) * 100;
|
||||||
|
const isFree = segment.status === 'free';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={cn(
|
||||||
|
'absolute top-0 flex h-16 min-w-0 flex-col justify-center overflow-hidden rounded-md border px-2 text-left text-xs shadow-sm transition-all hover:-translate-y-0.5 hover:shadow-md focus-visible:ring-2 focus-visible:ring-ring',
|
||||||
|
segment.status === 'free' &&
|
||||||
|
'border-primary/70 bg-primary/20 text-primary hover:bg-primary/25',
|
||||||
|
segment.status === 'reserved' &&
|
||||||
|
'border-reserved/70 bg-reserved/80 text-reserved-foreground',
|
||||||
|
segment.status === 'maintenance' &&
|
||||||
|
'border-maintenance/80 bg-maintenance/75 text-maintenance-foreground'
|
||||||
|
)}
|
||||||
|
style={{
|
||||||
|
left: `calc(${left}% + 4px)`,
|
||||||
|
width: `calc(${width}% - 8px)`,
|
||||||
|
}}
|
||||||
|
onClick={() => {
|
||||||
|
if (isFree) {
|
||||||
|
openCreateBooking({
|
||||||
|
courtId: schedule.court.id,
|
||||||
|
startTime: segment.startTime,
|
||||||
|
sportId: schedule.court.sportId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onDoubleClick={() => {
|
||||||
|
if (segment.booking?.status === 'CONFIRMED') {
|
||||||
|
updateBookingStatus(segment.booking.id, 'COMPLETED');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
title={
|
||||||
|
segment.booking
|
||||||
|
? `${segment.booking.customerName} · ${segment.startTime} - ${segment.endTime}`
|
||||||
|
: `${segment.startTime} - ${segment.endTime}`
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{isFree ? (
|
||||||
|
<span className="flex items-center justify-center gap-1 text-sm font-medium">
|
||||||
|
<Plus className="size-4" />
|
||||||
|
<span className="hidden sm:inline">Reservar</span>
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<span className="truncate text-sm font-medium">
|
||||||
|
{segment.startTime} - {segment.endTime}
|
||||||
|
</span>
|
||||||
|
<span className="mt-1 flex items-center gap-1 truncate opacity-90">
|
||||||
|
<Users className="size-3" />
|
||||||
|
{segment.booking?.customerName ?? 'Mantenimiento'}
|
||||||
|
</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CurrentTimeIndicatorProps {
|
||||||
|
time: string;
|
||||||
|
courtInfoWidth: number;
|
||||||
|
gridWidth: number;
|
||||||
|
rangeStart: number;
|
||||||
|
totalMinutes: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function CurrentTimeIndicator({
|
||||||
|
time,
|
||||||
|
courtInfoWidth,
|
||||||
|
gridWidth,
|
||||||
|
rangeStart,
|
||||||
|
totalMinutes,
|
||||||
|
}: CurrentTimeIndicatorProps) {
|
||||||
|
const left = courtInfoWidth + ((timeToMinutes(time) - rangeStart) / totalMinutes) * gridWidth;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="pointer-events-none absolute bottom-0 top-12 z-20" style={{ left }}>
|
||||||
|
<div className="absolute left-0 top-0 -translate-x-1/2 -translate-y-1/2 rounded-md bg-primary px-2 py-1 text-xs font-medium text-primary-foreground shadow-sm">
|
||||||
|
{time}
|
||||||
|
</div>
|
||||||
|
<div className="absolute bottom-0 left-0 top-0 w-px bg-primary" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { DatePicker } from '@/components/ui/date-picker';
|
||||||
|
import { Field, FieldLabel } from '@/components/ui/field';
|
||||||
|
import {
|
||||||
|
Select,
|
||||||
|
SelectContent,
|
||||||
|
SelectItem,
|
||||||
|
SelectTrigger,
|
||||||
|
SelectValue,
|
||||||
|
} from '@/components/ui/select';
|
||||||
|
import { ChevronLeft, ChevronRight, Clock, SlidersHorizontal } from 'lucide-react';
|
||||||
|
import { useBooking } from '../booking-provider';
|
||||||
|
import type { BookingStatusFilter } from '../booking.types';
|
||||||
|
import { fromIsoDateLocal, toIsoDateLocal } from '../lib/booking-time';
|
||||||
|
|
||||||
|
const timeRangeOptions = [
|
||||||
|
{ label: '08:00 - 22:00', start: '08:00', end: '22:00' },
|
||||||
|
{ label: '06:00 - 00:00', start: '06:00', end: '23:59' },
|
||||||
|
{ label: '08:00 - 14:00', start: '08:00', end: '14:00' },
|
||||||
|
{ label: '14:00 - 22:00', start: '14:00', end: '22:00' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const statusOptions: Array<{ value: BookingStatusFilter; label: string }> = [
|
||||||
|
{ value: 'all', label: 'Todos' },
|
||||||
|
{ value: 'free', label: 'Libre' },
|
||||||
|
{ value: 'reserved', label: 'Reservado' },
|
||||||
|
{ value: 'maintenance', label: 'Mantenimiento' },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function BookingToolbar() {
|
||||||
|
const {
|
||||||
|
courts,
|
||||||
|
selectedDate,
|
||||||
|
selectedSportId,
|
||||||
|
selectedStatus,
|
||||||
|
visibleTimeRange,
|
||||||
|
setSelectedDate,
|
||||||
|
moveSelectedDate,
|
||||||
|
setSelectedSportId,
|
||||||
|
setSelectedStatus,
|
||||||
|
setVisibleTimeRange,
|
||||||
|
} = useBooking();
|
||||||
|
|
||||||
|
const sports = [...new Map(courts.map((court) => [court.sport.id, court.sport])).values()];
|
||||||
|
const activeRangeValue = `${visibleTimeRange.start}-${visibleTimeRange.end}`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="rounded-lg border bg-card/85 p-4 shadow-sm">
|
||||||
|
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-[1fr_1fr_1.6fr_1.1fr_auto] xl:items-end">
|
||||||
|
<Field>
|
||||||
|
<FieldLabel>Deporte</FieldLabel>
|
||||||
|
<Select value={selectedSportId} onValueChange={setSelectedSportId}>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
<SelectItem value="all">Todos</SelectItem>
|
||||||
|
{sports.map((sport) => (
|
||||||
|
<SelectItem key={sport.id} value={sport.id}>
|
||||||
|
{sport.name}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field>
|
||||||
|
<FieldLabel>Estado</FieldLabel>
|
||||||
|
<Select
|
||||||
|
value={selectedStatus}
|
||||||
|
onValueChange={(value) => setSelectedStatus(value as BookingStatusFilter)}
|
||||||
|
>
|
||||||
|
<SelectTrigger>
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{statusOptions.map((option) => (
|
||||||
|
<SelectItem key={option.value} value={option.value}>
|
||||||
|
{option.label}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field>
|
||||||
|
<FieldLabel>Fecha</FieldLabel>
|
||||||
|
<div className="grid grid-cols-[auto_1fr_auto] gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
onClick={() => moveSelectedDate(-1)}
|
||||||
|
>
|
||||||
|
<ChevronLeft className="size-4" />
|
||||||
|
</Button>
|
||||||
|
<DatePicker
|
||||||
|
value={fromIsoDateLocal(selectedDate)}
|
||||||
|
onChange={(date) =>
|
||||||
|
setSelectedDate(date ? toIsoDateLocal(date) : toIsoDateLocal(new Date()))
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<Button type="button" variant="outline" size="icon" onClick={() => moveSelectedDate(1)}>
|
||||||
|
<ChevronRight className="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Field>
|
||||||
|
<FieldLabel>Hora</FieldLabel>
|
||||||
|
<Select
|
||||||
|
value={activeRangeValue}
|
||||||
|
onValueChange={(value) => {
|
||||||
|
const option = timeRangeOptions.find((item) => `${item.start}-${item.end}` === value);
|
||||||
|
if (option) {
|
||||||
|
setVisibleTimeRange({ start: option.start, end: option.end });
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<SelectTrigger>
|
||||||
|
<Clock className="mr-2 size-4 text-muted-foreground" />
|
||||||
|
<SelectValue />
|
||||||
|
</SelectTrigger>
|
||||||
|
<SelectContent>
|
||||||
|
{timeRangeOptions.map((option) => (
|
||||||
|
<SelectItem
|
||||||
|
key={`${option.start}-${option.end}`}
|
||||||
|
value={`${option.start}-${option.end}`}
|
||||||
|
>
|
||||||
|
{option.label}
|
||||||
|
</SelectItem>
|
||||||
|
))}
|
||||||
|
</SelectContent>
|
||||||
|
</Select>
|
||||||
|
</Field>
|
||||||
|
|
||||||
|
<Button variant="outline" className="xl:self-end">
|
||||||
|
<SlidersHorizontal className="size-4" />
|
||||||
|
Filtros avanzados
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
66
apps/frontend/src/features/booking/lib/booking-time.ts
Normal file
66
apps/frontend/src/features/booking/lib/booking-time.ts
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
import type { DayOfWeek } from '@repo/api-contract';
|
||||||
|
|
||||||
|
export 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}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function timeToMinutes(time: string) {
|
||||||
|
const [hours, minutes] = time.split(':').map(Number);
|
||||||
|
return hours * 60 + minutes;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function minutesToTime(minutes: number) {
|
||||||
|
const hours = Math.floor(minutes / 60);
|
||||||
|
const remainder = minutes % 60;
|
||||||
|
return `${String(hours).padStart(2, '0')}:${String(remainder).padStart(2, '0')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function addDaysIso(dateIso: string, amount: number) {
|
||||||
|
const date = fromIsoDateLocal(dateIso) ?? new Date();
|
||||||
|
date.setDate(date.getDate() + amount);
|
||||||
|
return toIsoDateLocal(date);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isTodayIso(dateIso: string) {
|
||||||
|
return dateIso === toIsoDateLocal(new Date());
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatBookingDate(dateIso: string, options?: Intl.DateTimeFormatOptions) {
|
||||||
|
const date = fromIsoDateLocal(dateIso);
|
||||||
|
if (!date) return dateIso;
|
||||||
|
|
||||||
|
return new Intl.DateTimeFormat('es-AR', {
|
||||||
|
weekday: 'long',
|
||||||
|
day: '2-digit',
|
||||||
|
month: 'long',
|
||||||
|
year: options?.year,
|
||||||
|
...options,
|
||||||
|
}).format(date);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getDayOfWeek(dateIso: string): DayOfWeek {
|
||||||
|
const date = fromIsoDateLocal(dateIso) ?? new Date();
|
||||||
|
const day = date.getDay();
|
||||||
|
|
||||||
|
if (day === 0) return 'SUNDAY';
|
||||||
|
if (day === 1) return 'MONDAY';
|
||||||
|
if (day === 2) return 'TUESDAY';
|
||||||
|
if (day === 3) return 'WEDNESDAY';
|
||||||
|
if (day === 4) return 'THURSDAY';
|
||||||
|
if (day === 5) return 'FRIDAY';
|
||||||
|
return 'SATURDAY';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getNowTime() {
|
||||||
|
const now = new Date();
|
||||||
|
return `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
|
||||||
|
}
|
||||||
@@ -1,62 +1,9 @@
|
|||||||
import { Button } from '@/components/ui/button';
|
import { Booking } from '@/features/booking/booking';
|
||||||
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 { ApiClientError, apiClient } from '@/lib/api-client';
|
import { ApiClientError, apiClient } from '@/lib/api-client';
|
||||||
import { useCurrentComplexStore } from '@/lib/stores/current-complex-store';
|
import { useCurrentComplexStore } from '@/lib/stores/current-complex-store';
|
||||||
import { zodResolver } from '@hookform/resolvers/zod';
|
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||||
import type { AdminBooking } from '@repo/api-contract';
|
|
||||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
|
||||||
import { useNavigate } from '@tanstack/react-router';
|
import { useNavigate } from '@tanstack/react-router';
|
||||||
import { Check, Copy } from 'lucide-react';
|
import { useEffect } from '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);
|
|
||||||
}
|
|
||||||
|
|
||||||
function extractMessage(error: unknown, fallback: string) {
|
function extractMessage(error: unknown, fallback: string) {
|
||||||
if (error instanceof ApiClientError) {
|
if (error instanceof ApiClientError) {
|
||||||
@@ -66,71 +13,9 @@ function extractMessage(error: unknown, fallback: string) {
|
|||||||
return 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 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() {
|
export function HomePage() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const navigate = useNavigate();
|
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({
|
const currentComplexQuery = useQuery({
|
||||||
queryKey: ['current-complex'],
|
queryKey: ['current-complex'],
|
||||||
@@ -152,6 +37,7 @@ export function HomePage() {
|
|||||||
queryClient.invalidateQueries({ queryKey: ['admin-bookings'] });
|
queryClient.invalidateQueries({ queryKey: ['admin-bookings'] });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return unsubscribe;
|
return unsubscribe;
|
||||||
}, [queryClient]);
|
}, [queryClient]);
|
||||||
|
|
||||||
@@ -191,7 +77,6 @@ export function HomePage() {
|
|||||||
if (!selectedComplex?.id) return;
|
if (!selectedComplex?.id) return;
|
||||||
|
|
||||||
const channel = `complex-${selectedComplex.id}`;
|
const channel = `complex-${selectedComplex.id}`;
|
||||||
|
|
||||||
let eventSource: EventSource | null = null;
|
let eventSource: EventSource | null = null;
|
||||||
let reconnectTimeout: ReturnType<typeof setTimeout> | null = null;
|
let reconnectTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||||
let reconnectAttempts = 0;
|
let reconnectAttempts = 0;
|
||||||
@@ -199,27 +84,32 @@ export function HomePage() {
|
|||||||
let lastEventId: string | null = null;
|
let lastEventId: string | null = null;
|
||||||
let pollInterval: ReturnType<typeof setInterval> | 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 = () => {
|
const connect = () => {
|
||||||
if (eventSource) {
|
if (eventSource) {
|
||||||
eventSource.close();
|
eventSource.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (reconnectAttempts >= maxReconnectAttempts) {
|
if (reconnectAttempts >= maxReconnectAttempts) {
|
||||||
console.log('[SSE] Max reconnect attempts reached, switching to polling');
|
|
||||||
startPolling();
|
startPolling();
|
||||||
return;
|
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 = new EventSource(url);
|
||||||
|
|
||||||
eventSource.onerror = () => {
|
eventSource.onerror = () => {
|
||||||
if (eventSource?.readyState === EventSource.CLOSED) {
|
if (eventSource?.readyState === EventSource.CLOSED) {
|
||||||
reconnectAttempts++;
|
reconnectAttempts++;
|
||||||
console.log(
|
|
||||||
`[SSE] Connection closed, retry ${reconnectAttempts}/${maxReconnectAttempts}`
|
|
||||||
);
|
|
||||||
reconnectTimeout = setTimeout(() => {
|
reconnectTimeout = setTimeout(() => {
|
||||||
connect();
|
connect();
|
||||||
}, 2000);
|
}, 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();
|
connect();
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
@@ -261,526 +142,21 @@ export function HomePage() {
|
|||||||
};
|
};
|
||||||
}, [selectedComplex?.id, queryClient]);
|
}, [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) {
|
if (myComplexesQuery.isLoading) {
|
||||||
return (
|
return <p className="text-sm text-muted-foreground">Cargando panel...</p>;
|
||||||
<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) {
|
if (myComplexesQuery.isError) {
|
||||||
return (
|
return (
|
||||||
<main className="mx-auto w-full max-w-6xl px-6 py-8">
|
<p className="text-sm text-destructive">
|
||||||
<p className="text-sm text-destructive">
|
{extractMessage(myComplexesQuery.error, 'No pudimos cargar tus complejos.')}
|
||||||
{extractMessage(myComplexesQuery.error, 'No pudimos cargar tus complejos.')}
|
</p>
|
||||||
</p>
|
|
||||||
</main>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!selectedComplex) {
|
if (!selectedComplex) {
|
||||||
return (
|
return <p className="text-sm text-muted-foreground">No tienes complejos asignados todavía.</p>;
|
||||||
<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 (
|
return <Booking complex={selectedComplex} />;
|
||||||
<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>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,245 +0,0 @@
|
|||||||
import { Button } from '@/components/ui/button';
|
|
||||||
import {
|
|
||||||
DropdownMenu,
|
|
||||||
DropdownMenuContent,
|
|
||||||
DropdownMenuItem,
|
|
||||||
DropdownMenuLabel,
|
|
||||||
DropdownMenuSeparator,
|
|
||||||
DropdownMenuTrigger,
|
|
||||||
} from '@/components/ui/dropdown-menu';
|
|
||||||
import { UserAvatar } from '@/components/user-avatar';
|
|
||||||
import { apiClient } from '@/lib/api-client';
|
|
||||||
import { useAuth } from '@/lib/auth';
|
|
||||||
import { acceptStoredPendingInvite } from '@/lib/invitations';
|
|
||||||
import { useCurrentComplexStore } from '@/lib/stores/current-complex-store';
|
|
||||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
|
||||||
import { Link, Outlet, useNavigate } from '@tanstack/react-router';
|
|
||||||
import { LogOut, Menu, UserRound } from 'lucide-react';
|
|
||||||
import { useEffect, useMemo, useRef } from 'react';
|
|
||||||
import { ThemeSwitcher } from './theme-switcher';
|
|
||||||
|
|
||||||
export function RootLayout() {
|
|
||||||
const navigate = useNavigate();
|
|
||||||
const queryClient = useQueryClient();
|
|
||||||
const { user, isAuthenticated, displayName, avatarUrl, signOut } = useAuth();
|
|
||||||
const { currentComplexSlug, setCurrentComplex } = useCurrentComplexStore();
|
|
||||||
const processedInviteForUser = useRef<string | null>(null);
|
|
||||||
const myComplexesQuery = useQuery({
|
|
||||||
queryKey: ['my-complexes'],
|
|
||||||
enabled: isAuthenticated,
|
|
||||||
queryFn: () => apiClient.complexes.listMine(),
|
|
||||||
});
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!isAuthenticated) {
|
|
||||||
processedInviteForUser.current = null;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const userKey = user?.email ?? displayName ?? 'authenticated-user';
|
|
||||||
|
|
||||||
if (processedInviteForUser.current === userKey) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
processedInviteForUser.current = userKey;
|
|
||||||
|
|
||||||
void (async () => {
|
|
||||||
await acceptStoredPendingInvite(apiClient.complexes.acceptPendingInvitations);
|
|
||||||
await queryClient.invalidateQueries({ queryKey: ['my-complexes'] });
|
|
||||||
})();
|
|
||||||
}, [displayName, isAuthenticated, queryClient, user?.email]);
|
|
||||||
|
|
||||||
const complexSlug = currentComplexSlug || myComplexesQuery.data?.[0]?.complexSlug;
|
|
||||||
|
|
||||||
const currentComplexName = useMemo(() => {
|
|
||||||
const complexes = myComplexesQuery.data ?? [];
|
|
||||||
if (complexes.length === 0) return 'Mi complejo';
|
|
||||||
|
|
||||||
const selected = complexes.find((complex) => complex.complexSlug === complexSlug);
|
|
||||||
|
|
||||||
return selected?.complexName ?? complexes[0]?.complexName ?? 'Mi complejo';
|
|
||||||
}, [complexSlug, myComplexesQuery.data]);
|
|
||||||
|
|
||||||
const handleSignOut = async () => {
|
|
||||||
await signOut();
|
|
||||||
await navigate({ to: '/login' });
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex min-h-screen flex-col">
|
|
||||||
<header className="mx-auto flex w-full max-w-6xl items-center justify-between px-6 py-4">
|
|
||||||
<div className="flex items-center gap-6">
|
|
||||||
<h1 className="text-sm font-semibold">{currentComplexName}</h1>
|
|
||||||
<nav className="hidden items-center gap-3 text-sm md:flex">
|
|
||||||
<Link
|
|
||||||
to="/"
|
|
||||||
className="text-muted-foreground"
|
|
||||||
activeProps={{ className: 'text-foreground font-medium' }}
|
|
||||||
>
|
|
||||||
Home
|
|
||||||
</Link>
|
|
||||||
{isAuthenticated && currentComplexSlug && (
|
|
||||||
<Link
|
|
||||||
to="/complex/$slug/edit"
|
|
||||||
params={{ slug: currentComplexSlug }}
|
|
||||||
className="text-muted-foreground"
|
|
||||||
activeProps={{ className: 'text-foreground font-medium' }}
|
|
||||||
>
|
|
||||||
Configuración
|
|
||||||
</Link>
|
|
||||||
)}
|
|
||||||
</nav>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<ThemeSwitcher />
|
|
||||||
|
|
||||||
{!isAuthenticated && (
|
|
||||||
<Button asChild size="sm" variant="outline" className="hidden md:inline-flex">
|
|
||||||
<Link to="/login">Login</Link>
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{isAuthenticated && (
|
|
||||||
<DropdownMenu>
|
|
||||||
<DropdownMenuTrigger asChild>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="hidden items-center gap-2 rounded-md px-2 py-1.5 transition-colors hover:bg-muted md:inline-flex"
|
|
||||||
>
|
|
||||||
<UserAvatar
|
|
||||||
src={avatarUrl}
|
|
||||||
alt={displayName}
|
|
||||||
fallbackText={displayName}
|
|
||||||
size="sm"
|
|
||||||
/>
|
|
||||||
<span className="max-w-32 truncate text-sm text-foreground">{displayName}</span>
|
|
||||||
</button>
|
|
||||||
</DropdownMenuTrigger>
|
|
||||||
<DropdownMenuContent align="end" className="w-52">
|
|
||||||
<DropdownMenuLabel>Mi cuenta</DropdownMenuLabel>
|
|
||||||
<DropdownMenuSeparator />
|
|
||||||
{myComplexesQuery.data && myComplexesQuery.data.length > 1 && (
|
|
||||||
<>
|
|
||||||
<DropdownMenuLabel className="text-xs font-normal text-muted-foreground">
|
|
||||||
Cambiar complejo
|
|
||||||
</DropdownMenuLabel>
|
|
||||||
{myComplexesQuery.data.map((complex) => (
|
|
||||||
<DropdownMenuItem
|
|
||||||
key={complex.id}
|
|
||||||
onSelect={async () => {
|
|
||||||
await apiClient.complexes.select({ complexId: complex.id });
|
|
||||||
setCurrentComplex(complex.complexSlug);
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{complex.complexSlug === complexSlug && <span className="mr-2">✓</span>}
|
|
||||||
{complex.complexName}
|
|
||||||
</DropdownMenuItem>
|
|
||||||
))}
|
|
||||||
<DropdownMenuSeparator />
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<DropdownMenuItem
|
|
||||||
onSelect={() => {
|
|
||||||
void navigate({ to: '/profile' });
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<UserRound className="size-4" />
|
|
||||||
Profile
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem
|
|
||||||
variant="destructive"
|
|
||||||
onSelect={() => {
|
|
||||||
void handleSignOut();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<LogOut className="size-4" />
|
|
||||||
Sign out
|
|
||||||
</DropdownMenuItem>
|
|
||||||
</DropdownMenuContent>
|
|
||||||
</DropdownMenu>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<DropdownMenu>
|
|
||||||
<DropdownMenuTrigger asChild>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
size="icon-sm"
|
|
||||||
className="md:hidden"
|
|
||||||
aria-label="Abrir menú"
|
|
||||||
>
|
|
||||||
<Menu className="size-4" />
|
|
||||||
</Button>
|
|
||||||
</DropdownMenuTrigger>
|
|
||||||
<DropdownMenuContent align="end" className="w-56 md:hidden">
|
|
||||||
<DropdownMenuLabel>Navegación</DropdownMenuLabel>
|
|
||||||
<DropdownMenuSeparator />
|
|
||||||
<DropdownMenuItem
|
|
||||||
onSelect={() => {
|
|
||||||
void navigate({ to: '/' });
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Home
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem
|
|
||||||
onSelect={() => {
|
|
||||||
void navigate({ to: '/about' });
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
About
|
|
||||||
</DropdownMenuItem>
|
|
||||||
{isAuthenticated && currentComplexSlug && (
|
|
||||||
<DropdownMenuItem
|
|
||||||
onSelect={() => {
|
|
||||||
void navigate({
|
|
||||||
to: '/complex/$slug/edit',
|
|
||||||
params: { slug: currentComplexSlug },
|
|
||||||
});
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Configuración
|
|
||||||
</DropdownMenuItem>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<DropdownMenuSeparator />
|
|
||||||
{isAuthenticated ? (
|
|
||||||
<>
|
|
||||||
<DropdownMenuItem
|
|
||||||
onSelect={() => {
|
|
||||||
void navigate({ to: '/profile' });
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<UserRound className="size-4" />
|
|
||||||
Profile
|
|
||||||
</DropdownMenuItem>
|
|
||||||
<DropdownMenuItem
|
|
||||||
variant="destructive"
|
|
||||||
onSelect={() => {
|
|
||||||
void handleSignOut();
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<LogOut className="size-4" />
|
|
||||||
Sign out
|
|
||||||
</DropdownMenuItem>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<DropdownMenuItem
|
|
||||||
onSelect={() => {
|
|
||||||
void navigate({ to: '/login' });
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Login
|
|
||||||
</DropdownMenuItem>
|
|
||||||
)}
|
|
||||||
</DropdownMenuContent>
|
|
||||||
</DropdownMenu>
|
|
||||||
</div>
|
|
||||||
</header>
|
|
||||||
<div className="flex-1">
|
|
||||||
<Outlet />
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -215,4 +215,33 @@ body,
|
|||||||
[role="button"]:not(:disabled) {
|
[role="button"]:not(:disabled) {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@layer utilities {
|
||||||
|
.booking-scrollbar {
|
||||||
|
scrollbar-color: oklch(0.67 0.21 158 / 62%) oklch(1 0 0 / 8%);
|
||||||
|
scrollbar-width: thin;
|
||||||
|
}
|
||||||
|
|
||||||
|
.booking-scrollbar::-webkit-scrollbar {
|
||||||
|
height: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.booking-scrollbar::-webkit-scrollbar-track {
|
||||||
|
background: oklch(1 0 0 / 6%);
|
||||||
|
border-radius: 999px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.booking-scrollbar::-webkit-scrollbar-thumb {
|
||||||
|
background: linear-gradient(90deg, oklch(0.67 0.21 158 / 72%), oklch(0.61 0.2 255 / 58%));
|
||||||
|
border: 3px solid transparent;
|
||||||
|
border-radius: 999px;
|
||||||
|
background-clip: padding-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.booking-scrollbar::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: linear-gradient(90deg, oklch(0.67 0.21 158 / 88%), oklch(0.61 0.2 255 / 72%));
|
||||||
|
border: 3px solid transparent;
|
||||||
|
background-clip: padding-box;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
type PropsWithChildren,
|
type PropsWithChildren,
|
||||||
createContext,
|
createContext,
|
||||||
|
useCallback,
|
||||||
useContext,
|
useContext,
|
||||||
useEffect,
|
useEffect,
|
||||||
useMemo,
|
useMemo,
|
||||||
@@ -14,6 +15,7 @@ type ThemeContextValue = {
|
|||||||
theme: Theme;
|
theme: Theme;
|
||||||
resolvedTheme: ResolvedTheme;
|
resolvedTheme: ResolvedTheme;
|
||||||
setTheme: (theme: Theme) => void;
|
setTheme: (theme: Theme) => void;
|
||||||
|
toggleTheme: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
const THEME_STORAGE_KEY = 'theme';
|
const THEME_STORAGE_KEY = 'theme';
|
||||||
@@ -27,6 +29,18 @@ function applyResolvedTheme(theme: ResolvedTheme) {
|
|||||||
document.documentElement.classList.toggle('dark', theme === 'dark');
|
document.documentElement.classList.toggle('dark', theme === 'dark');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isEditableElement(target: EventTarget | null) {
|
||||||
|
if (!(target instanceof HTMLElement)) return false;
|
||||||
|
|
||||||
|
const tagName = target.tagName.toLowerCase();
|
||||||
|
return (
|
||||||
|
tagName === 'input' ||
|
||||||
|
tagName === 'textarea' ||
|
||||||
|
tagName === 'select' ||
|
||||||
|
target.isContentEditable
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function ThemeProvider({ children }: PropsWithChildren) {
|
export function ThemeProvider({ children }: PropsWithChildren) {
|
||||||
const [theme, setThemeState] = useState<Theme>('system');
|
const [theme, setThemeState] = useState<Theme>('system');
|
||||||
const [resolvedTheme, setResolvedTheme] = useState<ResolvedTheme>('light');
|
const [resolvedTheme, setResolvedTheme] = useState<ResolvedTheme>('light');
|
||||||
@@ -54,18 +68,37 @@ export function ThemeProvider({ children }: PropsWithChildren) {
|
|||||||
return () => mediaQuery.removeEventListener('change', updateTheme);
|
return () => mediaQuery.removeEventListener('change', updateTheme);
|
||||||
}, [theme]);
|
}, [theme]);
|
||||||
|
|
||||||
const setTheme = (nextTheme: Theme) => {
|
const setTheme = useCallback((nextTheme: Theme) => {
|
||||||
setThemeState(nextTheme);
|
setThemeState(nextTheme);
|
||||||
localStorage.setItem(THEME_STORAGE_KEY, nextTheme);
|
localStorage.setItem(THEME_STORAGE_KEY, nextTheme);
|
||||||
};
|
}, []);
|
||||||
|
|
||||||
|
const toggleTheme = useCallback(() => {
|
||||||
|
setTheme(resolvedTheme === 'dark' ? 'light' : 'dark');
|
||||||
|
}, [resolvedTheme, setTheme]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handleKeyDown = (event: KeyboardEvent) => {
|
||||||
|
if (isEditableElement(event.target)) return;
|
||||||
|
if (!event.metaKey || event.ctrlKey || event.altKey || event.shiftKey) return;
|
||||||
|
if (event.key.toLowerCase() !== 'd') return;
|
||||||
|
|
||||||
|
event.preventDefault();
|
||||||
|
toggleTheme();
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('keydown', handleKeyDown);
|
||||||
|
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||||
|
}, [toggleTheme]);
|
||||||
|
|
||||||
const value = useMemo<ThemeContextValue>(
|
const value = useMemo<ThemeContextValue>(
|
||||||
() => ({
|
() => ({
|
||||||
theme,
|
theme,
|
||||||
resolvedTheme,
|
resolvedTheme,
|
||||||
setTheme,
|
setTheme,
|
||||||
|
toggleTheme,
|
||||||
}),
|
}),
|
||||||
[theme, resolvedTheme]
|
[theme, resolvedTheme, setTheme, toggleTheme]
|
||||||
);
|
);
|
||||||
|
|
||||||
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
|
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
|
||||||
|
|||||||
@@ -23,5 +23,5 @@ function RootRoute() {
|
|||||||
<Outlet />
|
<Outlet />
|
||||||
</div>
|
</div>
|
||||||
</Layout>
|
</Layout>
|
||||||
)
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { RootLayout } from '@/features/layout/root-layout';
|
|
||||||
import { createFileRoute } from '@tanstack/react-router';
|
import { createFileRoute } from '@tanstack/react-router';
|
||||||
|
import { Outlet } from '@tanstack/react-router';
|
||||||
|
|
||||||
export const Route = createFileRoute('/_app')({
|
export const Route = createFileRoute('/_app')({
|
||||||
component: RootLayout,
|
component: Outlet,
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user