diff --git a/AGENTS.md b/AGENTS.md index 11e3917..72131f8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -288,6 +288,16 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo - **CSS**: блок `/* --- Профиль ученика (#profileDataModal) --- */` в `public/admin.css`, сразу после `/* --- Библиотека лиц --- */`. Сетка строк — 12 колонок, ширины полей заданы классами `.pf-mid` (3), `.pf-media` (2), `.pf-media-lg` (4), `.pf-row-wide` (12); на ширине до 820px всё складывается в одну колонку - **Иконки**: `renderIcons()` звать после каждой перерисовки списков — `pfRenderAll()` и `pfAddRow` уже это делают. Новые `` добавляйте с существующими именами из `public/vendor/lucide.min.js` +### 3n. Страница ученика (`student.html`, `js/student.js`, `server.js`) + +- **Роут** `GET /api/students/:id/overview` (`requireAuth`) — единственный агрегат для страницы. Отдаёт `{ student: { …students, group_name, profile }, entries: { items, total }, feedbacks: { items, total }, shorts: { items, total }, photos: { items, photo_path }, faces: { refs, found, similar } }`. Списки ограничены 200 последними строками (`total` — полное число), фото записей подмешиваются в `entries.items[].photos` +- **Идентификация ученика — по имени, не по `student_id`**: `entries.student_name`, `feedbacks.resident`, `short_messages.resident` — свободный текст, FK на `students` нет. Совпадение **точное** (`=`), как в `GET /api/export/student`; не заменяйте на `ILIKE` — в выборку попадут однофамильцы. `student_photos`/`student_face_refs`/`photo_faces` привязаны по `student_id` +- **Филиалы**: доступ к ученику — `studentProfileAccess`; записи и отзывы фильтруются `branchScope` (у не-admin с пустым списком филиалов → `1 = 0`). Короткие сообщения — как в `GET /api/shorts`, без фильтра по филиалам +- **Страница** `public/student.html` + `public/js/student.js` (`data-page="students"`, в сайдбаре активен пункт «Ученики»). Шапка (аватар, имя, группа, мета), карточки-счётчики (клик переключает таб), блок «Профиль» из `students.profile`, табы: Журнал / Короткие сообщения / Обратная связь / Фото / Лица. Лица подгружаются лениво через `GET /api/students/:id/face-photos` при первом открытии таба +- **Даты — только через `public/js/datetime.js`**: `fmtDateTime` для `TIMESTAMPTZ` (`entries.created_at`), `fmtDateLong` для `student.created_at`, `fmtDateOnlyIso` для чистых DATE (`lesson_date`, `feedback_date`). Прямых `toLocale*`/`new Date` в `student.js` быть не должно +- **Кнопка входа** — `` в строке ученика (`renderStudents()`), делегирование в `students.js` (`location.href = 'student.html?id=…'`). Кнопка «Скачать профиль» на странице дёргает `GET /api/export/student?name=` +- **CSS** — page-local блок `.sp-*` в `` `student.html`; карточки записей/отзывов/сообщений переиспользуют общие `.lesson-item` / `.lesson-*` / `.ai-badge` из `admin.css` + --- ### 4. API Patterns @@ -497,6 +507,8 @@ guards against. | `public/chat.html` | Чат тьютор↔админ: список диалогов, лента сообщений, вложения (Ctrl+V) | | `public/js/chat.js` | Логика чата: загрузка треда/сообщений, отправка, вставка файлов из буфера | | `public/feedback.html` | Страница обратной связи (отзывы тьютора) | +| `public/student.html` | Страница одного ученика: профиль, журнал, короткие сообщения, обратная связь, фото и лица (агрегат `GET /api/students/:id/overview`) | +| `public/js/student.js` | Логика страницы ученика: загрузка агрегата, вкладки, ленивая загрузка лиц | | `public/notes.html` | Заметки: сетка карточек 4 в ряд, инлайн-стили `.note-*`, модалка редактирования | | `public/js/notes.js` | Заметки: рендер карточек, CRUD, drag-and-drop порядок (`bindDrag`/`persistNoteOrder`) | | `public/bookmarks.html` | Закладки: сетка карточек (логотип/обложка), поиск, drag-and-drop порядок | diff --git a/public/js/student.js b/public/js/student.js new file mode 100644 index 0000000..2b0bf14 --- /dev/null +++ b/public/js/student.js @@ -0,0 +1,357 @@ +(async function () { + 'use strict'; + const API = location.origin; + let studentId = 0; + let data = null; + let activeTab = 'entries'; + let facesLoaded = false; + let facesData = null; + + const TABS = [ + { key: 'entries', label: 'Журнал', icon: 'book-open' }, + { key: 'shorts', label: 'Короткие сообщения', icon: 'zap' }, + { key: 'feedbacks', label: 'Обратная связь', icon: 'message-square-heart' }, + { key: 'photos', label: 'Фото', icon: 'image' }, + { key: 'faces', label: 'Лица', icon: 'scan-face' }, + ]; + + function hdr() { + const t = sessionStorage.getItem('authToken'); + return t ? { 'X-Auth-Token': t } : {}; + } + + function sThumb(p) { + if (typeof p === 'string' && p.startsWith('/uploads/')) return `${API}/uploads/thumb/${p.slice('/uploads/'.length)}`; + return thumbSrc(p); + } + + function photoFull(p) { + if (!p) return ''; + return p.startsWith('/') ? `${API}${p}` : p; + } + + function initials(name) { + const parts = String(name || '').trim().split(/\s+/).filter(Boolean); + if (!parts.length) return 'У'; + const a = parts[0].charAt(0); + const b = parts.length > 1 ? parts[1].charAt(0) : (parts[0].length > 1 ? parts[0].charAt(1) : ''); + return (a + b).toUpperCase(); + } + + function fmtTs(v) { + try { return v ? (fmtDateTime(v) || '') : ''; } catch { return ''; } + } + + function fmtDateIso(v) { + try { return v ? (fmtDateOnlyIso(v) || '') : ''; } catch { return ''; } + } + + function aiBadge(status) { + if (!status || status === 'none') return ''; + const map = { pending: 'В очереди', processing: 'Обработка', done: 'Готово', error: 'Ошибка', skipped: 'Без изменений', reverted: 'Откат' }; + const cls = ['done', 'error', 'skipped', 'reverted'].includes(status) ? ' ai-badge-' + status : ''; + return `${esc(map[status] || status)}`; + } + + function photoTile(path, cls) { + return `
`; + } + + function emptyHtml(msg) { + return `
${esc(msg)}
`; + } + + function moreHint(total, shown) { + if (!total || total <= shown) return ''; + return `

