Spaces:
Running
Running
Download js/app.js from ballcoman/CosmoMente: direct link, hf CLI and curl.
- Browser
- Download file 20.8 kB
-
https://huggingface.co/spaces/ballcoman/CosmoMente/resolve/main/js/app.js
- Command line
-
hf download hf://spaces/ballcoman/CosmoMente/js/app.js
-
curl -L -o app.js https://huggingface.co/spaces/ballcoman/CosmoMente/resolve/main/js/app.js
20.8 kB
| import { supabase } from './config.js'; | |
| import { gameEngine } from './engine.js'; | |
| import { teacherUI } from './teacherUI.js'; | |
| import { ui } from './ui.js'; | |
| // Importación de los 6 Talleres | |
| import { taller1Data } from './talleres/taller1.js'; | |
| import { taller2Data } from './talleres/taller2.js'; | |
| import { taller3Data } from './talleres/taller3.js'; | |
| import { taller4Data } from './talleres/taller4.js'; | |
| import { taller5Data } from './talleres/taller5.js'; | |
| import { taller6Data } from './talleres/taller6.js'; | |
| export const app = { | |
| user: null, | |
| profile: null, | |
| role: null, // 'student' o 'teacher' | |
| unlockedWorkshops: [], | |
| heartbeatInterval: null, // Variable para el latido de sesión | |
| init: async () => { | |
| const { data: { session } } = await supabase.auth.getSession(); | |
| if (session) { | |
| app.user = session.user; | |
| app.loadUserProfile(); | |
| } else { | |
| app.showScreen('view-login'); | |
| } | |
| supabase.auth.onAuthStateChange(async (event, session) => { | |
| if (event === 'SIGNED_IN' && session) { | |
| app.user = session.user; | |
| app.loadUserProfile(); | |
| } | |
| if (event === 'SIGNED_OUT') { | |
| app.stopHeartbeat(); | |
| app.showScreen('view-login'); | |
| location.reload(); | |
| } | |
| }); | |
| }, | |
| finishIntro: () => { | |
| app.showScreen('view-map'); | |
| }, | |
| // Deprecated: La gestión de sesión única se elimina para simplificar | |
| checkSessionAvailability: async (userId) => { return true; }, | |
| startHeartbeat: () => { }, | |
| sendPulse: async () => { }, | |
| stopHeartbeat: () => { }, | |
| setupAutoLogout: () => { | |
| let timer; | |
| const timeLimit = 5 * 60 * 1000; | |
| const resetTimer = () => { | |
| clearTimeout(timer); | |
| timer = setTimeout(() => { | |
| alert("⏳ Tu sesión se ha cerrado por inactividad."); | |
| app.logout(); | |
| }, timeLimit); | |
| }; | |
| const events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart', 'click']; | |
| events.forEach(evt => document.addEventListener(evt, resetTimer, true)); | |
| resetTimer(); | |
| }, | |
| login: async () => { | |
| const email = document.getElementById('email').value.trim(); | |
| const password = document.getElementById('password').value; | |
| const errorMsg = document.getElementById('login-error'); | |
| if (!email || !password) { | |
| errorMsg.innerText = "Por favor completa los campos."; | |
| return; | |
| } | |
| errorMsg.innerText = "Verificando credenciales..."; | |
| const { error } = await supabase.auth.signInWithPassword({ email, password }); | |
| if (error) { | |
| console.error("Login fallido:", error.message); | |
| errorMsg.innerText = "Usuario no registrado o clave errónea."; | |
| } | |
| }, | |
| logout: async () => { | |
| await supabase.auth.signOut(); | |
| }, | |
| loadUserProfile: async () => { | |
| app.setupAutoLogout(); | |
| // 1. VERIFICAR SI ES DOCENTE | |
| const { data: docente, error: docenteError } = await supabase | |
| .from('docentes') | |
| .select('*') | |
| .eq('id', app.user.id) | |
| .single(); | |
| // Si se encuentra el perfil de docente, configurar y terminar | |
| if (docente) { | |
| app.profile = docente; | |
| app.role = 'teacher'; | |
| document.getElementById('user-name').innerText = docente.nombre_completo; | |
| document.querySelector('.avatar-img').src = "https://api.dicebear.com/7.x/bottts/svg?seed=ProfeAdmin"; | |
| if (document.querySelector('.energy-display')) document.querySelector('.energy-display').style.display = 'none'; | |
| if (document.getElementById('btn-teacher-panel')) document.getElementById('btn-teacher-panel').classList.remove('hidden'); | |
| // Desbloquear todos los planetas para el docente | |
| for (let i = 1; i <= 6; i++) { | |
| const planet = document.getElementById(`planet-${i}`); | |
| if (planet) { | |
| planet.classList.remove('locked'); | |
| planet.classList.add('unlocked'); | |
| } | |
| } | |
| teacherUI.renderDashboard(); | |
| app.showScreen('view-teacher'); | |
| return; // ¡IMPORTANTE! Salir de la función aquí | |
| } | |
| // Si hubo un error al buscar al docente (y no fue que simplemente no lo encontró) | |
| if (docenteError && docenteError.code !== 'PGRST116') { | |
| console.error("Error al buscar perfil de docente:", docenteError); | |
| alert("Error al verificar el perfil. Inténtalo de nuevo."); | |
| app.logout(); | |
| return; | |
| } | |
| // 2. SI NO ES DOCENTE, VERIFICAR SI ES ESTUDIANTE | |
| const { data: estudiante, error: estudianteError } = await supabase | |
| .from('estudiantes') | |
| .select('*') | |
| .eq('id', app.user.id) | |
| .single(); | |
| if (estudiante) { | |
| app.profile = estudiante; | |
| app.role = 'student'; | |
| await app.loadProgress(); | |
| app.updateHUD(); | |
| app.showScreen('view-intro-story'); | |
| return; | |
| } | |
| // Si hubo un error al buscar al estudiante | |
| if (estudianteError && estudianteError.code !== 'PGRST116') { | |
| console.error("Error al buscar perfil de estudiante:", estudianteError); | |
| alert("Error al verificar el perfil. Inténtalo de nuevo."); | |
| app.logout(); | |
| return; | |
| } | |
| // 3. SI NO ES NINGUNO, ES UN NUEVO ESTUDIANTE | |
| app.loadAvatarScreen(); | |
| }, | |
| loadProgress: async () => { | |
| const { data: progresos, error } = await supabase | |
| .from('progreso_acceso') | |
| .select('id_taller') | |
| .eq('id_estudiante', app.user.id) | |
| .eq('acceso_desbloqueado', true); | |
| if (error) console.error("Error cargando progreso:", error); | |
| app.unlockedWorkshops = progresos ? progresos.map(p => parseInt(p.id_taller)) : [1]; // Desbloquear taller 1 por defecto | |
| if (!app.unlockedWorkshops.includes(1)) app.unlockedWorkshops.push(1); | |
| }, | |
| loadStudentProfile: async () => { | |
| if (!app.user) return; | |
| const content = document.getElementById('student-profile-content'); | |
| content.innerHTML = '<p style="text-align:center;">Cargando perfil...</p>'; | |
| app.showScreen('view-student-profile'); | |
| // Sincronizar insignias antes de cargar (Auto-Fix) | |
| await app.syncBadges(); | |
| // Cargar notas (historial) | |
| const { data: notas, error } = await supabase | |
| .from('rubricas_evaluacion') | |
| .select('*') | |
| .eq('id_estudiante', app.user.id) | |
| .order('id_taller', { ascending: true }); | |
| // Cargar insignias ASIGNADAS (Simplificado: Solo IDs, sin join para evitar errores) | |
| const { data: misLogros, error: errorLogros } = await supabase | |
| .from('asignacion_logros') | |
| .select('id_insignia') | |
| .eq('id_estudiante', app.user.id); | |
| // Cargar catálogo completo | |
| const { data: catalogo, error: errorCatalogo } = await supabase | |
| .from('catalogo_insignias') | |
| .select('*') | |
| .order('id', { ascending: true }); | |
| if (error) { | |
| console.error("Error cargando notas:", error); | |
| content.innerHTML = '<p class="error-msg">Error cargando tu historial.</p>'; | |
| return; | |
| } | |
| const seed = app.profile.avatar_config || "Default"; | |
| const energy = app.profile.puntos_energia || 0; | |
| let html = ` | |
| <div style="text-align:center; margin-bottom:40px;"> | |
| <img src="https://api.dicebear.com/7.x/bottts/svg?seed=${seed}" | |
| style="width:120px; height:120px; border-radius:50%; border:4px solid var(--neon-blue); box-shadow:0 0 20px var(--neon-blue); background:#000;"> | |
| <h1 style="margin:10px 0; color:var(--neon-blue);">${app.profile.nombre_completo}</h1> | |
| <div style="font-size:1.5rem; font-weight:bold; color:var(--neon-gold);"> | |
| ⚡ ${energy} Energía Estelar | |
| </div> | |
| </div> | |
| <h2 style="border-bottom:2px solid var(--neon-gold); padding-bottom:10px; margin-bottom:20px; color:var(--neon-gold);">🏆 Mis Insignias</h2> | |
| `; | |
| if (catalogo && catalogo.length > 0) { | |
| html += `<div style="display:flex; flex-wrap:wrap; justify-content:center; gap:20px; margin-bottom:40px;">`; | |
| // IDs de insignias que TIENE el estudiante | |
| const logrosIds = misLogros ? misLogros.map(l => parseInt(l.id_insignia)) : []; | |
| catalogo.forEach(insignia => { | |
| const id = parseInt(insignia.id); | |
| const earned = logrosIds.includes(id); | |
| const opacity = earned ? '1' : '0.3'; | |
| const filter = earned ? 'drop-shadow(0 0 10px gold)' : 'grayscale(100%)'; | |
| // Lógica para detectar si es URL o Emoji | |
| const url = insignia.imagen_url || ''; | |
| const isUrl = url.startsWith('http') || url.startsWith('/') || url.startsWith('data:'); | |
| let icon; | |
| if (url && isUrl) { | |
| icon = `<img src="${url}" style="width:50px; height:50px;">`; | |
| } else if (url) { | |
| // Es un emoji o texto | |
| icon = `<span style="font-size:3rem;">${url}</span>`; | |
| } else { | |
| // Fallback si viene vacío | |
| const fallbackIcons = ['💎', '🌊', '🧠', '⚔️', '👑', '🏆']; | |
| icon = `<span style="font-size:3rem;">${fallbackIcons[id - 1] || '🏅'}</span>`; | |
| } | |
| html += ` | |
| <div style="text-align:center; width:100px; opacity:${opacity}; filter:${filter}; transition:all 0.3s;"> | |
| <div style="margin-bottom:5px;">${icon}</div> | |
| <div style="font-size:0.8rem; color:${earned ? 'white' : '#888'}; font-weight:bold;">${insignia.nombre_logro}</div> | |
| </div> | |
| `; | |
| }); | |
| html += `</div>`; | |
| } else { | |
| html += `<p style="text-align:center; font-style:italic; color:#888;">No hay insignias disponibles.</p>`; | |
| } | |
| html += `<h2 style="border-bottom:2px solid var(--neon-purple); padding-bottom:10px; margin-bottom:20px;">📜 Historial de Misiones</h2>`; | |
| if (!notas || notas.length === 0) { | |
| html += `<p style="text-align:center; color:#ddd;">Aún no has completado ninguna misión. ¡Ve al mapa y comienza tu aventura!</p>`; | |
| } else { | |
| html += `<div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap:20px;">`; | |
| notas.forEach(nota => { | |
| const coop = nota.criterio_coop || 0; | |
| const math = nota.criterio_math || 0; | |
| const feedback = nota.feedback ? `<p style="background:rgba(255,255,255,0.1); padding:10px; border-radius:8px; font-style:italic; margin-top:10px;">"${nota.feedback}"</p>` : ''; | |
| html += ` | |
| <div style="background:rgba(0,0,0,0.6); border:1px solid var(--neon-blue); border-radius:15px; padding:20px; box-shadow:0 0 10px rgba(0,243,255,0.2);"> | |
| <div style="display:flex; justify-content:space-between; align-items:center;"> | |
| <h3 style="margin:0; color:var(--neon-purple);">Taller ${nota.id_taller}</h3> | |
| <span class="grade-badge" style="font-size:1rem;">Nota App: ${nota.nota_final}</span> | |
| </div> | |
| <div style="margin-top:15px; display:flex; justify-content:space-around; background:rgba(0,0,0,0.3); padding:10px; border-radius:10px;"> | |
| <div style="text-align:center;"> | |
| <div style="font-size:0.8rem; color:#ccc;">Cooperación</div> | |
| <div style="font-weight:bold; color:${coop > 0 ? '#4cd137' : '#888'};">${coop || '-'}</div> | |
| </div> | |
| <div style="text-align:center;"> | |
| <div style="font-size:0.8rem; color:#ccc;">Matemática</div> | |
| <div style="font-weight:bold; color:${math > 0 ? '#4cd137' : '#888'};">${math || '-'}</div> | |
| </div> | |
| </div> | |
| ${feedback} | |
| </div> | |
| `; | |
| }); | |
| html += `</div>`; | |
| } | |
| content.innerHTML = html; | |
| }, | |
| syncBadges: async () => { | |
| // 1. Obtener talleres completados donde la nota sea mayor o igual a 80 | |
| const { data: completados } = await supabase | |
| .from('rubricas_evaluacion') | |
| .select('id_taller, nota_final') // Traemos también la nota para validar | |
| .eq('id_estudiante', app.user.id) | |
| .gte('nota_final', 80); // <--- FILTRO CLAVE: Mayor o igual a 80 | |
| if (!completados || completados.length === 0) return; | |
| // 2. Obtener insignias ya asignadas | |
| const { data: asignadas } = await supabase | |
| .from('asignacion_logros') | |
| .select('id_insignia') | |
| .eq('id_estudiante', app.user.id); | |
| const asignadasIds = asignadas ? asignadas.map(a => parseInt(a.id_insignia)) : []; | |
| const talleresIds = [...new Set(completados.map(c => parseInt(c.id_taller)))]; | |
| // 3. Identificar faltantes (solo de los que pasaron con 80+) | |
| for (let tallerId of talleresIds) { | |
| if (!asignadasIds.includes(tallerId)) { | |
| console.log(`Auto-Fix: Asignando insignia ${tallerId} por nota meritoria...`); | |
| await supabase.from('asignacion_logros').insert({ | |
| id_estudiante: app.user.id, | |
| id_insignia: tallerId | |
| }); | |
| } | |
| } | |
| }, | |
| loadAvatarScreen: () => { | |
| const grid = document.getElementById('avatar-grid'); | |
| grid.innerHTML = ""; | |
| const seeds = ['CosmoBot1', 'AstroX', 'NovaUnit', 'GalaxDroid', 'StarFighter', 'CometZero', 'NebulaBot', 'QuantumBit', 'OrionUnit', 'TitanMech']; | |
| seeds.forEach(seed => { | |
| const div = document.createElement('div'); | |
| div.className = 'avatar-option'; | |
| div.innerHTML = `<img src="https://api.dicebear.com/7.x/bottts/svg?seed=${seed}" alt="${seed}">`; | |
| div.onclick = () => app.createProfileWithAvatar(seed); | |
| grid.appendChild(div); | |
| }); | |
| app.showScreen('view-avatar'); | |
| }, | |
| createProfileWithAvatar: async (seedString) => { | |
| const username = app.user.email.split('@')[0]; | |
| const niceName = username.charAt(0).toUpperCase() + username.slice(1); | |
| const newProfile = { | |
| id: app.user.id, | |
| nombre_completo: "Cadete " + niceName, | |
| puntos_energia: 0, | |
| avatar_config: seedString | |
| }; | |
| const { error } = await supabase.from('estudiantes').insert([newProfile]); | |
| if (error) { | |
| alert("Error creando perfil: " + error.message); | |
| return; | |
| } | |
| // Asegurarse de que el primer taller está desbloqueado | |
| await supabase.from('progreso_acceso').insert({ | |
| id_estudiante: app.user.id, | |
| id_taller: 1, | |
| acceso_desbloqueado: true | |
| }); | |
| app.profile = newProfile; | |
| app.role = 'student'; | |
| app.unlockedWorkshops = [1]; | |
| app.updateHUD(); | |
| app.showScreen('view-intro-story'); | |
| }, | |
| updateHUD: () => { | |
| if (app.profile && app.role === 'student') { | |
| document.getElementById('user-name').innerText = app.profile.nombre_completo; | |
| document.getElementById('energy-points').innerText = app.profile.puntos_energia; | |
| const seed = app.profile.avatar_config || "Default"; | |
| document.querySelector('.avatar-img').src = `https://api.dicebear.com/7.x/bottts/svg?seed=${seed}`; | |
| // Asegurar que el planeta 1 esté siempre desbloqueado visualmente | |
| document.getElementById('planet-1').classList.remove('locked'); | |
| document.getElementById('planet-1').classList.add('unlocked'); | |
| for (let i = 2; i <= 6; i++) { | |
| const planetEl = document.getElementById(`planet-${i}`); | |
| if (planetEl) { | |
| if (app.unlockedWorkshops.includes(i)) { | |
| planetEl.classList.remove('locked'); | |
| planetEl.classList.add('unlocked'); | |
| } else { | |
| planetEl.classList.add('locked'); | |
| planetEl.classList.remove('unlocked'); | |
| } | |
| } | |
| } | |
| } | |
| }, | |
| showScreen: (screenId) => { | |
| document.querySelectorAll('.screen').forEach(s => { | |
| s.classList.remove('active'); | |
| s.classList.add('hidden'); | |
| }); | |
| document.getElementById(screenId).classList.remove('hidden'); | |
| document.getElementById(screenId).classList.add('active'); | |
| }, | |
| closeModal: () => { | |
| document.getElementById('modal-feedback').classList.add('hidden'); | |
| gameEngine.nextStep(); | |
| }, | |
| goBackFromGame: () => { | |
| document.getElementById('timer-display').innerText = ""; | |
| const timerBar = document.getElementById('timer-bar'); | |
| if (timerBar) timerBar.style.width = '100%'; | |
| if (app.role === 'teacher') { | |
| teacherUI.renderDashboard(); | |
| app.showScreen('view-teacher'); | |
| } else { | |
| app.showScreen('view-map'); | |
| } | |
| }, | |
| launchWorkshop: (id) => { | |
| const dataMap = { | |
| 1: taller1Data, 2: taller2Data, 3: taller3Data, | |
| 4: taller4Data, 5: taller5Data, 6: taller6Data | |
| }; | |
| if (app.role === 'teacher' || app.unlockedWorkshops.includes(parseInt(id))) { | |
| app.showScreen('view-game'); | |
| if (dataMap[id]) gameEngine.start(dataMap[id]); | |
| } else { | |
| alert("🔒 Nivel Bloqueado. Debes completar la misión anterior."); | |
| } | |
| }, | |
| finishWorkshop: async (resultados) => { | |
| if (app.role === 'teacher') { | |
| alert("Modo Profesor: Revisión completada. No se guardan datos."); | |
| app.goBackFromGame(); | |
| return; | |
| } | |
| const rubricaData = { | |
| id_estudiante: app.user.id, | |
| id_taller: resultados.taller_id, | |
| aciertos: resultados.aciertos, | |
| errores: resultados.errores, | |
| nota_final: resultados.puntaje, // Aquí se guarda la nota | |
| feedback: "Evaluación Automática" | |
| }; | |
| await supabase.from('rubricas_evaluacion').insert([rubricaData]); | |
| // --- ASIGNACIÓN DE LOGRO/INSIGNIA (Modificada) --- | |
| // Solo se asigna si la nota_final (resultados.puntaje) es >= 80 | |
| if (resultados.puntaje >= 80) { | |
| const logroData = { | |
| id_estudiante: app.user.id, | |
| id_insignia: resultados.taller_id | |
| }; | |
| const { error: errorLogro } = await supabase.from('asignacion_logros').insert([logroData]); | |
| if (errorLogro) { | |
| console.log("Nota: Logro ya existía o error:", errorLogro.message); | |
| } else { | |
| console.log("¡Felicidades! Insignia obtenida por excelente calificación."); | |
| } | |
| } else { | |
| console.log("Misión terminada, pero la nota es inferior a 80. No se asigna insignia."); | |
| } | |
| // ------------------------------------------------- | |
| // El resto del código para energía y desbloqueo de niveles sigue igual... | |
| const newEnergy = (app.profile.puntos_energia || 0) + resultados.puntaje; | |
| await supabase.from('estudiantes') | |
| .update({ puntos_energia: newEnergy }) | |
| .eq('id', app.user.id); | |
| const currentLevel = parseInt(resultados.taller_id); | |
| const nextLevel = currentLevel + 1; | |
| if (nextLevel <= 6) { | |
| await supabase.from('progreso_acceso').upsert({ | |
| id_estudiante: app.user.id, | |
| id_taller: nextLevel, | |
| acceso_desbloqueado: true | |
| }, { onConflict: 'id_estudiante, id_taller' }); | |
| } | |
| app.profile.puntos_energia = newEnergy; | |
| await app.loadProgress(); | |
| app.updateHUD(); | |
| if (currentLevel === 6) { | |
| ui.showGrandFinale(resultados); | |
| } else { | |
| alert(`¡Misión Cumplida! Energía ganada: ${resultados.puntaje}\nNivel ${nextLevel} Desbloqueado.`); | |
| app.showScreen('view-map'); | |
| } | |
| } | |
| }; | |
| window.app = app; | |
| app.init(); |