Merge branch 'main' into feat/observability-metrics-monitoring
Run Tests on Branches / Run Tests (push) Failing after 3h11m0s
Run Tests on Branches / Run Tests (push) Failing after 3h11m0s
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
import { transformOFFProduct, searchBabyProducts, getBabyProductDetails } from '../off-service.js';
|
||||
|
||||
describe('transformOFFProduct', () => {
|
||||
test('transforms a valid OFF product to unified model', () => {
|
||||
const offProduct = {
|
||||
_id: '12345',
|
||||
product_name: 'Baby Rice',
|
||||
brands: 'Nestlé',
|
||||
image_url: 'https://example.com/image.jpg',
|
||||
nutriscore_grade: 'a',
|
||||
ingredients_text: 'Rice, Iron, Vitamins',
|
||||
nova_group: 1,
|
||||
ecoscore_grade: 'b',
|
||||
categories_tags: ['en:baby-foods', 'en:baby-rice'],
|
||||
};
|
||||
|
||||
const result = transformOFFProduct(offProduct);
|
||||
|
||||
expect(result).toEqual({
|
||||
id: '12345',
|
||||
source: 'openfoodfacts',
|
||||
name: 'Baby Rice',
|
||||
brand: 'Nestlé',
|
||||
category: 'baby_food',
|
||||
image_url: 'https://example.com/image.jpg',
|
||||
nutriscore: 'a',
|
||||
ingredients: 'Rice, Iron, Vitamins',
|
||||
nova_group: 1,
|
||||
eco_score: 'b',
|
||||
});
|
||||
});
|
||||
|
||||
test('returns null for null/undefined input', () => {
|
||||
expect(transformOFFProduct(null)).toBeNull();
|
||||
expect(transformOFFProduct(undefined)).toBeNull();
|
||||
});
|
||||
|
||||
test('returns null when missing required fields', () => {
|
||||
expect(transformOFFProduct({ _id: '123' })).toBeNull();
|
||||
expect(transformOFFProduct({ product_name: 'Test' })).toBeNull();
|
||||
});
|
||||
|
||||
test('sets default brand to empty string when missing', () => {
|
||||
const result = transformOFFProduct({
|
||||
_id: '999',
|
||||
product_name: 'Plain Product',
|
||||
});
|
||||
expect(result.brand).toBe('');
|
||||
expect(result.image_url).toBeNull();
|
||||
expect(result.nutriscore).toBeNull();
|
||||
expect(result.ingredients).toBeNull();
|
||||
expect(result.nova_group).toBeNull();
|
||||
expect(result.eco_score).toBeNull();
|
||||
});
|
||||
|
||||
test('detects baby_milk category from tags', () => {
|
||||
const result = transformOFFProduct({
|
||||
_id: '200',
|
||||
product_name: 'Infant Formula',
|
||||
categories_tags: ['en:infant-milk'],
|
||||
});
|
||||
expect(result.category).toBe('baby_milk');
|
||||
});
|
||||
|
||||
test('detects baby_cereal category from tags', () => {
|
||||
const result = transformOFFProduct({
|
||||
_id: '300',
|
||||
product_name: 'Baby Cereal',
|
||||
categories_tags: ['en:baby-cereals'],
|
||||
});
|
||||
expect(result.category).toBe('baby_cereal');
|
||||
});
|
||||
});
|
||||
|
||||
describe('searchBabyProducts', () => {
|
||||
test('returns empty array for short query', async () => {
|
||||
const result = await searchBabyProducts('a');
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
test('returns empty array for null/empty query', async () => {
|
||||
expect(await searchBabyProducts(null)).toEqual([]);
|
||||
expect(await searchBabyProducts('')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getBabyProductDetails', () => {
|
||||
test('returns null for null barcode', async () => {
|
||||
const result = await getBabyProductDetails(null);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,12 @@ import { jest } from '@jest/globals'
|
||||
jest.unstable_mockModule('../cima-service.js', () => ({
|
||||
searchMedicines: jest.fn(async () => []),
|
||||
getMedicineDetails: jest.fn(async () => null),
|
||||
searchOTC: jest.fn(async () => []),
|
||||
}))
|
||||
|
||||
jest.unstable_mockModule('../off-service.js', () => ({
|
||||
searchBabyProducts: jest.fn(async () => []),
|
||||
getBabyProductDetails: jest.fn(async () => null),
|
||||
}))
|
||||
|
||||
jest.unstable_mockModule('../farmacias-webhook-import.js', () => ({
|
||||
|
||||
@@ -252,6 +252,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:*')
|
||||
|
||||
@@ -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
@@ -21,7 +21,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';
|
||||
|
||||
@@ -646,6 +647,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
|
||||
|
||||
Reference in New Issue
Block a user