Actualiser js/admin.js

This commit is contained in:
2026-06-22 14:15:25 +02:00
parent 8a171c34d3
commit 38128f7d57
+66 -57
View File
@@ -68,22 +68,16 @@ function initEventListeners() {
const filmForm = document.getElementById('film-form');
if (filmForm) filmForm.addEventListener('submit', saveFilmForm);
// 🔥 DISPATCHER D'IMPORT : Appelle la bonne fonction selon l'onglet actif
const csvInput = document.getElementById('csv-file');
if (csvInput) {
csvInput.addEventListener('change', (e) => {
if (currentAdminTab === 'critique') {
handleCritiqueUpload(e.target);
} else {
handleVideothequeUpload(e.target);
}
if (currentAdminTab === 'critique') handleCritiqueUpload(e.target);
else handleVideothequeUpload(e.target);
});
}
const searchInput = document.getElementById('search-input');
if (searchInput) {
searchInput.addEventListener('input', () => { currentPage = 1; renderAdminTable(); });
}
if (searchInput) searchInput.addEventListener('input', () => { currentPage = 1; renderAdminTable(); });
const selectAll = document.getElementById('select-all-checkbox');
if (selectAll) selectAll.addEventListener('change', (e) => toggleSelectAll(e.target));
@@ -97,9 +91,7 @@ function initEventListeners() {
});
const physicalFilter = document.getElementById('admin-physical-checkbox');
if (physicalFilter) {
physicalFilter.addEventListener('change', () => { currentPage = 1; renderAdminTable(); });
}
if (physicalFilter) physicalFilter.addEventListener('change', () => { currentPage = 1; renderAdminTable(); });
}
async function loadDashboardData() {
@@ -123,16 +115,11 @@ function renderAdminTable() {
const physicalFilter = document.getElementById('admin-physical-checkbox');
let filtered = allItems.filter(item => item.type === currentAdminTab);
if (physicalFilter && physicalFilter.checked) {
filtered = filtered.filter(f => f.format && !['dématérialisé', 'vod', 'digital', 'streaming'].includes(f.format.toLowerCase()));
}
if (currentSearch) {
filtered = filtered.filter(f =>
f.title.toLowerCase().includes(currentSearch) ||
(f.director && f.director.toLowerCase().includes(currentSearch))
);
filtered = filtered.filter(f => f.title.toLowerCase().includes(currentSearch) || (f.director && f.director.toLowerCase().includes(currentSearch)));
}
const countLabel = document.getElementById('admin-count-label');
@@ -227,8 +214,8 @@ function renderPagination(totalPages, totalItems) {
container.appendChild(nextBtn);
}
function showConfirmModal(actionFn) { pendingDeleteAction = actionFn; document.getElementById('confirm-modal')?.classList.add('open'); }
function closeConfirmModal() { document.getElementById('confirm-modal')?.classList.remove('open'); pendingDeleteAction = null; }
function showConfirmModal(actionFn) { pendingDeleteAction = actionFn; document.getElementById('confirm-modal').classList.add('open'); }
function closeConfirmModal() { document.getElementById('confirm-modal').classList.remove('open'); pendingDeleteAction = null; }
async function executeBulkDelete() {
const ids = Array.from(selectedIds);
@@ -253,28 +240,23 @@ async function deleteSingleFilm(id) {
}
function toggleFormFields() {
const critFields = document.getElementById('form-critique-fields');
const vidFields = document.getElementById('form-videotheque-fields');
if (critFields) critFields.style.display = currentAdminTab === 'critique' ? 'block' : 'none';
if (vidFields) vidFields.style.display = currentAdminTab === 'videotheque' ? 'block' : 'none';
document.getElementById('form-critique-fields').style.display = currentAdminTab === 'critique' ? 'block' : 'none';
document.getElementById('form-videotheque-fields').style.display = currentAdminTab === 'videotheque' ? 'block' : 'none';
}
function switchAdminTab(tabName) {
currentAdminTab = tabName;
currentPage = 1;
selectedIds.clear();
const searchInput = document.getElementById('search-input');
if (searchInput) searchInput.value = '';
document.getElementById('search-input').value = '';
const physicalFilter = document.getElementById('admin-physical-checkbox');
if (physicalFilter) {
physicalFilter.checked = false;
const wrapper = physicalFilter.closest('label') || physicalFilter.parentElement;
if (wrapper) wrapper.style.display = (tabName === 'videotheque') ? 'none' : 'flex';
}
physicalFilter.checked = false;
const wrapper = document.getElementById('physical-filter-wrapper');
if (wrapper) wrapper.style.display = (tabName === 'videotheque') ? 'none' : 'flex';
document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
document.getElementById(`btn-tab-${tabName}`)?.classList.add('active');
document.getElementById(`btn-tab-${tabName}`).classList.add('active');
updateImportInterface();
toggleFormFields();
@@ -314,9 +296,28 @@ function openEditModal(id) {
}
function closeAdminModal() { document.getElementById('admin-modal').classList.remove('open'); }
async function openConfigModal() {
document.getElementById('config-modal').classList.add('open');
try {
const res = await fetch(`${API_URL}?action=get_config_keys`, { headers: { 'Authorization': localStorage.getItem('token') } });
const data = await res.json();
document.getElementById('tmdb-key-input').value = '';
document.getElementById('tmdb-key-input').placeholder = data.tmdb_api_key ? '✅ Clé configurée (laisser vide pour garder)' : 'Entrez votre clé TMDB';
} catch(e) { console.error(e); }
}
function closeConfigModal() { document.getElementById('config-modal').classList.remove('open'); }
function openPasswordModal() {
document.getElementById('pwd-error').style.display = 'none';
document.getElementById('new-password-input').value = '';
document.getElementById('new-password-confirm').value = '';
document.getElementById('password-modal').classList.add('open');
}
function closePasswordModal() { document.getElementById('password-modal').classList.remove('open'); }
function logout() { localStorage.removeItem('token'); window.location.href = 'login.html'; }
async function saveFilmForm(e) {
e.preventDefault();
const payload = {
@@ -336,14 +337,12 @@ async function saveFilmForm(e) {
}
// ══════════════════════════════════════════════════════════════
// 🔥 FONCTION 1 : IMPORT CRITIQUE (Letterboxd)
// IMPORT CRITIQUE
// ══════════════════════════════════════════════════════════════
async function handleCritiqueUpload(input) {
if (!input.files || input.files.length === 0) return;
let allData = [];
for (const file of input.files) {
try { allData = allData.concat(parseCSV(await file.text())); } catch(e) {}
}
for (const file of input.files) { try { allData = allData.concat(parseCSV(await file.text())); } catch(e) {} }
input.value = '';
if (allData.length === 0) return alert('❌ Fichier vide.');
@@ -352,11 +351,7 @@ async function handleCritiqueUpload(input) {
for (let i = 0; i < allData.length; i += 10) {
const batch = allData.slice(i, i + 10);
try {
await fetch(`${API_URL}?action=import_batch`, {
method: 'POST',
headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' },
body: JSON.stringify({ items: batch, type: 'critique' }) // 🔥 Envoi strict vers Critiques
});
await fetch(`${API_URL}?action=import_batch`, { method: 'POST', headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' }, body: JSON.stringify({ items: batch, type: 'critique' }) });
} catch (err) { console.error(err); }
processed += batch.length;
updateImportModal(processed, allData.length);
@@ -367,14 +362,12 @@ async function handleCritiqueUpload(input) {
}
// ══════════════════════════════════════════════════════════════
// 🔥 FONCTION 2 : IMPORT VIDÉOTHÈQUE (Physique / EAN)
// IMPORT VIDÉOTHÈQUE
// ══════════════════════════════════════════════════════════════
async function handleVideothequeUpload(input) {
if (!input.files || input.files.length === 0) return;
let allData = [];
for (const file of input.files) {
try { allData = allData.concat(parseCSV(await file.text())); } catch(e) {}
}
for (const file of input.files) { try { allData = allData.concat(parseCSV(await file.text())); } catch(e) {} }
input.value = '';
if (allData.length === 0) return alert('❌ Fichier vide.');
@@ -383,27 +376,22 @@ async function handleVideothequeUpload(input) {
for (let i = 0; i < allData.length; i += 10) {
const batch = allData.slice(i, i + 10);
try {
await fetch(`${API_URL}?action=import_batch`, {
method: 'POST',
headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' },
body: JSON.stringify({ items: batch, type: 'videotheque' }) // 🔥 Envoi strict vers Vidéothèque
});
await fetch(`${API_URL}?action=import_batch`, { method: 'POST', headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' }, body: JSON.stringify({ items: batch, type: 'videotheque' }) });
} catch (err) { console.error(err); }
processed += batch.length;
updateImportModal(processed, allData.length);
}
closeImportModal();
alert(`${allData.length} support(s) physique(s) importé(s).`);
alert(`${allData.length} support(s) importé(s).`);
loadDashboardData();
}
function showImportModal(total, type) {
const modal = document.getElementById('import-progress-modal');
document.getElementById('import-modal-title').innerHTML = type === 'critique' ? '<i class="ti ti-star"></i> Import des Critiques' : '<i class="ti ti-video"></i> Import Vidéothèque';
document.getElementById('import-modal-title').innerHTML = type === 'critique' ? '<i class="ti ti-star"></i> Import Critiques' : '<i class="ti ti-video"></i> Import Vidéothèque';
document.getElementById('import-modal-desc').textContent = `Traitement de ${total} élément(s)...`;
document.getElementById('import-progress-bar').style.width = '0%';
document.getElementById('import-modal-counter').textContent = '0%';
modal.classList.add('open');
document.getElementById('import-progress-modal').classList.add('open');
}
function updateImportModal(current, total) {
const pct = Math.round((current / total) * 100);
@@ -412,6 +400,29 @@ function updateImportModal(current, total) {
}
function closeImportModal() { document.getElementById('import-progress-modal').classList.remove('open'); }
async function saveConfigKeys() {
const keyValue = document.getElementById('tmdb-key-input').value.trim();
if (!keyValue) { closeConfigModal(); return; }
try {
await fetch(`${API_URL}?action=save_config`, { method: 'POST', headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' }, body: JSON.stringify({ key_name: 'tmdb_api_key', key_value: keyValue }) });
alert('✅ Clé sauvegardée !');
closeConfigModal();
} catch (err) { alert('Erreur serveur.'); }
}
async function saveNewPassword() {
const pwdInput = document.getElementById('new-password-input');
const pwdConfirm = document.getElementById('new-password-confirm');
const errorMsg = document.getElementById('pwd-error');
if (pwdInput.value !== pwdConfirm.value) { errorMsg.textContent = "Les mots de passe ne correspondent pas."; errorMsg.style.display = "block"; return; }
if (pwdInput.value.length < 4) { errorMsg.textContent = "4 caractères minimum."; errorMsg.style.display = "block"; return; }
try {
const response = await fetch(`${API_URL}?action=update_password`, { method: 'POST', headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' }, body: JSON.stringify({ new_password: pwdInput.value }) });
const data = await response.json();
if (data.success) { alert('Mot de passe mis à jour.'); closePasswordModal(); }
} catch (err) { console.error(err); }
}
function updateImportInterface() {
const title = document.getElementById('import-title');
const desc = document.getElementById('import-desc');
@@ -422,6 +433,4 @@ function updateImportInterface() {
title.innerHTML = '<strong>Importer ma Vidéothèque</strong>';
desc.textContent = 'Sélectionnez vos listes CSV de supports physiques (Blu-ray, DVD, 4K).';
}
}
function logout() { localStorage.removeItem('token'); window.location.href = 'login.html'; }
}