feat: Add LTI launch, lesson preview, course progress, bookmarks, and asset management features.

This commit is contained in:
2026-02-23 15:43:45 -03:00
parent f365e585a2
commit 7f7ea3d70c
45 changed files with 5250 additions and 697 deletions
+127
View File
@@ -0,0 +1,127 @@
"use client";
import React, { useEffect, useState } from 'react';
import { lmsApi, UserBookmark, Course, Module } from '@/lib/api';
import { Bookmark, ChevronRight, BookOpen, Clock, Trash2 } from 'lucide-react';
import Link from 'next/link';
import { formatDistanceToNow } from 'date-fns';
import { es } from 'date-fns/locale';
export default function BookmarksPage() {
const [bookmarks, setBookmarks] = useState<UserBookmark[]>([]);
const [courses, setCourses] = useState<Record<string, Course & { modules: Module[] }>>({});
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchBookmarks = async () => {
try {
const data = await lmsApi.getBookmarks();
setBookmarks(data);
// Fetch course details for each unique course_id
const courseIds = [...new Set(data.map(b => b.course_id))];
const courseData: Record<string, Course & { modules: Module[] }> = {};
await Promise.all(courseIds.map(async (id) => {
try {
const outline = await lmsApi.getCourseOutline(id);
courseData[id] = { ...outline.course, modules: outline.modules };
} catch (e) {
console.error(`Error fetching course ${id}`, e);
}
}));
setCourses(courseData);
} catch (err) {
console.error("Error fetching bookmarks:", err);
} finally {
setLoading(false);
}
};
fetchBookmarks();
}, []);
const handleRemoveBookmark = async (lessonId: string) => {
try {
await lmsApi.toggleBookmark(lessonId);
setBookmarks(prev => prev.filter(b => b.lesson_id !== lessonId));
} catch (err) {
console.error("Error removing bookmark:", err);
}
};
if (loading) return <div className="p-20 text-center animate-pulse text-gray-500 font-bold uppercase tracking-widest">Cargando Marcadores...</div>;
return (
<div className="max-w-6xl mx-auto px-6 py-20">
<div className="mb-12">
<div className="flex items-center gap-4 mb-2">
<div className="w-12 h-12 rounded-2xl glass border-yellow-500/20 bg-yellow-500/10 flex items-center justify-center">
<Bookmark size={24} className="text-yellow-400" fill="currentColor" />
</div>
<h1 className="text-4xl font-black tracking-tight text-white">Mis Lecciones Guardadas</h1>
</div>
<p className="text-gray-500 font-bold uppercase tracking-widest text-[10px]">Acceso rápido a los contenidos que marcaste como importantes</p>
</div>
{bookmarks.length === 0 ? (
<div className="py-20 text-center glass rounded-[2.5rem] border-white/5 bg-white/[0.02]">
<div className="w-20 h-20 rounded-full bg-white/5 flex items-center justify-center mx-auto mb-6">
<Bookmark size={32} className="text-gray-600" />
</div>
<h3 className="text-xl font-bold text-white mb-2">Aún no tienes marcadores</h3>
<p className="text-gray-500 max-w-md mx-auto">Cuando encuentres una lección interesante, haz clic en el icono de marcador para guardarla aquí.</p>
</div>
) : (
<div className="grid gap-6">
{bookmarks.map((bookmark) => {
const course = courses[bookmark.course_id];
return (
<div key={bookmark.id} className="group relative glass rounded-3xl border-white/5 hover:border-yellow-500/30 transition-all duration-500 bg-white/[0.02] hover:bg-yellow-500/[0.02] p-6 flex flex-col md:flex-row md:items-center justify-between gap-6">
<div className="flex items-center gap-6">
<div className="w-16 h-16 rounded-2xl bg-gradient-to-br from-yellow-500/20 to-orange-500/20 flex items-center justify-center shrink-0 border border-white/5">
<BookOpen size={24} className="text-yellow-400" />
</div>
<div>
<div className="flex items-center gap-2 mb-1">
<span className="text-[10px] font-black uppercase tracking-widest text-yellow-500/60">{course?.title || 'Curso'}</span>
<span className="text-gray-700"></span>
<span className="text-[10px] font-bold text-gray-500 flex items-center gap-1">
<Clock size={10} />
Guardado {formatDistanceToNow(new Date(bookmark.created_at), { addSuffix: true, locale: es })}
</span>
</div>
<Link href={`/courses/${bookmark.course_id}/lessons/${bookmark.lesson_id}`}>
<h3 className="text-xl font-black text-white group-hover:text-yellow-400 transition-colors tracking-tight">
{(() => {
const lesson = course?.modules?.flatMap(m => m.lessons).find(l => l.id === bookmark.lesson_id);
return lesson?.title || `Lección ${bookmark.lesson_id.substring(0, 8)}`;
})()}
</h3>
</Link>
</div>
</div>
<div className="flex items-center gap-4">
<button
onClick={() => handleRemoveBookmark(bookmark.lesson_id)}
className="p-3 rounded-xl hover:bg-red-500/10 text-gray-500 hover:text-red-400 transition-all border border-transparent hover:border-red-500/20"
title="Eliminar marcador"
>
<Trash2 size={20} />
</button>
<Link
href={`/courses/${bookmark.course_id}/lessons/${bookmark.lesson_id}`}
className="btn-premium !py-3 !px-6 text-xs group/btn"
>
Continuar <ChevronRight size={16} className="group-hover/btn:translate-x-1 transition-transform" />
</Link>
</div>
</div>
);
})}
</div>
)}
</div>
);
}
@@ -3,7 +3,7 @@
import { useEffect, useState } from "react";
import { lmsApi, Lesson, Course, Module, UserGrade } from "@/lib/api";
import Link from "next/link";
import { ChevronLeft, ChevronRight, Menu, CheckCircle2 } from "lucide-react";
import { ChevronLeft, ChevronRight, Menu, CheckCircle2, Bookmark } from "lucide-react";
import { useAuth } from "@/context/AuthContext";
import DescriptionPlayer from "@/components/blocks/DescriptionPlayer";
@@ -35,6 +35,7 @@ export default function LessonPlayerPage({ params }: { params: { id: string, les
const [currentTime, setCurrentTime] = useState(0);
const [userGrade, setUserGrade] = useState<UserGrade | null>(null);
const [allGrades, setAllGrades] = useState<UserGrade[]>([]);
const [isBookmarked, setIsBookmarked] = useState(false);
const { user } = useAuth();
useEffect(() => {
@@ -48,10 +49,14 @@ export default function LessonPlayerPage({ params }: { params: { id: string, les
setCourse({ ...outlineData.course, modules: outlineData.modules });
if (user) {
const grades = await lmsApi.getUserGrades(user.id, params.id);
const [grades, bookmarks] = await Promise.all([
lmsApi.getUserGrades(user.id, params.id),
lmsApi.getBookmarks(params.id)
]);
setAllGrades(grades);
const currentGrade = grades.find((g: UserGrade) => g.lesson_id === params.lessonId);
setUserGrade(currentGrade || null);
setIsBookmarked(bookmarks.some(b => b.lesson_id === params.lessonId));
}
} catch (err) {
console.error("Error al cargar los datos de la lección", err);
@@ -129,6 +134,15 @@ export default function LessonPlayerPage({ params }: { params: { id: string, les
}
};
const handleToggleBookmark = async () => {
try {
await lmsApi.toggleBookmark(params.lessonId);
setIsBookmarked(!isBookmarked);
} catch (err) {
console.error("Error toggling bookmark", err);
}
};
const getLessonStatus = (l: Lesson) => {
const grade = allGrades.find(g => g.lesson_id === l.id);
const isCurrent = l.id === params.lessonId;
@@ -215,6 +229,13 @@ export default function LessonPlayerPage({ params }: { params: { id: string, les
>
<Menu size={20} />
</button>
<button
onClick={handleToggleBookmark}
className={`p-3 rounded-xl glass border-white/10 transition-all bg-black/40 ${isBookmarked ? 'text-yellow-400' : 'text-gray-400 hover:text-white'}`}
title={isBookmarked ? "Quitar Marcador" : "Guardar Marcador"}
>
<Bookmark size={20} fill={isBookmarked ? "currentColor" : "none"} />
</button>
{hasTranscription && (
<button
onClick={() => {
+31 -4
View File
@@ -18,6 +18,7 @@ export default function CourseOutlinePage({ params }: { params: { id: string } }
const [userGrades, setUserGrades] = useState<UserGrade[]>([]);
const [isEnrolled, setIsEnrolled] = useState(false);
const [lessonDependencies, setLessonDependencies] = useState<any[]>([]);
const [instructors, setInstructors] = useState<any[]>([]);
useEffect(() => {
const fetchData = async () => {
@@ -26,6 +27,7 @@ export default function CourseOutlinePage({ params }: { params: { id: string } }
const data = await lmsApi.getCourseOutline(params.id);
setCourseData({ ...data.course, modules: data.modules });
setLessonDependencies(data.dependencies || []);
setInstructors(data.instructors || []);
if (user) {
const grades = await lmsApi.getUserGrades(user.id, params.id);
@@ -171,6 +173,25 @@ export default function CourseOutlinePage({ params }: { params: { id: string } }
)}
</div>
{instructors.length > 0 && (
<div className="mb-10 animate-in fade-in slide-in-from-left-4 duration-700">
<span className="text-[10px] font-black uppercase tracking-[0.2em] text-gray-500 mb-4 block">Equipo docente</span>
<div className="flex flex-wrap gap-6">
{instructors.map((inst) => (
<div key={inst.id} className="flex items-center gap-3 glass border-white/5 px-4 py-2 rounded-2xl hover:bg-white/5 transition-all">
<div className="w-8 h-8 rounded-full bg-blue-500/20 flex items-center justify-center border border-blue-500/30 text-blue-400 font-bold text-xs">
{inst.full_name?.charAt(0) || inst.email?.charAt(0)}
</div>
<div>
<div className="text-xs font-bold text-gray-200">{inst.full_name}</div>
<div className="text-[8px] font-black uppercase tracking-widest text-blue-500/60">{inst.role === 'primary' ? 'Instructor principal' : inst.role}</div>
</div>
</div>
))}
</div>
</div>
)}
<div className="flex items-center justify-between">
<div className="flex items-center gap-8">
<div className="flex flex-col">
@@ -291,7 +312,8 @@ export default function CourseOutlinePage({ params }: { params: { id: string } }
<div className="grid gap-3 pl-14">
{module.lessons.map((lesson: any) => {
const locked = isLessonLocked(lesson.id);
return isEnrolled ? (
const isPreviewable = lesson.is_previewable;
return (isEnrolled || isPreviewable) ? (
locked ? (
<div key={lesson.id} className="glass-card !p-4 border-white/5 opacity-60 cursor-not-allowed">
<div className="flex items-center justify-between">
@@ -316,13 +338,18 @@ export default function CourseOutlinePage({ params }: { params: { id: string } }
<div className="flex items-center gap-4">
<div className="w-10 h-10 rounded-lg bg-white/5 flex items-center justify-center group-hover:bg-blue-500/20 transition-colors">
{lesson.content_type === 'video' ? (
<PlayCircle size={18} className="text-gray-400 group-hover:text-blue-400" />
<PlayCircle size={18} className={`${isPreviewable && !isEnrolled ? 'text-green-400' : 'text-gray-400'} group-hover:text-blue-400`} />
) : (
<BookOpen size={18} className="text-gray-400 group-hover:text-blue-400" />
<BookOpen size={18} className={`${isPreviewable && !isEnrolled ? 'text-green-400' : 'text-gray-400'} group-hover:text-blue-400`} />
)}
</div>
<div>
<h3 className="text-sm font-bold text-gray-200 group-hover:text-white transition-colors">{lesson.title}</h3>
<div className="flex items-center gap-2">
<h3 className="text-sm font-bold text-gray-200 group-hover:text-white transition-colors">{lesson.title}</h3>
{isPreviewable && !isEnrolled && (
<span className="text-[8px] font-black uppercase px-1.5 py-0.5 bg-green-500/10 text-green-400 border border-green-500/20 rounded">Vista previa</span>
)}
</div>
<span className="text-[10px] font-bold uppercase tracking-widest text-gray-500">
{lesson.content_type === 'activity' ? 'Actividad Interactiva' : 'Lección en Video'}
</span>
@@ -1,280 +1,49 @@
"use client";
import React, { useState, useEffect } from "react";
import { useParams, useRouter } from "next/navigation";
import { lmsApi, GradingCategory, UserGrade, Course, Module } from "@/lib/api";
import { useAuth } from "@/context/AuthContext";
import {
Award,
BarChart3,
CheckCircle2,
ChevronRight,
Target,
BookOpen,
ArrowLeft,
TrendingUp
} from "lucide-react";
import PerformanceBar from "@/components/PerformanceBar";
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export default function StudentProgressPage() {
const { id } = useParams() as { id: string };
const router = useRouter();
const [course, setCourse] = useState<(Course & { modules: Module[], grading_categories?: GradingCategory[] }) | null>(null);
const [userGrades, setUserGrades] = useState<UserGrade[]>([]);
const [loading, setLoading] = useState(true);
const { user } = useAuth();
const loadData = React.useCallback(async () => {
try {
const { course, modules, grading_categories } = await lmsApi.getCourseOutline(id);
setCourse({ ...course, modules, grading_categories });
if (user) {
const grades = await lmsApi.getUserGrades(user.id, id);
setUserGrades(grades);
}
} catch (err) {
console.error("Error al cargar los datos de progreso", err);
} finally {
setLoading(false);
}
}, [id, user]);
useEffect(() => {
loadData();
}, [loadData]);
if (loading) return (
<div className="min-h-screen bg-slate-950 flex items-center justify-center">
<div className="w-12 h-12 border-4 border-blue-500/20 border-t-blue-500 rounded-full animate-spin"></div>
</div>
);
if (!course) return <div className="p-20 text-center text-white">Curso no encontrado.</div>;
const gradingCategories = course.grading_categories || [];
// Calculate progress
const categoryStats = gradingCategories.map(cat => {
const catLessons = course.modules.flatMap(m => m.lessons).filter(l => l.grading_category_id === cat.id);
const catGrades = userGrades.filter(g => catLessons.some(l => l.id === g.lesson_id));
const count = catLessons.length;
const completedCount = catGrades.length;
const avgScore = completedCount > 0
? (catGrades.reduce((sum, g) => sum + g.score, 0) / completedCount) * 100
: 0;
const weightedScore = (avgScore * cat.weight) / 100;
return {
...cat,
count,
completedCount,
avgScore,
weightedScore
};
});
const totalWeightedGrade = categoryStats.reduce((sum, s) => sum + s.weightedScore, 0);
import React from 'react';
import ProgressDashboard from '@/components/ProgressDashboard';
import { ChevronLeft, LayoutDashboard } from 'lucide-react';
import Link from 'next/link';
export default function ProgressPage({ params }: { params: { id: string } }) {
return (
<div className="min-h-screen bg-slate-950 text-white pb-20">
{/* Nav */}
<div className="sticky top-0 z-50 bg-slate-950/80 backdrop-blur-xl border-b border-white/5 py-4 px-8">
<div className="max-w-6xl mx-auto flex items-center justify-between">
<div className="flex items-center gap-4">
<button onClick={() => router.back()} className="p-2 hover:bg-white/5 rounded-full transition-colors">
<ArrowLeft className="w-5 h-5 text-gray-400" />
</button>
<h1 className="text-xl font-bold">{course.title}</h1>
<div className="max-w-6xl mx-auto px-6 py-20">
<div className="mb-12 flex flex-col md:flex-row md:items-end justify-between gap-6">
<div>
<Link
href={`/courses/${params.id}`}
className="flex items-center gap-2 text-blue-500 font-bold text-xs uppercase tracking-widest mb-6 hover:text-white transition-colors group"
>
<ChevronLeft size={16} className="group-hover:-translate-x-1 transition-transform" />
Volver al curso
</Link>
<div className="flex items-center gap-4 mb-2">
<div className="w-12 h-12 rounded-2xl glass border-blue-500/20 bg-blue-500/10 flex items-center justify-center">
<LayoutDashboard size={24} className="text-blue-400" />
</div>
<h1 className="text-4xl font-black tracking-tight text-white">Tu Progreso de Aprendizaje</h1>
</div>
<p className="text-gray-500 font-bold uppercase tracking-widest text-[10px]">Análisis detallado de tu avance y predicción de finalización</p>
</div>
</div>
<div className="max-w-6xl mx-auto px-8 mt-12 grid grid-cols-1 lg:grid-cols-3 gap-12">
{/* Left: Overall Progress */}
<div className="lg:col-span-1 space-y-8">
<div className="bg-gradient-to-br from-blue-600/20 to-indigo-600/20 rounded-[2.5rem] p-12 border border-blue-500/20 text-center relative overflow-hidden group">
<div className="absolute top-0 right-0 w-32 h-32 bg-blue-500/10 blur-3xl rounded-full -translate-y-1/2 translate-x-1/2 group-hover:bg-blue-500/20 transition-all duration-700"></div>
<h2 className="text-gray-400 font-bold uppercase tracking-widest text-xs mb-8">Estado General</h2>
<ProgressDashboard courseId={params.id} />
<div className="relative inline-flex items-center justify-center mb-8">
<svg className="w-48 h-48 -rotate-90">
<circle
className="text-white/5"
strokeWidth="8"
stroke="currentColor"
fill="transparent"
r="88"
cx="96"
cy="96"
/>
<circle
className="text-blue-500 transition-all duration-1000 ease-out"
strokeWidth="8"
strokeDasharray={88 * 2 * Math.PI}
strokeDashoffset={88 * 2 * Math.PI * (1 - totalWeightedGrade / 100)}
strokeLinecap="round"
stroke="currentColor"
fill="transparent"
r="88"
cx="96"
cy="96"
/>
</svg>
<div className="absolute inset-0 flex flex-col items-center justify-center">
<span className="text-6xl font-black">{Math.round(totalWeightedGrade)}%</span>
<span className="text-xs text-blue-400 font-bold uppercase tracking-widest mt-1">Calificación Actual</span>
</div>
</div>
{/* Performance Bar */}
<div className="mt-8">
<PerformanceBar
score={Math.round(totalWeightedGrade)}
passingPercentage={course.passing_percentage || 70}
/>
</div>
<div className="mt-12 p-8 glass rounded-[2.5rem] border-white/5 bg-blue-500/[0.02]">
<h3 className="text-lg font-black text-white tracking-tight mb-4">¿Cómo se calcula mi progreso?</h3>
<div className="grid md:grid-cols-3 gap-8">
<div className="space-y-2">
<span className="text-[10px] font-black uppercase tracking-widest text-blue-400">Completado</span>
<p className="text-sm text-gray-400 leading-relaxed">Consideramos una lección como completada cuando has visualizado el contenido o aprobado la evaluación correspondiente.</p>
</div>
<div className="bg-white/5 rounded-3xl p-8 border border-white/10 space-y-6">
<h3 className="text-sm font-bold uppercase tracking-[0.2em] text-gray-500 flex items-center gap-2">
<BarChart3 className="w-4 h-4" /> Resumen de Evaluaciones
</h3>
<div className="space-y-4">
{categoryStats.map(stat => (
<div key={stat.id} className="flex items-center justify-between group">
<div className="flex items-center gap-3">
<div className="w-2 h-2 rounded-full bg-blue-500 shadow-[0_0_10px_rgba(59,130,246,0.5)]"></div>
<span className="text-gray-400 group-hover:text-white transition-colors">{stat.name}</span>
</div>
<span className="font-bold">{Math.round(stat.weightedScore)} / {stat.weight}%</span>
</div>
))}
</div>
<div className="space-y-2">
<span className="text-[10px] font-black uppercase tracking-widest text-indigo-400">Predicción</span>
<p className="text-sm text-gray-400 leading-relaxed">Calculamos tu fecha estimada analizando cuántas lecciones completas por día desde que iniciaste el curso.</p>
</div>
<div className="space-y-2">
<span className="text-[10px] font-black uppercase tracking-widest text-purple-400">Recomendaciones</span>
<p className="text-sm text-gray-400 leading-relaxed">Si tu ritmo es bajo, verás sugerencias personalizadas en la página principal para ayudarte a retomar el camino.</p>
</div>
</div>
{/* Right: Detailed Breakdown */}
<div className="lg:col-span-2 space-y-12">
<section>
<h2 className="text-2xl font-black mb-8 flex items-center gap-3">
<Target className="w-8 h-8 text-blue-500" />
Desglose Detallado
</h2>
<div className="space-y-4">
{categoryStats.map(cat => (
<div key={cat.id} className="bg-white/5 border border-white/10 rounded-3xl p-8 hover:bg-white/[0.07] transition-all group">
<div className="flex items-start justify-between mb-8">
<div>
<h3 className="text-xl font-bold">{cat.name}</h3>
<p className="text-gray-400 text-sm mt-1">
Peso: {cat.weight}% de la calificación total del curso
</p>
</div>
<div className="text-right">
<div className="text-4xl font-black text-blue-500">{Math.round(cat.avgScore)}%</div>
<div className="text-[10px] text-gray-500 font-bold uppercase tracking-widest mt-1">Puntuación Promedio</div>
</div>
</div>
<div className="space-y-6">
<div className="relative h-2 bg-white/5 rounded-full overflow-hidden">
<div
className="absolute inset-y-0 left-0 bg-gradient-to-r from-blue-600 to-indigo-600 rounded-full transition-all duration-1000 ease-out"
style={{ width: `${cat.avgScore}%` }}
></div>
</div>
<div className="flex items-center justify-between text-sm">
<div className="flex items-center gap-4">
<div className="flex items-center gap-2">
<BookOpen className="w-4 h-4 text-gray-500" />
<span className="text-gray-400">{cat.completedCount} / {cat.count} evaluaciones completadas</span>
</div>
</div>
{cat.completedCount === cat.count && (
<div className="flex items-center gap-2 text-green-400 font-bold">
<CheckCircle2 className="w-4 h-4" />
Categoría Finalizada
</div>
)}
</div>
</div>
</div>
))}
</div>
</section>
{/* Certificate Section */}
{totalWeightedGrade >= (course.passing_percentage || 70) ? (
<section className="bg-green-500/10 border border-green-500/20 rounded-[2rem] p-8 flex items-center justify-between">
<div className="flex items-center gap-6">
<div className="w-16 h-16 rounded-2xl bg-green-500/20 flex items-center justify-center text-green-400">
<Award className="w-8 h-8" />
</div>
<div>
<h3 className="text-lg font-bold text-green-400">¡Curso Completado!</h3>
<p className="text-sm text-green-300/60 mt-0.5">
¡Felicidades! Has aprobado <b>{course.title}</b>.
</p>
</div>
</div>
<button
onClick={() => {
if (!course.certificate_template || !user) {
alert("Plantilla de certificado no disponible.");
return;
}
const filledTemplate = course.certificate_template
.replace(/{{student_name}}/g, user.full_name)
.replace(/{{course_title}}/g, course.title)
.replace(/{{date}}/g, new Date().toLocaleDateString())
.replace(/{{score}}/g, Math.round(totalWeightedGrade).toString());
const win = window.open('', '_blank');
if (win) {
win.document.write(filledTemplate);
win.document.close();
// Wait visuals to render then print
setTimeout(() => {
win.focus();
win.print();
}, 500);
}
}}
className="px-6 py-3 bg-green-500 hover:bg-green-600 text-white font-bold rounded-xl transition-colors shadow-lg shadow-green-900/20 flex items-center gap-2"
>
<Award className="w-4 h-4" />
Descargar Certificado
</button>
</section>
) : (
<section className="bg-indigo-600/10 border border-indigo-500/20 rounded-[2rem] p-8 flex items-center justify-between">
<div className="flex items-center gap-6">
<div className="w-16 h-16 rounded-2xl bg-indigo-500/20 flex items-center justify-center text-indigo-400">
<TrendingUp className="w-8 h-8" />
</div>
<div>
<h3 className="text-lg font-bold">Ruta de Certificación</h3>
<p className="text-sm text-indigo-300/60 mt-0.5">
Mantén {course.passing_percentage || 70}% o más para obtener tu certificado verificado.
</p>
</div>
</div>
<div className="text-indigo-400 font-bold text-sm">
Falta {Math.max(0, (course.passing_percentage || 70) - Math.round(totalWeightedGrade))}%
</div>
</section>
)}
</div>
</div>
</div>
@@ -0,0 +1,85 @@
"use client";
import { useEffect, useState, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { lmsApi } from "@/lib/api";
import { useAuth } from "@/context/AuthContext";
function LtiLaunchContent() {
const router = useRouter();
const searchParams = useSearchParams();
const { login } = useAuth();
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const handleLaunch = async () => {
const token = searchParams.get("token");
const target = searchParams.get("target") || "/dashboard";
if (!token) {
setError("No launch token provided");
return;
}
try {
// 1. Temporarily save token so api client can use it for getMe
localStorage.setItem("experience_token", token);
// 2. Fetch user details
const user = await lmsApi.getMe();
// 3. Initialize session in AuthContext
login(user, token);
// 4. Redirect to final destination
router.replace(target);
} catch (err: any) {
console.error("LTI Launch Error:", err);
setError("Failed to initialize session. Please try again.");
}
};
handleLaunch();
}, [searchParams, login, router]);
if (error) {
return (
<div className="min-h-screen flex items-center justify-center bg-[#0a0a0a] text-white p-6">
<div className="max-w-md w-full bg-white/5 border border-white/10 rounded-3xl p-8 text-center space-y-4">
<div className="text-4xl"></div>
<h1 className="text-2xl font-black text-red-400">Error de Inicio</h1>
<p className="text-gray-400">{error}</p>
<button
onClick={() => router.push("/auth/login")}
className="btn-primary w-full py-3 rounded-xl font-bold uppercase tracking-widest text-xs"
>
Volver al Login
</button>
</div>
</div>
);
}
return (
<div className="min-h-screen flex items-center justify-center bg-[#0a0a0a] text-white">
<div className="text-center space-y-6">
<div className="relative w-20 h-20 mx-auto">
<div className="absolute inset-0 border-t-4 border-purple-500 rounded-full animate-spin"></div>
<div className="absolute inset-2 border-t-4 border-blue-500 rounded-full animate-spin-slow"></div>
</div>
<div>
<h1 className="text-2xl font-black tracking-tighter uppercase italic">Iniciando Sesión</h1>
<p className="text-gray-500 text-sm font-bold tracking-widest uppercase mt-2">OpenCCB LTI Gateway</p>
</div>
</div>
</div>
);
}
export default function LtiLaunchPage() {
return (
<Suspense fallback={null}>
<LtiLaunchContent />
</Suspense>
);
}
@@ -48,6 +48,9 @@ export default function AppHeader() {
<Link href="/my-learning" className="text-[10px] font-black uppercase tracking-[0.2em] text-gray-400 hover:text-white transition-colors">
{t('nav.myLearning')}
</Link>
<Link href="/bookmarks" className="text-[10px] font-black uppercase tracking-[0.2em] text-gray-400 hover:text-white transition-colors">
{t('nav.bookmarks')}
</Link>
</nav>
<div className="flex items-center gap-2 md:gap-4">
@@ -117,6 +120,13 @@ export default function AppHeader() {
>
{t('nav.myLearning')}
</Link>
<Link
href="/bookmarks"
onClick={() => setIsMenuOpen(false)}
className="text-sm font-black uppercase tracking-widest text-gray-300 hover:text-white border-l-2 border-transparent hover:border-blue-500 pl-4 transition-all"
>
{t('nav.bookmarks')}
</Link>
<div className="pt-6 mt-6 border-t border-white/5 space-y-4">
<div className="flex items-center gap-3 px-4 py-2 rounded-xl bg-white/5">
@@ -0,0 +1,181 @@
"use client";
import React, { useEffect, useState } from 'react';
import { lmsApi, ProgressStats } from '@/lib/api';
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
ResponsiveContainer,
AreaChart,
Area
} from 'recharts';
import { Calendar, CheckCircle2, TrendingUp, Clock, AlertTriangle } from 'lucide-react';
import { format, parseISO } from 'date-fns';
import { es } from 'date-fns/locale';
interface ProgressDashboardProps {
courseId: string;
}
const ProgressDashboard: React.FC<ProgressDashboardProps> = ({ courseId }) => {
const [stats, setStats] = useState<ProgressStats | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchStats = async () => {
try {
const data = await lmsApi.getProgressStats(courseId);
setStats(data);
} catch (err) {
console.error("Error fetching progress stats:", err);
setError("No se pudieron cargar las estadísticas de progreso.");
} finally {
setLoading(false);
}
};
fetchStats();
}, [courseId]);
if (loading) return <div className="p-8 animate-pulse space-y-4">
<div className="h-40 bg-white/5 rounded-3xl" />
<div className="h-64 bg-white/5 rounded-3xl" />
</div>;
if (error || !stats) return <div className="p-8 text-center text-red-400">
<AlertTriangle className="mx-auto mb-2" />
{error || "Error al cargar datos."}
</div>;
const chartData = stats.daily_completions.map(d => ({
date: format(parseISO(d.date), 'dd MMM', { locale: es }),
count: d.count
}));
return (
<div className="space-y-8 animate-in fade-in slide-in-from-bottom-4 duration-700">
{/* Summary Cards */}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
<div className="glass p-6 rounded-3xl border-white/5 space-y-2">
<div className="flex items-center justify-between">
<span className="text-[10px] font-black uppercase tracking-widest text-blue-400">Progreso Total</span>
<TrendingUp size={16} className="text-blue-400" />
</div>
<div className="flex items-baseline gap-2">
<span className="text-3xl font-black text-white">{Math.round(stats.progress_percentage)}%</span>
<span className="text-xs text-gray-500 font-bold uppercase tracking-widest">Completado</span>
</div>
<div className="w-full h-1.5 bg-white/10 rounded-full overflow-hidden">
<div
className="h-full bg-blue-500 shadow-[0_0_10px_rgba(59,130,246,0.5)] transition-all duration-1000"
style={{ width: `${stats.progress_percentage}%` }}
/>
</div>
</div>
<div className="glass p-6 rounded-3xl border-white/5 space-y-2">
<div className="flex items-center justify-between">
<span className="text-[10px] font-black uppercase tracking-widest text-green-400">Lecciones</span>
<CheckCircle2 size={16} className="text-green-400" />
</div>
<div className="flex items-baseline gap-2">
<span className="text-3xl font-black text-white">{stats.completed_lessons}</span>
<span className="text-xs text-gray-500 font-bold uppercase tracking-widest">de {stats.total_lessons}</span>
</div>
<p className="text-[10px] text-gray-400 font-medium">Lecciones finalizadas con éxito</p>
</div>
<div className="glass p-6 rounded-3xl border-white/5 space-y-2">
<div className="flex items-center justify-between">
<span className="text-[10px] font-black uppercase tracking-widest text-indigo-400">Predicción</span>
<Clock size={16} className="text-indigo-400" />
</div>
<div className="space-y-1">
<span className="text-sm font-black text-white block">
{stats.estimated_completion_date
? format(parseISO(stats.estimated_completion_date), "d 'de' MMMM", { locale: es })
: "N/A"
}
</span>
<span className="text-[10px] text-gray-500 font-bold uppercase tracking-widest">Fecha estimada de cierre</span>
</div>
</div>
<div className="glass p-6 rounded-3xl border-white/5 space-y-2">
<div className="flex items-center justify-between">
<span className="text-[10px] font-black uppercase tracking-widest text-purple-400">Estado</span>
<Calendar size={16} className="text-purple-400" />
</div>
<div className="space-y-1">
<span className="text-sm font-black text-white block uppercase">
{stats.progress_percentage >= 80 ? 'Excelente' : stats.progress_percentage >= 50 ? 'Buen Ritmo' : 'En Progreso'}
</span>
<span className="text-[10px] text-gray-500 font-bold uppercase tracking-widest">Según tu ritmo actual</span>
</div>
</div>
</div>
{/* Activity Chart */}
<div className="glass p-8 rounded-[2.5rem] border-white/5">
<div className="flex items-center justify-between mb-8">
<div>
<h3 className="text-lg font-black text-white tracking-tight">Actividad de Aprendizaje</h3>
<p className="text-xs text-gray-500 font-bold uppercase tracking-widest">Lecciones completadas por día (Últimos 30 días)</p>
</div>
</div>
<div className="h-[300px] w-full">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={chartData}>
<defs>
<linearGradient id="colorCount" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#3b82f6" stopOpacity={0.3} />
<stop offset="95%" stopColor="#3b82f6" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke="rgba(255,255,255,0.05)" />
<XAxis
dataKey="date"
axisLine={false}
tickLine={false}
tick={{ fill: '#6b7280', fontSize: 10, fontWeight: 900 }}
dy={10}
/>
<YAxis
hide={true}
/>
<Tooltip
contentStyle={{
backgroundColor: 'rgba(0,0,0,0.8)',
border: '1px solid rgba(255,255,255,0.1)',
borderRadius: '16px',
backdropFilter: 'blur(10px)',
fontSize: '12px',
fontWeight: 'bold'
}}
itemStyle={{ color: '#3b82f6' }}
cursor={{ stroke: 'rgba(59,130,246,0.2)', strokeWidth: 2 }}
/>
<Area
type="monotone"
dataKey="count"
stroke="#3b82f6"
strokeWidth={4}
fillOpacity={1}
fill="url(#colorCount)"
animationDuration={2000}
/>
</AreaChart>
</ResponsiveContainer>
</div>
</div>
</div>
);
};
export default ProgressDashboard;
@@ -183,7 +183,7 @@ export default function PeerReviewPlayer({ courseId, lessonId, block }: PeerRevi
>
<span className="text-2xl mb-2 block group-hover:scale-110 transition-transform">👀</span>
<div className="font-bold text-purple-400">Review a Peer</div>
<div className="text-xs text-gray-500 mt-1">Earn credit by reviewing other students' work.</div>
<div className="text-xs text-gray-500 mt-1">Earn credit by reviewing other students&apos; work.</div>
</button>
<button
+45 -1
View File
@@ -105,6 +105,16 @@ export interface Block {
metadata?: any;
}
export interface CourseInstructor {
id: string;
course_id: string;
user_id: string;
role: 'primary' | 'instructor' | 'assistant';
created_at: string;
email: string;
full_name: string;
}
export interface Lesson {
id: string;
module_id: string;
@@ -127,6 +137,7 @@ export interface Lesson {
position: number;
due_date?: string;
important_date_type?: 'exam' | 'assignment' | 'milestone' | 'live-session';
is_previewable: boolean;
created_at: string;
}
@@ -199,6 +210,28 @@ export interface Notification {
created_at: string;
}
export interface DailyProgress {
date: string;
count: number;
}
export interface UserBookmark {
id: string;
organization_id: string;
user_id: string;
course_id: string;
lesson_id: string;
created_at: string;
}
export interface ProgressStats {
total_lessons: number;
completed_lessons: number;
progress_percentage: number;
daily_completions: DailyProgress[];
estimated_completion_date?: string;
}
export interface AuthResponse {
user: User;
token: string;
@@ -393,6 +426,7 @@ export const lmsApi = {
modules: Module[],
grading_categories: GradingCategory[],
organization: Organization,
instructors?: CourseInstructor[],
dependencies?: LessonDependency[]
}> {
return apiFetch(`/courses/${courseId}/outline`);
@@ -417,7 +451,7 @@ export const lmsApi = {
},
async getMe(): Promise<User> {
return apiFetch('/auth/me', {}, true); // isCMS = true
return apiFetch('/auth/me', {}, false);
},
initSSOLogin(orgId: string): void {
@@ -663,4 +697,14 @@ export const lmsApi = {
async getMySubmissionFeedback(courseId: string, lessonId: string): Promise<PeerReview[]> {
return apiFetch(`/courses/${courseId}/lessons/${lessonId}/feedback`);
},
async getProgressStats(courseId: string): Promise<ProgressStats> {
return apiFetch(`/courses/${courseId}/progress-stats`);
},
async toggleBookmark(lessonId: string): Promise<void> {
return apiFetch(`/lessons/${lessonId}/bookmark`, { method: 'POST' });
},
async getBookmarks(courseId?: string): Promise<UserBookmark[]> {
const query = courseId ? `?cohort_id=${courseId}` : '';
return apiFetch(`/bookmarks${query}`);
}
};
+1
View File
@@ -10,6 +10,7 @@
"nav": {
"catalog": "Catalog",
"myLearning": "My Learning",
"bookmarks": "Bookmarks",
"profile": "Profile",
"signOut": "Sign Out"
},
+1
View File
@@ -10,6 +10,7 @@
"nav": {
"catalog": "Catálogo",
"myLearning": "Mi Aprendizaje",
"bookmarks": "Marcadores",
"profile": "Perfil",
"signOut": "Cerrar Sesión"
},
+1
View File
@@ -10,6 +10,7 @@
"nav": {
"catalog": "Catálogo",
"myLearning": "Meu Aprendizado",
"bookmarks": "Favoritos",
"profile": "Perfil",
"signOut": "Sair"
},