Update BotService.php
This commit is contained in:
+73
-3
@@ -53,6 +53,15 @@ class BotService {
|
||||
// ignore logging errors
|
||||
}
|
||||
|
||||
// Si ha pasado suficiente tiempo (6 horas) desde la última actividad, reiniciar la conversación y permitir re-enviar el welcome
|
||||
try {
|
||||
if (!empty($user['id'])) {
|
||||
$this->maybeResetConversationAfterIdle($user['id']);
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
error_log('[BotService] maybeResetConversationAfterIdle threw: ' . $e->getMessage());
|
||||
}
|
||||
|
||||
// Verificar si es un nuevo usuario (enviar mensaje de bienvenida)
|
||||
if ($this->isNewUser($user['id'])) {
|
||||
$this->sendWelcomeMessage($phoneNumber);
|
||||
@@ -370,19 +379,76 @@ class BotService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Si la última actividad del usuario fue hace >= 6 horas, reinicia el estado de la conversación
|
||||
* para que el usuario vuelva a recibir la bienvenida y empiece desde cero. Esto incluye limpiar
|
||||
* menús, flags de espera/asesor, y `welcome_sent_at`.
|
||||
*/
|
||||
private function maybeResetConversationAfterIdle($userId) {
|
||||
try {
|
||||
$sixHours = 6 * 3600;
|
||||
$row = $this->db->fetch("SELECT MAX(created_at) as last_at FROM conversations WHERE user_id = :uid", ['uid' => $userId]);
|
||||
$lastAt = $row && !empty($row['last_at']) ? strtotime($row['last_at']) : null;
|
||||
if (!$lastAt) return false;
|
||||
if ((time() - $lastAt) >= $sixHours) {
|
||||
try {
|
||||
$this->db->update('users', [
|
||||
'current_menu_id' => null,
|
||||
'current_step' => 0,
|
||||
'session_data' => null,
|
||||
'welcome_sent_at' => null,
|
||||
'advisor_requested' => 0,
|
||||
'on_hold' => 0,
|
||||
'in_service' => 0,
|
||||
'in_service_by' => null,
|
||||
'bot_paused_until' => null
|
||||
], 'id = :id', ['id' => $userId]);
|
||||
|
||||
// Registrar mensaje sistema para trazabilidad
|
||||
$this->db->insert('conversations', [
|
||||
'user_id' => $userId,
|
||||
'direction' => 'outgoing',
|
||||
'message_type' => 'text',
|
||||
'content' => json_encode(['system' => 'system', 'type' => 'session_reset', 'text' => 'Sesión reiniciada por inactividad (6h).']),
|
||||
'status' => 'sent',
|
||||
'created_at' => date('Y-m-d H:i:s')
|
||||
]);
|
||||
|
||||
error_log("[BotService] maybeResetConversationAfterIdle: reset session for user_id={$userId} after inactivity");
|
||||
} catch (Exception $e) {
|
||||
error_log('[BotService] maybeResetConversationAfterIdle -> failed to reset user state: ' . $e->getMessage());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} catch (Exception $e) {
|
||||
error_log('[BotService] maybeResetConversationAfterIdle failed: ' . $e->getMessage());
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Verificar si es un nuevo usuario
|
||||
* Ahora: reenvía el welcome si no se envió o si el último welcome fue hace >= 6 horas
|
||||
*/
|
||||
private function isNewUser($userId) {
|
||||
$messageCount = $this->db->fetch(
|
||||
"SELECT COUNT(*) as count FROM conversations WHERE user_id = :user_id",
|
||||
['user_id' => $userId]
|
||||
);
|
||||
// Evitar reenviar welcome si ya se envió
|
||||
// Evitar reenviar welcome si ya se envió recientemente
|
||||
$user = $this->db->fetch("SELECT welcome_sent_at FROM users WHERE id = :id", ['id' => $userId]);
|
||||
$welcomeSent = !empty($user['welcome_sent_at']);
|
||||
return ($messageCount['count'] <= 1) && !$welcomeSent; // Solo el mensaje actual y si no se ha enviado welcome
|
||||
$welcomeSentAt = !empty($user['welcome_sent_at']) ? strtotime($user['welcome_sent_at']) : null;
|
||||
|
||||
// Si nunca se envió el welcome, consideramos nuevo
|
||||
if (!$welcomeSentAt) return true;
|
||||
|
||||
// Si el welcome fue hace 6 horas o más, consideramos que debe reenviarse
|
||||
$sixHours = 6 * 3600;
|
||||
if ((time() - $welcomeSentAt) >= $sixHours) return true;
|
||||
|
||||
// En otros casos, no es nuevo
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -997,6 +1063,10 @@ class BotService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Si ha pasado 6 horas desde la última actividad, reinicia el estado de la conversación para que
|
||||
* el bot vuelva a enviar el mensaje de bienvenida y el usuario empiece
|
||||
|
||||
/**
|
||||
* Marcar la conversación como "en servicio" por un operador (Atender)
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user