9 Commits

15 changed files with 533 additions and 166 deletions

View File

@@ -31,11 +31,14 @@ export const auth = betterAuth({
sendOnSignUp: true, sendOnSignUp: true,
autoSignInAfterVerification: true, autoSignInAfterVerification: true,
sendVerificationEmail: async ({ user, url }) => { sendVerificationEmail: async ({ user, url }) => {
const verificationUrl = new URL(url);
const appUrl = process.env.APP_BASE_URL ?? 'http://localhost:5173';
verificationUrl.searchParams.set('callbackURL', appUrl);
await sendMail({ await sendMail({
to: user.email, to: user.email,
subject: 'Verificá tu email en Playzer', subject: 'Verificá tu email en Playzer',
html: `Hacé click para verificar tu email: <a href="${url}">${url}</a>`, html: `Hacé click para verificar tu email: <a href="${verificationUrl.toString()}">${verificationUrl.toString()}</a>`,
text: `Hacé click para verificar tu email: ${url}`, text: `Hacé click para verificar tu email: ${verificationUrl.toString()}`,
}); });
}, },
}, },

View File

@@ -258,6 +258,16 @@ export async function createAdminBooking(
input: CreateAdminBookingInput input: CreateAdminBookingInput
) { ) {
const complex = await ensureComplexAccess(complexId, userId); const complex = await ensureComplexAccess(complexId, userId);
const adminUser = await db.user.findUnique({
where: { id: userId },
select: { emailVerified: true },
});
if (!adminUser?.emailVerified) {
throw new AdminBookingServiceError('Debés verificar tu email para poder crear reservas.', 403);
}
const bookingDate = parseIsoDate(input.date); const bookingDate = parseIsoDate(input.date);
const dayOfWeek = getDayOfWeek(bookingDate); const dayOfWeek = getDayOfWeek(bookingDate);

View File

@@ -13,6 +13,16 @@ type Slot = {
endTime: string; endTime: string;
}; };
type PriceableCourt = {
basePrice: unknown;
priceRules: Array<{
dayOfWeek: DayOfWeek | null;
startTime: string | null;
endTime: string | null;
price: unknown;
}>;
};
type ComplexWithPublicBookingData = Awaited<ReturnType<typeof getComplexWithBookingData>>; type ComplexWithPublicBookingData = Awaited<ReturnType<typeof getComplexWithBookingData>>;
const DAY_OF_WEEK_BY_INDEX: DayOfWeek[] = [ const DAY_OF_WEEK_BY_INDEX: DayOfWeek[] = [
@@ -202,6 +212,10 @@ async function getComplexWithBookingData(complexSlug: string) {
availabilities: { availabilities: {
orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }], orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }],
}, },
priceRules: {
where: { isActive: true },
orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }],
},
}, },
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' },
}, },
@@ -226,6 +240,33 @@ async function getComplexWithBookingData(complexSlug: string) {
return complex; return complex;
} }
function resolveSlotPrice(court: PriceableCourt, dayOfWeek: DayOfWeek, slot: Slot): number {
const slotStart = toMinutes(slot.startTime);
const slotEnd = toMinutes(slot.endTime);
const matchingRules = court.priceRules
.filter((rule) => {
if (rule.dayOfWeek && rule.dayOfWeek !== dayOfWeek) {
return false;
}
if (!rule.startTime || !rule.endTime) {
return true;
}
return slotStart >= toMinutes(rule.startTime) && slotEnd <= toMinutes(rule.endTime);
})
.sort((first, second) => {
const firstSpecificity =
(first.dayOfWeek ? 2 : 0) + (first.startTime && first.endTime ? 1 : 0);
const secondSpecificity =
(second.dayOfWeek ? 2 : 0) + (second.startTime && second.endTime ? 1 : 0);
return secondSpecificity - firstSpecificity;
});
return Number(matchingRules[0]?.price ?? court.basePrice);
}
function mapBookingResponse(input: { function mapBookingResponse(input: {
bookingId: string; bookingId: string;
bookingCode: string; bookingCode: string;
@@ -289,6 +330,11 @@ export async function getPublicBookingConfirmation(complexSlug: string, bookingC
court: { court: {
select: { select: {
name: true, name: true,
basePrice: true,
priceRules: {
where: { isActive: true },
orderBy: [{ dayOfWeek: 'asc' }, { startTime: 'asc' }],
},
sport: { sport: {
select: { select: {
id: true, id: true,
@@ -299,6 +345,7 @@ export async function getPublicBookingConfirmation(complexSlug: string, bookingC
complex: { complex: {
select: { select: {
complexName: true, complexName: true,
physicalAddress: true,
complexSlug: true, complexSlug: true,
}, },
}, },
@@ -311,13 +358,22 @@ export async function getPublicBookingConfirmation(complexSlug: string, bookingC
throw new PublicBookingServiceError('Reserva no encontrada.', 404); throw new PublicBookingServiceError('Reserva no encontrada.', 404);
} }
const date = formatIsoDate(booking.bookingDate);
const { dayOfWeek } = parseIsoDate(date);
const price = resolveSlotPrice(booking.court, dayOfWeek, {
startTime: booking.startTime,
endTime: booking.endTime,
});
return { return {
bookingCode: booking.bookingCode, bookingCode: booking.bookingCode,
complexName: booking.court.complex.complexName, complexName: booking.court.complex.complexName,
complexAddress: booking.court.complex.physicalAddress ?? undefined,
complexSlug: booking.court.complex.complexSlug, complexSlug: booking.court.complex.complexSlug,
date: formatIsoDate(booking.bookingDate), date,
startTime: booking.startTime, startTime: booking.startTime,
endTime: booking.endTime, endTime: booking.endTime,
price,
courtName: booking.court.name, courtName: booking.court.name,
sport: { sport: {
id: booking.court.sport.id, id: booking.court.sport.id,
@@ -329,9 +385,34 @@ export async function getPublicBookingConfirmation(complexSlug: string, bookingC
}; };
} }
async function hasVerifiedAdmin(complexId: string): Promise<boolean> {
const verifiedAdmin = await db.complexUser.findFirst({
where: {
complexId,
role: 'ADMIN',
user: { emailVerified: true },
},
});
return verifiedAdmin !== null;
}
export async function listPublicAvailability(complexSlug: string, query: PublicAvailabilityQuery) { export async function listPublicAvailability(complexSlug: string, query: PublicAvailabilityQuery) {
const { bookingDate, dayOfWeek } = parseIsoDate(query.date); const { bookingDate, dayOfWeek } = parseIsoDate(query.date);
const complex = await getComplexWithBookingData(complexSlug); const complex = await getComplexWithBookingData(complexSlug);
if (!(await hasVerifiedAdmin(complex.id))) {
return {
complexId: complex.id,
complexName: complex.complexName,
complexAddress: complex.physicalAddress ?? null,
complexSlug: complex.complexSlug,
date: query.date,
sportSelectionRequired: false,
sports: [],
courts: [],
};
}
const sports = resolveSports(complex); const sports = resolveSports(complex);
const sportSelectionRequired = sports.length > 1; const sportSelectionRequired = sports.length > 1;
@@ -407,7 +488,10 @@ export async function listPublicAvailability(complexSlug: string, query: PublicA
}, },
slotDurationMinutes: court.slotDurationMinutes, slotDurationMinutes: court.slotDurationMinutes,
availabilityDay: dayOfWeek, availabilityDay: dayOfWeek,
availableSlots, availableSlots: availableSlots.map((slot) => ({
...slot,
price: resolveSlotPrice(court, dayOfWeek, slot),
})),
}; };
}) })
.filter((court) => court.availableSlots.length > 0); .filter((court) => court.availableSlots.length > 0);
@@ -427,6 +511,14 @@ export async function listPublicAvailability(complexSlug: string, query: PublicA
export async function createPublicBooking(complexSlug: string, input: CreatePublicBookingInput) { export async function createPublicBooking(complexSlug: string, input: CreatePublicBookingInput) {
const { bookingDate, dayOfWeek } = parseIsoDate(input.date); const { bookingDate, dayOfWeek } = parseIsoDate(input.date);
const complex = await getComplexWithBookingData(complexSlug); const complex = await getComplexWithBookingData(complexSlug);
if (!(await hasVerifiedAdmin(complex.id))) {
throw new PublicBookingServiceError(
'El complejo no puede recibir reservas hasta que un administrador verifique su email.',
403
);
}
const sports = resolveSports(complex); const sports = resolveSports(complex);
const { sportSelectionRequired } = validateSportSelection(sports, input.sportId); const { sportSelectionRequired } = validateSportSelection(sports, input.sportId);

View File

@@ -1,5 +1,8 @@
import { useIsMobile } from '@/hooks/use-mobile'; import { useIsMobile } from '@/hooks/use-mobile';
import { authClient } from '@/lib/api-client';
import { useAuth } from '@/lib/auth';
import type { ComplexWithRole } from '@repo/api-contract'; import type { ComplexWithRole } from '@repo/api-contract';
import { useState } from 'react';
import { BookingProvider } from './booking-provider'; import { BookingProvider } from './booking-provider';
import { BookingCreateDialog } from './components/booking-create-dialog'; import { BookingCreateDialog } from './components/booking-create-dialog';
import { BookingDaySummary, BookingQuickActions } from './components/booking-day-summary'; import { BookingDaySummary, BookingQuickActions } from './components/booking-day-summary';
@@ -15,9 +18,44 @@ interface BookingProps {
export function Booking({ complex }: BookingProps) { export function Booking({ complex }: BookingProps) {
const isMobile = useIsMobile(); const isMobile = useIsMobile();
const { user } = useAuth();
const [sending, setSending] = useState(false);
const [emailSent, setEmailSent] = useState(false);
const emailNotVerified = user && !user.emailVerified;
const handleResendVerification = async () => {
if (!user?.email || sending) return;
setSending(true);
try {
await authClient.sendVerificationEmail({ email: user.email });
setEmailSent(true);
setTimeout(() => setEmailSent(false), 6000);
} catch {
// Silently fail — the banner already shows the email to contact
} finally {
setSending(false);
}
};
return ( return (
<BookingProvider complex={complex}> <BookingProvider complex={complex}>
{emailNotVerified && (
<div className="mb-6 flex items-center justify-between gap-4 rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800 dark:border-amber-800/30 dark:bg-amber-950/30 dark:text-amber-200">
<span>
No verificaste tu email. Para crear reservas necesitás verificar tu dirección de correo
electrónico.
</span>
<button
type="button"
onClick={handleResendVerification}
disabled={sending}
className="shrink-0 rounded-lg bg-amber-200 px-3 py-1.5 text-xs font-medium text-amber-900 transition-colors hover:bg-amber-300 disabled:opacity-50 dark:bg-amber-800 dark:text-amber-50 dark:hover:bg-amber-700"
>
{sending ? 'Enviando...' : emailSent ? '¡Email enviado!' : 'Reenviar email'}
</button>
</div>
)}
{isMobile ? ( {isMobile ? (
<BookingMobile /> <BookingMobile />
) : ( ) : (

View File

@@ -18,16 +18,35 @@ function formatDateLabel(isoDate: string) {
}).format(date); }).format(date);
} }
function formatBookingPrice(price: number): string {
if (price === 0) {
return 'Sin cargo';
}
return new Intl.NumberFormat('es-AR', {
style: 'currency',
currency: 'ARS',
maximumFractionDigits: Number.isInteger(price) ? 0 : 2,
}).format(price);
}
function createWhatsappMessage(confirmation: PublicBookingConfirmation) { function createWhatsappMessage(confirmation: PublicBookingConfirmation) {
const dateLabel = formatDateLabel(confirmation.date); const dateLabel = formatDateLabel(confirmation.date);
return [ const lines = ['Ya reservamos cancha para jugar.', `Complejo: ${confirmation.complexName}`];
'Ya reservamos cancha para jugar.',
`Complejo: ${confirmation.complexName}`, if (confirmation.complexAddress) {
lines.push(`Direccion: ${confirmation.complexAddress}`);
}
lines.push(
`Cancha: ${confirmation.courtName} (${confirmation.sport.name})`, `Cancha: ${confirmation.courtName} (${confirmation.sport.name})`,
`Fecha: ${dateLabel}`, `Fecha: ${dateLabel}`,
`Horario: ${confirmation.startTime} - ${confirmation.endTime}`, `Horario: ${confirmation.startTime} - ${confirmation.endTime}`,
`Codigo de reserva: ${confirmation.bookingCode}`, `Precio: ${formatBookingPrice(confirmation.price)}`,
].join('\n'); `Codigo de reserva: ${confirmation.bookingCode}`
);
return lines.join('\n');
} }
export function ShareWhatsappButton({ confirmation }: ShareWhatsappButtonProps) { export function ShareWhatsappButton({ confirmation }: ShareWhatsappButtonProps) {
@@ -36,7 +55,12 @@ export function ShareWhatsappButton({ confirmation }: ShareWhatsappButtonProps)
)}`; )}`;
return ( return (
<Button type="button" variant="outline" className="h-11 w-full text-sm sm:text-base" asChild> <Button
type="button"
variant="outline"
className="h-12 w-full rounded-xl border-slate-200 bg-white text-sm font-semibold text-slate-900 hover:bg-slate-50 sm:text-base"
asChild
>
<a href={whatsappUrl} target="_blank" rel="noopener noreferrer"> <a href={whatsappUrl} target="_blank" rel="noopener noreferrer">
<svg <svg
viewBox="0 0 24 24" viewBox="0 0 24 24"

View File

@@ -1,7 +1,18 @@
import PlayzerIcon from '@/assets/playzer-favicon-512-transparent.png';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { ApiClientError, apiClient } from '@/lib/api-client'; import { ApiClientError, apiClient } from '@/lib/api-client';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { useNavigate } from '@tanstack/react-router'; import { useNavigate } from '@tanstack/react-router';
import {
AlertCircle,
ArrowRight,
CalendarDays,
CheckCircle2,
Clock3,
LoaderCircle,
Receipt,
Trophy,
} from 'lucide-react';
import { ShareWhatsappButton } from './components/share-whatsapp-button'; import { ShareWhatsappButton } from './components/share-whatsapp-button';
type PublicBookingConfirmationPageProps = { type PublicBookingConfirmationPageProps = {
@@ -21,12 +32,25 @@ function formatDateLabel(isoDate: string) {
const [year, month, day] = isoDate.split('-').map(Number); const [year, month, day] = isoDate.split('-').map(Number);
const date = new Date(year, (month ?? 1) - 1, day ?? 1); const date = new Date(year, (month ?? 1) - 1, day ?? 1);
return new Intl.DateTimeFormat('es-AR', { const label = new Intl.DateTimeFormat('es-AR', {
weekday: 'long', weekday: 'long',
day: '2-digit', day: '2-digit',
month: 'long', month: 'long',
year: 'numeric',
}).format(date); }).format(date);
return label.charAt(0).toUpperCase() + label.slice(1);
}
function formatBookingPrice(price: number): string {
if (price === 0) {
return 'Sin cargo';
}
return new Intl.NumberFormat('es-AR', {
style: 'currency',
currency: 'ARS',
maximumFractionDigits: Number.isInteger(price) ? 0 : 2,
}).format(price);
} }
export function PublicBookingConfirmationPage({ export function PublicBookingConfirmationPage({
@@ -40,62 +64,98 @@ export function PublicBookingConfirmationPage({
}); });
return ( return (
<main className="min-h-screen bg-linear-to-b from-background via-background to-primary/5"> <main className="min-h-screen bg-[#edf7f4] text-[#111827]">
<div className="mx-auto flex min-h-screen w-full max-w-3xl items-center px-3 py-8 sm:px-6"> <div className="mx-auto flex min-h-screen w-full max-w-3xl items-center px-4 py-8 sm:px-6">
<section className="w-full rounded-3xl border bg-card p-5 shadow-lg sm:p-8"> <section className="w-full rounded-[28px] border border-emerald-950/10 bg-white p-5 shadow-[0_24px_70px_rgba(15,23,42,0.12)] sm:p-8">
{confirmationQuery.isLoading && ( {confirmationQuery.isLoading && (
<p className="text-sm text-muted-foreground">Cargando confirmacion...</p> <div className="flex items-center gap-3 text-sm text-slate-500">
<LoaderCircle className="size-5 animate-spin text-emerald-600" />
Cargando confirmación...
</div>
)} )}
{confirmationQuery.isError && ( {confirmationQuery.isError && (
<p className="text-sm text-destructive"> <div className="flex gap-3 rounded-2xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">
<AlertCircle className="mt-0.5 size-5 shrink-0" />
<p>
{extractMessage( {extractMessage(
confirmationQuery.error, confirmationQuery.error,
'No pudimos cargar la confirmacion de la reserva.' 'No pudimos cargar la confirmación de la reserva.'
)} )}
</p> </p>
</div>
)} )}
{confirmationQuery.data && ( {confirmationQuery.data && (
<div className="space-y-6"> <div className="space-y-6">
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
<div> <div>
<p className="text-xs font-medium tracking-[0.2em] text-muted-foreground uppercase"> <div className="inline-flex items-center gap-2 rounded-full bg-emerald-50 px-3 py-1 text-xs font-semibold tracking-[0.14em] text-emerald-700 uppercase">
<CheckCircle2 className="size-4" />
Reserva confirmada Reserva confirmada
</p> </div>
<h1 className="mt-2 text-2xl font-semibold sm:text-3xl"> <h1 className="mt-3 text-2xl font-bold tracking-tight sm:text-3xl">
{confirmationQuery.data.complexName} {confirmationQuery.data.complexName}
</h1> </h1>
</div> </div>
<div className="flex items-center gap-2 text-slate-600">
<img src={PlayzerIcon} alt="Playzer" className="size-8" />
<span className="text-lg font-bold tracking-tight">Playzer</span>
</div>
</div>
<div className="rounded-2xl border border-primary/30 bg-primary/5 p-4 text-center sm:p-5"> <div className="rounded-[24px] border border-emerald-500/30 bg-emerald-50/80 p-5 sm:p-6">
<p className="text-xs text-muted-foreground">Codigo de reserva</p> <div className="flex flex-col gap-5 sm:flex-row sm:items-end sm:justify-between">
<p className="mt-1 text-3xl font-bold tracking-[0.25em] text-primary sm:text-4xl"> <div>
<p className="flex items-center gap-2 text-sm font-semibold text-emerald-700">
<CalendarDays className="size-4" />
Tu turno
</p>
<p className="mt-3 text-2xl font-black leading-tight tracking-tight text-slate-950 sm:text-4xl">
{formatDateLabel(confirmationQuery.data.date)}
</p>
<p className="mt-2 flex items-center gap-2 text-3xl font-black leading-none text-emerald-700 sm:text-5xl">
<Clock3 className="size-7 sm:size-9" />
{confirmationQuery.data.startTime} - {confirmationQuery.data.endTime}
</p>
</div>
<div className="rounded-2xl border border-emerald-600/20 bg-white/80 px-4 py-3 sm:min-w-40 sm:text-right">
<p className="text-xs font-medium text-slate-500">Precio del turno</p>
<p className="mt-1 text-2xl font-bold text-slate-950">
{formatBookingPrice(confirmationQuery.data.price)}
</p>
</div>
</div>
</div>
<div className="overflow-hidden rounded-[22px] border border-slate-200 bg-slate-50/70">
<div className="grid gap-px bg-slate-200 sm:grid-cols-2">
<div className="bg-white p-4">
<p className="flex items-center gap-2 text-sm font-medium text-slate-500">
<Trophy className="size-4 text-emerald-600" />
Cancha
</p>
<p className="mt-2 text-base font-semibold text-slate-950">
{confirmationQuery.data.courtName} · {confirmationQuery.data.sport.name}
</p>
</div>
<div className="bg-white p-4">
<p className="flex items-center gap-2 text-sm font-medium text-slate-500">
<Receipt className="size-4 text-emerald-600" />
Código de reserva
</p>
<p className="mt-2 font-mono text-lg font-bold tracking-[0.18em] text-slate-950">
{confirmationQuery.data.bookingCode} {confirmationQuery.data.bookingCode}
</p> </p>
</div> </div>
</div>
<div className="rounded-2xl border bg-background p-4 sm:p-5">
<p className="text-sm text-muted-foreground">Fecha</p>
<p className="mt-1 text-base font-medium capitalize sm:text-lg">
{formatDateLabel(confirmationQuery.data.date)}
</p>
<p className="mt-4 text-sm text-muted-foreground">Horario</p>
<p className="mt-1 text-base font-medium sm:text-lg">
{confirmationQuery.data.startTime} - {confirmationQuery.data.endTime}
</p>
<p className="mt-4 text-sm text-muted-foreground">Cancha</p>
<p className="mt-1 text-base font-medium sm:text-lg">
{confirmationQuery.data.courtName} · {confirmationQuery.data.sport.name}
</p>
</div> </div>
<div className="grid gap-3 sm:grid-cols-2"> <div className="grid gap-3 sm:grid-cols-2">
<ShareWhatsappButton confirmation={confirmationQuery.data} /> <ShareWhatsappButton confirmation={confirmationQuery.data} />
<Button <Button
type="button" type="button"
className="h-11 w-full text-sm sm:text-base" className="h-12 w-full rounded-xl bg-emerald-600 text-sm font-semibold text-white hover:bg-emerald-500 sm:text-base"
onClick={() => { onClick={() => {
void navigate({ void navigate({
to: '/$complexSlug/booking', to: '/$complexSlug/booking',
@@ -104,6 +164,7 @@ export function PublicBookingConfirmationPage({
}} }}
> >
Hacer otra reserva Hacer otra reserva
<ArrowRight className="size-4" />
</Button> </Button>
</div> </div>
</div> </div>

View File

@@ -2,13 +2,6 @@ import PlayzerIcon from '@/assets/playzer-favicon-512-transparent.png';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Field, FieldError, FieldLabel } from '@/components/ui/field'; import { Field, FieldError, FieldLabel } from '@/components/ui/field';
import { Input } from '@/components/ui/input'; import { Input } from '@/components/ui/input';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { import {
Stepper, Stepper,
StepperIndicator, StepperIndicator,
@@ -84,6 +77,7 @@ type SelectedSlot = {
sportName: string; sportName: string;
startTime: string; startTime: string;
endTime: string; endTime: string;
price: number;
}; };
type BookingShellProps = { type BookingShellProps = {
@@ -186,6 +180,18 @@ function extractMessage(error: unknown, fallback: string) {
return fallback; return fallback;
} }
function formatBookingPrice(price: number): string {
if (price === 0) {
return 'Sin cargo';
}
return new Intl.NumberFormat('es-AR', {
style: 'currency',
currency: 'ARS',
maximumFractionDigits: Number.isInteger(price) ? 0 : 2,
}).format(price);
}
function getStep(selectedSlot: SelectedSlot | null, isValid: boolean) { function getStep(selectedSlot: SelectedSlot | null, isValid: boolean) {
if (!selectedSlot) return 1; if (!selectedSlot) return 1;
if (!isValid) return 3; if (!isValid) return 3;
@@ -638,6 +644,8 @@ function PublicBookingDesktop(props: BookingShellProps) {
)} )}
{isError && <StatusPanel>{errorMessage}</StatusPanel>} {isError && <StatusPanel>{errorMessage}</StatusPanel>}
{isLoading && <StatusPanel>Buscando disponibilidad...</StatusPanel>} {isLoading && <StatusPanel>Buscando disponibilidad...</StatusPanel>}
{selectedCourt && (
<>
<Panel className="overflow-hidden"> <Panel className="overflow-hidden">
<div className="flex items-center border-b border-white/10 px-6 py-5"> <div className="flex items-center border-b border-white/10 px-6 py-5">
<CourtHeader court={selectedCourt} complexName={props.complexName} /> <CourtHeader court={selectedCourt} complexName={props.complexName} />
@@ -680,6 +688,8 @@ function PublicBookingDesktop(props: BookingShellProps) {
<CourtDetails court={selectedCourt} /> <CourtDetails court={selectedCourt} />
<SelectedSlotCard {...props} /> <SelectedSlotCard {...props} />
</div> </div>
</>
)}
</section> </section>
</div> </div>
</PublicBookingPageChrome> </PublicBookingPageChrome>
@@ -711,16 +721,19 @@ function PublicBookingMobile(props: BookingShellProps) {
options={props.sports.map((sport) => ({ value: sport.id, label: sport.name }))} options={props.sports.map((sport) => ({ value: sport.id, label: sport.name }))}
/> />
)} )}
<MobileSelect {props.courts.length > 0 ? (
label="Cancha" <MobileCourtPicker
value={selectedCourt?.courtId ?? ''} courts={props.courts}
placeholder="Seleccioná" selectedCourtId={selectedCourt?.courtId}
onValueChange={props.onSelectCourt} onSelectCourt={props.onSelectCourt}
options={props.courts.map((court) => ({
value: court.courtId,
label: court.courtName,
}))}
/> />
) : (
!props.isLoading && (
<p className="rounded-md border border-white/10 bg-white/[0.035] p-3 text-sm text-white/62">
No hay canchas disponibles para esta fecha.
</p>
)
)}
</div> </div>
</Panel> </Panel>
@@ -756,25 +769,23 @@ function PublicBookingMobile(props: BookingShellProps) {
)} )}
{props.isLoading && <StatusPanel>Buscando disponibilidad...</StatusPanel>} {props.isLoading && <StatusPanel>Buscando disponibilidad...</StatusPanel>}
{props.isError && <StatusPanel>{props.errorMessage}</StatusPanel>} {props.isError && <StatusPanel>{props.errorMessage}</StatusPanel>}
{selectedCourt && (
<Panel className="overflow-hidden"> <Panel className="overflow-hidden">
<div className="p-3"> <div className="p-3">
<CourtHeader court={selectedCourt} compact /> <CourtHeader court={selectedCourt} compact />
<div className="mt-3">
<Legend />
</div> </div>
</div> <div className="border-t border-white/10 p-3">
<div className="border-t border-white/10 px-0 py-3"> <MobileAvailableSlots
<BookingTimeline
court={selectedCourt} court={selectedCourt}
selectedSlot={props.selectedSlot} selectedSlot={props.selectedSlot}
onSelectSlot={props.onSelectSlot} onSelectSlot={props.onSelectSlot}
compact
/> />
</div> </div>
<div className="px-3 pb-3"> <div className="px-3 pb-3">
<SelectedSlotCard {...props} compact /> <SelectedSlotCard {...props} compact />
</div> </div>
</Panel> </Panel>
)}
</div> </div>
</PublicBookingPageChrome> </PublicBookingPageChrome>
); );
@@ -876,34 +887,119 @@ function MobileSportSelector({
); );
} }
function MobileSelect({ function MobileCourtPicker({
label, courts,
value, selectedCourtId,
placeholder, onSelectCourt,
options,
onValueChange,
}: { }: {
label: string; courts: PublicAvailabilityCourt[];
value: string; selectedCourtId?: string;
placeholder: string; onSelectCourt: (courtId: string) => void;
options: { value: string; label: string }[];
onValueChange: (value: string) => void;
}) { }) {
return ( return (
<div className="grid grid-cols-[88px_minmax(0,1fr)] items-center border-b border-white/10 bg-white/[0.025] px-3 py-2 last:border-b-0"> <div className="border-b border-white/10 bg-white/[0.025] px-3 py-3 last:border-b-0">
<span className="text-xs text-white/66">{label}</span> <div className="grid grid-cols-2 gap-2">
<Select value={value} onValueChange={onValueChange}> {courts.map((court) => {
<SelectTrigger className="h-8 border-0 bg-transparent px-0 text-xs text-white shadow-none"> const isSelected = selectedCourtId === court.courtId;
<SelectValue placeholder={placeholder} />
</SelectTrigger> return (
<SelectContent> <button
{options.map((option) => ( key={court.courtId}
<SelectItem key={option.value} value={option.value}> type="button"
{option.label} onClick={() => onSelectCourt(court.courtId)}
</SelectItem> aria-pressed={isSelected}
))} className={`flex min-h-16 items-start gap-2 rounded-md border p-3 text-left transition ${
</SelectContent> isSelected
</Select> ? 'border-emerald-400 bg-emerald-500/20 text-white shadow-[inset_0_0_18px_rgba(16,185,129,0.12)]'
: 'border-white/10 bg-white/[0.045] text-white/72 active:border-white/25 active:bg-white/[0.075]'
}`}
>
<span
className={`mt-0.5 flex size-5 shrink-0 items-center justify-center rounded-full border ${
isSelected
? 'border-emerald-300 bg-emerald-400 text-[#061019]'
: 'border-white/18 text-transparent'
}`}
>
<Check className="size-3.5" />
</span>
<span className="min-w-0">
<span className="block truncate text-sm font-semibold">{court.courtName}</span>
<span className="mt-0.5 block truncate text-xs text-white/52">
{court.sport.name}
</span>
</span>
</button>
);
})}
</div>
</div>
);
}
function MobileAvailableSlots({
court,
selectedSlot,
onSelectSlot,
}: {
court: PublicAvailabilityCourt;
selectedSlot: SelectedSlot | null;
onSelectSlot: (slot: SelectedSlot) => void;
}) {
const slots = court.availableSlots;
return (
<div>
<div className="flex items-end justify-between gap-3">
<div>
<h3 className="text-base font-semibold">Horarios disponibles</h3>
<p className="mt-0.5 text-xs text-white/58">
Turnos de {court.slotDurationMinutes} minutos
</p>
</div>
<span className="shrink-0 text-xs font-medium text-emerald-300/90">
{slots.length} {slots.length === 1 ? 'turno' : 'turnos'}
</span>
</div>
{slots.length > 0 ? (
<div className="mt-3 grid grid-cols-3 gap-2">
{slots.map((slot) => {
const selected = isSlotSelected(slot, court.courtId, selectedSlot);
return (
<button
key={`${court.courtId}-${slot.startTime}`}
type="button"
onClick={() =>
onSelectSlot({
courtId: court.courtId,
courtName: court.courtName,
sportId: court.sport.id,
sportName: court.sport.name,
startTime: slot.startTime,
endTime: slot.endTime,
price: slot.price,
})
}
aria-pressed={selected}
className={`flex h-12 items-center justify-center gap-1.5 rounded-md border text-sm font-bold transition ${
selected
? 'border-emerald-300 bg-emerald-400 text-[#061019] shadow-lg shadow-emerald-500/20'
: 'border-emerald-500/45 bg-emerald-500/12 text-white active:bg-emerald-500/24'
}`}
>
{selected && <Check className="size-4" />}
{slot.startTime}
</button>
);
})}
</div>
) : (
<p className="mt-3 rounded-md border border-white/10 bg-white/[0.035] p-3 text-sm text-white/62">
No hay horarios disponibles para esta cancha.
</p>
)}
</div> </div>
); );
} }
@@ -1011,6 +1107,7 @@ function BookingTimeline({
sportName: court.sport.name, sportName: court.sport.name,
startTime: slot.startTime, startTime: slot.startTime,
endTime: slot.endTime, endTime: slot.endTime,
price: slot.price,
}); });
}} }}
className={`absolute top-7 flex h-12 min-w-[50px] items-center justify-center rounded border text-xs transition ${ className={`absolute top-7 flex h-12 min-w-[50px] items-center justify-center rounded border text-xs transition ${
@@ -1155,6 +1252,13 @@ function SelectedSlotCard(props: BookingShellProps & { compact?: boolean }) {
className={compact ? 'mt-4 space-y-3' : 'mt-5 grid gap-3'} className={compact ? 'mt-4 space-y-3' : 'mt-5 grid gap-3'}
onSubmit={handleSubmit(onSubmit)} onSubmit={handleSubmit(onSubmit)}
> >
<div className="flex items-center justify-between gap-3 rounded-md border border-emerald-400/20 bg-emerald-400/[0.06] px-3 py-2.5">
<span className="text-sm text-white/72">Precio del turno</span>
<span className="shrink-0 text-base font-bold text-white">
{formatBookingPrice(selectedSlot.price)}
</span>
</div>
<div className={compact ? 'space-y-3' : 'grid grid-cols-2 gap-3'}> <div className={compact ? 'space-y-3' : 'grid grid-cols-2 gap-3'}>
<Field data-invalid={Boolean(errors.customerName)}> <Field data-invalid={Boolean(errors.customerName)}>
<FieldLabel htmlFor="customerName" className="text-white/76"> <FieldLabel htmlFor="customerName" className="text-white/76">

View File

@@ -6,21 +6,32 @@ import { QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'; import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { RouterProvider } from '@tanstack/react-router'; import { RouterProvider } from '@tanstack/react-router';
import { TanStackRouterDevtools } from '@tanstack/router-devtools'; import { TanStackRouterDevtools } from '@tanstack/router-devtools';
import { StrictMode, useEffect } from 'react'; import { StrictMode, useEffect, useRef } from 'react';
import { createRoot } from 'react-dom/client'; import { createRoot } from 'react-dom/client';
import { router } from './router'; import { router } from './router';
import './index.css'; import './index.css';
function AppRouter() { function AppRouter() {
const auth = useAuth(); const auth = useAuth();
const prevAuthRef = useRef(auth);
if (auth !== prevAuthRef.current) {
prevAuthRef.current = auth;
router.update({ context: { auth, api: apiClient } });
}
useEffect(() => { useEffect(() => {
router.update({ context: { auth, api: apiClient } });
router.invalidate(); router.invalidate();
}, [auth.isAuthenticated, auth.loading, auth.user]); }, [auth.isAuthenticated, auth.loading, auth.user]);
useEffect(() => { useEffect(() => {
configureApiClient({ configureApiClient({
onForbidden: async () => { onForbidden: async (error) => {
if (error.message?.includes('verificar tu email')) {
return;
}
if (!auth.isAuthenticated) { if (!auth.isAuthenticated) {
return; return;
} }

View File

@@ -1,11 +1,15 @@
import { PublicBookingConfirmationPage } from '@/features/public-booking/public-booking-confirmation-page'; import { createFileRoute, lazyRouteComponent } from '@tanstack/react-router';
import { createFileRoute } from '@tanstack/react-router';
const PublicBookingConfirmationPage = lazyRouteComponent(
() => import('@/features/public-booking/public-booking-confirmation-page'),
'PublicBookingConfirmationPage'
);
export const Route = createFileRoute('/$complexSlug/booking/confirmed/$bookingCode')({ export const Route = createFileRoute('/$complexSlug/booking/confirmed/$bookingCode')({
component: PublicBookingConfirmationRouteComponent, component: RouteComponent,
}); });
function PublicBookingConfirmationRouteComponent() { function RouteComponent() {
const { complexSlug, bookingCode } = Route.useParams(); const { complexSlug, bookingCode } = Route.useParams();
return <PublicBookingConfirmationPage complexSlug={complexSlug} bookingCode={bookingCode} />; return <PublicBookingConfirmationPage complexSlug={complexSlug} bookingCode={bookingCode} />;

View File

@@ -1,11 +1,15 @@
import { PublicBookingPage } from '@/features/public-booking/public-booking-page'; import { createFileRoute, lazyRouteComponent } from '@tanstack/react-router';
import { createFileRoute } from '@tanstack/react-router';
const PublicBookingPage = lazyRouteComponent(
() => import('@/features/public-booking/public-booking-page'),
'PublicBookingPage'
);
export const Route = createFileRoute('/$complexSlug/booking/')({ export const Route = createFileRoute('/$complexSlug/booking/')({
component: PublicBookingIndexRouteComponent, component: RouteComponent,
}); });
function PublicBookingIndexRouteComponent() { function RouteComponent() {
const { complexSlug } = Route.useParams(); const { complexSlug } = Route.useParams();
return <PublicBookingPage complexSlug={complexSlug} />; return <PublicBookingPage complexSlug={complexSlug} />;

View File

@@ -1,5 +1,9 @@
import { ComplexSettingsPage } from '@/features/complex/complex-settings-page'; import { createFileRoute, lazyRouteComponent } from '@tanstack/react-router';
import { createFileRoute } from '@tanstack/react-router';
const ComplexSettingsPage = lazyRouteComponent(
() => import('@/features/complex/complex-settings-page'),
'ComplexSettingsPage'
);
export const Route = createFileRoute('/_app/_authenticated/complex/$slug/edit')({ export const Route = createFileRoute('/_app/_authenticated/complex/$slug/edit')({
component: RouteComponent, component: RouteComponent,

View File

@@ -1,5 +1,9 @@
import { ProfilePage } from '@/features/profile/profile-page'; import { createFileRoute, lazyRouteComponent } from '@tanstack/react-router';
import { createFileRoute } from '@tanstack/react-router';
const ProfilePage = lazyRouteComponent(
() => import('@/features/profile/profile-page'),
'ProfilePage'
);
export const Route = createFileRoute('/_app/profile')({ export const Route = createFileRoute('/_app/profile')({
component: ProfilePage, component: ProfilePage,

View File

@@ -1,5 +1,9 @@
import { SetupStepperPage } from '@/features/onboard/setup-stepper-page'; import { createFileRoute, lazyRouteComponent, redirect } from '@tanstack/react-router';
import { createFileRoute, redirect } from '@tanstack/react-router';
const SetupStepperPage = lazyRouteComponent(
() => import('@/features/onboard/setup-stepper-page'),
'SetupStepperPage'
);
export const Route = createFileRoute('/onboard/setup')({ export const Route = createFileRoute('/onboard/setup')({
beforeLoad: ({ context }) => { beforeLoad: ({ context }) => {

View File

@@ -3,4 +3,5 @@ set -e
cd /app/apps/backend cd /app/apps/backend
bun prisma migrate deploy bun prisma migrate deploy
bun prisma generate bun prisma generate
bun prisma/seed.ts
bun run start bun run start

View File

@@ -19,6 +19,7 @@ export const publicBookingSportSchema = z.object({
export const publicBookingSlotSchema = z.object({ export const publicBookingSlotSchema = z.object({
startTime: z.string().regex(TIME_REGEX), startTime: z.string().regex(TIME_REGEX),
endTime: z.string().regex(TIME_REGEX), endTime: z.string().regex(TIME_REGEX),
price: z.number().nonnegative(),
}) })
export const publicAvailabilityCourtSchema = z.object({ export const publicAvailabilityCourtSchema = z.object({
@@ -79,10 +80,12 @@ export const publicBookingSchema = z.object({
export const publicBookingConfirmationSchema = z.object({ export const publicBookingConfirmationSchema = z.object({
bookingCode: z.string().regex(BOOKING_CODE_REGEX), bookingCode: z.string().regex(BOOKING_CODE_REGEX),
complexName: z.string(), complexName: z.string(),
complexAddress: z.string().optional(),
complexSlug: z.string(), complexSlug: z.string(),
date: z.string().regex(ISO_DATE_REGEX), date: z.string().regex(ISO_DATE_REGEX),
startTime: z.string().regex(TIME_REGEX), startTime: z.string().regex(TIME_REGEX),
endTime: z.string().regex(TIME_REGEX), endTime: z.string().regex(TIME_REGEX),
price: z.number().nonnegative(),
courtName: z.string(), courtName: z.string(),
sport: publicBookingSportSchema, sport: publicBookingSportSchema,
status: z.enum(['CONFIRMED', 'CANCELLED', 'COMPLETED']), status: z.enum(['CONFIRMED', 'CANCELLED', 'COMPLETED']),