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('
');
}
+ const bodyText = d.body || '';
+ const longBody = bodyText.length > 600;
+ const bodyHtml = '
' +
'
' +
'
' + 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 +
'';
}
+ 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) {}
}
}