let allStudents = [];
let allGroups = [];
let groupOptionsLoaded = false;
let sPage = 1;
const S_PAGE_SIZE = 25;
let sSearchTimer = null;
let aSearchTimer = null;
let attachGroupLoaded = false;
async function loadGroupOptions(sel, selected) {
if (!groupOptionsLoaded) {
const res = await fetch(`${API}/api/groups`, { headers: hdr() });
allGroups = await res.json();
groupOptionsLoaded = true;
const filt = document.getElementById('studentGroupFilter');
if (filt && filt.options.length <= 1) {
filt.innerHTML = `` +
allGroups.map(g => ``).join('');
}
}
if (sel) {
sel.innerHTML = `` +
allGroups.map(g => ``).join('');
}
}
async function loadStudents() {
const res = await fetch(`${API}/api/students`, { headers: hdr() });
allStudents = await res.json();
renderStudents();
}
function renderStudents() {
const q = document.getElementById('studentSearch').value.trim().toLowerCase();
const gid = document.getElementById('studentGroupFilter').value;
let filtered = q ? allStudents.filter(s => s.name.toLowerCase().includes(q)) : allStudents;
if (gid) filtered = filtered.filter(s => String(s.group_id) === gid);
const totalPages = Math.max(1, Math.ceil(filtered.length / S_PAGE_SIZE));
if (sPage > totalPages) sPage = 1;
const slice = filtered.slice((sPage - 1) * S_PAGE_SIZE, sPage * S_PAGE_SIZE);
const list = document.getElementById('studentList');
if (!slice.length) { list.innerHTML = '
})
${p.photo_path === main ? '
Главная' : ''}
`).join('');
}
async function uploadStudentPhoto(file) {
if (!profileDataId || !file) return;
if (!file.type.startsWith('image/')) {
alert('Можно загружать только изображения');
return;
}
showToast('Загружаем фото...');
const fd = new FormData();
fd.append('photo', file);
try {
const res = await fetch(`${API}/api/students/${profileDataId}/photos`, { method: 'POST', headers: hdr(), body: fd });
if (res.ok) {
await loadStudentPhotos(profileDataId);
showToast('Фото загружено');
} else {
const e = await res.json().catch(() => ({}));
alert(e.error || 'Не удалось загрузить фото');
}
} catch (err) {
alert('Ошибка при загрузке фото');
}
}
async function setMainStudentPhoto(pid) {
if (!profileDataId) return;
try {
const res = await fetch(`${API}/api/students/${profileDataId}/photos/${pid}/main`, { method: 'PUT', headers: hdr() });
if (res.ok) {
const r = await res.json();
document.getElementById('pfPhoto').value = r.photo_path || '';
renderStudentPhotos();
showToast('Главное фото обновлено');
} else {
const e = await res.json().catch(() => ({}));
alert(e.error || 'Не удалось выбрать главное фото');
}
} catch (err) {
alert('Ошибка при выборе главного фото');
}
}
async function delStudentPhoto(pid) {
if (!profileDataId) return;
if (!confirm('Удалить это фото?')) return;
try {
const res = await fetch(`${API}/api/students/${profileDataId}/photos/${pid}`, { method: 'DELETE', headers: hdr() });
if (res.ok) {
await loadStudentPhotos(profileDataId);
showToast('Фото удалено');
} else {
const e = await res.json().catch(() => ({}));
alert(e.error || 'Не удалось удалить фото');
}
} catch (err) {
alert('Ошибка при удалении фото');
}
}
function fillProfileForm(profile, name, photoPath) {
const p = profile || {};
const set = (id, v) => { document.getElementById(id).value = v === null || v === undefined ? '' : String(v); };
document.getElementById('profileDataTitle').textContent = name || 'Профиль ученика';
set('pfRole', p.role); set('pfStatus', p.status); set('pfStatusNote', p.status_note);
set('pfCity', p.city); set('pfMentor', p.mentor); set('pfJoined', p.joined);
set('pfBio', p.bio); set('pfQuote', p.quote);
set('pfTags', (p.tags || []).join(', '));
set('pfContacts', (p.contacts || []).map(c => [c.icon || 'link', c.label, c.href || ''].join(' | ')).join('\n'));
set('pfAchievements', (p.achievements || []).join('\n'));
set('pfSkills', (p.skills || []).map(s => [s.group || 'Навыки', s.name, s.level || '', s.value === null || s.value === undefined ? '' : s.value].join(' | ')).join('\n'));
set('pfExperience', (p.experience || []).map(e => [e.title, e.company || '', e.period || '', e.date || '', e.badge || '', e.description || '', (e.tags || []).join(',')].join(' | ')).join('\n'));
set('pfEducation', (p.education || []).map(m => [m.module, m.progress === null || m.progress === undefined ? '' : m.progress, m.grade || '', m.teacher || ''].join(' | ')).join('\n'));
set('pfPhoto', photoPath || '');
}
function collectProfile() {
const val = id => document.getElementById(id).value.trim();
const lines = id => val(id).split('\n').map(s => s.trim()).filter(Boolean);
const cols = line => line.split('|').map(s => s.trim());
const intOrNull = s => (s === '' || s === null || s === undefined ? null : Number(s));
const out = {
role: val('pfRole') || null,
status: val('pfStatus') || null,
status_note: val('pfStatusNote') || null,
city: val('pfCity') || null,
mentor: val('pfMentor') || null,
joined: val('pfJoined') || null,
bio: val('pfBio') || null,
quote: val('pfQuote') || null,
tags: val('pfTags') ? val('pfTags').split(',').map(s => s.trim()).filter(Boolean) : [],
contacts: lines('pfContacts').map(l => {
const c = cols(l);
return { icon: c[0] || 'link', label: c[1] || '', href: c[2] || '' };
}).filter(c => c.label),
achievements: lines('pfAchievements'),
skills: lines('pfSkills').map(l => {
const c = cols(l);
return { group: c[0] || 'Навыки', name: c[1] || '', level: c[2] || null, value: intOrNull(c[3]) };
}).filter(s => s.name),
experience: lines('pfExperience').map(l => {
const c = cols(l);
return {
title: c[0] || '', company: c[1] || null, period: c[2] || null, date: c[3] || null,
badge: c[4] || null, description: c[5] || null,
tags: c[6] ? c[6].split(',').map(s => s.trim()).filter(Boolean) : [],
};
}).filter(e => e.title),
education: lines('pfEducation').map(l => {
const c = cols(l);
return { module: c[0] || '', progress: intOrNull(c[1]), grade: c[2] || null, teacher: c[3] || null };
}).filter(m => m.module),
};
const hasData = Object.keys(out).some(k => (Array.isArray(out[k]) ? out[k].length : out[k]));
return hasData ? out : null;
}
async function saveProfileData(e) {
e.preventDefault();
if (!profileDataId) return;
const body = { profile: collectProfile() };
const photoPath = document.getElementById('pfPhoto').value.trim();
body.photo_path = photoPath || null;
const res = await fetch(`${API}/api/students/${profileDataId}/profile`, {
method: 'PUT',
headers: hdrJson(),
body: JSON.stringify(body),
});
if (res.ok) {
closeProfileData();
loadStudents();
showToast('Данные профиля сохранены');
} else {
const err = await res.json().catch(() => ({}));
alert(err.error || 'Не удалось сохранить данные профиля');
}
}
async function delStudent(id) {
if (!confirm('Удалить ученика из списка? Старые записи останутся.')) return;
await fetch(`${API}/api/students/${id}`, { method: 'DELETE', headers: hdr() });
loadStudents();
fillAutocomplete();
}
function openBatchAdd() {
document.getElementById('batchText').value = '';
loadGroupOptions(document.getElementById('batchGroup'), '');
document.getElementById('batchModal').classList.add('open');
}
function closeBatchAdd() {
document.getElementById('batchModal').classList.remove('open');
}
async function batchAdd() {
const raw = document.getElementById('batchText').value;
const names = [...new Set(raw.split('\n').map(s => s.trim()).filter(Boolean))];
if (!names.length) return;
const group_id = document.getElementById('batchGroup').value;
let added = 0, dupes = 0;
for (const name of names) {
const res = await fetch(`${API}/api/students`, { method: 'POST', headers: hdrJson(), body: JSON.stringify({ name, group_id: group_id || null }) });
if (res.ok) added++;
else if (res.status === 409) dupes++;
}
closeBatchAdd();
loadStudents();
fillAutocomplete();
showToast(`Добавлено: ${added}${dupes ? `, дубликатов: ${dupes}` : ''}`);
}
document.getElementById('newStudent').addEventListener('keydown', e => { if (e.key === 'Enter') addStudent(); });
document.getElementById('batchForm').addEventListener('submit', e => {
e.preventDefault();
batchAdd();
});
document.getElementById('studentSearch').addEventListener('input', () => {
clearTimeout(sSearchTimer);
sSearchTimer = setTimeout(() => { sPage = 1; renderStudents(); }, 300);
});
document.getElementById('studentGroupFilter').addEventListener('change', () => { sPage = 1; renderStudents(); });
function exportStudentsCSV() {
const gid = document.getElementById('studentGroupFilter').value;
const list = gid ? allStudents.filter(s => String(s.group_id) === gid) : allStudents;
if (!list.length) { alert('Нет данных для экспорта'); return; }
const rows = [['Фамилия Имя', 'Группа', 'Ссылка на страницу']];
list.forEach(s => {
rows.push([
s.name,
s.group_name || '',
`${location.origin}/?nameInput=${encodeURIComponent(s.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;
const groupName = gid ? (allGroups.find(g => g.id == gid)?.name || 'group') : 'all';
a.download = `students_${groupName.replace(/[\\/:*?"<>|]/g, '_')}.csv`;
a.click();
URL.revokeObjectURL(url);
showToast(`Экспортировано: ${list.length}`);
}
async function exportStudentsUrls() {
const gid = document.getElementById('studentGroupFilter').value;
const list = gid ? allStudents.filter(s => String(s.group_id) === gid) : allStudents;
if (!list.length) { alert('Нет данных для экспорта'); return; }
const groupName = gid ? (allGroups.find(g => g.id == gid)?.name || 'group') : 'all';
await exportStudentUrlZip(list, `students_${groupName.replace(/[\\/:*?"<>|]/g, '_')}.zip`);
showToast(`Экспортировано: ${list.length}`);
}
async function openBatchAttach() {
const sel = document.getElementById('attachGroup');
if (!attachGroupLoaded) {
const res = await fetch(`${API}/api/groups`, { headers: hdr() });
const groups = await res.json();
sel.innerHTML = `