Compare commits
30 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8bf0b33249 | |||
| f921b15d67 | |||
| 59edc7fbf1 | |||
| 731a6c98ae | |||
| 31c1a14343 | |||
| 25ebb899e9 | |||
| 2e3ce44e7b | |||
| 20debdb023 | |||
| 452a835b64 | |||
| f1b0eab11d | |||
| ee23f61057 | |||
| 26f309acfb | |||
| 4df1594b3b | |||
| 981f3bd3db | |||
| 83920ae57c | |||
| 7b1636a96e | |||
| bb2dbbab3a | |||
| d5b23aa94a | |||
| 9e786f2966 | |||
| a709deb893 | |||
| 229e1d8106 | |||
| f2a5dc4ca3 | |||
| d62e5976ce | |||
| d6f4164dae | |||
| 2713be85a3 | |||
| 0c43d32cf1 | |||
| a00cfe949c | |||
| 2a7ab64bbf | |||
| bf519e43c9 | |||
| d371fd2bb7 |
@@ -1 +1 @@
|
||||
{"pid":10782,"startedAt":1783578681151}
|
||||
{"pid":596137,"startedAt":1783946773113}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"$schema": "https://mimo.xiaomi.com/mimocode/config.json",
|
||||
"mcp": {
|
||||
"n8n": {
|
||||
"type": "remote",
|
||||
"url": "https://n8n.hacecalor.net/mcp-server/http",
|
||||
"headers": {
|
||||
"Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJjNDE1ODI4Yy00ZWU0LTQ1MjEtOGQ3Mi0xODZmYWNjNGU4ZmEiLCJpc3MiOiJuOG4iLCJhdWQiOiJtY3Atc2VydmVyLWFwaSIsImp0aSI6ImU1YzUyNjIxLTExZDAtNDM4MC04YmRjLTlhMmQ2MDA1OGU4OSIsImlhdCI6MTc4Mzk0NjY3Mn0._0LG3CJJjUg7-g1kvMjME5nBjIEWkrfEeAZrhDxpfC4"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,3 +15,14 @@ PG_PASSWORD=change-me
|
||||
VAPID_PUBLIC_KEY=
|
||||
VAPID_PRIVATE_KEY=
|
||||
VAPID_SUBJECT=mailto:admin@example.com
|
||||
|
||||
# Expo Push Notifications (mobile). Get token from:
|
||||
# https://expo.dev/accounts/[username]/settings/access-tokens
|
||||
EXPO_ACCESS_TOKEN=
|
||||
|
||||
# Open Food Facts
|
||||
# Register at: https://world.openfoodfacts.org/
|
||||
# User-Agent is REQUIRED per OFF docs (format: AppName/Version (ContactEmail))
|
||||
OFF_USER_AGENT=FarmaFinder/1.0 (https://github.com/farmafinder)
|
||||
OFF_USERNAME=
|
||||
OFF_PASSWORD=
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { jest } from '@jest/globals'
|
||||
|
||||
jest.unstable_mockModule('../redis-client.js', () => ({
|
||||
default: {
|
||||
get: jest.fn(async () => null),
|
||||
setEx: jest.fn(async () => 'OK'),
|
||||
},
|
||||
}))
|
||||
|
||||
jest.unstable_mockModule('axios', () => ({
|
||||
default: {
|
||||
get: jest.fn(async () => ({ data: { products: [] } })),
|
||||
},
|
||||
}))
|
||||
|
||||
const { transformOFFProduct, searchBabyProducts, getBabyProductDetails } = await import('../off-service.js')
|
||||
|
||||
describe('transformOFFProduct', () => {
|
||||
test('transforms a valid OFF product to unified model', () => {
|
||||
const offProduct = {
|
||||
_id: '12345',
|
||||
product_name: 'Baby Rice',
|
||||
brands: 'Nestlé',
|
||||
image_url: 'https://example.com/image.jpg',
|
||||
nutriscore_grade: 'a',
|
||||
ingredients_text: 'Rice, Iron, Vitamins',
|
||||
nova_group: 1,
|
||||
ecoscore_grade: 'b',
|
||||
categories_tags: ['en:baby-foods', 'en:baby-rice'],
|
||||
}
|
||||
|
||||
const result = transformOFFProduct(offProduct)
|
||||
|
||||
expect(result).toEqual({
|
||||
id: '12345',
|
||||
source: 'openfoodfacts',
|
||||
name: 'Baby Rice',
|
||||
brand: 'Nestlé',
|
||||
category: 'baby_food',
|
||||
image_url: 'https://example.com/image.jpg',
|
||||
nutriscore: 'a',
|
||||
ingredients: 'Rice, Iron, Vitamins',
|
||||
nova_group: 1,
|
||||
eco_score: 'b',
|
||||
})
|
||||
})
|
||||
|
||||
test('returns null for null/undefined input', () => {
|
||||
expect(transformOFFProduct(null)).toBeNull()
|
||||
expect(transformOFFProduct(undefined)).toBeNull()
|
||||
})
|
||||
|
||||
test('returns null when missing required fields', () => {
|
||||
expect(transformOFFProduct({ _id: '123' })).toBeNull()
|
||||
expect(transformOFFProduct({ product_name: 'Test' })).toBeNull()
|
||||
})
|
||||
|
||||
test('sets default brand to empty string when missing', () => {
|
||||
const result = transformOFFProduct({
|
||||
_id: '999',
|
||||
product_name: 'Plain Product',
|
||||
})
|
||||
expect(result.brand).toBe('')
|
||||
expect(result.image_url).toBeNull()
|
||||
expect(result.nutriscore).toBeNull()
|
||||
expect(result.ingredients).toBeNull()
|
||||
expect(result.nova_group).toBeNull()
|
||||
expect(result.eco_score).toBeNull()
|
||||
})
|
||||
|
||||
test('detects baby_milk category from tags', () => {
|
||||
const result = transformOFFProduct({
|
||||
_id: '200',
|
||||
product_name: 'Infant Formula',
|
||||
categories_tags: ['en:infant-milk'],
|
||||
})
|
||||
expect(result.category).toBe('baby_milk')
|
||||
})
|
||||
|
||||
test('detects baby_cereal category from tags', () => {
|
||||
const result = transformOFFProduct({
|
||||
_id: '300',
|
||||
product_name: 'Baby Cereal',
|
||||
categories_tags: ['en:baby-cereals'],
|
||||
})
|
||||
expect(result.category).toBe('baby_cereal')
|
||||
})
|
||||
})
|
||||
|
||||
describe('searchBabyProducts', () => {
|
||||
test('returns empty array for short query', async () => {
|
||||
const result = await searchBabyProducts('a')
|
||||
expect(result).toEqual([])
|
||||
})
|
||||
|
||||
test('returns empty array for null/empty query', async () => {
|
||||
expect(await searchBabyProducts(null)).toEqual([])
|
||||
expect(await searchBabyProducts('')).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('getBabyProductDetails', () => {
|
||||
test('returns null for null barcode', async () => {
|
||||
const result = await getBabyProductDetails(null)
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -3,6 +3,7 @@ import { jest } from '@jest/globals'
|
||||
jest.unstable_mockModule('../cima-service.js', () => ({
|
||||
searchMedicines: jest.fn(async () => []),
|
||||
getMedicineDetails: jest.fn(async () => null),
|
||||
searchOTC: jest.fn(async () => []),
|
||||
}))
|
||||
|
||||
jest.unstable_mockModule('../farmacias-webhook-import.js', () => ({
|
||||
|
||||
@@ -231,6 +231,86 @@ export async function getMedicineDetails(nregistro) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Busca medicamentos OTC (Sin Receta) en la API de CIMA con caché de Redis
|
||||
* @param {string} query - Término de búsqueda
|
||||
* @returns {Promise<Array>} - Lista de medicamentos OTC encontrados
|
||||
*/
|
||||
export async function searchOTC(query) {
|
||||
if (!query || query.trim().length < 2) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const searchTerm = query.trim().toLowerCase();
|
||||
const cacheKey = `cima:otc:${searchTerm}`;
|
||||
|
||||
try {
|
||||
// Intentar obtener del caché
|
||||
const cachedData = await redisClient.get(cacheKey);
|
||||
|
||||
if (cachedData) {
|
||||
console.log(`📦 Cache hit for OTC search: ${searchTerm}`);
|
||||
return JSON.parse(cachedData);
|
||||
}
|
||||
|
||||
const parsed = parseSearchQuery(searchTerm);
|
||||
const apiSearchTerm = parsed.nameQuery || searchTerm;
|
||||
|
||||
console.log(`🌐 Fetching OTC from CIMA API: ${apiSearchTerm}`);
|
||||
const response = await axios.get(`${CIMA_API_BASE_URL}/medicamentos`, {
|
||||
params: {
|
||||
nombre: apiSearchTerm,
|
||||
cpresc: 'Sin Receta'
|
||||
},
|
||||
timeout: 5000
|
||||
});
|
||||
|
||||
if (response.data && response.data.resultados) {
|
||||
// Transformar los datos de CIMA al modelo unificado Product
|
||||
const medicines = response.data.resultados.map(med => ({
|
||||
id: med.nregistro,
|
||||
source: 'cima',
|
||||
name: med.nombre,
|
||||
brand: med.labtitular || '',
|
||||
category: 'otc',
|
||||
image_url: med.fotos?.[0]?.url || null,
|
||||
active_ingredient: med.vtm?.nombre || null,
|
||||
dosage: med.dosis || null,
|
||||
form: med.formaFarmaceutica?.nombre || null,
|
||||
prescription: med.cpresc,
|
||||
commercialized: med.comerc,
|
||||
photos: med.fotos || [],
|
||||
docs: med.docs || []
|
||||
}));
|
||||
|
||||
const filtered = filterMedicinesByFullQuery(medicines, searchTerm);
|
||||
|
||||
// Guardar en caché (1h TTL)
|
||||
await redisClient.setEx(cacheKey, CACHE_TTL, JSON.stringify(filtered));
|
||||
|
||||
console.log(`✅ Cached ${filtered.length} OTC medicines for: ${searchTerm}`);
|
||||
return filtered;
|
||||
}
|
||||
|
||||
return [];
|
||||
} catch (error) {
|
||||
console.error('Error searching OTC medicines from CIMA:', error.message);
|
||||
|
||||
// Si falla, intentar devolver datos cacheados aunque hayan expirado
|
||||
try {
|
||||
const staleData = await redisClient.get(cacheKey);
|
||||
if (staleData) {
|
||||
console.log('⚠️ Returning stale OTC cache data due to API error');
|
||||
return JSON.parse(staleData);
|
||||
}
|
||||
} catch (cacheError) {
|
||||
console.error('OTC cache fallback also failed:', cacheError);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Limpia el caché de búsquedas (útil para testing o mantenimiento)
|
||||
* @param {string} pattern - Patrón de claves a eliminar (ej: 'medicines:search:*')
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
import axios from 'axios';
|
||||
import redisClient from './redis-client.js';
|
||||
|
||||
// OFF API v3 (recommended) with fallback to v2 for search
|
||||
const OFF_API_BASE = 'https://world.openfoodfacts.org';
|
||||
const CACHE_TTL = 3600;
|
||||
const MAX_RETRIES = 2;
|
||||
const RETRY_DELAY_MS = 1000;
|
||||
|
||||
// User-Agent is REQUIRED per OFF docs: AppName/Version (ContactEmail)
|
||||
const OFF_USER_AGENT = process.env.OFF_USER_AGENT || 'FarmaFinder/1.0 (https://github.com/farmafinder)';
|
||||
|
||||
// Open Food Facts authentication (optional, for write operations)
|
||||
const OFF_USERNAME = process.env.OFF_USERNAME;
|
||||
const OFF_PASSWORD = process.env.OFF_PASSWORD;
|
||||
|
||||
function getOffHeaders() {
|
||||
return {
|
||||
'User-Agent': OFF_USER_AGENT,
|
||||
};
|
||||
}
|
||||
|
||||
function getOffAuth() {
|
||||
if (OFF_USERNAME && OFF_PASSWORD) {
|
||||
return {
|
||||
username: OFF_USERNAME,
|
||||
password: OFF_PASSWORD,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function sleep(ms) {
|
||||
return new Promise(resolve => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
export function transformOFFProduct(offProduct) {
|
||||
if (!offProduct || !offProduct._id || !offProduct.product_name) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const categoriesTags = offProduct.categories_tags || [];
|
||||
let category = 'baby_food';
|
||||
for (const tag of categoriesTags) {
|
||||
const lower = tag.toLowerCase();
|
||||
if (lower.includes('baby-milk') || lower.includes('infant-milk')) {
|
||||
category = 'baby_milk';
|
||||
break;
|
||||
}
|
||||
if (lower.includes('baby-cereal') || lower.includes('infant-cereal')) {
|
||||
category = 'baby_cereal';
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: offProduct._id,
|
||||
source: 'openfoodfacts',
|
||||
name: offProduct.product_name,
|
||||
brand: offProduct.brands || '',
|
||||
category,
|
||||
image_url: offProduct.image_url || null,
|
||||
nutriscore: offProduct.nutriscore_grade || null,
|
||||
ingredients: offProduct.ingredients_text || null,
|
||||
nova_group: offProduct.nova_group || null,
|
||||
eco_score: offProduct.ecoscore_grade || null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function searchBabyProducts(query) {
|
||||
if (!query || query.trim().length < 2) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const searchTerm = query.trim().toLowerCase();
|
||||
const cacheKey = `off:baby:${searchTerm}`;
|
||||
|
||||
try {
|
||||
const cachedData = await redisClient.get(cacheKey);
|
||||
if (cachedData) {
|
||||
console.log(`Cache hit for OFF search: ${searchTerm}`);
|
||||
return JSON.parse(cachedData);
|
||||
}
|
||||
|
||||
console.log(`Fetching from OFF API: ${searchTerm}`);
|
||||
const headers = getOffHeaders();
|
||||
console.log(`[OFF] User-Agent: ${headers['User-Agent']}`);
|
||||
console.log(`[OFF] URL: ${OFF_API_BASE}/api/v2/search?brands_tags=${searchTerm}`);
|
||||
|
||||
let lastError;
|
||||
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
||||
try {
|
||||
// Use v2 structured search with brand filter (more reliable than /cgi/search.pl)
|
||||
// READ operations don't require auth per OFF docs, only User-Agent
|
||||
const response = await axios.get(`${OFF_API_BASE}/api/v2/search`, {
|
||||
params: {
|
||||
brands_tags: searchTerm,
|
||||
page_size: 20,
|
||||
},
|
||||
headers,
|
||||
timeout: 10000,
|
||||
validateStatus: (status) => status === 200,
|
||||
});
|
||||
|
||||
// Check if response is actually JSON (OFF sometimes returns HTML on error)
|
||||
if (typeof response.data === 'string' || !response.data.products) {
|
||||
console.warn(`[OFF] Invalid response for "${searchTerm}" (attempt ${attempt + 1}): API may be down`);
|
||||
if (attempt < MAX_RETRIES) {
|
||||
await sleep(RETRY_DELAY_MS * (attempt + 1));
|
||||
continue;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
const products = response.data.products
|
||||
.map(transformOFFProduct)
|
||||
.filter(Boolean);
|
||||
|
||||
// Only cache non-empty results to avoid caching API failures
|
||||
if (products.length > 0) {
|
||||
try {
|
||||
await redisClient.setEx(cacheKey, CACHE_TTL, JSON.stringify(products));
|
||||
console.log(`Cached ${products.length} OFF products for: ${searchTerm}`);
|
||||
} catch (cacheErr) {
|
||||
// cache write failed, still return the data
|
||||
}
|
||||
} else {
|
||||
console.log(`[OFF] No products found for "${searchTerm}", not caching empty result`);
|
||||
}
|
||||
return products;
|
||||
} catch (err) {
|
||||
lastError = err;
|
||||
console.warn(`[OFF] Request failed for "${searchTerm}" (attempt ${attempt + 1}): ${err.message}`);
|
||||
if (attempt < MAX_RETRIES) {
|
||||
await sleep(RETRY_DELAY_MS * (attempt + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.error(`[OFF] All retries failed for "${searchTerm}": ${lastError?.message}`);
|
||||
return [];
|
||||
} catch (error) {
|
||||
console.error('Error searching baby products from OFF:', error.message);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function getBabyProductDetails(barcode) {
|
||||
if (!barcode) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cacheKey = `off:product:${barcode}`;
|
||||
|
||||
try {
|
||||
const cachedData = await redisClient.get(cacheKey);
|
||||
if (cachedData) {
|
||||
console.log(`Cache hit for OFF product: ${barcode}`);
|
||||
return JSON.parse(cachedData);
|
||||
}
|
||||
|
||||
console.log(`Fetching OFF product details: ${barcode}`);
|
||||
const headers = getOffHeaders();
|
||||
// Use v3 API (recommended) for product details
|
||||
// READ operations don't require auth per OFF docs, only User-Agent
|
||||
const response = await axios.get(`${OFF_API_BASE}/api/v3/product/${barcode}.json`, {
|
||||
headers,
|
||||
timeout: 10000,
|
||||
validateStatus: (status) => status === 200,
|
||||
});
|
||||
|
||||
if (response.data && response.data.product) {
|
||||
const product = transformOFFProduct(response.data.product);
|
||||
|
||||
if (product) {
|
||||
try {
|
||||
await redisClient.setEx(cacheKey, CACHE_TTL, JSON.stringify(product));
|
||||
console.log(`Cached OFF product: ${barcode}`);
|
||||
} catch (cacheErr) {
|
||||
// cache write failed, still return the data
|
||||
}
|
||||
return product;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error(`Error fetching OFF product ${barcode}:`, error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function clearCache(pattern = 'off:*') {
|
||||
try {
|
||||
const keys = await redisClient.keys(pattern);
|
||||
if (keys.length > 0) {
|
||||
await redisClient.del(keys);
|
||||
console.log(`Cleared ${keys.length} OFF cache entries`);
|
||||
return keys.length;
|
||||
}
|
||||
return 0;
|
||||
} catch (error) {
|
||||
console.error('Error clearing OFF cache:', error);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
+461
-16
@@ -19,7 +19,8 @@ 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';
|
||||
|
||||
@@ -96,11 +97,12 @@ const geocodeLimiter = rateLimit({ windowMs: 60_000, max: 10, standardHeaders: t
|
||||
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
|
||||
@@ -238,6 +240,38 @@ async function initDatabase() {
|
||||
await dbRun(`CREATE INDEX IF NOT EXISTS idx_pharmacy_medicine ON pharmacy_medicines(medicine_nregistro)`);
|
||||
}
|
||||
|
||||
// Create junction table for pharmacy-product relationships (CIMA / Open Food Facts)
|
||||
if (pgPool) {
|
||||
await pgPool.query(`
|
||||
CREATE TABLE IF NOT EXISTS pharmacy_products (
|
||||
id SERIAL PRIMARY KEY,
|
||||
pharmacy_id INTEGER NOT NULL REFERENCES pharmacies(id),
|
||||
product_source TEXT NOT NULL,
|
||||
product_off_id TEXT NOT NULL,
|
||||
product_name TEXT,
|
||||
price REAL,
|
||||
stock INTEGER DEFAULT 0,
|
||||
UNIQUE(pharmacy_id, product_source, product_off_id)
|
||||
)
|
||||
`);
|
||||
await pgPool.query(`CREATE INDEX IF NOT EXISTS idx_pharmacy_product ON pharmacy_products(product_source, product_off_id)`);
|
||||
} else {
|
||||
await dbRun(`
|
||||
CREATE TABLE IF NOT EXISTS pharmacy_products (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
pharmacy_id INTEGER NOT NULL,
|
||||
product_source TEXT NOT NULL,
|
||||
product_off_id TEXT NOT NULL,
|
||||
product_name TEXT,
|
||||
price REAL,
|
||||
stock INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id),
|
||||
UNIQUE(pharmacy_id, product_source, product_off_id)
|
||||
)
|
||||
`);
|
||||
await dbRun(`CREATE INDEX IF NOT EXISTS idx_pharmacy_product ON pharmacy_products(product_source, product_off_id)`);
|
||||
}
|
||||
|
||||
// Create users table — PG when available, SQLite fallback
|
||||
if (pgPool) {
|
||||
await pgPool.query(`
|
||||
@@ -313,6 +347,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 +388,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) {
|
||||
@@ -573,6 +631,104 @@ 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' });
|
||||
}
|
||||
});
|
||||
|
||||
// Get pharmacies that sell a specific product (by source and product ID)
|
||||
app.get('/api/products/:source/:productId/pharmacies', async (req, res) => {
|
||||
try {
|
||||
const { source, productId } = req.params;
|
||||
|
||||
if (source !== 'cima' && source !== 'openfoodfacts') {
|
||||
return res.status(400).json({ error: 'Invalid source' });
|
||||
}
|
||||
|
||||
let pharmacies = await userDbAll(`
|
||||
SELECT
|
||||
p.id,
|
||||
p.name,
|
||||
p.address,
|
||||
p.phone,
|
||||
p.latitude,
|
||||
p.longitude,
|
||||
p.opening_hours,
|
||||
pp.price,
|
||||
pp.stock
|
||||
FROM pharmacies p
|
||||
INNER JOIN pharmacy_products pp ON p.id = pp.pharmacy_id
|
||||
WHERE pp.product_source = ? AND pp.product_off_id = ?
|
||||
ORDER BY p.name
|
||||
`, [source, productId]);
|
||||
|
||||
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 for product:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// ========== AUTHENTICATION MIDDLEWARE ==========
|
||||
|
||||
// Middleware to check if user is authenticated
|
||||
@@ -1606,10 +1762,9 @@ app.delete('/api/admin/pharmacies/:id', requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const pharmacyId = parseInt(req.params.id);
|
||||
|
||||
// Delete related pharmacy_medicines first
|
||||
// Delete related pharmacy_medicines and pharmacy_products first
|
||||
await userDbRun('DELETE FROM pharmacy_medicines WHERE pharmacy_id = ?', [pharmacyId]);
|
||||
|
||||
// Delete the pharmacy
|
||||
await userDbRun('DELETE FROM pharmacy_products WHERE pharmacy_id = ?', [pharmacyId]);
|
||||
await userDbRun('DELETE FROM pharmacies WHERE id = ?', [pharmacyId]);
|
||||
|
||||
res.json({ message: 'Pharmacy deleted successfully' });
|
||||
@@ -1827,6 +1982,115 @@ app.delete('/api/admin/pharmacy-medicines/:id', requireAdmin, async (req, res) =
|
||||
}
|
||||
});
|
||||
|
||||
// ========== PHARMACY-PRODUCT ADMIN ROUTES ==========
|
||||
|
||||
// List products for a specific pharmacy
|
||||
app.get('/api/admin/pharmacies/:pharmacyId/products', requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const pharmacyId = parseInt(req.params.pharmacyId);
|
||||
|
||||
const products = await userDbAll(`
|
||||
SELECT
|
||||
pp.id,
|
||||
pp.pharmacy_id,
|
||||
pp.product_source,
|
||||
pp.product_off_id,
|
||||
pp.product_name,
|
||||
pp.price,
|
||||
pp.stock
|
||||
FROM pharmacy_products pp
|
||||
WHERE pp.pharmacy_id = ?
|
||||
ORDER BY pp.product_name
|
||||
`, [pharmacyId]);
|
||||
|
||||
res.json(products);
|
||||
} catch (error) {
|
||||
console.error('Error fetching pharmacy products:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Add/upsert a product-pharmacy link
|
||||
app.post('/api/admin/pharmacy-products', requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const { pharmacy_id, product_source, product_off_id, product_name, price, stock } = req.body;
|
||||
|
||||
if (!pharmacy_id || !product_source || !product_off_id) {
|
||||
return res.status(400).json({ error: 'pharmacy_id, product_source, and product_off_id are required' });
|
||||
}
|
||||
|
||||
if (product_source !== 'cima' && product_source !== 'openfoodfacts') {
|
||||
return res.status(400).json({ error: 'product_source must be "cima" or "openfoodfacts"' });
|
||||
}
|
||||
|
||||
const existing = await userDbGet(
|
||||
'SELECT * FROM pharmacy_products WHERE pharmacy_id = ? AND product_source = ? AND product_off_id = ?',
|
||||
[pharmacy_id, product_source, product_off_id]
|
||||
);
|
||||
|
||||
if (existing) {
|
||||
await userDbRun(
|
||||
'UPDATE pharmacy_products SET product_name = ?, price = ?, stock = ? WHERE pharmacy_id = ? AND product_source = ? AND product_off_id = ?',
|
||||
[product_name || null, price || null, stock || 0, pharmacy_id, product_source, product_off_id]
|
||||
);
|
||||
} else {
|
||||
await userDbRun(
|
||||
'INSERT INTO pharmacy_products (pharmacy_id, product_source, product_off_id, product_name, price, stock) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
[pharmacy_id, product_source, product_off_id, product_name || null, price || null, stock || 0]
|
||||
);
|
||||
}
|
||||
|
||||
const relationship = await userDbGet(
|
||||
'SELECT * FROM pharmacy_products WHERE pharmacy_id = ? AND product_source = ? AND product_off_id = ?',
|
||||
[pharmacy_id, product_source, product_off_id]
|
||||
);
|
||||
|
||||
res.status(201).json(relationship);
|
||||
} catch (error) {
|
||||
console.error('Error adding pharmacy product:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Update price/stock for a pharmacy-product link
|
||||
app.put('/api/admin/pharmacy-products/:id', requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const id = parseInt(req.params.id);
|
||||
const { price, stock } = req.body;
|
||||
|
||||
await userDbRun(
|
||||
'UPDATE pharmacy_products SET price = ?, stock = ? WHERE id = ?',
|
||||
[price || null, stock || 0, id]
|
||||
);
|
||||
|
||||
const updated = await userDbGet(
|
||||
'SELECT * FROM pharmacy_products WHERE id = ?',
|
||||
[id]
|
||||
);
|
||||
|
||||
if (!updated) {
|
||||
return res.status(404).json({ error: 'Relationship not found' });
|
||||
}
|
||||
|
||||
res.json(updated);
|
||||
} catch (error) {
|
||||
console.error('Error updating pharmacy product:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Delete a pharmacy-product link
|
||||
app.delete('/api/admin/pharmacy-products/:id', requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const id = parseInt(req.params.id);
|
||||
await userDbRun('DELETE FROM pharmacy_products WHERE id = ?', [id]);
|
||||
res.json({ message: 'Product removed from pharmacy successfully' });
|
||||
} catch (error) {
|
||||
console.error('Error deleting pharmacy product:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Push notifications
|
||||
|
||||
app.get('/api/notifications/vapid-public-key', (req, res) => {
|
||||
@@ -1919,6 +2183,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 {
|
||||
@@ -1979,7 +2338,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 = ?',
|
||||
@@ -1990,7 +2349,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 });
|
||||
@@ -1998,21 +2357,39 @@ async function sendPushForMedicine({ medicine_nregistro, medicine_name, pharmacy
|
||||
|
||||
if (subs.length === 0) return { sent: 0, failed: 0, pruned: 0 };
|
||||
|
||||
// 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;
|
||||
|
||||
// Web Push via VAPID
|
||||
if (PUSH_ENABLED && webSubs.length > 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)}`,
|
||||
title,
|
||||
body,
|
||||
url,
|
||||
medicine_nregistro,
|
||||
medicine_name: medicine_name || null,
|
||||
pharmacy_id: pharmacy?.id ?? null,
|
||||
pharmacy_name: pharmacy?.name ?? null,
|
||||
});
|
||||
|
||||
let sent = 0;
|
||||
let failed = 0;
|
||||
let pruned = 0;
|
||||
|
||||
await Promise.all(subs.map(async (sub) => {
|
||||
await Promise.all(webSubs.map(async (sub) => {
|
||||
try {
|
||||
await webpush.sendNotification(
|
||||
{ endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth } },
|
||||
@@ -2031,10 +2408,78 @@ async function sendPushForMedicine({ medicine_nregistro, medicine_name, pharmacy
|
||||
pruned++;
|
||||
} catch {}
|
||||
} else {
|
||||
console.error('[push] send failed:', status, err?.body || err?.message);
|
||||
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++;
|
||||
} else {
|
||||
failed++;
|
||||
// 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;
|
||||
}
|
||||
} else {
|
||||
failed += chunk.length;
|
||||
console.error('[push] expo send failed:', response.status);
|
||||
}
|
||||
} catch (err) {
|
||||
failed += chunk.length;
|
||||
console.error('[push] expo send error:', err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { sent, failed, pruned };
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { View, Text, StyleSheet, FlatList, TouchableOpacity, Alert, useWindowDimensions } from 'react-native';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { useAuth } from '../../hooks/useAuth';
|
||||
import { spacing, borderRadius, shadows } from '../../constants/theme';
|
||||
import { LoadingSpinner } from '../../components/LoadingSpinner';
|
||||
import api from '../../services/api';
|
||||
@@ -20,17 +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(() => {
|
||||
if (!authLoading && isAuthenticated) {
|
||||
loadNotifications();
|
||||
}, []);
|
||||
} else if (!authLoading && !isAuthenticated) {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [authLoading, isAuthenticated]);
|
||||
|
||||
async function loadNotifications() {
|
||||
setIsLoading(true);
|
||||
@@ -123,10 +131,28 @@ 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, { backgroundColor: colors.background }]}>
|
||||
<View style={[styles.header, isTablet && styles.headerTablet]}>
|
||||
@@ -172,6 +198,32 @@ const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
},
|
||||
centered: {
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
paddingHorizontal: spacing.xl,
|
||||
gap: spacing.md,
|
||||
},
|
||||
loginTitle: {
|
||||
fontSize: 20,
|
||||
fontWeight: '600',
|
||||
textAlign: 'center',
|
||||
},
|
||||
loginSubtitle: {
|
||||
fontSize: 14,
|
||||
textAlign: 'center',
|
||||
lineHeight: 20,
|
||||
},
|
||||
loginButton: {
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingVertical: spacing.md,
|
||||
borderRadius: borderRadius.lg,
|
||||
marginTop: spacing.sm,
|
||||
},
|
||||
loginButtonText: {
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
},
|
||||
header: {
|
||||
paddingHorizontal: spacing.lg,
|
||||
paddingTop: spacing.lg,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { View, FlatList, StyleSheet, Text, TouchableOpacity, useWindowDimensions } from 'react-native';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { useNavigation } from 'expo-router';
|
||||
import { useNavigation, useRouter } from 'expo-router';
|
||||
import { SearchBar } from '../../components/SearchBar';
|
||||
import { MedicineCard } from '../../components/MedicineCard';
|
||||
import { LoadingSpinner } from '../../components/LoadingSpinner';
|
||||
@@ -9,6 +9,7 @@ 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';
|
||||
@@ -31,11 +32,14 @@ export default function SearchScreen() {
|
||||
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();
|
||||
@@ -43,6 +47,8 @@ export default function SearchScreen() {
|
||||
const unsubscribe = parent.addListener('tabPress', () => {
|
||||
setQuery('');
|
||||
setResults([]);
|
||||
setProducts([]);
|
||||
setSearchMode('all');
|
||||
setIsLoading(false);
|
||||
setError(null);
|
||||
});
|
||||
@@ -52,6 +58,7 @@ export default function SearchScreen() {
|
||||
useEffect(() => {
|
||||
if (debouncedQuery.length < 2) {
|
||||
setResults([]);
|
||||
setProducts([]);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -69,7 +76,17 @@ export default function SearchScreen() {
|
||||
}
|
||||
};
|
||||
|
||||
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) => {
|
||||
@@ -77,7 +94,7 @@ export default function SearchScreen() {
|
||||
if (searchQuery.trim()) addSearch(searchQuery);
|
||||
};
|
||||
|
||||
const showSuggestions = !query && !isLoading && results.length === 0;
|
||||
const showSuggestions = !query && !isLoading && results.length === 0 && products.length === 0;
|
||||
|
||||
return (
|
||||
<View style={[styles.container, { backgroundColor: colors.background }]}>
|
||||
@@ -87,6 +104,20 @@ export default function SearchScreen() {
|
||||
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]}>
|
||||
@@ -130,7 +161,7 @@ export default function SearchScreen() {
|
||||
</>
|
||||
)}
|
||||
|
||||
{isLoading && <LoadingSpinner message="Buscando medicamentos..." />}
|
||||
{isLoading && <LoadingSpinner message="Buscando..." />}
|
||||
|
||||
{error && (
|
||||
<View style={[styles.errorContainer, isTablet && styles.errorContainerTablet, { backgroundColor: colors.dangerContainer }]}>
|
||||
@@ -138,16 +169,43 @@ export default function SearchScreen() {
|
||||
</View>
|
||||
)}
|
||||
|
||||
{!isLoading && !error && results.length === 0 && query.length >= 2 && (
|
||||
{!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 medicamentos</Text>
|
||||
<Text style={[styles.emptyText, { color: colors.textSecondary }]}>No se encontraron resultados</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
<FlatList
|
||||
data={results}
|
||||
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}
|
||||
/>
|
||||
@@ -159,6 +217,34 @@ 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',
|
||||
@@ -245,4 +331,38 @@ const styles = StyleSheet.create({
|
||||
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,7 +1,7 @@
|
||||
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';
|
||||
@@ -11,6 +11,9 @@ import { ThemeProvider, useThemeContext } from '../components/ThemeProvider';
|
||||
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
const bgLight = require('../assets/bg.png');
|
||||
const bgDark = require('../assets/bg_dark.png');
|
||||
|
||||
function RootLayoutInner() {
|
||||
const { checkAuth } = useAuthStore();
|
||||
const { colors, isDark } = useThemeContext();
|
||||
@@ -81,37 +84,56 @@ function RootLayoutInner() {
|
||||
);
|
||||
}
|
||||
|
||||
function ThemedBackground({ children }: { children: React.ReactNode }) {
|
||||
const { isDark } = useThemeContext();
|
||||
|
||||
return (
|
||||
<View style={styles.root}>
|
||||
<Image
|
||||
source={isDark ? bgDark : bgLight}
|
||||
style={styles.bgImage}
|
||||
resizeMode="cover"
|
||||
/>
|
||||
<View style={[styles.overlay, isDark && styles.overlayDark]} pointerEvents="none" />
|
||||
<View style={styles.content}>
|
||||
{children}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export default function RootLayout() {
|
||||
return (
|
||||
<GestureHandlerRootView style={{ flex: 1 }}>
|
||||
<ImageBackground
|
||||
source={require('../assets/bg.png')}
|
||||
style={bgStyles.background}
|
||||
resizeMode="cover"
|
||||
imageStyle={bgStyles.backgroundImage}
|
||||
>
|
||||
<View style={bgStyles.overlay} />
|
||||
<GestureHandlerRootView style={styles.root}>
|
||||
<SafeAreaProvider>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<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: {
|
||||
...StyleSheet.absoluteFillObject,
|
||||
opacity: 0.55,
|
||||
},
|
||||
overlay: {
|
||||
...StyleSheet.absoluteFillObject,
|
||||
backgroundColor: 'rgba(255, 252, 245, 0.2)',
|
||||
backgroundColor: 'rgba(255, 252, 245, 0.48)',
|
||||
},
|
||||
overlayDark: {
|
||||
backgroundColor: 'rgba(0, 0, 0, 0.25)',
|
||||
},
|
||||
content: {
|
||||
flex: 1,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -7,34 +7,48 @@ import {
|
||||
StyleSheet,
|
||||
KeyboardAvoidingView,
|
||||
Platform,
|
||||
Alert
|
||||
Alert,
|
||||
Image,
|
||||
} from 'react-native';
|
||||
import { useRouter } from 'expo-router';
|
||||
import { Ionicons } from '@expo/vector-icons';
|
||||
import { useAuthStore } from '../../store/authStore';
|
||||
import { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { spacing, borderRadius } from '../../constants/theme';
|
||||
import { register } from '../../services/auth';
|
||||
import { spacing, borderRadius, shadows } from '../../constants/theme';
|
||||
import {
|
||||
isBiometricsAvailable,
|
||||
authenticateWithBiometrics,
|
||||
saveBiometricCredentials,
|
||||
getBiometricUsername
|
||||
getBiometricUsername,
|
||||
} from '../../services/biometrics';
|
||||
|
||||
type Tab = 'login' | 'register';
|
||||
|
||||
export default function LoginScreen() {
|
||||
const router = useRouter();
|
||||
const { login } = useAuthStore();
|
||||
const { colors } = useThemeContext();
|
||||
const [tab, setTab] = useState<Tab>('login');
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [confirmPassword, setConfirmPassword] = useState('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [biometricsAvailable, setBiometricsAvailable] = useState(false);
|
||||
const [biometricUsername, setBiometricUsername] = useState<string | null>(null);
|
||||
|
||||
const isRegister = tab === 'register';
|
||||
|
||||
useEffect(() => {
|
||||
checkBiometrics();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setUsername('');
|
||||
setPassword('');
|
||||
setConfirmPassword('');
|
||||
}, [tab]);
|
||||
|
||||
const checkBiometrics = async () => {
|
||||
try {
|
||||
const available = await isBiometricsAvailable();
|
||||
@@ -48,21 +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);
|
||||
if (isRegister) {
|
||||
await register(username.trim(), password);
|
||||
Alert.alert('Éxito', 'Cuenta creada correctamente', [
|
||||
{ text: 'OK', onPress: () => setTab('login') },
|
||||
]);
|
||||
} else {
|
||||
await login(username.trim(), password);
|
||||
if (biometricsAvailable) {
|
||||
await saveBiometricCredentials(username);
|
||||
await saveBiometricCredentials(username.trim());
|
||||
}
|
||||
router.replace('/(tabs)');
|
||||
}
|
||||
} catch (error) {
|
||||
Alert.alert('Error', 'Credenciales incorrectas');
|
||||
Alert.alert(
|
||||
'Error',
|
||||
isRegister ? 'No se pudo crear la cuenta' : 'Credenciales incorrectas'
|
||||
);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -95,61 +130,162 @@ export default function LoginScreen() {
|
||||
style={[styles.container, { backgroundColor: colors.background }]}
|
||||
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
|
||||
>
|
||||
<View style={styles.form}>
|
||||
<Text style={[styles.title, { color: colors.text }]}>Iniciar Sesión</Text>
|
||||
<Text style={[styles.subtitle, { color: colors.textSecondary }]}>Ingresa tus credenciales para continuar</Text>
|
||||
<View style={styles.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, { color: colors.text }]}>Usuario</Text>
|
||||
{/* Tabs */}
|
||||
<View style={[styles.tabBar, { backgroundColor: colors.surfaceLow }]}>
|
||||
<TouchableOpacity
|
||||
style={[
|
||||
styles.tab,
|
||||
!isRegister && [styles.tabActive, { backgroundColor: colors.primary }],
|
||||
]}
|
||||
onPress={() => setTab('login')}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Text
|
||||
style={[
|
||||
styles.tabText,
|
||||
{ color: isRegister ? colors.textSecondary : colors.onPrimaryContainer },
|
||||
!isRegister && styles.tabTextActive,
|
||||
]}
|
||||
>
|
||||
Iniciar Sesión
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
<TouchableOpacity
|
||||
style={[
|
||||
styles.tab,
|
||||
isRegister && [styles.tabActive, { backgroundColor: colors.primary }],
|
||||
]}
|
||||
onPress={() => setTab('register')}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Text
|
||||
style={[
|
||||
styles.tabText,
|
||||
{ color: !isRegister ? colors.textSecondary : colors.onPrimaryContainer },
|
||||
isRegister && styles.tabTextActive,
|
||||
]}
|
||||
>
|
||||
Crear Cuenta
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
</View>
|
||||
|
||||
{/* Card */}
|
||||
<View style={[styles.card, { backgroundColor: colors.card }, shadows.card]}>
|
||||
{/* Header */}
|
||||
<Text style={[styles.title, { color: colors.text }]}>
|
||||
{isRegister ? 'Crea tu cuenta' : 'Bienvenido de nuevo'}
|
||||
</Text>
|
||||
<Text style={[styles.subtitle, { color: colors.textSecondary }]}>
|
||||
{isRegister
|
||||
? 'Guarda tu dirección y recibe notificaciones cuando lleguen medicamentos.'
|
||||
: 'Inicia sesión para gestionar tu perfil y notificaciones.'}
|
||||
</Text>
|
||||
|
||||
{/* Username */}
|
||||
<View style={[styles.inputWrapper, { backgroundColor: colors.surfaceLow, borderColor: colors.border }]}>
|
||||
<Ionicons name="person-outline" size={20} color={colors.textSecondary} style={styles.inputIcon} />
|
||||
<TextInput
|
||||
style={[styles.input, { backgroundColor: colors.card, color: colors.text }]}
|
||||
style={[styles.input, { color: colors.text }]}
|
||||
value={username}
|
||||
onChangeText={setUsername}
|
||||
placeholder="Tu usuario"
|
||||
placeholder="Usuario"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
autoComplete="username"
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={styles.inputContainer}>
|
||||
<Text style={[styles.label, { color: colors.text }]}>Contraseña</Text>
|
||||
{/* Password */}
|
||||
<View style={[styles.inputWrapper, { backgroundColor: colors.surfaceLow, borderColor: colors.border }]}>
|
||||
<Ionicons name="lock-closed-outline" size={20} color={colors.textSecondary} style={styles.inputIcon} />
|
||||
<TextInput
|
||||
style={[styles.input, { backgroundColor: colors.card, color: colors.text }]}
|
||||
style={[styles.input, { color: colors.text }]}
|
||||
value={password}
|
||||
onChangeText={setPassword}
|
||||
placeholder="Tu contraseña"
|
||||
placeholder="Contraseña"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
secureTextEntry
|
||||
autoComplete={isRegister ? 'new-password' : 'current-password'}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{/* Confirm password (register only) */}
|
||||
{isRegister && (
|
||||
<View style={[styles.inputWrapper, { backgroundColor: colors.surfaceLow, borderColor: colors.border }]}>
|
||||
<Ionicons name="lock-closed-outline" size={20} color={colors.textSecondary} style={styles.inputIcon} />
|
||||
<TextInput
|
||||
style={[styles.input, { color: colors.text }]}
|
||||
value={confirmPassword}
|
||||
onChangeText={setConfirmPassword}
|
||||
placeholder="Confirmar contraseña"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
secureTextEntry
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Hints (register only) */}
|
||||
{isRegister && (
|
||||
<View style={styles.hints}>
|
||||
<Text style={[styles.hint, { color: colors.textSecondary }]}>
|
||||
<Ionicons name="information-circle-outline" size={14} color={colors.textSecondary} /> 3-32 caracteres para el usuario
|
||||
</Text>
|
||||
<Text style={[styles.hint, { color: colors.textSecondary }]}>
|
||||
<Ionicons name="information-circle-outline" size={14} color={colors.textSecondary} /> Mínimo 8 caracteres para la contraseña
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Submit button */}
|
||||
<TouchableOpacity
|
||||
style={[styles.button, isLoading && styles.buttonDisabled]}
|
||||
onPress={handleLogin}
|
||||
style={[styles.button, { backgroundColor: colors.primary }, isLoading && styles.buttonDisabled]}
|
||||
onPress={handleSubmit}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Text style={styles.buttonText}>
|
||||
{isLoading ? 'Ingresando...' : 'Iniciar Sesión'}
|
||||
{isLoading ? (
|
||||
<Ionicons name="hourglass" size={20} color={colors.onPrimaryContainer} />
|
||||
) : (
|
||||
<Text style={[styles.buttonText, { color: colors.onPrimaryContainer }]}>
|
||||
{isRegister ? 'Crear Cuenta' : 'Iniciar Sesión'}
|
||||
</Text>
|
||||
)}
|
||||
</TouchableOpacity>
|
||||
|
||||
{biometricsAvailable && biometricUsername && (
|
||||
{/* Biometrics (login only) */}
|
||||
{!isRegister && biometricsAvailable && biometricUsername && (
|
||||
<TouchableOpacity
|
||||
style={[styles.biometricButton, { backgroundColor: colors.card, borderColor: colors.primary }]}
|
||||
style={[styles.biometricButton, { borderColor: colors.primary }]}
|
||||
onPress={handleBiometricLogin}
|
||||
disabled={isLoading}
|
||||
>
|
||||
<Ionicons name="finger-print" size={24} color={colors.primary} />
|
||||
<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, { color: colors.primary }]}>¿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,54 +296,102 @@ const styles = StyleSheet.create({
|
||||
container: {
|
||||
flex: 1,
|
||||
},
|
||||
form: {
|
||||
content: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
padding: spacing.xl,
|
||||
paddingHorizontal: spacing.lg,
|
||||
gap: spacing.lg,
|
||||
},
|
||||
title: {
|
||||
fontSize: 28,
|
||||
fontWeight: 'bold',
|
||||
marginBottom: spacing.sm,
|
||||
logoSection: {
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
},
|
||||
subtitle: {
|
||||
fontSize: 16,
|
||||
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',
|
||||
},
|
||||
tabTextActive: {
|
||||
fontWeight: '700',
|
||||
},
|
||||
card: {
|
||||
borderRadius: borderRadius.xl,
|
||||
padding: spacing.lg,
|
||||
gap: spacing.sm,
|
||||
},
|
||||
title: {
|
||||
fontSize: 22,
|
||||
fontWeight: '700',
|
||||
marginBottom: spacing.xs,
|
||||
},
|
||||
input: {
|
||||
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,
|
||||
},
|
||||
hints: {
|
||||
gap: 2,
|
||||
marginTop: spacing.xs,
|
||||
},
|
||||
hint: {
|
||||
fontSize: 12,
|
||||
lineHeight: 18,
|
||||
},
|
||||
button: {
|
||||
backgroundColor: '#7fbf8f',
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
alignItems: 'center',
|
||||
marginTop: spacing.md,
|
||||
marginTop: spacing.sm,
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
buttonDisabled: {
|
||||
opacity: 0.6,
|
||||
},
|
||||
buttonText: {
|
||||
color: '#ffffff',
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
},
|
||||
linkButton: {
|
||||
marginTop: spacing.lg,
|
||||
alignItems: 'center',
|
||||
},
|
||||
linkText: {
|
||||
fontSize: 14,
|
||||
fontWeight: '700',
|
||||
},
|
||||
biometricButton: {
|
||||
flexDirection: 'row',
|
||||
@@ -215,12 +399,20 @@ const styles = StyleSheet.create({
|
||||
justifyContent: 'center',
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
marginTop: spacing.md,
|
||||
marginTop: spacing.xs,
|
||||
borderWidth: 1,
|
||||
gap: spacing.sm,
|
||||
},
|
||||
biometricText: {
|
||||
fontSize: 16,
|
||||
fontSize: 15,
|
||||
fontWeight: '600',
|
||||
},
|
||||
linkButton: {
|
||||
alignItems: 'center',
|
||||
paddingVertical: spacing.sm,
|
||||
},
|
||||
linkText: {
|
||||
fontSize: 14,
|
||||
fontWeight: '600',
|
||||
marginLeft: spacing.sm,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,167 +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 { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { spacing, borderRadius } from '../../constants/theme';
|
||||
import { Redirect } from 'expo-router';
|
||||
|
||||
export default function RegisterScreen() {
|
||||
const router = useRouter();
|
||||
const { colors } = useThemeContext();
|
||||
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, { backgroundColor: colors.background }]}
|
||||
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
|
||||
>
|
||||
<View style={styles.form}>
|
||||
<Text style={[styles.title, { color: colors.text }]}>Crear Cuenta</Text>
|
||||
<Text style={[styles.subtitle, { color: colors.textSecondary }]}>Regístrate para empezar</Text>
|
||||
|
||||
<View style={styles.inputContainer}>
|
||||
<Text style={[styles.label, { color: colors.text }]}>Usuario</Text>
|
||||
<TextInput
|
||||
style={[styles.input, { backgroundColor: colors.card, color: colors.text }]}
|
||||
value={username}
|
||||
onChangeText={setUsername}
|
||||
placeholder="Elige un usuario"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={styles.inputContainer}>
|
||||
<Text style={[styles.label, { color: colors.text }]}>Contraseña</Text>
|
||||
<TextInput
|
||||
style={[styles.input, { backgroundColor: colors.card, color: colors.text }]}
|
||||
value={password}
|
||||
onChangeText={setPassword}
|
||||
placeholder="Elige una contraseña"
|
||||
placeholderTextColor={colors.textSecondary}
|
||||
secureTextEntry
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View style={styles.inputContainer}>
|
||||
<Text style={[styles.label, { color: colors.text }]}>Confirmar Contraseña</Text>
|
||||
<TextInput
|
||||
style={[styles.input, { backgroundColor: colors.card, color: colors.text }]}
|
||||
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, { color: colors.primary }]}>¿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,
|
||||
},
|
||||
form: {
|
||||
flex: 1,
|
||||
justifyContent: 'center',
|
||||
padding: spacing.xl,
|
||||
},
|
||||
title: {
|
||||
fontSize: 28,
|
||||
fontWeight: 'bold',
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
subtitle: {
|
||||
fontSize: 16,
|
||||
marginBottom: spacing.xl,
|
||||
},
|
||||
inputContainer: {
|
||||
marginBottom: spacing.md,
|
||||
},
|
||||
label: {
|
||||
fontSize: 14,
|
||||
fontWeight: '500',
|
||||
marginBottom: spacing.xs,
|
||||
},
|
||||
input: {
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
fontSize: 16,
|
||||
},
|
||||
button: {
|
||||
backgroundColor: '#7fbf8f',
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
alignItems: 'center',
|
||||
marginTop: spacing.md,
|
||||
},
|
||||
buttonDisabled: {
|
||||
opacity: 0.6,
|
||||
},
|
||||
buttonText: {
|
||||
color: '#ffffff',
|
||||
fontSize: 16,
|
||||
fontWeight: '600',
|
||||
},
|
||||
linkButton: {
|
||||
marginTop: spacing.lg,
|
||||
alignItems: 'center',
|
||||
},
|
||||
linkText: {
|
||||
fontSize: 14,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -4,6 +4,8 @@ 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 { useThemeContext } from '../../components/ThemeProvider';
|
||||
@@ -40,6 +42,7 @@ 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);
|
||||
@@ -47,6 +50,8 @@ export default function MedicineDetailScreen() {
|
||||
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;
|
||||
@@ -96,6 +101,24 @@ export default function MedicineDetailScreen() {
|
||||
}
|
||||
};
|
||||
|
||||
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;
|
||||
|
||||
@@ -148,7 +171,22 @@ export default function MedicineDetailScreen() {
|
||||
<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, { backgroundColor: colors.card }]}>
|
||||
@@ -277,12 +315,24 @@ const styles = StyleSheet.create({
|
||||
alignItems: 'flex-start',
|
||||
padding: spacing.lg,
|
||||
},
|
||||
headerRight: {
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: spacing.sm,
|
||||
},
|
||||
name: {
|
||||
flex: 1,
|
||||
fontSize: 22,
|
||||
fontWeight: 'bold',
|
||||
marginRight: spacing.sm,
|
||||
},
|
||||
bellButton: {
|
||||
width: 36,
|
||||
height: 36,
|
||||
borderRadius: 18,
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
},
|
||||
infoSection: {
|
||||
marginTop: spacing.sm,
|
||||
padding: spacing.lg,
|
||||
|
||||
@@ -4,6 +4,8 @@ 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 { useThemeContext } from '../../components/ThemeProvider';
|
||||
import { spacing, borderRadius } from '../../constants/theme';
|
||||
@@ -13,9 +15,11 @@ 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;
|
||||
@@ -51,6 +55,27 @@ 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..." />;
|
||||
}
|
||||
@@ -124,10 +149,12 @@ export default function PharmacyDetailScreen() {
|
||||
{medicines.length === 0 ? (
|
||||
<Text style={[styles.noMedicines, { color: colors.textSecondary }]}>No hay medicamentos disponibles</Text>
|
||||
) : (
|
||||
medicines.map((med) => (
|
||||
medicines.map((med) => {
|
||||
const isSub = subscribedMeds.has(med.medicine_nregistro);
|
||||
return (
|
||||
<View key={med.id} style={[styles.medicineCard, { backgroundColor: colors.card }]}>
|
||||
<TouchableOpacity
|
||||
key={med.id}
|
||||
style={[styles.medicineCard, { backgroundColor: colors.card }]}
|
||||
style={styles.medicineCardContent}
|
||||
onPress={() => router.push(`/medicine/${med.medicine_nregistro}`)}
|
||||
>
|
||||
<View style={styles.medicineInfo}>
|
||||
@@ -139,7 +166,24 @@ export default function PharmacyDetailScreen() {
|
||||
<Text style={[styles.stock, { color: colors.textSecondary }]}>Stock: {med.stock}</Text>
|
||||
</View>
|
||||
</TouchableOpacity>
|
||||
))
|
||||
{isAuthenticated && (
|
||||
<TouchableOpacity
|
||||
style={[styles.bellButton, { backgroundColor: isSub ? colors.primary : colors.surfaceVariant, borderTopColor: colors.border }]}
|
||||
onPress={() => handleToggleMedSubscription(med.medicine_nregistro, med.medicine_name)}
|
||||
>
|
||||
<Ionicons
|
||||
name={isSub ? 'notifications' : 'notifications-outline'}
|
||||
size={18}
|
||||
color={isSub ? '#fff' : colors.textSecondary}
|
||||
/>
|
||||
<Text style={[styles.bellText, { color: isSub ? '#fff' : colors.textSecondary }]}>
|
||||
{isSub ? 'Notificaciones activas' : 'Notificarme cuando haya stock'}
|
||||
</Text>
|
||||
</TouchableOpacity>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</View>
|
||||
</ScrollView>
|
||||
@@ -207,11 +251,14 @@ const styles = StyleSheet.create({
|
||||
padding: spacing.xl,
|
||||
},
|
||||
medicineCard: {
|
||||
borderRadius: borderRadius.md,
|
||||
marginBottom: spacing.sm,
|
||||
overflow: 'hidden',
|
||||
},
|
||||
medicineCardContent: {
|
||||
flexDirection: 'row',
|
||||
justifyContent: 'space-between',
|
||||
borderRadius: borderRadius.md,
|
||||
padding: spacing.md,
|
||||
marginBottom: spacing.sm,
|
||||
},
|
||||
medicineInfo: {
|
||||
flex: 1,
|
||||
@@ -235,6 +282,18 @@ const styles = StyleSheet.create({
|
||||
fontSize: 12,
|
||||
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',
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
});
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.5 MiB |
@@ -26,7 +26,7 @@ export const colors = {
|
||||
warning: '#FF9500',
|
||||
|
||||
// Surface
|
||||
background: '#fbfbfb',
|
||||
background: 'transparent',
|
||||
card: '#ffffff',
|
||||
surfaceLow: '#f2f4f5',
|
||||
surface: '#eceeef',
|
||||
@@ -72,7 +72,7 @@ export const darkColors = {
|
||||
warning: '#FF9500',
|
||||
|
||||
// Surface
|
||||
background: '#121212',
|
||||
background: 'transparent',
|
||||
card: '#1e1e1e',
|
||||
surfaceLow: '#2a2a2a',
|
||||
surface: '#333333',
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import React, { useState, useEffect } from 'react';
|
||||
import './App.css';
|
||||
import HomeView from './views/HomeView';
|
||||
import SearchView from './views/SearchView';
|
||||
import ProductView from './views/ProductView';
|
||||
import ScannerView from './views/ScannerView';
|
||||
import AlertsView from './views/AlertsView';
|
||||
import ProfileView from './views/ProfileView';
|
||||
@@ -19,6 +20,7 @@ function App() {
|
||||
const [showSaved, setShowSaved] = useState(false);
|
||||
const [badgeCount, setBadgeCount] = useState(0);
|
||||
const [prescriptionSearch, setPrescriptionSearch] = useState('');
|
||||
const [productScreen, setProductScreen] = useState(null);
|
||||
const [screenSize, setScreenSize] = useState({
|
||||
width: window.innerWidth,
|
||||
height: window.innerHeight
|
||||
@@ -180,6 +182,19 @@ function App() {
|
||||
currentUser={currentUser}
|
||||
onLoginRequest={() => setShowLogin(true)}
|
||||
initialQuery={prescriptionSearch}
|
||||
onNavigateToProduct={(source, id) => {
|
||||
setProductScreen({ source, id });
|
||||
setScreen('product');
|
||||
}}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
case 'product':
|
||||
activeView = (
|
||||
<ProductView
|
||||
source={productScreen?.source}
|
||||
id={productScreen?.id}
|
||||
onBack={() => { setProductScreen(null); setScreen('search'); }}
|
||||
/>
|
||||
);
|
||||
break;
|
||||
|
||||
@@ -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;
|
||||
@@ -397,6 +397,28 @@
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
|
||||
/* Source badges */
|
||||
.source-badge {
|
||||
display: inline-block;
|
||||
padding: 0.15rem 0.5rem;
|
||||
border-radius: 4px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.source-badge--cima {
|
||||
background: rgba(37, 99, 235, 0.12);
|
||||
color: #2563eb;
|
||||
}
|
||||
|
||||
.source-badge--off {
|
||||
background: rgba(16, 185, 129, 0.12);
|
||||
color: #10b981;
|
||||
}
|
||||
|
||||
/* Pharmacies: search, region import, list filter */
|
||||
.pharmacy-tools-card {
|
||||
background: var(--surface);
|
||||
|
||||
@@ -0,0 +1,421 @@
|
||||
import React, { useState, useEffect, useMemo, useRef } from 'react';
|
||||
import './AdminComponents.css';
|
||||
|
||||
const MAX_PHARMACY_RESULTS = 25;
|
||||
|
||||
function normalize(s) {
|
||||
return (s || '').toString().toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '');
|
||||
}
|
||||
|
||||
function PharmacyProductLink() {
|
||||
const [pharmacies, setPharmacies] = useState([]);
|
||||
const [productSearch, setProductSearch] = useState('');
|
||||
const [productResults, setProductResults] = useState([]);
|
||||
const [selectedPharmacy, setSelectedPharmacy] = useState(null);
|
||||
const [selectedProduct, setSelectedProduct] = useState(null);
|
||||
const [pharmacyProducts, setPharmacyProducts] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [searching, setSearching] = useState(false);
|
||||
const [pharmacyQuery, setPharmacyQuery] = useState('');
|
||||
const [pharmacyDropdownOpen, setPharmacyDropdownOpen] = useState(false);
|
||||
const pharmacyInputRef = useRef(null);
|
||||
const [formData, setFormData] = useState({
|
||||
pharmacy_id: '',
|
||||
price: '',
|
||||
stock: ''
|
||||
});
|
||||
|
||||
const filteredPharmacies = useMemo(() => {
|
||||
const q = normalize(pharmacyQuery).trim();
|
||||
if (!q) return pharmacies.slice(0, MAX_PHARMACY_RESULTS);
|
||||
const tokens = q.split(/\s+/).filter(Boolean);
|
||||
return pharmacies
|
||||
.filter(p => {
|
||||
const hay = `${normalize(p.name)} ${normalize(p.address)}`;
|
||||
return tokens.every(tok => hay.includes(tok));
|
||||
})
|
||||
.slice(0, MAX_PHARMACY_RESULTS);
|
||||
}, [pharmacies, pharmacyQuery]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchPharmacies();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedPharmacy) {
|
||||
fetchPharmacyProducts(selectedPharmacy.id);
|
||||
}
|
||||
}, [selectedPharmacy]);
|
||||
|
||||
// Buscar productos en la API mientras el usuario escribe
|
||||
useEffect(() => {
|
||||
const q = productSearch.trim();
|
||||
if (q.length < 2) {
|
||||
setProductResults([]);
|
||||
setSearching(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(async () => {
|
||||
setSearching(true);
|
||||
try {
|
||||
const response = await fetch(`/api/products/search?q=${encodeURIComponent(q)}`, {
|
||||
credentials: 'include',
|
||||
signal: controller.signal,
|
||||
});
|
||||
const data = await response.json();
|
||||
setProductResults(Array.isArray(data) ? data : []);
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') return;
|
||||
console.error('Error searching products:', error);
|
||||
} finally {
|
||||
if (!controller.signal.aborted) setSearching(false);
|
||||
}
|
||||
}, 500);
|
||||
|
||||
return () => {
|
||||
clearTimeout(timeoutId);
|
||||
controller.abort();
|
||||
};
|
||||
}, [productSearch]);
|
||||
|
||||
const fetchPharmacies = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/pharmacies', {
|
||||
credentials: 'include',
|
||||
});
|
||||
const data = await response.json();
|
||||
setPharmacies(data);
|
||||
} catch (error) {
|
||||
console.error('Error fetching pharmacies:', error);
|
||||
}
|
||||
};
|
||||
|
||||
const fetchPharmacyProducts = async (pharmacyId) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await fetch(`/api/admin/pharmacies/${pharmacyId}/products`, {
|
||||
credentials: 'include',
|
||||
});
|
||||
const data = await response.json();
|
||||
setPharmacyProducts(data);
|
||||
} catch (error) {
|
||||
console.error('Error fetching pharmacy products:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!selectedProduct) {
|
||||
alert('Por favor, selecciona un producto primero');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Build identifier: source:id (e.g., openfoodfacts:9421025231209)
|
||||
const identifier = selectedProduct._id
|
||||
? `${selectedProduct.source || 'openfoodfacts'}:${selectedProduct._id}`
|
||||
: `${selectedProduct.source || 'openfoodfacts'}:${selectedProduct.id}`;
|
||||
|
||||
const payload = {
|
||||
pharmacy_id: parseInt(formData.pharmacy_id),
|
||||
product_source: selectedProduct.source || 'openfoodfacts',
|
||||
product_off_id: selectedProduct._id || selectedProduct.id,
|
||||
product_name: selectedProduct.product_name || selectedProduct.name,
|
||||
price: formData.price ? parseFloat(formData.price) : null,
|
||||
stock: formData.stock ? parseInt(formData.stock) : 0
|
||||
};
|
||||
|
||||
const response = await fetch('/api/admin/pharmacy-products', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Error al vincular producto a farmacia');
|
||||
|
||||
resetForm();
|
||||
if (selectedPharmacy) {
|
||||
fetchPharmacyProducts(selectedPharmacy.id);
|
||||
}
|
||||
alert('¡Producto vinculado a la farmacia correctamente!');
|
||||
} catch (error) {
|
||||
console.error('Error linking product:', error);
|
||||
alert('Error al vincular producto a farmacia');
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdate = async (id, price, stock) => {
|
||||
try {
|
||||
const response = await fetch(`/api/admin/pharmacy-products/${id}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ price, stock })
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Error al actualizar');
|
||||
|
||||
fetchPharmacyProducts(selectedPharmacy.id);
|
||||
alert('¡Actualizado correctamente!');
|
||||
} catch (error) {
|
||||
console.error('Error updating:', error);
|
||||
alert('Error al actualizar');
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (id) => {
|
||||
if (!confirm('¿Eliminar este producto de la farmacia?')) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/admin/pharmacy-products/${id}`, {
|
||||
method: 'DELETE',
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('Error al eliminar');
|
||||
|
||||
fetchPharmacyProducts(selectedPharmacy.id);
|
||||
alert('¡Producto eliminado de la farmacia!');
|
||||
} catch (error) {
|
||||
console.error('Error deleting:', error);
|
||||
alert('Error al eliminar producto');
|
||||
}
|
||||
};
|
||||
|
||||
const resetForm = () => {
|
||||
setFormData({
|
||||
pharmacy_id: selectedPharmacy ? selectedPharmacy.id.toString() : '',
|
||||
price: '',
|
||||
stock: ''
|
||||
});
|
||||
setSelectedProduct(null);
|
||||
setProductSearch('');
|
||||
setProductResults([]);
|
||||
};
|
||||
|
||||
const selectProduct = (product) => {
|
||||
setSelectedProduct(product);
|
||||
setProductSearch(product.product_name || product.name);
|
||||
setProductResults([]);
|
||||
};
|
||||
|
||||
const pickPharmacy = (pharmacy) => {
|
||||
setSelectedPharmacy(pharmacy);
|
||||
setFormData(prev => ({ ...prev, pharmacy_id: pharmacy.id.toString() }));
|
||||
setPharmacyQuery(`${pharmacy.name} — ${pharmacy.address}`);
|
||||
setPharmacyDropdownOpen(false);
|
||||
};
|
||||
|
||||
const clearPharmacy = () => {
|
||||
setSelectedPharmacy(null);
|
||||
setFormData(prev => ({ ...prev, pharmacy_id: '' }));
|
||||
setPharmacyQuery('');
|
||||
setPharmacyDropdownOpen(true);
|
||||
setTimeout(() => pharmacyInputRef.current?.focus(), 0);
|
||||
};
|
||||
|
||||
const getSourceBadge = (source) => {
|
||||
if (source === 'cima') {
|
||||
return <span className="source-badge source-badge--cima">CIMA</span>;
|
||||
}
|
||||
return <span className="source-badge source-badge--off">OFF</span>;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="admin-section">
|
||||
<h2>Vincular Producto a Farmacia</h2>
|
||||
|
||||
<form className="admin-form" onSubmit={handleSubmit}>
|
||||
<div className="form-group">
|
||||
<label>Farmacia *</label>
|
||||
<input
|
||||
ref={pharmacyInputRef}
|
||||
type="text"
|
||||
value={pharmacyQuery}
|
||||
onChange={(e) => {
|
||||
setPharmacyQuery(e.target.value);
|
||||
if (selectedPharmacy) {
|
||||
setSelectedPharmacy(null);
|
||||
setFormData(prev => ({ ...prev, pharmacy_id: '' }));
|
||||
}
|
||||
setPharmacyDropdownOpen(true);
|
||||
}}
|
||||
onFocus={() => setPharmacyDropdownOpen(true)}
|
||||
onBlur={() => setTimeout(() => setPharmacyDropdownOpen(false), 150)}
|
||||
placeholder={pharmacies.length ? `Buscar entre ${pharmacies.length} farmacias por nombre o dirección…` : 'Cargando farmacias…'}
|
||||
autoComplete="off"
|
||||
required={!selectedPharmacy}
|
||||
/>
|
||||
{!selectedPharmacy && pharmacyDropdownOpen && (
|
||||
<div className="medicine-search-results">
|
||||
{filteredPharmacies.length === 0 ? (
|
||||
<div className="search-result-item search-result-item--empty">
|
||||
<span>No hay farmacias que coincidan con "{pharmacyQuery}"</span>
|
||||
</div>
|
||||
) : (
|
||||
filteredPharmacies.map((pharmacy) => (
|
||||
<div
|
||||
key={pharmacy.id}
|
||||
className="search-result-item"
|
||||
onMouseDown={(e) => { e.preventDefault(); pickPharmacy(pharmacy); }}
|
||||
>
|
||||
<strong>{pharmacy.name}</strong>
|
||||
<span>{pharmacy.address}</span>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{selectedPharmacy && (
|
||||
<div className="selected-medicine-info">
|
||||
<p>✅ Selected: <strong>{selectedPharmacy.name}</strong></p>
|
||||
<p className="medicine-details">{selectedPharmacy.address}</p>
|
||||
<button type="button" className="btn-small" onClick={clearPharmacy}>
|
||||
Cambiar farmacia
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Buscar Producto (Open Food Facts) *</label>
|
||||
<input
|
||||
type="text"
|
||||
value={productSearch}
|
||||
onChange={(e) => {
|
||||
setProductSearch(e.target.value);
|
||||
setSelectedProduct(null);
|
||||
}}
|
||||
placeholder="Escribe para buscar productos..."
|
||||
required
|
||||
/>
|
||||
{searching && <p className="loading-text">Buscando...</p>}
|
||||
|
||||
{productResults.length > 0 && !selectedProduct && (
|
||||
<div className="medicine-search-results">
|
||||
{productResults.slice(0, 10).map((product) => (
|
||||
<div
|
||||
key={product._id || product.id}
|
||||
className="search-result-item"
|
||||
onClick={() => selectProduct(product)}
|
||||
>
|
||||
<strong>{product.product_name || product.name}</strong>
|
||||
{product.brands && <span> - {product.brands}</span>}
|
||||
{product.quantity && <span> ({product.quantity})</span>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{selectedProduct && (
|
||||
<div className="selected-medicine-info">
|
||||
<p>✅ Selected: <strong>{selectedProduct.product_name || selectedProduct.name}</strong></p>
|
||||
<p className="medicine-details">
|
||||
{selectedProduct.brands && `Marca: ${selectedProduct.brands} • `}
|
||||
{selectedProduct.quantity && `Cantidad: ${selectedProduct.quantity} • `}
|
||||
{getSourceBadge(selectedProduct.source || 'openfoodfacts')}
|
||||
{' '}
|
||||
{selectedProduct._id || selectedProduct.id}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
className="btn-small"
|
||||
onClick={() => {
|
||||
setSelectedProduct(null);
|
||||
setProductSearch('');
|
||||
}}
|
||||
>
|
||||
Cambiar producto
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="form-row">
|
||||
<div className="form-group">
|
||||
<label>Precio (€)</label>
|
||||
<input
|
||||
type="number"
|
||||
step="0.01"
|
||||
value={formData.price}
|
||||
onChange={(e) => setFormData({ ...formData, price: e.target.value })}
|
||||
placeholder="e.g., 3.50"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>Stock</label>
|
||||
<input
|
||||
type="number"
|
||||
value={formData.stock}
|
||||
onChange={(e) => setFormData({ ...formData, stock: e.target.value })}
|
||||
placeholder="e.g., 100"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="form-actions">
|
||||
<button type="submit" className="btn-primary">
|
||||
Vincular Producto
|
||||
</button>
|
||||
<button type="button" className="btn-secondary" onClick={resetForm}>
|
||||
Reiniciar
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{selectedPharmacy && (
|
||||
<div className="pharmacy-medicines-section">
|
||||
<h3>Productos en {selectedPharmacy.name}</h3>
|
||||
{loading ? (
|
||||
<div className="loading">Cargando...</div>
|
||||
) : pharmacyProducts.length === 0 ? (
|
||||
<p className="empty-state">Aún no hay productos vinculados a esta farmacia.</p>
|
||||
) : (
|
||||
<div className="admin-list">
|
||||
{pharmacyProducts.map((pp) => (
|
||||
<div key={pp.id} className="admin-item">
|
||||
<div className="item-content">
|
||||
<h4>
|
||||
{pp.product_name}
|
||||
{getSourceBadge(pp.product_source)}
|
||||
</h4>
|
||||
<p>
|
||||
<strong>Precio:</strong> {pp.price ? `€${parseFloat(pp.price).toFixed(2)}` : 'No definido'} •
|
||||
<strong> Stock:</strong> {pp.stock || 0}
|
||||
</p>
|
||||
</div>
|
||||
<div className="item-actions">
|
||||
<button
|
||||
className="btn-edit"
|
||||
onClick={() => {
|
||||
const newPrice = prompt('Introduce nuevo precio:', pp.price || '');
|
||||
const newStock = prompt('Introduce nuevo stock:', pp.stock || '0');
|
||||
if (newPrice !== null && newStock !== null) {
|
||||
handleUpdate(pp.id, newPrice ? parseFloat(newPrice) : null, parseInt(newStock) || 0);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Actualizar
|
||||
</button>
|
||||
<button className="btn-delete" onClick={() => handleDelete(pp.id)}>
|
||||
Eliminar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default PharmacyProductLink;
|
||||
@@ -5,6 +5,7 @@ import LoginForm from '../components/admin/LoginForm';
|
||||
import PharmacyManagement from '../components/admin/PharmacyManagement';
|
||||
import MedicineManagement from '../components/admin/MedicineManagement';
|
||||
import PharmacyMedicineLink from '../components/admin/PharmacyMedicineLink';
|
||||
import PharmacyProductLink from '../components/admin/PharmacyProductLink';
|
||||
|
||||
function AdminView() {
|
||||
const [authenticated, setAuthenticated] = useState(false);
|
||||
@@ -115,12 +116,19 @@ function AdminView() {
|
||||
>
|
||||
🔗 Vincular Medicamento a Farmacia
|
||||
</button>
|
||||
<button
|
||||
className={`admin-tab ${activeTab === 'link-product' ? 'active' : ''}`}
|
||||
onClick={() => setActiveTab('link-product')}
|
||||
>
|
||||
🍎 Vincular Producto a Farmacia
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="admin-content">
|
||||
{activeTab === 'pharmacies' && <PharmacyManagement />}
|
||||
{activeTab === 'medicines' && <MedicineManagement />}
|
||||
{activeTab === 'link' && <PharmacyMedicineLink />}
|
||||
{activeTab === 'link-product' && <PharmacyProductLink />}
|
||||
</div>
|
||||
</main>
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
.product-view {
|
||||
width: 100%;
|
||||
max-width: 48rem;
|
||||
margin: 0 auto;
|
||||
padding: 1rem var(--margin-main) 2rem;
|
||||
animation: fadeInUp 0.3s ease-out;
|
||||
}
|
||||
|
||||
.back-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.5rem 0;
|
||||
margin-bottom: 1rem;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--primary, #2563eb);
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.back-btn:hover {
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.product-loading,
|
||||
.product-error {
|
||||
text-align: center;
|
||||
padding: 3rem 1rem;
|
||||
color: var(--on-surface-variant, #6b7280);
|
||||
font-size: 1rem;
|
||||
}
|
||||
|
||||
.product-header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.product-image {
|
||||
width: 120px;
|
||||
height: 120px;
|
||||
object-fit: contain;
|
||||
border-radius: var(--radius-md, 0.75rem);
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.source-badge {
|
||||
display: inline-block;
|
||||
padding: 0.25rem 0.75rem;
|
||||
border-radius: 9999px;
|
||||
color: white;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.product-name {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 700;
|
||||
color: var(--on-surface);
|
||||
text-align: center;
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.product-brand {
|
||||
font-size: 1rem;
|
||||
color: var(--on-surface-variant, #6b7280);
|
||||
text-align: center;
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
|
||||
.product-details {
|
||||
background: var(--surface-container-lowest, #f9fafb);
|
||||
border-radius: var(--radius-md, 0.75rem);
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.detail-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
padding: 0.75rem 0;
|
||||
border-bottom: 1px solid var(--outline-variant, #e5e7eb);
|
||||
}
|
||||
|
||||
.detail-row:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.detail-label {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
color: var(--on-surface-variant, #9ca3af);
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.detail-value {
|
||||
font-size: 0.9375rem;
|
||||
color: var(--on-surface);
|
||||
}
|
||||
|
||||
.product-pharmacies {
|
||||
margin-top: 2rem;
|
||||
}
|
||||
|
||||
.pharmacies-loading {
|
||||
text-align: center;
|
||||
padding: 2rem 1rem;
|
||||
color: var(--on-surface-variant, #6b7280);
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.pharmacies-title {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: var(--on-surface);
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
|
||||
.pharmacies-grid {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.product-pharmacy-card {
|
||||
background: var(--surface-container-lowest, #f9fafb);
|
||||
border-radius: var(--radius-md, 0.75rem);
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.product-pharmacy-name {
|
||||
font-size: 0.9375rem;
|
||||
font-weight: 600;
|
||||
color: var(--on-surface);
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.product-pharmacy-address {
|
||||
font-size: 0.8125rem;
|
||||
color: var(--on-surface-variant, #6b7280);
|
||||
margin-bottom: 0.25rem;
|
||||
}
|
||||
|
||||
.product-pharmacy-phone {
|
||||
font-size: 0.8125rem;
|
||||
color: var(--on-surface-variant, #6b7280);
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.product-pharmacy-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.product-pharmacy-price {
|
||||
font-size: 0.9375rem;
|
||||
font-weight: 600;
|
||||
color: var(--primary, #2563eb);
|
||||
}
|
||||
|
||||
.product-pharmacy-stock {
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
padding: 0.15rem 0.5rem;
|
||||
border-radius: 9999px;
|
||||
}
|
||||
|
||||
.product-pharmacy-stock.in-stock {
|
||||
background: #dcfce7;
|
||||
color: #166534;
|
||||
}
|
||||
|
||||
.product-pharmacy-stock.low-stock {
|
||||
background: #fef9c3;
|
||||
color: #854d0e;
|
||||
}
|
||||
|
||||
.product-pharmacy-stock.out-of-stock {
|
||||
background: #fee2e2;
|
||||
color: #991b1b;
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import './ProductView.css';
|
||||
|
||||
export default function ProductView({ source, id, onBack }) {
|
||||
const [product, setProduct] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
const [pharmacies, setPharmacies] = useState([]);
|
||||
const [loadingPharmacies, setLoadingPharmacies] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadProduct();
|
||||
}, [source, id]);
|
||||
|
||||
async function loadProduct() {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setPharmacies([]);
|
||||
try {
|
||||
const response = await fetch(`/api/products/${source}/${id}`);
|
||||
if (!response.ok) {
|
||||
throw new Error('Producto no encontrado');
|
||||
}
|
||||
const data = await response.json();
|
||||
setProduct(data);
|
||||
loadPharmacies(source, data.id);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPharmacies(productSource, productId) {
|
||||
setLoadingPharmacies(true);
|
||||
try {
|
||||
const response = await fetch(`/api/products/${productSource}/${productId}/pharmacies`);
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setPharmacies(data);
|
||||
}
|
||||
} catch {
|
||||
// Pharmacies are optional — don't block on failure
|
||||
} finally {
|
||||
setLoadingPharmacies(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="product-view">
|
||||
<div className="product-loading">Cargando...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="product-view">
|
||||
<button className="back-btn" onClick={onBack}>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M19 12H5M12 19l-7-7 7-7" />
|
||||
</svg>
|
||||
Volver
|
||||
</button>
|
||||
<div className="product-error">{error}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!product) return null;
|
||||
|
||||
const isCima = product.source === 'cima';
|
||||
const sourceColor = isCima ? '#2563eb' : '#16a34a';
|
||||
const sourceLabel = isCima ? 'CIMA' : 'Open Food Facts';
|
||||
|
||||
return (
|
||||
<div className="product-view">
|
||||
<button className="back-btn" onClick={onBack}>
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="M19 12H5M12 19l-7-7 7-7" />
|
||||
</svg>
|
||||
Volver
|
||||
</button>
|
||||
|
||||
<div className="product-header">
|
||||
{product.image_url && (
|
||||
<img src={product.image_url} alt={product.name} className="product-image" />
|
||||
)}
|
||||
<span className="source-badge" style={{ backgroundColor: sourceColor }}>
|
||||
{sourceLabel}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<h1 className="product-name">{product.name}</h1>
|
||||
<p className="product-brand">{product.brand}</p>
|
||||
|
||||
<div className="product-details">
|
||||
{isCima ? (
|
||||
<>
|
||||
{product.active_ingredient && (
|
||||
<DetailRow label="Principio activo" value={product.active_ingredient} />
|
||||
)}
|
||||
{product.dosage && (
|
||||
<DetailRow label="Dosis" value={product.dosage} />
|
||||
)}
|
||||
{product.form && (
|
||||
<DetailRow label="Forma farmacéutica" value={product.form} />
|
||||
)}
|
||||
{product.prescription && (
|
||||
<DetailRow label="Prescripción" value={product.prescription} />
|
||||
)}
|
||||
{product.commercialized !== undefined && (
|
||||
<DetailRow label="Comercializado" value={product.commercialized ? 'Sí' : 'No'} />
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
{product.nutriscore && product.nutriscore !== 'not-applicable' && product.nutriscore !== 'unknown' && (
|
||||
<DetailRow label="Nutri-Score" value={product.nutriscore.toUpperCase()} />
|
||||
)}
|
||||
{product.nova_group && (
|
||||
<DetailRow label="NOVA" value={`Grupo ${product.nova_group}`} />
|
||||
)}
|
||||
{product.eco_score && product.eco_score !== 'unknown' && (
|
||||
<DetailRow label="Eco-Score" value={product.eco_score.toUpperCase()} />
|
||||
)}
|
||||
{product.ingredients && (
|
||||
<DetailRow label="Ingredientes" value={product.ingredients} />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="product-pharmacies">
|
||||
{loadingPharmacies ? (
|
||||
<div className="pharmacies-loading">Cargando farmacias...</div>
|
||||
) : pharmacies.length > 0 ? (
|
||||
<>
|
||||
<h3 className="pharmacies-title">
|
||||
Disponible en {pharmacies.length} {pharmacies.length === 1 ? 'farmacia' : 'farmacias'}
|
||||
</h3>
|
||||
<div className="pharmacies-grid">
|
||||
{pharmacies.map((pharmacy) => (
|
||||
<div key={pharmacy.id} className="product-pharmacy-card">
|
||||
<h4 className="product-pharmacy-name">{pharmacy.name}</h4>
|
||||
<p className="product-pharmacy-address">{pharmacy.address}</p>
|
||||
{pharmacy.phone && (
|
||||
<p className="product-pharmacy-phone">{pharmacy.phone}</p>
|
||||
)}
|
||||
<div className="product-pharmacy-status">
|
||||
{pharmacy.price && (
|
||||
<span className="product-pharmacy-price">
|
||||
{parseFloat(pharmacy.price).toFixed(2)} €
|
||||
</span>
|
||||
)}
|
||||
{pharmacy.stock !== undefined && (
|
||||
<span className={`product-pharmacy-stock ${pharmacy.stock > 20 ? 'in-stock' : pharmacy.stock > 0 ? 'low-stock' : 'out-of-stock'}`}>
|
||||
{pharmacy.stock > 20 ? 'En Stock' : pharmacy.stock > 0 ? `Stock Bajo (${pharmacy.stock})` : 'Sin Stock'}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DetailRow({ label, value }) {
|
||||
return (
|
||||
<div className="detail-row">
|
||||
<span className="detail-label">{label}</span>
|
||||
<span className="detail-value">{value}</span>
|
||||
</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,12 +57,20 @@
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
[data-theme="dark"] .suggestion-btn:hover {
|
||||
background: #07243d;
|
||||
}
|
||||
|
||||
.suggestion-btn--neutral-1 {
|
||||
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: var(--suggestion-2);
|
||||
color: var(--suggestion-text);
|
||||
@@ -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;
|
||||
}
|
||||
@@ -340,3 +356,44 @@
|
||||
color: var(--primary);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
/* Filter tabs */
|
||||
.filter-tabs {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 1rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.filter-tab {
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 9999px;
|
||||
border: none;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
background: var(--surface-container-lowest, #f3f4f6);
|
||||
color: var(--on-surface-variant, #6b7280);
|
||||
transition: all 0.15s;
|
||||
}
|
||||
|
||||
.filter-tab:hover {
|
||||
background: var(--surface-container-low, #e5e7eb);
|
||||
}
|
||||
|
||||
.filter-tab--active {
|
||||
background: var(--primary, #2563eb);
|
||||
color: white;
|
||||
}
|
||||
|
||||
/* Products section */
|
||||
.products-section {
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.section-subtitle {
|
||||
font-size: 1.125rem;
|
||||
font-weight: 600;
|
||||
color: var(--on-surface);
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { useState, useEffect, useMemo, useCallback } from 'react';
|
||||
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 { haversineKm, getUserPosition, hasCachedPosition } from '../utils/geo';
|
||||
@@ -13,9 +14,11 @@ const suggestions = [
|
||||
{ name: 'Omeprazol', icon: 'emergency_home', color: 'neutral-4' },
|
||||
];
|
||||
|
||||
function SearchView({ currentUser, onLoginRequest, initialQuery = '' }) {
|
||||
function SearchView({ currentUser, onLoginRequest, initialQuery = '', onNavigateToProduct }) {
|
||||
const [searchQuery, setSearchQuery] = useState(initialQuery);
|
||||
const [medicines, setMedicines] = useState([]);
|
||||
const [products, setProducts] = useState([]);
|
||||
const [searchMode, setSearchMode] = useState('all');
|
||||
const [selectedMedicine, setSelectedMedicine] = useState(null);
|
||||
const [pharmacies, setPharmacies] = useState([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -73,25 +76,43 @@ function SearchView({ currentUser, onLoginRequest, initialQuery = '' }) {
|
||||
}, [currentUser]);
|
||||
|
||||
useEffect(() => {
|
||||
const searchMedicines = async () => {
|
||||
const searchAll = async () => {
|
||||
if (searchQuery.trim().length < 2) {
|
||||
setMedicines([]);
|
||||
setProducts([]);
|
||||
setSelectedMedicine(null);
|
||||
setPharmacies([]);
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
const query = searchQuery.trim();
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/medicines/search?q=${encodeURIComponent(searchQuery)}`);
|
||||
const data = await response.json();
|
||||
setMedicines(data);
|
||||
// Run both searches in parallel for speed
|
||||
const [medicinesRes, productsRes] = await Promise.allSettled([
|
||||
fetch(`/api/medicines/search?q=${encodeURIComponent(query)}`),
|
||||
fetch(`/api/products/search?q=${encodeURIComponent(query)}`),
|
||||
]);
|
||||
|
||||
// Only update if this search is still the current one
|
||||
if (query !== searchQuery.trim()) return;
|
||||
|
||||
if (medicinesRes.status === 'fulfilled' && medicinesRes.value.ok) {
|
||||
const medicinesData = await medicinesRes.value.json();
|
||||
setMedicines(medicinesData);
|
||||
}
|
||||
|
||||
if (productsRes.status === 'fulfilled' && productsRes.value.ok) {
|
||||
const productsData = await productsRes.value.json();
|
||||
setProducts(productsData.results || []);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error searching medicines:', error);
|
||||
console.error('Search error:', error);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
const timeoutId = setTimeout(searchMedicines, 300);
|
||||
const timeoutId = setTimeout(searchAll, 300);
|
||||
return () => clearTimeout(timeoutId);
|
||||
}, [searchQuery]);
|
||||
|
||||
@@ -276,6 +297,29 @@ function SearchView({ currentUser, onLoginRequest, initialQuery = '' }) {
|
||||
)}
|
||||
|
||||
{searchQuery && !selectedMedicine && (
|
||||
<>
|
||||
<div className="filter-tabs">
|
||||
<button
|
||||
className={`filter-tab ${searchMode === 'all' ? 'filter-tab--active' : ''}`}
|
||||
onClick={() => setSearchMode('all')}
|
||||
>
|
||||
Todos ({medicines.length + products.length})
|
||||
</button>
|
||||
<button
|
||||
className={`filter-tab ${searchMode === 'medicines' ? 'filter-tab--active' : ''}`}
|
||||
onClick={() => setSearchMode('medicines')}
|
||||
>
|
||||
Medicamentos ({medicines.length})
|
||||
</button>
|
||||
<button
|
||||
className={`filter-tab ${searchMode === 'products' ? 'filter-tab--active' : ''}`}
|
||||
onClick={() => setSearchMode('products')}
|
||||
>
|
||||
Parafarmacia ({products.length})
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{(searchMode === 'all' || searchMode === 'medicines') && (
|
||||
<MedicineResults
|
||||
medicines={medicines}
|
||||
onSelect={(m) => {
|
||||
@@ -288,6 +332,24 @@ function SearchView({ currentUser, onLoginRequest, initialQuery = '' }) {
|
||||
/>
|
||||
)}
|
||||
|
||||
{(searchMode === 'all' || searchMode === 'products') && products.length > 0 && (
|
||||
<div className="products-section">
|
||||
<h3 className="section-subtitle">Parafarmacia y Bebé</h3>
|
||||
<ProductResults
|
||||
products={products}
|
||||
onSelect={(p) => {
|
||||
if (onNavigateToProduct) {
|
||||
onNavigateToProduct(p.source, p.id);
|
||||
} else {
|
||||
window.location.href = `/product/${p.source}/${p.id}`;
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{selectedMedicine && (
|
||||
<div className="selected-medicine-section">
|
||||
<div className="medicine-info">
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,226 @@
|
||||
# Parafarmacia + Productos de Bebé — Design Spec
|
||||
|
||||
**Date:** 2026-07-13
|
||||
**Status:** Approved
|
||||
**Author:** MiMoCode
|
||||
|
||||
## Problem
|
||||
|
||||
FarmaFinder currently only searches medications via the CIMA API. Users need to find parapharmacy products (OTC medications, vitamins, topical treatments) and baby products (formula milk, baby food, cereals) — categories that pharmacies sell but CIMA doesn't cover comprehensively.
|
||||
|
||||
## Goal
|
||||
|
||||
Extend FarmaFinder's search to include:
|
||||
1. **OTC medications** from CIMA (filtered by `cpresc = "Sin Receta"`)
|
||||
2. **Baby products** (formula milk, baby food, cereals) from Open Food Facts API
|
||||
|
||||
Results should appear in a unified search alongside existing prescription medication results.
|
||||
|
||||
## Data Sources
|
||||
|
||||
### CIMA API (existing, extended)
|
||||
|
||||
- **Base URL:** `https://cima.aemps.es/cima/rest`
|
||||
- **No authentication required**
|
||||
- **New filter:** `cpresc=Sin+Receta` to get only OTC products
|
||||
- **Endpoints used:**
|
||||
- `GET /medicamentos?nombre={query}&cpresc=Sin+Receta` — search OTC products
|
||||
- `GET /medicamento/{nregistro}` — get OTC product details
|
||||
- **Rate limits:** None documented; existing 5s timeout per request
|
||||
- **Data fields:** nregistro, nombre, labtitular, cpresc, formaFarmaceutica, vtm, dosis, fotos, docs
|
||||
|
||||
### Open Food Facts API (new)
|
||||
|
||||
- **Base URL:** `https://world.openfoodfacts.org/api/v2`
|
||||
- **No authentication required**
|
||||
- **Endpoints used:**
|
||||
- `GET /search?categories_tags=baby-food&search_terms={query}&json=true` — search baby products
|
||||
- `GET /product/{barcode}.json` — get product details
|
||||
- **Rate limits:** Be polite (< 10 req/s)
|
||||
- **Data fields:** product_name, brands, image_url, nutriscore, ingredients_text, categories_tags
|
||||
- **Product categories to search:**
|
||||
- `baby-foods` — general baby food
|
||||
- `baby-milks` — formula milk
|
||||
- `cereals-for-babies` — baby cereals
|
||||
- `snacks-and-desserts-for-babies` — baby snacks
|
||||
|
||||
## Architecture
|
||||
|
||||
### Data Flow
|
||||
|
||||
```
|
||||
User searches "leche"
|
||||
→ Frontend: GET /api/products/search?q=leche
|
||||
→ Backend orchestrator:
|
||||
1. cimaService.searchOTC('leche') — CIMA OTC search
|
||||
2. offService.searchBaby('leche') — Open Food Facts search
|
||||
3. Merge results with source tag
|
||||
4. Cache in Redis (1h TTL)
|
||||
→ Return unified result list
|
||||
```
|
||||
|
||||
### Unified Product Model
|
||||
|
||||
```typescript
|
||||
interface Product {
|
||||
id: string; // nregistro (CIMA) or _id (OFF)
|
||||
source: 'cima' | 'openfoodfacts';
|
||||
name: string;
|
||||
brand: string; // labtitular (CIMA) or brands (OFF)
|
||||
category: 'otc' | 'baby_food' | 'baby_milk' | 'baby_cereal';
|
||||
image_url: string | null; // fotos[0].url (CIMA) or image_url (OFF)
|
||||
|
||||
// CIMA-specific fields
|
||||
active_ingredient?: string; // vtm.nombre
|
||||
dosage?: string; // dosis
|
||||
form?: string; // formaFarmaceutica.nombre
|
||||
prescription?: string; // cpresc
|
||||
commercialized?: boolean; // comerc
|
||||
photos?: string[];
|
||||
docs?: { tipo: number; url: string }[];
|
||||
|
||||
// OFF-specific fields
|
||||
nutriscore?: string; // nutriscore_grade
|
||||
ingredients?: string; // ingredients_text
|
||||
nova_group?: number; // nova_group
|
||||
eco_score?: string; // ecoscore_grade
|
||||
}
|
||||
```
|
||||
|
||||
## Backend Changes
|
||||
|
||||
### 1. New file: `apps/backend/off-service.js`
|
||||
|
||||
Open Food Facts API client:
|
||||
|
||||
```javascript
|
||||
const OFF_API_BASE = 'https://world.openfoodfacts.org/api/v2';
|
||||
|
||||
async function searchBabyProducts(query) {
|
||||
// Search in baby-food categories
|
||||
const url = `${OFF_API_BASE}/search?categories_tags=baby-food&search_terms=${encodeURIComponent(query)}&json=true&fields=product_name,brands,image_url,nutriscore_grade,ingredients_text,nova_group,ecoscore_grade,categories_tags&page_size=20`;
|
||||
// Cache key: off:baby:{query}, TTL: 1 hour
|
||||
// Transform to unified Product model
|
||||
}
|
||||
|
||||
async function getBabyProductDetails(barcode) {
|
||||
const url = `${OFF_API_BASE}/product/${barcode}.json`;
|
||||
// Cache key: off:product:{barcode}, TTL: 24 hours
|
||||
// Transform to unified Product model
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Modify: `apps/backend/cima-service.js`
|
||||
|
||||
Add OTC-specific search function:
|
||||
|
||||
```javascript
|
||||
async function searchOTC(query) {
|
||||
// Same as searchMedicines but adds cpresc=Sin+Receta filter
|
||||
// Cache key: cima:otc:{query}, TTL: 1 hour
|
||||
// Transform to unified Product model (add source: 'cima', category: 'otc')
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Modify: `apps/backend/server.js`
|
||||
|
||||
New unified search route:
|
||||
|
||||
```javascript
|
||||
app.get('/api/products/search', async (req, res) => {
|
||||
const { q } = req.query;
|
||||
// Launch parallel searches:
|
||||
const [cimaResults, offResults] = await Promise.allSettled([
|
||||
searchOTC(q),
|
||||
searchBabyProducts(q)
|
||||
]);
|
||||
// Merge, deduplicate, sort by relevance
|
||||
// Return unified results
|
||||
});
|
||||
|
||||
app.get('/api/products/:source/:id', async (req, res) => {
|
||||
const { source, id } = req.params;
|
||||
if (source === 'cima') return getMedicineDetails(id);
|
||||
if (source === 'openfoodfacts') return getBabyProductDetails(id);
|
||||
});
|
||||
```
|
||||
|
||||
### 4. Redis Cache Strategy
|
||||
|
||||
| Key Pattern | TTL | Source |
|
||||
|-------------|-----|--------|
|
||||
| `products:search:{query}` | 1 hour | Merged results |
|
||||
| `cima:otc:{query}` | 1 hour | CIMA OTC only |
|
||||
| `off:baby:{query}` | 1 hour | OFF baby only |
|
||||
| `off:product:{barcode}` | 24 hours | OFF product detail |
|
||||
|
||||
## Frontend Changes
|
||||
|
||||
### 1. New component: `ProductResults.jsx`
|
||||
|
||||
Displays unified search results with:
|
||||
- Product card with image, name, brand
|
||||
- Source badge: "CIMA" or "Open Food Facts"
|
||||
- Category badge: "OTC", "Baby Food", "Formula"
|
||||
- Click navigates to `/product/{source}/{id}`
|
||||
|
||||
### 2. Modify: `PublicView.jsx`
|
||||
|
||||
- Update search to call `/api/products/search?q=`
|
||||
- Show unified results alongside existing medicine results
|
||||
- Add category filter tabs: "All" | "Medications" | "OTC" | "Baby"
|
||||
|
||||
### 3. Modify: `MedicineResults.jsx`
|
||||
|
||||
- Accept mixed product types
|
||||
- Conditionally render fields based on `source`
|
||||
- Show CIMA-specific fields (active ingredient, dosage) for CIMA products
|
||||
- Show OFF-specific fields (nutriscore, ingredients) for OFF products
|
||||
|
||||
### 4. New route: `/product/:source/:id`
|
||||
|
||||
- Detail page for any product type
|
||||
- CIMA products: show full medication info + pharmacies
|
||||
- OFF products: show nutritional info + "Available at pharmacies" section
|
||||
|
||||
## Mobile Changes
|
||||
|
||||
### 1. `apps/frontend-mobile/services/products.ts`
|
||||
|
||||
```typescript
|
||||
export async function searchProducts(query: string): Promise<Product[]> {
|
||||
const { data } = await api.get('/products/search', { params: { q: query } });
|
||||
return data.results;
|
||||
}
|
||||
```
|
||||
|
||||
### 2. `apps/frontend-mobile/app/(tabs)/search.tsx`
|
||||
|
||||
- Add product search alongside medicine search
|
||||
- Display unified results with source/category badges
|
||||
|
||||
### 3. `apps/frontend-mobile/app/product/[source]/[id].tsx`
|
||||
|
||||
- New detail screen for non-medication products
|
||||
- Adapt layout based on product source
|
||||
|
||||
## Error Handling
|
||||
|
||||
- CIMA API down: return OFF results only (graceful degradation)
|
||||
- OFF API down: return CIMA results only
|
||||
- Both down: return cached results if available, else empty
|
||||
- OFF rate limit: implement 100ms delay between requests
|
||||
|
||||
## Testing
|
||||
|
||||
1. **Unit tests:** off-service.js search/transform functions
|
||||
2. **Integration tests:** `/api/products/search` endpoint with mocked APIs
|
||||
3. **Manual test:** Search "leche" and verify both CIMA OTC + OFF baby results appear
|
||||
4. **Edge cases:** Empty results, API timeout, malformed OFF responses
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- Homeopathy (not reliably available in either API)
|
||||
- Commercial parapharmacy APIs (paid, not needed for OTC + baby)
|
||||
- Product price/stock for OFF products (pharmacies don't stock these in the current model)
|
||||
- User reviews/ratings for products
|
||||
@@ -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": {}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user