Actualiser js/admin.js

This commit is contained in:
2026-06-21 14:18:09 +02:00
parent 93061a268b
commit d96938eff6
+124 -186
View File
@@ -5,13 +5,14 @@ let currentPage = 1;
const itemsPerPage = 12; const itemsPerPage = 12;
let selectedIds = new Set(); let selectedIds = new Set();
let pendingDeleteAction = null; let pendingDeleteAction = null;
let adminPhysicalOnlyFilter = false; let physicalOnlyFilter = false;
// ─ UTILITAIRES DOM SÉCURISÉS (Anti-Crash) ── // ─ UTILITAIRES DOM SÉCURISÉS ──
function safeGetValue(id, defaultValue = '') { function safeGetValue(id, defaultValue = '') {
const el = document.getElementById(id); const el = document.getElementById(id);
return el ? el.value : defaultValue; return el ? el.value : defaultValue;
} }
function safeSetValue(id, value) { function safeSetValue(id, value) {
const el = document.getElementById(id); const el = document.getElementById(id);
if (el) el.value = value; if (el) el.value = value;
@@ -66,6 +67,24 @@ function parseCSV(text) {
return data; return data;
} }
// ── BARRE DE PROGRESSION ──
function showProgressModal(total) {
document.getElementById('progress-text').textContent = 'Traitement des films et récupération TMDB...';
document.getElementById('progress-bar').style.width = '0%';
document.getElementById('progress-count').textContent = `0 / ${total}`;
document.getElementById('progress-overlay').classList.add('open');
}
function updateProgressModal(current, total) {
const pct = Math.round((current / total) * 100);
document.getElementById('progress-bar').style.width = pct + '%';
document.getElementById('progress-count').textContent = `${current} / ${total}`;
}
function closeProgressModal() {
document.getElementById('progress-overlay').classList.remove('open');
}
// ── INITIALISATION ── // ── INITIALISATION ──
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
loadDashboardData(); loadDashboardData();
@@ -80,14 +99,6 @@ document.addEventListener('DOMContentLoaded', () => {
}); });
function initEventListeners() { function initEventListeners() {
const physicalCheckbox = document.getElementById('admin-physical-checkbox');
if (physicalCheckbox) {
physicalCheckbox.addEventListener('change', (e) => {
adminPhysicalOnlyFilter = e.target.checked;
currentPage = 1;
renderAdminTable();
});
}
const filmForm = document.getElementById('film-form'); const filmForm = document.getElementById('film-form');
if (filmForm) filmForm.addEventListener('submit', saveFilmForm); if (filmForm) filmForm.addEventListener('submit', saveFilmForm);
@@ -107,6 +118,16 @@ function initEventListeners() {
selectAll.addEventListener('change', (e) => toggleSelectAll(e.target)); selectAll.addEventListener('change', (e) => toggleSelectAll(e.target));
} }
// Filtre support physique
const physicalCheckbox = document.getElementById('admin-physical-checkbox');
if (physicalCheckbox) {
physicalCheckbox.addEventListener('change', (e) => {
physicalOnlyFilter = e.target.checked;
currentPage = 1;
renderAdminTable();
});
}
document.addEventListener('click', (e) => { document.addEventListener('click', (e) => {
if (e.target.classList.contains('modal-close') || e.target.closest('.modal-close')) { if (e.target.classList.contains('modal-close') || e.target.closest('.modal-close')) {
const overlay = e.target.closest('.overlay'); const overlay = e.target.closest('.overlay');
@@ -118,7 +139,7 @@ function initEventListeners() {
}); });
} }
// ── CHARGEMENT ── // ── CHARGEMENT DES DONNÉES ──
async function loadDashboardData() { async function loadDashboardData() {
try { try {
const res = await fetch(`${API_URL}?action=get_films`, { cache: 'no-store' }); const res = await fetch(`${API_URL}?action=get_films`, { cache: 'no-store' });
@@ -131,149 +152,88 @@ async function loadDashboardData() {
} catch (err) { console.error('Erreur chargement :', err); } } catch (err) { console.error('Erreur chargement :', err); }
} }
// ── FILTRES (Répare le bug de la recherche combinée) ── // ── RENDU DU TABLEAU ──
function getFilteredItems() {
const searchInput = document.getElementById('search-input');
const currentSearch = searchInput ? searchInput.value.toLowerCase() : '';
let filtered = allItems.filter(item => item.type === currentAdminTab);
if (currentSearch) {
filtered = filtered.filter(f =>
(f.title && f.title.toLowerCase().includes(currentSearch)) ||
(f.director && f.director.toLowerCase().includes(currentSearch))
);
}
return filtered;
}
// ── RENDU DU TABLEAU (VERSION COMPLÈTE ET CORRIGÉE) ──
function renderAdminTable() { function renderAdminTable() {
const tbody = document.getElementById('admin-table-body'); const tbody = document.getElementById('admin-table-body');
if (!tbody) return; if (!tbody) return;
tbody.innerHTML = ''; tbody.innerHTML = '';
// 1. Récupération des valeurs de filtrage
const searchInput = document.getElementById('search-input'); const searchInput = document.getElementById('search-input');
const query = searchInput ? searchInput.value.toLowerCase().trim() : ''; const currentSearch = searchInput ? searchInput.value.toLowerCase() : '';
const physicalCheckbox = document.getElementById('admin-physical-checkbox');
const isPhysicalOnly = physicalCheckbox ? physicalCheckbox.checked : false;
// 2. Filtrage des données
let filtered = allItems.filter(item => item.type === currentAdminTab); let filtered = allItems.filter(item => item.type === currentAdminTab);
// Filtre support physique / cinéma uniquement // Filtre support physique / cinéma uniquement
if (isPhysicalOnly) { if (physicalOnlyFilter) {
filtered = filtered.filter(item => { filtered = filtered.filter(f => {
const streaming = item.streaming ? item.streaming.trim() : ''; const streaming = f.streaming ? f.streaming.trim() : '';
return !streaming || streaming === 'Disponible en support physique ou Cinéma'; return !streaming || streaming === 'Disponible en support physique ou Cinéma';
}); });
} }
// Filtre recherche // Filtre recherche
if (query) { if (currentSearch) {
filtered = filtered.filter(item => filtered = filtered.filter(f =>
item.title.toLowerCase().includes(query) || f.title.toLowerCase().includes(currentSearch) ||
(item.director && item.director.toLowerCase().includes(query)) (f.director && f.director.toLowerCase().includes(currentSearch))
); );
} }
// 3. Mise à jour du compteur
const countLabel = document.getElementById('admin-count-label'); const countLabel = document.getElementById('admin-count-label');
if (countLabel) countLabel.textContent = `${filtered.length} élément(s)`; if (countLabel) countLabel.textContent = `${filtered.length} élément(s)`;
// 4. Logique de pagination // Pagination
const totalPages = Math.ceil(filtered.length / itemsPerPage) || 1; const totalPages = Math.ceil(filtered.length / itemsPerPage) || 1;
if (currentPage > totalPages) currentPage = totalPages; if (currentPage > totalPages) currentPage = totalPages;
const startIndex = (currentPage - 1) * itemsPerPage; const startIdx = (currentPage - 1) * itemsPerPage;
const pageItems = filtered.slice(startIndex, startIndex + itemsPerPage); const pageItems = filtered.slice(startIdx, startIdx + itemsPerPage);
// 5. Génération des lignes (6 colonnes : Checkbox, Titre, Année, Réalisateur, Info, Actions) pageItems.forEach(f => {
pageItems.forEach(item => {
const tr = document.createElement('tr'); const tr = document.createElement('tr');
const isChecked = selectedIds.has(String(item.id)) ? 'checked' : ''; const isChecked = selectedIds.has(String(f.id)) ? 'checked' : '';
const infoHTML = currentAdminTab === 'critique'
? `<span class="tbl-stars">${getStarsHTML(item.rating)}</span>`
: `<span class="badge-format">${item.format || '-'}</span>`;
tr.innerHTML = ` tr.innerHTML = `
<td style="text-align:center;"> <td style="text-align:center;">
<input type="checkbox" class="film-checkbox" value="${item.id}" ${isChecked} onclick="handleFilmCheckbox(this)"> <input type="checkbox" class="film-checkbox" value="${f.id}" ${isChecked} onclick="toggleSingleSelect('${f.id}', this)">
</td> </td>
<td><strong>${item.title}</strong></td> <td style="text-align:center;">
<td>${item.year || '-'}</td> ${f.poster ? `<img src="${f.poster}" class="thumb" alt="Affiche">` : '<div class="thumb-ph"><i class="ti ti-photo"></i></div>'}
<td>${item.director || '-'}</td> </td>
<td>${infoHTML}</td> <td><strong>${f.title}</strong></td>
<td style="text-align:right;"> <td>${f.year || '-'}</td>
<td>${f.director || '-'}</td>
<td>${currentAdminTab === 'critique' ? `<span class="tbl-stars">${getStarsHTML(f.rating)}</span>` : `<span class="badge-format">${f.format || '-'}</span>`}</td>
<td>
<div class="tbl-actions"> <div class="tbl-actions">
<button onclick="openEditModal('${item.id}')" title="Éditer"><i class="ti ti-edit"></i></button> <button onclick="openEditModal('${f.id}')" title="Éditer"><i class="ti ti-edit"></i></button>
<button class="del" onclick="deleteSingleFilm('${item.id}')" title="Supprimer"><i class="ti ti-trash"></i></button> <button class="del" onclick="deleteSingleFilm('${f.id}')" title="Supprimer"><i class="ti ti-trash"></i></button>
</div> </div>
</td> </td>`;
`;
tbody.appendChild(tr); tbody.appendChild(tr);
}); });
// 6. Rendu de la pagination
renderPagination(totalPages, filtered.length); renderPagination(totalPages, filtered.length);
// 7. Synchronisation de la case "Tout sélectionner"
syncSelectAllCheckbox();
}
// ── GESTION DES CHECKBOXES INDIVIDUELLES ─
function handleFilmCheckbox(checkbox) {
const id = checkbox.value;
if (checkbox.checked) {
selectedIds.add(id);
} else {
selectedIds.delete(id);
}
updateBulkBar();
syncSelectAllCheckbox();
}
// ─ SYNCHRONISATION DU "TOUT SÉLECTIONNER" ──
function syncSelectAllCheckbox() {
const selectAll = document.getElementById('select-all-checkbox');
if (!selectAll) return;
const visibleCheckboxes = document.querySelectorAll('#admin-table-body .film-checkbox');
const allChecked = visibleCheckboxes.length > 0 && Array.from(visibleCheckboxes).every(cb => cb.checked);
selectAll.checked = allChecked;
}
// ── BARRE D'ACTIONS GROUPÉES ──
function updateBulkBar() {
const bulkBar = document.getElementById('bulk-actions-bar');
const bulkCount = document.getElementById('bulk-count');
if (!bulkBar || !bulkCount) return;
if (selectedIds.size > 0) {
bulkBar.style.display = 'flex';
bulkCount.textContent = selectedIds.size;
} else {
bulkBar.style.display = 'none';
}
}
// ── SÉLECTION & BULK ──
function toggleSingleSelect(id, checkbox) {
if (checkbox.checked) selectedIds.add(String(id));
else selectedIds.delete(String(id));
updateBulkBar();
const pageItems = getFilteredItems().slice((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage);
const selectAll = document.getElementById('select-all-checkbox'); const selectAll = document.getElementById('select-all-checkbox');
if (selectAll) { if (selectAll) {
selectAll.checked = pageItems.length > 0 && pageItems.every(f => selectedIds.has(String(f.id))); selectAll.checked = pageItems.length > 0 && pageItems.every(f => selectedIds.has(String(f.id)));
} }
} }
// ── SÉLECTION ──
function toggleSingleSelect(id, checkbox) {
if (checkbox.checked) selectedIds.add(String(id));
else selectedIds.delete(String(id));
updateBulkBar();
const filtered = allItems.filter(item => item.type === currentAdminTab);
const selectAll = document.getElementById('select-all-checkbox');
if (selectAll) {
selectAll.checked = filtered.length > 0 && filtered.every(f => selectedIds.has(String(f.id)));
}
}
function toggleSelectAll(source) { function toggleSelectAll(source) {
const filtered = getFilteredItems(); const filtered = allItems.filter(item => item.type === currentAdminTab);
if (source.checked) { if (source.checked) {
filtered.forEach(f => selectedIds.add(String(f.id))); filtered.forEach(f => selectedIds.add(String(f.id)));
} else { } else {
@@ -293,8 +253,6 @@ function updateBulkBar() {
if (bulkCount) bulkCount.textContent = selectedIds.size; if (bulkCount) bulkCount.textContent = selectedIds.size;
} else { } else {
if (bulkBar) bulkBar.style.display = 'none'; if (bulkBar) bulkBar.style.display = 'none';
const selectAll = document.getElementById('select-all-checkbox');
if (selectAll) selectAll.checked = false;
} }
} }
@@ -368,6 +326,7 @@ function showConfirmModal(actionFn) {
const modal = document.getElementById('confirm-modal'); const modal = document.getElementById('confirm-modal');
if (modal) modal.classList.add('open'); if (modal) modal.classList.add('open');
} }
function closeConfirmModal() { function closeConfirmModal() {
const modal = document.getElementById('confirm-modal'); const modal = document.getElementById('confirm-modal');
if (modal) modal.classList.remove('open'); if (modal) modal.classList.remove('open');
@@ -387,7 +346,9 @@ async function executeBulkDelete() {
}); });
if (!res.ok) throw new Error("Erreur serveur."); if (!res.ok) throw new Error("Erreur serveur.");
selectedIds.clear(); selectedIds.clear();
updateBulkBar(); document.getElementById('bulk-actions-bar').style.display = 'none';
const selectAll = document.getElementById('select-all-checkbox');
if (selectAll) selectAll.checked = false;
loadDashboardData(); loadDashboardData();
} catch (err) { } catch (err) {
console.error('Erreur bulk delete :', err); console.error('Erreur bulk delete :', err);
@@ -404,8 +365,6 @@ async function deleteSingleFilm(id) {
headers: { 'Authorization': localStorage.getItem('token') } headers: { 'Authorization': localStorage.getItem('token') }
}); });
if (!res.ok) throw new Error("Erreur serveur."); if (!res.ok) throw new Error("Erreur serveur.");
selectedIds.delete(String(id));
updateBulkBar();
loadDashboardData(); loadDashboardData();
} catch (err) { } catch (err) {
console.error('Erreur delete :', err); console.error('Erreur delete :', err);
@@ -428,54 +387,43 @@ function switchAdminTab(tabName) {
selectedIds.clear(); selectedIds.clear();
const searchInput = document.getElementById('search-input'); const searchInput = document.getElementById('search-input');
if (searchInput) searchInput.value = ''; if (searchInput) searchInput.value = '';
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
const btn = document.getElementById(`btn-tab-${tabName}`); const btn = document.getElementById(`btn-tab-${tabName}`);
if (btn) btn.classList.add('active'); if (btn) btn.classList.add('active');
toggleFormFields(); toggleFormFields();
updateBulkBar();
renderAdminTable(); renderAdminTable();
} }
function openAddModal() { function openAddModal() {
const form = document.getElementById('film-form'); document.getElementById('film-form').reset();
if (form) form.reset(); document.getElementById('f-id').value = '';
safeSetValue('f-id', '');
toggleFormFields(); toggleFormFields();
const modal = document.getElementById('admin-modal'); document.getElementById('admin-modal').classList.add('open');
if (modal) modal.classList.add('open');
} }
function openEditModal(id) { function openEditModal(id) {
const item = allItems.find(x => String(x.id) === String(id)); const item = allItems.find(x => String(x.id) === String(id));
if (!item) return; if (!item) return;
document.getElementById('f-id').value = item.id;
safeSetValue('f-id', item.id); document.getElementById('f-title').value = item.title;
safeSetValue('f-title', item.title); document.getElementById('f-year').value = item.year || '';
safeSetValue('f-year', item.year); document.getElementById('f-director').value = item.director || '';
safeSetValue('f-director', item.director); document.getElementById('f-poster').value = item.poster || '';
safeSetValue('f-poster', item.poster); toggleFormFields();
if (currentAdminTab === 'critique') { if (currentAdminTab === 'critique') {
// Remplacez la ligne existante par celle-ci : document.getElementById('f-rating').value = item.rating || 3;
document.getElementById('f-rating').value = parseFloat(item.rating || 3);
document.getElementById('f-review').value = item.review || ''; document.getElementById('f-review').value = item.review || '';
document.getElementById('f-streaming').value = item.streaming || ''; document.getElementById('f-streaming').value = item.streaming || '';
} else { } else {
safeSetValue('f-format', item.format); document.getElementById('f-format').value = item.format || '';
safeSetValue('f-length', item.length); document.getElementById('f-length').value = item.length || '';
safeSetValue('f-publisher', item.publisher); document.getElementById('f-publisher').value = item.publisher || '';
safeSetValue('f-aspect', item.aspect_ratio); document.getElementById('f-aspect').value = item.aspect_ratio || '';
safeSetValue('f-ean', item.ean_isbn13); document.getElementById('f-ean').value = item.ean_isbn13 || '';
safeSetValue('f-discs', item.number_of_discs || 1); document.getElementById('f-discs').value = item.number_of_discs || 1;
safeSetValue('f-description', item.description); document.getElementById('f-description').value = item.description || '';
} }
toggleFormFields(); document.getElementById('admin-modal').classList.add('open');
const modal = document.getElementById('admin-modal');
if (modal) modal.classList.add('open');
} }
function closeAdminModal() { document.getElementById('admin-modal').classList.remove('open'); } function closeAdminModal() { document.getElementById('admin-modal').classList.remove('open'); }
@@ -491,42 +439,26 @@ function logout() {
window.location.href = 'login.html'; window.location.href = 'login.html';
} }
// ── PROGRESS BAR ──
function showProgressModal(total) {
document.getElementById('progress-text').textContent = 'Traitement des films...';
document.getElementById('progress-bar').style.width = '0%';
document.getElementById('progress-count').textContent = `0 / ${total}`;
document.getElementById('progress-overlay').classList.add('open');
}
function updateProgressModal(current, total) {
const pct = Math.round((current / total) * 100);
document.getElementById('progress-bar').style.width = pct + '%';
document.getElementById('progress-count').textContent = `${current} / ${total}`;
}
function closeProgressModal() {
document.getElementById('progress-overlay').classList.remove('open');
}
// ── SAUVEGARDE FILM ── // ── SAUVEGARDE FILM ──
async function saveFilmForm(e) { async function saveFilmForm(e) {
e.preventDefault(); e.preventDefault();
const payload = { const payload = {
type: currentAdminTab, type: currentAdminTab,
id: safeGetValue('f-id'), id: document.getElementById('f-id').value,
title: safeGetValue('f-title'), title: document.getElementById('f-title').value,
year: safeGetValue('f-year'), year: document.getElementById('f-year').value,
director: safeGetValue('f-director'), director: document.getElementById('f-director').value,
poster: safeGetValue('f-poster'), poster: document.getElementById('f-poster').value,
rating: safeGetValue('f-rating', 3), rating: document.getElementById('f-rating') ? document.getElementById('f-rating').value : '',
review: safeGetValue('f-review'), review: document.getElementById('f-review') ? document.getElementById('f-review').value : '',
streaming: safeGetValue('f-streaming'), streaming: document.getElementById('f-streaming') ? document.getElementById('f-streaming').value : '',
format: safeGetValue('f-format'), format: document.getElementById('f-format') ? document.getElementById('f-format').value : '',
length: safeGetValue('f-length'), length: document.getElementById('f-length') ? document.getElementById('f-length').value : '',
publisher: safeGetValue('f-publisher'), publisher: document.getElementById('f-publisher') ? document.getElementById('f-publisher').value : '',
aspect_ratio: safeGetValue('f-aspect'), aspect_ratio: document.getElementById('f-aspect') ? document.getElementById('f-aspect').value : '',
ean_isbn13: safeGetValue('f-ean'), ean_isbn13: document.getElementById('f-ean') ? document.getElementById('f-ean').value : '',
number_of_discs: safeGetValue('f-discs', 1), number_of_discs: document.getElementById('f-discs') ? document.getElementById('f-discs').value : 1,
description: safeGetValue('f-description') description: document.getElementById('f-description') ? document.getElementById('f-description').value : ''
}; };
try { try {
await fetch(`${API_URL}?action=save_film`, { await fetch(`${API_URL}?action=save_film`, {
@@ -539,12 +471,11 @@ async function saveFilmForm(e) {
} catch (err) { console.error('Erreur sauvegarde :', err); } } catch (err) { console.error('Erreur sauvegarde :', err); }
} }
// ─ IMPORT CSV ── // ─ IMPORT CSV PAR LOTS ──
async function handleCsvUpload(input) { async function handleCsvUpload(input) {
if (!input.files || input.files.length === 0) return; if (!input.files || input.files.length === 0) return;
const file = input.files[0]; const file = input.files[0];
input.value = ''; input.value = '';
try { try {
const text = await file.text(); const text = await file.text();
const allData = parseCSV(text); const allData = parseCSV(text);
@@ -562,10 +493,15 @@ async function handleCsvUpload(input) {
try { try {
await fetch(`${API_URL}?action=import_batch`, { await fetch(`${API_URL}?action=import_batch`, {
method: 'POST', method: 'POST',
headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' }, headers: {
'Authorization': localStorage.getItem('token'),
'Content-Type': 'application/json'
},
body: JSON.stringify({ items: batch, type: currentAdminTab }) body: JSON.stringify({ items: batch, type: currentAdminTab })
}); });
} catch (err) { console.error('Erreur sur un lot:', err); } } catch (err) {
console.error('Erreur sur un lot:', err);
}
processed += batch.length; processed += batch.length;
updateProgressModal(processed, allData.length); updateProgressModal(processed, allData.length);
} }
@@ -573,6 +509,7 @@ async function handleCsvUpload(input) {
alert(`✅ Import terminé ! ${allData.length} élément(s) traité(s).`); alert(`✅ Import terminé ! ${allData.length} élément(s) traité(s).`);
loadDashboardData(); loadDashboardData();
} catch (err) { } catch (err) {
console.error('Erreur lecture CSV :', err);
closeProgressModal(); closeProgressModal();
alert('Impossible de lire le fichier CSV.'); alert('Impossible de lire le fichier CSV.');
} }
@@ -590,12 +527,15 @@ async function saveTmdbKey() {
}); });
const data = await res.json(); const data = await res.json();
if (data.success) { if (data.success) {
alert('✅ Clé API sauvegardée !'); alert('✅ Clé API sauvegardée et chiffrée en base de données !');
closeConfigModal(); closeConfigModal();
} else { } else {
alert('❌ Erreur : ' + (data.error || 'Impossible de sauvegarder.')); alert('❌ Erreur : ' + (data.error || 'Impossible de sauvegarder.'));
} }
} catch (err) { alert('Erreur de communication avec le serveur.'); } } catch (err) {
console.error('Erreur sauvegarde clé :', err);
alert('Erreur de communication avec le serveur.');
}
} }
} }
@@ -605,7 +545,6 @@ async function saveNewPassword() {
const pwdConfirm = document.getElementById('new-password-confirm'); const pwdConfirm = document.getElementById('new-password-confirm');
const errorMsg = document.getElementById('pwd-error'); const errorMsg = document.getElementById('pwd-error');
if (!pwdInput || !pwdConfirm) return; if (!pwdInput || !pwdConfirm) return;
if (pwdInput.value !== pwdConfirm.value) { if (pwdInput.value !== pwdConfirm.value) {
errorMsg.textContent = "Les mots de passe ne correspondent pas."; errorMsg.textContent = "Les mots de passe ne correspondent pas.";
errorMsg.style.display = "block"; errorMsg.style.display = "block";
@@ -616,7 +555,6 @@ async function saveNewPassword() {
errorMsg.style.display = "block"; errorMsg.style.display = "block";
return; return;
} }
try { try {
const response = await fetch(`${API_URL}?action=update_password`, { const response = await fetch(`${API_URL}?action=update_password`, {
method: 'POST', method: 'POST',
@@ -632,5 +570,5 @@ async function saveNewPassword() {
alert('Mot de passe mis à jour.'); alert('Mot de passe mis à jour.');
loadDashboardData(); loadDashboardData();
} }
} catch (err) { console.error('Erreur :', err); } } catch (err) { console.error('Erreur mise à jour mot de passe :', err); }
} }