👤
Atención Personal
Un asesor humano ha tomado control de esta conversación y te responderá pronto.
`;
elements.messagesContainer.appendChild(noticeDiv);
scrollToBottom();
}
/**
* Muestra el badge de notificación en el botón del chatbot
*/
function showBadgeNotification() {
if (chatbotState.initialized) {
chatbotState.unreadCount++;
updateBadge();
}
}
/**
* Oculta el badge de notificación
*/
function hideBadgeNotification() {
chatbotState.unreadCount = 0;
updateBadge();
}
/**
* Actualiza el badge con el contador de mensajes no leídos
*/
function updateBadge() {
if (elements.badge) {
if (chatbotState.unreadCount > 0) {
elements.badge.textContent = chatbotState.unreadCount > 9 ? '9+' : chatbotState.unreadCount;
elements.badge.style.display = 'flex';
} else {
elements.badge.style.display = 'none';
}
}
}
function saveSession() {
if (chatbotState.sessionId) {
try {
localStorage.setItem('chatbot_session', JSON.stringify({
sessionId: chatbotState.sessionId,
threadId: chatbotState.threadId,
privacyAccepted: chatbotState.privacyAccepted,
timestamp: Date.now(),
}));
} catch (e) {
console.warn('localStorage not available:', e);
}
}
}
function loadSession() {
try {
const saved = localStorage.getItem('chatbot_session');
if (saved) {
const data = JSON.parse(saved);
// Verificar que no haya expirado (7 días)
const maxAge = 7 * 24 * 60 * 60 * 1000;
const age = Date.now() - data.timestamp;
if (age < maxAge) {
chatbotState.sessionId = data.sessionId;
chatbotState.threadId = data.threadId;
chatbotState.privacyAccepted = data.privacyAccepted;
// Cargar historial si el usuario está autenticado
if (document.body.dataset.userAuthenticated === 'true') {
loadHistory();
}
} else {
// Sesión expirada
localStorage.removeItem('chatbot_session');
}
}
} catch (e) {
console.warn('Error loading session:', e);
}
}
function loadHistory() {
fetch('/lms/api/chatbot/history/')
.then(response => response.json())
.then(data => {
if (data.success && data.messages.length > 0) {
// Limpiar mensajes de bienvenida
elements.messagesContainer.innerHTML = '';
// Agregar mensajes del historial
data.messages.forEach(msg => {
const role = msg.role.toLowerCase();
if (role !== 'system') {
addMessage(role, msg.content);
}
});
// Guardar el ID del último mensaje
if (data.messages.length > 0) {
const lastMsg = data.messages[data.messages.length - 1];
chatbotState.lastMessageId = lastMsg.id;
}
if (!chatbotState.initialized) {
chatbotState.initialized = true;
}
// Hacer scroll al último mensaje después de cargar el historial
setTimeout(() => {
scrollToBottom();
}, 200);
}
})
.catch(error => {
console.error('Error loading history:', error);
});
}
/**
* Verifica si hay nuevos mensajes en la conversación
* Útil cuando hay intervención humana o mensajes asíncronos
*/
function checkForNewMessages() {
if (!chatbotState.sessionId) return;
// Construir URL con parámetro del último mensaje
let url = '/lms/api/chatbot/history/';
if (chatbotState.lastMessageId) {
url += `?after_id=${chatbotState.lastMessageId}`;
}
fetch(url)
.then(response => response.json())
.then(data => {
if (data.success && data.messages && data.messages.length > 0) {
console.log(`🤖 Found ${data.messages.length} new message(s)`);
// Agregar solo mensajes nuevos
data.messages.forEach(msg => {
const role = msg.role.toLowerCase();
if (role !== 'system') {
// Solo agregar si no es el mensaje que acabamos de enviar nosotros
if (role === 'assistant') {
chatbotState.pollingCount = 0;
console.log('🤖 Polling count reset to 0');
addMessage(role, msg.content);
// Actualizar lastMessageId
chatbotState.lastMessageId = msg.id;
}
}
});
}
})
.catch(error => {
console.error('Error checking for new messages:', error);
});
}
/**
* Inicia el polling para verificar nuevos mensajes cada X segundos
*/
function startPolling() {
// No iniciar si ya está corriendo
if (chatbotState.pollingInterval) return;
console.log('🤖 Starting message polling...');
// Verificar cada 3 segundos
chatbotState.pollingInterval = setInterval(() => {
// Solo hacer polling si hay sesión y privacidad aceptada
if (chatbotState.sessionId && chatbotState.privacyAccepted) {
checkForNewMessages();
}
console.log('🤖 Polling timeout:', chatbotState.pollingTimeout);
console.log('🤖 Polling count:', chatbotState.maxPollingCount * (60000));
if (chatbotState.pollingCount > (chatbotState.maxPollingCount * (60000))) {
console.log('🤖 Polling count exceeded, stopping polling...');
stopPolling();
}
chatbotState.pollingCount = chatbotState.pollingCount + chatbotState.pollingTimeout;
}, chatbotState.pollingTimeout); // 3 segundos
}
/**
* Detiene el polling de mensajes
*/
function stopPolling() {
if (chatbotState.pollingInterval) {
console.log('🤖 Stopping message polling...');
clearInterval(chatbotState.pollingInterval);
chatbotState.pollingInterval = null;
}
}
})();