diff --git a/backup-restore.js b/backup-restore.js index 9867a17..7c09810 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', 'doc_sections', 'doc_articles', 'doc_images', + 'student_work_marks', 'achievement_types', 'student_achievements', 'doc_sections', 'doc_articles', 'doc_images', ]; 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', 'doc_sections', 'doc_articles', 'doc_images', + 'student_work_marks', 'achievement_types', 'student_achievements', 'doc_sections', 'doc_articles', 'doc_images', ]; function isSupportedBackupVersion(data) { @@ -623,6 +623,25 @@ function normalizeRestoreData(data) { created_at: optTs(x.created_at), updated_at: optTs(x.updated_at), })); + const achievementTypes = (data.achievement_types || []).map(x => ({ + id: reqInt(x.id), + name: optText(x.name, 150) || '', + sort_order: optInt(x.sort_order, -10000000, 10000000) ?? 0, + is_active: x.is_active !== false, + created_at: optTs(x.created_at), + updated_at: optTs(x.updated_at), + })).filter(x => x.name); + const studentAchievements = (data.student_achievements || []).map(x => ({ + id: reqInt(x.id), + student_id: reqInt(x.student_id), + type_name: optText(x.type_name, 150) || '', + value: optText(x.value, 200) || '', + achieved_at: optDate(x.achieved_at), + note: optText(x.note, 800) || '', + author_id: x.author_id == null ? null : reqInt(x.author_id), + created_at: optTs(x.created_at), + updated_at: optTs(x.updated_at), + })).filter(x => x.student_id); const docSections = (data.doc_sections || []).map(x => ({ id: reqInt(x.id), parent_id: x.parent_id == null ? null : reqInt(x.parent_id), @@ -693,7 +712,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, student_face_refs: faceRefs, photo_faces: faceRows, student_work_marks, doc_sections: docSections, doc_articles: docArticles, doc_images: docImages }; + 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 }; } module.exports = { diff --git a/db/init.sql b/db/init.sql index 3733034..74ac455 100644 --- a/db/init.sql +++ b/db/init.sql @@ -684,3 +684,27 @@ INSERT INTO settings (key, value) VALUES ('face_scan_on_upload', 'true') ON CONF INSERT INTO settings (key, value) VALUES ('notify_face_scan_done', 'false') ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('notify_face_recognized', 'true') ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('notify_face_scan_error', 'true') ON CONFLICT (key) DO NOTHING; + +CREATE TABLE IF NOT EXISTS achievement_types ( + id SERIAL PRIMARY KEY, + name VARCHAR(150) NOT NULL, + sort_order INT NOT NULL DEFAULT 0, + is_active BOOLEAN NOT NULL DEFAULT true, + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); +CREATE UNIQUE INDEX IF NOT EXISTS idx_achievement_types_name ON achievement_types(lower(name)); +CREATE INDEX IF NOT EXISTS idx_achievement_types_order ON achievement_types(sort_order, id); + +CREATE TABLE IF NOT EXISTS student_achievements ( + id SERIAL PRIMARY KEY, + student_id INT NOT NULL REFERENCES students(id) ON DELETE CASCADE, + type_name VARCHAR(150) NOT NULL, + value VARCHAR(200) NOT NULL DEFAULT '', + achieved_at DATE, + note TEXT NOT NULL DEFAULT '', + author_id INT REFERENCES users(id) ON DELETE SET NULL, + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); +CREATE INDEX IF NOT EXISTS idx_student_achievements_student ON student_achievements(student_id); diff --git a/db/migration.sql b/db/migration.sql index 4d5d63e..f57ecfc 100644 --- a/db/migration.sql +++ b/db/migration.sql @@ -921,3 +921,27 @@ CREATE TABLE IF NOT EXISTS doc_images ( CREATE INDEX IF NOT EXISTS idx_doc_images_article ON doc_images(article_id); CREATE INDEX IF NOT EXISTS idx_doc_images_path ON doc_images(path); +CREATE TABLE IF NOT EXISTS achievement_types ( + id SERIAL PRIMARY KEY, + name VARCHAR(150) NOT NULL, + sort_order INT NOT NULL DEFAULT 0, + is_active BOOLEAN NOT NULL DEFAULT true, + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); +CREATE UNIQUE INDEX IF NOT EXISTS idx_achievement_types_name ON achievement_types(lower(name)); +CREATE INDEX IF NOT EXISTS idx_achievement_types_order ON achievement_types(sort_order, id); + +CREATE TABLE IF NOT EXISTS student_achievements ( + id SERIAL PRIMARY KEY, + student_id INT NOT NULL REFERENCES students(id) ON DELETE CASCADE, + type_name VARCHAR(150) NOT NULL, + value VARCHAR(200) NOT NULL DEFAULT '', + achieved_at DATE, + note TEXT NOT NULL DEFAULT '', + author_id INT REFERENCES users(id) ON DELETE SET NULL, + created_at TIMESTAMPTZ DEFAULT now(), + updated_at TIMESTAMPTZ DEFAULT now() +); +CREATE INDEX IF NOT EXISTS idx_student_achievements_student ON student_achievements(student_id); + diff --git a/lib/achievements.js b/lib/achievements.js new file mode 100644 index 0000000..9559c47 --- /dev/null +++ b/lib/achievements.js @@ -0,0 +1,181 @@ +const { reqStr, optText, optDate } = require('../backup-restore'); + +const ACH_TYPE_NAME_MAX = 150; +const ACH_VALUE_MAX = 200; +const ACH_NOTE_MAX = 800; +const ACH_TYPES_LIMIT = 200; +const ACH_LIST_LIMIT = 200; + +function httpError(status, message) { + const err = new Error(message); + err.status = status; + return err; +} + +function achError(res, e, fallback, label) { + if (e && e.status) return res.status(e.status).json({ error: e.message }); + if (e && e.code === '23505') return res.status(400).json({ error: 'Такой тип уже есть' }); + if (e && (e.message === 'Invalid string' || e.message === 'Invalid string length' || e.message === 'Invalid integer' || e.message === 'Invalid date')) { + return res.status(400).json({ error: 'Неверные данные' }); + } + console.error(`${label}:`, e); + return res.status(500).json({ error: fallback }); +} + +function normAchDate(v) { + if (v === null || v === undefined || v === '') return null; + return optDate(v); +} + +function achRecordFields(body) { + return { + typeName: reqStr(body?.type_name, ACH_TYPE_NAME_MAX), + value: optText(body?.value, ACH_VALUE_MAX), + achievedAt: normAchDate(body?.achieved_at), + note: optText(body?.note, ACH_NOTE_MAX), + }; +} + +function achFieldsError(e) { + return e.message === 'Invalid date' ? 'Некорректная дата достижения' : 'Неверные данные достижения'; +} + +async function listTypes(pool) { + const { rows } = await pool.query( + 'SELECT id, name, sort_order, is_active, created_at, updated_at FROM achievement_types ORDER BY sort_order ASC, id ASC' + ); + return rows; +} + +async function listActiveTypes(pool) { + const { rows } = await pool.query( + 'SELECT id, name FROM achievement_types WHERE is_active = true ORDER BY sort_order ASC, id ASC LIMIT $1', + [ACH_TYPES_LIMIT] + ); + return rows; +} + +async function createType(pool, name) { + const dup = await pool.query('SELECT 1 FROM achievement_types WHERE lower(name) = lower($1) LIMIT 1', [name]); + if (dup.rows.length) throw httpError(400, 'Такой тип уже есть'); + const { rows } = await pool.query( + `INSERT INTO achievement_types (name, sort_order) + VALUES ($1, COALESCE((SELECT MIN(sort_order) FROM achievement_types), 1) - 1) + RETURNING id, name, sort_order, is_active, created_at, updated_at`, + [name] + ); + return rows[0]; +} + +async function updateType(pool, id, name, isActive) { + const prev = await pool.query('SELECT name, is_active FROM achievement_types WHERE id = $1', [id]); + if (!prev.rows.length) throw httpError(404, 'Тип не найден'); + const oldName = prev.rows[0].name; + const effectiveActive = typeof isActive === 'boolean' ? isActive : prev.rows[0].is_active === true; + const dup = await pool.query('SELECT 1 FROM achievement_types WHERE lower(name) = lower($1) AND id <> $2 LIMIT 1', [name, id]); + if (dup.rows.length) throw httpError(400, 'Такой тип уже есть'); + const { rows } = await pool.query( + `UPDATE achievement_types SET name = $1, is_active = $2, updated_at = now() + WHERE id = $3 + RETURNING id, name, sort_order, is_active, created_at, updated_at`, + [name, effectiveActive, id] + ); + let renamed = 0; + if (oldName !== name) { + const up = await pool.query('UPDATE student_achievements SET type_name = $1, updated_at = now() WHERE type_name = $2', [name, oldName]); + renamed = up.rowCount; + } + return { item: rows[0], renamed }; +} + +async function deleteType(pool, id) { + const { rows } = await pool.query('DELETE FROM achievement_types WHERE id = $1 RETURNING name', [id]); + if (!rows.length) throw httpError(404, 'Тип не найден'); + return rows[0]; +} + +async function reorderTypes(pool, ids) { + const client = await pool.connect(); + try { + await client.query('BEGIN'); + for (let i = 0; i < ids.length; i++) { + const { rowCount } = await client.query('UPDATE achievement_types SET sort_order = $1 WHERE id = $2', [i + 1, ids[i]]); + if (!rowCount) throw httpError(404, 'Тип не найден'); + } + await client.query('COMMIT'); + } catch (e) { + await client.query('ROLLBACK'); + throw e; + } finally { + client.release(); + } +} + +const ACH_ITEM_COLS = 'id, student_id, type_name, value, achieved_at, note, author_id, created_at, updated_at'; + +async function listForStudent(pool, studentId) { + const { rows } = await pool.query( + `SELECT ${ACH_ITEM_COLS}, count(*) OVER () AS total + FROM student_achievements + WHERE student_id = $1 + ORDER BY achieved_at DESC NULLS LAST, id DESC + LIMIT $2`, + [studentId, ACH_LIST_LIMIT] + ); + const total = rows.length ? Number(rows[0].total) : 0; + const items = rows.map(({ total: _t, ...rest }) => rest); + return { items, total }; +} + +async function createRecord(pool, { studentId, typeName, value, achievedAt, note, authorId }) { + const { rows } = await pool.query( + `INSERT INTO student_achievements (student_id, type_name, value, achieved_at, note, author_id) + VALUES ($1, $2, $3, $4, $5, $6) + RETURNING ${ACH_ITEM_COLS}`, + [studentId, typeName, value, achievedAt, note, authorId] + ); + return rows[0]; +} + +async function updateRecord(pool, studentId, achId, { typeName, value, achievedAt, note }) { + const { rows } = await pool.query( + `UPDATE student_achievements + SET type_name = $2, value = $3, achieved_at = $4, note = $5, updated_at = now() + WHERE id = $6 AND student_id = $1 + RETURNING ${ACH_ITEM_COLS}`, + [studentId, typeName, value, achievedAt, note, achId] + ); + if (!rows.length) throw httpError(404, 'Достижение не найдено'); + return rows[0]; +} + +async function deleteRecord(pool, studentId, achId) { + const { rows } = await pool.query( + `DELETE FROM student_achievements WHERE id = $2 AND student_id = $1 RETURNING ${ACH_ITEM_COLS}`, + [studentId, achId] + ); + if (!rows.length) throw httpError(404, 'Достижение не найдено'); + return rows[0]; +} + +module.exports = { + ACH_TYPE_NAME_MAX, + ACH_VALUE_MAX, + ACH_NOTE_MAX, + ACH_TYPES_LIMIT, + ACH_LIST_LIMIT, + achError, + normAchDate, + achRecordFields, + achFieldsError, + listTypes, + listActiveTypes, + createType, + updateType, + deleteType, + reorderTypes, + listForStudent, + createRecord, + updateRecord, + deleteRecord, +}; diff --git a/public/admin.css b/public/admin.css index cdbcd6b..2c6f1b2 100644 --- a/public/admin.css +++ b/public/admin.css @@ -554,6 +554,22 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b .attach-name{font-size:.84rem;font-weight:600;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} .attach-sub{margin-left:auto;flex:0 0 auto;max-width:45%;font-size:.72rem;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +/* --- Достижения ученика (#profileDataModal) --- */ +.pf-ach-form{display:grid;gap:10px;grid-template-columns:repeat(12,minmax(0,1fr));background:var(--bg);border:1px solid var(--border);border-radius:12px;padding:12px} +.pf-ach-form[hidden]{display:none} +.pf-ach-form .pf-f:nth-child(1){grid-column:span 4} +.pf-ach-actions{grid-column:span 12;display:flex;gap:8px;justify-content:flex-end} +.pf-ach-row{display:flex;gap:10px;align-items:flex-start;background:var(--bg);border:1px solid var(--border);border-radius:12px;padding:10px 12px} +.pf-ach-main{flex:1;min-width:0;display:flex;flex-direction:column;gap:5px} +.pf-ach-top{display:flex;align-items:center;gap:8px;flex-wrap:wrap} +.pf-ach-type{display:inline-flex;font-size:.72rem;font-weight:700;padding:3px 10px;border-radius:999px;background:rgba(37,99,235,.08);border:1px solid rgba(37,99,235,.2);color:var(--accent)} +.pf-ach-value{font-size:.88rem;overflow-wrap:anywhere} +.pf-ach-when{margin-left:auto;font-size:.74rem;color:var(--muted)} +.pf-ach-note{font-size:.8rem;color:var(--muted);white-space:pre-wrap;overflow-wrap:anywhere} +.pf-ach-acts{display:flex;gap:2px;flex-shrink:0} +.pf-ach-empty{color:var(--muted);font-size:.84rem;padding:4px 2px} +@media(max-width:820px){.pf-ach-form .pf-f:nth-child(1){grid-column:span 12}} + /* --- Фото группы (хронология) --- */ .group-cover{width:100%;aspect-ratio:16/9;object-fit:cover;border-radius:10px;display:block;background:var(--bg)} .group-cover:hover{opacity:.9} diff --git a/public/js/settings.js b/public/js/settings.js index be86150..fcad20e 100644 --- a/public/js/settings.js +++ b/public/js/settings.js @@ -1,6 +1,6 @@ const DIRTY_FIELDS = ['systemName', 'timezone', 'timeFormat', 'spamInterval', 'footerLeft', 'footerRight', 'aiPrompt', 'aiAutoCheck', 'lessonAiPrompt', 'lessonAiEnabled', 'notesAiEnabled', 'shareShowMessage', 'shareShowDate', 'shareShowNames', 'shareShowPhotos', 'cookieNoticeText', 'photoResolution', 'photoQuality', 'photoEngine', 'camEnabled', 'photoAiFaceMode', 'photoAiFaceModel', 'photoAiDevicePref', 'trashPurgeDays', 'notifyEnabled', 'notifyRetentionDays']; const NOTIFY_IDS = []; -const SECTION_IDS = ['sec-system', 'sec-stack', 'sec-brand', 'sec-datetime', 'sec-antispam', 'sec-share', 'sec-ai', 'sec-lesson-ai', 'sec-notes-ai', 'sec-tls', 'sec-backup', 'sec-trash', 'sec-form', 'sec-notify', 'sec-photo', 'sec-photo-ai', 'sec-bans']; +const SECTION_IDS = ['sec-system', 'sec-stack', 'sec-brand', 'sec-datetime', 'sec-antispam', 'sec-share', 'sec-ai', 'sec-lesson-ai', 'sec-notes-ai', 'sec-achievements', 'sec-tls', 'sec-backup', 'sec-trash', 'sec-form', 'sec-notify', 'sec-photo', 'sec-photo-ai', 'sec-bans']; const SPAM_MAX = 10080; const BAN_REASONS = { 'honeypot': 'Антиспам-поле', @@ -1479,6 +1479,165 @@ window.addEventListener('beforeunload', e => { } }); +let seAchTypes = []; + +function seAchRowHtml(t) { + return `
Каталог типов персональных достижений учеников: скорость печати, результаты олимпиад и т.п. Тип выбирается при добавлении достижения — на странице ученика (вкладка «Достижения») или в профиле. Переименование типа обновляет уже внесённые записи; при удалении типа записи сохраняют его название. Выключенный тип не предлагается для новых достижений.
+ +Персональные результаты: скорость печати, олимпиады и т.п. Типы задаёт администратор в настройках.
+