Compare commits
12 Commits
main
...
4df1594b3b
| Author | SHA1 | Date | |
|---|---|---|---|
| 4df1594b3b | |||
| 981f3bd3db | |||
| 83920ae57c | |||
| 7b1636a96e | |||
| bb2dbbab3a | |||
| d5b23aa94a | |||
| 9e786f2966 | |||
| a709deb893 | |||
| 229e1d8106 | |||
| f2a5dc4ca3 | |||
| d62e5976ce | |||
| d6f4164dae |
@@ -0,0 +1,92 @@
|
||||
import { transformOFFProduct, searchBabyProducts, getBabyProductDetails } from '../off-service.js';
|
||||
|
||||
describe('transformOFFProduct', () => {
|
||||
test('transforms a valid OFF product to unified model', () => {
|
||||
const offProduct = {
|
||||
_id: '12345',
|
||||
product_name: 'Baby Rice',
|
||||
brands: 'Nestlé',
|
||||
image_url: 'https://example.com/image.jpg',
|
||||
nutriscore_grade: 'a',
|
||||
ingredients_text: 'Rice, Iron, Vitamins',
|
||||
nova_group: 1,
|
||||
ecoscore_grade: 'b',
|
||||
categories_tags: ['en:baby-foods', 'en:baby-rice'],
|
||||
};
|
||||
|
||||
const result = transformOFFProduct(offProduct);
|
||||
|
||||
expect(result).toEqual({
|
||||
id: '12345',
|
||||
source: 'openfoodfacts',
|
||||
name: 'Baby Rice',
|
||||
brand: 'Nestlé',
|
||||
category: 'baby_food',
|
||||
image_url: 'https://example.com/image.jpg',
|
||||
nutriscore: 'a',
|
||||
ingredients: 'Rice, Iron, Vitamins',
|
||||
nova_group: 1,
|
||||
eco_score: 'b',
|
||||
});
|
||||
});
|
||||
|
||||
test('returns null for null/undefined input', () => {
|
||||
expect(transformOFFProduct(null)).toBeNull();
|
||||
expect(transformOFFProduct(undefined)).toBeNull();
|
||||
});
|
||||
|
||||
test('returns null when missing required fields', () => {
|
||||
expect(transformOFFProduct({ _id: '123' })).toBeNull();
|
||||
expect(transformOFFProduct({ product_name: 'Test' })).toBeNull();
|
||||
});
|
||||
|
||||
test('sets default brand to empty string when missing', () => {
|
||||
const result = transformOFFProduct({
|
||||
_id: '999',
|
||||
product_name: 'Plain Product',
|
||||
});
|
||||
expect(result.brand).toBe('');
|
||||
expect(result.image_url).toBeNull();
|
||||
expect(result.nutriscore).toBeNull();
|
||||
expect(result.ingredients).toBeNull();
|
||||
expect(result.nova_group).toBeNull();
|
||||
expect(result.eco_score).toBeNull();
|
||||
});
|
||||
|
||||
test('detects baby_milk category from tags', () => {
|
||||
const result = transformOFFProduct({
|
||||
_id: '200',
|
||||
product_name: 'Infant Formula',
|
||||
categories_tags: ['en:infant-milk'],
|
||||
});
|
||||
expect(result.category).toBe('baby_milk');
|
||||
});
|
||||
|
||||
test('detects baby_cereal category from tags', () => {
|
||||
const result = transformOFFProduct({
|
||||
_id: '300',
|
||||
product_name: 'Baby Cereal',
|
||||
categories_tags: ['en:baby-cereals'],
|
||||
});
|
||||
expect(result.category).toBe('baby_cereal');
|
||||
});
|
||||
});
|
||||
|
||||
describe('searchBabyProducts', () => {
|
||||
test('returns empty array for short query', async () => {
|
||||
const result = await searchBabyProducts('a');
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
test('returns empty array for null/empty query', async () => {
|
||||
expect(await searchBabyProducts(null)).toEqual([]);
|
||||
expect(await searchBabyProducts('')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getBabyProductDetails', () => {
|
||||
test('returns null for null barcode', async () => {
|
||||
const result = await getBabyProductDetails(null);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,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,141 @@
|
||||
import axios from 'axios';
|
||||
import redisClient from './redis-client.js';
|
||||
|
||||
const OFF_API_BASE = 'https://world.openfoodfacts.org/api/v2';
|
||||
const CACHE_TTL = 3600;
|
||||
|
||||
export function transformOFFProduct(offProduct) {
|
||||
if (!offProduct || !offProduct._id || !offProduct.product_name) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const categoriesTags = offProduct.categories_tags || [];
|
||||
let category = 'baby_food';
|
||||
for (const tag of categoriesTags) {
|
||||
const lower = tag.toLowerCase();
|
||||
if (lower.includes('baby-milk') || lower.includes('infant-milk')) {
|
||||
category = 'baby_milk';
|
||||
break;
|
||||
}
|
||||
if (lower.includes('baby-cereal') || lower.includes('infant-cereal')) {
|
||||
category = 'baby_cereal';
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: offProduct._id,
|
||||
source: 'openfoodfacts',
|
||||
name: offProduct.product_name,
|
||||
brand: offProduct.brands || '',
|
||||
category,
|
||||
image_url: offProduct.image_url || null,
|
||||
nutriscore: offProduct.nutriscore_grade || null,
|
||||
ingredients: offProduct.ingredients_text || null,
|
||||
nova_group: offProduct.nova_group || null,
|
||||
eco_score: offProduct.ecoscore_grade || null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function searchBabyProducts(query) {
|
||||
if (!query || query.trim().length < 2) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const searchTerm = query.trim().toLowerCase();
|
||||
const cacheKey = `off:baby:${searchTerm}`;
|
||||
|
||||
try {
|
||||
const cachedData = await redisClient.get(cacheKey);
|
||||
if (cachedData) {
|
||||
console.log(`Cache hit for OFF search: ${searchTerm}`);
|
||||
return JSON.parse(cachedData);
|
||||
}
|
||||
|
||||
console.log(`Fetching from OFF API: ${searchTerm}`);
|
||||
const response = await axios.get(`${OFF_API_BASE}/search`, {
|
||||
params: {
|
||||
categories_tags: 'baby-food',
|
||||
search_terms: searchTerm,
|
||||
json: true,
|
||||
fields: 'product_name,brands,image_url,nutriscore_grade,ingredients_text,nova_group,ecoscore_grade,categories_tags',
|
||||
page_size: 20,
|
||||
},
|
||||
timeout: 5000,
|
||||
});
|
||||
|
||||
if (response.data && response.data.products) {
|
||||
const products = response.data.products
|
||||
.map(transformOFFProduct)
|
||||
.filter(Boolean);
|
||||
|
||||
try {
|
||||
await redisClient.setEx(cacheKey, CACHE_TTL, JSON.stringify(products));
|
||||
console.log(`Cached ${products.length} OFF products for: ${searchTerm}`);
|
||||
} catch (cacheErr) {
|
||||
// cache write failed, still return the data
|
||||
}
|
||||
return products;
|
||||
}
|
||||
|
||||
return [];
|
||||
} catch (error) {
|
||||
console.error('Error searching baby products from OFF:', error.message);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function getBabyProductDetails(barcode) {
|
||||
if (!barcode) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const cacheKey = `off:product:${barcode}`;
|
||||
|
||||
try {
|
||||
const cachedData = await redisClient.get(cacheKey);
|
||||
if (cachedData) {
|
||||
console.log(`Cache hit for OFF product: ${barcode}`);
|
||||
return JSON.parse(cachedData);
|
||||
}
|
||||
|
||||
console.log(`Fetching OFF product details: ${barcode}`);
|
||||
const response = await axios.get(`${OFF_API_BASE}/product/${barcode}.json`, {
|
||||
timeout: 5000,
|
||||
});
|
||||
|
||||
if (response.data && response.data.product) {
|
||||
const product = transformOFFProduct(response.data.product);
|
||||
|
||||
if (product) {
|
||||
try {
|
||||
await redisClient.setEx(cacheKey, CACHE_TTL, JSON.stringify(product));
|
||||
console.log(`Cached OFF product: ${barcode}`);
|
||||
} catch (cacheErr) {
|
||||
// cache write failed, still return the data
|
||||
}
|
||||
return product;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error(`Error fetching OFF product ${barcode}:`, error.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export async function clearCache(pattern = 'off:*') {
|
||||
try {
|
||||
const keys = await redisClient.keys(pattern);
|
||||
if (keys.length > 0) {
|
||||
await redisClient.del(keys);
|
||||
console.log(`Cleared ${keys.length} OFF cache entries`);
|
||||
return keys.length;
|
||||
}
|
||||
return 0;
|
||||
} catch (error) {
|
||||
console.error('Error clearing OFF cache:', error);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
+50
-1
@@ -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';
|
||||
|
||||
@@ -598,6 +599,54 @@ app.get('/api/medicines/:medicineId', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// ========== UNIFIED PRODUCT SEARCH ==========
|
||||
|
||||
app.get('/api/products/search', searchLimiter, async (req, res) => {
|
||||
try {
|
||||
const { q } = req.query;
|
||||
if (!q || q.trim().length < 2) {
|
||||
return res.json({ results: [], total: 0 });
|
||||
}
|
||||
const searchTerm = q.trim();
|
||||
const [cimaResults, offResults] = await Promise.allSettled([
|
||||
searchOTC(searchTerm),
|
||||
searchBabyProducts(searchTerm)
|
||||
]);
|
||||
const cimaProducts = cimaResults.status === 'fulfilled' ? cimaResults.value : [];
|
||||
const offProducts = offResults.status === 'fulfilled' ? offResults.value : [];
|
||||
const allProducts = [...cimaProducts, ...offProducts]
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
res.json({
|
||||
results: allProducts,
|
||||
total: allProducts.length,
|
||||
sources: { cima: cimaProducts.length, openfoodfacts: offProducts.length }
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('[Products] Search error:', err);
|
||||
res.status(500).json({ error: 'Error searching products' });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/products/:source/:id', async (req, res) => {
|
||||
try {
|
||||
const { source, id } = req.params;
|
||||
if (source === 'cima') {
|
||||
const product = await getMedicineDetails(id);
|
||||
if (!product) return res.status(404).json({ error: 'Product not found' });
|
||||
return res.json({ ...product, source: 'cima', category: 'otc' });
|
||||
}
|
||||
if (source === 'openfoodfacts') {
|
||||
const product = await getBabyProductDetails(id);
|
||||
if (!product) return res.status(404).json({ error: 'Product not found' });
|
||||
return res.json(product);
|
||||
}
|
||||
res.status(400).json({ error: 'Invalid source' });
|
||||
} catch (err) {
|
||||
console.error('[Products] Detail error:', err);
|
||||
res.status(500).json({ error: 'Error fetching product details' });
|
||||
}
|
||||
});
|
||||
|
||||
// ========== AUTHENTICATION MIDDLEWARE ==========
|
||||
|
||||
// Middleware to check if user is authenticated
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import api from './api';
|
||||
|
||||
export interface Product {
|
||||
id: string;
|
||||
source: 'cima' | 'openfoodfacts';
|
||||
name: string;
|
||||
brand: string;
|
||||
category: string;
|
||||
image_url: string | null;
|
||||
active_ingredient?: string;
|
||||
dosage?: string;
|
||||
form?: string;
|
||||
prescription?: string;
|
||||
commercialized?: boolean;
|
||||
photos?: { tipo: string; url: string }[];
|
||||
docs?: { tipo: number; url: string }[];
|
||||
nutriscore?: string;
|
||||
ingredients?: string;
|
||||
nova_group?: number;
|
||||
eco_score?: string;
|
||||
}
|
||||
|
||||
export interface ProductSearchResponse {
|
||||
results: Product[];
|
||||
total: number;
|
||||
sources: {
|
||||
cima: number;
|
||||
openfoodfacts: number;
|
||||
};
|
||||
}
|
||||
|
||||
export async function searchProducts(query: string): Promise<Product[]> {
|
||||
if (!query || query.trim().length < 2) return [];
|
||||
try {
|
||||
const { data } = await api.get<ProductSearchResponse>('/products/search', {
|
||||
params: { q: query }
|
||||
});
|
||||
return data.results || [];
|
||||
} catch (error) {
|
||||
console.error('[Products] Search error:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function getProduct(source: string, id: string): Promise<Product | null> {
|
||||
try {
|
||||
const { data } = await api.get<Product>(`/products/${source}/${id}`);
|
||||
return data;
|
||||
} catch (error) {
|
||||
console.error('[Products] Detail error:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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;
|
||||
@@ -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">
|
||||
|
||||
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
|
||||
Reference in New Issue
Block a user