From ed52756173468bfe98cdb62d95483b4949b27351 Mon Sep 17 00:00:00 2001 From: Anita Date: Sun, 19 Apr 2026 19:20:09 +0100 Subject: feat(reservations): edición de reservas + validación de disponibilidad + mejoras de flujo refs #7 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../reservations/domain/getAvailableTimeSlots.ts | 89 +++++ .../reservations/hooks/useCreateReservation.ts | 88 +++-- src/features/reservations/hooks/useReservations.ts | 40 ++- .../reservations/hooks/useUpdateReservation.ts | 178 ++++++++++ .../reservations/services/reservationsService.ts | 391 +++++++++++++++++---- src/features/reservations/types.ts | 3 +- 6 files changed, 673 insertions(+), 116 deletions(-) create mode 100644 src/features/reservations/domain/getAvailableTimeSlots.ts create mode 100644 src/features/reservations/hooks/useUpdateReservation.ts (limited to 'src/features/reservations') diff --git a/src/features/reservations/domain/getAvailableTimeSlots.ts b/src/features/reservations/domain/getAvailableTimeSlots.ts new file mode 100644 index 0000000..54a9138 --- /dev/null +++ b/src/features/reservations/domain/getAvailableTimeSlots.ts @@ -0,0 +1,89 @@ +import { Reservation } from "@/features/reservations/types"; + +type TimeSlot = { + startTime: string; + endTime: string; +}; + +// funcion para convertir tiempo en formato HH:MM a minutos totales +function timeToMinutes(time: string): number { + const [hours, minutes] = time.split(":").map(Number); + return hours * 60 + minutes; +} + +// funcion para convertir minutos totales a formato HH:MM +function minutesToTime(minutes: number): string { + const hours = Math.floor(minutes / 60); + const mins = minutes % 60; + return `${String(hours).padStart(2, "0")}:${String(mins).padStart(2, "0")}`; +} + +// calcula las franjas horarias disponibles considerando las reservas existentes +// recibe la fecha, las reservas activas de ese dia y retorna las franjas libres +export function getAvailableTimeSlots( + date: string, + existingReservations: Reservation[], +): TimeSlot[] { + // horario operativo de la aplicacion + const dayStartMinutes = timeToMinutes("08:00"); + const dayEndMinutes = timeToMinutes("20:00"); + + // si no hay reservas ese dia, toda la jornada esta disponible + if (existingReservations.length === 0) { + return [ + { + startTime: "08:00", + endTime: "20:00", + }, + ]; + } + + // ordenar reservas por hora de inicio + const sortedReservations = [...existingReservations].sort((a, b) => { + const timeA = timeToMinutes(a.startTime); + const timeB = timeToMinutes(b.startTime); + return timeA - timeB; + }); + + const availableSlots: TimeSlot[] = []; + let currentMinutes = dayStartMinutes; + + // iterar sobre cada reserva para encontrar huecos libres + for (const reservation of sortedReservations) { + const reservationStartMinutes = timeToMinutes(reservation.startTime); + const reservationEndMinutes = timeToMinutes(reservation.endTime); + + // si hay espacio antes de esta reserva, es una franja disponible + if (currentMinutes < reservationStartMinutes) { + availableSlots.push({ + startTime: minutesToTime(currentMinutes), + endTime: minutesToTime(reservationStartMinutes), + }); + } + + // actualizar la posicion actual para el siguiente hueco + currentMinutes = Math.max(currentMinutes, reservationEndMinutes); + } + + // si queda tiempo libre hasta el final del dia, agregarlo + if (currentMinutes < dayEndMinutes) { + availableSlots.push({ + startTime: minutesToTime(currentMinutes), + endTime: minutesToTime(dayEndMinutes), + }); + } + + return availableSlots; +} + +// formatea las franjas disponibles como un mensaje legible +// separa cada franja en una linea diferente +export function formatAvailableSlots(slots: TimeSlot[]): string { + if (slots.length === 0) { + return "No hay franjas disponibles en este día"; + } + + // crear una linea por cada franja, separadas por salto de linea + const slotTexts = slots.map((slot) => `${slot.startTime} - ${slot.endTime}`); + return "Franjas disponibles:\n" + slotTexts.join(",\n"); +} 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(null); - const [successMessage, setSuccessMessage] = useState(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([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); - const [cancelingReservationId, setCancelingReservationId] = useState(null); - const [checkingInReservationId, setCheckingInReservationId] = useState(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(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, + }; +} diff --git a/src/features/reservations/services/reservationsService.ts b/src/features/reservations/services/reservationsService.ts index 176bbce..ac67001 100644 --- a/src/features/reservations/services/reservationsService.ts +++ b/src/features/reservations/services/reservationsService.ts @@ -1,3 +1,14 @@ +import { + CreateReservationInput, + Reservation, + ReservationStatus, +} from "@/features/reservations/types"; +import { db } from "@/shared/lib/firebase/config"; +import { + mockDelay, + mockReservationLocks, + mockReservations, +} from "@/shared/lib/mockData"; import { collection, doc, @@ -6,44 +17,40 @@ import { query, runTransaction, serverTimestamp, - writeBatch, where, -} from 'firebase/firestore'; -import { db } from '@/shared/lib/firebase/config'; -import { - CreateReservationInput, - Reservation, - ReservationStatus, -} from '@/features/reservations/types'; + writeBatch, +} from "firebase/firestore"; + +const USE_MOCK = process.env.EXPO_PUBLIC_USE_MOCK_DATA === "true"; function mapReservationStatus(value: unknown): ReservationStatus { - if (value === 'completed') { - return 'completed'; + if (value === "completed") { + return "completed"; } - return value === 'cancelled' ? 'cancelled' : 'active'; + return value === "cancelled" ? "cancelled" : "active"; } function mapReservation(id: string, data: any): Reservation { return { id, - officeId: data.officeId ?? '', - officeName: data.officeName ?? '', - userId: data.userId ?? '', - userEmail: data.userEmail ?? '', - date: data.date ?? '', - startTime: data.startTime ?? '', - endTime: data.endTime ?? '', + officeId: data.officeId ?? "", + officeName: data.officeName ?? "", + userId: data.userId ?? "", + userEmail: data.userEmail ?? "", + date: data.date ?? "", + startTime: data.startTime ?? "", + endTime: data.endTime ?? "", status: mapReservationStatus(data.status), checkInAt: data.checkInAt, createdAt: data.createdAt, }; } -const RESERVATION_CONFLICT_ERROR = 'RESERVATION_CONFLICT'; +const RESERVATION_CONFLICT_ERROR = "RESERVATION_CONFLICT"; function parseTimeToMinutes(value: string): number { - const [hours, minutes] = value.split(':').map(Number); + const [hours, minutes] = value.split(":").map(Number); return hours * 60 + minutes; } @@ -51,7 +58,7 @@ function formatMinuteSlot(totalMinutes: number): string { const hours = Math.floor(totalMinutes / 60); const minutes = totalMinutes % 60; - return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}`; + return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}`; } function buildReservationLockIds(input: { @@ -66,19 +73,26 @@ function buildReservationLockIds(input: { for (let minute = startMinutes; minute < endMinutes; minute += 1) { lockIds.push( - `${input.officeId}__${input.date}__${formatMinuteSlot(minute)}` + `${input.officeId}__${input.date}__${formatMinuteSlot(minute)}`, ); } return lockIds; } -function getReservationEndDate(reservation: Pick): Date { +function getReservationEndDate( + reservation: Pick, +): Date { return new Date(`${reservation.date}T${reservation.endTime}:00`); } -function isPastActiveReservation(reservation: Reservation, now = new Date()): boolean { - return reservation.status === 'active' && getReservationEndDate(reservation) < now; +function isPastActiveReservation( + reservation: Reservation, + now = new Date(), +): boolean { + return ( + reservation.status === "active" && getReservationEndDate(reservation) < now + ); } type ReservationRecord = { @@ -88,15 +102,52 @@ type ReservationRecord = { export const reservationsService = { async create(input: CreateReservationInput): Promise { - const reservationsCollection = collection(db, 'reservations'); - const reservationLocksCollection = collection(db, 'reservationLocks'); + if (USE_MOCK) { + await mockDelay(); + const lockId = `${input.officeId}__${input.date}__${input.startTime}`; + const newLockIds = buildReservationLockIds(input); + + // Simular conflicto si hay locks existentes + for (const lockId of newLockIds) { + if (mockReservationLocks[lockId]) { + throw new Error(RESERVATION_CONFLICT_ERROR); + } + } + + // Crear locks simulados + for (const lockId of newLockIds) { + mockReservationLocks[lockId] = { + reservationId: `res-mock-${Date.now()}`, + userId: input.userId, + officeId: input.officeId, + date: input.date, + time: lockId.split("__")[2], + }; + } + + // Agregar reserva al array simulado + mockReservations.push({ + id: `res-mock-${Date.now()}`, + ...input, + lockIds: newLockIds, + status: "active", + createdAt: new Date(), + checkInAt: null, + }); + return; + } + + const reservationsCollection = collection(db, "reservations"); + const reservationLocksCollection = collection(db, "reservationLocks"); const reservationRef = doc(reservationsCollection); const lockIds = buildReservationLockIds(input); await runTransaction(db, async (transaction) => { - const lockRefs = lockIds.map((lockId) => doc(reservationLocksCollection, lockId)); + const lockRefs = lockIds.map((lockId) => + doc(reservationLocksCollection, lockId), + ); const lockSnapshots = await Promise.all( - lockRefs.map((lockRef) => transaction.get(lockRef)) + lockRefs.map((lockRef) => transaction.get(lockRef)), ); for (const lockSnapshot of lockSnapshots) { @@ -111,39 +162,63 @@ export const reservationsService = { userId: input.userId, officeId: input.officeId, date: input.date, - time: lockIds[index].split('__')[2], + time: lockIds[index].split("__")[2], }); } transaction.set(reservationRef, { ...input, lockIds, - status: 'active', + status: "active", createdAt: serverTimestamp(), }); }); }, async cancel(reservationId: string): Promise { - const reservationRef = doc(db, 'reservations', reservationId); - const reservationLocksCollection = collection(db, 'reservationLocks'); + if (USE_MOCK) { + await mockDelay(); + const reservation = mockReservations.find((r) => r.id === reservationId); + if (!reservation) { + throw new Error("La reserva no existe"); + } + if (reservation.status === "cancelled") { + return; + } + reservation.status = "cancelled"; + + // Limpiar locks simulados + const lockIds = + reservation.lockIds || buildReservationLockIds(reservation); + for (const lockId of lockIds) { + delete mockReservationLocks[lockId]; + } + return; + } + + const reservationRef = doc(db, "reservations", reservationId); + const reservationLocksCollection = collection(db, "reservationLocks"); await runTransaction(db, async (transaction) => { const reservationSnapshot = await transaction.get(reservationRef); if (!reservationSnapshot.exists()) { - throw new Error('La reserva no existe'); + throw new Error("La reserva no existe"); } - const reservation = mapReservation(reservationSnapshot.id, reservationSnapshot.data()); + const reservation = mapReservation( + reservationSnapshot.id, + reservationSnapshot.data(), + ); - if (reservation.status === 'cancelled') { + if (reservation.status === "cancelled") { return; } const storedLockIds = reservationSnapshot.data().lockIds; const lockIds = - Array.isArray(storedLockIds) && storedLockIds.every((value) => typeof value === 'string') + Array.isArray(storedLockIds) && + storedLockIds.every((value) => typeof value === "string") ? storedLockIds : buildReservationLockIds(reservation); @@ -152,25 +227,44 @@ export const reservationsService = { } transaction.update(reservationRef, { - status: 'cancelled', + status: "cancelled", }); }); }, async checkIn(reservationId: string): Promise { - const reservationRef = doc(db, 'reservations', reservationId); + if (USE_MOCK) { + await mockDelay(); + const reservation = mockReservations.find((r) => r.id === reservationId); + if (!reservation) { + throw new Error("La reserva no existe"); + } + if (reservation.status !== "active") { + throw new Error("Solo puedes hacer check-in en reservas activas"); + } + if (reservation.checkInAt) { + return; + } + reservation.checkInAt = new Date(); + return; + } + + const reservationRef = doc(db, "reservations", reservationId); await runTransaction(db, async (transaction) => { const reservationSnapshot = await transaction.get(reservationRef); if (!reservationSnapshot.exists()) { - throw new Error('La reserva no existe'); + throw new Error("La reserva no existe"); } - const reservation = mapReservation(reservationSnapshot.id, reservationSnapshot.data()); + const reservation = mapReservation( + reservationSnapshot.id, + reservationSnapshot.data(), + ); - if (reservation.status !== 'active') { - throw new Error('Solo puedes hacer check-in en reservas activas'); + if (reservation.status !== "active") { + throw new Error("Solo puedes hacer check-in en reservas activas"); } if (reservation.checkInAt) { @@ -184,35 +278,49 @@ export const reservationsService = { }, async getByUserId(userId: string): Promise { + if (USE_MOCK) { + await mockDelay(); + return mockReservations + .filter((r) => r.userId === userId) + .sort((a, b) => { + const dateCompare = a.date.localeCompare(b.date); + if (dateCompare !== 0) return dateCompare; + return a.startTime.localeCompare(b.startTime); + }); + } + const q = query( - collection(db, 'reservations'), - where('userId', '==', userId), - orderBy('date', 'asc'), - orderBy('startTime', 'asc') + collection(db, "reservations"), + where("userId", "==", userId), + orderBy("date", "asc"), + orderBy("startTime", "asc"), ); const snapshot = await getDocs(q); - const reservationRecords: ReservationRecord[] = snapshot.docs.map((snapshotDoc) => { - const rawData = snapshotDoc.data() as Record; - - return { - reservation: mapReservation(snapshotDoc.id, rawData), - rawData, - }; - }); + const reservationRecords: ReservationRecord[] = snapshot.docs.map( + (snapshotDoc) => { + const rawData = snapshotDoc.data() as Record; + + return { + reservation: mapReservation(snapshotDoc.id, rawData), + rawData, + }; + }, + ); const reservations = reservationRecords.map((record) => record.reservation); const reservationsToComplete = reservationRecords.filter((record) => - isPastActiveReservation(record.reservation) + isPastActiveReservation(record.reservation), ); if (reservationsToComplete.length > 0) { const batch = writeBatch(db); - const reservationLocksCollection = collection(db, 'reservationLocks'); + const reservationLocksCollection = collection(db, "reservationLocks"); for (const { reservation, rawData } of reservationsToComplete) { const storedLockIds = rawData.lockIds; const lockIds = - Array.isArray(storedLockIds) && storedLockIds.every((value) => typeof value === 'string') + Array.isArray(storedLockIds) && + storedLockIds.every((value) => typeof value === "string") ? storedLockIds : buildReservationLockIds(reservation); @@ -220,8 +328,8 @@ export const reservationsService = { batch.delete(doc(reservationLocksCollection, lockId)); } - batch.update(doc(db, 'reservations', reservation.id), { - status: 'completed', + batch.update(doc(db, "reservations", reservation.id), { + status: "completed", }); } @@ -229,27 +337,174 @@ export const reservationsService = { return reservations.map((reservation) => isPastActiveReservation(reservation) - ? { ...reservation, status: 'completed' } - : reservation + ? { ...reservation, status: "completed" } + : reservation, ); } return reservations; }, - async getByOfficeAndDate(officeId: string, date: string): Promise { + async getByOfficeAndDate( + officeId: string, + date: string, + ): Promise { + if (USE_MOCK) { + await mockDelay(); + return mockReservations + .filter( + (r) => + r.officeId === officeId && r.date === date && r.status === "active", + ) + .sort((a, b) => a.startTime.localeCompare(b.startTime)); + } + const q = query( - collection(db, 'reservations'), - where('officeId', '==', officeId), - where('date', '==', date), - where('status', '==', 'active'), - orderBy('startTime', 'asc') + collection(db, "reservations"), + where("officeId", "==", officeId), + where("date", "==", date), + where("status", "==", "active"), + orderBy("startTime", "asc"), ); const snapshot = await getDocs(q); return snapshot.docs.map((item) => mapReservation(item.id, item.data())); }, + + async update(input: { + reservationId: string; + userId: string; + officeId: string; + date: string; + startTime: string; + endTime: string; + oldDate: string; + oldStartTime: string; + oldEndTime: string; + }): Promise { + if (USE_MOCK) { + await mockDelay(); + const reservation = mockReservations.find( + (r) => r.id === input.reservationId, + ); + + if (!reservation) { + throw new Error("La reserva no existe"); + } + + // Generar nuevos bloqueos + const newLockIds = buildReservationLockIds({ + officeId: input.officeId, + date: input.date, + startTime: input.startTime, + endTime: input.endTime, + }); + + // Verificar conflictos + for (const lockId of newLockIds) { + if (mockReservationLocks[lockId]) { + throw new Error(RESERVATION_CONFLICT_ERROR); + } + } + + // Limpiar locks antiguos + const oldLockIds = buildReservationLockIds({ + officeId: input.officeId, + date: input.oldDate, + startTime: input.oldStartTime, + endTime: input.oldEndTime, + }); + + for (const lockId of oldLockIds) { + delete mockReservationLocks[lockId]; + } + + // Crear nuevos locks + for (const lockId of newLockIds) { + mockReservationLocks[lockId] = { + reservationId: input.reservationId, + userId: input.userId, + officeId: input.officeId, + date: input.date, + time: lockId.split("__")[2], + }; + } + + // Actualizar reserva + reservation.date = input.date; + reservation.startTime = input.startTime; + reservation.endTime = input.endTime; + reservation.lockIds = newLockIds; + return; + } + + const reservationRef = doc(db, "reservations", input.reservationId); + const reservationLocksCollection = collection(db, "reservationLocks"); + + // generar los bloqueos antiguos que necesitan ser eliminados + const oldLockIds = buildReservationLockIds({ + officeId: input.officeId, + date: input.oldDate, + startTime: input.oldStartTime, + endTime: input.oldEndTime, + }); + + // generar los nuevos bloqueos que se van a crear + const newLockIds = buildReservationLockIds({ + officeId: input.officeId, + date: input.date, + startTime: input.startTime, + endTime: input.endTime, + }); + + await runTransaction(db, async (transaction) => { + // verificar que la reserva existe + const reservationSnapshot = await transaction.get(reservationRef); + + if (!reservationSnapshot.exists()) { + throw new Error("La reserva no existe"); + } + + // verificar que todos los nuevos bloqueos estan disponibles + const newLockRefs = newLockIds.map((lockId) => + doc(reservationLocksCollection, lockId), + ); + const newLockSnapshots = await Promise.all( + newLockRefs.map((lockRef) => transaction.get(lockRef)), + ); + + for (const lockSnapshot of newLockSnapshots) { + if (lockSnapshot.exists()) { + throw new Error(RESERVATION_CONFLICT_ERROR); + } + } + + // eliminar los bloqueos antiguos + for (const lockId of oldLockIds) { + transaction.delete(doc(reservationLocksCollection, lockId)); + } + + // crear los nuevos bloqueos + for (const [index, lockRef] of newLockRefs.entries()) { + transaction.set(lockRef, { + reservationId: input.reservationId, + userId: input.userId, + officeId: input.officeId, + date: input.date, + time: newLockIds[index].split("__")[2], + }); + } + + // actualizar la reserva con los nuevos datos y bloqueos + transaction.update(reservationRef, { + date: input.date, + startTime: input.startTime, + endTime: input.endTime, + lockIds: newLockIds, + }); + }); + }, }; export function isReservationConflictError(error: unknown): boolean { diff --git a/src/features/reservations/types.ts b/src/features/reservations/types.ts index 5b36351..e29354e 100644 --- a/src/features/reservations/types.ts +++ b/src/features/reservations/types.ts @@ -1,4 +1,4 @@ -export type ReservationStatus = 'active' | 'completed' | 'cancelled'; +export type ReservationStatus = "active" | "completed" | "cancelled"; export type Reservation = { id: string; @@ -12,6 +12,7 @@ export type Reservation = { status: ReservationStatus; checkInAt?: unknown; createdAt?: unknown; + lockIds?: string[]; }; export type CreateReservationInput = { -- cgit v1.2.3-54-g00ecf