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
+149
View File
@@ -0,0 +1,149 @@
import { Router } from 'express';
import bcrypt from 'bcryptjs';
import rateLimit, { ipKeyGenerator } from 'express-rate-limit';
import { prismaBase, publicUser, effectiveKind } from '../db.js';
import { config } from '../config.js';
import { issueSession, clearSession, requireAuth, orgAccessError } from '../middleware/auth.js';
import { ldapAuthenticate, LdapUnavailableError, LdapForbiddenError } from '../services/ldap.js';
import { ldapConfigOf, publicOrg } from '../services/orgs.js';
import { hashPassword, passwordProblem } from '../services/accounts.js';
import { logEvent } from '../services/events.js';
const router = Router();
/** DOMAIN\user, user@domain → user */
const normalizeUsername = (s) =>
String(s || '')
.trim()
.replace(/^.*\\/, '')
.replace(/@.*$/, '')
.toLowerCase()
.slice(0, 100);
const orgSlug = (req) => String(req.body?.org || '').trim().toLowerCase().slice(0, 40);
// Считаем только неудачные попытки: в университете целые компьютерные классы выходят
// в интернет через один IP, и успешные входы студентов не должны блокировать друг друга.
const LIMIT_MSG = { error: 'Слишком много неудачных попыток входа. Повторите через 15 минут.' };
// подбор пароля к одной учётной записи
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 10,
skipSuccessfulRequests: true,
keyGenerator: (req) => `${ipKeyGenerator(req.ip)}|${orgSlug(req)}|${normalizeUsername(req.body?.username)}`,
standardHeaders: true,
legacyHeaders: false,
message: LIMIT_MSG,
});
// перебор многих учётных записей с одного адреса
const loginIpLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 300,
skipSuccessfulRequests: true,
standardHeaders: true,
legacyHeaders: false,
message: LIMIT_MSG,
});
router.post('/login', loginIpLimiter, loginLimiter, async (req, res) => {
const username = normalizeUsername(req.body?.username);
const password = String(req.body?.password || '');
const slug = orgSlug(req);
// вкладка на странице входа: «Студент» или «Преподаватель»
const claim = req.body?.kind === 'TEACHER' ? 'TEACHER' : 'STUDENT';
if (!username || !password) return res.status(400).json({ error: 'Введите логин и пароль' });
let org = null;
const fail = async (status, error, reason, userId) => {
await logEvent(req, 'LOGIN_FAILED', { userId: userId ?? null, organizationId: org?.id ?? null, meta: { username, reason, org: slug || null } });
return res.status(status).json({ error });
};
try {
let user;
if (!slug) {
// вход владельца платформы (страница /platform) — только локальная учётная запись
user = await prismaBase.user.findFirst({ where: { organizationId: null, isPlatformAdmin: true, username } });
if (!user?.passwordHash || !(await bcrypt.compare(password, user.passwordHash))) return fail(401, 'Неверный логин или пароль', 'bad_password', user?.id);
} else {
org = await prismaBase.organization.findUnique({ where: { slug } });
if (!org) return res.status(404).json({ error: 'Библиотека не найдена' });
if (org.status === 'SUSPENDED') return fail(403, orgAccessError({}, org), 'org_suspended');
user = await prismaBase.user.findUnique({ where: { organizationId_username: { organizationId: org.id, username } } });
const L = ldapConfigOf(org);
if (user?.source === 'LOCAL') {
// учётные записи без AD: созданные администратором, импортированные из списка, администратор организации
if (!config.localAuthEnabled || !user.passwordHash) return fail(401, 'Неверный логин или пароль', 'local_disabled', user.id);
if (!(await bcrypt.compare(password, user.passwordHash))) return fail(401, 'Неверный логин или пароль', 'bad_password', user.id);
} else if (L.enabled) {
const info = await ldapAuthenticate(L, username, password);
if (!info) return fail(401, 'Неверный логин или пароль', 'bad_credentials', user?.id);
const isNew = !user;
// если AD не определил тип — запоминаем выбор пользователя (преподаватель требует подтверждения)
const kindClaim = info.kind ? null : claim === 'TEACHER' ? 'TEACHER' : null;
user = await prismaBase.user.upsert({
where: { organizationId_username: { organizationId: org.id, username: info.username } },
create: { ...info, kindClaim, source: 'LDAP', organizationId: org.id },
update: { ...info, kindClaim },
});
if (isNew) await logEvent(req, 'REGISTER', { userId: user.id, userKind: effectiveKind(user), organizationId: org.id });
} else {
return fail(401, 'Неверный логин или пароль', 'unknown_user', user?.id);
}
}
if (user.isBlocked) return fail(403, 'Учётная запись заблокирована администратором', 'blocked', user.id);
const denied = orgAccessError(user, org);
if (denied) return fail(403, denied, 'org_' + org?.status?.toLowerCase(), user.id);
user = await prismaBase.user.update({
where: { id: user.id },
data: { lastLoginAt: new Date(), lastSeenAt: new Date(), loginCount: { increment: 1 } },
});
await logEvent(req, 'LOGIN', { userId: user.id, userKind: effectiveKind(user), organizationId: org?.id ?? null, meta: { tab: claim } });
issueSession(res, user);
res.json({ user: publicUser(user), org: publicOrg(org) });
} catch (e) {
if (e instanceof LdapForbiddenError) return fail(403, e.message, 'not_in_allowed_group');
if (e instanceof LdapUnavailableError) {
console.error(`LDAP unavailable (${slug}):`, e.message);
return fail(503, 'Сервер Active Directory вашей организации недоступен. Попробуйте позже.', 'ldap_unavailable');
}
console.error('Login error:', e);
return fail(500, 'Ошибка входа', 'error');
}
});
router.post('/logout', async (req, res) => {
if (req.user) await logEvent(req, 'LOGOUT');
clearSession(res);
res.json({ ok: true });
});
router.get('/me', requireAuth, (req, res) => {
res.json({ user: publicUser(req.user), org: publicOrg(req.org) });
});
// Смена пароля (локальные учётные записи; пароль AD меняется в домене)
const changeLimiter = rateLimit({ windowMs: 15 * 60 * 1000, limit: 10, keyGenerator: (req) => `u${req.user?.id}`, message: LIMIT_MSG });
router.post('/change-password', requireAuth, changeLimiter, async (req, res) => {
const user = await prismaBase.user.findUnique({ where: { id: req.user.id } });
if (user.source !== 'LOCAL' || !user.passwordHash)
return res.status(400).json({ error: 'Пароль учётной записи домена меняется в Active Directory (Ctrl+Alt+Del → «Изменить пароль»)' });
const current = String(req.body?.currentPassword || '');
const next = String(req.body?.newPassword || '');
if (!(await bcrypt.compare(current, user.passwordHash))) return res.status(400).json({ error: 'Текущий пароль указан неверно' });
const problem = passwordProblem(next, user.username);
if (problem) return res.status(400).json({ error: problem });
if (next === current) return res.status(400).json({ error: 'Новый пароль должен отличаться от текущего' });
const updated = await prismaBase.user.update({
where: { id: user.id },
data: { passwordHash: await hashPassword(next), mustChangePassword: false, tokenVersion: { increment: 1 } },
});
// старые сессии (на других устройствах) завершаются, текущая — продолжается с новым токеном
issueSession(res, updated);
logEvent(req, 'PASSWORD_CHANGE');
res.json({ user: publicUser(updated) });
});
export default router;
+328
View File
@@ -0,0 +1,328 @@
import { Router } from 'express';
import multer from 'multer';
import path from 'node:path';
import fs from 'node:fs';
import crypto from 'node:crypto';
import { prisma, prismaBase } from '../db.js';
import { config } from '../config.js';
import { requireAuth, requireRole, hasRole, keepTenant } from '../middleware/auth.js';
import { logEvent } from '../services/events.js';
const router = Router();
export const BOOKS_DIR = path.join(config.storageDir, 'books');
export const COVERS_DIR = path.join(config.storageDir, 'covers');
fs.mkdirSync(BOOKS_DIR, { recursive: true });
fs.mkdirSync(COVERS_DIR, { recursive: true });
const BOOK_EXT = ['.pdf', '.odt', '.epub', '.djvu', '.doc', '.docx', '.ppt', '.pptx', '.xls', '.xlsx', '.rtf', '.txt', '.zip', '.rar', '.mp3', '.mp4'];
const COVER_EXT = ['.jpg', '.jpeg', '.png', '.webp'];
const MIME = { '.pdf': 'application/pdf', '.epub': 'application/epub+zip', '.txt': 'text/plain; charset=utf-8', '.mp4': 'video/mp4', '.mp3': 'audio/mpeg' };
const upload = multer({
storage: multer.diskStorage({
destination: (req, file, cb) => cb(null, file.fieldname === 'cover' ? COVERS_DIR : BOOKS_DIR),
filename: (req, file, cb) => cb(null, crypto.randomUUID() + path.extname(file.originalname).toLowerCase()),
}),
limits: { fileSize: config.maxUploadMb * 1024 * 1024 },
fileFilter: (req, file, cb) => {
// multer отдаёт имя в latin1 — восстанавливаем UTF-8 (кириллица)
file.originalname = Buffer.from(file.originalname, 'latin1').toString('utf8');
const ext = path.extname(file.originalname).toLowerCase();
const ok = file.fieldname === 'cover' ? COVER_EXT.includes(ext) : BOOK_EXT.includes(ext);
cb(ok ? null : new Error(`Недопустимый тип файла: ${ext || 'без расширения'}`), ok);
},
}).fields([
{ name: 'file', maxCount: 1 },
{ name: 'cover', maxCount: 1 },
]);
// keepTenant: multer вызывает next() из событий потока — без него терялся бы контекст организации
export const uploadMw = keepTenant((req, res, next) =>
upload(req, res, (err) => (err ? res.status(400).json({ error: err.message }) : next())));
export const removeFile = (dir, name) => name && fs.promises.unlink(path.join(dir, path.basename(name))).catch(() => {});
/** Видимость: опубликовано — всем; автору — всегда; модератору и научному руководителю — всё, кроме черновиков */
export const canSee = (req, b) =>
b.isPublished ||
b.createdById === req.user?.id ||
(b.status !== 'DRAFT' && (hasRole(req, 'MODERATOR') || (b.supervisorId && b.supervisorId === req.user?.id)));
export function serializeBook(b) {
const { filePath, coverPath, searchText, ...rest } = b;
return {
...rest,
shared: b.organizationId === null, // общий фонд платформы — организация не может его менять
hasFile: !!filePath,
hasCover: !!coverPath,
fileExt: filePath ? path.extname(filePath).slice(1).toLowerCase() : null,
coverUrl: coverPath ? `/api/books/${b.id}/cover?v=${b.updatedAt?.getTime?.() || 0}` : null,
};
}
const buildSearchText = (b) =>
[b.title, b.subtitle, b.authors, b.keywords, b.isbn, b.publisher, b.udc, b.year].filter(Boolean).join(' ').toLowerCase();
const intOrNull = (v) => (v === '' || v == null || isNaN(Number(v)) ? null : Math.trunc(Number(v)));
const strOrNull = (v) => (v == null || String(v).trim() === '' ? null : String(v).trim());
export function bookData(body) {
const d = {
title: String(body.title || '').trim(),
subtitle: strOrNull(body.subtitle),
authors: String(body.authors || '').trim(),
description: strOrNull(body.description),
isbn: strOrNull(body.isbn),
udc: strOrNull(body.udc),
publisher: strOrNull(body.publisher),
year: intOrNull(body.year),
language: strOrNull(body.language) || 'ru',
type: strOrNull(body.type) || 'textbook',
pages: intOrNull(body.pages),
keywords: strOrNull(body.keywords),
categoryId: intOrNull(body.categoryId),
supervisor: strOrNull(body.supervisor),
isPublished: body.isPublished === undefined ? true : String(body.isPublished) === 'true',
};
d.searchText = buildSearchText(d) + (d.supervisor ? ' ' + d.supervisor.toLowerCase() : '');
return d;
}
// ---------- Список / поиск ----------
router.get('/', requireAuth, async (req, res) => {
const page = Math.max(1, Number(req.query.page) || 1);
const limit = Math.min(100, Math.max(1, Number(req.query.limit) || 24));
const q = String(req.query.q || '').trim().toLowerCase().slice(0, 200);
const showAll = req.query.all === '1' && hasRole(req, 'MODERATOR');
const where = { AND: [] };
if (!showAll) where.isPublished = true;
else where.status = { not: 'DRAFT' }; // черновики студентов видны только автору
if (req.query.source === 'USER' || req.query.source === 'LIBRARY') where.source = req.query.source;
// фонд: own — книги организации, shared — общий открытый фонд платформы
if (req.query.fund === 'own') where.organizationId = { not: null };
else if (req.query.fund === 'shared') where.organizationId = null;
if (q) for (const t of q.split(/\s+/).slice(0, 8)) where.AND.push({ searchText: { contains: t } });
if (req.query.category) where.categoryId = Number(req.query.category);
if (req.query.language) where.language = String(req.query.language);
if (req.query.type) where.type = String(req.query.type);
if (req.query.yearFrom) where.AND.push({ year: { gte: Number(req.query.yearFrom) } });
if (req.query.yearTo) where.AND.push({ year: { lte: Number(req.query.yearTo) } });
const orderBy =
{
popular: [{ downloadCount: 'desc' }, { viewCount: 'desc' }],
views: [{ viewCount: 'desc' }],
title: [{ title: 'asc' }],
year: [{ year: 'desc' }],
}[req.query.sort] || [{ createdAt: 'desc' }];
const [total, items] = await Promise.all([
prisma.book.count({ where }),
prisma.book.findMany({
where,
orderBy,
skip: (page - 1) * limit,
take: limit,
include: { category: { select: { id: true, name: true, color: true } } },
}),
]);
// Журналируем только явный поиск (Enter / кнопка), а не каждое нажатие клавиши
if (q && req.query.log === '1' && page === 1) {
logEvent(req, 'SEARCH', { query: q, resultCount: total });
}
res.json({ items: items.map(serializeBook), total, page, pages: Math.ceil(total / limit) });
});
// Фильтры для каталога
router.get('/facets', requireAuth, async (req, res) => {
const where = { isPublished: true };
const [languages, types, years] = await Promise.all([
prisma.book.groupBy({ by: ['language'], where, _count: { _all: true } }),
prisma.book.groupBy({ by: ['type'], where, _count: { _all: true } }),
prisma.book.aggregate({ where, _min: { year: true }, _max: { year: true } }),
]);
res.json({
languages: languages.map((l) => ({ value: l.language, count: l._count._all })),
types: types.map((t) => ({ value: t.type, count: t._count._all })),
minYear: years._min.year,
maxYear: years._max.year,
});
});
// ---------- Карточка книги ----------
router.get('/:id', requireAuth, async (req, res) => {
const id = Number(req.params.id);
const book = await prisma.book.findUnique({
where: { id },
include: {
category: true,
createdBy: { select: { id: true, displayName: true, department: true, studyGroup: true, kind: true, kindOverride: true } },
reviewedBy: { select: { id: true, displayName: true } },
supervisorRef: { select: { id: true, displayName: true, title: true, department: true } },
},
});
if (!book || !canSee(req, book)) return res.status(404).json({ error: 'Книга не найдена' });
if (book.createdBy) {
book.createdBy.kind = book.createdBy.kindOverride || book.createdBy.kind;
delete book.createdBy.kindOverride;
}
const [fav, related] = await Promise.all([
prisma.favorite.findUnique({ where: { userId_bookId: { userId: req.user.id, bookId: id } } }),
book.categoryId
? prisma.book.findMany({
where: { categoryId: book.categoryId, isPublished: true, NOT: { id } },
orderBy: { downloadCount: 'desc' },
take: 6,
include: { category: { select: { id: true, name: true, color: true } } },
})
: [],
// счётчики общих книг тоже растут — поэтому без ограничения организацией (книга уже проверена canSee)
prismaBase.book.update({ where: { id }, data: { viewCount: { increment: 1 } } }),
]);
logEvent(req, 'VIEW', { bookId: id });
res.json({ book: { ...serializeBook(book), isFavorite: !!fav }, related: related.map(serializeBook) });
});
async function getFileBook(req, res) {
const book = await prisma.book.findUnique({ where: { id: Number(req.params.id) } });
if (!book || !book.filePath || !canSee(req, book)) {
res.status(404).json({ error: 'Файл не найден' });
return null;
}
const full = path.join(BOOKS_DIR, path.basename(book.filePath));
if (!fs.existsSync(full)) {
res.status(404).json({ error: 'Файл отсутствует в хранилище' });
return null;
}
return { book, full };
}
// Скачивание
router.get('/:id/download', requireAuth, async (req, res) => {
const r = await getFileBook(req, res);
if (!r) return;
await prismaBase.book.update({ where: { id: r.book.id }, data: { downloadCount: { increment: 1 } } });
logEvent(req, 'DOWNLOAD', { bookId: r.book.id });
const ext = path.extname(r.book.filePath);
const name = r.book.fileName || `${r.book.title}${ext}`;
res.download(r.full, name);
});
// Чтение онлайн (inline, с поддержкой Range для PDF-просмотрщика)
router.get('/:id/read', requireAuth, async (req, res) => {
const r = await getFileBook(req, res);
if (!r) return;
const range = req.headers.range;
if (!range || /^bytes=0-/.test(range)) {
// засчитываем открытие не чаще раза в 30 минут на пользователя/книгу
const recent = await prisma.event.findFirst({
where: { type: 'READ', userId: req.user.id, bookId: r.book.id, createdAt: { gte: new Date(Date.now() - 30 * 60_000) } },
select: { id: true },
});
if (!recent) logEvent(req, 'READ', { bookId: r.book.id });
}
const ext = path.extname(r.full).toLowerCase();
res.setHeader('Content-Type', MIME[ext] || 'application/octet-stream');
res.setHeader('Content-Disposition', `inline; filename*=UTF-8''${encodeURIComponent(r.book.fileName || 'file' + ext)}`);
res.sendFile(r.full, { acceptRanges: true });
});
router.get('/:id/cover', requireAuth, async (req, res) => {
const book = await prisma.book.findUnique({ where: { id: Number(req.params.id) }, select: { coverPath: true } });
if (!book?.coverPath) return res.status(404).end();
res.setHeader('Cache-Control', 'private, max-age=604800');
res.sendFile(path.join(COVERS_DIR, path.basename(book.coverPath)), (err) => err && !res.headersSent && res.status(404).end());
});
// Избранное
router.post('/:id/favorite', requireAuth, async (req, res) => {
const bookId = Number(req.params.id);
// только книги, видимые организации пользователя
if (!(await prisma.book.count({ where: { id: bookId, isPublished: true } }))) return res.status(404).json({ error: 'Книга не найдена' });
await prisma.favorite.upsert({
where: { userId_bookId: { userId: req.user.id, bookId } },
create: { userId: req.user.id, bookId },
update: {},
});
logEvent(req, 'FAVORITE', { bookId });
res.json({ ok: true });
});
router.delete('/:id/favorite', requireAuth, async (req, res) => {
await prisma.favorite.deleteMany({ where: { userId: req.user.id, bookId: Number(req.params.id) } });
res.json({ ok: true });
});
// ---------- Управление (модераторы) ----------
router.post('/', requireRole('MODERATOR'), uploadMw, async (req, res) => {
const file = req.files?.file?.[0];
const cover = req.files?.cover?.[0];
const data = bookData(req.body);
if (!data.title || !data.authors) {
removeFile(BOOKS_DIR, file?.filename);
removeFile(COVERS_DIR, cover?.filename);
return res.status(400).json({ error: 'Укажите название и авторов' });
}
const book = await prisma.book.create({
data: {
...data,
organizationId: req.user.organizationId,
createdById: req.user.id,
...(file && { filePath: file.filename, fileName: file.originalname, fileSize: file.size, mimeType: file.mimetype }),
...(cover && { coverPath: cover.filename }),
},
});
logEvent(req, 'BOOK_CREATE', { bookId: book.id, meta: { title: book.title } });
res.status(201).json({ book: serializeBook(book) });
});
router.put('/:id', requireRole('MODERATOR'), uploadMw, async (req, res) => {
const id = Number(req.params.id);
const old = await prisma.book.findUnique({ where: { id } });
const file = req.files?.file?.[0];
if (!old || old.organizationId !== req.user.organizationId) {
removeFile(BOOKS_DIR, file?.filename);
removeFile(COVERS_DIR, req.files?.cover?.[0]?.filename);
return res.status(old ? 403 : 404).json({ error: old ? 'Книги общего фонда меняет только администратор платформы' : 'Книга не найдена' });
}
const cover = req.files?.cover?.[0];
const data = bookData(req.body);
if (!data.title || !data.authors) return res.status(400).json({ error: 'Укажите название и авторов' });
if (file) removeFile(BOOKS_DIR, old.filePath);
if (cover || req.body.removeCover === 'true') removeFile(COVERS_DIR, old.coverPath);
// синхронизация статуса модерации с флагом публикации
data.status = data.isPublished ? 'PUBLISHED' : old.status === 'PUBLISHED' ? 'PENDING' : old.status;
const book = await prisma.book.update({
where: { id },
data: {
...data,
...(file && { filePath: file.filename, fileName: file.originalname, fileSize: file.size, mimeType: file.mimetype }),
...(cover ? { coverPath: cover.filename } : req.body.removeCover === 'true' ? { coverPath: null } : {}),
},
});
logEvent(req, 'BOOK_UPDATE', { bookId: id, meta: { title: book.title } });
res.json({ book: serializeBook(book) });
});
router.delete('/:id', requireRole('MODERATOR'), async (req, res) => {
const id = Number(req.params.id);
const book = await prisma.book.findUnique({ where: { id } });
if (!book) return res.status(404).json({ error: 'Книга не найдена' });
if (book.organizationId !== req.user.organizationId) return res.status(403).json({ error: 'Книги общего фонда удаляет только администратор платформы' });
await prisma.book.delete({ where: { id } });
removeFile(BOOKS_DIR, book.filePath);
removeFile(COVERS_DIR, book.coverPath);
logEvent(req, 'BOOK_DELETE', { meta: { id, title: book.title } });
res.json({ ok: true });
});
export default router;
+231
View File
@@ -0,0 +1,231 @@
/**
* Личный кабинет: студента (литература по группе, прогресс, публикации)
* и преподавателя (списки литературы, охват студентов, работы под руководством, статистика материалов)
*/
import { Router } from 'express';
import { prisma, publicUser, effectiveKind, normGroup } from '../db.js';
import { requireAuth, requireTeacher } from '../middleware/auth.js';
import { logEvent } from '../services/events.js';
import { dayKey, addDays, daysBetween } from '../services/time.js';
import { serializeBook } from './books.js';
import { groupsOf, listSummary } from './lists.js';
const router = Router();
router.use(requireAuth);
const catInc = { category: { select: { id: true, name: true, color: true } } };
const OPENED = ['READ', 'DOWNLOAD'];
/** Где-то 6 последних открытых книг — «Продолжить чтение» */
async function recentBooks(userId, take = 6) {
const ev = await prisma.event.findMany({
where: { userId, type: { in: ['VIEW', 'READ', 'DOWNLOAD'] }, bookId: { not: null } },
orderBy: { createdAt: 'desc' },
take: 200,
select: { bookId: true, createdAt: true },
});
const ids = [];
const at = new Map();
for (const e of ev) if (!at.has(e.bookId)) { at.set(e.bookId, e.createdAt); ids.push(e.bookId); }
const books = await prisma.book.findMany({ where: { id: { in: ids.slice(0, 30) }, isPublished: true }, include: catInc });
const bm = new Map(books.map((b) => [b.id, b]));
return ids.filter((id) => bm.has(id)).slice(0, take).map((id) => ({ ...serializeBook(bm.get(id)), lastAt: at.get(id) }));
}
/** Активность пользователя за 30 дней (для мини-графика) */
async function activity30(userId) {
const to = dayKey();
const from = addDays(to, -29);
const rows = await prisma.event.groupBy({
by: ['day'],
where: { userId, day: { gte: from, lte: to }, type: { in: ['VIEW', 'READ', 'DOWNLOAD', 'SEARCH'] } },
_count: { _all: true },
});
const m = new Map(rows.map((r) => [r.day, r._count._all]));
return daysBetween(from, to).map((d) => ({ day: d, count: m.get(d) || 0 }));
}
/** Популярное у однокурсников (та же группа, иначе — то же подразделение) за 60 дней */
async function popularAmongPeers(user) {
const peer = user.studyGroup ? { studyGroup: user.studyGroup } : user.department ? { department: user.department } : null;
if (!peer) return { by: null, items: [] };
const rows = await prisma.event.groupBy({
by: ['bookId'],
where: { type: { in: OPENED }, bookId: { not: null }, day: { gte: addDays(dayKey(), -59) }, user: peer, NOT: { userId: user.id } },
_count: { _all: true },
orderBy: { _count: { bookId: 'desc' } },
take: 12,
});
const books = await prisma.book.findMany({ where: { id: { in: rows.map((r) => r.bookId) }, isPublished: true }, include: catInc });
const bm = new Map(books.map((b) => [b.id, b]));
return {
by: user.studyGroup ? `группа ${user.studyGroup}` : user.department,
items: rows.filter((r) => bm.has(r.bookId)).slice(0, 6).map((r) => ({ ...serializeBook(bm.get(r.bookId)), peerCount: r._count._all })),
};
}
router.get('/', async (req, res) => {
const me = req.user;
const kind = effectiveKind(me);
const [byType, favCount, pubs, recent, activity] = await Promise.all([
prisma.event.groupBy({ by: ['type'], where: { userId: me.id, type: { in: ['VIEW', 'READ', 'DOWNLOAD', 'SEARCH', 'LOGIN'] } }, _count: { _all: true } }),
prisma.favorite.count({ where: { userId: me.id, book: { isPublished: true } } }),
prisma.book.groupBy({ by: ['status'], where: { createdById: me.id, source: 'USER' }, _count: { _all: true } }),
recentBooks(me.id),
activity30(me.id),
]);
const counts = Object.fromEntries(byType.map((t) => [t.type, t._count._all]));
const out = {
user: publicUser(me),
kind,
counts: { ...counts, favorites: favCount },
publications: Object.fromEntries(pubs.map((p) => [p.status, p._count._all])),
recent,
activity,
};
if (kind === 'TEACHER') {
// --- Кабинет преподавателя ---
const [lists, supCounts, supRecent, materials] = await Promise.all([
prisma.readingList.findMany({
where: { ownerId: me.id },
orderBy: { updatedAt: 'desc' },
include: { _count: { select: { items: true } }, items: { select: { bookId: true } } },
}),
prisma.book.groupBy({ by: ['status'], where: { supervisorId: me.id, status: { not: 'DRAFT' } }, _count: { _all: true } }),
prisma.book.findMany({
where: { supervisorId: me.id, status: { not: 'DRAFT' } },
orderBy: [{ submittedAt: 'desc' }],
take: 6,
include: { ...catInc, createdBy: { select: { id: true, displayName: true, studyGroup: true, department: true } } },
}),
prisma.book.findMany({
where: { createdById: me.id, source: 'USER', status: 'PUBLISHED' },
orderBy: { downloadCount: 'desc' },
include: catInc,
}),
]);
// Охват: сколько студентов из групп списка открывали/скачивали книги списка за 30 дней
const since = addDays(dayKey(), -29);
out.lists = await Promise.all(
lists.map(async (l) => {
const groups = groupsOf(l);
const bookIds = l.items.map((i) => i.bookId);
let students = 0;
let reached = 0;
if (groups.length) {
const [st, ev] = await Promise.all([
prisma.user.count({ where: { studyGroup: { in: groups } } }),
bookIds.length
? prisma.event.groupBy({
by: ['userId'],
where: { type: { in: OPENED }, bookId: { in: bookIds }, day: { gte: since }, user: { studyGroup: { in: groups } } },
})
: [],
]);
students = st;
reached = ev.length;
}
return { ...listSummary(l), students, reached };
})
);
out.supervised = {
counts: Object.fromEntries(supCounts.map((c) => [c.status, c._count._all])),
awaiting: await prisma.book.count({ where: { supervisorId: me.id, status: 'PENDING', endorsedAt: null } }),
recent: supRecent.map((b) => ({ ...serializeBook(b), createdBy: b.createdBy })),
};
out.materials = {
count: materials.length,
views: materials.reduce((s, b) => s + b.viewCount, 0),
downloads: materials.reduce((s, b) => s + b.downloadCount, 0),
top: materials.slice(0, 5).map(serializeBook),
};
} else {
// --- Кабинет студента / сотрудника ---
const lists = me.studyGroup
? await prisma.readingList.findMany({
where: { groups: { contains: `,${me.studyGroup},` } },
orderBy: { updatedAt: 'desc' },
include: {
owner: { select: { id: true, displayName: true, title: true, department: true } },
_count: { select: { items: true } },
items: { select: { bookId: true, required: true, book: { select: { isPublished: true } } } },
},
})
: [];
// прогресс: какие книги из списков студент уже открывал
const allIds = [...new Set(lists.flatMap((l) => l.items.map((i) => i.bookId)))];
const opened = allIds.length
? new Set(
(await prisma.event.groupBy({ by: ['bookId'], where: { userId: me.id, type: { in: OPENED }, bookId: { in: allIds } } })).map((r) => r.bookId)
)
: new Set();
out.lists = lists.map((l) => {
const visible = l.items.filter((i) => i.book.isPublished);
return {
...listSummary(l),
owner: l.owner,
total: visible.length,
required: visible.filter((i) => i.required).length,
done: visible.filter((i) => opened.has(i.bookId)).length,
};
});
out.peers = await popularAmongPeers(me);
}
res.json(out);
});
// Профиль: группа и курс (если их не заполняет AD)
router.patch('/profile', async (req, res) => {
const data = {};
if ('studyGroup' in req.body) data.studyGroup = normGroup(req.body.studyGroup);
if ('course' in req.body) {
const c = parseInt(req.body.course, 10);
data.course = c >= 1 && c <= 7 ? c : null;
}
const user = await prisma.user.update({ where: { id: req.user.id }, data });
res.json({ user: publicUser(user) });
});
// Поиск преподавателей — для выбора научного руководителя
router.get('/teachers', async (req, res) => {
const q = String(req.query.q || '').trim().slice(0, 60);
const teacher = { OR: [{ kindOverride: 'TEACHER' }, { kindOverride: null, kind: 'TEACHER' }], isBlocked: false };
const where = q
? { AND: [teacher, { OR: ['displayName', 'username', 'department'].map((f) => ({ [f]: { contains: q, mode: 'insensitive' } })) }] }
: teacher;
const items = await prisma.user.findMany({
where,
orderBy: { displayName: 'asc' },
take: 15,
select: { id: true, displayName: true, title: true, department: true },
});
res.json({ items });
});
// ---------- Работы под моим руководством ----------
router.get('/supervised', requireTeacher, async (req, res) => {
const status = ['PENDING', 'PUBLISHED', 'REJECTED'].includes(req.query.status) ? req.query.status : undefined;
const items = await prisma.book.findMany({
where: { supervisorId: req.user.id, status: status || { not: 'DRAFT' } },
orderBy: [{ submittedAt: 'desc' }],
take: 200,
include: { ...catInc, createdBy: { select: { id: true, displayName: true, studyGroup: true, department: true } } },
});
res.json({ items: items.map((b) => ({ ...serializeBook(b), createdBy: b.createdBy })) });
});
// Руководитель подтверждает работу студента (модератор видит отметку в очереди)
router.post('/supervised/:id/endorse', requireTeacher, async (req, res) => {
const id = Number(req.params.id);
const b = await prisma.book.findFirst({ where: { id, supervisorId: req.user.id, status: { not: 'DRAFT' } } });
if (!b) return res.status(404).json({ error: 'Работа не найдена' });
const endorse = req.body?.endorse !== false;
await prisma.book.update({ where: { id }, data: { endorsedAt: endorse ? new Date() : null } });
if (endorse) logEvent(req, 'ENDORSE', { bookId: id, meta: { title: b.title } });
res.json({ ok: true, endorsedAt: endorse ? new Date() : null });
});
export default router;
+68
View File
@@ -0,0 +1,68 @@
import { Router } from 'express';
import { prisma, prismaBase } from '../db.js';
import { requireAuth, requireRole } from '../middleware/auth.js';
const router = Router();
const TR = { а:'a',б:'b',в:'v',г:'g',д:'d',е:'e',ё:'e',ж:'zh',з:'z',и:'i',й:'y',к:'k',л:'l',м:'m',н:'n',о:'o',п:'p',р:'r',с:'s',т:'t',у:'u',ф:'f',х:'h',ц:'c',ч:'ch',ш:'sh',щ:'sch',ъ:'',ы:'y',ь:'',э:'e',ю:'yu',я:'ya',ў:'o',қ:'q',ғ:'g',ҳ:'h' };
export const slugify = (s) =>
String(s)
.toLowerCase()
.split('')
.map((c) => TR[c] ?? c)
.join('')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '') || `cat-${Date.now()}`;
// Разделы: общие (платформы) + свои. Число книг — только видимых организации
router.get('/', requireAuth, async (req, res) => {
const [cats, counts] = await Promise.all([
prisma.category.findMany({ orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }] }),
prisma.book.groupBy({ by: ['categoryId'], where: { isPublished: true, categoryId: { not: null } }, _count: { _all: true } }),
]);
const cm = new Map(counts.map((c) => [c.categoryId, c._count._all]));
res.json({ items: cats.map((c) => ({ ...c, shared: c.organizationId === null, bookCount: cm.get(c.id) || 0 })) });
});
/** Менять можно только разделы своей организации (общие — владелец платформы) */
async function ownCategory(req, res) {
const c = await prisma.category.findUnique({ where: { id: Number(req.params.id) } });
if (!c) return res.status(404).json({ error: 'Раздел не найден' }), null;
if (c.organizationId !== (req.user.organizationId ?? null))
return res.status(403).json({ error: 'Это общий раздел платформы — его нельзя изменить' }), null;
return c;
}
const data = (b) => ({
name: String(b.name || '').trim(),
description: b.description?.trim() || null,
color: /^#[0-9a-f]{6}$/i.test(b.color) ? b.color : '#6366f1',
icon: String(b.icon || 'BookOpen').slice(0, 40),
sortOrder: Number(b.sortOrder) || 0,
});
router.post('/', requireRole('MODERATOR'), async (req, res) => {
const d = data(req.body);
if (!d.name) return res.status(400).json({ error: 'Введите название' });
let slug = slugify(d.name);
// slug уникален на всю платформу
if (await prismaBase.category.findUnique({ where: { slug } })) slug += '-' + Date.now().toString(36);
res.status(201).json({ item: await prisma.category.create({ data: { ...d, slug } }) });
});
router.put('/:id', requireRole('MODERATOR'), async (req, res) => {
const d = data(req.body);
if (!d.name) return res.status(400).json({ error: 'Введите название' });
const c = await ownCategory(req, res);
if (!c) return;
res.json({ item: await prisma.category.update({ where: { id: c.id }, data: d }) });
});
router.delete('/:id', requireRole('MODERATOR'), async (req, res) => {
const c = await ownCategory(req, res);
if (!c) return;
await prisma.category.delete({ where: { id: c.id } });
res.json({ ok: true });
});
export default router;
+236
View File
@@ -0,0 +1,236 @@
/**
* Списки литературы преподавателей: дисциплина → книги из фонда (основная / дополнительная),
* привязка к академическим группам — студенты видят списки своей группы в кабинете.
*/
import { Router } from 'express';
import { prisma, normGroup } from '../db.js';
import { requireAuth, requireTeacher, hasRole } from '../middleware/auth.js';
import { logEvent } from '../services/events.js';
import { serializeBook } from './books.js';
const router = Router();
router.use(requireAuth);
const MAX_LISTS = 100;
const MAX_ITEMS = 200;
/** ",ИС-21-01,ИС-21-02," ⇄ ['ИС-21-01','ИС-21-02'] */
export const groupsOf = (l) => String(l.groups || '').split(',').filter(Boolean);
const packGroups = (v) => {
const arr = (Array.isArray(v) ? v : String(v || '').split(/[,;\n]/)).map(normGroup).filter(Boolean);
return ',' + [...new Set(arr)].slice(0, 30).join(',') + (arr.length ? ',' : '');
};
export const listSummary = (l) => ({
id: l.id,
title: l.title,
description: l.description,
semester: l.semester,
isPublic: l.isPublic,
groups: groupsOf(l),
itemCount: l._count?.items ?? l.items?.length ?? 0,
ownerId: l.ownerId,
updatedAt: l.updatedAt,
createdAt: l.createdAt,
});
const ownerSel = { select: { id: true, displayName: true, title: true, department: true } };
const canEdit = (req, l) => l.ownerId === req.user.id || hasRole(req, 'ADMIN');
const canView = (req, l) =>
l.isPublic || canEdit(req, l) || hasRole(req, 'MODERATOR') || (req.user.studyGroup && groupsOf(l).includes(req.user.studyGroup));
function listData(body) {
const title = String(body.title || '').trim().slice(0, 200);
return {
title,
description: String(body.description || '').trim().slice(0, 2000) || null,
semester: String(body.semester || '').trim().slice(0, 60) || null,
groups: packGroups(body.groups),
isPublic: body.isPublic !== false,
};
}
// Каталог списков: ?scope=mine|group|all &q=
router.get('/', async (req, res) => {
const scope = req.query.scope || 'all';
const q = String(req.query.q || '').trim().slice(0, 80);
const where = { AND: [] };
if (scope === 'mine') where.ownerId = req.user.id;
else if (scope === 'group') {
if (!req.user.studyGroup) return res.json({ items: [] });
where.groups = { contains: `,${req.user.studyGroup},` };
} else if (!hasRole(req, 'MODERATOR')) {
where.AND.push({
OR: [{ isPublic: true }, { ownerId: req.user.id }, ...(req.user.studyGroup ? [{ groups: { contains: `,${req.user.studyGroup},` } }] : [])],
});
}
if (q) {
const ci = { contains: q, mode: 'insensitive' };
where.AND.push({ OR: [{ title: ci }, { description: ci }, { groups: { contains: normGroup(q) } }, { owner: { displayName: ci } }, { owner: { department: ci } }] });
}
const items = await prisma.readingList.findMany({
where,
orderBy: { updatedAt: 'desc' },
take: 200,
include: { owner: ownerSel, _count: { select: { items: true } } },
});
res.json({ items: items.map((l) => ({ ...listSummary(l), owner: l.owner })) });
});
// Мои списки с отметкой, есть ли в них книга (для кнопки «В список литературы»)
router.get('/for-book/:bookId', requireTeacher, async (req, res) => {
const bookId = Number(req.params.bookId);
const lists = await prisma.readingList.findMany({
where: { ownerId: req.user.id },
orderBy: { updatedAt: 'desc' },
include: { _count: { select: { items: true } }, items: { where: { bookId }, select: { id: true, required: true } } },
});
res.json({ items: lists.map((l) => ({ ...listSummary(l), has: l.items.length > 0, required: l.items[0]?.required ?? true })) });
});
router.get('/:id', async (req, res) => {
const l = await prisma.readingList.findUnique({
where: { id: Number(req.params.id) },
include: {
owner: ownerSel,
items: {
orderBy: [{ required: 'desc' }, { position: 'asc' }, { id: 'asc' }],
include: { book: { include: { category: { select: { id: true, name: true, color: true } } } } },
},
},
});
if (!l || !canView(req, l)) return res.status(404).json({ error: 'Список не найден' });
const editable = canEdit(req, l);
const items = l.items.filter((i) => i.book.isPublished || editable);
// отметки «я уже открывал» для студента
const opened = new Set(
(
await prisma.event.groupBy({
by: ['bookId'],
where: { userId: req.user.id, type: { in: ['READ', 'DOWNLOAD'] }, bookId: { in: items.map((i) => i.bookId) } },
})
).map((r) => r.bookId)
);
// статистика для автора: сколько студентов групп открыли каждую книгу
let reach = null;
const groups = groupsOf(l);
if (editable && groups.length && items.length) {
const [students, rows] = await Promise.all([
prisma.user.count({ where: { studyGroup: { in: groups } } }),
prisma.event.groupBy({
by: ['bookId', 'userId'],
where: { type: { in: ['READ', 'DOWNLOAD'] }, bookId: { in: items.map((i) => i.bookId) }, user: { studyGroup: { in: groups } } },
}),
]);
const per = {};
const all = new Set();
for (const r of rows) {
per[r.bookId] = (per[r.bookId] || 0) + 1;
all.add(r.userId);
}
reach = { students, reached: all.size, perBook: per };
}
res.json({
list: { ...listSummary({ ...l, _count: { items: items.length } }), owner: l.owner },
editable,
reach,
items: items.map((i) => ({
id: i.id,
required: i.required,
note: i.note,
opened: opened.has(i.bookId),
book: serializeBook(i.book),
})),
});
});
router.post('/', requireTeacher, async (req, res) => {
if (!req.user.organizationId) return res.status(403).json({ error: 'Списки ведут преподаватели организаций' });
const data = listData(req.body || {});
if (data.title.length < 3) return res.status(400).json({ error: 'Укажите название дисциплины (не короче 3 символов)' });
if ((await prisma.readingList.count({ where: { ownerId: req.user.id } })) >= MAX_LISTS)
return res.status(429).json({ error: `Не более ${MAX_LISTS} списков на преподавателя` });
const l = await prisma.readingList.create({ data: { ...data, ownerId: req.user.id } });
// сразу добавить книгу, если список создан из карточки книги
const bookId = Number(req.body?.bookId);
if (bookId && (await prisma.book.count({ where: { id: bookId, isPublished: true } })))
await prisma.readingListItem.create({ data: { listId: l.id, bookId } });
logEvent(req, 'LIST_CREATE', { meta: { listId: l.id, title: l.title, groups: groupsOf(l) } });
res.status(201).json({ list: listSummary(l) });
});
async function ownList(req, res) {
const l = await prisma.readingList.findUnique({ where: { id: Number(req.params.id) } });
if (!l || !canEdit(req, l)) {
res.status(404).json({ error: 'Список не найден' });
return null;
}
return l;
}
router.put('/:id', requireTeacher, async (req, res) => {
const l = await ownList(req, res);
if (!l) return;
const data = listData(req.body || {});
if (data.title.length < 3) return res.status(400).json({ error: 'Укажите название дисциплины (не короче 3 символов)' });
const upd = await prisma.readingList.update({ where: { id: l.id }, data });
res.json({ list: listSummary(upd) });
});
router.delete('/:id', requireTeacher, async (req, res) => {
const l = await ownList(req, res);
if (!l) return;
await prisma.readingList.delete({ where: { id: l.id } });
res.json({ ok: true });
});
// Книги в списке
router.post('/:id/items', requireTeacher, async (req, res) => {
const l = await ownList(req, res);
if (!l) return;
const bookId = Number(req.body?.bookId);
// опубликованные издания — любые; свои загруженные — и до проверки (студенты увидят их после публикации)
if (!(await prisma.book.count({ where: { id: bookId, OR: [{ isPublished: true }, { createdById: req.user.id, source: 'USER' }] } })))
return res.status(400).json({ error: 'Издание не найдено' });
if ((await prisma.readingListItem.count({ where: { listId: l.id } })) >= MAX_ITEMS)
return res.status(400).json({ error: `В списке не может быть больше ${MAX_ITEMS} изданий` });
const last = await prisma.readingListItem.aggregate({ where: { listId: l.id }, _max: { position: true } });
const item = await prisma.readingListItem.upsert({
where: { listId_bookId: { listId: l.id, bookId } },
create: {
listId: l.id,
bookId,
required: req.body?.required !== false,
note: String(req.body?.note || '').trim().slice(0, 500) || null,
position: (last._max.position ?? 0) + 1,
},
update: { ...('required' in (req.body || {}) && { required: req.body.required !== false }) },
});
await prisma.readingList.update({ where: { id: l.id }, data: { updatedAt: new Date() } });
res.status(201).json({ item });
});
router.patch('/:id/items/:bookId', requireTeacher, async (req, res) => {
const l = await ownList(req, res);
if (!l) return;
const data = {};
if ('required' in req.body) data.required = !!req.body.required;
if ('note' in req.body) data.note = String(req.body.note || '').trim().slice(0, 500) || null;
if ('position' in req.body) data.position = Number(req.body.position) || 0;
const r = await prisma.readingListItem.updateMany({ where: { listId: l.id, bookId: Number(req.params.bookId) }, data });
if (!r.count) return res.status(404).json({ error: 'Издание не найдено в списке' });
res.json({ ok: true });
});
router.delete('/:id/items/:bookId', requireTeacher, async (req, res) => {
const l = await ownList(req, res);
if (!l) return;
await prisma.readingListItem.deleteMany({ where: { listId: l.id, bookId: Number(req.params.bookId) } });
await prisma.readingList.update({ where: { id: l.id }, data: { updatedAt: new Date() } });
res.json({ ok: true });
});
export default router;
+43
View File
@@ -0,0 +1,43 @@
import { Router } from 'express';
import { prisma } from '../db.js';
import { requireAuth } from '../middleware/auth.js';
import { serializeBook } from './books.js';
const router = Router();
router.use(requireAuth);
const inc = { category: { select: { id: true, name: true, color: true } } };
router.get('/favorites', async (req, res) => {
const favs = await prisma.favorite.findMany({
where: { userId: req.user.id },
orderBy: { createdAt: 'desc' },
include: { book: { include: inc } },
});
res.json({ items: favs.filter((f) => f.book.isPublished).map((f) => ({ ...serializeBook(f.book), favoritedAt: f.createdAt })) });
});
// История: последние открытые / скачанные книги (уникальные)
router.get('/history', async (req, res) => {
const events = await prisma.event.findMany({
where: { userId: req.user.id, type: { in: ['VIEW', 'READ', 'DOWNLOAD'] }, bookId: { not: null } },
orderBy: { createdAt: 'desc' },
take: 500,
select: { bookId: true, type: true, createdAt: true },
});
const seen = new Map();
for (const e of events) {
const s = seen.get(e.bookId) || { lastAt: e.createdAt, downloaded: false, read: false };
if (e.type === 'DOWNLOAD') s.downloaded = true;
if (e.type === 'READ') s.read = true;
seen.set(e.bookId, s);
}
const ids = [...seen.keys()].slice(0, 100);
const books = await prisma.book.findMany({ where: { id: { in: ids }, isPublished: true }, include: inc });
const byId = new Map(books.map((b) => [b.id, b]));
res.json({
items: ids.filter((id) => byId.has(id)).map((id) => ({ ...serializeBook(byId.get(id)), ...seen.get(id) })),
});
});
export default router;
+308
View File
@@ -0,0 +1,308 @@
/**
* Администратор организации: профиль библиотеки, Active Directory,
* учётные записи без AD (импорт списка, создание, сброс паролей, лист с логинами).
* Все запросы — в контексте организации администратора (db.js), чужие данные недоступны.
*/
import { Router } from 'express';
import multer from 'multer';
import rateLimit from 'express-rate-limit';
import { prisma, prismaBase, KINDS, ROLES } from '../db.js';
import { requireOrgAdmin, keepTenant } from '../middleware/auth.js';
import { logEvent } from '../services/events.js';
import { encrypt, decrypt } from '../services/crypto.js';
import { ldapAuthenticate, ldapTest, explain, LdapForbiddenError, LdapUnavailableError } from '../services/ldap.js';
import { LOGOS_DIR, publicOrg, normalizeLdap, ldapError, ldapForForm, DEFAULT_USER_FILTER } from '../services/orgs.js';
import {
readTable, normalizeRow, baseLogin, makeLoginAllocator, genPassword, hashTempPassword,
credentialsWorkbook, templateWorkbook, MAX_IMPORT_ROWS,
} from '../services/accounts.js';
import { removeFile } from './books.js';
import { logoMw } from './orgs.js';
const router = Router();
router.use(requireOrgAdmin);
const str = (v, max = 200) => String(v ?? '').replace(/\s+/g, ' ').trim().slice(0, max);
const orgOf = (req) => prismaBase.organization.findUnique({ where: { id: req.user.organizationId } });
// ---------- Профиль организации ----------
async function settingsPayload(org) {
const [users, bySource, books, mustChange] = await Promise.all([
prisma.user.count(),
prisma.user.groupBy({ by: ['source'], _count: { _all: true } }),
prisma.book.count({ where: { organizationId: { not: null } } }),
prisma.user.count({ where: { mustChangePassword: true } }),
]);
return {
org: {
...publicOrg(org),
city: org.city,
website: org.website,
contactName: org.contactName,
contactEmail: org.contactEmail,
contactPhone: org.contactPhone,
statusNote: org.statusNote,
createdAt: org.createdAt,
approvedAt: org.approvedAt,
},
ldap: ldapForForm(org),
counts: { users, books, mustChange, bySource: Object.fromEntries(bySource.map((x) => [x.source, x._count._all])) },
};
}
router.get('/settings', async (req, res) => {
res.json(await settingsPayload(await orgOf(req)));
});
router.put('/settings', logoMw, async (req, res) => {
const b = req.body || {};
const org = await orgOf(req);
const name = str(b.name);
if (name.length < 5) {
removeFile(LOGOS_DIR, req.file?.filename);
return res.status(400).json({ error: 'Укажите полное название организации' });
}
let website = str(b.website) || null;
if (website && !/^https?:\/\//i.test(website)) website = 'https://' + website;
const removeLogo = b.removeLogo === 'true';
if (req.file || removeLogo) removeFile(LOGOS_DIR, org.logoPath);
const upd = await prismaBase.organization.update({
where: { id: org.id },
data: {
name,
shortName: str(b.shortName, 60) || null,
city: str(b.city, 80) || null,
website,
contactName: str(b.contactName, 120) || null,
contactEmail: str(b.contactEmail, 120).toLowerCase() || null,
contactPhone: str(b.contactPhone, 40) || null,
...(req.file ? { logoPath: req.file.filename } : removeLogo ? { logoPath: null } : {}),
},
});
logEvent(req, 'ORG_UPDATE', { meta: { section: 'profile' } });
res.json(await settingsPayload(upd));
});
// ---------- Active Directory ----------
/** Конфигурация из формы; пароль — новый из формы или сохранённый */
function formLdap(body, org) {
const cfg = normalizeLdap(body);
cfg.userFilter = cfg.userFilter || DEFAULT_USER_FILTER;
cfg.bindPassword = body.bindPassword ? String(body.bindPassword) : body.clearBindPassword ? '' : decrypt(org.ldapBindSecret);
return cfg;
}
router.put('/ldap', async (req, res) => {
const org = await orgOf(req);
const b = req.body || {};
const ldap = normalizeLdap(b);
if (ldap.enabled) {
const err = ldapError(ldap);
if (err) return res.status(400).json({ error: err });
if (ldap.bindDN && !b.bindPassword && !org.ldapBindSecret) return res.status(400).json({ error: 'Укажите пароль сервисной учётной записи' });
}
const secret = b.bindPassword ? encrypt(String(b.bindPassword)) : b.clearBindPassword || !ldap.bindDN ? null : org.ldapBindSecret;
const upd = await prismaBase.organization.update({ where: { id: org.id }, data: { ldap, ldapBindSecret: secret } });
logEvent(req, 'ORG_UPDATE', { meta: { section: 'ldap', enabled: ldap.enabled, url: ldap.url } });
res.json(await settingsPayload(upd));
});
const ldapTestLimiter = rateLimit({ windowMs: 15 * 60 * 1000, limit: 30, keyGenerator: (req) => `o${req.user.organizationId}`, message: { error: 'Слишком много проверок. Подождите несколько минут.' } });
router.post('/ldap/test', ldapTestLimiter, async (req, res) => {
const cfg = formLdap(req.body || {}, await orgOf(req));
const err = ldapError(cfg);
if (err) return res.json({ ok: false, message: err });
res.json(await ldapTest(cfg));
});
// Проверка входа конкретного пользователя: что система получит из AD (роль, тип, группа)
router.post('/ldap/test-user', ldapTestLimiter, async (req, res) => {
const b = req.body || {};
const cfg = formLdap(b, await orgOf(req));
const err = ldapError(cfg);
if (err) return res.json({ ok: false, message: err });
const username = str(b.testUsername, 100).replace(/^.*\\/, '').replace(/@.*$/, '').toLowerCase();
if (!username || !b.testPassword) return res.json({ ok: false, message: 'Введите логин и пароль пользователя домена' });
try {
const info = await ldapAuthenticate(cfg, username, String(b.testPassword));
if (!info) return res.json({ ok: false, message: 'Пользователь не найден, отключён или пароль неверный' });
res.json({ ok: true, message: 'Вход выполнен успешно', profile: info });
} catch (e) {
if (e instanceof LdapForbiddenError || e instanceof LdapUnavailableError) return res.json({ ok: false, message: e.message });
res.json({ ok: false, message: explain(e) });
}
});
// ---------- Импорт списка пользователей ----------
const importUpload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: 10 * 1024 * 1024, files: 1 },
}).single('file');
const importMw = keepTenant((req, res, next) =>
importUpload(req, res, (err) => (err ? res.status(400).json({ error: err.code === 'LIMIT_FILE_SIZE' ? 'Файл больше 10 МБ' : err.message }) : next()))
);
router.get('/import/template.xlsx', async (req, res) => {
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent('Шаблон списка пользователей.xlsx')}`);
res.send(Buffer.from(await templateWorkbook()));
});
// Шаг 1: файл → столбцы и строки (ничего не сохраняется)
router.post('/import/preview', importMw, async (req, res) => {
if (!req.file) return res.status(400).json({ error: 'Выберите файл' });
try {
const name = Buffer.from(req.file.originalname, 'latin1').toString('utf8');
res.json(await readTable(req.file.buffer, name));
} catch (e) {
res.status(400).json({ error: e.message?.includes('zip') || e.message?.includes('Corrupted') ? 'Не удалось прочитать файл Excel' : e.message });
}
});
const nameKey = (displayName, group) => `${String(displayName).toLowerCase().replace(/ё/g, 'е')}|${group || ''}`;
/**
* Шаг 2: проверка (dryRun) и создание. Совпадения ищем по ID (зачётка/HEMIS),
* иначе по ФИО + группе — повторная загрузка того же списка не создаёт дублей.
*/
async function planImport(rows, defaultKind) {
const existing = await prisma.user.findMany({ select: { id: true, username: true, displayName: true, studyGroup: true, employeeId: true } });
const byEmp = new Map(existing.filter((u) => u.employeeId).map((u) => [u.employeeId, u]));
const byName = new Map(existing.map((u) => [nameKey(u.displayName, u.studyGroup), u]));
const alloc = makeLoginAllocator(existing.map((u) => u.username));
const seen = new Set();
return rows.map((raw, i) => {
const n = normalizeRow(raw || {}, defaultKind);
const base = { row: i + 1, displayName: n.displayName, studyGroup: n.studyGroup, course: n.course, kind: n.kind };
if (n.error) return { ...base, status: 'error', message: n.error };
const key = n.employeeId ? `id:${n.employeeId}` : nameKey(n.displayName, n.studyGroup);
const ex = (n.employeeId && byEmp.get(n.employeeId)) || byName.get(nameKey(n.displayName, n.studyGroup));
if (ex) return { ...base, status: 'exists', username: ex.username, message: 'Уже есть в системе' };
if (seen.has(key)) return { ...base, status: 'duplicate', message: 'Повтор строки в файле' };
seen.add(key);
return { ...base, status: 'new', username: alloc(baseLogin(n)), data: n };
});
}
const summarize = (plan) => ({
total: plan.length,
new: plan.filter((x) => x.status === 'new').length,
exists: plan.filter((x) => x.status === 'exists').length,
duplicate: plan.filter((x) => x.status === 'duplicate').length,
error: plan.filter((x) => x.status === 'error').length,
});
/** Создание учётных записей; возвращает пароли (показываются один раз) */
async function createAccounts(req, items, role = 'USER') {
const created = [];
for (let i = 0; i < items.length; i += 200) {
const chunk = items.slice(i, i + 200);
const data = [];
for (const it of chunk) {
const password = genPassword();
it.password = password;
const d = it.data;
data.push({
organizationId: req.user.organizationId,
username: it.username,
displayName: d.displayName,
email: d.email,
department: d.department,
employeeId: d.employeeId,
studyGroup: d.studyGroup,
course: d.course,
kind: d.kind,
title: d.kind === 'STUDENT' && d.studyGroup ? `Студент группы ${d.studyGroup}` : null,
role,
source: 'LOCAL',
passwordHash: await hashTempPassword(password),
mustChangePassword: true,
});
}
await prisma.user.createMany({ data, skipDuplicates: true });
// если логин успели занять параллельно — запись пропущена; такие строки помечаем ошибкой
const got = await prisma.user.findMany({ where: { username: { in: chunk.map((x) => x.username) } }, select: { id: true, username: true, displayName: true } });
const gm = new Map(got.map((u) => [u.username, u]));
for (const it of chunk) {
const u = gm.get(it.username);
if (u && u.displayName === it.data.displayName) created.push({ ...it, id: u.id, data: undefined });
else Object.assign(it, { status: 'error', message: 'Логин занят — загрузите строку ещё раз', password: undefined });
}
}
return created;
}
router.post('/import/commit', async (req, res) => {
const b = req.body || {};
const rows = Array.isArray(b.rows) ? b.rows : [];
if (!rows.length) return res.status(400).json({ error: 'Список пуст' });
if (rows.length > MAX_IMPORT_ROWS) return res.status(400).json({ error: `Не больше ${MAX_IMPORT_ROWS} строк за раз` });
const defaultKind = KINDS.includes(b.defaultKind) ? b.defaultKind : 'STUDENT';
const plan = await planImport(rows, defaultKind);
const strip = (x) => ({ ...x, data: undefined });
if (b.dryRun !== false) return res.json({ summary: summarize(plan), results: plan.map(strip) });
const created = await createAccounts(req, plan.filter((x) => x.status === 'new'));
const summary = { ...summarize(plan), created: created.length };
logEvent(req, 'USERS_IMPORT', { meta: { ...summary, file: str(b.fileName, 120) || null } });
res.json({ summary, results: plan.map(strip), credentials: created.map(({ row, status, message, ...c }) => c) });
});
// Один пользователь вручную
router.post('/users', async (req, res) => {
const b = req.body || {};
const role = ROLES.includes(b.role) ? b.role : 'USER';
const [it] = await planImport([b], KINDS.includes(b.kind) ? b.kind : 'STUDENT');
if (it.status === 'error') return res.status(400).json({ error: it.message });
if (it.status === 'exists') return res.status(409).json({ error: `Такой пользователь уже есть: ${it.username}` });
const [c] = await createAccounts(req, [it], role);
if (!c) return res.status(409).json({ error: it.message || 'Не удалось создать пользователя' });
logEvent(req, 'USER_UPDATE', { meta: { created: c.username, role } });
const { row, status, message, ...cred } = c;
res.status(201).json({ credential: cred });
});
// Сброс паролей: выбранным пользователям или всей группе. Работает только для учётных записей без AD
router.post('/users/reset-passwords', async (req, res) => {
const b = req.body || {};
const where = { source: 'LOCAL', isPlatformAdmin: false, NOT: { id: req.user.id } };
if (Array.isArray(b.ids) && b.ids.length) where.id = { in: b.ids.map(Number).filter(Boolean).slice(0, MAX_IMPORT_ROWS) };
else if (b.group) where.studyGroup = str(b.group, 40).toUpperCase();
else return res.status(400).json({ error: 'Выберите пользователей или группу' });
const users = await prisma.user.findMany({ where, select: { id: true, username: true, displayName: true, studyGroup: true, kind: true, kindOverride: true }, take: MAX_IMPORT_ROWS });
if (!users.length) return res.status(400).json({ error: 'Нет подходящих пользователей. Пароли учётных записей AD меняются в домене.' });
const out = [];
for (const u of users) {
const password = genPassword();
await prisma.user.update({
where: { id: u.id },
// tokenVersion++ — все открытые сессии пользователя завершаются
data: { passwordHash: await hashTempPassword(password), mustChangePassword: true, tokenVersion: { increment: 1 } },
});
out.push({ id: u.id, username: u.username, displayName: u.displayName, studyGroup: u.studyGroup, kind: u.kindOverride || u.kind, password });
}
logEvent(req, 'PASSWORD_RESET', { meta: { count: out.length, group: b.group || null } });
res.json({ credentials: out });
});
// Лист с логинами и паролями (Excel). Пароли присылает браузер — сервер их не хранит
router.post('/credentials.xlsx', async (req, res) => {
const items = (Array.isArray(req.body?.items) ? req.body.items : []).slice(0, MAX_IMPORT_ROWS).map((x) => ({
displayName: str(x.displayName),
studyGroup: str(x.studyGroup, 40),
kind: KINDS.includes(x.kind) ? x.kind : '',
username: str(x.username, 60),
password: str(x.password, 60),
}));
if (!items.length) return res.status(400).json({ error: 'Нет данных' });
const org = await orgOf(req);
const url = /^https?:\/\/[^\s]+$/.test(String(req.body?.loginUrl || '')) ? String(req.body.loginUrl) : `/${org.slug}`;
const buf = await credentialsWorkbook({ orgName: org.shortName || org.name, loginUrl: url, items });
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader('Content-Disposition', `attachment; filename*=UTF-8''${encodeURIComponent(`Логины и пароли — ${org.shortName || org.slug}.xlsx`)}`);
res.setHeader('Cache-Control', 'no-store');
res.send(Buffer.from(buf));
});
export default router;
+162
View File
@@ -0,0 +1,162 @@
/**
* Публичная часть платформы (без входа): данные библиотеки для страницы входа,
* логотип, поиск «найти свою библиотеку», регистрация новой организации.
*/
import { Router } from 'express';
import multer from 'multer';
import path from 'node:path';
import crypto from 'node:crypto';
import rateLimit, { ipKeyGenerator } from 'express-rate-limit';
import { prismaBase, publicUser } from '../db.js';
import { issueSession, keepTenant } from '../middleware/auth.js';
import { LOGOS_DIR, publicOrg, slugError, logoUrl } from '../services/orgs.js';
import { hashPassword, passwordProblem, translit } from '../services/accounts.js';
import { logEvent } from '../services/events.js';
import { removeFile } from './books.js';
const router = Router();
const LOGO_EXT = ['.png', '.jpg', '.jpeg', '.webp']; // SVG не принимаем: в нём может быть скрипт
const logoUpload = multer({
storage: multer.diskStorage({
destination: LOGOS_DIR,
filename: (req, file, cb) => cb(null, crypto.randomUUID() + path.extname(file.originalname).toLowerCase()),
}),
limits: { fileSize: 2 * 1024 * 1024, files: 1 },
fileFilter: (req, file, cb) => {
const ok = LOGO_EXT.includes(path.extname(file.originalname).toLowerCase()) && /^image\/(png|jpeg|webp)$/.test(file.mimetype);
cb(ok ? null : new Error('Логотип: PNG, JPG или WEBP до 2 МБ'), ok);
},
}).single('logo');
export const logoMw = keepTenant((req, res, next) =>
logoUpload(req, res, (err) =>
err ? res.status(400).json({ error: err.code === 'LIMIT_FILE_SIZE' ? 'Логотип должен быть не больше 2 МБ' : err.message }) : next()
)
);
const str = (v, max = 200) => String(v ?? '').replace(/\s+/g, ' ').trim().slice(0, max);
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
/** Предложение адреса по названию: «Ташкентский государственный экономический университет» → tgeu */
function suggestSlug(name, shortName) {
const src = shortName || name;
const words = translit(src) ? src.split(/\s+/) : [];
const abbr = words.length > 1 ? words.map((w) => translit(w).charAt(0)).join('') : translit(src);
return abbr.replace(/[^a-z0-9]/g, '').slice(0, 20);
}
// Проверка адреса «на лету» в форме регистрации
router.get('/check-slug', async (req, res) => {
const slug = str(req.query.slug, 40).toLowerCase();
const err = slugError(slug);
if (err) return res.json({ available: false, error: err });
const taken = await prismaBase.organization.count({ where: { slug } });
res.json({ available: !taken, error: taken ? 'Этот адрес уже занят' : null });
});
router.get('/suggest-slug', async (req, res) => {
const base = suggestSlug(str(req.query.name), str(req.query.shortName)) || 'library';
let slug = /^[a-z]/.test(base) ? base : 'lib' + base;
if (slug.length < 3) slug = slug.padEnd(3, '0');
for (let i = 2; slugError(slug) || (await prismaBase.organization.count({ where: { slug } })); i++) slug = `${base}${i}`;
res.json({ slug });
});
// «Найдите свою библиотеку» на главной странице платформы
router.get('/search', async (req, res) => {
const q = str(req.query.q, 80);
if (q.length < 2) return res.json({ items: [] });
const ci = { contains: q, mode: 'insensitive' };
const items = await prismaBase.organization.findMany({
where: { status: 'ACTIVE', OR: [{ name: ci }, { shortName: ci }, { slug: { contains: q.toLowerCase() } }, { city: ci }] },
orderBy: { name: 'asc' },
take: 10,
});
res.json({ items: items.map((o) => ({ ...publicOrg(o), city: o.city })) });
});
// Название и логотип — для страницы входа библиотеки
router.get('/:slug/public', async (req, res) => {
const org = await prismaBase.organization.findUnique({ where: { slug: str(req.params.slug, 40).toLowerCase() } });
if (!org) return res.status(404).json({ error: 'Библиотека не найдена' });
res.json({ org: publicOrg(org) });
});
router.get('/:slug/logo', async (req, res) => {
const org = await prismaBase.organization.findUnique({ where: { slug: str(req.params.slug, 40).toLowerCase() }, select: { logoPath: true } });
if (!org?.logoPath) return res.status(404).end();
res.setHeader('Cache-Control', 'public, max-age=86400');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.sendFile(path.join(LOGOS_DIR, path.basename(org.logoPath)), (err) => err && !res.headersSent && res.status(404).end());
});
// ---------- Регистрация организации ----------
const registerLimiter = rateLimit({
windowMs: 60 * 60 * 1000,
limit: 5,
keyGenerator: (req) => ipKeyGenerator(req.ip),
message: { error: 'Слишком много заявок с вашего адреса. Попробуйте через час.' },
});
router.post('/register', registerLimiter, logoMw, async (req, res) => {
const b = req.body || {};
const logo = req.file;
const bad = (error) => {
removeFile(LOGOS_DIR, logo?.filename);
return res.status(400).json({ error });
};
// ловушка для ботов: скрытое поле, которое человек не заполняет
if (b.website2) return bad('Заявка отклонена');
const name = str(b.name, 200);
const shortName = str(b.shortName, 60) || null;
const slug = str(b.slug, 40).toLowerCase();
const contactName = str(b.contactName, 120);
const contactEmail = str(b.contactEmail, 120).toLowerCase();
const contactPhone = str(b.contactPhone, 40) || null;
const city = str(b.city, 80) || null;
let website = str(b.website, 200) || null;
const username = str(b.username, 40).toLowerCase();
const password = String(b.password || '');
if (name.length < 5) return bad('Укажите полное название организации');
const se = slugError(slug);
if (se) return bad(se);
if (contactName.split(' ').length < 2) return bad('Укажите фамилию и имя ответственного');
if (!EMAIL_RE.test(contactEmail)) return bad('Укажите корректный e-mail');
if (website && !/^https?:\/\//i.test(website)) website = 'https://' + website;
if (!/^[a-z][a-z0-9._-]{2,39}$/.test(username)) return bad('Логин администратора: латинские буквы, цифры, точка; от 3 символов');
const pp = passwordProblem(password, username);
if (pp) return bad(pp);
if (b.agree !== 'true') return bad('Подтвердите согласие с условиями');
if (await prismaBase.organization.count({ where: { slug } })) return bad('Этот адрес уже занят — выберите другой');
const passwordHash = await hashPassword(password);
const { org, user } = await prismaBase.$transaction(async (tx) => {
const org = await tx.organization.create({
data: { slug, name, shortName, city, website, contactName, contactEmail, contactPhone, status: 'PENDING', ...(logo && { logoPath: logo.filename }) },
});
const user = await tx.user.create({
data: {
organizationId: org.id,
username,
displayName: contactName,
email: contactEmail,
source: 'LOCAL',
passwordHash,
role: 'ADMIN',
kind: 'STAFF',
title: 'Администратор библиотеки',
lastLoginAt: new Date(),
lastSeenAt: new Date(),
loginCount: 1,
},
});
return { org, user };
});
await logEvent(req, 'ORG_REGISTER', { userId: user.id, organizationId: org.id, meta: { slug, name } });
issueSession(res, user);
res.status(201).json({ org: { ...publicOrg(org), logoUrl: logoUrl(org) }, user: publicUser(user) });
});
export default router;
+131
View File
@@ -0,0 +1,131 @@
/** Владелец платформы: заявки организаций, одобрение / приостановка, сводка по платформе */
import { Router } from 'express';
import { prismaBase } from '../db.js';
import { requirePlatformAdmin } from '../middleware/auth.js';
import { logEvent } from '../services/events.js';
import { LOGOS_DIR, ORG_STATUSES, publicOrg } from '../services/orgs.js';
import { dayKey, addDays } from '../services/time.js';
import { BOOKS_DIR, COVERS_DIR, removeFile } from './books.js';
const router = Router();
router.use(requirePlatformAdmin);
const db = prismaBase;
router.get('/overview', async (req, res) => {
const since = addDays(dayKey(), -29);
const [byStatus, users, ownBooks, sharedBooks, events30, active30] = await Promise.all([
db.organization.groupBy({ by: ['status'], _count: { _all: true } }),
db.user.count({ where: { organizationId: { not: null } } }),
db.book.count({ where: { organizationId: { not: null } } }),
db.book.count({ where: { organizationId: null } }),
db.event.count({ where: { day: { gte: since }, organizationId: { not: null } } }),
db.event.groupBy({ by: ['userId'], where: { day: { gte: since }, userId: { not: null }, organizationId: { not: null }, type: { not: 'LOGIN_FAILED' } } }),
]);
res.json({
orgs: Object.fromEntries(byStatus.map((x) => [x.status, x._count._all])),
users,
ownBooks,
sharedBooks,
events30,
activeUsers30: active30.length,
});
});
router.get('/orgs', async (req, res) => {
const where = {};
if (ORG_STATUSES.includes(req.query.status)) where.status = req.query.status;
const q = String(req.query.q || '').trim().slice(0, 80);
if (q) {
const ci = { contains: q, mode: 'insensitive' };
where.OR = [{ name: ci }, { shortName: ci }, { slug: { contains: q.toLowerCase() } }, { city: ci }, { contactEmail: ci }];
}
const orgs = await db.organization.findMany({
where,
orderBy: req.query.status === 'PENDING' ? { createdAt: 'asc' } : { createdAt: 'desc' },
take: 200,
include: { _count: { select: { users: true, books: true } } },
});
// последняя активность каждой организации
const last = await db.event.groupBy({ by: ['organizationId'], where: { organizationId: { in: orgs.map((o) => o.id) } }, _max: { createdAt: true } });
const lm = new Map(last.map((x) => [x.organizationId, x._max.createdAt]));
res.json({
items: orgs.map((o) => ({
...publicOrg(o),
city: o.city,
website: o.website,
contactName: o.contactName,
contactEmail: o.contactEmail,
contactPhone: o.contactPhone,
statusNote: o.statusNote,
createdAt: o.createdAt,
approvedAt: o.approvedAt,
users: o._count.users,
books: o._count.books,
lastActivityAt: lm.get(o.id) || null,
})),
});
});
router.get('/orgs/:id', async (req, res) => {
const id = Number(req.params.id);
const o = await db.organization.findUnique({ where: { id }, include: { _count: { select: { users: true, books: true, lists: true } } } });
if (!o) return res.status(404).json({ error: 'Организация не найдена' });
const since = addDays(dayKey(), -29);
const [admins, byType, byKind] = await Promise.all([
db.user.findMany({
where: { organizationId: id, OR: [{ roleOverride: 'ADMIN' }, { roleOverride: null, role: 'ADMIN' }] },
select: { id: true, username: true, displayName: true, email: true, source: true, lastLoginAt: true },
}),
db.event.groupBy({ by: ['type'], where: { organizationId: id, day: { gte: since } }, _count: { _all: true } }),
db.user.groupBy({ by: ['source'], where: { organizationId: id }, _count: { _all: true } }),
]);
res.json({
org: {
...publicOrg(o),
city: o.city, website: o.website, contactName: o.contactName, contactEmail: o.contactEmail, contactPhone: o.contactPhone,
statusNote: o.statusNote, createdAt: o.createdAt, approvedAt: o.approvedAt,
ldapUrl: o.ldap?.enabled ? o.ldap.url : null,
counts: o._count,
},
admins,
activity30: Object.fromEntries(byType.map((x) => [x.type, x._count._all])),
usersBySource: Object.fromEntries(byKind.map((x) => [x.source, x._count._all])),
});
});
// Одобрить / приостановить / возобновить
router.patch('/orgs/:id', async (req, res) => {
const id = Number(req.params.id);
const status = req.body?.status;
if (!ORG_STATUSES.includes(status)) return res.status(400).json({ error: 'Неизвестный статус' });
const note = String(req.body?.note || '').trim().slice(0, 1000) || null;
if (status === 'SUSPENDED' && !note) return res.status(400).json({ error: 'Укажите причину — её увидит администратор организации' });
const o = await db.organization.findUnique({ where: { id } });
if (!o) return res.status(404).json({ error: 'Организация не найдена' });
const upd = await db.organization.update({
where: { id },
data: { status, statusNote: status === 'ACTIVE' ? null : note, ...(status === 'ACTIVE' && !o.approvedAt && { approvedAt: new Date() }) },
});
logEvent(req, 'ORG_STATUS', { organizationId: id, meta: { slug: o.slug, from: o.status, to: status, note } });
res.json({ org: publicOrg(upd) });
});
// Удаление — только для отклонённых заявок и приостановленных организаций; удаляет всё, включая файлы
router.delete('/orgs/:id', async (req, res) => {
const id = Number(req.params.id);
const o = await db.organization.findUnique({ where: { id } });
if (!o) return res.status(404).json({ error: 'Организация не найдена' });
if (o.status === 'ACTIVE') return res.status(400).json({ error: 'Сначала приостановите организацию' });
if (String(req.body?.confirm || '') !== o.slug) return res.status(400).json({ error: `Для подтверждения введите адрес организации: ${o.slug}` });
const books = await db.book.findMany({ where: { organizationId: id }, select: { filePath: true, coverPath: true } });
await db.organization.delete({ where: { id } });
for (const b of books) {
removeFile(BOOKS_DIR, b.filePath);
removeFile(COVERS_DIR, b.coverPath);
}
removeFile(LOGOS_DIR, o.logoPath);
logEvent(req, 'ORG_DELETE', { organizationId: null, meta: { slug: o.slug, name: o.name, books: books.length } });
res.json({ ok: true });
});
export default router;
+274
View File
@@ -0,0 +1,274 @@
import { Router } from 'express';
import { prisma, KINDS, effectiveKind } from '../db.js';
import { requireRole } from '../middleware/auth.js';
import { dayKey, addDays, daysBetween, isDay } from '../services/time.js';
const router = Router();
router.use(requireRole('MODERATOR'));
function range(req) {
let to = isDay(req.query.to) ? req.query.to : dayKey();
let from = isDay(req.query.from) ? req.query.from : addDays(to, -(Math.min(Math.max(Number(req.query.days) || 30, 1), 730) - 1));
if (from > to) [from, to] = [to, from];
const len = daysBetween(from, to).length;
return { from, to, len, prevFrom: addDays(from, -len), prevTo: addDays(from, -1) };
}
const cnt = (rows, key) => Object.fromEntries(rows.map((r) => [r[key], r._count._all]));
const top = (by, where, take = 10) =>
prisma.event.groupBy({ by: [by], where: { ...where, [by]: { not: null } }, _count: { _all: true }, orderBy: { _count: { [by]: 'desc' } }, take });
// ---------- Сводка ----------
router.get('/overview', async (req, res) => {
const r = range(req);
const inR = { day: { gte: r.from, lte: r.to } };
const prevR = { day: { gte: r.prevFrom, lte: r.prevTo } };
const [
byType, prevByType, dayType, dayUser, activeUsers, prevActiveUsers,
topDl, topViews, topRead, topSearch, zeroSearch, heat, browsers, oses, devices,
dlByUser, dlByBook, totalUsers, totalBooks, storage, pending, online, failedRecent,
audType, audUsers, kindTotals, pendingTeachers, listsCount,
] = await Promise.all([
prisma.event.groupBy({ by: ['type'], where: inR, _count: { _all: true } }),
prisma.event.groupBy({ by: ['type'], where: prevR, _count: { _all: true } }),
prisma.event.groupBy({ by: ['day', 'type'], where: { ...inR, type: { in: ['VIEW', 'READ', 'DOWNLOAD', 'LOGIN', 'SEARCH'] } }, _count: { _all: true } }),
prisma.event.groupBy({ by: ['day', 'userId'], where: { ...inR, userId: { not: null }, type: { not: 'LOGIN_FAILED' } } }),
prisma.event.groupBy({ by: ['userId'], where: { ...inR, userId: { not: null }, type: { not: 'LOGIN_FAILED' } } }),
prisma.event.groupBy({ by: ['userId'], where: { ...prevR, userId: { not: null }, type: { not: 'LOGIN_FAILED' } } }),
top('bookId', { ...inR, type: 'DOWNLOAD' }),
top('bookId', { ...inR, type: 'VIEW' }),
top('bookId', { ...inR, type: 'READ' }),
top('query', { ...inR, type: 'SEARCH' }, 15),
top('query', { ...inR, type: 'SEARCH', resultCount: 0 }, 15),
prisma.event.groupBy({ by: ['weekday', 'hour'], where: { ...inR, type: { not: 'LOGIN_FAILED' } }, _count: { _all: true } }),
top('browser', inR, 8),
top('os', inR, 8),
top('device', inR, 5),
prisma.event.groupBy({ by: ['userId'], where: { ...inR, type: 'DOWNLOAD', userId: { not: null } }, _count: { _all: true } }),
prisma.event.groupBy({ by: ['bookId'], where: { ...inR, type: 'DOWNLOAD', bookId: { not: null } }, _count: { _all: true } }),
prisma.user.count(),
prisma.book.count({ where: { isPublished: true } }),
// место — только файлы своей организации (общий фонд хранит платформа)
prisma.book.aggregate({ where: { organizationId: { not: null } }, _sum: { fileSize: true } }),
prisma.book.count({ where: { source: 'USER', status: 'PENDING' } }),
prisma.user.count({ where: { lastSeenAt: { gte: new Date(Date.now() - 5 * 60_000) } } }),
prisma.event.findMany({
where: { type: 'LOGIN_FAILED' },
orderBy: { createdAt: 'desc' },
take: 10,
select: { id: true, ip: true, meta: true, createdAt: true, browser: true, os: true },
}),
// Аудитория: студенты / преподаватели / сотрудники
prisma.event.groupBy({ by: ['userKind', 'type'], where: { ...inR, userKind: { not: null }, type: { in: ['LOGIN', 'VIEW', 'READ', 'DOWNLOAD'] } }, _count: { _all: true } }),
prisma.event.groupBy({ by: ['userKind', 'userId'], where: { ...inR, userKind: { not: null }, userId: { not: null }, type: { not: 'LOGIN_FAILED' } } }),
prisma.user.groupBy({ by: ['kindOverride', 'kind', 'roleOverride', 'role'], _count: { _all: true } }),
prisma.user.count({ where: { kindOverride: null, kind: null, kindClaim: 'TEACHER' } }),
prisma.readingList.count(),
]);
const audience = new Map(KINDS.map((k) => [k, { kind: k, users: 0, active: 0, LOGIN: 0, VIEW: 0, READ: 0, DOWNLOAD: 0 }]));
for (const x of audType) audience.get(x.userKind) && (audience.get(x.userKind)[x.type] = x._count._all);
for (const x of audUsers) audience.get(x.userKind) && audience.get(x.userKind).active++;
for (const x of kindTotals) {
const k = effectiveKind(x);
if (audience.has(k)) audience.get(k).users += x._count._all;
}
// Временной ряд
const days = daysBetween(r.from, r.to);
const series = new Map(days.map((d) => [d, { day: d, VIEW: 0, READ: 0, DOWNLOAD: 0, LOGIN: 0, SEARCH: 0, users: 0 }]));
for (const x of dayType) if (series.has(x.day)) series.get(x.day)[x.type] = x._count._all;
for (const x of dayUser) if (series.has(x.day)) series.get(x.day).users++;
// Подтягиваем названия книг
const bookIds = [...new Set([...topDl, ...topViews, ...topRead].map((x) => x.bookId))];
const allBookIds = [...new Set([...bookIds, ...dlByBook.map((x) => x.bookId)])];
const books = await prisma.book.findMany({
where: { id: { in: allBookIds } },
select: { id: true, title: true, authors: true, coverPath: true, updatedAt: true, categoryId: true, category: { select: { name: true, color: true } } },
});
const bm = new Map(books.map((b) => [b.id, b]));
const bookRow = (x) => {
const b = bm.get(x.bookId);
return b && {
id: b.id, title: b.title, authors: b.authors, count: x._count._all,
coverUrl: b.coverPath ? `/api/books/${b.id}/cover?v=${b.updatedAt.getTime()}` : null,
category: b.category?.name || null,
};
};
// Скачивания по категориям
const catAgg = new Map();
for (const x of dlByBook) {
const b = bm.get(x.bookId);
const key = b?.category?.name || 'Без категории';
const cur = catAgg.get(key) || { name: key, color: b?.category?.color || '#94a3b8', count: 0 };
cur.count += x._count._all;
catAgg.set(key, cur);
}
// Скачивания по подразделениям (из AD) + топ читателей
const userIds = dlByUser.map((x) => x.userId);
const users = await prisma.user.findMany({
where: { id: { in: userIds } },
select: { id: true, displayName: true, username: true, department: true },
});
const um = new Map(users.map((u) => [u.id, u]));
const depAgg = new Map();
for (const x of dlByUser) {
const dep = um.get(x.userId)?.department || 'Не указано';
const cur = depAgg.get(dep) || { name: dep, count: 0, users: 0 };
cur.count += x._count._all;
cur.users++;
depAgg.set(dep, cur);
}
const topUsers = [...dlByUser]
.sort((a, b) => b._count._all - a._count._all)
.slice(0, 10)
.map((x) => ({ ...um.get(x.userId), count: x._count._all }))
.filter((u) => u.id);
const t = cnt(byType, 'type');
const p = cnt(prevByType, 'type');
const kpi = (k) => ({ value: t[k] || 0, prev: p[k] || 0 });
res.json({
range: r,
kpi: {
downloads: kpi('DOWNLOAD'),
views: kpi('VIEW'),
reads: kpi('READ'),
logins: kpi('LOGIN'),
searches: kpi('SEARCH'),
newUsers: kpi('REGISTER'),
failedLogins: kpi('LOGIN_FAILED'),
activeUsers: { value: activeUsers.length, prev: prevActiveUsers.length },
},
totals: { users: totalUsers, books: totalBooks, storageBytes: storage._sum.fileSize || 0, online, pendingSubmissions: pending, pendingTeachers, lists: listsCount },
audience: [...audience.values()],
submissions: { submitted: t.SUBMIT || 0, approved: t.SUBMIT_APPROVE || 0, rejected: t.SUBMIT_REJECT || 0 },
timeline: [...series.values()],
topDownloads: topDl.map(bookRow).filter(Boolean),
topViews: topViews.map(bookRow).filter(Boolean),
topReads: topRead.map(bookRow).filter(Boolean),
topSearches: topSearch.map((x) => ({ query: x.query, count: x._count._all })),
zeroSearches: zeroSearch.map((x) => ({ query: x.query, count: x._count._all })),
heatmap: heat.map((x) => ({ weekday: x.weekday, hour: x.hour, count: x._count._all })),
browsers: browsers.map((x) => ({ name: x.browser, count: x._count._all })),
os: oses.map((x) => ({ name: x.os, count: x._count._all })),
devices: devices.map((x) => ({ name: x.device, count: x._count._all })),
categories: [...catAgg.values()].sort((a, b) => b.count - a.count),
departments: [...depAgg.values()].sort((a, b) => b.count - a.count).slice(0, 15),
topUsers,
failedLogins: failedRecent.map((e) => ({ ...e, meta: e.meta ? JSON.parse(e.meta) : null })),
});
});
// ---------- Кто сейчас онлайн ----------
router.get('/online', async (req, res) => {
const users = await prisma.user.findMany({
where: { lastSeenAt: { gte: new Date(Date.now() - 5 * 60_000) } },
orderBy: { lastSeenAt: 'desc' },
take: 100,
select: { id: true, displayName: true, username: true, department: true, lastSeenAt: true },
});
res.json({ items: users });
});
// ---------- Журнал событий ----------
function eventWhere(q) {
const where = {};
if (q.type) where.type = { in: String(q.type).split(',') };
if (q.userId) where.userId = Number(q.userId);
if (q.bookId) where.bookId = Number(q.bookId);
if (isDay(q.from) || isDay(q.to)) where.day = { ...(isDay(q.from) && { gte: q.from }), ...(isDay(q.to) && { lte: q.to }) };
if (q.ip) where.ip = { contains: String(q.ip) };
if (KINDS.includes(q.kind)) where.userKind = q.kind;
if (q.q) {
const s = String(q.q).trim();
const ci = { contains: s, mode: 'insensitive' };
where.OR = [
{ user: { username: ci } },
{ user: { displayName: ci } },
{ user: { department: ci } },
{ book: { title: ci } },
{ query: ci },
];
}
return where;
}
const eventInclude = {
user: { select: { id: true, username: true, displayName: true, department: true, studyGroup: true } },
book: { select: { id: true, title: true } },
};
router.get('/events', async (req, res) => {
const page = Math.max(1, Number(req.query.page) || 1);
const limit = Math.min(200, Number(req.query.limit) || 50);
const where = eventWhere(req.query);
const [total, items] = await Promise.all([
prisma.event.count({ where }),
prisma.event.findMany({ where, orderBy: { id: 'desc' }, skip: (page - 1) * limit, take: limit, include: eventInclude }),
]);
res.json({ items, total, page, pages: Math.ceil(total / limit) });
});
const TYPE_RU = {
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: 'Изменён статус организации',
USERS_IMPORT: 'Загрузка списка пользователей', PASSWORD_RESET: 'Выданы новые пароли', PASSWORD_CHANGE: 'Смена пароля',
};
const KIND_RU = { STUDENT: 'Студент', TEACHER: 'Преподаватель', STAFF: 'Сотрудник' };
router.get('/events.csv', async (req, res) => {
const items = await prisma.event.findMany({
where: eventWhere(req.query),
orderBy: { id: 'desc' },
take: 100_000,
include: eventInclude,
});
const esc = (v) => {
const s = v == null ? '' : String(v);
return /[";\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
};
const head = ['Дата и время', 'Событие', 'Логин', 'ФИО', 'Кто', 'Группа', 'Подразделение', 'Книга', 'Поисковый запрос', 'Результатов', 'IP', 'Браузер', 'ОС', 'Устройство'];
const lines = items.map((e) =>
[
e.createdAt.toISOString(), TYPE_RU[e.type] || e.type, e.user?.username, e.user?.displayName, KIND_RU[e.userKind], e.user?.studyGroup, e.user?.department,
e.book?.title, e.query, e.resultCount, e.ip, e.browser, e.os, e.device,
].map(esc).join(';')
);
res.setHeader('Content-Type', 'text/csv; charset=utf-8');
res.setHeader('Content-Disposition', `attachment; filename="elibrary-events-${dayKey()}.csv"`);
// BOM + ";" — чтобы Excel корректно открыл кириллицу
res.send('' + [head.join(';'), ...lines].join('\r\n'));
});
// ---------- Статистика по книге ----------
router.get('/books/:id', async (req, res) => {
const bookId = Number(req.params.id);
const to = dayKey();
const from = addDays(to, -29);
const [byDay, byType, readers] = await Promise.all([
prisma.event.groupBy({ by: ['day', 'type'], where: { bookId, day: { gte: from, lte: to }, type: { in: ['VIEW', 'READ', 'DOWNLOAD'] } }, _count: { _all: true } }),
prisma.event.groupBy({ by: ['type'], where: { bookId }, _count: { _all: true } }),
prisma.event.findMany({
where: { bookId, type: 'DOWNLOAD' },
orderBy: { createdAt: 'desc' },
take: 30,
include: { user: { select: { id: true, displayName: true, department: true } } },
}),
]);
const series = new Map(daysBetween(from, to).map((d) => [d, { day: d, VIEW: 0, READ: 0, DOWNLOAD: 0 }]));
for (const x of byDay) if (series.has(x.day)) series.get(x.day)[x.type] = x._count._all;
res.json({ counts: cnt(byType, 'type'), timeline: [...series.values()], recentDownloads: readers });
});
export default router;
+263
View File
@@ -0,0 +1,263 @@
/**
* Публикация работ студентами (статьи, тезисы, курсовые, ВКР…)
* Цикл: DRAFT (черновик) → PENDING (на модерации) → PUBLISHED | REJECTED (на доработку)
*/
import { Router } from 'express';
import path from 'node:path';
import rateLimit from 'express-rate-limit';
import { prisma, effectiveKind } from '../db.js';
import { requireAuth, requireRole } from '../middleware/auth.js';
import { logEvent } from '../services/events.js';
import { BOOKS_DIR, COVERS_DIR, bookData, removeFile, serializeBook, uploadMw } from './books.js';
const router = Router();
export const STUDENT_TYPES = ['article', 'conference', 'coursework', 'thesis', 'report', 'other'];
// преподаватели дополнительно публикуют учебно-методические материалы
export const TEACHER_TYPES = ['textbook', 'tutorial', 'methodical', 'lecture', 'monograph', 'reference', 'atlas', 'article', 'conference', 'other'];
const isTeacherUser = (req) => effectiveKind(req.user) === 'TEACHER';
const allowedTypes = (req) => (isTeacherUser(req) ? [...new Set([...TEACHER_TYPES, ...STUDENT_TYPES])] : STUDENT_TYPES);
/** Руководитель из системы: только преподаватель; текстовое поле заполняется его ФИО */
async function resolveSupervisor(req, data) {
const id = Number(req.body.supervisorId) || null;
if (!id || id === req.user.id) return (data.supervisorId = null);
const t = await prisma.user.findFirst({
where: { id, isBlocked: false, OR: [{ kindOverride: 'TEACHER' }, { kindOverride: null, kind: 'TEACHER' }] },
select: { id: true, displayName: true },
});
data.supervisorId = t?.id ?? null;
if (t && !data.supervisor) {
data.supervisor = t.displayName;
data.searchText += ' ' + t.displayName.toLowerCase();
}
}
const DOC_EXT = ['.pdf', '.doc', '.docx', '.odt', '.rtf', '.ppt', '.pptx'];
// преподаватели загружают и книги: электронные форматы
const TEACHER_EXT = [...DOC_EXT, '.epub', '.djvu', '.txt'];
const MAX_OPEN = 10; // не более 10 работ на модерации одновременно
const submitLimiter = rateLimit({
windowMs: 60 * 60 * 1000,
limit: 30,
keyGenerator: (req) => `u${req.user.id}`, // requireAuth стоит раньше
message: { error: 'Слишком много отправок. Попробуйте позже.' },
});
const include = {
category: { select: { id: true, name: true, color: true } },
createdBy: { select: { id: true, displayName: true, username: true, department: true, title: true, kind: true, kindOverride: true, studyGroup: true } },
reviewedBy: { select: { id: true, displayName: true } },
supervisorRef: { select: { id: true, displayName: true, title: true } },
};
const author = (u) => u && { ...u, kind: u.kindOverride || u.kind || 'STUDENT', kindOverride: undefined };
const serialize = (b) => ({ ...serializeBook(b), createdBy: author(b.createdBy), reviewedBy: b.reviewedBy, supervisorRef: b.supervisorRef });
function validate(req, data, file, existing) {
const draft = req.body.draft === 'true';
if (!allowedTypes(req).includes(data.type)) return 'Недопустимый тип работы';
const teacher = isTeacherUser(req);
if (file && !(teacher ? TEACHER_EXT : DOC_EXT).includes(path.extname(file.originalname).toLowerCase()))
return `Допустимые форматы: PDF, DOC, DOCX, ODT, RTF, PPT, PPTX${teacher ? ', EPUB, DJVU, TXT' : ''}`;
if (!file && !existing?.filePath) return 'Прикрепите файл работы';
if (draft) {
// черновик: достаточно файла; название подставим из имени файла
if (!data.title) data.title = (file?.originalname || existing?.fileName || 'Черновик').replace(/\.[^.]+$/, '');
if (!data.authors) data.authors = req.user.displayName;
return null;
}
if (data.title.length < 5) return 'Название должно быть не короче 5 символов';
if (!data.authors) return 'Укажите авторов';
// у книг преподавателя аннотация желательна, но не обязательна
if (!teacher && (!data.description || data.description.length < 50)) return 'Аннотация должна быть не короче 50 символов';
if (req.body.agree !== 'true') return teacher ? 'Подтвердите право на размещение издания' : 'Подтвердите авторство и согласие на размещение';
return null;
}
const cleanup = (req) => {
removeFile(BOOKS_DIR, req.files?.file?.[0]?.filename);
removeFile(COVERS_DIR, req.files?.cover?.[0]?.filename);
};
/** Преподаватель загружает книгу прямо из списка литературы — сразу кладём её в этот список.
* Студенты увидят её там только после одобрения модератором. */
async function addToOwnList(req, bookId) {
const listId = Number(req.body.listId);
if (!listId || !isTeacherUser(req)) return null;
const l = await prisma.readingList.findFirst({ where: { id: listId, ownerId: req.user.id }, select: { id: true } });
if (!l) return null;
const last = await prisma.readingListItem.aggregate({ where: { listId }, _max: { position: true } });
await prisma.readingListItem.upsert({
where: { listId_bookId: { listId, bookId } },
create: { listId, bookId, required: req.body.required !== 'false', position: (last._max.position ?? 0) + 1 },
update: {},
});
await prisma.readingList.update({ where: { id: listId }, data: { updatedAt: new Date() } });
return listId;
}
// ---------- Мои работы ----------
router.get('/mine', requireAuth, async (req, res) => {
const items = await prisma.book.findMany({
where: { createdById: req.user.id, source: 'USER' },
orderBy: { updatedAt: 'desc' },
include,
});
res.json({ items: items.map(serialize) });
});
router.get('/mine/:id', requireAuth, async (req, res) => {
const b = await prisma.book.findFirst({ where: { id: Number(req.params.id), createdById: req.user.id, source: 'USER' }, include });
if (!b) return res.status(404).json({ error: 'Работа не найдена' });
res.json({ item: serialize(b) });
});
// Отправка новой работы
router.post('/', requireAuth, submitLimiter, uploadMw, async (req, res) => {
const file = req.files?.file?.[0];
const cover = req.files?.cover?.[0];
const data = bookData(req.body);
await resolveSupervisor(req, data);
const err = validate(req, data, file);
if (err) {
cleanup(req);
return res.status(400).json({ error: err });
}
const open = await prisma.book.count({ where: { createdById: req.user.id, source: 'USER', status: { in: ['DRAFT', 'PENDING'] } } });
if (open >= MAX_OPEN) {
cleanup(req);
return res.status(429).json({ error: `У вас уже ${open} работ в черновиках и на модерации. Дождитесь проверки.` });
}
const draft = req.body.draft === 'true';
const book = await prisma.book.create({
data: {
...data,
organizationId: req.user.organizationId,
source: 'USER',
status: draft ? 'DRAFT' : 'PENDING',
isPublished: false,
submittedAt: draft ? null : new Date(),
createdById: req.user.id,
filePath: file.filename,
fileName: file.originalname,
fileSize: file.size,
mimeType: file.mimetype,
...(cover && { coverPath: cover.filename }),
},
include,
});
const listId = await addToOwnList(req, book.id);
if (!draft) logEvent(req, 'SUBMIT', { bookId: book.id, meta: { title: book.title, ...(listId && { listId }) } });
res.status(201).json({ item: serialize(book), listId });
});
// Редактирование своей работы (опубликованные — только через модератора)
router.put('/:id', requireAuth, uploadMw, async (req, res) => {
const id = Number(req.params.id);
const old = await prisma.book.findFirst({ where: { id, createdById: req.user.id, source: 'USER' } });
if (!old) {
cleanup(req);
return res.status(404).json({ error: 'Работа не найдена' });
}
if (old.status === 'PUBLISHED') {
cleanup(req);
return res.status(400).json({ error: 'Опубликованную работу может изменить только модератор' });
}
const file = req.files?.file?.[0];
const cover = req.files?.cover?.[0];
const data = bookData(req.body);
await resolveSupervisor(req, data);
data.endorsedAt = null; // после правок руководитель подтверждает заново
const err = validate(req, data, file, old);
if (err) {
cleanup(req);
return res.status(400).json({ error: err });
}
if (file) removeFile(BOOKS_DIR, old.filePath);
if (cover || req.body.removeCover === 'true') removeFile(COVERS_DIR, old.coverPath);
const draft = req.body.draft === 'true';
const book = await prisma.book.update({
where: { id },
data: {
...data,
isPublished: false,
status: draft ? 'DRAFT' : 'PENDING',
...(!draft && old.status !== 'PENDING' && { submittedAt: new Date() }),
...(file && { filePath: file.filename, fileName: file.originalname, fileSize: file.size, mimeType: file.mimetype }),
...(cover ? { coverPath: cover.filename } : req.body.removeCover === 'true' ? { coverPath: null } : {}),
},
include,
});
if (!draft && old.status !== 'PENDING') logEvent(req, 'SUBMIT', { bookId: id, meta: { title: book.title, resubmit: old.status === 'REJECTED' } });
res.json({ item: serialize(book) });
});
// Удаление своей неопубликованной работы
router.delete('/:id', requireAuth, async (req, res) => {
const b = await prisma.book.findFirst({ where: { id: Number(req.params.id), createdById: req.user.id, source: 'USER' } });
if (!b) return res.status(404).json({ error: 'Работа не найдена' });
if (b.status === 'PUBLISHED') return res.status(400).json({ error: 'Опубликованную работу может снять только модератор' });
await prisma.book.delete({ where: { id: b.id } });
removeFile(BOOKS_DIR, b.filePath);
removeFile(COVERS_DIR, b.coverPath);
res.json({ ok: true });
});
// ---------- Модерация ----------
router.get('/', requireRole('MODERATOR'), async (req, res) => {
const status = ['PENDING', 'PUBLISHED', 'REJECTED'].includes(req.query.status) ? req.query.status : undefined;
const page = Math.max(1, Number(req.query.page) || 1);
const limit = 20;
const where = { source: 'USER', status: status || { not: 'DRAFT' } };
const [total, items, counts] = await Promise.all([
prisma.book.count({ where }),
prisma.book.findMany({
where,
orderBy: status === 'PENDING' ? { submittedAt: 'asc' } : { updatedAt: 'desc' }, // очередь — старые первыми
skip: (page - 1) * limit,
take: limit,
include,
}),
prisma.book.groupBy({ by: ['status'], where: { source: 'USER', status: { not: 'DRAFT' } }, _count: { _all: true } }),
]);
res.json({
items: items.map(serialize),
total,
page,
pages: Math.ceil(total / limit),
counts: Object.fromEntries(counts.map((c) => [c.status, c._count._all])),
});
});
router.get('/pending-count', requireRole('MODERATOR'), async (req, res) => {
res.json({ count: await prisma.book.count({ where: { source: 'USER', status: 'PENDING' } }) });
});
router.post('/:id/review', requireRole('MODERATOR'), async (req, res) => {
const id = Number(req.params.id);
const { action } = req.body || {};
const note = String(req.body?.note || '').trim().slice(0, 2000) || null;
const b = await prisma.book.findFirst({ where: { id, source: 'USER', status: { not: 'DRAFT' } } });
if (!b) return res.status(404).json({ error: 'Работа не найдена' });
if (!['approve', 'reject'].includes(action)) return res.status(400).json({ error: 'Неизвестное действие' });
if (action === 'reject' && !note) return res.status(400).json({ error: 'Укажите причину — автор увидит этот комментарий' });
const approve = action === 'approve';
const book = await prisma.book.update({
where: { id },
data: {
status: approve ? 'PUBLISHED' : 'REJECTED',
isPublished: approve,
reviewNote: note,
reviewedById: req.user.id,
reviewedAt: new Date(),
...(approve && req.body.categoryId !== undefined && { categoryId: Number(req.body.categoryId) || null }),
},
include,
});
logEvent(req, approve ? 'SUBMIT_APPROVE' : 'SUBMIT_REJECT', { bookId: id, meta: { title: book.title, author: book.createdBy?.username, note } });
res.json({ item: serialize(book) });
});
export default router;
+26
View File
@@ -0,0 +1,26 @@
import { Router } from 'express';
import { config } from '../config.js';
import { requireRole } from '../middleware/auth.js';
import { prisma } from '../db.js';
const router = Router();
router.use(requireRole('ADMIN'));
// Сводка о сервере. Настройки Active Directory — в /api/org/ldap (у каждой организации свои)
router.get('/status', async (req, res) => {
const [events, users, books] = await Promise.all([
prisma.event.count(),
prisma.user.count(),
prisma.book.count({ where: { organizationId: { not: null } } }),
]);
res.json({
localAuthEnabled: config.localAuthEnabled,
timezone: config.timezone,
maxUploadMb: config.maxUploadMb,
counts: { events, users, books },
node: process.version,
uptimeSec: Math.round(process.uptime()),
});
});
export default router;
+136
View File
@@ -0,0 +1,136 @@
import { Router } from 'express';
import { prisma, publicUser, ROLES, KINDS, effectiveRole, effectiveKind, normGroup } from '../db.js';
import { requireRole } from '../middleware/auth.js';
import { logEvent } from '../services/events.js';
const router = Router();
// Список пользователей (модераторы видят, администраторы управляют)
router.get('/', requireRole('MODERATOR'), async (req, res) => {
const page = Math.max(1, Number(req.query.page) || 1);
const limit = Math.min(100, Number(req.query.limit) || 25);
const q = String(req.query.q || '').trim();
const where = {};
if (q)
where.OR = ['username', 'displayName', 'department', 'email', 'title', 'studyGroup'].map((f) => ({
[f]: { contains: q, mode: 'insensitive' },
}));
if (req.query.role) {
const r = String(req.query.role);
where.AND = [{ OR: [{ roleOverride: r }, { roleOverride: null, role: r }] }];
}
if (req.query.department) where.department = String(req.query.department);
if (req.query.kind === 'PENDING') Object.assign(where, { kindOverride: null, kind: null, kindClaim: 'TEACHER' });
else if (KINDS.includes(req.query.kind)) {
const k = String(req.query.kind);
// STAFF без явного типа — это модераторы/администраторы без группы AD
const implicit = k === 'STUDENT' ? [{ kindOverride: null, kind: null, roleOverride: null, role: 'USER' }, { kindOverride: null, kind: null, roleOverride: 'USER' }]
: k === 'STAFF' ? [{ kindOverride: null, kind: null, roleOverride: { in: ['MODERATOR', 'ADMIN'] } }, { kindOverride: null, kind: null, roleOverride: null, role: { in: ['MODERATOR', 'ADMIN'] } }]
: [];
(where.AND ||= []).push({ OR: [{ kindOverride: k }, { kindOverride: null, kind: k }, ...implicit] });
}
if (req.query.group) where.studyGroup = normGroup(req.query.group);
if (req.query.blocked === '1') where.isBlocked = true;
const orderBy =
{ name: { displayName: 'asc' }, logins: { loginCount: 'desc' }, created: { createdAt: 'desc' } }[req.query.sort] ||
{ lastSeenAt: { sort: 'desc', nulls: 'last' } };
const [total, users] = await Promise.all([
prisma.user.count({ where }),
prisma.user.findMany({
where,
orderBy,
skip: (page - 1) * limit,
take: limit,
include: {
_count: { select: { events: { where: { type: 'DOWNLOAD' } }, favorites: true } },
},
}),
]);
const onlineSince = Date.now() - 5 * 60_000;
res.json({
items: users.map((u) => ({
...publicUser(u),
downloads: u._count.events,
favorites: u._count.favorites,
online: !!u.lastSeenAt && u.lastSeenAt.getTime() > onlineSince,
})),
total,
page,
pages: Math.ceil(total / limit),
});
});
router.get('/groups', requireRole('MODERATOR'), async (req, res) => {
const rows = await prisma.user.groupBy({ by: ['studyGroup'], _count: { _all: true }, where: { studyGroup: { not: null } }, orderBy: { studyGroup: 'asc' } });
res.json({ items: rows.map((r) => ({ value: r.studyGroup, count: r._count._all })) });
});
router.get('/departments', requireRole('MODERATOR'), async (req, res) => {
const rows = await prisma.user.groupBy({ by: ['department'], _count: { _all: true }, where: { department: { not: null } } });
res.json({ items: rows.map((r) => ({ value: r.department, count: r._count._all })).sort((a, b) => b.count - a.count) });
});
// Профиль пользователя с его активностью
router.get('/:id', requireRole('MODERATOR'), async (req, res) => {
const id = Number(req.params.id);
const user = await prisma.user.findUnique({ where: { id } });
if (!user) return res.status(404).json({ error: 'Пользователь не найден' });
const [byType, topBooks, recent, byDay] = await Promise.all([
prisma.event.groupBy({ by: ['type'], where: { userId: id }, _count: { _all: true } }),
prisma.event.groupBy({
by: ['bookId'],
where: { userId: id, type: 'DOWNLOAD', bookId: { not: null } },
_count: { _all: true },
orderBy: { _count: { bookId: 'desc' } },
take: 10,
}),
prisma.event.findMany({
where: { userId: id },
orderBy: { createdAt: 'desc' },
take: 100,
include: { book: { select: { id: true, title: true } } },
}),
prisma.event.groupBy({ by: ['day'], where: { userId: id }, _count: { _all: true }, orderBy: { day: 'desc' }, take: 90 }),
]);
const books = await prisma.book.findMany({
where: { id: { in: topBooks.map((t) => t.bookId) } },
select: { id: true, title: true, authors: true },
});
const bm = new Map(books.map((b) => [b.id, b]));
res.json({
user: publicUser(user),
counts: Object.fromEntries(byType.map((t) => [t.type, t._count._all])),
topBooks: topBooks.filter((t) => bm.has(t.bookId)).map((t) => ({ ...bm.get(t.bookId), count: t._count._all })),
activity: byDay.map((d) => ({ day: d.day, count: d._count._all })).reverse(),
recent,
});
});
// Управление: роль / блокировка (только администратор)
router.patch('/:id', requireRole('ADMIN'), async (req, res) => {
const id = Number(req.params.id);
const data = {};
// тип пользователя и группу можно менять и себе
if ('kindOverride' in req.body) {
const k = req.body.kindOverride;
if (k !== null && !KINDS.includes(k)) return res.status(400).json({ error: 'Неизвестный тип пользователя' });
data.kindOverride = k;
}
if ('studyGroup' in req.body) data.studyGroup = normGroup(req.body.studyGroup);
if (id === req.user.id && ('roleOverride' in req.body || 'isBlocked' in req.body))
return res.status(400).json({ error: 'Нельзя менять собственную роль или блокировку' });
if ('roleOverride' in req.body) {
const r = req.body.roleOverride;
if (r !== null && !ROLES.includes(r)) return res.status(400).json({ error: 'Неизвестная роль' });
data.roleOverride = r;
}
if ('isBlocked' in req.body) data.isBlocked = !!req.body.isBlocked;
const user = await prisma.user.update({ where: { id }, data });
logEvent(req, 'USER_UPDATE', { meta: { targetId: id, target: user.username, ...data, role: effectiveRole(user), kind: effectiveKind(user) } });
res.json({ user: publicUser(user) });
});
export default router;