Files
WhatIDo/public/js/photos.js
T
dev 39ae3fdd30 feat(modules): флаг «Вложения» у модуля и подсказка ученику на главной
- переключатель «Вложения» слева от «Количество занятий» в модалке модуля,
  бейдж «Вложения» в списке модулей
- колонка modules.has_attachments: db/init.sql, db/migration.sql,
  ensureModulesTable(), POST/PUT/GET /api/modules, GET /api/v1/modules, backup
- на главной странице у выбранного модуля с вложениями показывается
  подсказка «К этой теме нужно приложить файлы»

Также вошла ранее незакоммиченная работа:
- битые изображения: скан и карантин, раздел «Битые изображения» в корзине
  (таблица broken_images, /api/broken-images/*, trash.html + trash.js)
- отзывы: фото ученика и цветовая полоса оценки работ в модалке
  (#fbResidentPhoto, #fbMarkStripe, GET /api/feedbacks/work-marks)
- фото и галереи: photo_key/photo_id в /api/photos и inline-карантин битых фото
- поля пароля на journal.html и links.html обёрнуты в no-op form
2026-10-14 00:01:27 +03:00

178 lines
7.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const PAGE_SIZE = 28;
let page = 1;
let totalPhotos = 0;
let currentPhotos = [];
let groupsLoaded = false;
let studentsLoaded = false;
let sourcesLoaded = false;
let searchTimer = null;
function humanSize(b) {
if (!b) return '';
if (b < 1024) return b + ' Б';
if (b < 1048576) return (b / 1024).toFixed(1) + ' КБ';
return (b / 1048576).toFixed(1) + ' МБ';
}
function photoLink(p) {
if (p.source_type === 'entry') return `journal.html#entry-${p.source_id}`;
if (p.source_type === 'entry_photo') return `journal.html#entry-${p.source_id}`;
if (p.source_type === 'group_photo') return 'groups.html';
if (p.source_type === 'student_photo') return 'students.html';
if (p.source_type === 'module_photo') return 'modules.html';
return '';
}
function photoThumb(p) {
if (typeof p === 'string' && p.startsWith('/uploads/.originals/')) return `${API}${p}`;
if (typeof p === 'string' && p.startsWith('/uploads/')) return `${API}/uploads/thumb/${p.slice('/uploads/'.length)}`;
return thumbSrc(p);
}
function photoCardHTML(p) {
const url = p.path;
const meta = [];
if (p.student_name) meta.push(esc(p.student_name));
if (p.group_name) meta.push(esc(p.group_name));
const link = photoLink(p);
const canFix = isAdmin() && p.photo_key && p.photo_id != null;
return `
<div class="ph-card">
<img src="${esc(photoThumb(url))}" data-img="${esc(url)}" loading="lazy" decoding="async" alt="" onerror="photoImgError(this)">
<div class="ph-body">
<span class="ph-badge">${esc(p.source_label)}</span>
<div class="ph-title">${esc(p.title || 'Без описания')}</div>
${meta.length ? `<div class="ph-meta">${meta.join(' · ')}</div>` : ''}
<div class="ph-time">${fmtFull(p.created_at)}</div>
<span class="ph-broken-tag" hidden>Файл не найден</span>
${canFix ? `<button type="button" class="btn-link danger ph-broken-btn" data-quarantine="${esc(p.photo_key)}" data-quarantine-id="${esc(p.photo_id)}" hidden>В корзину</button>` : ''}
${link ? `<a class="ph-link" href="${link}">Открыть источник →</a>` : ''}
</div>
</div>
`;
}
function renderGrid() {
const grid = document.getElementById('grid');
if (!currentPhotos.length) {
grid.innerHTML = '<div class="empty" style="grid-column:1/-1">Фотографий не найдено</div>';
return;
}
grid.innerHTML = currentPhotos.map(photoCardHTML).join('');
}
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;
}
async function loadStudentOptions() {
if (studentsLoaded) return;
const dl = document.getElementById('studentFilterList');
const fs = document.getElementById('faceStudentFilter');
const res = await fetch(`${API}/api/students/names`, { headers: hdr() });
const names = await res.json();
dl.innerHTML = names.map(n => `<option value="${esc(n)}">`).join('');
if (fs) {
try {
const r2 = await fetch(`${API}/api/students?limit=1000`, { headers: hdr() });
const data = r2.ok ? await r2.json() : null;
const list = Array.isArray(data) ? data : (data && data.students) || [];
list.filter(s => !s.deleted_at).forEach(s => {
const o = document.createElement('option');
o.value = String(s.id);
o.textContent = s.name;
fs.appendChild(o);
});
} catch {}
}
studentsLoaded = true;
}
function fillSourceOptions() {
if (sourcesLoaded) return;
const sel = document.getElementById('sourceFilter');
const labels = [];
currentPhotos.forEach(p => { if (!labels.includes(p.source_label)) labels.push(p.source_label); });
const known = ['Главное фото записи', 'Фото записи', 'Фотохроника группы', 'Фото ученика', 'Тема модуля'];
known.concat(labels.filter(l => !known.includes(l))).forEach(label => {
const o = document.createElement('option');
o.value = label; o.textContent = label;
sel.appendChild(o);
});
sourcesLoaded = true;
}
async function loadPhotos() {
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);
const fv = document.getElementById('faceStudentFilter') ? document.getElementById('faceStudentFilter').value : '';
if (fv === '__unassigned__') p.set('unassigned_faces', '1');
else if (fv) p.set('student_id', fv);
p.set('limit', PAGE_SIZE);
p.set('offset', (page - 1) * PAGE_SIZE);
const res = await fetch(`${API}/api/photos?${p}`, { headers: hdr() });
if (!res.ok) {
document.getElementById('grid').innerHTML = '<div class="empty" style="grid-column:1/-1">Не удалось загрузить фотографии</div>';
return;
}
const data = await res.json();
const srcFilter = document.getElementById('sourceFilter').value;
currentPhotos = srcFilter ? data.photos.filter(x => x.source_label === srcFilter) : data.photos;
totalPhotos = srcFilter ? currentPhotos.length : data.total;
fillSourceOptions();
renderGrid();
renderPager(document.getElementById('pager'), page, Math.max(1, Math.ceil(totalPhotos / PAGE_SIZE)), goPage);
}
function goPage(p) {
page = p;
loadPhotos();
}
document.getElementById('studentFilter').addEventListener('change', () => { page = 1; loadPhotos(); });
document.getElementById('groupFilter').addEventListener('change', () => { page = 1; loadPhotos(); });
document.getElementById('sourceFilter').addEventListener('change', () => { page = 1; loadPhotos(); });
document.getElementById('faceStudentFilter')?.addEventListener('change', () => { page = 1; loadPhotos(); });
document.getElementById('dateFrom').addEventListener('change', () => { page = 1; loadPhotos(); });
document.getElementById('dateTo').addEventListener('change', () => { page = 1; loadPhotos(); });
document.getElementById('searchInput').addEventListener('input', () => {
clearTimeout(searchTimer);
searchTimer = setTimeout(() => { page = 1; loadPhotos(); }, 300);
});
document.getElementById('imgModal').addEventListener('click', e => e.currentTarget.classList.remove('open'));
document.getElementById('grid').addEventListener('click', async e => {
const btn = e.target.closest('[data-quarantine]');
if (!btn) return;
if (await quarantineBrokenPhoto(btn.dataset.quarantine, btn.dataset.quarantineId)) loadPhotos();
});
(async () => {
if (await checkAuth()) {
buildSidebar('photos');
await loadGroupOptions();
await loadStudentOptions();
loadPhotos();
}
})();