u
This commit is contained in:
+42
-7
@@ -33,9 +33,16 @@ class BotService {
|
||||
// ignore logging errors
|
||||
}
|
||||
|
||||
// Verificar si es un nuevo usuario (enviar mensaje de bienvenida)
|
||||
// Verificar si es un nuevo usuario (iniciar con menú principal)
|
||||
if ($this->isNewUser($user['id'])) {
|
||||
$this->sendWelcomeMessage($phoneNumber);
|
||||
// En lugar de welcome textual, mostramos el menú principal y marcamos welcome_sent
|
||||
try {
|
||||
$this->showMainMenu($phoneNumber);
|
||||
$this->db->update('users', ['welcome_sent_at' => date('Y-m-d H:i:s')], 'phone_number = :phone', ['phone' => $phoneNumber]);
|
||||
error_log("[BotService] processMessage - initial menu sent to new user {$user['id']}");
|
||||
} catch (Exception $e) {
|
||||
error_log('[BotService] Failed to send initial menu: ' . $e->getMessage());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -98,12 +105,16 @@ class BotService {
|
||||
return;
|
||||
}
|
||||
|
||||
// Si el asesor ya respondió después del último mensaje del usuario, frenar al bot
|
||||
// Verificar si el asesor ya respondió después del último mensaje del usuario.
|
||||
// En ese caso NO enviaremos respuestas automáticas, pero sí permitiremos
|
||||
// que el usuario interactúe con menús manualmente.
|
||||
$lastIncoming = $this->db->fetch("SELECT created_at FROM conversations WHERE user_id = :uid AND direction = 'incoming' ORDER BY created_at DESC LIMIT 1", ['uid' => $user['id']]);
|
||||
$lastOutgoing = $this->db->fetch("SELECT created_at FROM conversations WHERE user_id = :uid AND direction = 'outgoing' ORDER BY created_at DESC LIMIT 1", ['uid' => $user['id']]);
|
||||
$advisorReplied = false;
|
||||
if ($lastOutgoing && $lastIncoming && strtotime($lastOutgoing['created_at']) >= strtotime($lastIncoming['created_at'])) {
|
||||
// El asesor ya respondió, no enviar respuestas automáticas
|
||||
return;
|
||||
// El asesor ya respondió, marcar flag pero no retornar (permitir menús y comandos explícitos)
|
||||
$advisorReplied = true;
|
||||
error_log("[BotService] processMessage - advisorReplied=true for user {$user['id']}");
|
||||
}
|
||||
// Verificar si el usuario está en un menú
|
||||
if ($user['current_menu_id']) {
|
||||
@@ -111,7 +122,17 @@ class BotService {
|
||||
} else {
|
||||
// No usar las "respuestas rápidas" (autoresponses) automáticamente desde el bot.
|
||||
// Estas respuestas solo se mostrarán en la UI del chat como "respuestas rápidas".
|
||||
$this->sendDefaultNoMatch($phoneNumber);
|
||||
// Si un asesor ya respondió recientemente, no enviar respuestas automáticas.
|
||||
if (empty($advisorReplied)) {
|
||||
$this->sendDefaultNoMatch($phoneNumber);
|
||||
} else {
|
||||
// Opcional: informar que el asesor ya respondió y no podemos enviar automáticas
|
||||
try {
|
||||
$this->whatsappService->sendTextMessage($phoneNumber, "🔕 Un asesor ya ha intervenido en la conversación, por favor espera su respuesta o utiliza *menu* para ver opciones.");
|
||||
} catch (Exception $e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -269,12 +290,26 @@ class BotService {
|
||||
|
||||
$optionNumber = (int)$messageText;
|
||||
|
||||
// Buscar la opción seleccionada
|
||||
// Buscar la opción seleccionada por número
|
||||
$option = $this->db->fetch(
|
||||
"SELECT * FROM menu_options WHERE menu_id = :menu_id AND option_number = :option_number AND is_active = 1",
|
||||
['menu_id' => $currentMenuId, 'option_number' => $optionNumber]
|
||||
);
|
||||
|
||||
// Si no encontramos por número, intentar buscar por texto (caso de replies interactivos que envían título)
|
||||
if (!$option) {
|
||||
$txt = strtolower(trim($messageText));
|
||||
if (!empty($txt)) {
|
||||
$option = $this->db->fetch(
|
||||
"SELECT * FROM menu_options WHERE menu_id = :menu_id AND is_active = 1 AND (LOWER(text) = :txt OR LOWER(text) LIKE :like) LIMIT 1",
|
||||
['menu_id' => $currentMenuId, 'txt' => $txt, 'like' => "%{$txt}%"]
|
||||
);
|
||||
if ($option) {
|
||||
error_log("[BotService] processMenuSelection - matched option by text for user {$user['id']} menu={$currentMenuId} text='{$txt}' => option_number={$option['option_number']}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!$option) {
|
||||
$this->whatsappService->sendTextMessage(
|
||||
$phoneNumber,
|
||||
|
||||
Reference in New Issue
Block a user