This commit is contained in:
lizandrogd
2026-01-21 15:12:15 -05:00
parent 75b8f469f4
commit ddc9a68a40
4 changed files with 51 additions and 6 deletions
+11 -3
View File
@@ -20,9 +20,17 @@ try {
exit; exit;
} }
$db->update('users', ['on_hold' => 0], 'id = :id', ['id' => $userId]); // Use BotService to release hold (sends notification and clears flags)
try {
echo json_encode(['success' => true]); require_once __DIR__ . '/../services/BotService.php';
$bot = new BotService();
$bot->releaseHold($user['phone_number']);
echo json_encode(['success' => true]);
} catch (Exception $e) {
// Fallback to direct DB update if BotService fails
$db->update('users', ['on_hold' => 0, 'advisor_requested' => 0, 'bot_paused_until' => null], 'id = :id', ['id' => $userId]);
echo json_encode(['success' => true, 'warning' => 'BotService failed, flags cleared directly']);
}
} catch (Exception $e) { } catch (Exception $e) {
http_response_code(500); http_response_code(500);
echo json_encode(['success' => false, 'error' => $e->getMessage()]); echo json_encode(['success' => false, 'error' => $e->getMessage()]);
+23 -2
View File
@@ -843,11 +843,23 @@
const releaseBtn = document.getElementById('release-hold-btn'); const releaseBtn = document.getElementById('release-hold-btn');
if (holdIndicator) { if (holdIndicator) {
holdIndicator.style.display = conv.on_hold ? 'inline' : 'none'; // Show different labels depending on state
if (conv.on_hold) {
holdIndicator.textContent = 'EN ESPERA';
holdIndicator.style.color = '#b85';
holdIndicator.style.display = 'inline';
} else if (conv.advisor_requested) {
holdIndicator.textContent = 'SOLICITUD PENDIENTE';
holdIndicator.style.color = '#f39c12';
holdIndicator.style.display = 'inline';
} else {
holdIndicator.style.display = 'none';
}
} }
if (releaseBtn) { if (releaseBtn) {
releaseBtn.style.display = conv.on_hold ? 'inline-block' : 'none'; // show button when on_hold or advisor_requested
releaseBtn.style.display = (conv.on_hold || conv.advisor_requested) ? 'inline-block' : 'none';
releaseBtn.onclick = async () => { releaseBtn.onclick = async () => {
try { try {
const resp = await fetch('api/release_hold.php', { const resp = await fetch('api/release_hold.php', {
@@ -855,9 +867,14 @@
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ user_id: userId }) body: JSON.stringify({ user_id: userId })
}); });
if (resp.status === 401) {
alert('Sesión expirada. Por favor inicie sesión de nuevo.');
return;
}
const json = await resp.json(); const json = await resp.json();
if (json && json.success) { if (json && json.success) {
conv.on_hold = false; conv.on_hold = false;
conv.advisor_requested = 0;
holdIndicator.style.display = 'none'; holdIndicator.style.display = 'none';
releaseBtn.style.display = 'none'; releaseBtn.style.display = 'none';
await this.loadConversations(); await this.loadConversations();
@@ -866,6 +883,10 @@
} }
} catch (e) { } catch (e) {
console.error('Error releasing hold', e); console.error('Error releasing hold', e);
alert('Error liberando espera');
}
};
}
} }
}; };
} }
+1 -1
View File
@@ -653,7 +653,7 @@ try {
<!-- Scripts --> <!-- 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/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="./assets/js/app_simple.js?v=4"></script> <script src="./assets/js/app_simple.js?v=5"></script>
<script> <script>
// Función de diagnóstico mejorada // Función de diagnóstico mejorada
function runDiagnostic() { function runDiagnostic() {
+16
View File
@@ -24,6 +24,14 @@ class BotService {
$messageText = trim($messageText); $messageText = trim($messageText);
$phoneNumber = $user['phone_number']; $phoneNumber = $user['phone_number'];
// DEBUG: log basic context
try {
$userId = $user['id'] ?? 'unknown';
error_log("[BotService] processMessage start - user_id={$userId} phone={$phoneNumber} type={$messageType} message='" . substr($messageText,0,200) . "' current_menu_id=" . ($user['current_menu_id'] ?? 'null') . " on_hold=" . ($user['on_hold'] ?? '0') . " advisor_requested=" . ($user['advisor_requested'] ?? '0') . " bot_paused_until=" . ($user['bot_paused_until'] ?? 'null'));
} catch (Throwable $t) {
// ignore logging errors
}
// Verificar si es un nuevo usuario (enviar mensaje de bienvenida) // Verificar si es un nuevo usuario (enviar mensaje de bienvenida)
if ($this->isNewUser($user['id'])) { if ($this->isNewUser($user['id'])) {
@@ -50,6 +58,7 @@ class BotService {
} catch (Exception $e) { } catch (Exception $e) {
// ignore // ignore
} }
error_log("[BotService] processMessage - returning early because on_hold active for user {$user['id']}");
return; return;
} else { } else {
// El hold expiró, liberar y continuar // El hold expiró, liberar y continuar
@@ -67,6 +76,7 @@ class BotService {
} catch (Exception $e) { } catch (Exception $e) {
// ignore // ignore
} }
error_log("[BotService] processMessage - returning early because advisor_requested active for user {$user['id']}");
return; return;
} else { } else {
// expiró la espera: limpiar flag // expiró la espera: limpiar flag
@@ -244,12 +254,16 @@ class BotService {
$phoneNumber = $user['phone_number']; $phoneNumber = $user['phone_number'];
$currentMenuId = $user['current_menu_id']; $currentMenuId = $user['current_menu_id'];
// DEBUG
try { error_log("[BotService] processMenuSelection - user_id={$user['id']} menu_id={$currentMenuId} received='{$messageText}'"); } catch (Throwable $t) {}
// Verificar si es un número // Verificar si es un número
if (!is_numeric($messageText)) { if (!is_numeric($messageText)) {
$this->whatsappService->sendTextMessage( $this->whatsappService->sendTextMessage(
$phoneNumber, $phoneNumber,
"❌ Por favor, responde solo con el número de la opción deseada." "❌ Por favor, responde solo con el número de la opción deseada."
); );
error_log("[BotService] processMenuSelection - non-numeric response from user {$user['id']}: '{$messageText}'");
return; return;
} }
@@ -266,9 +280,11 @@ class BotService {
$phoneNumber, $phoneNumber,
"❌ Opción inválida. Por favor, selecciona una opción válida del menú." "❌ Opción inválida. Por favor, selecciona una opción válida del menú."
); );
error_log("[BotService] processMenuSelection - no option found for user {$user['id']} menu={$currentMenuId} option={$optionNumber}");
return; return;
} }
error_log("[BotService] processMenuSelection - option found for user {$user['id']} menu={$currentMenuId} option={$optionNumber} action={$option['action_type']}");
// Procesar acción de la opción // Procesar acción de la opción
$this->processMenuAction($phoneNumber, $option); $this->processMenuAction($phoneNumber, $option);
} }