From bd4a70dab890153617cad4e0be1364941993d51d Mon Sep 17 00:00:00 2001 From: Alberto Duarte Delgado Date: Wed, 1 Apr 2026 00:56:41 +0100 Subject: firestore rules y logica de cancelación de reservas MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../reservations/domain/hasReservationConflict.ts | 4 + .../reservations/hooks/useCreateReservation.ts | 27 ++--- src/features/reservations/hooks/useReservations.ts | 17 +++ .../reservations/services/reservationsService.ts | 115 ++++++++++++++++++++- src/features/reservations/types.ts | 3 + 5 files changed, 143 insertions(+), 23 deletions(-) (limited to 'src/features/reservations') diff --git a/src/features/reservations/domain/hasReservationConflict.ts b/src/features/reservations/domain/hasReservationConflict.ts index e246c00..c2348de 100644 --- a/src/features/reservations/domain/hasReservationConflict.ts +++ b/src/features/reservations/domain/hasReservationConflict.ts @@ -16,6 +16,10 @@ export function hasReservationConflict({ endTime, }: ConflictParams): boolean { return existingReservations.some((reservation) => { + if (reservation.status !== 'active') { + return false; + } + if (reservation.officeId !== officeId) { return false; } diff --git a/src/features/reservations/hooks/useCreateReservation.ts b/src/features/reservations/hooks/useCreateReservation.ts index 5361894..2b6830c 100644 --- a/src/features/reservations/hooks/useCreateReservation.ts +++ b/src/features/reservations/hooks/useCreateReservation.ts @@ -1,8 +1,10 @@ import { useState } from 'react'; import { router } from 'expo-router'; -import { reservationsService } from '@/features/reservations/services/reservationsService'; +import { + isReservationConflictError, + reservationsService, +} from '@/features/reservations/services/reservationsService'; import { validateReservation } from '@/features/reservations/domain/validateReservation'; -import { hasReservationConflict } from '@/features/reservations/domain/hasReservationConflict'; import { CreateReservationInput } from '@/features/reservations/types'; import { useAuthSession } from '@/providers/AuthProvider'; @@ -47,22 +49,6 @@ export function useCreateReservation({ return; } - const existingReservations = - await reservationsService.getByOfficeAndDate(input.officeId, input.date); - - const hasConflict = hasReservationConflict({ - existingReservations, - officeId: input.officeId, - date: input.date, - startTime: input.startTime, - endTime: input.endTime, - }); - - if (hasConflict) { - setError('Ya existe una reserva que se solapa con ese horario'); - return; - } - await reservationsService.create(input); setSuccessMessage('Reserva creada correctamente'); @@ -72,6 +58,11 @@ export function useCreateReservation({ router.replace('/(protected)/(tabs)/reservations'); } catch (err: any) { + if (isReservationConflictError(err)) { + setError('Ya existe una reserva que se solapa con ese horario'); + return; + } + setError(err?.message ?? 'No se pudo crear la reserva'); } finally { setIsSubmitting(false); diff --git a/src/features/reservations/hooks/useReservations.ts b/src/features/reservations/hooks/useReservations.ts index c993c89..abeecf5 100644 --- a/src/features/reservations/hooks/useReservations.ts +++ b/src/features/reservations/hooks/useReservations.ts @@ -9,6 +9,7 @@ export function useReservations() { const [reservations, setReservations] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); + const [cancelingReservationId, setCancelingReservationId] = useState(null); const loadReservations = async () => { if (!user?.uid) { @@ -34,10 +35,26 @@ export function useReservations() { loadReservations(); }, [user?.uid]); + const cancelReservation = async (reservationId: string) => { + try { + setError(null); + setCancelingReservationId(reservationId); + + await reservationsService.cancel(reservationId); + await loadReservations(); + } catch (err: any) { + setError(err?.message ?? 'No se pudo cancelar la reserva'); + } finally { + setCancelingReservationId(null); + } + }; + return { reservations, loading, error, + cancelingReservationId, + cancelReservation, reload: loadReservations, }; } diff --git a/src/features/reservations/services/reservationsService.ts b/src/features/reservations/services/reservationsService.ts index e56a302..e58308d 100644 --- a/src/features/reservations/services/reservationsService.ts +++ b/src/features/reservations/services/reservationsService.ts @@ -1,9 +1,10 @@ import { - addDoc, collection, + doc, getDocs, orderBy, query, + runTransaction, serverTimestamp, where, } from 'firebase/firestore'; @@ -11,8 +12,13 @@ import { db } from '@/shared/lib/firebase/config'; import { CreateReservationInput, Reservation, + ReservationStatus, } from '@/features/reservations/types'; +function mapReservationStatus(value: unknown): ReservationStatus { + return value === 'cancelled' ? 'cancelled' : 'active'; +} + function mapReservation(id: string, data: any): Reservation { return { id, @@ -23,15 +29,108 @@ function mapReservation(id: string, data: any): Reservation { date: data.date ?? '', startTime: data.startTime ?? '', endTime: data.endTime ?? '', + status: mapReservationStatus(data.status), createdAt: data.createdAt, }; } +const RESERVATION_CONFLICT_ERROR = 'RESERVATION_CONFLICT'; + +function parseTimeToMinutes(value: string): number { + const [hours, minutes] = value.split(':').map(Number); + return hours * 60 + minutes; +} + +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')}`; +} + +function buildReservationLockIds(input: { + officeId: string; + date: string; + startTime: string; + endTime: string; +}): string[] { + const startMinutes = parseTimeToMinutes(input.startTime); + const endMinutes = parseTimeToMinutes(input.endTime); + const lockIds: string[] = []; + + for (let minute = startMinutes; minute < endMinutes; minute += 1) { + lockIds.push( + `${input.officeId}__${input.date}__${formatMinuteSlot(minute)}` + ); + } + + return lockIds; +} + export const reservationsService = { async create(input: CreateReservationInput): Promise { - await addDoc(collection(db, 'reservations'), { - ...input, - createdAt: serverTimestamp(), + const reservationsCollection = collection(db, 'reservations'); + const reservationLocksCollection = collection(db, 'reservationLocks'); + const reservationRef = doc(reservationsCollection); + const lockIds = buildReservationLockIds(input); + + await runTransaction(db, async (transaction) => { + for (const lockId of lockIds) { + const lockRef = doc(reservationLocksCollection, lockId); + const lockSnapshot = await transaction.get(lockRef); + + if (lockSnapshot.exists()) { + throw new Error(RESERVATION_CONFLICT_ERROR); + } + + transaction.set(lockRef, { + reservationId: reservationRef.id, + userId: input.userId, + officeId: input.officeId, + date: input.date, + time: lockId.split('__')[2], + }); + } + + transaction.set(reservationRef, { + ...input, + lockIds, + status: 'active', + createdAt: serverTimestamp(), + }); + }); + }, + + async cancel(reservationId: string): Promise { + 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'); + } + + const reservation = mapReservation(reservationSnapshot.id, reservationSnapshot.data()); + + if (reservation.status === 'cancelled') { + return; + } + + const storedLockIds = reservationSnapshot.data().lockIds; + const lockIds = + Array.isArray(storedLockIds) && storedLockIds.every((value) => typeof value === 'string') + ? storedLockIds + : buildReservationLockIds(reservation); + + for (const lockId of lockIds) { + transaction.delete(doc(reservationLocksCollection, lockId)); + } + + transaction.update(reservationRef, { + status: 'cancelled', + }); }); }, @@ -58,6 +157,12 @@ export const reservationsService = { const snapshot = await getDocs(q); - return snapshot.docs.map((doc) => mapReservation(doc.id, doc.data())); + return snapshot.docs + .map((item) => mapReservation(item.id, item.data())) + .filter((reservation) => reservation.status === 'active'); }, }; + +export function isReservationConflictError(error: unknown): boolean { + return error instanceof Error && error.message === RESERVATION_CONFLICT_ERROR; +} diff --git a/src/features/reservations/types.ts b/src/features/reservations/types.ts index b04b980..5900ac7 100644 --- a/src/features/reservations/types.ts +++ b/src/features/reservations/types.ts @@ -1,3 +1,5 @@ +export type ReservationStatus = 'active' | 'cancelled'; + export type Reservation = { id: string; officeId: string; @@ -7,6 +9,7 @@ export type Reservation = { date: string; startTime: string; endTime: string; + status: ReservationStatus; createdAt?: unknown; }; -- cgit v1.2.3-54-g00ecf