Spaces:
Sleeping
Sleeping
File size: 15,200 Bytes
eddc354 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | import { useCallback, useEffect, useState } from "react";
import { Check, Copy, FolderOpen, KeyRound, MessageSquare, RotateCcw, Trash2, UserPlus, Users } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import {
createUser,
deleteUser,
listUsers,
resetPassword,
roleLabel,
statusLabel,
type StoredUser,
} from "@/lib/auth-service";
import {
countProjectsByOwner,
formatStamp,
listProjects,
removeProjectsOfOwner,
type StoredProject,
} from "@/lib/studio-storage";
import { listFeedback, markFeedbackRead, removeFeedback, type FeedbackItem } from "@/lib/feedback-service";
type Props = {
open: boolean;
onOpenChange: (v: boolean) => void;
};
export default function AdminPanel({ open, onOpenChange }: Props) {
const [users, setUsers] = useState<StoredUser[]>([]);
const [counts, setCounts] = useState<Record<string, number>>({});
const [createOpen, setCreateOpen] = useState(false);
const [newLogin, setNewLogin] = useState("");
const [createError, setCreateError] = useState<string | null>(null);
const [credentials, setCredentials] = useState<{ username: string; password: string } | null>(null);
const [toDelete, setToDelete] = useState<StoredUser | null>(null);
const [viewing, setViewing] = useState<{ user: StoredUser; items: StoredProject[] } | null>(null);
const [feedback, setFeedback] = useState<FeedbackItem[]>([]);
const refresh = useCallback(() => {
setUsers(listUsers());
setCounts(countProjectsByOwner());
setFeedback(listFeedback());
}, []);
useEffect(() => {
if (open) refresh();
}, [open, refresh]);
const totalProjects = Object.values(counts).reduce((a, b) => a + b, 0);
const activeUsers = users.filter((u) => u.status === "active").length;
const pendingUsers = users.length - activeUsers;
const copy = (value: string) => {
void navigator.clipboard?.writeText(value);
};
const submitCreate = () => {
const result = createUser(newLogin);
if (!result.ok) {
setCreateError(result.error);
return;
}
setCreateError(null);
setCreateOpen(false);
setNewLogin("");
setCredentials({ username: result.user.username, password: result.tempPassword });
refresh();
};
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[88vh] max-w-5xl overflow-y-auto">
<DialogHeader>
<DialogTitle className="flex items-center gap-2 font-display text-2xl">
<Users className="h-6 w-6 text-accent" /> Панель админа
</DialogTitle>
<DialogDescription>Управление пользователями студии и обзор сохранённых схем.</DialogDescription>
</DialogHeader>
<div className="grid gap-3 sm:grid-cols-5">
{[
{ label: "Пользователей", value: users.length },
{ label: "Активных", value: activeUsers },
{ label: "Ожидают входа", value: pendingUsers },
{ label: "Всего схем", value: totalProjects },
{ label: "Новых пожеланий", value: feedback.filter((f) => !f.read).length },
].map((s) => (
<div key={s.label} className="rounded-2xl border border-border bg-secondary p-4">
<p className="text-xs text-muted-foreground">{s.label}</p>
<p className="font-display text-3xl leading-tight">{s.value}</p>
</div>
))}
</div>
<section className="rounded-2xl border border-border">
<h3 className="flex items-center gap-2 border-b border-border px-4 py-2 font-display text-lg">
<MessageSquare className="h-5 w-5 text-accent" /> Пожелания пользователей
</h3>
{feedback.length === 0 ? (
<p className="px-4 py-6 text-center text-sm text-muted-foreground">Пока нет сообщений.</p>
) : (
<ul className="max-h-64 divide-y divide-border overflow-y-auto">
{feedback.map((f) => (
<li key={f.id} className="flex items-start gap-3 px-4 py-2.5">
<div className="min-w-0 flex-1">
<p className="text-xs text-muted-foreground">
{f.username} · {formatStamp(f.createdAt)}
{!f.read && <Badge className="ml-2 align-middle">новое</Badge>}
</p>
<p className="whitespace-pre-wrap text-sm">{f.text}</p>
</div>
<div className="flex shrink-0 gap-1">
{!f.read && (
<Button
variant="outline"
size="icon"
className="h-8 w-8"
title="Отметить прочитанным"
onClick={() => setFeedback(markFeedbackRead(f.id))}
>
<Check className="h-4 w-4" />
</Button>
)}
<Button
variant="outline"
size="icon"
className="h-8 w-8 text-destructive"
title="Удалить сообщение"
onClick={() => setFeedback(removeFeedback(f.id))}
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</li>
))}
</ul>
)}
</section>
<div>
<Button size="lg" className="h-12 gap-2" onClick={() => setCreateOpen(true)}>
<UserPlus className="h-5 w-5" /> Создать пользователя
</Button>
</div>
<div className="overflow-x-auto rounded-2xl border border-border">
<Table>
<TableHeader>
<TableRow>
<TableHead>Логин</TableHead>
<TableHead>Роль</TableHead>
<TableHead>Создан</TableHead>
<TableHead>Статус</TableHead>
<TableHead>Схемы</TableHead>
<TableHead className="text-right">Действия</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{users.map((u) => (
<TableRow key={u.id}>
<TableCell className="font-medium">{u.username}</TableCell>
<TableCell>{roleLabel(u.role)}</TableCell>
<TableCell className="text-muted-foreground">{formatStamp(u.createdAt)}</TableCell>
<TableCell>
<Badge variant={u.status === "active" ? "secondary" : "outline"}>{statusLabel(u.status)}</Badge>
</TableCell>
<TableCell>{counts[u.id] ?? 0}</TableCell>
<TableCell>
<div className="flex flex-wrap justify-end gap-2">
<Button
variant="outline"
size="sm"
className="h-10 gap-1"
title="Сбросить пароль и выдать временный"
onClick={() => {
const password = resetPassword(u.id);
setCredentials({ username: u.username, password });
refresh();
}}
>
<RotateCcw className="h-4 w-4" /> Сбросить пароль
</Button>
<Button
variant="outline"
size="sm"
className="h-10 gap-1"
title="Просмотреть проекты пользователя"
onClick={() => setViewing({ user: u, items: listProjects(u.id) })}
>
<FolderOpen className="h-4 w-4" /> Просмотреть проекты
</Button>
<Button
variant="destructive"
size="sm"
className="h-10 gap-1"
disabled={u.role === "admin"}
title={
u.role === "admin" ? "Администратора удалить нельзя" : "Удалить пользователя и его схемы"
}
onClick={() => setToDelete(u)}
>
<Trash2 className="h-4 w-4" /> Удалить
</Button>
</div>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</div>
</DialogContent>
</Dialog>
{/* Создание пользователя */}
<Dialog open={createOpen} onOpenChange={setCreateOpen}>
<DialogContent className="max-w-sm">
<DialogHeader>
<DialogTitle className="font-display text-2xl">Создать пользователя</DialogTitle>
<DialogDescription>
Укажите логин — система выдаст одноразовый временный пароль для первого входа.
</DialogDescription>
</DialogHeader>
<div className="space-y-2">
<Label htmlFor="new-user-login">Логин</Label>
<Input
id="new-user-login"
autoFocus
value={newLogin}
onChange={(e) => {
setNewLogin(e.target.value);
setCreateError(null);
}}
className="h-12"
/>
{createError && <p className="text-sm text-destructive">{createError}</p>}
</div>
<Button size="lg" className="h-12 w-full" onClick={submitCreate}>
<UserPlus className="h-5 w-5" /> Создать и выдать пароль
</Button>
</DialogContent>
</Dialog>
{/* Показ временного пароля */}
<Dialog open={!!credentials} onOpenChange={(v) => !v && setCredentials(null)}>
<DialogContent className="max-w-sm">
<DialogHeader>
<DialogTitle className="flex items-center gap-2 font-display text-2xl">
<KeyRound className="h-6 w-6 text-accent" /> Временный пароль
</DialogTitle>
<DialogDescription>
Передайте пароль пользователю «{credentials?.username}». При первом входе он задаст постоянный пароль.
</DialogDescription>
</DialogHeader>
<div className="flex items-center gap-2">
<code className="flex-1 rounded-xl border border-border bg-secondary px-4 py-3 text-center text-lg tracking-widest">
{credentials?.password}
</code>
<Button
variant="outline"
size="lg"
className="h-12 gap-2"
title="Скопировать пароль"
onClick={() => credentials && copy(credentials.password)}
>
<Copy className="h-5 w-5" />
</Button>
</div>
<Button size="lg" className="h-12 w-full" onClick={() => setCredentials(null)}>
Готово
</Button>
</DialogContent>
</Dialog>
{/* Проекты пользователя */}
<Dialog open={!!viewing} onOpenChange={(v) => !v && setViewing(null)}>
<DialogContent className="max-h-[80vh] max-w-3xl overflow-y-auto">
<DialogHeader>
<DialogTitle className="font-display text-2xl">Проекты «{viewing?.user.username}»</DialogTitle>
<DialogDescription>Схемы, сохранённые этим пользователем.</DialogDescription>
</DialogHeader>
{viewing && viewing.items.length === 0 ? (
<p className="py-8 text-center text-sm text-muted-foreground">У пользователя пока нет схем.</p>
) : (
<div className="grid gap-4 sm:grid-cols-3">
{viewing?.items.map((p) => (
<article key={p.id} className="overflow-hidden rounded-2xl border border-border bg-card">
<img
src={p.thumb}
alt={`Превью схемы «${p.title}»`}
className="aspect-[4/3] w-full bg-secondary object-cover"
/>
<div className="space-y-1 p-3">
<h3 className="truncate font-medium">{p.title}</h3>
<p className="text-xs text-muted-foreground">
{formatStamp(p.updatedAt)} · элементов: {p.elements}
</p>
</div>
</article>
))}
</div>
)}
</DialogContent>
</Dialog>
<AlertDialog open={!!toDelete} onOpenChange={(v) => !v && setToDelete(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Удалить пользователя?</AlertDialogTitle>
<AlertDialogDescription>
Пользователь «{toDelete?.username}» и все его схемы будут удалены безвозвратно.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Отмена</AlertDialogCancel>
<AlertDialogAction
onClick={() => {
if (toDelete) {
removeProjectsOfOwner(toDelete.id);
deleteUser(toDelete.id);
}
setToDelete(null);
refresh();
}}
>
Удалить
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}
|