(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('Не удалось загрузить данные ученика'); } })();