211 lines
7.9 KiB
JavaScript
211 lines
7.9 KiB
JavaScript
/**
|
|
* ai-chat-widget.js - Lógica interactiva del Asistente IA (SDD-009)
|
|
* Maneja el estado conversacional, llamadas AJAX al backend FastAPI,
|
|
* persistencia de sesión y renderizado accesible de mensajes.
|
|
*/
|
|
(function() {
|
|
'use strict';
|
|
|
|
let isProcessing = false;
|
|
const STORAGE_KEY = 'edu_space_ai_chat_messages_v1';
|
|
|
|
function getContainer() {
|
|
return document.getElementById('aiChatContainer');
|
|
}
|
|
|
|
function getUserRole() {
|
|
const container = getContainer();
|
|
return (container ? container.getAttribute('data-user-role') : 'alumno') || 'alumno';
|
|
}
|
|
|
|
function getWelcomeMessage(role) {
|
|
const r = (role || 'alumno').toLowerCase();
|
|
if (r.includes('docente') || r.includes('profesor') || r.includes('teacher')) {
|
|
return "¡Hola! 👋 Soy tu <strong>Tutor de Edu-Space</strong> para Docentes. Puedo orientarte sobre cómo consultar tus aulas asignadas, cargar calificaciones en el <strong>Gradebook</strong>, cerrar actas de regularidad y gestionar enlaces de Google Meet. ¿En qué puedo asistirte?";
|
|
} else if (r.includes('bedelia') || r.includes('admin')) {
|
|
return "¡Hola! 👋 Soy el <strong>Asistente Técnico de Bedelía</strong>. Puedo ayudarte con el <strong>flujo secuencial de 9 pasos</strong>, matriz de conflictos áulicos, el Optimizador Genético, importación masiva de Google Sheets y la cola de Moodle 4.1. ¿Qué tarea deseas revisar?";
|
|
} else {
|
|
return "¡Hola! 👋 Soy tu <strong>Tutor de Cursada</strong>. Puedo ayudarte a consultar en qué aula o sala virtual cursas hoy, ver tus horarios semanales, verificar materias inscriptas y notas académicas. ¿Cuál es tu consulta?";
|
|
}
|
|
}
|
|
|
|
function loadHistory() {
|
|
try {
|
|
const raw = sessionStorage.getItem(STORAGE_KEY);
|
|
return raw ? JSON.parse(raw) : [];
|
|
} catch (e) {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
function saveHistory(messages) {
|
|
try {
|
|
sessionStorage.setItem(STORAGE_KEY, JSON.stringify(messages));
|
|
} catch (e) {}
|
|
}
|
|
|
|
function renderMarkdown(text) {
|
|
if (!text) return '';
|
|
let escaped = text
|
|
.replace(/&/g, '&')
|
|
.replace(/</g, '<')
|
|
.replace(/>/g, '>');
|
|
|
|
// 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>');
|
|
|
|
return escaped;
|
|
}
|
|
|
|
function appendMessage(role, content, 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'}`;
|
|
msgDiv.innerHTML = isUser ? renderMarkdown(content) : renderMarkdown(content);
|
|
|
|
messagesContainer.appendChild(msgDiv);
|
|
messagesContainer.scrollTop = messagesContainer.scrollHeight;
|
|
|
|
if (save) {
|
|
const history = loadHistory();
|
|
history.push({ role, content });
|
|
saveHistory(history);
|
|
}
|
|
}
|
|
|
|
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;
|
|
|
|
// Toggle panel
|
|
launcher.addEventListener('click', () => {
|
|
const isHidden = panel.classList.contains('d-none');
|
|
if (isHidden) {
|
|
panel.classList.remove('d-none');
|
|
launcher.style.transform = 'scale(0.9)';
|
|
setTimeout(() => {
|
|
if (textarea) textarea.focus();
|
|
}, 100);
|
|
} else {
|
|
panel.classList.add('d-none');
|
|
launcher.style.transform = '';
|
|
}
|
|
});
|
|
|
|
if (closeBtn) {
|
|
closeBtn.addEventListener('click', () => {
|
|
panel.classList.add('d-none');
|
|
launcher.style.transform = '';
|
|
});
|
|
}
|
|
|
|
// Limpiar conversación
|
|
if (clearBtn) {
|
|
clearBtn.addEventListener('click', () => {
|
|
if (confirm('¿Deseas reiniciar la conversación con el tutor?')) {
|
|
sessionStorage.removeItem(STORAGE_KEY);
|
|
const messagesContainer = document.getElementById('aiChatMessages');
|
|
if (messagesContainer) messagesContainer.innerHTML = '';
|
|
const role = getUserRole();
|
|
appendMessage('assistant', getWelcomeMessage(role), false);
|
|
}
|
|
});
|
|
}
|
|
|
|
// Cargar historial previo o mensaje de bienvenida
|
|
const history = loadHistory();
|
|
const role = getUserRole();
|
|
if (history.length > 0) {
|
|
history.forEach(msg => appendMessage(msg.role, msg.content, false));
|
|
} else {
|
|
appendMessage('assistant', getWelcomeMessage(role), false);
|
|
}
|
|
|
|
// Auto-resize de textarea y atajo Enter
|
|
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 = async function(e) {
|
|
if (e) e.preventDefault();
|
|
if (isProcessing) return;
|
|
|
|
const textarea = document.getElementById('aiChatInput');
|
|
const typing = document.getElementById('aiChatTyping');
|
|
const sendBtn = document.getElementById('aiChatSendBtn');
|
|
if (!textarea) return;
|
|
|
|
const query = textarea.value.trim();
|
|
if (!query) return;
|
|
|
|
// Limpiar campo de texto y mostrar mensaje del usuario
|
|
textarea.value = '';
|
|
appendMessage('user', query, true);
|
|
|
|
// Bloquear UI e indicar escritura
|
|
isProcessing = true;
|
|
if (typing) typing.classList.remove('d-none');
|
|
if (sendBtn) sendBtn.disabled = true;
|
|
|
|
const userRole = getUserRole();
|
|
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
|
|
})
|
|
});
|
|
|
|
const data = await res.json();
|
|
if (res.ok && data.response) {
|
|
appendMessage('assistant', data.response, true);
|
|
} else {
|
|
const errorMsg = data.detail || data.message || 'El motor de IA local no está respondiendo en este momento.';
|
|
appendMessage('assistant', `⚠️ <em>${errorMsg}</em>`, false);
|
|
}
|
|
} catch (err) {
|
|
appendMessage('assistant', `⚠️ <em>No se pudo comunicar con el servidor local de IA: ${err.message}</em>`, false);
|
|
} finally {
|
|
isProcessing = false;
|
|
if (typing) typing.classList.add('d-none');
|
|
if (sendBtn) sendBtn.disabled = false;
|
|
textarea.focus();
|
|
}
|
|
};
|
|
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', initChat);
|
|
} else {
|
|
initChat();
|
|
}
|
|
})();
|