From 97426c70af60a443ca4aee4552f05c122bdcb7bf Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 23 Oct 2026 21:33:48 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=BA=D1=83=D0=BC=D0=B5=D0=BD?= =?UTF-8?q?=D1=82=D0=B0=D1=86=D0=B8=D1=8F:=20=D1=80=D0=B0=D0=B7=D0=B4?= =?UTF-8?q?=D0=B5=D0=BB=D1=8B=20=D0=B8=20=D1=81=D1=82=D0=B0=D1=82=D1=8C?= =?UTF-8?q?=D0=B8=20=D0=B2=20docs.html?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Добавлены 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 --- AGENTS.md | 30 ++ backup-restore.js | 53 ++- db/migration.sql | 66 ++++ lib/docs.js | 718 +++++++++++++++++++++++++++++++++++++++ public/admin.js | 1 + public/docs-public.html | 136 ++++++++ public/docs.html | 285 ++++++++++++++++ public/js/docs-public.js | 152 +++++++++ public/js/docs.js | 691 +++++++++++++++++++++++++++++++++++++ public/js/md.js | 192 +++++++++++ server.js | 247 +++++++++++++- 11 files changed, 2565 insertions(+), 6 deletions(-) create mode 100644 lib/docs.js create mode 100644 public/docs-public.html create mode 100644 public/docs.html create mode 100644 public/js/docs-public.js create mode 100644 public/js/docs.js create mode 100644 public/js/md.js diff --git a/AGENTS.md b/AGENTS.md index 5ac8041..ca6255e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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») и здесь - **Перевыпуск серверного сертификата** = `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/`); `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/` — хранимый 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=` + - `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 - **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` и фильтр не добавляется diff --git a/backup-restore.js b/backup-restore.js index ff18172..9867a17 100644 --- a/backup-restore.js +++ b/backup-restore.js @@ -19,14 +19,14 @@ const BACKUP_TABLES = [ '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', 'photo_faces', - 'student_work_marks', + 'student_work_marks', 'doc_sections', 'doc_articles', 'doc_images', ]; const BACKUP_SEQUENCE_TABLES = [ 'groups', 'students', 'entries', 'project_files', 'branches', 'users', 'user_notes', 'group_photos', 'entry_photos', 'modules', 'student_photos', 'share_links', 'photo_jobs', 'lesson_reports', 'lesson_report_versions', 'audit_log', 'notifications', 'chat_threads', 'chat_messages', '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) { @@ -623,6 +623,53 @@ function normalizeRestoreData(data) { created_at: optTs(x.created_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 => ({ id: reqInt(x.id), student_id: reqInt(x.student_id), @@ -646,7 +693,7 @@ function normalizeRestoreData(data) { created_at: optTs(x.created_at), updated_at: optTs(x.updated_at), })).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 = { diff --git a/db/migration.sql b/db/migration.sql index c0d53a1..37ae7ba 100644 --- a/db/migration.sql +++ b/db/migration.sql @@ -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 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 = 'Заметки'); diff --git a/lib/docs.js b/lib/docs.js new file mode 100644 index 0000000..1224048 --- /dev/null +++ b/lib/docs.js @@ -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, +}; diff --git a/public/admin.js b/public/admin.js index f7d674e..204dcf9 100644 --- a/public/admin.js +++ b/public/admin.js @@ -63,6 +63,7 @@ function buildSidebar(active) { { page: 'files', label: 'Файлы', icon: 'folder' }, { page: 'links', label: 'Ссылки', icon: 'link' }, { page: 'bookmarks', label: 'Закладки', icon: 'bookmark' }, + { page: 'docs', label: 'Документация', icon: 'book-open-text' }, { page: 'trash', label: 'Корзина', icon: 'trash-2' }, { page: 'notes', label: 'Заметки', icon: 'sticky-note' }, ]; diff --git a/public/docs-public.html b/public/docs-public.html new file mode 100644 index 0000000..5c5b1a8 --- /dev/null +++ b/public/docs-public.html @@ -0,0 +1,136 @@ + + + + + + Документация + + + +
+
+
Документация
+ +
+
+
+ +
+
+
+ + + + diff --git a/public/docs.html b/public/docs.html new file mode 100644 index 0000000..e69a381 --- /dev/null +++ b/public/docs.html @@ -0,0 +1,285 @@ + + + + + + Документация — Админ-панель + + + + +
+ +
+
+

Документация

+

Справочник по работе с системой

+ +
+ +
+ + +
+ + +
+
+
+ + + + + +
+ + + + + + + + diff --git a/public/js/docs-public.js b/public/js/docs-public.js new file mode 100644 index 0000000..f81b8ab --- /dev/null +++ b/public/js/docs-public.js @@ -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 = ''; + const ICON_FOLDER = ''; + 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, '&') + .replace(//g, '>') + .replace(/"/g, '"'); + } + + 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 `
${esc(article.title)}
`; + } + + 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 + ? `` + : ''; + const children = closed ? '' : [ + ...(node.children || []).map(child => sectionNode(child, depth + 1)), + ...(node.articles || []).map(article => articleRow(article, depth + 1)), + ].join(''); + return `
+
+ ${chev}${ICON_FOLDER}${esc(node.title)} +
+ ${children}
+ `; + } + + function renderTree() { + if (!tree.length) { + treeEl.innerHTML = '
Документация пока пуста
'; + 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 = `
${esc(article.section_title || '')}
+

