feat(modules): batch module import in admin, module usage in journal
This commit is contained in:
+62
-21
@@ -5,7 +5,10 @@ const placeholderSrc = preview.src;
|
||||
const removePhotoBtn = document.getElementById('removePhotoBtn');
|
||||
const groupInput = document.getElementById('groupInput');
|
||||
const moduleInput = document.getElementById('moduleInput');
|
||||
const moduleInputList = document.getElementById('moduleInputList');
|
||||
const moduleField = document.getElementById('moduleField');
|
||||
const moduleNames = new Map();
|
||||
let moduleSearchTimer = null;
|
||||
const toast = document.getElementById('toast');
|
||||
const camVideo = document.getElementById('camVideo');
|
||||
const camCanvas = document.getElementById('camCanvas');
|
||||
@@ -134,22 +137,46 @@ if (params.get('nameInput')) {
|
||||
field.innerHTML = `<label>Фамилия и имя</label><div class="fixed-name" id="fixedName">${escName(studentName)}</div>`;
|
||||
}
|
||||
|
||||
function renderModuleOptions(list) {
|
||||
list.forEach(m => moduleNames.set(m.name, m.id));
|
||||
moduleInputList.innerHTML = '';
|
||||
list.forEach(m => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = m.name;
|
||||
moduleInputList.appendChild(opt);
|
||||
});
|
||||
}
|
||||
|
||||
async function fetchModules(q, limit) {
|
||||
const p = new URLSearchParams();
|
||||
if (q) p.set('search', q);
|
||||
p.set('limit', String(limit));
|
||||
try {
|
||||
const res = await fetch(`${API}/api/modules?${p}`);
|
||||
if (!res.ok) return [];
|
||||
const data = await res.json();
|
||||
return data.modules || [];
|
||||
} catch (e) { return []; }
|
||||
}
|
||||
|
||||
async function resolveModuleId(name) {
|
||||
const n = (name || '').trim();
|
||||
if (!n) return null;
|
||||
if (moduleNames.has(n)) return moduleNames.get(n);
|
||||
const list = await fetchModules(n, 5);
|
||||
renderModuleOptions(list);
|
||||
const lower = n.toLowerCase();
|
||||
const exact = list.find(m => m.name.toLowerCase() === lower);
|
||||
return exact ? exact.id : null;
|
||||
}
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const mRes = await fetch(`${API}/api/modules`);
|
||||
if (mRes.ok) {
|
||||
const mData = await mRes.json();
|
||||
const list = mData.modules || [];
|
||||
if (list.length) {
|
||||
list.forEach(m => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = m.id;
|
||||
opt.textContent = m.lessons_count > 0 ? `${m.name} · ${m.lessons_count} зан.` : m.name;
|
||||
moduleInput.appendChild(opt);
|
||||
});
|
||||
moduleInput.required = true;
|
||||
moduleField.style.display = '';
|
||||
}
|
||||
const list = await fetchModules('', 50);
|
||||
if (list.length) {
|
||||
renderModuleOptions(list);
|
||||
moduleInput.required = true;
|
||||
moduleField.style.display = '';
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
const res = await fetch(`${API}/api/students`);
|
||||
@@ -238,11 +265,15 @@ form.addEventListener('submit', async (e) => {
|
||||
setTimeout(() => toast.classList.remove('show', 'error'), 3200);
|
||||
return;
|
||||
}
|
||||
if (moduleField.style.display !== 'none' && !moduleInput.value) {
|
||||
toast.textContent = 'Выберите тему модуля';
|
||||
toast.classList.add('show', 'error');
|
||||
setTimeout(() => toast.classList.remove('show', 'error'), 3200);
|
||||
return;
|
||||
let moduleId = '';
|
||||
if (moduleField.style.display !== 'none') {
|
||||
moduleId = await resolveModuleId(moduleInput.value);
|
||||
if (!moduleId) {
|
||||
toast.textContent = 'Выберите тему модуля из списка подсказок';
|
||||
toast.classList.add('show', 'error');
|
||||
setTimeout(() => toast.classList.remove('show', 'error'), 3200);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const btn = document.getElementById('submitBtn');
|
||||
btn.disabled = true;
|
||||
@@ -253,7 +284,7 @@ form.addEventListener('submit', async (e) => {
|
||||
selectedFiles.forEach(f => fd.append('files', f, f.name));
|
||||
fd.append('student_name', studentName || document.getElementById('nameInput').value);
|
||||
fd.append('group_id', groupInput.value);
|
||||
fd.append('module_id', moduleInput.value);
|
||||
fd.append('module_id', moduleId || '');
|
||||
fd.append('description', document.getElementById('descInput').value);
|
||||
fd.append('website', document.getElementById('hpWebsite').value);
|
||||
|
||||
@@ -285,4 +316,14 @@ document.getElementById('openCamBtn').addEventListener('click', openCam);
|
||||
filesClearBtn.addEventListener('click', clearFiles);
|
||||
document.getElementById('filesBtn').addEventListener('click', () => document.getElementById('filesInput').click());
|
||||
document.getElementById('cancelCamBtn').addEventListener('click', closeCam);
|
||||
document.getElementById('captureBtn').addEventListener('click', capture);
|
||||
document.getElementById('captureBtn').addEventListener('click', capture);
|
||||
moduleInput.addEventListener('input', () => {
|
||||
clearTimeout(moduleSearchTimer);
|
||||
const q = moduleInput.value.trim();
|
||||
moduleSearchTimer = setTimeout(async () => {
|
||||
renderModuleOptions(await fetchModules(q, 20));
|
||||
}, 250);
|
||||
});
|
||||
moduleInput.addEventListener('focus', async () => {
|
||||
if (!moduleInput.value.trim()) renderModuleOptions(await fetchModules('', 50));
|
||||
});
|
||||
+85
-28
@@ -5,6 +5,10 @@ let highlightClearTimer = null;
|
||||
let editId = null;
|
||||
let editGroups = [];
|
||||
let editModules = [];
|
||||
let moduleNames = new Map();
|
||||
let moduleFilterId = '';
|
||||
let moduleSearchTimer = null;
|
||||
let editModuleSearchTimer = null;
|
||||
let modulesLoaded = false;
|
||||
let groupsLoaded = false;
|
||||
let studentsLoaded = false;
|
||||
@@ -219,29 +223,64 @@ async function loadGroupOptions() {
|
||||
groupsLoaded = true;
|
||||
}
|
||||
|
||||
async function loadModuleOptions() {
|
||||
const res = await fetch(`${API}/api/modules`);
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
editModules = data.modules || [];
|
||||
modulesLoaded = true;
|
||||
const filt = document.getElementById('moduleFilter');
|
||||
if (filt) {
|
||||
while (filt.options.length > 1) filt.remove(1);
|
||||
editModules.forEach(m => {
|
||||
const o = document.createElement('option');
|
||||
o.value = m.id; o.textContent = m.name;
|
||||
filt.appendChild(o);
|
||||
});
|
||||
}
|
||||
function renderModuleOptions(datalistId, list) {
|
||||
list.forEach(m => moduleNames.set(m.name, m.id));
|
||||
const dl = document.getElementById(datalistId);
|
||||
if (!dl) return;
|
||||
dl.innerHTML = '';
|
||||
list.forEach(m => {
|
||||
const opt = document.createElement('option');
|
||||
opt.value = m.name;
|
||||
dl.appendChild(opt);
|
||||
});
|
||||
}
|
||||
|
||||
function fillEditModuleSelect(selected) {
|
||||
const sel = document.getElementById('editModule');
|
||||
if (!sel) return;
|
||||
sel.innerHTML = '<option value="">— не выбрано —</option>' +
|
||||
editModules.map(m => `<option value="${m.id}">${esc(m.name)}</option>`).join('');
|
||||
sel.value = selected ? String(selected) : '';
|
||||
async function fetchModules(q, limit) {
|
||||
const p = new URLSearchParams();
|
||||
if (q) p.set('search', q);
|
||||
p.set('limit', String(limit));
|
||||
const res = await fetch(`${API}/api/modules?${p}`, { headers: hdr() });
|
||||
if (!res.ok) return [];
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return data.modules || [];
|
||||
}
|
||||
|
||||
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);
|
||||
const lower = n.toLowerCase();
|
||||
const exact = list.find(m => m.name.toLowerCase() === lower);
|
||||
return exact ? String(exact.id) : null;
|
||||
}
|
||||
|
||||
async function loadModuleOptions() {
|
||||
editModules = await fetchModules('', 50);
|
||||
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);
|
||||
}
|
||||
|
||||
async function loadStudentOptions() {
|
||||
@@ -265,8 +304,7 @@ async function loadEntries() {
|
||||
if (gid) p.set('group_id', gid);
|
||||
if (df) p.set('date_from', df);
|
||||
if (dt) p.set('date_to', dt);
|
||||
const mid = document.getElementById('moduleFilter') ? document.getElementById('moduleFilter').value : '';
|
||||
if (mid) p.set('module_id', mid);
|
||||
if (moduleFilterId) p.set('module_id', moduleFilterId);
|
||||
p.set('limit', PAGE_SIZE);
|
||||
p.set('offset', (page - 1) * PAGE_SIZE);
|
||||
const res = await fetch(`${API}/api/entries?${p}`, { headers: hdr() });
|
||||
@@ -368,7 +406,7 @@ async function openEdit(id) {
|
||||
}
|
||||
sel.value = e.group_id;
|
||||
if (!modulesLoaded) await loadModuleOptions();
|
||||
fillEditModuleSelect(e.module_id);
|
||||
fillEditModuleInput(e);
|
||||
renderEditPhotos(e.photos || [], e.photo_path);
|
||||
document.getElementById('editModal').classList.add('open');
|
||||
}
|
||||
@@ -1158,11 +1196,14 @@ async function saveEdit() {
|
||||
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', document.getElementById('editModule').value);
|
||||
formData.append('module_id', moduleId);
|
||||
|
||||
const photoFiles = document.getElementById('editPhoto').files;
|
||||
for (const f of photoFiles) formData.append('photo', f);
|
||||
@@ -1206,7 +1247,24 @@ async function delEntry(id) {
|
||||
|
||||
document.getElementById('studentFilter').addEventListener('change', () => { page = 1; loadEntries(); });
|
||||
document.getElementById('groupFilter').addEventListener('change', () => { page = 1; loadEntries(); });
|
||||
document.getElementById('moduleFilter').addEventListener('change', () => { page = 1; loadEntries(); });
|
||||
document.getElementById('moduleFilter').addEventListener('change', applyModuleFilter);
|
||||
document.getElementById('moduleFilter').addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter') { e.preventDefault(); applyModuleFilter(); }
|
||||
});
|
||||
document.getElementById('moduleFilter').addEventListener('input', () => {
|
||||
clearTimeout(moduleSearchTimer);
|
||||
const q = document.getElementById('moduleFilter').value.trim();
|
||||
moduleSearchTimer = setTimeout(async () => {
|
||||
renderModuleOptions('moduleFilterList', await fetchModules(q, 20));
|
||||
}, 250);
|
||||
});
|
||||
document.getElementById('editModule').addEventListener('input', () => {
|
||||
clearTimeout(editModuleSearchTimer);
|
||||
const q = document.getElementById('editModule').value.trim();
|
||||
editModuleSearchTimer = setTimeout(async () => {
|
||||
renderModuleOptions('editModuleList', await fetchModules(q, 20));
|
||||
}, 250);
|
||||
});
|
||||
document.getElementById('dateFrom').addEventListener('change', () => { page = 1; loadEntries(); });
|
||||
document.getElementById('dateTo').addEventListener('change', () => { page = 1; loadEntries(); });
|
||||
document.getElementById('searchInput').addEventListener('input', () => {
|
||||
@@ -1261,8 +1319,7 @@ async function exportCSV() {
|
||||
if (gid) p.set('group_id', gid);
|
||||
if (df) p.set('date_from', df);
|
||||
if (dt) p.set('date_to', dt);
|
||||
const mid = document.getElementById('moduleFilter') ? document.getElementById('moduleFilter').value : '';
|
||||
if (mid) p.set('module_id', mid);
|
||||
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; }
|
||||
|
||||
@@ -114,6 +114,83 @@ document.getElementById('moduleForm').addEventListener('submit', async (e) => {
|
||||
}
|
||||
});
|
||||
|
||||
function parseBatchModules(raw) {
|
||||
const items = [];
|
||||
const errors = [];
|
||||
const seen = new Set();
|
||||
String(raw).split('\n').forEach((line, idx) => {
|
||||
const text = line.trim();
|
||||
if (!text) return;
|
||||
const lineNo = idx + 1;
|
||||
let name = '';
|
||||
let lessonsRaw = '';
|
||||
const sepIndex = text.search(/[|;=\t]/);
|
||||
if (sepIndex !== -1) {
|
||||
name = text.slice(0, sepIndex).trim();
|
||||
lessonsRaw = text.slice(sepIndex + 1).trim();
|
||||
} else {
|
||||
const numMatch = text.match(/^(.*\S)\s+(\d+)$/);
|
||||
if (numMatch) {
|
||||
name = numMatch[1].trim();
|
||||
lessonsRaw = numMatch[2];
|
||||
}
|
||||
}
|
||||
if (!name && !lessonsRaw) { errors.push(`Строка ${lineNo}: «${text}» — укажите название и количество занятий, например: Основы Python | 10`); return; }
|
||||
if (!name) { errors.push(`Строка ${lineNo}: «${text}» — не указано название`); return; }
|
||||
if (!lessonsRaw) { errors.push(`Строка ${lineNo}: «${text}» — не указано количество занятий`); return; }
|
||||
const lessons = Number(lessonsRaw);
|
||||
if (!Number.isInteger(lessons) || lessons < 0 || lessons > 10000) {
|
||||
errors.push(`Строка ${lineNo}: «${text}» — количество занятий должно быть целым числом от 0 до 10000`);
|
||||
return;
|
||||
}
|
||||
const key = name.toLowerCase();
|
||||
if (seen.has(key)) { errors.push(`Строка ${lineNo}: «${text}» — дубликат названия в списке`); return; }
|
||||
seen.add(key);
|
||||
items.push({ name, lessons_count: lessons });
|
||||
});
|
||||
return { items, errors };
|
||||
}
|
||||
|
||||
function openBatchModuleModal() {
|
||||
document.getElementById('batchModuleForm').reset();
|
||||
document.getElementById('batchModuleModal').classList.add('open');
|
||||
setTimeout(() => document.getElementById('batchModuleText').focus(), 100);
|
||||
}
|
||||
|
||||
function closeBatchModuleModal() {
|
||||
document.getElementById('batchModuleModal').classList.remove('open');
|
||||
}
|
||||
|
||||
async function batchAddModules() {
|
||||
const submitBtn = document.getElementById('batchModuleSubmitBtn');
|
||||
const { items, errors } = parseBatchModules(document.getElementById('batchModuleText').value);
|
||||
if (errors.length) {
|
||||
alert('Исправьте строки:\n\n' + errors.join('\n'));
|
||||
return;
|
||||
}
|
||||
if (!items.length) { alert('Добавьте хотя бы один модуль'); return; }
|
||||
submitBtn.disabled = true;
|
||||
let added = 0, dupes = 0, failed = 0;
|
||||
for (const item of items) {
|
||||
const res = await fetch(`${API}/api/modules`, { method: 'POST', headers: hdrJson(), body: JSON.stringify(item) });
|
||||
if (res.ok) added++;
|
||||
else if (res.status === 409) dupes++;
|
||||
else failed++;
|
||||
}
|
||||
submitBtn.disabled = false;
|
||||
closeBatchModuleModal();
|
||||
loadModules();
|
||||
showToast(`Добавлено: ${added}${dupes ? `, дубликатов: ${dupes}` : ''}${failed ? `, ошибок: ${failed}` : ''}`);
|
||||
}
|
||||
|
||||
document.getElementById('batchModuleForm').addEventListener('submit', e => {
|
||||
e.preventDefault();
|
||||
batchAddModules();
|
||||
});
|
||||
document.getElementById('batchModuleBtn').addEventListener('click', openBatchModuleModal);
|
||||
document.getElementById('batchModuleCancelBtn').addEventListener('click', closeBatchModuleModal);
|
||||
document.getElementById('batchModuleModal').addEventListener('click', e => { if (e.target === e.currentTarget) closeBatchModuleModal(); });
|
||||
|
||||
document.getElementById('addModuleBtn').addEventListener('click', () => openModuleModal());
|
||||
document.getElementById('moduleCancelBtn').addEventListener('click', closeModuleModal);
|
||||
document.getElementById('moduleModal').addEventListener('click', e => { if (e.target === e.currentTarget) closeModuleModal(); });
|
||||
|
||||
Reference in New Issue
Block a user