/** * ai-chat-widget.js - Lógica interactiva de UdeCi (SDD-010) * Asistente y Tutor Virtual de UniCABA con soporte RAG, * respuestas concisas y botones de opciones interactivas. */ (function () { 'use strict'; let isProcessing = false; // Limpiar clave histórica compartida para evitar contaminación entre perfiles try { sessionStorage.removeItem('edu_space_udeci_chat_history_v2'); localStorage.removeItem('edu_space_udeci_chat_history_v2'); } catch (e) { } function getContainer() { return document.getElementById('aiChatContainer'); } function getUserId() { const container = getContainer(); const rawId = container ? (container.getAttribute('data-user-id') || container.getAttribute('data-user-email')) : null; if (rawId && rawId.toString().trim()) { return 'usr_' + rawId.toString().trim().replace(/[^a-zA-Z0-9_-]/g, '_'); } // Identificador único de sesión por pestaña si no está logueado let anonId = sessionStorage.getItem('edu_space_anon_chat_session'); if (!anonId) { anonId = 'anon_' + Math.random().toString(36).substring(2, 10) + '_' + Date.now(); sessionStorage.setItem('edu_space_anon_chat_session', anonId); } return anonId; } function getStorageKey() { return 'edu_space_udeci_chat_usr_' + getUserId(); } const ROLE_CHIPS = { docente: [ { label: "📝 Notas de Alumnos", query: "¿Cuáles son las notas y calificaciones de mis alumnos?" }, { label: "📅 Hitos y Exámenes", query: "¿Cuáles son los hitos evaluativos y fechas de examen programadas?" }, { label: "📍 Mis Comisiones", query: "¿Cuáles son mis comisiones a cargo y aulas asignadas?" } ], bedelia: [ { label: "🔄 Flujo 9 Pasos", query: "¿Cuáles son los 9 pasos del flujo de Bedelía?" }, { label: "⚠️ Conflictos Áulicos", query: "¿Cómo funciona la matriz de conflictos y aforo?" }, { label: "🧬 Optimizador IA", query: "¿Cómo uso el optimizador de aulas?" }, { label: "📑 Importar Sheets", query: "¿Cómo uso el importador de Google Sheets?" } ], alumno: [ { label: "📍 Próxima Presencial", query: "¿Cuándo y dónde es mi próxima clase presencial?" }, { label: "📊 Mis Notas", query: "¿Cuáles son mis notas, calificaciones y regularidad en mis materias?" }, { label: "📚 Mis Materias", query: "¿En qué materias y comisiones estoy inscripto?" } ] }; function getUserRole() { const container = getContainer(); const rawRole = (container ? container.getAttribute('data-user-role') : 'alumno') || 'alumno'; const r = rawRole.toLowerCase(); if (r === 'admin' || r.includes('admin')) return 'admin'; if (r.includes('bedelia')) return 'bedelia'; if (r.includes('docente') || r.includes('profesor') || r.includes('teacher')) return 'docente'; return 'alumno'; } function getUserName() { const container = getContainer(); return (container ? container.getAttribute('data-user-name') : '') || ''; } function getRawUserId() { const container = getContainer(); return (container ? container.getAttribute('data-user-id') : '') || ''; } function getUserEmail() { const container = getContainer(); return (container ? container.getAttribute('data-user-email') : '') || ''; } function getWelcomeMessage(role, name) { const greeting = name ? `¡Hola, **${name}**! 👋` : '¡Hola! 👋'; if (role === 'admin') { return `${greeting} Soy **UdeCi**, tu tutor de Edu-Space para Administración y Gobierno del Sistema. ¿Qué deseas gestionar o configurar hoy?`; } else if (role === 'bedelia') { return `${greeting} Soy **UdeCi**, tu asistente de soporte técnico para Bedelía. Puedo guiarte en el circuito de 9 pasos, resolución de conflictos y Moodle.`; } else if (role === 'docente') { return `${greeting} Soy **UdeCi**, tu tutor de Edu-Space para docentes. Puedo orientarte sobre asignaciones de aulas, el Gradebook y tus clases asignadas.`; } else { return `${greeting} Soy **UdeCi**, tu tutor virtual de cursada. Puedo orientarte sobre en qué aula cursas hoy, horarios y notas.`; } } function loadHistory() { try { const raw = sessionStorage.getItem(getStorageKey()); return raw ? JSON.parse(raw) : []; } catch (e) { return []; } } function saveHistory(messages) { try { sessionStorage.setItem(getStorageKey(), JSON.stringify(messages)); } catch (e) { } } function renderMarkdown(text) { if (!text) return ''; let escaped = text .replace(/&/g, '&') .replace(//g, '>'); // Negrita **texto** escaped = escaped.replace(/\*\*(.*?)\*\*/g, '$1'); // Cursiva *texto* escaped = escaped.replace(/\*(.*?)\*/g, '$1'); // Código inline `codigo` escaped = escaped.replace(/`([^`]+)`/g, '$1'); // Saltos de línea escaped = escaped.replace(/\n/g, '
'); return escaped; } function appendMessage(role, content, options = [], save = true) { const messagesContainer = document.getElementById('aiChatMessages'); if (!messagesContainer) return; const isUser = role === 'user'; const msgDiv = document.createElement('div'); msgDiv.className = `ai-msg ${isUser ? 'ai-msg-user' : 'ai-msg-assistant'}`; let html = renderMarkdown(content); // Si es mensaje del asistente y tiene opciones, renderizar botones interactivos if (!isUser && options && options.length > 0) { html += '
'; options.forEach(opt => { const cleanOpt = opt.replace(/^[📍📝👥🔄⚠️🧬📑📚📊❓]\s*/, '').trim(); html += ``; }); html += '
'; } msgDiv.innerHTML = html; messagesContainer.appendChild(msgDiv); messagesContainer.scrollTop = messagesContainer.scrollHeight; // Asignar listeners a los botones de opciones dentro de la burbuja msgDiv.querySelectorAll('.ai-option-btn').forEach(btn => { btn.addEventListener('click', function (e) { e.preventDefault(); const q = this.getAttribute('data-query'); if (q) sendQuery(q); }); }); if (save) { const history = loadHistory(); history.push({ role, content, options }); saveHistory(history); } } async function sendQuery(queryText) { if (!queryText || isProcessing) return; const textarea = document.getElementById('aiChatInput'); const typing = document.getElementById('aiChatTyping'); const sendBtn = document.getElementById('aiChatSendBtn'); if (textarea) textarea.value = ''; appendMessage('user', queryText, [], true); isProcessing = true; if (typing) typing.classList.remove('d-none'); if (sendBtn) sendBtn.disabled = true; const userRole = getUserRole(); const userName = getUserName(); const rawUserId = getRawUserId(); const userEmail = getUserEmail(); const rawHistory = loadHistory(); const payloadMessages = rawHistory.map(m => ({ role: m.role, content: m.content })); try { const res = await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ messages: payloadMessages, user_role: userRole, user_name: userName, user_id: rawUserId || null, user_email: userEmail || null, current_path: window.location.pathname, conversation_id: getUserId() }) }); const data = await res.json(); if (res.ok && data.response) { appendMessage('assistant', data.response, data.quick_options || [], true); // Si UdeCi emite una directiva de guía interactiva, activar el Spotlight if (data.guide_step && window.WalkthroughEngine) { const panel = document.getElementById('aiChatPanel'); const launcher = document.getElementById('aiChatLauncher'); if (panel && launcher) { panel.classList.add('d-none'); launcher.style.transform = ''; launcher.classList.remove('chat-open'); document.body.classList.remove('ai-chat-mobile-open'); } setTimeout(() => { window.WalkthroughEngine.startStep(data.guide_step); }, 250); } } else { const errorMsg = data.detail || data.message || 'UdeCi no pudo procesar la respuesta en este momento.'; appendMessage('assistant', `⚠️ ${errorMsg}`, [], false); } } catch (err) { appendMessage('assistant', `⚠️ Error de comunicación: ${err.message}`, [], false); } finally { isProcessing = false; if (typing) typing.classList.add('d-none'); if (sendBtn) sendBtn.disabled = false; if (textarea) textarea.focus(); } } function initChat() { const launcher = document.getElementById('aiChatLauncher'); const panel = document.getElementById('aiChatPanel'); const closeBtn = document.getElementById('aiChatCloseBtn'); const clearBtn = document.getElementById('aiChatClearBtn'); const textarea = document.getElementById('aiChatInput'); const form = document.getElementById('aiChatForm'); if (!launcher || !panel) return; const role = getUserRole(); const name = getUserName(); function openChat() { panel.classList.remove('d-none'); launcher.style.transform = 'scale(0.9)'; launcher.classList.add('chat-open'); if (window.innerWidth <= 768) { document.body.classList.add('ai-chat-mobile-open'); } setTimeout(() => { if (textarea) textarea.focus(); }, 100); } function closeChat() { panel.classList.add('d-none'); launcher.style.transform = ''; launcher.classList.remove('chat-open'); document.body.classList.remove('ai-chat-mobile-open'); } // Toggle panel launcher.addEventListener('click', () => { const isHidden = panel.classList.contains('d-none'); if (isHidden) { openChat(); } else { closeChat(); } }); if (closeBtn) { closeBtn.addEventListener('click', closeChat); } document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && panel && !panel.classList.contains('d-none')) { closeChat(); } }); // Reiniciar conversación del usuario actual if (clearBtn) { clearBtn.addEventListener('click', () => { sessionStorage.removeItem(getStorageKey()); const messagesContainer = document.getElementById('aiChatMessages'); if (messagesContainer) messagesContainer.innerHTML = ''; appendMessage('assistant', getWelcomeMessage(role, name), [], false); }); } // Cargar historial previo o mensaje de bienvenida const history = loadHistory(); if (history.length > 0) { history.forEach(msg => appendMessage(msg.role, msg.content, msg.options || [], false)); } else { appendMessage('assistant', getWelcomeMessage(role, name), [], false); } // Atajo Enter para enviar if (textarea) { textarea.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); if (form) form.dispatchEvent(new Event('submit', { cancelable: true })); } }); } } window.handleAiChatSubmit = function (e) { if (e) e.preventDefault(); const textarea = document.getElementById('aiChatInput'); if (!textarea) return; const text = textarea.value.trim(); if (text) sendQuery(text); }; if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initChat); } else { initChat(); } })();