Implement photo-related enhancements and chat updates
This commit is contained in:
+5
-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)}
|
||||
@@ -953,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();
|
||||
}
|
||||
})();
|
||||
|
||||
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user