async function init() {
if (!(await checkAuth())) return;
buildSidebar('shorts');
document.getElementById('addShortsBtn').addEventListener('click', () => openShortsModal(null));
document.getElementById('shortsCancel').addEventListener('click', closeModal);
document.getElementById('shortsSave').addEventListener('click', saveShorts);
document.getElementById('shortsClearBtn').addEventListener('click', resetShortsFilters);
document.getElementById('shortsModalUsed').addEventListener('change', e => {
const at = document.getElementById('shortsUsedAt');
if (e.target.checked && !at.value) at.value = todayIso();
if (!e.target.checked) at.value = '';
});
document.getElementById('shortsUsedAt').addEventListener('change', e => {
document.getElementById('shortsModalUsed').checked = !!e.target.value;
});
document.getElementById('shortsAiBtn').addEventListener('click', openShortsAi);
document.getElementById('aiImproveBtn').addEventListener('click', improveShortsAi);
document.getElementById('aiAcceptBtn').addEventListener('click', acceptShortsAi);
document.getElementById('aiRejectBtn').addEventListener('click', closeShortsAi);
document.getElementById('shortsDeltaSeg').addEventListener('click', e => {
const btn = e.target.closest('[data-delta]');
if (!btn) return;
setShortsDelta(parseInt(btn.dataset.delta, 10));
});
['shortsGroup', 'shortsDateFrom', 'shortsDateTo', 'shortsUsedFilter', 'shortsDeltaFilter', 'shortsOrder'].forEach(id => {
document.getElementById(id).addEventListener('change', () => { shortsPage = 1; loadShorts(); });
});
document.getElementById('shortsDeleted').addEventListener('change', () => { shortsPage = 1; loadShorts(); });
document.getElementById('shortsSearch').addEventListener('input', () => {
clearTimeout(shortsSearchTimer);
shortsSearchTimer = setTimeout(() => { shortsSearchTimer = null; shortsPage = 1; loadShorts(); }, 300);
});
document.getElementById('shortsSearch').addEventListener('keydown', e => {
if (e.key === 'Enter') { clearTimeout(shortsSearchTimer); shortsPage = 1; loadShorts(); }
});
document.getElementById('shortsLines').addEventListener('input', updateShortsLinesCount);
document.getElementById('shortsLines').addEventListener('keydown', e => {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { e.preventDefault(); saveShorts(); }
});
document.getElementById('shortsModal').addEventListener('click', e => { if (e.target.id === 'shortsModal') closeModal(); });
document.getElementById('aiCorrectModal').addEventListener('click', e => { if (e.target.id === 'aiCorrectModal') closeShortsAi(); });
document.addEventListener('keydown', e => {
if (e.key !== 'Escape') return;
if (document.getElementById('aiCorrectModal').classList.contains('open')) { closeShortsAi(); return; }
if (document.getElementById('shortsModal').classList.contains('open')) closeModal();
});
await loadShortsGroups();
connectShortsLive();
await loadShorts();
renderIcons();
}
let shortsLiveSource = null;
let shortsRefreshTimer = null;
function connectShortsLive() {
if (shortsLiveSource) { shortsLiveSource.close(); shortsLiveSource = null; }
const connect = () => {
const t = sessionStorage.getItem('authToken');
if (!t) return;
shortsLiveSource = new EventSource(`${API}/api/events?token=${encodeURIComponent(t)}`);
shortsLiveSource.addEventListener('shorts_changed', () => {
if (shortsRefreshTimer) return;
shortsRefreshTimer = setTimeout(() => {
shortsRefreshTimer = null;
loadShorts();
}, 300);
});
shortsLiveSource.onerror = () => {
if (shortsLiveSource) { shortsLiveSource.close(); shortsLiveSource = null; }
setTimeout(connect, 5000);
};
};
connect();
window.addEventListener('beforeunload', () => { if (shortsLiveSource) shortsLiveSource.close(); });
}
let shortsPage = 1;
const SHORTS_PAGE_SIZE = 50;
let shortsTotal = 0;
let shortsSearchTimer = null;
let shortsReqSeq = 0;
let editingId = null;
let shortsDelta = 0;
let shortsGroups = [];
const shortsRowsById = new Map();
function setShortsDelta(value) {
shortsDelta = (value === -1 || value === 1) ? value : 0;
document.querySelectorAll('#shortsDeltaSeg [data-delta]').forEach(b => {
b.classList.toggle('on', parseInt(b.dataset.delta, 10) === shortsDelta);
});
}
function currentShortsUser() {
try { return (typeof currentUser !== 'undefined') ? currentUser : null; } catch (e) { return null; }
}
function isTutorOrAdmin() {
const u = currentShortsUser();
return !!(u && (u.role === 'admin' || u.role === 'tutor'));
}
function isAdmin() {
const u = currentShortsUser();
return !!(u && u.role === 'admin');
}
async function loadShortsGroups() {
try {
const res = await fetch(`${API}/api/groups`, { headers: hdr() });
if (!res.ok) return;
const data = await res.json();
shortsGroups = Array.isArray(data) ? data : (data.groups || data.items || []);
const sel = document.getElementById('shortsGroup');
sel.innerHTML = '' +
shortsGroups.map(g => ``).join('');
} catch (e) {}
}
function activeFilters() {
const list = [];
if (document.getElementById('shortsSearch').value.trim()) list.push(document.getElementById('shortsSearch').value.trim());
if (document.getElementById('shortsGroup').value) {
const sel = document.getElementById('shortsGroup');
list.push(sel.options[sel.selectedIndex] ? sel.options[sel.selectedIndex].textContent : 'группа');
}
const from = document.getElementById('shortsDateFrom').value;
const to = document.getElementById('shortsDateTo').value;
if (from) list.push(`с ${from}`);
if (to) list.push(`по ${to}`);
if (document.getElementById('shortsUsedFilter').value !== '') {
list.push(document.getElementById('shortsUsedFilter').value === '1' ? 'использованные' : 'не использованные');
}
if (document.getElementById('shortsDeltaFilter').value !== '') {
const v = document.getElementById('shortsDeltaFilter').value;
list.push(v === '1' ? 'оценка +1' : v === '-1' ? 'оценка −1' : 'без оценки');
}
return list;
}
function resetShortsFilters() {
document.getElementById('shortsSearch').value = '';
document.getElementById('shortsGroup').value = '';
document.getElementById('shortsDateFrom').value = '';
document.getElementById('shortsDateTo').value = '';
document.getElementById('shortsUsedFilter').value = '';
document.getElementById('shortsDeltaFilter').value = '';
document.getElementById('shortsOrder').value = 'desc';
document.getElementById('shortsDeleted').checked = false;
clearTimeout(shortsSearchTimer);
shortsPage = 1;
loadShorts();
}
async function loadShorts() {
const list = document.getElementById('shortsList');
const reqSeq = ++shortsReqSeq;
const page = shortsPage;
list.innerHTML = '
';
document.getElementById('shortsEmpty').style.display = 'none';
document.getElementById('shortsState').textContent = 'Загрузка…';
const p = new URLSearchParams();
p.set('limit', SHORTS_PAGE_SIZE);
p.set('offset', (page - 1) * SHORTS_PAGE_SIZE);
const search = document.getElementById('shortsSearch').value.trim();
if (search) p.set('search', search);
const group = document.getElementById('shortsGroup').value;
if (group) p.set('group_id', group);
const from = document.getElementById('shortsDateFrom').value;
if (from) p.set('date_from', from);
const to = document.getElementById('shortsDateTo').value;
if (to) p.set('date_to', to);
const used = document.getElementById('shortsUsedFilter').value;
if (used !== '') p.set('used', used);
const delta = document.getElementById('shortsDeltaFilter').value;
if (delta !== '') p.set('delta', delta);
const order = document.getElementById('shortsOrder').value;
if (order) p.set('order', order);
if (document.getElementById('shortsDeleted').checked) p.set('deleted', '1');
try {
const res = await fetch(`${API}/api/shorts?${p.toString()}`, { headers: hdr() });
const data = await res.json().catch(() => ({}));
if (reqSeq !== shortsReqSeq) return;
if (!res.ok) { showToast(data.error || 'Не удалось загрузить сообщения'); return; }
const items = data.items || [];
shortsTotal = data.total || 0;
const totalPages = Math.max(1, Math.ceil(shortsTotal / SHORTS_PAGE_SIZE));
if (page > totalPages) { shortsPage = totalPages; loadShorts(); return; }
const deletedMode = document.getElementById('shortsDeleted').checked;
renderShortsList(items, deletedMode);
const shown = items.length;
const fromNum = shown ? (page - 1) * SHORTS_PAGE_SIZE + 1 : 0;
document.getElementById('shortsState').textContent = shown
? `Показано ${fromNum}–${fromNum + shown - 1} из ${shortsTotal}`
: `Найдено 0 из ${shortsTotal}`;
const filters = activeFilters();
const hint = document.getElementById('shortsHint');
hint.textContent = filters.length ? `Фильтры: ${filters.join(', ')}` : '';
renderPager(document.getElementById('shortsPager'), page, totalPages, pg => { shortsPage = pg; loadShorts(); });
renderIcons();
} catch (e) {
if (reqSeq !== shortsReqSeq) return;
showToast('Ошибка загрузки: ' + e.message);
}
}
function highlight(text, term) {
const safe = esc(text == null ? '' : String(text));
if (!term) return safe;
const needle = term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
if (!needle) return safe;
return safe.replace(new RegExp(`(${needle})`, 'gi'), '$1');
}
function renderShortsList(items, deletedMode) {
const list = document.getElementById('shortsList');
const empty = document.getElementById('shortsEmpty');
shortsRowsById.clear();
items.forEach(it => shortsRowsById.set(String(it.id), it));
if (!items.length) {
list.innerHTML = '';
if (deletedMode) {
empty.innerHTML = 'В корзине нет сообщений';
} else if (activeFilters().length) {
empty.innerHTML = 'По выбранным фильтрам ничего не найдено
';
const btn = document.getElementById('shortsEmptyReset');
if (btn) btn.addEventListener('click', resetShortsFilters);
} else {
empty.innerHTML = 'Сообщений пока нет
';
const btn = document.getElementById('shortsEmptyAdd');
if (btn) btn.addEventListener('click', () => openShortsModal(null));
}
empty.style.display = '';
return;
}
empty.style.display = 'none';
const term = document.getElementById('shortsSearch').value.trim();
list.innerHTML = items.map(s => {
const delta = Number(s.delta || 0);
const deltaBadge = delta > 0 ? '+1'
: delta < 0 ? '−1' : '';
const topic = s.topic ? `${highlight(s.topic, term)}
` : '';
const author = s.author_name || s.author_username || '';
const usage = s.used
? ``
: ``;
const actions = deletedMode
? (isAdmin()
? ''
: '')
: '';
const meta = [
author ? `Автор: ${esc(author)}` : '',
s.used_at ? `использовано ${esc(String(s.used_at).slice(0, 10))}` : ''
].filter(Boolean).join(' · ');
return `
${highlight(s.resident || '', term)}
${esc(String(s.lesson_date || '').slice(0, 10))}
${deltaBadge}
${actions}
${topic}
${highlight(s.message || '', term)}
${usage}
${meta ? `${meta}` : ''}
`;
}).join('');
}
function onShortsListClick(e) {
const edit = e.target.closest('[data-edit]');
if (edit) { openShortsModal(shortsRowsById.get(edit.closest('.shorts-item').dataset.shortId)); return; }
const del = e.target.closest('[data-del]');
if (del) { delShorts(del.closest('.shorts-item').dataset.shortId); return; }
const restore = e.target.closest('[data-restore]');
if (restore) { restoreShorts(restore.closest('.shorts-item').dataset.shortId); return; }
const permanent = e.target.closest('[data-permanent]');
if (permanent) { permanentShorts(permanent.closest('.shorts-item').dataset.shortId); return; }
const toggle = e.target.closest('[data-toggle-used]');
if (toggle) { toggleUsed(toggle.closest('.shorts-item').dataset.shortId); return; }
}
document.getElementById('shortsList').addEventListener('click', onShortsListClick);
async function restoreShorts(id) {
if (!confirm('Восстановить сообщение из корзины?')) return;
try {
const res = await fetch(`${API}/api/shorts/${id}/restore`, { method: 'PUT', headers: hdr() });
if (!res.ok) { const err = await res.json().catch(() => ({})); showToast(err.error || 'Ошибка'); return; }
await loadShorts();
showToast('Сообщение восстановлено');
} catch (e) { showToast('Ошибка: ' + e.message); }
}
async function permanentShorts(id) {
if (!confirm('Удалить сообщение навсегда? Действие необратимо.')) return;
try {
const res = await fetch(`${API}/api/shorts/${id}/permanent`, { method: 'DELETE', headers: hdr() });
if (!res.ok) { const err = await res.json().catch(() => ({})); showToast(err.error || 'Ошибка'); return; }
await loadShorts();
showToast('Сообщение удалено навсегда');
} catch (e) { showToast('Ошибка: ' + e.message); }
}
async function toggleUsed(id) {
const row = shortsRowsById.get(String(id));
if (!row) return;
const next = !row.used;
try {
const res = await fetch(`${API}/api/shorts/${id}`, {
method: 'PUT',
headers: hdrJson(),
body: JSON.stringify({ used: next, used_at: next ? todayIso() : null })
});
if (!res.ok) { const err = await res.json().catch(() => ({})); showToast(err.error || 'Ошибка'); return; }
// Update only the current element's UI instead of reloading entire page
const chip = row.querySelector('[data-toggle-used]');
if (chip) {
if (next) {
chip.classList.add('on');
chip.innerHTML = ' Использовано';
chip.title = 'Снять отметку об использовании';
} else {
chip.classList.remove('on');
chip.innerHTML = ' Не использовано';
chip.title = 'Отметить как использованное';
}
renderIcons();
}
showToast(next ? 'Отмечено как использованное' : 'Отметка снята');
} catch (e) { showToast('Ошибка: ' + e.message); }
}
function openShortsModal(row) {
editingId = row ? row.id : null;
document.getElementById('shortsModalTitle').textContent = row ? `Сообщение #${row.id}` : 'Новое сообщение';
document.getElementById('shortsLinesHint').textContent = row
? 'Только текст сообщения'
: 'Формат: ФИО - текст или ФИО — текст; опц. −1/+1';
document.getElementById('shortsDate').value = row ? String(row.lesson_date || '').slice(0, 10) : todayIso();
document.getElementById('shortsTopic').value = row ? (row.topic || '') : '';
document.getElementById('shortsResident').value = row ? (row.resident || '') : '';
document.getElementById('shortsResidentField').style.display = row ? '' : 'none';
document.getElementById('shortsModalUsed').checked = row ? !!row.used : false;
document.getElementById('shortsUsedAt').value = row && row.used_at ? String(row.used_at).slice(0, 10) : '';
const usedDisplay = row ? '' : 'none';
document.getElementById('shortsUsedField').style.display = usedDisplay;
document.getElementById('shortsUsedAtField').style.display = usedDisplay;
const deltaField = document.getElementById('shortsDeltaField');
if (row && isTutorOrAdmin()) {
deltaField.style.display = '';
setShortsDelta(Number(row.delta || 0));
} else {
deltaField.style.display = 'none';
setShortsDelta(0);
}
document.getElementById('shortsLines').value = row ? (row.message || '') : '';
updateShortsLinesCount();
document.getElementById('shortsModal').classList.add('open');
setTimeout(() => document.getElementById('shortsLines').focus(), 40);
renderIcons();
}
function updateShortsLinesCount() {
const el = document.getElementById('shortsLinesCount');
if (!el) return;
const n = document.getElementById('shortsLines').value.split('\n').filter(l => l.trim()).length;
el.textContent = n ? `Строк: ${n}` : '';
}
function closeModal() {
document.getElementById('shortsModal').classList.remove('open');
}
async function saveShorts() {
const date = document.getElementById('shortsDate').value.trim();
const topic = document.getElementById('shortsTopic').value.trim() || null;
const linesText = document.getElementById('shortsLines').value.trim();
const residentOverride = document.getElementById('shortsResident').value.trim() || null;
const used = document.getElementById('shortsModalUsed').checked;
let usedAt = document.getElementById('shortsUsedAt').value.trim() || null;
if (used && !usedAt) usedAt = todayIso();
if (!used) usedAt = null;
if (!date) { showToast('Укажите дату занятия'); return; }
if (!linesText) { showToast('Укажите текст сообщения(я)'); return; }
let residentFromLine = residentOverride || '';
const lines = linesText.split('\n');
const parsed = [];
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) continue;
const match = trimmed.match(/^(.+?)\s*[-—]\s*(.+)$/);
if (match) {
parsed.push({ resident: match[1].trim(), message: match[2].trim() });
if (!residentFromLine) residentFromLine = match[1].trim();
} else {
parsed.push({ resident: residentOverride || 'Не указан', message: trimmed });
if (!residentFromLine) residentFromLine = residentOverride || 'Не указан';
}
}
if (!parsed.length) { showToast('Нет сообщений для добавления'); return; }
const saveBtn = document.getElementById('shortsSave');
saveBtn.disabled = true;
try {
let res;
if (editingId) {
const resident = residentOverride || parsed[0].resident || 'Не указан';
const message = parsed.map(p => p.message).join('\n');
res = await fetch(`${API}/api/shorts/${editingId}`, {
method: 'PUT',
headers: hdrJson(),
body: JSON.stringify({ resident, lesson_date: date, topic, message, used, used_at: usedAt, delta: shortsDelta })
});
} else {
res = await fetch(`${API}/api/shorts`, {
method: 'POST',
headers: hdrJson(),
body: JSON.stringify({ lesson_date: date, topic, lines: linesText, resident: residentOverride })
});
}
if (!res.ok) {
const err = await res.json().catch(() => ({}));
showToast(err.error || 'Ошибка');
return;
}
closeModal();
shortsPage = 1;
await loadShorts();
showToast(editingId ? 'Сообщение обновлено' : 'Сообщения добавлены');
} catch (e) {
showToast('Ошибка: ' + e.message);
} finally {
saveBtn.disabled = false;
}
}
async function delShorts(id) {
if (!confirm('Переместить сообщение в корзину?')) return;
try {
const res = await fetch(`${API}/api/shorts/${id}`, { method: 'DELETE', headers: hdr() });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
showToast(err.error || 'Ошибка');
return;
}
await loadShorts();
showToast('Сообщение перемещено в корзину');
} catch (e) {
showToast('Ошибка: ' + e.message);
}
}
let shortsAiBusy = false;
async function loadShortsAiModels() {
const [mineRes, optRes] = await Promise.allSettled([
fetch(`${API}/api/user-settings`, { headers: hdr() }),
fetch(`${API}/api/ai/profiles/options`, { headers: hdr() })
]);
const result = { native: 'Нативная', active: 'native', profiles: [], personal: [] };
if (optRes.status === 'fulfilled' && optRes.value.ok) {
const d = await optRes.value.json().catch(() => ({}));
if (d.native?.model) result.native = `Нативная — ${d.native.model}`;
result.active = d.active || 'native';
if (Array.isArray(d.profiles)) result.profiles = d.profiles;
}
if (mineRes.status === 'fulfilled' && mineRes.value.ok) {
const d = await mineRes.value.json().catch(() => ({}));
let arr = [];
try { arr = JSON.parse(d.settings?.feedback_models || '[]'); } catch (e) { arr = []; }
if (Array.isArray(arr)) result.personal = arr.filter(m => m && m.id);
}
return result;
}
function shortsAiNativeOption(label) {
const o = document.createElement('option');
o.value = 'native';
o.textContent = label;
return o;
}
function shortsAiOptgroup(label, items) {
const grp = document.createElement('optgroup');
grp.label = label;
items.forEach(m => {
const o = document.createElement('option');
o.value = m.id;
o.textContent = [m.name, m.model].filter(Boolean).join(' — ');
grp.appendChild(o);
});
return grp;
}
async function openShortsAi() {
const src = document.getElementById('aiSourceText');
src.value = document.getElementById('shortsLines').value;
document.getElementById('aiSuggestion').textContent = '';
document.getElementById('aiCorrectModal').classList.add('open');
const sel = document.getElementById('aiModelSelect');
const keep = sel.value;
try {
const models = await loadShortsAiModels();
sel.innerHTML = '';
if (isAdmin()) {
if (models.personal.length) sel.appendChild(shortsAiOptgroup('Мои модели', models.personal));
const sys = shortsAiOptgroup('Системные', models.profiles);
sys.insertBefore(shortsAiNativeOption(models.native), sys.firstChild);
sel.appendChild(sys);
} else {
sel.appendChild(shortsAiNativeOption(models.native));
if (models.personal.length) sel.appendChild(shortsAiOptgroup('Мои модели', models.personal));
}
sel.value = keep && [...sel.options].some(o => o.value === keep) ? keep
: ([...sel.options].some(o => o.value === models.active) ? models.active : 'native');
} catch (e) {
sel.innerHTML = '';
}
}
function closeShortsAi() {
document.getElementById('aiCorrectModal').classList.remove('open');
}
async function improveShortsAi() {
if (shortsAiBusy) return;
const text = document.getElementById('aiSourceText').value.trim();
if (!text) { showToast('Нет текста для улучшения'); return; }
const suggestionEl = document.getElementById('aiSuggestion');
const btn = document.getElementById('aiImproveBtn');
shortsAiBusy = true;
btn.disabled = true;
suggestionEl.textContent = 'Обработка...';
try {
const res = await fetch(`${API}/api/shorts/ai-correct`, {
method: 'POST',
headers: hdrJson(),
body: JSON.stringify({ text, profile: document.getElementById('aiModelSelect').value })
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || 'Ошибка ИИ');
}
const data = await res.json();
suggestionEl.textContent = data.suggestion || text;
} catch (e) {
suggestionEl.textContent = 'Ошибка: ' + e.message;
showToast('ИИ недоступен: ' + e.message);
} finally {
shortsAiBusy = false;
btn.disabled = false;
}
}
function acceptShortsAi() {
const suggestion = document.getElementById('aiSuggestion').textContent;
if (suggestion && suggestion !== 'Обработка...' && !suggestion.startsWith('Ошибка:')) {
document.getElementById('shortsLines').value = suggestion;
updateShortsLinesCount();
}
closeShortsAi();
}
init();