Compare commits
76 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8bf0b33249 | |||
| f921b15d67 | |||
| 59edc7fbf1 | |||
| 731a6c98ae | |||
| 31c1a14343 | |||
| 25ebb899e9 | |||
| 2e3ce44e7b | |||
| 20debdb023 | |||
| 452a835b64 | |||
| f1b0eab11d | |||
| ee23f61057 | |||
| 26f309acfb | |||
| 4df1594b3b | |||
| 981f3bd3db | |||
| 83920ae57c | |||
| 7b1636a96e | |||
| bb2dbbab3a | |||
| d5b23aa94a | |||
| 9e786f2966 | |||
| a709deb893 | |||
| 229e1d8106 | |||
| f2a5dc4ca3 | |||
| d62e5976ce | |||
| d6f4164dae | |||
| 2713be85a3 | |||
| 0c43d32cf1 | |||
| a00cfe949c | |||
| 2a7ab64bbf | |||
| bf519e43c9 | |||
| d371fd2bb7 | |||
| 02cab5f740 | |||
| 8b9b7e8444 | |||
| f58b4427a8 | |||
| ec2416613c | |||
| 2f36ef685d | |||
| e9a1d7c53d | |||
| 2e9b2f2c1f | |||
| 5f604b11ba | |||
| 16fea2de8f | |||
| 302d574220 | |||
| 411d6604a9 | |||
| d6db48b695 | |||
| a3cea35b13 | |||
| 0099aab093 | |||
| fe08dd512e | |||
| 6612c8b10c | |||
| aae3ac04af | |||
| 69ef048388 | |||
| a7834607fb | |||
| ce3cca1d79 | |||
| c5d47ddd4d | |||
| 562ede1961 | |||
| a65f1a6293 | |||
| 9949b85001 | |||
| 69d66729aa | |||
| a58ce306bf | |||
| 7eb791f181 | |||
| 439e0830a5 | |||
| fc12582814 | |||
| e2bd726663 | |||
| 006fae43d4 | |||
| 071ed91e43 | |||
| c5a074187b | |||
| afaa4de385 | |||
| 6f6c117db2 | |||
| 4404db62ee | |||
| 166e9635a1 | |||
| b5e5edda30 | |||
| fe22e6ee9b | |||
| c5417ff787 | |||
| b899d9a297 | |||
| c46a3ee7ea | |||
| 4f36820d34 | |||
| eb3cde67eb | |||
| bc8b9ecd31 | |||
| 86a4e119b0 |
@@ -7,14 +7,36 @@ on:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
detect-changes:
|
||||
name: Detect Changes
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
backend: ${{ steps.filter.outputs.backend }}
|
||||
frontend: ${{ steps.filter.outputs.frontend }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dorny/paths-filter@v3
|
||||
id: filter
|
||||
with:
|
||||
filters: |
|
||||
backend:
|
||||
- 'apps/backend/**'
|
||||
- 'packages/**'
|
||||
frontend:
|
||||
- 'apps/frontend/**'
|
||||
- 'packages/**'
|
||||
|
||||
test-backend:
|
||||
name: Backend Tests
|
||||
needs: detect-changes
|
||||
if: needs.detect-changes.outputs.backend == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
@@ -22,13 +44,16 @@ jobs:
|
||||
run: npm test --workspace=farma-clic-backend -- --ci
|
||||
|
||||
test-frontend:
|
||||
name: Frontend Tests
|
||||
needs: detect-changes
|
||||
if: needs.detect-changes.outputs.frontend == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
@@ -36,7 +61,12 @@ jobs:
|
||||
run: npm test --workspace=farma-clic-frontend -- --run --reporter=basic
|
||||
|
||||
build-backend:
|
||||
needs: [ test-backend, test-frontend ]
|
||||
name: Build Backend
|
||||
needs: [ detect-changes, test-backend ]
|
||||
if: |
|
||||
always() &&
|
||||
needs.detect-changes.outputs.backend == 'true' &&
|
||||
(needs.test-backend.result == 'success' || needs.test-backend.result == 'skipped')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -57,7 +87,12 @@ jobs:
|
||||
git.hacecalor.net/ichitux/farmafinder-backend:${{ gitea.sha }}
|
||||
|
||||
build-frontend:
|
||||
needs: [ test-backend, test-frontend ]
|
||||
name: Build Frontend
|
||||
needs: [ detect-changes, test-frontend ]
|
||||
if: |
|
||||
always() &&
|
||||
needs.detect-changes.outputs.frontend == 'true' &&
|
||||
(needs.test-frontend.result == 'success' || needs.test-frontend.result == 'skipped')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -77,7 +112,13 @@ jobs:
|
||||
git.hacecalor.net/ichitux/farmafinder-frontend:${{ gitea.sha }}
|
||||
|
||||
deploy:
|
||||
needs: [ build-backend, build-frontend ]
|
||||
name: Deploy
|
||||
needs: [ detect-changes, build-backend, build-frontend ]
|
||||
if: |
|
||||
always() &&
|
||||
(needs.build-backend.result == 'success' || needs.build-backend.result == 'skipped') &&
|
||||
(needs.build-frontend.result == 'success' || needs.build-frontend.result == 'skipped') &&
|
||||
(needs.detect-changes.outputs.backend == 'true' || needs.detect-changes.outputs.frontend == 'true')
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: SSH to remote server
|
||||
@@ -89,5 +130,7 @@ jobs:
|
||||
port: ${{ secrets.PORT }}
|
||||
script: |
|
||||
cd /docker/FarmaFinder
|
||||
git pull
|
||||
docker compose pull
|
||||
docker compose down --remove-orphans
|
||||
docker compose up -d
|
||||
|
||||
@@ -6,8 +6,33 @@ on:
|
||||
- 'main'
|
||||
|
||||
jobs:
|
||||
detect-changes:
|
||||
name: Detect Changes
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
backend: ${{ steps.filter.outputs.backend }}
|
||||
frontend: ${{ steps.filter.outputs.frontend }}
|
||||
frontend-mobile: ${{ steps.filter.outputs.frontend-mobile }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dorny/paths-filter@v3
|
||||
id: filter
|
||||
with:
|
||||
filters: |
|
||||
backend:
|
||||
- 'apps/backend/**'
|
||||
- 'packages/**'
|
||||
frontend:
|
||||
- 'apps/frontend/**'
|
||||
- 'packages/**'
|
||||
frontend-mobile:
|
||||
- 'apps/frontend-mobile/**'
|
||||
- 'packages/**'
|
||||
|
||||
test-backend:
|
||||
name: Backend Tests
|
||||
needs: detect-changes
|
||||
if: needs.detect-changes.outputs.backend == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
@@ -16,7 +41,7 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install Dependencies
|
||||
@@ -27,6 +52,8 @@ jobs:
|
||||
|
||||
test-frontend:
|
||||
name: Frontend Tests
|
||||
needs: detect-changes
|
||||
if: needs.detect-changes.outputs.frontend == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
@@ -35,7 +62,7 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install Dependencies
|
||||
@@ -43,3 +70,25 @@ jobs:
|
||||
|
||||
- name: Run Frontend Tests
|
||||
run: npm test --workspace=farma-clic-frontend -- --run --reporter=basic
|
||||
|
||||
test-frontend-mobile:
|
||||
name: Frontend Mobile Tests
|
||||
needs: detect-changes
|
||||
if: needs.detect-changes.outputs.frontend-mobile == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install Dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Run Frontend Mobile Tests
|
||||
run: npm test --workspace=frontend-mobile -- --ci
|
||||
continue-on-error: true
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
{"pid":596137,"startedAt":1783946773113}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"$schema": "https://mimo.xiaomi.com/mimocode/config.json",
|
||||
"mcp": {
|
||||
"n8n": {
|
||||
"type": "remote",
|
||||
"url": "https://n8n.hacecalor.net/mcp-server/http",
|
||||
"headers": {
|
||||
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJjNDE1ODI4Yy00ZWU0LTQ1MjEtOGQ3Mi0xODZmYWNjNGU4ZmEiLCJpc3MiOiJuOG4iLCJhdWQiOiJtY3Atc2VydmVyLWFwaSIsImp0aSI6ImU1YzUyNjIxLTExZDAtNDM4MC04YmRjLTlhMmQ2MDA1OGU4OSIsImlhdCI6MTc4Mzk0NjY3Mn0._0LG3CJJjUg7-g1kvMjME5nBjIEWkrfEeAZrhDxpfC4"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
# Plan: Dark Mode para FarmaFinder Mobile
|
||||
|
||||
## Objetivo
|
||||
Añadir soporte de modo oscuro a la app móvil con:
|
||||
- Detección automática del modo oscuro del sistema
|
||||
- Toggle manual en la pantalla de perfil (Configuración)
|
||||
- Persistencia de la preferencia del usuario
|
||||
|
||||
## Arquitectura
|
||||
|
||||
### 1. Theme Store (Zustand + AsyncStorage)
|
||||
**Nuevo archivo: `store/themeStore.ts`**
|
||||
|
||||
- Estado: `mode: 'light' | 'dark' | 'system'`
|
||||
- Persistencia con `@react-native-async-storage/async-storage`
|
||||
- Acciones: `setMode()`, `init()` (carga del storage al arrancar)
|
||||
- Por defecto: `'system'` (respeta el dispositivo)
|
||||
|
||||
### 2. Hook `useThemeColor`
|
||||
**Nuevo archivo: `hooks/useThemeColor.ts`**
|
||||
|
||||
- Usa `useColorScheme()` de React Native para detectar el color del sistema
|
||||
- Combina con el `mode` del themeStore para determinar el tema efectivo
|
||||
- Retorna el objeto `colors` apropiado (light o dark)
|
||||
- Los componentes consumirán este hook en vez de importar `colors` directamente
|
||||
|
||||
### 3. Paleta de colores oscura
|
||||
**Modificar: `constants/theme.ts`**
|
||||
|
||||
Añadir exportación `darkColors` con la paleta oscura:
|
||||
|
||||
| Token | Light (actual) | Dark (nuevo) |
|
||||
|---|---|---|
|
||||
| `background` | `#fbfbfb` | `#121212` |
|
||||
| `card` | `#ffffff` | `#1e1e1e` |
|
||||
| `surfaceLow` | `#f2f4f5` | `#2a2a2a` |
|
||||
| `surface` | `#eceeef` | `#333333` |
|
||||
| `surfaceHigh` | `#e6e8e9` | `#3a3a3a` |
|
||||
| `border` | `#c0c9bb` | `#3a3a3a` |
|
||||
| `separator` | `#c0c9bb` | `#3a3a3a` |
|
||||
| `text` | `#111417` | `#f0f0f0` |
|
||||
| `textSecondary` | `#41493e` | `#a0a0a0` |
|
||||
| `textInverse` | `#ffffff` | `#111417` |
|
||||
| `primaryContainer` | `#cfead0` | `#1a3a1c` |
|
||||
| `onPrimaryContainer` | `#0d2b12` | `#cfead0` |
|
||||
| `secondaryContainer` | `#dbe7ff` | `#1a2a4a` |
|
||||
| `tertiaryContainer` | `#efe7ff` | `#2a1a4a` |
|
||||
| `dangerContainer` | `#feecec` | `#3a1a1a` |
|
||||
| `accentWarm` | `#f5a97a` | `#f5a97a` (sin cambio) |
|
||||
| `primary`, `secondary`, `tertiary`, `scanButton`, `success`, `danger`, `warning` | (sin cambios) | (sin cambios) |
|
||||
|
||||
### 4. Provider wrapper
|
||||
**Nuevo archivo: `components/ThemeProvider.tsx`**
|
||||
|
||||
- Lee el `mode` del themeStore y el `useColorScheme()` del sistema
|
||||
- Calcula el tema efectivo (`light` o `dark`)
|
||||
- Provee `colors` y `isDark` vía React Context
|
||||
- Carga la preferencia guardada en AsyncStorage al montar
|
||||
|
||||
### 5. Integración en Root Layout
|
||||
**Modificar: `app/_layout.tsx`**
|
||||
|
||||
- Envolver toda la app con `<ThemeProvider>`
|
||||
- El `StatusBar` se ajusta: `style={isDark ? 'light' : 'auto'}`
|
||||
- Los colores del Stack header se leen del contexto
|
||||
|
||||
### 6. Toggle en el perfil
|
||||
**Modificar: `app/(tabs)/profile.tsx`**
|
||||
|
||||
Añadir en la pantalla de perfil (antes de "Configuración") un nuevo item de menú:
|
||||
- Icono: `moon-outline` / `sunny-outline` según el tema actual
|
||||
- Texto: "Modo de pantalla"
|
||||
- Al pulsar, mostrar un picker/modal con 3 opciones:
|
||||
- **Sistema** (icono: phone-portrait) - respeta el SO
|
||||
- **Claro** (icono: sunny) - fuerza light
|
||||
- **Oscuro** (icono: moon) - fuerza dark
|
||||
- El toggle se muestra inline (sin modal extra) tipo Segmented Control
|
||||
|
||||
### 7. Actualizar todos los screens y components
|
||||
|
||||
Cada archivo que importa `colors` debe cambiar a usar el hook `useThemeColor()`:
|
||||
|
||||
| Archivo | Cambio |
|
||||
|---|---|
|
||||
| `app/_layout.tsx` | Usa ThemeProvider + context para header colors |
|
||||
| `app/(tabs)/_layout.tsx` | Tab bar y header leen colors del context |
|
||||
| `app/(tabs)/index.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `app/(tabs)/search.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `app/(tabs)/scan.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `app/(tabs)/alerts.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `app/(tabs)/profile.tsx` | `const { colors, isDark } = useThemeColor()` |
|
||||
| `app/(tabs)/map.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `app/medicine/[id].tsx` | `const { colors } = useThemeColor()` |
|
||||
| `app/pharmacy/[id].tsx` | `const { colors } = useThemeColor()` |
|
||||
| `app/auth/login.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `app/auth/register.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `components/SearchBar.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `components/MedicineCard.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `components/LoadingSpinner.tsx` | `const { colors } = useThemeColor()` |
|
||||
| `components/StockBadge.tsx` | Añade colores dark para badges |
|
||||
| `components/BarcodeScanner.tsx` | `const { colors } = useThemeColor()` |
|
||||
|
||||
**Nota sobre StyleSheet**: Los `StyleSheet.create()` se ejecutan una vez. Para que los estilos se actualicen con el tema, las propiedades que dependen de `colors` deben aplicarse vía `style` inline o moverse a funciones que retornen estilos dinámicos. La estrategia más limpia es:
|
||||
- Los colores de fondo/texto van como inline styles
|
||||
- Las estructuras (flex, padding, borderRadius) se quedan en `StyleSheet.create`
|
||||
|
||||
### 8. Colores hardcodeados
|
||||
Los siguientes archivos tienen colores inline hardcodeados que necesitan variante dark:
|
||||
|
||||
- **`StockBadge.tsx`**: `#eaf7ec`, `#fff3cd`, `#feecec` → añadir tokens al tema
|
||||
- **`search.tsx`**: suggestions con `#ffffff`, `#f0f7ff`, etc. → usar colores del tema
|
||||
- **`profile.tsx`**: feedback `#eaf7ec`, `#cfead0`, `#fecaca` → usar colores del tema
|
||||
- **`home/index.tsx`**: `rgba(255,255,255,0.2/0.3)` para iconos → ajustar opacidad
|
||||
|
||||
### 9. app.json
|
||||
**Modificar: `app.json`**
|
||||
|
||||
Cambiar `"userInterfaceStyle": "light"` → `"userInterfaceStyle": "automatic"`
|
||||
|
||||
## Orden de ejecución
|
||||
|
||||
1. `store/themeStore.ts` (nuevo)
|
||||
2. `hooks/useThemeColor.ts` (nuevo)
|
||||
3. `constants/theme.ts` (añadir `darkColors`)
|
||||
4. `components/ThemeProvider.tsx` (nuevo)
|
||||
5. `app/_layout.tsx` (envolver con ThemeProvider)
|
||||
6. `app/(tabs)/_layout.tsx` (colores dinámicos)
|
||||
7. `app/(tabs)/profile.tsx` (toggle de tema)
|
||||
8. Todos los screens y components (migrar a hook)
|
||||
9. `app.json` (userInterfaceStyle: automatic)
|
||||
10. Corregir colores hardcodeados
|
||||
|
||||
## Verificación
|
||||
|
||||
1. Ejecutar `npx expo start` y verificar que la app arranca sin errores
|
||||
2. Probar en iOS/Android: el tema respeta la configuración del sistema
|
||||
3. Ir a Perfil > Modo de pantalla y cambiar entre Claro/Oscuro/Sistema
|
||||
4. Verificar que el cambio es inmediato sin recargar la app
|
||||
5. Cerrar y reabrir la app → la preferencia persiste
|
||||
6. Verificar que todos los screens se ven bien en ambos modos (sin texto invisible, sin fondos transparentes)
|
||||
7. Probar tablets ( responsive)
|
||||
@@ -15,3 +15,14 @@ PG_PASSWORD=change-me
|
||||
VAPID_PUBLIC_KEY=
|
||||
VAPID_PRIVATE_KEY=
|
||||
VAPID_SUBJECT=mailto:admin@example.com
|
||||
|
||||
# Expo Push Notifications (mobile). Get token from:
|
||||
# https://expo.dev/accounts/[username]/settings/access-tokens
|
||||
EXPO_ACCESS_TOKEN=
|
||||
|
||||
# Open Food Facts
|
||||
# Register at: https://world.openfoodfacts.org/
|
||||
# User-Agent is REQUIRED per OFF docs (format: AppName/Version (ContactEmail))
|
||||
OFF_USER_AGENT=FarmaFinder/1.0 (https://github.com/farmafinder)
|
||||
OFF_USERNAME=
|
||||
OFF_PASSWORD=
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
FROM node:18-slim
|
||||
FROM node:24-alpine
|
||||
WORKDIR /app
|
||||
COPY apps/backend/package*.json ./
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends python3 make g++ && rm -rf /var/lib/apt/lists/*
|
||||
RUN npm ci --omit=dev
|
||||
RUN apk add --no-cache python3 make g++ && npm ci --omit=dev
|
||||
COPY apps/backend/ .
|
||||
COPY apps/API/ /API/
|
||||
RUN mkdir -p /app/data
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { jest } from '@jest/globals'
|
||||
|
||||
jest.unstable_mockModule('../redis-client.js', () => ({
|
||||
default: {
|
||||
get: jest.fn(async () => null),
|
||||
setEx: jest.fn(async () => 'OK'),
|
||||
},
|
||||
}))
|
||||
|
||||
jest.unstable_mockModule('axios', () => ({
|
||||
default: {
|
||||
get: jest.fn(async () => ({ data: { products: [] } })),
|
||||
},
|
||||
}))
|
||||
|
||||
const { transformOFFProduct, searchBabyProducts, getBabyProductDetails } = await import('../off-service.js')
|
||||
|
||||
describe('transformOFFProduct', () => {
|
||||
test('transforms a valid OFF product to unified model', () => {
|
||||
const offProduct = {
|
||||
_id: '12345',
|
||||
product_name: 'Baby Rice',
|
||||
brands: 'Nestlé',
|
||||
image_url: 'https://example.com/image.jpg',
|
||||
nutriscore_grade: 'a',
|
||||
ingredients_text: 'Rice, Iron, Vitamins',
|
||||
nova_group: 1,
|
||||
ecoscore_grade: 'b',
|
||||
categories_tags: ['en:baby-foods', 'en:baby-rice'],
|
||||
}
|
||||
|
||||
const result = transformOFFProduct(offProduct)
|
||||
|
||||
expect(result).toEqual({
|
||||
id: '12345',
|
||||
source: 'openfoodfacts',
|
||||
name: 'Baby Rice',
|
||||
brand: 'Nestlé',
|
||||
category: 'baby_food',
|
||||
image_url: 'https://example.com/image.jpg',
|
||||
nutriscore: 'a',
|
||||
ingredients: 'Rice, Iron, Vitamins',
|
||||
nova_group: 1,
|
||||
eco_score: 'b',
|
||||
})
|
||||
})
|
||||
|
||||
test('returns null for null/undefined input', () => {
|
||||
expect(transformOFFProduct(null)).toBeNull()
|
||||
expect(transformOFFProduct(undefined)).toBeNull()
|
||||
})
|
||||
|
||||
test('returns null when missing required fields', () => {
|
||||
expect(transformOFFProduct({ _id: '123' })).toBeNull()
|
||||
expect(transformOFFProduct({ product_name: 'Test' })).toBeNull()
|
||||
})
|
||||
|
||||
test('sets default brand to empty string when missing', () => {
|
||||
const result = transformOFFProduct({
|
||||
_id: '999',
|
||||
product_name: 'Plain Product',
|
||||
})
|
||||
expect(result.brand).toBe('')
|
||||
expect(result.image_url).toBeNull()
|
||||
expect(result.nutriscore).toBeNull()
|
||||
expect(result.ingredients).toBeNull()
|
||||
expect(result.nova_group).toBeNull()
|
||||
expect(result.eco_score).toBeNull()
|
||||
})
|
||||
|
||||
test('detects baby_milk category from tags', () => {
|
||||
const result = transformOFFProduct({
|
||||
_id: '200',
|
||||
product_name: 'Infant Formula',
|
||||
categories_tags: ['en:infant-milk'],
|
||||
})
|
||||
expect(result.category).toBe('baby_milk')
|
||||
})
|
||||
|
||||
test('detects baby_cereal category from tags', () => {
|
||||
const result = transformOFFProduct({
|
||||
_id: '300',
|
||||
product_name: 'Baby Cereal',
|
||||
categories_tags: ['en:baby-cereals'],
|
||||
})
|
||||
expect(result.category).toBe('baby_cereal')
|
||||
})
|
||||
})
|
||||
|
||||
describe('searchBabyProducts', () => {
|
||||
test('returns empty array for short query', async () => {
|
||||
const result = await searchBabyProducts('a')
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
test('returns empty array for null/empty query', async () => {
|
||||
expect(await searchBabyProducts(null)).toEqual([])
|
||||
expect(await searchBabyProducts('')).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('getBabyProductDetails', () => {
|
||||
test('returns null for null barcode', async () => {
|
||||
const result = await getBabyProductDetails(null)
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -3,6 +3,7 @@ import { jest } from '@jest/globals'
|
||||
jest.unstable_mockModule('../cima-service.js', () => ({
|
||||
searchMedicines: jest.fn(async () => []),
|
||||
getMedicineDetails: jest.fn(async () => null),
|
||||
searchOTC: jest.fn(async () => []),
|
||||
}))
|
||||
|
||||
jest.unstable_mockModule('../farmacias-webhook-import.js', () => ({
|
||||
|
||||
@@ -2,22 +2,56 @@ import axios from 'axios';
|
||||
import redisClient from './redis-client.js';
|
||||
|
||||
const CIMA_API_BASE_URL = 'https://cima.aemps.es/cima/rest';
|
||||
const CACHE_TTL = 3600; // 1 hora en segundos
|
||||
const CACHE_TTL = 3600;
|
||||
|
||||
/**
|
||||
* CIMA's nombre filter is prefix-oriented; narrow to rows that contain every
|
||||
* search term in the commercial name or active ingredient (full-word style).
|
||||
* Separa los términos de dosis (ej: "1g", "1000 mg") del nombre del
|
||||
* medicamento, para poder buscar en CIMA solo con el nombre y luego
|
||||
* filtrar por dosis con mayor precisión.
|
||||
*/
|
||||
function parseSearchQuery(query) {
|
||||
const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
||||
|
||||
const dosagePattern = /^\d+(g|mg|mcg|µg|ml|ui|%)$/i;
|
||||
const dosageTerms = [];
|
||||
const nameTerms = [];
|
||||
|
||||
for (const term of terms) {
|
||||
const clean = term.replace(/\s+/g, '');
|
||||
if (dosagePattern.test(clean)) {
|
||||
dosageTerms.push(clean);
|
||||
} else {
|
||||
nameTerms.push(term);
|
||||
}
|
||||
}
|
||||
|
||||
return { nameQuery: nameTerms.join(' '), dosageTerms };
|
||||
}
|
||||
|
||||
/**
|
||||
* Filtra los resultados de CIMA comprobando que todos los términos del
|
||||
* nombre aparezcan en el nombre comercial o principio activo, y que los
|
||||
* términos de dosis coincidan con el campo dosage normalizado.
|
||||
*/
|
||||
function filterMedicinesByFullQuery(medicines, searchTerm) {
|
||||
const terms = searchTerm
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.split(/\s+/)
|
||||
.filter(Boolean);
|
||||
if (terms.length === 0) return medicines;
|
||||
const parsed = parseSearchQuery(searchTerm);
|
||||
const nameTerms = parsed.nameQuery.split(/\s+/).filter(Boolean);
|
||||
const dosageTerms = parsed.dosageTerms;
|
||||
|
||||
if (nameTerms.length === 0 && dosageTerms.length === 0) return medicines;
|
||||
|
||||
return medicines.filter((m) => {
|
||||
if (nameTerms.length > 0) {
|
||||
const hay = `${m.name || ''} ${m.active_ingredient || ''}`.toLowerCase();
|
||||
return terms.every((term) => hay.includes(term));
|
||||
if (!nameTerms.every((term) => hay.includes(term))) return false;
|
||||
}
|
||||
|
||||
if (dosageTerms.length > 0) {
|
||||
const dosageHay = (m.dosage || '').toLowerCase().replace(/\s+/g, '');
|
||||
if (!dosageTerms.every((term) => dosageHay.includes(term))) return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -32,7 +66,7 @@ export async function searchMedicines(query) {
|
||||
}
|
||||
|
||||
const searchTerm = query.trim().toLowerCase();
|
||||
const cacheKey = `medicines:search:v2:${searchTerm}`;
|
||||
const cacheKey = `medicines:search:v3:${searchTerm}`;
|
||||
|
||||
try {
|
||||
// Intentar obtener del caché
|
||||
@@ -43,11 +77,13 @@ export async function searchMedicines(query) {
|
||||
return JSON.parse(cachedData);
|
||||
}
|
||||
|
||||
// Si no está en caché, consultar la API de CIMA
|
||||
console.log(`🌐 Fetching from CIMA API: ${searchTerm}`);
|
||||
const parsed = parseSearchQuery(searchTerm);
|
||||
const apiSearchTerm = parsed.nameQuery || searchTerm;
|
||||
|
||||
console.log(`🌐 Fetching from CIMA API: ${apiSearchTerm}`);
|
||||
const response = await axios.get(`${CIMA_API_BASE_URL}/medicamentos`, {
|
||||
params: {
|
||||
nombre: searchTerm
|
||||
nombre: apiSearchTerm
|
||||
},
|
||||
timeout: 5000
|
||||
});
|
||||
@@ -115,8 +151,9 @@ export async function getMedicineDetails(nregistro) {
|
||||
return JSON.parse(cachedData);
|
||||
}
|
||||
|
||||
// Consultar la API de CIMA
|
||||
// Intentar obtener de la API de CIMA (endpoint individual puede no existir)
|
||||
console.log(`🌐 Fetching medicine details from CIMA: ${nregistro}`);
|
||||
try {
|
||||
const response = await axios.get(`${CIMA_API_BASE_URL}/medicamento/${nregistro}`, {
|
||||
timeout: 5000
|
||||
});
|
||||
@@ -140,9 +177,38 @@ export async function getMedicineDetails(nregistro) {
|
||||
presentations: med.presentaciones || []
|
||||
};
|
||||
|
||||
// Guardar en caché (TTL más largo para detalles específicos)
|
||||
await redisClient.setEx(cacheKey, CACHE_TTL * 24, JSON.stringify(medicineDetails));
|
||||
return medicineDetails;
|
||||
}
|
||||
} catch (apiError) {
|
||||
console.log(`⚠️ Individual medicine endpoint failed, trying search fallback`);
|
||||
}
|
||||
|
||||
// Fallback: buscar por nregistro usando el endpoint de búsqueda
|
||||
const searchResponse = await axios.get(`${CIMA_API_BASE_URL}/medicamentos`, {
|
||||
params: { nregistro },
|
||||
timeout: 5000
|
||||
});
|
||||
|
||||
if (searchResponse.data?.resultados?.length > 0) {
|
||||
const med = searchResponse.data.resultados[0];
|
||||
const medicineDetails = {
|
||||
id: med.nregistro,
|
||||
nregistro: med.nregistro,
|
||||
name: med.nombre,
|
||||
active_ingredient: med.vtm?.nombre || null,
|
||||
dosage: med.dosis || null,
|
||||
form: med.formaFarmaceutica?.nombre || null,
|
||||
formSimplified: med.formaFarmaceuticaSimplificada?.nombre || null,
|
||||
laboratory: med.labtitular,
|
||||
prescription: med.cpresc,
|
||||
commercialized: med.comerc,
|
||||
generic: med.generico,
|
||||
photos: med.fotos || [],
|
||||
docs: med.docs || []
|
||||
};
|
||||
|
||||
await redisClient.setEx(cacheKey, CACHE_TTL * 24, JSON.stringify(medicineDetails));
|
||||
return medicineDetails;
|
||||
}
|
||||
|
||||
@@ -165,6 +231,86 @@ export async function getMedicineDetails(nregistro) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Busca medicamentos OTC (Sin Receta) en la API de CIMA con caché de Redis
|
||||
* @param {string} query - Término de búsqueda
|
||||
* @returns {Promise<Array>} - Lista de medicamentos OTC encontrados
|
||||
*/
|
||||
export async function searchOTC(query) {
|
||||
if (!query || query.trim().length < 2) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const searchTerm = query.trim().toLowerCase();
|
||||
const cacheKey = `cima:otc:${searchTerm}`;
|
||||
|
||||
try {
|
||||
// Intentar obtener del caché
|
||||
const cachedData = await redisClient.get(cacheKey);
|
||||
|
||||
if (cachedData) {
|
||||
console.log(`📦 Cache hit for OTC search: ${searchTerm}`);
|
||||
return JSON.parse(cachedData);
|
||||
}
|
||||
|
||||
const parsed = parseSearchQuery(searchTerm);
|
||||
const apiSearchTerm = parsed.nameQuery || searchTerm;
|
||||
|
||||
console.log(`🌐 Fetching OTC from CIMA API: ${apiSearchTerm}`);
|
||||
const response = await axios.get(`${CIMA_API_BASE_URL}/medicamentos`, {
|
||||
params: {
|
||||
nombre: apiSearchTerm,
|
||||
cpresc: 'Sin Receta'
|
||||
},
|
||||
timeout: 5000
|
||||
});
|
||||
|
||||
if (response.data && response.data.resultados) {
|
||||
// Transformar los datos de CIMA al modelo unificado Product
|
||||
const medicines = response.data.resultados.map(med => ({
|
||||
id: med.nregistro,
|
||||
source: 'cima',
|
||||
name: med.nombre,
|
||||
brand: med.labtitular || '',
|
||||
category: 'otc',
|
||||
image_url: med.fotos?.[0]?.url || null,
|
||||
active_ingredient: med.vtm?.nombre || null,
|
||||
dosage: med.dosis || null,
|
||||
form: med.formaFarmaceutica?.nombre || null,
|
||||
prescription: med.cpresc,
|
||||
commercialized: med.comerc,
|
||||
photos: med.fotos || [],
|
||||
docs: med.docs || []
|
||||
}));
|
||||
|
||||
const filtered = filterMedicinesByFullQuery(medicines, searchTerm);
|
||||
|
||||
// Guardar en caché (1h TTL)
|
||||
await redisClient.setEx(cacheKey, CACHE_TTL, JSON.stringify(filtered));
|
||||
|
||||
console.log(`✅ Cached ${filtered.length} OTC medicines for: ${searchTerm}`);
|
||||
return filtered;
|
||||
}
|
||||
|
||||
return [];
|
||||
} catch (error) {
|
||||
console.error('Error searching OTC medicines from CIMA:', error.message);
|
||||
|
||||
// Si falla, intentar devolver datos cacheados aunque hayan expirado
|
||||
try {
|
||||
const staleData = await redisClient.get(cacheKey);
|
||||
if (staleData) {
|
||||
console.log('⚠️ Returning stale OTC cache data due to API error');
|
||||
return JSON.parse(staleData);
|
||||
}
|
||||
} catch (cacheError) {
|
||||
console.error('OTC cache fallback also failed:', cacheError);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Limpia el caché de búsquedas (útil para testing o mantenimiento)
|
||||
* @param {string} pattern - Patrón de claves a eliminar (ej: 'medicines:search:*')
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* CLI: pull pharmacies from webhook and insert into database.sqlite
|
||||
* CLI: pull pharmacies from webhook and insert into database
|
||||
*
|
||||
* npm run import-farmacias
|
||||
* FARMACIAS_WEBHOOK_URL=https://... npm run import-farmacias
|
||||
@@ -10,12 +10,15 @@
|
||||
* node import-farmacias.js "https://n8n.example/webhook/farmacias" --lat 41.5631 --lon 2.0038 --radio 1500
|
||||
*
|
||||
* Env defaults for region: FARMACIAS_IMPORT_LAT, FARMACIAS_IMPORT_LON, FARMACIAS_IMPORT_RADIO
|
||||
*
|
||||
* Uses PostgreSQL when PG_URL is set, otherwise falls back to local SQLite.
|
||||
*/
|
||||
|
||||
import sqlite3 from 'sqlite3';
|
||||
import { promisify } from 'util';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import pg from 'pg';
|
||||
import {
|
||||
runFarmaciaWebhookImport,
|
||||
DEFAULT_FARMACIAS_WEBHOOK,
|
||||
@@ -24,19 +27,43 @@ import {
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const dbPath = path.join(__dirname, 'database.sqlite');
|
||||
const db = new sqlite3.Database(dbPath);
|
||||
const PG_URL = process.env.PG_URL;
|
||||
let pool = null;
|
||||
let db = null;
|
||||
|
||||
function dbRun(sql, params = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let dbRun, dbGet;
|
||||
|
||||
if (PG_URL) {
|
||||
pool = new pg.Pool({ connectionString: PG_URL });
|
||||
|
||||
function toPositional(sql) {
|
||||
let i = 0;
|
||||
return sql.replace(/\?/g, () => `$${++i}`);
|
||||
}
|
||||
|
||||
dbGet = async (sql, params = []) => {
|
||||
const res = await pool.query(toPositional(sql), params);
|
||||
return res.rows[0] ?? null;
|
||||
};
|
||||
|
||||
dbRun = async (sql, params = []) => {
|
||||
const res = await pool.query(toPositional(sql), params);
|
||||
return { lastID: res.rows[0]?.id, changes: res.rowCount };
|
||||
};
|
||||
} else {
|
||||
const dbPath = path.join(__dirname, 'database.sqlite');
|
||||
db = new sqlite3.Database(dbPath);
|
||||
|
||||
dbRun = (sql, params = []) =>
|
||||
new Promise((resolve, reject) => {
|
||||
db.run(sql, params, function (err) {
|
||||
if (err) reject(err);
|
||||
else resolve({ lastID: this.lastID, changes: this.changes });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const dbGet = promisify(db.get.bind(db));
|
||||
dbGet = promisify(db.get.bind(db));
|
||||
}
|
||||
|
||||
function parseCli(argv) {
|
||||
const region = {};
|
||||
@@ -76,6 +103,7 @@ async function main() {
|
||||
const { url, region } = parseCli(process.argv);
|
||||
console.log('Fetching pharmacies from:', url);
|
||||
if (region) console.log('Region query:', region);
|
||||
console.log('Using:', PG_URL ? 'PostgreSQL' : 'SQLite');
|
||||
|
||||
try {
|
||||
const result = await runFarmaciaWebhookImport(dbGet, dbRun, url, region);
|
||||
@@ -97,7 +125,8 @@ async function main() {
|
||||
}
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
db.close();
|
||||
if (pool) await pool.end();
|
||||
else if (db) db.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
import axios from 'axios';
|
||||
import redisClient from './redis-client.js';
|
||||
|
||||
// OFF API v3 (recommended) with fallback to v2 for search
|
||||
const OFF_API_BASE = 'https://world.openfoodfacts.org';
|
||||
const CACHE_TTL = 3600;
|
||||
const MAX_RETRIES = 2;
|
||||
const RETRY_DELAY_MS = 1000;
|
||||
|
||||
// User-Agent is REQUIRED per OFF docs: AppName/Version (ContactEmail)
|
||||
const OFF_USER_AGENT = process.env.OFF_USER_AGENT || 'FarmaFinder/1.0 (https://github.com/farmafinder)';
|
||||
|
||||
// Open Food Facts authentication (optional, for write operations)
|
||||
const OFF_USERNAME = process.env.OFF_USERNAME;
|
||||
const OFF_PASSWORD = process.env.OFF_PASSWORD;
|
||||
|
||||
function getOffHeaders() {
|
||||
return {
|
||||
'User-Agent': OFF_USER_AGENT,
|
||||
};
|
||||
}
|
||||
|
||||
function getOffAuth() {
|
||||
if (OFF_USERNAME && OFF_PASSWORD) {
|
||||
return {
|
||||
username: OFF_USERNAME,
|
||||
password: OFF_PASSWORD,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
export function transformOFFProduct(offProduct) {
|
||||
if (!offProduct || !offProduct._id || !offProduct.product_name) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const categoriesTags = offProduct.categories_tags || [];
|
||||
let category = 'baby_food';
|
||||
for (const tag of categoriesTags) {
|
||||
const lower = tag.toLowerCase();
|
||||
if (lower.includes('baby-milk') || lower.includes('infant-milk')) {
|
||||
category = 'baby_milk';
|
||||
break;
|
||||
}
|
||||
if (lower.includes('baby-cereal') || lower.includes('infant-cereal')) {
|
||||
category = 'baby_cereal';
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: offProduct._id,
|
||||
source: 'openfoodfacts',
|
||||
name: offProduct.product_name,
|
||||
brand: offProduct.brands || '',
|
||||
category,
|
||||
image_url: offProduct.image_url || null,
|
||||
nutriscore: offProduct.nutriscore_grade || null,
|
||||
ingredients: offProduct.ingredients_text || null,
|
||||
nova_group: offProduct.nova_group || null,
|
||||
eco_score: offProduct.ecoscore_grade || null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function searchBabyProducts(query) {
|
||||
if (!query || query.trim().length < 2) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const searchTerm = query.trim().toLowerCase();
|
||||
const cacheKey = `off:baby:${searchTerm}`;
|
||||
|
||||
try {
|
||||
const cachedData = await redisClient.get(cacheKey);
|
||||
if (cachedData) {
|
||||
console.log(`Cache hit for OFF search: ${searchTerm}`);
|
||||
return JSON.parse(cachedData);
|
||||
}
|
||||
|
||||
console.log(`Fetching from OFF API: ${searchTerm}`);
|
||||
const headers = getOffHeaders();
|
||||
console.log(`[OFF] User-Agent: ${headers['User-Agent']}`);
|
||||
console.log(`[OFF] URL: ${OFF_API_BASE}/api/v2/search?brands_tags=${searchTerm}`);
|
||||
|
||||
let lastError;
|
||||
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
||||
try {
|
||||
// Use v2 structured search with brand filter (more reliable than /cgi/search.pl)
|
||||
// READ operations don't require auth per OFF docs, only User-Agent
|
||||
const response = await axios.get(`${OFF_API_BASE}/api/v2/search`, {
|
||||
params: {
|
||||
brands_tags: searchTerm,
|
||||
page_size: 20,
|
||||
},
|
||||
headers,
|
||||
timeout: 10000,
|
||||
validateStatus: (status) => status === 200,
|
||||
});
|
||||
|
||||
// Check if response is actually JSON (OFF sometimes returns HTML on error)
|
||||
if (typeof response.data === 'string' || !response.data.products) {
|
||||
console.warn(`[OFF] Invalid response for "${searchTerm}" (attempt ${attempt + 1}): API may be down`);
|
||||
if (attempt < MAX_RETRIES) {
|
||||
await sleep(RETRY_DELAY_MS * (attempt + 1));
|
||||
continue;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
const products = response.data.products
|
||||
.map(transformOFFProduct)
|
||||
.filter(Boolean);
|
||||
|
||||
// Only cache non-empty results to avoid caching API failures
|
||||
if (products.length > 0) {
|
||||
try {
|
||||
await redisClient.setEx(cacheKey, CACHE_TTL, JSON.stringify(products));
|
||||
console.log(`Cached ${products.length} OFF products for: ${searchTerm}`);
|
||||
} catch (cacheErr) {
|
||||
// cache write failed, still return the data
|
||||
}
|
||||
} else {
|
||||
console.log(`[OFF] No products found for "${searchTerm}", not caching empty result`);
|
||||
}
|
||||
return products;
|
||||
} catch (err) {
|
||||
lastError = err;
|
||||
console.warn(`[OFF] Request failed for "${searchTerm}" (attempt ${attempt + 1}): ${err.message}`);
|
||||
if (attempt < MAX_RETRIES) {
|
||||
await sleep(RETRY_DELAY_MS * (attempt + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.error(`[OFF] All retries failed for "${searchTerm}": ${lastError?.message}`);
|
||||
return [];
|
||||
} catch (error) {
|
||||
console.error('Error searching baby products from OFF:', error.message);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function getBabyProductDetails(barcode) {
|
||||
if (!barcode) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cacheKey = `off:product:${barcode}`;
|
||||
|
||||
try {
|
||||
const cachedData = await redisClient.get(cacheKey);
|
||||
if (cachedData) {
|
||||
console.log(`Cache hit for OFF product: ${barcode}`);
|
||||
return JSON.parse(cachedData);
|
||||
}
|
||||
|
||||
console.log(`Fetching OFF product details: ${barcode}`);
|
||||
const headers = getOffHeaders();
|
||||
// Use v3 API (recommended) for product details
|
||||
// READ operations don't require auth per OFF docs, only User-Agent
|
||||
const response = await axios.get(`${OFF_API_BASE}/api/v3/product/${barcode}.json`, {
|
||||
headers,
|
||||
timeout: 10000,
|
||||
validateStatus: (status) => status === 200,
|
||||
});
|
||||
|
||||
if (response.data && response.data.product) {
|
||||
const product = transformOFFProduct(response.data.product);
|
||||
|
||||
if (product) {
|
||||
try {
|
||||
await redisClient.setEx(cacheKey, CACHE_TTL, JSON.stringify(product));
|
||||
console.log(`Cached OFF product: ${barcode}`);
|
||||
} catch (cacheErr) {
|
||||
// cache write failed, still return the data
|
||||
}
|
||||
return product;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error(`Error fetching OFF product ${barcode}:`, error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function clearCache(pattern = 'off:*') {
|
||||
try {
|
||||
const keys = await redisClient.keys(pattern);
|
||||
if (keys.length > 0) {
|
||||
await redisClient.del(keys);
|
||||
console.log(`Cleared ${keys.length} OFF cache entries`);
|
||||
return keys.length;
|
||||
}
|
||||
return 0;
|
||||
} catch (error) {
|
||||
console.error('Error clearing OFF cache:', error);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@
|
||||
"@opentelemetry/sdk-trace-base": "^1.28.0",
|
||||
"@opentelemetry/semantic-conventions": "^1.28.0",
|
||||
"axios": "^1.6.0",
|
||||
"barcode-detector": "^3.2.0",
|
||||
"bcrypt": "^5.1.1",
|
||||
"connect-pg-simple": "^10.0.0",
|
||||
"connect-sqlite3": "^0.9.16",
|
||||
@@ -3458,6 +3459,12 @@
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/emscripten": {
|
||||
"version": "1.41.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/emscripten/-/emscripten-1.41.5.tgz",
|
||||
"integrity": "sha512-cMQm7pxu6BxtHyqJ7mQZ2kXWV5SLmugybFdHCBbJ5eHzOo6VhBckEgAT3//rP5FwPHNPeEiq4SmQ5ucBwsOo4Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/graceful-fs": {
|
||||
"version": "4.1.9",
|
||||
"resolved": "https://registry.npmjs.org/@types/graceful-fs/-/graceful-fs-4.1.9.tgz",
|
||||
@@ -3946,6 +3953,15 @@
|
||||
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/barcode-detector": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/barcode-detector/-/barcode-detector-3.2.0.tgz",
|
||||
"integrity": "sha512-MrT5TT058ptG5YB157pHLfXKVpp0BKEfQBOb8QvzTbatzmLDu85JJ0Gd/sCYwbwdwStJvxsYflrSN6D6E4Ndyw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"zxing-wasm": "3.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/base64-js": {
|
||||
"version": "1.5.1",
|
||||
"resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
|
||||
@@ -8743,6 +8759,18 @@
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/tagged-tag": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz",
|
||||
"integrity": "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/tar": {
|
||||
"version": "6.2.1",
|
||||
"resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz",
|
||||
@@ -9293,6 +9321,34 @@
|
||||
"engines": {
|
||||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/zxing-wasm": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/zxing-wasm/-/zxing-wasm-3.1.0.tgz",
|
||||
"integrity": "sha512-5+3V1wPRx4gvbeLH2jB7n2cKrYJ1q4i3QgjnBUtrDPeqxJSi6BdzKJg4y6aF6bgW8zfntnYJyrkqFMevDhL2NA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@types/emscripten": "^1.41.5",
|
||||
"type-fest": "^5.7.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@types/emscripten": ">=1.39.6"
|
||||
}
|
||||
},
|
||||
"node_modules/zxing-wasm/node_modules/type-fest": {
|
||||
"version": "5.8.0",
|
||||
"resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.8.0.tgz",
|
||||
"integrity": "sha512-YGYEVz3Fm5iy/AybuA0oyNFq7H4CgQNfRp/qfe8nurE1kuCeNm3/vfm9X4Mtl+qLyaKJUh5xrFZwogr41SMjYA==",
|
||||
"license": "(MIT OR CC0-1.0)",
|
||||
"dependencies": {
|
||||
"tagged-tag": "^1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
"@opentelemetry/sdk-trace-base": "^1.28.0",
|
||||
"@opentelemetry/semantic-conventions": "^1.28.0",
|
||||
"axios": "^1.6.0",
|
||||
"barcode-detector": "^3.2.0",
|
||||
"bcrypt": "^5.1.1",
|
||||
"connect-pg-simple": "^10.0.0",
|
||||
"connect-sqlite3": "^0.9.16",
|
||||
|
||||
@@ -1,8 +1,27 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="DeviceStreaming">
|
||||
<option name="defaultDeviceApplied" value="true" />
|
||||
<option name="deviceSelectionList">
|
||||
<list>
|
||||
<PersistentDeviceSelectionData>
|
||||
<option name="api" value="30" />
|
||||
<option name="brand" value="google" />
|
||||
<option name="codename" value="redfin" />
|
||||
<option name="id" value="redfin" />
|
||||
<option name="labId" value="google" />
|
||||
<option name="manufacturer" value="Google" />
|
||||
<option name="name" value="Pixel 5" />
|
||||
<option name="screenDensity" value="440" />
|
||||
<option name="screenX" value="1080" />
|
||||
<option name="screenY" value="2340" />
|
||||
<option name="selected" value="true" />
|
||||
<option name="tags">
|
||||
<list>
|
||||
<option value="default" />
|
||||
</list>
|
||||
</option>
|
||||
</PersistentDeviceSelectionData>
|
||||
<PersistentDeviceSelectionData>
|
||||
<option name="api" value="34" />
|
||||
<option name="brand" value="Sony" />
|
||||
@@ -171,6 +190,18 @@
|
||||
<option name="screenX" value="720" />
|
||||
<option name="screenY" value="1600" />
|
||||
</PersistentDeviceSelectionData>
|
||||
<PersistentDeviceSelectionData>
|
||||
<option name="api" value="33" />
|
||||
<option name="brand" value="samsung" />
|
||||
<option name="codename" value="a03sutfn" />
|
||||
<option name="id" value="a03sutfn" />
|
||||
<option name="labId" value="google" />
|
||||
<option name="manufacturer" value="Samsung" />
|
||||
<option name="name" value="Galaxy A03s" />
|
||||
<option name="screenDensity" value="280" />
|
||||
<option name="screenX" value="720" />
|
||||
<option name="screenY" value="1600" />
|
||||
</PersistentDeviceSelectionData>
|
||||
<PersistentDeviceSelectionData>
|
||||
<option name="api" value="35" />
|
||||
<option name="brand" value="samsung" />
|
||||
@@ -531,6 +562,18 @@
|
||||
<option name="screenX" value="1440" />
|
||||
<option name="screenY" value="3088" />
|
||||
</PersistentDeviceSelectionData>
|
||||
<PersistentDeviceSelectionData>
|
||||
<option name="api" value="36" />
|
||||
<option name="brand" value="samsung" />
|
||||
<option name="codename" value="b4qsqw" />
|
||||
<option name="id" value="b4qsqw" />
|
||||
<option name="labId" value="google" />
|
||||
<option name="manufacturer" value="Samsung" />
|
||||
<option name="name" value="Galaxy Z Flip4" />
|
||||
<option name="screenDensity" value="480" />
|
||||
<option name="screenX" value="1080" />
|
||||
<option name="screenY" value="2640" />
|
||||
</PersistentDeviceSelectionData>
|
||||
<PersistentDeviceSelectionData>
|
||||
<option name="api" value="36" />
|
||||
<option name="brand" value="samsung" />
|
||||
@@ -1681,6 +1724,18 @@
|
||||
<option name="screenX" value="1080" />
|
||||
<option name="screenY" value="2340" />
|
||||
</PersistentDeviceSelectionData>
|
||||
<PersistentDeviceSelectionData>
|
||||
<option name="api" value="36" />
|
||||
<option name="brand" value="samsung" />
|
||||
<option name="codename" value="r0qksx" />
|
||||
<option name="id" value="r0qksx" />
|
||||
<option name="labId" value="google" />
|
||||
<option name="manufacturer" value="Samsung" />
|
||||
<option name="name" value="Galaxy S22" />
|
||||
<option name="screenDensity" value="480" />
|
||||
<option name="screenX" value="1080" />
|
||||
<option name="screenY" value="2340" />
|
||||
</PersistentDeviceSelectionData>
|
||||
<PersistentDeviceSelectionData>
|
||||
<option name="api" value="30" />
|
||||
<option name="brand" value="google" />
|
||||
@@ -1785,23 +1840,6 @@
|
||||
</list>
|
||||
</option>
|
||||
</PersistentDeviceSelectionData>
|
||||
<PersistentDeviceSelectionData>
|
||||
<option name="api" value="30" />
|
||||
<option name="brand" value="google" />
|
||||
<option name="codename" value="redfin" />
|
||||
<option name="id" value="redfin" />
|
||||
<option name="labId" value="google" />
|
||||
<option name="manufacturer" value="Google" />
|
||||
<option name="name" value="Pixel 5" />
|
||||
<option name="screenDensity" value="440" />
|
||||
<option name="screenX" value="1080" />
|
||||
<option name="screenY" value="2340" />
|
||||
<option name="tags">
|
||||
<list>
|
||||
<option value="default" />
|
||||
</list>
|
||||
</option>
|
||||
</PersistentDeviceSelectionData>
|
||||
<PersistentDeviceSelectionData>
|
||||
<option name="accessStatus">
|
||||
<list>
|
||||
@@ -2186,5 +2224,6 @@
|
||||
</PersistentDeviceSelectionData>
|
||||
</list>
|
||||
</option>
|
||||
<option name="selectedCloudProject" value="farmaclic-53c42" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -1,6 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
|
||||
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1 @@
|
||||
{"pid":1390854,"startedAt":1783459832497}
|
||||
@@ -5,7 +5,7 @@
|
||||
"version": "1.0.0",
|
||||
"orientation": "portrait",
|
||||
"icon": "./assets/icon.png",
|
||||
"userInterfaceStyle": "light",
|
||||
"userInterfaceStyle": "automatic",
|
||||
"newArchEnabled": true,
|
||||
"splash": {
|
||||
"image": "./assets/splash.png",
|
||||
@@ -25,17 +25,34 @@
|
||||
"backgroundColor": "#007AFF"
|
||||
},
|
||||
"package": "com.farmafinder.app",
|
||||
"googleServicesFile": "./google-services.json"
|
||||
"googleServicesFile": "./google-services.json",
|
||||
"config": {
|
||||
"googleMaps": {
|
||||
"apiKey": ""
|
||||
}
|
||||
}
|
||||
},
|
||||
"plugins": [
|
||||
"expo-router",
|
||||
["expo-camera", {"cameraPermission": "Allow FarmaFinder to access your camera for scanning barcodes"}],
|
||||
["expo-notifications", {"icon": "./assets/notification-icon.png", "color": "#007AFF"}]
|
||||
["expo-notifications", {"icon": "./assets/notification-icon.png", "color": "#007AFF"}],
|
||||
[
|
||||
"react-native-maps",
|
||||
{
|
||||
"locationAlwaysAndWhenInUsePermission": "Allow FarmaFinder to use your location to find nearby pharmacies."
|
||||
}
|
||||
],
|
||||
[
|
||||
"expo-location",
|
||||
{
|
||||
"locationAlwaysAndWhenInUsePermission": "Allow FarmaFinder to use your location to find nearby pharmacies."
|
||||
}
|
||||
]
|
||||
],
|
||||
"scheme": "farmafinder",
|
||||
"extra": {
|
||||
"eas": {
|
||||
"projectId": ""
|
||||
"projectId": "9a424f20-1073-4477-93e1-6b302a1ae389"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,16 +1,73 @@
|
||||
import { Tabs } from 'expo-router';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { View, StyleSheet, useWindowDimensions } from 'react-native';
|
||||
import { useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||
import { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { shadows } from '../../constants/theme';
|
||||
|
||||
const TABLET_MIN_WIDTH = 768;
|
||||
|
||||
// Standard Android navigation bar heights in dp
|
||||
const ANDROID_NAV_BAR_HEIGHT = 48;
|
||||
|
||||
function ScanIcon({ size }: { size: number }) {
|
||||
return (
|
||||
<View style={styles.fabContainer}>
|
||||
<View style={[styles.fab, shadows.scanButton]}>
|
||||
<Ionicons name="scan" size={size} color="#ffffff" />
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export default function TabLayout() {
|
||||
const insets = useSafeAreaInsets();
|
||||
const { width } = useWindowDimensions();
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
const { colors } = useThemeContext();
|
||||
// Use safe area insets if available, otherwise use standard Android nav bar height
|
||||
const bottomPadding = insets.bottom > 0 ? insets.bottom : ANDROID_NAV_BAR_HEIGHT;
|
||||
|
||||
return (
|
||||
<Tabs
|
||||
screenOptions={{
|
||||
tabBarActiveTintColor: '#007AFF',
|
||||
tabBarInactiveTintColor: '#8E8E93',
|
||||
tabBarActiveTintColor: colors.primary,
|
||||
tabBarInactiveTintColor: colors.textSecondary,
|
||||
tabBarStyle: {
|
||||
...(isTablet ? styles.tabBarTablet : {}),
|
||||
backgroundColor: colors.card,
|
||||
borderTopColor: colors.border,
|
||||
paddingTop: isTablet ? 10 : 8,
|
||||
height: (isTablet ? 64 : 60) + bottomPadding,
|
||||
paddingBottom: bottomPadding,
|
||||
...(isTablet ? { paddingHorizontal: 24 } : {}),
|
||||
},
|
||||
tabBarLabelStyle: {
|
||||
fontSize: isTablet ? 13 : 11,
|
||||
fontWeight: '500',
|
||||
},
|
||||
headerStyle: {
|
||||
backgroundColor: colors.card,
|
||||
},
|
||||
headerTintColor: colors.primary,
|
||||
headerTitleStyle: {
|
||||
color: colors.text,
|
||||
fontWeight: '600',
|
||||
fontSize: isTablet ? 20 : 17,
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Tabs.Screen
|
||||
name="index"
|
||||
options={{
|
||||
title: 'Inicio',
|
||||
tabBarIcon: ({ color, size }) => (
|
||||
<Ionicons name="home" size={size} color={color} />
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
name="search"
|
||||
options={{
|
||||
title: 'Buscar',
|
||||
tabBarIcon: ({ color, size }) => (
|
||||
@@ -18,13 +75,27 @@ export default function TabLayout() {
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
name="scan"
|
||||
options={{
|
||||
title: 'Escanear',
|
||||
tabBarIcon: ({ color, size }) => <ScanIcon color={color} size={size} />,
|
||||
tabBarLabel: () => null,
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
name="alerts"
|
||||
options={{
|
||||
title: 'Avisos',
|
||||
tabBarIcon: ({ color, size }) => (
|
||||
<Ionicons name="notifications" size={size} color={color} />
|
||||
),
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
name="map"
|
||||
options={{
|
||||
title: 'Mapa',
|
||||
tabBarIcon: ({ color, size }) => (
|
||||
<Ionicons name="map" size={size} color={color} />
|
||||
),
|
||||
href: null,
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
@@ -39,3 +110,19 @@ export default function TabLayout() {
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
fabContainer: {
|
||||
position: 'absolute',
|
||||
top: -16,
|
||||
alignItems: 'center',
|
||||
},
|
||||
fab: {
|
||||
width: 52,
|
||||
height: 52,
|
||||
borderRadius: 26,
|
||||
backgroundColor: '#2b5bb5',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,353 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Alert, useWindowDimensions } from 'react-native';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { useAuth } from '../../hooks/useAuth';
|
||||
import { spacing, borderRadius, shadows } from '../../constants/theme';
|
||||
import { LoadingSpinner } from '../../components/LoadingSpinner';
|
||||
import api from '../../services/api';
|
||||
|
||||
const TABLET_MIN_WIDTH = 768;
|
||||
|
||||
interface NotificationItem {
|
||||
scope: string;
|
||||
id: number;
|
||||
medicine_name?: string;
|
||||
medicine_nregistro?: string;
|
||||
pharmacy_name?: string;
|
||||
pharmacy_id?: number;
|
||||
pharmacy_address?: string;
|
||||
created_at?: string;
|
||||
}
|
||||
|
||||
export default function AlertsScreen() {
|
||||
const router = useRouter();
|
||||
const { width } = useWindowDimensions();
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
const { colors } = useThemeContext();
|
||||
const { isAuthenticated, isLoading: authLoading } = useAuth();
|
||||
const [items, setItems] = useState<NotificationItem[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [deletingId, setDeletingId] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!authLoading && isAuthenticated) {
|
||||
loadNotifications();
|
||||
} else if (!authLoading && !isAuthenticated) {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [authLoading, isAuthenticated]);
|
||||
|
||||
async function loadNotifications() {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await api.get('/notifications/mine');
|
||||
const data = res.data;
|
||||
const merged = [
|
||||
...(data.pharmacy || []),
|
||||
...(data.global || []),
|
||||
].sort((a: NotificationItem, b: NotificationItem) =>
|
||||
(b.created_at || '').localeCompare(a.created_at || '')
|
||||
);
|
||||
setItems(merged);
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'No se pudieron cargar las notificaciones');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(item: NotificationItem) {
|
||||
const key = `${item.scope}:${item.id}`;
|
||||
Alert.alert(
|
||||
'Eliminar notificación',
|
||||
`¿Eliminar la notificación de ${item.medicine_name || item.medicine_nregistro}?`,
|
||||
[
|
||||
{ text: 'Cancelar', style: 'cancel' },
|
||||
{
|
||||
text: 'Eliminar',
|
||||
style: 'destructive',
|
||||
onPress: async () => {
|
||||
setDeletingId(key);
|
||||
try {
|
||||
await api.delete('/notifications/mine', {
|
||||
data: { scope: item.scope, id: item.id },
|
||||
});
|
||||
setItems(prev => prev.filter(i => !(i.scope === item.scope && i.id === item.id)));
|
||||
} catch (err: any) {
|
||||
Alert.alert('Error', err.message || 'No se pudo eliminar');
|
||||
} finally {
|
||||
setDeletingId(null);
|
||||
}
|
||||
},
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
function renderItem({ item }: { item: NotificationItem }) {
|
||||
const key = `${item.scope}:${item.id}`;
|
||||
return (
|
||||
<View style={[styles.item, { backgroundColor: colors.card }]}>
|
||||
<View style={styles.itemContent}>
|
||||
<Text style={[styles.itemName, { color: colors.text }]} numberOfLines={2}>
|
||||
{item.medicine_name || item.medicine_nregistro}
|
||||
</Text>
|
||||
<View style={styles.itemMeta}>
|
||||
<View style={[styles.chip, { backgroundColor: colors.primaryContainer }]}>
|
||||
<Ionicons
|
||||
name={item.scope === 'pharmacy' ? 'medical' : 'globe'}
|
||||
size={12}
|
||||
color={colors.primary}
|
||||
/>
|
||||
<Text style={[styles.chipText, { color: colors.onPrimaryContainer }]}>
|
||||
{item.scope === 'pharmacy'
|
||||
? item.pharmacy_name || `Farmacia #${item.pharmacy_id}`
|
||||
: 'Cualquier farmacia'}
|
||||
</Text>
|
||||
</View>
|
||||
{item.pharmacy_address && (
|
||||
<Text style={[styles.itemAddress, { color: colors.textSecondary }]} numberOfLines={1}>
|
||||
{item.pharmacy_address}
|
||||
</Text>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
<TouchableOpacity
|
||||
style={[styles.deleteButton, { backgroundColor: colors.dangerContainer }]}
|
||||
onPress={() => handleDelete(item)}
|
||||
disabled={deletingId === key}
|
||||
>
|
||||
{deletingId === key ? (
|
||||
<Ionicons name="hourglass" size={18} color={colors.danger} />
|
||||
) : (
|
||||
<Ionicons name="trash-outline" size={18} color={colors.danger} />
|
||||
)}
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (isLoading || authLoading) {
|
||||
return <LoadingSpinner message="Cargando notificaciones..." />;
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return (
|
||||
<View style={[styles.container, styles.centered, { backgroundColor: colors.background }]}>
|
||||
<Ionicons name="lock-closed-outline" size={64} color={colors.border} />
|
||||
<Text style={[styles.loginTitle, { color: colors.text }]}>Inicia sesión para continuar</Text>
|
||||
<Text style={[styles.loginSubtitle, { color: colors.textSecondary }]}>
|
||||
Necesitas estar autenticado para ver tus notificaciones
|
||||
</Text>
|
||||
<TouchableOpacity
|
||||
style={[styles.loginButton, { backgroundColor: colors.primary }]}
|
||||
onPress={() => router.push('/auth/login')}
|
||||
>
|
||||
<Text style={[styles.loginButtonText, { color: colors.onPrimaryContainer }]}>Iniciar Sesión</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={[styles.container, { backgroundColor: colors.background }]}>
|
||||
<View style={[styles.header, isTablet && styles.headerTablet]}>
|
||||
<Text style={[styles.title, isTablet && styles.titleTablet, { color: colors.text }]}>Notificaciones Guardadas</Text>
|
||||
<Text style={[styles.subtitle, isTablet && styles.subtitleTablet, { color: colors.textSecondary }]}>
|
||||
Recibe avisos cuando medicamentos sin stock se repongan
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
{error && (
|
||||
<View style={[styles.errorContainer, isTablet && styles.errorContainerTablet, { backgroundColor: colors.dangerContainer }]}>
|
||||
<Text style={[styles.errorText, { color: colors.danger }]}>{error}</Text>
|
||||
<TouchableOpacity onPress={loadNotifications} style={styles.retryButton}>
|
||||
<Text style={[styles.retryText, { color: colors.primary }]}>Reintentar</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{!error && items.length === 0 && (
|
||||
<View style={styles.emptyContainer}>
|
||||
<Ionicons name="notifications-off-outline" size={isTablet ? 80 : 64} color={colors.border} />
|
||||
<Text style={[styles.emptyTitle, isTablet && styles.emptyTitleTablet, { color: colors.text }]}>Sin notificaciones</Text>
|
||||
<Text style={[styles.emptyText, isTablet && styles.emptyTextTablet, { color: colors.textSecondary }]}>
|
||||
Toca la campana en una farmacia sin stock para recibir notificaciones cuando se reponga.
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{!error && items.length > 0 && (
|
||||
<FlatList
|
||||
data={items}
|
||||
keyExtractor={(item) => `${item.scope}:${item.id}`}
|
||||
renderItem={renderItem}
|
||||
contentContainerStyle={[styles.list, isTablet && styles.listTablet]}
|
||||
showsVerticalScrollIndicator={false}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
},
|
||||
centered: {
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
paddingHorizontal: spacing.xl,
|
||||
gap: spacing.md,
|
||||
},
|
||||
loginTitle: {
|
||||
fontSize: 20,
|
||||
fontWeight: '600',
|
||||
textAlign: 'center',
|
||||
},
|
||||
loginSubtitle: {
|
||||
fontSize: 14,
|
||||
textAlign: 'center',
|
||||
lineHeight: 20,
|
||||
},
|
||||
loginButton: {
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingVertical: spacing.md,
|
||||
borderRadius: borderRadius.lg,
|
||||
marginTop: spacing.sm,
|
||||
},
|
||||
loginButtonText: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
},
|
||||
header: {
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingTop: spacing.lg,
|
||||
paddingBottom: spacing.md,
|
||||
},
|
||||
headerTablet: {
|
||||
maxWidth: 700,
|
||||
alignSelf: 'center',
|
||||
width: '100%',
|
||||
},
|
||||
title: {
|
||||
fontSize: 22,
|
||||
fontWeight: 'bold',
|
||||
},
|
||||
titleTablet: {
|
||||
fontSize: 28,
|
||||
},
|
||||
subtitle: {
|
||||
fontSize: 14,
|
||||
marginTop: spacing.xs,
|
||||
lineHeight: 20,
|
||||
},
|
||||
subtitleTablet: {
|
||||
fontSize: 16,
|
||||
lineHeight: 24,
|
||||
},
|
||||
list: {
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingBottom: spacing.xl,
|
||||
gap: spacing.sm,
|
||||
},
|
||||
listTablet: {
|
||||
maxWidth: 700,
|
||||
alignSelf: 'center',
|
||||
width: '100%',
|
||||
},
|
||||
item: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
borderRadius: borderRadius.lg,
|
||||
padding: spacing.md,
|
||||
...shadows.card,
|
||||
},
|
||||
itemContent: {
|
||||
flex: 1,
|
||||
gap: spacing.xs,
|
||||
},
|
||||
itemName: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
lineHeight: 22,
|
||||
},
|
||||
itemMeta: {
|
||||
gap: spacing.xs,
|
||||
},
|
||||
chip: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.xs,
|
||||
borderRadius: borderRadius.full,
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: 3,
|
||||
alignSelf: 'flex-start',
|
||||
},
|
||||
chipText: {
|
||||
fontSize: 12,
|
||||
fontWeight: '600',
|
||||
},
|
||||
itemAddress: {
|
||||
fontSize: 12,
|
||||
},
|
||||
deleteButton: {
|
||||
width: 36,
|
||||
height: 36,
|
||||
borderRadius: 18,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
marginLeft: spacing.sm,
|
||||
},
|
||||
errorContainer: {
|
||||
margin: spacing.lg,
|
||||
padding: spacing.md,
|
||||
borderRadius: borderRadius.lg,
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
},
|
||||
errorContainerTablet: {
|
||||
maxWidth: 700,
|
||||
alignSelf: 'center',
|
||||
},
|
||||
errorText: {
|
||||
fontSize: 14,
|
||||
textAlign: 'center',
|
||||
},
|
||||
retryButton: {
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: spacing.xs,
|
||||
},
|
||||
retryText: {
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
},
|
||||
emptyContainer: {
|
||||
flex: 1,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
paddingHorizontal: spacing.xl,
|
||||
gap: spacing.md,
|
||||
},
|
||||
emptyTitle: {
|
||||
fontSize: 18,
|
||||
fontWeight: '600',
|
||||
},
|
||||
emptyTitleTablet: {
|
||||
fontSize: 24,
|
||||
},
|
||||
emptyText: {
|
||||
fontSize: 14,
|
||||
textAlign: 'center',
|
||||
lineHeight: 20,
|
||||
},
|
||||
emptyTextTablet: {
|
||||
fontSize: 16,
|
||||
maxWidth: 400,
|
||||
lineHeight: 24,
|
||||
},
|
||||
});
|
||||
@@ -1,89 +1,61 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { View, FlatList, StyleSheet, Text, TouchableOpacity } from 'react-native';
|
||||
import React from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity, Image, useWindowDimensions } from 'react-native';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { SearchBar } from '../../components/SearchBar';
|
||||
import { MedicineCard } from '../../components/MedicineCard';
|
||||
import { LoadingSpinner } from '../../components/LoadingSpinner';
|
||||
import { useDebounce } from '../../hooks/useDebounce';
|
||||
import { searchMedicines } from '../../services/medicines';
|
||||
import { colors, spacing, borderRadius } from '../../constants/theme';
|
||||
import { Medicine } from '../../types';
|
||||
import { config } from '../../constants/config';
|
||||
import { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { spacing, borderRadius, shadows } from '../../constants/theme';
|
||||
|
||||
const TABLET_MIN_WIDTH = 768;
|
||||
|
||||
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);
|
||||
};
|
||||
const { width } = useWindowDimensions();
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
const { colors } = useThemeContext();
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<View style={styles.searchContainer}>
|
||||
<SearchBar
|
||||
onSearch={handleSearch}
|
||||
value={query}
|
||||
onChangeText={setQuery}
|
||||
<View style={[styles.container, { backgroundColor: colors.background }]}>
|
||||
<View style={[styles.hero, isTablet && styles.heroTablet]}>
|
||||
<Image
|
||||
source={require('../../assets/farmaclic_logo.png')}
|
||||
style={[styles.logo, isTablet && styles.logoTablet]}
|
||||
resizeMode="contain"
|
||||
/>
|
||||
<Text style={[styles.brandName, isTablet && styles.brandNameTablet, { color: colors.text }]}>FarmaClic</Text>
|
||||
<Text style={[styles.description, isTablet && styles.descriptionTablet, { color: colors.textSecondary }]}>
|
||||
Encuentra tus medicamentos en farmacias cercanas
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<View style={[styles.cards, isTablet && styles.cardsTablet]}>
|
||||
<TouchableOpacity
|
||||
style={styles.scannerButton}
|
||||
style={[styles.card, isTablet && styles.cardTablet, { backgroundColor: colors.primaryContainer }]}
|
||||
activeOpacity={0.85}
|
||||
onPress={() => router.push('/(tabs)/search')}
|
||||
>
|
||||
<View style={[styles.cardIcon, styles.cardIconSearch]}>
|
||||
<Ionicons name="search" size={isTablet ? 28 : 24} color={colors.onPrimaryContainer} />
|
||||
</View>
|
||||
<View style={styles.cardContent}>
|
||||
<Text style={[styles.cardLabel, isTablet && styles.cardLabelTablet, { color: colors.onPrimaryContainer }]}>Buscar Medicamento</Text>
|
||||
<Ionicons name="chevron-forward" size={20} color={colors.onPrimaryContainer} style={{ opacity: 0.7 }} />
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
|
||||
<TouchableOpacity
|
||||
style={[styles.card, styles.cardScan, isTablet && styles.cardTablet]}
|
||||
activeOpacity={0.85}
|
||||
onPress={() => router.push('/scanner')}
|
||||
>
|
||||
<Ionicons name="scan" size={24} color={colors.primary} />
|
||||
<View style={[styles.cardIcon, styles.cardIconScan]}>
|
||||
<Ionicons name="scan" size={isTablet ? 28 : 24} color="#ffffff" />
|
||||
</View>
|
||||
<View style={styles.cardContent}>
|
||||
<Text style={[styles.cardLabel, styles.cardLabelScan, isTablet && styles.cardLabelTablet]}>Escanear TSI</Text>
|
||||
<Ionicons name="chevron-forward" size={20} color="#ffffff" style={{ opacity: 0.7 }} />
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
{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>
|
||||
);
|
||||
}
|
||||
@@ -91,37 +63,101 @@ export default function HomeScreen() {
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: colors.background,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
paddingHorizontal: spacing.lg,
|
||||
gap: spacing.lg,
|
||||
},
|
||||
searchContainer: {
|
||||
hero: {
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
heroTablet: {
|
||||
marginBottom: spacing.xl,
|
||||
},
|
||||
logo: {
|
||||
width: 120,
|
||||
height: 120,
|
||||
marginBottom: spacing.xs,
|
||||
},
|
||||
logoTablet: {
|
||||
width: 160,
|
||||
height: 160,
|
||||
},
|
||||
brandName: {
|
||||
fontSize: 28,
|
||||
fontWeight: 'bold',
|
||||
letterSpacing: -0.5,
|
||||
},
|
||||
brandNameTablet: {
|
||||
fontSize: 36,
|
||||
},
|
||||
description: {
|
||||
fontSize: 16,
|
||||
textAlign: 'center',
|
||||
maxWidth: 260,
|
||||
lineHeight: 24,
|
||||
},
|
||||
descriptionTablet: {
|
||||
fontSize: 18,
|
||||
maxWidth: 400,
|
||||
lineHeight: 28,
|
||||
},
|
||||
cards: {
|
||||
width: '100%',
|
||||
maxWidth: 320,
|
||||
gap: spacing.md,
|
||||
},
|
||||
cardsTablet: {
|
||||
maxWidth: 480,
|
||||
},
|
||||
card: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
},
|
||||
scannerButton: {
|
||||
marginRight: spacing.md,
|
||||
padding: spacing.sm,
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.md,
|
||||
},
|
||||
list: {
|
||||
paddingBottom: spacing.xl,
|
||||
},
|
||||
errorContainer: {
|
||||
gap: spacing.md,
|
||||
borderRadius: borderRadius.lg,
|
||||
padding: spacing.md,
|
||||
marginHorizontal: spacing.md,
|
||||
backgroundColor: '#F8D7DA',
|
||||
borderRadius: 8,
|
||||
minHeight: 64,
|
||||
...shadows.card,
|
||||
},
|
||||
errorText: {
|
||||
color: '#721C24',
|
||||
textAlign: 'center',
|
||||
cardTablet: {
|
||||
padding: spacing.lg,
|
||||
minHeight: 72,
|
||||
},
|
||||
emptyContainer: {
|
||||
padding: spacing.xl,
|
||||
cardScan: {
|
||||
backgroundColor: '#2b5bb5',
|
||||
},
|
||||
cardIcon: {
|
||||
width: 48,
|
||||
height: 48,
|
||||
borderRadius: borderRadius.md,
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.2)',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
flexShrink: 0,
|
||||
},
|
||||
emptyText: {
|
||||
color: colors.textSecondary,
|
||||
fontSize: 16,
|
||||
cardIconSearch: {
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.3)',
|
||||
},
|
||||
cardIconScan: {
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.2)',
|
||||
},
|
||||
cardContent: {
|
||||
flex: 1,
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
},
|
||||
cardLabel: {
|
||||
fontSize: 18,
|
||||
fontWeight: '700',
|
||||
lineHeight: 24,
|
||||
},
|
||||
cardLabelTablet: {
|
||||
fontSize: 20,
|
||||
},
|
||||
cardLabelScan: {
|
||||
color: '#ffffff',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -4,15 +4,17 @@ import MapView, { Marker } from 'react-native-maps';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { getPharmacies } from '../../services/pharmacies';
|
||||
import { LoadingSpinner } from '../../components/LoadingSpinner';
|
||||
import { colors, spacing } from '../../constants/theme';
|
||||
import { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { spacing, borderRadius } from '../../constants/theme';
|
||||
import { Pharmacy } from '../../types';
|
||||
|
||||
export default function MapScreen() {
|
||||
const router = useRouter();
|
||||
const { colors } = useThemeContext();
|
||||
const [pharmacies, setPharmacies] = useState<Pharmacy[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [region, setRegion] = useState({
|
||||
latitude: 40.4168, // Madrid default
|
||||
latitude: 40.4168,
|
||||
longitude: -3.7038,
|
||||
latitudeDelta: 0.0922,
|
||||
longitudeDelta: 0.0421,
|
||||
@@ -24,7 +26,6 @@ export default function MapScreen() {
|
||||
const data = await getPharmacies();
|
||||
setPharmacies(data);
|
||||
|
||||
// Center map on first pharmacy if available
|
||||
if (data.length > 0) {
|
||||
setRegion({
|
||||
latitude: data[0].latitude,
|
||||
@@ -70,8 +71,8 @@ export default function MapScreen() {
|
||||
))}
|
||||
</MapView>
|
||||
|
||||
<View style={styles.legend}>
|
||||
<Text style={styles.legendText}>
|
||||
<View style={[styles.legend, { backgroundColor: colors.card }]}>
|
||||
<Text style={[styles.legendText, { color: colors.text }]}>
|
||||
{pharmacies.length} farmacias en el mapa
|
||||
</Text>
|
||||
</View>
|
||||
@@ -91,18 +92,16 @@ const styles = StyleSheet.create({
|
||||
bottom: spacing.lg,
|
||||
left: spacing.md,
|
||||
right: spacing.md,
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: 8,
|
||||
padding: spacing.sm,
|
||||
borderRadius: borderRadius.lg,
|
||||
padding: spacing.sm + 4,
|
||||
alignItems: 'center',
|
||||
shadowColor: '#000',
|
||||
shadowOffset: { width: 0, height: 2 },
|
||||
shadowOpacity: 0.25,
|
||||
shadowRadius: 4,
|
||||
elevation: 5,
|
||||
shadowOffset: { width: 0, height: 4 },
|
||||
shadowOpacity: 0.08,
|
||||
shadowRadius: 20,
|
||||
elevation: 4,
|
||||
},
|
||||
legendText: {
|
||||
fontSize: 14,
|
||||
color: colors.text,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,219 +1,696 @@
|
||||
import React from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity, Alert } from 'react-native';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity, Alert, TextInput, ScrollView, Image, ActivityIndicator, Modal, Pressable, useWindowDimensions } from 'react-native';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import * as ImagePicker from 'expo-image-picker';
|
||||
import { useAuth } from '../../hooks/useAuth';
|
||||
import { colors, spacing, borderRadius } from '../../constants/theme';
|
||||
import { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { useThemeStore, ThemeMode } from '../../store/themeStore';
|
||||
import { spacing, borderRadius, shadows } from '../../constants/theme';
|
||||
import api from '../../services/api';
|
||||
|
||||
const TABLET_MIN_WIDTH = 768;
|
||||
|
||||
const AVATARS = [
|
||||
require('../../assets/avatars/avatar1.png'),
|
||||
require('../../assets/avatars/avatar2.png'),
|
||||
require('../../assets/avatars/avatar3.png'),
|
||||
require('../../assets/avatars/avatar4.png'),
|
||||
require('../../assets/avatars/avatar5.png'),
|
||||
require('../../assets/avatars/avatar6.png'),
|
||||
];
|
||||
|
||||
const COLOR_CIRCLES = [
|
||||
require('../../assets/avatars/color1.png'),
|
||||
require('../../assets/avatars/color2.png'),
|
||||
require('../../assets/avatars/color3.png'),
|
||||
require('../../assets/avatars/color4.png'),
|
||||
require('../../assets/avatars/color5.png'),
|
||||
require('../../assets/avatars/color6.png'),
|
||||
];
|
||||
|
||||
function resolveAvatarUrl(url: string | null | undefined): number | null {
|
||||
if (!url) return null;
|
||||
const matchPreset = url.match(/^preset_avatar_(\d+)$/);
|
||||
if (matchPreset) {
|
||||
const idx = parseInt(matchPreset[1], 10);
|
||||
if (idx >= 1 && idx <= 6) return AVATARS[idx - 1];
|
||||
}
|
||||
const matchColor = url.match(/^color_circle_(\d+)$/);
|
||||
if (matchColor) {
|
||||
const idx = parseInt(matchColor[1], 10);
|
||||
if (idx >= 1 && idx <= 6) return COLOR_CIRCLES[idx - 1];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
interface SearchHistoryItem {
|
||||
id: number;
|
||||
address: string;
|
||||
latitude: number | null;
|
||||
longitude: number | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
interface Address {
|
||||
id: number;
|
||||
address: string;
|
||||
latitude: number | null;
|
||||
longitude: number | null;
|
||||
label: string;
|
||||
is_default: number;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
const THEME_OPTIONS: { mode: ThemeMode; label: string; icon: string }[] = [
|
||||
{ mode: 'system', label: 'Sistema', icon: 'phone-portrait-outline' },
|
||||
{ mode: 'light', label: 'Claro', icon: 'sunny-outline' },
|
||||
{ mode: 'dark', label: 'Oscuro', icon: 'moon-outline' },
|
||||
];
|
||||
|
||||
export default function ProfileScreen() {
|
||||
const router = useRouter();
|
||||
const { width } = useWindowDimensions();
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
const { user, isAuthenticated, isLoading, logout, isAdmin } = useAuth();
|
||||
const { colors, isDark } = useThemeContext();
|
||||
const themeMode = useThemeStore((s) => s.mode);
|
||||
const setThemeMode = useThemeStore((s) => s.setMode);
|
||||
|
||||
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');
|
||||
const initialResolved = resolveAvatarUrl(user?.avatar_url);
|
||||
const [firstName, setFirstName] = useState(user?.first_name || '');
|
||||
const [lastName, setLastName] = useState(user?.last_name || '');
|
||||
const [avatarUrl, setAvatarUrl] = useState(initialResolved ? '' : (user?.avatar_url || ''));
|
||||
const [avatarLocalSource, setAvatarLocalSource] = useState<number | null>(initialResolved);
|
||||
const [searchHistory, setSearchHistory] = useState<SearchHistoryItem[]>([]);
|
||||
|
||||
const [showAvatarModal, setShowAvatarModal] = useState(false);
|
||||
const [avatarTab, setAvatarTab] = useState<'presets' | 'colors' | 'upload'>('presets');
|
||||
|
||||
const [showConfig, setShowConfig] = useState(false);
|
||||
const [configFirstName, setConfigFirstName] = useState('');
|
||||
const [configLastName, setConfigLastName] = useState('');
|
||||
const [configEmail, setConfigEmail] = useState('');
|
||||
const [configCity, setConfigCity] = useState('');
|
||||
const [configAddress, setConfigAddress] = useState('');
|
||||
const [configSaving, setConfigSaving] = useState(false);
|
||||
const [configFeedback, setConfigFeedback] = useState<{ type: 'ok' | 'err'; text: string } | null>(null);
|
||||
|
||||
const [showAddresses, setShowAddresses] = useState(false);
|
||||
const [addresses, setAddresses] = useState<Address[]>([]);
|
||||
const [addressesLoading, setAddressesLoading] = useState(false);
|
||||
const [showAddressForm, setShowAddressForm] = useState(false);
|
||||
const [editingAddressId, setEditingAddressId] = useState<number | null>(null);
|
||||
const [formAddress, setFormAddress] = useState('');
|
||||
const [formLabel, setFormLabel] = useState('');
|
||||
const [formDefault, setFormDefault] = useState(false);
|
||||
const [formSaving, setFormSaving] = useState(false);
|
||||
const [formError, setFormError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuthenticated) loadSearchHistory();
|
||||
}, [isAuthenticated]);
|
||||
|
||||
useEffect(() => {
|
||||
setFirstName(user?.first_name || '');
|
||||
setLastName(user?.last_name || '');
|
||||
const resolved = resolveAvatarUrl(user?.avatar_url);
|
||||
if (resolved) { setAvatarLocalSource(resolved); setAvatarUrl(''); }
|
||||
else { setAvatarLocalSource(null); setAvatarUrl(user?.avatar_url || ''); }
|
||||
}, [user]);
|
||||
|
||||
async function loadSearchHistory() {
|
||||
try { const res = await api.get('/search-history'); setSearchHistory(res.data); } catch {}
|
||||
}
|
||||
},
|
||||
]
|
||||
);
|
||||
|
||||
function openConfig() {
|
||||
setConfigFirstName(user?.first_name || '');
|
||||
setConfigLastName(user?.last_name || '');
|
||||
setConfigEmail(user?.email || '');
|
||||
setConfigCity(user?.city || '');
|
||||
setConfigAddress(user?.address || '');
|
||||
setConfigFeedback(null);
|
||||
setShowConfig(true);
|
||||
}
|
||||
|
||||
async function handleConfigSave() {
|
||||
setConfigSaving(true);
|
||||
setConfigFeedback(null);
|
||||
try {
|
||||
const res = await api.put('/users/me', {
|
||||
first_name: configFirstName.trim() || null,
|
||||
last_name: configLastName.trim() || null,
|
||||
email: configEmail.trim() || null,
|
||||
city: configCity.trim() || null,
|
||||
address: configAddress.trim() || null,
|
||||
});
|
||||
setFirstName(res.data.first_name || '');
|
||||
setLastName(res.data.last_name || '');
|
||||
setConfigFeedback({ type: 'ok', text: 'Perfil guardado.' });
|
||||
setTimeout(() => setShowConfig(false), 1200);
|
||||
} catch (err: any) {
|
||||
setConfigFeedback({ type: 'err', text: err.message || 'Error al guardar' });
|
||||
} finally { setConfigSaving(false); }
|
||||
}
|
||||
|
||||
async function handlePickImage() {
|
||||
const result = await ImagePicker.launchImageLibraryAsync({ mediaTypes: ImagePicker.MediaTypeOptions.Images, allowsEditing: true, aspect: [1, 1], quality: 0.8, base64: true });
|
||||
if (!result.canceled && result.assets[0]?.base64) {
|
||||
const dataUri = `data:${result.assets[0].mimeType};base64,${result.assets[0].base64}`;
|
||||
setAvatarLocalSource(null); setAvatarUrl(dataUri); setShowAvatarModal(false);
|
||||
try { await api.put('/users/me', { avatar_url: dataUri }); } catch {}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleTakePhoto() {
|
||||
const { status } = await ImagePicker.requestCameraPermissionsAsync();
|
||||
if (status !== 'granted') { Alert.alert('Permiso requerido', 'Necesitamos permiso para acceder a la cámara.'); return; }
|
||||
const result = await ImagePicker.launchCameraAsync({ allowsEditing: true, aspect: [1, 1], quality: 0.8, base64: true });
|
||||
if (!result.canceled && result.assets[0]?.base64) {
|
||||
const dataUri = `data:${result.assets[0].mimeType};base64,${result.assets[0].base64}`;
|
||||
setAvatarLocalSource(null); setAvatarUrl(dataUri); setShowAvatarModal(false);
|
||||
try { await api.put('/users/me', { avatar_url: dataUri }); } catch {}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSelectPresetAvatar(index: number) {
|
||||
setAvatarUrl(''); setAvatarLocalSource(AVATARS[index]); setShowAvatarModal(false);
|
||||
try { await api.put('/users/me', { avatar_url: `preset_avatar_${index + 1}` }); } catch {}
|
||||
}
|
||||
|
||||
async function handleSelectColor(index: number) {
|
||||
setAvatarUrl(''); setAvatarLocalSource(COLOR_CIRCLES[index]); setShowAvatarModal(false);
|
||||
try { await api.put('/users/me', { avatar_url: `color_circle_${index + 1}` }); } catch {}
|
||||
}
|
||||
|
||||
async function handleDeleteSearch(id: number) {
|
||||
try { await api.delete(`/search-history/${id}`); setSearchHistory(prev => prev.filter(i => i.id !== id)); } catch {}
|
||||
}
|
||||
|
||||
async function loadAddresses() {
|
||||
setAddressesLoading(true);
|
||||
try { const res = await api.get('/addresses'); setAddresses(res.data); } catch {} finally { setAddressesLoading(false); }
|
||||
}
|
||||
|
||||
function openAddresses() { setShowAddresses(true); loadAddresses(); }
|
||||
|
||||
function openAddAddressForm() {
|
||||
setEditingAddressId(null); setFormAddress(''); setFormLabel(''); setFormDefault(addresses.length === 0); setFormError(''); setShowAddressForm(true);
|
||||
}
|
||||
|
||||
function openEditAddressForm(addr: Address) {
|
||||
setEditingAddressId(addr.id); setFormAddress(addr.address); setFormLabel(addr.label || ''); setFormDefault(Boolean(addr.is_default)); setFormError(''); setShowAddressForm(true);
|
||||
}
|
||||
|
||||
async function handleAddressSave() {
|
||||
const addr = formAddress.trim();
|
||||
if (!addr) { setFormError('La dirección es obligatoria'); return; }
|
||||
setFormSaving(true); setFormError('');
|
||||
try {
|
||||
const url = editingAddressId ? `/api/addresses/${editingAddressId}` : '/api/addresses';
|
||||
const res = await fetch(url, { method: editingAddressId ? 'PUT' : 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', body: JSON.stringify({ address: addr, label: formLabel.trim(), is_default: formDefault }) });
|
||||
if (!res.ok) { const err = await res.json().catch(() => ({})); throw new Error(err.error || 'Error al guardar'); }
|
||||
setShowAddressForm(false); setEditingAddressId(null); loadAddresses();
|
||||
} catch (err: any) { setFormError(err.message); } finally { setFormSaving(false); }
|
||||
}
|
||||
|
||||
async function handleDeleteAddress(id: number) {
|
||||
try { const res = await fetch(`/api/addresses/${id}`, { method: 'DELETE', credentials: 'include' }); if (res.ok) setAddresses(prev => prev.filter(a => a.id !== id)); } catch {}
|
||||
}
|
||||
|
||||
async function handleSetDefault(id: number) {
|
||||
try { const res = await fetch(`/api/addresses/${id}/default`, { method: 'PUT', credentials: 'include' }); if (res.ok) loadAddresses(); } catch {}
|
||||
}
|
||||
|
||||
const handleLogout = () => {
|
||||
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'); } },
|
||||
]);
|
||||
};
|
||||
|
||||
const getThemeModeIcon = (): 'phone-portrait-outline' | 'sunny-outline' | 'moon-outline' => {
|
||||
if (themeMode === 'light') return 'sunny-outline';
|
||||
if (themeMode === 'dark') return 'moon-outline';
|
||||
return 'phone-portrait-outline';
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<Text style={styles.loadingText}>Cargando...</Text>
|
||||
</View>
|
||||
);
|
||||
return <View style={[styles.container, { backgroundColor: colors.background }]}><ActivityIndicator size="large" color={colors.primary} style={{ marginTop: spacing.xxl }} /></View>;
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<View style={[styles.container, { backgroundColor: colors.background }]}>
|
||||
<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
|
||||
<View style={[styles.authIconCircle, { backgroundColor: colors.primaryContainer }]}>
|
||||
<Ionicons name="person-outline" size={isTablet ? 60 : 48} color={colors.primary} />
|
||||
</View>
|
||||
<Text style={[styles.authTitle, isTablet && styles.authTitleTablet, { color: colors.text }]}>Inicia Sesión</Text>
|
||||
<Text style={[styles.authSubtitle, isTablet && styles.authSubtitleTablet, { color: colors.textSecondary }]}>
|
||||
Inicia sesión para acceder a tu perfil, notificaciones y más
|
||||
</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 style={[styles.authButton, { backgroundColor: colors.primary }]} onPress={() => router.push('/auth/login')}>
|
||||
<Text style={[styles.authButtonText, { color: colors.onPrimaryContainer }]}>Iniciar Sesión</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const displayName = [firstName, lastName].filter(Boolean).join(' ') || user?.username;
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<View style={styles.header}>
|
||||
<View style={styles.avatar}>
|
||||
<Ionicons name="person" size={40} color={colors.primary} />
|
||||
<ScrollView style={[styles.container, { backgroundColor: colors.background }]} showsVerticalScrollIndicator={false}>
|
||||
{/* Header card with avatar + name */}
|
||||
<View style={[styles.headerCard, { backgroundColor: colors.card }, shadows.card]}>
|
||||
<TouchableOpacity style={[styles.avatarRing, { borderColor: colors.primary }]} onPress={() => setShowAvatarModal(true)}>
|
||||
{avatarLocalSource ? (
|
||||
<Image source={avatarLocalSource} style={styles.avatarImage} />
|
||||
) : avatarUrl ? (
|
||||
<Image source={{ uri: avatarUrl }} style={styles.avatarImage} />
|
||||
) : (
|
||||
<View style={[styles.avatarFallback, { backgroundColor: colors.primaryContainer }]}>
|
||||
<Ionicons name="person" size={36} color={colors.primary} />
|
||||
</View>
|
||||
<Text style={styles.username}>{user?.username}</Text>
|
||||
{isAdmin && <Text style={styles.adminBadge}>Administrador</Text>}
|
||||
)}
|
||||
<View style={[styles.avatarEditBadge, { backgroundColor: colors.primary }]}>
|
||||
<Ionicons name="camera" size={14} color="#fff" />
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
<Text style={[styles.displayName, { color: colors.text }]}>{displayName}</Text>
|
||||
<Text style={[styles.username, { color: colors.textSecondary }]}>@{user?.username}</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>
|
||||
{/* Info section */}
|
||||
{(firstName || lastName) && (
|
||||
<View style={[styles.card, { backgroundColor: colors.card }, shadows.card]}>
|
||||
<View style={styles.cardHeader}>
|
||||
<Ionicons name="person-outline" size={18} color={colors.primary} />
|
||||
<Text style={[styles.cardTitle, { color: colors.text }]}>Datos personales</Text>
|
||||
</View>
|
||||
<View style={styles.infoGrid}>
|
||||
<View style={[styles.infoBox, { backgroundColor: colors.surfaceLow }]}>
|
||||
<Text style={[styles.infoLabel, { color: colors.textSecondary }]}>Nombre</Text>
|
||||
<Text style={[styles.infoValue, { color: colors.text }]}>{firstName || '—'}</Text>
|
||||
</View>
|
||||
<View style={[styles.infoBox, { backgroundColor: colors.surfaceLow }]}>
|
||||
<Text style={[styles.infoLabel, { color: colors.textSecondary }]}>Apellidos</Text>
|
||||
<Text style={[styles.infoValue, { color: colors.text }]}>{lastName || '—'}</Text>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
)}
|
||||
|
||||
<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} />
|
||||
{/* Theme card */}
|
||||
<View style={[styles.card, { backgroundColor: colors.card }, shadows.card]}>
|
||||
<View style={styles.cardHeader}>
|
||||
<Ionicons name={getThemeModeIcon()} size={18} color={colors.primary} />
|
||||
<Text style={[styles.cardTitle, { color: colors.text }]}>Apariencia</Text>
|
||||
</View>
|
||||
<View style={[styles.themePills, { backgroundColor: colors.surfaceLow }]}>
|
||||
{THEME_OPTIONS.map((opt) => (
|
||||
<TouchableOpacity
|
||||
key={opt.mode}
|
||||
style={[styles.themePill, themeMode === opt.mode && { backgroundColor: colors.primary }]}
|
||||
onPress={() => setThemeMode(opt.mode)}
|
||||
>
|
||||
<Ionicons name={opt.icon as any} size={16} color={themeMode === opt.mode ? colors.onPrimaryContainer : colors.textSecondary} />
|
||||
<Text style={[styles.themePillText, { color: themeMode === opt.mode ? colors.onPrimaryContainer : colors.textSecondary }]}>{opt.label}</Text>
|
||||
</TouchableOpacity>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<TouchableOpacity style={styles.logoutButton} onPress={handleLogout}>
|
||||
<Ionicons name="log-out" size={20} color={colors.danger} />
|
||||
<Text style={styles.logoutText}>Cerrar Sesión</Text>
|
||||
{/* Menu card */}
|
||||
<View style={[styles.card, { backgroundColor: colors.card }, shadows.card]}>
|
||||
<TouchableOpacity style={styles.menuRow} onPress={openConfig}>
|
||||
<View style={[styles.menuIconCircle, { backgroundColor: colors.surfaceLow }]}>
|
||||
<Ionicons name="settings-outline" size={20} color={colors.primary} />
|
||||
</View>
|
||||
<Text style={[styles.menuLabel, { color: colors.text }]}>Configuración</Text>
|
||||
<Ionicons name="chevron-forward" size={18} color={colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
|
||||
<View style={[styles.menuDivider, { backgroundColor: colors.surfaceLow }]} />
|
||||
|
||||
<TouchableOpacity style={styles.menuRow} onPress={openAddresses}>
|
||||
<View style={[styles.menuIconCircle, { backgroundColor: colors.surfaceLow }]}>
|
||||
<Ionicons name="location-outline" size={20} color={colors.primary} />
|
||||
</View>
|
||||
<Text style={[styles.menuLabel, { color: colors.text }]}>Mis Direcciones</Text>
|
||||
<Ionicons name="chevron-forward" size={18} color={colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
|
||||
{isAdmin && (
|
||||
<>
|
||||
<View style={[styles.menuDivider, { backgroundColor: colors.surfaceLow }]} />
|
||||
<TouchableOpacity style={styles.menuRow}>
|
||||
<View style={[styles.menuIconCircle, { backgroundColor: colors.surfaceLow }]}>
|
||||
<Ionicons name="shield-outline" size={20} color={colors.primary} />
|
||||
</View>
|
||||
<Text style={[styles.menuLabel, { color: colors.text }]}>Panel Admin</Text>
|
||||
<Ionicons name="chevron-forward" size={18} color={colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
|
||||
{/* Search history */}
|
||||
{searchHistory.length > 0 && (
|
||||
<View style={[styles.card, { backgroundColor: colors.card }, shadows.card]}>
|
||||
<View style={styles.cardHeader}>
|
||||
<Ionicons name="time-outline" size={18} color={colors.primary} />
|
||||
<Text style={[styles.cardTitle, { color: colors.text }]}>Búsquedas recientes</Text>
|
||||
</View>
|
||||
{searchHistory.map((item, i) => (
|
||||
<React.Fragment key={item.id}>
|
||||
{i > 0 && <View style={[styles.menuDivider, { backgroundColor: colors.surfaceLow }]} />}
|
||||
<View style={styles.historyRow}>
|
||||
<Ionicons name="location-outline" size={16} color={colors.textSecondary} />
|
||||
<Text style={[styles.historyAddress, { color: colors.text }]} numberOfLines={1}>{item.address}</Text>
|
||||
<TouchableOpacity onPress={() => handleDeleteSearch(item.id)} hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}>
|
||||
<Ionicons name="close-circle" size={18} color={colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</React.Fragment>
|
||||
))}
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Logout */}
|
||||
<TouchableOpacity style={[styles.logoutCard, { backgroundColor: colors.card, borderColor: isDark ? '#5a2020' : '#fecaca' }]} onPress={handleLogout}>
|
||||
<Ionicons name="log-out-outline" size={20} color={colors.danger} />
|
||||
<Text style={[styles.logoutText, { color: colors.danger }]}>Cerrar Sesión</Text>
|
||||
</TouchableOpacity>
|
||||
|
||||
<View style={{ height: spacing.xl }} />
|
||||
|
||||
{/* ─── Modals ─── */}
|
||||
|
||||
{/* Avatar Modal */}
|
||||
<Modal visible={showAvatarModal} animationType="slide" transparent>
|
||||
<View style={styles.modalBackdrop}>
|
||||
<View style={[styles.modalSheet, { backgroundColor: colors.card }]}>
|
||||
<View style={[styles.modalHandle, { backgroundColor: colors.border }]} />
|
||||
<View style={[styles.modalHeader, { borderBottomColor: colors.surfaceLow }]}>
|
||||
<Text style={[styles.modalTitle, { color: colors.text }]}>Cambiar Avatar</Text>
|
||||
<TouchableOpacity onPress={() => setShowAvatarModal(false)} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
|
||||
<Ionicons name="close" size={24} color={colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<View style={[styles.avatarTabBar, { borderBottomColor: colors.surfaceLow }]}>
|
||||
{(['presets', 'colors', 'upload'] as const).map((t) => (
|
||||
<TouchableOpacity key={t} style={[styles.avatarTabBtn, avatarTab === t && { borderBottomColor: colors.primary }]} onPress={() => setAvatarTab(t)}>
|
||||
<Ionicons name={t === 'presets' ? 'person-outline' : t === 'colors' ? 'color-palette-outline' : 'cloud-upload-outline'} size={18} color={avatarTab === t ? colors.primary : colors.textSecondary} />
|
||||
<Text style={[styles.avatarTabLabel, { color: avatarTab === t ? colors.primary : colors.textSecondary }]}>{t === 'presets' ? 'Prediseñado' : t === 'colors' ? 'Colores' : 'Subir'}</Text>
|
||||
</TouchableOpacity>
|
||||
))}
|
||||
</View>
|
||||
<ScrollView style={styles.modalBody} contentContainerStyle={{ paddingBottom: spacing.xl }}>
|
||||
{avatarTab === 'presets' && (
|
||||
<View style={styles.avatarGrid}>
|
||||
{AVATARS.map((av, i) => (
|
||||
<TouchableOpacity key={i} style={styles.avatarOption} onPress={() => handleSelectPresetAvatar(i)}>
|
||||
<Image source={av} style={styles.avatarOptionImage} />
|
||||
</TouchableOpacity>
|
||||
))}
|
||||
</View>
|
||||
)}
|
||||
{avatarTab === 'colors' && (
|
||||
<View style={styles.avatarGrid}>
|
||||
{COLOR_CIRCLES.map((c, i) => (
|
||||
<TouchableOpacity key={i} style={styles.avatarOption} onPress={() => handleSelectColor(i)}>
|
||||
<Image source={c} style={styles.avatarOptionImage} />
|
||||
</TouchableOpacity>
|
||||
))}
|
||||
</View>
|
||||
)}
|
||||
{avatarTab === 'upload' && (
|
||||
<View style={{ gap: spacing.md }}>
|
||||
<TouchableOpacity style={[styles.uploadCard, { backgroundColor: colors.surfaceLow }]} onPress={handleTakePhoto}>
|
||||
<View style={[styles.uploadIconCircle, { backgroundColor: colors.primaryContainer }]}>
|
||||
<Ionicons name="camera-outline" size={28} color={colors.primary} />
|
||||
</View>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text style={[styles.uploadTitle, { color: colors.text }]}>Tomar foto</Text>
|
||||
<Text style={[styles.uploadSub, { color: colors.textSecondary }]}>Usa la cámara de tu dispositivo</Text>
|
||||
</View>
|
||||
<Ionicons name="chevron-forward" size={18} color={colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity style={[styles.uploadCard, { backgroundColor: colors.surfaceLow }]} onPress={handlePickImage}>
|
||||
<View style={[styles.uploadIconCircle, { backgroundColor: colors.primaryContainer }]}>
|
||||
<Ionicons name="images-outline" size={28} color={colors.primary} />
|
||||
</View>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text style={[styles.uploadTitle, { color: colors.text }]}>Elegir de galería</Text>
|
||||
<Text style={[styles.uploadSub, { color: colors.textSecondary }]}>Selecciona una imagen existente</Text>
|
||||
</View>
|
||||
<Ionicons name="chevron-forward" size={18} color={colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
)}
|
||||
</ScrollView>
|
||||
</View>
|
||||
</View>
|
||||
</Modal>
|
||||
|
||||
{/* Config Modal */}
|
||||
<Modal visible={showConfig} animationType="slide" transparent>
|
||||
<View style={styles.modalBackdrop}>
|
||||
<View style={[styles.modalSheet, { backgroundColor: colors.card }]}>
|
||||
<View style={[styles.modalHandle, { backgroundColor: colors.border }]} />
|
||||
<View style={[styles.modalHeader, { borderBottomColor: colors.surfaceLow }]}>
|
||||
<Text style={[styles.modalTitle, { color: colors.text }]}>Configuración</Text>
|
||||
<TouchableOpacity onPress={() => setShowConfig(false)} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
|
||||
<Ionicons name="close" size={24} color={colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<ScrollView style={styles.modalBody} contentContainerStyle={{ paddingBottom: spacing.xl }}>
|
||||
{[
|
||||
{ label: 'Nombre', value: configFirstName, onChange: setConfigFirstName, placeholder: 'Tu nombre', icon: 'person-outline' },
|
||||
{ label: 'Apellidos', value: configLastName, onChange: setConfigLastName, placeholder: 'Tus apellidos', icon: 'person-outline' },
|
||||
{ label: 'Correo electrónico', value: configEmail, onChange: setConfigEmail, placeholder: 'tu@email.com', icon: 'mail-outline', keyboard: 'email-address' as const },
|
||||
{ label: 'Ciudad', value: configCity, onChange: setConfigCity, placeholder: 'Tu ciudad', icon: 'business-outline' },
|
||||
{ label: 'Dirección', value: configAddress, onChange: setConfigAddress, placeholder: 'Calle Mayor 1, Madrid', icon: 'location-outline' },
|
||||
].map((field) => (
|
||||
<View key={field.label} style={styles.modalField}>
|
||||
<Text style={[styles.modalLabel, { color: colors.textSecondary }]}>{field.label}</Text>
|
||||
<View style={[styles.modalInputRow, { backgroundColor: colors.surfaceLow, borderColor: colors.border }]}>
|
||||
<Ionicons name={field.icon as any} size={18} color={colors.textSecondary} style={{ marginRight: spacing.sm }} />
|
||||
<TextInput
|
||||
style={[styles.modalInput, { color: colors.text }]}
|
||||
value={field.value}
|
||||
onChangeText={field.onChange}
|
||||
placeholder={field.placeholder}
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
keyboardType={field.keyboard}
|
||||
autoCapitalize="none"
|
||||
editable={!configSaving}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
))}
|
||||
|
||||
{configFeedback && (
|
||||
<View style={[styles.modalFeedback, { backgroundColor: configFeedback.type === 'ok' ? (isDark ? '#1a3a1c' : '#eaf7ec') : colors.dangerContainer, borderColor: configFeedback.type === 'ok' ? (isDark ? '#2a5a35' : '#cfead0') : (isDark ? '#5a2020' : '#fecaca') }]}>
|
||||
<Ionicons name={configFeedback.type === 'ok' ? 'checkmark-circle' : 'alert-circle'} size={18} color={configFeedback.type === 'ok' ? colors.primary : colors.danger} />
|
||||
<Text style={[styles.modalFeedbackText, { color: colors.text }]}>{configFeedback.text}</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
<View style={styles.modalActions}>
|
||||
<TouchableOpacity style={[styles.modalCancelBtn, { borderColor: colors.border }]} onPress={() => setShowConfig(false)} disabled={configSaving}>
|
||||
<Text style={[styles.modalCancelText, { color: colors.text }]}>Cancelar</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity style={[styles.modalSaveBtn, { backgroundColor: colors.primary }, configSaving && { opacity: 0.6 }]} onPress={handleConfigSave} disabled={configSaving}>
|
||||
{configSaving ? <ActivityIndicator color={colors.onPrimaryContainer} /> : <Text style={[styles.modalSaveText, { color: colors.onPrimaryContainer }]}>Guardar</Text>}
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</ScrollView>
|
||||
</View>
|
||||
</View>
|
||||
</Modal>
|
||||
|
||||
{/* Addresses Modal */}
|
||||
<Modal visible={showAddresses} animationType="slide" transparent>
|
||||
<View style={styles.modalBackdrop}>
|
||||
<View style={[styles.modalSheet, { backgroundColor: colors.card }]}>
|
||||
<View style={[styles.modalHandle, { backgroundColor: colors.border }]} />
|
||||
<View style={[styles.modalHeader, { borderBottomColor: colors.surfaceLow }]}>
|
||||
<Text style={[styles.modalTitle, { color: colors.text }]}>Mis Direcciones</Text>
|
||||
<TouchableOpacity onPress={() => { setShowAddresses(false); setShowAddressForm(false); }} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
|
||||
<Ionicons name="close" size={24} color={colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
<ScrollView style={styles.modalBody} contentContainerStyle={{ paddingBottom: spacing.xl }}>
|
||||
{showAddressForm ? (
|
||||
<View>
|
||||
<View style={styles.modalField}>
|
||||
<Text style={[styles.modalLabel, { color: colors.textSecondary }]}>Dirección</Text>
|
||||
<View style={[styles.modalInputRow, { backgroundColor: colors.surfaceLow, borderColor: colors.border }]}>
|
||||
<Ionicons name="location-outline" size={18} color={colors.textSecondary} style={{ marginRight: spacing.sm }} />
|
||||
<TextInput style={[styles.modalInput, { color: colors.text }]} value={formAddress} onChangeText={setFormAddress} placeholder="Calle Mayor 1, Madrid" placeholderTextColor={colors.textSecondary} editable={!formSaving} />
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.modalField}>
|
||||
<Text style={[styles.modalLabel, { color: colors.textSecondary }]}>Etiqueta (opcional)</Text>
|
||||
<View style={[styles.modalInputRow, { backgroundColor: colors.surfaceLow, borderColor: colors.border }]}>
|
||||
<Ionicons name="pricetag-outline" size={18} color={colors.textSecondary} style={{ marginRight: spacing.sm }} />
|
||||
<TextInput style={[styles.modalInput, { color: colors.text }]} value={formLabel} onChangeText={setFormLabel} placeholder="Casa, Trabajo..." placeholderTextColor={colors.textSecondary} editable={!formSaving} />
|
||||
</View>
|
||||
</View>
|
||||
<TouchableOpacity style={styles.checkboxRow} onPress={() => setFormDefault(!formDefault)} disabled={formSaving}>
|
||||
<Ionicons name={formDefault ? 'checkbox' : 'square-outline'} size={22} color={formDefault ? colors.primary : colors.textSecondary} />
|
||||
<Text style={[styles.checkboxLabel, { color: colors.text }]}>Dirección predeterminada</Text>
|
||||
</TouchableOpacity>
|
||||
{formError ? (
|
||||
<View style={[styles.modalFeedback, { backgroundColor: colors.dangerContainer, borderColor: isDark ? '#5a2020' : '#fecaca' }]}>
|
||||
<Text style={[styles.modalFeedbackText, { color: colors.text }]}>{formError}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
<View style={styles.modalActions}>
|
||||
<TouchableOpacity style={[styles.modalCancelBtn, { borderColor: colors.border }]} onPress={() => { setShowAddressForm(false); setFormError(''); }} disabled={formSaving}>
|
||||
<Text style={[styles.modalCancelText, { color: colors.text }]}>Cancelar</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity style={[styles.modalSaveBtn, { backgroundColor: colors.primary }, formSaving && { opacity: 0.6 }]} onPress={handleAddressSave} disabled={formSaving}>
|
||||
{formSaving ? <ActivityIndicator color={colors.onPrimaryContainer} /> : <Text style={[styles.modalSaveText, { color: colors.onPrimaryContainer }]}>{editingAddressId ? 'Actualizar' : 'Añadir'}</Text>}
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
) : (
|
||||
<View>
|
||||
{addressesLoading ? (
|
||||
<ActivityIndicator size="small" color={colors.primary} style={{ paddingVertical: spacing.lg }} />
|
||||
) : (
|
||||
<View style={{ gap: spacing.sm }}>
|
||||
{user?.address && (
|
||||
<View style={[styles.addrCard, { borderColor: colors.primary, backgroundColor: isDark ? '#1a3a1c' : '#eaf7ec' }]}>
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text style={[styles.addrBadge, { color: colors.primary }]}>Principal</Text>
|
||||
<Text style={[styles.addrText, { color: colors.text }]}>{user.address}</Text>
|
||||
</View>
|
||||
<Ionicons name="checkmark-circle" size={20} color={colors.primary} />
|
||||
</View>
|
||||
)}
|
||||
{addresses.map((addr) => (
|
||||
<View key={addr.id} style={[styles.addrCard, { borderColor: colors.border, backgroundColor: colors.surfaceLow }]}>
|
||||
<View style={{ flex: 1 }}>
|
||||
{addr.label ? <Text style={[styles.addrLabel, { color: colors.primary }]}>{addr.label}</Text> : null}
|
||||
<Text style={[styles.addrText, { color: colors.text }]}>{addr.address}</Text>
|
||||
{!addr.is_default && (
|
||||
<TouchableOpacity onPress={() => handleSetDefault(addr.id)}>
|
||||
<Text style={[styles.addrDefaultLink, { color: colors.primary }]}>Marcar como predeterminada</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
<View style={{ gap: spacing.xs, marginLeft: spacing.sm }}>
|
||||
<TouchableOpacity style={[styles.addrAction, { backgroundColor: colors.card }]} onPress={() => openEditAddressForm(addr)}>
|
||||
<Ionicons name="pencil-outline" size={16} color={colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity style={[styles.addrAction, { backgroundColor: colors.card }]} onPress={() => handleDeleteAddress(addr.id)}>
|
||||
<Ionicons name="trash-outline" size={16} color={colors.danger} />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
))}
|
||||
<TouchableOpacity style={[styles.addAddrBtn, { borderColor: colors.border }]} onPress={openAddAddressForm}>
|
||||
<Ionicons name="add-circle-outline" size={20} color={colors.primary} />
|
||||
<Text style={[styles.addAddrText, { color: colors.primary }]}>Añadir dirección</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
)}
|
||||
</ScrollView>
|
||||
</View>
|
||||
</View>
|
||||
</Modal>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
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',
|
||||
},
|
||||
container: { flex: 1 },
|
||||
// Auth prompt
|
||||
authPrompt: { flex: 1, justifyContent: 'center', alignItems: 'center', paddingHorizontal: spacing.xl, gap: spacing.md },
|
||||
authIconCircle: { width: 100, height: 100, borderRadius: 50, justifyContent: 'center', alignItems: 'center' },
|
||||
authTitle: { fontSize: 24, fontWeight: '700', marginTop: spacing.sm },
|
||||
authTitleTablet: { fontSize: 32 },
|
||||
authSubtitle: { fontSize: 15, textAlign: 'center', lineHeight: 22 },
|
||||
authSubtitleTablet: { fontSize: 17, maxWidth: 400 },
|
||||
authButton: { paddingHorizontal: spacing.xl, paddingVertical: spacing.md, borderRadius: borderRadius.lg, marginTop: spacing.sm },
|
||||
authButtonText: { fontSize: 16, fontWeight: '700' },
|
||||
// Header card
|
||||
headerCard: { alignItems: 'center', marginHorizontal: spacing.lg, marginTop: spacing.lg, borderRadius: borderRadius.xl, paddingVertical: spacing.xl, gap: spacing.xs },
|
||||
avatarRing: { width: 104, height: 104, borderRadius: 52, borderWidth: 3, padding: 2, overflow: 'hidden' },
|
||||
avatarImage: { width: '100%', height: '100%', borderRadius: 50 },
|
||||
avatarFallback: { width: '100%', height: '100%', borderRadius: 50, justifyContent: 'center', alignItems: 'center' },
|
||||
avatarEditBadge: { position: 'absolute', bottom: 2, right: 2, width: 28, height: 28, borderRadius: 14, justifyContent: 'center', alignItems: 'center', borderWidth: 2, borderColor: '#fff' },
|
||||
displayName: { fontSize: 20, fontWeight: '700', marginTop: spacing.sm },
|
||||
username: { fontSize: 14 },
|
||||
// Cards
|
||||
card: { marginHorizontal: spacing.lg, marginTop: spacing.md, borderRadius: borderRadius.xl, padding: spacing.lg },
|
||||
cardHeader: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, marginBottom: spacing.md },
|
||||
cardTitle: { fontSize: 15, fontWeight: '700' },
|
||||
// Info grid
|
||||
infoGrid: { flexDirection: 'row', gap: spacing.sm },
|
||||
infoBox: { flex: 1, borderRadius: borderRadius.md, padding: spacing.md },
|
||||
infoLabel: { fontSize: 11, fontWeight: '600', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 2 },
|
||||
infoValue: { fontSize: 15, fontWeight: '500' },
|
||||
// Theme
|
||||
themePills: { flexDirection: 'row', borderRadius: borderRadius.md, padding: 3 },
|
||||
themePill: { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 4, paddingVertical: spacing.sm + 2, borderRadius: borderRadius.sm },
|
||||
themePillText: { fontSize: 13, fontWeight: '500' },
|
||||
// Menu
|
||||
menuRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.md, paddingVertical: spacing.sm + 2 },
|
||||
menuIconCircle: { width: 36, height: 36, borderRadius: 18, justifyContent: 'center', alignItems: 'center' },
|
||||
menuLabel: { flex: 1, fontSize: 15, fontWeight: '500' },
|
||||
menuDivider: { height: 1, marginVertical: spacing.xs },
|
||||
// History
|
||||
historyRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, paddingVertical: spacing.sm },
|
||||
historyAddress: { flex: 1, fontSize: 14 },
|
||||
// Logout
|
||||
logoutCard: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', marginHorizontal: spacing.lg, marginTop: spacing.md, padding: spacing.md, borderRadius: borderRadius.xl, borderWidth: 1, gap: spacing.sm },
|
||||
logoutText: { fontSize: 15, fontWeight: '600' },
|
||||
// Modal shared
|
||||
modalBackdrop: { flex: 1, backgroundColor: 'rgba(0,0,0,0.45)', justifyContent: 'flex-end' },
|
||||
modalSheet: { borderTopLeftRadius: 20, borderTopRightRadius: 20, maxHeight: '90%' },
|
||||
modalHandle: { width: 36, height: 4, borderRadius: 2, alignSelf: 'center', marginTop: spacing.sm, marginBottom: spacing.xs },
|
||||
modalHeader: { flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', paddingHorizontal: spacing.lg, paddingVertical: spacing.md, borderBottomWidth: 1 },
|
||||
modalTitle: { fontSize: 17, fontWeight: '700' },
|
||||
modalBody: { padding: spacing.lg },
|
||||
modalField: { marginBottom: spacing.md },
|
||||
modalLabel: { fontSize: 13, fontWeight: '600', marginBottom: spacing.xs },
|
||||
modalInputRow: { flexDirection: 'row', alignItems: 'center', borderRadius: borderRadius.md, borderWidth: 1, paddingHorizontal: spacing.md },
|
||||
modalInput: { flex: 1, paddingVertical: spacing.md, fontSize: 16 },
|
||||
modalFeedback: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, padding: spacing.md, borderRadius: borderRadius.md, marginBottom: spacing.md, borderWidth: 1 },
|
||||
modalFeedbackText: { fontSize: 14, flex: 1 },
|
||||
modalActions: { flexDirection: 'row', justifyContent: 'flex-end', gap: spacing.md, marginTop: spacing.md },
|
||||
modalCancelBtn: { paddingVertical: spacing.md, paddingHorizontal: spacing.lg, borderRadius: borderRadius.md, borderWidth: 1 },
|
||||
modalCancelText: { fontSize: 15, fontWeight: '500' },
|
||||
modalSaveBtn: { paddingVertical: spacing.md, paddingHorizontal: spacing.xl, borderRadius: borderRadius.md, minWidth: 100, alignItems: 'center' },
|
||||
modalSaveText: { fontSize: 15, fontWeight: '700' },
|
||||
// Avatar modal
|
||||
avatarTabBar: { flexDirection: 'row', borderBottomWidth: 1 },
|
||||
avatarTabBtn: { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: spacing.xs, paddingVertical: spacing.md, borderBottomWidth: 2, borderBottomColor: 'transparent' },
|
||||
avatarTabLabel: { fontSize: 13, fontWeight: '500' },
|
||||
avatarGrid: { flexDirection: 'row', flexWrap: 'wrap', gap: spacing.md },
|
||||
avatarOption: { width: '30%', aspectRatio: 1 },
|
||||
avatarOptionImage: { width: '100%', height: '100%', borderRadius: borderRadius.lg },
|
||||
uploadCard: { flexDirection: 'row', alignItems: 'center', padding: spacing.md, borderRadius: borderRadius.lg, gap: spacing.md },
|
||||
uploadIconCircle: { width: 48, height: 48, borderRadius: 24, justifyContent: 'center', alignItems: 'center' },
|
||||
uploadTitle: { fontSize: 15, fontWeight: '600' },
|
||||
uploadSub: { fontSize: 13, marginTop: 1 },
|
||||
// Addresses
|
||||
addrCard: { flexDirection: 'row', alignItems: 'flex-start', padding: spacing.md, borderRadius: borderRadius.lg, borderWidth: 1 },
|
||||
addrLabel: { fontSize: 12, fontWeight: '700', textTransform: 'uppercase', marginBottom: 2 },
|
||||
addrBadge: { fontSize: 12, fontWeight: '700', textTransform: 'uppercase', marginBottom: 2 },
|
||||
addrText: { fontSize: 14, lineHeight: 20 },
|
||||
addrDefaultLink: { fontSize: 12, fontWeight: '600', marginTop: 4, textDecorationLine: 'underline' },
|
||||
addrAction: { width: 32, height: 32, borderRadius: 8, justifyContent: 'center', alignItems: 'center' },
|
||||
addAddrBtn: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: spacing.sm, padding: spacing.md, marginTop: spacing.sm, borderWidth: 2, borderStyle: 'dashed', borderRadius: borderRadius.lg },
|
||||
addAddrText: { fontSize: 15, fontWeight: '600' },
|
||||
checkboxRow: { flexDirection: 'row', alignItems: 'center', gap: spacing.sm, marginBottom: spacing.md },
|
||||
checkboxLabel: { fontSize: 14 },
|
||||
});
|
||||
|
||||
@@ -0,0 +1,347 @@
|
||||
import React, { useState } from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity, TextInput, Alert, useWindowDimensions, ScrollView } from 'react-native';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { useRouter } from 'expo-router';
|
||||
import * as ImagePicker from 'expo-image-picker';
|
||||
import { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { spacing, borderRadius, shadows } from '../../constants/theme';
|
||||
|
||||
const TABLET_MIN_WIDTH = 768;
|
||||
|
||||
export default function ScanTabScreen() {
|
||||
const router = useRouter();
|
||||
const { width } = useWindowDimensions();
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
const { colors } = useThemeContext();
|
||||
const [manualNumber, setManualNumber] = useState('');
|
||||
const [selectedImage, setSelectedImage] = useState<string | null>(null);
|
||||
|
||||
const handleTakePhoto = async () => {
|
||||
const { status } = await ImagePicker.requestCameraPermissionsAsync();
|
||||
if (status !== 'granted') {
|
||||
Alert.alert(
|
||||
'Permiso requerido',
|
||||
'Necesitamos acceso a la cámara para tomar fotos del dispositivo.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await ImagePicker.launchCameraAsync({
|
||||
mediaTypes: ['images'],
|
||||
allowsEditing: true,
|
||||
quality: 0.8,
|
||||
});
|
||||
|
||||
if (!result.canceled && result.assets[0]) {
|
||||
setSelectedImage(result.assets[0].uri);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelectFromGallery = async () => {
|
||||
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
|
||||
if (status !== 'granted') {
|
||||
Alert.alert(
|
||||
'Permiso requerido',
|
||||
'Necesitamos acceso a la galería para seleccionar fotos.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await ImagePicker.launchImageLibraryAsync({
|
||||
mediaTypes: ['images'],
|
||||
allowsEditing: true,
|
||||
quality: 0.8,
|
||||
});
|
||||
|
||||
if (!result.canceled && result.assets[0]) {
|
||||
setSelectedImage(result.assets[0].uri);
|
||||
}
|
||||
};
|
||||
|
||||
const handleManualSubmit = () => {
|
||||
const trimmed = manualNumber.trim();
|
||||
if (trimmed.length === 0) {
|
||||
Alert.alert('Campo requerido', 'Por favor, introduce el número de la tarjeta.');
|
||||
return;
|
||||
}
|
||||
router.push(`/medicine/${trimmed}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<ScrollView
|
||||
style={[styles.scrollContainer, { backgroundColor: colors.background }]}
|
||||
contentContainerStyle={styles.scrollContent}
|
||||
>
|
||||
<View style={[styles.content, isTablet && styles.contentTablet]}>
|
||||
<View style={[styles.iconContainer, isTablet && styles.iconContainerTablet, { backgroundColor: colors.primaryContainer }]}>
|
||||
<Ionicons name="scan" size={isTablet ? 80 : 64} color={colors.scanButton} />
|
||||
</View>
|
||||
<Text style={[styles.title, isTablet && styles.titleTablet, { color: colors.text }]}>Escanear TSI</Text>
|
||||
<Text style={[styles.description, isTablet && styles.descriptionTablet, { color: colors.textSecondary }]}>
|
||||
Escanea el código de barras de tu tarjeta sanitaria para encontrar tus medicamentos
|
||||
</Text>
|
||||
<TouchableOpacity
|
||||
style={[styles.primaryButton, shadows.scanButton, isTablet && styles.primaryButtonTablet]}
|
||||
activeOpacity={0.85}
|
||||
onPress={() => router.push('/scanner')}
|
||||
>
|
||||
<Ionicons name="scan" size={isTablet ? 28 : 24} color="#ffffff" />
|
||||
<Text style={[styles.primaryButtonText, isTablet && styles.primaryButtonTextTablet]}>
|
||||
Iniciar escaneo
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
|
||||
{/* Separator */}
|
||||
<View style={styles.separator}>
|
||||
<View style={[styles.separatorLine, { backgroundColor: colors.border }]} />
|
||||
<Text style={[styles.separatorText, { color: colors.textSecondary }]}>o</Text>
|
||||
<View style={[styles.separatorLine, { backgroundColor: colors.border }]} />
|
||||
</View>
|
||||
|
||||
{/* Option 2: Upload device photo */}
|
||||
<View style={[styles.optionCard, isTablet && styles.optionCardTablet, { backgroundColor: colors.card, borderColor: colors.border }]}>
|
||||
<Ionicons name="camera" size={24} color={colors.primary} />
|
||||
<View style={styles.optionTextContainer}>
|
||||
<Text style={[styles.optionTitle, isTablet && styles.optionTitleTablet, { color: colors.text }]}>
|
||||
Subir foto del dispositivo
|
||||
</Text>
|
||||
<Text style={[styles.optionDescription, isTablet && styles.optionDescriptionTablet, { color: colors.textSecondary }]}>
|
||||
Toma o selecciona una foto del dispositivo sanitario
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.photoButtonsRow}>
|
||||
<TouchableOpacity
|
||||
style={[styles.photoButton, isTablet && styles.photoButtonTablet, { backgroundColor: colors.primaryContainer, borderColor: colors.primary }]}
|
||||
activeOpacity={0.7}
|
||||
onPress={handleTakePhoto}
|
||||
>
|
||||
<Ionicons name="camera-outline" size={20} color={colors.primary} />
|
||||
<Text style={[styles.photoButtonText, { color: colors.primary }]}>Tomar foto</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity
|
||||
style={[styles.photoButton, isTablet && styles.photoButtonTablet, { backgroundColor: colors.primaryContainer, borderColor: colors.primary }]}
|
||||
activeOpacity={0.7}
|
||||
onPress={handleSelectFromGallery}
|
||||
>
|
||||
<Ionicons name="images-outline" size={20} color={colors.primary} />
|
||||
<Text style={[styles.photoButtonText, { color: colors.primary }]}>Galería</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
{selectedImage && (
|
||||
<View style={styles.imagePreviewContainer}>
|
||||
<Ionicons name="checkmark-circle" size={20} color={colors.success} />
|
||||
<Text style={[styles.imagePreviewText, { color: colors.success }]}>Foto seleccionada correctamente</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Option 3: Enter card number manually */}
|
||||
<View style={[styles.optionCard, isTablet && styles.optionCardTablet, { backgroundColor: colors.card, borderColor: colors.border }]}>
|
||||
<Ionicons name="keypad" size={24} color={colors.primary} />
|
||||
<View style={styles.optionTextContainer}>
|
||||
<Text style={[styles.optionTitle, isTablet && styles.optionTitleTablet, { color: colors.text }]}>
|
||||
Introducir número manualmente
|
||||
</Text>
|
||||
<Text style={[styles.optionDescription, isTablet && styles.optionDescriptionTablet, { color: colors.textSecondary }]}>
|
||||
Escribe el número de tu tarjeta sanitaria
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.manualInputRow}>
|
||||
<TextInput
|
||||
style={[styles.manualInput, isTablet && styles.manualInputTablet, { backgroundColor: colors.card, borderColor: colors.border, color: colors.text }]}
|
||||
placeholder="Introduce el número de tarjeta"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
value={manualNumber}
|
||||
onChangeText={setManualNumber}
|
||||
keyboardType="default"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
returnKeyType="search"
|
||||
onSubmitEditing={handleManualSubmit}
|
||||
/>
|
||||
<TouchableOpacity
|
||||
style={[styles.manualSubmitButton, isTablet && styles.manualSubmitButtonTablet]}
|
||||
activeOpacity={0.7}
|
||||
onPress={handleManualSubmit}
|
||||
>
|
||||
<Ionicons name="arrow-forward" size={20} color="#ffffff" />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
scrollContainer: {
|
||||
flex: 1,
|
||||
},
|
||||
scrollContent: {
|
||||
flexGrow: 1,
|
||||
paddingVertical: spacing.xl,
|
||||
},
|
||||
content: {
|
||||
alignItems: 'center',
|
||||
paddingHorizontal: spacing.xl,
|
||||
gap: spacing.md,
|
||||
},
|
||||
contentTablet: {
|
||||
gap: spacing.lg,
|
||||
},
|
||||
iconContainer: {
|
||||
width: 100,
|
||||
height: 100,
|
||||
borderRadius: 50,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
iconContainerTablet: {
|
||||
width: 140,
|
||||
height: 140,
|
||||
borderRadius: 70,
|
||||
},
|
||||
title: {
|
||||
fontSize: 22,
|
||||
fontWeight: 'bold',
|
||||
},
|
||||
titleTablet: {
|
||||
fontSize: 28,
|
||||
},
|
||||
description: {
|
||||
fontSize: 15,
|
||||
textAlign: 'center',
|
||||
lineHeight: 22,
|
||||
maxWidth: 280,
|
||||
},
|
||||
descriptionTablet: {
|
||||
fontSize: 17,
|
||||
maxWidth: 420,
|
||||
lineHeight: 26,
|
||||
},
|
||||
primaryButton: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
backgroundColor: '#2b5bb5',
|
||||
borderRadius: borderRadius.lg,
|
||||
paddingVertical: spacing.md,
|
||||
paddingHorizontal: spacing.xl,
|
||||
marginTop: spacing.sm,
|
||||
},
|
||||
primaryButtonTablet: {
|
||||
paddingVertical: spacing.lg,
|
||||
paddingHorizontal: spacing.xl * 1.5,
|
||||
},
|
||||
primaryButtonText: {
|
||||
fontSize: 17,
|
||||
fontWeight: '600',
|
||||
color: '#ffffff',
|
||||
},
|
||||
primaryButtonTextTablet: {
|
||||
fontSize: 20,
|
||||
},
|
||||
separator: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
width: '100%',
|
||||
marginVertical: spacing.sm,
|
||||
},
|
||||
separatorLine: {
|
||||
flex: 1,
|
||||
height: 1,
|
||||
},
|
||||
separatorText: {
|
||||
marginHorizontal: spacing.md,
|
||||
fontSize: 14,
|
||||
},
|
||||
optionCard: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
width: '100%',
|
||||
borderRadius: borderRadius.lg,
|
||||
padding: spacing.md,
|
||||
gap: spacing.md,
|
||||
borderWidth: 1,
|
||||
},
|
||||
optionCardTablet: {
|
||||
padding: spacing.lg,
|
||||
},
|
||||
optionTextContainer: {
|
||||
flex: 1,
|
||||
},
|
||||
optionTitle: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
},
|
||||
optionTitleTablet: {
|
||||
fontSize: 18,
|
||||
},
|
||||
optionDescription: {
|
||||
fontSize: 13,
|
||||
marginTop: 2,
|
||||
},
|
||||
optionDescriptionTablet: {
|
||||
fontSize: 15,
|
||||
},
|
||||
photoButtonsRow: {
|
||||
flexDirection: 'row',
|
||||
width: '100%',
|
||||
gap: spacing.sm,
|
||||
},
|
||||
photoButton: {
|
||||
flex: 1,
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: spacing.xs,
|
||||
borderRadius: borderRadius.md,
|
||||
paddingVertical: spacing.sm + 4,
|
||||
borderWidth: 1,
|
||||
},
|
||||
photoButtonTablet: {
|
||||
paddingVertical: spacing.md,
|
||||
},
|
||||
photoButtonText: {
|
||||
fontSize: 14,
|
||||
fontWeight: '500',
|
||||
},
|
||||
imagePreviewContainer: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.xs,
|
||||
paddingVertical: spacing.xs,
|
||||
},
|
||||
imagePreviewText: {
|
||||
fontSize: 13,
|
||||
fontWeight: '500',
|
||||
},
|
||||
manualInputRow: {
|
||||
flexDirection: 'row',
|
||||
width: '100%',
|
||||
gap: spacing.sm,
|
||||
},
|
||||
manualInput: {
|
||||
flex: 1,
|
||||
borderRadius: borderRadius.md,
|
||||
borderWidth: 1,
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: spacing.sm + 4,
|
||||
fontSize: 15,
|
||||
},
|
||||
manualInputTablet: {
|
||||
fontSize: 18,
|
||||
paddingVertical: spacing.md,
|
||||
},
|
||||
manualSubmitButton: {
|
||||
backgroundColor: '#7fbf8f',
|
||||
borderRadius: borderRadius.md,
|
||||
width: 48,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
manualSubmitButtonTablet: {
|
||||
width: 56,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,368 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { View, FlatList, StyleSheet, Text, TouchableOpacity, useWindowDimensions } from 'react-native';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { useNavigation, 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 { useAuth } from '../../hooks/useAuth';
|
||||
import { useRecentSearches } from '../../hooks/useRecentSearches';
|
||||
import { searchMedicines } from '../../services/medicines';
|
||||
import { searchProducts, Product } from '../../services/products';
|
||||
import { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { spacing, borderRadius } from '../../constants/theme';
|
||||
import { Medicine } from '../../types';
|
||||
import { config } from '../../constants/config';
|
||||
|
||||
const TABLET_MIN_WIDTH = 768;
|
||||
|
||||
const suggestions = [
|
||||
{ name: 'Paracetamol', icon: 'medical' as const },
|
||||
{ name: 'Ibuprofeno', icon: 'fitness' as const },
|
||||
{ name: 'Aspirina', icon: 'heart' as const },
|
||||
{ name: 'Omeprazol', icon: 'bandage' as const },
|
||||
];
|
||||
|
||||
export default function SearchScreen() {
|
||||
const { width } = useWindowDimensions();
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
const { isAuthenticated } = useAuth();
|
||||
const { recentSearches, addSearch, removeSearch } = useRecentSearches();
|
||||
const { colors } = useThemeContext();
|
||||
const [query, setQuery] = useState('');
|
||||
const [results, setResults] = useState<Medicine[]>([]);
|
||||
const [products, setProducts] = useState<Product[]>([]);
|
||||
const [searchMode, setSearchMode] = useState<'all' | 'medicines' | 'products'>('all');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const debouncedQuery = useDebounce(query, config.SEARCH_DEBOUNCE_MS);
|
||||
const navigation = useNavigation();
|
||||
const router = useRouter();
|
||||
|
||||
useEffect(() => {
|
||||
const parent = navigation.getParent();
|
||||
if (!parent) return;
|
||||
const unsubscribe = parent.addListener('tabPress', () => {
|
||||
setQuery('');
|
||||
setResults([]);
|
||||
setProducts([]);
|
||||
setSearchMode('all');
|
||||
setIsLoading(false);
|
||||
setError(null);
|
||||
});
|
||||
return unsubscribe;
|
||||
}, [navigation]);
|
||||
|
||||
useEffect(() => {
|
||||
if (debouncedQuery.length < 2) {
|
||||
setResults([]);
|
||||
setProducts([]);
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchProducts = async () => {
|
||||
try {
|
||||
const productResults = await searchProducts(debouncedQuery);
|
||||
setProducts(productResults);
|
||||
} catch (err) {
|
||||
console.error('Product search error:', err);
|
||||
}
|
||||
};
|
||||
|
||||
fetchResults();
|
||||
fetchProducts();
|
||||
}, [debouncedQuery]);
|
||||
|
||||
const handleSearch = (searchQuery: string) => {
|
||||
setQuery(searchQuery);
|
||||
if (searchQuery.trim()) addSearch(searchQuery);
|
||||
};
|
||||
|
||||
const showSuggestions = !query && !isLoading && results.length === 0 && products.length === 0;
|
||||
|
||||
return (
|
||||
<View style={[styles.container, { backgroundColor: colors.background }]}>
|
||||
<SearchBar
|
||||
onSearch={handleSearch}
|
||||
value={query}
|
||||
onChangeText={setQuery}
|
||||
/>
|
||||
|
||||
{query.length >= 2 && (
|
||||
<View style={styles.filterContainer}>
|
||||
<TouchableOpacity style={[styles.filterTab, searchMode === 'all' && styles.filterTabActive]} onPress={() => setSearchMode('all')}>
|
||||
<Text style={[styles.filterText, searchMode === 'all' && styles.filterTextActive]}>Todos</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity style={[styles.filterTab, searchMode === 'medicines' && styles.filterTabActive]} onPress={() => setSearchMode('medicines')}>
|
||||
<Text style={[styles.filterText, searchMode === 'medicines' && styles.filterTextActive]}>Medicamentos</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity style={[styles.filterTab, searchMode === 'products' && styles.filterTabActive]} onPress={() => setSearchMode('products')}>
|
||||
<Text style={[styles.filterText, searchMode === 'products' && styles.filterTextActive]}>Parafarmacia</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{showSuggestions && (
|
||||
<>
|
||||
<View style={[styles.suggestionsSection, isTablet && styles.suggestionsSectionTablet]}>
|
||||
<Text style={[styles.sectionTitle, { color: colors.text }]}>Sugerencias</Text>
|
||||
<View style={styles.suggestionsGrid}>
|
||||
{suggestions.map((s) => (
|
||||
<TouchableOpacity
|
||||
key={s.name}
|
||||
style={[styles.suggestionCard, { backgroundColor: colors.card, borderColor: colors.border }]}
|
||||
onPress={() => handleSearch(s.name)}
|
||||
activeOpacity={0.7}
|
||||
>
|
||||
<View style={[styles.suggestionIcon, { backgroundColor: colors.surfaceLow }]}>
|
||||
<Ionicons name={s.icon} size={22} color={colors.primary} />
|
||||
</View>
|
||||
<Text style={[styles.suggestionName, { color: colors.text }]}>{s.name}</Text>
|
||||
</TouchableOpacity>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{isAuthenticated && recentSearches.length > 0 && (
|
||||
<View style={[styles.recentSection, isTablet && styles.recentSectionTablet]}>
|
||||
<Text style={[styles.sectionTitle, { color: colors.text }]}>Búsquedas recientes</Text>
|
||||
{recentSearches.map((term) => (
|
||||
<TouchableOpacity
|
||||
key={term}
|
||||
style={styles.recentItem}
|
||||
onPress={() => handleSearch(term)}
|
||||
activeOpacity={0.7}
|
||||
>
|
||||
<Ionicons name="time-outline" size={18} color={colors.textSecondary} />
|
||||
<Text style={[styles.recentText, { color: colors.text }]}>{term}</Text>
|
||||
<TouchableOpacity onPress={() => removeSearch(term)} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
|
||||
<Ionicons name="close" size={16} color={colors.textSecondary} />
|
||||
</TouchableOpacity>
|
||||
</TouchableOpacity>
|
||||
))}
|
||||
</View>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{isLoading && <LoadingSpinner message="Buscando..." />}
|
||||
|
||||
{error && (
|
||||
<View style={[styles.errorContainer, isTablet && styles.errorContainerTablet, { backgroundColor: colors.dangerContainer }]}>
|
||||
<Text style={[styles.errorText, { color: colors.danger }]}>{error}</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{!isLoading && !error && results.length === 0 && products.length === 0 && query.length >= 2 && (
|
||||
<View style={styles.emptyContainer}>
|
||||
<Text style={[styles.emptyText, { color: colors.textSecondary }]}>No se encontraron resultados</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
<FlatList
|
||||
data={(searchMode === 'medicines' || searchMode === 'all') ? results : []}
|
||||
keyExtractor={(item) => item.nregistro}
|
||||
renderItem={({ item }) => <MedicineCard medicine={item} />}
|
||||
ListHeaderComponent={
|
||||
<>
|
||||
{(searchMode === 'all' || searchMode === 'products') && products.length > 0 && (
|
||||
<View style={styles.section}>
|
||||
<Text style={[styles.sectionTitle, { color: colors.text }]}>Parafarmacia y Bebé</Text>
|
||||
{products.map((product) => (
|
||||
<TouchableOpacity
|
||||
key={`${product.source}-${product.id}`}
|
||||
style={[styles.productCard, { backgroundColor: colors.card, borderColor: colors.border }]}
|
||||
onPress={() => router.push(`/product/${product.source}/${product.id}`)}
|
||||
activeOpacity={0.7}
|
||||
>
|
||||
<View style={styles.productInfo}>
|
||||
<View style={styles.badges}>
|
||||
<View style={[styles.sourceBadge, { backgroundColor: product.source === 'cima' ? '#2563eb' : '#16a34a' }]}>
|
||||
<Text style={styles.badgeText}>{product.source === 'cima' ? 'CIMA' : 'OFF'}</Text>
|
||||
</View>
|
||||
</View>
|
||||
<Text style={[styles.productName, { color: colors.text }]} numberOfLines={1}>{product.name}</Text>
|
||||
<Text style={[styles.productBrand, { color: colors.textSecondary }]} numberOfLines={1}>{product.brand}</Text>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
))}
|
||||
</View>
|
||||
)}
|
||||
</>
|
||||
}
|
||||
contentContainerStyle={[styles.list, isTablet && styles.listTablet]}
|
||||
showsVerticalScrollIndicator={false}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
},
|
||||
filterContainer: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'center',
|
||||
gap: spacing.sm,
|
||||
paddingVertical: spacing.sm,
|
||||
paddingHorizontal: spacing.md,
|
||||
},
|
||||
filterTab: {
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: spacing.sm,
|
||||
borderRadius: borderRadius.full,
|
||||
backgroundColor: 'rgba(0,0,0,0.05)',
|
||||
},
|
||||
filterTabActive: {
|
||||
backgroundColor: '#7fbf8f',
|
||||
},
|
||||
filterText: {
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
color: '#41493e',
|
||||
},
|
||||
filterTextActive: {
|
||||
color: '#ffffff',
|
||||
},
|
||||
section: {
|
||||
paddingHorizontal: spacing.lg,
|
||||
marginTop: spacing.md,
|
||||
},
|
||||
suggestionsSection: {
|
||||
marginTop: spacing.sm,
|
||||
alignSelf: 'center',
|
||||
width: '80%',
|
||||
},
|
||||
suggestionsSectionTablet: {
|
||||
maxWidth: 700,
|
||||
alignSelf: 'center',
|
||||
width: '100%',
|
||||
},
|
||||
sectionTitle: {
|
||||
fontSize: 20,
|
||||
fontWeight: '700',
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
suggestionsGrid: {
|
||||
flexDirection: 'row',
|
||||
flexWrap: 'wrap',
|
||||
gap: spacing.sm,
|
||||
},
|
||||
suggestionCard: {
|
||||
width: '48%' as unknown as number,
|
||||
borderRadius: borderRadius.lg,
|
||||
borderWidth: 1,
|
||||
padding: spacing.md,
|
||||
gap: spacing.sm,
|
||||
},
|
||||
suggestionIcon: {
|
||||
width: 40,
|
||||
height: 40,
|
||||
borderRadius: borderRadius.md,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
suggestionName: {
|
||||
fontSize: 16,
|
||||
fontWeight: '700',
|
||||
},
|
||||
recentSection: {
|
||||
marginTop: spacing.lg,
|
||||
alignSelf: 'center',
|
||||
width: '80%',
|
||||
},
|
||||
recentSectionTablet: {
|
||||
maxWidth: 700,
|
||||
alignSelf: 'center',
|
||||
width: '100%',
|
||||
},
|
||||
recentItem: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
paddingVertical: spacing.sm,
|
||||
gap: spacing.sm,
|
||||
},
|
||||
recentText: {
|
||||
flex: 1,
|
||||
fontSize: 15,
|
||||
},
|
||||
list: {
|
||||
paddingBottom: spacing.xl,
|
||||
},
|
||||
listTablet: {
|
||||
maxWidth: 700,
|
||||
alignSelf: 'center',
|
||||
width: '100%',
|
||||
},
|
||||
errorContainer: {
|
||||
padding: spacing.md,
|
||||
marginHorizontal: spacing.lg,
|
||||
borderRadius: borderRadius.lg,
|
||||
},
|
||||
errorContainerTablet: {
|
||||
maxWidth: 700,
|
||||
alignSelf: 'center',
|
||||
},
|
||||
errorText: {
|
||||
textAlign: 'center',
|
||||
fontSize: 14,
|
||||
},
|
||||
emptyContainer: {
|
||||
padding: spacing.xl,
|
||||
alignItems: 'center',
|
||||
},
|
||||
emptyText: {
|
||||
fontSize: 16,
|
||||
},
|
||||
productCard: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
borderRadius: borderRadius.lg,
|
||||
borderWidth: 1,
|
||||
padding: spacing.md,
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
productInfo: {
|
||||
flex: 1,
|
||||
gap: 4,
|
||||
},
|
||||
badges: {
|
||||
flexDirection: 'row',
|
||||
gap: spacing.sm,
|
||||
marginBottom: 2,
|
||||
},
|
||||
sourceBadge: {
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: 2,
|
||||
borderRadius: borderRadius.sm,
|
||||
},
|
||||
badgeText: {
|
||||
color: '#ffffff',
|
||||
fontSize: 11,
|
||||
fontWeight: '700',
|
||||
},
|
||||
productName: {
|
||||
fontSize: 15,
|
||||
fontWeight: '600',
|
||||
},
|
||||
productBrand: {
|
||||
fontSize: 13,
|
||||
},
|
||||
});
|
||||
@@ -1,15 +1,22 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import { Stack } from 'expo-router';
|
||||
import { StatusBar } from 'expo-status-bar';
|
||||
import { Image, StyleSheet, View } from 'react-native';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { GestureHandlerRootView } from 'react-native-gesture-handler';
|
||||
import { SafeAreaProvider } from 'react-native-safe-area-context';
|
||||
import { useAuthStore } from '../store/authStore';
|
||||
import { registerForPushNotifications, addNotificationListener, addNotificationResponseListener } from '../services/notifications';
|
||||
import { ThemeProvider, useThemeContext } from '../components/ThemeProvider';
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
export default function RootLayout() {
|
||||
const bgLight = require('../assets/bg.png');
|
||||
const bgDark = require('../assets/bg_dark.png');
|
||||
|
||||
function RootLayoutInner() {
|
||||
const { checkAuth } = useAuthStore();
|
||||
const { colors, isDark } = useThemeContext();
|
||||
const notificationListener = useRef<ReturnType<typeof addNotificationListener>>();
|
||||
const responseListener = useRef<ReturnType<typeof addNotificationResponseListener>>();
|
||||
|
||||
@@ -33,22 +40,28 @@ export default function RootLayout() {
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<Stack>
|
||||
<>
|
||||
<Stack
|
||||
screenOptions={{
|
||||
headerStyle: { backgroundColor: colors.card },
|
||||
headerTintColor: colors.primary,
|
||||
headerTitleStyle: { color: colors.text, fontWeight: '600' },
|
||||
}}
|
||||
>
|
||||
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
|
||||
<Stack.Screen
|
||||
name="medicine/[id]"
|
||||
options={{
|
||||
title: 'Medicamento',
|
||||
headerTintColor: '#007AFF',
|
||||
}}
|
||||
options={{ title: 'Medicamento' }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="pharmacy/[id]"
|
||||
options={{ title: 'Farmacia' }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="scanner"
|
||||
options={{
|
||||
title: 'Farmacia',
|
||||
headerTintColor: '#007AFF',
|
||||
title: 'Escanear',
|
||||
headerShown: false,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
@@ -66,8 +79,61 @@ export default function RootLayout() {
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
<StatusBar style="auto" />
|
||||
<StatusBar style={isDark ? 'light' : 'auto'} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function ThemedBackground({ children }: { children: React.ReactNode }) {
|
||||
const { isDark } = useThemeContext();
|
||||
|
||||
return (
|
||||
<View style={styles.root}>
|
||||
<Image
|
||||
source={isDark ? bgDark : bgLight}
|
||||
style={styles.bgImage}
|
||||
resizeMode="cover"
|
||||
/>
|
||||
<View style={[styles.overlay, isDark && styles.overlayDark]} pointerEvents="none" />
|
||||
<View style={styles.content}>
|
||||
{children}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export default function RootLayout() {
|
||||
return (
|
||||
<GestureHandlerRootView style={styles.root}>
|
||||
<SafeAreaProvider>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<ThemeProvider>
|
||||
<ThemedBackground>
|
||||
<RootLayoutInner />
|
||||
</ThemedBackground>
|
||||
</ThemeProvider>
|
||||
</QueryClientProvider>
|
||||
</SafeAreaProvider>
|
||||
</GestureHandlerRootView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
root: {
|
||||
flex: 1,
|
||||
},
|
||||
bgImage: {
|
||||
...StyleSheet.absoluteFillObject,
|
||||
opacity: 0.55,
|
||||
},
|
||||
overlay: {
|
||||
...StyleSheet.absoluteFillObject,
|
||||
backgroundColor: 'rgba(255, 252, 245, 0.48)',
|
||||
},
|
||||
overlayDark: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.25)',
|
||||
},
|
||||
content: {
|
||||
flex: 1,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -7,32 +7,48 @@ import {
|
||||
StyleSheet,
|
||||
KeyboardAvoidingView,
|
||||
Platform,
|
||||
Alert
|
||||
Alert,
|
||||
Image,
|
||||
} 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 { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { register } from '../../services/auth';
|
||||
import { spacing, borderRadius, shadows } from '../../constants/theme';
|
||||
import {
|
||||
isBiometricsAvailable,
|
||||
authenticateWithBiometrics,
|
||||
saveBiometricCredentials,
|
||||
getBiometricUsername
|
||||
getBiometricUsername,
|
||||
} from '../../services/biometrics';
|
||||
|
||||
type Tab = 'login' | 'register';
|
||||
|
||||
export default function LoginScreen() {
|
||||
const router = useRouter();
|
||||
const { login } = useAuthStore();
|
||||
const { colors } = useThemeContext();
|
||||
const [tab, setTab] = useState<Tab>('login');
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [biometricsAvailable, setBiometricsAvailable] = useState(false);
|
||||
const [biometricUsername, setBiometricUsername] = useState<string | null>(null);
|
||||
|
||||
const isRegister = tab === 'register';
|
||||
|
||||
useEffect(() => {
|
||||
checkBiometrics();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setUsername('');
|
||||
setPassword('');
|
||||
setConfirmPassword('');
|
||||
}, [tab]);
|
||||
|
||||
const checkBiometrics = async () => {
|
||||
try {
|
||||
const available = await isBiometricsAvailable();
|
||||
@@ -46,22 +62,42 @@ export default function LoginScreen() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleLogin = async () => {
|
||||
if (!username || !password) {
|
||||
Alert.alert('Error', 'Por favor ingresa usuario y contraseña');
|
||||
const handleSubmit = async () => {
|
||||
if (!username.trim() || !password) {
|
||||
Alert.alert('Error', 'Por favor completa todos los campos');
|
||||
return;
|
||||
}
|
||||
|
||||
if (isRegister) {
|
||||
if (password.length < 8) {
|
||||
Alert.alert('Error', 'La contraseña debe tener al menos 8 caracteres');
|
||||
return;
|
||||
}
|
||||
if (password !== confirmPassword) {
|
||||
Alert.alert('Error', 'Las contraseñas no coinciden');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
await login(username, password);
|
||||
// Save username for biometric login
|
||||
if (isRegister) {
|
||||
await register(username.trim(), password);
|
||||
Alert.alert('Éxito', 'Cuenta creada correctamente', [
|
||||
{ text: 'OK', onPress: () => setTab('login') },
|
||||
]);
|
||||
} else {
|
||||
await login(username.trim(), password);
|
||||
if (biometricsAvailable) {
|
||||
await saveBiometricCredentials(username);
|
||||
await saveBiometricCredentials(username.trim());
|
||||
}
|
||||
router.replace('/(tabs)');
|
||||
}
|
||||
} catch (error) {
|
||||
Alert.alert('Error', 'Credenciales incorrectas');
|
||||
Alert.alert(
|
||||
'Error',
|
||||
isRegister ? 'No se pudo crear la cuenta' : 'Credenciales incorrectas'
|
||||
);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -77,8 +113,6 @@ export default function LoginScreen() {
|
||||
try {
|
||||
const authenticated = await authenticateWithBiometrics();
|
||||
if (authenticated) {
|
||||
// Use saved username with empty password for biometric login
|
||||
// The backend should handle biometric authentication differently
|
||||
await login(biometricUsername, '');
|
||||
router.replace('/(tabs)');
|
||||
} else {
|
||||
@@ -93,64 +127,165 @@ export default function LoginScreen() {
|
||||
|
||||
return (
|
||||
<KeyboardAvoidingView
|
||||
style={styles.container}
|
||||
style={[styles.container, { backgroundColor: colors.background }]}
|
||||
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
|
||||
>
|
||||
<View style={styles.form}>
|
||||
<Text style={styles.title}>Iniciar Sesión</Text>
|
||||
<Text style={styles.subtitle}>Ingresa tus credenciales para continuar</Text>
|
||||
<View style={styles.content}>
|
||||
{/* Logo */}
|
||||
<View style={styles.logoSection}>
|
||||
<Image
|
||||
source={require('../../assets/farmaclic_logo.png')}
|
||||
style={styles.logo}
|
||||
resizeMode="contain"
|
||||
/>
|
||||
<Text style={[styles.brandName, { color: colors.text }]}>FarmaClic</Text>
|
||||
</View>
|
||||
|
||||
<View style={styles.inputContainer}>
|
||||
<Text style={styles.label}>Usuario</Text>
|
||||
{/* Tabs */}
|
||||
<View style={[styles.tabBar, { backgroundColor: colors.surfaceLow }]}>
|
||||
<TouchableOpacity
|
||||
style={[
|
||||
styles.tab,
|
||||
!isRegister && [styles.tabActive, { backgroundColor: colors.primary }],
|
||||
]}
|
||||
onPress={() => setTab('login')}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Text
|
||||
style={[
|
||||
styles.tabText,
|
||||
{ color: isRegister ? colors.textSecondary : colors.onPrimaryContainer },
|
||||
!isRegister && styles.tabTextActive,
|
||||
]}
|
||||
>
|
||||
Iniciar Sesión
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity
|
||||
style={[
|
||||
styles.tab,
|
||||
isRegister && [styles.tabActive, { backgroundColor: colors.primary }],
|
||||
]}
|
||||
onPress={() => setTab('register')}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Text
|
||||
style={[
|
||||
styles.tabText,
|
||||
{ color: !isRegister ? colors.textSecondary : colors.onPrimaryContainer },
|
||||
isRegister && styles.tabTextActive,
|
||||
]}
|
||||
>
|
||||
Crear Cuenta
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
{/* Card */}
|
||||
<View style={[styles.card, { backgroundColor: colors.card }, shadows.card]}>
|
||||
{/* Header */}
|
||||
<Text style={[styles.title, { color: colors.text }]}>
|
||||
{isRegister ? 'Crea tu cuenta' : 'Bienvenido de nuevo'}
|
||||
</Text>
|
||||
<Text style={[styles.subtitle, { color: colors.textSecondary }]}>
|
||||
{isRegister
|
||||
? 'Guarda tu dirección y recibe notificaciones cuando lleguen medicamentos.'
|
||||
: 'Inicia sesión para gestionar tu perfil y notificaciones.'}
|
||||
</Text>
|
||||
|
||||
{/* Username */}
|
||||
<View style={[styles.inputWrapper, { backgroundColor: colors.surfaceLow, borderColor: colors.border }]}>
|
||||
<Ionicons name="person-outline" size={20} color={colors.textSecondary} style={styles.inputIcon} />
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
style={[styles.input, { color: colors.text }]}
|
||||
value={username}
|
||||
onChangeText={setUsername}
|
||||
placeholder="Tu usuario"
|
||||
placeholder="Usuario"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
autoComplete="username"
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={styles.inputContainer}>
|
||||
<Text style={styles.label}>Contraseña</Text>
|
||||
{/* Password */}
|
||||
<View style={[styles.inputWrapper, { backgroundColor: colors.surfaceLow, borderColor: colors.border }]}>
|
||||
<Ionicons name="lock-closed-outline" size={20} color={colors.textSecondary} style={styles.inputIcon} />
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
style={[styles.input, { color: colors.text }]}
|
||||
value={password}
|
||||
onChangeText={setPassword}
|
||||
placeholder="Tu contraseña"
|
||||
placeholder="Contraseña"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
secureTextEntry
|
||||
autoComplete={isRegister ? 'new-password' : 'current-password'}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{/* Confirm password (register only) */}
|
||||
{isRegister && (
|
||||
<View style={[styles.inputWrapper, { backgroundColor: colors.surfaceLow, borderColor: colors.border }]}>
|
||||
<Ionicons name="lock-closed-outline" size={20} color={colors.textSecondary} style={styles.inputIcon} />
|
||||
<TextInput
|
||||
style={[styles.input, { color: colors.text }]}
|
||||
value={confirmPassword}
|
||||
onChangeText={setConfirmPassword}
|
||||
placeholder="Confirmar contraseña"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
secureTextEntry
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Hints (register only) */}
|
||||
{isRegister && (
|
||||
<View style={styles.hints}>
|
||||
<Text style={[styles.hint, { color: colors.textSecondary }]}>
|
||||
<Ionicons name="information-circle-outline" size={14} color={colors.textSecondary} /> 3-32 caracteres para el usuario
|
||||
</Text>
|
||||
<Text style={[styles.hint, { color: colors.textSecondary }]}>
|
||||
<Ionicons name="information-circle-outline" size={14} color={colors.textSecondary} /> Mínimo 8 caracteres para la contraseña
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Submit button */}
|
||||
<TouchableOpacity
|
||||
style={[styles.button, isLoading && styles.buttonDisabled]}
|
||||
onPress={handleLogin}
|
||||
style={[styles.button, { backgroundColor: colors.primary }, isLoading && styles.buttonDisabled]}
|
||||
onPress={handleSubmit}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Text style={styles.buttonText}>
|
||||
{isLoading ? 'Ingresando...' : 'Iniciar Sesión'}
|
||||
{isLoading ? (
|
||||
<Ionicons name="hourglass" size={20} color={colors.onPrimaryContainer} />
|
||||
) : (
|
||||
<Text style={[styles.buttonText, { color: colors.onPrimaryContainer }]}>
|
||||
{isRegister ? 'Crear Cuenta' : 'Iniciar Sesión'}
|
||||
</Text>
|
||||
)}
|
||||
</TouchableOpacity>
|
||||
|
||||
{biometricsAvailable && biometricUsername && (
|
||||
{/* Biometrics (login only) */}
|
||||
{!isRegister && biometricsAvailable && biometricUsername && (
|
||||
<TouchableOpacity
|
||||
style={[styles.biometricButton, isLoading && styles.buttonDisabled]}
|
||||
style={[styles.biometricButton, { borderColor: colors.primary }]}
|
||||
onPress={handleBiometricLogin}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Ionicons name="finger-print" size={24} color={colors.primary} />
|
||||
<Text style={styles.biometricText}>Iniciar con biometría</Text>
|
||||
<Ionicons name="finger-print" size={22} color={colors.primary} />
|
||||
<Text style={[styles.biometricText, { color: colors.primary }]}>Iniciar con biometría</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
|
||||
{/* Footer link */}
|
||||
<TouchableOpacity
|
||||
style={styles.linkButton}
|
||||
onPress={() => router.push('/auth/register')}
|
||||
onPress={() => setTab(isRegister ? 'login' : 'register')}
|
||||
>
|
||||
<Text style={styles.linkText}>¿No tienes cuenta? Regístrate</Text>
|
||||
<Text style={[styles.linkText, { color: colors.primary }]}>
|
||||
{isRegister ? '¿Ya tienes cuenta? Inicia sesión' : '¿No tienes cuenta? Regístrate'}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
@@ -160,78 +295,124 @@ export default function LoginScreen() {
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: colors.background,
|
||||
},
|
||||
form: {
|
||||
content: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
padding: spacing.xl,
|
||||
paddingHorizontal: spacing.lg,
|
||||
gap: spacing.lg,
|
||||
},
|
||||
title: {
|
||||
fontSize: 28,
|
||||
fontWeight: 'bold',
|
||||
color: colors.text,
|
||||
marginBottom: spacing.sm,
|
||||
logoSection: {
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
},
|
||||
subtitle: {
|
||||
fontSize: 16,
|
||||
color: colors.textSecondary,
|
||||
marginBottom: spacing.xl,
|
||||
logo: {
|
||||
width: 80,
|
||||
height: 80,
|
||||
},
|
||||
inputContainer: {
|
||||
marginBottom: spacing.md,
|
||||
brandName: {
|
||||
fontSize: 22,
|
||||
fontWeight: '700',
|
||||
letterSpacing: -0.3,
|
||||
},
|
||||
label: {
|
||||
tabBar: {
|
||||
flexDirection: 'row',
|
||||
borderRadius: borderRadius.lg,
|
||||
padding: 4,
|
||||
},
|
||||
tab: {
|
||||
flex: 1,
|
||||
paddingVertical: spacing.sm + 2,
|
||||
borderRadius: borderRadius.md,
|
||||
alignItems: 'center',
|
||||
},
|
||||
tabActive: {
|
||||
shadowColor: '#000',
|
||||
shadowOffset: { width: 0, height: 1 },
|
||||
shadowOpacity: 0.1,
|
||||
shadowRadius: 4,
|
||||
elevation: 2,
|
||||
},
|
||||
tabText: {
|
||||
fontSize: 14,
|
||||
fontWeight: '500',
|
||||
color: colors.text,
|
||||
},
|
||||
tabTextActive: {
|
||||
fontWeight: '700',
|
||||
},
|
||||
card: {
|
||||
borderRadius: borderRadius.xl,
|
||||
padding: spacing.lg,
|
||||
gap: spacing.sm,
|
||||
},
|
||||
title: {
|
||||
fontSize: 22,
|
||||
fontWeight: '700',
|
||||
marginBottom: spacing.xs,
|
||||
},
|
||||
input: {
|
||||
backgroundColor: colors.card,
|
||||
subtitle: {
|
||||
fontSize: 14,
|
||||
lineHeight: 20,
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
inputWrapper: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
borderWidth: 1,
|
||||
paddingHorizontal: spacing.md,
|
||||
},
|
||||
inputIcon: {
|
||||
marginRight: spacing.sm,
|
||||
},
|
||||
input: {
|
||||
flex: 1,
|
||||
paddingVertical: spacing.md,
|
||||
fontSize: 16,
|
||||
color: colors.text,
|
||||
},
|
||||
hints: {
|
||||
gap: 2,
|
||||
marginTop: spacing.xs,
|
||||
},
|
||||
hint: {
|
||||
fontSize: 12,
|
||||
lineHeight: 18,
|
||||
},
|
||||
button: {
|
||||
backgroundColor: colors.primary,
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
alignItems: 'center',
|
||||
marginTop: spacing.md,
|
||||
marginTop: spacing.sm,
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
buttonDisabled: {
|
||||
opacity: 0.6,
|
||||
},
|
||||
buttonText: {
|
||||
color: colors.textInverse,
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
},
|
||||
linkButton: {
|
||||
marginTop: spacing.lg,
|
||||
alignItems: 'center',
|
||||
},
|
||||
linkText: {
|
||||
color: colors.primary,
|
||||
fontSize: 14,
|
||||
fontWeight: '700',
|
||||
},
|
||||
biometricButton: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
marginTop: spacing.md,
|
||||
marginTop: spacing.xs,
|
||||
borderWidth: 1,
|
||||
borderColor: colors.primary,
|
||||
gap: spacing.sm,
|
||||
},
|
||||
biometricText: {
|
||||
color: colors.primary,
|
||||
fontSize: 16,
|
||||
fontSize: 15,
|
||||
fontWeight: '600',
|
||||
},
|
||||
linkButton: {
|
||||
alignItems: 'center',
|
||||
paddingVertical: spacing.sm,
|
||||
},
|
||||
linkText: {
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
marginLeft: spacing.sm,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,172 +1,5 @@
|
||||
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';
|
||||
import { Redirect } from 'expo-router';
|
||||
|
||||
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;
|
||||
export default function RegisterRedirect() {
|
||||
return <Redirect href="/auth/login" />;
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,18 +1,57 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { View, Text, ScrollView, StyleSheet, TouchableOpacity } from 'react-native';
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import { View, Text, ScrollView, StyleSheet, TouchableOpacity, Linking } from 'react-native';
|
||||
import { useLocalSearchParams, useRouter } from 'expo-router';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import * as Location from 'expo-location';
|
||||
import { getMedicine, getMedicinePharmacies } from '../../services/medicines';
|
||||
import { subscribeToMedicine, unsubscribeFromMedicine } from '../../services/notifications';
|
||||
import { useAuth } from '../../hooks/useAuth';
|
||||
import { StockBadge } from '../../components/StockBadge';
|
||||
import { LoadingSpinner } from '../../components/LoadingSpinner';
|
||||
import { colors, spacing, borderRadius } from '../../constants/theme';
|
||||
import { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { spacing, borderRadius } from '../../constants/theme';
|
||||
import { Medicine, PharmacyMedicine } from '../../types';
|
||||
|
||||
function haversineKm(lat1: number, lon1: number, lat2: number, lon2: number): number {
|
||||
const R = 6371;
|
||||
const dLat = ((lat2 - lat1) * Math.PI) / 180;
|
||||
const dLon = ((lon2 - lon1) * Math.PI) / 180;
|
||||
const a =
|
||||
Math.sin(dLat / 2) ** 2 +
|
||||
Math.cos((lat1 * Math.PI) / 180) *
|
||||
Math.cos((lat2 * Math.PI) / 180) *
|
||||
Math.sin(dLon / 2) ** 2;
|
||||
return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
|
||||
}
|
||||
|
||||
function formatDistance(km: number): string {
|
||||
if (km < 1) return `${Math.round(km * 1000)} m`;
|
||||
if (km < 10) return `${km.toFixed(1)} km`;
|
||||
return `${Math.round(km)} km`;
|
||||
}
|
||||
|
||||
function getPharmacyLat(p: PharmacyMedicine): number | null {
|
||||
return p.latitude ?? p.pharmacy?.latitude ?? null;
|
||||
}
|
||||
|
||||
function getPharmacyLon(p: PharmacyMedicine): number | null {
|
||||
return p.longitude ?? p.pharmacy?.longitude ?? null;
|
||||
}
|
||||
|
||||
export default function MedicineDetailScreen() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>();
|
||||
const router = useRouter();
|
||||
const { colors } = useThemeContext();
|
||||
const { isAuthenticated } = useAuth();
|
||||
const [medicine, setMedicine] = useState<Medicine | null>(null);
|
||||
const [pharmacies, setPharmacies] = useState<PharmacyMedicine[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [sortByDistance, setSortByDistance] = useState(false);
|
||||
const [userPosition, setUserPosition] = useState<{ lat: number; lon: number } | null>(null);
|
||||
const [locating, setLocating] = useState(false);
|
||||
const [locationError, setLocationError] = useState<string | null>(null);
|
||||
const [isSubscribed, setIsSubscribed] = useState(false);
|
||||
const [togglingSub, setTogglingSub] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
@@ -35,71 +74,233 @@ export default function MedicineDetailScreen() {
|
||||
fetchMedicine();
|
||||
}, [id]);
|
||||
|
||||
const handleSortByDistance = async () => {
|
||||
if (sortByDistance) {
|
||||
setSortByDistance(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setLocating(true);
|
||||
setLocationError(null);
|
||||
|
||||
try {
|
||||
const { status } = await Location.requestForegroundPermissionsAsync();
|
||||
if (status !== 'granted') {
|
||||
setLocationError('Permiso de ubicación denegado');
|
||||
setLocating(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const pos = await Location.getCurrentPositionAsync({ accuracy: Location.Accuracy.Balanced });
|
||||
setUserPosition({ lat: pos.coords.latitude, lon: pos.coords.longitude });
|
||||
setSortByDistance(true);
|
||||
} catch {
|
||||
setLocationError('No se pudo obtener tu ubicación');
|
||||
} finally {
|
||||
setLocating(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleSubscription = async () => {
|
||||
if (!isAuthenticated || !id) return;
|
||||
setTogglingSub(true);
|
||||
try {
|
||||
if (isSubscribed) {
|
||||
await unsubscribeFromMedicine(id as string);
|
||||
setIsSubscribed(false);
|
||||
} else {
|
||||
await subscribeToMedicine(id as string, medicine?.name || null);
|
||||
setIsSubscribed(true);
|
||||
}
|
||||
} catch {
|
||||
// silently fail
|
||||
} finally {
|
||||
setTogglingSub(false);
|
||||
}
|
||||
};
|
||||
|
||||
const sortedPharmacies = useMemo(() => {
|
||||
if (!sortByDistance || !userPosition) return pharmacies;
|
||||
|
||||
return [...pharmacies]
|
||||
.map((p) => {
|
||||
const lat = getPharmacyLat(p);
|
||||
const lon = getPharmacyLon(p);
|
||||
const distance =
|
||||
lat != null && lon != null
|
||||
? haversineKm(userPosition.lat, userPosition.lon, lat, lon)
|
||||
: Infinity;
|
||||
return { ...p, _distance: distance };
|
||||
})
|
||||
.sort((a, b) => a._distance - b._distance);
|
||||
}, [pharmacies, sortByDistance, userPosition]);
|
||||
|
||||
const locatedPharmacies = useMemo(
|
||||
() =>
|
||||
sortedPharmacies.filter(
|
||||
(p) => getPharmacyLat(p) != null && getPharmacyLon(p) != null
|
||||
),
|
||||
[sortedPharmacies]
|
||||
);
|
||||
|
||||
const mapCenter = useMemo(() => {
|
||||
if (locatedPharmacies.length === 0) return { latitude: 40.4168, longitude: -3.7038 };
|
||||
const lat = locatedPharmacies.reduce((s, p) => s + (getPharmacyLat(p) || 0), 0) / locatedPharmacies.length;
|
||||
const lon = locatedPharmacies.reduce((s, p) => s + (getPharmacyLon(p) || 0), 0) / locatedPharmacies.length;
|
||||
return { latitude: lat, longitude: lon };
|
||||
}, [locatedPharmacies]);
|
||||
|
||||
const handleDirections = (latitude: number, longitude: number) => {
|
||||
const url = `https://www.google.com/maps/dir/?api=1&destination=${latitude},${longitude}`;
|
||||
Linking.openURL(url);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingSpinner message="Cargando medicamento..." />;
|
||||
}
|
||||
|
||||
if (!medicine) {
|
||||
return (
|
||||
<View style={styles.errorContainer}>
|
||||
<Text style={styles.errorText}>Medicamento no encontrado</Text>
|
||||
<View style={[styles.errorContainer, { backgroundColor: colors.background }]}>
|
||||
<Text style={[styles.errorText, { color: colors.textSecondary }]}>Medicamento no encontrado</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollView style={styles.container}>
|
||||
<View style={styles.header}>
|
||||
<Text style={styles.name}>{medicine.nombre}</Text>
|
||||
<StockBadge stock={medicine.stock} />
|
||||
<ScrollView style={[styles.container, { backgroundColor: colors.background }]}>
|
||||
<View style={[styles.header, { backgroundColor: colors.card }]}>
|
||||
<Text style={[styles.name, { color: colors.text }]}>{medicine.name}</Text>
|
||||
<View style={styles.headerRight}>
|
||||
{medicine.stock != null && <StockBadge stock={medicine.stock} />}
|
||||
{isAuthenticated && (
|
||||
<TouchableOpacity
|
||||
style={[styles.bellButton, { backgroundColor: isSubscribed ? colors.primary : colors.surfaceVariant }]}
|
||||
onPress={handleToggleSubscription}
|
||||
disabled={togglingSub}
|
||||
>
|
||||
<Ionicons
|
||||
name={isSubscribed ? 'notifications' : 'notifications-outline'}
|
||||
size={20}
|
||||
color={isSubscribed ? '#fff' : colors.textSecondary}
|
||||
/>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
</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} />
|
||||
<View style={[styles.infoSection, { backgroundColor: colors.card }]}>
|
||||
<InfoRow label="Principio activo" value={medicine.active_ingredient} colors={colors} />
|
||||
<InfoRow label="Laboratorio" value={medicine.laboratory} colors={colors} />
|
||||
<InfoRow label="Forma farmacéutica" value={medicine.form} colors={colors} />
|
||||
<InfoRow label="Dosificación" value={medicine.dosage} colors={colors} />
|
||||
<InfoRow
|
||||
label="Precio"
|
||||
value={medicine.precio ? `${medicine.precio.toFixed(2)} €` : 'No disponible'}
|
||||
value={medicine.precio != null ? `${medicine.precio.toFixed(2)} €` : 'No disponible'}
|
||||
colors={colors}
|
||||
/>
|
||||
<InfoRow label="Registro" value={medicine.nregistro} />
|
||||
<InfoRow label="Registro" value={medicine.nregistro} colors={colors} />
|
||||
</View>
|
||||
|
||||
{locatedPharmacies.length > 0 && (
|
||||
<View style={[styles.mapContainer, { backgroundColor: colors.surfaceVariant }]}>
|
||||
<Ionicons name="map-outline" size={48} color={colors.textSecondary} />
|
||||
<Text style={[styles.mapPlaceholder, { color: colors.textSecondary }]}>
|
||||
Mapa próximamente…
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
<View style={styles.pharmaciesSection}>
|
||||
<Text style={styles.sectionTitle}>
|
||||
Farmacias ({pharmacies.length})
|
||||
<View style={styles.pharmaciesHeader}>
|
||||
<Text style={[styles.sectionTitle, { color: colors.text }]}>
|
||||
Farmacias ({sortedPharmacies.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}`)}
|
||||
style={[styles.sortButton, sortByDistance && styles.sortButtonActive, { backgroundColor: sortByDistance ? colors.primary : colors.primaryContainer, borderColor: colors.primary }]}
|
||||
onPress={handleSortByDistance}
|
||||
disabled={locating}
|
||||
>
|
||||
<Ionicons name="location" size={16} color={sortByDistance ? '#fff' : colors.primary} />
|
||||
<Text style={[styles.sortButtonText, sortByDistance && styles.sortButtonTextActive, { color: sortByDistance ? '#fff' : colors.primary }]}>
|
||||
{locating
|
||||
? 'Localizando…'
|
||||
: sortByDistance
|
||||
? 'Distancia · Reset'
|
||||
: 'Ordenar por distancia'}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
{locationError && (
|
||||
<View style={[styles.locationErrorContainer, { backgroundColor: colors.dangerContainer }]}>
|
||||
<Text style={[styles.locationErrorText, { color: colors.danger }]}>{locationError}</Text>
|
||||
<TouchableOpacity onPress={handleSortByDistance}>
|
||||
<Text style={[styles.retryText, { color: colors.primary }]}>Reintentar</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{sortedPharmacies.length === 0 ? (
|
||||
<Text style={[styles.noPharmacies, { color: colors.textSecondary }]}>No hay farmacias disponibles</Text>
|
||||
) : (
|
||||
sortedPharmacies.map((pharm) => {
|
||||
const lat = getPharmacyLat(pharm);
|
||||
const lon = getPharmacyLon(pharm);
|
||||
const distanceKm =
|
||||
sortByDistance && userPosition && lat != null && lon != null
|
||||
? haversineKm(userPosition.lat, userPosition.lon, lat, lon)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<View key={pharm.id} style={[styles.pharmacyCard, { backgroundColor: colors.card }]}>
|
||||
<TouchableOpacity
|
||||
style={styles.pharmacyCardContent}
|
||||
onPress={() => router.push(`/pharmacy/${pharm.pharmacy_id || pharm.id}`)}
|
||||
>
|
||||
<View style={styles.pharmacyInfo}>
|
||||
<Text style={styles.pharmacyName}>{pharm.pharmacy?.name}</Text>
|
||||
<Text style={styles.pharmacyAddress}>{pharm.pharmacy?.address}</Text>
|
||||
<View style={styles.pharmacyNameRow}>
|
||||
<Text style={[styles.pharmacyName, { color: colors.text }]}>{pharm.pharmacy?.name || pharm.name}</Text>
|
||||
{distanceKm != null && (
|
||||
<Text style={[styles.pharmacyDistance, { color: colors.primary, backgroundColor: colors.primaryContainer }]}>{formatDistance(distanceKm)}</Text>
|
||||
)}
|
||||
</View>
|
||||
<Text style={[styles.pharmacyAddress, { color: colors.textSecondary }]}>{pharm.pharmacy?.address || pharm.address}</Text>
|
||||
</View>
|
||||
<View style={styles.pharmacyStock}>
|
||||
<Text style={styles.price}>{pharm.price.toFixed(2)} €</Text>
|
||||
<Text style={styles.stock}>Stock: {pharm.stock}</Text>
|
||||
{pharm.price != null ? (
|
||||
<Text style={[styles.price, { color: colors.primary }]}>{pharm.price.toFixed(2)} €</Text>
|
||||
) : (
|
||||
<Text style={[styles.price, { color: colors.primary }]}>Consultar precio</Text>
|
||||
)}
|
||||
{pharm.stock > 0 && (
|
||||
<Text style={[styles.stock, { color: colors.textSecondary }]}>Stock: {pharm.stock}</Text>
|
||||
)}
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
))
|
||||
{lat != null && lon != null && (
|
||||
<TouchableOpacity
|
||||
style={[styles.directionsButton, { borderTopColor: colors.border }]}
|
||||
onPress={() => handleDirections(lat, lon)}
|
||||
>
|
||||
<Ionicons name="navigate" size={16} color={colors.primary} />
|
||||
<Text style={[styles.directionsText, { color: colors.primary }]}>Cómo llegar</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
function InfoRow({ label, value }: { label: string; value: string }) {
|
||||
function InfoRow({ label, value, colors }: { label: string; value: string; colors: any }) {
|
||||
return (
|
||||
<View style={styles.infoRow}>
|
||||
<Text style={styles.infoLabel}>{label}</Text>
|
||||
<Text style={styles.infoValue}>{value}</Text>
|
||||
<View style={[styles.infoRow, { borderBottomColor: colors.border }]}>
|
||||
<Text style={[styles.infoLabel, { color: colors.textSecondary }]}>{label}</Text>
|
||||
<Text style={[styles.infoValue, { color: colors.text }]}>{value}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -107,77 +308,154 @@ function InfoRow({ label, value }: { label: string; value: string }) {
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: colors.background,
|
||||
},
|
||||
header: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'flex-start',
|
||||
padding: spacing.md,
|
||||
backgroundColor: colors.card,
|
||||
padding: spacing.lg,
|
||||
},
|
||||
headerRight: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
},
|
||||
name: {
|
||||
flex: 1,
|
||||
fontSize: 22,
|
||||
fontWeight: 'bold',
|
||||
color: colors.text,
|
||||
marginRight: spacing.sm,
|
||||
},
|
||||
bellButton: {
|
||||
width: 36,
|
||||
height: 36,
|
||||
borderRadius: 18,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
infoSection: {
|
||||
backgroundColor: colors.card,
|
||||
marginTop: spacing.sm,
|
||||
padding: spacing.md,
|
||||
padding: spacing.lg,
|
||||
},
|
||||
infoRow: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
paddingVertical: spacing.sm,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: colors.separator,
|
||||
},
|
||||
infoLabel: {
|
||||
fontSize: 14,
|
||||
color: colors.textSecondary,
|
||||
fontSize: 13,
|
||||
flexShrink: 0,
|
||||
marginRight: spacing.sm,
|
||||
},
|
||||
infoValue: {
|
||||
fontSize: 13,
|
||||
fontWeight: '500',
|
||||
flex: 1,
|
||||
textAlign: 'right',
|
||||
},
|
||||
mapContainer: {
|
||||
marginTop: spacing.sm,
|
||||
marginHorizontal: spacing.lg,
|
||||
height: 200,
|
||||
borderRadius: borderRadius.lg,
|
||||
overflow: 'hidden',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: spacing.sm,
|
||||
},
|
||||
mapPlaceholder: {
|
||||
fontSize: 14,
|
||||
color: colors.text,
|
||||
fontWeight: '500',
|
||||
},
|
||||
pharmaciesSection: {
|
||||
marginTop: spacing.sm,
|
||||
padding: spacing.md,
|
||||
padding: spacing.lg,
|
||||
},
|
||||
pharmaciesHeader: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
sectionTitle: {
|
||||
fontSize: 18,
|
||||
fontWeight: '600',
|
||||
color: colors.text,
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
sortButton: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.xs,
|
||||
paddingHorizontal: spacing.sm + 4,
|
||||
paddingVertical: spacing.xs + 2,
|
||||
borderRadius: borderRadius.full,
|
||||
borderWidth: 1,
|
||||
},
|
||||
sortButtonActive: {},
|
||||
sortButtonText: {
|
||||
fontSize: 13,
|
||||
fontWeight: '600',
|
||||
},
|
||||
sortButtonTextActive: {},
|
||||
locationErrorContainer: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
padding: spacing.sm,
|
||||
marginBottom: spacing.sm,
|
||||
borderRadius: borderRadius.md,
|
||||
},
|
||||
locationErrorText: {
|
||||
flex: 1,
|
||||
fontSize: 13,
|
||||
},
|
||||
retryText: {
|
||||
fontSize: 13,
|
||||
fontWeight: '600',
|
||||
},
|
||||
noPharmacies: {
|
||||
color: colors.textSecondary,
|
||||
textAlign: 'center',
|
||||
padding: spacing.xl,
|
||||
},
|
||||
pharmacyCard: {
|
||||
borderRadius: borderRadius.lg,
|
||||
marginBottom: spacing.sm,
|
||||
overflow: 'hidden',
|
||||
shadowColor: '#000',
|
||||
shadowOffset: { width: 0, height: 2 },
|
||||
shadowOpacity: 0.06,
|
||||
shadowRadius: 8,
|
||||
elevation: 2,
|
||||
},
|
||||
pharmacyCardContent: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
pharmacyInfo: {
|
||||
flex: 1,
|
||||
},
|
||||
pharmacyNameRow: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
},
|
||||
pharmacyName: {
|
||||
flex: 1,
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: colors.text,
|
||||
marginRight: spacing.sm,
|
||||
},
|
||||
pharmacyDistance: {
|
||||
fontSize: 12,
|
||||
fontWeight: '600',
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: 2,
|
||||
borderRadius: borderRadius.full,
|
||||
overflow: 'hidden',
|
||||
},
|
||||
pharmacyAddress: {
|
||||
fontSize: 14,
|
||||
color: colors.textSecondary,
|
||||
marginTop: spacing.xs,
|
||||
},
|
||||
pharmacyStock: {
|
||||
@@ -186,13 +464,23 @@ const styles = StyleSheet.create({
|
||||
price: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: colors.primary,
|
||||
},
|
||||
stock: {
|
||||
fontSize: 12,
|
||||
color: colors.textSecondary,
|
||||
marginTop: spacing.xs,
|
||||
},
|
||||
directionsButton: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: spacing.xs,
|
||||
paddingVertical: spacing.sm,
|
||||
borderTopWidth: 1,
|
||||
},
|
||||
directionsText: {
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
},
|
||||
errorContainer: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
@@ -200,6 +488,5 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
errorText: {
|
||||
fontSize: 16,
|
||||
color: colors.textSecondary,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -4,16 +4,22 @@ 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 { subscribeToMedicine, unsubscribeFromMedicine } from '../../services/notifications';
|
||||
import { useAuth } from '../../hooks/useAuth';
|
||||
import { LoadingSpinner } from '../../components/LoadingSpinner';
|
||||
import { colors, spacing, borderRadius } from '../../constants/theme';
|
||||
import { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { spacing, borderRadius } from '../../constants/theme';
|
||||
import { Pharmacy, PharmacyMedicine } from '../../types';
|
||||
|
||||
export default function PharmacyDetailScreen() {
|
||||
const { id } = useLocalSearchParams<{ id: string }>();
|
||||
const router = useRouter();
|
||||
const { colors } = useThemeContext();
|
||||
const { isAuthenticated } = useAuth();
|
||||
const [pharmacy, setPharmacy] = useState<Pharmacy | null>(null);
|
||||
const [medicines, setMedicines] = useState<PharmacyMedicine[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [subscribedMeds, setSubscribedMeds] = useState<Set<string>>(new Set());
|
||||
|
||||
useEffect(() => {
|
||||
if (!id) return;
|
||||
@@ -49,46 +55,67 @@ export default function PharmacyDetailScreen() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleMedSubscription = async (nregistro: string, medicineName: string) => {
|
||||
if (!isAuthenticated) return;
|
||||
const key = nregistro;
|
||||
const isSub = subscribedMeds.has(key);
|
||||
try {
|
||||
if (isSub) {
|
||||
await unsubscribeFromMedicine(nregistro, Number(id));
|
||||
setSubscribedMeds(prev => {
|
||||
const next = new Set(prev);
|
||||
next.delete(key);
|
||||
return next;
|
||||
});
|
||||
} else {
|
||||
await subscribeToMedicine(nregistro, medicineName, Number(id));
|
||||
setSubscribedMeds(prev => new Set(prev).add(key));
|
||||
}
|
||||
} catch {
|
||||
// silently fail
|
||||
}
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingSpinner message="Cargando farmacia..." />;
|
||||
}
|
||||
|
||||
if (!pharmacy) {
|
||||
return (
|
||||
<View style={styles.errorContainer}>
|
||||
<Text style={styles.errorText}>Farmacia no encontrada</Text>
|
||||
<View style={[styles.errorContainer, { backgroundColor: colors.background }]}>
|
||||
<Text style={[styles.errorText, { color: colors.textSecondary }]}>Farmacia no encontrada</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollView style={styles.container}>
|
||||
<View style={styles.header}>
|
||||
<Text style={styles.name}>{pharmacy.name}</Text>
|
||||
<ScrollView style={[styles.container, { backgroundColor: colors.background }]}>
|
||||
<View style={[styles.header, { backgroundColor: colors.card }]}>
|
||||
<Text style={[styles.name, { color: colors.text }]}>{pharmacy.name}</Text>
|
||||
</View>
|
||||
|
||||
<View style={styles.actionsRow}>
|
||||
<View style={[styles.actionsRow, { backgroundColor: colors.card, borderBottomColor: colors.separator }]}>
|
||||
<TouchableOpacity style={styles.actionButton} onPress={handleCall}>
|
||||
<Ionicons name="call" size={20} color={colors.primary} />
|
||||
<Text style={styles.actionText}>Llamar</Text>
|
||||
<Text style={[styles.actionText, { color: colors.primary }]}>Llamar</Text>
|
||||
</TouchableOpacity>
|
||||
|
||||
<TouchableOpacity style={styles.actionButton} onPress={handleDirections}>
|
||||
<Ionicons name="navigate" size={20} color={colors.primary} />
|
||||
<Text style={styles.actionText}>Cómo llegar</Text>
|
||||
<Text style={[styles.actionText, { color: colors.primary }]}>Cómo llegar</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
<View style={styles.infoSection}>
|
||||
<View style={[styles.infoSection, { backgroundColor: colors.card }]}>
|
||||
<View style={styles.infoRow}>
|
||||
<Ionicons name="location" size={18} color={colors.textSecondary} />
|
||||
<Text style={styles.infoText}>{pharmacy.address}</Text>
|
||||
<Text style={[styles.infoText, { color: colors.text }]}>{pharmacy.address}</Text>
|
||||
</View>
|
||||
|
||||
{pharmacy.phone && (
|
||||
<View style={styles.infoRow}>
|
||||
<Ionicons name="call" size={18} color={colors.textSecondary} />
|
||||
<Text style={styles.infoText}>{pharmacy.phone}</Text>
|
||||
<Text style={[styles.infoText, { color: colors.text }]}>{pharmacy.phone}</Text>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
@@ -115,29 +142,48 @@ export default function PharmacyDetailScreen() {
|
||||
</View>
|
||||
|
||||
<View style={styles.medicinesSection}>
|
||||
<Text style={styles.sectionTitle}>
|
||||
<Text style={[styles.sectionTitle, { color: colors.text }]}>
|
||||
Medicamentos ({medicines.length})
|
||||
</Text>
|
||||
|
||||
{medicines.length === 0 ? (
|
||||
<Text style={styles.noMedicines}>No hay medicamentos disponibles</Text>
|
||||
<Text style={[styles.noMedicines, { color: colors.textSecondary }]}>No hay medicamentos disponibles</Text>
|
||||
) : (
|
||||
medicines.map((med) => (
|
||||
medicines.map((med) => {
|
||||
const isSub = subscribedMeds.has(med.medicine_nregistro);
|
||||
return (
|
||||
<View key={med.id} style={[styles.medicineCard, { backgroundColor: colors.card }]}>
|
||||
<TouchableOpacity
|
||||
key={med.id}
|
||||
style={styles.medicineCard}
|
||||
style={styles.medicineCardContent}
|
||||
onPress={() => router.push(`/medicine/${med.medicine_nregistro}`)}
|
||||
>
|
||||
<View style={styles.medicineInfo}>
|
||||
<Text style={styles.medicineName}>{med.medicine_name}</Text>
|
||||
<Text style={styles.medicineNregistro}>Reg: {med.medicine_nregistro}</Text>
|
||||
<Text style={[styles.medicineName, { color: colors.text }]}>{med.medicine_name}</Text>
|
||||
<Text style={[styles.medicineNregistro, { color: colors.textSecondary }]}>Reg: {med.medicine_nregistro}</Text>
|
||||
</View>
|
||||
<View style={styles.medicineStock}>
|
||||
<Text style={styles.price}>{med.price.toFixed(2)} €</Text>
|
||||
<Text style={styles.stock}>Stock: {med.stock}</Text>
|
||||
<Text style={[styles.price, { color: colors.primary }]}>{med.price.toFixed(2)} €</Text>
|
||||
<Text style={[styles.stock, { color: colors.textSecondary }]}>Stock: {med.stock}</Text>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
))
|
||||
{isAuthenticated && (
|
||||
<TouchableOpacity
|
||||
style={[styles.bellButton, { backgroundColor: isSub ? colors.primary : colors.surfaceVariant, borderTopColor: colors.border }]}
|
||||
onPress={() => handleToggleMedSubscription(med.medicine_nregistro, med.medicine_name)}
|
||||
>
|
||||
<Ionicons
|
||||
name={isSub ? 'notifications' : 'notifications-outline'}
|
||||
size={18}
|
||||
color={isSub ? '#fff' : colors.textSecondary}
|
||||
/>
|
||||
<Text style={[styles.bellText, { color: isSub ? '#fff' : colors.textSecondary }]}>
|
||||
{isSub ? 'Notificaciones activas' : 'Notificarme cuando haya stock'}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</View>
|
||||
</ScrollView>
|
||||
@@ -147,24 +193,19 @@ export default function PharmacyDetailScreen() {
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: colors.background,
|
||||
},
|
||||
header: {
|
||||
padding: spacing.md,
|
||||
backgroundColor: colors.card,
|
||||
},
|
||||
name: {
|
||||
fontSize: 22,
|
||||
fontWeight: 'bold',
|
||||
color: colors.text,
|
||||
},
|
||||
actionsRow: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-around',
|
||||
padding: spacing.md,
|
||||
backgroundColor: colors.card,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: colors.separator,
|
||||
},
|
||||
actionButton: {
|
||||
flexDirection: 'row',
|
||||
@@ -173,12 +214,10 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
actionText: {
|
||||
marginLeft: spacing.xs,
|
||||
color: colors.primary,
|
||||
fontWeight: '500',
|
||||
},
|
||||
infoSection: {
|
||||
padding: spacing.md,
|
||||
backgroundColor: colors.card,
|
||||
marginTop: spacing.sm,
|
||||
},
|
||||
infoRow: {
|
||||
@@ -190,7 +229,6 @@ const styles = StyleSheet.create({
|
||||
flex: 1,
|
||||
marginLeft: spacing.sm,
|
||||
fontSize: 16,
|
||||
color: colors.text,
|
||||
},
|
||||
mapContainer: {
|
||||
height: 200,
|
||||
@@ -206,21 +244,21 @@ const styles = StyleSheet.create({
|
||||
sectionTitle: {
|
||||
fontSize: 18,
|
||||
fontWeight: '600',
|
||||
color: colors.text,
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
noMedicines: {
|
||||
color: colors.textSecondary,
|
||||
textAlign: 'center',
|
||||
padding: spacing.xl,
|
||||
},
|
||||
medicineCard: {
|
||||
borderRadius: borderRadius.md,
|
||||
marginBottom: spacing.sm,
|
||||
overflow: 'hidden',
|
||||
},
|
||||
medicineCardContent: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
medicineInfo: {
|
||||
flex: 1,
|
||||
@@ -228,11 +266,9 @@ const styles = StyleSheet.create({
|
||||
medicineName: {
|
||||
fontSize: 16,
|
||||
fontWeight: '500',
|
||||
color: colors.text,
|
||||
},
|
||||
medicineNregistro: {
|
||||
fontSize: 12,
|
||||
color: colors.textSecondary,
|
||||
marginTop: spacing.xs,
|
||||
},
|
||||
medicineStock: {
|
||||
@@ -241,13 +277,23 @@ const styles = StyleSheet.create({
|
||||
price: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: colors.primary,
|
||||
},
|
||||
stock: {
|
||||
fontSize: 12,
|
||||
color: colors.textSecondary,
|
||||
marginTop: spacing.xs,
|
||||
},
|
||||
bellButton: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: spacing.xs,
|
||||
paddingVertical: spacing.sm,
|
||||
borderTopWidth: 1,
|
||||
},
|
||||
bellText: {
|
||||
fontSize: 13,
|
||||
fontWeight: '600',
|
||||
},
|
||||
errorContainer: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
@@ -255,6 +301,5 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
errorText: {
|
||||
fontSize: 16,
|
||||
color: colors.textSecondary,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { View, Text, ScrollView, StyleSheet, Image, ActivityIndicator } from 'react-native';
|
||||
import { useLocalSearchParams } from 'expo-router';
|
||||
import { getProduct, Product } from '../../../services/products';
|
||||
import { LoadingSpinner } from '../../../components/LoadingSpinner';
|
||||
import { useThemeContext } from '../../../components/ThemeProvider';
|
||||
import { spacing, borderRadius } from '../../../constants/theme';
|
||||
|
||||
export default function ProductDetailScreen() {
|
||||
const { source, id } = useLocalSearchParams<{ source: string; id: string }>();
|
||||
const { colors } = useThemeContext();
|
||||
const [product, setProduct] = useState<Product | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!source || !id) return;
|
||||
|
||||
const fetchProduct = async () => {
|
||||
try {
|
||||
const data = await getProduct(source, id);
|
||||
if (data) {
|
||||
setProduct(data);
|
||||
} else {
|
||||
setError(true);
|
||||
}
|
||||
} catch {
|
||||
setError(true);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchProduct();
|
||||
}, [source, id]);
|
||||
|
||||
if (isLoading) {
|
||||
return <LoadingSpinner message="Cargando producto..." />;
|
||||
}
|
||||
|
||||
if (error || !product) {
|
||||
return (
|
||||
<View style={[styles.errorContainer, { backgroundColor: colors.background }]}>
|
||||
<Text style={[styles.errorText, { color: colors.textSecondary }]}>Producto no encontrado</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const isCima = product.source === 'cima';
|
||||
|
||||
return (
|
||||
<ScrollView style={[styles.container, { backgroundColor: colors.background }]}>
|
||||
{product.image_url ? (
|
||||
<Image source={{ uri: product.image_url }} style={styles.image} resizeMode="contain" />
|
||||
) : (
|
||||
<View style={[styles.imagePlaceholder, { backgroundColor: colors.surfaceLow }]}>
|
||||
<Text style={[styles.placeholderText, { color: colors.textSecondary }]}>Sin imagen</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
<View style={[styles.header, { backgroundColor: colors.card }]}>
|
||||
<View style={styles.nameRow}>
|
||||
<Text style={[styles.name, { color: colors.text }]}>{product.name}</Text>
|
||||
<View style={[styles.badge, { backgroundColor: isCima ? '#2b5bb5' : '#4caf50' }]}>
|
||||
<Text style={styles.badgeText}>{isCima ? 'CIMA' : 'OFF'}</Text>
|
||||
</View>
|
||||
</View>
|
||||
{product.brand ? (
|
||||
<Text style={[styles.brand, { color: colors.textSecondary }]}>{product.brand}</Text>
|
||||
) : null}
|
||||
{product.category ? (
|
||||
<Text style={[styles.category, { color: colors.textSecondary }]}>{product.category}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
{isCima ? (
|
||||
<View style={[styles.infoSection, { backgroundColor: colors.card }]}>
|
||||
<Text style={[styles.sectionTitle, { color: colors.text }]}>Detalles CIMA</Text>
|
||||
{product.active_ingredient && (
|
||||
<InfoRow label="Principio activo" value={product.active_ingredient} colors={colors} />
|
||||
)}
|
||||
{product.dosage && (
|
||||
<InfoRow label="Dosificación" value={product.dosage} colors={colors} />
|
||||
)}
|
||||
{product.form && (
|
||||
<InfoRow label="Forma farmacéutica" value={product.form} colors={colors} />
|
||||
)}
|
||||
{product.prescription && (
|
||||
<InfoRow label="Tipo de dispensación" value={product.prescription} colors={colors} />
|
||||
)}
|
||||
<InfoRow label="Comercializado" value={product.commercialized ? 'Sí' : 'No'} colors={colors} />
|
||||
</View>
|
||||
) : (
|
||||
<View style={[styles.infoSection, { backgroundColor: colors.card }]}>
|
||||
<Text style={[styles.sectionTitle, { color: colors.text }]}>Información nutricional</Text>
|
||||
{product.nutriscore && (
|
||||
<InfoRow label="Nutri-Score" value={product.nutriscore.toUpperCase()} colors={colors} />
|
||||
)}
|
||||
{product.nova_group != null && (
|
||||
<InfoRow label="Grupo NOVA" value={String(product.nova_group)} colors={colors} />
|
||||
)}
|
||||
{product.eco_score && (
|
||||
<InfoRow label="Eco-Score" value={product.eco_score.toUpperCase()} colors={colors} />
|
||||
)}
|
||||
{product.ingredients && (
|
||||
<View style={[styles.infoRow, { borderBottomColor: colors.border }]}>
|
||||
<Text style={[styles.infoLabel, { color: colors.textSecondary }]}>Ingredientes</Text>
|
||||
<Text style={[styles.infoValueMultiline, { color: colors.text }]}>{product.ingredients}</Text>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
)}
|
||||
|
||||
{isCima && product.photos && product.photos.length > 0 && (
|
||||
<View style={[styles.infoSection, { backgroundColor: colors.card }]}>
|
||||
<Text style={[styles.sectionTitle, { color: colors.text }]}>Imágenes</Text>
|
||||
<ScrollView horizontal showsHorizontalScrollIndicator={false} style={styles.photosScroll}>
|
||||
{product.photos.map((photo, i) => (
|
||||
<View key={i} style={styles.photoItem}>
|
||||
<Image source={{ uri: photo.url }} style={styles.photoImage} resizeMode="contain" />
|
||||
<Text style={[styles.photoLabel, { color: colors.textSecondary }]}>{photo.tipo}</Text>
|
||||
</View>
|
||||
))}
|
||||
</ScrollView>
|
||||
</View>
|
||||
)}
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
function InfoRow({ label, value, colors }: { label: string; value: string; colors: any }) {
|
||||
return (
|
||||
<View style={[styles.infoRow, { borderBottomColor: colors.border }]}>
|
||||
<Text style={[styles.infoLabel, { color: colors.textSecondary }]}>{label}</Text>
|
||||
<Text style={[styles.infoValue, { color: colors.text }]}>{value}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
},
|
||||
image: {
|
||||
width: '100%',
|
||||
height: 260,
|
||||
backgroundColor: '#f5f5f5',
|
||||
},
|
||||
imagePlaceholder: {
|
||||
width: '100%',
|
||||
height: 160,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
placeholderText: {
|
||||
fontSize: 14,
|
||||
},
|
||||
header: {
|
||||
padding: spacing.lg,
|
||||
},
|
||||
nameRow: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'flex-start',
|
||||
gap: spacing.sm,
|
||||
},
|
||||
name: {
|
||||
flex: 1,
|
||||
fontSize: 22,
|
||||
fontWeight: 'bold',
|
||||
},
|
||||
badge: {
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: spacing.xs,
|
||||
borderRadius: borderRadius.full,
|
||||
overflow: 'hidden',
|
||||
},
|
||||
badgeText: {
|
||||
color: '#fff',
|
||||
fontSize: 12,
|
||||
fontWeight: '700',
|
||||
},
|
||||
brand: {
|
||||
fontSize: 15,
|
||||
marginTop: spacing.xs,
|
||||
},
|
||||
category: {
|
||||
fontSize: 13,
|
||||
marginTop: spacing.xs,
|
||||
},
|
||||
infoSection: {
|
||||
marginTop: spacing.sm,
|
||||
padding: spacing.lg,
|
||||
},
|
||||
sectionTitle: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
infoRow: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
paddingVertical: spacing.sm,
|
||||
borderBottomWidth: 1,
|
||||
},
|
||||
infoLabel: {
|
||||
fontSize: 13,
|
||||
flexShrink: 0,
|
||||
marginRight: spacing.sm,
|
||||
},
|
||||
infoValue: {
|
||||
fontSize: 13,
|
||||
fontWeight: '500',
|
||||
flex: 1,
|
||||
textAlign: 'right',
|
||||
},
|
||||
infoValueMultiline: {
|
||||
fontSize: 13,
|
||||
fontWeight: '500',
|
||||
flex: 1,
|
||||
textAlign: 'right',
|
||||
},
|
||||
photosScroll: {
|
||||
marginTop: spacing.xs,
|
||||
},
|
||||
photoItem: {
|
||||
marginRight: spacing.md,
|
||||
alignItems: 'center',
|
||||
width: 120,
|
||||
},
|
||||
photoImage: {
|
||||
width: 120,
|
||||
height: 120,
|
||||
borderRadius: borderRadius.md,
|
||||
backgroundColor: '#f5f5f5',
|
||||
},
|
||||
photoLabel: {
|
||||
fontSize: 11,
|
||||
marginTop: spacing.xs,
|
||||
},
|
||||
errorContainer: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
},
|
||||
errorText: {
|
||||
fontSize: 16,
|
||||
},
|
||||
});
|
||||
|
Before Width: | Height: | Size: 384 KiB After Width: | Height: | Size: 325 KiB |
|
Before Width: | Height: | Size: 77 KiB After Width: | Height: | Size: 325 KiB |
|
Before Width: | Height: | Size: 4.0 KiB After Width: | Height: | Size: 325 KiB |
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 198 KiB |
|
After Width: | Height: | Size: 1.5 MiB |
|
After Width: | Height: | Size: 325 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
Before Width: | Height: | Size: 1.1 KiB After Width: | Height: | Size: 325 KiB |
|
Before Width: | Height: | Size: 384 KiB After Width: | Height: | Size: 325 KiB |
|
Before Width: | Height: | Size: 384 KiB After Width: | Height: | Size: 325 KiB |
|
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 325 KiB |
@@ -2,7 +2,8 @@ import React, { useState } from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
|
||||
import { CameraView, useCameraPermissions } from 'expo-camera';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { colors, spacing, borderRadius } from '../constants/theme';
|
||||
import { useThemeContext } from './ThemeProvider';
|
||||
import { spacing, borderRadius } from '../constants/theme';
|
||||
|
||||
interface BarcodeScannerProps {
|
||||
onBarcodeScanned: (barcode: string) => void;
|
||||
@@ -12,6 +13,7 @@ interface BarcodeScannerProps {
|
||||
export function BarcodeScanner({ onBarcodeScanned, onClose }: BarcodeScannerProps) {
|
||||
const [permission, requestPermission] = useCameraPermissions();
|
||||
const [scanned, setScanned] = useState(false);
|
||||
const { colors } = useThemeContext();
|
||||
|
||||
if (!permission) {
|
||||
return <View style={styles.container} />;
|
||||
@@ -19,17 +21,17 @@ export function BarcodeScanner({ onBarcodeScanned, onClose }: BarcodeScannerProp
|
||||
|
||||
if (!permission.granted) {
|
||||
return (
|
||||
<View style={styles.permissionContainer}>
|
||||
<View style={[styles.permissionContainer, { backgroundColor: colors.background }]}>
|
||||
<Ionicons name="camera" size={64} color={colors.textSecondary} />
|
||||
<Text style={styles.permissionTitle}>Permiso de cámara requerido</Text>
|
||||
<Text style={styles.permissionText}>
|
||||
<Text style={[styles.permissionTitle, { color: colors.text }]}>Permiso de cámara requerido</Text>
|
||||
<Text style={[styles.permissionText, { color: colors.textSecondary }]}>
|
||||
Necesitamos acceso a la cámara para escanear códigos de barras
|
||||
</Text>
|
||||
<TouchableOpacity style={styles.permissionButton} onPress={requestPermission}>
|
||||
<TouchableOpacity style={[styles.permissionButton, { backgroundColor: colors.primary }]} onPress={requestPermission}>
|
||||
<Text style={styles.permissionButtonText}>Conceder permiso</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity style={styles.cancelButton} onPress={onClose}>
|
||||
<Text style={styles.cancelButtonText}>Cancelar</Text>
|
||||
<Text style={[styles.cancelButtonText, { color: colors.textSecondary }]}>Cancelar</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
);
|
||||
@@ -54,10 +56,10 @@ export function BarcodeScanner({ onBarcodeScanned, onClose }: BarcodeScannerProp
|
||||
|
||||
<View style={styles.overlay}>
|
||||
<View style={styles.scannerFrame}>
|
||||
<View style={[styles.corner, styles.topLeft]} />
|
||||
<View style={[styles.corner, styles.topRight]} />
|
||||
<View style={[styles.corner, styles.bottomLeft]} />
|
||||
<View style={[styles.corner, styles.bottomRight]} />
|
||||
<View style={[styles.corner, styles.topLeft, { borderColor: colors.primary }]} />
|
||||
<View style={[styles.corner, styles.topRight, { borderColor: colors.primary }]} />
|
||||
<View style={[styles.corner, styles.bottomLeft, { borderColor: colors.primary }]} />
|
||||
<View style={[styles.corner, styles.bottomRight, { borderColor: colors.primary }]} />
|
||||
</View>
|
||||
|
||||
<Text style={styles.instruction}>
|
||||
@@ -72,7 +74,7 @@ export function BarcodeScanner({ onBarcodeScanned, onClose }: BarcodeScannerProp
|
||||
{scanned && (
|
||||
<View style={styles.scannedOverlay}>
|
||||
<TouchableOpacity
|
||||
style={styles.scanAgainButton}
|
||||
style={[styles.scanAgainButton, { backgroundColor: colors.primary }]}
|
||||
onPress={() => setScanned(false)}
|
||||
>
|
||||
<Text style={styles.scanAgainText}>Escanear de nuevo</Text>
|
||||
@@ -92,30 +94,26 @@ const styles = StyleSheet.create({
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
alignItems: 'center',
|
||||
backgroundColor: colors.background,
|
||||
padding: spacing.xl,
|
||||
},
|
||||
permissionTitle: {
|
||||
fontSize: 20,
|
||||
fontWeight: 'bold',
|
||||
color: colors.text,
|
||||
marginTop: spacing.lg,
|
||||
},
|
||||
permissionText: {
|
||||
fontSize: 16,
|
||||
color: colors.textSecondary,
|
||||
textAlign: 'center',
|
||||
marginTop: spacing.sm,
|
||||
marginBottom: spacing.xl,
|
||||
},
|
||||
permissionButton: {
|
||||
backgroundColor: colors.primary,
|
||||
borderRadius: borderRadius.md,
|
||||
paddingVertical: spacing.md,
|
||||
paddingHorizontal: spacing.xl,
|
||||
},
|
||||
permissionButtonText: {
|
||||
color: colors.textInverse,
|
||||
color: '#ffffff',
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
},
|
||||
@@ -123,7 +121,6 @@ const styles = StyleSheet.create({
|
||||
marginTop: spacing.md,
|
||||
},
|
||||
cancelButtonText: {
|
||||
color: colors.textSecondary,
|
||||
fontSize: 14,
|
||||
},
|
||||
overlay: {
|
||||
@@ -143,7 +140,6 @@ const styles = StyleSheet.create({
|
||||
position: 'absolute',
|
||||
width: 30,
|
||||
height: 30,
|
||||
borderColor: colors.primary,
|
||||
},
|
||||
topLeft: {
|
||||
top: 0,
|
||||
@@ -170,7 +166,7 @@ const styles = StyleSheet.create({
|
||||
borderRightWidth: 3,
|
||||
},
|
||||
instruction: {
|
||||
color: colors.textInverse,
|
||||
color: '#ffffff',
|
||||
fontSize: 14,
|
||||
textAlign: 'center',
|
||||
marginTop: spacing.xl,
|
||||
@@ -194,13 +190,12 @@ const styles = StyleSheet.create({
|
||||
right: spacing.xl,
|
||||
},
|
||||
scanAgainButton: {
|
||||
backgroundColor: colors.primary,
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
alignItems: 'center',
|
||||
},
|
||||
scanAgainText: {
|
||||
color: colors.textInverse,
|
||||
color: '#ffffff',
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
},
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
import React from 'react';
|
||||
import { View, ActivityIndicator, Text, StyleSheet } from 'react-native';
|
||||
import { colors, spacing } from '../constants/theme';
|
||||
import { useThemeContext } from './ThemeProvider';
|
||||
import { spacing } from '../constants/theme';
|
||||
|
||||
interface LoadingSpinnerProps {
|
||||
message?: string;
|
||||
}
|
||||
|
||||
export function LoadingSpinner({ message = 'Cargando...' }: LoadingSpinnerProps) {
|
||||
const { colors } = useThemeContext();
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<ActivityIndicator size="large" color={colors.primary} />
|
||||
<Text style={styles.message}>{message}</Text>
|
||||
<Text style={[styles.message, { color: colors.textSecondary }]}>{message}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -25,6 +28,5 @@ const styles = StyleSheet.create({
|
||||
message: {
|
||||
marginTop: spacing.md,
|
||||
fontSize: 16,
|
||||
color: colors.textSecondary,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,47 +1,57 @@
|
||||
import React from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
|
||||
import { View, Text, StyleSheet, TouchableOpacity, useWindowDimensions } from 'react-native';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { colors, spacing, borderRadius } from '../constants/theme';
|
||||
import { useThemeContext } from './ThemeProvider';
|
||||
import { spacing, borderRadius } from '../constants/theme';
|
||||
import { StockBadge } from './StockBadge';
|
||||
import { Medicine } from '../types';
|
||||
|
||||
const TABLET_MIN_WIDTH = 768;
|
||||
|
||||
interface MedicineCardProps {
|
||||
medicine: Medicine;
|
||||
}
|
||||
|
||||
export function MedicineCard({ medicine }: MedicineCardProps) {
|
||||
const router = useRouter();
|
||||
const { width } = useWindowDimensions();
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
const { colors } = useThemeContext();
|
||||
|
||||
const handlePress = () => {
|
||||
router.push(`/medicine/${medicine.nregistro}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<TouchableOpacity style={styles.card} onPress={handlePress} activeOpacity={0.7}>
|
||||
<TouchableOpacity
|
||||
style={[styles.card, isTablet && styles.cardTablet, { backgroundColor: colors.card }]}
|
||||
onPress={handlePress}
|
||||
activeOpacity={0.7}
|
||||
>
|
||||
<View style={styles.header}>
|
||||
<Text style={styles.name} numberOfLines={2}>
|
||||
{medicine.nombre}
|
||||
<Text style={[styles.name, isTablet && styles.nameTablet, { color: colors.text }]} numberOfLines={2}>
|
||||
{medicine.name}
|
||||
</Text>
|
||||
<StockBadge stock={medicine.stock} />
|
||||
{medicine.stock != null && <StockBadge stock={medicine.stock} />}
|
||||
</View>
|
||||
|
||||
<Text style={styles.principioActivo} numberOfLines={1}>
|
||||
{medicine.principioActivo}
|
||||
<Text style={[styles.principioActivo, { color: colors.textSecondary }]} numberOfLines={1}>
|
||||
{medicine.active_ingredient}{medicine.dosage ? ` - ${medicine.dosage}` : ''}
|
||||
</Text>
|
||||
|
||||
<View style={styles.footer}>
|
||||
<View style={styles.priceContainer}>
|
||||
<Ionicons name="pricetag" size={14} color={colors.textSecondary} />
|
||||
<Text style={styles.price}>
|
||||
{medicine.precio ? `${medicine.precio.toFixed(2)} €` : 'Sin precio'}
|
||||
<Text style={[styles.price, isTablet && styles.priceTablet, { color: colors.primary }]}>
|
||||
{medicine.precio != null ? `${medicine.precio.toFixed(2)} €` : 'Sin precio'}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<View style={styles.labContainer}>
|
||||
<Ionicons name="business" size={14} color={colors.textSecondary} />
|
||||
<Text style={styles.laboratorio} numberOfLines={1}>
|
||||
{medicine.laboratorio}
|
||||
<Text style={[styles.laboratorio, isTablet && styles.laboratorioTablet, { color: colors.textSecondary }]} numberOfLines={1}>
|
||||
{medicine.laboratory}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
@@ -51,17 +61,22 @@ export function MedicineCard({ medicine }: MedicineCardProps) {
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
card: {
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.md,
|
||||
borderRadius: borderRadius.lg,
|
||||
padding: spacing.md,
|
||||
marginHorizontal: spacing.md,
|
||||
marginHorizontal: spacing.lg,
|
||||
marginVertical: spacing.xs,
|
||||
shadowColor: '#000',
|
||||
shadowOffset: { width: 0, height: 2 },
|
||||
shadowOpacity: 0.1,
|
||||
shadowRadius: 4,
|
||||
shadowOpacity: 0.06,
|
||||
shadowRadius: 8,
|
||||
elevation: 2,
|
||||
},
|
||||
cardTablet: {
|
||||
padding: spacing.lg,
|
||||
maxWidth: 700,
|
||||
alignSelf: 'center',
|
||||
width: '100%',
|
||||
},
|
||||
header: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
@@ -72,12 +87,13 @@ const styles = StyleSheet.create({
|
||||
flex: 1,
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: colors.text,
|
||||
marginRight: spacing.sm,
|
||||
},
|
||||
nameTablet: {
|
||||
fontSize: 18,
|
||||
},
|
||||
principioActivo: {
|
||||
fontSize: 14,
|
||||
color: colors.textSecondary,
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
footer: {
|
||||
@@ -92,9 +108,11 @@ const styles = StyleSheet.create({
|
||||
price: {
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
color: colors.text,
|
||||
marginLeft: spacing.xs,
|
||||
},
|
||||
priceTablet: {
|
||||
fontSize: 16,
|
||||
},
|
||||
labContainer: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
@@ -103,8 +121,11 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
laboratorio: {
|
||||
fontSize: 12,
|
||||
color: colors.textSecondary,
|
||||
marginLeft: spacing.xs,
|
||||
maxWidth: 120,
|
||||
},
|
||||
laboratorioTablet: {
|
||||
fontSize: 14,
|
||||
maxWidth: 200,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import React, { useState } from 'react';
|
||||
import { View, TextInput, StyleSheet, TouchableOpacity } from 'react-native';
|
||||
import { View, TextInput, StyleSheet, TouchableOpacity, useWindowDimensions } from 'react-native';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { colors, spacing, borderRadius } from '../constants/theme';
|
||||
import { useThemeContext } from './ThemeProvider';
|
||||
import { spacing, borderRadius } from '../constants/theme';
|
||||
|
||||
const TABLET_MIN_WIDTH = 768;
|
||||
|
||||
interface SearchBarProps {
|
||||
placeholder?: string;
|
||||
@@ -16,6 +19,9 @@ export function SearchBar({
|
||||
value,
|
||||
onChangeText
|
||||
}: SearchBarProps) {
|
||||
const { width } = useWindowDimensions();
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
const { colors } = useThemeContext();
|
||||
const [localValue, setLocalValue] = useState(value || '');
|
||||
|
||||
const handleChange = (text: string) => {
|
||||
@@ -34,10 +40,10 @@ export function SearchBar({
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<View style={[styles.container, isTablet && styles.containerTablet, { backgroundColor: colors.card }]}>
|
||||
<Ionicons name="search" size={20} color={colors.textSecondary} style={styles.icon} />
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
style={[styles.input, isTablet && styles.inputTablet, { color: colors.text }]}
|
||||
placeholder={placeholder}
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
value={localValue}
|
||||
@@ -59,12 +65,21 @@ const styles = StyleSheet.create({
|
||||
container: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.md,
|
||||
borderRadius: borderRadius.lg,
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: spacing.sm,
|
||||
marginHorizontal: spacing.md,
|
||||
paddingVertical: spacing.sm + 2,
|
||||
marginVertical: spacing.sm,
|
||||
alignSelf: 'center',
|
||||
width: '80%',
|
||||
shadowColor: '#000',
|
||||
shadowOffset: { width: 0, height: 2 },
|
||||
shadowOpacity: 0.06,
|
||||
shadowRadius: 8,
|
||||
elevation: 2,
|
||||
},
|
||||
containerTablet: {
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingVertical: spacing.md,
|
||||
},
|
||||
icon: {
|
||||
marginRight: spacing.sm,
|
||||
@@ -72,9 +87,12 @@ const styles = StyleSheet.create({
|
||||
input: {
|
||||
flex: 1,
|
||||
fontSize: 16,
|
||||
color: colors.text,
|
||||
paddingVertical: spacing.xs,
|
||||
},
|
||||
inputTablet: {
|
||||
fontSize: 18,
|
||||
paddingVertical: spacing.sm,
|
||||
},
|
||||
clearButton: {
|
||||
marginLeft: spacing.sm,
|
||||
},
|
||||
|
||||
@@ -1,27 +1,32 @@
|
||||
import React from 'react';
|
||||
import { View, Text, StyleSheet } from 'react-native';
|
||||
import { colors, borderRadius, spacing } from '../constants/theme';
|
||||
import { useThemeContext } from './ThemeProvider';
|
||||
import { borderRadius, spacing } from '../constants/theme';
|
||||
|
||||
interface StockBadgeProps {
|
||||
stock: number;
|
||||
}
|
||||
|
||||
export function StockBadge({ stock }: StockBadgeProps) {
|
||||
const getBadgeStyle = () => {
|
||||
if (stock === 0) return styles.danger;
|
||||
if (stock < 5) return styles.warning;
|
||||
return styles.success;
|
||||
const { colors, isDark } = useThemeContext();
|
||||
|
||||
const getBadgeColors = () => {
|
||||
if (stock === 0) {
|
||||
return { bg: isDark ? '#3a1a1a' : '#feecec', text: isDark ? '#ef9a9a' : '#b91c1c' };
|
||||
}
|
||||
if (stock < 5) {
|
||||
return { bg: isDark ? '#3a3010' : '#fff3cd', text: isDark ? '#ffd54f' : '#FF9500' };
|
||||
}
|
||||
return { bg: isDark ? '#1a3a1c' : '#eaf7ec', text: isDark ? '#81c784' : '#34C759' };
|
||||
};
|
||||
|
||||
const getText = () => {
|
||||
if (stock === 0) return 'Sin stock';
|
||||
if (stock < 5) return `Bajo (${stock})`;
|
||||
return `Disponible (${stock})`;
|
||||
};
|
||||
const badgeColors = getBadgeColors();
|
||||
|
||||
return (
|
||||
<View style={[styles.badge, getBadgeStyle()]}>
|
||||
<Text style={styles.text}>{getText()}</Text>
|
||||
<View style={[styles.badge, { backgroundColor: badgeColors.bg }]}>
|
||||
<Text style={[styles.text, { color: badgeColors.text }]}>
|
||||
{stock === 0 ? 'Sin stock' : stock < 5 ? `Bajo (${stock})` : `Disponible (${stock})`}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -32,15 +37,6 @@ const styles = StyleSheet.create({
|
||||
paddingVertical: spacing.xs,
|
||||
borderRadius: borderRadius.sm,
|
||||
},
|
||||
success: {
|
||||
backgroundColor: '#D4EDDA',
|
||||
},
|
||||
warning: {
|
||||
backgroundColor: '#FFF3CD',
|
||||
},
|
||||
danger: {
|
||||
backgroundColor: '#F8D7DA',
|
||||
},
|
||||
text: {
|
||||
fontSize: 12,
|
||||
fontWeight: '600',
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import React, { createContext, useContext, useEffect, useMemo } from 'react';
|
||||
import { useColorScheme } from 'react-native';
|
||||
import { useThemeStore } from '../store/themeStore';
|
||||
import { colors, darkColors } from '../constants/theme';
|
||||
import type { AppColors } from '../hooks/useThemeColor';
|
||||
|
||||
interface ThemeContextValue {
|
||||
colors: AppColors;
|
||||
isDark: boolean;
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextValue>({
|
||||
colors,
|
||||
isDark: false,
|
||||
});
|
||||
|
||||
export function useThemeContext() {
|
||||
return useContext(ThemeContext);
|
||||
}
|
||||
|
||||
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||
const systemScheme = useColorScheme();
|
||||
const mode = useThemeStore((s) => s.mode);
|
||||
const init = useThemeStore((s) => s.init);
|
||||
|
||||
useEffect(() => {
|
||||
init();
|
||||
}, []);
|
||||
|
||||
const value = useMemo(() => {
|
||||
const isDark = mode === 'dark' || (mode === 'system' && systemScheme === 'dark');
|
||||
return {
|
||||
colors: isDark ? darkColors : colors,
|
||||
isDark,
|
||||
};
|
||||
}, [mode, systemScheme]);
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={value}>
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -5,14 +5,16 @@ const ENV = {
|
||||
API_BASE_URL: 'http://localhost:3001/api',
|
||||
},
|
||||
production: {
|
||||
API_BASE_URL: 'https://your-production-api.com/api',
|
||||
API_BASE_URL: 'https://farmacias.hacecalor.net/api',
|
||||
},
|
||||
};
|
||||
|
||||
const environment = Constants.expoConfig?.extra?.environment || (__DEV__ ? 'development' : 'production');
|
||||
|
||||
const envBaseUrl = process.env.EXPO_PUBLIC_API_URL;
|
||||
|
||||
export const config = {
|
||||
API_BASE_URL: ENV[environment as keyof typeof ENV]?.API_BASE_URL || ENV.development.API_BASE_URL,
|
||||
API_BASE_URL: envBaseUrl || 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
|
||||
|
||||
@@ -1,25 +1,93 @@
|
||||
export const colors = {
|
||||
// Primary
|
||||
primary: '#007AFF',
|
||||
primaryLight: '#4DA3FF',
|
||||
primaryDark: '#0056CC',
|
||||
// Primary - pastel green pharmacy palette (matching PWA)
|
||||
primary: '#7fbf8f',
|
||||
primaryLight: '#cfead0',
|
||||
primaryDark: '#09310a',
|
||||
onPrimary: '#09310a',
|
||||
primaryContainer: '#cfead0',
|
||||
onPrimaryContainer: '#0d2b12',
|
||||
|
||||
// Secondary - soft blue
|
||||
secondary: '#a3b8ff',
|
||||
secondaryContainer: '#dbe7ff',
|
||||
|
||||
// Tertiary - soft lavender
|
||||
tertiary: '#c9b3ff',
|
||||
tertiaryContainer: '#efe7ff',
|
||||
|
||||
// Scan button - vivid blue (intentionally prominent)
|
||||
scanButton: '#2b5bb5',
|
||||
scanButtonShadow: 'rgba(43, 91, 181, 0.32)',
|
||||
|
||||
// Semantic
|
||||
success: '#34C759',
|
||||
danger: '#FF3B30',
|
||||
danger: '#b91c1c',
|
||||
dangerContainer: '#feecec',
|
||||
warning: '#FF9500',
|
||||
|
||||
// Neutral
|
||||
background: '#F2F2F7',
|
||||
card: '#FFFFFF',
|
||||
border: '#E5E5EA',
|
||||
separator: '#C6C6C8',
|
||||
// Surface
|
||||
background: 'transparent',
|
||||
card: '#ffffff',
|
||||
surfaceLow: '#f2f4f5',
|
||||
surface: '#eceeef',
|
||||
surfaceHigh: '#e6e8e9',
|
||||
border: '#c0c9bb',
|
||||
separator: '#c0c9bb',
|
||||
|
||||
// Text
|
||||
text: '#1C1C1E',
|
||||
textSecondary: '#8E8E93',
|
||||
textInverse: '#FFFFFF',
|
||||
textLink: '#007AFF',
|
||||
text: '#111417',
|
||||
textSecondary: '#41493e',
|
||||
textInverse: '#ffffff',
|
||||
textLink: '#7fbf8f',
|
||||
|
||||
// Accent
|
||||
accentWarm: '#f5a97a',
|
||||
};
|
||||
|
||||
export const darkColors = {
|
||||
// Primary - pastel green pharmacy palette
|
||||
primary: '#7fbf8f',
|
||||
primaryLight: '#2a5a35',
|
||||
primaryDark: '#cfead0',
|
||||
onPrimary: '#cfead0',
|
||||
primaryContainer: '#1a3a1c',
|
||||
onPrimaryContainer: '#cfead0',
|
||||
|
||||
// Secondary - soft blue
|
||||
secondary: '#a3b8ff',
|
||||
secondaryContainer: '#1a2a4a',
|
||||
|
||||
// Tertiary - soft lavender
|
||||
tertiary: '#c9b3ff',
|
||||
tertiaryContainer: '#2a1a4a',
|
||||
|
||||
// Scan button - vivid blue
|
||||
scanButton: '#4a7dd5',
|
||||
scanButtonShadow: 'rgba(74, 125, 213, 0.32)',
|
||||
|
||||
// Semantic
|
||||
success: '#34C759',
|
||||
danger: '#ef5350',
|
||||
dangerContainer: '#3a1a1a',
|
||||
warning: '#FF9500',
|
||||
|
||||
// Surface
|
||||
background: 'transparent',
|
||||
card: '#1e1e1e',
|
||||
surfaceLow: '#2a2a2a',
|
||||
surface: '#333333',
|
||||
surfaceHigh: '#3a3a3a',
|
||||
border: '#3a3a3a',
|
||||
separator: '#3a3a3a',
|
||||
|
||||
// Text
|
||||
text: '#f0f0f0',
|
||||
textSecondary: '#a0a0a0',
|
||||
textInverse: '#111417',
|
||||
textLink: '#7fbf8f',
|
||||
|
||||
// Accent
|
||||
accentWarm: '#f5a97a',
|
||||
};
|
||||
|
||||
export const spacing = {
|
||||
@@ -32,27 +100,67 @@ export const spacing = {
|
||||
};
|
||||
|
||||
export const borderRadius = {
|
||||
sm: 8,
|
||||
md: 12,
|
||||
lg: 16,
|
||||
xl: 24,
|
||||
sm: 4,
|
||||
md: 8,
|
||||
lg: 12,
|
||||
xl: 16,
|
||||
full: 9999,
|
||||
};
|
||||
|
||||
export const typography = {
|
||||
title: {
|
||||
fontSize: 28,
|
||||
fontWeight: 'bold' as const,
|
||||
color: '#111417',
|
||||
},
|
||||
heading: {
|
||||
fontSize: 20,
|
||||
fontWeight: '600' as const,
|
||||
color: '#111417',
|
||||
},
|
||||
body: {
|
||||
fontSize: 16,
|
||||
fontWeight: 'normal' as const,
|
||||
color: '#111417',
|
||||
},
|
||||
bodyLarge: {
|
||||
fontSize: 18,
|
||||
fontWeight: '400' as const,
|
||||
color: '#41493e',
|
||||
lineHeight: 27,
|
||||
},
|
||||
caption: {
|
||||
fontSize: 12,
|
||||
fontWeight: 'normal' as const,
|
||||
color: '#41493e',
|
||||
},
|
||||
label: {
|
||||
fontSize: 14,
|
||||
fontWeight: '500' as const,
|
||||
color: '#41493e',
|
||||
},
|
||||
};
|
||||
|
||||
export const shadows = {
|
||||
soft: {
|
||||
shadowColor: '#000',
|
||||
shadowOffset: { width: 0, height: 4 },
|
||||
shadowOpacity: 0.08,
|
||||
shadowRadius: 20,
|
||||
elevation: 3,
|
||||
},
|
||||
card: {
|
||||
shadowColor: '#000',
|
||||
shadowOffset: { width: 0, height: 2 },
|
||||
shadowOpacity: 0.06,
|
||||
shadowRadius: 8,
|
||||
elevation: 2,
|
||||
},
|
||||
scanButton: {
|
||||
shadowColor: '#2b5bb5',
|
||||
shadowOffset: { width: 0, height: 8 },
|
||||
shadowOpacity: 0.32,
|
||||
shadowRadius: 26,
|
||||
elevation: 8,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -15,17 +15,11 @@
|
||||
},
|
||||
"preview": {
|
||||
"distribution": "internal",
|
||||
"ios": {
|
||||
"buildType": "preview"
|
||||
},
|
||||
"android": {
|
||||
"buildType": "apk"
|
||||
}
|
||||
},
|
||||
"production": {
|
||||
"ios": {
|
||||
"buildType": "release"
|
||||
},
|
||||
"android": {
|
||||
"buildType": "app-bundle"
|
||||
}
|
||||
@@ -33,11 +27,6 @@
|
||||
},
|
||||
"submit": {
|
||||
"production": {
|
||||
"ios": {
|
||||
"appleId": "",
|
||||
"ascAppId": "",
|
||||
"appleTeamId": ""
|
||||
},
|
||||
"android": {
|
||||
"serviceAccountKeyPath": "./google-service-account.json"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"project_info": {
|
||||
"project_number": "441816187714",
|
||||
"project_id": "farmaclic-53c42",
|
||||
"storage_bucket": "farmaclic-53c42.firebasestorage.app"
|
||||
},
|
||||
"client": [
|
||||
{
|
||||
"client_info": {
|
||||
"mobilesdk_app_id": "1:441816187714:android:e212145141c570147fbedb",
|
||||
"android_client_info": {
|
||||
"package_name": "com.farmafinder.app"
|
||||
}
|
||||
},
|
||||
"oauth_client": [],
|
||||
"api_key": [
|
||||
{
|
||||
"current_key": "AIzaSyD6cnDvP9v1a7XUI7p8oF0jTPwTNBgKylY"
|
||||
}
|
||||
],
|
||||
"services": {
|
||||
"appinvite_service": {
|
||||
"other_platform_oauth_client": []
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"configuration_version": "1"
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
|
||||
const STORAGE_KEY = 'recent_medicine_searches';
|
||||
const MAX_ITEMS = 5;
|
||||
|
||||
export function useRecentSearches() {
|
||||
const [recentSearches, setRecentSearches] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
AsyncStorage.getItem(STORAGE_KEY).then((data) => {
|
||||
if (data) setRecentSearches(JSON.parse(data));
|
||||
});
|
||||
}, []);
|
||||
|
||||
const addSearch = useCallback(async (query: string) => {
|
||||
const trimmed = query.trim();
|
||||
if (!trimmed) return;
|
||||
setRecentSearches((prev) => {
|
||||
const filtered = prev.filter((s) => s !== trimmed);
|
||||
const next = [trimmed, ...filtered].slice(0, MAX_ITEMS);
|
||||
AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const removeSearch = useCallback(async (query: string) => {
|
||||
setRecentSearches((prev) => {
|
||||
const next = prev.filter((s) => s !== query);
|
||||
AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const clearAll = useCallback(async () => {
|
||||
setRecentSearches([]);
|
||||
AsyncStorage.removeItem(STORAGE_KEY);
|
||||
}, []);
|
||||
|
||||
return { recentSearches, addSearch, removeSearch, clearAll };
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { useWindowDimensions } from 'react-native';
|
||||
|
||||
const TABLET_MIN_WIDTH = 768;
|
||||
|
||||
export function useResponsive() {
|
||||
const { width, height } = useWindowDimensions();
|
||||
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
const isLandscape = width > height;
|
||||
|
||||
// Scale factor for tablet: 1.0 on phone, ~1.2 on tablet
|
||||
const scale = isTablet ? 1.2 : 1.0;
|
||||
|
||||
// Max content width to prevent stretching on large screens
|
||||
const maxContentWidth = isTablet ? Math.min(600, width * 0.6) : width;
|
||||
|
||||
// Horizontal padding: more on tablets to center content
|
||||
const horizontalPadding = isTablet ? 48 : 24;
|
||||
|
||||
return {
|
||||
width,
|
||||
height,
|
||||
isTablet,
|
||||
isLandscape,
|
||||
scale,
|
||||
maxContentWidth,
|
||||
horizontalPadding,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useColorScheme } from 'react-native';
|
||||
import { colors, darkColors } from '../constants/theme';
|
||||
import { useThemeStore, ThemeMode } from '../store/themeStore';
|
||||
|
||||
export type AppColors = typeof colors;
|
||||
|
||||
export function useThemeColor(): { colors: AppColors; isDark: boolean; mode: ThemeMode } {
|
||||
const systemScheme = useColorScheme();
|
||||
const mode = useThemeStore((s) => s.mode);
|
||||
|
||||
const isDark =
|
||||
mode === 'dark' || (mode === 'system' && systemScheme === 'dark');
|
||||
|
||||
return {
|
||||
colors: isDark ? darkColors : colors,
|
||||
isDark,
|
||||
mode,
|
||||
};
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
"version": "1.0.0",
|
||||
"main": "expo-router/entry",
|
||||
"dependencies": {
|
||||
"@expo/vector-icons": "^15.0.2",
|
||||
"@react-native-async-storage/async-storage": "2.2.0",
|
||||
"@tanstack/react-query": "^5.101.2",
|
||||
"axios": "^1.18.1",
|
||||
@@ -12,8 +13,10 @@
|
||||
"expo-constants": "~57.0.3",
|
||||
"expo-dev-client": "~57.0.5",
|
||||
"expo-device": "~7.0.2",
|
||||
"expo-image-picker": "~57.0.2",
|
||||
"expo-linking": "~57.0.1",
|
||||
"expo-local-authentication": "~57.0.0",
|
||||
"expo-location": "~57.0.2",
|
||||
"expo-notifications": "~57.0.3",
|
||||
"expo-router": "~57.0.3",
|
||||
"expo-secure-store": "~57.0.0",
|
||||
|
||||
@@ -2,32 +2,43 @@ import axios from 'axios';
|
||||
import * as SecureStore from 'expo-secure-store';
|
||||
import { config } from '../constants/config';
|
||||
|
||||
const SESSION_KEY = 'session_id';
|
||||
|
||||
export const api = axios.create({
|
||||
baseURL: config.API_BASE_URL,
|
||||
timeout: 10000,
|
||||
withCredentials: true,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
// Request interceptor - add auth token
|
||||
// Request interceptor - restore session cookie from SecureStore
|
||||
api.interceptors.request.use(
|
||||
async (axiosConfig) => {
|
||||
const token = await SecureStore.getItemAsync('auth_token');
|
||||
if (token) {
|
||||
axiosConfig.headers.Authorization = `Bearer ${token}`;
|
||||
const session = await SecureStore.getItemAsync(SESSION_KEY);
|
||||
if (session) {
|
||||
axiosConfig.headers.Cookie = session;
|
||||
}
|
||||
return axiosConfig;
|
||||
},
|
||||
(error) => Promise.reject(error)
|
||||
);
|
||||
|
||||
// Response interceptor - handle errors
|
||||
// Response interceptor - capture and persist session cookie from responses
|
||||
api.interceptors.response.use(
|
||||
(response) => response,
|
||||
(response) => {
|
||||
const setCookie = response.headers['set-cookie'];
|
||||
if (setCookie) {
|
||||
const cookieStr = Array.isArray(setCookie) ? setCookie[0] : setCookie;
|
||||
const sessionId = cookieStr.split(';')[0];
|
||||
SecureStore.setItemAsync(SESSION_KEY, sessionId);
|
||||
}
|
||||
return response;
|
||||
},
|
||||
async (error) => {
|
||||
if (error.response?.status === 401) {
|
||||
await SecureStore.deleteItemAsync('auth_token');
|
||||
await SecureStore.deleteItemAsync(SESSION_KEY);
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
@@ -2,42 +2,44 @@ import api from './api';
|
||||
import * as SecureStore from 'expo-secure-store';
|
||||
import { AuthResponse, User } from '../types';
|
||||
|
||||
const USER_KEY = 'user_data';
|
||||
|
||||
export async function login(username: string, password: string): Promise<AuthResponse> {
|
||||
const response = await api.post('/auth/login', { username, password });
|
||||
const { user, token } = response.data;
|
||||
const { user } = response.data;
|
||||
|
||||
await SecureStore.setItemAsync('auth_token', token);
|
||||
await SecureStore.setItemAsync('user', JSON.stringify(user));
|
||||
await SecureStore.setItemAsync(USER_KEY, JSON.stringify(user));
|
||||
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function logout(): Promise<void> {
|
||||
await api.post('/auth/logout');
|
||||
await SecureStore.deleteItemAsync('auth_token');
|
||||
await SecureStore.deleteItemAsync('user');
|
||||
await SecureStore.deleteItemAsync(USER_KEY);
|
||||
}
|
||||
|
||||
export async function checkAuth(): Promise<User | null> {
|
||||
try {
|
||||
const response = await api.get('/auth/check');
|
||||
if (response.data.authenticated) {
|
||||
return response.data.user;
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getStoredUser(): Promise<User | null> {
|
||||
const userStr = await SecureStore.getItemAsync('user');
|
||||
const userStr = await SecureStore.getItemAsync(USER_KEY);
|
||||
return userStr ? JSON.parse(userStr) : null;
|
||||
}
|
||||
|
||||
export async function register(username: string, password: string): Promise<AuthResponse> {
|
||||
const response = await api.post('/auth/register', { username, password });
|
||||
const { user, token } = response.data;
|
||||
const { user } = response.data;
|
||||
|
||||
await SecureStore.setItemAsync('auth_token', token);
|
||||
await SecureStore.setItemAsync('user', JSON.stringify(user));
|
||||
await SecureStore.setItemAsync(USER_KEY, JSON.stringify(user));
|
||||
|
||||
return response.data;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import * as Notifications from 'expo-notifications';
|
||||
import * as Device from 'expo-device';
|
||||
import * as Constants from 'expo-constants';
|
||||
import { Platform } from 'react-native';
|
||||
import api from './api';
|
||||
|
||||
Notifications.setNotificationHandler({
|
||||
handleNotification: async () => ({
|
||||
@@ -12,6 +13,8 @@ Notifications.setNotificationHandler({
|
||||
}),
|
||||
});
|
||||
|
||||
let _cachedToken: string | null = null;
|
||||
|
||||
export async function registerForPushNotifications() {
|
||||
if (!Device.isDevice) {
|
||||
console.log('Push notifications require a physical device');
|
||||
@@ -48,6 +51,11 @@ export async function registerForPushNotifications() {
|
||||
projectId,
|
||||
});
|
||||
|
||||
_cachedToken = token.data;
|
||||
|
||||
// Register token with backend (fire and forget)
|
||||
registerTokenWithBackend(token.data).catch(() => {});
|
||||
|
||||
return token.data;
|
||||
} catch (e) {
|
||||
console.log('Error getting push token:', e);
|
||||
@@ -55,6 +63,52 @@ export async function registerForPushNotifications() {
|
||||
}
|
||||
}
|
||||
|
||||
async function registerTokenWithBackend(token: string) {
|
||||
try {
|
||||
await api.post('/notifications/expo-register', { token });
|
||||
} catch (e) {
|
||||
console.log('Failed to register push token with backend:', e);
|
||||
}
|
||||
}
|
||||
|
||||
export async function subscribeToMedicine(
|
||||
medicineNregistro: string,
|
||||
medicineName: string | null,
|
||||
pharmacyId?: number | null
|
||||
) {
|
||||
const token = _cachedToken;
|
||||
if (!token) {
|
||||
console.log('No push token available for subscription');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await api.post('/notifications/expo-register', {
|
||||
token,
|
||||
medicine_nregistro: medicineNregistro,
|
||||
medicine_name: medicineName,
|
||||
pharmacy_id: pharmacyId || null,
|
||||
});
|
||||
} catch (e) {
|
||||
console.log('Failed to subscribe to medicine notifications:', e);
|
||||
}
|
||||
}
|
||||
|
||||
export async function unsubscribeFromMedicine(
|
||||
medicineNregistro: string,
|
||||
pharmacyId?: number | null
|
||||
) {
|
||||
try {
|
||||
await api.delete('/notifications/expo-unregister', {
|
||||
data: {
|
||||
medicine_nregistro: medicineNregistro,
|
||||
pharmacy_id: pharmacyId || null,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
console.log('Failed to unsubscribe from medicine notifications:', e);
|
||||
}
|
||||
}
|
||||
|
||||
export async function scheduleMedicineAvailabilityNotification(
|
||||
medicineName: string,
|
||||
pharmacyName: string
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import api from './api';
|
||||
|
||||
export interface Product {
|
||||
id: string;
|
||||
source: 'cima' | 'openfoodfacts';
|
||||
name: string;
|
||||
brand: string;
|
||||
category: string;
|
||||
image_url: string | null;
|
||||
active_ingredient?: string;
|
||||
dosage?: string;
|
||||
form?: string;
|
||||
prescription?: string;
|
||||
commercialized?: boolean;
|
||||
photos?: { tipo: string; url: string }[];
|
||||
docs?: { tipo: number; url: string }[];
|
||||
nutriscore?: string;
|
||||
ingredients?: string;
|
||||
nova_group?: number;
|
||||
eco_score?: string;
|
||||
}
|
||||
|
||||
export interface ProductSearchResponse {
|
||||
results: Product[];
|
||||
total: number;
|
||||
sources: {
|
||||
cima: number;
|
||||
openfoodfacts: number;
|
||||
};
|
||||
}
|
||||
|
||||
export async function searchProducts(query: string): Promise<Product[]> {
|
||||
if (!query || query.trim().length < 2) return [];
|
||||
try {
|
||||
const { data } = await api.get<ProductSearchResponse>('/products/search', {
|
||||
params: { q: query }
|
||||
});
|
||||
return data.results || [];
|
||||
} catch (error) {
|
||||
console.error('[Products] Search error:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function getProduct(source: string, id: string): Promise<Product | null> {
|
||||
try {
|
||||
const { data } = await api.get<Product>(`/products/${source}/${id}`);
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('[Products] Detail error:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { create } from 'zustand';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
|
||||
export type ThemeMode = 'light' | 'dark' | 'system';
|
||||
|
||||
interface ThemeState {
|
||||
mode: ThemeMode;
|
||||
setMode: (mode: ThemeMode) => Promise<void>;
|
||||
init: () => Promise<void>;
|
||||
}
|
||||
|
||||
const STORAGE_KEY = '@theme_mode';
|
||||
|
||||
export const useThemeStore = create<ThemeState>((set) => ({
|
||||
mode: 'system',
|
||||
|
||||
setMode: async (mode: ThemeMode) => {
|
||||
set({ mode });
|
||||
await AsyncStorage.setItem(STORAGE_KEY, mode);
|
||||
},
|
||||
|
||||
init: async () => {
|
||||
try {
|
||||
const saved = await AsyncStorage.getItem(STORAGE_KEY);
|
||||
if (saved === 'light' || saved === 'dark' || saved === 'system') {
|
||||
set({ mode: saved });
|
||||
}
|
||||
} catch {}
|
||||
},
|
||||
}));
|
||||
@@ -1,12 +1,20 @@
|
||||
export interface Medicine {
|
||||
id: string;
|
||||
nregistro: string;
|
||||
nombre: string;
|
||||
principioActivo: string;
|
||||
laboratorio: string;
|
||||
formaFarmaceutica: string;
|
||||
precio: number | null;
|
||||
stock: number;
|
||||
disponibilidad: 'disponible' | 'sin_stock' | 'bajo_stock';
|
||||
name: string;
|
||||
active_ingredient: string;
|
||||
dosage: string;
|
||||
form: string;
|
||||
formSimplified: string;
|
||||
laboratory: string;
|
||||
prescription: string;
|
||||
commercialized: boolean;
|
||||
generic: boolean;
|
||||
photos: string[];
|
||||
docs: { tipo: number; url: string; urlHtml?: string; secc: boolean; fecha: number }[];
|
||||
// Optional pharmacy-specific fields (only present in pharmacy_medicines joins)
|
||||
precio?: number | null;
|
||||
stock?: number;
|
||||
}
|
||||
|
||||
export interface Pharmacy {
|
||||
@@ -16,15 +24,22 @@ export interface Pharmacy {
|
||||
phone: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
opening_hours?: string;
|
||||
}
|
||||
|
||||
export interface PharmacyMedicine {
|
||||
id: number;
|
||||
pharmacy_id: number;
|
||||
medicine_nregistro: string;
|
||||
medicine_name: string;
|
||||
price: number;
|
||||
stock: number;
|
||||
pharmacy_id?: number;
|
||||
medicine_nregistro?: string;
|
||||
medicine_name?: string;
|
||||
name?: string;
|
||||
address?: string;
|
||||
phone?: string;
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
opening_hours?: string;
|
||||
price?: number | null;
|
||||
stock?: number;
|
||||
pharmacy?: Pharmacy;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM node:20-alpine AS build
|
||||
FROM node:24-alpine AS build
|
||||
ARG VITE_FARO_ENDPOINT
|
||||
ARG VITE_FARO_APP_NAME=farmaclic-frontend
|
||||
ARG VITE_FARO_ENV=production
|
||||
@@ -9,7 +9,7 @@ ENV VITE_FARO_ENV=$VITE_FARO_ENV
|
||||
ENV VITE_FARO_APP_VERSION=$VITE_FARO_APP_VERSION
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm ci
|
||||
RUN npm ci --legacy-peer-deps
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||
<meta name="theme-color" content="#7fbf8f" />
|
||||
<meta name="theme-color" content="#c0dde9" />
|
||||
<title>FarmaClic</title>
|
||||
<link rel="icon" href="/favicon.png" type="image/png" />
|
||||
<link rel="icon" href="/favicon.ico" sizes="32x32" />
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
"@grafana/faro-web-sdk": "^1.7.0",
|
||||
"@grafana/faro-web-tracing": "^1.7.0",
|
||||
"@zxing/browser": "^0.2.0",
|
||||
"@zxing/library": "^0.22.0",
|
||||
"@zxing/library": "^0.23.0",
|
||||
"leaflet": "^1.9.4",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
@@ -3704,9 +3704,10 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@zxing/library": {
|
||||
"version": "0.22.0",
|
||||
"resolved": "https://registry.npmjs.org/@zxing/library/-/library-0.22.0.tgz",
|
||||
"integrity": "sha512-BmInervZV7NwaZWX1LW64sZ4Lh4wxXYFZwGmj98ArPOkRXCtO9b8Gog0Xyh82dsYYGOeRxX+aAhLSq+hQ2XLZQ==",
|
||||
"version": "0.23.0",
|
||||
"resolved": "https://registry.npmjs.org/@zxing/library/-/library-0.23.0.tgz",
|
||||
"integrity": "sha512-6fkkoFwP8CHxl6ugnPsj74PLJgX2iRv5zczGAyt5OBzQgxFhuhF0NCEc4t4OvSr8xAv2MRLlI0Iu9ZGDZQ2urA==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"ts-custom-error": "^3.3.1"
|
||||
},
|
||||
|
||||
|
Before Width: | Height: | Size: 85 KiB After Width: | Height: | Size: 602 KiB |
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 44 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 34 KiB |
|
After Width: | Height: | Size: 36 KiB |
|
After Width: | Height: | Size: 33 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
After Width: | Height: | Size: 1.8 KiB |
|
Before Width: | Height: | Size: 68 KiB After Width: | Height: | Size: 325 KiB |
|
After Width: | Height: | Size: 325 KiB |
|
Before Width: | Height: | Size: 29 KiB After Width: | Height: | Size: 121 KiB |
|
Before Width: | Height: | Size: 9.1 KiB After Width: | Height: | Size: 15 KiB |
|
Before Width: | Height: | Size: 149 KiB After Width: | Height: | Size: 325 KiB |
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 325 KiB |
@@ -11,6 +11,7 @@
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
overscroll-behavior-y: contain;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import React, { useState, useEffect } from 'react';
|
||||
import './App.css';
|
||||
import HomeView from './views/HomeView';
|
||||
import SearchView from './views/SearchView';
|
||||
import ProductView from './views/ProductView';
|
||||
import ScannerView from './views/ScannerView';
|
||||
import AlertsView from './views/AlertsView';
|
||||
import ProfileView from './views/ProfileView';
|
||||
@@ -9,6 +10,7 @@ import AdminView from './views/AdminView';
|
||||
import LoginModal from './components/LoginModal';
|
||||
import SavedNotifications from './components/SavedNotifications';
|
||||
import BottomNav from './components/BottomNav';
|
||||
import { getFaro } from './utils/faro';
|
||||
|
||||
function App() {
|
||||
const [screen, setScreen] = useState('home');
|
||||
@@ -17,16 +19,45 @@ function App() {
|
||||
const [showLogin, setShowLogin] = useState(false);
|
||||
const [showSaved, setShowSaved] = useState(false);
|
||||
const [badgeCount, setBadgeCount] = useState(0);
|
||||
const [prescriptionSearch, setPrescriptionSearch] = useState('');
|
||||
const [productScreen, setProductScreen] = useState(null);
|
||||
const [screenSize, setScreenSize] = useState({
|
||||
width: window.innerWidth,
|
||||
height: window.innerHeight
|
||||
});
|
||||
|
||||
// Theme: 'auto' | 'light' | 'dark'
|
||||
const [theme, setThemeState] = useState(() => {
|
||||
return localStorage.getItem('ff-theme') || 'auto';
|
||||
});
|
||||
|
||||
// Device detection
|
||||
const isMobile = screenSize.width <= 768;
|
||||
const isTablet = screenSize.width > 768 && screenSize.width <= 1024;
|
||||
const isDesktop = screenSize.width > 1024;
|
||||
|
||||
// Apply theme to document
|
||||
useEffect(() => {
|
||||
const mq = window.matchMedia('(prefers-color-scheme: dark)');
|
||||
|
||||
function applyTheme() {
|
||||
const isDark = theme === 'dark' || (theme === 'auto' && mq.matches);
|
||||
document.documentElement.setAttribute('data-theme', isDark ? 'dark' : 'light');
|
||||
}
|
||||
|
||||
applyTheme();
|
||||
|
||||
if (theme === 'auto') {
|
||||
mq.addEventListener('change', applyTheme);
|
||||
return () => mq.removeEventListener('change', applyTheme);
|
||||
}
|
||||
}, [theme]);
|
||||
|
||||
function setTheme(newTheme) {
|
||||
setThemeState(newTheme);
|
||||
localStorage.setItem('ff-theme', newTheme);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
// Set initial screen size
|
||||
const handleResize = () => {
|
||||
@@ -39,7 +70,10 @@ function App() {
|
||||
fetch('/api/auth/check')
|
||||
.then(r => r.json())
|
||||
.then(data => { if (data.authenticated) setCurrentUser(data.user); })
|
||||
.catch(() => {})
|
||||
.catch((err) => {
|
||||
console.warn('[auth/check]', err);
|
||||
getFaro()?.pushError(err, { type: 'network', url: '/api/auth/check' });
|
||||
})
|
||||
.finally(() => setAuthChecked(true));
|
||||
|
||||
window.addEventListener('resize', handleResize);
|
||||
@@ -56,7 +90,10 @@ function App() {
|
||||
const count = (data.global?.length || 0) + (data.pharmacy?.length || 0);
|
||||
setBadgeCount(count);
|
||||
})
|
||||
.catch(() => {});
|
||||
.catch((err) => {
|
||||
console.warn('[notifications/mine]', err);
|
||||
getFaro()?.pushError(err, { type: 'network', url: '/api/notifications/mine' });
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [currentUser]);
|
||||
|
||||
@@ -68,7 +105,10 @@ function App() {
|
||||
if (!data) return;
|
||||
setBadgeCount((data.global?.length || 0) + (data.pharmacy?.length || 0));
|
||||
})
|
||||
.catch(() => {});
|
||||
.catch((err) => {
|
||||
console.warn('[refreshBadge]', err);
|
||||
getFaro()?.pushError(err, { type: 'network', url: '/api/notifications/mine' });
|
||||
});
|
||||
}
|
||||
|
||||
function handleLogin(user) {
|
||||
@@ -120,17 +160,41 @@ function App() {
|
||||
onShowSaved={() => setShowSaved(true)}
|
||||
onLogout={handleLogout}
|
||||
onAdminClick={handleAdminClick}
|
||||
theme={theme}
|
||||
onThemeChange={setTheme}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
case 'alerts':
|
||||
activeView = <AlertsView onNotificationChange={refreshBadgeCount} />;
|
||||
activeView = (
|
||||
<AlertsView
|
||||
onNotificationChange={refreshBadgeCount}
|
||||
onNavigateToMedicine={(name) => {
|
||||
setPrescriptionSearch(name);
|
||||
setScreen('search');
|
||||
}}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
case 'search':
|
||||
activeView = (
|
||||
<SearchView
|
||||
currentUser={currentUser}
|
||||
onLoginRequest={() => setShowLogin(true)}
|
||||
initialQuery={prescriptionSearch}
|
||||
onNavigateToProduct={(source, id) => {
|
||||
setProductScreen({ source, id });
|
||||
setScreen('product');
|
||||
}}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
case 'product':
|
||||
activeView = (
|
||||
<ProductView
|
||||
source={productScreen?.source}
|
||||
id={productScreen?.id}
|
||||
onBack={() => { setProductScreen(null); setScreen('search'); }}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
@@ -139,7 +203,8 @@ function App() {
|
||||
<ScannerView
|
||||
onClose={() => setScreen('home')}
|
||||
onSelectMedicine={(name) => {
|
||||
setScreen('home');
|
||||
setPrescriptionSearch(name);
|
||||
setScreen('search');
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
|
After Width: | Height: | Size: 1.5 MiB |