mongodb
Signed-off-by: Omar Sánchez Pizarro <omar.sanchez@pistacero.net>
This commit is contained in:
@@ -2,21 +2,59 @@
|
||||
<div>
|
||||
<div class="mb-4 sm:mb-6">
|
||||
<div class="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-3 sm:gap-4 mb-4">
|
||||
<h1 class="text-2xl sm:text-3xl font-bold text-gray-900 dark:text-gray-100">Artículos Notificados</h1>
|
||||
<div class="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:space-x-4">
|
||||
<div>
|
||||
<h1 class="text-2xl sm:text-3xl font-bold text-gray-900 dark:text-gray-100">Artículos Notificados</h1>
|
||||
<p v-if="currentUser" class="mt-1 text-sm text-gray-500 dark:text-gray-400">
|
||||
<span v-if="isAdmin">Todos los artículos</span>
|
||||
<span v-else>Tus artículos</span>
|
||||
<span class="font-medium text-gray-700 dark:text-gray-300 ml-1">({{ currentUser }})</span>
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex flex-col sm:flex-row items-stretch sm:items-center gap-2 sm:space-x-4 flex-wrap">
|
||||
<select
|
||||
v-model="selectedPlatform"
|
||||
@change="loadArticles"
|
||||
class="input text-sm sm:text-base"
|
||||
style="width: 100%; min-width: 180px;"
|
||||
style="width: 100%; min-width: 150px;"
|
||||
>
|
||||
<option value="">Todas las plataformas</option>
|
||||
<option value="wallapop">Wallapop</option>
|
||||
<option value="vinted">Vinted</option>
|
||||
</select>
|
||||
<select
|
||||
v-if="isAdmin"
|
||||
v-model="selectedUsername"
|
||||
@change="loadArticles"
|
||||
class="input text-sm sm:text-base"
|
||||
style="width: 100%; min-width: 150px;"
|
||||
>
|
||||
<option value="">Todos los usuarios</option>
|
||||
<option v-for="username in availableUsernames" :key="username" :value="username">
|
||||
{{ username }}
|
||||
</option>
|
||||
</select>
|
||||
<select
|
||||
v-model="selectedWorker"
|
||||
@change="loadArticles"
|
||||
class="input text-sm sm:text-base"
|
||||
style="width: 100%; min-width: 150px;"
|
||||
>
|
||||
<option value="">Todos los workers</option>
|
||||
<option v-for="worker in availableWorkers" :key="worker" :value="worker">
|
||||
{{ worker }}
|
||||
</option>
|
||||
</select>
|
||||
<button @click="loadArticles" class="btn btn-primary whitespace-nowrap">
|
||||
Actualizar
|
||||
</button>
|
||||
<button
|
||||
v-if="isAdmin"
|
||||
@click="handleClearAllArticles"
|
||||
class="btn btn-danger whitespace-nowrap"
|
||||
title="Borrar todos los artículos (solo admin)"
|
||||
>
|
||||
🗑️ Borrar Todos
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -25,7 +63,7 @@
|
||||
<input
|
||||
v-model="searchQuery"
|
||||
type="text"
|
||||
placeholder="Buscar artículos en Redis por título, descripción, precio, localidad..."
|
||||
placeholder="Buscar artículos por título, descripción, precio, localidad..."
|
||||
class="input pr-10"
|
||||
@input="searchQuery = $event.target.value"
|
||||
/>
|
||||
@@ -49,7 +87,7 @@
|
||||
|
||||
<div v-else-if="searching" class="card text-center py-12">
|
||||
<div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
|
||||
<p class="mt-2 text-gray-600 dark:text-gray-400">Buscando artículos en Redis...</p>
|
||||
<p class="mt-2 text-gray-600 dark:text-gray-400">Buscando artículos...</p>
|
||||
</div>
|
||||
|
||||
<div v-else-if="filteredArticles.length === 0 && searchQuery && !searching" class="card text-center py-12">
|
||||
@@ -58,95 +96,11 @@
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-4">
|
||||
<div
|
||||
<ArticleCard
|
||||
v-for="article in filteredArticles"
|
||||
:key="`${article.platform}-${article.id}`"
|
||||
class="card hover:shadow-lg transition-shadow"
|
||||
>
|
||||
<div class="flex flex-col sm:flex-row gap-3 sm:gap-4">
|
||||
<!-- Imagen del artículo -->
|
||||
<div class="flex-shrink-0 self-center sm:self-start">
|
||||
<div v-if="article.images && article.images.length > 0" class="w-24 h-24 sm:w-32 sm:h-32 relative">
|
||||
<img
|
||||
:src="article.images[0]"
|
||||
:alt="article.title || 'Sin título'"
|
||||
class="w-24 h-24 sm:w-32 sm:h-32 object-cover rounded-lg"
|
||||
@error="($event) => handleImageError($event)"
|
||||
/>
|
||||
</div>
|
||||
<div v-else class="w-24 h-24 sm:w-32 sm:h-32 bg-gray-200 dark:bg-gray-700 rounded-lg flex items-center justify-center">
|
||||
<span class="text-gray-400 dark:text-gray-500 text-xs">Sin imagen</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Información del artículo -->
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex items-start justify-between mb-2">
|
||||
<div class="flex-1 min-w-0">
|
||||
<div class="flex flex-wrap items-center gap-2 mb-2">
|
||||
<span
|
||||
class="px-2 py-1 text-xs font-semibold rounded flex-shrink-0"
|
||||
:class="
|
||||
article.platform === 'wallapop'
|
||||
? 'bg-blue-100 text-blue-800'
|
||||
: 'bg-green-100 text-green-800'
|
||||
"
|
||||
>
|
||||
{{ article.platform?.toUpperCase() || 'N/A' }}
|
||||
</span>
|
||||
<span class="text-xs sm:text-sm text-gray-500 dark:text-gray-400">
|
||||
{{ formatDate(article.notifiedAt) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<h3 class="text-base sm:text-lg font-semibold text-gray-900 dark:text-gray-100 mb-1 line-clamp-2" :title="article.title">
|
||||
{{ article.title || 'Sin título' }}
|
||||
</h3>
|
||||
|
||||
<div v-if="article.price !== null && article.price !== undefined" class="mb-2">
|
||||
<span class="text-xl font-bold text-primary-600">
|
||||
{{ article.price }} {{ article.currency || '€' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1 text-xs sm:text-sm text-gray-600 dark:text-gray-400 mb-2">
|
||||
<div v-if="article.location" class="flex flex-wrap items-center">
|
||||
<span class="font-medium">📍 Localidad:</span>
|
||||
<span class="ml-2">{{ article.location }}</span>
|
||||
</div>
|
||||
<div v-if="article.allows_shipping !== null" class="flex flex-wrap items-center">
|
||||
<span class="font-medium">🚚 Envío:</span>
|
||||
<span class="ml-2">{{ article.allows_shipping ? '✅ Acepta envíos' : '❌ No acepta envíos' }}</span>
|
||||
</div>
|
||||
<div v-if="article.modified_at" class="flex flex-wrap items-center">
|
||||
<span class="font-medium">🕒 Modificado:</span>
|
||||
<span class="ml-2 break-all">{{ article.modified_at }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p v-if="article.description" class="text-xs sm:text-sm text-gray-700 dark:text-gray-300 mb-2 overflow-hidden line-clamp-2">
|
||||
{{ article.description }}
|
||||
</p>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2 sm:gap-4 mt-3">
|
||||
<a
|
||||
v-if="article.url"
|
||||
:href="article.url"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="text-primary-600 hover:text-primary-700 text-xs sm:text-sm font-medium break-all"
|
||||
>
|
||||
🔗 Ver anuncio
|
||||
</a>
|
||||
<span class="text-xs text-gray-400 dark:text-gray-500 break-all">
|
||||
ID: {{ article.id }}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
:article="article"
|
||||
/>
|
||||
|
||||
<div v-if="!searchQuery" class="flex justify-center space-x-2 mt-6">
|
||||
<button
|
||||
@@ -161,7 +115,7 @@
|
||||
|
||||
<p class="text-center text-xs sm:text-sm text-gray-500 mt-4 px-2">
|
||||
<span v-if="searchQuery">
|
||||
Mostrando {{ filteredArticles.length }} resultados de búsqueda en Redis
|
||||
Mostrando {{ filteredArticles.length }} resultados de búsqueda
|
||||
<span class="block sm:inline sm:ml-2 text-xs text-primary-600">(de {{ total }} artículos totales)</span>
|
||||
</span>
|
||||
<span v-else>
|
||||
@@ -176,6 +130,11 @@
|
||||
<script setup>
|
||||
import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
|
||||
import api from '../services/api';
|
||||
import authService from '../services/auth';
|
||||
import ArticleCard from '../components/ArticleCard.vue';
|
||||
|
||||
const currentUser = ref(authService.getUsername() || null);
|
||||
const isAdmin = ref(false);
|
||||
|
||||
const allArticles = ref([]);
|
||||
const searchResults = ref([]);
|
||||
@@ -185,12 +144,45 @@ const total = ref(0);
|
||||
const offset = ref(0);
|
||||
const limit = 50;
|
||||
const selectedPlatform = ref('');
|
||||
const selectedUsername = ref('');
|
||||
const selectedWorker = ref('');
|
||||
const searchQuery = ref('');
|
||||
const autoPollInterval = ref(null);
|
||||
const searchTimeout = ref(null);
|
||||
const POLL_INTERVAL = 30000; // 30 segundos
|
||||
const SEARCH_DEBOUNCE = 500; // 500ms de debounce para búsqueda
|
||||
|
||||
// Obtener listas de usuarios y workers únicos de los artículos
|
||||
const availableUsernames = computed(() => {
|
||||
const usernames = new Set();
|
||||
allArticles.value.forEach(article => {
|
||||
if (article.username) {
|
||||
usernames.add(article.username);
|
||||
}
|
||||
});
|
||||
searchResults.value.forEach(article => {
|
||||
if (article.username) {
|
||||
usernames.add(article.username);
|
||||
}
|
||||
});
|
||||
return Array.from(usernames).sort();
|
||||
});
|
||||
|
||||
const availableWorkers = computed(() => {
|
||||
const workers = new Set();
|
||||
allArticles.value.forEach(article => {
|
||||
if (article.worker_name) {
|
||||
workers.add(article.worker_name);
|
||||
}
|
||||
});
|
||||
searchResults.value.forEach(article => {
|
||||
if (article.worker_name) {
|
||||
workers.add(article.worker_name);
|
||||
}
|
||||
});
|
||||
return Array.from(workers).sort();
|
||||
});
|
||||
|
||||
// Artículos que se muestran (búsqueda o lista normal)
|
||||
const filteredArticles = computed(() => {
|
||||
if (searchQuery.value.trim()) {
|
||||
@@ -199,9 +191,14 @@ const filteredArticles = computed(() => {
|
||||
return allArticles.value;
|
||||
});
|
||||
|
||||
function formatDate(timestamp) {
|
||||
if (!timestamp) return 'N/A';
|
||||
return new Date(timestamp).toLocaleString('es-ES');
|
||||
|
||||
function checkUserRole() {
|
||||
currentUser.value = authService.getUsername() || null;
|
||||
isAdmin.value = currentUser.value === 'admin'; // Simplificación temporal
|
||||
// Si no es admin, no permitir filtrar por username
|
||||
if (!isAdmin.value && selectedUsername.value) {
|
||||
selectedUsername.value = '';
|
||||
}
|
||||
}
|
||||
|
||||
async function loadArticles(reset = true, silent = false) {
|
||||
@@ -215,9 +212,19 @@ async function loadArticles(reset = true, silent = false) {
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await api.getArticles(limit, offset.value);
|
||||
// Construir query params para filtros
|
||||
const params = { limit, offset: offset.value };
|
||||
if (selectedPlatform.value) params.platform = selectedPlatform.value;
|
||||
// Solo permitir filtrar por username si es admin
|
||||
if (selectedUsername.value && isAdmin.value) {
|
||||
params.username = selectedUsername.value;
|
||||
}
|
||||
if (selectedWorker.value) params.worker_name = selectedWorker.value;
|
||||
|
||||
const data = await api.getArticles(limit, offset.value, params);
|
||||
|
||||
let filtered = data.articles;
|
||||
// El filtro de plataforma se aplica en el backend ahora, pero mantenemos compatibilidad
|
||||
if (selectedPlatform.value) {
|
||||
filtered = filtered.filter(a => a.platform === selectedPlatform.value);
|
||||
}
|
||||
@@ -240,17 +247,82 @@ async function loadArticles(reset = true, silent = false) {
|
||||
}
|
||||
}
|
||||
|
||||
function handleAuthChange() {
|
||||
checkUserRole();
|
||||
if (currentUser.value) {
|
||||
loadArticles();
|
||||
}
|
||||
}
|
||||
|
||||
function loadMore() {
|
||||
loadArticles(false);
|
||||
}
|
||||
|
||||
function handleWSMessage(event) {
|
||||
const data = event.detail;
|
||||
if (data.type === 'articles_updated') {
|
||||
if (data.type === 'articles_updated' || data.type === 'articles_cleared' || data.type === 'cache_cleared') {
|
||||
loadArticles();
|
||||
}
|
||||
}
|
||||
|
||||
async function handleClearAllArticles() {
|
||||
if (!isAdmin.value) {
|
||||
alert('Solo los administradores pueden borrar todos los artículos');
|
||||
return;
|
||||
}
|
||||
|
||||
const confirmed = confirm(
|
||||
'⚠️ ¿Estás seguro de que quieres borrar TODOS los artículos?\n\n' +
|
||||
'Esta acción eliminará permanentemente todos los artículos de la base de datos.\n' +
|
||||
'Esta acción NO se puede deshacer.\n\n' +
|
||||
'¿Continuar?'
|
||||
);
|
||||
|
||||
if (!confirmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Confirmación adicional
|
||||
const doubleConfirmed = confirm(
|
||||
'⚠️ ÚLTIMA CONFIRMACIÓN ⚠️\n\n' +
|
||||
'Estás a punto de borrar TODOS los artículos de la base de datos.\n' +
|
||||
'Esta acción es IRREVERSIBLE.\n\n' +
|
||||
'¿Estás absolutamente seguro?'
|
||||
);
|
||||
|
||||
if (!doubleConfirmed) {
|
||||
return;
|
||||
}
|
||||
|
||||
loading.value = true;
|
||||
|
||||
try {
|
||||
const result = await api.clearAllArticles();
|
||||
alert(`✅ ${result.message || `Se borraron ${result.count || 0} artículos`}`);
|
||||
|
||||
// Limpiar la vista
|
||||
allArticles.value = [];
|
||||
searchResults.value = [];
|
||||
total.value = 0;
|
||||
offset.value = 0;
|
||||
|
||||
// Recargar artículos (ahora estará vacío)
|
||||
await loadArticles();
|
||||
} catch (error) {
|
||||
console.error('Error borrando artículos:', error);
|
||||
|
||||
if (error.response?.status === 403) {
|
||||
alert('❌ Error: No tienes permisos de administrador para realizar esta acción');
|
||||
} else if (error.response?.status === 401) {
|
||||
alert('❌ Error: Debes estar autenticado para realizar esta acción');
|
||||
} else {
|
||||
alert('❌ Error al borrar artículos: ' + (error.response?.data?.error || error.message || 'Error desconocido'));
|
||||
}
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function searchArticles(query) {
|
||||
if (!query.trim()) {
|
||||
searchResults.value = [];
|
||||
@@ -265,10 +337,16 @@ async function searchArticles(query) {
|
||||
|
||||
let filtered = data.articles || [];
|
||||
|
||||
// Aplicar filtro de plataforma si está seleccionado
|
||||
// Aplicar filtros si están seleccionados
|
||||
if (selectedPlatform.value) {
|
||||
filtered = filtered.filter(a => a.platform === selectedPlatform.value);
|
||||
}
|
||||
if (selectedUsername.value) {
|
||||
filtered = filtered.filter(a => a.username === selectedUsername.value);
|
||||
}
|
||||
if (selectedWorker.value) {
|
||||
filtered = filtered.filter(a => a.worker_name === selectedWorker.value);
|
||||
}
|
||||
|
||||
searchResults.value = filtered;
|
||||
} catch (error) {
|
||||
@@ -298,15 +376,13 @@ watch(searchQuery, (newQuery) => {
|
||||
}, SEARCH_DEBOUNCE);
|
||||
});
|
||||
|
||||
function handleImageError(event) {
|
||||
// Si la imagen falla al cargar, reemplazar con placeholder
|
||||
event.target.onerror = null; // Prevenir bucle infinito
|
||||
event.target.src = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTI4IiBoZWlnaHQ9IjEyOCIgdmlld0JveD0iMCAwIDEyOCAxMjgiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIxMjgiIGhlaWdodD0iMTI4IiBmaWxsPSIjRjNGNEY2Ii8+CjxwYXRoIGQ9Ik00OCA0OEg4ME04MCA4MEg0OE00OCA0OEw2NCA2NEw4MCA0OE00OCA4MEw2NCA2NE04MCA4MEw2NCA2NEw0OCA4MCIgc3Ryb2tlPSIjOUI5Q0E0IiBzdHJva2Utd2lkdGg9IjIiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLWxpbmVqb2luPSJyb3VuZCIvPgo8L3N2Zz4K';
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
checkUserRole();
|
||||
loadArticles();
|
||||
window.addEventListener('ws-message', handleWSMessage);
|
||||
window.addEventListener('auth-logout', handleAuthChange);
|
||||
window.addEventListener('auth-login', handleAuthChange);
|
||||
|
||||
// Iniciar autopoll para actualizar automáticamente
|
||||
autoPollInterval.value = setInterval(() => {
|
||||
@@ -316,6 +392,8 @@ onMounted(() => {
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('ws-message', handleWSMessage);
|
||||
window.removeEventListener('auth-logout', handleAuthChange);
|
||||
window.removeEventListener('auth-login', handleAuthChange);
|
||||
|
||||
// Limpiar el intervalo cuando el componente se desmonte
|
||||
if (autoPollInterval.value) {
|
||||
|
||||
Reference in New Issue
Block a user