This commit is contained in:
Marcelo
2026-02-17 00:07:00 +00:00
parent b7a86a2d1c
commit be4ca2ed78
92 changed files with 6850 additions and 1188 deletions

View File

@@ -0,0 +1,386 @@
"use server";
import { db } from "@/lib/prisma";
import { requireTeacher } from "@/lib/auth/requireTeacher";
import { z } from "zod";
import { revalidatePath } from "next/cache";
import { ContentStatus, Prisma, ProficiencyLevel } from "@prisma/client";
// --- VALIDATION SCHEMAS (Zod) ---
const createCourseSchema = z.object({
title: z.string().min(3, "El título debe tener al menos 3 caracteres"),
});
// --- ACTIONS ---
/**
* 1. LIST COURSES
* Used by: app/(protected)/teacher/page.tsx (Dashboard)
*/
export async function getTeacherCourses() {
const user = await requireTeacher();
if (!user) {
return { success: false, error: "No autorizado" };
}
try {
const courses = await db.course.findMany({
where: {
authorId: user.id,
},
orderBy: {
updatedAt: "desc",
},
select: {
id: true,
title: true,
slug: true,
price: true,
status: true,
level: true,
_count: {
select: {
modules: true,
enrollments: true,
}
}
}
});
return { success: true, data: courses };
} catch (error) {
console.error("Error fetching courses:", error);
return { success: false, error: "Error al cargar los cursos" };
}
}
/**
* 2. CREATE COURSE (Draft) */
export async function createCourse(formData: FormData) {
const user = await requireTeacher();
if (!user) {
return { success: false, error: "No autorizado" };
}
// 1. Extract & Validate
const rawTitle = formData.get("title");
const validated = createCourseSchema.safeParse({ title: rawTitle });
if (!validated.success) {
return { success: false, error: validated.error.flatten().fieldErrors.title?.[0] || "Error en el título" };
}
const title = validated.data.title;
// 2. Generate basic slug
const slug = `${title.toLowerCase().replace(/ /g, "-").replace(/[^\w-]/g, "")}-${Math.floor(Math.random() * 10000)}`;
try {
// 3. Create DB Record
const course = await db.course.create({
data: {
title: title,
slug: slug,
authorId: user.id,
description: "Descripción pendiente...",
status: "DRAFT",
},
});
// 4. Revalidate & Return
revalidatePath("/teacher/courses");
return { success: true, data: course };
} catch (error) {
console.error("Create course error:", error);
return { success: false, error: "No se pudo crear el curso." };
}
}
/**
* 3. DELETE COURSE */
export async function deleteCourse(courseId: string) {
const user = await requireTeacher();
if (!user) return { success: false, error: "No autorizado" };
try {
const course = await db.course.findUnique({
where: { id: courseId },
select: { authorId: true }
});
if (!course || course.authorId !== user.id) {
return { success: false, error: "No tienes permiso para eliminar este curso." };
}
await db.course.delete({
where: { id: courseId },
});
revalidatePath("/teacher/courses");
return { success: true, data: "Curso eliminado" };
} catch {
return { success: false, error: "Error al eliminar el curso" };
}
}
export async function updateCourse(courseId: string, courseSlug: string, formData: FormData) {
const user = await requireTeacher();
if (!user) return { success: false, error: "Unauthorized" };
try {
const title = formData.get("title") as string;
const summary = formData.get("summary") as string;
// Direct cast is okay if you trust the select/input values
const level = formData.get("level") as ProficiencyLevel;
const status = formData.get("status") as ContentStatus;
const price = parseFloat(formData.get("price") as string) || 0;
await db.course.update({
where: { id: courseId, authorId: user.id },
data: {
title,
description: summary,
level,
status,
price,
},
});
// Revalidate both the list and the editor (edit route uses slug, not id)
revalidatePath("/teacher/courses");
revalidatePath(`/teacher/courses/${courseSlug}/edit`, "page");
return { success: true };
} catch {
return { success: false, error: "Failed to update" };
}
}
export async function updateLesson(lessonId: string, data: {
title?: string;
description?: Prisma.InputJsonValue | null;
videoUrl?: string;
isPublished?: boolean; // optional: for later
}) {
const user = await requireTeacher();
if (!user) return { success: false, error: "Unauthorized" };
try {
const updateData: Prisma.LessonUpdateInput = { updatedAt: new Date() };
if (data.title !== undefined) updateData.title = data.title;
if (data.description !== undefined) updateData.description = data.description === null ? Prisma.JsonNull : data.description;
if (data.videoUrl !== undefined) updateData.videoUrl = data.videoUrl;
await db.lesson.update({
where: { id: lessonId },
data: updateData,
});
// 2. Revalidate to show changes immediately
revalidatePath("/teacher/courses");
return { success: true };
} catch (error) {
console.error("Update Lesson Error:", error);
return { success: false, error: "Failed to update lesson" };
}
}
export async function createModule(courseId: string) {
const user = await requireTeacher();
if (!user) return { success: false, error: "Unauthorized" };
try {
// Find the highest orderIndex so we can put the new one at the end
const lastModule = await db.module.findFirst({
where: { courseId },
orderBy: { orderIndex: "desc" },
});
const newOrder = lastModule ? lastModule.orderIndex + 1 : 0;
await db.module.create({
data: {
courseId,
title: "Nuevo Módulo", // Default title
orderIndex: newOrder,
},
});
revalidatePath(`/teacher/courses/${courseId}/edit`, "page");
return { success: true };
} catch (error) {
console.error("Create Module Error:", error);
return { success: false, error: "Failed to create module" };
}
}
// 2. CREATE LESSON
export async function createLesson(moduleId: string) {
const user = await requireTeacher();
if (!user) return { success: false, error: "Unauthorized" };
try {
// Find the highest orderIndex for lessons in this module
const lastLesson = await db.lesson.findFirst({
where: { moduleId },
orderBy: { orderIndex: "desc" },
});
const newOrder = lastLesson ? lastLesson.orderIndex + 1 : 0;
// Create the lesson with default values
const lesson = await db.lesson.create({
data: {
moduleId,
title: "Nueva Lección",
orderIndex: newOrder,
estimatedDuration: 0,
version: 1,
// The type field is required in your schema (based on previous context)
// If you have a 'type' enum, set a default like 'VIDEO' or 'TEXT'
// type: "VIDEO",
},
});
revalidatePath(`/teacher/courses/${moduleId}/edit`, "page");
return { success: true, lessonId: lesson.id };
} catch (error) {
console.error("Create Lesson Error:", error);
return { success: false, error: "Failed to create lesson" };
}
}
/**
* DELETE MODULE
* Also deletes all lessons inside it due to Prisma cascade or manual cleanup
*/
export async function deleteModule(moduleId: string) {
const user = await requireTeacher();
if (!user) return { success: false, error: "Unauthorized" };
try {
await db.module.delete({
where: {
id: moduleId,
course: { authorId: user.id } // Security: ownership check
},
});
revalidatePath("/teacher/courses");
return { success: true };
} catch {
return { success: false, error: "No se pudo eliminar el módulo" };
}
}
/**
* DELETE LESSON
*/
export async function deleteLesson(lessonId: string) {
const user = await requireTeacher();
if (!user) return { success: false, error: "Unauthorized" };
try {
await db.lesson.delete({
where: {
id: lessonId,
module: { course: { authorId: user.id } } // Deep ownership check
},
});
revalidatePath("/teacher/courses");
return { success: true };
} catch {
return { success: false, error: "No se pudo eliminar la lección" };
}
}
export async function reorderModules(moduleId: string, direction: 'up' | 'down') {
const user = await requireTeacher();
if (!user) return { success: false, error: "Unauthorized" };
const currentModule = await db.module.findUnique({
where: { id: moduleId },
include: { course: true }
});
if (!currentModule || currentModule.course.authorId !== user.id) {
return { success: false, error: "Module not found" };
}
const siblingModule = await db.module.findFirst({
where: {
courseId: currentModule.courseId,
orderIndex: direction === 'up'
? { lt: currentModule.orderIndex }
: { gt: currentModule.orderIndex }
},
orderBy: { orderIndex: direction === 'up' ? 'desc' : 'asc' }
});
if (!siblingModule) return { success: true }; // Already at the top/bottom
// Swap orderIndex values
await db.$transaction([
db.module.update({
where: { id: currentModule.id },
data: { orderIndex: siblingModule.orderIndex }
}),
db.module.update({
where: { id: siblingModule.id },
data: { orderIndex: currentModule.orderIndex }
})
]);
revalidatePath(`/teacher/courses/${currentModule.course.slug}/edit`, "page");
return { success: true };
}
/**
* Reorder lessons within the same module (swap orderIndex with sibling)
*/
export async function reorderLessons(lessonId: string, direction: "up" | "down") {
const user = await requireTeacher();
if (!user) return { success: false, error: "Unauthorized" };
const currentLesson = await db.lesson.findUnique({
where: { id: lessonId },
include: { module: { include: { course: true } } },
});
if (!currentLesson || currentLesson.module.course.authorId !== user.id) {
return { success: false, error: "Lesson not found" };
}
const siblingLesson = await db.lesson.findFirst({
where: {
moduleId: currentLesson.moduleId,
orderIndex:
direction === "up"
? { lt: currentLesson.orderIndex }
: { gt: currentLesson.orderIndex },
},
orderBy: { orderIndex: direction === "up" ? "desc" : "asc" },
});
if (!siblingLesson) return { success: true }; // Already at top/bottom
await db.$transaction([
db.lesson.update({
where: { id: currentLesson.id },
data: { orderIndex: siblingLesson.orderIndex },
}),
db.lesson.update({
where: { id: siblingLesson.id },
data: { orderIndex: currentLesson.orderIndex },
}),
]);
revalidatePath(`/teacher/courses/${currentLesson.module.course.slug}/edit`, "page");
return { success: true };
}

