From 174f1acd46c4ffbde88c04465e8fa6b6810ce113 Mon Sep 17 00:00:00 2001 From: Alberto Duarte Delgado Date: Mon, 30 Mar 2026 17:37:42 +0100 Subject: logica de reservas --- src/app/(protected)/(tabs)/reservations/index.tsx | 92 +++++++++++++-- src/app/(protected)/offices/[officeId].tsx | 18 ++- "src/app/(protected)/offices/\\" | 129 +++++++++++++++++++++ src/app/(protected)/reservations/create.tsx | 110 +++++++++++++++++- .../reservations/domain/hasReservationConflict.ts | 32 +++++ .../reservations/domain/hasReservationConflict.ts~ | 0 .../reservations/domain/validateReservation.ts | 47 ++++++++ .../reservations/domain/validateReservation.ts~ | 0 .../reservations/hooks/useCreateReservation.ts | 93 +++++++++++++++ .../reservations/hooks/useCreateReservation.ts~ | 0 src/features/reservations/hooks/useReservations.ts | 43 +++++++ .../reservations/hooks/useReservations.ts~ | 0 .../reservations/services/reservationsService.ts | 63 ++++++++++ .../reservations/services/reservationsService.ts~ | 0 src/features/reservations/types.ts | 21 ++++ src/features/reservations/types.ts~ | 0 16 files changed, 630 insertions(+), 18 deletions(-) create mode 100644 "src/app/(protected)/offices/\\" create mode 100644 src/features/reservations/domain/hasReservationConflict.ts create mode 100644 src/features/reservations/domain/hasReservationConflict.ts~ create mode 100644 src/features/reservations/domain/validateReservation.ts create mode 100644 src/features/reservations/domain/validateReservation.ts~ create mode 100644 src/features/reservations/hooks/useCreateReservation.ts create mode 100644 src/features/reservations/hooks/useCreateReservation.ts~ create mode 100644 src/features/reservations/hooks/useReservations.ts create mode 100644 src/features/reservations/hooks/useReservations.ts~ create mode 100644 src/features/reservations/services/reservationsService.ts create mode 100644 src/features/reservations/services/reservationsService.ts~ create mode 100644 src/features/reservations/types.ts create mode 100644 src/features/reservations/types.ts~ (limited to 'src') diff --git a/src/app/(protected)/(tabs)/reservations/index.tsx b/src/app/(protected)/(tabs)/reservations/index.tsx index 817ec6e..56f7832 100644 --- a/src/app/(protected)/(tabs)/reservations/index.tsx +++ b/src/app/(protected)/(tabs)/reservations/index.tsx @@ -1,10 +1,55 @@ -import { StyleSheet, Text, View } from 'react-native'; +import { + ActivityIndicator, + FlatList, + Pressable, + StyleSheet, + Text, + View, +} from 'react-native'; +import { useReservations } from '@/features/reservations/hooks/useReservations'; export default function ReservationsScreen() { + const { reservations, loading, error, reload } = useReservations(); + + if (loading) { + return ( + + + + ); + } + + if (error) { + return ( + + {error} + + Reintentar + + + ); + } + return ( - Reservas - Pantalla en construcción. + Mis reservas + + item.id} + contentContainerStyle={styles.list} + ListEmptyComponent={ + No tienes reservas todavía + } + renderItem={({ item }) => ( + + {item.officeName} + Fecha: {item.date} + Inicio: {item.startTime} + Fin: {item.endTime} + + )} + /> ); } @@ -13,16 +58,47 @@ const styles = StyleSheet.create({ container: { flex: 1, padding: 16, - justifyContent: 'center', + }, + center: { + flex: 1, alignItems: 'center', - gap: 12, + justifyContent: 'center', + padding: 24, }, title: { fontSize: 28, fontWeight: '700', + marginBottom: 16, + }, + list: { + gap: 12, + }, + card: { + borderWidth: 1, + borderColor: '#ddd', + borderRadius: 12, + padding: 16, + gap: 6, + }, + cardTitle: { + fontSize: 18, + fontWeight: '600', + }, + error: { + color: 'red', + marginBottom: 12, + }, + button: { + backgroundColor: '#1f6feb', + paddingHorizontal: 16, + paddingVertical: 12, + borderRadius: 10, + }, + buttonText: { + color: '#fff', + fontWeight: '600', }, - text: { - fontSize: 16, - color: '#555', + empty: { + color: '#666', }, }); diff --git a/src/app/(protected)/offices/[officeId].tsx b/src/app/(protected)/offices/[officeId].tsx index 77fd610..34095c5 100644 --- a/src/app/(protected)/offices/[officeId].tsx +++ b/src/app/(protected)/offices/[officeId].tsx @@ -53,11 +53,21 @@ export default function OfficeDetailScreen() { ) : null} - - - Reservar este espacio - + + + Reservar este espacio + + ); } diff --git "a/src/app/(protected)/offices/\\" "b/src/app/(protected)/offices/\\" new file mode 100644 index 0000000..34095c5 --- /dev/null +++ "b/src/app/(protected)/offices/\\" @@ -0,0 +1,129 @@ +import { Link, useLocalSearchParams } from 'expo-router'; +import { ActivityIndicator, Pressable, StyleSheet, Text, View } from 'react-native'; +import { useOffice } from '@/features/offices/hooks/useOffice'; + +export default function OfficeDetailScreen() { + const params = useLocalSearchParams<{ officeId: string }>(); + const officeId = typeof params.officeId === 'string' ? params.officeId : undefined; + + const { office, loading, error, reload } = useOffice(officeId); + + if (loading) { + return ( + + + + ); + } + + if (error || !office) { + return ( + + {error ?? 'No se pudo cargar la oficina'} + + + Reintentar + + + + + Volver a espacios + + + + ); + } + + return ( + + {office.name} + + + Ubicación + {office.location} + + Capacidad + {office.capacity} personas + + {office.description ? ( + <> + Descripción + {office.description} + + ) : null} + + + + + Reservar este espacio + + + + + ); +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + padding: 16, + gap: 16, + }, + center: { + flex: 1, + alignItems: 'center', + justifyContent: 'center', + padding: 24, + gap: 12, + }, + title: { + fontSize: 28, + fontWeight: '700', + }, + card: { + borderWidth: 1, + borderColor: '#ddd', + borderRadius: 12, + padding: 16, + gap: 10, + }, + label: { + fontSize: 14, + fontWeight: '700', + color: '#444', + }, + value: { + fontSize: 16, + color: '#111', + }, + button: { + backgroundColor: '#1f6feb', + paddingVertical: 14, + borderRadius: 10, + alignItems: 'center', + }, + secondaryButton: { + backgroundColor: '#555', + paddingVertical: 14, + paddingHorizontal: 16, + borderRadius: 10, + alignItems: 'center', + }, + buttonText: { + color: '#fff', + fontWeight: '600', + }, + error: { + color: 'red', + textAlign: 'center', + }, +}); diff --git a/src/app/(protected)/reservations/create.tsx b/src/app/(protected)/reservations/create.tsx index c1c88b3..138f0ee 100644 --- a/src/app/(protected)/reservations/create.tsx +++ b/src/app/(protected)/reservations/create.tsx @@ -1,10 +1,72 @@ -import { StyleSheet, Text, View } from 'react-native'; +import { useLocalSearchParams } from 'expo-router'; +import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native'; +import { useCreateReservation } from '@/features/reservations/hooks/useCreateReservation'; export default function CreateReservationScreen() { + const params = useLocalSearchParams<{ + officeId?: string; + officeName?: string; + }>(); + + const officeId = + typeof params.officeId === 'string' ? params.officeId : undefined; + const officeName = + typeof params.officeName === 'string' ? params.officeName : undefined; + + const { + date, + startTime, + endTime, + isSubmitting, + error, + successMessage, + setDate, + setStartTime, + setEndTime, + submit, + } = useCreateReservation({ officeId, officeName }); + return ( Crear reserva - Pantalla en construcción. + + + Espacio + {officeName ?? 'No indicado'} + + ID oficina + {officeId ?? 'No indicado'} + + + + + + + + + {error ? {error} : null} + {successMessage ? {successMessage} : null} + + + + {isSubmitting ? 'Guardando...' : 'Guardar reserva'} + + ); } @@ -13,16 +75,52 @@ const styles = StyleSheet.create({ container: { flex: 1, padding: 16, - justifyContent: 'center', - alignItems: 'center', gap: 12, }, title: { fontSize: 28, fontWeight: '700', + marginBottom: 8, + }, + infoBox: { + borderWidth: 1, + borderColor: '#ddd', + borderRadius: 12, + padding: 12, + gap: 6, + marginBottom: 8, }, - text: { + label: { + fontSize: 14, + fontWeight: '700', + color: '#444', + }, + value: { fontSize: 16, - color: '#555', + color: '#111', + }, + input: { + borderWidth: 1, + borderColor: '#ccc', + borderRadius: 10, + paddingHorizontal: 14, + paddingVertical: 12, + }, + button: { + backgroundColor: '#1f6feb', + paddingVertical: 14, + borderRadius: 10, + alignItems: 'center', + marginTop: 8, + }, + buttonText: { + color: '#fff', + fontWeight: '600', + }, + error: { + color: 'red', + }, + success: { + color: 'green', }, }); diff --git a/src/features/reservations/domain/hasReservationConflict.ts b/src/features/reservations/domain/hasReservationConflict.ts new file mode 100644 index 0000000..e246c00 --- /dev/null +++ b/src/features/reservations/domain/hasReservationConflict.ts @@ -0,0 +1,32 @@ +import { Reservation } from '@/features/reservations/types'; + +type ConflictParams = { + existingReservations: Reservation[]; + officeId: string; + date: string; + startTime: string; + endTime: string; +}; + +export function hasReservationConflict({ + existingReservations, + officeId, + date, + startTime, + endTime, +}: ConflictParams): boolean { + return existingReservations.some((reservation) => { + if (reservation.officeId !== officeId) { + return false; + } + + if (reservation.date !== date) { + return false; + } + + const overlaps = + startTime < reservation.endTime && endTime > reservation.startTime; + + return overlaps; + }); +} diff --git a/src/features/reservations/domain/hasReservationConflict.ts~ b/src/features/reservations/domain/hasReservationConflict.ts~ new file mode 100644 index 0000000..e69de29 diff --git a/src/features/reservations/domain/validateReservation.ts b/src/features/reservations/domain/validateReservation.ts new file mode 100644 index 0000000..40055c0 --- /dev/null +++ b/src/features/reservations/domain/validateReservation.ts @@ -0,0 +1,47 @@ +import { CreateReservationInput } from '@/features/reservations/types'; + +export function validateReservation(input: CreateReservationInput): string | null { + if (!input.officeId.trim()) { + return 'No se indicó una oficina válida'; + } + + if (!input.officeName.trim()) { + return 'No se indicó el nombre de la oficina'; + } + + if (!input.userId.trim()) { + return 'No se identificó al usuario'; + } + + if (!input.userEmail.trim()) { + return 'No se identificó el correo del usuario'; + } + + if (!input.date.trim()) { + return 'La fecha es obligatoria'; + } + + if (!input.startTime.trim()) { + return 'La hora de inicio es obligatoria'; + } + + if (!input.endTime.trim()) { + return 'La hora de fin es obligatoria'; + } + + const datePattern = /^\d{4}-\d{2}-\d{2}$/; + if (!datePattern.test(input.date)) { + return 'La fecha debe tener formato YYYY-MM-DD'; + } + + const timePattern = /^\d{2}:\d{2}$/; + if (!timePattern.test(input.startTime) || !timePattern.test(input.endTime)) { + return 'Las horas deben tener formato HH:MM'; + } + + if (input.endTime <= input.startTime) { + return 'La hora de fin debe ser posterior a la de inicio'; + } + + return null; +} diff --git a/src/features/reservations/domain/validateReservation.ts~ b/src/features/reservations/domain/validateReservation.ts~ new file mode 100644 index 0000000..e69de29 diff --git a/src/features/reservations/hooks/useCreateReservation.ts b/src/features/reservations/hooks/useCreateReservation.ts new file mode 100644 index 0000000..5361894 --- /dev/null +++ b/src/features/reservations/hooks/useCreateReservation.ts @@ -0,0 +1,93 @@ +import { useState } from 'react'; +import { router } from 'expo-router'; +import { 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'; + +type UseCreateReservationParams = { + officeId?: string; + officeName?: string; +}; + +export function useCreateReservation({ + officeId, + officeName, +}: UseCreateReservationParams) { + const { user } = useAuthSession(); + + const [date, setDate] = 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 submit = async () => { + try { + setError(null); + setSuccessMessage(null); + setIsSubmitting(true); + + const input: CreateReservationInput = { + officeId: officeId ?? '', + officeName: officeName ?? '', + userId: user?.uid ?? '', + userEmail: user?.email ?? '', + date: date.trim(), + startTime: startTime.trim(), + endTime: endTime.trim(), + }; + + const validationError = validateReservation(input); + + if (validationError) { + setError(validationError); + 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'); + setDate(''); + setStartTime(''); + setEndTime(''); + + router.replace('/(protected)/(tabs)/reservations'); + } catch (err: any) { + setError(err?.message ?? 'No se pudo crear la reserva'); + } finally { + setIsSubmitting(false); + } + }; + + return { + date, + startTime, + endTime, + isSubmitting, + error, + successMessage, + setDate, + setStartTime, + setEndTime, + submit, + }; +} diff --git a/src/features/reservations/hooks/useCreateReservation.ts~ b/src/features/reservations/hooks/useCreateReservation.ts~ new file mode 100644 index 0000000..e69de29 diff --git a/src/features/reservations/hooks/useReservations.ts b/src/features/reservations/hooks/useReservations.ts new file mode 100644 index 0000000..c993c89 --- /dev/null +++ b/src/features/reservations/hooks/useReservations.ts @@ -0,0 +1,43 @@ +import { useEffect, useState } from 'react'; +import { reservationsService } from '@/features/reservations/services/reservationsService'; +import { Reservation } from '@/features/reservations/types'; +import { useAuthSession } from '@/providers/AuthProvider'; + +export function useReservations() { + const { user } = useAuthSession(); + + const [reservations, setReservations] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + + const loadReservations = async () => { + if (!user?.uid) { + setReservations([]); + setLoading(false); + return; + } + + try { + setError(null); + setLoading(true); + + const data = await reservationsService.getByUserId(user.uid); + setReservations(data); + } catch (err: any) { + setError(err?.message ?? 'No se pudieron cargar las reservas'); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + loadReservations(); + }, [user?.uid]); + + return { + reservations, + loading, + error, + reload: loadReservations, + }; +} diff --git a/src/features/reservations/hooks/useReservations.ts~ b/src/features/reservations/hooks/useReservations.ts~ new file mode 100644 index 0000000..e69de29 diff --git a/src/features/reservations/services/reservationsService.ts b/src/features/reservations/services/reservationsService.ts new file mode 100644 index 0000000..e56a302 --- /dev/null +++ b/src/features/reservations/services/reservationsService.ts @@ -0,0 +1,63 @@ +import { + addDoc, + collection, + getDocs, + orderBy, + query, + serverTimestamp, + where, +} from 'firebase/firestore'; +import { db } from '@/shared/lib/firebase/config'; +import { + CreateReservationInput, + Reservation, +} from '@/features/reservations/types'; + +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 ?? '', + createdAt: data.createdAt, + }; +} + +export const reservationsService = { + async create(input: CreateReservationInput): Promise { + await addDoc(collection(db, 'reservations'), { + ...input, + createdAt: serverTimestamp(), + }); + }, + + async getByUserId(userId: string): Promise { + const q = query( + collection(db, 'reservations'), + where('userId', '==', userId), + orderBy('date', 'asc'), + orderBy('startTime', 'asc') + ); + + const snapshot = await getDocs(q); + + return snapshot.docs.map((doc) => mapReservation(doc.id, doc.data())); + }, + + async getByOfficeAndDate(officeId: string, date: string): Promise { + const q = query( + collection(db, 'reservations'), + where('officeId', '==', officeId), + where('date', '==', date), + orderBy('startTime', 'asc') + ); + + const snapshot = await getDocs(q); + + return snapshot.docs.map((doc) => mapReservation(doc.id, doc.data())); + }, +}; diff --git a/src/features/reservations/services/reservationsService.ts~ b/src/features/reservations/services/reservationsService.ts~ new file mode 100644 index 0000000..e69de29 diff --git a/src/features/reservations/types.ts b/src/features/reservations/types.ts new file mode 100644 index 0000000..b04b980 --- /dev/null +++ b/src/features/reservations/types.ts @@ -0,0 +1,21 @@ +export type Reservation = { + id: string; + officeId: string; + officeName: string; + userId: string; + userEmail: string; + date: string; + startTime: string; + endTime: string; + createdAt?: unknown; +}; + +export type CreateReservationInput = { + officeId: string; + officeName: string; + userId: string; + userEmail: string; + date: string; + startTime: string; + endTime: string; +}; diff --git a/src/features/reservations/types.ts~ b/src/features/reservations/types.ts~ new file mode 100644 index 0000000..e69de29 -- cgit v1.2.3-54-g00ecf