Compare commits
2
Commits
2bc96aaecc
...
617ed60e65
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
617ed60e65 | ||
|
|
12034812ec |
+23
-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) {
|
||||
@@ -512,6 +512,7 @@ function normalizeRestoreData(data) {
|
||||
const chat_threads = (data.chat_threads || []).map(x => ({
|
||||
id: reqInt(x.id),
|
||||
tutor_id: reqInt(x.tutor_id),
|
||||
peer_id: optInt(x.peer_id),
|
||||
last_message_at: optTs(x.last_message_at),
|
||||
last_message_text: optStr(x.last_message_text, 300),
|
||||
tutor_unread: optInt(x.tutor_unread, 0, 2147483647) ?? 0,
|
||||
@@ -623,6 +624,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 +713,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 = {
|
||||
|
||||
+29
-2
@@ -398,14 +398,16 @@ CREATE INDEX IF NOT EXISTS idx_notification_reads_user ON notification_reads(use
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chat_threads (
|
||||
id SERIAL PRIMARY KEY,
|
||||
tutor_id INT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
|
||||
tutor_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
peer_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||
last_message_at TIMESTAMPTZ DEFAULT now(),
|
||||
last_message_text VARCHAR(300),
|
||||
tutor_unread INT NOT NULL DEFAULT 0,
|
||||
admin_unread INT NOT NULL DEFAULT 0,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
purge_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ DEFAULT now()
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
UNIQUE (tutor_id, peer_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_chat_threads_last_message ON chat_threads(last_message_at DESC);
|
||||
@@ -684,3 +686,28 @@ 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;
|
||||
INSERT INTO settings (key, value) VALUES ('notify_chat_message', '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);
|
||||
|
||||
+32
-2
@@ -383,18 +383,23 @@ CREATE INDEX IF NOT EXISTS idx_notification_reads_user ON notification_reads(use
|
||||
|
||||
CREATE TABLE IF NOT EXISTS chat_threads (
|
||||
id SERIAL PRIMARY KEY,
|
||||
tutor_id INT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
|
||||
tutor_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
peer_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||
last_message_at TIMESTAMPTZ DEFAULT now(),
|
||||
last_message_text VARCHAR(300),
|
||||
tutor_unread INT NOT NULL DEFAULT 0,
|
||||
admin_unread INT NOT NULL DEFAULT 0,
|
||||
deleted_at TIMESTAMPTZ,
|
||||
purge_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ DEFAULT now()
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
UNIQUE (tutor_id, peer_id)
|
||||
);
|
||||
|
||||
ALTER TABLE chat_threads ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE chat_threads ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ;
|
||||
ALTER TABLE chat_threads DROP CONSTRAINT IF EXISTS chat_threads_tutor_id_key;
|
||||
ALTER TABLE chat_threads ADD COLUMN IF NOT EXISTS peer_id INT REFERENCES users(id) ON DELETE CASCADE;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS idx_chat_threads_pair ON chat_threads (tutor_id, peer_id);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_chat_threads_last_message ON chat_threads(last_message_at DESC);
|
||||
|
||||
@@ -861,6 +866,7 @@ 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;
|
||||
INSERT INTO settings (key, value) VALUES ('notify_chat_message', 'true') ON CONFLICT (key) DO NOTHING;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS broken_images (
|
||||
id SERIAL PRIMARY KEY,
|
||||
@@ -921,3 +927,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,
|
||||
};
|
||||
+21
-2
@@ -14,6 +14,9 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b
|
||||
.user-box .user-meta{display:flex;flex-direction:column;min-width:0;flex:1}
|
||||
.user-box .user-name{font-weight:600;font-size:.85rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text);line-height:1.25}
|
||||
.user-box .user-role{color:var(--muted);font-size:.7rem;font-weight:500;line-height:1.2}
|
||||
.user-box .notify-bell{margin-left:auto;color:var(--muted);text-decoration:none;display:flex;align-items:center;gap:6px;padding:6px 8px;border-radius:8px;transition:all .14s ease}
|
||||
.user-box .notify-bell:hover{color:var(--text);background:var(--bg)}
|
||||
.user-box .notify-bell i{width:16px;height:16px;flex-shrink:0}
|
||||
|
||||
.nav-scroll-wrap{flex:1 1 auto;min-height:0;overflow-y:auto;overflow-x:hidden;overscroll-behavior:contain;padding:8px 0;scrollbar-width:thin;scrollbar-color:rgba(0,0,0,.15) transparent}
|
||||
.nav-scroll-wrap::-webkit-scrollbar{width:5px}
|
||||
@@ -64,7 +67,7 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b
|
||||
.sidebar .bottom-actions a{display:flex;align-items:center;gap:10px;padding:6px 10px;border-radius:8px;color:var(--muted);text-decoration:none;font-size:.82rem;font-weight:500;transition:all .14s ease;position:relative}
|
||||
.sidebar .bottom-actions a:hover{color:var(--text);background:var(--bg)}
|
||||
.sidebar .bottom-actions a[data-nav=home] svg{color:#2563eb}
|
||||
.sidebar .bottom-actions .notify-bell svg{color:#f59e0b}
|
||||
.user-box .notify-bell svg{color:#f59e0b}
|
||||
.sidebar .bottom-footer{display:flex;align-items:center;justify-content:space-between;gap:8px;padding-top:6px;border-top:1px dashed var(--border)}
|
||||
.sidebar .bottom-footer .logout-btn{display:inline-flex;align-items:center;gap:6px;padding:4px 8px;border-radius:6px;color:#ef4444;text-decoration:none;font-size:.78rem;font-weight:600;cursor:pointer;transition:background .14s ease}
|
||||
.sidebar .bottom-footer .logout-btn:hover{background:rgba(239,68,68,.08)}
|
||||
@@ -554,6 +557,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}
|
||||
@@ -937,7 +956,7 @@ body[data-page=settings] .page-head{align-items:flex-end}
|
||||
.notify-bell{position:relative}
|
||||
.notify-badge{position:absolute;left:20px;top:-3px;min-width:16px;height:16px;padding:0 4px;border-radius:999px;background:#ef4444;color:#fff;font-size:.62rem;font-weight:700;line-height:16px;text-align:center}
|
||||
.notify-badge[hidden]{display:none}
|
||||
.notify-panel{position:fixed;left:12px;bottom:96px;width:min(380px,calc(100vw - 24px));max-height:min(70vh,520px);display:flex;flex-direction:column;background:var(--card);border:1px solid var(--border);border-radius:14px;box-shadow:0 18px 40px rgba(0,0,0,.18);z-index:90;overflow:hidden}
|
||||
.notify-panel{position:fixed;width:min(380px,calc(100vw - 24px));max-height:min(70vh,520px);display:flex;flex-direction:column;background:var(--card);border:1px solid var(--border);border-radius:14px;box-shadow:0 18px 40px rgba(0,0,0,.18);z-index:90;overflow:hidden}
|
||||
.notify-panel[hidden]{display:none}
|
||||
.notify-head{display:flex;align-items:center;justify-content:space-between;gap:10px;padding:12px 14px;border-bottom:1px solid var(--border);font-size:.9rem}
|
||||
.notify-list{overflow-y:auto;flex:1}
|
||||
|
||||
+15
-8
@@ -102,6 +102,10 @@ function buildSidebar(active) {
|
||||
<div class="user-name" title="${esc(userName)}">${esc(userName)}</div>
|
||||
<div class="user-role">${roleLabel}</div>
|
||||
</div>
|
||||
<a href="#" class="notify-bell" id="notifyBell" title="Быстрые уведомления" style="margin-left:auto">
|
||||
<i data-lucide="bell"></i>
|
||||
<span class="notify-badge" id="notifyBadge" ${notifyUnread > 0 ? '' : 'hidden'}>${notifyUnread > 99 ? '99+' : notifyUnread}</span>
|
||||
</a>
|
||||
</div>
|
||||
<div class="nav-scroll-wrap">
|
||||
<nav>
|
||||
@@ -122,11 +126,6 @@ function buildSidebar(active) {
|
||||
</div>
|
||||
<div class="bottom">
|
||||
<div class="bottom-actions">
|
||||
<a href="#" class="notify-bell" id="notifyBell" title="Быстрые уведомления">
|
||||
<i data-lucide="bell"></i>
|
||||
<span>Уведомления</span>
|
||||
<span class="notify-badge" id="notifyBadge" ${notifyUnread > 0 ? '' : 'hidden'}>${notifyUnread > 99 ? '99+' : notifyUnread}</span>
|
||||
</a>
|
||||
<a href="/" data-nav="home" title="Перейти на главную страницу">
|
||||
<i data-lucide="home"></i>
|
||||
<span>На главную</span>
|
||||
@@ -202,6 +201,7 @@ const NOTIFY_ICONS = {
|
||||
'face.scan.done': 'scan-face',
|
||||
'face.recognized': 'user-round-check',
|
||||
'face.scan.error': 'scan-search',
|
||||
'chat.message': 'bell',
|
||||
};
|
||||
const NOTIFY_LEVELS = { warning: 'Предупреждение', critical: 'Важно', info: '' };
|
||||
|
||||
@@ -363,7 +363,14 @@ function toggleNotifyPanel(force) {
|
||||
if (!panel) return;
|
||||
const open = force === undefined ? panel.hidden : !!force;
|
||||
panel.hidden = !open;
|
||||
if (open) { renderNotifyPanel(); loadNotifications(); }
|
||||
if (open) {
|
||||
const bell = document.getElementById('notifyBell');
|
||||
const rect = bell ? bell.getBoundingClientRect() : null;
|
||||
panel.style.left = rect ? (rect.right + 8) + 'px' : '240px';
|
||||
panel.style.top = rect ? rect.top + 'px' : '80px';
|
||||
renderNotifyPanel();
|
||||
loadNotifications();
|
||||
}
|
||||
}
|
||||
async function markNotifyRead(id) {
|
||||
const item = notifyList.find(n => n.id === id);
|
||||
@@ -457,7 +464,6 @@ function initNotifications() {
|
||||
const bell = document.getElementById('notifyBell');
|
||||
const panel = notifyPanelEl();
|
||||
if (!bell || !panel) return;
|
||||
bell.addEventListener('click', e => { e.preventDefault(); toggleNotifyPanel(); });
|
||||
panel.addEventListener('click', e => {
|
||||
if (e.target.closest('#notifyReadAll')) { markAllNotifyRead(); return; }
|
||||
if (e.target.closest('#notifyDesktopToggle')) { toggleDesktopNotifications(); return; }
|
||||
@@ -471,8 +477,9 @@ function initNotifications() {
|
||||
if (link) location.href = link;
|
||||
});
|
||||
document.addEventListener('click', e => {
|
||||
if (e.target.closest('#notifyBell')) { e.preventDefault(); toggleNotifyPanel(); return; }
|
||||
if (panel.hidden) return;
|
||||
if (e.target.closest('#notifyPanel') || e.target.closest('#notifyBell')) return;
|
||||
if (e.target.closest('#notifyPanel')) return;
|
||||
toggleNotifyPanel(false);
|
||||
});
|
||||
document.addEventListener('keydown', e => { if (e.key === 'Escape' && !panel.hidden) toggleNotifyPanel(false); });
|
||||
|
||||
+13
-3
@@ -5,6 +5,14 @@
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Чаты — Админ-панель</title>
|
||||
<link rel="stylesheet" href="admin.css">
|
||||
<style>
|
||||
.chat-new-user-list{position:absolute;z-index:50;left:0;right:0;top:100%;max-height:240px;overflow:auto;background:#fff;border:1px solid var(--border,#ddd);border-radius:8px;margin-top:4px;box-shadow:0 6px 20px rgba(0,0,0,.12)}
|
||||
.chat-new-user-item{padding:8px 12px;cursor:pointer;display:flex;flex-direction:column}
|
||||
.chat-new-user-item:hover,.chat-new-user-item.active{background:var(--hover,#f0f4ff)}
|
||||
.chat-new-user-item .cn-name{font-weight:600}
|
||||
.chat-new-user-item .cn-sub{font-size:12px;opacity:.7}
|
||||
.chat-new-modal .settings-field{position:relative}
|
||||
</style>
|
||||
</head>
|
||||
<body data-page="chat">
|
||||
<div class="layout">
|
||||
@@ -23,7 +31,7 @@
|
||||
<span class="chat-side-title">Диалоги</span>
|
||||
<span class="grow"></span>
|
||||
<button class="btn-primary ghost chat-side-toggle" id="chatHiddenBtn" type="button" hidden title="Показать скрытые диалоги"><i data-lucide="archive"></i><span class="chat-hidden-count" id="chatHiddenCount" hidden></span></button>
|
||||
<button class="btn-primary ghost chat-new-btn" id="chatNewBtn" type="button" hidden title="Начать диалог с тьютором"><i data-lucide="user-plus"></i> Начать диалог</button>
|
||||
<button class="btn-primary ghost chat-new-btn" id="chatNewBtn" type="button" title="Начать диалог"><i data-lucide="user-plus"></i> Начать диалог</button>
|
||||
</div>
|
||||
<div class="chat-side-hint" id="chatHiddenHint" hidden>Скрытые диалоги. Новое сообщение от тьютора вернёт диалог в список.</div>
|
||||
<div class="chat-thread-list" id="chatThreadList"></div>
|
||||
@@ -77,8 +85,10 @@
|
||||
<div class="edit-modal chat-new-modal">
|
||||
<h3>Начать диалог</h3>
|
||||
<div class="settings-field">
|
||||
<label>Тьютор</label>
|
||||
<select id="chatNewUser" class="settings-input"></select>
|
||||
<label>Собеседник</label>
|
||||
<input id="chatNewUser" class="settings-input" type="text" placeholder="Поиск по имени или логину…" autocomplete="off" />
|
||||
<div id="chatNewUserList" class="chat-new-user-list" hidden></div>
|
||||
<input id="chatNewUserId" type="hidden" />
|
||||
</div>
|
||||
<div class="card-foot" style="justify-content:flex-end;gap:8px">
|
||||
<button type="button" class="btn-primary ghost" id="chatNewCancel">Отмена</button>
|
||||
|
||||
+102
-29
@@ -64,10 +64,23 @@ function chatThreadTime(ts) {
|
||||
return fmtDateShort(d);
|
||||
}
|
||||
|
||||
function chatThreadPeer(t) {
|
||||
const me = (typeof currentUser !== 'undefined' && currentUser) ? currentUser.id : null;
|
||||
const amA = me != null && Number(me) === Number(t.tutor_id);
|
||||
if (amA) {
|
||||
if (t.peer_id != null) {
|
||||
return { name: t.peer_name || t.peer_username, username: t.peer_username, active: t.peer_active !== false };
|
||||
}
|
||||
return { name: 'Администратор', username: '', active: true };
|
||||
}
|
||||
// current user is B or admin: show participant A
|
||||
return { name: t.tutor_name || t.tutor_username, username: t.tutor_username, active: t.tutor_active !== false };
|
||||
}
|
||||
function chatThreadCardHtml(t) {
|
||||
const active = t.id === chatActiveId ? ' active' : '';
|
||||
const unread = Number(t.unread) || 0;
|
||||
const preview = (t.last_message_text || '').trim() || 'Нет сообщений';
|
||||
const peer = chatThreadPeer(t);
|
||||
const hidden = t.deleted_at ? ' is-hidden' : '';
|
||||
const acts = isAdmin() ? (t.deleted_at
|
||||
? `<span class="chat-thread-acts">
|
||||
@@ -78,11 +91,11 @@ function chatThreadCardHtml(t) {
|
||||
<button type="button" class="chat-thread-act" data-thread-hide="${t.id}" title="Скрыть диалог"><i data-lucide="archive"></i></button>
|
||||
</span>`) : '';
|
||||
return `<div class="chat-thread${active}${hidden}${unread ? ' unread' : ''}" data-thread="${t.id}" role="button" tabindex="0">
|
||||
<span class="chat-thread-avatar">${esc((t.tutor_name || '?').slice(0, 1).toUpperCase())}</span>
|
||||
<span class="chat-thread-avatar">${esc((peer.name || '?').slice(0, 1).toUpperCase())}</span>
|
||||
<span class="chat-thread-body">
|
||||
<span class="chat-thread-top">
|
||||
<span class="chat-thread-name">${esc(t.tutor_name || t.tutor_username)}</span>
|
||||
${t.tutor_active === false ? '<span class="chat-off" title="Пользователь отключён">отключён</span>' : ''}
|
||||
<span class="chat-thread-name">${esc(peer.name || peer.username)}</span>
|
||||
${peer.active === false ? '<span class="chat-off" title="Пользователь отключён">отключён</span>' : ''}
|
||||
${t.deleted_at ? '<span class="chat-off chat-hidden-tag" title="Диалог скрыт">скрыт</span>' : ''}
|
||||
<span class="grow"></span>
|
||||
<span class="chat-thread-time">${esc(chatThreadTime(t.last_message_at || t.created_at))}</span>
|
||||
@@ -331,15 +344,14 @@ function renderChatHeader() {
|
||||
}
|
||||
if (empty) empty.hidden = true;
|
||||
if (main) main.hidden = false;
|
||||
const peer = chatThreadPeer(thread);
|
||||
const av = document.getElementById('chatAvatar');
|
||||
const nm = document.getElementById('chatPeerName');
|
||||
const sub = document.getElementById('chatPeerSub');
|
||||
if (av) av.textContent = (thread.tutor_name || '?').slice(0, 1).toUpperCase();
|
||||
if (nm) nm.textContent = isAdmin() ? (thread.tutor_name || thread.tutor_username) : 'Администратор';
|
||||
if (av) av.textContent = (peer.name || '?').slice(0, 1).toUpperCase();
|
||||
if (nm) nm.textContent = peer.name || peer.username || 'диалог';
|
||||
if (sub) {
|
||||
sub.textContent = isAdmin()
|
||||
? `@${thread.tutor_username}${thread.tutor_active === false ? ' · отключён' : ''}`
|
||||
: 'Ответ администратора';
|
||||
sub.textContent = `@${peer.username || ''}${peer.active === false ? ' · отключён' : ''}`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -499,6 +511,7 @@ function selectChatThread(id) {
|
||||
clearChatReply();
|
||||
renderChatThreads();
|
||||
loadChatMessages();
|
||||
markChatRead();
|
||||
}
|
||||
|
||||
function onChatMessage(p) {
|
||||
@@ -656,23 +669,58 @@ async function deleteChatMessage(messageId) {
|
||||
}
|
||||
}
|
||||
|
||||
async function openChatNewModal() {
|
||||
const modal = document.getElementById('chatNewModal');
|
||||
const select = document.getElementById('chatNewUser');
|
||||
if (!modal || !select) return;
|
||||
try {
|
||||
const users = await chatApi('/api/users', { headers: hdr() });
|
||||
const tutors = (users || []).filter(u => u.role !== 'admin' && u.is_active !== false);
|
||||
const known = new Set(chatThreads.map(t => t.tutor_id));
|
||||
const rest = tutors.filter(u => !known.has(u.id));
|
||||
const pool = rest.length ? rest : tutors;
|
||||
select.innerHTML = pool.map(u => `<option value="${u.id}">${esc(u.name || u.username)} (@${esc(u.username)})</option>`).join('')
|
||||
|| '<option value="">Нет доступных тьюторов</option>';
|
||||
} catch (e) {
|
||||
showToast(e.message || 'Не удалось загрузить пользователей', true);
|
||||
let chatNewSearchTimer = null;
|
||||
let chatNewSelectedId = null;
|
||||
|
||||
function chatNewRenderResults(items) {
|
||||
const list = document.getElementById('chatNewUserList');
|
||||
const input = document.getElementById('chatNewUser');
|
||||
if (!list) return;
|
||||
if (!items || !items.length) {
|
||||
list.hidden = true;
|
||||
list.innerHTML = '';
|
||||
return;
|
||||
}
|
||||
list.innerHTML = items.map(u => `
|
||||
<div class="chat-new-user-item" data-uid="${u.id}">
|
||||
<span class="cn-name">${esc(u.name || u.username)}</span>
|
||||
<span class="cn-sub">@${esc(u.username)}${u.role ? ' · ' + esc(u.role) : ''}</span>
|
||||
</div>`).join('');
|
||||
list.hidden = false;
|
||||
list.querySelectorAll('.chat-new-user-item').forEach(el => {
|
||||
el.addEventListener('click', () => {
|
||||
const id = Number(el.dataset.uid);
|
||||
const item = items.find(x => Number(x.id) === id);
|
||||
if (!item) return;
|
||||
chatNewSelectedId = id;
|
||||
if (input) input.value = `${item.name || item.username} (@${item.username})`;
|
||||
list.hidden = true;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function chatNewSearch(q) {
|
||||
try {
|
||||
const items = await chatApi('/api/users/search?q=' + encodeURIComponent(q || ''), { headers: hdr() });
|
||||
chatNewRenderResults(items || []);
|
||||
} catch (e) {
|
||||
chatNewRenderResults([]);
|
||||
}
|
||||
}
|
||||
|
||||
async function openChatNewModal() {
|
||||
const modal = document.getElementById('chatNewModal');
|
||||
const input = document.getElementById('chatNewUser');
|
||||
const hidden = document.getElementById('chatNewUserId');
|
||||
if (!modal || !input) return;
|
||||
chatNewSelectedId = null;
|
||||
if (hidden) hidden.value = '';
|
||||
input.value = '';
|
||||
const list = document.getElementById('chatNewUserList');
|
||||
if (list) { list.hidden = true; list.innerHTML = ''; }
|
||||
modal.classList.add('open');
|
||||
if (input) input.focus();
|
||||
chatNewSearch('');
|
||||
}
|
||||
|
||||
async function sendChatMessage() {
|
||||
@@ -715,11 +763,11 @@ async function sendChatMessage() {
|
||||
}
|
||||
|
||||
async function submitChatNew() {
|
||||
const select = document.getElementById('chatNewUser');
|
||||
const input = document.getElementById('chatNewUser');
|
||||
const modal = document.getElementById('chatNewModal');
|
||||
const userId = Number(select.value);
|
||||
const userId = chatNewSelectedId || Number((document.getElementById('chatNewUserId') || {}).value);
|
||||
if (!userId) {
|
||||
showToast('Выберите тьютора', true);
|
||||
showToast('Выберите собеседника', true);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
@@ -864,6 +912,31 @@ function initChatPage() {
|
||||
newModal.addEventListener('click', e => { if (e.target === newModal) newModal.classList.remove('open'); });
|
||||
}
|
||||
if (newOk) newOk.addEventListener('click', submitChatNew);
|
||||
const newUserInput = document.getElementById('chatNewUser');
|
||||
const newUserList = document.getElementById('chatNewUserList');
|
||||
if (newUserInput) {
|
||||
newUserInput.addEventListener('input', () => {
|
||||
chatNewSelectedId = null;
|
||||
const v = newUserInput.value.trim();
|
||||
clearTimeout(chatNewSearchTimer);
|
||||
chatNewSearchTimer = setTimeout(() => chatNewSearch(v), 200);
|
||||
});
|
||||
newUserInput.addEventListener('focus', () => {
|
||||
if (!newUserList || !newUserList.hidden) return;
|
||||
chatNewSearch(newUserInput.value.trim());
|
||||
});
|
||||
}
|
||||
if (newUserList) {
|
||||
newUserList.addEventListener('click', e => {
|
||||
const item = e.target.closest('.chat-new-user-item');
|
||||
if (!item) return;
|
||||
const id = Number(item.dataset.uid);
|
||||
const txt = item.querySelector('.cn-name')?.textContent || '';
|
||||
chatNewSelectedId = id;
|
||||
if (newUserInput) newUserInput.value = txt;
|
||||
newUserList.hidden = true;
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('paste', e => {
|
||||
if (!chatActiveId) return;
|
||||
@@ -900,13 +973,13 @@ function initChatPage() {
|
||||
imgModal.addEventListener('click', e => e.currentTarget.classList.remove('open'));
|
||||
}
|
||||
|
||||
if (newBtn) newBtn.hidden = !isAdmin();
|
||||
if (newBtn) newBtn.hidden = false;
|
||||
const side = document.getElementById('chatSide');
|
||||
const layout = document.getElementById('chatLayout');
|
||||
if (!isAdmin() && side) side.hidden = true;
|
||||
if (!isAdmin() && layout) layout.classList.add('chat-layout-solo');
|
||||
if (side) side.hidden = false;
|
||||
if (layout) layout.classList.remove('chat-layout-solo');
|
||||
const emptySub = document.querySelector('#chatEmpty .chat-empty-sub');
|
||||
if (emptySub && !isAdmin()) emptySub.textContent = 'Напишите администратору — сообщения доставятся мгновенно';
|
||||
if (emptySub && !isAdmin()) emptySub.textContent = 'Выберите диалог или начните новый — можно писать любому пользователю';
|
||||
|
||||
loadChatThreads().then(async () => {
|
||||
if (!isAdmin()) {
|
||||
|
||||
@@ -7,6 +7,13 @@ let studentsLoaded = false;
|
||||
let sourcesLoaded = false;
|
||||
let searchTimer = null;
|
||||
|
||||
const FACE_CANDIDATE_MIN = 0.5;
|
||||
let faceViewer = { sourceType: 'group', photoId: null, photoPath: '', faces: [], layout: null, candidateMin: FACE_CANDIDATE_MIN };
|
||||
let faceAssignFaceId = null;
|
||||
let allStudents = [];
|
||||
let allStudentsLoaded = false;
|
||||
let faceScanLiveSource = null;
|
||||
|
||||
function humanSize(b) {
|
||||
if (!b) return '';
|
||||
if (b < 1024) return b + ' Б';
|
||||
@@ -36,9 +43,11 @@ function photoCardHTML(p) {
|
||||
if (p.group_name) meta.push(esc(p.group_name));
|
||||
const link = photoLink(p);
|
||||
const canFix = isAdmin() && p.photo_key && p.photo_id != null;
|
||||
const canFaces = !!(p.face_source_type && p.face_photo_id != null);
|
||||
return `
|
||||
<div class="ph-card">
|
||||
<img src="${esc(photoThumb(url))}" data-img="${esc(url)}" loading="lazy" decoding="async" alt="" onerror="photoImgError(this)">
|
||||
${canFaces ? `<button type="button" class="btn-link ph-faces-btn" data-fv-source="${esc(p.face_source_type)}" data-fv-id="${esc(p.face_photo_id)}" data-fv-path="${esc(url)}" title="Распознанные лица"><i data-lucide="scan-face"></i></button>` : ''}
|
||||
<div class="ph-body">
|
||||
<span class="ph-badge">${esc(p.source_label)}</span>
|
||||
<div class="ph-title">${esc(p.title || 'Без описания')}</div>
|
||||
@@ -140,6 +149,7 @@ async function loadPhotos() {
|
||||
totalPhotos = srcFilter ? currentPhotos.length : data.total;
|
||||
fillSourceOptions();
|
||||
renderGrid();
|
||||
if (typeof renderIcons === 'function') renderIcons();
|
||||
renderPager(document.getElementById('pager'), page, Math.max(1, Math.ceil(totalPhotos / PAGE_SIZE)), goPage);
|
||||
}
|
||||
|
||||
@@ -148,6 +158,210 @@ function goPage(p) {
|
||||
loadPhotos();
|
||||
}
|
||||
|
||||
const faceCandidateMin = () => (Number(faceViewer.candidateMin) > 0 ? Number(faceViewer.candidateMin) : FACE_CANDIDATE_MIN);
|
||||
|
||||
async function loadFaceViewerFaces(sourceType, photoId) {
|
||||
const res = await fetch(`${API}/api/photos/${sourceType}/${photoId}/faces`, { headers: hdr() });
|
||||
if (!res.ok) throw new Error('faces');
|
||||
const data = await res.json();
|
||||
faceViewer.faces = data.faces || [];
|
||||
faceViewer.candidateMin = Number(data.candidate_min) > 0 ? Number(data.candidate_min) : FACE_CANDIDATE_MIN;
|
||||
faceViewer.imgWidth = Number(data.img_width) || 0;
|
||||
faceViewer.imgHeight = Number(data.img_height) || 0;
|
||||
faceViewer.scanned = Boolean(data.scanned);
|
||||
return faceViewer;
|
||||
}
|
||||
|
||||
function faceViewerWarn(msg) {
|
||||
const el = document.getElementById('faceViewerWarn');
|
||||
if (!el) return;
|
||||
if (msg) { el.textContent = msg; el.hidden = false; }
|
||||
else { el.textContent = ''; el.hidden = true; }
|
||||
}
|
||||
|
||||
function checkFaceViewerSync(nw, nh) {
|
||||
if (!faceViewer.imgWidth || !faceViewer.imgHeight) return;
|
||||
if (faceViewer.imgWidth === nw && faceViewer.imgHeight === nh) { faceViewerWarn(''); return; }
|
||||
faceViewerWarn(`Рамки рассчитаны для ${faceViewer.imgWidth}×${faceViewer.imgHeight}px, а текущее фото ${nw}×${nh}px. Нажмите «Переиндексировать», чтобы пересчитать.`);
|
||||
}
|
||||
|
||||
function faceBoxesHTML(nw, nh) {
|
||||
return faceViewer.faces.map(f => {
|
||||
const left = (f.x / nw) * 100;
|
||||
const top = (f.y / nh) * 100;
|
||||
const width = (f.w / nw) * 100;
|
||||
const height = (f.h / nh) * 100;
|
||||
let cls = 'face-box--unassigned';
|
||||
let label = 'Не опознано';
|
||||
if (f.student_id) {
|
||||
cls = 'face-box--matched';
|
||||
label = f.manual ? `${esc(f.student_name || '')} · вручную` : `${esc(f.student_name || '')} · ${Math.round((f.confidence || 0) * 100)}%`;
|
||||
} else if (f.best_student_id && f.best_score >= faceCandidateMin()) {
|
||||
cls = 'face-box--candidate';
|
||||
label = `Похож: ${esc(f.best_student_name || '')} · ${Math.round((f.best_score || 0) * 100)}%`;
|
||||
}
|
||||
return `<button type="button" class="face-box ${cls}" data-face-box="${f.id}" style="left:${left}%;top:${top}%;width:${width}%;height:${height}%" title="${esc(label)}"><span class="face-box-label">${label}</span></button>`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
function renderFaceViewer(photoPath) {
|
||||
if (faceViewer.layout) window.removeEventListener('resize', faceViewer.layout);
|
||||
const body = document.getElementById('faceViewerBody');
|
||||
if (!body) return;
|
||||
body.innerHTML = `<div class="face-stage"><img id="faceStageImg" src="${esc(API + photoPath)}" data-img="${esc(photoPath)}" alt=""><div class="face-overlay" id="faceOverlay"></div></div>`;
|
||||
const img = document.getElementById('faceStageImg');
|
||||
const overlay = document.getElementById('faceOverlay');
|
||||
const stage = img.parentElement;
|
||||
const layout = () => {
|
||||
const nw = img.naturalWidth || 0;
|
||||
const nh = img.naturalHeight || 0;
|
||||
if (!nw || !nh) return;
|
||||
overlay.style.width = img.clientWidth + 'px';
|
||||
overlay.style.height = img.clientHeight + 'px';
|
||||
overlay.innerHTML = faceViewer.faces.length ? faceBoxesHTML(nw, nh) : '<div class="empty">Лиц не найдено</div>';
|
||||
checkFaceViewerSync(nw, nh);
|
||||
if (typeof renderIcons === 'function') renderIcons();
|
||||
};
|
||||
faceViewer.layout = layout;
|
||||
window.addEventListener('resize', layout);
|
||||
img.addEventListener('load', layout);
|
||||
if (img.complete) layout();
|
||||
}
|
||||
|
||||
async function refreshOpenFaceViewer() {
|
||||
const photoId = faceViewer.photoId;
|
||||
if (!photoId) return;
|
||||
try {
|
||||
await loadFaceViewerFaces(faceViewer.sourceType, photoId);
|
||||
renderFaceViewer(faceViewer.photoPath);
|
||||
} catch { /* ignore */ }
|
||||
}
|
||||
|
||||
function closeFaceViewer() {
|
||||
if (faceViewer.layout) window.removeEventListener('resize', faceViewer.layout);
|
||||
faceViewer.layout = null;
|
||||
faceViewer.photoId = null;
|
||||
faceViewer.photoPath = '';
|
||||
const m = document.getElementById('faceViewerModal');
|
||||
if (m) m.classList.remove('open');
|
||||
}
|
||||
|
||||
async function openFaceViewer(sourceType, photoId, photoPath) {
|
||||
if (faceViewer.layout) window.removeEventListener('resize', faceViewer.layout);
|
||||
faceViewer = { sourceType, photoId, photoPath, faces: [], layout: null, candidateMin: FACE_CANDIDATE_MIN };
|
||||
const body = document.getElementById('faceViewerBody');
|
||||
if (body) body.innerHTML = '<div class="empty">Загрузка...</div>';
|
||||
faceViewerWarn('');
|
||||
document.getElementById('faceViewerModal').classList.add('open');
|
||||
try {
|
||||
await loadFaceViewerFaces(sourceType, photoId);
|
||||
renderFaceViewer(photoPath);
|
||||
} catch (e) {
|
||||
if (body) body.innerHTML = `<div class="empty">${e.status === 404 ? 'Фото не найдено' : 'Не удалось загрузить лица'}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAllStudents() {
|
||||
if (allStudentsLoaded) return;
|
||||
try {
|
||||
const res = await fetch(`${API}/api/students?limit=10000`, { headers: hdr() });
|
||||
const data = res.ok ? await res.json() : [];
|
||||
const list = Array.isArray(data) ? data : (data && data.students) || [];
|
||||
allStudents = list.filter(s => !s.deleted_at).map(s => ({ id: s.id, name: s.name, group_id: s.group_id, group_name: s.group_name || s.group }));
|
||||
allStudentsLoaded = true;
|
||||
} catch { allStudents = []; }
|
||||
}
|
||||
|
||||
function renderFaceAssignList(q) {
|
||||
const list = document.getElementById('faceAssignList');
|
||||
if (!list) return;
|
||||
const query = (q || '').trim().toLowerCase();
|
||||
const filtered = allStudents.filter(s => {
|
||||
if (!query) return true;
|
||||
return (s.name || '').toLowerCase().includes(query) || (s.group_name || '').toLowerCase().includes(query);
|
||||
}).sort((a, b) => {
|
||||
// photos page has no "current group" concept; keep id order
|
||||
return String(a.name).localeCompare(String(b.name), 'ru');
|
||||
});
|
||||
list.innerHTML = filtered.map(s => `
|
||||
<button type="button" class="attach-item" data-face-pick="${s.id}">
|
||||
<span class="attach-name">${esc(s.name)}</span>
|
||||
<span class="attach-sub">${esc(s.group_name || '')}</span>
|
||||
</button>
|
||||
`).join('');
|
||||
if (typeof renderIcons === 'function') renderIcons();
|
||||
}
|
||||
|
||||
function openFaceAssign(faceId) {
|
||||
faceAssignFaceId = faceId;
|
||||
const face = faceViewer.faces.find(f => String(f.id) === String(faceId));
|
||||
const inp = document.getElementById('faceAssignSearch');
|
||||
if (inp) inp.value = (face && !face.student_id && face.best_student_id && face.best_score >= faceCandidateMin()) ? (face.best_student_name || '') : '';
|
||||
loadAllStudents().then(() => renderFaceAssignList(inp ? inp.value : ''));
|
||||
document.getElementById('faceAssignModal').classList.add('open');
|
||||
}
|
||||
|
||||
async function assignFace(studentId) {
|
||||
if (!faceAssignFaceId) return;
|
||||
try {
|
||||
const res = await fetch(`${API}/api/photo-faces/${faceAssignFaceId}/assign`, {
|
||||
method: 'PUT',
|
||||
headers: { ...hdr(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ student_id: studentId || 0 })
|
||||
});
|
||||
if (!res.ok) throw new Error('assign');
|
||||
document.getElementById('faceAssignModal').classList.remove('open');
|
||||
faceAssignFaceId = null;
|
||||
await refreshOpenFaceViewer();
|
||||
loadPhotos();
|
||||
} catch { showToast('Не удалось привязать лицо'); }
|
||||
}
|
||||
|
||||
async function rescanFaceViewerPhoto() {
|
||||
const photoId = faceViewer.photoId;
|
||||
const sourceType = faceViewer.sourceType;
|
||||
if (!photoId || !sourceType) return;
|
||||
const btn = document.getElementById('faceViewerRescanBtn');
|
||||
if (btn) { btn.disabled = true; btn.textContent = 'В очередь...'; }
|
||||
try {
|
||||
const res = await fetch(`${API}/api/photos/${sourceType}/${photoId}/faces/rescan`, {
|
||||
method: 'POST',
|
||||
headers: { ...hdr(), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({})
|
||||
});
|
||||
if (!res.ok) throw new Error('rescan');
|
||||
showToast('Фото поставлено в очередь проверки — рамки обновятся автоматически');
|
||||
loadPhotos();
|
||||
} catch { showToast('Не удалось поставить в очередь'); }
|
||||
finally {
|
||||
if (btn) { btn.disabled = false; btn.textContent = 'Переиндексировать'; }
|
||||
}
|
||||
}
|
||||
|
||||
function connectFaceScanLive() {
|
||||
if (faceScanLiveSource) { faceScanLiveSource.close(); faceScanLiveSource = null; }
|
||||
const connect = () => {
|
||||
const t = sessionStorage.getItem('authToken');
|
||||
if (!t) return;
|
||||
faceScanLiveSource = new EventSource(`${API}/api/events?token=${encodeURIComponent(t)}`);
|
||||
faceScanLiveSource.addEventListener('face_scan_status', ev => {
|
||||
let p = null;
|
||||
try { p = JSON.parse(ev.data); } catch { return; }
|
||||
if (!p || p.status === 'processing' || p.status === 'pending') return;
|
||||
if (Number(p.source_id) === Number(faceViewer.photoId) && faceViewer.photoId) {
|
||||
refreshOpenFaceViewer();
|
||||
loadPhotos();
|
||||
}
|
||||
});
|
||||
faceScanLiveSource.onerror = () => {
|
||||
if (faceScanLiveSource) { faceScanLiveSource.close(); faceScanLiveSource = null; }
|
||||
setTimeout(connect, 5000);
|
||||
};
|
||||
};
|
||||
connect();
|
||||
window.addEventListener('beforeunload', () => { if (faceScanLiveSource) faceScanLiveSource.close(); });
|
||||
}
|
||||
|
||||
document.getElementById('studentFilter').addEventListener('change', () => { page = 1; loadPhotos(); });
|
||||
document.getElementById('groupFilter').addEventListener('change', () => { page = 1; loadPhotos(); });
|
||||
document.getElementById('sourceFilter').addEventListener('change', () => { page = 1; loadPhotos(); });
|
||||
@@ -161,7 +375,28 @@ document.getElementById('searchInput').addEventListener('input', () => {
|
||||
|
||||
document.getElementById('imgModal').addEventListener('click', e => e.currentTarget.classList.remove('open'));
|
||||
|
||||
document.getElementById('faceViewerCloseBtn')?.addEventListener('click', closeFaceViewer);
|
||||
document.getElementById('faceViewerRescanBtn')?.addEventListener('click', rescanFaceViewerPhoto);
|
||||
document.getElementById('faceViewerModal')?.addEventListener('click', e => { if (e.target === e.currentTarget) closeFaceViewer(); });
|
||||
document.getElementById('faceViewerBody')?.addEventListener('click', e => {
|
||||
const box = e.target.closest('[data-face-box]');
|
||||
if (box) openFaceAssign(box.dataset.faceBox);
|
||||
});
|
||||
document.getElementById('faceAssignCancelBtn')?.addEventListener('click', () => document.getElementById('faceAssignModal').classList.remove('open'));
|
||||
document.getElementById('faceAssignModal')?.addEventListener('click', e => { if (e.target === e.currentTarget) e.currentTarget.classList.remove('open'); });
|
||||
document.getElementById('faceAssignList')?.addEventListener('click', e => {
|
||||
const pick = e.target.closest('[data-face-pick]');
|
||||
if (pick) assignFace(parseInt(pick.dataset.facePick, 10));
|
||||
});
|
||||
document.getElementById('faceUnassignBtn')?.addEventListener('click', () => assignFace(0));
|
||||
document.getElementById('faceAssignSearch')?.addEventListener('input', e => renderFaceAssignList(e.target.value));
|
||||
|
||||
document.getElementById('grid').addEventListener('click', async e => {
|
||||
const facesBtn = e.target.closest('[data-fv-source]');
|
||||
if (facesBtn) {
|
||||
openFaceViewer(facesBtn.dataset.fvSource, parseInt(facesBtn.dataset.fvId, 10), facesBtn.dataset.fvPath);
|
||||
return;
|
||||
}
|
||||
const btn = e.target.closest('[data-quarantine]');
|
||||
if (!btn) return;
|
||||
if (await quarantineBrokenPhoto(btn.dataset.quarantine, btn.dataset.quarantineId)) loadPhotos();
|
||||
@@ -173,5 +408,6 @@ document.getElementById('grid').addEventListener('click', async e => {
|
||||
await loadGroupOptions();
|
||||
await loadStudentOptions();
|
||||
loadPhotos();
|
||||
connectFaceScanLive();
|
||||
}
|
||||
})();
|
||||
|
||||
+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();
|
||||
|
||||
@@ -20,6 +20,10 @@
|
||||
.ph-card.ph-broken img{filter:grayscale(1);opacity:.55;cursor:default}
|
||||
.ph-broken-tag{align-self:flex-start;background:rgba(239,68,68,.12);border:1px solid rgba(239,68,68,.35);color:#ef4444;border-radius:999px;padding:2px 8px;font-size:.68rem;font-weight:700}
|
||||
.ph-broken-btn{align-self:flex-start}
|
||||
.ph-card{position:relative}
|
||||
.ph-faces-btn{position:absolute;top:6px;right:6px;display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;padding:0;border-radius:6px;background:rgba(0,0,0,.55);color:#fff;font-size:.7rem;line-height:1;backdrop-filter:blur(2px)}
|
||||
.ph-faces-btn:hover{background:rgba(0,0,0,.75)}
|
||||
.ph-faces-btn svg,.ph-faces-btn i{width:14px;height:14px}
|
||||
</style>
|
||||
</head>
|
||||
<body data-page="photos">
|
||||
@@ -41,6 +45,34 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="faceViewerModal">
|
||||
<div class="edit-modal" style="max-width:1000px;width:96%;max-height:94dvh">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:12px">
|
||||
<h3 style="font-size:1.05rem;font-weight:600">Распознанные лица</h3>
|
||||
<div style="display:flex;align-items:center;gap:8px">
|
||||
<button type="button" class="btn-primary ghost" id="faceViewerRescanBtn" title="Распознать лица заново на текущем разрешении фото">Переиндексировать</button>
|
||||
<button type="button" class="btn-primary ghost" id="faceViewerCloseBtn">Закрыть</button>
|
||||
</div>
|
||||
</div>
|
||||
<div id="faceViewerWarn" hidden style="margin-bottom:10px;padding:8px 10px;border-radius:8px;background:rgba(245,158,11,.14);border:1px solid rgba(245,158,11,.5);font-size:.84rem;color:#f59e0b"></div>
|
||||
<div id="faceViewerBody" style="display:flex;justify-content:center"></div>
|
||||
<p class="hint" style="margin-top:10px">Синяя рамка — лицо привязано автоматически, в подписи процент сходства; «вручную» — привязано вами. Оранжевая пунктирная — похоже на известного ученика, но сходство ниже порога. Серая — не опознано. Клик по любой рамке — привязать или сменить ученика.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="faceAssignModal">
|
||||
<div class="edit-modal" style="max-width:460px">
|
||||
<h3 style="font-size:1.05rem;font-weight:600;margin-bottom:12px">Привязать лицо к ученику</h3>
|
||||
<input type="text" id="faceAssignSearch" class="settings-input" placeholder="Поиск ученика или группы..." autocomplete="off">
|
||||
<p class="hint" style="margin:6px 0 0">Поиск по всем группам — на фото может быть ученик из другой группы. Сначала идут ученики текущей группы.</p>
|
||||
<div class="attach-list" id="faceAssignList" style="margin-top:10px;max-height:44vh;overflow:auto"></div>
|
||||
<div class="card-foot" style="justify-content:flex-end;gap:8px;margin-top:12px">
|
||||
<button type="button" class="btn-primary ghost" id="faceUnassignBtn">Снять привязку</button>
|
||||
<button type="button" class="btn-primary ghost" id="faceAssignCancelBtn">Отмена</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="imgModal">
|
||||
<img id="imgModalSrc">
|
||||
</div>
|
||||
|
||||
@@ -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');
|
||||
@@ -316,6 +334,7 @@ const NOTIFY_TYPES = {
|
||||
'face.scan.done': { label: 'Найдены лица на фото', hint: 'Фоновая проверка нашла лица на загруженном фото. Сколько именно — в тексте уведомления', icon: 'scan-face', level: 'info', enabled: false, admin: false },
|
||||
'face.recognized': { label: 'Ученики распознаны на фото', hint: 'Фоновая проверка сопоставила лица с эталонами и назвала учеников', icon: 'user-round-check', level: 'info', enabled: true, admin: false },
|
||||
'face.scan.error': { label: 'Ошибка проверки лиц', hint: 'Сервис face-id недоступен или очередь проверки исчерпала попытки', icon: 'scan-search', level: 'warning', enabled: true, admin: false },
|
||||
'chat.message': { label: 'Новое сообщение в чате', hint: 'Тьютор написал в личный чат администрации', icon: 'bell', level: 'info', enabled: true, admin: true },
|
||||
};
|
||||
|
||||
function notifySettingKey(type) {
|
||||
@@ -551,16 +570,21 @@ function chatUploadFilter(req, file, cb) {
|
||||
async function ensureChatTables() {
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS chat_threads (
|
||||
id SERIAL PRIMARY KEY,
|
||||
tutor_id INT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
|
||||
tutor_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
peer_id INT REFERENCES users(id) ON DELETE CASCADE,
|
||||
last_message_at TIMESTAMPTZ DEFAULT now(),
|
||||
last_message_text VARCHAR(300),
|
||||
tutor_unread INT NOT NULL DEFAULT 0,
|
||||
admin_unread INT NOT NULL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ DEFAULT now()
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
UNIQUE (tutor_id, peer_id)
|
||||
)`);
|
||||
await pool.query(`CREATE INDEX IF NOT EXISTS idx_chat_threads_last_message ON chat_threads(last_message_at DESC)`);
|
||||
await pool.query('ALTER TABLE chat_threads ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ');
|
||||
await pool.query('ALTER TABLE chat_threads ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ');
|
||||
await pool.query('ALTER TABLE chat_threads DROP CONSTRAINT IF EXISTS chat_threads_tutor_id_key');
|
||||
await pool.query('ALTER TABLE chat_threads ADD COLUMN IF NOT EXISTS peer_id INT REFERENCES users(id) ON DELETE CASCADE');
|
||||
await pool.query('CREATE UNIQUE INDEX IF NOT EXISTS idx_chat_threads_pair ON chat_threads (tutor_id, peer_id)');
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS chat_messages (
|
||||
id SERIAL PRIMARY KEY,
|
||||
thread_id INT NOT NULL REFERENCES chat_threads(id) ON DELETE CASCADE,
|
||||
@@ -848,7 +872,7 @@ async function sendImageThumb(res, key) {
|
||||
}
|
||||
}
|
||||
|
||||
app.get('/uploads/thumb/:name', fileLimiter, async (req, res) => {
|
||||
app.get('/uploads/thumb/:name', async (req, res) => {
|
||||
const name = req.params.name;
|
||||
if (!/^[A-Za-z0-9._-]+$/.test(name)) return res.status(400).end();
|
||||
return sendImageThumb(res, name);
|
||||
@@ -2743,6 +2767,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 +2832,7 @@ async function ensureUsersAndFirstAdmin() {
|
||||
await ensureApiKeysTable();
|
||||
await ensureUserNotesTable();
|
||||
await ensureBookmarksTable();
|
||||
await ensureAchievementsTables();
|
||||
await ensureDocsTables(pool);
|
||||
await ensureFirstAdmin();
|
||||
}
|
||||
@@ -2998,10 +3048,11 @@ app.delete('/api/notifications', requireAdmin, async (req, res) => {
|
||||
const CHAT_CHANNEL = 'whatido:chat';
|
||||
const chatClients = new Set();
|
||||
|
||||
function chatVisible(user, tutorId) {
|
||||
function chatVisible(user, a, b) {
|
||||
if (!user) return false;
|
||||
if (user.role === 'admin') return true;
|
||||
return Number(user.id) === Number(tutorId);
|
||||
const id = Number(user.id);
|
||||
return id === Number(a) || (b != null && id === Number(b));
|
||||
}
|
||||
|
||||
function writeChatFrame(client, event, data) {
|
||||
@@ -3019,20 +3070,24 @@ cache.on(CHAT_CHANNEL, async message => {
|
||||
try { payload = JSON.parse(message); } catch (e) { return; }
|
||||
if (!payload || !payload.thread_id) return;
|
||||
const event = CHAT_EVENTS.has(payload.type) ? payload.type : 'message';
|
||||
const tutorId = payload.tutor_id === null || payload.tutor_id === undefined
|
||||
? (await chatThreadTutor(payload.thread_id))
|
||||
: payload.tutor_id;
|
||||
if (tutorId === null) return;
|
||||
let tutorId = payload.tutor_id;
|
||||
let peerId = payload.peer_id;
|
||||
if (tutorId === undefined || peerId === undefined) {
|
||||
const t = await chatThreadParticipants(payload.thread_id);
|
||||
tutorId = t ? t.tutor_id : null;
|
||||
peerId = t ? t.peer_id : null;
|
||||
}
|
||||
if (tutorId === null && peerId === null) return;
|
||||
for (const client of [...chatClients]) {
|
||||
if (!chatVisible(client.user, tutorId)) continue;
|
||||
if (!chatVisible(client.user, tutorId, peerId)) continue;
|
||||
try { writeChatFrame(client, event, payload); } catch (e) { chatClients.delete(client); }
|
||||
}
|
||||
});
|
||||
|
||||
async function chatThreadTutor(threadId) {
|
||||
async function chatThreadParticipants(threadId) {
|
||||
try {
|
||||
const { rows } = await pool.query('SELECT tutor_id FROM chat_threads WHERE id = $1', [threadId]);
|
||||
return rows.length ? rows[0].tutor_id : null;
|
||||
const { rows } = await pool.query('SELECT tutor_id, peer_id FROM chat_threads WHERE id = $1', [threadId]);
|
||||
return rows.length ? { tutor_id: rows[0].tutor_id, peer_id: rows[0].peer_id } : null;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
@@ -3060,15 +3115,17 @@ async function chatThreadFor(user, threadId) {
|
||||
const id = parseInt(threadId, 10);
|
||||
if (!Number.isInteger(id) || id < 1) return { error: 400, message: 'Invalid thread' };
|
||||
const { rows } = await pool.query(
|
||||
`SELECT t.id, t.tutor_id, t.last_message_at, t.last_message_text, t.tutor_unread, t.admin_unread, t.created_at,
|
||||
`SELECT t.id, t.tutor_id, t.peer_id, t.last_message_at, t.last_message_text, t.tutor_unread, t.admin_unread, t.created_at,
|
||||
t.deleted_at,
|
||||
u.username AS tutor_username, u.name AS tutor_name, u.is_active AS tutor_active
|
||||
u.username AS tutor_username, u.name AS tutor_name, u.is_active AS tutor_active,
|
||||
p.username AS peer_username, p.name AS peer_name, p.is_active AS peer_active
|
||||
FROM chat_threads t JOIN users u ON u.id = t.tutor_id
|
||||
LEFT JOIN users p ON p.id = t.peer_id
|
||||
WHERE t.id = $1`,
|
||||
[id]
|
||||
);
|
||||
if (!rows.length) return { error: 404, message: 'Диалог не найден' };
|
||||
if (user.role !== 'admin' && rows[0].tutor_id !== user.id) return { error: 403, message: 'Нет доступа к диалогу' };
|
||||
if (user.role !== 'admin' && rows[0].tutor_id !== user.id && rows[0].peer_id !== user.id) return { error: 403, message: 'Нет доступа к диалогу' };
|
||||
return { thread: rows[0] };
|
||||
}
|
||||
|
||||
@@ -3125,9 +3182,13 @@ function chatThreadJson(t, unread) {
|
||||
return {
|
||||
id: t.id,
|
||||
tutor_id: t.tutor_id,
|
||||
peer_id: t.peer_id || null,
|
||||
tutor_username: t.tutor_username,
|
||||
tutor_name: t.tutor_name || t.tutor_username,
|
||||
tutor_active: t.tutor_active !== false,
|
||||
peer_username: t.peer_username || null,
|
||||
peer_name: (t.peer_name || t.peer_username) || null,
|
||||
peer_active: t.peer_active !== false,
|
||||
last_message_at: t.last_message_at,
|
||||
last_message_text: t.last_message_text || '',
|
||||
unread: unread === undefined ? 0 : unread,
|
||||
@@ -3138,37 +3199,55 @@ function chatThreadJson(t, unread) {
|
||||
|
||||
async function chatUnread(user) {
|
||||
if (user.role === 'admin') {
|
||||
const { rows } = await pool.query('SELECT COALESCE(SUM(admin_unread), 0)::int AS n FROM chat_threads WHERE deleted_at IS NULL');
|
||||
const { rows } = await pool.query(
|
||||
`SELECT COALESCE(SUM(CASE WHEN tutor_id = $1 THEN tutor_unread ELSE admin_unread END), 0)::int AS n
|
||||
FROM chat_threads WHERE deleted_at IS NULL AND (tutor_id = $1 OR peer_id = $1 OR peer_id IS NULL)`,
|
||||
[user.id]
|
||||
);
|
||||
return rows[0] ? rows[0].n : 0;
|
||||
}
|
||||
const { rows } = await pool.query('SELECT tutor_unread AS n FROM chat_threads WHERE tutor_id = $1', [user.id]);
|
||||
return rows.length ? rows[0].n : 0;
|
||||
const { rows } = await pool.query(
|
||||
`SELECT COALESCE(SUM(CASE WHEN tutor_id = $1 THEN tutor_unread ELSE admin_unread END), 0)::int AS n
|
||||
FROM chat_threads WHERE deleted_at IS NULL AND (tutor_id = $1 OR peer_id = $1)`,
|
||||
[user.id]
|
||||
);
|
||||
return rows[0] ? rows[0].n : 0;
|
||||
}
|
||||
|
||||
app.get('/api/chat/threads', requireAuth, chatLimiter, async (req, res) => {
|
||||
try {
|
||||
const isAdmin = req.user.role === 'admin';
|
||||
const showDeleted = isAdmin && (req.query.deleted === '1' || req.query.deleted === 'true');
|
||||
const peerJoin = `LEFT JOIN users p ON p.id = t.peer_id`;
|
||||
const { rows } = isAdmin
|
||||
? await pool.query(
|
||||
`SELECT t.id, t.tutor_id, t.last_message_at, t.last_message_text, t.admin_unread, t.created_at, t.deleted_at,
|
||||
u.username AS tutor_username, u.name AS tutor_name, u.is_active AS tutor_active
|
||||
`SELECT t.id, t.tutor_id, t.peer_id, t.last_message_at, t.last_message_text, t.admin_unread, t.tutor_unread, t.created_at, t.deleted_at,
|
||||
u.username AS tutor_username, u.name AS tutor_name, u.is_active AS tutor_active,
|
||||
p.username AS peer_username, p.name AS peer_name, p.is_active AS peer_active
|
||||
FROM chat_threads t JOIN users u ON u.id = t.tutor_id
|
||||
${peerJoin}
|
||||
WHERE t.deleted_at IS ${showDeleted ? 'NOT NULL' : 'NULL'}
|
||||
ORDER BY COALESCE(t.last_message_at, t.created_at) DESC`
|
||||
)
|
||||
: await pool.query(
|
||||
`SELECT t.id, t.tutor_id, t.last_message_at, t.last_message_text, t.tutor_unread, t.created_at, t.deleted_at,
|
||||
u.username AS tutor_username, u.name AS tutor_name, u.is_active AS tutor_active
|
||||
`SELECT t.id, t.tutor_id, t.peer_id, t.last_message_at, t.last_message_text, t.tutor_unread, t.admin_unread, t.created_at, t.deleted_at,
|
||||
u.username AS tutor_username, u.name AS tutor_name, u.is_active AS tutor_active,
|
||||
p.username AS peer_username, p.name AS peer_name, p.is_active AS peer_active
|
||||
FROM chat_threads t JOIN users u ON u.id = t.tutor_id
|
||||
WHERE t.tutor_id = $1`,
|
||||
${peerJoin}
|
||||
WHERE (t.tutor_id = $1 OR t.peer_id = $1) AND t.deleted_at IS NULL`,
|
||||
[req.user.id]
|
||||
);
|
||||
const hidden = isAdmin && !showDeleted
|
||||
? (await pool.query('SELECT COUNT(*)::int AS n FROM chat_threads WHERE deleted_at IS NOT NULL')).rows[0].n
|
||||
: 0;
|
||||
res.json({
|
||||
items: rows.map(t => chatThreadJson(t, isAdmin ? t.admin_unread : t.tutor_unread)),
|
||||
items: rows.map(t => {
|
||||
const unread = isAdmin
|
||||
? t.admin_unread
|
||||
: (Number(req.user.id) === Number(t.tutor_id) ? t.tutor_unread : t.admin_unread);
|
||||
return chatThreadJson(t, unread);
|
||||
}),
|
||||
unread: await chatUnread(req.user),
|
||||
hidden,
|
||||
hidden_mode: !!showDeleted,
|
||||
@@ -3180,19 +3259,34 @@ app.get('/api/chat/threads', requireAuth, chatLimiter, async (req, res) => {
|
||||
|
||||
app.post('/api/chat/threads', requireAuth, chatLimiter, async (req, res) => {
|
||||
try {
|
||||
let tutorId = req.user.id;
|
||||
if (req.user.role === 'admin') {
|
||||
const wanted = parseInt(req.body?.user_id, 10);
|
||||
if (!Number.isInteger(wanted) || wanted < 1) return res.status(400).json({ error: 'Некорректный пользователь' });
|
||||
const { rows } = await pool.query('SELECT id FROM users WHERE id = $1', [wanted]);
|
||||
let recipientId = null;
|
||||
const wanted = req.body?.user_id;
|
||||
if (wanted !== undefined && wanted !== null && wanted !== '') {
|
||||
const w = parseInt(wanted, 10);
|
||||
if (!Number.isInteger(w) || w < 1) return res.status(400).json({ error: 'Некорректный пользователь' });
|
||||
const { rows } = await pool.query('SELECT id FROM users WHERE id = $1 AND is_active IS NOT FALSE', [w]);
|
||||
if (!rows.length) return res.status(404).json({ error: 'Пользователь не найден' });
|
||||
tutorId = rows[0].id;
|
||||
recipientId = w;
|
||||
} else {
|
||||
// default recipient: an admin (for tutors creating "chat with admins")
|
||||
const { rows } = await pool.query("SELECT id FROM users WHERE role = 'admin' AND is_active IS NOT FALSE ORDER BY id LIMIT 1");
|
||||
if (!rows.length) return res.status(404).json({ error: 'Нет доступного собеседника' });
|
||||
recipientId = rows[0].id;
|
||||
if (recipientId === req.user.id) {
|
||||
// self is the only admin; allow self-thread? reject instead
|
||||
const { rows: r2 } = await pool.query("SELECT id FROM users WHERE id <> $1 AND is_active IS NOT FALSE ORDER BY id LIMIT 1", [req.user.id]);
|
||||
if (!r2.length) return res.status(400).json({ error: 'Нет доступного собеседника' });
|
||||
recipientId = r2[0].id;
|
||||
}
|
||||
}
|
||||
const a = Math.min(req.user.id, recipientId);
|
||||
const b = Math.max(req.user.id, recipientId);
|
||||
// tutor_id = a (participant A), peer_id = b (participant B)
|
||||
const { rows: ins } = await pool.query(
|
||||
`INSERT INTO chat_threads (tutor_id) VALUES ($1)
|
||||
ON CONFLICT (tutor_id) DO UPDATE SET tutor_id = EXCLUDED.tutor_id
|
||||
`INSERT INTO chat_threads (tutor_id, peer_id) VALUES ($1, $2)
|
||||
ON CONFLICT (tutor_id, peer_id) DO UPDATE SET tutor_id = EXCLUDED.tutor_id
|
||||
RETURNING id`,
|
||||
[tutorId]
|
||||
[a, b]
|
||||
);
|
||||
const acc = await chatThreadFor(req.user, ins[0].id);
|
||||
if (acc.error) return res.status(acc.error).json({ error: acc.message });
|
||||
@@ -3262,7 +3356,7 @@ app.get('/api/chat/threads/:id/messages', requireAuth, chatLimiter, async (req,
|
||||
reply_file_token: m.reply_deleted_at ? null : (m.reply_file_token || null),
|
||||
files: m.deleted_at ? [] : (byMessage.get(m.id) || []),
|
||||
}));
|
||||
const unreadCol = req.user.role === 'admin' ? acc.thread.admin_unread : acc.thread.tutor_unread;
|
||||
const unreadCol = (Number(req.user.id) === Number(acc.thread.tutor_id) && req.user.role !== 'admin') ? acc.thread.tutor_unread : acc.thread.admin_unread;
|
||||
res.json({ items, thread: chatThreadJson(acc.thread, unreadCol) });
|
||||
} catch (e) {
|
||||
res.status(500).json({ error: e.message });
|
||||
@@ -3279,8 +3373,8 @@ app.delete('/api/chat/threads/:id', requireAuth, requireAdmin, chatLimiter, asyn
|
||||
[String(days), acc.thread.id]
|
||||
);
|
||||
if (!r.rowCount) return res.status(400).json({ error: 'Диалог уже скрыт' });
|
||||
publishChat({ type: 'thread_update', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, deleted_at: '1' });
|
||||
await logAudit(req, 'chat.thread.hide', { id: acc.thread.id, tutor_id: acc.thread.tutor_id, purge_days: days });
|
||||
publishChat({ type: 'thread_update', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, peer_id: acc.thread.peer_id, deleted_at: '1' });
|
||||
await logAudit(req, 'chat.thread.hide', { id: acc.thread.id, tutor_id: acc.thread.tutor_id, peer_id: acc.thread.peer_id, purge_days: days });
|
||||
res.json({ ok: true, thread: chatThreadJson({ ...acc.thread, deleted_at: 'now' }, acc.thread.admin_unread) });
|
||||
});
|
||||
|
||||
@@ -3292,7 +3386,7 @@ app.put('/api/chat/threads/:id/restore', requireAuth, requireAdmin, chatLimiter,
|
||||
[acc.thread.id]
|
||||
);
|
||||
if (!r.rowCount) return res.status(400).json({ error: 'Диалог не скрыт' });
|
||||
publishChat({ type: 'thread_update', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, deleted_at: null });
|
||||
publishChat({ type: 'thread_update', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, peer_id: acc.thread.peer_id, deleted_at: null });
|
||||
await logAudit(req, 'chat.thread.restore', { id: acc.thread.id, tutor_id: acc.thread.tutor_id });
|
||||
res.json({ ok: true, thread: chatThreadJson({ ...acc.thread, deleted_at: null }, acc.thread.admin_unread) });
|
||||
});
|
||||
@@ -3318,7 +3412,7 @@ app.delete('/api/chat/threads/:id/permanent', requireAuth, requireAdmin, chatLim
|
||||
[String(await trashPurgeDays()), acc.thread.id]
|
||||
);
|
||||
if (!r.rowCount) return res.status(400).json({ error: 'Диалог не скрыт или уже запланирован к удалению' });
|
||||
publishChat({ type: 'thread_update', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, deleted_at: '1' });
|
||||
publishChat({ type: 'thread_update', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, peer_id: acc.thread.peer_id, deleted_at: '1' });
|
||||
await logAudit(req, 'chat.thread.schedule', { id: acc.thread.id, tutor_id: acc.thread.tutor_id });
|
||||
res.json({ ok: true });
|
||||
});
|
||||
@@ -3386,6 +3480,11 @@ app.post('/api/chat/threads/:id/messages', requireAuth, chatLimiter, (req, res,
|
||||
const client = await pool.connect();
|
||||
let created;
|
||||
const byTutor = req.user.role !== 'admin';
|
||||
const senderIsA = Number(req.user.id) === Number(acc.thread.tutor_id);
|
||||
const senderIsB = Number(req.user.id) === Number(acc.thread.peer_id);
|
||||
const selfThread = senderIsA && senderIsB;
|
||||
const incA = (!selfThread && senderIsB) ? 1 : 0;
|
||||
const incB = (!selfThread && senderIsA) ? 1 : 0;
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const mr = await client.query(
|
||||
@@ -3410,7 +3509,7 @@ app.post('/api/chat/threads/:id/messages', requireAuth, chatLimiter, (req, res,
|
||||
deleted_at = CASE WHEN $5::boolean THEN NULL ELSE deleted_at END,
|
||||
purge_at = CASE WHEN $5::boolean THEN NULL ELSE purge_at END
|
||||
WHERE id = $1`,
|
||||
[acc.thread.id, chatPreviewText(body, files), byTutor ? 0 : 1, byTutor ? 1 : 0, byTutor]
|
||||
[acc.thread.id, chatPreviewText(body, files), incA, incB, byTutor]
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
} catch (e) {
|
||||
@@ -3420,7 +3519,7 @@ app.post('/api/chat/threads/:id/messages', requireAuth, chatLimiter, (req, res,
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
if (byTutor && acc.thread.deleted_at) publishChat({ type: 'thread_update', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, deleted_at: null });
|
||||
if (byTutor && acc.thread.deleted_at) publishChat({ type: 'thread_update', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, peer_id: acc.thread.peer_id, deleted_at: null });
|
||||
|
||||
const { rows: frows } = await pool.query(
|
||||
'SELECT id, token, name, size FROM chat_attachments WHERE message_id = $1 ORDER BY id',
|
||||
@@ -3464,7 +3563,17 @@ app.post('/api/chat/threads/:id/messages', requireAuth, chatLimiter, (req, res,
|
||||
reply_file_token: replyFileToken,
|
||||
files: frows.map(f => ({ id: f.id, token: f.token, name: f.name, size: f.size })),
|
||||
};
|
||||
publishChat({ type: 'message', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, message });
|
||||
publishChat({ type: 'message', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, peer_id: acc.thread.peer_id, message });
|
||||
if (byTutor) {
|
||||
await pushNotification({
|
||||
type: 'chat.message',
|
||||
title: 'Новое сообщение в чате',
|
||||
body: `${req.user.name || req.user.username}: ${body}`,
|
||||
link: 'chat.html',
|
||||
target: { thread_id: acc.thread.id },
|
||||
adminOnly: true,
|
||||
});
|
||||
}
|
||||
await logAudit(req, 'chat.message.create', { thread_id: acc.thread.id, message_id: created.id, files: frows.length });
|
||||
res.json({ message });
|
||||
}));
|
||||
@@ -3518,7 +3627,7 @@ app.put('/api/chat/threads/:id/messages/:messageId', requireAuth, chatLimiter, a
|
||||
publishChat({
|
||||
type: 'message_update',
|
||||
thread_id: acc.thread.id,
|
||||
tutor_id: acc.thread.tutor_id,
|
||||
tutor_id: acc.thread.tutor_id, peer_id: acc.thread.peer_id,
|
||||
message: payload,
|
||||
preview,
|
||||
});
|
||||
@@ -3567,7 +3676,7 @@ app.delete('/api/chat/threads/:id/messages/:messageId', requireAuth, chatLimiter
|
||||
publishChat({
|
||||
type: 'message_delete',
|
||||
thread_id: acc.thread.id,
|
||||
tutor_id: acc.thread.tutor_id,
|
||||
tutor_id: acc.thread.tutor_id, peer_id: acc.thread.peer_id,
|
||||
message: {
|
||||
id: rows[0].id,
|
||||
sender_id: rows[0].sender_id,
|
||||
@@ -3594,7 +3703,7 @@ app.delete('/api/chat/threads/:id/messages/:messageId', requireAuth, chatLimiter
|
||||
app.post('/api/chat/threads/:id/read', requireAuth, chatLimiter, asyncRoute(async (req, res) => {
|
||||
const acc = await chatThreadFor(req.user, req.params.id);
|
||||
if (acc.error) return res.status(acc.error).json({ error: acc.message });
|
||||
const col = req.user.role === 'admin' ? 'admin_unread' : 'tutor_unread';
|
||||
const col = Number(req.user.id) === Number(acc.thread.tutor_id) ? 'tutor_unread' : 'admin_unread';
|
||||
await pool.query(`UPDATE chat_threads SET ${col} = 0 WHERE id = $1`, [acc.thread.id]);
|
||||
res.json({ ok: true, unread: await chatUnread(req.user) });
|
||||
}));
|
||||
@@ -3638,7 +3747,7 @@ app.get('/api/chat/files/:token', fileLimiter, async (req, res) => {
|
||||
}
|
||||
if (!user || !user.is_active) return res.status(401).json({ error: 'Требуется вход' });
|
||||
const { rows } = await pool.query(
|
||||
`SELECT a.token, a.path, a.name, t.tutor_id
|
||||
`SELECT a.token, a.path, a.name, t.tutor_id, t.peer_id
|
||||
FROM chat_attachments a
|
||||
JOIN chat_messages m ON m.id = a.message_id
|
||||
JOIN chat_threads t ON t.id = m.thread_id
|
||||
@@ -3647,7 +3756,7 @@ app.get('/api/chat/files/:token', fileLimiter, async (req, res) => {
|
||||
);
|
||||
if (!rows.length) return res.status(404).json({ error: 'Файл не найден' });
|
||||
const r = rows[0];
|
||||
if (!chatVisible(user, r.tutor_id)) return res.status(403).json({ error: 'Нет доступа к файлу' });
|
||||
if (!chatVisible(user, r.tutor_id, r.peer_id)) return res.status(403).json({ error: 'Нет доступа к файлу' });
|
||||
const key = storage.keyFromPath(r.path);
|
||||
if (!key) return res.status(404).json({ error: 'Файл не найден' });
|
||||
if (isImageName(r.name)) {
|
||||
@@ -4374,6 +4483,23 @@ app.get('/api/users/tutors', requireAuth, async (_, res) => {
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
app.get('/api/users/search', requireAuth, async (req, res) => {
|
||||
const q = String(req.query.q || '').trim().slice(0, 80);
|
||||
const params = [];
|
||||
let where = 'is_active IS NOT FALSE';
|
||||
if (q) {
|
||||
params.push('%' + q + '%');
|
||||
where += ` AND (name ILIKE $${params.length} OR username ILIKE $${params.length})`;
|
||||
}
|
||||
params.push(req.user.id);
|
||||
where += ` AND id <> $${params.length}`;
|
||||
const { rows } = await pool.query(
|
||||
`SELECT id, name, username, role FROM users WHERE ${where} ORDER BY COALESCE(NULLIF(name, ''), username) LIMIT 20`,
|
||||
params
|
||||
);
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
app.get('/api/users/branches', requireAuth, async (req, res) => {
|
||||
const s = branchScope(req.user);
|
||||
const params = [];
|
||||
@@ -4995,6 +5121,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 +6483,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 +6518,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 +6538,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 +6751,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 +6763,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 +6805,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 +6866,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)',
|
||||
@@ -6774,8 +6983,8 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
|
||||
const ex = await client.query('SELECT 1 FROM users WHERE id = $1', [x.tutor_id]);
|
||||
if (!ex.rowCount) continue;
|
||||
await client.query(
|
||||
'INSERT INTO chat_threads (id, tutor_id, last_message_at, last_message_text, tutor_unread, admin_unread, deleted_at, purge_at, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)',
|
||||
[x.id, x.tutor_id, x.last_message_at, x.last_message_text, x.tutor_unread || 0, x.admin_unread || 0, x.deleted_at || null, x.purge_at || null, x.created_at]
|
||||
'INSERT INTO chat_threads (id, tutor_id, peer_id, last_message_at, last_message_text, tutor_unread, admin_unread, deleted_at, purge_at, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)',
|
||||
[x.id, x.tutor_id, x.peer_id || null, x.last_message_at, x.last_message_text, x.tutor_unread || 0, x.admin_unread || 0, x.deleted_at || null, x.purge_at || null, x.created_at]
|
||||
);
|
||||
}
|
||||
const restoredMsgIds = new Set();
|
||||
@@ -9093,7 +9302,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 +9346,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 +9370,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 +9378,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) {
|
||||
@@ -10848,7 +11164,9 @@ app.get('/api/photos', requireAuth, async (req, res) => {
|
||||
e.photo_path AS path, e.id AS source_id, 'entries.photo_path'::text AS photo_key, e.id AS photo_id,
|
||||
e.student_name, e.group_id,
|
||||
g.branch_id, g.name AS group_name, e.created_at,
|
||||
e.description AS title
|
||||
e.description AS title,
|
||||
'entry'::text AS face_source_type,
|
||||
(SELECT ep.id FROM entry_photos ep WHERE ep.entry_id = e.id AND ep.photo_path = e.photo_path LIMIT 1) AS face_photo_id
|
||||
FROM entries e
|
||||
JOIN groups g ON g.id = e.group_id
|
||||
WHERE e.deleted_at IS NULL AND e.photo_path IS NOT NULL
|
||||
@@ -10856,7 +11174,9 @@ app.get('/api/photos', requireAuth, async (req, res) => {
|
||||
SELECT 'entry_photo', 'Фото записи', ep.photo_path, ep.entry_id, 'entry_photos.photo_path', ep.id,
|
||||
e.student_name, e.group_id,
|
||||
g.branch_id, g.name, ep.created_at,
|
||||
COALESCE(NULLIF(ep.caption, ''), e.description)
|
||||
COALESCE(NULLIF(ep.caption, ''), e.description),
|
||||
'entry'::text AS face_source_type,
|
||||
ep.id AS face_photo_id
|
||||
FROM entry_photos ep
|
||||
JOIN entries e ON e.id = ep.entry_id
|
||||
JOIN groups g ON g.id = e.group_id
|
||||
@@ -10865,14 +11185,18 @@ app.get('/api/photos', requireAuth, async (req, res) => {
|
||||
SELECT 'group_photo', 'Фотохроника группы', gp.photo_path, gp.group_id, 'group_photos.photo_path', gp.id,
|
||||
NULL::varchar, gp.group_id,
|
||||
g.branch_id, g.name, gp.created_at,
|
||||
COALESCE(NULLIF(gp.caption, ''), g.name)
|
||||
COALESCE(NULLIF(gp.caption, ''), g.name),
|
||||
'group'::text AS face_source_type,
|
||||
gp.id AS face_photo_id
|
||||
FROM group_photos gp
|
||||
JOIN groups g ON g.id = gp.group_id
|
||||
UNION ALL
|
||||
SELECT 'student_photo', 'Фото ученика', sp.photo_path, sp.student_id, 'student_photos.photo_path', sp.id,
|
||||
s.name, s.group_id,
|
||||
g.branch_id, g.name, sp.created_at,
|
||||
s.name
|
||||
s.name,
|
||||
NULL::text AS face_source_type,
|
||||
NULL::int AS face_photo_id
|
||||
FROM student_photos sp
|
||||
JOIN students s ON s.id = sp.student_id AND s.deleted_at IS NULL
|
||||
LEFT JOIN groups g ON g.id = s.group_id
|
||||
@@ -10880,14 +11204,16 @@ app.get('/api/photos', requireAuth, async (req, res) => {
|
||||
SELECT 'module_photo', 'Тема модуля', m.photo_path, m.id, 'modules.photo_path', m.id,
|
||||
NULL::varchar, NULL::int,
|
||||
NULL::int, NULL::varchar, m.created_at,
|
||||
m.name
|
||||
m.name,
|
||||
NULL::text AS face_source_type,
|
||||
NULL::int AS face_photo_id
|
||||
FROM modules m
|
||||
WHERE m.photo_path IS NOT NULL
|
||||
) t`;
|
||||
const { rows: crows } = await pool.query(`SELECT count(*)::int AS n ${from}${where}`, params);
|
||||
const total = crows[0].n;
|
||||
let q = `SELECT t.source_type, t.source_label, t.path, t.source_id, t.photo_key, t.photo_id, t.student_name,
|
||||
t.group_id, t.group_name, t.created_at, t.title ${from}${where}
|
||||
t.group_id, t.group_name, t.created_at, t.title, t.face_source_type, t.face_photo_id ${from}${where}
|
||||
ORDER BY t.created_at DESC`;
|
||||
const qparams = params.slice();
|
||||
const lim = parseInt(limit, 10);
|
||||
@@ -10906,7 +11232,9 @@ app.get('/api/photos', requireAuth, async (req, res) => {
|
||||
student_name: r.student_name || null,
|
||||
group_id: r.group_id || null,
|
||||
group_name: r.group_name || null,
|
||||
created_at: r.created_at
|
||||
created_at: r.created_at,
|
||||
face_source_type: r.face_source_type || null,
|
||||
face_photo_id: r.face_photo_id == null ? null : r.face_photo_id
|
||||
}));
|
||||
res.json({ photos, total });
|
||||
} catch (e) {
|
||||
|
||||
Reference in New Issue
Block a user