Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8bf0b33249 | |||
| f921b15d67 | |||
| 59edc7fbf1 | |||
| 731a6c98ae | |||
| 31c1a14343 | |||
| 25ebb899e9 | |||
| 2e3ce44e7b | |||
| 20debdb023 | |||
| 452a835b64 | |||
| f1b0eab11d | |||
| ee23f61057 | |||
| 26f309acfb |
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,3 +19,10 @@ VAPID_SUBJECT=mailto:admin@example.com
|
||||
# Expo Push Notifications (mobile). Get token from:
|
||||
# https://expo.dev/accounts/[username]/settings/access-tokens
|
||||
EXPO_ACCESS_TOKEN=
|
||||
|
||||
# Open Food Facts
|
||||
# Register at: https://world.openfoodfacts.org/
|
||||
# User-Agent is REQUIRED per OFF docs (format: AppName/Version (ContactEmail))
|
||||
OFF_USER_AGENT=FarmaFinder/1.0 (https://github.com/farmafinder)
|
||||
OFF_USERNAME=
|
||||
OFF_PASSWORD=
|
||||
|
||||
@@ -1,4 +1,19 @@
|
||||
import { transformOFFProduct, searchBabyProducts, getBabyProductDetails } from '../off-service.js';
|
||||
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', () => {
|
||||
@@ -12,9 +27,9 @@ describe('transformOFFProduct', () => {
|
||||
nova_group: 1,
|
||||
ecoscore_grade: 'b',
|
||||
categories_tags: ['en:baby-foods', 'en:baby-rice'],
|
||||
};
|
||||
}
|
||||
|
||||
const result = transformOFFProduct(offProduct);
|
||||
const result = transformOFFProduct(offProduct)
|
||||
|
||||
expect(result).toEqual({
|
||||
id: '12345',
|
||||
@@ -27,66 +42,66 @@ describe('transformOFFProduct', () => {
|
||||
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();
|
||||
});
|
||||
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();
|
||||
});
|
||||
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();
|
||||
});
|
||||
})
|
||||
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');
|
||||
});
|
||||
})
|
||||
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');
|
||||
});
|
||||
});
|
||||
})
|
||||
expect(result.category).toBe('baby_cereal')
|
||||
})
|
||||
})
|
||||
|
||||
describe('searchBabyProducts', () => {
|
||||
test('returns empty array for short query', async () => {
|
||||
const result = await searchBabyProducts('a');
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
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([]);
|
||||
});
|
||||
});
|
||||
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();
|
||||
});
|
||||
});
|
||||
const result = await getBabyProductDetails(null)
|
||||
expect(result).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
+88
-23
@@ -1,8 +1,38 @@
|
||||
import axios from 'axios';
|
||||
import redisClient from './redis-client.js';
|
||||
|
||||
const OFF_API_BASE = 'https://world.openfoodfacts.org/api/v2';
|
||||
// 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) {
|
||||
@@ -53,31 +83,61 @@ export async function searchBabyProducts(query) {
|
||||
}
|
||||
|
||||
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);
|
||||
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 {
|
||||
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
|
||||
// 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));
|
||||
}
|
||||
}
|
||||
return products;
|
||||
}
|
||||
|
||||
console.error(`[OFF] All retries failed for "${searchTerm}": ${lastError?.message}`);
|
||||
return [];
|
||||
} catch (error) {
|
||||
console.error('Error searching baby products from OFF:', error.message);
|
||||
@@ -100,8 +160,13 @@ export async function getBabyProductDetails(barcode) {
|
||||
}
|
||||
|
||||
console.log(`Fetching OFF product details: ${barcode}`);
|
||||
const response = await axios.get(`${OFF_API_BASE}/product/${barcode}.json`, {
|
||||
timeout: 5000,
|
||||
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) {
|
||||
|
||||
+193
-3
@@ -240,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(`
|
||||
@@ -647,6 +679,56 @@ app.get('/api/products/:source/:id', async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
// 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
|
||||
@@ -1680,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' });
|
||||
@@ -1901,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) => {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -356,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,16 +297,57 @@ function SearchView({ currentUser, onLoginRequest, initialQuery = '' }) {
|
||||
)}
|
||||
|
||||
{searchQuery && !selectedMedicine && (
|
||||
<MedicineResults
|
||||
medicines={medicines}
|
||||
onSelect={(m) => {
|
||||
saveToRecent(m);
|
||||
setSelectedMedicine(m);
|
||||
}}
|
||||
query={searchQuery}
|
||||
currentUser={currentUser}
|
||||
onLoginRequest={onLoginRequest}
|
||||
/>
|
||||
<>
|
||||
<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) => {
|
||||
saveToRecent(m);
|
||||
setSelectedMedicine(m);
|
||||
}}
|
||||
query={searchQuery}
|
||||
currentUser={currentUser}
|
||||
onLoginRequest={onLoginRequest}
|
||||
/>
|
||||
)}
|
||||
|
||||
{(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 && (
|
||||
|
||||
Reference in New Issue
Block a user