Mes Annonces
0Chargement de vos annonces...
Chargement de vos annonces...
// Configuration const CONFIG = { API_URL: (() => { if (window.location.protocol === 'file:') return 'https://warapservices.com/api/api.php'; return 'api/api.php'; })() }; // State let userListings = []; let filteredListings = []; let currentUser = null; // Category labels const categoryLabels = { product: 'Produit', service: 'Service', immo: 'Immobilier', education: 'Formation', event: 'Événement' }; // Initialize document.addEventListener('DOMContentLoaded', async () => { // Check authentication const userStr = localStorage.getItem('warap_user'); try { currentUser = userStr ? JSON.parse(userStr) : null; } catch (e) { currentUser = null; } if (!currentUser || !currentUser.user_id) { // Redirect to login showAuthRequired(); return; } // Load listings await loadUserListings(); }); // Show auth required function showAuthRequired() { document.getElementById('listingsContent').innerHTML = `
`; } // Load user listings async function loadUserListings() { try { const response = await fetch(`${CONFIG.API_URL}?action=getUserListings&userId=${currentUser.user_id}`); const data = await response.json(); if (data.success && Array.isArray(data.listings)) { userListings = data.listings; updateStats(); applyFilters(); } else { showEmptyState(); } } catch (error) { console.error('Error loading listings:', error); showError(); } } // Update stats function updateStats() { const active = userListings.filter(l => l.status === 'ACTIVE').length; const pending = userListings.filter(l => l.status === 'PENDING').length; const totalViews = userListings.reduce((sum, l) => sum + (parseInt(l.views) || 0), 0); document.getElementById('totalCount').textContent = userListings.length; document.getElementById('activeCount').textContent = active; document.getElementById('pendingCount').textContent = pending; document.getElementById('totalViews').textContent = totalViews; document.getElementById('allCount').textContent = userListings.length; } // Apply filters function applyFilters() { const status = document.getElementById('filterStatus').value; const category = document.getElementById('filterCategory').value; const search = document.getElementById('filterSearch').value.toLowerCase(); filteredListings = userListings.filter(listing => { const matchStatus = !status || listing.status === status; const matchCategory = !category || listing.category === category; const matchSearch = !search || (listing.title && listing.title.toLowerCase().includes(search)) || (listing.description && listing.description.toLowerCase().includes(search)); return matchStatus && matchCategory && matchSearch; }); renderListings(); } // Render listings function renderListings() { if (filteredListings.length === 0) { showEmptyState(); return; } let html = `
| Annonce | Prix | Statut | Vues | Date | Actions |
|---|---|---|---|---|---|
|
${image}
${escapeHtml(listing.title)}${category} |
${price} | ${statusLabel} | ${listing.views || 0} | ${date} |
|
'; document.getElementById('listingsContent').innerHTML = html; } // Show empty state function showEmptyState() { document.getElementById('listingsContent').innerHTML = `
Vous n'avez pas encore publié d'annonces. Commencez à vendre dès maintenant !
Créer une annonce`; } // Show error function showError() { document.getElementById('listingsContent').innerHTML = `
Impossible de charger vos annonces. Veuillez réessayer.
`; } // Refresh listings function refreshListings() { document.getElementById('listingsContent').innerHTML = `
Actualisation...
`; loadUserListings(); } // Toggle actions menu function toggleActionsMenu(dropdown, event) { event.stopPropagation(); // Close all other menus document.querySelectorAll('.actions-dropdown.open').forEach(d => { if (d !== dropdown) d.classList.remove('open'); }); dropdown.classList.toggle('open'); } // Close menus on click outside document.addEventListener('click', () => { document.querySelectorAll('.actions-dropdown.open').forEach(d => { d.classList.remove('open'); }); }); // Toggle listing status async function toggleListingStatus(id, currentStatus) { const newStatus = currentStatus === 'ACTIVE' ? 'INACTIVE' : 'ACTIVE'; try { const response = await fetch(CONFIG.API_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'updateListing', listing_id: id, status: newStatus }) }); const data = await response.json(); if (data.success) { // Update local data const listing = userListings.find(l => (l.listing_id || l.id) === id); if (listing) listing.status = newStatus; updateStats(); applyFilters(); alert(`Annonce ${newStatus === 'ACTIVE' ? 'activée' : 'désactivée'} avec succès`); } else { alert('Erreur: ' + (data.error || 'Impossible de modifier le statut')); } } catch (error) { console.error('Error:', error); alert('Erreur de connexion'); } } // Delete listing async function deleteListing(id) { if (!confirm('Êtes-vous sûr de vouloir supprimer cette annonce ? Cette action est irréversible.')) { return; } try { const response = await fetch(CONFIG.API_URL, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'deleteListing', listing_id: id }) }); const data = await response.json(); if (data.success) { // Remove from local data userListings = userListings.filter(l => (l.listing_id || l.id) !== id); updateStats(); applyFilters(); alert('Annonce supprimée avec succès'); } else { alert('Erreur: ' + (data.error || 'Impossible de supprimer')); } } catch (error) { console.error('Error:', error); alert('Erreur de connexion'); } } // Utility functions function formatPrice(price) { return new Intl.NumberFormat('fr-FR').format(price) + ' FCFA'; } function formatDate(dateStr) { if (!dateStr) return '-'; const date = new Date(dateStr); return date.toLocaleDateString('fr-FR', { day: 'numeric', month: 'short', year: 'numeric' }); } function escapeHtml(text) { if (!text) return ''; const div = document.createElement('div'); div.textContent = text; return div.innerHTML; } // Handle account click function handleAccountNavClick(event) { event.preventDefault(); const userStr = localStorage.getItem('warap_user'); let user = null; try { user = userStr ? JSON.parse(userStr) : null; } catch (e) { user = null; } if (user && user.user_id) { window.location.href = 'dashboard.html'; } else { if (typeof showAuthModal === 'function') { showAuthModal(); } else if (typeof toggleSidebar === 'function') { toggleSidebar(); } } } // Open login modal function openLoginModal() { if (typeof showAuthModal === 'function') { showAuthModal(); } else if (typeof toggleSidebar === 'function') { toggleSidebar(); } }