const DAYS = ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'];
const FACE_CANDIDATE_MIN = 0.5;
const facePct = v => Math.round((Number(v) || 0) * 100) + '%';
const faceCandidateMin = () => (Number(faceViewer.candidateMin) > 0 ? Number(faceViewer.candidateMin) : FACE_CANDIDATE_MIN);
let branchesCache = [];
let tutorsCache = [];
let allGroups = [];
let currentCover = null;
async function loadBranchesCache() {
const res = await fetch(`${API}/api/branches`, { headers: hdr() });
if (res.ok) branchesCache = await res.json();
}
async function loadTutorsCache() {
const res = await fetch(`${API}/api/users/tutors`, { headers: hdr() });
if (res.ok) tutorsCache = await res.json();
}
function tutorSelectHTML(selectedId) {
const opts = tutorsCache.map(t => ``).join('');
return `
`;
}
function branchSelectHTML(selectedId) {
const opts = branchesCache.map(b => ``).join('');
return ``;
}
async function loadGroups() {
await loadBranchesCache();
await loadTutorsCache();
const res = await fetch(`${API}/api/groups`, { headers: hdr() });
const groups = await res.json();
allGroups = groups;
const list = document.getElementById('groupList');
if (!groups.length) { list.innerHTML = 'Нет групп
'; return; }
list.innerHTML = `` + groups.map(g => {
const schedSet = g.day_of_week != null && g.time_start && g.time_end;
return `
${g.cover_path
? `
})
`
: `
📷
`}
`;
}).join('') + `
`;
}
async function saveGroup(id) {
const name = document.getElementById(`name-${id}`).value.trim();
if (!name) return;
const nameInput = document.getElementById(`name-${id}`);
const groupCard = nameInput.closest('.group-card');
const branchSelect = groupCard ? groupCard.querySelector('.branch-select') : null;
const branch_id = branchSelect ? branchSelect.value : '';
const tutorSelect = groupCard ? groupCard.querySelector('.tutor-select') : null;
const tutor_id = tutorSelect ? (tutorSelect.value || null) : undefined;
const dow = document.getElementById(`dow-${id}`).value;
const ts = document.getElementById(`ts-${id}`).value;
const te = document.getElementById(`te-${id}`).value;
const res = await fetch(`${API}/api/groups/${id}`, {
method: 'PUT',
headers: hdrJson(),
body: JSON.stringify({ name, branch_id: branch_id || null, tutor_id, day_of_week: dow !== '' ? parseInt(dow) : null, time_start: ts || null, time_end: te || null })
});
if (res.ok) {
loadGroups();
const dayLabel = dow !== '' ? DAYS[dow] : 'без расписания';
const timeLabel = ts && te ? `, ${ts}–${te}` : '';
showToast(`Сохранено: «${name}» — ${dayLabel}${timeLabel}`);
} else { const e = await res.json(); alert(e.error); }
}
async function addGroup() {
const input = document.getElementById('newGroup');
const name = input.value.trim();
if (!name) return;
await loadBranchesCache();
await loadTutorsCache();
const branchSelect = document.getElementById('newGroupBranch');
const branch_id = branchSelect ? branchSelect.value : '';
const tutorSelect = document.getElementById('newGroupTutor');
const tutor_id = tutorSelect && tutorSelect.value ? tutorSelect.value : null;
const res = await fetch(`${API}/api/groups`, { method: 'POST', headers: hdrJson(), body: JSON.stringify({ name, branch_id: branch_id || null, tutor_id }) });
if (res.ok) { input.value = ''; loadGroups(); }
else { const e = await res.json(); alert(e.error); }
}
async function delGroup(id) {
if (!confirm('Удалить группу? Группа попадёт в корзину, восстановить её можно будет позже.')) return;
const res = await fetch(`${API}/api/groups/${id}`, { method: 'DELETE', headers: hdr() });
if (!res.ok) { const e = await res.json(); alert(e.error || 'Ошибка'); }
loadGroups();
}
const PHOTO_PAGE_SIZE = 24;
let currentGroupId = null;
let currentGroupName = '';
let photos = [];
let photoPage = 1;
let totalPhotos = 0;
let editingPhotoId = null;
async function openPhotos(groupId, groupName) {
currentGroupId = groupId;
currentGroupName = groupName;
const g = allGroups.find(x => String(x.id) === String(groupId));
currentCover = g ? g.cover_path : null;
photoPage = 1;
editingPhotoId = null;
document.getElementById('photosTitle').textContent = `Фото — ${groupName}`;
document.getElementById('photosModal').classList.add('open');
await loadAllStudents();
renderFaceStudentFilter();
await loadGroupPhotos();
}
function closePhotos() {
document.getElementById('photosModal').classList.remove('open');
currentGroupId = null;
}
async function loadGroupPhotos() {
const p = new URLSearchParams();
p.set('limit', PHOTO_PAGE_SIZE);
p.set('offset', (photoPage - 1) * PHOTO_PAGE_SIZE);
const sel = document.getElementById('faceStudentFilter');
const fv = sel ? sel.value : '';
if (fv === '__unassigned__') p.set('unassigned_faces', '1');
else if (fv) p.set('student_id', fv);
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos?${p}`, { headers: hdr() });
const data = await res.json();
photos = data.photos;
totalPhotos = data.total;
document.getElementById('photoGrid').className = 'photo-grid';
document.getElementById('photoGrid').innerHTML = photos.length
? photos.map(photoHTML).join('')
: 'Фото пока нет. Загрузите первое фото.
';
renderIcons();
renderPager(document.getElementById('photosPager'), photoPage, Math.max(1, Math.ceil(totalPhotos / PHOTO_PAGE_SIZE)), goPhotoPage);
}
function goPhotoPage(p) { photoPage = p; loadGroupPhotos(); }
let allStudents = [];
let allStudentsLoaded = false;
let faceViewer = { photoId: null, faces: [], sourceType: 'group', layout: null, candidateMin: FACE_CANDIDATE_MIN };
let faceAssignFaceId = null;
async function loadAllStudents() {
if (allStudentsLoaded) return;
try {
const res = await fetch(`${API}/api/students`, { headers: hdr() });
const data = res.ok ? await res.json() : null;
const list = Array.isArray(data) ? data : (data && data.students) || [];
allStudents = list
.filter(s => !s.deleted_at)
.map(s => ({ id: s.id, name: s.name, group_id: s.group_id, group_name: s.group_name || '' }));
allStudentsLoaded = true;
} catch {
allStudents = [];
}
}
function groupStudents() {
return allStudents.filter(s => String(s.group_id) === String(currentGroupId));
}
function renderFaceStudentFilter() {
const sel = document.getElementById('faceStudentFilter');
if (!sel) return;
const cur = sel.value;
sel.innerHTML = '';
groupStudents().forEach(s => {
const o = document.createElement('option');
o.value = String(s.id);
o.textContent = s.name;
sel.appendChild(o);
});
if (Array.from(sel.options).some(o => o.value === cur)) sel.value = cur;
}
async function loadFaceViewerFaces(photoId) {
const res = await fetch(`${API}/api/photos/group/${photoId}/faces`, { headers: hdr() });
if (!res.ok) {
const err = new Error(res.status === 404 ? 'Фото не найдено' : 'Не удалось загрузить лица');
err.status = res.status;
throw err;
}
const data = await res.json();
faceViewer.faces = data.faces || [];
faceViewer.candidateMin = Number(data.candidate_min) > 0 ? Number(data.candidate_min) : FACE_CANDIDATE_MIN;
faceViewer.imgWidth = Number(data.img_width) || 0;
faceViewer.imgHeight = Number(data.img_height) || 0;
faceViewer.scanned = Boolean(data.scanned);
return faceViewer;
}
async function refreshOpenFaceViewer() {
const photoId = faceViewer.photoId;
if (!photoId) return;
const photo = photos.find(x => x.id === photoId);
if (!photo) return;
try {
await loadFaceViewerFaces(photoId);
renderFaceViewer(photo.photo_path);
} catch {
/* фотография могла исчезнуть — закрывать просмотр не нужно */
}
}
function faceViewerWarn(msg) {
const el = document.getElementById('faceViewerWarn');
if (!el) return;
if (!msg) { el.hidden = true; el.textContent = ''; return; }
el.hidden = false;
el.textContent = msg;
}
function checkFaceViewerSync(nw, nh) {
if (!faceViewer.faces.length || !faceViewer.imgWidth || !faceViewer.imgHeight) {
faceViewerWarn('');
return;
}
if (faceViewer.imgWidth === nw && faceViewer.imgHeight === nh) {
faceViewerWarn('');
return;
}
faceViewerWarn(`Фото было заменено (было ${faceViewer.imgWidth}×${faceViewer.imgHeight}, стало ${nw}×${nh}) — рамки сохранены в старом масштабе. Нажмите «Переиндексировать», чтобы распознать лица заново.`);
}
async function rescanFaceViewerPhoto() {
const photoId = faceViewer.photoId;
if (!photoId || faceViewer.rescanBusy) return;
faceViewer.rescanBusy = true;
const btn = document.getElementById('faceViewerRescanBtn');
if (btn) { btn.disabled = true; btn.textContent = 'В очередь...'; }
try {
const res = await fetch(`${API}/api/photos/group/${photoId}/faces/rescan`, {
method: 'POST',
headers: { ...hdr(), 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось поставить фото в очередь');
showToast('Фото поставлено в очередь проверки — рамки обновятся автоматически');
loadGroupPhotos();
} catch (e) {
alert(e.message);
} finally {
faceViewer.rescanBusy = false;
if (btn) { btn.disabled = false; btn.textContent = 'Переиндексировать'; }
}
}
let faceScanLiveSource = null;
function connectFaceScanLive() {
if (faceScanLiveSource) { faceScanLiveSource.close(); faceScanLiveSource = null; }
const connect = () => {
const t = sessionStorage.getItem('authToken');
if (!t) return;
faceScanLiveSource = new EventSource(`${API}/api/events?token=${encodeURIComponent(t)}`);
faceScanLiveSource.addEventListener('face_scan_status', ev => {
let p = null;
try { p = JSON.parse(ev.data); } catch { return; }
if (!p || p.status === 'processing' || p.status === 'pending') return;
if (Number(p.source_id) === Number(faceViewer.photoId) && faceViewer.photoId) {
refreshOpenFaceViewer();
loadGroupPhotos();
}
});
faceScanLiveSource.onerror = () => {
if (faceScanLiveSource) { faceScanLiveSource.close(); faceScanLiveSource = null; }
setTimeout(connect, 5000);
};
};
connect();
window.addEventListener('beforeunload', () => { if (faceScanLiveSource) faceScanLiveSource.close(); });
}
async function openFaceViewer(photoId) {
const photo = photos.find(x => x.id === photoId);
if (!photo) return;
if (faceViewer.layout) window.removeEventListener('resize', faceViewer.layout);
faceViewer = { photoId, faces: [], sourceType: 'group', layout: null };
const body = document.getElementById('faceViewerBody');
body.innerHTML = 'Загрузка...
';
document.getElementById('faceViewerModal').classList.add('open');
try {
await loadFaceViewerFaces(photoId);
renderFaceViewer(photo.photo_path);
} catch (e) {
body.innerHTML = `${e.status === 404 ? 'Фото не найдено' : 'Не удалось загрузить лица'}
`;
}
}
function faceBoxesHTML(nw, nh) {
if (!nw || !nh) return '';
return faceViewer.faces.map(f => {
const matched = Boolean(f.student_id);
let cls = 'face-box face-box--unassigned';
let label = 'Не опознано';
if (matched) {
cls = 'face-box face-box--matched';
const name = f.student_name || 'Ученик';
label = f.manual ? name + ' · вручную' : name + ' · ' + facePct(f.confidence);
} else if (f.best_student_id && f.best_score >= faceCandidateMin()) {
cls = 'face-box face-box--candidate';
label = 'Похож: ' + (f.best_student_name || 'ученик') + ' · ' + facePct(f.best_score);
}
const px = v => (Number(v) || 0);
const left = (px(f.x) / nw) * 100, top = (px(f.y) / nh) * 100;
const width = (px(f.w) / nw) * 100, height = (px(f.h) / nh) * 100;
return ``;
}).join('');
}
function renderFaceViewer(photoPath) {
if (faceViewer.layout) window.removeEventListener('resize', faceViewer.layout);
const body = document.getElementById('faceViewerBody');
body.innerHTML = `
`;
const img = document.getElementById('faceStageImg');
const ov = document.getElementById('faceOverlay');
ov.innerHTML = 'Загрузка...
';
const layout = () => {
const nw = img.naturalWidth;
const nh = img.naturalHeight;
if (!nw || !nh) return;
ov.style.width = img.clientWidth + 'px';
ov.style.height = img.clientHeight + 'px';
ov.style.left = img.offsetLeft + 'px';
ov.style.top = img.offsetTop + 'px';
ov.innerHTML = faceViewer.faces.length ? faceBoxesHTML(nw, nh) : 'Лиц не найдено
';
checkFaceViewerSync(nw, nh);
};
if (img.complete && img.naturalWidth) layout();
else img.addEventListener('load', layout, { once: true });
window.addEventListener('resize', layout);
faceViewer.layout = layout;
}
function closeFaceViewer() {
if (faceViewer.layout) window.removeEventListener('resize', faceViewer.layout);
faceViewerWarn('');
document.getElementById('faceViewerModal').classList.remove('open');
faceViewer = { photoId: null, faces: [], sourceType: 'group', layout: null, candidateMin: FACE_CANDIDATE_MIN };
}
async function openFaceAssign(faceId) {
await loadAllStudents();
faceAssignFaceId = faceId;
const face = faceViewer.faces.find(f => String(f.id) === String(faceId));
const inp = document.getElementById('faceAssignSearch');
inp.value = face && !face.student_id && face.best_student_id && face.best_score >= faceCandidateMin()
? (face.best_student_name || '')
: '';
renderFaceAssignList(inp.value);
document.getElementById('faceAssignModal').classList.add('open');
}
function renderFaceAssignList(q) {
const wrap = document.getElementById('faceAssignList');
const needle = q.trim().toLowerCase();
const list = allStudents.filter(s =>
s.name.toLowerCase().includes(needle) || (s.group_name || '').toLowerCase().includes(needle));
list.sort((a, b) => {
const own = x => (String(x.group_id) === String(currentGroupId) ? 0 : 1);
if (own(a) !== own(b)) return own(a) - own(b);
return a.name.localeCompare(b.name, 'ru');
});
if (!list.length) {
wrap.innerHTML = 'Ученики не найдены
';
return;
}
wrap.innerHTML = list.map(s => `
`).join('');
}
async function assignFace(studentId) {
if (!faceAssignFaceId) return;
try {
const res = await fetch(`${API}/api/photo-faces/${faceAssignFaceId}/assign`, {
method: 'PUT',
headers: { ...hdr(), 'Content-Type': 'application/json' },
body: JSON.stringify({ student_id: studentId }),
});
if (!res.ok) {
const d = await res.json().catch(() => ({}));
showToast(d.error || 'Не удалось сохранить привязку');
return;
}
showToast(studentId ? 'Лицо привязано' : 'Привязка снята');
document.getElementById('faceAssignModal').classList.remove('open');
const photoId = faceViewer.photoId;
if (photoId) await refreshOpenFaceViewer();
loadGroupPhotos();
} catch {
showToast('Не удалось сохранить привязку');
}
}
async function scanGroupFaces() {
if (!currentGroupId) return;
const btn = document.getElementById('scanFacesBtn');
btn.disabled = true;
const label = btn.textContent;
btn.textContent = 'В очередь...';
try {
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/scan-faces`, {
method: 'POST',
headers: { ...hdr(), 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
const data = res.ok ? await res.json() : null;
if (!res.ok) {
showToast((data && data.error) || 'Не удалось запустить сканирование');
return;
}
showToast(`В очередь добавлено фото: ${data.queued}${data.skipped ? `, уже в очереди: ${data.skipped}` : ''}`);
loadGroupPhotos();
} catch {
showToast('Не удалось запустить сканирование');
} finally {
btn.disabled = false;
btn.textContent = label;
}
}
function fmtPhotoDate(d) { return fmtDateOnlyIso(d); }
function photoHTML(p) {
const taken = p.taken_at ? `Дата: ${fmtPhotoDate(p.taken_at)}` : '';
const uploaded = `Загружено: ${fmtDateFull(p.created_at)}`;
const isCover = currentCover && p.photo_path === currentCover;
const faces = p.face_count || 0;
const unassigned = p.face_unassigned || 0;
const faceBadge = faces
? ` ${faces}${unassigned ? ` (${unassigned})` : ''}`
: '';
return `
⠿
})
${faceBadge}
Файл не найден
${esc(p.caption || '')}
${taken ? taken + ' · ' : ''}${uploaded}
${isAdmin() ? `` : ''}
`;
}
function openAddPhoto() {
editingPhotoId = null;
document.getElementById('photoFormTitle').textContent = `Добавить фото — ${currentGroupName}`;
document.getElementById('photoFile').value = '';
document.getElementById('photoCaption').value = '';
document.getElementById('photoTakenAt').value = '';
document.getElementById('photoFormPreview').style.display = 'none';
document.getElementById('photoFormModal').classList.add('open');
}
async function openEditPhoto(id) {
const p = photos.find(x => x.id === id);
if (!p) return;
editingPhotoId = id;
document.getElementById('photoFormTitle').textContent = 'Редактировать фото';
document.getElementById('photoFile').value = '';
document.getElementById('photoCaption').value = p.caption || '';
document.getElementById('photoTakenAt').value = p.taken_at || '';
const prev = document.getElementById('photoFormPreview');
const img = document.getElementById('photoPreviewImg');
img.src = `${API}${p.photo_path}`;
prev.style.display = 'block';
document.getElementById('photoFormModal').classList.add('open');
}
function closePhotoForm() {
document.getElementById('photoFormModal').classList.remove('open');
editingPhotoId = null;
}
function previewPhotoFile() {
const file = document.getElementById('photoFile').files[0];
const prev = document.getElementById('photoFormPreview');
if (!file) { prev.style.display = 'none'; return; }
const img = document.getElementById('photoPreviewImg');
img.src = URL.createObjectURL(file);
prev.style.display = 'block';
}
function pasteGroupPhotoFile(e) {
const modal = document.getElementById('photoFormModal');
if (!modal || !modal.classList.contains('open')) return;
if (editingPhotoId) return;
const active = document.activeElement;
if (active && active.id === 'photoCaption') return;
const items = e.clipboardData && e.clipboardData.items;
if (!items) return;
for (const item of items) {
if (item.type && item.type.startsWith('image/')) {
const file = item.getAsFile();
if (!file) continue;
e.preventDefault();
let named = file;
if (!/\.[a-z0-9]{2,5}$/i.test(file.name || '')) {
const m = /^image\/([a-z0-9.+-]+)$/i.exec(file.type || '');
let ext = m ? m[1].toLowerCase() : 'png';
if (ext === 'jpeg') ext = 'jpg';
named = new File([file], `photo-${Date.now()}.${ext}`, { type: file.type || 'image/png', lastModified: file.lastModified });
}
const dt = new DataTransfer();
dt.items.add(named);
document.getElementById('photoFile').files = dt.files;
previewPhotoFile();
return;
}
}
}
async function savePhotoForm() {
const caption = document.getElementById('photoCaption').value.trim();
const taken_at = document.getElementById('photoTakenAt').value;
if (editingPhotoId) {
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${editingPhotoId}`, {
method: 'PUT',
headers: hdrJson(),
body: JSON.stringify({ caption: caption || null, taken_at: taken_at || null })
});
if (!res.ok) { const e = await res.json(); alert(e.error || 'Ошибка'); return; }
showToast('Фото обновлено');
} else {
const file = document.getElementById('photoFile').files[0];
if (!file) { alert('Выберите файл'); return; }
const fd = new FormData();
fd.append('photo', file);
fd.append('caption', caption);
fd.append('taken_at', taken_at);
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos`, {
method: 'POST',
headers: hdr(),
body: fd
});
if (!res.ok) { const e = await res.json(); alert(e.error || 'Ошибка'); return; }
showToast('Фото добавлено в хронологию');
}
closePhotoForm();
loadGroupPhotos();
loadGroups();
}
async function deletePhoto(id) {
if (!confirm('Удалить это фото безвозвратно?')) return;
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${id}`, { method: 'DELETE', headers: hdr() });
if (!res.ok) { const e = await res.json(); alert(e.error || 'Ошибка'); return; }
const p = photos.find(x => x.id === id);
if (p && currentCover === p.photo_path) currentCover = null;
showToast('Фото удалено');
loadGroupPhotos();
loadGroups();
}
async function exportGroup(id, name) {
const res = await fetch(`${API}/api/entries?group_id=${id}`, { headers: hdr() });
const { entries } = await res.json();
if (!entries.length) { alert('Нет данных для экспорта'); return; }
const rows = [['Фамилия Имя', 'Группа', 'Описание', 'Дата', 'Ссылка на страницу']];
entries.forEach(e => {
rows.push([
e.student_name,
e.group_name,
e.description.replace(/\n/g, ' '),
fmtFull(e.created_at),
`${location.origin}/?nameInput=${encodeURIComponent(e.student_name)}`
]);
});
const csv = rows.map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(';')).join('\n');
const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `group_${name.replace(/[\\/:*?"<>|]/g, '_')}.csv`;
a.click();
URL.revokeObjectURL(url);
showToast(`Экспортировано записей: ${entries.length}`);
}
async function exportGroupUrls(groupId, groupName) {
const res = await fetch(`${API}/api/students`, { headers: hdr() });
const students = await res.json();
const list = students.filter(s => s.group_id === groupId);
if (!list.length) { alert('В группе нет учеников'); return; }
await exportStudentUrlZip(list, `group_${groupName.replace(/[\\/:*?"<>|]/g, '_')}.zip`);
showToast(`Экспортировано: ${list.length}`);
}
function openGroupFilesModal(groupId, groupName) {
const sel = document.getElementById('groupFilesGroup');
sel.innerHTML = allGroups.map(g => ``).join('');
document.getElementById('groupFilesTitle').textContent = `Архив файлов — ${groupName}`;
document.getElementById('groupFilesFrom').value = '';
document.getElementById('groupFilesTo').value = todayISOLocal();
document.getElementById('groupFilesIncludeWorks').checked = true;
document.getElementById('groupFilesIncludePhotos').checked = false;
document.getElementById('groupFilesMainPhoto').checked = true;
document.getElementById('groupFilesGallery').checked = false;
document.getElementById('groupFilesOriginals').checked = false;
onGroupFilesPhotosToggle();
document.getElementById('groupFilesModal').classList.add('open');
}
function closeGroupFilesModal() {
document.getElementById('groupFilesModal').classList.remove('open');
}
function todayISOLocal() {
return todayIso();
}
const GROUP_FILES_PHOTO_BOXES = ['groupFilesMainPhoto', 'groupFilesGallery', 'groupFilesOriginals'];
function onGroupFilesPhotosToggle() {
const on = document.getElementById('groupFilesIncludePhotos').checked;
GROUP_FILES_PHOTO_BOXES.forEach(id => {
const el = document.getElementById(id);
if (el) el.disabled = !on;
});
}
function groupFilesPhotosOptions() {
const main = document.getElementById('groupFilesMainPhoto').checked;
const gallery = document.getElementById('groupFilesGallery').checked;
const originals = document.getElementById('groupFilesOriginals').checked;
return {
main,
gallery,
originals,
mode: gallery ? 'all' : 'latest',
any: main || gallery || originals,
};
}
async function downloadGroupFiles() {
const groupId = document.getElementById('groupFilesGroup').value;
const dateFrom = document.getElementById('groupFilesFrom').value;
const dateTo = document.getElementById('groupFilesTo').value;
const includeWorks = document.getElementById('groupFilesIncludeWorks').checked;
const includePhotos = document.getElementById('groupFilesIncludePhotos').checked;
const photoOpts = groupFilesPhotosOptions();
if (!groupId) { alert('Выберите группу'); return; }
if (!includeWorks && !includePhotos) { alert('Выберите хотя бы одну категорию: работы или фото записи'); return; }
if (includePhotos && !photoOpts.any) { alert('Выберите, какие фото выгружать: главное фото, галерея или оригиналы'); return; }
if (dateFrom && dateTo && dateFrom > dateTo) { alert('Дата «С» позже даты «По»'); return; }
const btn = document.getElementById('downloadGroupFilesBtn');
btn.disabled = true;
btn.textContent = 'Формируем...';
try {
const q = new URLSearchParams();
if (dateFrom) q.set('date_from', dateFrom);
if (dateTo) q.set('date_to', dateTo);
q.set('include_files', includeWorks ? '1' : '0');
q.set('include_photos', includePhotos ? '1' : '0');
q.set('include_main', photoOpts.main ? '1' : '0');
q.set('photos_mode', photoOpts.mode);
q.set('include_originals', photoOpts.originals ? '1' : '0');
const res = await fetch(`${API}/api/groups/${groupId}/export/files?${q}`, { headers: hdr() });
if (!res.ok) {
let msg = 'Не удалось сформировать архив';
try { const e = await res.json(); msg = e.error || msg; } catch {}
alert(msg);
return;
}
const blob = await res.blob();
let disp = res.headers.get('Content-Disposition') || '';
let fname = 'group_files.zip';
const star = disp.match(/filename\*=UTF-8''([^;]+)/i);
const plain = disp.match(/filename="?([^";]+)"?/i);
if (star) { try { fname = decodeURIComponent(star[1]); } catch { fname = plain ? plain[1] : fname; } }
else if (plain) fname = plain[1];
downloadBlob(blob, fname);
showToast('Архив сформирован');
closeGroupFilesModal();
} catch (err) {
alert('Ошибка при формировании архива: ' + err.message);
} finally {
btn.disabled = false;
btn.textContent = 'Скачать ZIP';
}
}
document.getElementById('newGroup').addEventListener('keydown', e => { if (e.key === 'Enter') addGroup(); });
document.getElementById('addGroupBtn').addEventListener('click', addGroup);
document.getElementById('photoFile').addEventListener('change', previewPhotoFile);
document.addEventListener('paste', pasteGroupPhotoFile);
document.getElementById('photoForm').addEventListener('submit', e => {
e.preventDefault();
savePhotoForm();
});
document.getElementById('photosModal').addEventListener('click', e => { if (e.target === e.currentTarget) closePhotos(); });
document.getElementById('photoFormModal').addEventListener('click', e => { if (e.target === e.currentTarget) closePhotoForm(); });
document.getElementById('groupFilesModal').addEventListener('click', e => { if (e.target === e.currentTarget) closeGroupFilesModal(); });
document.getElementById('closeGroupFilesBtn').addEventListener('click', closeGroupFilesModal);
document.getElementById('groupFilesForm').addEventListener('submit', e => { e.preventDefault(); downloadGroupFiles(); });
document.getElementById('groupFilesIncludePhotos').addEventListener('change', onGroupFilesPhotosToggle);
document.getElementById('openPhotoBtn').addEventListener('click', openAddPhoto);
document.getElementById('closePhotosBtn').addEventListener('click', closePhotos);
document.getElementById('closePhotoFormBtn').addEventListener('click', closePhotoForm);
document.getElementById('groupList').addEventListener('click', e => {
const sg = e.target.closest('[data-save-group]');
if (sg) { saveGroup(parseInt(sg.dataset.saveGroup, 10)); return; }
const dg = e.target.closest('[data-del-group]');
if (dg) { delGroup(parseInt(dg.dataset.delGroup, 10)); return; }
const eg = e.target.closest('[data-export-group]');
if (eg) { exportGroup(parseInt(eg.dataset.exportGroup, 10), eg.dataset.groupName); return; }
const eu = e.target.closest('[data-export-urls]');
if (eu) { exportGroupUrls(parseInt(eu.dataset.exportUrls, 10), eu.dataset.groupName); return; }
const ef = e.target.closest('[data-export-files]');
if (ef) { openGroupFilesModal(parseInt(ef.dataset.exportFiles, 10), ef.dataset.groupName); return; }
const photoBtn = e.target.closest('.photo-btn');
if (photoBtn) {
const id = parseInt(photoBtn.dataset.groupId, 10);
const name = photoBtn.dataset.groupName;
if (!isNaN(id)) openPhotos(id, name);
}
});
function updateGroupCoverUI(coverPath) {
const card = document.querySelector(`.group-card[data-group-id="${currentGroupId}"]`);
if (!card) return;
const g = allGroups.find(x => String(x.id) === String(currentGroupId));
const existing = card.querySelector('.group-cover');
if (existing && existing.tagName === 'IMG') { existing.src = API + coverPath; existing.dataset.img = API + coverPath; return; }
const el = document.createElement('img');
el.className = 'group-cover';
el.src = API + coverPath;
el.dataset.img = API + coverPath;
el.alt = '';
if (existing) existing.replaceWith(el);
else card.insertBefore(el, card.firstChild);
}
let dragPhotoId = null;
async function persistPhotoOrder() {
const items = [...document.querySelectorAll('#photoGrid .photo-item')];
const order = items.map(el => parseInt(el.dataset.photoId, 10));
if (JSON.stringify(order) === JSON.stringify(photos.map(p => p.id))) return;
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/reorder`, {
method: 'PUT',
headers: hdrJson(),
body: JSON.stringify({ order })
});
if (res.ok) showToast('Порядок фото сохранён');
else {
try { const err = await res.json(); alert(err.error || 'Ошибка'); } catch { alert('Ошибка'); }
loadGroupPhotos();
}
}
document.getElementById('photoGrid').addEventListener('dragstart', e => {
const item = e.target.closest('.photo-item');
if (!item) return;
e.stopPropagation();
dragPhotoId = parseInt(item.dataset.photoId, 10);
item.classList.add('dragging');
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/plain', String(dragPhotoId));
});
document.getElementById('photoGrid').addEventListener('dragover', e => {
e.preventDefault();
e.dataTransfer.dropEffect = 'move';
const target = e.target.closest('.photo-item');
const dragged = dragPhotoId != null ? document.querySelector(`.photo-item[data-photo-id="${dragPhotoId}"]`) : null;
if (!target || !dragged || target === dragged) return;
if (target.contains(dragged)) return;
const rect = target.getBoundingClientRect();
const grid = document.getElementById('photoGrid');
grid.insertBefore(dragged, e.clientX > rect.left + rect.width / 2 ? target.nextSibling : target);
});
document.getElementById('photoGrid').addEventListener('dragend', e => {
const item = e.target.closest('.photo-item');
if (item) item.classList.remove('dragging');
if (dragPhotoId != null) persistPhotoOrder();
dragPhotoId = null;
});
document.getElementById('photoGrid').addEventListener('drop', e => e.preventDefault());
document.getElementById('photoGrid').addEventListener('click', async e => {
const bq = e.target.closest('[data-quarantine]');
if (bq) {
if (await quarantineBrokenPhoto(bq.dataset.quarantine, bq.dataset.quarantineId)) loadGroupPhotos();
return;
}
const facesBtn = e.target.closest('[data-faces-photo]');
if (facesBtn) {
openFaceViewer(parseInt(facesBtn.dataset.facesPhoto, 10));
return;
}
const coverBtn = e.target.closest('.p-cover');
if (coverBtn) {
const photoId = parseInt(coverBtn.dataset.photoId, 10);
const photoPath = coverBtn.dataset.photoPath;
if (!isNaN(photoId)) {
try {
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${photoId}/cover`, {
method: 'PUT',
headers: hdrJson(),
});
if (res.ok) {
const g = await res.json();
currentCover = g.cover_path || null;
const grp = allGroups.find(x => String(x.id) === String(currentGroupId));
if (grp) grp.cover_path = currentCover;
showToast('Обложка обновлена');
updateGroupCoverUI(currentCover);
loadGroupPhotos();
} else {
const err = await res.json();
alert(err.error || 'Ошибка');
}
} catch (err) {
alert('Ошибка сети: ' + err.message);
}
}
return;
}
const ed = e.target.closest('[data-edit-photo]');
if (ed) { openEditPhoto(parseInt(ed.dataset.editPhoto, 10)); return; }
const en = e.target.closest('[data-enhance-photo]');
if (en) { openEnhance(parseInt(en.dataset.enhancePhoto, 10)); return; }
const dl = e.target.closest('[data-del-photo]');
if (dl) { deletePhoto(parseInt(dl.dataset.delPhoto, 10)); }
});
async function populateNewGroupBranch() {
const res = await fetch(`${API}/api/branches`, { headers: hdr() });
if (res.ok) {
const branches = await res.json();
const sel = document.getElementById('newGroupBranch');
sel.innerHTML = '' + branches.map(b => ``).join('');
}
const tRes = await fetch(`${API}/api/users/tutors`, { headers: hdr() });
if (tRes.ok) {
const tutors = await tRes.json();
const tSel = document.getElementById('newGroupTutor');
tSel.innerHTML = '' + tutors.map(t => ``).join('');
}
}
(async () => {
if (await checkAuth()) {
buildSidebar(document.body.dataset.page);
await populateNewGroupBranch();
loadGroups();
connectFaceScanLive();
}
})();
let enhancePhotoId = null;
let enhanceAiJobId = null;
let enhanceAiResultPath = null;
let enhanceSourceImg = null;
let photoAiEnabled = false;
let photoAiFaceMode = 'off';
let photoAiFaceModel = 'gfpgan';
let photoAiDevice = '';
let photoAiConfigLoaded = false;
let enhanceSaving = false;
let enhanceTimer = null;
let enhanceClipPos = 50;
let enhanceZoom = 1;
let enhancePanX = 0;
let enhancePanY = 0;
async function loadPhotoAiConfig() {
if (photoAiConfigLoaded) return;
try {
const res = await fetch(API + '/api/public-settings', { headers: hdr() });
if (res.ok) {
const s = await res.json();
photoAiEnabled = s.photo_ai_enabled === 'true';
if (['off', 'face', 'all'].includes(s.photo_ai_face_mode)) photoAiFaceMode = s.photo_ai_face_mode;
if (['gfpgan', 'codeformer'].includes(s.photo_ai_face_model)) photoAiFaceModel = s.photo_ai_face_model;
}
} catch (e) { photoAiEnabled = false; }
photoAiConfigLoaded = true;
const sel = document.getElementById('enhanceAiMode');
if (sel) sel.value = defaultPhotoAiModeKey();
loadPhotoAiDevice();
}
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) {}
}
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';
}
function showEnhanceResult(show) {
const top = document.getElementById('enhanceTop');
const loading = document.getElementById('enhanceLoading');
if (top) top.style.display = show ? '' : 'none';
if (loading) loading.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)) + '%';
}
}
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');
if (!canvas) return;
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 isDefaultEnhanceParams() {
const p = enhanceParams();
return p.brightness === 100 && p.contrast === 100 && p.saturate === 100 && p.denoise === 0 && p.sharp === 0;
}
function setEnhanceClip(p) {
enhanceClipPos = Math.min(100, Math.max(0, p));
const top = document.getElementById('enhanceTop');
const divider = document.getElementById('enhanceDivider');
if (top) top.style.clipPath = `inset(0 0 0 ${enhanceClipPos}%)`;
if (divider) divider.style.left = enhanceClipPos + '%';
}
function applyEnhanceTransform() {
const t = `translate(${enhancePanX}px, ${enhancePanY}px) scale(${enhanceZoom})`;
const stage = document.getElementById('enhanceStage');
const inner = document.getElementById('enhanceInner');
if (stage) stage.style.transform = t;
if (inner) inner.style.transform = t;
const area = document.getElementById('enhanceCompare');
if (area) {
area.classList.toggle('zoomed', enhanceZoom > 1);
if (enhanceZoom <= 1) area.classList.remove('panning');
}
}
function clampEnhancePan() {
const area = document.getElementById('enhanceCompare');
if (!area) return;
const rect = area.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');
if (!area) return;
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);
})();
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();
}
const PHOTO_JOB_ACTION_LABELS = { ai: 'ИИ-обработка', ai_face: 'ИИ-обработка (лица)', enhance: 'Улучшение', restore: 'Возврат оригинала', rollback: 'Откат' };
const PHOTO_JOB_STATUS_LABELS = { pending: 'В очереди', processing: 'Обрабатывается', done: 'Готово', error: 'Ошибка', rejected: 'Отклонено' };
function photoJobThumb(p) {
if (!p) return '';
if (p.startsWith('/uploads/.originals/')) return `${API}${p}`;
return `${API}/uploads/thumb/${p.split('/').pop()}`;
}
async function loadPhotoHistory() {
if (!enhancePhotoId || !currentGroupId) return;
const list = document.getElementById('photoHistoryList');
if (!list) return;
list.innerHTML = 'Загрузка...
';
try {
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${enhancePhotoId}/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.action === 'ai_face') && !!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() {
if (!enhancePhotoId) return;
document.getElementById('photoHistoryTitle').textContent = `История изменений фотографии — фото #${enhancePhotoId}`;
document.getElementById('photoHistoryModal').classList.add('open');
loadPhotoHistory();
}
async function refreshEnhanceFromPath(mp) {
document.getElementById('enhanceOrig').src = `${API}${mp}`;
showEnhanceResult(false);
setEnhanceLoadingText('Загрузка...');
await new Promise(resolve => {
const img = new Image();
img.onload = () => { enhanceSourceImg = img; renderEnhancePreview(); resolve(); };
img.onerror = () => { setEnhanceLoadingText('Не удалось загрузить фото'); resolve(); };
img.src = `${API}${mp}`;
});
}
async function rollbackPhotoJob(jobId) {
if (!enhancePhotoId || !currentGroupId || enhanceSaving) return;
if (!confirm('Откатить фотографию к сохранённой версии? Текущая версия сохранится в истории.')) return;
enhanceSaving = true;
try {
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${enhancePhotoId}/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');
await refreshEnhanceFromPath(data.photo_path);
await loadGroupPhotos();
await refreshOpenFaceViewer();
loadGroups();
} catch (e) {
alert(e.message);
} finally {
enhanceSaving = false;
}
}
async function applyPhotoJob(jobId) {
if (!enhancePhotoId || !currentGroupId || enhanceSaving) return;
if (!confirm('Применить обработанную фотографию? Текущая версия сохранится в истории.')) return;
enhanceSaving = true;
try {
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${enhancePhotoId}/jobs/${jobId}/apply`, { 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');
await refreshEnhanceFromPath(data.photo_path);
await loadGroupPhotos();
await refreshOpenFaceViewer();
loadGroups();
} catch (e) {
alert(e.message);
} finally {
enhanceSaving = false;
}
}
async function saveEnhance() {
if (!enhancePhotoId || !currentGroupId || !enhanceSourceImg || enhanceSaving) return;
if (enhanceAiResultPath && isDefaultEnhanceParams()) return applyAiResult();
const btn = document.getElementById('enhanceSaveBtn');
enhanceSaving = true;
if (btn) { btn.disabled = true; btn.textContent = 'Сохранение...'; }
const groupId = currentGroupId;
const photoId = enhancePhotoId;
try {
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 res = await fetch(`${API}/api/groups/${groupId}/photos/${photoId}/enhance`, { method: 'PUT', headers: hdr(), body: fd });
if (!res.ok) { const err = await res.json().catch(() => ({})); throw new Error(err.error || 'Ошибка сохранения'); }
enhanceSaving = false;
showToast('Фото улучшено и сохранено');
closeEnhance();
await loadGroupPhotos();
await refreshOpenFaceViewer();
loadGroups();
} catch (e) {
enhanceSaving = false;
alert(e.message);
} finally {
if (btn) { btn.disabled = false; btn.textContent = 'Применить'; }
}
}
function openEnhance(id) {
const p = photos.find(x => x.id === id);
if (!p) return;
enhancePhotoId = id;
enhanceAiJobId = null;
enhanceAiResultPath = null;
enhanceSourceImg = null;
enhanceSaving = false;
resetEnhanceZoom();
setEnhanceClip(50);
const modal = document.getElementById('enhanceModal');
if (!modal) return;
['Brightness', 'Contrast', 'Saturate'].forEach(k => {
document.getElementById('enhance' + k).value = 100;
document.getElementById('enhance' + k + 'Val').textContent = '100%';
});
document.getElementById('enhanceDenoise').value = 0;
document.getElementById('enhanceDenoiseVal').textContent = '0%';
document.getElementById('enhanceSharp').value = 0;
document.getElementById('enhanceSharpVal').textContent = '0%';
const orig = document.getElementById('enhanceOrig');
if (orig) orig.src = API + p.photo_path;
const btnAi = document.getElementById('enhanceAiBtn');
if (btnAi) { btnAi.disabled = false; setBtnLabel(btnAi, 'ИИ'); }
const saveBtn = document.getElementById('enhanceSaveBtn');
if (saveBtn) saveBtn.disabled = true;
loadPhotoAiConfig().then(() => {
const show = photoAiEnabled ? '' : 'none';
if (btnAi) btnAi.style.display = show;
const modeSel = document.getElementById('enhanceAiMode');
if (modeSel) modeSel.style.display = show;
updateAiHint();
});
showEnhanceResult(false);
setEnhanceLoadingText('Загрузка...');
const img = new Image();
img.onload = () => {
if (enhanceAiResultPath) return;
enhanceSourceImg = img;
renderEnhancePreview();
if (saveBtn) saveBtn.disabled = false;
};
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 + p.photo_path;
modal.classList.add('open');
renderIcons();
}
function closeEnhance() {
cleanupAiPreview();
const modal = document.getElementById('enhanceModal');
if (modal) modal.classList.remove('open');
const history = document.getElementById('photoHistoryModal');
if (history) history.classList.remove('open');
enhancePhotoId = null;
enhanceAiJobId = null;
enhanceAiResultPath = null;
enhanceSourceImg = null;
enhanceSaving = false;
resetEnhanceZoom();
if (enhanceTimer) { clearTimeout(enhanceTimer); enhanceTimer = null; }
const loadingEl = document.getElementById('enhanceLoading');
if (loadingEl) loadingEl.style.display = 'none';
}
async function runPhotoAi() {
if (!enhancePhotoId || !currentGroupId || enhanceSaving) return;
const mode = photoAiMode();
const faceNote = mode.face === 'off'
? 'Может занять до минуты на CPU.'
: `Восстановление лиц (${mode.face_model}), на CPU может занять несколько минут.`;
if (!confirm(`ИИ-обработка фото: ${mode.title}. ${faceNote} Продолжить?`)) return;
const btnAi = document.getElementById('enhanceAiBtn');
const saveBtn = document.getElementById('enhanceSaveBtn');
enhanceSaving = true;
if (btnAi) { btnAi.disabled = true; setBtnLabel(btnAi, '⏳ ИИ...'); }
if (saveBtn) saveBtn.disabled = true;
showEnhanceResult(false);
setEnhanceLoadingProgress(0, mode.face === 'off'
? 'ИИ обрабатывает фото...'
: 'ИИ обрабатывает фото и восстанавливает лица...');
try {
const res = await fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/enhance-ai`, {
method: 'POST', headers: hdrJson(), body: JSON.stringify({ model: mode.model, face: mode.face, face_model: mode.face_model }),
});
if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error || 'Ошибка постановки задания'); }
const data = await res.json();
enhanceAiJobId = data.jobId;
pollAiResult();
} catch (err) {
enhanceSaving = false;
if (btnAi) { btnAi.disabled = false; setBtnLabel(btnAi, 'ИИ'); }
if (saveBtn) saveBtn.disabled = (enhanceAiJobId == null);
showEnhanceResult(true);
alert(err.message);
}
}
async function pollAiResult() {
if (!enhancePhotoId || !enhanceAiJobId || !currentGroupId) return;
if (enhanceAiResultPath) return;
try {
const res = await fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/enhance-ai/${enhanceAiJobId}`, { headers: hdr() });
if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error || 'Ошибка статуса'); }
const data = await res.json();
if (data.status === 'done' && data.photo_path) {
enhanceSaving = false;
enhanceAiResultPath = data.photo_path;
const btnAi = document.getElementById('enhanceAiBtn');
if (btnAi) { btnAi.disabled = false; setBtnLabel(btnAi, 'ИИ'); }
const saveBtn = document.getElementById('enhanceSaveBtn');
if (saveBtn) saveBtn.disabled = false;
const img = new Image();
img.onload = () => {
enhanceSourceImg = img;
['Brightness', 'Contrast', 'Saturate'].forEach(k => {
document.getElementById('enhance' + k).value = 100;
document.getElementById('enhance' + k + 'Val').textContent = '100%';
});
document.getElementById('enhanceDenoise').value = 0;
document.getElementById('enhanceDenoiseVal').textContent = '0%';
document.getElementById('enhanceSharp').value = 0;
document.getElementById('enhanceSharpVal').textContent = '0%';
renderEnhancePreview();
flashEnhanceResult();
};
img.onerror = () => showEnhanceResult(true);
img.src = API + data.photo_path;
setEnhanceLoadingProgress(100, 'Загрузка результата...');
showToast('ИИ результат готов');
return;
}
if (data.status === 'error') {
enhanceSaving = false;
alert(data.error || 'Ошибка обработки');
const btnAi = document.getElementById('enhanceAiBtn');
if (btnAi) { btnAi.disabled = false; setBtnLabel(btnAi, 'ИИ'); }
showEnhanceResult(true);
return;
}
// Simulate progress
const currentMode = photoAiMode();
const progress = Math.min(95, Date.now() % 10000 / 100); // Cycles 0-95 over 10 seconds
setEnhanceLoadingProgress(progress, currentMode.face === 'off'
? 'ИИ обрабатывает фото...'
: 'ИИ обрабатывает фото и восстанавливает лица...');
setTimeout(pollAiResult, 500);
} catch (err) {
enhanceSaving = false;
showEnhanceResult(true);
alert(err.message);
const btnAi = document.getElementById('enhanceAiBtn');
if (btnAi) { btnAi.disabled = false; setBtnLabel(btnAi, 'ИИ'); }
}
}
async function applyAiResult() {
if (!enhancePhotoId || !enhanceAiJobId || !currentGroupId || enhanceSaving) return;
enhanceSaving = true;
const saveBtn = document.getElementById('enhanceSaveBtn');
if (saveBtn) { saveBtn.disabled = true; saveBtn.textContent = 'Применение...'; }
const jobId = enhanceAiJobId;
try {
const res = await fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/jobs/${jobId}/apply`, {
method: 'POST', headers: hdrJson(),
});
if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error || 'Ошибка применения'); }
enhanceAiJobId = null;
enhanceAiResultPath = null;
closeEnhance();
await loadGroupPhotos();
await refreshOpenFaceViewer();
loadGroups();
} catch (err) {
alert(err.message);
enhanceSaving = false;
if (saveBtn) { saveBtn.disabled = false; saveBtn.textContent = 'Применить'; }
}
}
function cleanupAiPreview() {
if (!enhancePhotoId || !currentGroupId || !enhanceAiJobId) return;
fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/jobs/${enhanceAiJobId}/reject`, {
method: 'POST', headers: hdr(),
}).catch(() => {});
}
document.getElementById('enhanceCancelBtn')?.addEventListener('click', () => { closeEnhance(); });
document.getElementById('enhanceAiBtn')?.addEventListener('click', runPhotoAi);
document.getElementById('enhanceSaveBtn')?.addEventListener('click', saveEnhance);
document.getElementById('enhanceAutoBtn')?.addEventListener('click', autoEnhance);
document.getElementById('enhanceHistoryBtn')?.addEventListener('click', openPhotoHistory);
document.getElementById('enhanceModal')?.addEventListener('click', e => { if (e.target === e.currentTarget) closeEnhance(); });
document.getElementById('photoHistoryCloseBtn')?.addEventListener('click', () => {
const m = document.getElementById('photoHistoryModal');
if (m) m.classList.remove('open');
});
document.getElementById('photoHistoryModal')?.addEventListener('click', e => {
if (e.target === e.currentTarget) e.currentTarget.classList.remove('open');
});
document.getElementById('imgModal')?.addEventListener('click', e => e.currentTarget.classList.remove('open'));
document.getElementById('scanFacesBtn')?.addEventListener('click', scanGroupFaces);
document.getElementById('faceStudentFilter')?.addEventListener('change', () => { photoPage = 1; loadGroupPhotos(); });
document.getElementById('faceViewerCloseBtn')?.addEventListener('click', closeFaceViewer);
document.getElementById('faceViewerRescanBtn')?.addEventListener('click', rescanFaceViewerPhoto);
document.getElementById('faceViewerModal')?.addEventListener('click', e => { if (e.target === e.currentTarget) closeFaceViewer(); });
document.getElementById('faceViewerBody')?.addEventListener('click', e => {
const box = e.target.closest('[data-face-box]');
if (!box) return;
openFaceAssign(parseInt(box.dataset.faceBox, 10));
});
document.getElementById('faceAssignCancelBtn')?.addEventListener('click', () => document.getElementById('faceAssignModal').classList.remove('open'));
document.getElementById('faceAssignModal')?.addEventListener('click', e => { if (e.target === e.currentTarget) document.getElementById('faceAssignModal').classList.remove('open'); });
document.getElementById('faceAssignList')?.addEventListener('click', e => {
const pick = e.target.closest('[data-face-pick]');
if (!pick) return;
assignFace(parseInt(pick.dataset.facePick, 10));
});
document.getElementById('faceUnassignBtn')?.addEventListener('click', () => assignFace(0));
document.getElementById('faceAssignSearch')?.addEventListener('input', e => renderFaceAssignList(e.target.value));
document.getElementById('photoHistoryList')?.addEventListener('click', e => {
const rollbackBtn = e.target.closest('[data-job-rollback]');
if (rollbackBtn) { rollbackPhotoJob(parseInt(rollbackBtn.dataset.jobRollback, 10)); return; }
const applyBtn = e.target.closest('[data-job-apply]');
if (applyBtn) applyPhotoJob(parseInt(applyBtn.dataset.jobApply, 10));
});
['enhanceBrightness', 'enhanceContrast', 'enhanceSaturate', 'enhanceDenoise', 'enhanceSharp'].forEach(id => {
document.getElementById(id)?.addEventListener('input', scheduleEnhancePreview);
});
loadPhotoAiConfig();