diff options
| author | Alberto Duarte Delgado <alberto@albertoduarte.com> | 2026-04-19 21:46:46 +0100 |
|---|---|---|
| committer | Alberto Duarte Delgado <alberto@albertoduarte.com> | 2026-04-19 21:46:46 +0100 |
| commit | be90a5f202f80bb423c6e0aaf1c4d5feca668f01 (patch) | |
| tree | c91081a6c60d2f1efb4de22c324721c5d798e3ee /src/features/reservations/hooks | |
| parent | 40cc6cea25d048c2e77e11bbfea0cd1e5eb784f6 (diff) | |
| parent | 4d0962a44715f71acd2fc9ea59bf87d8da70f662 (diff) | |
Merge branch 'feature/anita' into develop
Diffstat (limited to 'src/features/reservations/hooks')
| -rw-r--r-- | src/features/reservations/hooks/useCreateReservation.ts | 88 | ||||
| -rw-r--r-- | src/features/reservations/hooks/useReservations.ts | 40 | ||||
| -rw-r--r-- | src/features/reservations/hooks/useUpdateReservation.ts | 178 |
3 files changed, 259 insertions, 47 deletions
diff --git a/src/features/reservations/hooks/useCreateReservation.ts b/src/features/reservations/hooks/useCreateReservation.ts index 9cf8a46..9bc0692 100644 --- a/src/features/reservations/hooks/useCreateReservation.ts +++ b/src/features/reservations/hooks/useCreateReservation.ts @@ -1,13 +1,18 @@ -import { useState } from 'react'; -import { router } from 'expo-router'; import { - isReservationConflictError, - reservationsService, -} from '@/features/reservations/services/reservationsService'; -import { validateReservation } from '@/features/reservations/domain/validateReservation'; -import { CreateReservationInput } from '@/features/reservations/types'; -import { useAuthSession } from '@/providers/AuthProvider'; -import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage'; + formatAvailableSlots, + getAvailableTimeSlots, +} from "@/features/reservations/domain/getAvailableTimeSlots"; +import { validateReservation } from "@/features/reservations/domain/validateReservation"; +import { + isReservationConflictError, + reservationsService, +} from "@/features/reservations/services/reservationsService"; +import { CreateReservationInput } from "@/features/reservations/types"; +import { useAuthSession } from "@/providers/AuthProvider"; +import { getErrorMessage } from "@/shared/lib/errors/getErrorMessage"; +import { router } from "expo-router"; +import { useState } from "react"; +import { Alert, Platform } from "react-native"; type UseCreateReservationParams = { officeId?: string; @@ -18,14 +23,14 @@ type UseCreateReservationParams = { function getTodayDate(): string { const today = new Date(); const year = today.getFullYear(); - const month = String(today.getMonth() + 1).padStart(2, '0'); - const day = String(today.getDate()).padStart(2, '0'); + const month = String(today.getMonth() + 1).padStart(2, "0"); + const day = String(today.getDate()).padStart(2, "0"); return `${year}-${month}-${day}`; } function normalizeDateInput(value: string): string { - const digits = value.replace(/\D/g, '').slice(0, 8); + const digits = value.replace(/\D/g, "").slice(0, 8); if (digits.length <= 4) { return digits; @@ -39,7 +44,7 @@ function normalizeDateInput(value: string): string { } function normalizeTimeInput(value: string): string { - const digits = value.replace(/\D/g, '').slice(0, 4); + const digits = value.replace(/\D/g, "").slice(0, 4); if (digits.length <= 2) { return digits; @@ -55,11 +60,10 @@ export function useCreateReservation({ const { user } = useAuthSession(); const [date, setDate] = useState(getTodayDate()); - const [startTime, setStartTime] = useState(''); - const [endTime, setEndTime] = useState(''); + const [startTime, setStartTime] = useState(""); + const [endTime, setEndTime] = useState(""); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState<string | null>(null); - const [successMessage, setSuccessMessage] = useState<string | null>(null); const handleDateChange = (value: string) => { setError(null); @@ -84,14 +88,13 @@ export function useCreateReservation({ const submit = async () => { try { setError(null); - setSuccessMessage(null); setIsSubmitting(true); const input: CreateReservationInput = { - officeId: officeId ?? '', - officeName: officeName ?? '', - userId: user?.uid ?? '', - userEmail: user?.email ?? '', + officeId: officeId ?? "", + officeName: officeName ?? "", + userId: user?.uid ?? "", + userEmail: user?.email ?? "", date: date.trim(), startTime: startTime.trim(), endTime: endTime.trim(), @@ -106,19 +109,45 @@ export function useCreateReservation({ await reservationsService.create(input); - setSuccessMessage('Reserva creada correctamente'); - setDate(getTodayDate()); - setStartTime(''); - setEndTime(''); - - router.replace('/(protected)/(tabs)/reservations'); + // mostrar popup de confirmacion + if (Platform.OS === "web") { + const confirmed = window.confirm("Reserva creada correctamente"); + if (confirmed) { + router.replace("/(protected)/(tabs)/reservations"); + } + } else { + Alert.alert("¡Éxito!", "Reserva creada correctamente", [ + { + text: "OK", + onPress: () => router.replace("/(protected)/(tabs)/reservations"), + }, + ]); + } } catch (err) { if (isReservationConflictError(err)) { - setError('Ya existe una reserva que se solapa con ese horario'); + // cuando hay conflicto, obtener las reservas de ese dia + const reservasDelDia = await reservationsService.getByOfficeAndDate( + officeId ?? "", + date.trim(), + ); + + // calcular las franjas disponibles considerando las reservas existentes + const availableSlots = getAvailableTimeSlots( + date.trim(), + reservasDelDia, + ); + + // formatear las franjas como mensaje legible + const slotsMessage = formatAvailableSlots(availableSlots); + + // mostrar error con las franjas disponibles + setError( + `Ya existe una reserva que se solapa con ese horario.\n\n${slotsMessage}`, + ); return; } - setError(getErrorMessage(err, 'No se pudo crear la reserva')); + setError(getErrorMessage(err, "No se pudo crear la reserva")); } finally { setIsSubmitting(false); } @@ -131,7 +160,6 @@ export function useCreateReservation({ isFormComplete, isSubmitting, error, - successMessage, setDate: handleDateChange, setStartTime: handleStartTimeChange, setEndTime: handleEndTimeChange, diff --git a/src/features/reservations/hooks/useReservations.ts b/src/features/reservations/hooks/useReservations.ts index a3c1944..86c6ad3 100644 --- a/src/features/reservations/hooks/useReservations.ts +++ b/src/features/reservations/hooks/useReservations.ts @@ -1,9 +1,9 @@ -import { useCallback, useEffect, useState } from 'react'; -import { useFocusEffect } from 'expo-router'; -import { reservationsService } from '@/features/reservations/services/reservationsService'; -import { Reservation } from '@/features/reservations/types'; -import { useAuthSession } from '@/providers/AuthProvider'; -import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage'; +import { reservationsService } from "@/features/reservations/services/reservationsService"; +import { Reservation } from "@/features/reservations/types"; +import { useAuthSession } from "@/providers/AuthProvider"; +import { getErrorMessage } from "@/shared/lib/errors/getErrorMessage"; +import { useFocusEffect } from "expo-router"; +import { useCallback, useEffect, useState } from "react"; export function useReservations() { const { user } = useAuthSession(); @@ -11,8 +11,12 @@ export function useReservations() { const [reservations, setReservations] = useState<Reservation[]>([]); const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null); - const [cancelingReservationId, setCancelingReservationId] = useState<string | null>(null); - const [checkingInReservationId, setCheckingInReservationId] = useState<string | null>(null); + const [cancelingReservationId, setCancelingReservationId] = useState< + string | null + >(null); + const [checkingInReservationId, setCheckingInReservationId] = useState< + string | null + >(null); const loadReservations = async () => { if (!user?.uid) { @@ -28,7 +32,7 @@ export function useReservations() { const data = await reservationsService.getByUserId(user.uid); setReservations(data); } catch (err) { - setError(getErrorMessage(err, 'No se pudieron cargar las reservas')); + setError(getErrorMessage(err, "No se pudieron cargar las reservas")); } finally { setLoading(false); } @@ -38,10 +42,10 @@ export function useReservations() { loadReservations(); }, [user?.uid]); - useFocusEffect( + useFocusEffect( useCallback(() => { void loadReservations(); - }, [user?.uid]) + }, [user?.uid]), ); const cancelReservation = async (reservationId: string) => { @@ -52,7 +56,7 @@ export function useReservations() { await reservationsService.cancel(reservationId); await loadReservations(); } catch (err) { - setError(getErrorMessage(err, 'No se pudo cancelar la reserva')); + setError(getErrorMessage(err, "No se pudo cancelar la reserva")); } finally { setCancelingReservationId(null); } @@ -66,7 +70,7 @@ export function useReservations() { await reservationsService.checkIn(reservationId); await loadReservations(); } catch (err) { - setError(getErrorMessage(err, 'No se pudo registrar la llegada')); + setError(getErrorMessage(err, "No se pudo registrar la llegada")); } finally { setCheckingInReservationId(null); } @@ -74,11 +78,13 @@ export function useReservations() { return { reservations, - activeReservations: reservations - .filter((reservation) => reservation.status === 'active') - .reverse(), + // reservas activas en orden normal para mostrar la mas proxima primero + activeReservations: reservations.filter( + (reservation) => reservation.status === "active", + ), + // historial invertido para mostrar la mas reciente primero historyReservations: reservations - .filter((reservation) => reservation.status !== 'active') + .filter((reservation) => reservation.status !== "active") .reverse(), loading, error, diff --git a/src/features/reservations/hooks/useUpdateReservation.ts b/src/features/reservations/hooks/useUpdateReservation.ts new file mode 100644 index 0000000..c26f12c --- /dev/null +++ b/src/features/reservations/hooks/useUpdateReservation.ts @@ -0,0 +1,178 @@ +import { + formatAvailableSlots, + getAvailableTimeSlots, +} from "@/features/reservations/domain/getAvailableTimeSlots"; +import { validateReservation } from "@/features/reservations/domain/validateReservation"; +import { + isReservationConflictError, + reservationsService, +} from "@/features/reservations/services/reservationsService"; +import { useAuthSession } from "@/providers/AuthProvider"; +import { getErrorMessage } from "@/shared/lib/errors/getErrorMessage"; +import { router } from "expo-router"; +import { useState } from "react"; +import { Alert, Platform } from "react-native"; + +type UseUpdateReservationParams = { + reservationId: string; + officeId: string; + officeName: string; + oldDate: string; + oldStartTime: string; + oldEndTime: string; +}; + +function normalizeDateInput(value: string): string { + const digits = value.replace(/\D/g, "").slice(0, 8); + + if (digits.length <= 4) { + return digits; + } + + if (digits.length <= 6) { + return `${digits.slice(0, 4)}-${digits.slice(4)}`; + } + + return `${digits.slice(0, 4)}-${digits.slice(4, 6)}-${digits.slice(6)}`; +} + +function normalizeTimeInput(value: string): string { + const digits = value.replace(/\D/g, "").slice(0, 4); + + if (digits.length <= 2) { + return digits; + } + + return `${digits.slice(0, 2)}:${digits.slice(2)}`; +} + +export function useUpdateReservation({ + reservationId, + officeId, + officeName, + oldDate, + oldStartTime, + oldEndTime, +}: UseUpdateReservationParams) { + const { user } = useAuthSession(); + + // precarga los valores anteriores para que el usuario vea lo que habia antes + const [date, setDate] = useState(oldDate); + const [startTime, setStartTime] = useState(oldStartTime); + const [endTime, setEndTime] = useState(oldEndTime); + const [isSubmitting, setIsSubmitting] = useState(false); + const [error, setError] = useState<string | null>(null); + + const handleDateChange = (value: string) => { + setError(null); + setDate(normalizeDateInput(value)); + }; + + const handleStartTimeChange = (value: string) => { + setError(null); + setStartTime(normalizeTimeInput(value)); + }; + + const handleEndTimeChange = (value: string) => { + setError(null); + setEndTime(normalizeTimeInput(value)); + }; + + const isFormComplete = + date.trim().length === 10 && + startTime.trim().length === 5 && + endTime.trim().length === 5; + + const submit = async () => { + try { + setError(null); + setIsSubmitting(true); + + // validacion igual que en create, usando los nuevos valores + const validationInput = { + officeId, + officeName, + userId: user?.uid ?? "", + userEmail: user?.email ?? "", + date: date.trim(), + startTime: startTime.trim(), + endTime: endTime.trim(), + }; + + const validationError = validateReservation(validationInput); + + if (validationError) { + setError(validationError); + return; + } + + // llamar al servicio de actualizacion con los datos antiguos y nuevos + await reservationsService.update({ + reservationId, + userId: user?.uid ?? "", + officeId, + date: date.trim(), + startTime: startTime.trim(), + endTime: endTime.trim(), + oldDate, + oldStartTime, + oldEndTime, + }); + + // mostrar popup de confirmacion + if (Platform.OS === "web") { + const confirmed = window.confirm("Reserva actualizada correctamente"); + if (confirmed) { + router.replace("/(protected)/(tabs)/reservations"); + } + } else { + Alert.alert("¡Éxito!", "Reserva actualizada correctamente", [ + { + text: "OK", + onPress: () => router.replace("/(protected)/(tabs)/reservations"), + }, + ]); + } + } catch (err) { + if (isReservationConflictError(err)) { + // cuando hay conflicto, obtener las reservas de ese dia + const reservasDelDia = await reservationsService.getByOfficeAndDate( + officeId, + date.trim(), + ); + + // calcular las franjas disponibles considerando las reservas existentes + const availableSlots = getAvailableTimeSlots( + date.trim(), + reservasDelDia, + ); + + // formatear las franjas como mensaje legible + const slotsMessage = formatAvailableSlots(availableSlots); + + // mostrar error con las franjas disponibles + setError( + `Ya existe una reserva que se solapa con ese horario.\n\n${slotsMessage}`, + ); + return; + } + + setError(getErrorMessage(err, "No se pudo actualizar la reserva")); + } finally { + setIsSubmitting(false); + } + }; + + return { + date, + startTime, + endTime, + isFormComplete, + isSubmitting, + error, + setDate: handleDateChange, + setStartTime: handleStartTimeChange, + setEndTime: handleEndTimeChange, + submit, + }; +} |