Mobile App design
Run Tests on Branches / Detect Changes (push) Successful in 10s
Run Tests on Branches / Backend Tests (push) Successful in 2m12s
Run Tests on Branches / Frontend Tests (push) Has been skipped
Run Tests on Branches / Frontend Mobile Tests (push) Successful in 1m47s

This commit is contained in:
Ichitux
2026-07-09 13:33:54 +02:00
parent 5f604b11ba
commit 2f36ef685d
32 changed files with 1793 additions and 926 deletions
+26 -47
View File
@@ -1,12 +1,16 @@
import { Tabs } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { View, StyleSheet, Platform, useWindowDimensions } from 'react-native';
import { View, StyleSheet, useWindowDimensions } from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import { colors, shadows } from '../../constants/theme';
import { useThemeContext } from '../../components/ThemeProvider';
import { shadows } from '../../constants/theme';
const TABLET_MIN_WIDTH = 768;
function ScanIcon({ color, size }: { color: string; size: number }) {
// Standard Android navigation bar heights in dp
const ANDROID_NAV_BAR_HEIGHT = 48;
function ScanIcon({ size }: { size: number }) {
return (
<View style={styles.fabContainer}>
<View style={[styles.fab, shadows.scanButton]}>
@@ -20,7 +24,9 @@ export default function TabLayout() {
const insets = useSafeAreaInsets();
const { width } = useWindowDimensions();
const isTablet = width >= TABLET_MIN_WIDTH;
const bottomPadding = Platform.OS === 'ios' ? insets.bottom : 8;
const { colors } = useThemeContext();
// Use safe area insets if available, otherwise use standard Android nav bar height
const bottomPadding = insets.bottom > 0 ? insets.bottom : ANDROID_NAV_BAR_HEIGHT;
return (
<Tabs
@@ -28,24 +34,31 @@ export default function TabLayout() {
tabBarActiveTintColor: colors.primary,
tabBarInactiveTintColor: colors.textSecondary,
tabBarStyle: {
...(isTablet ? styles.tabBarTablet : styles.tabBar),
...(isTablet ? styles.tabBarTablet : {}),
backgroundColor: colors.card,
borderTopColor: colors.border,
paddingTop: isTablet ? 10 : 8,
height: (isTablet ? 64 : 60) + bottomPadding,
paddingBottom: bottomPadding,
...(isTablet ? { paddingHorizontal: 24 } : {}),
},
tabBarLabelStyle: {
...styles.tabBarLabel,
...(isTablet ? styles.tabBarLabelTablet : {}),
fontSize: isTablet ? 13 : 11,
fontWeight: '500',
},
headerStyle: {
backgroundColor: colors.card,
},
headerStyle: styles.header,
headerTintColor: colors.primary,
headerTitleStyle: {
...styles.headerTitle,
...(isTablet ? styles.headerTitleTablet : {}),
color: colors.text,
fontWeight: '600',
fontSize: isTablet ? 20 : 17,
},
}}
>
<Tabs.Screen
name="home"
name="index"
options={{
title: 'Inicio',
tabBarIcon: ({ color, size }) => (
@@ -54,7 +67,7 @@ export default function TabLayout() {
}}
/>
<Tabs.Screen
name="index"
name="search"
options={{
title: 'Buscar',
tabBarIcon: ({ color, size }) => (
@@ -99,40 +112,6 @@ export default function TabLayout() {
}
const styles = StyleSheet.create({
tabBar: {
backgroundColor: colors.card,
borderTopColor: colors.border,
paddingTop: 8,
},
tabBarTablet: {
backgroundColor: colors.card,
borderTopColor: colors.border,
paddingTop: 10,
paddingHorizontal: 24,
},
tabBarLabel: {
fontSize: 11,
fontWeight: '500',
},
tabBarLabelTablet: {
fontSize: 13,
},
header: {
backgroundColor: colors.card,
shadowColor: '#000',
shadowOffset: { width: 0, height: 1 },
shadowOpacity: 0.05,
shadowRadius: 4,
elevation: 1,
},
headerTitle: {
color: colors.text,
fontWeight: '600',
fontSize: 17,
},
headerTitleTablet: {
fontSize: 20,
},
fabContainer: {
position: 'absolute',
top: -16,
@@ -142,7 +121,7 @@ const styles = StyleSheet.create({
width: 52,
height: 52,
borderRadius: 26,
backgroundColor: colors.scanButton,
backgroundColor: '#2b5bb5',
alignItems: 'center',
justifyContent: 'center',
},
+17 -29
View File
@@ -1,7 +1,8 @@
import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Alert, useWindowDimensions } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { colors, spacing, borderRadius, shadows } from '../../constants/theme';
import { useThemeContext } from '../../components/ThemeProvider';
import { spacing, borderRadius, shadows } from '../../constants/theme';
import { LoadingSpinner } from '../../components/LoadingSpinner';
import api from '../../services/api';
@@ -21,6 +22,7 @@ interface NotificationItem {
export default function AlertsScreen() {
const { width } = useWindowDimensions();
const isTablet = width >= TABLET_MIN_WIDTH;
const { colors } = useThemeContext();
const [items, setItems] = useState<NotificationItem[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@@ -81,33 +83,33 @@ export default function AlertsScreen() {
function renderItem({ item }: { item: NotificationItem }) {
const key = `${item.scope}:${item.id}`;
return (
<View style={styles.item}>
<View style={[styles.item, { backgroundColor: colors.card }]}>
<View style={styles.itemContent}>
<Text style={styles.itemName} numberOfLines={2}>
<Text style={[styles.itemName, { color: colors.text }]} numberOfLines={2}>
{item.medicine_name || item.medicine_nregistro}
</Text>
<View style={styles.itemMeta}>
<View style={styles.chip}>
<View style={[styles.chip, { backgroundColor: colors.primaryContainer }]}>
<Ionicons
name={item.scope === 'pharmacy' ? 'medical' : 'globe'}
size={12}
color={colors.primary}
/>
<Text style={styles.chipText}>
<Text style={[styles.chipText, { color: colors.onPrimaryContainer }]}>
{item.scope === 'pharmacy'
? item.pharmacy_name || `Farmacia #${item.pharmacy_id}`
: 'Cualquier farmacia'}
</Text>
</View>
{item.pharmacy_address && (
<Text style={styles.itemAddress} numberOfLines={1}>
<Text style={[styles.itemAddress, { color: colors.textSecondary }]} numberOfLines={1}>
{item.pharmacy_address}
</Text>
)}
</View>
</View>
<TouchableOpacity
style={styles.deleteButton}
style={[styles.deleteButton, { backgroundColor: colors.dangerContainer }]}
onPress={() => handleDelete(item)}
disabled={deletingId === key}
>
@@ -126,19 +128,19 @@ export default function AlertsScreen() {
}
return (
<View style={styles.container}>
<View style={[styles.container, { backgroundColor: colors.background }]}>
<View style={[styles.header, isTablet && styles.headerTablet]}>
<Text style={[styles.title, isTablet && styles.titleTablet]}>Notificaciones Guardadas</Text>
<Text style={[styles.subtitle, isTablet && styles.subtitleTablet]}>
<Text style={[styles.title, isTablet && styles.titleTablet, { color: colors.text }]}>Notificaciones Guardadas</Text>
<Text style={[styles.subtitle, isTablet && styles.subtitleTablet, { color: colors.textSecondary }]}>
Recibe avisos cuando medicamentos sin stock se repongan
</Text>
</View>
{error && (
<View style={[styles.errorContainer, isTablet && styles.errorContainerTablet]}>
<Text style={styles.errorText}>{error}</Text>
<View style={[styles.errorContainer, isTablet && styles.errorContainerTablet, { backgroundColor: colors.dangerContainer }]}>
<Text style={[styles.errorText, { color: colors.danger }]}>{error}</Text>
<TouchableOpacity onPress={loadNotifications} style={styles.retryButton}>
<Text style={styles.retryText}>Reintentar</Text>
<Text style={[styles.retryText, { color: colors.primary }]}>Reintentar</Text>
</TouchableOpacity>
</View>
)}
@@ -146,8 +148,8 @@ export default function AlertsScreen() {
{!error && items.length === 0 && (
<View style={styles.emptyContainer}>
<Ionicons name="notifications-off-outline" size={isTablet ? 80 : 64} color={colors.border} />
<Text style={[styles.emptyTitle, isTablet && styles.emptyTitleTablet]}>Sin notificaciones</Text>
<Text style={[styles.emptyText, isTablet && styles.emptyTextTablet]}>
<Text style={[styles.emptyTitle, isTablet && styles.emptyTitleTablet, { color: colors.text }]}>Sin notificaciones</Text>
<Text style={[styles.emptyText, isTablet && styles.emptyTextTablet, { color: colors.textSecondary }]}>
Toca la campana en una farmacia sin stock para recibir notificaciones cuando se reponga.
</Text>
</View>
@@ -169,7 +171,6 @@ export default function AlertsScreen() {
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.background,
},
header: {
paddingHorizontal: spacing.lg,
@@ -184,14 +185,12 @@ const styles = StyleSheet.create({
title: {
fontSize: 22,
fontWeight: 'bold',
color: colors.text,
},
titleTablet: {
fontSize: 28,
},
subtitle: {
fontSize: 14,
color: colors.textSecondary,
marginTop: spacing.xs,
lineHeight: 20,
},
@@ -212,7 +211,6 @@ const styles = StyleSheet.create({
item: {
flexDirection: 'row',
alignItems: 'center',
backgroundColor: colors.card,
borderRadius: borderRadius.lg,
padding: spacing.md,
...shadows.card,
@@ -224,7 +222,6 @@ const styles = StyleSheet.create({
itemName: {
fontSize: 16,
fontWeight: '600',
color: colors.text,
lineHeight: 22,
},
itemMeta: {
@@ -234,7 +231,6 @@ const styles = StyleSheet.create({
flexDirection: 'row',
alignItems: 'center',
gap: spacing.xs,
backgroundColor: colors.primaryContainer,
borderRadius: borderRadius.full,
paddingHorizontal: spacing.sm,
paddingVertical: 3,
@@ -243,17 +239,14 @@ const styles = StyleSheet.create({
chipText: {
fontSize: 12,
fontWeight: '600',
color: colors.onPrimaryContainer,
},
itemAddress: {
fontSize: 12,
color: colors.textSecondary,
},
deleteButton: {
width: 36,
height: 36,
borderRadius: 18,
backgroundColor: colors.dangerContainer,
alignItems: 'center',
justifyContent: 'center',
marginLeft: spacing.sm,
@@ -261,7 +254,6 @@ const styles = StyleSheet.create({
errorContainer: {
margin: spacing.lg,
padding: spacing.md,
backgroundColor: colors.dangerContainer,
borderRadius: borderRadius.lg,
alignItems: 'center',
gap: spacing.sm,
@@ -272,7 +264,6 @@ const styles = StyleSheet.create({
},
errorText: {
fontSize: 14,
color: colors.danger,
textAlign: 'center',
},
retryButton: {
@@ -282,7 +273,6 @@ const styles = StyleSheet.create({
retryText: {
fontSize: 14,
fontWeight: '600',
color: colors.primary,
},
emptyContainer: {
flex: 1,
@@ -294,14 +284,12 @@ const styles = StyleSheet.create({
emptyTitle: {
fontSize: 18,
fontWeight: '600',
color: colors.text,
},
emptyTitleTablet: {
fontSize: 24,
},
emptyText: {
fontSize: 14,
color: colors.textSecondary,
textAlign: 'center',
lineHeight: 20,
},
-166
View File
@@ -1,166 +0,0 @@
import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Image, useWindowDimensions } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { colors, spacing, borderRadius, shadows } from '../../constants/theme';
const TABLET_MIN_WIDTH = 768;
export default function HomeScreen() {
const router = useRouter();
const { width } = useWindowDimensions();
const isTablet = width >= TABLET_MIN_WIDTH;
return (
<View style={styles.container}>
<View style={[styles.hero, isTablet && styles.heroTablet]}>
<Image
source={require('../../assets/farmaclic_logo.png')}
style={[styles.logo, isTablet && styles.logoTablet]}
resizeMode="contain"
/>
<Text style={[styles.brandName, isTablet && styles.brandNameTablet]}>FarmaClic</Text>
<Text style={[styles.description, isTablet && styles.descriptionTablet]}>
Encuentra tus medicamentos en farmacias cercanas
</Text>
</View>
<View style={[styles.cards, isTablet && styles.cardsTablet]}>
<TouchableOpacity
style={[styles.card, isTablet && styles.cardTablet]}
activeOpacity={0.85}
onPress={() => router.push('/(tabs)')}
>
<View style={[styles.cardIcon, styles.cardIconSearch]}>
<Ionicons name="search" size={isTablet ? 28 : 24} color={colors.onPrimaryContainer} />
</View>
<View style={styles.cardContent}>
<Text style={[styles.cardLabel, isTablet && styles.cardLabelTablet]}>Buscar Medicamento</Text>
<Ionicons name="chevron-forward" size={20} color={colors.onPrimaryContainer} style={{ opacity: 0.7 }} />
</View>
</TouchableOpacity>
<TouchableOpacity
style={[styles.card, styles.cardScan, isTablet && styles.cardTablet]}
activeOpacity={0.85}
onPress={() => router.push('/scanner')}
>
<View style={[styles.cardIcon, styles.cardIconScan]}>
<Ionicons name="scan" size={isTablet ? 28 : 24} color="#ffffff" />
</View>
<View style={styles.cardContent}>
<Text style={[styles.cardLabel, styles.cardLabelScan, isTablet && styles.cardLabelTablet]}>Escanear TSI</Text>
<Ionicons name="chevron-forward" size={20} color="#ffffff" style={{ opacity: 0.7 }} />
</View>
</TouchableOpacity>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.background,
alignItems: 'center',
justifyContent: 'center',
paddingHorizontal: spacing.lg,
gap: spacing.lg,
},
hero: {
alignItems: 'center',
gap: spacing.sm,
marginBottom: spacing.md,
},
heroTablet: {
marginBottom: spacing.xl,
},
logo: {
width: 120,
height: 120,
marginBottom: spacing.xs,
},
logoTablet: {
width: 160,
height: 160,
},
brandName: {
fontSize: 28,
fontWeight: 'bold',
color: colors.text,
letterSpacing: -0.5,
},
brandNameTablet: {
fontSize: 36,
},
description: {
fontSize: 16,
color: colors.textSecondary,
textAlign: 'center',
maxWidth: 260,
lineHeight: 24,
},
descriptionTablet: {
fontSize: 18,
maxWidth: 400,
lineHeight: 28,
},
cards: {
width: '100%',
maxWidth: 320,
gap: spacing.md,
},
cardsTablet: {
maxWidth: 480,
},
card: {
flexDirection: 'row',
alignItems: 'center',
gap: spacing.md,
backgroundColor: colors.primaryContainer,
borderRadius: borderRadius.lg,
padding: spacing.md,
minHeight: 64,
...shadows.card,
},
cardTablet: {
padding: spacing.lg,
minHeight: 72,
},
cardScan: {
backgroundColor: colors.scanButton,
},
cardIcon: {
width: 48,
height: 48,
borderRadius: borderRadius.md,
backgroundColor: 'rgba(255, 255, 255, 0.2)',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
},
cardIconSearch: {
backgroundColor: 'rgba(255, 255, 255, 0.3)',
},
cardIconScan: {
backgroundColor: 'rgba(255, 255, 255, 0.2)',
},
cardContent: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
cardLabel: {
fontSize: 18,
fontWeight: '700',
color: colors.onPrimaryContainer,
lineHeight: 24,
},
cardLabelTablet: {
fontSize: 20,
},
cardLabelScan: {
color: '#ffffff',
},
});
+133 -127
View File
@@ -1,15 +1,9 @@
import React, { useState, useEffect } from 'react';
import { View, FlatList, StyleSheet, Text, TouchableOpacity, useWindowDimensions } from 'react-native';
import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Image, useWindowDimensions } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { SearchBar } from '../../components/SearchBar';
import { MedicineCard } from '../../components/MedicineCard';
import { LoadingSpinner } from '../../components/LoadingSpinner';
import { useDebounce } from '../../hooks/useDebounce';
import { searchMedicines } from '../../services/medicines';
import { colors, spacing, borderRadius } from '../../constants/theme';
import { Medicine } from '../../types';
import { config } from '../../constants/config';
import { useThemeContext } from '../../components/ThemeProvider';
import { spacing, borderRadius, shadows } from '../../constants/theme';
const TABLET_MIN_WIDTH = 768;
@@ -17,77 +11,51 @@ export default function HomeScreen() {
const router = useRouter();
const { width } = useWindowDimensions();
const isTablet = width >= TABLET_MIN_WIDTH;
const [query, setQuery] = useState('');
const [results, setResults] = useState<Medicine[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const debouncedQuery = useDebounce(query, config.SEARCH_DEBOUNCE_MS);
useEffect(() => {
if (debouncedQuery.length < 2) {
setResults([]);
return;
}
const fetchResults = async () => {
setIsLoading(true);
setError(null);
try {
const data = await searchMedicines(debouncedQuery);
setResults(data);
} catch (err) {
setError('Error al buscar medicamentos');
console.error(err);
} finally {
setIsLoading(false);
}
};
fetchResults();
}, [debouncedQuery]);
const handleSearch = (searchQuery: string) => {
setQuery(searchQuery);
};
const { colors } = useThemeContext();
return (
<View style={styles.container}>
<View style={[styles.searchContainer, isTablet && styles.searchContainerTablet]}>
<SearchBar
onSearch={handleSearch}
value={query}
onChangeText={setQuery}
<View style={[styles.container, { backgroundColor: colors.background }]}>
<View style={[styles.hero, isTablet && styles.heroTablet]}>
<Image
source={require('../../assets/farmaclic_logo.png')}
style={[styles.logo, isTablet && styles.logoTablet]}
resizeMode="contain"
/>
<TouchableOpacity
style={styles.scannerButton}
onPress={() => router.push('/scanner')}
>
<Ionicons name="scan" size={22} color="#ffffff" />
</TouchableOpacity>
<Text style={[styles.brandName, isTablet && styles.brandNameTablet, { color: colors.text }]}>FarmaClic</Text>
<Text style={[styles.description, isTablet && styles.descriptionTablet, { color: colors.textSecondary }]}>
Encuentra tus medicamentos en farmacias cercanas
</Text>
</View>
{isLoading && <LoadingSpinner message="Buscando medicamentos..." />}
<View style={[styles.cards, isTablet && styles.cardsTablet]}>
<TouchableOpacity
style={[styles.card, isTablet && styles.cardTablet, { backgroundColor: colors.primaryContainer }]}
activeOpacity={0.85}
onPress={() => router.push('/(tabs)/search')}
>
<View style={[styles.cardIcon, styles.cardIconSearch]}>
<Ionicons name="search" size={isTablet ? 28 : 24} color={colors.onPrimaryContainer} />
</View>
<View style={styles.cardContent}>
<Text style={[styles.cardLabel, isTablet && styles.cardLabelTablet, { color: colors.onPrimaryContainer }]}>Buscar Medicamento</Text>
<Ionicons name="chevron-forward" size={20} color={colors.onPrimaryContainer} style={{ opacity: 0.7 }} />
</View>
</TouchableOpacity>
{error && (
<View style={[styles.errorContainer, isTablet && styles.errorContainerTablet]}>
<Text style={styles.errorText}>{error}</Text>
</View>
)}
{!isLoading && !error && results.length === 0 && query.length >= 2 && (
<View style={styles.emptyContainer}>
<Text style={styles.emptyText}>No se encontraron medicamentos</Text>
</View>
)}
<FlatList
data={results}
keyExtractor={(item) => item.nregistro}
renderItem={({ item }) => <MedicineCard medicine={item} />}
contentContainerStyle={[styles.list, isTablet && styles.listTablet]}
showsVerticalScrollIndicator={false}
/>
<TouchableOpacity
style={[styles.card, styles.cardScan, isTablet && styles.cardTablet]}
activeOpacity={0.85}
onPress={() => router.push('/scanner')}
>
<View style={[styles.cardIcon, styles.cardIconScan]}>
<Ionicons name="scan" size={isTablet ? 28 : 24} color="#ffffff" />
</View>
<View style={styles.cardContent}>
<Text style={[styles.cardLabel, styles.cardLabelScan, isTablet && styles.cardLabelTablet]}>Escanear TSI</Text>
<Ionicons name="chevron-forward" size={20} color="#ffffff" style={{ opacity: 0.7 }} />
</View>
</TouchableOpacity>
</View>
</View>
);
}
@@ -95,63 +63,101 @@ export default function HomeScreen() {
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.background,
},
searchContainer: {
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: spacing.lg,
maxWidth: 480,
alignSelf: 'center',
width: '100%',
},
searchContainerTablet: {
maxWidth: 700,
alignSelf: 'center',
width: '100%',
},
scannerButton: {
width: 44,
height: 44,
borderRadius: 22,
backgroundColor: colors.scanButton,
alignItems: 'center',
justifyContent: 'center',
shadowColor: '#2b5bb5',
shadowOffset: { width: 0, height: 4 },
shadowOpacity: 0.3,
shadowRadius: 12,
elevation: 6,
paddingHorizontal: spacing.lg,
gap: spacing.lg,
},
list: {
paddingBottom: spacing.xl,
},
listTablet: {
maxWidth: 700,
alignSelf: 'center',
width: '100%',
},
errorContainer: {
padding: spacing.md,
marginHorizontal: spacing.lg,
backgroundColor: colors.dangerContainer,
borderRadius: borderRadius.lg,
},
errorContainerTablet: {
maxWidth: 700,
alignSelf: 'center',
},
errorText: {
color: colors.danger,
textAlign: 'center',
fontSize: 14,
},
emptyContainer: {
padding: spacing.xl,
hero: {
alignItems: 'center',
gap: spacing.sm,
marginBottom: spacing.md,
},
emptyText: {
color: colors.textSecondary,
heroTablet: {
marginBottom: spacing.xl,
},
logo: {
width: 120,
height: 120,
marginBottom: spacing.xs,
},
logoTablet: {
width: 160,
height: 160,
},
brandName: {
fontSize: 28,
fontWeight: 'bold',
letterSpacing: -0.5,
},
brandNameTablet: {
fontSize: 36,
},
description: {
fontSize: 16,
textAlign: 'center',
maxWidth: 260,
lineHeight: 24,
},
descriptionTablet: {
fontSize: 18,
maxWidth: 400,
lineHeight: 28,
},
cards: {
width: '100%',
maxWidth: 320,
gap: spacing.md,
},
cardsTablet: {
maxWidth: 480,
},
card: {
flexDirection: 'row',
alignItems: 'center',
gap: spacing.md,
borderRadius: borderRadius.lg,
padding: spacing.md,
minHeight: 64,
...shadows.card,
},
cardTablet: {
padding: spacing.lg,
minHeight: 72,
},
cardScan: {
backgroundColor: '#2b5bb5',
},
cardIcon: {
width: 48,
height: 48,
borderRadius: borderRadius.md,
backgroundColor: 'rgba(255, 255, 255, 0.2)',
alignItems: 'center',
justifyContent: 'center',
flexShrink: 0,
},
cardIconSearch: {
backgroundColor: 'rgba(255, 255, 255, 0.3)',
},
cardIconScan: {
backgroundColor: 'rgba(255, 255, 255, 0.2)',
},
cardContent: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
cardLabel: {
fontSize: 18,
fontWeight: '700',
lineHeight: 24,
},
cardLabelTablet: {
fontSize: 20,
},
cardLabelScan: {
color: '#ffffff',
},
});
+6 -7
View File
@@ -4,15 +4,17 @@ import MapView, { Marker } from 'react-native-maps';
import { useRouter } from 'expo-router';
import { getPharmacies } from '../../services/pharmacies';
import { LoadingSpinner } from '../../components/LoadingSpinner';
import { colors, spacing, borderRadius } from '../../constants/theme';
import { useThemeContext } from '../../components/ThemeProvider';
import { spacing, borderRadius } from '../../constants/theme';
import { Pharmacy } from '../../types';
export default function MapScreen() {
const router = useRouter();
const { colors } = useThemeContext();
const [pharmacies, setPharmacies] = useState<Pharmacy[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [region, setRegion] = useState({
latitude: 40.4168, // Madrid default
latitude: 40.4168,
longitude: -3.7038,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
@@ -24,7 +26,6 @@ export default function MapScreen() {
const data = await getPharmacies();
setPharmacies(data);
// Center map on first pharmacy if available
if (data.length > 0) {
setRegion({
latitude: data[0].latitude,
@@ -70,8 +71,8 @@ export default function MapScreen() {
))}
</MapView>
<View style={styles.legend}>
<Text style={styles.legendText}>
<View style={[styles.legend, { backgroundColor: colors.card }]}>
<Text style={[styles.legendText, { color: colors.text }]}>
{pharmacies.length} farmacias en el mapa
</Text>
</View>
@@ -91,7 +92,6 @@ const styles = StyleSheet.create({
bottom: spacing.lg,
left: spacing.md,
right: spacing.md,
backgroundColor: colors.card,
borderRadius: borderRadius.lg,
padding: spacing.sm + 4,
alignItems: 'center',
@@ -103,6 +103,5 @@ const styles = StyleSheet.create({
},
legendText: {
fontSize: 14,
color: colors.text,
},
});
File diff suppressed because it is too large Load Diff
+262 -23
View File
@@ -1,8 +1,10 @@
import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity, useWindowDimensions } from 'react-native';
import React, { useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, TextInput, Alert, useWindowDimensions, ScrollView } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { colors, spacing, borderRadius, shadows } from '../../constants/theme';
import * as ImagePicker from 'expo-image-picker';
import { useThemeContext } from '../../components/ThemeProvider';
import { spacing, borderRadius, shadows } from '../../constants/theme';
const TABLET_MIN_WIDTH = 768;
@@ -10,36 +12,174 @@ export default function ScanTabScreen() {
const router = useRouter();
const { width } = useWindowDimensions();
const isTablet = width >= TABLET_MIN_WIDTH;
const { colors } = useThemeContext();
const [manualNumber, setManualNumber] = useState('');
const [selectedImage, setSelectedImage] = useState<string | null>(null);
const handleTakePhoto = async () => {
const { status } = await ImagePicker.requestCameraPermissionsAsync();
if (status !== 'granted') {
Alert.alert(
'Permiso requerido',
'Necesitamos acceso a la cámara para tomar fotos del dispositivo.'
);
return;
}
const result = await ImagePicker.launchCameraAsync({
mediaTypes: ['images'],
allowsEditing: true,
quality: 0.8,
});
if (!result.canceled && result.assets[0]) {
setSelectedImage(result.assets[0].uri);
}
};
const handleSelectFromGallery = async () => {
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
if (status !== 'granted') {
Alert.alert(
'Permiso requerido',
'Necesitamos acceso a la galería para seleccionar fotos.'
);
return;
}
const result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ['images'],
allowsEditing: true,
quality: 0.8,
});
if (!result.canceled && result.assets[0]) {
setSelectedImage(result.assets[0].uri);
}
};
const handleManualSubmit = () => {
const trimmed = manualNumber.trim();
if (trimmed.length === 0) {
Alert.alert('Campo requerido', 'Por favor, introduce el número de la tarjeta.');
return;
}
router.push(`/medicine/${trimmed}`);
};
return (
<View style={styles.container}>
<ScrollView
style={[styles.scrollContainer, { backgroundColor: colors.background }]}
contentContainerStyle={styles.scrollContent}
>
<View style={[styles.content, isTablet && styles.contentTablet]}>
<View style={[styles.iconContainer, isTablet && styles.iconContainerTablet]}>
<View style={[styles.iconContainer, isTablet && styles.iconContainerTablet, { backgroundColor: colors.primaryContainer }]}>
<Ionicons name="scan" size={isTablet ? 80 : 64} color={colors.scanButton} />
</View>
<Text style={[styles.title, isTablet && styles.titleTablet]}>Escanear TSI</Text>
<Text style={[styles.description, isTablet && styles.descriptionTablet]}>
<Text style={[styles.title, isTablet && styles.titleTablet, { color: colors.text }]}>Escanear TSI</Text>
<Text style={[styles.description, isTablet && styles.descriptionTablet, { color: colors.textSecondary }]}>
Escanea el código de barras de tu tarjeta sanitaria para encontrar tus medicamentos
</Text>
<TouchableOpacity
style={[styles.button, shadows.scanButton, isTablet && styles.buttonTablet]}
style={[styles.primaryButton, shadows.scanButton, isTablet && styles.primaryButtonTablet]}
activeOpacity={0.85}
onPress={() => router.push('/scanner')}
>
<Ionicons name="scan" size={isTablet ? 28 : 24} color="#ffffff" />
<Text style={[styles.buttonText, isTablet && styles.buttonTextTablet]}>Iniciar escaneo</Text>
<Text style={[styles.primaryButtonText, isTablet && styles.primaryButtonTextTablet]}>
Iniciar escaneo
</Text>
</TouchableOpacity>
{/* Separator */}
<View style={styles.separator}>
<View style={[styles.separatorLine, { backgroundColor: colors.border }]} />
<Text style={[styles.separatorText, { color: colors.textSecondary }]}>o</Text>
<View style={[styles.separatorLine, { backgroundColor: colors.border }]} />
</View>
{/* Option 2: Upload device photo */}
<View style={[styles.optionCard, isTablet && styles.optionCardTablet, { backgroundColor: colors.card, borderColor: colors.border }]}>
<Ionicons name="camera" size={24} color={colors.primary} />
<View style={styles.optionTextContainer}>
<Text style={[styles.optionTitle, isTablet && styles.optionTitleTablet, { color: colors.text }]}>
Subir foto del dispositivo
</Text>
<Text style={[styles.optionDescription, isTablet && styles.optionDescriptionTablet, { color: colors.textSecondary }]}>
Toma o selecciona una foto del dispositivo sanitario
</Text>
</View>
</View>
<View style={styles.photoButtonsRow}>
<TouchableOpacity
style={[styles.photoButton, isTablet && styles.photoButtonTablet, { backgroundColor: colors.primaryContainer, borderColor: colors.primary }]}
activeOpacity={0.7}
onPress={handleTakePhoto}
>
<Ionicons name="camera-outline" size={20} color={colors.primary} />
<Text style={[styles.photoButtonText, { color: colors.primary }]}>Tomar foto</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.photoButton, isTablet && styles.photoButtonTablet, { backgroundColor: colors.primaryContainer, borderColor: colors.primary }]}
activeOpacity={0.7}
onPress={handleSelectFromGallery}
>
<Ionicons name="images-outline" size={20} color={colors.primary} />
<Text style={[styles.photoButtonText, { color: colors.primary }]}>Galería</Text>
</TouchableOpacity>
</View>
{selectedImage && (
<View style={styles.imagePreviewContainer}>
<Ionicons name="checkmark-circle" size={20} color={colors.success} />
<Text style={[styles.imagePreviewText, { color: colors.success }]}>Foto seleccionada correctamente</Text>
</View>
)}
{/* Option 3: Enter card number manually */}
<View style={[styles.optionCard, isTablet && styles.optionCardTablet, { backgroundColor: colors.card, borderColor: colors.border }]}>
<Ionicons name="keypad" size={24} color={colors.primary} />
<View style={styles.optionTextContainer}>
<Text style={[styles.optionTitle, isTablet && styles.optionTitleTablet, { color: colors.text }]}>
Introducir número manualmente
</Text>
<Text style={[styles.optionDescription, isTablet && styles.optionDescriptionTablet, { color: colors.textSecondary }]}>
Escribe el número de tu tarjeta sanitaria
</Text>
</View>
</View>
<View style={styles.manualInputRow}>
<TextInput
style={[styles.manualInput, isTablet && styles.manualInputTablet, { backgroundColor: colors.card, borderColor: colors.border, color: colors.text }]}
placeholder="Introduce el número de tarjeta"
placeholderTextColor={colors.textSecondary}
value={manualNumber}
onChangeText={setManualNumber}
keyboardType="default"
autoCapitalize="none"
autoCorrect={false}
returnKeyType="search"
onSubmitEditing={handleManualSubmit}
/>
<TouchableOpacity
style={[styles.manualSubmitButton, isTablet && styles.manualSubmitButtonTablet]}
activeOpacity={0.7}
onPress={handleManualSubmit}
>
<Ionicons name="arrow-forward" size={20} color="#ffffff" />
</TouchableOpacity>
</View>
</View>
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
container: {
scrollContainer: {
flex: 1,
backgroundColor: colors.background,
alignItems: 'center',
justifyContent: 'center',
},
scrollContent: {
flexGrow: 1,
paddingVertical: spacing.xl,
},
content: {
alignItems: 'center',
@@ -53,7 +193,6 @@ const styles = StyleSheet.create({
width: 100,
height: 100,
borderRadius: 50,
backgroundColor: colors.primaryContainer,
alignItems: 'center',
justifyContent: 'center',
marginBottom: spacing.sm,
@@ -66,14 +205,12 @@ const styles = StyleSheet.create({
title: {
fontSize: 22,
fontWeight: 'bold',
color: colors.text,
},
titleTablet: {
fontSize: 28,
},
description: {
fontSize: 15,
color: colors.textSecondary,
textAlign: 'center',
lineHeight: 22,
maxWidth: 280,
@@ -83,26 +220,128 @@ const styles = StyleSheet.create({
maxWidth: 420,
lineHeight: 26,
},
button: {
primaryButton: {
flexDirection: 'row',
alignItems: 'center',
gap: spacing.sm,
backgroundColor: colors.scanButton,
backgroundColor: '#2b5bb5',
borderRadius: borderRadius.lg,
paddingVertical: spacing.md,
paddingHorizontal: spacing.xl,
marginTop: spacing.md,
marginTop: spacing.sm,
},
buttonTablet: {
primaryButtonTablet: {
paddingVertical: spacing.lg,
paddingHorizontal: spacing.xl * 1.5,
},
buttonText: {
primaryButtonText: {
fontSize: 17,
fontWeight: '600',
color: '#ffffff',
},
buttonTextTablet: {
primaryButtonTextTablet: {
fontSize: 20,
},
separator: {
flexDirection: 'row',
alignItems: 'center',
width: '100%',
marginVertical: spacing.sm,
},
separatorLine: {
flex: 1,
height: 1,
},
separatorText: {
marginHorizontal: spacing.md,
fontSize: 14,
},
optionCard: {
flexDirection: 'row',
alignItems: 'center',
width: '100%',
borderRadius: borderRadius.lg,
padding: spacing.md,
gap: spacing.md,
borderWidth: 1,
},
optionCardTablet: {
padding: spacing.lg,
},
optionTextContainer: {
flex: 1,
},
optionTitle: {
fontSize: 16,
fontWeight: '600',
},
optionTitleTablet: {
fontSize: 18,
},
optionDescription: {
fontSize: 13,
marginTop: 2,
},
optionDescriptionTablet: {
fontSize: 15,
},
photoButtonsRow: {
flexDirection: 'row',
width: '100%',
gap: spacing.sm,
},
photoButton: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
gap: spacing.xs,
borderRadius: borderRadius.md,
paddingVertical: spacing.sm + 4,
borderWidth: 1,
},
photoButtonTablet: {
paddingVertical: spacing.md,
},
photoButtonText: {
fontSize: 14,
fontWeight: '500',
},
imagePreviewContainer: {
flexDirection: 'row',
alignItems: 'center',
gap: spacing.xs,
paddingVertical: spacing.xs,
},
imagePreviewText: {
fontSize: 13,
fontWeight: '500',
},
manualInputRow: {
flexDirection: 'row',
width: '100%',
gap: spacing.sm,
},
manualInput: {
flex: 1,
borderRadius: borderRadius.md,
borderWidth: 1,
paddingHorizontal: spacing.md,
paddingVertical: spacing.sm + 4,
fontSize: 15,
},
manualInputTablet: {
fontSize: 18,
paddingVertical: spacing.md,
},
manualSubmitButton: {
backgroundColor: '#7fbf8f',
borderRadius: borderRadius.md,
width: 48,
alignItems: 'center',
justifyContent: 'center',
},
manualSubmitButtonTablet: {
width: 56,
},
});
+248
View File
@@ -0,0 +1,248 @@
import React, { useState, useEffect } from 'react';
import { View, FlatList, StyleSheet, Text, TouchableOpacity, useWindowDimensions } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useNavigation } from 'expo-router';
import { SearchBar } from '../../components/SearchBar';
import { MedicineCard } from '../../components/MedicineCard';
import { LoadingSpinner } from '../../components/LoadingSpinner';
import { useDebounce } from '../../hooks/useDebounce';
import { useAuth } from '../../hooks/useAuth';
import { useRecentSearches } from '../../hooks/useRecentSearches';
import { searchMedicines } from '../../services/medicines';
import { useThemeContext } from '../../components/ThemeProvider';
import { spacing, borderRadius } from '../../constants/theme';
import { Medicine } from '../../types';
import { config } from '../../constants/config';
const TABLET_MIN_WIDTH = 768;
const suggestions = [
{ name: 'Paracetamol', icon: 'medical' as const },
{ name: 'Ibuprofeno', icon: 'fitness' as const },
{ name: 'Aspirina', icon: 'heart' as const },
{ name: 'Omeprazol', icon: 'bandage' as const },
];
export default function SearchScreen() {
const { width } = useWindowDimensions();
const isTablet = width >= TABLET_MIN_WIDTH;
const { isAuthenticated } = useAuth();
const { recentSearches, addSearch, removeSearch } = useRecentSearches();
const { colors } = useThemeContext();
const [query, setQuery] = useState('');
const [results, setResults] = useState<Medicine[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const debouncedQuery = useDebounce(query, config.SEARCH_DEBOUNCE_MS);
const navigation = useNavigation();
useEffect(() => {
const parent = navigation.getParent();
if (!parent) return;
const unsubscribe = parent.addListener('tabPress', () => {
setQuery('');
setResults([]);
setIsLoading(false);
setError(null);
});
return unsubscribe;
}, [navigation]);
useEffect(() => {
if (debouncedQuery.length < 2) {
setResults([]);
return;
}
const fetchResults = async () => {
setIsLoading(true);
setError(null);
try {
const data = await searchMedicines(debouncedQuery);
setResults(data);
} catch (err) {
setError('Error al buscar medicamentos');
console.error(err);
} finally {
setIsLoading(false);
}
};
fetchResults();
}, [debouncedQuery]);
const handleSearch = (searchQuery: string) => {
setQuery(searchQuery);
if (searchQuery.trim()) addSearch(searchQuery);
};
const showSuggestions = !query && !isLoading && results.length === 0;
return (
<View style={[styles.container, { backgroundColor: colors.background }]}>
<SearchBar
onSearch={handleSearch}
value={query}
onChangeText={setQuery}
/>
{showSuggestions && (
<>
<View style={[styles.suggestionsSection, isTablet && styles.suggestionsSectionTablet]}>
<Text style={[styles.sectionTitle, { color: colors.text }]}>Sugerencias</Text>
<View style={styles.suggestionsGrid}>
{suggestions.map((s) => (
<TouchableOpacity
key={s.name}
style={[styles.suggestionCard, { backgroundColor: colors.card, borderColor: colors.border }]}
onPress={() => handleSearch(s.name)}
activeOpacity={0.7}
>
<View style={[styles.suggestionIcon, { backgroundColor: colors.surfaceLow }]}>
<Ionicons name={s.icon} size={22} color={colors.primary} />
</View>
<Text style={[styles.suggestionName, { color: colors.text }]}>{s.name}</Text>
</TouchableOpacity>
))}
</View>
</View>
{isAuthenticated && recentSearches.length > 0 && (
<View style={[styles.recentSection, isTablet && styles.recentSectionTablet]}>
<Text style={[styles.sectionTitle, { color: colors.text }]}>Búsquedas recientes</Text>
{recentSearches.map((term) => (
<TouchableOpacity
key={term}
style={styles.recentItem}
onPress={() => handleSearch(term)}
activeOpacity={0.7}
>
<Ionicons name="time-outline" size={18} color={colors.textSecondary} />
<Text style={[styles.recentText, { color: colors.text }]}>{term}</Text>
<TouchableOpacity onPress={() => removeSearch(term)} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
<Ionicons name="close" size={16} color={colors.textSecondary} />
</TouchableOpacity>
</TouchableOpacity>
))}
</View>
)}
</>
)}
{isLoading && <LoadingSpinner message="Buscando medicamentos..." />}
{error && (
<View style={[styles.errorContainer, isTablet && styles.errorContainerTablet, { backgroundColor: colors.dangerContainer }]}>
<Text style={[styles.errorText, { color: colors.danger }]}>{error}</Text>
</View>
)}
{!isLoading && !error && results.length === 0 && query.length >= 2 && (
<View style={styles.emptyContainer}>
<Text style={[styles.emptyText, { color: colors.textSecondary }]}>No se encontraron medicamentos</Text>
</View>
)}
<FlatList
data={results}
keyExtractor={(item) => item.nregistro}
renderItem={({ item }) => <MedicineCard medicine={item} />}
contentContainerStyle={[styles.list, isTablet && styles.listTablet]}
showsVerticalScrollIndicator={false}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
suggestionsSection: {
marginTop: spacing.sm,
alignSelf: 'center',
width: '80%',
},
suggestionsSectionTablet: {
maxWidth: 700,
alignSelf: 'center',
width: '100%',
},
sectionTitle: {
fontSize: 20,
fontWeight: '700',
marginBottom: spacing.md,
},
suggestionsGrid: {
flexDirection: 'row',
flexWrap: 'wrap',
gap: spacing.sm,
},
suggestionCard: {
width: '48%' as unknown as number,
borderRadius: borderRadius.lg,
borderWidth: 1,
padding: spacing.md,
gap: spacing.sm,
},
suggestionIcon: {
width: 40,
height: 40,
borderRadius: borderRadius.md,
alignItems: 'center',
justifyContent: 'center',
},
suggestionName: {
fontSize: 16,
fontWeight: '700',
},
recentSection: {
marginTop: spacing.lg,
alignSelf: 'center',
width: '80%',
},
recentSectionTablet: {
maxWidth: 700,
alignSelf: 'center',
width: '100%',
},
recentItem: {
flexDirection: 'row',
alignItems: 'center',
paddingVertical: spacing.sm,
gap: spacing.sm,
},
recentText: {
flex: 1,
fontSize: 15,
},
list: {
paddingBottom: spacing.xl,
},
listTablet: {
maxWidth: 700,
alignSelf: 'center',
width: '100%',
},
errorContainer: {
padding: spacing.md,
marginHorizontal: spacing.lg,
borderRadius: borderRadius.lg,
},
errorContainerTablet: {
maxWidth: 700,
alignSelf: 'center',
},
errorText: {
textAlign: 'center',
fontSize: 14,
},
emptyContainer: {
padding: spacing.xl,
alignItems: 'center',
},
emptyText: {
fontSize: 16,
},
});
+52 -41
View File
@@ -7,12 +7,13 @@ import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { useAuthStore } from '../store/authStore';
import { registerForPushNotifications, addNotificationListener, addNotificationResponseListener } from '../services/notifications';
import { colors } from '../constants/theme';
import { ThemeProvider, useThemeContext } from '../components/ThemeProvider';
const queryClient = new QueryClient();
export default function RootLayout() {
function RootLayoutInner() {
const { checkAuth } = useAuthStore();
const { colors, isDark } = useThemeContext();
const notificationListener = useRef<ReturnType<typeof addNotificationListener>>();
const responseListener = useRef<ReturnType<typeof addNotificationResponseListener>>();
@@ -35,6 +36,52 @@ export default function RootLayout() {
};
}, []);
return (
<>
<Stack
screenOptions={{
headerStyle: { backgroundColor: colors.card },
headerTintColor: colors.primary,
headerTitleStyle: { color: colors.text, fontWeight: '600' },
}}
>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen
name="medicine/[id]"
options={{ title: 'Medicamento' }}
/>
<Stack.Screen
name="pharmacy/[id]"
options={{ title: 'Farmacia' }}
/>
<Stack.Screen
name="scanner"
options={{
title: 'Escanear',
headerShown: false,
}}
/>
<Stack.Screen
name="auth/login"
options={{
title: 'Iniciar Sesión',
headerShown: false,
}}
/>
<Stack.Screen
name="auth/register"
options={{
title: 'Registrarse',
headerShown: false,
}}
/>
</Stack>
<StatusBar style={isDark ? 'light' : 'auto'} />
</>
);
}
export default function RootLayout() {
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<ImageBackground
@@ -46,45 +93,9 @@ export default function RootLayout() {
<View style={bgStyles.overlay} />
<SafeAreaProvider>
<QueryClientProvider client={queryClient}>
<Stack
screenOptions={{
headerStyle: { backgroundColor: colors.card },
headerTintColor: colors.primary,
headerTitleStyle: { color: colors.text, fontWeight: '600' },
}}
>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen
name="medicine/[id]"
options={{ title: 'Medicamento' }}
/>
<Stack.Screen
name="pharmacy/[id]"
options={{ title: 'Farmacia' }}
/>
<Stack.Screen
name="scanner"
options={{
title: 'Escanear',
headerShown: false,
}}
/>
<Stack.Screen
name="auth/login"
options={{
title: 'Iniciar Sesión',
headerShown: false,
}}
/>
<Stack.Screen
name="auth/register"
options={{
title: 'Registrarse',
headerShown: false,
}}
/>
</Stack>
<StatusBar style="auto" />
<ThemeProvider>
<RootLayoutInner />
</ThemeProvider>
</QueryClientProvider>
</SafeAreaProvider>
</ImageBackground>
+15 -26
View File
@@ -12,7 +12,8 @@ import {
import { useRouter } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { useAuthStore } from '../../store/authStore';
import { colors, spacing, borderRadius } from '../../constants/theme';
import { useThemeContext } from '../../components/ThemeProvider';
import { spacing, borderRadius } from '../../constants/theme';
import {
isBiometricsAvailable,
authenticateWithBiometrics,
@@ -23,6 +24,7 @@ import {
export default function LoginScreen() {
const router = useRouter();
const { login } = useAuthStore();
const { colors } = useThemeContext();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [isLoading, setIsLoading] = useState(false);
@@ -55,7 +57,6 @@ export default function LoginScreen() {
setIsLoading(true);
try {
await login(username, password);
// Save username for biometric login
if (biometricsAvailable) {
await saveBiometricCredentials(username);
}
@@ -77,8 +78,6 @@ export default function LoginScreen() {
try {
const authenticated = await authenticateWithBiometrics();
if (authenticated) {
// Use saved username with empty password for biometric login
// The backend should handle biometric authentication differently
await login(biometricUsername, '');
router.replace('/(tabs)');
} else {
@@ -93,17 +92,17 @@ export default function LoginScreen() {
return (
<KeyboardAvoidingView
style={styles.container}
style={[styles.container, { backgroundColor: colors.background }]}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
>
<View style={styles.form}>
<Text style={styles.title}>Iniciar Sesión</Text>
<Text style={styles.subtitle}>Ingresa tus credenciales para continuar</Text>
<Text style={[styles.title, { color: colors.text }]}>Iniciar Sesión</Text>
<Text style={[styles.subtitle, { color: colors.textSecondary }]}>Ingresa tus credenciales para continuar</Text>
<View style={styles.inputContainer}>
<Text style={styles.label}>Usuario</Text>
<Text style={[styles.label, { color: colors.text }]}>Usuario</Text>
<TextInput
style={styles.input}
style={[styles.input, { backgroundColor: colors.card, color: colors.text }]}
value={username}
onChangeText={setUsername}
placeholder="Tu usuario"
@@ -114,9 +113,9 @@ export default function LoginScreen() {
</View>
<View style={styles.inputContainer}>
<Text style={styles.label}>Contraseña</Text>
<Text style={[styles.label, { color: colors.text }]}>Contraseña</Text>
<TextInput
style={styles.input}
style={[styles.input, { backgroundColor: colors.card, color: colors.text }]}
value={password}
onChangeText={setPassword}
placeholder="Tu contraseña"
@@ -137,12 +136,12 @@ export default function LoginScreen() {
{biometricsAvailable && biometricUsername && (
<TouchableOpacity
style={[styles.biometricButton, isLoading && styles.buttonDisabled]}
style={[styles.biometricButton, { backgroundColor: colors.card, borderColor: colors.primary }]}
onPress={handleBiometricLogin}
disabled={isLoading}
>
<Ionicons name="finger-print" size={24} color={colors.primary} />
<Text style={styles.biometricText}>Iniciar con biometría</Text>
<Text style={[styles.biometricText, { color: colors.primary }]}>Iniciar con biometría</Text>
</TouchableOpacity>
)}
@@ -150,7 +149,7 @@ export default function LoginScreen() {
style={styles.linkButton}
onPress={() => router.push('/auth/register')}
>
<Text style={styles.linkText}>¿No tienes cuenta? Regístrate</Text>
<Text style={[styles.linkText, { color: colors.primary }]}>¿No tienes cuenta? Regístrate</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
@@ -160,7 +159,6 @@ export default function LoginScreen() {
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.background,
},
form: {
flex: 1,
@@ -170,12 +168,10 @@ const styles = StyleSheet.create({
title: {
fontSize: 28,
fontWeight: 'bold',
color: colors.text,
marginBottom: spacing.sm,
},
subtitle: {
fontSize: 16,
color: colors.textSecondary,
marginBottom: spacing.xl,
},
inputContainer: {
@@ -184,18 +180,15 @@ const styles = StyleSheet.create({
label: {
fontSize: 14,
fontWeight: '500',
color: colors.text,
marginBottom: spacing.xs,
},
input: {
backgroundColor: colors.card,
borderRadius: borderRadius.md,
padding: spacing.md,
fontSize: 16,
color: colors.text,
},
button: {
backgroundColor: colors.primary,
backgroundColor: '#7fbf8f',
borderRadius: borderRadius.md,
padding: spacing.md,
alignItems: 'center',
@@ -205,7 +198,7 @@ const styles = StyleSheet.create({
opacity: 0.6,
},
buttonText: {
color: colors.textInverse,
color: '#ffffff',
fontSize: 16,
fontWeight: '600',
},
@@ -214,22 +207,18 @@ const styles = StyleSheet.create({
alignItems: 'center',
},
linkText: {
color: colors.primary,
fontSize: 14,
},
biometricButton: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: colors.card,
borderRadius: borderRadius.md,
padding: spacing.md,
marginTop: spacing.md,
borderWidth: 1,
borderColor: colors.primary,
},
biometricText: {
color: colors.primary,
fontSize: 16,
fontWeight: '600',
marginLeft: spacing.sm,
+15 -20
View File
@@ -11,10 +11,12 @@ import {
} from 'react-native';
import { useRouter } from 'expo-router';
import { register } from '../../services/auth';
import { colors, spacing, borderRadius } from '../../constants/theme';
import { useThemeContext } from '../../components/ThemeProvider';
import { spacing, borderRadius } from '../../constants/theme';
export default function RegisterScreen() {
const router = useRouter();
const { colors } = useThemeContext();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
@@ -44,17 +46,17 @@ export default function RegisterScreen() {
return (
<KeyboardAvoidingView
style={styles.container}
style={[styles.container, { backgroundColor: colors.background }]}
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
>
<View style={styles.form}>
<Text style={styles.title}>Crear Cuenta</Text>
<Text style={styles.subtitle}>Regístrate para empezar</Text>
<Text style={[styles.title, { color: colors.text }]}>Crear Cuenta</Text>
<Text style={[styles.subtitle, { color: colors.textSecondary }]}>Regístrate para empezar</Text>
<View style={styles.inputContainer}>
<Text style={styles.label}>Usuario</Text>
<Text style={[styles.label, { color: colors.text }]}>Usuario</Text>
<TextInput
style={styles.input}
style={[styles.input, { backgroundColor: colors.card, color: colors.text }]}
value={username}
onChangeText={setUsername}
placeholder="Elige un usuario"
@@ -65,9 +67,9 @@ export default function RegisterScreen() {
</View>
<View style={styles.inputContainer}>
<Text style={styles.label}>Contraseña</Text>
<Text style={[styles.label, { color: colors.text }]}>Contraseña</Text>
<TextInput
style={styles.input}
style={[styles.input, { backgroundColor: colors.card, color: colors.text }]}
value={password}
onChangeText={setPassword}
placeholder="Elige una contraseña"
@@ -77,9 +79,9 @@ export default function RegisterScreen() {
</View>
<View style={styles.inputContainer}>
<Text style={styles.label}>Confirmar Contraseña</Text>
<Text style={[styles.label, { color: colors.text }]}>Confirmar Contraseña</Text>
<TextInput
style={styles.input}
style={[styles.input, { backgroundColor: colors.card, color: colors.text }]}
value={confirmPassword}
onChangeText={setConfirmPassword}
placeholder="Repite la contraseña"
@@ -102,7 +104,7 @@ export default function RegisterScreen() {
style={styles.linkButton}
onPress={() => router.back()}
>
<Text style={styles.linkText}>¿Ya tienes cuenta? Inicia sesión</Text>
<Text style={[styles.linkText, { color: colors.primary }]}>¿Ya tienes cuenta? Inicia sesión</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
@@ -112,7 +114,6 @@ export default function RegisterScreen() {
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.background,
},
form: {
flex: 1,
@@ -122,12 +123,10 @@ const styles = StyleSheet.create({
title: {
fontSize: 28,
fontWeight: 'bold',
color: colors.text,
marginBottom: spacing.sm,
},
subtitle: {
fontSize: 16,
color: colors.textSecondary,
marginBottom: spacing.xl,
},
inputContainer: {
@@ -136,18 +135,15 @@ const styles = StyleSheet.create({
label: {
fontSize: 14,
fontWeight: '500',
color: colors.text,
marginBottom: spacing.xs,
},
input: {
backgroundColor: colors.card,
borderRadius: borderRadius.md,
padding: spacing.md,
fontSize: 16,
color: colors.text,
},
button: {
backgroundColor: colors.primary,
backgroundColor: '#7fbf8f',
borderRadius: borderRadius.md,
padding: spacing.md,
alignItems: 'center',
@@ -157,7 +153,7 @@ const styles = StyleSheet.create({
opacity: 0.6,
},
buttonText: {
color: colors.textInverse,
color: '#ffffff',
fontSize: 16,
fontWeight: '600',
},
@@ -166,7 +162,6 @@ const styles = StyleSheet.create({
alignItems: 'center',
},
linkText: {
color: colors.primary,
fontSize: 14,
},
});
+263 -65
View File
@@ -1,19 +1,52 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect, useState, useMemo } from 'react';
import { View, Text, ScrollView, StyleSheet, TouchableOpacity, Linking } from 'react-native';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import * as Location from 'expo-location';
import { getMedicine, getMedicinePharmacies } from '../../services/medicines';
import { StockBadge } from '../../components/StockBadge';
import { LoadingSpinner } from '../../components/LoadingSpinner';
import { colors, spacing, borderRadius } from '../../constants/theme';
import { useThemeContext } from '../../components/ThemeProvider';
import { spacing, borderRadius } from '../../constants/theme';
import { Medicine, PharmacyMedicine } from '../../types';
function haversineKm(lat1: number, lon1: number, lat2: number, lon2: number): number {
const R = 6371;
const dLat = ((lat2 - lat1) * Math.PI) / 180;
const dLon = ((lon2 - lon1) * Math.PI) / 180;
const a =
Math.sin(dLat / 2) ** 2 +
Math.cos((lat1 * Math.PI) / 180) *
Math.cos((lat2 * Math.PI) / 180) *
Math.sin(dLon / 2) ** 2;
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
function formatDistance(km: number): string {
if (km < 1) return `${Math.round(km * 1000)} m`;
if (km < 10) return `${km.toFixed(1)} km`;
return `${Math.round(km)} km`;
}
function getPharmacyLat(p: PharmacyMedicine): number | null {
return p.latitude ?? p.pharmacy?.latitude ?? null;
}
function getPharmacyLon(p: PharmacyMedicine): number | null {
return p.longitude ?? p.pharmacy?.longitude ?? null;
}
export default function MedicineDetailScreen() {
const { id } = useLocalSearchParams<{ id: string }>();
const router = useRouter();
const { colors } = useThemeContext();
const [medicine, setMedicine] = useState<Medicine | null>(null);
const [pharmacies, setPharmacies] = useState<PharmacyMedicine[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [sortByDistance, setSortByDistance] = useState(false);
const [userPosition, setUserPosition] = useState<{ lat: number; lon: number } | null>(null);
const [locating, setLocating] = useState(false);
const [locationError, setLocationError] = useState<string | null>(null);
useEffect(() => {
if (!id) return;
@@ -36,6 +69,64 @@ export default function MedicineDetailScreen() {
fetchMedicine();
}, [id]);
const handleSortByDistance = async () => {
if (sortByDistance) {
setSortByDistance(false);
return;
}
setLocating(true);
setLocationError(null);
try {
const { status } = await Location.requestForegroundPermissionsAsync();
if (status !== 'granted') {
setLocationError('Permiso de ubicación denegado');
setLocating(false);
return;
}
const pos = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.Balanced });
setUserPosition({ lat: pos.coords.latitude, lon: pos.coords.longitude });
setSortByDistance(true);
} catch {
setLocationError('No se pudo obtener tu ubicación');
} finally {
setLocating(false);
}
};
const sortedPharmacies = useMemo(() => {
if (!sortByDistance || !userPosition) return pharmacies;
return [...pharmacies]
.map((p) => {
const lat = getPharmacyLat(p);
const lon = getPharmacyLon(p);
const distance =
lat != null && lon != null
? haversineKm(userPosition.lat, userPosition.lon, lat, lon)
: Infinity;
return { ...p, _distance: distance };
})
.sort((a, b) => a._distance - b._distance);
}, [pharmacies, sortByDistance, userPosition]);
const locatedPharmacies = useMemo(
() =>
sortedPharmacies.filter(
(p) => getPharmacyLat(p) != null && getPharmacyLon(p) != null
),
[sortedPharmacies]
);
const mapCenter = useMemo(() => {
if (locatedPharmacies.length === 0) return { latitude: 40.4168, longitude: -3.7038 };
const lat = locatedPharmacies.reduce((s, p) => s + (getPharmacyLat(p) || 0), 0) / locatedPharmacies.length;
const lon = locatedPharmacies.reduce((s, p) => s + (getPharmacyLon(p) || 0), 0) / locatedPharmacies.length;
return { latitude: lat, longitude: lon };
}, [locatedPharmacies]);
const handleDirections = (latitude: number, longitude: number) => {
const url = `https://www.google.com/maps/dir/?api=1&destination=${latitude},${longitude}`;
Linking.openURL(url);
@@ -47,76 +138,131 @@ export default function MedicineDetailScreen() {
if (!medicine) {
return (
<View style={styles.errorContainer}>
<Text style={styles.errorText}>Medicamento no encontrado</Text>
<View style={[styles.errorContainer, { backgroundColor: colors.background }]}>
<Text style={[styles.errorText, { color: colors.textSecondary }]}>Medicamento no encontrado</Text>
</View>
);
}
return (
<ScrollView style={styles.container}>
<View style={styles.header}>
<Text style={styles.name}>{medicine.name}</Text>
<ScrollView style={[styles.container, { backgroundColor: colors.background }]}>
<View style={[styles.header, { backgroundColor: colors.card }]}>
<Text style={[styles.name, { color: colors.text }]}>{medicine.name}</Text>
{medicine.stock != null && <StockBadge stock={medicine.stock} />}
</View>
<View style={styles.infoSection}>
<InfoRow label="Principio activo" value={medicine.active_ingredient} />
<InfoRow label="Laboratorio" value={medicine.laboratory} />
<InfoRow label="Forma farmacéutica" value={medicine.form} />
<InfoRow label="Dosificación" value={medicine.dosage} />
<View style={[styles.infoSection, { backgroundColor: colors.card }]}>
<InfoRow label="Principio activo" value={medicine.active_ingredient} colors={colors} />
<InfoRow label="Laboratorio" value={medicine.laboratory} colors={colors} />
<InfoRow label="Forma farmacéutica" value={medicine.form} colors={colors} />
<InfoRow label="Dosificación" value={medicine.dosage} colors={colors} />
<InfoRow
label="Precio"
value={medicine.precio != null ? `${medicine.precio.toFixed(2)}` : 'No disponible'}
colors={colors}
/>
<InfoRow label="Registro" value={medicine.nregistro} />
<InfoRow label="Registro" value={medicine.nregistro} colors={colors} />
</View>
<View style={styles.pharmaciesSection}>
<Text style={styles.sectionTitle}>
Farmacias ({pharmacies.length})
</Text>
{locatedPharmacies.length > 0 && (
<View style={[styles.mapContainer, { backgroundColor: colors.surfaceVariant }]}>
<Ionicons name="map-outline" size={48} color={colors.textSecondary} />
<Text style={[styles.mapPlaceholder, { color: colors.textSecondary }]}>
Mapa próximamente
</Text>
</View>
)}
{pharmacies.length === 0 ? (
<Text style={styles.noPharmacies}>No hay farmacias con este medicamento</Text>
<View style={styles.pharmaciesSection}>
<View style={styles.pharmaciesHeader}>
<Text style={[styles.sectionTitle, { color: colors.text }]}>
Farmacias ({sortedPharmacies.length})
</Text>
<TouchableOpacity
style={[styles.sortButton, sortByDistance && styles.sortButtonActive, { backgroundColor: sortByDistance ? colors.primary : colors.primaryContainer, borderColor: colors.primary }]}
onPress={handleSortByDistance}
disabled={locating}
>
<Ionicons name="location" size={16} color={sortByDistance ? '#fff' : colors.primary} />
<Text style={[styles.sortButtonText, sortByDistance && styles.sortButtonTextActive, { color: sortByDistance ? '#fff' : colors.primary }]}>
{locating
? 'Localizando…'
: sortByDistance
? 'Distancia · Reset'
: 'Ordenar por distancia'}
</Text>
</TouchableOpacity>
</View>
{locationError && (
<View style={[styles.locationErrorContainer, { backgroundColor: colors.dangerContainer }]}>
<Text style={[styles.locationErrorText, { color: colors.danger }]}>{locationError}</Text>
<TouchableOpacity onPress={handleSortByDistance}>
<Text style={[styles.retryText, { color: colors.primary }]}>Reintentar</Text>
</TouchableOpacity>
</View>
)}
{sortedPharmacies.length === 0 ? (
<Text style={[styles.noPharmacies, { color: colors.textSecondary }]}>No hay farmacias disponibles</Text>
) : (
pharmacies.map((pharm) => (
<View key={pharm.id} style={styles.pharmacyCard}>
<TouchableOpacity
style={styles.pharmacyCardContent}
onPress={() => router.push(`/pharmacy/${pharm.pharmacy_id}`)}
>
<View style={styles.pharmacyInfo}>
<Text style={styles.pharmacyName}>{pharm.pharmacy?.name}</Text>
<Text style={styles.pharmacyAddress}>{pharm.pharmacy?.address}</Text>
</View>
<View style={styles.pharmacyStock}>
<Text style={styles.price}>{pharm.price.toFixed(2)} </Text>
<Text style={styles.stock}>Stock: {pharm.stock}</Text>
</View>
</TouchableOpacity>
{pharm.pharmacy?.latitude != null && pharm.pharmacy?.longitude != null && (
sortedPharmacies.map((pharm) => {
const lat = getPharmacyLat(pharm);
const lon = getPharmacyLon(pharm);
const distanceKm =
sortByDistance && userPosition && lat != null && lon != null
? haversineKm(userPosition.lat, userPosition.lon, lat, lon)
: null;
return (
<View key={pharm.id} style={[styles.pharmacyCard, { backgroundColor: colors.card }]}>
<TouchableOpacity
style={styles.directionsButton}
onPress={() => handleDirections(pharm.pharmacy.latitude, pharm.pharmacy.longitude)}
style={styles.pharmacyCardContent}
onPress={() => router.push(`/pharmacy/${pharm.pharmacy_id || pharm.id}`)}
>
<Ionicons name="navigate" size={16} color={colors.primary} />
<Text style={styles.directionsText}>Cómo llegar</Text>
<View style={styles.pharmacyInfo}>
<View style={styles.pharmacyNameRow}>
<Text style={[styles.pharmacyName, { color: colors.text }]}>{pharm.pharmacy?.name || pharm.name}</Text>
{distanceKm != null && (
<Text style={[styles.pharmacyDistance, { color: colors.primary, backgroundColor: colors.primaryContainer }]}>{formatDistance(distanceKm)}</Text>
)}
</View>
<Text style={[styles.pharmacyAddress, { color: colors.textSecondary }]}>{pharm.pharmacy?.address || pharm.address}</Text>
</View>
<View style={styles.pharmacyStock}>
{pharm.price != null ? (
<Text style={[styles.price, { color: colors.primary }]}>{pharm.price.toFixed(2)} </Text>
) : (
<Text style={[styles.price, { color: colors.primary }]}>Consultar precio</Text>
)}
{pharm.stock > 0 && (
<Text style={[styles.stock, { color: colors.textSecondary }]}>Stock: {pharm.stock}</Text>
)}
</View>
</TouchableOpacity>
)}
</View>
))
{lat != null && lon != null && (
<TouchableOpacity
style={[styles.directionsButton, { borderTopColor: colors.border }]}
onPress={() => handleDirections(lat, lon)}
>
<Ionicons name="navigate" size={16} color={colors.primary} />
<Text style={[styles.directionsText, { color: colors.primary }]}>Cómo llegar</Text>
</TouchableOpacity>
)}
</View>
);
})
)}
</View>
</ScrollView>
);
}
function InfoRow({ label, value }: { label: string; value: string }) {
function InfoRow({ label, value, colors }: { label: string; value: string; colors: any }) {
return (
<View style={styles.infoRow}>
<Text style={styles.infoLabel}>{label}</Text>
<Text style={styles.infoValue}>{value}</Text>
<View style={[styles.infoRow, { borderBottomColor: colors.border }]}>
<Text style={[styles.infoLabel, { color: colors.textSecondary }]}>{label}</Text>
<Text style={[styles.infoValue, { color: colors.text }]}>{value}</Text>
</View>
);
}
@@ -124,24 +270,20 @@ function InfoRow({ label, value }: { label: string; value: string }) {
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.background,
},
header: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'flex-start',
padding: spacing.lg,
backgroundColor: colors.card,
},
name: {
flex: 1,
fontSize: 22,
fontWeight: 'bold',
color: colors.text,
marginRight: spacing.sm,
},
infoSection: {
backgroundColor: colors.card,
marginTop: spacing.sm,
padding: spacing.lg,
},
@@ -150,34 +292,82 @@ const styles = StyleSheet.create({
justifyContent: 'space-between',
paddingVertical: spacing.sm,
borderBottomWidth: 1,
borderBottomColor: colors.border,
},
infoLabel: {
fontSize: 14,
color: colors.textSecondary,
fontSize: 13,
flexShrink: 0,
marginRight: spacing.sm,
},
infoValue: {
fontSize: 13,
fontWeight: '500',
flex: 1,
textAlign: 'right',
},
mapContainer: {
marginTop: spacing.sm,
marginHorizontal: spacing.lg,
height: 200,
borderRadius: borderRadius.lg,
overflow: 'hidden',
alignItems: 'center',
justifyContent: 'center',
gap: spacing.sm,
},
mapPlaceholder: {
fontSize: 14,
color: colors.text,
fontWeight: '500',
},
pharmaciesSection: {
marginTop: spacing.sm,
padding: spacing.lg,
},
pharmaciesHeader: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: spacing.md,
},
sectionTitle: {
fontSize: 18,
fontWeight: '600',
color: colors.text,
marginBottom: spacing.md,
},
sortButton: {
flexDirection: 'row',
alignItems: 'center',
gap: spacing.xs,
paddingHorizontal: spacing.sm + 4,
paddingVertical: spacing.xs + 2,
borderRadius: borderRadius.full,
borderWidth: 1,
},
sortButtonActive: {},
sortButtonText: {
fontSize: 13,
fontWeight: '600',
},
sortButtonTextActive: {},
locationErrorContainer: {
flexDirection: 'row',
alignItems: 'center',
gap: spacing.sm,
padding: spacing.sm,
marginBottom: spacing.sm,
borderRadius: borderRadius.md,
},
locationErrorText: {
flex: 1,
fontSize: 13,
},
retryText: {
fontSize: 13,
fontWeight: '600',
},
noPharmacies: {
color: colors.textSecondary,
textAlign: 'center',
padding: spacing.xl,
},
pharmacyCard: {
backgroundColor: colors.card,
borderRadius: borderRadius.lg,
marginBottom: spacing.sm,
overflow: 'hidden',
@@ -195,14 +385,27 @@ const styles = StyleSheet.create({
pharmacyInfo: {
flex: 1,
},
pharmacyNameRow: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
pharmacyName: {
flex: 1,
fontSize: 16,
fontWeight: '600',
color: colors.text,
marginRight: spacing.sm,
},
pharmacyDistance: {
fontSize: 12,
fontWeight: '600',
paddingHorizontal: spacing.sm,
paddingVertical: 2,
borderRadius: borderRadius.full,
overflow: 'hidden',
},
pharmacyAddress: {
fontSize: 14,
color: colors.textSecondary,
marginTop: spacing.xs,
},
pharmacyStock: {
@@ -211,11 +414,9 @@ const styles = StyleSheet.create({
price: {
fontSize: 16,
fontWeight: '600',
color: colors.primary,
},
stock: {
fontSize: 12,
color: colors.textSecondary,
marginTop: spacing.xs,
},
directionsButton: {
@@ -225,10 +426,8 @@ const styles = StyleSheet.create({
gap: spacing.xs,
paddingVertical: spacing.sm,
borderTopWidth: 1,
borderTopColor: colors.border,
},
directionsText: {
color: colors.primary,
fontSize: 14,
fontWeight: '600',
},
@@ -239,6 +438,5 @@ const styles = StyleSheet.create({
},
errorText: {
fontSize: 16,
color: colors.textSecondary,
},
});
+21 -35
View File
@@ -5,12 +5,14 @@ import { Ionicons } from '@expo/vector-icons';
import MapView, { Marker } from 'react-native-maps';
import { getPharmacy, getPharmacyMedicines } from '../../services/pharmacies';
import { LoadingSpinner } from '../../components/LoadingSpinner';
import { colors, spacing, borderRadius } from '../../constants/theme';
import { useThemeContext } from '../../components/ThemeProvider';
import { spacing, borderRadius } from '../../constants/theme';
import { Pharmacy, PharmacyMedicine } from '../../types';
export default function PharmacyDetailScreen() {
const { id } = useLocalSearchParams<{ id: string }>();
const router = useRouter();
const { colors } = useThemeContext();
const [pharmacy, setPharmacy] = useState<Pharmacy | null>(null);
const [medicines, setMedicines] = useState<PharmacyMedicine[]>([]);
const [isLoading, setIsLoading] = useState(true);
@@ -55,40 +57,40 @@ export default function PharmacyDetailScreen() {
if (!pharmacy) {
return (
<View style={styles.errorContainer}>
<Text style={styles.errorText}>Farmacia no encontrada</Text>
<View style={[styles.errorContainer, { backgroundColor: colors.background }]}>
<Text style={[styles.errorText, { color: colors.textSecondary }]}>Farmacia no encontrada</Text>
</View>
);
}
return (
<ScrollView style={styles.container}>
<View style={styles.header}>
<Text style={styles.name}>{pharmacy.name}</Text>
<ScrollView style={[styles.container, { backgroundColor: colors.background }]}>
<View style={[styles.header, { backgroundColor: colors.card }]}>
<Text style={[styles.name, { color: colors.text }]}>{pharmacy.name}</Text>
</View>
<View style={styles.actionsRow}>
<View style={[styles.actionsRow, { backgroundColor: colors.card, borderBottomColor: colors.separator }]}>
<TouchableOpacity style={styles.actionButton} onPress={handleCall}>
<Ionicons name="call" size={20} color={colors.primary} />
<Text style={styles.actionText}>Llamar</Text>
<Text style={[styles.actionText, { color: colors.primary }]}>Llamar</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.actionButton} onPress={handleDirections}>
<Ionicons name="navigate" size={20} color={colors.primary} />
<Text style={styles.actionText}>Cómo llegar</Text>
<Text style={[styles.actionText, { color: colors.primary }]}>Cómo llegar</Text>
</TouchableOpacity>
</View>
<View style={styles.infoSection}>
<View style={[styles.infoSection, { backgroundColor: colors.card }]}>
<View style={styles.infoRow}>
<Ionicons name="location" size={18} color={colors.textSecondary} />
<Text style={styles.infoText}>{pharmacy.address}</Text>
<Text style={[styles.infoText, { color: colors.text }]}>{pharmacy.address}</Text>
</View>
{pharmacy.phone && (
<View style={styles.infoRow}>
<Ionicons name="call" size={18} color={colors.textSecondary} />
<Text style={styles.infoText}>{pharmacy.phone}</Text>
<Text style={[styles.infoText, { color: colors.text }]}>{pharmacy.phone}</Text>
</View>
)}
</View>
@@ -115,26 +117,26 @@ export default function PharmacyDetailScreen() {
</View>
<View style={styles.medicinesSection}>
<Text style={styles.sectionTitle}>
<Text style={[styles.sectionTitle, { color: colors.text }]}>
Medicamentos ({medicines.length})
</Text>
{medicines.length === 0 ? (
<Text style={styles.noMedicines}>No hay medicamentos disponibles</Text>
<Text style={[styles.noMedicines, { color: colors.textSecondary }]}>No hay medicamentos disponibles</Text>
) : (
medicines.map((med) => (
<TouchableOpacity
key={med.id}
style={styles.medicineCard}
style={[styles.medicineCard, { backgroundColor: colors.card }]}
onPress={() => router.push(`/medicine/${med.medicine_nregistro}`)}
>
<View style={styles.medicineInfo}>
<Text style={styles.medicineName}>{med.medicine_name}</Text>
<Text style={styles.medicineNregistro}>Reg: {med.medicine_nregistro}</Text>
<Text style={[styles.medicineName, { color: colors.text }]}>{med.medicine_name}</Text>
<Text style={[styles.medicineNregistro, { color: colors.textSecondary }]}>Reg: {med.medicine_nregistro}</Text>
</View>
<View style={styles.medicineStock}>
<Text style={styles.price}>{med.price.toFixed(2)} </Text>
<Text style={styles.stock}>Stock: {med.stock}</Text>
<Text style={[styles.price, { color: colors.primary }]}>{med.price.toFixed(2)} </Text>
<Text style={[styles.stock, { color: colors.textSecondary }]}>Stock: {med.stock}</Text>
</View>
</TouchableOpacity>
))
@@ -147,24 +149,19 @@ export default function PharmacyDetailScreen() {
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.background,
},
header: {
padding: spacing.md,
backgroundColor: colors.card,
},
name: {
fontSize: 22,
fontWeight: 'bold',
color: colors.text,
},
actionsRow: {
flexDirection: 'row',
justifyContent: 'space-around',
padding: spacing.md,
backgroundColor: colors.card,
borderBottomWidth: 1,
borderBottomColor: colors.separator,
},
actionButton: {
flexDirection: 'row',
@@ -173,12 +170,10 @@ const styles = StyleSheet.create({
},
actionText: {
marginLeft: spacing.xs,
color: colors.primary,
fontWeight: '500',
},
infoSection: {
padding: spacing.md,
backgroundColor: colors.card,
marginTop: spacing.sm,
},
infoRow: {
@@ -190,7 +185,6 @@ const styles = StyleSheet.create({
flex: 1,
marginLeft: spacing.sm,
fontSize: 16,
color: colors.text,
},
mapContainer: {
height: 200,
@@ -206,18 +200,15 @@ const styles = StyleSheet.create({
sectionTitle: {
fontSize: 18,
fontWeight: '600',
color: colors.text,
marginBottom: spacing.md,
},
noMedicines: {
color: colors.textSecondary,
textAlign: 'center',
padding: spacing.xl,
},
medicineCard: {
flexDirection: 'row',
justifyContent: 'space-between',
backgroundColor: colors.card,
borderRadius: borderRadius.md,
padding: spacing.md,
marginBottom: spacing.sm,
@@ -228,11 +219,9 @@ const styles = StyleSheet.create({
medicineName: {
fontSize: 16,
fontWeight: '500',
color: colors.text,
},
medicineNregistro: {
fontSize: 12,
color: colors.textSecondary,
marginTop: spacing.xs,
},
medicineStock: {
@@ -241,11 +230,9 @@ const styles = StyleSheet.create({
price: {
fontSize: 16,
fontWeight: '600',
color: colors.primary,
},
stock: {
fontSize: 12,
color: colors.textSecondary,
marginTop: spacing.xs,
},
errorContainer: {
@@ -255,6 +242,5 @@ const styles = StyleSheet.create({
},
errorText: {
fontSize: 16,
color: colors.textSecondary,
},
});