142 lines
4.8 KiB
JavaScript
142 lines
4.8 KiB
JavaScript
import express from 'express';
|
|
import { getFavorites, getNotifiedArticles, getDB, getWorkers, clearAllArticles } 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();
|
|
|
|
// 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 });
|
|
}
|
|
});
|
|
|
|
// Limpiar toda la caché de MongoDB (requiere autenticación de administrador)
|
|
router.delete('/cache', basicAuthMiddleware, adminAuthMiddleware, async (req, res) => {
|
|
try {
|
|
const db = getDB();
|
|
if (!db) {
|
|
return res.status(500).json({ error: 'MongoDB no está disponible' });
|
|
}
|
|
|
|
// Eliminar todos los artículos
|
|
const count = await clearAllArticles();
|
|
|
|
// Notificar a los clientes WebSocket
|
|
broadcast({
|
|
type: 'cache_cleared',
|
|
data: { count, timestamp: Date.now() }
|
|
});
|
|
|
|
// También notificar actualización de artículos (ahora está vacío)
|
|
broadcast({ type: 'articles_updated', data: [] });
|
|
|
|
// También actualizar favoritos (debería estar vacío ahora)
|
|
const favorites = await getFavorites(null);
|
|
broadcast({ type: 'favorites_updated', data: favorites, username: null });
|
|
|
|
res.json({
|
|
success: true,
|
|
message: `Todos los artículos eliminados: ${count} artículos borrados`,
|
|
count
|
|
});
|
|
} catch (error) {
|
|
console.error('Error limpiando cache de MongoDB:', error);
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// Endpoint específico para borrar artículos (alias de /cache para claridad)
|
|
router.delete('/articles', basicAuthMiddleware, adminAuthMiddleware, async (req, res) => {
|
|
try {
|
|
const db = getDB();
|
|
if (!db) {
|
|
return res.status(500).json({ error: 'MongoDB no está disponible' });
|
|
}
|
|
|
|
// Eliminar todos los artículos
|
|
const count = await clearAllArticles();
|
|
|
|
// Notificar a los clientes WebSocket
|
|
broadcast({
|
|
type: 'articles_cleared',
|
|
data: { count, timestamp: Date.now() }
|
|
});
|
|
|
|
// También notificar actualización de artículos (ahora está vacío)
|
|
broadcast({ type: 'articles_updated', data: [] });
|
|
|
|
// También actualizar favoritos (debería estar vacío ahora)
|
|
const favorites = await getFavorites(null);
|
|
broadcast({ type: 'favorites_updated', data: favorites, username: null });
|
|
|
|
res.json({
|
|
success: true,
|
|
message: `Todos los artículos eliminados: ${count} artículos borrados`,
|
|
count
|
|
});
|
|
} catch (error) {
|
|
console.error('Error borrando artículos:', error);
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
export default router;
|
|
|