From ffe71f502d3388121d1cfdacfa18cbea4895f5da Mon Sep 17 00:00:00 2001 From: Anita Date: Sat, 18 Apr 2026 19:15:56 +0100 Subject: feat(auth): mejora UX login y register (mostrar contraseña y validación) refs #6 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/(auth)/login.tsx | 52 +++++++++++++++++++++------ src/app/(auth)/register.tsx | 85 +++++++++++++++++++++++++++++++++++++++------ 2 files changed, 117 insertions(+), 20 deletions(-) diff --git a/src/app/(auth)/login.tsx b/src/app/(auth)/login.tsx index bf4eda7..8dbac8b 100644 --- a/src/app/(auth)/login.tsx +++ b/src/app/(auth)/login.tsx @@ -1,8 +1,9 @@ import { Link } from 'expo-router'; -import { Pressable, StyleSheet, Text, TextInput, View } from 'react-native'; +import { Alert, Platform, Pressable, StyleSheet, Text, TextInput, View } from 'react-native'; import { MaterialIcons } from '@expo/vector-icons'; import theme from '@/theme'; import { useLogin } from '@/features/auth/hooks/useLogin'; +import { useState } from 'react'; import { StatusMessage } from '@/shared/ui/StatusMessage'; const { colors, spacing, radius, typography, fontWeight, layout, shadows } = theme; @@ -11,6 +12,22 @@ export default function LoginScreen() { // hook de login const { email, password, setEmail, setPassword, submit, isSubmitting, error } = useLogin(); + // controla si la contraseña se muestra o se oculta + const [showPassword, setShowPassword] = useState(false); + + // mensaje temporal para recuperar contraseña + const handleForgotPassword = () => { + const message = + 'La recuperación de contraseña todavía no está disponible en esta versión.'; + + if (Platform.OS === 'web') { + window.alert(message); + return; + } + + Alert.alert('Próximamente', message); + }; + return ( {/* contenido central acotado */} @@ -42,17 +59,32 @@ export default function LoginScreen() { {/* campo contraseña */} Contraseña - + + + + setShowPassword((prev) => !prev)} + style={styles.iconButton} + > + + + {/* enlace visual de recuperar contraseña */} - ¿Olvidaste tu contraseña? + + ¿Olvidaste tu contraseña? + {/* mensaje de error */} {error ? : null} diff --git a/src/app/(auth)/register.tsx b/src/app/(auth)/register.tsx index 0b57ce5..902c752 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 { MaterialIcons } from '@expo/vector-icons'; +import { useState } from 'react'; import theme from '@/theme'; import { useRegister } from '@/features/auth/hooks/useRegister'; import { StatusMessage } from '@/shared/ui/StatusMessage'; @@ -21,6 +22,27 @@ export default function RegisterScreen() { error, } = useRegister(); + // estado para confirmar contraseña + const [confirmPassword, setConfirmPassword] = useState(''); + + // estados para mostrar/ocultar contraseña + const [showPassword, setShowPassword] = useState(false); + const [showConfirmPassword, setShowConfirmPassword] = useState(false); + + // error local (frontend) + const [localError, setLocalError] = useState(null); + + const handleSubmit = () => { + setLocalError(null); + + if (password !== confirmPassword) { + setLocalError('Las contraseñas no coinciden'); + return; + } + + submit(); + }; + return ( {/* contenido central acotado */} @@ -62,20 +84,62 @@ export default function RegisterScreen() { {/* campo contraseña */} Contraseña - + + + + setShowPassword((prev) => !prev)} + style={styles.iconButton} + > + + + + + {/* campo confirmar contraseña */} + Confirmar contraseña + + + + setShowConfirmPassword((prev) => !prev)} + style={styles.iconButton} + > + + + {/* mensaje de error */} + {localError ? : null} {error ? : null} {/* boton principal */} - + {isSubmitting ? 'Registrando...' : 'Crear cuenta'} @@ -84,7 +148,8 @@ export default function RegisterScreen() { {/* enlace inferior a login */} - ¿Ya tienes cuenta? Inicia sesión + ¿Ya tienes cuenta?{' '} + Inicia sesión -- cgit v1.2.3-54-g00ecf From e68c8c3e71b0130b8a749cc40a2760fd71c4040c Mon Sep 17 00:00:00 2001 From: Anita Date: Sat, 18 Apr 2026 19:16:12 +0100 Subject: feat(profile): mejora cabecera y sección actividad refs #5 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/(protected)/(tabs)/profile/index.tsx | 206 +++++++++++++++------------ 1 file changed, 117 insertions(+), 89 deletions(-) diff --git a/src/app/(protected)/(tabs)/profile/index.tsx b/src/app/(protected)/(tabs)/profile/index.tsx index 660d113..c15db39 100644 --- a/src/app/(protected)/(tabs)/profile/index.tsx +++ b/src/app/(protected)/(tabs)/profile/index.tsx @@ -1,19 +1,12 @@ import { useEffect, useMemo, useState } from 'react'; import theme from '@/theme'; -import { - ActivityIndicator, - Pressable, - ScrollView, - StyleSheet, - Text, - TextInput, - View, -} from 'react-native'; +import {ActivityIndicator, Pressable, ScrollView, StyleSheet, Text, TextInput, View,} from 'react-native'; import { Feather } from '@expo/vector-icons'; import { Image } from 'expo-image'; import { useAuthSession } from '@/providers/AuthProvider'; import { useProfile } from '@/features/profile/hooks/useProfile'; import { useUpdateProfile } from '@/features/profile/hooks/useUpdateProfile'; +import { useReservations } from '@/features/reservations/hooks/useReservations'; import { router } from 'expo-router'; import { StatusMessage } from '@/shared/ui/StatusMessage'; import { useOffices } from '@/features/offices/hooks/useOffices'; @@ -54,15 +47,54 @@ export default function ProfileScreen() { error: officesError, } = useOffices(); - // estado local para alternar entre modo vista y modo edicion - const [isEditing, setIsEditing] = useState(false); - + // hook de reservas para mostrar actividad del usuario + const { + reservations, + activeReservations, + } = useReservations(); + + // calcula cuantas reservas tienen llegada registrada + const checkedInReservationsCount = useMemo(() => { + return reservations.filter((reservation) => reservation.checkInAt).length; + }, [reservations]); + // cruce entre ids favoritos y lista completa de oficinas // para obtener los datos reales de las oficinas favoritas const favoriteOffices = useMemo(() => { return offices.filter((office) => favoriteOfficeIds.includes(office.id)); }, [offices, favoriteOfficeIds]); + // calcula el espacio favorito mas usado entre reservas completadas + const mostUsedFavoriteOffice = useMemo(() => { + const completedReservations = reservations.filter( + (reservation) => reservation.status === 'completed' + ); + + const favoriteReservationCounts = favoriteOffices.map((office) => { + const usageCount = completedReservations.filter( + (reservation) => reservation.officeId === office.id + ).length; + + return { + office, + usageCount, + }; + }); + + const sortedFavorites = favoriteReservationCounts.sort( + (a, b) => b.usageCount - a.usageCount + ); + + if (sortedFavorites.length === 0 || sortedFavorites[0].usageCount === 0) { + return null; + } + + return sortedFavorites[0].office; + }, [reservations, favoriteOffices]); + + // estado local para alternar entre modo vista y modo edicion + const [isEditing, setIsEditing] = useState(false); + // sincroniza el formulario con los datos cargados del perfil useEffect(() => { if (profile?.displayName) { @@ -172,8 +204,7 @@ export default function ProfileScreen() { {/* seccion informacion personal */} - {/* en modo vista muestra datos */} - {/* en modo edicion muestra formulario */} + {/* en modo vista muestra datos y en modo edicion muestra formulario */} Información personal @@ -261,6 +292,33 @@ export default function ProfileScreen() { + {/* seccion actividad */} + + Resumen de actividad + + + + Check in confirmados en {checkedInReservationsCount} reservas. + + + + + + + Actualmente tienes {activeReservations.length} reservas activas. + + + + + + + {mostUsedFavoriteOffice + ? `Top de favoritos: ${mostUsedFavoriteOffice.name}.` + : 'Aún no tienes suficiente actividad para destacar un espacio favorito.'} + + + + {/* seccion favoritos */} Favoritos @@ -312,42 +370,12 @@ export default function ProfileScreen() { - {/* seccion enlaces secundarios */} - - - - - - Notificaciones - - {'>'} - - - - - - Privacidad y seguridad - - {'>'} - - - - - - Ayuda y soporte - - {'>'} - - - - - {/* boton cerrar sesion */} - - - + {/* seccion cierre de sesion */} + + Cerrar sesión - - + + {/* texto inferior de version */} App Oficina v1.0.0 @@ -411,7 +439,7 @@ const styles = StyleSheet.create({ headerCard: { backgroundColor: colors.surface, borderRadius: radius.xxl, - padding: spacing.lg, + padding: spacing.xxl, borderWidth: 1, borderColor: colors.border, ...shadows.card, @@ -422,7 +450,7 @@ const styles = StyleSheet.create({ headerRow: { flexDirection: 'row', alignItems: 'center', - gap: spacing.lg, + gap: spacing.xxl, }, // bloque de informacion de la cabecera @@ -433,9 +461,9 @@ const styles = StyleSheet.create({ // avatar del usuario avatar: { - width: 64, - height: 64, - borderRadius: 32, + width: 88, + height: 88, + borderRadius: 44, }, // avatar alternativo cuando no hay foto @@ -448,20 +476,20 @@ const styles = StyleSheet.create({ // letra dentro del avatar alternativo avatarPlaceholderText: { color: colors.white, - fontSize: 28, + fontSize: 34, fontWeight: fontWeight.semibold, }, // nombre principal del usuario profileName: { - fontSize: typography.xl, + fontSize: typography.xxxl, fontWeight: fontWeight.semibold, color: colors.text, }, // correo mostrado en cabecera profileEmail: { - fontSize: typography.md, + fontSize: typography.xl, color: colors.textSecondary, }, @@ -519,12 +547,6 @@ const styles = StyleSheet.create({ gap: spacing.xs, }, - // bloque antiguo de informacion personal - // se mantienen por si se reutiliza sino ELIMINAR - infoBlock: { - gap: spacing.xs, - }, - // etiqueta pequena de informacion personal infoLabel: { fontSize: typography.sm, @@ -553,6 +575,35 @@ const styles = StyleSheet.create({ color: colors.error, }, + // bloque de actividad + // muestra resumen narrativo del uso de la app + activityText: { + fontSize: typography.md, + color: colors.textSecondary, + lineHeight: 20, + }, + // fila individual de actividad + activityItem: { + flexDirection: 'row', + alignItems: 'flex-start', + gap: spacing.md, + }, + // punto visual de cada item de actividad + activityDot: { + width: 8, + height: 8, + borderRadius: 4, + backgroundColor: colors.primary, + marginTop: 6, + }, + // texto de la seccion actividad + activityText: { + flex: 1, + fontSize: typography.md, + color: colors.textSecondary, + lineHeight: 20, + }, + // bloque de favoritos // fila resumen de favoritos coloca numero y texto en la misma linea favoriteSummaryRow: { @@ -669,32 +720,9 @@ const styles = StyleSheet.create({ fontWeight: fontWeight.semibold, }, - // bloque de enlaces secundarios - // cada fila del bloque - linkItem: { - flexDirection: 'row', - justifyContent: 'space-between', - alignItems: 'center', - paddingVertical: spacing.md, - }, - - // parte izquierda del enlace: icono + texto - linkLeft: { - flexDirection: 'row', - alignItems: 'center', - gap: spacing.md, - }, - - // texto del enlace - linkText: { - fontSize: typography.md, - color: colors.text, - }, - - // flecha simple a la derecha - chevron: { - fontSize: typography.md, - color: colors.textSecondary, + // separacion antes del bloque de cierre de sesion + logoutSection: { + marginTop: spacing.lg, }, // boton de cerrar sesion -- cgit v1.2.3-54-g00ecf 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 --- src/app/(protected)/(tabs)/reservations/index.tsx | 220 +++++++----- src/app/(protected)/reservations/create.tsx | 250 ++++++++----- .../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 +- 8 files changed, 967 insertions(+), 292 deletions(-) create mode 100644 src/features/reservations/domain/getAvailableTimeSlots.ts create mode 100644 src/features/reservations/hooks/useUpdateReservation.ts diff --git a/src/app/(protected)/(tabs)/reservations/index.tsx b/src/app/(protected)/(tabs)/reservations/index.tsx index 8eaa80e..e790cb4 100644 --- a/src/app/(protected)/(tabs)/reservations/index.tsx +++ b/src/app/(protected)/(tabs)/reservations/index.tsx @@ -1,4 +1,8 @@ -import { useState } from 'react'; +import { useReservations } from "@/features/reservations/hooks/useReservations"; +import theme from "@/theme"; +import { MaterialIcons } from "@expo/vector-icons"; +import { useRouter } from "expo-router"; +import { useState } from "react"; import { ActivityIndicator, Alert, @@ -8,12 +12,10 @@ import { StyleSheet, Text, View, -} from 'react-native'; -import { MaterialIcons } from '@expo/vector-icons'; -import theme from '@/theme'; -import { useReservations } from '@/features/reservations/hooks/useReservations'; +} from "react-native"; -const { colors, spacing, radius, typography, fontWeight, layout, shadows } = theme; +const { colors, spacing, radius, typography, fontWeight, layout, shadows } = + theme; function getReservationWindowStart(date: string, startTime: string): Date { return new Date(`${date}T${startTime}:00`); @@ -27,7 +29,8 @@ 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); + // permitir check-in desde 30 minutos antes de la hora de la reserva + const checkInOpensAt = new Date(reservationStart.getTime() - 30 * 60 * 1000); return now >= checkInOpensAt && now <= reservationEnd; } @@ -35,30 +38,33 @@ function canCheckIn(date: string, startTime: string, endTime: string): boolean { function hasToDate(value: unknown): value is { toDate: () => Date } { return ( !!value && - typeof value === 'object' && - 'toDate' in value && - typeof value.toDate === 'function' + typeof value === "object" && + "toDate" in value && + typeof value.toDate === "function" ); } function formatCheckInAt(value: unknown): string { if (!hasToDate(value)) { - return 'Registrada'; + return "Registrada"; } const date = value.toDate(); if (!(date instanceof Date) || Number.isNaN(date.getTime())) { - return 'Registrada'; + return "Registrada"; } - return new Intl.DateTimeFormat('es-ES', { - dateStyle: 'short', - timeStyle: 'short', + return new Intl.DateTimeFormat("es-ES", { + dateStyle: "short", + timeStyle: "short", }).format(date); } export default function ReservationsScreen() { + // router para navegar a otras pantallas + const router = useRouter(); + // hook principal de reservas const { activeReservations, @@ -73,14 +79,14 @@ export default function ReservationsScreen() { } = useReservations(); // controla la pestaña visible de reservas - const [activeTab, setActiveTab] = useState<'active' | 'history'>('active'); + const [activeTab, setActiveTab] = useState<"active" | "history">("active"); // confirmacion antes de cancelar una reserva // en web usamos window.confirm porque Alert puede no comportarse bien const handleCancelReservation = (reservationId: string) => { - if (Platform.OS === 'web') { + if (Platform.OS === "web") { const confirmed = window.confirm( - 'Esta acción marcará la reserva como cancelada.' + "Esta acción marcará la reserva como cancelada.", ); if (confirmed) { @@ -91,18 +97,18 @@ export default function ReservationsScreen() { } // en movil sigue usando el Alert Alert.alert( - 'Cancelar reserva', - 'Esta acción marcará la reserva como cancelada.', + "Cancelar reserva", + "Esta acción marcará la reserva como cancelada.", [ - { text: 'Volver', style: 'cancel' }, + { text: "Volver", style: "cancel" }, { - text: 'Cancelar reserva', - style: 'destructive', + text: "Cancelar reserva", + style: "destructive", onPress: () => { void cancelReservation(reservationId); }, }, - ] + ], ); }; @@ -145,14 +151,14 @@ export default function ReservationsScreen() { setActiveTab('active')} + onPress={() => setActiveTab("active")} > Activas ({activeReservations.length}) @@ -162,14 +168,14 @@ export default function ReservationsScreen() { setActiveTab('history')} + onPress={() => setActiveTab("history")} > Historial ({historyReservations.length}) @@ -178,7 +184,7 @@ export default function ReservationsScreen() { {/* seccion de reservas activas */} - {activeTab === 'active' ? ( + {activeTab === "active" ? ( Activas @@ -186,7 +192,9 @@ export default function ReservationsScreen() { {activeReservations.length === 0 ? ( - No tienes reservas activas + + No tienes reservas activas + Cuando realices una nueva reserva, aparecerá aquí. @@ -212,7 +220,9 @@ export default function ReservationsScreen() { - + Activa @@ -249,7 +259,7 @@ export default function ReservationsScreen() { {item.checkInAt ? `Llegada registrada: ${formatCheckInAt(item.checkInAt)}` - : 'Llegada pendiente'} + : "Llegada pendiente"} @@ -257,8 +267,9 @@ export default function ReservationsScreen() { {/* linea separadora antes de acciones */} - {/* boton de check-in visible siempre de forma temporal para ajustar diseño */} - {!item.checkInAt ? ( + {/* boton de check-in solo visible cuando se puede hacer check-in */} + {!item.checkInAt && + canCheckIn(item.date, item.startTime, item.endTime) ? ( { @@ -268,8 +279,8 @@ export default function ReservationsScreen() { > {checkingInReservationId === item.id - ? 'Registrando llegada...' - : 'He llegado'} + ? "Registrando llegada..." + : "He llegado"} ) : null} @@ -282,6 +293,21 @@ export default function ReservationsScreen() { styles.editButton, pressed && styles.editButtonPressed, ]} + onPress={() => { + // navegar a create en modo edicion, pasando los parametros necesarios + router.push({ + pathname: "/(protected)/reservations/create", + params: { + mode: "edit", + reservationId: item.id, + officeId: item.officeId, + officeName: item.officeName, + oldDate: item.date, + oldStartTime: item.startTime, + oldEndTime: item.endTime, + }, + }); + }} > Editar @@ -296,9 +322,15 @@ export default function ReservationsScreen() { disabled={cancelingReservationId === item.id} > - + - {cancelingReservationId === item.id ? 'Cancelando...' : 'Cancelar'} + {cancelingReservationId === item.id + ? "Cancelando..." + : "Cancelar"} @@ -310,7 +342,7 @@ export default function ReservationsScreen() { ) : null} {/* seccion historial */} - {activeTab === 'history' ? ( + {activeTab === "history" ? ( Historial @@ -339,14 +371,16 @@ export default function ReservationsScreen() { {item.officeName} - Reserva finalizada + + Reserva finalizada + - {item.status === 'completed' ? 'Completada' : 'Cancelada'} + {item.status === "completed" + ? "Completada" + : "Cancelada"} @@ -395,7 +431,7 @@ export default function ReservationsScreen() { {item.checkInAt ? `Llegada registrada: ${formatCheckInAt(item.checkInAt)}` - : 'Llegada no registrada'} + : "Llegada no registrada"} @@ -431,10 +467,10 @@ const styles = StyleSheet.create({ fontSize: typography.xxl, fontWeight: fontWeight.semibold, color: colors.text, - textAlign: 'left', + textAlign: "left", maxWidth: layout.contentWidth, - width: '100%', - alignSelf: 'center', + width: "100%", + alignSelf: "center", }, // scroll principal @@ -450,15 +486,15 @@ const styles = StyleSheet.create({ paddingBottom: spacing.xxxl, gap: spacing.xl, maxWidth: layout.contentWidth, - width: '100%', - alignSelf: 'center', + width: "100%", + alignSelf: "center", }, // estado de carga / error center: { flex: 1, - alignItems: 'center', - justifyContent: 'center', + alignItems: "center", + justifyContent: "center", padding: spacing.xxxl, gap: spacing.md, backgroundColor: colors.background, @@ -471,9 +507,9 @@ const styles = StyleSheet.create({ // cabecera de seccion sectionHeader: { - flexDirection: 'row', - alignItems: 'center', - justifyContent: 'space-between', + flexDirection: "row", + alignItems: "center", + justifyContent: "space-between", }, // titulo de seccion @@ -485,9 +521,9 @@ const styles = StyleSheet.create({ // fila de pestañas superiores tabsRow: { - flexDirection: 'row', + flexDirection: "row", gap: spacing.sm, - backgroundColor: '#E9EEF5', + backgroundColor: "#E9EEF5", borderRadius: radius.xxl, padding: spacing.xs, }, @@ -497,7 +533,7 @@ const styles = StyleSheet.create({ flex: 1, paddingVertical: spacing.md, borderRadius: radius.xl, - alignItems: 'center', + alignItems: "center", }, // boton activo @@ -531,16 +567,16 @@ const styles = StyleSheet.create({ // cabecera de la tarjeta cardHeader: { - flexDirection: 'row', - alignItems: 'flex-start', - justifyContent: 'space-between', + flexDirection: "row", + alignItems: "flex-start", + justifyContent: "space-between", gap: spacing.md, }, // bloque izquierdo de la cabecera de la card cardHeaderLeft: { - flexDirection: 'row', - alignItems: 'flex-start', + flexDirection: "row", + alignItems: "flex-start", gap: spacing.md, flex: 1, }, @@ -551,8 +587,8 @@ const styles = StyleSheet.create({ height: 40, borderRadius: radius.md, backgroundColor: colors.primarySoft, - alignItems: 'center', - justifyContent: 'center', + alignItems: "center", + justifyContent: "center", }, // bloque de titulo de tarjeta @@ -583,17 +619,17 @@ const styles = StyleSheet.create({ // estado activa statusActive: { - backgroundColor: '#DCFCE7', + backgroundColor: "#DCFCE7", }, // estado completada statusCompleted: { - backgroundColor: '#DBEAFE', + backgroundColor: "#DBEAFE", }, // estado cancelada statusCancelled: { - backgroundColor: '#FEE2E2', + backgroundColor: "#FEE2E2", }, // texto base del estado @@ -604,17 +640,17 @@ const styles = StyleSheet.create({ // color texto activa statusTextActive: { - color: '#166534', + color: "#166534", }, // color texto completada statusTextCompleted: { - color: '#1D4ED8', + color: "#1D4ED8", }, // color texto cancelada statusTextCancelled: { - color: '#B91C1C', + color: "#B91C1C", }, // lista de detalles @@ -624,8 +660,8 @@ const styles = StyleSheet.create({ // fila individual de detalle detailRow: { - flexDirection: 'row', - alignItems: 'center', + flexDirection: "row", + alignItems: "center", gap: spacing.sm, }, @@ -649,7 +685,7 @@ const styles = StyleSheet.create({ paddingHorizontal: spacing.xl, paddingVertical: spacing.md, borderRadius: radius.md, - alignItems: 'center', + alignItems: "center", }, // texto del boton principal @@ -663,7 +699,7 @@ const styles = StyleSheet.create({ backgroundColor: colors.successBg, paddingVertical: spacing.md, borderRadius: radius.md, - alignItems: 'center', + alignItems: "center", marginTop: spacing.xs, }, @@ -676,28 +712,28 @@ const styles = StyleSheet.create({ // fila de acciones secundarias // coloca editar a la izquierda y cancelar a la derecha actionsRow: { - flexDirection: 'row', - justifyContent: 'space-between', - alignItems: 'center', + flexDirection: "row", + justifyContent: "space-between", + alignItems: "center", marginTop: spacing.xs, }, - // boton editar reserva + // boton editar reserva editButton: { paddingVertical: spacing.sm, paddingHorizontal: spacing.md, borderRadius: radius.md, backgroundColor: colors.surface, - alignItems: 'center', - justifyContent: 'center', + alignItems: "center", + justifyContent: "center", }, // estado pulsado del boton editar editButtonPressed: { - backgroundColor: '#EAF2FF', + backgroundColor: "#EAF2FF", }, - // texto del boton editar + // texto del boton editar editButtonText: { color: colors.primary, fontWeight: fontWeight.medium, @@ -710,26 +746,26 @@ const styles = StyleSheet.create({ paddingHorizontal: spacing.md, borderRadius: radius.md, backgroundColor: colors.surface, - alignItems: 'center', - justifyContent: 'center', + alignItems: "center", + justifyContent: "center", }, // estado pulsado del boton cancelar cancelButtonPressed: { - backgroundColor: '#FEECEC', + backgroundColor: "#FEECEC", }, // texto del boton cancelar cancelButtonText: { - color: '#DC2626', + color: "#DC2626", fontWeight: fontWeight.medium, fontSize: typography.sm, }, // contenido interno del boton cancelar cancelContent: { - flexDirection: 'row', - alignItems: 'center', + flexDirection: "row", + alignItems: "center", gap: spacing.xs, }, @@ -760,6 +796,6 @@ const styles = StyleSheet.create({ // error general error: { color: colors.error, - textAlign: 'center', + textAlign: "center", }, -}); \ No newline at end of file +}); diff --git a/src/app/(protected)/reservations/create.tsx b/src/app/(protected)/reservations/create.tsx index 8d03275..4cddd33 100644 --- a/src/app/(protected)/reservations/create.tsx +++ b/src/app/(protected)/reservations/create.tsx @@ -1,4 +1,9 @@ -import { Link, useLocalSearchParams } from 'expo-router'; +import { useCreateReservation } from "@/features/reservations/hooks/useCreateReservation"; +import { useUpdateReservation } from "@/features/reservations/hooks/useUpdateReservation"; +import { StatusMessage } from "@/shared/ui/StatusMessage"; +import theme from "@/theme"; +import { MaterialIcons } from "@expo/vector-icons"; +import { Link, useLocalSearchParams, useRouter } from "expo-router"; import { KeyboardAvoidingView, Platform, @@ -8,27 +13,61 @@ import { Text, TextInput, View, -} from 'react-native'; -import { MaterialIcons } from '@expo/vector-icons'; -import theme from '@/theme'; -import { useCreateReservation } from '@/features/reservations/hooks/useCreateReservation'; -import { StatusMessage } from '@/shared/ui/StatusMessage'; +} from "react-native"; -const { colors, spacing, radius, typography, fontWeight, layout, shadows } = theme; +const { colors, spacing, radius, typography, fontWeight, layout, shadows } = + theme; export default function CreateReservationScreen() { + // router para navegar + const router = useRouter(); + // parametros recibidos al entrar desde otra pantalla const params = useLocalSearchParams<{ + mode?: string; + reservationId?: string; officeId?: string; officeName?: string; + date?: string; + startTime?: string; + endTime?: string; + oldDate?: string; + oldStartTime?: string; + oldEndTime?: string; }>(); + // determinar si estamos en modo crear o editar + const isEditMode = params.mode === "edit"; + + // extraer parametros de creacion const officeId = - typeof params.officeId === 'string' ? params.officeId : undefined; + typeof params.officeId === "string" ? params.officeId : undefined; const officeName = - typeof params.officeName === 'string' ? params.officeName : undefined; + typeof params.officeName === "string" ? params.officeName : undefined; + + // extraer parametros de edicion + const reservationId = + typeof params.reservationId === "string" ? params.reservationId : ""; + const oldDate = typeof params.oldDate === "string" ? params.oldDate : ""; + const oldStartTime = + typeof params.oldStartTime === "string" ? params.oldStartTime : ""; + const oldEndTime = + typeof params.oldEndTime === "string" ? params.oldEndTime : ""; + + // usar el hook correspondiente segun el modo + const createReservation = useCreateReservation({ officeId, officeName }); + const updateReservation = useUpdateReservation({ + reservationId, + officeId: officeId || params.officeId || "", + officeName: officeName || params.officeName || "", + oldDate, + oldStartTime, + oldEndTime, + }); + + // seleccionar el hook activo segun el modo + const hook = isEditMode ? updateReservation : createReservation; - // hook de creacion de reserva const { date, startTime, @@ -36,21 +75,22 @@ export default function CreateReservationScreen() { isFormComplete, isSubmitting, error, - successMessage, setDate, setStartTime, setEndTime, submit, - } = useCreateReservation({ officeId, officeName }); + } = hook; return ( {/* cabecera superior */} - Crear reserva + + {isEditMode ? "Editar reserva" : "Crear reserva"} + {/* texto introductorio */} - Nueva reserva + + {isEditMode ? "Editar reserva" : "Nueva reserva"} + - Selecciona el espacio, la fecha y el horario de tu reserva. + {isEditMode + ? "Actualiza el horario de tu reserva." + : "Selecciona el espacio, la fecha y el horario de tu reserva."} @@ -81,27 +125,29 @@ export default function CreateReservationScreen() { Espacio - {officeName ?? 'No indicado'} + {officeName ?? "No indicado"} {/* enlace para volver a oficinas */} - - - [ - styles.changeOfficeButton, - pressed && styles.changeOfficeButtonPressed, - ]} - > - - Cambiar oficina - - - - + {!isEditMode && ( + + + [ + styles.changeOfficeButton, + pressed && styles.changeOfficeButtonPressed, + ]} + > + + Cambiar oficina + + + + + )} {/* tarjeta de condiciones de reserva */} @@ -110,25 +156,15 @@ export default function CreateReservationScreen() { - + Horario permitido: de 08:00 a 20:00 - - - Duración mínima: 30 minutos - + + Duración mínima: 30 minutos @@ -137,9 +173,7 @@ export default function CreateReservationScreen() { size={16} color={colors.primary} /> - - Duración máxima: 8 horas - + Duración máxima: 8 horas @@ -153,21 +187,21 @@ export default function CreateReservationScreen() { Fecha {/* en web usamos calendario nativo */} - {Platform.OS === 'web' ? ( + {Platform.OS === "web" ? ( setDate(e.target.value)} - min={new Date().toISOString().split('T')[0]} + min={new Date().toISOString().split("T")[0]} style={{ height: 46, border: `1px solid ${colors.border}`, borderRadius: radius.md, - padding: '0 14px', + padding: "0 14px", fontSize: 14, color: colors.text, backgroundColor: colors.background, - outline: 'none', + outline: "none", }} /> ) : ( @@ -183,9 +217,9 @@ export default function CreateReservationScreen() { )} - {Platform.OS === 'web' - ? 'Selecciona una fecha en el calendario' - : 'Formato: YYYY-MM-DD'} + {Platform.OS === "web" + ? "Selecciona una fecha en el calendario" + : "Formato: YYYY-MM-DD"} @@ -222,11 +256,8 @@ export default function CreateReservationScreen() { {/* mensajes de error / exito */} {error ? : null} - {successMessage ? ( - - ) : null} - {/* boton principal de guardar */} + {/* boton principal de guardar / actualizar */} [ styles.primaryButton, @@ -240,10 +271,32 @@ export default function CreateReservationScreen() { disabled={!isFormComplete || isSubmitting} > - {isSubmitting ? 'Guardando...' : 'Guardar reserva'} + {isSubmitting + ? isEditMode + ? "Actualizando..." + : "Guardando..." + : isEditMode + ? "Actualizar reserva" + : "Guardar reserva"} + + {/* boton cancelar fuera de la tarjeta */} + {isEditMode && ( + [ + styles.cancelButton, + pressed && styles.cancelButtonPressed, + ]} + onPress={() => router.back()} + > + + + Cancelar + + + )} ); @@ -271,10 +324,10 @@ const styles = StyleSheet.create({ fontSize: typography.xxl, fontWeight: fontWeight.semibold, color: colors.text, - textAlign: 'left', + textAlign: "left", maxWidth: layout.contentWidth, - width: '100%', - alignSelf: 'center', + width: "100%", + alignSelf: "center", }, // scroll principal @@ -290,8 +343,8 @@ const styles = StyleSheet.create({ paddingBottom: spacing.xxxl, gap: spacing.xl, maxWidth: layout.contentWidth, - width: '100%', - alignSelf: 'center', + width: "100%", + alignSelf: "center", }, // bloque introductorio @@ -326,26 +379,26 @@ const styles = StyleSheet.create({ // tarjeta de condiciones con tono azul suave rulesCard: { - backgroundColor: '#F4F8FF', + backgroundColor: "#F4F8FF", borderRadius: radius.xxl, padding: spacing.lg, borderWidth: 1, - borderColor: '#D7E3F7', + borderColor: "#D7E3F7", gap: spacing.md, }, // cabecera de tarjeta cardHeader: { - flexDirection: 'row', - alignItems: 'flex-start', - justifyContent: 'space-between', + flexDirection: "row", + alignItems: "flex-start", + justifyContent: "space-between", gap: spacing.md, }, // bloque izquierdo de cabecera cardHeaderLeft: { - flexDirection: 'row', - alignItems: 'flex-start', + flexDirection: "row", + alignItems: "flex-start", gap: spacing.md, flex: 1, }, @@ -356,8 +409,8 @@ const styles = StyleSheet.create({ height: 40, borderRadius: radius.md, backgroundColor: colors.primarySoft, - alignItems: 'center', - justifyContent: 'center', + alignItems: "center", + justifyContent: "center", }, // bloque de textos de la tarjeta @@ -382,8 +435,8 @@ const styles = StyleSheet.create({ // boton secundario para cambiar oficina changeOfficeRow: { - width: '100%', - alignItems: 'flex-end', + width: "100%", + alignItems: "flex-end", }, changeOfficeButton: { paddingVertical: spacing.xs, @@ -393,7 +446,7 @@ const styles = StyleSheet.create({ // estado pulsado del boton cambiar oficina changeOfficeButtonPressed: { - backgroundColor: '#EAF2FF', + backgroundColor: "#EAF2FF", }, // texto del boton cambiar oficina @@ -424,8 +477,8 @@ const styles = StyleSheet.create({ // fila de una regla ruleRow: { - flexDirection: 'row', - alignItems: 'center', + flexDirection: "row", + alignItems: "center", gap: spacing.sm, }, @@ -443,7 +496,7 @@ const styles = StyleSheet.create({ // fila de campos de hora timeRow: { - flexDirection: 'row', + flexDirection: "row", gap: spacing.lg, }, @@ -481,19 +534,19 @@ const styles = StyleSheet.create({ backgroundColor: colors.primary, paddingVertical: spacing.lg, borderRadius: radius.md, - alignItems: 'center', - justifyContent: 'center', + alignItems: "center", + justifyContent: "center", marginTop: spacing.sm, }, // estado pulsado del boton principal primaryButtonPressed: { - backgroundColor: '#185DCB', + backgroundColor: "#185DCB", }, // boton deshabilitado primaryButtonDisabled: { - backgroundColor: '#8FB5EC', + backgroundColor: "#8FB5EC", }, // texto del boton principal @@ -502,4 +555,33 @@ const styles = StyleSheet.create({ fontWeight: fontWeight.semibold, fontSize: typography.md, }, -}); \ No newline at end of file + + // boton cancelar reserva + cancelButton: { + paddingVertical: spacing.sm, + paddingHorizontal: spacing.md, + borderRadius: radius.md, + backgroundColor: colors.surface, + alignItems: "center", + justifyContent: "center", + }, + + // estado pulsado del boton cancelar + cancelButtonPressed: { + backgroundColor: "#FEECEC", + }, + + // texto del boton cancelar + cancelButtonText: { + color: "#DC2626", + fontWeight: fontWeight.medium, + fontSize: typography.sm, + }, + + // contenido interno del boton cancelar + cancelContent: { + flexDirection: "row", + alignItems: "center", + gap: spacing.xs, + }, +}); 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 From e8914f03cce7db31485ec26912ac7c20ec3165ce Mon Sep 17 00:00:00 2001 From: Anita Date: Sun, 19 Apr 2026 19:21:17 +0100 Subject: feat(profile): edición de perfil con bio, teléfono y empresa + validación de bio (200 caracteres) refs #5 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/(protected)/(tabs)/profile/index.tsx | 173 ++++++++++++++++++------ src/features/profile/hooks/useUpdateProfile.ts | 40 +++++- src/features/profile/services/profileService.ts | 67 +++++++-- src/features/profile/types.ts | 3 + 4 files changed, 224 insertions(+), 59 deletions(-) diff --git a/src/app/(protected)/(tabs)/profile/index.tsx b/src/app/(protected)/(tabs)/profile/index.tsx index c15db39..0439708 100644 --- a/src/app/(protected)/(tabs)/profile/index.tsx +++ b/src/app/(protected)/(tabs)/profile/index.tsx @@ -1,6 +1,14 @@ import { useEffect, useMemo, useState } from 'react'; import theme from '@/theme'; -import {ActivityIndicator, Pressable, ScrollView, StyleSheet, Text, TextInput, View,} from 'react-native'; +import { + ActivityIndicator, + Pressable, + ScrollView, + StyleSheet, + Text, + TextInput, + View, +} from 'react-native'; import { Feather } from '@expo/vector-icons'; import { Image } from 'expo-image'; import { useAuthSession } from '@/providers/AuthProvider'; @@ -21,17 +29,30 @@ export default function ProfileScreen() { // hook para cargar datos del perfil const { profile, loading, error, reload } = useProfile(); - // hook para actualizar nombre y foto del perfil + // hook para actualizar los campos editables del perfil const { displayName, photoURL, + phone, + company, + bio, setPhotoURL, setDisplayName, + setPhone, + setCompany, + setBio, isSubmitting, error: updateError, successMessage, + maxBioLength, submit, - } = useUpdateProfile(profile?.displayName ?? '', profile?.photoURL ?? ''); + } = useUpdateProfile( + profile?.displayName ?? '', + profile?.photoURL ?? '', + profile?.phone ?? '', + profile?.company ?? '', + profile?.bio ?? '', + ); // hook de favoritos del usuario const { @@ -57,7 +78,7 @@ export default function ProfileScreen() { const checkedInReservationsCount = useMemo(() => { return reservations.filter((reservation) => reservation.checkInAt).length; }, [reservations]); - + // cruce entre ids favoritos y lista completa de oficinas // para obtener los datos reales de las oficinas favoritas const favoriteOffices = useMemo(() => { @@ -102,7 +123,21 @@ export default function ProfileScreen() { } setPhotoURL(profile?.photoURL ?? ''); - }, [profile?.displayName, profile?.photoURL, setDisplayName, setPhotoURL]); + setPhone(profile?.phone ?? ''); + setCompany(profile?.company ?? ''); + setBio(profile?.bio ?? ''); + }, [ + profile?.displayName, + profile?.photoURL, + profile?.phone, + profile?.company, + profile?.bio, + setDisplayName, + setPhotoURL, + setPhone, + setCompany, + setBio, + ]); // cerrar sesion y redirigir a pantalla de bienvenida const handleLogout = async () => { @@ -116,6 +151,9 @@ export default function ProfileScreen() { if (isEditing) { setDisplayName(profile?.displayName ?? ''); setPhotoURL(profile?.photoURL ?? ''); + setPhone(profile?.phone ?? ''); + setCompany(profile?.company ?? ''); + setBio(profile?.bio ?? ''); } setIsEditing((current) => !current); @@ -123,8 +161,12 @@ export default function ProfileScreen() { // guardar cambios del perfil const handleSaveProfile = async () => { - await submit(); - setIsEditing(false); + const wasSaved = await submit(); + + if (wasSaved) { + setIsEditing(false); + reload(); + } }; // estado de carga inicial del perfil @@ -154,13 +196,14 @@ export default function ProfileScreen() { style={styles.container} contentContainerStyle={styles.content} showsVerticalScrollIndicator={false} - > + > {/* cabecera superior visual dentro del scroll */} Perfil + {/* tarjeta cabecera del perfil */} - {/* avatar, nombre, correo y boton editar / cancelar */} + {/* avatar, nombre, correo y boton editar o cancelar */} {photoURL ? ( @@ -180,7 +223,7 @@ export default function ProfileScreen() { {/* correo del usuario */} {profile.email} - {/* boton editar perfil / cancelar */} + {/* boton editar perfil o cancelar */} {isEditing ? 'Cancelar' : 'Editar perfil'} @@ -191,22 +234,40 @@ export default function ProfileScreen() { {/* seccion sobre mi */} - {/* solo visual por ahora, FALTA CONEXION CON FIREBASE PARA GUARDAR INFO */} - Sobre mí + Sobre mi - - Espacio personal del usuario para mostrar una breve descripción o - presentación dentro de la aplicación. - + {isEditing ? ( + <> + {/* campo editable para la descripcion personal */} + + + {/* contador visual para orientar el limite de la bio */} + + {bio.length}/{maxBioLength} caracteres + + + ) : ( + + {bio?.trim() || 'Todavia no has anadido una descripcion personal.'} + + )} {/* seccion informacion personal */} {/* en modo vista muestra datos y en modo edicion muestra formulario */} - Información personal + Informacion personal {isEditing ? ( @@ -231,6 +292,25 @@ export default function ProfileScreen() { autoCorrect={false} /> + {/* formulario de edicion: telefono */} + Telefono + + + {/* formulario de edicion: empresa */} + Empresa + + {/* mensajes de error o exito al guardar */} {updateError ? : null} {successMessage ? ( @@ -263,28 +343,30 @@ export default function ProfileScreen() { - Correo electrónico + Correo electronico {profile.email} {/* fila de telefono */} - {/* por ahora es solo visual, FALTA CONEXION CON FIREBASE */} - Teléfono - +34 600 123 456 + Telefono + + {phone?.trim() || 'No especificado'} + {/* fila de empresa */} - {/* por ahora es solo visual, FALTA CONEXION CON FIREBASE */} Empresa - Empresa Innovadora S.L. + + {company?.trim() || 'No especificada'} + @@ -314,7 +396,7 @@ export default function ProfileScreen() { {mostUsedFavoriteOffice ? `Top de favoritos: ${mostUsedFavoriteOffice.name}.` - : 'Aún no tienes suficiente actividad para destacar un espacio favorito.'} + : 'Aun no tienes suficiente actividad para destacar un espacio favorito.'} @@ -332,7 +414,7 @@ export default function ProfileScreen() { ) : favoriteOffices.length === 0 ? ( - Todavía no has marcado oficinas como favoritas. + Todavia no has marcado oficinas como favoritas. ) : ( <> @@ -358,8 +440,8 @@ export default function ProfileScreen() { ))} - {/* enlace visual para ver todos los favoritos - solo aparece si hay mas de 3 favoritos */} + {/* enlace visual para ver todos los favoritos */} + {/* solo aparece si hay mas de 3 favoritos */} {favoriteOffices.length > 3 ? ( Ver todos @@ -373,7 +455,7 @@ export default function ProfileScreen() { {/* seccion cierre de sesion */} - Cerrar sesión + Cerrar sesion @@ -391,7 +473,7 @@ const styles = StyleSheet.create({ }, // contenido interno del scroll - // padding general, separacion entre bloques y el ancho maximo + // padding general, separacion entre bloques y el ancho maximo // para mantener consistencia con otras pantallas content: { padding: spacing.xl, @@ -493,7 +575,7 @@ const styles = StyleSheet.create({ color: colors.textSecondary, }, - // boton pequeno de editar / cancelar + // boton pequeno de editar o cancelar editButton: { marginTop: spacing.xs, borderWidth: 1, @@ -504,7 +586,7 @@ const styles = StyleSheet.create({ alignSelf: 'flex-start', }, - // texto del boton editar / cancelar + // texto del boton editar o cancelar editButtonText: { color: colors.primary, fontSize: typography.sm, @@ -576,18 +658,13 @@ const styles = StyleSheet.create({ }, // bloque de actividad - // muestra resumen narrativo del uso de la app - activityText: { - fontSize: typography.md, - color: colors.textSecondary, - lineHeight: 20, - }, - // fila individual de actividad + // fila individual de actividad activityItem: { flexDirection: 'row', alignItems: 'flex-start', gap: spacing.md, }, + // punto visual de cada item de actividad activityDot: { width: 8, @@ -596,6 +673,7 @@ const styles = StyleSheet.create({ backgroundColor: colors.primary, marginTop: 6, }, + // texto de la seccion actividad activityText: { flex: 1, @@ -620,7 +698,7 @@ const styles = StyleSheet.create({ color: colors.text, }, - // texto pequeno junto al numero + // texto pequeno junto al numero favoriteSummaryText: { fontSize: typography.sm, color: colors.textSecondary, @@ -674,7 +752,7 @@ const styles = StyleSheet.create({ color: colors.textSecondary, }, - // boton / enlace visual para ver todos los favoritos + // boton o enlace visual para ver todos los favoritos viewAllButton: { marginTop: spacing.xs, alignSelf: 'flex-start', @@ -705,6 +783,18 @@ const styles = StyleSheet.create({ backgroundColor: colors.surface, }, + // variante del input para textos mas largos + textArea: { + minHeight: 120, + }, + + // texto de apoyo para el limite de caracteres + helperText: { + fontSize: typography.sm, + color: colors.textSecondary, + textAlign: 'right', + }, + // boton principal de guardar cambios button: { backgroundColor: colors.primary, @@ -741,6 +831,7 @@ const styles = StyleSheet.create({ color: colors.error, fontWeight: fontWeight.regular, }, + // contenido interno del boton cerrar sesion // alinea icono y texto en horizontal logoutContent: { @@ -762,4 +853,4 @@ const styles = StyleSheet.create({ color: colors.error, textAlign: 'center', }, -}); \ No newline at end of file +}); diff --git a/src/features/profile/hooks/useUpdateProfile.ts b/src/features/profile/hooks/useUpdateProfile.ts index cd4a39a..f8f20f9 100644 --- a/src/features/profile/hooks/useUpdateProfile.ts +++ b/src/features/profile/hooks/useUpdateProfile.ts @@ -5,11 +5,22 @@ 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 MAX_BIO_LENGTH = 200; + +export function useUpdateProfile( + initialDisplayName = '', + initialPhotoURL = '', + initialPhone = '', + initialCompany = '', + initialBio = '', +) { const { user } = useAuthSession(); const [displayName, setDisplayName] = useState(initialDisplayName); const [photoURL, setPhotoURL] = useState(initialPhotoURL); + const [phone, setPhone] = useState(initialPhone); + const [company, setCompany] = useState(initialCompany); + const [bio, setBio] = useState(initialBio); const [isSubmitting, setIsSubmitting] = useState(false); const [error, setError] = useState(null); const [successMessage, setSuccessMessage] = useState(null); @@ -17,12 +28,18 @@ export function useUpdateProfile(initialDisplayName = '', initialPhotoURL = '') const submit = async () => { if (!user?.uid) { setError('No hay usuario autenticado'); - return; + return false; } if (!displayName.trim()) { - setError('El nombre no puede estar vacío'); - return; + setError('El nombre no puede estar vacio'); + return false; + } + + // validacion del campo bio antes de enviar los cambios + if (bio.trim().length > MAX_BIO_LENGTH) { + setError(`La bio no puede superar los ${MAX_BIO_LENGTH} caracteres`); + return false; } try { @@ -34,12 +51,20 @@ export function useUpdateProfile(initialDisplayName = '', initialPhotoURL = '') uid: user.uid, displayName: displayName.trim(), photoURL: photoURL.trim(), + phone: phone.trim(), + company: company.trim(), + bio: bio.trim(), }); setPhotoURL(photoURL.trim()); + setPhone(phone.trim()); + setCompany(company.trim()); + setBio(bio.trim()); setSuccessMessage('Perfil actualizado correctamente'); + return true; } catch (err) { setError(getErrorMessage(err, 'No se pudo actualizar el perfil')); + return false; } finally { setIsSubmitting(false); } @@ -48,11 +73,18 @@ export function useUpdateProfile(initialDisplayName = '', initialPhotoURL = '') return { displayName, photoURL, + phone, + company, + bio, setDisplayName, setPhotoURL, + setPhone, + setCompany, + setBio, isSubmitting, error, successMessage, + maxBioLength: MAX_BIO_LENGTH, submit, }; } diff --git a/src/features/profile/services/profileService.ts b/src/features/profile/services/profileService.ts index f7e89b4..c202c18 100644 --- a/src/features/profile/services/profileService.ts +++ b/src/features/profile/services/profileService.ts @@ -1,13 +1,21 @@ // src/features/profile/services/profileService.ts -import { doc, getDoc, setDoc } from 'firebase/firestore'; -import { updateProfile } from 'firebase/auth'; -import { db, auth } from '@/shared/lib/firebase/config'; -import { UserProfile } from '@/features/profile/types'; +import { UserProfile } from "@/features/profile/types"; +import { auth, db } from "@/shared/lib/firebase/config"; +import { mockDelay, mockUserProfile } from "@/shared/lib/mockData"; +import { updateProfile } from "firebase/auth"; +import { doc, getDoc, setDoc } from "firebase/firestore"; + +const USE_MOCK = process.env.EXPO_PUBLIC_USE_MOCK_DATA === "true"; export const profileService = { async getMyProfile(uid: string): Promise { - const snapshot = await getDoc(doc(db, 'users', uid)); + if (USE_MOCK) { + await mockDelay(); + return mockUserProfile.uid === uid ? mockUserProfile : null; + } + + const snapshot = await getDoc(doc(db, "users", uid)); if (!snapshot.exists()) { return null; @@ -17,9 +25,12 @@ export const profileService = { return { uid, - email: data.email ?? '', - displayName: data.displayName ?? '', - photoURL: data.photoURL ?? '', + email: data.email ?? "", + displayName: data.displayName ?? "", + photoURL: data.photoURL ?? "", + phone: data.phone ?? "", + company: data.company ?? "", + bio: data.bio ?? "", }; }, @@ -27,15 +38,43 @@ export const profileService = { uid: string; displayName: string; photoURL?: string; + phone?: string; + company?: string; + bio?: string; }): Promise { - const { uid, displayName, photoURL } = params; + if (USE_MOCK) { + await mockDelay(); + mockUserProfile.displayName = params.displayName; + if (params.photoURL !== undefined) { + mockUserProfile.photoURL = params.photoURL; + } + if (params.phone !== undefined) { + mockUserProfile.phone = params.phone; + } + if (params.company !== undefined) { + mockUserProfile.company = params.company; + } + if (params.bio !== undefined) { + mockUserProfile.bio = params.bio; + } + return; + } + + const { uid, displayName, photoURL, phone, company, bio } = params; const currentUser = auth.currentUser; - await setDoc(doc(db, 'users', uid), { - email: currentUser?.email ?? '', - displayName, - ...(photoURL !== undefined ? { photoURL } : {}), - }, { merge: true }); + await setDoc( + doc(db, "users", uid), + { + email: currentUser?.email ?? "", + displayName, + ...(photoURL !== undefined ? { photoURL } : {}), + ...(phone !== undefined ? { phone } : {}), + ...(company !== undefined ? { company } : {}), + ...(bio !== undefined ? { bio } : {}), + }, + { merge: true }, + ); if (currentUser) { await updateProfile(currentUser, { diff --git a/src/features/profile/types.ts b/src/features/profile/types.ts index 1c6d219..579d5db 100644 --- a/src/features/profile/types.ts +++ b/src/features/profile/types.ts @@ -5,4 +5,7 @@ export type UserProfile = { email: string; displayName: string; photoURL?: string; + phone?: string; // numero de telefono del usuario + company?: string; // empresa donde trabaja el usuario + bio?: string; // descripcion personal o "acerca de mi" (max 200 caracteres) }; -- cgit v1.2.3-54-g00ecf From 8dd49e680bfea6886839a8841dd829d7f6e71ce8 Mon Sep 17 00:00:00 2001 From: Anita Date: Sun, 19 Apr 2026 19:22:57 +0100 Subject: feat(home): mejora sección estadísticas de uso refs #4 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/(protected)/(tabs)/home.tsx | 171 ++++++++++++++++++++---------------- 1 file changed, 95 insertions(+), 76 deletions(-) diff --git a/src/app/(protected)/(tabs)/home.tsx b/src/app/(protected)/(tabs)/home.tsx index e3458ab..ea6c5cc 100644 --- a/src/app/(protected)/(tabs)/home.tsx +++ b/src/app/(protected)/(tabs)/home.tsx @@ -1,31 +1,38 @@ -import { useReservations } from '@/features/reservations/hooks/useReservations'; -import { useAuthSession } from '@/providers/AuthProvider'; -import theme from '@/theme'; -import { Feather, MaterialIcons } from '@expo/vector-icons'; -import { Link } from 'expo-router'; -import { useMemo } from 'react'; -import { ActivityIndicator, Pressable, StyleSheet, Text, View } from 'react-native'; +import { useReservations } from "@/features/reservations/hooks/useReservations"; +import { useAuthSession } from "@/providers/AuthProvider"; +import theme from "@/theme"; +import { Feather, MaterialIcons } from "@expo/vector-icons"; +import { Link } from "expo-router"; +import { useMemo } from "react"; +import { + ActivityIndicator, + Pressable, + StyleSheet, + Text, + View, +} from "react-native"; function formatDate(date: string): string { const parsedDate = new Date(date); - // formato fecha - return parsedDate.toLocaleDateString('es-ES', { - day: '2-digit', - month: 'short', - year: 'numeric', - }); - } + // formato fecha + return parsedDate.toLocaleDateString("es-ES", { + day: "2-digit", + month: "short", + year: "numeric", + }); +} // creacion de acceso rapidos al theme de estilos -const { colors, spacing, radius, typography, fontWeight, layout, shadows } = theme; +const { colors, spacing, radius, typography, fontWeight, layout, shadows } = + theme; export default function HomeScreen() { const { user } = useAuthSession(); - const { reservations, activeReservations, loading, error } = useReservations(); - + const { reservations, activeReservations, loading, error } = + useReservations(); // crea el contador de reservas en el mes actual - const currentMonthReservationsCount = useMemo(() => { + const currentMonthReservationsCount = useMemo(() => { const now = new Date(); const currentMonth = now.getMonth(); const currentYear = now.getFullYear(); @@ -42,7 +49,7 @@ export default function HomeScreen() { // crea una lista con las 2 primeras reservas activas const previewReservations = useMemo( () => activeReservations.slice(0, 2), - [activeReservations] + [activeReservations], ); if (loading) { @@ -66,12 +73,10 @@ export default function HomeScreen() { {/* cabecera de bienvenida */} - Hola{user?.displayName ? `, ${user.displayName}` : ''} 👋 + Hola{user?.displayName ? `, ${user.displayName}` : ""} 👋 - - Bienvenido a la App Oficina - + Bienvenido a la App Oficina {/* seccion de accesos rapidos */} @@ -111,7 +116,7 @@ export default function HomeScreen() { Ver todas - {'>'} + {">"} @@ -122,20 +127,28 @@ export default function HomeScreen() { previewReservations.map((reservation) => ( - - + - - {reservation.officeName} - {'>'} + + {reservation.officeName} + + {">"} - + {formatDate(reservation.date)} @@ -162,11 +175,10 @@ export default function HomeScreen() { : styles.statusTextPending, ]} > - {reservation.checkInAt ? 'Confirmada' : 'Pendiente'} + {reservation.checkInAt ? "Confirmada" : "Pendiente"} - @@ -181,6 +193,10 @@ export default function HomeScreen() { {/* seccion de estadisticas */} + + Estadísticas de uso + + {activeReservations.length} @@ -210,14 +226,14 @@ const styles = StyleSheet.create({ paddingBottom: spacing.xl, gap: 18, maxWidth: layout.contentWidth, - width: '100%', - alignSelf: 'center', + width: "100%", + alignSelf: "center", backgroundColor: colors.background, }, center: { flex: 1, - alignItems: 'center', - justifyContent: 'center', + alignItems: "center", + justifyContent: "center", padding: spacing.xxxl, backgroundColor: colors.background, }, @@ -248,7 +264,7 @@ const styles = StyleSheet.create({ gap: spacing.lg, }, quickAccessRow: { - flexDirection: 'row', + flexDirection: "row", gap: spacing.lg, }, quickAccessButton: { @@ -256,8 +272,8 @@ const styles = StyleSheet.create({ backgroundColor: colors.primary, paddingVertical: spacing.xxxl, borderRadius: radius.xl, - alignItems: 'center', - justifyContent: 'center', + alignItems: "center", + justifyContent: "center", gap: spacing.md, minHeight: 120, }, @@ -266,8 +282,8 @@ const styles = StyleSheet.create({ backgroundColor: colors.primaryDark, paddingVertical: spacing.xxxl, borderRadius: radius.xl, - alignItems: 'center', - justifyContent: 'center', + alignItems: "center", + justifyContent: "center", gap: spacing.md, minHeight: 112, }, @@ -277,7 +293,7 @@ const styles = StyleSheet.create({ color: colors.white, fontWeight: fontWeight.regular, fontSize: typography.md, - textAlign: 'center', + textAlign: "center", lineHeight: 16, }, //---------------------------------- @@ -286,28 +302,28 @@ const styles = StyleSheet.create({ width: 40, height: 40, borderRadius: radius.md, - backgroundColor: '#3b82f6', - alignItems: 'center', - justifyContent: 'center', + backgroundColor: "#3b82f6", + alignItems: "center", + justifyContent: "center", }, quickAccessIconContainerDark: { width: 40, height: 40, borderRadius: radius.md, - backgroundColor: '#334e68', - alignItems: 'center', - justifyContent: 'center', + backgroundColor: "#334e68", + alignItems: "center", + justifyContent: "center", }, // estilos de reservas activas reservationsHeader: { - flexDirection: 'row', - justifyContent: 'space-between', - alignItems: 'center', + flexDirection: "row", + justifyContent: "space-between", + alignItems: "center", }, linkRow: { - flexDirection: 'row', - alignItems: 'center', + flexDirection: "row", + alignItems: "center", gap: spacing.xs, }, chevronSmall: { @@ -333,7 +349,7 @@ const styles = StyleSheet.create({ ...shadows.card, }, reservationContent: { - flexDirection: 'row', + flexDirection: "row", gap: spacing.lg, }, reservationIconContainer: { @@ -341,17 +357,17 @@ const styles = StyleSheet.create({ height: 48, borderRadius: radius.lg, backgroundColor: colors.primarySoft, - alignItems: 'center', - justifyContent: 'center', + alignItems: "center", + justifyContent: "center", }, reservationInfo: { flex: 1, gap: spacing.sm, }, reservationHeader: { - flexDirection: 'row', - justifyContent: 'space-between', - alignItems: 'center', + flexDirection: "row", + justifyContent: "space-between", + alignItems: "center", }, reservationOffice: { fontSize: 18, @@ -364,8 +380,8 @@ const styles = StyleSheet.create({ fontWeight: fontWeight.semibold, }, reservationMetaRow: { - flexDirection: 'row', - alignItems: 'center', + flexDirection: "row", + alignItems: "center", gap: spacing.sm, }, reservationMeta: { @@ -373,9 +389,9 @@ const styles = StyleSheet.create({ fontSize: typography.md, }, reservationRow: { - flexDirection: 'row', - justifyContent: 'space-between', - alignItems: 'center', + flexDirection: "row", + justifyContent: "space-between", + alignItems: "center", }, reservationTime: { color: colors.text, @@ -383,13 +399,13 @@ const styles = StyleSheet.create({ flex: 1, }, statusBadge: { - alignSelf: 'flex-start', + alignSelf: "flex-start", backgroundColor: colors.successBg, paddingHorizontal: 10, paddingVertical: spacing.xs, borderRadius: radius.sm, }, - // estado confirmada (verde) + // estado confirmada (verde) statusConfirmed: { backgroundColor: colors.successBg, }, @@ -399,12 +415,12 @@ const styles = StyleSheet.create({ }, // estado pendiente (gris neutro) statusPending: { - backgroundColor: '#EEF2F6', + backgroundColor: "#EEF2F6", }, statusTextPending: { - color: '#475569', + color: "#475569", }, - + statusText: { color: colors.successText, fontWeight: fontWeight.semibold, @@ -419,12 +435,15 @@ const styles = StyleSheet.create({ }, emptyReservationText: { color: colors.textSecondary, - textAlign: 'center', + textAlign: "center", }, //estilos estadisticas + statsHeader: { + marginBottom: spacing.md, + }, statsGrid: { - flexDirection: 'row', + flexDirection: "row", gap: spacing.lg, }, statCard: { @@ -437,8 +456,8 @@ const styles = StyleSheet.create({ minHeight: 115, backgroundColor: colors.surface, gap: spacing.sm, - alignItems: 'center', - justifyContent: 'space-between', + alignItems: "center", + justifyContent: "space-between", }, // --- estilos textos estadisticas @@ -451,12 +470,12 @@ const styles = StyleSheet.create({ color: colors.textSecondary, fontSize: typography.sm, fontWeight: fontWeight.regular, - textAlign: 'center', + textAlign: "center", }, //-------------------------------- error: { color: colors.error, - textAlign: 'center', + textAlign: "center", }, -}); \ No newline at end of file +}); -- cgit v1.2.3-54-g00ecf From ed3b1eaacc7a209ae038ea68b195e8b2926df92f Mon Sep 17 00:00:00 2001 From: Anita Date: Sun, 19 Apr 2026 19:23:42 +0100 Subject: feat(firebase): actualización de reglas para permitir edición de reservas refs #11 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- firestore.rules | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/firestore.rules b/firestore.rules index 4d45ca3..daddd37 100644 --- a/firestore.rules +++ b/firestore.rules @@ -21,19 +21,21 @@ service cloud.firestore { } function reservationUpdateIsValid() { + // validar que no cambien los campos inmutables return request.resource.data.userId == resource.data.userId && request.resource.data.officeId == resource.data.officeId && request.resource.data.officeName == resource.data.officeName && request.resource.data.userEmail == resource.data.userEmail - && request.resource.data.date == resource.data.date - && request.resource.data.startTime == resource.data.startTime - && request.resource.data.endTime == resource.data.endTime + && request.resource.data.status in ['active', 'completed', 'cancelled'] + // permitir cambios en date, startTime, endTime + && request.resource.data.date is string + && request.resource.data.startTime is string + && request.resource.data.endTime is string && ( !('checkInAt' in resource.data) || request.resource.data.checkInAt == resource.data.checkInAt || request.resource.data.checkInAt is timestamp - ) - && request.resource.data.status in ['active', 'completed', 'cancelled']; + ); } match /users/{userId} { -- cgit v1.2.3-54-g00ecf From 4d0962a44715f71acd2fc9ea59bf87d8da70f662 Mon Sep 17 00:00:00 2001 From: Anita Date: Sun, 19 Apr 2026 19:24:19 +0100 Subject: chore(config): ajuste TypeScript por deprecación de baseUrl (TS6) refs #10 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tsconfig.json | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/tsconfig.json b/tsconfig.json index 0b8b6c6..3fe2c77 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,14 +2,10 @@ "extends": "expo/tsconfig.base", "compilerOptions": { "baseUrl": ".", + "ignoreDeprecations": "6.0", "paths": { "@/*": ["src/*"] } }, - "include": [ - "**/*.ts", - "**/*.tsx", - ".expo/types/**/*.ts", - "expo-env.d.ts" - ] + "include": ["**/*.ts", "**/*.tsx", ".expo/types/**/*.ts", "expo-env.d.ts"] } -- cgit v1.2.3-54-g00ecf