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';
try {
// Verificar autenticación si no estás en modo debug
$debugMode = isset($_GET['debug']);
if (!$debugMode) {
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Suprimir errores para obtener JSON limpio
error_reporting(E_ERROR | E_PARSE);
if (!isset($_SESSION['user_id'])) {
http_response_code(401);
echo json_encode(['error' => 'No autorizado']);
exit;
}
try {
// Modo debug: desactivar autenticación si existe el parámetro debug
$debugMode = isset($_GET['debug']) && $_GET['debug'] === 'true';
if (!$debugMode) {
requireAuthentication();
}
// Obtener configuración de WhatsApp
@@ -123,6 +119,46 @@ try {
$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);
} catch (Exception $e) {
+219 -13
View File
@@ -14,6 +14,7 @@ class SimpleWhatsAppManager {
init() {
this.log('Iniciando sistema simplificado');
this.setupEventListeners();
this.setupCharts();
this.loadDashboard();
}
@@ -113,6 +114,9 @@ class SimpleWhatsAppManager {
case 'templates':
this.loadTemplates();
break;
case 'logs':
this.loadLogs();
break;
case 'settings':
this.loadSettings();
break;
@@ -186,35 +190,166 @@ class SimpleWhatsAppManager {
try {
// 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);
// 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) {
this.showError('Error cargando dashboard: ' + error.message);
}
}
updateStats(response) {
if (response && response.success && response.data) {
const data = response.data;
updateStats(stats) {
this.log('Actualizando estadísticas del dashboard');
// Actualizar elementos del dashboard si existen
if (stats) {
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' }
{ id: 'total-users', value: stats.total_users || 0 },
{ id: 'messages-today', value: stats.messages_today || 0 },
{ id: 'active-users', value: stats.active_users || 0 },
{ id: 'total-messages', value: stats.total_messages || 0 }
];
elements.forEach(item => {
const element = document.getElementById(item.id);
if (element) {
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() {
this.log('Cargando usuarios');
@@ -275,14 +410,19 @@ class SimpleWhatsAppManager {
try {
const response = await this.apiCall('get_conversations.php');
console.log('Respuesta get_conversations:', response); // Debug
if (response && response.success) {
this.updateConversationsList(response.data || []);
if (response && response.success && Array.isArray(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 {
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) {
console.error('Error en loadConversations:', error);
this.showError('Error cargando conversaciones: ' + error.message);
}
}
@@ -678,6 +818,21 @@ class SimpleWhatsAppManager {
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
@@ -966,3 +1121,54 @@ function displayDiagnosticResults(data) {
html += '</div>';
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;
}