From 08ce78dbd97ad792e163482f454f285557c7cdd0 Mon Sep 17 00:00:00 2001 From: Alberto Duarte Delgado Date: Wed, 1 Apr 2026 13:03:25 +0100 Subject: Mejoras de UX y feedback de errores; y, manejo de status de reserva --- src/app/(auth)/login.tsx | 6 +- src/app/(auth)/register.tsx | 6 +- src/app/(protected)/(tabs)/profile/index.tsx | 11 +- src/app/(protected)/(tabs)/reservations/index.tsx | 125 +++++++++------ src/app/(protected)/reservations/create.tsx | 167 +++++++++++++++------ src/features/auth/hooks/useLogin.ts | 5 +- src/features/auth/hooks/useRegister.ts | 5 +- src/features/offices/hooks/useOffice.ts | 5 +- src/features/offices/hooks/useOffices.ts | 5 +- src/features/profile/hooks/useProfile.ts | 5 +- src/features/profile/hooks/useUpdateProfile.ts | 5 +- .../reservations/domain/validateReservation.ts | 67 +++++++++ .../reservations/hooks/useCreateReservation.ts | 56 ++++++- src/features/reservations/hooks/useReservations.ts | 11 +- .../reservations/services/reservationsService.ts | 61 +++++++- src/features/reservations/types.ts | 2 +- src/shared/lib/errors/getErrorMessage.ts | 40 +++++ src/shared/ui/StatusMessage.tsx | 33 ++++ 18 files changed, 489 insertions(+), 126 deletions(-) create mode 100644 src/shared/lib/errors/getErrorMessage.ts create mode 100644 src/shared/ui/StatusMessage.tsx (limited to 'src') diff --git a/src/app/(auth)/login.tsx b/src/app/(auth)/login.tsx index 5664bbf..7457b54 100644 --- a/src/app/(auth)/login.tsx +++ b/src/app/(auth)/login.tsx @@ -1,6 +1,7 @@ import { Link } from 'expo-router'; import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native'; import { useLogin } from '@/features/auth/hooks/useLogin'; +import { StatusMessage } from '@/shared/ui/StatusMessage'; export default function LoginScreen() { const { email, password, setEmail, setPassword, submit, isSubmitting, error } = useLogin(); @@ -26,7 +27,7 @@ export default function LoginScreen() { onChangeText={setPassword} /> - {error ? {error} : null} + {error ? : null} @@ -71,9 +72,6 @@ const styles = StyleSheet.create({ color: '#fff', fontWeight: '600', }, - error: { - color: 'red', - }, link: { marginTop: 12, }, diff --git a/src/app/(auth)/register.tsx b/src/app/(auth)/register.tsx index 1a39a78..0eeb058 100644 --- a/src/app/(auth)/register.tsx +++ b/src/app/(auth)/register.tsx @@ -1,6 +1,7 @@ import { Link } from 'expo-router'; import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native'; import { useRegister } from '@/features/auth/hooks/useRegister'; +import { StatusMessage } from '@/shared/ui/StatusMessage'; export default function RegisterScreen() { const { @@ -43,7 +44,7 @@ export default function RegisterScreen() { onChangeText={setPassword} /> - {error ? {error} : null} + {error ? : null} @@ -88,9 +89,6 @@ const styles = StyleSheet.create({ color: '#fff', fontWeight: '600', }, - error: { - color: 'red', - }, link: { marginTop: 12, }, diff --git a/src/app/(protected)/(tabs)/profile/index.tsx b/src/app/(protected)/(tabs)/profile/index.tsx index 1e87f21..760b352 100644 --- a/src/app/(protected)/(tabs)/profile/index.tsx +++ b/src/app/(protected)/(tabs)/profile/index.tsx @@ -12,6 +12,7 @@ import { useAuthSession } from '@/providers/AuthProvider'; import { useProfile } from '@/features/profile/hooks/useProfile'; import { useUpdateProfile } from '@/features/profile/hooks/useUpdateProfile'; import { router } from 'expo-router'; +import { StatusMessage } from '@/shared/ui/StatusMessage'; export default function ProfileScreen() { const { logout } = useAuthSession(); @@ -96,8 +97,8 @@ export default function ProfileScreen() { autoCorrect={false} /> - {updateError ? {updateError} : null} - {successMessage ? {successMessage} : null} + {updateError ? : null} + {successMessage ? : null} @@ -191,9 +192,7 @@ const styles = StyleSheet.create({ fontWeight: '600', }, error: { - color: 'red', - }, - success: { - color: 'green', + color: '#9f1d35', + textAlign: 'center', }, }); diff --git a/src/app/(protected)/(tabs)/reservations/index.tsx b/src/app/(protected)/(tabs)/reservations/index.tsx index a2a0d9d..ccec7e9 100644 --- a/src/app/(protected)/(tabs)/reservations/index.tsx +++ b/src/app/(protected)/(tabs)/reservations/index.tsx @@ -1,8 +1,8 @@ import { ActivityIndicator, Alert, - FlatList, Pressable, + ScrollView, StyleSheet, Text, View, @@ -11,7 +11,8 @@ import { useReservations } from '@/features/reservations/hooks/useReservations'; export default function ReservationsScreen() { const { - reservations, + activeReservations, + historyReservations, loading, error, reload, @@ -59,48 +60,77 @@ export default function ReservationsScreen() { Mis reservas - item.id} - contentContainerStyle={styles.list} - ListEmptyComponent={ - No tienes reservas todavía - } - renderItem={({ item }) => ( - - - {item.officeName} - - - {item.status === 'active' ? 'Activa' : 'Cancelada'} - + + + Activas + + {activeReservations.length === 0 ? ( + No tienes reservas activas + ) : ( + activeReservations.map((item) => ( + + + {item.officeName} + + Activa + + + Fecha: {item.date} + Inicio: {item.startTime} + Fin: {item.endTime} + + handleCancelReservation(item.id)} + disabled={cancelingReservationId === item.id} + > + + {cancelingReservationId === item.id + ? 'Cancelando...' + : 'Cancelar reserva'} + + - - Fecha: {item.date} - Inicio: {item.startTime} - Fin: {item.endTime} + )) + )} + + + + Historial - {item.status === 'active' ? ( - handleCancelReservation(item.id)} - disabled={cancelingReservationId === item.id} - > - - {cancelingReservationId === item.id - ? 'Cancelando...' - : 'Cancelar reserva'} - - - ) : null} - - )} - /> + {historyReservations.length === 0 ? ( + No tienes reservas en el historial + ) : ( + historyReservations.map((item) => ( + + + {item.officeName} + + + {item.status === 'completed' ? 'Completada' : 'Cancelada'} + + + + Fecha: {item.date} + Inicio: {item.startTime} + Fin: {item.endTime} + + )) + )} + + ); } @@ -123,6 +153,14 @@ const styles = StyleSheet.create({ }, list: { gap: 12, + paddingBottom: 24, + }, + section: { + gap: 12, + }, + sectionTitle: { + fontSize: 20, + fontWeight: '700', }, card: { borderWidth: 1, @@ -153,6 +191,9 @@ const styles = StyleSheet.create({ statusCancelled: { backgroundColor: '#f3d8d8', }, + statusCompleted: { + backgroundColor: '#dce8f8', + }, statusText: { fontSize: 12, fontWeight: '700', diff --git a/src/app/(protected)/reservations/create.tsx b/src/app/(protected)/reservations/create.tsx index 138f0ee..65a16f5 100644 --- a/src/app/(protected)/reservations/create.tsx +++ b/src/app/(protected)/reservations/create.tsx @@ -1,6 +1,16 @@ import { useLocalSearchParams } from 'expo-router'; -import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native'; +import { + KeyboardAvoidingView, + Platform, + Pressable, + ScrollView, + StyleSheet, + Text, + TextInput, + View, +} from 'react-native'; import { useCreateReservation } from '@/features/reservations/hooks/useCreateReservation'; +import { StatusMessage } from '@/shared/ui/StatusMessage'; export default function CreateReservationScreen() { const params = useLocalSearchParams<{ @@ -17,6 +27,7 @@ export default function CreateReservationScreen() { date, startTime, endTime, + isFormComplete, isSubmitting, error, successMessage, @@ -27,60 +38,101 @@ export default function CreateReservationScreen() { } = useCreateReservation({ officeId, officeName }); return ( - - Crear reserva + + + Crear reserva + + Completa la fecha y el horario en formato 24h. + - - Espacio - {officeName ?? 'No indicado'} + + Espacio + {officeName ?? 'No indicado'} + - ID oficina - {officeId ?? 'No indicado'} - + + Condiciones de reserva + Horario permitido: de 08:00 a 20:00 + Duración mínima: 30 minutos + Duración máxima: 8 horas + - + + Fecha + + Formato: YYYY-MM-DD + - + + + Hora de inicio + + Formato 24h + - + + Hora de fin + + Debe ser posterior + + - {error ? {error} : null} - {successMessage ? {successMessage} : null} + {error ? : null} + {successMessage ? : null} - - - {isSubmitting ? 'Guardando...' : 'Guardar reserva'} - - - + + + {isSubmitting ? 'Guardando...' : 'Guardar reserva'} + + + + ); } const styles = StyleSheet.create({ container: { flex: 1, + }, + content: { padding: 16, - gap: 12, + gap: 14, }, title: { fontSize: 28, fontWeight: '700', - marginBottom: 8, + }, + subtitle: { + color: '#555', + marginBottom: 4, }, infoBox: { borderWidth: 1, @@ -90,6 +142,34 @@ const styles = StyleSheet.create({ gap: 6, marginBottom: 8, }, + rulesBox: { + borderWidth: 1, + borderColor: '#d7e3f7', + backgroundColor: '#f4f8ff', + borderRadius: 12, + padding: 12, + gap: 4, + }, + rulesTitle: { + fontSize: 14, + fontWeight: '700', + color: '#1d4f91', + marginBottom: 2, + }, + rulesText: { + color: '#365b86', + fontSize: 13, + }, + field: { + gap: 6, + }, + row: { + flexDirection: 'row', + gap: 12, + }, + rowField: { + flex: 1, + }, label: { fontSize: 14, fontWeight: '700', @@ -106,6 +186,10 @@ const styles = StyleSheet.create({ paddingHorizontal: 14, paddingVertical: 12, }, + helper: { + color: '#666', + fontSize: 12, + }, button: { backgroundColor: '#1f6feb', paddingVertical: 14, @@ -113,14 +197,11 @@ const styles = StyleSheet.create({ alignItems: 'center', marginTop: 8, }, + buttonDisabled: { + backgroundColor: '#8fb5ec', + }, buttonText: { color: '#fff', fontWeight: '600', }, - error: { - color: 'red', - }, - success: { - color: 'green', - }, }); diff --git a/src/features/auth/hooks/useLogin.ts b/src/features/auth/hooks/useLogin.ts index 5e4c881..6af76c5 100644 --- a/src/features/auth/hooks/useLogin.ts +++ b/src/features/auth/hooks/useLogin.ts @@ -1,6 +1,7 @@ import { useState } from 'react'; import { router } from 'expo-router'; import { authService } from '@/features/auth/services/authService'; +import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage'; export function useLogin() { const [email, setEmail] = useState(''); @@ -19,8 +20,8 @@ export function useLogin() { }); router.replace('/(protected)/home'); - } catch (err: any) { - setError(err?.message ?? 'No se pudo iniciar sesión'); + } catch (err) { + setError(getErrorMessage(err, 'No se pudo iniciar sesión')); } finally { setIsSubmitting(false); } diff --git a/src/features/auth/hooks/useRegister.ts b/src/features/auth/hooks/useRegister.ts index 7b93e92..fe83d85 100644 --- a/src/features/auth/hooks/useRegister.ts +++ b/src/features/auth/hooks/useRegister.ts @@ -1,6 +1,7 @@ import { useState } from 'react'; import { router } from 'expo-router'; import { authService } from '@/features/auth/services/authService'; +import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage'; export function useRegister() { const [displayName, setDisplayName] = useState(''); @@ -21,8 +22,8 @@ export function useRegister() { }); router.replace('/(protected)/home'); - } catch (err: any) { - setError(err?.message ?? 'No se pudo registrar el usuario'); + } catch (err) { + setError(getErrorMessage(err, 'No se pudo registrar el usuario')); } finally { setIsSubmitting(false); } diff --git a/src/features/offices/hooks/useOffice.ts b/src/features/offices/hooks/useOffice.ts index 87d47b5..c737719 100644 --- a/src/features/offices/hooks/useOffice.ts +++ b/src/features/offices/hooks/useOffice.ts @@ -1,6 +1,7 @@ import { useEffect, useState } from 'react'; import { officesService } from '@/features/offices/services/officesService'; import { Office } from '@/features/offices/types'; +import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage'; export function useOffice(officeId?: string) { const [office, setOffice] = useState(null); @@ -27,8 +28,8 @@ export function useOffice(officeId?: string) { } setOffice(data); - } catch (err: any) { - setError(err?.message ?? 'No se pudo cargar la oficina'); + } catch (err) { + setError(getErrorMessage(err, 'No se pudo cargar la oficina')); } finally { setLoading(false); } diff --git a/src/features/offices/hooks/useOffices.ts b/src/features/offices/hooks/useOffices.ts index ff08f6c..99f8f8e 100644 --- a/src/features/offices/hooks/useOffices.ts +++ b/src/features/offices/hooks/useOffices.ts @@ -1,6 +1,7 @@ import { useEffect, useState } from 'react'; import { officesService } from '@/features/offices/services/officesService'; import { Office } from '@/features/offices/types'; +import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage'; export function useOffices() { const [offices, setOffices] = useState([]); @@ -14,8 +15,8 @@ export function useOffices() { const data = await officesService.getAll(); setOffices(data); - } catch (err: any) { - setError(err?.message ?? 'No se pudieron cargar los espacios'); + } catch (err) { + setError(getErrorMessage(err, 'No se pudieron cargar los espacios')); } finally { setLoading(false); } diff --git a/src/features/profile/hooks/useProfile.ts b/src/features/profile/hooks/useProfile.ts index 82068f4..2f5278d 100644 --- a/src/features/profile/hooks/useProfile.ts +++ b/src/features/profile/hooks/useProfile.ts @@ -4,6 +4,7 @@ import { useEffect, useState } from 'react'; import { useAuthSession } from '@/providers/AuthProvider'; import { profileService } from '@/features/profile/services/profileService'; import { UserProfile } from '@/features/profile/types'; +import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage'; export function useProfile() { const { user } = useAuthSession(); @@ -25,8 +26,8 @@ export function useProfile() { const data = await profileService.getMyProfile(user.uid); setProfile(data); - } catch (err: any) { - setError(err?.message ?? 'No se pudo cargar el perfil'); + } catch (err) { + setError(getErrorMessage(err, 'No se pudo cargar el perfil')); } finally { setLoading(false); } diff --git a/src/features/profile/hooks/useUpdateProfile.ts b/src/features/profile/hooks/useUpdateProfile.ts index bc069dc..cd4a39a 100644 --- a/src/features/profile/hooks/useUpdateProfile.ts +++ b/src/features/profile/hooks/useUpdateProfile.ts @@ -3,6 +3,7 @@ import { useState } from 'react'; import { profileService } from '@/features/profile/services/profileService'; import { useAuthSession } from '@/providers/AuthProvider'; +import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage'; export function useUpdateProfile(initialDisplayName = '', initialPhotoURL = '') { const { user } = useAuthSession(); @@ -37,8 +38,8 @@ export function useUpdateProfile(initialDisplayName = '', initialPhotoURL = '') setPhotoURL(photoURL.trim()); setSuccessMessage('Perfil actualizado correctamente'); - } catch (err: any) { - setError(err?.message ?? 'No se pudo actualizar el perfil'); + } catch (err) { + setError(getErrorMessage(err, 'No se pudo actualizar el perfil')); } finally { setIsSubmitting(false); } diff --git a/src/features/reservations/domain/validateReservation.ts b/src/features/reservations/domain/validateReservation.ts index 40055c0..93df375 100644 --- a/src/features/reservations/domain/validateReservation.ts +++ b/src/features/reservations/domain/validateReservation.ts @@ -1,5 +1,43 @@ import { CreateReservationInput } from '@/features/reservations/types'; +const ALLOWED_START_MINUTES = 8 * 60; +const ALLOWED_END_MINUTES = 20 * 60; +const MIN_DURATION_MINUTES = 30; +const MAX_DURATION_MINUTES = 8 * 60; + +function isValidDate(value: string): boolean { + const [year, month, day] = value.split('-').map(Number); + const date = new Date(`${value}T00:00:00`); + + return ( + Number.isInteger(year) && + Number.isInteger(month) && + Number.isInteger(day) && + !Number.isNaN(date.getTime()) && + date.getFullYear() === year && + date.getMonth() + 1 === month && + date.getDate() === day + ); +} + +function isValidTime(value: string): boolean { + const [hours, minutes] = value.split(':').map(Number); + + return ( + Number.isInteger(hours) && + Number.isInteger(minutes) && + hours >= 0 && + hours <= 23 && + minutes >= 0 && + minutes <= 59 + ); +} + +function parseTimeToMinutes(value: string): number { + const [hours, minutes] = value.split(':').map(Number); + return hours * 60 + minutes; +} + export function validateReservation(input: CreateReservationInput): string | null { if (!input.officeId.trim()) { return 'No se indicó una oficina válida'; @@ -34,14 +72,43 @@ export function validateReservation(input: CreateReservationInput): string | nul return 'La fecha debe tener formato YYYY-MM-DD'; } + if (!isValidDate(input.date)) { + return 'La fecha indicada no es válida'; + } + const timePattern = /^\d{2}:\d{2}$/; if (!timePattern.test(input.startTime) || !timePattern.test(input.endTime)) { return 'Las horas deben tener formato HH:MM'; } + if (!isValidTime(input.startTime) || !isValidTime(input.endTime)) { + return 'Indica horas válidas en formato 24h'; + } + if (input.endTime <= input.startTime) { return 'La hora de fin debe ser posterior a la de inicio'; } + const startMinutes = parseTimeToMinutes(input.startTime); + const endMinutes = parseTimeToMinutes(input.endTime); + const durationMinutes = endMinutes - startMinutes; + + const reservationStart = new Date(`${input.date}T${input.startTime}:00`); + if (reservationStart.getTime() < Date.now()) { + return 'No puedes crear una reserva en una fecha u hora pasada'; + } + + if (startMinutes < ALLOWED_START_MINUTES || endMinutes > ALLOWED_END_MINUTES) { + return 'Las reservas solo están permitidas entre las 08:00 y las 20:00'; + } + + if (durationMinutes < MIN_DURATION_MINUTES) { + return 'La reserva debe durar al menos 30 minutos'; + } + + if (durationMinutes > MAX_DURATION_MINUTES) { + return 'La reserva no puede superar las 8 horas'; + } + return null; } diff --git a/src/features/reservations/hooks/useCreateReservation.ts b/src/features/reservations/hooks/useCreateReservation.ts index 2b6830c..00faa7c 100644 --- a/src/features/reservations/hooks/useCreateReservation.ts +++ b/src/features/reservations/hooks/useCreateReservation.ts @@ -7,12 +7,37 @@ import { 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'; type UseCreateReservationParams = { officeId?: string; officeName?: 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 useCreateReservation({ officeId, officeName, @@ -26,6 +51,26 @@ export function useCreateReservation({ const [error, setError] = useState(null); const [successMessage, setSuccessMessage] = 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); @@ -57,13 +102,13 @@ export function useCreateReservation({ setEndTime(''); router.replace('/(protected)/(tabs)/reservations'); - } catch (err: any) { + } catch (err) { if (isReservationConflictError(err)) { setError('Ya existe una reserva que se solapa con ese horario'); return; } - setError(err?.message ?? 'No se pudo crear la reserva'); + setError(getErrorMessage(err, 'No se pudo crear la reserva')); } finally { setIsSubmitting(false); } @@ -73,12 +118,13 @@ export function useCreateReservation({ date, startTime, endTime, + isFormComplete, isSubmitting, error, successMessage, - setDate, - setStartTime, - setEndTime, + setDate: handleDateChange, + setStartTime: handleStartTimeChange, + setEndTime: handleEndTimeChange, submit, }; } diff --git a/src/features/reservations/hooks/useReservations.ts b/src/features/reservations/hooks/useReservations.ts index abeecf5..cf58811 100644 --- a/src/features/reservations/hooks/useReservations.ts +++ b/src/features/reservations/hooks/useReservations.ts @@ -2,6 +2,7 @@ import { useEffect, useState } from 'react'; 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'; export function useReservations() { const { user } = useAuthSession(); @@ -24,8 +25,8 @@ export function useReservations() { const data = await reservationsService.getByUserId(user.uid); setReservations(data); - } catch (err: any) { - setError(err?.message ?? 'No se pudieron cargar las reservas'); + } catch (err) { + setError(getErrorMessage(err, 'No se pudieron cargar las reservas')); } finally { setLoading(false); } @@ -42,8 +43,8 @@ export function useReservations() { await reservationsService.cancel(reservationId); await loadReservations(); - } catch (err: any) { - setError(err?.message ?? 'No se pudo cancelar la reserva'); + } catch (err) { + setError(getErrorMessage(err, 'No se pudo cancelar la reserva')); } finally { setCancelingReservationId(null); } @@ -51,6 +52,8 @@ export function useReservations() { return { reservations, + activeReservations: reservations.filter((reservation) => reservation.status === 'active'), + historyReservations: reservations.filter((reservation) => reservation.status !== 'active'), loading, error, cancelingReservationId, diff --git a/src/features/reservations/services/reservationsService.ts b/src/features/reservations/services/reservationsService.ts index e58308d..4ddf436 100644 --- a/src/features/reservations/services/reservationsService.ts +++ b/src/features/reservations/services/reservationsService.ts @@ -6,6 +6,7 @@ import { query, runTransaction, serverTimestamp, + writeBatch, where, } from 'firebase/firestore'; import { db } from '@/shared/lib/firebase/config'; @@ -16,6 +17,10 @@ import { } from '@/features/reservations/types'; function mapReservationStatus(value: unknown): ReservationStatus { + if (value === 'completed') { + return 'completed'; + } + return value === 'cancelled' ? 'cancelled' : 'active'; } @@ -67,6 +72,14 @@ function buildReservationLockIds(input: { return lockIds; } +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; +} + export const reservationsService = { async create(input: CreateReservationInput): Promise { const reservationsCollection = collection(db, 'reservations'); @@ -75,20 +88,24 @@ export const reservationsService = { 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); + const lockRefs = lockIds.map((lockId) => doc(reservationLocksCollection, lockId)); + const lockSnapshots = await Promise.all( + lockRefs.map((lockRef) => transaction.get(lockRef)) + ); + for (const lockSnapshot of lockSnapshots) { if (lockSnapshot.exists()) { throw new Error(RESERVATION_CONFLICT_ERROR); } + } + for (const [index, lockRef] of lockRefs.entries()) { transaction.set(lockRef, { reservationId: reservationRef.id, userId: input.userId, officeId: input.officeId, date: input.date, - time: lockId.split('__')[2], + time: lockIds[index].split('__')[2], }); } @@ -143,8 +160,42 @@ export const reservationsService = { ); const snapshot = await getDocs(q); + const reservations = snapshot.docs.map((doc) => mapReservation(doc.id, doc.data())); + const reservationsToComplete = reservations.filter((reservation) => + isPastActiveReservation(reservation) + ); + + if (reservationsToComplete.length > 0) { + const batch = writeBatch(db); + const reservationLocksCollection = collection(db, 'reservationLocks'); + + for (const reservation of reservationsToComplete) { + const snapshotData = snapshot.docs.find((doc) => doc.id === reservation.id)?.data(); + const storedLockIds = snapshotData?.lockIds; + const lockIds = + Array.isArray(storedLockIds) && storedLockIds.every((value) => typeof value === 'string') + ? storedLockIds + : buildReservationLockIds(reservation); + + for (const lockId of lockIds) { + batch.delete(doc(reservationLocksCollection, lockId)); + } + + batch.update(doc(db, 'reservations', reservation.id), { + status: 'completed', + }); + } + + await batch.commit(); + + return reservations.map((reservation) => + isPastActiveReservation(reservation) + ? { ...reservation, status: 'completed' } + : reservation + ); + } - return snapshot.docs.map((doc) => mapReservation(doc.id, doc.data())); + return reservations; }, async getByOfficeAndDate(officeId: string, date: string): Promise { diff --git a/src/features/reservations/types.ts b/src/features/reservations/types.ts index 5900ac7..9a5fe73 100644 --- a/src/features/reservations/types.ts +++ b/src/features/reservations/types.ts @@ -1,4 +1,4 @@ -export type ReservationStatus = 'active' | 'cancelled'; +export type ReservationStatus = 'active' | 'completed' | 'cancelled'; export type Reservation = { id: string; diff --git a/src/shared/lib/errors/getErrorMessage.ts b/src/shared/lib/errors/getErrorMessage.ts new file mode 100644 index 0000000..e25f24b --- /dev/null +++ b/src/shared/lib/errors/getErrorMessage.ts @@ -0,0 +1,40 @@ +type FirebaseLikeError = { + code?: string; + message?: string; +}; + +const ERROR_MESSAGES: Record = { + 'auth/email-already-in-use': 'Ese correo ya está registrado', + 'auth/invalid-credential': 'Correo o contraseña incorrectos', + 'auth/invalid-email': 'El correo electrónico no es válido', + 'auth/missing-password': 'Debes indicar una contraseña', + 'auth/network-request-failed': 'No se pudo conectar. Revisa tu conexión e inténtalo otra vez', + 'auth/too-many-requests': 'Demasiados intentos. Espera un momento antes de volver a probar', + 'auth/weak-password': 'La contraseña es demasiado débil', + 'permission-denied': 'No tienes permisos para realizar esta acción', + 'unavailable': 'El servicio no está disponible ahora mismo. Inténtalo más tarde', +}; + +export function getErrorMessage(error: unknown, fallback: string): string { + if (typeof error === 'string' && error.trim()) { + return error; + } + + if (error && typeof error === 'object') { + const { code, message } = error as FirebaseLikeError; + + if (code && ERROR_MESSAGES[code]) { + return ERROR_MESSAGES[code]; + } + + if (message && message.trim()) { + return message; + } + } + + if (error instanceof Error && error.message.trim()) { + return error.message; + } + + return fallback; +} diff --git a/src/shared/ui/StatusMessage.tsx b/src/shared/ui/StatusMessage.tsx new file mode 100644 index 0000000..c289243 --- /dev/null +++ b/src/shared/ui/StatusMessage.tsx @@ -0,0 +1,33 @@ +import { StyleSheet, Text } from 'react-native'; + +type StatusMessageProps = { + message: string; + tone?: 'error' | 'success'; +}; + +export function StatusMessage({ + message, + tone = 'error', +}: StatusMessageProps) { + return ( + + {message} + + ); +} + +const styles = StyleSheet.create({ + base: { + borderRadius: 10, + paddingHorizontal: 12, + paddingVertical: 10, + }, + error: { + backgroundColor: '#fde7e9', + color: '#9f1d35', + }, + success: { + backgroundColor: '#e1f5e8', + color: '#166534', + }, +}); -- cgit v1.2.3-54-g00ecf