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,92 @@
"use server";
import { revalidatePath } from "next/cache";
import { requireUser } from "@/lib/auth/requireUser";
import { db } from "@/lib/prisma";
type ToggleLessonCompleteInput = {
courseSlug: string;
lessonId: string;
};
export async function toggleLessonComplete({ courseSlug, lessonId }: ToggleLessonCompleteInput) {
const user = await requireUser();
if (!user?.id) {
return { success: false, error: "Unauthorized" };
}
const lesson = await db.lesson.findUnique({
where: { id: lessonId },
select: {
id: true,
module: {
select: {
courseId: true,
course: {
select: {
slug: true,
},
},
},
},
},
});
if (!lesson || lesson.module.course.slug !== courseSlug) {
return { success: false, error: "Lesson not found" };
}
const enrollment = await db.enrollment.findUnique({
where: {
userId_courseId: {
userId: user.id,
courseId: lesson.module.courseId,
},
},
select: { id: true },
});
if (!enrollment) {
return { success: false, error: "Not enrolled in this course" };
}
const existingProgress = await db.userProgress.findUnique({
where: {
userId_lessonId: {
userId: user.id,
lessonId,
},
},
select: {
id: true,
isCompleted: true,
},
});
const nextCompleted = !existingProgress?.isCompleted;
if (existingProgress) {
await db.userProgress.update({
where: { id: existingProgress.id },
data: {
isCompleted: nextCompleted,
finishedAt: nextCompleted ? new Date() : null,
lastPlayedAt: new Date(),
},
});
} else {
await db.userProgress.create({
data: {
userId: user.id,
lessonId,
isCompleted: true,
finishedAt: new Date(),
},
});
}
revalidatePath(`/courses/${courseSlug}/learn`);
return { success: true, isCompleted: nextCompleted };
}

304
app/(protected)/courses/[slug]/learn/page.tsx Normal file → Executable file
View File

