← Back
Editing: admin.js
/* SEO URL Replacer v2.2 — assets/admin.js */ (function ($) { 'use strict'; let mappings = []; let batchSize = 50; let lastIsDryRun = true; // ========================================================================= // ABAS: CSV ↔ Manual // ========================================================================= document.getElementById('surTabCsv').addEventListener('click', function () { switchTab('csv'); }); document.getElementById('surTabManual').addEventListener('click', function () { switchTab('manual'); // Garante que pelo menos 1 linha existe ao abrir if (document.querySelectorAll('.sur-manual-row').length === 0) { addManualRow(); } }); function switchTab(tab) { const isCsv = tab === 'csv'; document.getElementById('surPanelCsv').style.display = isCsv ? '' : 'none'; document.getElementById('surPanelManual').style.display = isCsv ? 'none' : ''; document.getElementById('surTabCsv').classList.toggle('sur-tab-active', isCsv); document.getElementById('surTabManual').classList.toggle('sur-tab-active', !isCsv); } // ========================================================================= // ENTRADA MANUAL // ========================================================================= let rowIndex = 0; function addManualRow(fromVal, toVal) { rowIndex++; const idx = rowIndex; const wrap = document.getElementById('surManualRows'); const div = document.createElement('div'); div.className = 'sur-manual-row'; div.dataset.idx = idx; div.innerHTML = ` <input type="url" class="sur-input-from" placeholder="https://site.com/url-antiga/" value="${escHtml(fromVal || '')}"> <input type="url" class="sur-input-to" placeholder="https://site.com/url-nova/" value="${escHtml(toVal || '')}"> <button type="button" class="sur-remove-row button" title="Remover linha">✕</button>`; div.querySelector('.sur-remove-row').addEventListener('click', function () { div.remove(); updateRowNumbers(); }); wrap.appendChild(div); // Foca no campo "DE" da nova linha div.querySelector('.sur-input-from').focus(); updateRowNumbers(); } function updateRowNumbers() { document.querySelectorAll('.sur-manual-row').forEach((row, i) => { const btn = row.querySelector('.sur-remove-row'); if (btn) btn.title = `Remover linha ${i + 1}`; }); } document.getElementById('surAddRowBtn').addEventListener('click', () => addManualRow()); document.getElementById('surClearManualBtn').addEventListener('click', function () { document.getElementById('surManualRows').innerHTML = `<div class="sur-manual-header"> <span>DE (URL antiga)</span> <span>PARA (URL nova)</span> <span></span> </div>`; rowIndex = 0; addManualRow(); }); // Carregar mapeamentos da entrada manual → prévia document.getElementById('surApplyManualBtn').addEventListener('click', function () { const rows = document.querySelectorAll('.sur-manual-row'); const raw = []; let hasError = false; rows.forEach((row, i) => { const from = row.querySelector('.sur-input-from').value.trim(); const to = row.querySelector('.sur-input-to').value.trim(); row.querySelector('.sur-input-from').classList.remove('sur-input-error'); row.querySelector('.sur-input-to').classList.remove('sur-input-error'); if (!from && !to) return; // linha vazia, ignora if (!from) { row.querySelector('.sur-input-from').classList.add('sur-input-error'); hasError = true; return; } if (!to) { row.querySelector('.sur-input-to').classList.add('sur-input-error'); hasError = true; return; } raw.push({ from, to }); }); if (hasError) { alert('Preencha todos os campos destacados em vermelho.'); return; } if (!raw.length) { alert('Adicione pelo menos um par DE → PARA.'); return; } applyMappings(raw); }); // Atalho: Enter no último campo "PARA" adiciona nova linha document.getElementById('surManualRows').addEventListener('keydown', function (e) { if (e.key === 'Enter') { const target = e.target; if (target.classList.contains('sur-input-to')) { e.preventDefault(); addManualRow(); } } }); // ========================================================================= // UPLOAD / PARSE CSV // ========================================================================= const dropZone = document.getElementById('surDropZone'); const fileInput = document.getElementById('surCsvFile'); dropZone.addEventListener('click', () => fileInput.click()); dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.style.background = '#DBEAFE'; }); dropZone.addEventListener('dragleave', () => { dropZone.style.background = ''; }); dropZone.addEventListener('drop', e => { e.preventDefault(); dropZone.style.background = ''; handleFile(e.dataTransfer.files[0]); }); fileInput.addEventListener('change', e => handleFile(e.target.files[0])); function handleFile(file) { if (!file || !file.name.endsWith('.csv')) { alert('Selecione um arquivo .csv válido.'); return; } const reader = new FileReader(); reader.onload = e => parseAndPreviewCSV(e.target.result); reader.onerror = () => alert('Erro ao ler o arquivo.'); reader.readAsText(file, 'UTF-8'); } function parseAndPreviewCSV(text) { if (text.charCodeAt(0) === 0xFEFF) text = text.slice(1); // remove BOM (Excel UTF-8) const lines = text.split(/\r?\n/).filter(l => l.trim()); if (!lines.length) { applyMappings([]); return; } // Detecta o separador pelo cabeçalho: ';' (Excel pt-BR) e TAB têm // prioridade sobre ',', já que URLs costumam conter vírgulas. const header = lines[0]; let sep = ','; if (header.includes(';')) sep = ';'; else if (header.includes('\t')) sep = '\t'; const raw = []; for (let i = 1; i < lines.length; i++) { const cols = parseCsvLine(lines[i], sep); const pair = extractPair(cols, sep); if (pair) raw.push(pair); } applyMappings(raw); } // Parser RFC-4180: respeita aspas duplas e "" como aspas escapadas, // de modo que vírgulas dentro de campos entre aspas não quebram a linha. function parseCsvLine(line, sep) { const out = []; let field = ''; let inQuotes = false; for (let i = 0; i < line.length; i++) { const ch = line[i]; if (inQuotes) { if (ch === '"') { if (line[i + 1] === '"') { field += '"'; i++; } // aspas escapadas else inQuotes = false; } else { field += ch; } } else if (ch === '"') { inQuotes = true; } else if (ch === sep) { out.push(field); field = ''; } else { field += ch; } } out.push(field); return out.map(c => c.trim()); } // Extrai o par DE→PARA tolerando vírgulas NÃO escapadas dentro das URLs. // Quando há mais de 2 colunas, a URL de destino (PARA) é assumida como // começando no último campo que inicia uma URL (http(s):// ou /), e os // campos são reagrupados em torno desse limite. function extractPair(cols, sep) { cols = cols.filter(c => c !== ''); if (cols.length < 2) return null; if (cols.length === 2) return { from: cols[0], to: cols[1] }; const isUrlStart = s => /^(https?:\/\/|\/)/i.test(s); let toStart = -1; for (let i = 1; i < cols.length; i++) { if (isUrlStart(cols[i])) toStart = i; } if (toStart === -1) toStart = cols.length - 1; // fallback: último campo const from = cols.slice(0, toStart).join(sep); const to = cols.slice(toStart).join(sep); if (!from || !to) return null; return { from, to }; } // ========================================================================= // APLICAR MAPEAMENTOS (unifica CSV e Manual) // ========================================================================= function applyMappings(raw) { // Deduplicação const seen = new Set(); const deduped = raw.filter(r => { const k = r.from + '||' + r.to; if (seen.has(k)) return false; seen.add(k); return true; }); // Ordenação: mais longo primeiro deduped.sort((a, b) => b.from.length - a.from.length); mappings = deduped; renderPreview(mappings); } function renderPreview(items) { const tbody = document.getElementById('surPreviewBody'); tbody.innerHTML = ''; items.forEach((m, i) => { tbody.insertAdjacentHTML('beforeend', `<tr> <td>${i + 1}</td> <td style="color:#DC2626">${escHtml(m.from)}</td> <td style="color:#16A34A">${escHtml(m.to)}</td> </tr>`); }); document.getElementById('surEntryCount').textContent = items.length; document.getElementById('surCsvPreview').style.display = ''; document.getElementById('surOptionsCard').style.display = ''; } // ========================================================================= // INICIAR PROCESSAMENTO // ========================================================================= document.getElementById('surStartBtn').addEventListener('click', function () { if (!mappings.length) { alert('Nenhum mapeamento carregado.'); return; } const isDryRun = document.getElementById('surDryRun').checked; const isExact = document.getElementById('surExact').checked; const tables = [...document.querySelectorAll('.sur-table-chk:checked')].map(c => c.value); batchSize = parseInt(document.getElementById('surBatchSize').value) || 50; if (!tables.length) { alert('Selecione ao menos uma tabela.'); return; } lastIsDryRun = isDryRun; this.disabled = true; document.getElementById('surProgressCard').style.display = ''; document.getElementById('surHealthCard').style.display = ''; document.getElementById('surPostActions').style.display = 'none'; document.getElementById('surAuditLog').textContent = ''; document.getElementById('surHealthBody').innerHTML = ''; setProgress('surProgressBar', 0); setProgress('surHealthBar', 0); document.getElementById('surProgressMsg').textContent = 'Calculando totais...'; document.getElementById('surTableMsg').textContent = ''; $.post(SUR.ajaxUrl, { action: 'sur_count_totals', _wpnonce: SUR.nonceBatch, tables: JSON.stringify(tables), mappings: JSON.stringify(mappings), exact: isExact ? 1 : 0, }, function (res) { if (!res.success) { logLine('[ERRO] Falha ao contar totais: ' + (res.data || ''), ''); return; } const grandTotal = res.data.grand_total; const totals = res.data.totals; logLine('[INÍCIO] ' + (isDryRun ? 'SIMULAÇÃO' : 'PROCESSAMENTO REAL') + (isExact ? ' (modo exato)' : '') + ' — ' + grandTotal + ' registros a verificar', 'log-dry'); startBatchLoop(isDryRun, isExact, tables, totals, grandTotal); }, 'json').fail(function (xhr) { logLine('[ERRO HTTP] ' + xhr.status + ' ao contar totais', ''); }); }); // ========================================================================= // LOOP DE LOTES // ========================================================================= function startBatchLoop(isDryRun, isExact, tables, totals, grandTotal) { let tableKey = ''; let offset = 0; let processed = 0; function runBatch() { $.post(SUR.ajaxUrl, { action: 'sur_batch_replace', _wpnonce: SUR.nonceBatch, mappings: JSON.stringify(mappings), tables: JSON.stringify(tables), totals: JSON.stringify(totals), table_key: tableKey, offset: offset, batch: batchSize, dry_run: isDryRun ? 1 : 0, exact: isExact ? 1 : 0, }, function (res) { if (!res.success) { logLine('[ERRO] ' + (res.data || 'Resposta inválida do servidor'), ''); showPostActions(isDryRun); return; } const d = res.data; processed += d.processed_in_batch; tableKey = d.next_table_key; offset = d.next_offset; if (d.log && d.log.length) { d.log.forEach(e => logLine(e.msg, e.changed ? 'log-changed' : 'log-skip')); } const pct = grandTotal > 0 ? Math.min(Math.round((processed / grandTotal) * 100), 99) : 50; setProgress('surProgressBar', pct); document.getElementById('surProgressMsg').textContent = `Verificados ${processed} de ${grandTotal} registros...`; document.getElementById('surTableMsg').textContent = 'Tabela atual: ' + d.current_table; if (d.done) { setProgress('surProgressBar', 100); document.getElementById('surProgressMsg').textContent = (isDryRun ? '🔍 Simulação concluída!' : '✅ Substituições aplicadas!') + ' ' + processed + ' registros verificados.'; document.getElementById('surTableMsg').textContent = ''; logLine('\n[FIM] Processamento concluído.', 'log-changed'); if (d.elementor_cleared) logLine('[Elementor] Cache CSS regenerado.', 'log-dry'); showPostActions(isDryRun); runHealthCheck(); } else { runBatch(); } }, 'json').fail(function (xhr) { logLine('[ERRO HTTP] ' + xhr.status + ' ' + xhr.statusText + ' — tente reduzir o tamanho do lote.', ''); showPostActions(isDryRun); }); } runBatch(); } // ========================================================================= // AÇÕES PÓS-CONCLUSÃO // ========================================================================= function showPostActions(isDryRun) { const wrap = document.getElementById('surPostActions'); const applyBtn = document.getElementById('surApplyRealBtn'); applyBtn.style.display = isDryRun ? 'inline-block' : 'none'; wrap.style.display = 'flex'; applyBtn.onclick = function () { document.getElementById('surDryRun').checked = false; wrap.style.display = 'none'; document.getElementById('surStartBtn').disabled = false; document.getElementById('surStartBtn').click(); }; document.getElementById('surNewRunBtn').onclick = function () { wrap.style.display = 'none'; document.getElementById('surAuditLog').textContent = ''; document.getElementById('surHealthBody').innerHTML = ''; document.getElementById('surHealthCard').style.display = 'none'; document.getElementById('surProgressCard').style.display = 'none'; setProgress('surProgressBar', 0); setProgress('surHealthBar', 0); document.getElementById('surStartBtn').disabled = false; }; document.getElementById('surResetBtn').onclick = function () { mappings = []; document.getElementById('surCsvPreview').style.display = 'none'; document.getElementById('surOptionsCard').style.display = 'none'; document.getElementById('surProgressCard').style.display = 'none'; document.getElementById('surHealthCard').style.display = 'none'; wrap.style.display = 'none'; document.getElementById('surPreviewBody').innerHTML = ''; document.getElementById('surAuditLog').textContent = ''; document.getElementById('surHealthBody').innerHTML = ''; document.getElementById('surEntryCount').textContent = '0'; document.getElementById('surStartBtn').disabled = false; document.getElementById('surDryRun').checked = true; document.getElementById('surCsvFile').value = ''; setProgress('surProgressBar', 0); setProgress('surHealthBar', 0); // Reseta entrada manual document.getElementById('surManualRows').innerHTML = `<div class="sur-manual-header"> <span>DE (URL antiga)</span> <span>PARA (URL nova)</span> <span></span> </div>`; rowIndex = 0; addManualRow(); switchTab('csv'); }; } // ========================================================================= // HEALTH CHECK // ========================================================================= function runHealthCheck() { logLine('\n[HEALTH CHECK] Verificando URLs de destino...', 'log-dry'); const toUrls = [...new Set(mappings.map(m => m.to))]; const chunkSize = 5; let idx = 0; function checkChunk() { const chunk = toUrls.slice(idx, idx + chunkSize); if (!chunk.length) { setProgress('surHealthBar', 100); logLine('[HEALTH CHECK] Concluído.', 'log-changed'); return; } $.post(SUR.ajaxUrl, { action: 'sur_health_check', _wpnonce: SUR.nonceCheck, urls: JSON.stringify(chunk), }, function (res) { if (res.success && res.data) res.data.forEach(r => renderHealthRow(r)); idx += chunkSize; setProgress('surHealthBar', Math.min(Math.round((idx / toUrls.length) * 100), 100)); checkChunk(); }, 'json'); } checkChunk(); } function renderHealthRow(r) { document.getElementById('surHealthBody').insertAdjacentHTML('beforeend', `<tr> <td style="word-break:break-all">${escHtml(r.url)}</td> <td>${r.code}</td> <td>${statusBadge(r.code)}</td> </tr>`); } function statusBadge(code) { const c = parseInt(code); if (c === 200) return '<span class="sur-badge sur-badge-200">✓ OK</span>'; if (c === 301 || c === 302) return `<span class="sur-badge sur-badge-301">↪ Redirect ${c}</span>`; if (c === 404) return '<span class="sur-badge sur-badge-404">✗ Not Found</span>'; if (c >= 500) return `<span class="sur-badge sur-badge-err">⚠ Server Error ${c}</span>`; return `<span class="sur-badge sur-badge-err">${code}</span>`; } // ========================================================================= // HELPERS // ========================================================================= function setProgress(id, pct) { const el = document.getElementById(id); el.style.width = pct + '%'; el.textContent = pct + '%'; } function logLine(msg, cls) { const log = document.getElementById('surAuditLog'); const span = document.createElement('span'); if (cls) span.className = cls; span.textContent = msg + '\n'; log.appendChild(span); log.scrollTop = log.scrollHeight; } function escHtml(str) { if (!str) return ''; return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); } // Inicializa: abre com 1 linha manual já pronta (mas painel CSV visível) addManualRow(); })(jQuery);
Save File
Cancel