From 0c8cbb56e1302ce24924179d24b51327033ef0df Mon Sep 17 00:00:00 2001 From: dev Date: Wed, 4 Nov 2026 23:48:28 +0300 Subject: [PATCH] feat(feedback): notify on feedback AI ready/error --- db/init.sql | 3 +- db/migration.sql | 4 +- public/admin.js | 1 + public/digest.html | 72 +++++++++----- public/js/digest.js | 235 +++++++++++++++++++++++++++++++------------- server.js | 23 ++++- 6 files changed, 244 insertions(+), 94 deletions(-) diff --git a/db/init.sql b/db/init.sql index ad64996..c310f3e 100644 --- a/db/init.sql +++ b/db/init.sql @@ -584,7 +584,8 @@ INSERT INTO settings (key, value) VALUES ('feedback_ai_prompt','Ты — пом - Не придумывай фактов, которых нет в контексте. ФОРМАТ ОТВЕТА: только текст отзыва, без лишних элементов.') ON CONFLICT (key) DO NOTHING; -INSERT INTO settings (key, value) VALUES ('notify_feedback_ai_ready','false') ON CONFLICT (key) DO NOTHING; +INSERT INTO settings (key, value) VALUES ('notify_feedback_ai_ready','true') ON CONFLICT (key) DO NOTHING; +INSERT INTO settings (key, value) VALUES ('notify_feedback_ai_error','true') ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('feedback_imgbb_url','') ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('feedback_imgbb_key','') ON CONFLICT (key) DO NOTHING; diff --git a/db/migration.sql b/db/migration.sql index 7884a58..4450efb 100644 --- a/db/migration.sql +++ b/db/migration.sql @@ -829,7 +829,9 @@ INSERT INTO settings (key, value) VALUES ('feedback_ai_prompt','Ты — пом - Не придумывай фактов, которых нет в контексте. ФОРМАТ ОТВЕТА: только текст отзыва, без лишних элементов.') ON CONFLICT (key) DO NOTHING; -INSERT INTO settings (key, value) VALUES ('notify_feedback_ai_ready','false') ON CONFLICT (key) DO NOTHING; +INSERT INTO settings (key, value) VALUES ('notify_feedback_ai_ready','true') ON CONFLICT (key) DO NOTHING; +INSERT INTO settings (key, value) VALUES ('notify_feedback_ai_error','true') ON CONFLICT (key) DO NOTHING; +UPDATE settings SET value = 'true' WHERE key = 'notify_feedback_ai_ready' AND value IN ('false'); CREATE TABLE IF NOT EXISTS user_settings ( user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE, diff --git a/public/admin.js b/public/admin.js index 66a3d88..a7f145a 100644 --- a/public/admin.js +++ b/public/admin.js @@ -245,6 +245,7 @@ const NOTIFY_ICONS = { 'lesson.report': 'notebook-pen', 'lesson.ai.formatted': 'file-check', 'feedback.ai.ready': 'message-square-heart', + 'feedback.ai.error': 'message-square-x', 'face.scan.done': 'scan-face', 'face.recognized': 'user-round-check', 'face.scan.error': 'scan-search', diff --git a/public/digest.html b/public/digest.html index d839ee5..c4618ca 100644 --- a/public/digest.html +++ b/public/digest.html @@ -6,45 +6,64 @@ Дайджест — Админ-панель @@ -57,6 +76,10 @@

Важные сообщения для команды

+
+ + +
@@ -71,20 +94,22 @@
- +
- - + + + Курсор в поле текста + Ctrl+V — вставит картинку из буфера обмена.
- + + Доступно администраторам. Закреплённые сообщения всегда сверху.
- Пусто — опубликовано сразу. Будущая дата — появится автоматически и придет уведомление всем. + Пусто — опубликовано сразу. Будущая дата — появится автоматически для всех и придёт уведомление.
@@ -98,18 +123,21 @@
превью
- - +
+ + +
+ Обложка сообщения. Загружается при сохранении.
-
- - +
+ +
- До 20 картинок. Удаление картинки стирает файл с диска. Вставка из буфера — Ctrl+V в поле текста. + До 20 картинок. Удаление картинки стирает файл с диска.
diff --git a/public/js/digest.js b/public/js/digest.js index 2ad6823..4339633 100644 --- a/public/js/digest.js +++ b/public/js/digest.js @@ -3,6 +3,8 @@ let digests = []; let editingId = null; let saving = false; + let query = ''; + let digestLoaded = false; let previewPath = null; let previewRemoved = false; let previewFile = null; @@ -40,6 +42,7 @@ const pinnedEl = document.getElementById('digestPinned'); const postAtEl = document.getElementById('digestPostAt'); const hideAtEl = document.getElementById('digestHideAt'); + let restored = false; if (titleEl && d.title != null) titleEl.value = d.title; if (bodyEl && d.body != null) bodyEl.value = d.body; if (pinnedEl && d.isPinned != null) pinnedEl.checked = !!d.isPinned; @@ -47,7 +50,9 @@ if (hideAtEl && d.hideAt != null) hideAtEl.value = d.hideAt; previewPath = d.previewPath || null; showPreview(previewPath); - } catch (e) {} + restored = !!(d.title || d.body || d.postAt || d.hideAt || previewPath || d.isPinned); + return restored; + } catch { return false; } } function clearDraft() { @@ -67,12 +72,6 @@ return String(s || '').replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"').replace(/'/g, '''); } - function escAttr(s) { - const d = document.createElement('textarea'); - d.textContent = s || ''; - return d.value; - } - function tzOffsetMinutes(instant) { try { const d = new Date(instant); @@ -111,34 +110,20 @@ } catch { return null; } } - function thumbSrc(p) { - if (!p) return ''; - if (p.startsWith('/uploads/')) return `${API}/uploads/thumb/${p.slice('/uploads/'.length)}`; - return p; - } - - function fmtDigestDate(iso) { - if (!iso) return '—'; - try { - return new Intl.DateTimeFormat('ru-RU', { - timeZone: DateTime.tz, day: '2-digit', month: '2-digit', year: 'numeric', - hour: '2-digit', minute: '2-digit' - }).format(new Date(iso)); - } catch { return String(iso).slice(0, 16); } - } - function digestCardHtml(d) { const admin = isAdmin(); const mine = currentUser && d.author_id === currentUser.id; const canEdit = admin || mine; const pinned = !!d.is_pinned; - const nowTs = new Date(); + const nowTs = Date.now(); + const postFuture = d.post_at && new Date(d.post_at).getTime() > nowTs; const hidden = d.hide_at && new Date(d.hide_at) <= nowTs; const badge = []; if (pinned) badge.push('Закреплено'); - if (d.post_at) badge.push('Публикация ' + fmtDigestDate(d.post_at) + ''); - if (d.hide_at) badge.push('Скрыть ' + fmtDigestDate(d.hide_at) + ''); + if (postFuture) badge.push('Запланировано на ' + esc(fmtDateTimeY(d.post_at)) + ''); + if (hidden) badge.push('Скрыто'); + else if (d.hide_at) badge.push('Скроется ' + esc(fmtDateTimeY(d.hide_at)) + ''); const preview = d.preview_path ? '
' @@ -164,6 +149,11 @@ actions.push(''); } + const bodyText = d.body || ''; + const longBody = bodyText.length > 600; + const bodyHtml = '
' + esc(bodyText) + '
' + + (longBody ? '' : ''); + return '
' + '
' + '

' + esc(d.title) + '

' + @@ -171,10 +161,10 @@ '
' + preview + '
' + - '' + esc(d.author_name || '—') + '' + - '' + fmtShortIso(d.created_at) + '' + + '' + esc(d.author_name || '—') + '' + + '' + esc(fmtDateTimeY(d.published_at || d.created_at)) + '' + '
' + - '
' + esc(d.body) + '
' + + bodyHtml + imagesHtml + '
' + '
' + actions.join('') + '
' + @@ -182,14 +172,55 @@ '
'; } + function filterDigests() { + const q = query.trim().toLowerCase(); + if (!q) return digests; + return digests.filter(function(d) { + return (d.title || '').toLowerCase().includes(q) || + (d.body || '').toLowerCase().includes(q) || + (d.author_name || '').toLowerCase().includes(q); + }); + } + + function updateCountInfo(list) { + const el = document.getElementById('digestCount'); + if (!el) return; + el.textContent = query.trim() + ? 'Найдено: ' + list.length + ' из ' + digests.length + : (digests.length ? 'Сообщений: ' + digests.length : ''); + } + function renderDigests() { const el = document.getElementById('digestList'); if (!el) return; + if (!digestLoaded) return; + const list = filterDigests(); + updateCountInfo(list); if (!digests.length) { - el.innerHTML = '
Сообщений пока нет
'; + el.innerHTML = '
' + + '

Сообщений пока нет

' + + '

Опубликуйте важное объявление — его увидят все тьюторы и админы.

' + + '
'; + renderIcons(); return; } - el.innerHTML = digests.map(digestCardHtml).join(''); + if (!list.length) { + el.innerHTML = '
' + + '

Ничего не найдено

' + + '

По запросу «' + esc(query.trim()) + '» сообщений нет

'; + renderIcons(); + return; + } + el.innerHTML = list.map(digestCardHtml).join(''); + renderIcons(); + } + + function renderLoadError() { + const el = document.getElementById('digestList'); + if (!el) return; + el.innerHTML = '
' + + '

Не удалось загрузить сообщения

' + + '
'; renderIcons(); } @@ -198,12 +229,18 @@ try { res = await fetch(API + '/api/digests', { headers: hdr() }); } catch (e) { + if (!digestLoaded) renderLoadError(); showToast('Ошибка сети при загрузке дайджеста', true); return; } - if (!res.ok) return; + if (!res.ok) { + if (!digestLoaded) renderLoadError(); + showToast('Не удалось загрузить дайджест', true); + return; + } const data = await res.json().catch(function() { return {}; }); digests = Array.isArray(data.items) ? data.items : (Array.isArray(data) ? data : []); + digestLoaded = true; renderDigests(); } @@ -253,6 +290,15 @@ btn.style.display = path || previewRemoved || previewFile ? '' : 'none'; } + function updateCounts() { + const t = document.getElementById('digestTitle'); + const b = document.getElementById('digestBody'); + const tc = document.getElementById('digestTitleCount'); + const bc = document.getElementById('digestBodyCount'); + if (t && tc) tc.textContent = t.value.length + ' / 200'; + if (b && bc) bc.textContent = b.value.length + ' / 5000'; + } + function openDigestModal(d) { editingId = d ? d.id : null; previewPath = d ? d.preview_path : null; @@ -260,8 +306,8 @@ previewFile = null; digestImages = []; document.getElementById('digestModalTitle').textContent = d ? 'Редактирование сообщения' : 'Новое сообщение'; - document.getElementById('digestTitle').value = d ? escAttr(d.title) : ''; - document.getElementById('digestBody').value = d ? escAttr(d.body) : ''; + document.getElementById('digestTitle').value = d ? d.title : ''; + document.getElementById('digestBody').value = d ? d.body : ''; document.getElementById('digestPostAt').value = d ? toLocalInput(d.post_at) : ''; document.getElementById('digestHideAt').value = d ? toLocalInput(d.hide_at) : ''; const pinRow = document.getElementById('digestPinned').closest('.settings-field'); @@ -272,22 +318,26 @@ document.getElementById('digestImageFile').value = ''; const canManageImages = !!editingId; document.getElementById('digestImageAdd').style.display = canManageImages ? '' : 'none'; - document.getElementById('digestImagesWrap').style.display = canManageImages ? '' : 'none'; + document.getElementById('digestImagesWrap').style.display = ''; if (canManageImages) { loadImages(editingId); } else { - document.getElementById('digestImagesWrap').innerHTML = 'Сохраните сообщение, чтобы добавить картинки'; + document.getElementById('digestImagesWrap').innerHTML = 'Добавятся после сохранения. Или вставьте картинку из буфера — Ctrl+V в поле текста, сообщение сохранится автоматически.'; } + let draftRestored = false; if (editingId) { clearDraft(); } else { - restoreDraft(); + draftRestored = restoreDraft(); } + updateCounts(); document.getElementById('digestModal').classList.add('open'); document.getElementById('digestTitle').focus(); + if (draftRestored) showToast('Несохранённый черновик восстановлен'); } function closeDigestModal() { + if (saving) return; if (hasDraft() && !confirm('Есть несохранённые изменения. Закрыть без сохранения?')) return; document.getElementById('digestModal').classList.remove('open'); editingId = null; @@ -299,7 +349,6 @@ } async function uploadPreview(digestId) { - if (!previewFile) return; if (previewRemoved) { try { await fetch(API + '/api/digests/' + digestId + '/preview', { method: 'DELETE', headers: hdr() }); @@ -307,6 +356,7 @@ previewRemoved = false; return; } + if (!previewFile) return; const fd = new FormData(); fd.append('image', previewFile); try { @@ -322,43 +372,66 @@ } } + function setInvalid(el, on) { + if (el) el.classList.toggle('invalid', !!on); + } + async function doSaveDigest() { - const title = document.getElementById('digestTitle').value.trim(); - const body = document.getElementById('digestBody').value.trim(); + const titleEl = document.getElementById('digestTitle'); + const bodyEl = document.getElementById('digestBody'); + const title = titleEl.value.trim(); + const body = bodyEl.value.trim(); const isPinned = document.getElementById('digestPinned').checked; const postAt = inputToIso(document.getElementById('digestPostAt').value); const hideAt = inputToIso(document.getElementById('digestHideAt').value); - if (!title) { showToast('Введите заголовок', true); return null; } - if (!body) { showToast('Введите текст сообщения', true); return null; } + if (!title || !body) { + setInvalid(titleEl, !title); + setInvalid(bodyEl, !body); + if (!title) titleEl.focus(); else bodyEl.focus(); + showToast(!title ? 'Введите заголовок' : 'Введите текст сообщения', true); + return null; + } + if (hideAt && postAt && new Date(hideAt).getTime() <= new Date(postAt).getTime()) { + showToast('Дата скрытия должна быть позже даты публикации', true); + document.getElementById('digestHideAt').focus(); + return null; + } if (saving) return null; const payload = { title: title, body: body, is_pinned: isPinned, preview_path: previewPath || null, post_at: postAt, hide_at: hideAt }; + const saveBtn = document.getElementById('digestSave'); saving = true; - let res; + saveBtn.disabled = true; + saveBtn.textContent = 'Сохранение…'; try { - if (editingId) { - res = await fetch(API + '/api/digests/' + editingId, { - method: 'PUT', headers: hdrJson(), body: JSON.stringify(payload) - }); - } else { - res = await fetch(API + '/api/digests', { method: 'POST', headers: hdrJson(), body: JSON.stringify(payload) }); + let res; + try { + if (editingId) { + res = await fetch(API + '/api/digests/' + editingId, { + method: 'PUT', headers: hdrJson(), body: JSON.stringify(payload) + }); + } else { + res = await fetch(API + '/api/digests', { method: 'POST', headers: hdrJson(), body: JSON.stringify(payload) }); + } + } catch (e) { + showToast('Ошибка сети', true); + return null; } - } catch (e) { + const data = await res.json().catch(function() { return {}; }); + if (!res.ok) { + showToast(data.error || 'Ошибка при сохранении', true); + return null; + } + const savedId = editingId || (data.item && data.item.id); + if (savedId) { + await uploadPreview(savedId); + previewFile = null; + } + return savedId; + } finally { saving = false; - showToast('Ошибка сети', true); - return null; + saveBtn.disabled = false; + saveBtn.textContent = 'Сохранить'; } - const data = await res.json().catch(function() { return {}; }); - saving = false; - if (!res.ok) { - showToast(data.error || 'Ошибка при сохранении', true); - return null; - } - const savedId = editingId || (data.item && data.item.id); - if (savedId) { - await uploadPreview(savedId); - previewFile = null; - } - return savedId; } async function saveDigest() { @@ -404,6 +477,9 @@ if (!saved) return; targetId = saved; editingId = targetId; + clearDraft(); + document.getElementById('digestModalTitle').textContent = 'Редактирование сообщения'; + showToast('Сообщение сохранено — картинка добавляется к нему'); document.getElementById('digestImageAdd').style.display = ''; document.getElementById('digestImagesWrap').style.display = ''; } @@ -548,7 +624,6 @@ document.getElementById('digestSave').addEventListener('click', saveDigest); document.getElementById('digestPreviewFile').addEventListener('change', addPreviewFile); document.getElementById('digestPreviewRemove').addEventListener('click', removePreview); - document.getElementById('digestImageAdd').addEventListener('click', addImages); document.getElementById('digestImageFile').addEventListener('change', addImages); document.getElementById('digestModal').addEventListener('paste', digestPaste); const draftTitle = document.getElementById('digestTitle'); @@ -556,7 +631,11 @@ const draftPinned = document.getElementById('digestPinned'); const draftPostAt = document.getElementById('digestPostAt'); const draftHideAt = document.getElementById('digestHideAt'); - [draftTitle, draftBody].forEach(el => el && el.addEventListener('input', persistDraft)); + [draftTitle, draftBody].forEach(el => el && el.addEventListener('input', function() { + persistDraft(); + updateCounts(); + setInvalid(el, false); + })); [draftPinned, draftPostAt, draftHideAt].forEach(el => el && el.addEventListener('change', persistDraft)); document.getElementById('digestImagesWrap').addEventListener('click', function(e) { const btn = e.target.closest('[data-action="del-image"]'); @@ -568,12 +647,20 @@ document.addEventListener('keydown', function(e) { const m = document.getElementById('digestModal'); const open = m && m.classList.contains('open'); - if (e.key === 'Escape' && open) closeDigestModal(); + if (!open) return; + if (e.key === 'Escape') { closeDigestModal(); return; } + if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { + e.preventDefault(); + const tag = document.activeElement && document.activeElement.tagName; + if (tag !== 'INPUT' || document.activeElement.type !== 'file') saveDigest(); + } }); } function bindPage() { document.getElementById('digestNewBtn').addEventListener('click', function() { openDigestModal(null); }); + const search = document.getElementById('digestSearch'); + if (search) search.addEventListener('input', function() { query = search.value; renderDigests(); }); document.addEventListener('click', async function(e) { const actEl = e.target.closest('[data-action]'); if (actEl) { @@ -586,6 +673,18 @@ } if (action === 'delete') { await removeDigest(id); return; } if (action === 'pin') { await togglePin(id, actEl.dataset.pin === '1'); return; } + if (action === 'toggle-body') { + const card = actEl.closest('.digest-card'); + if (card) { + const body = card.querySelector('.digest-body'); + if (body) { + const clamped = body.classList.toggle('clamp'); + actEl.textContent = clamped ? 'Показать полностью' : 'Свернуть'; + } + } + return; + } + if (action === 'reload') { await loadDigests(); return; } return; } }); @@ -611,7 +710,7 @@ const mine = currentUser && d.author_id === currentUser.id; if (admin || mine) openDigestModal(d); else { - const card = document.querySelector('[data-id="' + id + '"]'); + const card = document.querySelector('[data-page="digest"] .digest-card[data-id="' + id + '"]'); if (card) { card.scrollIntoView({ behavior: 'smooth', block: 'center' }); card.classList.add('digest-highlight'); setTimeout(function() { card.classList.remove('digest-highlight'); }, 1500); } } } diff --git a/server.js b/server.js index 4f62e24..9c37721 100644 --- a/server.js +++ b/server.js @@ -362,6 +362,7 @@ const NOTIFY_TYPES = { 'lesson.report': { label: 'Отчёт о занятии', hint: 'Тьютор сохранил отчёт о том, что прошли на занятии', icon: 'notebook-pen', level: 'info', enabled: true, admin: false }, 'lesson.ai.formatted': { label: 'Отчёт оформлен по шаблону', hint: 'ИИ привёл текст отчёта о занятии к деловому виду', icon: 'file-check', level: 'info', enabled: false, admin: false }, 'feedback.ai.ready': { label: 'Отзыв сгенерирован', hint: 'ИИ сформировал отзыв по результатам занятия', icon: 'message-square-heart', level: 'info', enabled: true, admin: false }, + 'feedback.ai.error': { label: 'Ошибка генерации отзыва', hint: 'ИИ не смог обработать отзыв после всех попыток', icon: 'message-square-x', level: 'warning', enabled: true, admin: false }, '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 }, @@ -6966,8 +6967,26 @@ async function onFeedbackDone({ row, status, text, aiText, error }) { }).catch(() => {}); if (status === 'done') { try { - const branchId = row.branch_id ?? null; - pushNotification('feedback.ai.ready', { id: row.id, resident: row.resident }, branchId).catch(() => {}); + await pushNotification({ + type: 'feedback.ai.ready', + title: `Отзыв сгенерирован: ${row.resident || row.group_name || 'занятие'}`, + body: String(text || aiText || '').slice(0, 300), + link: 'feedback.html', + target: { feedback_id: row.id, resident: row.resident || null }, + branchId: row.branch_id, + }); + } catch (e) {} + } + if (status === 'error') { + try { + await pushNotification({ + type: 'feedback.ai.error', + title: `Не удалось сгенерировать отзыв: ${row.resident || row.group_name || 'занятие'}`, + body: String(error || 'Ошибка обработки').slice(0, 300), + link: 'feedback.html', + target: { feedback_id: row.id, resident: row.resident || null }, + branchId: row.branch_id, + }); } catch (e) {} } }