version estable
This commit is contained in:
BIN
Binary file not shown.
+47
-11
@@ -6,19 +6,15 @@ header('Access-Control-Allow-Headers: Content-Type');
|
|||||||
|
|
||||||
require_once __DIR__ . '/../config/config.php';
|
require_once __DIR__ . '/../config/config.php';
|
||||||
|
|
||||||
|
// Suprimir errores para obtener JSON limpio
|
||||||
|
error_reporting(E_ERROR | E_PARSE);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Verificar autenticación si no estás en modo debug
|
// Modo debug: desactivar autenticación si existe el parámetro debug
|
||||||
$debugMode = isset($_GET['debug']);
|
$debugMode = isset($_GET['debug']) && $_GET['debug'] === 'true';
|
||||||
|
|
||||||
if (!$debugMode) {
|
if (!$debugMode) {
|
||||||
if (session_status() === PHP_SESSION_NONE) {
|
requireAuthentication();
|
||||||
session_start();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!isset($_SESSION['user_id'])) {
|
|
||||||
http_response_code(401);
|
|
||||||
echo json_encode(['error' => 'No autorizado']);
|
|
||||||
exit;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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) {
|
||||||
|
|||||||
+320
-114
@@ -7,13 +7,14 @@ class SimpleWhatsAppManager {
|
|||||||
constructor() {
|
constructor() {
|
||||||
this.apiBaseUrl = './api/';
|
this.apiBaseUrl = './api/';
|
||||||
this.currentTab = 'dashboard';
|
this.currentTab = 'dashboard';
|
||||||
|
|
||||||
this.init();
|
this.init();
|
||||||
}
|
}
|
||||||
|
|
||||||
init() {
|
init() {
|
||||||
this.log('Iniciando sistema simplificado');
|
this.log('Iniciando sistema simplificado');
|
||||||
this.setupEventListeners();
|
this.setupEventListeners();
|
||||||
|
this.setupCharts();
|
||||||
this.loadDashboard();
|
this.loadDashboard();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,7 +25,7 @@ class SimpleWhatsAppManager {
|
|||||||
|
|
||||||
setupEventListeners() {
|
setupEventListeners() {
|
||||||
this.log('Configurando event listeners');
|
this.log('Configurando event listeners');
|
||||||
|
|
||||||
// Navegación de tabs - más defensiva
|
// Navegación de tabs - más defensiva
|
||||||
const navLinks = document.querySelectorAll('.nav-link[data-tab]');
|
const navLinks = document.querySelectorAll('.nav-link[data-tab]');
|
||||||
if (navLinks) {
|
if (navLinks) {
|
||||||
@@ -65,7 +66,7 @@ class SimpleWhatsAppManager {
|
|||||||
|
|
||||||
showTab(tabName) {
|
showTab(tabName) {
|
||||||
this.log(`Cambiando a tab: ${tabName}`);
|
this.log(`Cambiando a tab: ${tabName}`);
|
||||||
|
|
||||||
// Ocultar todas las pestañas
|
// Ocultar todas las pestañas
|
||||||
const tabs = document.querySelectorAll('.tab-content');
|
const tabs = document.querySelectorAll('.tab-content');
|
||||||
if (tabs) {
|
if (tabs) {
|
||||||
@@ -96,7 +97,7 @@ class SimpleWhatsAppManager {
|
|||||||
|
|
||||||
loadTabData(tabName) {
|
loadTabData(tabName) {
|
||||||
this.log(`Cargando datos para tab: ${tabName}`);
|
this.log(`Cargando datos para tab: ${tabName}`);
|
||||||
|
|
||||||
switch (tabName) {
|
switch (tabName) {
|
||||||
case 'dashboard':
|
case 'dashboard':
|
||||||
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;
|
||||||
@@ -123,9 +127,9 @@ class SimpleWhatsAppManager {
|
|||||||
|
|
||||||
async apiCall(endpoint, options = {}) {
|
async apiCall(endpoint, options = {}) {
|
||||||
const url = `${this.apiBaseUrl}${endpoint}${endpoint.includes('?') ? '&' : '?'}debug=true`;
|
const url = `${this.apiBaseUrl}${endpoint}${endpoint.includes('?') ? '&' : '?'}debug=true`;
|
||||||
|
|
||||||
this.log(`API Call: ${url}`, 'info');
|
this.log(`API Call: ${url}`, 'info');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
method: options.method || 'GET',
|
method: options.method || 'GET',
|
||||||
@@ -143,7 +147,7 @@ class SimpleWhatsAppManager {
|
|||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
this.log(`API Response: ${JSON.stringify(data).substring(0, 100)}...`, 'success');
|
this.log(`API Response: ${JSON.stringify(data).substring(0, 100)}...`, 'success');
|
||||||
return data;
|
return data;
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.log(`API Error: ${error.message}`, 'error');
|
this.log(`API Error: ${error.message}`, 'error');
|
||||||
this.showError('Error en petición: ' + error.message);
|
this.showError('Error en petición: ' + error.message);
|
||||||
@@ -153,9 +157,9 @@ class SimpleWhatsAppManager {
|
|||||||
|
|
||||||
async apiCallReal(endpoint, options = {}) {
|
async apiCallReal(endpoint, options = {}) {
|
||||||
const url = `${this.apiBaseUrl}${endpoint}`;
|
const url = `${this.apiBaseUrl}${endpoint}`;
|
||||||
|
|
||||||
this.log(`API Call (REAL): ${url}`, 'info');
|
this.log(`API Call (REAL): ${url}`, 'info');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(url, {
|
const response = await fetch(url, {
|
||||||
method: options.method || 'GET',
|
method: options.method || 'GET',
|
||||||
@@ -173,7 +177,7 @@ class SimpleWhatsAppManager {
|
|||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
this.log(`API Response (REAL): ${JSON.stringify(data).substring(0, 100)}...`, 'success');
|
this.log(`API Response (REAL): ${JSON.stringify(data).substring(0, 100)}...`, 'success');
|
||||||
return data;
|
return data;
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.log(`API Error (REAL): ${error.message}`, 'error');
|
this.log(`API Error (REAL): ${error.message}`, 'error');
|
||||||
this.showError('Error en petición real: ' + error.message);
|
this.showError('Error en petición real: ' + error.message);
|
||||||
@@ -183,50 +187,181 @@ class SimpleWhatsAppManager {
|
|||||||
|
|
||||||
async loadDashboard() {
|
async loadDashboard() {
|
||||||
this.log('Cargando dashboard');
|
this.log('Cargando dashboard');
|
||||||
|
|
||||||
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;
|
|
||||||
|
if (stats) {
|
||||||
// Actualizar elementos del dashboard si existen
|
|
||||||
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');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await this.apiCall('get_users.php');
|
const response = await this.apiCall('get_users.php');
|
||||||
|
|
||||||
if (response && response.success) {
|
if (response && response.success) {
|
||||||
this.updateUsersList(response.data || []);
|
this.updateUsersList(response.data || []);
|
||||||
} else {
|
} else {
|
||||||
this.showError('No se pudieron cargar los usuarios');
|
this.showError('No se pudieron cargar los usuarios');
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.showError('Error cargando usuarios: ' + error.message);
|
this.showError('Error cargando usuarios: ' + error.message);
|
||||||
}
|
}
|
||||||
@@ -242,11 +377,11 @@ class SimpleWhatsAppManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let html = '';
|
let html = '';
|
||||||
|
|
||||||
users.forEach(user => {
|
users.forEach(user => {
|
||||||
const createdDate = new Date(user.created_at);
|
const createdDate = new Date(user.created_at);
|
||||||
const formatDate = createdDate.toLocaleDateString() + ' ' + createdDate.toLocaleTimeString('es', { hour: '2-digit', minute: '2-digit' });
|
const formatDate = createdDate.toLocaleDateString() + ' ' + createdDate.toLocaleTimeString('es', { hour: '2-digit', minute: '2-digit' });
|
||||||
|
|
||||||
html += `
|
html += `
|
||||||
<tr>
|
<tr>
|
||||||
<td>${user.id}</td>
|
<td>${user.id}</td>
|
||||||
@@ -266,23 +401,28 @@ class SimpleWhatsAppManager {
|
|||||||
</tr>
|
</tr>
|
||||||
`;
|
`;
|
||||||
});
|
});
|
||||||
|
|
||||||
container.innerHTML = html;
|
container.innerHTML = html;
|
||||||
}
|
}
|
||||||
|
|
||||||
async loadConversations() {
|
async loadConversations() {
|
||||||
this.log('Cargando conversaciones');
|
this.log('Cargando conversaciones');
|
||||||
|
|
||||||
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) {
|
|
||||||
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 {
|
} 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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -297,11 +437,11 @@ class SimpleWhatsAppManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let html = '';
|
let html = '';
|
||||||
|
|
||||||
conversations.forEach(conv => {
|
conversations.forEach(conv => {
|
||||||
const date = new Date(conv.created_at);
|
const date = new Date(conv.created_at);
|
||||||
const formatDate = date.toLocaleDateString() + ' ' + date.toLocaleTimeString('es', { hour: '2-digit', minute: '2-digit' });
|
const formatDate = date.toLocaleDateString() + ' ' + date.toLocaleTimeString('es', { hour: '2-digit', minute: '2-digit' });
|
||||||
|
|
||||||
html += `
|
html += `
|
||||||
<tr>
|
<tr>
|
||||||
<td>
|
<td>
|
||||||
@@ -326,20 +466,20 @@ class SimpleWhatsAppManager {
|
|||||||
</tr>
|
</tr>
|
||||||
`;
|
`;
|
||||||
});
|
});
|
||||||
|
|
||||||
container.innerHTML = html;
|
container.innerHTML = html;
|
||||||
}
|
}
|
||||||
|
|
||||||
async loadSettings() {
|
async loadSettings() {
|
||||||
this.log('Cargando configuraciones');
|
this.log('Cargando configuraciones');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await this.apiCall('manage_config.php?action=whatsapp');
|
const response = await this.apiCall('manage_config.php?action=whatsapp');
|
||||||
|
|
||||||
if (response && response.success) {
|
if (response && response.success) {
|
||||||
this.updateSettingsForm(response.data);
|
this.updateSettingsForm(response.data);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.showError('Error cargando configuraciones: ' + error.message);
|
this.showError('Error cargando configuraciones: ' + error.message);
|
||||||
}
|
}
|
||||||
@@ -347,7 +487,7 @@ class SimpleWhatsAppManager {
|
|||||||
|
|
||||||
updateSettingsForm(data) {
|
updateSettingsForm(data) {
|
||||||
if (!data) return;
|
if (!data) return;
|
||||||
|
|
||||||
const fields = [
|
const fields = [
|
||||||
{ id: 'whatsapp-token', value: data.token },
|
{ id: 'whatsapp-token', value: data.token },
|
||||||
{ id: 'phone-number-id', value: data.phone_number_id },
|
{ id: 'phone-number-id', value: data.phone_number_id },
|
||||||
@@ -355,7 +495,7 @@ class SimpleWhatsAppManager {
|
|||||||
{ id: 'business-name', value: data.business_name },
|
{ id: 'business-name', value: data.business_name },
|
||||||
{ id: 'welcome-message', value: data.welcome_message }
|
{ id: 'welcome-message', value: data.welcome_message }
|
||||||
];
|
];
|
||||||
|
|
||||||
fields.forEach(field => {
|
fields.forEach(field => {
|
||||||
const element = document.getElementById(field.id);
|
const element = document.getElementById(field.id);
|
||||||
if (element && field.value) {
|
if (element && field.value) {
|
||||||
@@ -369,7 +509,7 @@ class SimpleWhatsAppManager {
|
|||||||
|
|
||||||
async saveSettings() {
|
async saveSettings() {
|
||||||
this.log('Guardando configuraciones');
|
this.log('Guardando configuraciones');
|
||||||
|
|
||||||
const settings = {
|
const settings = {
|
||||||
token: document.getElementById('whatsapp-token').value,
|
token: document.getElementById('whatsapp-token').value,
|
||||||
phone_number_id: document.getElementById('phone-number-id').value,
|
phone_number_id: document.getElementById('phone-number-id').value,
|
||||||
@@ -377,19 +517,19 @@ class SimpleWhatsAppManager {
|
|||||||
business_name: document.getElementById('business-name').value,
|
business_name: document.getElementById('business-name').value,
|
||||||
welcome_message: document.getElementById('welcome-message').value
|
welcome_message: document.getElementById('welcome-message').value
|
||||||
};
|
};
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await this.apiCall('manage_config.php?action=save_whatsapp', {
|
const response = await this.apiCall('manage_config.php?action=save_whatsapp', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: { whatsapp: settings }
|
body: { whatsapp: settings }
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response && response.success) {
|
if (response && response.success) {
|
||||||
this.showSuccess('Configuraciones guardadas exitosamente');
|
this.showSuccess('Configuraciones guardadas exitosamente');
|
||||||
} else {
|
} else {
|
||||||
this.showError('Error guardando configuraciones');
|
this.showError('Error guardando configuraciones');
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.showError('Error: ' + error.message);
|
this.showError('Error: ' + error.message);
|
||||||
}
|
}
|
||||||
@@ -414,9 +554,9 @@ class SimpleWhatsAppManager {
|
|||||||
${message}
|
${message}
|
||||||
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
document.body.appendChild(alertDiv);
|
document.body.appendChild(alertDiv);
|
||||||
|
|
||||||
// Auto-remover después de 5 segundos
|
// Auto-remover después de 5 segundos
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
if (alertDiv.parentNode) {
|
if (alertDiv.parentNode) {
|
||||||
@@ -427,22 +567,22 @@ class SimpleWhatsAppManager {
|
|||||||
|
|
||||||
async loadMessages() {
|
async loadMessages() {
|
||||||
this.log('Cargando interfaz de mensajes');
|
this.log('Cargando interfaz de mensajes');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Cargar usuarios para el select
|
// Cargar usuarios para el select
|
||||||
const usersResponse = await this.apiCall('get_users.php');
|
const usersResponse = await this.apiCall('get_users.php');
|
||||||
|
|
||||||
if (usersResponse && usersResponse.success) {
|
if (usersResponse && usersResponse.success) {
|
||||||
this.populateUsersSelect(usersResponse.data || []);
|
this.populateUsersSelect(usersResponse.data || []);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cargar plantillas para el select
|
// Cargar plantillas para el select
|
||||||
const templatesResponse = await this.apiCall('get_templates.php');
|
const templatesResponse = await this.apiCall('get_templates.php');
|
||||||
|
|
||||||
if (templatesResponse && templatesResponse.success) {
|
if (templatesResponse && templatesResponse.success) {
|
||||||
this.populateTemplatesSelect(templatesResponse.data || []);
|
this.populateTemplatesSelect(templatesResponse.data || []);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.showError('Error cargando datos para mensajes: ' + error.message);
|
this.showError('Error cargando datos para mensajes: ' + error.message);
|
||||||
}
|
}
|
||||||
@@ -482,16 +622,16 @@ class SimpleWhatsAppManager {
|
|||||||
|
|
||||||
async loadTemplates() {
|
async loadTemplates() {
|
||||||
this.log('Cargando plantillas');
|
this.log('Cargando plantillas');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await this.apiCall('get_templates.php');
|
const response = await this.apiCall('get_templates.php');
|
||||||
|
|
||||||
if (response && response.success) {
|
if (response && response.success) {
|
||||||
this.updateTemplatesList(response.data || []);
|
this.updateTemplatesList(response.data || []);
|
||||||
} else {
|
} else {
|
||||||
this.showError('Error cargando plantillas');
|
this.showError('Error cargando plantillas');
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.showError('Error cargando plantillas: ' + error.message);
|
this.showError('Error cargando plantillas: ' + error.message);
|
||||||
}
|
}
|
||||||
@@ -507,7 +647,7 @@ class SimpleWhatsAppManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let html = '';
|
let html = '';
|
||||||
|
|
||||||
templates.forEach(template => {
|
templates.forEach(template => {
|
||||||
html += `
|
html += `
|
||||||
<tr>
|
<tr>
|
||||||
@@ -527,13 +667,13 @@ class SimpleWhatsAppManager {
|
|||||||
</tr>
|
</tr>
|
||||||
`;
|
`;
|
||||||
});
|
});
|
||||||
|
|
||||||
container.innerHTML = html;
|
container.innerHTML = html;
|
||||||
}
|
}
|
||||||
|
|
||||||
async saveTemplate() {
|
async saveTemplate() {
|
||||||
this.log('Guardando plantilla');
|
this.log('Guardando plantilla');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const templateData = {
|
const templateData = {
|
||||||
name: document.getElementById('template-name').value,
|
name: document.getElementById('template-name').value,
|
||||||
@@ -541,37 +681,37 @@ class SimpleWhatsAppManager {
|
|||||||
language: document.getElementById('template-language').value,
|
language: document.getElementById('template-language').value,
|
||||||
category: document.getElementById('template-category').value
|
category: document.getElementById('template-category').value
|
||||||
};
|
};
|
||||||
|
|
||||||
// Validar campos requeridos
|
// Validar campos requeridos
|
||||||
if (!templateData.name || !templateData.whatsapp_name) {
|
if (!templateData.name || !templateData.whatsapp_name) {
|
||||||
this.showError('Nombre descriptivo y nombre de WhatsApp son requeridos');
|
this.showError('Nombre descriptivo y nombre de WhatsApp son requeridos');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const response = await this.apiCall('save_template.php', {
|
const response = await this.apiCall('save_template.php', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: templateData
|
body: templateData
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response && response.success) {
|
if (response && response.success) {
|
||||||
this.showSuccess('Plantilla guardada correctamente');
|
this.showSuccess('Plantilla guardada correctamente');
|
||||||
|
|
||||||
// Cerrar modal
|
// Cerrar modal
|
||||||
const modal = document.getElementById('createTemplateModal');
|
const modal = document.getElementById('createTemplateModal');
|
||||||
if (modal) {
|
if (modal) {
|
||||||
const bsModal = bootstrap.Modal.getInstance(modal);
|
const bsModal = bootstrap.Modal.getInstance(modal);
|
||||||
if (bsModal) bsModal.hide();
|
if (bsModal) bsModal.hide();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Limpiar formulario
|
// Limpiar formulario
|
||||||
document.getElementById('template-form').reset();
|
document.getElementById('template-form').reset();
|
||||||
|
|
||||||
// Recargar plantillas
|
// Recargar plantillas
|
||||||
this.loadTemplates();
|
this.loadTemplates();
|
||||||
} else {
|
} else {
|
||||||
this.showError(`Error guardando plantilla: ${response?.error || 'Error desconocido'}`);
|
this.showError(`Error guardando plantilla: ${response?.error || 'Error desconocido'}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.showError('Error guardando plantilla: ' + error.message);
|
this.showError('Error guardando plantilla: ' + error.message);
|
||||||
}
|
}
|
||||||
@@ -579,14 +719,14 @@ class SimpleWhatsAppManager {
|
|||||||
|
|
||||||
async sendMessage() {
|
async sendMessage() {
|
||||||
this.log('Enviando mensaje');
|
this.log('Enviando mensaje');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const recipientType = document.getElementById('recipient-type').value;
|
const recipientType = document.getElementById('recipient-type').value;
|
||||||
const messageType = document.getElementById('message-type').value;
|
const messageType = document.getElementById('message-type').value;
|
||||||
|
|
||||||
let recipient;
|
let recipient;
|
||||||
let messageData = {};
|
let messageData = {};
|
||||||
|
|
||||||
// Obtener destinatario
|
// Obtener destinatario
|
||||||
if (recipientType === 'existing') {
|
if (recipientType === 'existing') {
|
||||||
const userSelect = document.getElementById('message-recipient');
|
const userSelect = document.getElementById('message-recipient');
|
||||||
@@ -594,11 +734,11 @@ class SimpleWhatsAppManager {
|
|||||||
this.showError('Por favor selecciona un usuario');
|
this.showError('Por favor selecciona un usuario');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Obtener datos del usuario seleccionado
|
// Obtener datos del usuario seleccionado
|
||||||
const selectedOption = userSelect.options[userSelect.selectedIndex];
|
const selectedOption = userSelect.options[userSelect.selectedIndex];
|
||||||
const userId = userSelect.value;
|
const userId = userSelect.value;
|
||||||
|
|
||||||
// Necesitamos obtener el número de teléfono del usuario
|
// Necesitamos obtener el número de teléfono del usuario
|
||||||
const usersResponse = await this.apiCall('get_users.php');
|
const usersResponse = await this.apiCall('get_users.php');
|
||||||
if (usersResponse && usersResponse.success) {
|
if (usersResponse && usersResponse.success) {
|
||||||
@@ -620,7 +760,7 @@ class SimpleWhatsAppManager {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Preparar mensaje según el tipo
|
// Preparar mensaje según el tipo
|
||||||
if (messageType === 'text') {
|
if (messageType === 'text') {
|
||||||
const messageText = document.getElementById('message-text').value;
|
const messageText = document.getElementById('message-text').value;
|
||||||
@@ -628,7 +768,7 @@ class SimpleWhatsAppManager {
|
|||||||
this.showError('Por favor escribe un mensaje');
|
this.showError('Por favor escribe un mensaje');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
messageData = {
|
messageData = {
|
||||||
recipient: recipient,
|
recipient: recipient,
|
||||||
type: 'text',
|
type: 'text',
|
||||||
@@ -640,21 +780,21 @@ class SimpleWhatsAppManager {
|
|||||||
this.showError('Por favor selecciona una plantilla');
|
this.showError('Por favor selecciona una plantilla');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
messageData = {
|
messageData = {
|
||||||
recipient: recipient,
|
recipient: recipient,
|
||||||
type: 'template',
|
type: 'template',
|
||||||
template_name: templateSelect.value
|
template_name: templateSelect.value
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
this.log(`Enviando mensaje a ${recipient}: ${JSON.stringify(messageData)}`);
|
this.log(`Enviando mensaje a ${recipient}: ${JSON.stringify(messageData)}`);
|
||||||
|
|
||||||
// Preguntar al usuario si quiere envío real o simulado
|
// 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)');
|
const sendReal = confirm('¿Enviar mensaje REAL por WhatsApp?\n\nSí = Envío real\nNo = Envío simulado (debug)');
|
||||||
|
|
||||||
// Enviar mensaje
|
// Enviar mensaje
|
||||||
const response = sendReal
|
const response = sendReal
|
||||||
? await this.apiCallReal('send_message.php', {
|
? await this.apiCallReal('send_message.php', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: messageData
|
body: messageData
|
||||||
@@ -663,27 +803,42 @@ class SimpleWhatsAppManager {
|
|||||||
method: 'POST',
|
method: 'POST',
|
||||||
body: messageData
|
body: messageData
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response && response.success) {
|
if (response && response.success) {
|
||||||
this.showSuccess(`Mensaje enviado correctamente a ${recipient}`);
|
this.showSuccess(`Mensaje enviado correctamente a ${recipient}`);
|
||||||
|
|
||||||
// Limpiar formulario
|
// Limpiar formulario
|
||||||
document.getElementById('send-message-form').reset();
|
document.getElementById('send-message-form').reset();
|
||||||
document.getElementById('message-recipient').value = '';
|
document.getElementById('message-recipient').value = '';
|
||||||
} else {
|
} else {
|
||||||
this.showError(`Error enviando mensaje: ${response?.error || 'Error desconocido'}`);
|
this.showError(`Error enviando mensaje: ${response?.error || 'Error desconocido'}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
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 {
|
||||||
window.whatsappManager = new SimpleWhatsAppManager();
|
window.whatsappManager = new SimpleWhatsAppManager();
|
||||||
console.log('WhatsApp Manager inicializado correctamente');
|
console.log('WhatsApp Manager inicializado correctamente');
|
||||||
@@ -693,19 +848,19 @@ 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');
|
||||||
if (!modalElement) {
|
if (!modalElement) {
|
||||||
console.error('❌ Modal de plantilla no encontrado');
|
console.error('❌ Modal de plantilla no encontrado');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const form = document.getElementById('template-form');
|
const form = document.getElementById('template-form');
|
||||||
if (form) form.reset();
|
if (form) form.reset();
|
||||||
|
|
||||||
if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
|
if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
|
||||||
const modal = new bootstrap.Modal(modalElement);
|
const modal = new bootstrap.Modal(modalElement);
|
||||||
modal.show();
|
modal.show();
|
||||||
@@ -719,19 +874,19 @@ 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');
|
||||||
if (!modalElement) {
|
if (!modalElement) {
|
||||||
console.error('❌ Modal de menú no encontrado');
|
console.error('❌ Modal de menú no encontrado');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const form = document.getElementById('menu-form');
|
const form = document.getElementById('menu-form');
|
||||||
if (form) form.reset();
|
if (form) form.reset();
|
||||||
|
|
||||||
if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
|
if (typeof bootstrap !== 'undefined' && bootstrap.Modal) {
|
||||||
const modal = new bootstrap.Modal(modalElement);
|
const modal = new bootstrap.Modal(modalElement);
|
||||||
modal.show();
|
modal.show();
|
||||||
@@ -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,11 +964,11 @@ 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');
|
||||||
|
|
||||||
if (recipientType === 'manual') {
|
if (recipientType === 'manual') {
|
||||||
existingGroup.style.display = 'none';
|
existingGroup.style.display = 'none';
|
||||||
manualGroup.style.display = 'block';
|
manualGroup.style.display = 'block';
|
||||||
@@ -823,11 +978,11 @@ 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');
|
||||||
|
|
||||||
if (messageType === 'template') {
|
if (messageType === 'template') {
|
||||||
textGroup.style.display = 'none';
|
textGroup.style.display = 'none';
|
||||||
templateGroup.style.display = 'block';
|
templateGroup.style.display = 'block';
|
||||||
@@ -838,9 +993,9 @@ 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
|
||||||
resultsDiv.innerHTML = `
|
resultsDiv.innerHTML = `
|
||||||
<div class="text-center">
|
<div class="text-center">
|
||||||
@@ -850,7 +1005,7 @@ window.runDiagnostic = function() {
|
|||||||
<p class="mt-2">Ejecutando diagnóstico...</p>
|
<p class="mt-2">Ejecutando diagnóstico...</p>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
fetch('./api/diagnose_whatsapp.php')
|
fetch('./api/diagnose_whatsapp.php')
|
||||||
.then(response => response.json())
|
.then(response => response.json())
|
||||||
.then(data => {
|
.then(data => {
|
||||||
@@ -878,7 +1033,7 @@ window.runDiagnostic = function() {
|
|||||||
|
|
||||||
function displayDiagnosticResults(data) {
|
function displayDiagnosticResults(data) {
|
||||||
const resultsDiv = document.getElementById('diagnostic-results');
|
const resultsDiv = document.getElementById('diagnostic-results');
|
||||||
|
|
||||||
let html = `
|
let html = `
|
||||||
<div class="diagnostic-results">
|
<div class="diagnostic-results">
|
||||||
<small class="text-muted">Última verificación: ${data.timestamp}</small>
|
<small class="text-muted">Última verificación: ${data.timestamp}</small>
|
||||||
@@ -938,15 +1093,15 @@ function displayDiagnosticResults(data) {
|
|||||||
<h6><i class="fas fa-cloud"></i> API WhatsApp</h6>
|
<h6><i class="fas fa-cloud"></i> API WhatsApp</h6>
|
||||||
<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>
|
||||||
`;
|
`;
|
||||||
|
|
||||||
// Recomendaciones
|
// Recomendaciones
|
||||||
if (data.recommendations && data.recommendations.length > 0) {
|
if (data.recommendations && data.recommendations.length > 0) {
|
||||||
html += `
|
html += `
|
||||||
@@ -962,7 +1117,58 @@ function displayDiagnosticResults(data) {
|
|||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user