diff --git a/js/admin.js b/js/admin.js index 1f92a5a..6395845 100644 --- a/js/admin.js +++ b/js/admin.js @@ -420,33 +420,41 @@ async function handleCritiqueUpload(input) { } function normalizeVideothequeRow(row) { - let ean = row['ean_isbn13'] || row['EAN'] || ''; + let ean = row['ean_isbn13'] || row['EAN'] || row['ean'] || ''; if (ean !== '') { ean = String(ean).replace(/[^0-9]/g, ''); ean = ean.replace(/^0+/, ''); } - let length = row['length'] || ''; + let length = row['length'] || row['Length'] || ''; if (length !== '' && length !== null) { const l = parseFloat(length); length = isNaN(l) ? '' : String(Math.round(l)); } - - let discs = row['number_of_discs'] || ''; + + let discs = row['number_of_discs'] || row['Number_of_discs'] || row['Discs'] || ''; if (discs === '' || discs === null || isNaN(parseFloat(discs))) { discs = 1; } else { discs = Math.round(parseFloat(discs)); } + let aspect = row['aspect_ratio'] || row['Aspect_ratio'] || row['AspectRatio'] || ''; + let actors = row['actors'] || row['Actors'] || row['creators'] || ''; + let publisher = row['publisher'] || row['Publisher'] || ''; + let director = row['director'] || row['Director'] || row['first_name'] + ' ' + row['last_name'] || ''; + return Object.assign({}, row, { - ean_isbn13: ean, + ean: ean, length: length, - number_of_discs: discs + number_of_discs: discs, + aspect_ratio: aspect, + actors: actors, + publisher: publisher, + director: director.trim() }); } -// ── 2. Importation et Mapping du CSV Blu-ray.com ── function handleVideothequeUpload(input) { const file = input.files[0]; if (!file) return; @@ -454,61 +462,97 @@ function handleVideothequeUpload(input) { const reader = new FileReader(); reader.onload = async (e) => { const text = e.target.result; - - // On suppose que ta fonction parseCSV retourne un tableau d'objets avec les en-têtes en clés const parsedData = parseCSV(text); + if (parsedData.length === 0) { + alert("❌ Fichier CSV vide ou invalide."); + return; + } + const items = parsedData.map(row => { - // Lecture des colonnes spécifiques du CSV de Blu-ray.com - const title = row['title'] ? row['title'].trim() : ''; + const normalizedRow = normalizeVideothequeRow(row); + + const title = normalizedRow['title'] || normalizedRow['Title'] || ''; if (!title) return null; - // On priorise l'EAN, avec un fallback sur l'UPC si l'EAN est vide - let ean = row['ean_isbn13'] ? row['ean_isbn13'].trim() : ''; - if (!ean && row['upc_isbn10']) { - ean = row['upc_isbn10'].trim(); - } + const ean = normalizedRow['ean'] || ''; + const publishDate = normalizedRow['publish_date'] || normalizedRow['Publish_date'] || normalizedRow['publishdate'] || ''; + const year = publishDate ? publishDate.split('-')[0] : (normalizedRow['year'] || normalizedRow['Year'] || ''); - // Extraction de l'année depuis la date complète - const publishDate = row['publish_date'] ? row['publish_date'].trim() : ''; - const year = publishDate ? publishDate.split('-')[0] : ''; + const description = normalizedRow['description'] || normalizedRow['Description'] || ''; + const length = normalizedRow['length'] || ''; + const discs = normalizedRow['number_of_discs'] || 1; + const aspect = normalizedRow['aspect_ratio'] || ''; + const actors = normalizedRow['actors'] || ''; + const publisher = normalizedRow['publisher'] || ''; + const director = normalizedRow['director'] || ''; - const description = row['description'] ? row['description'].trim() : ''; - - return { title, ean, year, description }; + return { + title: title.trim(), + ean: ean, + year: year, + description: description.trim(), + length: length, + number_of_discs: discs, + aspect_ratio: aspect, + actors: actors, + publisher: publisher, + director: director + }; }).filter(item => item !== null); if (items.length === 0) { - alert("Aucun film valide trouvé dans le fichier CSV."); + alert("❌ Aucun film valide trouvé dans le fichier CSV."); return; } + showImportModal(items.length, 'videotheque'); + let processed = 0; + try { - const response = await fetch(`${API_URL}?action=import_batch`, { - method: 'POST', - headers: { - 'Authorization': localStorage.getItem('token'), - 'Content-Type': 'application/json' - }, - body: JSON.stringify({ type: 'videotheque', items }) - }); - const data = await response.json(); - - if (data.success) { - // Utilisation de ta modale de succès - if (typeof showSuccessModal === 'function') { - showSuccessModal(`${data.imported} éditions physiques importées !`); - } else { - alert(`${data.imported} éditions physiques importées !`); + // Traiter par lots de 5 pour éviter la surcharge + for (let i = 0; i < items.length; i += 5) { + const batch = items.slice(i, i + 5); + + const response = await fetch(`${API_URL}?action=import_batch`, { + method: 'POST', + headers: { + 'Authorization': localStorage.getItem('token'), + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ type: 'videotheque', items: batch }) + }); + + if (!response.ok) { + throw new Error(`Erreur serveur ${response.status}`); } - loadDashboardData(); - } else { - alert("Erreur lors de l'importation côté serveur."); + + const data = await response.json(); + + if (!data.success) { + throw new Error(data.error || "Erreur inconnue"); + } + + processed += batch.length; + updateImportModal(processed, items.length); + + // Petit délai pour éviter de surcharger le serveur + await new Promise(resolve => setTimeout(resolve, 500)); } + + input.value = ''; + closeImportModal(); + showSuccessModal(`${items.length} édition(s) physique(s) importée(s) avec succès !`); + loadDashboardData(); + } catch (err) { - console.error("Erreur d'importation :", err); + console.error("Erreur d'importation : ", err); + closeImportModal(); + alert("❌ Échec de l'import : " + err.message); + input.value = ''; } }; + reader.readAsText(file); }