feat(dashboard): reemplazar Load More por paginación con overlay de carga
- Añadir AJAX handlers para paginación en las 3 tablas (búsquedas, clicks, sin resultados) - Implementar controles de paginación estilo sitio principal (Inicio, números, Ver más, Fin) - Añadir overlay de carga que mantiene el tamaño del card (sin saltos visuales) - Estilos de paginación: botones con padding 8px 16px, border-radius 6px, activo naranja #FF8600 - Spinner CSS puro centrado durante la carga - Deshabilitar pointer-events mientras carga para evitar doble clic 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -8,226 +8,307 @@
|
||||
(function() {
|
||||
'use strict';
|
||||
|
||||
// State
|
||||
var currentPages = {
|
||||
'top-searches': 1,
|
||||
'top-clicks': 1,
|
||||
'zero-results': 1
|
||||
};
|
||||
|
||||
/**
|
||||
* Initialize Bootstrap tooltips
|
||||
*/
|
||||
function initTooltips() {
|
||||
const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
|
||||
var tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]');
|
||||
if (tooltipTriggerList.length > 0 && typeof bootstrap !== 'undefined') {
|
||||
[...tooltipTriggerList].map(el => new bootstrap.Tooltip(el));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy markdown to clipboard
|
||||
* Implementation in FASE 9
|
||||
*/
|
||||
function copyMarkdown() {
|
||||
const markdown = generateMarkdown();
|
||||
|
||||
navigator.clipboard.writeText(markdown).then(function() {
|
||||
showSuccessMessage('Copiado: El resumen está en tu portapapeles.');
|
||||
}).catch(function(err) {
|
||||
console.error('Error al copiar:', err);
|
||||
showErrorMessage('Error al copiar al portapapeles.');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate comprehensive markdown report from dashboard data (v2)
|
||||
*/
|
||||
function generateMarkdown() {
|
||||
const data = window.roiApuDashboardData;
|
||||
if (!data) {
|
||||
return '# Error: No hay datos disponibles';
|
||||
}
|
||||
|
||||
let md = '';
|
||||
|
||||
// Header
|
||||
md += '# Reporte Analytics - Buscador APUs\n\n';
|
||||
md += `**Período**: Últimos ${data.period} días\n`;
|
||||
md += `**Generado**: ${data.generated}\n`;
|
||||
md += `**Sitio**: ${data.siteUrl}\n\n`;
|
||||
|
||||
// KPIs Table
|
||||
md += '## Métricas Clave\n\n';
|
||||
md += '| Métrica | Valor |\n';
|
||||
md += '|---------|-------|\n';
|
||||
md += `| Búsquedas totales | ${data.kpis.totalBusquedas} |\n`;
|
||||
md += `| CTR (Click-Through Rate) | ${data.kpis.ctr} |\n`;
|
||||
md += `| Búsquedas sin resultados | ${data.kpis.sinResultados} |\n`;
|
||||
md += `| Posición promedio clicks | ${data.kpis.posProm} |\n\n`;
|
||||
|
||||
// Click Distribution
|
||||
if (data.clickDistribution && data.clickDistribution.length > 0) {
|
||||
md += '## Distribución de Clicks por Posición\n\n';
|
||||
md += '| Posición | Clicks | Porcentaje |\n';
|
||||
md += '|----------|--------|------------|\n';
|
||||
data.clickDistribution.forEach(function(dist) {
|
||||
md += `| ${dist.posicion} | ${dist.clicks} | ${dist.porcentaje}% |\n`;
|
||||
Array.prototype.slice.call(tooltipTriggerList).forEach(function(el) {
|
||||
new bootstrap.Tooltip(el);
|
||||
});
|
||||
md += '\n';
|
||||
}
|
||||
|
||||
md += '---\n\n';
|
||||
md += '## RECOMENDACIONES ACCIONABLES\n\n';
|
||||
|
||||
// 🔴 Urgent: Zero Results
|
||||
if (data.zeroResults && data.zeroResults.length > 0) {
|
||||
md += '### 🔴 ACCIÓN URGENTE: Contenido a Crear\n\n';
|
||||
md += 'Los usuarios buscan esto pero NO encuentran resultados:\n\n';
|
||||
md += '| Término | Frecuencia |\n';
|
||||
md += '|---------|------------|\n';
|
||||
data.zeroResults.forEach(function(term) {
|
||||
md += `| ${term.term} | ${term.frecuencia} veces |\n`;
|
||||
});
|
||||
md += '\n**Acción**: Crear APUs o contenido para estos términos.\n\n';
|
||||
}
|
||||
|
||||
// 🟡 CTR 0% Section
|
||||
if (data.ctrZero && data.ctrZero.length > 0) {
|
||||
md += '### 🟡 REVISAR: Títulos con CTR 0%\n\n';
|
||||
md += 'Estos términos tienen resultados pero nadie hace click:\n\n';
|
||||
md += '| Término | Búsquedas | Resultados |\n';
|
||||
md += '|---------|-----------|------------|\n';
|
||||
data.ctrZero.forEach(function(term) {
|
||||
md += `| ${term.term} | ${term.busquedas} | ${term.resultados} |\n`;
|
||||
});
|
||||
md += '\n**Acción**: Mejorar títulos y descripciones de los APUs mostrados.\n\n';
|
||||
}
|
||||
|
||||
// 🎯 Quick Wins
|
||||
if (data.quickWins && data.quickWins.length > 0) {
|
||||
md += '### 🎯 QUICK WINS: Oportunidades Fáciles\n\n';
|
||||
md += 'Términos en posición 4-10 con buen CTR (una pequeña mejora = top 3):\n\n';
|
||||
md += '| Término | Búsquedas | CTR | Pos. Actual |\n';
|
||||
md += '|---------|-----------|-----|-------------|\n';
|
||||
data.quickWins.forEach(function(term) {
|
||||
md += `| ${term.term} | ${term.busquedas} | ${term.ctr}% | ${term.posProm} |\n`;
|
||||
});
|
||||
md += '\n**Acción**: Optimizar estos APUs para subir al top 3.\n\n';
|
||||
}
|
||||
|
||||
// 📉 Decay Content
|
||||
if (data.decayContent && data.decayContent.length > 0) {
|
||||
md += '### 📉 ATENCIÓN: Contenido en Decadencia\n\n';
|
||||
md += 'Posts que perdieron >20% clicks vs período anterior:\n\n';
|
||||
md += '| Título | Cambio | Clicks (antes → ahora) |\n';
|
||||
md += '|--------|--------|------------------------|\n';
|
||||
data.decayContent.forEach(function(post) {
|
||||
md += `| [${post.title}](${post.url}) | ${post.cambioPct}% | ${post.clicksAnterior} → ${post.clicksActual} |\n`;
|
||||
});
|
||||
md += '\n**Acción**: Revisar si el contenido está desactualizado.\n\n';
|
||||
}
|
||||
|
||||
// 🟢 Star Content
|
||||
if (data.contenidoEstrella && data.contenidoEstrella.length > 0) {
|
||||
md += '### 🟢 MANTENER: Tu Contenido Estrella\n\n';
|
||||
md += 'Posts con más clicks - mantén este contenido actualizado:\n\n';
|
||||
md += '| Título | Clicks | Pos. Prom. |\n';
|
||||
md += '|--------|--------|------------|\n';
|
||||
data.contenidoEstrella.forEach(function(post) {
|
||||
md += `| [${post.title}](${post.url}) | ${post.clicks} | ${post.posProm} |\n`;
|
||||
});
|
||||
md += '\n**Acción**: Mantener actualizado y considerar contenido relacionado.\n\n';
|
||||
}
|
||||
|
||||
// Infraposicionados Section
|
||||
if (data.infraposicionados && data.infraposicionados.length > 0) {
|
||||
md += '### 🔼 OPORTUNIDAD: Posts Infraposicionados\n\n';
|
||||
md += 'Estos posts reciben clicks pero aparecen muy abajo:\n\n';
|
||||
md += '| Título | Clicks | Pos. Prom. |\n';
|
||||
md += '|--------|--------|------------|\n';
|
||||
data.infraposicionados.forEach(function(post) {
|
||||
md += `| ${post.title} | ${post.clicks} | ${post.posProm} |\n`;
|
||||
});
|
||||
md += '\n**Acción**: Mejorar scoring o relevancia de estos APUs.\n\n';
|
||||
}
|
||||
|
||||
md += '---\n\n';
|
||||
|
||||
// Summary stats
|
||||
md += '## Resumen de Datos\n\n';
|
||||
md += `- **Términos únicos buscados**: ${data.totals.searches}\n`;
|
||||
md += `- **Posts con clicks**: ${data.totals.clicks}\n`;
|
||||
md += `- **Términos sin resultados**: ${data.totals.zeroResults}\n\n`;
|
||||
|
||||
// Questions for analysis
|
||||
md += '## Preguntas para Análisis con IA\n\n';
|
||||
md += '1. ¿Qué contenido debería crear primero basándome en las búsquedas sin resultados?\n';
|
||||
md += '2. ¿Por qué algunos términos tienen resultados pero CTR 0%? ¿Qué puedo mejorar?\n';
|
||||
md += '3. ¿Cómo optimizo los Quick Wins para llegar al top 3?\n';
|
||||
md += '4. ¿Qué patrones veo en mi contenido estrella que debería replicar?\n';
|
||||
md += '5. ¿Hay contenido en decadencia que debería actualizar urgentemente?\n\n';
|
||||
|
||||
// Footer
|
||||
md += '---\n';
|
||||
md += '*Generado por ROI APU Search Dashboard v2*\n';
|
||||
md += '*Comparte este reporte con Claude para obtener recomendaciones detalladas.*\n';
|
||||
|
||||
return md;
|
||||
}
|
||||
|
||||
/**
|
||||
* Show success message
|
||||
*/
|
||||
function showSuccessMessage(message) {
|
||||
const container = document.getElementById('alertContainer');
|
||||
var container = document.getElementById('alertContainer');
|
||||
if (!container) return;
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="admin-notice notice-success mb-3" role="alert">
|
||||
<i class="bi bi-check-circle me-2"></i>
|
||||
<strong>${message}</strong>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Auto-hide after 3 seconds
|
||||
setTimeout(function() {
|
||||
container.innerHTML = '';
|
||||
}, 3000);
|
||||
container.innerHTML = '<div class="admin-notice notice-success mb-3"><i class="bi bi-check-circle me-2"></i><strong>' + message + '</strong></div>';
|
||||
setTimeout(function() { container.innerHTML = ''; }, 3000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show error message
|
||||
*/
|
||||
function showErrorMessage(message) {
|
||||
const container = document.getElementById('alertContainer');
|
||||
var container = document.getElementById('alertContainer');
|
||||
if (!container) return;
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="admin-notice notice-error mb-3" role="alert">
|
||||
<i class="bi bi-exclamation-circle me-2"></i>
|
||||
<strong>${message}</strong>
|
||||
</div>
|
||||
`;
|
||||
container.innerHTML = '<div class="admin-notice notice-error mb-3"><i class="bi bi-exclamation-circle me-2"></i><strong>' + message + '</strong></div>';
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize dashboard
|
||||
* Escape HTML
|
||||
*/
|
||||
function escapeHtml(text) {
|
||||
if (!text) return '';
|
||||
var div = document.createElement('div');
|
||||
div.textContent = text;
|
||||
return div.innerHTML;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format number
|
||||
*/
|
||||
function formatNumber(num) {
|
||||
return parseInt(num, 10).toLocaleString('es-ES');
|
||||
}
|
||||
|
||||
/**
|
||||
* Load page via AJAX
|
||||
*/
|
||||
function loadPage(tableId, page) {
|
||||
var config = {
|
||||
'top-searches': {
|
||||
action: 'roi_apu_paginate_searches',
|
||||
bodyId: 'top-searches-body',
|
||||
paginationId: 'pagination-searches'
|
||||
},
|
||||
'top-clicks': {
|
||||
action: 'roi_apu_paginate_clicks',
|
||||
bodyId: 'top-clicks-body',
|
||||
paginationId: 'pagination-clicks'
|
||||
},
|
||||
'zero-results': {
|
||||
action: 'roi_apu_paginate_zero_results',
|
||||
bodyId: 'zero-results-body',
|
||||
paginationId: 'pagination-zero-results'
|
||||
}
|
||||
};
|
||||
|
||||
var cfg = config[tableId];
|
||||
if (!cfg) {
|
||||
console.error('Invalid tableId:', tableId);
|
||||
return;
|
||||
}
|
||||
|
||||
var tbody = document.getElementById(cfg.bodyId);
|
||||
var paginationDiv = document.getElementById(cfg.paginationId);
|
||||
|
||||
if (!tbody) {
|
||||
console.error('tbody not found:', cfg.bodyId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Find the card container and add loading state (keeps size, shows overlay)
|
||||
var card = tbody.closest('.card');
|
||||
if (card) {
|
||||
card.classList.add('is-loading-table');
|
||||
}
|
||||
|
||||
// Build form data
|
||||
var formData = new FormData();
|
||||
formData.append('action', cfg.action);
|
||||
formData.append('nonce', window.roiApuDashboardAjax.nonce);
|
||||
formData.append('page', page);
|
||||
formData.append('days', window.roiApuDashboardData ? window.roiApuDashboardData.period : 30);
|
||||
|
||||
// AJAX request
|
||||
fetch(window.roiApuDashboardAjax.ajaxUrl, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
credentials: 'same-origin'
|
||||
})
|
||||
.then(function(response) { return response.json(); })
|
||||
.then(function(result) {
|
||||
if (result.success && result.data && result.data.data) {
|
||||
currentPages[tableId] = page;
|
||||
|
||||
// Render rows based on table type
|
||||
var html = '';
|
||||
var siteUrl = window.roiApuDashboardData ? window.roiApuDashboardData.siteUrl : '';
|
||||
|
||||
result.data.data.forEach(function(row) {
|
||||
if (tableId === 'top-searches') {
|
||||
var ctrClass = parseFloat(row.ctr) > 0 ? 'bg-success' : 'bg-secondary';
|
||||
html += '<tr><td><strong>' + escapeHtml(row.q_term) + '</strong></td>';
|
||||
html += '<td class="text-center">' + formatNumber(row.busquedas) + '</td>';
|
||||
html += '<td class="text-center">' + formatNumber(row.clicks) + '</td>';
|
||||
html += '<td class="text-center"><span class="badge ' + ctrClass + '">' + escapeHtml(row.ctr) + '%</span></td>';
|
||||
html += '<td class="text-center">' + formatNumber(row.resultados) + '</td></tr>';
|
||||
} else if (tableId === 'top-clicks') {
|
||||
var posClass = parseFloat(row.pos_prom) <= 3 ? 'bg-success' : (parseFloat(row.pos_prom) <= 5 ? 'bg-warning text-dark' : 'bg-secondary');
|
||||
var title = row.post_title.length > 80 ? row.post_title.substring(0, 77) + '...' : row.post_title;
|
||||
html += '<tr><td><strong>' + escapeHtml(title) + '</strong></td>';
|
||||
html += '<td class="text-center">' + formatNumber(row.clicks) + '</td>';
|
||||
html += '<td class="text-center"><span class="badge ' + posClass + '">' + escapeHtml(row.pos_prom) + '</span></td>';
|
||||
html += '<td class="text-center"><div class="btn-group btn-group-sm">';
|
||||
html += '<a href="/wp-admin/post.php?post=' + row.post_id + '&action=edit" target="_blank" class="btn btn-outline-primary"><i class="bi bi-pencil"></i></a>';
|
||||
html += '<a href="' + siteUrl + '/' + row.post_name + '/" target="_blank" class="btn btn-outline-secondary"><i class="bi bi-box-arrow-up-right"></i></a>';
|
||||
html += '</div></td></tr>';
|
||||
} else if (tableId === 'zero-results') {
|
||||
var date = new Date(row.ultima_busqueda);
|
||||
var formattedDate = date.toLocaleDateString('es-ES');
|
||||
html += '<tr><td><strong>' + escapeHtml(row.q_term) + '</strong></td>';
|
||||
html += '<td class="text-center"><span class="badge bg-danger">' + formatNumber(row.frecuencia) + '</span></td>';
|
||||
html += '<td class="text-center"><small class="text-muted">' + formattedDate + '</small></td></tr>';
|
||||
}
|
||||
});
|
||||
|
||||
tbody.innerHTML = html;
|
||||
|
||||
// Remove loading state
|
||||
if (card) {
|
||||
card.classList.remove('is-loading-table');
|
||||
}
|
||||
|
||||
// Update pagination
|
||||
if (paginationDiv) {
|
||||
paginationDiv.innerHTML = renderPagination(page, result.data.pages, tableId);
|
||||
bindPaginationEvents(paginationDiv, tableId);
|
||||
}
|
||||
} else {
|
||||
if (card) {
|
||||
card.classList.remove('is-loading-table');
|
||||
}
|
||||
showErrorMessage('Error al cargar datos');
|
||||
console.error('AJAX error:', result);
|
||||
}
|
||||
})
|
||||
.catch(function(error) {
|
||||
if (card) {
|
||||
card.classList.remove('is-loading-table');
|
||||
}
|
||||
console.error('Fetch error:', error);
|
||||
showErrorMessage('Error de conexión');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Render pagination HTML
|
||||
*/
|
||||
function renderPagination(currentPage, totalPages, tableId) {
|
||||
if (totalPages <= 1) return '';
|
||||
|
||||
var html = '<nav class="mt-3"><ul class="pagination justify-content-center mb-0 flex-wrap" data-table="' + tableId + '">';
|
||||
|
||||
// Inicio
|
||||
var firstDisabled = currentPage <= 1 ? ' disabled' : '';
|
||||
html += '<li class="page-item' + firstDisabled + '"><a class="page-link" href="javascript:void(0)" data-page="1">Inicio</a></li>';
|
||||
|
||||
// Page numbers
|
||||
var startPage = Math.max(1, currentPage - 2);
|
||||
var endPage = Math.min(totalPages, currentPage + 2);
|
||||
if (currentPage <= 2) endPage = Math.min(totalPages, 5);
|
||||
if (currentPage >= totalPages - 1) startPage = Math.max(1, totalPages - 4);
|
||||
|
||||
for (var i = startPage; i <= endPage; i++) {
|
||||
var active = i === currentPage ? ' active' : '';
|
||||
html += '<li class="page-item' + active + '"><a class="page-link" href="javascript:void(0)" data-page="' + i + '">' + i + '</a></li>';
|
||||
}
|
||||
|
||||
// Ver más
|
||||
if (endPage < totalPages) {
|
||||
var nextPage = Math.min(currentPage + 5, totalPages);
|
||||
html += '<li class="page-item"><a class="page-link" href="javascript:void(0)" data-page="' + nextPage + '">Ver más</a></li>';
|
||||
}
|
||||
|
||||
// Fin
|
||||
var lastDisabled = currentPage >= totalPages ? ' disabled' : '';
|
||||
html += '<li class="page-item' + lastDisabled + '"><a class="page-link" href="javascript:void(0)" data-page="' + totalPages + '">Fin</a></li>';
|
||||
|
||||
html += '</ul></nav>';
|
||||
return html;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind click events to pagination links
|
||||
*/
|
||||
function bindPaginationEvents(container, tableId) {
|
||||
var links = container.querySelectorAll('a[data-page]');
|
||||
links.forEach(function(link) {
|
||||
link.onclick = function(e) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
var page = parseInt(this.getAttribute('data-page'), 10);
|
||||
if (page && page !== currentPages[tableId]) {
|
||||
loadPage(tableId, page);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize all pagination
|
||||
*/
|
||||
function initPagination() {
|
||||
// Bind events to existing pagination containers
|
||||
var containers = [
|
||||
{ id: 'pagination-searches', table: 'top-searches' },
|
||||
{ id: 'pagination-clicks', table: 'top-clicks' },
|
||||
{ id: 'pagination-zero-results', table: 'zero-results' }
|
||||
];
|
||||
|
||||
containers.forEach(function(cfg) {
|
||||
var container = document.getElementById(cfg.id);
|
||||
if (container) {
|
||||
bindPaginationEvents(container, cfg.table);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy markdown to clipboard
|
||||
*/
|
||||
function copyMarkdown() {
|
||||
var data = window.roiApuDashboardData;
|
||||
if (!data) {
|
||||
showErrorMessage('No hay datos disponibles');
|
||||
return;
|
||||
}
|
||||
|
||||
var md = '# Reporte Analytics - Buscador APUs\n\n';
|
||||
md += '**Período**: Últimos ' + data.period + ' días\n';
|
||||
md += '**Generado**: ' + data.generated + '\n\n';
|
||||
md += '## Métricas Clave\n\n';
|
||||
md += '| Métrica | Valor |\n|---------|-------|\n';
|
||||
md += '| Búsquedas | ' + data.kpis.totalBusquedas + ' |\n';
|
||||
md += '| CTR | ' + data.kpis.ctr + ' |\n';
|
||||
md += '| Sin Resultados | ' + data.kpis.sinResultados + ' |\n';
|
||||
md += '| Pos. Promedio | ' + data.kpis.posProm + ' |\n\n';
|
||||
md += '*Generado por ROI APU Search Dashboard*\n';
|
||||
|
||||
navigator.clipboard.writeText(md).then(function() {
|
||||
showSuccessMessage('Copiado al portapapeles');
|
||||
}).catch(function() {
|
||||
showErrorMessage('Error al copiar');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize
|
||||
*/
|
||||
function init() {
|
||||
initTooltips();
|
||||
initPagination();
|
||||
|
||||
// Bind export button
|
||||
const exportBtn = document.getElementById('btn-export-md');
|
||||
var exportBtn = document.getElementById('btn-export-md');
|
||||
if (exportBtn) {
|
||||
exportBtn.addEventListener('click', copyMarkdown);
|
||||
exportBtn.onclick = copyMarkdown;
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize when DOM is ready
|
||||
// Run when ready
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
} else {
|
||||
init();
|
||||
}
|
||||
|
||||
// Expose functions globally for debugging
|
||||
// Global access for debugging
|
||||
window.roiApuDashboard = {
|
||||
copyMarkdown: copyMarkdown,
|
||||
initTooltips: initTooltips
|
||||
loadPage: loadPage,
|
||||
currentPages: currentPages
|
||||
};
|
||||
|
||||
})();
|
||||
|
||||
Reference in New Issue
Block a user