diff --git a/CHANGELOG.md b/CHANGELOG.md index 1693a2f..391ca0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,22 @@ El formato está basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1 - **Sincronización Continua Moodle (Fase 6):** Automatización de workers persistentes en background para el procesamiento continuo de la cola de Web Services Moodle 4.1. - **Pruebas de Carga y Hardening (Fase 6):** Pruebas de estrés de concurrencia y validación final de producción. +## [3.8.36] - 2026-10-27 +### Added & Enhanced (Rediseño Móvil del Chatbot UdeCi estilo Mercado Libre / Mago) +- **Bottom Sheet Nativo en Móvil (< 768px)**: + - Se transformó la interfaz del chatbot en móvil a un **Bottom Sheet modal nativo** inspirado en la experiencia de Mercado Libre ("Mago"), cubriendo el 92% de la pantalla (`height: 92dvh; border-top-left-radius: 28px; border-top-right-radius: 28px;`). + - Incorporación de **Backdrop sombreado con desenfoque (`#aiChatBackdrop`)** que bloquea la interacción con la página web de fondo y evita desbordes visuales. + - **Drag Handle Superior Interactiva**: Barra de deslizamiento táctil con soporte de gestos (`touchmove` / `touchend`) para cerrar el panel deslizando hacia abajo. + - **Cabecera Flotante y Limpia**: Botón de retroceso `<` tipo píldora, ícono Sparkle animado de UdeCi y botones superiores de nuevo chat y atajos rápidos. + - **Disclaimer Institucional**: Frase *"UdeCi usa inteligencia artificial para responderte."* con tipografía limpia. +- **Dock de Entrada y Manejo Dinámico del Teclado Virtual (`visualViewport`)**: + - Cápsula de entrada redondeada (`border-radius: 28px`) con botón circular `+` para desplegar atajos temáticos, textarea expandible con placeholder *"Pregúntame"* y botón de envío circular. + - Integración de la API `window.visualViewport`: al desplegarse el teclado táctil en smartphones Android/iOS, el contenedor del chat se recalcula dinámicamente y el input se ancla **directamente encima del teclado**, eliminando cualquier espacio o transparencia no deseada. +- **Burbujas de Conversación y Acciones de Feedback**: + - Mensaje de usuario en píldora suave a la derecha con marca horaria (`HH:mm`) en pie de burbuja. + - Mensaje de UdeCi en texto limpio y aireado con barra de utilidades (copiado al portapapeles con confirmación visual, lectura con síntesis de voz `SpeechSynthesisUtterance` y pulgares de valoración). + - Explicitación en System Prompt de las capacidades accesibles del tutor virtual (datos académicos, ocupación, reservas, clima en tiempo real de Sede Central y rutas Google Maps). + ## [3.8.35] - 2026-10-27 ### Fixed & Enhanced (Comportamiento de Acordeón Único y Legibilidad de Alto Contraste en Menú Lateral) - **Acordeón Estricto de Menú Lateral (Un Solo Menú Desplegado)**: diff --git a/MEMORY.md b/MEMORY.md index f712e7c..2e89eeb 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -9,10 +9,12 @@ Memoria del proyecto entre sesiones para la rama `dev`. - Libro de Calificaciones (*Gradebook*) con actas de regularidad inmutables. - Autenticación híbrida (Google OAuth 2.0, Moodle SSO, Local) y Modo Impersonación. - Reinicialización segura del sistema con contraseña de Administrador. -- **Sprint Activo: Menú Lateral con Acordeón Estricto y Legibilidad de Alto Contraste — SDD-011 (v3.8.35)**: - - **Acordeón Estricto (Un Solo Menú Desplegado)**: Se configuró `data-bs-parent="#sidebarNav"` en los 13 submenús colapsables y se depuró el script JS para asegurar que sólo el submenú activo o en uso permanezca abierto, cerrando inmediatamente cualquier otro. En Dashboard e inicio, todos los submenús quedan replegados. - - **Legibilidad Nítida y Alto Contraste (WCAG AAA)**: Se corrigió la falta de contraste en enlaces con clases utilitarias (`.text-info`, `.text-success`, `.text-warning`, `.text-primary`), asignando paletas adaptativas legibles. Se fijó tipografía seminegrita (`font-weight: 600`) y colores Slate-900 / Slate-50 en submenús, y Slate-700 / Slate-300 con `font-weight: 800` en encabezados de sección. Se amplió el ancho a `275px`. - - **Versión Consolidada**: `v3.8.35`. +- **Sprint Activo: Rediseño Móvil del Chatbot UdeCi estilo Mercado Libre — SDD-011 (v3.8.36)**: + - **Experiencia Bottom Sheet Nativa**: Panel de chat transformado a bottom sheet modal en móviles (< 768px) ocupando el 92% de la pantalla (`92dvh`), con esquinas redondeadas (`28px`), drag handle superior con gestos de deslizamiento táctil para cerrar, botón de retroceso `<`, header con ícono de destellos (sparkle) y disclaimer institucional. + - **Backdrop y Aislamiento Total**: Fondo desenfocado `#aiChatBackdrop` que bloquea la interacción con la pantalla subyacente y previene desbordes. + - **Dock de Entrada y Teclado Virtual con `visualViewport`**: Contenedor en cápsula con botón `+`, placeholder *"Pregúntame"*, y anclaje automático e impecable directamente encima del teclado móvil táctil. + - **Burbujas y Acciones Meli**: Mensajes de usuario con timestamp (`HH:mm`), respuestas limpias con barra de utilidades (copiar, síntesis de voz, feedback), y precisión en el System Prompt para informar acceso a clima y geolocalización. + - **Versión Consolidada**: `v3.8.36`. ## Decisiones (y por qué) - **Flujo Secuencial de Bedelía (9 Pasos)**: Estandarizar la carga operativa en: 1) Sede -> 2) Aula -> 3) Ciclo Lectivo -> 4) Carrera -> 5) Materia (vinculada a Carrera) -> 6) Comisión (asociada a Materia, Carrera y Ciclo) -> 7) Profesores -> 8) Alumnos -> 9) Reserva de Espacio. Esto asegura consistencia e integridad relacional. diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 7454e15..7ee6299 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -7,7 +7,7 @@ from typing import Any from database import db, get_db, engine, SessionLocal, session from config.config import Config -__version__ = "3.8.35" +__version__ = "3.8.36" class DummyContext: def __enter__(self): diff --git a/backend/routers/ai_chat.py b/backend/routers/ai_chat.py index 29dc914..8be362e 100644 --- a/backend/routers/ai_chat.py +++ b/backend/routers/ai_chat.py @@ -121,6 +121,13 @@ def generate_system_prompt_for_role( "5. PRIVACIDAD ESTRICTA: Los alumnos NUNCA deben ser remitidos al 'Gradebook' ni a la 'Sábana de Calificaciones', ya que ese panel contiene datos de todos los compañeros. Para consultar notas, un alumno debe dirigirse a 'Mis Calificaciones e Hitos' en 'Mi Trayectoria'.\n" "6. BREVEDAD Y PRECISIÓN: Responde en máximo 2 a 3 oraciones concisas o pasos directos sin rodeos ni introducciones vacías.\n" "7. DATOS REALES EN VIVO, CALIFICACIONES E HITOS: Utiliza la sección 'ESTADO EN VIVO DEL SISTEMA' para responder con total fidelidad:\n" + " - Si preguntan a qué información tienes acceso o qué puedes responder, aclara con amabilidad que tienes acceso a:\n" + " * Datos académicos y de cursada del usuario según su rol (materias, comisiones, notas, regularidad y próximas clases presenciales).\n" + " * Estado de ocupación de sedes y aulas (presenciales y virtuales) y cartelera del día.\n" + " * Gestión y estado de reservas de espacios áulicos.\n" + " * Clima y temperatura en tiempo real en UniCABA Sede Central (vía integración meteorológica).\n" + " * Rutas y cómo llegar a la universidad con Google Maps y medios de transporte público.\n" + " * Flujo operativo de 9 pasos para Bedelía, optimizador genético y soporte en Moodle.\n" " - Si un alumno pregunta por sus notas o regularidad, responde con las notas y condición académica según 'ESTADO EN VIVO DEL SISTEMA'.\n" " - Si preguntan cuántas comisiones hay sin asignar o cuál es la comisión que más alumnos tiene, responde con los datos operativos del estado en vivo.\n" " - Si preguntan por profesores registrados o si alguno se llama de cierta forma (ej. Sergio), responde en base a la nómina de docentes del estado en vivo.\n" diff --git a/backend/setup.py b/backend/setup.py index d41c88a..532e289 100644 --- a/backend/setup.py +++ b/backend/setup.py @@ -2,7 +2,7 @@ from setuptools import setup, find_packages setup( name="edu-space-admin", - version="3.8.35", + version="3.8.36", description="Administrative interface for Edu-Space Classroom Management System (FastAPI ASGI Core)", author="Edu-Space Development Team", author_email="admin@edu-space.com", diff --git a/frontend/package.json b/frontend/package.json index 394a009..b457768 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "frontend", - "version": "3.8.35", + "version": "3.8.36", "description": "", "main": "index.js", "scripts": { diff --git a/frontend/public/js/ai-chat-widget.js b/frontend/public/js/ai-chat-widget.js index cc0f29b..91e72ed 100644 --- a/frontend/public/js/ai-chat-widget.js +++ b/frontend/public/js/ai-chat-widget.js @@ -1,14 +1,17 @@ /** - * 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. + * 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 clave histórica compartida para evitar contaminación entre perfiles + // Limpiar claves obsoletas try { sessionStorage.removeItem('edu_space_udeci_chat_history_v2'); localStorage.removeItem('edu_space_udeci_chat_history_v2'); @@ -24,7 +27,6 @@ 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(); @@ -38,17 +40,23 @@ } 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?" } + 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 de aulas?" }, + { 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?" }, @@ -82,15 +90,15 @@ } function getWelcomeMessage(role, name) { - const greeting = name ? `¡Hola, **${name}**! 👋` : '¡Hola! 👋'; + 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?`; + 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 técnico para Bedelía. Puedo guiarte en el circuito de 9 pasos, resolución de conflictos y Moodle.`; + 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 de Edu-Space para docentes. Puedo orientarte sobre asignaciones de aulas, el Gradebook y tus clases asignadas.`; + 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 en qué aula cursas hoy, horarios y notas.`; + return `${greeting} Soy **UdeCi**, tu tutor virtual de cursada. Puedo orientarte sobre aulas, horarios y notas. ¿En qué te puedo ayudar?`; } } @@ -112,7 +120,7 @@ function renderMarkdown(text) { if (!text) return ''; - // 1. Proteger enlaces Markdown [texto](url) antes del escape HTML + // Proteger enlaces Markdown [texto](url) const links = []; let processed = text.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, (match, label, url) => { const idx = links.length; @@ -120,7 +128,7 @@ return `__MD_LINK_${idx}__`; }); - // 2. Proteger URLs directas https://... + // Proteger URLs directas https://... const rawUrls = []; processed = processed.replace(/(https?:\/\/[^\s<"'>)]+)/g, (match, url) => { const idx = rawUrls.length; @@ -128,40 +136,45 @@ return `__RAW_URL_${idx}__`; }); - // 3. Escaping HTML seguro + // Escaping seguro de HTML let escaped = processed .replace(/&/g, '&') .replace(//g, '>'); - // 4. Negrita **texto** + // Negrita **texto** escaped = escaped.replace(/\*\*(.*?)\*\*/g, '$1'); - // 5. Cursiva *texto* + // Cursiva *texto* escaped = escaped.replace(/\*(.*?)\*/g, '$1'); - // 6. Código inline `codigo` + // Código inline `codigo` escaped = escaped.replace(/`([^`]+)`/g, '$1'); - // 7. Saltos de línea + // Saltos de línea escaped = escaped.replace(/\n/g, '
'); - // 8. Restaurar enlaces Markdown como botones/hipervínculos atractivos + // 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 `${item.label}`; }); - // 9. Restaurar URLs directas como enlaces clickeables + // 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 > 48 ? url.substring(0, 45) + '...' : url; + const displayUrl = url.length > 46 ? url.substring(0, 43) + '...' : url; return `${displayUrl}`; }); return escaped; } - function appendMessage(role, content, options = [], save = true) { + 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; @@ -169,23 +182,99 @@ const msgDiv = document.createElement('div'); msgDiv.className = `ai-msg ${isUser ? 'ai-msg-user' : 'ai-msg-assistant'}`; - let html = renderMarkdown(content); + const formattedHtml = renderMarkdown(content); + const timestamp = timeStr || formatCurrentTime(); - // 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 += '
'; + if (isUser) { + msgDiv.innerHTML = ` +
${formattedHtml}
+ ${timestamp} + `; + } else { + let optionsHtml = ''; + if (options && options.length > 0) { + optionsHtml = '
'; + options.forEach(opt => { + optionsHtml += ``; + }); + optionsHtml += '
'; + } + + msgDiv.innerHTML = ` +
${formattedHtml}
+ ${optionsHtml} +
+ + + + +
+ `; + + // 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 = ''; + setTimeout(() => { copyBtn.innerHTML = ''; }, 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'); + }); + } } - msgDiv.innerHTML = html; messagesContainer.appendChild(msgDiv); messagesContainer.scrollTop = messagesContainer.scrollHeight; - // Asignar listeners a los botones de opciones dentro de la burbuja + // Asignar listeners a los chips de opciones msgDiv.querySelectorAll('.ai-option-btn').forEach(btn => { btn.addEventListener('click', function (e) { e.preventDefault(); @@ -196,7 +285,7 @@ if (save) { const history = loadHistory(); - history.push({ role, content, options }); + history.push({ role, content, options, timeStr: timestamp }); saveHistory(history); } } @@ -207,8 +296,11 @@ 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; @@ -240,45 +332,58 @@ }) }); - 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); + 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) { - appendMessage('assistant', `⚠️ Error de comunicación: ${err.message}`, [], false); + 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) textarea.focus(); + 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 form = document.getElementById('aiChatForm'); + const handleBar = document.getElementById('aiSheetHandleBar'); if (!launcher || !panel) return; @@ -287,44 +392,118 @@ function openChat() { panel.classList.remove('d-none'); - launcher.style.transform = 'scale(0.9)'; + 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(() => { - if (textarea) textarea.focus(); + 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'); - launcher.style.transform = ''; + 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 (isHidden) openChat(); else closeChat(); }); - if (closeBtn) { - closeBtn.addEventListener('click', 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 del usuario actual + // Reiniciar conversación if (clearBtn) { clearBtn.addEventListener('click', () => { sessionStorage.removeItem(getStorageKey()); @@ -334,20 +513,20 @@ }); } - // Cargar historial previo o mensaje de bienvenida + // Cargar historial previo o bienvenida const history = loadHistory(); if (history.length > 0) { - history.forEach(msg => appendMessage(msg.role, msg.content, msg.options || [], false)); + history.forEach(msg => appendMessage(msg.role, msg.content, msg.options || [], false, msg.timeStr)); } else { appendMessage('assistant', getWelcomeMessage(role, name), [], false); } - // Atajo Enter para enviar + // Atajo Enter en desktop 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(e); } }); } diff --git a/frontend/src/app.js b/frontend/src/app.js index 009f612..a25d100 100644 --- a/frontend/src/app.js +++ b/frontend/src/app.js @@ -86,9 +86,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), { }); // Versiones institucionales del sistema -const APP_VERSION = '3.8.35'; -const FRONTEND_VERSION = '3.8.35'; -const BACKEND_VERSION = '3.8.35'; +const APP_VERSION = '3.8.36'; +const FRONTEND_VERSION = '3.8.36'; +const BACKEND_VERSION = '3.8.36'; env.addGlobal('app_version', APP_VERSION); env.addGlobal('frontend_version', FRONTEND_VERSION); diff --git a/frontend/views/partials/ai_chat_widget.html b/frontend/views/partials/ai_chat_widget.html index 858191d..01853ef 100644 --- a/frontend/views/partials/ai_chat_widget.html +++ b/frontend/views/partials/ai_chat_widget.html @@ -4,53 +4,84 @@ {% set current_user_name = active_auth_user.first_name if (active_auth_user and active_auth_user.first_name) else (active_auth_user.name if active_auth_user else '') %} {% set current_role_name = (active_auth_user.role if active_auth_user and active_auth_user.role else 'alumno') | lower %} - - + + + + +
+ - - -