diff options
| author | Alberto Duarte Delgado <alberto@albertoduarte.com> | 2026-04-19 21:46:46 +0100 |
|---|---|---|
| committer | Alberto Duarte Delgado <alberto@albertoduarte.com> | 2026-04-19 21:46:46 +0100 |
| commit | be90a5f202f80bb423c6e0aaf1c4d5feca668f01 (patch) | |
| tree | c91081a6c60d2f1efb4de22c324721c5d798e3ee /src/app | |
| parent | 40cc6cea25d048c2e77e11bbfea0cd1e5eb784f6 (diff) | |
| parent | 4d0962a44715f71acd2fc9ea59bf87d8da70f662 (diff) | |
Merge branch 'feature/anita' into develop
Diffstat (limited to 'src/app')
| -rw-r--r-- | src/app/(auth)/login.tsx | 52 | ||||
| -rw-r--r-- | src/app/(auth)/register.tsx | 85 | ||||
| -rw-r--r-- | src/app/(protected)/(tabs)/home.tsx | 171 | ||||
| -rw-r--r-- | src/app/(protected)/(tabs)/profile/index.tsx | 337 | ||||
| -rw-r--r-- | src/app/(protected)/(tabs)/reservations/index.tsx | 220 | ||||
| -rw-r--r-- | src/app/(protected)/reservations/create.tsx | 250 |
6 files changed, 734 insertions, 381 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 ( <View style={styles.container}> {/* contenido central acotado */} @@ -42,17 +59,32 @@ export default function LoginScreen() { {/* campo contraseña */} <Text style={styles.label}>Contraseña</Text> - <TextInput - style={styles.input} - placeholder="••••••••" - placeholderTextColor={colors.textSecondary} - secureTextEntry - value={password} - onChangeText={setPassword} - /> + <View style={styles.inputWrapper}> + <TextInput + style={styles.inputWithIcon} + placeholder="••••••••" + placeholderTextColor={colors.textSecondary} + secureTextEntry={!showPassword} + value={password} + onChangeText={setPassword} + /> + + <Pressable + onPress={() => setShowPassword((prev) => !prev)} + style={styles.iconButton} + > + <MaterialIcons + name={showPassword ? 'visibility-off' : 'visibility'} + size={20} + color={colors.textSecondary} + /> + </Pressable> + </View> {/* enlace visual de recuperar contraseña */} - <Text style={styles.forgotPassword}>¿Olvidaste tu contraseña?</Text> + <Pressable onPress={handleForgotPassword}> + <Text style={styles.forgotPassword}>¿Olvidaste tu contraseña?</Text> + </Pressable> {/* mensaje de error */} {error ? <StatusMessage message={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<string | null>(null); + + const handleSubmit = () => { + setLocalError(null); + + if (password !== confirmPassword) { + setLocalError('Las contraseñas no coinciden'); + return; + } + + submit(); + }; + return ( <View style={styles.container}> {/* contenido central acotado */} @@ -62,20 +84,62 @@ export default function RegisterScreen() { {/* campo contraseña */} <Text style={styles.label}>Contraseña</Text> - <TextInput - style={styles.input} - placeholder="Mínimo 8 caracteres" - placeholderTextColor={colors.textSecondary} - secureTextEntry - value={password} - onChangeText={setPassword} - /> + <View style={styles.inputWrapper}> + <TextInput + style={styles.inputWithIcon} + placeholder="Mínimo 8 caracteres" + placeholderTextColor={colors.textSecondary} + secureTextEntry={!showPassword} + value={password} + onChangeText={setPassword} + /> + + <Pressable + onPress={() => setShowPassword((prev) => !prev)} + style={styles.iconButton} + > + <MaterialIcons + name={showPassword ? 'visibility-off' : 'visibility'} + size={20} + color={colors.textSecondary} + /> + </Pressable> + </View> + + {/* campo confirmar contraseña */} + <Text style={styles.label}>Confirmar contraseña</Text> + <View style={styles.inputWrapper}> + <TextInput + style={styles.inputWithIcon} + placeholder="Repite la contraseña" + placeholderTextColor={colors.textSecondary} + secureTextEntry={!showConfirmPassword} + value={confirmPassword} + onChangeText={setConfirmPassword} + /> + + <Pressable + onPress={() => setShowConfirmPassword((prev) => !prev)} + style={styles.iconButton} + > + <MaterialIcons + name={showConfirmPassword ? 'visibility-off' : 'visibility'} + size={20} + color={colors.textSecondary} + /> + </Pressable> + </View> {/* mensaje de error */} + {localError ? <StatusMessage message={localError} /> : null} {error ? <StatusMessage message={error} /> : null} {/* boton principal */} - <Pressable style={styles.button} onPress={submit} disabled={isSubmitting}> + <Pressable + style={styles.button} + onPress={handleSubmit} + disabled={isSubmitting} + > <Text style={styles.buttonText}> {isSubmitting ? 'Registrando...' : 'Crear cuenta'} </Text> @@ -84,7 +148,8 @@ export default function RegisterScreen() { {/* enlace inferior a login */} <Link href="/(auth)/login" style={styles.link}> - ¿Ya tienes cuenta? <Text style={styles.linkHighlight}>Inicia sesión</Text> + ¿Ya tienes cuenta?{' '} + <Text style={styles.linkHighlight}>Inicia sesión</Text> </Link> </View> </View> 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() { <View style={styles.container}> {/* cabecera de bienvenida */} <Text style={styles.title}> - Hola{user?.displayName ? `, ${user.displayName}` : ''} 👋 + Hola{user?.displayName ? `, ${user.displayName}` : ""} 👋 </Text> - <Text style={styles.subtitle}> - Bienvenido a la App Oficina - </Text> + <Text style={styles.subtitle}>Bienvenido a la App Oficina</Text> <View style={styles.divider} /> {/* seccion de accesos rapidos */} @@ -111,7 +116,7 @@ export default function HomeScreen() { <Pressable> <View style={styles.linkRow}> <Text style={styles.linkText}>Ver todas</Text> - <Text style={styles.chevronSmall}>{'>'}</Text> + <Text style={styles.chevronSmall}>{">"}</Text> </View> </Pressable> </Link> @@ -122,20 +127,28 @@ export default function HomeScreen() { previewReservations.map((reservation) => ( <View key={reservation.id} style={styles.reservationCard}> <View style={styles.reservationContent}> - <View style={styles.reservationIconContainer}> - <MaterialIcons name="business" size={22} color={colors.primary} /> + <MaterialIcons + name="business" + size={22} + color={colors.primary} + /> </View> <View style={styles.reservationInfo}> - <View style={styles.reservationHeader}> - <Text style={styles.reservationOffice}>{reservation.officeName}</Text> - <Text style={styles.chevron}>{'>'}</Text> + <Text style={styles.reservationOffice}> + {reservation.officeName} + </Text> + <Text style={styles.chevron}>{">"}</Text> </View> <View style={styles.reservationMetaRow}> - <MaterialIcons name="access-time" size={14} color={colors.textSecondary} /> + <MaterialIcons + name="access-time" + size={14} + color={colors.textSecondary} + /> <Text style={styles.reservationMeta}> {formatDate(reservation.date)} </Text> @@ -162,11 +175,10 @@ export default function HomeScreen() { : styles.statusTextPending, ]} > - {reservation.checkInAt ? 'Confirmada' : 'Pendiente'} + {reservation.checkInAt ? "Confirmada" : "Pendiente"} </Text> </View> </View> - </View> </View> </View> @@ -181,6 +193,10 @@ export default function HomeScreen() { </View> {/* seccion de estadisticas */} + <View style={styles.statsHeader}> + <Text style={styles.sectionTitle}>Estadísticas de uso</Text> + </View> + <View style={styles.statsGrid}> <View style={styles.statCard}> <Text style={styles.statValue}>{activeReservations.length}</Text> @@ -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 +}); diff --git a/src/app/(protected)/(tabs)/profile/index.tsx b/src/app/(protected)/(tabs)/profile/index.tsx index 660d113..0439708 100644 --- a/src/app/(protected)/(tabs)/profile/index.tsx +++ b/src/app/(protected)/(tabs)/profile/index.tsx @@ -14,6 +14,7 @@ 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'; @@ -28,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 { @@ -54,8 +68,16 @@ 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 @@ -63,6 +85,37 @@ export default function ProfileScreen() { 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) { @@ -70,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 () => { @@ -84,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); @@ -91,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 @@ -122,13 +196,14 @@ export default function ProfileScreen() { style={styles.container} contentContainerStyle={styles.content} showsVerticalScrollIndicator={false} - > + > {/* cabecera superior visual dentro del scroll */} <View style={styles.topBar}> <Text style={styles.topBarTitle}>Perfil</Text> </View> + {/* tarjeta cabecera del perfil */} - {/* avatar, nombre, correo y boton editar / cancelar */} + {/* avatar, nombre, correo y boton editar o cancelar */} <View style={styles.headerCard}> <View style={styles.headerRow}> {photoURL ? ( @@ -148,7 +223,7 @@ export default function ProfileScreen() { {/* correo del usuario */} <Text style={styles.profileEmail}>{profile.email}</Text> - {/* boton editar perfil / cancelar */} + {/* boton editar perfil o cancelar */} <Pressable style={styles.editButton} onPress={handleToggleEditing}> <Text style={styles.editButtonText}> {isEditing ? 'Cancelar' : 'Editar perfil'} @@ -159,23 +234,40 @@ export default function ProfileScreen() { </View> {/* seccion sobre mi */} - {/* solo visual por ahora, FALTA CONEXION CON FIREBASE PARA GUARDAR INFO */} <View style={styles.section}> - <Text style={styles.sectionTitle}>Sobre mí</Text> + <Text style={styles.sectionTitle}>Sobre mi</Text> <View style={styles.card}> - <Text style={styles.aboutText}> - Espacio personal del usuario para mostrar una breve descripción o - presentación dentro de la aplicación. - </Text> + {isEditing ? ( + <> + {/* campo editable para la descripcion personal */} + <TextInput + style={[styles.input, styles.textArea]} + value={bio} + onChangeText={setBio} + placeholder="Cuentanos algo sobre ti" + multiline + maxLength={maxBioLength} + textAlignVertical="top" + /> + + {/* contador visual para orientar el limite de la bio */} + <Text style={styles.helperText}> + {bio.length}/{maxBioLength} caracteres + </Text> + </> + ) : ( + <Text style={styles.aboutText}> + {bio?.trim() || 'Todavia no has anadido una descripcion personal.'} + </Text> + )} </View> </View> {/* seccion informacion personal */} - {/* en modo vista muestra datos */} - {/* en modo edicion muestra formulario */} + {/* en modo vista muestra datos y en modo edicion muestra formulario */} <View style={styles.section}> - <Text style={styles.sectionTitle}>Información personal</Text> + <Text style={styles.sectionTitle}>Informacion personal</Text> <View style={styles.card}> {isEditing ? ( @@ -200,6 +292,25 @@ export default function ProfileScreen() { autoCorrect={false} /> + {/* formulario de edicion: telefono */} + <Text style={styles.label}>Telefono</Text> + <TextInput + style={styles.input} + value={phone} + onChangeText={setPhone} + placeholder="+34 600 123 456" + keyboardType="phone-pad" + /> + + {/* formulario de edicion: empresa */} + <Text style={styles.label}>Empresa</Text> + <TextInput + style={styles.input} + value={company} + onChangeText={setCompany} + placeholder="Tu empresa" + /> + {/* mensajes de error o exito al guardar */} {updateError ? <StatusMessage message={updateError} /> : null} {successMessage ? ( @@ -232,28 +343,30 @@ export default function ProfileScreen() { <View style={styles.infoRow}> <Feather name="mail" size={16} color={colors.textSecondary} /> <View style={styles.infoContent}> - <Text style={styles.infoLabel}>Correo electrónico</Text> + <Text style={styles.infoLabel}>Correo electronico</Text> <Text style={styles.infoValue}>{profile.email}</Text> </View> </View> {/* fila de telefono */} - {/* por ahora es solo visual, FALTA CONEXION CON FIREBASE */} <View style={styles.infoRow}> <Feather name="phone" size={16} color={colors.textSecondary} /> <View style={styles.infoContent}> - <Text style={styles.infoLabel}>Teléfono</Text> - <Text style={styles.infoValue}>+34 600 123 456</Text> + <Text style={styles.infoLabel}>Telefono</Text> + <Text style={styles.infoValue}> + {phone?.trim() || 'No especificado'} + </Text> </View> </View> {/* fila de empresa */} - {/* por ahora es solo visual, FALTA CONEXION CON FIREBASE */} <View style={styles.infoRow}> <Feather name="briefcase" size={16} color={colors.textSecondary} /> <View style={styles.infoContent}> <Text style={styles.infoLabel}>Empresa</Text> - <Text style={styles.infoValue}>Empresa Innovadora S.L.</Text> + <Text style={styles.infoValue}> + {company?.trim() || 'No especificada'} + </Text> </View> </View> </> @@ -261,6 +374,33 @@ export default function ProfileScreen() { </View> </View> + {/* seccion actividad */} + <View style={styles.card}> + <Text style={styles.sectionTitle}>Resumen de actividad</Text> + <View style={styles.activityItem}> + <View style={styles.activityDot} /> + <Text style={styles.activityText}> + Check in confirmados en {checkedInReservationsCount} reservas. + </Text> + </View> + + <View style={styles.activityItem}> + <View style={styles.activityDot} /> + <Text style={styles.activityText}> + Actualmente tienes {activeReservations.length} reservas activas. + </Text> + </View> + + <View style={styles.activityItem}> + <View style={styles.activityDot} /> + <Text style={styles.activityText}> + {mostUsedFavoriteOffice + ? `Top de favoritos: ${mostUsedFavoriteOffice.name}.` + : 'Aun no tienes suficiente actividad para destacar un espacio favorito.'} + </Text> + </View> + </View> + {/* seccion favoritos */} <View style={styles.section}> <Text style={styles.sectionTitle}>Favoritos</Text> @@ -274,7 +414,7 @@ export default function ProfileScreen() { </Text> ) : favoriteOffices.length === 0 ? ( <Text style={styles.aboutText}> - Todavía no has marcado oficinas como favoritas. + Todavia no has marcado oficinas como favoritas. </Text> ) : ( <> @@ -300,8 +440,8 @@ export default function ProfileScreen() { ))} </View> - {/* 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 ? ( <Pressable style={styles.viewAllButton}> <Text style={styles.viewAllText}>Ver todos</Text> @@ -312,43 +452,13 @@ export default function ProfileScreen() { </View> </View> - {/* seccion enlaces secundarios */} - <View style={styles.section}> - <View style={styles.card}> - <View style={styles.linkItem}> - <View style={styles.linkLeft}> - <Feather name="bell" size={16} color={colors.textSecondary} /> - <Text style={styles.linkText}>Notificaciones</Text> - </View> - <Text style={styles.chevron}>{'>'}</Text> - </View> - - <View style={styles.linkItem}> - <View style={styles.linkLeft}> - <Feather name="shield" size={16} color={colors.textSecondary} /> - <Text style={styles.linkText}>Privacidad y seguridad</Text> - </View> - <Text style={styles.chevron}>{'>'}</Text> - </View> - - <View style={styles.linkItem}> - <View style={styles.linkLeft}> - <Feather name="help-circle" size={16} color={colors.textSecondary} /> - <Text style={styles.linkText}>Ayuda y soporte</Text> - </View> - <Text style={styles.chevron}>{'>'}</Text> - </View> - </View> + {/* seccion cierre de sesion */} + <View style={styles.logoutSection}> + <Pressable style={styles.logoutButton} onPress={handleLogout}> + <Text style={styles.logoutButtonText}>Cerrar sesion</Text> + </Pressable> </View> - {/* boton cerrar sesion */} - <Pressable style={styles.logoutButton} onPress={handleLogout}> - <View style={styles.logoutContent}> - <Feather name="log-out" size={16} color={colors.error} /> - <Text style={styles.logoutButtonText}>Cerrar sesión</Text> - </View> - </Pressable> - {/* texto inferior de version */} <Text style={styles.footerText}>App Oficina v1.0.0</Text> </ScrollView> @@ -363,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, @@ -411,7 +521,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 +532,7 @@ const styles = StyleSheet.create({ headerRow: { flexDirection: 'row', alignItems: 'center', - gap: spacing.lg, + gap: spacing.xxl, }, // bloque de informacion de la cabecera @@ -433,9 +543,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,24 +558,24 @@ 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, }, - // boton pequeno de editar / cancelar + // boton pequeno de editar o cancelar editButton: { marginTop: spacing.xs, borderWidth: 1, @@ -476,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, @@ -519,12 +629,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 +657,31 @@ const styles = StyleSheet.create({ color: colors.error, }, + // bloque 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, + 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: { @@ -569,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, @@ -623,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', @@ -654,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, @@ -669,32 +810,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 @@ -713,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: { @@ -734,4 +853,4 @@ const styles = StyleSheet.create({ color: colors.error, textAlign: 'center', }, -});
\ No newline at end of file +}); 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() { <Pressable style={[ styles.tabButton, - activeTab === 'active' && styles.tabButtonActive, + activeTab === "active" && styles.tabButtonActive, ]} - onPress={() => setActiveTab('active')} + onPress={() => setActiveTab("active")} > <Text style={[ styles.tabButtonText, - activeTab === 'active' && styles.tabButtonTextActive, + activeTab === "active" && styles.tabButtonTextActive, ]} > Activas ({activeReservations.length}) @@ -162,14 +168,14 @@ export default function ReservationsScreen() { <Pressable style={[ styles.tabButton, - activeTab === 'history' && styles.tabButtonActive, + activeTab === "history" && styles.tabButtonActive, ]} - onPress={() => setActiveTab('history')} + onPress={() => setActiveTab("history")} > <Text style={[ styles.tabButtonText, - activeTab === 'history' && styles.tabButtonTextActive, + activeTab === "history" && styles.tabButtonTextActive, ]} > Historial ({historyReservations.length}) @@ -178,7 +184,7 @@ export default function ReservationsScreen() { </View> {/* seccion de reservas activas */} - {activeTab === 'active' ? ( + {activeTab === "active" ? ( <View style={styles.section}> <View style={styles.sectionHeader}> <Text style={styles.sectionTitle}>Activas</Text> @@ -186,7 +192,9 @@ export default function ReservationsScreen() { {activeReservations.length === 0 ? ( <View style={styles.emptyCard}> - <Text style={styles.emptyTitle}>No tienes reservas activas</Text> + <Text style={styles.emptyTitle}> + No tienes reservas activas + </Text> <Text style={styles.emptyText}> Cuando realices una nueva reserva, aparecerá aquí. </Text> @@ -212,7 +220,9 @@ export default function ReservationsScreen() { </View> <View style={[styles.statusBadge, styles.statusActive]}> - <Text style={[styles.statusText, styles.statusTextActive]}> + <Text + style={[styles.statusText, styles.statusTextActive]} + > Activa </Text> </View> @@ -249,7 +259,7 @@ export default function ReservationsScreen() { <Text style={styles.detailText}> {item.checkInAt ? `Llegada registrada: ${formatCheckInAt(item.checkInAt)}` - : 'Llegada pendiente'} + : "Llegada pendiente"} </Text> </View> </View> @@ -257,8 +267,9 @@ export default function ReservationsScreen() { {/* linea separadora antes de acciones */} <View style={styles.cardDivider} /> - {/* 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) ? ( <Pressable style={styles.checkInButton} onPress={() => { @@ -268,8 +279,8 @@ export default function ReservationsScreen() { > <Text style={styles.checkInButtonText}> {checkingInReservationId === item.id - ? 'Registrando llegada...' - : 'He llegado'} + ? "Registrando llegada..." + : "He llegado"} </Text> </Pressable> ) : 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, + }, + }); + }} > <Text style={styles.editButtonText}>Editar</Text> </Pressable> @@ -296,9 +322,15 @@ export default function ReservationsScreen() { disabled={cancelingReservationId === item.id} > <View style={styles.cancelContent}> - <MaterialIcons name="cancel" size={14} color="#DC2626" /> + <MaterialIcons + name="cancel" + size={14} + color="#DC2626" + /> <Text style={styles.cancelButtonText}> - {cancelingReservationId === item.id ? 'Cancelando...' : 'Cancelar'} + {cancelingReservationId === item.id + ? "Cancelando..." + : "Cancelar"} </Text> </View> </Pressable> @@ -310,7 +342,7 @@ export default function ReservationsScreen() { ) : null} {/* seccion historial */} - {activeTab === 'history' ? ( + {activeTab === "history" ? ( <View style={styles.section}> <View style={styles.sectionHeader}> <Text style={styles.sectionTitle}>Historial</Text> @@ -339,14 +371,16 @@ export default function ReservationsScreen() { <View style={styles.cardTitleBlock}> <Text style={styles.cardTitle}>{item.officeName}</Text> - <Text style={styles.cardSubtitle}>Reserva finalizada</Text> + <Text style={styles.cardSubtitle}> + Reserva finalizada + </Text> </View> </View> <View style={[ styles.statusBadge, - item.status === 'completed' + item.status === "completed" ? styles.statusCompleted : styles.statusCancelled, ]} @@ -354,12 +388,14 @@ export default function ReservationsScreen() { <Text style={[ styles.statusText, - item.status === 'completed' + item.status === "completed" ? styles.statusTextCompleted : styles.statusTextCancelled, ]} > - {item.status === 'completed' ? 'Completada' : 'Cancelada'} + {item.status === "completed" + ? "Completada" + : "Cancelada"} </Text> </View> </View> @@ -395,7 +431,7 @@ export default function ReservationsScreen() { <Text style={styles.detailText}> {item.checkInAt ? `Llegada registrada: ${formatCheckInAt(item.checkInAt)}` - : 'Llegada no registrada'} + : "Llegada no registrada"} </Text> </View> </View> @@ -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 ( <KeyboardAvoidingView style={styles.container} - behavior={Platform.OS === 'ios' ? 'padding' : undefined} + behavior={Platform.OS === "ios" ? "padding" : undefined} > {/* cabecera superior */} <View style={styles.topBar}> - <Text style={styles.topBarTitle}>Crear reserva</Text> + <Text style={styles.topBarTitle}> + {isEditMode ? "Editar reserva" : "Crear reserva"} + </Text> </View> <ScrollView @@ -60,9 +100,13 @@ export default function CreateReservationScreen() { > {/* texto introductorio */} <View style={styles.introSection}> - <Text style={styles.title}>Nueva reserva</Text> + <Text style={styles.title}> + {isEditMode ? "Editar reserva" : "Nueva reserva"} + </Text> <Text style={styles.subtitle}> - 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."} </Text> </View> @@ -81,27 +125,29 @@ export default function CreateReservationScreen() { <View style={styles.cardTitleBlock}> <Text style={styles.cardTitle}>Espacio</Text> <Text style={styles.cardSubtitle}> - {officeName ?? 'No indicado'} + {officeName ?? "No indicado"} </Text> </View> </View> </View> {/* enlace para volver a oficinas */} - <View style={styles.changeOfficeRow}> - <Link href="/(protected)/(tabs)/offices" asChild> - <Pressable - style={({ pressed }) => [ - styles.changeOfficeButton, - pressed && styles.changeOfficeButtonPressed, - ]} - > - <Text style={styles.changeOfficeButtonText}> - Cambiar oficina - </Text> - </Pressable> - </Link> - </View> + {!isEditMode && ( + <View style={styles.changeOfficeRow}> + <Link href="/(protected)/(tabs)/offices" asChild> + <Pressable + style={({ pressed }) => [ + styles.changeOfficeButton, + pressed && styles.changeOfficeButtonPressed, + ]} + > + <Text style={styles.changeOfficeButtonText}> + Cambiar oficina + </Text> + </Pressable> + </Link> + </View> + )} </View> {/* tarjeta de condiciones de reserva */} @@ -110,25 +156,15 @@ export default function CreateReservationScreen() { <View style={styles.rulesList}> <View style={styles.ruleRow}> - <MaterialIcons - name="schedule" - size={16} - color={colors.primary} - /> + <MaterialIcons name="schedule" size={16} color={colors.primary} /> <Text style={styles.ruleText}> Horario permitido: de 08:00 a 20:00 </Text> </View> <View style={styles.ruleRow}> - <MaterialIcons - name="timer" - size={16} - color={colors.primary} - /> - <Text style={styles.ruleText}> - Duración mínima: 30 minutos - </Text> + <MaterialIcons name="timer" size={16} color={colors.primary} /> + <Text style={styles.ruleText}>Duración mínima: 30 minutos</Text> </View> <View style={styles.ruleRow}> @@ -137,9 +173,7 @@ export default function CreateReservationScreen() { size={16} color={colors.primary} /> - <Text style={styles.ruleText}> - Duración máxima: 8 horas - </Text> + <Text style={styles.ruleText}>Duración máxima: 8 horas</Text> </View> </View> </View> @@ -153,21 +187,21 @@ export default function CreateReservationScreen() { <Text style={styles.label}>Fecha</Text> {/* en web usamos calendario nativo */} - {Platform.OS === 'web' ? ( + {Platform.OS === "web" ? ( <input type="date" value={date} onChange={(e) => 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() { )} <Text style={styles.helper}> - {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"} </Text> </View> @@ -222,11 +256,8 @@ export default function CreateReservationScreen() { {/* mensajes de error / exito */} {error ? <StatusMessage message={error} /> : null} - {successMessage ? ( - <StatusMessage message={successMessage} tone="success" /> - ) : null} - {/* boton principal de guardar */} + {/* boton principal de guardar / actualizar */} <Pressable style={({ pressed }) => [ styles.primaryButton, @@ -240,10 +271,32 @@ export default function CreateReservationScreen() { disabled={!isFormComplete || isSubmitting} > <Text style={styles.primaryButtonText}> - {isSubmitting ? 'Guardando...' : 'Guardar reserva'} + {isSubmitting + ? isEditMode + ? "Actualizando..." + : "Guardando..." + : isEditMode + ? "Actualizar reserva" + : "Guardar reserva"} </Text> </Pressable> </View> + + {/* boton cancelar fuera de la tarjeta */} + {isEditMode && ( + <Pressable + style={({ pressed }) => [ + styles.cancelButton, + pressed && styles.cancelButtonPressed, + ]} + onPress={() => router.back()} + > + <View style={styles.cancelContent}> + <MaterialIcons name="cancel" size={14} color="#DC2626" /> + <Text style={styles.cancelButtonText}>Cancelar</Text> + </View> + </Pressable> + )} </ScrollView> </KeyboardAvoidingView> ); @@ -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, + }, +}); |