Add lesson comments (Stage 6)
- LessonComment CRUD: addComment / deleteComment server actions - LessonComments client component with form, avatar, delete - Comments section at bottom of lesson page (enrolled users only) - Soft-delete support, moderation for curator/admin - ROADMAP: moved Квизы to end (Stage 11), marked Stage 7 done Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
"use server";
|
||||
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { revalidatePath } from "next/cache";
|
||||
|
||||
export async function addComment(lessonId: string, slug: string, text: string) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) throw new Error("Unauthorized");
|
||||
|
||||
const trimmed = text.trim();
|
||||
if (!trimmed || trimmed.length > 2000) throw new Error("Invalid text");
|
||||
|
||||
// Verify user has access to this lesson's course
|
||||
const lesson = await prisma.lesson.findUnique({
|
||||
where: { id: lessonId },
|
||||
select: { module: { select: { course: { select: { id: true } } } } },
|
||||
});
|
||||
if (!lesson) throw new Error("Lesson not found");
|
||||
|
||||
const isAdmin = session.user.role === "admin";
|
||||
if (!isAdmin) {
|
||||
const enrollment = await prisma.courseEnrollment.findUnique({
|
||||
where: {
|
||||
userId_courseId: {
|
||||
userId: session.user.id,
|
||||
courseId: lesson.module.course.id,
|
||||
},
|
||||
},
|
||||
});
|
||||
if (!enrollment) throw new Error("Not enrolled");
|
||||
if (enrollment.expiresAt && enrollment.expiresAt < new Date()) throw new Error("Access expired");
|
||||
}
|
||||
|
||||
await prisma.lessonComment.create({
|
||||
data: { lessonId, userId: session.user.id, text: trimmed },
|
||||
});
|
||||
|
||||
revalidatePath(`/courses/${slug}/lessons/${lessonId}`);
|
||||
}
|
||||
|
||||
export async function deleteComment(commentId: string, lessonId: string, slug: string) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) throw new Error("Unauthorized");
|
||||
|
||||
const comment = await prisma.lessonComment.findUnique({ where: { id: commentId } });
|
||||
if (!comment) throw new Error("Not found");
|
||||
|
||||
const canDelete =
|
||||
comment.userId === session.user.id ||
|
||||
session.user.role === "curator" ||
|
||||
session.user.role === "admin";
|
||||
if (!canDelete) throw new Error("Forbidden");
|
||||
|
||||
await prisma.lessonComment.update({
|
||||
where: { id: commentId },
|
||||
data: { deleted: true },
|
||||
});
|
||||
|
||||
revalidatePath(`/courses/${slug}/lessons/${lessonId}`);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { KinescopePlayer } from "@/components/player/kinescope-player";
|
||||
import { LessonContent } from "@/components/student/lesson-content";
|
||||
import { LessonCompleteButton } from "@/components/student/lesson-complete-button";
|
||||
import { HomeworkSection } from "@/components/student/homework-section";
|
||||
import { LessonComments } from "@/components/student/lesson-comments";
|
||||
|
||||
interface Props {
|
||||
params: Promise<{ slug: string; lessonId: string }>;
|
||||
@@ -18,7 +19,7 @@ export default async function LessonPage({ params }: Props) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
const isAdmin = session?.user.role === "admin";
|
||||
|
||||
const [lesson, progress] = await Promise.all([
|
||||
const [lesson, progress, comments] = await Promise.all([
|
||||
prisma.lesson.findUnique({
|
||||
where: { id: lessonId, ...(isAdmin ? {} : { published: true }) },
|
||||
include: {
|
||||
@@ -49,6 +50,11 @@ export default async function LessonPage({ params }: Props) {
|
||||
where: { userId_lessonId: { userId: session.user.id, lessonId } },
|
||||
})
|
||||
: null,
|
||||
prisma.lessonComment.findMany({
|
||||
where: { lessonId },
|
||||
orderBy: { createdAt: "asc" },
|
||||
include: { user: { select: { id: true, name: true } } },
|
||||
}),
|
||||
]);
|
||||
|
||||
// Fetch homework submission for this student
|
||||
@@ -179,6 +185,25 @@ export default async function LessonPage({ params }: Props) {
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Comments */}
|
||||
{session && (
|
||||
<div
|
||||
className="mt-10 pt-8"
|
||||
style={{ borderTop: "2px solid var(--border)" }}
|
||||
>
|
||||
<p className="text-xs font-bold uppercase tracking-widest mb-6" style={{ color: "var(--muted-foreground)" }}>
|
||||
Обсуждение ({comments.filter((c) => !c.deleted).length})
|
||||
</p>
|
||||
<LessonComments
|
||||
lessonId={lessonId}
|
||||
slug={slug}
|
||||
comments={comments}
|
||||
currentUserId={session.user.id}
|
||||
currentUserRole={session.user.role ?? "student"}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useTransition } from "react";
|
||||
import { addComment, deleteComment } from "@/app/(student)/courses/[slug]/lessons/[lessonId]/comment-actions";
|
||||
|
||||
type Comment = {
|
||||
id: string;
|
||||
text: string;
|
||||
deleted: boolean;
|
||||
createdAt: Date;
|
||||
user: { id: string; name: string };
|
||||
};
|
||||
|
||||
interface Props {
|
||||
lessonId: string;
|
||||
slug: string;
|
||||
comments: Comment[];
|
||||
currentUserId: string;
|
||||
currentUserRole: string;
|
||||
}
|
||||
|
||||
export function LessonComments({ lessonId, slug, comments, currentUserId, currentUserRole }: Props) {
|
||||
const [text, setText] = useState("");
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const canModerate = currentUserRole === "curator" || currentUserRole === "admin";
|
||||
|
||||
function handleAdd(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!text.trim()) return;
|
||||
setError(null);
|
||||
startTransition(async () => {
|
||||
try {
|
||||
await addComment(lessonId, slug, text.trim());
|
||||
setText("");
|
||||
} catch {
|
||||
setError("Не удалось отправить комментарий. Попробуйте ещё раз.");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function handleDelete(commentId: string) {
|
||||
startTransition(async () => {
|
||||
try {
|
||||
await deleteComment(commentId, lessonId, slug);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
{/* Comment list */}
|
||||
<div className="space-y-5 mb-6">
|
||||
{comments.length === 0 && (
|
||||
<p className="text-sm" style={{ color: "var(--muted-foreground)" }}>
|
||||
Пока нет комментариев. Будьте первым!
|
||||
</p>
|
||||
)}
|
||||
{comments.map((comment) => (
|
||||
<div key={comment.id} className="flex gap-3">
|
||||
{/* Avatar */}
|
||||
<div
|
||||
className="w-8 h-8 shrink-0 flex items-center justify-center text-xs font-bold"
|
||||
style={{
|
||||
backgroundColor: "var(--accent)",
|
||||
color: "var(--foreground)",
|
||||
border: "2px solid var(--border)",
|
||||
}}
|
||||
>
|
||||
{comment.user.name[0]?.toUpperCase() ?? "?"}
|
||||
</div>
|
||||
|
||||
{/* Body */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1 flex-wrap">
|
||||
<span className="text-sm font-bold">{comment.user.name}</span>
|
||||
<span className="text-xs" style={{ color: "var(--muted-foreground)" }}>
|
||||
{new Date(comment.createdAt).toLocaleDateString("ru-RU", {
|
||||
day: "numeric",
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{comment.deleted ? (
|
||||
<p className="text-sm italic" style={{ color: "var(--muted-foreground)" }}>
|
||||
[Комментарий удалён]
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-sm whitespace-pre-wrap break-words leading-relaxed">
|
||||
{comment.text}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{!comment.deleted && (comment.user.id === currentUserId || canModerate) && (
|
||||
<button
|
||||
onClick={() => handleDelete(comment.id)}
|
||||
disabled={isPending}
|
||||
className="text-xs mt-1 underline"
|
||||
style={{ color: "var(--muted-foreground)" }}
|
||||
>
|
||||
Удалить
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Add comment form */}
|
||||
<form onSubmit={handleAdd}>
|
||||
<textarea
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder="Напишите комментарий..."
|
||||
rows={3}
|
||||
maxLength={2000}
|
||||
disabled={isPending}
|
||||
className="w-full text-sm p-3 resize-y"
|
||||
style={{
|
||||
border: "2px solid var(--border)",
|
||||
backgroundColor: "var(--background)",
|
||||
color: "var(--foreground)",
|
||||
outline: "none",
|
||||
fontFamily: "inherit",
|
||||
}}
|
||||
onFocus={(e) => (e.target.style.borderColor = "var(--foreground)")}
|
||||
onBlur={(e) => (e.target.style.borderColor = "var(--border)")}
|
||||
/>
|
||||
{error && (
|
||||
<p className="text-xs mt-1" style={{ color: "oklch(0.577 0.245 27.325)" }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center justify-between mt-2">
|
||||
<span className="text-xs" style={{ color: "var(--muted-foreground)" }}>
|
||||
{text.length > 0 ? `${text.length}/2000` : ""}
|
||||
</span>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isPending || !text.trim()}
|
||||
className="btn-aubade btn-aubade-accent text-sm"
|
||||
>
|
||||
{isPending ? "Отправка..." : "Отправить"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user