diff --git a/DEPLOYMENT_GUIDE.md b/DEPLOYMENT_GUIDE.md index 4cc8159..6c6fd49 100644 --- a/DEPLOYMENT_GUIDE.md +++ b/DEPLOYMENT_GUIDE.md @@ -212,7 +212,7 @@ https://tudominio.com/bot/api/webhook.php 4. En **Webhooks**: - **Callback URL**: `https://tudominio.com/migrador/api/webhook.php` - **Verify Token**: `mi_token_secreto_123` (o cambia en config.php) - - **Webhook fields**: ✅ `messages` + - **Webhook fields**: ✅ `conversations` ### 3. Verificar Webhook ```bash diff --git a/GUIA_HESTIACP_COMPLETA.md b/GUIA_HESTIACP_COMPLETA.md index 9fe6f63..474a650 100644 --- a/GUIA_HESTIACP_COMPLETA.md +++ b/GUIA_HESTIACP_COMPLETA.md @@ -150,7 +150,7 @@ define('DB_CHARSET', 'utf8mb4'); 2. Configuration → Webhook URL: https://tudominio.com/api/webhook.php 3. Verify Token: (copiar del dashboard) -4. Suscribirse a: messages, message_status +4. Suscribirse a: conversations, message_status ``` ## 🚨 Solución de Problemas HestiaCP @@ -197,9 +197,9 @@ define('DB_CHARSET', 'utf8mb4'); ### Performance ```bash -1. Activar OPcache en PHP settings +1. Activar OPcache en PHP system_config 2. Configurar Redis/Memcached si disponible -3. Optimizar MySQL en HestiaCP settings +3. Optimizar MySQL en HestiaCP system_config 4. Usar Cloudflare para CDN ``` diff --git a/INSTALACION.md b/INSTALACION.md index 5494db5..096dd04 100644 --- a/INSTALACION.md +++ b/INSTALACION.md @@ -28,7 +28,7 @@ 2. Crear/configurar aplicación WhatsApp Business 3. Webhook URL: `https://tudominio.com/migrador/api/webhook.php` 4. Token de verificación: `mi_token_secreto_123` -5. Suscribirse a eventos: `messages` +5. Suscribirse a eventos: `conversations` ## 🎯 Prueba Rápida del Bot diff --git a/README.md b/README.md index ea7c0f1..65a1282 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ chmod 666 config/config.php 2. **Configurar Webhook** - URL del Webhook: `https://tudominio.com/migrador/api/webhook.php` - Token de Verificación: `mi_token_secreto_123` - - Suscribirse a: `messages` + - Suscribirse a: `conversations` 3. **Obtener Tokens** - Token de Acceso (ya proporcionado) @@ -164,7 +164,7 @@ migrador/ - `conversations` - Historial de mensajes - `menus` - Configuración de menús - `menu_options` - Opciones de cada menú -- `auto_responses` - Respuestas automáticas +- `autoresponses` - Respuestas automáticas - `system_config` - Configuración del sistema - `webhook_logs` - Logs de webhooks @@ -186,7 +186,7 @@ INSERT INTO menu_options (menu_id, option_number, text, action_type, action_valu ### Respuestas Automáticas ```sql -- Agregar respuesta automática -INSERT INTO auto_responses (trigger_type, trigger_value, response_text) VALUES +INSERT INTO autoresponses (trigger_type, trigger_value, response_text) VALUES ('keyword', 'precio', 'Para consultar precios, escribe *catalogo* o visita www.mitienda.com'), ('keyword', 'horarios', 'Atendemos de Lunes a Viernes de 8am a 6pm'); ``` diff --git a/README_LABORATORIO.md b/README_LABORATORIO.md index 6686c79..e00cda2 100644 --- a/README_LABORATORIO.md +++ b/README_LABORATORIO.md @@ -99,7 +99,7 @@ Este script: 1. En Meta for Developers, configura el webhook: - URL: `https://tu-dominio.com/api/webhook.php` - Verify Token: El mismo que configuraste en el paso anterior - - Suscripciones: `messages`, `message_status` + - Suscripciones: `conversations`, `message_status` ## 📚 Estructura de Archivos diff --git a/README_SETUP.md b/README_SETUP.md index f8917fd..a8c7d37 100644 --- a/README_SETUP.md +++ b/README_SETUP.md @@ -94,7 +94,7 @@ Este validador te mostrará: #### **Configurar Webhook:** 1. URL del webhook: `https://tudominio.com/api/webhook.php` 2. Token de verificación: (el que configuraste en .env) -3. Eventos a suscribirse: `messages` +3. Eventos a suscribirse: `conversations` ### 5. **Acceso al Panel de Administración** diff --git a/REPORTE_SISTEMA_COMPLETO.md b/REPORTE_SISTEMA_COMPLETO.md index b1d28e1..f36ffe1 100644 --- a/REPORTE_SISTEMA_COMPLETO.md +++ b/REPORTE_SISTEMA_COMPLETO.md @@ -160,7 +160,7 @@ downloadMedia($mediaId) - ✅ `get_conversation_list.php` - Lista simplificada - ✅ `get_conversation_detail.php` - Detalle de conversación - ✅ `get_conversation_stats.php` - Estadísticas -- ✅ `get_recent_messages.php` - Mensajes recientes +- ✅ `get_recent_conversations.php` - Mensajes recientes ### 🍽️ Menús: - ✅ `get_menus.php` - Listar menús @@ -188,8 +188,8 @@ downloadMedia($mediaId) - ✅ `send_media_message.php` - Enviar multimedia ### ⚙️ Configuración: -- ✅ `get_settings.php` - Obtener configuración -- ✅ `save_settings.php` - Guardar configuración +- ✅ `get_system_config.php` - Obtener configuración +- ✅ `save_system_config.php` - Guardar configuración - ✅ `manage_config.php` - Gestión completa ### 📝 Logs: diff --git a/SOLUCION_SEGURIDAD.md b/SOLUCION_SEGURIDAD.md index 751e663..c75b2c8 100644 --- a/SOLUCION_SEGURIDAD.md +++ b/SOLUCION_SEGURIDAD.md @@ -46,10 +46,10 @@ function requireAuthentication() { ### 3. APIs protegidas Archivos corregidos con `requireAuthentication()`: - ✅ `api/get_stats.php` -- ✅ `api/save_settings.php` +- ✅ `api/save_system_config.php` - ✅ `api/get_users.php` - ✅ `api/send_message.php` -- ✅ `api/get_settings.php` +- ✅ `api/get_system_config.php` - ✅ `api/get_menus.php` - ✅ `api/export_users.php` diff --git a/api/delete_user.php b/api/delete_user.php index 772cca1..b1772bd 100644 --- a/api/delete_user.php +++ b/api/delete_user.php @@ -69,10 +69,10 @@ try { try { // Eliminar mensajes relacionados usando PDO - $stmt = $conn->prepare("DELETE FROM messages WHERE user_id = ?"); + $stmt = $conn->prepare("DELETE FROM conversations WHERE user_id = ?"); $stmt->bindValue(1, $user_id, PDO::PARAM_INT); $stmt->execute(); - $deleted_messages = $stmt->rowCount(); + $deleted_conversations = $stmt->rowCount(); // Eliminar el usuario $stmt = $conn->prepare("DELETE FROM users WHERE id = ?"); @@ -94,7 +94,7 @@ try { 'deleted_user_id' => $user_id, 'deleted_user_name' => $user_data['name'], 'deleted_user_phone' => $user_data['phone_number'], - 'deleted_messages_count' => $deleted_messages, + 'deleted_conversations_count' => $deleted_conversations, 'timestamp' => date('Y-m-d H:i:s') ] ]); diff --git a/api/export_users.php b/api/export_users.php index dcc0ba8..fb0311c 100644 --- a/api/export_users.php +++ b/api/export_users.php @@ -27,7 +27,7 @@ try { u.status, u.created_at, u.updated_at, - COUNT(c.id) as total_messages, + COUNT(c.id) as total_conversations, MAX(c.created_at) as last_activity FROM users u LEFT JOIN conversations c ON u.id = c.user_id @@ -61,7 +61,7 @@ try { $user['name'] ?? 'Sin nombre', $user['email'] ?? 'Sin email', $user['status'], - $user['total_messages'], + $user['total_conversations'], $user['last_activity'] ? date('d/m/Y H:i', strtotime($user['last_activity'])) : 'Nunca', date('d/m/Y H:i', strtotime($user['created_at'])) ], ';'); diff --git a/api/get_conversation_detail.php b/api/get_conversation_detail.php index 322ebba..a3811e1 100644 --- a/api/get_conversation_detail.php +++ b/api/get_conversation_detail.php @@ -41,7 +41,7 @@ try { } // Obtener todos los mensajes de la conversación - $messages = $db->fetchAll( + $conversations = $db->fetchAll( "SELECT id, message_id, @@ -62,7 +62,7 @@ try { ); // Formatear mensajes - $messages = array_map(function($msg) { + $conversations = array_map(function($msg) { return [ 'id' => intval($msg['id']), 'message_id' => $msg['message_id'] ?? '', @@ -75,7 +75,7 @@ try { 'time' => date('H:i', strtotime($msg['created_at'])), 'date' => date('d/m/Y', strtotime($msg['created_at'])) ]; - }, $messages); + }, $conversations); // Marcar mensajes como leídos $db->query( @@ -90,8 +90,8 @@ try { 'phone_number' => $user['phone_number'], 'name' => $user['name'] ?? $user['phone_number'] ], - 'messages' => $messages, - 'total_messages' => count($messages) + 'conversations' => $conversations, + 'total_conversations' => count($conversations) ]); } catch (Exception $e) { diff --git a/api/get_conversation_list.php b/api/get_conversation_list.php index 32c9201..17a04f8 100644 --- a/api/get_conversation_list.php +++ b/api/get_conversation_list.php @@ -31,7 +31,7 @@ try { c.message_type as last_message_type, c.created_at as last_message_time, c.status as last_message_status, - COUNT(*) as total_messages, + COUNT(*) as total_conversations, SUM(CASE WHEN c.direction = 'incoming' AND c.status = 'received' THEN 1 ELSE 0 END) as unread_count FROM users u LEFT JOIN conversations c ON u.id = c.user_id @@ -61,7 +61,7 @@ try { 'last_message_type' => $conv['last_message_type'] ?? 'text', 'last_message_time' => $conv['last_message_time'], 'last_message_status' => $conv['last_message_status'] ?? 'sent', - 'total_messages' => intval($conv['total_messages']), + 'total_conversations' => intval($conv['total_conversations']), 'unread_count' => intval($conv['unread_count']), 'time_ago' => timeAgo($conv['last_message_time']) ]; diff --git a/api/get_conversation_stats.php b/api/get_conversation_stats.php index 8ecf3b5..9647719 100644 --- a/api/get_conversation_stats.php +++ b/api/get_conversation_stats.php @@ -33,10 +33,10 @@ try { // En el futuro, esto consultaría la base de datos real $stats = [ 'user_id' => $user_id, - 'total_messages' => rand(10, 100), - 'messages_today' => rand(0, 15), - 'messages_this_week' => rand(5, 50), - 'messages_this_month' => rand(20, 80), + 'total_conversations' => rand(10, 100), + 'conversations_today' => rand(0, 15), + 'conversations_this_week' => rand(5, 50), + 'conversations_this_month' => rand(20, 80), 'first_message_date' => date('Y-m-d H:i:s', strtotime('-' . rand(1, 30) . ' days')), 'last_message_date' => date('Y-m-d H:i:s', strtotime('-' . rand(1, 24) . ' hours')), 'avg_response_time' => rand(5, 120) . ' minutos', diff --git a/api/get_recent_messages.php b/api/get_recent_messages.php index eae9c50..560bf46 100644 --- a/api/get_recent_messages.php +++ b/api/get_recent_messages.php @@ -14,7 +14,7 @@ header('Access-Control-Allow-Headers: Content-Type'); try { $db = Database::getInstance(); - $recentMessages = $db->fetchAll( + $recentconversations = $db->fetchAll( "SELECT c.content, c.direction, @@ -29,10 +29,10 @@ try { LIMIT 10" ); - echo json_encode($recentMessages); + echo json_encode($recentconversations); } catch (Exception $e) { - error_log("Error in get_recent_messages.php: " . $e->getMessage()); + error_log("Error in get_recent_conversations.php: " . $e->getMessage()); http_response_code(500); echo json_encode(['error' => 'Error interno del servidor']); } diff --git a/api/get_settings.php b/api/get_settings.php index 7a9e48b..68538df 100644 --- a/api/get_settings.php +++ b/api/get_settings.php @@ -21,15 +21,15 @@ try { "SELECT config_key, config_value FROM system_config" ); - $settings = []; + $system_config = []; foreach ($configs as $config) { - $settings[$config['config_key']] = $config['config_value']; + $system_config[$config['config_key']] = $config['config_value']; } - echo json_encode($settings); + echo json_encode($system_config); } catch (Exception $e) { - error_log("Error in get_settings.php: " . $e->getMessage()); + error_log("Error in get_system_config.php: " . $e->getMessage()); http_response_code(500); echo json_encode(['error' => 'Error interno del servidor']); } diff --git a/api/get_stats.php b/api/get_stats.php index 219cad1..38156f2 100644 --- a/api/get_stats.php +++ b/api/get_stats.php @@ -28,7 +28,7 @@ try { $totalUsers = $db->fetch("SELECT COUNT(*) as count FROM users")['count']; // Mensajes hoy - $messagesToday = $db->fetch( + $conversationsToday = $db->fetch( "SELECT COUNT(*) as count FROM conversations WHERE DATE(created_at) = CURDATE()" )['count']; @@ -39,13 +39,13 @@ try { )['count']; // Total de mensajes - $totalMessages = $db->fetch("SELECT COUNT(*) as count FROM conversations")['count']; + $totalconversations = $db->fetch("SELECT COUNT(*) as count FROM conversations")['count']; $stats = [ 'total_users' => (int)$totalUsers, - 'messages_today' => (int)$messagesToday, + 'conversations_today' => (int)$conversationsToday, 'active_users' => (int)$activeUsers, - 'total_messages' => (int)$totalMessages + 'total_conversations' => (int)$totalconversations ]; echo json_encode($stats); diff --git a/api/get_user_messages.php b/api/get_user_messages.php index 6ed0327..a92a54a 100644 --- a/api/get_user_messages.php +++ b/api/get_user_messages.php @@ -26,7 +26,7 @@ try { $db = Database::getInstance(); // Obtener mensajes del usuario (de ambas tablas para compatibilidad) - $messages = $db->fetchAll( + $conversations = $db->fetchAll( "SELECT id, user_id, @@ -55,15 +55,15 @@ try { status, created_at, 1 as is_read - FROM messages + FROM conversations WHERE user_id = :user_id ORDER BY created_at ASC", ['user_id' => $userId] ); - // Si no hay mensajes en conversations, intentar con messages - if (empty($messages)) { - $messages = $db->fetchAll( + // Si no hay mensajes en conversations, intentar con conversations + if (empty($conversations)) { + $conversations = $db->fetchAll( "SELECT id, user_id, @@ -72,7 +72,7 @@ try { message_type, status, created_at - FROM messages + FROM conversations WHERE user_id = :user_id ORDER BY created_at ASC", ['user_id' => $userId] @@ -80,7 +80,7 @@ try { } // Formatear fechas y limpiar datos - $messages = array_map(function($msg) { + $conversations = array_map(function($msg) { return [ 'id' => intval($msg['id']), 'user_id' => intval($msg['user_id']), @@ -93,12 +93,12 @@ try { 'status' => $msg['status'] ?? 'sent', 'created_at' => $msg['created_at'] ]; - }, $messages); + }, $conversations); - echo json_encode($messages); + echo json_encode($conversations); } catch (Exception $e) { - error_log("Error in get_user_messages.php: " . $e->getMessage()); + error_log("Error in get_user_conversations.php: " . $e->getMessage()); http_response_code(500); echo json_encode(['error' => 'Error interno del servidor']); } diff --git a/api/get_webhook_logs.php b/api/get_webhook_logs.php index 2389012..fd2f4e8 100644 --- a/api/get_webhook_logs.php +++ b/api/get_webhook_logs.php @@ -40,7 +40,7 @@ try { $offset = ($page - 1) * $limit; $sinceId = isset($_GET['since_id']) ? intval($_GET['since_id']) : null; $search = trim($_GET['search'] ?? ''); - $filter = trim($_GET['filter'] ?? ''); // e.g., HAS_MESSAGES + $filter = trim($_GET['filter'] ?? ''); // e.g., HAS_conversations $where = []; $params = []; @@ -55,9 +55,9 @@ try { $params[] = "%{$search}%"; } - if ($filter === 'HAS_MESSAGES') { + if ($filter === 'HAS_conversations') { $where[] = 'request_body LIKE ?'; - $params[] = '%"messages"%'; + $params[] = '%"conversations"%'; } $whereClause = empty($where) ? '' : 'WHERE ' . implode(' AND ', $where); diff --git a/api/save_settings.php b/api/save_settings.php index ee6caf6..46ec525 100644 --- a/api/save_settings.php +++ b/api/save_settings.php @@ -85,7 +85,7 @@ try { } } catch (Exception $e) { - error_log("Error in save_settings.php: " . $e->getMessage()); + error_log("Error in save_system_config.php: " . $e->getMessage()); http_response_code(500); echo json_encode(['error' => 'Error interno del servidor: ' . $e->getMessage()]); } diff --git a/api/send_media_message.php b/api/send_media_message.php index 22e68bf..bcedfda 100644 --- a/api/send_media_message.php +++ b/api/send_media_message.php @@ -133,7 +133,7 @@ try { } // Guardar respuesta en base de datos - if ($response && isset($response['messages'][0]['id'])) { + if ($response && isset($response['conversations'][0]['id'])) { error_log("send_media_message.php - Respuesta de WhatsApp exitosa: " . json_encode($response)); // Guardar en base de datos @@ -149,7 +149,7 @@ try { // Datos base para insertar $conversationData = [ 'user_id' => $user['id'], - 'message_id' => $response['messages'][0]['id'], + 'message_id' => $response['conversations'][0]['id'], 'direction' => 'outgoing', 'message_type' => $mediaType, 'content' => $caption ?? $filename ?? '', diff --git a/api/send_message.php b/api/send_message.php index 4f446cd..ccf3ac1 100644 --- a/api/send_message.php +++ b/api/send_message.php @@ -470,7 +470,7 @@ try { $response = $whatsappService->sendTextMessage($user['phone_number'], $message); - if ($response && isset($response['messages']) && !empty($response['messages'])) { + if ($response && isset($response['conversations']) && !empty($response['conversations'])) { // Saving handled by WhatsAppService->saveOutgoingMessage(), skip manual insert to avoid duplicates echo json_encode([ 'success' => true, diff --git a/api/webhook.php b/api/webhook.php index e5d1a96..4a31de6 100644 --- a/api/webhook.php +++ b/api/webhook.php @@ -80,8 +80,8 @@ class WhatsAppWebhook { foreach ($data['entry'] as $entry) { if (isset($entry['changes'])) { foreach ($entry['changes'] as $change) { - if ($change['field'] === 'messages') { - $this->processMessages($change['value']); + if ($change['field'] === 'conversations') { + $this->processconversations($change['value']); } } } @@ -96,12 +96,12 @@ class WhatsAppWebhook { } } - private function processMessages($value) { - if (!isset($value['messages'])) { + private function processconversations($value) { + if (!isset($value['conversations'])) { return; } - foreach ($value['messages'] as $message) { + foreach ($value['conversations'] as $message) { $phoneNumber = $message['from']; $messageId = $message['id']; $timestamp = $message['timestamp']; @@ -209,11 +209,11 @@ class WhatsAppWebhook { // Procesar estados de mensajes (entregado, leído, etc.) if (isset($value['statuses'])) { - $this->processMessageStatuses($value['statuses']); + $this->processconversationstatuses($value['statuses']); } } - private function processMessageStatuses($statuses) { + private function processconversationstatuses($statuses) { foreach ($statuses as $status) { $messageId = $status['id']; $newStatus = $status['status']; // sent, delivered, read, failed @@ -294,11 +294,11 @@ class WhatsAppWebhook { if (isset($entry['changes'])) { foreach ($entry['changes'] as $change) { error_log("processPayload: processing change field=" . ($change['field'] ?? '')); - if (($change['field'] ?? '') === 'messages' && isset($change['value'])) { + if (($change['field'] ?? '') === 'conversations' && isset($change['value'])) { try { - $this->processMessages($change['value']); + $this->processconversations($change['value']); } catch (Exception $e) { - error_log("processPayload: processMessages failed: " . $e->getMessage()); + error_log("processPayload: processconversations failed: " . $e->getMessage()); } } } diff --git a/assets/css/styles.css b/assets/css/styles.css index 2cc0f4b..36bb3ba 100644 --- a/assets/css/styles.css +++ b/assets/css/styles.css @@ -548,7 +548,7 @@ body { border-left: 4px solid var(--info-color); } -/* Recent Messages */ +/* Recent conversations */ .recent-message { padding: 10px 15px; border-radius: 8px; diff --git a/assets/js/app.js b/assets/js/app.js index 208f17c..050de4d 100644 --- a/assets/js/app.js +++ b/assets/js/app.js @@ -52,11 +52,11 @@ class WhatsAppBotManager { setupFormListeners() { // Formulario de configuración - const settingsForm = document.getElementById('settings-form'); - if (settingsForm) { - settingsForm.addEventListener('submit', (e) => { + const system_configForm = document.getElementById('system_config-form'); + if (system_configForm) { + system_configForm.addEventListener('submit', (e) => { e.preventDefault(); - this.saveSettings(); + this.savesystem_config(); }); } @@ -149,7 +149,7 @@ class WhatsAppBotManager { case 'menus': this.loadMenus(); break; - case 'messages': + case 'conversations': this.loadMessageUsers(); break; case 'templates': @@ -158,8 +158,8 @@ class WhatsAppBotManager { case 'autoresponses': this.loadAutoResponses(); break; - case 'settings': - this.loadSettings(); + case 'system_config': + this.loadsystem_config(); break; case 'logs': this.loadLogs(); @@ -172,12 +172,12 @@ class WhatsAppBotManager { const stats = await this.apiCall('get_stats.php'); this.updateStats(stats); - 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)) { + const recentconversationsResponse = await this.apiCall('get_recent_conversations.php'); + if (recentconversationsResponse && recentconversationsResponse.success && Array.isArray(recentconversationsResponse.data)) { + this.updateRecentconversations(recentconversationsResponse.data); + } else if (recentconversationsResponse && Array.isArray(recentconversationsResponse)) { // Retrocompatibilidad por si la API devuelve directamente el array - this.updateRecentMessages(recentMessagesResponse); + this.updateRecentconversations(recentconversationsResponse); } this.updateChart(); @@ -189,20 +189,20 @@ class WhatsAppBotManager { updateStats(stats) { if (stats) { document.getElementById('total-users').textContent = stats.total_users || 0; - document.getElementById('messages-today').textContent = stats.messages_today || 0; + document.getElementById('conversations-today').textContent = stats.conversations_today || 0; document.getElementById('active-users').textContent = stats.active_users || 0; - document.getElementById('total-messages').textContent = stats.total_messages || 0; + document.getElementById('total-conversations').textContent = stats.total_conversations || 0; } } - updateRecentMessages(messages) { - const container = document.getElementById('recent-messages'); + updateRecentconversations(conversations) { + const container = document.getElementById('recent-conversations'); if (!container) return; container.innerHTML = ''; - if (messages && messages.length > 0) { - messages.forEach(message => { + if (conversations && conversations.length > 0) { + conversations.forEach(message => { const messageElement = this.createRecentMessageElement(message); container.appendChild(messageElement); }); @@ -230,9 +230,9 @@ class WhatsAppBotManager { } setupCharts() { - const ctx = document.getElementById('messagesChart'); + const ctx = document.getElementById('conversationsChart'); if (ctx) { - this.charts.messages = new Chart(ctx, { + this.charts.conversations = new Chart(ctx, { type: 'line', data: { labels: [], @@ -275,10 +275,10 @@ class WhatsAppBotManager { async updateChart() { 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(); + if (chartData && this.charts.conversations) { + this.charts.conversations.data.labels = chartData.labels; + this.charts.conversations.data.datasets[0].data = chartData.data; + this.charts.conversations.update(); } } catch (error) { console.error('Error updating chart:', error); @@ -725,7 +725,7 @@ class WhatsAppBotManager { } } - async saveSettings() { + async savesystem_config() { const formData = { whatsapp_token: document.getElementById('whatsapp-token').value, phone_number_id: document.getElementById('phone-number-id').value, @@ -736,7 +736,7 @@ class WhatsAppBotManager { try { this.showLoading('Guardando configuración...'); - const result = await this.apiCall('save_settings.php', 'POST', formData); + const result = await this.apiCall('save_system_config.php', 'POST', formData); if (result.success) { this.showSuccess('Configuración guardada correctamente'); @@ -750,16 +750,16 @@ class WhatsAppBotManager { } } - async loadSettings() { + async loadsystem_config() { try { - const settings = await this.apiCall('get_settings.php'); + const system_config = await this.apiCall('get_system_config.php'); - if (settings) { - document.getElementById('whatsapp-token').value = settings.whatsapp_token || ''; - document.getElementById('phone-number-id').value = settings.phone_number_id || ''; - document.getElementById('webhook-token').value = settings.webhook_token || ''; - document.getElementById('business-name').value = settings.business_name || ''; - document.getElementById('welcome-message').value = settings.welcome_message || ''; + if (system_config) { + document.getElementById('whatsapp-token').value = system_config.whatsapp_token || ''; + document.getElementById('phone-number-id').value = system_config.phone_number_id || ''; + document.getElementById('webhook-token').value = system_config.webhook_token || ''; + document.getElementById('business-name').value = system_config.business_name || ''; + document.getElementById('welcome-message').value = system_config.welcome_message || ''; } } catch (error) { this.showError('Error cargando configuración: ' + error.message); @@ -1025,7 +1025,7 @@ class WhatsAppBotManager { replyToUser(phoneNumber) { document.getElementById('message-recipient').value = phoneNumber; - this.showTab('messages'); + this.showTab('conversations'); } replyToMessage(messageId, userPhone) { @@ -1049,7 +1049,7 @@ class WhatsAppBotManager { if (data.success) { this.showSuccess('Reacción enviada'); // Refrescar mensajes - await this.loadMessages(this.currentUserId, false); + await this.loadconversations(this.currentUserId, false); } else { this.showError('Error enviando reacción: ' + (data.error || 'desconocido')); } diff --git a/assets/js/app_simple.js b/assets/js/app_simple.js index 230d405..2f88c42 100644 --- a/assets/js/app_simple.js +++ b/assets/js/app_simple.js @@ -46,11 +46,11 @@ class SimpleWhatsAppManager { setupFormListeners() { // Formulario de configuración - const settingsForm = document.getElementById('settings-form'); - if (settingsForm) { - settingsForm.addEventListener('submit', (e) => { + const system_configForm = document.getElementById('system_config-form'); + if (system_configForm) { + system_configForm.addEventListener('submit', (e) => { e.preventDefault(); - this.saveSettings(); + this.savesystem_config(); }); } @@ -108,8 +108,8 @@ class SimpleWhatsAppManager { case 'users': this.loadUsers(); break; - case 'messages': - this.loadMessages(); + case 'conversations': + this.loadconversations(); break; case 'templates': this.loadTemplates(); @@ -123,8 +123,8 @@ class SimpleWhatsAppManager { case 'logs': this.loadLogs(); break; - case 'settings': - this.loadSettings(); + case 'system_config': + this.loadsystem_config(); break; default: this.log(`Tab no reconocido: ${tabName}`, 'warning'); @@ -200,12 +200,12 @@ class SimpleWhatsAppManager { 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)) { + const recentconversationsResponse = await this.apiCall('get_recent_conversations.php'); + if (recentconversationsResponse && recentconversationsResponse.success && Array.isArray(recentconversationsResponse.data)) { + this.updateRecentconversations(recentconversationsResponse.data); + } else if (recentconversationsResponse && Array.isArray(recentconversationsResponse)) { // Retrocompatibilidad por si la API devuelve directamente el array - this.updateRecentMessages(recentMessagesResponse); + this.updateRecentconversations(recentconversationsResponse); } // Actualizar gráfico si existe @@ -222,9 +222,9 @@ class SimpleWhatsAppManager { if (stats) { const elements = [ { id: 'total-users', value: stats.total_users || 0 }, - { id: 'messages-today', value: stats.messages_today || 0 }, + { id: 'conversations-today', value: stats.conversations_today || 0 }, { id: 'active-users', value: stats.active_users || 0 }, - { id: 'total-messages', value: stats.total_messages || 0 } + { id: 'total-conversations', value: stats.total_conversations || 0 } ]; elements.forEach(item => { @@ -237,8 +237,8 @@ class SimpleWhatsAppManager { } } - updateRecentMessages(messages) { - const container = document.getElementById('recent-messages'); + updateRecentconversations(conversations) { + const container = document.getElementById('recent-conversations'); if (!container) { this.log('Contenedor de mensajes recientes no encontrado', 'warning'); return; @@ -246,9 +246,9 @@ class SimpleWhatsAppManager { container.innerHTML = ''; - if (messages && messages.length > 0) { - this.log(`Mostrando ${messages.length} mensajes recientes`); - messages.forEach(message => { + if (conversations && conversations.length > 0) { + this.log(`Mostrando ${conversations.length} mensajes recientes`); + conversations.forEach(message => { const messageElement = this.createRecentMessageElement(message); container.appendChild(messageElement); }); @@ -281,17 +281,17 @@ class SimpleWhatsAppManager { } async updateChart() { - if (!this.charts || !this.charts.messages) { + if (!this.charts || !this.charts.conversations) { 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(); + if (chartData && this.charts.conversations) { + this.charts.conversations.data.labels = chartData.labels || []; + this.charts.conversations.data.datasets[0].data = chartData.data || []; + this.charts.conversations.update(); this.log('Gráfico actualizado correctamente'); } } catch (error) { @@ -300,7 +300,7 @@ class SimpleWhatsAppManager { } setupCharts() { - const ctx = document.getElementById('messagesChart'); + const ctx = document.getElementById('conversationsChart'); if (!ctx) { this.log('Canvas de gráfico no encontrado', 'warning'); return; @@ -313,7 +313,7 @@ class SimpleWhatsAppManager { try { this.charts = this.charts || {}; - this.charts.messages = new Chart(ctx, { + this.charts.conversations = new Chart(ctx, { type: 'line', data: { labels: [], @@ -634,14 +634,14 @@ class SimpleWhatsAppManager { return date.toLocaleDateString(); } - async loadSettings() { + async loadsystem_config() { this.log('Cargando configuraciones'); try { const response = await this.apiCall('manage_config.php?action=whatsapp'); if (response && response.success) { - this.updateSettingsForm(response.data); + this.updatesystem_configForm(response.data); } } catch (error) { @@ -649,7 +649,7 @@ class SimpleWhatsAppManager { } } - updateSettingsForm(data) { + updatesystem_configForm(data) { if (!data) return; const fields = [ @@ -672,10 +672,10 @@ class SimpleWhatsAppManager { }); } - async saveSettings() { + async savesystem_config() { this.log('Guardando configuraciones'); - const settings = { + const system_config = { token: document.getElementById('whatsapp-token').value, phone_number_id: document.getElementById('phone-number-id').value, webhook_verify_token: document.getElementById('webhook-token').value, @@ -687,7 +687,7 @@ class SimpleWhatsAppManager { try { const response = await this.apiCall('manage_config.php?action=save_whatsapp', { method: 'POST', - body: { whatsapp: settings } + body: { whatsapp: system_config } }); if (response && response.success) { @@ -741,7 +741,7 @@ class SimpleWhatsAppManager { }, 5000); } - async loadMessages() { + async loadconversations() { this.log('Cargando interfaz de mensajes'); try { @@ -1606,7 +1606,7 @@ window.openChatWindow = function (userId) { }; // Función para mostrar modal de chat -function showChatModal(user, messages) { +function showChatModal(user, conversations) { // Escapar datos del usuario para evitar XSS const userName = escapeHtml(user.name || 'Usuario'); const userPhone = escapeHtml(user.phone_number || ''); @@ -1623,8 +1623,8 @@ function showChatModal(user, messages) {