feat(sidebar): виды пунктов меню (item/divider/group), restore и upsert по id
- схема sidebar_items: колонка kind (item|divider|group), pagenullable, label с дефолтом '', constraint種別 - миграция для существующих БД: ADD COLUMN kind, DROP NOT NULL page, SET DEFAULT label, пересоздание constraint - restore: upsert по id (обновление существующих, вставка новых, удаление отсутствующих вpayload) - normalizeRestoreData: kind валидируется, filter по kind/item требует page+label - фронт: добавление разделителя/группы, удаление по cid, порядок из DOM через _cid, payload с kind/id
This commit is contained in:
+3
-2
@@ -704,7 +704,8 @@ function normalizeRestoreData(data) {
|
||||
})).filter(x => x.path);
|
||||
const sidebarItems = (data.sidebar_items || []).map(x => ({
|
||||
id: reqInt(x.id),
|
||||
page: optText(x.page, 64) || '',
|
||||
kind: ['item','divider','group'].includes(x.kind) ? x.kind : 'item',
|
||||
page: optText(x.page, 64) || null,
|
||||
label: optText(x.label, 64) || '',
|
||||
icon: optText(x.icon, 64) || 'circle',
|
||||
section: x.section === 'admin' ? 'admin' : 'base',
|
||||
@@ -713,7 +714,7 @@ function normalizeRestoreData(data) {
|
||||
enabled: x.enabled !== false,
|
||||
created_at: optTs(x.created_at),
|
||||
updated_at: optTs(x.updated_at),
|
||||
})).filter(x => x.page && x.label);
|
||||
})).filter(x => x.kind !== 'item' || (x.page && x.label));
|
||||
const faceRefs = (data.student_face_refs || []).map(x => ({
|
||||
id: reqInt(x.id),
|
||||
student_id: reqInt(x.student_id),
|
||||
|
||||
+5
-3
@@ -733,14 +733,16 @@ CREATE INDEX IF NOT EXISTS idx_student_achievements_student ON student_achieveme
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sidebar_items (
|
||||
id SERIAL PRIMARY KEY,
|
||||
page TEXT NOT NULL UNIQUE,
|
||||
label TEXT NOT NULL,
|
||||
kind TEXT NOT NULL DEFAULT 'item',
|
||||
page TEXT UNIQUE,
|
||||
label TEXT NOT NULL DEFAULT '',
|
||||
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()
|
||||
updated_at TIMESTAMPTZ DEFAULT now(),
|
||||
CONSTRAINT sidebar_items_kind_check CHECK (kind IN ('item','divider','group'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_sidebar_items_section_order ON sidebar_items(section, sort_order, id);
|
||||
|
||||
+10
-3
@@ -991,14 +991,21 @@ INSERT INTO settings (key, value) VALUES ('feedback_imgbb_key','') ON CONFLICT (
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sidebar_items (
|
||||
id SERIAL PRIMARY KEY,
|
||||
page TEXT NOT NULL UNIQUE,
|
||||
label TEXT NOT NULL,
|
||||
kind TEXT NOT NULL DEFAULT 'item',
|
||||
page TEXT UNIQUE,
|
||||
label TEXT NOT NULL DEFAULT '',
|
||||
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()
|
||||
updated_at TIMESTAMPTZ DEFAULT now(),
|
||||
CONSTRAINT sidebar_items_kind_check CHECK (kind IN ('item','divider','group'))
|
||||
);
|
||||
ALTER TABLE sidebar_items ADD COLUMN IF NOT EXISTS kind TEXT NOT NULL DEFAULT 'item';
|
||||
ALTER TABLE sidebar_items ALTER COLUMN page DROP NOT NULL;
|
||||
ALTER TABLE sidebar_items ALTER COLUMN label SET DEFAULT '';
|
||||
ALTER TABLE sidebar_items DROP CONSTRAINT IF EXISTS sidebar_items_kind_check;
|
||||
ALTER TABLE sidebar_items ADD CONSTRAINT sidebar_items_kind_check CHECK (kind IN ('item','divider','group'));
|
||||
CREATE INDEX IF NOT EXISTS idx_sidebar_items_section_order ON sidebar_items(section, sort_order, id);
|
||||
|
||||
+35
-16
@@ -32,21 +32,28 @@ const DEFAULT_ITEMS = [
|
||||
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,
|
||||
kind TEXT NOT NULL DEFAULT 'item',
|
||||
page TEXT UNIQUE,
|
||||
label TEXT NOT NULL DEFAULT '',
|
||||
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()
|
||||
updated_at TIMESTAMPTZ DEFAULT now(),
|
||||
CONSTRAINT sidebar_items_kind_check CHECK (kind IN ('item','divider','group'))
|
||||
)`);
|
||||
await pool.query(`ALTER TABLE sidebar_items ADD COLUMN IF NOT EXISTS kind TEXT NOT NULL DEFAULT 'item'`);
|
||||
await pool.query(`ALTER TABLE sidebar_items ALTER COLUMN page DROP NOT NULL`);
|
||||
await pool.query(`ALTER TABLE sidebar_items ALTER COLUMN label SET DEFAULT ''`);
|
||||
await pool.query(`ALTER TABLE sidebar_items DROP CONSTRAINT IF EXISTS sidebar_items_kind_check`);
|
||||
await pool.query(`ALTER TABLE sidebar_items ADD CONSTRAINT sidebar_items_kind_check CHECK (kind IN ('item','divider','group'))`);
|
||||
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`,
|
||||
`INSERT INTO sidebar_items (kind, page, label, icon, section, sort_order, tutor_visible, enabled)
|
||||
VALUES ('item',$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]
|
||||
);
|
||||
}
|
||||
@@ -54,7 +61,7 @@ async function ensureSidebarItemsTable(pool) {
|
||||
|
||||
async function listSidebarItems(pool) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, page, label, icon, section, sort_order, tutor_visible, enabled, updated_at
|
||||
`SELECT id, kind, 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;
|
||||
@@ -63,22 +70,34 @@ async function listSidebarItems(pool) {
|
||||
function normalizeSidebarPayload(input) {
|
||||
if (!Array.isArray(input)) throw new Error('items must be array');
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
const seenPages = 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 kind = ['item','divider','group'].includes(raw.kind) ? raw.kind : 'item';
|
||||
const id = Number.isFinite(Number(raw.id)) ? Math.trunc(Number(raw.id)) : null;
|
||||
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 });
|
||||
|
||||
if (kind === 'item') {
|
||||
const page = String(raw.page || '').trim();
|
||||
if (!page || page.length > 64) throw new Error('bad page');
|
||||
if (seenPages.has(page)) throw new Error('duplicate page');
|
||||
seenPages.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');
|
||||
out.push({ id, kind, page, label, icon, section, sort_order, tutor_visible, enabled });
|
||||
} else {
|
||||
const label = String(raw.label || '').trim();
|
||||
if (kind === 'group' && (!label || label.length > 64)) throw new Error('bad label');
|
||||
if (label.length > 64) throw new Error('bad label');
|
||||
const icon = String(raw.icon || 'circle').trim() || 'circle';
|
||||
if (icon.length > 64) throw new Error('bad icon');
|
||||
out.push({ id, kind, page: null, label, icon, section, sort_order, tutor_visible, enabled });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b
|
||||
.sidebar nav{display:flex;flex-direction:column;gap:10px;padding:0 8px}
|
||||
.nav-group{display:flex;flex-direction:column;gap:2px}
|
||||
.nav-group-title{font-size:.66rem;font-weight:700;text-transform:uppercase;letter-spacing:.06em;color:var(--muted);padding:6px 10px 4px;user-select:none;opacity:.8}
|
||||
.nav-divider{height:1px;background:var(--border);margin:6px 10px;opacity:.7}
|
||||
.nav-items{display:flex;flex-direction:column;gap:1px}
|
||||
|
||||
.sidebar nav a{display:flex;align-items:center;gap:10px;padding:7px 10px;border-radius:8px;color:var(--muted);text-decoration:none;font-size:.84rem;font-weight:500;line-height:1.3;transition:all .14s ease;position:relative}
|
||||
|
||||
+3
-1
@@ -117,13 +117,15 @@ function buildSidebar(active) {
|
||||
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' });
|
||||
const toNav = (i) => ({ page: i.page, label: i.label, icon: i.icon, kind: i.kind || 'item', 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 => {
|
||||
if (n.kind === 'divider') return `<div class="nav-divider"></div>`;
|
||||
if (n.kind === 'group') return `<div class="nav-group-title">${esc(n.label)}</div>`;
|
||||
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>` : '';
|
||||
|
||||
+112
-26
@@ -1,49 +1,65 @@
|
||||
let sidebarItems = [];
|
||||
let cidCounter = 0;
|
||||
function newCid() { return 'c' + (++cidCounter); }
|
||||
|
||||
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 }));
|
||||
sidebarItems = (data.items || []).map(x => ({ ...x, _cid: newCid() }));
|
||||
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);
|
||||
const base = sidebarItems.filter(x => x.section === 'base').sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0) || String(a._cid).localeCompare(b._cid));
|
||||
const admin = sidebarItems.filter(x => x.section === 'admin').sort((a, b) => (a.sort_order || 0) - (b.sort_order || 0) || String(a._cid).localeCompare(b._cid));
|
||||
document.getElementById('sidebarBaseList').innerHTML = base.map(renderSidebarItem).join('');
|
||||
document.getElementById('sidebarAdminList').innerHTML = admin.map(renderSidebarItem).join('');
|
||||
renderIcons();
|
||||
bindSidebarDrag();
|
||||
bindSidebarLabels();
|
||||
bindSidebarDeletes();
|
||||
ensureInsertButtons();
|
||||
}
|
||||
|
||||
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 handle = `<span class="sidebar-item-handle" draggable="true" data-drag="${esc(it._cid)}" title="Перетащить"><i data-lucide="grip-vertical"></i></span>`;
|
||||
let iconHtml = '';
|
||||
let labelHtml = '';
|
||||
if (it.kind === 'divider') {
|
||||
iconHtml = `<span class="sidebar-item-icon"><i data-lucide="minus"></i></span>`;
|
||||
labelHtml = `<input class="sidebar-item-label-input" data-label="${esc(it._cid)}" type="text" value="${esc(it.label || '')}" placeholder="Разделитель (подпись необязательна)">`;
|
||||
} else if (it.kind === 'group') {
|
||||
iconHtml = `<span class="sidebar-item-icon"><i data-lucide="folder"></i></span>`;
|
||||
labelHtml = `<input class="sidebar-item-label-input" data-label="${esc(it._cid)}" type="text" value="${esc(it.label || '')}" placeholder="Название группы">`;
|
||||
} else {
|
||||
iconHtml = `<span class="sidebar-item-icon"><i data-lucide="${esc(it.icon)}"></i></span>`;
|
||||
labelHtml = `<div class="sidebar-item-label">${esc(it.label)}<small>${esc(it.page)}</small></div>`;
|
||||
}
|
||||
const tutorToggle = (it.section === 'base' && it.kind === 'item')
|
||||
? `<label class="toggle"><input type="checkbox" data-tutor="${esc(it._cid)}" ${it.tutor_visible ? 'checked' : ''} ${disabled ? 'disabled' : ''}><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><b>Доступно тьюторам</b></span></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)}">
|
||||
let enabledToggle = '';
|
||||
if (it.kind === 'item' && it.page === 'sidebar') {
|
||||
enabledToggle = `<label class="toggle"><input type="checkbox" data-enabled="${esc(it._cid)}" checked disabled><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><b>Включён</b></span></label>`;
|
||||
} else {
|
||||
enabledToggle = `<label class="toggle"><input type="checkbox" data-enabled="${esc(it._cid)}" ${it.enabled !== false ? 'checked' : ''}><span class="toggle-track"><span class="toggle-thumb"></span></span><span class="toggle-text"><b>Включён</b></span></label>`;
|
||||
}
|
||||
return `<div class="sidebar-item ${disabled ? 'disabled' : ''}" data-cid="${esc(it._cid)}" data-kind="${esc(it.kind)}" data-section="${esc(it.section)}" data-id="${it.id || ''}">
|
||||
${handle}
|
||||
${icon}
|
||||
<div class="sidebar-item-label">
|
||||
${esc(it.label)}
|
||||
<small>${esc(it.page)}</small>
|
||||
</div>
|
||||
${iconHtml}
|
||||
${labelHtml}
|
||||
<div class="sidebar-item-controls">
|
||||
${tutorToggle}
|
||||
${enabledToggle}
|
||||
<span class="sidebar-status ${statusCls}">${statusText}</span>
|
||||
${it.kind !== 'item' ? `<button type="button" class="icon-btn danger" data-del="${esc(it._cid)}" title="Удалить"><i data-lucide="trash-2"></i></button>` : ''}
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
@@ -56,7 +72,7 @@ function bindSidebarDrag() {
|
||||
const handle = item.querySelector('.sidebar-item-handle');
|
||||
if (!handle) return;
|
||||
handle.addEventListener('dragstart', e => {
|
||||
e.dataTransfer.setData('text/plain', item.dataset.page);
|
||||
e.dataTransfer.setData('text/plain', item.dataset.cid);
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
item.classList.add('dragging');
|
||||
});
|
||||
@@ -75,19 +91,78 @@ function bindSidebarDrag() {
|
||||
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);
|
||||
const it = sidebarItems.find(x => x._cid === 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;
|
||||
const it = sidebarItems.find(x => x._cid === cb.dataset.enabled);
|
||||
if (!it) return;
|
||||
if (it.page === 'sidebar') return;
|
||||
it.enabled = cb.checked;
|
||||
renderSidebarSettings();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function bindSidebarLabels() {
|
||||
document.querySelectorAll('[data-label]').forEach(inp => {
|
||||
inp.addEventListener('input', () => {
|
||||
const it = sidebarItems.find(x => x._cid === inp.dataset.label);
|
||||
if (it) it.label = inp.value;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function ensureInsertButtons() {
|
||||
['sidebarBaseList', 'sidebarAdminList'].forEach(id => {
|
||||
const list = document.getElementById(id);
|
||||
if (!list) return;
|
||||
const card = list.parentElement;
|
||||
if (card.querySelector('.sidebar-add-row')) return;
|
||||
const section = id === 'sidebarBaseList' ? 'base' : 'admin';
|
||||
const row = document.createElement('div');
|
||||
row.className = 'sidebar-add-row';
|
||||
row.style.cssText = 'display:flex;gap:8px;margin-top:8px;';
|
||||
row.innerHTML = `<button type="button" class="btn-secondary" data-add="divider" data-section="${section}">+ Разделитель</button><button type="button" class="btn-secondary" data-add="group" data-section="${section}">+ Группа</button>`;
|
||||
card.appendChild(row);
|
||||
});
|
||||
}
|
||||
|
||||
function bindSidebarInserts() {
|
||||
document.querySelectorAll('[data-add]').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
const kind = btn.dataset.add;
|
||||
const section = btn.dataset.section;
|
||||
const siblings = sidebarItems.filter(x => x.section === section);
|
||||
const maxOrder = siblings.reduce((m, x) => Math.max(m, x.sort_order || 0), 0);
|
||||
const item = {
|
||||
id: null,
|
||||
_cid: newCid(),
|
||||
kind,
|
||||
page: null,
|
||||
label: kind === 'group' ? 'Новая группа' : '',
|
||||
icon: kind === 'divider' ? 'minus' : 'folder',
|
||||
section,
|
||||
sort_order: maxOrder + 10,
|
||||
tutor_visible: true,
|
||||
enabled: true,
|
||||
};
|
||||
sidebarItems.push(item);
|
||||
renderSidebarSettings();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function bindSidebarDeletes() {
|
||||
document.querySelectorAll('[data-del]').forEach(btn => {
|
||||
btn.addEventListener('click', () => {
|
||||
const cid = btn.dataset.del;
|
||||
sidebarItems = sidebarItems.filter(x => x._cid !== cid);
|
||||
renderSidebarSettings();
|
||||
});
|
||||
});
|
||||
@@ -109,13 +184,12 @@ function getDragAfterElement(container, y) {
|
||||
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);
|
||||
const it = sidebarItems.find(x => x._cid === el.dataset.cid);
|
||||
if (it) {
|
||||
it.sort_order = (idx + 1) * 10;
|
||||
ordered.push(it);
|
||||
@@ -124,10 +198,21 @@ async function saveSidebarSettings() {
|
||||
});
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const payload = ordered.map(it => ({
|
||||
id: it.id || undefined,
|
||||
kind: it.kind,
|
||||
page: it.page,
|
||||
label: it.label,
|
||||
icon: it.icon,
|
||||
section: it.section,
|
||||
sort_order: it.sort_order,
|
||||
tutor_visible: it.tutor_visible,
|
||||
enabled: it.enabled,
|
||||
}));
|
||||
const res = await fetch(`${API}/api/sidebar`, {
|
||||
method: 'PUT',
|
||||
headers: hdrJson(),
|
||||
body: JSON.stringify({ items: ordered }),
|
||||
body: JSON.stringify({ items: payload }),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const d = await res.json().catch(() => ({}));
|
||||
@@ -153,5 +238,6 @@ async function saveSidebarSettings() {
|
||||
document.getElementById('sidebarSaveHint').textContent = 'Не удалось загрузить меню';
|
||||
}
|
||||
document.getElementById('sidebarSaveBtn').addEventListener('click', saveSidebarSettings);
|
||||
bindSidebarInserts();
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -32,6 +32,18 @@
|
||||
}
|
||||
.sidebar-settings-warn i { flex: none; margin-top: 2px; }
|
||||
.sidebar-items { display: flex; flex-direction: column; gap: 6px; }
|
||||
.sidebar-item .icon-btn.danger { color: #ef4444; }
|
||||
.sidebar-item .icon-btn.danger:hover { color: #dc2626; border-color: #ef4444; }
|
||||
.sidebar-item-label-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-size: .85rem;
|
||||
}
|
||||
.sidebar-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -6020,6 +6020,8 @@ app.get('/api/sidebar', requireAuth, async (req, res) => {
|
||||
out = items.filter(i => i.section === 'base' && i.enabled && i.tutor_visible);
|
||||
}
|
||||
out = out.map(i => ({
|
||||
id: i.id,
|
||||
kind: i.kind || 'item',
|
||||
page: i.page,
|
||||
label: i.label,
|
||||
icon: i.icon,
|
||||
@@ -6042,12 +6044,30 @@ app.put('/api/sidebar', requireAdmin, async (req, res) => {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const existing = await client.query('SELECT id FROM sidebar_items');
|
||||
const existingIds = new Set(existing.rows.map(r => r.id));
|
||||
const submittedIds = [];
|
||||
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]
|
||||
);
|
||||
if (it.id && existingIds.has(it.id)) {
|
||||
await client.query(
|
||||
`UPDATE sidebar_items SET kind=$1, page=$2, label=$3, icon=$4, section=$5, sort_order=$6, tutor_visible=$7, enabled=$8, updated_at=now()
|
||||
WHERE id=$9`,
|
||||
[it.kind, it.page, it.label, it.icon, it.section, it.sort_order, it.tutor_visible, it.enabled, it.id]
|
||||
);
|
||||
submittedIds.push(it.id);
|
||||
} else {
|
||||
const ins = await client.query(
|
||||
`INSERT INTO sidebar_items (kind, page, label, icon, section, sort_order, tutor_visible, enabled)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8) RETURNING id`,
|
||||
[it.kind, it.page, it.label, it.icon, it.section, it.sort_order, it.tutor_visible, it.enabled]
|
||||
);
|
||||
submittedIds.push(ins.rows[0].id);
|
||||
}
|
||||
}
|
||||
if (submittedIds.length) {
|
||||
await client.query('DELETE FROM sidebar_items WHERE NOT (id = ANY($1::int[]))', [submittedIds]);
|
||||
} else {
|
||||
await client.query('DELETE FROM sidebar_items');
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
} catch (e) {
|
||||
@@ -7195,8 +7215,8 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
}
|
||||
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]
|
||||
'INSERT INTO sidebar_items (id, kind, page, label, icon, section, sort_order, tutor_visible, enabled, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)',
|
||||
[x.id, x.kind || 'item', 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 || [])) {
|
||||
|
||||
Reference in New Issue
Block a user