let currentPostTasks = []; let allPostTasks = []; let plPage = 1; let plPageSize = 20; let plReasonPending = null; function esc(s) { return String(s == null ? '' : s).replace(/&/g,'&').replace(//g,'>').replace(/"/g,'"'); } async function loadPostLessonTasks() { const days = document.getElementById('plDays').value; const res = await fetch(`${API}/api/post-lesson-tasks?days=${encodeURIComponent(days)}`, { headers: hdr() }); if (!res.ok) { document.getElementById('plList').innerHTML = '
Не удалось загрузить задачи
'; return; } const d = await res.json(); allPostTasks = Array.isArray(d.items) ? d.items : []; renderPostLessonTasks(); } function filteredTasks() { const q = (document.getElementById('plSearch').value || '').trim().toLowerCase(); const status = document.getElementById('plStatus').value; const showClosed = document.getElementById('plShowDismissed').checked; return allPostTasks.filter(t => { if (q && !String(t.group_name || '').toLowerCase().includes(q)) return false; const isClosed = !!t.closed; if (!showClosed && isClosed) return false; if (status === 'pending' && (t.all_done || isClosed)) return false; if (status === 'completed' && !t.all_done) return false; if (status === 'overdue' && !(t.overdue && !t.all_done)) return false; return true; }); } function fmtInstant(v) { try { if (typeof fmtDateTime === 'function') return fmtDateTime(v); } catch (e) {} return String(v || ''); } function renderBasis(steps) { const doneSteps = (steps || []).filter(s => s.done && Array.isArray(s.basis) && s.basis.length); if (!doneSteps.length) return ''; const rows = doneSteps.map(s => { const items = s.basis.map(b => { const parts = []; if (b.author) parts.push(esc(b.author)); if (b.resident) parts.push('резидент: ' + esc(b.resident)); if (b.created_at) parts.push(fmtInstant(b.created_at)); if (b.id) parts.push('#' + esc(b.id)); return `${parts.join(' · ')}`; }).join(', '); return `
${esc(s.label)}: ${items}
`; }).join(''); return `
${rows}
`; } function renderPostLessonTasks() { const el = document.getElementById('plList'); const summary = document.getElementById('plSummary'); if (!el) return; const visible = filteredTasks(); currentPostTasks = visible; if (!visible.length) { el.innerHTML = '
Нет задач
'; if (summary) summary.textContent = ''; renderPager(0); return; } const pendingCount = visible.filter(t => !t.all_done && !t.closed).length; const overdueCount = visible.filter(t => t.overdue && !t.all_done).length; const closedCount = allPostTasks.filter(t => t.closed).length; if (summary) summary.textContent = `Всего: ${visible.length} · невыполненных: ${pendingCount} · просроченных: ${overdueCount} · закрытых: ${closedCount}`; const pageSize = plPageSize; const totalPages = Math.max(1, Math.ceil(visible.length / pageSize)); if (plPage > totalPages) plPage = totalPages; if (plPage < 1) plPage = 1; const start = (plPage - 1) * pageSize; const pageItems = visible.slice(start, start + pageSize); el.innerHTML = pageItems.map(t => { const steps2 = t.steps.map(s => ({ ...s, manual: !s.done && !!s.reason })); const completed = steps2.filter(s => s.done).length; const allDone = completed === steps2.length; const nextIdx = steps2.findIndex(s => !s.done); const link = steps2[nextIdx >= 0 ? nextIdx : 0].link; const isClosed = !!t.closed; const isOverdue = t.overdue && !allDone; const pct = steps2.length ? Math.round((completed / steps2.length) * 100) : 0; let badgeCls = 'pending', badgeText = 'В работе', barColor = '#f59e0b'; if (isClosed) { badgeCls = 'dismissed'; badgeText = 'Закрыта'; barColor = '#94a3b8'; } else if (allDone) { badgeCls = 'done'; badgeText = 'Выполнена'; barColor = '#22c55e'; } else if (t.overdue) { badgeCls = 'overdue'; badgeText = 'Просрочена'; barColor = '#ef4444'; } return `
${t.group_cover ? `` : `
`}
${completed}/${steps2.length}
${esc(t.group_name)} · ${esc(t.lesson_date)}
${esc(t.lesson_time)}${t.tutor_name ? ' · ' + esc(t.tutor_name) : ''}
${badgeText}${isClosed && t.close_reason ? ' · ' + esc(t.close_reason) : ''}
${steps2.map((s, i) => { const related = (s.key === 'shorts' && Array.isArray(s.related) && s.related.length) ? s.related : []; const warn = (!s.done && related.length) ? 'warn' : ''; const title = related.length ? 'Короткие сообщения найдены, но не засчитаны: ' + related.map(r => r.resident + ' (' + r.lesson_date + (r.reason === 'date' ? ', другая дата' : ', другой автор') + ')').join('; ') : 'Нажмите, чтобы переключить статус'; const reason = s.reason ? ' · причина: ' + esc(s.reason) : ''; return `${s.done ? '✓' : (related.length ? '⚠' : '○')} ${esc(s.label)}${related.length ? ' (' + related.length + ')' : ''}`; }).join('')}
${t.shorts_related && t.shorts_related.length ? `
Короткие сообщения найдены (${t.shorts_related.length}), но не засчитаны: ${t.shorts_related.map(r => esc(r.resident) + ' — ' + esc(r.lesson_date) + (r.reason === 'date' ? ' (другая дата)' : ' (другой автор)')).join(', ')}. Проверьте дату и автора.
` : ''}
${isClosed ? `` : ``}
`; }).join(''); renderPager(visible.length); renderIcons(); } function renderPager(total) { const pager = document.getElementById('plPager'); if (!pager) return; const pageSize = plPageSize; const totalPages = Math.max(1, Math.ceil(total / pageSize)); if (plPage > totalPages) plPage = totalPages; if (plPage < 1) plPage = 1; if (total <= pageSize) { pager.innerHTML = ''; return; } let html = ''; html += ``; const maxBtns = 7; let start = Math.max(1, plPage - 3); let end = Math.min(totalPages, start + maxBtns - 1); if (end - start < maxBtns - 1) start = Math.max(1, end - maxBtns + 1); if (start > 1) { html += ``; if (start > 2) html += `…`; } for (let p = start; p <= end; p++) { html += ``; } if (end < totalPages) { if (end < totalPages - 1) html += `…`; html += ``; } html += ``; html += `${(plPage - 1) * pageSize + 1}–${Math.min(plPage * pageSize, total)} из ${total}`; pager.innerHTML = html; } async function saveStepState(taskKey, stepKey, isDone, reason) { const p = parseTaskKey(taskKey); if (!p) return; const res = await fetch(`${API}/api/post-lesson-tasks/step`, { method: 'POST', headers: { ...hdr(), 'Content-Type': 'application/json' }, body: JSON.stringify({ group_id: p.groupId, lesson_date: p.lessonDate, step_key: stepKey, is_done: isDone, reason }), }); if (!res.ok) throw new Error('Не удалось сохранить шаг'); await loadPostLessonTasks(); } async function closeTaskWithReason(taskKey, closeReason) { const p = parseTaskKey(taskKey); if (!p) return; const res = await fetch(`${API}/api/post-lesson-tasks/close`, { method: 'POST', headers: { ...hdr(), 'Content-Type': 'application/json' }, body: JSON.stringify({ group_id: p.groupId, lesson_date: p.lessonDate, close_reason: closeReason }), }); if (!res.ok) throw new Error('Не удалось закрыть задачу'); await loadPostLessonTasks(); } async function reopenTask(taskKey) { const p = parseTaskKey(taskKey); if (!p) return; const res = await fetch(`${API}/api/post-lesson-tasks/close`, { method: 'DELETE', headers: { ...hdr(), 'Content-Type': 'application/json' }, body: JSON.stringify({ group_id: p.groupId, lesson_date: p.lessonDate }), }); if (!res.ok) throw new Error('Не удалось вернуть задачу'); await loadPostLessonTasks(); } function parseTaskKey(key) { const idx = key.lastIndexOf('|'); if (idx <= 0) return null; const groupId = parseInt(key.slice(0, idx), 10); const lessonDate = key.slice(idx + 1); if (!groupId || !/^\d{4}-\d{2}-\d{2}$/.test(lessonDate)) return null; return { groupId, lessonDate }; } function openReasonModal(taskKey, stepKey, currentReason) { const modal = document.getElementById('plReasonModal'); const title = document.getElementById('plReasonTitle'); const sub = document.getElementById('plReasonSub'); const textarea = document.getElementById('plReasonText'); const t = allPostTasks.find(x => x.key === taskKey); const step = t && t.steps.find(s => s.key === stepKey); if (!modal || !title || !sub || !textarea || !t || !step) return; title.textContent = `Причина закрытия шага: ${esc(step.label)}`; sub.textContent = `${esc(t.group_name)} · ${esc(t.lesson_date)}`; textarea.value = currentReason || ''; plReasonPending = { taskKey, stepKey }; modal.classList.add('open'); textarea.focus(); } function closeReasonModal() { const modal = document.getElementById('plReasonModal'); if (modal) modal.classList.remove('open'); plReasonPending = null; const ta = document.getElementById('plReasonText'); if (ta) ta.value = ''; } function openCloseReasonModal(taskKey, currentReason) { const modal = document.getElementById('plReasonModal'); const title = document.getElementById('plReasonTitle'); const sub = document.getElementById('plReasonSub'); const textarea = document.getElementById('plReasonText'); const t = allPostTasks.find(x => x.key === taskKey); if (!modal || !title || !sub || !textarea || !t) return; title.textContent = `Причина закрытия задачи`; sub.textContent = `${esc(t.group_name)} · ${esc(t.lesson_date)}`; textarea.value = currentReason || ''; plReasonPending = { taskKey, stepKey: null, closeTask: true }; modal.classList.add('open'); textarea.focus(); } document.getElementById('plSearch').addEventListener('input', () => { plPage = 1; renderPostLessonTasks(); }); document.getElementById('plStatus').addEventListener('change', () => { plPage = 1; renderPostLessonTasks(); }); document.getElementById('plDays').addEventListener('change', () => { plPage = 1; loadPostLessonTasks(); }); document.getElementById('plShowDismissed').addEventListener('change', () => { plPage = 1; renderPostLessonTasks(); }); const plPageSizeEl = document.getElementById('plPageSize'); if (plPageSizeEl) plPageSizeEl.addEventListener('change', () => { plPageSize = parseInt(plPageSizeEl.value, 10) || 20; plPage = 1; renderPostLessonTasks(); }); const plPager = document.getElementById('plPager'); if (plPager) { plPager.addEventListener('click', (e) => { const btn = e.target.closest('[data-page-nav]'); if (!btn) return; const nav = btn.dataset.pageNav; const total = filteredTasks().length; const totalPages = Math.max(1, Math.ceil(total / plPageSize)); if (nav === 'prev') plPage = Math.max(1, plPage - 1); else if (nav === 'next') plPage = Math.min(totalPages, plPage + 1); else plPage = parseInt(nav, 10) || 1; renderPostLessonTasks(); }); } function openPostTaskDetail(taskKey) { const t = allPostTasks.find(x => x.key === taskKey); if (!t) return; const modal = document.getElementById('plDetailModal'); const title = document.getElementById('plDetailTitle'); const body = document.getElementById('plDetailBody'); if (!modal || !title || !body) return; const steps = t.steps.map(s => ({ ...s, manual: !s.done && !!s.reason })); const completed = steps.filter(s => s.done).length; const allDone = completed === steps.length; title.textContent = `${t.group_name} · ${t.lesson_date}`; const statusBadge = allDone ? 'Выполнено' : (t.overdue ? 'Просрочено' : 'В работе'); const statusCls = allDone ? 'done' : (t.overdue ? 'overdue' : 'pending'); let html = ''; html += `
`; html += `${completed}/${steps.length}`; html += `${esc(t.lesson_time)}${t.tutor_name ? ' · ' + esc(t.tutor_name) : ''}`; html += `${esc(statusBadge)}`; html += `
`; html += `
`; for (const s of steps) { html += `
`; html += `
`; html += `${s.done ? '✓' : '○'} ${esc(s.label)}`; html += `Открыть`; html += `
`; if (s.manual) { html += `
Отмечено вручную${s.reason ? ' — причина: ' + esc(s.reason) : ''}
`; } if (Array.isArray(s.basis) && s.basis.length) { html += `
Основание:
`; html += ``; } else { html += `
Нет данных об основании
`; } html += `
`; } html += `
`; body.innerHTML = html; modal.classList.add('open'); } function closePostTaskDetail() { const modal = document.getElementById('plDetailModal'); if (modal) modal.classList.remove('open'); } const plList = document.getElementById('plList'); if (plList) { plList.addEventListener('click', async (e) => { const closeBtn = e.target.closest('[data-close-task]'); if (closeBtn) { e.stopPropagation(); const t = allPostTasks.find(x => x.key === closeBtn.dataset.closeTask); if (t && !t.all_done) { openCloseReasonModal(closeBtn.dataset.closeTask); return; } try { await closeTaskWithReason(closeBtn.dataset.closeTask, ''); } catch (err) { showToast(err.message); } return; } const restoreBtn = e.target.closest('[data-restore-task]'); if (restoreBtn) { e.stopPropagation(); try { await reopenTask(restoreBtn.dataset.restoreTask); } catch (err) { showToast(err.message); } return; } const detailBtn = e.target.closest('[data-detail-task]'); if (detailBtn) { e.stopPropagation(); openPostTaskDetail(detailBtn.dataset.detailTask); return; } const step = e.target.closest('[data-step-key]'); if (step) { e.stopPropagation(); const t = allPostTasks.find(x => x.key === step.dataset.taskKey); const s = t && t.steps.find(x => x.key === step.dataset.stepKey); if (s && s.done) { try { await saveStepState(step.dataset.taskKey, step.dataset.stepKey, false, ''); } catch (err) { showToast(err.message); } return; } openReasonModal(step.dataset.taskKey, step.dataset.stepKey, ''); return; } const photo = e.target.closest('.post-task-photo[data-img]'); if (photo) { e.stopPropagation(); showImg(photo.dataset.img); return; } const card = e.target.closest('.post-task[data-task-link]'); if (card && card.dataset.taskLink) { window.location.href = card.dataset.taskLink; } }); } const plDetailClose = document.getElementById('plDetailClose'); if (plDetailClose) plDetailClose.addEventListener('click', closePostTaskDetail); const plDetailModal = document.getElementById('plDetailModal'); if (plDetailModal) { plDetailModal.addEventListener('click', (e) => { if (e.target === plDetailModal) closePostTaskDetail(); }); } document.addEventListener('keydown', (e) => { if (e.key === 'Escape') { closePostTaskDetail(); closeReasonModal(); } }); const plReasonSave = document.getElementById('plReasonSave'); const plReasonCancel = document.getElementById('plReasonCancel'); const plReasonModal = document.getElementById('plReasonModal'); if (plReasonSave) plReasonSave.addEventListener('click', async () => { if (!plReasonPending) return; const textarea = document.getElementById('plReasonText'); const reason = (textarea && textarea.value || '').trim(); if (!reason) return; try { if (plReasonPending.closeTask) { await closeTaskWithReason(plReasonPending.taskKey, reason); } else { await saveStepState(plReasonPending.taskKey, plReasonPending.stepKey, true, reason); } } catch (err) { showToast(err.message || 'Не удалось сохранить'); return; } closeReasonModal(); }); if (plReasonCancel) plReasonCancel.addEventListener('click', closeReasonModal); if (plReasonModal) plReasonModal.addEventListener('click', (e) => { if (e.target === plReasonModal) closeReasonModal(); }); (async () => { if (await checkAuth()) { buildSidebar(document.body.dataset.page); loadPostLessonTasks(); } })();