Add student questions list, new question form, and thread pages
Tasks 8–10: student-facing questions UI — list page with unread badges, new question form with client-side submission, and thread page with QuestionThread component for real-time reply + file attachment flow. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
import { headers } from "next/headers";
|
||||
import { auth } from "@/lib/auth";
|
||||
import { redirect, notFound } from "next/navigation";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import Link from "next/link";
|
||||
import { QuestionThread } from "@/components/questions/QuestionThread";
|
||||
|
||||
export default async function QuestionThreadPage({
|
||||
params,
|
||||
}: {
|
||||
params: Promise<{ id: string }>;
|
||||
}) {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) redirect("/login");
|
||||
|
||||
const { id } = await params;
|
||||
|
||||
const question = await prisma.studentQuestion.findUnique({
|
||||
where: { id },
|
||||
include: {
|
||||
user: { select: { id: true, name: true } },
|
||||
messages: {
|
||||
include: { author: { select: { id: true, name: true, role: true } } },
|
||||
orderBy: { createdAt: "asc" },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!question || question.userId !== session.user.id) notFound();
|
||||
|
||||
// Mark staff messages as read
|
||||
await prisma.studentQuestionMessage.updateMany({
|
||||
where: {
|
||||
questionId: id,
|
||||
isRead: false,
|
||||
NOT: { authorId: session.user.id },
|
||||
},
|
||||
data: { isRead: true },
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto px-4 py-8">
|
||||
<div className="flex items-start justify-between mb-6">
|
||||
<div>
|
||||
<h1 className="text-lg font-bold mb-1" style={{ color: "var(--foreground)" }}>
|
||||
{question.title}
|
||||
</h1>
|
||||
<p className="text-xs" style={{ color: "var(--muted-foreground)" }}>
|
||||
Создан{" "}
|
||||
{new Date(question.createdAt).toLocaleDateString("ru", {
|
||||
day: "numeric",
|
||||
month: "long",
|
||||
})}{" "}
|
||||
·{" "}
|
||||
<span
|
||||
style={{
|
||||
color: question.status === "OPEN" ? "var(--foreground)" : "var(--muted-foreground)",
|
||||
fontWeight: 700,
|
||||
}}
|
||||
>
|
||||
{question.status === "OPEN" ? "● Открыт" : "✓ Закрыт"}
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
<Link
|
||||
href="/questions"
|
||||
className="text-xs"
|
||||
style={{ color: "var(--muted-foreground)", textDecoration: "underline" }}
|
||||
>
|
||||
← Все вопросы
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
<QuestionThread
|
||||
questionId={id}
|
||||
questionStatus={question.status as "OPEN" | "CLOSED"}
|
||||
currentUserId={session.user.id}
|
||||
initialMessages={question.messages.map((m) => ({
|
||||
...m,
|
||||
files: m.files as Array<{ name: string; url: string; size: number }> | null,
|
||||
createdAt: m.createdAt.toISOString(),
|
||||
}))}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
export default function NewQuestionPage() {
|
||||
const router = useRouter();
|
||||
const [title, setTitle] = useState("");
|
||||
const [text, setText] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
async function handleSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
if (!title.trim() || !text.trim()) return;
|
||||
setLoading(true);
|
||||
setError("");
|
||||
|
||||
try {
|
||||
const res = await fetch("/api/questions", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ title, text }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json();
|
||||
throw new Error(data.error ?? "Ошибка при создании вопроса");
|
||||
}
|
||||
const q = await res.json();
|
||||
router.push(`/questions/${q.id}`);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Ошибка");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="max-w-xl mx-auto px-4 py-8">
|
||||
<div className="flex items-center gap-3 mb-6">
|
||||
<a
|
||||
href="/questions"
|
||||
className="text-sm"
|
||||
style={{ color: "var(--muted-foreground)", textDecoration: "underline" }}
|
||||
>
|
||||
← Все вопросы
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<h1 className="text-xl font-bold mb-6" style={{ color: "var(--foreground)" }}>
|
||||
Новый вопрос
|
||||
</h1>
|
||||
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4">
|
||||
<div>
|
||||
<label
|
||||
className="block text-sm font-bold mb-1"
|
||||
style={{ color: "var(--foreground)" }}
|
||||
>
|
||||
Тема вопроса
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="Кратко опишите суть вопроса"
|
||||
required
|
||||
className="w-full text-sm px-3 py-2 outline-none"
|
||||
style={{
|
||||
border: "2px solid var(--border)",
|
||||
background: "var(--surface)",
|
||||
color: "var(--foreground)",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label
|
||||
className="block text-sm font-bold mb-1"
|
||||
style={{ color: "var(--foreground)" }}
|
||||
>
|
||||
Описание
|
||||
</label>
|
||||
<textarea
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder="Подробно опишите вопрос или проблему"
|
||||
required
|
||||
rows={6}
|
||||
className="w-full text-sm px-3 py-2 outline-none resize-none"
|
||||
style={{
|
||||
border: "2px solid var(--border)",
|
||||
background: "var(--surface)",
|
||||
color: "var(--foreground)",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<p className="text-sm" style={{ color: "#c00" }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading || !title.trim() || !text.trim()}
|
||||
className="self-end text-sm font-bold px-6 py-2"
|
||||
style={{
|
||||
background: "var(--foreground)",
|
||||
color: "var(--background)",
|
||||
border: "none",
|
||||
opacity: loading ? 0.6 : 1,
|
||||
}}
|
||||
>
|
||||
{loading ? "Отправка..." : "Отправить →"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
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";
|
||||
|
||||
export default async function QuestionsPage() {
|
||||
const session = await auth.api.getSession({ headers: await headers() });
|
||||
if (!session) redirect("/login");
|
||||
|
||||
const questions = await prisma.studentQuestion.findMany({
|
||||
where: { userId: session.user.id },
|
||||
include: {
|
||||
_count: {
|
||||
select: {
|
||||
messages: {
|
||||
where: { isRead: false, NOT: { authorId: session.user.id } },
|
||||
},
|
||||
},
|
||||
},
|
||||
messages: {
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 1,
|
||||
include: { author: { select: { name: true } } },
|
||||
},
|
||||
},
|
||||
orderBy: { updatedAt: "desc" },
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="max-w-2xl mx-auto px-4 py-8">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-xl font-bold" style={{ color: "var(--foreground)" }}>
|
||||
Мои вопросы
|
||||
</h1>
|
||||
<Link
|
||||
href="/questions/new"
|
||||
className="text-sm font-bold px-4 py-2"
|
||||
style={{
|
||||
background: "var(--surface)",
|
||||
border: "2px solid var(--border-strong)",
|
||||
color: "var(--foreground)",
|
||||
}}
|
||||
>
|
||||
+ Задать вопрос
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{questions.length === 0 && (
|
||||
<p className="text-sm" style={{ color: "var(--muted-foreground)" }}>
|
||||
У вас ещё нет вопросов.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
{questions.map((q) => {
|
||||
const unread = q._count.messages > 0;
|
||||
const lastMsg = q.messages[0];
|
||||
return (
|
||||
<Link
|
||||
key={q.id}
|
||||
href={`/questions/${q.id}`}
|
||||
className="block p-3 rounded-sm transition-colors"
|
||||
style={{
|
||||
border: unread ? "2px solid var(--border-strong)" : "1px solid var(--border)",
|
||||
background: q.status === "CLOSED" ? "var(--surface-muted)" : "var(--surface)",
|
||||
opacity: q.status === "CLOSED" ? 0.7 : 1,
|
||||
}}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-2 mb-1">
|
||||
<span
|
||||
className="text-sm"
|
||||
style={{
|
||||
fontWeight: unread ? 700 : 400,
|
||||
color: q.status === "CLOSED" ? "var(--muted-foreground)" : "var(--foreground)",
|
||||
}}
|
||||
>
|
||||
{q.title}
|
||||
</span>
|
||||
<span
|
||||
className="text-xs shrink-0 px-1.5 py-0.5 rounded-sm"
|
||||
style={
|
||||
q.status === "OPEN"
|
||||
? { background: "#E8F0D8", border: "1px solid var(--border)", color: "var(--foreground)" }
|
||||
: { background: "var(--surface-muted)", color: "var(--muted-foreground)" }
|
||||
}
|
||||
>
|
||||
{q.status === "OPEN" ? "● ОТКРЫТ" : "✓ ЗАКРЫТ"}
|
||||
</span>
|
||||
</div>
|
||||
{unread && (
|
||||
<div className="flex items-center gap-1.5 mb-1">
|
||||
<span
|
||||
className="inline-block w-2 h-2 rounded-full"
|
||||
style={{ background: "var(--foreground)" }}
|
||||
/>
|
||||
<span className="text-xs font-bold" style={{ color: "var(--foreground)" }}>
|
||||
Новый ответ от школы
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
{lastMsg && !unread && (
|
||||
<p className="text-xs" style={{ color: "var(--muted-foreground)" }}>
|
||||
последнее от {lastMsg.author.name}
|
||||
</p>
|
||||
)}
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef } from "react";
|
||||
|
||||
interface FileAttachment {
|
||||
name: string;
|
||||
url: string;
|
||||
size: number;
|
||||
}
|
||||
|
||||
interface Message {
|
||||
id: string;
|
||||
authorId: string;
|
||||
text: string;
|
||||
files: FileAttachment[] | null;
|
||||
isRead: boolean;
|
||||
createdAt: string;
|
||||
author: { id: string; name: string; role: string };
|
||||
}
|
||||
|
||||
interface QuestionThreadProps {
|
||||
questionId: string;
|
||||
questionStatus: "OPEN" | "CLOSED";
|
||||
currentUserId: string;
|
||||
initialMessages: Message[];
|
||||
}
|
||||
|
||||
function formatDate(iso: string) {
|
||||
return new Date(iso).toLocaleString("ru", {
|
||||
day: "numeric",
|
||||
month: "long",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
function formatFileSize(bytes: number) {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
export function QuestionThread({
|
||||
questionId,
|
||||
questionStatus,
|
||||
currentUserId,
|
||||
initialMessages,
|
||||
}: QuestionThreadProps) {
|
||||
const [messages, setMessages] = useState<Message[]>(initialMessages);
|
||||
const [text, setText] = useState("");
|
||||
const [files, setFiles] = useState<FileAttachment[]>([]);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [sending, setSending] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
async function handleFileSelect(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const selected = Array.from(e.target.files ?? []);
|
||||
if (!selected.length) return;
|
||||
setUploading(true);
|
||||
setError("");
|
||||
|
||||
try {
|
||||
const uploaded: FileAttachment[] = [];
|
||||
for (const f of selected) {
|
||||
const form = new FormData();
|
||||
form.append("file", f);
|
||||
const res = await fetch("/api/student/question-upload", { method: "POST", body: form });
|
||||
if (!res.ok) {
|
||||
const d = await res.json();
|
||||
throw new Error(d.error ?? "Ошибка загрузки файла");
|
||||
}
|
||||
uploaded.push(await res.json());
|
||||
}
|
||||
setFiles((prev) => [...prev, ...uploaded]);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Ошибка загрузки");
|
||||
} finally {
|
||||
setUploading(false);
|
||||
if (fileInputRef.current) fileInputRef.current.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSend() {
|
||||
if (!text.trim() && files.length === 0) return;
|
||||
setSending(true);
|
||||
setError("");
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/questions/${questionId}/messages`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ text: text.trim(), files }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const d = await res.json();
|
||||
throw new Error(d.error ?? "Ошибка отправки");
|
||||
}
|
||||
const msg = await res.json();
|
||||
setMessages((prev) => [...prev, msg]);
|
||||
setText("");
|
||||
setFiles([]);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Ошибка");
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2 w-full">
|
||||
{/* Messages */}
|
||||
<div className="flex flex-col gap-2 mb-4 max-h-96 overflow-y-auto pr-1">
|
||||
{messages.map((msg) => {
|
||||
const isMine = msg.authorId === currentUserId;
|
||||
const isNew = !msg.isRead && !isMine;
|
||||
return (
|
||||
<div
|
||||
key={msg.id}
|
||||
className="max-w-[88%] px-3 py-2 rounded-sm text-sm"
|
||||
style={{
|
||||
alignSelf: isMine ? "flex-start" : "flex-end",
|
||||
background: isMine ? "#E8E8E0" : "#F5F5F0",
|
||||
border: isMine ? "none" : `2px solid #E8F0D8`,
|
||||
borderLeft: !isMine && isNew ? "3px solid #323232" : undefined,
|
||||
}}
|
||||
>
|
||||
<p
|
||||
className="text-xs mb-1"
|
||||
style={{ color: "var(--muted-foreground)" }}
|
||||
>
|
||||
{isMine ? "Ты" : msg.author.name} · {formatDate(msg.createdAt)}
|
||||
{isNew && (
|
||||
<strong style={{ color: "#323232" }}> · 🔵 новое</strong>
|
||||
)}
|
||||
</p>
|
||||
<p style={{ color: "var(--foreground)" }}>{msg.text}</p>
|
||||
{msg.files && msg.files.length > 0 && (
|
||||
<div className="flex flex-col gap-1 mt-2">
|
||||
{msg.files.map((f, i) => (
|
||||
<a
|
||||
key={i}
|
||||
href={f.url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center gap-1.5 text-xs px-2 py-1 rounded-sm"
|
||||
style={{
|
||||
background: "#F5F5F0",
|
||||
border: "1px solid #AAAAAA",
|
||||
color: "var(--foreground)",
|
||||
width: "fit-content",
|
||||
}}
|
||||
>
|
||||
📎 <span>{f.name}</span>
|
||||
<span style={{ color: "#999" }}>· {formatFileSize(f.size)}</span>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Queued files preview */}
|
||||
{files.length > 0 && (
|
||||
<div className="flex flex-wrap gap-1 mb-2">
|
||||
{files.map((f, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="flex items-center gap-1 text-xs px-2 py-1 rounded-sm"
|
||||
style={{ background: "var(--surface)", border: "1px solid var(--border)" }}
|
||||
>
|
||||
📎 {f.name}
|
||||
<button
|
||||
onClick={() => setFiles((prev) => prev.filter((_, j) => j !== i))}
|
||||
className="ml-1 text-xs"
|
||||
style={{ color: "var(--muted-foreground)" }}
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Reply form */}
|
||||
<div
|
||||
className="rounded-sm p-2"
|
||||
style={{
|
||||
border: "2px solid #AAAAAA",
|
||||
background: "var(--surface)",
|
||||
opacity: questionStatus === "CLOSED" ? 0.5 : 1,
|
||||
pointerEvents: questionStatus === "CLOSED" ? "none" : "auto",
|
||||
}}
|
||||
>
|
||||
<textarea
|
||||
value={text}
|
||||
onChange={(e) => setText(e.target.value)}
|
||||
placeholder={questionStatus === "CLOSED" ? "Вопрос закрыт" : "Написать сообщение..."}
|
||||
rows={3}
|
||||
disabled={questionStatus === "CLOSED"}
|
||||
className="w-full text-sm outline-none resize-none bg-transparent"
|
||||
style={{ border: "none", color: "var(--foreground)" }}
|
||||
/>
|
||||
<div
|
||||
className="flex items-center justify-between pt-2 mt-1"
|
||||
style={{ borderTop: "1px solid #E8E8E0" }}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
multiple
|
||||
accept=".jpg,.jpeg,.png,.pdf,.md,.txt"
|
||||
className="hidden"
|
||||
onChange={handleFileSelect}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={uploading}
|
||||
className="text-xs px-2 py-1 rounded-sm"
|
||||
style={{ background: "var(--surface)", border: "1px solid #AAAAAA" }}
|
||||
>
|
||||
{uploading ? "Загрузка..." : "📎 Прикрепить"}
|
||||
</button>
|
||||
<span className="text-xs" style={{ color: "#999" }}>
|
||||
jpg, png, pdf, md · до 10 МБ
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSend}
|
||||
disabled={sending || (!text.trim() && files.length === 0)}
|
||||
className="text-xs font-bold px-4 py-1.5 rounded-sm"
|
||||
style={{
|
||||
background: "var(--foreground)",
|
||||
color: "var(--background)",
|
||||
border: "none",
|
||||
opacity: sending ? 0.6 : 1,
|
||||
}}
|
||||
>
|
||||
{sending ? "..." : "Отправить →"}
|
||||
</button>
|
||||
</div>
|
||||
{error && (
|
||||
<p className="text-xs mt-1" style={{ color: "#c00" }}>
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user