feat(sidebar): настройка пунктов меню, порядок и доступность для тьюторов; подсветка admin-only
This commit is contained in:
+15
-3
@@ -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 = {
|
||||
|
||||
+14
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+30
-4
@@ -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 ? `<span class="sidebar-badge" id="sidebarNotifyBadge" ${notifyUnread > 0 ? '' : 'hidden'}>${notifyUnread > 99 ? '99+' : notifyUnread}</span>` : '';
|
||||
const chatBadgeHtml = n.chatBadge ? `<span class="sidebar-badge" id="sidebarChatBadge" ${chatUnread > 0 ? '' : 'hidden'}>${chatUnread > 99 ? '99+' : chatUnread}</span>` : '';
|
||||
return `<a href="${n.page}.html" data-nav="${n.page}" class="${isAct ? 'active' : ''}" title="${n.label}">
|
||||
return `<a href="${n.page}.html" data-nav="${n.page}" class="${isAct ? 'active' : ''} ${isAdmin() && adminOnly ? 'nav-admin-only' : ''}" title="${n.label}${isAdmin() && adminOnly ? ' (только администратор)' : ''}">
|
||||
<i data-lucide="${n.icon}"></i>
|
||||
<span class="nav-text">${n.label}</span>
|
||||
${badgeHtml}
|
||||
|
||||
@@ -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 = `<span class="sidebar-item-handle" draggable="true" data-drag="${esc(it.page)}" title="Перетащить"><i data-lucide="grip-vertical"></i></span>`;
|
||||
const icon = `<span class="sidebar-item-icon"><i data-lucide="${esc(it.icon)}"></i></span>`;
|
||||
const tutorToggle = it.section === 'base'
|
||||
? `<label class="sidebar-toggle"><input type="checkbox" data-tutor="${esc(it.page)}" ${it.tutor_visible ? 'checked' : ''} ${disabled ? 'disabled' : ''}> Доступно тьюторам</label>`
|
||||
: '';
|
||||
const enabledToggle = it.page === 'sidebar'
|
||||
? `<label class="sidebar-toggle"><input type="checkbox" data-enabled="${esc(it.page)}" checked disabled> Включён</label>`
|
||||
: `<label class="sidebar-toggle"><input type="checkbox" data-enabled="${esc(it.page)}" ${it.enabled !== false ? 'checked' : ''}> Включён</label>`;
|
||||
return `<div class="sidebar-item ${disabled ? 'disabled' : ''}" data-page="${esc(it.page)}" data-section="${esc(it.section)}">
|
||||
${handle}
|
||||
${icon}
|
||||
<div class="sidebar-item-label">
|
||||
${esc(it.label)}
|
||||
<small>${esc(it.page)}</small>
|
||||
</div>
|
||||
<div class="sidebar-item-controls">
|
||||
${tutorToggle}
|
||||
${enabledToggle}
|
||||
<span class="sidebar-status ${statusCls}">${statusText}</span>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
})();
|
||||
@@ -0,0 +1,162 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Меню — Админ-панель</title>
|
||||
<link rel="stylesheet" href="admin.css">
|
||||
<style>
|
||||
.sidebar-settings-wrap { display: flex; flex-direction: column; gap: 20px; max-width: 920px; }
|
||||
.sidebar-settings-card {
|
||||
background: var(--card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 18px 20px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
}
|
||||
.sidebar-settings-card h3 { margin: 0; font-size: 1.05rem; display: flex; align-items: center; gap: 8px; }
|
||||
.sidebar-settings-card .hint { font-size: .82rem; color: var(--muted); line-height: 1.5; margin: 0; }
|
||||
.sidebar-settings-warn {
|
||||
background: rgba(245,158,11,.10);
|
||||
border: 1px solid rgba(245,158,11,.35);
|
||||
color: #b45309;
|
||||
border-radius: 10px;
|
||||
padding: 12px 14px;
|
||||
font-size: .85rem;
|
||||
line-height: 1.5;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
}
|
||||
.sidebar-settings-warn i { flex: none; margin-top: 2px; }
|
||||
.sidebar-items { display: flex; flex-direction: column; gap: 6px; }
|
||||
.sidebar-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 12px;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
transition: box-shadow .15s, opacity .15s, transform .15s;
|
||||
}
|
||||
.sidebar-item.dragging { opacity: .4; border-style: dashed; }
|
||||
.sidebar-item.drag-over { box-shadow: 0 0 0 2px var(--accent); }
|
||||
.sidebar-item.disabled { opacity: .5; }
|
||||
.sidebar-item-handle {
|
||||
cursor: grab;
|
||||
color: var(--muted);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 6px;
|
||||
flex: none;
|
||||
}
|
||||
.sidebar-item-handle:hover { color: var(--text); background: rgba(127,127,127,.15); }
|
||||
.sidebar-item-handle:active { cursor: grabbing; }
|
||||
.sidebar-item-icon {
|
||||
width: 32px;
|
||||
height: 32px;
|
||||
border-radius: 8px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: rgba(127,127,127,.12);
|
||||
color: var(--text);
|
||||
flex: none;
|
||||
}
|
||||
.sidebar-item-icon svg { width: 16px; height: 16px; }
|
||||
.sidebar-item-label {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-weight: 600;
|
||||
font-size: .9rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
.sidebar-item-label small { font-weight: 400; color: var(--muted); font-size: .75rem; }
|
||||
.sidebar-item-controls { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||
.sidebar-toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: .8rem;
|
||||
color: var(--text);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
.sidebar-toggle input { width: 16px; height: 16px; accent-color: var(--accent); cursor: pointer; }
|
||||
.sidebar-status {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 3px 9px;
|
||||
border-radius: 999px;
|
||||
font-size: .72rem;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.sidebar-status.status-tutor { background: rgba(34,197,94,.14); color: #15803d; }
|
||||
.sidebar-status.status-admin { background: rgba(127,127,127,.16); color: var(--muted); }
|
||||
.sidebar-status.status-off { background: rgba(239,68,68,.12); color: #dc2626; }
|
||||
.sidebar-settings-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
padding-top: 8px;
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
.sidebar-settings-foot .btn-primary { min-width: 140px; }
|
||||
.sidebar-settings-foot .save-hint { font-size: .82rem; color: var(--muted); }
|
||||
@media (max-width: 720px) {
|
||||
.sidebar-item { flex-wrap: wrap; }
|
||||
.sidebar-item-controls { width: 100%; justify-content: flex-start; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body data-page="sidebar">
|
||||
<div class="layout">
|
||||
<div class="sidebar" id="sidebar"></div>
|
||||
<div class="main">
|
||||
<div class="page-head">
|
||||
<h2>Настройка меню</h2>
|
||||
<p class="page-sub">Порядок и доступность пунктов бокового меню для пользователей</p>
|
||||
</div>
|
||||
<div class="sidebar-settings-wrap">
|
||||
<div class="sidebar-settings-warn">
|
||||
<i data-lucide="alert-triangle"></i>
|
||||
<div>
|
||||
<strong>Важно:</strong> скрытие пункта не закрывает страницу по прямой ссылке — доступ к URL по-прежнему определяется правами пользователя.
|
||||
Пункты раздела «Администрирование» всегда видны только администраторам.
|
||||
</div>
|
||||
</div>
|
||||
<div class="sidebar-settings-card">
|
||||
<h3><i data-lucide="layout-list"></i> Основное меню</h3>
|
||||
<p class="hint">Перетащите пункты, чтобы изменить порядок. Включите «Доступно тьюторам», чтобы пункт появился у пользователей без прав администратора.</p>
|
||||
<div class="sidebar-items" id="sidebarBaseList"></div>
|
||||
</div>
|
||||
<div class="sidebar-settings-card">
|
||||
<h3><i data-lucide="shield-check"></i> Администрирование</h3>
|
||||
<p class="hint">Эти пункты видны только администраторам. Можно отключить отдельные пункты, если они не нужны.</p>
|
||||
<div class="sidebar-items" id="sidebarAdminList"></div>
|
||||
</div>
|
||||
<div class="sidebar-settings-foot">
|
||||
<button type="button" class="btn-primary" id="sidebarSaveBtn"><i data-lucide="save"></i> Сохранить</button>
|
||||
<span class="save-hint" id="sidebarSaveHint"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="vendor/lucide.min.js"></script>
|
||||
<script src="js/datetime.js"></script>
|
||||
<script src="admin.js"></script>
|
||||
<script src="js/sidebar-settings.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user