Files
WhatIDo/lib/sidebar.js
T
dev 7c9c6ef116 Тесты и опросы: модуль тестов, анонимные опросы, страницы и бэкап
- lib/quizzes.js: таблицы quizzes*, CRUD, привязка медиа, подсчёт баллов, попытки, статистика, purge и уборка ассетов
- server.js: роуты CRUD/прохождения/статистики, отдача медиа, публичные роуты анонимного опроса, sweep и restore
- db/init.sql + db/migration.sql: схема шести таблиц, индексы и идемпотентные ALTER/CHECK
- backup-restore.js: нормализация и списки таблиц, покрытие в backup.selftest.js
- страницы quizzes/quiz-edit/quiz/quiz-public и публичный опрос без входа, пункт сайдбара «Тесты и опросы»
- quiz.selftest.js: юнит-проверки подсчёта баллов и нормализации ответов
- AGENTS.md: раздел 3t и File Map
2026-12-01 19:00:06 +03:00

114 lines
8.0 KiB
JavaScript

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: 'calendar', label: 'Календарь', icon: 'calendar-days', section: 'base', sort_order: 35, tutor_visible: true, enabled: true },
{ page: 'quizzes', label: 'Тесты и опросы', icon: 'clipboard-list', section: 'base', sort_order: 37, 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: 'digest', label: 'Дайджест', icon: 'newspaper', section: 'base', sort_order: 95, 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,
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(),
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 (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]
);
}
}
async function listSidebarItems(pool) {
const { rows } = await pool.query(
`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;
}
function normalizeSidebarPayload(input) {
if (!Array.isArray(input)) throw new Error('items must be array');
const out = [];
const seenPages = new Set();
for (const raw of input) {
if (!raw || typeof raw !== 'object') throw new Error('bad item');
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');
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;
}
module.exports = {
DEFAULT_ITEMS,
ensureSidebarItemsTable,
listSidebarItems,
normalizeSidebarPayload,
};