Показаны последние ${shown} из ${total}

`; + } + + function statCard(icon, num, label, goto) { + return ``; + } + + function tabCount(key) { + if (key === 'entries') return data.entries.total; + 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); + if (key === 'faces') return data.faces.found; + return 0; + } + + function renderTabs() { + const el = document.getElementById('spTabs'); + if (!el) return; + el.innerHTML = TABS.map(t => + `` + ).join(''); + renderIcons(); + } + + function profileHtml(p) { + if (!p) return ''; + const kv = []; + const add = (k, v) => { if (v !== undefined && v !== null && String(v).trim() !== '') kv.push(`
${esc(k)}${esc(v)}
`); }; + add('Роль', p.role); + add('Статус', p.status); + add('Заметка статуса', p.status_note); + add('Город', p.city); + add('Наставник', p.mentor); + add('В обучении с', p.joined); + const tags = Array.isArray(p.tags) ? p.tags.filter(Boolean) : []; + const skills = Array.isArray(p.skills) ? p.skills : []; + const contacts = Array.isArray(p.contacts) ? p.contacts : []; + let html = '
Профиль
'; + if (kv.length) html += `
${kv.join('')}
`; + if (p.bio) html += `
О себе
${esc(p.bio)}
`; + if (p.quote) html += `
Цитата
${esc(p.quote)}
`; + if (tags.length) html += `
Теги
${tags.map(t => `${esc(t)}`).join('')}
`; + if (skills.length) { + html += `
Навыки
${skills.map(sk => { + const name = [sk.group, sk.name].filter(Boolean).join(' · ') || 'Навык'; + const raw = Number(sk.value); + const val = Number.isFinite(raw) ? Math.max(0, Math.min(100, Math.round(raw))) : 0; + const lvl = sk.level ? esc(sk.level) : val + '%'; + return `
${esc(name)}${lvl}
`; + }).join('')}
`; + } + if (contacts.length) { + html += `
Контакты
`; + } + if (!kv.length && !p.bio && !p.quote && !tags.length && !skills.length && !contacts.length) { + html += `
Профиль не заполнен — данные заполняются кнопкой «Данные» на странице «Ученики».
`; + } + return html + '
'; + } + + function entriesHtml() { + const items = data.entries.items; + if (!items.length) return emptyHtml('Записей в журнале пока нет'); + return `
${items.map(e => { + const photos = (e.photos || []).map(p => photoTile(p.photo_path)); + if (e.photo_path) photos.unshift(photoTile(e.photo_path)); + return `
+
+ ${esc(fmtTs(e.created_at))} + ${e.module_name ? `${esc(e.module_name)}` : ''} + ${e.group_name ? `${esc(e.group_name)}` : ''} + ${aiBadge(e.ai_status)} +
+ ${e.description ? `
${esc(e.description)}
` : ''} + ${photos.length ? `
${photos.join('')}
` : ''} +
`; + }).join('')}
${moreHint(data.entries.total, items.length)}`; + } + + function shortsHtml() { + const items = data.shorts.items; + if (!items.length) return emptyHtml('Коротких сообщений нет'); + return `
${items.map(s => `
+
+ ${s.lesson_date ? `${esc(fmtDateIso(s.lesson_date))}` : ''} + ${s.topic ? `${esc(s.topic)}` : ''} + ${s.used ? 'Использовано' : ''} + ${(s.author_name || s.author_username) ? `${esc(s.author_name || s.author_username)}` : ''} +
+
${esc(s.message)}
+
`).join('')}
${moreHint(data.shorts.total, items.length)}`; + } + + function feedbacksHtml() { + const items = data.feedbacks.items; + if (!items.length) return emptyHtml('Обратной связи по ученику нет'); + return `
${items.map(f => `
+
+ ${f.feedback_date ? `${esc(fmtDateIso(f.feedback_date))}` : ''} + ${f.topic ? `${esc(f.topic)}` : ''} + ${f.group_name ? `${esc(f.group_name)}` : ''} + ${f.sent_at ? 'Отправлено' : aiBadge(f.ai_status)} +
+ ${f.text ? `
${esc(f.text)}
` : '
Без текста
'} +
`).join('')}
${moreHint(data.feedbacks.total, items.length)}`; + } + + function photosHtml() { + const main = data.photos.photo_path; + const items = data.photos.items || []; + if (!main && !items.length) return emptyHtml('Фотографий нет'); + const tiles = []; + if (main) tiles.push(photoTile(main, 'sp-photo')); + items.forEach(p => tiles.push(photoTile(p.photo_path, 'sp-photo'))); + return `
${tiles.join('')}
`; + } + + function facesHtml() { + if (!facesData) return ''; + const found = facesData.photos || []; + const similar = facesData.similar || []; + let html = ''; + if (found.length) { + html += `
Найдены на фото (${found.length})
${found.map(f => { + const cap = f.manual ? 'вручную' : (f.confidence != null ? Math.round(Number(f.confidence) * 100) + '%' : ''); + return `
${photoTile(f.path, 'sp-photo')}
${esc(f.group_name || '')}${cap ? ` · ${esc(cap)}` : ''}
`; + }).join('')}
`; + } + if (similar.length) { + html += `
Похожие лица без привязки (${similar.length})
${similar.map(f => { + const cap = f.score != null ? Math.round(Number(f.score) * 100) + '%' : ''; + return `
${photoTile(f.path, 'sp-photo')}
${esc(f.group_name || '')}${cap ? ` · ${esc(cap)}` : ''}
`; + }).join('')}
`; + } + if (!html) html = emptyHtml('Фото с распознанным лицом не найдены'); + return html; + } + + function renderPane() { + const pane = document.getElementById('spPane'); + if (!pane) return; + if (activeTab === 'faces') { + if (!facesLoaded) { + pane.innerHTML = '
Загрузка…
'; + renderIcons(); + loadFaces(); + return; + } + pane.innerHTML = facesHtml(); + } else if (activeTab === 'entries') { + pane.innerHTML = entriesHtml(); + } else if (activeTab === 'shorts') { + pane.innerHTML = shortsHtml(); + } else if (activeTab === 'feedbacks') { + pane.innerHTML = feedbacksHtml(); + } else if (activeTab === 'photos') { + pane.innerHTML = photosHtml(); + } + renderIcons(); + } + + async function loadFaces() { + try { + const res = await fetch(`${API}/api/students/${studentId}/face-photos`, { headers: hdr() }); + facesData = res.ok ? await res.json() : { photos: [], similar: [] }; + } catch { + facesData = { photos: [], similar: [] }; + } + facesLoaded = true; + if (activeTab === 'faces') renderPane(); + } + + async function downloadProfile() { + const btn = document.getElementById('spDownloadBtn'); + if (btn) btn.disabled = true; + try { + const res = await fetch(`${API}/api/export/student?name=${encodeURIComponent(data.student.name)}`, { headers: hdr() }); + if (!res.ok) throw new Error('export failed'); + const blob = await res.blob(); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `${data.student.name}.zip`; + document.body.appendChild(a); + a.click(); + a.remove(); + URL.revokeObjectURL(url); + } catch { + showToast('Не удалось сформировать профиль', true); + } finally { + if (btn) btn.disabled = false; + } + } + + function renderPage() { + const s = data.student; + const photoCount = data.photos.items.length + (data.photos.photo_path ? 1 : 0); + const avatar = s.photo_path + ? `` + : `
${esc(initials(s.name))}
`; + const page = document.getElementById('studentPage'); + page.innerHTML = ` +
+ Все ученики +
+ +
+
+
+ ${avatar} +
+

