Документация: разделы и статьи в docs.html

- Добавлены 12 разделов документации: Журнал, Отчёты о занятиях,
  Ученики, Группы, Обратная связь, Короткие сообщения, Чаты, Фото,
  Файлы, Ссылки, Закладки, Заметки (каждый со вступительной статьёй)
- Сид разделов в lib/docs.js (ensureDocsTables) и db/migration.sql
-doc_images добавлен в sweepOrphanedUploads и BROKEN_IMAGE_SOURCES
- Исправлен дубль docSectionIds в backup-restore.js
- Роуты /api/docs/* в server.js
- Страницы public/docs.html, public/docs-public.html, скрипты
  public/js/docs.js, public/js/docs-public.js, public/js/md.js
This commit is contained in:
dev
2026-10-23 21:33:48 +03:00
parent 4ba0f810b2
commit 97426c70af
11 changed files with 2565 additions and 6 deletions
+30
View File
@@ -369,6 +369,36 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo
- **Новую переменную `CERT_*` документируют в четырёх местах**: `entrypoint.sh`, `docker-compose.yml` (app → `environment`), `.env.example`, `README.md` (раздел «Сертификат и HTTPS») и здесь - **Новую переменную `CERT_*` документируют в четырёх местах**: `entrypoint.sh`, `docker-compose.yml` (app → `environment`), `.env.example`, `README.md` (раздел «Сертификат и HTTPS») и здесь
- **Перевыпуск серверного сертификата** = `rm certs/cert.pem certs/key.pem && docker compose up -d --force-recreate app` (или изменение `CERT_HOSTNAMES` — хеш в `certs/.san` заставит entrypoint перевыпустить его сам). Корневой CA остаётся тем же, поэтому доверие у клиентов не теряется и GPO менять не нужно. **Полная замена корневого CA** = удалить `root-ca.pem`, `root-ca-key.pem`, `cert.pem`, `key.pem` и пересоздать контейнер; после этого старый корневой сертификат в GPO/хранилищах надо удалить, а новый — раздать заново. Если меняете SAN или корневой CA у себя на стенде — предупредите пользователя явно, а не меняйте молча - **Перевыпуск серверного сертификата** = `rm certs/cert.pem certs/key.pem && docker compose up -d --force-recreate app` (или изменение `CERT_HOSTNAMES` — хеш в `certs/.san` заставит entrypoint перевыпустить его сам). Корневой CA остаётся тем же, поэтому доверие у клиентов не теряется и GPO менять не нужно. **Полная замена корневого CA** = удалить `root-ca.pem`, `root-ca-key.pem`, `cert.pem`, `key.pem` и пересоздать контейнер; после этого старый корневой сертификат в GPO/хранилищах надо удалить, а новый — раздать заново. Если меняете SAN или корневой CA у себя на стенде — предупредите пользователя явно, а не меняйте молча
### 3r. Документация (`lib/docs.js`, `server.js`, `public/docs.html`, `public/js/md.js`)
- **Назначение**: внутренняя справка — дерево разделов и статьи в Markdown. Структуру (разделы, порядок) создаёт только админ; писать статьи может админ и тьютор в разделах с `tutor_edit = true`. Публичный доступ по умолчанию выключен, но есть флаг `is_public` и страница `docs-public.html`
- **Таблицы**:
- `doc_sections` (`parent_id` — самоссылка `ON DELETE CASCADE`, `title`, `sort_order`, `tutor_edit`, `is_public`) — дерево любой глубины
- `doc_articles` (`section_id`, `slug UNIQUE`, `title`, `body` — Markdown, `sort_order`, `is_published`, `is_public`, `author_id` c `ON DELETE SET NULL`)
- `doc_images` (`article_id` **nullable**, `path`, `uploaded_by`) — реестр картинок для `sweepOrphanedUploads()`
- **Схема в трёх местах**: `db/init.sql`, `db/migration.sql`, `ensureDocsTables(pool)` в `lib/docs.js` — вызывается из `ensureUsersAndFirstAdmin()` **с аргументом `pool`** (без него падает `Cannot read properties of undefined (reading 'query')`, таблицы не создаются, а `sweepOrphanedUploads()` затем валится на `doc_images`). Cхема в `init.sql` нужна только для свежих БД; `ensureDocsTables` досоздаёт всё на существующих
- **Сид**: если `doc_sections` пуста, `ensureDocsTables` создаёт раздел «Начало работы» (`tutor_edit = true`) и статью `intro` — только на пустой БД, повторно не перезаписывает
- **Права** (в `lib/docs.js`: `canWriteSection`, `canEditArticle`, проверки внутри `createArticle`/`updateArticle`/`deleteArticle`):
- админ — любые разделы и статьи, управление структурой и `is_public`;
- тьютор — создаёт статью только в разделе с `tutor_edit = true`, правит/удаляет **только свои** статьи в таком разделе; `is_public` ему недоступен (сервер сохраняет текущее значение);
- `can_edit`/`can_write` приходят в `GET /api/docs/tree`, фронт по ним рисует кнопки, но сервер проверяет права заново;
- не-admin видит только `is_published = true` или свои черновики
- **Роуты** (валидация в `server.js`, логика в `lib/docs.js`, ошибки через `docsError`):
- `GET /api/docs/tree`, `GET /api/docs/search?q=`, `GET /api/docs/articles/:slug|:id`
- `POST/PUT/DELETE /api/docs/sections…` + `PUT /api/docs/sections/reorder` — `requireAdmin`; `reorder` **регистрируется до** `/:id`
- `POST/PUT/DELETE /api/docs/articles…` + `PUT /api/docs/articles/reorder` — `requireAuth`; `reorder` до `/:id`
- `POST /api/docs/images` — `requireAuth`, multer `upload.single('image')`, `convertPhoto`, `registerDocImage`; файл сохраняется в `uploads/` (как обычно) и строкой в `doc_images` с `article_id = NULL`
- `GET /api/docs/public/tree`, `GET /api/docs/public/articles/:slug` — **без авторизации**, под `apiLimiter`; статья отдаётся только если `is_public` у статьи, у её раздела и у всех родителей
- **Связывание картинок с статьёй — по пути**: при `POST/PUT` статьи `linkImages()` обновляет `doc_images.article_id` для всех `NULL`-строк, чей `path` встречается в теле (`/uploads/<name>`); `pruneImages()` удаляет строки статьи, которых больше нет в Markdown, и возвращает пути — роут вызывает `safeUnlink` + `thumbUnlinkFor`. Поэтому картинку можно вставить до первого сохранения статьи (в том числе из буфера обмена), и она не потеряется
- **`doc_images.path` обязателен в `sweepOrphanedUploads()`** и в `BROKEN_IMAGE_SOURCES` — иначе sweep удалит картинки, на которые ссылается только Markdown, или они не попадут в отчёт о битых изображениях
- **Бэкап**: `doc_sections`/`doc_articles`/`doc_images` входят в `BACKUP_TABLES` и `BACKUP_SEQUENCE_TABLES`, в `buildBackupArchive`, в `normalizeRestoreData` (`docSections`/`docArticles`/`docImages`, путь — `optUploadPath`) и в restore. Restore вставляет разделы сначала с `parent_id = NULL`, затем отдельным проходом проставляет родителей (иначе FK на ещё не вставленного родителя); у статей `author_id` и у картинок `article_id`/`uploaded_by` берутся через `(SELECT id …)`, отсутствующая ссылка даёт `NULL` (колонки nullable). `doc_images` удаляется/вставляется вместе с остальными таблицами и до `users`
- **Markdown-рендерер — свой, без зависимостей**: `public/js/md.js` (`window.WhatIDoMD.render`). Разрешены заголовки h1–h4, параграфы, списки (в т.ч. вложенные и чекбоксы), цитаты, код (inline и блок), таблицы, `hr`, ссылки и картинки. HTML экранируется **до** разметки, URL пропускает только `http(s)` и `/uploads/<name>` — хранимый XSS через тело статьи невозможен, `DOMPurify`/`marked` не нужны. Картинки рендерятся через `thumbUrl()` (`thumbSrc`, если доступен) с полным путём в `data-img` — лайтбокс открывает оригинал
- **Страницы**:
- `public/docs.html` + `public/js/docs.js` — дерево слева (сворачивание в `localStorage`, поиск, стрелки порядка у админа), просмотр статьи справа, инлайн-редактор с панелью Markdown и живым предпросмотром. Картинки вставляются кнопкой, Ctrl+V и drag&drop; `Ctrl/Cmd+S` сохраняет, `beforeunload` предупреждает о несохранённых правках. Статья в адресе — `#a=<slug>`
- `public/docs-public.html` + `public/js/docs-public.js` — самостоятельная публичная страница без `admin.js`, тот же рендерер; `?slug=`
- пункт сайдбара `docs` («Документация», иконка `book-open-text`) — в массиве `base` в `public/admin.js`
- **Новая страница/поле**: не забудьте про `data-page="docs"`, `buildSidebar()` и `renderIcons()` после перерисовки дерева; иконки для `data-lucide` брать из уже используемых в `public/` имён (бандл Lucide 1.44 — PascalCase-экспорты)
### 4. API Patterns ### 4. API Patterns
- **Middleware**: `requireAuth` — читает `X-Auth-Token`, 401 без валидной активной сессии. `requireAdmin` — самодостаточный (внутри вызывает `requireAuth`, если `req.user` ещё нет), 403 при `role !== 'admin'`. `optionalAuth` — для публичных страниц с персонализацией - **Middleware**: `requireAuth` — читает `X-Auth-Token`, 401 без валидной активной сессии. `requireAdmin` — самодостаточный (внутри вызывает `requireAuth`, если `req.user` ещё нет), 403 при `role !== 'admin'`. `optionalAuth` — для публичных страниц с персонализацией
- **Филиалы**: `branchScope(user)` / `branchWhere(user, alias)` — для не-admin `user.branch_ids` (из `user_branches`) ограничивают выборку; у `admin` `ids = null` и фильтр не добавляется - **Филиалы**: `branchScope(user)` / `branchWhere(user, alias)` — для не-admin `user.branch_ids` (из `user_branches`) ограничивают выборку; у `admin` `ids = null` и фильтр не добавляется
+50 -3
View File
@@ -19,14 +19,14 @@ const BACKUP_TABLES = [
'lesson_reports', 'lesson_report_versions', 'audit_log', 'notifications', 'lesson_reports', 'lesson_report_versions', 'audit_log', 'notifications',
'notification_reads', 'banned_ips', 'chat_threads', 'chat_messages', 'chat_attachments', 'notification_reads', 'banned_ips', 'chat_threads', 'chat_messages', 'chat_attachments',
'short_messages', 'feedbacks', 'bookmarks', 'student_face_refs', 'photo_faces', 'short_messages', 'feedbacks', 'bookmarks', 'student_face_refs', 'photo_faces',
'student_work_marks', 'student_work_marks', 'doc_sections', 'doc_articles', 'doc_images',
]; ];
const BACKUP_SEQUENCE_TABLES = [ const BACKUP_SEQUENCE_TABLES = [
'groups', 'students', 'entries', 'project_files', 'branches', 'users', 'user_notes', 'group_photos', 'groups', 'students', 'entries', 'project_files', 'branches', 'users', 'user_notes', 'group_photos',
'entry_photos', 'modules', 'student_photos', 'share_links', 'photo_jobs', 'lesson_reports', 'entry_photos', 'modules', 'student_photos', 'share_links', 'photo_jobs', 'lesson_reports',
'lesson_report_versions', 'audit_log', 'notifications', 'chat_threads', 'chat_messages', 'lesson_report_versions', 'audit_log', 'notifications', 'chat_threads', 'chat_messages',
'chat_attachments', 'short_messages', 'feedbacks', 'bookmarks', 'student_face_refs', 'photo_faces', 'chat_attachments', 'short_messages', 'feedbacks', 'bookmarks', 'student_face_refs', 'photo_faces',
'student_work_marks', 'student_work_marks', 'doc_sections', 'doc_articles', 'doc_images',
]; ];
function isSupportedBackupVersion(data) { function isSupportedBackupVersion(data) {
@@ -623,6 +623,53 @@ function normalizeRestoreData(data) {
created_at: optTs(x.created_at), created_at: optTs(x.created_at),
updated_at: optTs(x.updated_at), updated_at: optTs(x.updated_at),
})); }));
const docSections = (data.doc_sections || []).map(x => ({
id: reqInt(x.id),
parent_id: x.parent_id == null ? null : reqInt(x.parent_id),
title: optText(x.title, 200) || '',
sort_order: optInt(x.sort_order, -10000000, 10000000) ?? 0,
tutor_edit: x.tutor_edit === true,
is_public: x.is_public === true,
created_at: optTs(x.created_at),
updated_at: optTs(x.updated_at),
})).filter(x => x.title);
const docSectionIds = new Set(docSections.map(x => x.id));
for (const section of docSections) {
if (section.parent_id != null && (!docSectionIds.has(section.parent_id) || section.parent_id === section.id)) {
section.parent_id = null;
}
}
const docArticles = (data.doc_articles || []).map(x => ({
id: reqInt(x.id),
section_id: reqInt(x.section_id),
slug: optText(x.slug, 140) || '',
title: optText(x.title, 200) || '',
body: optText(x.body, 200000) || '',
sort_order: optInt(x.sort_order, -10000000, 10000000) ?? 0,
is_published: x.is_published !== false,
is_public: x.is_public === true,
author_id: x.author_id == null ? null : reqInt(x.author_id),
created_at: optTs(x.created_at),
updated_at: optTs(x.updated_at),
})).filter(x => x.slug && x.title && x.section_id);
const usedDocSlugs = new Set();
for (const article of docArticles) {
let slug = article.slug;
let suffix = 1;
while (usedDocSlugs.has(slug)) {
suffix += 1;
slug = `${article.slug.slice(0, 130)}-${suffix}`;
}
article.slug = slug;
usedDocSlugs.add(slug);
}
const docImages = (data.doc_images || []).map(x => ({
id: reqInt(x.id),
article_id: x.article_id == null ? null : reqInt(x.article_id),
path: optUploadPath(x.path, 300) || '',
uploaded_by: x.uploaded_by == null ? null : reqInt(x.uploaded_by),
created_at: optTs(x.created_at),
})).filter(x => x.path);
const faceRefs = (data.student_face_refs || []).map(x => ({ const faceRefs = (data.student_face_refs || []).map(x => ({
id: reqInt(x.id), id: reqInt(x.id),
student_id: reqInt(x.student_id), student_id: reqInt(x.student_id),
@@ -646,7 +693,7 @@ function normalizeRestoreData(data) {
created_at: optTs(x.created_at), created_at: optTs(x.created_at),
updated_at: optTs(x.updated_at), updated_at: optTs(x.updated_at),
})).filter(x => x.source_id && x.photo_path); })).filter(x => x.source_id && x.photo_path);
return { groups, students, entries, project_files, settings, branches, users, user_branches, user_settings, user_notes, entry_photos, student_photos, group_photos, share_links, modules, photo_jobs, lesson_reports, lesson_report_versions, audit_log, notifications, notification_reads, banned_ips, chat_threads, chat_messages, chat_attachments, short_messages, feedbacks, bookmarks, student_face_refs: faceRefs, photo_faces: faceRows, student_work_marks }; return { groups, students, entries, project_files, settings, branches, users, user_branches, user_settings, user_notes, entry_photos, student_photos, group_photos, share_links, modules, photo_jobs, lesson_reports, lesson_report_versions, audit_log, notifications, notification_reads, banned_ips, chat_threads, chat_messages, chat_attachments, short_messages, feedbacks, bookmarks, student_face_refs: faceRefs, photo_faces: faceRows, student_work_marks, doc_sections: docSections, doc_articles: docArticles, doc_images: docImages };
} }
module.exports = { module.exports = {
+66
View File
@@ -879,3 +879,69 @@ CREATE TABLE IF NOT EXISTS broken_images (
); );
CREATE INDEX IF NOT EXISTS idx_broken_images_purge ON broken_images(purge_at); CREATE INDEX IF NOT EXISTS idx_broken_images_purge ON broken_images(purge_at);
CREATE TABLE IF NOT EXISTS doc_sections (
id SERIAL PRIMARY KEY,
parent_id INT REFERENCES doc_sections(id) ON DELETE CASCADE,
title VARCHAR(200) NOT NULL,
sort_order INT NOT NULL DEFAULT 0,
tutor_edit BOOLEAN NOT NULL DEFAULT false,
is_public BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_doc_sections_parent ON doc_sections(parent_id, sort_order, id);
CREATE TABLE IF NOT EXISTS doc_articles (
id SERIAL PRIMARY KEY,
section_id INT NOT NULL REFERENCES doc_sections(id) ON DELETE CASCADE,
slug VARCHAR(140) NOT NULL UNIQUE,
title VARCHAR(200) NOT NULL,
body TEXT NOT NULL DEFAULT '',
sort_order INT NOT NULL DEFAULT 0,
is_published BOOLEAN NOT NULL DEFAULT true,
is_public BOOLEAN NOT NULL DEFAULT false,
author_id INT REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_doc_articles_section ON doc_articles(section_id, sort_order, id);
CREATE INDEX IF NOT EXISTS idx_doc_articles_author ON doc_articles(author_id);
CREATE TABLE IF NOT EXISTS doc_images (
id SERIAL PRIMARY KEY,
article_id INT REFERENCES doc_articles(id) ON DELETE CASCADE,
path TEXT NOT NULL,
uploaded_by INT REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_doc_images_article ON doc_images(article_id);
CREATE INDEX IF NOT EXISTS idx_doc_images_path ON doc_images(path);
INSERT INTO doc_sections (title, sort_order, tutor_edit)
SELECT 'Журнал', 10, true WHERE NOT EXISTS (SELECT 1 FROM doc_sections WHERE title = 'Журнал');
INSERT INTO doc_sections (title, sort_order, tutor_edit)
SELECT 'Отчёты о занятиях', 20, true WHERE NOT EXISTS (SELECT 1 FROM doc_sections WHERE title = 'Отчёты о занятиях');
INSERT INTO doc_sections (title, sort_order, tutor_edit)
SELECT 'Ученики', 30, true WHERE NOT EXISTS (SELECT 1 FROM doc_sections WHERE title = 'Ученики');
INSERT INTO doc_sections (title, sort_order, tutor_edit)
SELECT 'Группы', 40, true WHERE NOT EXISTS (SELECT 1 FROM doc_sections WHERE title = 'Группы');
INSERT INTO doc_sections (title, sort_order, tutor_edit)
SELECT 'Обратная связь', 50, true WHERE NOT EXISTS (SELECT 1 FROM doc_sections WHERE title = 'Обратная связь');
INSERT INTO doc_sections (title, sort_order, tutor_edit)
SELECT 'Короткие сообщения', 60, true WHERE NOT EXISTS (SELECT 1 FROM doc_sections WHERE title = 'Короткие сообщения');
INSERT INTO doc_sections (title, sort_order, tutor_edit)
SELECT 'Чаты', 70, true WHERE NOT EXISTS (SELECT 1 FROM doc_sections WHERE title = 'Чаты');
INSERT INTO doc_sections (title, sort_order, tutor_edit)
SELECT 'Фото', 80, true WHERE NOT EXISTS (SELECT 1 FROM doc_sections WHERE title = 'Фото');
INSERT INTO doc_sections (title, sort_order, tutor_edit)
SELECT 'Файлы', 90, true WHERE NOT EXISTS (SELECT 1 FROM doc_sections WHERE title = 'Файлы');
INSERT INTO doc_sections (title, sort_order, tutor_edit)
SELECT 'Ссылки', 100, true WHERE NOT EXISTS (SELECT 1 FROM doc_sections WHERE title = 'Ссылки');
INSERT INTO doc_sections (title, sort_order, tutor_edit)
SELECT 'Закладки', 110, true WHERE NOT EXISTS (SELECT 1 FROM doc_sections WHERE title = 'Закладки');
INSERT INTO doc_sections (title, sort_order, tutor_edit)
SELECT 'Заметки', 120, true WHERE NOT EXISTS (SELECT 1 FROM doc_sections WHERE title = 'Заметки');
+718
View File
@@ -0,0 +1,718 @@
const crypto = require('crypto');
const { reqInt, reqStr, optText } = require('../backup-restore');
const DOC_TITLE_MAX = 200;
const DOC_BODY_MAX = 200000;
const DOC_SLUG_MAX = 140;
const DOC_SECTION_TITLE_MAX = 200;
const DOC_SEARCH_LIMIT = 30;
const TRANSLIT = {
а: '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',
};
const DOC_SEED_TITLE = 'Начало работы';
const DOC_SEED_BODY = `## Добро пожаловать в документацию
Это внутренний раздел справки. Здесь можно описывать работу с журналом, отчётами, отзывами и остальными разделами системы.
**Как пользоваться**
- слева — дерево разделов и статей;
- нажмите на статью, чтобы прочитать её;
- автор статьи (или администратор) увидит кнопку «Редактировать».
**Форматирование**
Текст пишется в Markdown: \`**жирный**\`, \`*курсив*\`, списки, таблицы и картинки.
1. Выделите текст и нажмите кнопку на панели.
2. Картинку можно вставить из буфера обмена (Ctrl+V) или перетащить в поле текста.
3. Клик по картинке в статье открывает её в полном размере.
> Раздел можно наполнить инструкциями для тьюторов и администраторов.
`;
function httpError(status, message) {
const err = new Error(message);
err.status = status;
return err;
}
function docsError(res, e, fallback, label) {
if (e && e.status) return res.status(e.status).json({ error: e.message });
if (e && (e.message === 'Invalid string' || e.message === 'Invalid string length' || e.message === 'Invalid integer')) {
return res.status(400).json({ error: 'Неверные данные' });
}
console.error(`${label}:`, e);
return res.status(500).json({ error: fallback });
}
function slugify(value) {
const text = String(value || '').toLowerCase();
let out = '';
for (const ch of text) {
if (Object.prototype.hasOwnProperty.call(TRANSLIT, ch)) out += TRANSLIT[ch];
else out += ch;
}
return out
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, DOC_SLUG_MAX - 10);
}
async function uniqueSlug(client, title, excludeId) {
const base = slugify(title) || 'doc';
for (let i = 0; i < 50; i++) {
const slug = i === 0 ? base : `${base}-${i + 1}`;
const { rowCount } = await client.query(
'SELECT 1 FROM doc_articles WHERE slug = $1 AND ($2::int IS NULL OR id <> $2)',
[slug, excludeId || null]
);
if (!rowCount) return slug;
}
return `${base}-${crypto.randomBytes(3).toString('hex')}`;
}
async function ensureDocsTables(pool) {
await pool.query(`CREATE TABLE IF NOT EXISTS doc_sections (
id SERIAL PRIMARY KEY,
parent_id INT REFERENCES doc_sections(id) ON DELETE CASCADE,
title VARCHAR(200) NOT NULL,
sort_order INT NOT NULL DEFAULT 0,
tutor_edit BOOLEAN NOT NULL DEFAULT false,
is_public BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
)`);
await pool.query('CREATE INDEX IF NOT EXISTS idx_doc_sections_parent ON doc_sections(parent_id, sort_order, id)');
await pool.query(`CREATE TABLE IF NOT EXISTS doc_articles (
id SERIAL PRIMARY KEY,
section_id INT NOT NULL REFERENCES doc_sections(id) ON DELETE CASCADE,
slug VARCHAR(140) NOT NULL UNIQUE,
title VARCHAR(200) NOT NULL,
body TEXT NOT NULL DEFAULT '',
sort_order INT NOT NULL DEFAULT 0,
is_published BOOLEAN NOT NULL DEFAULT true,
is_public BOOLEAN NOT NULL DEFAULT false,
author_id INT REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
)`);
await pool.query('CREATE INDEX IF NOT EXISTS idx_doc_articles_section ON doc_articles(section_id, sort_order, id)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_doc_articles_author ON doc_articles(author_id)');
await pool.query(`CREATE TABLE IF NOT EXISTS doc_images (
id SERIAL PRIMARY KEY,
article_id INT REFERENCES doc_articles(id) ON DELETE CASCADE,
path TEXT NOT NULL,
uploaded_by INT REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
)`);
await pool.query('CREATE INDEX IF NOT EXISTS idx_doc_images_article ON doc_images(article_id)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_doc_images_path ON doc_images(path)');
const { rows } = await pool.query('SELECT 1 FROM doc_sections LIMIT 1');
if (rows.length) return;
const DOC_SECTIONS = [
{
title: 'Журнал',
slug: 'zhurnal',
articleTitle: 'Ведение журнала посещений',
articleBody: `## Журнал посещений
В журнале фиксируются посещения занятий учениками. Каждая запись содержит дату, группу, ученика, описание занятия и прикреплённые файлы (фото, видео, документы).
Тьютор может:
- создавать и редактировать записи посещений;
- прикреплять фото и файлы к записи;
- пользоваться короткими сообщениями для быстрого отзыва.
Администратор управляет группами, модулями и филиалами.`,
},
{
title: 'Отчёты о занятиях',
slug: 'otchety',
articleTitle: 'Отчёты о занятиях',
articleBody: `## Отчёты о занятиях
Отчёт о занятии — текстовое резюме, которое тьютор пишет после урока. Может проверяться ИИ: грамматика, стиль, соответствие шаблону.
Возможности:
- создание и редактирование отчётов;
- история версий с возвратом к любому варианту;
- ИИ-переписывание и откат к тексту тьютора;
- уведомления о готовности отчёта.`,
},
{
title: 'Ученики',
slug: 'ucheniki',
articleTitle: 'Работа с учениками',
articleBody: `## Ученики
Карточка ученика содержит личные данные, контакты, навыки, достижения, опыт и образование. Также доступны фото профиля и библиотека лиц.
Разделы карточки:
- профиль ученика;
- журнал посещений;
- короткие сообщения;
- обратная связь;
- фото;
- лица (распознавание и привязка).`,
},
{
title: 'Группы',
slug: 'gruppy',
articleTitle: 'Группы',
articleBody: `## Группы
Группа объединяет учеников по расписанию: день недели, время начала и окончания, филиал.
В(group) можно:
- вести galerry фотографий группы;
- сканировать лица на фото и привязывать их к ученикам;
- управлять обложкой группы.`,
},
{
title: 'Обратная связь',
slug: 'obratnaya-svyaz',
articleTitle: 'Обратная связь',
articleBody: `## Обратная связь
Отзывы тьютора о занятии — короткие деловая записи, отправляемые родителям или ученикам.
Настройки:
- персональная модель ИИ и промпт отзыва;
- несколько шаблонов промптов;
- отметка «Использовано» для коротких сообщений;
- статус отправки отзыва.`,
},
{
title: 'Короткие сообщения',
slug: 'korotkie-soobshcheniya',
articleTitle: 'Короткие сообщения',
articleBody: `## Короткие сообщения
Короткие сообщения — заготовки отзывов, которые тьютор может быстро вставить в обратную связь.
Отметка «Использовано» показывает, что сообщение уже задействовано в отправленном отзыве. Оценка уровня работы (+1 / 0 / −1) формирует динамику работы на дашборде.`,
},
{
title: 'Чаты',
slug: 'chats',
articleTitle: 'Чаты тьютор ↔ администратор',
articleBody: `## Чат
Личные диалоги 1:1 между тьютором и администратором. На каждого тьютора — один тред.
Возможности:
- отправка текста и вложений (в т.ч. из буфера обмена);
- правка и удаление своих сообщений;
- скрытие и восстановление диалогов администратором;
- подсчёт непрочитанных сообщений.`,
},
{
title: 'Фото',
slug: 'foto',
articleTitle: 'Фото и galerie',
articleBody: `## Фото
Фотографии хранятся в galerry групп и в карточках записей журнала. Поддерживается улучшение фото через ИИ-сервис (опционально).
Библиотека лиц позволяет распознавать учеников на фото и привязывать их к карточкам. Найденные лица можно привязать вручную.`,
},
{
title: 'Файлы',
slug: 'failly',
articleTitle: 'Файлы и вложения',
articleBody: `## Файлы
К записи в журнале можно прикрепить фото, видео и документы. Изображения отдаются с миниатюрами, видео — с возможностью проигрывания в плеере.
Все загрузки проходят проверку по списку разрешённых расширений и лимитам размера.`,
},
{
title: 'Ссылки',
slug: 'ssylki',
articleTitle: 'Публичные ссылки',
articleBody: `## Публичные ссылки
Публичная ссылка открывает доступ к фото и видео группы без авторизации — удобно для показа родителям.
Настройки ссылки: диапазон дат, показ имён учеников, даты занятия, фотографий группы. Срок действия ссылки ограничен.`,
},
{
title: 'Закладки',
slug: 'zakladki',
articleTitle: 'Закладки',
articleBody: `## Закладки
Общие закладки-ссылки на полезные ресурсы. У каждой закладки есть название, URL, описание и картинка (логотип или обложка).
Редактировать закладки может только администратор. Тьюторы видят только активные закладки.`,
},
{
title: 'Заметки',
slug: 'zametki',
articleTitle: 'Заметки',
articleBody: `## Заметки
Личные заметки пользователя: заголовок, текст, теги и цвет карточки. Заметки доступны только их автору.
Возможности:
- создание, редактирование, удаление;
- перетаскиванием меняется порядок карточек;
- мягкое удаление в корзину с возможностью восстановления.`,
},
];
for (const [i, sec] of DOC_SECTIONS.entries()) {
const section = await pool.query(
'INSERT INTO doc_sections (title, sort_order, tutor_edit) VALUES ($1, $2, true) RETURNING id',
[sec.title, (i + 1) * 10]
);
await pool.query(
`INSERT INTO doc_articles (section_id, slug, title, body, sort_order)
VALUES ($1, $2, $3, $4, 10)`,
[section.rows[0].id, sec.slug, sec.articleTitle, sec.articleBody]
);
}
}
function canWriteSection(user, section) {
if (!user || !section) return false;
return user.role === 'admin' || section.tutor_edit === true;
}
function canEditArticle(user, article, section) {
if (!user || !article) return false;
if (user.role === 'admin') return true;
return article.author_id != null && Number(article.author_id) === Number(user.id) && !!section && section.tutor_edit === true;
}
async function getSection(pool, id) {
const { rows } = await pool.query(
'SELECT id, parent_id, title, sort_order, tutor_edit, is_public FROM doc_sections WHERE id = $1',
[id]
);
if (!rows.length) throw httpError(404, 'Раздел не найден');
return rows[0];
}
async function sectionHasPublicAncestors(pool, parentId) {
let current = parentId;
const visited = new Set();
while (current) {
if (visited.has(current)) return false;
visited.add(current);
const { rows } = await pool.query('SELECT id, parent_id, is_public FROM doc_sections WHERE id = $1', [current]);
if (!rows.length) return false;
if (!rows[0].is_public) return false;
current = rows[0].parent_id;
}
return true;
}
async function docsTree(pool, user) {
const admin = user.role === 'admin';
const sections = (await pool.query(
'SELECT id, parent_id, title, sort_order, tutor_edit, is_public FROM doc_sections ORDER BY sort_order ASC, id ASC'
)).rows;
const articles = (await pool.query(
`SELECT a.id, a.section_id, a.slug, a.title, a.sort_order, a.is_published, a.is_public, a.author_id, a.updated_at,
u.name AS author_name
FROM doc_articles a
LEFT JOIN users u ON u.id = a.author_id
WHERE $1::boolean OR a.is_published = true OR a.author_id = $2
ORDER BY a.sort_order ASC, a.id ASC`,
[admin, user.id]
)).rows;
const nodes = new Map();
for (const s of sections) {
nodes.set(s.id, {
...s,
can_write: canWriteSection(user, s),
children: [],
articles: [],
});
}
const roots = [];
for (const node of nodes.values()) {
const parent = node.parent_id ? nodes.get(node.parent_id) : null;
(parent ? parent.children : roots).push(node);
}
for (const a of articles) {
const section = nodes.get(a.section_id);
if (!section) continue;
section.articles.push({
id: a.id,
section_id: a.section_id,
slug: a.slug,
title: a.title,
sort_order: a.sort_order,
is_published: a.is_published,
is_public: a.is_public,
author_id: a.author_id,
author_name: a.author_name,
updated_at: a.updated_at,
can_edit: canEditArticle(user, a, section),
});
}
return { sections: roots };
}
async function getArticle(pool, user, key, { publicOnly = false } = {}) {
const numeric = /^\d+$/.test(String(key));
const { rows } = await pool.query(
`SELECT a.*, u.name AS author_name,
s.title AS section_title, s.tutor_edit, s.is_public AS section_public, s.parent_id
FROM doc_articles a
JOIN doc_sections s ON s.id = a.section_id
LEFT JOIN users u ON u.id = a.author_id
WHERE ${numeric ? 'a.id = $1' : 'a.slug = $1'}`,
[numeric ? Number(key) : String(key)]
);
if (!rows.length) throw httpError(404, 'Статья не найдена');
const article = rows[0];
const section = { id: article.section_id, tutor_edit: article.tutor_edit, is_public: article.section_public };
if (publicOnly) {
if (!article.is_published || !article.is_public || !section.is_public) throw httpError(404, 'Статья не найдена');
if (!(await sectionHasPublicAncestors(pool, article.parent_id))) throw httpError(404, 'Статья не найдена');
} else if (user.role !== 'admin' && !article.is_published && article.author_id !== user.id) {
throw httpError(404, 'Статья не найдена');
}
article.can_edit = canEditArticle(user, article, section);
article.can_write_section = canWriteSection(user, section);
return article;
}
async function createSection(pool, data) {
const title = reqStr(data.title, DOC_SECTION_TITLE_MAX);
const parentId = data.parent_id == null || data.parent_id === '' ? null : reqInt(data.parent_id);
if (parentId) await getSection(pool, parentId);
const tutorEdit = data.tutor_edit === true;
const isPublic = data.is_public === true;
const { rows } = await pool.query(
`INSERT INTO doc_sections (parent_id, title, sort_order, tutor_edit, is_public)
VALUES ($1, $2, COALESCE((SELECT MAX(sort_order) FROM doc_sections WHERE parent_id IS NOT DISTINCT FROM $1), 0) + 10, $3, $4)
RETURNING id, parent_id, title, sort_order, tutor_edit, is_public`,
[parentId, title, tutorEdit, isPublic]
);
return rows[0];
}
async function updateSection(pool, id, data) {
const section = await getSection(pool, id);
const title = reqStr(data.title, DOC_SECTION_TITLE_MAX);
const tutorEdit = data.tutor_edit === true;
const isPublic = data.is_public === true;
let parentId = section.parent_id;
if (Object.prototype.hasOwnProperty.call(data, 'parent_id')) {
parentId = data.parent_id == null || data.parent_id === '' ? null : reqInt(data.parent_id);
if (parentId === Number(id)) throw httpError(400, 'Раздел не может быть родителем сам себе');
if (parentId) {
await getSection(pool, parentId);
let current = parentId;
const visited = new Set();
while (current) {
if (Number(current) === Number(id)) throw httpError(400, 'Нельзя переместить раздел внутрь своего подраздела');
if (visited.has(current)) break;
visited.add(current);
const { rows } = await pool.query('SELECT parent_id FROM doc_sections WHERE id = $1', [current]);
current = rows.length ? rows[0].parent_id : null;
}
}
}
const { rows } = await pool.query(
`UPDATE doc_sections SET title = $1, parent_id = $2, tutor_edit = $3, is_public = $4, updated_at = now()
WHERE id = $5
RETURNING id, parent_id, title, sort_order, tutor_edit, is_public`,
[title, parentId, tutorEdit, isPublic, id]
);
return rows[0];
}
async function deleteSection(pool, id) {
await getSection(pool, id);
const { rows } = await pool.query(
`WITH RECURSIVE sub AS (
SELECT id FROM doc_sections WHERE id = $1
UNION ALL
SELECT s.id FROM doc_sections s JOIN sub ON s.parent_id = sub.id
)
SELECT di.path
FROM doc_images di
JOIN doc_articles a ON a.id = di.article_id
WHERE a.section_id IN (SELECT id FROM sub)`,
[id]
);
await pool.query('DELETE FROM doc_sections WHERE id = $1', [id]);
return rows.map(r => r.path);
}
async function reorderSections(pool, ids) {
if (!ids.length) throw httpError(400, 'Некорректный порядок разделов');
const client = await pool.connect();
try {
await client.query('BEGIN');
for (let i = 0; i < ids.length; i++) {
const { rowCount } = await client.query(
'UPDATE doc_sections SET sort_order = $1, updated_at = now() WHERE id = $2',
[(i + 1) * 10, ids[i]]
);
if (!rowCount) throw httpError(404, 'Раздел не найден');
}
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release();
}
}
async function linkImages(client, articleId, body) {
const names = [...String(body || '').matchAll(/\/uploads\/([A-Za-z0-9._-]+)/g)].map(m => `/uploads/${m[1]}`);
if (!names.length) return;
await client.query(
'UPDATE doc_images SET article_id = $1 WHERE article_id IS NULL AND path = ANY($2::text[])',
[articleId, [...new Set(names)]]
);
}
async function pruneImages(client, articleId, body) {
const used = new Set([...String(body || '').matchAll(/\/uploads\/([A-Za-z0-9._-]+)/g)].map(m => `/uploads/${m[1]}`));
const { rows } = await client.query('SELECT id, path FROM doc_images WHERE article_id = $1', [articleId]);
const stale = rows.filter(r => !used.has(r.path));
if (!stale.length) return [];
await client.query('DELETE FROM doc_images WHERE id = ANY($1::int[])', [stale.map(r => r.id)]);
return stale.map(r => r.path);
}
async function createArticle(pool, user, data) {
const sectionId = reqInt(data.section_id);
const section = await getSection(pool, sectionId);
if (!canWriteSection(user, section)) throw httpError(403, 'Нет прав на создание статьи в этом разделе');
const title = reqStr(data.title, DOC_TITLE_MAX);
const body = optText(data.body, DOC_BODY_MAX);
const isPublished = data.is_published !== false;
const isPublic = user.role === 'admin' && data.is_public === true;
const client = await pool.connect();
try {
await client.query('BEGIN');
const slug = await uniqueSlug(client, title);
const { rows } = await client.query(
`INSERT INTO doc_articles (section_id, slug, title, body, sort_order, is_published, is_public, author_id)
VALUES ($1, $2, $3, $4,
COALESCE((SELECT MAX(sort_order) FROM doc_articles WHERE section_id = $1), 0) + 10,
$5, $6, $7)
RETURNING id, section_id, slug, title, body, sort_order, is_published, is_public, author_id, created_at, updated_at`,
[sectionId, slug, title, body, isPublished, isPublic, user.id]
);
await linkImages(client, rows[0].id, body);
await client.query('COMMIT');
return rows[0];
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release();
}
}
async function updateArticle(pool, user, id, data) {
const { rows: found } = await pool.query(
`SELECT a.*, s.tutor_edit FROM doc_articles a JOIN doc_sections s ON s.id = a.section_id WHERE a.id = $1`,
[id]
);
if (!found.length) throw httpError(404, 'Статья не найдена');
const current = found[0];
if (!canEditArticle(user, current, { tutor_edit: current.tutor_edit })) {
throw httpError(403, 'Нет прав на редактирование этой статьи');
}
const title = reqStr(data.title, DOC_TITLE_MAX);
const body = data.body === undefined ? current.body : optText(data.body, DOC_BODY_MAX);
let sectionId = current.section_id;
if (data.section_id != null && Number(data.section_id) !== Number(current.section_id)) {
sectionId = reqInt(data.section_id);
const target = await getSection(pool, sectionId);
if (!canWriteSection(user, target)) throw httpError(403, 'Нет прав на публикацию в выбранном разделе');
}
const isPublished = data.is_published === undefined ? current.is_published : data.is_published !== false;
const isPublic = user.role === 'admin'
? (data.is_public === undefined ? current.is_public : data.is_public === true)
: current.is_public;
const client = await pool.connect();
try {
await client.query('BEGIN');
const updated = await client.query(
`UPDATE doc_articles
SET section_id = $1, title = $2, body = $3, is_published = $4, is_public = $5,
sort_order = CASE WHEN section_id = $1 THEN sort_order
ELSE COALESCE((SELECT MAX(sort_order) FROM doc_articles WHERE section_id = $1), 0) + 10 END,
updated_at = now()
WHERE id = $6
RETURNING id, section_id, slug, title, body, sort_order, is_published, is_public, author_id, created_at, updated_at`,
[sectionId, title, body, isPublished, isPublic, id]
);
await linkImages(client, id, body);
const staleImages = await pruneImages(client, id, body);
await client.query('COMMIT');
return { item: updated.rows[0], staleImages };
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release();
}
}
async function deleteArticle(pool, user, id) {
const { rows } = await pool.query(
`SELECT a.*, s.tutor_edit FROM doc_articles a JOIN doc_sections s ON s.id = a.section_id WHERE a.id = $1`,
[id]
);
if (!rows.length) throw httpError(404, 'Статья не найдена');
if (!canEditArticle(user, rows[0], { tutor_edit: rows[0].tutor_edit })) {
throw httpError(403, 'Нет прав на удаление этой статьи');
}
const images = await pool.query('SELECT path FROM doc_images WHERE article_id = $1', [id]);
await pool.query('DELETE FROM doc_articles WHERE id = $1', [id]);
return images.rows.map(r => r.path);
}
async function reorderArticles(pool, sectionId, ids) {
const client = await pool.connect();
try {
await client.query('BEGIN');
for (let i = 0; i < ids.length; i++) {
const { rowCount } = await client.query(
'UPDATE doc_articles SET sort_order = $1 WHERE id = $2 AND section_id = $3',
[(i + 1) * 10, ids[i], sectionId]
);
if (!rowCount) throw httpError(404, 'Статья не найдена в разделе');
}
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK');
throw e;
} finally {
client.release();
}
}
async function registerImage(pool, { path, userId }) {
const { rows } = await pool.query(
'INSERT INTO doc_images (path, uploaded_by) VALUES ($1, $2) RETURNING id, path',
[path, userId]
);
return rows[0];
}
async function searchArticles(pool, user, query) {
const q = String(query || '').trim();
if (!q || q.length < 2) return [];
const admin = user.role === 'admin';
const { rows } = await pool.query(
`SELECT a.id, a.slug, a.title, a.section_id, s.title AS section_title, a.updated_at,
substring(a.body, GREATEST(position(lower($3) in lower(a.body)) - 80, 1), 220) AS excerpt
FROM doc_articles a
JOIN doc_sections s ON s.id = a.section_id
WHERE ($1::boolean OR a.is_published = true OR a.author_id = $2)
AND (a.title ILIKE $4 OR a.body ILIKE $4)
ORDER BY a.updated_at DESC
LIMIT ${DOC_SEARCH_LIMIT}`,
[admin, user.id, q, `%${q}%`]
);
return rows;
}
function publicSections(sections) {
const byId = new Map(sections.map(s => [s.id, s]));
const visible = new Map();
for (const s of sections) {
if (!s.is_public) continue;
let current = s.parent_id;
let ok = true;
const visited = new Set();
while (current) {
if (visited.has(current)) { ok = false; break; }
visited.add(current);
const parent = byId.get(current);
if (!parent || !parent.is_public) { ok = false; break; }
current = parent.parent_id;
}
if (ok) visible.set(s.id, s);
}
return visible;
}
async function publicTree(pool) {
const sections = (await pool.query(
'SELECT id, parent_id, title, sort_order, is_public FROM doc_sections WHERE is_public = true ORDER BY sort_order ASC, id ASC'
)).rows;
const visible = publicSections(sections);
const articles = (await pool.query(
`SELECT id, section_id, slug, title, sort_order, updated_at
FROM doc_articles
WHERE is_public = true AND is_published = true
ORDER BY sort_order ASC, id ASC`
)).rows;
const nodes = new Map();
for (const s of visible.values()) nodes.set(s.id, { ...s, children: [], articles: [] });
const roots = [];
for (const node of nodes.values()) {
const parent = node.parent_id ? nodes.get(node.parent_id) : null;
(parent ? parent.children : roots).push(node);
}
for (const a of articles) {
const section = nodes.get(a.section_id);
if (section) section.articles.push({ id: a.id, slug: a.slug, title: a.title, updated_at: a.updated_at });
}
return { sections: roots };
}
async function publicArticle(pool, slug) {
const { rows } = await pool.query(
`SELECT a.id, a.slug, a.title, a.body, a.updated_at, a.section_id, a.is_public, a.is_published,
s.title AS section_title, s.parent_id, s.is_public AS section_public
FROM doc_articles a
JOIN doc_sections s ON s.id = a.section_id
WHERE a.slug = $1`,
[String(slug)]
);
if (!rows.length) throw httpError(404, 'Статья не найдена');
const article = rows[0];
if (!article.is_public || !article.is_published || !article.section_public) {
throw httpError(404, 'Статья не найдена');
}
if (!(await sectionHasPublicAncestors(pool, article.parent_id))) throw httpError(404, 'Статья не найдена');
return article;
}
module.exports = {
DOC_TITLE_MAX,
DOC_BODY_MAX,
DOC_SECTION_TITLE_MAX,
ensureDocsTables,
docsTree,
getArticle,
getSection,
canWriteSection,
canEditArticle,
docsError,
createSection,
updateSection,
deleteSection,
reorderSections,
createArticle,
updateArticle,
deleteArticle,
reorderArticles,
registerImage,
searchArticles,
publicTree,
publicArticle,
};
+1
View File
@@ -63,6 +63,7 @@ function buildSidebar(active) {
{ page: 'files', label: 'Файлы', icon: 'folder' }, { page: 'files', label: 'Файлы', icon: 'folder' },
{ page: 'links', label: 'Ссылки', icon: 'link' }, { page: 'links', label: 'Ссылки', icon: 'link' },
{ page: 'bookmarks', label: 'Закладки', icon: 'bookmark' }, { page: 'bookmarks', label: 'Закладки', icon: 'bookmark' },
{ page: 'docs', label: 'Документация', icon: 'book-open-text' },
{ page: 'trash', label: 'Корзина', icon: 'trash-2' }, { page: 'trash', label: 'Корзина', icon: 'trash-2' },
{ page: 'notes', label: 'Заметки', icon: 'sticky-note' }, { page: 'notes', label: 'Заметки', icon: 'sticky-note' },
]; ];
+136
View File
@@ -0,0 +1,136 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Документация</title>
<style>
:root {
--bg: #f6f7f9;
--card: #ffffff;
--text: #1f2430;
--muted: #6b7280;
--border: #e3e6ec;
--accent: #2563eb;
}
@media (prefers-color-scheme: dark) {
:root {
--bg: #14161b;
--card: #1b1e25;
--text: #e6e8ee;
--muted: #9aa1ad;
--border: #2b2f39;
--accent: #5b8def;
}
}
* { box-sizing: border-box; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
line-height: 1.6;
}
a { color: var(--accent); }
.dp-head {
border-bottom: 1px solid var(--border);
background: var(--card);
position: sticky;
top: 0;
z-index: 10;
}
.dp-wrap { max-width: 1220px; margin: 0 auto; padding: 0 20px; }
.dp-head .dp-wrap { display: flex; align-items: center; gap: 12px; height: 58px; }
.dp-brand { font-weight: 700; font-size: 1.02rem; }
.dp-head-sub { color: var(--muted); font-size: .8rem; }
.dp-layout { display: grid; grid-template-columns: 280px minmax(0, 1fr); gap: 24px; align-items: start; padding-top: 24px; padding-bottom: 60px; }
.dp-side {
position: sticky;
top: 82px;
background: var(--card);
border: 1px solid var(--border);
border-radius: 14px;
padding: 10px;
max-height: calc(100dvh - 110px);
overflow: auto;
}
.dp-tree { display: flex; flex-direction: column; gap: 1px; }
.dp-section-row {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 8px;
border-radius: 8px;
font-size: .86rem;
font-weight: 600;
cursor: pointer;
user-select: none;
}
.dp-section-row:hover { background: rgba(127,127,127,.1); }
.dp-chev { border: none; background: none; color: var(--muted); padding: 0; display: inline-flex; cursor: pointer; }
.dp-chev svg { width: 14px; height: 14px; transition: transform .15s; }
.dp-chev.closed svg { transform: rotate(-90deg); }
.dp-chev svg, .dp-section-row svg { stroke: currentColor; }
.dp-section-row .dp-folder { width: 15px; height: 15px; flex: none; color: var(--muted); }
.dp-section-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.dp-article-row a {
display: block;
padding: 6px 8px;
border-radius: 8px;
color: var(--text);
text-decoration: none;
font-size: .84rem;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.dp-article-row a:hover { background: rgba(127,127,127,.08); }
.dp-article-row a.active { background: rgba(37,99,235,.13); color: var(--accent); font-weight: 600; }
.dp-empty { color: var(--muted); font-size: .85rem; padding: 14px 8px; text-align: center; }
.dp-article { background: var(--card); border: 1px solid var(--border); border-radius: 14px; padding: 28px 34px; min-height: 320px; }
.dp-crumbs { font-size: .74rem; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin-bottom: 8px; }
.dp-article h1 { font-size: 1.65rem; line-height: 1.25; margin: 0 0 18px; word-break: break-word; }
.dp-body { font-size: .96rem; line-height: 1.68; overflow-wrap: anywhere; }
.dp-body h1, .dp-body h2, .dp-body h3, .dp-body h4 { margin: 1.4em 0 .5em; line-height: 1.3; }
.dp-body h1 { font-size: 1.5rem; }
.dp-body h2 { font-size: 1.25rem; }
.dp-body h3 { font-size: 1.08rem; }
.dp-body p { margin: 0 0 .85em; }
.dp-body ul, .dp-body ol { margin: 0 0 .9em; padding-left: 1.5em; }
.dp-body li { margin: 0 0 .25em; }
.dp-body img { max-width: 100%; border-radius: 10px; border: 1px solid var(--border); cursor: zoom-in; margin: 6px 0; }
.dp-body blockquote { margin: 0 0 1em; padding: 8px 14px; border-left: 3px solid var(--accent); background: rgba(127,127,127,.07); border-radius: 0 8px 8px 0; color: var(--muted); }
.dp-body code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .86em; background: rgba(127,127,127,.14); padding: 1px 5px; border-radius: 5px; }
.dp-body pre { background: rgba(127,127,127,.12); border-radius: 10px; padding: 12px 14px; overflow: auto; margin: 0 0 1em; }
.dp-body pre code { background: none; padding: 0; }
.dp-body hr { border: none; border-top: 1px solid var(--border); margin: 1.4em 0; }
.dp-body .md-table-wrap { overflow: auto; margin: 0 0 1em; }
.dp-body table { border-collapse: collapse; min-width: 60%; }
.dp-body th, .dp-body td { border: 1px solid var(--border); padding: 6px 10px; text-align: left; font-size: .88rem; }
.dp-body th { background: rgba(127,127,127,.09); }
.dp-lightbox { position: fixed; inset: 0; background: rgba(0,0,0,.82); display: none; align-items: center; justify-content: center; z-index: 100; padding: 24px; }
.dp-lightbox.open { display: flex; }
.dp-lightbox img { max-width: 95vw; max-height: 92dvh; border-radius: 10px; }
@media (max-width: 900px) {
.dp-layout { grid-template-columns: 1fr; }
.dp-side { position: static; max-height: none; }
.dp-article { padding: 20px 16px; }
}
</style>
</head>
<body>
<header class="dp-head">
<div class="dp-wrap">
<div class="dp-brand">Документация</div>
<span class="dp-head-sub" id="dpHeadSub"></span>
</div>
</header>
<main class="dp-wrap dp-layout">
<aside class="dp-side"><div id="dpTree" class="dp-tree"></div></aside>
<article class="dp-article" id="dpArticle"></article>
</main>
<div class="dp-lightbox" id="dpLightbox"><img id="dpLightboxImg" alt=""></div>
<script src="js/md.js"></script>
<script src="js/docs-public.js"></script>
</body>
</html>
+285
View File
@@ -0,0 +1,285 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Документация — Админ-панель</title>
<link rel="stylesheet" href="admin.css">
<style>
.docs-wrap { display: grid; grid-template-columns: 306px minmax(0, 1fr); gap: 20px; align-items: start; }
.docs-side {
position: sticky;
top: 16px;
background: var(--card);
border: 1px solid var(--border);
border-radius: 14px;
padding: 10px;
max-height: calc(100dvh - 120px);
overflow: auto;
display: flex;
flex-direction: column;
gap: 8px;
}
.docs-search { width: 100%; }
.docs-side-foot { display: flex; gap: 6px; flex-wrap: wrap; border-top: 1px solid var(--border); padding-top: 8px; margin-top: auto; }
.docs-side-foot .btn-primary { display: inline-flex; align-items: center; gap: 6px; padding: 8px 12px; font-size: .8rem; }
.docs-side-foot .btn-primary svg { width: 14px; height: 14px; }
.docs-tree { display: flex; flex-direction: column; gap: 1px; }
.docs-node { display: flex; flex-direction: column; }
.docs-section-row {
display: flex;
align-items: center;
gap: 5px;
padding: 6px 8px;
border-radius: 8px;
cursor: pointer;
font-size: .86rem;
font-weight: 600;
min-width: 0;
user-select: none;
}
.docs-section-row:hover { background: rgba(127,127,127,.1); }
.docs-section-row svg { width: 15px; height: 15px; flex: none; }
.docs-chev { border: none; background: none; color: var(--muted); padding: 0; display: inline-flex; cursor: pointer; }
.docs-chev svg { width: 14px; height: 14px; transition: transform .15s; }
.docs-chev.closed svg { transform: rotate(-90deg); }
.docs-section-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
.docs-row-acts { margin-left: auto; display: none; align-items: center; gap: 2px; }
.docs-section-row:hover .docs-row-acts, .docs-article-row:hover .docs-row-acts { display: inline-flex; }
.docs-row-acts button {
border: none;
background: none;
color: var(--muted);
padding: 2px;
border-radius: 5px;
cursor: pointer;
display: inline-flex;
}
.docs-row-acts button:hover { color: var(--text); background: rgba(127,127,127,.18); }
.docs-row-acts svg { width: 13px; height: 13px; }
.docs-article-row { display: flex; align-items: center; gap: 4px; border-radius: 8px; }
.docs-article-row:hover { background: rgba(127,127,127,.08); }
.docs-article-row a {
flex: 1;
min-width: 0;
padding: 6px 8px;
color: var(--text);
text-decoration: none;
font-size: .84rem;
border-radius: 8px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.docs-article-row a.active { background: rgba(37,99,235,.14); color: var(--accent); font-weight: 600; }
.docs-article-row .docs-dot { width: 6px; height: 6px; border-radius: 50%; background: #f59e0b; flex: none; margin-left: 6px; }
.docs-empty { color: var(--muted); font-size: .85rem; padding: 14px 8px; text-align: center; }
.docs-search-results { display: flex; flex-direction: column; gap: 2px; }
.docs-search-item { padding: 8px; border-radius: 8px; cursor: pointer; border: 1px solid transparent; }
.docs-search-item:hover { border-color: var(--border); background: rgba(127,127,127,.06); }
.docs-search-item b { display: block; font-size: .84rem; margin-bottom: 2px; }
.docs-search-item span { display: block; font-size: .75rem; color: var(--muted); line-height: 1.4; }
.docs-search-item em { display: block; font-style: normal; font-size: .7rem; color: var(--accent); margin-top: 3px; }
.docs-article { background: var(--card); border: 1px solid var(--border); border-radius: 14px; padding: 26px 30px; min-height: 320px; }
.docs-crumbs { font-size: .74rem; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin-bottom: 8px; }
.docs-article h1 { font-size: 1.65rem; line-height: 1.25; margin: 0 0 10px; word-break: break-word; }
.docs-meta { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; font-size: .78rem; color: var(--muted); margin-bottom: 14px; }
.docs-badge { display: inline-flex; align-items: center; padding: 1px 9px; border-radius: 999px; font-size: .7rem; font-weight: 600; background: rgba(245,158,11,.15); color: #d97706; }
.docs-badge.public { background: rgba(34,197,94,.14); color: #16a34a; }
.docs-article-actions { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 18px; padding-bottom: 16px; border-bottom: 1px solid var(--border); }
.docs-article-actions:empty { display: none; }
.docs-body { font-size: .95rem; line-height: 1.68; overflow-wrap: anywhere; }
.docs-body h1, .docs-body h2, .docs-body h3, .docs-body h4 { margin: 1.4em 0 .5em; line-height: 1.3; }
.docs-body h1 { font-size: 1.5rem; }
.docs-body h2 { font-size: 1.25rem; }
.docs-body h3 { font-size: 1.08rem; }
.docs-body h4 { font-size: 1rem; }
.docs-body p { margin: 0 0 .85em; }
.docs-body ul, .docs-body ol { margin: 0 0 .9em; padding-left: 1.5em; }
.docs-body li { margin: 0 0 .25em; }
.docs-body img { max-width: 100%; border-radius: 10px; border: 1px solid var(--border); cursor: zoom-in; margin: 6px 0; }
.docs-body a { color: var(--accent); }
.docs-body blockquote { margin: 0 0 1em; padding: 8px 14px; border-left: 3px solid var(--accent); background: rgba(127,127,127,.07); border-radius: 0 8px 8px 0; color: var(--muted); }
.docs-body code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: .86em; background: rgba(127,127,127,.14); padding: 1px 5px; border-radius: 5px; }
.docs-body pre { background: rgba(127,127,127,.12); border-radius: 10px; padding: 12px 14px; overflow: auto; margin: 0 0 1em; }
.docs-body pre code { background: none; padding: 0; }
.docs-body hr { border: none; border-top: 1px solid var(--border); margin: 1.4em 0; }
.docs-body .md-table-wrap { overflow: auto; margin: 0 0 1em; }
.docs-body table { border-collapse: collapse; min-width: 60%; }
.docs-body th, .docs-body td { border: 1px solid var(--border); padding: 6px 10px; text-align: left; font-size: .88rem; }
.docs-body th { background: rgba(127,127,127,.09); }
.docs-editor { background: var(--card); border: 1px solid var(--border); border-radius: 14px; padding: 18px 20px; display: flex; flex-direction: column; gap: 12px; }
.docs-editor[hidden] { display: none; }
.docs-editor-head { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.docs-title-input {
flex: 1;
min-width: 220px;
background: var(--bg);
border: 1px solid var(--border);
color: var(--text);
border-radius: 9px;
padding: 10px 12px;
font-size: 1.1rem;
font-weight: 600;
outline: none;
font-family: inherit;
}
.docs-title-input:focus { border-color: var(--accent); }
.docs-editor-actions { display: flex; gap: 8px; }
.docs-editor-meta { display: flex; gap: 14px; align-items: center; flex-wrap: wrap; font-size: .82rem; color: var(--muted); }
.docs-editor-meta select { background: var(--bg); border: 1px solid var(--border); color: var(--text); border-radius: 8px; padding: 7px 10px; font-size: .82rem; font-family: inherit; max-width: 260px; }
.docs-editor-meta label { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
.docs-editor-meta label[hidden] { display: none; }
.docs-toolbar { display: flex; gap: 4px; flex-wrap: wrap; padding: 6px; background: var(--bg); border: 1px solid var(--border); border-radius: 10px 10px 0 0; border-bottom: none; }
.docs-toolbar button {
min-width: 30px;
height: 28px;
padding: 0 7px;
border: 1px solid transparent;
background: none;
color: var(--text);
border-radius: 6px;
cursor: pointer;
font-size: .8rem;
font-family: inherit;
display: inline-flex;
align-items: center;
justify-content: center;
}
.docs-toolbar button:hover { background: rgba(127,127,127,.16); border-color: var(--border); }
.docs-toolbar .sep { width: 1px; background: var(--border); margin: 3px 2px; }
.docs-edit-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.docs-edit-area { display: flex; flex-direction: column; min-width: 0; }
#docsEditBody {
flex: 1;
min-height: 540px;
background: var(--bg);
border: 1px solid var(--border);
border-radius: 0 0 10px 10px;
color: var(--text);
padding: 14px;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: .86rem;
line-height: 1.6;
resize: vertical;
outline: none;
}
#docsEditBody:focus { border-color: var(--accent); }
.docs-preview { background: var(--bg); border: 1px solid var(--border); border-radius: 10px; padding: 14px 16px; overflow: auto; max-height: 640px; }
.docs-preview .docs-body { font-size: .9rem; }
.docs-preview-empty { color: var(--muted); font-size: .82rem; }
.docs-hint { font-size: .74rem; color: var(--muted); }
.docs-drop { outline: 2px dashed var(--accent); outline-offset: -4px; }
.docs-file-input { display: none; }
.docs-modal-parent { width: 100%; }
.docs-check { display: flex; align-items: center; gap: 8px; font-size: .88rem; color: var(--text); cursor: pointer; }
@media (max-width: 1100px) { .docs-edit-grid { grid-template-columns: 1fr; } }
@media (max-width: 960px) {
.docs-wrap { grid-template-columns: 1fr; }
.docs-side { position: static; max-height: none; }
.docs-article { padding: 20px 16px; }
}
</style>
</head>
<body data-page="docs">
<div class="layout">
<div class="sidebar" id="sidebar"></div>
<div class="main">
<div class="page-head">
<h2>Документация</h2>
<p class="page-sub">Справочник по работе с системой</p>
<button type="button" class="btn-primary" id="docsNewArticleBtn"><i data-lucide="file-plus"></i> Новая статья</button>
</div>
<div class="docs-wrap">
<aside class="docs-side">
<input type="text" id="docsSearch" class="settings-input docs-search" placeholder="Поиск по документации..." autocomplete="off">
<div id="docsTree" class="docs-tree"></div>
<div class="docs-side-foot" id="docsSideFoot">
<button type="button" class="btn-primary ghost" id="docsNewSectionBtn"><i data-lucide="folder-plus"></i> Раздел</button>
</div>
</aside>
<section class="docs-content" id="docsContent"></section>
<section class="docs-editor" id="docsEditor" hidden>
<div class="docs-editor-head">
<input type="text" id="docsEditTitle" class="docs-title-input" maxlength="200" placeholder="Заголовок статьи">
<div class="docs-editor-actions">
<button type="button" class="btn-primary ghost" id="docsCancelBtn">Отмена</button>
<button type="button" class="btn-primary" id="docsSaveBtn">Сохранить</button>
</div>
</div>
<div class="docs-editor-meta">
<select id="docsEditSection"></select>
<label><input type="checkbox" id="docsEditPublished" checked> Опубликована</label>
<label id="docsEditPublicWrap"><input type="checkbox" id="docsEditPublic"> Публичная ссылка</label>
<span class="docs-hint" id="docsEditHint"></span>
</div>
<div class="docs-toolbar" id="docsToolbar">
<button type="button" data-md="h2" title="Заголовок">H2</button>
<button type="button" data-md="h3" title="Подзаголовок">H3</button>
<span class="sep"></span>
<button type="button" data-md="bold" title="Жирный"><b>B</b></button>
<button type="button" data-md="italic" title="Курсив"><i>I</i></button>
<button type="button" data-md="strike" title="Зачёркнутый"><s>S</s></button>
<button type="button" data-md="code" title="Код">&lt;/&gt;</button>
<span class="sep"></span>
<button type="button" data-md="ul" title="Маркированный список">• Список</button>
<button type="button" data-md="ol" title="Нумерованный список">1. Список</button>
<button type="button" data-md="quote" title="Цитата">❝</button>
<button type="button" data-md="table" title="Таблица">Таблица</button>
<button type="button" data-md="hr" title="Разделитель">—</button>
<span class="sep"></span>
<button type="button" data-md="link" title="Ссылка">Ссылка</button>
<button type="button" data-md="image" title="Картинка">Картинка</button>
</div>
<div class="docs-edit-grid">
<div class="docs-edit-area">
<textarea id="docsEditBody" spellcheck="true" placeholder="Текст статьи в Markdown. Картинку можно вставить из буфера обмена (Ctrl+V) или перетащить сюда."></textarea>
</div>
<div class="docs-preview"><div class="docs-body" id="docsPreview"></div></div>
</div>
<input type="file" id="docsImageFile" class="docs-file-input" accept="image/*">
</section>
</div>
</div>
</div>
<div class="modal-overlay" id="docsSectionModal">
<div class="edit-modal" style="max-width:520px">
<h3 id="docsSectionModalTitle">Новый раздел</h3>
<div class="settings-field">
<label>Название <span style="color:#ef4444">*</span></label>
<input id="docsSectionTitle" class="settings-input" maxlength="200" placeholder="Например, Журнал">
</div>
<div class="settings-field">
<label>Родительский раздел</label>
<select id="docsSectionParent" class="settings-input docs-modal-parent"></select>
</div>
<label class="docs-check"><input type="checkbox" id="docsSectionTutor"> Тьюторы могут писать статьи в этом разделе</label>
<label class="docs-check"><input type="checkbox" id="docsSectionPublic"> Показывать раздел в публичной версии</label>
<div class="card-foot">
<button type="button" class="btn-primary ghost" id="docsSectionDeleteBtn" style="display:none;color:#ef4444;border-color:rgba(239,68,68,.35)">Удалить</button>
<button type="button" class="btn-primary ghost" id="docsSectionCancel">Отмена</button>
<button type="button" class="btn-primary" id="docsSectionSave">Сохранить</button>
</div>
</div>
</div>
<div class="modal-overlay" id="imgModal">
<img id="imgModalSrc" alt="">
</div>
<div class="toast" id="toast"></div>
<script src="vendor/lucide.min.js"></script>
<script src="js/datetime.js"></script>
<script src="admin.js"></script>
<script src="js/md.js"></script>
<script src="js/docs.js"></script>
</body>
</html>
+152
View File
@@ -0,0 +1,152 @@
(function () {
const treeEl = document.getElementById('dpTree');
const articleEl = document.getElementById('dpArticle');
const headSub = document.getElementById('dpHeadSub');
const lightbox = document.getElementById('dpLightbox');
const lightboxImg = document.getElementById('dpLightboxImg');
const COLLAPSE_KEY = 'whatido.docsPublic.collapsed';
const ICON_CHEVRON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>';
const ICON_FOLDER = '<svg class="dp-folder" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"/></svg>';
let tree = [];
let currentSlug = '';
let collapsed = new Set();
try {
const saved = JSON.parse(localStorage.getItem(COLLAPSE_KEY) || '[]');
if (Array.isArray(saved)) collapsed = new Set(saved.map(Number));
} catch (e) {}
function esc(value) {
return String(value == null ? '' : value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function saveCollapsed() {
localStorage.setItem(COLLAPSE_KEY, JSON.stringify([...collapsed]));
}
async function getJson(url) {
const res = await fetch(url);
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Ошибка загрузки');
return data;
}
function articleRow(article, depth) {
return `<div class="dp-article-row"><a href="?slug=${encodeURIComponent(article.slug)}" data-slug="${esc(article.slug)}"
style="padding-left:${26 + depth * 14}px" class="${currentSlug === article.slug ? 'active' : ''}">${esc(article.title)}</a></div>`;
}
function sectionNode(node, depth) {
const closed = collapsed.has(Number(node.id));
const hasItems = (node.children && node.children.length) || (node.articles && node.articles.length);
const chev = hasItems
? `<button type="button" class="dp-chev${closed ? ' closed' : ''}" data-toggle="${node.id}">${ICON_CHEVRON}</button>`
: '<span style="width:14px;flex:none"></span>';
const children = closed ? '' : [
...(node.children || []).map(child => sectionNode(child, depth + 1)),
...(node.articles || []).map(article => articleRow(article, depth + 1)),
].join('');
return `<div>
<div class="dp-section-row" data-section="${node.id}" style="padding-left:${8 + depth * 14}px">
${chev}${ICON_FOLDER}<span class="dp-section-title">${esc(node.title)}</span>
</div>
<div${closed ? ' hidden' : ''}>${children}</div>
</div>`;
}
function renderTree() {
if (!tree.length) {
treeEl.innerHTML = '<div class="dp-empty">Документация пока пуста</div>';
return;
}
treeEl.innerHTML = tree.map(node => sectionNode(node, 0)).join('');
}
async function open(slug, updateUrl) {
const data = await getJson('/api/docs/public/articles/' + encodeURIComponent(slug));
const article = data.item;
currentSlug = article.slug;
articleEl.innerHTML = `<div class="dp-crumbs">${esc(article.section_title || '')}</div>
<h1>${esc(article.title)}</h1>
<div class="dp-body">${WhatIDoMD.render(article.body)}</div>`;
document.title = article.title + ' — Документация';
if (headSub) headSub.textContent = article.section_title || '';
if (updateUrl !== false) history.replaceState(null, '', '?slug=' + encodeURIComponent(article.slug));
renderTree();
}
function bind() {
treeEl.addEventListener('click', e => {
const toggle = e.target.closest('[data-toggle]');
if (toggle) {
e.preventDefault();
const id = Number(toggle.dataset.toggle);
if (collapsed.has(id)) collapsed.delete(id); else collapsed.add(id);
saveCollapsed();
renderTree();
return;
}
const link = e.target.closest('[data-slug]');
if (link) {
e.preventDefault();
open(link.dataset.slug).catch(err => { articleEl.textContent = err.message; });
return;
}
const row = e.target.closest('.dp-section-row');
if (row) {
const id = Number(row.dataset.section);
if (collapsed.has(id)) collapsed.delete(id); else collapsed.add(id);
saveCollapsed();
renderTree();
}
});
articleEl.addEventListener('click', e => {
const img = e.target.closest('[data-img]');
if (!img) return;
e.preventDefault();
lightboxImg.src = img.dataset.img;
lightbox.classList.add('open');
});
lightbox.addEventListener('click', () => {
lightbox.classList.remove('open');
lightboxImg.removeAttribute('src');
});
document.addEventListener('keydown', e => {
if (e.key === 'Escape' && lightbox.classList.contains('open')) {
lightbox.classList.remove('open');
lightboxImg.removeAttribute('src');
}
});
}
function firstSlug(nodes) {
for (const node of nodes) {
if (node.articles && node.articles.length) return node.articles[0].slug;
const nested = firstSlug(node.children || []);
if (nested) return nested;
}
return '';
}
async function init() {
bind();
try {
const data = await getJson('/api/docs/public/tree');
tree = data.sections || [];
renderTree();
const params = new URLSearchParams(location.search);
const slug = params.get('slug') || firstSlug(tree);
if (slug) await open(slug, !params.get('slug'));
else articleEl.innerHTML = '<div class="dp-empty" style="padding:40px 0">Статьи не опубликованы</div>';
} catch (e) {
articleEl.textContent = e.message;
treeEl.innerHTML = '<div class="dp-empty">Не удалось загрузить документацию</div>';
}
}
init();
})();
+691
View File
@@ -0,0 +1,691 @@
(function () {
const el = id => document.getElementById(id);
const treeEl = el('docsTree');
const contentEl = el('docsContent');
const editorEl = el('docsEditor');
const titleEl = el('docsEditTitle');
const sectionEl = el('docsEditSection');
const publishedEl = el('docsEditPublished');
const publicEl = el('docsEditPublic');
const publicWrap = el('docsEditPublicWrap');
const bodyEl = el('docsEditBody');
const previewEl = el('docsPreview');
const hintEl = el('docsEditHint');
const searchEl = el('docsSearch');
const imageFileEl = el('docsImageFile');
const sectionModal = el('docsSectionModal');
const sectionTitleEl = el('docsSectionTitle');
const sectionParentEl = el('docsSectionParent');
const sectionTutorEl = el('docsSectionTutor');
const sectionPublicEl = el('docsSectionPublic');
const sectionDeleteBtn = el('docsSectionDeleteBtn');
const COLLAPSE_KEY = 'whatido.docs.collapsed';
let tree = [];
let current = null;
let editState = null;
let sectionEditId = null;
let collapsed = new Set();
let searchTimer = null;
let previewTimer = null;
try {
const saved = JSON.parse(localStorage.getItem(COLLAPSE_KEY) || '[]');
if (Array.isArray(saved)) collapsed = new Set(saved.map(Number));
} catch (e) {}
async function req(path, options) {
const opts = options || {};
const headers = opts.body instanceof FormData ? hdr() : hdrJson();
const res = await fetch(API + path, Object.assign({}, opts, { headers }));
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Ошибка запроса');
return data;
}
function saveCollapsed() {
localStorage.setItem(COLLAPSE_KEY, JSON.stringify([...collapsed]));
}
function sectionList() {
const out = [];
const walk = (nodes, depth) => {
for (const node of nodes) {
out.push(Object.assign({}, node, { depth }));
walk(node.children || [], depth + 1);
}
};
walk(tree, 0);
return out;
}
function findSection(id) {
return sectionList().find(s => Number(s.id) === Number(id)) || null;
}
function findSectionNode(id) {
let found = null;
const walk = nodes => {
for (const node of nodes) {
if (Number(node.id) === Number(id)) { found = node; return; }
walk(node.children || []);
if (found) return;
}
};
walk(tree);
return found;
}
function canCreateAnywhere() {
return isAdmin() || sectionList().some(s => s.can_write);
}
function updateNewArticleButton() {
const btn = el('docsNewArticleBtn');
if (btn) btn.hidden = !canCreateAnywhere();
}
async function loadTree() {
const data = await req('/api/docs/tree');
tree = data.sections || [];
updateNewArticleButton();
if (searchEl.value.trim().length >= 2) {
renderTree();
runSearch();
} else {
renderTree();
}
}
function renderIconsSafe() {
if (typeof renderIcons === 'function') renderIcons();
}
function sectionActs(node) {
const acts = [];
if (node.can_write) acts.push(`<button type="button" data-act="add-article" data-id="${node.id}" title="Новая статья"><i data-lucide="file-plus"></i></button>`);
if (isAdmin()) {
acts.push(`<button type="button" data-act="add-sub" data-id="${node.id}" title="Подраздел"><i data-lucide="folder-plus"></i></button>`);
acts.push(`<button type="button" data-act="edit-section" data-id="${node.id}" title="Изменить раздел"><i data-lucide="pencil"></i></button>`);
acts.push(`<button type="button" data-act="section-up" data-id="${node.id}" title="Выше"><i data-lucide="arrow-up"></i></button>`);
acts.push(`<button type="button" data-act="section-down" data-id="${node.id}" title="Ниже"><i data-lucide="arrow-down"></i></button>`);
}
return acts.join('');
}
function articleRow(article, depth) {
const active = current && Number(current.id) === Number(article.id);
const acts = isAdmin()
? `<button type="button" data-act="article-up" data-id="${article.id}" data-section="${article.section_id}" title="Выше"><i data-lucide="arrow-up"></i></button>
<button type="button" data-act="article-down" data-id="${article.id}" data-section="${article.section_id}" title="Ниже"><i data-lucide="arrow-down"></i></button>`
: '';
return `<div class="docs-article-row">
<a href="#a=${encodeURIComponent(article.slug)}" data-slug="${esc(article.slug)}" class="${active ? 'active' : ''}" style="padding-left:${26 + depth * 14}px" title="${esc(article.title)}">${esc(article.title)}${article.is_published ? '' : '<span class="docs-dot" title="Черновик"></span>'}</a>
<span class="docs-row-acts">${acts}</span>
</div>`;
}
function sectionNode(node, depth) {
const closed = collapsed.has(Number(node.id));
const hasItems = (node.children && node.children.length) || (node.articles && node.articles.length);
const chev = hasItems
? `<button type="button" class="docs-chev${closed ? ' closed' : ''}" data-toggle="${node.id}" aria-label="Свернуть раздел"><i data-lucide="chevron-down"></i></button>`
: '<span style="width:14px;flex:none"></span>';
const children = closed ? '' : [
...(node.children || []).map(child => sectionNode(child, depth + 1)),
...(node.articles || []).map(article => articleRow(article, depth + 1)),
].join('');
return `<div class="docs-node">
<div class="docs-section-row" data-section="${node.id}" style="padding-left:${8 + depth * 14}px">
${chev}
<i data-lucide="${closed ? 'folder' : 'folder-open'}"></i>
<span class="docs-section-title">${esc(node.title)}</span>
<span class="docs-row-acts">${sectionActs(node)}</span>
</div>
<div class="docs-children"${closed ? ' hidden' : ''}>${children}</div>
</div>`;
}
function renderTree() {
if (!tree.length) {
treeEl.innerHTML = '<div class="docs-empty">Разделов пока нет</div>';
renderIconsSafe();
return;
}
treeEl.innerHTML = tree.map(node => sectionNode(node, 0)).join('');
renderIconsSafe();
}
function renderEmpty() {
contentEl.hidden = false;
editorEl.hidden = true;
contentEl.innerHTML = `<div class="docs-article"><div class="docs-empty" style="padding:60px 16px">Выберите статью слева${canCreateAnywhere() ? ' или создайте новую' : ''}</div></div>`;
}
function articleHtml(article) {
const actions = [];
if (article.can_edit) {
actions.push('<button type="button" class="btn-primary ghost" data-doc-act="edit">Редактировать</button>');
actions.push('<button type="button" class="btn-primary ghost" data-doc-act="delete" style="color:#ef4444;border-color:rgba(239,68,68,.35)">Удалить</button>');
}
if (article.is_public) {
actions.push('<button type="button" class="btn-primary ghost" data-doc-act="copy">Скопировать публичную ссылку</button>');
}
const meta = [];
if (article.author_name) meta.push(`<span>${esc(article.author_name)}</span>`);
if (article.updated_at) meta.push(`<span>Обновлено: ${fmtDateTime(article.updated_at)}</span>`);
if (!article.is_published) meta.push('<span class="docs-badge">Черновик</span>');
if (article.is_public) meta.push('<span class="docs-badge public">Публичная</span>');
return `<article class="docs-article">
<div class="docs-crumbs">${esc(article.section_title || '')}</div>
<h1>${esc(article.title)}</h1>
<div class="docs-meta">${meta.join('')}</div>
<div class="docs-article-actions">${actions.join('')}</div>
<div class="docs-body">${WhatIDoMD.render(article.body)}</div>
</article>`;
}
function renderArticle() {
if (!current) return renderEmpty();
contentEl.hidden = false;
editorEl.hidden = true;
contentEl.innerHTML = articleHtml(current);
markActive();
}
function markActive() {
treeEl.querySelectorAll('.docs-article-row a').forEach(a => {
a.classList.toggle('active', !!current && a.dataset.slug === current.slug);
});
}
async function openArticle(slug, updateHash) {
if (editState && editState.dirty && !confirm('Несохранённые изменения будут потеряны. Продолжить?')) return;
const data = await req('/api/docs/articles/' + encodeURIComponent(slug));
current = data.item;
editState = null;
if (updateHash !== false) history.replaceState(null, '', '#a=' + encodeURIComponent(current.slug));
renderArticle();
markActive();
}
function fillSectionSelect(selectedId) {
const list = sectionList().filter(s => isAdmin() || s.can_write);
sectionEl.innerHTML = list.map(s => {
const prefix = s.depth ? '\u00A0\u00A0'.repeat(s.depth) + '— ' : '';
return `<option value="${s.id}">${esc(prefix + s.title)}</option>`;
}).join('');
if (selectedId && list.some(s => Number(s.id) === Number(selectedId))) sectionEl.value = String(selectedId);
return list.length > 0;
}
function markDirty() {
if (!editState) return;
editState.dirty = true;
hintEl.textContent = 'Есть несохранённые изменения';
}
function updatePreview() {
previewEl.innerHTML = bodyEl.value.trim()
? WhatIDoMD.render(bodyEl.value)
: '<div class="docs-preview-empty">Предпросмотр появится здесь</div>';
}
function schedulePreview() {
clearTimeout(previewTimer);
previewTimer = setTimeout(updatePreview, 150);
}
function startEdit(article, presetSectionId) {
if (article && !article.can_edit) {
showToast('Нет прав на редактирование этой статьи', true);
return;
}
const list = sectionList().filter(s => isAdmin() || s.can_write);
if (!list.length) {
showToast('Нет разделов, где вам разрешено писать', true);
return;
}
editState = { id: article ? article.id : null, dirty: false };
titleEl.value = article ? article.title : '';
bodyEl.value = article ? article.body : '';
publishedEl.checked = article ? article.is_published : true;
publicEl.checked = article ? article.is_public : false;
publicWrap.hidden = !isAdmin();
const preferred = article ? article.section_id : (presetSectionId || (current && current.section_id));
fillSectionSelect(preferred);
hintEl.textContent = '';
contentEl.hidden = true;
editorEl.hidden = false;
updatePreview();
renderIconsSafe();
titleEl.focus();
titleEl.select();
}
function closeEditor() {
editorEl.hidden = true;
contentEl.hidden = false;
editState = null;
hintEl.textContent = '';
}
function cancelEdit() {
if (editState && editState.dirty && !confirm('Отменить несохранённые изменения?')) return;
closeEditor();
if (current) renderArticle(); else renderEmpty();
}
async function saveArticle() {
if (!editState) return;
const title = titleEl.value.trim();
if (!title) { showToast('Введите заголовок статьи', true); titleEl.focus(); return; }
const sectionId = parseInt(sectionEl.value, 10);
if (!Number.isInteger(sectionId) || sectionId < 1) { showToast('Выберите раздел', true); return; }
const payload = {
section_id: sectionId,
title,
body: bodyEl.value,
is_published: publishedEl.checked,
is_public: isAdmin() ? publicEl.checked : false,
};
const saveBtn = el('docsSaveBtn');
saveBtn.disabled = true;
try {
const path = editState.id ? '/api/docs/articles/' + editState.id : '/api/docs/articles';
const method = editState.id ? 'PUT' : 'POST';
const data = await req(path, { method, body: JSON.stringify(payload) });
editState.dirty = false;
closeEditor();
await loadTree();
await openArticle(data.item.slug);
showToast('Статья сохранена');
} catch (e) {
showToast(e.message, true);
} finally {
saveBtn.disabled = false;
}
}
async function deleteArticle() {
if (!current || !current.can_edit) return;
if (!confirm(`Удалить статью «${current.title}»? Действие необратимо.`)) return;
try {
await req('/api/docs/articles/' + current.id, { method: 'DELETE' });
const slug = current.slug;
current = null;
history.replaceState(null, '', location.pathname);
await loadTree();
renderEmpty();
showToast('Статья удалена');
} catch (e) {
showToast(e.message, true);
}
}
function copyPublicLink() {
if (!current) return;
const url = `${location.origin}/docs-public.html?slug=${encodeURIComponent(current.slug)}`;
const done = () => showToast('Ссылка скопирована');
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(url).then(done).catch(() => prompt('Публичная ссылка', url));
} else {
prompt('Публичная ссылка', url);
}
}
function applyWrap(before, after, fallback) {
const start = bodyEl.selectionStart;
const end = bodyEl.selectionEnd;
const selected = bodyEl.value.slice(start, end);
const inner = selected || fallback || '';
bodyEl.setRangeText(before + inner + after, start, end, 'end');
bodyEl.focus();
if (!selected && inner) {
bodyEl.setSelectionRange(start + before.length, start + before.length + inner.length);
}
markDirty();
updatePreview();
}
function applyPrefix(prefix) {
const start = bodyEl.selectionStart;
const lineStart = bodyEl.value.lastIndexOf('\n', start - 1) + 1;
bodyEl.setRangeText(prefix, lineStart, lineStart, 'end');
bodyEl.focus();
markDirty();
updatePreview();
}
function insertBlock(text) {
const start = bodyEl.selectionStart;
const before = bodyEl.value.slice(0, start);
const prefix = before && !before.endsWith('\n') ? '\n' : '';
bodyEl.setRangeText(prefix + text + '\n', start, bodyEl.selectionEnd, 'end');
bodyEl.focus();
markDirty();
updatePreview();
}
function applyToolbar(kind) {
if (kind === 'bold') return applyWrap('**', '**', 'жирный текст');
if (kind === 'italic') return applyWrap('*', '*', 'курсив');
if (kind === 'strike') return applyWrap('~~', '~~', 'зачёркнутый');
if (kind === 'code') return applyWrap('`', '`', 'код');
if (kind === 'h2') return applyPrefix('## ');
if (kind === 'h3') return applyPrefix('### ');
if (kind === 'ul') return applyPrefix('- ');
if (kind === 'ol') return applyPrefix('1. ');
if (kind === 'quote') return applyPrefix('> ');
if (kind === 'hr') return insertBlock('---');
if (kind === 'link') return applyWrap('[', '](https://)', 'текст ссылки');
if (kind === 'table') return insertBlock('| Колонка | Колонка |\n| --- | --- |\n| | |');
if (kind === 'image') { imageFileEl.click(); return; }
}
async function uploadImage(file) {
if (!file || !file.type || !file.type.startsWith('image/')) {
showToast('Можно вставлять только изображения', true);
return;
}
showToast('Загрузка картинки...');
try {
const form = new FormData();
form.append('image', file);
const data = await req('/api/docs/images', { method: 'POST', body: form });
const alt = (file.name || 'картинка').replace(/\.[^.]+$/, '');
insertBlock(`![${alt}](${data.item.path})`);
showToast('Картинка добавлена');
} catch (e) {
showToast(e.message, true);
}
}
function fillParentSelect(excludeId, selectedId) {
const list = sectionList().filter(s => Number(s.id) !== Number(excludeId));
sectionParentEl.innerHTML = '<option value="">— Корень —</option>' + list.map(s => {
const prefix = s.depth ? '\u00A0\u00A0'.repeat(s.depth) + '— ' : '';
return `<option value="${s.id}">${esc(prefix + s.title)}</option>`;
}).join('');
sectionParentEl.value = selectedId ? String(selectedId) : '';
}
function openSectionModal(id, parentId) {
const section = id ? findSection(id) : null;
sectionEditId = section ? Number(section.id) : null;
el('docsSectionModalTitle').textContent = section ? 'Изменить раздел' : 'Новый раздел';
sectionTitleEl.value = section ? section.title : '';
sectionTutorEl.checked = section ? !!section.tutor_edit : false;
sectionPublicEl.checked = section ? !!section.is_public : false;
fillParentSelect(section ? section.id : null, section ? section.parent_id : (parentId || null));
sectionDeleteBtn.style.display = section ? '' : 'none';
sectionModal.classList.add('open');
sectionTitleEl.focus();
sectionTitleEl.select();
}
function closeSectionModal() {
sectionModal.classList.remove('open');
sectionEditId = null;
}
async function saveSection() {
const title = sectionTitleEl.value.trim();
if (!title) { showToast('Введите название раздела', true); sectionTitleEl.focus(); return; }
const payload = {
title,
parent_id: sectionParentEl.value ? parseInt(sectionParentEl.value, 10) : null,
tutor_edit: sectionTutorEl.checked,
is_public: sectionPublicEl.checked,
};
try {
const path = sectionEditId ? '/api/docs/sections/' + sectionEditId : '/api/docs/sections';
await req(path, { method: sectionEditId ? 'PUT' : 'POST', body: JSON.stringify(payload) });
closeSectionModal();
await loadTree();
if (current) {
try { await openArticle(current.slug); } catch (e) {}
}
showToast('Раздел сохранён');
} catch (e) {
showToast(e.message, true);
}
}
function countArticles(node) {
let total = (node.articles || []).length;
for (const child of node.children || []) total += countArticles(child);
return total;
}
async function deleteSection() {
if (!sectionEditId) return;
const node = findSectionNode(sectionEditId);
const count = node ? countArticles(node) : 0;
const warning = count ? ` Вместе с ним удалятся статьи: ${count}.` : '';
if (!confirm(`Удалить раздел «${sectionTitleEl.value.trim()}»?${warning}`)) return;
try {
const id = sectionEditId;
await req('/api/docs/sections/' + id, { method: 'DELETE' });
closeSectionModal();
await loadTree();
if (current) {
try { await openArticle(current.slug); } catch (e) { current = null; history.replaceState(null, '', location.pathname); renderEmpty(); }
}
showToast('Раздел удалён');
} catch (e) {
showToast(e.message, true);
}
}
async function moveSection(id, direction) {
const section = findSection(id);
if (!section) return;
const siblings = sectionList().filter(s => String(s.parent_id || '') === String(section.parent_id || ''));
const index = siblings.findIndex(s => Number(s.id) === Number(id));
const target = index + direction;
if (index < 0 || target < 0 || target >= siblings.length) return;
const swap = siblings[index];
siblings[index] = siblings[target];
siblings[target] = swap;
try {
await req('/api/docs/sections/reorder', {
method: 'PUT',
body: JSON.stringify({ ids: siblings.map(s => s.id) }),
});
await loadTree();
} catch (e) {
showToast(e.message, true);
}
}
async function moveArticle(id, sectionId, direction) {
const node = findSectionNode(sectionId);
if (!node) return;
const articles = (node.articles || []).slice();
const index = articles.findIndex(a => Number(a.id) === Number(id));
const target = index + direction;
if (index < 0 || target < 0 || target >= articles.length) return;
const swap = articles[index];
articles[index] = articles[target];
articles[target] = swap;
try {
await req('/api/docs/articles/reorder', {
method: 'PUT',
body: JSON.stringify({ section_id: Number(sectionId), ids: articles.map(a => a.id) }),
});
await loadTree();
} catch (e) {
showToast(e.message, true);
}
}
async function runSearch() {
const query = searchEl.value.trim();
if (query.length < 2) { renderTree(); return; }
try {
const data = await req('/api/docs/search?q=' + encodeURIComponent(query));
if (!data.items.length) {
treeEl.innerHTML = '<div class="docs-empty">Ничего не найдено</div>';
return;
}
treeEl.innerHTML = `<div class="docs-search-results">${data.items.map(item => {
const excerpt = String(item.excerpt || '').replace(/\s+/g, ' ').trim();
return `<div class="docs-search-item" data-slug="${esc(item.slug)}">
<b>${esc(item.title)}</b>
<span>${esc(excerpt)}</span>
<em>${esc(item.section_title || '')}</em>
</div>`;
}).join('')}</div>`;
} catch (e) {
showToast(e.message, true);
}
}
function bindTree() {
treeEl.addEventListener('click', e => {
const act = e.target.closest('[data-act]');
if (act) {
e.preventDefault();
e.stopPropagation();
const id = parseInt(act.dataset.id, 10);
const action = act.dataset.act;
if (action === 'add-article') return startEdit(null, id);
if (action === 'add-sub') return openSectionModal(null, id);
if (action === 'edit-section') return openSectionModal(id, null);
if (action === 'section-up') return moveSection(id, -1);
if (action === 'section-down') return moveSection(id, 1);
if (action === 'article-up') return moveArticle(id, parseInt(act.dataset.section, 10), -1);
if (action === 'article-down') return moveArticle(id, parseInt(act.dataset.section, 10), 1);
return;
}
const toggle = e.target.closest('[data-toggle]');
if (toggle) {
e.preventDefault();
e.stopPropagation();
const id = Number(toggle.dataset.toggle);
if (collapsed.has(id)) collapsed.delete(id); else collapsed.add(id);
saveCollapsed();
renderTree();
return;
}
const link = e.target.closest('[data-slug]');
if (link) {
e.preventDefault();
openArticle(link.dataset.slug).catch(err => showToast(err.message, true));
return;
}
const row = e.target.closest('.docs-section-row');
if (row) {
const id = Number(row.dataset.section);
if (collapsed.has(id)) collapsed.delete(id); else collapsed.add(id);
saveCollapsed();
renderTree();
}
});
}
function bindEditor() {
el('docsToolbar').addEventListener('click', e => {
const btn = e.target.closest('[data-md]');
if (!btn) return;
e.preventDefault();
applyToolbar(btn.dataset.md);
});
bodyEl.addEventListener('input', () => { markDirty(); schedulePreview(); });
bodyEl.addEventListener('dragover', e => {
if (!e.dataTransfer || ![...e.dataTransfer.types].includes('Files')) return;
e.preventDefault();
bodyEl.classList.add('docs-drop');
});
bodyEl.addEventListener('dragleave', () => bodyEl.classList.remove('docs-drop'));
bodyEl.addEventListener('drop', async e => {
const files = [...(e.dataTransfer && e.dataTransfer.files ? e.dataTransfer.files : [])];
if (!files.length) return;
e.preventDefault();
bodyEl.classList.remove('docs-drop');
for (const file of files) await uploadImage(file);
});
bodyEl.addEventListener('paste', async e => {
const data = e.clipboardData;
if (!data) return;
const files = [...(data.files || [])].filter(f => f.type && f.type.startsWith('image/'));
if (!files.length) return;
e.preventDefault();
for (const file of files) await uploadImage(file);
});
[titleEl, sectionEl, publishedEl, publicEl].forEach(control => {
control.addEventListener('input', markDirty);
control.addEventListener('change', markDirty);
});
imageFileEl.addEventListener('change', async () => {
const file = imageFileEl.files && imageFileEl.files[0];
imageFileEl.value = '';
if (file) await uploadImage(file);
});
el('docsSaveBtn').addEventListener('click', saveArticle);
el('docsCancelBtn').addEventListener('click', cancelEdit);
}
function bindPage() {
el('docsNewArticleBtn').addEventListener('click', () => startEdit(null, current ? current.section_id : null));
el('docsNewSectionBtn').addEventListener('click', () => openSectionModal(null, null));
contentEl.addEventListener('click', e => {
const btn = e.target.closest('[data-doc-act]');
if (!btn) return;
const action = btn.dataset.docAct;
if (action === 'edit') startEdit(current);
if (action === 'delete') deleteArticle();
if (action === 'copy') copyPublicLink();
});
searchEl.addEventListener('input', () => {
clearTimeout(searchTimer);
searchTimer = setTimeout(runSearch, 250);
});
el('docsSectionSave').addEventListener('click', saveSection);
el('docsSectionCancel').addEventListener('click', closeSectionModal);
sectionDeleteBtn.addEventListener('click', deleteSection);
sectionModal.addEventListener('click', e => { if (e.target === sectionModal) closeSectionModal(); });
document.addEventListener('keydown', e => {
if (e.key === 'Escape' && sectionModal.classList.contains('open')) closeSectionModal();
if ((e.ctrlKey || e.metaKey) && e.key === 's' && editState) {
e.preventDefault();
saveArticle();
}
});
window.addEventListener('beforeunload', e => {
if (editState && editState.dirty) {
e.preventDefault();
e.returnValue = '';
}
});
}
async function init() {
if (!(await checkAuth())) return;
buildSidebar(document.body.dataset.page);
if (!isAdmin()) el('docsNewSectionBtn').hidden = true;
bindTree();
bindEditor();
bindPage();
renderIconsSafe();
try {
await loadTree();
} catch (e) {
showToast(e.message, true);
}
const hash = location.hash.replace(/^#a=/, '');
if (hash) {
try {
await openArticle(decodeURIComponent(hash), false);
} catch (e) {
renderEmpty();
}
} else {
renderEmpty();
}
renderIconsSafe();
}
init();
})();
+192
View File
@@ -0,0 +1,192 @@
(function () {
function esc(value) {
return String(value == null ? '' : value)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
function safeUrl(value) {
const url = String(value || '').trim();
if (/^\/uploads\/[A-Za-z0-9._-]+$/.test(url)) return url;
if (/^https?:\/\/[^\s]+$/i.test(url)) return url;
return '';
}
function thumbUrl(path) {
if (typeof window.thumbSrc === 'function') return window.thumbSrc(path);
if (path.startsWith('/uploads/')) return '/uploads/thumb/' + path.slice('/uploads/'.length);
return path;
}
function inline(raw) {
const codes = [];
let text = String(raw == null ? '' : raw).replace(/`([^`]+)`/g, (m, code) => {
codes.push(code);
return `\u0000${codes.length - 1}\u0000`;
});
text = esc(text);
text = text.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (m, alt, src) => {
const url = safeUrl(src.replace(/&amp;/g, '&'));
if (!url) return alt;
return `<img src="${esc(thumbUrl(url))}" data-img="${esc(url)}" alt="${esc(alt)}" loading="lazy">`;
});
text = text.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (m, label, href) => {
const url = safeUrl(href.replace(/&amp;/g, '&'));
if (!url) return label;
const external = /^https?:\/\//i.test(url);
return `<a href="${esc(url)}"${external ? ' target="_blank" rel="noopener noreferrer"' : ''}>${label}</a>`;
});
text = text.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
text = text.replace(/__([^_]+)__/g, '<strong>$1</strong>');
text = text.replace(/~~([^~]+)~~/g, '<del>$1</del>');
text = text.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>');
text = text.replace(/\u0000(\d+)\u0000/g, (m, index) => `<code>${esc(codes[Number(index)])}</code>`);
return text;
}
function isBlockStart(line) {
return /^\s*$/.test(line)
|| /^```/.test(line)
|| /^#{1,4}\s+/.test(line)
|| /^\s*>\s?/.test(line)
|| /^\s*([-*+]|\d+\.)\s+/.test(line)
|| /^\s*([-*_])\1{2,}\s*$/.test(line);
}
function parseList(lines, start) {
const baseIndent = lines[start].match(/^(\s*)/)[1].length;
const ordered = /^\s*\d+\.\s+/.test(lines[start]);
let html = ordered ? '<ol>' : '<ul>';
let i = start;
while (i < lines.length) {
const line = lines[i];
const match = line.match(/^(\s*)([-*+]|\d+\.)\s+(.*)$/);
if (!match) break;
const indent = match[1].length;
if (indent < baseIndent) break;
if (indent > baseIndent) {
const nested = parseList(lines, i);
html = html.replace(/<\/li>$/, nested.html + '</li>');
i = nested.next;
continue;
}
if (/^\s*\d+\.\s+/.test(line) !== ordered) break;
let content = match[3];
const task = content.match(/^\[( |x|X)\]\s+(.*)$/);
if (task) {
content = `<input type="checkbox" disabled${task[1].toLowerCase() === 'x' ? ' checked' : ''}> ${inline(task[2])}`;
} else {
content = inline(content);
}
html += `<li>${content}</li>`;
i++;
while (i < lines.length) {
const next = lines[i];
if (/^\s*$/.test(next)) break;
if (/^(\s*)([-*+]|\d+\.)\s+/.test(next)) break;
if (next.match(/^\s*/)[0].length <= baseIndent) break;
html = html.replace(/<\/li>$/, ' ' + inline(next.trim()) + '</li>');
i++;
}
}
html += ordered ? '</ol>' : '</ul>';
return { html, next: i };
}
function splitRow(line) {
let row = line.trim();
if (row.startsWith('|')) row = row.slice(1);
if (row.endsWith('|')) row = row.slice(0, -1);
return row.split('|').map(cell => cell.trim());
}
function renderTable(lines, start) {
const head = splitRow(lines[start]);
let i = start + 2;
const rows = [];
while (i < lines.length && lines[i].includes('|') && lines[i].trim()) {
rows.push(splitRow(lines[i]));
i++;
}
const thead = head.map(cell => `<th>${inline(cell)}</th>`).join('');
const tbody = rows.map(row => `<tr>${row.map(cell => `<td>${inline(cell)}</td>`).join('')}</tr>`).join('');
return {
html: `<div class="md-table-wrap"><table><thead><tr>${thead}</tr></thead><tbody>${tbody}</tbody></table></div>`,
next: i,
};
}
function render(markdown) {
const lines = String(markdown == null ? '' : markdown).replace(/\r\n?/g, '\n').split('\n');
const out = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
if (/^\s*$/.test(line)) { i++; continue; }
const fence = line.match(/^```\s*([\w-]*)\s*$/);
if (fence) {
const code = [];
i++;
while (i < lines.length && !/^```\s*$/.test(lines[i])) {
code.push(lines[i]);
i++;
}
if (i < lines.length) i++;
out.push(`<pre><code>${esc(code.join('\n'))}</code></pre>`);
continue;
}
const heading = line.match(/^(#{1,4})\s+(.*)$/);
if (heading) {
const level = heading[1].length;
out.push(`<h${level}>${inline(heading[2])}</h${level}>`);
i++;
continue;
}
if (/^\s*([-*_])\1{2,}\s*$/.test(line)) {
out.push('<hr>');
i++;
continue;
}
if (/^\s*>\s?/.test(line)) {
const quote = [];
while (i < lines.length && /^\s*>\s?/.test(lines[i])) {
quote.push(lines[i].replace(/^\s*>\s?/, ''));
i++;
}
out.push(`<blockquote>${render(quote.join('\n'))}</blockquote>`);
continue;
}
if (line.includes('|') && i + 1 < lines.length && /^\s*\|?[\s:|-]+\|[\s:|-]*$/.test(lines[i + 1]) && lines[i + 1].includes('-')) {
const table = renderTable(lines, i);
out.push(table.html);
i = table.next;
continue;
}
if (/^\s*([-*+]|\d+\.)\s+/.test(line)) {
const list = parseList(lines, i);
out.push(list.html);
i = list.next;
continue;
}
const paragraph = [];
while (i < lines.length && !isBlockStart(lines[i])) {
paragraph.push(lines[i]);
i++;
}
if (!paragraph.length) { i++; continue; }
out.push(`<p>${paragraph.map(inline).join('<br>')}</p>`);
}
return out.join('\n');
}
window.WhatIDoMD = { render, inline, esc, thumbUrl, safeUrl };
})();
+244 -3
View File
@@ -49,6 +49,24 @@ const { normalizeStudentStatus, ensureStudentsTable } = require('./lib/students'
const { lessonReportWriteBlocked } = require('./lib/lesson-reports'); const { lessonReportWriteBlocked } = require('./lib/lesson-reports');
const { groupOwnedBy } = require('./lib/groups'); const { groupOwnedBy } = require('./lib/groups');
const { ensureProjectFileSizeColumn, backfillProjectFileSizes } = require('./lib/file-sizes'); const { ensureProjectFileSizeColumn, backfillProjectFileSizes } = require('./lib/file-sizes');
const {
ensureDocsTables,
docsTree,
getArticle: getDocArticle,
createSection: createDocSection,
updateSection: updateDocSection,
deleteSection: deleteDocSection,
reorderSections: reorderDocSections,
createArticle: createDocArticle,
updateArticle: updateDocArticle,
deleteArticle: deleteDocArticle,
reorderArticles: reorderDocArticles,
registerImage: registerDocImage,
searchArticles: searchDocArticles,
publicTree: publicDocTree,
publicArticle: publicDocArticle,
docsError,
} = require('./lib/docs');
const https = require('https'); const https = require('https');
const path = require('path'); const path = require('path');
@@ -1678,7 +1696,7 @@ async function removeEntryFiles(entryId) {
async function sweepOrphanedUploads() { async function sweepOrphanedUploads() {
const dir = UPLOADS_DIR; const dir = UPLOADS_DIR;
try { fs.mkdirSync(dir, { recursive: true }); } catch {} try { fs.mkdirSync(dir, { recursive: true }); } catch {}
const [{ rows: photos }, { rows: files }, { rows: gphotos }, { rows: gporiginals }, { rows: ephotos }, { rows: pendingJobs }, { rows: mphotos }, { rows: sphotos }, { rows: logos }, { rows: studentAvatars }, { rows: groupCovers }, { rows: originals }, { rows: jobBefore }, { rows: chatFiles }, { rows: bmarkPhotos }, { rows: faceRefs }] = await Promise.all([ const [{ rows: photos }, { rows: files }, { rows: gphotos }, { rows: gporiginals }, { rows: ephotos }, { rows: pendingJobs }, { rows: mphotos }, { rows: sphotos }, { rows: logos }, { rows: studentAvatars }, { rows: groupCovers }, { rows: originals }, { rows: jobBefore }, { rows: chatFiles }, { rows: bmarkPhotos }, { rows: faceRefs }, { rows: docPhotos }] = await Promise.all([
pool.query('SELECT photo_path AS p FROM entries WHERE photo_path IS NOT NULL'), pool.query('SELECT photo_path AS p FROM entries WHERE photo_path IS NOT NULL'),
pool.query('SELECT path AS p FROM project_files'), pool.query('SELECT path AS p FROM project_files'),
pool.query('SELECT photo_path AS p FROM group_photos'), pool.query('SELECT photo_path AS p FROM group_photos'),
@@ -1696,9 +1714,10 @@ async function sweepOrphanedUploads() {
pool.query('SELECT path AS p FROM chat_attachments'), pool.query('SELECT path AS p FROM chat_attachments'),
pool.query('SELECT photo_path AS p FROM bookmarks WHERE photo_path IS NOT NULL'), pool.query('SELECT photo_path AS p FROM bookmarks WHERE photo_path IS NOT NULL'),
pool.query('SELECT photo_path AS p FROM student_face_refs'), pool.query('SELECT photo_path AS p FROM student_face_refs'),
pool.query('SELECT path AS p FROM doc_images'),
]); ]);
const refs = new Set(); const refs = new Set();
[...photos, ...files, ...gphotos, ...gporiginals, ...ephotos, ...pendingJobs, ...mphotos, ...sphotos, ...logos, ...studentAvatars, ...groupCovers, ...originals, ...jobBefore, ...chatFiles, ...bmarkPhotos, ...faceRefs].forEach(r => { [...photos, ...files, ...gphotos, ...gporiginals, ...ephotos, ...pendingJobs, ...mphotos, ...sphotos, ...logos, ...studentAvatars, ...groupCovers, ...originals, ...jobBefore, ...chatFiles, ...bmarkPhotos, ...faceRefs, ...docPhotos].forEach(r => {
const key = storage.keyFromPath(r.p); const key = storage.keyFromPath(r.p);
if (key) refs.add(key); if (key) refs.add(key);
}); });
@@ -1735,6 +1754,7 @@ const BROKEN_IMAGE_SOURCES = [
{ key: 'modules.photo_path', table: 'modules', column: 'photo_path', idColumn: 'id', kind: 'column', label: 'Фото темы' }, { key: 'modules.photo_path', table: 'modules', column: 'photo_path', idColumn: 'id', kind: 'column', label: 'Фото темы' },
{ key: 'bookmarks.photo_path', table: 'bookmarks', column: 'photo_path', idColumn: 'id', kind: 'column', label: 'Картинка закладки' }, { key: 'bookmarks.photo_path', table: 'bookmarks', column: 'photo_path', idColumn: 'id', kind: 'column', label: 'Картинка закладки' },
{ key: 'student_face_refs.photo_path', table: 'student_face_refs', column: 'photo_path', idColumn: 'id', kind: 'row', label: 'Эталон лица' }, { key: 'student_face_refs.photo_path', table: 'student_face_refs', column: 'photo_path', idColumn: 'id', kind: 'row', label: 'Эталон лица' },
{ key: 'doc_images.path', table: 'doc_images', column: 'path', idColumn: 'id', kind: 'row', label: 'Картинка документации' },
{ key: 'project_files.path', table: 'project_files', column: 'path', idColumn: 'id', kind: 'row', label: 'Файл проекта' }, { key: 'project_files.path', table: 'project_files', column: 'path', idColumn: 'id', kind: 'row', label: 'Файл проекта' },
{ key: 'chat_attachments.path', table: 'chat_attachments', column: 'path', idColumn: 'id', kind: 'row', label: 'Вложение чата' }, { key: 'chat_attachments.path', table: 'chat_attachments', column: 'path', idColumn: 'id', kind: 'row', label: 'Вложение чата' },
{ key: 'photo_jobs.before_path', table: 'photo_jobs', column: 'before_path', idColumn: 'id', kind: 'column', label: 'Фото до обработки' }, { key: 'photo_jobs.before_path', table: 'photo_jobs', column: 'before_path', idColumn: 'id', kind: 'column', label: 'Фото до обработки' },
@@ -2745,6 +2765,7 @@ async function ensureUsersAndFirstAdmin() {
await ensureApiKeysTable(); await ensureApiKeysTable();
await ensureUserNotesTable(); await ensureUserNotesTable();
await ensureBookmarksTable(); await ensureBookmarksTable();
await ensureDocsTables(pool);
await ensureFirstAdmin(); await ensureFirstAdmin();
} }
@@ -4956,6 +4977,195 @@ app.delete('/api/bookmarks/:id/photo', requireAdmin, async (req, res) => {
res.json({ ok: true }); res.json({ ok: true });
}); });
app.get('/api/docs/tree', requireAuth, async (req, res) => {
try {
res.json(await docsTree(pool, req.user));
} catch (e) {
docsError(res, e, 'Не удалось загрузить документацию', 'docs tree');
}
});
app.get('/api/docs/search', requireAuth, async (req, res) => {
try {
const q = typeof req.query.q === 'string' ? req.query.q.trim() : '';
res.json({ items: await searchDocArticles(pool, req.user, q) });
} catch (e) {
docsError(res, e, 'Не удалось выполнить поиск', 'docs search');
}
});
app.get('/api/docs/articles/:key', requireAuth, async (req, res) => {
try {
res.json({ item: await getDocArticle(pool, req.user, req.params.key) });
} catch (e) {
docsError(res, e, 'Не удалось загрузить статью', 'docs article');
}
});
app.post('/api/docs/sections', requireAdmin, async (req, res) => {
try {
const item = await createDocSection(pool, {
title: req.body?.title,
parent_id: req.body?.parent_id,
tutor_edit: req.body?.tutor_edit === true,
is_public: req.body?.is_public === true,
});
await logAudit(req, 'docs.section.create', { id: item.id, title: item.title, parent_id: item.parent_id });
res.json({ item });
} catch (e) {
docsError(res, e, 'Не удалось создать раздел', 'docs section create');
}
});
app.put('/api/docs/sections/reorder', requireAdmin, async (req, res) => {
try {
const raw = Array.isArray(req.body?.ids) ? req.body.ids : null;
if (!raw || raw.some(id => !Number.isInteger(Number(id)) || Number(id) < 1)) {
return res.status(400).json({ error: 'Некорректный порядок разделов' });
}
const ids = raw.map(Number);
if (new Set(ids).size !== ids.length) return res.status(400).json({ error: 'Порядок разделов содержит дубликаты' });
await reorderDocSections(pool, ids);
await logAudit(req, 'docs.section.reorder', { order: ids });
res.json({ ok: true });
} catch (e) {
docsError(res, e, 'Не удалось сохранить порядок разделов', 'docs section reorder');
}
});
app.put('/api/docs/sections/:id', requireAdmin, async (req, res) => {
try {
const item = await updateDocSection(pool, reqInt(req.params.id), {
title: req.body?.title,
parent_id: req.body?.parent_id,
tutor_edit: req.body?.tutor_edit === true,
is_public: req.body?.is_public === true,
});
await logAudit(req, 'docs.section.update', { id: item.id, title: item.title, tutor_edit: item.tutor_edit, is_public: item.is_public });
res.json({ item });
} catch (e) {
docsError(res, e, 'Не удалось сохранить раздел', 'docs section update');
}
});
app.delete('/api/docs/sections/:id', requireAdmin, async (req, res) => {
try {
const id = reqInt(req.params.id);
const images = await deleteDocSection(pool, id);
images.forEach(p => { safeUnlink(p); thumbUnlinkFor(p); });
await logAudit(req, 'docs.section.delete', { id });
res.json({ ok: true });
} catch (e) {
docsError(res, e, 'Не удалось удалить раздел', 'docs section delete');
}
});
app.post('/api/docs/articles', requireAuth, async (req, res) => {
try {
const item = await createDocArticle(pool, req.user, {
section_id: req.body?.section_id,
title: req.body?.title,
body: req.body?.body,
is_published: req.body?.is_published,
is_public: req.body?.is_public,
});
await logAudit(req, 'docs.article.create', { id: item.id, title: item.title, section_id: item.section_id });
res.json({ item });
} catch (e) {
docsError(res, e, 'Не удалось создать статью', 'docs article create');
}
});
app.put('/api/docs/articles/reorder', requireAdmin, async (req, res) => {
try {
const sectionId = reqInt(req.body?.section_id);
const raw = Array.isArray(req.body?.ids) ? req.body.ids : null;
if (!raw || raw.some(id => !Number.isInteger(Number(id)) || Number(id) < 1)) {
return res.status(400).json({ error: 'Некорректный порядок статей' });
}
const ids = raw.map(Number);
if (new Set(ids).size !== ids.length) return res.status(400).json({ error: 'Порядок статей содержит дубликаты' });
await reorderDocArticles(pool, sectionId, ids);
await logAudit(req, 'docs.article.reorder', { section_id: sectionId, order: ids });
res.json({ ok: true });
} catch (e) {
docsError(res, e, 'Не удалось сохранить порядок статей', 'docs article reorder');
}
});
app.put('/api/docs/articles/:id', requireAuth, async (req, res) => {
try {
const { item, staleImages } = await updateDocArticle(pool, req.user, reqInt(req.params.id), {
section_id: req.body?.section_id,
title: req.body?.title,
body: req.body?.body,
is_published: req.body?.is_published,
is_public: req.body?.is_public,
});
staleImages.forEach(p => { safeUnlink(p); thumbUnlinkFor(p); });
await logAudit(req, 'docs.article.update', {
id: item.id,
title: item.title,
section_id: item.section_id,
is_published: item.is_published,
is_public: item.is_public,
});
res.json({ item });
} catch (e) {
docsError(res, e, 'Не удалось сохранить статью', 'docs article update');
}
});
app.delete('/api/docs/articles/:id', requireAuth, async (req, res) => {
try {
const id = reqInt(req.params.id);
const images = await deleteDocArticle(pool, req.user, id);
images.forEach(p => { safeUnlink(p); thumbUnlinkFor(p); });
await logAudit(req, 'docs.article.delete', { id });
res.json({ ok: true });
} catch (e) {
docsError(res, e, 'Не удалось удалить статью', 'docs article delete');
}
});
const docImageUpload = upload.single('image');
app.post('/api/docs/images', requireAuth, (req, res) => {
docImageUpload(req, res, async err => {
if (err) {
if (err.code === 'LIMIT_FILE_SIZE') return res.status(400).json({ error: FILE_TOO_LARGE_ERROR });
if (err.message === 'Only images') return res.status(400).json({ error: 'Допустимы только изображения (jpg, png, gif, webp, bmp, avif, ico, heic, heif, jfif)' });
if (err.message === 'Not allowed extension') return res.status(400).json({ error: 'Недопустимый тип файла' });
return res.status(400).json({ error: 'Недопустимый файл' });
}
if (!req.file) return res.status(400).json({ error: 'Файл обязателен' });
try {
await convertPhoto(req.file);
const item = await registerDocImage(pool, { path: `/uploads/${req.file.filename}`, userId: req.user.id });
await logAudit(req, 'docs.image.create', { id: item.id, path: item.path });
res.json({ item: { id: item.id, path: item.path, url: item.path } });
} catch (e) {
removeUpload(req.file);
docsError(res, e, 'Не удалось загрузить картинку', 'docs image upload');
}
});
});
app.get('/api/docs/public/tree', apiLimiter, async (req, res) => {
try {
res.json(await publicDocTree(pool));
} catch (e) {
docsError(res, e, 'Не удалось загрузить документацию', 'docs public tree');
}
});
app.get('/api/docs/public/articles/:slug', apiLimiter, async (req, res) => {
try {
res.json({ item: await publicDocArticle(pool, req.params.slug) });
} catch (e) {
docsError(res, e, 'Не удалось загрузить статью', 'docs public article');
}
});
app.put('/api/feedbacks/:id', requireAuth, asyncRoute(async (req, res) => { app.put('/api/feedbacks/:id', requireAuth, asyncRoute(async (req, res) => {
const id = parseInt(req.params.id, 10); const id = parseInt(req.params.id, 10);
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' }); if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
@@ -6015,7 +6225,7 @@ function sweepBackupStorage() {
async function buildBackupArchive() { async function buildBackupArchive() {
const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-bk-')); const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-bk-'));
try { try {
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm, sfr, pfcs, swm] = await Promise.all([ const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm, sfr, pfcs, swm, ds, da, di] = await Promise.all([
pool.query('SELECT * FROM groups ORDER BY id'), pool.query('SELECT * FROM groups ORDER BY id'),
pool.query('SELECT * FROM students ORDER BY id'), pool.query('SELECT * FROM students ORDER BY id'),
pool.query('SELECT * FROM entries ORDER BY id'), pool.query('SELECT * FROM entries ORDER BY id'),
@@ -6047,6 +6257,9 @@ async function buildBackupArchive() {
pool.query('SELECT * FROM student_face_refs ORDER BY id'), pool.query('SELECT * FROM student_face_refs ORDER BY id'),
pool.query('SELECT * FROM photo_faces ORDER BY id'), pool.query('SELECT * FROM photo_faces ORDER BY id'),
pool.query('SELECT * FROM student_work_marks ORDER BY id'), pool.query('SELECT * FROM student_work_marks ORDER BY id'),
pool.query('SELECT * FROM doc_sections ORDER BY id'),
pool.query('SELECT * FROM doc_articles ORDER BY id'),
pool.query('SELECT * FROM doc_images ORDER BY id'),
]); ]);
const settings = {}; const settings = {};
st.rows.forEach(r => { settings[r.key] = r.value; }); st.rows.forEach(r => { settings[r.key] = r.value; });
@@ -6065,8 +6278,10 @@ async function buildBackupArchive() {
short_messages: sm.rowCount, feedbacks: fb.rowCount, user_settings: uss.rowCount, user_notes: un.rowCount, short_messages: sm.rowCount, feedbacks: fb.rowCount, user_settings: uss.rowCount, user_notes: un.rowCount,
bookmarks: bm.rowCount, bookmarks: bm.rowCount,
student_face_refs: sfr.rowCount, photo_faces: pfcs.rowCount, student_work_marks: swm.rowCount, student_face_refs: sfr.rowCount, photo_faces: pfcs.rowCount, student_work_marks: swm.rowCount,
doc_sections: ds.rowCount, doc_articles: da.rowCount, doc_images: di.rowCount,
}, },
groups: g.rows, students: s.rows, entries: e.rows, settings, project_files: pf.rows, branches: br.rows, users: us.rows, user_branches: ub.rows, group_photos: gp.rows, entry_photos: ep.rows, modules: md.rows, student_photos: sp.rows, share_links: sl.rows, photo_jobs: pj.rows, lesson_reports: lr.rows, lesson_report_versions: lrv.rows, audit_log: al.rows, notifications: nt.rows, notification_reads: nr.rows, banned_ips: bi.rows, chat_threads: ct.rows, chat_messages: cm.rows, chat_attachments: ca.rows, short_messages: sm.rows, feedbacks: fb.rows, user_settings: uss.rows, user_notes: un.rows, bookmarks: bm.rows, student_face_refs: sfr.rows, photo_faces: pfcs.rows, student_work_marks: swm.rows, groups: g.rows, students: s.rows, entries: e.rows, settings, project_files: pf.rows, branches: br.rows, users: us.rows, user_branches: ub.rows, group_photos: gp.rows, entry_photos: ep.rows, modules: md.rows, student_photos: sp.rows, share_links: sl.rows, photo_jobs: pj.rows, lesson_reports: lr.rows, lesson_report_versions: lrv.rows, audit_log: al.rows, notifications: nt.rows, notification_reads: nr.rows, banned_ips: bi.rows, chat_threads: ct.rows, chat_messages: cm.rows, chat_attachments: ca.rows, short_messages: sm.rows, feedbacks: fb.rows, user_settings: uss.rows, user_notes: un.rows, bookmarks: bm.rows, student_face_refs: sfr.rows, photo_faces: pfcs.rows, student_work_marks: swm.rows,
doc_sections: ds.rows, doc_articles: da.rows, doc_images: di.rows,
}; };
fs.writeFileSync(path.join(staging, 'data.json'), JSON.stringify(payload)); fs.writeFileSync(path.join(staging, 'data.json'), JSON.stringify(payload));
const files = await storage.downloadAll(path.join(staging, 'uploads')); const files = await storage.downloadAll(path.join(staging, 'uploads'));
@@ -6287,6 +6502,9 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
await client.query('DELETE FROM bookmarks'); await client.query('DELETE FROM bookmarks');
await client.query('DELETE FROM photo_faces'); await client.query('DELETE FROM photo_faces');
await client.query('DELETE FROM student_face_refs'); await client.query('DELETE FROM student_face_refs');
await client.query('DELETE FROM doc_images');
await client.query('DELETE FROM doc_articles');
await client.query('DELETE FROM doc_sections');
await client.query('DELETE FROM users'); await client.query('DELETE FROM users');
await client.query('DELETE FROM branches'); await client.query('DELETE FROM branches');
for (const x of ndata.branches) { for (const x of ndata.branches) {
@@ -6323,6 +6541,29 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
[x.id, x.title, x.url, x.description, x.photo_path || null, x.image_mode === 'cover' ? 'cover' : 'logo', x.open_new_tab !== false, x.is_active !== false, x.sort_order, x.created_at || null, x.updated_at || null] [x.id, x.title, x.url, x.description, x.photo_path || null, x.image_mode === 'cover' ? 'cover' : 'logo', x.open_new_tab !== false, x.is_active !== false, x.sort_order, x.created_at || null, x.updated_at || null]
); );
} }
for (const x of (ndata.doc_sections || [])) {
await client.query(
'INSERT INTO doc_sections (id, parent_id, title, sort_order, tutor_edit, is_public, created_at, updated_at) VALUES ($1, NULL, $2, $3, $4, $5, $6, $7)',
[x.id, x.title, x.sort_order, x.tutor_edit === true, x.is_public === true, x.created_at || null, x.updated_at || null]
);
}
for (const x of (ndata.doc_sections || [])) {
if (x.parent_id == null) continue;
await client.query('UPDATE doc_sections SET parent_id = $1 WHERE id = $2', [x.parent_id, x.id]);
}
for (const x of (ndata.doc_articles || [])) {
await client.query(
`INSERT INTO doc_articles (id, section_id, slug, title, body, sort_order, is_published, is_public, author_id, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, (SELECT id FROM users WHERE id = $9), $10, $11)`,
[x.id, x.section_id, x.slug, x.title, x.body, x.sort_order, x.is_published !== false, x.is_public === true, x.author_id, x.created_at || null, x.updated_at || null]
);
}
for (const x of (ndata.doc_images || [])) {
await client.query(
'INSERT INTO doc_images (id, article_id, path, uploaded_by, created_at) VALUES ($1, (SELECT id FROM doc_articles WHERE id = $2), $3, (SELECT id FROM users WHERE id = $4), $5)',
[x.id, x.article_id, x.path, x.uploaded_by, x.created_at || null]
);
}
for (const x of ndata.user_branches) { for (const x of ndata.user_branches) {
await client.query( await client.query(
'INSERT INTO user_branches (user_id, branch_id) VALUES ($1,$2)', 'INSERT INTO user_branches (user_id, branch_id) VALUES ($1,$2)',