diff --git a/api/get_last_webhook_time.php b/api/get_last_webhook_time.php new file mode 100644 index 0000000..5e70016 --- /dev/null +++ b/api/get_last_webhook_time.php @@ -0,0 +1,51 @@ +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']); +} diff --git a/api/get_user_conversations.php b/api/get_user_conversations.php new file mode 100644 index 0000000..87bfaa2 --- /dev/null +++ b/api/get_user_conversations.php @@ -0,0 +1,4 @@ + { + 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}`; diff --git a/index.php b/index.php index a1000fd..f8effc4 100644 --- a/index.php +++ b/index.php @@ -645,7 +645,7 @@ try { - +