E-Library: платформа электронных библиотек для организаций
- Каталог, чтение онлайн, кабинеты студента и преподавателя, списки литературы, публикации - Организации: регистрация, логотип, адрес /<slug>, одобрение владельцем платформы - Вход через Active Directory (настройки у каждой организации) или по логинам из загруженного списка - Изоляция данных организаций, общий открытый фонд книг, статистика Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#4f46e5" />
|
||||
<title>Электронная библиотека</title>
|
||||
<script src="/theme-init.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.jsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+2942
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "elibrary-client",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"clsx": "^2.1.1",
|
||||
"lucide-react": "^1.72.0",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1",
|
||||
"react-router-dom": "^7.18.5",
|
||||
"recharts": "^2.15.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/vite": "^4.3.5",
|
||||
"@vitejs/plugin-react": "^4.7.0",
|
||||
"tailwindcss": "^4.3.5",
|
||||
"vite": "^6.4.6"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#6366f1"/><stop offset="1" stop-color="#8b5cf6"/></linearGradient></defs><rect width="64" height="64" rx="16" fill="url(#g)"/><path d="M18 18h10a6 6 0 0 1 6 6v22a4 4 0 0 0-4-4H18zM46 18H36a6 6 0 0 0-6 6v22a4 4 0 0 1 4-4h12z" fill="none" stroke="#fff" stroke-width="3.5" stroke-linejoin="round"/></svg>
|
||||
|
After Width: | Height: | Size: 448 B |
@@ -0,0 +1,5 @@
|
||||
// Тема применяется до отрисовки, чтобы не было вспышки светлого фона (отдельный файл — из-за CSP script-src 'self')
|
||||
try {
|
||||
var t = localStorage.getItem('elib-theme');
|
||||
if (t === 'dark' || (!t && matchMedia('(prefers-color-scheme: dark)').matches)) document.documentElement.classList.add('dark');
|
||||
} catch (e) {}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Download, Eye } from 'lucide-react';
|
||||
import BookCover from './BookCover';
|
||||
import { Badge } from './ui';
|
||||
import { BOOK_TYPES, fmtNum } from '../lib/format';
|
||||
|
||||
export default function BookCard({ book }) {
|
||||
return (
|
||||
<Link to={`/books/${book.id}`} className="group flex flex-col">
|
||||
<div className="transition duration-300 group-hover:-translate-y-1.5 group-hover:drop-shadow-xl">
|
||||
<BookCover book={book} />
|
||||
</div>
|
||||
<div className="mt-3 min-w-0">
|
||||
<div className="line-clamp-2 text-sm font-semibold leading-snug text-ink group-hover:text-brand-600 dark:group-hover:text-brand-300">{book.title}</div>
|
||||
<div className="mt-0.5 truncate text-xs text-muted">{book.authors}</div>
|
||||
<div className="mt-1.5 flex items-center gap-3 text-[11px] text-subtle tnum">
|
||||
{book.year && <span>{book.year}</span>}
|
||||
<span className="flex items-center gap-1" title="Просмотры">
|
||||
<Eye className="size-3" />
|
||||
{fmtNum(book.viewCount)}
|
||||
</span>
|
||||
<span className="flex items-center gap-1" title="Скачивания">
|
||||
<Download className="size-3" />
|
||||
{fmtNum(book.downloadCount)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
export function BookRow({ book, extra }) {
|
||||
return (
|
||||
<Link to={`/books/${book.id}`} className="card group flex gap-4 p-3 transition hover:border-brand-300 hover:shadow-md dark:hover:border-brand-500/40">
|
||||
<BookCover book={book} size="sm" className="w-16 shrink-0 sm:w-20" />
|
||||
<div className="min-w-0 flex-1 py-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{book.category && (
|
||||
<span className="text-xs font-medium" style={{ color: book.category.color }}>
|
||||
{book.category.name}
|
||||
</span>
|
||||
)}
|
||||
<Badge>{BOOK_TYPES[book.type] || book.type}</Badge>
|
||||
</div>
|
||||
<div className="mt-1 line-clamp-2 font-semibold text-ink group-hover:text-brand-600 dark:group-hover:text-brand-300">{book.title}</div>
|
||||
<div className="truncate text-sm text-muted">{book.authors}</div>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-subtle tnum">
|
||||
{book.year && <span>{book.year} г.</span>}
|
||||
{book.pages && <span>{book.pages} стр.</span>}
|
||||
{book.fileExt && <span className="uppercase">{book.fileExt}</span>}
|
||||
<span className="flex items-center gap-1">
|
||||
<Eye className="size-3.5" /> {fmtNum(book.viewCount)}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<Download className="size-3.5" /> {fmtNum(book.downloadCount)}
|
||||
</span>
|
||||
{extra}
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
export function BookGrid({ books }) {
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6">
|
||||
{books.map((b) => (
|
||||
<BookCard key={b.id} book={b} />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useState } from 'react';
|
||||
import clsx from 'clsx';
|
||||
import { hashColor } from '../lib/format';
|
||||
|
||||
const PALETTES = [
|
||||
['#4f46e5', '#7c3aed'],
|
||||
['#0369a1', '#0ea5e9'],
|
||||
['#047857', '#10b981'],
|
||||
['#b45309', '#f59e0b'],
|
||||
['#be123c', '#f43f5e'],
|
||||
['#6d28d9', '#c026d3'],
|
||||
['#0f766e', '#14b8a6'],
|
||||
['#1e293b', '#475569'],
|
||||
['#9a3412', '#ea580c'],
|
||||
];
|
||||
|
||||
/** Обложка книги: загруженная картинка или сгенерированная «типографская» обложка */
|
||||
export default function BookCover({ book, className, size = 'md' }) {
|
||||
const [failed, setFailed] = useState(false);
|
||||
const h = hashColor(book.title);
|
||||
const [a, b] = book.category?.color ? [book.category.color, PALETTES[h % PALETTES.length][1]] : PALETTES[h % PALETTES.length];
|
||||
|
||||
return (
|
||||
<div
|
||||
className={clsx(
|
||||
'relative aspect-[2/3] overflow-hidden rounded-lg shadow-[0_8px_24px_-8px_rgba(15,23,42,0.35)] ring-1 ring-black/5',
|
||||
className
|
||||
)}
|
||||
>
|
||||
{book.coverUrl && !failed ? (
|
||||
<img src={book.coverUrl} alt={book.title} loading="lazy" onError={() => setFailed(true)} className="size-full object-cover" />
|
||||
) : (
|
||||
<div className="flex size-full flex-col text-white" style={{ background: `linear-gradient(150deg, ${a} 0%, ${b} 100%)` }}>
|
||||
<svg className="absolute inset-0 size-full opacity-[0.12]" viewBox="0 0 100 150" preserveAspectRatio="none" aria-hidden>
|
||||
<circle cx={20 + (h % 60)} cy={110} r={45} fill="white" />
|
||||
<circle cx={90} cy={20 + (h % 40)} r={25} fill="white" />
|
||||
</svg>
|
||||
<div className="absolute inset-y-0 left-0 w-[6%] bg-black/15" />
|
||||
<div className={clsx('relative flex flex-1 flex-col justify-between', size === 'sm' ? 'p-2 pl-3' : 'p-3 pl-5 sm:p-4 sm:pl-6')}>
|
||||
<div className={clsx('h-0.5 w-8 bg-white/60', size === 'sm' && 'w-5')} />
|
||||
<div
|
||||
className={clsx(
|
||||
'font-semibold leading-tight [text-wrap:balance]',
|
||||
size === 'sm' ? 'line-clamp-4 text-[9px]' : size === 'lg' ? 'line-clamp-6 text-xl sm:text-2xl' : 'line-clamp-5 text-[13px] sm:text-sm'
|
||||
)}
|
||||
>
|
||||
{book.title}
|
||||
</div>
|
||||
{size !== 'sm' && <div className={clsx('line-clamp-2 text-white/75', size === 'lg' ? 'text-sm' : 'text-[10px]')}>{book.authors}</div>}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="pointer-events-none absolute inset-0 bg-gradient-to-r from-white/10 via-transparent to-transparent" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { useState } from 'react';
|
||||
import { AlertTriangle, Copy, FileSpreadsheet, Printer, Search } from 'lucide-react';
|
||||
import { downloadPost } from '../lib/api';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { KIND_LABELS } from '../lib/format';
|
||||
import { Button, useToast } from './ui';
|
||||
import { OrgLogo } from '../pages/OrgScreens';
|
||||
|
||||
/**
|
||||
* Выданные логины и пароли. Сервер хранит только хеши — пароли видны здесь один раз:
|
||||
* скачать Excel, распечатать карточки (по 8 на листе A4) или скопировать.
|
||||
*/
|
||||
export default function Credentials({ items }) {
|
||||
const { org } = useAuth();
|
||||
const toast = useToast();
|
||||
const [q, setQ] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const loginUrl = `${window.location.origin}/${org.slug}`;
|
||||
const shown = q ? items.filter((x) => `${x.displayName} ${x.username} ${x.studyGroup || ''}`.toLowerCase().includes(q.toLowerCase())) : items;
|
||||
|
||||
const excel = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await downloadPost('/org/credentials.xlsx', { items, loginUrl }, 'logins.xlsx');
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const copy = () => {
|
||||
const text = items.map((x) => [x.displayName, x.studyGroup || '', x.username, x.password].join('\t')).join('\n');
|
||||
navigator.clipboard?.writeText(`ФИО\tГруппа\tЛогин\tПароль\n${text}`).then(() => toast('Скопировано — вставьте в Excel'));
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-4 flex items-start gap-3 rounded-2xl bg-amber-50 p-4 text-sm text-amber-900 dark:bg-amber-500/10 dark:text-amber-100">
|
||||
<AlertTriangle className="mt-0.5 size-5 shrink-0" />
|
||||
<div>
|
||||
<b>Пароли показываются только сейчас.</b> Сохраните лист или распечатайте карточки. Если пароль потеряется — администратор выдаст новый
|
||||
(Пользователи → профиль → «Новый пароль»). При первом входе каждый придумает свой пароль.
|
||||
</div>
|
||||
</div>
|
||||
<div className="mb-4 flex flex-wrap items-center gap-2">
|
||||
<Button icon={FileSpreadsheet} loading={busy} onClick={excel}>Скачать Excel</Button>
|
||||
<Button variant="secondary" icon={Printer} onClick={() => window.print()}>Печать карточек</Button>
|
||||
<Button variant="ghost" icon={Copy} onClick={copy}>Копировать</Button>
|
||||
{items.length > 10 && (
|
||||
<div className="relative ml-auto w-full sm:w-64">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-subtle" />
|
||||
<input className="input h-9 pl-9" placeholder="Найти в списке" value={q} onChange={(e) => setQ(e.target.value)} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="card overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-line text-left text-xs text-muted">
|
||||
<th className="px-4 py-2.5 font-medium">ФИО</th>
|
||||
<th className="px-4 py-2.5 font-medium">Группа</th>
|
||||
<th className="px-4 py-2.5 font-medium">Логин</th>
|
||||
<th className="px-4 py-2.5 font-medium">Пароль</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-line">
|
||||
{shown.slice(0, 500).map((x) => (
|
||||
<tr key={x.username}>
|
||||
<td className="px-4 py-2">
|
||||
{x.displayName}
|
||||
{x.kind && x.kind !== 'STUDENT' && <span className="ml-2 text-xs text-muted">{KIND_LABELS[x.kind]}</span>}
|
||||
</td>
|
||||
<td className="px-4 py-2 text-muted">{x.studyGroup || '—'}</td>
|
||||
<td className="px-4 py-2 font-mono">{x.username}</td>
|
||||
<td className="px-4 py-2 font-mono font-semibold">{x.password}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
{shown.length > 500 && <div className="p-3 text-center text-xs text-muted">Показаны первые 500 — все строки есть в Excel и при печати</div>}
|
||||
</div>
|
||||
|
||||
{/* Карточки для печати: видны только при печати (index.css → .print-area) */}
|
||||
<div className="print-area">
|
||||
{items.map((x) => (
|
||||
<div key={x.username} className="print-card">
|
||||
<div className="print-card-head">
|
||||
<OrgLogo org={org} className="print-logo" rounded="" />
|
||||
<div>
|
||||
<div className="print-org">{org.shortName || org.name}</div>
|
||||
<div className="print-sub">Электронная библиотека</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="print-name">{x.displayName}</div>
|
||||
{x.studyGroup && <div className="print-sub">Группа {x.studyGroup}</div>}
|
||||
<table className="print-creds">
|
||||
<tbody>
|
||||
<tr><td>Адрес</td><td>{loginUrl}</td></tr>
|
||||
<tr><td>Логин</td><td><b>{x.username}</b></td></tr>
|
||||
<tr><td>Пароль</td><td><b>{x.password}</b></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div className="print-note">При первом входе придумайте свой пароль.</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,225 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import clsx from 'clsx';
|
||||
import { BookMarked, Check, ListChecks, ListPlus, Plus, UsersRound } from 'lucide-react';
|
||||
import { api, useApi } from '../lib/api';
|
||||
import { fmtDate, plural } from '../lib/format';
|
||||
import { Badge, Button, Modal, Spinner, Switch, useToast } from './ui';
|
||||
|
||||
const splitGroups = (s) =>
|
||||
[...new Set(String(s || '').split(/[,;\n]/).map((g) => g.trim().toUpperCase().replace(/\s*-\s*/g, '-').replace(/\s+/g, '-')).filter(Boolean))];
|
||||
|
||||
/** Создание / редактирование списка литературы */
|
||||
export function ListFormModal({ open, list, bookId, onClose, onSaved }) {
|
||||
const toast = useToast();
|
||||
const [form, setForm] = useState({ title: '', groups: '', semester: '', description: '', isPublic: true });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
setError('');
|
||||
setForm(
|
||||
list
|
||||
? { title: list.title, groups: (list.groups || []).join(', '), semester: list.semester || '', description: list.description || '', isPublic: list.isPublic }
|
||||
: { title: '', groups: '', semester: '', description: '', isPublic: true }
|
||||
);
|
||||
}, [open, list]);
|
||||
|
||||
const save = async () => {
|
||||
if (form.title.trim().length < 3) return setError('Укажите название дисциплины');
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const body = { ...form, groups: splitGroups(form.groups), ...(bookId && { bookId }) };
|
||||
const d = await api(list ? `/lists/${list.id}` : '/lists', { method: list ? 'PUT' : 'POST', body });
|
||||
toast(list ? 'Список сохранён' : 'Список литературы создан');
|
||||
onSaved?.(d.list);
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const groups = splitGroups(form.groups);
|
||||
const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title={list ? 'Редактирование списка' : 'Новый список литературы'}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onClose}>Отмена</Button>
|
||||
<Button loading={busy} onClick={save} className="!bg-violet-600 hover:!bg-violet-700">{list ? 'Сохранить' : 'Создать список'}</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
{error && <div className="rounded-xl bg-rose-50 p-3 text-sm text-rose-700 dark:bg-rose-500/10 dark:text-rose-300">{error}</div>}
|
||||
<div>
|
||||
<label className="label">Дисциплина *</label>
|
||||
<input className="input" autoFocus value={form.title} onChange={set('title')} placeholder="Например: Алгоритмы и структуры данных" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Академические группы</label>
|
||||
<input className="input" value={form.groups} onChange={set('groups')} placeholder="ИС-24-01, ИС-24-02" />
|
||||
<div className="mt-2 flex min-h-6 flex-wrap gap-1.5">
|
||||
{groups.length ? groups.map((g) => <Badge key={g} color="violet">{g}</Badge>) : (
|
||||
<span className="text-xs text-subtle">Студенты этих групп увидят список у себя в кабинете</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div>
|
||||
<label className="label">Семестр / учебный год</label>
|
||||
<input className="input" value={form.semester} onChange={set('semester')} placeholder="2026/27, 1 семестр" />
|
||||
</div>
|
||||
<div className="flex items-end pb-2">
|
||||
<Switch checked={form.isPublic} onChange={(v) => setForm({ ...form, isPublic: v })} label="Виден всем пользователям" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Комментарий для студентов</label>
|
||||
<textarea className="input h-24 resize-y py-2" value={form.description} onChange={set('description')} placeholder="Что читать к экзамену, порядок изучения, требования" />
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/** Кнопка в карточке книги: добавить издание в свои списки литературы */
|
||||
export function AddToListButton({ bookId }) {
|
||||
const toast = useToast();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [busy, setBusy] = useState(null);
|
||||
const { data, loading, reload, setData } = useApi(open ? `/lists/for-book/${bookId}` : null, [open, bookId]);
|
||||
|
||||
const toggle = async (l) => {
|
||||
setBusy(l.id);
|
||||
try {
|
||||
if (l.has) await api(`/lists/${l.id}/items/${bookId}`, { method: 'DELETE' });
|
||||
else await api(`/lists/${l.id}/items`, { method: 'POST', body: { bookId } });
|
||||
setData((d) => ({ items: d.items.map((x) => (x.id === l.id ? { ...x, has: !x.has, itemCount: x.itemCount + (x.has ? -1 : 1) } : x)) }));
|
||||
toast(l.has ? `Убрано из списка «${l.title}»` : `Добавлено в список «${l.title}»`);
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
const setRequired = async (l, required) => {
|
||||
await api(`/lists/${l.id}/items/${bookId}`, { method: 'PATCH', body: { required } });
|
||||
setData((d) => ({ items: d.items.map((x) => (x.id === l.id ? { ...x, required } : x)) }));
|
||||
};
|
||||
|
||||
const count = data?.items.filter((l) => l.has).length;
|
||||
return (
|
||||
<>
|
||||
<Button size="lg" variant="secondary" icon={ListPlus} onClick={() => setOpen(true)}>В список литературы</Button>
|
||||
<Modal
|
||||
open={open && !creating}
|
||||
onClose={() => setOpen(false)}
|
||||
title="Списки литературы"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="ghost" icon={Plus} onClick={() => setCreating(true)} className="mr-auto">Новый список</Button>
|
||||
<Button onClick={() => setOpen(false)}>Готово</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{loading && !data && <div className="flex justify-center py-8"><Spinner /></div>}
|
||||
{data && !data.items.length && (
|
||||
<div className="py-6 text-center text-sm text-muted">
|
||||
<ListChecks className="mx-auto mb-2 size-8 text-subtle" />
|
||||
У вас пока нет списков литературы. Создайте первый — издание добавится в него сразу.
|
||||
</div>
|
||||
)}
|
||||
{data?.items.length > 0 && (
|
||||
<>
|
||||
<p className="mb-3 text-sm text-muted">Отметьте дисциплины, к которым относится это издание{count ? ` · выбрано: ${count}` : ''}.</p>
|
||||
<div className="space-y-2">
|
||||
{data.items.map((l) => (
|
||||
<div key={l.id} className={clsx('flex items-center gap-3 rounded-xl border p-3 transition', l.has ? 'border-violet-300 bg-violet-50/60 dark:border-violet-500/40 dark:bg-violet-500/10' : 'border-line')}>
|
||||
<button
|
||||
onClick={() => toggle(l)}
|
||||
disabled={busy === l.id}
|
||||
aria-pressed={l.has}
|
||||
className={clsx('flex size-6 shrink-0 items-center justify-center rounded-md border-2 transition', l.has ? 'border-violet-600 bg-violet-600 text-white' : 'border-line hover:border-violet-400')}
|
||||
>
|
||||
{busy === l.id ? <Spinner className="size-3.5 text-current" /> : l.has && <Check className="size-4" />}
|
||||
</button>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-medium">{l.title}</div>
|
||||
<div className="truncate text-xs text-muted">
|
||||
{l.groups.length ? l.groups.join(', ') : 'без групп'} · {l.itemCount} {plural(l.itemCount, 'издание', 'издания', 'изданий')}
|
||||
</div>
|
||||
</div>
|
||||
{l.has && (
|
||||
<select className="input h-8 w-auto text-xs" value={l.required ? '1' : '0'} onChange={(e) => setRequired(l, e.target.value === '1')}>
|
||||
<option value="1">Основная</option>
|
||||
<option value="0">Дополнительная</option>
|
||||
</select>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Modal>
|
||||
<ListFormModal
|
||||
open={creating}
|
||||
bookId={bookId}
|
||||
onClose={() => setCreating(false)}
|
||||
onSaved={() => { setCreating(false); reload(); }}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Карточка списка литературы (для кабинета и каталога списков) */
|
||||
export function ListCard({ list, children, showOwner = true }) {
|
||||
return (
|
||||
<Link to={`/lists/${list.id}`} className="card group flex flex-col p-5 transition hover:-translate-y-0.5 hover:border-violet-300 hover:shadow-lg dark:hover:border-violet-500/40">
|
||||
<div className="flex items-start gap-3">
|
||||
<div className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-violet-100 text-violet-700 dark:bg-violet-500/15 dark:text-violet-300">
|
||||
<BookMarked className="size-5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="line-clamp-2 font-semibold group-hover:text-violet-700 dark:group-hover:text-violet-300">{list.title}</div>
|
||||
{showOwner && list.owner && <div className="truncate text-xs text-muted">{list.owner.displayName}{list.owner.title ? ` · ${list.owner.title}` : ''}</div>}
|
||||
{!showOwner && list.semester && <div className="truncate text-xs text-muted">{list.semester}</div>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap items-center gap-1.5">
|
||||
{list.groups?.slice(0, 4).map((g) => <Badge key={g} color="violet"><UsersRound className="size-3" />{g}</Badge>)}
|
||||
{list.groups?.length > 4 && <Badge>+{list.groups.length - 4}</Badge>}
|
||||
<span className="text-xs text-subtle tnum">
|
||||
{list.itemCount ?? list.total} {plural(list.itemCount ?? list.total ?? 0, 'издание', 'издания', 'изданий')}
|
||||
{showOwner && list.semester ? ` · ${list.semester}` : ''}
|
||||
</span>
|
||||
</div>
|
||||
{children && <div className="mt-auto pt-4">{children}</div>}
|
||||
{!children && list.updatedAt && <div className="mt-auto pt-3 text-xs text-subtle">Обновлён {fmtDate(list.updatedAt)}</div>}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
/** Полоса прогресса (одна серия, подпись — текстом рядом) */
|
||||
export function Progress({ value, max, color = 'bg-brand-500', label }) {
|
||||
const pct = max ? Math.round((value / max) * 100) : 0;
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-1.5 flex items-center justify-between text-xs">
|
||||
<span className="text-muted">{label}</span>
|
||||
<span className="font-medium tnum">{value} / {max}</span>
|
||||
</div>
|
||||
<div className="h-2 overflow-hidden rounded-full bg-surface-2" role="progressbar" aria-valuenow={value} aria-valuemin={0} aria-valuemax={max}>
|
||||
<div className={clsx('h-full rounded-full transition-all', color)} style={{ width: `${pct}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { BookMarked, History, KeyRound, LayoutDashboard, ListChecks, LogOut, Library, PenLine, UserRound } from 'lucide-react';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { Avatar, Badge } from './ui';
|
||||
import { KIND_COLORS, KIND_LABELS, ROLE_LABELS } from '../lib/format';
|
||||
|
||||
export default function UserMenu({ inAdmin }) {
|
||||
const { user, logout, can } = useAuth();
|
||||
const [open, setOpen] = useState(false);
|
||||
const ref = useRef();
|
||||
const nav = useNavigate();
|
||||
useEffect(() => {
|
||||
const h = (e) => ref.current && !ref.current.contains(e.target) && setOpen(false);
|
||||
document.addEventListener('mousedown', h);
|
||||
return () => document.removeEventListener('mousedown', h);
|
||||
}, []);
|
||||
const item = 'flex items-center gap-3 rounded-lg px-3 py-2 text-sm text-ink hover:bg-surface-2';
|
||||
return (
|
||||
<div className="relative" ref={ref}>
|
||||
<button onClick={() => setOpen((o) => !o)} className="flex items-center gap-2 rounded-full p-0.5 pr-0.5 transition hover:ring-4 hover:ring-brand-500/15 sm:pr-3">
|
||||
<Avatar name={user.displayName} size={34} />
|
||||
<span className="hidden max-w-[140px] truncate text-sm font-medium sm:block">{user.displayName.split(' ').slice(0, 2).join(' ')}</span>
|
||||
</button>
|
||||
{open && (
|
||||
<div className="absolute right-0 z-40 mt-2 w-72 animate-slide-up rounded-2xl border border-line bg-surface p-2 shadow-xl" onClick={() => setOpen(false)}>
|
||||
<div className="flex items-center gap-3 px-3 py-3">
|
||||
<Avatar name={user.displayName} size={40} />
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-sm font-semibold">{user.displayName}</div>
|
||||
<div className="truncate text-xs text-muted">{user.studyGroup ? `Группа ${user.studyGroup}` : user.department || user.username}</div>
|
||||
<div className="mt-1 flex flex-wrap gap-1">
|
||||
<Badge color={KIND_COLORS[user.kind]}>{KIND_LABELS[user.kind]}</Badge>
|
||||
{user.role !== 'USER' && <Badge color={user.role === 'ADMIN' ? 'violet' : 'sky'}>{ROLE_LABELS[user.role]}</Badge>}
|
||||
{user.teacherPending && <Badge color="amber">ждёт подтверждения</Badge>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="my-1 h-px bg-line" />
|
||||
<Link to="/cabinet" className={item}>
|
||||
<UserRound className="size-4 text-muted" /> Личный кабинет
|
||||
</Link>
|
||||
{inAdmin ? (
|
||||
<Link to="/" className={item}>
|
||||
<Library className="size-4 text-muted" /> Перейти в библиотеку
|
||||
</Link>
|
||||
) : (
|
||||
can('MODERATOR') && (
|
||||
<Link to="/admin" className={item}>
|
||||
<LayoutDashboard className="size-4 text-muted" /> Панель управления
|
||||
</Link>
|
||||
)
|
||||
)}
|
||||
<Link to="/lists" className={item}>
|
||||
<ListChecks className="size-4 text-muted" /> Списки литературы
|
||||
</Link>
|
||||
<Link to="/publications" className={item}>
|
||||
<PenLine className="size-4 text-muted" /> Мои публикации
|
||||
</Link>
|
||||
<Link to="/favorites" className={item}>
|
||||
<BookMarked className="size-4 text-muted" /> Избранное
|
||||
</Link>
|
||||
<Link to="/history" className={item}>
|
||||
<History className="size-4 text-muted" /> История
|
||||
</Link>
|
||||
{user.source === 'LOCAL' && (
|
||||
<Link to="/account/password" className={item}>
|
||||
<KeyRound className="size-4 text-muted" /> Сменить пароль
|
||||
</Link>
|
||||
)}
|
||||
<div className="my-1 h-px bg-line" />
|
||||
<button
|
||||
onClick={async () => {
|
||||
await logout();
|
||||
nav('/login');
|
||||
}}
|
||||
className={item + ' w-full text-rose-600 dark:text-rose-400'}
|
||||
>
|
||||
<LogOut className="size-4" /> Выйти
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import clsx from 'clsx';
|
||||
import { AlertCircle, CheckCircle2, ChevronLeft, ChevronRight, Loader2, Moon, Sun, X } from 'lucide-react';
|
||||
import { initials, hashColor } from '../lib/format';
|
||||
|
||||
export function Button({ variant = 'primary', size = 'md', loading, icon: Icon, className, children, ...p }) {
|
||||
return (
|
||||
<button
|
||||
{...p}
|
||||
disabled={p.disabled || loading}
|
||||
className={clsx(
|
||||
'inline-flex shrink-0 items-center justify-center gap-2 rounded-xl font-medium transition active:scale-[0.98] disabled:pointer-events-none disabled:opacity-50 focus-visible:outline-none focus-visible:ring-4 focus-visible:ring-brand-500/25',
|
||||
{
|
||||
primary: 'bg-brand-600 text-white shadow-sm shadow-brand-600/25 hover:bg-brand-700',
|
||||
secondary: 'border border-line bg-surface text-ink hover:bg-surface-2',
|
||||
ghost: 'text-muted hover:bg-surface-2 hover:text-ink',
|
||||
danger: 'bg-rose-600 text-white hover:bg-rose-700',
|
||||
soft: 'bg-brand-50 text-brand-700 hover:bg-brand-100 dark:bg-brand-500/15 dark:text-brand-300 dark:hover:bg-brand-500/25',
|
||||
}[variant],
|
||||
{ sm: 'h-8 px-3 text-xs', md: 'h-10 px-4 text-sm', lg: 'h-12 px-6 text-base', icon: 'h-9 w-9' }[size],
|
||||
className
|
||||
)}
|
||||
>
|
||||
{loading ? <Loader2 className="size-4 animate-spin" /> : Icon && <Icon className={size === 'lg' ? 'size-5' : 'size-4'} />}
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function Badge({ color = 'gray', className, children }) {
|
||||
return (
|
||||
<span
|
||||
className={clsx(
|
||||
'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-xs font-medium whitespace-nowrap',
|
||||
{
|
||||
gray: 'bg-surface-2 text-muted',
|
||||
brand: 'bg-brand-50 text-brand-700 dark:bg-brand-500/15 dark:text-brand-300',
|
||||
green: 'bg-emerald-50 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300',
|
||||
amber: 'bg-amber-50 text-amber-700 dark:bg-amber-500/15 dark:text-amber-300',
|
||||
red: 'bg-rose-50 text-rose-700 dark:bg-rose-500/15 dark:text-rose-300',
|
||||
violet: 'bg-violet-50 text-violet-700 dark:bg-violet-500/15 dark:text-violet-300',
|
||||
sky: 'bg-sky-50 text-sky-700 dark:bg-sky-500/15 dark:text-sky-300',
|
||||
}[color],
|
||||
className
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export const Spinner = ({ className }) => <Loader2 className={clsx('size-6 animate-spin text-brand-500', className)} />;
|
||||
|
||||
export function PageLoader() {
|
||||
return (
|
||||
<div className="flex min-h-[40vh] items-center justify-center">
|
||||
<Spinner />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Skeleton({ className }) {
|
||||
return <div className={clsx('animate-pulse rounded-xl bg-surface-2', className)} />;
|
||||
}
|
||||
|
||||
export function Empty({ icon: Icon, title, text, action }) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center px-6 py-16 text-center">
|
||||
{Icon && (
|
||||
<div className="mb-4 flex size-14 items-center justify-center rounded-2xl bg-surface-2 text-subtle">
|
||||
<Icon className="size-7" />
|
||||
</div>
|
||||
)}
|
||||
<div className="font-semibold text-ink">{title}</div>
|
||||
{text && <div className="mt-1 max-w-sm text-sm text-muted">{text}</div>}
|
||||
{action && <div className="mt-5">{action}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function ErrorBox({ error, onRetry }) {
|
||||
return (
|
||||
<div className="card flex items-center gap-3 border-rose-200 p-4 text-sm text-rose-700 dark:border-rose-500/30 dark:text-rose-300">
|
||||
<AlertCircle className="size-5 shrink-0" />
|
||||
<div className="flex-1">{error?.message || 'Ошибка загрузки'}</div>
|
||||
{onRetry && (
|
||||
<Button size="sm" variant="secondary" onClick={() => onRetry()}>
|
||||
Повторить
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Avatar({ name, size = 36, className }) {
|
||||
const hues = [250, 200, 160, 30, 330, 280, 190, 10];
|
||||
const h = hues[hashColor(name) % hues.length];
|
||||
return (
|
||||
<div
|
||||
className={clsx('flex shrink-0 items-center justify-center rounded-full font-semibold text-white', className)}
|
||||
style={{
|
||||
width: size,
|
||||
height: size,
|
||||
fontSize: size * 0.38,
|
||||
background: `linear-gradient(135deg, hsl(${h} 70% 58%), hsl(${(h + 40) % 360} 70% 48%))`,
|
||||
}}
|
||||
>
|
||||
{initials(name) || '?'}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Modal({ open, onClose, title, children, footer, size = 'md' }) {
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const onKey = (e) => e.key === 'Escape' && onClose?.();
|
||||
document.addEventListener('keydown', onKey);
|
||||
document.body.style.overflow = 'hidden';
|
||||
return () => {
|
||||
document.removeEventListener('keydown', onKey);
|
||||
document.body.style.overflow = '';
|
||||
};
|
||||
}, [open, onClose]);
|
||||
if (!open) return null;
|
||||
return createPortal(
|
||||
<div className="fixed inset-0 z-50 flex items-end justify-center p-0 sm:items-center sm:p-4">
|
||||
<div className="absolute inset-0 animate-fade-in bg-slate-950/50 backdrop-blur-sm" onClick={onClose} />
|
||||
<div
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
className={clsx(
|
||||
'relative flex max-h-[94vh] w-full animate-slide-up flex-col rounded-t-3xl border border-line bg-surface shadow-2xl sm:rounded-3xl',
|
||||
{ sm: 'sm:max-w-md', md: 'sm:max-w-xl', lg: 'sm:max-w-3xl', xl: 'sm:max-w-5xl' }[size]
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between gap-4 border-b border-line px-6 py-4">
|
||||
<h2 className="text-lg font-semibold">{title}</h2>
|
||||
<button onClick={onClose} className="rounded-lg p-1.5 text-muted hover:bg-surface-2 hover:text-ink" aria-label="Закрыть">
|
||||
<X className="size-5" />
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto px-6 py-5">{children}</div>
|
||||
{footer && <div className="flex justify-end gap-2 border-t border-line px-6 py-4">{footer}</div>}
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
);
|
||||
}
|
||||
|
||||
export function Pagination({ page, pages, onChange }) {
|
||||
if (!pages || pages <= 1) return null;
|
||||
const nums = [];
|
||||
for (let i = Math.max(1, page - 2); i <= Math.min(pages, page + 2); i++) nums.push(i);
|
||||
const btn = 'flex h-9 min-w-9 items-center justify-center rounded-lg px-2 text-sm transition';
|
||||
return (
|
||||
<div className="flex items-center justify-center gap-1">
|
||||
<button className={clsx(btn, 'text-muted hover:bg-surface-2 disabled:opacity-40')} disabled={page <= 1} onClick={() => onChange(page - 1)} aria-label="Назад">
|
||||
<ChevronLeft className="size-4" />
|
||||
</button>
|
||||
{nums[0] > 1 && (
|
||||
<>
|
||||
<button className={clsx(btn, 'hover:bg-surface-2')} onClick={() => onChange(1)}>1</button>
|
||||
{nums[0] > 2 && <span className="px-1 text-subtle">…</span>}
|
||||
</>
|
||||
)}
|
||||
{nums.map((n) => (
|
||||
<button key={n} onClick={() => onChange(n)} className={clsx(btn, n === page ? 'bg-brand-600 font-medium text-white' : 'hover:bg-surface-2')}>
|
||||
{n}
|
||||
</button>
|
||||
))}
|
||||
{nums.at(-1) < pages && (
|
||||
<>
|
||||
{nums.at(-1) < pages - 1 && <span className="px-1 text-subtle">…</span>}
|
||||
<button className={clsx(btn, 'hover:bg-surface-2')} onClick={() => onChange(pages)}>{pages}</button>
|
||||
</>
|
||||
)}
|
||||
<button className={clsx(btn, 'text-muted hover:bg-surface-2 disabled:opacity-40')} disabled={page >= pages} onClick={() => onChange(page + 1)} aria-label="Вперёд">
|
||||
<ChevronRight className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Segmented({ value, onChange, options, className }) {
|
||||
return (
|
||||
<div className={clsx('inline-flex rounded-xl border border-line bg-surface-2 p-1', className)}>
|
||||
{options.map((o) => (
|
||||
<button
|
||||
key={o.value}
|
||||
onClick={() => onChange(o.value)}
|
||||
title={o.title}
|
||||
className={clsx(
|
||||
'flex h-8 items-center gap-1.5 rounded-lg px-3 text-xs font-medium transition',
|
||||
value === o.value ? 'bg-surface text-ink shadow-sm' : 'text-muted hover:text-ink'
|
||||
)}
|
||||
>
|
||||
{o.icon && <o.icon className="size-4" />}
|
||||
{o.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Switch({ checked, onChange, label }) {
|
||||
return (
|
||||
<label className="inline-flex cursor-pointer items-center gap-2.5 text-sm">
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={checked}
|
||||
onClick={() => onChange(!checked)}
|
||||
className={clsx('relative h-6 w-11 rounded-full transition', checked ? 'bg-brand-600' : 'bg-line')}
|
||||
>
|
||||
<span className={clsx('absolute top-0.5 size-5 rounded-full bg-white shadow transition-all', checked ? 'left-[22px]' : 'left-0.5')} />
|
||||
</button>
|
||||
{label}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- Тема ----------
|
||||
export function useTheme() {
|
||||
const [dark, setDark] = useState(() => document.documentElement.classList.contains('dark'));
|
||||
const toggle = useCallback(() => {
|
||||
setDark((d) => {
|
||||
const next = !d;
|
||||
document.documentElement.classList.toggle('dark', next);
|
||||
try {
|
||||
localStorage.setItem('elib-theme', next ? 'dark' : 'light');
|
||||
} catch {}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
return [dark, toggle];
|
||||
}
|
||||
|
||||
export function ThemeToggle({ className }) {
|
||||
const [dark, toggle] = useTheme();
|
||||
return (
|
||||
<button onClick={toggle} className={clsx('rounded-xl p-2 text-muted transition hover:bg-surface-2 hover:text-ink', className)} title={dark ? 'Светлая тема' : 'Тёмная тема'}>
|
||||
{dark ? <Sun className="size-5" /> : <Moon className="size-5" />}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- Уведомления ----------
|
||||
const ToastCtx = createContext(() => {});
|
||||
export function ToastProvider({ children }) {
|
||||
const [items, setItems] = useState([]);
|
||||
const push = useCallback((text, type = 'success') => {
|
||||
const id = Math.random();
|
||||
setItems((s) => [...s, { id, text, type }]);
|
||||
setTimeout(() => setItems((s) => s.filter((t) => t.id !== id)), 3500);
|
||||
}, []);
|
||||
return (
|
||||
<ToastCtx.Provider value={push}>
|
||||
{children}
|
||||
<div aria-live="polite" className="pointer-events-none fixed right-4 bottom-4 z-[60] flex flex-col gap-2">
|
||||
{items.map((t) => (
|
||||
<div key={t.id} role={t.type === 'error' ? 'alert' : 'status'} className="pointer-events-auto flex animate-slide-up items-center gap-2.5 rounded-xl border border-line bg-surface px-4 py-3 text-sm shadow-xl">
|
||||
{t.type === 'error' ? <AlertCircle className="size-5 text-rose-500" /> : <CheckCircle2 className="size-5 text-emerald-500" />}
|
||||
{t.text}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ToastCtx.Provider>
|
||||
);
|
||||
}
|
||||
export const useToast = () => useContext(ToastCtx);
|
||||
@@ -0,0 +1,220 @@
|
||||
@import 'tailwindcss';
|
||||
|
||||
@custom-variant dark (&:where(.dark, .dark *));
|
||||
|
||||
/* ---------- Токены темы ---------- */
|
||||
:root {
|
||||
--bg: #f6f7fb;
|
||||
--surface: #ffffff;
|
||||
--surface-2: #f1f3f9;
|
||||
--line: #e4e7f0;
|
||||
--ink: #0f172a;
|
||||
--muted: #5b6478;
|
||||
--subtle: #8a93a8;
|
||||
|
||||
/* Палитра графиков (проверена на различимость при дальтонизме) */
|
||||
--series-1: #2a78d6;
|
||||
--series-2: #eb6834;
|
||||
--series-3: #1baf7a;
|
||||
--series-4: #6250d6;
|
||||
--chart-grid: #e8ebf2;
|
||||
--seq-0: #f1f3f9;
|
||||
--seq-1: #cde2fb;
|
||||
--seq-2: #9ec5f4;
|
||||
--seq-3: #6da7ec;
|
||||
--seq-4: #3987e5;
|
||||
--seq-5: #256abf;
|
||||
--seq-6: #184f95;
|
||||
--seq-7: #0d366b;
|
||||
color-scheme: light;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--bg: #0b0f1a;
|
||||
--surface: #121829;
|
||||
--surface-2: #1a2136;
|
||||
--line: #262f47;
|
||||
--ink: #e8ebf4;
|
||||
--muted: #a3acc2;
|
||||
--subtle: #6f7a94;
|
||||
|
||||
--series-1: #3987e5;
|
||||
--series-2: #d95926;
|
||||
--series-3: #199e70;
|
||||
--series-4: #9085e9;
|
||||
--chart-grid: #222a40;
|
||||
--seq-0: #1a2136;
|
||||
--seq-1: #0d366b;
|
||||
--seq-2: #104281;
|
||||
--seq-3: #184f95;
|
||||
--seq-4: #256abf;
|
||||
--seq-5: #3987e5;
|
||||
--seq-6: #6da7ec;
|
||||
--seq-7: #9ec5f4;
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--font-sans: 'Inter Variable', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
|
||||
--color-bg: var(--bg);
|
||||
--color-surface: var(--surface);
|
||||
--color-surface-2: var(--surface-2);
|
||||
--color-line: var(--line);
|
||||
--color-ink: var(--ink);
|
||||
--color-muted: var(--muted);
|
||||
--color-subtle: var(--subtle);
|
||||
}
|
||||
|
||||
/* Фирменный цвет — поменяйте под брендбук университета */
|
||||
@theme {
|
||||
--color-brand-50: #eef2ff;
|
||||
--color-brand-100: #e0e7ff;
|
||||
--color-brand-200: #c7d2fe;
|
||||
--color-brand-300: #a5b4fc;
|
||||
--color-brand-400: #818cf8;
|
||||
--color-brand-500: #6366f1;
|
||||
--color-brand-600: #4f46e5;
|
||||
--color-brand-700: #4338ca;
|
||||
--color-brand-800: #3730a3;
|
||||
--color-brand-900: #312e81;
|
||||
--animate-fade-in: fade-in 0.25s ease-out both;
|
||||
--animate-slide-up: slide-up 0.3s cubic-bezier(0.2, 0.8, 0.2, 1) both;
|
||||
}
|
||||
|
||||
@keyframes fade-in {
|
||||
from { opacity: 0; }
|
||||
to { opacity: 1; }
|
||||
}
|
||||
@keyframes slide-up {
|
||||
from { opacity: 0; transform: translateY(10px); }
|
||||
to { opacity: 1; transform: none; }
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
background: var(--bg);
|
||||
color: var(--ink);
|
||||
font-family: var(--font-sans);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
font-feature-settings: 'cv11', 'ss01';
|
||||
}
|
||||
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--line) transparent;
|
||||
}
|
||||
|
||||
::selection {
|
||||
background: color-mix(in srgb, var(--color-brand-500) 25%, transparent);
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.card {
|
||||
@apply rounded-2xl border border-line bg-surface shadow-[0_1px_2px_rgba(15,23,42,0.04)];
|
||||
}
|
||||
.input {
|
||||
@apply h-10 w-full rounded-xl border border-line bg-surface px-3 text-sm text-ink outline-none transition placeholder:text-subtle focus:border-brand-400 focus:ring-4 focus:ring-brand-500/15;
|
||||
}
|
||||
.label {
|
||||
@apply mb-1.5 block text-xs font-medium text-muted;
|
||||
}
|
||||
.tnum {
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
}
|
||||
|
||||
.hero-gradient {
|
||||
background:
|
||||
radial-gradient(1200px 400px at 10% -10%, rgba(139, 92, 246, 0.35), transparent 60%),
|
||||
radial-gradient(800px 400px at 100% 0%, rgba(14, 165, 233, 0.3), transparent 60%),
|
||||
linear-gradient(135deg, #312e81 0%, #4338ca 45%, #6d28d9 100%);
|
||||
}
|
||||
|
||||
.grid-pattern {
|
||||
background-image:
|
||||
linear-gradient(rgba(255, 255, 255, 0.06) 1px, transparent 1px),
|
||||
linear-gradient(90deg, rgba(255, 255, 255, 0.06) 1px, transparent 1px);
|
||||
background-size: 32px 32px;
|
||||
}
|
||||
|
||||
/* ---------- Печать карточек с логинами (components/Credentials.jsx) ---------- */
|
||||
.print-area {
|
||||
display: none;
|
||||
}
|
||||
@media print {
|
||||
@page {
|
||||
size: A4;
|
||||
margin: 10mm;
|
||||
}
|
||||
body * {
|
||||
visibility: hidden;
|
||||
}
|
||||
.print-area,
|
||||
.print-area * {
|
||||
visibility: visible;
|
||||
}
|
||||
.print-area {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 6mm;
|
||||
position: absolute;
|
||||
inset: 0 auto auto 0;
|
||||
width: 100%;
|
||||
color: #000;
|
||||
background: #fff;
|
||||
font-family: system-ui, sans-serif;
|
||||
}
|
||||
.print-card {
|
||||
border: 1px dashed #888;
|
||||
border-radius: 3mm;
|
||||
padding: 4mm 5mm;
|
||||
break-inside: avoid;
|
||||
font-size: 10pt;
|
||||
height: 62mm;
|
||||
overflow: hidden;
|
||||
}
|
||||
.print-card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 3mm;
|
||||
margin-bottom: 3mm;
|
||||
}
|
||||
.print-logo {
|
||||
width: 10mm;
|
||||
height: 10mm;
|
||||
object-fit: contain;
|
||||
}
|
||||
.print-org {
|
||||
font-weight: 700;
|
||||
font-size: 11pt;
|
||||
}
|
||||
.print-sub {
|
||||
color: #555;
|
||||
font-size: 8.5pt;
|
||||
}
|
||||
.print-name {
|
||||
font-weight: 600;
|
||||
font-size: 11pt;
|
||||
}
|
||||
.print-creds {
|
||||
margin-top: 2.5mm;
|
||||
border-collapse: collapse;
|
||||
font-size: 10pt;
|
||||
}
|
||||
.print-creds td {
|
||||
padding: 0.6mm 3mm 0.6mm 0;
|
||||
vertical-align: top;
|
||||
}
|
||||
.print-creds td:first-child {
|
||||
color: #555;
|
||||
}
|
||||
.print-creds td:last-child {
|
||||
font-family: Consolas, 'Courier New', monospace;
|
||||
word-break: break-all;
|
||||
}
|
||||
.print-note {
|
||||
margin-top: 2mm;
|
||||
font-size: 8pt;
|
||||
color: #555;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { NavLink, Outlet, useLocation } from 'react-router-dom';
|
||||
import clsx from 'clsx';
|
||||
import { Activity, BarChart3, BookCopy, FileCheck2, FolderTree, Menu, Settings, Users, X } from 'lucide-react';
|
||||
import { api } from '../lib/api';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { ThemeToggle } from '../components/ui';
|
||||
import UserMenu from '../components/UserMenu';
|
||||
import { Logo, PendingBanner } from './AppLayout';
|
||||
|
||||
const NAV = [
|
||||
{ to: '/admin', label: 'Статистика', icon: BarChart3, end: true },
|
||||
{ to: '/admin/activity', label: 'Журнал событий', icon: Activity },
|
||||
{ to: '/admin/users', label: 'Пользователи', icon: Users },
|
||||
{ to: '/admin/moderation', label: 'Модерация', icon: FileCheck2, badge: true },
|
||||
{ to: '/admin/books', label: 'Книги', icon: BookCopy },
|
||||
{ to: '/admin/categories', label: 'Категории', icon: FolderTree },
|
||||
{ to: '/admin/settings', label: 'Настройки и AD', icon: Settings, role: 'ADMIN' },
|
||||
];
|
||||
|
||||
export default function AdminLayout() {
|
||||
const { can } = useAuth();
|
||||
const [open, setOpen] = useState(false);
|
||||
const loc = useLocation();
|
||||
useEffect(() => {
|
||||
setOpen(false);
|
||||
}, [loc.pathname]);
|
||||
// счётчик работ на модерации
|
||||
const [pending, setPending] = useState(0);
|
||||
useEffect(() => {
|
||||
const load = () => api('/submissions/pending-count').then((d) => setPending(d.count)).catch(() => {});
|
||||
load();
|
||||
const t = setInterval(load, 60_000);
|
||||
window.addEventListener('elib:moderation', load);
|
||||
return () => {
|
||||
clearInterval(t);
|
||||
window.removeEventListener('elib:moderation', load);
|
||||
};
|
||||
}, []);
|
||||
|
||||
const sidebar = (
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="flex h-16 items-center px-5">
|
||||
<Logo />
|
||||
</div>
|
||||
<div className="px-5 pt-2 pb-2 text-[11px] font-semibold tracking-wider text-subtle uppercase">Управление</div>
|
||||
<nav className="flex flex-col gap-0.5 px-3">
|
||||
{NAV.filter((n) => !n.role || can(n.role)).map((n) => (
|
||||
<NavLink
|
||||
key={n.to}
|
||||
to={n.to}
|
||||
end={n.end}
|
||||
className={({ isActive }) =>
|
||||
clsx(
|
||||
'flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition',
|
||||
isActive ? 'bg-brand-600 text-white shadow-md shadow-brand-600/25' : 'text-muted hover:bg-surface-2 hover:text-ink'
|
||||
)
|
||||
}
|
||||
>
|
||||
<n.icon className="size-[18px]" />
|
||||
<span className="flex-1">{n.label}</span>
|
||||
{n.badge && pending > 0 && (
|
||||
<span className="min-w-5 rounded-full bg-amber-500 px-1.5 text-center text-[11px] leading-5 font-semibold text-white tnum">{pending}</span>
|
||||
)}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen lg:pl-64">
|
||||
<PendingBanner />
|
||||
<aside className="fixed inset-y-0 left-0 z-40 hidden w-64 border-r border-line bg-surface lg:block">{sidebar}</aside>
|
||||
{open && (
|
||||
<div className="fixed inset-0 z-50 lg:hidden">
|
||||
<div className="absolute inset-0 animate-fade-in bg-slate-950/50" onClick={() => setOpen(false)} />
|
||||
<aside className="absolute inset-y-0 left-0 w-72 animate-slide-up border-r border-line bg-surface">
|
||||
<button className="absolute top-4 right-3 rounded-lg p-1.5 text-muted" onClick={() => setOpen(false)} aria-label="Закрыть меню">
|
||||
<X className="size-5" />
|
||||
</button>
|
||||
{sidebar}
|
||||
</aside>
|
||||
</div>
|
||||
)}
|
||||
<header className="sticky top-0 z-30 flex h-16 items-center gap-3 border-b border-line bg-surface/80 px-4 backdrop-blur-xl sm:px-6">
|
||||
<button className="rounded-lg p-2 text-muted hover:bg-surface-2 lg:hidden" onClick={() => setOpen(true)} aria-label="Меню">
|
||||
<Menu className="size-5" />
|
||||
</button>
|
||||
<div className="text-sm font-semibold text-muted lg:hidden">Панель управления</div>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<ThemeToggle />
|
||||
<UserMenu inAdmin />
|
||||
</div>
|
||||
</header>
|
||||
<main className="mx-auto max-w-[1400px] animate-fade-in p-4 sm:p-6 lg:p-8" key={loc.pathname}>
|
||||
<Outlet />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function PageHeader({ title, subtitle, actions }) {
|
||||
return (
|
||||
<div className="mb-6 flex flex-wrap items-end justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold tracking-tight">{title}</h1>
|
||||
{subtitle && <p className="mt-1 text-sm text-muted">{subtitle}</p>}
|
||||
</div>
|
||||
{actions && <div className="flex flex-wrap items-center gap-2">{actions}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link, NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom';
|
||||
import clsx from 'clsx';
|
||||
import { BookMarked, Compass, Home, LayoutDashboard, ListChecks, PenLine, Search, UserRound } from 'lucide-react';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { ThemeToggle } from '../components/ui';
|
||||
import UserMenu from '../components/UserMenu';
|
||||
import { OrgLogo } from '../pages/OrgScreens';
|
||||
|
||||
export function Logo({ light, compact }) {
|
||||
const { org } = useAuth();
|
||||
return (
|
||||
<Link to="/" className="flex min-w-0 items-center gap-2.5">
|
||||
<OrgLogo org={org} className="size-9" />
|
||||
{!compact && (
|
||||
<div className="min-w-0 max-w-[16rem] leading-tight">
|
||||
<div className={clsx('truncate text-sm font-bold tracking-tight', light ? 'text-white' : 'text-ink')} title={org?.name}>{org?.shortName || org?.name || 'E-Library'}</div>
|
||||
<div className={clsx('hidden truncate text-[11px] sm:block', light ? 'text-white/70' : 'text-muted')}>{org?.shortName ? org.name : 'Электронная библиотека'}</div>
|
||||
</div>
|
||||
)}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
/** Организация ещё не одобрена владельцем платформы — видит только её администратор */
|
||||
export function PendingBanner() {
|
||||
const { org } = useAuth();
|
||||
if (org?.status !== 'PENDING') return null;
|
||||
return (
|
||||
<div className="bg-amber-500 px-4 py-2 text-center text-sm font-medium text-white">
|
||||
Заявка организации на проверке — студенты и преподаватели смогут войти после одобрения. Пока можно{' '}
|
||||
<Link to="/admin/settings" className="underline underline-offset-2">настроить библиотеку</Link>.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const NAV = [
|
||||
{ to: '/', label: 'Главная', icon: Home, end: true },
|
||||
{ to: '/cabinet', label: 'Кабинет', icon: UserRound },
|
||||
{ to: '/catalog', label: 'Каталог', icon: Compass },
|
||||
{ to: '/lists', label: 'Литература', icon: ListChecks },
|
||||
{ to: '/publications', label: 'Публикации', icon: PenLine },
|
||||
{ to: '/favorites', label: 'Избранное', icon: BookMarked, desktop: false },
|
||||
];
|
||||
|
||||
export default function AppLayout() {
|
||||
const { can } = useAuth();
|
||||
const loc = useLocation();
|
||||
const nav = useNavigate();
|
||||
const [q, setQ] = useState('');
|
||||
useEffect(() => {
|
||||
window.scrollTo(0, 0); // в новых браузерах scrollTo возвращает Promise — его нельзя отдавать React как cleanup
|
||||
}, [loc.pathname]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen pb-20 md:pb-0">
|
||||
<PendingBanner />
|
||||
<header className="sticky top-0 z-30 border-b border-line bg-surface/80 backdrop-blur-xl">
|
||||
<div className="mx-auto flex h-16 max-w-7xl items-center gap-4 px-4 sm:px-6">
|
||||
<Logo />
|
||||
<nav className="ml-2 hidden items-center gap-0.5 md:flex lg:ml-4 lg:gap-1">
|
||||
{NAV.filter((n) => n.desktop !== false).map((n) => (
|
||||
<NavLink
|
||||
key={n.to}
|
||||
to={n.to}
|
||||
end={n.end}
|
||||
className={({ isActive }) =>
|
||||
clsx('rounded-lg px-3 py-2 text-sm font-medium whitespace-nowrap transition', isActive ? 'bg-brand-50 text-brand-700 dark:bg-brand-500/15 dark:text-brand-300' : 'text-muted hover:text-ink')
|
||||
}
|
||||
>
|
||||
{n.desktopLabel || n.label}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
<form
|
||||
className="ml-auto hidden max-w-xs flex-1 lg:block"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
if (q.trim()) nav(`/catalog?q=${encodeURIComponent(q.trim())}`);
|
||||
setQ('');
|
||||
}}
|
||||
>
|
||||
{loc.pathname !== '/' && loc.pathname !== '/catalog' && (
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-subtle" />
|
||||
<input className="input h-9 rounded-full pl-9" placeholder="Быстрый поиск…" value={q} onChange={(e) => setQ(e.target.value)} />
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
<div className="ml-auto flex items-center gap-1 lg:ml-0">
|
||||
{can('MODERATOR') && (
|
||||
<Link to="/admin" className="hidden items-center gap-2 rounded-xl px-3 py-2 text-sm font-medium text-muted transition hover:bg-surface-2 hover:text-ink sm:flex">
|
||||
<LayoutDashboard className="size-4" /> Панель
|
||||
</Link>
|
||||
)}
|
||||
<ThemeToggle />
|
||||
<UserMenu />
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="animate-fade-in" key={loc.pathname}>
|
||||
<Outlet />
|
||||
</main>
|
||||
|
||||
<footer className="mt-16 hidden border-t border-line py-8 text-center text-xs text-subtle md:block">
|
||||
© {new Date().getFullYear()} Электронная библиотека · Доступ для студентов и сотрудников по учётной записи университета
|
||||
</footer>
|
||||
|
||||
{/* Нижняя навигация на телефонах */}
|
||||
<nav className="fixed inset-x-0 bottom-0 z-30 grid grid-cols-5 border-t border-line bg-surface/95 pb-[env(safe-area-inset-bottom)] backdrop-blur-xl md:hidden">
|
||||
{NAV.filter((n) => n.to !== '/favorites').map((n) => (
|
||||
<NavLink
|
||||
key={n.to}
|
||||
to={n.to}
|
||||
end={n.end}
|
||||
className={({ isActive }) => clsx('flex flex-col items-center gap-1 py-2.5 text-[10px] font-medium', isActive ? 'text-brand-600 dark:text-brand-300' : 'text-subtle')}
|
||||
>
|
||||
<n.icon className="size-5" />
|
||||
{n.label}
|
||||
</NavLink>
|
||||
))}
|
||||
</nav>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
|
||||
export class ApiError extends Error {
|
||||
constructor(message, status) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
export async function api(path, { method = 'GET', body, signal } = {}) {
|
||||
const isForm = body instanceof FormData;
|
||||
const res = await fetch('/api' + path, {
|
||||
method,
|
||||
signal,
|
||||
credentials: 'same-origin',
|
||||
headers: body && !isForm ? { 'Content-Type': 'application/json' } : undefined,
|
||||
body: body && !isForm ? JSON.stringify(body) : body,
|
||||
});
|
||||
if (res.status === 401 && !path.startsWith('/auth')) window.dispatchEvent(new Event('elib:unauthorized'));
|
||||
const data = res.headers.get('content-type')?.includes('json') ? await res.json() : null;
|
||||
if (res.status === 403 && data?.code === 'PASSWORD_CHANGE_REQUIRED') window.dispatchEvent(new Event('elib:password-change'));
|
||||
if (!res.ok) throw new ApiError(data?.error || `Ошибка ${res.status}`, res.status);
|
||||
return data;
|
||||
}
|
||||
|
||||
/** POST, который возвращает файл (Excel) — скачивание через временную ссылку */
|
||||
export async function downloadPost(path, body, fallbackName = 'file') {
|
||||
const res = await fetch('/api' + path, {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const data = await res.json().catch(() => null);
|
||||
throw new ApiError(data?.error || `Ошибка ${res.status}`, res.status);
|
||||
}
|
||||
const cd = res.headers.get('content-disposition') || '';
|
||||
const m = cd.match(/filename\*=UTF-8''([^;]+)/);
|
||||
const name = m ? decodeURIComponent(m[1]) : fallbackName;
|
||||
const url = URL.createObjectURL(await res.blob());
|
||||
const a = Object.assign(document.createElement('a'), { href: url, download: name });
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 10_000);
|
||||
}
|
||||
|
||||
/** Загрузка файлов с прогрессом */
|
||||
export function upload(path, method, formData, onProgress) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open(method, '/api' + path);
|
||||
xhr.upload.onprogress = (e) => e.lengthComputable && onProgress?.(e.loaded / e.total);
|
||||
xhr.onload = () => {
|
||||
let data = null;
|
||||
try {
|
||||
data = JSON.parse(xhr.responseText);
|
||||
} catch {}
|
||||
if (xhr.status >= 200 && xhr.status < 300) resolve(data);
|
||||
else reject(new ApiError(data?.error || `Ошибка ${xhr.status}`, xhr.status));
|
||||
};
|
||||
xhr.onerror = () => reject(new ApiError('Сеть недоступна', 0));
|
||||
xhr.send(formData);
|
||||
});
|
||||
}
|
||||
|
||||
export function qs(params) {
|
||||
const p = new URLSearchParams();
|
||||
for (const [k, v] of Object.entries(params)) if (v !== undefined && v !== null && v !== '') p.set(k, v);
|
||||
const s = p.toString();
|
||||
return s ? '?' + s : '';
|
||||
}
|
||||
|
||||
/** Хук загрузки данных */
|
||||
export function useApi(path, deps = []) {
|
||||
const [state, setState] = useState({ data: null, error: null, loading: !!path });
|
||||
const ctrl = useRef();
|
||||
const load = useCallback(
|
||||
async (silent = false) => {
|
||||
if (!path) return;
|
||||
ctrl.current?.abort();
|
||||
const c = (ctrl.current = new AbortController());
|
||||
if (!silent) setState((s) => ({ ...s, loading: true, error: null }));
|
||||
try {
|
||||
const data = await api(path, { signal: c.signal });
|
||||
setState({ data, error: null, loading: false });
|
||||
} catch (e) {
|
||||
if (e.name !== 'AbortError') setState((s) => ({ ...s, error: e, loading: false }));
|
||||
}
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[path, ...deps]
|
||||
);
|
||||
useEffect(() => {
|
||||
load();
|
||||
return () => ctrl.current?.abort();
|
||||
}, [load]);
|
||||
return { ...state, reload: load, setData: (fn) => setState((s) => ({ ...s, data: typeof fn === 'function' ? fn(s.data) : fn })) };
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useState } from 'react';
|
||||
import { api } from './api';
|
||||
|
||||
const AuthCtx = createContext(null);
|
||||
const RANK = { USER: 0, MODERATOR: 1, ADMIN: 2 };
|
||||
|
||||
/** Адрес организации — первый сегмент пути: /tsue/catalog → tsue. Пусто — страницы платформы */
|
||||
export const ROOT_PAGES = ['', 'register', 'platform'];
|
||||
export const currentSlug = () => decodeURIComponent(window.location.pathname.split('/')[1] || '').toLowerCase();
|
||||
|
||||
/**
|
||||
* Контекст библиотеки организации.
|
||||
* org — публичные данные (название, логотип, статус); null — библиотека не найдена
|
||||
* user — вошедший пользователь; undefined — загрузка
|
||||
* mismatch — вошёл пользователь другой организации (сессия одна на сайт)
|
||||
*/
|
||||
export function AuthProvider({ slug, children }) {
|
||||
const [user, setUser] = useState(undefined);
|
||||
const [org, setOrg] = useState(undefined);
|
||||
const [userOrg, setUserOrg] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (slug) {
|
||||
api(`/orgs/${encodeURIComponent(slug)}/public`)
|
||||
.then((d) => setOrg(d.org))
|
||||
.catch(() => setOrg(null));
|
||||
} else setOrg(null);
|
||||
api('/auth/me')
|
||||
.then((d) => {
|
||||
setUser(d.user);
|
||||
setUserOrg(d.org);
|
||||
})
|
||||
.catch(() => setUser(null));
|
||||
const onUnauth = () => setUser(null);
|
||||
// сервер требует сменить временный пароль
|
||||
const onMustChange = () => setUser((u) => (u ? { ...u, mustChangePassword: true } : u));
|
||||
window.addEventListener('elib:unauthorized', onUnauth);
|
||||
window.addEventListener('elib:password-change', onMustChange);
|
||||
return () => {
|
||||
window.removeEventListener('elib:unauthorized', onUnauth);
|
||||
window.removeEventListener('elib:password-change', onMustChange);
|
||||
};
|
||||
}, [slug]);
|
||||
|
||||
useEffect(() => {
|
||||
document.title = org ? `${org.shortName || org.name} — электронная библиотека` : 'E-Library — электронные библиотеки организаций';
|
||||
}, [org]);
|
||||
|
||||
const login = useCallback(
|
||||
async (username, password, kind) => {
|
||||
const d = await api('/auth/login', { method: 'POST', body: { org: slug || null, username, password, kind } });
|
||||
setUser(d.user);
|
||||
setUserOrg(d.org);
|
||||
return d.user;
|
||||
},
|
||||
[slug]
|
||||
);
|
||||
|
||||
const logout = useCallback(async () => {
|
||||
await api('/auth/logout', { method: 'POST' }).catch(() => {});
|
||||
setUser(null);
|
||||
setUserOrg(null);
|
||||
}, []);
|
||||
|
||||
/** Обновить данные организации (после изменения названия / логотипа в настройках) */
|
||||
const reloadOrg = useCallback(() => slug && api(`/orgs/${encodeURIComponent(slug)}/public`).then((d) => setOrg(d.org)).catch(() => {}), [slug]);
|
||||
|
||||
const can = useCallback((role) => !!user && RANK[user.role] >= RANK[role], [user]);
|
||||
/** Преподаватель (подтверждённый) или модератор — может вести списки литературы */
|
||||
const isTeacher = !!user && (user.kind === 'TEACHER' || RANK[user.role] >= RANK.MODERATOR);
|
||||
const mismatch = !!user && !!org && user.organizationId !== org.id;
|
||||
// совместимость: название библиотеки в шапке
|
||||
const cfg = { universityName: org?.name || 'Электронная библиотека', ldapEnabled: !!org?.ldapEnabled };
|
||||
|
||||
return (
|
||||
<AuthCtx.Provider value={{ slug, org, userOrg, user, setUser, cfg, login, logout, can, isTeacher, mismatch, reloadOrg }}>
|
||||
{children}
|
||||
</AuthCtx.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export const useAuth = () => useContext(AuthCtx);
|
||||
@@ -0,0 +1,140 @@
|
||||
import {
|
||||
Atom, BookOpen, Briefcase, Calculator, Cpu, FlaskConical, Globe, GraduationCap, HeartPulse, Landmark,
|
||||
Languages, Leaf, Music, Palette, Scale, Sigma, TrendingUp, Wrench, Building2, Microscope,
|
||||
} from 'lucide-react';
|
||||
|
||||
export const CATEGORY_ICONS = {
|
||||
BookOpen, Sigma, Atom, Cpu, TrendingUp, Scale, HeartPulse, Languages, Landmark, Wrench, GraduationCap,
|
||||
FlaskConical, Globe, Music, Palette, Leaf, Briefcase, Calculator, Building2, Microscope,
|
||||
};
|
||||
|
||||
export const BOOK_TYPES = {
|
||||
textbook: 'Учебник',
|
||||
tutorial: 'Учебное пособие',
|
||||
methodical: 'Методические указания',
|
||||
lecture: 'Конспект лекций',
|
||||
monograph: 'Монография',
|
||||
atlas: 'Атлас',
|
||||
article: 'Научная статья',
|
||||
conference: 'Тезисы конференции',
|
||||
coursework: 'Курсовая работа',
|
||||
thesis: 'Выпускная квалификационная работа',
|
||||
report: 'Реферат / доклад',
|
||||
dissertation: 'Диссертация',
|
||||
abstract: 'Автореферат',
|
||||
periodical: 'Периодическое издание',
|
||||
reference: 'Справочник',
|
||||
fiction: 'Художественная литература',
|
||||
other: 'Другое',
|
||||
};
|
||||
|
||||
export const LANGUAGES = { ru: 'Русский', uz: 'Oʻzbekcha', en: 'English', kk: 'Қазақша', tg: 'Тоҷикӣ', de: 'Deutsch', fr: 'Français', other: 'Другой' };
|
||||
|
||||
export const ROLE_LABELS = { USER: 'Читатель', MODERATOR: 'Модератор', ADMIN: 'Администратор' };
|
||||
|
||||
/** Тип пользователя: студент / преподаватель / сотрудник */
|
||||
export const KIND_LABELS = { STUDENT: 'Студент', TEACHER: 'Преподаватель', STAFF: 'Сотрудник' };
|
||||
export const KIND_COLORS = { STUDENT: 'brand', TEACHER: 'violet', STAFF: 'gray' };
|
||||
|
||||
export const EVENT_LABELS = {
|
||||
LOGIN: 'Вход',
|
||||
LOGIN_FAILED: 'Неудачный вход',
|
||||
LOGOUT: 'Выход',
|
||||
REGISTER: 'Первый вход',
|
||||
VIEW: 'Просмотр',
|
||||
READ: 'Чтение онлайн',
|
||||
DOWNLOAD: 'Скачивание',
|
||||
SEARCH: 'Поиск',
|
||||
FAVORITE: 'В избранное',
|
||||
BOOK_CREATE: 'Добавлена книга',
|
||||
BOOK_UPDATE: 'Изменена книга',
|
||||
BOOK_DELETE: 'Удалена книга',
|
||||
USER_UPDATE: 'Изменён пользователь',
|
||||
SUBMIT: 'Работа на модерацию',
|
||||
SUBMIT_APPROVE: 'Работа одобрена',
|
||||
SUBMIT_REJECT: 'Работа отклонена',
|
||||
LIST_CREATE: 'Создан список литературы',
|
||||
ENDORSE: 'Подтверждено руководителем',
|
||||
ORG_REGISTER: 'Регистрация организации',
|
||||
ORG_UPDATE: 'Изменены настройки',
|
||||
ORG_STATUS: 'Изменён статус организации',
|
||||
ORG_DELETE: 'Организация удалена',
|
||||
USERS_IMPORT: 'Загрузка списка пользователей',
|
||||
PASSWORD_RESET: 'Выданы новые пароли',
|
||||
PASSWORD_CHANGE: 'Смена пароля',
|
||||
};
|
||||
|
||||
/** Типы работ, которые могут публиковать студенты */
|
||||
export const STUDENT_TYPES = ['article', 'conference', 'coursework', 'thesis', 'report', 'other'];
|
||||
/** …и преподаватели (учебно-методические материалы) */
|
||||
export const TEACHER_TYPES = ['textbook', 'tutorial', 'methodical', 'lecture', 'monograph', 'reference', 'atlas', 'article', 'conference', 'other'];
|
||||
|
||||
export const SUBMISSION_STATUS = {
|
||||
DRAFT: { label: 'Черновик', color: 'gray' },
|
||||
PENDING: { label: 'На модерации', color: 'amber' },
|
||||
PUBLISHED: { label: 'Опубликовано', color: 'green' },
|
||||
REJECTED: { label: 'На доработку', color: 'red' },
|
||||
};
|
||||
|
||||
export const nf = new Intl.NumberFormat('ru-RU');
|
||||
export const fmtNum = (n) => nf.format(n ?? 0);
|
||||
|
||||
export function fmtSize(bytes) {
|
||||
if (!bytes) return '—';
|
||||
const u = ['Б', 'КБ', 'МБ', 'ГБ', 'ТБ'];
|
||||
let i = 0;
|
||||
let n = bytes;
|
||||
while (n >= 1024 && i < u.length - 1) {
|
||||
n /= 1024;
|
||||
i++;
|
||||
}
|
||||
return `${n.toFixed(n < 10 && i ? 1 : 0)} ${u[i]}`;
|
||||
}
|
||||
|
||||
export const fmtDate = (d) => (d ? new Date(d).toLocaleDateString('ru-RU', { day: 'numeric', month: 'short', year: 'numeric' }) : '—');
|
||||
export const fmtDateTime = (d) =>
|
||||
d ? new Date(d).toLocaleString('ru-RU', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '—';
|
||||
export const fmtDay = (day) => new Date(day + 'T12:00:00').toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' });
|
||||
|
||||
export function timeAgo(d) {
|
||||
if (!d) return 'никогда';
|
||||
const s = (Date.now() - new Date(d).getTime()) / 1000;
|
||||
if (s < 60) return 'только что';
|
||||
if (s < 3600) return `${Math.floor(s / 60)} мин назад`;
|
||||
if (s < 86400) return `${Math.floor(s / 3600)} ч назад`;
|
||||
if (s < 86400 * 7) return `${Math.floor(s / 86400)} дн назад`;
|
||||
return fmtDate(d);
|
||||
}
|
||||
|
||||
export function plural(n, one, few, many) {
|
||||
const m10 = n % 10;
|
||||
const m100 = n % 100;
|
||||
if (m10 === 1 && m100 !== 11) return one;
|
||||
if (m10 >= 2 && m10 <= 4 && (m100 < 10 || m100 >= 20)) return few;
|
||||
return many;
|
||||
}
|
||||
|
||||
export function initials(name = '') {
|
||||
return name
|
||||
.split(/\s+/)
|
||||
.filter(Boolean)
|
||||
.slice(0, 2)
|
||||
.map((s) => s[0].toUpperCase())
|
||||
.join('');
|
||||
}
|
||||
|
||||
export function hashColor(str = '') {
|
||||
let h = 0;
|
||||
for (const c of str) h = (h * 31 + c.charCodeAt(0)) >>> 0;
|
||||
return h;
|
||||
}
|
||||
|
||||
export const READABLE = ['pdf', 'txt', 'mp4', 'mp3'];
|
||||
|
||||
export function greeting() {
|
||||
const h = new Date().getHours();
|
||||
if (h < 5) return 'Доброй ночи';
|
||||
if (h < 12) return 'Доброе утро';
|
||||
if (h < 18) return 'Добрый день';
|
||||
return 'Добрый вечер';
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { StrictMode, Suspense, lazy } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { BrowserRouter, Navigate, Route, Routes, useLocation } from 'react-router-dom';
|
||||
import '@fontsource-variable/inter';
|
||||
import './index.css';
|
||||
import { AuthProvider, ROOT_PAGES, currentSlug, useAuth } from './lib/auth';
|
||||
import { PageLoader, ToastProvider } from './components/ui';
|
||||
import AppLayout from './layouts/AppLayout';
|
||||
import Login from './pages/Login';
|
||||
import Home from './pages/Home';
|
||||
import Catalog from './pages/Catalog';
|
||||
import BookDetails from './pages/BookDetails';
|
||||
import Reader from './pages/Reader';
|
||||
import { Favorites, History } from './pages/MyBooks';
|
||||
import Publications from './pages/Publications';
|
||||
import SubmitWork from './pages/SubmitWork';
|
||||
import Cabinet from './pages/Cabinet';
|
||||
import ReadingLists, { Supervised } from './pages/ReadingLists';
|
||||
import ListDetails from './pages/ListDetails';
|
||||
import ChangePassword from './pages/ChangePassword';
|
||||
import { OrgMismatch, OrgNotFound } from './pages/OrgScreens';
|
||||
|
||||
// Страницы платформы: главная, регистрация организации, кабинет владельца платформы
|
||||
const Landing = lazy(() => import('./pages/platform/Landing'));
|
||||
const Register = lazy(() => import('./pages/platform/Register'));
|
||||
const Platform = lazy(() => import('./pages/platform/Platform'));
|
||||
|
||||
// Админ-панель загружается отдельно (графики не нужны обычным читателям)
|
||||
const AdminLayout = lazy(() => import('./layouts/AdminLayout'));
|
||||
const Dashboard = lazy(() => import('./pages/admin/Dashboard'));
|
||||
const AdminBooks = lazy(() => import('./pages/admin/Books'));
|
||||
const AdminCategories = lazy(() => import('./pages/admin/Categories'));
|
||||
const AdminUsers = lazy(() => import('./pages/admin/Users'));
|
||||
const UserDetails = lazy(() => import('./pages/admin/UserDetails'));
|
||||
const Activity = lazy(() => import('./pages/admin/Activity'));
|
||||
const Moderation = lazy(() => import('./pages/admin/Moderation'));
|
||||
const Settings = lazy(() => import('./pages/admin/Settings'));
|
||||
const ImportUsers = lazy(() => import('./pages/admin/ImportUsers'));
|
||||
|
||||
function Protected({ role, children }) {
|
||||
const { user, can, mismatch } = useAuth();
|
||||
const loc = useLocation();
|
||||
if (user === undefined) return <PageLoader />;
|
||||
if (!user) return <Navigate to="/login" replace state={{ from: loc.pathname + loc.search }} />;
|
||||
if (mismatch) return <OrgMismatch />;
|
||||
// выданный системой пароль — сначала сменить
|
||||
if (user.mustChangePassword) return <ChangePassword forced />;
|
||||
if (role && !can(role)) return <Navigate to="/" replace />;
|
||||
return children;
|
||||
}
|
||||
|
||||
/** Библиотека организации: site/<slug>/… */
|
||||
function App() {
|
||||
const { org } = useAuth();
|
||||
if (org === undefined) return <PageLoader />;
|
||||
if (org === null) return <OrgNotFound />;
|
||||
return (
|
||||
<Suspense fallback={<PageLoader />}>
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/read/:id" element={<Protected><Reader /></Protected>} />
|
||||
<Route element={<Protected><AppLayout /></Protected>}>
|
||||
<Route index element={<Home />} />
|
||||
<Route path="catalog" element={<Catalog />} />
|
||||
<Route path="books/:id" element={<BookDetails />} />
|
||||
<Route path="favorites" element={<Favorites />} />
|
||||
<Route path="history" element={<History />} />
|
||||
<Route path="publications" element={<Publications />} />
|
||||
<Route path="publications/new" element={<SubmitWork />} />
|
||||
<Route path="publications/:id/edit" element={<SubmitWork />} />
|
||||
<Route path="cabinet" element={<Cabinet />} />
|
||||
<Route path="cabinet/supervised" element={<Supervised />} />
|
||||
<Route path="lists" element={<ReadingLists />} />
|
||||
<Route path="lists/:id" element={<ListDetails />} />
|
||||
<Route path="account/password" element={<ChangePassword />} />
|
||||
</Route>
|
||||
<Route path="/admin" element={<Protected role="MODERATOR"><AdminLayout /></Protected>}>
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="books" element={<AdminBooks />} />
|
||||
<Route path="moderation" element={<Moderation />} />
|
||||
<Route path="categories" element={<AdminCategories />} />
|
||||
<Route path="users" element={<AdminUsers />} />
|
||||
<Route path="users/import" element={<Protected role="ADMIN"><ImportUsers /></Protected>} />
|
||||
<Route path="users/:id" element={<UserDetails />} />
|
||||
<Route path="activity" element={<Activity />} />
|
||||
<Route path="settings" element={<Protected role="ADMIN"><Settings /></Protected>} />
|
||||
<Route path="system" element={<Navigate to="/admin/settings?tab=server" replace />} />
|
||||
</Route>
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
/** Платформа: site/, site/register, site/platform */
|
||||
function RootApp() {
|
||||
return (
|
||||
<Suspense fallback={<PageLoader />}>
|
||||
<Routes>
|
||||
<Route path="/" element={<Landing />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/platform/*" element={<Platform />} />
|
||||
<Route path="*" element={<Navigate to="/" replace />} />
|
||||
</Routes>
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
// Первый сегмент адреса решает, что показать: страницы платформы или библиотеку организации.
|
||||
// У библиотеки свой basename — все ссылки внутри приложения (/catalog, /admin…) получают префикс /<slug>.
|
||||
const slug = currentSlug();
|
||||
const isRoot = ROOT_PAGES.includes(slug);
|
||||
|
||||
createRoot(document.getElementById('root')).render(
|
||||
<StrictMode>
|
||||
<BrowserRouter basename={isRoot ? undefined : `/${slug}`}>
|
||||
<AuthProvider slug={isRoot ? null : slug}>
|
||||
<ToastProvider>{isRoot ? <RootApp /> : <App />}</ToastProvider>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
</StrictMode>
|
||||
);
|
||||
@@ -0,0 +1,201 @@
|
||||
import { Suspense, lazy, useState } from 'react';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import { BookOpen, ChevronRight, Download, Eye, Heart, Pencil, FileText, GraduationCap, Clock, MessageSquareWarning, Presentation, BadgeCheck } from 'lucide-react';
|
||||
import { api, useApi } from '../lib/api';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { BOOK_TYPES, LANGUAGES, READABLE, SUBMISSION_STATUS, fmtDate, fmtNum, fmtSize } from '../lib/format';
|
||||
import BookCover from '../components/BookCover';
|
||||
import BookCard from '../components/BookCard';
|
||||
import { Badge, Button, ErrorBox, PageLoader, useToast } from '../components/ui';
|
||||
import { AddToListButton } from '../components/Lists';
|
||||
|
||||
const BookStats = lazy(() => import('./admin/BookStats'));
|
||||
const BookForm = lazy(() => import('./admin/BookForm'));
|
||||
|
||||
export default function BookDetails() {
|
||||
const { id } = useParams();
|
||||
const { can, user, isTeacher } = useAuth();
|
||||
const toast = useToast();
|
||||
const { data, error, loading, reload, setData } = useApi(`/books/${id}`, [id]);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [favBusy, setFavBusy] = useState(false);
|
||||
|
||||
if (loading && !data) return <PageLoader />;
|
||||
if (error) return <div className="mx-auto max-w-3xl p-6"><ErrorBox error={error} onRetry={reload} /></div>;
|
||||
const { book, related } = data;
|
||||
|
||||
const toggleFav = async () => {
|
||||
setFavBusy(true);
|
||||
try {
|
||||
await api(`/books/${book.id}/favorite`, { method: book.isFavorite ? 'DELETE' : 'POST' });
|
||||
setData((d) => ({ ...d, book: { ...d.book, isFavorite: !d.book.isFavorite } }));
|
||||
toast(book.isFavorite ? 'Удалено из избранного' : 'Добавлено в избранное');
|
||||
} finally {
|
||||
setFavBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const meta = [
|
||||
['Авторы', book.authors],
|
||||
['Научный руководитель', book.supervisorRef ? (
|
||||
<span className="inline-flex flex-wrap items-center gap-1.5">
|
||||
{book.supervisor || book.supervisorRef.displayName}
|
||||
{book.endorsedAt && <Badge color="violet"><BadgeCheck className="size-3" />подтвердил(а) работу</Badge>}
|
||||
</span>
|
||||
) : book.supervisor],
|
||||
['Год издания', book.year],
|
||||
[book.source === 'USER' ? 'Где представлено' : 'Издательство', book.publisher],
|
||||
['Тип издания', BOOK_TYPES[book.type] || book.type],
|
||||
['Язык', LANGUAGES[book.language] || book.language],
|
||||
['Страниц', book.pages],
|
||||
['ISBN', book.isbn],
|
||||
['УДК / ББК', book.udc],
|
||||
['Формат файла', book.fileExt && `${book.fileExt.toUpperCase()} · ${fmtSize(book.fileSize)}`],
|
||||
book.source === 'USER' && ['Опубликовал(а)', book.createdBy && `${book.createdBy.displayName}${book.createdBy.studyGroup ? ' · ' + book.createdBy.studyGroup : book.createdBy.department ? ' · ' + book.createdBy.department : ''}`],
|
||||
book.source === 'USER' && ['Дата публикации', book.status === 'PUBLISHED' && fmtDate(book.reviewedAt || book.createdAt)],
|
||||
].filter((x) => x && x[1]);
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-7xl px-4 py-8 sm:px-6">
|
||||
<nav className="mb-6 flex items-center gap-1.5 text-sm text-muted">
|
||||
<Link to="/catalog" className="hover:text-ink">Каталог</Link>
|
||||
{book.category && (
|
||||
<>
|
||||
<ChevronRight className="size-4" />
|
||||
<Link to={`/catalog?category=${book.category.id}`} className="hover:text-ink">{book.category.name}</Link>
|
||||
</>
|
||||
)}
|
||||
</nav>
|
||||
|
||||
<div className="grid gap-8 md:grid-cols-[280px_1fr] lg:gap-12">
|
||||
<div className="mx-auto w-56 md:w-full">
|
||||
<div className="md:sticky md:top-24">
|
||||
<BookCover book={book} size="lg" />
|
||||
<div className="mt-5 grid grid-cols-2 gap-3 text-center">
|
||||
<div className="card py-3">
|
||||
<div className="flex items-center justify-center gap-1.5 text-lg font-bold tnum"><Eye className="size-4 text-subtle" />{fmtNum(book.viewCount)}</div>
|
||||
<div className="text-xs text-muted">просмотров</div>
|
||||
</div>
|
||||
<div className="card py-3">
|
||||
<div className="flex items-center justify-center gap-1.5 text-lg font-bold tnum"><Download className="size-4 text-subtle" />{fmtNum(book.downloadCount)}</div>
|
||||
<div className="text-xs text-muted">скачиваний</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{book.category && (
|
||||
<span className="rounded-full px-2.5 py-0.5 text-xs font-medium text-white" style={{ background: book.category.color }}>
|
||||
{book.category.name}
|
||||
</span>
|
||||
)}
|
||||
<Badge>{BOOK_TYPES[book.type] || book.type}</Badge>
|
||||
{book.source === 'USER' && (book.createdBy?.kind === 'TEACHER'
|
||||
? <Badge color="violet"><Presentation className="size-3" />Материал преподавателя</Badge>
|
||||
: <Badge color="green"><GraduationCap className="size-3" />Студенческая работа</Badge>)}
|
||||
{!book.isPublished && <Badge color={SUBMISSION_STATUS[book.status]?.color || 'amber'}>{SUBMISSION_STATUS[book.status]?.label || 'Не опубликовано'}</Badge>}
|
||||
</div>
|
||||
{book.source === 'USER' && !book.isPublished && book.supervisorRef?.id === user.id && book.createdBy?.id !== user.id && (
|
||||
<div className="mt-4 flex items-start gap-3 rounded-2xl bg-violet-50 p-4 text-sm text-violet-900 dark:bg-violet-500/10 dark:text-violet-200">
|
||||
<GraduationCap className="mt-0.5 size-5 shrink-0" />
|
||||
<div className="flex-1">Вы указаны научным руководителем этой работы. {book.endorsedAt ? 'Вы её уже подтвердили.' : 'Подтвердите её в кабинете — библиотекарь увидит вашу отметку.'}</div>
|
||||
<Link to="/cabinet/supervised" className="shrink-0 font-medium underline">Мои студенты</Link>
|
||||
</div>
|
||||
)}
|
||||
{book.source === 'USER' && !book.isPublished && book.createdBy?.id === user.id && (
|
||||
<div className="mt-4 flex items-start gap-3 rounded-2xl bg-amber-50 p-4 text-sm text-amber-900 dark:bg-amber-500/10 dark:text-amber-200">
|
||||
{book.status === 'REJECTED' ? <MessageSquareWarning className="mt-0.5 size-5 shrink-0" /> : <Clock className="mt-0.5 size-5 shrink-0" />}
|
||||
<div className="flex-1">
|
||||
{book.status === 'REJECTED' ? <><b>Работа возвращена на доработку:</b> {book.reviewNote}</> : book.status === 'DRAFT' ? 'Это черновик: его видите только вы.' : 'Работа на проверке у библиотекаря. Её видите только вы и модераторы.'}
|
||||
</div>
|
||||
<Link to={`/publications/${book.id}/edit`} className="shrink-0 font-medium underline">Изменить</Link>
|
||||
</div>
|
||||
)}
|
||||
<h1 className="mt-3 text-3xl font-bold tracking-tight sm:text-4xl [text-wrap:balance]">{book.title}</h1>
|
||||
{book.subtitle && <p className="mt-2 text-lg text-muted">{book.subtitle}</p>}
|
||||
<p className="mt-3 text-lg font-medium text-brand-600 dark:text-brand-300">{book.authors}</p>
|
||||
|
||||
<div className="mt-7 flex flex-wrap gap-3">
|
||||
{book.hasFile && READABLE.includes(book.fileExt) && (
|
||||
<Link to={`/read/${book.id}`} target="_blank" rel="noopener">
|
||||
<Button size="lg" icon={BookOpen}>Читать онлайн</Button>
|
||||
</Link>
|
||||
)}
|
||||
{book.hasFile && (
|
||||
<a href={`/api/books/${book.id}/download`}>
|
||||
<Button size="lg" variant={READABLE.includes(book.fileExt) ? 'secondary' : 'primary'} icon={Download}>
|
||||
Скачать <span className="text-xs opacity-60">{fmtSize(book.fileSize)}</span>
|
||||
</Button>
|
||||
</a>
|
||||
)}
|
||||
<Button size="lg" variant="secondary" onClick={toggleFav} loading={favBusy} className={book.isFavorite ? '!border-rose-200 !text-rose-600 dark:!border-rose-500/30 dark:!text-rose-400' : ''}>
|
||||
<Heart className={`size-5 ${book.isFavorite ? 'fill-current' : ''}`} />
|
||||
{book.isFavorite ? 'В избранном' : 'В избранное'}
|
||||
</Button>
|
||||
{isTeacher && book.isPublished && <AddToListButton bookId={book.id} />}
|
||||
{can('MODERATOR') && (
|
||||
<Button size="lg" variant="ghost" icon={Pencil} onClick={() => setEditing(true)}>Редактировать</Button>
|
||||
)}
|
||||
</div>
|
||||
{!book.hasFile && (
|
||||
<div className="mt-4 flex items-center gap-2 text-sm text-amber-600 dark:text-amber-400">
|
||||
<FileText className="size-4" /> Электронная версия пока не загружена
|
||||
</div>
|
||||
)}
|
||||
|
||||
{book.description && (
|
||||
<div className="mt-10">
|
||||
<h2 className="mb-3 text-lg font-semibold">Описание</h2>
|
||||
<p className="leading-relaxed whitespace-pre-line text-muted">{book.description}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-10">
|
||||
<h2 className="mb-3 text-lg font-semibold">Библиографические данные</h2>
|
||||
<dl className="card divide-y divide-line">
|
||||
{meta.map(([k, v]) => (
|
||||
<div key={k} className="grid grid-cols-[140px_1fr] gap-4 px-5 py-3 text-sm sm:grid-cols-[180px_1fr]">
|
||||
<dt className="text-muted">{k}</dt>
|
||||
<dd className="font-medium break-words">{v}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</div>
|
||||
|
||||
{book.keywords && (
|
||||
<div className="mt-6 flex flex-wrap gap-2">
|
||||
{book.keywords.split(/[,;]/).map((k) => k.trim()).filter(Boolean).map((k) => (
|
||||
<Link key={k} to={`/catalog?q=${encodeURIComponent(k)}`} className="rounded-full bg-surface-2 px-3 py-1 text-xs text-muted hover:text-ink">
|
||||
#{k}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{can('MODERATOR') && (
|
||||
<Suspense fallback={null}>
|
||||
<BookStats bookId={book.id} />
|
||||
</Suspense>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{related.length > 0 && (
|
||||
<section className="mt-16">
|
||||
<h2 className="mb-5 text-xl font-bold tracking-tight">Похожие издания</h2>
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-8 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6">
|
||||
{related.map((b) => <BookCard key={b.id} book={b} />)}
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{editing && (
|
||||
<Suspense fallback={null}>
|
||||
<BookForm book={book} onClose={() => setEditing(false)} onSaved={() => { setEditing(false); reload(); }} />
|
||||
</Suspense>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
import { useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import clsx from 'clsx';
|
||||
import {
|
||||
ArrowRight, BadgeCheck, BookMarked, BookOpen, Clock, Download, Eye, FileCheck2, GraduationCap, Heart, Hourglass, ListChecks,
|
||||
PenLine, Pencil, Plus, Presentation, Search, Sparkles, UsersRound,
|
||||
} from 'lucide-react';
|
||||
import { api, useApi } from '../lib/api';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { BOOK_TYPES, KIND_LABELS, SUBMISSION_STATUS, fmtDate, fmtDay, fmtNum, greeting, plural } from '../lib/format';
|
||||
import BookCover from '../components/BookCover';
|
||||
import { BookGrid } from '../components/BookCard';
|
||||
import { ListCard, ListFormModal, Progress } from '../components/Lists';
|
||||
import { Avatar, Badge, Button, Empty, ErrorBox, Modal, PageLoader, useToast } from '../components/ui';
|
||||
|
||||
export default function Cabinet() {
|
||||
const { data, error, loading, reload } = useApi('/cabinet');
|
||||
if (loading && !data) return <PageLoader />;
|
||||
if (error) return <div className="mx-auto max-w-3xl p-6"><ErrorBox error={error} onRetry={reload} /></div>;
|
||||
return data.kind === 'TEACHER' ? <TeacherCabinet data={data} reload={reload} /> : <StudentCabinet data={data} reload={reload} />;
|
||||
}
|
||||
|
||||
/* ---------- Общие блоки ---------- */
|
||||
|
||||
function Section({ title, icon: Icon, action, children, className }) {
|
||||
return (
|
||||
<section className={clsx('mt-10', className)}>
|
||||
<div className="mb-4 flex flex-wrap items-center justify-between gap-2">
|
||||
<h2 className="flex items-center gap-2.5 text-xl font-bold tracking-tight">
|
||||
{Icon && <Icon className="size-5 text-subtle" />}
|
||||
{title}
|
||||
</h2>
|
||||
{action}
|
||||
</div>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const MoreLink = ({ to, children = 'Все' }) => (
|
||||
<Link to={to} className="flex items-center gap-1 text-sm font-medium text-brand-600 transition-all hover:gap-2 dark:text-brand-300">
|
||||
{children} <ArrowRight className="size-4" />
|
||||
</Link>
|
||||
);
|
||||
|
||||
function Stat({ icon: Icon, label, value, to }) {
|
||||
const body = (
|
||||
<>
|
||||
<div className="flex items-center gap-1.5 text-xs text-white/70"><Icon className="size-4" />{label}</div>
|
||||
<div className="mt-1 text-2xl font-bold tnum">{fmtNum(value)}</div>
|
||||
</>
|
||||
);
|
||||
return to ? (
|
||||
<Link to={to} className="rounded-2xl bg-white/10 p-4 ring-1 ring-white/15 backdrop-blur transition hover:bg-white/15">{body}</Link>
|
||||
) : (
|
||||
<div className="rounded-2xl bg-white/10 p-4 ring-1 ring-white/15 backdrop-blur">{body}</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Активность за 30 дней — простые столбики, подробности во всплывающей подсказке */
|
||||
function ActivityBars({ data }) {
|
||||
const max = Math.max(1, ...data.map((d) => d.count));
|
||||
const total = data.reduce((s, d) => s + d.count, 0);
|
||||
const days = data.filter((d) => d.count).length;
|
||||
return (
|
||||
<div className="card p-5">
|
||||
<div className="flex items-baseline justify-between">
|
||||
<div className="text-sm font-semibold">Ваша активность за 30 дней</div>
|
||||
<div className="text-xs text-muted tnum">{fmtNum(total)} действий · {days} {plural(days, 'день', 'дня', 'дней')}</div>
|
||||
</div>
|
||||
<div className="mt-4 flex h-16 items-end gap-[2px]">
|
||||
{data.map((d) => (
|
||||
<div key={d.day} className="group relative flex h-full flex-1 items-end" title={`${fmtDay(d.day)}: ${d.count}`}>
|
||||
<div
|
||||
className={clsx('w-full rounded-t-[3px] transition', d.count ? 'bg-[var(--series-1)] group-hover:opacity-80' : 'bg-surface-2')}
|
||||
style={{ height: d.count ? `${Math.max(8, (d.count / max) * 100)}%` : '4px' }}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-1.5 flex justify-between text-[10px] text-subtle">
|
||||
<span>{fmtDay(data[0].day)}</span>
|
||||
<span>сегодня</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RecentBooks({ items }) {
|
||||
if (!items.length) return null;
|
||||
return (
|
||||
<Section title="Продолжить чтение" icon={Clock} action={<MoreLink to="/history">История</MoreLink>}>
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{items.map((b) => (
|
||||
<Link key={b.id} to={`/books/${b.id}`} className="card group flex items-center gap-3 p-3 transition hover:border-brand-300 hover:shadow-md">
|
||||
<BookCover book={b} size="sm" className="w-12 shrink-0" />
|
||||
<div className="min-w-0">
|
||||
<div className="line-clamp-2 text-sm font-semibold group-hover:text-brand-600 dark:group-hover:text-brand-300">{b.title}</div>
|
||||
<div className="truncate text-xs text-muted">{b.authors}</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
function PublicationsSummary({ pubs, teacher }) {
|
||||
const total = Object.values(pubs).reduce((a, b) => a + b, 0);
|
||||
return (
|
||||
<div className="card flex flex-wrap items-center gap-4 p-5">
|
||||
<div className={clsx('flex size-11 items-center justify-center rounded-xl', teacher ? 'bg-violet-100 text-violet-700 dark:bg-violet-500/15 dark:text-violet-300' : 'bg-emerald-100 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300')}>
|
||||
<PenLine className="size-5" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="font-semibold">{teacher ? 'Учебные материалы и публикации' : 'Мои публикации'}</div>
|
||||
<div className="mt-1 flex flex-wrap gap-1.5">
|
||||
{total ? (
|
||||
Object.entries(SUBMISSION_STATUS).map(([k, s]) => pubs[k] ? <Badge key={k} color={s.color}>{s.label}: {pubs[k]}</Badge> : null)
|
||||
) : (
|
||||
<span className="text-sm text-muted">{teacher ? 'Методички, конспекты лекций, статьи' : 'Статьи, тезисы, курсовые и ВКР'} — после проверки появятся в каталоге</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
{total > 0 && <Link to="/publications"><Button variant="secondary" size="sm">Открыть</Button></Link>}
|
||||
<Link to="/publications/new"><Button size="sm" icon={Plus}>Опубликовать</Button></Link>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProfileModal({ open, user, onClose, onSaved }) {
|
||||
const toast = useToast();
|
||||
const { setUser } = useAuth();
|
||||
const [form, setForm] = useState({ studyGroup: user.studyGroup || '', course: user.course || '' });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const save = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const d = await api('/cabinet/profile', { method: 'PATCH', body: form });
|
||||
setUser(d.user);
|
||||
toast('Профиль сохранён');
|
||||
onSaved();
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
onClose={onClose}
|
||||
title="Учебная группа"
|
||||
size="sm"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onClose}>Отмена</Button>
|
||||
<Button loading={busy} onClick={save}>Сохранить</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-muted">По группе подбираются списки литературы от ваших преподавателей и популярное у однокурсников.</p>
|
||||
<div className="grid grid-cols-[1fr_100px] gap-3">
|
||||
<div>
|
||||
<label className="label">Группа</label>
|
||||
<input className="input uppercase" autoFocus value={form.studyGroup} onChange={(e) => setForm({ ...form, studyGroup: e.target.value })} placeholder="ИС-24-01" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Курс</label>
|
||||
<select className="input" value={form.course} onChange={(e) => setForm({ ...form, course: e.target.value })}>
|
||||
<option value="">—</option>
|
||||
{[1, 2, 3, 4, 5, 6].map((c) => <option key={c} value={c}>{c}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- Кабинет студента ---------- */
|
||||
|
||||
function StudentCabinet({ data, reload }) {
|
||||
const { user } = data;
|
||||
const [editing, setEditing] = useState(false);
|
||||
const c = data.counts;
|
||||
const firstName = user.displayName.split(' ')[1] || user.displayName.split(' ')[0];
|
||||
const staff = data.kind === 'STAFF';
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-7xl px-4 py-8 sm:px-6">
|
||||
{/* Шапка */}
|
||||
<div className="hero-gradient relative overflow-hidden rounded-3xl p-6 text-white sm:p-8">
|
||||
<div className="grid-pattern absolute inset-0" />
|
||||
<div className="relative flex flex-wrap items-center gap-5">
|
||||
<Avatar name={user.displayName} size={72} className="ring-4 ring-white/20" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm text-white/70">{greeting()}, {firstName}</div>
|
||||
<h1 className="mt-0.5 text-2xl font-bold tracking-tight sm:text-3xl">{staff ? 'Кабинет читателя' : 'Кабинет студента'}</h1>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2 text-sm text-white/80">
|
||||
<span className="inline-flex items-center gap-1.5 rounded-full bg-white/15 px-2.5 py-0.5 text-xs font-medium ring-1 ring-white/20">
|
||||
<GraduationCap className="size-3.5" /> {KIND_LABELS[data.kind]}
|
||||
</span>
|
||||
{user.studyGroup ? (
|
||||
<button onClick={() => setEditing(true)} className="inline-flex items-center gap-1 rounded-full bg-white/15 px-2.5 py-0.5 text-xs font-medium ring-1 ring-white/20 hover:bg-white/25">
|
||||
Группа {user.studyGroup}{user.course ? ` · ${user.course} курс` : ''} <Pencil className="size-3" />
|
||||
</button>
|
||||
) : (
|
||||
!staff && (
|
||||
<button onClick={() => setEditing(true)} className="inline-flex items-center gap-1 rounded-full bg-amber-400 px-2.5 py-0.5 text-xs font-semibold text-amber-950 hover:bg-amber-300">
|
||||
<Plus className="size-3" /> Укажите группу
|
||||
</button>
|
||||
)
|
||||
)}
|
||||
{user.department && <span className="truncate">{user.department}</span>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative mt-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||
<Stat icon={BookOpen} label="Открыто онлайн" value={c.READ || 0} to="/history" />
|
||||
<Stat icon={Download} label="Скачано" value={c.DOWNLOAD || 0} to="/history" />
|
||||
<Stat icon={Heart} label="В избранном" value={c.favorites} to="/favorites" />
|
||||
<Stat icon={PenLine} label="Опубликовано работ" value={data.publications.PUBLISHED || 0} to="/publications" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{user.teacherPending && (
|
||||
<div className="mt-4 flex items-start gap-3 rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-200">
|
||||
<Hourglass className="mt-0.5 size-5 shrink-0" />
|
||||
<div>
|
||||
<b>Статус преподавателя ожидает подтверждения.</b> Active Directory не подтвердил, что вы преподаватель. Администратор библиотеки проверит заявку,
|
||||
после этого откроется кабинет преподавателя: списки литературы и руководство работами.
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Литература по дисциплинам */}
|
||||
{!staff && (
|
||||
<Section title="Литература по моим дисциплинам" icon={ListChecks} action={<MoreLink to="/lists">Все списки</MoreLink>}>
|
||||
{!user.studyGroup ? (
|
||||
<div className="card">
|
||||
<Empty
|
||||
icon={UsersRound}
|
||||
title="Укажите свою учебную группу"
|
||||
text="Тогда здесь появятся списки литературы, которые преподаватели составили для вашей группы."
|
||||
action={<Button icon={Plus} onClick={() => setEditing(true)}>Указать группу</Button>}
|
||||
/>
|
||||
</div>
|
||||
) : !data.lists.length ? (
|
||||
<div className="card">
|
||||
<Empty
|
||||
icon={ListChecks}
|
||||
title={`Для группы ${user.studyGroup} списков пока нет`}
|
||||
text="Преподаватели ещё не добавили списки литературы. Посмотрите общие списки или найдите книги в каталоге."
|
||||
action={<Link to="/lists"><Button variant="secondary" icon={Search}>Все списки литературы</Button></Link>}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{data.lists.map((l) => (
|
||||
<ListCard key={l.id} list={l}>
|
||||
<Progress value={l.done} max={l.total} label="Открыто изданий" color={l.done === l.total && l.total ? 'bg-emerald-500' : 'bg-brand-500'} />
|
||||
</ListCard>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
)}
|
||||
|
||||
<div className="mt-10 grid gap-4 lg:grid-cols-2">
|
||||
<ActivityBars data={data.activity} />
|
||||
<PublicationsSummary pubs={data.publications} />
|
||||
</div>
|
||||
|
||||
<RecentBooks items={data.recent} />
|
||||
|
||||
{data.peers?.items.length > 0 && (
|
||||
<Section title={`Популярно: ${data.peers.by}`} icon={Sparkles}>
|
||||
<BookGrid books={data.peers.items} />
|
||||
</Section>
|
||||
)}
|
||||
|
||||
<ProfileModal open={editing} user={user} onClose={() => setEditing(false)} onSaved={() => { setEditing(false); reload(); }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------- Кабинет преподавателя ---------- */
|
||||
|
||||
function TeacherCabinet({ data, reload }) {
|
||||
const { user, lists, supervised, materials } = data;
|
||||
const toast = useToast();
|
||||
const nav = useNavigate();
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [busy, setBusy] = useState(null);
|
||||
const firstName = user.displayName.split(' ')[1] || user.displayName.split(' ')[0];
|
||||
const students = lists.reduce((s, l) => s + l.students, 0);
|
||||
const reached = lists.reduce((s, l) => s + l.reached, 0);
|
||||
const supTotal = Object.values(supervised.counts).reduce((a, b) => a + b, 0);
|
||||
|
||||
const endorse = async (b) => {
|
||||
setBusy(b.id);
|
||||
try {
|
||||
await api(`/cabinet/supervised/${b.id}/endorse`, { method: 'POST', body: { endorse: true } });
|
||||
toast('Работа подтверждена — библиотекарь увидит отметку руководителя');
|
||||
reload();
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-7xl px-4 py-8 sm:px-6">
|
||||
{/* Шапка */}
|
||||
<div className="relative overflow-hidden rounded-3xl bg-gradient-to-br from-violet-700 via-indigo-700 to-slate-900 p-6 text-white sm:p-8">
|
||||
<div className="grid-pattern absolute inset-0" />
|
||||
<div className="relative flex flex-wrap items-center gap-5">
|
||||
<Avatar name={user.displayName} size={72} className="ring-4 ring-white/20" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="text-sm text-white/70">{greeting()}, {firstName}</div>
|
||||
<h1 className="mt-0.5 text-2xl font-bold tracking-tight sm:text-3xl">Кабинет преподавателя</h1>
|
||||
<div className="mt-2 flex flex-wrap items-center gap-2 text-sm text-white/80">
|
||||
<span className="inline-flex items-center gap-1.5 rounded-full bg-white/15 px-2.5 py-0.5 text-xs font-medium ring-1 ring-white/20">
|
||||
<Presentation className="size-3.5" /> {user.title || 'Преподаватель'}
|
||||
</span>
|
||||
{user.department && <span className="truncate">{user.department}</span>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button className="!bg-white !text-violet-700 hover:!bg-violet-50" icon={Plus} onClick={() => setCreating(true)}>Список литературы</Button>
|
||||
<Link to="/publications/new"><Button variant="secondary" className="!border-white/30 !bg-white/10 !text-white hover:!bg-white/20" icon={PenLine}>Материал</Button></Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative mt-6 grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||
<Stat icon={ListChecks} label="Списков литературы" value={lists.length} />
|
||||
<Stat icon={UsersRound} label="Студентов открыли (30 дн.)" value={reached} />
|
||||
<Stat icon={GraduationCap} label="Работ под руководством" value={supTotal} />
|
||||
<Stat icon={Download} label="Скачиваний моих материалов" value={materials.downloads} to="/publications" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Списки литературы */}
|
||||
<Section
|
||||
title="Мои списки литературы"
|
||||
icon={ListChecks}
|
||||
action={lists.length > 0 && <Button size="sm" variant="secondary" icon={Plus} onClick={() => setCreating(true)}>Новый список</Button>}
|
||||
>
|
||||
{!lists.length ? (
|
||||
<div className="card">
|
||||
<Empty
|
||||
icon={BookMarked}
|
||||
title="Составьте первый список литературы"
|
||||
text="Укажите дисциплину и группы — студенты увидят список в своём кабинете, а вы — сколько из них открыли материалы."
|
||||
action={<Button icon={Plus} onClick={() => setCreating(true)} className="!bg-violet-600 hover:!bg-violet-700">Создать список</Button>}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
{students > 0 && (
|
||||
<p className="-mt-2 mb-4 text-sm text-muted">
|
||||
Охват за 30 дней: <b className="text-ink tnum">{reached}</b> из <span className="tnum">{students}</span> студентов ваших групп открывали или скачивали книги из списков.
|
||||
</p>
|
||||
)}
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{lists.map((l) => (
|
||||
<ListCard key={l.id} list={l} showOwner={false}>
|
||||
{l.groups.length ? (
|
||||
<Progress value={l.reached} max={l.students} label="Студентов открыли за 30 дней" color="bg-violet-500" />
|
||||
) : (
|
||||
<div className="text-xs text-subtle">Группы не указаны — список виден всем{!l.isPublic && ' (скрыт)'}</div>
|
||||
)}
|
||||
</ListCard>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</Section>
|
||||
|
||||
{/* Научное руководство */}
|
||||
<Section
|
||||
title="Работы под моим руководством"
|
||||
icon={GraduationCap}
|
||||
action={supTotal > 0 && <MoreLink to="/cabinet/supervised">Все работы</MoreLink>}
|
||||
>
|
||||
{supervised.awaiting > 0 && (
|
||||
<div className="mb-4 flex items-center gap-3 rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900 dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-200">
|
||||
<FileCheck2 className="size-5 shrink-0" />
|
||||
<span><b className="tnum">{supervised.awaiting}</b> {plural(supervised.awaiting, 'работа ждёт', 'работы ждут', 'работ ждут')} вашего подтверждения. Отметка руководителя ускоряет проверку в библиотеке.</span>
|
||||
</div>
|
||||
)}
|
||||
{!supervised.recent.length ? (
|
||||
<div className="card p-6 text-sm text-muted">
|
||||
Когда студент выберет вас научным руководителем при публикации работы, она появится здесь — вы сможете её просмотреть и подтвердить.
|
||||
</div>
|
||||
) : (
|
||||
<SupervisedList items={supervised.recent} busy={busy} onEndorse={endorse} />
|
||||
)}
|
||||
</Section>
|
||||
|
||||
<div className="mt-10 grid gap-4 lg:grid-cols-2">
|
||||
<ActivityBars data={data.activity} />
|
||||
<PublicationsSummary pubs={data.publications} teacher />
|
||||
</div>
|
||||
|
||||
{materials.top.length > 0 && (
|
||||
<Section title="Мои материалы в библиотеке" icon={BookOpen} action={<MoreLink to="/publications">Все</MoreLink>}>
|
||||
<div className="card divide-y divide-line">
|
||||
{materials.top.map((b) => (
|
||||
<Link key={b.id} to={`/books/${b.id}`} className="flex items-center gap-4 p-4 transition hover:bg-surface-2/60">
|
||||
<BookCover book={b} size="sm" className="w-10 shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate font-medium">{b.title}</div>
|
||||
<div className="text-xs text-muted">{BOOK_TYPES[b.type] || b.type} · {b.year}</div>
|
||||
</div>
|
||||
<div className="flex gap-4 text-sm text-muted tnum">
|
||||
<span className="flex items-center gap-1" title="Просмотры"><Eye className="size-4" />{fmtNum(b.viewCount)}</span>
|
||||
<span className="flex items-center gap-1 font-semibold text-ink" title="Скачивания"><Download className="size-4 text-subtle" />{fmtNum(b.downloadCount)}</span>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
<RecentBooks items={data.recent} />
|
||||
|
||||
<ListFormModal open={creating} onClose={() => setCreating(false)} onSaved={(l) => nav(`/lists/${l.id}`)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SupervisedList({ items, busy, onEndorse }) {
|
||||
return (
|
||||
<div className="card divide-y divide-line">
|
||||
{items.map((b) => {
|
||||
const st = SUBMISSION_STATUS[b.status];
|
||||
return (
|
||||
<div key={b.id} className="flex flex-wrap items-center gap-4 p-4">
|
||||
<BookCover book={b} size="sm" className="w-10 shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge color={st.color}>{st.label}</Badge>
|
||||
<Badge>{BOOK_TYPES[b.type] || b.type}</Badge>
|
||||
{b.endorsedAt && <Badge color="violet"><BadgeCheck className="size-3" />Подтверждено вами</Badge>}
|
||||
</div>
|
||||
<Link to={`/books/${b.id}`} className="mt-1 line-clamp-1 block font-medium hover:text-violet-700 dark:hover:text-violet-300">{b.title}</Link>
|
||||
<div className="truncate text-xs text-muted">
|
||||
{b.createdBy?.displayName}{b.createdBy?.studyGroup ? ` · ${b.createdBy.studyGroup}` : ''} · отправлено {fmtDate(b.submittedAt)}
|
||||
</div>
|
||||
</div>
|
||||
{b.status === 'PENDING' && !b.endorsedAt && (
|
||||
<Button size="sm" icon={BadgeCheck} loading={busy === b.id} onClick={() => onEndorse(b)} className="!bg-violet-600 hover:!bg-violet-700">
|
||||
Подтвердить
|
||||
</Button>
|
||||
)}
|
||||
{b.status === 'PUBLISHED' && (
|
||||
<div className="flex gap-3 text-xs text-muted tnum">
|
||||
<span className="flex items-center gap-1"><Eye className="size-3.5" />{fmtNum(b.viewCount)}</span>
|
||||
<span className="flex items-center gap-1"><Download className="size-3.5" />{fmtNum(b.downloadCount)}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import clsx from 'clsx';
|
||||
import { LayoutGrid, List, Search, SearchX, SlidersHorizontal, X } from 'lucide-react';
|
||||
import { qs, useApi } from '../lib/api';
|
||||
import { BOOK_TYPES, LANGUAGES, fmtNum, plural } from '../lib/format';
|
||||
import BookCard, { BookRow } from '../components/BookCard';
|
||||
import { Button, Empty, ErrorBox, Modal, Pagination, Segmented, Skeleton } from '../components/ui';
|
||||
|
||||
const SORTS = [
|
||||
['new', 'Сначала новые'],
|
||||
['popular', 'Популярные'],
|
||||
['views', 'Просматриваемые'],
|
||||
['title', 'По названию'],
|
||||
['year', 'По году издания'],
|
||||
];
|
||||
|
||||
export default function Catalog() {
|
||||
const [sp, setSp] = useSearchParams();
|
||||
const get = (k) => sp.get(k) || '';
|
||||
const [q, setQ] = useState(get('q'));
|
||||
const [view, setView] = useState(() => {
|
||||
try {
|
||||
return localStorage.getItem('elib-view') || 'grid';
|
||||
} catch {
|
||||
return 'grid';
|
||||
}
|
||||
});
|
||||
const [filtersOpen, setFiltersOpen] = useState(false);
|
||||
useEffect(() => {
|
||||
setQ(get('q'));
|
||||
}, [sp.get('q')]); // eslint-disable-line
|
||||
|
||||
const params = {
|
||||
q: get('q'),
|
||||
category: get('category'),
|
||||
type: get('type'),
|
||||
language: get('language'),
|
||||
source: get('source'),
|
||||
yearFrom: get('yearFrom'),
|
||||
yearTo: get('yearTo'),
|
||||
sort: get('sort') || 'new',
|
||||
page: get('page') || 1,
|
||||
limit: 24,
|
||||
log: sp.get('q') ? 1 : '',
|
||||
};
|
||||
const books = useApi('/books' + qs(params));
|
||||
const cats = useApi('/categories');
|
||||
const facets = useApi('/books/facets');
|
||||
|
||||
const update = (patch) => {
|
||||
const next = new URLSearchParams(sp);
|
||||
for (const [k, v] of Object.entries(patch)) v ? next.set(k, v) : next.delete(k);
|
||||
if (!('page' in patch)) next.delete('page');
|
||||
setSp(next);
|
||||
};
|
||||
|
||||
const setViewSaved = (v) => {
|
||||
setView(v);
|
||||
try {
|
||||
localStorage.setItem('elib-view', v);
|
||||
} catch {}
|
||||
};
|
||||
|
||||
const activeCat = cats.data?.items.find((c) => String(c.id) === get('category'));
|
||||
const chips = [
|
||||
get('q') && { k: 'q', label: `«${get('q')}»` },
|
||||
activeCat && { k: 'category', label: activeCat.name },
|
||||
get('source') && { k: 'source', label: get('source') === 'USER' ? 'Студенческие работы' : 'Фонд библиотеки' },
|
||||
get('type') && { k: 'type', label: BOOK_TYPES[get('type')] || get('type') },
|
||||
get('language') && { k: 'language', label: LANGUAGES[get('language')] || get('language') },
|
||||
(get('yearFrom') || get('yearTo')) && { k: ['yearFrom', 'yearTo'], label: `${get('yearFrom') || '…'} – ${get('yearTo') || '…'} гг.` },
|
||||
].filter(Boolean);
|
||||
|
||||
const filters = (
|
||||
<div className="space-y-7">
|
||||
<div>
|
||||
<div className="mb-2 text-xs font-semibold tracking-wider text-subtle uppercase">Источник</div>
|
||||
<div className="space-y-0.5">
|
||||
<FilterItem active={!get('source')} onClick={() => update({ source: '' })} label="Все материалы" />
|
||||
<FilterItem active={get('source') === 'LIBRARY'} onClick={() => update({ source: 'LIBRARY' })} label="Фонд библиотеки" />
|
||||
<FilterItem active={get('source') === 'USER'} onClick={() => update({ source: 'USER' })} label="Студенческие работы" color="#10b981" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-2 text-xs font-semibold tracking-wider text-subtle uppercase">Раздел</div>
|
||||
<div className="space-y-0.5">
|
||||
<FilterItem active={!get('category')} onClick={() => update({ category: '' })} label="Все разделы" />
|
||||
{cats.data?.items.map((c) => (
|
||||
<FilterItem key={c.id} active={get('category') === String(c.id)} onClick={() => update({ category: c.id })} label={c.name} count={c.bookCount} color={c.color} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-2 text-xs font-semibold tracking-wider text-subtle uppercase">Тип издания</div>
|
||||
<select className="input" value={get('type')} onChange={(e) => update({ type: e.target.value })}>
|
||||
<option value="">Любой</option>
|
||||
{facets.data?.types.map((t) => (
|
||||
<option key={t.value} value={t.value}>
|
||||
{BOOK_TYPES[t.value] || t.value} ({t.count})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-2 text-xs font-semibold tracking-wider text-subtle uppercase">Язык</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{facets.data?.languages.map((l) => (
|
||||
<button
|
||||
key={l.value}
|
||||
onClick={() => update({ language: get('language') === l.value ? '' : l.value })}
|
||||
className={clsx(
|
||||
'rounded-full border px-3 py-1 text-xs font-medium transition',
|
||||
get('language') === l.value ? 'border-brand-500 bg-brand-50 text-brand-700 dark:bg-brand-500/15 dark:text-brand-300' : 'border-line text-muted hover:text-ink'
|
||||
)}
|
||||
>
|
||||
{LANGUAGES[l.value] || l.value} <span className="opacity-60">{l.count}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-2 text-xs font-semibold tracking-wider text-subtle uppercase">Год издания</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<input className="input" type="number" placeholder={facets.data?.minYear || 'с'} defaultValue={get('yearFrom')} onBlur={(e) => update({ yearFrom: e.target.value })} />
|
||||
<span className="text-subtle">—</span>
|
||||
<input className="input" type="number" placeholder={facets.data?.maxYear || 'по'} defaultValue={get('yearTo')} onBlur={(e) => update({ yearTo: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-7xl px-4 py-8 sm:px-6">
|
||||
<div className="mb-6">
|
||||
<h1 className="text-3xl font-bold tracking-tight">{activeCat?.name || (get('source') === 'USER' ? 'Студенческие работы' : 'Каталог')}</h1>
|
||||
{activeCat?.description && <p className="mt-1 text-muted">{activeCat.description}</p>}
|
||||
</div>
|
||||
|
||||
<div className="flex gap-8">
|
||||
<aside className="hidden w-60 shrink-0 lg:block">
|
||||
<div className="sticky top-24">{filters}</div>
|
||||
</aside>
|
||||
|
||||
<div className="min-w-0 flex-1">
|
||||
<form
|
||||
className="flex gap-2"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
update({ q: q.trim() });
|
||||
}}
|
||||
>
|
||||
<div className="relative flex-1">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-3.5 size-5 -translate-y-1/2 text-subtle" />
|
||||
<input className="input h-12 pl-11 text-base" placeholder="Поиск по названию, автору, ISBN…" value={q} onChange={(e) => setQ(e.target.value)} />
|
||||
</div>
|
||||
<Button size="lg" type="submit">
|
||||
Найти
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="mt-4 flex flex-wrap items-center gap-3">
|
||||
<Button variant="secondary" size="sm" icon={SlidersHorizontal} className="lg:hidden" onClick={() => setFiltersOpen(true)}>
|
||||
Фильтры
|
||||
</Button>
|
||||
<div className="text-sm text-muted tnum">
|
||||
{books.data && (
|
||||
<>
|
||||
Найдено <b className="text-ink">{fmtNum(books.data.total)}</b> {plural(books.data.total, 'издание', 'издания', 'изданий')}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<select className="input h-9 w-auto" value={params.sort} onChange={(e) => update({ sort: e.target.value })}>
|
||||
{SORTS.map(([v, l]) => (
|
||||
<option key={v} value={v}>
|
||||
{l}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<Segmented
|
||||
value={view}
|
||||
onChange={setViewSaved}
|
||||
options={[
|
||||
{ value: 'grid', icon: LayoutGrid, title: 'Плитка' },
|
||||
{ value: 'list', icon: List, title: 'Список' },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{chips.length > 0 && (
|
||||
<div className="mt-4 flex flex-wrap gap-2">
|
||||
{chips.map((c) => (
|
||||
<button
|
||||
key={c.label}
|
||||
onClick={() => update(Object.fromEntries([c.k].flat().map((k) => [k, ''])))}
|
||||
className="inline-flex items-center gap-1.5 rounded-full bg-brand-50 py-1 pr-2 pl-3 text-xs font-medium text-brand-700 hover:bg-brand-100 dark:bg-brand-500/15 dark:text-brand-300"
|
||||
>
|
||||
{c.label} <X className="size-3.5" />
|
||||
</button>
|
||||
))}
|
||||
<button onClick={() => setSp({})} className="px-2 text-xs font-medium text-muted hover:text-ink">
|
||||
Сбросить всё
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-6">
|
||||
{books.error && <ErrorBox error={books.error} onRetry={books.reload} />}
|
||||
{books.loading && !books.data && (
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5">
|
||||
{Array.from({ length: 10 }).map((_, i) => (
|
||||
<Skeleton key={i} className="aspect-[2/3]" />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{books.data &&
|
||||
(books.data.items.length === 0 ? (
|
||||
<Empty icon={SearchX} title="Ничего не найдено" text="Попробуйте изменить запрос или сбросить фильтры. Если нужной книги нет — сообщите в библиотеку." />
|
||||
) : (
|
||||
<div className={clsx('transition-opacity', books.loading && 'opacity-50')}>
|
||||
{view === 'grid' ? (
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-8 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5">
|
||||
{books.data.items.map((b) => (
|
||||
<BookCard key={b.id} book={b} />
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-3">
|
||||
{books.data.items.map((b) => (
|
||||
<BookRow key={b.id} book={b} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-10">
|
||||
<Pagination
|
||||
page={Number(params.page)}
|
||||
pages={books.data?.pages}
|
||||
onChange={(p) => {
|
||||
update({ page: p });
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Modal open={filtersOpen} onClose={() => setFiltersOpen(false)} title="Фильтры" footer={<Button onClick={() => setFiltersOpen(false)}>Показать</Button>}>
|
||||
{filters}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FilterItem({ active, onClick, label, count, color }) {
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className={clsx(
|
||||
'flex w-full items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left text-sm transition',
|
||||
active ? 'bg-brand-50 font-medium text-brand-700 dark:bg-brand-500/15 dark:text-brand-300' : 'text-muted hover:bg-surface-2 hover:text-ink'
|
||||
)}
|
||||
>
|
||||
{color && <span className="size-2 shrink-0 rounded-full" style={{ background: color }} />}
|
||||
<span className="flex-1 truncate">{label}</span>
|
||||
{count != null && <span className="text-xs text-subtle tnum">{count}</span>}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import clsx from 'clsx';
|
||||
import { Check, Eye, EyeOff, KeyRound, LogOut, ShieldCheck } from 'lucide-react';
|
||||
import { api } from '../lib/api';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { Button, ThemeToggle, useToast } from '../components/ui';
|
||||
import { OrgBrand } from './OrgScreens';
|
||||
|
||||
const RULES = [
|
||||
[(p) => p.length >= 8, 'Не короче 8 символов'],
|
||||
[(p) => /[a-zа-яё]/i.test(p) && /\d/.test(p), 'Буквы и цифры'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Смена пароля.
|
||||
* forced — после входа с паролем, который выдала система (импорт / сброс администратором):
|
||||
* пока пароль не сменён, остальная библиотека недоступна (это проверяет и сервер).
|
||||
*/
|
||||
export default function ChangePassword({ forced }) {
|
||||
const { user, setUser, logout } = useAuth();
|
||||
const nav = useNavigate();
|
||||
const toast = useToast();
|
||||
const [f, setF] = useState({ current: '', next: '', repeat: '' });
|
||||
const [show, setShow] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const ldap = user.source !== 'LOCAL';
|
||||
|
||||
const submit = async (e) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
if (f.next !== f.repeat) return setError('Пароли не совпадают');
|
||||
setBusy(true);
|
||||
try {
|
||||
const d = await api('/auth/change-password', { method: 'POST', body: { currentPassword: f.current, newPassword: f.next } });
|
||||
setUser((u) => ({ ...u, ...d.user }));
|
||||
toast('Пароль изменён');
|
||||
nav(forced ? '/cabinet' : '/', { replace: true });
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const type = show ? 'text' : 'password';
|
||||
const form = ldap ? (
|
||||
<div className="rounded-2xl bg-surface-2 p-5 text-sm text-muted">
|
||||
Вы входите через учётную запись домена (Active Directory). Пароль меняется в домене — например, на компьютере университета: Ctrl+Alt+Del → «Изменить пароль».
|
||||
</div>
|
||||
) : (
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
<div>
|
||||
<label className="label" htmlFor="cur">{forced ? 'Временный пароль (из листа)' : 'Текущий пароль'}</label>
|
||||
<input id="cur" className="input h-11" type={type} autoComplete="current-password" autoFocus value={f.current} onChange={(e) => setF({ ...f, current: e.target.value })} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label flex items-center justify-between" htmlFor="new">
|
||||
<span>Новый пароль</span>
|
||||
<button type="button" className="flex items-center gap-1 text-xs text-muted hover:text-ink" onClick={() => setShow((v) => !v)}>
|
||||
{show ? <EyeOff className="size-3.5" /> : <Eye className="size-3.5" />} {show ? 'Скрыть' : 'Показать'}
|
||||
</button>
|
||||
</label>
|
||||
<input id="new" className="input h-11" type={type} autoComplete="new-password" value={f.next} onChange={(e) => setF({ ...f, next: e.target.value })} />
|
||||
<div className="mt-2 flex flex-wrap gap-3">
|
||||
{RULES.map(([test, label]) => (
|
||||
<span key={label} className={clsx('flex items-center gap-1 text-xs', test(f.next) ? 'text-emerald-600 dark:text-emerald-400' : 'text-subtle')}>
|
||||
<Check className="size-3.5" /> {label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label" htmlFor="rep">Повторите новый пароль</label>
|
||||
<input id="rep" className="input h-11" type={type} autoComplete="new-password" value={f.repeat} onChange={(e) => setF({ ...f, repeat: e.target.value })} />
|
||||
</div>
|
||||
{error && <div className="rounded-xl bg-rose-50 p-3 text-sm text-rose-700 dark:bg-rose-500/10 dark:text-rose-300">{error}</div>}
|
||||
<Button type="submit" size="lg" className="w-full" icon={KeyRound} loading={busy} disabled={!f.current || !f.next || !f.repeat}>
|
||||
Сохранить пароль
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
|
||||
if (!forced)
|
||||
return (
|
||||
<div className="mx-auto max-w-md px-4 py-10 sm:px-6">
|
||||
<h1 className="text-2xl font-bold tracking-tight">Смена пароля</h1>
|
||||
<p className="mt-1 mb-6 text-sm text-muted">После смены пароля другие открытые сеансы (на других устройствах) завершатся.</p>
|
||||
<div className="card p-6">{form}</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="relative flex min-h-screen items-center justify-center p-6">
|
||||
<ThemeToggle className="absolute top-5 right-5" />
|
||||
<div className="w-full max-w-sm animate-slide-up">
|
||||
<OrgBrand className="mb-8" />
|
||||
<div className="mb-6 flex items-start gap-3 rounded-2xl bg-brand-50 p-4 text-sm text-brand-900 dark:bg-brand-500/10 dark:text-brand-100">
|
||||
<ShieldCheck className="mt-0.5 size-5 shrink-0" />
|
||||
<div>
|
||||
<b>Здравствуйте, {user.displayName.split(' ').slice(1, 2).join('') || user.displayName}!</b> Вы вошли с паролем, который выдала библиотека.
|
||||
Придумайте свой — его будете знать только вы.
|
||||
</div>
|
||||
</div>
|
||||
{form}
|
||||
<button onClick={logout} className="mx-auto mt-6 flex items-center gap-1.5 text-sm text-muted hover:text-ink">
|
||||
<LogOut className="size-4" /> Выйти
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { useState } from 'react';
|
||||
import { Link, useNavigate } from 'react-router-dom';
|
||||
import { ArrowRight, BookOpen, Flame, Search, Sparkles, Clock, GraduationCap, PenLine } from 'lucide-react';
|
||||
import { useApi } from '../lib/api';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { CATEGORY_ICONS, fmtNum, greeting, plural } from '../lib/format';
|
||||
import { BookGrid } from '../components/BookCard';
|
||||
import BookCover from '../components/BookCover';
|
||||
import { Skeleton } from '../components/ui';
|
||||
|
||||
function Section({ title, icon: Icon, to, children }) {
|
||||
return (
|
||||
<section className="mt-14">
|
||||
<div className="mb-5 flex items-center justify-between">
|
||||
<h2 className="flex items-center gap-2.5 text-xl font-bold tracking-tight">
|
||||
{Icon && <Icon className="size-5 text-brand-500" />}
|
||||
{title}
|
||||
</h2>
|
||||
{to && (
|
||||
<Link to={to} className="flex items-center gap-1 text-sm font-medium text-brand-600 hover:gap-2 dark:text-brand-300 transition-all">
|
||||
Смотреть все <ArrowRight className="size-4" />
|
||||
</Link>
|
||||
)}
|
||||
</div>
|
||||
{children}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
const GridSkeleton = () => (
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Skeleton key={i} className="aspect-[2/3]" />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
|
||||
export default function Home() {
|
||||
const { user } = useAuth();
|
||||
const nav = useNavigate();
|
||||
const [q, setQ] = useState('');
|
||||
const cats = useApi('/categories');
|
||||
const popular = useApi('/books?sort=popular&limit=6');
|
||||
const fresh = useApi('/books?sort=new&limit=12');
|
||||
const history = useApi('/me/history');
|
||||
const student = useApi('/books?source=USER&sort=new&limit=6');
|
||||
|
||||
const totalBooks = cats.data?.items.reduce((s, c) => s + c.bookCount, 0) ?? 0;
|
||||
const recent = history.data?.items.slice(0, 4) || [];
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Hero */}
|
||||
<div className="hero-gradient relative overflow-hidden">
|
||||
<div className="grid-pattern absolute inset-0" />
|
||||
<div className="relative mx-auto max-w-7xl px-4 py-14 sm:px-6 sm:py-20">
|
||||
<div className="max-w-2xl">
|
||||
<div className="mb-3 inline-flex items-center gap-2 rounded-full bg-white/10 px-3 py-1 text-xs font-medium text-white/90 ring-1 ring-white/20 backdrop-blur">
|
||||
<Sparkles className="size-3.5" /> {greeting()}, {user.displayName.split(' ')[1] || user.displayName.split(' ')[0]}
|
||||
</div>
|
||||
<h1 className="text-3xl font-bold tracking-tight text-white sm:text-5xl [text-wrap:balance]">Что будем читать сегодня?</h1>
|
||||
<p className="mt-3 text-base text-white/75 sm:text-lg">
|
||||
{fmtNum(totalBooks)} {plural(totalBooks, 'издание', 'издания', 'изданий')} в {cats.data?.items.length ?? '…'} разделах — учебники, пособия, монографии
|
||||
</p>
|
||||
</div>
|
||||
<form
|
||||
className="mt-8 flex max-w-2xl gap-2 rounded-2xl bg-white/95 p-2 shadow-2xl shadow-brand-950/30 dark:bg-surface"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
nav(`/catalog?q=${encodeURIComponent(q.trim())}`);
|
||||
}}
|
||||
>
|
||||
<div className="relative flex-1">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-3 size-5 -translate-y-1/2 text-slate-400" />
|
||||
<input
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
placeholder="Название, автор, ISBN, ключевые слова…"
|
||||
className="h-12 w-full rounded-xl bg-transparent pl-11 text-base text-slate-900 outline-none placeholder:text-slate-400 dark:text-ink"
|
||||
/>
|
||||
</div>
|
||||
<button className="h-12 rounded-xl bg-brand-600 px-6 font-medium text-white transition hover:bg-brand-700">Найти</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mx-auto max-w-7xl px-4 sm:px-6">
|
||||
{recent.length > 0 && (
|
||||
<Section title="Продолжить чтение" icon={Clock} to="/history">
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{recent.map((b) => (
|
||||
<Link key={b.id} to={`/books/${b.id}`} className="card group flex items-center gap-3 p-3 transition hover:border-brand-300 hover:shadow-md">
|
||||
<BookCover book={b} size="sm" className="w-12 shrink-0" />
|
||||
<div className="min-w-0">
|
||||
<div className="line-clamp-2 text-sm font-semibold group-hover:text-brand-600 dark:group-hover:text-brand-300">{b.title}</div>
|
||||
<div className="truncate text-xs text-muted">{b.authors}</div>
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</Section>
|
||||
)}
|
||||
|
||||
<Section title="Разделы" icon={BookOpen}>
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
|
||||
{cats.loading && Array.from({ length: 10 }).map((_, i) => <Skeleton key={i} className="h-24" />)}
|
||||
{cats.data?.items.map((c) => {
|
||||
const Icon = CATEGORY_ICONS[c.icon] || BookOpen;
|
||||
return (
|
||||
<Link
|
||||
key={c.id}
|
||||
to={`/catalog?category=${c.id}`}
|
||||
className="card group relative overflow-hidden p-4 transition hover:-translate-y-0.5 hover:shadow-lg"
|
||||
>
|
||||
<div className="absolute -top-6 -right-6 size-20 rounded-full opacity-10 transition group-hover:scale-125" style={{ background: c.color }} />
|
||||
<div className="mb-3 flex size-10 items-center justify-center rounded-xl text-white shadow-sm" style={{ background: c.color }}>
|
||||
<Icon className="size-5" />
|
||||
</div>
|
||||
<div className="line-clamp-1 text-sm font-semibold">{c.name}</div>
|
||||
<div className="text-xs text-muted tnum">
|
||||
{c.bookCount} {plural(c.bookCount, 'издание', 'издания', 'изданий')}
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Популярное" icon={Flame} to="/catalog?sort=popular">
|
||||
{popular.loading ? <GridSkeleton /> : <BookGrid books={popular.data?.items || []} />}
|
||||
</Section>
|
||||
|
||||
<Section title="Студенческие работы" icon={GraduationCap} to="/catalog?source=USER">
|
||||
<Link
|
||||
to="/publications/new"
|
||||
className="group mb-6 flex flex-wrap items-center gap-4 rounded-2xl bg-gradient-to-r from-emerald-600 to-teal-600 p-5 text-white shadow-lg shadow-emerald-600/20 transition hover:shadow-xl"
|
||||
>
|
||||
<div className="flex size-12 items-center justify-center rounded-xl bg-white/20"><PenLine className="size-6" /></div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="font-semibold">Опубликуйте свою статью или научную работу</div>
|
||||
<div className="text-sm text-white/80">Статьи, тезисы, курсовые и ВКР появятся в каталоге после проверки библиотекарем</div>
|
||||
</div>
|
||||
<span className="flex items-center gap-1 rounded-xl bg-white px-4 py-2 text-sm font-medium text-emerald-700 transition group-hover:gap-2">
|
||||
Опубликовать <ArrowRight className="size-4" />
|
||||
</span>
|
||||
</Link>
|
||||
{student.data?.items.length > 0 && <BookGrid books={student.data.items} />}
|
||||
</Section>
|
||||
|
||||
<Section title="Новые поступления" icon={Sparkles} to="/catalog?sort=new">
|
||||
{fresh.loading ? <GridSkeleton /> : <BookGrid books={fresh.data?.items || []} />}
|
||||
</Section>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
import { useState } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router-dom';
|
||||
import clsx from 'clsx';
|
||||
import {
|
||||
ArrowLeft, BookOpen, CheckCircle2, Circle, Download, Lock, MessageSquare, Pencil, Plus, Search, Trash2, UploadCloud, UsersRound, X,
|
||||
} from 'lucide-react';
|
||||
import { api, qs, useApi } from '../lib/api';
|
||||
import { BOOK_TYPES, READABLE, fmtDate, fmtNum, plural } from '../lib/format';
|
||||
import BookCover from '../components/BookCover';
|
||||
import { ListFormModal, Progress } from '../components/Lists';
|
||||
import { Avatar, Badge, Button, ErrorBox, Modal, PageLoader, Spinner, useToast } from '../components/ui';
|
||||
|
||||
export default function ListDetails() {
|
||||
const { id } = useParams();
|
||||
const nav = useNavigate();
|
||||
const toast = useToast();
|
||||
const { data, error, loading, reload, setData } = useApi(`/lists/${id}`, [id]);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [adding, setAdding] = useState(false);
|
||||
|
||||
if (loading && !data) return <PageLoader />;
|
||||
if (error) return <div className="mx-auto max-w-3xl p-6"><ErrorBox error={error} onRetry={reload} /></div>;
|
||||
const { list, items, editable, reach } = data;
|
||||
const required = items.filter((i) => i.required);
|
||||
const extra = items.filter((i) => !i.required);
|
||||
const done = items.filter((i) => i.opened).length;
|
||||
|
||||
const patchItem = async (it, body) => {
|
||||
try {
|
||||
await api(`/lists/${list.id}/items/${it.book.id}`, { method: 'PATCH', body });
|
||||
setData((d) => ({ ...d, items: d.items.map((x) => (x.id === it.id ? { ...x, ...body } : x)) }));
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
}
|
||||
};
|
||||
const removeItem = async (it) => {
|
||||
try {
|
||||
await api(`/lists/${list.id}/items/${it.book.id}`, { method: 'DELETE' });
|
||||
setData((d) => ({ ...d, items: d.items.filter((x) => x.id !== it.id) }));
|
||||
toast('Издание убрано из списка');
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
}
|
||||
};
|
||||
const del = async () => {
|
||||
await api(`/lists/${list.id}`, { method: 'DELETE' });
|
||||
toast('Список удалён');
|
||||
nav('/lists');
|
||||
};
|
||||
|
||||
const Group = ({ title, rows }) =>
|
||||
rows.length > 0 && (
|
||||
<section className="mt-8">
|
||||
<h2 className="mb-3 flex items-center gap-2 text-lg font-semibold">
|
||||
{title} <span className="text-sm font-normal text-muted tnum">{rows.length}</span>
|
||||
</h2>
|
||||
<div className="space-y-3">
|
||||
{rows.map((it, i) => (
|
||||
<Item key={it.id} it={it} n={i + 1} editable={editable} reach={reach} onPatch={patchItem} onRemove={removeItem} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-5xl px-4 py-8 sm:px-6">
|
||||
<Link to="/lists" className="mb-4 inline-flex items-center gap-1.5 text-sm text-muted hover:text-ink">
|
||||
<ArrowLeft className="size-4" /> Списки литературы
|
||||
</Link>
|
||||
|
||||
<div className="card overflow-hidden">
|
||||
<div className="h-1.5 bg-gradient-to-r from-violet-600 via-indigo-500 to-sky-500" />
|
||||
<div className="p-6">
|
||||
<div className="flex flex-wrap items-start gap-4">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
{list.groups.map((g) => <Badge key={g} color="violet"><UsersRound className="size-3" />{g}</Badge>)}
|
||||
{list.semester && <Badge>{list.semester}</Badge>}
|
||||
{!list.isPublic && <Badge color="amber"><Lock className="size-3" />Только для групп</Badge>}
|
||||
</div>
|
||||
<h1 className="mt-2 text-2xl font-bold tracking-tight sm:text-3xl [text-wrap:balance]">{list.title}</h1>
|
||||
<div className="mt-3 flex items-center gap-2.5">
|
||||
<Avatar name={list.owner.displayName} size={32} />
|
||||
<div className="text-sm leading-tight">
|
||||
<div className="font-medium">{list.owner.displayName}</div>
|
||||
<div className="text-xs text-muted">{[list.owner.title, list.owner.department].filter(Boolean).join(' · ')}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{editable && (
|
||||
<div className="flex gap-2">
|
||||
<Button variant="secondary" size="sm" icon={Pencil} onClick={() => setEditing(true)}>Изменить</Button>
|
||||
<Button variant="ghost" size="sm" icon={Trash2} onClick={() => setDeleting(true)} className="hover:!text-rose-600">Удалить</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{list.description && <p className="mt-4 whitespace-pre-line text-muted">{list.description}</p>}
|
||||
|
||||
<div className="mt-5 grid gap-4 border-t border-line pt-5 sm:grid-cols-2">
|
||||
{editable && reach ? (
|
||||
<Progress value={reach.reached} max={reach.students} label="Студентов групп открыли хотя бы одно издание" color="bg-violet-500" />
|
||||
) : !editable && items.length > 0 ? (
|
||||
<Progress value={done} max={items.length} label="Вы открыли изданий" color={done === items.length ? 'bg-emerald-500' : 'bg-brand-500'} />
|
||||
) : (
|
||||
<div />
|
||||
)}
|
||||
<div className="flex items-end justify-end gap-2 text-xs text-subtle">
|
||||
{items.length} {plural(items.length, 'издание', 'издания', 'изданий')} · обновлён {fmtDate(list.updatedAt)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{editable && (
|
||||
<div className="mt-6 flex flex-wrap gap-2">
|
||||
<Button className="!bg-violet-600 hover:!bg-violet-700" icon={Plus} onClick={() => setAdding(true)}>Добавить из каталога</Button>
|
||||
<Link to={`/publications/new?list=${list.id}`}><Button variant="secondary" icon={UploadCloud}>Загрузить свою книгу</Button></Link>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!items.length && (
|
||||
<div className="card mt-6 p-8 text-center text-sm text-muted">
|
||||
{editable ? 'Список пуст. Добавьте издания из каталога — здесь или кнопкой «В список литературы» в карточке книги.' : 'Преподаватель ещё не добавил издания в этот список.'}
|
||||
</div>
|
||||
)}
|
||||
<Group title="Основная литература" rows={required} />
|
||||
<Group title="Дополнительная литература" rows={extra} />
|
||||
|
||||
<ListFormModal open={editing} list={list} onClose={() => setEditing(false)} onSaved={() => { setEditing(false); reload(); }} />
|
||||
<AddBooksModal open={adding} list={list} have={new Set(items.map((i) => i.book.id))} onClose={() => { setAdding(false); reload(); }} />
|
||||
<Modal
|
||||
open={deleting}
|
||||
onClose={() => setDeleting(false)}
|
||||
title="Удалить список?"
|
||||
size="sm"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setDeleting(false)}>Отмена</Button>
|
||||
<Button variant="danger" onClick={del}>Удалить</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<p className="text-sm text-muted">Список «<b className="text-ink">{list.title}</b>» пропадёт у студентов. Сами издания останутся в каталоге.</p>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Item({ it, n, editable, reach, onPatch, onRemove }) {
|
||||
const b = it.book;
|
||||
const [noteEdit, setNoteEdit] = useState(false);
|
||||
const [note, setNote] = useState(it.note || '');
|
||||
const readers = reach?.perBook?.[b.id] || 0;
|
||||
return (
|
||||
<div className={clsx('card flex gap-4 p-4', !b.isPublished && 'opacity-60')}>
|
||||
<div className="hidden w-6 shrink-0 pt-1 text-right text-sm font-semibold text-subtle tnum sm:block">{n}.</div>
|
||||
<Link to={`/books/${b.id}`} className="shrink-0"><BookCover book={b} size="sm" className="w-14 sm:w-16" /></Link>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge>{BOOK_TYPES[b.type] || b.type}</Badge>
|
||||
{!editable && (it.opened ? (
|
||||
<span className="flex items-center gap-1 text-xs font-medium text-emerald-600 dark:text-emerald-400"><CheckCircle2 className="size-3.5" />Открыто</span>
|
||||
) : (
|
||||
<span className="flex items-center gap-1 text-xs text-subtle"><Circle className="size-3.5" />Ещё не открыто</span>
|
||||
))}
|
||||
{!b.isPublished && (
|
||||
b.status === 'PENDING' ? <Badge color="amber">На проверке — студенты пока не видят</Badge>
|
||||
: b.status === 'DRAFT' ? <Badge>Черновик — студенты не видят</Badge>
|
||||
: b.status === 'REJECTED' ? <Badge color="red">Отклонено — см. «Публикации»</Badge>
|
||||
: <Badge color="amber">Снято с публикации</Badge>
|
||||
)}
|
||||
</div>
|
||||
<Link to={`/books/${b.id}`} className="mt-1 line-clamp-2 block font-semibold hover:text-brand-600 dark:hover:text-brand-300">{b.title}</Link>
|
||||
<div className="truncate text-sm text-muted">{b.authors}{b.year ? ` · ${b.year}` : ''}</div>
|
||||
|
||||
{noteEdit ? (
|
||||
<form
|
||||
className="mt-2 flex gap-2"
|
||||
onSubmit={(e) => { e.preventDefault(); onPatch(it, { note: note.trim() || null }); setNoteEdit(false); }}
|
||||
>
|
||||
<input className="input h-9" autoFocus value={note} onChange={(e) => setNote(e.target.value)} placeholder="Например: главы 1–4, стр. 10–85" />
|
||||
<Button size="sm" type="submit">OK</Button>
|
||||
</form>
|
||||
) : it.note ? (
|
||||
<div className="mt-2 flex items-start gap-1.5 rounded-lg bg-violet-50 px-2.5 py-1.5 text-sm text-violet-900 dark:bg-violet-500/10 dark:text-violet-200">
|
||||
<MessageSquare className="mt-0.5 size-3.5 shrink-0" /> {it.note}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||
{b.hasFile && READABLE.includes(b.fileExt) && (
|
||||
<Link to={`/read/${b.id}`} target="_blank" rel="noopener"><Button size="sm" variant="secondary" icon={BookOpen}>Читать</Button></Link>
|
||||
)}
|
||||
{b.hasFile && <a href={`/api/books/${b.id}/download`}><Button size="sm" variant="ghost" icon={Download}>Скачать</Button></a>}
|
||||
{editable && (
|
||||
<>
|
||||
<select className="input h-8 w-auto text-xs" value={it.required ? '1' : '0'} onChange={(e) => onPatch(it, { required: e.target.value === '1' })}>
|
||||
<option value="1">Основная</option>
|
||||
<option value="0">Дополнительная</option>
|
||||
</select>
|
||||
<Button size="sm" variant="ghost" icon={MessageSquare} onClick={() => setNoteEdit((v) => !v)}>{it.note ? 'Комментарий' : 'Добавить комментарий'}</Button>
|
||||
<Button size="sm" variant="ghost" icon={X} onClick={() => onRemove(it)} className="hover:!text-rose-600">Убрать</Button>
|
||||
{reach && (
|
||||
<span className="ml-auto text-xs text-muted tnum" title="Студентов из групп списка, открывших или скачавших издание">
|
||||
<UsersRound className="mr-1 inline size-3.5" />{readers} из {reach.students}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AddBooksModal({ open, list, have, onClose }) {
|
||||
const toast = useToast();
|
||||
const [q, setQ] = useState('');
|
||||
const [search, setSearch] = useState('');
|
||||
const [added, setAdded] = useState(new Set());
|
||||
const [busy, setBusy] = useState(null);
|
||||
const { data, loading } = useApi(open && search ? '/books' + qs({ q: search, limit: 10 }) : null, [open, search]);
|
||||
|
||||
const add = async (b, required) => {
|
||||
setBusy(b.id);
|
||||
try {
|
||||
await api(`/lists/${list.id}/items`, { method: 'POST', body: { bookId: b.id, required } });
|
||||
setAdded((s) => new Set(s).add(b.id));
|
||||
toast(`«${b.title}» добавлено`);
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal open={open} onClose={onClose} title={`Добавить в «${list.title}»`} size="lg" footer={<Button onClick={onClose}>Готово</Button>}>
|
||||
<form className="relative" onSubmit={(e) => { e.preventDefault(); setSearch(q.trim()); }}>
|
||||
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-subtle" />
|
||||
<input className="input pl-9" autoFocus placeholder="Название, автор, ISBN… (Enter)" value={q} onChange={(e) => setQ(e.target.value)} />
|
||||
</form>
|
||||
<div className="mt-4 min-h-40">
|
||||
{!search && <p className="py-10 text-center text-sm text-muted">Найдите издания в каталоге библиотеки</p>}
|
||||
{loading && <div className="flex justify-center py-10"><Spinner /></div>}
|
||||
{data && !data.items.length && (
|
||||
<div className="py-10 text-center text-sm text-muted">
|
||||
Ничего не найдено.{' '}
|
||||
<Link to={`/publications/new?list=${list.id}`} className="font-medium text-violet-600 hover:underline dark:text-violet-300">Загрузите свою книгу</Link>
|
||||
</div>
|
||||
)}
|
||||
<div className="divide-y divide-line">
|
||||
{data?.items.map((b) => {
|
||||
const inList = have.has(b.id) || added.has(b.id);
|
||||
return (
|
||||
<div key={b.id} className="flex items-center gap-3 py-2.5">
|
||||
<BookCover book={b} size="sm" className="w-9 shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-medium">{b.title}</div>
|
||||
<div className="truncate text-xs text-muted">{b.authors}{b.year ? ` · ${b.year}` : ''} · {fmtNum(b.downloadCount)} скач.</div>
|
||||
</div>
|
||||
{inList ? (
|
||||
<span className="flex items-center gap-1 text-xs font-medium text-emerald-600 dark:text-emerald-400"><CheckCircle2 className="size-4" />В списке</span>
|
||||
) : (
|
||||
<div className="flex gap-1">
|
||||
<Button size="sm" loading={busy === b.id} onClick={() => add(b, true)}>Основная</Button>
|
||||
<Button size="sm" variant="secondary" disabled={busy === b.id} onClick={() => add(b, false)}>Доп.</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
import { useState } from 'react';
|
||||
import { Navigate, useLocation, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import clsx from 'clsx';
|
||||
import {
|
||||
AlertCircle, BarChart3, BookOpen, Clock, Download, GraduationCap, KeyRound, ListChecks, Lock, PenLine, Presentation, ShieldCheck, User, UsersRound,
|
||||
} from 'lucide-react';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { KIND_LABELS } from '../lib/format';
|
||||
import { Button, ThemeToggle, useToast } from '../components/ui';
|
||||
import { OrgBrand, OrgMismatch } from './OrgScreens';
|
||||
|
||||
const TABS = {
|
||||
STUDENT: {
|
||||
label: 'Студент',
|
||||
icon: GraduationCap,
|
||||
title: 'Кабинет студента',
|
||||
heading: 'Вся литература по вашим дисциплинам — в одном месте',
|
||||
text: 'Списки литературы от преподавателей вашей группы, чтение онлайн и скачивание учебников, публикация статей и курсовых.',
|
||||
features: [
|
||||
[ListChecks, 'Литература группы'],
|
||||
[BookOpen, 'Чтение онлайн'],
|
||||
[PenLine, 'Публикация работ'],
|
||||
],
|
||||
placeholder: 'например, s.karimov',
|
||||
gradient: 'hero-gradient',
|
||||
},
|
||||
TEACHER: {
|
||||
label: 'Преподаватель',
|
||||
icon: Presentation,
|
||||
title: 'Кабинет преподавателя',
|
||||
heading: 'Списки литературы, руководство работами и статистика',
|
||||
text: 'Составляйте списки литературы для групп, следите, сколько студентов открыли материалы, подтверждайте работы своих студентов и публикуйте методички.',
|
||||
features: [
|
||||
[UsersRound, 'Списки для групп'],
|
||||
[BarChart3, 'Охват студентов'],
|
||||
[Download, 'Учебные материалы'],
|
||||
],
|
||||
placeholder: 'например, m.orlova',
|
||||
gradient: 'bg-gradient-to-br from-violet-700 via-indigo-700 to-slate-900',
|
||||
},
|
||||
};
|
||||
|
||||
const readTab = () => {
|
||||
try {
|
||||
return localStorage.getItem('elib:login-tab') === 'TEACHER' ? 'TEACHER' : 'STUDENT';
|
||||
} catch {
|
||||
return 'STUDENT';
|
||||
}
|
||||
};
|
||||
|
||||
export default function Login() {
|
||||
const { user, login, cfg, org, mismatch } = useAuth();
|
||||
const nav = useNavigate();
|
||||
const loc = useLocation();
|
||||
const toast = useToast();
|
||||
const [sp] = useSearchParams();
|
||||
const [tab, setTabState] = useState(() => (sp.get('as') === 'teacher' ? 'TEACHER' : sp.get('as') === 'student' ? 'STUDENT' : readTab()));
|
||||
const [form, setForm] = useState({ username: '', password: '' });
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const t = TABS[tab];
|
||||
|
||||
if (user && mismatch) return <OrgMismatch />;
|
||||
if (user) return <Navigate to={loc.state?.from || '/cabinet'} replace />;
|
||||
const suspended = org.status === 'SUSPENDED';
|
||||
|
||||
const setTab = (v) => {
|
||||
setTabState(v);
|
||||
setError('');
|
||||
try {
|
||||
localStorage.setItem('elib:login-tab', v);
|
||||
} catch {}
|
||||
};
|
||||
|
||||
const submit = async (e) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const u = await login(form.username, form.password, tab);
|
||||
if (tab === 'TEACHER' && u.kind !== 'TEACHER') {
|
||||
toast(u.teacherPending ? 'Статус преподавателя ожидает подтверждения администратором. Пока открыт кабинет читателя.' : `Вы вошли как ${KIND_LABELS[u.kind].toLowerCase()}`);
|
||||
} else if (tab === 'STUDENT' && u.kind === 'TEACHER') {
|
||||
toast('Вы вошли как преподаватель');
|
||||
}
|
||||
nav(loc.state?.from || '/cabinet', { replace: true });
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="grid min-h-screen lg:grid-cols-[1.1fr_1fr]">
|
||||
{/* Левая часть — бренд, меняется вместе с вкладкой */}
|
||||
<div className={clsx('relative hidden overflow-hidden transition-colors duration-500 lg:flex lg:flex-col lg:justify-between lg:p-12', t.gradient)}>
|
||||
<div className="grid-pattern absolute inset-0" />
|
||||
<OrgBrand light className="relative max-w-md" />
|
||||
<div className="relative max-w-lg" key={tab}>
|
||||
<div className="mb-4 inline-flex animate-fade-in items-center gap-2 rounded-full bg-white/15 px-3 py-1 text-xs font-medium text-white ring-1 ring-white/25">
|
||||
<t.icon className="size-3.5" /> {t.title}
|
||||
</div>
|
||||
<h1 className="animate-slide-up text-4xl leading-tight font-bold tracking-tight text-white xl:text-5xl [text-wrap:balance]">{t.heading}</h1>
|
||||
<p className="mt-4 animate-fade-in text-lg text-white/75">{t.text}</p>
|
||||
<div className="mt-10 grid grid-cols-3 gap-4">
|
||||
{t.features.map(([Icon, label]) => (
|
||||
<div key={label} className="animate-fade-in rounded-2xl bg-white/10 p-4 text-white ring-1 ring-white/15 backdrop-blur">
|
||||
<Icon className="mb-3 size-6 text-white/90" />
|
||||
<div className="text-sm font-medium">{label}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative text-xs text-white/50">© {new Date().getFullYear()} {org.name} · на платформе E-Library</div>
|
||||
</div>
|
||||
|
||||
{/* Правая часть — форма */}
|
||||
<div className="relative flex items-center justify-center p-6 sm:p-12">
|
||||
<ThemeToggle className="absolute top-5 right-5" />
|
||||
<div className="w-full max-w-sm animate-slide-up">
|
||||
<OrgBrand className="mb-8 lg:hidden" />
|
||||
|
||||
{org.status === 'PENDING' && (
|
||||
<div className="mb-6 flex items-start gap-2.5 rounded-xl bg-amber-50 p-3 text-sm text-amber-800 dark:bg-amber-500/10 dark:text-amber-200">
|
||||
<Clock className="mt-0.5 size-4 shrink-0" />
|
||||
<span>Библиотека проходит проверку и скоро откроется. Сейчас может войти только администратор организации, чтобы её настроить.</span>
|
||||
</div>
|
||||
)}
|
||||
{suspended && (
|
||||
<div className="mb-6 flex items-start gap-2.5 rounded-xl bg-rose-50 p-3 text-sm text-rose-700 dark:bg-rose-500/10 dark:text-rose-300">
|
||||
<AlertCircle className="mt-0.5 size-4 shrink-0" />
|
||||
<span>Доступ к библиотеке временно приостановлен. Обратитесь к администратору вашей организации.</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Переключатель: студент / преподаватель */}
|
||||
<div role="tablist" aria-label="Тип входа" className="mb-8 grid grid-cols-2 gap-1 rounded-2xl border border-line bg-surface-2 p-1">
|
||||
{Object.entries(TABS).map(([k, v]) => (
|
||||
<button
|
||||
key={k}
|
||||
role="tab"
|
||||
type="button"
|
||||
aria-selected={tab === k}
|
||||
onClick={() => setTab(k)}
|
||||
className={clsx(
|
||||
'flex h-11 items-center justify-center gap-2 rounded-xl text-sm font-medium transition',
|
||||
tab === k
|
||||
? clsx('bg-surface shadow-sm', k === 'TEACHER' ? 'text-violet-700 dark:text-violet-300' : 'text-brand-700 dark:text-brand-300')
|
||||
: 'text-muted hover:text-ink'
|
||||
)}
|
||||
>
|
||||
<v.icon className="size-4" /> {v.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<h2 className="text-2xl font-bold tracking-tight">{tab === 'TEACHER' ? 'Вход для преподавателей' : 'Вход для студентов'}</h2>
|
||||
<p className="mt-1.5 text-sm text-muted">
|
||||
{cfg.ldapEnabled ? 'Логин и пароль от учётной записи университета — как для входа в компьютер.' : 'Логин и пароль, которые выдала библиотека.'}
|
||||
</p>
|
||||
|
||||
<form onSubmit={submit} className="mt-8 space-y-4">
|
||||
<div>
|
||||
<label className="label" htmlFor="username">Логин</label>
|
||||
<div className="relative">
|
||||
<User className="pointer-events-none absolute top-1/2 left-3.5 size-4 -translate-y-1/2 text-subtle" />
|
||||
<input
|
||||
id="username"
|
||||
className="input h-12 pl-10"
|
||||
placeholder={cfg.ldapEnabled ? t.placeholder : 'например, ivanov.ab'}
|
||||
autoComplete="username"
|
||||
autoFocus
|
||||
value={form.username}
|
||||
onChange={(e) => setForm({ ...form, username: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label" htmlFor="password">Пароль</label>
|
||||
<div className="relative">
|
||||
<Lock className="pointer-events-none absolute top-1/2 left-3.5 size-4 -translate-y-1/2 text-subtle" />
|
||||
<input
|
||||
id="password"
|
||||
type="password"
|
||||
className="input h-12 pl-10"
|
||||
placeholder="••••••••"
|
||||
autoComplete="current-password"
|
||||
value={form.password}
|
||||
onChange={(e) => setForm({ ...form, password: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{error && (
|
||||
<div className="flex animate-fade-in items-start gap-2 rounded-xl bg-rose-50 p-3 text-sm text-rose-700 dark:bg-rose-500/10 dark:text-rose-300">
|
||||
<AlertCircle className="mt-0.5 size-4 shrink-0" /> {error}
|
||||
</div>
|
||||
)}
|
||||
<Button type="submit" size="lg" disabled={suspended} className={clsx('w-full', tab === 'TEACHER' && '!bg-violet-600 hover:!bg-violet-700')} loading={loading}>
|
||||
Войти в кабинет
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<div className="mt-8 space-y-2">
|
||||
{cfg.ldapEnabled ? (
|
||||
<div className="flex items-center gap-3 rounded-xl border border-line bg-surface-2 p-3 text-xs text-muted">
|
||||
<ShieldCheck className="size-5 shrink-0 text-emerald-500" />
|
||||
Пароль проверяет контроллер домена Active Directory, библиотека его не хранит.
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-3 rounded-xl border border-line bg-surface-2 p-3 text-xs text-muted">
|
||||
<KeyRound className="size-5 shrink-0 text-brand-500" />
|
||||
При первом входе система попросит придумать свой пароль. Забыли пароль — администратор библиотеки выдаст новый.
|
||||
</div>
|
||||
)}
|
||||
<p className="px-1 text-xs text-subtle">
|
||||
{tab === 'TEACHER'
|
||||
? cfg.ldapEnabled
|
||||
? 'Статус преподавателя определяется по группам AD. Если он не определился, администратор библиотеки подтвердит его вручную.'
|
||||
: 'Статус преподавателя задаёт администратор библиотеки.'
|
||||
: 'Сотрудники библиотеки и администрации входят через любую вкладку.'}
|
||||
</p>
|
||||
<a href="/" className="block px-1 pt-2 text-xs text-subtle hover:text-ink">Не ваша организация? Найти свою библиотеку →</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { BookMarked, BookOpen, Download, History as HistoryIcon } from 'lucide-react';
|
||||
import { useApi } from '../lib/api';
|
||||
import { timeAgo } from '../lib/format';
|
||||
import { BookGrid, BookRow } from '../components/BookCard';
|
||||
import { Badge, Button, Empty, ErrorBox, PageLoader } from '../components/ui';
|
||||
|
||||
function Shell({ title, subtitle, children }) {
|
||||
return (
|
||||
<div className="mx-auto max-w-7xl px-4 py-8 sm:px-6">
|
||||
<h1 className="text-3xl font-bold tracking-tight">{title}</h1>
|
||||
<p className="mt-1 mb-8 text-muted">{subtitle}</p>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const toCatalog = (
|
||||
<Link to="/catalog">
|
||||
<Button>Перейти в каталог</Button>
|
||||
</Link>
|
||||
);
|
||||
|
||||
export function Favorites() {
|
||||
const { data, error, loading, reload } = useApi('/me/favorites');
|
||||
return (
|
||||
<Shell title="Избранное" subtitle="Книги, которые вы отложили, чтобы вернуться к ним позже">
|
||||
{loading && <PageLoader />}
|
||||
{error && <ErrorBox error={error} onRetry={reload} />}
|
||||
{data && (data.items.length ? <BookGrid books={data.items} /> : <Empty icon={BookMarked} title="Пока пусто" text="Нажмите «В избранное» на странице книги, чтобы она появилась здесь." action={toCatalog} />)}
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
|
||||
export function History() {
|
||||
const { data, error, loading, reload } = useApi('/me/history');
|
||||
return (
|
||||
<Shell title="История" subtitle="Книги, которые вы недавно открывали, читали или скачивали">
|
||||
{loading && <PageLoader />}
|
||||
{error && <ErrorBox error={error} onRetry={reload} />}
|
||||
{data &&
|
||||
(data.items.length ? (
|
||||
<div className="grid gap-3 lg:grid-cols-2">
|
||||
{data.items.map((b) => (
|
||||
<BookRow
|
||||
key={b.id}
|
||||
book={b}
|
||||
extra={
|
||||
<>
|
||||
<span>{timeAgo(b.lastAt)}</span>
|
||||
{b.read && <Badge color="brand"><BookOpen className="size-3" />читали</Badge>}
|
||||
{b.downloaded && <Badge color="green"><Download className="size-3" />скачано</Badge>}
|
||||
</>
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Empty icon={HistoryIcon} title="История пуста" text="Здесь появятся книги, которые вы откроете." action={toCatalog} />
|
||||
))}
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import clsx from 'clsx';
|
||||
import { ArrowRight, Building2, LogOut, SearchX } from 'lucide-react';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { Button, ThemeToggle } from '../components/ui';
|
||||
|
||||
/** Логотип организации, если загружен; иначе — знак E-Library */
|
||||
export function OrgLogo({ org, className = 'size-10', rounded = 'rounded-xl' }) {
|
||||
if (org?.logoUrl) return <img src={org.logoUrl} alt="" className={clsx(className, rounded, 'shrink-0 bg-white object-contain p-0.5 ring-1 ring-black/5')} />;
|
||||
return <img src="/favicon.svg" alt="" className={clsx(className, 'shrink-0')} />;
|
||||
}
|
||||
|
||||
export function OrgBrand({ className, light }) {
|
||||
const { org } = useAuth();
|
||||
return (
|
||||
<div className={clsx('flex items-center gap-3', className)}>
|
||||
<OrgLogo org={org} className="size-11" />
|
||||
<div className="min-w-0">
|
||||
<div className={clsx('truncate text-lg leading-tight font-bold', light && 'text-white')}>{org?.shortName || 'E-Library'}</div>
|
||||
<div className={clsx('line-clamp-2 text-sm', light ? 'text-white/70' : 'text-muted')}>{org?.name}</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Screen({ icon: Icon, title, children }) {
|
||||
return (
|
||||
<div className="relative flex min-h-screen items-center justify-center p-6">
|
||||
<ThemeToggle className="absolute top-5 right-5" />
|
||||
<div className="w-full max-w-md animate-slide-up text-center">
|
||||
<div className="mx-auto mb-5 flex size-16 items-center justify-center rounded-2xl bg-surface-2 text-muted">
|
||||
<Icon className="size-8" />
|
||||
</div>
|
||||
<h1 className="text-2xl font-bold tracking-tight [text-wrap:balance]">{title}</h1>
|
||||
{children}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** site/<slug>, а такой библиотеки нет */
|
||||
export function OrgNotFound() {
|
||||
const { slug } = useAuth();
|
||||
return (
|
||||
<Screen icon={SearchX} title="Библиотека не найдена">
|
||||
<p className="mt-2 text-muted">
|
||||
По адресу <b className="text-ink">/{slug}</b> библиотеки нет. Проверьте адрес или найдите свою организацию на главной странице.
|
||||
</p>
|
||||
<a href="/" className="mt-6 inline-block">
|
||||
<Button icon={ArrowRight}>Найти библиотеку</Button>
|
||||
</a>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
|
||||
/** Сессия одна на сайт: вошли в одну организацию, а открыли адрес другой */
|
||||
export function OrgMismatch() {
|
||||
const { org, userOrg, user, logout } = useAuth();
|
||||
const home = user?.isPlatformAdmin ? '/platform' : userOrg ? `/${userOrg.slug}` : '/';
|
||||
return (
|
||||
<Screen icon={Building2} title={`Вы вошли в другую библиотеку`}>
|
||||
<p className="mt-2 text-muted">
|
||||
Сейчас вы вошли как <b className="text-ink">{user?.displayName}</b>
|
||||
{userOrg ? <> в библиотеку «{userOrg.shortName || userOrg.name}»</> : user?.isPlatformAdmin ? ' (владелец платформы)' : ''}. Чтобы открыть библиотеку «
|
||||
{org?.shortName || org?.name}», выйдите и войдите её учётной записью.
|
||||
</p>
|
||||
<div className="mt-6 flex flex-wrap justify-center gap-2">
|
||||
<a href={home}>
|
||||
<Button variant="secondary">Вернуться в свою</Button>
|
||||
</a>
|
||||
<Button icon={LogOut} onClick={logout}>
|
||||
Выйти и войти здесь
|
||||
</Button>
|
||||
</div>
|
||||
</Screen>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { CheckCircle2, Clock, FilePen, MessageSquareWarning, PenLine, Plus, Send, ShieldCheck, Trash2, Eye, Download } from 'lucide-react';
|
||||
import { api, useApi } from '../lib/api';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { BOOK_TYPES, SUBMISSION_STATUS, fmtDate, fmtNum } from '../lib/format';
|
||||
import BookCover from '../components/BookCover';
|
||||
import { Badge, Button, Empty, ErrorBox, Modal, PageLoader, useToast } from '../components/ui';
|
||||
|
||||
const STEPS = [
|
||||
[FilePen, 'Заполните карточку', 'Название, аннотация, научный руководитель и файл работы'],
|
||||
[Send, 'Отправьте на проверку', 'Библиотекарь проверит оформление и содержание'],
|
||||
[CheckCircle2, 'Работа опубликована', 'Её смогут найти, прочитать и скачать все пользователи'],
|
||||
];
|
||||
|
||||
export default function Publications() {
|
||||
const toast = useToast();
|
||||
const { user } = useAuth();
|
||||
const teacher = user.kind === 'TEACHER';
|
||||
const { data, error, loading, reload } = useApi('/submissions/mine');
|
||||
const [deleting, setDeleting] = useState(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const del = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api(`/submissions/${deleting.id}`, { method: 'DELETE' });
|
||||
toast('Работа удалена');
|
||||
setDeleting(null);
|
||||
reload();
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const items = data?.items || [];
|
||||
const published = items.filter((x) => x.status === 'PUBLISHED');
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-7xl px-4 py-8 sm:px-6">
|
||||
{/* Шапка */}
|
||||
<div className="relative overflow-hidden rounded-3xl bg-gradient-to-br from-emerald-600 via-teal-600 to-sky-700 p-6 text-white sm:p-10">
|
||||
<div className="grid-pattern absolute inset-0" />
|
||||
<div className="relative flex flex-wrap items-end justify-between gap-6">
|
||||
<div className="max-w-xl">
|
||||
<div className="mb-3 inline-flex items-center gap-2 rounded-full bg-white/15 px-3 py-1 text-xs font-medium ring-1 ring-white/25">
|
||||
<PenLine className="size-3.5" /> {teacher ? 'Материалы преподавателя' : 'Публикации студентов'}
|
||||
</div>
|
||||
<h1 className="text-3xl font-bold tracking-tight sm:text-4xl">{teacher ? 'Опубликуйте учебный материал' : 'Опубликуйте свою работу'}</h1>
|
||||
<p className="mt-2 text-white/80">
|
||||
{teacher
|
||||
? 'Методические указания, конспекты лекций, учебные пособия и статьи. После проверки библиотекарем материал появится в каталоге — его можно добавить в списки литературы.'
|
||||
: 'Научные статьи, тезисы конференций, курсовые и выпускные работы. После проверки библиотекарем работа появится в каталоге университета.'}
|
||||
</p>
|
||||
</div>
|
||||
<Link to="/publications/new">
|
||||
<Button size="lg" className="!bg-white !text-emerald-700 hover:!bg-emerald-50" icon={Plus}>
|
||||
{teacher ? 'Загрузить книгу' : 'Новая публикация'}
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<div className="relative mt-8 grid gap-3 sm:grid-cols-3">
|
||||
{STEPS.map(([Icon, t, d], i) => (
|
||||
<div key={t} className="flex gap-3 rounded-2xl bg-white/10 p-4 ring-1 ring-white/15 backdrop-blur">
|
||||
<div className="flex size-9 shrink-0 items-center justify-center rounded-xl bg-white/20 text-sm font-bold">{i + 1}</div>
|
||||
<div>
|
||||
<div className="flex items-center gap-1.5 text-sm font-semibold"><Icon className="size-4" />{t}</div>
|
||||
<div className="mt-0.5 text-xs text-white/75">{d}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-10 mb-4 flex items-center justify-between">
|
||||
<h2 className="text-xl font-bold tracking-tight">Мои работы</h2>
|
||||
{published.length > 0 && (
|
||||
<div className="text-sm text-muted tnum">
|
||||
Опубликовано: <b className="text-ink">{published.length}</b> · просмотров {fmtNum(published.reduce((s, b) => s + b.viewCount, 0))} · скачиваний{' '}
|
||||
{fmtNum(published.reduce((s, b) => s + b.downloadCount, 0))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{loading && !data && <PageLoader />}
|
||||
{error && <ErrorBox error={error} onRetry={reload} />}
|
||||
{data && !items.length && (
|
||||
<div className="card">
|
||||
<Empty
|
||||
icon={PenLine}
|
||||
title="У вас пока нет публикаций"
|
||||
text="Загрузите свою первую работу — это займёт пару минут."
|
||||
action={<Link to="/publications/new"><Button icon={Plus}>Новая публикация</Button></Link>}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-2">
|
||||
{items.map((b) => {
|
||||
const st = SUBMISSION_STATUS[b.status];
|
||||
const editable = b.status !== 'PUBLISHED';
|
||||
return (
|
||||
<div key={b.id} className="card flex gap-4 p-4">
|
||||
<BookCover book={b} size="sm" className="w-20 shrink-0" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge color={st.color}>
|
||||
{b.status === 'PENDING' && <Clock className="size-3" />}
|
||||
{b.status === 'PUBLISHED' && <CheckCircle2 className="size-3" />}
|
||||
{st.label}
|
||||
</Badge>
|
||||
<Badge>{BOOK_TYPES[b.type] || b.type}</Badge>
|
||||
</div>
|
||||
<Link to={`/books/${b.id}`} className="mt-1.5 line-clamp-2 block font-semibold hover:text-brand-600 dark:hover:text-brand-300">
|
||||
{b.title}
|
||||
</Link>
|
||||
<div className="truncate text-xs text-muted">
|
||||
{b.authors}
|
||||
{b.supervisor && ` · рук. ${b.supervisor}`}
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-subtle">
|
||||
{b.status === 'DRAFT' ? `Сохранено ${fmtDate(b.updatedAt)}` : `Отправлено ${fmtDate(b.submittedAt)}`}
|
||||
{b.reviewedAt && ` · проверено ${fmtDate(b.reviewedAt)}`}
|
||||
</div>
|
||||
|
||||
{b.status === 'REJECTED' && b.reviewNote && (
|
||||
<div className="mt-3 flex gap-2 rounded-xl bg-rose-50 p-3 text-sm text-rose-800 dark:bg-rose-500/10 dark:text-rose-200">
|
||||
<MessageSquareWarning className="mt-0.5 size-4 shrink-0" />
|
||||
<div>
|
||||
<div className="text-xs font-semibold">Комментарий модератора{b.reviewedBy ? ` (${b.reviewedBy.displayName})` : ''}:</div>
|
||||
{b.reviewNote}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{b.status === 'PUBLISHED' && (
|
||||
<div className="mt-2 flex gap-4 text-xs text-muted tnum">
|
||||
<span className="flex items-center gap-1"><Eye className="size-3.5" />{fmtNum(b.viewCount)}</span>
|
||||
<span className="flex items-center gap-1"><Download className="size-3.5" />{fmtNum(b.downloadCount)}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{editable && (
|
||||
<div className="mt-3 flex flex-wrap gap-2">
|
||||
<Link to={`/publications/${b.id}/edit`}>
|
||||
<Button size="sm" variant={b.status === 'REJECTED' ? 'primary' : 'secondary'} icon={PenLine}>
|
||||
{b.status === 'REJECTED' ? 'Исправить и отправить' : b.status === 'DRAFT' ? 'Продолжить' : 'Изменить'}
|
||||
</Button>
|
||||
</Link>
|
||||
<Button size="sm" variant="ghost" icon={Trash2} onClick={() => setDeleting(b)} className="hover:!text-rose-600">
|
||||
Удалить
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<div className="mt-10 flex items-start gap-3 rounded-2xl border border-line bg-surface-2 p-4 text-sm text-muted">
|
||||
<ShieldCheck className="mt-0.5 size-5 shrink-0 text-emerald-500" />
|
||||
<div>
|
||||
<b className="text-ink">Правила публикации.</b> Публикуются только собственные работы с указанием научного руководителя (если он есть).
|
||||
Работы с заимствованиями без ссылок, неправильным оформлением или посторонним содержанием возвращаются на доработку с комментарием.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
open={!!deleting}
|
||||
onClose={() => setDeleting(null)}
|
||||
title="Удалить работу?"
|
||||
size="sm"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setDeleting(null)}>Отмена</Button>
|
||||
<Button variant="danger" loading={busy} onClick={del}>Удалить</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<p className="text-sm text-muted">«<b className="text-ink">{deleting?.title}</b>» будет удалена вместе с файлом.</p>
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import { ArrowLeft, Download, Maximize2 } from 'lucide-react';
|
||||
import { useApi } from '../lib/api';
|
||||
import { Button, ErrorBox, PageLoader, ThemeToggle } from '../components/ui';
|
||||
|
||||
export default function Reader() {
|
||||
const { id } = useParams();
|
||||
const { data, error, loading } = useApi(`/books/${id}`, [id]);
|
||||
if (loading) return <PageLoader />;
|
||||
if (error) return <div className="p-6"><ErrorBox error={error} /></div>;
|
||||
const { book } = data;
|
||||
const src = `/api/books/${book.id}/read`;
|
||||
|
||||
return (
|
||||
<div className="flex h-dvh flex-col bg-bg">
|
||||
<header className="flex h-14 shrink-0 items-center gap-3 border-b border-line bg-surface px-3 sm:px-4">
|
||||
<Link to={`/books/${book.id}`} className="rounded-lg p-2 text-muted hover:bg-surface-2 hover:text-ink" title="Назад">
|
||||
<ArrowLeft className="size-5" />
|
||||
</Link>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-semibold">{book.title}</div>
|
||||
<div className="truncate text-xs text-muted">{book.authors}</div>
|
||||
</div>
|
||||
<a href={src} target="_blank" rel="noreferrer" className="hidden rounded-lg p-2 text-muted hover:bg-surface-2 hover:text-ink sm:block" title="Открыть в новой вкладке">
|
||||
<Maximize2 className="size-5" />
|
||||
</a>
|
||||
<ThemeToggle />
|
||||
<a href={`/api/books/${book.id}/download`}>
|
||||
<Button size="sm" icon={Download}>Скачать</Button>
|
||||
</a>
|
||||
</header>
|
||||
<div className="min-h-0 flex-1">
|
||||
{book.fileExt === 'mp4' ? (
|
||||
<video src={src} controls className="size-full bg-black" />
|
||||
) : book.fileExt === 'mp3' ? (
|
||||
<div className="flex size-full items-center justify-center p-6"><audio src={src} controls className="w-full max-w-xl" /></div>
|
||||
) : (
|
||||
<iframe src={src} title={book.title} className="size-full border-0 bg-white" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { useState } from 'react';
|
||||
import { Link, Navigate, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { ArrowLeft, BookMarked, GraduationCap, Plus, Search, UploadCloud } from 'lucide-react';
|
||||
import { api, qs, useApi } from '../lib/api';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { ListCard, ListFormModal } from '../components/Lists';
|
||||
import { Button, Empty, ErrorBox, PageLoader, Segmented, useToast } from '../components/ui';
|
||||
import { SupervisedList } from './Cabinet';
|
||||
|
||||
/** /lists — каталог списков литературы */
|
||||
export default function ReadingLists() {
|
||||
const { user, isTeacher } = useAuth();
|
||||
const [params] = useSearchParams();
|
||||
const [scope, setScope] = useState(['mine', 'group', 'all'].includes(params.get('scope')) ? params.get('scope') : isTeacher ? 'mine' : user.studyGroup ? 'group' : 'all');
|
||||
const [q, setQ] = useState('');
|
||||
const [search, setSearch] = useState('');
|
||||
const [creating, setCreating] = useState(false);
|
||||
const nav = useNavigate();
|
||||
const { data, error, loading, reload } = useApi('/lists' + qs({ scope, q: search }));
|
||||
|
||||
const options = [
|
||||
...(isTeacher ? [{ value: 'mine', label: 'Мои списки' }] : []),
|
||||
...(user.studyGroup ? [{ value: 'group', label: `Группа ${user.studyGroup}` }] : []),
|
||||
{ value: 'all', label: 'Все списки' },
|
||||
];
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-7xl px-4 py-8 sm:px-6">
|
||||
<div className="flex flex-wrap items-end justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Списки литературы</h1>
|
||||
<p className="mt-1 text-muted">Подборки изданий по дисциплинам от преподавателей университета</p>
|
||||
</div>
|
||||
{isTeacher && (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Link to="/publications/new"><Button variant="secondary" icon={UploadCloud}>Загрузить книгу</Button></Link>
|
||||
<Button icon={Plus} onClick={() => setCreating(true)} className="!bg-violet-600 hover:!bg-violet-700">Новый список</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-6 mb-6 flex flex-wrap items-center gap-3">
|
||||
{options.length > 1 && <Segmented value={scope} onChange={setScope} options={options} />}
|
||||
<form className="relative min-w-[220px] flex-1 sm:max-w-sm" onSubmit={(e) => { e.preventDefault(); setSearch(q.trim()); }}>
|
||||
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-subtle" />
|
||||
<input className="input pl-9" placeholder="Дисциплина, преподаватель, группа…" value={q} onChange={(e) => setQ(e.target.value)} />
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{error && <ErrorBox error={error} onRetry={reload} />}
|
||||
{loading && !data && <PageLoader />}
|
||||
{data && !data.items.length && (
|
||||
<div className="card">
|
||||
<Empty
|
||||
icon={BookMarked}
|
||||
title={search ? 'Ничего не найдено' : scope === 'mine' ? 'У вас пока нет списков' : 'Списков пока нет'}
|
||||
text={scope === 'mine' ? 'Создайте список для дисциплины и укажите группы — студенты увидят его в кабинете.' : 'Попробуйте другой запрос или посмотрите все списки.'}
|
||||
action={scope === 'mine' && <Button icon={Plus} onClick={() => setCreating(true)}>Создать список</Button>}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{data?.items.length > 0 && (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{data.items.map((l) => <ListCard key={l.id} list={l} showOwner={scope !== 'mine'} />)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ListFormModal open={creating} onClose={() => setCreating(false)} onSaved={(l) => nav(`/lists/${l.id}`)} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** /cabinet/supervised — все работы, где пользователь научный руководитель */
|
||||
export function Supervised() {
|
||||
const { isTeacher } = useAuth();
|
||||
if (!isTeacher) return <Navigate to="/cabinet" replace />;
|
||||
return <SupervisedPage />;
|
||||
}
|
||||
|
||||
function SupervisedPage() {
|
||||
const toast = useToast();
|
||||
const [status, setStatus] = useState('');
|
||||
const [busy, setBusy] = useState(null);
|
||||
const { data, error, loading, reload } = useApi('/cabinet/supervised' + qs({ status }));
|
||||
const endorse = async (b) => {
|
||||
setBusy(b.id);
|
||||
try {
|
||||
await api(`/cabinet/supervised/${b.id}/endorse`, { method: 'POST', body: { endorse: true } });
|
||||
toast('Работа подтверждена');
|
||||
reload();
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className="mx-auto max-w-5xl px-4 py-8 sm:px-6">
|
||||
<Link to="/cabinet" className="mb-4 inline-flex items-center gap-1.5 text-sm text-muted hover:text-ink">
|
||||
<ArrowLeft className="size-4" /> Кабинет
|
||||
</Link>
|
||||
<h1 className="text-3xl font-bold tracking-tight">Работы под моим руководством</h1>
|
||||
<p className="mt-1 mb-6 text-muted">Работы, в которых студенты указали вас научным руководителем</p>
|
||||
<Segmented
|
||||
className="mb-5"
|
||||
value={status}
|
||||
onChange={setStatus}
|
||||
options={[
|
||||
{ value: '', label: 'Все' },
|
||||
{ value: 'PENDING', label: 'На проверке' },
|
||||
{ value: 'PUBLISHED', label: 'Опубликованные' },
|
||||
{ value: 'REJECTED', label: 'На доработке' },
|
||||
]}
|
||||
/>
|
||||
{error && <ErrorBox error={error} onRetry={reload} />}
|
||||
{loading && !data && <PageLoader />}
|
||||
{data && !data.items.length && <div className="card"><Empty icon={GraduationCap} title="Работ нет" text="Здесь появятся работы студентов, выбравших вас руководителем." /></div>}
|
||||
{data?.items.length > 0 && <SupervisedList items={data.items} busy={busy} onEndorse={endorse} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom';
|
||||
import clsx from 'clsx';
|
||||
import { ArrowLeft, BadgeCheck, BookMarked, FileText, Info, MessageSquareWarning, Save, Send, UploadCloud, X } from 'lucide-react';
|
||||
import { qs, upload, useApi } from '../lib/api';
|
||||
import { useAuth } from '../lib/auth';
|
||||
import { BOOK_TYPES, LANGUAGES, STUDENT_TYPES, TEACHER_TYPES, fmtSize } from '../lib/format';
|
||||
import { Button, ErrorBox, PageLoader, useToast } from '../components/ui';
|
||||
|
||||
const ACCEPT = '.pdf,.doc,.docx,.odt,.rtf,.ppt,.pptx';
|
||||
const TEACHER_ACCEPT = ACCEPT + ',.epub,.djvu,.txt';
|
||||
const empty = (user) => ({
|
||||
title: '', subtitle: '', authors: user.displayName, supervisor: '', supervisorId: '', type: user.kind === 'TEACHER' ? 'methodical' : 'article', categoryId: '', language: 'ru',
|
||||
year: new Date().getFullYear(), pages: '', keywords: '', description: '', publisher: '',
|
||||
});
|
||||
|
||||
/** Научный руководитель: поиск преподавателя в системе или свободный текст */
|
||||
function SupervisorPicker({ value, id, onChange }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const term = value.trim();
|
||||
const { data } = useApi(open && !id && term.length >= 2 ? '/cabinet/teachers' + qs({ q: term }) : null, [open, id, term]);
|
||||
const items = data?.items || [];
|
||||
return (
|
||||
<div className="relative">
|
||||
<input
|
||||
className="input pr-9"
|
||||
value={value}
|
||||
onChange={(e) => { onChange({ supervisor: e.target.value, supervisorId: '' }); setOpen(true); }}
|
||||
onFocus={() => setOpen(true)}
|
||||
onBlur={() => setTimeout(() => setOpen(false), 150)}
|
||||
placeholder="Начните вводить фамилию"
|
||||
autoComplete="off"
|
||||
/>
|
||||
{id && (
|
||||
<button type="button" onClick={() => onChange({ supervisor: '', supervisorId: '' })} className="absolute top-1/2 right-2.5 -translate-y-1/2 text-subtle hover:text-ink" aria-label="Очистить">
|
||||
<X className="size-4" />
|
||||
</button>
|
||||
)}
|
||||
{open && items.length > 0 && (
|
||||
<div className="absolute inset-x-0 top-full z-20 mt-1 max-h-64 overflow-auto rounded-xl border border-line bg-surface p-1 shadow-xl">
|
||||
{items.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
type="button"
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={() => { onChange({ supervisor: t.displayName, supervisorId: t.id }); setOpen(false); }}
|
||||
className="block w-full rounded-lg px-3 py-2 text-left hover:bg-surface-2"
|
||||
>
|
||||
<div className="text-sm font-medium">{t.displayName}</div>
|
||||
<div className="truncate text-xs text-muted">{[t.title, t.department].filter(Boolean).join(' · ')}</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-1 text-xs">
|
||||
{id ? (
|
||||
<span className="flex items-center gap-1 text-violet-600 dark:text-violet-300"><BadgeCheck className="size-3.5" />Преподаватель увидит работу в своём кабинете и сможет её подтвердить</span>
|
||||
) : (
|
||||
<span className="text-subtle">Выберите из списка — руководитель сможет подтвердить работу</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function SubmitWork() {
|
||||
const { id } = useParams();
|
||||
const [params] = useSearchParams();
|
||||
const { user } = useAuth();
|
||||
const nav = useNavigate();
|
||||
const toast = useToast();
|
||||
const cats = useApi('/categories');
|
||||
const existing = useApi(id ? `/submissions/mine/${id}` : null, [id]);
|
||||
const [form, setForm] = useState(() => empty(user));
|
||||
const [file, setFile] = useState(null);
|
||||
const [agree, setAgree] = useState(false);
|
||||
const [over, setOver] = useState(false);
|
||||
const [progress, setProgress] = useState(null);
|
||||
const [error, setError] = useState('');
|
||||
const fileRef = useRef();
|
||||
const teacher = user.kind === 'TEACHER';
|
||||
// преподаватель может сразу положить книгу в свой список литературы
|
||||
const myLists = useApi(teacher && !id ? '/lists?scope=mine' : null, [teacher, id]);
|
||||
const [listId, setListId] = useState(params.get('list') || '');
|
||||
const [required, setRequired] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const it = existing.data?.item;
|
||||
if (it) setForm(Object.fromEntries(Object.keys(empty(user)).map((k) => [k, it[k] ?? ''])));
|
||||
}, [existing.data]); // eslint-disable-line
|
||||
|
||||
if (id && existing.loading) return <PageLoader />;
|
||||
if (id && existing.error) return <div className="mx-auto max-w-3xl p-6"><ErrorBox error={existing.error} /></div>;
|
||||
const item = existing.data?.item;
|
||||
|
||||
const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });
|
||||
const types = teacher ? TEACHER_TYPES : STUDENT_TYPES;
|
||||
|
||||
const submit = async (draft) => {
|
||||
setError('');
|
||||
if (!draft) {
|
||||
if (form.title.trim().length < 5) return setError('Название должно быть не короче 5 символов');
|
||||
if (!teacher && form.description.trim().length < 50) return setError('Аннотация должна быть не короче 50 символов');
|
||||
if (!file && !item?.hasFile) return setError(teacher ? 'Прикрепите файл книги' : 'Прикрепите файл работы');
|
||||
if (!agree) return setError(teacher ? 'Подтвердите право на размещение издания' : 'Подтвердите авторство и согласие на размещение');
|
||||
} else if (!file && !item?.hasFile) return setError('Чтобы сохранить черновик, прикрепите файл');
|
||||
const fd = new FormData();
|
||||
for (const [k, v] of Object.entries(form)) fd.append(k, v ?? '');
|
||||
fd.append('draft', String(draft));
|
||||
fd.append('agree', String(agree));
|
||||
if (teacher && !id && listId) {
|
||||
fd.append('listId', listId);
|
||||
fd.append('required', String(required));
|
||||
}
|
||||
if (file) fd.append('file', file);
|
||||
setProgress(0);
|
||||
try {
|
||||
const res = await upload(id ? `/submissions/${id}` : '/submissions', id ? 'PUT' : 'POST', fd, setProgress);
|
||||
if (res?.listId) {
|
||||
toast(draft ? 'Черновик сохранён и добавлен в список' : 'Книга добавлена в список и отправлена на проверку');
|
||||
nav(`/lists/${res.listId}`);
|
||||
} else {
|
||||
toast(draft ? 'Черновик сохранён' : teacher ? 'Материал отправлен на проверку' : 'Работа отправлена на модерацию');
|
||||
nav('/publications');
|
||||
}
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
} finally {
|
||||
setProgress(null);
|
||||
}
|
||||
};
|
||||
|
||||
const descLen = form.description.trim().length;
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-4xl px-4 py-8 sm:px-6">
|
||||
<Link to="/publications" className="mb-4 inline-flex items-center gap-1.5 text-sm text-muted hover:text-ink">
|
||||
<ArrowLeft className="size-4" /> Мои публикации
|
||||
</Link>
|
||||
<h1 className="text-3xl font-bold tracking-tight">{id ? 'Редактирование работы' : teacher ? 'Загрузка книги или учебного материала' : 'Новая публикация'}</h1>
|
||||
<p className="mt-1 text-muted">
|
||||
{teacher
|
||||
? 'Учебники, пособия, методички, конспекты лекций. После проверки библиотекарем издание появится в каталоге и в ваших списках литературы.'
|
||||
: 'Поля со звёздочкой обязательны. Черновик можно сохранить и вернуться к нему позже.'}
|
||||
</p>
|
||||
|
||||
{item?.status === 'REJECTED' && item.reviewNote && (
|
||||
<div className="mt-6 flex gap-3 rounded-2xl bg-rose-50 p-4 text-sm text-rose-800 dark:bg-rose-500/10 dark:text-rose-200">
|
||||
<MessageSquareWarning className="mt-0.5 size-5 shrink-0" />
|
||||
<div><b>Что нужно исправить:</b> {item.reviewNote}</div>
|
||||
</div>
|
||||
)}
|
||||
{error && <div className="mt-6 rounded-xl bg-rose-50 p-3 text-sm text-rose-700 dark:bg-rose-500/10 dark:text-rose-300">{error}</div>}
|
||||
|
||||
<div className="mt-6 space-y-6">
|
||||
{/* Файл */}
|
||||
<section className="card p-6">
|
||||
<h2 className="mb-4 font-semibold">1. {teacher ? 'Файл книги *' : 'Файл работы *'}</h2>
|
||||
<div
|
||||
onClick={() => fileRef.current.click()}
|
||||
onDragOver={(e) => { e.preventDefault(); setOver(true); }}
|
||||
onDragLeave={() => setOver(false)}
|
||||
onDrop={(e) => { e.preventDefault(); setOver(false); e.dataTransfer.files[0] && setFile(e.dataTransfer.files[0]); }}
|
||||
className={clsx(
|
||||
'flex cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed p-8 text-center transition',
|
||||
over ? 'border-emerald-500 bg-emerald-50 dark:bg-emerald-500/10' : 'border-line hover:border-emerald-400 hover:bg-surface-2'
|
||||
)}
|
||||
>
|
||||
<input ref={fileRef} type="file" accept={teacher ? TEACHER_ACCEPT : ACCEPT} hidden onChange={(e) => e.target.files[0] && setFile(e.target.files[0])} />
|
||||
{file || item?.hasFile ? (
|
||||
<>
|
||||
<FileText className="mb-2 size-9 text-emerald-500" />
|
||||
<div className="max-w-full truncate font-medium">{file ? file.name : item.fileName}</div>
|
||||
<div className="text-xs text-muted">{fmtSize(file ? file.size : item.fileSize)} · нажмите, чтобы заменить</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<UploadCloud className="mb-2 size-9 text-emerald-500" />
|
||||
<div className="font-medium">Перетащите файл сюда или нажмите для выбора</div>
|
||||
<div className="mt-1 text-xs text-muted">
|
||||
PDF (рекомендуется: его можно читать онлайн), DOC, DOCX, ODT, PPTX{teacher && ', EPUB, DJVU, TXT'}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Описание */}
|
||||
<section className="card space-y-4 p-6">
|
||||
<h2 className="font-semibold">2. Описание</h2>
|
||||
<div>
|
||||
<label className="label">{teacher ? 'Тип материала *' : 'Тип работы *'}</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{types.map((t) => (
|
||||
<button
|
||||
key={t}
|
||||
type="button"
|
||||
onClick={() => setForm({ ...form, type: t })}
|
||||
className={clsx(
|
||||
'rounded-full border px-3.5 py-1.5 text-sm transition',
|
||||
form.type === t ? 'border-emerald-500 bg-emerald-50 font-medium text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300' : 'border-line text-muted hover:text-ink'
|
||||
)}
|
||||
>
|
||||
{BOOK_TYPES[t]}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Название *</label>
|
||||
<input className="input" value={form.title} onChange={set('title')} placeholder="Например: Применение машинного обучения для…" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Подзаголовок</label>
|
||||
<input className="input" value={form.subtitle} onChange={set('subtitle')} />
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div>
|
||||
<label className="label">Авторы *</label>
|
||||
<input className="input" value={form.authors} onChange={set('authors')} placeholder="Фамилия И. О., соавторы через запятую" />
|
||||
</div>
|
||||
{!teacher && (
|
||||
<div>
|
||||
<label className="label">Научный руководитель</label>
|
||||
<SupervisorPicker value={form.supervisor} id={form.supervisorId} onChange={(p) => setForm({ ...form, ...p })} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<label className="label flex justify-between">
|
||||
<span>{teacher ? 'Аннотация' : 'Аннотация *'}</span>
|
||||
{!teacher && <span className={clsx('tnum', descLen < 50 ? 'text-amber-600' : 'text-emerald-600')}>{descLen} / мин. 50</span>}
|
||||
</label>
|
||||
<textarea className="input h-36 resize-y py-2" value={form.description} onChange={set('description')} placeholder={teacher ? 'О чём издание, для каких дисциплин и курсов' : 'Цель, методы, основные результаты и выводы работы'} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Ключевые слова (через запятую)</label>
|
||||
<input className="input" value={form.keywords} onChange={set('keywords')} placeholder="нейросети, распознавание, python" />
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-4">
|
||||
<div className="sm:col-span-2">
|
||||
<label className="label">Раздел каталога</label>
|
||||
<select className="input" value={form.categoryId ?? ''} onChange={set('categoryId')}>
|
||||
<option value="">— выберите —</option>
|
||||
{cats.data?.items.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Язык</label>
|
||||
<select className="input" value={form.language} onChange={set('language')}>
|
||||
{Object.entries(LANGUAGES).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Год</label>
|
||||
<input className="input" type="number" value={form.year} onChange={set('year')} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-4">
|
||||
<div className="sm:col-span-3">
|
||||
<label className="label">{teacher ? 'Издательство' : 'Где опубликовано / представлено'}</label>
|
||||
<input className="input" value={form.publisher} onChange={set('publisher')} placeholder={teacher ? 'Издательство или кафедра' : 'Журнал, конференция или кафедра'} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Страниц</label>
|
||||
<input className="input" type="number" value={form.pages} onChange={set('pages')} />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Список литературы (преподаватель) */}
|
||||
{teacher && !id && (
|
||||
<section className="card p-6">
|
||||
<h2 className="mb-1 flex items-center gap-2 font-semibold"><BookMarked className="size-4.5 text-violet-500" />3. Список литературы</h2>
|
||||
<p className="mb-4 text-sm text-muted">Издание сразу появится в выбранном списке. Студенты групп увидят его после проверки библиотекарем.</p>
|
||||
{myLists.data?.items.length ? (
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<div className="sm:col-span-2">
|
||||
<label className="label">Добавить в список</label>
|
||||
<select className="input" value={listId} onChange={(e) => setListId(e.target.value)}>
|
||||
<option value="">— не добавлять —</option>
|
||||
{myLists.data.items.map((l) => (
|
||||
<option key={l.id} value={l.id}>{l.title}{l.groups.length ? ` (${l.groups.join(', ')})` : ''}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Раздел</label>
|
||||
<select className="input" value={required ? '1' : '0'} disabled={!listId} onChange={(e) => setRequired(e.target.value === '1')}>
|
||||
<option value="1">Основная литература</option>
|
||||
<option value="0">Дополнительная</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-subtle">
|
||||
{myLists.loading ? 'Загрузка списков…' : <>У вас пока нет списков. <Link to="/lists" className="text-violet-600 hover:underline dark:text-violet-300">Создать список</Link></>}
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* Отправка */}
|
||||
<section className="card p-6">
|
||||
<h2 className="mb-4 font-semibold">{teacher && !id ? '4' : '3'}. Отправка</h2>
|
||||
<label className="flex cursor-pointer items-start gap-3 text-sm">
|
||||
<input type="checkbox" checked={agree} onChange={(e) => setAgree(e.target.checked)} className="mt-0.5 size-4 accent-emerald-600" />
|
||||
<span>
|
||||
{teacher
|
||||
? 'Подтверждаю, что являюсь автором издания или имею право на его размещение (издание распространяется по открытой лицензии либо получено разрешение правообладателя).'
|
||||
: 'Подтверждаю, что являюсь автором (соавтором) работы, заимствования оформлены ссылками, и даю согласие на её размещение в электронной библиотеке университета.'}
|
||||
</span>
|
||||
</label>
|
||||
<div className="mt-4 flex items-start gap-2 rounded-xl bg-surface-2 p-3 text-xs text-muted">
|
||||
<Info className="mt-0.5 size-4 shrink-0" />
|
||||
После отправки {teacher ? 'издание' : 'работу'} проверит библиотекарь. Статус проверки виден в разделе «Публикации».
|
||||
</div>
|
||||
{progress !== null && (
|
||||
<div className="mt-4 flex items-center gap-3">
|
||||
<div className="h-2 flex-1 overflow-hidden rounded-full bg-surface-2">
|
||||
<div className="h-full rounded-full bg-emerald-500 transition-all" style={{ width: `${progress * 100}%` }} />
|
||||
</div>
|
||||
<span className="text-xs text-muted tnum">{Math.round(progress * 100)}%</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-5 flex flex-wrap justify-end gap-2">
|
||||
<Button variant="secondary" icon={Save} disabled={progress !== null} onClick={() => submit(true)}>Сохранить черновик</Button>
|
||||
<Button icon={Send} loading={progress !== null} onClick={() => submit(false)} className="!bg-emerald-600 hover:!bg-emerald-700">
|
||||
Отправить на модерацию
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link, useSearchParams } from 'react-router-dom';
|
||||
import clsx from 'clsx';
|
||||
import {
|
||||
BadgeCheck, BookOpen, BookPlus, FileCheck2, FileUp, FileX2, ListPlus, Download, Eye, FileSpreadsheet, Heart, LogIn, LogOut, Pencil, Radio, Search, ShieldAlert, Trash2, UserCog, UserPlus, Activity as ActivityIcon,
|
||||
} from 'lucide-react';
|
||||
import { qs, useApi } from '../../lib/api';
|
||||
import { EVENT_LABELS, KIND_LABELS, fmtDateTime, fmtNum } from '../../lib/format';
|
||||
import { Avatar, Button, Empty, ErrorBox, PageLoader, Pagination, Switch } from '../../components/ui';
|
||||
import { PageHeader } from '../../layouts/AdminLayout';
|
||||
import { reasonLabel } from './Dashboard';
|
||||
|
||||
const ICONS = {
|
||||
LOGIN: [LogIn, 'text-sky-600 bg-sky-50 dark:bg-sky-500/15 dark:text-sky-300'],
|
||||
LOGOUT: [LogOut, 'text-slate-500 bg-surface-2'],
|
||||
LOGIN_FAILED: [ShieldAlert, 'text-rose-600 bg-rose-50 dark:bg-rose-500/15 dark:text-rose-300'],
|
||||
REGISTER: [UserPlus, 'text-emerald-600 bg-emerald-50 dark:bg-emerald-500/15 dark:text-emerald-300'],
|
||||
VIEW: [Eye, 'text-slate-500 bg-surface-2'],
|
||||
READ: [BookOpen, 'text-violet-600 bg-violet-50 dark:bg-violet-500/15 dark:text-violet-300'],
|
||||
DOWNLOAD: [Download, 'text-emerald-600 bg-emerald-50 dark:bg-emerald-500/15 dark:text-emerald-300'],
|
||||
SEARCH: [Search, 'text-amber-600 bg-amber-50 dark:bg-amber-500/15 dark:text-amber-300'],
|
||||
FAVORITE: [Heart, 'text-pink-600 bg-pink-50 dark:bg-pink-500/15 dark:text-pink-300'],
|
||||
BOOK_CREATE: [BookPlus, 'text-brand-600 bg-brand-50 dark:bg-brand-500/15 dark:text-brand-300'],
|
||||
BOOK_UPDATE: [Pencil, 'text-brand-600 bg-brand-50 dark:bg-brand-500/15 dark:text-brand-300'],
|
||||
BOOK_DELETE: [Trash2, 'text-rose-600 bg-rose-50 dark:bg-rose-500/15 dark:text-rose-300'],
|
||||
SUBMIT: [FileUp, 'text-teal-600 bg-teal-50 dark:bg-teal-500/15 dark:text-teal-300'],
|
||||
SUBMIT_APPROVE: [FileCheck2, 'text-emerald-600 bg-emerald-50 dark:bg-emerald-500/15 dark:text-emerald-300'],
|
||||
SUBMIT_REJECT: [FileX2, 'text-rose-600 bg-rose-50 dark:bg-rose-500/15 dark:text-rose-300'],
|
||||
LIST_CREATE: [ListPlus, 'text-violet-600 bg-violet-50 dark:bg-violet-500/15 dark:text-violet-300'],
|
||||
ENDORSE: [BadgeCheck, 'text-violet-600 bg-violet-50 dark:bg-violet-500/15 dark:text-violet-300'],
|
||||
USER_UPDATE: [UserCog, 'text-violet-600 bg-violet-50 dark:bg-violet-500/15 dark:text-violet-300'],
|
||||
};
|
||||
|
||||
export function EventIcon({ type }) {
|
||||
const [Icon, cls] = ICONS[type] || [ActivityIcon, 'bg-surface-2 text-muted'];
|
||||
return (
|
||||
<span className={clsx('flex size-8 shrink-0 items-center justify-center rounded-lg', cls)} title={EVENT_LABELS[type]}>
|
||||
<Icon className="size-4" />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function details(e) {
|
||||
const meta = e.meta ? JSON.parse(e.meta) : {};
|
||||
if (e.book) return <Link to={`/books/${e.book.id}`} className="text-brand-600 hover:underline dark:text-brand-300">{e.book.title}</Link>;
|
||||
if (e.type === 'SEARCH') return <span>«{e.query}» <span className={e.resultCount === 0 ? 'font-medium text-amber-600 dark:text-amber-400' : 'text-muted'}>— {e.resultCount} рез.</span></span>;
|
||||
if (e.type === 'LOGIN_FAILED') return <span className="text-muted">логин «{meta.username}» · {reasonLabel(meta.reason)}</span>;
|
||||
if (e.type === 'BOOK_DELETE') return <span className="text-muted">{meta.title}</span>;
|
||||
if (e.type === 'LIST_CREATE') return <Link to={`/lists/${meta.listId}`} className="text-brand-600 hover:underline dark:text-brand-300">{meta.title}{meta.groups?.length ? ` · ${meta.groups.join(', ')}` : ''}</Link>;
|
||||
if (e.type === 'USER_UPDATE') return <span className="text-muted">{meta.target}{meta.isBlocked !== undefined ? (meta.isBlocked ? ' — заблокирован' : ' — разблокирован') : ''}{meta.roleOverride !== undefined ? ` — роль: ${meta.role}` : ''}</span>;
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function Activity() {
|
||||
const [sp, setSp] = useSearchParams();
|
||||
const [q, setQ] = useState(sp.get('q') || '');
|
||||
const [live, setLive] = useState(false);
|
||||
const f = Object.fromEntries(['type', 'kind', 'q', 'from', 'to', 'userId', 'bookId', 'ip', 'page'].map((k) => [k, sp.get(k) || '']));
|
||||
const query = qs({ ...f, page: f.page || 1, limit: 50 });
|
||||
const { data, error, loading, reload } = useApi('/stats/events' + query);
|
||||
|
||||
useEffect(() => {
|
||||
if (!live) return;
|
||||
const t = setInterval(() => reload(true), 5000);
|
||||
return () => clearInterval(t);
|
||||
}, [live, reload]);
|
||||
|
||||
const update = (patch) => {
|
||||
const next = new URLSearchParams(sp);
|
||||
for (const [k, v] of Object.entries(patch)) v ? next.set(k, v) : next.delete(k);
|
||||
if (!('page' in patch)) next.delete('page');
|
||||
setSp(next);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Журнал событий"
|
||||
subtitle="Кто, когда и что делал: входы, просмотры, чтение, скачивания, поиск, изменения"
|
||||
actions={
|
||||
<>
|
||||
<Switch checked={live} onChange={setLive} label={<span className="flex items-center gap-1.5"><Radio className={clsx('size-4', live && 'animate-pulse text-emerald-500')} />Онлайн-режим</span>} />
|
||||
<a href={'/api/stats/events.csv' + qs({ ...f, page: '' })}>
|
||||
<Button variant="secondary" icon={FileSpreadsheet}>Экспорт в Excel</Button>
|
||||
</a>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
<div className="card overflow-hidden">
|
||||
<div className="flex flex-wrap items-center gap-3 border-b border-line p-4">
|
||||
<form className="relative min-w-[220px] flex-1" onSubmit={(e) => { e.preventDefault(); update({ q }); }}>
|
||||
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-subtle" />
|
||||
<input className="input pl-9" placeholder="Логин, ФИО, книга, запрос… (Enter)" value={q} onChange={(e) => setQ(e.target.value)} />
|
||||
</form>
|
||||
<select className="input w-auto" value={f.type} onChange={(e) => update({ type: e.target.value })}>
|
||||
<option value="">Все события</option>
|
||||
<option value="DOWNLOAD">Скачивания</option>
|
||||
<option value="READ">Чтение онлайн</option>
|
||||
<option value="VIEW">Просмотры</option>
|
||||
<option value="LOGIN,LOGOUT,REGISTER">Входы и выходы</option>
|
||||
<option value="LOGIN_FAILED">Неудачные входы</option>
|
||||
<option value="SEARCH">Поиск</option>
|
||||
<option value="SUBMIT,SUBMIT_APPROVE,SUBMIT_REJECT,ENDORSE">Публикации студентов</option>
|
||||
<option value="LIST_CREATE,ENDORSE">Действия преподавателей</option>
|
||||
<option value="BOOK_CREATE,BOOK_UPDATE,BOOK_DELETE,USER_UPDATE,SUBMIT_APPROVE,SUBMIT_REJECT">Действия модераторов</option>
|
||||
</select>
|
||||
<select className="input w-auto" value={f.kind} onChange={(e) => update({ kind: e.target.value })}>
|
||||
<option value="">Все пользователи</option>
|
||||
<option value="STUDENT">Студенты</option>
|
||||
<option value="TEACHER">Преподаватели</option>
|
||||
<option value="STAFF">Сотрудники</option>
|
||||
</select>
|
||||
<input type="date" className="input w-auto" value={f.from} onChange={(e) => update({ from: e.target.value })} title="С даты" />
|
||||
<input type="date" className="input w-auto" value={f.to} onChange={(e) => update({ to: e.target.value })} title="По дату" />
|
||||
<input className="input w-36" placeholder="IP-адрес" defaultValue={f.ip} onKeyDown={(e) => e.key === 'Enter' && update({ ip: e.target.value })} />
|
||||
{(f.userId || f.bookId || [...sp.keys()].length > 0) && (
|
||||
<Button variant="ghost" size="sm" onClick={() => { setQ(''); setSp({}); }}>Сбросить</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && <div className="p-4"><ErrorBox error={error} onRetry={reload} /></div>}
|
||||
{loading && !data && <PageLoader />}
|
||||
{data && !data.items.length && <Empty icon={ActivityIcon} title="Событий не найдено" text="Измените фильтры или период" />}
|
||||
{data && data.items.length > 0 && (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-surface-2 text-xs text-muted">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left font-medium">Событие</th>
|
||||
<th className="px-4 py-3 text-left font-medium">Пользователь</th>
|
||||
<th className="px-4 py-3 text-left font-medium">Детали</th>
|
||||
<th className="hidden px-4 py-3 text-left font-medium lg:table-cell">Устройство / IP</th>
|
||||
<th className="px-4 py-3 text-right font-medium">Время</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-line">
|
||||
{data.items.map((e) => (
|
||||
<tr key={e.id} className="hover:bg-surface-2/60">
|
||||
<td className="px-4 py-2.5">
|
||||
<div className="flex items-center gap-2.5 whitespace-nowrap">
|
||||
<EventIcon type={e.type} />
|
||||
<span className="font-medium">{EVENT_LABELS[e.type] || e.type}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-2.5">
|
||||
{e.user ? (
|
||||
<Link to={`/admin/users/${e.user.id}`} className="flex items-center gap-2 hover:opacity-80">
|
||||
<Avatar name={e.user.displayName} size={28} />
|
||||
<div className="min-w-0">
|
||||
<div className="max-w-[200px] truncate font-medium">{e.user.displayName}</div>
|
||||
<div className="max-w-[200px] truncate text-xs text-muted">{e.userKind ? KIND_LABELS[e.userKind] + ' · ' : ''}{e.user.studyGroup || e.user.department || e.user.username}</div>
|
||||
</div>
|
||||
</Link>
|
||||
) : <span className="text-subtle">—</span>}
|
||||
</td>
|
||||
<td className="max-w-[320px] truncate px-4 py-2.5">{details(e)}</td>
|
||||
<td className="hidden px-4 py-2.5 text-xs text-muted lg:table-cell">
|
||||
<div>{e.device} · {e.browser} · {e.os}</div>
|
||||
<button className="font-mono hover:text-brand-600" onClick={() => update({ ip: e.ip })} title="Фильтр по IP">{e.ip}</button>
|
||||
</td>
|
||||
<td className="px-4 py-2.5 text-right text-xs whitespace-nowrap text-muted tnum">{fmtDateTime(e.createdAt)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between border-t border-line p-3">
|
||||
<span className="pl-2 text-xs text-muted tnum">{data && `Найдено: ${fmtNum(data.total)}`}</span>
|
||||
<Pagination page={Number(f.page) || 1} pages={data?.pages} onChange={(page) => update({ page })} />
|
||||
<span />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import { useRef, useState } from 'react';
|
||||
import clsx from 'clsx';
|
||||
import { FileUp, ImagePlus, Trash2, UploadCloud } from 'lucide-react';
|
||||
import { upload, useApi } from '../../lib/api';
|
||||
import { BOOK_TYPES, LANGUAGES, fmtSize } from '../../lib/format';
|
||||
import { Button, Modal, Switch, useToast } from '../../components/ui';
|
||||
import BookCover from '../../components/BookCover';
|
||||
|
||||
const FIELDS = ['title', 'subtitle', 'authors', 'description', 'isbn', 'udc', 'publisher', 'year', 'language', 'type', 'pages', 'keywords', 'categoryId'];
|
||||
|
||||
function DropZone({ accept, file, onFile, icon: Icon, title, hint, current }) {
|
||||
const ref = useRef();
|
||||
const [over, setOver] = useState(false);
|
||||
return (
|
||||
<div
|
||||
onClick={() => ref.current.click()}
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault();
|
||||
setOver(true);
|
||||
}}
|
||||
onDragLeave={() => setOver(false)}
|
||||
onDrop={(e) => {
|
||||
e.preventDefault();
|
||||
setOver(false);
|
||||
if (e.dataTransfer.files[0]) onFile(e.dataTransfer.files[0]);
|
||||
}}
|
||||
className={clsx(
|
||||
'flex cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed p-5 text-center transition',
|
||||
over ? 'border-brand-500 bg-brand-50 dark:bg-brand-500/10' : 'border-line hover:border-brand-300 hover:bg-surface-2'
|
||||
)}
|
||||
>
|
||||
<input ref={ref} type="file" accept={accept} hidden onChange={(e) => e.target.files[0] && onFile(e.target.files[0])} />
|
||||
<Icon className="mb-2 size-7 text-brand-500" />
|
||||
{file ? (
|
||||
<>
|
||||
<div className="max-w-full truncate text-sm font-medium">{file.name}</div>
|
||||
<div className="text-xs text-muted">{fmtSize(file.size)} · нажмите, чтобы заменить</div>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="text-sm font-medium">{title}</div>
|
||||
<div className="text-xs text-muted">{current || hint}</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function BookForm({ book, onClose, onSaved }) {
|
||||
const toast = useToast();
|
||||
const cats = useApi('/categories');
|
||||
const [form, setForm] = useState(() => {
|
||||
const f = Object.fromEntries(FIELDS.map((k) => [k, book?.[k] ?? '']));
|
||||
if (!book) Object.assign(f, { language: 'ru', type: 'textbook' });
|
||||
f.isPublished = book ? book.isPublished : true;
|
||||
return f;
|
||||
});
|
||||
const [file, setFile] = useState(null);
|
||||
const [cover, setCover] = useState(null);
|
||||
const [removeCover, setRemoveCover] = useState(false);
|
||||
const [progress, setProgress] = useState(null);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });
|
||||
|
||||
const onFile = (f) => {
|
||||
setFile(f);
|
||||
// Подставляем название из имени файла, если поле пустое
|
||||
if (!form.title) setForm((s) => ({ ...s, title: f.name.replace(/\.[^.]+$/, '').replace(/[_]+/g, ' ') }));
|
||||
};
|
||||
|
||||
const submit = async (e) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
if (!form.title.trim() || !form.authors.trim()) return setError('Заполните название и авторов');
|
||||
const fd = new FormData();
|
||||
for (const [k, v] of Object.entries(form)) fd.append(k, v ?? '');
|
||||
if (file) fd.append('file', file);
|
||||
if (cover) fd.append('cover', cover);
|
||||
if (removeCover) fd.append('removeCover', 'true');
|
||||
setProgress(0);
|
||||
try {
|
||||
const res = await upload(book ? `/books/${book.id}` : '/books', book ? 'PUT' : 'POST', fd, setProgress);
|
||||
toast(book ? 'Изменения сохранены' : 'Книга добавлена');
|
||||
onSaved?.(res.book);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setProgress(null);
|
||||
}
|
||||
};
|
||||
|
||||
const coverPreview = cover ? URL.createObjectURL(cover) : removeCover ? null : book?.coverUrl;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open
|
||||
onClose={progress === null ? onClose : undefined}
|
||||
title={book ? 'Редактирование издания' : 'Новое издание'}
|
||||
size="lg"
|
||||
footer={
|
||||
<>
|
||||
{progress !== null && (
|
||||
<div className="mr-auto flex flex-1 items-center gap-3">
|
||||
<div className="h-2 flex-1 overflow-hidden rounded-full bg-surface-2">
|
||||
<div className="h-full rounded-full bg-brand-600 transition-all" style={{ width: `${progress * 100}%` }} />
|
||||
</div>
|
||||
<span className="text-xs text-muted tnum">{Math.round(progress * 100)}%</span>
|
||||
</div>
|
||||
)}
|
||||
<Button variant="secondary" onClick={onClose} disabled={progress !== null}>Отмена</Button>
|
||||
<Button type="submit" form="book-form" loading={progress !== null}>{book ? 'Сохранить' : 'Добавить'}</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<form id="book-form" onSubmit={submit} className="grid gap-6 md:grid-cols-[180px_1fr]">
|
||||
<div className="space-y-3">
|
||||
<div className="relative">
|
||||
<BookCover book={{ title: form.title || 'Название', authors: form.authors, coverUrl: coverPreview }} />
|
||||
{coverPreview && (
|
||||
<button type="button" onClick={() => { setCover(null); setRemoveCover(true); }} className="absolute top-2 right-2 rounded-lg bg-black/50 p-1.5 text-white hover:bg-black/70" title="Убрать обложку">
|
||||
<Trash2 className="size-4" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<DropZone accept="image/jpeg,image/png,image/webp" file={cover} onFile={(f) => { setCover(f); setRemoveCover(false); }} icon={ImagePlus} title="Обложка" hint="JPG, PNG, WEBP" />
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<DropZone
|
||||
accept=".pdf,.epub,.djvu,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.rtf,.txt,.zip,.rar,.mp3,.mp4"
|
||||
file={file}
|
||||
onFile={onFile}
|
||||
icon={book?.hasFile ? FileUp : UploadCloud}
|
||||
title={book?.hasFile ? 'Заменить файл' : 'Перетащите файл издания сюда'}
|
||||
hint="PDF, EPUB, DJVU, DOCX, PPTX, MP4… — PDF можно читать онлайн"
|
||||
current={book?.hasFile ? `Текущий: ${book.fileName} (${fmtSize(book.fileSize)})` : null}
|
||||
/>
|
||||
<div>
|
||||
<label className="label">Название *</label>
|
||||
<input className="input" value={form.title} onChange={set('title')} required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Подзаголовок</label>
|
||||
<input className="input" value={form.subtitle} onChange={set('subtitle')} placeholder="Учебное пособие для студентов…" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Авторы *</label>
|
||||
<input className="input" value={form.authors} onChange={set('authors')} placeholder="Иванов И. И., Петров П. П." required />
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div>
|
||||
<label className="label">Раздел</label>
|
||||
<select className="input" value={form.categoryId ?? ''} onChange={set('categoryId')}>
|
||||
<option value="">— не выбран —</option>
|
||||
{cats.data?.items.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Тип издания</label>
|
||||
<select className="input" value={form.type} onChange={set('type')}>
|
||||
{Object.entries(BOOK_TYPES).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Язык</label>
|
||||
<select className="input" value={form.language} onChange={set('language')}>
|
||||
{Object.entries(LANGUAGES).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="label">Год</label>
|
||||
<input className="input" type="number" value={form.year} onChange={set('year')} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Страниц</label>
|
||||
<input className="input" type="number" value={form.pages} onChange={set('pages')} />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Издательство</label>
|
||||
<input className="input" value={form.publisher} onChange={set('publisher')} />
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div>
|
||||
<label className="label">ISBN</label>
|
||||
<input className="input" value={form.isbn} onChange={set('isbn')} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">УДК / ББК</label>
|
||||
<input className="input" value={form.udc} onChange={set('udc')} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Описание / аннотация</label>
|
||||
<textarea className="input h-28 resize-y py-2" value={form.description} onChange={set('description')} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Ключевые слова (через запятую)</label>
|
||||
<input className="input" value={form.keywords} onChange={set('keywords')} placeholder="алгебра, матрицы, векторы" />
|
||||
</div>
|
||||
<Switch checked={form.isPublished} onChange={(v) => setForm({ ...form, isPublished: v })} label="Опубликовано — видно читателям" />
|
||||
{error && <div className="rounded-xl bg-rose-50 p-3 text-sm text-rose-700 dark:bg-rose-500/10 dark:text-rose-300">{error}</div>}
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { BarChart3 } from 'lucide-react';
|
||||
import { useApi } from '../../lib/api';
|
||||
import { fmtNum, timeAgo } from '../../lib/format';
|
||||
import { Avatar } from '../../components/ui';
|
||||
import { TimelineChart } from './charts';
|
||||
|
||||
const SERIES = [
|
||||
{ key: 'VIEW', label: 'Просмотры', color: 'var(--series-1)' },
|
||||
{ key: 'READ', label: 'Чтение', color: 'var(--series-2)' },
|
||||
{ key: 'DOWNLOAD', label: 'Скачивания', color: 'var(--series-3)' },
|
||||
];
|
||||
|
||||
/** Статистика книги — видна только модераторам и администраторам */
|
||||
export default function BookStats({ bookId }) {
|
||||
const { data } = useApi(`/stats/books/${bookId}`, [bookId]);
|
||||
if (!data) return null;
|
||||
return (
|
||||
<div className="mt-10 rounded-2xl border border-dashed border-brand-300 bg-brand-50/40 p-5 dark:border-brand-500/30 dark:bg-brand-500/5">
|
||||
<h2 className="mb-1 flex items-center gap-2 text-lg font-semibold">
|
||||
<BarChart3 className="size-5 text-brand-500" /> Статистика издания
|
||||
</h2>
|
||||
<p className="mb-4 text-xs text-muted">
|
||||
Видно только модераторам · всего: {fmtNum(data.counts.VIEW)} просмотров, {fmtNum(data.counts.READ)} открытий, {fmtNum(data.counts.DOWNLOAD)} скачиваний
|
||||
</p>
|
||||
<div className="card p-4">
|
||||
<TimelineChart data={data.timeline} series={SERIES} height={200} />
|
||||
</div>
|
||||
{data.recentDownloads.length > 0 && (
|
||||
<div className="mt-4">
|
||||
<div className="mb-2 text-sm font-medium">Кто скачивал недавно</div>
|
||||
<div className="card divide-y divide-line">
|
||||
{data.recentDownloads.slice(0, 8).map((e) => (
|
||||
<Link key={e.id} to={e.user ? `/admin/users/${e.user.id}` : '#'} className="flex items-center gap-3 px-4 py-2.5 text-sm hover:bg-surface-2">
|
||||
<Avatar name={e.user?.displayName || '?'} size={28} />
|
||||
<span className="min-w-0 flex-1 truncate">
|
||||
{e.user?.displayName || 'Удалённый пользователь'} <span className="text-muted">· {e.user?.department || ''}</span>
|
||||
</span>
|
||||
<span className="shrink-0 text-xs text-subtle">{timeAgo(e.createdAt)}</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { BookPlus, Download, Eye, Pencil, Search, Trash2, BookX } from 'lucide-react';
|
||||
import { api, qs, useApi } from '../../lib/api';
|
||||
import { BOOK_TYPES, fmtDate, fmtNum, fmtSize } from '../../lib/format';
|
||||
import { Badge, Button, Empty, ErrorBox, Modal, Pagination, PageLoader, useToast } from '../../components/ui';
|
||||
import BookCover from '../../components/BookCover';
|
||||
import { PageHeader } from '../../layouts/AdminLayout';
|
||||
import BookForm from './BookForm';
|
||||
|
||||
export default function AdminBooks() {
|
||||
const toast = useToast();
|
||||
const [q, setQ] = useState('');
|
||||
const [params, setParams] = useState({ q: '', page: 1, sort: 'new', category: '', fund: 'own' });
|
||||
const [editing, setEditing] = useState(null); // null | 'new' | book
|
||||
const [deleting, setDeleting] = useState(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const cats = useApi('/categories');
|
||||
const { data, error, loading, reload } = useApi('/books' + qs({ ...params, all: 1, limit: 20 }));
|
||||
|
||||
const del = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api(`/books/${deleting.id}`, { method: 'DELETE' });
|
||||
toast('Издание удалено');
|
||||
setDeleting(null);
|
||||
reload();
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Книги"
|
||||
subtitle={data ? `${fmtNum(data.total)} ${params.fund === 'shared' ? 'изданий в общем фонде платформы' : params.fund === 'own' ? 'изданий в фонде организации' : 'изданий'}` : ' '}
|
||||
actions={<Button icon={BookPlus} onClick={() => setEditing('new')}>Добавить издание</Button>}
|
||||
/>
|
||||
|
||||
<div className="card overflow-hidden">
|
||||
<div className="flex flex-wrap items-center gap-3 border-b border-line p-4">
|
||||
<form
|
||||
className="relative min-w-[220px] flex-1"
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
setParams({ ...params, q, page: 1 });
|
||||
}}
|
||||
>
|
||||
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-subtle" />
|
||||
<input className="input pl-9" placeholder="Поиск по названию, автору, ISBN… (Enter)" value={q} onChange={(e) => setQ(e.target.value)} />
|
||||
</form>
|
||||
<select className="input w-auto" value={params.fund} onChange={(e) => setParams({ ...params, fund: e.target.value, page: 1 })}>
|
||||
<option value="own">Фонд организации</option>
|
||||
<option value="shared">Общий фонд платформы</option>
|
||||
<option value="">Все издания</option>
|
||||
</select>
|
||||
<select className="input w-auto" value={params.category} onChange={(e) => setParams({ ...params, category: e.target.value, page: 1 })}>
|
||||
<option value="">Все разделы</option>
|
||||
{cats.data?.items.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
|
||||
</select>
|
||||
<select className="input w-auto" value={params.sort} onChange={(e) => setParams({ ...params, sort: e.target.value, page: 1 })}>
|
||||
<option value="new">Недавно добавленные</option>
|
||||
<option value="popular">По скачиваниям</option>
|
||||
<option value="views">По просмотрам</option>
|
||||
<option value="title">По названию</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{error && <div className="p-4"><ErrorBox error={error} onRetry={reload} /></div>}
|
||||
{loading && !data && <PageLoader />}
|
||||
{data && data.items.length === 0 && <Empty icon={BookX} title="Изданий не найдено" />}
|
||||
{data && data.items.length > 0 && (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-surface-2 text-xs text-muted">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left font-medium">Издание</th>
|
||||
<th className="hidden px-4 py-3 text-left font-medium md:table-cell">Раздел</th>
|
||||
<th className="hidden px-4 py-3 text-left font-medium lg:table-cell">Файл</th>
|
||||
<th className="px-4 py-3 text-right font-medium"><Eye className="ml-auto size-4" /></th>
|
||||
<th className="px-4 py-3 text-right font-medium"><Download className="ml-auto size-4" /></th>
|
||||
<th className="hidden px-4 py-3 text-left font-medium xl:table-cell">Добавлено</th>
|
||||
<th className="px-4 py-3" />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-line">
|
||||
{data.items.map((b) => (
|
||||
<tr key={b.id} className="hover:bg-surface-2/60">
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<BookCover book={b} size="sm" className="w-10 shrink-0 !rounded" />
|
||||
<div className="min-w-0">
|
||||
<Link to={`/books/${b.id}`} className="line-clamp-1 font-medium hover:text-brand-600 dark:hover:text-brand-300">{b.title}</Link>
|
||||
<div className="truncate text-xs text-muted">{b.authors}{b.year ? ` · ${b.year}` : ''}</div>
|
||||
<div className="mt-1 flex gap-1.5">
|
||||
<Badge>{BOOK_TYPES[b.type] || b.type}</Badge>
|
||||
{!b.isPublished && <Badge color="amber">Черновик</Badge>}
|
||||
{!b.hasFile && <Badge color="red">Нет файла</Badge>}
|
||||
{b.shared && <Badge color="sky">Общий фонд</Badge>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td className="hidden px-4 py-3 md:table-cell">
|
||||
{b.category ? (
|
||||
<span className="flex items-center gap-2 text-muted"><span className="size-2 rounded-full" style={{ background: b.category.color }} />{b.category.name}</span>
|
||||
) : <span className="text-subtle">—</span>}
|
||||
</td>
|
||||
<td className="hidden px-4 py-3 text-muted lg:table-cell">
|
||||
{b.hasFile ? <span className="uppercase">{b.fileExt}</span> : '—'} <span className="text-xs text-subtle">{b.hasFile && fmtSize(b.fileSize)}</span>
|
||||
</td>
|
||||
<td className="px-4 py-3 text-right tnum">{fmtNum(b.viewCount)}</td>
|
||||
<td className="px-4 py-3 text-right font-semibold tnum">{fmtNum(b.downloadCount)}</td>
|
||||
<td className="hidden px-4 py-3 text-muted xl:table-cell">{fmtDate(b.createdAt)}</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex justify-end gap-1">
|
||||
{/* книги общего фонда меняет только администратор платформы */}
|
||||
{b.shared ? (
|
||||
<span className="px-2 text-xs text-subtle" title="Книга общего фонда платформы — доступна всем организациям">только чтение</span>
|
||||
) : (
|
||||
<>
|
||||
<Button variant="ghost" size="icon" onClick={() => setEditing(b)} title="Редактировать"><Pencil className="size-4" /></Button>
|
||||
<Button variant="ghost" size="icon" onClick={() => setDeleting(b)} title="Удалить" className="hover:!text-rose-600"><Trash2 className="size-4" /></Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
<div className="border-t border-line p-3">
|
||||
<Pagination page={params.page} pages={data?.pages} onChange={(page) => setParams({ ...params, page })} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{editing && (
|
||||
<BookForm
|
||||
book={editing === 'new' ? null : editing}
|
||||
onClose={() => setEditing(null)}
|
||||
onSaved={() => {
|
||||
setEditing(null);
|
||||
reload();
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Modal
|
||||
open={!!deleting}
|
||||
onClose={() => setDeleting(null)}
|
||||
title="Удалить издание?"
|
||||
size="sm"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setDeleting(null)}>Отмена</Button>
|
||||
<Button variant="danger" loading={busy} onClick={del}>Удалить</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<p className="text-sm text-muted">
|
||||
«<b className="text-ink">{deleting?.title}</b>» и его файл будут удалены безвозвратно. История скачиваний в статистике сохранится.
|
||||
</p>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { useState } from 'react';
|
||||
import clsx from 'clsx';
|
||||
import { BookOpen, FolderPlus, Pencil, Trash2 } from 'lucide-react';
|
||||
import { api, useApi } from '../../lib/api';
|
||||
import { CATEGORY_ICONS, plural } from '../../lib/format';
|
||||
import { Button, ErrorBox, Modal, PageLoader, useToast } from '../../components/ui';
|
||||
import { PageHeader } from '../../layouts/AdminLayout';
|
||||
|
||||
const COLORS = ['#6366f1', '#0ea5e9', '#10b981', '#f59e0b', '#8b5cf6', '#ef4444', '#ec4899', '#a16207', '#64748b', '#14b8a6', '#2563eb', '#16a34a'];
|
||||
|
||||
export default function AdminCategories() {
|
||||
const toast = useToast();
|
||||
const { data, error, loading, reload } = useApi('/categories');
|
||||
const [edit, setEdit] = useState(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const save = async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
try {
|
||||
await api(edit.id ? `/categories/${edit.id}` : '/categories', { method: edit.id ? 'PUT' : 'POST', body: edit });
|
||||
toast('Сохранено');
|
||||
setEdit(null);
|
||||
reload();
|
||||
} catch (err) {
|
||||
toast(err.message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (c) => {
|
||||
if (!window.confirm(`Удалить раздел «${c.name}»? Книги останутся без раздела.`)) return;
|
||||
await api(`/categories/${c.id}`, { method: 'DELETE' });
|
||||
toast('Раздел удалён');
|
||||
reload();
|
||||
};
|
||||
|
||||
if (error) return <ErrorBox error={error} onRetry={reload} />;
|
||||
if (loading && !data) return <PageLoader />;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Категории"
|
||||
subtitle="Разделы каталога — показываются на главной и в фильтрах"
|
||||
actions={<Button icon={FolderPlus} onClick={() => setEdit({ name: '', description: '', color: COLORS[0], icon: 'BookOpen', sortOrder: data.items.length })}>Новый раздел</Button>}
|
||||
/>
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{data.items.map((c) => {
|
||||
const Icon = CATEGORY_ICONS[c.icon] || BookOpen;
|
||||
return (
|
||||
<div key={c.id} className="card flex items-center gap-4 p-4">
|
||||
<div className="flex size-12 shrink-0 items-center justify-center rounded-xl text-white" style={{ background: c.color }}>
|
||||
<Icon className="size-6" />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate font-semibold">{c.name}</div>
|
||||
<div className="text-xs text-muted tnum">{c.bookCount} {plural(c.bookCount, 'издание', 'издания', 'изданий')}</div>
|
||||
</div>
|
||||
{c.shared ? (
|
||||
<span className="text-xs text-subtle" title="Общий раздел платформы — его видят все организации">общий</span>
|
||||
) : (
|
||||
<>
|
||||
<Button variant="ghost" size="icon" onClick={() => setEdit(c)} title="Изменить"><Pencil className="size-4" /></Button>
|
||||
<Button variant="ghost" size="icon" onClick={() => remove(c)} title="Удалить" className="hover:!text-rose-600"><Trash2 className="size-4" /></Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
open={!!edit}
|
||||
onClose={() => setEdit(null)}
|
||||
title={edit?.id ? 'Изменить раздел' : 'Новый раздел'}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setEdit(null)}>Отмена</Button>
|
||||
<Button type="submit" form="cat-form" loading={busy}>Сохранить</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
{edit && (
|
||||
<form id="cat-form" onSubmit={save} className="space-y-4">
|
||||
<div>
|
||||
<label className="label">Название *</label>
|
||||
<input className="input" value={edit.name} onChange={(e) => setEdit({ ...edit, name: e.target.value })} required autoFocus />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Описание</label>
|
||||
<textarea className="input h-20 py-2" value={edit.description || ''} onChange={(e) => setEdit({ ...edit, description: e.target.value })} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Цвет</label>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{COLORS.map((c) => (
|
||||
<button type="button" key={c} onClick={() => setEdit({ ...edit, color: c })} className={clsx('size-8 rounded-full transition', edit.color === c && 'ring-2 ring-offset-2 ring-offset-surface')} style={{ background: c, '--tw-ring-color': c }} aria-label={c} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Иконка</label>
|
||||
<div className="grid grid-cols-10 gap-1.5">
|
||||
{Object.entries(CATEGORY_ICONS).map(([name, Icon]) => (
|
||||
<button
|
||||
type="button"
|
||||
key={name}
|
||||
onClick={() => setEdit({ ...edit, icon: name })}
|
||||
className={clsx('flex aspect-square items-center justify-center rounded-lg border transition', edit.icon === name ? 'border-transparent text-white' : 'border-line text-muted hover:text-ink')}
|
||||
style={edit.icon === name ? { background: edit.color } : undefined}
|
||||
title={name}
|
||||
>
|
||||
<Icon className="size-4" />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Порядок сортировки</label>
|
||||
<input className="input w-32" type="number" value={edit.sortOrder} onChange={(e) => setEdit({ ...edit, sortOrder: e.target.value })} />
|
||||
</div>
|
||||
</form>
|
||||
)}
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import {
|
||||
AlertTriangle, ArrowRight, FileCheck2, GraduationCap, Hourglass, Presentation, Briefcase, BookOpen, Download, Eye, HardDrive, Library, LogIn, RefreshCw, Search, SearchX, ShieldAlert, UserPlus, Users,
|
||||
} from 'lucide-react';
|
||||
import { qs, useApi } from '../../lib/api';
|
||||
import { fmtDateTime, fmtNum, fmtSize, plural, timeAgo } from '../../lib/format';
|
||||
import { Avatar, Button, ErrorBox, Modal, PageLoader, Segmented } from '../../components/ui';
|
||||
import BookCover from '../../components/BookCover';
|
||||
import { PageHeader } from '../../layouts/AdminLayout';
|
||||
import { BarList, ChartCard, Heatmap, KpiTile, TimelineChart } from './charts';
|
||||
|
||||
const PERIODS = [
|
||||
{ value: '7', label: '7 дней' },
|
||||
{ value: '30', label: '30 дней' },
|
||||
{ value: '90', label: '90 дней' },
|
||||
{ value: '365', label: 'Год' },
|
||||
{ value: 'custom', label: 'Период' },
|
||||
];
|
||||
|
||||
const ACTIVITY = [
|
||||
{ key: 'VIEW', label: 'Просмотры', color: 'var(--series-1)' },
|
||||
{ key: 'READ', label: 'Чтение онлайн', color: 'var(--series-2)' },
|
||||
{ key: 'DOWNLOAD', label: 'Скачивания', color: 'var(--series-3)' },
|
||||
];
|
||||
|
||||
export default function Dashboard() {
|
||||
const [period, setPeriod] = useState('30');
|
||||
const [custom, setCustom] = useState({ from: '', to: '' });
|
||||
const [tech, setTech] = useState('devices');
|
||||
const [onlineOpen, setOnlineOpen] = useState(false);
|
||||
|
||||
const query = period === 'custom' ? qs(custom) : qs({ days: period });
|
||||
const { data, error, loading, reload } = useApi('/stats/overview' + query);
|
||||
const online = useApi(onlineOpen ? '/stats/online' : null);
|
||||
|
||||
if (error) return <ErrorBox error={error} onRetry={reload} />;
|
||||
if (!data) return <PageLoader />;
|
||||
const k = data.kpi;
|
||||
|
||||
return (
|
||||
<div className={loading ? 'opacity-60 transition-opacity' : 'transition-opacity'}>
|
||||
<PageHeader
|
||||
title="Статистика"
|
||||
subtitle={`${new Date(data.range.from).toLocaleDateString('ru-RU')} — ${new Date(data.range.to).toLocaleDateString('ru-RU')} · сравнение с предыдущими ${data.range.len} дн.`}
|
||||
actions={
|
||||
<>
|
||||
<button
|
||||
onClick={() => setOnlineOpen(true)}
|
||||
className="flex h-10 items-center gap-2 rounded-xl border border-line bg-surface px-3 text-sm font-medium hover:bg-surface-2"
|
||||
>
|
||||
<span className="relative flex size-2.5">
|
||||
<span className="absolute inline-flex size-full animate-ping rounded-full bg-emerald-400 opacity-75" />
|
||||
<span className="relative inline-flex size-2.5 rounded-full bg-emerald-500" />
|
||||
</span>
|
||||
Онлайн: <span className="tnum">{data.totals.online}</span>
|
||||
</button>
|
||||
<Button variant="secondary" size="icon" onClick={() => reload()} title="Обновить">
|
||||
<RefreshCw className="size-4" />
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{/* Фильтры — одна строка над графиками */}
|
||||
<div className="mb-6 flex flex-wrap items-center gap-3">
|
||||
<Segmented value={period} onChange={setPeriod} options={PERIODS} />
|
||||
{period === 'custom' && (
|
||||
<div className="flex items-center gap-2">
|
||||
<input type="date" className="input h-9 w-auto" value={custom.from} onChange={(e) => setCustom({ ...custom, from: e.target.value })} />
|
||||
<span className="text-subtle">—</span>
|
||||
<input type="date" className="input h-9 w-auto" value={custom.to} onChange={(e) => setCustom({ ...custom, to: e.target.value })} />
|
||||
</div>
|
||||
)}
|
||||
<div className="ml-auto flex flex-wrap gap-4 text-xs text-muted">
|
||||
<span className="flex items-center gap-1.5"><Users className="size-4" />{fmtNum(data.totals.users)} пользователей</span>
|
||||
<span className="flex items-center gap-1.5"><Library className="size-4" />{fmtNum(data.totals.books)} изданий</span>
|
||||
<span className="flex items-center gap-1.5"><HardDrive className="size-4" />{fmtSize(data.totals.storageBytes)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{data.totals.pendingSubmissions > 0 && (
|
||||
<Link
|
||||
to="/admin/moderation"
|
||||
className="mb-4 flex items-center gap-3 rounded-2xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900 transition hover:shadow-md dark:border-amber-500/30 dark:bg-amber-500/10 dark:text-amber-200"
|
||||
>
|
||||
<FileCheck2 className="size-5 shrink-0" />
|
||||
<span className="flex-1">
|
||||
<b className="tnum">{data.totals.pendingSubmissions}</b> {plural(data.totals.pendingSubmissions, 'студенческая работа ждёт', 'студенческие работы ждут', 'студенческих работ ждут')} проверки · за период отправлено {data.submissions.submitted}, опубликовано {data.submissions.approved}, возвращено {data.submissions.rejected}
|
||||
</span>
|
||||
<ArrowRight className="size-4" />
|
||||
</Link>
|
||||
)}
|
||||
|
||||
{data.totals.pendingTeachers > 0 && (
|
||||
<Link
|
||||
to="/admin/users?kind=PENDING"
|
||||
className="mb-4 flex items-center gap-3 rounded-2xl border border-violet-200 bg-violet-50 p-4 text-sm text-violet-900 transition hover:shadow-md dark:border-violet-500/30 dark:bg-violet-500/10 dark:text-violet-200"
|
||||
>
|
||||
<Hourglass className="size-5 shrink-0" />
|
||||
<span className="flex-1">
|
||||
<b className="tnum">{data.totals.pendingTeachers}</b> {plural(data.totals.pendingTeachers, 'пользователь вошёл', 'пользователя вошли', 'пользователей вошли')} как преподаватель, но AD этого не подтвердил — проверьте и подтвердите статус
|
||||
</span>
|
||||
<ArrowRight className="size-4" />
|
||||
</Link>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-2 gap-3 sm:gap-4 xl:grid-cols-4">
|
||||
<KpiTile label="Активные пользователи" icon={Users} {...k.activeUsers} hint="Уникальные пользователи, совершившие хотя бы одно действие" />
|
||||
<KpiTile label="Входы в систему" icon={LogIn} {...k.logins} />
|
||||
<KpiTile label="Скачивания" icon={Download} {...k.downloads} />
|
||||
<KpiTile label="Чтение онлайн" icon={BookOpen} {...k.reads} />
|
||||
<KpiTile label="Просмотры карточек" icon={Eye} {...k.views} />
|
||||
<KpiTile label="Поисковые запросы" icon={Search} {...k.searches} />
|
||||
<KpiTile label="Новые пользователи" icon={UserPlus} {...k.newUsers} hint="Первый вход через AD" />
|
||||
<KpiTile label="Неудачные входы" icon={ShieldAlert} {...k.failedLogins} inverse />
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 xl:grid-cols-3">
|
||||
<ChartCard title="Использование фонда" subtitle="Просмотры, чтение и скачивания по дням" className="xl:col-span-2">
|
||||
<TimelineChart data={data.timeline} series={ACTIVITY} />
|
||||
</ChartCard>
|
||||
<ChartCard title="Уникальные пользователи" subtitle="Сколько человек пользовались библиотекой каждый день">
|
||||
<TimelineChart data={data.timeline} series={[{ key: 'users', label: 'Пользователи', color: 'var(--series-4)' }]} />
|
||||
</ChartCard>
|
||||
</div>
|
||||
|
||||
<ChartCard title="Студенты и преподаватели" subtitle="Активность по типу пользователя за период" className="mt-4">
|
||||
<Audience rows={data.audience} />
|
||||
</ChartCard>
|
||||
|
||||
<div className="mt-4 grid gap-4 lg:grid-cols-2">
|
||||
<ChartCard title="Самые скачиваемые" subtitle="Топ-10 изданий за период">
|
||||
<TopBooks items={data.topDownloads} />
|
||||
</ChartCard>
|
||||
<ChartCard title="Самые читаемые онлайн" subtitle="Открытия во встроенной читалке">
|
||||
<TopBooks items={data.topReads} />
|
||||
</ChartCard>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 lg:grid-cols-2">
|
||||
<ChartCard title="Скачивания по подразделениям" subtitle="Факультет / отдел из Active Directory">
|
||||
<BarList items={data.departments} valueLabel="скачиваний" getSub={(x) => `${fmtNum(x.users)} чел.`} />
|
||||
</ChartCard>
|
||||
<ChartCard title="Скачивания по разделам">
|
||||
<BarList items={data.categories} getDot={(x) => x.color} valueLabel="скачиваний" />
|
||||
</ChartCard>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 xl:grid-cols-3">
|
||||
<ChartCard title="Когда пользуются библиотекой" subtitle="Активность по дням недели и часам" className="xl:col-span-2">
|
||||
<Heatmap data={data.heatmap} />
|
||||
</ChartCard>
|
||||
<ChartCard
|
||||
title="Устройства и браузеры"
|
||||
actions={
|
||||
<Segmented
|
||||
value={tech}
|
||||
onChange={setTech}
|
||||
options={[
|
||||
{ value: 'devices', label: 'Тип' },
|
||||
{ value: 'browsers', label: 'Браузер' },
|
||||
{ value: 'os', label: 'ОС' },
|
||||
]}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<BarList items={data[tech]} valueLabel="действий" />
|
||||
</ChartCard>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 lg:grid-cols-2">
|
||||
<ChartCard title="Что ищут" subtitle="Популярные поисковые запросы">
|
||||
<BarList items={data.topSearches} getLabel={(x) => x.query} getHref={(x) => `/catalog?q=${encodeURIComponent(x.query)}`} valueLabel="раз" />
|
||||
</ChartCard>
|
||||
<ChartCard
|
||||
title={
|
||||
<span className="flex items-center gap-2">
|
||||
<SearchX className="size-4 text-amber-500" /> Ищут, но не находят
|
||||
</span>
|
||||
}
|
||||
subtitle="Запросы без результатов — подсказка, что докупить или оцифровать"
|
||||
>
|
||||
<BarList items={data.zeroSearches} getLabel={(x) => x.query} valueLabel="раз" empty="Все запросы находили результаты 🎉" />
|
||||
</ChartCard>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 lg:grid-cols-2">
|
||||
<ChartCard title="Самые активные читатели" subtitle="По числу скачиваний">
|
||||
<BarList
|
||||
items={data.topUsers}
|
||||
getLabel={(x) => x.displayName}
|
||||
getSub={(x) => x.department || x.username}
|
||||
getHref={(x) => `/admin/users/${x.id}`}
|
||||
valueLabel="скачиваний"
|
||||
/>
|
||||
</ChartCard>
|
||||
<ChartCard
|
||||
title={
|
||||
<span className="flex items-center gap-2">
|
||||
<AlertTriangle className="size-4 text-rose-500" /> Неудачные попытки входа
|
||||
</span>
|
||||
}
|
||||
subtitle="Последние 10 — для контроля безопасности"
|
||||
actions={
|
||||
<Link to="/admin/activity?type=LOGIN_FAILED" className="text-xs font-medium text-brand-600 dark:text-brand-300">
|
||||
Все →
|
||||
</Link>
|
||||
}
|
||||
>
|
||||
{data.failedLogins.length ? (
|
||||
<div className="divide-y divide-line text-sm">
|
||||
{data.failedLogins.map((e) => (
|
||||
<div key={e.id} className="flex items-center justify-between gap-3 py-2">
|
||||
<div className="min-w-0">
|
||||
<div className="truncate font-medium">{e.meta?.username || '—'}</div>
|
||||
<div className="text-xs text-muted">{reasonLabel(e.meta?.reason)} · {e.browser}, {e.os}</div>
|
||||
</div>
|
||||
<div className="shrink-0 text-right text-xs text-muted tnum">
|
||||
<div className="font-mono">{e.ip}</div>
|
||||
<div>{fmtDateTime(e.createdAt)}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="py-10 text-center text-sm text-subtle">Нет неудачных попыток</div>
|
||||
)}
|
||||
</ChartCard>
|
||||
</div>
|
||||
|
||||
<Modal open={onlineOpen} onClose={() => setOnlineOpen(false)} title="Сейчас на сайте" size="sm">
|
||||
{!online.data ? (
|
||||
<PageLoader />
|
||||
) : online.data.items.length ? (
|
||||
<div className="divide-y divide-line">
|
||||
{online.data.items.map((u) => (
|
||||
<Link key={u.id} to={`/admin/users/${u.id}`} className="flex items-center gap-3 py-2.5 hover:opacity-80">
|
||||
<Avatar name={u.displayName} size={34} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-medium">{u.displayName}</div>
|
||||
<div className="truncate text-xs text-muted">{u.department || u.username}</div>
|
||||
</div>
|
||||
<span className="text-xs text-subtle">{timeAgo(u.lastSeenAt)}</span>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<div className="py-8 text-center text-sm text-muted">Никого нет онлайн</div>
|
||||
)}
|
||||
</Modal>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const reasonLabel = (r) =>
|
||||
({
|
||||
bad_credentials: 'Неверный логин/пароль',
|
||||
bad_password: 'Неверный пароль',
|
||||
unknown_user: 'Неизвестный пользователь',
|
||||
blocked: 'Заблокирован',
|
||||
not_in_allowed_group: 'Нет в разрешённых группах',
|
||||
ldap_unavailable: 'AD недоступен',
|
||||
local_disabled: 'Локальный вход отключён',
|
||||
})[r] || r || 'Ошибка';
|
||||
|
||||
function TopBooks({ items }) {
|
||||
if (!items.length) return <div className="py-10 text-center text-sm text-subtle">Нет данных за период</div>;
|
||||
const max = Math.max(...items.map((x) => x.count));
|
||||
return (
|
||||
<ol className="space-y-2.5">
|
||||
{items.map((b, i) => (
|
||||
<li key={b.id}>
|
||||
<Link to={`/books/${b.id}`} className="group flex items-center gap-3" title={`${b.title}: ${fmtNum(b.count)}`}>
|
||||
<span className="w-4 shrink-0 text-right text-xs text-subtle tnum">{i + 1}</span>
|
||||
<BookCover book={b} size="sm" className="w-8 shrink-0 !rounded" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex items-baseline justify-between gap-3">
|
||||
<span className="truncate text-sm text-ink group-hover:text-brand-600 dark:group-hover:text-brand-300">{b.title}</span>
|
||||
<span className="shrink-0 text-sm font-semibold tnum">{fmtNum(b.count)}</span>
|
||||
</div>
|
||||
<div className="mt-1 h-1.5 overflow-hidden rounded-full bg-surface-2">
|
||||
<div className="h-full rounded-full" style={{ width: `${(b.count / max) * 100}%`, background: 'var(--series-1)' }} />
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
|
||||
const AUD = {
|
||||
STUDENT: ['Студенты', GraduationCap],
|
||||
TEACHER: ['Преподаватели', Presentation],
|
||||
STAFF: ['Сотрудники', Briefcase],
|
||||
};
|
||||
|
||||
/** Таблица аудитории: несколько показателей на три группы — таблица читается лучше графика */
|
||||
function Audience({ rows }) {
|
||||
const cols = [
|
||||
['LOGIN', 'Входы'],
|
||||
['VIEW', 'Просмотры'],
|
||||
['READ', 'Чтение'],
|
||||
['DOWNLOAD', 'Скачивания'],
|
||||
];
|
||||
return (
|
||||
<div className="-mx-5 overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="text-xs text-muted">
|
||||
<tr className="border-b border-line">
|
||||
<th className="px-5 py-2 text-left font-medium">Кто</th>
|
||||
<th className="px-3 py-2 text-left font-medium">Активны за период</th>
|
||||
{cols.map(([, l]) => <th key={l} className="px-3 py-2 text-right font-medium">{l}</th>)}
|
||||
<th className="px-5 py-2 text-right font-medium">Скачиваний на активного</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-line">
|
||||
{rows.map((r) => {
|
||||
const [label, Icon] = AUD[r.kind];
|
||||
const share = r.users ? r.active / r.users : 0;
|
||||
return (
|
||||
<tr key={r.kind} className="hover:bg-surface-2/60">
|
||||
<td className="px-5 py-3">
|
||||
<Link to={`/admin/activity?kind=${r.kind}`} className="flex items-center gap-2 font-medium hover:text-brand-600 dark:hover:text-brand-300">
|
||||
<Icon className="size-4 text-subtle" /> {label}
|
||||
</Link>
|
||||
</td>
|
||||
<td className="px-3 py-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="h-2 w-24 overflow-hidden rounded-full bg-surface-2">
|
||||
<div className="h-full rounded-full bg-[var(--series-1)]" style={{ width: `${Math.round(share * 100)}%` }} />
|
||||
</div>
|
||||
<span className="text-xs text-muted tnum">
|
||||
<b className="text-ink">{fmtNum(r.active)}</b> из {fmtNum(r.users)} · {Math.round(share * 100)}%
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
{cols.map(([k]) => <td key={k} className="px-3 py-3 text-right tnum">{fmtNum(r[k])}</td>)}
|
||||
<td className="px-5 py-3 text-right font-semibold tnum">{r.active ? (r.DOWNLOAD / r.active).toFixed(1).replace('.', ',') : '—'}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import clsx from 'clsx';
|
||||
import { ArrowLeft, CheckCircle2, Download, FileSpreadsheet, Info, RotateCcw, UploadCloud, UserPlus, Users } from 'lucide-react';
|
||||
import { api, upload } from '../../lib/api';
|
||||
import { useAuth } from '../../lib/auth';
|
||||
import { KIND_LABELS, plural } from '../../lib/format';
|
||||
import { Badge, Button, Segmented, Spinner } from '../../components/ui';
|
||||
import { PageHeader } from '../../layouts/AdminLayout';
|
||||
import Credentials from '../../components/Credentials';
|
||||
|
||||
const FIELDS = [
|
||||
['fio', 'ФИО полностью'],
|
||||
['lastName', 'Фамилия'],
|
||||
['firstName', 'Имя'],
|
||||
['middleName', 'Отчество'],
|
||||
['group', 'Группа'],
|
||||
['course', 'Курс'],
|
||||
['kind', 'Тип (студент / преподаватель)'],
|
||||
['email', 'E-mail'],
|
||||
['employeeId', 'ID / № зачётки'],
|
||||
['department', 'Факультет / кафедра'],
|
||||
];
|
||||
const STATUS = {
|
||||
new: ['Будет создан', 'green'],
|
||||
exists: ['Уже есть', 'gray'],
|
||||
duplicate: ['Повтор в файле', 'amber'],
|
||||
error: ['Ошибка', 'red'],
|
||||
};
|
||||
|
||||
/**
|
||||
* Импорт пользователей без Active Directory: файл → сопоставление столбцов → проверка → создание.
|
||||
* Логины генерируются из ФИО (ivanov.ab), пароли — случайные, при первом входе их меняют.
|
||||
*/
|
||||
export default function ImportUsers() {
|
||||
const { org } = useAuth();
|
||||
const [step, setStep] = useState('file'); // file | map | done
|
||||
const [file, setFile] = useState(null);
|
||||
const [table, setTable] = useState(null);
|
||||
const [colField, setColField] = useState([]); // столбец → поле
|
||||
const [defaultKind, setDefaultKind] = useState('STUDENT');
|
||||
const [check, setCheck] = useState(null);
|
||||
const [filter, setFilter] = useState('all');
|
||||
const [busy, setBusy] = useState(null);
|
||||
const [error, setError] = useState('');
|
||||
const [result, setResult] = useState(null);
|
||||
const [over, setOver] = useState(false);
|
||||
const fileRef = useRef();
|
||||
|
||||
const reset = () => {
|
||||
setStep('file');
|
||||
setFile(null);
|
||||
setTable(null);
|
||||
setCheck(null);
|
||||
setResult(null);
|
||||
setError('');
|
||||
};
|
||||
|
||||
const readFile = async (f) => {
|
||||
setError('');
|
||||
setFile(f);
|
||||
setBusy('read');
|
||||
const fd = new FormData();
|
||||
fd.append('file', f);
|
||||
try {
|
||||
const t = await upload('/org/import/preview', 'POST', fd);
|
||||
const cols = Array(t.headers.length).fill('');
|
||||
for (const [field, col] of Object.entries(t.mapping)) cols[col] = field;
|
||||
setTable(t);
|
||||
setColField(cols);
|
||||
setStep('map');
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
// строки файла → объекты по выбранным столбцам
|
||||
const rows = useMemo(() => {
|
||||
if (!table) return [];
|
||||
return table.rows.map((r) => Object.fromEntries(colField.map((f, i) => [f, r[i]]).filter(([f]) => f)));
|
||||
}, [table, colField]);
|
||||
const hasName = colField.includes('fio') || (colField.includes('lastName') && colField.includes('firstName'));
|
||||
|
||||
// проверка «на сухую» при каждом изменении сопоставления
|
||||
useEffect(() => {
|
||||
if (step !== 'map' || !hasName) return setCheck(null);
|
||||
const t = setTimeout(async () => {
|
||||
setBusy('check');
|
||||
try {
|
||||
setCheck(await api('/org/import/commit', { method: 'POST', body: { rows, defaultKind, dryRun: true } }));
|
||||
setError('');
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
}, 300);
|
||||
return () => clearTimeout(t);
|
||||
}, [rows, defaultKind, step, hasName]);
|
||||
|
||||
const commit = async () => {
|
||||
setBusy('commit');
|
||||
setError('');
|
||||
try {
|
||||
const d = await api('/org/import/commit', { method: 'POST', body: { rows, defaultKind, dryRun: false, fileName: file?.name } });
|
||||
setResult(d);
|
||||
setStep('done');
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
const setCol = (i, field) =>
|
||||
setColField((cols) => cols.map((f, j) => (j === i ? field : field && f === field ? '' : f))); // одно поле — один столбец
|
||||
|
||||
const s = check?.summary;
|
||||
const list = (check?.results || []).filter((x) => filter === 'all' || x.status === filter);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Link to="/admin/users" className="mb-3 inline-flex items-center gap-1.5 text-sm text-muted hover:text-ink">
|
||||
<ArrowLeft className="size-4" /> Пользователи
|
||||
</Link>
|
||||
<PageHeader
|
||||
title="Загрузка списка пользователей"
|
||||
subtitle="Для студентов и преподавателей без учётной записи Active Directory — система сама выдаст логины и пароли"
|
||||
actions={step !== 'file' && <Button variant="secondary" icon={RotateCcw} onClick={reset}>Другой файл</Button>}
|
||||
/>
|
||||
|
||||
<Steps step={step} />
|
||||
{error && <div className="mb-4 rounded-xl bg-rose-50 p-3 text-sm text-rose-700 dark:bg-rose-500/10 dark:text-rose-300">{error}</div>}
|
||||
|
||||
{step === 'file' && (
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
<div className="card p-6 lg:col-span-2">
|
||||
<div
|
||||
onClick={() => fileRef.current.click()}
|
||||
onDragOver={(e) => { e.preventDefault(); setOver(true); }}
|
||||
onDragLeave={() => setOver(false)}
|
||||
onDrop={(e) => { e.preventDefault(); setOver(false); e.dataTransfer.files[0] && readFile(e.dataTransfer.files[0]); }}
|
||||
className={clsx(
|
||||
'flex cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed p-12 text-center transition',
|
||||
over ? 'border-brand-500 bg-brand-50 dark:bg-brand-500/10' : 'border-line hover:border-brand-400 hover:bg-surface-2'
|
||||
)}
|
||||
>
|
||||
<input ref={fileRef} type="file" accept=".xlsx,.csv" hidden onChange={(e) => e.target.files[0] && readFile(e.target.files[0])} />
|
||||
{busy === 'read' ? <Spinner className="mb-3 size-10" /> : <UploadCloud className="mb-3 size-10 text-brand-500" />}
|
||||
<div className="font-semibold">{busy === 'read' ? 'Читаю файл…' : 'Перетащите файл Excel или CSV'}</div>
|
||||
<div className="mt-1 text-sm text-muted">или нажмите, чтобы выбрать · до 5000 строк</div>
|
||||
</div>
|
||||
<div className="mt-5 flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-3 text-sm">
|
||||
<span className="text-muted">Если в файле нет столбца «Тип», это:</span>
|
||||
<Segmented value={defaultKind} onChange={setDefaultKind} options={[{ value: 'STUDENT', label: 'Студенты' }, { value: 'TEACHER', label: 'Преподаватели' }, { value: 'STAFF', label: 'Сотрудники' }]} />
|
||||
</div>
|
||||
<a href="/api/org/import/template.xlsx">
|
||||
<Button variant="ghost" icon={Download}>Скачать шаблон</Button>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<div className="card space-y-3 p-6 text-sm">
|
||||
<div className="flex items-center gap-2 font-semibold"><Info className="size-4 text-brand-500" />Что должно быть в файле</div>
|
||||
<ul className="list-disc space-y-1.5 pl-5 text-muted">
|
||||
<li><b className="text-ink">ФИО</b> — одним столбцом или «Фамилия», «Имя», «Отчество».</li>
|
||||
<li><b className="text-ink">Группа</b> — студенты увидят списки литературы своей группы.</li>
|
||||
<li>Курс, e-mail, факультет, номер зачётки — по желанию. Курс считается сам по году в названии группы.</li>
|
||||
<li>Подойдёт выгрузка из HEMIS или ведомость: строку заголовков система найдёт сама.</li>
|
||||
</ul>
|
||||
<div className="rounded-xl bg-surface-2 p-3 text-xs text-muted">
|
||||
Логин: <b className="font-mono text-ink">Иванов Алишер Бахтиёрович → ivanov.ab</b>. Пароль — случайный, при первом входе пользователь придумает свой.
|
||||
Повторная загрузка того же списка не создаёт дублей.
|
||||
</div>
|
||||
{org.ldapEnabled && (
|
||||
<div className="rounded-xl bg-sky-50 p-3 text-xs text-sky-800 dark:bg-sky-500/10 dark:text-sky-200">
|
||||
У вас включён вход через Active Directory: пользователи домена появляются сами при первом входе. Загружайте только тех, у кого нет учётной записи в AD.
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'map' && table && (
|
||||
<>
|
||||
<div className="card mb-4 p-5">
|
||||
<div className="mb-1 flex flex-wrap items-center gap-2 font-semibold">
|
||||
<FileSpreadsheet className="size-5 text-emerald-500" /> {file?.name}
|
||||
<span className="text-sm font-normal text-muted">· {table.rows.length} {plural(table.rows.length, 'строка', 'строки', 'строк')}</span>
|
||||
</div>
|
||||
<p className="mb-4 text-sm text-muted">
|
||||
{table.headerFound ? 'Столбцы распознаны автоматически — проверьте и при необходимости поправьте.' : 'Строка заголовков не найдена — укажите, что в каком столбце.'}
|
||||
</p>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
{table.headers.map((h, i) => (
|
||||
<th key={i} className="min-w-40 px-2 pb-2 text-left align-bottom font-normal">
|
||||
<div className="mb-1 truncate text-xs text-muted" title={h}>{h}</div>
|
||||
<select className={clsx('input h-9 text-xs', colField[i] && 'border-brand-400 font-medium')} value={colField[i]} onChange={(e) => setCol(i, e.target.value)}>
|
||||
<option value="">— не загружать —</option>
|
||||
{FIELDS.map(([v, l]) => <option key={v} value={v}>{l}</option>)}
|
||||
</select>
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-line">
|
||||
{table.rows.slice(0, 4).map((r, j) => (
|
||||
<tr key={j}>
|
||||
{r.map((c, i) => <td key={i} className={clsx('truncate px-2 py-1.5', !colField[i] && 'text-subtle')}>{c}</td>)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="mt-4 flex items-center gap-3 text-sm">
|
||||
<span className="text-muted">Тип по умолчанию:</span>
|
||||
<Segmented value={defaultKind} onChange={setDefaultKind} options={[{ value: 'STUDENT', label: 'Студенты' }, { value: 'TEACHER', label: 'Преподаватели' }, { value: 'STAFF', label: 'Сотрудники' }]} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{!hasName && <div className="card p-6 text-center text-sm text-muted">Укажите столбец с ФИО (или «Фамилия» и «Имя»).</div>}
|
||||
{hasName && (
|
||||
<div className="card p-5">
|
||||
<div className="mb-4 flex flex-wrap items-center gap-2">
|
||||
<Segmented
|
||||
value={filter}
|
||||
onChange={setFilter}
|
||||
options={[
|
||||
{ value: 'all', label: `Все ${s?.total ?? ''}` },
|
||||
{ value: 'new', label: `Новые ${s?.new ?? ''}` },
|
||||
{ value: 'exists', label: `Уже есть ${s?.exists ?? ''}` },
|
||||
...(s?.duplicate ? [{ value: 'duplicate', label: `Повторы ${s.duplicate}` }] : []),
|
||||
...(s?.error ? [{ value: 'error', label: `Ошибки ${s.error}` }] : []),
|
||||
]}
|
||||
/>
|
||||
{busy === 'check' && <Spinner className="size-5" />}
|
||||
<Button className="ml-auto" icon={UserPlus} loading={busy === 'commit'} disabled={!s?.new || busy === 'check'} onClick={commit}>
|
||||
Создать {s?.new || 0} {plural(s?.new || 0, 'учётную запись', 'учётные записи', 'учётных записей')}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="max-h-[480px] overflow-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="sticky top-0 bg-surface">
|
||||
<tr className="border-b border-line text-left text-xs text-muted">
|
||||
<th className="px-2 py-2 font-medium">№</th>
|
||||
<th className="px-2 py-2 font-medium">ФИО</th>
|
||||
<th className="px-2 py-2 font-medium">Тип</th>
|
||||
<th className="px-2 py-2 font-medium">Группа</th>
|
||||
<th className="px-2 py-2 font-medium">Курс</th>
|
||||
<th className="px-2 py-2 font-medium">Логин</th>
|
||||
<th className="px-2 py-2 font-medium">Статус</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-line">
|
||||
{list.slice(0, 1000).map((x) => (
|
||||
<tr key={x.row} className={clsx(x.status === 'error' && 'bg-rose-50/50 dark:bg-rose-500/5')}>
|
||||
<td className="px-2 py-1.5 text-subtle tnum">{x.row}</td>
|
||||
<td className="px-2 py-1.5">{x.displayName || <span className="text-subtle">—</span>}</td>
|
||||
<td className="px-2 py-1.5 text-muted">{KIND_LABELS[x.kind]}</td>
|
||||
<td className="px-2 py-1.5">{x.studyGroup || <span className="text-subtle">—</span>}</td>
|
||||
<td className="px-2 py-1.5 tnum">{x.course || ''}</td>
|
||||
<td className="px-2 py-1.5 font-mono text-xs">{x.username}</td>
|
||||
<td className="px-2 py-1.5">
|
||||
<Badge color={STATUS[x.status][1]}>{STATUS[x.status][0]}</Badge>
|
||||
{x.status === 'error' && <span className="ml-2 text-xs text-rose-600">{x.message}</span>}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{step === 'done' && result && (
|
||||
<>
|
||||
<div className="card mb-6 flex flex-wrap items-center gap-4 p-5">
|
||||
<div className="flex size-12 items-center justify-center rounded-2xl bg-emerald-50 text-emerald-600 dark:bg-emerald-500/15 dark:text-emerald-300">
|
||||
<CheckCircle2 className="size-6" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<div className="text-lg font-semibold">
|
||||
Создано {result.summary.created} {plural(result.summary.created, 'учётная запись', 'учётные записи', 'учётных записей')}
|
||||
</div>
|
||||
<div className="text-sm text-muted">
|
||||
{result.summary.exists > 0 && `${result.summary.exists} уже были в системе. `}
|
||||
{result.summary.error > 0 && `${result.summary.error} ${plural(result.summary.error, 'строка с ошибкой пропущена', 'строки с ошибками пропущены', 'строк с ошибками пропущено')}.`}
|
||||
</div>
|
||||
</div>
|
||||
<Link to="/admin/users"><Button variant="secondary" icon={Users}>К пользователям</Button></Link>
|
||||
</div>
|
||||
<Credentials items={result.credentials} />
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Steps({ step }) {
|
||||
const all = [['file', 'Файл'], ['map', 'Проверка'], ['done', 'Логины и пароли']];
|
||||
const idx = all.findIndex(([k]) => k === step);
|
||||
return (
|
||||
<div className="mb-6 flex items-center gap-2 text-sm">
|
||||
{all.map(([k, l], i) => (
|
||||
<div key={k} className="flex items-center gap-2">
|
||||
{i > 0 && <div className="h-px w-6 bg-line sm:w-10" />}
|
||||
<span className={clsx('flex size-6 items-center justify-center rounded-full text-xs font-semibold', i <= idx ? 'bg-brand-600 text-white' : 'bg-surface-2 text-muted')}>{i + 1}</span>
|
||||
<span className={clsx(i === idx ? 'font-medium' : 'text-muted')}>{l}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { BadgeCheck, BookOpen, Check, CheckCircle2, Clock, Download, GraduationCap, Inbox, X, XCircle } from 'lucide-react';
|
||||
import { api, qs, useApi } from '../../lib/api';
|
||||
import { BOOK_TYPES, KIND_LABELS, READABLE, SUBMISSION_STATUS, fmtDateTime, fmtSize, timeAgo } from '../../lib/format';
|
||||
import { Avatar, Badge, Button, Empty, ErrorBox, Modal, PageLoader, Pagination, Segmented, useToast } from '../../components/ui';
|
||||
import BookCover from '../../components/BookCover';
|
||||
import { PageHeader } from '../../layouts/AdminLayout';
|
||||
|
||||
const QUICK_REASONS = [
|
||||
'Оформление не соответствует требованиям (ГОСТ, список литературы).',
|
||||
'Низкая оригинальность текста — оформите заимствования ссылками.',
|
||||
'Аннотация не раскрывает содержание работы.',
|
||||
'Файл повреждён или не открывается — загрузите PDF.',
|
||||
'Укажите научного руководителя.',
|
||||
];
|
||||
|
||||
export default function Moderation() {
|
||||
const toast = useToast();
|
||||
const [status, setStatus] = useState('PENDING');
|
||||
const [page, setPage] = useState(1);
|
||||
const { data, error, loading, reload } = useApi('/submissions' + qs({ status, page }));
|
||||
const cats = useApi('/categories');
|
||||
const [rejecting, setRejecting] = useState(null);
|
||||
const [note, setNote] = useState('');
|
||||
const [busy, setBusy] = useState(null);
|
||||
|
||||
const review = async (item, action, extra = {}) => {
|
||||
setBusy(item.id);
|
||||
try {
|
||||
await api(`/submissions/${item.id}/review`, { method: 'POST', body: { action, ...extra } });
|
||||
toast(action === 'approve' ? 'Работа опубликована' : 'Работа возвращена на доработку');
|
||||
setRejecting(null);
|
||||
setNote('');
|
||||
reload();
|
||||
window.dispatchEvent(new Event('elib:moderation'));
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
const c = data?.counts || {};
|
||||
return (
|
||||
<>
|
||||
<PageHeader title="Модерация публикаций" subtitle="Работы студентов и сотрудников, отправленные на публикацию в библиотеке" />
|
||||
|
||||
<Segmented
|
||||
className="mb-5"
|
||||
value={status}
|
||||
onChange={(v) => { setStatus(v); setPage(1); }}
|
||||
options={[
|
||||
{ value: 'PENDING', label: `На проверке${c.PENDING ? ` · ${c.PENDING}` : ''}`, icon: Clock },
|
||||
{ value: 'PUBLISHED', label: `Опубликованные${c.PUBLISHED ? ` · ${c.PUBLISHED}` : ''}`, icon: CheckCircle2 },
|
||||
{ value: 'REJECTED', label: `На доработке${c.REJECTED ? ` · ${c.REJECTED}` : ''}`, icon: XCircle },
|
||||
]}
|
||||
/>
|
||||
|
||||
{error && <ErrorBox error={error} onRetry={reload} />}
|
||||
{loading && !data && <PageLoader />}
|
||||
{data && !data.items.length && (
|
||||
<div className="card">
|
||||
<Empty icon={Inbox} title={status === 'PENDING' ? 'Очередь пуста' : 'Нет работ'} text={status === 'PENDING' ? 'Все отправленные работы проверены 🎉' : undefined} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{data?.items.map((b) => (
|
||||
<div key={b.id} className="card p-5">
|
||||
<div className="flex flex-col gap-5 sm:flex-row">
|
||||
<BookCover book={b} className="w-28 shrink-0 self-start" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge color={SUBMISSION_STATUS[b.status].color}>{SUBMISSION_STATUS[b.status].label}</Badge>
|
||||
<Badge>{BOOK_TYPES[b.type] || b.type}</Badge>
|
||||
{b.createdBy?.kind === 'TEACHER' && <Badge color="violet">Материал преподавателя</Badge>}
|
||||
{b.endorsedAt && <Badge color="violet"><BadgeCheck className="size-3" />Руководитель подтвердил</Badge>}
|
||||
{b.category && (
|
||||
<span className="flex items-center gap-1.5 text-xs text-muted"><span className="size-2 rounded-full" style={{ background: b.category.color }} />{b.category.name}</span>
|
||||
)}
|
||||
<span className="ml-auto text-xs text-subtle" title={fmtDateTime(b.submittedAt)}>отправлено {timeAgo(b.submittedAt)}</span>
|
||||
</div>
|
||||
<Link to={`/books/${b.id}`} className="mt-2 block text-lg font-semibold hover:text-brand-600 dark:hover:text-brand-300">{b.title}</Link>
|
||||
{b.subtitle && <div className="text-sm text-muted">{b.subtitle}</div>}
|
||||
<div className="mt-1 text-sm">
|
||||
<span className="font-medium">{b.authors}</span>
|
||||
{b.supervisor && <span className="text-muted"> · научный руководитель: {b.supervisor}{b.supervisorRef ? ' ✓' : ''}</span>}
|
||||
</div>
|
||||
|
||||
{b.createdBy && (
|
||||
<Link to={`/admin/users/${b.createdBy.id}`} className="mt-3 inline-flex items-center gap-2 rounded-xl bg-surface-2 py-1.5 pr-3 pl-1.5 text-xs hover:opacity-80">
|
||||
<Avatar name={b.createdBy.displayName} size={24} />
|
||||
<span>
|
||||
Загрузил(а): <b>{b.createdBy.displayName}</b> ({b.createdBy.username}) · {KIND_LABELS[b.createdBy.kind]}{b.createdBy.studyGroup && `, ${b.createdBy.studyGroup}`}{b.createdBy.department && ` · ${b.createdBy.department}`}
|
||||
</span>
|
||||
</Link>
|
||||
)}
|
||||
|
||||
<p className="mt-3 line-clamp-4 text-sm leading-relaxed text-muted">{b.description}</p>
|
||||
{b.keywords && <div className="mt-2 text-xs text-subtle">Ключевые слова: {b.keywords}</div>}
|
||||
|
||||
{b.reviewNote && (
|
||||
<div className="mt-3 rounded-xl bg-rose-50 p-3 text-sm text-rose-800 dark:bg-rose-500/10 dark:text-rose-200">
|
||||
<b>Комментарий{b.reviewedBy ? ` (${b.reviewedBy.displayName})` : ''}:</b> {b.reviewNote}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-4 flex flex-wrap items-center gap-2">
|
||||
{READABLE.includes(b.fileExt) && (
|
||||
<Link to={`/read/${b.id}`} target="_blank"><Button size="sm" variant="secondary" icon={BookOpen}>Открыть</Button></Link>
|
||||
)}
|
||||
<a href={`/api/books/${b.id}/download`}>
|
||||
<Button size="sm" variant="secondary" icon={Download}>{b.fileExt?.toUpperCase()} · {fmtSize(b.fileSize)}</Button>
|
||||
</a>
|
||||
<div className="ml-auto flex flex-wrap items-center gap-2">
|
||||
{b.status !== 'PUBLISHED' && (
|
||||
<>
|
||||
{!b.category && (
|
||||
<select id={`cat-${b.id}`} className="input h-8 w-auto text-xs" defaultValue="">
|
||||
<option value="">Раздел…</option>
|
||||
{cats.data?.items.map((x) => <option key={x.id} value={x.id}>{x.name}</option>)}
|
||||
</select>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
icon={Check}
|
||||
loading={busy === b.id}
|
||||
className="!bg-emerald-600 hover:!bg-emerald-700"
|
||||
onClick={() => {
|
||||
const sel = document.getElementById(`cat-${b.id}`);
|
||||
review(b, 'approve', sel?.value ? { categoryId: sel.value } : {});
|
||||
}}
|
||||
>
|
||||
Опубликовать
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{b.status !== 'REJECTED' && (
|
||||
<Button size="sm" variant="secondary" icon={X} onClick={() => { setRejecting(b); setNote(''); }} className="hover:!text-rose-600">
|
||||
{b.status === 'PUBLISHED' ? 'Снять с публикации' : 'На доработку'}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-6"><Pagination page={page} pages={data?.pages} onChange={setPage} /></div>
|
||||
|
||||
<Modal
|
||||
open={!!rejecting}
|
||||
onClose={() => setRejecting(null)}
|
||||
title="Вернуть на доработку"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setRejecting(null)}>Отмена</Button>
|
||||
<Button variant="danger" loading={busy === rejecting?.id} disabled={!note.trim()} onClick={() => review(rejecting, 'reject', { note })}>Отправить автору</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<p className="mb-3 text-sm text-muted">
|
||||
Автор «<b className="text-ink">{rejecting?.title}</b>» увидит этот комментарий и сможет исправить работу.
|
||||
</p>
|
||||
<div className="mb-3 flex flex-wrap gap-1.5">
|
||||
{QUICK_REASONS.map((r) => (
|
||||
<button key={r} type="button" onClick={() => setNote((n) => (n ? n + ' ' : '') + r)} className="rounded-full border border-line px-2.5 py-1 text-left text-xs text-muted hover:text-ink">
|
||||
+ {r}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<textarea className="input h-28 py-2" value={note} onChange={(e) => setNote(e.target.value)} placeholder="Что нужно исправить…" autoFocus />
|
||||
<div className="mt-2 flex items-center gap-1.5 text-xs text-subtle"><GraduationCap className="size-3.5" />Пишите конкретно и доброжелательно — это помогает студентам.</div>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link, useSearchParams } from 'react-router-dom';
|
||||
import clsx from 'clsx';
|
||||
import {
|
||||
Building2, CheckCircle2, ChevronDown, Circle, Clock, Copy, Database, ImagePlus, Info, KeyRound, Network, PlugZap, Save,
|
||||
Server, ShieldCheck, Trash2, Upload, UserCheck, XCircle,
|
||||
} from 'lucide-react';
|
||||
import { api, upload, useApi } from '../../lib/api';
|
||||
import { useAuth } from '../../lib/auth';
|
||||
import { KIND_LABELS, ROLE_LABELS, fmtNum } from '../../lib/format';
|
||||
import { Badge, Button, ErrorBox, Modal, PageLoader, Segmented, Switch, useToast } from '../../components/ui';
|
||||
import { PageHeader } from '../../layouts/AdminLayout';
|
||||
|
||||
const TABS = [
|
||||
{ value: 'profile', label: 'Организация', icon: Building2 },
|
||||
{ value: 'ldap', label: 'Active Directory', icon: KeyRound },
|
||||
{ value: 'server', label: 'Сервер', icon: Server },
|
||||
];
|
||||
|
||||
export default function Settings() {
|
||||
const [sp, setSp] = useSearchParams();
|
||||
const tab = TABS.some((t) => t.value === sp.get('tab')) ? sp.get('tab') : 'profile';
|
||||
const { data, error, reload, setData } = useApi('/org/settings');
|
||||
if (error) return <ErrorBox error={error} onRetry={reload} />;
|
||||
if (!data) return <PageLoader />;
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader title="Настройки библиотеки" subtitle="Профиль организации, вход через Active Directory и учётные записи" />
|
||||
<Checklist data={data} onTab={(t) => setSp({ tab: t })} />
|
||||
<Segmented className="mb-6" value={tab} onChange={(t) => setSp({ tab: t })} options={TABS} />
|
||||
{tab === 'profile' && <Profile data={data} onSaved={setData} />}
|
||||
{tab === 'ldap' && <Ldap data={data} onSaved={setData} />}
|
||||
{tab === 'server' && <ServerInfo />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Первые шаги после регистрации — пока библиотека не готова */
|
||||
function Checklist({ data, onTab }) {
|
||||
const { org, ldap, counts } = data;
|
||||
const steps = [
|
||||
[!!org.logoUrl, 'Загрузите логотип', 'Его увидят на странице входа и в шапке', () => onTab('profile')],
|
||||
[ldap.enabled || counts.users > 1, 'Подключите пользователей', 'Active Directory или загрузка списка студентов из Excel', null],
|
||||
[org.status === 'ACTIVE', 'Одобрение платформой', org.status === 'PENDING' ? 'Заявка на проверке — обычно до одного рабочего дня' : 'Библиотека открыта', null],
|
||||
];
|
||||
if (steps.every((s) => s[0])) return null;
|
||||
return (
|
||||
<div className="card mb-6 p-5">
|
||||
<div className="mb-4 font-semibold">Подготовка библиотеки</div>
|
||||
<div className="grid gap-3 md:grid-cols-3">
|
||||
{steps.map(([done, title, text, go], i) => (
|
||||
<div key={title} className={clsx('rounded-2xl border p-4', done ? 'border-emerald-200 bg-emerald-50/60 dark:border-emerald-500/20 dark:bg-emerald-500/5' : 'border-line')}>
|
||||
<div className="flex items-center gap-2 text-sm font-semibold">
|
||||
{done ? <CheckCircle2 className="size-5 text-emerald-500" /> : i === 2 ? <Clock className="size-5 text-amber-500" /> : <Circle className="size-5 text-subtle" />}
|
||||
{title}
|
||||
</div>
|
||||
<div className="mt-1 text-xs text-muted">{text}</div>
|
||||
{!done && i === 0 && <button onClick={go} className="mt-2 text-xs font-medium text-brand-600 hover:underline dark:text-brand-300">Открыть профиль →</button>}
|
||||
{!done && i === 1 && (
|
||||
<div className="mt-2 flex gap-3 text-xs font-medium">
|
||||
<button onClick={() => onTab('ldap')} className="text-brand-600 hover:underline dark:text-brand-300">Настроить AD</button>
|
||||
<Link to="/admin/users/import" className="text-brand-600 hover:underline dark:text-brand-300">Загрузить список</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- Профиль ----------
|
||||
function Profile({ data, onSaved }) {
|
||||
const { reloadOrg } = useAuth();
|
||||
const toast = useToast();
|
||||
const o = data.org;
|
||||
const [f, setF] = useState({
|
||||
name: o.name || '', shortName: o.shortName || '', city: o.city || '', website: o.website || '',
|
||||
contactName: o.contactName || '', contactEmail: o.contactEmail || '', contactPhone: o.contactPhone || '',
|
||||
});
|
||||
const [logo, setLogo] = useState(null);
|
||||
const [removeLogo, setRemoveLogo] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const fileRef = useRef();
|
||||
const preview = logo ? URL.createObjectURL(logo) : removeLogo ? null : o.logoUrl;
|
||||
const url = `${window.location.origin}/${o.slug}`;
|
||||
const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
|
||||
|
||||
const save = async () => {
|
||||
setError('');
|
||||
setBusy(true);
|
||||
const fd = new FormData();
|
||||
Object.entries(f).forEach(([k, v]) => fd.append(k, v));
|
||||
if (logo) fd.append('logo', logo);
|
||||
if (removeLogo) fd.append('removeLogo', 'true');
|
||||
try {
|
||||
const d = await upload('/org/settings', 'PUT', fd);
|
||||
onSaved(d);
|
||||
setLogo(null);
|
||||
setRemoveLogo(false);
|
||||
reloadOrg();
|
||||
toast('Сохранено');
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
<div className="card space-y-4 p-6 lg:col-span-2">
|
||||
{error && <div className="rounded-xl bg-rose-50 p-3 text-sm text-rose-700 dark:bg-rose-500/10 dark:text-rose-300">{error}</div>}
|
||||
<div>
|
||||
<label className="label">Полное название *</label>
|
||||
<input className="input" value={f.name} onChange={set('name')} />
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div>
|
||||
<label className="label">Краткое название (в шапке)</label>
|
||||
<input className="input" value={f.shortName} onChange={set('shortName')} placeholder="ТГЭУ" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Город</label>
|
||||
<input className="input" value={f.city} onChange={set('city')} />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Сайт</label>
|
||||
<input className="input" value={f.website} onChange={set('website')} placeholder="https://university.uz" />
|
||||
</div>
|
||||
<div className="border-t border-line pt-4 text-sm font-semibold">Ответственный за библиотеку</div>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<div>
|
||||
<label className="label">ФИО</label>
|
||||
<input className="input" value={f.contactName} onChange={set('contactName')} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">E-mail</label>
|
||||
<input className="input" value={f.contactEmail} onChange={set('contactEmail')} />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Телефон</label>
|
||||
<input className="input" value={f.contactPhone} onChange={set('contactPhone')} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<Button icon={Save} loading={busy} onClick={save}>Сохранить</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="card p-6">
|
||||
<div className="mb-3 font-semibold">Логотип</div>
|
||||
<div className="flex items-center gap-4">
|
||||
<div className="flex size-24 items-center justify-center overflow-hidden rounded-2xl border border-dashed border-line bg-surface-2">
|
||||
{preview ? <img src={preview} alt="" className="size-full bg-white object-contain p-1" /> : <ImagePlus className="size-8 text-subtle" />}
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<input ref={fileRef} type="file" accept="image/png,image/jpeg,image/webp" hidden onChange={(e) => { if (e.target.files[0]) { setLogo(e.target.files[0]); setRemoveLogo(false); } }} />
|
||||
<Button size="sm" variant="secondary" icon={Upload} onClick={() => fileRef.current.click()}>Выбрать</Button>
|
||||
{preview && <Button size="sm" variant="ghost" icon={Trash2} onClick={() => { setLogo(null); setRemoveLogo(true); }}>Убрать</Button>}
|
||||
</div>
|
||||
</div>
|
||||
<p className="mt-3 text-xs text-muted">PNG, JPG или WEBP до 2 МБ. Лучше квадратный, на прозрачном или белом фоне. Сохраните изменения кнопкой слева.</p>
|
||||
</div>
|
||||
<div className="card p-6">
|
||||
<div className="mb-2 font-semibold">Адрес библиотеки</div>
|
||||
<div className="flex items-center gap-2 rounded-xl bg-surface-2 p-2.5 font-mono text-sm break-all">
|
||||
<span className="flex-1">{url}</span>
|
||||
<button className="rounded-lg p-1.5 text-muted hover:bg-surface hover:text-ink" title="Скопировать" onClick={() => navigator.clipboard?.writeText(url).then(() => toast('Адрес скопирован'))}>
|
||||
<Copy className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
<p className="mt-2 text-xs text-muted">Разошлите этот адрес студентам и преподавателям. Изменить адрес может только администратор платформы.</p>
|
||||
<div className="mt-4 flex items-center gap-2 text-sm">
|
||||
Статус:
|
||||
{o.status === 'ACTIVE' ? <Badge color="green">Открыта</Badge> : o.status === 'PENDING' ? <Badge color="amber">На проверке</Badge> : <Badge color="red">Приостановлена</Badge>}
|
||||
</div>
|
||||
{o.statusNote && <p className="mt-2 rounded-lg bg-surface-2 p-2 text-xs text-muted">{o.statusNote}</p>}
|
||||
</div>
|
||||
<div className="card p-6 text-sm">
|
||||
<div className="mb-2 font-semibold">Пользователи</div>
|
||||
<div className="flex justify-between py-1"><span className="text-muted">Всего</span><b className="tnum">{fmtNum(data.counts.users)}</b></div>
|
||||
<div className="flex justify-between py-1"><span className="text-muted">Из Active Directory</span><b className="tnum">{fmtNum(data.counts.bySource.LDAP || 0)}</b></div>
|
||||
<div className="flex justify-between py-1"><span className="text-muted">С паролем библиотеки</span><b className="tnum">{fmtNum(data.counts.bySource.LOCAL || 0)}</b></div>
|
||||
<div className="flex justify-between py-1"><span className="text-muted">Ещё не сменили выданный пароль</span><b className="tnum">{fmtNum(data.counts.mustChange)}</b></div>
|
||||
<Link to="/admin/users/import" className="mt-3 block"><Button size="sm" variant="secondary" className="w-full" icon={Upload}>Загрузить список пользователей</Button></Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- Active Directory ----------
|
||||
const LISTS = [
|
||||
['adminGroups', 'Группы администраторов библиотеки', 'CN=ELibrary-Admins,OU=Groups,DC=university,DC=uz'],
|
||||
['moderatorGroups', 'Группы модераторов (библиотекари)', 'CN=ELibrary-Moderators,OU=Groups,DC=university,DC=uz'],
|
||||
['teacherGroups', 'Группы преподавателей', 'CN=Teachers,OU=Groups,DC=university,DC=uz'],
|
||||
['studentGroups', 'Группы студентов', 'CN=Students,OU=Groups,DC=university,DC=uz'],
|
||||
['staffGroups', 'Группы сотрудников', ''],
|
||||
['teacherOUs', 'OU преподавателей', 'OU=Teachers,DC=university,DC=uz'],
|
||||
['studentOUs', 'OU студентов', 'OU=Students,DC=university,DC=uz'],
|
||||
['staffOUs', 'OU сотрудников', ''],
|
||||
['allowedGroups', 'Разрешённые группы (пусто — весь домен)', ''],
|
||||
];
|
||||
|
||||
function Ldap({ data, onSaved }) {
|
||||
const toast = useToast();
|
||||
const { reloadOrg } = useAuth();
|
||||
const l = data.ldap;
|
||||
const init = () => ({
|
||||
...l,
|
||||
...Object.fromEntries(LISTS.map(([k]) => [k, (l[k] || []).join('\n')])),
|
||||
userFilter: l.userFilter || '',
|
||||
bindPassword: '',
|
||||
clearBindPassword: false,
|
||||
});
|
||||
const [f, setF] = useState(init);
|
||||
const [advanced, setAdvanced] = useState(() => LISTS.slice(4).some(([k]) => l[k]?.length) || !!l.studyGroupAttr);
|
||||
const [busy, setBusy] = useState(null);
|
||||
const [result, setResult] = useState(null);
|
||||
const [error, setError] = useState('');
|
||||
const [testUser, setTestUser] = useState(false);
|
||||
useEffect(() => setF(init()), [data]); // eslint-disable-line
|
||||
const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
|
||||
const body = () => ({ ...f, ...Object.fromEntries(LISTS.map(([k]) => [k, f[k].split('\n')])) });
|
||||
|
||||
const test = async () => {
|
||||
setBusy('test');
|
||||
setResult(null);
|
||||
try {
|
||||
setResult(await api('/org/ldap/test', { method: 'POST', body: body() }));
|
||||
} catch (e) {
|
||||
setResult({ ok: false, message: e.message });
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
const save = async () => {
|
||||
setError('');
|
||||
setBusy('save');
|
||||
try {
|
||||
const d = await api('/org/ldap', { method: 'PUT', body: body() });
|
||||
onSaved(d);
|
||||
reloadOrg();
|
||||
toast(d.ldap.enabled ? 'Вход через Active Directory включён' : 'Настройки сохранены');
|
||||
} catch (e) {
|
||||
setError(e.message);
|
||||
} finally {
|
||||
setBusy(null);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="grid gap-6 lg:grid-cols-3">
|
||||
<div className="card space-y-5 p-6 lg:col-span-2">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<Switch checked={f.enabled} onChange={(v) => setF({ ...f, enabled: v })} label={<span className="font-semibold">Вход через Active Directory</span>} />
|
||||
{l.enabled ? <Badge color="green"><CheckCircle2 className="size-3" />Включён</Badge> : <Badge>Выключен</Badge>}
|
||||
</div>
|
||||
<p className="-mt-2 text-sm text-muted">
|
||||
Студенты и преподаватели входят логином и паролем домена. Учётная запись в библиотеке создаётся при первом входе, а ФИО, подразделение и роль обновляются из AD.
|
||||
Пользователи, загруженные списком, продолжают входить паролем библиотеки.
|
||||
</p>
|
||||
{error && <div className="rounded-xl bg-rose-50 p-3 text-sm text-rose-700 dark:bg-rose-500/10 dark:text-rose-300">{error}</div>}
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="sm:col-span-2">
|
||||
<label className="label">Адрес контроллера домена *</label>
|
||||
<input className="input font-mono text-sm" value={f.url} onChange={set('url')} placeholder="ldaps://dc01.university.uz:636" />
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<label className="label">Базовый DN (где искать пользователей) *</label>
|
||||
<input className="input font-mono text-sm" value={f.baseDN} onChange={set('baseDN')} placeholder="DC=university,DC=uz" />
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<label className="label">Сервисная учётная запись (только чтение)</label>
|
||||
<input className="input font-mono text-sm" value={f.bindDN} onChange={set('bindDN')} placeholder="CN=svc-elibrary,OU=Service Accounts,DC=university,DC=uz" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Пароль сервисной учётной записи</label>
|
||||
<input
|
||||
className="input"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
value={f.bindPassword}
|
||||
onChange={(e) => setF({ ...f, bindPassword: e.target.value, clearBindPassword: false })}
|
||||
placeholder={l.hasBindPassword && !f.clearBindPassword ? '•••••••• сохранён' : ''}
|
||||
/>
|
||||
{l.hasBindPassword && !f.bindPassword && (
|
||||
<button className="mt-1 text-xs text-muted hover:text-rose-600" onClick={() => setF({ ...f, clearBindPassword: !f.clearBindPassword })}>
|
||||
{f.clearBindPassword ? 'Пароль будет удалён — отменить' : 'Удалить сохранённый пароль'}
|
||||
</button>
|
||||
)}
|
||||
<p className="mt-1 text-xs text-subtle">Хранится в зашифрованном виде и никогда не показывается.</p>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">…или UPN-суффикс домена</label>
|
||||
<input className="input font-mono text-sm" value={f.upnSuffix} onChange={set('upnSuffix')} placeholder="university.uz" />
|
||||
<p className="mt-1 text-xs text-subtle">Если сервисной учётной записи нет: вход как логин@суффикс. Группы и роли тогда тоже работают.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button className="flex items-center gap-1.5 text-sm font-medium text-brand-600 dark:text-brand-300" onClick={() => setAdvanced((v) => !v)}>
|
||||
<ChevronDown className={clsx('size-4 transition', advanced && 'rotate-180')} /> Роли, группы и дополнительные параметры
|
||||
</button>
|
||||
{/* скрываем, а не убираем из DOM — введённые значения сохраняются */}
|
||||
<div className={clsx('grid gap-4 sm:grid-cols-2', !advanced && 'hidden')}>
|
||||
{LISTS.map(([k, label, ph]) => (
|
||||
<div key={k}>
|
||||
<label className="label">{label}</label>
|
||||
<textarea className="input h-20 resize-y py-2 font-mono text-xs" value={f[k]} onChange={set(k)} placeholder={ph ? ph + '\n(по одной на строке)' : 'по одной на строке'} />
|
||||
</div>
|
||||
))}
|
||||
<div>
|
||||
<label className="label">Атрибут с академической группой</label>
|
||||
<input className="input font-mono text-sm" value={f.studyGroupAttr} onChange={set('studyGroupAttr')} placeholder="extensionAttribute1" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Атрибут с курсом</label>
|
||||
<input className="input font-mono text-sm" value={f.courseAttr} onChange={set('courseAttr')} placeholder="extensionAttribute2" />
|
||||
</div>
|
||||
<div className="sm:col-span-2">
|
||||
<label className="label">Фильтр поиска пользователя</label>
|
||||
<input className="input font-mono text-xs" value={f.userFilter} onChange={set('userFilter')} />
|
||||
</div>
|
||||
<div className="flex items-center gap-6 sm:col-span-2">
|
||||
<Switch checked={f.tlsRejectUnauthorized} onChange={(v) => setF({ ...f, tlsRejectUnauthorized: v })} label="Проверять TLS-сертификат" />
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
Таймаут, мс
|
||||
<input className="input h-9 w-24" type="number" value={f.timeout} onChange={set('timeout')} />
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{result && (
|
||||
<div className={clsx('flex items-start gap-2 rounded-xl p-3 text-sm', result.ok ? 'bg-emerald-50 text-emerald-800 dark:bg-emerald-500/10 dark:text-emerald-300' : 'bg-rose-50 text-rose-800 dark:bg-rose-500/10 dark:text-rose-300')}>
|
||||
{result.ok ? <CheckCircle2 className="mt-0.5 size-4 shrink-0" /> : <XCircle className="mt-0.5 size-4 shrink-0" />}
|
||||
{result.message}
|
||||
</div>
|
||||
)}
|
||||
<div className="flex flex-wrap justify-end gap-2 border-t border-line pt-5">
|
||||
<Button variant="secondary" icon={PlugZap} loading={busy === 'test'} onClick={test}>Проверить подключение</Button>
|
||||
<Button variant="secondary" icon={UserCheck} onClick={() => setTestUser(true)}>Проверить вход пользователя</Button>
|
||||
<Button icon={Save} loading={busy === 'save'} onClick={save}>Сохранить</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="card p-6 text-sm">
|
||||
<div className="mb-2 flex items-center gap-2 font-semibold"><Network className="size-4 text-sky-500" />Сетевой доступ</div>
|
||||
<p className="text-muted">
|
||||
Сервер библиотеки подключается к вашему контроллеру домена по сети. Если библиотека работает в облаке, а контроллер — внутри университета:
|
||||
</p>
|
||||
<ul className="mt-2 list-disc space-y-1 pl-5 text-muted">
|
||||
<li>используйте <b className="text-ink">ldaps://</b> (порт 636) — пароли передаются зашифрованно;</li>
|
||||
<li>откройте порт 636 на межсетевом экране <b className="text-ink">только для IP-адреса сервера библиотеки</b>;</li>
|
||||
<li>сертификат контроллера должен быть выдан на его DNS-имя.</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div className="card p-6 text-sm">
|
||||
<div className="mb-2 flex items-center gap-2 font-semibold"><ShieldCheck className="size-4 text-emerald-500" />Безопасность</div>
|
||||
<ul className="list-disc space-y-1 pl-5 text-muted">
|
||||
<li>Сервисной учётной записи нужны только права на чтение каталога.</li>
|
||||
<li>Пароли пользователей библиотека не хранит — их проверяет контроллер домена.</li>
|
||||
<li>Отключённые в AD учётные записи войти не могут.</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div className="card p-6 text-sm">
|
||||
<div className="mb-2 flex items-center gap-2 font-semibold"><Info className="size-4 text-brand-500" />Как определяются роли</div>
|
||||
<p className="text-muted">
|
||||
Администратор и модератор — по группам. Студент / преподаватель — сначала по OU, затем по группам. Если тип не определился, пользователь выбирает его на странице входа,
|
||||
а статус преподавателя подтверждает администратор.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<TestUserModal open={testUser} onClose={() => setTestUser(false)} body={body} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TestUserModal({ open, onClose, body }) {
|
||||
const [u, setU] = useState({ testUsername: '', testPassword: '' });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [res, setRes] = useState(null);
|
||||
const run = async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setRes(null);
|
||||
try {
|
||||
setRes(await api('/org/ldap/test-user', { method: 'POST', body: { ...body(), ...u } }));
|
||||
} catch (err) {
|
||||
setRes({ ok: false, message: err.message });
|
||||
} finally {
|
||||
setBusy(false);
|
||||
setU((x) => ({ ...x, testPassword: '' }));
|
||||
}
|
||||
};
|
||||
const p = res?.profile;
|
||||
return (
|
||||
<Modal open={open} onClose={onClose} title="Проверка входа пользователя" size="md">
|
||||
<p className="mb-4 text-sm text-muted">Введите учётные данные любого пользователя домена — увидите, какие данные библиотека получит из AD. Ничего не сохраняется.</p>
|
||||
<form onSubmit={run} className="grid gap-3 sm:grid-cols-[1fr_1fr_auto]">
|
||||
<input className="input" placeholder="логин" value={u.testUsername} onChange={(e) => setU({ ...u, testUsername: e.target.value })} autoComplete="off" />
|
||||
<input className="input" type="password" placeholder="пароль" value={u.testPassword} onChange={(e) => setU({ ...u, testPassword: e.target.value })} autoComplete="new-password" />
|
||||
<Button type="submit" loading={busy}>Проверить</Button>
|
||||
</form>
|
||||
{res && (
|
||||
<div className={clsx('mt-4 rounded-xl p-3 text-sm', res.ok ? 'bg-emerald-50 text-emerald-800 dark:bg-emerald-500/10 dark:text-emerald-300' : 'bg-rose-50 text-rose-800 dark:bg-rose-500/10 dark:text-rose-300')}>
|
||||
{res.message}
|
||||
</div>
|
||||
)}
|
||||
{p && (
|
||||
<div className="mt-3 divide-y divide-line rounded-xl border border-line text-sm">
|
||||
{[
|
||||
['Логин', p.username], ['ФИО', p.displayName], ['E-mail', p.email], ['Подразделение', p.department], ['Должность', p.title],
|
||||
['Роль', ROLE_LABELS[p.role]], ['Тип', p.kind ? KIND_LABELS[p.kind] : 'не определён — выберет при входе'], ['Группа', p.studyGroup], ['Курс', p.course],
|
||||
].map(([k, v]) => (
|
||||
<div key={k} className="grid grid-cols-[140px_1fr] gap-3 px-3 py-2">
|
||||
<span className="text-muted">{k}</span>
|
||||
<span>{v || <span className="text-subtle">—</span>}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
|
||||
// ---------- Сервер ----------
|
||||
function ServerInfo() {
|
||||
const { data, error, reload } = useApi('/system/status');
|
||||
if (error) return <ErrorBox error={error} onRetry={reload} />;
|
||||
if (!data) return <PageLoader />;
|
||||
return (
|
||||
<div className="grid gap-4 md:grid-cols-2">
|
||||
<div className="card p-6">
|
||||
<div className="mb-3 flex items-center gap-2 font-semibold"><Database className="size-5 text-subtle" />Данные организации</div>
|
||||
<div className="divide-y divide-line text-sm">
|
||||
<div className="flex justify-between py-2"><span className="text-muted">Пользователей</span><b className="tnum">{fmtNum(data.counts.users)}</b></div>
|
||||
<div className="flex justify-between py-2"><span className="text-muted">Своих изданий</span><b className="tnum">{fmtNum(data.counts.books)}</b></div>
|
||||
<div className="flex justify-between py-2"><span className="text-muted">Записей в журнале</span><b className="tnum">{fmtNum(data.counts.events)}</b></div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="card p-6">
|
||||
<div className="mb-3 flex items-center gap-2 font-semibold"><Server className="size-5 text-subtle" />Сервер платформы</div>
|
||||
<div className="divide-y divide-line text-sm">
|
||||
<div className="flex justify-between py-2"><span className="text-muted">Часовой пояс статистики</span><span>{data.timezone}</span></div>
|
||||
<div className="flex justify-between py-2"><span className="text-muted">Макс. размер файла</span><span>{data.maxUploadMb} МБ</span></div>
|
||||
<div className="flex justify-between py-2"><span className="text-muted">Node.js</span><span>{data.node}</span></div>
|
||||
<div className="flex justify-between py-2"><span className="text-muted">Работает</span><span>{Math.floor(data.uptimeSec / 3600)} ч {Math.floor((data.uptimeSec % 3600) / 60)} мин</span></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
import { useState } from 'react';
|
||||
import { Link, useParams } from 'react-router-dom';
|
||||
import { ArrowLeft, Ban, BookOpen, Download, Eye, Hourglass, KeyRound, LogIn, Search, ShieldCheck, UserRound } from 'lucide-react';
|
||||
import { api, useApi } from '../../lib/api';
|
||||
import { useAuth } from '../../lib/auth';
|
||||
import { EVENT_LABELS, KIND_COLORS, KIND_LABELS, ROLE_LABELS, fmtDate, fmtDateTime, fmtNum, timeAgo } from '../../lib/format';
|
||||
import { Avatar, Badge, Button, ErrorBox, Modal, PageLoader, useToast } from '../../components/ui';
|
||||
import Credentials from '../../components/Credentials';
|
||||
import { BarList, ChartCard, TimelineChart } from './charts';
|
||||
import { roleColor } from './Users';
|
||||
import { EventIcon } from './Activity';
|
||||
|
||||
export default function UserDetails() {
|
||||
const { id } = useParams();
|
||||
const { can, user: me } = useAuth();
|
||||
const toast = useToast();
|
||||
const { data, error, loading, reload } = useApi(`/users/${id}`, [id]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [resetAsk, setResetAsk] = useState(false);
|
||||
const [issued, setIssued] = useState(null);
|
||||
|
||||
if (error) return <ErrorBox error={error} onRetry={reload} />;
|
||||
if (loading && !data) return <PageLoader />;
|
||||
const { user: u, counts, topBooks, activity, recent } = data;
|
||||
|
||||
// новый временный пароль (только учётные записи без AD); старые сессии пользователя завершаются
|
||||
const resetPassword = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const d = await api('/org/users/reset-passwords', { method: 'POST', body: { ids: [u.id] } });
|
||||
setResetAsk(false);
|
||||
setIssued(d.credentials);
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const patch = async (body, msg) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api(`/users/${u.id}`, { method: 'PATCH', body });
|
||||
toast(msg);
|
||||
reload();
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
// заполняем пропуски дней нулями для графика
|
||||
const series = (() => {
|
||||
if (!activity.length) return [];
|
||||
const map = new Map(activity.map((a) => [a.day, a.count]));
|
||||
const out = [];
|
||||
const d = new Date(activity[0].day + 'T12:00:00Z');
|
||||
const end = new Date(activity.at(-1).day + 'T12:00:00Z');
|
||||
while (d <= end) {
|
||||
const k = d.toISOString().slice(0, 10);
|
||||
out.push({ day: k, count: map.get(k) || 0 });
|
||||
d.setUTCDate(d.getUTCDate() + 1);
|
||||
}
|
||||
return out;
|
||||
})();
|
||||
|
||||
const stats = [
|
||||
['Входы', counts.LOGIN, LogIn],
|
||||
['Просмотры', counts.VIEW, Eye],
|
||||
['Чтение онлайн', counts.READ, BookOpen],
|
||||
['Скачивания', counts.DOWNLOAD, Download],
|
||||
['Поиски', counts.SEARCH, Search],
|
||||
];
|
||||
const self = me.id === u.id;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Link to="/admin/users" className="mb-4 inline-flex items-center gap-1.5 text-sm text-muted hover:text-ink">
|
||||
<ArrowLeft className="size-4" /> Все пользователи
|
||||
</Link>
|
||||
|
||||
<div className="card mb-4 flex flex-wrap items-center gap-5 p-6">
|
||||
<Avatar name={u.displayName} size={64} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<h1 className="text-2xl font-bold tracking-tight">{u.displayName}</h1>
|
||||
<Badge color={KIND_COLORS[u.kind]}>{KIND_LABELS[u.kind]}{u.studyGroup ? ` · ${u.studyGroup}` : ''}{u.course ? ` · ${u.course} курс` : ''}</Badge>
|
||||
<Badge color={roleColor(u.role)}>{ROLE_LABELS[u.role]}</Badge>
|
||||
{u.isBlocked && <Badge color="red"><Ban className="size-3" />Заблокирован</Badge>}
|
||||
</div>
|
||||
<div className="mt-1 text-sm text-muted">
|
||||
{u.username} {u.email && `· ${u.email}`} {u.title && `· ${u.title}`}
|
||||
</div>
|
||||
<div className="text-sm text-muted">{u.department || 'Подразделение не указано'}</div>
|
||||
<div className="mt-2 text-xs text-subtle">
|
||||
Источник: {u.source === 'LDAP' ? 'Active Directory' : 'локальная учётная запись'} · Зарегистрирован {fmtDate(u.createdAt)} · Последний вход {fmtDateTime(u.lastLoginAt)} · Активность {timeAgo(u.lastSeenAt)}
|
||||
</div>
|
||||
</div>
|
||||
{can('ADMIN') && (
|
||||
<div className="flex flex-col gap-2 sm:items-end">
|
||||
<div className="flex items-center gap-2">
|
||||
<UserRound className="size-4 text-subtle" />
|
||||
<select
|
||||
className="input h-9 w-auto"
|
||||
disabled={busy}
|
||||
value={u.kindOverride || ''}
|
||||
onChange={(e) => patch({ kindOverride: e.target.value || null }, 'Тип пользователя изменён')}
|
||||
>
|
||||
<option value="">По AD ({u.adKind ? KIND_LABELS[u.adKind] : 'не определён'})</option>
|
||||
{Object.entries(KIND_LABELS).map(([v, l]) => <option key={v} value={v}>{l} (вручную)</option>)}
|
||||
</select>
|
||||
</div>
|
||||
{u.teacherPending && (
|
||||
<Button size="sm" icon={Hourglass} loading={busy} onClick={() => patch({ kindOverride: 'TEACHER' }, 'Статус преподавателя подтверждён')} className="!bg-violet-600 hover:!bg-violet-700">
|
||||
Подтвердить: преподаватель
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{can('ADMIN') && !self && (
|
||||
<div className="flex flex-col gap-2 sm:items-end">
|
||||
<div className="flex items-center gap-2">
|
||||
<ShieldCheck className="size-4 text-subtle" />
|
||||
<select
|
||||
className="input h-9 w-auto"
|
||||
disabled={busy}
|
||||
value={u.roleOverride || ''}
|
||||
onChange={(e) => patch({ roleOverride: e.target.value || null }, 'Роль изменена')}
|
||||
>
|
||||
<option value="">{u.source === 'LDAP' ? `По группам AD (${ROLE_LABELS[u.adRole]})` : `Как при создании (${ROLE_LABELS[u.adRole]})`}</option>
|
||||
{Object.entries(ROLE_LABELS).map(([v, l]) => <option key={v} value={v}>{l} (вручную)</option>)}
|
||||
</select>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant={u.isBlocked ? 'secondary' : 'danger'}
|
||||
icon={Ban}
|
||||
loading={busy}
|
||||
onClick={() => patch({ isBlocked: !u.isBlocked }, u.isBlocked ? 'Пользователь разблокирован' : 'Пользователь заблокирован')}
|
||||
>
|
||||
{u.isBlocked ? 'Разблокировать' : 'Заблокировать'}
|
||||
</Button>
|
||||
{u.source === 'LOCAL' && u.id !== me.id && (
|
||||
<Button size="sm" variant="secondary" icon={KeyRound} disabled={busy} onClick={() => setResetAsk(true)}>
|
||||
Новый пароль
|
||||
</Button>
|
||||
)}
|
||||
{u.mustChangePassword && <span className="text-xs text-amber-600 dark:text-amber-400">Ещё не сменил выданный пароль</span>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-5">
|
||||
{stats.map(([l, v, Icon]) => (
|
||||
<div key={l} className="card p-4">
|
||||
<div className="flex items-center gap-1.5 text-xs text-muted"><Icon className="size-4 text-subtle" />{l}</div>
|
||||
<div className="mt-1 text-2xl font-bold tnum">{fmtNum(v || 0)}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 lg:grid-cols-3">
|
||||
<ChartCard title="Активность" subtitle="Действий в день (последние 90 активных дней)" className="lg:col-span-2">
|
||||
<TimelineChart data={series} series={[{ key: 'count', label: 'Действия', color: 'var(--series-1)' }]} height={220} />
|
||||
</ChartCard>
|
||||
<ChartCard title="Что скачивал(а)">
|
||||
<BarList items={topBooks} getLabel={(b) => b.title} getSub={(b) => b.authors} getHref={(b) => `/books/${b.id}`} valueLabel="раз" />
|
||||
</ChartCard>
|
||||
</div>
|
||||
|
||||
<ChartCard title="Последние действия" className="mt-4" actions={<Link to={`/admin/activity?userId=${u.id}`} className="text-xs font-medium text-brand-600 dark:text-brand-300">Полный журнал →</Link>}>
|
||||
<div className="-mx-5 divide-y divide-line">
|
||||
{recent.map((e) => (
|
||||
<div key={e.id} className="flex items-center gap-3 px-5 py-2.5 text-sm">
|
||||
<EventIcon type={e.type} />
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="font-medium">{EVENT_LABELS[e.type] || e.type}</span>
|
||||
{e.book && <> · <Link to={`/books/${e.book.id}`} className="text-brand-600 hover:underline dark:text-brand-300">{e.book.title}</Link></>}
|
||||
{e.query && <span className="text-muted"> · «{e.query}» ({e.resultCount} рез.)</span>}
|
||||
</div>
|
||||
<div className="hidden shrink-0 text-xs text-subtle sm:block">{e.browser} · {e.os} · <span className="font-mono">{e.ip}</span></div>
|
||||
<div className="shrink-0 text-xs text-muted tnum">{fmtDateTime(e.createdAt)}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ChartCard>
|
||||
<Modal
|
||||
open={resetAsk}
|
||||
onClose={() => setResetAsk(false)}
|
||||
title="Выдать новый пароль?"
|
||||
size="sm"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setResetAsk(false)}>Отмена</Button>
|
||||
<Button icon={KeyRound} loading={busy} onClick={resetPassword}>Выдать пароль</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<p className="text-sm text-muted">
|
||||
Текущий пароль <b className="text-ink">{u.displayName}</b> перестанет работать, открытые сеансы завершатся. При входе с новым паролем система попросит придумать свой.
|
||||
</p>
|
||||
</Modal>
|
||||
<Modal open={!!issued} onClose={() => setIssued(null)} title="Новый пароль" size="lg">
|
||||
{issued && <Credentials items={issued} />}
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,230 @@
|
||||
import { useState } from 'react';
|
||||
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { useAuth } from '../../lib/auth';
|
||||
import { Ban, Hourglass, KeyRound, Search, Upload, UserPlus, UserX } from 'lucide-react';
|
||||
import { api, qs, useApi } from '../../lib/api';
|
||||
import { KIND_COLORS, KIND_LABELS, ROLE_LABELS, fmtNum, timeAgo } from '../../lib/format';
|
||||
import { Avatar, Badge, Button, Empty, ErrorBox, Modal, PageLoader, Pagination, useToast } from '../../components/ui';
|
||||
import Credentials from '../../components/Credentials';
|
||||
import { PageHeader } from '../../layouts/AdminLayout';
|
||||
|
||||
export const roleColor = (r) => (r === 'ADMIN' ? 'violet' : r === 'MODERATOR' ? 'sky' : 'gray');
|
||||
|
||||
export default function AdminUsers() {
|
||||
const nav = useNavigate();
|
||||
const [q, setQ] = useState('');
|
||||
const [sp] = useSearchParams();
|
||||
const [p, setP] = useState({ q: '', role: '', kind: sp.get('kind') || '', group: '', department: '', sort: '', page: 1 });
|
||||
const deps = useApi('/users/departments');
|
||||
const groups = useApi('/users/groups');
|
||||
const { data, error, loading, reload } = useApi('/users' + qs(p));
|
||||
const { can, org } = useAuth();
|
||||
const toast = useToast();
|
||||
const [adding, setAdding] = useState(false);
|
||||
const [groupReset, setGroupReset] = useState(false);
|
||||
const [issued, setIssued] = useState(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const resetGroup = async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const d = await api('/org/users/reset-passwords', { method: 'POST', body: { group: p.group } });
|
||||
setGroupReset(false);
|
||||
setIssued(d.credentials);
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<PageHeader
|
||||
title="Пользователи"
|
||||
subtitle={org?.ldapEnabled ? 'Пользователи домена появляются автоматически при первом входе через Active Directory' : 'Учётные записи с паролем библиотеки: загрузите список или добавьте вручную'}
|
||||
actions={
|
||||
can('ADMIN') && (
|
||||
<>
|
||||
{p.group && <Button variant="ghost" icon={KeyRound} onClick={() => setGroupReset(true)}>Новые пароли группе {p.group}</Button>}
|
||||
<Button variant="secondary" icon={UserPlus} onClick={() => setAdding(true)}>Добавить</Button>
|
||||
<Link to="/admin/users/import"><Button icon={Upload}>Загрузить список</Button></Link>
|
||||
</>
|
||||
)
|
||||
}
|
||||
/>
|
||||
<AddUserModal open={adding} onClose={() => setAdding(false)} onCreated={(c) => { setAdding(false); setIssued([c]); reload(); }} />
|
||||
<Modal
|
||||
open={groupReset}
|
||||
onClose={() => setGroupReset(false)}
|
||||
title={`Новые пароли группе ${p.group}?`}
|
||||
size="sm"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setGroupReset(false)}>Отмена</Button>
|
||||
<Button icon={KeyRound} loading={busy} onClick={resetGroup}>Выдать пароли</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<p className="text-sm text-muted">Всем студентам группы с паролем библиотеки будут выданы новые временные пароли, текущие перестанут работать. Учётные записи AD не затрагиваются.</p>
|
||||
</Modal>
|
||||
<Modal open={!!issued} onClose={() => setIssued(null)} title="Логины и пароли" size="lg">
|
||||
{issued && <Credentials items={issued} />}
|
||||
</Modal>
|
||||
<div className="card overflow-hidden">
|
||||
<div className="flex flex-wrap items-center gap-3 border-b border-line p-4">
|
||||
<form className="relative min-w-[220px] flex-1" onSubmit={(e) => { e.preventDefault(); setP({ ...p, q, page: 1 }); }}>
|
||||
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-subtle" />
|
||||
<input className="input pl-9" placeholder="ФИО, логин, e-mail, подразделение… (Enter)" value={q} onChange={(e) => setQ(e.target.value)} />
|
||||
</form>
|
||||
<select className="input w-auto" value={p.kind} onChange={(e) => setP({ ...p, kind: e.target.value, page: 1 })}>
|
||||
<option value="">Студенты и преподаватели</option>
|
||||
{Object.entries(KIND_LABELS).map(([v, l]) => <option key={v} value={v}>{l === 'Сотрудник' ? 'Сотрудники' : l === 'Студент' ? 'Студенты' : 'Преподаватели'}</option>)}
|
||||
<option value="PENDING">Ждут подтверждения преподавателя</option>
|
||||
</select>
|
||||
{groups.data?.items.length > 0 && (
|
||||
<select className="input w-auto" value={p.group} onChange={(e) => setP({ ...p, group: e.target.value, page: 1 })}>
|
||||
<option value="">Все группы</option>
|
||||
{groups.data.items.map((g) => <option key={g.value} value={g.value}>{g.value} ({g.count})</option>)}
|
||||
</select>
|
||||
)}
|
||||
<select className="input w-auto" value={p.role} onChange={(e) => setP({ ...p, role: e.target.value, page: 1 })}>
|
||||
<option value="">Все роли</option>
|
||||
{Object.entries(ROLE_LABELS).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
|
||||
</select>
|
||||
<select className="input w-auto max-w-[240px]" value={p.department} onChange={(e) => setP({ ...p, department: e.target.value, page: 1 })}>
|
||||
<option value="">Все подразделения</option>
|
||||
{deps.data?.items.map((d) => <option key={d.value} value={d.value}>{d.value} ({d.count})</option>)}
|
||||
</select>
|
||||
<select className="input w-auto" value={p.sort} onChange={(e) => setP({ ...p, sort: e.target.value, page: 1 })}>
|
||||
<option value="">По активности</option>
|
||||
<option value="logins">По числу входов</option>
|
||||
<option value="created">Новые</option>
|
||||
<option value="name">По имени</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{error && <div className="p-4"><ErrorBox error={error} onRetry={reload} /></div>}
|
||||
{loading && !data && <PageLoader />}
|
||||
{data && !data.items.length && <Empty icon={UserX} title="Никого не найдено" />}
|
||||
{data && data.items.length > 0 && (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead className="bg-surface-2 text-xs text-muted">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left font-medium">Пользователь</th>
|
||||
<th className="hidden px-4 py-3 text-left font-medium md:table-cell">Подразделение</th>
|
||||
<th className="px-4 py-3 text-left font-medium">Кто</th>
|
||||
<th className="hidden px-4 py-3 text-left font-medium lg:table-cell">Роль</th>
|
||||
<th className="hidden px-4 py-3 text-right font-medium sm:table-cell">Входов</th>
|
||||
<th className="hidden px-4 py-3 text-right font-medium sm:table-cell">Скачиваний</th>
|
||||
<th className="px-4 py-3 text-left font-medium">Был(а)</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-line">
|
||||
{data.items.map((u) => (
|
||||
<tr key={u.id} onClick={(e) => !e.target.closest('a') && nav(`/admin/users/${u.id}`)} className="cursor-pointer hover:bg-surface-2/60">
|
||||
<td className="px-4 py-3">
|
||||
<Link to={`/admin/users/${u.id}`} className="flex items-center gap-3">
|
||||
<div className="relative">
|
||||
<Avatar name={u.displayName} size={36} />
|
||||
{u.online && <span className="absolute -right-0.5 -bottom-0.5 size-3 rounded-full border-2 border-surface bg-emerald-500" title="Онлайн" />}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-1.5 truncate font-medium">
|
||||
{u.displayName}
|
||||
{u.isBlocked && <Ban className="size-3.5 text-rose-500" title="Заблокирован" />}
|
||||
</div>
|
||||
<div className="truncate text-xs text-muted">{u.username}{u.title ? ` · ${u.title}` : ''}</div>
|
||||
</div>
|
||||
</Link>
|
||||
</td>
|
||||
<td className="hidden max-w-[260px] truncate px-4 py-3 text-muted md:table-cell">{u.department || '—'}</td>
|
||||
<td className="px-4 py-3 whitespace-nowrap">
|
||||
<Badge color={KIND_COLORS[u.kind]}>{KIND_LABELS[u.kind]}</Badge>
|
||||
{u.studyGroup && <span className="ml-1.5 text-xs text-muted">{u.studyGroup}</span>}
|
||||
{u.teacherPending && <Badge color="amber" className="ml-1"><Hourglass className="size-3" />преподаватель?</Badge>}
|
||||
</td>
|
||||
<td className="hidden px-4 py-3 lg:table-cell">
|
||||
<Badge color={roleColor(u.role)}>{ROLE_LABELS[u.role]}</Badge>
|
||||
{u.source === 'LOCAL' && <Badge className="ml-1">локальный</Badge>}
|
||||
</td>
|
||||
<td className="hidden px-4 py-3 text-right tnum sm:table-cell">{fmtNum(u.loginCount)}</td>
|
||||
<td className="hidden px-4 py-3 text-right font-semibold tnum sm:table-cell">{fmtNum(u.downloads)}</td>
|
||||
<td className="px-4 py-3 whitespace-nowrap text-muted">{u.online ? <span className="font-medium text-emerald-600 dark:text-emerald-400">онлайн</span> : timeAgo(u.lastSeenAt)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
<div className="flex items-center justify-between border-t border-line p-3">
|
||||
<span className="pl-2 text-xs text-muted tnum">{data && `Всего: ${fmtNum(data.total)}`}</span>
|
||||
<Pagination page={p.page} pages={data?.pages} onChange={(page) => setP({ ...p, page })} />
|
||||
<span />
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/** Один пользователь вручную: логин и пароль система сгенерирует */
|
||||
function AddUserModal({ open, onClose, onCreated }) {
|
||||
const empty = { lastName: '', firstName: '', middleName: '', kind: 'STUDENT', group: '', email: '', department: '', role: 'USER' };
|
||||
const [f, setF] = useState(empty);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
|
||||
const submit = async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const d = await api('/org/users', { method: 'POST', body: f });
|
||||
setF(empty);
|
||||
onCreated(d.credential);
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<Modal open={open} onClose={onClose} title="Новый пользователь" size="md">
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
{error && <div className="rounded-xl bg-rose-50 p-3 text-sm text-rose-700 dark:bg-rose-500/10 dark:text-rose-300">{error}</div>}
|
||||
<div className="grid gap-3 sm:grid-cols-3">
|
||||
<div><label className="label">Фамилия *</label><input className="input" autoFocus value={f.lastName} onChange={set('lastName')} /></div>
|
||||
<div><label className="label">Имя *</label><input className="input" value={f.firstName} onChange={set('firstName')} /></div>
|
||||
<div><label className="label">Отчество</label><input className="input" value={f.middleName} onChange={set('middleName')} /></div>
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div>
|
||||
<label className="label">Тип</label>
|
||||
<select className="input" value={f.kind} onChange={set('kind')}>
|
||||
{Object.entries(KIND_LABELS).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
{f.kind === 'STUDENT' ? (
|
||||
<div><label className="label">Группа</label><input className="input" value={f.group} onChange={set('group')} placeholder="ИС-24-01" /></div>
|
||||
) : (
|
||||
<div>
|
||||
<label className="label">Роль в библиотеке</label>
|
||||
<select className="input" value={f.role} onChange={set('role')}>
|
||||
{Object.entries(ROLE_LABELS).map(([v, l]) => <option key={v} value={v}>{l}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div><label className="label">E-mail</label><input className="input" value={f.email} onChange={set('email')} /></div>
|
||||
<div><label className="label">Факультет / кафедра</label><input className="input" value={f.department} onChange={set('department')} /></div>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button variant="secondary" type="button" onClick={onClose}>Отмена</Button>
|
||||
<Button type="submit" icon={UserPlus} loading={busy}>Создать и выдать пароль</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
import { useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import clsx from 'clsx';
|
||||
import { Area, AreaChart, CartesianGrid, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
|
||||
import { ArrowDownRight, ArrowUpRight, Minus, Table2, LineChart as LineIcon } from 'lucide-react';
|
||||
import { fmtDay, fmtNum } from '../../lib/format';
|
||||
import { Segmented } from '../../components/ui';
|
||||
|
||||
export function ChartCard({ title, subtitle, actions, children, className }) {
|
||||
return (
|
||||
<div className={clsx('card flex flex-col p-5', className)}>
|
||||
<div className="mb-4 flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h3 className="font-semibold text-ink">{title}</h3>
|
||||
{subtitle && <p className="mt-0.5 text-xs text-muted">{subtitle}</p>}
|
||||
</div>
|
||||
{actions}
|
||||
</div>
|
||||
<div className="min-h-0 flex-1">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** KPI-плитка с изменением к предыдущему периоду */
|
||||
export function KpiTile({ label, icon: Icon, value, prev, inverse, hint }) {
|
||||
const delta = prev ? ((value - prev) / prev) * 100 : value ? 100 : 0;
|
||||
const good = inverse ? delta < 0 : delta > 0;
|
||||
const flat = Math.abs(delta) < 0.5;
|
||||
return (
|
||||
<div className="card p-4 sm:p-5" title={hint}>
|
||||
<div className="flex items-center gap-2 text-xs font-medium text-muted">
|
||||
{Icon && <Icon className="size-4 text-subtle" />}
|
||||
{label}
|
||||
</div>
|
||||
<div className="mt-2 text-2xl font-bold tracking-tight tnum sm:text-3xl">{fmtNum(value)}</div>
|
||||
<div className="mt-1.5 flex items-center gap-1.5 text-xs">
|
||||
<span
|
||||
className={clsx(
|
||||
'inline-flex items-center gap-0.5 rounded-md px-1.5 py-0.5 font-semibold tnum',
|
||||
flat ? 'bg-surface-2 text-muted' : good ? 'bg-emerald-50 text-emerald-700 dark:bg-emerald-500/15 dark:text-emerald-300' : 'bg-rose-50 text-rose-700 dark:bg-rose-500/15 dark:text-rose-300'
|
||||
)}
|
||||
>
|
||||
{flat ? <Minus className="size-3" /> : delta > 0 ? <ArrowUpRight className="size-3" /> : <ArrowDownRight className="size-3" />}
|
||||
{flat ? '0%' : `${Math.abs(delta).toFixed(Math.abs(delta) < 10 ? 1 : 0)}%`}
|
||||
</span>
|
||||
<span className="text-subtle">к пред. периоду ({fmtNum(prev)})</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Legend({ series }) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-1">
|
||||
{series.map((s) => (
|
||||
<span key={s.key} className="flex items-center gap-1.5 text-xs text-muted">
|
||||
<span className="h-2.5 w-2.5 rounded-sm" style={{ background: s.color }} />
|
||||
{s.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ChartTooltip({ active, payload, label, series }) {
|
||||
if (!active || !payload?.length) return null;
|
||||
const row = payload[0].payload;
|
||||
return (
|
||||
<div className="min-w-40 rounded-xl border border-line bg-surface px-3 py-2.5 text-xs shadow-xl">
|
||||
<div className="mb-1.5 font-semibold text-ink">{new Date(label + 'T12:00:00').toLocaleDateString('ru-RU', { weekday: 'short', day: 'numeric', month: 'long' })}</div>
|
||||
{series.map((s) => (
|
||||
<div key={s.key} className="flex items-center justify-between gap-4 py-0.5">
|
||||
<span className="flex items-center gap-1.5 text-muted">
|
||||
<span className="h-0.5 w-3 rounded" style={{ background: s.color }} />
|
||||
{s.label}
|
||||
</span>
|
||||
<span className="font-semibold text-ink tnum">{fmtNum(row[s.key])}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Временной ряд: одна ось Y, тонкие линии, перекрестие + подсказка, переключатель «таблица» */
|
||||
export function TimelineChart({ data, series, height = 280 }) {
|
||||
const [mode, setMode] = useState('chart');
|
||||
return (
|
||||
<div>
|
||||
<div className="mb-3 flex items-center justify-between gap-3">
|
||||
{series.length > 1 ? <Legend series={series} /> : <span />}
|
||||
<Segmented
|
||||
value={mode}
|
||||
onChange={setMode}
|
||||
options={[
|
||||
{ value: 'chart', icon: LineIcon, title: 'График' },
|
||||
{ value: 'table', icon: Table2, title: 'Таблица' },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
{mode === 'chart' ? (
|
||||
<div style={{ height }}>
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={data} margin={{ top: 8, right: 8, left: -12, bottom: 0 }}>
|
||||
<defs>
|
||||
{series.map((s) => (
|
||||
<linearGradient key={s.key} id={`g-${s.key}`} x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor={s.color} stopOpacity={series.length > 1 ? 0.12 : 0.22} />
|
||||
<stop offset="100%" stopColor={s.color} stopOpacity={0} />
|
||||
</linearGradient>
|
||||
))}
|
||||
</defs>
|
||||
<CartesianGrid vertical={false} stroke="var(--chart-grid)" />
|
||||
<XAxis
|
||||
dataKey="day"
|
||||
tickFormatter={fmtDay}
|
||||
tick={{ fill: 'var(--subtle)', fontSize: 11 }}
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
minTickGap={28}
|
||||
/>
|
||||
<YAxis tick={{ fill: 'var(--subtle)', fontSize: 11 }} axisLine={false} tickLine={false} allowDecimals={false} width={48} />
|
||||
<Tooltip content={<ChartTooltip series={series} />} cursor={{ stroke: 'var(--subtle)', strokeDasharray: '3 3' }} />
|
||||
{series.map((s) => (
|
||||
<Area
|
||||
key={s.key}
|
||||
type="monotone"
|
||||
dataKey={s.key}
|
||||
name={s.label}
|
||||
stroke={s.color}
|
||||
strokeWidth={2}
|
||||
fill={`url(#g-${s.key})`}
|
||||
activeDot={{ r: 4.5, strokeWidth: 2, stroke: 'var(--surface)' }}
|
||||
dot={false}
|
||||
isAnimationActive={false}
|
||||
/>
|
||||
))}
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
) : (
|
||||
<div className="overflow-auto rounded-xl border border-line" style={{ maxHeight: height }}>
|
||||
<table className="w-full text-sm tnum">
|
||||
<thead className="sticky top-0 bg-surface-2 text-xs text-muted">
|
||||
<tr>
|
||||
<th className="px-3 py-2 text-left font-medium">Дата</th>
|
||||
{series.map((s) => (
|
||||
<th key={s.key} className="px-3 py-2 text-right font-medium">{s.label}</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-line">
|
||||
{[...data].reverse().map((r) => (
|
||||
<tr key={r.day}>
|
||||
<td className="px-3 py-1.5">{fmtDay(r.day)}</td>
|
||||
{series.map((s) => (
|
||||
<td key={s.key} className="px-3 py-1.5 text-right">{fmtNum(r[s.key])}</td>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Горизонтальный рейтинг: подпись + значение + тонкая полоса (величина = один цвет) */
|
||||
export function BarList({ items, getLabel = (x) => x.name, getHref, getSub, getDot, valueLabel, empty = 'Нет данных' }) {
|
||||
if (!items?.length) return <div className="py-10 text-center text-sm text-subtle">{empty}</div>;
|
||||
const max = Math.max(...items.map((x) => x.count), 1);
|
||||
const total = items.reduce((s, x) => s + x.count, 0);
|
||||
return (
|
||||
<ol className="space-y-3">
|
||||
{items.map((x, i) => {
|
||||
const href = getHref?.(x);
|
||||
const label = getLabel(x);
|
||||
const Inner = (
|
||||
<>
|
||||
<div className="flex items-baseline justify-between gap-3 text-sm">
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
<span className="w-4 shrink-0 text-right text-xs text-subtle tnum">{i + 1}</span>
|
||||
{getDot && <span className="size-2 shrink-0 rounded-full" style={{ background: getDot(x) }} />}
|
||||
<span className={clsx('truncate text-ink', href && 'group-hover:text-brand-600 dark:group-hover:text-brand-300')}>{label}</span>
|
||||
</span>
|
||||
<span className="shrink-0 font-semibold text-ink tnum">{fmtNum(x.count)}</span>
|
||||
</div>
|
||||
{getSub?.(x) && <div className="truncate pl-6 text-xs text-muted">{getSub(x)}</div>}
|
||||
<div className="mt-1.5 ml-6 h-1.5 overflow-hidden rounded-full bg-surface-2">
|
||||
<div className="h-full rounded-full transition-all" style={{ width: `${(x.count / max) * 100}%`, background: 'var(--series-1)' }} />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
const title = `${label}: ${fmtNum(x.count)}${valueLabel ? ' ' + valueLabel : ''} (${((x.count / total) * 100).toFixed(1)}%)`;
|
||||
return (
|
||||
<li key={i} title={title}>
|
||||
{href ? (
|
||||
<Link to={href} className="group block">
|
||||
{Inner}
|
||||
</Link>
|
||||
) : (
|
||||
Inner
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
|
||||
const WD = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'];
|
||||
|
||||
/** Тепловая карта активности: дни недели × часы, последовательная шкала одного оттенка */
|
||||
export function Heatmap({ data }) {
|
||||
const [hover, setHover] = useState(null);
|
||||
const grid = Array.from({ length: 7 }, () => Array(24).fill(0));
|
||||
for (const x of data) grid[x.weekday][x.hour] += x.count;
|
||||
const max = Math.max(...grid.flat(), 1);
|
||||
const step = (v) => (v === 0 ? 0 : Math.min(7, 1 + Math.floor((v / max) * 6.999)));
|
||||
return (
|
||||
<div>
|
||||
<div className="overflow-x-auto">
|
||||
<div className="min-w-[560px]">
|
||||
<div className="grid grid-cols-[28px_repeat(24,1fr)] gap-[3px]">
|
||||
<div />
|
||||
{Array.from({ length: 24 }, (_, h) => (
|
||||
<div key={h} className="text-center text-[10px] text-subtle tnum">{h % 3 === 0 ? h : ''}</div>
|
||||
))}
|
||||
{grid.map((row, wd) => [
|
||||
<div key={`l${wd}`} className="flex items-center text-[11px] text-muted">{WD[wd]}</div>,
|
||||
...row.map((v, h) => (
|
||||
<div
|
||||
key={`${wd}-${h}`}
|
||||
onMouseEnter={() => setHover({ wd, h, v })}
|
||||
onMouseLeave={() => setHover(null)}
|
||||
className={clsx('aspect-square rounded-[4px] transition', hover?.wd === wd && hover?.h === h && 'ring-2 ring-ink')}
|
||||
style={{ background: `var(--seq-${step(v)})` }}
|
||||
/>
|
||||
)),
|
||||
])}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap items-center justify-between gap-2 text-xs text-muted">
|
||||
<span className="tnum">
|
||||
{hover ? (
|
||||
<>
|
||||
<b className="text-ink">{WD[hover.wd]}, {String(hover.h).padStart(2, '0')}:00–{String(hover.h + 1).padStart(2, '0')}:00</b> — {fmtNum(hover.v)} действий
|
||||
</>
|
||||
) : (
|
||||
'Наведите на ячейку, чтобы увидеть значение'
|
||||
)}
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
меньше
|
||||
{[0, 1, 2, 3, 4, 5, 6, 7].map((i) => (
|
||||
<span key={i} className="size-3 rounded-[3px]" style={{ background: `var(--seq-${i})` }} />
|
||||
))}
|
||||
больше
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import {
|
||||
ArrowRight, BarChart3, BookOpenCheck, Building2, FileSpreadsheet, KeyRound, ListChecks, PenLine, Search, ShieldCheck,
|
||||
} from 'lucide-react';
|
||||
import { api } from '../../lib/api';
|
||||
import { useAuth } from '../../lib/auth';
|
||||
import { Button, Spinner, ThemeToggle } from '../../components/ui';
|
||||
import { OrgLogo } from '../OrgScreens';
|
||||
|
||||
const FEATURES = [
|
||||
[KeyRound, 'Вход через Active Directory', 'Студенты и преподаватели входят паролем домена. Роли и группы — из AD.'],
|
||||
[FileSpreadsheet, 'Нет AD? Загрузите Excel', 'Система сама создаст логины и пароли и подготовит карточки для раздачи.'],
|
||||
[BookOpenCheck, 'Фонд с первого дня', 'Более ста открытых учебников уже в каталоге — добавляйте к ним свои издания.'],
|
||||
[ListChecks, 'Списки литературы', 'Преподаватели собирают литературу по дисциплинам для своих групп.'],
|
||||
[PenLine, 'Публикации', 'Статьи, курсовые и методички проходят проверку библиотекаря.'],
|
||||
[BarChart3, 'Подробная статистика', 'Кто заходит, что читают и скачивают — по факультетам, группам и дням.'],
|
||||
];
|
||||
|
||||
/** Главная платформы: найти свою библиотеку или подключить организацию */
|
||||
export default function Landing() {
|
||||
const { user, userOrg } = useAuth();
|
||||
const [q, setQ] = useState('');
|
||||
const [found, setFound] = useState(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const term = q.trim();
|
||||
if (term.length < 2) return setFound(null);
|
||||
setBusy(true);
|
||||
const t = setTimeout(() => {
|
||||
api('/orgs/search?q=' + encodeURIComponent(term))
|
||||
.then((d) => setFound(d.items))
|
||||
.catch(() => setFound([]))
|
||||
.finally(() => setBusy(false));
|
||||
}, 250);
|
||||
return () => clearTimeout(t);
|
||||
}, [q]);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen">
|
||||
<header className="mx-auto flex h-16 max-w-7xl items-center gap-3 px-4 sm:px-6">
|
||||
<img src="/favicon.svg" alt="" className="size-9" />
|
||||
<div className="leading-tight">
|
||||
<div className="text-sm font-bold">E-Library</div>
|
||||
<div className="text-[11px] text-muted">Электронные библиотеки организаций</div>
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-2">
|
||||
<ThemeToggle />
|
||||
<Link to="/register" className="hidden sm:block"><Button size="sm">Подключить организацию</Button></Link>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{user && (userOrg || user.isPlatformAdmin) && (
|
||||
<div className="mx-auto max-w-7xl px-4 sm:px-6">
|
||||
<a href={user.isPlatformAdmin ? '/platform' : `/${userOrg.slug}`} className="flex items-center gap-3 rounded-2xl border border-line bg-surface p-3 text-sm hover:border-brand-400">
|
||||
{userOrg && <OrgLogo org={userOrg} className="size-8" />}
|
||||
<span className="flex-1">
|
||||
Вы вошли как <b>{user.displayName}</b>{userOrg ? ` — ${userOrg.shortName || userOrg.name}` : ' — владелец платформы'}
|
||||
</span>
|
||||
<span className="font-medium text-brand-600 dark:text-brand-300">Открыть →</span>
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<section className="mx-auto max-w-7xl px-4 pt-10 pb-16 sm:px-6 sm:pt-16">
|
||||
<div className="hero-gradient relative overflow-hidden rounded-[2rem] p-8 text-white sm:p-14">
|
||||
<div className="grid-pattern absolute inset-0" />
|
||||
<div className="relative max-w-3xl">
|
||||
<div className="mb-4 inline-flex items-center gap-2 rounded-full bg-white/15 px-3 py-1 text-xs font-medium ring-1 ring-white/25">
|
||||
<Building2 className="size-3.5" /> Для университетов, колледжей и школ
|
||||
</div>
|
||||
<h1 className="text-4xl leading-tight font-bold tracking-tight sm:text-5xl [text-wrap:balance]">Электронная библиотека вашей организации — за один день</h1>
|
||||
<p className="mt-4 max-w-2xl text-lg text-white/80">
|
||||
Зарегистрируйте организацию, загрузите логотип, подключите Active Directory или список студентов — и откройте библиотеку по своему адресу.
|
||||
</p>
|
||||
<div className="mt-8 flex flex-wrap gap-3">
|
||||
<Link to="/register">
|
||||
<Button size="lg" className="!bg-white !text-brand-700 hover:!bg-brand-50" icon={ArrowRight}>Подключить организацию</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Найти свою библиотеку */}
|
||||
<div className="relative mt-10 max-w-xl">
|
||||
<label className="mb-2 block text-sm font-medium text-white/85" htmlFor="find">Уже учитесь или работаете? Найдите свою библиотеку</label>
|
||||
<div className="relative">
|
||||
<Search className="pointer-events-none absolute top-1/2 left-4 size-5 -translate-y-1/2 text-slate-400" />
|
||||
<input
|
||||
id="find"
|
||||
className="h-13 w-full rounded-2xl border-0 bg-white pr-12 pl-12 text-base text-slate-900 shadow-xl outline-none placeholder:text-slate-400 focus:ring-4 focus:ring-white/30"
|
||||
placeholder="Название университета или город"
|
||||
value={q}
|
||||
onChange={(e) => setQ(e.target.value)}
|
||||
autoComplete="off"
|
||||
/>
|
||||
{busy && <Spinner className="absolute top-1/2 right-4 size-5 -translate-y-1/2" />}
|
||||
</div>
|
||||
{found && (
|
||||
<div className="absolute inset-x-0 top-full z-10 mt-2 overflow-hidden rounded-2xl bg-white text-slate-900 shadow-2xl dark:bg-slate-900 dark:text-slate-100">
|
||||
{!found.length && <div className="p-4 text-sm text-slate-500">Библиотека не найдена. Спросите адрес у администратора вашей организации.</div>}
|
||||
{found.map((o) => (
|
||||
<a key={o.id} href={`/${o.slug}`} className="flex items-center gap-3 px-4 py-3 hover:bg-slate-100 dark:hover:bg-slate-800">
|
||||
<OrgLogo org={o} className="size-9" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate font-medium">{o.shortName || o.name}</div>
|
||||
<div className="truncate text-xs text-slate-500">{[o.shortName && o.name, o.city].filter(Boolean).join(' · ')}</div>
|
||||
</div>
|
||||
<span className="font-mono text-xs text-slate-400">/{o.slug}</span>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="mx-auto max-w-7xl px-4 pb-16 sm:px-6">
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{FEATURES.map(([Icon, title, text]) => (
|
||||
<div key={title} className="card p-6">
|
||||
<div className="mb-4 flex size-11 items-center justify-center rounded-xl bg-brand-50 text-brand-600 dark:bg-brand-500/15 dark:text-brand-300">
|
||||
<Icon className="size-5" />
|
||||
</div>
|
||||
<div className="font-semibold">{title}</div>
|
||||
<p className="mt-1 text-sm text-muted">{text}</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="mx-auto max-w-7xl px-4 pb-20 sm:px-6">
|
||||
<h2 className="mb-6 text-2xl font-bold tracking-tight">Как подключиться</h2>
|
||||
<div className="grid gap-4 md:grid-cols-3">
|
||||
{[
|
||||
['Заявка', 'Название, адрес библиотеки и учётная запись администратора — 3 минуты.'],
|
||||
['Настройка', 'Логотип, Active Directory или загрузка списка студентов из Excel. Можно начинать сразу, пока заявка на проверке.'],
|
||||
['Открытие', 'После одобрения студенты и преподаватели входят по адресу вашей библиотеки.'],
|
||||
].map(([t, d], i) => (
|
||||
<div key={t} className="flex gap-4 rounded-2xl border border-line p-5">
|
||||
<div className="flex size-9 shrink-0 items-center justify-center rounded-xl bg-brand-600 font-bold text-white">{i + 1}</div>
|
||||
<div>
|
||||
<div className="font-semibold">{t}</div>
|
||||
<div className="mt-1 text-sm text-muted">{d}</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-8 flex items-center gap-2 text-xs text-subtle">
|
||||
<ShieldCheck className="size-4" /> Данные каждой организации изолированы: другие организации не видят ваших пользователей, книг и статистики.
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
import { useState } from 'react';
|
||||
import clsx from 'clsx';
|
||||
import {
|
||||
AlertCircle, Building2, CheckCircle2, ChevronDown, Clock, ExternalLink, Globe, Lock, LogOut, Mail, PauseCircle, Phone,
|
||||
PlayCircle, Search, ShieldCheck, Trash2, User, Users,
|
||||
} from 'lucide-react';
|
||||
import { api, qs, useApi } from '../../lib/api';
|
||||
import { useAuth } from '../../lib/auth';
|
||||
import { EVENT_LABELS, fmtDate, fmtNum, timeAgo } from '../../lib/format';
|
||||
import { Badge, Button, Empty, ErrorBox, Modal, PageLoader, Segmented, ThemeToggle, useToast } from '../../components/ui';
|
||||
import { OrgLogo } from '../OrgScreens';
|
||||
|
||||
const STATUS = { PENDING: ['На проверке', 'amber'], ACTIVE: ['Открыта', 'green'], SUSPENDED: ['Приостановлена', 'red'] };
|
||||
|
||||
/** /platform — кабинет владельца платформы */
|
||||
export default function Platform() {
|
||||
const { user, logout } = useAuth();
|
||||
if (user === undefined) return <PageLoader />;
|
||||
if (!user?.isPlatformAdmin) return <PlatformLogin />;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen">
|
||||
<header className="sticky top-0 z-30 border-b border-line bg-surface/80 backdrop-blur-xl">
|
||||
<div className="mx-auto flex h-16 max-w-7xl items-center gap-3 px-4 sm:px-6">
|
||||
<img src="/favicon.svg" alt="" className="size-9" />
|
||||
<div className="leading-tight">
|
||||
<div className="text-sm font-bold">E-Library · платформа</div>
|
||||
<div className="text-[11px] text-muted">{user.displayName}</div>
|
||||
</div>
|
||||
<div className="ml-auto flex items-center gap-1">
|
||||
<ThemeToggle />
|
||||
<Button variant="ghost" size="sm" icon={LogOut} onClick={logout}>Выйти</Button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
<main className="mx-auto max-w-7xl p-4 sm:p-6 lg:p-8">
|
||||
<Overview />
|
||||
<Orgs />
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PlatformLogin() {
|
||||
const { user, login, logout } = useAuth();
|
||||
const [f, setF] = useState({ username: '', password: '' });
|
||||
const [error, setError] = useState('');
|
||||
const [busy, setBusy] = useState(false);
|
||||
const submit = async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
setError('');
|
||||
try {
|
||||
const u = await login(f.username, f.password);
|
||||
if (!u.isPlatformAdmin) setError('Это не учётная запись владельца платформы');
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
return (
|
||||
<div className="relative flex min-h-screen items-center justify-center p-6">
|
||||
<ThemeToggle className="absolute top-5 right-5" />
|
||||
<div className="w-full max-w-sm animate-slide-up">
|
||||
<div className="mb-8 flex items-center gap-3">
|
||||
<div className="flex size-11 items-center justify-center rounded-xl bg-slate-900 text-white dark:bg-white dark:text-slate-900"><ShieldCheck className="size-6" /></div>
|
||||
<div>
|
||||
<div className="text-lg font-bold">Управление платформой</div>
|
||||
<div className="text-sm text-muted">Только для владельца E-Library</div>
|
||||
</div>
|
||||
</div>
|
||||
{user && !user.isPlatformAdmin ? (
|
||||
<div className="space-y-4">
|
||||
<p className="text-sm text-muted">Вы вошли как {user.displayName} (пользователь организации). Чтобы войти в управление платформой, выйдите.</p>
|
||||
<Button icon={LogOut} onClick={logout}>Выйти</Button>
|
||||
</div>
|
||||
) : (
|
||||
<form onSubmit={submit} className="space-y-4">
|
||||
<div>
|
||||
<label className="label">Логин</label>
|
||||
<div className="relative">
|
||||
<User className="pointer-events-none absolute top-1/2 left-3.5 size-4 -translate-y-1/2 text-subtle" />
|
||||
<input className="input h-12 pl-10" autoFocus autoComplete="username" value={f.username} onChange={(e) => setF({ ...f, username: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Пароль</label>
|
||||
<div className="relative">
|
||||
<Lock className="pointer-events-none absolute top-1/2 left-3.5 size-4 -translate-y-1/2 text-subtle" />
|
||||
<input className="input h-12 pl-10" type="password" autoComplete="current-password" value={f.password} onChange={(e) => setF({ ...f, password: e.target.value })} />
|
||||
</div>
|
||||
</div>
|
||||
{error && <div className="flex items-start gap-2 rounded-xl bg-rose-50 p-3 text-sm text-rose-700 dark:bg-rose-500/10 dark:text-rose-300"><AlertCircle className="mt-0.5 size-4 shrink-0" />{error}</div>}
|
||||
<Button type="submit" size="lg" className="w-full" loading={busy}>Войти</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Overview() {
|
||||
const { data } = useApi('/platform/overview');
|
||||
const tiles = data && [
|
||||
['Организаций открыто', data.orgs.ACTIVE || 0, Building2],
|
||||
['Заявок на проверке', data.orgs.PENDING || 0, Clock],
|
||||
['Пользователей', data.users, Users],
|
||||
['Активных за 30 дней', data.activeUsers30, CheckCircle2],
|
||||
['Книг организаций', data.ownBooks, Building2],
|
||||
['Книг в общем фонде', data.sharedBooks, Globe],
|
||||
];
|
||||
return (
|
||||
<div className="mb-8">
|
||||
<h1 className="mb-4 text-2xl font-bold tracking-tight">Организации</h1>
|
||||
<div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-6">
|
||||
{(tiles || Array(6).fill(['…', '…', Building2])).map(([l, v, Icon], i) => (
|
||||
<div key={i} className={clsx('card p-4', i === 1 && v > 0 && 'border-amber-300 dark:border-amber-500/40')}>
|
||||
<div className="flex items-center gap-1.5 text-xs text-muted"><Icon className="size-4 text-subtle" />{l}</div>
|
||||
<div className="mt-1 text-2xl font-bold tnum">{typeof v === 'number' ? fmtNum(v) : v}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Orgs() {
|
||||
const toast = useToast();
|
||||
const [status, setStatus] = useState('PENDING');
|
||||
const [q, setQ] = useState('');
|
||||
const [search, setSearch] = useState('');
|
||||
const { data, error, loading, reload } = useApi('/platform/orgs' + qs({ status, q: search }), [status, search]);
|
||||
const [suspend, setSuspend] = useState(null);
|
||||
const [del, setDel] = useState(null);
|
||||
const [open, setOpen] = useState(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
const setOrgStatus = async (o, st, note) => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api(`/platform/orgs/${o.id}`, { method: 'PATCH', body: { status: st, note } });
|
||||
toast(st === 'ACTIVE' ? `«${o.shortName || o.name}» открыта` : 'Организация приостановлена');
|
||||
setSuspend(null);
|
||||
reload();
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="mb-4 flex flex-wrap items-center gap-3">
|
||||
<Segmented
|
||||
value={status}
|
||||
onChange={setStatus}
|
||||
options={[
|
||||
{ value: 'PENDING', label: 'Заявки' },
|
||||
{ value: 'ACTIVE', label: 'Открытые' },
|
||||
{ value: 'SUSPENDED', label: 'Приостановленные' },
|
||||
{ value: '', label: 'Все' },
|
||||
]}
|
||||
/>
|
||||
<form className="relative min-w-[220px] flex-1 sm:max-w-sm" onSubmit={(e) => { e.preventDefault(); setSearch(q.trim()); }}>
|
||||
<Search className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-subtle" />
|
||||
<input className="input pl-9" placeholder="Название, адрес, город, e-mail (Enter)" value={q} onChange={(e) => setQ(e.target.value)} />
|
||||
</form>
|
||||
</div>
|
||||
{error && <ErrorBox error={error} onRetry={reload} />}
|
||||
{loading && !data && <PageLoader />}
|
||||
{data && !data.items.length && (
|
||||
<div className="card"><Empty icon={Building2} title={status === 'PENDING' ? 'Новых заявок нет' : 'Ничего не найдено'} /></div>
|
||||
)}
|
||||
<div className="space-y-3">
|
||||
{data?.items.map((o) => (
|
||||
<div key={o.id} className="card p-5">
|
||||
<div className="flex flex-wrap items-start gap-4">
|
||||
<OrgLogo org={o} className="size-12" />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="font-semibold">{o.name}</span>
|
||||
{o.shortName && <span className="text-muted">({o.shortName})</span>}
|
||||
<Badge color={STATUS[o.status][1]}>{STATUS[o.status][0]}</Badge>
|
||||
</div>
|
||||
<div className="mt-1 flex flex-wrap gap-x-4 gap-y-1 text-xs text-muted">
|
||||
<a href={`/${o.slug}`} target="_blank" rel="noopener" className="flex items-center gap-1 font-mono hover:text-brand-600">/{o.slug}<ExternalLink className="size-3" /></a>
|
||||
{o.city && <span>{o.city}</span>}
|
||||
{o.website && <a href={o.website} target="_blank" rel="noopener noreferrer" className="flex items-center gap-1 hover:text-brand-600"><Globe className="size-3" />{o.website.replace(/^https?:\/\//, '')}</a>}
|
||||
<span>Заявка {fmtDate(o.createdAt)}</span>
|
||||
<span>{fmtNum(o.users)} польз. · {fmtNum(o.books)} книг</span>
|
||||
{o.lastActivityAt && <span>Активность {timeAgo(o.lastActivityAt)}</span>}
|
||||
</div>
|
||||
<div className="mt-2 flex flex-wrap gap-x-4 gap-y-1 text-sm">
|
||||
<span className="flex items-center gap-1"><User className="size-3.5 text-subtle" />{o.contactName}</span>
|
||||
{o.contactEmail && <a href={`mailto:${o.contactEmail}`} className="flex items-center gap-1 text-brand-600 dark:text-brand-300"><Mail className="size-3.5" />{o.contactEmail}</a>}
|
||||
{o.contactPhone && <span className="flex items-center gap-1"><Phone className="size-3.5 text-subtle" />{o.contactPhone}</span>}
|
||||
</div>
|
||||
{o.statusNote && <div className="mt-2 rounded-lg bg-surface-2 px-3 py-1.5 text-xs text-muted">{o.statusNote}</div>}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{o.status !== 'ACTIVE' && <Button size="sm" icon={o.status === 'PENDING' ? CheckCircle2 : PlayCircle} disabled={busy} onClick={() => setOrgStatus(o, 'ACTIVE')}>{o.status === 'PENDING' ? 'Одобрить' : 'Возобновить'}</Button>}
|
||||
{o.status !== 'SUSPENDED' && <Button size="sm" variant="secondary" icon={PauseCircle} onClick={() => setSuspend({ org: o, note: '' })}>{o.status === 'PENDING' ? 'Отклонить' : 'Приостановить'}</Button>}
|
||||
{o.status !== 'ACTIVE' && <Button size="sm" variant="ghost" icon={Trash2} className="hover:!text-rose-600" onClick={() => setDel({ org: o, confirm: '' })}>Удалить</Button>}
|
||||
<Button size="sm" variant="ghost" icon={ChevronDown} onClick={() => setOpen(open === o.id ? null : o.id)} className={clsx(open === o.id && '[&_svg]:rotate-180')}>Подробнее</Button>
|
||||
</div>
|
||||
</div>
|
||||
{open === o.id && <OrgDetails id={o.id} />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
open={!!suspend}
|
||||
onClose={() => setSuspend(null)}
|
||||
title={suspend?.org.status === 'PENDING' ? 'Отклонить заявку' : 'Приостановить организацию'}
|
||||
size="sm"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setSuspend(null)}>Отмена</Button>
|
||||
<Button variant="danger" loading={busy} disabled={!suspend?.note.trim()} onClick={() => setOrgStatus(suspend.org, 'SUSPENDED', suspend.note)}>Приостановить</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<p className="mb-3 text-sm text-muted">Пользователи организации не смогут войти, открытые сеансы завершатся. Данные сохранятся — организацию можно возобновить.</p>
|
||||
<label className="label">Причина (увидит администратор организации) *</label>
|
||||
<textarea className="input h-24 py-2" value={suspend?.note || ''} onChange={(e) => setSuspend({ ...suspend, note: e.target.value })} />
|
||||
</Modal>
|
||||
|
||||
<Modal
|
||||
open={!!del}
|
||||
onClose={() => setDel(null)}
|
||||
title="Удалить организацию навсегда?"
|
||||
size="sm"
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={() => setDel(null)}>Отмена</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
loading={busy}
|
||||
disabled={del?.confirm !== del?.org.slug}
|
||||
onClick={async () => {
|
||||
setBusy(true);
|
||||
try {
|
||||
await api(`/platform/orgs/${del.org.id}`, { method: 'DELETE', body: { confirm: del.confirm } });
|
||||
toast('Организация удалена');
|
||||
setDel(null);
|
||||
reload();
|
||||
} catch (e) {
|
||||
toast(e.message, 'error');
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
Удалить
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<p className="mb-3 text-sm text-muted">
|
||||
Будут удалены все пользователи, книги с файлами, списки литературы и статистика «{del?.org.name}». Это нельзя отменить.
|
||||
</p>
|
||||
<label className="label">Для подтверждения введите адрес: <b className="font-mono text-ink">{del?.org.slug}</b></label>
|
||||
<input className="input font-mono" value={del?.confirm || ''} onChange={(e) => setDel({ ...del, confirm: e.target.value })} />
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function OrgDetails({ id }) {
|
||||
const { data, error } = useApi(`/platform/orgs/${id}`, [id]);
|
||||
if (error) return <div className="mt-4"><ErrorBox error={error} /></div>;
|
||||
if (!data) return <div className="mt-4 h-20 animate-pulse rounded-xl bg-surface-2" />;
|
||||
const a = data.activity30;
|
||||
return (
|
||||
<div className="mt-4 grid gap-4 border-t border-line pt-4 text-sm md:grid-cols-3">
|
||||
<div>
|
||||
<div className="mb-2 text-xs font-semibold tracking-wider text-subtle uppercase">Администраторы</div>
|
||||
{data.admins.map((u) => (
|
||||
<div key={u.id} className="py-1">
|
||||
<div className="font-medium">{u.displayName} <span className="font-mono text-xs text-muted">{u.username}</span></div>
|
||||
<div className="text-xs text-muted">{u.email || '—'} · вход {u.lastLoginAt ? timeAgo(u.lastLoginAt) : 'ещё не входил'}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-2 text-xs font-semibold tracking-wider text-subtle uppercase">Подключение</div>
|
||||
<div className="py-1">Active Directory: {data.org.ldapUrl ? <span className="font-mono text-xs">{data.org.ldapUrl}</span> : 'не подключён'}</div>
|
||||
<div className="py-1">Пользователи из AD: {fmtNum(data.usersBySource.LDAP || 0)}, с паролем библиотеки: {fmtNum(data.usersBySource.LOCAL || 0)}</div>
|
||||
<div className="py-1">Списков литературы: {fmtNum(data.org.counts.lists)}</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-2 text-xs font-semibold tracking-wider text-subtle uppercase">Активность за 30 дней</div>
|
||||
{['LOGIN', 'VIEW', 'READ', 'DOWNLOAD', 'SEARCH'].map((k) => (
|
||||
<div key={k} className="flex justify-between py-0.5"><span className="text-muted">{EVENT_LABELS[k]}</span><b className="tnum">{fmtNum(a[k] || 0)}</b></div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import clsx from 'clsx';
|
||||
import { ArrowLeft, Building2, Check, CheckCircle2, ImagePlus, Loader2, Send, Trash2, UserCog, XCircle } from 'lucide-react';
|
||||
import { api, upload } from '../../lib/api';
|
||||
import { Button, ThemeToggle } from '../../components/ui';
|
||||
|
||||
/** Регистрация организации. После отправки — сразу вход администратором и настройка библиотеки */
|
||||
export default function Register() {
|
||||
const [f, setF] = useState({
|
||||
name: '', shortName: '', slug: '', city: '', website: '',
|
||||
contactName: '', contactEmail: '', contactPhone: '', username: 'admin', password: '', repeat: '', website2: '',
|
||||
});
|
||||
const [slugTouched, setSlugTouched] = useState(false);
|
||||
const [slugState, setSlugState] = useState(null); // null | 'checking' | {available, error}
|
||||
const [logo, setLogo] = useState(null);
|
||||
const [agree, setAgree] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const fileRef = useRef();
|
||||
const set = (k) => (e) => setF({ ...f, [k]: e.target.value });
|
||||
const origin = window.location.origin.replace(/^https?:\/\//, '');
|
||||
|
||||
// предложить адрес по названию, пока его не поменяли вручную
|
||||
useEffect(() => {
|
||||
if (slugTouched || f.name.trim().length < 3) return;
|
||||
const t = setTimeout(() => {
|
||||
api(`/orgs/suggest-slug?name=${encodeURIComponent(f.name)}&shortName=${encodeURIComponent(f.shortName)}`)
|
||||
.then((d) => setF((x) => ({ ...x, slug: d.slug })))
|
||||
.catch(() => {});
|
||||
}, 400);
|
||||
return () => clearTimeout(t);
|
||||
}, [f.name, f.shortName, slugTouched]);
|
||||
|
||||
// проверка занятости адреса
|
||||
useEffect(() => {
|
||||
if (!f.slug) return setSlugState(null);
|
||||
setSlugState('checking');
|
||||
const t = setTimeout(() => {
|
||||
api('/orgs/check-slug?slug=' + encodeURIComponent(f.slug))
|
||||
.then(setSlugState)
|
||||
.catch(() => setSlugState(null));
|
||||
}, 350);
|
||||
return () => clearTimeout(t);
|
||||
}, [f.slug]);
|
||||
|
||||
const submit = async (e) => {
|
||||
e.preventDefault();
|
||||
setError('');
|
||||
if (f.password !== f.repeat) return setError('Пароли не совпадают');
|
||||
if (!agree) return setError('Подтвердите согласие с условиями');
|
||||
setBusy(true);
|
||||
const fd = new FormData();
|
||||
Object.entries(f).forEach(([k, v]) => k !== 'repeat' && fd.append(k, v));
|
||||
fd.append('agree', 'true');
|
||||
if (logo) fd.append('logo', logo);
|
||||
try {
|
||||
const d = await upload('/orgs/register', 'POST', fd);
|
||||
// библиотека организации — отдельное приложение со своим адресом
|
||||
window.location.href = `/${d.org.slug}/admin/settings?welcome=1`;
|
||||
} catch (err) {
|
||||
setError(err.message);
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
|
||||
const slugOk = slugState && slugState !== 'checking' && slugState.available;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen pb-16">
|
||||
<header className="mx-auto flex h-16 max-w-3xl items-center gap-3 px-4 sm:px-6">
|
||||
<Link to="/" className="flex items-center gap-2 text-sm text-muted hover:text-ink">
|
||||
<ArrowLeft className="size-4" /> E-Library
|
||||
</Link>
|
||||
<ThemeToggle className="ml-auto" />
|
||||
</header>
|
||||
<form onSubmit={submit} className="mx-auto max-w-3xl px-4 sm:px-6">
|
||||
<h1 className="text-3xl font-bold tracking-tight">Подключение организации</h1>
|
||||
<p className="mt-1 text-muted">
|
||||
Заполните заявку — и сразу сможете настроить библиотеку. Студенты и преподаватели получат доступ после проверки заявки администратором платформы.
|
||||
</p>
|
||||
{error && <div className="mt-6 rounded-xl bg-rose-50 p-3 text-sm text-rose-700 dark:bg-rose-500/10 dark:text-rose-300">{error}</div>}
|
||||
|
||||
{/* ловушка для ботов — человек это поле не видит */}
|
||||
<input type="text" name="website2" value={f.website2} onChange={set('website2')} tabIndex={-1} autoComplete="off" className="hidden" aria-hidden="true" />
|
||||
|
||||
<section className="card mt-6 space-y-4 p-6">
|
||||
<h2 className="flex items-center gap-2 font-semibold"><Building2 className="size-5 text-brand-500" />1. Организация</h2>
|
||||
<div>
|
||||
<label className="label">Полное название *</label>
|
||||
<input className="input" value={f.name} onChange={set('name')} placeholder="Ташкентский государственный экономический университет" required />
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div>
|
||||
<label className="label">Краткое название</label>
|
||||
<input className="input" value={f.shortName} onChange={set('shortName')} placeholder="ТГЭУ" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Город</label>
|
||||
<input className="input" value={f.city} onChange={set('city')} placeholder="Ташкент" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Адрес библиотеки *</label>
|
||||
<div className={clsx('flex items-center overflow-hidden rounded-xl border bg-surface transition focus-within:ring-2 focus-within:ring-brand-500/30',
|
||||
slugState && slugState !== 'checking' ? (slugState.available ? 'border-emerald-400' : 'border-rose-400') : 'border-line')}>
|
||||
<span className="border-r border-line bg-surface-2 px-3 py-2.5 text-sm text-muted">{origin}/</span>
|
||||
<input
|
||||
className="h-11 min-w-0 flex-1 bg-transparent px-3 font-mono text-sm outline-none"
|
||||
value={f.slug}
|
||||
onChange={(e) => { setSlugTouched(true); setF({ ...f, slug: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, '') }); }}
|
||||
placeholder="tsue"
|
||||
maxLength={30}
|
||||
required
|
||||
/>
|
||||
<span className="px-3">
|
||||
{slugState === 'checking' ? <Loader2 className="size-4 animate-spin text-subtle" /> : slugState?.available ? <CheckCircle2 className="size-4 text-emerald-500" /> : slugState ? <XCircle className="size-4 text-rose-500" /> : null}
|
||||
</span>
|
||||
</div>
|
||||
<p className={clsx('mt-1 text-xs', slugState?.error ? 'text-rose-600' : 'text-subtle')}>
|
||||
{slugState?.error || 'Латинские буквы, цифры и дефис. По этому адресу студенты будут входить в библиотеку.'}
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-[1fr_auto]">
|
||||
<div>
|
||||
<label className="label">Сайт организации</label>
|
||||
<input className="input" value={f.website} onChange={set('website')} placeholder="https://tsue.uz" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Логотип</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<button type="button" onClick={() => fileRef.current.click()} className="flex size-11 items-center justify-center overflow-hidden rounded-xl border border-dashed border-line bg-surface-2 hover:border-brand-400">
|
||||
{logo ? <img src={URL.createObjectURL(logo)} alt="" className="size-full bg-white object-contain" /> : <ImagePlus className="size-5 text-subtle" />}
|
||||
</button>
|
||||
{logo && <button type="button" onClick={() => setLogo(null)} className="text-muted hover:text-rose-600"><Trash2 className="size-4" /></button>}
|
||||
<input ref={fileRef} type="file" accept="image/png,image/jpeg,image/webp" hidden onChange={(e) => e.target.files[0] && setLogo(e.target.files[0])} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="card mt-6 space-y-4 p-6">
|
||||
<h2 className="flex items-center gap-2 font-semibold"><UserCog className="size-5 text-violet-500" />2. Администратор библиотеки</h2>
|
||||
<p className="-mt-2 text-sm text-muted">Учётная запись для управления библиотекой. Остальных пользователей добавите позже — через AD или списком.</p>
|
||||
<div>
|
||||
<label className="label">ФИО ответственного *</label>
|
||||
<input className="input" value={f.contactName} onChange={set('contactName')} placeholder="Каримов Рустам Алишерович" required />
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div>
|
||||
<label className="label">E-mail *</label>
|
||||
<input className="input" type="email" value={f.contactEmail} onChange={set('contactEmail')} required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Телефон</label>
|
||||
<input className="input" value={f.contactPhone} onChange={set('contactPhone')} placeholder="+998 90 123-45-67" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<div>
|
||||
<label className="label">Логин *</label>
|
||||
<input className="input font-mono" value={f.username} onChange={(e) => setF({ ...f, username: e.target.value.toLowerCase() })} autoComplete="username" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Пароль *</label>
|
||||
<input className="input" type="password" value={f.password} onChange={set('password')} autoComplete="new-password" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="label">Повтор пароля *</label>
|
||||
<input className="input" type="password" value={f.repeat} onChange={set('repeat')} autoComplete="new-password" required />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-3 text-xs">
|
||||
{[[f.password.length >= 8, 'не короче 8 символов'], [/[a-zа-я]/i.test(f.password) && /\d/.test(f.password), 'буквы и цифры'], [f.password && f.password === f.repeat, 'пароли совпадают']].map(([ok, l]) => (
|
||||
<span key={l} className={clsx('flex items-center gap-1', ok ? 'text-emerald-600 dark:text-emerald-400' : 'text-subtle')}><Check className="size-3.5" />{l}</span>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="card mt-6 p-6">
|
||||
<label className="flex cursor-pointer items-start gap-3 text-sm">
|
||||
<input type="checkbox" checked={agree} onChange={(e) => setAgree(e.target.checked)} className="mt-0.5 size-4 accent-brand-600" />
|
||||
<span>
|
||||
Я представляю эту организацию и имею право подключить её к платформе. Организация отвечает за размещаемые материалы и соблюдение авторских прав,
|
||||
а также за персональные данные загружаемых пользователей.
|
||||
</span>
|
||||
</label>
|
||||
<div className="mt-5 flex justify-end">
|
||||
<Button type="submit" size="lg" icon={Send} loading={busy} disabled={!slugOk}>Отправить заявку</Button>
|
||||
</div>
|
||||
</section>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import tailwindcss from '@tailwindcss/vite';
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: { '/api': 'http://localhost:4000' },
|
||||
},
|
||||
build: { chunkSizeWarningLimit: 1200 },
|
||||
});
|
||||
Reference in New Issue
Block a user