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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 10:35:19 +05:00

234 lines
10 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
generator client {
provider = "prisma-client-js"
// native — для разработки, debian-openssl-3.0.x — Ubuntu 22.04+/Debian 12, linux-musl — Docker Alpine
binaryTargets = ["native", "debian-openssl-3.0.x", "linux-musl-openssl-3.0.x"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
// Организация (университет, колледж…) — отдельная библиотека на платформе
model Organization {
id Int @id @default(autoincrement())
slug String @unique // адрес: site.uz/<slug>
name String // полное название
shortName String? // краткое (в шапке)
logoPath String?
status String @default("PENDING") // PENDING — ждёт одобрения владельцем платформы | ACTIVE | SUSPENDED
statusNote String? // причина приостановки / комментарий владельца платформы
contactName String?
contactEmail String?
contactPhone String?
website String?
city String?
// Active Directory: JSON с настройками; пароль сервисной учётки зашифрован (ldapBindSecret)
ldap Json?
ldapBindSecret String?
approvedAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
users User[]
books Book[]
categories Category[]
events Event[]
lists ReadingList[]
@@index([status])
}
model User {
id Int @id @default(autoincrement())
// null — владелец платформы (isPlatformAdmin)
organizationId Int?
organization Organization? @relation(fields: [organizationId], references: [id], onDelete: Cascade)
isPlatformAdmin Boolean @default(false)
username String // sAMAccountName или сгенерированный логин (в нижнем регистре); уникален внутри организации
displayName String
email String?
department String? // отдел / факультет из AD
title String? // должность / группа из AD
employeeId String?
// Тип пользователя: STUDENT | TEACHER | STAFF
kind String? // определён по группам / OU в AD (или задан для локальных учёток)
kindOverride String? // ручное назначение администратором (приоритетнее AD)
kindClaim String? // выбран на странице входа, если AD не определил тип (требует подтверждения)
studyGroup String? // академическая группа студента (в верхнем регистре, без пробелов)
course Int? @db.SmallInt // курс
source String @default("LDAP") // LDAP | LOCAL
passwordHash String? // только для локальных учётных записей
mustChangePassword Boolean @default(false) // выданный системой пароль — сменить при первом входе
tokenVersion Int @default(0) // увеличивается при смене/сбросе пароля — старые сессии становятся недействительными
role String @default("USER") // роль из групп AD: USER | MODERATOR | ADMIN
roleOverride String? // ручное назначение роли администратором (приоритетнее AD)
isBlocked Boolean @default(false)
loginCount Int @default(0)
lastLoginAt DateTime?
lastSeenAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
favorites Favorite[]
events Event[]
books Book[] @relation("BookCreator")
reviewed Book[] @relation("BookReviewer")
supervised Book[] @relation("BookSupervisor")
lists ReadingList[]
@@unique([organizationId, username])
@@index([kind])
@@index([studyGroup])
@@index([organizationId, employeeId])
}
model Category {
id Int @id @default(autoincrement())
organizationId Int? // null — общий раздел платформы
organization Organization? @relation(fields: [organizationId], references: [id], onDelete: Cascade)
name String
slug String @unique
description String?
color String @default("#6366f1")
icon String @default("BookOpen")
sortOrder Int @default(0)
createdAt DateTime @default(now())
books Book[]
@@index([organizationId])
}
model Book {
id Int @id @default(autoincrement())
organizationId Int? // null — общий открытый фонд, виден всем организациям
organization Organization? @relation(fields: [organizationId], references: [id], onDelete: Cascade)
title String
subtitle String?
authors String // через запятую
description String?
isbn String?
udc String? // УДК / ББК
publisher String?
year Int?
language String @default("ru")
type String @default("textbook")
pages Int?
keywords String?
filePath String?
fileName String?
fileSize Int?
mimeType String?
coverPath String?
isPublished Boolean @default(true)
// Студенческие публикации
source String @default("LIBRARY") // LIBRARY — фонд библиотеки, USER — работа, загруженная пользователем
status String @default("PUBLISHED") // DRAFT | PENDING | PUBLISHED | REJECTED
supervisor String? // научный руководитель (текстом)
supervisorId Int? // руководитель — преподаватель из системы
supervisorRef User? @relation("BookSupervisor", fields: [supervisorId], references: [id], onDelete: SetNull)
endorsedAt DateTime? // руководитель подтвердил работу
reviewNote String? // комментарий модератора
reviewedById Int?
reviewedBy User? @relation("BookReviewer", fields: [reviewedById], references: [id], onDelete: SetNull)
reviewedAt DateTime?
submittedAt DateTime?
searchText String @default("")
viewCount Int @default(0)
downloadCount Int @default(0)
categoryId Int?
category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
createdById Int?
createdBy User? @relation("BookCreator", fields: [createdById], references: [id], onDelete: SetNull)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
favorites Favorite[]
events Event[]
listItems ReadingListItem[]
@@index([categoryId])
@@index([supervisorId])
@@index([createdAt])
@@index([downloadCount])
@@index([source, status])
@@index([createdById])
@@index([organizationId])
}
model Favorite {
userId Int
bookId Int
createdAt DateTime @default(now())
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
book Book @relation(fields: [bookId], references: [id], onDelete: Cascade)
@@id([userId, bookId])
}
// Журнал всех действий — основа статистики
model Event {
id Int @id @default(autoincrement())
organizationId Int?
organization Organization? @relation(fields: [organizationId], references: [id], onDelete: Cascade)
type String // ORG_REGISTER | ORG_UPDATE | USERS_IMPORT | PASSWORD_RESET | PASSWORD_CHANGE | LIST_CREATE | ENDORSE | LOGIN | LOGIN_FAILED | LOGOUT | REGISTER | VIEW | READ | DOWNLOAD | SEARCH | FAVORITE | BOOK_CREATE | BOOK_UPDATE | BOOK_DELETE | USER_UPDATE | SUBMIT | SUBMIT_APPROVE | SUBMIT_REJECT
userId Int?
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
userKind String? // STUDENT | TEACHER | STAFF на момент события — для статистики по аудитории
bookId Int?
book Book? @relation(fields: [bookId], references: [id], onDelete: SetNull)
query String?
resultCount Int?
ip String?
userAgent String?
browser String?
os String?
device String?
meta String? // JSON
day String @db.Char(10) // YYYY-MM-DD в часовом поясе университета
hour Int @db.SmallInt
weekday Int @db.SmallInt // 0 = понедельник
createdAt DateTime @default(now()) @db.Timestamptz(3)
@@index([type, day])
@@index([day])
@@index([userId, createdAt])
@@index([bookId, type])
@@index([createdAt])
@@index([userKind, day])
@@index([organizationId, day])
@@index([organizationId, type, day])
}
// Списки литературы преподавателей по дисциплинам
model ReadingList {
id Int @id @default(autoincrement())
title String // дисциплина / курс
description String?
groups String @default(",") // ",ИС-21-01,ИС-21-02," — для поиска по группе
semester String?
isPublic Boolean @default(true) // виден всей организации, а не только группам
organizationId Int
organization Organization @relation(fields: [organizationId], references: [id], onDelete: Cascade)
ownerId Int
owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
items ReadingListItem[]
@@index([ownerId])
@@index([organizationId])
}
model ReadingListItem {
id Int @id @default(autoincrement())
listId Int
list ReadingList @relation(fields: [listId], references: [id], onDelete: Cascade)
bookId Int
book Book @relation(fields: [bookId], references: [id], onDelete: Cascade)
required Boolean @default(true) // основная / дополнительная литература
note String? // комментарий преподавателя (главы, страницы)
position Int @default(0)
createdAt DateTime @default(now())
@@unique([listId, bookId])
@@index([bookId])
}