42
app/(protected)/teacher/courses/[slug]/edit/page.tsx Normal file → Executable file
View File

@@ -1,13 +1,41 @@
import { db } from "@/lib/prisma";
import { requireTeacher } from "@/lib/auth/requireTeacher";
import { notFound, redirect } from "next/navigation";
import TeacherEditCourseForm from "@/components/teacher/TeacherEditCourseForm";
type TeacherEditCoursePageProps = {
params: Promise<{ slug: string }>;
};
export default async function CourseEditPage({ params }: { params: Promise<{ slug: string }> }) {
const user = await requireTeacher();
if (!user) redirect("/auth/login");
export default async function TeacherEditCoursePage({ params }: TeacherEditCoursePageProps) {
await requireTeacher();
const { slug } = await params;
return <TeacherEditCourseForm slug={slug} />;
}
// Fetch Course + Modules + Lessons
const course = await db.course.findUnique({
where: { slug: slug },
include: {
modules: {
orderBy: { orderIndex: "asc" },
include: {
lessons: {
orderBy: { orderIndex: "asc" },
},
},
},
},
});
if (!course) notFound();
// Security Check
if (course.authorId !== user.id && user.role !== "SUPER_ADMIN") {
return <div>No autorizado</div>;
}
// Transform Decimal to number for the UI component
const courseData = {
...course,
price: course.price.toNumber(),
};
return <TeacherEditCourseForm course={courseData} />;
}

