Files
admin-edu-space/frontend/public/js/ai-chat-widget.js
T

549 lines
23 KiB
JavaScript

/**
* ai-chat-widget.js - Tutor Virtual UdeCi (UniCABA)
* Experiencia de usuario y diseño tipo Bottom Sheet móvil estilo Mercado Libre.
* Incluye soporte RAG, input dock inteligente, manejo de teclado virtual,
* chips de rol, copia de mensajes y síntesis de voz en español.
*/
(function () {
'use strict';
let isProcessing = false;
let touchStartY = 0;
let touchDeltaY = 0;
// Limpiar claves obsoletas
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, '_');
}
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 = {
admin: [
{ label: "📊 Métricas del Sistema", query: "¿Cuáles son las estadísticas y métricas generales del sistema?" },
{ label: "⚙️ Configuración Global", query: "¿Cómo configuro el servidor LLM y los parámetros de IA?" },
{ label: "🛡️ Roles y Usuarios", query: "¿Cómo administro los usuarios y roles RBAC?" },
{ label: "📍 Ocupación de Sedes", query: "¿Cuál es el estado de ocupación de las sedes y aulas?" }
],
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 genético de aulas?" },
{ label: "📑 Importar Sheets", query: "¿Cómo uso el importador de Google Sheets?" }
],
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?" }
],
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. ¿En qué te puedo ayudar hoy?`;
} else if (role === 'bedelia') {
return `${greeting} Soy **UdeCi**, tu asistente de soporte para Bedelía. Puedo orientarte en el circuito de 9 pasos, resolución de conflictos y reservas.`;
} else if (role === 'docente') {
return `${greeting} Soy **UdeCi**, tu tutor docente. Puedo orientarte sobre asignaciones de aulas, comisiones y el Libro de Calificaciones.`;
} else {
return `${greeting} Soy **UdeCi**, tu tutor virtual de cursada. Puedo orientarte sobre aulas, horarios y notas. ¿En qué te puedo ayudar?`;
}
}
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 '';
// Proteger enlaces Markdown [texto](url)
const links = [];
let processed = text.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, (match, label, url) => {
const idx = links.length;
links.push({ label, url });
return `__MD_LINK_${idx}__`;
});
// Proteger URLs directas https://...
const rawUrls = [];
processed = processed.replace(/(https?:\/\/[^\s<"'>)]+)/g, (match, url) => {
const idx = rawUrls.length;
rawUrls.push(url);
return `__RAW_URL_${idx}__`;
});
// Escaping seguro de HTML
let escaped = processed
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
// Negrita **texto**
escaped = escaped.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
// Cursiva *texto*
escaped = escaped.replace(/\*(.*?)\*/g, '<em>$1</em>');
// Código inline `codigo`
escaped = escaped.replace(/`([^`]+)`/g, '<code>$1</code>');
// Saltos de línea
escaped = escaped.replace(/\n/g, '<br>');
// Restaurar enlaces Markdown como botones atractivos
escaped = escaped.replace(/__MD_LINK_(\d+)__/g, (match, idx) => {
const item = links[parseInt(idx, 10)];
if (!item) return '';
return `<a href="${item.url}" target="_blank" rel="noopener noreferrer" class="ai-chat-link"><i class="bi bi-box-arrow-up-right me-1"></i>${item.label}</a>`;
});
// Restaurar URLs directas como enlaces clickeables
escaped = escaped.replace(/__RAW_URL_(\d+)__/g, (match, idx) => {
const url = rawUrls[parseInt(idx, 10)];
if (!url) return '';
const displayUrl = url.length > 46 ? url.substring(0, 43) + '...' : url;
return `<a href="${url}" target="_blank" rel="noopener noreferrer" class="ai-chat-link"><i class="bi bi-link-45deg me-1"></i>${displayUrl}</a>`;
});
return escaped;
}
function formatCurrentTime() {
const now = new Date();
return now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
function appendMessage(role, content, options = [], save = true, timeStr = null) {
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'}`;
const formattedHtml = renderMarkdown(content);
const timestamp = timeStr || formatCurrentTime();
if (isUser) {
msgDiv.innerHTML = `
<div class="ai-msg-text">${formattedHtml}</div>
<span class="ai-msg-time">${timestamp}</span>
`;
} else {
let optionsHtml = '';
if (options && options.length > 0) {
optionsHtml = '<div class="ai-msg-options">';
options.forEach(opt => {
optionsHtml += `<button type="button" class="ai-option-btn" data-query="${opt}">${opt}</button>`;
});
optionsHtml += '</div>';
}
msgDiv.innerHTML = `
<div class="ai-msg-body">${formattedHtml}</div>
${optionsHtml}
<div class="ai-msg-actions">
<button type="button" class="ai-action-icon-btn copy-btn" title="Copiar respuesta" aria-label="Copiar">
<i class="bi bi-copy"></i>
</button>
<button type="button" class="ai-action-icon-btn speak-btn" title="Escuchar en voz alta" aria-label="Escuchar">
<i class="bi bi-volume-up"></i>
</button>
<button type="button" class="ai-action-icon-btn thumbs-up-btn" title="Respuesta útil" aria-label="Útil">
<i class="bi bi-hand-thumbs-up"></i>
</button>
<button type="button" class="ai-action-icon-btn thumbs-down-btn" title="No me sirvió" aria-label="No útil">
<i class="bi bi-hand-thumbs-down"></i>
</button>
</div>
`;
// Configurar botones de acción interactivos estilo Mercado Libre
const copyBtn = msgDiv.querySelector('.copy-btn');
if (copyBtn) {
copyBtn.addEventListener('click', () => {
const temp = document.createElement('div');
temp.innerHTML = formattedHtml;
const plain = temp.textContent || temp.innerText || '';
if (navigator.clipboard) {
navigator.clipboard.writeText(plain).then(() => {
copyBtn.innerHTML = '<i class="bi bi-check-lg text-success"></i>';
setTimeout(() => { copyBtn.innerHTML = '<i class="bi bi-copy"></i>'; }, 2000);
});
}
});
}
const speakBtn = msgDiv.querySelector('.speak-btn');
if (speakBtn) {
speakBtn.addEventListener('click', () => {
if ('speechSynthesis' in window) {
if (window.speechSynthesis.speaking) {
window.speechSynthesis.cancel();
speakBtn.classList.remove('active');
return;
}
const temp = document.createElement('div');
temp.innerHTML = formattedHtml;
const plain = temp.textContent || temp.innerText || '';
const utter = new SpeechSynthesisUtterance(plain);
utter.lang = 'es-AR';
speakBtn.classList.add('active');
utter.onend = () => speakBtn.classList.remove('active');
utter.onerror = () => speakBtn.classList.remove('active');
window.speechSynthesis.speak(utter);
}
});
}
const thumbsUp = msgDiv.querySelector('.thumbs-up-btn');
const thumbsDown = msgDiv.querySelector('.thumbs-down-btn');
if (thumbsUp && thumbsDown) {
thumbsUp.addEventListener('click', () => {
thumbsUp.classList.toggle('active');
thumbsDown.classList.remove('active');
});
thumbsDown.addEventListener('click', () => {
thumbsDown.classList.toggle('active');
thumbsUp.classList.remove('active');
});
}
}
messagesContainer.appendChild(msgDiv);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
// Asignar listeners a los chips de opciones
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, timeStr: timestamp });
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');
const chipsDrawer = document.getElementById('aiChatQuickChips');
if (textarea) textarea.value = '';
if (chipsDrawer) chipsDrawer.classList.add('d-none');
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()
})
});
if (!res.ok) {
throw new Error(`Error HTTP ${res.status}`);
}
const data = await res.json();
const reply = data.reply || "Disculpa, no pude procesar tu solicitud en este momento.";
const options = Array.isArray(data.options) ? data.options : [];
appendMessage('assistant', reply, options, true);
} catch (err) {
console.error("[UdeCi Widget] Error al consultar API:", err);
appendMessage('assistant', "Hubo una interrupción en la conexión con el tutor inteligente. Por favor, verifica tu conexión o intenta nuevamente en unos instantes.", [], true);
} finally {
isProcessing = false;
if (typing) typing.classList.add('d-none');
if (sendBtn) sendBtn.disabled = false;
if (textarea && window.innerWidth > 768) textarea.focus();
}
}
function populateRoleChips() {
const chipsContainer = document.getElementById('aiRoleChipsContainer');
if (!chipsContainer || chipsContainer.children.length > 0) return;
const role = getUserRole();
const chips = ROLE_CHIPS[role] || ROLE_CHIPS.alumno;
chips.forEach(c => {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'ai-chip-pill';
btn.textContent = c.label;
btn.setAttribute('data-query', c.query);
btn.addEventListener('click', () => {
sendQuery(c.query);
});
chipsContainer.appendChild(btn);
});
}
function initChat() {
const launcher = document.getElementById('aiChatLauncher');
const panel = document.getElementById('aiChatPanel');
const backdrop = document.getElementById('aiChatBackdrop');
const backBtn = document.getElementById('aiChatBackBtn');
const closeBtn = document.getElementById('aiChatCloseBtn');
const clearBtn = document.getElementById('aiChatClearBtn');
const chipsToggleBtn = document.getElementById('aiChatChipsToggleBtn');
const plusBtn = document.getElementById('aiChatPlusBtn');
const chipsDrawer = document.getElementById('aiChatQuickChips');
const closeChipsBtn = document.getElementById('aiChatCloseChipsBtn');
const textarea = document.getElementById('aiChatInput');
const handleBar = document.getElementById('aiSheetHandleBar');
if (!launcher || !panel) return;
const role = getUserRole();
const name = getUserName();
function openChat() {
panel.classList.remove('d-none');
if (backdrop) backdrop.classList.remove('d-none');
launcher.classList.add('chat-open');
if (window.innerWidth <= 768) {
document.body.classList.add('ai-chat-mobile-open');
}
populateRoleChips();
setTimeout(() => {
const messagesContainer = document.getElementById('aiChatMessages');
if (messagesContainer) messagesContainer.scrollTop = messagesContainer.scrollHeight;
if (textarea && window.innerWidth > 768) textarea.focus();
}, 100);
}
function closeChat() {
panel.classList.add('d-none');
if (backdrop) backdrop.classList.add('d-none');
launcher.classList.remove('chat-open');
document.body.classList.remove('ai-chat-mobile-open');
if (chipsDrawer) chipsDrawer.classList.add('d-none');
if ('speechSynthesis' in window && window.speechSynthesis.speaking) {
window.speechSynthesis.cancel();
}
// Restaurar transform o estilos modificados por gestos
panel.style.transform = '';
panel.style.height = '';
panel.style.bottom = '';
}
// Toggle panel
launcher.addEventListener('click', () => {
const isHidden = panel.classList.contains('d-none');
if (isHidden) openChat(); else closeChat();
});
if (backBtn) backBtn.addEventListener('click', closeChat);
if (closeBtn) closeBtn.addEventListener('click', closeChat);
if (backdrop) backdrop.addEventListener('click', closeChat);
// Deslizar hacia abajo en la drag handle bar para cerrar (Touch Gesture)
if (handleBar) {
handleBar.addEventListener('touchstart', (e) => {
touchStartY = e.touches[0].clientY;
touchDeltaY = 0;
}, { passive: true });
handleBar.addEventListener('touchmove', (e) => {
touchDeltaY = e.touches[0].clientY - touchStartY;
if (touchDeltaY > 0) {
panel.style.transform = `translateY(${touchDeltaY}px)`;
}
}, { passive: true });
handleBar.addEventListener('touchend', () => {
if (touchDeltaY > 65) {
closeChat();
} else {
panel.style.transform = '';
}
touchDeltaY = 0;
});
}
// Drawer de consultas rápidas (+)
function toggleChips() {
if (!chipsDrawer) return;
populateRoleChips();
chipsDrawer.classList.toggle('d-none');
}
if (plusBtn) plusBtn.addEventListener('click', toggleChips);
if (chipsToggleBtn) chipsToggleBtn.addEventListener('click', toggleChips);
if (closeChipsBtn) closeChipsBtn.addEventListener('click', () => {
chipsDrawer.classList.add('d-none');
});
// Manejo del Teclado Virtual en Dispositivos Móviles (visualViewport)
if (window.visualViewport) {
window.visualViewport.addEventListener('resize', () => {
if (window.innerWidth <= 768 && !panel.classList.contains('d-none')) {
const currentViewHeight = window.visualViewport.height;
const screenHeight = window.innerHeight;
// Si la altura del viewport se reduce significativamente (teclado abierto)
if (currentViewHeight < screenHeight * 0.88) {
panel.style.height = `${currentViewHeight}px`;
panel.style.bottom = `${Math.max(0, screenHeight - currentViewHeight - (window.visualViewport.offsetTop || 0))}px`;
} else {
// Teclado cerrado
panel.style.height = '';
panel.style.bottom = '';
}
const messagesContainer = document.getElementById('aiChatMessages');
if (messagesContainer) {
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
}
});
}
// Escape para cerrar
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && panel && !panel.classList.contains('d-none')) {
closeChat();
}
});
// Reiniciar conversación
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 bienvenida
const history = loadHistory();
if (history.length > 0) {
history.forEach(msg => appendMessage(msg.role, msg.content, msg.options || [], false, msg.timeStr));
} else {
appendMessage('assistant', getWelcomeMessage(role, name), [], false);
}
// Atajo Enter en desktop
if (textarea) {
textarea.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
window.handleAiChatSubmit(e);
}
});
}
}
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();
}
})();