Restructure with Turborepo
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
PORT=3001
|
||||
SESSION_SECRET=change-me-in-production
|
||||
CORS_ORIGIN=http://localhost:3000
|
||||
FARMACIAS_WEBHOOK_URL=
|
||||
REDIS_HOST=localhost
|
||||
REDIS_PORT=6379
|
||||
REDIS_PASSWORD=
|
||||
|
||||
# PostgreSQL for user accounts (leave unset to fallback to SQLite — dev/test only)
|
||||
PG_URL=postgresql://farmaclic:change-me@localhost:5432/farmaclic
|
||||
PG_PASSWORD=change-me
|
||||
|
||||
# Web Push (VAPID). Generate with:
|
||||
# node -e "import('web-push').then(w => console.log(w.default.generateVAPIDKeys()))"
|
||||
VAPID_PUBLIC_KEY=
|
||||
VAPID_PRIVATE_KEY=
|
||||
VAPID_SUBJECT=mailto:admin@example.com
|
||||
@@ -0,0 +1,10 @@
|
||||
FROM node:18-slim
|
||||
WORKDIR /app
|
||||
COPY backend/package*.json ./
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends python3 make g++ && rm -rf /var/lib/apt/lists/*
|
||||
RUN npm ci --omit=dev
|
||||
COPY backend/ .
|
||||
COPY API/ /API/
|
||||
RUN mkdir -p /app/data
|
||||
EXPOSE 3001
|
||||
CMD ["node", "server.js"]
|
||||
@@ -0,0 +1,144 @@
|
||||
# 🔧 Solución Rápida - Error: no such column: medicine_id
|
||||
|
||||
## ❌ El Error
|
||||
|
||||
```
|
||||
Error: SQLITE_ERROR: no such column: medicine_id
|
||||
```
|
||||
|
||||
Este error ocurre porque la base de datos tiene la estructura antigua que usa `medicine_id`, pero el código actualizado ahora usa `medicine_nregistro`.
|
||||
|
||||
## ✅ Soluciones
|
||||
|
||||
### Opción 1: Reset Completo (Recomendado para desarrollo)
|
||||
|
||||
**Esto eliminará todos los datos actuales:**
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
|
||||
# Método 1: Usando el script
|
||||
npm run reset-db
|
||||
|
||||
# Método 2: Manual
|
||||
rm database.sqlite
|
||||
node seed.js
|
||||
node create-admin.js
|
||||
```
|
||||
|
||||
### Opción 2: Migración (Mantiene farmacias, pierde vínculos medicamento-farmacia)
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
node migrate.js
|
||||
```
|
||||
|
||||
**Nota:** Esta opción mantiene las farmacias pero elimina las relaciones medicamento-farmacia porque ahora usan un esquema diferente (nregistro de CIMA en lugar de IDs locales).
|
||||
|
||||
### Opción 3: Manual con SQLite
|
||||
|
||||
Si quieres más control:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
sqlite3 database.sqlite
|
||||
|
||||
# Dentro de SQLite:
|
||||
DROP TABLE IF EXISTS pharmacy_medicines;
|
||||
DROP INDEX IF EXISTS idx_pharmacy_medicine;
|
||||
|
||||
CREATE TABLE pharmacy_medicines (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
pharmacy_id INTEGER NOT NULL,
|
||||
medicine_nregistro TEXT NOT NULL,
|
||||
medicine_name TEXT,
|
||||
price REAL,
|
||||
stock INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id),
|
||||
UNIQUE(pharmacy_id, medicine_nregistro)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_pharmacy_medicine ON pharmacy_medicines(medicine_nregistro);
|
||||
|
||||
.quit
|
||||
```
|
||||
|
||||
## 🔍 Verificar la Estructura
|
||||
|
||||
Para verificar que la base de datos tiene la estructura correcta:
|
||||
|
||||
```bash
|
||||
cd backend
|
||||
sqlite3 database.sqlite "PRAGMA table_info(pharmacy_medicines);"
|
||||
```
|
||||
|
||||
**Salida esperada:**
|
||||
```
|
||||
0|id|INTEGER|0||1
|
||||
1|pharmacy_id|INTEGER|1||0
|
||||
2|medicine_nregistro|TEXT|1||0
|
||||
3|medicine_name|TEXT|0||0
|
||||
4|price|REAL|0||0
|
||||
5|stock|INTEGER|0|0|0
|
||||
```
|
||||
|
||||
## 🚀 Después de la Corrección
|
||||
|
||||
1. **Verifica que Redis esté corriendo:**
|
||||
```bash
|
||||
redis-cli ping
|
||||
# Debe responder: PONG
|
||||
```
|
||||
|
||||
2. **Inicia el servidor:**
|
||||
```bash
|
||||
cd backend
|
||||
npm start
|
||||
```
|
||||
|
||||
3. **Vincula medicamentos en el Admin Panel:**
|
||||
- Ve a http://localhost:3000
|
||||
- Haz login en el Admin Panel
|
||||
- Ve a la pestaña "Link Medicine"
|
||||
- Busca medicamentos desde CIMA
|
||||
- Vincúlalos a tus farmacias
|
||||
|
||||
## 📝 ¿Por qué cambió?
|
||||
|
||||
La aplicación ahora usa la **API oficial de CIMA** (Agencia Española de Medicamentos) en lugar de almacenar medicamentos localmente.
|
||||
|
||||
**Beneficios:**
|
||||
- ✅ Datos siempre actualizados
|
||||
- ✅ Más de 30,000 medicamentos disponibles
|
||||
- ✅ Información oficial y verificada
|
||||
- ✅ Menos mantenimiento de base de datos
|
||||
|
||||
**Estructura anterior:**
|
||||
```
|
||||
pharmacy_medicines
|
||||
- medicine_id → ID local en tabla medicines
|
||||
```
|
||||
|
||||
**Estructura nueva:**
|
||||
```
|
||||
pharmacy_medicines
|
||||
- medicine_nregistro → Número de registro de CIMA
|
||||
- medicine_name → Nombre cacheado para mostrar
|
||||
```
|
||||
|
||||
## 💡 Preguntas Frecuentes
|
||||
|
||||
**P: ¿Perderé mis farmacias?**
|
||||
R: No, las farmacias se mantienen. Solo necesitas re-vincular los medicamentos.
|
||||
|
||||
**P: ¿Perderé los vínculos medicamento-farmacia?**
|
||||
R: Sí, porque ahora usan un sistema diferente (nregistros de CIMA). Tendrás que re-vincularlos usando el panel de admin.
|
||||
|
||||
**P: ¿Y si tengo muchos vínculos?**
|
||||
R: La migración vale la pena por los beneficios a largo plazo. La re-vinculación es fácil con la búsqueda en tiempo real desde CIMA.
|
||||
|
||||
## 📚 Más Información
|
||||
|
||||
- Ver [MIGRATION.md](./MIGRATION.md) para guía completa de migración
|
||||
- Ver [CHANGES.md](./CHANGES.md) para lista de todos los cambios
|
||||
- Ver [README.md](./README.md) para documentación general
|
||||
@@ -0,0 +1,87 @@
|
||||
import { parseOsmOpeningHours } from '../../API/opening-hours-osm.js';
|
||||
|
||||
describe('parseOsmOpeningHours', () => {
|
||||
test('returns null for empty / non-string input', () => {
|
||||
expect(parseOsmOpeningHours('')).toBeNull();
|
||||
expect(parseOsmOpeningHours(null)).toBeNull();
|
||||
expect(parseOsmOpeningHours(undefined)).toBeNull();
|
||||
expect(parseOsmOpeningHours(123)).toBeNull();
|
||||
});
|
||||
|
||||
test('24/7 → every day 00:00–24:00', () => {
|
||||
expect(parseOsmOpeningHours('24/7')).toEqual({
|
||||
mon: ['00:00', '24:00'],
|
||||
tue: ['00:00', '24:00'],
|
||||
wed: ['00:00', '24:00'],
|
||||
thu: ['00:00', '24:00'],
|
||||
fri: ['00:00', '24:00'],
|
||||
sat: ['00:00', '24:00'],
|
||||
sun: ['00:00', '24:00'],
|
||||
});
|
||||
});
|
||||
|
||||
test('Mo-Fr 09:00-21:00 → weekdays set, weekend null', () => {
|
||||
const result = parseOsmOpeningHours('Mo-Fr 09:00-21:00');
|
||||
expect(result.mon).toEqual(['09:00', '21:00']);
|
||||
expect(result.fri).toEqual(['09:00', '21:00']);
|
||||
expect(result.sat).toBeNull();
|
||||
expect(result.sun).toBeNull();
|
||||
});
|
||||
|
||||
test('Multiple rules separated by semicolons', () => {
|
||||
const result = parseOsmOpeningHours('Mo-Fr 09:00-21:00; Sa 09:00-14:00; Su closed');
|
||||
expect(result.mon).toEqual(['09:00', '21:00']);
|
||||
expect(result.fri).toEqual(['09:00', '21:00']);
|
||||
expect(result.sat).toEqual(['09:00', '14:00']);
|
||||
expect(result.sun).toBeNull();
|
||||
});
|
||||
|
||||
test('Comma-separated day list', () => {
|
||||
const result = parseOsmOpeningHours('Mo,We,Fr 10:00-14:00');
|
||||
expect(result.mon).toEqual(['10:00', '14:00']);
|
||||
expect(result.tue).toBeNull();
|
||||
expect(result.wed).toEqual(['10:00', '14:00']);
|
||||
expect(result.thu).toBeNull();
|
||||
expect(result.fri).toEqual(['10:00', '14:00']);
|
||||
});
|
||||
|
||||
test('Split shifts collapsed to first-open / last-close', () => {
|
||||
const result = parseOsmOpeningHours('Mo-Fr 09:00-13:30,16:30-20:00');
|
||||
expect(result.mon).toEqual(['09:00', '20:00']);
|
||||
expect(result.fri).toEqual(['09:00', '20:00']);
|
||||
});
|
||||
|
||||
test('Wrap-around day range Sa-Mo', () => {
|
||||
const result = parseOsmOpeningHours('Sa-Mo 10:00-18:00');
|
||||
expect(result.sat).toEqual(['10:00', '18:00']);
|
||||
expect(result.sun).toEqual(['10:00', '18:00']);
|
||||
expect(result.mon).toEqual(['10:00', '18:00']);
|
||||
expect(result.tue).toBeNull();
|
||||
});
|
||||
|
||||
test('Public-holiday rules are ignored', () => {
|
||||
const result = parseOsmOpeningHours('Mo-Fr 09:00-21:00; PH off');
|
||||
expect(result.mon).toEqual(['09:00', '21:00']);
|
||||
});
|
||||
|
||||
test('Parenthetical comments are stripped', () => {
|
||||
const result = parseOsmOpeningHours('Mo-Fr 09:00-14:00 (verano)');
|
||||
expect(result.mon).toEqual(['09:00', '14:00']);
|
||||
});
|
||||
|
||||
test('"off" applies null to those days', () => {
|
||||
const result = parseOsmOpeningHours('Mo-Fr 09:00-21:00; Sa off');
|
||||
expect(result.sat).toBeNull();
|
||||
expect(result.mon).toEqual(['09:00', '21:00']);
|
||||
});
|
||||
|
||||
test('Returns null when nothing parses', () => {
|
||||
expect(parseOsmOpeningHours('see website')).toBeNull();
|
||||
expect(parseOsmOpeningHours('?')).toBeNull();
|
||||
});
|
||||
|
||||
test('Single-digit hours get zero-padded', () => {
|
||||
const result = parseOsmOpeningHours('Mo 9:00-18:00');
|
||||
expect(result.mon).toEqual(['09:00', '18:00']);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,80 @@
|
||||
import { jest } from '@jest/globals'
|
||||
|
||||
jest.unstable_mockModule('../cima-service.js', () => ({
|
||||
searchMedicines: jest.fn(async () => []),
|
||||
getMedicineDetails: jest.fn(async () => null),
|
||||
}))
|
||||
|
||||
jest.unstable_mockModule('../farmacias-webhook-import.js', () => ({
|
||||
runFarmaciaWebhookImport: jest.fn(async () => ({})),
|
||||
DEFAULT_FARMACIAS_WEBHOOK: '',
|
||||
importPharmaciesFromRows: jest.fn(async () => ({})),
|
||||
}))
|
||||
|
||||
jest.unstable_mockModule('../../API/index.js', () => ({
|
||||
fetchPharmaciesExternal: jest.fn(async () => []),
|
||||
}))
|
||||
|
||||
process.env.DATABASE_PATH = ':memory:'
|
||||
process.env.NODE_ENV = 'test'
|
||||
|
||||
const { default: supertest } = await import('supertest')
|
||||
const { app, initDatabase, db } = await import('../server.js')
|
||||
const { default: bcrypt } = await import('bcrypt')
|
||||
|
||||
beforeAll(async () => {
|
||||
await initDatabase()
|
||||
const hash = await bcrypt.hash('testpass', 10)
|
||||
await new Promise((resolve, reject) => {
|
||||
db.run(
|
||||
'INSERT INTO users (username, password_hash, is_admin) VALUES (?, ?, 1)',
|
||||
['testadmin', hash],
|
||||
(err) => (err ? reject(err) : resolve())
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Medicine search', () => {
|
||||
test('GET /api/medicines/search with empty q returns []', async () => {
|
||||
const res = await supertest(app).get('/api/medicines/search?q=')
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.body).toEqual([])
|
||||
})
|
||||
|
||||
test('GET /api/medicines/search with short q returns array', async () => {
|
||||
const res = await supertest(app).get('/api/medicines/search?q=a')
|
||||
expect(res.status).toBe(200)
|
||||
expect(Array.isArray(res.body)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Authentication', () => {
|
||||
test('POST /api/auth/login with wrong creds returns 401', async () => {
|
||||
const res = await supertest(app)
|
||||
.post('/api/auth/login')
|
||||
.send({ username: 'nobody', password: 'wrong' })
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Admin routes', () => {
|
||||
test('GET /api/admin/medicines without auth returns 401', async () => {
|
||||
const res = await supertest(app).get('/api/admin/medicines')
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
test('POST /api/admin/pharmacies with valid auth returns 201', async () => {
|
||||
const agent = supertest.agent(app)
|
||||
const login = await agent
|
||||
.post('/api/auth/login')
|
||||
.send({ username: 'testadmin', password: 'testpass' })
|
||||
expect(login.status).toBe(200)
|
||||
|
||||
const res = await agent.post('/api/admin/pharmacies').send({
|
||||
name: 'Test Pharmacy',
|
||||
address: 'Test Street 1',
|
||||
})
|
||||
expect(res.status).toBe(201)
|
||||
expect(res.body).toMatchObject({ name: 'Test Pharmacy', address: 'Test Street 1' })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,186 @@
|
||||
import axios from 'axios';
|
||||
import redisClient from './redis-client.js';
|
||||
|
||||
const CIMA_API_BASE_URL = 'https://cima.aemps.es/cima/rest';
|
||||
const CACHE_TTL = 3600; // 1 hora en segundos
|
||||
|
||||
/**
|
||||
* CIMA's nombre filter is prefix-oriented; narrow to rows that contain every
|
||||
* search term in the commercial name or active ingredient (full-word style).
|
||||
*/
|
||||
function filterMedicinesByFullQuery(medicines, searchTerm) {
|
||||
const terms = searchTerm
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.split(/\s+/)
|
||||
.filter(Boolean);
|
||||
if (terms.length === 0) return medicines;
|
||||
return medicines.filter((m) => {
|
||||
const hay = `${m.name || ''} ${m.active_ingredient || ''}`.toLowerCase();
|
||||
return terms.every((term) => hay.includes(term));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Busca medicamentos en la API de CIMA con caché de Redis
|
||||
* @param {string} query - Término de búsqueda
|
||||
* @returns {Promise<Array>} - Lista de medicamentos encontrados
|
||||
*/
|
||||
export async function searchMedicines(query) {
|
||||
if (!query || query.trim().length < 2) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const searchTerm = query.trim().toLowerCase();
|
||||
const cacheKey = `medicines:search:v2:${searchTerm}`;
|
||||
|
||||
try {
|
||||
// Intentar obtener del caché
|
||||
const cachedData = await redisClient.get(cacheKey);
|
||||
|
||||
if (cachedData) {
|
||||
console.log(`📦 Cache hit for: ${searchTerm}`);
|
||||
return JSON.parse(cachedData);
|
||||
}
|
||||
|
||||
// Si no está en caché, consultar la API de CIMA
|
||||
console.log(`🌐 Fetching from CIMA API: ${searchTerm}`);
|
||||
const response = await axios.get(`${CIMA_API_BASE_URL}/medicamentos`, {
|
||||
params: {
|
||||
nombre: searchTerm
|
||||
},
|
||||
timeout: 5000
|
||||
});
|
||||
|
||||
if (response.data && response.data.resultados) {
|
||||
// Transformar los datos de CIMA a nuestro formato
|
||||
const medicines = response.data.resultados.map(med => ({
|
||||
id: med.nregistro,
|
||||
nregistro: med.nregistro,
|
||||
name: med.nombre,
|
||||
active_ingredient: med.vtm?.nombre || null,
|
||||
dosage: med.dosis || null,
|
||||
form: med.formaFarmaceutica?.nombre || null,
|
||||
formSimplified: med.formaFarmaceuticaSimplificada?.nombre || null,
|
||||
laboratory: med.labtitular,
|
||||
prescription: med.cpresc,
|
||||
commercialized: med.comerc,
|
||||
generic: med.generico,
|
||||
photos: med.fotos || [],
|
||||
docs: med.docs || []
|
||||
}));
|
||||
|
||||
const filtered = filterMedicinesByFullQuery(medicines, searchTerm);
|
||||
|
||||
// Guardar en caché
|
||||
await redisClient.setEx(cacheKey, CACHE_TTL, JSON.stringify(filtered));
|
||||
|
||||
console.log(`✅ Cached ${filtered.length} medicines for: ${searchTerm}`);
|
||||
return filtered;
|
||||
}
|
||||
|
||||
return [];
|
||||
} catch (error) {
|
||||
console.error('Error searching medicines from CIMA:', error.message);
|
||||
|
||||
// Si falla, intentar devolver datos cacheados aunque hayan expirado
|
||||
try {
|
||||
const staleData = await redisClient.get(cacheKey);
|
||||
if (staleData) {
|
||||
console.log('⚠️ Returning stale cache data due to API error');
|
||||
return JSON.parse(staleData);
|
||||
}
|
||||
} catch (cacheError) {
|
||||
console.error('Cache fallback also failed:', cacheError);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtiene detalles de un medicamento específico por su número de registro
|
||||
* @param {string} nregistro - Número de registro del medicamento
|
||||
* @returns {Promise<Object|null>} - Datos del medicamento
|
||||
*/
|
||||
export async function getMedicineDetails(nregistro) {
|
||||
const cacheKey = `medicine:${nregistro}`;
|
||||
|
||||
try {
|
||||
// Intentar obtener del caché
|
||||
const cachedData = await redisClient.get(cacheKey);
|
||||
|
||||
if (cachedData) {
|
||||
console.log(`📦 Cache hit for medicine: ${nregistro}`);
|
||||
return JSON.parse(cachedData);
|
||||
}
|
||||
|
||||
// Consultar la API de CIMA
|
||||
console.log(`🌐 Fetching medicine details from CIMA: ${nregistro}`);
|
||||
const response = await axios.get(`${CIMA_API_BASE_URL}/medicamento/${nregistro}`, {
|
||||
timeout: 5000
|
||||
});
|
||||
|
||||
if (response.data) {
|
||||
const med = response.data;
|
||||
const medicineDetails = {
|
||||
id: med.nregistro,
|
||||
nregistro: med.nregistro,
|
||||
name: med.nombre,
|
||||
active_ingredient: med.principiosActivos?.[0]?.nombre || med.vtm?.nombre || null,
|
||||
dosage: med.dosis || null,
|
||||
form: med.formaFarmaceutica?.nombre || null,
|
||||
formSimplified: med.formaFarmaceuticaSimplificada?.nombre || null,
|
||||
laboratory: med.labtitular,
|
||||
prescription: med.cpresc,
|
||||
commercialized: med.comerc,
|
||||
generic: med.generico,
|
||||
photos: med.fotos || [],
|
||||
docs: med.docs || [],
|
||||
presentations: med.presentaciones || []
|
||||
};
|
||||
|
||||
// Guardar en caché (TTL más largo para detalles específicos)
|
||||
await redisClient.setEx(cacheKey, CACHE_TTL * 24, JSON.stringify(medicineDetails));
|
||||
|
||||
return medicineDetails;
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (error) {
|
||||
console.error(`Error fetching medicine ${nregistro} from CIMA:`, error.message);
|
||||
|
||||
// Intentar devolver datos cacheados aunque hayan expirado
|
||||
try {
|
||||
const staleData = await redisClient.get(cacheKey);
|
||||
if (staleData) {
|
||||
console.log('⚠️ Returning stale cache data due to API error');
|
||||
return JSON.parse(staleData);
|
||||
}
|
||||
} catch (cacheError) {
|
||||
console.error('Cache fallback also failed:', cacheError);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Limpia el caché de búsquedas (útil para testing o mantenimiento)
|
||||
* @param {string} pattern - Patrón de claves a eliminar (ej: 'medicines:search:*')
|
||||
* @returns {Promise<number>} - Número de claves eliminadas
|
||||
*/
|
||||
export async function clearCache(pattern = 'medicines:*') {
|
||||
try {
|
||||
const keys = await redisClient.keys(pattern);
|
||||
if (keys.length > 0) {
|
||||
await redisClient.del(keys);
|
||||
console.log(`🗑️ Cleared ${keys.length} cache entries`);
|
||||
return keys.length;
|
||||
}
|
||||
return 0;
|
||||
} catch (error) {
|
||||
console.error('Error clearing cache:', error);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import sqlite3 from 'sqlite3';
|
||||
import { promisify } from 'util';
|
||||
import bcrypt from 'bcrypt';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import pg from 'pg';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const PG_URL = process.env.PG_URL;
|
||||
|
||||
async function createAdmin() {
|
||||
const username = process.env.ADMIN_USERNAME || 'admin';
|
||||
const password = process.env.ADMIN_PASSWORD || 'admin123';
|
||||
const passwordHash = await bcrypt.hash(password, 10);
|
||||
|
||||
if (PG_URL) {
|
||||
const { Pool } = pg;
|
||||
const pool = new Pool({ connectionString: PG_URL });
|
||||
try {
|
||||
await pool.query(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||
address TEXT,
|
||||
latitude DOUBLE PRECISION,
|
||||
longitude DOUBLE PRECISION,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW()
|
||||
)
|
||||
`);
|
||||
|
||||
const existing = await pool.query('SELECT id FROM users WHERE username = $1', [username]);
|
||||
if (existing.rows.length > 0) {
|
||||
console.log(`Admin user '${username}' already exists.`);
|
||||
console.log('To reset, delete the user first and re-run.');
|
||||
await pool.end();
|
||||
return;
|
||||
}
|
||||
|
||||
await pool.query(
|
||||
'INSERT INTO users (username, password_hash, is_admin) VALUES ($1, $2, 1)',
|
||||
[username, passwordHash]
|
||||
);
|
||||
console.log(`Admin user '${username}' created in PostgreSQL.`);
|
||||
} finally {
|
||||
await pool.end();
|
||||
}
|
||||
} else {
|
||||
const dbPath = process.env.DATABASE_PATH || path.join(__dirname, 'database.sqlite');
|
||||
const db = new sqlite3.Database(dbPath);
|
||||
const dbRun = (sql, params = []) =>
|
||||
new Promise((resolve, reject) =>
|
||||
db.run(sql, params, function (err) { err ? reject(err) : resolve({ lastID: this.lastID }); })
|
||||
);
|
||||
const dbGet = promisify(db.get.bind(db));
|
||||
|
||||
try {
|
||||
await dbRun(`
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
username TEXT UNIQUE NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
try { await dbRun('ALTER TABLE users ADD COLUMN is_admin INTEGER NOT NULL DEFAULT 0'); } catch {}
|
||||
|
||||
const existing = await dbGet('SELECT id FROM users WHERE username = ?', [username]);
|
||||
if (existing) {
|
||||
console.log(`Admin user '${username}' already exists.`);
|
||||
console.log('To reset, delete the user first and re-run.');
|
||||
db.close();
|
||||
return;
|
||||
}
|
||||
|
||||
await dbRun(
|
||||
'INSERT INTO users (username, password_hash, is_admin) VALUES (?, ?, 1)',
|
||||
[username, passwordHash]
|
||||
);
|
||||
console.log(`Admin user '${username}' created in SQLite.`);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Username: ${username}`);
|
||||
console.log(`Password: ${password}`);
|
||||
console.log('\nIMPORTANT: Change the default password after first login!');
|
||||
}
|
||||
|
||||
createAdmin().catch((err) => {
|
||||
console.error('Error creating admin user:', err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,308 @@
|
||||
/**
|
||||
* Fetch pharmacy lists from an n8n (or any) HTTP webhook and map into FarmaClic rows.
|
||||
* Default URL: FARMACIAS_WEBHOOK_URL env or the project webhook.
|
||||
*/
|
||||
|
||||
import { parseOsmOpeningHours } from '../API/opening-hours-osm.js';
|
||||
|
||||
export const DEFAULT_FARMACIAS_WEBHOOK =
|
||||
process.env.FARMACIAS_WEBHOOK_URL ||
|
||||
'https://n8n.hacecalor.net/webhook/farmacias';
|
||||
|
||||
/**
|
||||
* Append region query params, e.g. GET /webhook/farmacias?lat=41.5631&lon=2.0038&radio=1500
|
||||
* @param {string} baseUrl - Absolute webhook URL (may already include other query params)
|
||||
* @param {{ lat?: number|string, lon?: number|string, lng?: number|string, radio?: number|string }} region
|
||||
*/
|
||||
export function buildFarmaciasWebhookUrl(baseUrl, region = {}) {
|
||||
const u = new URL(baseUrl);
|
||||
const lat = region.lat;
|
||||
const lon = region.lon ?? region.lng;
|
||||
const radio = region.radio;
|
||||
|
||||
if (lat !== undefined && lat !== null && String(lat).trim() !== '') {
|
||||
u.searchParams.set('lat', String(lat).trim());
|
||||
}
|
||||
if (lon !== undefined && lon !== null && String(lon).trim() !== '') {
|
||||
u.searchParams.set('lon', String(lon).trim());
|
||||
}
|
||||
if (radio !== undefined && radio !== null && String(radio).trim() !== '') {
|
||||
u.searchParams.set('radio', String(radio).trim());
|
||||
}
|
||||
return u.toString();
|
||||
}
|
||||
|
||||
function pick(obj, keys) {
|
||||
if (!obj || typeof obj !== 'object') return null;
|
||||
for (const k of keys) {
|
||||
if (Object.prototype.hasOwnProperty.call(obj, k)) {
|
||||
const v = obj[k];
|
||||
if (v !== undefined && v !== null && String(v).trim() !== '') {
|
||||
return String(v).trim();
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function toNumber(v) {
|
||||
if (v === undefined || v === null || v === '') return null;
|
||||
const n = typeof v === 'number' ? v : parseFloat(String(v).replace(',', '.'));
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize one raw record (Spanish / English field names, GeoJSON-ish).
|
||||
*/
|
||||
export function normalizePharmacyRecord(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
if (raw.json != null && typeof raw.json === 'object' && !Array.isArray(raw.json)) {
|
||||
return normalizePharmacyRecord(raw.json);
|
||||
}
|
||||
|
||||
let name = pick(raw, [
|
||||
'name',
|
||||
'nombre',
|
||||
'farmacia',
|
||||
'titular',
|
||||
'denominacion',
|
||||
'denominación',
|
||||
'razon_social',
|
||||
'razón_social',
|
||||
'title',
|
||||
]);
|
||||
let address = pick(raw, [
|
||||
'address',
|
||||
'direccion',
|
||||
'dirección',
|
||||
'domicilio',
|
||||
'ubicacion',
|
||||
'ubicación',
|
||||
'calle',
|
||||
'full_address',
|
||||
'direccion_completa',
|
||||
]);
|
||||
const phone = pick(raw, [
|
||||
'phone',
|
||||
'telefono',
|
||||
'teléfono',
|
||||
'tel',
|
||||
'telephone',
|
||||
'movil',
|
||||
'móvil',
|
||||
]);
|
||||
|
||||
let latitude = toNumber(raw.latitude ?? raw.latitud ?? raw.lat ?? raw.y);
|
||||
let longitude = toNumber(raw.longitude ?? raw.longitud ?? raw.lng ?? raw.lon ?? raw.x);
|
||||
|
||||
const coords = raw.geometry?.coordinates;
|
||||
if (Array.isArray(coords) && coords.length >= 2) {
|
||||
if (longitude == null) longitude = toNumber(coords[0]);
|
||||
if (latitude == null) latitude = toNumber(coords[1]);
|
||||
}
|
||||
if (raw.location && typeof raw.location === 'object') {
|
||||
if (latitude == null) latitude = toNumber(raw.location.lat ?? raw.location.latitude);
|
||||
if (longitude == null) longitude = toNumber(raw.location.lng ?? raw.location.lon ?? raw.location.longitude);
|
||||
}
|
||||
|
||||
if (!name && pick(raw, ['properties'])) {
|
||||
return normalizePharmacyRecord(raw.properties);
|
||||
}
|
||||
|
||||
if (!address && name) {
|
||||
const parts = [pick(raw, ['localidad', 'city', 'municipio']), pick(raw, ['cp', 'codigo_postal', 'postal_code'])]
|
||||
.filter(Boolean)
|
||||
.join(', ');
|
||||
if (parts) address = parts;
|
||||
}
|
||||
|
||||
return {
|
||||
name: name || null,
|
||||
address: address || null,
|
||||
phone: phone || null,
|
||||
latitude,
|
||||
longitude,
|
||||
opening_hours: extractOpeningHours(raw),
|
||||
};
|
||||
}
|
||||
|
||||
function extractOpeningHours(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const direct = raw.opening_hours;
|
||||
if (direct && typeof direct === 'object' && !Array.isArray(direct)) {
|
||||
return direct;
|
||||
}
|
||||
const candidates = [
|
||||
direct,
|
||||
raw.openingHours,
|
||||
raw.horario,
|
||||
raw.hours,
|
||||
raw.tags?.opening_hours,
|
||||
raw.properties?.opening_hours,
|
||||
];
|
||||
for (const c of candidates) {
|
||||
if (typeof c === 'string' && c.trim()) {
|
||||
const parsed = parseOsmOpeningHours(c);
|
||||
if (parsed) return parsed;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** n8n often returns [{ json: { ... } }, ...] */
|
||||
function unwrapN8nItemArray(arr) {
|
||||
if (!Array.isArray(arr) || arr.length === 0) return arr || [];
|
||||
const first = arr[0];
|
||||
if (
|
||||
first &&
|
||||
typeof first === 'object' &&
|
||||
first.json != null &&
|
||||
typeof first.json === 'object' &&
|
||||
!Array.isArray(first.json)
|
||||
) {
|
||||
return arr.map((x) => x.json);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
export function extractPharmacyRows(payload) {
|
||||
if (payload == null) return [];
|
||||
let list = [];
|
||||
|
||||
if (Array.isArray(payload)) list = payload;
|
||||
else if (typeof payload === 'object') {
|
||||
const candidates = [
|
||||
payload.farmacias,
|
||||
payload.data,
|
||||
payload.results,
|
||||
payload.items,
|
||||
payload.rows,
|
||||
payload.records,
|
||||
payload.pharmacies,
|
||||
payload.body,
|
||||
payload.output,
|
||||
];
|
||||
for (const c of candidates) {
|
||||
if (Array.isArray(c)) {
|
||||
list = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (list.length === 0 && Array.isArray(payload.json)) list = payload.json;
|
||||
}
|
||||
|
||||
return unwrapN8nItemArray(list);
|
||||
}
|
||||
|
||||
export async function fetchWebhookJson(url, fetchOptions = {}) {
|
||||
const res = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: { Accept: 'application/json', ...fetchOptions.headers },
|
||||
...fetchOptions,
|
||||
});
|
||||
const text = await res.text();
|
||||
let json;
|
||||
try {
|
||||
json = text ? JSON.parse(text) : null;
|
||||
} catch {
|
||||
throw new Error(
|
||||
`Webhook returned non-JSON (HTTP ${res.status}): ${text.slice(0, 300)}`
|
||||
);
|
||||
}
|
||||
if (!res.ok) {
|
||||
const hint = json?.message || JSON.stringify(json);
|
||||
throw new Error(`Webhook HTTP ${res.status}: ${hint}`);
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Function} dbGet - (sql, params) => Promise<row|undefined>
|
||||
* @param {Function} dbRun - (sql, params) => Promise<{lastID, changes}>
|
||||
* @param {object[]} rows - raw webhook items
|
||||
*/
|
||||
/** Insert normalized pharmacy rows; exported for OSM/Google/open-data importers */
|
||||
export async function importPharmaciesFromRows(dbGet, dbRun, rows) {
|
||||
let inserted = 0;
|
||||
let skipped = 0;
|
||||
let invalid = 0;
|
||||
const errors = [];
|
||||
|
||||
for (let i = 0; i < rows.length; i++) {
|
||||
const normalized = normalizePharmacyRecord(rows[i]);
|
||||
if (!normalized?.name || !normalized?.address) {
|
||||
invalid++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const { name, address, phone, latitude, longitude, opening_hours } = normalized;
|
||||
|
||||
try {
|
||||
const existing = await dbGet(
|
||||
'SELECT id FROM pharmacies WHERE name = ? AND address = ?',
|
||||
[name, address]
|
||||
);
|
||||
if (existing) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const openingHoursValue = opening_hours ? JSON.stringify(opening_hours) : null;
|
||||
|
||||
await dbRun(
|
||||
'INSERT INTO pharmacies (name, address, phone, latitude, longitude, opening_hours) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
[name, address, phone || null, latitude, longitude, openingHoursValue]
|
||||
);
|
||||
inserted++;
|
||||
} catch (err) {
|
||||
errors.push({ index: i, message: err.message });
|
||||
}
|
||||
}
|
||||
|
||||
return { inserted, skipped, invalid, errors };
|
||||
}
|
||||
|
||||
/**
|
||||
* Full flow: GET webhook → parse rows → insert into DB.
|
||||
* @param {string} [url] - Webhook base URL
|
||||
* @param {{ lat?: number|string, lon?: number|string, lng?: number|string, radio?: number|string } | null} [region] - Optional; adds ?lat=&lon=&radio= (meters)
|
||||
*/
|
||||
export async function runFarmaciaWebhookImport(
|
||||
dbGet,
|
||||
dbRun,
|
||||
url = DEFAULT_FARMACIAS_WEBHOOK,
|
||||
region = null
|
||||
) {
|
||||
const finalUrl =
|
||||
region && (region.lat != null || region.lon != null || region.lng != null || region.radio != null)
|
||||
? buildFarmaciasWebhookUrl(url, region)
|
||||
: url;
|
||||
|
||||
const json = await fetchWebhookJson(finalUrl);
|
||||
const rows = extractPharmacyRows(json);
|
||||
|
||||
if (rows.length === 0) {
|
||||
const keys = json && typeof json === 'object' ? Object.keys(json).join(', ') : typeof json;
|
||||
const err = new Error(
|
||||
`No pharmacy list found in webhook JSON (top-level keys: ${keys}). ` +
|
||||
`Fix the n8n workflow so the last node returns an array or { data: [...] }.`
|
||||
);
|
||||
err.details = json;
|
||||
throw err;
|
||||
}
|
||||
|
||||
const stats = await importPharmaciesFromRows(dbGet, dbRun, rows);
|
||||
const out = {
|
||||
...stats,
|
||||
totalReceived: rows.length,
|
||||
webhookUrl: finalUrl,
|
||||
};
|
||||
if (region && (region.lat != null || region.lon != null || region.lng != null || region.radio != null)) {
|
||||
out.region = {
|
||||
lat: region.lat ?? null,
|
||||
lon: region.lon ?? region.lng ?? null,
|
||||
radio: region.radio ?? null,
|
||||
};
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* CLI: pull pharmacies from webhook and insert into database.sqlite
|
||||
*
|
||||
* npm run import-farmacias
|
||||
* FARMACIAS_WEBHOOK_URL=https://... npm run import-farmacias
|
||||
*
|
||||
* Region (adds ?lat=&lon=&radio= in metres), e.g. your city:
|
||||
* node import-farmacias.js --lat 41.5631 --lon 2.0038 --radio 1500
|
||||
* node import-farmacias.js "https://n8n.example/webhook/farmacias" --lat 41.5631 --lon 2.0038 --radio 1500
|
||||
*
|
||||
* Env defaults for region: FARMACIAS_IMPORT_LAT, FARMACIAS_IMPORT_LON, FARMACIAS_IMPORT_RADIO
|
||||
*/
|
||||
|
||||
import sqlite3 from 'sqlite3';
|
||||
import { promisify } from 'util';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import {
|
||||
runFarmaciaWebhookImport,
|
||||
DEFAULT_FARMACIAS_WEBHOOK,
|
||||
} from './farmacias-webhook-import.js';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const dbPath = path.join(__dirname, 'database.sqlite');
|
||||
const db = new sqlite3.Database(dbPath);
|
||||
|
||||
function dbRun(sql, params = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.run(sql, params, function (err) {
|
||||
if (err) reject(err);
|
||||
else resolve({ lastID: this.lastID, changes: this.changes });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const dbGet = promisify(db.get.bind(db));
|
||||
|
||||
function parseCli(argv) {
|
||||
const region = {};
|
||||
const positional = [];
|
||||
for (let i = 2; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
if (a === '--lat' && argv[i + 1] != null) {
|
||||
region.lat = argv[++i];
|
||||
continue;
|
||||
}
|
||||
if ((a === '--lon' || a === '--lng') && argv[i + 1] != null) {
|
||||
region.lon = argv[++i];
|
||||
continue;
|
||||
}
|
||||
if (a === '--radio' && argv[i + 1] != null) {
|
||||
region.radio = argv[++i];
|
||||
continue;
|
||||
}
|
||||
if (a.startsWith('--')) {
|
||||
console.warn('Unknown flag:', a);
|
||||
continue;
|
||||
}
|
||||
positional.push(a);
|
||||
}
|
||||
if (process.env.FARMACIAS_IMPORT_LAT && region.lat == null) region.lat = process.env.FARMACIAS_IMPORT_LAT;
|
||||
if (process.env.FARMACIAS_IMPORT_LON && region.lon == null) region.lon = process.env.FARMACIAS_IMPORT_LON;
|
||||
if (process.env.FARMACIAS_IMPORT_RADIO && region.radio == null) {
|
||||
region.radio = process.env.FARMACIAS_IMPORT_RADIO;
|
||||
}
|
||||
const url = positional[0] || DEFAULT_FARMACIAS_WEBHOOK;
|
||||
const hasRegion =
|
||||
region.lat != null || region.lon != null || region.radio != null;
|
||||
return { url, region: hasRegion ? region : null };
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const { url, region } = parseCli(process.argv);
|
||||
console.log('Fetching pharmacies from:', url);
|
||||
if (region) console.log('Region query:', region);
|
||||
|
||||
try {
|
||||
const result = await runFarmaciaWebhookImport(dbGet, dbRun, url, region);
|
||||
console.log('Done.');
|
||||
console.log(' Total rows in response:', result.totalReceived);
|
||||
console.log(' Inserted:', result.inserted);
|
||||
console.log(' Skipped (duplicate name+address):', result.skipped);
|
||||
console.log(' Invalid (missing name or address):', result.invalid);
|
||||
if (result.errors.length) {
|
||||
console.log(' Row errors:', result.errors.length);
|
||||
console.log(result.errors.slice(0, 5));
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Import failed:', e.message);
|
||||
if (e.message.includes('Unused Respond to Webhook')) {
|
||||
console.error(
|
||||
'\n Hint: In n8n, connect the Webhook to a single "Respond to Webhook" node, or remove unused ones.'
|
||||
);
|
||||
}
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,6 @@
|
||||
export default {
|
||||
testEnvironment: 'node',
|
||||
transform: {},
|
||||
moduleFileExtensions: ['js', 'json'],
|
||||
testMatch: ['**/__tests__/**/*.test.js'],
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import sqlite3 from 'sqlite3';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const dbPath = path.join(__dirname, 'database.sqlite');
|
||||
const db = new sqlite3.Database(dbPath);
|
||||
|
||||
console.log('🔄 Starting database migration...');
|
||||
|
||||
// Promisify database operations
|
||||
function dbRun(sql, params = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.run(sql, params, function(err) {
|
||||
if (err) reject(err);
|
||||
else resolve({ lastID: this.lastID, changes: this.changes });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function dbAll(sql, params = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.all(sql, params, (err, rows) => {
|
||||
if (err) reject(err);
|
||||
else resolve(rows);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function migrate() {
|
||||
try {
|
||||
// Check if old medicines table exists
|
||||
const tables = await dbAll(`
|
||||
SELECT name FROM sqlite_master
|
||||
WHERE type='table' AND name='medicines'
|
||||
`);
|
||||
|
||||
if (tables.length > 0) {
|
||||
console.log('📋 Found old medicines table');
|
||||
|
||||
// Check if we need to migrate pharmacy_medicines
|
||||
const columns = await dbAll(`PRAGMA table_info(pharmacy_medicines)`);
|
||||
const hasMedicineId = columns.some(col => col.name === 'medicine_id');
|
||||
const hasNregistro = columns.some(col => col.name === 'medicine_nregistro');
|
||||
|
||||
if (hasMedicineId && !hasNregistro) {
|
||||
console.log('🔄 Migrating pharmacy_medicines table...');
|
||||
|
||||
// Create new table with updated schema
|
||||
await dbRun(`
|
||||
CREATE TABLE pharmacy_medicines_new (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
pharmacy_id INTEGER NOT NULL,
|
||||
medicine_nregistro TEXT NOT NULL,
|
||||
medicine_name TEXT,
|
||||
price REAL,
|
||||
stock INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id),
|
||||
UNIQUE(pharmacy_id, medicine_nregistro)
|
||||
)
|
||||
`);
|
||||
|
||||
console.log('✅ Created new pharmacy_medicines table');
|
||||
|
||||
// Copy data if any exists (though it will be invalid without nregistro)
|
||||
const oldData = await dbAll('SELECT * FROM pharmacy_medicines');
|
||||
console.log(`📦 Found ${oldData.length} old pharmacy-medicine relationships`);
|
||||
|
||||
if (oldData.length > 0) {
|
||||
console.log('⚠️ Warning: Old medicine relationships will be lost.');
|
||||
console.log(' You will need to re-link medicines using the CIMA database.');
|
||||
}
|
||||
|
||||
// Drop old table
|
||||
await dbRun('DROP TABLE pharmacy_medicines');
|
||||
|
||||
// Rename new table
|
||||
await dbRun('ALTER TABLE pharmacy_medicines_new RENAME TO pharmacy_medicines');
|
||||
|
||||
console.log('✅ Migrated pharmacy_medicines table');
|
||||
} else if (hasNregistro) {
|
||||
console.log('✅ pharmacy_medicines table already migrated');
|
||||
}
|
||||
|
||||
// We can keep the old medicines table for reference, or drop it
|
||||
console.log('ℹ️ Old medicines table can be kept for reference or deleted manually');
|
||||
console.log(' To delete: sqlite3 database.sqlite "DROP TABLE IF EXISTS medicines;"');
|
||||
} else {
|
||||
console.log('✅ No old medicines table found - creating new schema');
|
||||
|
||||
// Create pharmacy_medicines table with new schema
|
||||
await dbRun(`
|
||||
CREATE TABLE IF NOT EXISTS pharmacy_medicines (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
pharmacy_id INTEGER NOT NULL,
|
||||
medicine_nregistro TEXT NOT NULL,
|
||||
medicine_name TEXT,
|
||||
price REAL,
|
||||
stock INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id),
|
||||
UNIQUE(pharmacy_id, medicine_nregistro)
|
||||
)
|
||||
`);
|
||||
|
||||
console.log('✅ Created pharmacy_medicines table');
|
||||
}
|
||||
|
||||
console.log('');
|
||||
console.log('✨ Migration completed successfully!');
|
||||
console.log('');
|
||||
console.log('Next steps:');
|
||||
console.log('1. Install Redis: brew install redis (macOS) or apt-get install redis-server (Linux)');
|
||||
console.log('2. Start Redis: redis-server');
|
||||
console.log('3. Install dependencies: npm install');
|
||||
console.log('4. Start the server: npm start');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Migration failed:', error);
|
||||
process.exit(1);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
migrate();
|
||||
Generated
+9298
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"name": "farma-clic-backend",
|
||||
"version": "1.0.0",
|
||||
"description": "Backend API for FarmaClic",
|
||||
"main": "server.js",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"start": "node --env-file-if-exists=.env server.js",
|
||||
"dev": "node --env-file-if-exists=.env --watch server.js",
|
||||
"seed": "node seed.js",
|
||||
"create-admin": "node create-admin.js",
|
||||
"migrate": "node migrate.js",
|
||||
"reset-db": "bash reset-db.sh",
|
||||
"import-farmacias": "node import-farmacias.js",
|
||||
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --forceExit"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"@opentelemetry/api": "^1.9.0",
|
||||
"@opentelemetry/auto-instrumentations-node": "^0.52.0",
|
||||
"@opentelemetry/exporter-logs-otlp-grpc": "^0.55.0",
|
||||
"@opentelemetry/exporter-trace-otlp-grpc": "^0.55.0",
|
||||
"@opentelemetry/instrumentation-pino": "^0.45.0",
|
||||
"@opentelemetry/resources": "^1.28.0",
|
||||
"@opentelemetry/sdk-logs": "^0.55.0",
|
||||
"@opentelemetry/sdk-node": "^0.55.0",
|
||||
"@opentelemetry/sdk-trace-base": "^1.28.0",
|
||||
"@opentelemetry/semantic-conventions": "^1.28.0",
|
||||
"axios": "^1.6.0",
|
||||
"bcrypt": "^5.1.1",
|
||||
"connect-pg-simple": "^10.0.0",
|
||||
"connect-sqlite3": "^0.9.16",
|
||||
"cors": "^2.8.5",
|
||||
"express": "^4.18.2",
|
||||
"express-rate-limit": "^8.5.2",
|
||||
"express-session": "^1.17.3",
|
||||
"multer": "^2.2.0",
|
||||
"pg": "^8.13.0",
|
||||
"pino": "^9.4.0",
|
||||
"pino-http": "^10.3.0",
|
||||
"redis": "^4.6.0",
|
||||
"sqlite3": "^5.1.6",
|
||||
"tesseract.js": "^7.0.0",
|
||||
"web-push": "^3.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"jest": "^29.7.0",
|
||||
"supertest": "^7.2.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { createClient } from 'redis';
|
||||
|
||||
// Create Redis client
|
||||
const redisClient = createClient({
|
||||
socket: {
|
||||
host: process.env.REDIS_HOST || 'localhost',
|
||||
port: process.env.REDIS_PORT || 6379
|
||||
},
|
||||
password: process.env.REDIS_PASSWORD || undefined
|
||||
});
|
||||
|
||||
// Error handler
|
||||
redisClient.on('error', (err) => {
|
||||
console.error('Redis Client Error:', err);
|
||||
});
|
||||
|
||||
// Connection handler
|
||||
redisClient.on('connect', () => {
|
||||
console.log('✅ Connected to Redis');
|
||||
});
|
||||
|
||||
// Connect to Redis
|
||||
await redisClient.connect();
|
||||
|
||||
export default redisClient;
|
||||
@@ -0,0 +1,35 @@
|
||||
#!/bin/bash
|
||||
|
||||
echo "🔄 FarmaClic - Quick Database Reset"
|
||||
echo "===================================="
|
||||
echo ""
|
||||
echo "Este script eliminará la base de datos actual y creará una nueva."
|
||||
echo "⚠️ ADVERTENCIA: Todos los datos actuales se perderán."
|
||||
echo ""
|
||||
|
||||
read -p "¿Continuar? (s/n): " -n 1 -r
|
||||
echo ""
|
||||
|
||||
if [[ ! $REPLY =~ ^[Ss]$ ]]
|
||||
then
|
||||
echo "Operación cancelada."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "1️⃣ Eliminando base de datos antigua..."
|
||||
rm -f database.sqlite
|
||||
|
||||
echo "2️⃣ Creando nueva base de datos con estructura actualizada..."
|
||||
node seed.js
|
||||
|
||||
echo "3️⃣ Creando usuario administrador..."
|
||||
node create-admin.js
|
||||
|
||||
echo ""
|
||||
echo "✅ ¡Listo! Base de datos reiniciada con éxito."
|
||||
echo ""
|
||||
echo "Próximos pasos:"
|
||||
echo "1. Asegúrate de que Redis esté corriendo: redis-server"
|
||||
echo "2. Inicia el servidor: npm start"
|
||||
echo ""
|
||||
@@ -0,0 +1,171 @@
|
||||
import sqlite3 from 'sqlite3';
|
||||
import { promisify } from 'util';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const dbPath = path.join(__dirname, 'database.sqlite');
|
||||
const db = new sqlite3.Database(dbPath);
|
||||
|
||||
// Custom wrapper to get lastID from db.run
|
||||
function dbRun(sql, params = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
db.run(sql, params, function(err) {
|
||||
if (err) reject(err);
|
||||
else resolve({ lastID: this.lastID, changes: this.changes });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const dbGet = promisify(db.get.bind(db));
|
||||
|
||||
// Initialize database tables
|
||||
async function initDatabase() {
|
||||
try {
|
||||
// Create pharmacies table
|
||||
await dbRun(`
|
||||
CREATE TABLE IF NOT EXISTS pharmacies (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
address TEXT NOT NULL,
|
||||
phone TEXT,
|
||||
latitude REAL,
|
||||
longitude REAL
|
||||
)
|
||||
`);
|
||||
|
||||
// Create medicines table
|
||||
await dbRun(`
|
||||
CREATE TABLE IF NOT EXISTS medicines (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
active_ingredient TEXT,
|
||||
dosage TEXT,
|
||||
form TEXT
|
||||
)
|
||||
`);
|
||||
|
||||
// Create junction table for pharmacy-medicine relationships
|
||||
// Ahora usa nregistro (número de registro de CIMA) en lugar de medicine_id local
|
||||
await dbRun(`
|
||||
CREATE TABLE IF NOT EXISTS pharmacy_medicines (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
pharmacy_id INTEGER NOT NULL,
|
||||
medicine_nregistro TEXT NOT NULL,
|
||||
medicine_name TEXT,
|
||||
price REAL,
|
||||
stock INTEGER DEFAULT 0,
|
||||
FOREIGN KEY (pharmacy_id) REFERENCES pharmacies(id),
|
||||
UNIQUE(pharmacy_id, medicine_nregistro)
|
||||
)
|
||||
`);
|
||||
|
||||
// Create indexes for better search performance
|
||||
await dbRun(`CREATE INDEX IF NOT EXISTS idx_medicine_name ON medicines(name)`);
|
||||
await dbRun(`CREATE INDEX IF NOT EXISTS idx_pharmacy_medicine ON pharmacy_medicines(medicine_nregistro)`);
|
||||
|
||||
console.log('Database tables initialized');
|
||||
} catch (error) {
|
||||
console.error('Error initializing database:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Sample data
|
||||
const pharmacies = [
|
||||
{ name: 'Farmacia Central', address: 'Av. Principal 123, Ciudad', phone: '+34 123 456 789', lat: 40.4168, lng: -3.7038 },
|
||||
{ name: 'Farmacia San José', address: 'Calle Mayor 45, Ciudad', phone: '+34 987 654 321', lat: 40.4178, lng: -3.7048 },
|
||||
{ name: 'Farmacia del Sol', address: 'Plaza del Sol 12, Ciudad', phone: '+34 555 123 456', lat: 40.4158, lng: -3.7028 },
|
||||
{ name: 'Farmacia Salud', address: 'Calle Salud 78, Ciudad', phone: '+34 666 789 012', lat: 40.4188, lng: -3.7058 },
|
||||
{ name: 'Farmacia 24h', address: 'Av. Libertad 234, Ciudad', phone: '+34 777 345 678', lat: 40.4148, lng: -3.7018 },
|
||||
];
|
||||
|
||||
const medicines = [
|
||||
{ name: 'Paracetamol 500mg', active_ingredient: 'Paracetamol', dosage: '500mg', form: 'Tabletas' },
|
||||
{ name: 'Ibuprofeno 600mg', active_ingredient: 'Ibuprofeno', dosage: '600mg', form: 'Tabletas' },
|
||||
{ name: 'Aspirina 100mg', active_ingredient: 'Ácido Acetilsalicílico', dosage: '100mg', form: 'Tabletas' },
|
||||
{ name: 'Amoxicilina 500mg', active_ingredient: 'Amoxicilina', dosage: '500mg', form: 'Cápsulas' },
|
||||
{ name: 'Omeprazol 20mg', active_ingredient: 'Omeprazol', dosage: '20mg', form: 'Cápsulas' },
|
||||
{ name: 'Loratadina 10mg', active_ingredient: 'Loratadina', dosage: '10mg', form: 'Tabletas' },
|
||||
{ name: 'Diclofenaco 50mg', active_ingredient: 'Diclofenaco', dosage: '50mg', form: 'Tabletas' },
|
||||
{ name: 'Metformina 850mg', active_ingredient: 'Metformina', dosage: '850mg', form: 'Tabletas' },
|
||||
{ name: 'Atorvastatina 20mg', active_ingredient: 'Atorvastatina', dosage: '20mg', form: 'Tabletas' },
|
||||
{ name: 'Losartán 50mg', active_ingredient: 'Losartán', dosage: '50mg', form: 'Tabletas' },
|
||||
];
|
||||
|
||||
async function seedDatabase() {
|
||||
try {
|
||||
console.log('Starting database seeding...');
|
||||
|
||||
// Initialize database tables first
|
||||
await initDatabase();
|
||||
|
||||
// Clear existing data
|
||||
await dbRun('DELETE FROM pharmacy_medicines');
|
||||
await dbRun('DELETE FROM medicines');
|
||||
await dbRun('DELETE FROM pharmacies');
|
||||
|
||||
// Insert pharmacies
|
||||
const pharmacyIds = [];
|
||||
for (const pharmacy of pharmacies) {
|
||||
const result = await dbRun(
|
||||
'INSERT INTO pharmacies (name, address, phone, latitude, longitude) VALUES (?, ?, ?, ?, ?)',
|
||||
[pharmacy.name, pharmacy.address, pharmacy.phone, pharmacy.lat, pharmacy.lng]
|
||||
);
|
||||
pharmacyIds.push(result.lastID);
|
||||
}
|
||||
console.log(`Inserted ${pharmacyIds.length} pharmacies`);
|
||||
|
||||
// Insert medicines
|
||||
const medicineIds = [];
|
||||
for (const medicine of medicines) {
|
||||
const result = await dbRun(
|
||||
'INSERT INTO medicines (name, active_ingredient, dosage, form) VALUES (?, ?, ?, ?)',
|
||||
[medicine.name, medicine.active_ingredient, medicine.dosage, medicine.form]
|
||||
);
|
||||
medicineIds.push(result.lastID);
|
||||
}
|
||||
console.log(`Inserted ${medicineIds.length} medicines`);
|
||||
|
||||
// Create pharmacy-medicine relationships
|
||||
// Each medicine is available in 2-4 random pharmacies with random prices
|
||||
let relationshipCount = 0;
|
||||
for (let i = 0; i < medicineIds.length; i++) {
|
||||
const medicineId = medicineIds[i];
|
||||
const numPharmacies = Math.floor(Math.random() * 3) + 2; // 2-4 pharmacies
|
||||
const selectedPharmacies = new Set();
|
||||
|
||||
while (selectedPharmacies.size < numPharmacies) {
|
||||
selectedPharmacies.add(Math.floor(Math.random() * pharmacyIds.length));
|
||||
}
|
||||
|
||||
for (const pharmacyIndex of selectedPharmacies) {
|
||||
const pharmacyId = pharmacyIds[pharmacyIndex];
|
||||
const price = (Math.random() * 20 + 5).toFixed(2); // Random price between 5-25
|
||||
const stock = Math.floor(Math.random() * 50) + 10; // Random stock 10-60
|
||||
|
||||
// NOTA: Como ahora usamos CIMA API, este seed solo crea ejemplos
|
||||
// En producción, deberías vincular usando nregistros reales de CIMA
|
||||
const medicine = medicines[i];
|
||||
await dbRun(
|
||||
'INSERT INTO pharmacy_medicines (pharmacy_id, medicine_nregistro, medicine_name, price, stock) VALUES (?, ?, ?, ?, ?)',
|
||||
[pharmacyId, `EXAMPLE_${medicineId}`, medicine.name, price, stock]
|
||||
);
|
||||
relationshipCount++;
|
||||
}
|
||||
}
|
||||
console.log(`Created ${relationshipCount} pharmacy-medicine relationships`);
|
||||
console.log('⚠️ NOTA: Los medicamentos de ejemplo usan IDs ficticios.');
|
||||
|
||||
console.log('Database seeding completed successfully!');
|
||||
} catch (error) {
|
||||
console.error('Error seeding database:', error);
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
}
|
||||
|
||||
seedDatabase();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,60 @@
|
||||
// OpenTelemetry Node SDK bootstrap for FarmaClic backend.
|
||||
// Started as a side-effect import from server.js (ESM).
|
||||
//
|
||||
// Env vars (set by docker-compose):
|
||||
// OTEL_SERVICE_NAME — default: farmaclic-backend
|
||||
// OTEL_EXPORTER_OTLP_ENDPOINT — OTLP gRPC endpoint (e.g. http://alloy:4317)
|
||||
//
|
||||
// Exports traces to the shared Grafana Alloy collector, where they are
|
||||
// routed to Tempo.
|
||||
|
||||
import { NodeSDK } from '@opentelemetry/sdk-node';
|
||||
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
|
||||
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc';
|
||||
import * as resources from '@opentelemetry/resources';
|
||||
import { ATTR_SERVICE_NAME, ATTR_SERVICE_NAMESPACE } from '@opentelemetry/semantic-conventions';
|
||||
import { PinoInstrumentation } from '@opentelemetry/instrumentation-pino';
|
||||
|
||||
const serviceName = process.env.OTEL_SERVICE_NAME || 'farmaclic-backend';
|
||||
const otlpEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4317';
|
||||
|
||||
const resource = typeof resources.resourceFromAttributes === 'function'
|
||||
? resources.resourceFromAttributes({
|
||||
[ATTR_SERVICE_NAME]: serviceName,
|
||||
[ATTR_SERVICE_NAMESPACE]: 'farmaclic',
|
||||
})
|
||||
: new resources.Resource({
|
||||
[ATTR_SERVICE_NAME]: serviceName,
|
||||
[ATTR_SERVICE_NAMESPACE]: 'farmaclic',
|
||||
});
|
||||
|
||||
const sdk = new NodeSDK({
|
||||
resource,
|
||||
traceExporter: new OTLPTraceExporter({ url: otlpEndpoint }),
|
||||
instrumentations: [
|
||||
getNodeAutoInstrumentations({
|
||||
// Disable fs by default — it is noisy and rarely useful.
|
||||
'@opentelemetry/instrumentation-fs': { enabled: false },
|
||||
'@opentelemetry/instrumentation-dns': { enabled: false },
|
||||
}),
|
||||
new PinoInstrumentation(),
|
||||
],
|
||||
});
|
||||
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
sdk.start();
|
||||
}
|
||||
|
||||
const shutdown = async () => {
|
||||
try {
|
||||
if (process.env.NODE_ENV !== 'test') {
|
||||
await sdk.shutdown();
|
||||
}
|
||||
} catch (err) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('OpenTelemetry shutdown failed', err);
|
||||
}
|
||||
};
|
||||
|
||||
process.on('SIGTERM', shutdown);
|
||||
process.on('SIGINT', shutdown);
|
||||
Reference in New Issue
Block a user