Implement photo-related enhancements and chat updates
This commit is contained in:
@@ -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,
|
||||
|
||||
+5
-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,6 +686,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 achievement_types (
|
||||
id SERIAL PRIMARY KEY,
|
||||
|
||||
+8
-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,
|
||||
|
||||
+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>
|
||||
|
||||
@@ -334,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) {
|
||||
@@ -569,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,
|
||||
@@ -866,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);
|
||||
@@ -3042,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) {
|
||||
@@ -3063,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;
|
||||
}
|
||||
@@ -3104,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] };
|
||||
}
|
||||
|
||||
@@ -3169,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,
|
||||
@@ -3182,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,
|
||||
@@ -3224,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 });
|
||||
@@ -3306,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 });
|
||||
@@ -3323,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) });
|
||||
});
|
||||
|
||||
@@ -3336,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) });
|
||||
});
|
||||
@@ -3362,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 });
|
||||
});
|
||||
@@ -3430,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(
|
||||
@@ -3454,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) {
|
||||
@@ -3464,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',
|
||||
@@ -3508,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 });
|
||||
}));
|
||||
@@ -3562,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,
|
||||
});
|
||||
@@ -3611,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,
|
||||
@@ -3638,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) });
|
||||
}));
|
||||
@@ -3682,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
|
||||
@@ -3691,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)) {
|
||||
@@ -4418,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 = [];
|
||||
@@ -6901,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();
|
||||
@@ -11082,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
|
||||
@@ -11090,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
|
||||
@@ -11099,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
|
||||
@@ -11114,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);
|
||||
@@ -11140,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