feat(комментарии): письмо ученику об ответе под уроком
Ответы персонала в ветке комментариев никуда не уведомляли: ученик видел ответ, только если сам возвращался в урок. У тредов вопросов письмо есть, у комментариев не было — из-за этого ответ под уроком 6.3 «Холст» висел непрочитанным, пока его не продублировали руками. - sendCommentReplyEmail: тот же шаблон ДС-2, что у ответов в тредах, с текстом ответа внутри письма и кнопкой на урок. Свой лимит превью 4000 символов: ввод разрешает 10 000, а порог вопросов (2000) резал бы развёрнутые разборы. - commentReplyRecipient: правила «шлём / не шлём» вынесены чистой функцией и покрыты тестами — не шлём при выключенной настройке, не-staff, удалённом родителе, ответе самому себе и пустой почте. - notifyStudentOnCommentReply: тумблер в админке рядом с уведомлением о фидбеке, по умолчанию включён. - Удалён неподключённый дубль comment-actions.ts: компонент комментариев ходит в lib/actions/student-actions.ts, а в дубле жил свой лимит 2000 — правка в нём не давала эффекта. Проверено: type-check и lint чистые (3 ошибки линтера — существующий долг в quick-enroll-modal и kinescope-player), vitest 13/13, письмо отправлено боем и доставлено (Resend, last_event=delivered). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -1,69 +0,0 @@
|
||||
"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, parentId?: 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";
|
||||
const isCurator = session.user.role === "curator";
|
||||
if (!isAdmin && !isCurator) {
|
||||
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");
|
||||
}
|
||||
|
||||
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, ...(parentId ? { parentId } : {}) },
|
||||
});
|
||||
|
||||
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}`);
|
||||
}
|
||||
Reference in New Issue
Block a user