View File

@@ -0,0 +1,120 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { updateLesson } from "@/app/(protected)/teacher/actions";
import VideoUpload from "@/components/teacher/VideoUpload"; // The component you created earlier
interface LessonEditorFormProps {
lesson: {
id: string;
title: string;
description?: string | null;
videoUrl?: string | null;
};
courseSlug: string;
}
export function LessonEditorForm({ lesson, courseSlug }: LessonEditorFormProps) {
const router = useRouter();
const [loading, setLoading] = useState(false);
const [title, setTitle] = useState(lesson.title);
const [description, setDescription] = useState(lesson.description ?? "");
// 1. Auto-save Video URL when upload finishes
const handleVideoUploaded = async (url: string) => {
toast.loading("Guardando video...");
const res = await updateLesson(lesson.id, { videoUrl: url });
if (res.success) {
toast.dismiss();
toast.success("Video guardado correctamente");
router.refresh(); // Update the UI to show the new video player
} else {
toast.error("Error al guardar el video en la base de datos");
}
};
// 2. Save Text Changes (Title/Desc)
const handleSave = async () => {
setLoading(true);
const res = await updateLesson(lesson.id, { title, description });
if (res.success) {
toast.success("Cambios guardados");
router.refresh();
} else {
toast.error("Error al guardar cambios");
}
setLoading(false);
};
return (
<div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
{/* LEFT: Video & Content */}
<div className="lg:col-span-2 space-y-6">
{/* Video Upload Section */}
<section className="bg-white rounded-xl border border-slate-200 shadow-sm overflow-hidden">
<div className="p-6 border-b border-slate-100">
<h2 className="font-semibold text-slate-900">Video del Curso</h2>
<p className="text-sm text-slate-500">Sube el video principal de esta lección.</p>
</div>
<div className="p-6 bg-slate-50/50">
<VideoUpload
lessonId={lesson.id}
currentVideoUrl={lesson.videoUrl}
onUploadComplete={handleVideoUploaded}
/>
</div>
</section>
{/* Text Content */}
<section className="bg-white rounded-xl border border-slate-200 shadow-sm p-6 space-y-4">
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Título de la Lección</label>
<input
value={title}
onChange={(e) => setTitle(e.target.value)}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
/>
</div>
<div>
<label className="block text-sm font-medium text-slate-700 mb-1">Descripción / Notas</label>
<textarea
rows={6}
value={description}
onChange={(e) => setDescription(e.target.value)}
className="w-full rounded-md border border-slate-300 px-3 py-2 outline-none focus:border-black"
placeholder="Escribe aquí el contenido de la lección..."
/>
</div>
</section>
</div>
{/* RIGHT: Settings / Actions */}
<div className="space-y-6">
<div className="bg-white rounded-xl border border-slate-200 shadow-sm p-6">
<h3 className="font-semibold text-slate-900 mb-4">Acciones</h3>
<button
onClick={handleSave}
disabled={loading}
className="w-full bg-black text-white rounded-lg py-2.5 font-medium hover:bg-slate-800 disabled:opacity-50 transition-colors"
>
{loading ? "Guardando..." : "Guardar Cambios"}
</button>
<button
onClick={() => router.push(`/teacher/courses/${courseSlug}/edit`)}
className="w-full mt-3 bg-white border border-slate-300 text-slate-700 rounded-lg py-2.5 font-medium hover:bg-slate-50 transition-colors"
>
Volver al Curso
</button>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,73 @@
import { db } from "@/lib/prisma";
import { requireTeacher } from "@/lib/auth/requireTeacher";
import { redirect, notFound } from "next/navigation";
import Link from "next/link";
import { LessonEditorForm } from "./LessonEditorForm";
function getText(value: unknown): string {
if (!value) return "";
if (typeof value === "string") return value;
if (typeof value === "object") {
const text = value as Record<string, string>;
return text.es || text.en || "";
}
return "";
}
interface PageProps {
params: Promise<{ slug: string; lessonId: string }>;
}
export default async function LessonPage({ params }: PageProps) {
const user = await requireTeacher();
if (!user) redirect("/auth/login");
const { slug, lessonId } = await params;
// 1. Fetch Lesson + Course Info (for breadcrumbs)
const lesson = await db.lesson.findUnique({
where: { id: lessonId },
include: {
module: {
include: {
course: {
select: { title: true, slug: true, authorId: true }
}
}
}
}
});
// 2. Security & Null Checks
if (!lesson) notFound();
if (lesson.module.course.authorId !== user.id) redirect("/teacher");
return (
<div className="max-w-4xl mx-auto p-6">
{/* Breadcrumbs */}
<div className="flex items-center gap-2 text-sm text-slate-500 mb-6">
<Link href="/teacher" className="hover:text-black">Cursos</Link>
<span>/</span>
<Link href={`/teacher/courses/${slug}/edit`} className="hover:text-black">
{getText(lesson.module.course.title)}
</Link>
<span>/</span>
<span className="text-slate-900 font-medium">{getText(lesson.title)}</span>
</div>
<div className="flex items-center justify-between mb-8">
<h1 className="text-3xl font-bold text-slate-900">Editar Lección</h1>
</div>
{/* The Client Form */}
<LessonEditorForm
lesson={{
...lesson,
title: getText(lesson.title),
description: getText(lesson.description),
}}
courseSlug={slug}
/>
</div>
);
}

View File

View File

@@ -0,0 +1,14 @@
import { redirect } from "next/navigation";
interface PageProps {
params: Promise<{ slug: string }>;
}
export default async function CourseDashboardPage({ params }: PageProps) {
// 1. Get the slug from the URL
const { slug } = await params;
// 2. Automatically redirect to the Edit page
// This saves us from building a separate "Stats" page for now
redirect(`/teacher/courses/${slug}/edit`);
}

0
app/(protected)/teacher/courses/new/page.tsx Normal file → Executable file
View File

108
app/(protected)/teacher/page.tsx Normal file → Executable file
View File

@@ -1,7 +1,107 @@
export const dynamic = 'force-dynamic';
import { getTeacherCourses } from "./actions"; // Import the server action
import Link from "next/link";
import { redirect } from "next/navigation";
import { requireTeacher } from "@/lib/auth/requireTeacher";
import TeacherDashboardClient from "@/components/teacher/TeacherDashboardClient";
import { logger } from "@/lib/logger";
export default async function TeacherDashboardPage() {
await requireTeacher();
return <TeacherDashboardClient />;
}
try {
// 1. Auth Check (Double protection)
// We log the attempt
logger.info("Accessing Teacher Dashboard");
// We wrap requireTeacher to catch potential DB/Supabase connection errors
let user;
try {
user = await requireTeacher();
} catch (authError) {
logger.error("requireTeacher failed with exception", authError);
throw authError;
}
if (!user) {
logger.info("User not authorized as teacher, redirecting");
redirect("/login");
}
// 2. Fetch Data
const { success, data: courses, error } = await getTeacherCourses();
return (
<div className="p-6 max-w-7xl mx-auto">
{/* Header */}
<div className="flex items-center justify-between mb-8">
<div>
<h1 className="text-2xl font-bold tracking-tight">Panel del Profesor</h1>
<p className="text-gray-500">Gestiona tus cursos y contenidos.</p>
</div>
<Link
href="/teacher/courses/new"
className="bg-black text-white px-4 py-2 rounded-md hover:bg-gray-800 transition-colors"
>
+ Nuevo Curso
</Link>
</div>
{/* Error State */}
{!success && (
<div className="bg-red-50 text-red-600 p-4 rounded-md border border-red-100">
Error: {error}
</div>
)}
{/* List State */}
{success && courses && (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{courses.length === 0 ? (
// Empty State
<div className="col-span-full text-center py-12 border-2 border-dashed border-gray-200 rounded-lg">
<h3 className="mt-2 text-sm font-semibold text-gray-900">No hay cursos</h3>
<p className="mt-1 text-sm text-gray-500">Empieza creando tu primer curso de Inglés Jurídico.</p>
</div>
) : (
// Course Cards
courses.map((course) => (
<Link
key={course.id}
href={`/teacher/courses/${course.slug}`}
className="block group"
>
<div className="border border-gray-200 rounded-lg p-5 hover:border-black transition-all bg-white shadow-sm hover:shadow-md">
<div className="flex justify-between items-start mb-4">
<span className={`text-xs font-medium px-2 py-1 rounded-full ${course.status === 'PUBLISHED' ? 'bg-green-100 text-green-700' : 'bg-yellow-100 text-yellow-700'
}`}>
{course.status === 'PUBLISHED' ? 'Publicado' : 'Borrador'}
</span>
<span className="text-sm font-bold text-gray-900">
${course.price.toString()}
</span>
</div>
<h3 className="font-semibold text-lg text-gray-900 group-hover:text-blue-600 mb-1">
{course.title as string}
</h3>
<p className="text-sm text-gray-500 mb-4">
{course.level}
</p>
<div className="flex items-center gap-4 text-xs text-gray-500 border-t pt-4">
<span>📚 {course._count.modules} Módulos</span>
<span>👥 {course._count.enrollments} Alumnos</span>
</div>
</div>
</Link>
))
)}
</div>
)}
</div>
);
} catch (error) {
logger.error("Critical error in TeacherDashboardPage", error);
throw error;
}
}

View File

@@ -0,0 +1,7 @@
import { requireTeacher } from "@/lib/auth/requireTeacher";
import TeacherUploadsLibraryClient from "@/components/teacher/TeacherUploadsLibraryClient";
export default async function TeacherUploadsPage() {
await requireTeacher();
return <TeacherUploadsLibraryClient />;
}