Stage 1.5: categories, enrollment expiry, access log, bulk grant, user page
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { revalidatePath } from "next/cache";
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
async function requireAdmin() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session || session.user.role !== "admin") throw new Error("Forbidden");
|
||||
}
|
||||
|
||||
function slugify(str: string) {
|
||||
const map: Record<string, string> = {
|
||||
а:"a",б:"b",в:"v",г:"g",д:"d",е:"e",ё:"yo",ж:"zh",з:"z",и:"i",й:"y",
|
||||
к:"k",л:"l",м:"m",н:"n",о:"o",п:"p",р:"r",с:"s",т:"t",у:"u",ф:"f",
|
||||
х:"kh",ц:"ts",ч:"ch",ш:"sh",щ:"shch",ъ:"",ы:"y",ь:"",э:"e",ю:"yu",я:"ya",
|
||||
};
|
||||
return str.toLowerCase()
|
||||
.replace(/[а-яё]/g, (c) => map[c] ?? c)
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "");
|
||||
}
|
||||
|
||||
export async function createCategory(formData: FormData) {
|
||||
await requireAdmin();
|
||||
const title = formData.get("title") as string;
|
||||
const slug = (formData.get("slug") as string).trim() || slugify(title);
|
||||
const count = await prisma.category.count();
|
||||
await prisma.category.create({ data: { title, slug, order: count } });
|
||||
revalidatePath("/admin/categories");
|
||||
}
|
||||
|
||||
export async function updateCategory(id: string, formData: FormData) {
|
||||
await requireAdmin();
|
||||
const title = formData.get("title") as string;
|
||||
const slug = formData.get("slug") as string;
|
||||
await prisma.category.update({ where: { id }, data: { title, slug } });
|
||||
revalidatePath("/admin/categories");
|
||||
}
|
||||
|
||||
export async function deleteCategory(id: string) {
|
||||
await requireAdmin();
|
||||
await prisma.category.delete({ where: { id } });
|
||||
revalidatePath("/admin/categories");
|
||||
revalidatePath("/admin/courses");
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { CategoryRow } from "@/components/admin/category-row";
|
||||
import { createCategory } from "./actions";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
|
||||
export default async function CategoriesPage() {
|
||||
const categories = await prisma.category.findMany({
|
||||
orderBy: { order: "asc" },
|
||||
include: { _count: { select: { courses: true } } },
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="p-8 max-w-2xl">
|
||||
<div className="mb-6">
|
||||
<h1 className="text-2xl font-bold" style={{ color: "var(--foreground)" }}>Категории</h1>
|
||||
<p className="text-sm mt-0.5" style={{ color: "var(--muted-foreground)" }}>
|
||||
{categories.length} категорий
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 mb-8">
|
||||
{categories.length === 0 ? (
|
||||
<p className="text-sm py-4" style={{ color: "var(--muted-foreground)" }}>
|
||||
Категорий пока нет. Создайте первую.
|
||||
</p>
|
||||
) : (
|
||||
categories.map((cat) => (
|
||||
<CategoryRow key={cat.id} category={cat} courseCount={cat._count.courses} />
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="card-aubade p-5">
|
||||
<p className="text-xs font-bold uppercase tracking-widest mb-4" style={{ color: "var(--muted-foreground)" }}>
|
||||
Новая категория
|
||||
</p>
|
||||
<form action={createCategory} className="flex flex-col gap-3">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="text-xs uppercase tracking-widest font-bold block mb-1.5" style={{ color: "var(--muted-foreground)" }}>
|
||||
Название
|
||||
</label>
|
||||
<Input name="title" placeholder="Obsidian PKM" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="text-xs uppercase tracking-widest font-bold block mb-1.5" style={{ color: "var(--muted-foreground)" }}>
|
||||
Slug
|
||||
</label>
|
||||
<Input name="slug" placeholder="obsidian-pkm (авто)" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit">+ Создать</Button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { revalidatePath } from "next/cache";
|
||||
async function requireAdmin() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session || session.user.role !== "admin") throw new Error("Forbidden");
|
||||
return session;
|
||||
}
|
||||
|
||||
// ── Modules ──────────────────────────────────────────────────────────────────
|
||||
@@ -45,20 +46,45 @@ export async function reorderModules(courseId: string, orderedIds: string[]) {
|
||||
|
||||
// ── Enrollment ───────────────────────────────────────────────────────────────
|
||||
|
||||
export async function grantAccess(courseId: string, userId: string) {
|
||||
await requireAdmin();
|
||||
export async function grantAccess(
|
||||
courseId: string,
|
||||
userId: string,
|
||||
expiresAt?: string | null,
|
||||
note?: string
|
||||
) {
|
||||
const session = await requireAdmin();
|
||||
await prisma.courseEnrollment.upsert({
|
||||
where: { userId_courseId: { userId, courseId } },
|
||||
update: {},
|
||||
create: { userId, courseId },
|
||||
update: { expiresAt: expiresAt ? new Date(expiresAt) : null },
|
||||
create: { userId, courseId, expiresAt: expiresAt ? new Date(expiresAt) : null },
|
||||
});
|
||||
await prisma.accessLog.create({
|
||||
data: {
|
||||
courseId,
|
||||
userId,
|
||||
action: "granted",
|
||||
method: "manual",
|
||||
grantedById: session.user.id,
|
||||
note: note || null,
|
||||
},
|
||||
});
|
||||
revalidatePath(`/admin/courses/${courseId}`);
|
||||
}
|
||||
|
||||
export async function revokeAccess(courseId: string, userId: string) {
|
||||
await requireAdmin();
|
||||
export async function revokeAccess(courseId: string, userId: string, note?: string) {
|
||||
const session = await requireAdmin();
|
||||
await prisma.courseEnrollment.delete({
|
||||
where: { userId_courseId: { userId, courseId } },
|
||||
});
|
||||
await prisma.accessLog.create({
|
||||
data: {
|
||||
courseId,
|
||||
userId,
|
||||
action: "revoked",
|
||||
method: "manual",
|
||||
grantedById: session.user.id,
|
||||
note: note || null,
|
||||
},
|
||||
});
|
||||
revalidatePath(`/admin/courses/${courseId}`);
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ interface Props {
|
||||
export default async function CourseDetailPage({ params }: Props) {
|
||||
const { courseId } = await params;
|
||||
|
||||
const [course, allStudents] = await Promise.all([
|
||||
const [course, allStudents, categories] = await Promise.all([
|
||||
prisma.course.findUnique({
|
||||
where: { id: courseId },
|
||||
include: {
|
||||
@@ -20,7 +20,17 @@ export default async function CourseDetailPage({ params }: Props) {
|
||||
orderBy: { order: "asc" },
|
||||
include: { _count: { select: { lessons: true } } },
|
||||
},
|
||||
enrollments: { include: { user: { select: { id: true, name: true, email: true } } } },
|
||||
enrollments: {
|
||||
select: { userId: true, expiresAt: true },
|
||||
},
|
||||
accessLogs: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
include: {
|
||||
user: { select: { name: true } },
|
||||
grantedBy: { select: { name: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
prisma.user.findMany({
|
||||
@@ -28,43 +38,51 @@ export default async function CourseDetailPage({ params }: Props) {
|
||||
select: { id: true, name: true, email: true },
|
||||
orderBy: { name: "asc" },
|
||||
}),
|
||||
prisma.category.findMany({ orderBy: { order: "asc" } }),
|
||||
]);
|
||||
|
||||
if (!course) notFound();
|
||||
|
||||
const enrolledIds = new Set(course.enrollments.map((e) => e.userId));
|
||||
|
||||
return (
|
||||
<div className="p-8 max-w-4xl">
|
||||
{/* Breadcrumb */}
|
||||
<nav className="text-sm text-slate-400 mb-6">
|
||||
<Link href="/admin/courses" className="hover:text-slate-600">Курсы</Link>
|
||||
<nav className="text-xs mb-6 uppercase tracking-widest" style={{ color: "var(--muted-foreground)" }}>
|
||||
<Link href="/admin/courses" className="hover:underline">Курсы</Link>
|
||||
<span className="mx-2">/</span>
|
||||
<span className="text-slate-700">{course.title}</span>
|
||||
<span style={{ color: "var(--foreground)" }}>{course.title}</span>
|
||||
</nav>
|
||||
|
||||
{/* Course metadata */}
|
||||
<section className="bg-white border border-slate-200 rounded-2xl p-6 mb-6">
|
||||
<h2 className="text-base font-semibold text-slate-700 mb-4">Основная информация</h2>
|
||||
<CourseEditForm course={course} />
|
||||
<section className="card-aubade p-6 mb-6">
|
||||
<p className="text-xs font-bold uppercase tracking-widest mb-5" style={{ color: "var(--muted-foreground)" }}>
|
||||
Основная информация
|
||||
</p>
|
||||
<CourseEditForm course={course} categories={categories} />
|
||||
</section>
|
||||
|
||||
{/* Modules */}
|
||||
<section className="bg-white border border-slate-200 rounded-2xl p-6 mb-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h2 className="text-base font-semibold text-slate-700">Модули</h2>
|
||||
<span className="text-sm text-slate-400">{course.modules.length} модулей</span>
|
||||
<section className="card-aubade p-6 mb-6">
|
||||
<div className="flex items-center justify-between mb-5">
|
||||
<p className="text-xs font-bold uppercase tracking-widest" style={{ color: "var(--muted-foreground)" }}>
|
||||
Модули
|
||||
</p>
|
||||
<span className="text-xs" style={{ color: "var(--muted-foreground)" }}>
|
||||
{course.modules.length} модулей
|
||||
</span>
|
||||
</div>
|
||||
<SortableModules courseId={courseId} modules={course.modules} />
|
||||
</section>
|
||||
|
||||
{/* Access management */}
|
||||
<section className="bg-white border border-slate-200 rounded-2xl p-6">
|
||||
<h2 className="text-base font-semibold text-slate-700 mb-4">Доступ к курсу</h2>
|
||||
<section className="card-aubade p-6">
|
||||
<p className="text-xs font-bold uppercase tracking-widest mb-5" style={{ color: "var(--muted-foreground)" }}>
|
||||
Управление доступом
|
||||
</p>
|
||||
<EnrollmentManager
|
||||
courseId={courseId}
|
||||
allStudents={allStudents}
|
||||
enrolledIds={[...enrolledIds]}
|
||||
enrollments={course.enrollments}
|
||||
accessLogs={course.accessLogs}
|
||||
/>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -44,10 +44,11 @@ export async function updateCourse(courseId: string, formData: FormData) {
|
||||
const description = (formData.get("description") as string) || null;
|
||||
const published = formData.get("published") === "true";
|
||||
const coverImage = (formData.get("coverImage") as string) || null;
|
||||
const categoryId = (formData.get("categoryId") as string) || null;
|
||||
|
||||
await prisma.course.update({
|
||||
where: { id: courseId },
|
||||
data: { title, slug, description, published, coverImage },
|
||||
data: { title, slug, description, published, coverImage, categoryId },
|
||||
});
|
||||
|
||||
revalidatePath("/admin/courses");
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"use server";
|
||||
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
async function requireAdmin() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session || session.user.role !== "admin") throw new Error("Forbidden");
|
||||
return session;
|
||||
}
|
||||
|
||||
export async function bulkGrantAccess(
|
||||
userId: string,
|
||||
courseIds: string[],
|
||||
expiresAt?: string | null
|
||||
) {
|
||||
const session = await requireAdmin();
|
||||
const expiry = expiresAt ? new Date(expiresAt) : null;
|
||||
|
||||
await Promise.all(
|
||||
courseIds.map(async (courseId) => {
|
||||
await prisma.courseEnrollment.upsert({
|
||||
where: { userId_courseId: { userId, courseId } },
|
||||
update: { expiresAt: expiry },
|
||||
create: { userId, courseId, expiresAt: expiry },
|
||||
});
|
||||
await prisma.accessLog.create({
|
||||
data: {
|
||||
courseId,
|
||||
userId,
|
||||
action: "granted",
|
||||
method: "bulk",
|
||||
grantedById: session.user.id,
|
||||
},
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
revalidatePath(`/admin/users/${userId}`);
|
||||
}
|
||||
|
||||
export async function revokeUserAccess(userId: string, courseId: string) {
|
||||
const session = await requireAdmin();
|
||||
await prisma.courseEnrollment.delete({
|
||||
where: { userId_courseId: { userId, courseId } },
|
||||
});
|
||||
await prisma.accessLog.create({
|
||||
data: {
|
||||
courseId,
|
||||
userId,
|
||||
action: "revoked",
|
||||
method: "manual",
|
||||
grantedById: session.user.id,
|
||||
},
|
||||
});
|
||||
revalidatePath(`/admin/users/${userId}`);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { notFound } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import { UserEnrollmentManager } from "@/components/admin/user-enrollment-manager";
|
||||
|
||||
interface Props {
|
||||
params: Promise<{ userId: string }>;
|
||||
}
|
||||
|
||||
export default async function UserPage({ params }: Props) {
|
||||
const { userId } = await params;
|
||||
|
||||
const [user, allCourses] = await Promise.all([
|
||||
prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
include: {
|
||||
enrollments: {
|
||||
include: { course: { select: { id: true, title: true, published: true } } },
|
||||
orderBy: { enrolledAt: "desc" },
|
||||
},
|
||||
accessLogs: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 30,
|
||||
include: {
|
||||
course: { select: { title: true } },
|
||||
grantedBy: { select: { name: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
prisma.course.findMany({
|
||||
orderBy: { title: "asc" },
|
||||
select: { id: true, title: true, published: true },
|
||||
}),
|
||||
]);
|
||||
|
||||
if (!user) notFound();
|
||||
|
||||
const roleLabel: Record<string, string> = { admin: "Администратор", curator: "Куратор", student: "Ученик" };
|
||||
|
||||
return (
|
||||
<div className="p-8 max-w-3xl">
|
||||
<nav className="text-xs mb-6 uppercase tracking-widest" style={{ color: "var(--muted-foreground)" }}>
|
||||
<Link href="/admin/users" className="hover:underline">Пользователи</Link>
|
||||
<span className="mx-2">/</span>
|
||||
<span style={{ color: "var(--foreground)" }}>{user.name}</span>
|
||||
</nav>
|
||||
|
||||
{/* User info */}
|
||||
<section className="card-aubade p-6 mb-6">
|
||||
<div className="flex items-start justify-between">
|
||||
<div>
|
||||
<h1 className="text-xl font-bold">{user.name}</h1>
|
||||
<p className="text-sm mt-0.5" style={{ color: "var(--muted-foreground)" }}>{user.email}</p>
|
||||
</div>
|
||||
<div className="flex flex-col items-end gap-1">
|
||||
<span className="tag-aubade">{roleLabel[user.role] ?? user.role}</span>
|
||||
<span className="text-xs" style={{ color: "var(--muted-foreground)" }}>
|
||||
с {new Date(user.createdAt).toLocaleDateString("ru-RU")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Enrollments + bulk grant */}
|
||||
<section className="card-aubade p-6 mb-6">
|
||||
<p className="text-xs font-bold uppercase tracking-widest mb-5" style={{ color: "var(--muted-foreground)" }}>
|
||||
Доступ к курсам
|
||||
</p>
|
||||
<UserEnrollmentManager
|
||||
userId={userId}
|
||||
allCourses={allCourses}
|
||||
enrollments={user.enrollments.map((e) => ({
|
||||
courseId: e.courseId,
|
||||
expiresAt: e.expiresAt,
|
||||
courseTitle: e.course.title,
|
||||
}))}
|
||||
/>
|
||||
</section>
|
||||
|
||||
{/* Access log */}
|
||||
{user.accessLogs.length > 0 && (
|
||||
<section className="card-aubade p-6">
|
||||
<p className="text-xs font-bold uppercase tracking-widest mb-4" style={{ color: "var(--muted-foreground)" }}>
|
||||
История доступа
|
||||
</p>
|
||||
<div className="space-y-1.5 max-h-72 overflow-y-auto">
|
||||
{user.accessLogs.map((log) => (
|
||||
<div key={log.id} className="flex items-center gap-3 px-3 py-2 text-xs" style={{ border: "2px solid var(--border)" }}>
|
||||
<span style={{ color: log.action === "granted" ? "#3A6A3A" : "oklch(0.577 0.245 27.325)", fontWeight: 700, minWidth: 70 }}>
|
||||
{log.action === "granted" ? "▲ Выдан" : "▼ Отозван"}
|
||||
</span>
|
||||
<span className="flex-1">{log.course.title}</span>
|
||||
<span style={{ color: "var(--muted-foreground)" }}>{log.grantedBy?.name ?? "—"}</span>
|
||||
<span style={{ color: "var(--muted-foreground)" }}>
|
||||
{new Date(log.createdAt).toLocaleString("ru-RU", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import Link from "next/link";
|
||||
|
||||
const roleLabel: Record<string, string> = {
|
||||
admin: "Администратор",
|
||||
@@ -39,10 +40,10 @@ export default async function UsersPage() {
|
||||
</thead>
|
||||
<tbody>
|
||||
{users.map((user) => (
|
||||
<tr key={user.id} className="border-b border-slate-50 last:border-0 hover:bg-slate-50">
|
||||
<tr key={user.id} className="border-b last:border-0" style={{ borderColor: "var(--border)" }}>
|
||||
<td className="px-5 py-3">
|
||||
<p className="font-medium text-slate-800">{user.name}</p>
|
||||
<p className="text-xs text-slate-400">{user.email}</p>
|
||||
<Link href={`/admin/users/${user.id}`} className="font-medium hover:underline" style={{ color: "var(--foreground)" }}>{user.name}</Link>
|
||||
<p className="text-xs" style={{ color: "var(--muted-foreground)" }}>{user.email}</p>
|
||||
</td>
|
||||
<td className="px-5 py-3">
|
||||
<Badge variant={roleVariant[user.role] ?? "outline"}>
|
||||
|
||||
Reference in New Issue
Block a user