Compare commits
44 Commits
2e9b2f2c1f
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 5c782dede7 | |||
| ff387e3d20 | |||
| 58c1fb5bb6 | |||
| e83f32324f | |||
| 59f81c9203 | |||
| 809d4b8a7f | |||
| e281bd4fa8 | |||
| 52b5b72cfb | |||
| 89cb8ee2fb | |||
| bd7fe56330 | |||
| e3db56715b | |||
| 84bf5f3f79 | |||
| 4370d3c35c | |||
| 5ae3ebecee | |||
| 20cc399731 | |||
| 6fa12b12d9 | |||
| 731b51ff48 | |||
| ca4a9671e7 | |||
| 241d362528 | |||
| 13cf7b66ee | |||
| 39868d95c6 | |||
| 2d839b9082 | |||
| 1a2e9aafb2 | |||
| edfe7d6390 | |||
| b7ca3633e6 | |||
| e48ef31fee | |||
| ee42562e13 | |||
| 484220a0f6 | |||
| 930b9434c6 | |||
| 1318243841 | |||
| b8b8655634 | |||
| 839c64c12a | |||
| 2713be85a3 | |||
| 0c43d32cf1 | |||
| a00cfe949c | |||
| 2a7ab64bbf | |||
| bf519e43c9 | |||
| d371fd2bb7 | |||
| 02cab5f740 | |||
| 8b9b7e8444 | |||
| f58b4427a8 | |||
| ec2416613c | |||
| 2f36ef685d | |||
| e9a1d7c53d |
@@ -31,32 +31,36 @@ jobs:
|
||||
needs: detect-changes
|
||||
if: needs.detect-changes.outputs.backend == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
node-version: '22'
|
||||
cache: 'npm'
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
run: npm ci --ignore-scripts
|
||||
- name: Install backend native deps
|
||||
run: npm rebuild sqlite3 bcrypt --workspace=farma-clic-backend
|
||||
- name: Run tests
|
||||
run: npm test --workspace=farma-clic-backend -- --ci
|
||||
run: npm test --workspace=farma-clic-backend
|
||||
|
||||
test-frontend:
|
||||
name: Frontend Tests
|
||||
needs: detect-changes
|
||||
if: needs.detect-changes.outputs.frontend == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
node-version: '22'
|
||||
cache: 'npm'
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
run: npm ci --ignore-scripts
|
||||
- name: Run tests
|
||||
run: npm test --workspace=farma-clic-frontend -- --run --reporter=basic
|
||||
|
||||
|
||||
@@ -34,40 +34,36 @@ jobs:
|
||||
needs: detect-changes
|
||||
if: needs.detect-changes.outputs.backend == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
node-version: '22'
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install Dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci --ignore-scripts
|
||||
- name: Install backend native deps
|
||||
run: npm rebuild sqlite3 bcrypt --workspace=farma-clic-backend
|
||||
- name: Run Backend Tests
|
||||
run: npm test --workspace=farma-clic-backend -- --ci
|
||||
run: npm test --workspace=farma-clic-backend
|
||||
|
||||
test-frontend:
|
||||
name: Frontend Tests
|
||||
needs: detect-changes
|
||||
if: needs.detect-changes.outputs.frontend == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
node-version: '22'
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install Dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci --ignore-scripts
|
||||
- name: Run Frontend Tests
|
||||
run: npm test --workspace=farma-clic-frontend -- --run --reporter=basic
|
||||
|
||||
@@ -76,19 +72,16 @@ jobs:
|
||||
needs: detect-changes
|
||||
if: needs.detect-changes.outputs.frontend-mobile == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout Code
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
node-version: '22'
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install Dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci --ignore-scripts
|
||||
- name: Run Frontend Mobile Tests
|
||||
run: npm test --workspace=frontend-mobile -- --ci
|
||||
continue-on-error: true
|
||||
|
||||
@@ -3,6 +3,7 @@ dist/
|
||||
dev-dist/
|
||||
build/
|
||||
.turbo/
|
||||
.mimocode/
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
.env
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"pid":864463,"startedAt":1783550197179}
|
||||
{"pid":568607,"startedAt":1784046408782}
|
||||
@@ -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,7 @@ 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=
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { transformOFFProduct, searchBabyProducts, getBabyProductDetails } from '../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,12 @@ 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('../off-service.js', () => ({
|
||||
searchBabyProducts: jest.fn(async () => []),
|
||||
getBabyProductDetails: jest.fn(async () => null),
|
||||
}))
|
||||
|
||||
jest.unstable_mockModule('../farmacias-webhook-import.js', () => ({
|
||||
|
||||
@@ -1,9 +1,27 @@
|
||||
import axios from 'axios';
|
||||
import redisClient from './redis-client.js';
|
||||
import * as appMetrics from './src/metrics.js';
|
||||
|
||||
const CIMA_API_BASE_URL = 'https://cima.aemps.es/cima/rest';
|
||||
const CACHE_TTL = 3600;
|
||||
|
||||
/**
|
||||
* Wraps a CIMA API GET with duration + success/error metrics.
|
||||
*/
|
||||
async function trackedCimaGet(url, params) {
|
||||
const start = Date.now();
|
||||
try {
|
||||
const response = await axios.get(url, { params, timeout: 5000 });
|
||||
appMetrics.cimaRequestDuration.record(Date.now() - start);
|
||||
appMetrics.cimaRequestsTotal.add(1, { status: 'ok' });
|
||||
return response;
|
||||
} catch (err) {
|
||||
appMetrics.cimaRequestDuration.record(Date.now() - start);
|
||||
appMetrics.cimaRequestsTotal.add(1, { status: 'error' });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -69,23 +87,24 @@ export async function searchMedicines(query) {
|
||||
const cacheKey = `medicines:search:v3:${searchTerm}`;
|
||||
|
||||
try {
|
||||
appMetrics.medicineSearchesTotal.add(1);
|
||||
|
||||
// Intentar obtener del caché
|
||||
const cachedData = await redisClient.get(cacheKey);
|
||||
|
||||
if (cachedData) {
|
||||
console.log(`📦 Cache hit for: ${searchTerm}`);
|
||||
appMetrics.cacheHitsTotal.add(1);
|
||||
return JSON.parse(cachedData);
|
||||
}
|
||||
|
||||
appMetrics.cacheMissesTotal.add(1);
|
||||
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: apiSearchTerm
|
||||
},
|
||||
timeout: 5000
|
||||
const response = await trackedCimaGet(`${CIMA_API_BASE_URL}/medicamentos`, {
|
||||
nombre: apiSearchTerm,
|
||||
});
|
||||
|
||||
if (response.data && response.data.resultados) {
|
||||
@@ -143,20 +162,23 @@ export async function getMedicineDetails(nregistro) {
|
||||
const cacheKey = `medicine:${nregistro}`;
|
||||
|
||||
try {
|
||||
appMetrics.medicineSearchesTotal.add(1);
|
||||
|
||||
// Intentar obtener del caché
|
||||
const cachedData = await redisClient.get(cacheKey);
|
||||
|
||||
if (cachedData) {
|
||||
console.log(`📦 Cache hit for medicine: ${nregistro}`);
|
||||
appMetrics.cacheHitsTotal.add(1);
|
||||
return JSON.parse(cachedData);
|
||||
}
|
||||
|
||||
appMetrics.cacheMissesTotal.add(1);
|
||||
|
||||
// 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
|
||||
});
|
||||
const response = await trackedCimaGet(`${CIMA_API_BASE_URL}/medicamento/${nregistro}`);
|
||||
|
||||
if (response.data) {
|
||||
const med = response.data;
|
||||
@@ -185,9 +207,8 @@ export async function getMedicineDetails(nregistro) {
|
||||
}
|
||||
|
||||
// Fallback: buscar por nregistro usando el endpoint de búsqueda
|
||||
const searchResponse = await axios.get(`${CIMA_API_BASE_URL}/medicamentos`, {
|
||||
const searchResponse = await trackedCimaGet(`${CIMA_API_BASE_URL}/medicamentos`, {
|
||||
params: { nregistro },
|
||||
timeout: 5000
|
||||
});
|
||||
|
||||
if (searchResponse.data?.resultados?.length > 0) {
|
||||
@@ -231,9 +252,89 @@ 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:*')
|
||||
* @param {string} pattern - Patrón de claves a eliminar (ej: 'medicines:*')
|
||||
* @returns {Promise<number>} - Número de claves eliminadas
|
||||
*/
|
||||
export async function clearCache(pattern = 'medicines:*') {
|
||||
|
||||
@@ -3,4 +3,8 @@ export default {
|
||||
transform: {},
|
||||
moduleFileExtensions: ['js', 'json'],
|
||||
testMatch: ['**/__tests__/**/*.test.js'],
|
||||
testTimeout: 15000,
|
||||
openHandlesTimeout: 5000,
|
||||
// Run test files in parallel (not individual tests within a file)
|
||||
// workerIdleMemoryLimit: '512MB',
|
||||
}
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import axios from 'axios';
|
||||
import redisClient from './redis-client.js';
|
||||
|
||||
const OFF_API_BASE = 'https://world.openfoodfacts.org/api/v2';
|
||||
const CACHE_TTL = 3600;
|
||||
|
||||
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 response = await axios.get(`${OFF_API_BASE}/search`, {
|
||||
params: {
|
||||
categories_tags: 'baby-food',
|
||||
search_terms: searchTerm,
|
||||
json: true,
|
||||
fields: 'product_name,brands,image_url,nutriscore_grade,ingredients_text,nova_group,ecoscore_grade,categories_tags',
|
||||
page_size: 20,
|
||||
},
|
||||
timeout: 5000,
|
||||
});
|
||||
|
||||
if (response.data && response.data.products) {
|
||||
const products = response.data.products
|
||||
.map(transformOFFProduct)
|
||||
.filter(Boolean);
|
||||
|
||||
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
|
||||
}
|
||||
return products;
|
||||
}
|
||||
|
||||
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 response = await axios.get(`${OFF_API_BASE}/product/${barcode}.json`, {
|
||||
timeout: 5000,
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@
|
||||
"migrate": "node migrate.js",
|
||||
"reset-db": "bash reset-db.sh",
|
||||
"import-farmacias": "node import-farmacias.js",
|
||||
"test": "NODE_OPTIONS='--experimental-vm-modules' npx jest --forceExit"
|
||||
"test": "NODE_OPTIONS='--experimental-vm-modules' npx jest --ci --forceExit --forceExitTimeout=30000"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
@@ -21,10 +21,12 @@
|
||||
"@opentelemetry/api": "^1.9.0",
|
||||
"@opentelemetry/auto-instrumentations-node": "^0.52.0",
|
||||
"@opentelemetry/exporter-logs-otlp-grpc": "^0.55.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.55.0",
|
||||
"@opentelemetry/exporter-trace-otlp-grpc": "^0.55.0",
|
||||
"@opentelemetry/instrumentation-pino": "^0.45.0",
|
||||
"@opentelemetry/resources": "^1.28.0",
|
||||
"@opentelemetry/sdk-logs": "^0.55.0",
|
||||
"@opentelemetry/sdk-metrics": "^1.28.0",
|
||||
"@opentelemetry/sdk-node": "^0.55.0",
|
||||
"@opentelemetry/sdk-trace-base": "^1.28.0",
|
||||
"@opentelemetry/semantic-conventions": "^1.28.0",
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
import { createClient } from 'redis';
|
||||
import * as appMetrics from './src/metrics.js';
|
||||
|
||||
// Create Redis client
|
||||
const redisClient = createClient({
|
||||
socket: {
|
||||
host: process.env.REDIS_HOST || 'localhost',
|
||||
port: process.env.REDIS_PORT || 6379
|
||||
port: process.env.REDIS_PORT || 6379,
|
||||
reconnectStrategy: (retries) => {
|
||||
if (retries > 10) return new Error('Redis max retries reached');
|
||||
return Math.min(retries * 100, 3000);
|
||||
}
|
||||
},
|
||||
password: process.env.REDIS_PASSWORD || undefined
|
||||
});
|
||||
|
||||
// Error handler
|
||||
redisClient.on('error', (err) => {
|
||||
appMetrics.redisErrorsTotal.add(1);
|
||||
console.error('Redis Client Error:', err);
|
||||
});
|
||||
|
||||
@@ -19,7 +25,30 @@ redisClient.on('connect', () => {
|
||||
console.log('✅ Connected to Redis');
|
||||
});
|
||||
|
||||
// Connect to Redis
|
||||
await redisClient.connect();
|
||||
// Instrument get/setEx with command duration (used by the CIMA cache path).
|
||||
const origGet = redisClient.get.bind(redisClient);
|
||||
redisClient.get = async (...args) => {
|
||||
const start = performance.now();
|
||||
try {
|
||||
return await origGet(...args);
|
||||
} finally {
|
||||
appMetrics.redisCmdDuration.record(performance.now() - start);
|
||||
}
|
||||
};
|
||||
|
||||
const origSetEx = redisClient.setEx.bind(redisClient);
|
||||
redisClient.setEx = async (...args) => {
|
||||
const start = performance.now();
|
||||
try {
|
||||
return await origSetEx(...args);
|
||||
} finally {
|
||||
appMetrics.redisCmdDuration.record(performance.now() - start);
|
||||
}
|
||||
};
|
||||
|
||||
// Connect to Redis — skip in test (services are mocked) or when REDIS_URL is unset
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
await redisClient.connect();
|
||||
}
|
||||
|
||||
export default redisClient;
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
// OpenTelemetry SDK — must be imported first to instrument http, express, pg, etc.
|
||||
import './src/tracing.js';
|
||||
// Skipped in test to avoid gRPC connection attempts to a non-existent collector.
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
await import('./src/tracing.js');
|
||||
}
|
||||
|
||||
import express from 'express';
|
||||
import redisClient from './redis-client.js';
|
||||
import * as appMetrics from './src/metrics.js';
|
||||
import cors from 'cors';
|
||||
import sqlite3 from 'sqlite3';
|
||||
import { promisify } from 'util';
|
||||
@@ -17,9 +22,8 @@ import webpush from 'web-push';
|
||||
import pino from 'pino';
|
||||
import pinoHttp from 'pino-http';
|
||||
import multer from 'multer';
|
||||
import { createWorker } from 'tesseract.js';
|
||||
import { BarcodeDetector } from 'barcode-detector';
|
||||
import { searchMedicines, getMedicineDetails } from './cima-service.js';
|
||||
import { searchMedicines, getMedicineDetails, searchOTC } from './cima-service.js';
|
||||
import { searchBabyProducts, getBabyProductDetails } from './off-service.js';
|
||||
import { runFarmaciaWebhookImport, DEFAULT_FARMACIAS_WEBHOOK, importPharmaciesFromRows } from './farmacias-webhook-import.js';
|
||||
import { fetchPharmaciesExternal } from '../API/index.js';
|
||||
|
||||
@@ -56,6 +60,19 @@ app.use(cors({
|
||||
app.use(express.json({ limit: '10mb' }));
|
||||
app.use(pinoHttp({ logger }));
|
||||
|
||||
// Explicit HTTP request metrics (count by route + status class, duration).
|
||||
// Auto-instrumentation gives duration histograms but no discrete error count.
|
||||
app.use((req, res, next) => {
|
||||
const start = performance.now();
|
||||
res.on('finish', () => {
|
||||
const route = req.route?.path || req.path;
|
||||
const statusClass = `${Math.floor(res.statusCode / 100)}xx`;
|
||||
appMetrics.httpRequestsTotal.add(1, { route, status_class: statusClass });
|
||||
appMetrics.httpRequestDuration.record(performance.now() - start, { route });
|
||||
});
|
||||
next();
|
||||
});
|
||||
|
||||
const PG_URL = process.env.PG_URL;
|
||||
let pgPool = null;
|
||||
if (PG_URL) {
|
||||
@@ -88,19 +105,26 @@ if (process.env.NODE_ENV !== 'test') {
|
||||
// Configure session
|
||||
app.use(session(sessionConfig));
|
||||
|
||||
const searchLimiter = rateLimit({ windowMs: 60_000, max: 30, standardHeaders: true, legacyHeaders: false });
|
||||
const loginLimiter = rateLimit({ windowMs: 60_000, max: 5, standardHeaders: true, legacyHeaders: false });
|
||||
const registerLimiter = rateLimit({ windowMs: 60 * 60_000, max: 10, standardHeaders: true, legacyHeaders: false });
|
||||
const geocodeLimiter = rateLimit({ windowMs: 60_000, max: 10, standardHeaders: true, legacyHeaders: false });
|
||||
// Shared handler so every limiter emits a counter (route label) on rejection.
|
||||
const limitHandler = (route) => (req, res, next) => {
|
||||
appMetrics.rateLimitRejectedTotal.add(1, { route });
|
||||
res.status(429).json({ error: 'Too many requests, please try again later.' });
|
||||
};
|
||||
|
||||
const searchLimiter = rateLimit({ windowMs: 60_000, max: 30, standardHeaders: true, legacyHeaders: false, handler: limitHandler('search') });
|
||||
const loginLimiter = rateLimit({ windowMs: 60_000, max: 5, standardHeaders: true, legacyHeaders: false, handler: limitHandler('login') });
|
||||
const registerLimiter = rateLimit({ windowMs: 60 * 60_000, max: 10, standardHeaders: true, legacyHeaders: false, handler: limitHandler('register') });
|
||||
const geocodeLimiter = rateLimit({ windowMs: 60_000, max: 10, standardHeaders: true, legacyHeaders: false, handler: limitHandler('geocode') });
|
||||
|
||||
const VAPID_PUBLIC_KEY = process.env.VAPID_PUBLIC_KEY || '';
|
||||
const VAPID_PRIVATE_KEY = process.env.VAPID_PRIVATE_KEY || '';
|
||||
const VAPID_SUBJECT = process.env.VAPID_SUBJECT || 'mailto:admin@example.com';
|
||||
const EXPO_ACCESS_TOKEN = process.env.EXPO_ACCESS_TOKEN || '';
|
||||
const PUSH_ENABLED = Boolean(VAPID_PUBLIC_KEY && VAPID_PRIVATE_KEY);
|
||||
if (PUSH_ENABLED) {
|
||||
webpush.setVapidDetails(VAPID_SUBJECT, VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY);
|
||||
} else if (process.env.NODE_ENV !== 'test') {
|
||||
console.warn('[push] VAPID keys not configured — push notifications disabled');
|
||||
console.warn('[push] VAPID keys not configured — web push disabled');
|
||||
}
|
||||
|
||||
// Database setup
|
||||
@@ -127,27 +151,54 @@ function toPositional(sql) {
|
||||
}
|
||||
|
||||
async function userDbGet(sql, params = []) {
|
||||
if (pgPool) {
|
||||
const res = await pgPool.query(toPositional(sql), params);
|
||||
return res.rows[0] ?? null;
|
||||
const engine = pgPool ? 'pg' : 'sqlite';
|
||||
const start = performance.now();
|
||||
try {
|
||||
if (pgPool) {
|
||||
const res = await pgPool.query(toPositional(sql), params);
|
||||
return res.rows[0] ?? null;
|
||||
}
|
||||
return await dbGet(sql, params);
|
||||
} catch (err) {
|
||||
appMetrics.dbErrorsTotal.add(1, { engine });
|
||||
throw err;
|
||||
} finally {
|
||||
appMetrics.dbQueryDuration.record(performance.now() - start, { engine });
|
||||
}
|
||||
return dbGet(sql, params);
|
||||
}
|
||||
|
||||
async function userDbRun(sql, params = []) {
|
||||
if (pgPool) {
|
||||
const res = await pgPool.query(toPositional(sql), params);
|
||||
return { lastID: res.rows[0]?.id, changes: res.rowCount };
|
||||
const engine = pgPool ? 'pg' : 'sqlite';
|
||||
const start = performance.now();
|
||||
try {
|
||||
if (pgPool) {
|
||||
const res = await pgPool.query(toPositional(sql), params);
|
||||
return { lastID: res.rows[0]?.id, changes: res.rowCount };
|
||||
}
|
||||
return await dbRun(sql.replace(/\s+RETURNING\s+\w+\s*$/i, ''), params);
|
||||
} catch (err) {
|
||||
appMetrics.dbErrorsTotal.add(1, { engine });
|
||||
throw err;
|
||||
} finally {
|
||||
appMetrics.dbQueryDuration.record(performance.now() - start, { engine });
|
||||
}
|
||||
return dbRun(sql.replace(/\s+RETURNING\s+\w+\s*$/i, ''), params);
|
||||
}
|
||||
|
||||
async function userDbAll(sql, params = []) {
|
||||
if (pgPool) {
|
||||
const res = await pgPool.query(toPositional(sql), params);
|
||||
return res.rows;
|
||||
const engine = pgPool ? 'pg' : 'sqlite';
|
||||
const start = performance.now();
|
||||
try {
|
||||
if (pgPool) {
|
||||
const res = await pgPool.query(toPositional(sql), params);
|
||||
return res.rows;
|
||||
}
|
||||
return await dbAll(sql, params);
|
||||
} catch (err) {
|
||||
appMetrics.dbErrorsTotal.add(1, { engine });
|
||||
throw err;
|
||||
} finally {
|
||||
appMetrics.dbQueryDuration.record(performance.now() - start, { engine });
|
||||
}
|
||||
return dbAll(sql, params);
|
||||
}
|
||||
|
||||
// Accept opening_hours as either an object or a JSON string from the client
|
||||
@@ -313,6 +364,18 @@ async function initDatabase() {
|
||||
`);
|
||||
await pgPool.query(`CREATE INDEX IF NOT EXISTS idx_push_subs_pharm ON push_subscriptions_pharmacy(medicine_nregistro, pharmacy_id)`);
|
||||
await pgPool.query(`CREATE INDEX IF NOT EXISTS idx_push_subs_pharm_user ON push_subscriptions_pharmacy(user_id)`);
|
||||
|
||||
// Expo Push tokens (mobile)
|
||||
await pgPool.query(`
|
||||
CREATE TABLE IF NOT EXISTS expo_push_tokens (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
expo_token TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
UNIQUE(user_id, expo_token)
|
||||
)
|
||||
`);
|
||||
await pgPool.query(`CREATE INDEX IF NOT EXISTS idx_expo_push_tokens_user ON expo_push_tokens(user_id)`);
|
||||
} else {
|
||||
await dbRun(`
|
||||
CREATE TABLE IF NOT EXISTS push_subscriptions (
|
||||
@@ -342,6 +405,18 @@ async function initDatabase() {
|
||||
)
|
||||
`);
|
||||
await dbRun(`CREATE INDEX IF NOT EXISTS idx_push_subs_pharm ON push_subscriptions_pharmacy(medicine_nregistro, pharmacy_id)`);
|
||||
|
||||
// Expo Push tokens (mobile)
|
||||
await dbRun(`
|
||||
CREATE TABLE IF NOT EXISTS expo_push_tokens (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
expo_token TEXT NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(user_id, expo_token)
|
||||
)
|
||||
`);
|
||||
await dbRun(`CREATE INDEX IF NOT EXISTS idx_expo_push_tokens_user ON expo_push_tokens(user_id)`);
|
||||
}
|
||||
|
||||
if (!pgPool) {
|
||||
@@ -512,7 +587,8 @@ app.get('/api/medicines/:medicineId/pharmacies', async (req, res) => {
|
||||
try {
|
||||
const nregistro = req.params.medicineId; // Ahora es el nregistro de CIMA
|
||||
|
||||
const pharmacies = await userDbAll(`
|
||||
// First try to get pharmacies with specific medicine data
|
||||
let pharmacies = await userDbAll(`
|
||||
SELECT
|
||||
p.id,
|
||||
p.name,
|
||||
@@ -529,6 +605,24 @@ app.get('/api/medicines/:medicineId/pharmacies', async (req, res) => {
|
||||
ORDER BY p.name
|
||||
`, [nregistro]);
|
||||
|
||||
// If no specific links exist, return all pharmacies as potential sellers
|
||||
if (pharmacies.length === 0) {
|
||||
pharmacies = await userDbAll(`
|
||||
SELECT
|
||||
p.id,
|
||||
p.name,
|
||||
p.address,
|
||||
p.phone,
|
||||
p.latitude,
|
||||
p.longitude,
|
||||
p.opening_hours,
|
||||
NULL as price,
|
||||
0 as stock
|
||||
FROM pharmacies p
|
||||
ORDER BY p.name
|
||||
`);
|
||||
}
|
||||
|
||||
res.json(pharmacies);
|
||||
} catch (error) {
|
||||
console.error('Error fetching pharmacies:', error);
|
||||
@@ -554,6 +648,54 @@ app.get('/api/medicines/:medicineId', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// ========== UNIFIED PRODUCT SEARCH ==========
|
||||
|
||||
app.get('/api/products/search', searchLimiter, async (req, res) => {
|
||||
try {
|
||||
const { q } = req.query;
|
||||
if (!q || q.trim().length < 2) {
|
||||
return res.json({ results: [], total: 0 });
|
||||
}
|
||||
const searchTerm = q.trim();
|
||||
const [cimaResults, offResults] = await Promise.allSettled([
|
||||
searchOTC(searchTerm),
|
||||
searchBabyProducts(searchTerm)
|
||||
]);
|
||||
const cimaProducts = cimaResults.status === 'fulfilled' ? cimaResults.value : [];
|
||||
const offProducts = offResults.status === 'fulfilled' ? offResults.value : [];
|
||||
const allProducts = [...cimaProducts, ...offProducts]
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
res.json({
|
||||
results: allProducts,
|
||||
total: allProducts.length,
|
||||
sources: { cima: cimaProducts.length, openfoodfacts: offProducts.length }
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('[Products] Search error:', err);
|
||||
res.status(500).json({ error: 'Error searching products' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/products/:source/:id', async (req, res) => {
|
||||
try {
|
||||
const { source, id } = req.params;
|
||||
if (source === 'cima') {
|
||||
const product = await getMedicineDetails(id);
|
||||
if (!product) return res.status(404).json({ error: 'Product not found' });
|
||||
return res.json({ ...product, source: 'cima', category: 'otc' });
|
||||
}
|
||||
if (source === 'openfoodfacts') {
|
||||
const product = await getBabyProductDetails(id);
|
||||
if (!product) return res.status(404).json({ error: 'Product not found' });
|
||||
return res.json(product);
|
||||
}
|
||||
res.status(400).json({ error: 'Invalid source' });
|
||||
} catch (err) {
|
||||
console.error('[Products] Detail error:', err);
|
||||
res.status(500).json({ error: 'Error fetching product details' });
|
||||
}
|
||||
});
|
||||
|
||||
// ========== AUTHENTICATION MIDDLEWARE ==========
|
||||
|
||||
// Middleware to check if user is authenticated
|
||||
@@ -773,6 +915,7 @@ app.post('/api/tsi/ocr', upload.single('photo'), async (req, res) => {
|
||||
|
||||
console.log('[OCR] Processing image, size:', req.file.size, 'bytes');
|
||||
|
||||
const { createWorker } = await import('tesseract.js');
|
||||
const worker = await createWorker('spa+eng');
|
||||
const { data } = await worker.recognize(req.file.buffer);
|
||||
await worker.terminate();
|
||||
@@ -817,6 +960,7 @@ app.post('/api/auth/login', loginLimiter, async (req, res) => {
|
||||
);
|
||||
|
||||
if (!user) {
|
||||
appMetrics.loginFailureTotal.add(1);
|
||||
return res.status(401).json({ error: 'Invalid username or password' });
|
||||
}
|
||||
|
||||
@@ -824,6 +968,7 @@ app.post('/api/auth/login', loginLimiter, async (req, res) => {
|
||||
const isValidPassword = await bcrypt.compare(password, user.password_hash);
|
||||
|
||||
if (!isValidPassword) {
|
||||
appMetrics.loginFailureTotal.add(1);
|
||||
return res.status(401).json({ error: 'Invalid username or password' });
|
||||
}
|
||||
|
||||
@@ -832,6 +977,7 @@ app.post('/api/auth/login', loginLimiter, async (req, res) => {
|
||||
req.session.username = user.username;
|
||||
req.session.isAdmin = Boolean(user.is_admin);
|
||||
|
||||
appMetrics.loginSuccessTotal.add(1);
|
||||
res.json({
|
||||
message: 'Login successful',
|
||||
user: {
|
||||
@@ -1539,6 +1685,7 @@ app.post('/api/admin/pharmacies', requireAdmin, async (req, res) => {
|
||||
}
|
||||
|
||||
res.status(201).json(newPharmacy);
|
||||
appMetrics.pharmacyWriteTotal.add(1, { op: 'create' });
|
||||
} catch (error) {
|
||||
console.error('Error adding pharmacy:', error);
|
||||
if (error.message.includes('UNIQUE constraint')) {
|
||||
@@ -1576,6 +1723,7 @@ app.put('/api/admin/pharmacies/:id', requireAdmin, async (req, res) => {
|
||||
}
|
||||
|
||||
res.json(updatedPharmacy);
|
||||
appMetrics.pharmacyWriteTotal.add(1, { op: 'update' });
|
||||
} catch (error) {
|
||||
console.error('Error updating pharmacy:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
@@ -1594,6 +1742,7 @@ app.delete('/api/admin/pharmacies/:id', requireAdmin, async (req, res) => {
|
||||
await userDbRun('DELETE FROM pharmacies WHERE id = ?', [pharmacyId]);
|
||||
|
||||
res.json({ message: 'Pharmacy deleted successfully' });
|
||||
appMetrics.pharmacyWriteTotal.add(1, { op: 'delete' });
|
||||
} catch (error) {
|
||||
console.error('Error deleting pharmacy:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
@@ -1763,6 +1912,7 @@ app.post('/api/admin/pharmacy-medicines', requireAdmin, async (req, res) => {
|
||||
}
|
||||
|
||||
res.status(201).json(relationship);
|
||||
appMetrics.pharmacyMedicineLinkTotal.add(1, { op: 'create' });
|
||||
} catch (error) {
|
||||
console.error('Error adding medicine to pharmacy:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
@@ -1790,6 +1940,7 @@ app.put('/api/admin/pharmacy-medicines/:id', requireAdmin, async (req, res) => {
|
||||
}
|
||||
|
||||
res.json(updated);
|
||||
appMetrics.pharmacyMedicineLinkTotal.add(1, { op: 'update' });
|
||||
} catch (error) {
|
||||
console.error('Error updating pharmacy-medicine:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
@@ -1802,6 +1953,7 @@ app.delete('/api/admin/pharmacy-medicines/:id', requireAdmin, async (req, res) =
|
||||
const id = parseInt(req.params.id);
|
||||
await userDbRun('DELETE FROM pharmacy_medicines WHERE id = ?', [id]);
|
||||
res.json({ message: 'Medicine removed from pharmacy successfully' });
|
||||
appMetrics.pharmacyMedicineLinkTotal.add(1, { op: 'delete' });
|
||||
} catch (error) {
|
||||
console.error('Error deleting pharmacy-medicine:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
@@ -1900,6 +2052,101 @@ app.delete('/api/notifications/unsubscribe', requireAuth, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Expo Push tokens (mobile app)
|
||||
|
||||
app.post('/api/notifications/expo-register', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const { token, medicine_nregistro, medicine_name, pharmacy_id } = req.body || {};
|
||||
const userId = req.session.userId;
|
||||
if (!token) {
|
||||
return res.status(400).json({ error: 'expo token is required' });
|
||||
}
|
||||
|
||||
// Upsert the token for this user
|
||||
const existing = await userDbGet(
|
||||
'SELECT id FROM expo_push_tokens WHERE user_id = ? AND expo_token = ?',
|
||||
[userId, token]
|
||||
);
|
||||
if (!existing) {
|
||||
await userDbRun(
|
||||
'INSERT INTO expo_push_tokens (user_id, expo_token) VALUES (?, ?)',
|
||||
[userId, token]
|
||||
);
|
||||
}
|
||||
|
||||
// Also store the medicine subscription (reuse existing tables with expo prefix for endpoint)
|
||||
if (medicine_nregistro) {
|
||||
const expoEndpoint = `expo://${token}`;
|
||||
if (pharmacy_id) {
|
||||
const existingSub = await userDbGet(
|
||||
'SELECT id FROM push_subscriptions_pharmacy WHERE user_id = ? AND medicine_nregistro = ? AND pharmacy_id = ? AND endpoint = ?',
|
||||
[userId, medicine_nregistro, pharmacy_id, expoEndpoint]
|
||||
);
|
||||
if (!existingSub) {
|
||||
await userDbRun(
|
||||
'INSERT INTO push_subscriptions_pharmacy (user_id, medicine_nregistro, medicine_name, pharmacy_id, endpoint, p256dh, auth) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
[userId, medicine_nregistro, medicine_name || null, pharmacy_id, expoEndpoint, '', '']
|
||||
);
|
||||
}
|
||||
} else {
|
||||
const existingSub = await userDbGet(
|
||||
'SELECT id FROM push_subscriptions WHERE user_id = ? AND medicine_nregistro = ? AND endpoint = ?',
|
||||
[userId, medicine_nregistro, expoEndpoint]
|
||||
);
|
||||
if (!existingSub) {
|
||||
await userDbRun(
|
||||
'INSERT INTO push_subscriptions (user_id, medicine_nregistro, medicine_name, endpoint, p256dh, auth) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
[userId, medicine_nregistro, medicine_name || null, expoEndpoint, '', '']
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
res.status(201).json({ ok: true });
|
||||
} catch (error) {
|
||||
console.error('Error registering Expo push token:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/notifications/expo-unregister', requireAuth, async (req, res) => {
|
||||
try {
|
||||
const { medicine_nregistro, pharmacy_id } = req.body || {};
|
||||
const userId = req.session.userId;
|
||||
|
||||
// Get all expo tokens for this user to find the endpoints
|
||||
const tokens = await userDbAll(
|
||||
'SELECT expo_token FROM expo_push_tokens WHERE user_id = ?',
|
||||
[userId]
|
||||
);
|
||||
|
||||
for (const t of tokens || []) {
|
||||
const expoEndpoint = `expo://${t.expo_token}`;
|
||||
if (pharmacy_id && medicine_nregistro) {
|
||||
await userDbRun(
|
||||
'DELETE FROM push_subscriptions_pharmacy WHERE user_id = ? AND medicine_nregistro = ? AND pharmacy_id = ? AND endpoint = ?',
|
||||
[userId, medicine_nregistro, pharmacy_id, expoEndpoint]
|
||||
);
|
||||
} else if (medicine_nregistro) {
|
||||
await userDbRun(
|
||||
'DELETE FROM push_subscriptions WHERE user_id = ? AND medicine_nregistro = ? AND endpoint = ?',
|
||||
[userId, medicine_nregistro, expoEndpoint]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// If no medicine specified, remove the token entirely
|
||||
if (!medicine_nregistro) {
|
||||
await userDbRun('DELETE FROM expo_push_tokens WHERE user_id = ?', [userId]);
|
||||
}
|
||||
|
||||
res.status(204).end();
|
||||
} catch (error) {
|
||||
console.error('Error unregistering Expo push token:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// List the current user's saved notifications across all their devices
|
||||
app.get('/api/notifications/mine', requireAuth, async (req, res) => {
|
||||
try {
|
||||
@@ -1960,7 +2207,7 @@ app.delete('/api/notifications/mine', requireAuth, async (req, res) => {
|
||||
});
|
||||
|
||||
async function sendPushForMedicine({ medicine_nregistro, medicine_name, pharmacy }) {
|
||||
if (!PUSH_ENABLED) return { sent: 0, failed: 0, pruned: 0 };
|
||||
if (!PUSH_ENABLED && !EXPO_ACCESS_TOKEN) return { sent: 0, failed: 0, pruned: 0 };
|
||||
|
||||
const globalSubs = await userDbAll(
|
||||
'SELECT id, endpoint, p256dh, auth FROM push_subscriptions WHERE medicine_nregistro = ?',
|
||||
@@ -1971,7 +2218,7 @@ async function sendPushForMedicine({ medicine_nregistro, medicine_name, pharmacy
|
||||
[medicine_nregistro, pharmacy.id]
|
||||
) : [];
|
||||
|
||||
// Deduplicate by endpoint; pharmacy-specific overrides global so one notification per browser
|
||||
// Deduplicate by endpoint; pharmacy-specific overrides global so one notification per device
|
||||
const endpointMap = new Map();
|
||||
for (const sub of (globalSubs || [])) endpointMap.set(sub.endpoint, { ...sub, _pharmSub: false });
|
||||
for (const sub of (pharmacySubs || [])) endpointMap.set(sub.endpoint, { ...sub, _pharmSub: true });
|
||||
@@ -1979,47 +2226,162 @@ async function sendPushForMedicine({ medicine_nregistro, medicine_name, pharmacy
|
||||
|
||||
if (subs.length === 0) return { sent: 0, failed: 0, pruned: 0 };
|
||||
|
||||
const payload = JSON.stringify({
|
||||
title: 'Medicine available',
|
||||
body: `${medicine_name || medicine_nregistro} is now available at ${pharmacy?.name || 'a pharmacy near you'}`,
|
||||
url: `/?nregistro=${encodeURIComponent(medicine_nregistro)}`,
|
||||
medicine_nregistro,
|
||||
medicine_name: medicine_name || null,
|
||||
pharmacy_id: pharmacy?.id ?? null,
|
||||
pharmacy_name: pharmacy?.name ?? null,
|
||||
});
|
||||
// Split into web push (VAPID) and Expo push (mobile)
|
||||
const webSubs = [];
|
||||
const expoTokens = [];
|
||||
for (const sub of subs) {
|
||||
if (sub.endpoint?.startsWith('expo://')) {
|
||||
const token = sub.endpoint.replace('expo://', '');
|
||||
if (!expoTokens.includes(token)) expoTokens.push(token);
|
||||
} else {
|
||||
webSubs.push(sub);
|
||||
}
|
||||
}
|
||||
|
||||
const title = 'Medicamento disponible';
|
||||
const body = `${medicine_name || medicine_nregistro} está disponible en ${pharmacy?.name || 'una farmacia cercana'}`;
|
||||
const url = `/?nregistro=${encodeURIComponent(medicine_nregistro)}`;
|
||||
|
||||
let sent = 0;
|
||||
let failed = 0;
|
||||
let pruned = 0;
|
||||
|
||||
await Promise.all(subs.map(async (sub) => {
|
||||
try {
|
||||
await webpush.sendNotification(
|
||||
{ endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth } },
|
||||
payload
|
||||
);
|
||||
sent++;
|
||||
} catch (err) {
|
||||
failed++;
|
||||
const status = err?.statusCode;
|
||||
if (status === 404 || status === 410) {
|
||||
try {
|
||||
const deleteQuery = sub._pharmSub
|
||||
? 'DELETE FROM push_subscriptions_pharmacy WHERE id = ?'
|
||||
: 'DELETE FROM push_subscriptions WHERE id = ?';
|
||||
await userDbRun(deleteQuery, [sub.id]);
|
||||
pruned++;
|
||||
} catch {}
|
||||
} else {
|
||||
console.error('[push] send failed:', status, err?.body || err?.message);
|
||||
// Web Push via VAPID
|
||||
if (PUSH_ENABLED && webSubs.length > 0) {
|
||||
const payload = JSON.stringify({
|
||||
title,
|
||||
body,
|
||||
url,
|
||||
medicine_nregistro,
|
||||
medicine_name: medicine_name || null,
|
||||
pharmacy_id: pharmacy?.id ?? null,
|
||||
pharmacy_name: pharmacy?.name ?? null,
|
||||
});
|
||||
|
||||
await Promise.all(webSubs.map(async (sub) => {
|
||||
try {
|
||||
await webpush.sendNotification(
|
||||
{ endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth } },
|
||||
payload
|
||||
);
|
||||
sent++;
|
||||
appMetrics.pushSentTotal.add(1, { channel: 'web' });
|
||||
} catch (err) {
|
||||
failed++;
|
||||
appMetrics.pushFailedTotal.add(1, { channel: 'web' });
|
||||
const status = err?.statusCode;
|
||||
if (status === 404 || status === 410) {
|
||||
try {
|
||||
const deleteQuery = sub._pharmSub
|
||||
? 'DELETE FROM push_subscriptions_pharmacy WHERE id = ?'
|
||||
: 'DELETE FROM push_subscriptions WHERE id = ?';
|
||||
await userDbRun(deleteQuery, [sub.id]);
|
||||
pruned++;
|
||||
} catch {}
|
||||
} else {
|
||||
console.error('[push] web send failed:', status, err?.body || err?.message);
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
// Expo Push (mobile)
|
||||
if (EXPO_ACCESS_TOKEN && expoTokens.length > 0) {
|
||||
const chunks = [];
|
||||
for (let i = 0; i < expoTokens.length; i += 100) {
|
||||
chunks.push(expoTokens.slice(i, i + 100));
|
||||
}
|
||||
|
||||
for (const chunk of chunks) {
|
||||
const messages = chunk.map((token) => ({
|
||||
to: token,
|
||||
sound: 'default',
|
||||
title,
|
||||
body,
|
||||
data: {
|
||||
url,
|
||||
medicine_nregistro,
|
||||
medicine_name: medicine_name || null,
|
||||
pharmacy_id: pharmacy?.id ?? null,
|
||||
pharmacy_name: pharmacy?.name ?? null,
|
||||
},
|
||||
}));
|
||||
|
||||
try {
|
||||
const response = await fetch('https://exp.host/--/api/v2/push/send', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${EXPO_ACCESS_TOKEN}`,
|
||||
},
|
||||
body: JSON.stringify(messages),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const result = await response.json();
|
||||
// Handle individual ticket errors
|
||||
if (result.data) {
|
||||
for (const ticket of result.data) {
|
||||
if (ticket.status === 'ok') {
|
||||
sent++;
|
||||
appMetrics.pushSentTotal.add(1, { channel: 'expo' });
|
||||
} else {
|
||||
failed++;
|
||||
appMetrics.pushFailedTotal.add(1, { channel: 'expo' });
|
||||
// Prune invalid tokens
|
||||
if (ticket.message?.includes('InvalidCredentials') || ticket.message?.includes('DeviceNotRegistered')) {
|
||||
const expoEndpoint = `expo://${ticket.id || ''}`;
|
||||
try {
|
||||
await userDbRun('DELETE FROM push_subscriptions WHERE endpoint = ?', [expoEndpoint]);
|
||||
await userDbRun('DELETE FROM push_subscriptions_pharmacy WHERE endpoint = ?', [expoEndpoint]);
|
||||
await userDbRun('DELETE FROM expo_push_tokens WHERE expo_token = ?', [ticket.id || '']);
|
||||
pruned++;
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
sent += chunk.length;
|
||||
appMetrics.pushSentTotal.add(chunk.length, { channel: 'expo' });
|
||||
}
|
||||
} else {
|
||||
failed += chunk.length;
|
||||
appMetrics.pushFailedTotal.add(chunk.length, { channel: 'expo' });
|
||||
console.error('[push] expo send failed:', response.status);
|
||||
}
|
||||
} catch (err) {
|
||||
failed += chunk.length;
|
||||
appMetrics.pushFailedTotal.add(chunk.length, { channel: 'expo' });
|
||||
console.error('[push] expo send error:', err.message);
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
return { sent, failed, pruned };
|
||||
}
|
||||
|
||||
// --- Health & readiness probes --------------------------------------------
|
||||
// /healthz: liveness (process is up). /readyz: dependencies reachable.
|
||||
app.get('/healthz', (_req, res) => {
|
||||
res.json({ status: 'ok', uptime: process.uptime() });
|
||||
});
|
||||
|
||||
app.get('/readyz', async (_req, res) => {
|
||||
const checks = { redis: 'ok', db: 'ok' };
|
||||
try {
|
||||
await redisClient.ping();
|
||||
} catch {
|
||||
checks.redis = 'fail';
|
||||
}
|
||||
try {
|
||||
await userDbGet('SELECT 1');
|
||||
} catch {
|
||||
checks.db = 'fail';
|
||||
}
|
||||
const ready = checks.redis === 'ok' && checks.db === 'ok';
|
||||
res.status(ready ? 200 : 503).json({ status: ready ? 'ok' : 'degraded', checks });
|
||||
});
|
||||
|
||||
export { app, initDatabase, db };
|
||||
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// OpenTelemetry metrics for the FarmaFinder backend.
|
||||
//
|
||||
// Uses the global MeterProvider configured in `tracing.js` (imported first in
|
||||
// server.js). Metrics flow OTLP → Alloy → Prometheus remote_write, exactly like
|
||||
// the tracing pipeline, so no extra Prometheus scrape job is required.
|
||||
import { metrics } from '@opentelemetry/api';
|
||||
|
||||
const meter = metrics.getMeter('farmafinder-backend', '1.0.0');
|
||||
|
||||
// --- Heartbeat -------------------------------------------------------------
|
||||
// Emitted continuously so we can alert on "backend not sending telemetry"
|
||||
// (remote_write has no `up` metric).
|
||||
export const heartbeatTotal = meter.createCounter('app_heartbeat_total', {
|
||||
description: 'Heartbeat ticks from the backend process (liveness signal).',
|
||||
});
|
||||
|
||||
// --- Medicine search / CIMA upstream --------------------------------------
|
||||
export const medicineSearchesTotal = meter.createCounter('medicine_searches_total', {
|
||||
description: 'Total medicine searches handled (cache or upstream).',
|
||||
});
|
||||
|
||||
export const cimaRequestsTotal = meter.createCounter('cima_requests_total', {
|
||||
description: 'Total upstream CIMA API requests.',
|
||||
});
|
||||
|
||||
export const cimaRequestDuration = meter.createHistogram('cima_request_duration_ms', {
|
||||
description: 'Duration of upstream CIMA API requests.',
|
||||
unit: 'ms',
|
||||
});
|
||||
|
||||
export const cacheHitsTotal = meter.createCounter('cache_hits_total', {
|
||||
description: 'Total Redis cache hits.',
|
||||
});
|
||||
|
||||
export const cacheMissesTotal = meter.createCounter('cache_misses_total', {
|
||||
description: 'Total Redis cache misses (fell through to upstream).',
|
||||
});
|
||||
|
||||
// --- Auth ------------------------------------------------------------------
|
||||
export const loginSuccessTotal = meter.createCounter('login_success_total', {
|
||||
description: 'Successful login attempts.',
|
||||
});
|
||||
|
||||
export const loginFailureTotal = meter.createCounter('login_failure_total', {
|
||||
description: 'Failed login attempts.',
|
||||
});
|
||||
|
||||
export const rateLimitRejectedTotal = meter.createCounter('rate_limit_rejected_total', {
|
||||
description: 'Requests rejected by a rate limiter.',
|
||||
});
|
||||
|
||||
// --- Admin operations ------------------------------------------------------
|
||||
export const pharmacyWriteTotal = meter.createCounter('pharmacy_write_total', {
|
||||
description: 'Admin pharmacy write operations.',
|
||||
});
|
||||
|
||||
export const pharmacyMedicineLinkTotal = meter.createCounter('pharmacy_medicine_link_total', {
|
||||
description: 'Pharmacy-medicine link operations.',
|
||||
});
|
||||
|
||||
// --- Push notifications ----------------------------------------------------
|
||||
export const pushSentTotal = meter.createCounter('push_sent_total', {
|
||||
description: 'Push notifications successfully sent.',
|
||||
});
|
||||
|
||||
export const pushFailedTotal = meter.createCounter('push_failed_total', {
|
||||
description: 'Push notifications that failed to send.',
|
||||
});
|
||||
|
||||
// --- Datastores ------------------------------------------------------------
|
||||
export const dbQueryDuration = meter.createHistogram('db_query_duration_ms', {
|
||||
description: 'Duration of user DB queries.',
|
||||
unit: 'ms',
|
||||
});
|
||||
|
||||
export const dbErrorsTotal = meter.createCounter('db_errors_total', {
|
||||
description: 'User DB query errors.',
|
||||
});
|
||||
|
||||
export const redisErrorsTotal = meter.createCounter('redis_errors_total', {
|
||||
description: 'Redis client errors.',
|
||||
});
|
||||
|
||||
export const redisCmdDuration = meter.createHistogram('redis_cmd_duration_ms', {
|
||||
description: 'Duration of Redis commands.',
|
||||
unit: 'ms',
|
||||
});
|
||||
|
||||
// --- HTTP (explicit, so we get status class + per-route breakdowns) --------
|
||||
// OTel's http auto-instrumentation records duration but not a discrete
|
||||
// error count, so we track requests explicitly for error-rate alerting.
|
||||
export const httpRequestsTotal = meter.createCounter('http_requests_total', {
|
||||
description: 'Total HTTP requests, labelled by route and status class.',
|
||||
});
|
||||
|
||||
export const httpRequestDuration = meter.createHistogram('http_request_duration_ms', {
|
||||
description: 'HTTP request duration.',
|
||||
unit: 'ms',
|
||||
});
|
||||
|
||||
// --- Heartbeat loop (guarded against --watch duplicate intervals) ----------
|
||||
const HEARTBEAT_INTERVAL_MS = 30_000;
|
||||
if (process.env.NODE_ENV !== 'test' && !globalThis.__farmafinderHeartbeat) {
|
||||
globalThis.__farmafinderHeartbeat = setInterval(() => {
|
||||
heartbeatTotal.add(1);
|
||||
}, HEARTBEAT_INTERVAL_MS);
|
||||
globalThis.__farmafinderHeartbeat?.unref?.();
|
||||
}
|
||||
@@ -9,28 +9,40 @@
|
||||
// routed to Tempo.
|
||||
|
||||
import { NodeSDK } from '@opentelemetry/sdk-node';
|
||||
import { PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';
|
||||
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
|
||||
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';
|
||||
import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-grpc';
|
||||
import * as resources from '@opentelemetry/resources';
|
||||
import { ATTR_SERVICE_NAME, ATTR_SERVICE_NAMESPACE } from '@opentelemetry/semantic-conventions';
|
||||
import { PinoInstrumentation } from '@opentelemetry/instrumentation-pino';
|
||||
|
||||
const serviceName = process.env.OTEL_SERVICE_NAME || 'farmaclic-backend';
|
||||
const otlpEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4317';
|
||||
|
||||
// Use plain string attribute keys (not the semantic-conventions named exports)
|
||||
// so we don't depend on a specific @opentelemetry/semantic-conventions version.
|
||||
const resource = typeof resources.resourceFromAttributes === 'function'
|
||||
? resources.resourceFromAttributes({
|
||||
[ATTR_SERVICE_NAME]: serviceName,
|
||||
[ATTR_SERVICE_NAMESPACE]: 'farmaclic',
|
||||
'service.name': serviceName,
|
||||
'service.namespace': 'farmaclic',
|
||||
})
|
||||
: new resources.Resource({
|
||||
[ATTR_SERVICE_NAME]: serviceName,
|
||||
[ATTR_SERVICE_NAMESPACE]: 'farmaclic',
|
||||
'service.name': serviceName,
|
||||
'service.namespace': 'farmaclic',
|
||||
});
|
||||
|
||||
// Metrics → OTLP → Alloy → Prometheus remote_write. The PeriodicExportingMetricReader
|
||||
// makes the auto-instrumentations (http/express/redis) emit request duration/error
|
||||
// metrics with no extra code, on top of the custom business metrics in src/metrics.js.
|
||||
const metricReader = new PeriodicExportingMetricReader({
|
||||
exportIntervalMillis: 15_000,
|
||||
exporter: new OTLPMetricExporter({ url: otlpEndpoint }),
|
||||
});
|
||||
|
||||
const sdk = new NodeSDK({
|
||||
resource,
|
||||
traceExporter: new OTLPTraceExporter({ url: otlpEndpoint }),
|
||||
metricReader,
|
||||
instrumentations: [
|
||||
getNodeAutoInstrumentations({
|
||||
// Disable fs by default — it is noisy and rarely useful.
|
||||
|
||||
@@ -6,3 +6,8 @@ EXPO_PUBLIC_API_URL=http://localhost:3001/api
|
||||
|
||||
# For production builds, update this to:
|
||||
# EXPO_PUBLIC_API_URL=https://api.yourdomain.com/api
|
||||
|
||||
# Grafana Alloy OTLP/HTTP endpoint for Faro RUM (must be reachable from the
|
||||
# device — use a LAN IP / public hostname, NOT localhost).
|
||||
# Open router :4318 → srv84-macos:4318, or proxy /faro via Nginx Proxy Manager.
|
||||
EXPO_PUBLIC_FARO_URL=http://grafana.hacecalor.net:4318
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"version": "1.0.0",
|
||||
"orientation": "portrait",
|
||||
"icon": "./assets/icon.png",
|
||||
"userInterfaceStyle": "light",
|
||||
"userInterfaceStyle": "automatic",
|
||||
"newArchEnabled": true,
|
||||
"splash": {
|
||||
"image": "./assets/splash.png",
|
||||
@@ -25,12 +25,29 @@
|
||||
"backgroundColor": "#007AFF"
|
||||
},
|
||||
"package": "com.farmafinder.app",
|
||||
"googleServicesFile": "./google-services.json"
|
||||
"googleServicesFile": "./google-services.json",
|
||||
"config": {
|
||||
"googleMaps": {
|
||||
"apiKey": ""
|
||||
}
|
||||
}
|
||||
},
|
||||
"plugins": [
|
||||
"expo-router",
|
||||
["expo-camera", {"cameraPermission": "Allow FarmaFinder to access your camera for scanning barcodes"}],
|
||||
["expo-notifications", {"icon": "./assets/notification-icon.png", "color": "#007AFF"}]
|
||||
["expo-notifications", {"icon": "./assets/notification-icon.png", "color": "#007AFF"}],
|
||||
[
|
||||
"react-native-maps",
|
||||
{
|
||||
"locationAlwaysAndWhenInUsePermission": "Allow FarmaFinder to use your location to find nearby pharmacies."
|
||||
}
|
||||
],
|
||||
[
|
||||
"expo-location",
|
||||
{
|
||||
"locationAlwaysAndWhenInUsePermission": "Allow FarmaFinder to use your location to find nearby pharmacies."
|
||||
}
|
||||
]
|
||||
],
|
||||
"scheme": "farmafinder",
|
||||
"extra": {
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import { Tabs } from 'expo-router';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { View, StyleSheet, Platform, useWindowDimensions } from 'react-native';
|
||||
import { View, StyleSheet, useWindowDimensions } from 'react-native';
|
||||
import { useSafeAreaInsets } from 'react-native-safe-area-context';
|
||||
import { colors, shadows } from '../../constants/theme';
|
||||
import { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { shadows } from '../../constants/theme';
|
||||
|
||||
const TABLET_MIN_WIDTH = 768;
|
||||
|
||||
function ScanIcon({ color, size }: { color: string; size: number }) {
|
||||
// Standard Android navigation bar heights in dp
|
||||
const ANDROID_NAV_BAR_HEIGHT = 48;
|
||||
|
||||
function ScanIcon({ size }: { size: number }) {
|
||||
return (
|
||||
<View style={styles.fabContainer}>
|
||||
<View style={[styles.fab, shadows.scanButton]}>
|
||||
@@ -20,7 +24,9 @@ export default function TabLayout() {
|
||||
const insets = useSafeAreaInsets();
|
||||
const { width } = useWindowDimensions();
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
const bottomPadding = Platform.OS === 'ios' ? insets.bottom : 8;
|
||||
const { colors } = useThemeContext();
|
||||
// Use safe area insets if available, otherwise use standard Android nav bar height
|
||||
const bottomPadding = insets.bottom > 0 ? insets.bottom : ANDROID_NAV_BAR_HEIGHT;
|
||||
|
||||
return (
|
||||
<Tabs
|
||||
@@ -28,24 +34,33 @@ export default function TabLayout() {
|
||||
tabBarActiveTintColor: colors.primary,
|
||||
tabBarInactiveTintColor: colors.textSecondary,
|
||||
tabBarStyle: {
|
||||
...(isTablet ? styles.tabBarTablet : styles.tabBar),
|
||||
...(isTablet ? styles.tabBarTablet : {}),
|
||||
backgroundColor: colors.card,
|
||||
borderTopColor: colors.border,
|
||||
paddingTop: isTablet ? 10 : 8,
|
||||
height: (isTablet ? 64 : 60) + bottomPadding,
|
||||
paddingBottom: bottomPadding,
|
||||
...(isTablet ? { paddingHorizontal: 24 } : {}),
|
||||
},
|
||||
tabBarLabelStyle: {
|
||||
...styles.tabBarLabel,
|
||||
...(isTablet ? styles.tabBarLabelTablet : {}),
|
||||
fontSize: isTablet ? 13 : 11,
|
||||
fontWeight: '500',
|
||||
},
|
||||
headerStyle: {
|
||||
backgroundColor: colors.card,
|
||||
},
|
||||
headerStyle: styles.header,
|
||||
headerTintColor: colors.primary,
|
||||
headerTitleStyle: {
|
||||
...styles.headerTitle,
|
||||
...(isTablet ? styles.headerTitleTablet : {}),
|
||||
color: colors.text,
|
||||
fontWeight: '600',
|
||||
fontSize: isTablet ? 20 : 17,
|
||||
},
|
||||
sceneContainerStyle: { backgroundColor: 'transparent' },
|
||||
sceneStyle: { backgroundColor: 'transparent' },
|
||||
}}
|
||||
>
|
||||
<Tabs.Screen
|
||||
name="home"
|
||||
name="index"
|
||||
options={{
|
||||
title: 'Inicio',
|
||||
tabBarIcon: ({ color, size }) => (
|
||||
@@ -54,7 +69,7 @@ export default function TabLayout() {
|
||||
}}
|
||||
/>
|
||||
<Tabs.Screen
|
||||
name="index"
|
||||
name="search"
|
||||
options={{
|
||||
title: 'Buscar',
|
||||
tabBarIcon: ({ color, size }) => (
|
||||
@@ -99,40 +114,6 @@ export default function TabLayout() {
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
tabBar: {
|
||||
backgroundColor: colors.card,
|
||||
borderTopColor: colors.border,
|
||||
paddingTop: 8,
|
||||
},
|
||||
tabBarTablet: {
|
||||
backgroundColor: colors.card,
|
||||
borderTopColor: colors.border,
|
||||
paddingTop: 10,
|
||||
paddingHorizontal: 24,
|
||||
},
|
||||
tabBarLabel: {
|
||||
fontSize: 11,
|
||||
fontWeight: '500',
|
||||
},
|
||||
tabBarLabelTablet: {
|
||||
fontSize: 13,
|
||||
},
|
||||
header: {
|
||||
backgroundColor: colors.card,
|
||||
shadowColor: '#000',
|
||||
shadowOffset: { width: 0, height: 1 },
|
||||
shadowOpacity: 0.05,
|
||||
shadowRadius: 4,
|
||||
elevation: 1,
|
||||
},
|
||||
headerTitle: {
|
||||
color: colors.text,
|
||||
fontWeight: '600',
|
||||
fontSize: 17,
|
||||
},
|
||||
headerTitleTablet: {
|
||||
fontSize: 20,
|
||||
},
|
||||
fabContainer: {
|
||||
position: 'absolute',
|
||||
top: -16,
|
||||
@@ -142,7 +123,7 @@ const styles = StyleSheet.create({
|
||||
width: 52,
|
||||
height: 52,
|
||||
borderRadius: 26,
|
||||
backgroundColor: colors.scanButton,
|
||||
backgroundColor: '#2b5bb5',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Alert, useWindowDimensions } from 'react-native';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { colors, spacing, borderRadius, shadows } from '../../constants/theme';
|
||||
import { 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';
|
||||
|
||||
@@ -19,16 +22,23 @@ interface NotificationItem {
|
||||
}
|
||||
|
||||
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(() => {
|
||||
loadNotifications();
|
||||
}, []);
|
||||
if (!authLoading && isAuthenticated) {
|
||||
loadNotifications();
|
||||
} else if (!authLoading && !isAuthenticated) {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [authLoading, isAuthenticated]);
|
||||
|
||||
async function loadNotifications() {
|
||||
setIsLoading(true);
|
||||
@@ -81,33 +91,33 @@ export default function AlertsScreen() {
|
||||
function renderItem({ item }: { item: NotificationItem }) {
|
||||
const key = `${item.scope}:${item.id}`;
|
||||
return (
|
||||
<View style={styles.item}>
|
||||
<View style={[styles.item, { backgroundColor: colors.card }]}>
|
||||
<View style={styles.itemContent}>
|
||||
<Text style={styles.itemName} numberOfLines={2}>
|
||||
<Text style={[styles.itemName, { color: colors.text }]} numberOfLines={2}>
|
||||
{item.medicine_name || item.medicine_nregistro}
|
||||
</Text>
|
||||
<View style={styles.itemMeta}>
|
||||
<View style={styles.chip}>
|
||||
<View style={[styles.chip, { backgroundColor: colors.primaryContainer }]}>
|
||||
<Ionicons
|
||||
name={item.scope === 'pharmacy' ? 'medical' : 'globe'}
|
||||
size={12}
|
||||
color={colors.primary}
|
||||
/>
|
||||
<Text style={styles.chipText}>
|
||||
<Text style={[styles.chipText, { color: colors.onPrimaryContainer }]}>
|
||||
{item.scope === 'pharmacy'
|
||||
? item.pharmacy_name || `Farmacia #${item.pharmacy_id}`
|
||||
: 'Cualquier farmacia'}
|
||||
</Text>
|
||||
</View>
|
||||
{item.pharmacy_address && (
|
||||
<Text style={styles.itemAddress} numberOfLines={1}>
|
||||
<Text style={[styles.itemAddress, { color: colors.textSecondary }]} numberOfLines={1}>
|
||||
{item.pharmacy_address}
|
||||
</Text>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
<TouchableOpacity
|
||||
style={styles.deleteButton}
|
||||
style={[styles.deleteButton, { backgroundColor: colors.dangerContainer }]}
|
||||
onPress={() => handleDelete(item)}
|
||||
disabled={deletingId === key}
|
||||
>
|
||||
@@ -121,24 +131,42 @@ export default function AlertsScreen() {
|
||||
);
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
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}>
|
||||
<View style={[styles.container, { backgroundColor: colors.background }]}>
|
||||
<View style={[styles.header, isTablet && styles.headerTablet]}>
|
||||
<Text style={[styles.title, isTablet && styles.titleTablet]}>Notificaciones Guardadas</Text>
|
||||
<Text style={[styles.subtitle, isTablet && styles.subtitleTablet]}>
|
||||
<Text style={[styles.title, isTablet && styles.titleTablet, { color: colors.text }]}>Notificaciones Guardadas</Text>
|
||||
<Text style={[styles.subtitle, isTablet && styles.subtitleTablet, { color: colors.textSecondary }]}>
|
||||
Recibe avisos cuando medicamentos sin stock se repongan
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
{error && (
|
||||
<View style={[styles.errorContainer, isTablet && styles.errorContainerTablet]}>
|
||||
<Text style={styles.errorText}>{error}</Text>
|
||||
<View style={[styles.errorContainer, isTablet && styles.errorContainerTablet, { backgroundColor: colors.dangerContainer }]}>
|
||||
<Text style={[styles.errorText, { color: colors.danger }]}>{error}</Text>
|
||||
<TouchableOpacity onPress={loadNotifications} style={styles.retryButton}>
|
||||
<Text style={styles.retryText}>Reintentar</Text>
|
||||
<Text style={[styles.retryText, { color: colors.primary }]}>Reintentar</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
)}
|
||||
@@ -146,8 +174,8 @@ export default function AlertsScreen() {
|
||||
{!error && items.length === 0 && (
|
||||
<View style={styles.emptyContainer}>
|
||||
<Ionicons name="notifications-off-outline" size={isTablet ? 80 : 64} color={colors.border} />
|
||||
<Text style={[styles.emptyTitle, isTablet && styles.emptyTitleTablet]}>Sin notificaciones</Text>
|
||||
<Text style={[styles.emptyText, isTablet && styles.emptyTextTablet]}>
|
||||
<Text style={[styles.emptyTitle, isTablet && styles.emptyTitleTablet, { color: colors.text }]}>Sin notificaciones</Text>
|
||||
<Text style={[styles.emptyText, isTablet && styles.emptyTextTablet, { color: colors.textSecondary }]}>
|
||||
Toca la campana en una farmacia sin stock para recibir notificaciones cuando se reponga.
|
||||
</Text>
|
||||
</View>
|
||||
@@ -169,7 +197,32 @@ export default function AlertsScreen() {
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: colors.background,
|
||||
},
|
||||
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,
|
||||
@@ -184,14 +237,12 @@ const styles = StyleSheet.create({
|
||||
title: {
|
||||
fontSize: 22,
|
||||
fontWeight: 'bold',
|
||||
color: colors.text,
|
||||
},
|
||||
titleTablet: {
|
||||
fontSize: 28,
|
||||
},
|
||||
subtitle: {
|
||||
fontSize: 14,
|
||||
color: colors.textSecondary,
|
||||
marginTop: spacing.xs,
|
||||
lineHeight: 20,
|
||||
},
|
||||
@@ -212,7 +263,6 @@ const styles = StyleSheet.create({
|
||||
item: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.lg,
|
||||
padding: spacing.md,
|
||||
...shadows.card,
|
||||
@@ -224,7 +274,6 @@ const styles = StyleSheet.create({
|
||||
itemName: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: colors.text,
|
||||
lineHeight: 22,
|
||||
},
|
||||
itemMeta: {
|
||||
@@ -234,7 +283,6 @@ const styles = StyleSheet.create({
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.xs,
|
||||
backgroundColor: colors.primaryContainer,
|
||||
borderRadius: borderRadius.full,
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: 3,
|
||||
@@ -243,17 +291,14 @@ const styles = StyleSheet.create({
|
||||
chipText: {
|
||||
fontSize: 12,
|
||||
fontWeight: '600',
|
||||
color: colors.onPrimaryContainer,
|
||||
},
|
||||
itemAddress: {
|
||||
fontSize: 12,
|
||||
color: colors.textSecondary,
|
||||
},
|
||||
deleteButton: {
|
||||
width: 36,
|
||||
height: 36,
|
||||
borderRadius: 18,
|
||||
backgroundColor: colors.dangerContainer,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
marginLeft: spacing.sm,
|
||||
@@ -261,7 +306,6 @@ const styles = StyleSheet.create({
|
||||
errorContainer: {
|
||||
margin: spacing.lg,
|
||||
padding: spacing.md,
|
||||
backgroundColor: colors.dangerContainer,
|
||||
borderRadius: borderRadius.lg,
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
@@ -272,7 +316,6 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
errorText: {
|
||||
fontSize: 14,
|
||||
color: colors.danger,
|
||||
textAlign: 'center',
|
||||
},
|
||||
retryButton: {
|
||||
@@ -282,7 +325,6 @@ const styles = StyleSheet.create({
|
||||
retryText: {
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
color: colors.primary,
|
||||
},
|
||||
emptyContainer: {
|
||||
flex: 1,
|
||||
@@ -294,14 +336,12 @@ const styles = StyleSheet.create({
|
||||
emptyTitle: {
|
||||
fontSize: 18,
|
||||
fontWeight: '600',
|
||||
color: colors.text,
|
||||
},
|
||||
emptyTitleTablet: {
|
||||
fontSize: 24,
|
||||
},
|
||||
emptyText: {
|
||||
fontSize: 14,
|
||||
color: colors.textSecondary,
|
||||
textAlign: 'center',
|
||||
lineHeight: 20,
|
||||
},
|
||||
|
||||
@@ -1,166 +0,0 @@
|
||||
import React from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity, Image, useWindowDimensions } from 'react-native';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { colors, spacing, borderRadius, shadows } from '../../constants/theme';
|
||||
|
||||
const TABLET_MIN_WIDTH = 768;
|
||||
|
||||
export default function HomeScreen() {
|
||||
const router = useRouter();
|
||||
const { width } = useWindowDimensions();
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<View style={[styles.hero, isTablet && styles.heroTablet]}>
|
||||
<Image
|
||||
source={require('../../assets/farmaclic_logo.png')}
|
||||
style={[styles.logo, isTablet && styles.logoTablet]}
|
||||
resizeMode="contain"
|
||||
/>
|
||||
<Text style={[styles.brandName, isTablet && styles.brandNameTablet]}>FarmaClic</Text>
|
||||
<Text style={[styles.description, isTablet && styles.descriptionTablet]}>
|
||||
Encuentra tus medicamentos en farmacias cercanas
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<View style={[styles.cards, isTablet && styles.cardsTablet]}>
|
||||
<TouchableOpacity
|
||||
style={[styles.card, isTablet && styles.cardTablet]}
|
||||
activeOpacity={0.85}
|
||||
onPress={() => router.push('/(tabs)')}
|
||||
>
|
||||
<View style={[styles.cardIcon, styles.cardIconSearch]}>
|
||||
<Ionicons name="search" size={isTablet ? 28 : 24} color={colors.onPrimaryContainer} />
|
||||
</View>
|
||||
<View style={styles.cardContent}>
|
||||
<Text style={[styles.cardLabel, isTablet && styles.cardLabelTablet]}>Buscar Medicamento</Text>
|
||||
<Ionicons name="chevron-forward" size={20} color={colors.onPrimaryContainer} style={{ opacity: 0.7 }} />
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
|
||||
<TouchableOpacity
|
||||
style={[styles.card, styles.cardScan, isTablet && styles.cardTablet]}
|
||||
activeOpacity={0.85}
|
||||
onPress={() => router.push('/scanner')}
|
||||
>
|
||||
<View style={[styles.cardIcon, styles.cardIconScan]}>
|
||||
<Ionicons name="scan" size={isTablet ? 28 : 24} color="#ffffff" />
|
||||
</View>
|
||||
<View style={styles.cardContent}>
|
||||
<Text style={[styles.cardLabel, styles.cardLabelScan, isTablet && styles.cardLabelTablet]}>Escanear TSI</Text>
|
||||
<Ionicons name="chevron-forward" size={20} color="#ffffff" style={{ opacity: 0.7 }} />
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: colors.background,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
paddingHorizontal: spacing.lg,
|
||||
gap: spacing.lg,
|
||||
},
|
||||
hero: {
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
heroTablet: {
|
||||
marginBottom: spacing.xl,
|
||||
},
|
||||
logo: {
|
||||
width: 120,
|
||||
height: 120,
|
||||
marginBottom: spacing.xs,
|
||||
},
|
||||
logoTablet: {
|
||||
width: 160,
|
||||
height: 160,
|
||||
},
|
||||
brandName: {
|
||||
fontSize: 28,
|
||||
fontWeight: 'bold',
|
||||
color: colors.text,
|
||||
letterSpacing: -0.5,
|
||||
},
|
||||
brandNameTablet: {
|
||||
fontSize: 36,
|
||||
},
|
||||
description: {
|
||||
fontSize: 16,
|
||||
color: colors.textSecondary,
|
||||
textAlign: 'center',
|
||||
maxWidth: 260,
|
||||
lineHeight: 24,
|
||||
},
|
||||
descriptionTablet: {
|
||||
fontSize: 18,
|
||||
maxWidth: 400,
|
||||
lineHeight: 28,
|
||||
},
|
||||
cards: {
|
||||
width: '100%',
|
||||
maxWidth: 320,
|
||||
gap: spacing.md,
|
||||
},
|
||||
cardsTablet: {
|
||||
maxWidth: 480,
|
||||
},
|
||||
card: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.md,
|
||||
backgroundColor: colors.primaryContainer,
|
||||
borderRadius: borderRadius.lg,
|
||||
padding: spacing.md,
|
||||
minHeight: 64,
|
||||
...shadows.card,
|
||||
},
|
||||
cardTablet: {
|
||||
padding: spacing.lg,
|
||||
minHeight: 72,
|
||||
},
|
||||
cardScan: {
|
||||
backgroundColor: colors.scanButton,
|
||||
},
|
||||
cardIcon: {
|
||||
width: 48,
|
||||
height: 48,
|
||||
borderRadius: borderRadius.md,
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.2)',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
flexShrink: 0,
|
||||
},
|
||||
cardIconSearch: {
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.3)',
|
||||
},
|
||||
cardIconScan: {
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.2)',
|
||||
},
|
||||
cardContent: {
|
||||
flex: 1,
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
},
|
||||
cardLabel: {
|
||||
fontSize: 18,
|
||||
fontWeight: '700',
|
||||
color: colors.onPrimaryContainer,
|
||||
lineHeight: 24,
|
||||
},
|
||||
cardLabelTablet: {
|
||||
fontSize: 20,
|
||||
},
|
||||
cardLabelScan: {
|
||||
color: '#ffffff',
|
||||
},
|
||||
});
|
||||
@@ -1,15 +1,9 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { View, FlatList, StyleSheet, Text, TouchableOpacity, useWindowDimensions } from 'react-native';
|
||||
import React from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity, Image, useWindowDimensions } from 'react-native';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { SearchBar } from '../../components/SearchBar';
|
||||
import { MedicineCard } from '../../components/MedicineCard';
|
||||
import { LoadingSpinner } from '../../components/LoadingSpinner';
|
||||
import { useDebounce } from '../../hooks/useDebounce';
|
||||
import { searchMedicines } from '../../services/medicines';
|
||||
import { colors, spacing, borderRadius } from '../../constants/theme';
|
||||
import { Medicine } from '../../types';
|
||||
import { config } from '../../constants/config';
|
||||
import { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { spacing, borderRadius, shadows } from '../../constants/theme';
|
||||
|
||||
const TABLET_MIN_WIDTH = 768;
|
||||
|
||||
@@ -17,77 +11,51 @@ export default function HomeScreen() {
|
||||
const router = useRouter();
|
||||
const { width } = useWindowDimensions();
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
const [query, setQuery] = useState('');
|
||||
const [results, setResults] = useState<Medicine[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const debouncedQuery = useDebounce(query, config.SEARCH_DEBOUNCE_MS);
|
||||
|
||||
useEffect(() => {
|
||||
if (debouncedQuery.length < 2) {
|
||||
setResults([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const fetchResults = async () => {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const data = await searchMedicines(debouncedQuery);
|
||||
setResults(data);
|
||||
} catch (err) {
|
||||
setError('Error al buscar medicamentos');
|
||||
console.error(err);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchResults();
|
||||
}, [debouncedQuery]);
|
||||
|
||||
const handleSearch = (searchQuery: string) => {
|
||||
setQuery(searchQuery);
|
||||
};
|
||||
const { colors } = useThemeContext();
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<View style={[styles.searchContainer, isTablet && styles.searchContainerTablet]}>
|
||||
<SearchBar
|
||||
onSearch={handleSearch}
|
||||
value={query}
|
||||
onChangeText={setQuery}
|
||||
<View style={[styles.container, { backgroundColor: colors.background }]}>
|
||||
<View style={[styles.hero, isTablet && styles.heroTablet]}>
|
||||
<Image
|
||||
source={require('../../assets/farmaclic_logo.png')}
|
||||
style={[styles.logo, isTablet && styles.logoTablet]}
|
||||
resizeMode="contain"
|
||||
/>
|
||||
<TouchableOpacity
|
||||
style={styles.scannerButton}
|
||||
onPress={() => router.push('/scanner')}
|
||||
>
|
||||
<Ionicons name="scan" size={22} color="#ffffff" />
|
||||
</TouchableOpacity>
|
||||
<Text style={[styles.brandName, isTablet && styles.brandNameTablet, { color: colors.text }]}>FarmaClic</Text>
|
||||
<Text style={[styles.description, isTablet && styles.descriptionTablet, { color: colors.textSecondary }]}>
|
||||
Encuentra tus medicamentos en farmacias cercanas
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
{isLoading && <LoadingSpinner message="Buscando medicamentos..." />}
|
||||
<View style={[styles.cards, isTablet && styles.cardsTablet]}>
|
||||
<TouchableOpacity
|
||||
style={[styles.card, isTablet && styles.cardTablet, { backgroundColor: colors.primaryContainer }]}
|
||||
activeOpacity={0.85}
|
||||
onPress={() => router.push('/(tabs)/search')}
|
||||
>
|
||||
<View style={[styles.cardIcon, styles.cardIconSearch]}>
|
||||
<Ionicons name="search" size={isTablet ? 28 : 24} color={colors.onPrimaryContainer} />
|
||||
</View>
|
||||
<View style={styles.cardContent}>
|
||||
<Text style={[styles.cardLabel, isTablet && styles.cardLabelTablet, { color: colors.onPrimaryContainer }]}>Buscar Medicamento</Text>
|
||||
<Ionicons name="chevron-forward" size={20} color={colors.onPrimaryContainer} style={{ opacity: 0.7 }} />
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
|
||||
{error && (
|
||||
<View style={[styles.errorContainer, isTablet && styles.errorContainerTablet]}>
|
||||
<Text style={styles.errorText}>{error}</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{!isLoading && !error && results.length === 0 && query.length >= 2 && (
|
||||
<View style={styles.emptyContainer}>
|
||||
<Text style={styles.emptyText}>No se encontraron medicamentos</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
<FlatList
|
||||
data={results}
|
||||
keyExtractor={(item) => item.nregistro}
|
||||
renderItem={({ item }) => <MedicineCard medicine={item} />}
|
||||
contentContainerStyle={[styles.list, isTablet && styles.listTablet]}
|
||||
showsVerticalScrollIndicator={false}
|
||||
/>
|
||||
<TouchableOpacity
|
||||
style={[styles.card, styles.cardScan, isTablet && styles.cardTablet]}
|
||||
activeOpacity={0.85}
|
||||
onPress={() => router.push('/scanner')}
|
||||
>
|
||||
<View style={[styles.cardIcon, styles.cardIconScan]}>
|
||||
<Ionicons name="scan" size={isTablet ? 28 : 24} color="#ffffff" />
|
||||
</View>
|
||||
<View style={styles.cardContent}>
|
||||
<Text style={[styles.cardLabel, styles.cardLabelScan, isTablet && styles.cardLabelTablet]}>Escanear TSI</Text>
|
||||
<Ionicons name="chevron-forward" size={20} color="#ffffff" style={{ opacity: 0.7 }} />
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -95,63 +63,101 @@ export default function HomeScreen() {
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: colors.background,
|
||||
},
|
||||
searchContainer: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
paddingHorizontal: spacing.lg,
|
||||
maxWidth: 480,
|
||||
alignSelf: 'center',
|
||||
width: '100%',
|
||||
},
|
||||
searchContainerTablet: {
|
||||
maxWidth: 700,
|
||||
alignSelf: 'center',
|
||||
width: '100%',
|
||||
},
|
||||
scannerButton: {
|
||||
width: 44,
|
||||
height: 44,
|
||||
borderRadius: 22,
|
||||
backgroundColor: colors.scanButton,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
shadowColor: '#2b5bb5',
|
||||
shadowOffset: { width: 0, height: 4 },
|
||||
shadowOpacity: 0.3,
|
||||
shadowRadius: 12,
|
||||
elevation: 6,
|
||||
paddingHorizontal: spacing.lg,
|
||||
gap: spacing.lg,
|
||||
},
|
||||
list: {
|
||||
paddingBottom: spacing.xl,
|
||||
},
|
||||
listTablet: {
|
||||
maxWidth: 700,
|
||||
alignSelf: 'center',
|
||||
width: '100%',
|
||||
},
|
||||
errorContainer: {
|
||||
padding: spacing.md,
|
||||
marginHorizontal: spacing.lg,
|
||||
backgroundColor: colors.dangerContainer,
|
||||
borderRadius: borderRadius.lg,
|
||||
},
|
||||
errorContainerTablet: {
|
||||
maxWidth: 700,
|
||||
alignSelf: 'center',
|
||||
},
|
||||
errorText: {
|
||||
color: colors.danger,
|
||||
textAlign: 'center',
|
||||
fontSize: 14,
|
||||
},
|
||||
emptyContainer: {
|
||||
padding: spacing.xl,
|
||||
hero: {
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
emptyText: {
|
||||
color: colors.textSecondary,
|
||||
heroTablet: {
|
||||
marginBottom: spacing.xl,
|
||||
},
|
||||
logo: {
|
||||
width: 120,
|
||||
height: 120,
|
||||
marginBottom: spacing.xs,
|
||||
},
|
||||
logoTablet: {
|
||||
width: 160,
|
||||
height: 160,
|
||||
},
|
||||
brandName: {
|
||||
fontSize: 28,
|
||||
fontWeight: 'bold',
|
||||
letterSpacing: -0.5,
|
||||
},
|
||||
brandNameTablet: {
|
||||
fontSize: 36,
|
||||
},
|
||||
description: {
|
||||
fontSize: 16,
|
||||
textAlign: 'center',
|
||||
maxWidth: 260,
|
||||
lineHeight: 24,
|
||||
},
|
||||
descriptionTablet: {
|
||||
fontSize: 18,
|
||||
maxWidth: 400,
|
||||
lineHeight: 28,
|
||||
},
|
||||
cards: {
|
||||
width: '100%',
|
||||
maxWidth: 320,
|
||||
gap: spacing.md,
|
||||
},
|
||||
cardsTablet: {
|
||||
maxWidth: 480,
|
||||
},
|
||||
card: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.md,
|
||||
borderRadius: borderRadius.lg,
|
||||
padding: spacing.md,
|
||||
minHeight: 64,
|
||||
...shadows.card,
|
||||
},
|
||||
cardTablet: {
|
||||
padding: spacing.lg,
|
||||
minHeight: 72,
|
||||
},
|
||||
cardScan: {
|
||||
backgroundColor: '#2b5bb5',
|
||||
},
|
||||
cardIcon: {
|
||||
width: 48,
|
||||
height: 48,
|
||||
borderRadius: borderRadius.md,
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.2)',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
flexShrink: 0,
|
||||
},
|
||||
cardIconSearch: {
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.3)',
|
||||
},
|
||||
cardIconScan: {
|
||||
backgroundColor: 'rgba(255, 255, 255, 0.2)',
|
||||
},
|
||||
cardContent: {
|
||||
flex: 1,
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'space-between',
|
||||
},
|
||||
cardLabel: {
|
||||
fontSize: 18,
|
||||
fontWeight: '700',
|
||||
lineHeight: 24,
|
||||
},
|
||||
cardLabelTablet: {
|
||||
fontSize: 20,
|
||||
},
|
||||
cardLabelScan: {
|
||||
color: '#ffffff',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -4,15 +4,17 @@ import MapView, { Marker } from 'react-native-maps';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { getPharmacies } from '../../services/pharmacies';
|
||||
import { LoadingSpinner } from '../../components/LoadingSpinner';
|
||||
import { colors, spacing, borderRadius } from '../../constants/theme';
|
||||
import { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { spacing, borderRadius } from '../../constants/theme';
|
||||
import { Pharmacy } from '../../types';
|
||||
|
||||
export default function MapScreen() {
|
||||
const router = useRouter();
|
||||
const { colors } = useThemeContext();
|
||||
const [pharmacies, setPharmacies] = useState<Pharmacy[]>([]);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [region, setRegion] = useState({
|
||||
latitude: 40.4168, // Madrid default
|
||||
latitude: 40.4168,
|
||||
longitude: -3.7038,
|
||||
latitudeDelta: 0.0922,
|
||||
longitudeDelta: 0.0421,
|
||||
@@ -24,7 +26,6 @@ export default function MapScreen() {
|
||||
const data = await getPharmacies();
|
||||
setPharmacies(data);
|
||||
|
||||
// Center map on first pharmacy if available
|
||||
if (data.length > 0) {
|
||||
setRegion({
|
||||
latitude: data[0].latitude,
|
||||
@@ -70,8 +71,8 @@ export default function MapScreen() {
|
||||
))}
|
||||
</MapView>
|
||||
|
||||
<View style={styles.legend}>
|
||||
<Text style={styles.legendText}>
|
||||
<View style={[styles.legend, { backgroundColor: colors.card }]}>
|
||||
<Text style={[styles.legendText, { color: colors.text }]}>
|
||||
{pharmacies.length} farmacias en el mapa
|
||||
</Text>
|
||||
</View>
|
||||
@@ -91,7 +92,6 @@ const styles = StyleSheet.create({
|
||||
bottom: spacing.lg,
|
||||
left: spacing.md,
|
||||
right: spacing.md,
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.lg,
|
||||
padding: spacing.sm + 4,
|
||||
alignItems: 'center',
|
||||
@@ -103,6 +103,5 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
legendText: {
|
||||
fontSize: 14,
|
||||
color: colors.text,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import React from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity, useWindowDimensions } from 'react-native';
|
||||
import React, { useState } from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity, TextInput, Alert, useWindowDimensions, ScrollView } from 'react-native';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { colors, spacing, borderRadius, shadows } from '../../constants/theme';
|
||||
import * as ImagePicker from 'expo-image-picker';
|
||||
import { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { spacing, borderRadius, shadows } from '../../constants/theme';
|
||||
|
||||
const TABLET_MIN_WIDTH = 768;
|
||||
|
||||
@@ -10,36 +12,174 @@ export default function ScanTabScreen() {
|
||||
const router = useRouter();
|
||||
const { width } = useWindowDimensions();
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
const { colors } = useThemeContext();
|
||||
const [manualNumber, setManualNumber] = useState('');
|
||||
const [selectedImage, setSelectedImage] = useState<string | null>(null);
|
||||
|
||||
const handleTakePhoto = async () => {
|
||||
const { status } = await ImagePicker.requestCameraPermissionsAsync();
|
||||
if (status !== 'granted') {
|
||||
Alert.alert(
|
||||
'Permiso requerido',
|
||||
'Necesitamos acceso a la cámara para tomar fotos del dispositivo.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await ImagePicker.launchCameraAsync({
|
||||
mediaTypes: ['images'],
|
||||
allowsEditing: true,
|
||||
quality: 0.8,
|
||||
});
|
||||
|
||||
if (!result.canceled && result.assets[0]) {
|
||||
setSelectedImage(result.assets[0].uri);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSelectFromGallery = async () => {
|
||||
const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
|
||||
if (status !== 'granted') {
|
||||
Alert.alert(
|
||||
'Permiso requerido',
|
||||
'Necesitamos acceso a la galería para seleccionar fotos.'
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await ImagePicker.launchImageLibraryAsync({
|
||||
mediaTypes: ['images'],
|
||||
allowsEditing: true,
|
||||
quality: 0.8,
|
||||
});
|
||||
|
||||
if (!result.canceled && result.assets[0]) {
|
||||
setSelectedImage(result.assets[0].uri);
|
||||
}
|
||||
};
|
||||
|
||||
const handleManualSubmit = () => {
|
||||
const trimmed = manualNumber.trim();
|
||||
if (trimmed.length === 0) {
|
||||
Alert.alert('Campo requerido', 'Por favor, introduce el número de la tarjeta.');
|
||||
return;
|
||||
}
|
||||
router.push(`/medicine/${trimmed}`);
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<ScrollView
|
||||
style={[styles.scrollContainer, { backgroundColor: colors.background }]}
|
||||
contentContainerStyle={styles.scrollContent}
|
||||
>
|
||||
<View style={[styles.content, isTablet && styles.contentTablet]}>
|
||||
<View style={[styles.iconContainer, isTablet && styles.iconContainerTablet]}>
|
||||
<View style={[styles.iconContainer, isTablet && styles.iconContainerTablet, { backgroundColor: colors.primaryContainer }]}>
|
||||
<Ionicons name="scan" size={isTablet ? 80 : 64} color={colors.scanButton} />
|
||||
</View>
|
||||
<Text style={[styles.title, isTablet && styles.titleTablet]}>Escanear TSI</Text>
|
||||
<Text style={[styles.description, isTablet && styles.descriptionTablet]}>
|
||||
<Text style={[styles.title, isTablet && styles.titleTablet, { color: colors.text }]}>Escanear TSI</Text>
|
||||
<Text style={[styles.description, isTablet && styles.descriptionTablet, { color: colors.textSecondary }]}>
|
||||
Escanea el código de barras de tu tarjeta sanitaria para encontrar tus medicamentos
|
||||
</Text>
|
||||
<TouchableOpacity
|
||||
style={[styles.button, shadows.scanButton, isTablet && styles.buttonTablet]}
|
||||
style={[styles.primaryButton, shadows.scanButton, isTablet && styles.primaryButtonTablet]}
|
||||
activeOpacity={0.85}
|
||||
onPress={() => router.push('/scanner')}
|
||||
>
|
||||
<Ionicons name="scan" size={isTablet ? 28 : 24} color="#ffffff" />
|
||||
<Text style={[styles.buttonText, isTablet && styles.buttonTextTablet]}>Iniciar escaneo</Text>
|
||||
<Text style={[styles.primaryButtonText, isTablet && styles.primaryButtonTextTablet]}>
|
||||
Iniciar escaneo
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
|
||||
{/* Separator */}
|
||||
<View style={styles.separator}>
|
||||
<View style={[styles.separatorLine, { backgroundColor: colors.border }]} />
|
||||
<Text style={[styles.separatorText, { color: colors.textSecondary }]}>o</Text>
|
||||
<View style={[styles.separatorLine, { backgroundColor: colors.border }]} />
|
||||
</View>
|
||||
|
||||
{/* Option 2: Upload device photo */}
|
||||
<View style={[styles.optionCard, isTablet && styles.optionCardTablet, { backgroundColor: colors.card, borderColor: colors.border }]}>
|
||||
<Ionicons name="camera" size={24} color={colors.primary} />
|
||||
<View style={styles.optionTextContainer}>
|
||||
<Text style={[styles.optionTitle, isTablet && styles.optionTitleTablet, { color: colors.text }]}>
|
||||
Subir foto del dispositivo
|
||||
</Text>
|
||||
<Text style={[styles.optionDescription, isTablet && styles.optionDescriptionTablet, { color: colors.textSecondary }]}>
|
||||
Toma o selecciona una foto del dispositivo sanitario
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.photoButtonsRow}>
|
||||
<TouchableOpacity
|
||||
style={[styles.photoButton, isTablet && styles.photoButtonTablet, { backgroundColor: colors.primaryContainer, borderColor: colors.primary }]}
|
||||
activeOpacity={0.7}
|
||||
onPress={handleTakePhoto}
|
||||
>
|
||||
<Ionicons name="camera-outline" size={20} color={colors.primary} />
|
||||
<Text style={[styles.photoButtonText, { color: colors.primary }]}>Tomar foto</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity
|
||||
style={[styles.photoButton, isTablet && styles.photoButtonTablet, { backgroundColor: colors.primaryContainer, borderColor: colors.primary }]}
|
||||
activeOpacity={0.7}
|
||||
onPress={handleSelectFromGallery}
|
||||
>
|
||||
<Ionicons name="images-outline" size={20} color={colors.primary} />
|
||||
<Text style={[styles.photoButtonText, { color: colors.primary }]}>Galería</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
{selectedImage && (
|
||||
<View style={styles.imagePreviewContainer}>
|
||||
<Ionicons name="checkmark-circle" size={20} color={colors.success} />
|
||||
<Text style={[styles.imagePreviewText, { color: colors.success }]}>Foto seleccionada correctamente</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Option 3: Enter card number manually */}
|
||||
<View style={[styles.optionCard, isTablet && styles.optionCardTablet, { backgroundColor: colors.card, borderColor: colors.border }]}>
|
||||
<Ionicons name="keypad" size={24} color={colors.primary} />
|
||||
<View style={styles.optionTextContainer}>
|
||||
<Text style={[styles.optionTitle, isTablet && styles.optionTitleTablet, { color: colors.text }]}>
|
||||
Introducir número manualmente
|
||||
</Text>
|
||||
<Text style={[styles.optionDescription, isTablet && styles.optionDescriptionTablet, { color: colors.textSecondary }]}>
|
||||
Escribe el número de tu tarjeta sanitaria
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.manualInputRow}>
|
||||
<TextInput
|
||||
style={[styles.manualInput, isTablet && styles.manualInputTablet, { backgroundColor: colors.card, borderColor: colors.border, color: colors.text }]}
|
||||
placeholder="Introduce el número de tarjeta"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
value={manualNumber}
|
||||
onChangeText={setManualNumber}
|
||||
keyboardType="default"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
returnKeyType="search"
|
||||
onSubmitEditing={handleManualSubmit}
|
||||
/>
|
||||
<TouchableOpacity
|
||||
style={[styles.manualSubmitButton, isTablet && styles.manualSubmitButtonTablet]}
|
||||
activeOpacity={0.7}
|
||||
onPress={handleManualSubmit}
|
||||
>
|
||||
<Ionicons name="arrow-forward" size={20} color="#ffffff" />
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
scrollContainer: {
|
||||
flex: 1,
|
||||
backgroundColor: colors.background,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
scrollContent: {
|
||||
flexGrow: 1,
|
||||
paddingVertical: spacing.xl,
|
||||
},
|
||||
content: {
|
||||
alignItems: 'center',
|
||||
@@ -53,7 +193,6 @@ const styles = StyleSheet.create({
|
||||
width: 100,
|
||||
height: 100,
|
||||
borderRadius: 50,
|
||||
backgroundColor: colors.primaryContainer,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
marginBottom: spacing.sm,
|
||||
@@ -66,14 +205,12 @@ const styles = StyleSheet.create({
|
||||
title: {
|
||||
fontSize: 22,
|
||||
fontWeight: 'bold',
|
||||
color: colors.text,
|
||||
},
|
||||
titleTablet: {
|
||||
fontSize: 28,
|
||||
},
|
||||
description: {
|
||||
fontSize: 15,
|
||||
color: colors.textSecondary,
|
||||
textAlign: 'center',
|
||||
lineHeight: 22,
|
||||
maxWidth: 280,
|
||||
@@ -83,26 +220,128 @@ const styles = StyleSheet.create({
|
||||
maxWidth: 420,
|
||||
lineHeight: 26,
|
||||
},
|
||||
button: {
|
||||
primaryButton: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
backgroundColor: colors.scanButton,
|
||||
backgroundColor: '#2b5bb5',
|
||||
borderRadius: borderRadius.lg,
|
||||
paddingVertical: spacing.md,
|
||||
paddingHorizontal: spacing.xl,
|
||||
marginTop: spacing.md,
|
||||
marginTop: spacing.sm,
|
||||
},
|
||||
buttonTablet: {
|
||||
primaryButtonTablet: {
|
||||
paddingVertical: spacing.lg,
|
||||
paddingHorizontal: spacing.xl * 1.5,
|
||||
},
|
||||
buttonText: {
|
||||
primaryButtonText: {
|
||||
fontSize: 17,
|
||||
fontWeight: '600',
|
||||
color: '#ffffff',
|
||||
},
|
||||
buttonTextTablet: {
|
||||
primaryButtonTextTablet: {
|
||||
fontSize: 20,
|
||||
},
|
||||
separator: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
width: '100%',
|
||||
marginVertical: spacing.sm,
|
||||
},
|
||||
separatorLine: {
|
||||
flex: 1,
|
||||
height: 1,
|
||||
},
|
||||
separatorText: {
|
||||
marginHorizontal: spacing.md,
|
||||
fontSize: 14,
|
||||
},
|
||||
optionCard: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
width: '100%',
|
||||
borderRadius: borderRadius.lg,
|
||||
padding: spacing.md,
|
||||
gap: spacing.md,
|
||||
borderWidth: 1,
|
||||
},
|
||||
optionCardTablet: {
|
||||
padding: spacing.lg,
|
||||
},
|
||||
optionTextContainer: {
|
||||
flex: 1,
|
||||
},
|
||||
optionTitle: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
},
|
||||
optionTitleTablet: {
|
||||
fontSize: 18,
|
||||
},
|
||||
optionDescription: {
|
||||
fontSize: 13,
|
||||
marginTop: 2,
|
||||
},
|
||||
optionDescriptionTablet: {
|
||||
fontSize: 15,
|
||||
},
|
||||
photoButtonsRow: {
|
||||
flexDirection: 'row',
|
||||
width: '100%',
|
||||
gap: spacing.sm,
|
||||
},
|
||||
photoButton: {
|
||||
flex: 1,
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: spacing.xs,
|
||||
borderRadius: borderRadius.md,
|
||||
paddingVertical: spacing.sm + 4,
|
||||
borderWidth: 1,
|
||||
},
|
||||
photoButtonTablet: {
|
||||
paddingVertical: spacing.md,
|
||||
},
|
||||
photoButtonText: {
|
||||
fontSize: 14,
|
||||
fontWeight: '500',
|
||||
},
|
||||
imagePreviewContainer: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.xs,
|
||||
paddingVertical: spacing.xs,
|
||||
},
|
||||
imagePreviewText: {
|
||||
fontSize: 13,
|
||||
fontWeight: '500',
|
||||
},
|
||||
manualInputRow: {
|
||||
flexDirection: 'row',
|
||||
width: '100%',
|
||||
gap: spacing.sm,
|
||||
},
|
||||
manualInput: {
|
||||
flex: 1,
|
||||
borderRadius: borderRadius.md,
|
||||
borderWidth: 1,
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: spacing.sm + 4,
|
||||
fontSize: 15,
|
||||
},
|
||||
manualInputTablet: {
|
||||
fontSize: 18,
|
||||
paddingVertical: spacing.md,
|
||||
},
|
||||
manualSubmitButton: {
|
||||
backgroundColor: '#7fbf8f',
|
||||
borderRadius: borderRadius.md,
|
||||
width: 48,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
manualSubmitButtonTablet: {
|
||||
width: 56,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,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,34 +1,42 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import React, { useEffect, useRef } from 'react';
|
||||
import { Stack } from 'expo-router';
|
||||
import { StatusBar } from 'expo-status-bar';
|
||||
import { ImageBackground, StyleSheet, View } from 'react-native';
|
||||
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 { colors } from '../constants/theme';
|
||||
import { ThemeProvider, useThemeContext } from '../components/ThemeProvider';
|
||||
import { initFaro } from '../services/faro';
|
||||
|
||||
// Boot Faro RUM once, as early as possible.
|
||||
initFaro();
|
||||
|
||||
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>>();
|
||||
|
||||
useEffect(() => {
|
||||
checkAuth();
|
||||
|
||||
|
||||
registerForPushNotifications();
|
||||
|
||||
|
||||
notificationListener.current = addNotificationListener((notification) => {
|
||||
console.log('Notification received:', notification);
|
||||
});
|
||||
|
||||
|
||||
responseListener.current = addNotificationResponseListener((response) => {
|
||||
console.log('Notification clicked:', response);
|
||||
});
|
||||
|
||||
|
||||
return () => {
|
||||
notificationListener.current?.remove();
|
||||
responseListener.current?.remove();
|
||||
@@ -36,71 +44,114 @@ export default function RootLayout() {
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<ImageBackground
|
||||
source={require('../assets/bg.png')}
|
||||
style={bgStyles.background}
|
||||
resizeMode="cover"
|
||||
imageStyle={bgStyles.backgroundImage}
|
||||
<>
|
||||
<Stack
|
||||
screenOptions={{
|
||||
headerStyle: { backgroundColor: colors.card },
|
||||
headerTintColor: colors.primary,
|
||||
headerTitleStyle: { color: colors.text, fontWeight: '600' },
|
||||
contentStyle: { backgroundColor: 'transparent' },
|
||||
}}
|
||||
>
|
||||
<View style={bgStyles.overlay} />
|
||||
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
|
||||
<Stack.Screen
|
||||
name="medicine/[id]"
|
||||
options={{ title: 'Medicamento' }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="pharmacy/[id]"
|
||||
options={{ title: 'Farmacia' }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="scanner"
|
||||
options={{
|
||||
title: 'Escanear',
|
||||
headerShown: false,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="auth/login"
|
||||
options={{
|
||||
title: 'Iniciar Sesión',
|
||||
headerShown: false,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="auth/register"
|
||||
options={{
|
||||
title: 'Registrarse',
|
||||
headerShown: false,
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
<StatusBar style={isDark ? 'light' : 'auto'} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
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} pointerEvents="auto">
|
||||
{children}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export default function RootLayout() {
|
||||
return (
|
||||
<GestureHandlerRootView style={styles.root}>
|
||||
<SafeAreaProvider>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<Stack
|
||||
screenOptions={{
|
||||
headerStyle: { backgroundColor: colors.card },
|
||||
headerTintColor: colors.primary,
|
||||
headerTitleStyle: { color: colors.text, fontWeight: '600' },
|
||||
}}
|
||||
>
|
||||
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
|
||||
<Stack.Screen
|
||||
name="medicine/[id]"
|
||||
options={{ title: 'Medicamento' }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="pharmacy/[id]"
|
||||
options={{ title: 'Farmacia' }}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="scanner"
|
||||
options={{
|
||||
title: 'Escanear',
|
||||
headerShown: false,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="auth/login"
|
||||
options={{
|
||||
title: 'Iniciar Sesión',
|
||||
headerShown: false,
|
||||
}}
|
||||
/>
|
||||
<Stack.Screen
|
||||
name="auth/register"
|
||||
options={{
|
||||
title: 'Registrarse',
|
||||
headerShown: false,
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
<StatusBar style="auto" />
|
||||
<ThemeProvider>
|
||||
<ThemedBackground>
|
||||
<RootLayoutInner />
|
||||
</ThemedBackground>
|
||||
</ThemeProvider>
|
||||
</QueryClientProvider>
|
||||
</SafeAreaProvider>
|
||||
</ImageBackground>
|
||||
</GestureHandlerRootView>
|
||||
);
|
||||
}
|
||||
|
||||
const bgStyles = StyleSheet.create({
|
||||
background: {
|
||||
const styles = StyleSheet.create({
|
||||
root: {
|
||||
flex: 1,
|
||||
},
|
||||
backgroundImage: {
|
||||
opacity: 0.8,
|
||||
bgImage: {
|
||||
position: 'absolute',
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
opacity: 0.55,
|
||||
zIndex: 0,
|
||||
},
|
||||
overlay: {
|
||||
...StyleSheet.absoluteFillObject,
|
||||
backgroundColor: 'rgba(255, 252, 245, 0.2)',
|
||||
position: 'absolute',
|
||||
left: 0,
|
||||
right: 0,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
backgroundColor: 'rgba(255, 252, 245, 0.48)',
|
||||
zIndex: 1,
|
||||
},
|
||||
overlayDark: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.25)',
|
||||
},
|
||||
content: {
|
||||
flex: 1,
|
||||
zIndex: 2,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,38 +1,54 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
TextInput,
|
||||
TouchableOpacity,
|
||||
StyleSheet,
|
||||
import {
|
||||
View,
|
||||
Text,
|
||||
TextInput,
|
||||
TouchableOpacity,
|
||||
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 {
|
||||
isBiometricsAvailable,
|
||||
authenticateWithBiometrics,
|
||||
saveBiometricCredentials,
|
||||
getBiometricUsername
|
||||
import { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { register } from '../../services/auth';
|
||||
import { spacing, borderRadius, shadows } from '../../constants/theme';
|
||||
import {
|
||||
isBiometricsAvailable,
|
||||
authenticateWithBiometrics,
|
||||
saveBiometricCredentials,
|
||||
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 (biometricsAvailable) {
|
||||
await saveBiometricCredentials(username);
|
||||
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.trim());
|
||||
}
|
||||
router.replace('/(tabs)');
|
||||
}
|
||||
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.inputContainer}>
|
||||
<Text style={styles.label}>Usuario</Text>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
value={username}
|
||||
onChangeText={setUsername}
|
||||
placeholder="Tu usuario"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
<View 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}>Contraseña</Text>
|
||||
<TextInput
|
||||
style={styles.input}
|
||||
value={password}
|
||||
onChangeText={setPassword}
|
||||
placeholder="Tu contraseña"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
secureTextEntry
|
||||
/>
|
||||
</View>
|
||||
|
||||
<TouchableOpacity
|
||||
style={[styles.button, isLoading && styles.buttonDisabled]}
|
||||
onPress={handleLogin}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Text style={styles.buttonText}>
|
||||
{isLoading ? 'Ingresando...' : 'Iniciar Sesión'}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
|
||||
{biometricsAvailable && biometricUsername && (
|
||||
{/* Tabs */}
|
||||
<View style={[styles.tabBar, { backgroundColor: colors.surfaceLow }]}>
|
||||
<TouchableOpacity
|
||||
style={[styles.biometricButton, isLoading && styles.buttonDisabled]}
|
||||
onPress={handleBiometricLogin}
|
||||
style={[
|
||||
styles.tab,
|
||||
!isRegister && [styles.tabActive, { backgroundColor: colors.primary }],
|
||||
]}
|
||||
onPress={() => setTab('login')}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Ionicons name="finger-print" size={24} color={colors.primary} />
|
||||
<Text style={styles.biometricText}>Iniciar con biometría</Text>
|
||||
<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, { color: colors.text }]}
|
||||
value={username}
|
||||
onChangeText={setUsername}
|
||||
placeholder="Usuario"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
autoComplete="username"
|
||||
/>
|
||||
</View>
|
||||
|
||||
{/* 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, { color: colors.text }]}
|
||||
value={password}
|
||||
onChangeText={setPassword}
|
||||
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, { backgroundColor: colors.primary }, isLoading && styles.buttonDisabled]}
|
||||
onPress={handleSubmit}
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? (
|
||||
<Ionicons name="hourglass" size={20} color={colors.onPrimaryContainer} />
|
||||
) : (
|
||||
<Text style={[styles.buttonText, { color: colors.onPrimaryContainer }]}>
|
||||
{isRegister ? 'Crear Cuenta' : 'Iniciar Sesión'}
|
||||
</Text>
|
||||
)}
|
||||
</TouchableOpacity>
|
||||
|
||||
{/* Biometrics (login only) */}
|
||||
{!isRegister && biometricsAvailable && biometricUsername && (
|
||||
<TouchableOpacity
|
||||
style={[styles.biometricButton, { borderColor: colors.primary }]}
|
||||
onPress={handleBiometricLogin}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<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;
|
||||
}
|
||||
|
||||
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>
|
||||
);
|
||||
export default function RegisterRedirect() {
|
||||
return <Redirect href="/auth/login" />;
|
||||
}
|
||||
|
||||
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,19 +1,57 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import React, { useEffect, useState, useMemo } from 'react';
|
||||
import { View, Text, ScrollView, StyleSheet, TouchableOpacity, Linking } from 'react-native';
|
||||
import { useLocalSearchParams, useRouter } from 'expo-router';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import * as Location from 'expo-location';
|
||||
import { getMedicine, getMedicinePharmacies } from '../../services/medicines';
|
||||
import { 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;
|
||||
@@ -36,6 +74,82 @@ 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);
|
||||
@@ -47,76 +161,146 @@ export default function MedicineDetailScreen() {
|
||||
|
||||
if (!medicine) {
|
||||
return (
|
||||
<View style={styles.errorContainer}>
|
||||
<Text style={styles.errorText}>Medicamento no encontrado</Text>
|
||||
<View style={[styles.errorContainer, { backgroundColor: colors.background }]}>
|
||||
<Text style={[styles.errorText, { color: colors.textSecondary }]}>Medicamento no encontrado</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollView style={styles.container}>
|
||||
<View style={styles.header}>
|
||||
<Text style={styles.name}>{medicine.name}</Text>
|
||||
{medicine.stock != null && <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.active_ingredient} />
|
||||
<InfoRow label="Laboratorio" value={medicine.laboratory} />
|
||||
<InfoRow label="Forma farmacéutica" value={medicine.form} />
|
||||
<InfoRow label="Dosificación" value={medicine.dosage} />
|
||||
<View style={[styles.infoSection, { backgroundColor: colors.card }]}>
|
||||
<InfoRow label="Principio activo" value={medicine.active_ingredient} colors={colors} />
|
||||
<InfoRow label="Laboratorio" value={medicine.laboratory} colors={colors} />
|
||||
<InfoRow label="Forma farmacéutica" value={medicine.form} colors={colors} />
|
||||
<InfoRow label="Dosificación" value={medicine.dosage} colors={colors} />
|
||||
<InfoRow
|
||||
label="Precio"
|
||||
value={medicine.precio != null ? `${medicine.precio.toFixed(2)} €` : 'No disponible'}
|
||||
colors={colors}
|
||||
/>
|
||||
<InfoRow label="Registro" value={medicine.nregistro} />
|
||||
<InfoRow label="Registro" value={medicine.nregistro} colors={colors} />
|
||||
</View>
|
||||
|
||||
<View style={styles.pharmaciesSection}>
|
||||
<Text style={styles.sectionTitle}>
|
||||
Farmacias ({pharmacies.length})
|
||||
</Text>
|
||||
{locatedPharmacies.length > 0 && (
|
||||
<View style={[styles.mapContainer, { backgroundColor: colors.surfaceVariant }]}>
|
||||
<Ionicons name="map-outline" size={48} color={colors.textSecondary} />
|
||||
<Text style={[styles.mapPlaceholder, { color: colors.textSecondary }]}>
|
||||
Mapa próximamente…
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{pharmacies.length === 0 ? (
|
||||
<Text style={styles.noPharmacies}>No hay farmacias con este medicamento</Text>
|
||||
<View style={styles.pharmaciesSection}>
|
||||
<View style={styles.pharmaciesHeader}>
|
||||
<Text style={[styles.sectionTitle, { color: colors.text }]}>
|
||||
Farmacias ({sortedPharmacies.length})
|
||||
</Text>
|
||||
<TouchableOpacity
|
||||
style={[styles.sortButton, sortByDistance && styles.sortButtonActive, { backgroundColor: sortByDistance ? colors.primary : colors.primaryContainer, borderColor: colors.primary }]}
|
||||
onPress={handleSortByDistance}
|
||||
disabled={locating}
|
||||
>
|
||||
<Ionicons name="location" size={16} color={sortByDistance ? '#fff' : colors.primary} />
|
||||
<Text style={[styles.sortButtonText, sortByDistance && styles.sortButtonTextActive, { color: sortByDistance ? '#fff' : colors.primary }]}>
|
||||
{locating
|
||||
? 'Localizando…'
|
||||
: sortByDistance
|
||||
? 'Distancia · Reset'
|
||||
: 'Ordenar por distancia'}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
{locationError && (
|
||||
<View style={[styles.locationErrorContainer, { backgroundColor: colors.dangerContainer }]}>
|
||||
<Text style={[styles.locationErrorText, { color: colors.danger }]}>{locationError}</Text>
|
||||
<TouchableOpacity onPress={handleSortByDistance}>
|
||||
<Text style={[styles.retryText, { color: colors.primary }]}>Reintentar</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{sortedPharmacies.length === 0 ? (
|
||||
<Text style={[styles.noPharmacies, { color: colors.textSecondary }]}>No hay farmacias disponibles</Text>
|
||||
) : (
|
||||
pharmacies.map((pharm) => (
|
||||
<View key={pharm.id} style={styles.pharmacyCard}>
|
||||
<TouchableOpacity
|
||||
style={styles.pharmacyCardContent}
|
||||
onPress={() => router.push(`/pharmacy/${pharm.pharmacy_id}`)}
|
||||
>
|
||||
<View style={styles.pharmacyInfo}>
|
||||
<Text style={styles.pharmacyName}>{pharm.pharmacy?.name}</Text>
|
||||
<Text style={styles.pharmacyAddress}>{pharm.pharmacy?.address}</Text>
|
||||
</View>
|
||||
<View style={styles.pharmacyStock}>
|
||||
<Text style={styles.price}>{pharm.price.toFixed(2)} €</Text>
|
||||
<Text style={styles.stock}>Stock: {pharm.stock}</Text>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
{pharm.pharmacy?.latitude != null && pharm.pharmacy?.longitude != null && (
|
||||
sortedPharmacies.map((pharm) => {
|
||||
const lat = getPharmacyLat(pharm);
|
||||
const lon = getPharmacyLon(pharm);
|
||||
const distanceKm =
|
||||
sortByDistance && userPosition && lat != null && lon != null
|
||||
? haversineKm(userPosition.lat, userPosition.lon, lat, lon)
|
||||
: null;
|
||||
|
||||
return (
|
||||
<View key={pharm.id} style={[styles.pharmacyCard, { backgroundColor: colors.card }]}>
|
||||
<TouchableOpacity
|
||||
style={styles.directionsButton}
|
||||
onPress={() => handleDirections(pharm.pharmacy.latitude, pharm.pharmacy.longitude)}
|
||||
style={styles.pharmacyCardContent}
|
||||
onPress={() => router.push(`/pharmacy/${pharm.pharmacy_id || pharm.id}`)}
|
||||
>
|
||||
<Ionicons name="navigate" size={16} color={colors.primary} />
|
||||
<Text style={styles.directionsText}>Cómo llegar</Text>
|
||||
<View style={styles.pharmacyInfo}>
|
||||
<View style={styles.pharmacyNameRow}>
|
||||
<Text style={[styles.pharmacyName, { color: colors.text }]}>{pharm.pharmacy?.name || pharm.name}</Text>
|
||||
{distanceKm != null && (
|
||||
<Text style={[styles.pharmacyDistance, { color: colors.primary, backgroundColor: colors.primaryContainer }]}>{formatDistance(distanceKm)}</Text>
|
||||
)}
|
||||
</View>
|
||||
<Text style={[styles.pharmacyAddress, { color: colors.textSecondary }]}>{pharm.pharmacy?.address || pharm.address}</Text>
|
||||
</View>
|
||||
<View style={styles.pharmacyStock}>
|
||||
{pharm.price != null ? (
|
||||
<Text style={[styles.price, { color: colors.primary }]}>{pharm.price.toFixed(2)} €</Text>
|
||||
) : (
|
||||
<Text style={[styles.price, { color: colors.primary }]}>Consultar precio</Text>
|
||||
)}
|
||||
{pharm.stock > 0 && (
|
||||
<Text style={[styles.stock, { color: colors.textSecondary }]}>Stock: {pharm.stock}</Text>
|
||||
)}
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
))
|
||||
{lat != null && lon != null && (
|
||||
<TouchableOpacity
|
||||
style={[styles.directionsButton, { borderTopColor: colors.border }]}
|
||||
onPress={() => handleDirections(lat, lon)}
|
||||
>
|
||||
<Ionicons name="navigate" size={16} color={colors.primary} />
|
||||
<Text style={[styles.directionsText, { color: colors.primary }]}>Cómo llegar</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</View>
|
||||
</ScrollView>
|
||||
);
|
||||
}
|
||||
|
||||
function InfoRow({ label, value }: { label: string; value: string }) {
|
||||
function InfoRow({ label, value, colors }: { label: string; value: string; colors: any }) {
|
||||
return (
|
||||
<View style={styles.infoRow}>
|
||||
<Text style={styles.infoLabel}>{label}</Text>
|
||||
<Text style={styles.infoValue}>{value}</Text>
|
||||
<View style={[styles.infoRow, { borderBottomColor: colors.border }]}>
|
||||
<Text style={[styles.infoLabel, { color: colors.textSecondary }]}>{label}</Text>
|
||||
<Text style={[styles.infoValue, { color: colors.text }]}>{value}</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -124,24 +308,32 @@ function InfoRow({ label, value }: { label: string; value: string }) {
|
||||
const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
backgroundColor: colors.background,
|
||||
},
|
||||
header: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'flex-start',
|
||||
padding: spacing.lg,
|
||||
backgroundColor: colors.card,
|
||||
},
|
||||
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.lg,
|
||||
},
|
||||
@@ -150,34 +342,82 @@ const styles = StyleSheet.create({
|
||||
justifyContent: 'space-between',
|
||||
paddingVertical: spacing.sm,
|
||||
borderBottomWidth: 1,
|
||||
borderBottomColor: colors.border,
|
||||
},
|
||||
infoLabel: {
|
||||
fontSize: 14,
|
||||
color: colors.textSecondary,
|
||||
fontSize: 13,
|
||||
flexShrink: 0,
|
||||
marginRight: spacing.sm,
|
||||
},
|
||||
infoValue: {
|
||||
fontSize: 13,
|
||||
fontWeight: '500',
|
||||
flex: 1,
|
||||
textAlign: 'right',
|
||||
},
|
||||
mapContainer: {
|
||||
marginTop: spacing.sm,
|
||||
marginHorizontal: spacing.lg,
|
||||
height: 200,
|
||||
borderRadius: borderRadius.lg,
|
||||
overflow: 'hidden',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
gap: spacing.sm,
|
||||
},
|
||||
mapPlaceholder: {
|
||||
fontSize: 14,
|
||||
color: colors.text,
|
||||
fontWeight: '500',
|
||||
},
|
||||
pharmaciesSection: {
|
||||
marginTop: spacing.sm,
|
||||
padding: spacing.lg,
|
||||
},
|
||||
pharmaciesHeader: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
sectionTitle: {
|
||||
fontSize: 18,
|
||||
fontWeight: '600',
|
||||
color: colors.text,
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
sortButton: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.xs,
|
||||
paddingHorizontal: spacing.sm + 4,
|
||||
paddingVertical: spacing.xs + 2,
|
||||
borderRadius: borderRadius.full,
|
||||
borderWidth: 1,
|
||||
},
|
||||
sortButtonActive: {},
|
||||
sortButtonText: {
|
||||
fontSize: 13,
|
||||
fontWeight: '600',
|
||||
},
|
||||
sortButtonTextActive: {},
|
||||
locationErrorContainer: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
padding: spacing.sm,
|
||||
marginBottom: spacing.sm,
|
||||
borderRadius: borderRadius.md,
|
||||
},
|
||||
locationErrorText: {
|
||||
flex: 1,
|
||||
fontSize: 13,
|
||||
},
|
||||
retryText: {
|
||||
fontSize: 13,
|
||||
fontWeight: '600',
|
||||
},
|
||||
noPharmacies: {
|
||||
color: colors.textSecondary,
|
||||
textAlign: 'center',
|
||||
padding: spacing.xl,
|
||||
},
|
||||
pharmacyCard: {
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.lg,
|
||||
marginBottom: spacing.sm,
|
||||
overflow: 'hidden',
|
||||
@@ -195,14 +435,27 @@ const styles = StyleSheet.create({
|
||||
pharmacyInfo: {
|
||||
flex: 1,
|
||||
},
|
||||
pharmacyNameRow: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
alignItems: 'center',
|
||||
},
|
||||
pharmacyName: {
|
||||
flex: 1,
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: colors.text,
|
||||
marginRight: spacing.sm,
|
||||
},
|
||||
pharmacyDistance: {
|
||||
fontSize: 12,
|
||||
fontWeight: '600',
|
||||
paddingHorizontal: spacing.sm,
|
||||
paddingVertical: 2,
|
||||
borderRadius: borderRadius.full,
|
||||
overflow: 'hidden',
|
||||
},
|
||||
pharmacyAddress: {
|
||||
fontSize: 14,
|
||||
color: colors.textSecondary,
|
||||
marginTop: spacing.xs,
|
||||
},
|
||||
pharmacyStock: {
|
||||
@@ -211,11 +464,9 @@ const styles = StyleSheet.create({
|
||||
price: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: colors.primary,
|
||||
},
|
||||
stock: {
|
||||
fontSize: 12,
|
||||
color: colors.textSecondary,
|
||||
marginTop: spacing.xs,
|
||||
},
|
||||
directionsButton: {
|
||||
@@ -225,10 +476,8 @@ const styles = StyleSheet.create({
|
||||
gap: spacing.xs,
|
||||
paddingVertical: spacing.sm,
|
||||
borderTopWidth: 1,
|
||||
borderTopColor: colors.border,
|
||||
},
|
||||
directionsText: {
|
||||
color: colors.primary,
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
},
|
||||
@@ -239,6 +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) => (
|
||||
<TouchableOpacity
|
||||
key={med.id}
|
||||
style={styles.medicineCard}
|
||||
onPress={() => router.push(`/medicine/${med.medicine_nregistro}`)}
|
||||
>
|
||||
<View style={styles.medicineInfo}>
|
||||
<Text style={styles.medicineName}>{med.medicine_name}</Text>
|
||||
<Text style={styles.medicineNregistro}>Reg: {med.medicine_nregistro}</Text>
|
||||
medicines.map((med) => {
|
||||
const isSub = subscribedMeds.has(med.medicine_nregistro);
|
||||
return (
|
||||
<View key={med.id} style={[styles.medicineCard, { backgroundColor: colors.card }]}>
|
||||
<TouchableOpacity
|
||||
style={styles.medicineCardContent}
|
||||
onPress={() => router.push(`/medicine/${med.medicine_nregistro}`)}
|
||||
>
|
||||
<View style={styles.medicineInfo}>
|
||||
<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, { 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 style={styles.medicineStock}>
|
||||
<Text style={styles.price}>{med.price.toFixed(2)} €</Text>
|
||||
<Text style={styles.stock}>Stock: {med.stock}</Text>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
))
|
||||
);
|
||||
})
|
||||
)}
|
||||
</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: 602 KiB After Width: | Height: | Size: 325 KiB |
|
Before Width: | Height: | Size: 602 KiB After Width: | Height: | Size: 325 KiB |
|
Before Width: | Height: | Size: 4.0 KiB After Width: | Height: | Size: 325 KiB |
|
After Width: | Height: | Size: 1.5 MiB |
|
Before Width: | Height: | Size: 9.5 KiB After Width: | Height: | Size: 325 KiB |
|
After Width: | Height: | Size: 121 KiB |
|
Before Width: | Height: | Size: 33 KiB After Width: | Height: | Size: 325 KiB |
|
Before Width: | Height: | Size: 602 KiB After Width: | Height: | Size: 325 KiB |
|
Before Width: | Height: | Size: 602 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,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -2,7 +2,8 @@ import React from 'react';
|
||||
import { View, Text, StyleSheet, TouchableOpacity, useWindowDimensions } from 'react-native';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { colors, spacing, borderRadius } from '../constants/theme';
|
||||
import { useThemeContext } from './ThemeProvider';
|
||||
import { spacing, borderRadius } from '../constants/theme';
|
||||
import { StockBadge } from './StockBadge';
|
||||
import { Medicine } from '../types';
|
||||
|
||||
@@ -16,6 +17,7 @@ export function MedicineCard({ medicine }: MedicineCardProps) {
|
||||
const router = useRouter();
|
||||
const { width } = useWindowDimensions();
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
const { colors } = useThemeContext();
|
||||
|
||||
const handlePress = () => {
|
||||
router.push(`/medicine/${medicine.nregistro}`);
|
||||
@@ -23,32 +25,32 @@ export function MedicineCard({ medicine }: MedicineCardProps) {
|
||||
|
||||
return (
|
||||
<TouchableOpacity
|
||||
style={[styles.card, isTablet && styles.cardTablet]}
|
||||
style={[styles.card, isTablet && styles.cardTablet, { backgroundColor: colors.card }]}
|
||||
onPress={handlePress}
|
||||
activeOpacity={0.7}
|
||||
>
|
||||
<View style={styles.header}>
|
||||
<Text style={[styles.name, isTablet && styles.nameTablet]} numberOfLines={2}>
|
||||
<Text style={[styles.name, isTablet && styles.nameTablet, { color: colors.text }]} numberOfLines={2}>
|
||||
{medicine.name}
|
||||
</Text>
|
||||
{medicine.stock != null && <StockBadge stock={medicine.stock} />}
|
||||
</View>
|
||||
|
||||
<Text style={styles.principioActivo} numberOfLines={1}>
|
||||
<Text style={[styles.principioActivo, { color: colors.textSecondary }]} numberOfLines={1}>
|
||||
{medicine.active_ingredient}{medicine.dosage ? ` - ${medicine.dosage}` : ''}
|
||||
</Text>
|
||||
|
||||
<View style={styles.footer}>
|
||||
<View style={styles.priceContainer}>
|
||||
<Ionicons name="pricetag" size={14} color={colors.textSecondary} />
|
||||
<Text style={[styles.price, isTablet && styles.priceTablet]}>
|
||||
<Text style={[styles.price, isTablet && styles.priceTablet, { color: colors.primary }]}>
|
||||
{medicine.precio != null ? `${medicine.precio.toFixed(2)} €` : 'Sin precio'}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<View style={styles.labContainer}>
|
||||
<Ionicons name="business" size={14} color={colors.textSecondary} />
|
||||
<Text style={[styles.laboratorio, isTablet && styles.laboratorioTablet]} numberOfLines={1}>
|
||||
<Text style={[styles.laboratorio, isTablet && styles.laboratorioTablet, { color: colors.textSecondary }]} numberOfLines={1}>
|
||||
{medicine.laboratory}
|
||||
</Text>
|
||||
</View>
|
||||
@@ -59,7 +61,6 @@ export function MedicineCard({ medicine }: MedicineCardProps) {
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
card: {
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.lg,
|
||||
padding: spacing.md,
|
||||
marginHorizontal: spacing.lg,
|
||||
@@ -86,7 +87,6 @@ const styles = StyleSheet.create({
|
||||
flex: 1,
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
color: colors.text,
|
||||
marginRight: spacing.sm,
|
||||
},
|
||||
nameTablet: {
|
||||
@@ -94,7 +94,6 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
principioActivo: {
|
||||
fontSize: 14,
|
||||
color: colors.textSecondary,
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
footer: {
|
||||
@@ -109,7 +108,6 @@ const styles = StyleSheet.create({
|
||||
price: {
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
color: colors.primary,
|
||||
marginLeft: spacing.xs,
|
||||
},
|
||||
priceTablet: {
|
||||
@@ -123,7 +121,6 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
laboratorio: {
|
||||
fontSize: 12,
|
||||
color: colors.textSecondary,
|
||||
marginLeft: spacing.xs,
|
||||
maxWidth: 120,
|
||||
},
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import React, { useState } from 'react';
|
||||
import { View, TextInput, StyleSheet, TouchableOpacity, useWindowDimensions } from 'react-native';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { colors, spacing, borderRadius } from '../constants/theme';
|
||||
import { useThemeContext } from './ThemeProvider';
|
||||
import { spacing, borderRadius } from '../constants/theme';
|
||||
|
||||
const TABLET_MIN_WIDTH = 768;
|
||||
|
||||
@@ -20,6 +21,7 @@ export function SearchBar({
|
||||
}: SearchBarProps) {
|
||||
const { width } = useWindowDimensions();
|
||||
const isTablet = width >= TABLET_MIN_WIDTH;
|
||||
const { colors } = useThemeContext();
|
||||
const [localValue, setLocalValue] = useState(value || '');
|
||||
|
||||
const handleChange = (text: string) => {
|
||||
@@ -38,10 +40,10 @@ export function SearchBar({
|
||||
};
|
||||
|
||||
return (
|
||||
<View style={[styles.container, isTablet && styles.containerTablet]}>
|
||||
<View style={[styles.container, isTablet && styles.containerTablet, { backgroundColor: colors.card }]}>
|
||||
<Ionicons name="search" size={20} color={colors.textSecondary} style={styles.icon} />
|
||||
<TextInput
|
||||
style={[styles.input, isTablet && styles.inputTablet]}
|
||||
style={[styles.input, isTablet && styles.inputTablet, { color: colors.text }]}
|
||||
placeholder={placeholder}
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
value={localValue}
|
||||
@@ -63,15 +65,12 @@ const styles = StyleSheet.create({
|
||||
container: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
backgroundColor: colors.card,
|
||||
borderRadius: borderRadius.lg,
|
||||
paddingHorizontal: spacing.md,
|
||||
paddingVertical: spacing.sm + 2,
|
||||
marginHorizontal: spacing.lg,
|
||||
marginVertical: spacing.sm,
|
||||
maxWidth: 420,
|
||||
alignSelf: 'center',
|
||||
width: '100%',
|
||||
width: '80%',
|
||||
shadowColor: '#000',
|
||||
shadowOffset: { width: 0, height: 2 },
|
||||
shadowOpacity: 0.06,
|
||||
@@ -88,7 +87,6 @@ const styles = StyleSheet.create({
|
||||
input: {
|
||||
flex: 1,
|
||||
fontSize: 16,
|
||||
color: colors.text,
|
||||
paddingVertical: spacing.xs,
|
||||
},
|
||||
inputTablet: {
|
||||
|
||||
@@ -1,27 +1,32 @@
|
||||
import React from 'react';
|
||||
import { View, Text, StyleSheet } from 'react-native';
|
||||
import { colors, borderRadius, spacing } from '../constants/theme';
|
||||
import { useThemeContext } from './ThemeProvider';
|
||||
import { borderRadius, spacing } from '../constants/theme';
|
||||
|
||||
interface StockBadgeProps {
|
||||
stock: number;
|
||||
}
|
||||
|
||||
export function StockBadge({ stock }: StockBadgeProps) {
|
||||
const getBadgeStyle = () => {
|
||||
if (stock === 0) return styles.danger;
|
||||
if (stock < 5) return styles.warning;
|
||||
return styles.success;
|
||||
const { colors, isDark } = useThemeContext();
|
||||
|
||||
const getBadgeColors = () => {
|
||||
if (stock === 0) {
|
||||
return { bg: isDark ? '#3a1a1a' : '#feecec', text: isDark ? '#ef9a9a' : '#b91c1c' };
|
||||
}
|
||||
if (stock < 5) {
|
||||
return { bg: isDark ? '#3a3010' : '#fff3cd', text: isDark ? '#ffd54f' : '#FF9500' };
|
||||
}
|
||||
return { bg: isDark ? '#1a3a1c' : '#eaf7ec', text: isDark ? '#81c784' : '#34C759' };
|
||||
};
|
||||
|
||||
const getText = () => {
|
||||
if (stock === 0) return 'Sin stock';
|
||||
if (stock < 5) return `Bajo (${stock})`;
|
||||
return `Disponible (${stock})`;
|
||||
};
|
||||
const badgeColors = getBadgeColors();
|
||||
|
||||
return (
|
||||
<View style={[styles.badge, getBadgeStyle()]}>
|
||||
<Text style={styles.text}>{getText()}</Text>
|
||||
<View style={[styles.badge, { backgroundColor: badgeColors.bg }]}>
|
||||
<Text style={[styles.text, { color: badgeColors.text }]}>
|
||||
{stock === 0 ? 'Sin stock' : stock < 5 ? `Bajo (${stock})` : `Disponible (${stock})`}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -32,15 +37,6 @@ const styles = StyleSheet.create({
|
||||
paddingVertical: spacing.xs,
|
||||
borderRadius: borderRadius.sm,
|
||||
},
|
||||
success: {
|
||||
backgroundColor: '#eaf7ec',
|
||||
},
|
||||
warning: {
|
||||
backgroundColor: '#fff3cd',
|
||||
},
|
||||
danger: {
|
||||
backgroundColor: '#feecec',
|
||||
},
|
||||
text: {
|
||||
fontSize: 12,
|
||||
fontWeight: '600',
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import React, { createContext, useContext, useEffect, useMemo } from 'react';
|
||||
import { useColorScheme } from 'react-native';
|
||||
import { useThemeStore } from '../store/themeStore';
|
||||
import { colors, darkColors } from '../constants/theme';
|
||||
import type { AppColors } from '../hooks/useThemeColor';
|
||||
|
||||
interface ThemeContextValue {
|
||||
colors: AppColors;
|
||||
isDark: boolean;
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextValue>({
|
||||
colors,
|
||||
isDark: false,
|
||||
});
|
||||
|
||||
export function useThemeContext() {
|
||||
return useContext(ThemeContext);
|
||||
}
|
||||
|
||||
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
||||
const systemScheme = useColorScheme();
|
||||
const mode = useThemeStore((s) => s.mode);
|
||||
const init = useThemeStore((s) => s.init);
|
||||
|
||||
useEffect(() => {
|
||||
init();
|
||||
}, []);
|
||||
|
||||
const value = useMemo(() => {
|
||||
const isDark = mode === 'dark' || (mode === 'system' && systemScheme === 'dark');
|
||||
return {
|
||||
colors: isDark ? darkColors : colors,
|
||||
isDark,
|
||||
};
|
||||
}, [mode, systemScheme]);
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={value}>
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -26,7 +26,7 @@ export const colors = {
|
||||
warning: '#FF9500',
|
||||
|
||||
// Surface
|
||||
background: '#fbfbfb',
|
||||
background: 'transparent',
|
||||
card: '#ffffff',
|
||||
surfaceLow: '#f2f4f5',
|
||||
surface: '#eceeef',
|
||||
@@ -44,6 +44,52 @@ export const colors = {
|
||||
accentWarm: '#f5a97a',
|
||||
};
|
||||
|
||||
export const darkColors = {
|
||||
// Primary - pastel green pharmacy palette
|
||||
primary: '#7fbf8f',
|
||||
primaryLight: '#2a5a35',
|
||||
primaryDark: '#cfead0',
|
||||
onPrimary: '#cfead0',
|
||||
primaryContainer: '#1a3a1c',
|
||||
onPrimaryContainer: '#cfead0',
|
||||
|
||||
// Secondary - soft blue
|
||||
secondary: '#a3b8ff',
|
||||
secondaryContainer: '#1a2a4a',
|
||||
|
||||
// Tertiary - soft lavender
|
||||
tertiary: '#c9b3ff',
|
||||
tertiaryContainer: '#2a1a4a',
|
||||
|
||||
// Scan button - vivid blue
|
||||
scanButton: '#4a7dd5',
|
||||
scanButtonShadow: 'rgba(74, 125, 213, 0.32)',
|
||||
|
||||
// Semantic
|
||||
success: '#34C759',
|
||||
danger: '#ef5350',
|
||||
dangerContainer: '#3a1a1a',
|
||||
warning: '#FF9500',
|
||||
|
||||
// Surface
|
||||
background: '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 = {
|
||||
xs: 4,
|
||||
sm: 8,
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import AsyncStorage from '@react-native-async-storage/async-storage';
|
||||
|
||||
const STORAGE_KEY = 'recent_medicine_searches';
|
||||
const MAX_ITEMS = 5;
|
||||
|
||||
export function useRecentSearches() {
|
||||
const [recentSearches, setRecentSearches] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
AsyncStorage.getItem(STORAGE_KEY).then((data) => {
|
||||
if (data) setRecentSearches(JSON.parse(data));
|
||||
});
|
||||
}, []);
|
||||
|
||||
const addSearch = useCallback(async (query: string) => {
|
||||
const trimmed = query.trim();
|
||||
if (!trimmed) return;
|
||||
setRecentSearches((prev) => {
|
||||
const filtered = prev.filter((s) => s !== trimmed);
|
||||
const next = [trimmed, ...filtered].slice(0, MAX_ITEMS);
|
||||
AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const removeSearch = useCallback(async (query: string) => {
|
||||
setRecentSearches((prev) => {
|
||||
const next = prev.filter((s) => s !== query);
|
||||
AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(next));
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const clearAll = useCallback(async () => {
|
||||
setRecentSearches([]);
|
||||
AsyncStorage.removeItem(STORAGE_KEY);
|
||||
}, []);
|
||||
|
||||
return { recentSearches, addSearch, removeSearch, clearAll };
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { useColorScheme } from 'react-native';
|
||||
import { colors, darkColors } from '../constants/theme';
|
||||
import { useThemeStore, ThemeMode } from '../store/themeStore';
|
||||
|
||||
export type AppColors = typeof colors;
|
||||
|
||||
export function useThemeColor(): { colors: AppColors; isDark: boolean; mode: ThemeMode } {
|
||||
const systemScheme = useColorScheme();
|
||||
const mode = useThemeStore((s) => s.mode);
|
||||
|
||||
const isDark =
|
||||
mode === 'dark' || (mode === 'system' && systemScheme === 'dark');
|
||||
|
||||
return {
|
||||
colors: isDark ? darkColors : colors,
|
||||
isDark,
|
||||
mode,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
const { getDefaultConfig } = require("expo/metro-config");
|
||||
const path = require("path");
|
||||
|
||||
const projectRoot = __dirname;
|
||||
const monorepoRoot = path.resolve(projectRoot, "../..");
|
||||
|
||||
const config = getDefaultConfig(projectRoot);
|
||||
|
||||
// Watch the monorepo root so Metro sees all workspace packages
|
||||
config.watchFolders = [monorepoRoot];
|
||||
|
||||
// Resolve modules from both the workspace and root node_modules
|
||||
config.resolver.nodeModulesPaths = [
|
||||
path.resolve(projectRoot, "node_modules"),
|
||||
path.resolve(monorepoRoot, "node_modules"),
|
||||
];
|
||||
|
||||
// Ensure symlinks are followed (npm workspaces use symlinks)
|
||||
config.resolver.unstable_enableSymlinks = true;
|
||||
|
||||
module.exports = config;
|
||||
@@ -4,6 +4,7 @@
|
||||
"main": "expo-router/entry",
|
||||
"dependencies": {
|
||||
"@expo/vector-icons": "^15.0.2",
|
||||
"@grafana/faro-react-native": "^1.3.0",
|
||||
"@react-native-async-storage/async-storage": "2.2.0",
|
||||
"@tanstack/react-query": "^5.101.2",
|
||||
"axios": "^1.18.1",
|
||||
@@ -16,6 +17,7 @@
|
||||
"expo-image-picker": "~57.0.2",
|
||||
"expo-linking": "~57.0.1",
|
||||
"expo-local-authentication": "~57.0.0",
|
||||
"expo-location": "~57.0.2",
|
||||
"expo-notifications": "~57.0.3",
|
||||
"expo-router": "~57.0.3",
|
||||
"expo-secure-store": "~57.0.0",
|
||||
|
||||
@@ -2,32 +2,43 @@ import axios from 'axios';
|
||||
import * as SecureStore from 'expo-secure-store';
|
||||
import { config } from '../constants/config';
|
||||
|
||||
const SESSION_KEY = 'session_id';
|
||||
|
||||
export const api = axios.create({
|
||||
baseURL: config.API_BASE_URL,
|
||||
timeout: 10000,
|
||||
withCredentials: true,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
// Request interceptor - add auth token
|
||||
// Request interceptor - restore session cookie from SecureStore
|
||||
api.interceptors.request.use(
|
||||
async (axiosConfig) => {
|
||||
const token = await SecureStore.getItemAsync('auth_token');
|
||||
if (token) {
|
||||
axiosConfig.headers.Authorization = `Bearer ${token}`;
|
||||
const session = await SecureStore.getItemAsync(SESSION_KEY);
|
||||
if (session) {
|
||||
axiosConfig.headers.Cookie = session;
|
||||
}
|
||||
return axiosConfig;
|
||||
},
|
||||
(error) => Promise.reject(error)
|
||||
);
|
||||
|
||||
// Response interceptor - handle errors
|
||||
// Response interceptor - capture and persist session cookie from responses
|
||||
api.interceptors.response.use(
|
||||
(response) => response,
|
||||
(response) => {
|
||||
const setCookie = response.headers['set-cookie'];
|
||||
if (setCookie) {
|
||||
const cookieStr = Array.isArray(setCookie) ? setCookie[0] : setCookie;
|
||||
const sessionId = cookieStr.split(';')[0];
|
||||
SecureStore.setItemAsync(SESSION_KEY, sessionId);
|
||||
}
|
||||
return response;
|
||||
},
|
||||
async (error) => {
|
||||
if (error.response?.status === 401) {
|
||||
await SecureStore.deleteItemAsync('auth_token');
|
||||
await SecureStore.deleteItemAsync(SESSION_KEY);
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
|
||||
@@ -2,42 +2,44 @@ import api from './api';
|
||||
import * as SecureStore from 'expo-secure-store';
|
||||
import { AuthResponse, User } from '../types';
|
||||
|
||||
const USER_KEY = 'user_data';
|
||||
|
||||
export async function login(username: string, password: string): Promise<AuthResponse> {
|
||||
const response = await api.post('/auth/login', { username, password });
|
||||
const { user, token } = response.data;
|
||||
const { user } = response.data;
|
||||
|
||||
await SecureStore.setItemAsync('auth_token', token);
|
||||
await SecureStore.setItemAsync('user', JSON.stringify(user));
|
||||
await SecureStore.setItemAsync(USER_KEY, JSON.stringify(user));
|
||||
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function logout(): Promise<void> {
|
||||
await api.post('/auth/logout');
|
||||
await SecureStore.deleteItemAsync('auth_token');
|
||||
await SecureStore.deleteItemAsync('user');
|
||||
await SecureStore.deleteItemAsync(USER_KEY);
|
||||
}
|
||||
|
||||
export async function checkAuth(): Promise<User | null> {
|
||||
try {
|
||||
const response = await api.get('/auth/check');
|
||||
return response.data.user;
|
||||
if (response.data.authenticated) {
|
||||
return response.data.user;
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function getStoredUser(): Promise<User | null> {
|
||||
const userStr = await SecureStore.getItemAsync('user');
|
||||
const userStr = await SecureStore.getItemAsync(USER_KEY);
|
||||
return userStr ? JSON.parse(userStr) : null;
|
||||
}
|
||||
|
||||
export async function register(username: string, password: string): Promise<AuthResponse> {
|
||||
const response = await api.post('/auth/register', { username, password });
|
||||
const { user, token } = response.data;
|
||||
const { user } = response.data;
|
||||
|
||||
await SecureStore.setItemAsync('auth_token', token);
|
||||
await SecureStore.setItemAsync('user', JSON.stringify(user));
|
||||
await SecureStore.setItemAsync(USER_KEY, JSON.stringify(user));
|
||||
|
||||
return response.data;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { initializeFaro } from '@grafana/faro-react-native';
|
||||
|
||||
let initialized = false;
|
||||
|
||||
/**
|
||||
* Initializes Grafana Faro RUM for the React Native app.
|
||||
*
|
||||
* Telemetry (crashes, JS errors, console, app-start, memory/ANR vitals,
|
||||
* session + screen tracking) is sent OTLP/HTTP to the Alloy collector.
|
||||
*
|
||||
* NOTE: `@grafana/faro-react-native` ships a native module, so it requires a
|
||||
* custom dev build / EAS build (not Expo Go). Initialization is wrapped in a
|
||||
* try/catch so a collector outage never crashes the app.
|
||||
*/
|
||||
export function initFaro(): void {
|
||||
if (initialized) return;
|
||||
initialized = true;
|
||||
|
||||
try {
|
||||
const url =
|
||||
process.env.EXPO_PUBLIC_FARO_URL || 'http://grafana.hacecalor.net:4318';
|
||||
|
||||
initializeFaro({
|
||||
app: {
|
||||
name: 'farmafinder-mobile',
|
||||
version: '1.0.0',
|
||||
environment: __DEV__ ? 'development' : 'production',
|
||||
},
|
||||
url,
|
||||
sessionTracking: { enabled: true },
|
||||
// Crash/JS error/console capture are on by default.
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('[faro] initialization failed:', err);
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
},
|
||||
}));
|
||||
@@ -24,15 +24,22 @@ export interface Pharmacy {
|
||||
phone: string;
|
||||
latitude: number;
|
||||
longitude: number;
|
||||
opening_hours?: string;
|
||||
}
|
||||
|
||||
export interface PharmacyMedicine {
|
||||
id: number;
|
||||
pharmacy_id: number;
|
||||
medicine_nregistro: string;
|
||||
medicine_name: string;
|
||||
price: number;
|
||||
stock: number;
|
||||
pharmacy_id?: number;
|
||||
medicine_nregistro?: string;
|
||||
medicine_name?: string;
|
||||
name?: string;
|
||||
address?: string;
|
||||
phone?: string;
|
||||
latitude?: number;
|
||||
longitude?: number;
|
||||
opening_hours?: string;
|
||||
price?: number | null;
|
||||
stock?: number;
|
||||
pharmacy?: Pharmacy;
|
||||
}
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 9.5 KiB After Width: | Height: | Size: 325 KiB |
|
Before Width: | Height: | Size: 93 KiB After Width: | Height: | Size: 325 KiB |
|
Before Width: | Height: | Size: 29 KiB After Width: | Height: | Size: 121 KiB |
|
Before Width: | Height: | Size: 33 KiB After Width: | Height: | Size: 325 KiB |
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 325 KiB |
@@ -24,11 +24,38 @@ function App() {
|
||||
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 = () => {
|
||||
@@ -131,6 +158,8 @@ function App() {
|
||||
onShowSaved={() => setShowSaved(true)}
|
||||
onLogout={handleLogout}
|
||||
onAdminClick={handleAdminClick}
|
||||
theme={theme}
|
||||
onThemeChange={setTheme}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
|
||||
|
After Width: | Height: | Size: 1.5 MiB |
|
After Width: | Height: | Size: 325 KiB |
|
After Width: | Height: | Size: 121 KiB |
@@ -65,9 +65,9 @@
|
||||
height: 3.5rem;
|
||||
border-radius: var(--radius-full);
|
||||
/* Stronger, brighter blue to make scan button easy to find */
|
||||
background: #2b5bb5;
|
||||
color: #ffffff;
|
||||
box-shadow: 0 8px 26px rgba(43, 91, 181, 0.32);
|
||||
background: var(--fab-bg);
|
||||
color: var(--fab-text);
|
||||
box-shadow: 0 8px 26px var(--fab-shadow);
|
||||
margin-top: -1.5rem;
|
||||
transition: transform 0.12s, box-shadow 160ms ease;
|
||||
}
|
||||
@@ -78,12 +78,12 @@
|
||||
|
||||
.nav-fab:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 12px 36px rgba(43, 91, 181, 0.36);
|
||||
box-shadow: 0 12px 36px var(--fab-shadow);
|
||||
}
|
||||
|
||||
.nav-fab:focus {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 6px rgba(43,91,181,0.12), 0 8px 26px rgba(43, 91, 181, 0.32);
|
||||
box-shadow: 0 0 0 6px rgba(43,91,181,0.12), 0 8px 26px var(--fab-shadow);
|
||||
}
|
||||
|
||||
.nav-badge {
|
||||
|
||||
@@ -118,7 +118,7 @@
|
||||
|
||||
.modal-error {
|
||||
font-size: 0.82rem;
|
||||
color: #b91c1c;
|
||||
color: var(--error);
|
||||
margin: 0.25rem 0 0.75rem;
|
||||
}
|
||||
|
||||
@@ -149,7 +149,7 @@
|
||||
.modal-submit {
|
||||
background: var(--primary);
|
||||
border: none;
|
||||
color: #fff;
|
||||
color: var(--on-primary);
|
||||
padding: 0.55rem 1.35rem;
|
||||
border-radius: 999px;
|
||||
cursor: pointer;
|
||||
|
||||
@@ -139,8 +139,8 @@
|
||||
}
|
||||
|
||||
.stock.low-stock {
|
||||
background: rgba(180, 83, 9, 0.12);
|
||||
color: #b45309;
|
||||
background: var(--warning-container);
|
||||
color: var(--warning);
|
||||
}
|
||||
|
||||
.stock.out-of-stock {
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
.product-results {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
|
||||
gap: 1rem;
|
||||
margin-top: 0.5rem;
|
||||
max-height: 70vh;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
overscroll-behavior: contain;
|
||||
animation: fadeInUp 0.5s ease-out;
|
||||
}
|
||||
|
||||
@media (min-width: 1024px) {
|
||||
.product-results {
|
||||
max-height: 76vh;
|
||||
}
|
||||
}
|
||||
|
||||
.product-card {
|
||||
background: var(--surface-container-lowest);
|
||||
border-radius: var(--radius-md);
|
||||
padding: 1.25rem;
|
||||
cursor: pointer;
|
||||
transition: transform 0.15s, box-shadow 0.15s;
|
||||
border: 1px solid var(--outline-variant);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: space-between;
|
||||
box-shadow: var(--shadow-soft);
|
||||
}
|
||||
|
||||
.product-card:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
.product-card-image {
|
||||
width: 100%;
|
||||
height: 120px;
|
||||
margin-bottom: 1rem;
|
||||
overflow: hidden;
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--surface-container-low);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.product-card-image img {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.product-image-placeholder {
|
||||
color: var(--outline-variant);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.product-card-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.product-card-badges {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
.source-badge {
|
||||
color: white;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
.category-badge {
|
||||
background: var(--surface-container-high);
|
||||
color: var(--on-surface-variant);
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.nutri-score-badge {
|
||||
color: white;
|
||||
padding: 0.25rem 0.5rem;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.product-card-header {
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.product-card-header h3 {
|
||||
color: var(--on-surface);
|
||||
font-size: 1.15rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.01em;
|
||||
flex: 1;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.product-card-body {
|
||||
margin-bottom: 1rem;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.product-card-body p {
|
||||
font-size: 0.9rem;
|
||||
color: var(--on-surface-variant);
|
||||
line-height: 1.55;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.product-card-body strong {
|
||||
color: var(--on-surface);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.product-card-footer {
|
||||
padding-top: 0.75rem;
|
||||
border-top: 1px solid var(--outline-variant);
|
||||
}
|
||||
|
||||
.view-details {
|
||||
color: var(--primary);
|
||||
font-weight: 600;
|
||||
font-size: 0.9rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.view-details::after {
|
||||
content: "→";
|
||||
transition: transform 0.2s;
|
||||
}
|
||||
|
||||
.product-card:hover .view-details::after {
|
||||
transform: translateX(4px);
|
||||
}
|
||||
|
||||
.no-results {
|
||||
text-align: center;
|
||||
padding: 2.5rem 1.5rem;
|
||||
background: var(--surface-container-low);
|
||||
border-radius: var(--radius-md);
|
||||
color: var(--on-surface-variant);
|
||||
border: 1px dashed var(--outline-variant);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import React from 'react';
|
||||
import './ProductResults.css';
|
||||
|
||||
const categoryLabels = {
|
||||
otc: 'Sin Receta',
|
||||
baby_food: 'Alimentación Infantil',
|
||||
baby_milk: 'Leche de Fórmula',
|
||||
baby_cereal: 'Cereales Bebé'
|
||||
};
|
||||
|
||||
const sourceColors = {
|
||||
cima: '#2563eb',
|
||||
openfoodfacts: '#16a34a'
|
||||
};
|
||||
|
||||
const sourceLabels = {
|
||||
cima: 'CIMA',
|
||||
openfoodfacts: 'Open Food Facts'
|
||||
};
|
||||
|
||||
function ProductResults({ products, onSelect }) {
|
||||
if (!products || products.length === 0) {
|
||||
return (
|
||||
<div className="no-results">
|
||||
<p>No se encontraron productos</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="product-results">
|
||||
{products.map((product) => (
|
||||
<ProductCard
|
||||
key={product.id}
|
||||
product={product}
|
||||
onSelect={onSelect}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProductCard({ product, onSelect }) {
|
||||
const nutriScore = product.nutriscore;
|
||||
const nutriScoreColors = {
|
||||
a: '#16a34a',
|
||||
b: '#65a30d',
|
||||
c: '#eab308',
|
||||
d: '#f97316',
|
||||
e: '#dc2626'
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="product-card" onClick={() => onSelect(product)}>
|
||||
<div className="product-card-image">
|
||||
{product.image_url ? (
|
||||
<img src={product.image_url} alt={product.name} loading="lazy" />
|
||||
) : (
|
||||
<div className="product-image-placeholder">
|
||||
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
|
||||
<rect x="3" y="3" width="18" height="18" rx="2" ry="2" />
|
||||
<circle cx="8.5" cy="8.5" r="1.5" />
|
||||
<polyline points="21 15 16 10 5 21" />
|
||||
</svg>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="product-card-content">
|
||||
<div className="product-card-badges">
|
||||
<span
|
||||
className="source-badge"
|
||||
style={{ backgroundColor: sourceColors[product.source] }}
|
||||
>
|
||||
{sourceLabels[product.source]}
|
||||
</span>
|
||||
<span className="category-badge">
|
||||
{categoryLabels[product.category] || product.category}
|
||||
</span>
|
||||
{product.source === 'openfoodfacts' && nutriScore && (
|
||||
<span
|
||||
className="nutri-score-badge"
|
||||
style={{ backgroundColor: nutriScoreColors[nutriScore.toLowerCase()] || '#9ca3af' }}
|
||||
>
|
||||
Nutri-Score {nutriScore.toUpperCase()}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="product-card-header">
|
||||
<h3>{product.name}</h3>
|
||||
</div>
|
||||
|
||||
<div className="product-card-body">
|
||||
{product.brand && (
|
||||
<p><strong>Marca:</strong> {product.brand}</p>
|
||||
)}
|
||||
{product.source === 'cima' && product.active_ingredient && (
|
||||
<p><strong>Principio Activo:</strong> {product.active_ingredient}</p>
|
||||
)}
|
||||
{product.source === 'cima' && product.dosage && (
|
||||
<p><strong>Dosis:</strong> {product.dosage}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="product-card-footer">
|
||||
<span className="view-details">Ver detalles →</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ProductResults;
|
||||
@@ -73,7 +73,7 @@
|
||||
}
|
||||
|
||||
.saved-notifications-error {
|
||||
color: #b91c1c;
|
||||
color: var(--error);
|
||||
}
|
||||
|
||||
.saved-notifications-list {
|
||||
@@ -155,8 +155,8 @@
|
||||
}
|
||||
|
||||
.saved-notifications-remove:hover:not(:disabled) {
|
||||
border-color: #b91c1c;
|
||||
color: #b91c1c;
|
||||
border-color: var(--error);
|
||||
color: var(--error);
|
||||
background: rgba(185, 28, 28, 0.06);
|
||||
}
|
||||
|
||||
@@ -175,6 +175,41 @@
|
||||
to { opacity: 1; transform: translateY(0) scale(1); }
|
||||
}
|
||||
|
||||
/* Dark mode adaptations */
|
||||
[data-theme="dark"] .saved-notifications-item {
|
||||
background: var(--surface-container);
|
||||
border-color: var(--border);
|
||||
}
|
||||
|
||||
[data-theme="dark"] .saved-notifications-item-name {
|
||||
color: #b0d4b8;
|
||||
}
|
||||
|
||||
[data-theme="dark"] .saved-notifications-chip {
|
||||
background: rgba(96, 165, 250, 0.15);
|
||||
color: #93c5fd;
|
||||
}
|
||||
|
||||
[data-theme="dark"] .saved-notifications-chip--pharmacy {
|
||||
background: rgba(142, 212, 160, 0.15);
|
||||
color: #8ed4a0;
|
||||
}
|
||||
|
||||
[data-theme="dark"] .saved-notifications-address {
|
||||
color: #9ca3af;
|
||||
}
|
||||
|
||||
[data-theme="dark"] .saved-notifications-remove {
|
||||
border-color: var(--border);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
[data-theme="dark"] .saved-notifications-remove:hover:not(:disabled) {
|
||||
background: rgba(239, 68, 68, 0.12);
|
||||
color: #fca5a5;
|
||||
border-color: #f87171;
|
||||
}
|
||||
|
||||
@media (max-width: 540px) {
|
||||
.saved-notifications-backdrop {
|
||||
padding: 2vh 0.5rem;
|
||||
|
||||
@@ -71,6 +71,101 @@
|
||||
--primary-shadow: rgba(127, 191, 143, 0.12);
|
||||
--primary-light: #eaf7ec;
|
||||
--primary-faint: rgba(127, 191, 143, 0.06);
|
||||
--fab-bg: #2b5bb5;
|
||||
--fab-text: #ffffff;
|
||||
--fab-shadow: rgba(43, 91, 181, 0.32);
|
||||
--warning: #b45309;
|
||||
--warning-container: rgba(180, 83, 9, 0.12);
|
||||
--suggestion-1: #ffffff;
|
||||
--suggestion-2: #f0f7ff;
|
||||
--suggestion-3: #e0f0ff;
|
||||
--suggestion-4: #d4ebff;
|
||||
--suggestion-border-1: #e2e8f0;
|
||||
--suggestion-border-2: #dbeafe;
|
||||
--suggestion-border-3: #bfdbfe;
|
||||
--suggestion-border-4: #93c5fd;
|
||||
--suggestion-text: #1e293b;
|
||||
--suggestion-icon-bg: rgba(59, 130, 246, 0.08);
|
||||
--suggestion-icon-color: #3b82f6;
|
||||
}
|
||||
|
||||
/* ── Dark mode ── */
|
||||
[data-theme="dark"] {
|
||||
--primary: #8ed4a0;
|
||||
--on-primary: #003912;
|
||||
--primary-container: #1a5c2a;
|
||||
--on-primary-container: #c2ecd0;
|
||||
--secondary: #b8c9ff;
|
||||
--on-secondary: #1a3066;
|
||||
--secondary-container: #2a4080;
|
||||
--on-secondary-container: #d9e2ff;
|
||||
--tertiary: #dac4ff;
|
||||
--on-tertiary: #3b2a5a;
|
||||
--tertiary-container: #524070;
|
||||
--on-tertiary-container: #efe7ff;
|
||||
--surface: #1e2024;
|
||||
--on-surface: #e1e3e4;
|
||||
--on-surface-variant: #c0c9bb;
|
||||
--surface-container-lowest: #171a1d;
|
||||
--surface-container-low: #252830;
|
||||
--surface-container: #2c3038;
|
||||
--surface-container-high: #383c44;
|
||||
--surface-container-highest: #444850;
|
||||
--error: #ffb4ab;
|
||||
--on-error: #690005;
|
||||
--error-container: #93000a;
|
||||
--on-error-container: #ffdad6;
|
||||
--outline: #8a9486;
|
||||
--outline-variant: #41493e;
|
||||
--on-background: #e1e3e4;
|
||||
--inverse-surface: #e1e3e4;
|
||||
--inverse-on-surface: #2e3132;
|
||||
--inverse-primary: #2e7d32;
|
||||
--surface-tint: #8ed4a0;
|
||||
--surface-dim: #1e2024;
|
||||
--surface-bright: #4a4e56;
|
||||
--surface-variant: #41493e;
|
||||
--primary-fixed: #acf4a4;
|
||||
--primary-fixed-dim: #91d78a;
|
||||
--secondary-fixed: #d9e2ff;
|
||||
--secondary-fixed-dim: #b0c6ff;
|
||||
--tertiary-fixed: #e9ddff;
|
||||
--tertiary-fixed-dim: #cfbcff;
|
||||
|
||||
--shadow-soft: 0 4px 20px rgba(0, 0, 0, 0.32);
|
||||
|
||||
--text-main: var(--on-surface);
|
||||
--text-muted: var(--on-surface-variant);
|
||||
--surface-muted: var(--surface-container-low);
|
||||
--surface-card: var(--surface-container-lowest);
|
||||
--border: var(--outline-variant);
|
||||
--border-strong: var(--outline);
|
||||
--glass-bg: var(--surface-container);
|
||||
--glass-border: var(--outline-variant);
|
||||
--glass-shadow: var(--shadow-soft);
|
||||
--accent: var(--primary);
|
||||
--accent-warm: #f5a97a;
|
||||
--primary-hover: #a0dfb0;
|
||||
--primary-ring: rgba(142, 212, 160, 0.25);
|
||||
--primary-shadow: rgba(142, 212, 160, 0.15);
|
||||
--primary-light: #0d2b12;
|
||||
--primary-faint: rgba(142, 212, 160, 0.08);
|
||||
--fab-bg: #5b8bd5;
|
||||
--fab-text: #ffffff;
|
||||
--fab-shadow: rgba(91, 139, 213, 0.35);
|
||||
--warning: #f59e0b;
|
||||
--warning-container: rgba(245, 158, 11, 0.15);
|
||||
--suggestion-1: #2c3038;
|
||||
--suggestion-2: #252d40;
|
||||
--suggestion-3: #25334a;
|
||||
--suggestion-4: #253a55;
|
||||
--suggestion-border-1: #333637;
|
||||
--suggestion-border-2: #2a4080;
|
||||
--suggestion-border-3: #2a4a8a;
|
||||
--suggestion-border-4: #3060a0;
|
||||
--suggestion-text: #e1e3e4;
|
||||
--suggestion-icon-bg: rgba(96, 165, 250, 0.12);
|
||||
--suggestion-icon-color: #60a5fa;
|
||||
}
|
||||
|
||||
* {
|
||||
@@ -79,6 +174,14 @@
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html {
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
html, body {
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
@@ -117,6 +220,15 @@ body::after {
|
||||
z-index: -1;
|
||||
}
|
||||
|
||||
[data-theme="dark"] body::before {
|
||||
background-image: url('./assets/bg_dark.png');
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
[data-theme="dark"] body::after {
|
||||
background-color: rgba(0, 0, 0, 0.25);
|
||||
}
|
||||
|
||||
#root {
|
||||
height: 100dvh;
|
||||
overflow: hidden;
|
||||
|
||||
@@ -130,6 +130,42 @@
|
||||
background: var(--surface-container-high);
|
||||
}
|
||||
|
||||
/* Dark mode adaptations */
|
||||
[data-theme="dark"] .alert-card {
|
||||
background: var(--surface-container);
|
||||
}
|
||||
|
||||
[data-theme="dark"] .alert-badge--primary {
|
||||
background: rgba(239, 68, 68, 0.2);
|
||||
color: #fca5a5;
|
||||
}
|
||||
|
||||
[data-theme="dark"] .alert-badge--tertiary {
|
||||
background: rgba(167, 139, 250, 0.2);
|
||||
color: #c4b5fd;
|
||||
}
|
||||
|
||||
[data-theme="dark"] .alert-icon--primary {
|
||||
background: rgba(142, 212, 160, 0.15);
|
||||
color: #8ed4a0;
|
||||
}
|
||||
|
||||
[data-theme="dark"] .alert-icon--tertiary {
|
||||
background: rgba(167, 139, 250, 0.15);
|
||||
color: #a78bfa;
|
||||
}
|
||||
|
||||
[data-theme="dark"] .alert-delete {
|
||||
border-color: var(--border);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
[data-theme="dark"] .alert-delete:hover {
|
||||
background: rgba(239, 68, 68, 0.12);
|
||||
color: #fca5a5;
|
||||
border-color: #f87171;
|
||||
}
|
||||
|
||||
@media (max-width: 400px) {
|
||||
.alerts-title {
|
||||
font-size: 1.5rem;
|
||||
|
||||
@@ -192,9 +192,9 @@
|
||||
|
||||
.home-card--scan {
|
||||
/* Keep the scan button vivid and easy to find (intentionally prominent) */
|
||||
background: #2b5bb5; /* vivid blue to stand out */
|
||||
color: #ffffff;
|
||||
box-shadow: 0 8px 28px rgba(43, 91, 181, 0.28);
|
||||
background: var(--fab-bg);
|
||||
color: var(--fab-text);
|
||||
box-shadow: 0 8px 28px var(--fab-shadow);
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
@@ -204,7 +204,7 @@
|
||||
|
||||
.home-card--scan:focus {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 6px rgba(43,91,181,0.12), 0 8px 28px rgba(43,91,181,0.28);
|
||||
box-shadow: 0 0 0 6px rgba(43,91,181,0.12), 0 8px 28px var(--fab-shadow);
|
||||
}
|
||||
|
||||
.home-card-icon {
|
||||
|
||||
@@ -845,3 +845,63 @@
|
||||
align-self: flex-end;
|
||||
}
|
||||
}
|
||||
|
||||
/* Theme Toggle */
|
||||
.menu-item-theme-label {
|
||||
font-size: 0.8rem;
|
||||
font-weight: 500;
|
||||
color: var(--on-surface-variant);
|
||||
}
|
||||
|
||||
.profile-theme-options {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.profile-theme-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 0.85rem 1rem;
|
||||
background: var(--surface);
|
||||
border: 2px solid var(--outline-variant);
|
||||
border-radius: var(--radius);
|
||||
cursor: pointer;
|
||||
color: var(--on-surface-variant);
|
||||
font-family: inherit;
|
||||
text-align: left;
|
||||
transition: border-color 0.15s, color 0.15s, background 0.15s;
|
||||
}
|
||||
|
||||
.profile-theme-btn:hover {
|
||||
border-color: var(--primary);
|
||||
color: var(--on-surface);
|
||||
}
|
||||
|
||||
.profile-theme-btn--active {
|
||||
border-color: var(--primary);
|
||||
background: var(--primary-faint);
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
.profile-theme-btn--active .profile-theme-btn-label {
|
||||
color: var(--primary);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.profile-theme-btn-label {
|
||||
flex: 1;
|
||||
font-size: 1rem;
|
||||
font-weight: 600;
|
||||
color: var(--on-surface);
|
||||
}
|
||||
|
||||
.profile-theme-btn-desc {
|
||||
font-size: 0.8rem;
|
||||
color: var(--on-surface-variant);
|
||||
}
|
||||
|
||||
.profile-modal-theme {
|
||||
max-width: 24rem;
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ function resolveAvatarUrl(url) {
|
||||
return url;
|
||||
}
|
||||
|
||||
function ProfileView({ currentUser, onProfileSaved, onLogout, onAdminClick }) {
|
||||
function ProfileView({ currentUser, onProfileSaved, onLogout, onAdminClick, theme, onThemeChange }) {
|
||||
const [firstName, setFirstName] = useState(currentUser?.first_name || '');
|
||||
const [lastName, setLastName] = useState(currentUser?.last_name || '');
|
||||
const [avatarUrl, setAvatarUrl] = useState(resolveAvatarUrl(currentUser?.avatar_url));
|
||||
@@ -57,6 +57,9 @@ function ProfileView({ currentUser, onProfileSaved, onLogout, onAdminClick }) {
|
||||
const [configSaving, setConfigSaving] = useState(false);
|
||||
const [configFeedback, setConfigFeedback] = useState(null);
|
||||
|
||||
// Theme modal state
|
||||
const [showTheme, setShowTheme] = useState(false);
|
||||
|
||||
// Addresses modal state
|
||||
const [showAddresses, setShowAddresses] = useState(false);
|
||||
const [addresses, setAddresses] = useState([]);
|
||||
@@ -410,6 +413,21 @@ function ProfileView({ currentUser, onProfileSaved, onLogout, onAdminClick }) {
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
<button className="profile-menu-item" onClick={() => setShowTheme(true)}>
|
||||
<div className="menu-item-icon menu-item-icon--tertiary">
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="M12 3c-4.97 0-9 4.03-9 9s4.03 9 9 9 9-4.03 9-9c0-.46-.04-.92-.1-1.36-.98 1.37-2.58 2.26-4.4 2.26-2.98 0-5.4-2.42-5.4-5.4 0-1.81.89-3.42 2.26-4.4-.44-.06-.9-.1-1.36-.1z" />
|
||||
</svg>
|
||||
</div>
|
||||
<span className="menu-item-label">Tema</span>
|
||||
<span className="menu-item-theme-label">
|
||||
{theme === 'auto' ? 'Automático' : theme === 'light' ? 'Claro' : 'Oscuro'}
|
||||
</span>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="menu-item-chevron">
|
||||
<polyline points="9 18 15 12 9 6" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{searchHistory.length > 0 && (
|
||||
<div className="profile-search-history">
|
||||
<p className="profile-section-sub">Tus búsquedas recientes:</p>
|
||||
@@ -718,6 +736,44 @@ function ProfileView({ currentUser, onProfileSaved, onLogout, onAdminClick }) {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Theme Modal */}
|
||||
{showTheme && (
|
||||
<div className="profile-modal-backdrop" onClick={() => setShowTheme(false)}>
|
||||
<div className="profile-modal profile-modal-theme" onClick={(e) => e.stopPropagation()}>
|
||||
<div className="profile-modal-header">
|
||||
<h3>Tema de visualización</h3>
|
||||
<button className="profile-modal-close" onClick={() => setShowTheme(false)}>×</button>
|
||||
</div>
|
||||
<div className="profile-modal-body">
|
||||
<p className="profile-section-sub">Elige cómo se ve la aplicación. En modo automático, se adapta al tema de tu dispositivo.</p>
|
||||
<div className="profile-theme-options">
|
||||
{[
|
||||
{ value: 'auto', label: 'Automático', desc: 'Seguir sistema', icon: 'M12 3c-4.97 0-9 4.03-9 9s4.03 9 9 9 9-4.03 9-9c0-.46-.04-.92-.1-1.36-.98 1.37-2.58 2.26-4.4 2.26-2.98 0-5.4-2.42-5.4-5.4 0-1.81.89-3.42 2.26-4.4-.44-.06-.9-.1-1.36-.1z' },
|
||||
{ value: 'light', label: 'Claro', desc: 'Siempre claro', icon: 'M12 7c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5zM2 13h2c.55 0 1-.45 1-1s-.45-1-1-1H2c-.55 0-1 .45-1 1s.45 1 1 1zm18 0h2c.55 0 1-.45 1-1s-.45-1-1-1h-2c-.55 0-1 .45-1 1s.45 1 1 1zM11 2v2c0 .55.45 1 1 1s1-.45 1-1V2c0-.55-.45-1-1-1s-1 .45-1 1zm0 18v2c0 .55.45 1 1 1s1-.45 1-1v-2c0-.55-.45-1-1-1s-1 .45-1 1zM5.99 4.58c-.39-.39-1.03-.39-1.42 0-.39.39-.39 1.03 0 1.42l1.06 1.06c.39.39 1.03.39 1.42 0s.39-1.03 0-1.42L5.99 4.58zm12.37 12.37c-.39-.39-1.03-.39-1.42 0-.39.39-.39 1.03 0 1.42l1.06 1.06c.39.39 1.03.39 1.42 0 .39-.39.39-1.03 0-1.42l-1.06-1.06zm1.06-10.96c.39-.39.39-1.03 0-1.42-.39-.39-1.03-.39-1.42 0l-1.06 1.06c-.39.39-.39 1.03 0 1.42s1.03.39 1.42 0l1.06-1.06zM7.05 18.36c.39-.39.39-1.03 0-1.42-.39-.39-1.03-.39-1.42 0l-1.06 1.06c-.39.39-.39 1.03 0 1.42s1.03.39 1.42 0l1.06-1.06z' },
|
||||
{ value: 'dark', label: 'Oscuro', desc: 'Siempre oscuro', icon: 'M12 3c-4.97 0-9 4.03-9 9s4.03 9 9 9 9-4.03 9-9c0-.46-.04-.92-.1-1.36-.98 1.37-2.58 2.26-4.4 2.26-2.98 0-5.4-2.42-5.4-5.4 0-1.81.89-3.42 2.26-4.4-.44-.06-.9-.1-1.36-.1z' },
|
||||
].map(({ value, label, desc, icon }) => (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
className={`profile-theme-btn ${theme === value ? 'profile-theme-btn--active' : ''}`}
|
||||
onClick={() => {
|
||||
onThemeChange(value);
|
||||
setShowTheme(false);
|
||||
}}
|
||||
>
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d={icon} />
|
||||
</svg>
|
||||
<span className="profile-theme-btn-label">{label}</span>
|
||||
<span className="profile-theme-btn-desc">{desc}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import React, { useState, useEffect, useMemo } from 'react';
|
||||
import '../App.css';
|
||||
import SearchBar from '../components/SearchBar';
|
||||
import MedicineResults from '../components/MedicineResults';
|
||||
import ProductResults from '../components/ProductResults';
|
||||
import PharmacyList from '../components/PharmacyList';
|
||||
import PharmacyMap from '../components/PharmacyMap';
|
||||
import HomeView from './HomeView';
|
||||
@@ -22,6 +23,8 @@ function PublicView({
|
||||
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
const [medicines, setMedicines] = useState([]);
|
||||
const [products, setProducts] = useState([]);
|
||||
const [searchMode, setSearchMode] = useState('all'); // 'all' | 'medicines' | 'products'
|
||||
const [selectedMedicine, setSelectedMedicine] = useState(null);
|
||||
const [pharmacies, setPharmacies] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -35,6 +38,7 @@ function PublicView({
|
||||
const searchMedicines = async () => {
|
||||
if (searchQuery.trim().length < 2) {
|
||||
setMedicines([]);
|
||||
setProducts([]);
|
||||
setSelectedMedicine(null);
|
||||
setPharmacies([]);
|
||||
return;
|
||||
@@ -50,6 +54,16 @@ function PublicView({
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
try {
|
||||
const productsResponse = await fetch(`/api/products/search?q=${encodeURIComponent(searchQuery)}`);
|
||||
if (productsResponse.ok) {
|
||||
const productsData = await productsResponse.json();
|
||||
setProducts(productsData.results || []);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Product search error:', err);
|
||||
}
|
||||
};
|
||||
|
||||
const timeoutId = setTimeout(searchMedicines, 300);
|
||||
@@ -219,7 +233,42 @@ function PublicView({
|
||||
|
||||
{loading && <div className="loading">Buscando...</div>}
|
||||
|
||||
{searchQuery && !selectedMedicine && (
|
||||
{searchQuery && (
|
||||
<div className="flex gap-2 mb-4">
|
||||
<button
|
||||
onClick={() => setSearchMode('all')}
|
||||
className={`px-3 py-1.5 rounded-full text-sm font-medium transition-colors ${
|
||||
searchMode === 'all'
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
Todos
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setSearchMode('medicines')}
|
||||
className={`px-3 py-1.5 rounded-full text-sm font-medium transition-colors ${
|
||||
searchMode === 'medicines'
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
Medicamentos
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setSearchMode('products')}
|
||||
className={`px-3 py-1.5 rounded-full text-sm font-medium transition-colors ${
|
||||
searchMode === 'products'
|
||||
? 'bg-blue-600 text-white'
|
||||
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
|
||||
}`}
|
||||
>
|
||||
Parafarmacia
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{searchQuery && !selectedMedicine && (searchMode === 'all' || searchMode === 'medicines') && (
|
||||
<MedicineResults
|
||||
medicines={medicines}
|
||||
onSelect={setSelectedMedicine}
|
||||
@@ -229,6 +278,18 @@ function PublicView({
|
||||
/>
|
||||
)}
|
||||
|
||||
{(searchMode === 'all' || searchMode === 'products') && products.length > 0 && (
|
||||
<div className="mt-6">
|
||||
<h3 className="text-lg font-semibold mb-3">Parafarmacia y Bebé</h3>
|
||||
<ProductResults
|
||||
products={products}
|
||||
onSelect={(product) => {
|
||||
window.location.href = `/product/${product.source}/${product.id}`;
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedMedicine && (
|
||||
<div className="selected-medicine-section">
|
||||
<div className="medicine-info">
|
||||
|
||||
@@ -57,36 +57,44 @@
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
[data-theme="dark"] .suggestion-btn:hover {
|
||||
background: #07243d;
|
||||
}
|
||||
|
||||
.suggestion-btn--neutral-1 {
|
||||
background: #ffffff;
|
||||
color: #1e293b;
|
||||
border: 1px solid #e2e8f0;
|
||||
background: var(--suggestion-1);
|
||||
color: var(--suggestion-text);
|
||||
border: 1px solid var(--suggestion-border-1);
|
||||
}
|
||||
|
||||
[data-theme="dark"] .suggestion-btn--neutral-1:hover {
|
||||
background: #1e2225;
|
||||
}
|
||||
|
||||
.suggestion-btn--neutral-2 {
|
||||
background: #f0f7ff;
|
||||
color: #1e293b;
|
||||
border: 1px solid #dbeafe;
|
||||
background: var(--suggestion-2);
|
||||
color: var(--suggestion-text);
|
||||
border: 1px solid var(--suggestion-border-2);
|
||||
}
|
||||
|
||||
.suggestion-btn--neutral-3 {
|
||||
background: #e0f0ff;
|
||||
color: #1e293b;
|
||||
border: 1px solid #bfdbfe;
|
||||
background: var(--suggestion-3);
|
||||
color: var(--suggestion-text);
|
||||
border: 1px solid var(--suggestion-border-3);
|
||||
}
|
||||
|
||||
.suggestion-btn--neutral-4 {
|
||||
background: #d4ebff;
|
||||
color: #1e293b;
|
||||
border: 1px solid #93c5fd;
|
||||
background: var(--suggestion-4);
|
||||
color: var(--suggestion-text);
|
||||
border: 1px solid var(--suggestion-border-4);
|
||||
}
|
||||
|
||||
.suggestion-icon {
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
border-radius: var(--radius);
|
||||
background: rgba(59, 130, 246, 0.08);
|
||||
color: #3b82f6;
|
||||
background: var(--suggestion-icon-bg);
|
||||
color: var(--suggestion-icon-color);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
@@ -149,6 +157,10 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
[data-theme="dark"] .recent-tag {
|
||||
background: #2c3038;
|
||||
}
|
||||
|
||||
.recent-distance {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -175,6 +187,10 @@
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
|
||||
[data-theme="dark"] .recent-btn {
|
||||
background: #053d13;
|
||||
}
|
||||
|
||||
.recent-btn:active {
|
||||
opacity: 0.85;
|
||||
}
|
||||
@@ -321,7 +337,7 @@
|
||||
|
||||
.retry-location-btn {
|
||||
background: var(--error);
|
||||
color: white;
|
||||
color: var(--on-error);
|
||||
border: none;
|
||||
padding: 0.25rem 0.6rem;
|
||||
border-radius: var(--radius);
|
||||
|
||||
@@ -38,6 +38,7 @@ services:
|
||||
OTEL_SERVICE_NAME: farmafinder-backend
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: http://host.docker.internal:4317
|
||||
OTEL_TRACES_EXPORTER: otlp
|
||||
OTEL_METRICS_EXPORTER: otlp
|
||||
OTEL_LOGS_EXPORTER: otlp
|
||||
OTEL_RESOURCE_ATTRIBUTES: service.namespace=farmafinder
|
||||
volumes:
|
||||
@@ -61,6 +62,28 @@ services:
|
||||
depends_on:
|
||||
- backend
|
||||
|
||||
# --- Observability exporters (scraped by the shared Prometheus on srv84-macos) ---
|
||||
redis-exporter:
|
||||
image: oliver006/redis_exporter:latest
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "9121:9121"
|
||||
environment:
|
||||
REDIS_ADDR: redis://redis:6379
|
||||
REDIS_PASSWORD: ${REDIS_PASSWORD:-}
|
||||
depends_on:
|
||||
- redis
|
||||
|
||||
postgres-exporter:
|
||||
image: prometheuscommunity/postgres-exporter:latest
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "9187:9187"
|
||||
environment:
|
||||
DATA_SOURCE_NAME: postgresql://farmafinder:${PG_PASSWORD:-change-me-in-production}@postgres:5432/farmafinder?sslmode=disable
|
||||
depends_on:
|
||||
- postgres
|
||||
|
||||
volumes:
|
||||
backend_data:
|
||||
postgres_data:
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
# FarmaFinder — End-to-End Observability Plan & Progress
|
||||
|
||||
> **Purpose:** Single source of truth for adding metrics + monitoring across the
|
||||
> FarmaFinder stack. If the session runs out of tokens, a fresh session can read
|
||||
> this file and continue from the **Status** section.
|
||||
>
|
||||
> Created: 2026-07-13
|
||||
|
||||
---
|
||||
|
||||
## 1. Current State (verified)
|
||||
|
||||
### 1.1 Monitoring stack — `srv84-macos:/root/Monitoring` (Docker Compose)
|
||||
Running services (verified live):
|
||||
|
||||
| Service | Port | Role |
|
||||
|---|---|---|
|
||||
| Prometheus `v2.55.1` | 9090 | metrics + alerting (config `/etc/prometheus/`) |
|
||||
| Grafana `grafana/grafana` | 3000 | dashboards (admin `foobar`) |
|
||||
| Alertmanager `v0.27.0` | 9093 | **Telegram** notifications (already configured) |
|
||||
| Loki `latest` | 3100 | logs (`/otlp` receiver enabled) |
|
||||
| Tempo `latest` | 3200 | traces |
|
||||
| cAdvisor | 8080 | container metrics |
|
||||
| node-exporter | 9100 | host metrics (srv84-macos + srv102-hosting + srv104-omv) |
|
||||
| **Alloy `v1.6.1`** | 4317 gRPC / 4318 HTTP / 12345 self | unified OTel collector |
|
||||
|
||||
**Alloy pipeline (`alloy-config.alloy`):**
|
||||
`otelcol.receiver.otlp` (gRPC+HTTP) → `batch` →
|
||||
- traces → `otelp.tempo` (Tempo:4317)
|
||||
- logs → `otlphttp.loki` (Loki:3100/otlp)
|
||||
- metrics → `exporter.prometheus` → `prometheus.remote_write` → `http://prometheus:9090/api/v1/write`
|
||||
|
||||
So **any OTLP metrics sent to Alloy land in Prometheus automatically** — no new scrape job needed for app services.
|
||||
|
||||
### 1.2 Grafana datasources (provisioned, sufficient)
|
||||
Prometheus (default), Tempo, Loki, PostgreSQL, Alertmanager.
|
||||
|
||||
### 1.3 Grafana plugins (installed, sufficient)
|
||||
Built-in panels + **Drilldown apps**: `grafana-lokiexplore-app`, `grafana-metricsdrilldown-app`, `grafana-exploretraces-app`, `grafana-pyroscope-app`.
|
||||
**No extra plugins required.**
|
||||
|
||||
### 1.4 Existing app instrumentation
|
||||
| App | Traces | Metrics | Logs | Health | Notes |
|
||||
|---|---|---|---|---|---|
|
||||
| backend (Express) | ✅ OTel→Alloy | ❌ **none** | ✅ pino→Alloy | ❌ none | `src/tracing.js` boots NodeSDK; only traces+logs exported |
|
||||
| frontend (React/Vite PWA) | ✅ Faro→Alloy:4318 | ❌ | ✅ Faro→Loki | — | `src/utils/faro.js`; dashboards `faro-overview/-web-vitals/-js-errors` exist |
|
||||
| frontend-mobile (Expo RN) | ❌ | ❌ | console only | — | **no observability at all** |
|
||||
| pip-platform (FastAPI) | ✅ OTel | ✅ `/metrics` (prometheus_client) | ✅ structlog | ✅ /system/health,/ready,/status | **not scraped by Prometheus yet** |
|
||||
| scraper (Puppeteer) | ✅ OTel | ❌ | console | — | |
|
||||
|
||||
### 1.5 Prometheus scrape jobs (today)
|
||||
`prometheus`, `cadvisor`, `node-exporter` (x3 hosts). **No farmafinder/pip/redis/postgres jobs.**
|
||||
Comment in `prometheus.yml`: app metrics are expected via OTLP→Alloy→remote_write.
|
||||
|
||||
### 1.6 Existing Prometheus alerts (`alert.rules`)
|
||||
`service_down`, `high_load`, `high_memory`, `disk_almost_full`, `pm2_process_down`, `container_down`. All infra-level.
|
||||
|
||||
---
|
||||
|
||||
## 2. Decisions (confirmed with user)
|
||||
|
||||
- **Metrics transport = OTLP** for backend + mobile (aligns with stack design; no new app scrape jobs). Infra exporters (Redis/Postgres/pip) stay as scrape jobs.
|
||||
- **Mobile Faro endpoint:** env-configurable `EXPO_PUBLIC_FARO_URL`, default
|
||||
`http://grafana.hacecalor.net:4318`. User will **open router port 4318 → srv84-macos:4318**
|
||||
(and/or fix Nginx Proxy Manager `/faro` proxy to Alloy:4318). Devices are NOT on the docker
|
||||
host, so `localhost` will NOT work.
|
||||
- **Alertmanager:** Telegram already configured — **no contact-point change**. New rules just route to it.
|
||||
|
||||
---
|
||||
|
||||
## 3. Design / Tasks
|
||||
|
||||
### Task A — Backend metrics (OTel → Alloy → Prometheus)
|
||||
**Files:** `apps/backend/src/tracing.js`, `apps/backend/src/metrics.js` (new), `apps/backend/package.json`, `docker-compose.yml`.
|
||||
|
||||
1. Add metrics SDK to `tracing.js`:
|
||||
- `MeterProvider` + `OTLPMetricExporter` + `PeriodicExportingMetricReader` (interval 15s).
|
||||
- Reuse existing `resource` + `getNodeAutoInstrumentations` (already includes http/express/redis → gives `http.server.request.duration`, `http.client.request.duration`, `redis.client.commands.duration`, etc.).
|
||||
- Keep `PinoInstrumentation`. Gate on `NODE_ENV !== 'test'`.
|
||||
2. New `src/metrics.js` using `@opentelemetry/api` `metrics`:
|
||||
- `medicine_searches_total` (counter)
|
||||
- `cima_request_duration_ms` (histogram), `cima_errors_total` (counter)
|
||||
- `cache_hits_total` / `cache_misses_total` (counters)
|
||||
- `login_success_total` / `login_failure_total` (counters)
|
||||
- `rate_limit_rejected_total` (counter, label `route`)
|
||||
- `pharmacy_write_total` (counter, label `op`)
|
||||
- `pharmacy_medicine_link_total` (counter)
|
||||
- `push_sent_total` / `push_failed_total` (counters, label `channel=expo|web`)
|
||||
- `db_query_duration_ms` (histogram), `db_errors_total` (counter, label `engine=sqlite|pg`)
|
||||
- `redis_errors_total` (counter), `redis_cmd_duration_ms` (histogram)
|
||||
- `heartbeat_total` (counter, incremented every 30s) → drives "backend down" alert
|
||||
- Node runtime metrics via `views`/runtime instrumentation (event loop lag, heap, gc).
|
||||
3. Instrument the relevant handlers in `server.js` (search, auth, admin, notifications, db, redis) by importing the meters.
|
||||
4. `docker-compose.yml`: add `OTEL_METRICS_EXPORTER: otlp` under backend env (alongside existing traces/logs exporters).
|
||||
5. `package.json`: ensure `@opentelemetry/sdk-metrics` + `@opentelemetry/exporter-metrics-otlp-grpc` are present (add if missing; align versions with existing `^0.55.0`).
|
||||
|
||||
### Task B — Backend health endpoints
|
||||
**File:** `apps/backend/server.js`.
|
||||
- `GET /healthz` → `{status:"ok"}` (liveness).
|
||||
- `GET /readyz` → ping Redis + run a trivial DB query; return 200/503 JSON.
|
||||
- Used by Docker healthcheck / k8s; not scraped.
|
||||
|
||||
### Task C — Mobile RUM (Expo / React Native)
|
||||
**Files:** `apps/frontend-mobile/package.json`, `apps/frontend-mobile/app/_layout.tsx` (root), `.env.example`.
|
||||
- Add dependency `@grafana/faro-react-native` (`^1.2.1`).
|
||||
- Init in `_layout.tsx` (or `App.tsx`) entry:
|
||||
```ts
|
||||
import { initializeFaro } from '@grafana/faro-react-native';
|
||||
initializeFaro({
|
||||
app: { name: 'farmafinder-mobile', version: '1.0.0', environment: 'production' },
|
||||
url: process.env.EXPO_PUBLIC_FARO_URL || 'http://grafana.hacecalor.net:4318',
|
||||
sessionTracking: { enabled: true },
|
||||
// captures crashes, JS errors, console, ANR(Android), app-start, memory vitals
|
||||
});
|
||||
```
|
||||
- `EXPO_PUBLIC_FARO_URL` in `.env.example` (default the public URL above).
|
||||
- Optional follow-up: `@grafana/faro-react-native-tracing` for distributed traces + `@grafana/faro-metro-plugin` for source maps (post-MVP).
|
||||
|
||||
### Task D — Infra exporters (scrape jobs on `srv84-macos`)
|
||||
**Files (remote):** `/root/Monitoring/docker-compose.yml`, `/root/Monitoring/prometheus/prometheus.yml`.
|
||||
- Add containers `redis-exporter` (→ farmafinder redis) and `postgres-exporter` (→ farmafinder postgres) to the Monitoring compose. Reach farmafinder's redis/postgres via the docker gateway / service DNS on the same host.
|
||||
- Add scrape jobs in `prometheus.yml`:
|
||||
- `farmafinder-redis` → redis-exporter
|
||||
- `farmafinder-postgres` → postgres-exporter
|
||||
- `pip-platform` → `http://<pip-host>:8000/metrics` (pip already exposes it)
|
||||
- Reload Prometheus (`POST /-/reload`).
|
||||
|
||||
### Task E — Grafana dashboards (provisioned JSON)
|
||||
**Files:** `/root/Monitoring/grafana/provisioning/dashboards/*.json` + `dashboard.yml` entry.
|
||||
1. `farmafinder-backend.json` — req rate, error %, latency p50/p95/p99 by route, CIMA latency/errors, cache hit rate, Redis/DB errors, push counts, auth failures, rate-limit hits, Node runtime.
|
||||
2. `farmafinder-datastores.json` — Redis + Postgres + (SQLite via app metric) panels.
|
||||
3. `farmafinder-mobile-rum.json` — Faro RN data from Loki (`app.name="farmafinder-mobile"`).
|
||||
4. `farmafinder-overview.json` — combined RUM + backend metrics + deep-links to Tempo (traces) & Loki (logs).
|
||||
(Keep existing `faro-*` PWA dashboards.)
|
||||
|
||||
### Task F — Alerts
|
||||
**Files (remote):** `/root/Monitoring/prometheus/alert.rules` + Grafana-managed alert.
|
||||
Prometheus rules (group `farmafinder`):
|
||||
- `farmafinder_backend_down` — `absent(heartbeat_total{job="farmafinder-backend"}) > 0` for 5m → critical
|
||||
- `farmafinder_backend_5xx` — `rate(http.server.request.errors ...)` ratio > 5% over 5m → warning
|
||||
- `farmafinder_cima_errors` — CIMA error rate high → warning
|
||||
- `farmafinder_high_latency` — p95 `http.server.request.duration` > threshold → warning
|
||||
- `farmafinder_redis_down` / `farmafinder_postgres_down` / `pip_platform_down` — `up==0`
|
||||
Grafana-managed alert (Loki): **mobile/PWA JS-error spike** — count of Faro exceptions over 10m > N.
|
||||
All route to existing Alertmanager (Telegram).
|
||||
|
||||
### Task G — Mobile Faro reachability (user action)
|
||||
- Open router `TCP 4318 → srv84-macos:4318`, **or** fix Nginx Proxy Manager `grafana.hacecalor.net/faro` → `http://<alloy-host>:4318` ensuring OTLP HTTP paths (`/v1/logs`,`/v1/metrics`,`/v1/traces`) are proxied. Verify from a phone / external curl that `POST http://grafana.hacecalor.net:4318/v1/logs` is accepted.
|
||||
|
||||
---
|
||||
|
||||
## 4. Status (update as you go)
|
||||
|
||||
| Task | Status | Notes |
|
||||
|---|---|---|
|
||||
| A. Backend metrics | ✅ done (code) | `src/metrics.js`, `tracing.js` meter provider, instrumented server.js/cima-service.js/redis-client.js. Needs backend rebuild+redeploy to take effect. |
|
||||
| B. Backend health | ✅ done (code) | `/healthz`, `/readyz` added. |
|
||||
| C. Mobile Faro | ✅ done (code) | `services/faro.ts` + `_layout.tsx` init + dep `@grafana/faro-react-native`. Requires dev/EAS build (native module). |
|
||||
| D. Infra exporters | ✅ done | redis/postgres exporters added to farmafinder `docker-compose.yml`; Prometheus scrape jobs + alert rules applied on srv84-macos. Needs farmafinder redeploy. |
|
||||
| E. Dashboards | ✅ done + LIVE | 4 dashboards pushed to `/root/Monitoring/grafana/provisioning/dashboards/` and provisioned in Grafana. |
|
||||
| F. Alerts | ✅ done + LIVE | `farmafinder` group applied to `alert.rules`; routes to existing Alertmanager (Telegram). |
|
||||
| G. Mobile Faro URL | ⏳ user action | open :4318 → srv84-macos:4318, or fix Nginx Proxy Manager `/faro`. |
|
||||
|
||||
## 5. Deployment & Verification
|
||||
|
||||
### Backend (apply on next deploy)
|
||||
The running `farmafinder-backend-1` still runs old code. To activate metrics:
|
||||
```bash
|
||||
# from repo root on srv84-macos (or wherever farmafinder is deployed)
|
||||
docker compose build backend && docker compose up -d backend
|
||||
# or push to main and let .gitea deploy
|
||||
```
|
||||
Verify:
|
||||
```bash
|
||||
# after ~30s, a heartbeat sample should exist
|
||||
curl -s "http://srv84-macos:9090/api/v1/query?query=app_heartbeat_total{job=%22farmafinder-backend%22}"
|
||||
# health probes
|
||||
curl -s http://localhost:3001/healthz ; curl -s http://localhost:3001/readyz
|
||||
# dashboards populate: Grafana → FarmaFinder — Backend
|
||||
```
|
||||
|
||||
### Mobile (user)
|
||||
1. `cd apps/frontend-mobile && npm install` (pulls `@grafana/faro-react-native`).
|
||||
2. Build a **dev/EAS build** (not Expo Go — native module).
|
||||
3. Set `EXPO_PUBLIC_FARO_URL` (default `http://grafana.hacecalor.net:4318`) reachable from device.
|
||||
4. Verify in Grafana → FarmaFinder — Mobile RUM (Loki `{app="farmafinder-mobile"}`).
|
||||
|
||||
### Datastore exporters (apply on farmafinder redeploy)
|
||||
`docker compose up -d` brings up `redis-exporter` (`:9121`) and `postgres-exporter` (`:9187`);
|
||||
Prometheus already scrapes them. Verify: `up{job="farmafinder-redis"}`, `up{job="farmafinder-postgres"}`.
|
||||
|
||||
## 6. Verification checklist (end)
|
||||
- [x] 4 Grafana dashboards live (backend, datastores, mobile-rum, overview)
|
||||
- [x] Prometheus scrape jobs `farmafinder-redis` / `farmafinder-postgres` present
|
||||
- [x] Alert rules `farmafinder_*` loaded (no config errors)
|
||||
- [ ] Backend redeployed → `app_heartbeat_total`, `http_requests_total`, `cima_requests_total`, etc. appear
|
||||
- [ ] `/healthz`, `/readyz` return 200
|
||||
- [ ] Mobile build → Faro data in Loki + Mobile RUM dashboard
|
||||
- [ ] Trigger a test alert (stop backend) → Telegram receives it
|
||||
|
||||
## 7. Key commands / references
|
||||
- Remote stack: `ssh root@srv84-macos`, configs under `/root/Monitoring`.
|
||||
- Prometheus reload: `curl -X POST http://srv84-macos:9090/-/reload`.
|
||||
- Grafana dashboards reload: `curl -u admin:foobar -X POST http://srv84-macos:3000/api/admin/provisioning/dashboards/reload`.
|
||||
- Grafana API: `curl -u admin:foobar http://srv84-macos:3000/api/...` (admin password `foobar`).
|
||||
- Backend OTel env (in `docker-compose.yml`): `OTEL_SERVICE_NAME=farmafinder-backend`, `OTEL_EXPORTER_OTLP_ENDPOINT=http://host.docker.internal:4317`, `OTEL_TRACES_EXPORTER=otlp`, **`OTEL_METRICS_EXPORTER=otlp`** (added), `OTEL_LOGS_EXPORTER=otlp`.
|
||||
- New metrics module: `apps/backend/src/metrics.js`.
|
||||
- Dashboards source: `monitoring/dashboards/*.json` (mirrored on the host).
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"cli": {
|
||||
"version": ">= 20.5.1",
|
||||
"appVersionSource": "remote"
|
||||
},
|
||||
"build": {
|
||||
"development": {
|
||||
"developmentClient": true,
|
||||
"distribution": "internal"
|
||||
},
|
||||
"preview": {
|
||||
"distribution": "internal"
|
||||
},
|
||||
"production": {
|
||||
"autoIncrement": true
|
||||
}
|
||||
},
|
||||
"submit": {
|
||||
"production": {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
{
|
||||
"annotations": { "list": [] },
|
||||
"editable": true,
|
||||
"fiscalYearStartMonth": 0,
|
||||
"graphTooltip": 1,
|
||||
"id": null,
|
||||
"links": [],
|
||||
"liveNow": false,
|
||||
"panels": [
|
||||
{
|
||||
"id": 1, "title": "Request rate (req/s)", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 8, "x": 0, "y": 0 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [
|
||||
{ "expr": "sum(rate(http_requests_total{job=\"farmafinder-backend\"}[5m]))", "legendFormat": "req/s" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2, "title": "Requests by status class", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 8, "x": 8, "y": 0 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [
|
||||
{ "expr": "sum by (status_class) (rate(http_requests_total{job=\"farmafinder-backend\"}[5m]))", "legendFormat": "{{status_class}}" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3, "title": "5xx error rate", "type": "stat",
|
||||
"gridPos": { "h": 6, "w": 8, "x": 16, "y": 0 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [
|
||||
{ "expr": "sum(rate(http_requests_total{status_class=\"5xx\",job=\"farmafinder-backend\"}[5m])) / sum(rate(http_requests_total{job=\"farmafinder-backend\"}[5m]))", "legendFormat": "5xx ratio" }
|
||||
],
|
||||
"fieldConfig": { "defaults": { "unit": "percentunit", "thresholds": { "steps": [ { "color": "green", "value": 0 }, { "color": "yellow", "value": 0.01 }, { "color": "red", "value": 0.05 } ] } } }
|
||||
},
|
||||
{
|
||||
"id": 4, "title": "HTTP p95 latency (route)", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 12, "x": 0, "y": 6 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [
|
||||
{ "expr": "histogram_quantile(0.95, sum by (le, route) (rate(http_request_duration_ms_bucket{job=\"farmafinder-backend\"}[5m])))", "legendFormat": "{{route}} p95" }
|
||||
],
|
||||
"fieldConfig": { "defaults": { "unit": "ms" } }
|
||||
},
|
||||
{
|
||||
"id": 5, "title": "Medicine searches / CIMA requests", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 12, "x": 12, "y": 6 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [
|
||||
{ "expr": "sum(rate(medicine_searches_total{job=\"farmafinder-backend\"}[5m]))", "legendFormat": "searches/s" },
|
||||
{ "expr": "sum(rate(cima_requests_total{job=\"farmafinder-backend\"}[5m]))", "legendFormat": "cima req/s" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6, "title": "Cache hit ratio", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 8, "x": 0, "y": 12 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [
|
||||
{ "expr": "sum(rate(cache_hits_total{job=\"farmafinder-backend\"}[5m])) / (sum(rate(cache_hits_total{job=\"farmafinder-backend\"}[5m])) + sum(rate(cache_misses_total{job=\"farmafinder-backend\"}[5m])))", "legendFormat": "hit ratio" }
|
||||
],
|
||||
"fieldConfig": { "defaults": { "unit": "percentunit" } }
|
||||
},
|
||||
{
|
||||
"id": 7, "title": "CIMA API errors", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 8, "x": 8, "y": 12 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [
|
||||
{ "expr": "sum(rate(cima_requests_total{status=\"error\",job=\"farmafinder-backend\"}[5m]))", "legendFormat": "errors/s" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 8, "title": "Logins (success / failure)", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 8, "x": 16, "y": 12 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [
|
||||
{ "expr": "sum(rate(login_success_total{job=\"farmafinder-backend\"}[5m]))", "legendFormat": "success/s" },
|
||||
{ "expr": "sum(rate(login_failure_total{job=\"farmafinder-backend\"}[5m]))", "legendFormat": "failure/s" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 9, "title": "Rate-limit rejections (by route)", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 12, "x": 0, "y": 18 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [
|
||||
{ "expr": "sum by (route) (rate(rate_limit_rejected_total{job=\"farmafinder-backend\"}[5m]))", "legendFormat": "{{route}}" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 10, "title": "Push notifications (sent / failed)", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 12, "x": 12, "y": 18 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [
|
||||
{ "expr": "sum by (channel) (rate(push_sent_total{job=\"farmafinder-backend\"}[5m]))", "legendFormat": "sent {{channel}}" },
|
||||
{ "expr": "sum by (channel) (rate(push_failed_total{job=\"farmafinder-backend\"}[5m]))", "legendFormat": "failed {{channel}}" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 11, "title": "DB query p95 latency & errors", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 12, "x": 0, "y": 24 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [
|
||||
{ "expr": "histogram_quantile(0.95, sum by (le, engine) (rate(db_query_duration_ms_bucket{job=\"farmafinder-backend\"}[5m])))", "legendFormat": "p95 {{engine}}" },
|
||||
{ "expr": "sum by (engine) (rate(db_errors_total{job=\"farmafinder-backend\"}[5m]))", "legendFormat": "errors {{engine}}" }
|
||||
],
|
||||
"fieldConfig": { "defaults": { "unit": "ms" } }
|
||||
},
|
||||
{
|
||||
"id": 12, "title": "Redis cmd p95 & errors", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 12, "x": 12, "y": 24 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [
|
||||
{ "expr": "histogram_quantile(0.95, sum by (le) (rate(redis_cmd_duration_ms_bucket{job=\"farmafinder-backend\"}[5m])))", "legendFormat": "p95 redis" },
|
||||
{ "expr": "sum(rate(redis_errors_total{job=\"farmafinder-backend\"}[5m]))", "legendFormat": "redis errors/s" }
|
||||
],
|
||||
"fieldConfig": { "defaults": { "unit": "ms" } }
|
||||
},
|
||||
{
|
||||
"id": 13, "title": "Admin ops (pharmacy writes / links)", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 12, "x": 0, "y": 30 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [
|
||||
{ "expr": "sum by (op) (rate(pharmacy_write_total{job=\"farmafinder-backend\"}[5m]))", "legendFormat": "pharmacy {{op}}" },
|
||||
{ "expr": "sum by (op) (rate(pharmacy_medicine_link_total{job=\"farmafinder-backend\"}[5m]))", "legendFormat": "link {{op}}" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 14, "title": "Liveness (heartbeat)", "type": "stat",
|
||||
"gridPos": { "h": 6, "w": 12, "x": 12, "y": 30 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [
|
||||
{ "expr": "max(app_heartbeat_total{job=\"farmafinder-backend\"})", "legendFormat": "heartbeat total" }
|
||||
]
|
||||
}
|
||||
],
|
||||
"schemaVersion": 39,
|
||||
"style": "dark",
|
||||
"tags": ["farmafinder", "backend"],
|
||||
"templating": { "list": [] },
|
||||
"time": { "from": "now-6h", "to": "now" },
|
||||
"timepicker": {},
|
||||
"timezone": "browser",
|
||||
"title": "FarmaFinder — Backend",
|
||||
"uid": "farmafinder-backend",
|
||||
"version": 1,
|
||||
"weekStart": ""
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"annotations": { "list": [] },
|
||||
"editable": true,
|
||||
"fiscalYearStartMonth": 0,
|
||||
"graphTooltip": 1,
|
||||
"id": null,
|
||||
"links": [],
|
||||
"liveNow": false,
|
||||
"panels": [
|
||||
{
|
||||
"id": 1, "title": "Redis up", "type": "stat",
|
||||
"gridPos": { "h": 5, "w": 6, "x": 0, "y": 0 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [ { "expr": "redis_up{job=\"farmafinder-redis\"}", "legendFormat": "redis" } ]
|
||||
},
|
||||
{
|
||||
"id": 2, "title": "Connected clients", "type": "timeseries",
|
||||
"gridPos": { "h": 5, "w": 9, "x": 6, "y": 0 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [ { "expr": "redis_connected_clients{job=\"farmafinder-redis\"}", "legendFormat": "clients" } ]
|
||||
},
|
||||
{
|
||||
"id": 3, "title": "Memory used", "type": "timeseries",
|
||||
"gridPos": { "h": 5, "w": 9, "x": 15, "y": 0 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [ { "expr": "redis_memory_used_bytes{job=\"farmafinder-redis\"}", "legendFormat": "bytes" } ],
|
||||
"fieldConfig": { "defaults": { "unit": "bytes" } }
|
||||
},
|
||||
{
|
||||
"id": 4, "title": "Commands/sec", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 12, "x": 0, "y": 5 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [ { "expr": "rate(redis_commands_processed_total{job=\"farmafinder-redis\"}[5m])", "legendFormat": "cmd/s" } ]
|
||||
},
|
||||
{
|
||||
"id": 5, "title": "Keyspace hit ratio", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 12, "x": 12, "y": 5 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [ { "expr": "sum(rate(redis_keyspace_hits_total{job=\"farmafinder-redis\"}[5m])) / (sum(rate(redis_keyspace_hits_total{job=\"farmafinder-redis\"}[5m])) + sum(rate(redis_keyspace_misses_total{job=\"farmafinder-redis\"}[5m])))", "legendFormat": "hit ratio" } ],
|
||||
"fieldConfig": { "defaults": { "unit": "percentunit" } }
|
||||
},
|
||||
{
|
||||
"id": 6, "title": "Postgres up", "type": "stat",
|
||||
"gridPos": { "h": 5, "w": 6, "x": 0, "y": 11 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [ { "expr": "pg_up{job=\"farmafinder-postgres\"}", "legendFormat": "pg" } ]
|
||||
},
|
||||
{
|
||||
"id": 7, "title": "Active connections", "type": "timeseries",
|
||||
"gridPos": { "h": 5, "w": 9, "x": 6, "y": 11 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [ { "expr": "pg_stat_activity_count{job=\"farmafinder-postgres\"}", "legendFormat": "connections" } ]
|
||||
},
|
||||
{
|
||||
"id": 8, "title": "Tuples returned / fetched", "type": "timeseries",
|
||||
"gridPos": { "h": 5, "w": 9, "x": 15, "y": 11 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [ { "expr": "rate(pg_stat_database_tup_returned{job=\"farmafinder-postgres\"}[5m])", "legendFormat": "returned/s" }, { "expr": "rate(pg_stat_database_tup_fetched{job=\"farmafinder-postgres\"}[5m])", "legendFormat": "fetched/s" } ]
|
||||
},
|
||||
{
|
||||
"id": 9, "title": "Deadlocks / conflicts", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 12, "x": 0, "y": 16 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [ { "expr": "rate(pg_stat_database_deadlocks{job=\"farmafinder-postgres\"}[5m])", "legendFormat": "deadlocks/s" }, { "expr": "rate(pg_stat_database_conflicts{job=\"farmafinder-postgres\"}[5m])", "legendFormat": "conflicts/s" } ]
|
||||
},
|
||||
{
|
||||
"id": 10, "title": "Cache hit ratio (blocks)", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 12, "x": 12, "y": 16 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [ { "expr": "pg_stat_database_blk_hit{job=\"farmafinder-postgres\"} / (pg_stat_database_blk_hit{job=\"farmafinder-postgres\"} + pg_stat_database_blk_read{job=\"farmafinder-postgres\"})", "legendFormat": "block hit ratio" } ],
|
||||
"fieldConfig": { "defaults": { "unit": "percentunit" } }
|
||||
}
|
||||
],
|
||||
"schemaVersion": 39,
|
||||
"style": "dark",
|
||||
"tags": ["farmafinder", "datastores"],
|
||||
"templating": { "list": [] },
|
||||
"time": { "from": "now-6h", "to": "now" },
|
||||
"timepicker": {},
|
||||
"timezone": "browser",
|
||||
"title": "FarmaFinder — Datastores",
|
||||
"uid": "farmafinder-datastores",
|
||||
"version": 1,
|
||||
"weekStart": ""
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"annotations": { "list": [] },
|
||||
"editable": true,
|
||||
"fiscalYearStartMonth": 0,
|
||||
"graphTooltip": 1,
|
||||
"id": null,
|
||||
"links": [],
|
||||
"liveNow": false,
|
||||
"panels": [
|
||||
{
|
||||
"id": 1, "title": "Events/sec", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 8, "x": 0, "y": 0 },
|
||||
"datasource": { "type": "loki", "uid": "bfowk7qjoccu8b" },
|
||||
"targets": [ { "expr": "sum(count_over_time({app=\"farmafinder-mobile\"}[5m]))", "legendFormat": "events/s" } ]
|
||||
},
|
||||
{
|
||||
"id": 2, "title": "Active sessions", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 8, "x": 8, "y": 0 },
|
||||
"datasource": { "type": "loki", "uid": "bfowk7qjoccu8b" },
|
||||
"targets": [ { "expr": "count(count by (session_id) (count_over_time({app=\"farmafinder-mobile\"}[5m])))", "legendFormat": "sessions" } ]
|
||||
},
|
||||
{
|
||||
"id": 3, "title": "Errors/sec", "type": "timeseries",
|
||||
"gridPos": { "h": 6, "w": 8, "x": 16, "y": 0 },
|
||||
"datasource": { "type": "loki", "uid": "bfowk7qjoccu8b" },
|
||||
"targets": [ { "expr": "sum(count_over_time({app=\"farmafinder-mobile\"} |~ \"(?i)error|exception|crash\"[5m]))", "legendFormat": "errors/s" } ]
|
||||
},
|
||||
{
|
||||
"id": 4, "title": "Events by type", "type": "timeseries",
|
||||
"gridPos": { "h": 7, "w": 12, "x": 0, "y": 6 },
|
||||
"datasource": { "type": "loki", "uid": "bfowk7qjoccu8b" },
|
||||
"targets": [ { "expr": "sum by (type) (count_over_time({app=\"farmafinder-mobile\"}[5m]))", "legendFormat": "{{type}}" } ]
|
||||
},
|
||||
{
|
||||
"id": 5, "title": "Top error messages", "type": "timeseries",
|
||||
"gridPos": { "h": 7, "w": 12, "x": 12, "y": 6 },
|
||||
"datasource": { "type": "loki", "uid": "bfowk7qjoccu8b" },
|
||||
"targets": [ { "expr": "sum by (message) (count_over_time({app=\"farmafinder-mobile\"} |~ \"(?i)error|exception|crash\"[5m]))", "legendFormat": "{{message}}" } ]
|
||||
},
|
||||
{
|
||||
"id": 6, "title": "Recent logs", "type": "logs",
|
||||
"gridPos": { "h": 10, "w": 24, "x": 0, "y": 13 },
|
||||
"datasource": { "type": "loki", "uid": "bfowk7qjoccu8b" },
|
||||
"targets": [ { "expr": "{app=\"farmafinder-mobile\"}", "legendFormat": "" } ]
|
||||
}
|
||||
],
|
||||
"schemaVersion": 39,
|
||||
"style": "dark",
|
||||
"tags": ["farmafinder", "mobile", "rum"],
|
||||
"templating": { "list": [] },
|
||||
"time": { "from": "now-6h", "to": "now" },
|
||||
"timepicker": {},
|
||||
"timezone": "browser",
|
||||
"title": "FarmaFinder — Mobile RUM",
|
||||
"uid": "farmafinder-mobile-rum",
|
||||
"version": 1,
|
||||
"weekStart": ""
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"annotations": { "list": [] },
|
||||
"editable": true,
|
||||
"fiscalYearStartMonth": 0,
|
||||
"graphTooltip": 1,
|
||||
"id": null,
|
||||
"links": [],
|
||||
"liveNow": false,
|
||||
"panels": [
|
||||
{
|
||||
"id": 1, "title": "Backend req/s", "type": "stat",
|
||||
"gridPos": { "h": 5, "w": 6, "x": 0, "y": 0 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [ { "expr": "sum(rate(http_requests_total{job=\"farmafinder-backend\"}[5m]))", "legendFormat": "req/s" } ]
|
||||
},
|
||||
{
|
||||
"id": 2, "title": "Backend 5xx ratio", "type": "stat",
|
||||
"gridPos": { "h": 5, "w": 6, "x": 6, "y": 0 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [ { "expr": "sum(rate(http_requests_total{status_class=\"5xx\",job=\"farmafinder-backend\"}[5m])) / sum(rate(http_requests_total{job=\"farmafinder-backend\"}[5m]))", "legendFormat": "5xx" } ],
|
||||
"fieldConfig": { "defaults": { "unit": "percentunit", "thresholds": { "steps": [ { "color": "green", "value": 0 }, { "color": "yellow", "value": 0.01 }, { "color": "red", "value": 0.05 } ] } } }
|
||||
},
|
||||
{
|
||||
"id": 3, "title": "CIMA errors/s", "type": "stat",
|
||||
"gridPos": { "h": 5, "w": 6, "x": 12, "y": 0 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [ { "expr": "sum(rate(cima_requests_total{status=\"error\",job=\"farmafinder-backend\"}[5m]))", "legendFormat": "cima err/s" } ]
|
||||
},
|
||||
{
|
||||
"id": 4, "title": "Mobile events/s", "type": "stat",
|
||||
"gridPos": { "h": 5, "w": 6, "x": 18, "y": 0 },
|
||||
"datasource": { "type": "loki", "uid": "bfowk7qjoccu8b" },
|
||||
"targets": [ { "expr": "sum(count_over_time({app=\"farmafinder-mobile\"}[5m]))", "legendFormat": "mobile/s" } ]
|
||||
},
|
||||
{
|
||||
"id": 5, "title": "Datastore health", "type": "stat",
|
||||
"gridPos": { "h": 5, "w": 12, "x": 0, "y": 5 },
|
||||
"datasource": { "type": "prometheus", "uid": "PBFA97CFB590B2093" },
|
||||
"targets": [
|
||||
{ "expr": "redis_up{job=\"farmafinder-redis\"}", "legendFormat": "redis" },
|
||||
{ "expr": "pg_up{job=\"farmafinder-postgres\"}", "legendFormat": "postgres" }
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6, "title": "Navigation", "type": "text",
|
||||
"gridPos": { "h": 5, "w": 12, "x": 12, "y": 5 },
|
||||
"options": {
|
||||
"mode": "markdown",
|
||||
"content": "**Dashboards**\n- [Backend](/d/farmafinder-backend/farmafinder-backend)\n- [Datastores](/d/farmafinder-datastores/farmafinder-datastores)\n- [Mobile RUM](/d/farmafinder-mobile-rum/farmafinder-mobile-rum)\n- [Faro Web RUM](/d/faro-overview/faro-farmafinder-rum-overview)\n\n**Explore**\n- [Tempo (traces)](/explore?orgId=1&left=%5B%22now-6h%22,%22now%22,%22tempo%22,%7B%7D%5D)\n- [Loki (logs)](/explore?orgId=1&left=%5B%22now-6h%22,%22now%22,%22loki%22,%7B%7D%5D)\n- [Prometheus (metrics)](/explore?orgId=1&left=%5B%22now-6h%22,%22now%22,%22PBFA97CFB590B2093%22,%7B%7D%5D)"
|
||||
}
|
||||
}
|
||||
],
|
||||
"schemaVersion": 39,
|
||||
"style": "dark",
|
||||
"tags": ["farmafinder", "overview"],
|
||||
"templating": { "list": [] },
|
||||
"time": { "from": "now-6h", "to": "now" },
|
||||
"timepicker": {},
|
||||
"timezone": "browser",
|
||||
"title": "FarmaFinder — Overview",
|
||||
"uid": "farmafinder-overview",
|
||||
"version": 1,
|
||||
"weekStart": ""
|
||||
}
|
||||
@@ -35,10 +35,12 @@
|
||||
"@opentelemetry/api": "^1.9.0",
|
||||
"@opentelemetry/auto-instrumentations-node": "^0.52.0",
|
||||
"@opentelemetry/exporter-logs-otlp-grpc": "^0.55.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-grpc": "^0.55.0",
|
||||
"@opentelemetry/exporter-trace-otlp-grpc": "^0.55.0",
|
||||
"@opentelemetry/instrumentation-pino": "^0.45.0",
|
||||
"@opentelemetry/resources": "^1.28.0",
|
||||
"@opentelemetry/sdk-logs": "^0.55.0",
|
||||
"@opentelemetry/sdk-metrics": "^1.28.0",
|
||||
"@opentelemetry/sdk-node": "^0.55.0",
|
||||
"@opentelemetry/sdk-trace-base": "^1.28.0",
|
||||
"@opentelemetry/semantic-conventions": "^1.28.0",
|
||||
@@ -65,6 +67,43 @@
|
||||
"supertest": "^7.2.2"
|
||||
}
|
||||
},
|
||||
"apps/backend/node_modules/@opentelemetry/core": {
|
||||
"version": "1.30.1",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.30.1.tgz",
|
||||
"integrity": "sha512-OOCM2C/QIURhJMuKaekP3TRBxBKxG/TWWA0TL2J6nXUtDnuCtccy49LUJF8xPFXMX+0LMcxFpCo8M9cGY1W6rQ==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/semantic-conventions": "1.28.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": ">=1.0.0 <1.10.0"
|
||||
}
|
||||
},
|
||||
"apps/backend/node_modules/@opentelemetry/sdk-metrics": {
|
||||
"version": "1.30.1",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-1.30.1.tgz",
|
||||
"integrity": "sha512-q9zcZ0Okl8jRgmy7eNW3Ku1XSgg3sDLa5evHZpCwjspw7E8Is4K/haRPDJrBcX3YSn/Y7gUvFnByNYEKQNbNog==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/core": "1.30.1",
|
||||
"@opentelemetry/resources": "1.30.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": ">=1.3.0 <1.10.0"
|
||||
}
|
||||
},
|
||||
"apps/backend/node_modules/@opentelemetry/semantic-conventions": {
|
||||
"version": "1.28.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.28.0.tgz",
|
||||
"integrity": "sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==",
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"apps/frontend": {
|
||||
"name": "farma-clic-frontend",
|
||||
"version": "1.0.0",
|
||||
@@ -99,6 +138,7 @@
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@expo/vector-icons": "^15.0.2",
|
||||
"@grafana/faro-react-native": "^1.3.0",
|
||||
"@react-native-async-storage/async-storage": "2.2.0",
|
||||
"@tanstack/react-query": "^5.101.2",
|
||||
"axios": "^1.18.1",
|
||||
@@ -111,6 +151,7 @@
|
||||
"expo-image-picker": "~57.0.2",
|
||||
"expo-linking": "~57.0.1",
|
||||
"expo-local-authentication": "~57.0.0",
|
||||
"expo-location": "~57.0.2",
|
||||
"expo-notifications": "~57.0.3",
|
||||
"expo-router": "~57.0.3",
|
||||
"expo-secure-store": "~57.0.0",
|
||||
@@ -362,6 +403,158 @@
|
||||
"react-native": "*"
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/@grafana/faro-core": {
|
||||
"version": "2.8.2",
|
||||
"resolved": "https://registry.npmjs.org/@grafana/faro-core/-/faro-core-2.8.2.tgz",
|
||||
"integrity": "sha512-63C6+N/P9/ySUMaGut8yVb1DkPuHS5I/lfRm97+aDXFj3+8pxRT/QzyXNe0r6KMU5O95wC9FLVGxG9ZvkwEhJQ==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/api": "^1.9.0",
|
||||
"@opentelemetry/otlp-transformer": "^0.219.0"
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/@grafana/faro-react-native": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@grafana/faro-react-native/-/faro-react-native-1.3.0.tgz",
|
||||
"integrity": "sha512-KeohD3S2xmiukL5YW3mOGDqvFiwpD9IzJ2EtZ50ktEsnA+6EMt2AtJ8RzJfAamGTYqemBpDiw51rqB4ID+C2xg==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@grafana/faro-core": "^2.7.0",
|
||||
"@react-native-async-storage/async-storage": "^1.21.0",
|
||||
"react-native-device-info": "^11.1.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@react-navigation/native": ">=6.0.0",
|
||||
"react": ">=18.0.0",
|
||||
"react-native": ">=0.70.0",
|
||||
"react-native-mmkv": ">=2.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@react-navigation/native": {
|
||||
"optional": true
|
||||
},
|
||||
"react-native-mmkv": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/@grafana/faro-react-native/node_modules/@react-native-async-storage/async-storage": {
|
||||
"version": "1.24.0",
|
||||
"resolved": "https://registry.npmjs.org/@react-native-async-storage/async-storage/-/async-storage-1.24.0.tgz",
|
||||
"integrity": "sha512-W4/vbwUOYOjco0x3toB8QCr7EjIP6nE9G7o8PMguvvjYT5Awg09lyV4enACRx4s++PPulBiBSjL0KTFx2u0Z/g==",
|
||||
"dependencies": {
|
||||
"merge-options": "^3.0.4"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react-native": "^0.0.0-0 || >=0.60 <1.0"
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/@opentelemetry/api-logs": {
|
||||
"version": "0.219.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.219.0.tgz",
|
||||
"integrity": "sha512-FFx7YnaYJlIjqWW/AG/yAZ0L/NEY724PipXXXQLdtZPbLwBGbUMTGL1i/esI56TWfTUXxhLfpgrnWJCG8aUJyg==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/api": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.0.0"
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/@opentelemetry/core": {
|
||||
"version": "2.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.8.0.tgz",
|
||||
"integrity": "sha512-hd1Lfh8p545nNz+jq1Ejfz+Mn1hyLuxYn1YzTfFNrxr8urEWMNQLPf1Th8kjOH+HxwawCrtgBp8JpBUR4ZSgww==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/semantic-conventions": "^1.29.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.19.0 || >=20.6.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": ">=1.0.0 <1.10.0"
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/@opentelemetry/otlp-transformer": {
|
||||
"version": "0.219.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/otlp-transformer/-/otlp-transformer-0.219.0.tgz",
|
||||
"integrity": "sha512-aaYKAyXhw9VchKZVGOopD3Gw/kPsyrX2c6IQ0AW32mTjqmZOh5Y6Gf5OYqTNqVktAeBjmFinhyFaCwW6GYK9YQ==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/api-logs": "0.219.0",
|
||||
"@opentelemetry/core": "2.8.0",
|
||||
"@opentelemetry/resources": "2.8.0",
|
||||
"@opentelemetry/sdk-logs": "0.219.0",
|
||||
"@opentelemetry/sdk-metrics": "2.8.0",
|
||||
"@opentelemetry/sdk-trace-base": "2.8.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.19.0 || >=20.6.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/@opentelemetry/resources": {
|
||||
"version": "2.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.8.0.tgz",
|
||||
"integrity": "sha512-qmXQ27ilDbUK/vGMqwL8D4/rhn76C+sherM4wTbjlfknR8Nvfc/hCxjRJPhkzZzUsPiNg16SA31NxMabwttRjg==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/core": "2.8.0",
|
||||
"@opentelemetry/semantic-conventions": "^1.29.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.19.0 || >=20.6.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": ">=1.3.0 <1.10.0"
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/@opentelemetry/sdk-logs": {
|
||||
"version": "0.219.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-logs/-/sdk-logs-0.219.0.tgz",
|
||||
"integrity": "sha512-s6lTKRakaPClvKoWHRChxnXjDMkM/TQ30ff78jN6EBGf7MI7VzANE5PU3f4z9qDUudWjvZjOLHG0rBnBKYvoXA==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/api-logs": "0.219.0",
|
||||
"@opentelemetry/core": "2.8.0",
|
||||
"@opentelemetry/resources": "2.8.0",
|
||||
"@opentelemetry/semantic-conventions": "^1.29.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.19.0 || >=20.6.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": ">=1.4.0 <1.10.0"
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/@opentelemetry/sdk-metrics": {
|
||||
"version": "2.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-2.8.0.tgz",
|
||||
"integrity": "sha512-UDBGaj6W0Rgy5rTTaoxs8gVGF/aGkAKyjurJv7se6wjRxJu7FoquTLT/vt54DZfo4crbprYfhX/SOK9+BPw1qg==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/core": "2.8.0",
|
||||
"@opentelemetry/resources": "2.8.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.19.0 || >=20.6.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": ">=1.9.0 <1.10.0"
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/@opentelemetry/sdk-trace-base": {
|
||||
"version": "2.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.8.0.tgz",
|
||||
"integrity": "sha512-mhU4jp+vW0mGbFRd+GeXHvmfA4aDqWjBjLC3pE5XMpLs0IE2ryYb019Ts2AQrOq67gaTF25D91+fgvEHDZEnuQ==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/core": "2.8.0",
|
||||
"@opentelemetry/resources": "2.8.0",
|
||||
"@opentelemetry/semantic-conventions": "^1.29.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^18.19.0 || >=20.6.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": ">=1.3.0 <1.10.0"
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/@react-native-async-storage/async-storage": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@react-native-async-storage/async-storage/-/async-storage-2.2.0.tgz",
|
||||
@@ -792,6 +985,18 @@
|
||||
"expo": "*"
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/expo-location": {
|
||||
"version": "57.0.2",
|
||||
"resolved": "https://registry.npmjs.org/expo-location/-/expo-location-57.0.2.tgz",
|
||||
"integrity": "sha512-yyize0BsBfZjgelBQdhWFH2JUh9OLJOUt7fxz73Y70nbRV2rXZ7A9r0J6jfAa9lXqH7y/GDsFLqecfTc/PcFUQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@expo/image-utils": "^0.11.1"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"expo": "*"
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/expo-manifests": {
|
||||
"version": "57.0.0",
|
||||
"resolved": "https://registry.npmjs.org/expo-manifests/-/expo-manifests-57.0.0.tgz",
|
||||
@@ -1072,6 +1277,14 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/react-native-device-info": {
|
||||
"version": "11.1.0",
|
||||
"resolved": "https://registry.npmjs.org/react-native-device-info/-/react-native-device-info-11.1.0.tgz",
|
||||
"integrity": "sha512-hzXJSObJdezEz0hF7MAJ3tGeoesuQWenXXt9mrQR9Mjb8kXpZ09rqSsZ/quNpJdZpQ3rYiFa3/0GFG5KNn9PBg==",
|
||||
"peerDependencies": {
|
||||
"react-native": "*"
|
||||
}
|
||||
},
|
||||
"apps/frontend-mobile/node_modules/react-native-drawer-layout": {
|
||||
"version": "4.2.7",
|
||||
"resolved": "https://registry.npmjs.org/react-native-drawer-layout/-/react-native-drawer-layout-4.2.7.tgz",
|
||||
@@ -7128,6 +7341,273 @@
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-grpc": {
|
||||
"version": "0.55.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-grpc/-/exporter-metrics-otlp-grpc-0.55.0.tgz",
|
||||
"integrity": "sha512-9V6t3Tz1yFmXKXDjphgPSAsfQuG0bz9PlAVRY28D+wuG7Ut/Fv43XuccktdAcdrXx1MvCHdCcVmINLyYXLqTIg==",
|
||||
"dependencies": {
|
||||
"@grpc/grpc-js": "^1.7.1",
|
||||
"@opentelemetry/core": "1.28.0",
|
||||
"@opentelemetry/exporter-metrics-otlp-http": "0.55.0",
|
||||
"@opentelemetry/otlp-exporter-base": "0.55.0",
|
||||
"@opentelemetry/otlp-grpc-exporter-base": "0.55.0",
|
||||
"@opentelemetry/otlp-transformer": "0.55.0",
|
||||
"@opentelemetry/resources": "1.28.0",
|
||||
"@opentelemetry/sdk-metrics": "1.28.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-grpc/node_modules/@opentelemetry/api-logs": {
|
||||
"version": "0.55.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.55.0.tgz",
|
||||
"integrity": "sha512-3cpa+qI45VHYcA5c0bHM6VHo9gicv3p5mlLHNG3rLyjQU8b7e0st1rWtrUn3JbZ3DwwCfhKop4eQ9UuYlC6Pkg==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/api": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-grpc/node_modules/@opentelemetry/core": {
|
||||
"version": "1.28.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.28.0.tgz",
|
||||
"integrity": "sha512-ZLwRMV+fNDpVmF2WYUdBHlq0eOWtEaUJSusrzjGnBt7iSRvfjFE3RXYUZJrqou/wIDWV0DwQ5KIfYe9WXg9Xqw==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/semantic-conventions": "1.27.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": ">=1.0.0 <1.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-grpc/node_modules/@opentelemetry/otlp-exporter-base": {
|
||||
"version": "0.55.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/otlp-exporter-base/-/otlp-exporter-base-0.55.0.tgz",
|
||||
"integrity": "sha512-iHQI0Zzq3h1T6xUJTVFwmFl5Dt5y1es+fl4kM+k5T/3YvmVyeYkSiF+wHCg6oKrlUAJfk+t55kaAu3sYmt7ZYA==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/core": "1.28.0",
|
||||
"@opentelemetry/otlp-transformer": "0.55.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-grpc/node_modules/@opentelemetry/otlp-transformer": {
|
||||
"version": "0.55.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/otlp-transformer/-/otlp-transformer-0.55.0.tgz",
|
||||
"integrity": "sha512-kVqEfxtp6mSN2Dhpy0REo1ghP4PYhC1kMHQJ2qVlO99Pc+aigELjZDfg7/YKmL71gR6wVGIeJfiql/eXL7sQPA==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/api-logs": "0.55.0",
|
||||
"@opentelemetry/core": "1.28.0",
|
||||
"@opentelemetry/resources": "1.28.0",
|
||||
"@opentelemetry/sdk-logs": "0.55.0",
|
||||
"@opentelemetry/sdk-metrics": "1.28.0",
|
||||
"@opentelemetry/sdk-trace-base": "1.28.0",
|
||||
"protobufjs": "^7.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-grpc/node_modules/@opentelemetry/resources": {
|
||||
"version": "1.28.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.28.0.tgz",
|
||||
"integrity": "sha512-cIyXSVJjGeTICENN40YSvLDAq4Y2502hGK3iN7tfdynQLKWb3XWZQEkPc+eSx47kiy11YeFAlYkEfXwR1w8kfw==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/core": "1.28.0",
|
||||
"@opentelemetry/semantic-conventions": "1.27.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": ">=1.0.0 <1.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-grpc/node_modules/@opentelemetry/sdk-metrics": {
|
||||
"version": "1.28.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-1.28.0.tgz",
|
||||
"integrity": "sha512-43tqMK/0BcKTyOvm15/WQ3HLr0Vu/ucAl/D84NO7iSlv6O4eOprxSHa3sUtmYkaZWHqdDJV0AHVz/R6u4JALVQ==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/core": "1.28.0",
|
||||
"@opentelemetry/resources": "1.28.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": ">=1.3.0 <1.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-grpc/node_modules/@opentelemetry/sdk-trace-base": {
|
||||
"version": "1.28.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.28.0.tgz",
|
||||
"integrity": "sha512-ceUVWuCpIao7Y5xE02Xs3nQi0tOGmMea17ecBdwtCvdo9ekmO+ijc9RFDgfifMl7XCBf41zne/1POM3LqSTZDA==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/core": "1.28.0",
|
||||
"@opentelemetry/resources": "1.28.0",
|
||||
"@opentelemetry/semantic-conventions": "1.27.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": ">=1.0.0 <1.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-grpc/node_modules/@opentelemetry/semantic-conventions": {
|
||||
"version": "1.27.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.27.0.tgz",
|
||||
"integrity": "sha512-sAay1RrB+ONOem0OZanAR1ZI/k7yDpnOQSQmTMuGImUQb2y8EbSaCJ94FQluM74xoU03vlb2d2U90hZluL6nQg==",
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-http": {
|
||||
"version": "0.55.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-http/-/exporter-metrics-otlp-http-0.55.0.tgz",
|
||||
"integrity": "sha512-3MqDNZzgXmLaiVo9gs9kCw/zPEaZYKIT0+jeMWscWHL/jrA9BNArTOYWUHEPabAQmWQ2BbvgNC7yzlqjoynQwA==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/core": "1.28.0",
|
||||
"@opentelemetry/otlp-exporter-base": "0.55.0",
|
||||
"@opentelemetry/otlp-transformer": "0.55.0",
|
||||
"@opentelemetry/resources": "1.28.0",
|
||||
"@opentelemetry/sdk-metrics": "1.28.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-http/node_modules/@opentelemetry/api-logs": {
|
||||
"version": "0.55.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.55.0.tgz",
|
||||
"integrity": "sha512-3cpa+qI45VHYcA5c0bHM6VHo9gicv3p5mlLHNG3rLyjQU8b7e0st1rWtrUn3JbZ3DwwCfhKop4eQ9UuYlC6Pkg==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/api": "^1.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-http/node_modules/@opentelemetry/core": {
|
||||
"version": "1.28.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-1.28.0.tgz",
|
||||
"integrity": "sha512-ZLwRMV+fNDpVmF2WYUdBHlq0eOWtEaUJSusrzjGnBt7iSRvfjFE3RXYUZJrqou/wIDWV0DwQ5KIfYe9WXg9Xqw==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/semantic-conventions": "1.27.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": ">=1.0.0 <1.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-http/node_modules/@opentelemetry/otlp-exporter-base": {
|
||||
"version": "0.55.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/otlp-exporter-base/-/otlp-exporter-base-0.55.0.tgz",
|
||||
"integrity": "sha512-iHQI0Zzq3h1T6xUJTVFwmFl5Dt5y1es+fl4kM+k5T/3YvmVyeYkSiF+wHCg6oKrlUAJfk+t55kaAu3sYmt7ZYA==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/core": "1.28.0",
|
||||
"@opentelemetry/otlp-transformer": "0.55.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-http/node_modules/@opentelemetry/otlp-transformer": {
|
||||
"version": "0.55.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/otlp-transformer/-/otlp-transformer-0.55.0.tgz",
|
||||
"integrity": "sha512-kVqEfxtp6mSN2Dhpy0REo1ghP4PYhC1kMHQJ2qVlO99Pc+aigELjZDfg7/YKmL71gR6wVGIeJfiql/eXL7sQPA==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/api-logs": "0.55.0",
|
||||
"@opentelemetry/core": "1.28.0",
|
||||
"@opentelemetry/resources": "1.28.0",
|
||||
"@opentelemetry/sdk-logs": "0.55.0",
|
||||
"@opentelemetry/sdk-metrics": "1.28.0",
|
||||
"@opentelemetry/sdk-trace-base": "1.28.0",
|
||||
"protobufjs": "^7.3.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": "^1.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-http/node_modules/@opentelemetry/resources": {
|
||||
"version": "1.28.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-1.28.0.tgz",
|
||||
"integrity": "sha512-cIyXSVJjGeTICENN40YSvLDAq4Y2502hGK3iN7tfdynQLKWb3XWZQEkPc+eSx47kiy11YeFAlYkEfXwR1w8kfw==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/core": "1.28.0",
|
||||
"@opentelemetry/semantic-conventions": "1.27.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": ">=1.0.0 <1.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-http/node_modules/@opentelemetry/sdk-metrics": {
|
||||
"version": "1.28.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-1.28.0.tgz",
|
||||
"integrity": "sha512-43tqMK/0BcKTyOvm15/WQ3HLr0Vu/ucAl/D84NO7iSlv6O4eOprxSHa3sUtmYkaZWHqdDJV0AHVz/R6u4JALVQ==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/core": "1.28.0",
|
||||
"@opentelemetry/resources": "1.28.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": ">=1.3.0 <1.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-http/node_modules/@opentelemetry/sdk-trace-base": {
|
||||
"version": "1.28.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-1.28.0.tgz",
|
||||
"integrity": "sha512-ceUVWuCpIao7Y5xE02Xs3nQi0tOGmMea17ecBdwtCvdo9ekmO+ijc9RFDgfifMl7XCBf41zne/1POM3LqSTZDA==",
|
||||
"dependencies": {
|
||||
"@opentelemetry/core": "1.28.0",
|
||||
"@opentelemetry/resources": "1.28.0",
|
||||
"@opentelemetry/semantic-conventions": "1.27.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@opentelemetry/api": ">=1.0.0 <1.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-metrics-otlp-http/node_modules/@opentelemetry/semantic-conventions": {
|
||||
"version": "1.27.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.27.0.tgz",
|
||||
"integrity": "sha512-sAay1RrB+ONOem0OZanAR1ZI/k7yDpnOQSQmTMuGImUQb2y8EbSaCJ94FQluM74xoU03vlb2d2U90hZluL6nQg==",
|
||||
"engines": {
|
||||
"node": ">=14"
|
||||
}
|
||||
},
|
||||
"node_modules/@opentelemetry/exporter-trace-otlp-grpc": {
|
||||
"version": "0.55.0",
|
||||
"resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-grpc/-/exporter-trace-otlp-grpc-0.55.0.tgz",
|
||||
|
||||