E-Library: платформа электронных библиотек для организаций

- Каталог, чтение онлайн, кабинеты студента и преподавателя, списки литературы, публикации
- Организации: регистрация, логотип, адрес /<slug>, одобрение владельцем платформы
- Вход через Active Directory (настройки у каждой организации) или по логинам из загруженного списка
- Изоляция данных организаций, общий открытый фонд книг, статистика

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shukhrat Khamraev
2026-11-23 10:35:19 +05:00
commit 3ac99350be
163 changed files with 20042 additions and 0 deletions
+321
View File
@@ -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>
);
}