10 Commits

Author SHA1 Message Date
Antoni Nuñez Romeu 71a349e54b fix: add missing asset files (adaptive-icon, splash, notification-icon)
Run Tests on Branches / Backend Tests (push) Successful in 3m32s
Run Tests on Branches / Frontend Tests (push) Successful in 3m27s
2026-07-06 13:12:29 +02:00
Antoni Nuñez Romeu cea2c98c82 fix: update react version to resolve peer dependency conflict 2026-07-06 13:02:52 +02:00
Antoni Nuñez Romeu f6ddf30bda docs: add production deployment guide for mobile app 2026-07-06 12:54:55 +02:00
Antoni Nuñez Romeu c4fd5bfc77 feat: configure EAS Build for production and add env example 2026-07-06 12:09:41 +02:00
Antoni Nuñez Romeu 454da1416d docs: update README with React Native mobile app documentation 2026-07-06 11:42:14 +02:00
Antoni Nuñez Romeu 4afffe46f0 feat: add biometric authentication support 2026-07-06 11:36:01 +02:00
Antoni Nuñez Romeu d22f1b5646 feat: add barcode scanner for medicine lookup 2026-07-06 11:33:09 +02:00
Antoni Nuñez Romeu 205af1a795 feat: add push notifications support 2026-07-06 11:29:25 +02:00
Antoni Nuñez Romeu b4c572ce17 feat: configure EAS Build and add mobile scripts 2026-07-06 11:25:20 +02:00
Antoni Nuñez Romeu c02abe077a feat: add auth check on app startup 2026-07-06 11:23:20 +02:00
18 changed files with 1640 additions and 610 deletions
+273 -6
View File
@@ -4,6 +4,7 @@ A web application to search for medicines from the official Spanish CIMA databas
## ✨ Features ## ✨ Features
### Web App (Desktop/PWA)
- 🔍 **Real-time medicine search** from CIMA API (Agencia Española de Medicamentos) - 🔍 **Real-time medicine search** from CIMA API (Agencia Española de Medicamentos)
- 💾 **Redis caching** for improved performance - 💾 **Redis caching** for improved performance
- 📍 View pharmacies that sell a specific medicine - 📍 View pharmacies that sell a specific medicine
@@ -15,14 +16,38 @@ A web application to search for medicines from the official Spanish CIMA databas
- Search medicines from CIMA database - Search medicines from CIMA database
- Link medicines to pharmacies with prices and stock - Link medicines to pharmacies with prices and stock
### Mobile App (React Native)
- 📱 **Native iOS/Android** experience with Expo
- 🔍 **Medicine search** with real-time results
- 🗺️ **Interactive map** with pharmacy markers
- 📷 **Barcode scanner** for quick medicine lookup
- 🔔 **Push notifications** for availability alerts
- 🔐 **Biometric authentication** (Face ID / Touch ID)
- 💾 **Offline cache** for favorite medicines
## 🛠️ Tech Stack ## 🛠️ Tech Stack
- **Frontend**: React + Vite ### Backend
- **Backend**: Node.js + Express - **Runtime**: Node.js + Express
- **Database**: SQLite (for pharmacies and relationships) - **Database**: SQLite (for pharmacies and relationships)
- **Cache**: Redis - **Cache**: Redis
- **External API**: CIMA (Centro de Información online de Medicamentos de la AEMPS) - **External API**: CIMA (Centro de Información online de Medicamentos de la AEMPS)
### Frontend (Web/PWA)
- **Framework**: React + Vite
- **Mobile wrapper**: Capacitor (for hybrid mobile builds)
### Frontend (Mobile - React Native)
- **Framework**: Expo SDK 57 + React Native
- **Navigation**: Expo Router v4
- **State**: Zustand
- **HTTP**: Axios + TanStack Query
- **Maps**: react-native-maps
- **Camera**: expo-camera (barcode scanning)
- **Auth**: expo-local-authentication (biometrics)
- **Notifications**: expo-notifications
- **Build**: EAS Build
## 📋 Prerequisites ## 📋 Prerequisites
- Node.js (v18 or higher) - Node.js (v18 or higher)
@@ -200,7 +225,7 @@ FarmaFinder/
│ ├── create-admin.js # Admin user creation script │ ├── create-admin.js # Admin user creation script
│ ├── .env.example # Environment variable template │ ├── .env.example # Environment variable template
│ └── package.json │ └── package.json
├── frontend/ ├── frontend/ # React + Vite (Desktop/PWA)
│ ├── Dockerfile │ ├── Dockerfile
│ ├── nginx.conf # Nginx config (Docker): serves SPA + proxies /api │ ├── nginx.conf # Nginx config (Docker): serves SPA + proxies /api
│ ├── src/ │ ├── src/
@@ -213,6 +238,27 @@ FarmaFinder/
│ │ └── main.jsx # Entry point │ │ └── main.jsx # Entry point
│ ├── index.html │ ├── index.html
│ └── package.json │ └── package.json
├── frontend-mobile/ # Expo + React Native (iOS/Android)
│ ├── app/
│ │ ├── _layout.tsx # Root layout with providers
│ │ ├── (tabs)/ # Bottom tab navigation
│ │ │ ├── index.tsx # Home (medicine search)
│ │ │ ├── map.tsx # Pharmacy map
│ │ │ └── profile.tsx # User profile
│ │ ├── medicine/[id].tsx # Medicine detail
│ │ ├── pharmacy/[id].tsx # Pharmacy detail
│ │ ├── auth/ # Login/Register screens
│ │ └── scanner.tsx # Barcode scanner
│ ├── components/ # Reusable UI components
│ ├── services/ # API and business logic
│ ├── store/ # Zustand state management
│ ├── hooks/ # Custom React hooks
│ ├── constants/ # Theme and config
│ ├── types/ # TypeScript types
│ ├── eas.json # EAS Build configuration
│ └── package.json
├── android/ # Capacitor Android project
├── ios/ # Capacitor iOS project
└── README.md └── README.md
``` ```
@@ -289,6 +335,194 @@ The application now uses the **CIMA (Centro de Información online de Medicament
- Results are cached in Redis for performance - Results are cached in Redis for performance
- `pharmacy_medicines` now uses `medicine_nregistro` (CIMA registration number) instead of local `medicine_id` - `pharmacy_medicines` now uses `medicine_nregistro` (CIMA registration number) instead of local `medicine_id`
## 📱 Mobile App Setup (React Native)
### Prerequisites
- Node.js (v18 or higher)
- npm or yarn
- **Expo CLI**: `npm install -g expo-cli`
- **EAS CLI**: `npm install -g eas-cli`
- **iOS**: Xcode (Mac only) + CocoaPods
- **Android**: Android Studio + Android SDK
### Quick Start
```bash
# Install all dependencies (backend + web + mobile)
npm run install:all
# Start mobile development server
npm run dev:mobile
# Scan QR code with Expo Go app (iOS/Android)
```
### Development Build
For native features (camera, biometrics, notifications), use a development build:
```bash
# Install EAS CLI
npm install -g eas-cli
# Login to Expo
eas login
# Create development build
eas build --profile development --platform ios
eas build --profile development --platform android
```
### Project Structure
```
frontend-mobile/
├── app/ # Expo Router screens
│ ├── (tabs)/ # Bottom tab navigation
│ ├── auth/ # Login/Register
│ ├── medicine/ # Medicine detail
│ ├── pharmacy/ # Pharmacy detail
│ └── scanner.tsx # Barcode scanner
├── components/ # Reusable UI components
├── services/ # API and business logic
├── store/ # Zustand state management
├── hooks/ # Custom React hooks
├── constants/ # Theme and config
└── types/ # TypeScript types
```
### Native Features
| Feature | Implementation |
|---------|---------------|
| Barcode Scanner | `expo-camera` with `CameraView` |
| Push Notifications | `expo-notifications` |
| Biometrics | `expo-local-authentication` |
| Maps | `react-native-maps` |
| Secure Storage | `expo-secure-store` |
### EAS Build Profiles
| Profile | Platform | Build Type | Use Case |
|---------|----------|------------|----------|
| `development` | iOS | Simulator | Local testing on Mac |
| `development` | Android | APK | Local testing on device |
| `preview` | Android | APK | Internal testing & sharing |
| `production` | Android | AAB | Google Play Store submission |
**Note:** iOS builds require Apple Developer account ($99/year) and are configured separately.
### Environment Configuration
The mobile app uses the same backend API as the web app. Configure the API URL in:
```typescript
// frontend-mobile/constants/config.ts
const ENV = {
development: {
API_BASE_URL: 'http://localhost:3001/api',
},
production: {
API_BASE_URL: 'https://your-production-api.com/api',
},
};
```
## 🚀 Production Deployment (Mobile)
### Distribution Flow
```
Development → EAS Build → App Store / Google Play → User Device
```
The mobile app is a **native application** that runs directly on the device. No Docker or server needed - users download it from the app stores.
### Step 1: Setup Expo Account
```bash
# Install EAS CLI
npm install -g eas-cli
# Create account at https://expo.dev
# Login
eas login
```
### Step 2: Initialize EAS Project
```bash
cd frontend-mobile
eas init
```
This generates a `projectId` - add it to `app.json`:
```json
"extra": {
"eas": {
"projectId": "your-project-id"
}
}
```
### Step 3: Configure Credentials
**Android (Google Play):**
1. Create developer account ($25 one-time fee)
2. Create project in Google Cloud Console
3. Enable Play Developer API
4. Download `google-service-account.json`
5. Place in `frontend-mobile/` directory
**iOS (App Store):**
1. Join Apple Developer Program ($99/year)
2. Create App ID in Apple Developer portal
3. Generate certificates and provisioning profiles
4. Update `eas.json` with your credentials
### Step 4: Build for Production
```bash
# Android (Google Play)
eas build --profile production --platform android
# iOS (App Store)
eas build --profile production --platform ios
```
### Step 5: Submit to Stores
```bash
# Submit to Google Play
eas submit --profile production --platform android
# Submit to App Store
eas submit --profile production --platform ios
```
### OTA Updates (Without App Store Review)
Push updates directly to users without going through store review:
```bash
# Install expo-updates
npx expo install expo-updates
# Send update
eas update --branch production --message "Fix: improved search"
```
### Useful Commands
| Command | Description |
|---------|-------------|
| `eas build:list` | View previous builds |
| `eas build:cancel <id>` | Cancel a build |
| `eas submit:list` | View previous submissions |
| `eas update` | Send OTA update |
## 🐛 Troubleshooting ## 🐛 Troubleshooting
### Redis Connection Issues ### Redis Connection Issues
@@ -321,19 +555,52 @@ npm run create-admin
## 📝 Development ## 📝 Development
**Backend development with auto-reload:** ### Backend
**Start with auto-reload:**
```bash ```bash
cd backend cd backend
npm run dev npm run dev
``` ```
**Frontend development:** ### Frontend (Web/PWA)
**Start development server:**
```bash ```bash
cd frontend cd frontend
npm run dev npm run dev
``` ```
**Clear Redis cache:** ### Frontend (Mobile - React Native)
**Install all dependencies:**
```bash
npm run install:all
```
**Start Expo dev server:**
```bash
npm run dev:mobile
```
**Start for specific platform:**
```bash
npm run dev:mobile:android # Android emulator
npm run dev:mobile:ios # iOS simulator
```
**Build with EAS:**
```bash
npm run build:mobile # Production build
```
**Submit to stores:**
```bash
npm run submit:android # Google Play
npm run submit:ios # App Store
```
### Clear Redis cache
```bash ```bash
redis-cli FLUSHALL redis-cli FLUSHALL
``` ```
+8
View File
@@ -0,0 +1,8 @@
# FarmaFinder Mobile - Environment Variables
# API Configuration
# Change this to your production API URL
EXPO_PUBLIC_API_URL=http://localhost:3001/api
# For production builds, update this to:
# EXPO_PUBLIC_API_URL=https://api.yourdomain.com/api
+20 -19
View File
@@ -1,22 +1,17 @@
# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
# dependencies
node_modules/
# Expo # Expo
.expo/ .expo/
dist/ dist/
web-build/ web-build/
expo-env.d.ts
# Native # Native
.kotlin/ ios/
*.orig.* android/
*.jks *.jks
*.p8 *.p8
*.p12 *.p12
*.key *.key
*.mobileprovision *.mobileprovision
*.orig.*
# Metro # Metro
.metro-health-check* .metro-health-check*
@@ -26,16 +21,22 @@ npm-debug.*
yarn-debug.* yarn-debug.*
yarn-error.* yarn-error.*
# macOS # env files
.env
.env.local
.env.production
# EAS
eas-cli.json
# Dependencies
node_modules/
# OS
.DS_Store .DS_Store
*.pem Thumbs.db
# local env files # Build artifacts
.env*.local *.apk
*.aab
# typescript *.ipa
*.tsbuildinfo
# generated native folders
/ios
/android
+12 -3
View File
@@ -14,20 +14,29 @@
}, },
"ios": { "ios": {
"supportsTablet": true, "supportsTablet": true,
"bundleIdentifier": "com.farmafinder.app" "bundleIdentifier": "com.farmafinder.app",
"config": {
"usesNonExemptEncryption": false
}
}, },
"android": { "android": {
"adaptiveIcon": { "adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png", "foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#007AFF" "backgroundColor": "#007AFF"
}, },
"package": "com.farmafinder.app" "package": "com.farmafinder.app",
"googleServicesFile": "./google-services.json"
}, },
"plugins": [ "plugins": [
"expo-router", "expo-router",
["expo-camera", {"cameraPermission": "Allow FarmaFinder to access your camera for scanning barcodes"}], ["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"}]
], ],
"scheme": "farmafinder" "scheme": "farmafinder",
"extra": {
"eas": {
"projectId": ""
}
}
} }
} }
+28 -7
View File
@@ -1,15 +1,18 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { View, FlatList, StyleSheet, Text } from 'react-native'; import { View, FlatList, StyleSheet, Text, TouchableOpacity } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { useRouter } from 'expo-router';
import { SearchBar } from '../../components/SearchBar'; import { SearchBar } from '../../components/SearchBar';
import { MedicineCard } from '../../components/MedicineCard'; import { MedicineCard } from '../../components/MedicineCard';
import { LoadingSpinner } from '../../components/LoadingSpinner'; import { LoadingSpinner } from '../../components/LoadingSpinner';
import { useDebounce } from '../../hooks/useDebounce'; import { useDebounce } from '../../hooks/useDebounce';
import { searchMedicines } from '../../services/medicines'; import { searchMedicines } from '../../services/medicines';
import { colors, spacing } from '../../constants/theme'; import { colors, spacing, borderRadius } from '../../constants/theme';
import { Medicine } from '../../types'; import { Medicine } from '../../types';
import { config } from '../../constants/config'; import { config } from '../../constants/config';
export default function HomeScreen() { export default function HomeScreen() {
const router = useRouter();
const [query, setQuery] = useState(''); const [query, setQuery] = useState('');
const [results, setResults] = useState<Medicine[]>([]); const [results, setResults] = useState<Medicine[]>([]);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
@@ -46,11 +49,19 @@ export default function HomeScreen() {
return ( return (
<View style={styles.container}> <View style={styles.container}>
<SearchBar <View style={styles.searchContainer}>
onSearch={handleSearch} <SearchBar
value={query} onSearch={handleSearch}
onChangeText={setQuery} value={query}
/> onChangeText={setQuery}
/>
<TouchableOpacity
style={styles.scannerButton}
onPress={() => router.push('/scanner')}
>
<Ionicons name="scan" size={24} color={colors.primary} />
</TouchableOpacity>
</View>
{isLoading && <LoadingSpinner message="Buscando medicamentos..." />} {isLoading && <LoadingSpinner message="Buscando medicamentos..." />}
@@ -82,6 +93,16 @@ const styles = StyleSheet.create({
flex: 1, flex: 1,
backgroundColor: colors.background, backgroundColor: colors.background,
}, },
searchContainer: {
flexDirection: 'row',
alignItems: 'center',
},
scannerButton: {
marginRight: spacing.md,
padding: spacing.sm,
backgroundColor: colors.card,
borderRadius: borderRadius.md,
},
list: { list: {
paddingBottom: spacing.xl, paddingBottom: spacing.xl,
}, },
+54 -4
View File
@@ -1,20 +1,70 @@
import { useEffect, useRef } from 'react';
import { Stack } from 'expo-router'; import { Stack } from 'expo-router';
import { StatusBar } from 'expo-status-bar'; import { StatusBar } from 'expo-status-bar';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { GestureHandlerRootView } from 'react-native-gesture-handler'; import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { useAuthStore } from '../store/authStore';
import { registerForPushNotifications, addNotificationListener, addNotificationResponseListener } from '../services/notifications';
const queryClient = new QueryClient(); const queryClient = new QueryClient();
export default function RootLayout() { export default function RootLayout() {
const { checkAuth } = useAuthStore();
const notificationListener = useRef<ReturnType<typeof addNotificationListener>>();
const responseListener = useRef<ReturnType<typeof addNotificationResponseListener>>();
useEffect(() => {
checkAuth();
registerForPushNotifications();
notificationListener.current = addNotificationListener((notification) => {
console.log('Notification received:', notification);
});
responseListener.current = addNotificationResponseListener((response) => {
console.log('Notification clicked:', response);
});
return () => {
notificationListener.current?.remove();
responseListener.current?.remove();
};
}, []);
return ( return (
<GestureHandlerRootView style={{ flex: 1 }}> <GestureHandlerRootView style={{ flex: 1 }}>
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<Stack> <Stack>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} /> <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen name="medicine/[id]" options={{ title: 'Medicamento' }} /> <Stack.Screen
<Stack.Screen name="pharmacy/[id]" options={{ title: 'Farmacia' }} /> name="medicine/[id]"
<Stack.Screen name="auth/login" options={{ title: 'Iniciar Sesión' }} /> options={{
<Stack.Screen name="auth/register" options={{ title: 'Registrarse' }} /> title: 'Medicamento',
headerTintColor: '#007AFF',
}}
/>
<Stack.Screen
name="pharmacy/[id]"
options={{
title: 'Farmacia',
headerTintColor: '#007AFF',
}}
/>
<Stack.Screen
name="auth/login"
options={{
title: 'Iniciar Sesión',
headerShown: false,
}}
/>
<Stack.Screen
name="auth/register"
options={{
title: 'Registrarse',
headerShown: false,
}}
/>
</Stack> </Stack>
<StatusBar style="auto" /> <StatusBar style="auto" />
</QueryClientProvider> </QueryClientProvider>
+83 -1
View File
@@ -1,4 +1,4 @@
import React, { useState } from 'react'; import React, { useState, useEffect } from 'react';
import { import {
View, View,
Text, Text,
@@ -10,8 +10,15 @@ import {
Alert Alert
} from 'react-native'; } from 'react-native';
import { useRouter } from 'expo-router'; import { useRouter } from 'expo-router';
import { Ionicons } from '@expo/vector-icons';
import { useAuthStore } from '../../store/authStore'; import { useAuthStore } from '../../store/authStore';
import { colors, spacing, borderRadius } from '../../constants/theme'; import { colors, spacing, borderRadius } from '../../constants/theme';
import {
isBiometricsAvailable,
authenticateWithBiometrics,
saveBiometricCredentials,
getBiometricUsername
} from '../../services/biometrics';
export default function LoginScreen() { export default function LoginScreen() {
const router = useRouter(); const router = useRouter();
@@ -19,6 +26,25 @@ export default function LoginScreen() {
const [username, setUsername] = useState(''); const [username, setUsername] = useState('');
const [password, setPassword] = useState(''); const [password, setPassword] = useState('');
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [biometricsAvailable, setBiometricsAvailable] = useState(false);
const [biometricUsername, setBiometricUsername] = useState<string | null>(null);
useEffect(() => {
checkBiometrics();
}, []);
const checkBiometrics = async () => {
try {
const available = await isBiometricsAvailable();
setBiometricsAvailable(available);
if (available) {
const savedUsername = await getBiometricUsername();
setBiometricUsername(savedUsername);
}
} catch (error) {
console.error('Error checking biometrics:', error);
}
};
const handleLogin = async () => { const handleLogin = async () => {
if (!username || !password) { if (!username || !password) {
@@ -29,6 +55,10 @@ export default function LoginScreen() {
setIsLoading(true); setIsLoading(true);
try { try {
await login(username, password); await login(username, password);
// Save username for biometric login
if (biometricsAvailable) {
await saveBiometricCredentials(username);
}
router.replace('/(tabs)'); router.replace('/(tabs)');
} catch (error) { } catch (error) {
Alert.alert('Error', 'Credenciales incorrectas'); Alert.alert('Error', 'Credenciales incorrectas');
@@ -37,6 +67,30 @@ export default function LoginScreen() {
} }
}; };
const handleBiometricLogin = async () => {
if (!biometricUsername) {
Alert.alert('Error', 'No hay credenciales biométricas guardadas');
return;
}
setIsLoading(true);
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 {
Alert.alert('Error', 'Autenticación biométrica fallida');
}
} catch (error) {
Alert.alert('Error', 'Error en la autenticación biométrica');
} finally {
setIsLoading(false);
}
};
return ( return (
<KeyboardAvoidingView <KeyboardAvoidingView
style={styles.container} style={styles.container}
@@ -81,6 +135,17 @@ export default function LoginScreen() {
</Text> </Text>
</TouchableOpacity> </TouchableOpacity>
{biometricsAvailable && biometricUsername && (
<TouchableOpacity
style={[styles.biometricButton, isLoading && styles.buttonDisabled]}
onPress={handleBiometricLogin}
disabled={isLoading}
>
<Ionicons name="finger-print" size={24} color={colors.primary} />
<Text style={styles.biometricText}>Iniciar con biometría</Text>
</TouchableOpacity>
)}
<TouchableOpacity <TouchableOpacity
style={styles.linkButton} style={styles.linkButton}
onPress={() => router.push('/auth/register')} onPress={() => router.push('/auth/register')}
@@ -152,4 +217,21 @@ const styles = StyleSheet.create({
color: colors.primary, color: colors.primary,
fontSize: 14, 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,
},
}); });
+46
View File
@@ -0,0 +1,46 @@
import React, { useState } from 'react';
import { View, StyleSheet } from 'react-native';
import { useRouter } from 'expo-router';
import { BarcodeScanner } from '../components/BarcodeScanner';
import { searchMedicines } from '../services/medicines';
export default function ScannerScreen() {
const router = useRouter();
const [isSearching, setIsSearching] = useState(false);
const handleBarcodeScanned = async (barcode: string) => {
setIsSearching(true);
try {
const results = await searchMedicines(barcode);
if (results.length > 0) {
router.push(`/medicine/${results[0].nregistro}`);
} else {
router.push(`/medicine/${barcode}`);
}
} catch (error) {
console.error('Error searching medicine:', error);
router.push(`/medicine/${barcode}`);
} finally {
setIsSearching(false);
}
};
const handleClose = () => {
router.back();
};
return (
<View style={styles.container}>
<BarcodeScanner
onBarcodeScanned={handleBarcodeScanned}
onClose={handleClose}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 384 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 384 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 384 KiB

@@ -0,0 +1,207 @@
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';
interface BarcodeScannerProps {
onBarcodeScanned: (barcode: string) => void;
onClose: () => void;
}
export function BarcodeScanner({ onBarcodeScanned, onClose }: BarcodeScannerProps) {
const [permission, requestPermission] = useCameraPermissions();
const [scanned, setScanned] = useState(false);
if (!permission) {
return <View style={styles.container} />;
}
if (!permission.granted) {
return (
<View style={styles.permissionContainer}>
<Ionicons name="camera" size={64} color={colors.textSecondary} />
<Text style={styles.permissionTitle}>Permiso de cámara requerido</Text>
<Text style={styles.permissionText}>
Necesitamos acceso a la cámara para escanear códigos de barras
</Text>
<TouchableOpacity style={styles.permissionButton} onPress={requestPermission}>
<Text style={styles.permissionButtonText}>Conceder permiso</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.cancelButton} onPress={onClose}>
<Text style={styles.cancelButtonText}>Cancelar</Text>
</TouchableOpacity>
</View>
);
}
const handleBarCodeScanned = ({ type, data }: { type: string; data: string }) => {
if (scanned) return;
setScanned(true);
onBarcodeScanned(data);
};
return (
<View style={styles.container}>
<CameraView
style={StyleSheet.absoluteFillObject}
facing="back"
barcodeScannerSettings={{
barcodeTypes: ['ean13', 'ean8', 'upc_a', 'upc_e'],
}}
onBarcodeScanned={scanned ? undefined : handleBarCodeScanned}
/>
<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>
<Text style={styles.instruction}>
Apunta la cámara al código de barras del medicamento
</Text>
<TouchableOpacity style={styles.closeButton} onPress={onClose}>
<Ionicons name="close" size={24} color={colors.textInverse} />
</TouchableOpacity>
</View>
{scanned && (
<View style={styles.scannedOverlay}>
<TouchableOpacity
style={styles.scanAgainButton}
onPress={() => setScanned(false)}
>
<Text style={styles.scanAgainText}>Escanear de nuevo</Text>
</TouchableOpacity>
</View>
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#000',
},
permissionContainer: {
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,
fontSize: 16,
fontWeight: '600',
},
cancelButton: {
marginTop: spacing.md,
},
cancelButtonText: {
color: colors.textSecondary,
fontSize: 14,
},
overlay: {
flex: 1,
backgroundColor: 'transparent',
justifyContent: 'center',
alignItems: 'center',
},
scannerFrame: {
width: 250,
height: 250,
borderWidth: 2,
borderColor: 'transparent',
position: 'relative',
},
corner: {
position: 'absolute',
width: 30,
height: 30,
borderColor: colors.primary,
},
topLeft: {
top: 0,
left: 0,
borderTopWidth: 3,
borderLeftWidth: 3,
},
topRight: {
top: 0,
right: 0,
borderTopWidth: 3,
borderRightWidth: 3,
},
bottomLeft: {
bottom: 0,
left: 0,
borderBottomWidth: 3,
borderLeftWidth: 3,
},
bottomRight: {
bottom: 0,
right: 0,
borderBottomWidth: 3,
borderRightWidth: 3,
},
instruction: {
color: colors.textInverse,
fontSize: 14,
textAlign: 'center',
marginTop: spacing.xl,
backgroundColor: 'rgba(0,0,0,0.6)',
paddingHorizontal: spacing.md,
paddingVertical: spacing.sm,
borderRadius: borderRadius.sm,
},
closeButton: {
position: 'absolute',
top: spacing.xl,
right: spacing.xl,
backgroundColor: 'rgba(0,0,0,0.6)',
borderRadius: 20,
padding: spacing.sm,
},
scannedOverlay: {
position: 'absolute',
bottom: spacing.xxl,
left: spacing.xl,
right: spacing.xl,
},
scanAgainButton: {
backgroundColor: colors.primary,
borderRadius: borderRadius.md,
padding: spacing.md,
alignItems: 'center',
},
scanAgainText: {
color: colors.textInverse,
fontSize: 16,
fontWeight: '600',
},
});
+46
View File
@@ -0,0 +1,46 @@
{
"cli": {
"version": ">= 12.0.0"
},
"build": {
"development": {
"developmentClient": true,
"distribution": "internal",
"ios": {
"simulator": true
},
"android": {
"buildType": "apk"
}
},
"preview": {
"distribution": "internal",
"ios": {
"buildType": "preview"
},
"android": {
"buildType": "apk"
}
},
"production": {
"ios": {
"buildType": "release"
},
"android": {
"buildType": "app-bundle"
}
}
},
"submit": {
"production": {
"ios": {
"appleId": "",
"ascAppId": "",
"appleTeamId": ""
},
"android": {
"serviceAccountKeyPath": "./google-service-account.json"
}
}
}
}
+736 -567
View File
File diff suppressed because it is too large Load Diff
+4 -2
View File
@@ -10,13 +10,15 @@
"expo": "~57.0.2", "expo": "~57.0.2",
"expo-camera": "~57.0.0", "expo-camera": "~57.0.0",
"expo-constants": "~57.0.3", "expo-constants": "~57.0.3",
"expo-dev-client": "~57.0.5",
"expo-device": "~7.0.2",
"expo-linking": "~57.0.1", "expo-linking": "~57.0.1",
"expo-local-authentication": "~57.0.0", "expo-local-authentication": "~57.0.0",
"expo-notifications": "~57.0.3", "expo-notifications": "~57.0.3",
"expo-router": "~57.0.3", "expo-router": "~57.0.3",
"expo-secure-store": "~57.0.0", "expo-secure-store": "~57.0.0",
"expo-status-bar": "~57.0.0", "expo-status-bar": "~57.0.0",
"react": "19.2.3", "react": "19.2.7",
"react-native": "0.86.0", "react-native": "0.86.0",
"react-native-gesture-handler": "~2.32.0", "react-native-gesture-handler": "~2.32.0",
"react-native-maps": "^1.29.0", "react-native-maps": "^1.29.0",
@@ -27,7 +29,7 @@
"zustand": "^5.0.14" "zustand": "^5.0.14"
}, },
"devDependencies": { "devDependencies": {
"@types/react": "~19.2.2", "@types/react": "~19.2.7",
"typescript": "~6.0.3" "typescript": "~6.0.3"
}, },
"scripts": { "scripts": {
+34
View File
@@ -0,0 +1,34 @@
import * as LocalAuthentication from 'expo-local-authentication';
import * as SecureStore from 'expo-secure-store';
export async function isBiometricsAvailable(): Promise<boolean> {
const compatible = await LocalAuthentication.hasHardwareAsync();
const enrolled = await LocalAuthentication.isEnrolledAsync();
return compatible && enrolled;
}
export async function authenticateWithBiometrics(): Promise<boolean> {
try {
const result = await LocalAuthentication.authenticateAsync({
promptMessage: 'Inicia sesión con biometría',
cancelLabel: 'Cancelar',
disableDeviceFallback: false,
});
return result.success;
} catch (error) {
console.error('Biometric authentication error:', error);
return false;
}
}
export async function saveBiometricCredentials(username: string): Promise<void> {
await SecureStore.setItemAsync('biometric_username', username);
}
export async function getBiometricUsername(): Promise<string | null> {
return await SecureStore.getItemAsync('biometric_username');
}
export async function clearBiometricCredentials(): Promise<void> {
await SecureStore.deleteItemAsync('biometric_username');
}
+82
View File
@@ -0,0 +1,82 @@
import * as Notifications from 'expo-notifications';
import * as Device from 'expo-device';
import * as Constants from 'expo-constants';
import { Platform } from 'react-native';
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowBanner: true,
shouldShowList: true,
shouldPlaySound: true,
shouldSetBadge: true,
}),
});
export async function registerForPushNotifications() {
if (!Device.isDevice) {
console.log('Push notifications require a physical device');
return null;
}
const { status: existingStatus } = await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== 'granted') {
console.log('Failed to get push token for push notification');
return null;
}
if (Platform.OS === 'android') {
await Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#007AFF',
});
}
try {
const projectId =
Constants?.expoConfig?.extra?.eas?.projectId ?? Constants?.easConfig?.projectId;
const token = await Notifications.getExpoPushTokenAsync({
projectId,
});
return token.data;
} catch (e) {
console.log('Error getting push token:', e);
return null;
}
}
export async function scheduleMedicineAvailabilityNotification(
medicineName: string,
pharmacyName: string
) {
await Notifications.scheduleNotificationAsync({
content: {
title: 'Medicamento disponible',
body: `${medicineName} está disponible en ${pharmacyName}`,
data: { type: 'medicine_availability' },
},
trigger: null,
});
}
export function addNotificationListener(
handler: (notification: Notifications.Notification) => void
): Notifications.EventSubscription {
return Notifications.addNotificationReceivedListener(handler);
}
export function addNotificationResponseListener(
handler: (response: Notifications.NotificationResponse) => void
): Notifications.EventSubscription {
return Notifications.addNotificationResponseReceivedListener(handler);
}
+7 -1
View File
@@ -7,11 +7,17 @@
"dev": "npm-run-all --parallel dev:backend dev:frontend", "dev": "npm-run-all --parallel dev:backend dev:frontend",
"dev:backend": "npm run dev --prefix backend", "dev:backend": "npm run dev --prefix backend",
"dev:frontend": "npm run dev --prefix frontend", "dev:frontend": "npm run dev --prefix frontend",
"dev:mobile": "cd frontend-mobile && npx expo start",
"dev:mobile:android": "cd frontend-mobile && npx expo start --android",
"dev:mobile:ios": "cd frontend-mobile && npx expo start --ios",
"start": "npm-run-all --parallel start:backend start:frontend", "start": "npm-run-all --parallel start:backend start:frontend",
"start:backend": "npm start --prefix backend", "start:backend": "npm start --prefix backend",
"start:frontend": "npm run preview --prefix frontend", "start:frontend": "npm run preview --prefix frontend",
"install:all": "npm install && npm install --prefix backend && npm install --prefix frontend", "install:all": "npm install && npm install --prefix backend && npm install --prefix frontend && npm install --prefix frontend-mobile",
"build:web": "npm run build --prefix frontend", "build:web": "npm run build --prefix frontend",
"build:mobile": "cd frontend-mobile && eas build",
"submit:android": "cd frontend-mobile && eas submit --platform android",
"submit:ios": "cd frontend-mobile && eas submit --platform ios",
"cap:sync": "npm run build:web && cap sync", "cap:sync": "npm run build:web && cap sync",
"cap:copy": "npm run build:web && cap copy", "cap:copy": "npm run build:web && cap copy",
"cap:open:android": "cap open android", "cap:open:android": "cap open android",