feat: student achievements (admin-managed types + per-student records, UI & backup)
This commit is contained in:
+22
-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', '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 = {
|
||||
|
||||
+24
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
@@ -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}
|
||||
|
||||
+161
-1
@@ -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 `<div class="se-ach-row${t.is_active ? '' : ' is-off'}" data-id="${t.id}">
|
||||
<span class="se-ach-drag" draggable="true" title="Перетащите, чтобы изменить порядок">⠿</span>
|
||||
<button type="button" class="se-ach-on${t.is_active ? ' on' : ''}" data-ach-on title="${t.is_active ? 'Скрыть из выбора при добавлении' : 'Вернуть в выбор'}">${t.is_active ? 'Вкл' : 'Выкл'}</button>
|
||||
<span class="se-ach-name">${esc(t.name)}</span>
|
||||
<button type="button" class="se-ach-btn" data-ach-edit title="Переименовать"><i data-lucide="pencil"></i></button>
|
||||
<button type="button" class="se-ach-btn danger" data-ach-del title="Удалить"><i data-lucide="trash-2"></i></button>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function seAchRender() {
|
||||
const list = document.getElementById('seAchList');
|
||||
if (!list) return;
|
||||
list.innerHTML = seAchTypes.length ? seAchTypes.map(seAchRowHtml).join('') : '<div class="se-ach-empty">Типов пока нет — добавьте первый выше</div>';
|
||||
renderIcons();
|
||||
}
|
||||
|
||||
function seAchApi(url, body, method) {
|
||||
return fetch(url, {
|
||||
method: method || (body ? 'POST' : 'GET'),
|
||||
headers: body ? { ...hdr(), 'Content-Type': 'application/json' } : hdr(),
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
}).then(res => res.json().then(data => {
|
||||
if (!res.ok) throw new Error(data.error || 'Ошибка');
|
||||
return data;
|
||||
}));
|
||||
}
|
||||
|
||||
async function seAchLoad() {
|
||||
try {
|
||||
const data = await seAchApi(`${API}/api/achievement-types`);
|
||||
seAchTypes = Array.isArray(data.items) ? data.items : [];
|
||||
} catch {
|
||||
seAchTypes = [];
|
||||
}
|
||||
seAchRender();
|
||||
}
|
||||
|
||||
async function seAchPersistOrder(ids) {
|
||||
const oldIds = seAchTypes.map(t => t.id);
|
||||
if (oldIds.join() === ids.join()) { seAchRender(); return; }
|
||||
try {
|
||||
await seAchApi(`${API}/api/achievement-types/reorder`, { ids }, 'PUT');
|
||||
seAchTypes.sort((a, b) => ids.indexOf(a.id) - ids.indexOf(b.id));
|
||||
seAchRender();
|
||||
} catch (err) {
|
||||
showToast(err.message || 'Не удалось сохранить порядок', true);
|
||||
await seAchLoad();
|
||||
}
|
||||
}
|
||||
|
||||
async function initAchievementTypes() {
|
||||
if (!document.getElementById('seAchList')) return;
|
||||
const box = document.getElementById('seAchList');
|
||||
let seAchDragged = null;
|
||||
box.addEventListener('dragstart', e => {
|
||||
const row = e.target.closest('.se-ach-row');
|
||||
if (!row) return;
|
||||
seAchDragged = row;
|
||||
e.dataTransfer.effectAllowed = 'move';
|
||||
try { e.dataTransfer.setData('text/plain', row.dataset.id); } catch {}
|
||||
});
|
||||
box.addEventListener('dragover', e => {
|
||||
if (!seAchDragged) return;
|
||||
e.preventDefault();
|
||||
const row = e.target.closest('.se-ach-row');
|
||||
if (!row || row === seAchDragged) return;
|
||||
const rect = row.getBoundingClientRect();
|
||||
box.insertBefore(seAchDragged, e.clientY < rect.top + rect.height / 2 ? row : row.nextSibling);
|
||||
});
|
||||
box.addEventListener('drop', e => e.preventDefault());
|
||||
box.addEventListener('dragend', () => {
|
||||
if (!seAchDragged) return;
|
||||
const ids = [...box.querySelectorAll('.se-ach-row')].map(r => Number(r.dataset.id));
|
||||
seAchDragged = null;
|
||||
seAchPersistOrder(ids);
|
||||
});
|
||||
box.addEventListener('click', async e => {
|
||||
const row = e.target.closest('.se-ach-row');
|
||||
if (!row) return;
|
||||
const cur = seAchTypes.find(t => String(t.id) === String(row.dataset.id));
|
||||
if (!cur) return;
|
||||
const editBtn = e.target.closest('[data-ach-edit]');
|
||||
if (editBtn) {
|
||||
const nameEl = row.querySelector('.se-ach-name');
|
||||
const input = document.createElement('input');
|
||||
input.className = 'se-ach-name-input';
|
||||
input.value = cur.name;
|
||||
input.maxLength = 150;
|
||||
nameEl.replaceWith(input);
|
||||
input.focus();
|
||||
input.select();
|
||||
let done = false;
|
||||
const finish = save => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
const val = input.value.trim();
|
||||
if (!save || !val || val === cur.name) { seAchRender(); return; }
|
||||
seAchApi(`${API}/api/achievement-types/${cur.id}`, { name: val, is_active: cur.is_active }, 'PUT')
|
||||
.then(data => { cur.name = data.item.name; cur.is_active = data.item.is_active; showToast('Тип переименован'); seAchRender(); })
|
||||
.catch(err => { showToast(err.message || 'Не удалось переименовать', true); seAchRender(); });
|
||||
};
|
||||
input.addEventListener('keydown', ev => {
|
||||
if (ev.key === 'Enter') { ev.preventDefault(); finish(true); }
|
||||
if (ev.key === 'Escape') { ev.preventDefault(); finish(false); }
|
||||
});
|
||||
input.addEventListener('blur', () => finish(true));
|
||||
return;
|
||||
}
|
||||
const on = e.target.closest('[data-ach-on]');
|
||||
if (on) {
|
||||
try {
|
||||
const data = await seAchApi(`${API}/api/achievement-types/${cur.id}`, { name: cur.name, is_active: !cur.is_active }, 'PUT');
|
||||
Object.assign(cur, data.item);
|
||||
seAchRender();
|
||||
showToast(cur.is_active ? 'Тип снова доступен' : 'Тип скрыт из выбора');
|
||||
} catch (err) {
|
||||
showToast(err.message || 'Не удалось изменить тип', true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const del = e.target.closest('[data-ach-del]');
|
||||
if (del) {
|
||||
if (!confirm(`Удалить тип «${cur.name}»? Уже внесённые достижения сохранят его название`)) return;
|
||||
try {
|
||||
await seAchApi(`${API}/api/achievement-types/${cur.id}`, null, 'DELETE');
|
||||
seAchTypes = seAchTypes.filter(t => t.id !== cur.id);
|
||||
seAchRender();
|
||||
showToast('Тип удалён');
|
||||
} catch (err) {
|
||||
showToast(err.message || 'Не удалось удалить тип', true);
|
||||
}
|
||||
}
|
||||
});
|
||||
document.getElementById('seAchAddBtn').addEventListener('click', async () => {
|
||||
const input = document.getElementById('seAchNewName');
|
||||
const name = input.value.trim();
|
||||
if (!name) { showToast('Введите название типа', true); return; }
|
||||
try {
|
||||
const data = await seAchApi(`${API}/api/achievement-types`, { name });
|
||||
seAchTypes.unshift(data.item);
|
||||
input.value = '';
|
||||
seAchRender();
|
||||
showToast('Тип добавлен');
|
||||
} catch (err) {
|
||||
showToast(err.message || 'Не удалось добавить тип', true);
|
||||
}
|
||||
});
|
||||
document.getElementById('seAchNewName').addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
document.getElementById('seAchAddBtn').click();
|
||||
}
|
||||
});
|
||||
await seAchLoad();
|
||||
}
|
||||
|
||||
(async () => {
|
||||
if (await requireAdminPage()) {
|
||||
buildSidebar(document.body.dataset.page);
|
||||
@@ -1493,6 +1652,7 @@ window.addEventListener('beforeunload', e => {
|
||||
} catch {
|
||||
if (authStatus) { authStatus.classList.remove('loaded'); authStatus.classList.add('err'); authStatus.textContent = 'Ошибка загрузки настроек'; }
|
||||
}
|
||||
initAchievementTypes();
|
||||
loadBans();
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -6,9 +6,13 @@
|
||||
let activeTab = 'entries';
|
||||
let facesLoaded = false;
|
||||
let facesData = null;
|
||||
let achTypes = [];
|
||||
let achTypesLoaded = false;
|
||||
let achEditId = null;
|
||||
|
||||
const TABS = [
|
||||
{ key: 'entries', label: 'Журнал', icon: 'book-open' },
|
||||
{ key: 'ach', label: 'Достижения', icon: 'trophy' },
|
||||
{ key: 'shorts', label: 'Короткие сообщения', icon: 'zap' },
|
||||
{ key: 'feedbacks', label: 'Обратная связь', icon: 'message-square-heart' },
|
||||
{ key: 'photos', label: 'Фото', icon: 'image' },
|
||||
@@ -82,8 +86,15 @@
|
||||
</button>`;
|
||||
}
|
||||
|
||||
function achCount() {
|
||||
if (!data.achievements) return 0;
|
||||
if (typeof data.achievements.total === 'number') return data.achievements.total;
|
||||
return (data.achievements.items || []).length;
|
||||
}
|
||||
|
||||
function tabCount(key) {
|
||||
if (key === 'entries') return data.entries.total;
|
||||
if (key === 'ach') return achCount();
|
||||
if (key === 'shorts') return data.shorts.total;
|
||||
if (key === 'feedbacks') return data.feedbacks.total;
|
||||
if (key === 'photos') return data.photos.items.length + (data.photos.photo_path ? 1 : 0);
|
||||
@@ -235,6 +246,10 @@
|
||||
pane.innerHTML = facesHtml();
|
||||
} else if (activeTab === 'entries') {
|
||||
pane.innerHTML = entriesHtml();
|
||||
} else if (activeTab === 'ach') {
|
||||
ensureAchTypes();
|
||||
pane.innerHTML = achievementsHtml();
|
||||
bindAch();
|
||||
} else if (activeTab === 'shorts') {
|
||||
pane.innerHTML = shortsHtml();
|
||||
} else if (activeTab === 'feedbacks') {
|
||||
@@ -256,6 +271,166 @@
|
||||
if (activeTab === 'faces') renderPane();
|
||||
}
|
||||
|
||||
function achItemHtml(a) {
|
||||
return `<div class="sp-ach-item" data-ach-id="${a.id}">
|
||||
<div class="sp-ach-top">
|
||||
<span class="sp-ach-type"><i data-lucide="trophy"></i> ${esc(a.type_name)}</span>
|
||||
${a.value ? `<span class="sp-ach-value">${esc(a.value)}</span>` : ''}
|
||||
<span class="sp-ach-date">
|
||||
${a.achieved_at ? esc(fmtDateIso(a.achieved_at)) : ''}
|
||||
<button type="button" class="icon-btn" data-ach-edit="${a.id}" title="Редактировать"><i data-lucide="pencil"></i></button>
|
||||
<button type="button" class="icon-btn danger" data-ach-del="${a.id}" title="Удалить"><i data-lucide="trash-2"></i></button>
|
||||
</span>
|
||||
</div>
|
||||
${a.note ? `<div class="sp-ach-note">${esc(a.note)}</div>` : ''}
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function achFormHtml() {
|
||||
return `<form class="sp-ach-form" id="spAchForm" hidden>
|
||||
<select id="spAchType"></select>
|
||||
<input id="spAchValue" maxlength="200" placeholder="Результат: 271 знак/мин, 1 место">
|
||||
<input type="date" id="spAchDate">
|
||||
<textarea id="spAchNote" maxlength="800" rows="2" placeholder="Комментарий (необязательно)"></textarea>
|
||||
<div class="sp-ach-acts">
|
||||
<button type="button" class="btn-primary ghost" id="spAchCancelBtn">Отмена</button>
|
||||
<button type="submit" class="btn-primary" id="spAchSaveBtn">Сохранить</button>
|
||||
</div>
|
||||
</form>`;
|
||||
}
|
||||
|
||||
function achievementsHtml() {
|
||||
const list = (data.achievements && data.achievements.items) || [];
|
||||
return `<div class="sp-ach-head">
|
||||
<button type="button" class="btn-link" id="spAchAddBtn"><i data-lucide="plus"></i> Добавить достижение</button>
|
||||
${achTypesLoaded ? (achTypes.length ? '<span class="sp-ach-hint">Типы достижений настраивает администратор (Настройки → Достижения)</span>' : '<span class="sp-ach-hint">Администратор ещё не добавил типы — он делает это в Настройки → Достижения</span>') : ''}
|
||||
</div>${achFormHtml()}${list.length ? `<div class="sp-ach-list" id="spAchList">${list.map(achItemHtml).join('')}</div>` : emptyHtml('Достижений пока нет')}`;
|
||||
}
|
||||
|
||||
function achTypeForm(selected) {
|
||||
const act = achTypes.filter(t => t.is_active);
|
||||
const a = v => esc(String(v)).replace(/"/g, '"');
|
||||
const opts = ['<option value="">Выберите тип…</option>']
|
||||
.concat(act.map(t => `<option value="${a(t.name)}"${selected === t.name ? ' selected' : ''}>${esc(t.name)}</option>`));
|
||||
if (selected && !act.some(t => t.name === selected)) {
|
||||
opts.push(`<option value="${a(selected)}" selected>${esc(selected)} (недоступен)</option>`);
|
||||
}
|
||||
return opts.join('');
|
||||
}
|
||||
|
||||
function achFormOpen(rec) {
|
||||
const form = document.getElementById('spAchForm');
|
||||
if (!form) return;
|
||||
achEditId = rec ? rec.id : null;
|
||||
document.getElementById('spAchType').innerHTML = achTypeForm(rec ? rec.type_name : '');
|
||||
document.getElementById('spAchValue').value = rec ? (rec.value || '') : '';
|
||||
document.getElementById('spAchDate').value = rec ? (rec.achieved_at || '') : todayIso();
|
||||
document.getElementById('spAchNote').value = rec ? (rec.note || '') : '';
|
||||
form.hidden = false;
|
||||
document.getElementById('spAchType').focus();
|
||||
}
|
||||
|
||||
function achFormClose() {
|
||||
const form = document.getElementById('spAchForm');
|
||||
if (form) form.hidden = true;
|
||||
achEditId = null;
|
||||
}
|
||||
|
||||
async function ensureAchTypes() {
|
||||
if (achTypesLoaded) return;
|
||||
try {
|
||||
const res = await fetch(`${API}/api/achievement-types`, { headers: hdr() });
|
||||
const d = await res.json();
|
||||
achTypes = res.ok && Array.isArray(d.items) ? d.items : [];
|
||||
achTypesLoaded = true;
|
||||
} catch {
|
||||
achTypes = [];
|
||||
}
|
||||
if (activeTab === 'ach') renderPane();
|
||||
}
|
||||
|
||||
function bindAch() {
|
||||
const addBtn = document.getElementById('spAchAddBtn');
|
||||
if (addBtn) addBtn.addEventListener('click', () => achFormOpen(null));
|
||||
const form = document.getElementById('spAchForm');
|
||||
if (!form) return;
|
||||
form.addEventListener('submit', onAchSubmit);
|
||||
document.getElementById('spAchCancelBtn').addEventListener('click', achFormClose);
|
||||
const list = document.getElementById('spAchList');
|
||||
if (list) {
|
||||
list.addEventListener('click', async e => {
|
||||
const items = (data.achievements && data.achievements.items) || [];
|
||||
const edit = e.target.closest('[data-ach-edit]');
|
||||
if (edit) {
|
||||
const rec = items.find(x => String(x.id) === edit.dataset.achEdit);
|
||||
if (rec) achFormOpen(rec);
|
||||
return;
|
||||
}
|
||||
const del = e.target.closest('[data-ach-del]');
|
||||
if (del) {
|
||||
const rec = items.find(x => String(x.id) === del.dataset.achDel);
|
||||
if (!rec) return;
|
||||
if (!confirm(`Удалить «${rec.type_name}${rec.value ? ' — ' + rec.value : ''}»?`)) return;
|
||||
try {
|
||||
const res = await fetch(`${API}/api/students/${studentId}/achievements/${rec.id}`, { method: 'DELETE', headers: hdr() });
|
||||
if (!res.ok) throw new Error('delete failed');
|
||||
showToast('Достижение удалено');
|
||||
await refreshAch();
|
||||
} catch {
|
||||
showToast('Не удалось удалить достижение', true);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function onAchSubmit(e) {
|
||||
e.preventDefault();
|
||||
const typeName = document.getElementById('spAchType').value.trim();
|
||||
if (!typeName) { showToast('Выберите тип достижения', true); return; }
|
||||
const body = {
|
||||
type_name: typeName,
|
||||
value: document.getElementById('spAchValue').value.trim(),
|
||||
achieved_at: document.getElementById('spAchDate').value || null,
|
||||
note: document.getElementById('spAchNote').value.trim(),
|
||||
};
|
||||
const btn = document.getElementById('spAchSaveBtn');
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const url = achEditId
|
||||
? `${API}/api/students/${studentId}/achievements/${achEditId}`
|
||||
: `${API}/api/students/${studentId}/achievements`;
|
||||
const res = await fetch(url, {
|
||||
method: achEditId ? 'PUT' : 'POST',
|
||||
headers: { ...hdr(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err.error || 'Не удалось сохранить достижение');
|
||||
}
|
||||
showToast(achEditId ? 'Достижение обновлено' : 'Достижение добавлено');
|
||||
achFormClose();
|
||||
await refreshAch();
|
||||
} catch (err) {
|
||||
showToast(err.message || 'Не удалось сохранить достижение', true);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshAch() {
|
||||
try {
|
||||
const res = await fetch(`${API}/api/students/${studentId}/achievements`, { headers: hdr() });
|
||||
if (res.ok) {
|
||||
const d = await res.json();
|
||||
data.achievements = { items: d.items || [], total: typeof d.total === 'number' ? d.total : (d.items || []).length };
|
||||
}
|
||||
} catch {}
|
||||
renderTabs();
|
||||
if (activeTab === 'ach') renderPane();
|
||||
}
|
||||
|
||||
async function downloadProfile() {
|
||||
const btn = document.getElementById('spDownloadBtn');
|
||||
if (btn) btn.disabled = true;
|
||||
|
||||
@@ -367,6 +367,9 @@ let profilePhotos = [];
|
||||
let pfState = null;
|
||||
let pfBaseline = '';
|
||||
let pfActiveTab = 'general';
|
||||
let achRecords = [];
|
||||
let achTypes = [];
|
||||
let achEditId = null;
|
||||
|
||||
const PF_CONTACT_ICONS = ['mail', 'send', 'phone', 'github', 'globe', 'link', 'at-sign'];
|
||||
|
||||
@@ -587,6 +590,9 @@ function openProfileData(id) {
|
||||
document.getElementById('profileDataModal').classList.add('open');
|
||||
loadGroupOptions();
|
||||
loadStudentPhotos(id);
|
||||
resetAchForm();
|
||||
loadAchRecords(id);
|
||||
loadAchTypes();
|
||||
fetch(`${API}/api/students/${id}/profile`, { headers: hdr() })
|
||||
.then(r => (r.ok ? r.json() : Promise.reject(new Error('load'))))
|
||||
.then(data => {
|
||||
@@ -609,6 +615,124 @@ function closeProfileData(skipCheck) {
|
||||
return true;
|
||||
}
|
||||
|
||||
function achTypeSelect(selected) {
|
||||
const act = achTypes.filter(t => t.is_active);
|
||||
const opts = ['<option value="">Выберите тип…</option>'].concat(
|
||||
act.map(t => `<option value="${pfE(t.name)}"${selected === t.name ? ' selected' : ''}>${esc(t.name)}</option>`)
|
||||
);
|
||||
if (selected && !act.some(t => t.name === selected)) {
|
||||
opts.push(`<option value="${pfE(selected)}" selected>${esc(selected)} (недоступен)</option>`);
|
||||
}
|
||||
return opts.join('');
|
||||
}
|
||||
|
||||
function openAchForm(rec) {
|
||||
const form = document.getElementById('pfAchForm');
|
||||
if (!form) return;
|
||||
achEditId = rec ? rec.id : null;
|
||||
document.getElementById('pfAchType').innerHTML = achTypeSelect(rec ? rec.type_name : '');
|
||||
document.getElementById('pfAchValue').value = rec ? (rec.value || '') : '';
|
||||
document.getElementById('pfAchDate').value = rec ? (rec.achieved_at || '') : todayIso();
|
||||
document.getElementById('pfAchNote').value = rec ? (rec.note || '') : '';
|
||||
form.hidden = false;
|
||||
document.getElementById('pfAchType').focus();
|
||||
}
|
||||
|
||||
function resetAchForm() {
|
||||
const form = document.getElementById('pfAchForm');
|
||||
if (form) form.hidden = true;
|
||||
achEditId = null;
|
||||
}
|
||||
|
||||
function pfAchItemHtml(a) {
|
||||
return `<div class="pf-ach-row">
|
||||
<div class="pf-ach-main">
|
||||
<div class="pf-ach-top">
|
||||
<span class="pf-ach-type">${esc(a.type_name)}</span>
|
||||
${a.value ? `<b class="pf-ach-value">${esc(a.value)}</b>` : ''}
|
||||
<span class="pf-ach-when">${a.achieved_at ? esc(fmtDateOnlyIso(a.achieved_at)) : ''}</span>
|
||||
</div>
|
||||
${a.note ? `<div class="pf-ach-note">${esc(a.note)}</div>` : ''}
|
||||
</div>
|
||||
<div class="pf-ach-acts">
|
||||
<button type="button" class="icon-btn" data-ach-edit="${a.id}" title="Редактировать"><i data-lucide="pencil"></i></button>
|
||||
<button type="button" class="icon-btn" data-ach-del="${a.id}" title="Удалить"><i data-lucide="trash-2"></i></button>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function pfAchRender() {
|
||||
const wrap = document.getElementById('pfAchRecords');
|
||||
if (!wrap) return;
|
||||
wrap.innerHTML = achRecords.length ? achRecords.map(pfAchItemHtml).join('') : '<div class="pf-ach-empty">Достижений пока нет</div>';
|
||||
const cnt = document.getElementById('pfCountAch');
|
||||
if (cnt) cnt.textContent = achRecords.length ? String(achRecords.length) : '';
|
||||
renderIcons();
|
||||
}
|
||||
|
||||
async function loadAchRecords(id) {
|
||||
achRecords = [];
|
||||
pfAchRender();
|
||||
try {
|
||||
const res = await fetch(`${API}/api/students/${id}/achievements`, { headers: hdr() });
|
||||
const d = await res.json();
|
||||
achRecords = res.ok && Array.isArray(d.items) ? d.items : [];
|
||||
} catch {
|
||||
achRecords = [];
|
||||
}
|
||||
pfAchRender();
|
||||
}
|
||||
|
||||
async function loadAchTypes() {
|
||||
try {
|
||||
const res = await fetch(`${API}/api/achievement-types`, { headers: hdr() });
|
||||
const d = await res.json();
|
||||
achTypes = res.ok && Array.isArray(d.items) ? d.items : [];
|
||||
} catch {
|
||||
achTypes = [];
|
||||
}
|
||||
const form = document.getElementById('pfAchForm');
|
||||
if (form && !form.hidden && achEditId == null) {
|
||||
document.getElementById('pfAchType').innerHTML = achTypeSelect('');
|
||||
}
|
||||
}
|
||||
|
||||
async function onAchSubmit(e) {
|
||||
e.preventDefault();
|
||||
if (!profileDataId) return;
|
||||
const typeName = document.getElementById('pfAchType').value.trim();
|
||||
if (!typeName) { showToast('Выберите тип достижения', true); return; }
|
||||
const body = {
|
||||
type_name: typeName,
|
||||
value: document.getElementById('pfAchValue').value.trim(),
|
||||
achieved_at: document.getElementById('pfAchDate').value || null,
|
||||
note: document.getElementById('pfAchNote').value.trim(),
|
||||
};
|
||||
const btn = document.getElementById('pfAchSaveBtn');
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const url = achEditId
|
||||
? `${API}/api/students/${profileDataId}/achievements/${achEditId}`
|
||||
: `${API}/api/students/${profileDataId}/achievements`;
|
||||
const res = await fetch(url, {
|
||||
method: achEditId ? 'PUT' : 'POST',
|
||||
headers: { ...hdr(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
throw new Error(err.error || 'Не удалось сохранить достижение');
|
||||
}
|
||||
showToast(achEditId ? 'Достижение обновлено' : 'Достижение добавлено');
|
||||
resetAchForm();
|
||||
await loadAchRecords(profileDataId);
|
||||
} catch (err) {
|
||||
showToast(err.message || 'Не удалось сохранить достижение', true);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function openStudentFaces(id, name) {
|
||||
profileDataId = id;
|
||||
faceRefs = [];
|
||||
@@ -1595,6 +1719,39 @@ document.getElementById('profileDataForm').addEventListener('click', e => {
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('pfAchAddBtn').addEventListener('click', () => openAchForm(null));
|
||||
document.getElementById('pfAchSaveBtn').addEventListener('click', onAchSubmit);
|
||||
document.getElementById('pfAchForm').addEventListener('keydown', e => {
|
||||
if (e.key !== 'Enter' || e.shiftKey) return;
|
||||
if (e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT' || e.target.tagName === 'BUTTON') return;
|
||||
e.preventDefault();
|
||||
onAchSubmit(e);
|
||||
});
|
||||
document.getElementById('pfAchCancelBtn').addEventListener('click', resetAchForm);
|
||||
document.getElementById('pfAchRecords').addEventListener('click', async e => {
|
||||
const edit = e.target.closest('[data-ach-edit]');
|
||||
if (edit) {
|
||||
const rec = achRecords.find(x => String(x.id) === edit.dataset.achEdit);
|
||||
if (rec) openAchForm(rec);
|
||||
return;
|
||||
}
|
||||
const del = e.target.closest('[data-ach-del]');
|
||||
if (del) {
|
||||
if (!profileDataId) return;
|
||||
const rec = achRecords.find(x => String(x.id) === del.dataset.achDel);
|
||||
if (!rec) return;
|
||||
if (!confirm(`Удалить «${rec.type_name}${rec.value ? ' — ' + rec.value : ''}»?`)) return;
|
||||
try {
|
||||
const res = await fetch(`${API}/api/students/${profileDataId}/achievements/${rec.id}`, { method: 'DELETE', headers: hdr() });
|
||||
if (!res.ok) throw new Error('Не удалось удалить достижение');
|
||||
showToast('Достижение удалено');
|
||||
await loadAchRecords(profileDataId);
|
||||
} catch (err) {
|
||||
showToast(err.message || 'Не удалось удалить достижение', true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('pfTagsInput').addEventListener('keydown', e => {
|
||||
if (e.key !== 'Enter' && e.key !== ',') return;
|
||||
e.preventDefault();
|
||||
|
||||
@@ -5,6 +5,24 @@
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Настройки — Админ-панель</title>
|
||||
<link rel="stylesheet" href="admin.css">
|
||||
<style>
|
||||
.se-ach-list{display:flex;flex-direction:column;border:1px solid var(--border);border-radius:12px;overflow:hidden;margin-top:10px}
|
||||
.se-ach-row{display:flex;align-items:center;gap:10px;padding:8px 12px;border-bottom:1px solid var(--border)}
|
||||
.se-ach-row:last-child{border-bottom:none}
|
||||
.se-ach-row.is-off .se-ach-name{opacity:.45;text-decoration:line-through}
|
||||
.se-ach-drag{cursor:grab;color:var(--muted);font-weight:700;user-select:none;line-height:1}
|
||||
.se-ach-name{flex:1;min-width:0;font-size:.9rem;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.se-ach-name-input{flex:1;min-width:0;font:inherit;font-size:.88rem;padding:5px 10px;border:1px solid var(--accent);border-radius:8px;background:var(--card);color:var(--text)}
|
||||
.se-ach-on{background:var(--bg);border:1px solid var(--border);border-radius:999px;color:var(--muted);font-size:.68rem;font-weight:700;padding:3px 10px;cursor:pointer;transition:all .15s;flex:0 0 auto}
|
||||
.se-ach-on.on{color:var(--accent);border-color:rgba(37,99,235,.35);background:rgba(37,99,235,.08)}
|
||||
.se-ach-btn{border:none;background:none;color:var(--muted);cursor:pointer;padding:4px;display:flex}
|
||||
.se-ach-btn:hover{color:var(--text)}
|
||||
.se-ach-btn.danger:hover{color:#ef4444}
|
||||
.se-ach-btn svg{width:15px;height:15px}
|
||||
.se-ach-add{display:flex;gap:10px;margin-top:10px}
|
||||
.se-ach-add .settings-input{flex:1;min-width:0}
|
||||
.se-ach-empty{padding:16px 12px;color:var(--muted);font-size:.85rem;text-align:center}
|
||||
</style>
|
||||
</head>
|
||||
<body data-page="settings">
|
||||
<div class="layout">
|
||||
@@ -32,6 +50,7 @@
|
||||
<a href="#sec-ai" data-nav="sec-ai"><i data-lucide="bot"></i> ИИ</a>
|
||||
<a href="#sec-lesson-ai" data-nav="sec-lesson-ai"><i data-lucide="notebook-pen"></i> Шаблон отчёта</a>
|
||||
<a href="#sec-faces" data-nav="sec-faces"><i data-lucide="scan-face"></i> Библиотека лиц</a>
|
||||
<a href="#sec-achievements" data-nav="sec-achievements"><i data-lucide="trophy"></i> Достижения</a>
|
||||
<a href="#sec-notes-ai" data-nav="sec-notes-ai"><i data-lucide="sticky-note"></i> Заголовки заметок</a>
|
||||
<a href="#sec-tls" data-nav="sec-tls"><i data-lucide="key-round"></i> Сертификат</a>
|
||||
<a href="#sec-backup" data-nav="sec-backup"><i data-lucide="database"></i> Бэкапы</a>
|
||||
@@ -266,6 +285,19 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-card" id="sec-achievements">
|
||||
<div class="card-head">
|
||||
<div class="ic"><i data-lucide="trophy"></i></div>
|
||||
<h3>Достижения</h3>
|
||||
</div>
|
||||
<p class="hint">Каталог типов персональных достижений учеников: скорость печати, результаты олимпиад и т.п. Тип выбирается при добавлении достижения — на странице ученика (вкладка «Достижения») или в профиле. Переименование типа обновляет уже внесённые записи; при удалении типа записи сохраняют его название. Выключенный тип не предлагается для новых достижений.</p>
|
||||
<div class="se-ach-list" id="seAchList"></div>
|
||||
<div class="se-ach-add">
|
||||
<input type="text" id="seAchNewName" class="settings-input" maxlength="150" placeholder="Новый тип: Скорость печати">
|
||||
<button type="button" class="btn-primary" id="seAchAddBtn"><i data-lucide="plus"></i> Добавить</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-card" id="sec-notes-ai">
|
||||
<div class="card-head">
|
||||
<div class="ic"><i data-lucide="sticky-note"></i></div>
|
||||
|
||||
@@ -93,6 +93,23 @@
|
||||
.sp-loading{display:flex;align-items:center;justify-content:center;gap:10px;color:var(--muted);padding:60px 16px}
|
||||
.sp-loading svg{width:20px;height:20px;animation:spin 1s linear infinite}
|
||||
.sp-error{text-align:center;padding:60px 16px;color:#ef4444}
|
||||
.sp-ach-head{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;margin-bottom:12px}
|
||||
.sp-ach-hint{color:var(--muted);font-size:.78rem}
|
||||
.sp-ach-form{display:grid;grid-template-columns:minmax(170px,250px) minmax(180px,1fr) minmax(140px,170px);gap:10px;border:1px solid var(--border);border-radius:14px;padding:14px;margin-bottom:16px}
|
||||
.sp-ach-form[hidden]{display:none}
|
||||
.sp-ach-form input,.sp-ach-form select,.sp-ach-form textarea{width:100%;box-sizing:border-box;font:inherit;font-size:.88rem;padding:9px 12px;border:1px solid var(--border);border-radius:9px;background:var(--bg);color:var(--text)}
|
||||
.sp-ach-form input:focus,.sp-ach-form select:focus,.sp-ach-form textarea:focus{border-color:var(--accent);outline:none}
|
||||
.sp-ach-form textarea{grid-column:1/-1;resize:vertical}
|
||||
.sp-ach-acts{grid-column:1/-1;display:flex;gap:8px;justify-content:flex-end}
|
||||
.sp-ach-list{display:flex;flex-direction:column;gap:10px}
|
||||
.sp-ach-item{border:1px solid var(--border);border-radius:14px;padding:13px 15px;display:flex;flex-direction:column;gap:7px}
|
||||
.sp-ach-top{display:flex;align-items:center;gap:10px;flex-wrap:wrap}
|
||||
.sp-ach-type{display:inline-flex;align-items:center;gap:6px;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)}
|
||||
.sp-ach-type svg{width:12px;height:12px}
|
||||
.sp-ach-value{font-weight:700;font-size:.92rem}
|
||||
.sp-ach-date{margin-left:auto;color:var(--muted);font-size:.78rem;display:inline-flex;align-items:center;gap:4px}
|
||||
.sp-ach-note{color:var(--muted);font-size:.84rem;white-space:pre-wrap;overflow-wrap:anywhere}
|
||||
@media (max-width:720px){.sp-ach-form{grid-template-columns:1fr}}
|
||||
</style>
|
||||
</head>
|
||||
<body data-page="students">
|
||||
|
||||
@@ -169,6 +169,7 @@
|
||||
<button type="button" class="pf-tab" data-pf-tab="skills"><i data-lucide="sparkles"></i>Навыки<span class="pf-tab-count" id="pfCountSkills"></span></button>
|
||||
<button type="button" class="pf-tab" data-pf-tab="about"><i data-lucide="briefcase"></i>Опыт<span class="pf-tab-count" id="pfCountAbout"></span></button>
|
||||
<button type="button" class="pf-tab" data-pf-tab="contacts"><i data-lucide="at-sign"></i>Контакты<span class="pf-tab-count" id="pfCountContacts"></span></button>
|
||||
<button type="button" class="pf-tab" data-pf-tab="ach"><i data-lucide="trophy"></i>Достижения<span class="pf-tab-count" id="pfCountAch"></span></button>
|
||||
<button type="button" class="pf-tab" data-pf-tab="media"><i data-lucide="image"></i>Фото и лица</button>
|
||||
</nav>
|
||||
|
||||
@@ -272,6 +273,27 @@
|
||||
<div class="pf-list" id="pfContacts"></div>
|
||||
</section>
|
||||
|
||||
<section class="pf-pane" data-pf-pane="ach">
|
||||
<div class="pf-pane-head">
|
||||
<div>
|
||||
<h4>Достижения</h4>
|
||||
<p class="hint">Персональные результаты: скорость печати, олимпиады и т.п. Типы задаёт администратор в настройках.</p>
|
||||
</div>
|
||||
<button type="button" class="pf-add" id="pfAchAddBtn"><i data-lucide="plus"></i>Добавить</button>
|
||||
</div>
|
||||
<div class="pf-ach-form" id="pfAchForm" hidden>
|
||||
<label class="pf-f"><span>Тип</span><select id="pfAchType"></select></label>
|
||||
<label class="pf-f pf-mid"><span>Результат</span><input type="text" id="pfAchValue" maxlength="200" placeholder="271 знак/мин, 1 место"></label>
|
||||
<label class="pf-f pf-mid"><span>Дата</span><input type="date" id="pfAchDate"></label>
|
||||
<label class="pf-f pf-row-wide"><span>Комментарий</span><textarea id="pfAchNote" maxlength="800" rows="2" placeholder="Необязательно"></textarea></label>
|
||||
<div class="pf-ach-actions">
|
||||
<button type="button" class="btn-primary ghost" id="pfAchCancelBtn">Отмена</button>
|
||||
<button type="button" class="btn-primary" id="pfAchSaveBtn">Сохранить</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pf-list pf-ach-rows" id="pfAchRecords"></div>
|
||||
</section>
|
||||
|
||||
<section class="pf-pane" data-pf-pane="media">
|
||||
<div class="pf-tile">
|
||||
<div class="pf-tile-head">
|
||||
|
||||
@@ -67,6 +67,24 @@ const {
|
||||
publicArticle: publicDocArticle,
|
||||
docsError,
|
||||
} = require('./lib/docs');
|
||||
const {
|
||||
achError,
|
||||
normAchDate,
|
||||
achRecordFields,
|
||||
achFieldsError,
|
||||
ACH_TYPE_NAME_MAX,
|
||||
ACH_VALUE_MAX,
|
||||
ACH_NOTE_MAX,
|
||||
listTypes: achListTypes,
|
||||
createType: achCreateType,
|
||||
updateType: achUpdateType,
|
||||
deleteType: achDeleteType,
|
||||
reorderTypes: achReorderTypes,
|
||||
listForStudent: achListForStudent,
|
||||
createRecord: achCreateRecord,
|
||||
updateRecord: achUpdateRecord,
|
||||
deleteRecord: achDeleteRecord,
|
||||
} = require('./lib/achievements');
|
||||
|
||||
const https = require('https');
|
||||
const path = require('path');
|
||||
@@ -2743,6 +2761,31 @@ async function ensureBookmarksTable() {
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_bookmarks_sort ON bookmarks(sort_order, id)');
|
||||
}
|
||||
|
||||
async function ensureAchievementsTables() {
|
||||
await pool.query(`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()
|
||||
)`);
|
||||
await pool.query('CREATE UNIQUE INDEX IF NOT EXISTS idx_achievement_types_name ON achievement_types(lower(name))');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_achievement_types_order ON achievement_types(sort_order, id)');
|
||||
await pool.query(`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()
|
||||
)`);
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_student_achievements_student ON student_achievements(student_id)');
|
||||
}
|
||||
|
||||
async function ensureApiKeysTable() {
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id SERIAL PRIMARY KEY,
|
||||
@@ -2783,6 +2826,7 @@ async function ensureUsersAndFirstAdmin() {
|
||||
await ensureApiKeysTable();
|
||||
await ensureUserNotesTable();
|
||||
await ensureBookmarksTable();
|
||||
await ensureAchievementsTables();
|
||||
await ensureDocsTables(pool);
|
||||
await ensureFirstAdmin();
|
||||
}
|
||||
@@ -4995,6 +5039,68 @@ app.delete('/api/bookmarks/:id/photo', requireAdmin, async (req, res) => {
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get('/api/achievement-types', requireAuth, async (req, res) => {
|
||||
try {
|
||||
res.json({ items: await achListTypes(pool) });
|
||||
} catch (e) {
|
||||
achError(res, e, 'Не удалось получить типы достижений', 'achievement types list');
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/achievement-types', requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const name = reqStr(req.body?.name, ACH_TYPE_NAME_MAX);
|
||||
const item = await achCreateType(pool, name);
|
||||
await logAudit(req, 'achievement.type.create', { id: item.id, name: item.name });
|
||||
res.json({ item });
|
||||
} catch (e) {
|
||||
achError(res, e, 'Не удалось создать тип достижения', 'achievement type create');
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/achievement-types/reorder', requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const raw = Array.isArray(req.body?.ids) ? req.body.ids : null;
|
||||
if (!raw || raw.some(id => !Number.isInteger(Number(id)))) {
|
||||
return res.status(400).json({ error: 'Некорректный порядок типов' });
|
||||
}
|
||||
const ids = raw.map(id => Number(id));
|
||||
if (ids.some(id => id < 1)) return res.status(400).json({ error: 'Некорректный порядок типов' });
|
||||
if (new Set(ids).size !== ids.length) {
|
||||
return res.status(400).json({ error: 'Порядок содержит дубликаты' });
|
||||
}
|
||||
await achReorderTypes(pool, ids);
|
||||
await logAudit(req, 'achievement.type.reorder', { order: ids });
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
achError(res, e, 'Не удалось сохранить порядок типов', 'achievement type reorder');
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/achievement-types/:id', requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const id = reqInt(req.params.id);
|
||||
const name = reqStr(req.body?.name, ACH_TYPE_NAME_MAX);
|
||||
const isActive = typeof req.body?.is_active === 'boolean' ? req.body.is_active : undefined;
|
||||
const { item, renamed } = await achUpdateType(pool, id, name, isActive);
|
||||
await logAudit(req, 'achievement.type.update', { id, name: item.name, is_active: item.is_active, renamed });
|
||||
res.json({ item });
|
||||
} catch (e) {
|
||||
achError(res, e, 'Не удалось обновить тип достижения', 'achievement type update');
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/achievement-types/:id', requireAdmin, async (req, res) => {
|
||||
try {
|
||||
const id = reqInt(req.params.id);
|
||||
const gone = await achDeleteType(pool, id);
|
||||
await logAudit(req, 'achievement.type.delete', { id, name: gone.name });
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
achError(res, e, 'Не удалось удалить тип достижения', 'achievement type delete');
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/docs/tree', requireAuth, async (req, res) => {
|
||||
try {
|
||||
res.json(await docsTree(pool, req.user));
|
||||
@@ -6295,7 +6401,7 @@ function sweepBackupStorage() {
|
||||
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] = 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, 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'),
|
||||
@@ -6330,6 +6436,8 @@ async function buildBackupArchive() {
|
||||
pool.query('SELECT * FROM doc_sections ORDER BY id'),
|
||||
pool.query('SELECT * FROM doc_articles ORDER BY id'),
|
||||
pool.query('SELECT * FROM doc_images ORDER BY id'),
|
||||
pool.query('SELECT * FROM achievement_types ORDER BY id'),
|
||||
pool.query('SELECT * FROM student_achievements ORDER BY id'),
|
||||
]);
|
||||
const settings = {};
|
||||
st.rows.forEach(r => { settings[r.key] = r.value; });
|
||||
@@ -6348,9 +6456,11 @@ async function buildBackupArchive() {
|
||||
short_messages: sm.rowCount, feedbacks: fb.rowCount, user_settings: uss.rowCount, user_notes: un.rowCount,
|
||||
bookmarks: bm.rowCount,
|
||||
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,
|
||||
},
|
||||
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,
|
||||
};
|
||||
fs.writeFileSync(path.join(staging, 'data.json'), JSON.stringify(payload));
|
||||
@@ -6559,6 +6669,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
await client.query('DELETE FROM feedbacks');
|
||||
await client.query('DELETE FROM entries');
|
||||
await client.query('DELETE FROM modules');
|
||||
await client.query('DELETE FROM student_achievements');
|
||||
await client.query('DELETE FROM students');
|
||||
await client.query('DELETE FROM share_links');
|
||||
await client.query('DELETE FROM groups');
|
||||
@@ -6570,6 +6681,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
await client.query('DELETE FROM user_settings');
|
||||
await client.query('DELETE FROM user_notes');
|
||||
await client.query('DELETE FROM bookmarks');
|
||||
await client.query('DELETE FROM achievement_types');
|
||||
await client.query('DELETE FROM photo_faces');
|
||||
await client.query('DELETE FROM student_face_refs');
|
||||
await client.query('DELETE FROM doc_images');
|
||||
@@ -6611,6 +6723,12 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
[x.id, x.title, x.url, x.description, x.photo_path || null, x.image_mode === 'cover' ? 'cover' : 'logo', x.open_new_tab !== false, x.is_active !== false, x.sort_order, x.created_at || null, x.updated_at || null]
|
||||
);
|
||||
}
|
||||
for (const x of (ndata.achievement_types || [])) {
|
||||
await client.query(
|
||||
'INSERT INTO achievement_types (id, name, sort_order, is_active, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6)',
|
||||
[x.id, x.name, x.sort_order, x.is_active !== false, x.created_at || null, x.updated_at || null]
|
||||
);
|
||||
}
|
||||
for (const x of (ndata.doc_sections || [])) {
|
||||
await client.query(
|
||||
'INSERT INTO doc_sections (id, parent_id, title, sort_order, tutor_edit, is_public, created_at, updated_at) VALUES ($1, NULL, $2, $3, $4, $5, $6, $7)',
|
||||
@@ -6666,6 +6784,15 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
[x.id, x.student_id, x.photo_path, JSON.stringify(x.embedding || []), x.det_score || 0, x.created_at || null]
|
||||
);
|
||||
}
|
||||
for (const x of (ndata.student_achievements || [])) {
|
||||
const ex = await client.query('SELECT 1 FROM students WHERE id = $1', [x.student_id]);
|
||||
if (!ex.rowCount) continue;
|
||||
await client.query(
|
||||
`INSERT INTO student_achievements (id, student_id, type_name, value, achieved_at, note, author_id, created_at, updated_at)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,(SELECT id FROM users WHERE id = $7),$8,$9)`,
|
||||
[x.id, x.student_id, x.type_name, x.value, x.achieved_at || null, x.note, x.author_id, x.created_at || null, x.updated_at || null]
|
||||
);
|
||||
}
|
||||
for (const x of ndata.modules) {
|
||||
await client.query(
|
||||
'INSERT INTO modules (id, name, lessons_count, is_active, has_attachments, photo_path, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7)',
|
||||
@@ -9093,7 +9220,7 @@ app.get('/api/students/:id/overview', requireAuth, async (req, res) => {
|
||||
}
|
||||
const fWhere = fConds.join(' AND ');
|
||||
|
||||
const [groupRes, entriesTotalRes, entriesRes, fbTotalRes, fbRes, shortsTotalRes, shortsRes, photosRes, facesRes] = await Promise.all([
|
||||
const [groupRes, entriesTotalRes, entriesRes, fbTotalRes, fbRes, shortsTotalRes, shortsRes, photosRes, facesRes, achList] = await Promise.all([
|
||||
student.group_id ? pool.query('SELECT id, name FROM groups WHERE id = $1', [student.group_id]) : Promise.resolve({ rows: [] }),
|
||||
pool.query(`SELECT count(*)::int AS n FROM entries e JOIN groups g ON g.id = e.group_id WHERE ${eWhere}`, eParams),
|
||||
(() => {
|
||||
@@ -9137,6 +9264,7 @@ app.get('/api/students/:id/overview', requireAuth, async (req, res) => {
|
||||
(SELECT count(*)::int FROM photo_faces WHERE student_id IS NULL AND best_student_id = $1 AND best_score >= $2) AS similar`,
|
||||
[id, FACE_CANDIDATE_MIN]
|
||||
),
|
||||
achListForStudent(pool, id),
|
||||
]);
|
||||
|
||||
const entryIds = entriesRes.rows.map(r => r.id);
|
||||
@@ -9160,6 +9288,7 @@ app.get('/api/students/:id/overview', requireAuth, async (req, res) => {
|
||||
shorts: { items: shortsRes.rows, total: shortsTotalRes.rows[0].n },
|
||||
photos: { items: photosRes.rows, photo_path: student.photo_path || null },
|
||||
faces: { refs: faces.refs || 0, found: faces.found || 0, similar: faces.similar || 0 },
|
||||
achievements: achList || { items: [], total: 0 },
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('student overview:', e);
|
||||
@@ -9167,6 +9296,111 @@ app.get('/api/students/:id/overview', requireAuth, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/students/:id/achievements', requireAuth, async (req, res) => {
|
||||
let id;
|
||||
try {
|
||||
id = reqInt(req.params.id);
|
||||
} catch {
|
||||
return res.status(400).json({ error: 'Неверный id ученика' });
|
||||
}
|
||||
const acc = await studentProfileAccess(req.user, id);
|
||||
if (!acc.found) {
|
||||
return res.status(acc.forbidden ? 403 : 404).json({ error: acc.forbidden ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
|
||||
}
|
||||
try {
|
||||
res.json(await achListForStudent(pool, id));
|
||||
} catch (e) {
|
||||
achError(res, e, 'Не удалось получить достижения', 'student achievements list');
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/students/:id/achievements', requireAuth, async (req, res) => {
|
||||
let id;
|
||||
try {
|
||||
id = reqInt(req.params.id);
|
||||
} catch {
|
||||
return res.status(400).json({ error: 'Неверный id ученика' });
|
||||
}
|
||||
let fields;
|
||||
try {
|
||||
fields = achRecordFields(req.body);
|
||||
} catch (e) {
|
||||
return res.status(400).json({ error: achFieldsError(e) });
|
||||
}
|
||||
const acc = await studentProfileAccess(req.user, id);
|
||||
if (!acc.found) {
|
||||
return res.status(acc.forbidden ? 403 : 404).json({ error: acc.forbidden ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
|
||||
}
|
||||
try {
|
||||
const item = await achCreateRecord(pool, { ...fields, studentId: id, authorId: req.user.id });
|
||||
await logAudit(req, 'achievement.create', { id: item.id, student_id: id, type_name: item.type_name });
|
||||
invalidateStudents();
|
||||
res.json({ item });
|
||||
} catch (e) {
|
||||
achError(res, e, 'Не удалось добавить достижение', 'student achievement create');
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/students/:id/achievements/:aid', requireAuth, async (req, res) => {
|
||||
let id;
|
||||
try {
|
||||
id = reqInt(req.params.id);
|
||||
} catch {
|
||||
return res.status(400).json({ error: 'Неверный id ученика' });
|
||||
}
|
||||
let aid;
|
||||
try {
|
||||
aid = reqInt(req.params.aid);
|
||||
} catch {
|
||||
return res.status(400).json({ error: 'Неверный id достижения' });
|
||||
}
|
||||
let fields;
|
||||
try {
|
||||
fields = achRecordFields(req.body);
|
||||
} catch (e) {
|
||||
return res.status(400).json({ error: achFieldsError(e) });
|
||||
}
|
||||
const acc = await studentProfileAccess(req.user, id);
|
||||
if (!acc.found) {
|
||||
return res.status(acc.forbidden ? 403 : 404).json({ error: acc.forbidden ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
|
||||
}
|
||||
try {
|
||||
const item = await achUpdateRecord(pool, id, aid, fields);
|
||||
await logAudit(req, 'achievement.update', { id: aid, student_id: id, type_name: item.type_name });
|
||||
invalidateStudents();
|
||||
res.json({ item });
|
||||
} catch (e) {
|
||||
achError(res, e, 'Не удалось обновить достижение', 'student achievement update');
|
||||
}
|
||||
});
|
||||
|
||||
app.delete('/api/students/:id/achievements/:aid', requireAuth, async (req, res) => {
|
||||
let id;
|
||||
try {
|
||||
id = reqInt(req.params.id);
|
||||
} catch {
|
||||
return res.status(400).json({ error: 'Неверный id ученика' });
|
||||
}
|
||||
let aid;
|
||||
try {
|
||||
aid = reqInt(req.params.aid);
|
||||
} catch {
|
||||
return res.status(400).json({ error: 'Неверный id достижения' });
|
||||
}
|
||||
const acc = await studentProfileAccess(req.user, id);
|
||||
if (!acc.found) {
|
||||
return res.status(acc.forbidden ? 403 : 404).json({ error: acc.forbidden ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
|
||||
}
|
||||
try {
|
||||
const item = await achDeleteRecord(pool, id, aid);
|
||||
await logAudit(req, 'achievement.delete', { id: aid, student_id: id, type_name: item.type_name });
|
||||
invalidateStudents();
|
||||
res.json({ ok: true });
|
||||
} catch (e) {
|
||||
achError(res, e, 'Не удалось удалить достижение', 'student achievement delete');
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/students/:id/photos', requireAuth, (req, res, next) => {
|
||||
studentPhotoUpload(req, res, (err) => {
|
||||
if (err) {
|
||||
|
||||
Reference in New Issue
Block a user