diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/app/(protected)/(tabs)/home.tsx | 198 | ||||
| -rw-r--r-- | src/app/(protected)/(tabs)/reservations/index.tsx | 74 | ||||
| -rw-r--r-- | src/app/(protected)/offices/[officeId].tsx | 98 | ||||
| -rw-r--r-- | src/features/offices/hooks/useFavoriteOffices.ts | 9 | ||||
| -rw-r--r-- | src/features/reservations/hooks/useOfficeAvailability.ts | 74 | ||||
| -rw-r--r-- | src/features/reservations/hooks/useReservations.ts | 17 | ||||
| -rw-r--r-- | src/features/reservations/services/reservationsService.ts | 27 | ||||
| -rw-r--r-- | src/features/reservations/types.ts | 1 |
8 files changed, 462 insertions, 36 deletions
diff --git a/src/app/(protected)/(tabs)/home.tsx b/src/app/(protected)/(tabs)/home.tsx index d9e64ac..3ddad57 100644 --- a/src/app/(protected)/(tabs)/home.tsx +++ b/src/app/(protected)/(tabs)/home.tsx @@ -1,36 +1,114 @@ import { Link } from 'expo-router'; -import { Pressable, StyleSheet, Text, View } from 'react-native'; +import { useMemo } from 'react'; +import { ActivityIndicator, Pressable, StyleSheet, Text, View } from 'react-native'; import { useAuthSession } from '@/providers/AuthProvider'; +import { useReservations } from '@/features/reservations/hooks/useReservations'; +import { useFavoriteOffices } from '@/features/offices/hooks/useFavoriteOffices'; + +function getReservationStart(date: string, startTime: string): Date { + return new Date(`${date}T${startTime}:00`); +} export default function HomeScreen() { const { user } = useAuthSession(); + const { reservations, activeReservations, historyReservations, loading, error } = useReservations(); + const { + favoriteOfficeIds, + isLoadingFavorites, + favoritesError, + } = useFavoriteOffices(); + + const nextReservation = useMemo(() => { + const now = new Date(); + + return activeReservations.find((reservation) => getReservationStart(reservation.date, reservation.startTime) >= now) + ?? activeReservations[0] + ?? null; + }, [activeReservations]); + + const completedReservationsCount = useMemo( + () => historyReservations.filter((reservation) => reservation.status === 'completed').length, + [historyReservations] + ); + + const checkedInReservationsCount = useMemo( + () => reservations.filter((reservation) => reservation.checkInAt).length, + [reservations] + ); + + if (loading || isLoadingFavorites) { + return ( + <View style={styles.center}> + <ActivityIndicator size="large" /> + </View> + ); + } + + if (error || favoritesError) { + return ( + <View style={styles.center}> + <Text style={styles.error}>{error ?? favoritesError}</Text> + </View> + ); + } return ( <View style={styles.container}> - <Text style={styles.title}>Inicio</Text> - <Text style={styles.subtitle}> + <Text style={styles.eyebrow}>Dashboard</Text> + <Text style={styles.title}> Bienvenido{user?.displayName ? `, ${user.displayName}` : ''} </Text> <Text style={styles.email}>{user?.email}</Text> - <View style={styles.actions}> - <Link href="/(protected)/(tabs)/offices" asChild> - <Pressable style={styles.button}> - <Text style={styles.buttonText}>Ver espacios</Text> - </Pressable> - </Link> - - <Link href="/(protected)/(tabs)/reservations" asChild> - <Pressable style={styles.button}> - <Text style={styles.buttonText}>Mis reservas</Text> - </Pressable> - </Link> + <View style={styles.heroCard}> + <Text style={styles.cardLabel}>Próxima reserva</Text> + {nextReservation ? ( + <> + <Text style={styles.heroTitle}>{nextReservation.officeName}</Text> + <Text style={styles.heroMeta}> + {nextReservation.date} · {nextReservation.startTime} - {nextReservation.endTime} + </Text> + <Text style={styles.heroStatus}> + {nextReservation.checkInAt ? 'Llegada registrada' : 'Pendiente de check-in'} + </Text> + <Link href="/(protected)/(tabs)/reservations" asChild> + <Pressable style={styles.button}> + <Text style={styles.buttonText}>Ver mis reservas</Text> + </Pressable> + </Link> + </> + ) : ( + <> + <Text style={styles.heroTitle}>No tienes reservas próximas</Text> + <Text style={styles.heroMeta}> + Explora espacios disponibles y reserva cuando lo necesites. + </Text> + <Link href="/(protected)/(tabs)/offices" asChild> + <Pressable style={styles.button}> + <Text style={styles.buttonText}>Buscar espacios</Text> + </Pressable> + </Link> + </> + )} + </View> - <Link href="/(protected)/(tabs)/profile" asChild> - <Pressable style={styles.secondaryButton}> - <Text style={styles.buttonText}>Ir a perfil</Text> - </Pressable> - </Link> + <View style={styles.statsGrid}> + <View style={styles.statCard}> + <Text style={styles.statValue}>{activeReservations.length}</Text> + <Text style={styles.statLabel}>Reservas activas</Text> + </View> + <View style={styles.statCard}> + <Text style={styles.statValue}>{favoriteOfficeIds.length}</Text> + <Text style={styles.statLabel}>Favoritos</Text> + </View> + <View style={styles.statCard}> + <Text style={styles.statValue}>{completedReservationsCount}</Text> + <Text style={styles.statLabel}>Completadas</Text> + </View> + <View style={styles.statCard}> + <Text style={styles.statValue}>{checkedInReservationsCount}</Text> + <Text style={styles.statLabel}>Check-ins</Text> + </View> </View> </View> ); @@ -40,34 +118,90 @@ const styles = StyleSheet.create({ container: { flex: 1, padding: 16, + gap: 16, + }, + center: { + flex: 1, + alignItems: 'center', justifyContent: 'center', - gap: 12, + padding: 24, }, - title: { - fontSize: 30, + eyebrow: { + color: '#5a7188', + fontSize: 13, fontWeight: '700', + textTransform: 'uppercase', + letterSpacing: 1, }, - subtitle: { - fontSize: 18, + title: { + fontSize: 32, + fontWeight: '700', }, email: { color: '#666', - marginBottom: 20, }, - actions: { + heroCard: { + backgroundColor: '#eff6ff', + borderWidth: 1, + borderColor: '#c8daf7', + borderRadius: 18, + padding: 18, + gap: 10, + }, + cardLabel: { + color: '#2b5ea8', + fontSize: 13, + fontWeight: '700', + textTransform: 'uppercase', + letterSpacing: 0.8, + }, + heroTitle: { + fontSize: 24, + fontWeight: '700', + color: '#102a43', + }, + heroMeta: { + color: '#365b86', + fontSize: 15, + }, + heroStatus: { + color: '#1d4f91', + fontWeight: '600', + }, + statsGrid: { + flexDirection: 'row', + flexWrap: 'wrap', gap: 12, }, + statCard: { + width: '47%', + minWidth: 150, + borderWidth: 1, + borderColor: '#dde3ea', + borderRadius: 16, + padding: 16, + backgroundColor: '#fff', + gap: 4, + }, + statValue: { + fontSize: 28, + fontWeight: '700', + color: '#13293d', + }, + statLabel: { + color: '#66788a', + fontSize: 13, + fontWeight: '600', + }, button: { backgroundColor: '#1f6feb', paddingVertical: 14, borderRadius: 10, alignItems: 'center', }, - secondaryButton: { - backgroundColor: '#555', - paddingVertical: 14, - borderRadius: 10, - alignItems: 'center', + error: { + color: '#9f1d35', + textAlign: 'center', }, buttonText: { color: '#fff', diff --git a/src/app/(protected)/(tabs)/reservations/index.tsx b/src/app/(protected)/(tabs)/reservations/index.tsx index ccec7e9..59d2cad 100644 --- a/src/app/(protected)/(tabs)/reservations/index.tsx +++ b/src/app/(protected)/(tabs)/reservations/index.tsx @@ -9,6 +9,49 @@ import { } from 'react-native'; import { useReservations } from '@/features/reservations/hooks/useReservations'; +function getReservationWindowStart(date: string, startTime: string): Date { + return new Date(`${date}T${startTime}:00`); +} + +function getReservationWindowEnd(date: string, endTime: string): Date { + return new Date(`${date}T${endTime}:00`); +} + +function canCheckIn(date: string, startTime: string, endTime: string): boolean { + const now = new Date(); + const reservationStart = getReservationWindowStart(date, startTime); + const reservationEnd = getReservationWindowEnd(date, endTime); + const checkInOpensAt = new Date(reservationStart.getTime() - 15 * 60 * 1000); + + return now >= checkInOpensAt && now <= reservationEnd; +} + +function hasToDate(value: unknown): value is { toDate: () => Date } { + return ( + !!value && + typeof value === 'object' && + 'toDate' in value && + typeof value.toDate === 'function' + ); +} + +function formatCheckInAt(value: unknown): string { + if (!hasToDate(value)) { + return 'Registrada'; + } + + const date = value.toDate(); + + if (!(date instanceof Date) || Number.isNaN(date.getTime())) { + return 'Registrada'; + } + + return new Intl.DateTimeFormat('es-ES', { + dateStyle: 'short', + timeStyle: 'short', + }).format(date); +} + export default function ReservationsScreen() { const { activeReservations, @@ -18,6 +61,8 @@ export default function ReservationsScreen() { reload, cancelReservation, cancelingReservationId, + checkingInReservationId, + checkInReservation, } = useReservations(); const handleCancelReservation = (reservationId: string) => { @@ -83,6 +128,25 @@ export default function ReservationsScreen() { <Text>Fecha: {item.date}</Text> <Text>Inicio: {item.startTime}</Text> <Text>Fin: {item.endTime}</Text> + <Text> + Llegada: {item.checkInAt ? formatCheckInAt(item.checkInAt) : 'Pendiente'} + </Text> + + {!item.checkInAt && canCheckIn(item.date, item.startTime, item.endTime) ? ( + <Pressable + style={styles.checkInButton} + onPress={() => { + void checkInReservation(item.id); + }} + disabled={checkingInReservationId === item.id} + > + <Text style={styles.buttonText}> + {checkingInReservationId === item.id + ? 'Registrando llegada...' + : 'He llegado'} + </Text> + </Pressable> + ) : null} <Pressable style={styles.cancelButton} @@ -126,6 +190,9 @@ export default function ReservationsScreen() { <Text>Fecha: {item.date}</Text> <Text>Inicio: {item.startTime}</Text> <Text>Fin: {item.endTime}</Text> + <Text> + Llegada: {item.checkInAt ? formatCheckInAt(item.checkInAt) : 'No registrada'} + </Text> </View> )) )} @@ -220,6 +287,13 @@ const styles = StyleSheet.create({ alignItems: 'center', marginTop: 8, }, + checkInButton: { + backgroundColor: '#2e7d32', + paddingVertical: 12, + borderRadius: 10, + alignItems: 'center', + marginTop: 8, + }, empty: { color: '#666', }, diff --git a/src/app/(protected)/offices/[officeId].tsx b/src/app/(protected)/offices/[officeId].tsx index 8e3812f..c632490 100644 --- a/src/app/(protected)/offices/[officeId].tsx +++ b/src/app/(protected)/offices/[officeId].tsx @@ -1,8 +1,17 @@ import { Link, useLocalSearchParams } from 'expo-router'; -import { ActivityIndicator, Pressable, StyleSheet, Text, View } from 'react-native'; +import { + ActivityIndicator, + Pressable, + ScrollView, + StyleSheet, + Text, + TextInput, + View, +} from 'react-native'; import { useOffice } from '@/features/offices/hooks/useOffice'; import { useFavoriteOffices } from '@/features/offices/hooks/useFavoriteOffices'; import { StatusMessage } from '@/shared/ui/StatusMessage'; +import { useOfficeAvailability } from '@/features/reservations/hooks/useOfficeAvailability'; export default function OfficeDetailScreen() { const params = useLocalSearchParams<{ officeId: string }>(); @@ -15,6 +24,13 @@ export default function OfficeDetailScreen() { pendingOfficeId, toggleFavorite, } = useFavoriteOffices(); + const { + selectedDate, + reservations, + loading: loadingAvailability, + error: availabilityError, + setSelectedDate, + } = useOfficeAvailability(officeId); if (loading) { return ( @@ -43,7 +59,7 @@ export default function OfficeDetailScreen() { } return ( - <View style={styles.container}> + <ScrollView contentContainerStyle={styles.container}> <View style={styles.header}> <Text style={styles.title}>{office.name}</Text> <Pressable @@ -67,6 +83,7 @@ export default function OfficeDetailScreen() { </View> {favoritesError ? <StatusMessage message={favoritesError} /> : null} + {availabilityError ? <StatusMessage message={availabilityError} /> : null} <View style={styles.card}> <Text style={styles.label}>Ubicación</Text> @@ -83,6 +100,39 @@ export default function OfficeDetailScreen() { ) : null} </View> + <View style={styles.card}> + <Text style={styles.sectionTitle}>Disponibilidad</Text> + + <Text style={styles.label}>Fecha</Text> + <TextInput + style={styles.input} + placeholder="2026-04-01" + value={selectedDate} + onChangeText={setSelectedDate} + keyboardType="number-pad" + maxLength={10} + /> + + <Text style={styles.helper}>Consulta los horarios ocupados para esa fecha</Text> + + {loadingAvailability ? ( + <ActivityIndicator size="small" /> + ) : availabilityError ? null : reservations.length === 0 ? ( + <Text style={styles.availableText}>No hay bloques ocupados para esta fecha</Text> + ) : ( + <View style={styles.availabilityList}> + {reservations.map((reservation) => ( + <View key={reservation.id} style={styles.availabilityItem}> + <Text style={styles.availabilityTime}> + {reservation.startTime} - {reservation.endTime} + </Text> + <Text style={styles.availabilityStatus}>Ocupado</Text> + </View> + ))} + </View> + )} + </View> + <Link href={{ pathname: '/(protected)/reservations/create', @@ -98,7 +148,7 @@ export default function OfficeDetailScreen() { </Pressable> </Link> - </View> + </ScrollView> ); } @@ -137,10 +187,52 @@ const styles = StyleSheet.create({ fontWeight: '700', color: '#444', }, + sectionTitle: { + fontSize: 20, + fontWeight: '700', + marginBottom: 4, + }, value: { fontSize: 16, color: '#111', }, + input: { + borderWidth: 1, + borderColor: '#ccc', + borderRadius: 10, + paddingHorizontal: 14, + paddingVertical: 12, + marginTop: 4, + }, + helper: { + color: '#666', + fontSize: 12, + }, + availabilityList: { + gap: 10, + marginTop: 8, + }, + availabilityItem: { + borderWidth: 1, + borderColor: '#d9e5d4', + backgroundColor: '#f3faf1', + borderRadius: 10, + padding: 12, + gap: 4, + }, + availabilityTime: { + fontSize: 16, + fontWeight: '600', + color: '#1f3a1a', + }, + availabilityStatus: { + color: '#336b2f', + fontSize: 13, + }, + availableText: { + color: '#2e7d32', + marginTop: 8, + }, button: { backgroundColor: '#1f6feb', paddingVertical: 14, diff --git a/src/features/offices/hooks/useFavoriteOffices.ts b/src/features/offices/hooks/useFavoriteOffices.ts index 166dd1c..db87d64 100644 --- a/src/features/offices/hooks/useFavoriteOffices.ts +++ b/src/features/offices/hooks/useFavoriteOffices.ts @@ -1,4 +1,5 @@ -import { useEffect, useMemo, useState } from 'react'; +import { useFocusEffect } from 'expo-router'; +import { useCallback, useEffect, useMemo, useState } from 'react'; import { favoritesService } from '@/features/offices/services/favoritesService'; import { useAuthSession } from '@/providers/AuthProvider'; import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage'; @@ -34,6 +35,12 @@ export function useFavoriteOffices() { loadFavorites(); }, [user?.uid]); + useFocusEffect( + useCallback(() => { + void loadFavorites(); + }, [user?.uid]) + ); + const favoriteOfficeIdsSet = useMemo( () => new Set(favoriteOfficeIds), [favoriteOfficeIds] diff --git a/src/features/reservations/hooks/useOfficeAvailability.ts b/src/features/reservations/hooks/useOfficeAvailability.ts new file mode 100644 index 0000000..5cdd348 --- /dev/null +++ b/src/features/reservations/hooks/useOfficeAvailability.ts @@ -0,0 +1,74 @@ +import { useEffect, useState } from 'react'; +import { reservationsService } from '@/features/reservations/services/reservationsService'; +import { Reservation } from '@/features/reservations/types'; +import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage'; + +function getToday(): string { + return new Date().toISOString().slice(0, 10); +} + +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)}`; +} + +export function useOfficeAvailability(officeId?: string) { + const [selectedDate, setSelectedDateValue] = useState(getToday); + const [reservations, setReservations] = useState<Reservation[]>([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState<string | null>(null); + + const loadAvailability = async () => { + if (!officeId) { + setReservations([]); + setLoading(false); + setError('No se indicó una oficina válida'); + return; + } + + if (selectedDate.trim().length !== 10) { + setReservations([]); + setLoading(false); + return; + } + + try { + setError(null); + setLoading(true); + + const data = await reservationsService.getByOfficeAndDate(officeId, selectedDate); + setReservations(data); + } catch (err) { + setError(getErrorMessage(err, 'No se pudo cargar la disponibilidad')); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + loadAvailability(); + }, [officeId, selectedDate]); + + const setSelectedDate = (value: string) => { + setError(null); + setSelectedDateValue(normalizeDateInput(value)); + }; + + return { + selectedDate, + reservations, + loading, + error, + setSelectedDate, + reload: loadAvailability, + }; +} diff --git a/src/features/reservations/hooks/useReservations.ts b/src/features/reservations/hooks/useReservations.ts index cf58811..bb67a84 100644 --- a/src/features/reservations/hooks/useReservations.ts +++ b/src/features/reservations/hooks/useReservations.ts @@ -11,6 +11,7 @@ export function useReservations() { 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 loadReservations = async () => { if (!user?.uid) { @@ -50,6 +51,20 @@ export function useReservations() { } }; + const checkInReservation = async (reservationId: string) => { + try { + setError(null); + setCheckingInReservationId(reservationId); + + await reservationsService.checkIn(reservationId); + await loadReservations(); + } catch (err) { + setError(getErrorMessage(err, 'No se pudo registrar la llegada')); + } finally { + setCheckingInReservationId(null); + } + }; + return { reservations, activeReservations: reservations.filter((reservation) => reservation.status === 'active'), @@ -57,7 +72,9 @@ export function useReservations() { loading, error, cancelingReservationId, + checkingInReservationId, cancelReservation, + checkInReservation, reload: loadReservations, }; } diff --git a/src/features/reservations/services/reservationsService.ts b/src/features/reservations/services/reservationsService.ts index 4ddf436..cc53782 100644 --- a/src/features/reservations/services/reservationsService.ts +++ b/src/features/reservations/services/reservationsService.ts @@ -35,6 +35,7 @@ function mapReservation(id: string, data: any): Reservation { startTime: data.startTime ?? '', endTime: data.endTime ?? '', status: mapReservationStatus(data.status), + checkInAt: data.checkInAt, createdAt: data.createdAt, }; } @@ -151,6 +152,32 @@ export const reservationsService = { }); }, + async checkIn(reservationId: string): Promise<void> { + 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'); + } + + const reservation = mapReservation(reservationSnapshot.id, reservationSnapshot.data()); + + if (reservation.status !== 'active') { + throw new Error('Solo puedes hacer check-in en reservas activas'); + } + + if (reservation.checkInAt) { + return; + } + + transaction.update(reservationRef, { + checkInAt: serverTimestamp(), + }); + }); + }, + async getByUserId(userId: string): Promise<Reservation[]> { const q = query( collection(db, 'reservations'), diff --git a/src/features/reservations/types.ts b/src/features/reservations/types.ts index 9a5fe73..5b36351 100644 --- a/src/features/reservations/types.ts +++ b/src/features/reservations/types.ts @@ -10,6 +10,7 @@ export type Reservation = { startTime: string; endTime: string; status: ReservationStatus; + checkInAt?: unknown; createdAt?: unknown; }; |