diff options
| author | Anita <ana.tqtc@gmail.com> | 2026-04-19 19:20:09 +0100 |
|---|---|---|
| committer | Anita <ana.tqtc@gmail.com> | 2026-04-19 19:20:09 +0100 |
| commit | ed52756173468bfe98cdb62d95483b4949b27351 (patch) | |
| tree | 9b7bb8f068abb9f879e4e629ab0892319ed31d29 /src/features/reservations/hooks/useUpdateReservation.ts | |
| parent | e68c8c3e71b0130b8a749cc40a2760fd71c4040c (diff) | |
feat(reservations): edición de reservas + validación de disponibilidad + mejoras de flujo refs #7
Diffstat (limited to 'src/features/reservations/hooks/useUpdateReservation.ts')
| -rw-r--r-- | src/features/reservations/hooks/useUpdateReservation.ts | 178 |
1 files changed, 178 insertions, 0 deletions
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, + }; +} |