Actualiser js/admin.js

This commit is contained in:
2026-06-19 20:40:12 +02:00
parent c37b3df75c
commit f8c651334c
+138 -201
View File
@@ -4,8 +4,9 @@ let currentAdminTab = 'critique';
let currentPage = 1; let currentPage = 1;
const itemsPerPage = 12; const itemsPerPage = 12;
let searchQuery = ''; let searchQuery = '';
let selectedIds = new Set();
// ── GÉNÉRATEUR D'ÉTOILES (Supporte les demi-étoiles) ─ // ── GÉNÉRATEUR D'ÉTOILES (Supporte les demi-étoiles) ─
function getStarsHTML(rating) { function getStarsHTML(rating) {
const r = parseFloat(rating) || 0; const r = parseFloat(rating) || 0;
const full = Math.floor(r); const full = Math.floor(r);
@@ -17,13 +18,65 @@ function getStarsHTML(rating) {
return html; return html;
} }
// ── PARSER CSV ──
function parseCSV(text) {
if (text.charCodeAt(0) === 0xFEFF) text = text.slice(1);
const rows = [];
let col = '', row = [], inQuotes = false;
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (inQuotes) {
if (c === '"') {
if (text[i+1] === '"') { col += '"'; i++; }
else inQuotes = false;
} else col += c;
} else {
if (c === '"') inQuotes = true;
else if (c === ',') { row.push(col); col = ''; }
else if (c === '\n' || c === '\r') {
if (c === '\r' && text[i+1] === '\n') i++;
row.push(col); col = '';
if (row.length > 1 || row[0] !== '') rows.push(row);
row = [];
} else col += c;
}
}
if (col !== '' || row.length > 0) { row.push(col); rows.push(row); }
if (rows.length === 0) return [];
const headers = rows[0].map(h => h.trim());
const data = [];
for (let i = 1; i < rows.length; i++) {
if (rows[i].length === headers.length) {
const obj = {};
headers.forEach((h, idx) => obj[h] = rows[i][idx]);
data.push(obj);
}
}
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();
initEventListeners(); initEventListeners();
const confirmBtn = document.getElementById('confirm-btn'); const confirmBtn = document.getElementById('confirm-btn');
if(confirmBtn) { if (confirmBtn) {
confirmBtn.addEventListener('click', () => { confirmBtn.addEventListener('click', () => {
if (pendingDeleteAction) pendingDeleteAction(); if (pendingDeleteAction) pendingDeleteAction();
closeConfirmModal(); closeConfirmModal();
@@ -34,9 +87,17 @@ document.addEventListener('DOMContentLoaded', () => {
function initEventListeners() { function initEventListeners() {
const filmForm = document.getElementById('film-form'); const filmForm = document.getElementById('film-form');
if (filmForm) filmForm.addEventListener('submit', saveFilmForm); if (filmForm) filmForm.addEventListener('submit', saveFilmForm);
const csvInput = document.getElementById('csv-file'); const csvInput = document.getElementById('csv-file');
if (csvInput) csvInput.addEventListener('change', (e) => handleCsvUpload(e.target)); if (csvInput) csvInput.addEventListener('change', (e) => handleCsvUpload(e.target));
const searchInput = document.getElementById('search-input');
if (searchInput) {
searchInput.addEventListener('input', (e) => {
searchQuery = e.target.value;
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')) {
@@ -47,37 +108,27 @@ function initEventListeners() {
e.target.classList.remove('open'); e.target.classList.remove('open');
} }
}); });
const searchInput = document.getElementById('search-input');
if (searchInput) {
searchInput.addEventListener('input', (e) => {
searchQuery = e.target.value;
currentPage = 1; // Reset à la page 1 à chaque recherche
renderAdminTable();
});
}
} }
// ── CHARGEMENT DES DONNÉES (Anti-cache) ── // ── 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' });
allItems = await res.json(); allItems = await res.json();
const secRes = await fetch(`${API_URL}?action=check_security_status`, { cache: 'no-store' }); const secRes = await fetch(`${API_URL}?action=check_security_status`, { cache: 'no-store' });
const secData = await secRes.json(); const secData = await secRes.json();
const banner = document.getElementById('security-banner'); const banner = document.getElementById('security-banner');
if (banner) banner.style.display = secData.is_blank ? 'flex' : 'none'; if (banner) banner.style.display = secData.is_blank ? 'flex' : 'none';
renderAdminTable(); renderAdminTable();
} catch (err) { console.error('Erreur chargement :', err); } } catch (err) { console.error('Erreur chargement :', err); }
} }
// ── RENDU DU TABLEAU ──
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. Filtrage
let filtered = allItems.filter(item => item.type === currentAdminTab); let filtered = allItems.filter(item => item.type === currentAdminTab);
if (searchQuery) { if (searchQuery) {
const q = searchQuery.toLowerCase(); const q = searchQuery.toLowerCase();
@@ -88,30 +139,22 @@ function renderAdminTable() {
} }
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)`;
// 2. 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 startIdx = (currentPage - 1) * itemsPerPage; const startIdx = (currentPage - 1) * itemsPerPage;
const pageItems = filtered.slice(startIdx, startIdx + itemsPerPage); const pageItems = filtered.slice(startIdx, startIdx + itemsPerPage);
// 3. Rendu
pageItems.forEach(f => { pageItems.forEach(f => {
const tr = document.createElement('tr'); const tr = document.createElement('tr');
let infoHtml = ''; let infoHtml = '';
if (currentAdminTab === 'critique') { if (currentAdminTab === 'critique') {
const rating = parseFloat(f.rating) || 0;
const fullStars = Math.floor(rating);
const emptyStars = 5 - Math.ceil(rating);
const stars = '★'.repeat(fullStars) + '☆'.repeat(emptyStars);
infoHtml = ` infoHtml = `
<div style="display:flex; align-items:center; gap:0.6rem; flex-wrap:wrap;"> <div class="info-cell">
<span class="tbl-stars" style="font-size:1.05rem;">${stars}</span> <span class="tbl-stars">${getStarsHTML(f.rating)}</span>
<span class="rating-badge">${rating.toFixed(1)}</span> <span class="rating-badge">${parseFloat(f.rating).toFixed(1)}</span>
</div>`; </div>`;
if (f.streaming && f.streaming !== 'Disponible en support physique ou Cinéma') { if (f.streaming && f.streaming !== 'Disponible en support physique ou Cinéma') {
infoHtml += `<span class="streaming-badge" title="${f.streaming}">${f.streaming}</span>`; infoHtml += `<span class="streaming-badge" title="${f.streaming}">${f.streaming}</span>`;
} else { } else {
@@ -119,7 +162,7 @@ function renderAdminTable() {
} }
} else { } else {
infoHtml = `<span class="badge-format">${f.format || '-'}</span>`; infoHtml = `<span class="badge-format">${f.format || '-'}</span>`;
if(f.length) infoHtml += `<span style="font-size:0.8rem; color:var(--muted); margin-left:0.4rem;">${f.length}</span>`; if (f.length) infoHtml += `<span style="font-size:0.8rem; color:var(--muted); margin-left:0.4rem;">${f.length}</span>`;
} }
tr.innerHTML = ` tr.innerHTML = `
@@ -140,7 +183,6 @@ function renderAdminTable() {
tbody.appendChild(tr); tbody.appendChild(tr);
}); });
// ✅ Synchronise les checkboxes avec selectedIds après rendu
document.querySelectorAll('.film-checkbox').forEach(cb => { document.querySelectorAll('.film-checkbox').forEach(cb => {
cb.checked = selectedIds.has(cb.value); cb.checked = selectedIds.has(cb.value);
}); });
@@ -148,7 +190,7 @@ function renderAdminTable() {
renderPagination(totalPages, filtered.length); renderPagination(totalPages, filtered.length);
} }
// ── SÉLECTION INDIVIDUELLE ─ // ── SÉLECTION ─
function toggleSingleSelect(id, checkbox) { function toggleSingleSelect(id, checkbox) {
if (checkbox.checked) { if (checkbox.checked) {
selectedIds.add(String(id)); selectedIds.add(String(id));
@@ -156,8 +198,6 @@ function toggleSingleSelect(id, checkbox) {
selectedIds.delete(String(id)); selectedIds.delete(String(id));
} }
updateBulkBar(); updateBulkBar();
// Met à jour le checkbox "select all"
const selectAll = document.getElementById('select-all-checkbox'); const selectAll = document.getElementById('select-all-checkbox');
const filtered = allItems.filter(item => item.type === currentAdminTab); const filtered = allItems.filter(item => item.type === currentAdminTab);
if (selectAll) { if (selectAll) {
@@ -165,53 +205,69 @@ function toggleSingleSelect(id, checkbox) {
} }
} }
// ── FONCTIONS DE PAGINATION ── function toggleSelectAll(source) {
const filtered = allItems.filter(item => item.type === currentAdminTab);
if (source.checked) {
filtered.forEach(f => selectedIds.add(String(f.id)));
} else {
filtered.forEach(f => selectedIds.delete(String(f.id)));
}
document.querySelectorAll('.film-checkbox').forEach(cb => {
cb.checked = selectedIds.has(cb.value);
});
updateBulkBar();
}
function updateBulkBar() {
const bulkBar = document.getElementById('bulk-actions-bar');
const bulkCount = document.getElementById('bulk-count');
if (selectedIds.size > 0) {
if (bulkBar) bulkBar.style.display = 'flex';
if (bulkCount) bulkCount.textContent = selectedIds.size;
} else {
if (bulkBar) bulkBar.style.display = 'none';
const selectAll = document.getElementById('select-all-checkbox');
if (selectAll) selectAll.checked = false;
}
}
// ── PAGINATION ──
function renderPagination(totalPages, totalItems) { function renderPagination(totalPages, totalItems) {
const container = document.getElementById('pagination-container'); const container = document.getElementById('pagination-container');
if (!container) return; if (!container) return;
container.innerHTML = ''; container.innerHTML = '';
if (totalItems === 0) { if (totalItems === 0) {
container.innerHTML = '<p style="color:var(--muted); text-align:center; width:100%;">Aucun élément trouvé.</p>'; container.innerHTML = '<p style="color:var(--muted); text-align:center; width:100%;">Aucun élément trouvé.</p>';
return; return;
} }
// Info
const info = document.createElement('span'); const info = document.createElement('span');
info.className = 'pagination-info'; info.className = 'pagination-info';
info.textContent = `Page ${currentPage} sur ${totalPages}`; info.textContent = `Page ${currentPage} sur ${totalPages}`;
container.appendChild(info); container.appendChild(info);
// Prev
const prevBtn = document.createElement('button'); const prevBtn = document.createElement('button');
prevBtn.innerHTML = '<i class="ti ti-chevron-left"></i>'; prevBtn.innerHTML = '<i class="ti ti-chevron-left"></i>';
prevBtn.disabled = currentPage === 1; prevBtn.disabled = currentPage === 1;
prevBtn.onclick = () => { currentPage--; renderAdminTable(); }; prevBtn.onclick = () => { currentPage--; renderAdminTable(); };
container.appendChild(prevBtn); container.appendChild(prevBtn);
// Pages (affichage intelligent : 1 ... 4 5 6 ... 10)
const maxButtons = 5; const maxButtons = 5;
let startPage = Math.max(1, currentPage - Math.floor(maxButtons / 2)); let startPage = Math.max(1, currentPage - Math.floor(maxButtons / 2));
let endPage = Math.min(totalPages, startPage + maxButtons - 1); let endPage = Math.min(totalPages, startPage + maxButtons - 1);
if (endPage - startPage + 1 < maxButtons) { if (endPage - startPage + 1 < maxButtons) {
startPage = Math.max(1, endPage - maxButtons + 1); startPage = Math.max(1, endPage - maxButtons + 1);
} }
if (startPage > 1) { if (startPage > 1) {
container.appendChild(createPageBtn(1)); container.appendChild(createPageBtn(1));
if (startPage > 2) container.appendChild(createEllipsis()); if (startPage > 2) container.appendChild(createEllipsis());
} }
for (let i = startPage; i <= endPage; i++) { for (let i = startPage; i <= endPage; i++) {
container.appendChild(createPageBtn(i)); container.appendChild(createPageBtn(i));
} }
if (endPage < totalPages) { if (endPage < totalPages) {
if (endPage < totalPages - 1) container.appendChild(createEllipsis()); if (endPage < totalPages - 1) container.appendChild(createEllipsis());
container.appendChild(createPageBtn(totalPages)); container.appendChild(createPageBtn(totalPages));
} }
// Next
const nextBtn = document.createElement('button'); const nextBtn = document.createElement('button');
nextBtn.innerHTML = '<i class="ti ti-chevron-right"></i>'; nextBtn.innerHTML = '<i class="ti ti-chevron-right"></i>';
nextBtn.disabled = currentPage === totalPages; nextBtn.disabled = currentPage === totalPages;
@@ -235,81 +291,39 @@ function createEllipsis() {
return span; return span;
} }
// ── GESTION DE MASSE AMÉLIORÉE // ── POP-UP CONFIRMATION
let selectedIds = new Set(); // Stocke tous les IDs sélectionnés (toutes pages)
function toggleSelectAll(source) {
// Sélectionne tous les films de la catégorie actuelle (pas juste la page)
const filtered = allItems.filter(item => item.type === currentAdminTab);
if (source.checked) {
filtered.forEach(f => selectedIds.add(String(f.id)));
} else {
filtered.forEach(f => selectedIds.delete(String(f.id)));
}
// Met à jour visuellement les checkboxes de la page courante
document.querySelectorAll('.film-checkbox').forEach(cb => {
cb.checked = selectedIds.has(cb.value);
});
updateBulkBar();
}
function updateBulkBar() {
const bulkBar = document.getElementById('bulk-actions-bar');
const bulkCount = document.getElementById('bulk-count');
const selectAll = document.getElementById('select-all-checkbox');
if (selectedIds.size > 0) {
if(bulkBar) bulkBar.style.display = 'flex';
if(bulkCount) bulkCount.textContent = selectedIds.size;
} else {
if(bulkBar) bulkBar.style.display = 'none';
if(selectAll) selectAll.checked = false;
}
}
// ── POP-UP CONFIRMATION SUPPRESSION ──
let pendingDeleteAction = null; let pendingDeleteAction = null;
function showConfirmModal(actionFn) { function showConfirmModal(actionFn) {
pendingDeleteAction = actionFn; pendingDeleteAction = 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');
pendingDeleteAction = null; pendingDeleteAction = null;
} }
// ── ACTIONS CRUD (SUPPRESSION SÉCURISÉE) ── // ─ SUPPRESSIONS ──
async function executeBulkDelete() { async function executeBulkDelete() {
const ids = Array.from(selectedIds); const ids = Array.from(selectedIds);
if (ids.length === 0) return; if (ids.length === 0) return;
showConfirmModal(async () => { showConfirmModal(async () => {
try { try {
const res = await fetch(`${API_URL}?action=bulk_delete`, { const res = await fetch(`${API_URL}?action=bulk_delete`, {
method: 'POST', method: 'POST',
headers: { headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' },
'Authorization': localStorage.getItem('token'),
'Content-Type': 'application/json'
},
body: JSON.stringify({ ids, type: currentAdminTab }) body: JSON.stringify({ ids, type: currentAdminTab })
}); });
if (!res.ok) throw new Error("Erreur serveur lors de la suppression multiple."); if (!res.ok) throw new Error("Erreur serveur.");
selectedIds.clear(); selectedIds.clear();
document.getElementById('bulk-actions-bar').style.display = 'none'; document.getElementById('bulk-actions-bar').style.display = 'none';
const selectAll = document.getElementById('select-all-checkbox'); const selectAll = document.getElementById('select-all-checkbox');
if(selectAll) selectAll.checked = false; if (selectAll) selectAll.checked = false;
loadDashboardData(); loadDashboardData();
} catch (err) { } catch (err) {
console.error('Erreur bulk delete :', err); console.error('Erreur bulk delete :', err);
alert("Une erreur est survenue lors de la suppression."); alert("Une erreur est survenue.");
} }
}); });
} }
@@ -321,11 +335,11 @@ async function deleteSingleFilm(id) {
method: 'DELETE', method: 'DELETE',
headers: { 'Authorization': localStorage.getItem('token') } headers: { 'Authorization': localStorage.getItem('token') }
}); });
if (!res.ok) throw new Error("Erreur serveur lors de la suppression."); if (!res.ok) throw new Error("Erreur serveur.");
loadDashboardData(); loadDashboardData();
} catch (err) { } catch (err) {
console.error('Erreur delete :', err); console.error('Erreur delete :', err);
alert("Une erreur est survenue lors de la suppression."); alert("Une erreur est survenue.");
} }
}); });
} }
@@ -334,15 +348,20 @@ async function deleteSingleFilm(id) {
function toggleFormFields() { function toggleFormFields() {
const critFields = document.getElementById('form-critique-fields'); const critFields = document.getElementById('form-critique-fields');
const vidFields = document.getElementById('form-videotheque-fields'); const vidFields = document.getElementById('form-videotheque-fields');
if(critFields) critFields.style.display = currentAdminTab === 'critique' ? 'block' : 'none'; if (critFields) critFields.style.display = currentAdminTab === 'critique' ? 'block' : 'none';
if(vidFields) vidFields.style.display = currentAdminTab === 'videotheque' ? 'block' : 'none'; if (vidFields) vidFields.style.display = currentAdminTab === 'videotheque' ? 'block' : 'none';
} }
function switchAdminTab(tabName) { function switchAdminTab(tabName) {
currentAdminTab = tabName; currentAdminTab = tabName;
currentPage = 1;
searchQuery = '';
selectedIds.clear();
const searchInput = document.getElementById('search-input');
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();
renderAdminTable(); renderAdminTable();
} }
@@ -357,16 +376,13 @@ function openAddModal() {
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; document.getElementById('f-id').value = item.id;
document.getElementById('f-title').value = item.title; document.getElementById('f-title').value = item.title;
document.getElementById('f-year').value = item.year || ''; document.getElementById('f-year').value = item.year || '';
document.getElementById('f-director').value = item.director || ''; document.getElementById('f-director').value = item.director || '';
document.getElementById('f-poster').value = item.poster || ''; document.getElementById('f-poster').value = item.poster || '';
toggleFormFields(); toggleFormFields();
if (currentAdminTab === 'critique') {
if(currentAdminTab === 'critique') {
document.getElementById('f-rating').value = item.rating || 3; document.getElementById('f-rating').value = 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 || '';
@@ -385,15 +401,14 @@ function openEditModal(id) {
function closeAdminModal() { document.getElementById('admin-modal').classList.remove('open'); } function closeAdminModal() { document.getElementById('admin-modal').classList.remove('open'); }
function openConfigModal() { document.getElementById('config-modal').classList.add('open'); } function openConfigModal() { document.getElementById('config-modal').classList.add('open'); }
function closeConfigModal() { document.getElementById('config-modal').classList.remove('open'); } function closeConfigModal() { document.getElementById('config-modal').classList.remove('open'); }
function openPasswordModal() { function openPasswordModal() {
document.getElementById('pwd-error').style.display = 'none'; document.getElementById('pwd-error').style.display = 'none';
document.getElementById('password-modal').classList.add('open'); document.getElementById('password-modal').classList.add('open');
} }
function closePasswordModal() { document.getElementById('password-modal').classList.remove('open'); } function closePasswordModal() { document.getElementById('password-modal').classList.remove('open'); }
function logout() {
function logout() { localStorage.removeItem('token');
localStorage.removeItem('token'); window.location.href = 'login.html';
window.location.href = 'login.html';
} }
// ── SAUVEGARDE FILM ── // ── SAUVEGARDE FILM ──
@@ -417,14 +432,10 @@ async function saveFilmForm(e) {
number_of_discs: document.getElementById('f-discs') ? document.getElementById('f-discs').value : 1, number_of_discs: document.getElementById('f-discs') ? document.getElementById('f-discs').value : 1,
description: document.getElementById('f-description') ? document.getElementById('f-description').value : '' 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`, {
method: 'POST', method: 'POST',
headers: { headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' },
'Authorization': localStorage.getItem('token'),
'Content-Type': 'application/json'
},
body: JSON.stringify(payload) body: JSON.stringify(payload)
}); });
closeAdminModal(); closeAdminModal();
@@ -432,86 +443,26 @@ async function saveFilmForm(e) {
} catch (err) { console.error('Erreur sauvegarde :', err); } } catch (err) { console.error('Erreur sauvegarde :', err); }
} }
// ── PARSER CSV (Gère les virgules dans les titres entre guillemets) ── // ── IMPORT CSV PAR LOTS ──
function parseCSV(text) {
if (text.charCodeAt(0) === 0xFEFF) text = text.slice(1); // Supprime le BOM UTF-8
const rows = [];
let col = '', row = [], inQuotes = false;
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (inQuotes) {
if (c === '"') {
if (text[i+1] === '"') { col += '"'; i++; }
else inQuotes = false;
} else col += c;
} else {
if (c === '"') inQuotes = true;
else if (c === ',') { row.push(col); col = ''; }
else if (c === '\n' || c === '\r') {
if (c === '\r' && text[i+1] === '\n') i++;
row.push(col); col = '';
if (row.length > 1 || row[0] !== '') rows.push(row);
row = [];
} else col += c;
}
}
if (col !== '' || row.length > 0) { row.push(col); rows.push(row); }
if (rows.length === 0) return [];
const headers = rows[0].map(h => h.trim());
const data = [];
for (let i = 1; i < rows.length; i++) {
if (rows[i].length === headers.length) {
const obj = {};
headers.forEach((h, idx) => obj[h] = rows[i][idx]);
data.push(obj);
}
}
return data;
}
// ── GESTION UI 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');
}
// ── IMPORT CSV (Lecture locale + Envoi 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 = ''; // Reset l'input file input.value = '';
try { try {
// 1. Lecture du fichier en texte par le navigateur
const text = await file.text(); const text = await file.text();
const allData = parseCSV(text); const allData = parseCSV(text);
if (allData.length === 0) { if (allData.length === 0) {
alert('❌ Le fichier CSV est vide ou mal formaté.'); alert('❌ Le fichier CSV est vide ou mal formaté.');
return; return;
} }
closeConfigModal();
closeConfigModal(); // Ferme la modale de config
showProgressModal(allData.length); showProgressModal(allData.length);
// 2. Envoi par lots de 5 films pour éviter les timeouts et avoir une barre fluide const batchSize = 5;
const batchSize = 5;
let processed = 0; let processed = 0;
for (let i = 0; i < allData.length; i += batchSize) { for (let i = 0; i < allData.length; i += batchSize) {
const batch = allData.slice(i, i + batchSize); const batch = allData.slice(i, i + batchSize);
try { try {
await fetch(`${API_URL}?action=import_batch`, { await fetch(`${API_URL}?action=import_batch`, {
method: 'POST', method: 'POST',
@@ -524,37 +475,28 @@ async function handleCsvUpload(input) {
} catch (err) { } catch (err) {
console.error('Erreur sur un lot:', err); console.error('Erreur sur un lot:', err);
} }
processed += batch.length; processed += batch.length;
updateProgressModal(processed, allData.length); updateProgressModal(processed, allData.length);
} }
closeProgressModal(); closeProgressModal();
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); console.error('Erreur lecture CSV :', err);
closeProgressModal(); closeProgressModal();
alert(' Impossible de lire le fichier CSV.'); alert(' Impossible de lire le fichier CSV.');
} }
} }
// ── SAUVEGARDE CLÉ TMDB (EN BASE DE DONNÉES) ── // ── SAUVEGARDE CLÉ TMDB ──
async function saveTmdbKey() { async function saveTmdbKey() {
const input = document.getElementById('tmdb-key-input'); const input = document.getElementById('tmdb-key-input');
if (input && input.value) { if (input && input.value) {
try { try {
// On envoie la clé au serveur PHP pour qu'il la stocke en base
const res = await fetch(`${API_URL}?action=save_config`, { const res = await fetch(`${API_URL}?action=save_config`, {
method: 'POST', method: 'POST',
headers: { headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' },
'Authorization': localStorage.getItem('token'), body: JSON.stringify({ key_name: 'tmdb_api_key', key_value: input.value })
'Content-Type': 'application/json'
},
body: JSON.stringify({
key_name: 'tmdb_api_key',
key_value: input.value
})
}); });
const data = await res.json(); const data = await res.json();
if (data.success) { if (data.success) {
@@ -575,36 +517,31 @@ async function saveNewPassword() {
const pwdInput = document.getElementById('new-password-input'); const pwdInput = document.getElementById('new-password-input');
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";
return; return;
} }
if (pwdInput.value.length < 4) { if (pwdInput.value.length < 4) {
errorMsg.textContent = "Le mot de passe doit contenir au moins 4 caractères."; errorMsg.textContent = "Le mot de passe doit contenir au moins 4 caractères.";
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',
headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' }, headers: { 'Authorization': localStorage.getItem('token'), 'Content-Type': 'application/json' },
body: JSON.stringify({ new_password: pwdInput.value }) body: JSON.stringify({ new_password: pwdInput.value })
}); });
const data = await response.json(); const data = await response.json();
if(data.success) { if (data.success) {
pwdInput.value = ''; pwdInput.value = '';
pwdConfirm.value = ''; pwdConfirm.value = '';
errorMsg.style.display = "none"; errorMsg.style.display = "none";
closePasswordModal(); closePasswordModal();
alert('Mot de passe mis à jour.'); alert('Mot de passe mis à jour.');
loadDashboardData(); loadDashboardData();
} }
} catch (err) { console.error('Erreur mise à jour mot de passe :', err); } } catch (err) { console.error('Erreur mise à jour mot de passe :', err); }
} }