Документация: разделы и статьи в 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
+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,
};