version estable

This commit is contained in:
lizandrogd
2026-01-12 13:20:56 -05:00
parent dd36ed6fe0
commit e1b0ded7d9
3 changed files with 367 additions and 125 deletions
BIN
View File
Binary file not shown.
+48 -12
View File
@@ -6,19 +6,15 @@ header('Access-Control-Allow-Headers: Content-Type');
require_once __DIR__ . '/../config/config.php'; require_once __DIR__ . '/../config/config.php';
try { // Suprimir errores para obtener JSON limpio
// Verificar autenticación si no estás en modo debug error_reporting(E_ERROR | E_PARSE);
$debugMode = isset($_GET['debug']);
if (!$debugMode) {
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
if (!isset($_SESSION['user_id'])) { try {
http_response_code(401); // Modo debug: desactivar autenticación si existe el parámetro debug
echo json_encode(['error' => 'No autorizado']); $debugMode = isset($_GET['debug']) && $_GET['debug'] === 'true';
exit;
} if (!$debugMode) {
requireAuthentication();
} }
// Obtener configuración de WhatsApp // Obtener configuración de WhatsApp
@@ -123,6 +119,46 @@ try {
$diagnostic['recommendations'][] = 'Todo parece estar configurado correctamente'; $diagnostic['recommendations'][] = 'Todo parece estar configurado correctamente';
} }
// Agregar compatibilidad con la estructura esperada en index.php
$configComplete = $diagnostic['config_status']['complete'];
$completionPercentage = 0;
$configFields = ['phone_number_id', 'access_token', 'webhook_verify_token', 'business_account_id'];
$completedFields = 0;
foreach ($configFields as $field) {
if (isset($diagnostic['config_status'][$field]) && $diagnostic['config_status'][$field]) {
$completedFields++;
}
}
$completionPercentage = round(($completedFields / count($configFields)) * 100);
// Estructura adicional para compatibilidad
$diagnostic['config'] = [
'status' => $configComplete ? 'complete' : 'incomplete',
'message' => $configComplete ? 'Configuración completa' : 'Configuración incompleta',
'completion' => $completionPercentage
];
$diagnostic['templates'] = [
'approved' => $diagnostic['template_status']['approved'],
'pending' => $diagnostic['template_status']['pending'],
'rejected' => $diagnostic['template_status']['rejected'],
'total' => $diagnostic['template_status']['total'],
'message' => $diagnostic['template_status']['approved'] > 0
? 'Plantillas configuradas correctamente'
: ($diagnostic['template_status']['total'] > 0
? 'Tienes plantillas pendientes de aprobación'
: 'No hay plantillas configuradas')
];
// Estructura API para compatibilidad
$diagnostic['api'] = [
'status' => $diagnostic['api_status']['reachable'] ? 'ready' : 'error',
'message' => $diagnostic['api_status']['reachable']
? 'Conexión API establecida correctamente'
: ($diagnostic['api_status']['error'] ?? 'No conectado')
];
echo json_encode($diagnostic, JSON_PRETTY_PRINT); echo json_encode($diagnostic, JSON_PRETTY_PRINT);
} catch (Exception $e) { } catch (Exception $e) {
+236 -30
View File
@@ -14,6 +14,7 @@ class SimpleWhatsAppManager {
init() { init() {
this.log('Iniciando sistema simplificado'); this.log('Iniciando sistema simplificado');
this.setupEventListeners(); this.setupEventListeners();
this.setupCharts();
this.loadDashboard(); this.loadDashboard();
} }
@@ -113,6 +114,9 @@ class SimpleWhatsAppManager {
case 'templates': case 'templates':
this.loadTemplates(); this.loadTemplates();
break; break;
case 'logs':
this.loadLogs();
break;
case 'settings': case 'settings':
this.loadSettings(); this.loadSettings();
break; break;
@@ -186,35 +190,166 @@ class SimpleWhatsAppManager {
try { try {
// Cargar estadísticas básicas // Cargar estadísticas básicas
const stats = await this.apiCall('manage_config.php?action=status'); const stats = await this.apiCall('get_stats.php');
this.updateStats(stats); this.updateStats(stats);
// Cargar mensajes recientes
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);
}
// Actualizar gráfico si existe
this.updateChart();
} catch (error) { } catch (error) {
this.showError('Error cargando dashboard: ' + error.message); this.showError('Error cargando dashboard: ' + error.message);
} }
} }
updateStats(response) { updateStats(stats) {
if (response && response.success && response.data) { this.log('Actualizando estadísticas del dashboard');
const data = response.data;
// Actualizar elementos del dashboard si existen if (stats) {
const elements = [ const elements = [
{ id: 'total-users', value: data.total_configs || 0 }, { id: 'total-users', value: stats.total_users || 0 },
{ id: 'messages-today', value: data.whatsapp_configured ? 'Configurado' : 'Sin configurar' }, { id: 'messages-today', value: stats.messages_today || 0 },
{ id: 'active-users', value: data.database_migrated ? 'Migrada' : 'Pendiente' }, { id: 'active-users', value: stats.active_users || 0 },
{ id: 'total-messages', value: data.installation_completed ? 'Completada' : 'Pendiente' } { id: 'total-messages', value: stats.total_messages || 0 }
]; ];
elements.forEach(item => { elements.forEach(item => {
const element = document.getElementById(item.id); const element = document.getElementById(item.id);
if (element) { if (element) {
element.textContent = item.value; element.textContent = item.value;
this.log(`Estadística actualizada: ${item.id} = ${item.value}`);
} }
}); });
} }
} }
updateRecentMessages(messages) {
const container = document.getElementById('recent-messages');
if (!container) {
this.log('Contenedor de mensajes recientes no encontrado', 'warning');
return;
}
container.innerHTML = '';
if (messages && messages.length > 0) {
this.log(`Mostrando ${messages.length} mensajes recientes`);
messages.forEach(message => {
const messageElement = this.createRecentMessageElement(message);
container.appendChild(messageElement);
});
} else {
container.innerHTML = '<div class="text-center text-muted">No hay mensajes recientes</div>';
}
}
createRecentMessageElement(message) {
const div = document.createElement('div');
div.className = 'recent-message mb-3 p-2 border-bottom';
const direction = message.direction === 'incoming' ? '📥' : '📤';
const time = new Date(message.created_at).toLocaleString();
div.innerHTML = `
<div class="d-flex justify-content-between">
<span class="fw-bold">${direction} ${message.phone_number}</span>
<span class="time text-muted small">${time}</span>
</div>
<div class="content mt-1">${this.truncateText(message.content, 50)}</div>
`;
return div;
}
truncateText(text, length) {
if (!text) return '';
return text.length > length ? text.substring(0, length) + '...' : text;
}
async updateChart() {
if (!this.charts || !this.charts.messages) {
this.log('Gráfico no inicializado, omitiendo actualización', 'warning');
return;
}
try {
const chartData = await this.apiCall('get_chart_data.php');
if (chartData && this.charts.messages) {
this.charts.messages.data.labels = chartData.labels || [];
this.charts.messages.data.datasets[0].data = chartData.data || [];
this.charts.messages.update();
this.log('Gráfico actualizado correctamente');
}
} catch (error) {
this.log('Error actualizando gráfico: ' + error.message, 'warning');
}
}
setupCharts() {
const ctx = document.getElementById('messagesChart');
if (!ctx) {
this.log('Canvas de gráfico no encontrado', 'warning');
return;
}
if (typeof Chart === 'undefined') {
this.log('Chart.js no está cargado', 'warning');
return;
}
try {
this.charts = this.charts || {};
this.charts.messages = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Mensajes',
data: [],
borderColor: '#25d366',
backgroundColor: 'rgba(37, 211, 102, 0.1)',
borderWidth: 3,
fill: true,
tension: 0.4
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
grid: {
color: 'rgba(0,0,0,0.1)'
}
},
x: {
grid: {
color: 'rgba(0,0,0,0.1)'
}
}
},
plugins: {
legend: {
display: false
}
}
}
});
this.log('Gráfico de mensajes inicializado');
} catch (error) {
this.log('Error inicializando gráfico: ' + error.message, 'error');
}
}
async loadUsers() { async loadUsers() {
this.log('Cargando usuarios'); this.log('Cargando usuarios');
@@ -275,14 +410,19 @@ class SimpleWhatsAppManager {
try { try {
const response = await this.apiCall('get_conversations.php'); const response = await this.apiCall('get_conversations.php');
console.log('Respuesta get_conversations:', response); // Debug
if (response && response.success) { if (response && response.success && Array.isArray(response.data)) {
this.updateConversationsList(response.data || []); this.updateConversationsList(response.data);
} else if (response && Array.isArray(response)) {
// Retrocompatibilidad por si la API devuelve directamente el array
this.updateConversationsList(response);
} else { } else {
this.showError('No se pudieron cargar las conversaciones'); console.error('Formato de respuesta inesperado:', response);
this.showError('Error: formato de datos inválido para conversaciones');
} }
} catch (error) { } catch (error) {
console.error('Error en loadConversations:', error);
this.showError('Error cargando conversaciones: ' + error.message); this.showError('Error cargando conversaciones: ' + error.message);
} }
} }
@@ -678,10 +818,25 @@ class SimpleWhatsAppManager {
this.showError('Error enviando mensaje: ' + error.message); this.showError('Error enviando mensaje: ' + error.message);
} }
} }
async loadLogs() {
try {
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);
}
}
} }
// Inicializar cuando el DOM esté listo // Inicializar cuando el DOM esté listo
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function () {
console.log('DOM cargado, inicializando WhatsApp Manager...'); console.log('DOM cargado, inicializando WhatsApp Manager...');
try { try {
@@ -693,7 +848,7 @@ document.addEventListener('DOMContentLoaded', function() {
}); });
// Funciones globales para modales (compatibilidad con el HTML existente) // Funciones globales para modales (compatibilidad con el HTML existente)
window.openCreateTemplateModal = function() { window.openCreateTemplateModal = function () {
console.log('🔵 Abriendo modal de plantilla...'); console.log('🔵 Abriendo modal de plantilla...');
const modalElement = document.getElementById('createTemplateModal'); const modalElement = document.getElementById('createTemplateModal');
@@ -719,7 +874,7 @@ window.openCreateTemplateModal = function() {
} }
}; };
window.openCreateMenuModal = function() { window.openCreateMenuModal = function () {
console.log('🔵 Abriendo modal de menú...'); console.log('🔵 Abriendo modal de menú...');
const modalElement = document.getElementById('createMenuModal'); const modalElement = document.getElementById('createMenuModal');
@@ -746,7 +901,7 @@ window.openCreateMenuModal = function() {
}; };
// Función global para debugging // Función global para debugging
window.debugAPI = async function(endpoint) { window.debugAPI = async function (endpoint) {
try { try {
const manager = window.whatsappManager; const manager = window.whatsappManager;
if (manager) { if (manager) {
@@ -762,19 +917,19 @@ window.debugAPI = async function(endpoint) {
}; };
// Función para ver conversación específica // Función para ver conversación específica
window.viewConversation = function(userId) { window.viewConversation = function (userId) {
console.log('Viendo conversación del usuario:', userId); console.log('Viendo conversación del usuario:', userId);
alert(`Ver conversación del usuario ${userId} - Función en desarrollo`); alert(`Ver conversación del usuario ${userId} - Función en desarrollo`);
}; };
// Función para editar usuario // Función para editar usuario
window.editUser = function(userId) { window.editUser = function (userId) {
console.log('Editando usuario:', userId); console.log('Editando usuario:', userId);
alert(`Editar usuario ${userId} - Función en desarrollo`); alert(`Editar usuario ${userId} - Función en desarrollo`);
}; };
// Función para eliminar usuario // Función para eliminar usuario
window.deleteUser = function(userId) { window.deleteUser = function (userId) {
console.log('Eliminando usuario:', userId); console.log('Eliminando usuario:', userId);
if (confirm(`¿Está seguro que desea eliminar el usuario ${userId}?`)) { if (confirm(`¿Está seguro que desea eliminar el usuario ${userId}?`)) {
alert(`Eliminar usuario ${userId} - Función en desarrollo`); alert(`Eliminar usuario ${userId} - Función en desarrollo`);
@@ -782,17 +937,17 @@ window.deleteUser = function(userId) {
}; };
// Funciones para plantillas // Funciones para plantillas
window.showCreateTemplateModal = function() { window.showCreateTemplateModal = function () {
const modal = new bootstrap.Modal(document.getElementById('createTemplateModal')); const modal = new bootstrap.Modal(document.getElementById('createTemplateModal'));
modal.show(); modal.show();
}; };
window.editTemplate = function(templateId) { window.editTemplate = function (templateId) {
console.log('Editando plantilla:', templateId); console.log('Editando plantilla:', templateId);
alert(`Editar plantilla ${templateId} - Función en desarrollo`); alert(`Editar plantilla ${templateId} - Función en desarrollo`);
}; };
window.deleteTemplate = function(templateId) { window.deleteTemplate = function (templateId) {
console.log('Eliminando plantilla:', templateId); console.log('Eliminando plantilla:', templateId);
if (confirm(`¿Está seguro que desea eliminar la plantilla ${templateId}?`)) { if (confirm(`¿Está seguro que desea eliminar la plantilla ${templateId}?`)) {
alert(`Eliminar plantilla ${templateId} - Función en desarrollo`); alert(`Eliminar plantilla ${templateId} - Función en desarrollo`);
@@ -801,7 +956,7 @@ window.deleteTemplate = function(templateId) {
// Hacer que app.saveTemplate() funcione // Hacer que app.saveTemplate() funcione
window.app = { window.app = {
saveTemplate: function() { saveTemplate: function () {
if (window.whatsappManager) { if (window.whatsappManager) {
window.whatsappManager.saveTemplate(); window.whatsappManager.saveTemplate();
} }
@@ -809,7 +964,7 @@ window.app = {
}; };
// Funciones para el formulario de mensajes // Funciones para el formulario de mensajes
window.toggleRecipientType = function() { window.toggleRecipientType = function () {
const recipientType = document.getElementById('recipient-type').value; const recipientType = document.getElementById('recipient-type').value;
const existingGroup = document.getElementById('existing-recipient-group'); const existingGroup = document.getElementById('existing-recipient-group');
const manualGroup = document.getElementById('manual-recipient-group'); const manualGroup = document.getElementById('manual-recipient-group');
@@ -823,7 +978,7 @@ window.toggleRecipientType = function() {
} }
}; };
window.toggleMessageType = function() { window.toggleMessageType = function () {
const messageType = document.getElementById('message-type').value; const messageType = document.getElementById('message-type').value;
const textGroup = document.getElementById('message-text-group'); const textGroup = document.getElementById('message-text-group');
const templateGroup = document.getElementById('template-group'); const templateGroup = document.getElementById('template-group');
@@ -838,7 +993,7 @@ window.toggleMessageType = function() {
}; };
// Función de diagnóstico // Función de diagnóstico
window.runDiagnostic = function() { window.runDiagnostic = function () {
const resultsDiv = document.getElementById('diagnostic-results'); const resultsDiv = document.getElementById('diagnostic-results');
// Mostrar spinner de carga // Mostrar spinner de carga
@@ -939,9 +1094,9 @@ function displayDiagnosticResults(data) {
<div class="alert alert-${data.api_status.reachable ? 'success' : 'danger'} p-2"> <div class="alert alert-${data.api_status.reachable ? 'success' : 'danger'} p-2">
<small> <small>
${data.api_status.reachable ? ${data.api_status.reachable ?
`✓ Conectado - ${data.api_status.phone_number || 'N/A'}` : `✓ Conectado - ${data.api_status.phone_number || 'N/A'}` :
`${data.api_status.error || 'No conectado'}` `${data.api_status.error || 'No conectado'}`
} }
</small> </small>
</div> </div>
</div> </div>
@@ -966,3 +1121,54 @@ function displayDiagnosticResults(data) {
html += '</div>'; html += '</div>';
resultsDiv.innerHTML = html; resultsDiv.innerHTML = html;
} }
function updateLogsTable(logs) {
const tbody = document.getElementById('logs-table');
if (!tbody) {
this.log('Tabla de logs no encontrada', 'warning');
return;
}
tbody.innerHTML = '';
if (!logs || logs.length === 0) {
tbody.innerHTML = '<tr><td colspan="5" class="text-center text-muted">No hay logs registrados</td></tr>';
return;
}
logs.forEach(log => {
const row = this.createLogRow(log);
tbody.appendChild(row);
});
this.log(`${logs.length} logs cargados en la tabla`);
}
function createLogRow(log) {
const tr = document.createElement('tr');
const date = new Date(log.created_at);
const formatDate = date.toLocaleDateString() + ' ' + date.toLocaleTimeString('es', { hour: '2-digit', minute: '2-digit' });
tr.innerHTML = `
<td>${formatDate}</td>
<td>${log.ip_address || 'N/A'}</td>
<td>
<span class="badge bg-${log.status_code === 200 ? 'success' : 'danger'}">
${log.status_code || 'N/A'}
</span>
</td>
<td>
<button class="btn btn-sm btn-outline-primary" onclick="viewLogDetails('${log.id}', 'request')">
Ver Request
</button>
</td>
<td>
<button class="btn btn-sm btn-outline-primary" onclick="viewLogDetails('${log.id}', 'response')">
Ver Response
</button>
</td>
`;
return tr;
}