From e22992e29801e04ca4352045c5bd2f36eac1c31c Mon Sep 17 00:00:00 2001 From: Alberto Duarte Delgado Date: Wed, 1 Apr 2026 13:32:56 +0100 Subject: filtrado de oficinas y favoritos --- firestore.rules | 8 + src/app/(protected)/(tabs)/offices/index.tsx | 200 ++++++++++++++++++++-- src/app/(protected)/offices/[officeId].tsx | 53 +++++- src/features/offices/hooks/useFavoriteOffices.ts | 75 ++++++++ src/features/offices/services/favoritesService.ts | 27 +++ 5 files changed, 351 insertions(+), 12 deletions(-) create mode 100644 src/features/offices/hooks/useFavoriteOffices.ts create mode 100644 src/features/offices/services/favoritesService.ts diff --git a/firestore.rules b/firestore.rules index 2b1537a..b1de5ef 100644 --- a/firestore.rules +++ b/firestore.rules @@ -38,6 +38,14 @@ service cloud.firestore { allow delete: if false; } + match /users/{userId}/favorites/{officeId} { + allow create: if isOwner(userId) + && request.resource.data.officeId == officeId; + allow read: if isOwner(userId); + allow delete: if isOwner(userId); + allow update: if false; + } + match /offices/{officeId} { allow read: if isSignedIn(); allow write: if false; diff --git a/src/app/(protected)/(tabs)/offices/index.tsx b/src/app/(protected)/(tabs)/offices/index.tsx index 23445ee..9040fbd 100644 --- a/src/app/(protected)/(tabs)/offices/index.tsx +++ b/src/app/(protected)/(tabs)/offices/index.tsx @@ -1,18 +1,58 @@ import { Link } from 'expo-router'; +import { useMemo, useState } from 'react'; import { ActivityIndicator, FlatList, Pressable, StyleSheet, Text, + TextInput, View, } from 'react-native'; import { useOffices } from '@/features/offices/hooks/useOffices'; +import { useFavoriteOffices } from '@/features/offices/hooks/useFavoriteOffices'; +import { StatusMessage } from '@/shared/ui/StatusMessage'; export default function OfficesScreen() { const { offices, loading, error, reload } = useOffices(); + const { + favoriteOfficeIdsSet, + isLoadingFavorites, + favoritesError, + pendingOfficeId, + toggleFavorite, + } = useFavoriteOffices(); + const [search, setSearch] = useState(''); + const [minimumCapacity, setMinimumCapacity] = useState(''); + const [showFavoritesOnly, setShowFavoritesOnly] = useState(false); - if (loading) { + const filteredOffices = useMemo(() => { + const normalizedSearch = search.trim().toLowerCase(); + const parsedCapacity = Number(minimumCapacity); + const hasCapacityFilter = minimumCapacity.trim().length > 0 && !Number.isNaN(parsedCapacity); + + return offices.filter((office) => { + const matchesSearch = + normalizedSearch.length === 0 || + office.name.toLowerCase().includes(normalizedSearch); + + const matchesCapacity = + !hasCapacityFilter || office.capacity >= parsedCapacity; + + const matchesFavorites = + !showFavoritesOnly || favoriteOfficeIdsSet.has(office.id); + + return matchesSearch && matchesCapacity && matchesFavorites; + }); + }, [favoriteOfficeIdsSet, minimumCapacity, offices, search, showFavoritesOnly]); + + const clearFilters = () => { + setSearch(''); + setMinimumCapacity(''); + setShowFavoritesOnly(false); + }; + + if (loading || isLoadingFavorites) { return ( @@ -35,22 +75,90 @@ export default function OfficesScreen() { Espacios + + Buscar y filtrar + + + + setMinimumCapacity(value.replace(/\D/g, ''))} + keyboardType="number-pad" + /> + + + setShowFavoritesOnly((current) => !current)} + > + + {showFavoritesOnly ? 'Viendo favoritos' : 'Solo favoritos'} + + + + + Limpiar filtros + + + + + {favoritesError ? : null} + item.id} contentContainerStyle={styles.list} ListEmptyComponent={ - No hay espacios disponibles + + {offices.length === 0 + ? 'No hay espacios disponibles' + : showFavoritesOnly + ? 'No tienes oficinas favoritas que coincidan con los filtros' + : 'No hay espacios que coincidan con los filtros'} + } renderItem={({ item }) => ( - - + + {item.name} - {item.location} - Capacidad: {item.capacity} - {item.description ? {item.description} : null} - - + { + void toggleFavorite(item.id); + }} + disabled={pendingOfficeId === item.id} + > + + {pendingOfficeId === item.id + ? '...' + : favoriteOfficeIdsSet.has(item.id) + ? '★' + : '☆'} + + + + + + + {item.location} + Capacidad: {item.capacity} + {item.description ? {item.description} : null} + + + )} /> @@ -73,6 +181,32 @@ const styles = StyleSheet.create({ fontWeight: '700', marginBottom: 16, }, + filtersBox: { + borderWidth: 1, + borderColor: '#d8e0ea', + backgroundColor: '#f7f9fc', + borderRadius: 12, + padding: 12, + gap: 10, + marginBottom: 16, + }, + filtersTitle: { + fontSize: 16, + fontWeight: '700', + color: '#22354a', + }, + input: { + borderWidth: 1, + borderColor: '#ccd5df', + borderRadius: 10, + paddingHorizontal: 14, + paddingVertical: 12, + backgroundColor: '#fff', + }, + filterActions: { + flexDirection: 'row', + gap: 10, + }, list: { gap: 12, }, @@ -81,11 +215,21 @@ const styles = StyleSheet.create({ borderColor: '#ddd', borderRadius: 12, padding: 16, - gap: 6, + gap: 10, + }, + cardHeader: { + flexDirection: 'row', + alignItems: 'center', + justifyContent: 'space-between', + gap: 12, }, cardTitle: { fontSize: 18, fontWeight: '600', + flex: 1, + }, + cardBody: { + gap: 6, }, error: { color: 'red', @@ -97,6 +241,40 @@ const styles = StyleSheet.create({ paddingVertical: 12, borderRadius: 10, }, + secondaryButton: { + backgroundColor: '#5d6b79', + flex: 1, + paddingHorizontal: 16, + paddingVertical: 12, + borderRadius: 10, + alignItems: 'center', + }, + toggleButton: { + backgroundColor: '#1f6feb', + flex: 1, + paddingHorizontal: 16, + paddingVertical: 12, + borderRadius: 10, + alignItems: 'center', + }, + toggleButtonActive: { + backgroundColor: '#174ea6', + }, + favoriteButton: { + width: 40, + height: 40, + borderRadius: 20, + alignItems: 'center', + justifyContent: 'center', + backgroundColor: '#eef2f6', + }, + favoriteButtonActive: { + backgroundColor: '#ffe8a3', + }, + favoriteButtonText: { + fontSize: 20, + color: '#8a6700', + }, buttonText: { color: '#fff', fontWeight: '600', diff --git a/src/app/(protected)/offices/[officeId].tsx b/src/app/(protected)/offices/[officeId].tsx index 34095c5..8e3812f 100644 --- a/src/app/(protected)/offices/[officeId].tsx +++ b/src/app/(protected)/offices/[officeId].tsx @@ -1,12 +1,20 @@ import { Link, useLocalSearchParams } from 'expo-router'; import { ActivityIndicator, Pressable, StyleSheet, Text, View } from 'react-native'; import { useOffice } from '@/features/offices/hooks/useOffice'; +import { useFavoriteOffices } from '@/features/offices/hooks/useFavoriteOffices'; +import { StatusMessage } from '@/shared/ui/StatusMessage'; export default function OfficeDetailScreen() { const params = useLocalSearchParams<{ officeId: string }>(); const officeId = typeof params.officeId === 'string' ? params.officeId : undefined; const { office, loading, error, reload } = useOffice(officeId); + const { + favoriteOfficeIdsSet, + favoritesError, + pendingOfficeId, + toggleFavorite, + } = useFavoriteOffices(); if (loading) { return ( @@ -36,7 +44,29 @@ export default function OfficeDetailScreen() { return ( - {office.name} + + {office.name} + { + void toggleFavorite(office.id); + }} + disabled={pendingOfficeId === office.id} + > + + {pendingOfficeId === office.id + ? '...' + : favoriteOfficeIdsSet.has(office.id) + ? '★' + : '☆'} + + + + + {favoritesError ? : null} Ubicación @@ -88,6 +118,12 @@ const styles = StyleSheet.create({ title: { fontSize: 28, fontWeight: '700', + flex: 1, + }, + header: { + flexDirection: 'row', + alignItems: 'center', + gap: 12, }, card: { borderWidth: 1, @@ -118,6 +154,21 @@ const styles = StyleSheet.create({ borderRadius: 10, alignItems: 'center', }, + favoriteButton: { + width: 44, + height: 44, + borderRadius: 22, + alignItems: 'center', + justifyContent: 'center', + backgroundColor: '#eef2f6', + }, + favoriteButtonActive: { + backgroundColor: '#ffe8a3', + }, + favoriteButtonText: { + fontSize: 22, + color: '#8a6700', + }, buttonText: { color: '#fff', fontWeight: '600', diff --git a/src/features/offices/hooks/useFavoriteOffices.ts b/src/features/offices/hooks/useFavoriteOffices.ts new file mode 100644 index 0000000..166dd1c --- /dev/null +++ b/src/features/offices/hooks/useFavoriteOffices.ts @@ -0,0 +1,75 @@ +import { useEffect, useMemo, useState } from 'react'; +import { favoritesService } from '@/features/offices/services/favoritesService'; +import { useAuthSession } from '@/providers/AuthProvider'; +import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage'; + +export function useFavoriteOffices() { + const { user } = useAuthSession(); + const [favoriteOfficeIds, setFavoriteOfficeIds] = useState([]); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [pendingOfficeId, setPendingOfficeId] = useState(null); + + const loadFavorites = async () => { + if (!user?.uid) { + setFavoriteOfficeIds([]); + setLoading(false); + return; + } + + try { + setError(null); + setLoading(true); + + const data = await favoritesService.getByUserId(user.uid); + setFavoriteOfficeIds(data); + } catch (err) { + setError(getErrorMessage(err, 'No se pudieron cargar los favoritos')); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + loadFavorites(); + }, [user?.uid]); + + const favoriteOfficeIdsSet = useMemo( + () => new Set(favoriteOfficeIds), + [favoriteOfficeIds] + ); + + const toggleFavorite = async (officeId: string) => { + if (!user?.uid) { + setError('Debes iniciar sesión para usar favoritos'); + return; + } + + try { + setError(null); + setPendingOfficeId(officeId); + + if (favoriteOfficeIdsSet.has(officeId)) { + await favoritesService.remove(user.uid, officeId); + setFavoriteOfficeIds((current) => current.filter((id) => id !== officeId)); + } else { + await favoritesService.add(user.uid, officeId); + setFavoriteOfficeIds((current) => [...current, officeId]); + } + } catch (err) { + setError(getErrorMessage(err, 'No se pudo actualizar el favorito')); + } finally { + setPendingOfficeId(null); + } + }; + + return { + favoriteOfficeIds, + favoriteOfficeIdsSet, + isLoadingFavorites: loading, + favoritesError: error, + pendingOfficeId, + toggleFavorite, + reloadFavorites: loadFavorites, + }; +} diff --git a/src/features/offices/services/favoritesService.ts b/src/features/offices/services/favoritesService.ts new file mode 100644 index 0000000..39e7573 --- /dev/null +++ b/src/features/offices/services/favoritesService.ts @@ -0,0 +1,27 @@ +import { + collection, + deleteDoc, + doc, + getDocs, + serverTimestamp, + setDoc, +} from 'firebase/firestore'; +import { db } from '@/shared/lib/firebase/config'; + +export const favoritesService = { + async getByUserId(userId: string): Promise { + const snapshot = await getDocs(collection(db, 'users', userId, 'favorites')); + return snapshot.docs.map((item) => item.id); + }, + + async add(userId: string, officeId: string): Promise { + await setDoc(doc(db, 'users', userId, 'favorites', officeId), { + officeId, + createdAt: serverTimestamp(), + }); + }, + + async remove(userId: string, officeId: string): Promise { + await deleteDoc(doc(db, 'users', userId, 'favorites', officeId)); + }, +}; -- cgit v1.2.3-54-g00ecf