This commit is contained in:
lizandrogd
2026-01-21 11:17:36 -05:00
parent 5727721f02
commit fccaa3b649
6 changed files with 119 additions and 1 deletions
+51
View File
@@ -0,0 +1,51 @@
<?php
/**
* API - Obtener timestamp del último webhook recibido
*/
require_once '../config/config.php';
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');
try {
$db = Database::getInstance();
$row = $db->fetch('SELECT created_at, request_body FROM webhook_logs ORDER BY created_at DESC LIMIT 1');
if (!$row) {
echo json_encode(['success' => true, 'last_webhook' => null]);
exit;
}
// Intentar extraer teléfonos afectados del request_body (opcional)
$phones = [];
$req = json_decode($row['request_body'], true);
if ($req && isset($req['entry']) && is_array($req['entry'])) {
foreach ($req['entry'] as $entry) {
if (isset($entry['changes']) && is_array($entry['changes'])) {
foreach ($entry['changes'] as $change) {
$val = $change['value'] ?? [];
// buscar en contacts
if (isset($val['contacts']) && is_array($val['contacts'])) {
foreach ($val['contacts'] as $c) {
if (isset($c['wa_id'])) $phones[] = $c['wa_id'];
}
}
// buscar en messages
if (isset($val['messages']) && is_array($val['messages'])) {
foreach ($val['messages'] as $m) {
if (isset($m['from'])) $phones[] = $m['from'];
}
}
}
}
}
}
$phones = array_values(array_unique($phones));
echo json_encode(['success' => true, 'last_webhook' => $row['created_at'], 'phones' => $phones]);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['success' => false, 'error' => 'Error interno del servidor']);
}
+4
View File
@@ -0,0 +1,4 @@
<?php
// Compatibilidad: alias para get_user_messages.php
// Incluye directamente el archivo existente para mantener comportamiento uniforme
require_once 'get_user_messages.php';
+39
View File
@@ -9,6 +9,10 @@ class SimpleWhatsAppManager {
this.currentTab = 'dashboard';
this.init();
// Webhook polling state
this._lastWebhook = null;
this.setupWebhookPolling();
}
init() {
@@ -161,6 +165,41 @@ class SimpleWhatsAppManager {
}
}
// Polling ligero para detectar nuevos webhooks y refrescar UI rápidamente
setupWebhookPolling() {
// Ejecutar cada 5 segundos
setInterval(async () => {
try {
const res = await fetch(this.apiBaseUrl + 'get_last_webhook_time.php');
if (!res.ok) return;
const data = await res.json();
if (!data || !data.success) return;
const last = data.last_webhook;
if (!last) return;
if (this._lastWebhook && this._lastWebhook === last) return;
// Hubo un nuevo webhook
this._lastWebhook = last;
this.log('Nuevo webhook detectado, refrescando conversaciones', 'info');
// Refrescar lista de conversaciones
await this.loadUsers(); // reload users (optional)
await this.loadconversations(); // reload message-related selects if on send_message
await this.loadConversations();
// Si hay un chat abierto, recargar sus mensajes
if (this.currentTab === 'conversations' && this.currentUserId) {
await this.loadconversations(this.currentUserId, false);
}
} catch (e) {
this.log('Error polling webhook: ' + e.message, 'error');
}
}, 5000);
}
async apiCallReal(endpoint, options = {}) {
const url = `${this.apiBaseUrl}${endpoint}`;
+1 -1
View File
@@ -645,7 +645,7 @@ try {
<!-- Scripts -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="./assets/js/app_simple.js?v=2"></script>
<script src="./assets/js/app_simple.js?v=3"></script>
<script>
// Función de diagnóstico mejorada
function runDiagnostic() {
+11
View File
@@ -0,0 +1,11 @@
<?php
// Ejecutar api/get_conversations.php y mostrar salida
chdir(__DIR__ . '/../api');
ob_start();
try {
include 'get_conversations.php';
} catch (Throwable $t) {
echo 'Error: ' . $t->getMessage();
}
$out = ob_get_clean();
echo $out;
+13
View File
@@ -0,0 +1,13 @@
<?php
// Test API get_user_conversations.php
$_GET['user_id'] = 2;
$_GET['debug'] = 'true';
chdir(__DIR__ . '/../api');
ob_start();
try {
include 'get_user_conversations.php';
} catch (Throwable $t) {
echo 'Error: ' . $t->getMessage();
}
$out = ob_get_clean();
echo $out;