This commit is contained in:
Lizandro Guarnizo
2026-01-12 11:06:43 -05:00
parent ce12ac2cce
commit dd36ed6fe0
110 changed files with 20873 additions and 696 deletions
BIN
View File
Binary file not shown.
+215
View File
@@ -0,0 +1,215 @@
/* Estilos adicionales para el panel de diagnóstico */
.diagnostic-results {
font-size: 0.9em;
}
.diagnostic-results .list-group-item {
background: transparent;
border: none;
border-bottom: 1px solid #e9ecef;
padding: 0.5rem 0;
}
.diagnostic-results .list-group-item:last-child {
border-bottom: none;
}
.diagnostic-results h6 {
color: #495057;
font-size: 0.9em;
margin-bottom: 0.5rem;
border-bottom: 1px solid #e9ecef;
padding-bottom: 0.25rem;
}
.diagnostic-results .badge {
font-size: 0.7em;
min-width: 20px;
}
.diagnostic-results .alert {
margin-bottom: 0;
}
.diagnostic-results .alert small {
margin: 0;
}
.spinner-border-sm {
width: 1rem;
height: 1rem;
}
/* Mejoras en tabs */
.nav-pills .nav-link {
color: #6c757d;
border-radius: 0.5rem;
}
.nav-pills .nav-link.active {
background-color: #0d6efd;
color: white;
}
.nav-pills .nav-link:hover:not(.active) {
background-color: #f8f9fa;
color: #0d6efd;
}
/* Mejoras en cards */
.card {
box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
border: 1px solid rgba(0, 0, 0, 0.125);
}
.card-header {
background-color: #f8f9fa;
border-bottom: 1px solid rgba(0, 0, 0, 0.125);
}
/* Mejoras en modales */
.modal-content {
box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
}
/* Mejoras en alertas */
.alert {
border: none;
border-radius: 0.5rem;
}
/* Estilos para mensajes de chat */
.message-bubble {
max-width: 70%;
margin-bottom: 1rem;
padding: 0.75rem 1rem;
border-radius: 1rem;
position: relative;
}
.message-bubble.outgoing {
background-color: #dcf8c6;
margin-left: auto;
border-bottom-right-radius: 0.25rem;
}
.message-bubble.incoming {
background-color: #ffffff;
border: 1px solid #e9ecef;
margin-right: auto;
border-bottom-left-radius: 0.25rem;
}
.message-meta {
font-size: 0.75rem;
color: #6c757d;
margin-top: 0.25rem;
}
/* Tabla responsive mejorada */
.table-responsive {
border-radius: 0.5rem;
overflow: hidden;
}
.table th {
background-color: #f8f9fa;
border-top: none;
font-weight: 600;
font-size: 0.9em;
}
/* Botones mejorados */
.btn {
border-radius: 0.5rem;
font-weight: 500;
}
.btn-sm {
font-size: 0.8rem;
}
/* Estados de conexión */
.status-indicator {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
margin-right: 0.5rem;
}
.status-indicator.online {
background-color: #28a745;
}
.status-indicator.offline {
background-color: #dc3545;
}
.status-indicator.warning {
background-color: #ffc107;
}
/* Loading states */
.loading-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(255, 255, 255, 0.8);
display: flex;
align-items: center;
justify-content: center;
z-index: 10;
}
/* Responsive improvements */
@media (max-width: 768px) {
.nav-pills {
flex-direction: column;
}
.nav-pills .nav-link {
text-align: center;
margin-bottom: 0.25rem;
}
.message-bubble {
max-width: 85%;
}
.diagnostic-results .row {
text-align: center;
}
.card-body {
padding: 1rem;
}
}
/* Animaciones sutiles */
.card, .btn, .alert {
transition: all 0.2s ease-in-out;
}
.btn:hover {
transform: translateY(-1px);
box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.1);
}
.card:hover {
box-shadow: 0 0.25rem 0.5rem rgba(0, 0, 0, 0.1);
}
/* Mejoras en formularios */
.form-control:focus {
border-color: #86b7fe;
box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}
.form-select:focus {
border-color: #86b7fe;
box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25);
}
+91
View File
@@ -110,6 +110,29 @@ body {
text-align: center;
}
/* Divisor del sidebar */
.sidebar-divider {
margin: 10px 20px;
border-top: 1px solid rgba(255, 255, 255, 0.2);
}
/* Botón de logout en sidebar */
.sidebar-menu .logout-link {
color: rgba(255, 255, 255, 0.7);
background: rgba(220, 53, 69, 0.1);
border-top: 1px solid rgba(220, 53, 69, 0.3);
}
.sidebar-menu .logout-link:hover {
color: white;
background: rgba(220, 53, 69, 0.2);
border-color: rgba(220, 53, 69, 0.4);
}
.sidebar-menu .logout-link::before {
background: #dc3545;
}
/* Main Content */
.main-content {
margin-left: 280px;
@@ -373,6 +396,74 @@ body {
color: white;
}
/* Modal Fallback Styles */
.modal {
position: fixed;
top: 0;
left: 0;
z-index: 1055;
width: 100%;
height: 100%;
overflow-x: hidden;
overflow-y: auto;
outline: 0;
}
.modal.show {
display: block !important;
}
.modal-dialog {
position: relative;
width: auto;
margin: 1.75rem auto;
max-width: 500px;
}
.modal-content {
background: white;
border-radius: 0.375rem;
box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
}
.modal-header {
padding: 1rem;
border-bottom: 1px solid #dee2e6;
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-body {
padding: 1rem;
}
.modal-footer {
padding: 1rem;
border-top: 1px solid #dee2e6;
display: flex;
justify-content: flex-end;
gap: 0.5rem;
}
.modal-backdrop {
position: fixed;
top: 0;
left: 0;
z-index: 1050;
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.5);
}
.btn-close {
background: transparent;
border: none;
font-size: 1.25rem;
cursor: pointer;
padding: 0.25rem;
}
/* Menu Tree */
.menu-tree {
list-style: none;
+420 -27
View File
@@ -24,15 +24,22 @@ class WhatsAppBotManager {
this.refreshStats();
}
}, 30000);
// Verificar sesión cada 5 minutos
setInterval(() => {
this.checkSession();
}, 300000); // 5 minutos
}
setupEventListeners() {
// Navegación de tabs
document.querySelectorAll('.nav-link').forEach(link => {
// Navegación de tabs - solo enlaces que tengan data-tab
document.querySelectorAll('.nav-link[data-tab]').forEach(link => {
link.addEventListener('click', (e) => {
e.preventDefault();
const tabName = link.getAttribute('data-tab');
this.showTab(tabName);
if (tabName) {
this.showTab(tabName);
}
});
});
@@ -165,8 +172,13 @@ class WhatsAppBotManager {
const stats = await this.apiCall('get_stats.php');
this.updateStats(stats);
const recentMessages = await this.apiCall('get_recent_messages.php');
this.updateRecentMessages(recentMessages);
const recentMessagesResponse = await this.apiCall('get_recent_messages.php');
if (recentMessagesResponse && recentMessagesResponse.success && Array.isArray(recentMessagesResponse.data)) {
this.updateRecentMessages(recentMessagesResponse.data);
} else if (recentMessagesResponse && Array.isArray(recentMessagesResponse)) {
// Retrocompatibilidad por si la API devuelve directamente el array
this.updateRecentMessages(recentMessagesResponse);
}
this.updateChart();
} catch (error) {
@@ -275,9 +287,20 @@ class WhatsAppBotManager {
async loadConversations() {
try {
const conversations = await this.apiCall('get_conversations.php');
this.updateConversationsTable(conversations);
const response = await this.apiCall('get_conversations.php');
console.log('Respuesta get_conversations:', response); // Debug
if (response && response.success && Array.isArray(response.data)) {
this.updateConversationsTable(response.data);
} else if (response && Array.isArray(response)) {
// Retrocompatibilidad por si la API devuelve directamente el array
this.updateConversationsTable(response);
} else {
console.error('Formato de respuesta inesperado:', response);
this.showError('Error: formato de datos inválido para conversaciones');
}
} catch (error) {
console.error('Error en loadConversations:', error);
this.showError('Error cargando conversaciones: ' + error.message);
}
}
@@ -288,6 +311,19 @@ class WhatsAppBotManager {
tbody.innerHTML = '';
console.log('Datos para tabla de conversaciones:', conversations); // Debug
if (!Array.isArray(conversations)) {
console.error('conversations no es un array:', typeof conversations, conversations);
tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">Error: datos inválidos</td></tr>';
return;
}
if (conversations.length === 0) {
tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">No hay conversaciones</td></tr>';
return;
}
conversations.forEach(conv => {
const row = this.createConversationRow(conv);
tbody.appendChild(row);
@@ -327,8 +363,15 @@ class WhatsAppBotManager {
async loadUsers() {
try {
const users = await this.apiCall('get_users.php');
this.updateUsersTable(users);
const response = await this.apiCall('get_users.php');
if (response && response.success && Array.isArray(response.data)) {
this.updateUsersTable(response.data);
} else if (response && Array.isArray(response)) {
// Retrocompatibilidad por si la API devuelve directamente el array
this.updateUsersTable(response);
} else {
this.showError('Error: formato de datos inválido para usuarios');
}
} catch (error) {
this.showError('Error cargando usuarios: ' + error.message);
}
@@ -373,7 +416,14 @@ class WhatsAppBotManager {
async loadMenus() {
try {
const menus = await this.apiCall('get_menus.php');
const response = await this.apiCall('get_menus.php');
let menus = response;
if (response && response.success && Array.isArray(response.data)) {
menus = response.data;
} else if (!Array.isArray(response)) {
this.showError('Error: formato de datos inválido para menús');
return;
}
this.updateMenusTree(menus);
this.loadMenuParents(menus);
} catch (error) {
@@ -457,8 +507,18 @@ class WhatsAppBotManager {
async loadMessageUsers() {
try {
const users = await this.apiCall('get_users.php');
const templates = await this.apiCall('get_templates.php');
const usersResponse = await this.apiCall('get_users.php');
const templatesResponse = await this.apiCall('get_templates.php');
let users = usersResponse;
if (usersResponse && usersResponse.success && Array.isArray(usersResponse.data)) {
users = usersResponse.data;
}
let templates = templatesResponse;
if (templatesResponse && templatesResponse.success && Array.isArray(templatesResponse.data)) {
templates = templatesResponse.data;
}
this.updateMessageUserSelect(users);
this.updateTemplateSelect(templates);
@@ -512,16 +572,39 @@ class WhatsAppBotManager {
}
async sendMessage() {
const recipient = document.getElementById('message-recipient').value;
const recipientType = document.getElementById('recipient-type').value;
const messageType = document.getElementById('message-type').value;
let recipient;
if (recipientType === 'existing') {
recipient = document.getElementById('message-recipient').value;
} else {
recipient = document.getElementById('manual-recipient').value.trim();
// Para números manuales, solo permitir plantillas
if (messageType !== 'template') {
this.showError('Para números manuales solo se pueden enviar plantillas aprobadas');
return;
}
}
const messageText = document.getElementById('message-text').value;
const template = document.getElementById('message-template').value;
if (!recipient) {
this.showError('Por favor selecciona un destinatario');
this.showError('Por favor ingresa un destinatario');
return;
}
// Validar formato de número manual
if (recipientType === 'manual') {
const phoneRegex = /^\+\d{10,15}$/;
if (!phoneRegex.test(recipient)) {
this.showError('El número debe tener el formato: +57XXXXXXXXX (10-15 dígitos)');
return;
}
}
const data = {
recipient: recipient,
type: messageType
@@ -548,6 +631,30 @@ class WhatsAppBotManager {
if (result.success) {
this.showSuccess('Mensaje enviado correctamente');
document.getElementById('send-message-form').reset();
// Resetear la interfaz
this.resetMessageForm();
// Actualizar conversaciones si es necesario
if (this.currentTab === 'conversations') {
this.loadConversations();
}
} else {
this.showError(result.error || 'Error enviando mensaje');
}
} catch (error) {
this.showError('Error enviando mensaje: ' + error.message);
} finally {
this.hideLoading();
}
}
resetMessageForm() {
document.getElementById('recipient-type').value = 'existing';
document.getElementById('message-type').value = 'text';
toggleRecipientType();
toggleMessageType();
}
} else {
this.showError(result.error || 'Error enviando mensaje');
}
@@ -661,8 +768,15 @@ class WhatsAppBotManager {
async loadLogs() {
try {
const logs = await this.apiCall('get_logs.php');
this.updateLogsTable(logs);
const response = await this.apiCall('get_logs.php');
if (response && response.success && Array.isArray(response.data)) {
this.updateLogsTable(response.data);
} else if (response && Array.isArray(response)) {
// Retrocompatibilidad por si la API devuelve directamente el array
this.updateLogsTable(response);
} else {
this.showError('Error: formato de datos inválido para logs');
}
} catch (error) {
this.showError('Error cargando logs: ' + error.message);
}
@@ -710,6 +824,7 @@ class WhatsAppBotManager {
method: method,
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest' // Para identificar peticiones AJAX
}
};
@@ -717,13 +832,51 @@ class WhatsAppBotManager {
options.body = JSON.stringify(data);
}
const response = await fetch(this.apiBaseUrl + endpoint, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
try {
const response = await fetch(this.apiBaseUrl + endpoint, options);
// Verificar si es error de autenticación (401)
if (response.status === 401) {
try {
const errorData = await response.json();
if (errorData.redirect) {
this.showError(errorData.error || 'Sesión expirada. Redirigiendo al login...');
setTimeout(() => {
window.location.href = errorData.redirect;
}, 2000);
return null;
}
} catch (e) {
// Si no puede parsear JSON, redirigir al login
this.showError('Sesión expirada. Redirigiendo al login...');
setTimeout(() => {
window.location.href = 'login.php';
}, 2000);
return null;
}
}
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.json();
const result = await response.json();
// Verificar si la respuesta indica problemas de autenticación
if (result.success === false && result.redirect) {
this.showError(result.error || 'Sesión expirada. Redirigiendo al login...');
setTimeout(() => {
window.location.href = result.redirect;
}, 2000);
return null;
}
return result;
} catch (error) {
console.error('Error en apiCall:', error);
throw error;
}
}
showError(message) {
@@ -832,6 +985,26 @@ class WhatsAppBotManager {
}
// Funciones específicas
searchConversations(query) {
// Función de búsqueda de conversaciones
const tbody = document.getElementById('conversations-table');
if (!tbody) return;
const rows = tbody.getElementsByTagName('tr');
const searchTerm = query.toLowerCase();
for (let row of rows) {
const phoneNumber = row.cells[0]?.textContent?.toLowerCase() || '';
const lastMessage = row.cells[1]?.textContent?.toLowerCase() || '';
if (phoneNumber.includes(searchTerm) || lastMessage.includes(searchTerm)) {
row.style.display = '';
} else {
row.style.display = 'none';
}
}
}
refreshData() {
this.loadTabData(this.currentTab);
this.showSuccess('Datos actualizados');
@@ -900,13 +1073,233 @@ class WhatsAppBotManager {
refreshLogs() {
this.loadLogs();
}
async loadTemplates() {
try {
const response = await this.apiCall('get_templates.php');
if (response && response.success && Array.isArray(response.data)) {
this.updateTemplatesTable(response.data);
} else if (response && Array.isArray(response)) {
// Retrocompatibilidad por si la API devuelve directamente el array
this.updateTemplatesTable(response);
} else {
this.showError('Error: formato de datos inválido para plantillas');
}
} catch (error) {
this.showError('Error cargando plantillas: ' + error.message);
}
}
updateTemplatesTable(templates) {
const tbody = document.getElementById('templates-table');
if (!tbody) return;
tbody.innerHTML = '';
if (templates && templates.length > 0) {
templates.forEach(template => {
const row = this.createTemplateRow(template);
tbody.appendChild(row);
});
} else {
tbody.innerHTML = '<tr><td colspan="6" class="text-center text-muted">No hay plantillas registradas</td></tr>';
}
}
createTemplateRow(template) {
const tr = document.createElement('tr');
const statusBadge = this.getStatusBadge(template.status);
tr.innerHTML = `
<td>${template.name}</td>
<td><code>${template.template_name}</code></td>
<td>${template.language_code.toUpperCase()}</td>
<td>
<span class="badge bg-secondary">${template.category}</span>
</td>
<td>${statusBadge}</td>
<td>
<div class="btn-group btn-group-sm">
<button class="btn btn-outline-primary" onclick="app.editTemplate(${template.id})" title="Editar">
<i class="fas fa-edit"></i>
</button>
<button class="btn btn-outline-danger" onclick="app.deleteTemplate(${template.id})" title="Eliminar">
<i class="fas fa-trash"></i>
</button>
</div>
</td>
`;
return tr;
}
getStatusBadge(status) {
const badges = {
'approved': '<span class="badge bg-success">Aprobada</span>',
'pending': '<span class="badge bg-warning">Pendiente</span>',
'rejected': '<span class="badge bg-danger">Rechazada</span>'
};
return badges[status] || '<span class="badge bg-secondary">Desconocido</span>';
}
async saveTemplate() {
const formData = {
name: document.getElementById('template-name').value.trim(),
template_name: document.getElementById('template-whatsapp-name').value.trim(),
language_code: document.getElementById('template-language').value,
category: document.getElementById('template-category').value
};
if (!formData.name || !formData.template_name) {
this.showError('Por favor complete todos los campos requeridos');
return;
}
try {
this.showLoading('Guardando plantilla...');
const result = await this.apiCall('save_template.php', 'POST', formData);
if (result.success) {
this.showSuccess(result.message);
document.getElementById('template-form').reset();
// Cerrar modal
const modal = bootstrap.Modal.getInstance(document.getElementById('createTemplateModal'));
modal.hide();
// Recargar plantillas
this.loadTemplates();
} else {
this.showError(result.error || 'Error guardando plantilla');
}
} catch (error) {
this.showError('Error guardando plantilla: ' + error.message);
} finally {
this.hideLoading();
}
}
async editTemplate(templateId) {
// Por ahora, solo permitir cambiar el estado
const status = prompt('Cambiar estado de la plantilla:\n- pending (Pendiente)\n- approved (Aprobada)\n- rejected (Rechazada)', 'approved');
if (!status || !['pending', 'approved', 'rejected'].includes(status)) {
return;
}
try {
this.showLoading('Actualizando plantilla...');
const result = await this.apiCall('update_template_status.php', 'POST', {
id: templateId,
status: status
});
if (result.success) {
this.showSuccess(result.message);
this.loadTemplates();
} else {
this.showError(result.error || 'Error actualizando plantilla');
}
} catch (error) {
this.showError('Error actualizando plantilla: ' + error.message);
} finally {
this.hideLoading();
}
}
async deleteTemplate(templateId) {
if (!confirm('¿Estás seguro de que deseas eliminar esta plantilla?')) {
return;
}
try {
this.showLoading('Eliminando plantilla...');
// Por ahora usaremos update_template_status para marcar como eliminada
// En el futuro se puede crear delete_template.php
this.showError('Función de eliminar aún no implementada');
} catch (error) {
this.showError('Error eliminando plantilla: ' + error.message);
} finally {
this.hideLoading();
}
}
// Método para verificar el estado de la sesión
async checkSession() {
try {
const result = await this.apiCall('get_stats.php');
// Si la llamada es exitosa, la sesión está activa
if (!result) {
// La función apiCall ya manejó la redirección al login
return false;
}
return true;
} catch (error) {
console.warn('Error verificando sesión:', error);
// No mostrar error, solo en caso de problemas de red
return false;
}
}
}
// Inicializar la aplicación
const app = new WhatsAppBotManager();
// Funciones globales
window.refreshData = () => app.refreshData();
window.exportUsers = () => app.exportUsers();
window.refreshLogs = () => app.refreshLogs();
window.clearLogs = () => app.clearLogs();
// Funciones globales - usando function declarations para evitar problemas con SES
window.refreshData = function() {
if (typeof app !== 'undefined') app.refreshData();
};
window.exportUsers = function() {
if (typeof app !== 'undefined') app.exportUsers();
};
window.refreshLogs = function() {
if (typeof app !== 'undefined') app.refreshLogs();
};
window.clearLogs = function() {
if (typeof app !== 'undefined') app.clearLogs();
};
// Las funciones de modales se definen ahora en el HTML para evitar problemas con SES
// window.showCreateTemplateModal y window.showCreateMenuModal están en index.php
window.toggleRecipientType = () => {
const recipientType = document.getElementById('recipient-type').value;
const existingGroup = document.getElementById('existing-recipient-group');
const manualGroup = document.getElementById('manual-recipient-group');
const messageTypeSelect = document.getElementById('message-type');
if (recipientType === 'existing') {
existingGroup.style.display = 'block';
manualGroup.style.display = 'none';
// Habilitar todas las opciones
messageTypeSelect.innerHTML = `
<option value="text">Texto</option>
<option value="template">Plantilla</option>
`;
} else {
existingGroup.style.display = 'none';
manualGroup.style.display = 'block';
// Solo permitir plantillas para números manuales
messageTypeSelect.innerHTML = `
<option value="template">Plantilla (Solo opción disponible)</option>
`;
messageTypeSelect.value = 'template';
toggleMessageType(); // Actualizar la interfaz
}
};
// Funciones movidas al HTML inline para evitar problemas con SES
// window.showCreateMenuModal y window.saveNewMenu están ahora en index.php
window.toggleMessageType = function() {
const messageType = document.getElementById('message-type').value;
const textGroup = document.getElementById('message-text-group');
const templateGroup = document.getElementById('template-group');
if (messageType === 'text') {
textGroup.style.display = 'block';
templateGroup.style.display = 'none';
} else {
textGroup.style.display = 'none';
templateGroup.style.display = 'block';
}
};
+968
View File
@@ -0,0 +1,968 @@
/**
* WhatsApp Bot Manager - JavaScript Simplificado
* Versión sin librerías externas problemáticas
*/
class SimpleWhatsAppManager {
constructor() {
this.apiBaseUrl = './api/';
this.currentTab = 'dashboard';
this.init();
}
init() {
this.log('Iniciando sistema simplificado');
this.setupEventListeners();
this.loadDashboard();
}
log(message, type = 'info') {
const timestamp = new Date().toLocaleTimeString();
console.log(`[${timestamp}] [${type.toUpperCase()}] ${message}`);
}
setupEventListeners() {
this.log('Configurando event listeners');
// Navegación de tabs - más defensiva
const navLinks = document.querySelectorAll('.nav-link[data-tab]');
if (navLinks) {
navLinks.forEach(link => {
link.addEventListener('click', (e) => {
e.preventDefault();
const tabName = link.getAttribute('data-tab');
if (tabName) {
this.showTab(tabName);
}
});
});
}
// Formularios
this.setupFormListeners();
}
setupFormListeners() {
// Formulario de configuración
const settingsForm = document.getElementById('settings-form');
if (settingsForm) {
settingsForm.addEventListener('submit', (e) => {
e.preventDefault();
this.saveSettings();
});
}
// Formulario de envío de mensaje
const sendForm = document.getElementById('send-message-form');
if (sendForm) {
sendForm.addEventListener('submit', (e) => {
e.preventDefault();
this.sendMessage();
});
}
}
showTab(tabName) {
this.log(`Cambiando a tab: ${tabName}`);
// Ocultar todas las pestañas
const tabs = document.querySelectorAll('.tab-content');
if (tabs) {
tabs.forEach(tab => tab.classList.remove('active'));
}
// Remover clase active de navegación
const navLinks = document.querySelectorAll('.nav-link');
if (navLinks) {
navLinks.forEach(link => link.classList.remove('active'));
}
// Mostrar pestaña seleccionada
const targetTab = document.getElementById(tabName);
if (targetTab) {
targetTab.classList.add('active');
}
// Activar enlace de navegación
const activeLink = document.querySelector(`[data-tab="${tabName}"]`);
if (activeLink) {
activeLink.classList.add('active');
}
this.currentTab = tabName;
this.loadTabData(tabName);
}
loadTabData(tabName) {
this.log(`Cargando datos para tab: ${tabName}`);
switch (tabName) {
case 'dashboard':
this.loadDashboard();
break;
case 'conversations':
this.loadConversations();
break;
case 'users':
this.loadUsers();
break;
case 'messages':
this.loadMessages();
break;
case 'templates':
this.loadTemplates();
break;
case 'settings':
this.loadSettings();
break;
default:
this.log(`Tab no reconocido: ${tabName}`, 'warning');
}
}
async apiCall(endpoint, options = {}) {
const url = `${this.apiBaseUrl}${endpoint}${endpoint.includes('?') ? '&' : '?'}debug=true`;
this.log(`API Call: ${url}`, 'info');
try {
const response = await fetch(url, {
method: options.method || 'GET',
headers: {
'Content-Type': 'application/json',
...options.headers
},
body: options.body ? JSON.stringify(options.body) : undefined
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
this.log(`API Response: ${JSON.stringify(data).substring(0, 100)}...`, 'success');
return data;
} catch (error) {
this.log(`API Error: ${error.message}`, 'error');
this.showError('Error en petición: ' + error.message);
throw error;
}
}
async apiCallReal(endpoint, options = {}) {
const url = `${this.apiBaseUrl}${endpoint}`;
this.log(`API Call (REAL): ${url}`, 'info');
try {
const response = await fetch(url, {
method: options.method || 'GET',
headers: {
'Content-Type': 'application/json',
...options.headers
},
body: options.body ? JSON.stringify(options.body) : undefined
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
this.log(`API Response (REAL): ${JSON.stringify(data).substring(0, 100)}...`, 'success');
return data;
} catch (error) {
this.log(`API Error (REAL): ${error.message}`, 'error');
this.showError('Error en petición real: ' + error.message);
throw error;
}
}
async loadDashboard() {
this.log('Cargando dashboard');
try {
// Cargar estadísticas básicas
const stats = await this.apiCall('manage_config.php?action=status');
this.updateStats(stats);
} catch (error) {
this.showError('Error cargando dashboard: ' + error.message);
}
}
updateStats(response) {
if (response && response.success && response.data) {
const data = response.data;
// Actualizar elementos del dashboard si existen
const elements = [
{ id: 'total-users', value: data.total_configs || 0 },
{ id: 'messages-today', value: data.whatsapp_configured ? 'Configurado' : 'Sin configurar' },
{ id: 'active-users', value: data.database_migrated ? 'Migrada' : 'Pendiente' },
{ id: 'total-messages', value: data.installation_completed ? 'Completada' : 'Pendiente' }
];
elements.forEach(item => {
const element = document.getElementById(item.id);
if (element) {
element.textContent = item.value;
}
});
}
}
async loadUsers() {
this.log('Cargando usuarios');
try {
const response = await this.apiCall('get_users.php');
if (response && response.success) {
this.updateUsersList(response.data || []);
} else {
this.showError('No se pudieron cargar los usuarios');
}
} catch (error) {
this.showError('Error cargando usuarios: ' + error.message);
}
}
updateUsersList(users) {
const container = document.getElementById('users-table');
if (!container) return;
if (users.length === 0) {
container.innerHTML = '<tr><td colspan="7" class="text-center text-muted">No hay usuarios registrados</td></tr>';
return;
}
let html = '';
users.forEach(user => {
const createdDate = new Date(user.created_at);
const formatDate = createdDate.toLocaleDateString() + ' ' + createdDate.toLocaleTimeString('es', { hour: '2-digit', minute: '2-digit' });
html += `
<tr>
<td>${user.id}</td>
<td>${user.phone_number}</td>
<td>${user.name || 'Sin nombre'}</td>
<td><span class="badge bg-${user.status === 'active' ? 'success' : 'secondary'}">${user.status}</span></td>
<td>${user.current_menu || 'Sin menú'}</td>
<td>${formatDate}</td>
<td>
<button class="btn btn-sm btn-outline-primary me-1" onclick="editUser(${user.id})">
<i class="fas fa-edit"></i>
</button>
<button class="btn btn-sm btn-outline-danger" onclick="deleteUser(${user.id})">
<i class="fas fa-trash"></i>
</button>
</td>
</tr>
`;
});
container.innerHTML = html;
}
async loadConversations() {
this.log('Cargando conversaciones');
try {
const response = await this.apiCall('get_conversations.php');
if (response && response.success) {
this.updateConversationsList(response.data || []);
} else {
this.showError('No se pudieron cargar las conversaciones');
}
} catch (error) {
this.showError('Error cargando conversaciones: ' + error.message);
}
}
updateConversationsList(conversations) {
const container = document.getElementById('conversations-table');
if (!container) return;
if (conversations.length === 0) {
container.innerHTML = '<tr><td colspan="6" class="text-center text-muted">No hay conversaciones</td></tr>';
return;
}
let html = '';
conversations.forEach(conv => {
const date = new Date(conv.created_at);
const formatDate = date.toLocaleDateString() + ' ' + date.toLocaleTimeString('es', { hour: '2-digit', minute: '2-digit' });
html += `
<tr>
<td>
<div>
<strong>${conv.name || conv.phone_number}</strong><br>
<small class="text-muted">${conv.phone_number}</small>
</div>
</td>
<td>
<div style="max-width: 200px; overflow: hidden; text-overflow: ellipsis;">
${conv.content || 'Sin contenido'}
</div>
</td>
<td><span class="badge bg-info">${conv.message_type || 'text'}</span></td>
<td><span class="badge bg-${conv.status === 'sent' ? 'success' : 'warning'}">${conv.status || 'unknown'}</span></td>
<td>${formatDate}</td>
<td>
<button class="btn btn-sm btn-outline-primary" onclick="viewConversation(${conv.user_id})">
<i class="fas fa-eye"></i> Ver
</button>
</td>
</tr>
`;
});
container.innerHTML = html;
}
async loadSettings() {
this.log('Cargando configuraciones');
try {
const response = await this.apiCall('manage_config.php?action=whatsapp');
if (response && response.success) {
this.updateSettingsForm(response.data);
}
} catch (error) {
this.showError('Error cargando configuraciones: ' + error.message);
}
}
updateSettingsForm(data) {
if (!data) return;
const fields = [
{ id: 'whatsapp-token', value: data.token },
{ id: 'phone-number-id', value: data.phone_number_id },
{ id: 'webhook-token', value: data.webhook_verify_token },
{ id: 'business-name', value: data.business_name },
{ id: 'welcome-message', value: data.welcome_message }
];
fields.forEach(field => {
const element = document.getElementById(field.id);
if (element && field.value) {
element.value = field.value;
this.log(`Campo ${field.id} actualizado con valor: ${field.value}`);
} else {
this.log(`Campo ${field.id} no encontrado o sin valor`, 'warning');
}
});
}
async saveSettings() {
this.log('Guardando configuraciones');
const settings = {
token: document.getElementById('whatsapp-token').value,
phone_number_id: document.getElementById('phone-number-id').value,
webhook_verify_token: document.getElementById('webhook-token').value,
business_name: document.getElementById('business-name').value,
welcome_message: document.getElementById('welcome-message').value
};
try {
const response = await this.apiCall('manage_config.php?action=save_whatsapp', {
method: 'POST',
body: { whatsapp: settings }
});
if (response && response.success) {
this.showSuccess('Configuraciones guardadas exitosamente');
} else {
this.showError('Error guardando configuraciones');
}
} catch (error) {
this.showError('Error: ' + error.message);
}
}
showError(message) {
this.log(`Error: ${message}`, 'error');
this.showAlert(message, 'danger');
}
showSuccess(message) {
this.log(`Success: ${message}`, 'success');
this.showAlert(message, 'success');
}
showAlert(message, type) {
// Crear alerta temporal
const alertDiv = document.createElement('div');
alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
alertDiv.innerHTML = `
${message}
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
`;
document.body.appendChild(alertDiv);
// Auto-remover después de 5 segundos
setTimeout(() => {
if (alertDiv.parentNode) {
alertDiv.parentNode.removeChild(alertDiv);
}
}, 5000);
}
async loadMessages() {
this.log('Cargando interfaz de mensajes');
try {
// Cargar usuarios para el select
const usersResponse = await this.apiCall('get_users.php');
if (usersResponse && usersResponse.success) {
this.populateUsersSelect(usersResponse.data || []);
}
// Cargar plantillas para el select
const templatesResponse = await this.apiCall('get_templates.php');
if (templatesResponse && templatesResponse.success) {
this.populateTemplatesSelect(templatesResponse.data || []);
}
} catch (error) {
this.showError('Error cargando datos para mensajes: ' + error.message);
}
}
populateUsersSelect(users) {
const select = document.getElementById('message-recipient');
if (!select) return;
// Limpiar opciones existentes (excepto la primera)
select.innerHTML = '<option value="">Seleccionar usuario...</option>';
// Agregar usuarios
users.forEach(user => {
const option = document.createElement('option');
option.value = user.id;
option.textContent = `${user.name || user.phone_number} (${user.phone_number})`;
select.appendChild(option);
});
}
populateTemplatesSelect(templates) {
const select = document.getElementById('message-template');
if (!select) return;
// Limpiar opciones existentes (excepto la primera)
select.innerHTML = '<option value="">Seleccionar plantilla...</option>';
// Agregar plantillas
templates.forEach(template => {
const option = document.createElement('option');
option.value = template.template_name;
option.textContent = `${template.name} - ${template.category || 'Sin descripción'}`;
select.appendChild(option);
});
}
async loadTemplates() {
this.log('Cargando plantillas');
try {
const response = await this.apiCall('get_templates.php');
if (response && response.success) {
this.updateTemplatesList(response.data || []);
} else {
this.showError('Error cargando plantillas');
}
} catch (error) {
this.showError('Error cargando plantillas: ' + error.message);
}
}
updateTemplatesList(templates) {
const container = document.getElementById('templates-table');
if (!container) return;
if (templates.length === 0) {
container.innerHTML = '<tr><td colspan="6" class="text-center text-muted">No hay plantillas registradas</td></tr>';
return;
}
let html = '';
templates.forEach(template => {
html += `
<tr>
<td><strong>${template.name}</strong></td>
<td><code>${template.template_name}</code></td>
<td>${template.language_code || 'es'}</td>
<td><span class="badge bg-info">${template.category || 'utility'}</span></td>
<td><span class="badge bg-${template.status === 'approved' ? 'success' : 'warning'}">${template.status || 'pending'}</span></td>
<td>
<button class="btn btn-sm btn-outline-primary me-1" onclick="editTemplate(${template.id})">
<i class="fas fa-edit"></i>
</button>
<button class="btn btn-sm btn-outline-danger" onclick="deleteTemplate(${template.id})">
<i class="fas fa-trash"></i>
</button>
</td>
</tr>
`;
});
container.innerHTML = html;
}
async saveTemplate() {
this.log('Guardando plantilla');
try {
const templateData = {
name: document.getElementById('template-name').value,
whatsapp_name: document.getElementById('template-whatsapp-name').value,
language: document.getElementById('template-language').value,
category: document.getElementById('template-category').value
};
// Validar campos requeridos
if (!templateData.name || !templateData.whatsapp_name) {
this.showError('Nombre descriptivo y nombre de WhatsApp son requeridos');
return;
}
const response = await this.apiCall('save_template.php', {
method: 'POST',
body: templateData
});
if (response && response.success) {
this.showSuccess('Plantilla guardada correctamente');
// Cerrar modal
const modal = document.getElementById('createTemplateModal');
if (modal) {
const bsModal = bootstrap.Modal.getInstance(modal);
if (bsModal) bsModal.hide();
}
// Limpiar formulario
document.getElementById('template-form').reset();
// Recargar plantillas
this.loadTemplates();
} else {
this.showError(`Error guardando plantilla: ${response?.error || 'Error desconocido'}`);
}
} catch (error) {
this.showError('Error guardando plantilla: ' + error.message);
}
}
async sendMessage() {
this.log('Enviando mensaje');
try {
const recipientType = document.getElementById('recipient-type').value;
const messageType = document.getElementById('message-type').value;
let recipient;
let messageData = {};
// Obtener destinatario
if (recipientType === 'existing') {
const userSelect = document.getElementById('message-recipient');
if (!userSelect.value) {
this.showError('Por favor selecciona un usuario');
return;
}
// Obtener datos del usuario seleccionado
const selectedOption = userSelect.options[userSelect.selectedIndex];
const userId = userSelect.value;
// Necesitamos obtener el número de teléfono del usuario
const usersResponse = await this.apiCall('get_users.php');
if (usersResponse && usersResponse.success) {
const user = usersResponse.data.find(u => u.id == userId);
if (user) {
recipient = user.phone_number;
} else {
this.showError('Usuario no encontrado');
return;
}
} else {
this.showError('Error obteniendo datos del usuario');
return;
}
} else {
recipient = document.getElementById('manual-recipient').value;
if (!recipient) {
this.showError('Por favor ingresa un número de teléfono');
return;
}
}
// Preparar mensaje según el tipo
if (messageType === 'text') {
const messageText = document.getElementById('message-text').value;
if (!messageText) {
this.showError('Por favor escribe un mensaje');
return;
}
messageData = {
recipient: recipient,
type: 'text',
message: messageText
};
} else {
const templateSelect = document.getElementById('message-template');
if (!templateSelect.value) {
this.showError('Por favor selecciona una plantilla');
return;
}
messageData = {
recipient: recipient,
type: 'template',
template_name: templateSelect.value
};
}
this.log(`Enviando mensaje a ${recipient}: ${JSON.stringify(messageData)}`);
// Preguntar al usuario si quiere envío real o simulado
const sendReal = confirm('¿Enviar mensaje REAL por WhatsApp?\n\nSí = Envío real\nNo = Envío simulado (debug)');
// Enviar mensaje
const response = sendReal
? await this.apiCallReal('send_message.php', {
method: 'POST',
body: messageData
})
: await this.apiCall('send_message.php', {
method: 'POST',
body: messageData
});
if (response && response.success) {
this.showSuccess(`Mensaje enviado correctamente a ${recipient}`);
// Limpiar formulario
document.getElementById('send-message-form').reset();
document.getElementById('message-recipient').value = '';
} else {
this.showError(`Error enviando mensaje: ${response?.error || 'Error desconocido'}`);
}
} catch (error) {
this.showError('Error enviando mensaje: ' + error.message);
}
}
}
// Inicializar cuando el DOM esté listo
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM cargado, inicializando WhatsApp Manager...');
try {
window.whatsappManager = new SimpleWhatsAppManager();
console.log('WhatsApp Manager inicializado correctamente');
} catch (error) {
console.error('Error inicializando WhatsApp Manager:', error);
}
});
// Funciones globales para modales (compatibilidad con el HTML existente)
window.openCreateTemplateModal = function() {
console.log('🔵 Abriendo modal de plantilla...');
const modalElement = document.getElementById('createTemplateModal');
if (!modalElement) {
console.error('❌ Modal de plantilla no encontrado');
return;
}
try {
const form = document.getElementById('template-form');
if (form) form.reset();
if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
const modal = new bootstrap.Modal(modalElement);
modal.show();
} else {
modalElement.style.display = 'block';
modalElement.classList.add('show');
}
console.log('✅ Modal de plantilla abierto');
} catch (error) {
console.error('❌ Error abriendo modal de plantilla:', error);
}
};
window.openCreateMenuModal = function() {
console.log('🔵 Abriendo modal de menú...');
const modalElement = document.getElementById('createMenuModal');
if (!modalElement) {
console.error('❌ Modal de menú no encontrado');
return;
}
try {
const form = document.getElementById('menu-form');
if (form) form.reset();
if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
const modal = new bootstrap.Modal(modalElement);
modal.show();
} else {
modalElement.style.display = 'block';
modalElement.classList.add('show');
}
console.log('✅ Modal de menú abierto');
} catch (error) {
console.error('❌ Error abriendo modal de menú:', error);
}
};
// Función global para debugging
window.debugAPI = async function(endpoint) {
try {
const manager = window.whatsappManager;
if (manager) {
const result = await manager.apiCall(endpoint);
console.log('Debug API Result:', result);
return result;
} else {
console.error('Manager no inicializado');
}
} catch (error) {
console.error('Debug API Error:', error);
}
};
// Función para ver conversación específica
window.viewConversation = function(userId) {
console.log('Viendo conversación del usuario:', userId);
alert(`Ver conversación del usuario ${userId} - Función en desarrollo`);
};
// Función para editar usuario
window.editUser = function(userId) {
console.log('Editando usuario:', userId);
alert(`Editar usuario ${userId} - Función en desarrollo`);
};
// Función para eliminar usuario
window.deleteUser = function(userId) {
console.log('Eliminando usuario:', userId);
if (confirm(`¿Está seguro que desea eliminar el usuario ${userId}?`)) {
alert(`Eliminar usuario ${userId} - Función en desarrollo`);
}
};
// Funciones para plantillas
window.showCreateTemplateModal = function() {
const modal = new bootstrap.Modal(document.getElementById('createTemplateModal'));
modal.show();
};
window.editTemplate = function(templateId) {
console.log('Editando plantilla:', templateId);
alert(`Editar plantilla ${templateId} - Función en desarrollo`);
};
window.deleteTemplate = function(templateId) {
console.log('Eliminando plantilla:', templateId);
if (confirm(`¿Está seguro que desea eliminar la plantilla ${templateId}?`)) {
alert(`Eliminar plantilla ${templateId} - Función en desarrollo`);
}
};
// Hacer que app.saveTemplate() funcione
window.app = {
saveTemplate: function() {
if (window.whatsappManager) {
window.whatsappManager.saveTemplate();
}
}
};
// Funciones para el formulario de mensajes
window.toggleRecipientType = function() {
const recipientType = document.getElementById('recipient-type').value;
const existingGroup = document.getElementById('existing-recipient-group');
const manualGroup = document.getElementById('manual-recipient-group');
if (recipientType === 'manual') {
existingGroup.style.display = 'none';
manualGroup.style.display = 'block';
} else {
existingGroup.style.display = 'block';
manualGroup.style.display = 'none';
}
};
window.toggleMessageType = function() {
const messageType = document.getElementById('message-type').value;
const textGroup = document.getElementById('message-text-group');
const templateGroup = document.getElementById('template-group');
if (messageType === 'template') {
textGroup.style.display = 'none';
templateGroup.style.display = 'block';
} else {
textGroup.style.display = 'block';
templateGroup.style.display = 'none';
}
};
// Función de diagnóstico
window.runDiagnostic = function() {
const resultsDiv = document.getElementById('diagnostic-results');
// Mostrar spinner de carga
resultsDiv.innerHTML = `
<div class="text-center">
<div class="spinner-border spinner-border-sm" role="status">
<span class="visually-hidden">Cargando...</span>
</div>
<p class="mt-2">Ejecutando diagnóstico...</p>
</div>
`;
fetch('./api/diagnose_whatsapp.php')
.then(response => response.json())
.then(data => {
if (data.success) {
displayDiagnosticResults(data);
} else {
resultsDiv.innerHTML = `
<div class="alert alert-danger">
<i class="fas fa-exclamation-triangle"></i>
Error: ${data.error || 'Error desconocido'}
</div>
`;
}
})
.catch(error => {
console.error('Error en diagnóstico:', error);
resultsDiv.innerHTML = `
<div class="alert alert-danger">
<i class="fas fa-exclamation-triangle"></i>
Error de conexión: ${error.message}
</div>
`;
});
};
function displayDiagnosticResults(data) {
const resultsDiv = document.getElementById('diagnostic-results');
let html = `
<div class="diagnostic-results">
<small class="text-muted">Última verificación: ${data.timestamp}</small>
<!-- Estado de Configuración -->
<div class="mt-3">
<h6><i class="fas fa-cog"></i> Configuración</h6>
<div class="list-group list-group-flush">
<div class="list-group-item d-flex justify-content-between align-items-center py-2">
<small>Phone Number ID</small>
<span class="badge bg-${data.config_status.phone_number_id ? 'success' : 'danger'}">
${data.config_status.phone_number_id ? '✓' : '✗'}
</span>
</div>
<div class="list-group-item d-flex justify-content-between align-items-center py-2">
<small>Access Token</small>
<span class="badge bg-${data.config_status.access_token ? 'success' : 'danger'}">
${data.config_status.access_token ? '✓' : '✗'}
</span>
</div>
<div class="list-group-item d-flex justify-content-between align-items-center py-2">
<small>Webhook Token</small>
<span class="badge bg-${data.config_status.webhook_verify_token ? 'success' : 'danger'}">
${data.config_status.webhook_verify_token ? '✓' : '✗'}
</span>
</div>
</div>
</div>
<!-- Estado de Plantillas -->
<div class="mt-3">
<h6><i class="fas fa-file-text"></i> Plantillas</h6>
<div class="row text-center">
<div class="col-4">
<div class="text-success">
<strong>${data.template_status.approved || 0}</strong><br>
<small>Aprobadas</small>
</div>
</div>
<div class="col-4">
<div class="text-warning">
<strong>${data.template_status.pending || 0}</strong><br>
<small>Pendientes</small>
</div>
</div>
<div class="col-4">
<div class="text-danger">
<strong>${data.template_status.rejected || 0}</strong><br>
<small>Rechazadas</small>
</div>
</div>
</div>
</div>
<!-- Estado de API -->
<div class="mt-3">
<h6><i class="fas fa-cloud"></i> API WhatsApp</h6>
<div class="alert alert-${data.api_status.reachable ? 'success' : 'danger'} p-2">
<small>
${data.api_status.reachable ?
`✓ Conectado - ${data.api_status.phone_number || 'N/A'}` :
`${data.api_status.error || 'No conectado'}`
}
</small>
</div>
</div>
`;
// Recomendaciones
if (data.recommendations && data.recommendations.length > 0) {
html += `
<div class="mt-3">
<h6><i class="fas fa-lightbulb"></i> Recomendaciones</h6>
<ul class="list-unstyled">
`;
data.recommendations.forEach(rec => {
html += `<li><small><i class="fas fa-arrow-right text-muted"></i> ${rec}</small></li>`;
});
html += `
</ul>
</div>
`;
}
html += '</div>';
resultsDiv.innerHTML = html;
}