Files
lms-sb/src/app/(student)/dashboard/page.tsx
T
2026-07-05 16:35:30 +05:00

195 lines
7.9 KiB
TypeScript

import { headers } from "next/headers";
import { auth } from "@/lib/auth";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/prisma";
import Link from "next/link";
import { ArchetypeBanner } from "@/components/student/archetype-banner";
import { ToolboxPromoCard } from "@/components/tools/ToolboxPromoCard";
import { StoreShowcase } from "@/components/student/store-showcase";
import { STORE_CATALOG } from "@/lib/store-catalog";
export default async function StudentDashboard() {
const session = await auth.api.getSession({ headers: await headers() });
if (!session) redirect("/login");
const dbUser = await prisma.user.findUnique({
where: { id: session.user.id },
select: { archetype: true },
});
const enrollments = await prisma.courseEnrollment.findMany({
where: { userId: session.user.id },
include: {
course: {
include: {
modules: {
include: {
lessons: {
where: { published: true },
select: { id: true },
},
},
},
_count: { select: { modules: true } },
},
},
},
orderBy: { enrolledAt: "desc" },
});
const now = new Date();
const active = enrollments.filter((e) => !e.expiresAt || e.expiresAt > now);
const expired = enrollments.filter((e) => e.expiresAt && e.expiresAt <= now);
// Fetch progress for all lessons in active courses
const allLessonIds = active.flatMap((e) =>
e.course.modules.flatMap((m) => m.lessons.map((l) => l.id))
);
const progressRecords = allLessonIds.length > 0
? await prisma.lessonProgress.findMany({
where: { userId: session.user.id, lessonId: { in: allLessonIds } },
select: { lessonId: true },
})
: [];
const completedSet = new Set(progressRecords.map((p) => p.lessonId));
// Витрина: продаваемые курсы, которых у студента нет → заблюренные карточки
const enrolledSlugs = new Set(enrollments.map((e) => e.course.slug));
// Не показываем «Всё включено», если у студента уже есть обычная версия того же курса
const SUPPRESS_IF_OWNED: Record<string, string> = {
"obsidian-full": "obsidian", // ВВ Obsidian 2025 ← обычный Obsidian 2025
"zotero-full": "zotero", // ВВ Zotero ← обычный Zotero
};
const storeCourses = await prisma.course.findMany({
where: { slug: { in: Object.keys(STORE_CATALOG) }, published: true },
select: { id: true, slug: true, title: true, description: true, coverImage: true },
});
const locked = storeCourses.filter(
(c) =>
!enrolledSlugs.has(c.slug) &&
!(SUPPRESS_IF_OWNED[c.slug] && enrolledSlugs.has(SUPPRESS_IF_OWNED[c.slug]))
);
return (
<main className="max-w-5xl mx-auto px-6 py-10 w-full">
<h1 className="text-2xl font-bold mb-1">Мои курсы</h1>
<p className="text-sm mb-8" style={{ color: "var(--muted-foreground)" }}>
{active.length} активных курсов
</p>
{dbUser?.archetype && <ArchetypeBanner archetype={dbUser.archetype} />}
{active.length === 0 ? (
<div className="card-aubade p-12 text-center">
<p className="text-4xl mb-3">📚</p>
<p className="font-medium">Доступных курсов пока нет</p>
<p className="text-sm mt-1" style={{ color: "var(--muted-foreground)" }}>
Обратитесь к администратору за доступом
</p>
</div>
) : (
<div className="grid gap-4 sm:grid-cols-2">
{active.map(({ course, expiresAt }) => {
const totalLessons = course.modules.reduce((s, m) => s + m.lessons.length, 0);
const completedLessons = course.modules
.flatMap((m) => m.lessons)
.filter((l) => completedSet.has(l.id)).length;
const progressPct = totalLessons > 0
? Math.round((completedLessons / totalLessons) * 100)
: 0;
return (
<Link
key={course.id}
href={`/courses/${course.slug}`}
className="card-aubade p-0 overflow-hidden flex flex-col"
>
{course.coverImage ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={course.coverImage} alt={course.title} className="w-full aspect-video object-cover" />
) : (
<div className="w-full aspect-video flex items-center justify-center text-4xl" style={{ backgroundColor: "var(--color-surface)" }}>
📚
</div>
)}
<div className="p-4 flex-1 flex flex-col gap-2">
<h2 className="font-bold text-lg leading-tight">{course.title}</h2>
{course.description && (
<p className="text-sm line-clamp-3" style={{ color: "var(--muted-foreground)" }}>
{course.description}
</p>
)}
{/* Progress bar */}
{totalLessons > 0 && (
<div className="mt-auto">
<div className="flex items-center justify-between mb-1">
<span className="text-xs" style={{ color: "var(--muted-foreground)" }}>
{completedLessons} из {totalLessons} уроков
</span>
<span
className="text-xs font-bold"
style={{ color: progressPct === 100 ? "var(--foreground)" : "var(--muted-foreground)" }}
>
{progressPct === 100 ? "✓ Завершён" : `${progressPct}%`}
</span>
</div>
<div className="h-1.5 w-full" style={{ background: "var(--border)" }}>
<div
className="h-full transition-all"
style={{
width: `${progressPct}%`,
background: progressPct === 100 ? "var(--foreground)" : "var(--accent)",
border: progressPct > 0 ? "1px solid var(--foreground)" : "none",
}}
/>
</div>
</div>
)}
{expiresAt && (
<p className="text-xs" style={{ color: "var(--muted-foreground)" }}>
Доступ до {new Date(expiresAt).toLocaleDateString("ru-RU")}
</p>
)}
</div>
</Link>
);
})}
</div>
)}
{process.env.TOOLBOX_VISIBLE === "true" && (
<div className="mt-8">
<ToolboxPromoCard />
</div>
)}
{locked.length > 0 && (
<StoreShowcase
courses={locked}
buyer={{ name: session.user.name, email: session.user.email }}
/>
)}
{expired.length > 0 && (
<div className="mt-10">
<p className="text-xs font-bold uppercase tracking-widest mb-3" style={{ color: "var(--muted-foreground)" }}>
Доступ истёк
</p>
<div className="space-y-2">
{expired.map(({ course, expiresAt }) => (
<div key={course.id} className="flex items-center justify-between px-4 py-3 opacity-50" style={{ border: "2px solid var(--border)" }}>
<span className="text-sm font-medium">{course.title}</span>
<span className="text-xs" style={{ color: "oklch(0.577 0.245 27.325)" }}>
Истёк {new Date(expiresAt!).toLocaleDateString("ru-RU")}
</span>
</div>
))}
</div>
</div>
)}
</main>
);
}