@@ -1,214 +1,130 @@
"use client";
import { notFound, redirect } from "next/navigation";
import { db } from "@/lib/prisma";
import { requireUser } from "@/lib/auth/requireUser";
import StudentClassroomClient from "@/components/courses/StudentClassroomClient";
import { useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import LessonRow from "@/components/LessonRow";
import ProgressBar from "@/components/ProgressBar";
import { getCourseBySlug } from "@/lib/data/courseCatalog";
import {
getCourseProgress,
getCourseProgressPercent,
markLessonComplete,
setLastLesson,
} from "@/lib/progress/localProgress";
import { teacherCoursesUpdatedEventName } from "@/lib/data/teacherCourses";
import { supabaseBrowser } from "@/lib/supabase/browser";
import type { Course, Lesson } from "@/types/course";
const lessonContent = (lesson: Lesson) => {
if (lesson.type === "video") {
return (
<div className="space-y-3">
<div className="aspect-video rounded-2xl border border-slate-300 bg-[#f6f6f7] p-4">
<div className="flex h-full items-center justify-center rounded-xl border-2 border-dashed border-slate-300 text-lg text-slate-500">
Video placeholder ({lesson.minutes} min)
</div>
</div>
{lesson.videoUrl ? (
<p className="text-sm text-slate-500">
Demo video URL: <span className="font-medium text-slate-700">{lesson.videoUrl}</span>
</p>
) : null}
</div>
);
function getText(value: unknown): string {
if (!value) return "";
if (typeof value === "string") return value;
if (typeof value === "object") {
const record = value as Record<string, unknown>;
if (typeof record.es === "string") return record.es;
if (typeof record.en === "string") return record.en;
}
return "";
}
if (lesson.type === "reading") {
return (
<div className="rounded-2xl border border-slate-300 bg-white p-5">
<p className="text-lg leading-9 text-slate-700">
Reading placeholder content for lesson: {lesson.title}. Replace with full lesson text and references in Phase 2.
</p>
</div>
);
}
return (
<div className="rounded-2xl border border-slate-300 bg-white p-5">
<p className="text-lg text-slate-700">Interactive placeholder for lesson: {lesson.title}.</p>
<button className="acve-button-secondary mt-3 px-3 py-1.5 text-sm" type="button">
Start interactive
</button>
</div>
);
type PageProps = {
params: Promise<{ slug: string }>;
searchParams: Promise<{ lesson?: string }>;
};
export default function CourseLearnPage() {
const params = useParams<{ slug: string }>();
const slug = params.slug;
const [course, setCourse] = useState<Course | undefined>(() => getCourseBySlug(slug));
const [hasResolvedCourse, setHasResolvedCourse] = useState(false);
export default async function CourseLearnPage({ params, searchParams }: PageProps) {
const { slug } = await params;
const { lesson: requestedLessonId } = await searchParams;
const [userId, setUserId] = useState("guest");
const [isAuthed, setIsAuthed] = useState(false);
const [selectedLessonId, setSelectedLessonId] = useState<string | null>(null);
const [completedLessonIds, setCompletedLessonIds] = useState<string[]>([]);
const [progress, setProgress] = useState(0);
useEffect(() => {
const loadCourse = () => {
setCourse(getCourseBySlug(slug));
setHasResolvedCourse(true);
};
loadCourse();
window.addEventListener(teacherCoursesUpdatedEventName, loadCourse);
return () => window.removeEventListener(teacherCoursesUpdatedEventName, loadCourse);
}, [slug]);
useEffect(() => {
const client = supabaseBrowser();
if (!client) return;
client.auth.getUser().then(({ data }) => {
setUserId(data.user?.id ?? "guest");
setIsAuthed(Boolean(data.user));
});
const { data } = client.auth.onAuthStateChange((_event, session) => {
setUserId(session?.user?.id ?? "guest");
setIsAuthed(Boolean(session?.user));
});
return () => data.subscription.unsubscribe();
}, []);
useEffect(() => {
if (!course) return;
const progressState = getCourseProgress(userId, course.slug);
const fallback = course.lessons[0]?.id ?? null;
setSelectedLessonId(progressState.lastLessonId ?? fallback);
setCompletedLessonIds(progressState.completedLessonIds);
setProgress(getCourseProgressPercent(userId, course.slug, course.lessons.length));
}, [course, userId]);
const completionSet = new Set(completedLessonIds);
if (!course && !hasResolvedCourse) {
return (
<div className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
<p className="text-slate-600">Loading course...</p>
</div>
);
const user = await requireUser();
if (!user?.id) {
redirect(`/courses/${slug}`);
}
const course = await db.course.findUnique({
where: { slug },
select: {
id: true,
slug: true,
title: true,
price: true,
modules: {
orderBy: { orderIndex: "asc" },
select: {
id: true,
title: true,
lessons: {
orderBy: { orderIndex: "asc" },
select: {
id: true,
title: true,
description: true,
videoUrl: true,
estimatedDuration: true,
},
},
},
},
},
});
if (!course) {
return (
<div className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
<h1 className="text-2xl font-bold text-slate-900">Course not found</h1>
<p className="mt-2 text-slate-600">The requested course slug does not exist in mock data.</p>
<Link className="mt-4 inline-flex rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white" href="/courses">
Back to courses
</Link>
</div>
);
notFound();
}
const selectedLesson =
course.lessons.find((lesson) => lesson.id === selectedLessonId) ?? course.lessons[0];
let enrollment = await db.enrollment.findUnique({
where: {
userId_courseId: {
userId: user.id,
courseId: course.id,
},
},
select: { id: true },
});
if (!selectedLesson) {
return (
<div className="rounded-xl border border-slate-200 bg-white p-6 shadow-sm">
<h1 className="text-2xl font-bold text-slate-900">No lessons available</h1>
<p className="mt-2 text-slate-600">This course currently has no lessons configured.</p>
<Link className="mt-4 inline-flex rounded-md bg-ink px-4 py-2 text-sm font-semibold text-white" href={`/courses/${course.slug}`}>
Back to course
</Link>
</div>
);
if (!enrollment) {
const isFree = Number(course.price) === 0;
if (isFree) {
enrollment = await db.enrollment.create({
data: {
userId: user.id,
courseId: course.id,
amountPaid: 0,
},
select: { id: true },
});
} else {
redirect(`/courses/${slug}`);
}
}
const isLocked = (lesson: Lesson) => !lesson.isPreview && !isAuthed;
const completedProgress = await db.userProgress.findMany({
where: {
userId: user.id,
isCompleted: true,
lesson: {
module: {
courseId: course.id,
},
},
},
select: {
lessonId: true,
},
});
const onSelectLesson = (lesson: Lesson) => {
if (isLocked(lesson)) return;
setSelectedLessonId(lesson.id);
setLastLesson(userId, course.slug, lesson.id);
};
const modules = course.modules.map((module) => ({
id: module.id,
title: getText(module.title) || "Untitled module",
lessons: module.lessons.map((lesson) => ({
id: lesson.id,
title: getText(lesson.title) || "Untitled lesson",
description: getText(lesson.description),
videoUrl: lesson.videoUrl,
estimatedDuration: lesson.estimatedDuration,
})),
}));
const onMarkComplete = () => {
if (!selectedLesson) return;
markLessonComplete(userId, course.slug, selectedLesson.id);
const progressState = getCourseProgress(userId, course.slug);
setCompletedLessonIds(progressState.completedLessonIds);
setProgress(getCourseProgressPercent(userId, course.slug, course.lessons.length));
};
const flattenedLessonIds = modules.flatMap((module) => module.lessons.map((lesson) => lesson.id));
const initialSelectedLessonId =
requestedLessonId && flattenedLessonIds.includes(requestedLessonId)
? requestedLessonId
: flattenedLessonIds[0] ?? "";
return (
<div className="space-y-6">
<header className="acve-panel p-6">
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<Link className="inline-flex items-center gap-2 text-base text-slate-600 hover:text-brand md:text-xl" href={`/courses/${course.slug}`}>
<span className="text-base">{"<-"}</span>
Back to Course
</Link>
<h1 className="mt-2 text-3xl text-[#222b39] md:text-5xl">Course Content</h1>
</div>
<div className="min-w-[240px]">
<ProgressBar value={progress} label={`${progress}% complete`} />
</div>
</div>
</header>
<section className="space-y-3">
{course.lessons.map((lesson, index) => (
<div key={lesson.id} className="space-y-1">
<LessonRow
index={index}
isActive={lesson.id === selectedLesson?.id}
isLocked={isLocked(lesson)}
lesson={lesson}
onSelect={() => onSelectLesson(lesson)}
/>
{completionSet.has(lesson.id) ? (
<p className="pl-2 text-sm font-medium text-[#2f9d73]">Completed</p>
) : null}
</div>
))}
</section>
<section className="acve-panel space-y-4 p-6">
<div className="flex items-start justify-between gap-4">
<div>
<h2 className="text-2xl text-[#222b39] md:text-4xl">{selectedLesson.title}</h2>
<p className="mt-1 text-base text-slate-600">
{selectedLesson.type} | {selectedLesson.minutes} min
</p>
</div>
<button
className="acve-button-primary px-4 py-2 text-sm font-semibold hover:brightness-105"
onClick={onMarkComplete}
type="button"
>
Mark complete
</button>
</div>
{lessonContent(selectedLesson)}
</section>
</div>
<StudentClassroomClient
courseSlug={course.slug}
courseTitle={getText(course.title) || "Untitled course"}
modules={modules}
initialSelectedLessonId={initialSelectedLessonId}
initialCompletedLessonIds={completedProgress.map((progress) => progress.lessonId)}
/>
);
}

View File

@@ -0,0 +1,47 @@
import Link from "next/link";
import { requireUser } from "@/lib/auth/requireUser";
export default async function OrgDashboardPage() {
await requireUser();
return (
<div className="space-y-6">
<header className="acve-panel p-6">
<h1 className="text-3xl font-bold text-slate-900">Organization Dashboard (Placeholder)</h1>
<p className="mt-2 text-slate-600">
Org admin tools are frontend placeholders for seat management, usage analytics, and assignment flows.
</p>
<p className="mt-3 inline-flex rounded-md border border-amber-300 bg-amber-50 px-3 py-1 text-sm font-semibold text-amber-900">
Org admin only (access model pending backend)
</p>
</header>
<section className="grid gap-4 md:grid-cols-3">
<article className="acve-panel p-4">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Seats</p>
<p className="mt-2 text-2xl font-semibold text-slate-900">12 / 20 used</p>
</article>
<article className="acve-panel p-4">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Active learners</p>
<p className="mt-2 text-2xl font-semibold text-slate-900">9</p>
</article>
<article className="acve-panel p-4">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Courses assigned</p>
<p className="mt-2 text-2xl font-semibold text-slate-900">4</p>
</article>
</section>
<section className="acve-panel p-6">
<h2 className="text-xl font-semibold text-slate-900">Assignment Queue (Placeholder)</h2>
<ul className="mt-3 space-y-2 text-sm text-slate-700">
<li className="rounded-md border border-slate-200 px-3 py-2">Assign &quot;Contract Analysis Practice&quot; to Team A (disabled)</li>
<li className="rounded-md border border-slate-200 px-3 py-2">Invite 3 learners to &quot;Legal English Foundations&quot; (disabled)</li>
<li className="rounded-md border border-slate-200 px-3 py-2">Export monthly progress report (disabled)</li>
</ul>
<Link className="mt-4 inline-flex rounded-md border border-slate-300 px-3 py-2 text-sm hover:bg-slate-50" href="/">
Back to home
</Link>
</section>
</div>
);
}

194
app/(protected)/practice/[slug]/page.tsx Normal file → Executable file
View File

@@ -1,19 +1,49 @@
"use client";
import { useState } from "react";
import { useEffect, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import ProgressBar from "@/components/ProgressBar";
import { getPracticeBySlug, mockPracticeModules } from "@/lib/data/mockPractice";
const attemptsKey = (slug: string) => `acve.practice-attempts.${slug}`;
type AttemptRecord = {
completedAt: string;
score: number;
total: number;
};
export default function PracticeExercisePage() {
const params = useParams<{ slug: string }>();
const practiceModule = getPracticeBySlug(params.slug);
const [started, setStarted] = useState(false);
const [index, setIndex] = useState(0);
const [score, setScore] = useState(0);
const [finished, setFinished] = useState(false);
const [selected, setSelected] = useState<number | null>(null);
const [attempts, setAttempts] = useState<AttemptRecord[]>([]);
const loadAttempts = () => {
if (!practiceModule) return;
if (typeof window === "undefined") return;
const raw = window.localStorage.getItem(attemptsKey(practiceModule.slug));
if (!raw) {
setAttempts([]);
return;
}
try {
setAttempts(JSON.parse(raw) as AttemptRecord[]);
} catch {
setAttempts([]);
}
};
useEffect(() => {
loadAttempts();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [practiceModule?.slug]);
if (!practiceModule) {
return (
@@ -50,6 +80,20 @@ export default function PracticeExercisePage() {
const next = () => {
if (index + 1 >= total) {
if (typeof window !== "undefined") {
const raw = window.localStorage.getItem(attemptsKey(practiceModule.slug));
const parsed = raw ? ((JSON.parse(raw) as AttemptRecord[]) ?? []) : [];
const nextAttempts = [
{
completedAt: new Date().toISOString(),
score,
total,
},
...parsed,
].slice(0, 5);
window.localStorage.setItem(attemptsKey(practiceModule.slug), JSON.stringify(nextAttempts));
setAttempts(nextAttempts);
}
setFinished(true);
return;
}
@@ -58,31 +102,120 @@ export default function PracticeExercisePage() {
};
const restart = () => {
setStarted(true);
setIndex(0);
setScore(0);
setSelected(null);
setFinished(false);
};
const start = () => {
setStarted(true);
setFinished(false);
setIndex(0);
setScore(0);
setSelected(null);
};
if (finished) {
return (
<div className="mx-auto max-w-3xl rounded-2xl border border-slate-300 bg-white p-8 text-center shadow-sm">
<h1 className="acve-heading text-5xl">Exercise complete</h1>
<p className="mt-2 text-3xl text-slate-700">
Final score: {score}/{total}
</p>
<button className="acve-button-primary mt-6 px-6 py-2 text-lg font-semibold hover:brightness-105" onClick={restart} type="button">
Restart
</button>
<div className="acve-page">
<section className="acve-panel p-6 text-center md:p-8">
<p className="acve-pill mx-auto mb-3 w-fit">Practice Results</p>
<h1 className="text-3xl font-semibold text-[#222a38] md:text-4xl">Exercise complete</h1>
<p className="mt-2 text-xl text-slate-700 md:text-2xl">
Final score: {score}/{total}
</p>
<div className="mt-5 flex flex-wrap items-center justify-center gap-2">
<button className="acve-button-primary px-5 py-2 text-sm font-semibold hover:brightness-105" onClick={restart} type="button">
Retake quiz
</button>
<button className="rounded-md border border-slate-300 px-5 py-2 text-sm font-semibold text-slate-700" type="button">
Review answers (placeholder)
</button>
<Link className="rounded-md border border-slate-300 px-5 py-2 text-sm font-semibold text-slate-700" href="/practice">
Back to modules
</Link>
</div>
</section>
<section className="acve-panel p-4">
<h2 className="text-base font-semibold text-slate-800">Attempt History (Mock)</h2>
{attempts.length === 0 ? (
<p className="mt-2 text-sm text-slate-600">No attempts recorded yet.</p>
) : (
<ul className="mt-2 space-y-2">
{attempts.map((attempt) => (
<li key={attempt.completedAt} className="rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700">
Score {attempt.score}/{attempt.total} on {new Date(attempt.completedAt).toLocaleString()}
</li>
))}
</ul>
)}
</section>
</div>
);
}
if (!started) {
return (
<div className="acve-page">
<section className="acve-panel acve-section-base">
<p className="acve-pill mb-3 w-fit">Practice Session</p>
<h1 className="text-3xl font-semibold leading-tight text-[#222a38] md:text-4xl">{practiceModule.title}</h1>
<p className="mt-2 max-w-3xl text-base leading-relaxed text-slate-600">{practiceModule.description}</p>
<div className="mt-4 grid gap-3 sm:grid-cols-3">
<div className="rounded-xl border border-slate-200 bg-white p-3">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Questions</p>
<p className="mt-1 text-2xl font-semibold text-slate-900">{total}</p>
</div>
<div className="rounded-xl border border-slate-200 bg-white p-3">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Estimated time</p>
<p className="mt-1 text-2xl font-semibold text-slate-900">{Math.max(3, total * 2)} min</p>
</div>
<div className="rounded-xl border border-slate-200 bg-white p-3">
<p className="text-xs font-semibold uppercase tracking-wide text-slate-500">Difficulty</p>
<p className="mt-1 text-2xl font-semibold text-slate-900">Intermediate</p>
</div>
</div>
<div className="mt-5 flex flex-wrap items-center gap-2">
<button className="acve-button-primary px-5 py-2 text-sm font-semibold hover:brightness-105" onClick={start} type="button">
Start practice
</button>
<Link className="rounded-md border border-slate-300 px-5 py-2 text-sm font-semibold text-slate-700" href="/practice">
Back to modules
</Link>
</div>
</section>
<section className="acve-panel p-4">
<h2 className="text-base font-semibold text-slate-800">Attempt History (Mock)</h2>
{attempts.length === 0 ? (
<p className="mt-2 text-sm text-slate-600">No attempts recorded yet for this module.</p>
) : (
<ul className="mt-2 space-y-2">
{attempts.map((attempt) => (
<li key={attempt.completedAt} className="rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700">
Score {attempt.score}/{attempt.total} on {new Date(attempt.completedAt).toLocaleString()}
</li>
))}
</ul>
)}
</section>
</div>
);
}
return (
<div className="space-y-6">
<section className="text-center">
<p className="acve-pill mx-auto mb-4 w-fit">Practice and Exercises</p>
<h1 className="acve-heading text-4xl md:text-6xl">Master Your Skills</h1>
<div className="acve-page">
<section className="acve-panel p-4">
<div className="mb-3 flex flex-wrap items-center justify-between gap-3">
<p className="text-base font-semibold text-slate-700">
{practiceModule.title} | Question {index + 1} / {total}
</p>
<p className="text-base font-semibold text-[#222a38]">Score: {score}/{total}</p>
</div>
<ProgressBar value={progress} />
</section>
<section className="grid gap-4 md:grid-cols-3">
@@ -95,28 +228,33 @@ export default function PracticeExercisePage() {
isActive ? "border-brand bg-white shadow-sm" : "border-slate-300 bg-white"
}`}
>
<div className="mb-2 text-3xl text-brand md:text-4xl">{moduleIndex === 0 ? "A/" : moduleIndex === 1 ? "[]" : "O"}</div>
<h2 className="text-2xl text-[#222a38] md:text-4xl">{module.title}</h2>
<p className="mt-2 text-lg text-slate-600 md:text-2xl">{module.description}</p>
<div className="mb-2 text-3xl text-brand">{moduleIndex === 0 ? "A/" : moduleIndex === 1 ? "[]" : "O"}</div>
<h2 className="text-xl text-[#222a38]">{module.title}</h2>
<p className="mt-2 text-sm text-slate-600">{module.description}</p>
</div>
);
})}
</section>
<section className="acve-panel p-4">
<div className="mb-3 flex items-center justify-between gap-4">
<p className="text-xl font-semibold text-slate-700">
Question {index + 1} / {total}
</p>
<p className="text-xl font-semibold text-[#222a38] md:text-2xl">Score: {score}/{total}</p>
</div>
<ProgressBar value={progress} />
<h2 className="text-lg font-semibold text-slate-800">Attempt History (Mock)</h2>
{attempts.length === 0 ? (
<p className="mt-2 text-sm text-slate-600">No attempts recorded yet.</p>
) : (
<ul className="mt-2 space-y-2">
{attempts.map((attempt) => (
<li key={attempt.completedAt} className="rounded-lg border border-slate-200 px-3 py-2 text-sm text-slate-700">
Score {attempt.score}/{attempt.total} on {new Date(attempt.completedAt).toLocaleString()}
</li>
))}
</ul>
)}
</section>
<section className="acve-panel p-6">
<div className="rounded-2xl bg-[#f6f6f8] px-6 py-10 text-center">
<p className="text-lg text-slate-500 md:text-2xl">Spanish Term</p>
<h2 className="acve-heading mt-2 text-3xl md:text-6xl">{current.prompt.replace("Spanish term: ", "")}</h2>
<div className="rounded-2xl bg-[#f6f6f8] px-6 py-8 text-center">
<p className="text-sm font-semibold uppercase tracking-wide text-slate-500">Prompt</p>
<h2 className="mt-2 text-3xl font-semibold text-[#222a38] md:text-4xl">{current.prompt.replace("Spanish term: ", "")}</h2>
</div>
<div className="mt-6 grid gap-3">
@@ -135,7 +273,7 @@ export default function PracticeExercisePage() {
return (
<button
key={choice}
className={`rounded-xl border px-4 py-3 text-left text-base text-slate-800 md:text-xl ${stateClass}`}
className={`rounded-xl border px-4 py-3 text-left text-base text-slate-800 ${stateClass}`}
onClick={() => pick(choiceIndex)}
type="button"
>
@@ -146,7 +284,7 @@ export default function PracticeExercisePage() {
</div>
<button
className="acve-button-primary mt-6 px-6 py-2 text-lg font-semibold hover:brightness-105 disabled:opacity-50"
className="acve-button-primary mt-6 px-6 py-2 text-sm font-semibold hover:brightness-105 disabled:opacity-50"
disabled={selected === null}
onClick={next}
type="button"

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 />;
}