Merge pull request 'new_react_frontend' (#9) from new_react_frontend into main
Build & Push Docker Images / test-backend (push) Successful in 34s
Build & Push Docker Images / test-frontend (push) Successful in 31s
Build & Push Docker Images / deploy (push) Successful in 7s
Build & Push Docker Images / build-backend (push) Successful in 18s
Build & Push Docker Images / build-frontend (push) Successful in 16s
Run Tests on Branches / Frontend Tests (push) Has been cancelled
Run Tests on Branches / Backend Tests (push) Has been cancelled
Reviewed-on: #9
@@ -4,6 +4,7 @@ A web application to search for medicines from the official Spanish CIMA databas
|
||||
|
||||
## ✨ Features
|
||||
|
||||
### Web App (Desktop/PWA)
|
||||
- 🔍 **Real-time medicine search** from CIMA API (Agencia Española de Medicamentos)
|
||||
- 💾 **Redis caching** for improved performance
|
||||
- 📍 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
|
||||
- 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
|
||||
|
||||
- **Frontend**: React + Vite
|
||||
- **Backend**: Node.js + Express
|
||||
### Backend
|
||||
- **Runtime**: Node.js + Express
|
||||
- **Database**: SQLite (for pharmacies and relationships)
|
||||
- **Cache**: Redis
|
||||
- **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
|
||||
|
||||
- Node.js (v18 or higher)
|
||||
@@ -200,7 +225,7 @@ FarmaFinder/
|
||||
│ ├── create-admin.js # Admin user creation script
|
||||
│ ├── .env.example # Environment variable template
|
||||
│ └── package.json
|
||||
├── frontend/
|
||||
├── frontend/ # React + Vite (Desktop/PWA)
|
||||
│ ├── Dockerfile
|
||||
│ ├── nginx.conf # Nginx config (Docker): serves SPA + proxies /api
|
||||
│ ├── src/
|
||||
@@ -213,6 +238,27 @@ FarmaFinder/
|
||||
│ │ └── main.jsx # Entry point
|
||||
│ ├── index.html
|
||||
│ └── 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
|
||||
```
|
||||
|
||||
@@ -289,6 +335,194 @@ The application now uses the **CIMA (Centro de Información online de Medicament
|
||||
- Results are cached in Redis for performance
|
||||
- `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
|
||||
|
||||
### Redis Connection Issues
|
||||
@@ -321,19 +555,52 @@ npm run create-admin
|
||||
|
||||
## 📝 Development
|
||||
|
||||
**Backend development with auto-reload:**
|
||||
### Backend
|
||||
|
||||
**Start with auto-reload:**
|
||||
```bash
|
||||
cd backend
|
||||
npm run dev
|
||||
```
|
||||
|
||||
**Frontend development:**
|
||||
### Frontend (Web/PWA)
|
||||
|
||||
**Start development server:**
|
||||
```bash
|
||||
cd frontend
|
||||
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
|
||||
redis-cli FLUSHALL
|
||||
```
|
||||
|
||||
@@ -0,0 +1,420 @@
|
||||
# FarmaFinder Mobile - Especificación de Diseño
|
||||
|
||||
**Fecha**: 2026-07-06
|
||||
**Estado**: Aprobado
|
||||
**Versión**: 1.0
|
||||
|
||||
---
|
||||
|
||||
## 1. Resumen
|
||||
|
||||
Crear un segundo frontend en **React Native (Expo)** para FarmaFinder, manteniendo el frontend actual (React + Vite) para Desktop/PWA. El objetivo es lograr una experiencia móvil nativa que permita publicar en App Store y Google Play con mejor rendimiento, UX y mantenibilidad.
|
||||
|
||||
---
|
||||
|
||||
## 2. Arquitectura
|
||||
|
||||
### 2.1 Estructura del Proyecto
|
||||
|
||||
```
|
||||
FarmaFinder/
|
||||
├── frontend/ ← React + Vite (Desktop/PWA, mantiene Capacitor)
|
||||
├── frontend-mobile/ ← Expo + React Native (NUEVO)
|
||||
│ ├── app/ ← Expo Router (file-based routing)
|
||||
│ │ ├── _layout.tsx ← Layout raíz
|
||||
│ │ ├── (tabs)/ ← Bottom tabs
|
||||
│ │ │ ├── _layout.tsx ← Tab navigator
|
||||
│ │ │ ├── index.tsx ← Home (búsqueda)
|
||||
│ │ │ ├── map.tsx ← Mapa de farmacias
|
||||
│ │ │ └── profile.tsx ← Perfil de usuario
|
||||
│ │ ├── medicine/[id].tsx ← Detalle de medicamento
|
||||
│ │ ├── pharmacy/[id].tsx ← Detalle de farmacia
|
||||
│ │ └── auth/ ← Auth flow
|
||||
│ ├── components/ ← Componentes React Native
|
||||
│ ├── services/ ← Lógica de negocio y llamadas API
|
||||
│ ├── hooks/ ← Custom hooks
|
||||
│ ├── constants/ ← Colores, tipos, config
|
||||
│ └── assets/ ← Imágenes, fuentes
|
||||
├── backend/ ← API compartida (sin cambios)
|
||||
└── package.json ← Scripts para ambos frontends
|
||||
```
|
||||
|
||||
### 2.2 Stack Tecnológico
|
||||
|
||||
| Componente | Tecnología | Justificación |
|
||||
|------------|------------|---------------|
|
||||
| Framework | Expo SDK 52+ | Setup rápido, OTA updates, fácil publicación |
|
||||
| Routing | Expo Router v4 | File-based routing, similar a Next.js |
|
||||
| Navegación | React Navigation | Bottom tabs + stack navigation |
|
||||
| State | Zustand | Ligero, sin boilerplate, fácil de usar |
|
||||
| HTTP Client | Axios | Interceptors, cancelación de requests |
|
||||
| Cache | TanStack Query | Cache automático, optimistic updates |
|
||||
| Mapas | react-native-maps | Google Maps provider nativo |
|
||||
| Barcode | expo-camera | Escaneo de código de barras nativo |
|
||||
| Storage | AsyncStorage + expo-secure-store | Datos offline + tokens seguros |
|
||||
| Animaciones | React Native Reanimated 3 | Animaciones fluidas en 60fps |
|
||||
|
||||
---
|
||||
|
||||
## 3. Estructura de Navegación
|
||||
|
||||
### 3.1 Navegación Principal
|
||||
|
||||
```
|
||||
Bottom Tabs
|
||||
├── Home (🔍) → Búsqueda de medicamentos
|
||||
├── Mapa (📍) → Mapa de farmacias
|
||||
└── Perfil (👤) → Perfil de usuario + Admin
|
||||
```
|
||||
|
||||
### 3.2 Navegación Detallada
|
||||
|
||||
```
|
||||
Home Tab (Stack)
|
||||
├── index.tsx ← Lista de resultados de búsqueda
|
||||
└── medicine/[id].tsx ← Detalle de medicamento
|
||||
|
||||
Mapa Tab (Stack)
|
||||
├── map.tsx ← Mapa con marcadores de farmacias
|
||||
└── pharmacy/[id].tsx ← Detalle de farmacia
|
||||
|
||||
Perfil Tab (Stack)
|
||||
├── profile.tsx ← Info de usuario + opciones
|
||||
├── auth/login.tsx ← Login (si no autenticado)
|
||||
├── auth/register.tsx ← Registro
|
||||
└── admin/ ← Panel admin (solo si auth + admin)
|
||||
```
|
||||
|
||||
### 3.3 Flujos de Navegación
|
||||
|
||||
- **Auth Flow**: Si no hay token → redirigir a login
|
||||
- **Admin Flow**: Si usuario es admin → mostrar acceso a admin
|
||||
- **Deep Linking**: URLs como `farmafinder://medicine/123` abren pantalla específica
|
||||
|
||||
---
|
||||
|
||||
## 4. Funcionalidades
|
||||
|
||||
### 4.1 MVP (Paridad con Web)
|
||||
|
||||
| Funcionalidad | Descripción |
|
||||
|---------------|-------------|
|
||||
| **Búsqueda** | Búsqueda en tiempo real de medicamentos vía API CIMA |
|
||||
| **Resultados** | Lista de resultados con nombre, principio activo |
|
||||
| **Detalle medicamento** | Precio, stock, farmacias que lo tienen |
|
||||
| **Mapa farmacias** | Marcadores en mapa con ubicación |
|
||||
| **Detalle farmacia** | Dirección, teléfono, medicamentos disponibles |
|
||||
| **Auth** | Login/registro de usuarios |
|
||||
|
||||
### 4.2 Extras Nativos (NUEVO)
|
||||
|
||||
| Funcionalidad | Descripción |
|
||||
|---------------|-------------|
|
||||
| **Push Notifications** | Alertas de disponibilidad de medicamentos favoritos |
|
||||
| **Escáner código barras** | Escanear medicamentos directamente con cámara |
|
||||
| **Biometría** | Face ID / Touch ID para login rápido |
|
||||
| **Deep Links** | Compartir medicamentos/farmacias via URL |
|
||||
| **Offline Cache** | Medicamentos favoritos accesibles sin conexión |
|
||||
|
||||
---
|
||||
|
||||
## 5. Integración con la API
|
||||
|
||||
### 5.1 Cliente API
|
||||
|
||||
```typescript
|
||||
// frontend-mobile/services/api.ts
|
||||
import axios from 'axios';
|
||||
|
||||
const API_BASE = __DEV__
|
||||
? 'http://localhost:3001/api'
|
||||
: 'https://tu-dominio.com/api';
|
||||
|
||||
export const api = axios.create({
|
||||
baseURL: API_BASE,
|
||||
timeout: 10000,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
|
||||
// Request interceptor para auth token
|
||||
api.interceptors.request.use((config) => {
|
||||
const token = getToken();
|
||||
if (token) config.headers.Authorization = `Bearer ${token}`;
|
||||
return config;
|
||||
});
|
||||
```
|
||||
|
||||
### 5.2 Endpoints
|
||||
|
||||
**Públicos:**
|
||||
- `GET /api/medicines/search?q=<query>` - Búsqueda de medicamentos
|
||||
- `GET /api/medicines/:nregistro` - Detalle de medicamento
|
||||
- `GET /api/medicines/:nregistro/pharmacies` - Farmacias con medicamento
|
||||
- `GET /api/pharmacies` - Todas las farmacias
|
||||
|
||||
**Autenticados:**
|
||||
- `POST /api/auth/login` - Login
|
||||
- `POST /api/auth/logout` - Logout
|
||||
- `GET /api/auth/check` - Verificar auth
|
||||
|
||||
**Admin:**
|
||||
- CRUD de farmacias
|
||||
- Búsqueda de medicamentos para admin
|
||||
- Vincular medicamentos a farmacias
|
||||
|
||||
### 5.3 Estrategia de Cache
|
||||
|
||||
```typescript
|
||||
// Con TanStack Query
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['medicines', searchQuery],
|
||||
queryFn: () => searchMedicines(searchQuery),
|
||||
staleTime: 5 * 60 * 1000, // 5 minutos
|
||||
cacheTime: 30 * 60 * 1000, // 30 minutos
|
||||
});
|
||||
```
|
||||
|
||||
**Persistencia offline:**
|
||||
- AsyncStorage para datos no sensibles
|
||||
- expo-secure-store para tokens y credenciales
|
||||
- React Query persistor para cache de queries
|
||||
|
||||
---
|
||||
|
||||
## 6. Diseño Visual
|
||||
|
||||
### 6.1 Design Tokens
|
||||
|
||||
```typescript
|
||||
// frontend-mobile/constants/theme.ts
|
||||
export const colors = {
|
||||
// Primary
|
||||
primary: '#007AFF',
|
||||
primaryLight: '#4DA3FF',
|
||||
|
||||
// Semantic
|
||||
success: '#34C759', // Disponible
|
||||
danger: '#FF3B30', // Sin stock
|
||||
warning: '#FF9500', // Stock bajo
|
||||
|
||||
// Neutral
|
||||
background: '#F2F2F7',
|
||||
card: '#FFFFFF',
|
||||
border: '#E5E5EA',
|
||||
|
||||
// Text
|
||||
text: '#1C1C1E',
|
||||
textSecondary: '#8E8E93',
|
||||
textInverse: '#FFFFFF',
|
||||
};
|
||||
|
||||
export const spacing = {
|
||||
xs: 4,
|
||||
sm: 8,
|
||||
md: 16,
|
||||
lg: 24,
|
||||
xl: 32,
|
||||
};
|
||||
|
||||
export const borderRadius = {
|
||||
sm: 8,
|
||||
md: 12,
|
||||
lg: 16,
|
||||
};
|
||||
```
|
||||
|
||||
### 6.2 Componentes Principales
|
||||
|
||||
| Componente | Descripción |
|
||||
|------------|-------------|
|
||||
| **SearchBar** | Input con debounce (300ms) + dropdown de resultados |
|
||||
| **MedicineCard** | Card con nombre, principio activo, precio, badge de stock |
|
||||
| **PharmacyMarker** | Marcador personalizado en mapa con info window |
|
||||
| **StockBadge** | Badge verde (disponible) / rojo (sin stock) |
|
||||
| **LoadingSpinner** | Spinner nativo durante cargas |
|
||||
| **ErrorToast** | Toast de error con retry |
|
||||
|
||||
### 6.3 Patrones de Diseño
|
||||
|
||||
- **Cards**: Sombra sutil, border-radius 12px
|
||||
- **Tipografía**: Sistema nativo (SF Pro en iOS, Roboto en Android)
|
||||
- **Espaciado**: Escala de 4px base (4, 8, 12, 16, 24, 32)
|
||||
- **Animaciones**: Reanimated 3 para transiciones y gestos
|
||||
|
||||
---
|
||||
|
||||
## 7. Extras Nativos (Detalles)
|
||||
|
||||
### 7.1 Push Notifications
|
||||
|
||||
```typescript
|
||||
// Expo Notifications
|
||||
import * as Notifications from 'expo-notifications';
|
||||
|
||||
// Registrar para notificaciones
|
||||
const registerForPushNotifications = async () => {
|
||||
const { status } = await Notifications.requestPermissionsAsync();
|
||||
if (status !== 'granted') return;
|
||||
|
||||
const token = await Notifications.getExpoPushToken();
|
||||
return token.data;
|
||||
};
|
||||
|
||||
// Escuchar notificaciones
|
||||
Notifications.addNotificationReceivedListener((notification) => {
|
||||
// Mostrar alerta de disponibilidad
|
||||
});
|
||||
```
|
||||
|
||||
### 7.2 Escáner de Código de Barras
|
||||
|
||||
```typescript
|
||||
// expo-camera + barcode scanning
|
||||
import { CameraView } from 'expo-camera';
|
||||
|
||||
<CameraView
|
||||
onBarcodeScanned={(data) => {
|
||||
// Buscar medicamento por código de barras
|
||||
searchMedicineByBarcode(data.data);
|
||||
}}
|
||||
/>
|
||||
```
|
||||
|
||||
### 7.3 Biometría
|
||||
|
||||
```typescript
|
||||
// expo-local-authentication
|
||||
import * as LocalAuthentication from 'expo-local-authentication';
|
||||
|
||||
const authenticateWithBiometrics = async () => {
|
||||
const hasHardware = await LocalAuthentication.hasHardwareAsync();
|
||||
const isEnrolled = await LocalAuthentication.isEnrolledAsync();
|
||||
|
||||
if (hasHardware && isEnrolled) {
|
||||
return await LocalAuthentication.authenticateAsync();
|
||||
}
|
||||
return false;
|
||||
};
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Workflow de Desarrollo
|
||||
|
||||
### 8.1 Scripts
|
||||
|
||||
```json
|
||||
{
|
||||
"scripts": {
|
||||
"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",
|
||||
"build:mobile:dev": "cd frontend-mobile && eas build --profile development",
|
||||
"build:mobile:preview": "cd frontend-mobile && eas build --profile preview",
|
||||
"build:mobile:prod": "cd frontend-mobile && eas build --profile production",
|
||||
"submit:android": "cd frontend-mobile && eas submit --platform android",
|
||||
"submit:ios": "cd frontend-mobile && eas submit --platform ios"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 8.2 EAS Build Profiles
|
||||
|
||||
```json
|
||||
// frontend-mobile/eas.json
|
||||
{
|
||||
"build": {
|
||||
"development": {
|
||||
"developmentClient": true,
|
||||
"distribution": "internal"
|
||||
},
|
||||
"preview": {
|
||||
"distribution": "internal"
|
||||
},
|
||||
"production": {}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 8.3 CI/CD
|
||||
|
||||
- **Desarrollo**: Expo Go + hot reload
|
||||
- **Testing**: EAS Build (preview) → APK/IPA para testing
|
||||
- **Producción**: EAS Build (production) → Submit a tiendas
|
||||
- **OTA Updates**: Expo Updates para fixes sin pasar por tienda
|
||||
|
||||
---
|
||||
|
||||
## 9. Dependencias Principales
|
||||
|
||||
```json
|
||||
{
|
||||
"dependencies": {
|
||||
"expo": "~52.0.0",
|
||||
"expo-router": "~4.0.0",
|
||||
"expo-camera": "~16.0.0",
|
||||
"expo-notifications": "~0.29.0",
|
||||
"expo-local-authentication": "~15.0.0",
|
||||
"expo-secure-store": "~14.0.0",
|
||||
"react-native": "0.76.0",
|
||||
"react-native-maps": "1.18.0",
|
||||
"react-native-reanimated": "~3.16.0",
|
||||
"react-native-gesture-handler": "~2.20.0",
|
||||
"@react-navigation/native": "^7.0.0",
|
||||
"@react-navigation/bottom-tabs": "^7.0.0",
|
||||
"zustand": "^5.0.0",
|
||||
"axios": "^1.7.0",
|
||||
"@tanstack/react-query": "^5.0.0",
|
||||
"@react-native-async-storage/async-storage": "^2.0.0"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. Criterios de Aceptación
|
||||
|
||||
### MVP
|
||||
- [ ] Búsqueda de medicamentos funcional
|
||||
- [ ] Mapa con farmacias mostrando marcadores
|
||||
- [ ] Detalle de medicamento con precio y stock
|
||||
- [ ] Detalle de farmacia con ubicación
|
||||
- [ ] Login/registro funcional
|
||||
- [ ] Navegación entre pantallas fluida
|
||||
- [ ] Build de desarrollo funcionando en Expo Go
|
||||
|
||||
### Extras Nativos
|
||||
- [ ] Push notifications configuradas
|
||||
- [ ] Escáner de código de barras funcional
|
||||
- [ ] Biometría para login rápido
|
||||
- [ ] Deep links configurados
|
||||
- [ ] Offline cache para favoritos
|
||||
|
||||
### Publicación
|
||||
- [ ] Build de producción optimizado
|
||||
- [ ] App Store listing configurado
|
||||
- [ ] Google Play listing configurado
|
||||
- [ ] Screenshots y descripción preparados
|
||||
|
||||
---
|
||||
|
||||
## 11. Riesgos y Mitigaciones
|
||||
|
||||
| Riesgo | Mitigación |
|
||||
|--------|------------|
|
||||
| API del backend no preparada para móvil | Revisar endpoints, agregar si es necesario |
|
||||
| Performance en dispositivos antiguos | Testing en dispositivos低端, optimizar renders |
|
||||
| Diferencias iOS/Android | Usar componentes nativos, testing en ambas plataformas |
|
||||
| Mantenimiento de dos frontends | Documentar bien, compartir types cuando sea posible |
|
||||
|
||||
---
|
||||
|
||||
## 12. Próximos Pasos
|
||||
|
||||
1. Crear estructura del proyecto Expo
|
||||
2. Configurar routing con Expo Router
|
||||
3. Implementar cliente API
|
||||
4. Crear pantallas MVP
|
||||
5. Implementar extras nativos
|
||||
6. Testing y optimización
|
||||
7. Build y publicación en tiendas
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"enabledPlugins": {
|
||||
"expo@claude-plugins-official": true
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -0,0 +1,42 @@
|
||||
# Expo
|
||||
.expo/
|
||||
dist/
|
||||
web-build/
|
||||
|
||||
# Native
|
||||
ios/
|
||||
android/
|
||||
*.jks
|
||||
*.p8
|
||||
*.p12
|
||||
*.key
|
||||
*.mobileprovision
|
||||
*.orig.*
|
||||
|
||||
# Metro
|
||||
.metro-health-check*
|
||||
|
||||
# debug
|
||||
npm-debug.*
|
||||
yarn-debug.*
|
||||
yarn-error.*
|
||||
|
||||
# env files
|
||||
.env
|
||||
.env.local
|
||||
.env.production
|
||||
|
||||
# EAS
|
||||
eas-cli.json
|
||||
|
||||
# Dependencies
|
||||
node_modules/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Build artifacts
|
||||
*.apk
|
||||
*.aab
|
||||
*.ipa
|
||||
@@ -0,0 +1,3 @@
|
||||
# Expo HAS CHANGED
|
||||
|
||||
Read the exact versioned docs at https://docs.expo.dev/versions/v57.0.0/ before writing any code.
|
||||
@@ -0,0 +1,20 @@
|
||||
import { StatusBar } from 'expo-status-bar';
|
||||
import { StyleSheet, Text, View } from 'react-native';
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Text>Open up App.tsx to start working on your app!</Text>
|
||||
<StatusBar style="auto" />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: '#fff',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
@AGENTS.md
|
||||
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"expo": {
|
||||
"name": "FarmaFinder",
|
||||
"slug": "farmafinder",
|
||||
"version": "1.0.0",
|
||||
"orientation": "portrait",
|
||||
"icon": "./assets/icon.png",
|
||||
"userInterfaceStyle": "light",
|
||||
"newArchEnabled": true,
|
||||
"splash": {
|
||||
"image": "./assets/splash.png",
|
||||
"resizeMode": "contain",
|
||||
"backgroundColor": "#007AFF"
|
||||
},
|
||||
"ios": {
|
||||
"supportsTablet": true,
|
||||
"bundleIdentifier": "com.farmafinder.app",
|
||||
"config": {
|
||||
"usesNonExemptEncryption": false
|
||||
}
|
||||
},
|
||||
"android": {
|
||||
"adaptiveIcon": {
|
||||
"foregroundImage": "./assets/adaptive-icon.png",
|
||||
"backgroundColor": "#007AFF"
|
||||
},
|
||||
"package": "com.farmafinder.app",
|
||||
"googleServicesFile": "./google-services.json"
|
||||
},
|
||||
"plugins": [
|
||||
"expo-router",
|
||||
["expo-camera", {"cameraPermission": "Allow FarmaFinder to access your camera for scanning barcodes"}],
|
||||
["expo-notifications", {"icon": "./assets/notification-icon.png", "color": "#007AFF"}]
|
||||
],
|
||||
"scheme": "farmafinder",
|
||||
"extra": {
|
||||
"eas": {
|
||||
"projectId": ""
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Tabs } from 'expo-router';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
|
||||
export default function TabLayout() {
|
||||
return (
|
||||
<Tabs
|
||||
screenOptions={{
|
||||
tabBarActiveTintColor: '#007AFF',
|
||||
tabBarInactiveTintColor: '#8E8E93',
|
||||
}}
|
||||
>
|
||||
<Tabs.Screen
|
||||
name="index"
|
||||
options={{
|
||||
title: 'Buscar',
|
||||
tabBarIcon: ({ color, size }) => (
|
||||
<Ionicons name="search" size={size} color={color} />
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
name="map"
|
||||
options={{
|
||||
title: 'Mapa',
|
||||
tabBarIcon: ({ color, size }) => (
|
||||
<Ionicons name="map" size={size} color={color} />
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
name="profile"
|
||||
options={{
|
||||
title: 'Perfil',
|
||||
tabBarIcon: ({ color, size }) => (
|
||||
<Ionicons name="person" size={size} color={color} />
|
||||
),
|
||||
}}
|
||||
/>
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
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 { 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';
|
||||
|
||||
export default function HomeScreen() {
|
||||
const router = useRouter();
|
||||
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);
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<View style={styles.searchContainer}>
|
||||
<SearchBar
|
||||
onSearch={handleSearch}
|
||||
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..." />}
|
||||
|
||||
{error && (
|
||||
<View style={styles.errorContainer}>
|
||||
<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}
|
||||
showsVerticalScrollIndicator={false}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: colors.background,
|
||||
},
|
||||
searchContainer: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
},
|
||||
scannerButton: {
|
||||
marginRight: spacing.md,
|
||||
padding: spacing.sm,
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.md,
|
||||
},
|
||||
list: {
|
||||
paddingBottom: spacing.xl,
|
||||
},
|
||||
errorContainer: {
|
||||
padding: spacing.md,
|
||||
marginHorizontal: spacing.md,
|
||||
backgroundColor: '#F8D7DA',
|
||||
borderRadius: 8,
|
||||
},
|
||||
errorText: {
|
||||
color: '#721C24',
|
||||
textAlign: 'center',
|
||||
},
|
||||
emptyContainer: {
|
||||
padding: spacing.xl,
|
||||
alignItems: 'center',
|
||||
},
|
||||
emptyText: {
|
||||
color: colors.textSecondary,
|
||||
fontSize: 16,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { View, StyleSheet, Text } from 'react-native';
|
||||
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 } from '../../constants/theme';
|
||||
import { Pharmacy } from '../../types';
|
||||
|
||||
export default function MapScreen() {
|
||||
const router = useRouter();
|
||||
const [pharmacies, setPharmacies] = useState<Pharmacy[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [region, setRegion] = useState({
|
||||
latitude: 40.4168, // Madrid default
|
||||
longitude: -3.7038,
|
||||
latitudeDelta: 0.0922,
|
||||
longitudeDelta: 0.0421,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const fetchPharmacies = async () => {
|
||||
try {
|
||||
const data = await getPharmacies();
|
||||
setPharmacies(data);
|
||||
|
||||
// Center map on first pharmacy if available
|
||||
if (data.length > 0) {
|
||||
setRegion({
|
||||
latitude: data[0].latitude,
|
||||
longitude: data[0].longitude,
|
||||
latitudeDelta: 0.0922,
|
||||
longitudeDelta: 0.0421,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching pharmacies:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchPharmacies();
|
||||
}, []);
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingSpinner message="Cargando farmacias..." />;
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<MapView
|
||||
style={styles.map}
|
||||
region={region}
|
||||
onRegionChangeComplete={setRegion}
|
||||
showsUserLocation={true}
|
||||
showsMyLocationButton={true}
|
||||
>
|
||||
{pharmacies.map((pharmacy) => (
|
||||
<Marker
|
||||
key={pharmacy.id}
|
||||
coordinate={{
|
||||
latitude: pharmacy.latitude,
|
||||
longitude: pharmacy.longitude,
|
||||
}}
|
||||
title={pharmacy.name}
|
||||
description={pharmacy.address}
|
||||
onCalloutPress={() => router.push(`/pharmacy/${pharmacy.id}`)}
|
||||
/>
|
||||
))}
|
||||
</MapView>
|
||||
|
||||
<View style={styles.legend}>
|
||||
<Text style={styles.legendText}>
|
||||
{pharmacies.length} farmacias en el mapa
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
},
|
||||
map: {
|
||||
flex: 1,
|
||||
},
|
||||
legend: {
|
||||
position: 'absolute',
|
||||
bottom: spacing.lg,
|
||||
left: spacing.md,
|
||||
right: spacing.md,
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: 8,
|
||||
padding: spacing.sm,
|
||||
alignItems: 'center',
|
||||
shadowColor: '#000',
|
||||
shadowOffset: { width: 0, height: 2 },
|
||||
shadowOpacity: 0.25,
|
||||
shadowRadius: 4,
|
||||
elevation: 5,
|
||||
},
|
||||
legendText: {
|
||||
fontSize: 14,
|
||||
color: colors.text,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
import React from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity, Alert } from 'react-native';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { useAuth } from '../../hooks/useAuth';
|
||||
import { colors, spacing, borderRadius } from '../../constants/theme';
|
||||
|
||||
export default function ProfileScreen() {
|
||||
const router = useRouter();
|
||||
const { user, isAuthenticated, isLoading, logout, isAdmin } = useAuth();
|
||||
|
||||
const handleLogout = async () => {
|
||||
Alert.alert(
|
||||
'Cerrar Sesión',
|
||||
'¿Estás seguro que deseas cerrar sesión?',
|
||||
[
|
||||
{ text: 'Cancelar', style: 'cancel' },
|
||||
{
|
||||
text: 'Cerrar Sesión',
|
||||
style: 'destructive',
|
||||
onPress: async () => {
|
||||
await logout();
|
||||
router.replace('/auth/login');
|
||||
}
|
||||
},
|
||||
]
|
||||
);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Text style={styles.loadingText}>Cargando...</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<View style={styles.authPrompt}>
|
||||
<Ionicons name="person-outline" size={64} color={colors.textSecondary} />
|
||||
<Text style={styles.authTitle}>Inicia Sesión</Text>
|
||||
<Text style={styles.authSubtitle}>
|
||||
Inicia sesión para acceder a todas las funcionalidades
|
||||
</Text>
|
||||
<TouchableOpacity
|
||||
style={styles.button}
|
||||
onPress={() => router.push('/auth/login')}
|
||||
>
|
||||
<Text style={styles.buttonText}>Iniciar Sesión</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity
|
||||
style={styles.linkButton}
|
||||
onPress={() => router.push('/auth/register')}
|
||||
>
|
||||
<Text style={styles.linkText}>Crear cuenta nueva</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<View style={styles.header}>
|
||||
<View style={styles.avatar}>
|
||||
<Ionicons name="person" size={40} color={colors.primary} />
|
||||
</View>
|
||||
<Text style={styles.username}>{user?.username}</Text>
|
||||
{isAdmin && <Text style={styles.adminBadge}>Administrador</Text>}
|
||||
</View>
|
||||
|
||||
<View style={styles.menuSection}>
|
||||
{isAdmin && (
|
||||
<TouchableOpacity style={styles.menuItem}>
|
||||
<Ionicons name="settings" size={24} color={colors.text} />
|
||||
<Text style={styles.menuText}>Panel Admin</Text>
|
||||
<Ionicons name="chevron-forward" size={20} color={colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
|
||||
<TouchableOpacity style={styles.menuItem}>
|
||||
<Ionicons name="heart" size={24} color={colors.text} />
|
||||
<Text style={styles.menuText}>Favoritos</Text>
|
||||
<Ionicons name="chevron-forward" size={20} color={colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
|
||||
<TouchableOpacity style={styles.menuItem}>
|
||||
<Ionicons name="notifications" size={24} color={colors.text} />
|
||||
<Text style={styles.menuText}>Notificaciones</Text>
|
||||
<Ionicons name="chevron-forward" size={20} color={colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
|
||||
<TouchableOpacity style={styles.menuItem}>
|
||||
<Ionicons name="help-circle" size={24} color={colors.text} />
|
||||
<Text style={styles.menuText}>Ayuda</Text>
|
||||
<Ionicons name="chevron-forward" size={20} color={colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
<TouchableOpacity style={styles.logoutButton} onPress={handleLogout}>
|
||||
<Ionicons name="log-out" size={20} color={colors.danger} />
|
||||
<Text style={styles.logoutText}>Cerrar Sesión</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: colors.background,
|
||||
},
|
||||
loadingText: {
|
||||
textAlign: 'center',
|
||||
marginTop: spacing.xxl,
|
||||
color: colors.textSecondary,
|
||||
},
|
||||
authPrompt: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
padding: spacing.xl,
|
||||
},
|
||||
authTitle: {
|
||||
fontSize: 24,
|
||||
fontWeight: 'bold',
|
||||
color: colors.text,
|
||||
marginTop: spacing.lg,
|
||||
},
|
||||
authSubtitle: {
|
||||
fontSize: 16,
|
||||
color: colors.textSecondary,
|
||||
textAlign: 'center',
|
||||
marginTop: spacing.sm,
|
||||
marginBottom: spacing.xl,
|
||||
},
|
||||
header: {
|
||||
alignItems: 'center',
|
||||
padding: spacing.xl,
|
||||
backgroundColor: colors.card,
|
||||
},
|
||||
avatar: {
|
||||
width: 80,
|
||||
height: 80,
|
||||
borderRadius: 40,
|
||||
backgroundColor: colors.background,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
username: {
|
||||
fontSize: 20,
|
||||
fontWeight: 'bold',
|
||||
color: colors.text,
|
||||
marginTop: spacing.md,
|
||||
},
|
||||
adminBadge: {
|
||||
fontSize: 12,
|
||||
color: colors.primary,
|
||||
backgroundColor: '#E3F2FD',
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: spacing.xs,
|
||||
borderRadius: borderRadius.sm,
|
||||
marginTop: spacing.sm,
|
||||
},
|
||||
menuSection: {
|
||||
marginTop: spacing.md,
|
||||
backgroundColor: colors.card,
|
||||
},
|
||||
menuItem: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
padding: spacing.md,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: colors.separator,
|
||||
},
|
||||
menuText: {
|
||||
flex: 1,
|
||||
marginLeft: spacing.md,
|
||||
fontSize: 16,
|
||||
color: colors.text,
|
||||
},
|
||||
button: {
|
||||
backgroundColor: colors.primary,
|
||||
borderRadius: borderRadius.md,
|
||||
paddingVertical: spacing.md,
|
||||
paddingHorizontal: spacing.xl,
|
||||
},
|
||||
buttonText: {
|
||||
color: colors.textInverse,
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
},
|
||||
linkButton: {
|
||||
marginTop: spacing.md,
|
||||
},
|
||||
linkText: {
|
||||
color: colors.primary,
|
||||
fontSize: 14,
|
||||
},
|
||||
logoutButton: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
margin: spacing.xl,
|
||||
padding: spacing.md,
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.md,
|
||||
borderWidth: 1,
|
||||
borderColor: colors.danger,
|
||||
},
|
||||
logoutText: {
|
||||
marginLeft: spacing.sm,
|
||||
color: colors.danger,
|
||||
fontSize: 16,
|
||||
fontWeight: '500',
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { Stack } from 'expo-router';
|
||||
import { StatusBar } from 'expo-status-bar';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { GestureHandlerRootView } from 'react-native-gesture-handler';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { registerForPushNotifications, addNotificationListener, addNotificationResponseListener } from '../services/notifications';
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
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 (
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<Stack>
|
||||
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
|
||||
<Stack.Screen
|
||||
name="medicine/[id]"
|
||||
options={{
|
||||
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>
|
||||
<StatusBar style="auto" />
|
||||
</QueryClientProvider>
|
||||
</GestureHandlerRootView>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
TextInput,
|
||||
TouchableOpacity,
|
||||
StyleSheet,
|
||||
KeyboardAvoidingView,
|
||||
Platform,
|
||||
Alert
|
||||
} from 'react-native';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { colors, spacing, borderRadius } from '../../constants/theme';
|
||||
import {
|
||||
isBiometricsAvailable,
|
||||
authenticateWithBiometrics,
|
||||
saveBiometricCredentials,
|
||||
getBiometricUsername
|
||||
} from '../../services/biometrics';
|
||||
|
||||
export default function LoginScreen() {
|
||||
const router = useRouter();
|
||||
const { login } = useAuthStore();
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
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 () => {
|
||||
if (!username || !password) {
|
||||
Alert.alert('Error', 'Por favor ingresa usuario y contraseña');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await login(username, password);
|
||||
// Save username for biometric login
|
||||
if (biometricsAvailable) {
|
||||
await saveBiometricCredentials(username);
|
||||
}
|
||||
router.replace('/(tabs)');
|
||||
} catch (error) {
|
||||
Alert.alert('Error', 'Credenciales incorrectas');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
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 (
|
||||
<KeyboardAvoidingView
|
||||
style={styles.container}
|
||||
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>
|
||||
|
||||
<View style={styles.inputContainer}>
|
||||
<Text style={styles.label}>Usuario</Text>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
value={username}
|
||||
onChangeText={setUsername}
|
||||
placeholder="Tu usuario"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={styles.inputContainer}>
|
||||
<Text style={styles.label}>Contraseña</Text>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
value={password}
|
||||
onChangeText={setPassword}
|
||||
placeholder="Tu contraseña"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
secureTextEntry
|
||||
/>
|
||||
</View>
|
||||
|
||||
<TouchableOpacity
|
||||
style={[styles.button, isLoading && styles.buttonDisabled]}
|
||||
onPress={handleLogin}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Text style={styles.buttonText}>
|
||||
{isLoading ? 'Ingresando...' : 'Iniciar Sesión'}
|
||||
</Text>
|
||||
</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
|
||||
style={styles.linkButton}
|
||||
onPress={() => router.push('/auth/register')}
|
||||
>
|
||||
<Text style={styles.linkText}>¿No tienes cuenta? Regístrate</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: colors.background,
|
||||
},
|
||||
form: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
padding: spacing.xl,
|
||||
},
|
||||
title: {
|
||||
fontSize: 28,
|
||||
fontWeight: 'bold',
|
||||
color: colors.text,
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
subtitle: {
|
||||
fontSize: 16,
|
||||
color: colors.textSecondary,
|
||||
marginBottom: spacing.xl,
|
||||
},
|
||||
inputContainer: {
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
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,
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
alignItems: 'center',
|
||||
marginTop: spacing.md,
|
||||
},
|
||||
buttonDisabled: {
|
||||
opacity: 0.6,
|
||||
},
|
||||
buttonText: {
|
||||
color: colors.textInverse,
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
},
|
||||
linkButton: {
|
||||
marginTop: spacing.lg,
|
||||
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,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
import React, { useState } from 'react';
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
TextInput,
|
||||
TouchableOpacity,
|
||||
StyleSheet,
|
||||
KeyboardAvoidingView,
|
||||
Platform,
|
||||
Alert
|
||||
} from 'react-native';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { register } from '../../services/auth';
|
||||
import { colors, spacing, borderRadius } from '../../constants/theme';
|
||||
|
||||
export default function RegisterScreen() {
|
||||
const router = useRouter();
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
|
||||
const handleRegister = async () => {
|
||||
if (!username || !password || !confirmPassword) {
|
||||
Alert.alert('Error', 'Por favor completa todos los campos');
|
||||
return;
|
||||
}
|
||||
|
||||
if (password !== confirmPassword) {
|
||||
Alert.alert('Error', 'Las contraseñas no coinciden');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await register(username, password);
|
||||
router.replace('/(tabs)');
|
||||
} catch (error) {
|
||||
Alert.alert('Error', 'No se pudo crear la cuenta');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<KeyboardAvoidingView
|
||||
style={styles.container}
|
||||
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>
|
||||
|
||||
<View style={styles.inputContainer}>
|
||||
<Text style={styles.label}>Usuario</Text>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
value={username}
|
||||
onChangeText={setUsername}
|
||||
placeholder="Elige un usuario"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={styles.inputContainer}>
|
||||
<Text style={styles.label}>Contraseña</Text>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
value={password}
|
||||
onChangeText={setPassword}
|
||||
placeholder="Elige una contraseña"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
secureTextEntry
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={styles.inputContainer}>
|
||||
<Text style={styles.label}>Confirmar Contraseña</Text>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
value={confirmPassword}
|
||||
onChangeText={setConfirmPassword}
|
||||
placeholder="Repite la contraseña"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
secureTextEntry
|
||||
/>
|
||||
</View>
|
||||
|
||||
<TouchableOpacity
|
||||
style={[styles.button, isLoading && styles.buttonDisabled]}
|
||||
onPress={handleRegister}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Text style={styles.buttonText}>
|
||||
{isLoading ? 'Creando cuenta...' : 'Crear Cuenta'}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
|
||||
<TouchableOpacity
|
||||
style={styles.linkButton}
|
||||
onPress={() => router.back()}
|
||||
>
|
||||
<Text style={styles.linkText}>¿Ya tienes cuenta? Inicia sesión</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: colors.background,
|
||||
},
|
||||
form: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
padding: spacing.xl,
|
||||
},
|
||||
title: {
|
||||
fontSize: 28,
|
||||
fontWeight: 'bold',
|
||||
color: colors.text,
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
subtitle: {
|
||||
fontSize: 16,
|
||||
color: colors.textSecondary,
|
||||
marginBottom: spacing.xl,
|
||||
},
|
||||
inputContainer: {
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
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,
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
alignItems: 'center',
|
||||
marginTop: spacing.md,
|
||||
},
|
||||
buttonDisabled: {
|
||||
opacity: 0.6,
|
||||
},
|
||||
buttonText: {
|
||||
color: colors.textInverse,
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
},
|
||||
linkButton: {
|
||||
marginTop: spacing.lg,
|
||||
alignItems: 'center',
|
||||
},
|
||||
linkText: {
|
||||
color: colors.primary,
|
||||
fontSize: 14,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,205 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { View, Text, ScrollView, StyleSheet, TouchableOpacity } from 'react-native';
|
||||
import { useLocalSearchParams, useRouter } from 'expo-router';
|
||||
import { getMedicine, getMedicinePharmacies } from '../../services/medicines';
|
||||
import { StockBadge } from '../../components/StockBadge';
|
||||
import { LoadingSpinner } from '../../components/LoadingSpinner';
|
||||
import { colors, spacing, borderRadius } from '../../constants/theme';
|
||||
import { Medicine, PharmacyMedicine } from '../../types';
|
||||
|
||||
export default function MedicineDetailScreen() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>();
|
||||
const router = useRouter();
|
||||
const [medicine, setMedicine] = useState<Medicine | null>(null);
|
||||
const [pharmacies, setPharmacies] = useState<PharmacyMedicine[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
|
||||
const fetchMedicine = async () => {
|
||||
try {
|
||||
const [medData, pharmData] = await Promise.all([
|
||||
getMedicine(id),
|
||||
getMedicinePharmacies(id),
|
||||
]);
|
||||
setMedicine(medData);
|
||||
setPharmacies(pharmData);
|
||||
} catch (error) {
|
||||
console.error('Error fetching medicine:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchMedicine();
|
||||
}, [id]);
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingSpinner message="Cargando medicamento..." />;
|
||||
}
|
||||
|
||||
if (!medicine) {
|
||||
return (
|
||||
<View style={styles.errorContainer}>
|
||||
<Text style={styles.errorText}>Medicamento no encontrado</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollView style={styles.container}>
|
||||
<View style={styles.header}>
|
||||
<Text style={styles.name}>{medicine.nombre}</Text>
|
||||
<StockBadge stock={medicine.stock} />
|
||||
</View>
|
||||
|
||||
<View style={styles.infoSection}>
|
||||
<InfoRow label="Principio activo" value={medicine.principioActivo} />
|
||||
<InfoRow label="Laboratorio" value={medicine.laboratorio} />
|
||||
<InfoRow label="Forma farmacéutica" value={medicine.formaFarmaceutica} />
|
||||
<InfoRow
|
||||
label="Precio"
|
||||
value={medicine.precio ? `${medicine.precio.toFixed(2)} €` : 'No disponible'}
|
||||
/>
|
||||
<InfoRow label="Registro" value={medicine.nregistro} />
|
||||
</View>
|
||||
|
||||
<View style={styles.pharmaciesSection}>
|
||||
<Text style={styles.sectionTitle}>
|
||||
Farmacias ({pharmacies.length})
|
||||
</Text>
|
||||
|
||||
{pharmacies.length === 0 ? (
|
||||
<Text style={styles.noPharmacies}>No hay farmacias con este medicamento</Text>
|
||||
) : (
|
||||
pharmacies.map((pharm) => (
|
||||
<TouchableOpacity
|
||||
key={pharm.id}
|
||||
style={styles.pharmacyCard}
|
||||
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>
|
||||
))
|
||||
)}
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
function InfoRow({ label, value }: { label: string; value: string }) {
|
||||
return (
|
||||
<View style={styles.infoRow}>
|
||||
<Text style={styles.infoLabel}>{label}</Text>
|
||||
<Text style={styles.infoValue}>{value}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: colors.background,
|
||||
},
|
||||
header: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'flex-start',
|
||||
padding: spacing.md,
|
||||
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.md,
|
||||
},
|
||||
infoRow: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
paddingVertical: spacing.sm,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: colors.separator,
|
||||
},
|
||||
infoLabel: {
|
||||
fontSize: 14,
|
||||
color: colors.textSecondary,
|
||||
},
|
||||
infoValue: {
|
||||
fontSize: 14,
|
||||
color: colors.text,
|
||||
fontWeight: '500',
|
||||
},
|
||||
pharmaciesSection: {
|
||||
marginTop: spacing.sm,
|
||||
padding: spacing.md,
|
||||
},
|
||||
sectionTitle: {
|
||||
fontSize: 18,
|
||||
fontWeight: '600',
|
||||
color: colors.text,
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
noPharmacies: {
|
||||
color: colors.textSecondary,
|
||||
textAlign: 'center',
|
||||
padding: spacing.xl,
|
||||
},
|
||||
pharmacyCard: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
pharmacyInfo: {
|
||||
flex: 1,
|
||||
},
|
||||
pharmacyName: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: colors.text,
|
||||
},
|
||||
pharmacyAddress: {
|
||||
fontSize: 14,
|
||||
color: colors.textSecondary,
|
||||
marginTop: spacing.xs,
|
||||
},
|
||||
pharmacyStock: {
|
||||
alignItems: 'flex-end',
|
||||
},
|
||||
price: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: colors.primary,
|
||||
},
|
||||
stock: {
|
||||
fontSize: 12,
|
||||
color: colors.textSecondary,
|
||||
marginTop: spacing.xs,
|
||||
},
|
||||
errorContainer: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
errorText: {
|
||||
fontSize: 16,
|
||||
color: colors.textSecondary,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,260 @@
|
||||
import React, { useEffect, useState } 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 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 { Pharmacy, PharmacyMedicine } from '../../types';
|
||||
|
||||
export default function PharmacyDetailScreen() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>();
|
||||
const router = useRouter();
|
||||
const [pharmacy, setPharmacy] = useState<Pharmacy | null>(null);
|
||||
const [medicines, setMedicines] = useState<PharmacyMedicine[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
|
||||
const fetchPharmacy = async () => {
|
||||
try {
|
||||
const [pharmData, medData] = await Promise.all([
|
||||
getPharmacy(Number(id)),
|
||||
getPharmacyMedicines(Number(id)),
|
||||
]);
|
||||
setPharmacy(pharmData);
|
||||
setMedicines(medData as PharmacyMedicine[]);
|
||||
} catch (error) {
|
||||
console.error('Error fetching pharmacy:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchPharmacy();
|
||||
}, [id]);
|
||||
|
||||
const handleCall = () => {
|
||||
if (pharmacy?.phone) {
|
||||
Linking.openURL(`tel:${pharmacy.phone}`);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDirections = () => {
|
||||
if (pharmacy) {
|
||||
const url = `https://www.google.com/maps/dir/?api=1&destination=${pharmacy.latitude},${pharmacy.longitude}`;
|
||||
Linking.openURL(url);
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingSpinner message="Cargando farmacia..." />;
|
||||
}
|
||||
|
||||
if (!pharmacy) {
|
||||
return (
|
||||
<View style={styles.errorContainer}>
|
||||
<Text style={styles.errorText}>Farmacia no encontrada</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollView style={styles.container}>
|
||||
<View style={styles.header}>
|
||||
<Text style={styles.name}>{pharmacy.name}</Text>
|
||||
</View>
|
||||
|
||||
<View style={styles.actionsRow}>
|
||||
<TouchableOpacity style={styles.actionButton} onPress={handleCall}>
|
||||
<Ionicons name="call" size={20} color={colors.primary} />
|
||||
<Text style={styles.actionText}>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>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
<View style={styles.infoSection}>
|
||||
<View style={styles.infoRow}>
|
||||
<Ionicons name="location" size={18} color={colors.textSecondary} />
|
||||
<Text style={styles.infoText}>{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>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
|
||||
<View style={styles.mapContainer}>
|
||||
<MapView
|
||||
style={styles.map}
|
||||
initialRegion={{
|
||||
latitude: pharmacy.latitude,
|
||||
longitude: pharmacy.longitude,
|
||||
latitudeDelta: 0.01,
|
||||
longitudeDelta: 0.01,
|
||||
}}
|
||||
scrollEnabled={false}
|
||||
>
|
||||
<Marker
|
||||
coordinate={{
|
||||
latitude: pharmacy.latitude,
|
||||
longitude: pharmacy.longitude,
|
||||
}}
|
||||
title={pharmacy.name}
|
||||
/>
|
||||
</MapView>
|
||||
</View>
|
||||
|
||||
<View style={styles.medicinesSection}>
|
||||
<Text style={styles.sectionTitle}>
|
||||
Medicamentos ({medicines.length})
|
||||
</Text>
|
||||
|
||||
{medicines.length === 0 ? (
|
||||
<Text style={styles.noMedicines}>No hay medicamentos disponibles</Text>
|
||||
) : (
|
||||
medicines.map((med) => (
|
||||
<TouchableOpacity
|
||||
key={med.id}
|
||||
style={styles.medicineCard}
|
||||
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>
|
||||
</View>
|
||||
<View style={styles.medicineStock}>
|
||||
<Text style={styles.price}>{med.price.toFixed(2)} €</Text>
|
||||
<Text style={styles.stock}>Stock: {med.stock}</Text>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
))
|
||||
)}
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
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',
|
||||
alignItems: 'center',
|
||||
padding: spacing.sm,
|
||||
},
|
||||
actionText: {
|
||||
marginLeft: spacing.xs,
|
||||
color: colors.primary,
|
||||
fontWeight: '500',
|
||||
},
|
||||
infoSection: {
|
||||
padding: spacing.md,
|
||||
backgroundColor: colors.card,
|
||||
marginTop: spacing.sm,
|
||||
},
|
||||
infoRow: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'flex-start',
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
infoText: {
|
||||
flex: 1,
|
||||
marginLeft: spacing.sm,
|
||||
fontSize: 16,
|
||||
color: colors.text,
|
||||
},
|
||||
mapContainer: {
|
||||
height: 200,
|
||||
marginTop: spacing.sm,
|
||||
},
|
||||
map: {
|
||||
flex: 1,
|
||||
},
|
||||
medicinesSection: {
|
||||
marginTop: spacing.sm,
|
||||
padding: spacing.md,
|
||||
},
|
||||
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,
|
||||
},
|
||||
medicineInfo: {
|
||||
flex: 1,
|
||||
},
|
||||
medicineName: {
|
||||
fontSize: 16,
|
||||
fontWeight: '500',
|
||||
color: colors.text,
|
||||
},
|
||||
medicineNregistro: {
|
||||
fontSize: 12,
|
||||
color: colors.textSecondary,
|
||||
marginTop: spacing.xs,
|
||||
},
|
||||
medicineStock: {
|
||||
alignItems: 'flex-end',
|
||||
},
|
||||
price: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: colors.primary,
|
||||
},
|
||||
stock: {
|
||||
fontSize: 12,
|
||||
color: colors.textSecondary,
|
||||
marginTop: spacing.xs,
|
||||
},
|
||||
errorContainer: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
errorText: {
|
||||
fontSize: 16,
|
||||
color: colors.textSecondary,
|
||||
},
|
||||
});
|
||||
@@ -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,
|
||||
},
|
||||
});
|
||||
|
After Width: | Height: | Size: 384 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 1.1 KiB |
|
After Width: | Height: | Size: 384 KiB |
|
After Width: | Height: | Size: 384 KiB |
|
After Width: | Height: | Size: 17 KiB |
|
After Width: | Height: | Size: 384 KiB |
@@ -0,0 +1,7 @@
|
||||
module.exports = function(api) {
|
||||
api.cache(true);
|
||||
return {
|
||||
presets: ['babel-preset-expo'],
|
||||
plugins: ['react-native-reanimated/plugin'],
|
||||
};
|
||||
};
|
||||
@@ -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',
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import React from 'react';
|
||||
import { View, ActivityIndicator, Text, StyleSheet } from 'react-native';
|
||||
import { colors, spacing } from '../constants/theme';
|
||||
|
||||
interface LoadingSpinnerProps {
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export function LoadingSpinner({ message = 'Cargando...' }: LoadingSpinnerProps) {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<ActivityIndicator size="large" color={colors.primary} />
|
||||
<Text style={styles.message}>{message}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
padding: spacing.xl,
|
||||
},
|
||||
message: {
|
||||
marginTop: spacing.md,
|
||||
fontSize: 16,
|
||||
color: colors.textSecondary,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import React from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { colors, spacing, borderRadius } from '../constants/theme';
|
||||
import { StockBadge } from './StockBadge';
|
||||
import { Medicine } from '../types';
|
||||
|
||||
interface MedicineCardProps {
|
||||
medicine: Medicine;
|
||||
}
|
||||
|
||||
export function MedicineCard({ medicine }: MedicineCardProps) {
|
||||
const router = useRouter();
|
||||
|
||||
const handlePress = () => {
|
||||
router.push(`/medicine/${medicine.nregistro}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<TouchableOpacity style={styles.card} onPress={handlePress} activeOpacity={0.7}>
|
||||
<View style={styles.header}>
|
||||
<Text style={styles.name} numberOfLines={2}>
|
||||
{medicine.nombre}
|
||||
</Text>
|
||||
<StockBadge stock={medicine.stock} />
|
||||
</View>
|
||||
|
||||
<Text style={styles.principioActivo} numberOfLines={1}>
|
||||
{medicine.principioActivo}
|
||||
</Text>
|
||||
|
||||
<View style={styles.footer}>
|
||||
<View style={styles.priceContainer}>
|
||||
<Ionicons name="pricetag" size={14} color={colors.textSecondary} />
|
||||
<Text style={styles.price}>
|
||||
{medicine.precio ? `${medicine.precio.toFixed(2)} €` : 'Sin precio'}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<View style={styles.labContainer}>
|
||||
<Ionicons name="business" size={14} color={colors.textSecondary} />
|
||||
<Text style={styles.laboratorio} numberOfLines={1}>
|
||||
{medicine.laboratorio}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
card: {
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
marginHorizontal: spacing.md,
|
||||
marginVertical: spacing.xs,
|
||||
shadowColor: '#000',
|
||||
shadowOffset: { width: 0, height: 2 },
|
||||
shadowOpacity: 0.1,
|
||||
shadowRadius: 4,
|
||||
elevation: 2,
|
||||
},
|
||||
header: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'flex-start',
|
||||
marginBottom: spacing.xs,
|
||||
},
|
||||
name: {
|
||||
flex: 1,
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: colors.text,
|
||||
marginRight: spacing.sm,
|
||||
},
|
||||
principioActivo: {
|
||||
fontSize: 14,
|
||||
color: colors.textSecondary,
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
footer: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
},
|
||||
priceContainer: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
},
|
||||
price: {
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
color: colors.text,
|
||||
marginLeft: spacing.xs,
|
||||
},
|
||||
labContainer: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
flex: 1,
|
||||
justifyContent: 'flex-end',
|
||||
},
|
||||
laboratorio: {
|
||||
fontSize: 12,
|
||||
color: colors.textSecondary,
|
||||
marginLeft: spacing.xs,
|
||||
maxWidth: 120,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import React, { useState } from 'react';
|
||||
import { View, TextInput, StyleSheet, TouchableOpacity } from 'react-native';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { colors, spacing, borderRadius } from '../constants/theme';
|
||||
|
||||
interface SearchBarProps {
|
||||
placeholder?: string;
|
||||
onSearch: (query: string) => void;
|
||||
value?: string;
|
||||
onChangeText?: (text: string) => void;
|
||||
}
|
||||
|
||||
export function SearchBar({
|
||||
placeholder = 'Buscar medicamentos...',
|
||||
onSearch,
|
||||
value,
|
||||
onChangeText
|
||||
}: SearchBarProps) {
|
||||
const [localValue, setLocalValue] = useState(value || '');
|
||||
|
||||
const handleChange = (text: string) => {
|
||||
setLocalValue(text);
|
||||
onChangeText?.(text);
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
onSearch(localValue);
|
||||
};
|
||||
|
||||
const handleClear = () => {
|
||||
setLocalValue('');
|
||||
onChangeText?.('');
|
||||
onSearch('');
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Ionicons name="search" size={20} color={colors.textSecondary} style={styles.icon} />
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
placeholder={placeholder}
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
value={localValue}
|
||||
onChangeText={handleChange}
|
||||
onSubmitEditing={handleSubmit}
|
||||
returnKeyType="search"
|
||||
autoCorrect={false}
|
||||
/>
|
||||
{localValue.length > 0 && (
|
||||
<TouchableOpacity onPress={handleClear} style={styles.clearButton}>
|
||||
<Ionicons name="close-circle" size={20} color={colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.md,
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: spacing.sm,
|
||||
marginHorizontal: spacing.md,
|
||||
marginVertical: spacing.sm,
|
||||
},
|
||||
icon: {
|
||||
marginRight: spacing.sm,
|
||||
},
|
||||
input: {
|
||||
flex: 1,
|
||||
fontSize: 16,
|
||||
color: colors.text,
|
||||
paddingVertical: spacing.xs,
|
||||
},
|
||||
clearButton: {
|
||||
marginLeft: spacing.sm,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import React from 'react';
|
||||
import { View, Text, StyleSheet } from 'react-native';
|
||||
import { colors, 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 getText = () => {
|
||||
if (stock === 0) return 'Sin stock';
|
||||
if (stock < 5) return `Bajo (${stock})`;
|
||||
return `Disponible (${stock})`;
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={[styles.badge, getBadgeStyle()]}>
|
||||
<Text style={styles.text}>{getText()}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
badge: {
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: spacing.xs,
|
||||
borderRadius: borderRadius.sm,
|
||||
},
|
||||
success: {
|
||||
backgroundColor: '#D4EDDA',
|
||||
},
|
||||
warning: {
|
||||
backgroundColor: '#FFF3CD',
|
||||
},
|
||||
danger: {
|
||||
backgroundColor: '#F8D7DA',
|
||||
},
|
||||
text: {
|
||||
fontSize: 12,
|
||||
fontWeight: '600',
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
import Constants from 'expo-constants';
|
||||
|
||||
const ENV = {
|
||||
development: {
|
||||
API_BASE_URL: 'http://localhost:3001/api',
|
||||
},
|
||||
production: {
|
||||
API_BASE_URL: 'https://your-production-api.com/api',
|
||||
},
|
||||
};
|
||||
|
||||
const environment = Constants.expoConfig?.extra?.environment || (__DEV__ ? 'development' : 'production');
|
||||
|
||||
export const config = {
|
||||
API_BASE_URL: ENV[environment as keyof typeof ENV]?.API_BASE_URL || ENV.development.API_BASE_URL,
|
||||
SEARCH_DEBOUNCE_MS: 300,
|
||||
CACHE_STALE_TIME: 5 * 60 * 1000, // 5 minutes
|
||||
CACHE_CACHE_TIME: 30 * 60 * 1000, // 30 minutes
|
||||
};
|
||||
@@ -0,0 +1,58 @@
|
||||
export const colors = {
|
||||
// Primary
|
||||
primary: '#007AFF',
|
||||
primaryLight: '#4DA3FF',
|
||||
primaryDark: '#0056CC',
|
||||
|
||||
// Semantic
|
||||
success: '#34C759',
|
||||
danger: '#FF3B30',
|
||||
warning: '#FF9500',
|
||||
|
||||
// Neutral
|
||||
background: '#F2F2F7',
|
||||
card: '#FFFFFF',
|
||||
border: '#E5E5EA',
|
||||
separator: '#C6C6C8',
|
||||
|
||||
// Text
|
||||
text: '#1C1C1E',
|
||||
textSecondary: '#8E8E93',
|
||||
textInverse: '#FFFFFF',
|
||||
textLink: '#007AFF',
|
||||
};
|
||||
|
||||
export const spacing = {
|
||||
xs: 4,
|
||||
sm: 8,
|
||||
md: 16,
|
||||
lg: 24,
|
||||
xl: 32,
|
||||
xxl: 48,
|
||||
};
|
||||
|
||||
export const borderRadius = {
|
||||
sm: 8,
|
||||
md: 12,
|
||||
lg: 16,
|
||||
xl: 24,
|
||||
};
|
||||
|
||||
export const typography = {
|
||||
title: {
|
||||
fontSize: 28,
|
||||
fontWeight: 'bold' as const,
|
||||
},
|
||||
heading: {
|
||||
fontSize: 20,
|
||||
fontWeight: '600' as const,
|
||||
},
|
||||
body: {
|
||||
fontSize: 16,
|
||||
fontWeight: 'normal' as const,
|
||||
},
|
||||
caption: {
|
||||
fontSize: 12,
|
||||
fontWeight: 'normal' as const,
|
||||
},
|
||||
};
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
|
||||
export function useAuth() {
|
||||
const { user, isLoading, isAuthenticated, login, logout, checkAuth } = useAuthStore();
|
||||
|
||||
useEffect(() => {
|
||||
checkAuth();
|
||||
}, []);
|
||||
|
||||
return {
|
||||
user,
|
||||
isLoading,
|
||||
isAuthenticated,
|
||||
login,
|
||||
logout,
|
||||
isAdmin: user?.is_admin ?? false,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
export function useDebounce<T>(value: T, delay: number): T {
|
||||
const [debouncedValue, setDebouncedValue] = useState<T>(value);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
setDebouncedValue(value);
|
||||
}, delay);
|
||||
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [value, delay]);
|
||||
|
||||
return debouncedValue;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { registerRootComponent } from 'expo';
|
||||
|
||||
import App from './App';
|
||||
|
||||
// registerRootComponent calls AppRegistry.registerComponent('main', () => App);
|
||||
// It also ensures that whether you load the app in Expo Go or in a native build,
|
||||
// the environment is set up appropriately
|
||||
registerRootComponent(App);
|
||||
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "frontend-mobile",
|
||||
"version": "1.0.0",
|
||||
"main": "expo-router/entry",
|
||||
"dependencies": {
|
||||
"@react-native-async-storage/async-storage": "2.2.0",
|
||||
"@tanstack/react-query": "^5.101.2",
|
||||
"axios": "^1.18.1",
|
||||
"babel-preset-expo": "^57.0.1",
|
||||
"expo": "~57.0.2",
|
||||
"expo-camera": "~57.0.0",
|
||||
"expo-constants": "~57.0.3",
|
||||
"expo-dev-client": "~57.0.5",
|
||||
"expo-device": "~7.0.2",
|
||||
"expo-linking": "~57.0.1",
|
||||
"expo-local-authentication": "~57.0.0",
|
||||
"expo-notifications": "~57.0.3",
|
||||
"expo-router": "~57.0.3",
|
||||
"expo-secure-store": "~57.0.0",
|
||||
"expo-status-bar": "~57.0.0",
|
||||
"react": "19.2.7",
|
||||
"react-native": "0.86.0",
|
||||
"react-native-gesture-handler": "~2.32.0",
|
||||
"react-native-maps": "^1.29.0",
|
||||
"react-native-reanimated": "4.5.0",
|
||||
"react-native-safe-area-context": "~5.7.0",
|
||||
"react-native-screens": "4.25.2",
|
||||
"react-native-worklets": "0.10.0",
|
||||
"zustand": "^5.0.14"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "~19.2.7",
|
||||
"typescript": "~6.0.3"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "expo start",
|
||||
"android": "expo start --android",
|
||||
"ios": "expo start --ios",
|
||||
"web": "expo start --web"
|
||||
},
|
||||
"private": true
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import axios from 'axios';
|
||||
import * as SecureStore from 'expo-secure-store';
|
||||
import { config } from '../constants/config';
|
||||
|
||||
export const api = axios.create({
|
||||
baseURL: config.API_BASE_URL,
|
||||
timeout: 10000,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
// Request interceptor - add auth token
|
||||
api.interceptors.request.use(
|
||||
async (axiosConfig) => {
|
||||
const token = await SecureStore.getItemAsync('auth_token');
|
||||
if (token) {
|
||||
axiosConfig.headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
return axiosConfig;
|
||||
},
|
||||
(error) => Promise.reject(error)
|
||||
);
|
||||
|
||||
// Response interceptor - handle errors
|
||||
api.interceptors.response.use(
|
||||
(response) => response,
|
||||
async (error) => {
|
||||
if (error.response?.status === 401) {
|
||||
await SecureStore.deleteItemAsync('auth_token');
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
export default api;
|
||||
@@ -0,0 +1,43 @@
|
||||
import api from './api';
|
||||
import * as SecureStore from 'expo-secure-store';
|
||||
import { AuthResponse, User } from '../types';
|
||||
|
||||
export async function login(username: string, password: string): Promise<AuthResponse> {
|
||||
const response = await api.post('/auth/login', { username, password });
|
||||
const { user, token } = response.data;
|
||||
|
||||
await SecureStore.setItemAsync('auth_token', token);
|
||||
await SecureStore.setItemAsync('user', 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');
|
||||
}
|
||||
|
||||
export async function checkAuth(): Promise<User | null> {
|
||||
try {
|
||||
const response = await api.get('/auth/check');
|
||||
return response.data.user;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getStoredUser(): Promise<User | null> {
|
||||
const userStr = await SecureStore.getItemAsync('user');
|
||||
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;
|
||||
|
||||
await SecureStore.setItemAsync('auth_token', token);
|
||||
await SecureStore.setItemAsync('user', JSON.stringify(user));
|
||||
|
||||
return response.data;
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import api from './api';
|
||||
import { Medicine, PharmacyMedicine } from '../types';
|
||||
|
||||
export async function searchMedicines(query: string): Promise<Medicine[]> {
|
||||
const response = await api.get(`/medicines/search?q=${encodeURIComponent(query)}`);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function getMedicine(nregistro: string): Promise<Medicine> {
|
||||
const response = await api.get(`/medicines/${nregistro}`);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function getMedicinePharmacies(nregistro: string): Promise<PharmacyMedicine[]> {
|
||||
const response = await api.get(`/medicines/${nregistro}/pharmacies`);
|
||||
return response.data;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import api from './api';
|
||||
import { Pharmacy } from '../types';
|
||||
|
||||
export async function getPharmacies(): Promise<Pharmacy[]> {
|
||||
const response = await api.get('/pharmacies');
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function getPharmacy(id: number): Promise<Pharmacy> {
|
||||
const response = await api.get(`/pharmacies/${id}`);
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function getPharmacyMedicines(id: number): Promise<any[]> {
|
||||
const response = await api.get(`/pharmacies/${id}/medicines`);
|
||||
return response.data;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { create } from 'zustand';
|
||||
import { User } from '../types';
|
||||
import * as authService from '../services/auth';
|
||||
|
||||
interface AuthState {
|
||||
user: User | null;
|
||||
isLoading: boolean;
|
||||
isAuthenticated: boolean;
|
||||
login: (username: string, password: string) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
checkAuth: () => Promise<void>;
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>((set) => ({
|
||||
user: null,
|
||||
isLoading: true,
|
||||
isAuthenticated: false,
|
||||
|
||||
login: async (username: string, password: string) => {
|
||||
const { user } = await authService.login(username, password);
|
||||
set({ user, isAuthenticated: true });
|
||||
},
|
||||
|
||||
logout: async () => {
|
||||
await authService.logout();
|
||||
set({ user: null, isAuthenticated: false });
|
||||
},
|
||||
|
||||
checkAuth: async () => {
|
||||
set({ isLoading: true });
|
||||
const user = await authService.checkAuth() || await authService.getStoredUser();
|
||||
set({
|
||||
user,
|
||||
isAuthenticated: !!user,
|
||||
isLoading: false
|
||||
});
|
||||
},
|
||||
}));
|
||||
@@ -0,0 +1,27 @@
|
||||
import { create } from 'zustand';
|
||||
import { Medicine } from '../types';
|
||||
|
||||
interface SearchState {
|
||||
query: string;
|
||||
results: Medicine[];
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
setQuery: (query: string) => void;
|
||||
setResults: (results: Medicine[]) => void;
|
||||
setLoading: (loading: boolean) => void;
|
||||
setError: (error: string | null) => void;
|
||||
clearResults: () => void;
|
||||
}
|
||||
|
||||
export const useSearchStore = create<SearchState>((set) => ({
|
||||
query: '',
|
||||
results: [],
|
||||
isLoading: false,
|
||||
error: null,
|
||||
|
||||
setQuery: (query) => set({ query }),
|
||||
setResults: (results) => set({ results, isLoading: false }),
|
||||
setLoading: (isLoading) => set({ isLoading }),
|
||||
setError: (error) => set({ error, isLoading: false }),
|
||||
clearResults: () => set({ results: [], query: '', error: null }),
|
||||
}));
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"extends": "expo/tsconfig.base",
|
||||
"compilerOptions": {
|
||||
"strict": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"./*"
|
||||
]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"**/*.ts",
|
||||
"**/*.tsx"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
export interface Medicine {
|
||||
nregistro: string;
|
||||
nombre: string;
|
||||
principioActivo: string;
|
||||
laboratorio: string;
|
||||
formaFarmaceutica: string;
|
||||
precio: number | null;
|
||||
stock: number;
|
||||
disponibilidad: 'disponible' | 'sin_stock' | 'bajo_stock';
|
||||
}
|
||||
|
||||
export interface Pharmacy {
|
||||
id: number;
|
||||
name: string;
|
||||
address: string;
|
||||
phone: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
}
|
||||
|
||||
export interface PharmacyMedicine {
|
||||
id: number;
|
||||
pharmacy_id: number;
|
||||
medicine_nregistro: string;
|
||||
medicine_name: string;
|
||||
price: number;
|
||||
stock: number;
|
||||
pharmacy?: Pharmacy;
|
||||
}
|
||||
|
||||
export interface User {
|
||||
id: number;
|
||||
username: string;
|
||||
is_admin: boolean;
|
||||
}
|
||||
|
||||
export interface AuthResponse {
|
||||
user: User;
|
||||
token: string;
|
||||
}
|
||||
|
||||
export interface SearchResponse {
|
||||
medicines: Medicine[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
data: T;
|
||||
success: boolean;
|
||||
error?: string;
|
||||
}
|
||||
@@ -7,11 +7,17 @@
|
||||
"dev": "npm-run-all --parallel dev:backend dev:frontend",
|
||||
"dev:backend": "npm run dev --prefix backend",
|
||||
"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:backend": "npm start --prefix backend",
|
||||
"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: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:copy": "npm run build:web && cap copy",
|
||||
"cap:open:android": "cap open android",
|
||||
|
||||