Compare commits
24 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8bf0b33249 | |||
| f921b15d67 | |||
| 59edc7fbf1 | |||
| 731a6c98ae | |||
| 31c1a14343 | |||
| 25ebb899e9 | |||
| 2e3ce44e7b | |||
| 20debdb023 | |||
| 452a835b64 | |||
| f1b0eab11d | |||
| ee23f61057 | |||
| 26f309acfb | |||
| 4df1594b3b | |||
| 981f3bd3db | |||
| 83920ae57c | |||
| 7b1636a96e | |||
| bb2dbbab3a | |||
| d5b23aa94a | |||
| 9e786f2966 | |||
| a709deb893 | |||
| 229e1d8106 | |||
| f2a5dc4ca3 | |||
| d62e5976ce | |||
| d6f4164dae |
@@ -31,36 +31,32 @@ jobs:
|
|||||||
needs: detect-changes
|
needs: detect-changes
|
||||||
if: needs.detect-changes.outputs.backend == 'true'
|
if: needs.detect-changes.outputs.backend == 'true'
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 15
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '22'
|
node-version: '24'
|
||||||
cache: 'npm'
|
cache: 'npm'
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: npm ci --ignore-scripts
|
run: npm ci
|
||||||
- name: Install backend native deps
|
|
||||||
run: npm rebuild sqlite3 bcrypt --workspace=farma-clic-backend
|
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: npm test --workspace=farma-clic-backend
|
run: npm test --workspace=farma-clic-backend -- --ci
|
||||||
|
|
||||||
test-frontend:
|
test-frontend:
|
||||||
name: Frontend Tests
|
name: Frontend Tests
|
||||||
needs: detect-changes
|
needs: detect-changes
|
||||||
if: needs.detect-changes.outputs.frontend == 'true'
|
if: needs.detect-changes.outputs.frontend == 'true'
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 10
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '22'
|
node-version: '24'
|
||||||
cache: 'npm'
|
cache: 'npm'
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: npm ci --ignore-scripts
|
run: npm ci
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: npm test --workspace=farma-clic-frontend -- --run --reporter=basic
|
run: npm test --workspace=farma-clic-frontend -- --run --reporter=basic
|
||||||
|
|
||||||
|
|||||||
@@ -34,36 +34,40 @@ jobs:
|
|||||||
needs: detect-changes
|
needs: detect-changes
|
||||||
if: needs.detect-changes.outputs.backend == 'true'
|
if: needs.detect-changes.outputs.backend == 'true'
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 15
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- name: Checkout Code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '22'
|
node-version: '24'
|
||||||
cache: 'npm'
|
cache: 'npm'
|
||||||
- name: Install dependencies
|
|
||||||
run: npm ci --ignore-scripts
|
- name: Install Dependencies
|
||||||
- name: Install backend native deps
|
run: npm ci
|
||||||
run: npm rebuild sqlite3 bcrypt --workspace=farma-clic-backend
|
|
||||||
- name: Run Backend Tests
|
- name: Run Backend Tests
|
||||||
run: npm test --workspace=farma-clic-backend
|
run: npm test --workspace=farma-clic-backend -- --ci
|
||||||
|
|
||||||
test-frontend:
|
test-frontend:
|
||||||
name: Frontend Tests
|
name: Frontend Tests
|
||||||
needs: detect-changes
|
needs: detect-changes
|
||||||
if: needs.detect-changes.outputs.frontend == 'true'
|
if: needs.detect-changes.outputs.frontend == 'true'
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 10
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- name: Checkout Code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '22'
|
node-version: '24'
|
||||||
cache: 'npm'
|
cache: 'npm'
|
||||||
- name: Install dependencies
|
|
||||||
run: npm ci --ignore-scripts
|
- name: Install Dependencies
|
||||||
|
run: npm ci
|
||||||
|
|
||||||
- name: Run Frontend Tests
|
- name: Run Frontend Tests
|
||||||
run: npm test --workspace=farma-clic-frontend -- --run --reporter=basic
|
run: npm test --workspace=farma-clic-frontend -- --run --reporter=basic
|
||||||
|
|
||||||
@@ -72,16 +76,19 @@ jobs:
|
|||||||
needs: detect-changes
|
needs: detect-changes
|
||||||
if: needs.detect-changes.outputs.frontend-mobile == 'true'
|
if: needs.detect-changes.outputs.frontend-mobile == 'true'
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
timeout-minutes: 10
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- name: Checkout Code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js
|
||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: '22'
|
node-version: '24'
|
||||||
cache: 'npm'
|
cache: 'npm'
|
||||||
- name: Install dependencies
|
|
||||||
run: npm ci --ignore-scripts
|
- name: Install Dependencies
|
||||||
|
run: npm ci
|
||||||
|
|
||||||
- name: Run Frontend Mobile Tests
|
- name: Run Frontend Mobile Tests
|
||||||
run: npm test --workspace=frontend-mobile -- --ci
|
run: npm test --workspace=frontend-mobile -- --ci
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
|
|||||||
@@ -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:
|
# Expo Push Notifications (mobile). Get token from:
|
||||||
# https://expo.dev/accounts/[username]/settings/access-tokens
|
# https://expo.dev/accounts/[username]/settings/access-tokens
|
||||||
EXPO_ACCESS_TOKEN=
|
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', () => {
|
describe('transformOFFProduct', () => {
|
||||||
test('transforms a valid OFF product to unified model', () => {
|
test('transforms a valid OFF product to unified model', () => {
|
||||||
@@ -12,9 +27,9 @@ describe('transformOFFProduct', () => {
|
|||||||
nova_group: 1,
|
nova_group: 1,
|
||||||
ecoscore_grade: 'b',
|
ecoscore_grade: 'b',
|
||||||
categories_tags: ['en:baby-foods', 'en:baby-rice'],
|
categories_tags: ['en:baby-foods', 'en:baby-rice'],
|
||||||
};
|
}
|
||||||
|
|
||||||
const result = transformOFFProduct(offProduct);
|
const result = transformOFFProduct(offProduct)
|
||||||
|
|
||||||
expect(result).toEqual({
|
expect(result).toEqual({
|
||||||
id: '12345',
|
id: '12345',
|
||||||
@@ -27,66 +42,66 @@ describe('transformOFFProduct', () => {
|
|||||||
ingredients: 'Rice, Iron, Vitamins',
|
ingredients: 'Rice, Iron, Vitamins',
|
||||||
nova_group: 1,
|
nova_group: 1,
|
||||||
eco_score: 'b',
|
eco_score: 'b',
|
||||||
});
|
})
|
||||||
});
|
})
|
||||||
|
|
||||||
test('returns null for null/undefined input', () => {
|
test('returns null for null/undefined input', () => {
|
||||||
expect(transformOFFProduct(null)).toBeNull();
|
expect(transformOFFProduct(null)).toBeNull()
|
||||||
expect(transformOFFProduct(undefined)).toBeNull();
|
expect(transformOFFProduct(undefined)).toBeNull()
|
||||||
});
|
})
|
||||||
|
|
||||||
test('returns null when missing required fields', () => {
|
test('returns null when missing required fields', () => {
|
||||||
expect(transformOFFProduct({ _id: '123' })).toBeNull();
|
expect(transformOFFProduct({ _id: '123' })).toBeNull()
|
||||||
expect(transformOFFProduct({ product_name: 'Test' })).toBeNull();
|
expect(transformOFFProduct({ product_name: 'Test' })).toBeNull()
|
||||||
});
|
})
|
||||||
|
|
||||||
test('sets default brand to empty string when missing', () => {
|
test('sets default brand to empty string when missing', () => {
|
||||||
const result = transformOFFProduct({
|
const result = transformOFFProduct({
|
||||||
_id: '999',
|
_id: '999',
|
||||||
product_name: 'Plain Product',
|
product_name: 'Plain Product',
|
||||||
});
|
})
|
||||||
expect(result.brand).toBe('');
|
expect(result.brand).toBe('')
|
||||||
expect(result.image_url).toBeNull();
|
expect(result.image_url).toBeNull()
|
||||||
expect(result.nutriscore).toBeNull();
|
expect(result.nutriscore).toBeNull()
|
||||||
expect(result.ingredients).toBeNull();
|
expect(result.ingredients).toBeNull()
|
||||||
expect(result.nova_group).toBeNull();
|
expect(result.nova_group).toBeNull()
|
||||||
expect(result.eco_score).toBeNull();
|
expect(result.eco_score).toBeNull()
|
||||||
});
|
})
|
||||||
|
|
||||||
test('detects baby_milk category from tags', () => {
|
test('detects baby_milk category from tags', () => {
|
||||||
const result = transformOFFProduct({
|
const result = transformOFFProduct({
|
||||||
_id: '200',
|
_id: '200',
|
||||||
product_name: 'Infant Formula',
|
product_name: 'Infant Formula',
|
||||||
categories_tags: ['en:infant-milk'],
|
categories_tags: ['en:infant-milk'],
|
||||||
});
|
})
|
||||||
expect(result.category).toBe('baby_milk');
|
expect(result.category).toBe('baby_milk')
|
||||||
});
|
})
|
||||||
|
|
||||||
test('detects baby_cereal category from tags', () => {
|
test('detects baby_cereal category from tags', () => {
|
||||||
const result = transformOFFProduct({
|
const result = transformOFFProduct({
|
||||||
_id: '300',
|
_id: '300',
|
||||||
product_name: 'Baby Cereal',
|
product_name: 'Baby Cereal',
|
||||||
categories_tags: ['en:baby-cereals'],
|
categories_tags: ['en:baby-cereals'],
|
||||||
});
|
})
|
||||||
expect(result.category).toBe('baby_cereal');
|
expect(result.category).toBe('baby_cereal')
|
||||||
});
|
})
|
||||||
});
|
})
|
||||||
|
|
||||||
describe('searchBabyProducts', () => {
|
describe('searchBabyProducts', () => {
|
||||||
test('returns empty array for short query', async () => {
|
test('returns empty array for short query', async () => {
|
||||||
const result = await searchBabyProducts('a');
|
const result = await searchBabyProducts('a')
|
||||||
expect(result).toEqual([]);
|
expect(result).toEqual([])
|
||||||
});
|
})
|
||||||
|
|
||||||
test('returns empty array for null/empty query', async () => {
|
test('returns empty array for null/empty query', async () => {
|
||||||
expect(await searchBabyProducts(null)).toEqual([]);
|
expect(await searchBabyProducts(null)).toEqual([])
|
||||||
expect(await searchBabyProducts('')).toEqual([]);
|
expect(await searchBabyProducts('')).toEqual([])
|
||||||
});
|
})
|
||||||
});
|
})
|
||||||
|
|
||||||
describe('getBabyProductDetails', () => {
|
describe('getBabyProductDetails', () => {
|
||||||
test('returns null for null barcode', async () => {
|
test('returns null for null barcode', async () => {
|
||||||
const result = await getBabyProductDetails(null);
|
const result = await getBabyProductDetails(null)
|
||||||
expect(result).toBeNull();
|
expect(result).toBeNull()
|
||||||
});
|
})
|
||||||
});
|
})
|
||||||
|
|||||||
@@ -6,11 +6,6 @@ jest.unstable_mockModule('../cima-service.js', () => ({
|
|||||||
searchOTC: jest.fn(async () => []),
|
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', () => ({
|
jest.unstable_mockModule('../farmacias-webhook-import.js', () => ({
|
||||||
runFarmaciaWebhookImport: jest.fn(async () => ({})),
|
runFarmaciaWebhookImport: jest.fn(async () => ({})),
|
||||||
DEFAULT_FARMACIAS_WEBHOOK: '',
|
DEFAULT_FARMACIAS_WEBHOOK: '',
|
||||||
|
|||||||
@@ -3,8 +3,4 @@ export default {
|
|||||||
transform: {},
|
transform: {},
|
||||||
moduleFileExtensions: ['js', 'json'],
|
moduleFileExtensions: ['js', 'json'],
|
||||||
testMatch: ['**/__tests__/**/*.test.js'],
|
testMatch: ['**/__tests__/**/*.test.js'],
|
||||||
testTimeout: 15000,
|
|
||||||
openHandlesTimeout: 5000,
|
|
||||||
// Run test files in parallel (not individual tests within a file)
|
|
||||||
// workerIdleMemoryLimit: '512MB',
|
|
||||||
}
|
}
|
||||||
|
|||||||
+75
-10
@@ -1,8 +1,38 @@
|
|||||||
import axios from 'axios';
|
import axios from 'axios';
|
||||||
import redisClient from './redis-client.js';
|
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 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) {
|
export function transformOFFProduct(offProduct) {
|
||||||
if (!offProduct || !offProduct._id || !offProduct.product_name) {
|
if (!offProduct || !offProduct._id || !offProduct.product_name) {
|
||||||
@@ -53,31 +83,61 @@ export async function searchBabyProducts(query) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
console.log(`Fetching from OFF API: ${searchTerm}`);
|
console.log(`Fetching from OFF API: ${searchTerm}`);
|
||||||
const response = await axios.get(`${OFF_API_BASE}/search`, {
|
const headers = getOffHeaders();
|
||||||
|
console.log(`[OFF] User-Agent: ${headers['User-Agent']}`);
|
||||||
|
console.log(`[OFF] URL: ${OFF_API_BASE}/api/v2/search?brands_tags=${searchTerm}`);
|
||||||
|
|
||||||
|
let lastError;
|
||||||
|
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
|
||||||
|
try {
|
||||||
|
// Use v2 structured search with brand filter (more reliable than /cgi/search.pl)
|
||||||
|
// READ operations don't require auth per OFF docs, only User-Agent
|
||||||
|
const response = await axios.get(`${OFF_API_BASE}/api/v2/search`, {
|
||||||
params: {
|
params: {
|
||||||
categories_tags: 'baby-food',
|
brands_tags: searchTerm,
|
||||||
search_terms: searchTerm,
|
|
||||||
json: true,
|
|
||||||
fields: 'product_name,brands,image_url,nutriscore_grade,ingredients_text,nova_group,ecoscore_grade,categories_tags',
|
|
||||||
page_size: 20,
|
page_size: 20,
|
||||||
},
|
},
|
||||||
timeout: 5000,
|
headers,
|
||||||
|
timeout: 10000,
|
||||||
|
validateStatus: (status) => status === 200,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.data && response.data.products) {
|
// 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
|
const products = response.data.products
|
||||||
.map(transformOFFProduct)
|
.map(transformOFFProduct)
|
||||||
.filter(Boolean);
|
.filter(Boolean);
|
||||||
|
|
||||||
|
// Only cache non-empty results to avoid caching API failures
|
||||||
|
if (products.length > 0) {
|
||||||
try {
|
try {
|
||||||
await redisClient.setEx(cacheKey, CACHE_TTL, JSON.stringify(products));
|
await redisClient.setEx(cacheKey, CACHE_TTL, JSON.stringify(products));
|
||||||
console.log(`Cached ${products.length} OFF products for: ${searchTerm}`);
|
console.log(`Cached ${products.length} OFF products for: ${searchTerm}`);
|
||||||
} catch (cacheErr) {
|
} catch (cacheErr) {
|
||||||
// cache write failed, still return the data
|
// cache write failed, still return the data
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
console.log(`[OFF] No products found for "${searchTerm}", not caching empty result`);
|
||||||
|
}
|
||||||
return products;
|
return products;
|
||||||
|
} catch (err) {
|
||||||
|
lastError = err;
|
||||||
|
console.warn(`[OFF] Request failed for "${searchTerm}" (attempt ${attempt + 1}): ${err.message}`);
|
||||||
|
if (attempt < MAX_RETRIES) {
|
||||||
|
await sleep(RETRY_DELAY_MS * (attempt + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.error(`[OFF] All retries failed for "${searchTerm}": ${lastError?.message}`);
|
||||||
return [];
|
return [];
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error searching baby products from OFF:', error.message);
|
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}`);
|
console.log(`Fetching OFF product details: ${barcode}`);
|
||||||
const response = await axios.get(`${OFF_API_BASE}/product/${barcode}.json`, {
|
const headers = getOffHeaders();
|
||||||
timeout: 5000,
|
// 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) {
|
if (response.data && response.data.product) {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@
|
|||||||
"migrate": "node migrate.js",
|
"migrate": "node migrate.js",
|
||||||
"reset-db": "bash reset-db.sh",
|
"reset-db": "bash reset-db.sh",
|
||||||
"import-farmacias": "node import-farmacias.js",
|
"import-farmacias": "node import-farmacias.js",
|
||||||
"test": "NODE_OPTIONS='--experimental-vm-modules' npx jest --ci --forceExit --forceExitTimeout=30000"
|
"test": "NODE_OPTIONS='--experimental-vm-modules' npx jest --forceExit"
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"keywords": [],
|
||||||
"author": "",
|
"author": "",
|
||||||
|
|||||||
@@ -4,11 +4,7 @@ import { createClient } from 'redis';
|
|||||||
const redisClient = createClient({
|
const redisClient = createClient({
|
||||||
socket: {
|
socket: {
|
||||||
host: process.env.REDIS_HOST || 'localhost',
|
host: process.env.REDIS_HOST || 'localhost',
|
||||||
port: process.env.REDIS_PORT || 6379,
|
port: process.env.REDIS_PORT || 6379
|
||||||
reconnectStrategy: (retries) => {
|
|
||||||
if (retries > 10) return new Error('Redis max retries reached');
|
|
||||||
return Math.min(retries * 100, 3000);
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
password: process.env.REDIS_PASSWORD || undefined
|
password: process.env.REDIS_PASSWORD || undefined
|
||||||
});
|
});
|
||||||
@@ -23,9 +19,7 @@ redisClient.on('connect', () => {
|
|||||||
console.log('✅ Connected to Redis');
|
console.log('✅ Connected to Redis');
|
||||||
});
|
});
|
||||||
|
|
||||||
// Connect to Redis — skip in test (services are mocked) or when REDIS_URL is unset
|
// Connect to Redis
|
||||||
if (process.env.NODE_ENV !== 'test') {
|
|
||||||
await redisClient.connect();
|
await redisClient.connect();
|
||||||
}
|
|
||||||
|
|
||||||
export default redisClient;
|
export default redisClient;
|
||||||
|
|||||||
+196
-8
@@ -1,8 +1,5 @@
|
|||||||
// OpenTelemetry SDK — must be imported first to instrument http, express, pg, etc.
|
// OpenTelemetry SDK — must be imported first to instrument http, express, pg, etc.
|
||||||
// Skipped in test to avoid gRPC connection attempts to a non-existent collector.
|
import './src/tracing.js';
|
||||||
if (process.env.NODE_ENV !== 'test') {
|
|
||||||
await import('./src/tracing.js');
|
|
||||||
}
|
|
||||||
|
|
||||||
import express from 'express';
|
import express from 'express';
|
||||||
import cors from 'cors';
|
import cors from 'cors';
|
||||||
@@ -20,6 +17,8 @@ import webpush from 'web-push';
|
|||||||
import pino from 'pino';
|
import pino from 'pino';
|
||||||
import pinoHttp from 'pino-http';
|
import pinoHttp from 'pino-http';
|
||||||
import multer from 'multer';
|
import multer from 'multer';
|
||||||
|
import { createWorker } from 'tesseract.js';
|
||||||
|
import { BarcodeDetector } from 'barcode-detector';
|
||||||
import { searchMedicines, getMedicineDetails, searchOTC } from './cima-service.js';
|
import { searchMedicines, getMedicineDetails, searchOTC } from './cima-service.js';
|
||||||
import { searchBabyProducts, getBabyProductDetails } from './off-service.js';
|
import { searchBabyProducts, getBabyProductDetails } from './off-service.js';
|
||||||
import { runFarmaciaWebhookImport, DEFAULT_FARMACIAS_WEBHOOK, importPharmaciesFromRows } from './farmacias-webhook-import.js';
|
import { runFarmaciaWebhookImport, DEFAULT_FARMACIAS_WEBHOOK, importPharmaciesFromRows } from './farmacias-webhook-import.js';
|
||||||
@@ -241,6 +240,38 @@ async function initDatabase() {
|
|||||||
await dbRun(`CREATE INDEX IF NOT EXISTS idx_pharmacy_medicine ON pharmacy_medicines(medicine_nregistro)`);
|
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
|
// Create users table — PG when available, SQLite fallback
|
||||||
if (pgPool) {
|
if (pgPool) {
|
||||||
await pgPool.query(`
|
await pgPool.query(`
|
||||||
@@ -648,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 ==========
|
// ========== AUTHENTICATION MIDDLEWARE ==========
|
||||||
|
|
||||||
// Middleware to check if user is authenticated
|
// Middleware to check if user is authenticated
|
||||||
@@ -867,7 +948,6 @@ app.post('/api/tsi/ocr', upload.single('photo'), async (req, res) => {
|
|||||||
|
|
||||||
console.log('[OCR] Processing image, size:', req.file.size, 'bytes');
|
console.log('[OCR] Processing image, size:', req.file.size, 'bytes');
|
||||||
|
|
||||||
const { createWorker } = await import('tesseract.js');
|
|
||||||
const worker = await createWorker('spa+eng');
|
const worker = await createWorker('spa+eng');
|
||||||
const { data } = await worker.recognize(req.file.buffer);
|
const { data } = await worker.recognize(req.file.buffer);
|
||||||
await worker.terminate();
|
await worker.terminate();
|
||||||
@@ -1682,10 +1762,9 @@ app.delete('/api/admin/pharmacies/:id', requireAdmin, async (req, res) => {
|
|||||||
try {
|
try {
|
||||||
const pharmacyId = parseInt(req.params.id);
|
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]);
|
await userDbRun('DELETE FROM pharmacy_medicines WHERE pharmacy_id = ?', [pharmacyId]);
|
||||||
|
await userDbRun('DELETE FROM pharmacy_products WHERE pharmacy_id = ?', [pharmacyId]);
|
||||||
// Delete the pharmacy
|
|
||||||
await userDbRun('DELETE FROM pharmacies WHERE id = ?', [pharmacyId]);
|
await userDbRun('DELETE FROM pharmacies WHERE id = ?', [pharmacyId]);
|
||||||
|
|
||||||
res.json({ message: 'Pharmacy deleted successfully' });
|
res.json({ message: 'Pharmacy deleted successfully' });
|
||||||
@@ -1903,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
|
// Push notifications
|
||||||
|
|
||||||
app.get('/api/notifications/vapid-public-key', (req, res) => {
|
app.get('/api/notifications/vapid-public-key', (req, res) => {
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import React, { useState, useEffect } from 'react';
|
|||||||
import './App.css';
|
import './App.css';
|
||||||
import HomeView from './views/HomeView';
|
import HomeView from './views/HomeView';
|
||||||
import SearchView from './views/SearchView';
|
import SearchView from './views/SearchView';
|
||||||
|
import ProductView from './views/ProductView';
|
||||||
import ScannerView from './views/ScannerView';
|
import ScannerView from './views/ScannerView';
|
||||||
import AlertsView from './views/AlertsView';
|
import AlertsView from './views/AlertsView';
|
||||||
import ProfileView from './views/ProfileView';
|
import ProfileView from './views/ProfileView';
|
||||||
@@ -19,6 +20,7 @@ function App() {
|
|||||||
const [showSaved, setShowSaved] = useState(false);
|
const [showSaved, setShowSaved] = useState(false);
|
||||||
const [badgeCount, setBadgeCount] = useState(0);
|
const [badgeCount, setBadgeCount] = useState(0);
|
||||||
const [prescriptionSearch, setPrescriptionSearch] = useState('');
|
const [prescriptionSearch, setPrescriptionSearch] = useState('');
|
||||||
|
const [productScreen, setProductScreen] = useState(null);
|
||||||
const [screenSize, setScreenSize] = useState({
|
const [screenSize, setScreenSize] = useState({
|
||||||
width: window.innerWidth,
|
width: window.innerWidth,
|
||||||
height: window.innerHeight
|
height: window.innerHeight
|
||||||
@@ -180,6 +182,19 @@ function App() {
|
|||||||
currentUser={currentUser}
|
currentUser={currentUser}
|
||||||
onLoginRequest={() => setShowLogin(true)}
|
onLoginRequest={() => setShowLogin(true)}
|
||||||
initialQuery={prescriptionSearch}
|
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;
|
break;
|
||||||
|
|||||||
@@ -397,6 +397,28 @@
|
|||||||
border-color: var(--border-strong);
|
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 */
|
/* Pharmacies: search, region import, list filter */
|
||||||
.pharmacy-tools-card {
|
.pharmacy-tools-card {
|
||||||
background: var(--surface);
|
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 PharmacyManagement from '../components/admin/PharmacyManagement';
|
||||||
import MedicineManagement from '../components/admin/MedicineManagement';
|
import MedicineManagement from '../components/admin/MedicineManagement';
|
||||||
import PharmacyMedicineLink from '../components/admin/PharmacyMedicineLink';
|
import PharmacyMedicineLink from '../components/admin/PharmacyMedicineLink';
|
||||||
|
import PharmacyProductLink from '../components/admin/PharmacyProductLink';
|
||||||
|
|
||||||
function AdminView() {
|
function AdminView() {
|
||||||
const [authenticated, setAuthenticated] = useState(false);
|
const [authenticated, setAuthenticated] = useState(false);
|
||||||
@@ -115,12 +116,19 @@ function AdminView() {
|
|||||||
>
|
>
|
||||||
🔗 Vincular Medicamento a Farmacia
|
🔗 Vincular Medicamento a Farmacia
|
||||||
</button>
|
</button>
|
||||||
|
<button
|
||||||
|
className={`admin-tab ${activeTab === 'link-product' ? 'active' : ''}`}
|
||||||
|
onClick={() => setActiveTab('link-product')}
|
||||||
|
>
|
||||||
|
🍎 Vincular Producto a Farmacia
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="admin-content">
|
<div className="admin-content">
|
||||||
{activeTab === 'pharmacies' && <PharmacyManagement />}
|
{activeTab === 'pharmacies' && <PharmacyManagement />}
|
||||||
{activeTab === 'medicines' && <MedicineManagement />}
|
{activeTab === 'medicines' && <MedicineManagement />}
|
||||||
{activeTab === 'link' && <PharmacyMedicineLink />}
|
{activeTab === 'link' && <PharmacyMedicineLink />}
|
||||||
|
{activeTab === 'link-product' && <PharmacyProductLink />}
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</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);
|
color: var(--primary);
|
||||||
font-size: 0.85rem;
|
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 React, { useState, useEffect, useMemo, useCallback } from 'react';
|
||||||
import SearchBar from '../components/SearchBar';
|
import SearchBar from '../components/SearchBar';
|
||||||
import MedicineResults from '../components/MedicineResults';
|
import MedicineResults from '../components/MedicineResults';
|
||||||
|
import ProductResults from '../components/ProductResults';
|
||||||
import PharmacyList from '../components/PharmacyList';
|
import PharmacyList from '../components/PharmacyList';
|
||||||
import PharmacyMap from '../components/PharmacyMap';
|
import PharmacyMap from '../components/PharmacyMap';
|
||||||
import { haversineKm, getUserPosition, hasCachedPosition } from '../utils/geo';
|
import { haversineKm, getUserPosition, hasCachedPosition } from '../utils/geo';
|
||||||
@@ -13,9 +14,11 @@ const suggestions = [
|
|||||||
{ name: 'Omeprazol', icon: 'emergency_home', color: 'neutral-4' },
|
{ 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 [searchQuery, setSearchQuery] = useState(initialQuery);
|
||||||
const [medicines, setMedicines] = useState([]);
|
const [medicines, setMedicines] = useState([]);
|
||||||
|
const [products, setProducts] = useState([]);
|
||||||
|
const [searchMode, setSearchMode] = useState('all');
|
||||||
const [selectedMedicine, setSelectedMedicine] = useState(null);
|
const [selectedMedicine, setSelectedMedicine] = useState(null);
|
||||||
const [pharmacies, setPharmacies] = useState([]);
|
const [pharmacies, setPharmacies] = useState([]);
|
||||||
const [loading, setLoading] = useState(false);
|
const [loading, setLoading] = useState(false);
|
||||||
@@ -73,25 +76,43 @@ function SearchView({ currentUser, onLoginRequest, initialQuery = '' }) {
|
|||||||
}, [currentUser]);
|
}, [currentUser]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const searchMedicines = async () => {
|
const searchAll = async () => {
|
||||||
if (searchQuery.trim().length < 2) {
|
if (searchQuery.trim().length < 2) {
|
||||||
setMedicines([]);
|
setMedicines([]);
|
||||||
|
setProducts([]);
|
||||||
setSelectedMedicine(null);
|
setSelectedMedicine(null);
|
||||||
setPharmacies([]);
|
setPharmacies([]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
const query = searchQuery.trim();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/api/medicines/search?q=${encodeURIComponent(searchQuery)}`);
|
// Run both searches in parallel for speed
|
||||||
const data = await response.json();
|
const [medicinesRes, productsRes] = await Promise.allSettled([
|
||||||
setMedicines(data);
|
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) {
|
} catch (error) {
|
||||||
console.error('Error searching medicines:', error);
|
console.error('Search error:', error);
|
||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
const timeoutId = setTimeout(searchMedicines, 300);
|
const timeoutId = setTimeout(searchAll, 300);
|
||||||
return () => clearTimeout(timeoutId);
|
return () => clearTimeout(timeoutId);
|
||||||
}, [searchQuery]);
|
}, [searchQuery]);
|
||||||
|
|
||||||
@@ -276,6 +297,29 @@ function SearchView({ currentUser, onLoginRequest, initialQuery = '' }) {
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{searchQuery && !selectedMedicine && (
|
{searchQuery && !selectedMedicine && (
|
||||||
|
<>
|
||||||
|
<div className="filter-tabs">
|
||||||
|
<button
|
||||||
|
className={`filter-tab ${searchMode === 'all' ? 'filter-tab--active' : ''}`}
|
||||||
|
onClick={() => setSearchMode('all')}
|
||||||
|
>
|
||||||
|
Todos ({medicines.length + products.length})
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className={`filter-tab ${searchMode === 'medicines' ? 'filter-tab--active' : ''}`}
|
||||||
|
onClick={() => setSearchMode('medicines')}
|
||||||
|
>
|
||||||
|
Medicamentos ({medicines.length})
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className={`filter-tab ${searchMode === 'products' ? 'filter-tab--active' : ''}`}
|
||||||
|
onClick={() => setSearchMode('products')}
|
||||||
|
>
|
||||||
|
Parafarmacia ({products.length})
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{(searchMode === 'all' || searchMode === 'medicines') && (
|
||||||
<MedicineResults
|
<MedicineResults
|
||||||
medicines={medicines}
|
medicines={medicines}
|
||||||
onSelect={(m) => {
|
onSelect={(m) => {
|
||||||
@@ -288,6 +332,24 @@ function SearchView({ currentUser, onLoginRequest, initialQuery = '' }) {
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{(searchMode === 'all' || searchMode === 'products') && products.length > 0 && (
|
||||||
|
<div className="products-section">
|
||||||
|
<h3 className="section-subtitle">Parafarmacia y Bebé</h3>
|
||||||
|
<ProductResults
|
||||||
|
products={products}
|
||||||
|
onSelect={(p) => {
|
||||||
|
if (onNavigateToProduct) {
|
||||||
|
onNavigateToProduct(p.source, p.id);
|
||||||
|
} else {
|
||||||
|
window.location.href = `/product/${p.source}/${p.id}`;
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
|
||||||
{selectedMedicine && (
|
{selectedMedicine && (
|
||||||
<div className="selected-medicine-section">
|
<div className="selected-medicine-section">
|
||||||
<div className="medicine-info">
|
<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