const API_BASE = `${location.protocol}//${location.hostname}:8000`; const app = document.getElementById('app'); function render(html){ app.innerHTML = html } function showAgreement(){ render(`

Соглашение

Нажмите продолжить, чтобы зарегистрироваться и пройти тест.

`); document.getElementById('agree').onclick = ()=> showRegister(); } function showRegister(){ render(`

Регистрация



`); document.getElementById('reg').onsubmit = async (e)=>{ e.preventDefault(); const fd = new FormData(e.target); const first = (fd.get('firstname') || '').trim(); const last = (fd.get('lastname') || '').trim(); const data = {first_name: first, last_name: last}; const res = await fetch(`${API_BASE}/users/`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)}); if(!res.ok){ document.getElementById('result').innerText = 'Ошибка создания'; return } const user = await res.json(); localStorage.setItem('user_id', user.id); showPollList(); } } async function showPollList(){ const res = await fetch(`${API_BASE}/polls`); const polls = res.ok ? await res.json() : []; render(`

Доступные тесты

`); document.getElementById('refresh').onclick = showPollList; document.querySelectorAll('#polls a').forEach(a=>a.onclick = (ev)=>{ ev.preventDefault(); const id = a.getAttribute('href').slice(6); showPoll(id); }); } async function showPoll(id){ const res = await fetch(`${API_BASE}/polls/${id}`); if(!res.ok){ render('

Не удалось загрузить тест

'); return } const poll = await res.json(); // simple rendering: list questions and choices (if present) const html = [`

${poll.title||poll.name||'Тест'}

`]; poll.questions = poll.questions || []; html.push(`
`); poll.questions.forEach(q=>{ html.push(`
${q.text||q.prompt||q.id}`); const choices = q.choices || []; if(choices.length){ choices.forEach(c=> html.push(`
`)); } else { html.push(`
`); } html.push('
'); }); html.push('
'); html.push('
'); render(html.join('')); document.getElementById('resp').onsubmit = async (e)=>{ e.preventDefault(); const form = new FormData(e.target); const answers = []; for(const [k,v] of form.entries()){ if(!k.startsWith('q_')) continue; const qid = k.slice(2); answers.push({question_id: qid, choice_id: v}); } const payload = {user_id: localStorage.getItem('user_id'), answers}; const r = await fetch(`${API_BASE}/polls/${id}/responses`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(payload)}); if(!r.ok){ document.getElementById('msg').innerText = 'Ошибка отправки'; return } document.getElementById('msg').innerText = 'Ответы отправлены'; } } // start showAgreement();