Initial commit: Edu Helper (Docker, React, Express, Prisma)
Made-with: Cursor
This commit is contained in:
@@ -0,0 +1,342 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Search, HelpCircle, BookOpen, Image as ImageIcon, ChevronDown, Trash2 } from "lucide-react";
|
||||
import { apiFetch } from "@/lib/utils";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import Markdown from "@/components/Markdown";
|
||||
|
||||
type Tab = "questions" | "textbooks" | "hall";
|
||||
|
||||
interface Question {
|
||||
id: number;
|
||||
text: string;
|
||||
answer: string | null;
|
||||
date: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface Textbook {
|
||||
id: number;
|
||||
topic: string;
|
||||
content: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface HallPhoto {
|
||||
id: number;
|
||||
date: string;
|
||||
imageUrl: string;
|
||||
createdAt: string;
|
||||
fileName: string;
|
||||
displayName: string;
|
||||
}
|
||||
|
||||
function groupByDate<T extends { date?: string; createdAt: string }>(
|
||||
items: T[],
|
||||
dateKey: "date" | "createdAt" = "createdAt"
|
||||
): Record<string, T[]> {
|
||||
const groups: Record<string, T[]> = {};
|
||||
for (const item of items) {
|
||||
const d = dateKey === "date" && "date" in item && item.date
|
||||
? item.date
|
||||
: item.createdAt.split("T")[0];
|
||||
if (!groups[d]) groups[d] = [];
|
||||
groups[d].push(item);
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
function formatDate(d: string): string {
|
||||
const date = new Date(d);
|
||||
const today = new Date();
|
||||
const yesterday = new Date();
|
||||
yesterday.setDate(yesterday.getDate() - 1);
|
||||
|
||||
if (d === today.toISOString().split("T")[0]) return "Сегодня";
|
||||
if (d === yesterday.toISOString().split("T")[0]) return "Вчера";
|
||||
return date.toLocaleDateString("ru", { day: "numeric", month: "long", year: "numeric" });
|
||||
}
|
||||
|
||||
export default function ArchivePage() {
|
||||
const { user } = useAuth();
|
||||
const canDeleteQuestions = user?.role === "STUDENT";
|
||||
const canManageHallPhotos = user?.username?.toLowerCase() === "konstantin";
|
||||
const [tab, setTab] = useState<Tab>("questions");
|
||||
const [search, setSearch] = useState("");
|
||||
const [questions, setQuestions] = useState<Question[]>([]);
|
||||
const [textbooks, setTextbooks] = useState<Textbook[]>([]);
|
||||
const [hall, setHall] = useState<HallPhoto[]>([]);
|
||||
const [expandedTextbook, setExpandedTextbook] = useState<number | null>(null);
|
||||
const [expandedQuestion, setExpandedQuestion] = useState<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
loadAll();
|
||||
}, []);
|
||||
|
||||
async function loadAll() {
|
||||
try { setQuestions(await apiFetch<Question[]>("/questions")); } catch {}
|
||||
try { setTextbooks(await apiFetch<Textbook[]>("/textbooks")); } catch {}
|
||||
try { setHall(await apiFetch<HallPhoto[]>("/reports")); } catch {}
|
||||
}
|
||||
|
||||
async function deleteQuestion(id: number) {
|
||||
if (!canDeleteQuestions || !confirm("Удалить этот вопрос безвозвратно?")) return;
|
||||
try {
|
||||
await apiFetch(`/questions/${id}`, { method: "DELETE" });
|
||||
setQuestions((prev) => prev.filter((q) => q.id !== id));
|
||||
} catch (err: unknown) {
|
||||
alert(err instanceof Error ? err.message : "Ошибка");
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteHallPhoto(id: number) {
|
||||
if (!canManageHallPhotos || !confirm("Удалить это фото?")) return;
|
||||
try {
|
||||
await apiFetch(`/reports/${id}`, { method: "DELETE" });
|
||||
setHall((prev) => prev.filter((h) => h.id !== id));
|
||||
} catch (err: unknown) {
|
||||
alert(err instanceof Error ? err.message : "Ошибка");
|
||||
}
|
||||
}
|
||||
|
||||
const tabs: { key: Tab; label: string; icon: typeof HelpCircle; count: number }[] = [
|
||||
{ key: "questions", label: "Вопросы", icon: HelpCircle, count: questions.length },
|
||||
{ key: "textbooks", label: "Учебники", icon: BookOpen, count: textbooks.length },
|
||||
{ key: "hall", label: "Зал", icon: ImageIcon, count: hall.length },
|
||||
];
|
||||
|
||||
const filteredQuestions = questions.filter(
|
||||
(q) => q.text.toLowerCase().includes(search.toLowerCase()) ||
|
||||
(q.answer && q.answer.toLowerCase().includes(search.toLowerCase()))
|
||||
);
|
||||
|
||||
const filteredTextbooks = textbooks.filter(
|
||||
(t) => t.topic.toLowerCase().includes(search.toLowerCase()) ||
|
||||
t.content.toLowerCase().includes(search.toLowerCase())
|
||||
);
|
||||
|
||||
const filteredHall = hall.filter((r) =>
|
||||
r.date.toLowerCase().includes(search.toLowerCase())
|
||||
);
|
||||
|
||||
const questionGroups = groupByDate(filteredQuestions, "date");
|
||||
const textbookGroups = groupByDate(filteredTextbooks);
|
||||
const hallGroups = groupByDate(filteredHall, "date");
|
||||
|
||||
const sortedDates = (groups: Record<string, unknown[]>) =>
|
||||
Object.keys(groups).sort((a, b) => b.localeCompare(a));
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">Архив</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">Все материалы, сгруппированные по дням</p>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="flex gap-1 p-1 bg-muted rounded-xl">
|
||||
{tabs.map(({ key, label, icon: Icon, count }) => (
|
||||
<button
|
||||
key={key}
|
||||
onClick={() => { setTab(key); setSearch(""); }}
|
||||
className={`flex-1 flex items-center justify-center gap-2 py-2 rounded-lg text-xs font-medium transition-all duration-200 cursor-pointer ${
|
||||
tab === key
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
}`}
|
||||
>
|
||||
<Icon size={14} />
|
||||
{label}
|
||||
<span className={`text-[10px] px-1.5 py-0.5 rounded-full ${
|
||||
tab === key ? "bg-primary/10 text-primary" : "bg-muted-foreground/10"
|
||||
}`}>
|
||||
{count}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Search */}
|
||||
<div className="relative">
|
||||
<Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder={`Поиск по ${tab === "questions" ? "вопросам" : tab === "textbooks" ? "учебникам" : "фото"}...`}
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Questions */}
|
||||
{tab === "questions" && (
|
||||
<div className="space-y-5">
|
||||
{sortedDates(questionGroups).map((date) => (
|
||||
<div key={date} className="animate-fade-in">
|
||||
<h3 className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2">
|
||||
{formatDate(date)}
|
||||
<span className="ml-2 text-[10px] opacity-60">({questionGroups[date].length})</span>
|
||||
</h3>
|
||||
<div className="space-y-2">
|
||||
{questionGroups[date].map((q) => (
|
||||
<Card key={q.id}>
|
||||
<CardContent className="pt-4 pb-4">
|
||||
<div className="flex items-start gap-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpandedQuestion(expandedQuestion === q.id ? null : q.id)}
|
||||
className="flex-1 min-w-0 text-left flex items-start justify-between gap-2 cursor-pointer"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="text-sm font-medium">{q.text}</p>
|
||||
{q.answer && expandedQuestion !== q.id && (
|
||||
<p className="text-xs text-muted-foreground mt-1 line-clamp-1">{q.answer.slice(0, 100)}...</p>
|
||||
)}
|
||||
</div>
|
||||
{q.answer && (
|
||||
<ChevronDown
|
||||
size={15}
|
||||
className={`text-muted-foreground shrink-0 mt-0.5 transition-transform duration-200 ${
|
||||
expandedQuestion === q.id ? "rotate-180" : ""
|
||||
}`}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
{canDeleteQuestions && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8 shrink-0 text-destructive"
|
||||
title="Удалить вопрос"
|
||||
type="button"
|
||||
onClick={() => deleteQuestion(q.id)}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{expandedQuestion === q.id && q.answer && (
|
||||
<div className="mt-3 pt-3 border-t animate-fade-in">
|
||||
<Markdown className="text-[13px]">{q.answer}</Markdown>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{filteredQuestions.length === 0 && (
|
||||
<p className="text-center text-sm text-muted-foreground py-12">
|
||||
{search ? "Ничего не найдено" : "Нет вопросов"}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Textbooks */}
|
||||
{tab === "textbooks" && (
|
||||
<div className="space-y-5">
|
||||
{sortedDates(textbookGroups).map((date) => (
|
||||
<div key={date} className="animate-fade-in">
|
||||
<h3 className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2">
|
||||
{formatDate(date)}
|
||||
</h3>
|
||||
<div className="space-y-2">
|
||||
{textbookGroups[date].map((tb) => (
|
||||
<Card key={tb.id}>
|
||||
<CardContent className="pt-4 pb-4">
|
||||
<button
|
||||
onClick={() => setExpandedTextbook(expandedTextbook === tb.id ? null : tb.id)}
|
||||
className="w-full text-left flex items-center justify-between cursor-pointer"
|
||||
>
|
||||
<span className="text-sm font-medium">{tb.topic}</span>
|
||||
<ChevronDown
|
||||
size={15}
|
||||
className={`text-muted-foreground shrink-0 transition-transform duration-200 ${
|
||||
expandedTextbook === tb.id ? "rotate-180" : ""
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
{expandedTextbook === tb.id && (
|
||||
<div className="mt-3 pt-3 border-t animate-fade-in">
|
||||
<Markdown className="text-[13px]">{tb.content}</Markdown>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{filteredTextbooks.length === 0 && (
|
||||
<p className="text-center text-sm text-muted-foreground py-12">
|
||||
{search ? "Ничего не найдено" : "Нет учебников"}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Hall */}
|
||||
{tab === "hall" && (
|
||||
<div className="space-y-5">
|
||||
{sortedDates(hallGroups).map((date) => (
|
||||
<div key={date} className="animate-fade-in">
|
||||
<h3 className="text-xs font-medium text-muted-foreground uppercase tracking-wider mb-2">
|
||||
{formatDate(date)}
|
||||
</h3>
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 gap-3">
|
||||
{hallGroups[date].map((r) => {
|
||||
const label = r.displayName || r.fileName;
|
||||
return (
|
||||
<div
|
||||
key={r.id}
|
||||
className="relative flex flex-col rounded-xl overflow-hidden border bg-accent/20 hover:shadow-sm transition"
|
||||
>
|
||||
<div className="relative">
|
||||
<button
|
||||
type="button"
|
||||
className="block w-full"
|
||||
onClick={() => window.open(r.imageUrl, "_blank", "noopener,noreferrer")}
|
||||
>
|
||||
<img src={r.imageUrl} alt={label} className="w-full h-36 object-cover" />
|
||||
</button>
|
||||
{canManageHallPhotos && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
className="absolute top-2 right-2 h-8 w-8 opacity-90 shadow-md"
|
||||
title="Удалить"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
deleteHallPhoto(r.id);
|
||||
}}
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p
|
||||
className="text-[11px] px-2 py-1.5 text-muted-foreground truncate border-t bg-background/95"
|
||||
title={label}
|
||||
>
|
||||
{label}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{filteredHall.length === 0 && (
|
||||
<p className="text-center text-sm text-muted-foreground py-12">
|
||||
{search ? "Ничего не найдено" : "Нет фото"}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
import { useState, useEffect, useRef } from "react";
|
||||
import { Send, Trash2, Sparkles } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { getGreeting, apiFetch, API_BASE } from "@/lib/utils";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import Markdown from "@/components/Markdown";
|
||||
|
||||
interface ChatMsg {
|
||||
id?: number;
|
||||
role: "user" | "assistant";
|
||||
content: string;
|
||||
}
|
||||
|
||||
export default function HomePage() {
|
||||
const { user } = useAuth();
|
||||
const [messages, setMessages] = useState<ChatMsg[]>([]);
|
||||
const [input, setInput] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const bottomRef = useRef<HTMLDivElement>(null);
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
apiFetch<ChatMsg[]>("/chat/history").then(setMessages).catch(() => {});
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
bottomRef.current?.scrollIntoView({ behavior: "smooth" });
|
||||
}, [messages]);
|
||||
|
||||
function autoResize() {
|
||||
const el = inputRef.current;
|
||||
if (el) {
|
||||
el.style.height = "auto";
|
||||
el.style.height = Math.min(el.scrollHeight, 150) + "px";
|
||||
}
|
||||
}
|
||||
|
||||
async function sendMessage() {
|
||||
if (!input.trim() || loading) return;
|
||||
const text = input.trim();
|
||||
setInput("");
|
||||
if (inputRef.current) inputRef.current.style.height = "auto";
|
||||
setMessages((prev) => [...prev, { role: "user", content: text }]);
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/chat`, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ message: text }),
|
||||
});
|
||||
|
||||
const reader = res.body?.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let assistantContent = "";
|
||||
setMessages((prev) => [...prev, { role: "assistant", content: "" }]);
|
||||
|
||||
while (reader) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
const chunk = decoder.decode(value);
|
||||
const lines = chunk.split("\n").filter((l) => l.startsWith("data: "));
|
||||
|
||||
for (const line of lines) {
|
||||
const data = line.slice(6);
|
||||
if (data === "[DONE]") break;
|
||||
try {
|
||||
const parsed = JSON.parse(data);
|
||||
if (parsed.content) {
|
||||
assistantContent += parsed.content;
|
||||
setMessages((prev) => {
|
||||
const updated = [...prev];
|
||||
updated[updated.length - 1] = { role: "assistant", content: assistantContent };
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
} catch { /* skip */ }
|
||||
}
|
||||
}
|
||||
} catch (err: any) {
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{ role: "assistant", content: `Ошибка: ${err.message}` },
|
||||
]);
|
||||
}
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
async function clearHistory() {
|
||||
await apiFetch("/chat/history", { method: "DELETE" });
|
||||
setMessages([]);
|
||||
}
|
||||
|
||||
function handleKeyDown(e: React.KeyboardEvent) {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
sendMessage();
|
||||
}
|
||||
}
|
||||
|
||||
const isEmpty = messages.length === 0;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-[calc(100vh-3rem)]">
|
||||
{/* Header */}
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">
|
||||
{getGreeting()}
|
||||
{user?.displayName ? `, ${user.displayName}` : user?.username ? `, ${user.username}` : ""}
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground mt-0.5">
|
||||
Чем могу помочь сегодня?
|
||||
</p>
|
||||
</div>
|
||||
{!isEmpty && (
|
||||
<Button variant="ghost" size="sm" onClick={clearHistory} className="text-muted-foreground">
|
||||
<Trash2 size={15} />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Messages */}
|
||||
<div className="flex-1 overflow-y-auto py-4 space-y-5">
|
||||
{isEmpty && (
|
||||
<div className="flex flex-col items-center justify-center h-full text-center animate-fade-in">
|
||||
<div className="w-14 h-14 rounded-2xl bg-accent flex items-center justify-center mb-5 animate-float">
|
||||
<Sparkles size={26} className="text-primary" />
|
||||
</div>
|
||||
<h2 className="text-lg font-semibold mb-2">ИИ-ассистент</h2>
|
||||
<p className="text-sm text-muted-foreground max-w-sm leading-relaxed">
|
||||
Задайте любой вопрос — я постараюсь объяснить максимально понятно
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{messages.map((msg, i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="animate-fade-in"
|
||||
style={{ animationDelay: `${Math.min(i * 30, 200)}ms` }}
|
||||
>
|
||||
{msg.role === "user" ? (
|
||||
<div className="flex justify-end">
|
||||
<div className="max-w-[75%] bg-primary text-primary-foreground rounded-2xl rounded-br-md px-4 py-2.5 text-[14px] leading-relaxed shadow-sm">
|
||||
{msg.content}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex gap-3">
|
||||
<div className={`w-7 h-7 rounded-lg bg-accent flex items-center justify-center shrink-0 mt-0.5 ${
|
||||
loading && i === messages.length - 1 ? "" : ""
|
||||
}`}>
|
||||
<Sparkles
|
||||
size={14}
|
||||
className={`text-primary ${loading && i === messages.length - 1 ? "animate-spin-glow" : ""}`}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
{msg.content ? (
|
||||
<Markdown>{msg.content}</Markdown>
|
||||
) : (
|
||||
<div className="typing-indicator flex items-center gap-1 py-3">
|
||||
<span /><span /><span />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
<div ref={bottomRef} />
|
||||
</div>
|
||||
|
||||
{/* Input */}
|
||||
<div className="pt-3 pb-1">
|
||||
<div className="relative flex items-end gap-2 rounded-2xl border bg-background p-2 shadow-sm transition-shadow focus-within:shadow-md focus-within:shadow-primary/5 focus-within:border-primary/30">
|
||||
<textarea
|
||||
ref={inputRef}
|
||||
value={input}
|
||||
onChange={(e) => { setInput(e.target.value); autoResize(); }}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Напишите сообщение..."
|
||||
disabled={loading}
|
||||
rows={1}
|
||||
className="flex-1 resize-none bg-transparent px-2 py-1.5 text-sm outline-none placeholder:text-muted-foreground disabled:opacity-50 max-h-[150px]"
|
||||
/>
|
||||
<Button
|
||||
onClick={sendMessage}
|
||||
disabled={loading || !input.trim()}
|
||||
size="icon"
|
||||
className="shrink-0 h-8 w-8 rounded-xl"
|
||||
>
|
||||
<Send size={15} />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Loader2, Sparkles } from "lucide-react";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { API_BASE } from "@/lib/utils";
|
||||
|
||||
export default function LoginPage() {
|
||||
const navigate = useNavigate();
|
||||
const { user, loading, setUser } = useAuth();
|
||||
const [username, setUsername] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
if (!loading && user) navigate("/", { replace: true });
|
||||
}, [loading, user, navigate]);
|
||||
|
||||
async function onSubmit(e: React.FormEvent) {
|
||||
e.preventDefault();
|
||||
setError("");
|
||||
setSubmitting(true);
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/auth/login`, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ username: username.trim(), password }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) {
|
||||
setError(data.error || `Ошибка ${res.status}`);
|
||||
return;
|
||||
}
|
||||
setUser(data.user);
|
||||
navigate("/", { replace: true });
|
||||
} catch {
|
||||
setError("Сеть недоступна");
|
||||
} finally {
|
||||
setSubmitting(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-background">
|
||||
<Loader2 className="animate-spin text-primary" size={28} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-background p-4">
|
||||
<Card className="w-full max-w-md border-border/80 shadow-lg">
|
||||
<CardHeader className="text-center space-y-2">
|
||||
<div className="mx-auto w-10 h-10 rounded-xl bg-primary flex items-center justify-center">
|
||||
<Sparkles size={20} className="text-white" />
|
||||
</div>
|
||||
<CardTitle className="text-lg">EduHelper</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">Войдите, чтобы продолжить</p>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={onSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="username">Имя пользователя</Label>
|
||||
<Input
|
||||
id="username"
|
||||
autoComplete="username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
disabled={submitting}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="password">Пароль</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
disabled={submitting}
|
||||
/>
|
||||
</div>
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
<Button type="submit" className="w-full" disabled={submitting || !username.trim() || !password}>
|
||||
{submitting ? <Loader2 size={16} className="animate-spin" /> : "Войти"}
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Loader2, Sparkles, Plus, Send, Search, Trash2 } from "lucide-react";
|
||||
import { apiFetch, todayDate, API_BASE } from "@/lib/utils";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import Markdown from "@/components/Markdown";
|
||||
|
||||
interface Question {
|
||||
id: number;
|
||||
text: string;
|
||||
answer: string | null;
|
||||
date: string;
|
||||
}
|
||||
|
||||
export default function QuestionsPage() {
|
||||
const { user } = useAuth();
|
||||
const canDeleteOwn = user?.role === "STUDENT";
|
||||
const [fields, setFields] = useState<string[]>([]);
|
||||
const [saved, setSaved] = useState<Question[]>([]);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [answeringId, setAnsweringId] = useState<number | null>(null);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
useEffect(() => {
|
||||
loadQuestions();
|
||||
}, []);
|
||||
|
||||
async function loadQuestions() {
|
||||
try {
|
||||
const data = await apiFetch<Question[]>(`/questions?date=${todayDate()}`);
|
||||
setSaved(data);
|
||||
updateFieldCount(data.length);
|
||||
} catch {
|
||||
updateFieldCount(0);
|
||||
}
|
||||
}
|
||||
|
||||
function updateFieldCount(savedCount: number) {
|
||||
const needed = Math.max(1, 5 - savedCount);
|
||||
setFields(Array(needed).fill(""));
|
||||
}
|
||||
|
||||
function updateField(index: number, value: string) {
|
||||
setFields((prev) => { const c = [...prev]; c[index] = value; return c; });
|
||||
}
|
||||
|
||||
async function saveQuestions() {
|
||||
const nonEmpty = fields.filter((f) => f.trim());
|
||||
if (nonEmpty.length === 0) return;
|
||||
|
||||
setSaving(true);
|
||||
try {
|
||||
const data = await apiFetch<Question[]>("/questions", {
|
||||
method: "POST", body: JSON.stringify({ questions: nonEmpty }),
|
||||
});
|
||||
const newSaved = [...saved, ...data];
|
||||
setSaved(newSaved);
|
||||
updateFieldCount(newSaved.length);
|
||||
} catch (err: any) { alert(err.message); }
|
||||
setSaving(false);
|
||||
}
|
||||
|
||||
async function getAnswer(question: Question) {
|
||||
if (question.answer || answeringId === question.id) return;
|
||||
setAnsweringId(question.id);
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/questions/${question.id}/answer`, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
});
|
||||
const reader = res.body?.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let fullAnswer = "";
|
||||
|
||||
while (reader) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
for (const line of decoder.decode(value).split("\n").filter((l) => l.startsWith("data: "))) {
|
||||
const data = line.slice(6);
|
||||
if (data === "[DONE]") break;
|
||||
try {
|
||||
const parsed = JSON.parse(data);
|
||||
if (parsed.content) {
|
||||
fullAnswer += parsed.content;
|
||||
setSaved((prev) => prev.map((q) => q.id === question.id ? { ...q, answer: fullAnswer } : q));
|
||||
}
|
||||
} catch { /* skip */ }
|
||||
}
|
||||
}
|
||||
} catch (err: any) { alert(err.message); }
|
||||
setAnsweringId(null);
|
||||
}
|
||||
|
||||
async function deleteQuestion(id: number) {
|
||||
if (!canDeleteOwn || !confirm("Удалить этот вопрос безвозвратно?")) return;
|
||||
try {
|
||||
await apiFetch(`/questions/${id}`, { method: "DELETE" });
|
||||
const next = saved.filter((q) => q.id !== id);
|
||||
setSaved(next);
|
||||
updateFieldCount(next.length);
|
||||
} catch (err: any) {
|
||||
alert(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
const unanswered = saved.filter((q) =>
|
||||
!q.answer && (!search || q.text.toLowerCase().includes(search.toLowerCase()))
|
||||
);
|
||||
const answered = saved.filter((q) =>
|
||||
q.answer && (!search || q.text.toLowerCase().includes(search.toLowerCase()) || q.answer.toLowerCase().includes(search.toLowerCase()))
|
||||
);
|
||||
const todaySavedCount = saved.length;
|
||||
const remaining = Math.max(0, 5 - todaySavedCount);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">Ежедневные вопросы</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{remaining > 0
|
||||
? `Ещё ${remaining} из 5 обязательных вопросов`
|
||||
: `Норма выполнена (${todaySavedCount} вопросов)`}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* New questions form */}
|
||||
<Card>
|
||||
<CardContent className="pt-5 space-y-3">
|
||||
{fields.map((val, i) => (
|
||||
<div key={i} className="animate-fade-in" style={{ animationDelay: `${i * 50}ms` }}>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-medium text-muted-foreground w-4 text-right shrink-0">
|
||||
{todaySavedCount + i + 1}
|
||||
</span>
|
||||
<Input
|
||||
value={val}
|
||||
onChange={(e) => updateField(i, e.target.value)}
|
||||
placeholder={`Вопрос...`}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
<div className="flex gap-2 pt-2 ml-6">
|
||||
<Button variant="outline" size="sm" onClick={() => setFields((p) => [...p, ""])}>
|
||||
<Plus size={14} />
|
||||
Ещё
|
||||
</Button>
|
||||
<Button size="sm" onClick={saveQuestions} disabled={saving || fields.every((f) => !f.trim())}>
|
||||
{saving ? <Loader2 size={14} className="animate-spin" /> : <Send size={14} />}
|
||||
Сохранить
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Search */}
|
||||
{saved.length > 0 && (
|
||||
<div className="relative">
|
||||
<Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Поиск по вопросам..."
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Unanswered first */}
|
||||
{unanswered.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
|
||||
Ожидают ответа ({unanswered.length})
|
||||
</h2>
|
||||
{unanswered.map((q, i) => (
|
||||
<Card key={q.id} className="animate-fade-in border-orange-200/60" style={{ animationDelay: `${i * 40}ms` }}>
|
||||
<CardContent className="pt-5 space-y-3">
|
||||
<p className="text-[14px] font-medium">{q.text}</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => getAnswer(q)}
|
||||
disabled={answeringId === q.id}
|
||||
>
|
||||
{answeringId === q.id ? (
|
||||
<>
|
||||
<Sparkles size={13} className="animate-spin-glow" />
|
||||
Генерация...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Sparkles size={13} />
|
||||
Получить ответ
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
{canDeleteOwn && (
|
||||
<Button variant="ghost" size="sm" className="text-destructive" onClick={() => deleteQuestion(q.id)}>
|
||||
<Trash2 size={13} />
|
||||
Удалить
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Answered below */}
|
||||
{answered.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
|
||||
С ответами ({answered.length})
|
||||
</h2>
|
||||
{answered.map((q, i) => (
|
||||
<Card key={q.id} className="animate-fade-in" style={{ animationDelay: `${i * 40}ms` }}>
|
||||
<CardContent className="pt-5 space-y-3">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<p className="text-[14px] font-medium flex-1">{q.text}</p>
|
||||
{canDeleteOwn && (
|
||||
<Button variant="ghost" size="icon" className="shrink-0 text-destructive h-8 w-8" onClick={() => deleteQuestion(q.id)} title="Удалить вопрос">
|
||||
<Trash2 size={14} />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<div className="bg-accent/50 rounded-xl p-4">
|
||||
<Markdown className="text-[13px]" exportable exportTitle={`question-${q.id}`}>{q.answer!}</Markdown>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { API_BASE, apiFetch, todayDate } from "@/lib/utils";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { Calendar, ImagePlus, Loader2, Trash2 } from "lucide-react";
|
||||
|
||||
interface HallPhoto {
|
||||
id: number;
|
||||
date: string;
|
||||
createdAt: string;
|
||||
imageUrl: string;
|
||||
fileName: string;
|
||||
displayName: string;
|
||||
}
|
||||
|
||||
export default function ReportPage() {
|
||||
const { user } = useAuth();
|
||||
const canManagePhotos =
|
||||
user?.username?.toLowerCase() === "konstantin";
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [photos, setPhotos] = useState<HallPhoto[]>([]);
|
||||
const [selectedDate, setSelectedDate] = useState(todayDate());
|
||||
const [uploading, setUploading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
loadPhotos();
|
||||
}, []);
|
||||
|
||||
async function loadPhotos() {
|
||||
try {
|
||||
setPhotos(await apiFetch<HallPhoto[]>("/reports"));
|
||||
} catch {
|
||||
setPhotos([]);
|
||||
}
|
||||
}
|
||||
|
||||
async function onFileChange(e: React.ChangeEvent<HTMLInputElement>) {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
const formData = new FormData();
|
||||
formData.append("photo", file);
|
||||
formData.append("date", selectedDate);
|
||||
|
||||
setUploading(true);
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/reports/upload`, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
body: formData,
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({ error: "Ошибка загрузки" }));
|
||||
throw new Error(err.error || `HTTP ${res.status}`);
|
||||
}
|
||||
await loadPhotos();
|
||||
} catch (err: any) {
|
||||
alert(err.message);
|
||||
} finally {
|
||||
setUploading(false);
|
||||
e.target.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
async function deletePhoto(id: number) {
|
||||
if (!confirm("Удалить это фото?")) return;
|
||||
try {
|
||||
await apiFetch(`/reports/${id}`, { method: "DELETE" });
|
||||
await loadPhotos();
|
||||
} catch (err: unknown) {
|
||||
alert(err instanceof Error ? err.message : "Ошибка");
|
||||
}
|
||||
}
|
||||
|
||||
const grouped = useMemo(() => {
|
||||
const g: Record<string, HallPhoto[]> = {};
|
||||
for (const p of photos) {
|
||||
if (!g[p.date]) g[p.date] = [];
|
||||
g[p.date].push(p);
|
||||
}
|
||||
return g;
|
||||
}, [photos]);
|
||||
|
||||
const sortedDates = Object.keys(grouped).sort((a, b) => b.localeCompare(a));
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between gap-2 flex-wrap">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">Зал</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{canManagePhotos
|
||||
? "Загружайте фото и просматривайте их по датам"
|
||||
: "Просмотр фото ученика по датам"}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{canManagePhotos && (
|
||||
<Card>
|
||||
<CardContent className="pt-5 flex flex-wrap items-end gap-3">
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs text-muted-foreground">Дата</label>
|
||||
<Input type="date" value={selectedDate} onChange={(e) => setSelectedDate(e.target.value)} />
|
||||
</div>
|
||||
<div className="flex flex-col justify-end gap-0">
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
onChange={onFileChange}
|
||||
disabled={uploading}
|
||||
className="sr-only"
|
||||
tabIndex={-1}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={uploading}
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
>
|
||||
{uploading ? <Loader2 size={15} className="animate-spin" /> : <ImagePlus size={15} />}
|
||||
Прикрепить фото
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{sortedDates.map((date) => (
|
||||
<div key={date} className="space-y-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar size={14} className="text-muted-foreground" />
|
||||
<h2 className="text-sm font-medium">{date}</h2>
|
||||
<span className="text-xs text-muted-foreground">({grouped[date].length})</span>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 md:grid-cols-3 gap-3">
|
||||
{grouped[date].map((p) => {
|
||||
const label = p.displayName || p.fileName;
|
||||
return (
|
||||
<div
|
||||
key={p.id}
|
||||
className="relative group flex flex-col rounded-xl overflow-hidden border bg-accent/20 hover:shadow-sm transition"
|
||||
>
|
||||
<div className="relative">
|
||||
<button
|
||||
type="button"
|
||||
className="block w-full text-left"
|
||||
onClick={() => window.open(p.imageUrl, "_blank", "noopener,noreferrer")}
|
||||
>
|
||||
<img
|
||||
src={p.imageUrl}
|
||||
alt={label}
|
||||
loading="lazy"
|
||||
className="w-full h-40 object-cover group-hover:scale-[1.02] transition"
|
||||
/>
|
||||
</button>
|
||||
{canManagePhotos && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="destructive"
|
||||
size="icon"
|
||||
className="absolute top-2 right-2 h-8 w-8 opacity-90 shadow-md"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
deletePhoto(p.id);
|
||||
}}
|
||||
title="Удалить"
|
||||
>
|
||||
<Trash2 size={14} />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p
|
||||
className="text-[11px] px-2 py-1.5 text-muted-foreground truncate border-t bg-background/95"
|
||||
title={label}
|
||||
>
|
||||
{label}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{photos.length === 0 && (
|
||||
<div className="text-center py-12 text-sm text-muted-foreground">
|
||||
{canManagePhotos
|
||||
? "Пока нет фото. Добавьте первое изображение."
|
||||
: "Пока нет фото."}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Save, Loader2, CheckCircle2, Key, MessageSquare } from "lucide-react";
|
||||
import { apiFetch } from "@/lib/utils";
|
||||
import { useAuth } from "@/context/AuthContext";
|
||||
import { Navigate } from "react-router-dom";
|
||||
|
||||
const PROMPT_FIELDS = [
|
||||
{
|
||||
key: "prompt_answer",
|
||||
label: "Промпт для ответов на вопросы",
|
||||
description: "Используется при нажатии «Получить ответ» в разделе вопросов",
|
||||
placeholder:
|
||||
"Ты — помощник-репетитор. Ответь на вопрос ученика максимально подробно и понятно...",
|
||||
},
|
||||
{
|
||||
key: "prompt_textbook",
|
||||
label: "Промпт для генерации учебника",
|
||||
description: "Используется при генерации учебника по теме",
|
||||
placeholder:
|
||||
"Составь учебный материал по указанной теме. Объясняй просто, с примерами из жизни...",
|
||||
},
|
||||
{
|
||||
key: "prompt_test",
|
||||
label: "Промпт для генерации теста",
|
||||
description: "Используется при создании теста из 10 вопросов",
|
||||
placeholder:
|
||||
"Сгенерируй тест из 10 вопросов с 4 вариантами ответа. Верни JSON-массив...",
|
||||
},
|
||||
{
|
||||
key: "prompt_report",
|
||||
label: "Промпт для ежедневного отчёта",
|
||||
description: "Используется при генерации отчёта за день",
|
||||
placeholder:
|
||||
'Составь отчёт в формате: "Алексей Михайлович, добрый вечер, за сегодня я узнал..."',
|
||||
},
|
||||
];
|
||||
|
||||
export default function SettingsPage() {
|
||||
const { user } = useAuth();
|
||||
if (user?.role !== "TUTOR") {
|
||||
return <Navigate to="/" replace />;
|
||||
}
|
||||
|
||||
const [apiKey, setApiKey] = useState("");
|
||||
const [prompts, setPrompts] = useState<Record<string, string>>({});
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
|
||||
useEffect(() => { loadSettings(); }, []);
|
||||
|
||||
async function loadSettings() {
|
||||
try {
|
||||
const data = await apiFetch<Record<string, string>>("/settings/raw");
|
||||
setApiKey(data.deepseek_api_key || "");
|
||||
const p: Record<string, string> = {};
|
||||
for (const f of PROMPT_FIELDS) p[f.key] = data[f.key] || "";
|
||||
setPrompts(p);
|
||||
} catch { /* first time */ }
|
||||
}
|
||||
|
||||
async function saveSettings() {
|
||||
setSaving(true);
|
||||
setSaved(false);
|
||||
const settings: Record<string, string> = { deepseek_api_key: apiKey };
|
||||
for (const [k, v] of Object.entries(prompts)) {
|
||||
if (v.trim()) settings[k] = v.trim();
|
||||
}
|
||||
try {
|
||||
await apiFetch("/settings", { method: "PUT", body: JSON.stringify(settings) });
|
||||
setSaved(true);
|
||||
setTimeout(() => setSaved(false), 3000);
|
||||
} catch (err: any) { alert(err.message); }
|
||||
setSaving(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">Настройки</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">API-ключ и промпты для ИИ-ассистента</p>
|
||||
</div>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="flex items-center gap-2 text-sm">
|
||||
<Key size={15} className="text-primary" />
|
||||
API-ключ DeepSeek
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
<Input
|
||||
type="password"
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
placeholder="sk-..."
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Получите на{" "}
|
||||
<a href="https://platform.deepseek.com" target="_blank" className="text-primary hover:underline">
|
||||
platform.deepseek.com
|
||||
</a>
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-2">
|
||||
<CardTitle className="flex items-center gap-2 text-sm">
|
||||
<MessageSquare size={15} className="text-primary" />
|
||||
Промпты
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-5">
|
||||
{PROMPT_FIELDS.map((field) => (
|
||||
<div key={field.key} className="space-y-1.5">
|
||||
<Label htmlFor={field.key} className="text-[13px]">{field.label}</Label>
|
||||
<p className="text-xs text-muted-foreground">{field.description}</p>
|
||||
<Textarea
|
||||
id={field.key}
|
||||
value={prompts[field.key] || ""}
|
||||
onChange={(e) => setPrompts((p) => ({ ...p, [field.key]: e.target.value }))}
|
||||
placeholder={field.placeholder}
|
||||
className="min-h-[90px] text-[13px]"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Button onClick={saveSettings} disabled={saving} className="w-full">
|
||||
{saving ? (
|
||||
<Loader2 size={15} className="animate-spin" />
|
||||
) : saved ? (
|
||||
<CheckCircle2 size={15} />
|
||||
) : (
|
||||
<Save size={15} />
|
||||
)}
|
||||
{saved ? "Сохранено" : "Сохранить настройки"}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Loader2, ClipboardList, CheckCircle2, XCircle, RotateCcw, MessageSquare } from "lucide-react";
|
||||
import { apiFetch } from "@/lib/utils";
|
||||
|
||||
interface TestQuestion {
|
||||
question: string;
|
||||
options: Record<string, string>;
|
||||
correct: string;
|
||||
}
|
||||
|
||||
interface Test {
|
||||
id: number;
|
||||
topic: string;
|
||||
questions: string;
|
||||
createdAt: string;
|
||||
results: TestResult[];
|
||||
}
|
||||
|
||||
interface TestResult {
|
||||
id?: number;
|
||||
score: number;
|
||||
total: number;
|
||||
/** false для наставника — результат не сохраняется в БД */
|
||||
persisted?: boolean;
|
||||
}
|
||||
|
||||
type Phase = "setup" | "generating" | "taking" | "results";
|
||||
|
||||
export default function TestPage() {
|
||||
const [phase, setPhase] = useState<Phase>("setup");
|
||||
const [topic, setTopic] = useState("");
|
||||
const [fromQuestions, setFromQuestions] = useState(false);
|
||||
const [testId, setTestId] = useState<number | null>(null);
|
||||
const [questions, setQuestions] = useState<TestQuestion[]>([]);
|
||||
const [answers, setAnswers] = useState<Record<string, string>>({});
|
||||
const [result, setResult] = useState<TestResult | null>(null);
|
||||
const [tests, setTests] = useState<Test[]>([]);
|
||||
const [currentQ, setCurrentQ] = useState(0);
|
||||
|
||||
useEffect(() => { loadTests(); }, []);
|
||||
|
||||
async function loadTests() {
|
||||
try { setTests(await apiFetch<Test[]>("/tests")); } catch { /* empty */ }
|
||||
}
|
||||
|
||||
async function generateTest() {
|
||||
setPhase("generating");
|
||||
try {
|
||||
const body: Record<string, unknown> = fromQuestions
|
||||
? { fromQuestions: true }
|
||||
: { topic: topic.trim() };
|
||||
|
||||
if (!fromQuestions && !topic.trim()) {
|
||||
alert("Введите тему");
|
||||
setPhase("setup");
|
||||
return;
|
||||
}
|
||||
|
||||
const test = await apiFetch<Test>("/tests/generate", {
|
||||
method: "POST", body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
setTestId(test.id);
|
||||
setQuestions(JSON.parse(test.questions));
|
||||
setAnswers({});
|
||||
setCurrentQ(0);
|
||||
setPhase("taking");
|
||||
} catch (err: any) { alert(err.message); setPhase("setup"); }
|
||||
}
|
||||
|
||||
async function submitTest() {
|
||||
if (!testId) return;
|
||||
try {
|
||||
const res = await apiFetch<TestResult>(`/tests/${testId}/submit`, {
|
||||
method: "POST", body: JSON.stringify({ answers }),
|
||||
});
|
||||
setResult(res);
|
||||
setPhase("results");
|
||||
loadTests();
|
||||
} catch (err: any) { alert(err.message); }
|
||||
}
|
||||
|
||||
function reset() {
|
||||
setPhase("setup");
|
||||
setTopic("");
|
||||
setFromQuestions(false);
|
||||
setQuestions([]);
|
||||
setAnswers({});
|
||||
setResult(null);
|
||||
setTestId(null);
|
||||
setCurrentQ(0);
|
||||
}
|
||||
|
||||
function retakeTest(test: Test) {
|
||||
setTestId(test.id);
|
||||
setQuestions(JSON.parse(test.questions));
|
||||
setAnswers({});
|
||||
setCurrentQ(0);
|
||||
setResult(null);
|
||||
setPhase("taking");
|
||||
}
|
||||
|
||||
if (phase === "generating") {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center py-24 gap-4 animate-fade-in">
|
||||
<div className="w-12 h-12 rounded-2xl bg-accent flex items-center justify-center animate-pulse-glow">
|
||||
<Loader2 size={22} className="animate-spin text-primary" />
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">Генерируем тест из 10 вопросов...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (phase === "taking") {
|
||||
const q = questions[currentQ];
|
||||
const progress = Object.keys(answers).length;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<h1 className="text-xl font-semibold tracking-tight">
|
||||
Вопрос {currentQ + 1} из {questions.length}
|
||||
</h1>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Отвечено: {progress}/{questions.length}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="w-full bg-muted rounded-full h-1.5 overflow-hidden">
|
||||
<div
|
||||
className="bg-primary h-full rounded-full transition-all duration-500 ease-out"
|
||||
style={{ width: `${(progress / questions.length) * 100}%` }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Card className="animate-fade-in" key={currentQ}>
|
||||
<CardContent className="pt-5 space-y-4">
|
||||
<p className="text-[15px] font-medium leading-relaxed">{q.question}</p>
|
||||
<div className="space-y-2">
|
||||
{Object.entries(q.options).map(([key, text]) => (
|
||||
<button
|
||||
key={key}
|
||||
onClick={() => setAnswers((p) => ({ ...p, [q.question]: key }))}
|
||||
className={`w-full text-left p-3.5 rounded-xl border transition-all duration-200 cursor-pointer text-sm ${
|
||||
answers[q.question] === key
|
||||
? "bg-primary text-primary-foreground border-primary shadow-sm shadow-primary/20"
|
||||
: "hover:bg-secondary/80 hover:border-primary/20"
|
||||
}`}
|
||||
>
|
||||
<span className="font-medium mr-2 opacity-60">{key.toUpperCase()}</span>
|
||||
{text}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex justify-between">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => setCurrentQ((c) => Math.max(0, c - 1))}
|
||||
disabled={currentQ === 0}
|
||||
>
|
||||
Назад
|
||||
</Button>
|
||||
<div className="flex gap-2">
|
||||
{currentQ < questions.length - 1 ? (
|
||||
<Button onClick={() => setCurrentQ((c) => c + 1)}>
|
||||
Далее
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
onClick={submitTest}
|
||||
disabled={progress < questions.length}
|
||||
>
|
||||
Завершить тест
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (phase === "results" && result) {
|
||||
const pct = Math.round((result.score / result.total) * 100);
|
||||
const isGood = pct >= 70;
|
||||
|
||||
return (
|
||||
<div className="space-y-6 animate-fade-in">
|
||||
<Card className={isGood ? "border-green-200" : "border-orange-200"}>
|
||||
<CardContent className="pt-6 text-center space-y-4">
|
||||
<div className={`text-5xl font-bold ${isGood ? "text-green-600" : "text-orange-500"}`}>
|
||||
{result.score}/{result.total}
|
||||
</div>
|
||||
<p className="text-muted-foreground">
|
||||
{pct >= 90 ? "Превосходно!" : pct >= 70 ? "Хороший результат" : pct >= 50 ? "Неплохо, но стоит повторить" : "Нужно подтянуть материал"}
|
||||
</p>
|
||||
<div className="w-full bg-muted rounded-full h-2 overflow-hidden max-w-xs mx-auto">
|
||||
<div
|
||||
className={`h-full rounded-full transition-all duration-1000 ease-out ${isGood ? "bg-green-500" : "bg-orange-400"}`}
|
||||
style={{ width: `${pct}%` }}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="space-y-2">
|
||||
{questions.map((q, i) => {
|
||||
const userAnswer = answers[q.question];
|
||||
const isCorrect = userAnswer === q.correct;
|
||||
return (
|
||||
<div
|
||||
key={i}
|
||||
className={`flex items-start gap-3 p-3.5 rounded-xl border text-sm animate-fade-in ${
|
||||
isCorrect ? "border-green-200 bg-green-50/50" : "border-red-200 bg-red-50/50"
|
||||
}`}
|
||||
style={{ animationDelay: `${i * 50}ms` }}
|
||||
>
|
||||
{isCorrect
|
||||
? <CheckCircle2 size={17} className="text-green-600 mt-0.5 shrink-0" />
|
||||
: <XCircle size={17} className="text-red-500 mt-0.5 shrink-0" />}
|
||||
<div>
|
||||
<p className="font-medium">{q.question}</p>
|
||||
{!isCorrect && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
Правильно: {q.correct}) {q.options[q.correct]}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<Button onClick={reset} variant="outline" className="w-full">
|
||||
<RotateCcw size={15} />
|
||||
Новый тест
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">Тестирование</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">Проверьте знания — 10 вопросов с вариантами ответов</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<button
|
||||
onClick={() => setFromQuestions(false)}
|
||||
className={`p-5 rounded-2xl border text-center transition-all duration-200 cursor-pointer ${
|
||||
!fromQuestions
|
||||
? "bg-accent border-primary/20 shadow-sm shadow-primary/5"
|
||||
: "hover:bg-secondary/60"
|
||||
}`}
|
||||
>
|
||||
<ClipboardList size={22} className={`mx-auto mb-2 ${!fromQuestions ? "text-primary" : "text-muted-foreground"}`} />
|
||||
<span className="text-sm font-medium block">По теме</span>
|
||||
<span className="text-xs text-muted-foreground">Укажите тему теста</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setFromQuestions(true)}
|
||||
className={`p-5 rounded-2xl border text-center transition-all duration-200 cursor-pointer ${
|
||||
fromQuestions
|
||||
? "bg-accent border-primary/20 shadow-sm shadow-primary/5"
|
||||
: "hover:bg-secondary/60"
|
||||
}`}
|
||||
>
|
||||
<MessageSquare size={22} className={`mx-auto mb-2 ${fromQuestions ? "text-primary" : "text-muted-foreground"}`} />
|
||||
<span className="text-sm font-medium block">По моим вопросам</span>
|
||||
<span className="text-xs text-muted-foreground">На основе заданных ранее</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{!fromQuestions && (
|
||||
<Input
|
||||
value={topic}
|
||||
onChange={(e) => setTopic(e.target.value)}
|
||||
placeholder="Тема теста..."
|
||||
className="animate-fade-in"
|
||||
/>
|
||||
)}
|
||||
|
||||
<Button onClick={generateTest} className="w-full">
|
||||
Сгенерировать тест
|
||||
</Button>
|
||||
|
||||
{tests.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h2 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
|
||||
История
|
||||
</h2>
|
||||
{tests.map((t) => (
|
||||
<div key={t.id} className="flex items-center justify-between p-3.5 rounded-xl border text-sm">
|
||||
<div>
|
||||
<span className="font-medium">{t.topic}</span>
|
||||
<span className="text-xs text-muted-foreground ml-2">
|
||||
{new Date(t.createdAt).toLocaleDateString("ru")}
|
||||
</span>
|
||||
{t.results.length > 0 && (
|
||||
<span className={`ml-2 text-sm font-semibold ${
|
||||
t.results[t.results.length - 1].score / t.results[t.results.length - 1].total >= 0.7 ? "text-green-600" : "text-orange-500"
|
||||
}`}>
|
||||
{t.results[t.results.length - 1].score}/{t.results[t.results.length - 1].total}
|
||||
</span>
|
||||
)}
|
||||
{t.results.length > 1 && (
|
||||
<span className="text-[10px] text-muted-foreground ml-1">
|
||||
({t.results.length} попыток)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => retakeTest(t)}
|
||||
>
|
||||
<RotateCcw size={13} />
|
||||
Пройти
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { BookOpen, ChevronRight, Search, Sparkles } from "lucide-react";
|
||||
import { apiFetch, API_BASE } from "@/lib/utils";
|
||||
import Markdown from "@/components/Markdown";
|
||||
|
||||
interface Textbook {
|
||||
id: number;
|
||||
topic: string;
|
||||
content: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export default function TextbookPage() {
|
||||
const [topic, setTopic] = useState("");
|
||||
const [generating, setGenerating] = useState(false);
|
||||
const [current, setCurrent] = useState("");
|
||||
const [textbooks, setTextbooks] = useState<Textbook[]>([]);
|
||||
const [selectedId, setSelectedId] = useState<number | null>(null);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
useEffect(() => { loadTextbooks(); }, []);
|
||||
|
||||
async function loadTextbooks() {
|
||||
try { setTextbooks(await apiFetch<Textbook[]>("/textbooks")); } catch {}
|
||||
}
|
||||
|
||||
async function generate() {
|
||||
if (!topic.trim() || generating) return;
|
||||
setGenerating(true);
|
||||
setCurrent("");
|
||||
setSelectedId(null);
|
||||
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}/textbooks/generate`, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ topic: topic.trim() }),
|
||||
});
|
||||
|
||||
const reader = res.body?.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let fullContent = "";
|
||||
|
||||
while (reader) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
for (const line of decoder.decode(value).split("\n").filter((l) => l.startsWith("data: "))) {
|
||||
const data = line.slice(6);
|
||||
if (data === "[DONE]") break;
|
||||
try {
|
||||
const parsed = JSON.parse(data);
|
||||
if (parsed.content) { fullContent += parsed.content; setCurrent(fullContent); }
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
setTopic("");
|
||||
loadTextbooks();
|
||||
} catch (err: any) { setCurrent(`Ошибка: ${err.message}`); }
|
||||
setGenerating(false);
|
||||
}
|
||||
|
||||
const displayContent = selectedId
|
||||
? textbooks.find((t) => t.id === selectedId)?.content || ""
|
||||
: current;
|
||||
|
||||
const filtered = textbooks.filter(
|
||||
(t) => t.topic.toLowerCase().includes(search.toLowerCase())
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">Генерация учебника</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
ИИ составит учебник с понятными объяснениями по вашей теме
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={topic}
|
||||
onChange={(e) => setTopic(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && generate()}
|
||||
placeholder="Введите тему..."
|
||||
disabled={generating}
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button onClick={generate} disabled={generating || !topic.trim()}>
|
||||
{generating ? <Sparkles size={16} className="animate-spin-glow" /> : <BookOpen size={16} />}
|
||||
Создать
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{generating && !displayContent && (
|
||||
<div className="shimmer rounded-2xl h-40" />
|
||||
)}
|
||||
|
||||
{displayContent && (
|
||||
<Card className="animate-fade-in">
|
||||
<CardContent className="pt-5">
|
||||
<Markdown exportable exportTitle={selectedId ? textbooks.find((t) => t.id === selectedId)?.topic || "textbook" : topic || "textbook"}>
|
||||
{displayContent}
|
||||
</Markdown>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{textbooks.length > 0 && (
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-sm font-medium text-muted-foreground uppercase tracking-wider">
|
||||
Созданные учебники
|
||||
</h2>
|
||||
|
||||
<div className="relative">
|
||||
<Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
placeholder="Поиск по учебникам..."
|
||||
className="pl-9"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
{filtered.map((tb) => (
|
||||
<button
|
||||
key={tb.id}
|
||||
onClick={() => setSelectedId(tb.id === selectedId ? null : tb.id)}
|
||||
className={`w-full text-left flex items-center justify-between p-3.5 rounded-xl border transition-all duration-200 cursor-pointer group ${
|
||||
tb.id === selectedId
|
||||
? "bg-accent border-primary/20 shadow-sm"
|
||||
: "hover:bg-secondary/60 hover:border-border"
|
||||
}`}
|
||||
>
|
||||
<div>
|
||||
<span className="text-sm font-medium">{tb.topic}</span>
|
||||
<span className="text-xs text-muted-foreground ml-2">
|
||||
{new Date(tb.createdAt).toLocaleDateString("ru")}
|
||||
</span>
|
||||
</div>
|
||||
<ChevronRight
|
||||
size={15}
|
||||
className={`text-muted-foreground transition-transform duration-200 ${
|
||||
tb.id === selectedId ? "rotate-90" : "group-hover:translate-x-0.5"
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
{filtered.length === 0 && search && (
|
||||
<p className="text-center text-sm text-muted-foreground py-6">Ничего не найдено</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user