${esc(article.title)}

+
${WhatIDoMD.render(article.body)}
`; + 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 = '
Статьи не опубликованы
'; + } catch (e) { + articleEl.textContent = e.message; + treeEl.innerHTML = '
Не удалось загрузить документацию
'; + } + } + + init(); +})(); diff --git a/public/js/docs.js b/public/js/docs.js new file mode 100644 index 0000000..e2fe706 --- /dev/null +++ b/public/js/docs.js @@ -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(``); + if (isAdmin()) { + acts.push(``); + acts.push(``); + acts.push(``); + acts.push(``); + } + return acts.join(''); + } + + function articleRow(article, depth) { + const active = current && Number(current.id) === Number(article.id); + const acts = isAdmin() + ? ` + ` + : ''; + return `
+ ${esc(article.title)}${article.is_published ? '' : ''} + ${acts} +
`; + } + + 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 + ? `` + : ''; + const children = closed ? '' : [ + ...(node.children || []).map(child => sectionNode(child, depth + 1)), + ...(node.articles || []).map(article => articleRow(article, depth + 1)), + ].join(''); + return `
+
+ ${chev} + + ${esc(node.title)} + ${sectionActs(node)} +
+
${children}
+
`; + } + + function renderTree() { + if (!tree.length) { + treeEl.innerHTML = '
Разделов пока нет
'; + renderIconsSafe(); + return; + } + treeEl.innerHTML = tree.map(node => sectionNode(node, 0)).join(''); + renderIconsSafe(); + } + + function renderEmpty() { + contentEl.hidden = false; + editorEl.hidden = true; + contentEl.innerHTML = `
Выберите статью слева${canCreateAnywhere() ? ' или создайте новую' : ''}
`; + } + + function articleHtml(article) { + const actions = []; + if (article.can_edit) { + actions.push(''); + actions.push(''); + } + if (article.is_public) { + actions.push(''); + } + const meta = []; + if (article.author_name) meta.push(`${esc(article.author_name)}`); + if (article.updated_at) meta.push(`Обновлено: ${fmtDateTime(article.updated_at)}`); + if (!article.is_published) meta.push('Черновик'); + if (article.is_public) meta.push('Публичная'); + return `
+
${esc(article.section_title || '')}
+

${esc(article.title)}

