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(-) (limited to 'src/app/(protected)/(tabs)/profile/index.tsx') 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 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(-) (limited to 'src/app/(protected)/(tabs)/profile/index.tsx') 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