97 lines
3.2 KiB
JavaScript
97 lines
3.2 KiB
JavaScript
import express from 'express';
|
|
import { getFavorites, getNotifiedArticles, getDB, getWorkers } from '../services/mongodb.js';
|
|
import { basicAuthMiddleware } from '../middlewares/auth.js';
|
|
import { adminAuthMiddleware } from '../middlewares/adminAuth.js';
|
|
import { broadcast } from '../services/websocket.js';
|
|
|
|
const router = express.Router();
|
|
|
|
// Health check (no requiere autenticación)
|
|
router.get('/health', async (req, res) => {
|
|
try {
|
|
// Verificar que MongoDB está disponible (opcional, no falla si no está)
|
|
const db = getDB();
|
|
const mongodbStatus = db ? 'connected' : 'unavailable';
|
|
|
|
res.json({
|
|
status: 'ok',
|
|
timestamp: new Date().toISOString(),
|
|
mongodb: mongodbStatus,
|
|
service: 'wallamonitor-backend'
|
|
});
|
|
} catch (error) {
|
|
// Incluso si hay un error, el servidor está funcionando, así que retornamos ok
|
|
res.json({
|
|
status: 'ok',
|
|
timestamp: new Date().toISOString(),
|
|
mongodb: 'error',
|
|
service: 'wallamonitor-backend',
|
|
error: error.message
|
|
});
|
|
}
|
|
});
|
|
|
|
// Obtener estadísticas (requiere autenticación obligatoria)
|
|
router.get('/stats', basicAuthMiddleware, async (req, res) => {
|
|
try {
|
|
const db = getDB();
|
|
if (!db) {
|
|
return res.status(500).json({ error: 'MongoDB no está disponible' });
|
|
}
|
|
|
|
// Obtener usuario autenticado (requerido)
|
|
const user = req.user;
|
|
const isAdmin = user.role === 'admin';
|
|
|
|
let totalWorkers = 0;
|
|
let activeWorkers = 0;
|
|
let favorites = [];
|
|
let notifiedArticles = [];
|
|
|
|
if (isAdmin) {
|
|
// Admin: estadísticas globales de todos los usuarios
|
|
const workersCollection = db.collection('workers');
|
|
const allWorkers = await workersCollection.find({}).toArray();
|
|
|
|
for (const userWorkers of allWorkers) {
|
|
const items = userWorkers.items || [];
|
|
const disabled = userWorkers.disabled || [];
|
|
totalWorkers += items.length;
|
|
activeWorkers += items.filter(w => !disabled.includes(w.name) && !disabled.includes(w.id)).length;
|
|
}
|
|
|
|
favorites = await getFavorites(null); // Todos los favoritos
|
|
notifiedArticles = await getNotifiedArticles(); // Todos los artículos
|
|
} else {
|
|
// Usuario normal: solo sus estadísticas
|
|
const workers = await getWorkers(user.username);
|
|
const items = workers.items || [];
|
|
const disabled = workers.disabled || [];
|
|
totalWorkers = items.length;
|
|
activeWorkers = items.filter(w => !disabled.includes(w.name) && !disabled.includes(w.id)).length;
|
|
|
|
favorites = await getFavorites(user.username); // Solo sus favoritos
|
|
notifiedArticles = await getNotifiedArticles({ username: user.username }); // Solo sus artículos
|
|
}
|
|
|
|
const stats = {
|
|
totalWorkers,
|
|
activeWorkers,
|
|
totalFavorites: favorites.length,
|
|
totalNotified: notifiedArticles.length,
|
|
platforms: {
|
|
wallapop: notifiedArticles.filter(a => a.platform === 'wallapop').length,
|
|
vinted: notifiedArticles.filter(a => a.platform === 'vinted').length,
|
|
},
|
|
};
|
|
|
|
res.json(stats);
|
|
} catch (error) {
|
|
console.error('Error obteniendo estadísticas:', error);
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
export default router;
|
|
|