let currentEntries = []; let seenEntryIds = new Set(); let highlightNewIds = new Set(); let highlightClearTimer = null; let editId = null; let editGroups = []; let editModules = []; let moduleNames = new Map(); let moduleFilterId = ''; const MODULE_LIST_LIMIT = 1000; let moduleSearchTimer = null; let editModuleSearchTimer = null; let moduleFilterSeq = 0; let editModuleSeq = 0; const moduleOptionsKeys = new Map(); let modulesLoaded = false; let groupsLoaded = false; let studentsLoaded = false; const PAGE_SIZE = 20; let page = 1; let totalEntries = 0; let searchTimer = null; let view = localStorage.getItem('journalView') === 'cards' ? 'cards' : 'list'; let aiCorrecting = false; let editDeletePhoto = false; let editAiSuggestion = null; let linkSettings = null; async function loadLinkSettings() { if (!linkSettings) { const res = await fetch(`${API}/api/settings`, { headers: hdr() }); linkSettings = await res.json().catch(() => ({})); } return linkSettings; } function isImageFile(name) { return /\.(jpe?g|jfif|png|gif|webp|bmp|avif|svg|ico)$/i.test(name || ''); } function isPlayableVideoFile(name) { return /\.(mp4|m4v|webm|ogv)$/i.test(name || ''); } function isVideoFile(name) { return /\.(mp4|m4v|webm|ogv|mov|mkv|avi|mpeg|mpg|3gp|ts)$/i.test(name || ''); } function mainPhotoPath(e) { if (e.photo_path) return e.photo_path; if (e.photos && e.photos.length) return e.photos[0].photo_path; return null; } function journalImgHTML(mp) { return `
Загрузка…
`; } const REPORT_CARD_FIELDS = [ { key: 'photo', label: 'Фото' }, { key: 'lastname', label: 'Фамилия' }, { key: 'firstname', label: 'Имя' }, { key: 'group', label: 'Группа' }, { key: 'module', label: 'Модуль' }, { key: 'topic', label: 'Сообщение' }, { key: 'date', label: 'Дата и время' }, { key: 'files', label: 'Файлы' }, ]; const REPORT_CARD_FIELDS_KEY = 'reportCardFields'; const reportCardFields = loadReportCardFields(); const REPORT_CARD_EMBED_KEY = 'reportCardEmbedImages'; let reportCardEmbed = loadReportCardEmbed(); const REPORT_CARD_STUDENT_WORKS_KEY = 'reportCardStudentWorks'; let reportCardStudentWorks = loadReportCardStudentWorks(); const REPORT_CARD_LOGO_KEY = 'reportCardLogo'; let reportCardLogoOn = loadReportCardLogo(); let reportCardLogoSrc = ''; let reportCardEntryId = null; let galleryList = []; let galleryIndex = -1; const studentWorksCache = new Map(); const studentImagesCache = new Map(); let reportCardEmbedImages = []; function loadReportCardEmbed() { try { return localStorage.getItem(REPORT_CARD_EMBED_KEY) === '1'; } catch (err) { return false; } } function saveReportCardEmbed() { try { localStorage.setItem(REPORT_CARD_EMBED_KEY, reportCardEmbed ? '1' : '0'); } catch (err) { showToast('Не удалось сохранить настройку галереи', true); } } function loadReportCardStudentWorks() { try { return localStorage.getItem(REPORT_CARD_STUDENT_WORKS_KEY) === '1'; } catch (err) { return false; } } function saveReportCardStudentWorks() { try { localStorage.setItem(REPORT_CARD_STUDENT_WORKS_KEY, reportCardStudentWorks ? '1' : '0'); } catch (err) { showToast('Не удалось сохранить настройку «Фото на занятиях»', true); } } function loadReportCardLogo() { try { return localStorage.getItem(REPORT_CARD_LOGO_KEY) !== '0'; } catch (err) { return true; } } function saveReportCardLogo() { try { localStorage.setItem(REPORT_CARD_LOGO_KEY, reportCardLogoOn ? '1' : '0'); } catch (err) { showToast('Не удалось сохранить настройку «Логотип»', true); } } function reportCardEmbedTokens() { return new Set(reportCardEmbedImages.map(f => f.token)); } function loadReportCardFields() { const all = REPORT_CARD_FIELDS.map(f => f.key); try { const raw = JSON.parse(localStorage.getItem(REPORT_CARD_FIELDS_KEY) || 'null'); if (Array.isArray(raw)) return all.filter(k => raw.includes(k)); } catch (err) { return all; } return all; } function saveReportCardFields() { try { localStorage.setItem(REPORT_CARD_FIELDS_KEY, JSON.stringify(reportCardFields)); } catch (err) { showToast('Не удалось сохранить настройки полей', true); } } function reportCardFieldOn(key) { return reportCardFields.includes(key); } function splitStudentName(full) { const s = String(full || '').trim(); const i = s.indexOf(' '); if (i < 0) return { lastname: s, firstname: '' }; return { lastname: s.slice(0, i), firstname: s.slice(i + 1).trim() }; } function reportCardFilesHTML(e) { const hidden = reportCardEmbed ? reportCardEmbedTokens() : null; const files = (e.files || []).filter(f => !(hidden && hidden.has(f.token))); if (!files.length) return ''; return `
${files.map(f => { const url = `${API}/api/files/${f.token}`; if (isImageFile(f.name)) return `${esc(f.name)}`; if (isPlayableVideoFile(f.name)) return `${esc(f.name)}`; const note = isVideoFile(f.name) ? 'Скачать (браузер не умеет играть этот формат)' : 'Скачать'; return `${esc(f.name)}`; }).join('')}
`; } function reportCardGalleryHTML() { if (!reportCardEmbed) return ''; return ''; } function paintReportCardEmbedGallery(box, images) { if (!box) return; box.classList.remove('is-loading'); if (!images.length) { box.remove(); galleryList = []; return; } galleryList = images.map(f => `${API}/api/files/${f.token}`); box.innerHTML = images.map((f, i) => { const url = `${API}/api/files/${f.token}`; return ``; }).join(''); settleReportGallery(box); equalizeReportGallery(box); } function equalizeReportGallery(root) { if (!root) return; const imgs = Array.from(root.querySelectorAll('.sc-gal__img')); if (!imgs.length) return; let pending = imgs.length; const apply = () => { requestAnimationFrame(() => { let maxH = 0; imgs.forEach(img => { const h = img.getBoundingClientRect().height; if (h > maxH) maxH = h; }); if (maxH > 0) { root.style.setProperty('--gal-h', `${Math.round(maxH)}px`); root.classList.add('is-equal'); } }); }; const done = () => { pending -= 1; if (pending <= 0) apply(); }; imgs.forEach(img => { if (img.complete && img.naturalWidth > 0) { done(); return; } img.addEventListener('load', done, { once: true }); img.addEventListener('error', done, { once: true }); }); } function settleReportGallery(root) { if (!root) return; root.querySelectorAll('.sc-gal__img').forEach(img => { const shot = img.closest('.sc-gal__shot'); const ready = () => { img.classList.add('is-loaded'); if (img.naturalWidth > 0 && img.naturalHeight > 0 && img.naturalWidth > img.naturalHeight) img.classList.add('is-landscape'); if (shot) shot.classList.add('is-ready'); }; const failed = () => { img.classList.add('is-error'); if (shot) shot.classList.add('is-error'); }; if (img.complete) { if (img.naturalWidth > 0) ready(); else failed(); return; } img.addEventListener('load', ready, { once: true }); img.addEventListener('error', failed, { once: true }); }); } async function hydrateReportCardEmbedGallery(e) { const box = document.getElementById('reportCardEmbedGallery'); if (!box) { reportCardEmbedImages = []; galleryList = []; return; } const name = String(e.student_name || '').trim(); if (!name) { reportCardEmbedImages = []; box.remove(); galleryList = []; return; } let images = studentImagesCache.get(name); if (!images) { box.innerHTML = ''; try { const res = await fetch(`${API}/api/students/image-files-by-name?name=${encodeURIComponent(name)}&limit=3`, { headers: hdr() }); const data = await res.json(); images = (data.files || []).filter(f => f && f.token); studentImagesCache.set(name, images); } catch (err) { if (reportCardEntryId === e.id) { const cur = document.getElementById('reportCardEmbedGallery'); if (cur) cur.remove(); } return; } } if (reportCardEntryId !== e.id) return; reportCardEmbedImages = images; paintReportCardEmbedGallery(box, images); refreshReportCardFiles(e); renderIcons(); } function refreshReportCardFiles(e) { const el = document.getElementById('reportCardFiles'); const html = reportCardFilesHTML(e); if (!html) { if (el) el.remove(); return; } if (el) el.outerHTML = html; } function paintReportCardStudentWorks(box, photos, entryId) { if (!box || reportCardEntryId !== entryId) return; if (!photos.length) { box.remove(); return; } box.classList.remove('is-loading'); box.innerHTML = photos.map(p => ``).join(''); } async function hydrateReportCardStudentWorks(e) { const box = document.getElementById('reportCardStudentWorks'); if (!box) return; const name = String(e.student_name || '').trim(); if (!name) { box.remove(); return; } const key = `${name}#${e.id}`; const cached = studentWorksCache.get(key); if (cached) { paintReportCardStudentWorks(box, cached, e.id); return; } box.classList.add('is-loading'); box.innerHTML = ''; try { const res = await fetch(`${API}/api/students/works-by-name?name=${encodeURIComponent(name)}&limit=3&exclude_entry=${encodeURIComponent(e.id)}`, { headers: hdr() }); const data = await res.json(); const photos = (data.photos || []).filter(Boolean); studentWorksCache.set(key, photos); if (reportCardEntryId !== e.id) return; paintReportCardStudentWorks(document.getElementById('reportCardStudentWorks'), photos, e.id); } catch (err) { if (reportCardEntryId === e.id) { const cur = document.getElementById('reportCardStudentWorks'); if (cur) cur.remove(); } } } function reportCardMetaHTML(e) { let html = ''; if (reportCardFieldOn('date') && e.created_at) { html += `
${esc(fmtFull(e.created_at))}
`; } if (reportCardFieldOn('files')) html += reportCardFilesHTML(e); html += reportCardGalleryHTML(); if (reportCardStudentWorks && e.student_name) html += '
'; return html; } function moduleIconText(name) { const s = (name || '').trim().slice(0, 2); if (!s) return ''; return s.charAt(0).toUpperCase() + s.slice(1).toLowerCase(); } function renderReportCard(e) { const photo = document.getElementById('reportCardPhoto'); const noPhoto = document.getElementById('reportCardNoPhoto'); document.getElementById('reportCardMedia').hidden = !reportCardFieldOn('photo'); const mp = mainPhotoPath(e); if (mp) { photo.src = thumbSrc(mp); photo.dataset.img = `${API}${mp}`; photo.alt = e.student_name || ''; photo.hidden = false; noPhoto.hidden = true; } else { photo.src = ''; delete photo.dataset.img; photo.alt = ''; photo.hidden = true; noPhoto.hidden = false; } document.getElementById('reportCardLogo').hidden = !reportCardLogoOn || !reportCardLogoSrc; const name = splitStudentName(e.student_name); const lastEl = document.getElementById('reportCardLastName'); const firstEl = document.getElementById('reportCardFirstName'); lastEl.textContent = reportCardFieldOn('lastname') ? name.lastname : ''; firstEl.textContent = reportCardFieldOn('firstname') ? name.firstname : ''; document.getElementById('reportCardName').hidden = !lastEl.textContent && !firstEl.textContent; const topic = e.description || ''; const topicEl = document.getElementById('reportCardText'); topicEl.textContent = topic; topicEl.hidden = !reportCardFieldOn('topic') || !topic; const groupBadge = document.getElementById('reportCardTime'); const group = e.group_name || ''; groupBadge.textContent = group; groupBadge.parentElement.hidden = !reportCardFieldOn('group') || !group; const toolBadge = document.getElementById('reportCardModule').parentElement; const tool = e.module_name || ''; document.getElementById('reportCardModule').textContent = tool; document.getElementById('reportCardModuleIcon').textContent = moduleIconText(tool); toolBadge.hidden = !reportCardFieldOn('module') || !tool; const meta = document.getElementById('reportCardMeta'); reportCardEmbedImages = []; meta.innerHTML = reportCardMetaHTML(e); galleryList = []; settleReportGallery(meta); hydrateReportCardEmbedGallery(e); hydrateReportCardStudentWorks(e); renderIcons(); } function refreshReportCard() { if (reportCardEntryId === null) return; const e = currentEntries.find(x => x.id === reportCardEntryId); if (e) renderReportCard(e); } function openReportCard(id) { const e = currentEntries.find(x => x.id === id); if (!e) return; reportCardEntryId = id; renderReportCard(e); document.getElementById('reportCardModal').classList.add('open'); document.body.classList.add('report-card-open'); } function closeReportCard() { reportCardEntryId = null; galleryList = []; galleryIndex = -1; closeImgModal(); document.getElementById('reportCardModal').classList.remove('open'); document.body.classList.remove('report-card-open'); setReportFieldsOpen(false); } function fileExtLabel(name) { const m = String(name || '').match(/\.[^.\/]+$/); return m ? m[0].toLowerCase() : esc(name || ''); } function filesHTML(files) { if (!files || !files.length) return ''; return `
${files.map(f => { const url = `${API}/api/files/${f.token}`; const label = fileExtLabel(f.name); let link; if (isImageFile(f.name)) { link = `${label}`; } else if (isPlayableVideoFile(f.name)) { link = `${label}`; } else { link = `${label}`; } return `${link}`; }).join('')}
`; } const AI_STATUS_LABELS = { pending: 'ИИ: в очереди', processing: 'ИИ: проверяет…', done: 'ИИ: проверено', skipped: 'ИИ: пропущено', error: 'ИИ: ошибка', reverted: 'ИИ: возвращён оригинал', }; const AI_STATUS_ICONS = { pending: 'clock', processing: 'loader', done: 'circle-check', skipped: 'skip-forward', error: 'circle-alert', reverted: 'undo', }; function fmtRating(v) { const n = Number(v); return Number.isFinite(n) ? n.toFixed(1).replace('.', ',') : ''; } function entryRatingHTML(e) { const parts = []; if (e.module_name && e.module_rating_avg !== null && e.module_rating_avg !== undefined) { parts.push(`Модуль ★ ${esc(fmtRating(e.module_rating_avg))}`); } if (e.rating !== null && e.rating !== undefined && e.rating !== '') { parts.push(`Оценка ${esc(String(e.rating))}/10`); } return parts.length ? `
${parts.join('')}
` : ''; } function aiBadge(e) { if (!e || !e.ai_status) return ''; const st = e.ai_status; const label = AI_STATUS_LABELS[st] || `ИИ: ${st}`; const icon = AI_STATUS_ICONS[st] || 'sparkles'; return ``; } function findFile(id) { for (const e of currentEntries) { const f = (e.files || []).find(x => x.id === id); if (f) return f; } return null; } async function detachFile(id) { const f = findFile(id); if (!f) return; if (!confirm(`Открепить файл «${f.name}» от записи? Он переместится в «Файлы → Откреплённые».`)) return; const res = await fetch(`${API}/api/files/${id}/detach`, { method: 'POST', headers: hdr() }); if (res.ok) { showToast('Файл откреплён'); if (f.entry_id) refreshEntryCard(f.entry_id); else loadEntries(); } else { const err = await res.json().catch(() => ({})); alert(err.error || 'Ошибка'); } } function gridEntryHTML(e) { const mp = mainPhotoPath(e); return `
${mp ? journalImgHTML(mp) : ''}
${esc(e.student_name)}
${esc(e.group_name)}${e.module_name ? ' · ' + esc(e.module_name) : ''}
${entryRatingHTML(e)}
${esc(e.description)}${aiBadge(e)}
${filesHTML(e.files)}
${fmtFull(e.created_at)}
${mp ? `` : ''} ${mp ? `` : ''}
`; } function cardEntryHTML(e) { const mp = mainPhotoPath(e); return `
${mp ? journalImgHTML(mp) : `
`} ${e.group_name ? `${esc(e.group_name)}` : ''} ${e.module_name ? `${esc(e.module_name)}` : ''}
${esc(e.student_name)}
${entryRatingHTML(e)}
${esc(e.description)}${aiBadge(e)}
${filesHTML(e.files)}
${fmtFull(e.created_at)} ${mp ? `` : ''} ${mp ? `` : ''}
`; } function renderGrid() { const grid = document.getElementById('grid'); if (!currentEntries.length) { const fmt = d => d ? d.split('-').reverse().join('.') : ''; const from = fmt(document.getElementById('dateFrom').value); const to = fmt(document.getElementById('dateTo').value); let range = ''; if (from && to) range = ` за ${from} – ${to}`; else if (from) range = ` с ${from}`; else if (to) range = ` по ${to}`; grid.className = 'grid'; grid.innerHTML = `
Ничего не найдено${range}
`; return; } if (view === 'cards') { grid.className = 'journal-cards'; grid.innerHTML = currentEntries.map(cardEntryHTML).join(''); } else { grid.className = 'grid'; grid.innerHTML = currentEntries.map(gridEntryHTML).join(''); } const items = Array.from(grid.children); items.forEach((el, i) => { el.style.animationDelay = `${Math.min(i * 45, 500)}ms`; }); renderIcons(); settleJournalThumbs(grid); } function settleJournalThumbs(root) { if (!root) return; root.querySelectorAll('.img-media img.img-load, .img-media img.img-error').forEach((img) => { if (img.complete && img.naturalWidth > 0) { img.classList.remove('img-load', 'img-error'); img.classList.add('img-loaded'); } else if (img.complete && img.naturalWidth === 0) { img.classList.remove('img-load'); img.classList.add('img-error'); const sk = img.parentElement && img.parentElement.querySelector('.img-skeleton'); if (sk) sk.innerHTML = 'Нет фото'; } }); } function bindJournalThumbLoading() { const grid = document.getElementById('grid'); if (!grid) return; const settle = (img) => { if (!img || !img.classList) return; img.classList.remove('img-load', 'img-error'); img.classList.add('img-loaded'); }; const fail = (img) => { if (!img || !img.classList) return; img.classList.remove('img-load'); img.classList.add('img-error'); const sk = img.parentElement && img.parentElement.querySelector('.img-skeleton'); if (sk) sk.innerHTML = 'Нет фото'; }; grid.addEventListener('load', (e) => { if (e.target.tagName === 'IMG') settle(e.target); }, true); grid.addEventListener('error', (e) => { if (e.target.tagName === 'IMG') fail(e.target); }, true); } function refreshEntryCardDom(e) { const btn = document.querySelector(`[data-edit="${e.id}"]`); const card = btn ? btn.closest('.card, .journal-card') : null; if (!card) return; const tmp = document.createElement('div'); tmp.innerHTML = (view === 'cards' ? cardEntryHTML(e) : gridEntryHTML(e)).trim(); const fresh = tmp.firstElementChild; fresh.classList.remove('entry-enter', 'entry-appear'); fresh.style.animationDelay = ''; card.replaceWith(fresh); renderIcons(); settleJournalThumbs(fresh); } async function refreshEntryCard(id) { const res = await fetch(`${API}/api/entries/${id}`, { headers: hdr() }); if (!res.ok) return false; const e = await res.json(); const idx = currentEntries.findIndex(x => x.id === e.id); if (idx !== -1) currentEntries[idx] = e; refreshEntryCardDom(e); return true; } function setView(v) { view = v === 'cards' ? 'cards' : 'list'; localStorage.setItem('journalView', view); document.querySelectorAll('#viewToggle button').forEach(b => { b.classList.toggle('active', b.dataset.view === view); }); renderGrid(); } function setDefaultDates() { const today = todayIso(); document.getElementById('dateFrom').value = today; document.getElementById('dateTo').value = today; } async function loadGroupOptions() { if (groupsLoaded) return; const sel = document.getElementById('groupFilter'); while (sel.options.length > 1) sel.remove(1); const res = await fetch(`${API}/api/groups`, { headers: hdr() }); const groups = await res.json(); groups.forEach(g => { const o = document.createElement('option'); o.value = g.id; o.textContent = g.name; sel.appendChild(o); }); groupsLoaded = true; } function renderModuleOptions(datalistId, list, force) { list.forEach(m => moduleNames.set(m.name, m.id)); const dl = document.getElementById(datalistId); if (!dl) return; const input = document.querySelector(`input[list="${datalistId}"]`); const value = (input ? input.value : '').trim().toLowerCase(); if (!force && value && list.some(m => String(m.name).trim().toLowerCase() === value)) return; const key = list.map(m => m.name).join('\n'); if (!force && key === moduleOptionsKeys.get(datalistId)) return; moduleOptionsKeys.set(datalistId, key); dl.innerHTML = ''; list.forEach(m => { const opt = document.createElement('option'); opt.value = m.name; dl.appendChild(opt); }); } async function fetchModules(q, limit, attempts = 2) { const p = new URLSearchParams(); if (q) p.set('search', q); p.set('limit', String(limit)); p.set('active', '1'); for (let i = 0; i < attempts; i++) { try { const res = await fetch(`${API}/api/modules?${p}`, { headers: hdr() }); if (!res.ok) return null; const data = await res.json().catch(() => ({})); return data.modules || []; } catch (e) { if (i < attempts - 1) await new Promise(r => setTimeout(r, 600)); } } return null; } async function resolveModuleId(name) { const n = (name || '').trim(); if (!n) return ''; if (moduleNames.has(n)) return String(moduleNames.get(n)); const list = await fetchModules(n, 10); if (!list) return null; const lower = n.toLowerCase(); const exact = list.find(m => m.name.toLowerCase() === lower); return exact ? String(exact.id) : null; } async function loadModuleOptions() { const list = await fetchModules('', MODULE_LIST_LIMIT); if (list) { editModules = list; modulesLoaded = true; } renderModuleOptions('moduleFilterList', editModules); } async function applyModuleFilter() { const inp = document.getElementById('moduleFilter'); const resolved = await resolveModuleId(inp.value); if (resolved === null) { inp.value = ''; moduleFilterId = ''; showToast('Модуль не найден — фильтр сброшен'); } else { moduleFilterId = resolved; } page = 1; loadEntries(); } function fillEditModuleInput(entry) { const inp = document.getElementById('editModule'); if (!inp) return; if (entry.module_name && entry.module_id) moduleNames.set(entry.module_name, entry.module_id); inp.value = entry.module_name || ''; renderModuleOptions('editModuleList', editModules, true); } async function loadStudentOptions() { if (studentsLoaded) return; const dl = document.getElementById('studentFilterList'); const res = await fetch(`${API}/api/students/names`, { headers: hdr() }); const names = await res.json(); dl.innerHTML = names.map(n => ``).join(''); } sel.value = e.group_id; if (!modulesLoaded) await loadModuleOptions(); fillEditModuleInput(e); renderEditPhotos(e.photos || [], e.photo_path); document.getElementById('editModal').classList.add('open'); } function setEditRating(v) { const val = v === null || v === undefined ? '' : String(v); document.querySelectorAll('input[name="editRating"]').forEach(r => { r.checked = r.value === val; }); } function renderEditPhotos(photos, mainPath) { const preview = document.getElementById('editPhotoPreview'); preview.innerHTML = ''; if (!photos.length) return; photos.forEach((p) => { const isMain = p.photo_path === mainPath; const div = document.createElement('div'); div.className = 'file-preview-item'; div.style.cssText = 'display:flex;align-items:center;gap:8px;padding:6px 8px;background:var(--bg);border:1px solid var(--border);border-radius:6px;font-size:.8rem'; div.dataset.photoId = p.id; const applyStyle = isMain ? 'background:#16a34a;border:none;color:#fff;border-radius:6px;padding:4px 10px;font-size:.75rem;cursor:default;white-space:nowrap' : 'background:var(--card);border:1px solid var(--border);color:var(--text);border-radius:6px;padding:4px 10px;font-size:.75rem;cursor:pointer;white-space:nowrap'; div.innerHTML = ` ${esc(p.photo_path.split('/').pop())} `; preview.appendChild(div); const thumb = div.querySelector('img'); const showMissing = () => { const ph = document.createElement('span'); ph.textContent = 'нет файла'; ph.style.cssText = 'width:48px;height:48px;display:flex;align-items:center;justify-content:center;background:var(--bg);border:1px dashed var(--border);border-radius:4px;font-size:.6rem;color:var(--muted);text-align:center;line-height:1.1;flex:0 0 auto'; thumb.replaceWith(ph); }; thumb.addEventListener('error', showMissing); if (thumb.complete && thumb.naturalWidth === 0) showMissing(); div.querySelector('.delete-entry-photo').addEventListener('click', async () => { if (!confirm('Удалить это фото?')) return; const res = await fetch(`${API}/api/entries/${editId}/photos/${p.id}`, { method: 'DELETE', headers: hdr() }); if (res.ok) { div.remove(); showToast('Фото удалено'); refreshEntryCard(editId); } else { alert('Ошибка удаления'); } }); }); } async function applyMainPhoto(btn) { const div = btn.closest('.file-preview-item'); const photoId = div?.dataset.photoId; if (!photoId) return; btn.disabled = true; const res = await fetch(`${API}/api/entries/${editId}/photos/${photoId}/main`, { method: 'PUT', headers: hdr() }); if (!res.ok) { btn.disabled = false; const err = await res.json().catch(() => ({})); alert(err.error || 'Ошибка'); return; } document.querySelectorAll('#editPhotoPreview .apply-photo-btn').forEach(b => { b.disabled = false; b.textContent = 'Применить'; b.title = 'Сделать главным фото записи'; b.style.background = 'var(--card)'; b.style.color = 'var(--text)'; }); btn.disabled = true; btn.textContent = 'Применено ✓'; btn.title = 'Главное фото записи'; btn.style.background = '#16a34a'; btn.style.color = '#fff'; showToast('Главное фото обновлено'); refreshEntryCard(editId); } function closeEdit() { document.getElementById('editModal').classList.remove('open'); document.getElementById('editFiles').value = ''; document.getElementById('editFilesPreview').innerHTML = ''; document.getElementById('editPhoto').value = ''; document.getElementById('editPhotoPreview').innerHTML = ''; document.getElementById('editAiStatus').style.display = 'none'; setEditRating(''); editId = null; editDeletePhoto = false; } let enhanceEntryId = null; let enhanceSourceImg = null; let enhanceTimer = null; let enhanceSaving = false; let enhanceEngine = 'auto'; let enhanceEngineLoaded = false; let photoAiEnabled = false; let photoAiFaceMode = 'off'; let photoAiFaceModel = 'gfpgan'; let photoAiDevice = ''; let photoAiPollTimer = null; let enhanceAiResultPath = null; let enhanceAiJobId = null; let enhanceClipPos = 50; function setEnhanceClip(p) { enhanceClipPos = Math.min(100, Math.max(0, p)); document.getElementById('enhanceTop').style.clipPath = `inset(0 0 0 ${enhanceClipPos}%)`; document.getElementById('enhanceDivider').style.left = enhanceClipPos + '%'; } function showEnhanceResult(show) { document.getElementById('enhanceTop').style.display = show ? '' : 'none'; document.getElementById('enhanceLoading').style.display = show ? 'none' : ''; } function flashEnhanceResult() { const area = document.getElementById('enhanceCompare'); if (!area) return; area.classList.remove('enhance-flash'); void area.offsetWidth; area.classList.add('enhance-flash'); setTimeout(() => area.classList.remove('enhance-flash'), 1200); } function setBtnLabel(btn, text) { if (!btn) return; const icon = btn.querySelector('svg, i[data-lucide]'); btn.textContent = ''; if (icon) { btn.appendChild(icon); btn.appendChild(document.createTextNode(' ' + text)); } else { btn.textContent = text; } } function setEnhanceLoadingText(text) { const el = document.getElementById('enhanceLoading'); if (!el) return; el.style.display = ''; const textEl = document.getElementById('enhanceThinkingText'); if (textEl) textEl.textContent = text; const dots = el.querySelector('.enhance-thinking-dots'); if (dots) dots.style.display = ''; const progress = document.getElementById('enhanceProgress'); if (progress) progress.style.display = 'none'; } function setEnhanceLoadingProgress(pct, text) { const el = document.getElementById('enhanceLoading'); if (!el) return; el.style.display = ''; const textEl = document.getElementById('enhanceThinkingText'); if (textEl && text) textEl.textContent = text; const dots = el.querySelector('.enhance-thinking-dots'); if (dots) dots.style.display = pct >= 100 ? 'none' : ''; const progress = document.getElementById('enhanceProgress'); const bar = document.getElementById('enhanceProgressBar'); if (progress && bar) { progress.style.display = ''; bar.style.width = Math.min(100, Math.max(0, pct)) + '%'; } } let enhanceZoom = 1; let enhancePanX = 0; let enhancePanY = 0; function applyEnhanceTransform() { const t = `translate(${enhancePanX}px, ${enhancePanY}px) scale(${enhanceZoom})`; document.getElementById('enhanceStage').style.transform = t; document.getElementById('enhanceInner').style.transform = t; const area = document.getElementById('enhanceCompare'); area.classList.toggle('zoomed', enhanceZoom > 1); if (enhanceZoom <= 1) area.classList.remove('panning'); } function clampEnhancePan() { const rect = document.getElementById('enhanceCompare').getBoundingClientRect(); const minX = rect.width * (1 - enhanceZoom); const minY = rect.height * (1 - enhanceZoom); enhancePanX = Math.min(0, Math.max(minX, enhancePanX)); enhancePanY = Math.min(0, Math.max(minY, enhancePanY)); } function resetEnhanceZoom() { enhanceZoom = 1; enhancePanX = 0; enhancePanY = 0; applyEnhanceTransform(); } (function initEnhanceDrag() { const area = document.getElementById('enhanceCompare'); let dragging = false; let dividerDrag = false; let lastX = 0; let lastY = 0; const move = ev => { const rect = area.getBoundingClientRect(); setEnhanceClip(((ev.clientX - rect.left) / rect.width) * 100); }; area.addEventListener('pointerdown', ev => { dividerDrag = !!ev.target.closest('#enhanceDivider'); dragging = true; lastX = ev.clientX; lastY = ev.clientY; area.setPointerCapture(ev.pointerId); if (!dividerDrag && enhanceZoom === 1) move(ev); }); area.addEventListener('pointermove', ev => { if (!dragging) return; if (dividerDrag || enhanceZoom === 1) { move(ev); } else { area.classList.add('panning'); enhancePanX += ev.clientX - lastX; enhancePanY += ev.clientY - lastY; lastX = ev.clientX; lastY = ev.clientY; clampEnhancePan(); applyEnhanceTransform(); } }); const end = () => { dragging = false; area.classList.remove('panning'); }; area.addEventListener('pointerup', end); area.addEventListener('pointercancel', end); area.addEventListener('wheel', ev => { ev.preventDefault(); const rect = area.getBoundingClientRect(); const cx = ev.clientX - rect.left; const cy = ev.clientY - rect.top; const prev = enhanceZoom; const next = Math.min(5, Math.max(1, enhanceZoom * (ev.deltaY < 0 ? 1.15 : 1 / 1.15))); if (next === prev) return; enhanceZoom = next; enhancePanX = cx - (cx - enhancePanX) * (next / prev); enhancePanY = cy - (cy - enhancePanY) * (next / prev); clampEnhancePan(); applyEnhanceTransform(); }, { passive: false }); area.addEventListener('dblclick', resetEnhanceZoom); })(); const PHOTO_AI_MODES = { x2: { model: 'x2plus', face: 'off', face_model: null, title: 'Универсально (x2)' }, x4: { model: 'general-x4v3', face: 'off', face_model: null, title: 'Быстро (x4)' }, faces: { model: 'x2plus', face: 'face', face_model: null, title: 'Лица (восстановление)' }, facesbg: { model: 'x2plus', face: 'all', face_model: null, title: 'Лица + фон' }, }; function photoAiMode() { const sel = document.getElementById('enhanceAiMode'); const key = sel && PHOTO_AI_MODES[sel.value] ? sel.value : 'x2'; const m = { ...PHOTO_AI_MODES[key] }; m.face_model = m.face === 'off' ? null : photoAiFaceModel; return m; } function defaultPhotoAiModeKey() { if (photoAiFaceMode === 'all') return 'facesbg'; if (photoAiFaceMode === 'face') return 'faces'; return 'x2'; } function updateAiHint() { const hint = document.getElementById('enhanceAiHint'); if (!hint) return; const cpu = photoAiDevice.startsWith('cpu'); hint.textContent = cpu ? 'Фото-ИИ считает на CPU — лицевые режимы могут занять несколько минут' : ''; hint.style.display = photoAiEnabled && cpu ? '' : 'none'; } async function loadPhotoAiDevice() { if (!isAdmin()) return; try { const r = await fetch(`${API}/api/photo-ai/health`, { headers: hdr() }); if (!r.ok) return; const h = await r.json(); if (h && h.device) photoAiDevice = String(h.device); updateAiHint(); } catch (e) {} } async function loadEnhanceEngine() { if (enhanceEngineLoaded) return; enhanceEngineLoaded = true; try { const r = await fetch(`${API}/api/public-settings`); const f = await r.json(); if (['auto', 'server', 'client'].includes(f.photo_enhance_engine)) enhanceEngine = f.photo_enhance_engine; photoAiEnabled = f.photo_ai_enabled === 'true'; if (['off', 'face', 'all'].includes(f.photo_ai_face_mode)) photoAiFaceMode = f.photo_ai_face_mode; if (['gfpgan', 'codeformer'].includes(f.photo_ai_face_model)) photoAiFaceModel = f.photo_ai_face_model; const sel = document.getElementById('enhanceAiMode'); if (sel) sel.value = defaultPhotoAiModeKey(); loadPhotoAiDevice(); } catch (e) {} } async function runPhotoAi() { if (!enhanceEntryId || enhanceSaving) return; const entryId = enhanceEntryId; const mode = photoAiMode(); const faceNote = mode.face === 'off' ? 'Может занять до минуты на CPU.' : `Восстановление лиц (${mode.face_model}), на CPU может занять несколько минут.`; if (!confirm(`ИИ-обработка фото: ${mode.title}. ${faceNote} Продолжить?`)) return; enhanceSaving = true; const btn = document.getElementById('enhanceAiBtn'); if (btn) btn.disabled = true; try { const res = await fetch(`${API}/api/entries/${entryId}/photo/enhance-ai`, { method: 'POST', headers: hdrJson(), body: JSON.stringify({ model: mode.model, face: mode.face, face_model: mode.face_model }), }); if (!res.ok) { const err = await res.json().catch(() => ({})); throw new Error(err.error || 'Ошибка запуска ИИ'); } const { jobId } = await res.json(); enhanceAiJobId = jobId; showEnhanceResult(false); setEnhanceLoadingProgress(0, mode.face === 'off' ? 'ИИ обрабатывает фото...' : 'ИИ обрабатывает фото и восстанавливает лица...'); setBtnLabel(btn, '⏳ ИИ...'); let doneHandled = false; const result = await new Promise((resolve, reject) => { photoAiPollTimer = setInterval(async () => { if (doneHandled) return; try { const r = await fetch(`${API}/api/entries/${entryId}/photo/enhance-ai/${jobId}`, { headers: hdr() }); if (!r.ok) throw new Error('Ошибка опроса статуса'); const s = await r.json(); if (doneHandled) return; if (s.status === 'done') { doneHandled = true; clearInterval(photoAiPollTimer); setEnhanceLoadingProgress(100, 'Загрузка результата...'); resolve(s); } else if (s.status === 'error') { doneHandled = true; clearInterval(photoAiPollTimer); showEnhanceResult(true); reject(new Error(s.error || 'Ошибка ИИ')); } else { const progress = Math.min(95, Date.now() % 10000 / 100); setEnhanceLoadingProgress(progress, mode.face === 'off' ? 'ИИ обрабатывает фото...' : 'ИИ обрабатывает фото и восстанавливает лица...'); } } catch (e) { doneHandled = true; clearInterval(photoAiPollTimer); showEnhanceResult(true); reject(e); } }, 500); }); showToast('ИИ результат готов'); enhanceAiResultPath = result.photo_path; const aiImg = new Image(); aiImg.onload = () => { enhanceSourceImg = aiImg; ['Brightness', 'Contrast', 'Saturate'].forEach(k => { document.getElementById('enhance' + k).value = 100; document.getElementById('enhance' + k + 'Val').textContent = '100%'; }); document.getElementById('enhanceSharp').value = 0; document.getElementById('enhanceSharpVal').textContent = '0%'; document.getElementById('enhanceDenoise').value = 0; document.getElementById('enhanceDenoiseVal').textContent = '0%'; renderEnhancePreview(); flashEnhanceResult(); }; aiImg.onerror = () => { showEnhanceResult(true); showToast('Не удалось загрузить результат ИИ'); }; aiImg.src = `${API}${result.photo_path}`; } catch (e) { showEnhanceResult(true); alert(e.message); } finally { enhanceSaving = false; if (btn) btn.disabled = false; setBtnLabel(btn, 'ИИ'); } } async function restoreOriginal() { if (!enhanceEntryId || enhanceSaving) return; if (!confirm('Вернуть исходную фотографию? Текущая улучшенная версия будет удалена.')) return; enhanceSaving = true; const btn = document.getElementById('enhanceRestoreBtn'); btn.disabled = true; try { const res = await fetch(`${API}/api/entries/${enhanceEntryId}/photo/restore-original`, { method: 'POST', headers: hdr() }); if (!res.ok) { const err = await res.json().catch(() => ({})); throw new Error(err.error || 'Ошибка восстановления'); } const savedId = enhanceEntryId; showToast('Оригинал возвращён'); closeEnhance(); refreshEntryCard(savedId); } catch (e) { alert(e.message); } finally { enhanceSaving = false; btn.disabled = false; } } function openEnhance(id) { const e = currentEntries.find(x => x.id === id); if (!e) return; const mp = mainPhotoPath(e); if (!mp) { showToast('У записи нет фото'); return; } enhanceEntryId = id; enhanceSourceImg = null; enhanceAiResultPath = null; enhanceAiJobId = null; ['Brightness', 'Contrast', 'Saturate'].forEach(k => { const el = document.getElementById('enhance' + k); el.value = 100; document.getElementById('enhance' + k + 'Val').textContent = '100%'; }); const sharp = document.getElementById('enhanceSharp'); sharp.value = 0; document.getElementById('enhanceSharpVal').textContent = '0%'; const orig = document.getElementById('enhanceOrig'); orig.src = `${API}${mp}`; document.getElementById('enhanceRestoreBtn').style.display = e.photo_original_path ? '' : 'none'; const aiBtn = document.getElementById('enhanceAiBtn'); if (aiBtn) { aiBtn.disabled = false; setBtnLabel(aiBtn, 'ИИ'); } loadEnhanceEngine().then(() => { const show = photoAiEnabled ? '' : 'none'; document.getElementById('enhanceAiBtn').style.display = show; document.getElementById('enhanceAiMode').style.display = show; updateAiHint(); }); const canvas = document.getElementById('enhanceCanvas'); setEnhanceClip(50); resetEnhanceZoom(); showEnhanceResult(false); setEnhanceLoadingProgress(0, 'Загрузка...'); renderIcons(); const img = new Image(); img.onload = () => { if (enhanceAiResultPath) return; enhanceSourceImg = img; renderEnhancePreview(); }; img.onerror = () => { const loadingEl = document.getElementById('enhanceLoading'); if (loadingEl) { const textEl = document.getElementById('enhanceThinkingText'); if (textEl) textEl.textContent = 'Не удалось загрузить фото'; const dots = loadingEl.querySelector('.enhance-thinking-dots'); if (dots) dots.style.display = 'none'; const progress = document.getElementById('enhanceProgress'); if (progress) progress.style.display = 'none'; } }; img.src = `${API}${mp}`; document.getElementById('enhanceModal').classList.add('open'); } function isDefaultEnhanceParams() { const p = enhanceParams(); return p.brightness === 100 && p.contrast === 100 && p.saturate === 100 && p.denoise === 0 && p.sharp === 0; } async function applyAiResult(signal) { if (!enhanceAiJobId || !enhanceEntryId) return false; const res = await fetch(`${API}/api/entries/${enhanceEntryId}/photo/jobs/${enhanceAiJobId}/apply`, { method: 'POST', headers: hdr(), signal, }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Ошибка применения ИИ-результата'); enhanceAiResultPath = null; enhanceAiJobId = null; return true; } function cleanupAiPreview() { if (!enhanceEntryId) return; if (enhanceAiJobId) { fetch(`${API}/api/entries/${enhanceEntryId}/photo/jobs/${enhanceAiJobId}/reject`, { method: 'POST', headers: hdr(), }).catch(() => {}); } else if (enhanceAiResultPath) { fetch(`${API}/api/entries/${enhanceEntryId}/photo/enhance-ai/preview`, { method: 'DELETE', headers: hdrJson(), body: JSON.stringify({ path: enhanceAiResultPath }), }).catch(() => {}); } enhanceAiResultPath = null; enhanceAiJobId = null; } function closeEnhance() { cleanupAiPreview(); document.getElementById('enhanceModal').classList.remove('open'); document.getElementById('photoHistoryModal').classList.remove('open'); enhanceEntryId = null; enhanceSourceImg = null; enhanceAiResultPath = null; const loadingEl = document.getElementById('enhanceLoading'); if (loadingEl) loadingEl.style.display = 'none'; } let cpuEnhanceEntryId = null; let cpuEnhanceSaving = false; let cpuEnhanceAiJobId = null; let cpuEnhanceAiResultPath = null; let cpuEnhancePreviewUrl = ''; let cpuEnhanceParamsTouched = false; let cpuEnhanceActiveKey = ''; let cpuEnhanceDevice = { device: '', name: '', ready: false }; let cpuEnhanceZoom = 1; let cpuEnhancePanX = 0; let cpuEnhancePanY = 0; let cpuEnhanceView = 'split'; let cpuEnhanceBusy = false; let cpuEnhanceReturnFocus = null; const CPU_ENHANCE_SLIDERS = ['Quality', 'Clarity', 'Denoise', 'Sharp', 'Brightness', 'Contrast', 'Saturate', 'Warmth']; const CPU_ENHANCE_DEFAULTS = { Quality: 92, Clarity: 40, Denoise: 0, Sharp: 30, Brightness: 100, Contrast: 100, Saturate: 100, Warmth: 0 }; const CPU_ENHANCE_PREVIEW_MAX_PX = 1400; function cpuEnhanceSliderLabel(k) { const el = document.getElementById('cpuEnhance' + k); if (!el) return ''; const v = parseInt(el.value, 10) || 0; if (k === 'Warmth') return (v > 0 ? '+' : '') + v; if (k === 'Quality') return v + '%'; return String(v); } function cpuEnhanceSyncSlider(k) { const el = document.getElementById('cpuEnhance' + k); if (!el) return; const text = cpuEnhanceSliderLabel(k); const out = document.getElementById('cpuEnhance' + k + 'Val'); if (out) out.textContent = text; el.setAttribute('aria-valuetext', text); const field = el.closest('.settings-field'); if (field) field.classList.toggle('is-changed', parseInt(el.value, 10) !== CPU_ENHANCE_DEFAULTS[k]); } function cpuEnhanceHasResult() { const el = document.getElementById('cpuEnhanceResult'); return !!(el && el.getAttribute('src')); } function cpuEnhanceSetResultSrc(src) { const el = document.getElementById('cpuEnhanceResult'); const empty = document.getElementById('cpuEnhanceEmpty'); if (el) { if (src) el.src = src; else el.removeAttribute('src'); } const area = document.getElementById('cpuEnhanceCompare'); if (area) area.classList.toggle('no-result', !src); if (empty) empty.hidden = !!src; if (!src && cpuEnhanceView !== 'orig') cpuEnhanceSetView('split'); } function cpuEnhanceSetError(msg) { const box = document.getElementById('cpuEnhanceError'); const text = document.getElementById('cpuEnhanceErrorText'); if (text) text.textContent = msg || ''; if (box) box.hidden = !msg; } function cpuEnhanceClearError() { cpuEnhanceSetError(''); } function cpuEnhanceFocusables() { const modal = document.getElementById('cpuEnhanceModal'); if (!modal) return []; return [...modal.querySelectorAll('button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])')] .filter(el => el.offsetParent !== null || el.id === 'cpuEnhanceCompare'); } function cpuEnhanceReadParams() { const get = id => document.getElementById('cpuEnhance' + id); const num = id => parseInt(get(id).value, 10) || 0; const mode = get('Mode').value; const preset = mode === 'cpu' ? 'quality' : 'auto'; const params = { preset, scale: parseInt(get('Scale').value, 10) || 1, quality: num('Quality'), clarity: num('Clarity'), denoise: num('Denoise'), sharp: num('Sharp'), brightness: num('Brightness'), contrast: num('Contrast'), saturate: num('Saturate'), warmth: num('Warmth'), }; return params; } async function cpuEnhanceProbeDevice() { cpuEnhanceDevice = { device: '', name: '', ready: false }; try { const res = await fetch(`${API}/api/photo-ai/health`, { headers: hdr() }); if (!res.ok) throw new Error('health ' + res.status); const h = await res.json(); const dev = String(h && h.device ? h.device : ''); if (dev.startsWith('cuda')) cpuEnhanceDevice = { device: dev, name: String(h.device_name || 'GPU'), ready: true, gpu: true }; else if (dev === 'mps') cpuEnhanceDevice = { device: dev, name: String(h.device_name || 'Apple GPU'), ready: true, gpu: true }; else cpuEnhanceDevice = { device: dev || 'cpu', name: String((h && h.device_name) || 'CPU'), ready: false, gpu: false }; } catch (e) { cpuEnhanceDevice = { device: 'cpu', name: 'CPU (фото-ИИ недоступно)', ready: false, gpu: false }; } cpuEnhanceSetMode(cpuEnhanceDevice.gpu ? 'ai' : 'auto'); return cpuEnhanceDevice; } let cpuEnhanceBaseImg = null; let cpuEnhanceBaseKind = 'orig'; function cpuEnhanceNum(id) { const el = document.getElementById('cpuEnhance' + id); return el ? parseInt(el.value, 10) || 0 : 0; } function cpuEnhanceWarmthFilter(v) { if (!v) return ''; const t = Math.max(-100, Math.min(100, v)) / 100; const sep = 'sepia(' + Math.round(Math.abs(t) * 0.7) + ')'; return t > 0 ? 'sepia(' + Math.round(t * 0.5) + ') hue-rotate(' + Math.round(-8 * t) + 'deg) saturate(' + (1 + t * 0.25) + ')' : sep + ' hue-rotate(' + Math.round(8 * Math.abs(t)) + 'deg) saturate(1.1)'; } function cpuEnhanceUnsharpPass(ctx, w, h, amount) { if (amount <= 0) return; const img = ctx.getImageData(0, 0, w, h); const src = img.data; const out = new Uint8ClampedArray(src); const row = w * 4; const a = Math.max(0, Math.min(1, (amount / 100) * 0.9)); for (let y = 1; y < h - 1; y++) { for (let x = 1; x < w - 1; x++) { const i = y * row + x * 4; for (let ch = 0; ch < 3; ch++) { const c = src[i + ch]; const blur = (src[i - 4 + ch] + src[i + 4 + ch] + src[i - row + ch] + src[i + row + ch] + 2 * c) / 6; out[i + ch] = c + (c - blur) * a * 2; } } } ctx.putImageData(new ImageData(out, w, h), 0, 0); } let cpuEnhanceDrawRaf = 0; function cpuEnhanceDrawLocal() { if (cpuEnhanceDrawRaf) return; cpuEnhanceDrawRaf = requestAnimationFrame(() => { cpuEnhanceDrawRaf = 0; cpuEnhanceDrawLocalNow(); }); } function cpuEnhanceDrawLocalNow() { const result = document.getElementById('cpuEnhanceResult'); if (!result || !cpuEnhanceBaseImg) return; const img = cpuEnhanceBaseImg; const scale = Math.min(1, CPU_ENHANCE_PREVIEW_MAX_PX / (img.naturalWidth || 1)); const w = Math.max(1, Math.round((img.naturalWidth || 1) * scale)); const h = Math.max(1, Math.round((img.naturalHeight || 1) * scale)); const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; const ctx = canvas.getContext('2d'); const brightness = cpuEnhanceNum('Brightness'); const contrast = cpuEnhanceNum('Contrast'); const saturate = cpuEnhanceNum('Saturate'); const denoise = cpuEnhanceNum('Denoise'); const sharp = cpuEnhanceNum('Sharp'); const clarity = cpuEnhanceNum('Clarity'); const warmth = cpuEnhanceNum('Warmth'); const filters = []; if (brightness !== 100) filters.push('brightness(' + (brightness / 100) + ')'); if (contrast !== 100) filters.push('contrast(' + (contrast / 100) + ')'); if (saturate !== 100) filters.push('saturate(' + (saturate / 100) + ')'); const wf = cpuEnhanceWarmthFilter(warmth); if (wf) filters.push(wf); ctx.filter = filters.join(' ') || 'none'; ctx.drawImage(img, 0, 0, w, h); ctx.filter = 'none'; if (denoise > 0) { medianFilterPass(ctx, w, h); if (denoise > 70) medianFilterPass(ctx, w, h); } if (clarity > 0) cpuEnhanceUnsharpPass(ctx, w, h, clarity); if (sharp > 0) sharpenPass(ctx, w, h, sharp); const url = canvas.toDataURL('image/jpeg', Math.min(1, cpuEnhanceNum('Quality') / 100)); cpuEnhanceSetResultSrc(url); } function cpuEnhanceSetBaseImg(path) { cpuEnhanceBaseImg = null; cpuEnhanceBaseKind = 'orig'; const img = new Image(); img.onload = () => { if (String(cpuEnhanceBaseKind) !== 'orig') return; cpuEnhanceBaseImg = img; cpuEnhanceDrawLocal(); }; img.onerror = () => { cpuEnhanceBaseImg = null; }; img.src = `${API}${path}`; } function cpuEnhanceAdoptPreviewAsBase() { if (!cpuEnhancePreviewUrl) return; const img = new Image(); img.onload = () => { cpuEnhanceBaseImg = img; cpuEnhanceBaseKind = 'preview'; }; img.onerror = () => {}; img.src = cpuEnhancePreviewUrl; } function cpuEnhanceLoadAiBase() { if (!cpuEnhanceAiResultPath) return; const img = new Image(); img.onload = () => { cpuEnhanceBaseImg = img; cpuEnhanceBaseKind = 'result'; }; img.onerror = () => {}; img.src = `${API}${cpuEnhanceAiResultPath}`; } function cpuEnhanceSetBase(src, kind) { if (!src) return; cpuEnhanceBaseImg = src; cpuEnhanceBaseKind = kind === 'result' ? 'result' : 'orig'; cpuEnhanceDrawLocal(); } function cpuEnhanceParamsKey() { return JSON.stringify(cpuEnhanceReadParams()); } function cpuEnhanceIsDirty() { return cpuEnhanceActiveKey !== cpuEnhanceParamsKey(); } function cpuEnhanceSyncPending() { const dirty = cpuEnhanceIsDirty(); const ready = !!cpuEnhanceActiveKey; const mode = (document.getElementById('cpuEnhanceMode') || {}).value || 'auto'; const status = document.getElementById('cpuEnhanceStatus'); const text = document.getElementById('cpuEnhanceStatusText'); if (status) { status.classList.toggle('is-dirty', dirty && ready); status.classList.toggle('is-ok', ready && !dirty); status.classList.toggle('is-idle', !ready); } if (text) { if (!ready) text.textContent = 'Результата пока нет — настройте параметры и нажмите «Активировать»'; else if (dirty) text.textContent = 'Параметры изменены — результат устарел, нажмите «Активировать»'; else text.textContent = 'Результат готов — можно сохранять'; } const applyBtn = document.getElementById('cpuEnhanceApplyBtn'); if (applyBtn) { applyBtn.disabled = cpuEnhanceBusy || !ready || dirty; applyBtn.title = !ready ? 'Сначала получите результат — «Активировать»' : dirty ? 'Параметры изменены: обновите результат через «Активировать»' : 'Сохранить результат к записи'; } const activateBtn = document.getElementById('cpuEnhanceActivateBtn'); if (activateBtn) { activateBtn.disabled = cpuEnhanceBusy; activateBtn.classList.toggle('attention', dirty && ready && !cpuEnhanceBusy); } const previewBtn = document.getElementById('cpuEnhancePreviewBtn'); if (previewBtn) { const cpuOnly = mode === 'cpu'; previewBtn.disabled = cpuEnhanceBusy || !cpuOnly; previewBtn.title = cpuOnly ? 'Серверный предпросмотр текущих параметров' : 'Превью доступно только в режиме CPU — в режиме GPU жмите «Активировать»'; } const autoBtn = document.getElementById('cpuEnhanceAutoBtn'); if (autoBtn) autoBtn.disabled = cpuEnhanceBusy; const resetBtn = document.getElementById('cpuEnhanceResetBtn'); if (resetBtn) resetBtn.disabled = cpuEnhanceBusy; const applyCpuBtn = document.getElementById('cpuEnhanceApplyCpuBtn'); if (applyCpuBtn) applyCpuBtn.disabled = cpuEnhanceBusy; } function cpuEnhanceMarkApplied() { cpuEnhanceActiveKey = cpuEnhanceParamsKey(); cpuEnhanceSyncPending(); } function cpuEnhanceMarkCleared() { cpuEnhanceActiveKey = ''; cpuEnhanceSyncPending(); } function cpuEnhanceApplySuggested(s) { const set = (id, v) => { const el = document.getElementById('cpuEnhance' + id); if (!el) return; el.value = Math.max(parseInt(el.min, 10), Math.min(parseInt(el.max, 10), Math.round(v))); cpuEnhanceSyncSlider(id); }; if (!s) return; if (s.clarity !== undefined) set('Clarity', s.clarity); if (s.denoise !== undefined) set('Denoise', s.denoise); if (s.sharp !== undefined) set('Sharp', s.sharp); if (s.brightness !== undefined) set('Brightness', s.brightness); if (s.contrast !== undefined) set('Contrast', s.contrast); if (s.saturate !== undefined) set('Saturate', s.saturate); } function cpuEnhanceResetSliders(resetMode) { CPU_ENHANCE_SLIDERS.forEach(k => { const el = document.getElementById('cpuEnhance' + k); if (!el) return; el.value = CPU_ENHANCE_DEFAULTS[k]; cpuEnhanceSyncSlider(k); }); const scale = document.getElementById('cpuEnhanceScale'); if (scale) scale.value = '1'; if (resetMode) cpuEnhanceSetMode('auto'); } const CPU_ENHANCE_INFO_FMT = { 'Среднее': v => Math.round(v) + ' / 255', 'Контраст': v => Math.round(v), 'Резкость': v => Number(v).toFixed(1), }; function cpuEnhanceInfoValue(key, value) { const fmt = CPU_ENHANCE_INFO_FMT[key]; const n = Number(value); if (fmt && Number.isFinite(n)) return fmt(n); return String(value); } function cpuEnhanceSetInfo(analyze, extra) { const box = document.getElementById('cpuEnhanceInfo'); if (!box) return; const items = []; if (analyze) { items.push(['Размер', `${analyze.width}×${analyze.height}`]); items.push(['Среднее', analyze.mean]); items.push(['Контраст', analyze.stdev]); items.push(['Резкость', analyze.sharpness]); } if (extra) items.push(...extra); box.innerHTML = items.map(([k, v]) => { const wide = String(v).length > 22 ? ' is-wide' : ''; return `${esc(k)}: ${esc(cpuEnhanceInfoValue(k, v))}`; }).join(''); } function cpuEnhanceSetLoading(on, text, progress) { const el = document.getElementById('cpuEnhanceLoading'); const t = document.getElementById('cpuEnhanceLoadingText'); const track = document.getElementById('cpuEnhanceProgress'); const bar = document.getElementById('cpuEnhanceProgressBar'); const modal = document.getElementById('cpuEnhanceModal'); if (!el) return; el.style.display = on ? '' : 'none'; if (modal) modal.setAttribute('aria-busy', on ? 'true' : 'false'); if (t && text) t.textContent = text; if (track) track.hidden = !on; if (bar) { if (!on) { bar.classList.remove('indeterminate'); bar.style.width = '0%'; } else if (typeof progress === 'number') { bar.classList.remove('indeterminate'); bar.style.width = Math.max(2, Math.min(100, progress)) + '%'; } else { bar.classList.add('indeterminate'); } } cpuEnhanceSetBusy(!!on); } function cpuEnhanceSetBusy(on) { cpuEnhanceBusy = !!on; CPU_ENHANCE_SLIDERS.forEach(k => { const el = document.getElementById('cpuEnhance' + k); if (el) el.disabled = cpuEnhanceBusy; }); const mode = document.getElementById('cpuEnhanceMode'); const scale = document.getElementById('cpuEnhanceScale'); if (scale) scale.disabled = cpuEnhanceBusy; if (mode) mode.disabled = cpuEnhanceBusy; document.querySelectorAll('#cpuEnhanceModeGroup button[data-cpu-mode]').forEach(b => { b.disabled = cpuEnhanceBusy; }); cpuEnhanceSyncPending(); } function cpuEnhanceSetClip(pct) { const top = document.getElementById('cpuEnhanceTop'); const divider = document.getElementById('cpuEnhanceDivider'); if (!top || !divider) return; const v = Math.max(0, Math.min(100, pct)); top.style.clipPath = `inset(0 0 0 ${v}%)`; divider.style.left = `${v}%`; } function cpuEnhanceSetMode(mode) { const m = mode === 'ai' || mode === 'cpu' ? mode : 'auto'; const sel = document.getElementById('cpuEnhanceMode'); if (sel) sel.value = m; const gpuMode = m === 'ai' || m === 'auto'; const gpuActive = gpuMode && !!cpuEnhanceDevice.gpu; document.querySelectorAll('#cpuEnhanceModeGroup button[data-cpu-mode]').forEach(b => { const on = b.dataset.cpuMode === m; b.classList.toggle('active', on); b.setAttribute('aria-pressed', on ? 'true' : 'false'); }); const note = document.getElementById('cpuEnhanceGpuNote'); if (note) note.hidden = !gpuActive; const badge = document.getElementById('cpuEnhanceEngineBadge'); if (badge) { badge.classList.toggle('is-gpu', gpuActive); badge.classList.toggle('is-cpu', m === 'cpu'); badge.classList.toggle('is-warn', !gpuActive && m !== 'cpu'); if (m === 'cpu') badge.textContent = 'CPU · ' + (cpuEnhanceDevice.name || 'пайплайн'); else if (gpuActive) badge.textContent = 'GPU · ' + (cpuEnhanceDevice.name || 'photo-ai'); else if (m === 'ai') badge.textContent = 'GPU недоступен'; else badge.textContent = 'GPU недоступен → CPU'; } if (gpuActive && cpuEnhanceBaseKind === 'orig' && cpuEnhanceBaseImg) cpuEnhanceDrawLocal(); cpuEnhanceSyncPending(); } async function openCpuEnhance(id) { const e = currentEntries.find(x => x.id === id); if (!e) return; const mp = mainPhotoPath(e); if (!mp) { showToast('У записи нет фото'); return; } cpuEnhanceReturnFocus = document.activeElement; cpuEnhanceEntryId = id; cpuEnhanceSaving = false; cpuEnhanceAiJobId = null; cpuEnhanceAiResultPath = null; cpuEnhanceParamsTouched = false; cpuEnhanceActiveKey = ''; cpuEnhanceSetBusy(false); cpuEnhanceResetSliders(true); cpuEnhanceSetClip(50); cpuEnhanceResetZoom(); cpuEnhanceSetView('split'); const orig = document.getElementById('cpuEnhanceOrig'); if (orig) orig.src = `${API}${mp}`; cpuEnhanceClearResult(); cpuEnhanceSetBaseImg(mp); cpuEnhanceSetInfo(null, [['Движок', 'анализ…']]); cpuEnhanceClearError(); const applyLabel = document.getElementById('cpuEnhanceApplyLabel'); if (applyLabel) applyLabel.textContent = 'Сохранить'; const applyCpuLabel = document.getElementById('cpuEnhanceApplyCpuLabel'); if (applyCpuLabel) applyCpuLabel.textContent = 'Только эффекты'; const restoreBtn = document.getElementById('cpuEnhanceRestoreBtn'); if (restoreBtn) restoreBtn.style.display = e.photo_original_path ? '' : 'none'; const context = document.getElementById('cpuEnhanceContext'); if (context) { const parts = [e.student_name, e.group_name].filter(Boolean); if (e.module_name) parts.push(e.module_name); if (e.created_at) parts.push(fmtFull(e.created_at)); context.textContent = parts.join(' · '); } document.getElementById('cpuEnhanceModal').classList.add('open'); cpuEnhanceSetMode(cpuEnhanceDevice.gpu ? 'ai' : 'auto'); cpuEnhanceSyncPending(); renderIcons(); const compare = document.getElementById('cpuEnhanceCompare'); if (compare) compare.focus({ preventScroll: true }); cpuEnhanceProbeDevice(); } function cpuEnhanceClearResult() { if (cpuEnhancePreviewUrl) { if (cpuEnhancePreviewUrl.startsWith('blob:')) URL.revokeObjectURL(cpuEnhancePreviewUrl); cpuEnhancePreviewUrl = ''; } cpuEnhanceSetResultSrc(''); cpuEnhanceMarkCleared(); } async function cpuEnhanceAuto(showToastMsg) { if (!cpuEnhanceEntryId || cpuEnhanceSaving) return; cpuEnhanceClearError(); cpuEnhanceSetLoading(true, 'Анализ фото…'); try { const res = await fetch(`${API}/api/entries/${cpuEnhanceEntryId}/photo/cpu-analyze`, { method: 'POST', headers: hdrJson(), body: JSON.stringify({}), }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Ошибка анализа'); const kept = cpuEnhanceParamsTouched; if (!kept) cpuEnhanceApplySuggested(data.suggested); cpuEnhanceSetInfo(data.analyze, [ ['Движок', 'CPU'], ['ИИ доступен', data.ai_available ? 'да' : 'нет'], kept ? ['Авто', 'не применён — есть ручные правки'] : null, ].filter(Boolean)); if (showToastMsg) showToast(kept ? 'Авто-параметры рассчитаны, но ручные правки оставлены' : 'Параметры подобраны автоматически'); cpuEnhanceSyncPending(); } catch (e) { cpuEnhanceSetError(e.message); if (showToastMsg) showToast(e.message, true); } finally { cpuEnhanceSetLoading(false); } } async function cpuEnhancePreview() { if (!cpuEnhanceEntryId || cpuEnhanceSaving) return; const m = document.getElementById('cpuEnhanceMode').value; if (m === 'ai' || m === 'auto') { showToast('Превью доступно только в режиме CPU'); return; } cpuEnhanceClearError(); cpuEnhanceSetLoading(true, 'Предпросмотр…'); try { const res = await fetch(`${API}/api/entries/${cpuEnhanceEntryId}/photo/cpu-preview`, { method: 'POST', headers: hdrJson(), body: JSON.stringify({ params: cpuEnhanceReadParams(), width: 720 }), }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Ошибка предпросмотра'); const bytes = Uint8Array.from(atob(data.image_base64), c => c.charCodeAt(0)); if (cpuEnhancePreviewUrl && cpuEnhancePreviewUrl.startsWith('blob:')) URL.revokeObjectURL(cpuEnhancePreviewUrl); cpuEnhancePreviewUrl = URL.createObjectURL(new Blob([bytes], { type: 'image/jpeg' })); cpuEnhanceSetResultSrc(cpuEnhancePreviewUrl); cpuEnhanceAdoptPreviewAsBase(); if (data.params) cpuEnhanceApplySuggested(data.params); cpuEnhanceMarkApplied(); cpuEnhanceSetInfo(data.analyze, [['Превью', `${Math.round((data.bytes || 0) / 1024)} КБ`]]); } catch (e) { cpuEnhanceMarkCleared(); cpuEnhanceSetError(e.message); showToast(e.message, true); } finally { cpuEnhanceSetLoading(false); } } async function cpuEnhanceRunAi(entryId, mode) { cpuEnhanceSetLoading(true, 'Постановка ИИ-задачи…', 12); const res = await fetch(`${API}/api/entries/${entryId}/photo/enhance-cpu`, { method: 'POST', headers: hdrJson(), body: JSON.stringify({ mode: mode === 'auto' ? 'auto' : 'ai', params: cpuEnhanceReadParams(), face: 'face', face_model: 'gfpgan' }), }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Не удалось запустить ИИ'); if (!data.jobId) throw new Error('ИИ-задача не создана'); cpuEnhanceAiJobId = data.jobId; cpuEnhanceSetInfo(null, [['Движок', 'ИИ / photo-ai'], ['Задача', `#${data.jobId}`]]); const done = await cpuEnhancePollAi(entryId, data.jobId); cpuEnhanceAiResultPath = done.photo_path || ''; if (cpuEnhanceAiResultPath) { cpuEnhanceSetResultSrc(`${API}${cpuEnhanceAiResultPath}`); cpuEnhanceLoadAiBase(); cpuEnhanceSetView('result'); } cpuEnhanceMarkApplied(); cpuEnhanceSetInfo(null, [['Движок', 'ИИ / photo-ai'], ['Задача', `#${data.jobId}`]]); } async function cpuEnhanceRun() { if (!cpuEnhanceEntryId || cpuEnhanceSaving) return; const mode = document.getElementById('cpuEnhanceMode').value; const entryId = cpuEnhanceEntryId; if (mode === 'ai' || mode === 'auto') { cpuEnhanceSaving = true; cpuEnhanceClearError(); let fellBack = false; try { await cpuEnhanceRunAi(entryId, mode); } catch (e) { if (mode === 'auto') { fellBack = true; cpuEnhanceFallbackCpu(e.message); } else { cpuEnhanceMarkCleared(); cpuEnhanceSetError(e.message); showToast(e.message, true); } } finally { cpuEnhanceSaving = false; if (!fellBack) cpuEnhanceSetLoading(false); } return; } await cpuEnhancePreview(); } function cpuEnhanceFallbackCpu(reason) { cpuEnhanceDevice = { device: 'cpu', name: 'CPU (GPU недоступен)', ready: false, gpu: false }; cpuEnhanceSetMode('cpu'); showToast('GPU недоступен, переключаюсь на CPU'); cpuEnhanceSetInfo(null, [['Причина', reason || 'GPU недоступен'], ['Движок', 'CPU']]); cpuEnhanceSaving = false; cpuEnhancePreview(); } async function cpuEnhanceApply() { if (!cpuEnhanceEntryId || cpuEnhanceSaving) return; const mode = document.getElementById('cpuEnhanceMode').value; if (cpuEnhanceIsDirty()) { showToast('Параметры изменены — сначала обновите результат через «Активировать»', true); return; } if (!cpuEnhanceActiveKey) { showToast('Сначала нажмите «Активировать», чтобы получить результат', true); return; } cpuEnhanceSaving = true; cpuEnhanceClearError(); let fellBack = false; const applyLabel = document.getElementById('cpuEnhanceApplyLabel'); if (applyLabel) applyLabel.textContent = 'Сохраняю…'; cpuEnhanceSetBusy(true); cpuEnhanceSetLoading(true, 'Сохранение результата…'); const entryId = cpuEnhanceEntryId; try { if (cpuEnhanceAiJobId) { await cpuEnhanceApplyAi(entryId, cpuEnhanceAiJobId); showToast(cpuEnhanceDevice.gpu ? 'ИИ-результат сохранён' : 'Результат сохранён'); closeCpuEnhance(true); refreshEntryCard(entryId); return; } const payload = { mode, params: cpuEnhanceReadParams(), face: mode === 'cpu' ? 'off' : 'face', face_model: 'gfpgan', }; const res = await fetch(`${API}/api/entries/${entryId}/photo/enhance-cpu`, { method: 'POST', headers: hdrJson(), body: JSON.stringify(payload), }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Ошибка обработки'); if (data.jobId) { cpuEnhanceAiJobId = data.jobId; await cpuEnhancePollAi(entryId, data.jobId); await cpuEnhanceApplyAi(entryId, data.jobId); } else { showToast('Фото обработано'); } closeCpuEnhance(true); refreshEntryCard(entryId); } catch (e) { if (mode === 'auto' && /ИИ-обработка фото не настроена|503/i.test(e.message)) { cpuEnhanceFallbackCpu(e.message); fellBack = true; return; } cpuEnhanceSetError(e.message); showToast(e.message, true); } finally { cpuEnhanceSaving = false; if (applyLabel) applyLabel.textContent = 'Сохранить'; if (!fellBack) { cpuEnhanceSetLoading(false); cpuEnhanceSetBusy(false); } } } async function cpuEnhanceApplyCpuOnly() { if (!cpuEnhanceEntryId || cpuEnhanceSaving) return; const entryId = cpuEnhanceEntryId; const label = document.getElementById('cpuEnhanceApplyCpuLabel'); cpuEnhanceSaving = true; cpuEnhanceClearError(); if (label) label.textContent = 'Сохраняю…'; cpuEnhanceSetBusy(true); cpuEnhanceSetLoading(true, 'Применение эффектов…'); try { const res = await fetch(`${API}/api/entries/${entryId}/photo/enhance-cpu`, { method: 'POST', headers: hdrJson(), body: JSON.stringify({ mode: 'cpu', params: { ...cpuEnhanceReadParams(), preset: 'quality' }, face: 'off', face_model: 'gfpgan', }), }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Ошибка обработки'); showToast('Эффекты применены, ИИ не использовался'); closeCpuEnhance(true); refreshEntryCard(entryId); } catch (e) { cpuEnhanceSetError(e.message); showToast(e.message, true); } finally { cpuEnhanceSaving = false; if (label) label.textContent = 'Только эффекты'; cpuEnhanceSetLoading(false); } } function cpuEnhancePollAi(entryId, jobId) { return new Promise((resolve, reject) => { let done = false; const tick = async () => { if (done) return; try { const r = await fetch(`${API}/api/entries/${entryId}/photo/enhance-ai/${jobId}`, { headers: hdr() }); if (!r.ok) throw new Error('Ошибка опроса'); const s = await r.json(); if (done) return; if (s.status === 'done') { done = true; clearInterval(t); resolve(s); return; } if (s.status === 'error') { done = true; clearInterval(t); reject(new Error(s.error || 'Ошибка ИИ')); return; } if (s.status === 'pending') cpuEnhanceSetLoading(true, 'В очереди — ждём свободный воркер', 18); else cpuEnhanceSetLoading(true, 'ИИ обрабатывает фото…', 62); } catch (e) { done = true; clearInterval(t); reject(e); } }; const t = setInterval(tick, 1200); tick(); }); } async function cpuEnhanceApplyAi(entryId, jobId) { cpuEnhanceSetLoading(true, 'Сохранение результата…', 88); const res = await fetch(`${API}/api/entries/${entryId}/photo/jobs/${jobId}/apply`, { method: 'POST', headers: hdr() }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Ошибка применения ИИ-результата'); cpuEnhanceAiJobId = null; cpuEnhanceAiResultPath = null; } function closeCpuEnhance(force) { if (!force && cpuEnhanceActiveKey && cpuEnhanceIsDirty()) { if (!confirm('Параметры изменены, результат не сохранён. Закрыть без сохранения?')) return; } if (cpuEnhancePreviewUrl) { if (cpuEnhancePreviewUrl.startsWith('blob:')) URL.revokeObjectURL(cpuEnhancePreviewUrl); cpuEnhancePreviewUrl = ''; } if (cpuEnhanceAiJobId && cpuEnhanceEntryId) { const entryId = cpuEnhanceEntryId; const jobId = cpuEnhanceAiJobId; cpuEnhanceAiJobId = null; fetch(`${API}/api/entries/${entryId}/photo/jobs/${jobId}/reject`, { method: 'POST', headers: hdr() }).catch(() => {}); } cpuEnhanceAiResultPath = null; const modal = document.getElementById('cpuEnhanceModal'); if (modal) modal.classList.remove('open'); cpuEnhanceEntryId = null; cpuEnhanceSaving = false; cpuEnhanceSetBusy(false); cpuEnhanceClearResult(); cpuEnhanceResetZoom(); cpuEnhanceSetView('split'); cpuEnhanceClearError(); const restore = cpuEnhanceReturnFocus; cpuEnhanceReturnFocus = null; if (restore && typeof restore.focus === 'function' && document.contains(restore)) restore.focus({ preventScroll: true }); } function photoJobThumb(p) { if (!p) return ''; if (p.startsWith('/uploads/.originals/')) return `${API}${p}`; return `${API}/uploads/thumb/${p.split('/').pop()}`; } const PHOTO_JOB_ACTION_LABELS = { ai: 'ИИ-обработка', enhance: 'Улучшение', restore: 'Возврат оригинала', rollback: 'Откат' }; const PHOTO_JOB_STATUS_LABELS = { pending: 'В очереди', processing: 'Обрабатывается', done: 'Готово', error: 'Ошибка', rejected: 'Отклонено' }; async function loadPhotoHistory() { if (!enhanceEntryId) return; const list = document.getElementById('photoHistoryList'); list.innerHTML = '
Загрузка...
'; try { const res = await fetch(`${API}/api/entries/${enhanceEntryId}/photo/jobs`, { headers: hdr() }); if (!res.ok) throw new Error('Ошибка загрузки истории'); const rows = await res.json(); if (!rows.length) { list.innerHTML = '
Изменений фотографии пока не было.
'; return; } list.innerHTML = rows.map(r => { const before = r.before_path ? `было` : '—'; const after = r.after_path ? `стало` : '—'; const canApply = r.status === 'done' && r.applied === false && r.action === 'ai' && !!r.after_path; const canRollback = r.status === 'done' && r.before_path && r.action !== 'rollback' && !canApply; const err = r.error ? `
${esc(r.error)}
` : ''; const time = r.finished_at || r.created_at; return `
${before} было
→
${after} стало
${esc(PHOTO_JOB_ACTION_LABELS[r.action] || r.action)} ${esc(PHOTO_JOB_STATUS_LABELS[r.status] || r.status)} · ${esc(fmtFull(time))}
${err}
${canRollback ? `` : ''} ${canApply ? `` : ''}
`; }).join(''); } catch (e) { list.innerHTML = `
${esc(e.message)}
`; } } function openPhotoHistory() { document.getElementById('photoHistoryTitle').textContent = `История изменений фотографии — запись #${enhanceEntryId}`; document.getElementById('photoHistoryModal').classList.add('open'); loadPhotoHistory(); } async function rollbackPhotoJob(jobId) { if (!enhanceEntryId || enhanceSaving) return; if (!confirm('Откатить фотографию к сохранённой версии? Текущая версия сохранится в истории.')) return; enhanceSaving = true; try { const res = await fetch(`${API}/api/entries/${enhanceEntryId}/photo/jobs/${jobId}/rollback`, { method: 'POST', headers: hdr() }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Ошибка отката'); showToast('Фотография отката'); document.getElementById('photoHistoryModal').classList.remove('open'); const mp = data.photo_path; document.getElementById('enhanceOrig').src = `${API}${mp}`; showEnhanceResult(false); setEnhanceLoadingProgress(0, 'Загрузка...'); const img = new Image(); img.onload = () => { enhanceSourceImg = img; renderEnhancePreview(); }; img.onerror = () => { const loadingEl = document.getElementById('enhanceLoading'); if (loadingEl) { const textEl = document.getElementById('enhanceThinkingText'); if (textEl) textEl.textContent = 'Не удалось загрузить фото'; const dots = loadingEl.querySelector('.enhance-thinking-dots'); if (dots) dots.style.display = 'none'; const progress = document.getElementById('enhanceProgress'); if (progress) progress.style.display = 'none'; } }; img.src = `${API}${mp}`; refreshEntryCard(enhanceEntryId); } catch (e) { alert(e.message); } finally { enhanceSaving = false; } } function medianFilterPass(ctx, w, h) { const data = ctx.getImageData(0, 0, w, h); const src = data.data; const out = new Uint8ClampedArray(src); const row = w * 4; const win = new Array(9); for (let y = 1; y < h - 1; y++) { for (let x = 1; x < w - 1; x++) { const i = y * row + x * 4; for (let ch = 0; ch < 3; ch++) { win[0] = src[i - row - 4 + ch]; win[1] = src[i - row + ch]; win[2] = src[i - row + 4 + ch]; win[3] = src[i - 4 + ch]; win[4] = src[i + ch]; win[5] = src[i + 4 + ch]; win[6] = src[i + row - 4 + ch]; win[7] = src[i + row + ch]; win[8] = src[i + row + 4 + ch]; win.sort((a, b) => a - b); out[i + ch] = win[4]; } } } data.data.set(out); ctx.putImageData(data, 0, 0); } function sharpenPass(ctx, w, h, sharp) { const data = ctx.getImageData(0, 0, w, h); const src = data.data; const out = new Uint8ClampedArray(src); const row = w * 4; const a = (sharp / 100) * 1.5; for (let y = 1; y < h - 1; y++) { for (let x = 1; x < w - 1; x++) { const i = y * row + x * 4; for (let ch = 0; ch < 3; ch++) { const v = (1 + 4 * a) * src[i + ch] - a * src[i - 4 + ch] - a * src[i + 4 + ch] - a * src[i - row + ch] - a * src[i + row + ch]; out[i + ch] = v; } } } data.data.set(out); ctx.putImageData(data, 0, 0); } function drawEnhanced(ctx, img, w, h) { const b = document.getElementById('enhanceBrightness').value; const c = document.getElementById('enhanceContrast').value; const s = document.getElementById('enhanceSaturate').value; const dn = parseInt(document.getElementById('enhanceDenoise').value, 10); const sp = parseInt(document.getElementById('enhanceSharp').value, 10); ctx.filter = `brightness(${b}%) contrast(${c}%) saturate(${s}%)`; ctx.drawImage(img, 0, 0, w, h); ctx.filter = 'none'; if (dn > 0) { medianFilterPass(ctx, w, h); if (dn > 70) medianFilterPass(ctx, w, h); } if (sp > 0) sharpenPass(ctx, w, h, sp); } function renderEnhancePreview() { if (!enhanceSourceImg) return; const img = enhanceSourceImg; const scale = Math.min(1, 1600 / img.naturalWidth); const w = Math.max(1, Math.round(img.naturalWidth * scale)); const h = Math.max(1, Math.round(img.naturalHeight * scale)); const canvas = document.getElementById('enhanceCanvas'); canvas.width = w; canvas.height = h; const ctx = canvas.getContext('2d'); drawEnhanced(ctx, img, w, h); showEnhanceResult(true); } function scheduleEnhancePreview() { document.getElementById('enhanceBrightnessVal').textContent = document.getElementById('enhanceBrightness').value + '%'; document.getElementById('enhanceContrastVal').textContent = document.getElementById('enhanceContrast').value + '%'; document.getElementById('enhanceSaturateVal').textContent = document.getElementById('enhanceSaturate').value + '%'; document.getElementById('enhanceDenoiseVal').textContent = document.getElementById('enhanceDenoise').value + '%'; document.getElementById('enhanceSharpVal').textContent = document.getElementById('enhanceSharp').value + '%'; if (enhanceTimer) clearTimeout(enhanceTimer); enhanceTimer = setTimeout(renderEnhancePreview, 120); } function enhanceParams() { return { brightness: parseInt(document.getElementById('enhanceBrightness').value, 10), contrast: parseInt(document.getElementById('enhanceContrast').value, 10), saturate: parseInt(document.getElementById('enhanceSaturate').value, 10), denoise: parseInt(document.getElementById('enhanceDenoise').value, 10), sharp: parseInt(document.getElementById('enhanceSharp').value, 10), }; } function estimateNoise(img) { const aw = 160; const ah = Math.max(1, Math.round(img.naturalHeight * aw / img.naturalWidth)); const ac = document.createElement('canvas'); ac.width = aw; ac.height = ah; const actx = ac.getContext('2d'); actx.drawImage(img, 0, 0, aw, ah); const d = actx.getImageData(0, 0, aw, ah).data; let sum = 0; let n = 0; for (let y = 0; y < ah - 1; y++) { for (let x = 0; x < aw - 1; x++) { const i = (y * aw + x) * 4; const l = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2]; const lr = 0.299 * d[i + 4] + 0.587 * d[i + 5] + 0.114 * d[i + 6]; const lb = 0.299 * d[i + aw * 4] + 0.587 * d[i + aw * 4 + 1] + 0.114 * d[i + aw * 4 + 2]; sum += Math.abs(l - lr) + Math.abs(l - lb); n += 2; } } return n ? sum / n : 0; } function autoEnhance() { if (!enhanceSourceImg) return; const img = enhanceSourceImg; const aw = 160; const ah = Math.max(1, Math.round(img.naturalHeight * aw / img.naturalWidth)); const ac = document.createElement('canvas'); ac.width = aw; ac.height = ah; const actx = ac.getContext('2d'); actx.drawImage(img, 0, 0, aw, ah); const d = actx.getImageData(0, 0, aw, ah).data; const hist = new Array(256).fill(0); let total = 0; for (let i = 0; i < d.length; i += 4) { if (d[i + 3] < 16) continue; hist[Math.round(0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2])]++; total++; } const pct = p => { let acc = 0; const target = total * p; for (let v = 0; v < 256; v++) { acc += hist[v]; if (acc >= target) return v; } return 255; }; let lo = pct(0.005); let hi = pct(0.995); if (hi - lo < 30) { lo = Math.max(0, lo - 15); hi = Math.min(255, hi + 15); } const contrast = Math.round(Math.min(150, Math.max(100, 25500 / (hi - lo)))); const brightness = Math.round(Math.min(120, Math.max(85, 12800 / Math.max(1, (lo + hi) / 2)))); const noise = estimateNoise(img); let denoise = 0; let sharp = 30; if (noise > 6) { denoise = Math.min(50, Math.round(noise * 6)); sharp = 15; } const saturate = 106; document.getElementById('enhanceBrightness').value = brightness; document.getElementById('enhanceContrast').value = contrast; document.getElementById('enhanceSaturate').value = saturate; document.getElementById('enhanceDenoise').value = denoise; document.getElementById('enhanceSharp').value = sharp; scheduleEnhancePreview(); } async function saveEnhance() { if (enhanceSaving) return; if (!enhanceEntryId) { alert('Запись не выбрана'); return; } if (!enhanceSourceImg) { alert('Фото ещё не загружено — подождите'); return; } await loadEnhanceEngine(); const btn = document.getElementById('enhanceSaveBtn'); enhanceSaving = true; if (btn) { btn.disabled = true; btn.textContent = 'Сохранение...'; } const entryId = enhanceEntryId; try { let done = false; let engineLabel = 'клиент'; if (enhanceAiResultPath && isDefaultEnhanceParams()) { const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), 15000); try { await applyAiResult(ctrl.signal); } finally { clearTimeout(timer); } engineLabel = 'ИИ'; done = true; } else if (enhanceEngine !== 'client' && !enhanceAiResultPath) { try { const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), 8000); const res = await fetch(`${API}/api/entries/${entryId}/photo/enhance`, { method: 'PUT', headers: hdrJson(), body: JSON.stringify({ params: enhanceParams() }), signal: ctrl.signal, }); clearTimeout(timer); if (!res.ok) { const err = await res.json().catch(() => ({})); throw new Error(err.error || 'Ошибка сервера'); } engineLabel = 'сервер'; done = true; } catch (e) { if (enhanceEngine === 'server') throw e; } } if (!done) { const img = enhanceSourceImg; const canvas = document.createElement('canvas'); canvas.width = img.naturalWidth; canvas.height = img.naturalHeight; const ctx = canvas.getContext('2d'); drawEnhanced(ctx, img, canvas.width, canvas.height); const blob = await new Promise((resolve, reject) => canvas.toBlob(b => b ? resolve(b) : reject(new Error('toBlob failed')), 'image/jpeg', 0.92)); const fd = new FormData(); fd.append('photo', blob, 'enhanced.jpg'); const ctrl = new AbortController(); const timer = setTimeout(() => ctrl.abort(), 30000); let res; try { res = await fetch(`${API}/api/entries/${entryId}/photo/enhance`, { method: 'PUT', headers: hdr(), body: fd, signal: ctrl.signal }); } finally { clearTimeout(timer); } if (!res.ok) { const err = await res.json().catch(() => ({})); throw new Error(err.error || 'Ошибка сохранения'); } } showToast(`Фото улучшено (${engineLabel}) и сохранено`); try { closeEnhance(); } catch (e) { console.error('closeEnhance failed:', e); } try { await refreshEntryCard(entryId); } catch (e) { console.error('refreshEntryCard failed:', e); } } catch (e) { console.error('saveEnhance failed:', e); if (e && e.name === 'AbortError') { alert('Сохранение прервано: сервер не ответил вовремя. Подождите немного и повторите — если ответ всё же дошёл до сервера, фото могло уже сохраниться, проверьте карточку.'); } else { alert(e && e.message ? e.message : String(e)); } } finally { enhanceSaving = false; if (btn && document.contains(btn)) { btn.disabled = false; btn.textContent = 'Применить'; } } } async function aiCorrect() { if (aiCorrecting) return; const textarea = document.getElementById('editDesc'); const text = textarea.value.trim(); if (!text) { showToast('Нет текста для исправления'); return; } const btn = document.getElementById('aiCorrectBtn'); const modal = document.getElementById('aiCorrectModal'); const suggestionEl = document.getElementById('aiSuggestion'); aiCorrecting = true; btn.disabled = true; btn.textContent = '⏳'; suggestionEl.textContent = 'Обработка...'; modal.classList.add('open'); try { const res = await fetch(`${API}/api/ai/correct`, { method: 'POST', headers: hdrJson(), body: JSON.stringify({ text }) }); if (!res.ok) { const err = await res.json(); 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 { aiCorrecting = false; btn.disabled = false; btn.textContent = '✨'; } } function closeAiCorrect() { document.getElementById('aiCorrectModal').classList.remove('open'); } function acceptAiCorrect() { const suggestion = document.getElementById('aiSuggestion').textContent; if (suggestion && suggestion !== 'Обработка...' && !suggestion.startsWith('Ошибка:')) { document.getElementById('editDesc').value = suggestion; editAiSuggestion = suggestion.trim(); } closeAiCorrect(); } function renderEditAiStatus(e) { const el = document.getElementById('editAiStatus'); if (!e || !e.ai_status) { el.style.display = 'none'; el.innerHTML = ''; return; } el.style.display = 'block'; const changed = e.description_ai && e.description_original && e.description_ai !== e.description_original; const parts = [AI_STATUS_LABELS[e.ai_status] || `ИИ: ${e.ai_status}`]; if (e.ai_checked_at) parts.push(fmtFull(e.ai_checked_at)); let html = `${esc(parts.join(' · '))}`; if (changed) html += ` `; html += ` `; el.innerHTML = html; const rb = document.getElementById('aiRevertBtn'); if (rb) rb.addEventListener('click', () => revertAi(e.id)); const cb = document.getElementById('aiRecheckBtn'); if (cb) cb.addEventListener('click', () => recheckAi(e.id)); } async function revertAi(id) { if (!confirm('Вернуть исходный текст записи (до ИИ-проверки)?')) return; const res = await fetch(`${API}/api/entries/${id}/ai/revert`, { method: 'POST', headers: hdr() }); if (!res.ok) { const err = await res.json().catch(() => ({})); alert(err.error || 'Ошибка'); return; } const e = currentEntries.find(x => x.id === id); if (e) { if (e.description_original) e.description = e.description_original; e.description_ai = null; e.ai_status = 'reverted'; e.ai_error = null; } showToast('Оригинал восстановлен'); closeEdit(); refreshEntryCard(id); } async function recheckAi(id) { const res = await fetch(`${API}/api/entries/${id}/ai/recheck`, { method: 'POST', headers: hdr() }); if (!res.ok) { const err = await res.json().catch(() => ({})); alert(err.error || 'Ошибка'); return; } const e = currentEntries.find(x => x.id === id); if (e) { e.ai_status = 'pending'; e.ai_error = null; } showToast('Отправлено на ИИ-проверку'); closeEdit(); refreshEntryCard(id); } function editSourceFor(description) { if (!editAiSuggestion) return 'manual'; return description === editAiSuggestion ? 'ai' : 'ai_manual'; } async function saveEdit() { if (!editId) return; const name = document.getElementById('editName').value.trim(); const group_id = document.getElementById('editGroup').value; const description = document.getElementById('editDesc').value.trim(); if (!name || !group_id || !description) { alert('Заполните все поля'); return; } const moduleId = await resolveModuleId(document.getElementById('editModule').value); if (moduleId === null) { alert('Тема модуля не найдена. Выберите из списка подсказок.'); return; } const formData = new FormData(); formData.append('student_name', name); formData.append('group_id', group_id); formData.append('description', description); formData.append('module_id', moduleId); const ratingInput = document.querySelector('input[name="editRating"]:checked'); formData.append('rating', ratingInput ? ratingInput.value : ''); formData.append('edit_source', editSourceFor(description)); const photoFiles = document.getElementById('editPhoto').files; for (const f of photoFiles) formData.append('photo', f); const res = await fetch(`${API}/api/entries/${editId}`, { method: 'PUT', headers: hdr(), body: formData }); if (!res.ok) { const err = await res.json(); alert(err.error); return; } const files = document.getElementById('editFiles').files; if (files.length) { const filesFormData = new FormData(); for (const f of files) filesFormData.append('files', f); const uploadRes = await fetch(`${API}/api/entries/${editId}/files`, { method: 'POST', headers: hdr(), body: filesFormData }); if (!uploadRes.ok) { const err = await uploadRes.json().catch(() => ({})); alert(err.error || 'Ошибка загрузки файлов'); return; } } const id = editId; closeEdit(); const refreshed = await refreshEntryCard(id); if (!refreshed) loadEntries(); showToast('Запись обновлена'); } async function delEntry(id) { if (!confirm('Переместить запись в корзину? Файлы и фото сохранятся.')) return; await fetch(`${API}/api/entries/${id}`, { method: 'DELETE', headers: hdr() }); showToast('Запись перемещена в корзину'); loadEntries(); } document.getElementById('studentFilter').addEventListener('change', () => { page = 1; loadEntries(); }); document.getElementById('groupFilter').addEventListener('change', () => { page = 1; loadEntries(); }); document.getElementById('moduleFilter').addEventListener('change', () => { clearTimeout(moduleSearchTimer); moduleFilterSeq++; applyModuleFilter(); }); document.getElementById('moduleFilter').addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); clearTimeout(moduleSearchTimer); moduleFilterSeq++; applyModuleFilter(); } }); document.getElementById('moduleFilter').addEventListener('input', () => { clearTimeout(moduleSearchTimer); const q = document.getElementById('moduleFilter').value.trim(); const seq = ++moduleFilterSeq; moduleSearchTimer = setTimeout(async () => { const list = await fetchModules(q, q ? 20 : MODULE_LIST_LIMIT); if (seq !== moduleFilterSeq) return; if (list) renderModuleOptions('moduleFilterList', list); }, 250); }); document.getElementById('editModule').addEventListener('change', () => { clearTimeout(editModuleSearchTimer); editModuleSeq++; }); document.getElementById('editModule').addEventListener('input', () => { clearTimeout(editModuleSearchTimer); const q = document.getElementById('editModule').value.trim(); const seq = ++editModuleSeq; editModuleSearchTimer = setTimeout(async () => { const list = await fetchModules(q, q ? 20 : MODULE_LIST_LIMIT); if (seq !== editModuleSeq) return; if (list) renderModuleOptions('editModuleList', list); }, 250); }); document.getElementById('dateFrom').addEventListener('change', () => { page = 1; loadEntries(); }); document.getElementById('dateTo').addEventListener('change', () => { page = 1; loadEntries(); }); document.getElementById('searchInput').addEventListener('input', () => { clearTimeout(searchTimer); searchTimer = setTimeout(() => { page = 1; loadEntries(); }, 300); }); document.getElementById('editForm').addEventListener('submit', (e) => { e.preventDefault(); saveEdit(); }); document.getElementById('editFiles').addEventListener('change', (e) => { const preview = document.getElementById('editFilesPreview'); preview.innerHTML = ''; Array.from(e.target.files).forEach((f, i) => { const div = document.createElement('div'); div.className = 'file-preview-item'; div.style.cssText = 'display:flex;align-items:center;gap:8px;padding:6px 8px;background:var(--bg);border:1px solid var(--border);border-radius:6px;font-size:.8rem'; div.innerHTML = `${esc(f.name)} ${(f.size/1024).toFixed(1)} KB `; preview.appendChild(div); }); }); document.getElementById('editPhoto').addEventListener('change', (e) => { const preview = document.getElementById('editPhotoPreview'); Array.from(e.target.files).forEach(f => { const div = document.createElement('div'); div.className = 'file-preview-item'; div.style.cssText = 'display:flex;align-items:center;gap:8px;padding:6px 8px;background:var(--bg);border:1px solid var(--border);border-radius:6px;font-size:.8rem'; const url = URL.createObjectURL(f); div.innerHTML = ` ${esc(f.name)} ${(f.size/1024).toFixed(1)} KB `; preview.appendChild(div); }); }); function removeEditFile(index) { const input = document.getElementById('editFiles'); const dt = new DataTransfer(); Array.from(input.files).forEach((f, i) => { if (i !== index) dt.items.add(f); }); input.files = dt.files; input.dispatchEvent(new Event('change')); } async function exportCSV() { const p = new URLSearchParams(); const q = document.getElementById('searchInput').value; const sn = document.getElementById('studentFilter').value; const gid = document.getElementById('groupFilter').value; const df = document.getElementById('dateFrom').value; const dt = document.getElementById('dateTo').value; if (q) p.set('search', q); if (sn) p.set('student_name', sn); if (gid) p.set('group_id', gid); if (df) p.set('date_from', df); if (dt) p.set('date_to', dt); if (moduleFilterId) p.set('module_id', moduleFilterId); const res = await fetch(`${API}/api/entries?${p}`, { headers: hdr() }); const entries = (await res.json()).entries; if (!entries.length) { alert('Нет данных для экспорта'); return; } const rows = [['Фамилия и имя', 'Группа', 'Тема модуля', 'Описание', 'Дата', 'Фото']]; entries.forEach(e => { rows.push([ e.student_name, e.group_name, e.module_name || '', e.description.replace(/\n/g, ' '), fmtFull(e.created_at), e.photo_path ? `${API}${e.photo_path}` : '' ]); }); const csv = rows.map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(';')).join('\n'); const bom = '\uFEFF'; const blob = new Blob([bom + csv], { type: 'text/csv;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; const dateLabel = df && dt ? `${df}_${dt}` : 'all'; a.download = `journal_${dateLabel}.csv`; a.click(); URL.revokeObjectURL(url); } let linkGroups = []; let linkStudentsLoaded = false; let createdLinkUrl = ''; function fmtD(d) { return d ? d.split('-').reverse().join('.') : 'весь период'; } async function openLinkCreate() { const gid = document.getElementById('groupFilter').value; if (!gid) { alert('Сначала выберите группу в фильтре'); return; } const df = document.getElementById('dateFrom').value; const dt = document.getElementById('dateTo').value; if (!linkGroups.length) { const res = await fetch(`${API}/api/groups`, { headers: hdr() }); linkGroups = await res.json(); } if (!linkStudentsLoaded) { const res = await fetch(`${API}/api/students/names`, { headers: hdr() }); const names = await res.json(); const dl = document.getElementById('linkStudentList'); dl.innerHTML = names.map(n => `