Документация: разделы и статьи в 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
+244 -3
View File
@@ -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)',