+
${meta.join('')}
+
${actions.join('')}
+
${WhatIDoMD.render(article.body)}
+
`; + } + + 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 ``; + }).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) + : '
Предпросмотр появится здесь
'; + } + + 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 = '' + list.map(s => { + const prefix = s.depth ? '\u00A0\u00A0'.repeat(s.depth) + '— ' : ''; + return ``; + }).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 = '
Ничего не найдено
'; + return; + } + treeEl.innerHTML = `
${data.items.map(item => { + const excerpt = String(item.excerpt || '').replace(/\s+/g, ' ').trim(); + return `
+ ${esc(item.title)} + ${esc(excerpt)} + ${esc(item.section_title || '')} +
`; + }).join('')}
`; + } 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(); +})(); diff --git a/public/js/md.js b/public/js/md.js new file mode 100644 index 0000000..40c1cf6 --- /dev/null +++ b/public/js/md.js @@ -0,0 +1,192 @@ +(function () { + function esc(value) { + return String(value == null ? '' : value) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"'); + } + + 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(/&/g, '&')); + if (!url) return alt; + return `${esc(alt)}`; + }); + text = text.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (m, label, href) => { + const url = safeUrl(href.replace(/&/g, '&')); + if (!url) return label; + const external = /^https?:\/\//i.test(url); + return `${label}`; + }); + text = text.replace(/\*\*([^*]+)\*\*/g, '$1'); + text = text.replace(/__([^_]+)__/g, '$1'); + text = text.replace(/~~([^~]+)~~/g, '$1'); + text = text.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1$2'); + text = text.replace(/\u0000(\d+)\u0000/g, (m, index) => `${esc(codes[Number(index)])}`); + 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 ? '
    ' : '
      '; + 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 + ''); + 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 = ` ${inline(task[2])}`; + } else { + content = inline(content); + } + html += `
    • ${content}
    • `; + 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()) + ''); + i++; + } + } + html += ordered ? '
' : ''; + 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 => `${inline(cell)}`).join(''); + const tbody = rows.map(row => `${row.map(cell => `${inline(cell)}`).join('')}`).join(''); + return { + html: `
${thead}${tbody}
`, + 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(`
${esc(code.join('\n'))}
`); + continue; + } + + const heading = line.match(/^(#{1,4})\s+(.*)$/); + if (heading) { + const level = heading[1].length; + out.push(`${inline(heading[2])}`); + i++; + continue; + } + + if (/^\s*([-*_])\1{2,}\s*$/.test(line)) { + out.push('
'); + 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(`
${render(quote.join('\n'))}
`); + 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(`

${paragraph.map(inline).join('
')}

`); + } + return out.join('\n'); + } + + window.WhatIDoMD = { render, inline, esc, thumbUrl, safeUrl }; +})(); diff --git a/server.js b/server.js index 41e81df..0fd691d 100644 --- a/server.js +++ b/server.js @@ -49,6 +49,24 @@ const { normalizeStudentStatus, ensureStudentsTable } = require('./lib/students' const { lessonReportWriteBlocked } = require('./lib/lesson-reports'); const { groupOwnedBy } = require('./lib/groups'); 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 path = require('path'); @@ -1678,7 +1696,7 @@ async function removeEntryFiles(entryId) { async function sweepOrphanedUploads() { const dir = UPLOADS_DIR; 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 path AS p FROM project_files'), 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 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 path AS p FROM doc_images'), ]); 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); 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: '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: '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: '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: 'Фото до обработки' }, @@ -2745,6 +2765,7 @@ async function ensureUsersAndFirstAdmin() { await ensureApiKeysTable(); await ensureUserNotesTable(); await ensureBookmarksTable(); + await ensureDocsTables(pool); await ensureFirstAdmin(); } @@ -4956,6 +4977,195 @@ app.delete('/api/bookmarks/:id/photo', requireAdmin, async (req, res) => { 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) => { const id = parseInt(req.params.id, 10); if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' }); @@ -6015,7 +6225,7 @@ function sweepBackupStorage() { async function buildBackupArchive() { const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-bk-')); 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 students 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 photo_faces 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 = {}; 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, bookmarks: bm.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, + doc_sections: ds.rows, doc_articles: da.rows, doc_images: di.rows, }; fs.writeFileSync(path.join(staging, 'data.json'), JSON.stringify(payload)); 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 photo_faces'); 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 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] ); } + 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) { await client.query( 'INSERT INTO user_branches (user_id, branch_id) VALUES ($1,$2)',