From b360ca8303b3d22afe394e05a4060d41a86f091f Mon Sep 17 00:00:00 2001 From: dev Date: Mon, 2 Nov 2026 22:34:14 +0300 Subject: [PATCH] =?UTF-8?q?feat(sidebar):=20=D0=BD=D0=B0=D1=81=D1=82=D1=80?= =?UTF-8?q?=D0=BE=D0=B9=D0=BA=D0=B0=20=D0=BF=D1=83=D0=BD=D0=BA=D1=82=D0=BE?= =?UTF-8?q?=D0=B2=20=D0=BC=D0=B5=D0=BD=D1=8E,=20=D0=BF=D0=BE=D1=80=D1=8F?= =?UTF-8?q?=D0=B4=D0=BE=D0=BA=20=D0=B8=20=D0=B4=D0=BE=D1=81=D1=82=D1=83?= =?UTF-8?q?=D0=BF=D0=BD=D0=BE=D1=81=D1=82=D1=8C=20=D0=B4=D0=BB=D1=8F=20?= =?UTF-8?q?=D1=82=D1=8C=D1=8E=D1=82=D0=BE=D1=80=D0=BE=D0=B2;=20=D0=BF?= =?UTF-8?q?=D0=BE=D0=B4=D1=81=D0=B2=D0=B5=D1=82=D0=BA=D0=B0=20admin-only?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backup-restore.js | 18 +++- db/init.sql | 14 +++ db/migration.sql | 14 +++ lib/sidebar.js | 91 +++++++++++++++++++ public/admin.css | 10 +++ public/admin.js | 34 ++++++- public/js/sidebar-settings.js | 157 ++++++++++++++++++++++++++++++++ public/sidebar.html | 162 ++++++++++++++++++++++++++++++++++ server.js | 65 +++++++++++++- 9 files changed, 555 insertions(+), 10 deletions(-) create mode 100644 lib/sidebar.js create mode 100644 public/js/sidebar-settings.js create mode 100644 public/sidebar.html diff --git a/backup-restore.js b/backup-restore.js index 51ee23b..a8c92ae 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', 'achievement_types', 'student_achievements', 'doc_sections', 'doc_articles', 'doc_images', 'doc_files', + 'student_work_marks', 'achievement_types', 'student_achievements', 'doc_sections', 'doc_articles', 'doc_images', 'doc_files', 'sidebar_items', ]; 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', 'achievement_types', 'student_achievements', 'doc_sections', 'doc_articles', 'doc_images', 'doc_files', + 'student_work_marks', 'achievement_types', 'student_achievements', 'doc_sections', 'doc_articles', 'doc_images', 'doc_files', 'sidebar_items', ]; function isSupportedBackupVersion(data) { @@ -701,6 +701,18 @@ function normalizeRestoreData(data) { uploaded_by: x.uploaded_by == null ? null : reqInt(x.uploaded_by), created_at: optTs(x.created_at), })).filter(x => x.path); + const sidebarItems = (data.sidebar_items || []).map(x => ({ + id: reqInt(x.id), + page: optText(x.page, 64) || '', + label: optText(x.label, 64) || '', + icon: optText(x.icon, 64) || 'circle', + section: x.section === 'admin' ? 'admin' : 'base', + sort_order: optInt(x.sort_order, -10000000, 10000000) ?? 0, + tutor_visible: x.tutor_visible === true, + enabled: x.enabled !== false, + created_at: optTs(x.created_at), + updated_at: optTs(x.updated_at), + })).filter(x => x.page && x.label); const faceRefs = (data.student_face_refs || []).map(x => ({ id: reqInt(x.id), student_id: reqInt(x.student_id), @@ -724,7 +736,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, achievement_types: achievementTypes, student_achievements: studentAchievements, student_face_refs: faceRefs, photo_faces: faceRows, student_work_marks, doc_sections: docSections, doc_articles: docArticles, doc_images: docImages, doc_files: docFiles }; + 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, achievement_types: achievementTypes, student_achievements: studentAchievements, student_face_refs: faceRefs, photo_faces: faceRows, student_work_marks, doc_sections: docSections, doc_articles: docArticles, doc_images: docImages, doc_files: docFiles, sidebar_items: sidebarItems }; } module.exports = { diff --git a/db/init.sql b/db/init.sql index ca6b52a..2332e28 100644 --- a/db/init.sql +++ b/db/init.sql @@ -728,3 +728,17 @@ CREATE TABLE IF NOT EXISTS student_achievements ( updated_at TIMESTAMPTZ DEFAULT now() ); CREATE INDEX IF NOT EXISTS idx_student_achievements_student ON student_achievements(student_id); + +CREATE TABLE IF NOT EXISTS sidebar_items ( + id SERIAL PRIMARY KEY, + page TEXT NOT NULL UNIQUE, + label TEXT NOT NULL, + icon TEXT NOT NULL DEFAULT 'circle', + section TEXT NOT NULL DEFAULT 'base', + sort_order INT NOT NULL DEFAULT 0, + tutor_visible BOOLEAN NOT NULL DEFAULT true, + enabled BOOLEAN NOT NULL DEFAULT true, + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); +CREATE INDEX IF NOT EXISTS idx_sidebar_items_section_order ON sidebar_items(section, sort_order, id); diff --git a/db/migration.sql b/db/migration.sql index 0ff6f0a..bb372b4 100644 --- a/db/migration.sql +++ b/db/migration.sql @@ -987,3 +987,17 @@ CREATE INDEX IF NOT EXISTS idx_student_achievements_student ON student_achieveme INSERT INTO settings (key, value) VALUES ('feedback_imgbb_url','') ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('feedback_imgbb_key','') ON CONFLICT (key) DO NOTHING; + +CREATE TABLE IF NOT EXISTS sidebar_items ( + id SERIAL PRIMARY KEY, + page TEXT NOT NULL UNIQUE, + label TEXT NOT NULL, + icon TEXT NOT NULL DEFAULT 'circle', + section TEXT NOT NULL DEFAULT 'base', + sort_order INT NOT NULL DEFAULT 0, + tutor_visible BOOLEAN NOT NULL DEFAULT true, + enabled BOOLEAN NOT NULL DEFAULT true, + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); +CREATE INDEX IF NOT EXISTS idx_sidebar_items_section_order ON sidebar_items(section, sort_order, id); diff --git a/lib/sidebar.js b/lib/sidebar.js new file mode 100644 index 0000000..7c3f82f --- /dev/null +++ b/lib/sidebar.js @@ -0,0 +1,91 @@ +const DEFAULT_ITEMS = [ + { page: 'dashboard', label: 'Дашборд', icon: 'layout-dashboard', section: 'base', sort_order: 10, tutor_visible: true, enabled: true }, + { page: 'profile', label: 'Профиль', icon: 'user', section: 'base', sort_order: 20, tutor_visible: true, enabled: true }, + { page: 'journal', label: 'Журнал', icon: 'book-open', section: 'base', sort_order: 30, tutor_visible: true, enabled: true }, + { page: 'lessons', label: 'Отчёты о занятиях', icon: 'notebook-pen', section: 'base', sort_order: 40, tutor_visible: true, enabled: true }, + { page: 'postlesson', label: 'Задачи после занятия', icon: 'list-checks', section: 'base', sort_order: 50, tutor_visible: true, enabled: true }, + { page: 'students', label: 'Ученики', icon: 'graduation-cap', section: 'base', sort_order: 60, tutor_visible: true, enabled: true }, + { page: 'groups', label: 'Группы', icon: 'users', section: 'base', sort_order: 70, tutor_visible: true, enabled: true }, + { page: 'feedback', label: 'Обратная связь', icon: 'message-square-heart', section: 'base', sort_order: 80, tutor_visible: true, enabled: true }, + { page: 'shorts', label: 'Короткие сообщения', icon: 'zap', section: 'base', sort_order: 90, tutor_visible: true, enabled: true }, + { page: 'chat', label: 'Чаты', icon: 'messages-square', section: 'base', sort_order: 100, tutor_visible: true, enabled: true }, + { page: 'notifications', label: 'Уведомления', icon: 'bell', section: 'base', sort_order: 110, tutor_visible: true, enabled: true }, + { page: 'photos', label: 'Фото', icon: 'Image', section: 'base', sort_order: 120, tutor_visible: true, enabled: true }, + { page: 'files', label: 'Файлы', icon: 'folder', section: 'base', sort_order: 130, tutor_visible: true, enabled: true }, + { page: 'links', label: 'Ссылки', icon: 'link', section: 'base', sort_order: 140, tutor_visible: true, enabled: true }, + { page: 'bookmarks', label: 'Закладки', icon: 'bookmark', section: 'base', sort_order: 150, tutor_visible: true, enabled: true }, + { page: 'docs', label: 'Документация', icon: 'book-open-text', section: 'base', sort_order: 160, tutor_visible: true, enabled: true }, + { page: 'trash', label: 'Корзина', icon: 'trash-2', section: 'base', sort_order: 170, tutor_visible: true, enabled: true }, + { page: 'notes', label: 'Заметки', icon: 'sticky-note', section: 'base', sort_order: 180, tutor_visible: true, enabled: true }, + { page: 'settings', label: 'Настройки', icon: 'settings', section: 'admin', sort_order: 10, tutor_visible: false, enabled: true }, + { page: 'modules', label: 'Темы модулей', icon: 'layers', section: 'admin', sort_order: 20, tutor_visible: false, enabled: true }, + { page: 'users', label: 'Пользователи', icon: 'user-cog', section: 'admin', sort_order: 30, tutor_visible: false, enabled: true }, + { page: 'branches', label: 'Филиалы', icon: 'building-2', section: 'admin', sort_order: 40, tutor_visible: false, enabled: true }, + { page: 'audit', label: 'Аудит', icon: 'scroll-text', section: 'admin', sort_order: 50, tutor_visible: false, enabled: true }, + { page: 'worker', label: 'Воркер ИИ', icon: 'bot', section: 'admin', sort_order: 60, tutor_visible: false, enabled: true }, + { page: 'faces', label: 'Сканер лиц', icon: 'scan-face', section: 'admin', sort_order: 70, tutor_visible: false, enabled: true }, + { page: 'apikeys', label: 'API-ключи', icon: 'key-round', section: 'admin', sort_order: 80, tutor_visible: false, enabled: true }, + { page: 'bans', label: 'Блокировки', icon: 'shield-off', section: 'admin', sort_order: 90, tutor_visible: false, enabled: true }, + { page: 'sidebar', label: 'Меню', icon: 'panel-left', section: 'admin', sort_order: 100, tutor_visible: false, enabled: true }, +]; + +async function ensureSidebarItemsTable(pool) { + await pool.query(`CREATE TABLE IF NOT EXISTS sidebar_items ( + id SERIAL PRIMARY KEY, + page TEXT NOT NULL UNIQUE, + label TEXT NOT NULL, + icon TEXT NOT NULL DEFAULT 'circle', + section TEXT NOT NULL DEFAULT 'base', + sort_order INT NOT NULL DEFAULT 0, + tutor_visible BOOLEAN NOT NULL DEFAULT true, + enabled BOOLEAN NOT NULL DEFAULT true, + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() + )`); + await pool.query(`CREATE INDEX IF NOT EXISTS idx_sidebar_items_section_order ON sidebar_items(section, sort_order, id)`); + for (const it of DEFAULT_ITEMS) { + await pool.query( + `INSERT INTO sidebar_items (page, label, icon, section, sort_order, tutor_visible, enabled) + VALUES ($1,$2,$3,$4,$5,$6,$7) ON CONFLICT (page) DO NOTHING`, + [it.page, it.label, it.icon, it.section, it.sort_order, it.tutor_visible, it.enabled] + ); + } +} + +async function listSidebarItems(pool) { + const { rows } = await pool.query( + `SELECT id, page, label, icon, section, sort_order, tutor_visible, enabled, updated_at + FROM sidebar_items ORDER BY section ASC, sort_order ASC, id ASC` + ); + return rows; +} + +function normalizeSidebarPayload(input) { + if (!Array.isArray(input)) throw new Error('items must be array'); + const out = []; + const seen = new Set(); + for (const raw of input) { + if (!raw || typeof raw !== 'object') throw new Error('bad item'); + const page = String(raw.page || '').trim(); + if (!page || page.length > 64) throw new Error('bad page'); + if (seen.has(page)) throw new Error('duplicate page'); + seen.add(page); + const label = String(raw.label || '').trim(); + if (!label || label.length > 64) throw new Error('bad label'); + const icon = String(raw.icon || '').trim(); + if (!icon || icon.length > 64) throw new Error('bad icon'); + const section = raw.section === 'admin' ? 'admin' : 'base'; + const sort_order = Number.isFinite(Number(raw.sort_order)) ? Math.trunc(Number(raw.sort_order)) : 0; + const tutor_visible = raw.tutor_visible === true || raw.tutor_visible === 'true'; + const enabled = raw.enabled === undefined ? true : (raw.enabled === true || raw.enabled === 'true'); + out.push({ page, label, icon, section, sort_order, tutor_visible, enabled }); + } + return out; +} + +module.exports = { + DEFAULT_ITEMS, + ensureSidebarItemsTable, + listSidebarItems, + normalizeSidebarPayload, +}; diff --git a/public/admin.css b/public/admin.css index ab3e57c..79153d5 100644 --- a/public/admin.css +++ b/public/admin.css @@ -1464,3 +1464,13 @@ body.report-card-open .report-fields{display:flex} .chat-messages{max-height:none} .msg{max-width:92%} } +.nav-admin-only { opacity: .72; } +.nav-admin-only::after { + content: ''; + display: inline-block; + width: 6px; height: 6px; + border-radius: 50%; + background: #94a3b8; + margin-left: 6px; + vertical-align: middle; +} diff --git a/public/admin.js b/public/admin.js index 36f2df6..4b6274c 100644 --- a/public/admin.js +++ b/public/admin.js @@ -1,6 +1,7 @@ const API = location.origin; let token = sessionStorage.getItem('authToken'); let currentUser = null; +let sidebarConfig = null; function hdr() { return { 'X-Auth-Token': token }; } function hdrJson() { return { 'Content-Type': 'application/json', 'X-Auth-Token': token }; } function esc(s) { const d = document.createElement('div'); d.textContent = s; return d.innerHTML; } @@ -37,6 +38,7 @@ async function checkAuth() { if (!res.ok) { cleanupSession(); return false; } currentUser = await res.json(); await initDateTime(); + await loadSidebarConfig(); return true; } catch { cleanupSession(); return false; } } @@ -50,6 +52,15 @@ function cleanupSession() { function isAdmin() { return currentUser && currentUser.role === 'admin'; } +async function loadSidebarConfig() { + try { + const res = await fetch(`${API}/api/sidebar`, { headers: hdr() }); + if (!res.ok) return; + const data = await res.json(); + sidebarConfig = Array.isArray(data.items) ? data.items : null; + } catch { sidebarConfig = null; } +} + async function requireAdminPage() { if (!(await checkAuth())) return false; if (!isAdmin()) { location.href = 'journal.html'; return false; } @@ -65,8 +76,8 @@ async function doLogout() { function buildSidebar(active) { const el = document.getElementById('sidebar'); if (!el) return; - const base = [ - { page: 'dashboard', label: 'Дашборд', icon: 'layout-dashboard' }, + const fallbackBase = [ + { page: 'dashboard', label: 'Дашборд', icon: 'layout-dashboard', section: 'base', tutorVisible: true }, { page: 'profile', label: 'Профиль', icon: 'user' }, { page: 'journal', label: 'Журнал', icon: 'book-open' }, { page: 'lessons', label: 'Отчёты о занятиях', icon: 'notebook-pen' }, @@ -85,7 +96,7 @@ function buildSidebar(active) { { page: 'trash', label: 'Корзина', icon: 'trash-2' }, { page: 'notes', label: 'Заметки', icon: 'sticky-note' }, ]; - const adminNav = [ + const fallbackAdmin = [ { page: 'settings', label: 'Настройки', icon: 'settings' }, { page: 'modules', label: 'Темы модулей', icon: 'layers' }, { page: 'users', label: 'Пользователи', icon: 'user-cog' }, @@ -95,14 +106,29 @@ function buildSidebar(active) { { page: 'faces', label: 'Сканер лиц', icon: 'scan-face' }, { page: 'apikeys', label: 'API-ключи', icon: 'key-round' }, { page: 'bans', label: 'Блокировки', icon: 'shield-off' }, + { page: 'sidebar', label: 'Меню', icon: 'panel-left' }, ]; + fallbackBase.forEach(i => { i.section = 'base'; i.tutorVisible = true; }); + fallbackAdmin.forEach(i => { i.section = 'admin'; i.tutorVisible = false; }); + let base = fallbackBase; + let adminNav = fallbackAdmin; + if (sidebarConfig) { + const sorted = [...sidebarConfig].sort((a, b) => { + if (a.section !== b.section) return a.section === 'base' ? -1 : 1; + return (a.sort_order || 0) - (b.sort_order || 0); + }); + const toNav = (i) => ({ page: i.page, label: i.label, icon: i.icon, badge: i.page === 'notifications', chatBadge: i.page === 'chat' }); + base = sorted.filter(i => i.section === 'base' && i.enabled !== false).map(toNav); + adminNav = sorted.filter(i => i.section === 'admin' && i.enabled !== false).map(toNav); + } const userName = currentUser?.name || currentUser?.username || ''; const roleLabel = isAdmin() ? 'Администратор' : 'Тутор'; const renderItem = n => { const isAct = n.page === active; + const adminOnly = n.section === 'admin' || n.tutorVisible === false; const badgeHtml = n.badge ? ` 0 ? '' : 'hidden'}>${notifyUnread > 99 ? '99+' : notifyUnread}` : ''; const chatBadgeHtml = n.chatBadge ? ` 0 ? '' : 'hidden'}>${chatUnread > 99 ? '99+' : chatUnread}` : ''; - return ` + return ` ${n.label} ${badgeHtml} diff --git a/public/js/sidebar-settings.js b/public/js/sidebar-settings.js new file mode 100644 index 0000000..4d61aac --- /dev/null +++ b/public/js/sidebar-settings.js @@ -0,0 +1,157 @@ +let sidebarItems = []; + +async function loadSidebarSettings() { + const res = await fetch(`${API}/api/sidebar`, { headers: hdr() }); + if (!res.ok) throw new Error('load failed'); + const data = await res.json(); + sidebarItems = (data.items || []).map(x => ({ ...x })); + renderSidebarSettings(); +} + +function renderSidebarSettings() { + const base = sidebarItems.filter(x => x.section === 'base').sort((a, b) => a.sort_order - b.sort_order); + const admin = sidebarItems.filter(x => x.section === 'admin').sort((a, b) => a.sort_order - b.sort_order); + document.getElementById('sidebarBaseList').innerHTML = base.map(renderSidebarItem).join(''); + document.getElementById('sidebarAdminList').innerHTML = admin.map(renderSidebarItem).join(''); + renderIcons(); + bindSidebarDrag(); +} + +function renderSidebarItem(it) { + const disabled = it.enabled === false; + const isTutor = it.section === 'base' && it.tutor_visible === true && it.enabled !== false; + const isAdminOnly = it.section === 'admin' || it.tutor_visible === false; + let statusCls = 'status-admin'; + let statusText = 'Только админ'; + if (disabled) { statusCls = 'status-off'; statusText = 'Отключён'; } + else if (isTutor) { statusCls = 'status-tutor'; statusText = 'Доступно тьюторам'; } + const handle = ``; + const icon = ``; + const tutorToggle = it.section === 'base' + ? `` + : ''; + const enabledToggle = it.page === 'sidebar' + ? `` + : ``; + return ``; +} + +function bindSidebarDrag() { + const lists = [document.getElementById('sidebarBaseList'), document.getElementById('sidebarAdminList')]; + lists.forEach(list => { + if (!list) return; + list.querySelectorAll('.sidebar-item').forEach(item => { + const handle = item.querySelector('.sidebar-item-handle'); + if (!handle) return; + handle.addEventListener('dragstart', e => { + e.dataTransfer.setData('text/plain', item.dataset.page); + e.dataTransfer.effectAllowed = 'move'; + item.classList.add('dragging'); + }); + handle.addEventListener('dragend', () => item.classList.remove('dragging')); + }); + list.addEventListener('dragover', e => { + e.preventDefault(); + const dragging = list.querySelector('.dragging'); + if (!dragging) return; + const after = getDragAfterElement(list, e.clientY); + if (after == null) list.appendChild(dragging); + else list.insertBefore(dragging, after); + }); + list.addEventListener('drop', e => { + e.preventDefault(); + lists.forEach(l => l.querySelectorAll('.sidebar-item').forEach(i => i.classList.remove('drag-over'))); + }); + }); + // sync toggles + document.querySelectorAll('[data-tutor]').forEach(cb => { + cb.addEventListener('change', () => { + const it = sidebarItems.find(x => x.page === cb.dataset.tutor); + if (it) it.tutor_visible = cb.checked; + renderSidebarSettings(); + }); + }); + document.querySelectorAll('[data-enabled]').forEach(cb => { + cb.addEventListener('change', () => { + if (cb.dataset.enabled === 'sidebar') return; + const it = sidebarItems.find(x => x.page === cb.dataset.enabled); + if (it) it.enabled = cb.checked; + renderSidebarSettings(); + }); + }); +} + +function getDragAfterElement(container, y) { + const els = [...container.querySelectorAll('.sidebar-item:not(.dragging)')]; + let closest = { offset: Number.NEGATIVE_INFINITY, element: null }; + for (const el of els) { + const box = el.getBoundingClientRect(); + const offset = y - box.top - box.height / 2; + if (offset < 0 && offset > closest.offset) { + closest = { offset, element: el }; + } + } + return closest.element; +} + +async function saveSidebarSettings() { + const hint = document.getElementById('sidebarSaveHint'); + const btn = document.getElementById('sidebarSaveBtn'); + // rebuild order from DOM + const ordered = []; + ['sidebarBaseList', 'sidebarAdminList'].forEach(id => { + const list = document.getElementById(id); + if (!list) return; + list.querySelectorAll('.sidebar-item').forEach((el, idx) => { + const it = sidebarItems.find(x => x.page === el.dataset.page); + if (it) { + it.sort_order = (idx + 1) * 10; + ordered.push(it); + } + }); + }); + btn.disabled = true; + try { + const res = await fetch(`${API}/api/sidebar`, { + method: 'PUT', + headers: hdrJson(), + body: JSON.stringify({ items: ordered }), + }); + if (!res.ok) { + const d = await res.json().catch(() => ({})); + throw new Error(d.error || 'save failed'); + } + hint.textContent = 'Сохранено'; + hint.style.color = ''; + await loadSidebarSettings(); + } catch (e) { + hint.textContent = 'Ошибка: ' + (e.message || ''); + hint.style.color = '#ef4444'; + } finally { + btn.disabled = false; + } +} + +(async () => { + if (await requireAdminPage()) { + buildSidebar(document.body.dataset.page); + try { + await loadSidebarSettings(); + } catch (e) { + document.getElementById('sidebarSaveHint').textContent = 'Не удалось загрузить меню'; + } + document.getElementById('sidebarSaveBtn').addEventListener('click', saveSidebarSettings); + } +})(); diff --git a/public/sidebar.html b/public/sidebar.html new file mode 100644 index 0000000..b79f151 --- /dev/null +++ b/public/sidebar.html @@ -0,0 +1,162 @@ + + + + + + Меню — Админ-панель + + + + +
+ +
+
+

Настройка меню

+

Порядок и доступность пунктов бокового меню для пользователей

+
+ +
+
+ + + + + + + diff --git a/server.js b/server.js index ae88cb6..47bb6dd 100644 --- a/server.js +++ b/server.js @@ -114,6 +114,7 @@ const { updateRecord: achUpdateRecord, deleteRecord: achDeleteRecord, } = require('./lib/achievements'); +const { ensureSidebarItemsTable, listSidebarItems, normalizeSidebarPayload } = require('./lib/sidebar'); const https = require('https'); const path = require('path'); @@ -2906,6 +2907,7 @@ async function ensureUsersAndFirstAdmin() { await ensureUserNotesTable(); await ensureBookmarksTable(); await ensureAchievementsTables(); + await ensureSidebarItemsTable(pool); await ensureDocsTables(pool); await ensureBackupTicketsTable(pool); await ensureFirstAdmin(); @@ -6006,6 +6008,55 @@ app.post('/api/api-keys/:id/rotate', requireAuth, requireAdmin, async (req, res) res.json({ ...apiKeyPublic(rows[0]), key: raw }); }); +// --- Sidebar menu --- +app.get('/api/sidebar', requireAuth, async (req, res) => { + const isAdminUser = req.user && req.user.role === 'admin'; + const items = await listSidebarItems(pool); + let out = items; + if (!isAdminUser) { + out = items.filter(i => i.section === 'base' && i.enabled && i.tutor_visible); + } + out = out.map(i => ({ + page: i.page, + label: i.label, + icon: i.icon, + section: i.section, + sort_order: i.sort_order, + tutor_visible: i.tutor_visible, + enabled: i.enabled, + })); + res.json({ items: out }); +}); + +app.put('/api/sidebar', requireAdmin, async (req, res) => { + const body = req.body || {}; + let normalized; + try { + normalized = normalizeSidebarPayload(body.items); + } catch (e) { + return res.status(400).json({ error: e.message || 'bad payload' }); + } + const client = await pool.connect(); + try { + await client.query('BEGIN'); + for (const it of normalized) { + await client.query( + `UPDATE sidebar_items SET label=$1, icon=$2, section=$3, sort_order=$4, tutor_visible=$5, enabled=$6, updated_at=now() + WHERE page=$7`, + [it.label, it.icon, it.section, it.sort_order, it.tutor_visible, it.enabled, it.page] + ); + } + await client.query('COMMIT'); + } catch (e) { + await client.query('ROLLBACK'); + return res.status(500).json({ error: 'save failed' }); + } finally { + client.release(); + } + await logAudit(req, 'sidebar.update', { count: normalized.length }); + res.json({ ok: true }); +}); + // --- Settings --- app.get('/api/settings', requireAdmin, async (_, res) => { const { rows } = await pool.query('SELECT key, value FROM settings ORDER BY key'); @@ -6742,7 +6793,7 @@ function backupUploadGuard(req, res, next) { 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, ds, da, di, df, atr, sar] = 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, df, si, atr, sar] = 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'), @@ -6778,6 +6829,7 @@ async function buildBackupArchive() { pool.query('SELECT * FROM doc_articles ORDER BY id'), pool.query('SELECT * FROM doc_images ORDER BY id'), pool.query('SELECT * FROM doc_files ORDER BY id'), + pool.query('SELECT * FROM sidebar_items ORDER BY id'), pool.query('SELECT * FROM achievement_types ORDER BY id'), pool.query('SELECT * FROM student_achievements ORDER BY id'), ]); @@ -6800,12 +6852,12 @@ async function buildBackupArchive() { student_face_refs: sfr.rowCount, photo_faces: pfcs.rowCount, student_work_marks: swm.rowCount, achievement_types: atr.rowCount, student_achievements: sar.rowCount, doc_sections: ds.rowCount, doc_articles: da.rowCount, doc_images: di.rowCount, - doc_files: df.rowCount, + doc_files: df.rowCount, sidebar_items: si.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, achievement_types: atr.rows, student_achievements: sar.rows, doc_sections: ds.rows, doc_articles: da.rows, doc_images: di.rows, - doc_files: df.rows, + doc_files: df.rows, sidebar_items: si.rows, }; fs.writeFileSync(path.join(staging, 'data.json'), JSON.stringify(payload)); const files = await storage.downloadAll(path.join(staging, 'uploads')); @@ -7085,6 +7137,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b await client.query('DELETE FROM doc_files'); await client.query('DELETE FROM doc_articles'); await client.query('DELETE FROM doc_sections'); + await client.query('DELETE FROM sidebar_items'); await client.query('DELETE FROM users'); await client.query('DELETE FROM branches'); for (const x of ndata.branches) { @@ -7137,6 +7190,12 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b 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.sidebar_items || [])) { + await client.query( + 'INSERT INTO sidebar_items (id, page, label, icon, section, sort_order, tutor_visible, enabled, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)', + [x.id, x.page, x.label, x.icon, x.section, x.sort_order, x.tutor_visible, x.enabled, x.created_at || null, x.updated_at || null] + ); + } 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)