${esc(s.name)}

+
+ ${s.group_name ? ` ${esc(s.group_name)}` : ' Без группы'} + ${data.faces.refs ? ` Эталонов лиц: ${data.faces.refs}` : ''} +
+
+ ${s.created_at ? ` В системе с ${esc(fmtDateLong(s.created_at))}` : ''} + Записей: ${data.entries.total} + Отзывов: ${data.feedbacks.total} +
+
+
+
+ ${statCard('book-open', data.entries.total, 'Записей в журнале', 'entries')} + ${statCard('zap', data.shorts.total, 'Коротких сообщений', 'shorts')} + ${statCard('message-square-heart', data.feedbacks.total, 'Отзывов', 'feedbacks')} + ${statCard('image', photoCount, 'Фотографий', 'photos')} + ${statCard('scan-face', data.faces.found, 'Найдено лиц', 'faces')} +
+ ${profileHtml(s.profile)} +
+
+
+
`; + page.addEventListener('click', e => { + const g = e.target.closest('[data-tab],[data-goto]'); + if (!g) return; + const tab = g.dataset.tab || g.dataset.goto; + if (tab && tab !== activeTab) { + activeTab = tab; + renderTabs(); + renderPane(); + } + }); + document.getElementById('spDownloadBtn').addEventListener('click', downloadProfile); + renderTabs(); + renderPane(); + renderIcons(); + } + + function renderError(msg) { + const page = document.getElementById('studentPage'); + page.innerHTML = `
Все ученики
${esc(msg)}
`; + renderIcons(); + } + + if (!(await checkAuth())) return; + buildSidebar('students'); + document.getElementById('imgModal').addEventListener('click', e => e.currentTarget.classList.remove('open')); + document.addEventListener('keydown', e => { + if (e.key === 'Escape') document.getElementById('imgModal').classList.remove('open'); + }); + studentId = parseInt(new URLSearchParams(location.search).get('id'), 10) || 0; + if (!studentId) { renderError('Ученик не указан'); return; } + try { + const res = await fetch(`${API}/api/students/${studentId}/overview`, { headers: hdr() }); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + renderError(err.error || 'Не удалось загрузить данные ученика'); + return; + } + data = await res.json(); + document.title = `${data.student.name} — Админ-панель`; + renderPage(); + } catch { + renderError('Не удалось загрузить данные ученика'); + } +})(); diff --git a/public/js/students.js b/public/js/students.js index c4ab0d4..9566837 100644 --- a/public/js/students.js +++ b/public/js/students.js @@ -102,6 +102,7 @@ function renderStudents() {
+ @@ -1300,6 +1301,8 @@ document.addEventListener('keydown', e => { }); document.getElementById('studentList').addEventListener('click', e => { + const op = e.target.closest('[data-open-student]'); + if (op) { location.href = `student.html?id=${op.dataset.openStudent}`; return; } const av = e.target.closest('[data-avatar-student]'); if (av) { const p = av.dataset.studentPhoto; diff --git a/public/student.html b/public/student.html new file mode 100644 index 0000000..6130bd3 --- /dev/null +++ b/public/student.html @@ -0,0 +1,107 @@ + + + + + +Ученик — Админ-панель + + + + +
+ +
+
+
Загрузка…
+
+
+
+ + + +
+ + + + + + diff --git a/server.js b/server.js index 888668a..96a4ec1 100644 --- a/server.js +++ b/server.js @@ -7707,6 +7707,112 @@ app.get('/api/students/:id/photos', requireAuth, async (req, res) => { res.json({ photos: rows, photo_path: acc.student.photo_path || null }); }); +app.get('/api/students/:id/overview', 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 ? 'Нет доступа к этому ученику' : 'Ученик не найден' }); + } + const student = acc.student; + const name = student.name; + const LIST_LIMIT = 200; + try { + const bs = branchScope(req.user); + const eConds = ['e.student_name = $1', 'e.deleted_at IS NULL']; + const eParams = [name]; + if (bs.ids) { + if (!bs.ids.length) eConds.push('1 = 0'); + else { eParams.push(bs.ids); eConds.push(`g.branch_id = ANY($${eParams.length}::int[])`); } + } + const eWhere = eConds.join(' AND '); + + const fConds = ['f.resident = $1', 'f.deleted_at IS NULL']; + const fParams = [name]; + if (bs.ids) { + if (!bs.ids.length) fConds.push('1 = 0'); + else { fParams.push(bs.ids); fConds.push(`f.branch_id = ANY($${fParams.length}::int[])`); } + } + const fWhere = fConds.join(' AND '); + + const [groupRes, entriesTotalRes, entriesRes, fbTotalRes, fbRes, shortsTotalRes, shortsRes, photosRes, facesRes] = 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), + (() => { + const p = eParams.slice(); + p.push(LIST_LIMIT); + return pool.query( + `SELECT e.id, e.description, e.created_at, e.ai_status, e.module_id, e.group_id, e.photo_path, + g.name AS group_name, m.name AS module_name + FROM entries e JOIN groups g ON g.id = e.group_id + LEFT JOIN modules m ON m.id = e.module_id + WHERE ${eWhere} ORDER BY e.created_at DESC LIMIT $${p.length}`, + p + ); + })(), + pool.query(`SELECT count(*)::int AS n FROM feedbacks f WHERE ${fWhere}`, fParams), + (() => { + const p = fParams.slice(); + p.push(LIST_LIMIT); + return pool.query( + `SELECT f.id, f.feedback_date, f.topic, f.text, f.ai_status, f.sent_at, f.group_id, f.created_at, f.author_id, + g.name AS group_name + FROM feedbacks f LEFT JOIN groups g ON g.id = f.group_id + WHERE ${fWhere} ORDER BY f.feedback_date DESC NULLS LAST, f.id DESC LIMIT $${p.length}`, + p + ); + })(), + pool.query('SELECT count(*)::int AS n FROM short_messages WHERE resident = $1 AND deleted_at IS NULL', [name]), + pool.query( + `SELECT sm.id, sm.resident, sm.lesson_date, sm.topic, sm.message, sm.used, sm.used_at, sm.created_at, + u.name AS author_name, u.username AS author_username + FROM short_messages sm LEFT JOIN users u ON u.id = sm.author_id + WHERE sm.resident = $1 AND sm.deleted_at IS NULL + ORDER BY sm.lesson_date DESC, sm.id DESC LIMIT $2`, + [name, LIST_LIMIT] + ), + pool.query('SELECT id, photo_path, created_at FROM student_photos WHERE student_id = $1 ORDER BY id DESC LIMIT $2', [id, LIST_LIMIT]), + pool.query( + `SELECT + (SELECT count(*)::int FROM student_face_refs WHERE student_id = $1) AS refs, + (SELECT count(*)::int FROM photo_faces WHERE student_id = $1) AS found, + (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] + ), + ]); + + const entryIds = entriesRes.rows.map(r => r.id); + if (entryIds.length) { + const pr = await pool.query( + 'SELECT id, entry_id, photo_path, caption FROM entry_photos WHERE entry_id = ANY($1) ORDER BY sort_order, id', + [entryIds] + ); + const byEntry = {}; + pr.rows.forEach(p => { (byEntry[p.entry_id] = byEntry[p.entry_id] || []).push(p); }); + entriesRes.rows.forEach(r => { r.photos = byEntry[r.id] || []; }); + } else { + entriesRes.rows.forEach(r => { r.photos = []; }); + } + + const faces = facesRes.rows[0] || {}; + res.json({ + student: { ...student, group_name: groupRes.rows[0]?.name || null, profile: student.profile || null }, + entries: { items: entriesRes.rows, total: entriesTotalRes.rows[0].n }, + feedbacks: { items: fbRes.rows, total: fbTotalRes.rows[0].n }, + 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 }, + }); + } catch (e) { + console.error('student overview:', e); + res.status(500).json({ error: 'Internal error' }); + } +}); + app.post('/api/students/:id/photos', requireAuth, (req, res, next) => { studentPhotoUpload(req, res, (err) => { if (err) {