Add threaded comment replies for admin and curator
- Add parentId field to LessonComment (self-referential FK, SetNull on delete) - Show replies indented under parent comment with left border visual - Add reply button (visible to admin/curator only) with inline textarea - Only root comments shown in main list; replies nested below their parent - Update comment count to include replies - Server-side validation: only admin/curator can reply, parent must belong to same lesson Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
ALTER TABLE "LessonComment" ADD COLUMN "parentId" TEXT;
|
||||
|
||||
ALTER TABLE "LessonComment" ADD CONSTRAINT "LessonComment_parentId_fkey"
|
||||
FOREIGN KEY ("parentId") REFERENCES "LessonComment"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -301,9 +301,12 @@ model LessonComment {
|
||||
text String
|
||||
deleted Boolean @default(false)
|
||||
createdAt DateTime @default(now())
|
||||
parentId String?
|
||||
|
||||
lesson Lesson @relation(fields: [lessonId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
parent LessonComment? @relation("CommentReplies", fields: [parentId], references: [id], onDelete: SetNull)
|
||||
replies LessonComment[] @relation("CommentReplies")
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────
|
||||
|
||||
@@ -5,7 +5,7 @@ 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) {
|
||||
export async function addComment(lessonId: string, slug: string, text: string, parentId?: string) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) throw new Error("Unauthorized");
|
||||
|
||||
@@ -20,7 +20,8 @@ export async function addComment(lessonId: string, slug: string, text: string) {
|
||||
if (!lesson) throw new Error("Lesson not found");
|
||||
|
||||
const isAdmin = session.user.role === "admin";
|
||||
if (!isAdmin) {
|
||||
const isCurator = session.user.role === "curator";
|
||||
if (!isAdmin && !isCurator) {
|
||||
const enrollment = await prisma.courseEnrollment.findUnique({
|
||||
where: {
|
||||
userId_courseId: {
|
||||
@@ -33,8 +34,14 @@ export async function addComment(lessonId: string, slug: string, text: string) {
|
||||
if (enrollment.expiresAt && enrollment.expiresAt < new Date()) throw new Error("Access expired");
|
||||
}
|
||||
|
||||
if (parentId) {
|
||||
if (!isAdmin && !isCurator) throw new Error("Forbidden");
|
||||
const parent = await prisma.lessonComment.findUnique({ where: { id: parentId } });
|
||||
if (!parent || parent.lessonId !== lessonId) throw new Error("Invalid parent");
|
||||
}
|
||||
|
||||
await prisma.lessonComment.create({
|
||||
data: { lessonId, userId: session.user.id, text: trimmed },
|
||||
data: { lessonId, userId: session.user.id, text: trimmed, ...(parentId ? { parentId } : {}) },
|
||||
});
|
||||
|
||||
revalidatePath(`/courses/${slug}/lessons/${lessonId}`);
|
||||
|
||||
@@ -56,9 +56,15 @@ export default async function LessonPage({ params }: Props) {
|
||||
})
|
||||
: null,
|
||||
prisma.lessonComment.findMany({
|
||||
where: { lessonId },
|
||||
where: { lessonId, parentId: null },
|
||||
orderBy: { createdAt: "asc" },
|
||||
include: {
|
||||
user: { select: { id: true, name: true } },
|
||||
replies: {
|
||||
orderBy: { createdAt: "asc" },
|
||||
include: { user: { select: { id: true, name: true } } },
|
||||
},
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
@@ -232,7 +238,10 @@ export default async function LessonPage({ params }: Props) {
|
||||
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})
|
||||
Обсуждение ({
|
||||
comments.filter(c => !c.deleted).length +
|
||||
comments.flatMap(c => c.replies).filter(r => !r.deleted).length
|
||||
})
|
||||
</p>
|
||||
<LessonComments
|
||||
lessonId={lessonId}
|
||||
|
||||
@@ -3,12 +3,21 @@
|
||||
import { useState, useTransition } from "react";
|
||||
import { addComment, deleteComment } from "@/lib/actions/student-actions";
|
||||
|
||||
type Reply = {
|
||||
id: string;
|
||||
text: string;
|
||||
deleted: boolean;
|
||||
createdAt: Date;
|
||||
user: { id: string; name: string };
|
||||
};
|
||||
|
||||
type Comment = {
|
||||
id: string;
|
||||
text: string;
|
||||
deleted: boolean;
|
||||
createdAt: Date;
|
||||
user: { id: string; name: string };
|
||||
replies: Reply[];
|
||||
};
|
||||
|
||||
interface Props {
|
||||
@@ -19,8 +28,20 @@ interface Props {
|
||||
currentUserRole: string;
|
||||
}
|
||||
|
||||
function formatDate(date: Date) {
|
||||
return new Date(date).toLocaleDateString("ru-RU", {
|
||||
day: "numeric",
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
export function LessonComments({ lessonId, slug, comments, currentUserId, currentUserRole }: Props) {
|
||||
const [text, setText] = useState("");
|
||||
const [replyToId, setReplyToId] = useState<string | null>(null);
|
||||
const [replyText, setReplyText] = useState("");
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
@@ -40,6 +61,19 @@ export function LessonComments({ lessonId, slug, comments, currentUserId, curren
|
||||
});
|
||||
}
|
||||
|
||||
function handleReply(parentId: string) {
|
||||
if (!replyText.trim()) return;
|
||||
startTransition(async () => {
|
||||
try {
|
||||
await addComment(lessonId, slug, replyText.trim(), parentId);
|
||||
setReplyText("");
|
||||
setReplyToId(null);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function handleDelete(commentId: string) {
|
||||
startTransition(async () => {
|
||||
try {
|
||||
@@ -52,16 +86,17 @@ export function LessonComments({ lessonId, slug, comments, currentUserId, curren
|
||||
|
||||
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 key={comment.id}>
|
||||
{/* Root comment */}
|
||||
<div className="flex gap-3">
|
||||
<div
|
||||
className="w-8 h-8 shrink-0 flex items-center justify-center text-xs font-bold"
|
||||
style={{
|
||||
@@ -73,18 +108,11 @@ export function LessonComments({ lessonId, slug, comments, currentUserId, curren
|
||||
{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",
|
||||
})}
|
||||
{formatDate(comment.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -98,10 +126,105 @@ export function LessonComments({ lessonId, slug, comments, currentUserId, curren
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="flex gap-3 mt-1">
|
||||
{!comment.deleted && (comment.user.id === currentUserId || canModerate) && (
|
||||
<button
|
||||
onClick={() => handleDelete(comment.id)}
|
||||
disabled={isPending}
|
||||
className="text-xs underline"
|
||||
style={{ color: "var(--muted-foreground)" }}
|
||||
>
|
||||
Удалить
|
||||
</button>
|
||||
)}
|
||||
{!comment.deleted && canModerate && (
|
||||
<button
|
||||
onClick={() => {
|
||||
setReplyToId(replyToId === comment.id ? null : comment.id);
|
||||
setReplyText("");
|
||||
}}
|
||||
disabled={isPending}
|
||||
className="text-xs underline"
|
||||
style={{ color: "var(--muted-foreground)" }}
|
||||
>
|
||||
{replyToId === comment.id ? "Отмена" : "Ответить"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Inline reply form */}
|
||||
{replyToId === comment.id && (
|
||||
<div className="mt-3">
|
||||
<textarea
|
||||
value={replyText}
|
||||
onChange={(e) => setReplyText(e.target.value)}
|
||||
placeholder="Напишите ответ..."
|
||||
rows={2}
|
||||
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)")}
|
||||
/>
|
||||
<div className="flex justify-end mt-2">
|
||||
<button
|
||||
onClick={() => handleReply(comment.id)}
|
||||
disabled={isPending || !replyText.trim()}
|
||||
className="btn-aubade btn-aubade-accent text-sm"
|
||||
>
|
||||
{isPending ? "Отправка..." : "Отправить ответ"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Replies */}
|
||||
{comment.replies.length > 0 && (
|
||||
<div
|
||||
className="mt-3 ml-11 space-y-3 pl-4"
|
||||
style={{ borderLeft: "2px solid var(--border)" }}
|
||||
>
|
||||
{comment.replies.map((reply) => (
|
||||
<div key={reply.id} className="flex gap-3">
|
||||
<div
|
||||
className="w-7 h-7 shrink-0 flex items-center justify-center text-xs font-bold"
|
||||
style={{
|
||||
backgroundColor: "var(--accent)",
|
||||
color: "var(--foreground)",
|
||||
border: "2px solid var(--border)",
|
||||
}}
|
||||
>
|
||||
{reply.user.name[0]?.toUpperCase() ?? "?"}
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2 mb-1 flex-wrap">
|
||||
<span className="text-sm font-bold">{reply.user.name}</span>
|
||||
<span className="text-xs" style={{ color: "var(--muted-foreground)" }}>
|
||||
{formatDate(reply.createdAt)}
|
||||
</span>
|
||||
</div>
|
||||
{reply.deleted ? (
|
||||
<p className="text-sm italic" style={{ color: "var(--muted-foreground)" }}>
|
||||
[Комментарий удалён]
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-sm whitespace-pre-wrap break-words leading-relaxed">
|
||||
{reply.text}
|
||||
</p>
|
||||
)}
|
||||
{!reply.deleted && (reply.user.id === currentUserId || canModerate) && (
|
||||
<button
|
||||
onClick={() => handleDelete(reply.id)}
|
||||
disabled={isPending}
|
||||
className="text-xs mt-1 underline"
|
||||
style={{ color: "var(--muted-foreground)" }}
|
||||
>
|
||||
@@ -112,8 +235,12 @@ export function LessonComments({ lessonId, slug, comments, currentUserId, curren
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Add comment form */}
|
||||
{/* New comment form */}
|
||||
<form onSubmit={handleAdd}>
|
||||
<textarea
|
||||
value={text}
|
||||
|
||||
@@ -138,7 +138,7 @@ export async function submitQuizAttempt(
|
||||
|
||||
// ── Comments ──────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function addComment(lessonId: string, slug: string, text: string) {
|
||||
export async function addComment(lessonId: string, slug: string, text: string, parentId?: string) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) throw new Error("Unauthorized");
|
||||
|
||||
@@ -152,7 +152,8 @@ export async function addComment(lessonId: string, slug: string, text: string) {
|
||||
if (!lesson) throw new Error("Lesson not found");
|
||||
|
||||
const isAdmin = session.user.role === "admin";
|
||||
if (!isAdmin) {
|
||||
const isCurator = session.user.role === "curator";
|
||||
if (!isAdmin && !isCurator) {
|
||||
const enrollment = await prisma.courseEnrollment.findUnique({
|
||||
where: {
|
||||
userId_courseId: {
|
||||
@@ -165,8 +166,14 @@ export async function addComment(lessonId: string, slug: string, text: string) {
|
||||
if (enrollment.expiresAt && enrollment.expiresAt < new Date()) throw new Error("Access expired");
|
||||
}
|
||||
|
||||
if (parentId) {
|
||||
if (!isAdmin && !isCurator) throw new Error("Forbidden");
|
||||
const parent = await prisma.lessonComment.findUnique({ where: { id: parentId } });
|
||||
if (!parent || parent.lessonId !== lessonId) throw new Error("Invalid parent");
|
||||
}
|
||||
|
||||
await prisma.lessonComment.create({
|
||||
data: { lessonId, userId: session.user.id, text: trimmed },
|
||||
data: { lessonId, userId: session.user.id, text: trimmed, ...(parentId ? { parentId } : {}) },
|
||||
});
|
||||
|
||||
revalidatePath(`/courses/${slug}/lessons/${lessonId}`);
|
||||
|
||||
Reference in New Issue
Block a user