# PLAN DE CORRECCIÓN - PORTAL ESTUDIANTES GAMILIT **Fecha:** 2026-01-10 **Estado:** PENDIENTE VALIDACIÓN --- ## RESUMEN DE HALLAZGOS Tras el análisis exhaustivo, se identificaron las siguientes causas raíz: | Tarea | Problema | Causa Raíz | Tipo | |-------|----------|------------|------| | Leaderboard | Usuarios genéricos | `FEATURE_FLAGS.USE_MOCK_DATA` retorna `[]` cuando está activo | Código | | Achievements | No encuentra datos usuario | Usuarios testing sin achievements por diseño + UX deficiente | Seeds/UX | | ModuleDetail | Error al cargar ejercicios | Múltiples (RLS, JWT, seeds, relaciones) | Multi-factor | --- ## TAREA 1: CORRECCIÓN LEADERBOARD ### Diagnóstico Final El código está correcto. El problema es que `FEATURE_FLAGS.USE_MOCK_DATA` en `socialAPI.ts:390-392` retorna `[]` (vacío) cuando está activo, en lugar de datos mock reales. **Verificación necesaria:** 1. Confirmar si `VITE_USE_MOCK_DATA` está definido en algún `.env.local` o `.env.development` 2. Verificar que el backend está corriendo y responde 3. Verificar que hay datos en `gamification_system.user_stats` ### Plan de Corrección #### FASE 1: Verificación de ambiente ```bash # 1.1 Verificar todas las variables de entorno grep -r "VITE_USE_MOCK_DATA" apps/frontend/ # 1.2 Verificar si hay .env.local cat apps/frontend/.env.local 2>/dev/null || echo "No existe .env.local" # 1.3 Verificar backend corriendo curl -s http://localhost:3006/api/v1/health | jq # 1.4 Verificar endpoint leaderboard curl -s http://localhost:3006/api/v1/gamification/leaderboard/global | jq ``` #### FASE 2: Corrección de código (si es necesario) **Archivo:** `/apps/frontend/src/features/gamification/social/api/socialAPI.ts` **Cambio propuesto (líneas 390-393):** ```typescript // ANTES: if (FEATURE_FLAGS.USE_MOCK_DATA) { await new Promise((resolve) => setTimeout(resolve, 600)); return []; // ← Retorna vacío } // DESPUÉS: if (FEATURE_FLAGS.USE_MOCK_DATA) { await new Promise((resolve) => setTimeout(resolve, 600)); // Importar datos mock si está habilitado const { leaderboardMockData } = await import('../mockData/leaderboardsMockData'); return leaderboardMockData; } ``` #### FASE 3: Validación de Seeds **Verificar datos en BD:** ```sql -- Verificar user_stats con datos SELECT u.email, p.display_name, us.level, us.total_xp, us.ml_coins FROM gamification_system.user_stats us JOIN auth_management.profiles p ON p.user_id = us.user_id JOIN auth.users u ON u.id = p.user_id ORDER BY us.total_xp DESC LIMIT 20; ``` ### Archivos a Modificar | Archivo | Líneas | Cambio | |---------|--------|--------| | `socialAPI.ts` | 390-392 | Retornar mock data real o eliminar condición | | `.env` | N/A | Asegurar `VITE_USE_MOCK_DATA` no esté definido o sea `false` | ### Criterios de Éxito - [ ] Leaderboard muestra usuarios reales de la BD - [ ] Usuarios ordenados por XP/score descendente - [ ] Usuario actual marcado con `isCurrentUser: true` - [ ] No errores en consola --- ## TAREA 2: CORRECCIÓN ACHIEVEMENTS ### Diagnóstico Final **NO ES UN BUG** - Es comportamiento intencional: - Los usuarios de testing (`student@gamilit.com`, etc.) NO tienen achievements por diseño - Esto permite que empiecen desde cero como usuarios nuevos - Los usuarios demo (Ana García, Carlos Ramírez, etc.) SÍ tienen achievements **Problema UX:** La página debería mostrar todos los achievements disponibles aunque estén "locked", no un mensaje de "no hay datos". ### Plan de Corrección #### FASE 1: Verificar endpoint de achievements ```bash # Obtener todos los achievements disponibles curl -s http://localhost:3006/api/v1/gamification/achievements | jq # Obtener achievements del usuario student curl -s -H "Authorization: Bearer " \ http://localhost:3006/api/v1/gamification/users/cccccccc-cccc-cccc-cccc-cccccccccccc/achievements | jq ``` #### FASE 2: Mejora de UX (Frontend) **Archivo:** `/apps/frontend/src/apps/student/pages/GamificationPage.tsx` o página de Achievements **Cambio propuesto:** - Si `unlockedAchievements.length === 0`, mostrar: - "No tienes logros desbloqueados aún" - Lista de achievements disponibles con estado "locked" - Call to action: "¡Completa ejercicios para desbloquear logros!" #### FASE 3: Opción - Agregar achievement "Primera Visita" automático Los usuarios de testing podrían tener al menos el achievement de "Primera Visita" si se activa el trigger correspondiente al hacer login. **Verificar trigger:** ```sql -- Verificar si existe trigger para crear achievement automático SELECT * FROM pg_trigger WHERE tgname LIKE '%achievement%'; ``` ### Archivos a Modificar | Archivo | Líneas | Cambio | |---------|--------|--------| | `GamificationPage.tsx` | Sección achievements | Mejorar UX para lista vacía | | `AchievementsPage.tsx` | Render | Mostrar achievements locked si no hay unlocked | | `achievementsStore.ts` | N/A | Sin cambios - funciona correctamente | ### Criterios de Éxito - [ ] Página muestra todos los achievements (locked y unlocked) - [ ] Usuario sin achievements ve mensaje amigable + lista de disponibles - [ ] Progreso de achievements se muestra correctamente - [ ] No errores 404 en consola --- ## TAREA 3: CORRECCIÓN MODULE DETAIL ### Diagnóstico Final El problema puede tener múltiples causas: 1. **RLS (Row Level Security):** El usuario debe pertenecer a un classroom con assignments asignados 2. **JWT:** El token debe ser válido y contener el userId correcto 3. **Seeds:** Los ejercicios deben existir y estar relacionados con el módulo 4. **Relaciones:** module_id en exercises debe coincidir con id del módulo ### Plan de Corrección #### FASE 1: Diagnóstico completo ```bash # 1.1 Verificar módulos existentes curl -s http://localhost:3006/api/v1/educational/modules | jq # 1.2 Verificar ejercicios de un módulo específico (reemplazar {moduleId}) curl -s -H "Authorization: Bearer " \ http://localhost:3006/api/v1/educational/modules/{moduleId}/exercises | jq # 1.3 Verificar que usuario tiene classroom curl -s -H "Authorization: Bearer " \ http://localhost:3006/api/v1/users/me/classrooms | jq ``` #### FASE 2: Verificar seeds de módulos y ejercicios ```sql -- Verificar módulos SELECT id, title, status, is_active FROM educational_content.modules ORDER BY order_index; -- Verificar ejercicios por módulo SELECT m.title as module, COUNT(e.id) as exercises FROM educational_content.modules m LEFT JOIN educational_content.exercises e ON e.module_id = m.id GROUP BY m.id, m.title ORDER BY m.order_index; -- Verificar que student@ pertenece a classroom SELECT c.name as classroom, u.email FROM educational_content.classrooms c JOIN educational_content.classroom_students cs ON cs.classroom_id = c.id JOIN auth.users u ON u.id = cs.student_id WHERE u.email = 'student@gamilit.com'; ``` #### FASE 3: Correcciones de código (si es necesario) **Mejorar manejo de errores en frontend:** **Archivo:** `/apps/frontend/src/apps/student/pages/ModuleDetailPage.tsx` ```typescript // Agregar mensaje de error más descriptivo if (error) { return ( refetch()} /> ); } ``` #### FASE 4: Verificar relaciones classroom-student-assignment **Si el usuario no está en un classroom:** ```sql -- Agregar student@ a un classroom de prueba INSERT INTO educational_content.classroom_students (classroom_id, student_id) SELECT c.id, u.id FROM educational_content.classrooms c, auth.users u WHERE c.name = 'Aula Demo' AND u.email = 'student@gamilit.com' ON CONFLICT DO NOTHING; ``` ### Archivos a Modificar | Archivo | Líneas | Cambio | |---------|--------|--------| | `ModuleDetailPage.tsx` | Error handling | Mejorar mensajes de error | | `useModules.ts` | 94-129 | Agregar logging detallado | | Seeds SQL | N/A | Verificar relaciones classroom-student | ### Criterios de Éxito - [ ] Módulos se cargan correctamente - [ ] Ejercicios del módulo se muestran - [ ] Progreso del usuario visible - [ ] Errores descriptivos si hay problemas - [ ] No errores 500 en backend --- ## TAREA 4: VALIDACIÓN INTEGRAL ### Alcance 1. **Verificación de dependencias cruzadas** 2. **Seeds consistentes entre tablas** 3. **Integraciones con portales admin/teacher** 4. **Duplicidad de funcionalidades** ### Plan de Validación #### FASE 1: Validar consistencia de datos ```sql -- Verificar integridad referencial -- 1. Usuarios sin profile SELECT u.id, u.email FROM auth.users u LEFT JOIN auth_management.profiles p ON p.user_id = u.id WHERE p.id IS NULL; -- 2. Profiles sin user_stats SELECT p.display_name, p.user_id FROM auth_management.profiles p LEFT JOIN gamification_system.user_stats us ON us.user_id = p.user_id WHERE us.id IS NULL; -- 3. user_achievements huérfanos SELECT ua.id, ua.user_id, ua.achievement_id FROM gamification_system.user_achievements ua LEFT JOIN auth_management.profiles p ON p.user_id = ua.user_id LEFT JOIN gamification_system.achievements a ON a.id = ua.achievement_id WHERE p.id IS NULL OR a.id IS NULL; -- 4. Ejercicios sin módulo válido SELECT e.id, e.title, e.module_id FROM educational_content.exercises e LEFT JOIN educational_content.modules m ON m.id = e.module_id WHERE m.id IS NULL; ``` #### FASE 2: Verificar integraciones ```bash # Portal Admin - Verificar endpoints curl -s http://localhost:3006/api/v1/admin/users | head curl -s http://localhost:3006/api/v1/admin/statistics | head # Portal Teacher - Verificar endpoints curl -s http://localhost:3006/api/v1/teachers/classrooms | head curl -s http://localhost:3006/api/v1/teachers/assignments | head ``` #### FASE 3: Revisar duplicidad de funcionalidades Archivos a revisar: - `/apps/frontend/src/features/gamification/social/api/socialAPI.ts` - `/apps/frontend/src/api/gamification.api.ts` - `/apps/frontend/src/features/gamification/social/api/achievementsAPI.ts` **Consolidación recomendada:** - Unificar llamadas API duplicadas - Usar un solo store por dominio - Eliminar funciones duplicadas --- ## ORDEN DE EJECUCIÓN 1. **FASE 0:** Verificación de ambiente (backend corriendo, BD accesible) 2. **TAREA 1:** Corregir Leaderboard (más crítico) 3. **TAREA 3:** Corregir ModuleDetail (afecta funcionalidad core) 4. **TAREA 2:** Mejorar UX Achievements (mejora incremental) 5. **TAREA 4:** Validación integral (consolidación) --- ## ESTIMACIÓN DE CAMBIOS | Tarea | Archivos | Complejidad | Riesgo | |-------|----------|-------------|--------| | Leaderboard | 1-2 | Baja | Bajo | | Achievements | 2-3 | Media | Bajo | | ModuleDetail | 2-4 | Alta | Medio | | Validación | N/A | Media | Bajo | --- ## SIGUIENTE PASO **Ejecutar diagnóstico de ambiente para confirmar estado actual antes de aplicar correcciones.**