Mobile App design #26
@@ -1 +1 @@
|
||||
{"pid":864463,"startedAt":1783550197179}
|
||||
{"pid":10782,"startedAt":1783578681151}
|
||||
@@ -0,0 +1,141 @@
|
||||
# Plan: Dark Mode para FarmaFinder Mobile
|
||||
|
||||
## Objetivo
|
||||
Añadir soporte de modo oscuro a la app móvil con:
|
||||
- Detección automática del modo oscuro del sistema
|
||||
- Toggle manual en la pantalla de perfil (Configuración)
|
||||
- Persistencia de la preferencia del usuario
|
||||
|
||||
## Arquitectura
|
||||
|
||||
### 1. Theme Store (Zustand + AsyncStorage)
|
||||
**Nuevo archivo: `store/themeStore.ts`**
|
||||
|
||||
- Estado: `mode: 'light' | 'dark' | 'system'`
|
||||
- Persistencia con `@react-native-async-storage/async-storage`
|
||||
- Acciones: `setMode()`, `init()` (carga del storage al arrancar)
|
||||
- Por defecto: `'system'` (respeta el dispositivo)
|
||||
|
||||
### 2. Hook `useThemeColor`
|
||||
**Nuevo archivo: `hooks/useThemeColor.ts`**
|
||||
|
||||
- Usa `useColorScheme()` de React Native para detectar el color del sistema
|
||||
- Combina con el `mode` del themeStore para determinar el tema efectivo
|
||||
- Retorna el objeto `colors` apropiado (light o dark)
|
||||
- Los componentes consumirán este hook en vez de importar `colors` directamente
|
||||
|
||||
### 3. Paleta de colores oscura
|
||||
**Modificar: `constants/theme.ts`**
|
||||
|
||||
Añadir exportación `darkColors` con la paleta oscura:
|
||||
|
||||
| Token | Light (actual) | Dark (nuevo) |
|
||||
|---|---|---|
|
||||
| `background` | `#fbfbfb` | `#121212` |
|
||||
| `card` | `#ffffff` | `#1e1e1e` |
|
||||
| `surfaceLow` | `#f2f4f5` | `#2a2a2a` |
|
||||
| `surface` | `#eceeef` | `#333333` |
|
||||
| `surfaceHigh` | `#e6e8e9` | `#3a3a3a` |
|
||||
| `border` | `#c0c9bb` | `#3a3a3a` |
|
||||
| `separator` | `#c0c9bb` | `#3a3a3a` |
|
||||
| `text` | `#111417` | `#f0f0f0` |
|
||||
| `textSecondary` | `#41493e` | `#a0a0a0` |
|
||||
| `textInverse` | `#ffffff` | `#111417` |
|
||||
| `primaryContainer` | `#cfead0` | `#1a3a1c` |
|
||||
| `onPrimaryContainer` | `#0d2b12` | `#cfead0` |
|
||||
| `secondaryContainer` | `#dbe7ff` | `#1a2a4a` |
|
||||
| `tertiaryContainer` | `#efe7ff` | `#2a1a4a` |
|
||||
| `dangerContainer` | `#feecec` | `#3a1a1a` |
|
||||
| `accentWarm` | `#f5a97a` | `#f5a97a` (sin cambio) |
|
||||
| `primary`, `secondary`, `tertiary`, `scanButton`, `success`, `danger`, `warning` | (sin cambios) | (sin cambios) |
|
||||
|
||||
### 4. Provider wrapper
|
||||
**Nuevo archivo: `components/ThemeProvider.tsx`**
|
||||
|
||||
- Lee el `mode` del themeStore y el `useColorScheme()` del sistema
|
||||
- Calcula el tema efectivo (`light` o `dark`)
|
||||
- Provee `colors` y `isDark` vía React Context
|
||||
- Carga la preferencia guardada en AsyncStorage al montar
|
||||
|
||||
### 5. Integración en Root Layout
|
||||
**Modificar: `app/_layout.tsx`**
|
||||
|
||||
- Envolver toda la app con `<ThemeProvider>`
|
||||
- El `StatusBar` se ajusta: `style={isDark ? 'light' : 'auto'}`
|
||||
- Los colores del Stack header se leen del contexto
|
||||
|
||||
### 6. Toggle en el perfil
|
||||
**Modificar: `app/(tabs)/profile.tsx`**
|
||||
|
||||
Añadir en la pantalla de perfil (antes de "Configuración") un nuevo item de menú:
|
||||
- Icono: `moon-outline` / `sunny-outline` según el tema actual
|
||||
- Texto: "Modo de pantalla"
|
||||
- Al pulsar, mostrar un picker/modal con 3 opciones:
|
||||
- **Sistema** (icono: phone-portrait) - respeta el SO
|
||||
- **Claro** (icono: sunny) - fuerza light
|
||||
- **Oscuro** (icono: moon) - fuerza dark
|
||||
- El toggle se muestra inline (sin modal extra) tipo Segmented Control
|
||||
|
||||
### 7. Actualizar todos los screens y components
|
||||
|
||||
Cada archivo que importa `colors` debe cambiar a usar el hook `useThemeColor()`:
|
||||
|
||||
| Archivo | Cambio |
|
||||
|---|---|
|
||||
| `app/_layout.tsx` | Usa ThemeProvider + context para header colors |
|
||||
| `app/(tabs)/_layout.tsx` | Tab bar y header leen colors del context |
|
||||
| `app/(tabs)/index.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `app/(tabs)/search.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `app/(tabs)/scan.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `app/(tabs)/alerts.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `app/(tabs)/profile.tsx` | `const { colors, isDark } = useThemeColor()` |
|
||||
| `app/(tabs)/map.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `app/medicine/[id].tsx` | `const { colors } = useThemeColor()` |
|
||||
| `app/pharmacy/[id].tsx` | `const { colors } = useThemeColor()` |
|
||||
| `app/auth/login.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `app/auth/register.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `components/SearchBar.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `components/MedicineCard.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `components/LoadingSpinner.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `components/StockBadge.tsx` | Añade colores dark para badges |
|
||||
| `components/BarcodeScanner.tsx` | `const { colors } = useThemeColor()` |
|
||||
|
||||
**Nota sobre StyleSheet**: Los `StyleSheet.create()` se ejecutan una vez. Para que los estilos se actualicen con el tema, las propiedades que dependen de `colors` deben aplicarse vía `style` inline o moverse a funciones que retornen estilos dinámicos. La estrategia más limpia es:
|
||||
- Los colores de fondo/texto van como inline styles
|
||||
- Las estructuras (flex, padding, borderRadius) se quedan en `StyleSheet.create`
|
||||
|
||||
### 8. Colores hardcodeados
|
||||
Los siguientes archivos tienen colores inline hardcodeados que necesitan variante dark:
|
||||
|
||||
- **`StockBadge.tsx`**: `#eaf7ec`, `#fff3cd`, `#feecec` → añadir tokens al tema
|
||||
- **`search.tsx`**: suggestions con `#ffffff`, `#f0f7ff`, etc. → usar colores del tema
|
||||
- **`profile.tsx`**: feedback `#eaf7ec`, `#cfead0`, `#fecaca` → usar colores del tema
|
||||
- **`home/index.tsx`**: `rgba(255,255,255,0.2/0.3)` para iconos → ajustar opacidad
|
||||
|
||||
### 9. app.json
|
||||
**Modificar: `app.json`**
|
||||
|
||||
Cambiar `"userInterfaceStyle": "light"` → `"userInterfaceStyle": "automatic"`
|
||||
|
||||
## Orden de ejecución
|
||||
|
||||
1. `store/themeStore.ts` (nuevo)
|
||||
2. `hooks/useThemeColor.ts` (nuevo)
|
||||
3. `constants/theme.ts` (añadir `darkColors`)
|
||||
4. `components/ThemeProvider.tsx` (nuevo)
|
||||
5. `app/_layout.tsx` (envolver con ThemeProvider)
|
||||
6. `app/(tabs)/_layout.tsx` (colores dinámicos)
|
||||
7. `app/(tabs)/profile.tsx` (toggle de tema)
|
||||
8. Todos los screens y components (migrar a hook)
|
||||
9. `app.json` (userInterfaceStyle: automatic)
|
||||
10. Corregir colores hardcodeados
|
||||
|
||||
## Verificación
|
||||
|
||||
1. Ejecutar `npx expo start` y verificar que la app arranca sin errores
|
||||
2. Probar en iOS/Android: el tema respeta la configuración del sistema
|
||||
3. Ir a Perfil > Modo de pantalla y cambiar entre Claro/Oscuro/Sistema
|
||||
4. Verificar que el cambio es inmediato sin recargar la app
|
||||
5. Cerrar y reabrir la app → la preferencia persiste
|
||||
6. Verificar que todos los screens se ven bien en ambos modos (sin texto invisible, sin fondos transparentes)
|
||||
7. Probar tablets ( responsive)
|
||||
+20
-1
@@ -512,7 +512,8 @@ app.get('/api/medicines/:medicineId/pharmacies', async (req, res) => {
|
||||
try {
|
||||
const nregistro = req.params.medicineId; // Ahora es el nregistro de CIMA
|
||||
|
||||
const pharmacies = await userDbAll(`
|
||||
// First try to get pharmacies with specific medicine data
|
||||
let pharmacies = await userDbAll(`
|
||||
SELECT
|
||||
p.id,
|
||||
p.name,
|
||||
@@ -529,6 +530,24 @@ app.get('/api/medicines/:medicineId/pharmacies', async (req, res) => {
|
||||
ORDER BY p.name
|
||||
`, [nregistro]);
|
||||
|
||||
// If no specific links exist, return all pharmacies as potential sellers
|
||||
if (pharmacies.length === 0) {
|
||||
pharmacies = await userDbAll(`
|
||||
SELECT
|
||||
p.id,
|
||||
p.name,
|
||||
p.address,
|
||||
p.phone,
|
||||
p.latitude,
|
||||
p.longitude,
|
||||
p.opening_hours,
|
||||
NULL as price,
|
||||
0 as stock
|
||||
FROM pharmacies p
|
||||
ORDER BY p.name
|
||||
`);
|
||||
}
|
||||
|
||||
res.json(pharmacies);
|
||||
} catch (error) {
|
||||
console.error('Error fetching pharmacies:', error);
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"version": "1.0.0",
|
||||
"orientation": "portrait",
|
||||
"icon": "./assets/icon.png",
|
||||
"userInterfaceStyle": "light",
|
||||
"userInterfaceStyle": "automatic",
|
||||
"newArchEnabled": true,
|
||||
"splash": {
|
||||
"image": "./assets/splash.png",
|
||||
@@ -25,12 +25,29 @@
|
||||
"backgroundColor": "#007AFF"
|
||||
},
|
||||
"package": "com.farmafinder.app",
|
||||
"googleServicesFile": "./google-services.json"
|
||||
"googleServicesFile": "./google-services.json",
|
||||
"config": {
|
||||
"googleMaps": {
|
||||
"apiKey": ""
|
||||
}
|
||||
}
|
||||
},
|
||||
"plugins": [
|
||||
"expo-router",
|
||||
["expo-camera", {"cameraPermission": "Allow FarmaFinder to access your camera for scanning barcodes"}],
|
||||
["expo-notifications", {"icon": "./assets/notification-icon.png", "color": "#007AFF"}]
|
||||
["expo-notifications", {"icon": "./assets/notification-icon.png", "color": "#007AFF"}],
|
||||
[
|
||||
"react-native-maps",
|
||||
{
|
||||
"locationAlwaysAndWhenInUsePermission": "Allow FarmaFinder to use your location to find nearby pharmacies."
|
||||
}
|
||||
],
|
||||
[
|
||||
"expo-location",
|
||||
{
|
||||
"locationAlwaysAndWhenInUsePermission": "Allow FarmaFinder to use your location to find nearby pharmacies."
|
||||
}
|
||||
]
|
||||
],
|
||||
"scheme": "farmafinder",
|
||||
"extra": {
|
||||
|
||||
@@ -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',
|
||||
},
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -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',
|
||||
},
|
||||
});
|
||||
@@ -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',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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
@@ -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,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
});
|
||||
@@ -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>
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -2,7 +2,8 @@ import React, { useState } from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
|
||||
import { CameraView, useCameraPermissions } from 'expo-camera';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { colors, spacing, borderRadius } from '../constants/theme';
|
||||
import { useThemeContext } from './ThemeProvider';
|
||||
import { spacing, borderRadius } from '../constants/theme';
|
||||
|
||||
interface BarcodeScannerProps {
|
||||
onBarcodeScanned: (barcode: string) => void;
|
||||
@@ -12,6 +13,7 @@ interface BarcodeScannerProps {
|
||||
export function BarcodeScanner({ onBarcodeScanned, onClose }: BarcodeScannerProps) {
|
||||
const [permission, requestPermission] = useCameraPermissions();
|
||||
const [scanned, setScanned] = useState(false);
|
||||
const { colors } = useThemeContext();
|
||||
|
||||
if (!permission) {
|
||||
return <View style={styles.container} />;
|
||||
@@ -19,17 +21,17 @@ export function BarcodeScanner({ onBarcodeScanned, onClose }: BarcodeScannerProp
|
||||
|
||||
if (!permission.granted) {
|
||||
return (
|
||||
<View style={styles.permissionContainer}>
|
||||
<View style={[styles.permissionContainer, { backgroundColor: colors.background }]}>
|
||||
<Ionicons name="camera" size={64} color={colors.textSecondary} />
|
||||
<Text style={styles.permissionTitle}>Permiso de cámara requerido</Text>
|
||||
<Text style={styles.permissionText}>
|
||||
<Text style={[styles.permissionTitle, { color: colors.text }]}>Permiso de cámara requerido</Text>
|
||||
<Text style={[styles.permissionText, { color: colors.textSecondary }]}>
|
||||
Necesitamos acceso a la cámara para escanear códigos de barras
|
||||
</Text>
|
||||
<TouchableOpacity style={styles.permissionButton} onPress={requestPermission}>
|
||||
<TouchableOpacity style={[styles.permissionButton, { backgroundColor: colors.primary }]} onPress={requestPermission}>
|
||||
<Text style={styles.permissionButtonText}>Conceder permiso</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity style={styles.cancelButton} onPress={onClose}>
|
||||
<Text style={styles.cancelButtonText}>Cancelar</Text>
|
||||
<Text style={[styles.cancelButtonText, { color: colors.textSecondary }]}>Cancelar</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
);
|
||||
@@ -54,10 +56,10 @@ export function BarcodeScanner({ onBarcodeScanned, onClose }: BarcodeScannerProp
|
||||
|
||||
<View style={styles.overlay}>
|
||||
<View style={styles.scannerFrame}>
|
||||
<View style={[styles.corner, styles.topLeft]} />
|
||||
<View style={[styles.corner, styles.topRight]} />
|
||||
<View style={[styles.corner, styles.bottomLeft]} />
|
||||
<View style={[styles.corner, styles.bottomRight]} />
|
||||
<View style={[styles.corner, styles.topLeft, { borderColor: colors.primary }]} />
|
||||
<View style={[styles.corner, styles.topRight, { borderColor: colors.primary }]} />
|
||||
<View style={[styles.corner, styles.bottomLeft, { borderColor: colors.primary }]} />
|
||||
<View style={[styles.corner, styles.bottomRight, { borderColor: colors.primary }]} />
|
||||
</View>
|
||||
|
||||
<Text style={styles.instruction}>
|
||||
@@ -72,7 +74,7 @@ export function BarcodeScanner({ onBarcodeScanned, onClose }: BarcodeScannerProp
|
||||
{scanned && (
|
||||
<View style={styles.scannedOverlay}>
|
||||
<TouchableOpacity
|
||||
style={styles.scanAgainButton}
|
||||
style={[styles.scanAgainButton, { backgroundColor: colors.primary }]}
|
||||
onPress={() => setScanned(false)}
|
||||
>
|
||||
<Text style={styles.scanAgainText}>Escanear de nuevo</Text>
|
||||
@@ -92,30 +94,26 @@ const styles = StyleSheet.create({
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
backgroundColor: colors.background,
|
||||
padding: spacing.xl,
|
||||
},
|
||||
permissionTitle: {
|
||||
fontSize: 20,
|
||||
fontWeight: 'bold',
|
||||
color: colors.text,
|
||||
marginTop: spacing.lg,
|
||||
},
|
||||
permissionText: {
|
||||
fontSize: 16,
|
||||
color: colors.textSecondary,
|
||||
textAlign: 'center',
|
||||
marginTop: spacing.sm,
|
||||
marginBottom: spacing.xl,
|
||||
},
|
||||
permissionButton: {
|
||||
backgroundColor: colors.primary,
|
||||
borderRadius: borderRadius.md,
|
||||
paddingVertical: spacing.md,
|
||||
paddingHorizontal: spacing.xl,
|
||||
},
|
||||
permissionButtonText: {
|
||||
color: colors.textInverse,
|
||||
color: '#ffffff',
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
},
|
||||
@@ -123,7 +121,6 @@ const styles = StyleSheet.create({
|
||||
marginTop: spacing.md,
|
||||
},
|
||||
cancelButtonText: {
|
||||
color: colors.textSecondary,
|
||||
fontSize: 14,
|
||||
},
|
||||
overlay: {
|
||||
@@ -143,7 +140,6 @@ const styles = StyleSheet.create({
|
||||
position: 'absolute',
|
||||
width: 30,
|
||||
height: 30,
|
||||
borderColor: colors.primary,
|
||||
},
|
||||
topLeft: {
|
||||
top: 0,
|
||||
@@ -170,7 +166,7 @@ const styles = StyleSheet.create({
|
||||
borderRightWidth: 3,
|
||||
},
|
||||
instruction: {
|
||||
color: colors.textInverse,
|
||||
color: '#ffffff',
|
||||
fontSize: 14,
|
||||
textAlign: 'center',
|
||||
marginTop: spacing.xl,
|
||||
@@ -194,13 +190,12 @@ const styles = StyleSheet.create({
|
||||
right: spacing.xl,
|
||||
},
|
||||
scanAgainButton: {
|
||||
backgroundColor: colors.primary,
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
alignItems: 'center',
|
||||
},
|
||||
scanAgainText: {
|
||||
color: colors.textInverse,
|
||||
color: '#ffffff',
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
},
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
import React from 'react';
|
||||
import { View, ActivityIndicator, Text, StyleSheet } from 'react-native';
|
||||
import { colors, spacing } from '../constants/theme';
|
||||
import { useThemeContext } from './ThemeProvider';
|
||||
import { spacing } from '../constants/theme';
|
||||
|
||||
interface LoadingSpinnerProps {
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export function LoadingSpinner({ message = 'Cargando...' }: LoadingSpinnerProps) {
|
||||
const { colors } = useThemeContext();
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<ActivityIndicator size="large" color={colors.primary} />
|
||||
<Text style={styles.message}>{message}</Text>
|
||||
<Text style={[styles.message, { color: colors.textSecondary }]}>{message}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -25,6 +28,5 @@ const styles = StyleSheet.create({
|
||||
message: {
|
||||
marginTop: spacing.md,
|
||||
fontSize: 16,
|
||||
color: colors.textSecondary,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -2,7 +2,8 @@ import React from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity, useWindowDimensions } from 'react-native';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { colors, spacing, borderRadius } from '../constants/theme';
|
||||
import { useThemeContext } from './ThemeProvider';
|
||||
import { spacing, borderRadius } from '../constants/theme';
|
||||
import { StockBadge } from './StockBadge';
|
||||
import { Medicine } from '../types';
|
||||
|
||||
@@ -16,6 +17,7 @@ export function MedicineCard({ medicine }: MedicineCardProps) {
|
||||
const router = useRouter();
|
||||
const { width } = useWindowDimensions();
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
const { colors } = useThemeContext();
|
||||
|
||||
const handlePress = () => {
|
||||
router.push(`/medicine/${medicine.nregistro}`);
|
||||
@@ -23,32 +25,32 @@ export function MedicineCard({ medicine }: MedicineCardProps) {
|
||||
|
||||
return (
|
||||
<TouchableOpacity
|
||||
style={[styles.card, isTablet && styles.cardTablet]}
|
||||
style={[styles.card, isTablet && styles.cardTablet, { backgroundColor: colors.card }]}
|
||||
onPress={handlePress}
|
||||
activeOpacity={0.7}
|
||||
>
|
||||
<View style={styles.header}>
|
||||
<Text style={[styles.name, isTablet && styles.nameTablet]} numberOfLines={2}>
|
||||
<Text style={[styles.name, isTablet && styles.nameTablet, { color: colors.text }]} numberOfLines={2}>
|
||||
{medicine.name}
|
||||
</Text>
|
||||
{medicine.stock != null && <StockBadge stock={medicine.stock} />}
|
||||
</View>
|
||||
|
||||
<Text style={styles.principioActivo} numberOfLines={1}>
|
||||
<Text style={[styles.principioActivo, { color: colors.textSecondary }]} numberOfLines={1}>
|
||||
{medicine.active_ingredient}{medicine.dosage ? ` - ${medicine.dosage}` : ''}
|
||||
</Text>
|
||||
|
||||
<View style={styles.footer}>
|
||||
<View style={styles.priceContainer}>
|
||||
<Ionicons name="pricetag" size={14} color={colors.textSecondary} />
|
||||
<Text style={[styles.price, isTablet && styles.priceTablet]}>
|
||||
<Text style={[styles.price, isTablet && styles.priceTablet, { color: colors.primary }]}>
|
||||
{medicine.precio != null ? `${medicine.precio.toFixed(2)} €` : 'Sin precio'}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<View style={styles.labContainer}>
|
||||
<Ionicons name="business" size={14} color={colors.textSecondary} />
|
||||
<Text style={[styles.laboratorio, isTablet && styles.laboratorioTablet]} numberOfLines={1}>
|
||||
<Text style={[styles.laboratorio, isTablet && styles.laboratorioTablet, { color: colors.textSecondary }]} numberOfLines={1}>
|
||||
{medicine.laboratory}
|
||||
</Text>
|
||||
</View>
|
||||
@@ -59,7 +61,6 @@ export function MedicineCard({ medicine }: MedicineCardProps) {
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
card: {
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.lg,
|
||||
padding: spacing.md,
|
||||
marginHorizontal: spacing.lg,
|
||||
@@ -86,7 +87,6 @@ const styles = StyleSheet.create({
|
||||
flex: 1,
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: colors.text,
|
||||
marginRight: spacing.sm,
|
||||
},
|
||||
nameTablet: {
|
||||
@@ -94,7 +94,6 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
principioActivo: {
|
||||
fontSize: 14,
|
||||
color: colors.textSecondary,
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
footer: {
|
||||
@@ -109,7 +108,6 @@ const styles = StyleSheet.create({
|
||||
price: {
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
color: colors.primary,
|
||||
marginLeft: spacing.xs,
|
||||
},
|
||||
priceTablet: {
|
||||
@@ -123,7 +121,6 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
laboratorio: {
|
||||
fontSize: 12,
|
||||
color: colors.textSecondary,
|
||||
marginLeft: spacing.xs,
|
||||
maxWidth: 120,
|
||||
},
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import React, { useState } from 'react';
|
||||
import { View, TextInput, StyleSheet, TouchableOpacity, useWindowDimensions } from 'react-native';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { colors, spacing, borderRadius } from '../constants/theme';
|
||||
import { useThemeContext } from './ThemeProvider';
|
||||
import { spacing, borderRadius } from '../constants/theme';
|
||||
|
||||
const TABLET_MIN_WIDTH = 768;
|
||||
|
||||
@@ -20,6 +21,7 @@ export function SearchBar({
|
||||
}: SearchBarProps) {
|
||||
const { width } = useWindowDimensions();
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
const { colors } = useThemeContext();
|
||||
const [localValue, setLocalValue] = useState(value || '');
|
||||
|
||||
const handleChange = (text: string) => {
|
||||
@@ -38,10 +40,10 @@ export function SearchBar({
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={[styles.container, isTablet && styles.containerTablet]}>
|
||||
<View style={[styles.container, isTablet && styles.containerTablet, { backgroundColor: colors.card }]}>
|
||||
<Ionicons name="search" size={20} color={colors.textSecondary} style={styles.icon} />
|
||||
<TextInput
|
||||
style={[styles.input, isTablet && styles.inputTablet]}
|
||||
style={[styles.input, isTablet && styles.inputTablet, { color: colors.text }]}
|
||||
placeholder={placeholder}
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
value={localValue}
|
||||
@@ -63,15 +65,12 @@ const styles = StyleSheet.create({
|
||||
container: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.lg,
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: spacing.sm + 2,
|
||||
marginHorizontal: spacing.lg,
|
||||
marginVertical: spacing.sm,
|
||||
maxWidth: 420,
|
||||
alignSelf: 'center',
|
||||
width: '100%',
|
||||
width: '80%',
|
||||
shadowColor: '#000',
|
||||
shadowOffset: { width: 0, height: 2 },
|
||||
shadowOpacity: 0.06,
|
||||
@@ -88,7 +87,6 @@ const styles = StyleSheet.create({
|
||||
input: {
|
||||
flex: 1,
|
||||
fontSize: 16,
|
||||
color: colors.text,
|
||||
paddingVertical: spacing.xs,
|
||||
},
|
||||
inputTablet: {
|
||||
|
||||
@@ -1,27 +1,32 @@
|
||||
import React from 'react';
|
||||
import { View, Text, StyleSheet } from 'react-native';
|
||||
import { colors, borderRadius, spacing } from '../constants/theme';
|
||||
import { useThemeContext } from './ThemeProvider';
|
||||
import { borderRadius, spacing } from '../constants/theme';
|
||||
|
||||
interface StockBadgeProps {
|
||||
stock: number;
|
||||
}
|
||||
|
||||
export function StockBadge({ stock }: StockBadgeProps) {
|
||||
const getBadgeStyle = () => {
|
||||
if (stock === 0) return styles.danger;
|
||||
if (stock < 5) return styles.warning;
|
||||
return styles.success;
|
||||
const { colors, isDark } = useThemeContext();
|
||||
|
||||
const getBadgeColors = () => {
|
||||
if (stock === 0) {
|
||||
return { bg: isDark ? '#3a1a1a' : '#feecec', text: isDark ? '#ef9a9a' : '#b91c1c' };
|
||||
}
|
||||
if (stock < 5) {
|
||||
return { bg: isDark ? '#3a3010' : '#fff3cd', text: isDark ? '#ffd54f' : '#FF9500' };
|
||||
}
|
||||
return { bg: isDark ? '#1a3a1c' : '#eaf7ec', text: isDark ? '#81c784' : '#34C759' };
|
||||
};
|
||||
|
||||
const getText = () => {
|
||||
if (stock === 0) return 'Sin stock';
|
||||
if (stock < 5) return `Bajo (${stock})`;
|
||||
return `Disponible (${stock})`;
|
||||
};
|
||||
const badgeColors = getBadgeColors();
|
||||
|
||||
return (
|
||||
<View style={[styles.badge, getBadgeStyle()]}>
|
||||
<Text style={styles.text}>{getText()}</Text>
|
||||
<View style={[styles.badge, { backgroundColor: badgeColors.bg }]}>
|
||||
<Text style={[styles.text, { color: badgeColors.text }]}>
|
||||
{stock === 0 ? 'Sin stock' : stock < 5 ? `Bajo (${stock})` : `Disponible (${stock})`}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -32,15 +37,6 @@ const styles = StyleSheet.create({
|
||||
paddingVertical: spacing.xs,
|
||||
borderRadius: borderRadius.sm,
|
||||
},
|
||||
success: {
|
||||
backgroundColor: '#eaf7ec',
|
||||
},
|
||||
warning: {
|
||||
backgroundColor: '#fff3cd',
|
||||
},
|
||||
danger: {
|
||||
backgroundColor: '#feecec',
|
||||
},
|
||||
text: {
|
||||
fontSize: 12,
|
||||
fontWeight: '600',
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import React, { createContext, useContext, useEffect, useMemo } from 'react';
|
||||
import { useColorScheme } from 'react-native';
|
||||
import { useThemeStore } from '../store/themeStore';
|
||||
import { colors, darkColors } from '../constants/theme';
|
||||
import type { AppColors } from '../hooks/useThemeColor';
|
||||
|
||||
interface ThemeContextValue {
|
||||
colors: AppColors;
|
||||
isDark: boolean;
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextValue>({
|
||||
colors,
|
||||
isDark: false,
|
||||
});
|
||||
|
||||
export function useThemeContext() {
|
||||
return useContext(ThemeContext);
|
||||
}
|
||||
|
||||
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||
const systemScheme = useColorScheme();
|
||||
const mode = useThemeStore((s) => s.mode);
|
||||
const init = useThemeStore((s) => s.init);
|
||||
|
||||
useEffect(() => {
|
||||
init();
|
||||
}, []);
|
||||
|
||||
const value = useMemo(() => {
|
||||
const isDark = mode === 'dark' || (mode === 'system' && systemScheme === 'dark');
|
||||
return {
|
||||
colors: isDark ? darkColors : colors,
|
||||
isDark,
|
||||
};
|
||||
}, [mode, systemScheme]);
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={value}>
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -44,6 +44,52 @@ export const colors = {
|
||||
accentWarm: '#f5a97a',
|
||||
};
|
||||
|
||||
export const darkColors = {
|
||||
// Primary - pastel green pharmacy palette
|
||||
primary: '#7fbf8f',
|
||||
primaryLight: '#2a5a35',
|
||||
primaryDark: '#cfead0',
|
||||
onPrimary: '#cfead0',
|
||||
primaryContainer: '#1a3a1c',
|
||||
onPrimaryContainer: '#cfead0',
|
||||
|
||||
// Secondary - soft blue
|
||||
secondary: '#a3b8ff',
|
||||
secondaryContainer: '#1a2a4a',
|
||||
|
||||
// Tertiary - soft lavender
|
||||
tertiary: '#c9b3ff',
|
||||
tertiaryContainer: '#2a1a4a',
|
||||
|
||||
// Scan button - vivid blue
|
||||
scanButton: '#4a7dd5',
|
||||
scanButtonShadow: 'rgba(74, 125, 213, 0.32)',
|
||||
|
||||
// Semantic
|
||||
success: '#34C759',
|
||||
danger: '#ef5350',
|
||||
dangerContainer: '#3a1a1a',
|
||||
warning: '#FF9500',
|
||||
|
||||
// Surface
|
||||
background: '#121212',
|
||||
card: '#1e1e1e',
|
||||
surfaceLow: '#2a2a2a',
|
||||
surface: '#333333',
|
||||
surfaceHigh: '#3a3a3a',
|
||||
border: '#3a3a3a',
|
||||
separator: '#3a3a3a',
|
||||
|
||||
// Text
|
||||
text: '#f0f0f0',
|
||||
textSecondary: '#a0a0a0',
|
||||
textInverse: '#111417',
|
||||
textLink: '#7fbf8f',
|
||||
|
||||
// Accent
|
||||
accentWarm: '#f5a97a',
|
||||
};
|
||||
|
||||
export const spacing = {
|
||||
xs: 4,
|
||||
sm: 8,
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
|
||||
const STORAGE_KEY = 'recent_medicine_searches';
|
||||
const MAX_ITEMS = 5;
|
||||
|
||||
export function useRecentSearches() {
|
||||
const [recentSearches, setRecentSearches] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
AsyncStorage.getItem(STORAGE_KEY).then((data) => {
|
||||
if (data) setRecentSearches(JSON.parse(data));
|
||||
});
|
||||
}, []);
|
||||
|
||||
const addSearch = useCallback(async (query: string) => {
|
||||
const trimmed = query.trim();
|
||||
if (!trimmed) return;
|
||||
setRecentSearches((prev) => {
|
||||
const filtered = prev.filter((s) => s !== trimmed);
|
||||
const next = [trimmed, ...filtered].slice(0, MAX_ITEMS);
|
||||
AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const removeSearch = useCallback(async (query: string) => {
|
||||
setRecentSearches((prev) => {
|
||||
const next = prev.filter((s) => s !== query);
|
||||
AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const clearAll = useCallback(async () => {
|
||||
setRecentSearches([]);
|
||||
AsyncStorage.removeItem(STORAGE_KEY);
|
||||
}, []);
|
||||
|
||||
return { recentSearches, addSearch, removeSearch, clearAll };
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useColorScheme } from 'react-native';
|
||||
import { colors, darkColors } from '../constants/theme';
|
||||
import { useThemeStore, ThemeMode } from '../store/themeStore';
|
||||
|
||||
export type AppColors = typeof colors;
|
||||
|
||||
export function useThemeColor(): { colors: AppColors; isDark: boolean; mode: ThemeMode } {
|
||||
const systemScheme = useColorScheme();
|
||||
const mode = useThemeStore((s) => s.mode);
|
||||
|
||||
const isDark =
|
||||
mode === 'dark' || (mode === 'system' && systemScheme === 'dark');
|
||||
|
||||
return {
|
||||
colors: isDark ? darkColors : colors,
|
||||
isDark,
|
||||
mode,
|
||||
};
|
||||
}
|
||||
@@ -16,6 +16,7 @@
|
||||
"expo-image-picker": "~57.0.2",
|
||||
"expo-linking": "~57.0.1",
|
||||
"expo-local-authentication": "~57.0.0",
|
||||
"expo-location": "~57.0.2",
|
||||
"expo-notifications": "~57.0.3",
|
||||
"expo-router": "~57.0.3",
|
||||
"expo-secure-store": "~57.0.0",
|
||||
|
||||
@@ -2,32 +2,43 @@ import axios from 'axios';
|
||||
import * as SecureStore from 'expo-secure-store';
|
||||
import { config } from '../constants/config';
|
||||
|
||||
const SESSION_KEY = 'session_id';
|
||||
|
||||
export const api = axios.create({
|
||||
baseURL: config.API_BASE_URL,
|
||||
timeout: 10000,
|
||||
withCredentials: true,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
// Request interceptor - add auth token
|
||||
// Request interceptor - restore session cookie from SecureStore
|
||||
api.interceptors.request.use(
|
||||
async (axiosConfig) => {
|
||||
const token = await SecureStore.getItemAsync('auth_token');
|
||||
if (token) {
|
||||
axiosConfig.headers.Authorization = `Bearer ${token}`;
|
||||
const session = await SecureStore.getItemAsync(SESSION_KEY);
|
||||
if (session) {
|
||||
axiosConfig.headers.Cookie = session;
|
||||
}
|
||||
return axiosConfig;
|
||||
},
|
||||
(error) => Promise.reject(error)
|
||||
);
|
||||
|
||||
// Response interceptor - handle errors
|
||||
// Response interceptor - capture and persist session cookie from responses
|
||||
api.interceptors.response.use(
|
||||
(response) => response,
|
||||
(response) => {
|
||||
const setCookie = response.headers['set-cookie'];
|
||||
if (setCookie) {
|
||||
const cookieStr = Array.isArray(setCookie) ? setCookie[0] : setCookie;
|
||||
const sessionId = cookieStr.split(';')[0];
|
||||
SecureStore.setItemAsync(SESSION_KEY, sessionId);
|
||||
}
|
||||
return response;
|
||||
},
|
||||
async (error) => {
|
||||
if (error.response?.status === 401) {
|
||||
await SecureStore.deleteItemAsync('auth_token');
|
||||
await SecureStore.deleteItemAsync(SESSION_KEY);
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
@@ -2,42 +2,44 @@ import api from './api';
|
||||
import * as SecureStore from 'expo-secure-store';
|
||||
import { AuthResponse, User } from '../types';
|
||||
|
||||
const USER_KEY = 'user_data';
|
||||
|
||||
export async function login(username: string, password: string): Promise<AuthResponse> {
|
||||
const response = await api.post('/auth/login', { username, password });
|
||||
const { user, token } = response.data;
|
||||
const { user } = response.data;
|
||||
|
||||
await SecureStore.setItemAsync('auth_token', token);
|
||||
await SecureStore.setItemAsync('user', JSON.stringify(user));
|
||||
await SecureStore.setItemAsync(USER_KEY, JSON.stringify(user));
|
||||
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function logout(): Promise<void> {
|
||||
await api.post('/auth/logout');
|
||||
await SecureStore.deleteItemAsync('auth_token');
|
||||
await SecureStore.deleteItemAsync('user');
|
||||
await SecureStore.deleteItemAsync(USER_KEY);
|
||||
}
|
||||
|
||||
export async function checkAuth(): Promise<User | null> {
|
||||
try {
|
||||
const response = await api.get('/auth/check');
|
||||
return response.data.user;
|
||||
if (response.data.authenticated) {
|
||||
return response.data.user;
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getStoredUser(): Promise<User | null> {
|
||||
const userStr = await SecureStore.getItemAsync('user');
|
||||
const userStr = await SecureStore.getItemAsync(USER_KEY);
|
||||
return userStr ? JSON.parse(userStr) : null;
|
||||
}
|
||||
|
||||
export async function register(username: string, password: string): Promise<AuthResponse> {
|
||||
const response = await api.post('/auth/register', { username, password });
|
||||
const { user, token } = response.data;
|
||||
const { user } = response.data;
|
||||
|
||||
await SecureStore.setItemAsync('auth_token', token);
|
||||
await SecureStore.setItemAsync('user', JSON.stringify(user));
|
||||
await SecureStore.setItemAsync(USER_KEY, JSON.stringify(user));
|
||||
|
||||
return response.data;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { create } from 'zustand';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
|
||||
export type ThemeMode = 'light' | 'dark' | 'system';
|
||||
|
||||
interface ThemeState {
|
||||
mode: ThemeMode;
|
||||
setMode: (mode: ThemeMode) => Promise<void>;
|
||||
init: () => Promise<void>;
|
||||
}
|
||||
|
||||
const STORAGE_KEY = '@theme_mode';
|
||||
|
||||
export const useThemeStore = create<ThemeState>((set) => ({
|
||||
mode: 'system',
|
||||
|
||||
setMode: async (mode: ThemeMode) => {
|
||||
set({ mode });
|
||||
await AsyncStorage.setItem(STORAGE_KEY, mode);
|
||||
},
|
||||
|
||||
init: async () => {
|
||||
try {
|
||||
const saved = await AsyncStorage.getItem(STORAGE_KEY);
|
||||
if (saved === 'light' || saved === 'dark' || saved === 'system') {
|
||||
set({ mode: saved });
|
||||
}
|
||||
} catch {}
|
||||
},
|
||||
}));
|
||||
@@ -24,15 +24,22 @@ export interface Pharmacy {
|
||||
phone: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
opening_hours?: string;
|
||||
}
|
||||
|
||||
export interface PharmacyMedicine {
|
||||
id: number;
|
||||
pharmacy_id: number;
|
||||
medicine_nregistro: string;
|
||||
medicine_name: string;
|
||||
price: number;
|
||||
stock: number;
|
||||
pharmacy_id?: number;
|
||||
medicine_nregistro?: string;
|
||||
medicine_name?: string;
|
||||
name?: string;
|
||||
address?: string;
|
||||
phone?: string;
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
opening_hours?: string;
|
||||
price?: number | null;
|
||||
stock?: number;
|
||||
pharmacy?: Pharmacy;
|
||||
}
|
||||
|
||||
|
||||
Generated
+13
@@ -111,6 +111,7 @@
|
||||
"expo-image-picker": "~57.0.2",
|
||||
"expo-linking": "~57.0.1",
|
||||
"expo-local-authentication": "~57.0.0",
|
||||
"expo-location": "~57.0.2",
|
||||
"expo-notifications": "~57.0.3",
|
||||
"expo-router": "~57.0.3",
|
||||
"expo-secure-store": "~57.0.0",
|
||||
@@ -792,6 +793,18 @@
|
||||
"expo": "*"
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/expo-location": {
|
||||
"version": "57.0.2",
|
||||
"resolved": "https://registry.npmjs.org/expo-location/-/expo-location-57.0.2.tgz",
|
||||
"integrity": "sha512-yyize0BsBfZjgelBQdhWFH2JUh9OLJOUt7fxz73Y70nbRV2rXZ7A9r0J6jfAa9lXqH7y/GDsFLqecfTc/PcFUQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@expo/image-utils": "^0.11.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"expo": "*"
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/expo-manifests": {
|
||||
"version": "57.0.0",
|
||||
"resolved": "https://registry.npmjs.org/expo-manifests/-/expo-manifests-57.0.0.tgz",
|
||||
|
||||
Reference in New Issue
Block a user